text:
package org.apache.syncope.core.misc.jexl;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.JexlException;
import org.apache.commons.jexl2.MapContext;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.syncope.common.lib.to.AbstractAttributableTO;
import org.apache.syncope.common.lib.to.AttrTO;
import org.apache.syncope.core.persistence.api.entity.Attributable;
import org.apache.syncope.core.persistence.api.entity.DerAttr;
import org.apache.syncope.core.persistence.api.entity.PlainAttr;
import org.apache.syncope.core.persistence.api.entity.VirAttr;
import org.apache.syncope.core.misc.DataFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JEXL reference is available.
 */
public final class JexlUtil {

    /**
     * Logger.
     *
     */
    private static final Logger LOG = LoggerFactory.getLogger(JexlUtil.class);

    private static final String[] IGNORE_FIELDS = { "password", "clearPassword", "serialVersionUID", "class" };

    private static JexlEngine jexlEngine;

    private static JexlEngine getEngine() {
        synchronized (LOG) {
            if (jexlEngine == null) {
                jexlEngine = new JexlEngine(new ClassFreeUberspectImpl(null), null, null, null);
                jexlEngine.setClassLoader(new EmptyClassLoader());
                jexlEngine.setCache(512);
                jexlEngine.setLenient(true);
                jexlEngine.setSilent(false);
            }
        }

        return jexlEngine;
    }

    public static boolean isExpressionValid(final String expression) {
        boolean result;
        try {
            getEngine().createExpression(expression);
            result = true;
        } catch (JexlException e) {
            LOG.error("Invalid jexl expression: " + expression, e);
            result = false;
        }

        return result;
    }

    public static String evaluate(final String expression, final JexlContext jexlContext) {
        String result = StringUtils.EMPTY;

        if (StringUtils.isNotBlank(expression) && jexlContext != null) {
            try {
                Expression jexlExpression = getEngine().createExpression(expression);
                Object evaluated = jexlExpression.evaluate(jexlContext);
                if (evaluated != null) {
                    result = evaluated.toString();
                }
            } catch (Exception e) {
                LOG.error("Error while evaluating JEXL expression: " + expression, e);
            }
        } else {
            LOG.debug("Expression not provided or invalid context");
        }

        return result;
    }

    public static JexlContext addFieldsToContext(final Object object, final JexlContext jexlContext) {
        JexlContext context = jexlContext == null ? new MapContext() : jexlContext;

        try {
            for (PropertyDescriptor desc : Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors()) {
                final Class<?> type = desc.getPropertyType();
                final String fieldName = desc.getName();

                if ((!fieldName.startsWith("pc"))
                        && (!ArrayUtils.contains(IGNORE_FIELDS, fieldName))
                        && (!Iterable.class.isAssignableFrom(type))
                        && (!type.isArray())) {
                    try {
                        final Method getter = desc.getReadMethod();

                        final Object fieldValue;

                        if (getter == null) {
                            final Field field = object.getClass().getDeclaredField(fieldName);
                            field.setAccessible(true);
                            fieldValue = field.get(object);
                        } else {
                            fieldValue = getter.invoke(object);
                        }

                        context.set(fieldName, fieldValue == null
                                ? StringUtils.EMPTY
                                : (type.equals(Date.class)
                                        ? DataFormat.format((Date) fieldValue, false)
                                        : fieldValue));

                        LOG.debug("Add field {} with value {}", fieldName, fieldValue);

                    } catch (Exception iae) {
                        LOG.error("Reading '{}' value error", fieldName, iae);
                    }
                }
            }
        } catch (IntrospectionException ie) {
            LOG.error("Reading class attributes error", ie);
        }

        return context;
    }

    public static JexlContext addAttrsToContext(final Collection<? extends PlainAttr> attrs,
            final JexlContext jexlContext) {

        JexlContext context = jexlContext == null
                ? new MapContext()
                : jexlContext;

        for (PlainAttr attr : attrs) {
            if (attr.getSchema() != null) {
                List<String> attrValues = attr.getValuesAsStrings();
                String expressionValue = attrValues.isEmpty()
                        ? StringUtils.EMPTY
                        : attrValues.get(0);

                LOG.debug("Add attribute {} with value {}", attr.getSchema().getKey(), expressionValue);

                context.set(attr.getSchema().getKey(), expressionValue);
            }
        }

        return context;
    }

    public static JexlContext addDerAttrsToContext(final Collection<? extends DerAttr> derAttrs,
            final Collection<? extends PlainAttr> attrs, final JexlContext jexlContext) {

        JexlContext context = jexlContext == null
                ? new MapContext()
                : jexlContext;

        for (DerAttr derAttr : derAttrs) {
            if (derAttr.getSchema() != null) {
                String expressionValue = derAttr.getValue(attrs);
                if (expressionValue == null) {
                    expressionValue = StringUtils.EMPTY;
                }

                LOG.debug("Add derived attribute {} with value {}", derAttr.getSchema().getKey(), expressionValue);

                context.set(derAttr.getSchema().getKey(), expressionValue);
            }
        }

        return context;
    }

    public static JexlContext addVirAttrsToContext(final Collection<? extends VirAttr> virAttrs,
            final JexlContext jexlContext) {

        JexlContext context = jexlContext == null
                ? new MapContext()
                : jexlContext;

        for (VirAttr virAttr : virAttrs) {
            if (virAttr.getSchema() != null) {
                List<String> attrValues = virAttr.getValues();
                String expressionValue = attrValues.isEmpty()
                        ? StringUtils.EMPTY
                        : attrValues.get(0);

                LOG.debug("Add virtual attribute {} with value {}", virAttr.getSchema().getKey(), expressionValue);

                context.set(virAttr.getSchema().getKey(), expressionValue);
            }
        }

        return context;
    }

    public static boolean evaluateMandatoryCondition(
            final String mandatoryCondition, final Attributable<?, ?, ?> attributable) {

        JexlContext jexlContext = new MapContext();
        addAttrsToContext(attributable.getPlainAttrs(), jexlContext);
        addDerAttrsToContext(attributable.getDerAttrs(), attributable.getPlainAttrs(), jexlContext);
        addVirAttrsToContext(attributable.getVirAttrs(), jexlContext);

        return Boolean.parseBoolean(evaluate(mandatoryCondition, jexlContext));
    }

    public static String evaluate(final String expression,
            final Attributable<?, ?, ?> attributable, final Collection<? extends PlainAttr> attributes) {

        final JexlContext jexlContext = new MapContext();
        JexlUtil.addAttrsToContext(attributes, jexlContext);
        JexlUtil.addFieldsToContext(attributable, jexlContext);

        // Evaluate expression using the context prepared before
        return evaluate(expression, jexlContext);
    }

    public static String evaluate(final String expression, final AbstractAttributableTO attributableTO) {
        final JexlContext context = new MapContext();

        addFieldsToContext(attributableTO, context);

        for (AttrTO plainAttr : attributableTO.getPlainAttrs()) {
            List<String> values = plainAttr.getValues();
            String expressionValue = values.isEmpty()
                    ? StringUtils.EMPTY
                    : values.get(0);

            LOG.debug("Add plain attribute {} with value {}", plainAttr.getSchema(), expressionValue);

            context.set(plainAttr.getSchema(), expressionValue);
        }
        for (AttrTO derAttr : attributableTO.getDerAttrs()) {
            List<String> values = derAttr.getValues();
            String expressionValue = values.isEmpty()
                    ? StringUtils.EMPTY
                    : values.get(0);

            LOG.debug("Add derived attribute {} with value {}", derAttr.getSchema(), expressionValue);

            context.set(derAttr.getSchema(), expressionValue);
        }
        for (AttrTO virAttr : attributableTO.getVirAttrs()) {
            List<String> values = virAttr.getValues();
            String expressionValue = values.isEmpty()
                    ? StringUtils.EMPTY
                    : values.get(0);

            LOG.debug("Add virtual attribute {} with value {}", virAttr.getSchema(), expressionValue);

            context.set(virAttr.getSchema(), expressionValue);
        }

        // Evaluate expression using the context prepared before
        return evaluate(expression, context);
    }

    /**
     * Private default constructor, for static-only classes.
     */
    private JexlUtil() {
    }
}


text:
package re.agiledesign.mp2.internal.expressions;

import static re.agiledesign.mp2.util.Util.getClassString;

import java.util.List;
import java.util.Map;

import re.agiledesign.mp2.exception.ScriptException;
import re.agiledesign.mp2.internal.AssignmentVisitor;
import re.agiledesign.mp2.internal.Scope;
import re.agiledesign.mp2.util.ArrayUtil;

public class IndexAccessExpression extends AccessExpression {
	private final Expression mThis;
	private final Expression mIndex;

	public IndexAccessExpression(final Expression aThis, final Expression aIndex) {
		mThis = aThis;
		mIndex = aIndex;
	}

	public void visit(final AssignmentVisitor aVisitor) {
		aVisitor.visitIndexAssignment(mThis, mIndex);
	}

