text:
package com.snowplowanalytics.iglu.schemaddl.jsonschema
package properties

import java.net.URI

/**
  * Marker trait for properties specific *ONLY* for strings
  */
private[iglu] sealed trait StringProperty

object StringProperty {

  /**
   * Class representing `minLength` keyword
   *
   * @see http://json-schema.org/latest/json-schema-validation.html#anchor29
   */
  case class MinLength(value: BigInt) extends JsonSchemaProperty with StringProperty {
    val keyword: Keyword = Keyword.MinLength
  }

  /**
   * Class representing `maxLength` keyword
   *
   * @see http://json-schema.org/latest/json-schema-validation.html#anchor26
   */
  case class MaxLength(value: BigInt) extends JsonSchemaProperty with StringProperty {
    val keyword: Keyword = Keyword.MaxLength
  }

  /**
   * ADT representing all possible values for `format` keyword
   *
   * @see http://json-schema.org/latest/json-schema-validation.html#anchor104
   */
  sealed trait Format extends JsonSchemaProperty with StringProperty {
    val keyword: Keyword = Keyword.Format
    def asString: String
  }
  object Format {
    case object UriFormat extends Format { val asString = "uri" }
    case object Ipv4Format extends Format { val asString = "ipv4" }
    case object Ipv6Format extends Format { val asString = "ipv6" }
    case object EmailFormat extends Format { val asString = "email" }
    case object DateTimeFormat extends Format { val asString = "date-time" }
    case object DateFormat extends Format { val asString = "date" }
    case object HostNameFormat extends Format { val asString = "hostname" }
    case object UuidFormat extends Format { val asString = "uuid" }

    /**
      * Implementations MAY add custom format attributes
      */
    case class CustomFormat(value: String) extends Format with StringProperty  { val asString = value }

    def fromString(string: String): Format = string match {
      case "uri" => UriFormat
      case "ipv4" => Ipv4Format
      case "ivp6" => Ipv6Format
      case "email" => EmailFormat
      case "date-time" => DateTimeFormat
      case "date" => DateFormat
      case "hostname" => HostNameFormat
      case "uuid" => UuidFormat
      case custom => CustomFormat(custom)
    }
  }

  /**
   * Class representing `pattern` keyword
   *
   * @see http://json-schema.org/latest/json-schema-validation.html#anchor33
   */
  case class Pattern(value: String) extends JsonSchemaProperty with StringProperty {
    val keyword: Keyword = Keyword.Pattern
  }