	public Object execute(final Scope aScope) throws Exception {
		final Object _this = mThis.execute(aScope);

		if (_this == null) {
			throw new ScriptException("Null pointer indexing");
		}

		final Object index = mIndex.execute(aScope);
		if (_this.getClass().isArray()) {
			if (!(index instanceof Number)) {
				throw new ScriptException("Numeric index expected but found: " + getClassString(index));
			}

			// TODO: fix for float and higher than int precisions
			return ArrayUtil.atIndex(_this, ((Number) index).intValue());
		}

		if (_this instanceof List) {
			if (!(index instanceof Number)) {
				throw new ScriptException("Numeric index expected but found: " + getClassString(index));
			}

			// TODO: fix for float
			return ((List<?>) _this).get(((Number) index).intValue());
		}

		if (_this instanceof Map) {
			return ((Map<?, ?>) _this).get(index);
		}

		if (_this instanceof CharSequence) {
			if (!(index instanceof Number)) {
				throw new ScriptException("Numeric index expected but found: " + getClassString(index));
			}

			// TODO: fix for float
			return Character.valueOf(((CharSequence) _this).charAt(((Number) index).intValue()));
		}

		throw new ScriptException("Operator [] not applicable for types(" + getClassString(_this) + ", "
				+ getClassString(index) + ")");
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.dmmikkel.brisk.core.handler;

public class HandlerImpl
        extends Handler
{
    @Override
    public void handle()
    {
    }
}


text:
Комплект крепежа №1

                                    Винт m3x6
                            x5
                            Арт. 235

                                    Винт m3x6
                            x5
                            Арт. 235

                                    Винт m3x6
                            x5
                            Арт. 235

                                    Винт m3x6
                            x5
                            Арт. 235

                                    Винт m3x6
                            x5
                            Арт. 235

                                    Винт m3x6
                            x5
                            Арт. 235

                                    Винт m3x6
                            x5
                            Арт. 235

                                    Винт m3x6
                            x5
                            Арт. 235

                                    Винт m3x6
                            x5
                            Арт. 235

                                    Винт m3x6
                            x5
                            Арт. 235

                                    Винт m3x6
                            x5
                            Арт. 235

                                    Винт m3x6
                            x5
                            Арт. 235

                                    Винт m3x6
                            x5
                            Арт. 235

                                    Винт m3x6
                            x5
                            Арт. 235


text:
You can switch between staging and production environments via the admin menu mentioned below though. This means that data may have differences, as staging is copied from production once a week. However, being on staging means you can't break anything ;)

While on staging, the bottom tab bar of the app is purple. This lets us know which environment a screenshot was taken on.

### The admin menu

The admin menu is comprised of several sections:

- Useful actions, for example switching between staging and production
- Lab settings, which are toggles for specific features within Eigen
- Developer API settings (useful for web/platform developers)

To access it, do the following steps:

1. Run the app in the simulator or a real device.
   - Developer mode should be on in you are developing (`__DEV__` is true, or you are logged in with an artsy email). Make sure it is, by going to Profile > About. If "Version" has a one pixel purple line on the right, then you are good to go. If not, then you need to tap "Version" 7 times quickly, to enable developer mode.
2. Simulate a 'shake' event (^⌘Z), which will bring up the dev menu.
3. Choose the 'Debug JS Remotely' option, which should open Chrome.
4. In the new Chrome window, open the Developer Tools (⌘⌥J).

If you are an admin or using an artsy email, you can access the admin menu quickly:

- Just shake your device.
- Otherwise, go to Safari and type `artsy:///admin2` into the address bar (note the triple-slash).


text: export { default } from './NewArticleContainer';


text:
package org.apache.camel.component.mina;

import org.apache.camel.ExchangeTimedOutException;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;

import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

/**
 * Unit test with InOut however we want sometimes to not send a response.
 */
public class MinaInOutWithForcedNoResponseTest extends BaseMinaTest {

    int port1;
    int port2;

    @Test
    public void testResponse() throws Exception {
        Object out = template.requestBody("mina:tcp://localhost:" + port1 + "?sync=true", "Woodbine");
        assertEquals("Hello Chad", out);
    }

    @Test
    public void testNoResponseDisconnectOnNoReplyFalse() {
        RuntimeCamelException e = assertThrows(RuntimeCamelException.class,
                () -> template.requestBody("mina:tcp://localhost:" + port2 + "?sync=true&timeout=100", "London"),
                "Should throw an exception");
        assertIsInstanceOf(ExchangeTimedOutException.class, e.getCause());
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {

            public void configure() throws Exception {
                port1 = getPort();
                port2 = getNextPort();

                from("mina:tcp://localhost:" + port1 + "?sync=true")
                        .choice()
                        .when(body().isEqualTo("Woodbine"))
                        .transform(constant("Hello Chad"))
                        .otherwise()
                        .transform(constant(null));

                from("mina:tcp://localhost:" + port2 + "?sync=true&disconnectOnNoReply=false&noReplyLogLevel=OFF").choice()
                        .when(body().isEqualTo("Woodbine"))
                        .transform(constant("Hello Chad")).otherwise()
                        .transform(constant(null));
            }
        };
    }
}


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

  <groupId>com.vitalize</groupId>
  <artifactId>swole-dyn-admin</artifactId>
  <version>0.3.1-SNAPSHOT</version>

  <name>Swole Dyn Admin</name>
  <description>A bunch of things to make your Oracle ATG Commerce Dyn Admin swole</description>
  <packaging>jar</packaging>
  <url>http://github.com/vitalize/swole-dyn-admin</url>
  <scm>
    <url>http://github.com/vitalize/swole-dyn-admin</url>
  </scm>

  <!-- coveralls wants this -->
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <distributionManagement>
    <snapshotRepository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </snapshotRepository>
    <repository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
    </repository>
  </distributionManagement>

  <dependencies>

    <!-- there should ONLY be test dependencies in here, other than ATG
    we don't want to force anyone to have to add more jars.  Just keep it easy -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>1.10.19</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-library</artifactId>
      <version>1.3</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <defaultGoal>verify</defaultGoal>

    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-enforcer-plugin</artifactId>
        <version>1.4.1</version>
        <executions>
          <execution>
            <id>enforce-java</id>
            <goals>
              <goal>enforce</goal>
            </goals>
            <configuration>
              <rules>
                <requireJavaVersion>
                  <!-- ATG runs java 1.6 -->
                  <version>1.6</version>
                </requireJavaVersion>
              </rules>
            </configuration>
          </execution>
          <execution>
            <id>enforce-maven</id>
            <goals>
              <goal>enforce</goal>
            </goals>
            <configuration>
              <rules>
                <requireMavenVersion>
                  <version>3.3.9</version>
                </requireMavenVersion>
              </rules>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-pmd-plugin</artifactId>
        <version>3.7</version>
        <configuration>
          <linkXRef>false</linkXRef>
        </configuration>
      </plugin>

      <!-- COMPILATION OPTIONS -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <!-- java 6 for ATG 10 -->
          <source>1.6</source>
          <target>1.6</target>
          <compilerArgument>-Xlint:unchecked</compilerArgument>
        </configuration>
      </plugin>

      <!-- from https://maven.apache.org/plugins/maven-source-plugin/usage.html -->
      <plugin>
        <artifactId>maven-source-plugin</artifactId>
        <version>3.0.1</version>
        <executions>
          <execution>
            <id>attach-sources</id>
            <phase>verify</phase>
            <goals>
              <goal>jar-no-fork</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <!-- from https://maven.apache.org/plugins/maven-javadoc-plugin/usage.html -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.10.4</version>
        <executions>
          <execution>
            <id>attach-javadocs</id>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <!-- from http://maven.apache.org/plugins/maven-gpg-plugin/usage.html -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-gpg-plugin</artifactId>
        <version>1.6</version>
        <executions>
          <execution>
            <id>sign-artifacts</id>
            <phase>verify</phase>
            <goals>
              <goal>sign</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.sonatype.plugins</groupId>
        <artifactId>nexus-staging-maven-plugin</artifactId>
        <version>1.6.3</version>
        <extensions>true</extensions>
        <configuration>
          <serverId>ossrh</serverId>
          <nexusUrl>https://oss.sonatype.org/</nexusUrl>
          <autoReleaseAfterClose>true</autoReleaseAfterClose>
        </configuration>
      </plugin>

      <plugin>
        <groupId>pl.project13.maven</groupId>
        <artifactId>git-commit-id-plugin</artifactId>
        <version>2.2.2</version>
      </plugin>

      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>0.7.6.201602180812</version>
        <executions>
          <execution>
            <id>prepare-agent</id>
            <goals>
              <goal>prepare-agent</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.eluder.coveralls</groupId>
        <artifactId>coveralls-maven-plugin</artifactId>
        <version>4.3.0</version>
      </plugin>

    </plugins>

  </build>

  <profiles>

    <profile>
      <id>use-atg-stubs</id>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <dependencies>
        <dependency>
         <groupId>io.github.atg-stubs</groupId>
         <artifactId>atg-stubs</artifactId>
          <version>10.2.0-SNAPSHOT</version>
        </dependency>
      </dependencies>
      <repositories>
        <repository>
          <id>oss-sonatype</id>
          <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
          <snapshots>
            <updatePolicy>always</updatePolicy>
          </snapshots>
        </repository>
      </repositories>
    </profile>

    <profile>
      <!--
        Used when live dev'ing in an IDE to ref ACTUAL interfaces that may need to be contributed to ATG Stubs
        This profile only makes sense if you have an artifactory instance over at artifactory with the matching
        artifact id's..which you probably do not.  Open to suggestions.
      -->

      <id>use-atg-real</id>
      <dependencies>
        <dependency>
          <!--TODO: change to use the naming/versioning conventions of http://www.oracle.com/technetwork/indexes/samplecode/commerce-samples-2766867.html-->
          <groupId>com.oracle.atg</groupId>
          <artifactId>das</artifactId>
          <!-- this is 10.2 patch 3 in vitalize's maven repo-->
          <version>10.2.3</version>
        </dependency>

        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
          <version>2.5</version>
        </dependency>
      </dependencies>

      <repositories>
        <repository>
          <id>remote</id>
          <name>remote-repos</name>
          <url>http://artifactory/remote-repos</url>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
        </repository>
        <repository>
          <id>bbcom</id>
          <name>bbcom-repos</name>
          <url>http://artifactory/local-repos</url>
          <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
          </snapshots>
        </repository>
      </repositories>
    </profile>

  </profiles>

  <issueManagement>
    <system>github</system>
    <url>https://github.com/vitalize/swole-dyn-admin/issues</url>
  </issueManagement>

  <ciManagement>
    <system>TravisCI</system>
    <url>http://commerce-ci.dev/</url>
  </ciManagement>

  <licenses>
    <license>
      <name>Apache License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <developers>
    <developer>
      <id>VitalizeOSS</id>
      <name>Vitalize OSS</name>
      <email>oss@vitalize.com</email>
      <url>https://talkshowhost.net</url>
    </developer>
    <developer>
      <id>drdamour</id>
      <name>drdamour</name>
      <email>drdamour@gmail.com</email>
      <url>https://talkshowhost.net</url>
    </developer>
  </developers>

</project>


text:
import Em from 'ember';

export default {
  name: 'hightlightjs',
  initialize: function() {
    return Em.Route.reopen({
      renderTemplate: function() {
        this._super();
        return Em.run.next(this, function() {
          return $('pre code').each(function(i, e) {
            return hljs.highlightBlock(e);
          });
        });
      }
    });
  }
};


text:
$(document).ready(function(){
	$('#signUp').click(function() {

		$('#fader').fadeIn();
		$('#signUpBox').fadeIn();
		$('body').addClass('stop-scrolling');

        });
	$('#login').click(function(){

		$('#fader').fadeIn();
		$('#loginBox').fadeIn();
		$('body').addClass('stop-scrolling')

	});

	$('#loginCloseButton').click(function() {

		$('#fader').fadeOut();
		$('#loginBox').fadeOut();
		$('body').removeClass('stop-scrolling')

	});

	$('#signUpCloseButton').click(function() {

		$('#fader').fadeOut();
		$('#signUpBox').fadeOut();
		$('body').removeClass('stop-scrolling')

	});

	$('#switchToSignUp').click(function() {
		$('#loginBox').fadeOut();
		$('#signUpBox').fadeIn();
	});

	$('#switchToLogin').click(function() {
		$('#signUpBox').fadeOut();
		$('#loginBox').fadeIn();
	});

	$('.icon').mouseenter(function() {

		var whichDialog = "#" + this.id + "Dialog";
		if (!$(whichDialog).is(':visible')) {
  			$(whichDialog).show();
		};

	})

	$('.icon').mouseleave(function() {

		var whichDialog = "#" + this.id + "Dialog";
		if ($(whichDialog).is(':visible')) {
  			$(whichDialog).hide();
		};
	})

	$('#PASSION').click(function() {
		if($('#passionDef').is(':visible'))
			$('#passionDef').hide("fast");
		else {
			$('#passionDef').show("fast");
		}
	})
});


text:
'use strict';

require('should');

var Tc = require('./test-config');

describe('admin | Configuration', function () {
  it('should not accept undefined admin options', function () {
    (function () {
      require('../app/core.hub')(Tc.invalidAdminConfig);
    }).should.throw();
  });

  it('should accept properly defined admin options', function () {
    (function () {
      require('../app/core.hub')(Tc.validAdminConfig);
    }).should.not.throw();
  });
});

describe('admin.user | Public API', function () {
  var plz = require('../app/core.hub')(Tc.validAdminConfig),
      db = require('../app/utility.database')(plz);

  describe('plz.create.user()', function () {

    before(function (done) {
      db.getDatabase(function (error, database) {
        database.collection('user').count(function(error, count) {
          if(count >= 1) {
            database.collection('user').drop(function () {
              done();
            });
          } else {
            done();
          }
        });
      });
    });

    it('should insert a user with required fields present', function(done) {
      plz.create.user(Tc.validUser, function (error) {
        error.should.be.false;
        done();
      });
    });

    it('should return error if required fields are missing', function(done) {
      plz.create.user(Tc.invalidUser, function (error) {
        error.should.be.true;
        done();
      });
    });

    it('should not insert a user that already exists', function(done) {
      plz.create.user(Tc.validUser, function (error) {
        error.should.be.true;
        done();
      });
    });

    after(function (done) {
      db.getDatabase(function (error, database) {
        database.collection('user').drop(function () {
          done();
        });
      });
    });

  });

  describe('plz.get.user()', function () {

    before(function (done) {
      plz = require('../app/core.hub')(Tc.validAdminConfig);

      plz.create.user(Tc.validUser, function () {
        done();
      });
    });

    it('should find a user that exists', function (done) {
      plz.get.user({name: 'greg'}, function (error, result) {
        error.should.be.false;
        result.should.not.be.empty;

        // password should be stripped from user before return to client.
        for(var i = 0; i < result.length; i++) {
          result[i].password.hasOwnProperty('password').should.be.false;
        }

        done();
      });
    });

    it('should return an empty array if user does not exist', function (done) {
      plz.get.user({name: 'zanzabar'}, function (error, result) {
        error.should.be.false;
        result.data.should.be.eql([]);
        done();
      });
    });

    it('should callback error JSON if database fails', function (done) {
      var database = {
        getDocument: function (query, callback) {
          callback(true, { ok: false, message: 'Mocked Failure', data: null });
        }
      };

      require('../app/admin.user')(plz, database);

      plz.get.user({name: 'zanzabar'}, function (error, result) {
        error.should.be.true;
        result.should.be.an.Object;
        done();
      });
    });

    after(function (done) {
      db.getDatabase(function (error, database) {
        database.collection('user').drop(function () {
          done();
        });
      });
    });

  });

  describe('plz.remove.user()', function () {

    before(function (done) {
      plz = require('../app/core.hub')(Tc.validAdminConfig);

      plz.create.user(Tc.validUser, function () {
        done();
      });
    });

    it('should remove a user that exists', function (done) {
      plz.remove.user({name: 'greg'}, function (error, result) {
        error.should.be.false;
        result.data.ok.should.equal(1);
        result.data.n.should.equal(1);
        done();
      });
    });

    it('should return error if user does not exist', function (done) {
      plz.remove.user({name: 'doppio'}, function (error, result) {
        error.should.be.true;
        result.ok.should.be.false;
        (result.data === null).should.be.true;
        done();
      });
    });

    after(function (done) {
      db.getDatabase(function (error, database) {
        database.collection('user').drop(function () {
          done();
        });
      });
    });

  });

  describe('plz.edit.user()', function () {

    before(function (done) {
      plz = require('../app/core.hub')(Tc.validAdminConfig);

      plz.create.user(Tc.validUser, function () {
        done();
      });
    });

    it('should edit a user that exists', function (done) {
      var options = {
        criteria: {
          name: 'greg'
        },
        update: {
          name: 'doppio'
        }
      };

      plz.get.user({name: 'greg'}, function (error, result) {
        error.should.be.false;
        result.data[0].name.should.equal('greg');

        plz.edit.user(options, function (error, result) {
          error.should.be.false;
          result.data.updatedExisting.should.be.true;
          result.data.n.should.be.equal(1);

          plz.get.user({name: 'doppio'}, function (error, result) {
            result.data[0].name.should.equal('doppio');
            done();
          });
        });
      });
    });

    it('should return an error result if user does not exist', function (done) {
      plz.edit.user({email: 'majora@maskshop.com'}, function (error, result) {
        error.should.be.true;
        result.ok.should.be.false;
        (result.data === null).should.be.true;
        done();
      });
    });

    after(function (done) {
      db.getDatabase(function (error, database) {
        database.collection('user').drop(function () {
          done();
        });
      });
    });

  });

});

describe('admin.user | Private API', function () {
  var plz = {
    config: {
      admin: {
        roles: {
          user: true
        },
        required: {
          email: 'string'
        }
      }
    },
  };

  var adminUser = require('../app/admin.user')(plz);

  describe('prepareUserCreation()', function () {
    it('should callback an error if required role is not present', function (done) {
      var options = {
        role: 'prince-of-amber'
      };

      adminUser.prepareUserCreation(options, function (error, message) {
        error.should.be.true;
        message.should.be.a.String;
        done();
      });
    });

    it('should callback an error if required type is not valid', function (done) {
      var options = {
        role: 'user',
        email: 1000
      };

      // Mock validation
      plz.validate = {
        typeAs: function () { return false; }
      };

      adminUser.prepareUserCreation(options, function (error, message) {
        error.should.be.true;
        message.should.be.a.String;
        done();
      });
    });
  });
});


text:
set -e

# Constants
ACLOCAL="aclocal"
AUTOHEADER="autoheader"
AUTOMAKE="automake"
AUTOCONF="autoconf"

# Clean up autojunk
echo "cleaning up"
rm -rf .libs autom4te*.cache scripts aclocal.m4 configure config.log config.status .deps stamp-h1
rm -f otptool *.o *.la *.lo *.slo Makefile.in Makefile
rm -f mod_authn_otp-?.?.?.tar.gz
rm -f config.h*
rm -f TAGS tags

if [ "$1" = "-C" ]; then
    echo "cleanup done, exiting"
    exit
fi

# Create scripts directory
mkdir -p scripts

echo "running aclocal"
${ACLOCAL} ${ACLOCAL_ARGS} -I scripts

echo "running autoheader"
${AUTOHEADER}

echo "running automake"
${AUTOMAKE} --add-missing -c --foreign

echo "running autoconf"
${AUTOCONF} -f -i

if [ "$1" = "-c" ]; then
    echo "running configure"
    ./configure
fi


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/app_list/views/assistant/assistant_page_view.h"

#include <algorithm>
#include <utility>

#include "ash/app_list/app_list_view_delegate.h"
#include "ash/app_list/views/app_list_main_view.h"
#include "ash/app_list/views/app_list_view.h"
#include "ash/app_list/views/assistant/assistant_main_view.h"
#include "ash/app_list/views/contents_view.h"
#include "ash/app_list/views/search_box_view.h"
#include "ash/assistant/model/assistant_ui_model.h"
#include "ash/assistant/ui/assistant_ui_constants.h"
#include "ash/assistant/ui/assistant_view_delegate.h"
#include "ash/assistant/ui/colors/assistant_colors.h"
#include "ash/assistant/ui/colors/assistant_colors_util.h"
#include "ash/assistant/util/assistant_util.h"
#include "ash/constants/ash_features.h"
#include "ash/public/cpp/app_list/app_list_config.h"
#include "ash/public/cpp/assistant/assistant_state.h"
#include "ash/public/cpp/assistant/controller/assistant_ui_controller.h"
#include "ash/public/cpp/style/color_provider.h"
#include "ash/public/cpp/view_shadow.h"
#include "ash/search_box/search_box_constants.h"
#include "ash/shell.h"
#include "ash/strings/grit/ash_strings.h"
#include "ash/style/ash_color_id.h"
#include "base/bind.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/utf_string_conversions.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkTypes.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/compositor/animation_throughput_reporter.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_type.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/compositor_extra/shadow.h"
#include "ui/views/background.h"
#include "ui/views/layout/layout_manager_base.h"

namespace ash {

namespace {

// The min/max height of this page.
constexpr int kMaxHeightDip = 440;
constexpr int kMinHeightDip = 180;

// The height of the search box in this page.
constexpr int kSearchBoxHeightDip = 56;

// The shadow elevation value for the shadow of the Assistant search box.
constexpr int kShadowElevation = 12;

// Helpers ---------------------------------------------------------------------

int GetPreferredHeightForAppListState(AppListView* app_list_view) {
  auto app_list_view_state = app_list_view->app_list_state();
  switch (app_list_view_state) {
    case AppListViewState::kHalf:
    case AppListViewState::kFullscreenSearch:
      return kMaxHeightDip;
    default:
      return kMinHeightDip;
  }
}

bool IsInTabletMode() {
  // Shell might not has an instance in tests.
  return Shell::HasInstance() && Shell::Get()->IsInTabletMode();
}

// AssistantPageViewLayout -----------------------------------------------------

// A LayoutManager which calculates preferred size based on AppListState and
// always lays out its children to the calculated preferred size.
class AssistantPageViewLayout : public views::LayoutManagerBase {
 public:
  explicit AssistantPageViewLayout(AssistantPageView* assistant_page_view)
      : assistant_page_view_(assistant_page_view) {}

  AssistantPageViewLayout(const AssistantPageViewLayout&) = delete;
  AssistantPageViewLayout& operator=(const AssistantPageViewLayout&) = delete;
  ~AssistantPageViewLayout() override = default;

  // views::LayoutManagerBase:
  gfx::Size GetPreferredSize(const views::View* host) const override {
    DCHECK_EQ(assistant_page_view_, host);
    return assistant_page_view_->contents_view()
        ->AdjustSearchBoxSizeToFitMargins(
            gfx::Size(kPreferredWidthDip,
                      GetPreferredHeightForWidth(host, kPreferredWidthDip)));
  }

  int GetPreferredHeightForWidth(const views::View* host,
                                 int width) const override {
    DCHECK_EQ(assistant_page_view_, host);

    // Calculate |preferred_height| for AppListState.
    int preferred_height = GetPreferredHeightForAppListState(
        assistant_page_view_->contents_view()->app_list_view());

    // Respect |host|'s minimum size.
    preferred_height =
        std::max(preferred_height, host->GetMinimumSize().height());

    // Snap to |kMaxHeightDip| if |child| exceeds |preferred_height|.
    for (const auto* child : host->children()) {
      if (child->GetHeightForWidth(width) > preferred_height)
        return kMaxHeightDip;
    }

    return preferred_height;
  }

  views::ProposedLayout CalculateProposedLayout(
      const views::SizeBounds& size_bounds) const override {
    // Always use preferred size for layout. Our |host| will be clipped to give
    // the appearance of animating its bounds during AppListState transitions
    // and this will ensure that our content remains in the desired location.
    const gfx::Size size = GetPreferredSize(host_view());
    const int left = (host_view()->width() - size.width()) / 2;
    const int top = 0;
    const gfx::Rect bounds = gfx::Rect(left, top, size.width(), size.height());

    views::ProposedLayout proposed_layout;
    proposed_layout.host_size = host_view()->size();
    for (auto* child : host_view()->children()) {
      proposed_layout.child_layouts.push_back(views::ChildLayout{
          child, child->GetVisible(), bounds, views::SizeBounds()});
    }

    return proposed_layout;
  }

 private:
  AssistantPageView* const assistant_page_view_;
};

}  // namespace

// AssistantPageView -----------------------------------------------------------

AssistantPageView::AssistantPageView(
    AssistantViewDelegate* assistant_view_delegate)
    : assistant_view_delegate_(assistant_view_delegate),
      min_height_dip_(kMinHeightDip) {
  InitLayout();

  if (AssistantController::Get())  // May be |nullptr| in tests.
    assistant_controller_observation_.Observe(AssistantController::Get());

  if (AssistantUiController::Get())  // May be |nullptr| in tests.
    AssistantUiController::Get()->GetModel()->AddObserver(this);

  if (Shell::HasInstance())  // Shell might not has an instance in tests.
    tablet_mode_observation_.Observe(Shell::Get()->tablet_mode_controller());
}

AssistantPageView::~AssistantPageView() {
  if (AssistantUiController::Get())
    AssistantUiController::Get()->GetModel()->RemoveObserver(this);
}

gfx::Size AssistantPageView::GetMinimumSize() const {
  return gfx::Size(kPreferredWidthDip, min_height_dip_);
}

void AssistantPageView::OnBoundsChanged(const gfx::Rect& prev_bounds) {
  // The clip-rect set for page state animations needs to be reset when the
  // bounds change because page size change invalidates the previous bounds.
  // This allows content to properly follow target bounds w/ screen rotations.
  if (prev_bounds.size() != bounds().size())
    layer()->SetClipRect(gfx::Rect());

  if (!IsDrawn())
    return;

  // Until Assistant UI is closed, the view may grow in height but not shrink.
  min_height_dip_ = std::max(min_height_dip_, GetContentsBounds().height());
}

void AssistantPageView::RequestFocus() {
  if (!AssistantUiController::Get())  // May be |nullptr| in tests.
    return;

  if (assistant_main_view_)
    assistant_main_view_->RequestFocus();
}

void AssistantPageView::GetAccessibleNodeData(ui::AXNodeData* node_data) {
  View::GetAccessibleNodeData(node_data);

  // A valid role must be set prior to setting the name.
  node_data->role = ax::mojom::Role::kPane;
  node_data->SetName(l10n_util::GetStringUTF16(IDS_ASH_ASSISTANT_WINDOW));
}

void AssistantPageView::ChildPreferredSizeChanged(views::View* child) {
  MaybeUpdateAppListState(child->GetHeightForWidth(width()));
  PreferredSizeChanged();
}

void AssistantPageView::ChildVisibilityChanged(views::View* child) {
  if (!child->GetVisible())
    return;

  MaybeUpdateAppListState(child->GetHeightForWidth(width()));
}

void AssistantPageView::VisibilityChanged(views::View* starting_from,
                                          bool is_visible) {
  if (starting_from == this && !is_visible)
    min_height_dip_ = kMinHeightDip;
}

void AssistantPageView::OnMouseEvent(ui::MouseEvent* event) {
  switch (event->type()) {
    case ui::ET_MOUSE_PRESSED:
      // Prevents closing the AppListView when a click event is not handled.
      event->StopPropagation();
      break;
    default:
      break;
  }
}

void AssistantPageView::OnGestureEvent(ui::GestureEvent* event) {
  switch (event->type()) {
    case ui::ET_GESTURE_TAP:
    case ui::ET_GESTURE_DOUBLE_TAP:
    case ui::ET_GESTURE_LONG_PRESS:
    case ui::ET_GESTURE_LONG_TAP:
    case ui::ET_GESTURE_TWO_FINGER_TAP:
      // Prevents closing the AppListView when a tap event is not handled.
      event->StopPropagation();
      break;
    default:
      break;
  }
}

void AssistantPageView::OnWillBeShown() {
  // Our preferred size may require a change in AppListState in order to ensure
  // that the AssistantPageView renders fully on screen w/o being clipped. We do
  // this in OnWillBeShown(), as opposed to waiting for OnShown(), so that the
  // AppListState change animation can run in sync with page change animations.
  MaybeUpdateAppListState(GetPreferredSize().height());
}

void AssistantPageView::OnAnimationStarted(AppListState from_state,
                                           AppListState to_state) {
  // Animation is only needed when transitioning to/from Assistant.
  if (from_state != AppListState::kStateEmbeddedAssistant &&
      to_state != AppListState::kStateEmbeddedAssistant) {
    UpdatePageBoundsForState(to_state, contents_view()->GetContentsBounds(),
                             contents_view()->GetSearchBoxBounds(to_state));
    return;
  }

  const gfx::Rect contents_bounds = contents_view()->GetContentsBounds();

  const gfx::Rect from_rect =
      GetPageBoundsForState(from_state, contents_bounds,
                            contents_view()->GetSearchBoxBounds(from_state));

  const gfx::Rect to_rect = GetPageBoundsForState(
      to_state, contents_bounds, contents_view()->GetSearchBoxBounds(to_state));

  if (from_rect == to_rect)
    return;

  const int to_radius = contents_view()
                            ->GetSearchBoxView()
                            ->GetSearchBoxBorderCornerRadiusForState(to_state);

  // We are going to give the appearance of animating from |from_rect| to
  // |to_rect| using clip-rect animations. First, set bounds immediately to
  // target bounds...
  SetBoundsRect(to_rect);

  // ...but set the clip-rect to |from_rect| so that the user doesn't perceive
  // the change in bounds.
  gfx::Rect clip_rect = from_rect;
  clip_rect -= to_rect.OffsetFromOrigin();
  layer()->SetClipRect(clip_rect);

  // Animate the layer's clip-rect to the target bounds to give the appearance
  // of a bounds animation.
  {
    auto settings = contents_view()->CreateTransitionAnimationSettings(layer());

    ui::AnimationThroughputReporter reporter(
        settings->GetAnimator(),
        metrics_util::ForSmoothness(base::BindRepeating([](int value) {
          base::UmaHistogramPercentage(
              "Ash.Assistant.AnimationSmoothness.ResizeAssistantPageView",
              value);
        })));

    layer()->SetClipRect(gfx::Rect(to_rect.size()));

    // Also animate corner radius for the view.
    // NOTE: This changes the shadow's corner radius immediately while |this|'s
    // corner radius changes gradually. This should be fine because this will be
    // unnoticeable to most users.
    view_shadow_->SetRoundedCornerRadius(to_radius);
  }

  // Animate the shadow's bounds through transform.
  {
    gfx::Transform transform;
    transform.Translate(from_rect.origin() - to_rect.origin());
    transform.Scale(static_cast<float>(from_rect.width()) / to_rect.width(),
                    static_cast<float>(from_rect.height()) / to_rect.height());
    view_shadow_->shadow()->layer()->SetTransform(transform);

    auto settings = contents_view()->CreateTransitionAnimationSettings(
        view_shadow_->shadow()->layer());
    view_shadow_->shadow()->layer()->SetTransform(gfx::Transform());
  }
}

gfx::Size AssistantPageView::GetPreferredSearchBoxSize() const {
  return gfx::Size(kPreferredWidthDip, kSearchBoxHeightDip);
}

void AssistantPageView::AnimateYPosition(AppListViewState target_view_state,
                                         const TransformAnimator& animator,
                                         float default_offset) {
  // Assistant page view may host native views for its content. The native view
  // hosts use view to widget coordinate conversion to calculate the native view
  // bounds, and thus depend on the view transform values.
  // Make sure the view is laid out before starting the transform animation so
  // native views are not placed according to interim, animated page transform
  // value.
  layer()->GetAnimator()->StopAnimatingProperty(
      ui::LayerAnimationElement::TRANSFORM);
  if (needs_layout())
    Layout();

  animator.Run(default_offset, layer());
  animator.Run(default_offset, view_shadow_->shadow()->shadow_layer());
}

void AssistantPageView::UpdatePageOpacityForState(AppListState state,
                                                  float search_box_opacity,
                                                  bool restore_opacity) {
  layer()->SetOpacity(search_box_opacity);
}

gfx::Rect AssistantPageView::GetPageBoundsForState(
    AppListState state,
    const gfx::Rect& contents_bounds,
    const gfx::Rect& search_box_bounds) const {
  // If transitioning to/from |kStateApps|, Assistant bounds will be animating
  // to/from |search_box_bounds|.
  if (state == AppListState::kStateApps)
    return search_box_bounds;

  // If transitioning to/from Assistant, Assistant bounds will be animating
  // to/from the bounds of the page associated with the specified |state|.
  if (state != AppListState::kStateEmbeddedAssistant) {
    return contents_view()
        ->GetPageView(contents_view()->GetPageIndexForState(state))
        ->GetPageBoundsForState(state, contents_bounds, search_box_bounds);
  }

  gfx::Rect bounds =
      gfx::Rect(gfx::Point(contents_bounds.x(), search_box_bounds.y()),
                GetPreferredSize());
  bounds.Offset((contents_bounds.width() - bounds.width()) / 2, 0);
  return bounds;
}

void AssistantPageView::OnAssistantControllerDestroying() {
  if (AssistantUiController::Get())  // May be |nullptr| in tests.
    AssistantUiController::Get()->GetModel()->RemoveObserver(this);

  if (AssistantController::Get()) {
    // May be |nullptr| in tests.
    DCHECK(assistant_controller_observation_.IsObservingSource(
        AssistantController::Get()));
    assistant_controller_observation_.Reset();
  }
}

void AssistantPageView::OnUiVisibilityChanged(
    AssistantVisibility new_visibility,
    AssistantVisibility old_visibility,
    absl::optional<AssistantEntryPoint> entry_point,
    absl::optional<AssistantExitPoint> exit_point) {
  if (!assistant_view_delegate_)
    return;

  if (new_visibility != AssistantVisibility::kVisible) {
    min_height_dip_ = kMinHeightDip;
    return;
  }

  // Assistant page will get focus when widget shown.
  if (GetWidget() && GetWidget()->IsActive())
    RequestFocus();

  const bool prefer_voice =
      assistant_view_delegate_->IsTabletMode() ||
      AssistantState::Get()->launch_with_mic_open().value_or(false);
  if (!assistant::util::IsVoiceEntryPoint(entry_point.value(), prefer_voice)) {
    NotifyAccessibilityEvent(ax::mojom::Event::kAlert, true);
  }
}

void AssistantPageView::OnTabletModeStarted() {
  UpdateBackground(/*in_tablet_mode=*/true);
}

void AssistantPageView::OnTabletModeEnded() {
  UpdateBackground(/*in_tablet_mode=*/false);
}

void AssistantPageView::OnThemeChanged() {
  views::View::OnThemeChanged();

  UpdateBackground(IsInTabletMode());
}

void AssistantPageView::InitLayout() {
  // Use a solid color layer. The color is set in OnThemeChanged().
  SetPaintToLayer(ui::LAYER_SOLID_COLOR);
  layer()->SetFillsBoundsOpaquely(false);

  view_shadow_ = std::make_unique<ViewShadow>(this, kShadowElevation);
  view_shadow_->SetRoundedCornerRadius(
      kSearchBoxBorderCornerRadiusSearchResult);

  SetLayoutManager(std::make_unique<AssistantPageViewLayout>(this));

  // |assistant_view_delegate_| could be nullptr in test.
  if (!assistant_view_delegate_)
    return;

  assistant_main_view_ = AddChildView(
      std::make_unique<AssistantMainView>(assistant_view_delegate_));
}

void AssistantPageView::UpdateBackground(bool in_tablet_mode) {
  // Blur
  if (features::IsProductivityLauncherEnabled() ||
      (in_tablet_mode && features::IsDarkLightModeEnabled() &&
       features::IsBackgroundBlurEnabled())) {
    layer()->SetBackgroundBlur(ColorProvider::kBackgroundBlurSigma);
    layer()->SetBackdropFilterQuality(ColorProvider::kBackgroundBlurQuality);
  } else {
    layer()->SetBackgroundBlur(0.0f);
    layer()->SetBackdropFilterQuality(0.0f);
  }

  // Color
  const auto* color_provider =
      GetWidget() ? GetWidget()->GetColorProvider() : nullptr;
  // ColorProvide might be nullptr in tests or this function is triggered before
  // `this` is added to the view hierarchy.
  if (color_provider && features::IsProductivityLauncherEnabled()) {
    layer()->SetColor(color_provider->GetColor(kColorAshShieldAndBase80));
  } else if (color_provider && features::IsDarkLightModeEnabled()) {
    layer()->SetColor(color_provider->GetColor(
        features::IsBackgroundBlurEnabled() ? kColorAshShieldAndBase80
                                            : kColorAshShieldAndBase95));
  } else {
    layer()->SetColor(SK_ColorWHITE);
  }
}

void AssistantPageView::MaybeUpdateAppListState(int child_height) {
  auto* app_list_view = contents_view()->app_list_view();
  auto* widget = app_list_view->GetWidget();

  // |app_list_view| may not be initialized.
  if (!widget || !widget->IsVisible())
    return;

  // Update app list view state for |assistant_page_view_|.
  // Embedded Assistant Ui only has two sizes. The only state change is from
  // |kPeeking| to |kFullscreenAllApps| state.
  if (app_list_view->app_list_state() != AppListViewState::kPeeking)
    return;

  if (child_height > GetPreferredHeightForAppListState(app_list_view))
    app_list_view->SetState(AppListViewState::kFullscreenSearch);
}

BEGIN_METADATA(AssistantPageView, views::View)
END_METADATA

}  // namespace ash


text:
package com.intellij.psi;

import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.psi.xml.XmlComment;
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase;

public class XmlPsiTest extends LightJavaCodeInsightFixtureTestCase {

  public void testXmlComment() {
    PsiFile file = myFixture.configureByText(XmlFileType.INSTANCE, "<!-- foo -->");
    XmlComment element = (XmlComment)file.findElementAt(0).getParent();
    assertEquals(" foo ", element.getCommentText());
  }
}


text:
package org.broadleafcommerce.core.web.api.wrapper;

import org.broadleafcommerce.common.BroadleafEnumerationType;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * This is a JAXB wrapper around HibuProduct.

 */
@XmlRootElement(name = "BroadleafEnumerationTypeWrapper")
@XmlAccessorType(value = XmlAccessType.FIELD)
public class BroadleafEnumerationTypeWrapper extends BaseWrapper implements APIWrapper<BroadleafEnumerationType> {

    @XmlElement
    protected String friendlyName;

    @XmlElement
    protected String type;

    @Override
    public void wrapDetails(BroadleafEnumerationType model, HttpServletRequest request) {
        if (model == null) return;
        this.friendlyName = model.getFriendlyType();
        this.type = model.getType();
    }

    @Override
    public void wrapSummary(BroadleafEnumerationType model, HttpServletRequest request) {
        wrapDetails(model, request);
    }
}


text:
title: Blog Number 4
layout: post
author: daniel.hutchings
permalink: /blog-number-4/
source-id: 1i73g1k1Gcr_5nymjg1mKULPM04mC_66G2ZbVGilHwRY
published: true
---

    Title:
    Starting My Blog Using GitHub

    Date:
    04/09/16

    Starting point:

Started making a spreadsheet

    Target for this lesson?
    To learn how to use advanced spreadsheet

    Did I reach my target?
(add details to "Lesson Review")
    I finished the spreadsheet

    Lesson Review

    How did I learn? What strategies were effective?

    I followed the instructions carefully and used logic to find out what to do.

    What limited my learning? Which habits do I need to work on?

    I need to listen more carefully to the exact details so it works properly.

    What will I change for next time? How will I improve my learning?

    I will use this lesson to aid my learning in future.


text:
using System;
using System.Linq;
using System.Linq.Expressions;

using JetBrains.Annotations;

using NUnit.Framework;

#pragma warning disable CA1822 // Mark members as static

namespace CodeJam.Reflection
{
	[TestFixture]
	public class InfoOfTest
	{
		[Test]
		public void ExtractingPropertyInfo1()
		{
			var expected = typeof(User).GetProperty(nameof(User.Name));

			var info1 = InfoOf.Property(() => new User().Name);
			var info2 = InfoOf.Property<User>(u => u.Name!);
			var info3 = InfoOf.Property<User, string>(u => u.Name!);
			var info4 = InfoOf<User>.Property(u => u.Name);

			Assert.AreEqual(expected, info1, "#1");
			Assert.AreEqual(expected, info2, "#2");
			Assert.AreEqual(expected, info3, "#3");
			Assert.AreEqual(expected, info4, "#4");
		}

		[Test]
		public void ExtractingPropertyInfo2()
		{
			var expected = typeof(User).GetProperty(nameof(User.Age));

			var info1 = InfoOf.Property(() => new User().Age);
			var info2 = InfoOf.Property<User>(u => u.Age);
			var info3 = InfoOf.Property<User, int>(u => u.Age);
			var info4 = InfoOf<User>.Property(u => u.Age);

			Assert.AreEqual(expected, info1, "#1");
			Assert.AreEqual(expected, info2, "#2");
			Assert.AreEqual(expected, info3, "#3");
			Assert.AreEqual(expected, info4, "#4");
		}

		[Test]
		public void ExtractingFieldInfo()
		{
			var expected = typeof(User).GetField(nameof(User.LastName));

			var info1 = InfoOf.Field(() => new User().LastName);
			var info2 = InfoOf.Field<User>(u => u.LastName!);
			var info3 = InfoOf.Field<User, string>(u => u.LastName!);
			var info4 = InfoOf<User>.Field(u => u.LastName);

			Assert.AreEqual(expected, info1, "#1");
			Assert.AreEqual(expected, info2, "#2");
			Assert.AreEqual(expected, info3, "#3");
			Assert.AreEqual(expected, info4, "#4");
		}

		[Test]
		public void ExtractingCtor()
		{
			var expected = typeof(User).GetConstructors().First(c => c.GetParameters().Length != 0);
			var ctor1 = InfoOf.Constructor(() => new User("", ""));
			var ctor2 = InfoOf<User>.Constructor(() => new User("", ""));

			Assert.AreEqual(expected, ctor1, "#1");
			Assert.AreEqual(expected, ctor2, "#2");
		}

		[Test]
		public void ExtractingDefaultClassCtor()
		{
			var expected = typeof(User).GetConstructors().First(c => c.GetParameters().Length == 0);
			var ctor1 = InfoOf.Constructor<User>();
			var ctor2 = InfoOf.Constructor(() => new User());
			var ctor3 = InfoOf<User>.Constructor(() => new User());
			var ctor4 = Expression.New(typeof(User)).Constructor;

			NAssert.NotNull(ctor1, "#1");
			NAssert.NotNull(ctor2, "#2");
			NAssert.NotNull(ctor3, "#3");
			NAssert.NotNull(ctor4, "#4");

			Assert.AreEqual(expected, ctor1);
			Assert.AreEqual(expected, ctor2);
			Assert.AreEqual(expected, ctor3);
			Assert.AreEqual(expected, ctor4);
		}

		[Test]
		public void ExtractingDefaultStructCtor()
		{
			var ctor1 = InfoOf.Constructor<Guid>();
			var ctor2 = InfoOf.Constructor(() => new Guid());
			var ctor3 = InfoOf<Guid>.Constructor(() => new Guid());
			var ctor4 = Expression.New(typeof(Guid)).Constructor;

			Assert.Null(ctor1, "#1");
			Assert.Null(ctor2, "#2");
			Assert.Null(ctor3, "#3");
			Assert.Null(ctor4, "#4");
		}

		[Test]
		public void ExtractingMethod1()
		{
			var expected = typeof(User).GetMethod(nameof(User.Debug));
			var method1 = InfoOf.Method(() => new User().Debug());
			var method2 = InfoOf.Method<User>(u => u.Debug());
			var method3 = InfoOf<User>.Method(u => u.Debug());

			Assert.AreEqual(expected, method1, "#1");
			Assert.AreEqual(expected, method2, "#2");
			Assert.AreEqual(expected, method3, "#3");
		}

		[Test]
		public void ExtractingMethod2()
		{
			var expected = typeof(User).GetMethod(nameof(User.GetAge));
			var method1 = InfoOf.Method(() => new User().GetAge());
			var method2 = InfoOf.Method<User>(u => u.GetAge());
			var method3 = InfoOf.Method<User, int>(u => u.GetAge());
			var method4 = InfoOf<User>.Method(u => u.GetAge());

			Assert.AreEqual(expected, method1, "#1");
			Assert.AreEqual(expected, method2, "#2");
			Assert.AreEqual(expected, method3, "#3");
			Assert.AreEqual(expected, method4, "#4");
		}

		[Test]
		public void ExtractingPropertyGetMethod()
		{
			var expected = typeof(User).GetProperty("Name")!.GetGetMethod();
			var method1 = InfoOf.Method(() => new User().Name);
			var method2 = InfoOf.Method<User>(u => u.Name!);
			var method3 = InfoOf.Method<User, string>(u => u.Name!);
			var method4 = InfoOf<User>.Method(u => u.Name);

			Assert.AreEqual(expected, method1, "#1");
			Assert.AreEqual(expected, method2, "#2");
			Assert.AreEqual(expected, method3, "#3");
			Assert.AreEqual(expected, method4, "#4");
		}

		#region Inner types
		[UsedImplicitly(ImplicitUseTargetFlags.WithMembers)]
		public class User
		{
			public string? Name { get; set; }
			public string? LastName;
			public int Age { get; set; }

			public User()
			{
			}

			public User(string name, string lastName)
			{
				Name = name;
				LastName = lastName;
			}

			public void Debug()
			{
			}

			public int GetAge() => 0;
		}
		#endregion
	}
}


text:
Este proyecto diseñado para los estudiantes de la célula de Desarrollo de Software de CIRT consiste en la elaboración de un sitio web à-la-Reddit/Hacker News, es decir, una página donde los usuarios pueden agregar URLs de interés
y los mismos puedan tanto puntearlas como comentarlas.

[Volver al menú principal](https://github.com/aitbw/cirt_projects)

## Objetivos

Para que esta aplicación sea considerada _production-ready_, la misma debe cumplir con los siguientes parámetros:

1. Permitir a los usuarios poder crear una cuenta en el servicio y poder iniciar/cerrar sesión
2. Solo los usuarios que estén registrados podrán ejecutar acciones sobre el sitio web
3. Los usuarios registrados podrán agregar links al sitio web, los cuales deberán llevar los siguientes atributos:
   * Título
   * Link
   * Hora y fecha de publicación
   * Autor

4. El autor de una publicación será la única persona en capacidad de borrar dicho link
5. Los links pueden ser comentados y se tendrán en cuenta los siguientes atributos:
   * Autor
   * Hora y fecha de publicación
   * Hora y fecha de edición
   * Comentario

6. Un _feed_ principal que permita visualizar los links agregados recientemente, ordenados por su puntuación (de mayor a menor)
7. Visualizar todos las publicaciones que ha hecho un usuario

## Consideraciones adicionales

Al momento de evaluar el proyecto, se tendrán en cuenta los siguientes aspectos:

* Arquitectura MVC
* Código ordenado y comprensible
* El código sigue los estándares establecidos por la comunidad (Depende del lenguaje que se utilice para su desarrollo)
* Diseño de la interfaz gráfica
* Experiencia del usuario
* Documentación
* Uso de principios KISS y DRY

## Opcionales

Si el estudiante así lo desea, puede implementar alguno de los siguientes puntos, lo cual tendrá peso sobre su calificación final:

* Publicar links por categoría
* Filtros para visualizar solo las publicaciones que le interesen al usuario

## Limitaciones

Ninguna más allá del tiempo establecido para elaborar este proyecto.

## Inspiración

Pueden usar [Reddit](https://www.reddit.com/) y [Hacker News](https://news.ycombinator.com/) como referencia para el desarrollo de su aplicación.


text:
import { ContentChildren, Directive, ElementRef, Input, Renderer } from '@angular/core';
import { NavigationEnd, Router } from '../router';
import { containsTree } from '../url_tree';
import { RouterLink, RouterLinkWithHref } from './router_link';
export class RouterLinkActive {
    /**
     * @internal
     */
    constructor(router, element, renderer) {
        this.router = router;
        this.element = element;
        this.renderer = renderer;
        this.classes = [];
        this.routerLinkActiveOptions = { exact: false };
        this.subscription = router.events.subscribe(s => {
            if (s instanceof NavigationEnd) {
                this.update();
            }
        });
    }
    ngAfterContentInit() {
        this.links.changes.subscribe(s => this.update());
        this.linksWithHrefs.changes.subscribe(s => this.update());
        this.update();
    }
    set routerLinkActive(data) {
        if (Array.isArray(data)) {
            this.classes = data;
        }
        else {
            this.classes = data.split(' ');
        }
    }
    ngOnChanges(changes) { this.update(); }
    ngOnDestroy() { this.subscription.unsubscribe(); }
    update() {
        if (!this.links || !this.linksWithHrefs)
            return;
        const currentUrlTree = this.router.parseUrl(this.router.url);
        const isActiveLinks = this.reduceList(currentUrlTree, this.links);
        const isActiveLinksWithHrefs = this.reduceList(currentUrlTree, this.linksWithHrefs);
        this.classes.forEach(c => this.renderer.setElementClass(this.element.nativeElement, c, isActiveLinks || isActiveLinksWithHrefs));
    }
    reduceList(currentUrlTree, q) {
        return q.reduce((res, link) => res || containsTree(currentUrlTree, link.urlTree, this.routerLinkActiveOptions.exact), false);
    }
}
/** @nocollapse */
RouterLinkActive.decorators = [
    { type: Directive, args: [{ selector: '[routerLinkActive]' },] },
];
/** @nocollapse */
RouterLinkActive.ctorParameters = [
    { type: Router, },
    { type: ElementRef, },
    { type: Renderer, },
];
/** @nocollapse */
RouterLinkActive.propDecorators = {
    'links': [{ type: ContentChildren, args: [RouterLink,] },],
    'linksWithHrefs': [{ type: ContentChildren, args: [RouterLinkWithHref,] },],
    'routerLinkActiveOptions': [{ type: Input },],
    'routerLinkActive': [{ type: Input },],
};
//# sourceMappingURL=router_link_active.js.map


text:
#include "TrainingDataReader.h"
#include <assert.h>
#include <iosfwd>
#include <algorithm>
#include <iostream>

//-------------------------------------------------------------------------

namespace BPN
{
    TrainingDataReader::TrainingDataReader( std::string const& filename, int32_t numInputs, int32_t numOutputs )
        : m_filename( filename )
        , m_numInputs( numInputs )
        , m_numOutputs( numOutputs )
    {
        assert( !filename.empty() && m_numInputs > 0 && m_numOutputs > 0 );
    }

    bool TrainingDataReader::ReadData()
    {
        assert( !m_filename.empty() );

        std::fstream inputFile;
        inputFile.open( m_filename, std::ios::in );

        if ( inputFile.is_open() )
        {
            std::string line;

            // Read data
            //-------------------------------------------------------------------------

            int32_t const totalValuesToRead = m_numInputs + m_numOutputs;

            while ( !inputFile.eof() )
            {
                std::getline( inputFile, line );
                if ( line.length() > 2 )
                {
                    m_entries.push_back( TrainingEntry() );
                    TrainingEntry& entry = m_entries.back();

                    char* cstr = new char[line.size() + 1];
                    strcpy_s( cstr, line.size() + 1, line.c_str() );

                    // Read values
                    int i = 0;
                    char* nextToken = nullptr;
                    char* pToken = strtok_s( cstr, ",", &nextToken );

                    while ( pToken != nullptr && i < totalValuesToRead )
                    {
                        if ( i < m_numInputs )
                        {
                            entry.m_inputs.push_back( atof( pToken ) );
                        }
                        else
                        {
                            double const outputValue = atof( pToken );
                            entry.m_expectedOutputs.push_back( (int32_t) outputValue );
                        }

                        pToken = strtok_s( nullptr, ",", &nextToken );
                        i++;
                    }
                }
            }

            inputFile.close();

            if ( !m_entries.empty() )
            {
                CreateTrainingData();
            }

            std::cout << "Input file: " << m_filename << "\nRead complete: " << m_entries.size() << " inputs loaded" << std::endl;
            return true;
        }
        else
        {
            std::cout << "Error Opening Input File: " << m_filename << std::endl;
            return false;
        }
    }

    void TrainingDataReader::CreateTrainingData()
    {
        assert( !m_entries.empty() );

        std::random_shuffle( m_entries.begin(), m_entries.end() );

        // Training set
        int32_t const numEntries = (int32_t) m_entries.size();
        int32_t const numTrainingEntries  = (int32_t) ( 0.6 * numEntries );
        int32_t const numGeneralizationEntries = (int32_t) ( ceil( 0.2 * numEntries ) );

        int32_t entryIdx = 0;
        for ( ; entryIdx < numTrainingEntries; entryIdx++ )
        {
            m_data.m_trainingSet.push_back( m_entries[entryIdx] );
        }

        // Generalization set
        for ( ; entryIdx < numTrainingEntries + numGeneralizationEntries; entryIdx++ )
        {
            m_data.m_generalizationSet.push_back( m_entries[entryIdx] );
        }

        // Validation set
        for ( ; entryIdx < numEntries; entryIdx++ )
        {
            m_data.m_validationSet.push_back( m_entries[entryIdx] );
        }
    }
}


text:
import os
import collections

from confu.results import BuildResult
from confu.results import CompilationResult
from confu.utils import qualified_type

class CollectionResult(BuildResult):
    def __init__(self, subdir, name, objects, libraries=None, filename=None, rule=None, extra_outputs=list(), extra_deps=list(), variables=dict()):
        super(CollectionResult, self).__init__()
        if not isinstance(subdir, str):
            raise TypeError("Unsupported type of subdir argument: string expected")
        if subdir not in ['bin', 'lib', 'out', 'build']:
            raise ValueError("Unsupported value {subdir} of subdir argument: 'bin', 'lib', 'out', or 'build' expected".format(
                subdir=subdir))
        if not isinstance(name, str):
            raise TypeError("Unsupported type of name argument: string expected")
        if not isinstance(objects, collections.Iterable):
            raise TypeError("Unsupported type of objects argument: list, tuple, or iterable expected")
        if not isinstance(objects, list):
            objects = list(objects)
        for i, obj in enumerate(objects):
            if not isinstance(obj, (CompilationResult, CollectionResult)):
                raise TypeError("Unsupported type {type} of object #{index}: CompilationResult expected".format(
                    type=qualified_type(obj), index=i))
        self.subdir = subdir
        self.name = name
        self.filename = filename if filename is not None else name
        self.objects = objects
        self.libraries = libraries
        self.rule = rule
        self.extra_outputs = extra_outputs
        self.extra_deps = extra_deps
        self.variables = variables

    def get_target_path(self):
        import confu.globals
        return os.path.join(confu.globals.root_dir, self.subdir, self.filename)

    def generate(self, ninja):
        import confu.globals
        if self.generated:
            return self.get_target_path()

        object_files = list()
        for object in self.objects:
            assert isinstance(object, (CompilationResult, CollectionResult))
            object.generate(ninja)
            if isinstance(object, CompilationResult):
                object_files.append(object.get_object_path())
            else:
                object_files.append(object.get_target_path())

        library_files = list()
        implicit_deps = list(self.extra_deps)
        if self.libraries:
            for library in self.libraries:
                assert isinstance(library, (CollectionResult, str))
                if isinstance(library, str):
                    library_files.append("-l" + library)
                else:
                    library.generate(ninja)
                    library_files.append(library.get_target_path())
                    implicit_deps.append(library.get_target_path())

        target_path = self.get_target_path()
        variables = self.variables.copy()
        variables["path"] = os.path.join(self.subdir, self.filename)
        variables["ldlibs"] = " ".join(library_files + ["$ldlibs"])
        ninja.build(target_path, self.rule, object_files,
                    implicit=implicit_deps,
                    implicit_outputs=[os.path.join(confu.globals.root_dir, self.subdir, extra_output)
                                      for extra_output in self.extra_outputs],
                    order_only=confu.globals.build_ninja_path, variables=variables)

        self.generated = True
        return target_path


text:
/**
* A sample code for http://code.google.com/p/vfs-s3
*/

/**
* Basic ops
*/

// Create bucket
FileSystemManager fsManager = VFS.getManager();
FileObject dir = fsManager.resolveFile("s3://vfs-test-bucket");
dir.createFolder();

// Upload file to S3
FileObject src = fsManager.resolveFile(new File("/etc/shells").getAbsolutePath());
FileObject dest = fsManager.resolveFile("s3://vfs-test-bucket/shells");
dest.copyFrom(src, Selectors.SELECT_SELF);

// Download from S3
FileObject remote_file = fsManager.resolveFile("s3://vfs-bucket/backup.zip");
File local_file = File.createTempFile("vfs.", ".s3");
FileOutputStream out = new FileOutputStream(local_file);
InputStream in = remote_file.getContent().getInputStream();
IOUtils.copy(in, out);

// Delete bucket
FileObject dir = fsManager.resolveFile("s3://vfs-bucket");
dir.delete();

/*
* ACL (Access Control List) extension
*/
FileOperationProvider operationProvider = (FileOperationProvider) new AclOperationsProvider();
String[] schemes = {"s3"};
fsManager.addOperationProvider(schemes, operationProvider);

// Get ACL
IAclGetter aclGetter = (IAclGetter)remote_file.getFileOperations().getOperation(IAclGetter.class);
aclGetter.process();
fileAcl = aclGetter.getAcl();
if (aclGetter.canRead(Acl.Group.GUEST)) {
    System.out.println("Anyone can read s3://vfs-bucket/backup.zip");
}

// Permit all authorized users to read remote_file
fileAcl.allow(Acl.Group.AUTHORIZED, Acl.Right.READ);
IAclSetter aclSetter = (IAclSetter)remote_file.getFileOperations().getOperation(IAclSetter.class);
aclSetter.setAcl(fileAcl);
aclSetter.process();


text:
from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement

from django.utils.translation import ugettext_lazy as _

from ..forms.schoolyear import SchoolYearForm

from .generic import FormView

class SchoolYearView(FormView):
    form_class = SchoolYearForm
    title = _('Switch school year')

    def get_message(self, form):
        return _('You now work with school year {}.').format(self.request.school_year)

    def get_form_kwargs(self):
        kwargs = super(SchoolYearView, self).get_form_kwargs()
        kwargs['initial'] = {'school_year': self.request.school_year}
        return kwargs

    def form_valid(self, form):
        self.request.school_year = form.cleaned_data['school_year']
        return super(SchoolYearView, self).form_valid(form)


text:
This is the sample application for the [*Ruby on Rails Tutorial*](http://railstutorial.org/)
by [Michael Hart](http://michaelhartl.com)


text:
(function () {
    'use strict';

    var parser = require('./parser'),
        brDescriptor = require('./extensions/br-descriptor'),
        brContent = require('./extensions/br-content'),
        brInclude = require('./extensions/br-include');

    module.exports = Braces;

    function Braces(extensions) {
        this.parser = parser;

        this.extensions = {};

        // Set up builtin "extensions":
        this.extensions['br-descriptor'] = new brDescriptor(this);
        this.extensions['br-content'] = new brContent(this);
        this.extensions['br-include'] = new brInclude(this);

        // Declare after builtins to allow for overriding.
        var self = this;
        Object.keys(extensions || {}).forEach(function (key) {
            self.extensions[key] = new extensions[key](self);
        });
    }

    Braces.prototype.generateSyntaxTree = function generateSyntaxTree(markup) {
        firePreGenerate(this.extensions);
        return this.parser.parse(markup);
    };

    Braces.prototype.evaluateSyntaxTree = function evaluateSyntaxTree(syntaxTree) {
        var self = this;
        var result = syntaxTree.map(function processNode(node) {
            var extension = self.extensions[node.handler];
            if (!extension || !extension.parseNode) {
                throw new Error('No parseNode function found for handler ' + node.handler);
            }

            return extension.parseNode(node);
        }).join('');

        firePostEvaluate(this.extensions);
        return result;
    };

    Braces.prototype.parse = function parse(markup) {
        return this.evaluateSyntaxTree(this.generateSyntaxTree(markup));
    };

    Braces.prototype.isDescriptor = function isDescriptor(obj) {
        return Boolean((typeof obj == 'object') &&
               ((obj.left && obj.operator && obj.right) ||
                (obj.tag || obj.id || obj.attrs || obj.classes)));
    };

    Braces.prototype.generateTagsForDescriptor = function generateTagsForDescriptor(descriptor) {
        if (!descriptor.operator) {
            return baseGenerateTags(descriptor);
        }

        switch (descriptor.operator) {
        case '>':
            var left = baseGenerateTags(descriptor.left),
                right = generateTagsForDescriptor(descriptor.right);

            return {
                open: left.open + right.open,
                close: right.close + left.close
            };
        default:
            throw new Error('No handler for operator ' + descriptor.operator);
        }
    };

    function baseGenerateTags(descriptor) {
        descriptor.tag = descriptor.tag || 'div';

        var openTag = '<' + descriptor.tag,
            closeTag;

        if (descriptor.id) {
            openTag += ' id="' + descriptor.id + '"';
        }

        if (descriptor.classes && descriptor.classes.length > 0) {
            openTag += ' class="' + descriptor.classes.join(' ') + '"';
        }

        if (descriptor.attrs && descriptor.attrs.length > 0) {
            openTag += ' ' + descriptor.attrs.join(' ');
        }

        openTag += '>';

        closeTag = '</' + descriptor.tag + '>';

        return {
            open: openTag,
            close: closeTag
        };
    }

    function firePreGenerate(extensions) {
        Object.keys(extensions).forEach(function (key) {
            var extension = extensions[key];
            if (extension && extension.preGenerate) {
                extension.preGenerate();
            }
        });
    }

    function firePostEvaluate(extensions) {
        Object.keys(extensions).forEach(function (key) {
            var extension = extensions[key];
            if (extension && extension.postEvaluate) {
                extension.postEvaluate();
            }
        });
    }
}());


text:
#pragma once
#include <aws/mq/MQ_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace MQ
{
namespace Model
{
  enum class DayOfWeek
  {
    NOT_SET,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
  };

namespace DayOfWeekMapper
{
AWS_MQ_API DayOfWeek GetDayOfWeekForName(const Aws::String& name);

AWS_MQ_API Aws::String GetNameForDayOfWeek(DayOfWeek value);
} // namespace DayOfWeekMapper
} // namespace Model
} // namespace MQ
} // namespace Aws


text:
using System;

using Android.App;
using Android.OS;
using Android.Runtime;
using Plugin.CurrentActivity;
using XWeather.Constants;

namespace XWeather.Droid
{
	/// <summary>
	/// Custom extension of the base Android.App.Application class, in order to add properties which
	/// are global to the application, but not persisted as settings.
	/// </summary>
	[Application (Icon = "@mipmap/icon", Label = "XWeather", Theme = "@style/WeatherTheme", AllowBackup = true
#if DEBUG
				  , Debuggable = true
#endif
				 )]
	[MetaData ("com.google.android.geo.API_KEY", Value = PrivateKeys.GoogleMapsApiKey)]
	public class XWeatherApp : Application, Application.IActivityLifecycleCallbacks
	{
		/// <summary>
		/// Base constructor which must be implemented if it is to successfully inherit from the Application class.
		/// </summary>
		/// <param name="handle"></param>
		/// <param name="transfer"></param>
		public XWeatherApp (IntPtr handle, JniHandleOwnership transfer)
			: base (handle, transfer)
		{
		}

		public override void OnCreate ()
		{
			base.OnCreate ();

			RegisterActivityLifecycleCallbacks (this);

			//Bootstrap.Run (Context, this);
		}

		public override void OnTerminate ()
		{
			base.OnTerminate ();
			UnregisterActivityLifecycleCallbacks (this);
		}

		public void OnActivityCreated (Activity activity, Bundle savedInstanceState)
		{
			CrossCurrentActivity.Current.Activity = activity;
		}

		public void OnActivityDestroyed (Activity activity)
		{
		}

		public void OnActivityPaused (Activity activity)
		{
		}

		public void OnActivityResumed (Activity activity)
		{
			CrossCurrentActivity.Current.Activity = activity;
		}

		public void OnActivitySaveInstanceState (Activity activity, Bundle outState)
		{
		}

		public void OnActivityStarted (Activity activity)
		{
			CrossCurrentActivity.Current.Activity = activity;
		}

		public void OnActivityStopped (Activity activity)
		{
		}
	}
}


text:
import { connect } from 'react-redux';
import { injectIntl } from 'react-intl';

import {
  currentSectorSelector,
  isSidebarEditActiveSelector,
} from 'store/selectors/base.selectors';
import {
  isCurrentSectorSaved,
  isViewingSharedSector,
} from 'store/selectors/sector.selectors';
import {
  getCurrentEntity,
  getCurrentEntityType,
  getCurrentEntityChildren,
} from 'store/selectors/entity.selectors';

import {
  saveEntityEdit,
  saveSector,
  deleteEntity,
} from 'store/actions/entity.actions';
import {
  activateSidebarEdit,
  deactivateSidebarEdit,
} from 'store/actions/sidebar.actions';
import { openSectorExpansion } from 'store/actions/sector.actions';

import EntityActions from './entity-actions';

const mapStateToProps = state => ({
  isSaved: isCurrentSectorSaved(state),
  isShared: isViewingSharedSector(state),
  currentSector: currentSectorSelector(state),
  entity: getCurrentEntity(state),
  entityType: getCurrentEntityType(state),
  isSidebarEditActive: isSidebarEditActiveSelector(state),
  entityChildren: getCurrentEntityChildren(state),
});

const mapDispatchToProps = (dispatch, props) => ({
  activateSidebarEdit: () => dispatch(activateSidebarEdit()),
  deactivateSidebarEdit: () => dispatch(deactivateSidebarEdit()),
  saveEntityEdit: () => dispatch(saveEntityEdit(props.intl)),
  saveSector: () => dispatch(saveSector(props.intl)),
  deleteEntity: () => dispatch(deleteEntity(props.intl)),
  openSectorExpansion: () => dispatch(openSectorExpansion()),
});

export default injectIntl(
  connect(mapStateToProps, mapDispatchToProps)(EntityActions),
);


text:
class Reports::CommentsController < ::CommentsController

  def create
    @comment = @model.create_comment!(params[:comment])
    if @comment.save
      flash[:notice] = 'Comment was successfully created.'
    else
      flash[:error] = 'Comment wasn\'t created.'
    end
    redirect_to :back
  end

end


text:
""" read hostname into a python
variable and print it to the user
"""

import subprocess

proc = subprocess.Popen(['/bin/hostname'], stdout=subprocess.PIPE)
(stdout, stderr) = proc.communicate()

print "Hostname = %s" % stdout.strip()


text:
class Base {
  superMethod() {
    return 'good';
  }
}

class Sub extends Base {
  superMethod() {
    return 'bad';
  }

  #privateMethod() {
    return super.superMethod();
  }

  publicMethod() {
    return this.#privateMethod();
  }
}

expect((new Sub()).publicMethod()).toEqual('good');


text:
eprocurementApp.service('Article', function Article($http, $routeParams) {
    var articleService = this;

    return {
        getData : function(catalog) {
            return $http.get('/eprocurement/articles/get/'+catalog.catalogNodeId);
        }
    };
});


text:
<?php

namespace App\ECommerceBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Kf\KitBundle\Doctrine\Fixtures\AbstractFixture;
use App\ECommerceBundle\Entity as Entity;
use App\StoreBundle\DataFixtures\ORM\LoadStore;

class LoadProduct extends AbstractFixture  implements DependentFixtureInterface
{
    protected $entityClass = Entity\Product::CLASS;

    /**
     * @{@inheritdoc}
     */
    public function getDependencies()
    {
        return [
            LoadStore::CLASS,
            LoadCategory::CLASS,
            LoadColor::CLASS
        ];
    }
}


text:
namespace Dinobenz.Deployment
{
    partial class frmMain
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.trvSource = new System.Windows.Forms.TreeView();
            this.cboSource = new System.Windows.Forms.ComboBox();
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.cbxlDestination = new System.Windows.Forms.CheckedListBox();
            this.btnDeploy = new System.Windows.Forms.Button();
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.toolStripProgressBar1 = new System.Windows.Forms.ToolStripProgressBar();
            this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
            this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
            this.btnCancel = new System.Windows.Forms.Button();
            this.lblVersion = new System.Windows.Forms.Label();
            this.groupBox1.SuspendLayout();
            this.menuStrip1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.statusStrip1.SuspendLayout();
            this.SuspendLayout();
            //
            // groupBox1
            //
            this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox1.Controls.Add(this.trvSource);
            this.groupBox1.Controls.Add(this.cboSource);
            this.groupBox1.Location = new System.Drawing.Point(12, 27);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(569, 166);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Source";
            //
            // trvSource
            //
            this.trvSource.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.trvSource.CheckBoxes = true;
            this.trvSource.Location = new System.Drawing.Point(7, 47);
            this.trvSource.Name = "trvSource";
            this.trvSource.Size = new System.Drawing.Size(556, 113);
            this.trvSource.TabIndex = 2;
            //
            // cboSource
            //
            this.cboSource.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.cboSource.FormattingEnabled = true;
            this.cboSource.Location = new System.Drawing.Point(7, 20);
            this.cboSource.Name = "cboSource";
            this.cboSource.Size = new System.Drawing.Size(556, 21);
            this.cboSource.TabIndex = 0;
            this.cboSource.SelectedIndexChanged += new System.EventHandler(this.cboSource_SelectedIndexChanged);
            //
            // menuStrip1
            //
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.fileToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Size = new System.Drawing.Size(592, 24);
            this.menuStrip1.TabIndex = 1;
            this.menuStrip1.Text = "menuStrip1";
            //
            // fileToolStripMenuItem
            //
            this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.exitToolStripMenuItem});
            this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
            this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
            this.fileToolStripMenuItem.Text = "File";
            //
            // exitToolStripMenuItem
            //
            this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
            this.exitToolStripMenuItem.Size = new System.Drawing.Size(92, 22);
            this.exitToolStripMenuItem.Text = "Exit";
            this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
            //
            // groupBox2
            //
            this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox2.Controls.Add(this.cbxlDestination);
            this.groupBox2.Location = new System.Drawing.Point(12, 199);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(569, 106);
            this.groupBox2.TabIndex = 1;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Destination";
            //
            // cbxlDestination
            //
            this.cbxlDestination.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.cbxlDestination.CheckOnClick = true;
            this.cbxlDestination.FormattingEnabled = true;
            this.cbxlDestination.Location = new System.Drawing.Point(7, 20);
            this.cbxlDestination.Name = "cbxlDestination";
            this.cbxlDestination.Size = new System.Drawing.Size(556, 79);
            this.cbxlDestination.TabIndex = 0;
            //
            // btnDeploy
            //
            this.btnDeploy.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnDeploy.Location = new System.Drawing.Point(424, 311);
            this.btnDeploy.Name = "btnDeploy";
            this.btnDeploy.Size = new System.Drawing.Size(75, 23);
            this.btnDeploy.TabIndex = 2;
            this.btnDeploy.Text = "Deploy";
            this.btnDeploy.UseVisualStyleBackColor = true;
            this.btnDeploy.Click += new System.EventHandler(this.btnDeploy_Click);
            //
            // statusStrip1
            //
            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripProgressBar1,
            this.toolStripStatusLabel1});
            this.statusStrip1.Location = new System.Drawing.Point(0, 344);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.Size = new System.Drawing.Size(592, 22);
            this.statusStrip1.TabIndex = 3;
            this.statusStrip1.Text = "statusStrip1";
            //
            // toolStripProgressBar1
            //
            this.toolStripProgressBar1.Name = "toolStripProgressBar1";
            this.toolStripProgressBar1.Size = new System.Drawing.Size(100, 16);
            //
            // toolStripStatusLabel1
            //
            this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
            this.toolStripStatusLabel1.Size = new System.Drawing.Size(475, 17);
            this.toolStripStatusLabel1.Spring = true;
            this.toolStripStatusLabel1.Text = "toolStripStatusLabel1";
            this.toolStripStatusLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // backgroundWorker1
            //
            this.backgroundWorker1.WorkerReportsProgress = true;
            this.backgroundWorker1.WorkerSupportsCancellation = true;
            this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
            this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
            this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
            //
            // btnCancel
            //
            this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnCancel.Location = new System.Drawing.Point(505, 311);
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.Size = new System.Drawing.Size(75, 23);
            this.btnCancel.TabIndex = 4;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
            //
            // lblVersion
            //
            this.lblVersion.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.lblVersion.AutoSize = true;
            this.lblVersion.Location = new System.Drawing.Point(12, 320);
            this.lblVersion.Name = "lblVersion";
            this.lblVersion.Size = new System.Drawing.Size(52, 13);
            this.lblVersion.TabIndex = 5;
            this.lblVersion.Text = "lblVersion";
            //
            // frmMain
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(592, 366);
            this.Controls.Add(this.lblVersion);
            this.Controls.Add(this.btnCancel);
            this.Controls.Add(this.statusStrip1);
            this.Controls.Add(this.btnDeploy);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.menuStrip1);
            this.MainMenuStrip = this.menuStrip1;
            this.Name = "frmMain";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Deployment";
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            this.groupBox1.ResumeLayout(false);
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.statusStrip1.ResumeLayout(false);
            this.statusStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.MenuStrip menuStrip1;
        private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.Button btnDeploy;
        private System.Windows.Forms.ComboBox cboSource;
        private System.Windows.Forms.TreeView trvSource;
        private System.Windows.Forms.CheckedListBox cbxlDestination;
        private System.Windows.Forms.StatusStrip statusStrip1;
        private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar1;
        private System.ComponentModel.BackgroundWorker backgroundWorker1;
        private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
        private System.Windows.Forms.Button btnCancel;
        private System.Windows.Forms.Label lblVersion;
    }
}