  /**
    * Class representing `$$schema` keyword
    *
    * @see https://json-schema.org/understanding-json-schema/reference/schema.html
    */
  case class SchemaUri(value: URI) extends JsonSchemaProperty with StringProperty {
    val keyword: Keyword = Keyword.SchemaUri
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

<title>  Opening Day - The Web Standards Project</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="The Web Standards Project is a grassroots coalition fighting for standards which ensure simple, affordable access to web technologies for all." />
<meta name="MSSmartTagsPreventParsing" content="true" />

<link rel="stylesheet" type="text/css" media="screen, projection" href="/wp/wp-content/themes/web-standards-project/styles.css" />
<link rel="stylesheet" type="text/css" media="print" href="/wp/wp-content/themes/web-standards-project/print.css" />
<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="/feed/index.html" />
<link rel="alternate" type="text/xml" title="RSS .92" href="/feed/rss/index.html" />
<link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="/feed/atom/index.html" />
<link rel="pingback" href="/wp/xmlrpc.php" />
<link rel="Shortcut Icon" type="image/ico" href="/files/theme/wasp.ico" />
<link rel="home" title="Web Standards Project Home" href="/index.html" />
	<link rel='archives' title='March 2013' href='/2013/03/index.html' />
	<link rel='archives' title='February 2012' href='/2012/02/index.html' />
	<link rel='archives' title='December 2011' href='/2011/12/index.html' />
	<link rel='archives' title='November 2011' href='/2011/11/index.html' />
	<link rel='archives' title='March 2011' href='/2011/03/index.html' />
	<link rel='archives' title='February 2011' href='/2011/02/index.html' />
	<link rel='archives' title='January 2011' href='/2011/01/index.html' />
	<link rel='archives' title='August 2010' href='/2010/08/index.html' />
	<link rel='archives' title='June 2010' href='/2010/06/index.html' />
	<link rel='archives' title='March 2010' href='/2010/03/index.html' />
	<link rel='archives' title='February 2010' href='/2010/02/index.html' />
	<link rel='archives' title='January 2010' href='/2010/01/index.html' />
	<link rel='archives' title='November 2009' href='/2009/11/index.html' />
	<link rel='archives' title='June 2009' href='/2009/06/index.html' />
	<link rel='archives' title='May 2009' href='/2009/05/index.html' />
	<link rel='archives' title='April 2009' href='/2009/04/index.html' />
	<link rel='archives' title='March 2009' href='/2009/03/index.html' />
	<link rel='archives' title='February 2009' href='/2009/02/index.html' />
	<link rel='archives' title='January 2009' href='/2009/01/index.html' />
	<link rel='archives' title='December 2008' href='/2008/12/index.html' />
	<link rel='archives' title='November 2008' href='/2008/11/index.html' />
	<link rel='archives' title='October 2008' href='/2008/10/index.html' />
	<link rel='archives' title='September 2008' href='/2008/09/index.html' />
	<link rel='archives' title='August 2008' href='/2008/08/index.html' />
	<link rel='archives' title='July 2008' href='/2008/07/index.html' />
	<link rel='archives' title='June 2008' href='/2008/06/index.html' />
	<link rel='archives' title='May 2008' href='/2008/05/index.html' />
	<link rel='archives' title='April 2008' href='/2008/04/index.html' />
	<link rel='archives' title='March 2008' href='/2008/03/index.html' />
	<link rel='archives' title='February 2008' href='/2008/02/index.html' />
	<link rel='archives' title='January 2008' href='/2008/01/index.html' />
	<link rel='archives' title='December 2007' href='/2007/12/index.html' />
	<link rel='archives' title='November 2007' href='/2007/11/index.html' />
	<link rel='archives' title='October 2007' href='/2007/10/index.html' />
	<link rel='archives' title='September 2007' href='/2007/09/index.html' />
	<link rel='archives' title='August 2007' href='/2007/08/index.html' />
	<link rel='archives' title='June 2007' href='/2007/06/index.html' />
	<link rel='archives' title='May 2007' href='/2007/05/index.html' />
	<link rel='archives' title='April 2007' href='/2007/04/index.html' />
	<link rel='archives' title='March 2007' href='/2007/03/index.html' />
	<link rel='archives' title='February 2007' href='/2007/02/index.html' />
	<link rel='archives' title='January 2007' href='/2007/01/index.html' />
	<link rel='archives' title='December 2006' href='/2006/12/index.html' />
	<link rel='archives' title='November 2006' href='/2006/11/index.html' />
	<link rel='archives' title='October 2006' href='/2006/10/index.html' />
	<link rel='archives' title='September 2006' href='/2006/09/index.html' />
	<link rel='archives' title='August 2006' href='/2006/08/index.html' />
	<link rel='archives' title='July 2006' href='/2006/07/index.html' />
	<link rel='archives' title='June 2006' href='/2006/06/index.html' />
	<link rel='archives' title='May 2006' href='/2006/05/index.html' />
	<link rel='archives' title='April 2006' href='/2006/04/index.html' />
	<link rel='archives' title='March 2006' href='/2006/03/index.html' />
	<link rel='archives' title='February 2006' href='/2006/02/index.html' />
	<link rel='archives' title='January 2006' href='/2006/01/index.html' />
	<link rel='archives' title='December 2005' href='/2005/12/index.html' />
	<link rel='archives' title='November 2005' href='/2005/11/index.html' />
	<link rel='archives' title='October 2005' href='/2005/10/index.html' />
	<link rel='archives' title='September 2005' href='/2005/09/index.html' />
	<link rel='archives' title='August 2005' href='/2005/08/index.html' />
	<link rel='archives' title='July 2005' href='/2005/07/index.html' />
	<link rel='archives' title='June 2005' href='/2005/06/index.html' />
	<link rel='archives' title='May 2005' href='/2005/05/index.html' />
	<link rel='archives' title='April 2005' href='/2005/04/index.html' />
	<link rel='archives' title='March 2005' href='/2005/03/index.html' />
	<link rel='archives' title='February 2005' href='/2005/02/index.html' />
	<link rel='archives' title='January 2005' href='/2005/01/index.html' />
	<link rel='archives' title='December 2004' href='/2004/12/index.html' />
	<link rel='archives' title='November 2004' href='/2004/11/index.html' />
	<link rel='archives' title='October 2004' href='/2004/10/index.html' />
	<link rel='archives' title='September 2004' href='/2004/09/index.html' />
	<link rel='archives' title='August 2004' href='/2004/08/index.html' />
	<link rel='archives' title='July 2004' href='/2004/07/index.html' />
	<link rel='archives' title='June 2004' href='/2004/06/index.html' />
	<link rel='archives' title='May 2004' href='/2004/05/index.html' />
	<link rel='archives' title='April 2004' href='/2004/04/index.html' />
	<link rel='archives' title='March 2004' href='/2004/03/index.html' />
	<link rel='archives' title='February 2004' href='/2004/02/index.html' />
	<link rel='archives' title='January 2004' href='/2004/01/index.html' />
	<link rel='archives' title='December 2003' href='/2003/12/index.html' />
	<link rel='archives' title='November 2003' href='/2003/11/index.html' />
	<link rel='archives' title='October 2003' href='/2003/10/index.html' />
	<link rel='archives' title='September 2003' href='/2003/09/index.html' />
	<link rel='archives' title='August 2003' href='/2003/08/index.html' />
	<link rel='archives' title='July 2003' href='/2003/07/index.html' />
	<link rel='archives' title='June 2003' href='/2003/06/index.html' />
	<link rel='archives' title='May 2003' href='/2003/05/index.html' />
	<link rel='archives' title='April 2003' href='/2003/04/index.html' />
	<link rel='archives' title='March 2003' href='/2003/03/index.html' />
	<link rel='archives' title='February 2003' href='/2003/02/index.html' />
	<link rel='archives' title='January 2003' href='/2003/01/index.html' />
	<link rel='archives' title='December 2002' href='../../index.html' />
	<link rel='archives' title='November 2002' href='../../../11/index.html' />
	<link rel='archives' title='October 2002' href='../../../10/index.html' />
	<link rel='archives' title='September 2002' href='../../../09/index.html' />
	<link rel='archives' title='August 2002' href='../../../08/index.html' />
	<link rel='archives' title='July 2002' href='../../../07/index.html' />
	<link rel='archives' title='June 2002' href='../../../06/index.html' />
	<link rel='archives' title='April 2002' href='../../../04/index.html' />
	<link rel='archives' title='March 2002' href='../../../03/index.html' />
	<link rel='archives' title='December 2001' href='/2001/12/index.html' />
	<link rel='archives' title='September 2001' href='/2001/09/index.html' />
	<link rel='archives' title='November 2000' href='/2000/11/index.html' />
	<link rel='archives' title='July 2000' href='/2000/07/index.html' />
	<link rel='archives' title='April 2000' href='/2000/04/index.html' />
	<link rel='archives' title='March 1999' href='/1999/03/index.html' />
	<link rel='archives' title='October 1998' href='/1998/10/index.html' />
	<link rel='archives' title='August 1998' href='/1998/08/index.html' />
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="/wp/xmlrpc0db0.php?rsd" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="/wp/wp-includes/wlwmanifest.xml" />
<link rel='prev' title='Getting the Last Word' href='../../14/getting-the-last-word/index.html' />
<link rel='next' title='Is there a draft in here?' href='../../19/is-there-a-draft-in-here/index.html' />
<meta name="generator" content="WordPress 3.3.1" />
<link rel='canonical' href='index.html' />
<link rel='shortlink' href='../../../../index460d.html?p=108' />

Working together for standards  The Web Standards Project

		Skip to content

				<form id="fm-search" method="get" action="http://www.webstandards.org/index.php">
			<fieldset>
				<legend>Search</legend>
				Search WaSP
				<input id="s" name="s" class="search" value="" />
				<input type="submit" class="submit" name="submit" value="Go!" />
			</fieldset>
		</form>

Home

About

Learn

Action

Buzz

Press

Opening Day

By Porter Glendinning | December 17th, 2002 | Filed in Browsers

								Skip to comment form

Opera Software’s “Open the Web” project asks Opera users to  contact the owners of sites that fail in their browser or deny them entrance. “Let them know you would like to see the site work with all browsers, including Opera.”

If you’re developing a site and are considering refusing access to certain browsers, or if you have a site that’s already doing it, it’s probably time to go back to the drawing board.

			Return to top

Post a Reply

Comments are closed.

Back to Top

All of the entries posted in WaSP Buzz express the opinions of their individual authors. They do not necessarily reflect the plans or positions of the Web Standards Project as a group.

This site is valid XHTML 1.0 Strict, CSS | Get Buzz via RSS or Atom | Colophon | Legal

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package com.sivalabs.demo;

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

import org.springframework.context.annotation.Conditional;

/**
 * @author Siva
 *
 */
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Conditional(DatabaseTypeCondition.class)
public @interface DatabaseType
{
	String value();
}


text:
#include <vector>
#include <map>
#include <algorithm>
#include <sstream>
#include "config.h"
#include "Job.h"
#include "SimEngineTimer.h"
#include "TimeValues.h"
#include <list>
#include "ClaimRelease.h"
#include "Entity.h"
#include "Jobs.h"

#include "Admin.h"

using namespace std;

namespace EnergySim
{
	class Resource;
	class Process;
	class ConcreteProcess;
	class IJobAssigner;
	class ResourceHandler
	{
	public:
		ResourceHandler(SimModel* theModel);
		ResourceHandler(SimModel* theModel,IJobAssigner* assigner);
		static ResourceHandler* gResourceHandler(){ return itsResourceHandler; };
		IJob* getResources(long ProcessID, long RouteFollowerID);
		bool assignJob();
		friend class IJobAssigner;
		Resource* getResource(string name) { return itsResources.front(); };
		void wait(WaitForResourcesJob* aJob);
		void done(long theRouteFollowerID, long theProcessID);
	protected:
		static ResourceHandler* itsResourceHandler;
		list<Resource*> itsResources;
		list<pair<WaitForResourcesJob*, Process*>> itsResReq;

		list<WaitForResourcesJob*> waiting;
		list<pair<pair<long,long>,ConcreteProcess*>> onGoing; // LotID, ProcessID, Reslist
		SimModel* model;
		IJobAssigner* itsAssigner;
	};
	class IJobAssigner
	{
	public:
		IJobAssigner(ResourceHandler* theRH){ itsRH = theRH; }
		virtual bool assignJob()= 0;
	protected:
		list<Resource*> resources() { return itsRH->itsResources; }
		ResourceHandler* itsRH;
		list<pair<WaitForResourcesJob*, Process*>> resReg() { return itsRH->itsResReq; }
		void assignAJob(WaitForResourcesJob* aWFR,	list<Resource*>* aRL );
	};
	class TestJobAssigner : public IJobAssigner
	{
	public:
		TestJobAssigner(ResourceHandler* theRH) : IJobAssigner(theRH){}
		virtual bool assignJob();
		bool IsOdd(Resource* r) { return true; }
	};
	class IEntity;

	using namespace std::placeholders;
	class  Resource : public IEntity, protected ClaimReleaseResourceHandler<long>
	{
	public:
		Resource(IClock* theClock, string theName) : itsCapacity(0, theClock), itsUsedCapacity(0, theClock)
		{
			itsName = theName;
			MyRealSetter* aRS = new MyRealSetter(std::bind(&Resource::setDoubleCap, this, _1));
			SetterHandler::getSetterHandler()->store(itsName, aRS);
			IEvent::publishEvent(ET_RESOURCE_USES, vector<string>(2) = { (name()), to_string(0) });
		}
		int capacity() { return itsCapacity.getValue(); }
		void setDoubleCap(double d){ setCapacity(d); }
		void setCapacity(int cap)
		{
			itsCapacity = itsCapacity + cap - itsCapacity.getValue();
			IEvent::publishEvent(ET_RESOURCE_CAPACITY, vector<string>(2) = { (name()), to_string(cap) });
		}
		int free(){ return itsCapacity.getValue() - itsUsedCapacity.getValue(); }

		void free(long value)
		{
			vector<long> v1;
			v1.push_back(value);
			IEvent::publishEvent(ET_RESOURCE_RELEASE, eID(), v1);
			itsUsedCapacity = itsUsedCapacity - value;
			vector<long> v2;
			v2.push_back( itsUsedCapacity.getValue() );
			IEvent::publishEvent(ET_RESOURCE_USES, eID(), v2);
			IEvent::publishEvent(ET_RESOURCE_USES, vector<string>(2) = { (name()), std::to_string(itsUsedCapacity.getValue()) });
		}

		void get(IClaimer<long>* theClaimer, long neededCapacity)
		{
			vector<long> v1;
			v1.push_back(neededCapacity);
			IEvent::publishEvent(ET_RESOURCE_CLAIM, eID(), v1);
			itsUsedCapacity = itsUsedCapacity + neededCapacity;
			itsClaimers.push_back(pair<IClaimer<long>*, int>(theClaimer, neededCapacity));
		}
		void getCapacity(long neededCapacity)
		{
			vector<long> v1;
			v1.push_back(neededCapacity);
			IEvent::publishEvent(ET_RESOURCE_CLAIM, eID(), v1);
			itsUsedCapacity = itsUsedCapacity + neededCapacity;
			vector<long> v2;
			v2.push_back(itsUsedCapacity.getValue());
			IEvent::publishEvent(ET_RESOURCE_USES, eID(), v2);
			IEvent::publishEvent(ET_RESOURCE_USES, vector<string>(2) = { (name()), std::to_string(itsUsedCapacity.getValue()) });
		}
		string name(){ return itsName; };
		void free(IClaimer<long>* theClaimer)
		{
			for (pair<IClaimer<long>*, int> aP : itsClaimers)
			{
				if (aP.first == theClaimer)
				{
					itsUsedCapacity = itsUsedCapacity - aP.second;
					IEvent::publishEvent(ET_RESOURCE_USES, vector<string>(2) = { (name()), std::to_string(itsUsedCapacity.getValue()) });
					itsClaimers.remove(aP);
					break;
				}
			}
		}
		double getAvgUse() { return itsUsedCapacity.getAvg(); }
		double getAvg() { return itsCapacity.getAvg(); }
		long setup() { return itsSetup; }
		long setup(int theSetup){ return itsSetup = theSetup; }
		double setupTime(long theSetup)
		{
			if (theSetup == itsSetup)
				return 0;
			return 10;
		}
		ResourceState state() { return itsState; }
		ResourceState state(ResourceState theState) { return itsState = theState; }
	private:
		string itsName;
		ResourceState itsState;
		long itsSetup;
		TimeValue<long> itsCapacity, itsUsedCapacity;
		list<pair<IClaimer<long>*, int>> itsClaimers;
	};
	class ConcreteProcess
	{
	public:
		long prio;
		long id;
		list<pair<long, Resource*>>* need = new list<pair<long, Resource*>>();
		ConcreteProcess(list<pair<long, Resource*>>* theNeed, long theID){ need = theNeed; id = theID; }
	private:
		static long startID;
	};
	class Process : public IEntity
	{
	public:
		Process* copy()
		{
			Process* aP = new Process();
			aP->processID = processID;
			for each (auto var in itsAlternates)
			{
				aP->itsAlternates.push_back(var);
			}
			return aP;
		}
		long processID;
		list<ConcreteProcess*> itsAlternates = list<ConcreteProcess*>();
	};
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    style="@style/skittleLayoutStyle">

  <android.support.design.widget.FloatingActionButton
      xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      android:id="@+id/skittle"
      android:layout_margin="8dp"
      android:layout_gravity="end"
      android:layout_width="wrap_content"
      app:fabSize="mini"
      android:layout_height="wrap_content"
      android:src="@drawable/ic_add_white_18dp"
  />
</FrameLayout>


text:
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM;
using TTC2017.SmartGrids.CIM.IEC61968.Common;
using TTC2017.SmartGrids.CIM.IEC61970.Contingency;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Generation.Production;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.EnergyScheduling;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.Financial;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport;
using TTC2017.SmartGrids.CIM.IEC61970.LoadModel;
using TTC2017.SmartGrids.CIM.IEC61970.Meas;
using TTC2017.SmartGrids.CIM.IEC61970.Wires;

namespace TTC2017.SmartGrids.CIM.IEC61970.Informative.MarketOperations
{

    /// <summary>
    /// The public interface for SecurityConstraintsClearing
    /// </summary>
    [DefaultImplementationTypeAttribute(typeof(SecurityConstraintsClearing))]
    [XmlDefaultImplementationTypeAttribute(typeof(SecurityConstraintsClearing))]
    public interface ISecurityConstraintsClearing : IModelElement, IMarketFactors
    {

        /// <summary>
        /// The mwLimit property
        /// </summary>
        float MwLimit
        {
            get;
            set;
        }

        /// <summary>
        /// The mwFlow property
        /// </summary>
        float MwFlow
        {
            get;
            set;
        }

        /// <summary>
        /// The shadowPrice property
        /// </summary>
        float ShadowPrice
        {
            get;
            set;
        }

        /// <summary>
        /// Gets fired before the MwLimit property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> MwLimitChanging;

        /// <summary>
        /// Gets fired when the MwLimit property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> MwLimitChanged;

        /// <summary>
        /// Gets fired before the MwFlow property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> MwFlowChanging;

        /// <summary>
        /// Gets fired when the MwFlow property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> MwFlowChanged;

        /// <summary>
        /// Gets fired before the ShadowPrice property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> ShadowPriceChanging;

        /// <summary>
        /// Gets fired when the ShadowPrice property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> ShadowPriceChanged;
    }
}


text:
export class IrCode {

  public type: Number;
  public value: Number;
  public bits: Number;

}


text:
namespace CvSystem.Web.ViewModels.Edit
{
    using System.ComponentModel.DataAnnotations;

    using CvSystem.Common.ErrorConstants;
    using CvSystem.Common.ModelsConstants;
    using CvSystem.Data.Models;
    using CvSystem.Web.Infrastructure.Mapping;

    public class CourseEditModel : IMapFrom<Course>, IMapTo<Course>
    {
        [Required]
        [StringLength(
            CourseConstants.CourseNameMaxLength,
            ErrorMessage = ModelValidationError.ValidationErrorForRange,
            MinimumLength = CourseConstants.CourseNameMinLength)]
        public string CourseName { get; set; }

        public bool IsDeleted { get; set; }
    }
}


text:
// @flow
import I18n from 'react-native-i18n';

// Enable fallbacks if you want `en-US` and `en-GB` to fallback to `en`
I18n.fallbacks = true;

// English language is the main language for fall back:
I18n.translations = {
  en: require('./english.json'),
};

const languageCode = I18n.locale.substr(0, 2);

// All other translations for the app goes to the respective language file:
switch (languageCode) {
  case 'sl':
    I18n.translations.sl = require('./sl.json');
    break;
  /* case 'zu':
    I18n.translations.zu = require('./zu.json');
    break; */
  default:
    I18n.translations.en = require('./english.json');
}


text:
import Operator from "../Operator";
import AddonIndicatorClient from "../../client/AddonIndicatorClient";
import AddonEnabledRepository from "../../repositories/AddonEnabledRepository";
import ConsoleFramePresenter from "../../presenters/ConsoleFramePresenter";

export default class EnableAddonOperator implements Operator {
  constructor(
    private readonly indicator: AddonIndicatorClient,
    private readonly repository: AddonEnabledRepository,
    private readonly consoleFramePresenter: ConsoleFramePresenter
  ) {}

  async run(): Promise<void> {
    this.repository.set(true);
    this.consoleFramePresenter.attach();
    await this.indicator.setEnabled(true);
  }
}


text:
import paddle.fluid as fluid
from paddle.fluid.param_attr import ParamAttr
import numpy as np
from tqdm import tqdm
import math
from utils import fluid_flatten

class DuelingDQNModel(object):
    def __init__(self, state_dim, action_dim, gamma, hist_len, use_cuda=False):
        self.img_height = state_dim[0]
        self.img_width = state_dim[1]
        self.action_dim = action_dim
        self.gamma = gamma
        self.exploration = 1.1
        self.update_target_steps = 10000 // 4
        self.hist_len = hist_len
        self.use_cuda = use_cuda

        self.global_step = 0
        self._build_net()

    def _get_inputs(self):
        return fluid.layers.data(
                   name='state',
                   shape=[self.hist_len, self.img_height, self.img_width],
                   dtype='float32'), \
               fluid.layers.data(
                   name='action', shape=[1], dtype='int32'), \
               fluid.layers.data(
                   name='reward', shape=[], dtype='float32'), \
               fluid.layers.data(
                   name='next_s',
                   shape=[self.hist_len, self.img_height, self.img_width],
                   dtype='float32'), \
               fluid.layers.data(
                   name='isOver', shape=[], dtype='bool')

    def _build_net(self):
        state, action, reward, next_s, isOver = self._get_inputs()
        self.pred_value = self.get_DQN_prediction(state)
        self.predict_program = fluid.default_main_program().clone()

        reward = fluid.layers.clip(reward, min=-1.0, max=1.0)

        action_onehot = fluid.layers.one_hot(action, self.action_dim)
        action_onehot = fluid.layers.cast(action_onehot, dtype='float32')

        pred_action_value = fluid.layers.reduce_sum(
            fluid.layers.elementwise_mul(action_onehot, self.pred_value), dim=1)

        targetQ_predict_value = self.get_DQN_prediction(next_s, target=True)
        best_v = fluid.layers.reduce_max(targetQ_predict_value, dim=1)
        best_v.stop_gradient = True

        target = reward + (1.0 - fluid.layers.cast(
            isOver, dtype='float32')) * self.gamma * best_v
        cost = fluid.layers.square_error_cost(pred_action_value, target)
        cost = fluid.layers.reduce_mean(cost)

        self._sync_program = self._build_sync_target_network()

        optimizer = fluid.optimizer.Adam(1e-3 * 0.5, epsilon=1e-3)
        optimizer.minimize(cost)

        # define program
        self.train_program = fluid.default_main_program()

        # fluid exe
        place = fluid.CUDAPlace(0) if self.use_cuda else fluid.CPUPlace()
        self.exe = fluid.Executor(place)
        self.exe.run(fluid.default_startup_program())

    def get_DQN_prediction(self, image, target=False):
        image = image / 255.0

        variable_field = 'target' if target else 'policy'

        conv1 = fluid.layers.conv2d(
            input=image,
            num_filters=32,
            filter_size=[5, 5],
            stride=[1, 1],
            padding=[2, 2],
            act='relu',
            param_attr=ParamAttr(name='{}_conv1'.format(variable_field)),
            bias_attr=ParamAttr(name='{}_conv1_b'.format(variable_field)))
        max_pool1 = fluid.layers.pool2d(
            input=conv1, pool_size=[2, 2], pool_stride=[2, 2], pool_type='max')

        conv2 = fluid.layers.conv2d(
            input=max_pool1,
            num_filters=32,
            filter_size=[5, 5],
            stride=[1, 1],
            padding=[2, 2],
            act='relu',
            param_attr=ParamAttr(name='{}_conv2'.format(variable_field)),
            bias_attr=ParamAttr(name='{}_conv2_b'.format(variable_field)))
        max_pool2 = fluid.layers.pool2d(
            input=conv2, pool_size=[2, 2], pool_stride=[2, 2], pool_type='max')

        conv3 = fluid.layers.conv2d(
            input=max_pool2,
            num_filters=64,
            filter_size=[4, 4],
            stride=[1, 1],
            padding=[1, 1],
            act='relu',
            param_attr=ParamAttr(name='{}_conv3'.format(variable_field)),
            bias_attr=ParamAttr(name='{}_conv3_b'.format(variable_field)))
        max_pool3 = fluid.layers.pool2d(
            input=conv3, pool_size=[2, 2], pool_stride=[2, 2], pool_type='max')

        conv4 = fluid.layers.conv2d(
            input=max_pool3,
            num_filters=64,
            filter_size=[3, 3],
            stride=[1, 1],
            padding=[1, 1],
            act='relu',
            param_attr=ParamAttr(name='{}_conv4'.format(variable_field)),
            bias_attr=ParamAttr(name='{}_conv4_b'.format(variable_field)))

        flatten = fluid_flatten(conv4)

        value = fluid.layers.fc(
            input=flatten,
            size=1,
            param_attr=ParamAttr(name='{}_value_fc'.format(variable_field)),
            bias_attr=ParamAttr(name='{}_value_fc_b'.format(variable_field)))

        advantage = fluid.layers.fc(
            input=flatten,
            size=self.action_dim,
            param_attr=ParamAttr(name='{}_advantage_fc'.format(variable_field)),
            bias_attr=ParamAttr(
                name='{}_advantage_fc_b'.format(variable_field)))

        Q = advantage + (value - fluid.layers.reduce_mean(
            advantage, dim=1, keep_dim=True))
        return Q

    def _build_sync_target_network(self):
        vars = list(fluid.default_main_program().list_vars())
        policy_vars = filter(
            lambda x: 'GRAD' not in x.name and 'policy' in x.name, vars)
        target_vars = filter(
            lambda x: 'GRAD' not in x.name and 'target' in x.name, vars)
        policy_vars.sort(key=lambda x: x.name)
        target_vars.sort(key=lambda x: x.name)

        sync_program = fluid.default_main_program().clone()
        with fluid.program_guard(sync_program):
            sync_ops = []
            for i, var in enumerate(policy_vars):
                sync_op = fluid.layers.assign(policy_vars[i], target_vars[i])
                sync_ops.append(sync_op)
        sync_program = sync_program.prune(sync_ops)
        return sync_program

    def act(self, state, train_or_test):
        sample = np.random.random()
        if train_or_test == 'train' and sample < self.exploration:
            act = np.random.randint(self.action_dim)
        else:
            if np.random.random() < 0.01:
                act = np.random.randint(self.action_dim)
            else:
                state = np.expand_dims(state, axis=0)
                pred_Q = self.exe.run(self.predict_program,
                                      feed={'state': state.astype('float32')},
                                      fetch_list=[self.pred_value])[0]
                pred_Q = np.squeeze(pred_Q, axis=0)
                act = np.argmax(pred_Q)
        if train_or_test == 'train':
            self.exploration = max(0.1, self.exploration - 1e-6)
        return act

    def train(self, state, action, reward, next_state, isOver):
        if self.global_step % self.update_target_steps == 0:
            self.sync_target_network()
        self.global_step += 1

        action = np.expand_dims(action, -1)
        self.exe.run(self.train_program, \
                  feed={'state': state.astype('float32'), \
                        'action': action.astype('int32'), \
                        'reward': reward, \
                        'next_s': next_state.astype('float32'), \
                        'isOver': isOver})

    def sync_target_network(self):
        self.exe.run(self._sync_program)


text:
info_plist="${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/ReplicationSettings.plist"

echo $info_plist

if [ "$TEST_COUCH_USERNAME" ]; then
	echo "Setting couch username"
    /usr/libexec/PlistBuddy -c "Set :TEST_COUCH_USERNAME '${TEST_COUCH_USERNAME}'" "${info_plist}"
fi

if [ "$TEST_COUCH_PASSWORD" ]; then
		echo "Setting couch password"
/usr/libexec/PlistBuddy -c "Set :TEST_COUCH_PASSWORD '${TEST_COUCH_PASSWORD}'" "${info_plist}"
fi

if [ "$TEST_COUCH_HOST" ]; then
		echo "Setting couch host"
/usr/libexec/PlistBuddy -c "Set :TEST_COUCH_HOST '${TEST_COUCH_HOST}'" "${info_plist}"
fi

if [ "$TEST_COUCH_PORT" ]; then
		echo "Setting couch port"
    /usr/libexec/PlistBuddy -c "Set :TEST_COUCH_PORT '${TEST_COUCH_PORT}'" "${info_plist}";
fi

if [ "$TEST_COUCH_HTTP" ]; then
		echo "Setting couch http"
    /usr/libexec/PlistBuddy -c "Set :TEST_COUCH_HTTP '${TEST_COUCH_HTTP}'" "${info_plist}";
fi


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

using Piranha.Data;

namespace Piranha.Models
{
	/// <summary>
	/// Active record for a page region.
	/// </summary>
	[PrimaryKey(Column = "property_id,property_draft")]
	[Serializable]
	public class Property : PiranhaRecord<Property>
	{
		#region Fields
		/// <summary>
		/// Gets/sets the id.
		/// </summary>
		[Column(Name = "property_id")]
		public override Guid Id { get; set; }

		/// <summary>
		/// Gets/sets whether this is a draft or not.
		/// </summary>
		[Column(Name = "property_draft")]
		public bool IsDraft { get; set; }

		/// <summary>
		/// Gets/sets the parent id.
		/// </summary>
		[Column(Name = "property_parent_id")]
		public Guid ParentId { get; set; }

		/// <summary>
		/// Gets/sets the name.
		/// </summary>
		[Column(Name = "property_name")]
		public string Name { get; set; }

		/// <summary>
		/// Gets/sets the body content.
		/// </summary>
		[Column(Name = "property_value")]
		public string Value { get; set; }

		/// <summary>
		/// Gets/sets the created date.
		/// </summary>
		[Column(Name = "property_created")]
		public override DateTime Created { get; set; }

		/// <summary>
		/// Gets/sets the updated date.
		/// </summary>
		[Column(Name = "property_updated")]
		public override DateTime Updated { get; set; }

		/// <summary>
		/// Gets/sets the user id that created the record.
		/// </summary>
		[Column(Name = "property_created_by")]
		public override Guid CreatedBy { get; set; }

		/// <summary>
		/// Gets/sets the user id that created the record.
		/// </summary>
		[Column(Name = "property_updated_by")]
		public override Guid UpdatedBy { get; set; }
		#endregion

		/// <summary>
		/// Gets all properties associated with the given parent id of the given state.
		/// </summary>
		/// <param name="id">The parent id</param>
		/// <param name="draft">Whether to get the draft version or not</param>
		/// <returns>The properties</returns>
		public static List<Property> GetByParentId(Guid id, bool draft = false) {
			return Get("property_parent_id = @0 AND property_draft = @1", id, draft);
		}

		/// <summary>
		/// Gets all properties associated with the given parent id regardless of state.
		/// </summary>
		/// <param name="id">The parent id</param>
		/// <returns>The properties</returns>
		internal static List<Property> GetAllByParentId(Guid id) {
			return Get("property_parent_id = @0", id);
		}

		/// <summary>
		/// Gets the name & value for all properties associated with the given parent
		/// id of the given state.
		/// </summary>
		/// <param name="id">The parent id</param>
		/// <param name="draft">Whether to get the draft version or not</param>
		/// <returns>The properties</returns>
		public static List<Property> GetContentByParentId(Guid id, bool draft = false) {
			return GetFields("property_name, property_value", "property_parent_id = @0 AND property_draft = @1", id, draft);
		}
	}
}


text:
fast-oopsi
==========

a repository containing everything relevant to our fast non-negative deconvolution work.

note that the code in this repository is not kept up-to-date; rather, it is an archive of our work.
for an up-to-date code base, check out: https://github.com/jovo/oopsi

any questions about this work, please post questions [here](https://github.com/jovo/oopsi/issues)


text:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

/**
 * Created by training on 9/2/2014.
 */
public class WriteToFile2 {
    public static void main(String[] args) {
        try {
            Random rand = new Random();
            int randomNum;
            File file = new File("myFile.txt");
            // creates a FileWriter Object
            FileWriter writer = new FileWriter(file);
            // Writes the content to the file
            for (int i = 0; i < 100; i++) {
                randomNum = rand.nextInt(1000);
                writer.write(randomNum + "\n");
            }
            writer.flush();
            writer.close();

        } catch (IOException e) {
            System.out.println(e);
        }
    }
}


text:
"""Runs SpecCPU2006.

From SpecCPU2006's documentation:
The SPEC CPU2006 benchmark is SPEC's industry-standardized, CPU-intensive
benchmark suite, stressing a system's processor, memory subsystem and compiler.

SpecCPU2006 homepage: http://www.spec.org/cpu2006/
"""

import logging
import posixpath
import re

from perfkitbenchmarker import data
from perfkitbenchmarker import errors
from perfkitbenchmarker import flags
from perfkitbenchmarker import sample

FLAGS = flags.FLAGS

flags.DEFINE_enum('benchmark_subset', 'int', ['int', 'fp', 'all'],
                  'specify a subset of benchmarks to run: int, fp, all')

flags.DEFINE_string('runspec_config', 'linux64-x64-gcc47.cfg',
                    'name of the cpu2006 configuration to use (runspec --config'
                    ' argument)')

flags.DEFINE_integer('runspec_iterations', 3,
                     'number of benchmark iterations to execute - default 3 '
                     '(runspec --iterations argument)')

flags.DEFINE_string('runspec_define', '',
                    'optional comma separated list of preprocessor macros: '
                    'SYMBOL[=VALUE] - e.g. numa,smt,sse=SSE4.2 (runspec '
                    '--define arguments)')

flags.DEFINE_boolean('runspec_enable_32bit', default=False,
                     help='setting this flag will result in installation of '
                     'multilib packages to enable use of 32-bit cpu2006 '
                     'binaries (useful when running on memory constrained '
                     'instance types where 64-bit execution may be problematic '
                     ' - i.e. < 1.5-2GB/core)')

BENCHMARK_INFO = {'name': 'speccpu2006',
                  'description': 'Run Spec CPU2006',
                  'scratch_disk': True,
                  'num_machines': 1}

SPECCPU2006_TAR = 'cpu2006v1.2.tgz'
SPECCPU2006_DIR = 'cpu2006'

def GetInfo():
  return BENCHMARK_INFO

def CheckPrerequisites():
  """Verifies that the required resources are present.

  Raises:
    perfkitbenchmarker.data.ResourceNotFound: On missing resource.
  """
  data.ResourcePath(SPECCPU2006_TAR)

def Prepare(benchmark_spec):
  """Install SpecCPU2006 on the target vm.

  Args:
    benchmark_spec: The benchmark specification. Contains all data that is
        required to run the benchmark.
  """
  vms = benchmark_spec.vms
  vm = vms[0]
  logging.info('prepare SpecCPU2006 on %s', vm)
  vm.Install('wget')
  vm.Install('build_tools')
  vm.Install('fortran')
  if (FLAGS.runspec_enable_32bit):
    vm.Install('multilib')
  vm.Install('numactl')
  try:
    local_tar_file_path = data.ResourcePath(SPECCPU2006_TAR)
  except data.ResourceNotFound as e:
    logging.error('Please provide %s under perfkitbenchmarker/data directory '
                  'before running SpecCPU2006 benchmark.', SPECCPU2006_TAR)
    raise errors.Benchmarks.PrepareException(str(e))
  vm.tar_file_path = posixpath.join(vm.GetScratchDir(), SPECCPU2006_TAR)
  vm.spec_dir = posixpath.join(vm.GetScratchDir(), SPECCPU2006_DIR)
  vm.RemoteCommand('chmod 777 %s' % vm.GetScratchDir())
  vm.PushFile(local_tar_file_path, vm.GetScratchDir())
  vm.RemoteCommand('cd %s && tar xvfz %s' % (vm.GetScratchDir(),
                                             SPECCPU2006_TAR))

def ExtractScore(stdout, vm):
  """Exact the Spec (int|fp) score from stdout.

  Args:
    stdout: stdout from running RemoteCommand.
    vm: The vm instance where Spec CPU2006 was run.

  Sample input for SPECint:
      ...
      ...
      =============================================
      400.perlbench    9770        417       23.4 *
      401.bzip2        9650        565       17.1 *
      403.gcc          8050        364       22.1 *
      429.mcf          9120        364       25.1 *
      445.gobmk       10490        499       21.0 *
      456.hmmer        9330        491       19.0 *
      458.sjeng       12100        588       20.6 *
      462.libquantum  20720        468       44.2 *
      464.h264ref     22130        700       31.6 *
      471.omnetpp      6250        349       17.9 *
      473.astar        7020        482       14.6 *
      483.xalancbmk    6900        248       27.8 *
       Est. SPECint(R)_base2006              22.7

  Sample input for SPECfp:
      ...
      ...
      =============================================
      410.bwaves      13590        717      19.0  *
      416.gamess      19580        923      21.2  *
      433.milc         9180        480      19.1  *
      434.zeusmp       9100        600      15.2  *
      435.gromacs      7140        605      11.8  *
      436.cactusADM   11950       1289       9.27 *
      437.leslie3d     9400        859      10.9  *
      444.namd         8020        504      15.9  *
      447.dealII      11440        409      28.0  *
      450.soplex       8340        272      30.6  *
      453.povray       5320        231      23.0  *
      454.calculix     8250        993       8.31 *
      459.GemsFDTD    10610        775      13.7  *
      465.tonto        9840        565      17.4  *
      470.lbm         13740        365      37.7  *
      481.wrf         11170        788      14.2  *
      482.sphinx3     19490        668      29.2  *
       Est. SPECfp(R)_base2006              17.5

  Returns:
      A list of sample.Sample objects.
  """
  results = []

  re_begin_section = re.compile('^={1,}')
  re_end_section = re.compile(r'Est. (SPEC.*_base2006)\s*(\S*)')
  result_section = []
  in_result_section = False

  # Extract the summary section
  for line in stdout.splitlines():
    if in_result_section:
      result_section.append(line)
    # search for begin of result section
    match = re.search(re_begin_section, line)
    if match:
      assert not in_result_section
      in_result_section = True
      continue
    # search for end of result section
    match = re.search(re_end_section, line)
    if match:
      assert in_result_section
      spec_name = str(match.group(1))
      spec_score = float(match.group(2))
      in_result_section = False
      # remove the final SPEC(int|fp) score, which has only 2 columns.
      result_section.pop()

  metadata = {'machine_type': vm.machine_type, 'num_cpus': vm.num_cpus}
  results.append(sample.Sample(spec_name, spec_score, '', metadata))

  for benchmark in result_section:
    # ignore failed runs
    if re.search('NR', benchmark):
      continue
    # name, ref_time, time, score, misc
    name, _, _, score, _ = benchmark.split()
    results.append(sample.Sample(str(name), float(score), '', metadata))

  return results

def ParseOutput(vm):
  """Parses the output from Spec CPU2006.

  Args:
    vm: The vm instance where Spec CPU2006 was run.

  Returns:
    A list of samples to be published (in the same format as Run() returns).
  """
  results = []

  log_files = []
  # FIXME(liquncheng): Only reference runs generate SPEC scores. The log
  # id is hardcoded as 001, which might change with different runspec
  # parameters. Spec CPU 2006 will generate different logs for build, test
  # run, training run and ref run.
  if FLAGS.benchmark_subset in ('int', 'all'):
    log_files.append('CINT2006.001.ref.txt')
  if FLAGS.benchmark_subset in ('fp', 'all'):
    log_files.append('CFP2006.001.ref.txt')

  for log in log_files:
    stdout, _ = vm.RemoteCommand('cat %s/result/%s' % (vm.spec_dir, log),
                                 should_log=True)
    results.extend(ExtractScore(stdout, vm))

  return results

def Run(benchmark_spec):
  """Run SpecCPU2006 on the target vm.

  Args:
    benchmark_spec: The benchmark specification. Contains all data that is
        required to run the benchmark.

  Returns:
    A list of sample.Sample objects.
  """
  vms = benchmark_spec.vms
  vm = vms[0]
  logging.info('SpecCPU2006 running on %s', vm)
  num_cpus = vm.num_cpus
  iterations = ' --iterations=' + repr(FLAGS.runspec_iterations) if \
               FLAGS.runspec_iterations != 3 else ''
  defines = ' --define ' + ' --define '.join(FLAGS.runspec_define.split(','))\
            if FLAGS.runspec_define != '' else ''
  vm.RemoteCommand('cd %s; . ./shrc; ./bin/relocate; . ./shrc; rm -rf result; '
                   'runspec --config=%s --tune=base '
                   '--size=ref --noreportable --rate %s%s%s %s'
                   % (vm.spec_dir, FLAGS.runspec_config, num_cpus, iterations,
                      defines, FLAGS.benchmark_subset))
  logging.info('SpecCPU2006 Results:')
  return ParseOutput(vm)

def Cleanup(benchmark_spec):
  """Cleanup SpecCPU2006 on the target vm.

  Args:
    benchmark_spec: The benchmark specification. Contains all data that is
        required to run the benchmark.
  """
  vms = benchmark_spec.vms
  vm = vms[0]
  vm.RemoteCommand('rm -rf %s' % vm.spec_dir)
  vm.RemoteCommand('rm -f %s' % vm.tar_file_path)


text:
package com.cognizant.cognizantits.qcconnection.qcupdation;

import com4j.Com4jObject;
import com4j.DISPID;
import com4j.IID;
import com4j.NativeType;
import com4j.ReturnValue;
import com4j.VTID;

@IID("{3A3FE6C4-6DE7-47AB-8BF1-EE578637596A}")
public abstract interface IExtensionData
  extends Com4jObject
{
  @DISPID(1)
  @VTID(7)
  public abstract String name();

  @DISPID(2)
  @VTID(8)
  public abstract String displayName();

  @DISPID(3)
  @VTID(9)
  public abstract String uiDataProviderId();

  @DISPID(4)
  @VTID(10)
  public abstract String version();

  @DISPID(5)
  @VTID(11)
  public abstract String otaDataProviderId();

  @DISPID(6)
  @VTID(12)
  public abstract IList modules();

  @VTID(12)
  @ReturnValue(type=NativeType.VARIANT, defaultPropertyThrough={IList.class})
  public abstract Object modules(int paramInt);

  @DISPID(7)
  @VTID(13)
  public abstract String repositoryRoot();
}

/* Location:           D:\Prabu\jars\QC.jar
 * Qualified Name:     qcupdation.IExtensionData
 * JD-Core Version:    0.7.0.1
 */


text:
#pragma once

#include <string>
#include <future>
#include <memory>
#include <stdexcept>
#include <ctime>

#include <boost/process.hpp>
#include <boost/exception/all.hpp>
#include "SteamAppInfo.h"

class SteamServerProcess
{
    const std::string m_appID;
    std::string m_exePath;
    const std::string m_Args;
    const std::string m_branch;
    std::string m_manifestPath;

    const SteamAppInfo& m_appInfo;

    const std::string m_steamCMD;
    std::string m_steamCMDArgs;

    std::unique_ptr<boost::process::child> m_process;
    std::future<int> m_processThread;
    struct ManifestData
    {
        std::string path;
        std::string name;
        std::string installedBuildId;
        std::time_t lastModified;
    } m_manifest;
    /// get the version from the current installation
    ManifestData getManifest(const std::string& steamManifestDir);

    void steamCMDUpdate();
    void createProcess();
    void checkUpdateLoop(size_t intervalInMS);
public:
    struct Init
    {
        std::string steamCMD;
        std::string appId;
        std::string args;
        std::string installDir;
        std::string manifestPath;
        std::string branch;
        std::string branchPW;
    };

    struct file_find_exception : virtual boost::exception
    {
        typedef boost::error_info<struct tag_file_find_exception_func_desc, std::string > func_desc;
        file_find_exception(const std::string& filename, const std::string& function = "") :
            boost::exception()
        {
            *this << func_desc(function) << boost::errinfo_file_name(filename);
        }
    };

    SteamServerProcess(const SteamAppInfo &appInfo, Init i);
    inline ~SteamServerProcess()
    {
        terminateProgram();
    }

    inline std::string getAppName()const { return m_manifest.name; }

    inline std::string getBranch()const { return m_branch;  }

    inline std::string getAppId()const { return m_appID; }

    inline std::string getInstalledBuildId() const
    {
        return m_manifest.installedBuildId;
    }

    /** Creates and starts the process
    @param intervalInMS Give Interval between update checks in miliseconds
    @ param precheck If true, given app will be updated or installed (if not) before trying to start it
    */
    void run(std::size_t updateInMS, bool precheck = true);

    inline bool isRunning()const
    {
        return m_process != nullptr;
    }

    /// run the program and wait for exit
    inline void waitFor(std::size_t ms)const
    {
        m_processThread.wait_for(std::chrono::milliseconds(ms));
    }

    /// stops the program. TODO: reimplement with custom stop function per application
    inline void stop()
    {
        terminateProgram();
    }

    /// forces the program to terminate
    void terminateProgram();
};


text:
> Converts colors to [less color operation functions](http://lesscss.org/functions/#color-operations)

![](grunt-colors.gif)

## Install
`npm install grunt-colors-to-less-operations --save-dev`

## Usage

In Gruntfile.js write this:
```js
less_colors: {
  start: {
    options: {
      funcName: 'cless'
    },
    files: {
      'src/less/variables.less': ['src/less/variables.less']
    }
  }
}
```
After that you can use it like this:

```
@navy: #81b3d2;
@btn-nav-hvr: name_of_your_function(@navy, #5fac53);
```
will be converted right in your file to:

```
@btn-nav-hvr: spin(desaturate(darken(@navy, 16%), 12%), -91); // desire: #5fac53 - result: #60ad54
```


text:
"""
This defines the cmdset for the red_button. Here we have defined
the commands and the cmdset in the same module, but if you
have many different commands to merge it is often better
to define the cmdset separately, picking and choosing from
among the available commands as to what should be included in the
cmdset - this way you can often re-use the commands too.
"""

import random
from ev import Command, CmdSet

# Some simple commands for the red button

#------------------------------------------------------------
# Commands defined on the red button
#------------------------------------------------------------

class CmdNudge(Command):
    """
    Try to nudge the button's lid

    Usage:
      nudge lid

    This command will have you try to
    push the lid of the button away.
    """

    key = "nudge lid" # two-word command name!
    aliases = ["nudge"]
    locks = "cmd:all()"

    def func(self):
        """
        nudge the lid. Random chance of success to open it.
        """
        rand = random.random()
        if rand < 0.5:
            self.caller.msg("You nudge at the lid. It seems stuck.")
        elif 0.5 <= rand < 0.7:
            self.caller.msg("You move the lid back and forth. It won't budge.")
        else:
            self.caller.msg("You manage to get a nail under the lid.")
            self.caller.execute_cmd("open lid")

class CmdPush(Command):
    """
    Push the red button

    Usage:
      push button

    """
    key = "push button"
    aliases = ["push", "press button", "press"]
    locks = "cmd:all()"

    def func(self):
        """
        Note that we choose to implement this with checking for
        if the lid is open/closed. This is because this command
        is likely to be tried regardless of the state of the lid.

        An alternative would be to make two versions of this command
        and tuck them into the cmdset linked to the Open and Closed
        lid-state respectively.

        """

        if self.obj.db.lid_open:
            string = "You reach out to press the big red button ..."
            string += "\n\nA BOOM! A bright light blinds you!"
            string += "\nThe world goes dark ..."
            self.caller.msg(string)
            self.caller.location.msg_contents("%s presses the button. BOOM! %s is blinded by a flash!" %
                                              (self.caller.name, self.caller.name), exclude=self.caller)
            # the button's method will handle all setup of scripts etc.
            self.obj.press_button(self.caller)
        else:
            string = "You cannot push the button - there is a glass lid covering it."
            self.caller.msg(string)

class CmdSmashGlass(Command):
    """
    smash glass

    Usage:
      smash glass

    Try to smash the glass of the button.
    """

    key = "smash glass"
    aliases = ["smash lid", "break lid", "smash"]
    locks = "cmd:all()"

    def func(self):
        """
        The lid won't open, but there is a small chance
        of causing the lamp to break.
        """
        rand = random.random()

        if rand < 0.2:
            string = "You smash your hand against the glass"
            string += " with all your might. The lid won't budge"
            string += " but you cause quite the tremor through the button's mount."
            string += "\nIt looks like the button's lamp stopped working for the time being."
            self.obj.lamp_works = False
        elif rand < 0.6:
            string = "You hit the lid hard. It doesn't move an inch."
        else:
            string = "You place a well-aimed fist against the glass of the lid."
            string += " Unfortunately all you get is a pain in your hand. Maybe"
            string += " you should just try to open the lid instead?"
        self.caller.msg(string)
        self.caller.location.msg_contents("%s tries to smash the glass of the button." %
                                          (self.caller.name), exclude=self.caller)

class CmdOpenLid(Command):
    """
    open lid

    Usage:
      open lid

    """

    key = "open lid"
    aliases = ["open button", 'open']
    locks = "cmd:all()"

    def func(self):
        "simply call the right function."

        if self.obj.db.lid_locked:
            self.caller.msg("This lid seems locked in place for the moment.")
            return

        string = "\nA ticking sound is heard, like a winding mechanism. Seems "
        string += "the lid will soon close again."
        self.caller.msg(string)
        self.caller.location.msg_contents("%s opens the lid of the button." %
                                          (self.caller.name), exclude=self.caller)
        # add the relevant cmdsets to button
        self.obj.cmdset.add(LidClosedCmdSet)
        # call object method
        self.obj.open_lid()

class CmdCloseLid(Command):
    """
    close the lid

    Usage:
      close lid

    Closes the lid of the red button.
    """

    key = "close lid"
    aliases = ["close"]
    locks = "cmd:all()"

    def func(self):
        "Close the lid"

        self.obj.close_lid()

        # this will clean out scripts dependent on lid being open.
        self.caller.msg("You close the button's lid. It clicks back into place.")
        self.caller.location.msg_contents("%s closes the button's lid." %
                                          (self.caller.name), exclude=self.caller)

class CmdBlindLook(Command):
    """
    Looking around in darkness

    Usage:
      look <obj>

    ... not that there's much to see in the dark.

    """

    key = "look"
    aliases = ["l", "get", "examine", "ex", "feel", "listen"]
    locks = "cmd:all()"

    def func(self):
        "This replaces all the senses when blinded."

        # we decide what to reply based on which command was
        # actually tried

        if self.cmdstring == "get":
            string = "You fumble around blindly without finding anything."
        elif self.cmdstring == "examine":
            string = "You try to examine your surroundings, but can't see a thing."
        elif self.cmdstring == "listen":
            string = "You are deafened by the boom."
        elif self.cmdstring == "feel":
            string = "You fumble around, hands outstretched. You bump your knee."
        else:
            # trying to look
            string = "You are temporarily blinded by the flash. "
            string += "Until it wears off, all you can do is feel around blindly."
        self.caller.msg(string)
        self.caller.location.msg_contents("%s stumbles around, blinded." %
                                          (self.caller.name), exclude=self.caller)

class CmdBlindHelp(Command):
    """
    Help function while in the blinded state

    Usage:
      help

    """
    key = "help"
    aliases = "h"
    locks = "cmd:all()"

    def func(self):
        "Give a message."
        self.caller.msg("You are beyond help ... until you can see again.")

#---------------------------------------------------------------
# Command sets for the red button
#---------------------------------------------------------------

# We next tuck these commands into their respective command sets.
# (note that we are overdoing the cdmset separation a bit here
# to show how it works).

class DefaultCmdSet(CmdSet):
    """
    The default cmdset always sits
    on the button object and whereas other
    command sets may be added/merge onto it
    and hide it, removing them will always
    bring it back. It's added to the object
    using obj.cmdset.add_default().
    """
    key = "RedButtonDefault"
    mergetype = "Union" # this is default, we don't really need to put it here.

    def at_cmdset_creation(self):
        "Init the cmdset"
        self.add(CmdPush())

class LidClosedCmdSet(CmdSet):
    """
    A simple cmdset tied to the redbutton object.

    It contains the commands that launches the other
    command sets, making the red button a self-contained
    item (i.e. you don't have to manually add any
    scripts etc to it when creating it).
    """
    key = "LidClosedCmdSet"
    # default Union is used *except* if we are adding to a
    # cmdset named LidOpenCmdSet - this one we replace
    # completely.
    key_mergetype = {"LidOpenCmdSet": "Replace"}

    def at_cmdset_creation(self):
        "Populates the cmdset when it is instantiated."
        self.add(CmdNudge())
        self.add(CmdSmashGlass())
        self.add(CmdOpenLid())

class LidOpenCmdSet(CmdSet):
    """
    This is the opposite of the Closed cmdset.
    """
    key = "LidOpenCmdSet"
    # default Union is used *except* if we are adding to a
    # cmdset named LidClosedCmdSet - this one we replace
    # completely.
    key_mergetype = {"LidClosedCmdSet": "Replace"}

    def at_cmdset_creation(self):
        "setup the cmdset (just one command)"
        self.add(CmdCloseLid())

class BlindCmdSet(CmdSet):
    """
    This is the cmdset added to the *player* when
    the button is pushed.
    """
    key = "BlindCmdSet"
    # we want it to completely replace all normal commands
    # until the timed script removes it again.
    mergetype = "Replace"
    # we want to stop the player from walking around
    # in this blinded state, so we hide all exits too.
    # (channel commands will still work).
    no_exits = True # keep player in the same room
    no_objs = True # don't allow object commands

    def at_cmdset_creation(self):
        "Setup the blind cmdset"
        from src.commands.default.general import CmdSay
        from src.commands.default.general import CmdPose
        self.add(CmdSay())
        self.add(CmdPose())
        self.add(CmdBlindLook())
        self.add(CmdBlindHelp())


text:
#ifndef _TBB_malloc_Customize_H_
#define _TBB_malloc_Customize_H_

// customizing MALLOC_ASSERT macro
#include "tbb/tbb_stddef.h"
#define MALLOC_ASSERT(assertion, message) __TBB_ASSERT(assertion, message)

#ifndef MALLOC_DEBUG
#define MALLOC_DEBUG TBB_USE_DEBUG
#endif

#include "tbb/tbb_machine.h"

#if DO_ITT_NOTIFY
#include "tbb/itt_notify.h"
#define MALLOC_ITT_SYNC_PREPARE(pointer) ITT_NOTIFY(sync_prepare, (pointer))
#define MALLOC_ITT_SYNC_ACQUIRED(pointer) ITT_NOTIFY(sync_acquired, (pointer))
#define MALLOC_ITT_SYNC_RELEASING(pointer) ITT_NOTIFY(sync_releasing, (pointer))
#define MALLOC_ITT_SYNC_CANCEL(pointer) ITT_NOTIFY(sync_cancel, (pointer))
#define MALLOC_ITT_FINI_ITTLIB()        ITT_FINI_ITTLIB()
#else
#define MALLOC_ITT_SYNC_PREPARE(pointer) ((void)0)
#define MALLOC_ITT_SYNC_ACQUIRED(pointer) ((void)0)
#define MALLOC_ITT_SYNC_RELEASING(pointer) ((void)0)
#define MALLOC_ITT_SYNC_CANCEL(pointer) ((void)0)
#define MALLOC_ITT_FINI_ITTLIB()        ((void)0)
#endif

//! Stripped down version of spin_mutex.
/** Instances of MallocMutex must be declared in memory that is zero-initialized.
    There are no constructors.  This is a feature that lets it be
    used in situations where the mutex might be used while file-scope constructors
    are running.

    There are no methods "acquire" or "release".  The scoped_lock must be used
    in a strict block-scoped locking pattern.  Omitting these methods permitted
    further simplification. */
class MallocMutex : tbb::internal::no_copy {
    __TBB_atomic_flag flag;

public:
    class scoped_lock : tbb::internal::no_copy {
        MallocMutex& mutex;
        bool taken;
    public:
        scoped_lock( MallocMutex& m ) : mutex(m), taken(true) { __TBB_LockByte(m.flag); }
        scoped_lock( MallocMutex& m, bool block, bool *locked ) : mutex(m), taken(false) {
            if (block) {
                __TBB_LockByte(m.flag);
                taken = true;
            } else {
                taken = __TBB_TryLockByte(m.flag);
            }
            if (locked) *locked = taken;
        }
        ~scoped_lock() {
            if (taken) __TBB_UnlockByte(mutex.flag);
        }
    };
    friend class scoped_lock;
};

// TODO: use signed/unsigned in atomics more consistently
inline intptr_t AtomicIncrement( volatile intptr_t& counter ) {
    return __TBB_FetchAndAddW( &counter, 1 )+1;
}

inline uintptr_t AtomicAdd( volatile intptr_t& counter, intptr_t value ) {
    return __TBB_FetchAndAddW( &counter, value );
}

inline intptr_t AtomicCompareExchange( volatile intptr_t& location, intptr_t new_value, intptr_t comparand) {
    return __TBB_CompareAndSwapW( &location, new_value, comparand );
}

inline uintptr_t AtomicFetchStore(volatile void* location, uintptr_t value) {
    return __TBB_FetchAndStoreW(location, value);
}

inline void AtomicOr(volatile void *operand, uintptr_t addend) {
    __TBB_AtomicOR(operand, addend);
}

inline void AtomicAnd(volatile void *operand, uintptr_t addend) {
    __TBB_AtomicAND(operand, addend);
}

inline intptr_t FencedLoad( const volatile intptr_t &location ) {
    return __TBB_load_with_acquire(location);
}

inline void FencedStore( volatile intptr_t &location, intptr_t value ) {
    __TBB_store_with_release(location, value);
}

inline void SpinWaitWhileEq(const volatile intptr_t &location, const intptr_t value) {
    tbb::internal::spin_wait_while_eq(location, value);
}

class AtomicBackoff {
    tbb::internal::atomic_backoff backoff;
public:
    AtomicBackoff() {}
    void pause() { backoff.pause(); }
};

inline void SpinWaitUntilEq(const volatile intptr_t &location, const intptr_t value) {
    tbb::internal::spin_wait_until_eq(location, value);
}

inline intptr_t BitScanRev(uintptr_t x) {
    return !x? -1 : __TBB_Log2(x);
}

template<typename T>
static inline bool isAligned(T* arg, uintptr_t alignment) {
    return tbb::internal::is_aligned(arg,alignment);
}

static inline bool isPowerOfTwo(uintptr_t arg) {
    return tbb::internal::is_power_of_two(arg);
}
static inline bool isPowerOfTwoAtLeast(uintptr_t arg, uintptr_t power2) {
    return arg && tbb::internal::is_power_of_two_at_least(arg,power2);
}

#define MALLOC_STATIC_ASSERT(condition,msg) __TBB_STATIC_ASSERT(condition,msg)

#define USE_DEFAULT_MEMORY_MAPPING 1

// To support malloc replacement
#include "proxy.h"

#if MALLOC_UNIXLIKE_OVERLOAD_ENABLED
#define malloc_proxy __TBB_malloc_proxy
extern "C" void * __TBB_malloc_proxy(size_t)  __attribute__ ((weak));
#elif MALLOC_ZONE_OVERLOAD_ENABLED
// as there is no significant overhead, always suppose that proxy can be present
const bool malloc_proxy = true;
#else
const bool malloc_proxy = false;
#endif

namespace rml {
namespace internal {
    void init_tbbmalloc();
} } // namespaces

#define MALLOC_EXTRA_INITIALIZATION rml::internal::init_tbbmalloc()

// Need these to work regardless of tools support.
namespace tbb {
    namespace internal {

        enum notify_type {prepare=0, cancel, acquired, releasing};

#if TBB_USE_THREADING_TOOLS
        inline void call_itt_notify(notify_type t, void *ptr) {
            switch ( t ) {
            case prepare:
                MALLOC_ITT_SYNC_PREPARE( ptr );
                break;
            case cancel:
                MALLOC_ITT_SYNC_CANCEL( ptr );
                break;
            case acquired:
                MALLOC_ITT_SYNC_ACQUIRED( ptr );
                break;
            case releasing:
                MALLOC_ITT_SYNC_RELEASING( ptr );
                break;
            }
        }
#else
        inline void call_itt_notify(notify_type /*t*/, void * /*ptr*/) {}
#endif // TBB_USE_THREADING_TOOLS

        template <typename T>
        inline void itt_store_word_with_release(T& dst, T src) {
#if TBB_USE_THREADING_TOOLS
            call_itt_notify(releasing, &dst);
#endif // TBB_USE_THREADING_TOOLS
            FencedStore(*(intptr_t*)&dst, src);
        }

        template <typename T>
        inline T itt_load_word_with_acquire(T& src) {
            T result = FencedLoad(*(intptr_t*)&src);
#if TBB_USE_THREADING_TOOLS
            call_itt_notify(acquired, &src);
#endif // TBB_USE_THREADING_TOOLS
            return result;

        }
    } // namespace internal
} // namespace tbb

#include "tbb/internal/_aggregator_impl.h"

template <typename OperationType>
struct MallocAggregator {
    typedef tbb::internal::aggregator_generic<OperationType> type;
};

//! aggregated_operation base class
template <typename Derived>
struct MallocAggregatedOperation {
    typedef tbb::internal::aggregated_operation<Derived> type;
};

#endif /* _TBB_malloc_Customize_H_ */


text:
layout: default
title: Contact Loki Huang
---

Contact Me

This is an example Contact page. If you want to make changes then do so in the contact.html file.

The form is provided by Formspree. Follow the directions on their site to set up the form for use.

If you have questions about the theme feel free to email me or create an issue on GitHub. Enjoy!

  <form action="http://formspree.io/your@mail.com" method="POST">
    Name
    <input type="text" id="name" name="name" class="full-width">

    Email Address
    <input type="email" id="email" name="_replyto" class="full-width">

    Message
    <textarea name="message" id="message" cols="30" rows="10" class="full-width"></textarea>

    <input type="submit" value="Send" class="button">
  </form>


text:
package com.worldsworstsoftware.xmltagparser;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.AttributeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.worldsworstsoftware.logging.StatusUpdateLogger;

/**
 * The SimpleXMLTagParser uses a SAX XML parser to parse the given
 * file into tags.
 *
 * A typical XML parser would worry about parsing nested tags, but
 * apple's xml file format allows us to not worry about the complexities
 * of nested tags.
 *
 * For example in a typical XML format you might expect track information
 * to be formatted like so:
 *
 *    <Track>
 * 	   <Name>Come Together</Name>
 *     <Artist>The Beatles</Artist>
 *    </Track>
 *
 * But Apple's format for the same information is a bit different:
 *
 *    <key>Track ID</key><integer>401</integer>
 *    <key>Name</key><string>Come Together</string>
 *    <key>Artist</key><string>The Beatles</string>
 *
 * So for our purposes we can simply pass the latest parsed tag and its
 * inner text up to whatever tag handling mechanism we've implemented.
 *
 * @author Jason Baker of http://www.worldsworstsoftware.com
 */
public class SimpleXMLTagParser extends org.xml.sax.HandlerBase
{

	//TODO JAVADOC:

    private TagHandler tagHandler = null;
    private String xmlFileLocation = null;
    private ErrorHandler errorHandler;
    private boolean resolveEntities = false;
    private Tag currentTag = null;

    //provided for performance testing
    private int charactersCallsCount = 0;

    /** Creates a new instance of SimpleXMLTagParser */
    public SimpleXMLTagParser(String xmlFileLocation,
    		TagHandler tagHandler,
    		StatusUpdateLogger logger,
			boolean resolveEntities)
    {
        if (tagHandler == null)
        {
            throw new RuntimeException("tagHandler cannot be null.");
        }

        this.tagHandler = tagHandler;
        this.xmlFileLocation = xmlFileLocation;
        this.resolveEntities = resolveEntities;
        this.errorHandler = new SimpleXMLErrorHandler(logger);
        this.currentTag = new Tag();
        this.charactersCallsCount = 0;
    }

    public int getCharacterCallsCount()
    {
    	return this.charactersCallsCount;
    }

    public void setErrorHandler(ErrorHandler errorHandler)
    {
        if (errorHandler == null)
        {
            throw new RuntimeException("errorHandler cannot be null.");
        }

        this.errorHandler = errorHandler;
    }

    public void parse() throws IOException, SAXException, ParserConfigurationException
    {

        // parser stuff figured out with great ease thanks to java examples in a nutshell By David Flanagan
        // http://www.oreilly.com/catalog/jenut2/chapter/ch19.html

        // Create a JAXP "parser factory" for creating SAX parsers
        SAXParserFactory spf = SAXParserFactory.newInstance();

        // Configure the parser factory for the type of parsers we require
        spf.setValidating(false);  // No validation required

        // Now use the parser factory to create a SAXParser object
        // Note that SAXParser is a JAXP class, not a SAX class
        javax.xml.parsers.SAXParser sp = spf.newSAXParser();

        // Create a SAX input source for the file argument
        org.xml.sax.InputSource input = new InputSource(new FileReader(this.xmlFileLocation));

        // Give the InputSource an absolute URL for the file, so that
        // it can resolve relative URLs in a <!DOCTYPE> declaration, e.g.
        input.setSystemId("file://" + new File(this.xmlFileLocation).getAbsolutePath());

        // Finally, tell the parser to parse the input and notify the handler
        // sp.parse(input, this);

        // Instead of using the SAXParser.parse() method, which is part of the
        // JAXP API, we could also use the SAX1 API directly.  Note the
        // difference between the JAXP class javax.xml.parsers.SAXParser and
        // the SAX1 class org.xml.sax.Parser
        //
        org.xml.sax.Parser parser = sp.getParser();  // Get the SAX parser

        if (this.resolveEntities)
        {
            parser.setEntityResolver(this);
        }
        else
        {
            parser.setEntityResolver(new SAXFakeEntityResolver());
        }

        parser.setDocumentHandler(this);          // Set main handler
        parser.setErrorHandler(errorHandler);             // Set error handler
        parser.parse(input);                         // Parse!
    }

    public void startElement(String name, AttributeList attributes)
    {
        currentTag.clear();
        currentTag.setName(name);
    }

    public void endElement(String name)
    {
        //TODO FUTURE: we could do some sanity checking here to make sure the end tag name matches the tag on the top of the stack
        this.tagHandler.handleTag(currentTag);
    }

    public void characters(char[] buffer, int start, int length)
    {
    	charactersCallsCount++;

    	//put char data into the tag
        currentTag.addInnerText(buffer, start, length);
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>TestFlightHelper - FAKE - F# Make</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull">

    <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">

    <link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" />

fsharp.org

github page

FAKE - F# Make

TestFlightHelper

Contains tasks to upload apps to TestFlight

Nested types and modules

Type	Description

            TestFlightParams

The TestFlight parameter type.

Functions and values

Function or value	Description

            TestFlight setParams

            Signature:setParams:(TestFlightParams -> TestFlightParams) -> unit

Uploads the app build to TestFlight.

Parameters

setParams - Function used to manipulate the default TestFlightParams value.

            Go to GitHub source

            TestFlightDefaults

            Signature:TestFlightParams

The default TestFlight upload parameters.

            Go to GitHub source

FAKE - F# Make

Home page

Get FAKE via NuGet

Source Code on GitHub

License (MS-PL)

Who is using FAKE?

Release Notes

Contributing to FAKE

Ask a question

Articles

Getting started

NuGet package restore

Using FxCop in a build

Generating AssemblyInfo

Create NuGet packages

Running specific targets

Running FAKE from command line

Creating custom tasks

TeamCity integration

Running canopy tests

Octopus Deploy

TypeScript support

Fake.Deploy

Documentation

API Reference


text:
class Subject < ApplicationRecord
  # Uploaders
  mount_uploader :overview_report_pdf, PDFUploader

  # Concerns
  include Latexable
  include Reportable

  # Scopes
  scope :consented, -> { where.not(consented_at: nil).where(consent_revoked_at: nil) }
  scope :consent_revoked, -> { where.not(consented_at: nil, consent_revoked_at: nil) }

  # Validations
  validates :user_id, uniqueness: { scope: :project_id }

  # Relationships
  belongs_to :user
  belongs_to :project
  has_many :subject_surveys

  # Methods

  def consented?
    !consented_at.nil? && consent_revoked_at.nil?
  end

  def consent_revoked?
    !consented_at.nil? && !consent_revoked_at.nil?
  end

  def revoke_consent!
    update(consent_revoked_at: Time.zone.now)
  end

  # This method is only for external projects (that don't have Slice surveys).
  def recruited?
    !recruited_at.nil?
  end

  def linked?
    slice_subject_id.present?
  end

  def find_or_create_remote_subject!
    if linked?
      load_remote_subject
    else
      create_remote_subject!
      create_baseline_event!
    end
  end

  def create_remote_subject!
    params = {
      subject: {
        subject_code: project.generate_subject_code,
        site_id: project.slice_site_id
      }
    }
    (json, status) = Slice::JsonRequest.post("#{project.project_url}/subjects.json", params)
    load_subject_from_json(json, status)
    # link_subject
  end

  def load_remote_subject
    (json, status) = Slice::JsonRequest.get("#{project.project_url}/subjects/#{slice_subject_id}.json")
    load_subject_from_json(json, status)
  end

  def load_subject_from_json(json, status)
    return unless status.is_a?(Net::HTTPSuccess)
    return unless json
    update(
      slice_subject_id: json["id"],
      slice_subject_code_cache: json["subject_code"]
    )
    # @json = json
    # root_attributes.each do |attribute|
    #   send("#{attribute}=", json[attribute.to_s])
    # end
  end

  def create_baseline_event!
    return unless linked?
    params = { event_id: project.slice_baseline_event.presence || "baseline" } # Event.first.slug
    (json, status) = Slice::JsonRequest.post("#{project.project_url}/subjects/#{slice_subject_id}/events.json", params)
    load_events_from_json(json, status)
  end

  def subject_events
    @subject_events ||= begin
      load_subject_events
    end
  end

  def load_subject_events
    return [] unless linked?
    (json, status) = Slice::JsonRequest.get("#{project.project_url}/subjects/#{slice_subject_id}/events.json")
    load_events_from_json(json, status)
  end

  def load_events_from_json(json, status)
    return [] unless status.is_a?(Net::HTTPSuccess)
    return [] unless json
    json.collect do |subject_event|
      Slice::SubjectEvent.new(subject_event)
    end
  end

  def next_survey
    @next_survey ||= begin
      event = subject_events.find { |se| !se.complete?(self) }
      event&.event_designs&.find { |ed| !ed.complete?(self) }
    end
  end

  def resume_event_survey(event, design)
    Slice::JsonRequest.get("#{project.project_url}/subjects/#{slice_subject_id}/surveys/#{event}/#{design}/resume.json")
  end

  def page_event_survey(event, design, page)
    Slice::JsonRequest.get("#{project.project_url}/subjects/#{slice_subject_id}/surveys/#{event}/#{design}/#{page}.json")
  end

  def submit_response_event_survey(event, design, page, design_option_id, response, remote_ip)
    params = { _method: "patch", design_option_id: design_option_id, response: response, remote_ip: remote_ip }
    Slice::JsonRequest.post("#{project.project_url}/subjects/#{slice_subject_id}/surveys/#{event}/#{design}/#{page}.json", params)
  end

  def review_event_survey(event, design)
    params = { subject_id: slice_subject_id }
    Slice::JsonRequest.get("#{project.project_url}/reports/review/#{event}/#{design}.json", params)
  end

  def report_event_survey(event, design)
    params = { subject_id: slice_subject_id }
    Slice::JsonRequest.get("#{project.project_url}/reports/#{event}/#{design}.json", params)
  end

  def data(data_points)
    params = { data_points: data_points }
    (json, status) = Slice::JsonRequest.get("#{project.project_url}/subjects/#{slice_subject_id}/data.json", params)
    return unless status.is_a?(Net::HTTPSuccess)
    json
  end

  # Print Consent
  def latex_partial(partial)
    File.read(File.join("app", "views", "subjects", "latex", "_#{partial}.tex.erb"))
  end

  def generate_overview_report_pdf!(data)
    jobname = "overview_report"
    temp_dir = Dir.mktmpdir
    temp_tex = File.join(temp_dir, "#{jobname}.tex")
    write_tex_file(temp_tex, data)
    self.class.compile(jobname, temp_dir, temp_tex)
    temp_pdf = File.join(temp_dir, "#{jobname}.pdf")
    update overview_report_pdf: File.open(temp_pdf, "r"), overview_report_pdf_file_size: File.size(temp_pdf) if File.exist?(temp_pdf)
  ensure
    # Remove the directory.
    FileUtils.remove_entry temp_dir
  end

  def write_tex_file(temp_tex, data)
    # Needed by binding
    @project = project
    @subject = self
    @data = data
    File.open(temp_tex, "w") do |file|
      file.syswrite(ERB.new(latex_partial("header")).result(binding))
      file.syswrite(ERB.new(latex_partial("overview_report")).result(binding))
      file.syswrite(ERB.new(latex_partial("footer")).result(binding))
    end
  end
end


text:
<?php
namespace AppBundle\DependencyInjection;

// Autorisation de tourner 8h sans interruption pour le script
set_time_limit(28800);

use PHPCrawler;
use PHPCrawlerDocumentInfo;
use PHPCrawlerResponseHeader;

use Doctrine\ORM\EntityManager;
use AppBundle\Entity\Article;

/**
 * Description of MyCrawler
 *
 * @author Norman
 */
class MyCrawler extends PHPCrawler{

    public $result = array();
    public $content = array();

    public $blog_id;
    public $status;
    public $counter = 0;

    /**
     * Overridable method that will be called after the header of a document was received and BEFORE the content will be received
     *
     * @param PHPCrawlerResponseHeader $header
     */
    public function handleHeaderInfo(PHPCrawlerResponseHeader $header)
    {
//var_dump($header);
    }

    /**
     * Récupère les infos d'une url
     *
     * @param PHPCrawlerDocumentInfo $pageInfo
     */
    public function handleDocumentInfo(PHPCrawlerDocumentInfo $pageInfo)
    {
        $page_url = $pageInfo->url;
        $source = $pageInfo->source;
        $status = $pageInfo->http_status_code;

        $logPath = dirname(dirname(dirname(__DIR__))).'/web/logs';

        // Si page "OK" (pas de code erreur) et non vide, affiche l'url
        if($status == 200 && $source!='')
        {
            $this->counter++;
            // Ecriture d'un fichier getOutput.php qui contient les résultats actuels (en cours)

//            echo $this->blog_id;
//            echo $this->status;

//            echo $page_url.'
';
//            echo "Links found: " . count($pageInfo->links_found_url_descriptors) .'
';

            // $status = 1 pour crawl complet avec sauvegarde / $status = 0 pour les tests
            // le counter est là pour éviter l'enregistrement de la première entrée, qui est l'url de base
            if($this->status == 1 && $this->counter > 1){
                // Crawl complet
                $blog = $this->em->getRepository('AppBundle:Blog')->find($this->blog_id);

                $article = new Article();

                // Date actuelle
                $date = new \DateTime('', new \DateTimeZone('Europe/Paris'));
                $article->setSaveDate($date);

                $article->setBlog($blog);
                $article->setUrl($page_url);
                $article->setSource($pageInfo->content);

                $this->em->persist($article);
                $this->em->flush();

                // Enregistrement d'un log *************************************
                // Création du fichier log
                $file = glob($logPath ."/". "*" . $this->crawler_uniqid . ".txt");

                if(empty($file)){

                    $logFile = $logPath. '/crawl_log_for_blogId_' . $this->blog_id .'_'. date("Y_m_d_G_i_s") . '_ID_' . $this->crawler_uniqid . '.txt';
                    // Ouverture du fichier
                    $log = fopen($logFile, 'c');
                    // Ecriture
                    fwrite($log, $page_url . "\n");
                    fclose($log);
                }else{
                    file_put_contents($file[0], $page_url . "\n", FILE_APPEND);
                }
                // NOTE : Le fichier log est détruit lors du passage sur l'affichage du blog (blog_show)
                // Enregistrement d'un log FIN *********************************
//
//                echo $page_url.'
';
//                flush();

            }else{
                // Tests ($status == 0)
                $this->result[] = $page_url;
                $this->content[] = $pageInfo->content;
            }
        }
    }
}


text:
import { CordovaPopupWindow } from './CordovaPopupWindow';
import { INavigator } from './INavigator';
export declare class CordovaPopupNavigator implements INavigator {
    prepare(params: any): Promise<CordovaPopupWindow>;
}


text:
class Dict {
public:
  // Add new entry, return id if exists
  int insert_word(std::string word) {
    auto it = word2id_.find(word);
    if (it != word2id_.end()) { return it->second; } // found
    else { word2id_[word] = cnt_; id2word_[cnt_] = word; return cnt_++; } // new
  }
  // Return negative if not exist
  int get_id(std::string word) {
    auto it = word2id_.find(word);
    if (it != word2id_.end()) { return it->second; } // found
    else { return -1; }
  }
  // Error if id is not found
  std::string get_word(int id) {
    auto it = id2word_.find(id);
    CHECK(it != id2word_.end());
    return it->second;
  }
  size_t size() { return cnt_; }

private:
  size_t cnt_ = 0;
  std::unordered_map<std::string, int> word2id_;
  std::unordered_map<int, std::string> id2word_;
};

#endif


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Comparison_1_gen2887177558MethodDeclarations.h"

// System.Void System.Comparison`1<UnityEngine.Transform>::.ctor(System.Object,System.IntPtr)
#define Comparison_1__ctor_m1754711900(__this, ___object0, ___method1, method) ((  void (*) (Comparison_1_t375483973 *, Il2CppObject *, IntPtr_t, const MethodInfo*))Comparison_1__ctor_m487232819_gshared)(__this, ___object0, ___method1, method)
// System.Int32 System.Comparison`1<UnityEngine.Transform>::Invoke(T,T)
#define Comparison_1_Invoke_m934362468(__this, ___x0, ___y1, method) ((  int32_t (*) (Comparison_1_t375483973 *, Transform_t1659122786 *, Transform_t1659122786 *, const MethodInfo*))Comparison_1_Invoke_m1888033133_gshared)(__this, ___x0, ___y1, method)
// System.IAsyncResult System.Comparison`1<UnityEngine.Transform>::BeginInvoke(T,T,System.AsyncCallback,System.Object)
#define Comparison_1_BeginInvoke_m288418525(__this, ___x0, ___y1, ___callback2, ___object3, method) ((  Il2CppObject * (*) (Comparison_1_t375483973 *, Transform_t1659122786 *, Transform_t1659122786 *, AsyncCallback_t1369114871 *, Il2CppObject *, const MethodInfo*))Comparison_1_BeginInvoke_m3177996774_gshared)(__this, ___x0, ___y1, ___callback2, ___object3, method)
// System.Int32 System.Comparison`1<UnityEngine.Transform>::EndInvoke(System.IAsyncResult)
#define Comparison_1_EndInvoke_m472027272(__this, ___result0, method) ((  int32_t (*) (Comparison_1_t375483973 *, Il2CppObject *, const MethodInfo*))Comparison_1_EndInvoke_m651541983_gshared)(__this, ___result0, method)


text:
/* tslint:disable */
/* eslint-disable */

import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type FairOrganizerFollowButton_Test_QueryVariables = {
    id: string;
};
export type FairOrganizerFollowButton_Test_QueryResponse = {
    readonly fairOrganizer: {
        readonly " $fragmentRefs": FragmentRefs<"FairOrganizerFollowButton_fairOrganizer">;
    } | null;
};
export type FairOrganizerFollowButton_Test_Query = {
    readonly response: FairOrganizerFollowButton_Test_QueryResponse;
    readonly variables: FairOrganizerFollowButton_Test_QueryVariables;
};

/*
query FairOrganizerFollowButton_Test_Query(
  $id: String!
) {
  fairOrganizer(id: $id) {
    ...FairOrganizerFollowButton_fairOrganizer
    id
  }
}

fragment FairOrganizerFollowButton_fairOrganizer on FairOrganizer {
  slug
  name
  profile {
    id
    internalID
    isFollowed
  }
}
*/

const node: ConcreteRequest = (function(){
var v0 = [
  {
    "defaultValue": null,
    "kind": "LocalArgument",
    "name": "id",
    "type": "String!"
  }
],
v1 = [
  {
    "kind": "Variable",
    "name": "id",
    "variableName": "id"
  }
],
v2 = {
  "alias": null,
  "args": null,
  "kind": "ScalarField",
  "name": "id",
  "storageKey": null
};
return {
  "fragment": {
    "argumentDefinitions": (v0/*: any*/),
    "kind": "Fragment",
    "metadata": null,
    "name": "FairOrganizerFollowButton_Test_Query",
    "selections": [
      {
        "alias": null,
        "args": (v1/*: any*/),
        "concreteType": "FairOrganizer",
        "kind": "LinkedField",
        "name": "fairOrganizer",
        "plural": false,
        "selections": [
          {
            "args": null,
            "kind": "FragmentSpread",
            "name": "FairOrganizerFollowButton_fairOrganizer"
          }
        ],
        "storageKey": null
      }
    ],
    "type": "Query"
  },
  "kind": "Request",
  "operation": {
    "argumentDefinitions": (v0/*: any*/),
    "kind": "Operation",
    "name": "FairOrganizerFollowButton_Test_Query",
    "selections": [
      {
        "alias": null,
        "args": (v1/*: any*/),
        "concreteType": "FairOrganizer",
        "kind": "LinkedField",
        "name": "fairOrganizer",
        "plural": false,
        "selections": [
          {
            "alias": null,
            "args": null,
            "kind": "ScalarField",
            "name": "slug",
            "storageKey": null
          },
          {
            "alias": null,
            "args": null,
            "kind": "ScalarField",
            "name": "name",
            "storageKey": null
          },
          {
            "alias": null,
            "args": null,
            "concreteType": "Profile",
            "kind": "LinkedField",
            "name": "profile",
            "plural": false,
            "selections": [
              (v2/*: any*/),
              {
                "alias": null,
                "args": null,
                "kind": "ScalarField",
                "name": "internalID",
                "storageKey": null
              },
              {
                "alias": null,
                "args": null,
                "kind": "ScalarField",
                "name": "isFollowed",
                "storageKey": null
              }
            ],
            "storageKey": null
          },
          (v2/*: any*/)
        ],
        "storageKey": null
      }
    ]
  },
  "params": {
    "id": null,
    "metadata": {},
    "name": "FairOrganizerFollowButton_Test_Query",
    "operationKind": "query",
    "text": "query FairOrganizerFollowButton_Test_Query(\n  $id: String!\n) {\n  fairOrganizer(id: $id) {\n    ...FairOrganizerFollowButton_fairOrganizer\n    id\n  }\n}\n\nfragment FairOrganizerFollowButton_fairOrganizer on FairOrganizer {\n  slug\n  name\n  profile {\n    id\n    internalID\n    isFollowed\n  }\n}\n"
  }
};
})();
(node as any).hash = 'd6b1f282fc153c1ba563b4c3fa1934c7';
export default node;


text:
import os
from pyensembl import Locus, Genome

def data_path(name):
    """
    Return the absolute path to a file in the test/data directory.
    The name specified should be relative to test/data.
    """
    return os.path.join(os.path.dirname(__file__), "data", name)

# mapping of ensembl releases to transcript IDs for FOXP3-001
FOXP3_001_transcript_id = "ENST00000376207"

TP53_gene_id = "ENSG00000141510"

# beta-catenin interacting protein from the negative strand of chromosome 1
# URL: http://useast.ensembl.org/Homo_sapiens/Transcript/Sequence_cDNA?
#      db=core;g=ENSG00000178585;r=1:9848276-9910336;t=ENST00000377256
CTNNBIP1_004_transcript_id = "ENST00000377256"

# coding sequence for beta-catenin interacting protein (CTNNBIP1-004)
CTNNBIP1_004_CDS = "".join([
    "ATG",
    "AACCGCGAGGGAGCTCCCGGGAAGAGTCCGGAG",
    "GAGATGTACATTCAGCAGAAGGTCCGAGTGCTGCTCATGCTGCGGAAGATGGGATCAAAC",
    "CTGACAGCCAGCGAGGAGGAGTTCCTGCGCACCTATGCAGGGGTGGTCAACAGCCAGCTC",
    "AGCCAGCTGCCTCCGCACTCCATCGACCAGG",
    "GTGCAGAGGACGTGGTGATGGCGTTTTCCAGGTCGGAGACGGAAGACCGGAGGCAG",
    "TAG"
])

# 5' UTR for beta-catenin interacting protein (CTNNBIP1-004)
CTNNBIP1_004_UTR5 = "".join([
    "TGTGGGTGCAGGTTTCCTGGGCTTGCCAGACACACAGGGCGGCACCTTCCTACTTCTGCC",
    "CAGCCACAGCCCTCCCCTCACAGTTGAGCACCTGTTTGCCTGAAGTTAATTTCCAGAAGC",
    "AGGAGTCCCCAGAGCCAGGCAGGGGG"])

# 3' UTR for beta-catenin interacting protein (CTNNBIP1-004)
CTNNBIP1_004_UTR3 = \
    "CTGCAAAGCCCTTGGAACACCCTGGATGCTGTTGAGGGCCAAGAGATCTGTGTGGCTCC"

CTNNBIP1_004_locus = Locus("1", 9850659, 9878176, "-")

# properties of CTNNBIP1-004's exons copied from
# http://useast.ensembl.org/Homo_sapiens/Transcript/Exons?g=ENSG00000178585;
# r=1:9850659-9878176;redirect=no;t=ENST00000377256
CTTNNIP1_004_exon_ids = [
    'ENSE00001473268',
    'ENSE00001643659',
    'ENSE00001600669',
    'ENSE00001267940',
    'ENSE00001473265',
]

CTTNNIP1_004_exon_lengths = [
    37,
    85,
    120,
    91,
    118
]

#
# Information for EGFR from Ensembl website
# Date: March 25th, 2015
# Ensembl Release: 79
#
EGFR_001_name = "EGFR-001"
EGFR_001_transcript_id = "ENST00000275493"
EGFR_001_ccds_id = "CCDS5514"
EGFR_001_protein_id = "ENSP00000275493"
EGFR_001_protein_sequence = "".join([
    "MRPSGTAGAALLALLAALCPASRALEEKKVCQGTSNKLTQLGTFEDHFLSLQRMFNNCEVVLGNLEITYV",
    "QRNYDLSFLKTIQEVAGYVLIALNTVERIPLENLQIIRGNMYYENSYALAVLSNYDANKTGLKELPMRNL",
    "QEILHGAVRFSNNPALCNVESIQWRDIVSSDFLSNMSMDFQNHLGSCQKCDPSCPNGSCWGAGEENCQKL",
    "TKIICAQQCSGRCRGKSPSDCCHNQCAAGCTGPRESDCLVCRKFRDEATCKDTCPPLMLYNPTTYQMDVN",
    "PEGKYSFGATCVKKCPRNYVVTDHGSCVRACGADSYEMEEDGVRKCKKCEGPCRKVCNGIGIGEFKDSLS",
    "INATNIKHFKNCTSISGDLHILPVAFRGDSFTHTPPLDPQELDILKTVKEITGFLLIQAWPENRTDLHAF",
    "ENLEIIRGRTKQHGQFSLAVVSLNITSLGLRSLKEISDGDVIISGNKNLCYANTINWKKLFGTSGQKTKI",
    "ISNRGENSCKATGQVCHALCSPEGCWGPEPRDCVSCRNVSRGRECVDKCNLLEGEPREFVENSECIQCHP",
    "ECLPQAMNITCTGRGPDNCIQCAHYIDGPHCVKTCPAGVMGENNTLVWKYADAGHVCHLCHPNCTYGCTG",
    "PGLEGCPTNGPKIPSIATGMVGALLLLLVVALGIGLFMRRRHIVRKRTLRRLLQERELVEPLTPSGEAPN",
    "QALLRILKETEFKKIKVLGSGAFGTVYKGLWIPEGEKVKIPVAIKELREATSPKANKEILDEAYVMASVD",
    "NPHVCRLLGICLTSTVQLITQLMPFGCLLDYVREHKDNIGSQYLLNWCVQIAKGMNYLEDRRLVHRDLAA",
    "RNVLVKTPQHVKITDFGLAKLLGAEEKEYHAEGGKVPIKWMALESILHRIYTHQSDVWSYGVTVWELMTF",
    "GSKPYDGIPASEISSILEKGERLPQPPICTIDVYMIMVKCWMIDADSRPKFRELIIEFSKMARDPQRYLV",
    "IQGDERMHLPSPTDSNFYRALMDEEDMDDVVDADEYLIPQQGFFSSPSTSRTPLLSSLSATSNNSTVACI",
    "DRNGLQSCPIKEDSFLQRYSSDPTGALTEDSIDDTFLPVPEYINQSVPKRPAGSVQNPVYHNQPLNPAPS"
    "RDPHYQDPHSTAVGNPEYLNTVQPTCVNSTFDSPAHWAQKGSHQISLDNPDYQQDFFPKEAKPNGIFKGS"
    "TAENAEYLRVAPQSSEFIGA"
])

# GTF cropped from ftp://ftp.ensembl.org/pub/release-81/gtf/mus_musculus/
# Mus_musculus.GRCm38.81.gtf.gz via:
# grep "ENSMUSG00000017167" Mus_musculus.GRCm38.81.gtf

# Transcript FASTA cropped from ftp://ftp.ensembl.org/pub/release-81/
# fasta/mus_musculus/cdna/Mus_musculus.GRCm38.cdna.all.fa.gz via:
# grep "ENSMUSG00000017167" Mus_musculus.GRCm38.cdna.all.fa -A 50

# ncRNA FASTA cropped from ftp://ftp.ensembl.org/pub/release-81/
# fasta/mus_musculus/cdna/Mus_musculus.GRCm38.ncrna.fa.gz via:
# grep "ENSMUSG00000088969" Mus_musculus.GRCm38.ncrna.fa -A 2

# Protein FASTA cropped from ftp://ftp.ensembl.org/pub/release-81/fasta/
# mus_musculus/pep/Mus_musculus.GRCm38.pep.all.fa.gz via:
# grep "ENSMUSG00000017167" Mus_musculus.GRCm38.pep.all.fa -A 50

# Tested against:
# http://useast.ensembl.org/Mus_musculus/Gene/Summary?db=core;g=ENSMUSG00000017167

MOUSE_ENSMUSG00000017167_PATH = data_path(
    "mouse.ensembl.81.partial.ENSMUSG00000017167.gtf")
MOUSE_ENSMUSG00000017167_TRANSCRIPT_FASTA_PATH = data_path(
    "mouse.ensembl.81.partial.ENSMUSG00000017167.fa")
MOUSE_ENSMUSG00000088969_NCRNA_FASTA_PATH = data_path(
    "mouse.ensembl.81.partial.ncrna.ENSMUSG00000017167.fa")
MOUSE_ENSMUSG00000017167_PROTEIN_FASTA_PATH = data_path(
    "mouse.ensembl.81.partial.ENSMUSG00000017167.pep")

custom_mouse_genome_grcm38_subset = Genome(
    reference_name="GRCm38",
    annotation_name="_test_mouse_ensembl81_subset",
    gtf_path_or_url=MOUSE_ENSMUSG00000017167_PATH,
    transcript_fasta_paths_or_urls=[MOUSE_ENSMUSG00000017167_TRANSCRIPT_FASTA_PATH],
    protein_fasta_paths_or_urls=[MOUSE_ENSMUSG00000017167_PROTEIN_FASTA_PATH])

def setup_init_custom_mouse_genome():
    """
    If a unit test needs to start from a cleared cache, add this to the test
    setup.
    """
    custom_mouse_genome_grcm38_subset.clear_cache()
    custom_mouse_genome_grcm38_subset.index()


text:
import CSS_CLASS from '../constants/cssClass';
import ACTION_TYPE from '../constants/actionType';
import showSnippetModal from '../modal/showSnippetModal';

export default function () {
    let self = this;
    let contentAreasWrapper = self.contentAreasWrapper;

    contentAreasWrapper.on('click', `.${CSS_CLASS.TOOLBAR_COMPONENT_BOTTOM} .${CSS_CLASS.ADD_CONTENT}`, function (e) {
        e.preventDefault();

        let btn = $(this);
        let component = btn.closest(`.${CSS_CLASS.COMPONENT}`);
        let container = btn.closest(`.${CSS_CLASS.CONTAINER}`);
        showSnippetModal.call(self, component, ACTION_TYPE.AFTER, true, !container.hasClass(CSS_CLASS.SUB_CONTAINER));
    });
};