text:
from django.urls import path

from . import views

app_name = "userprofile"

urlpatterns = [
    path("", views.SelfProfileDetailView.as_view(), name="profile"),
    path("edit/", views.ProfileUpdateView.as_view(), name="edit_profile"),
    path("skills/", views.SelfSkillsView.as_view(), name="profile_skills"),
    path(
        "skills/<int:skill_pk>", views.SelfSkillsView.as_view(), name="profile_skills"
    ),
    path(
        "skills/category/<int:pk>",
        views.SkillsCategoryView.as_view(),
        name="profile_skills_category",
    ),
    path("<int:pk>/", views.ProfileDetailView.as_view(), name="profile_by_id"),
    path("<int:pk>/skills/", views.SkillsView.as_view(), name="profile_skills_by_id"),
    path(
        "<int:pk>/skills/<int:skill_pk>",
        views.SkillsView.as_view(),
        name="profile_skills_by_id",
    ),
    path(
        "<int:pk>/skills/approve/",
        views.ApproveSkillAPIView.as_view(),
        name="approve_skill_api_endpoint",
    ),
]


text:
package com.facebook.watchman.environment;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;

import com.facebook.watchman.util.TemporaryPaths;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;

public class FileFinderTest {
  @Rule
  public TemporaryPaths tmp = new TemporaryPaths();

  @Test
  public void combine() {
    Object[] result = FileFinder.combine(null, "foo", null).toArray();
    Arrays.sort(result);
    Assert.assertArrayEquals(
        new String[] { "foo" },
        result);

    result = FileFinder.combine(
        ImmutableSet.<String>of(),
        "foo",
        ImmutableSet.of(".exe", ".com", ".bat")).toArray();
    Arrays.sort(result);
    Assert.assertArrayEquals(
        new String[] { "foo.bat", "foo.com", "foo.exe" },
        result);

    result = FileFinder.combine(
        ImmutableSet.<String>of("lib", ""),
        "foo",
        null).toArray();
    Arrays.sort(result);
    Assert.assertArrayEquals(
        new String[] { "foo", "libfoo" },
        result);
  }

  @Test
  public void firstMatchInPath() throws IOException {
    Path fee = tmp.newFolder("fee");
    Path fie = tmp.newFolder("fie");
    tmp.newFile("fee/foo");
    tmp.newFile("fie/foo");
    ImmutableList<Path> searchPath = ImmutableList.of(fie, fee);
    Optional<Path> result = FileFinder.getOptionalFile("foo", searchPath);
    Assert.assertTrue(result.isPresent());
    Assert.assertEquals(fie.resolve("foo"), result.get());
  }

  @Test
  public void matchAny() throws IOException {
    Path fee = tmp.newFolder("fee");
    tmp.newFile("fee/foo");
    Path fie = tmp.newFolder("fie");
    tmp.newFile("fie/bar");

    ImmutableSet<String> names = ImmutableSet.of(
        "foo",
        "bar",
        "baz");
    Optional<Path> result =
        FileFinder.getOptionalFile(
            names,
            ImmutableSortedSet.of(fee));
    Assert.assertTrue(result.isPresent());
    Assert.assertEquals(fee.resolve("foo"), result.get());

    result = FileFinder.getOptionalFile(
        names,
        ImmutableSortedSet.of(fie));
    Assert.assertTrue(result.isPresent());
    Assert.assertEquals(fie.resolve("bar"), result.get());
  }

  @Test
  public void noMatch() throws IOException {
    Path fee = tmp.newFolder("fee");
    tmp.newFile("fee/foo");
    Path fie = tmp.newFolder("fie");
    tmp.newFile("fie/bar");

    Optional<Path> result =
        FileFinder.getOptionalFile(
            "baz",
            ImmutableSortedSet.of(fee, fie));
    Assert.assertFalse(result.isPresent());
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.protobee.guice.multiscopes.example.scopes;

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

import com.google.inject.BindingAnnotation;

/**
 * Specifies the Galaxy multiscope.
 *
 * @author Daniel Murphy (daniel@dmurph.com)
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@BindingAnnotation
public @interface Galaxy {

}


text:
MongoDB\BSON\UTCDateTime::__set_state() requires "milliseconds" integer or numeric string field
--FILE--
<?php

require_once __DIR__ . '/../utils/basic.inc';

echo throws(function() {
    MongoDB\BSON\UTCDateTime::__set_state(['milliseconds' => 1.0]);
}, 'MongoDB\Driver\Exception\InvalidArgumentException'), "\n";

?>
===DONE===
<?php exit(0); ?>
--EXPECT--
OK: Got MongoDB\Driver\Exception\InvalidArgumentException
MongoDB\BSON\UTCDateTime initialization requires "milliseconds" integer or numeric string field
===DONE===


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<type language="gradle" name="org.gradle.api.tasks.compile.GroovyForkOptions" version="3.0" superType="org.gradle.api.tasks.compile.BaseForkOptions">
    <description> Fork options for Groovy compilation. Only take effect if GroovyCompileOptions.fork
 is true.

</description>
</type>


text:
package com.autelhome.multiroom.playlist;

import com.autelhome.multiroom.song.Song;
import com.autelhome.multiroom.song.SongRepresentationFactory;
import com.theoryinpractise.halbuilder.api.RepresentationFactory;
import com.theoryinpractise.halbuilder.standard.StandardRepresentationFactory;
import org.junit.Test;

import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.Arrays;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ZonePlaylistRepresentationFactoryTest {
    private static final String MY_ZONE = "myZone";
    private final UriInfo uriInfo = getUriInfo();
    private final SongRepresentationFactory songRepresentationFactory = new SongRepresentationFactory(uriInfo);
    private final PlaylistSongRepresentationFactory playlistSongRepresentationFactory = new PlaylistSongRepresentationFactory(uriInfo, songRepresentationFactory);
    private final ZonePlaylistRepresentationFactory testSubject = new ZonePlaylistRepresentationFactory(uriInfo, playlistSongRepresentationFactory);

    public static final String BASE_URI = "http://myserver:1234/api";

    private UriInfo getUriInfo() {
        final UriInfo result = mock(UriInfo.class);
        when(result.getBaseUri()).thenReturn(URI.create(BASE_URI));
        return result;
    }

    @Test
    public void newRepresentation() throws Exception {
        final StandardRepresentationFactory representationFactory = new StandardRepresentationFactory();

        final URI self = URI.create(String.format("%s/zones/%s/playlist", BASE_URI, MY_ZONE));
        when(uriInfo.getBaseUriBuilder()).thenAnswer(i -> UriBuilder.fromPath(BASE_URI));
        final String expected = representationFactory
                .withFlag(RepresentationFactory.COALESCE_ARRAYS)
                .newRepresentation(self)
                .withNamespace("mr", "http://myserver:1234/multiroom-mpd/docs/#/relations/{rel}")
                .withRepresentation("mr:playlist-song",
                        playlistSongRepresentationFactory.newRepresentation("myZone", new PlaylistSong(new Song("Song A"), 1)))
                .withRepresentation("mr:playlist-song", playlistSongRepresentationFactory.newRepresentation(MY_ZONE, new PlaylistSong(new Song("Song B"), 2)))
                .toString(RepresentationFactory.HAL_JSON);

        final ZonePlaylistDto zonePlaylistDto = new ZonePlaylistDto(UUID.randomUUID(), "myZone", new ZonePlaylist(Arrays.asList(new PlaylistSong(new Song("Song A"), 1), new PlaylistSong(new Song("Song B"), 2))));

        final String actual = testSubject.newRepresentation(zonePlaylistDto).toString(RepresentationFactory.HAL_JSON);

        assertThat(actual).isEqualTo(expected);
    }

}


text:
maintainer        "Chris Modica"
maintainer_email  "chrismodica@gmail.com"
license           "Apache 2.0"
description       "Install and configure Shibboleth SP"
version           "0.1.2"

recipe "shibboleth_sp", "Install and configure Shibboleth SP"

%w{ centos }.each do |os|
  supports os
end

depends "apache2"


text:
ansible-playbook ./test.yml
docker-compose -f ./output/docker-compose.yml config > /dev/null
docker-compose -f ./output/docker-compose-nginx-tls-verify-client.yml config > /dev/null
docker-compose -f ./output/docker-compose-no_mysql_container.yml config > /dev/null
docker-compose -f ./output/docker-compose-no_mysql.yml config > /dev/null
python -m json.tool ./output/ca.json > /dev/null


text:
import re

_REGEX = re.compile('^(?P<major>(?:0|[1-9][0-9]*))'
                    '\.(?P<minor>(?:0|[1-9][0-9]*))'
                    '\.(?P<patch>(?:0|[1-9][0-9]*))'
                    '(\-(?P<prerelease>[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?'
                    '(\+(?P<build>[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?$')

_LAST_NUMBER = re.compile(r'(?:[^\d]*(\d+)[^\d]*)+')

if not hasattr(__builtins__, 'cmp'):
    cmp = lambda a, b: (a > b) - (a < b)

def parse(version):
    """
    Parse version to major, minor, patch, pre-release, build parts.
    """
    match = _REGEX.match(version)
    if match is None:
        raise ValueError('%s is not valid SemVer string' % version)

    verinfo = match.groupdict()

    verinfo['major'] = int(verinfo['major'])
    verinfo['minor'] = int(verinfo['minor'])
    verinfo['patch'] = int(verinfo['patch'])

    return verinfo

def compare(ver1, ver2):
    def nat_cmp(a, b):
        a, b = a or '', b or ''
        convert = lambda text: (2, int(text)) if re.match('[0-9]+', text) else (1, text)
        split_key = lambda key: [convert(c) for c in key.split('.')]
        return cmp(split_key(a), split_key(b))

    def compare_by_keys(d1, d2):
        for key in ['major', 'minor', 'patch']:
            v = cmp(d1.get(key), d2.get(key))
            if v:
                return v

        rc1, rc2 = d1.get('prerelease'), d2.get('prerelease')
        rccmp = nat_cmp(rc1, rc2)

        build_1, build_2 = d1.get('build'), d2.get('build')
        build_cmp = nat_cmp(build_1, build_2)

        if not rccmp and not build_cmp:
            return 0
        if not rc1 and not build_1:
            return 1
        elif not rc2 and not build_2:
            return -1

        return rccmp or build_cmp

    v1, v2 = parse(ver1), parse(ver2)

    return compare_by_keys(v1, v2)

def match(version, match_expr):
    prefix = match_expr[:2]
    if prefix in ('>=', '<=', '=='):
        match_version = match_expr[2:]
    elif prefix and prefix[0] in ('>', '<', '='):
        prefix = prefix[0]
        match_version = match_expr[1:]
    else:
        raise ValueError("match_expr parameter should be in format <op><ver>, "
                         "where <op> is one of ['<', '>', '==', '<=', '>=']. "
                         "You provided: %r" % match_expr)

    possibilities_dict = {
        '>': (1,),
        '<': (-1,),
        '==': (0,),
        '>=': (0, 1),
        '<=': (-1, 0)
    }

    possibilities = possibilities_dict[prefix]
    cmp_res = compare(version, match_version)

    return cmp_res in possibilities

def max_ver(ver1, ver2):
    cmp_res = compare(ver1, ver2)
    if cmp_res == 0 or cmp_res == 1:
        return ver1
    else:
        return ver2

def min_ver(ver1, ver2):
    cmp_res = compare(ver1, ver2)
    if cmp_res == 0 or cmp_res == -1:
        return ver1
    else:
        return ver2

def format_version(major, minor, patch, prerelease=None, build=None):
    version = "%d.%d.%d" % (major, minor, patch)
    if prerelease is not None:
        version = version + "-%s" % prerelease

    if build is not None:
        version = version + "+%s" % build

    return version

def _increment_string(string):
    # look for the last sequence of number(s) in a string and increment, from:
    # http://code.activestate.com/recipes/442460-increment-numbers-in-a-string/#c1
    match = _LAST_NUMBER.search(string)
    if match:
        next_ = str(int(match.group(1))+1)
        start, end = match.span(1)
        string = string[:max(end - len(next_), start)] + next_ + string[end:]
    return string

def bump_major(version):
    verinfo = parse(version)
    return format_version(verinfo['major'] + 1, 0, 0)

def bump_minor(version):
    verinfo = parse(version)
    return format_version(verinfo['major'], verinfo['minor'] + 1, 0)

def bump_patch(version):
    verinfo = parse(version)
    return format_version(verinfo['major'], verinfo['minor'], verinfo['patch'] + 1)

def bump_prerelease(version):
    verinfo = parse(version)
    verinfo['prerelease'] = _increment_string(verinfo['prerelease'] or 'rc.0')
    return format_version(verinfo['major'], verinfo['minor'], verinfo['patch'],
                          verinfo['prerelease'])

def bump_build(version):
    verinfo = parse(version)
    verinfo['build'] = _increment_string(verinfo['build'] or 'build.0')
    return format_version(verinfo['major'], verinfo['minor'], verinfo['patch'],
                          verinfo['prerelease'], verinfo['build'])


text:
package org.jetbrains.plugins.scala.lang.psi.impl

import com.intellij.openapi.project.Project
import com.intellij.psi._
import com.intellij.psi.impl.PsiManagerEx
import com.intellij.psi.impl.file.PsiPackageImpl
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.plugins.scala.ScalaFileType
import org.jetbrains.plugins.scala.caches.{CachesUtil, ScalaShortNamesCacheManager}
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.lang.psi.api.ScPackage
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.{ScObject, ScTypeDefinition}
import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.synthetic.SyntheticClasses
import org.jetbrains.plugins.scala.lang.psi.types.ScType
import org.jetbrains.plugins.scala.lang.psi.types.result.TypingContext
import org.jetbrains.plugins.scala.lang.resolve.ResolveUtils
import org.jetbrains.plugins.scala.lang.resolve.processor.{BaseProcessor, ResolveProcessor}

import scala.util.control.ControlThrowable

/**
 * User: Alexander Podkhalyuzin
 * Date: 22.04.2010
 */
class ScPackageImpl private (val pack: PsiPackage) extends PsiPackageImpl(pack.getManager.asInstanceOf[PsiManagerEx],
        pack.getQualifiedName) with ScPackage {
  def superProcessDeclarations(processor: PsiScopeProcessor, state: ResolveState,
                                    lastParent: PsiElement, place: PsiElement): Boolean = {
    super.processDeclarations(processor, state, lastParent, place)
  }

  override def processDeclarations(processor: PsiScopeProcessor, state: ResolveState,
                                   lastParent: PsiElement, place: PsiElement): Boolean = {
    if (place.getLanguage == ScalaFileType.SCALA_LANGUAGE && pack.getQualifiedName == "scala") {
      if (!BaseProcessor.isImplicitProcessor(processor)) {
        val scope = processor match {
          case r: ResolveProcessor => r.getResolveScope
          case _ => place.getResolveScope
        }
        val namesSet = ScalaShortNamesCacheManager.getInstance(getProject).getClassNames(pack, scope)

        //Process synthetic classes for scala._ package
        /**
         * Does the "scala" package already contain a class named `className`?
         *
         * [[http://youtrack.jetbrains.net/issue/SCL-2913]]
         */
        def alreadyContains(className: String) = namesSet.contains(className)

        for (synth <- SyntheticClasses.get(getProject).getAll) {
          if (!alreadyContains(synth.name)) processor.execute(synth, ResolveState.initial)
        }
        for (synthObj <- SyntheticClasses.get(getProject).syntheticObjects) {

          // Assume that is the scala package contained a class with the same names as the synthetic object,
          // then it must also contain the object.
          if (!alreadyContains(synthObj.name)) processor.execute(synthObj, ResolveState.initial)
        }
      }
    } else {
      if (!ResolveUtils.packageProcessDeclarations(pack, processor, state, lastParent, place)) return false
    }

    //for Scala
    if (place.getLanguage == ScalaFileType.SCALA_LANGUAGE) {
      val scope = processor match {
        case r: ResolveProcessor => r.getResolveScope
        case _ => place.getResolveScope
      }
      if (getQualifiedName == "scala") {
        ScPackageImpl.implicitlyImportedObject(place.getManager, scope, "scala") match {
          case Some(obj: ScObject) =>
            var newState = state
            obj.getType(TypingContext.empty).foreach {
              case tp: ScType => newState = state.put(BaseProcessor.FROM_TYPE_KEY, tp)
            }
            if (!obj.processDeclarations(processor, newState, lastParent, place)) return false
          case _ =>
        }
      } else {
        findPackageObject(scope) match {
          case Some(obj: ScObject) =>
            var newState = state
            obj.getType(TypingContext.empty).foreach {
              case tp: ScType => newState = state.put(BaseProcessor.FROM_TYPE_KEY, tp)
            }
            if (!obj.processDeclarations(processor, newState, lastParent, place)) return false
          case _ =>
        }
      }
    }
    true
  }

  def findPackageObject(scope: GlobalSearchScope): Option[ScTypeDefinition] = {
    val manager = ScalaShortNamesCacheManager.getInstance(getProject)

    var tuple = pack.getUserData(CachesUtil.PACKAGE_OBJECT_KEY)
    val count = ScalaPsiManager.instance(getProject).getModificationCount
    if (tuple == null || tuple._2.longValue != count) {
      val clazz = manager.getPackageObjectByName(getQualifiedName, scope)
      tuple = (clazz, java.lang.Long.valueOf(count)) // TODO is it safe to cache this ignoring `scope`?
      pack.putUserData(CachesUtil.PACKAGE_OBJECT_KEY, tuple)
    }
    Option(tuple._1)
  }

  override def getParentPackage: PsiPackageImpl = {
    val myQualifiedName = getQualifiedName
    if (myQualifiedName.length == 0) return null
    val lastDot: Int = myQualifiedName.lastIndexOf('.')
    if (lastDot < 0) {
      ScPackageImpl.findPackage(getProject, "")
    } else {
      ScPackageImpl.findPackage(getProject, myQualifiedName.substring(0, lastDot))
    }
  }

  override def getSubPackages: Array[PsiPackage] = {
    super.getSubPackages.map(ScPackageImpl(_))
  }

  override def getSubPackages(scope: GlobalSearchScope): Array[PsiPackage] = {
    super.getSubPackages(scope).map(ScPackageImpl(_))
  }

  override def isValid: Boolean = true
}

object ScPackageImpl {
  def apply(pack: PsiPackage): ScPackageImpl = {
    pack match {
      case null => null
      case impl: ScPackageImpl => impl
      case _ => new ScPackageImpl(pack)
    }
  }

  def findPackage(project: Project, pName: String) = {
    ScPackageImpl(ScalaPsiManager.instance(project).getCachedPackage(pName).orNull)
  }

  class DoNotProcessPackageObjectException extends ControlThrowable

  def isPackageObjectProcessing: Boolean = {
    processing.get() > 0
  }

  def startPackageObjectProcessing() {
    processing.set(processing.get() + 1)
  }

  def stopPackageObjectProcessing() {
    processing.set(processing.get() - 1)
  }

  private val processing: ThreadLocal[Long] = new ThreadLocal[Long] {
    override def initialValue(): Long = 0
  }

  private def implicitlyImportedObject(manager: PsiManager, scope: GlobalSearchScope, fqn: String): Option[PsiClass] = {
    ScalaPsiManager.instance(manager.getProject).getCachedClasses(scope, fqn).headOption
  }
}


text:
package utils.enhance.asm.util;

import org.objectweb.asm.*;

import utils.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 类操作的工具集
 * @author Jake
 * @date 2014年9月6日上午12:10:37
 */
public class AsmUtils implements Opcodes {

	/**
	 * 是否为基本类型的包装类
	 * @param clz 目标类型
	 * @return
	 */
	public static boolean isWrapClass(Class<?> clz) {
		if(clz.isPrimitive()) {
			return false;
		}
        try {
        	return ((Class<?>) clz.getField("TYPE").get(null)).isPrimitive();
        } catch (Exception e) {
        	return false;
        }
    }

	/**
	 * 是否基本类型(包括包装类型)
	 * @param clzz 目标类型
	 * @return
	 */
	public static boolean isBaseType(Class<?> clzz) {
		return clzz.isPrimitive() || clzz == Object.class || isWrapClass(clzz);
	}

	/**
	 * 获取get方法名
	 * @param field 属性
	 * @return
	 */
	public static String getGetterMethodName(Field field) {
		if(field.getType() == boolean.class) {
			return "is" + StringUtils.getUString(field.getName());
		}
		return "get" + StringUtils.getUString(field.getName());
	}

	/**
	 * 获取set方法名
	 * @param field 属性
	 * @return
	 */
	public static String getSetterMethodName(Field field) {
		return "set" + StringUtils.getUString(field.getName());
	}

	/**
	 * 把类名中的"."替换为"/"
	 *
	 * @param className
	 * @return
	 */
	public static String toAsmCls(String className) {
		return className.replace('.', '/');
	}

	/**
	 * 判断是否需要重写方法
	 *

	 * object类本身的方法不做重写
	 *

	 *

	 * "main" 方法不做重写
	 *

	 *
	 * @param m
	 *            目标方法
	 * @return
	 */
	public static boolean needOverride(Method m) {
		// object类本身的方法不做重写
		if (m.getDeclaringClass().getName().equals(Object.class.getName())) {
			return false;
		}
		// 复合方法
		if (m.isSynthetic()) {
			return false;
		}
		// "main" 方法不做重写
		return !(Modifier.isPublic(m.getModifiers())
				&& Modifier.isStatic(m.getModifiers())
				&& m.getReturnType().getName().equals("void")
				&& m.getName().equals("main"));
	}

	public static String getPrimitiveLetter(Class<?> type) {
        if (Integer.TYPE.equals(type)) {
            return "I";
        } else if (Void.TYPE.equals(type)) {
            return "V";
        } else if (Boolean.TYPE.equals(type)) {
            return "Z";
        } else if (Character.TYPE.equals(type)) {
            return "C";
        } else if (Byte.TYPE.equals(type)) {
            return "B";
        } else if (Short.TYPE.equals(type)) {
            return "S";
        } else if (Float.TYPE.equals(type)) {
            return "F";
        } else if (Long.TYPE.equals(type)) {
            return "J";
        } else if (Double.TYPE.equals(type)) {
            return "D";
        }

        throw new IllegalStateException("Type: " + type.getCanonicalName() + " is not a primitive type");
    }

    public static java.lang.reflect.Type getMethodType(Class<?> clazz, String methodName) {
        try {
            Method method = clazz.getMethod(methodName);

            return method.getGenericReturnType();
        } catch (Exception ex) {
            return null;
        }
    }

    public static java.lang.reflect.Type getFieldType(Class<?> clazz, String fieldName) {
        try {
            Field field = clazz.getField(fieldName);

            return field.getGenericType();
        } catch (Exception ex) {
            return null;
        }
    }

	/**
	 *
	 *

	 * get StoreCode(Opcodes#xStore)
	 *

	 *
	 *
	 * @param type
	 * @return
	 */
	public static int storeCode(Type type) {

		int sort = type.getSort();
		switch (sort) {
		case Type.ARRAY:
			sort = ASTORE;
			break;
		case Type.BOOLEAN:
			sort = ISTORE;
			break;
		case Type.BYTE:
			sort = ISTORE;
			break;
		case Type.CHAR:
			sort = ISTORE;
			break;
		case Type.DOUBLE:
			sort = DSTORE;
			break;
		case Type.FLOAT:
			sort = FSTORE;
			break;
		case Type.INT:
			sort = ISTORE;
			break;
		case Type.LONG:
			sort = LSTORE;
			break;
		case Type.OBJECT:
			sort = ASTORE;
			break;
		case Type.SHORT:
			sort = ISTORE;
			break;
		default:
			break;
		}
		return sort;
	}

	/**
	 *
	 *

	 * get StoreCode(Opcodes#xLOAD)
	 *

	 *
	 * @param type
	 * @return
	 */
	public static int loadCode(Type type) {
		int sort = type.getSort();
		switch (sort) {
		case Type.ARRAY:
			sort = ALOAD;
			break;
		case Type.BOOLEAN:
			sort = ILOAD;
			break;
		case Type.BYTE:
			sort = ILOAD;
			break;
		case Type.CHAR:
			sort = ILOAD;
			break;
		case Type.DOUBLE:
			sort = DLOAD;
			break;
		case Type.FLOAT:
			sort = FLOAD;
			break;
		case Type.INT:
			sort = ILOAD;
			break;
		case Type.LONG:
			sort = LLOAD;
			break;
		case Type.OBJECT:
			sort = ALOAD;
			break;
		case Type.SHORT:
			sort = ILOAD;
			break;
		default:
			break;
		}
		return sort;
	}

	/**
	 *
	 *

	 * get StoreCode(Opcodes#xRETURN)
	 *

	 *
	 * @param type
	 * @return
	 */
	public static int rtCode(Type type) {
		int sort = type.getSort();
		switch (sort) {
		case Type.ARRAY:
			sort = ARETURN;
			break;
		case Type.BOOLEAN:
			sort = IRETURN;
			break;
		case Type.BYTE:
			sort = IRETURN;
			break;
		case Type.CHAR:
			sort = IRETURN;
			break;
		case Type.DOUBLE:
			sort = DRETURN;
			break;
		case Type.FLOAT:
			sort = FRETURN;
			break;
		case Type.INT:
			sort = IRETURN;
			break;
		case Type.LONG:
			sort = LRETURN;
			break;
		case Type.OBJECT:
			sort = ARETURN;
			break;
		case Type.SHORT:
			sort = IRETURN;
			break;
		default:
			break;
		}
		return sort;
	}

	/**
	 * 封装成包装类型
	 */
	public static void withBoxingType(MethodVisitor mWriter, Type fieldType) {
		switch (fieldType.getSort()) {
			case Type.VOID:
				break;
			case Type.BOOLEAN:
				mWriter.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;");
				break;
			case Type.BYTE:
				mWriter.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;");
				break;
			case Type.CHAR:
				mWriter.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;");
				break;
			case Type.SHORT:
				mWriter.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;");
				break;
			case Type.INT:
				mWriter.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;");
				break;
			case Type.FLOAT:
				mWriter.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;");
				break;
			case Type.LONG:
				mWriter.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;");
				break;
			case Type.DOUBLE:
				mWriter.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;");
				break;
		}
	}

	/**
	 * 转换成拆箱类型
	 * @param mWriter
	 * @param fieldType
	 */
	public static void withUnBoxingType(MethodVisitor mWriter, Type fieldType) {
		if(fieldType == Type.VOID_TYPE) {
		} else if(fieldType == Type.INT_TYPE) {
			mWriter.visitTypeInsn(CHECKCAST, "java/lang/Integer");
			mWriter.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I");
		} else if(fieldType == Type.BOOLEAN_TYPE) {
			mWriter.visitTypeInsn(CHECKCAST, "java/lang/Boolean");
			mWriter.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z");
		} else if(fieldType == Type.BYTE_TYPE) {
			mWriter.visitTypeInsn(CHECKCAST, "java/lang/Byte");
			mWriter.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B");
		} else if(fieldType == Type.CHAR_TYPE) {
			mWriter.visitTypeInsn(CHECKCAST, "java/lang/Character");
			mWriter.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C");
		} else if(fieldType == Type.SHORT_TYPE) {
			mWriter.visitTypeInsn(CHECKCAST, "java/lang/Short");
			mWriter.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S");
		} else if(fieldType == Type.FLOAT_TYPE) {
			mWriter.visitTypeInsn(CHECKCAST, "java/lang/Float");
			mWriter.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F");
		} else if(fieldType == Type.LONG_TYPE) {
			mWriter.visitTypeInsn(CHECKCAST, "java/lang/Long");
			mWriter.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J");
		} else if(fieldType == Type.DOUBLE_TYPE) {
			mWriter.visitTypeInsn(CHECKCAST, "java/lang/Double");
			mWriter.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D");
		}
	}

	/**
	 * 获取加载数组元素指令
	 * @param type 数组元素类型
	 * @return
	 */
	public static int loadArrayCode(org.objectweb.asm.Type type) {
		switch (type.getSort()) {
			case Type.OBJECT:
				return AALOAD;
			case Type.BOOLEAN:
				return BALOAD;
			case Type.CHAR:
				return CALOAD;
			case Type.SHORT:
				return SALOAD;
			case Type.INT:
				return IALOAD;
			case Type.FLOAT:
				return FALOAD;
			case Type.LONG:
				return LALOAD;
			case Type.DOUBLE:
				return DALOAD;
		}

		return AALOAD;
	}

	/**
	 * 获取存储数组元素指令
	 * @param type 数组元素类型
	 * @return
	 */
	public static int storeArrayCode(org.objectweb.asm.Type type) {
		switch (type.getSort()) {
			case Type.OBJECT:
				return AASTORE;
			case Type.BOOLEAN:
				return BASTORE;
			case Type.CHAR:
				return CASTORE;
			case Type.SHORT:
				return SASTORE;
			case Type.INT:
				return IASTORE;
			case Type.FLOAT:
				return FASTORE;
			case Type.LONG:
				return LASTORE;
			case Type.DOUBLE:
				return DASTORE;
		}
		return AALOAD;
	}

	/**
	 * 创建数组指令
	 * @param componentClass 数组元素类型
	 * @return
	 */
	public static int newArrayCode(Class<?> type) {
		if (Integer.TYPE.equals(type)) {
            return T_INT;
        } else if (Boolean.TYPE.equals(type)) {
            return T_BOOLEAN;
        } else if (Character.TYPE.equals(type)) {
            return T_CHAR;
        } else if (Byte.TYPE.equals(type)) {
            return T_BYTE;
        } else if (Short.TYPE.equals(type)) {
            return T_SHORT;
        } else if (Float.TYPE.equals(type)) {
            return T_FLOAT;
        } else if (Long.TYPE.equals(type)) {
            return T_LONG;
        } else if (Double.TYPE.equals(type)) {
            return T_DOUBLE;
        }

        throw new IllegalStateException("Type: " + type.getCanonicalName() + " is not a primitive type");
	}

	/**
	 * 获取基本类型的TYPE
	 * @param mv
	 * @param fieldRawClass 类型
	 */
	public static void loadPrimitiveType(MethodVisitor mv, Class<?> fieldRawClass) {

		if (fieldRawClass == int.class || fieldRawClass == Integer.class) {
			mv.visitFieldInsn(GETSTATIC, "java/lang/Integer", "TYPE", "Ljava/lang/Class;");
		} else if (fieldRawClass == short.class || fieldRawClass == Short.class) {
			mv.visitFieldInsn(GETSTATIC, "java/lang/Short", "TYPE", "Ljava/lang/Class;");
		} else if (fieldRawClass == long.class || fieldRawClass == Long.class) {
			mv.visitFieldInsn(GETSTATIC, "java/lang/Long", "TYPE", "Ljava/lang/Class;");
		} else if (fieldRawClass == float.class || fieldRawClass == Float.class) {
			mv.visitFieldInsn(GETSTATIC, "java/lang/Float", "TYPE", "Ljava/lang/Class;");
		} else if (fieldRawClass == double.class || fieldRawClass == Double.class) {
			mv.visitFieldInsn(GETSTATIC, "java/lang/Double", "TYPE", "Ljava/lang/Class;");
		} else if (fieldRawClass == byte.class || fieldRawClass == Byte.class) {
			mv.visitFieldInsn(GETSTATIC, "java/lang/Double", "TYPE", "Ljava/lang/Class;");
		} else if (fieldRawClass == boolean.class || fieldRawClass == Boolean.class) {
			mv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;");
		} else if (fieldRawClass == char.class || fieldRawClass == Character.class) {
			mv.visitFieldInsn(GETSTATIC, "java/lang/Character", "TYPE", "Ljava/lang/Class;");
		}

	}

	/**
	 *
	 *

	 * 比较参数类型是否一致
	 *

	 *
	 * @param types
	 *            asm的类型({@link Type})
	 * @param clazzes
	 *            java 类型({@link Class})
	 * @return
	 */
	private static boolean sameType(Type[] types, Class<?>[] clazzes) {
		// 个数不同
		if (types.length != clazzes.length) {
			return false;
		}

		for (int i = 0; i < types.length; i++) {
			if (!Type.getType(clazzes[i]).equals(types[i])) {
				return false;
			}
		}

		return true;
	}

	/**
	 *
	 *

	 * 获取方法的参数名
	 *

	 * 兼容JDK1.6
	 * @param m
	 * @return
	 */
	public static Map<String, Class<?>> getMethodParams(final Method m) {
		//获取参数类型列表
		final Class<?>[] parameterTypes = m.getParameterTypes();

		final Map<String, Class<?>> paramMap = new LinkedHashMap<String, Class<?>>(parameterTypes.length);

		final String n = m.getDeclaringClass().getName();
		ClassReader cr;

		try {
			cr = new ClassReader(n);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		cr.accept(new ClassVisitor(Opcodes.ASM4) {

			@Override
			public MethodVisitor visitMethod(final int access,
					final String name, final String desc,
					final String signature, final String[] exceptions) {
				final Type[] args = Type.getArgumentTypes(desc);
				// 方法名相同并且参数个数相同
				if (!name.equals(m.getName())
						|| !sameType(args, m.getParameterTypes())) {
					return super.visitMethod(access, name, desc, signature,
							exceptions);
				}
				MethodVisitor v = super.visitMethod(access, name, desc,
						signature, exceptions);

				return new MethodVisitor(Opcodes.ASM4, v) {
					@Override
					public void visitLocalVariable(String name, String desc,
							String signature, Label start, Label end, int index) {
						int i = index - 1;
						// 如果是静态方法,则第一就是参数
						// 如果不是静态方法,则第一个是"this",然后才是方法的参数
						if (Modifier.isStatic(m.getModifiers())) {
							i = index;
						}
						if (i >= 0 && i < parameterTypes.length) {
							paramMap.put(name, parameterTypes[i]);
						}
						super.visitLocalVariable(name, desc, signature, start,
								end, index);
					}

				};

			}
		}, 0);

		return paramMap;
	}

	/**
	 *
	 *

	 * 把java字节码写入class文件
	 *

	 *
	 * @param <T>
	 * @param name
	 * @param data
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static <T> void writeClazz(String name, byte[] data) {
//		try {
//			File file = new File("C:\\" + name + ".class");
//			FileOutputStream fout = new FileOutputStream(file);
//
//			fout.write(data);
//			fout.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
	}

}


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var dataconnect_1 = require('../../../_service/dataconnect');
var router_1 = require('@angular/router');
var bankBookService = (function () {
    function bankBookService(_dataserver, _router) {
        this._dataserver = _dataserver;
        this._router = _router;
    }
    bankBookService.prototype.getBankMaster = function (req) {
        return this._dataserver.post("BankNameGet", req);
    };
    bankBookService.prototype.getBankBookList = function (req) {
        return this._dataserver.post("Get_BankBookReport", req);
    };
    bankBookService = __decorate([
        core_1.Injectable(),
        __metadata('design:paramtypes', [dataconnect_1.DataService, router_1.Router])
    ], bankBookService);
    return bankBookService;
}());
exports.bankBookService = bankBookService;
//# sourceMappingURL=bankbook-service.js.map


text:
View.define('test/views/v3', {

    keepInstances: View.KEEP_NONE,

    // transition: 'fade',

    loadTimes: 0,

    ready: function(root) {
        root.querySelector('.btn-back').addEventListener('click', function() {
            testSuite.viewport.back();
        });
        root.querySelector('.btn-next').addEventListener('click', function() {
            testSuite.viewport.back('/test/views/v1/fa4');
        });
    },

    load: function(options, complete) {
        var self = this;
        View.prototype.load.call(this, options, function(err, data) {
            self.loadTimes++;
            if (complete) {
                complete(err, data);
            }
        });
    }

});


text:
Test of base sinusoidal motion

- BAR turbine
- Sinusoidal motion of the base (pitch DOF)
- DBEMT


text:
<?xml version="1.0" encoding="UTF-8"?>
<jhove xmlns="http://hul.harvard.edu/ois/xml/ns/jhove" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="epubcheck" release="4.0.0-alpha11-SNAPSHOT" date="2012-10-31">
 <date>2014-09-05T03:15:43+02:00</date>
 <repInfo uri="Epub2_marked_v3.epub">
  <created>2014-09-05T01:49:14Z</created>
  <format>application/epub+zip</format>
  <version>3.0.1</version>
  <status>Not well-formed</status>
  <messages>
   <message severity="error" subMessage="RSC-005">RSC-005, ERROR, [Error while parsing file 'package dcterms:modified meta element must occur exactly once'.], OPS/content.opf (3-57)</message>
   <message severity="error" subMessage="RSC-005">RSC-005, ERROR, [Error while parsing file 'Exactly one manifest item must declare the 'nav' property (number of 'nav' items: 0).'.], OPS/content.opf (8-13)</message>
   <message severity="error" subMessage="HTM-004">HTM-004, ERROR, [Irregular DOCTYPE: found '-//W3C//DTD XHTML 1.1//EN', expected '<!DOCTYPE html>'.], OPS/page01.xhtml</message>
   <message severity="info" subMessage="HTM-010">HTM-010, HINT, [Namespace uri 'http://www.daisy.org/z3986/2005/ncx/' was found.], OPS/toc.ncx (2-68)</message>
   <message severity="info" subMessage="ACC-008">ACC-008, HINT, [Navigation Document has no 'landmarks nav' element.], Epub2_marked_v3.epub</message>
   <message severity="info" subMessage="ACC-007">ACC-007, HINT, [Content Documents do not use 'epub:type' attributes for semantic inflection.], OPS/page01.xhtml</message>
  </messages>
  <mimeType>application/epub+zip</mimeType>
  <properties>
   <property>
    <name>CharacterCount</name>
    <values arity="Scalar" type="Long">
     <value>73</value>
    </values>
   </property>
   <property>
    <name>Language</name>
    <values arity="Scalar" type="String">
     <value>en</value>
    </values>
   </property>
   <property>
    <name>Info</name>
    <values arity="List" type="Property">
     <property>
      <name>Identifier</name>
      <values arity="Scalar" type="String">
       <value>000000000000000000</value>
      </values>
     </property>
     <property>
      <name>CreationDate</name>
      <values arity="Scalar" type="Date">
       <value>2014-09-05T01:49:14Z</value>
      </values>
     </property>
     <property>
      <name>Title</name>
      <values arity="Scalar" type="String">
       <value>Epub2 marked as version 3</value>
      </values>
     </property>
    </values>
   </property>
   <property>
      <name>MediaTypes</name>
      <values arity="Array" type="String">
         <value>application/x-dtbncx+xml</value>
         <value>application/xhtml+xml</value>
      </values>
   </property>
  </properties>
 </repInfo>
</jhove>


text:
package de.learnlib.algorithms.ostia;

import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * @author Aleksander Mendoza-Drosik
 */
public class State extends StateParent {

    State(int alphabetSize) {
        super.out = null;
        super.transitions = new Edge[alphabetSize];
    }

    /**
     * The IntQueue is consumed and should not be reused after calling this method.
     */
    void prependButIgnoreMissingStateOutput(@Nullable IntQueue prefix) {
        for (@Nullable Edge edge : transitions) {
            if (edge != null) {
                edge.out = IntQueue.copyAndConcat(prefix, edge.out);
            }
        }
        if (out != null) {
            out.str = IntQueue.copyAndConcat(prefix, out.str);
        }
    }
}


text:
Each Dockerfile in this repo implements an instance of [Marconi](https://wiki.openstack.org/wiki/Marconi) Queues intended for development and testing. Thus, the setup is kept as simple as possible; no sharding, no auth, no memcached, runs on gunicorn with gevent.

You will find several directories. Each of these are intended to hold the files to build a release of Marconi.

You can find these images in the docker index and use them directly. For example, to run Marconi 2014.1:

    $ MARCONI=$(docker run -d -p 0.0.0.0:8080:80 sebasmagri/docker-marconi:2014.1)

Check if everything started:

    $ docker logs $MARCONI

Forks, patches and different setups are completely welcome.


text:
<?php

namespace Elektra\SeedBundle\Repository\Imports;

use Elektra\CrudBundle\Repository\Repository as CrudRepository;

/**
 * Class ImportRepository
 *
 * @package Elektra\SeedBundle\Repository\Imports
 *
 * @version 0.1-dev
 */
class ImportRepository extends CrudRepository
{

}


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>UpdateAPI</groupId>
    <artifactId>Main</artifactId>
    <version>1.0-SNAPSHOT</version>

    <repositories>
        <repository>
            <id>spigot-repo</id>
            <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.10.2-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>


text:
<?php

namespace OFFLINE\SiteSearch\Components;
use Cms\Classes\ComponentBase as OctoberBaseComponent;

abstract class BaseComponent extends OctoberBaseComponent
{
    /**
     * Sets a var as a property on this class
     * and as a key in $this->page.
     *
     * If no value is specified the component property
     * named $var is set as value.
     *
     * @param      $var
     * @param null $value
     */
    protected function setVar($var, $value = null)
    {
        if ($value === null) {
            $value = $this->property($var);
        }
        $this->{$var} = $this->page[$var] = $value;
    }

}


text:
var Album = {
    init: function () {
        this._initControls();
    },

    _initControls: function () {
        var photoAlbum = $.templates("#photoAlbumTemplate");
        var photoAlbumHtml = photoAlbum.render({});
        $("#main_content").append(photoAlbumHtml);
        var type = $("div#type-identifier").text();
        if (type == 'talking_album') {
            $(".volume-control").removeClass("hidden");
            $(".seek-bar-control").removeClass("hidden");
        }
        var album_json = $("div#json-identifier").text();
        album_json = jQuery.parseJSON(album_json);
        this.generateCarousel(album_json);
    },

    generateCarousel: function (data) {
        this.carouselData = data;

        data.slides.forEach(function (slide, index) {
            slide.carouselPageClass = index === 0 ? "item image-container active" : "item image-container";
            var carouselPage = $.templates("#carouselPage");
            var carouselPageHtml = carouselPage.render(slide);
            $(".carousel-items").append(carouselPageHtml);

            if (index === 0) {
                var carouselInfoBox = $.templates("#carouselStartingIntro");
                slide.photographerNames = constructPhotographerNames(slide.slide_photographer);
                var carouselInfoBoxHtml = carouselInfoBox.render(slide);
                $(".carousel-items .item:first-child .wrapper").append(carouselInfoBoxHtml);
                if ($("div#type-identifier").text() == "talking_album") {
                    var trackId = slide.track_id;
                    Album.prepareSoundCloudWidget("/tracks/"+trackId);
                }
                var albumDescription = slide.album_description;
                if(albumDescription.length > 450) {
                  albumDescription = albumDescription.substring(0, 450);
                }
                $(".floating-text .description").html(albumDescription);
            }

            $(".thumbnail-list").append('

');
        });

        data.authors.forEach(function (author) {
            var url = "";
            if (location.protocol != 'https:') {
                url = "http://"+window.location.hostname+author.author_url;
            } else {
                url = "https://"+window.location.hostname+author.author_url;
            }
            var fbShare = "https://facebook.com/sharer.php?u="+url;
            var twitterShare = "https://twitter.com/intent/tweet?url="+url+"&hashtags=RuralIndiaOnline&via=PARINetwork";
            author["fbShare"] = encodeURI(fbShare);
            author["twitterShare"] = encodeURI(twitterShare);
            author["url"] = encodeURI(url);
        });

        var carouselAuthor = $.templates("#carouselAuthor");
        var carouselAuthorHtml = carouselAuthor.render({"authors": data.authors});
        $(".carousel-items").append(carouselAuthorHtml);

        $(".photo-album-popup").removeClass("hide");
        $(".carousel-container").addClass("carousel");
        $(".carousel-container").attr("data-ride", "carousel");

        handleCarouselEvents(this.carouselData);
        setTimeout(function () {
            positionFloatingText();
        }, 500);

        $(window).resize(function () {
            positionFloatingText();
        });
    },

    prepareSoundCloudWidget: function (trackId) {
        var isTalkingAlbum = $("div#type-identifier").text() === "talking_album";
        if(isTalkingAlbum) {
          $("#playPause").hide();
        } else {
          $("#playPause").show();
        }

        var mediaPlayer = new MediaPlayerControl(".audio-player-controls");

        SC.initialize({
            client_id: "d129911dd3c35ec537c30a06990bd902"
        });
        var $this = this;

        SC.stream(trackId).then(function (player) {
            if (player.options.protocols[0] === 'rtmp') {
                player.options.protocols.splice(0, 1);
            }

            $this._player = player;
            var isAndroid = navigator.userAgent.match(/Android/i);
            if(isTalkingAlbum) {
                $(".play-pause").removeClass("fa-play fa-pause selected");
                Album.playAudio();
                if(isAndroid) {
                    Album.pauseAudio(); // To escape the exception due to chrome android
                    $(".play-pause").addClass("fa-play selected");
                } else {
                    $(".play-pause").addClass("fa-pause");
                }
            }

            $this._player.on("time", function () {
                mediaPlayer.updateOnSeek(player.currentTime(), player.options.duration);
            });

            $this._player.on("state-change", function (e) {
                if (e === "playing") {
                    mediaPlayer.setVolume(player.getVolume());
                }
            });

            $this._player.on("finish", function () {
                $("#carousel").carousel("next");
            });

            $(".audio-player-controls").on("play-pause-click", function (event, state) {
                if(state.isPaused) {
                  Album.pauseAudio();
                } else {
                  Album.playAudio();
                }
            });

            $(".audio-player-controls").on("volume-seekbar-click", function (event, data) {
                $this._player.setVolume(data.volume / 100);
            });

            $(".audio-player-controls").on("volume-seekbar-drag", function (event, data) {
                $this._player.setVolume(data.volume / 100);
            });

            $(".audio-player-controls").on("seeker-seekbar-click", function (event, data) {
                var seekTime = player.options.duration * data.seekPercent / 100;
                $this._player.seek(seekTime);
                $this._player.play(seekTime);
                $(".play-pause").removeClass("fa-play fa-pause selected").addClass("fa-pause");
            });

            $(".audio-player-controls").on("seeker-seekbar-drag", function (event, data) {
                var seekTime = player.options.duration * data.seekPercent / 100;
                $this._player.seek(seekTime);
                $this._player.play(seekTime, player);
                $(".play-pause").removeClass("fa-play fa-pause selected").addClass("fa-pause");
            });

            $('#carousel').on('slid.bs.carousel', function () {
              Album.stopAudioPlayer();
              mediaPlayer.play();
            });

        });
    },

    stopAudioPlayer: function () {
        if (this._player) {
            this._player.seek(0);
            this._player.pause(0);
            this._player.dispose();
            this._player = null;
        }
    },

    playAudio: function () {
      if(this._player) {
          this._player.play();
      }
    },

    pauseAudio: function () {
        if(this._player) {
            this._player.pause();
        }
    }
};

$(function () {
    Album.init();
});

function positionFloatingText() {
    if ($(".floating-text").length === 0) {
        return;
    }
    var image = $('.carousel-items .item:first-child img');

    var imageHeight = image.get(0).offsetHeight,
        contentHeight = imageHeight * 0.4,
        contentWidth = image.get(0).offsetWidth * 0.5;

    contentHeight = contentHeight < 350 ? 350 : contentHeight;
    contentHeight = contentHeight > imageHeight ? imageHeight : contentHeight;
    contentWidth = contentWidth < 415 ? 415 : contentWidth;
    var top = image.get(0).offsetTop + (imageHeight - contentHeight) / 2;

    $(".floating-text").css({
        left: image.get(0).offsetLeft + (image.get(0).offsetLeft * 0.15) + 40,
        top: top,
        height: contentHeight,
        width: contentWidth

    });
}

function constructPhotographerNames(photographers) {
    if(photographers.length==1) {
        photographerByline = photographers[0];
    } else {
        var commaSeparatedNames =[photographers.slice(0,-1).join(', ')];
        commaSeparatedNames.push(photographers.slice(-1)[0]);
        photographerByline = commaSeparatedNames.join(" and ");
    }
    return photographerByline;
}

function handleCarouselEvents(carouselData) {
    var totalItems = $('.carousel-items .item').length,
        currentIndex = 0,
        isTalkingAlbum = $("div#type-identifier").text() === "talking_album",
        isSlideshowPlaying = !isTalkingAlbum;

    updateCurrentPageData();

    $("#carousel").carousel({
        interval: isTalkingAlbum ? 1000 * 60 : 5000,
        pause: isTalkingAlbum
    });

    if(isTalkingAlbum) {
        $("#carousel").carousel("pause");
        $(".play-pause").show();
    } else {
      $(".play-pause").hide();
    }

    $('#playPause').click(function () {
        isSlideshowPlaying ? pauseSlide() : playSlide();
        $(this).toggleClass("selected");
    });

    $('#showSlideInfo').click(function () {
        $(this).toggleClass("selected");
        $(this).removeClass("fa-info-circle").removeClass("fa-angle-right");
        $(this).addClass($(this).hasClass("selected") ? "fa-angle-right" : "fa-info-circle");
        $(".photo-album").toggleClass("show-slide-info");

        setTimeout(function () {
            positionFloatingText();
        }, 500);
    });

    $('#showThumbnail').click(function () {
        pauseSlide();
        toggleThumbnail();
        $(".thumbnail-list li").removeClass("selected");
        $(".thumbnail-list li:nth-child(" + (currentIndex + 1) + ")").addClass("selected");
    });

    $('.thumbnail-list li').click(function (event) {
        var index = $(event.currentTarget).index('.thumbnail-list li');
        $("#carousel").carousel(index);
        toggleThumbnail();
        playSlide();
    });

    $('.close-thumbnail').click(function (event) {
        toggleThumbnail();
        playSlide();
    });

    $('.back-to-albums').click(function () {
        Album.stopAudioPlayer();
    });

    function pauseSlide() {
        isSlideshowPlaying = false;
        $('#playPause').removeClass("fa-pause").addClass("fa-play");
        $("#carousel").carousel("pause");
    }

    function playSlide() {
        isSlideshowPlaying = true;
        $('#playPause').removeClass("fa-play").addClass("fa-pause");
        $("#carousel").carousel("cycle");
    }

    $('#carousel').on('slid.bs.carousel', function () {
        if ($("div#type-identifier").text() == "talking_album") {
            pauseSlide();
        }
        updateIndexOnSlide();
        if ($("div#type-identifier").text() == "talking_album") {
            var data = carouselData.slides[currentIndex];
            if(data) {
              var trackId = data.track_id;
              Album.prepareSoundCloudWidget("/tracks/"+trackId);
              $(".audio-player-controls").show();
            } else {
              Album.stopAudioPlayer();
              $(".audio-player-controls").hide();
            }

        }
        if (currentIndex === 0) {
            setTimeout(function () {
                positionFloatingText();
            }, 500);
        }
    });

    function updateIndexOnSlide() {
        currentIndex = getSelectedCarouselIndex();
        updateCurrentPageData();
    }

    function getSelectedCarouselIndex() {
        return $('.photo-album .carousel-items li.active').index('.photo-album .carousel-items li.item');
    }

    function updateCurrentPageData() {
        updateSlideInfo();
        totalItems = $('.carousel-items .item').length;
        $('.carousel-index').html((currentIndex + 1) + " / " + totalItems);
        if(currentIndex === carouselData.slides.length) {
          if(!$(".carousel-area").hasClass("author-page")) {
              $(".carousel-area").addClass("author-page");
          }
        } else {
          $(".carousel-area").removeClass("author-page");
        }

    }

    function updateSlideInfo() {
        if (currentIndex === totalItems - 1) {
            $(".slide-info .info").html("");
            return;
        }

        var data = carouselData.slides[currentIndex];
        if (currentIndex <= carouselData.slides.length) {
            $(".slide-info .description").html(data.description);
            $(".slide-info .album-title").text(data.album_title);
            $(".slide-info .slide-photographer").text(constructPhotographerNames(data.slide_photographer));
            $(".slide-info .image-captured-date").text(data.image_captured_date);
            $(".slide-info .slide-location").text(data.slide_location);
            $(".open-in-new-tab").attr("href", data.src);
        }

    }

    function toggleThumbnail() {
        $('#showThumbnail').toggleClass("selected");
        $(".photo-album").toggleClass("show-thumbnail");
    }
}


text:
var deck = function () {
  this.ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]; // Specify the possible card ranks
  this.suits = ["Spades", "Diamonds", "Clubs", "Hearts"]; // Specify the possible card suits
  var cards = []; // Create an empty array for the deck

  var s,
      n,
      totalRanks = this.ranks.length, // Calculate the number of suits and names to loop through outside of the for loop
      totalSuits = this.suits.length; // (to avoid having to calculate it each time it runs through the loop)

  // Loop through the suit and rank options, to create one card of each variation and add it to the cards array
  for (s = 0; s < totalSuits; s++) {
    for (n = 0; n < totalRanks; n++) {
      // Push each card to the "cards" array
      // Assign the suit and name of each card, and increase the value by 1 for each card (starts again from 1 when start looping through a new suit)
      // (due to zero indexing; have to use n+1 to get the right value, as it will otherwise start at 0)
      cards.push(new card(this.suits[s], this.ranks[n], n+1));
    }
  }
  return cards; // Make the cards array available outside of the deck() function
}

// Create a card object which accepts the name, suit and value of each card
function card(suit, rank, value) { // Note that the arguments of this function need to be input in the same order as
                                   // the values in the cards.push() method (to ensure that the card name gets assigned to "name", etc)
  this.value = value;
  this.rank = rank;
  this.suit = suit;
}

// Use the Fisher-Yates shuffle algorithm to shuffle the cards, to ensure a non-biased shuffle (from https://www.frankmitchell.org/2015/01/fisher-yates/)
function shuffle (deck) {
  var currentIndex,
      randomIndex,
      tempValue;

  for (currentIndex = deck.length - 1; currentIndex > 0; currentIndex -= 1) {
    randomIndex = Math.floor(Math.random() * (currentIndex + 1));
    tempValue = deck[currentIndex];
    deck[currentIndex] = deck[randomIndex];
    deck[randomIndex] = tempValue;
  }
  return deck;
}

// Assign x number of cards to y number of players (get numbers from HTML input elements)
function deal() {

  // Shuffle the deck of cards returned from the deck() function, using the shuffle() function
  shuffledDeck = shuffle(deck());

  // Deal the cards using nested for loops, to loop through each player and each card that needs to be dealt
  var p,
      c,
      totalPlayers = document.getElementById("players").value, // get number from HTML input
      totalCards = document.getElementById("cards").value, // get number from HTML input
      game = []; // Create an object to contain all players' hands

  // Assuming that there have to be at least two players, and that there is only one deck of cards,
  // so if there are fewer than two players, and the number of players * the number of cards requested is above 52; display error message
  if ((totalPlayers >= 2) && ((totalPlayers * totalCards) <= 52)) {

    for (p = 0; p < totalPlayers; p++) {
      var hand = []; // Create an empty hand for the player
      for (c = 0; c < totalCards; c++) {
        // Add the top card of the deck to the player's hand
        hand.push(shuffledDeck[0]);
        // Delete the dealt card from the deck
        shuffledDeck.shift();
      }
      // Add each hand to the game array
      game.push(hand);
    }
    // Make the game array (containing all players' hands) available outside of the deal() function
    return game;
  } else {
    // If the criteria are not met; display an error message explaining which criteria are required to run the game
    var errorMessage = document.createElement("p"),
        errorAnnouncement = document.createTextNode("The game cannot be played using those criteria; please note that there are only 52 cards in the deck, and there needs to be at least two players to play the game.");
    errorMessage.appendChild(errorAnnouncement);
    document.getElementById("output").appendChild(errorMessage);
  }
}

// Score the cards of each player's hand, and return the value
function score() {

  var p,
      c,
      hands = deal(), // To ensure that the deal() function does not assign new values to the game array while executing the score() function >> Assign this array to a variable
      scores = [], // Create an empty array to contain each player's final score
      numOfPlayers = hands.length, // Calculate how many players' hands are within the game array
      numOfCards = hands[0].length; // Calculate how many cards each player has
                                     // (as each player has the same amount of cards, it is sufficient to calculate this for one of the players;
                                     // as there will always be at least one player, the first player is used to calculate this number)

  // Loop through each player's entire hand to calculate their final score
  for (p = 0; p < numOfPlayers; p++) {
    var score = 0; // Reset the score before calculating each player's score

    for (c = 0; c < numOfCards; c++) {
      score += hands[p][c].value; // Add up the total score of the cards in each player's hand
    }
    // Add each final score to the scores array
    scores.push(score);
  }
  // Make the scores array (containing all players' final scores) available outside of the score() function
  return scores;
}

function declareWinner() {
  var i,
      scores = score(),
      numOfScores = scores.length, // Calculate how many final scores there are to compare
      greatestValue = scores[0], // Create a variable to contain the current greatest value while comparing the scores, and assign the first score of the array to a variable
      draw = false, // Check whether there is a draw, rather than just one winner
      playerAnnouncement, // Create a variable to contain the "announcement" about each player's score
      winnerAnnouncement, // Create a variable to contain the announcement about the winner(s) of the game
      outputSection, // Create a variable to append the announcements to
      outputField = document.getElementById("output");

  // Loop through all of the final scores and compare them
  for (i = 0; i < numOfScores; i++) {

    // Announce the final score of each player on the page
    outputSection = document.createElement("p"); // Create a paragraph element to display the player announcement within
    playerAnnouncement = document.createTextNode("Player " + (i+1) + " has a score of " + scores[i]); // Update this variable to include the current player's number and score
    outputSection.appendChild(playerAnnouncement); // Append the announcement to the paragraph
    outputField.appendChild(outputSection); // Append the paragraph to the output section within the page

    // Compare each score of the array to the value of the variable:
    if (scores[i] === greatestValue) {
      draw = true; // If the current value is the same as the variable value; set draw to be true
                   // Don't need to update the greatestValue variable, as the values are the same
    } if (scores[i] > greatestValue) {
      greatestValue = scores[i]; // If the current score is greater than the variable value >> update the variable with the greater value
      draw = false; // Reset draw to false, in case a previous loop has set it to true
    } if (scores[i] < greatestValue) {
      draw = false; // Include this to avoid "false positives", ie it being declared a draw when there is only one winner
    }
  }

  // Once the loop has finished; find the winner
  if (draw === false) { // If there is no draw; find and declare the one winner
    var winner; // Create a variable to contain the number of the winning player

    winner = scores.indexOf(greatestValue); // Find the index of the winning value within the scores array, to find the number of the winning player
    winner += 1; // As zero indexing; use n+1 to find the number of the player

    // Display the winner announcement on the page
    outputSection = document.createElement("p"); // Create a paragraph element to display the player announcement within
    winnerAnnouncement = document.createTextNode("Player " + winner + " wins the game!"); // Assign the winner announcement to this variable
    outputSection.appendChild(winnerAnnouncement); // Append the announcement to the paragraph
    outputField.appendChild(outputSection); // Append the paragraph to the output section within the page

  } else if (draw === true) { // If there is a draw; find and declare both winners
    var winner1, // Create variables to contain the numbers of the winning players
        winner2;

    winner1 = scores.indexOf(greatestValue); // Look for the index of the first winner
    winner2 = scores.indexOf(greatestValue, winner1+1) // Start looking for the index of the second winner after the index of the first winner
    winner1 += 1; // As zero indexing; use n+1 to find the number of the players
    winner2 += 1; // As zero indexing; use n+1 to find the number of the players

    // Display the winner announcement on the page
    outputSection = document.createElement("p"); // Create a paragraph element to display the player announcement within
    winnerAnnouncement = document.createTextNode("It's a draw! Players " + winner1 + " and " + winner2 + " win the game!"); // Assign the winner announcement to this variable
    outputSection.appendChild(winnerAnnouncement); // Append the announcement to the paragraph
    outputField.appendChild(outputSection); // Append the paragraph to the output section within the page
  }
}

// Once the window has completed loading, let the user start the game by clicking the "Play the game" button
window.onload = function() {
  var startBtn = document.getElementById("startGameBtn");

  startBtn.addEventListener("click", (e) => {
    document.getElementById("output").innerHTML = ""; // Remove the previous game results from the page before starting a new game
    declareWinner(); // Run the game
  });
}


text:
'use strict'

import { stubArray } from 'lodash'
import { expect } from 'chai'
import index from './index'
import { generateTestToken, generateTestVersion } from './utils'

const API_METHODS = [
  'base',
  'createDesign', 'getDesign',
  'createForm', 'getForm',
  'createImage', 'getImage',
  'createURL', 'getURL', 'updateURL', 'deleteURL'
]

describe('API', () => {
  const TEST_TOKEN = generateTestToken()
  const TEST_VERSION = generateTestVersion()

  it('should exist', () => {
    expect(index).to.exist
  })

  it('should export method', () => {
    expect(index).to.be.a('function')
  })

  it('should require token string in method', () => {
    expect(() => index()).to.throw()
    expect(() => index(stubArray)).to.throw()
    expect(() => index(TEST_TOKEN)).not.to.throw()
  })

  it('should accept version string in method', () => {
    expect(() => index(TEST_TOKEN)).not.to.throw()
    expect(() => index(TEST_TOKEN, stubArray)).to.throw()
    expect(() => index(TEST_TOKEN, TEST_VERSION)).not.to.throw()
  })

  it('should return object from method', () => {
    expect(index(TEST_TOKEN)).to.be.an('object')
  })

  it('should contain all api methods in returned object', () => {
    expect(index(TEST_TOKEN)).to.have.all.keys([...API_METHODS, 'token', 'version'])
  })

  it('should return token property as defined', () => {
    const { token } = index(TEST_TOKEN)
    expect(token).to.equal(TEST_TOKEN)
  })

  it('should define version as \'latest\' if not defined', () => {
    const { version } = index(TEST_TOKEN)
    expect(version).to.equal('latest')
  })

  it('should prepend \'v\' to version if not defined as latest and not supplied', () => {
    expect(index(TEST_TOKEN, TEST_VERSION).version).to.equal(TEST_VERSION)
    expect(index(TEST_TOKEN, 'latest').version).to.equal('latest')
    expect(index(TEST_TOKEN, 'v0.4').version).to.equal('v0.4')
    expect(index(TEST_TOKEN, '0.4').version).to.equal('v0.4')
    expect(index(TEST_TOKEN, '2.0').version).to.equal('v2.0')
  })

})


text:
/**
 * Feature tester
 * @param {string} feature The feature to be testing for
 * @param {boolean} [forceObj] Force return value to be an object
 */
test.feature = function(feature, forceObj) {
    function returnValue(val) {
        return val || (forceObj ? {} : false);
    }

    if (feature === "class") {
        try {

            // Empty class test
            class EmptyClass {

            }

            // Class with contents test
            class FullClass {
                // Constructor test
                constructor() {

                }

                // Prototype test 1
                proto() {
                    return true;
                }

                // Prototype test 2
                proto2(value) {
                    return value;
                }
            }

            return returnValue(test.result(typeof EmptyClass === "function", [
                { name: "constructor", check: new FullClass() instanceof FullClass },
                { name: "proto", check: new FullClass().proto() === true },
                { name: "protoWithValue", check: new FullClass().proto2("test") === "test" }
            ]));
        } catch (e) {
            return returnValue();
        }
    }

    if (feature === "template literal") {
        try {
            var
                // Basic test
                basic = `basic`,

                // Multiline test
                multi = `multi
line`,

                // Template test
                template = `${"template"}`;

            return returnValue(test.result(basic === "basic", [
                { name: "multiline", check: multi === "multi\nline" },
                { name: "template", check: template === "template" }
            ]));
        } catch (e) {
            return returnValue();
        }
    }

    if (feature === "variable initializer") {
        var letValueOuter, constValueOuter;
        try {
            // Let test
            let letValue = "value"; letValueOuter = letValue;
        } catch (e) {
            letValueOuter = "false";
        }
        try {
            // Const test
            const constValue = "value";
            constValueOuter = constValue;
        } catch (e) {
            constValueOuter = "false";
        }

        return returnValue(test.result(true, [
            { name: "let", check: letValueOuter === "value" },
            { name: "const", check: constValueOuter === "value" }
        ]));
    }
};


text:
#include "matrixdef.h"

#include "codegenerator.h"
#include "clcodegenerator.h"
#include "formula.h"
#include "maximawrapper.h"
#include "transform.h"

// A hack for now, for inference we assume matrix is big
inline static petabricks::FormulaPtr LARGE(){
  return new petabricks::FormulaInteger(1000);
}

petabricks::MatrixDef::MatrixDef(const char* name, const FormulaList& version, const FormulaList& size)
  : _name(name), _version(version), _size(size), _type(T_UNKNOWN)
{}

void petabricks::MatrixDef::print(std::ostream& o) const {
  o << _name;
  if(!_version.empty()){
    o << '<';
    printStlList(o, _version.begin(), _version.end(), "..");
    o << '>';
  }
  if(!_size.empty()){
    o << '[';
    printStlList(o, _size.begin(), _size.end(), ", ");
    o << ']';
  }
}

void petabricks::MatrixDef::initialize(Transform& ){
  SRCPOSSCOPE();
//   _version.normalize();
//   _size.normalize();
  if(_version.size()>0){
    //TODO support for min region size
    JASSERT(_version.size()<=2);
    if(_version.size()==1){
      _version.insert(_version.begin(), FormulaInteger::zero());
    }
    JASSERT(_version[0]->getFreeVariables()->size()==0)(_version)
      .Text("Non constant minimum version size not yet supported");
    _size.push_back(_version.back()->plusOne());
  }
}

void petabricks::MatrixDef::exportConstants(Transform& trans){
  SRCPOSSCOPE();
  FreeVarsPtr tmp = _size.getFreeVariables();
  FreeVars::const_iterator i;
  for(i=tmp->begin(); i!=tmp->end(); ++i)
    trans.addSizeVar(*i);
}

void petabricks::MatrixDef::exportAssumptions(){
  SRCPOSSCOPE();
  for(FormulaList::const_iterator i=_size.begin(); i!=_size.end(); ++i){
    MaximaWrapper::instance().assume(new FormulaGT(*i, LARGE()));
  }
}

void petabricks::MatrixDef::argDeclRW(std::vector<std::string>& args, bool byRef) const {
  if(byRef)
    args.push_back("const "+matrixTypeName()+"& " + _name);
  else
    args.push_back("const "+matrixTypeName()+" " + _name);
}
void petabricks::MatrixDef::argDeclRO(std::vector<std::string>& args, bool byRef) const {
  if(byRef)
    args.push_back("const "+constMatrixTypeName()+"& " + _name);
  else
    args.push_back("const "+constMatrixTypeName()+" " + _name);
}
void petabricks::MatrixDef::genAllocTmpCode(CodeGenerator& o){
  o.varDecl(matrixTypeName()+" "+_name);
}
void petabricks::MatrixDef::generateCodeSimple(CodeGenerator& o){
  o.varDecl("Matrix" + jalib::XToString(_size.size()) + "D " + _name);
}
void petabricks::MatrixDef::extractDefines(FreeVars& defined, CodeGenerator& o){
  int d=0;
  for(FormulaList::const_iterator i=_size.begin(); i!=_size.end(); ++i,++d){
    FreeVarsPtr fv = (*i)->getFreeVariables();
    if(fv->size()==1){
      std::string var = *fv->begin();
      FormulaPtr tmp = FormulaVariable::mktmp();
      if(!defined.contains(var)){
        defined.insert(var);
        FormulaList l;
        l.push_back(new FormulaEQ(tmp, *i));
        l = *MaximaWrapper::instance().solve(l, var);
        JASSERT(l.size()==1)(*i)(var).Text("Failed to solve");
        o.addMember("IndexT", var, "");
        o.write(var + " = "
                + (*l.begin())->rhs()->replace(tmp, new FormulaVariable(_name+".size("+jalib::XToString(d)+")"))->toString()
                + ";");
      }
    }
  }
}

#ifdef HAVE_OPENCL
void petabricks::MatrixDef::extractCLDefines(FreeVars& defined, CLCodeGenerator& clo, unsigned int dims){
  unsigned int d=0;
  for(FormulaList::const_iterator i=_size.begin(); i!=_size.end(); ++i,++d){
    FreeVarsPtr fv = (*i)->getFreeVariables();
    if(fv->size()==1 && d < dims){
      std::string var = *fv->begin();
      FormulaPtr tmp = FormulaVariable::mktmp();
      if(!defined.contains(var)){
        defined.insert(var);
        FormulaList l;
        l.push_back(new FormulaEQ(tmp, *i));
        l = *MaximaWrapper::instance().solve(l, var);
        JASSERT(l.size()==1)(*i)(var).Text("Failed to solve");
        clo.os() << "unsigned int " << var << " = "
               << (*l.begin())->rhs()->replace(tmp, new FormulaVariable("dim_d"+jalib::XToString(d)))->toString() << ";\n";
      }
    }
  }
}
#endif

void petabricks::MatrixDef::verifyDefines(CodeGenerator& o){
  int d=0;
  for(FormulaList::const_iterator i=_size.begin(); i!=_size.end(); ++i,++d){
    o.addAssert((*i)->toString(), _name+".size("+jalib::XToString(d)+")");
  }
}
void petabricks::MatrixDef::allocateTemporary(CodeGenerator& o, bool setOnly, bool reallocAllowed){
  if(!setOnly)
    o.addMember(matrixTypeName(), name(), "");

  if(reallocAllowed)
    o.beginIf("!"+name()+".isSize("+_size.toString()+")");

  o.write(name()+" = "+allocateStr()+";");

  if(reallocAllowed)
    o.endIf();
}

std::string petabricks::MatrixDef::allocateStr() const{
  return matrixTypeName()+"::allocate("+_size.toString()+")";
}

void petabricks::MatrixDef::readFromFileCode(CodeGenerator& o, const std::string& fn){
  o.varDecl(name()
      +" = petabricks::MatrixIO("+fn+",\"r\").read<"+jalib::XToString(numDimensions())+">()");
}
void petabricks::MatrixDef::writeToFileCode(CodeGenerator& o, const std::string& fn){
  o.write("petabricks::MatrixIO("+fn+",\"w\").write("+name()+");");
}
void petabricks::MatrixDef::varDeclCodeRO(CodeGenerator& o){
  o.addMember(constMatrixTypeName(), name(), "");
}
void petabricks::MatrixDef::varDeclCodeRW(CodeGenerator& o){
  o.addMember(matrixTypeName(), name(), "");
}


text:
package de.sven_torben.cqrs.domain;

import java.io.Serializable;

/**
 * Marker interface for all messages (e.g. commands and events).
 */
public interface IAmAMessage extends Serializable {
}


text:
package de.fuberlin.wiwiss.d2rq.nodes;

import java.util.List;
import java.util.Set;

import com.hp.hpl.jena.datatypes.RDFDatatype;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.rdf.model.AnonId;

import de.fuberlin.wiwiss.d2rq.algebra.ColumnRenamer;
import de.fuberlin.wiwiss.d2rq.algebra.OrderSpec;
import de.fuberlin.wiwiss.d2rq.algebra.ProjectionSpec;
import de.fuberlin.wiwiss.d2rq.algebra.RelationalOperators;
import de.fuberlin.wiwiss.d2rq.expr.Expression;
import de.fuberlin.wiwiss.d2rq.pp.PrettyPrinter;
import de.fuberlin.wiwiss.d2rq.sql.ResultRow;
import de.fuberlin.wiwiss.d2rq.values.ValueMaker;

public class TypedNodeMaker implements NodeMaker {
	public final static NodeType URI = new URINodeType();
	public final static NodeType BLANK = new BlankNodeType();
	public final static NodeType PLAIN_LITERAL = new LiteralNodeType("", null);
	public final static NodeType XSD_DATE = new DateLiteralNodeType();
	public final static NodeType XSD_TIME = new TimeLiteralNodeType();
	public final static NodeType XSD_DATETIME = new DateTimeLiteralNodeType();
	public final static NodeType XSD_BOOLEAN = new BooleanLiteralNodeType();

	public static NodeType languageLiteral(String language) {
		return new LiteralNodeType(language, null);
	}
	public static NodeType typedLiteral(RDFDatatype datatype) {
		// TODO These subclasses can be abolished; just introduce an RDFDatatypeValidator instead
		if (datatype.equals(XSDDatatype.XSDdate)) {
			return XSD_DATE;
		}
		if (datatype.equals(XSDDatatype.XSDtime)) {
			return XSD_TIME;
		}
		if (datatype.equals(XSDDatatype.XSDdateTime)) {
			return XSD_DATETIME;
		}
		if (datatype.equals(XSDDatatype.XSDboolean)) {
			return XSD_BOOLEAN;
		}
		return new LiteralNodeType("", datatype);
	}

	private NodeType nodeType;
	private ValueMaker valueMaker;
	private boolean isUnique;

	public TypedNodeMaker(NodeType nodeType, ValueMaker valueMaker, boolean isUnique) {
		this.nodeType = nodeType;
		this.valueMaker = valueMaker;
		this.isUnique = isUnique;
	}

	public Set<ProjectionSpec> projectionSpecs() {
		return this.valueMaker.projectionSpecs();
	}

	public boolean isUnique() {
		return this.isUnique;
	}

	public void describeSelf(NodeSetFilter c) {
		this.nodeType.matchConstraint(c);
		this.valueMaker.describeSelf(c);
	}

	public ValueMaker valueMaker()
	{
		return this.valueMaker;
	}

	public Node makeNode(ResultRow tuple) {
		String value = this.valueMaker.makeValue(tuple);
		if (value == null) {
			return null;
		}
		return this.nodeType.makeNode(value);
	}

	public NodeMaker selectNode(Node node, RelationalOperators sideEffects) {
		if (node.equals(Node.ANY) || node.isVariable()) {
			return this;
		}
		if (!this.nodeType.matches(node)) {
			return NodeMaker.EMPTY;
		}
		String value = this.nodeType.extractValue(node);
		if (value == null) {
			return NodeMaker.EMPTY;
		}
		Expression expr = valueMaker.valueExpression(value);
		if (expr.isFalse()) {
			sideEffects.select(Expression.FALSE);
			return NodeMaker.EMPTY;
		}
		sideEffects.select(expr);
		return new FixedNodeMaker(node, isUnique());
	}

	public NodeMaker renameAttributes(ColumnRenamer renamer) {
		return new TypedNodeMaker(this.nodeType,
				this.valueMaker.renameAttributes(renamer), this.isUnique);
	}

	public List<OrderSpec> orderSpecs(boolean ascending) {
		// TODO: Consider the node type (e.g., RDF datatype) in ordering,
		//       rather than just deferring to the underlying value maker
		return valueMaker.orderSpecs(ascending);
	}

	public String toString() {
		return this.nodeType.toString() + "(" + this.valueMaker + ")";
	}

	public interface NodeType {
		String extractValue(Node node);
		Node makeNode(String value);
		void matchConstraint(NodeSetFilter c);
		boolean matches(Node node);
	}

	private static class URINodeType implements NodeType {
		public String extractValue(Node node) { return node.getURI(); }
		public Node makeNode(String value) { return Node.createURI(value); }
		public void matchConstraint(NodeSetFilter c) { c.limitToURIs(); }
		public boolean matches(Node node) { return node.isURI(); }
		public String toString() { return "URI"; }
	}

	private static class BlankNodeType implements NodeType {
		public String extractValue(Node node) { return node.getBlankNodeLabel(); }
		public Node makeNode(String value) { return Node.createAnon(new AnonId(value)); }
		public void matchConstraint(NodeSetFilter c) { c.limitToBlankNodes(); }
		public boolean matches(Node node) { return node.isBlank(); }
		public String toString() { return "Blank"; }
	}

	private static class LiteralNodeType implements NodeType {
		private String language;
		private RDFDatatype datatype;
		LiteralNodeType(String language, RDFDatatype datatype) {
			this.language = language;
			this.datatype = datatype;
		}
		public String extractValue(Node node) {
			return node.getLiteralLexicalForm();
		}
		public Node makeNode(String value) {
			return Node.createLiteral(value, this.language, this.datatype);
		}
		public void matchConstraint(NodeSetFilter c) {
	        c.limitToLiterals(this.language, this.datatype);
		}
		public boolean matches(Node node) {
			return node.isLiteral()
					&& this.language.equals(node.getLiteralLanguage())
					&& ((this.datatype == null && node.getLiteralDatatype() == null)
							|| (this.datatype != null && this.datatype.equals(node.getLiteralDatatype())));
		}
		public String toString() {
			StringBuffer result = new StringBuffer("Literal");
			if (!"".equals(this.language)) {
				result.append("@" + this.language);
			}
			if (this.datatype != null) {
				result.append("^^");
				result.append(PrettyPrinter.toString(this.datatype));
			}
			return result.toString();
		}
	}

	private static class DateLiteralNodeType extends LiteralNodeType {
		DateLiteralNodeType() {
			super("", XSDDatatype.XSDdate);
		}
		public boolean matches(Node node) {
			return super.matches(node) && XSDDatatype.XSDdate.isValid(node.getLiteralLexicalForm());
		}
		public Node makeNode(String value) {
			if (!XSDDatatype.XSDdate.isValid(value)) return null;
			return Node.createLiteral(value, null, XSDDatatype.XSDdate);
		}
	}

	private static class TimeLiteralNodeType extends LiteralNodeType {
		TimeLiteralNodeType() {
			super("", XSDDatatype.XSDtime);
		}
		public boolean matches(Node node) {
			return super.matches(node) && XSDDatatype.XSDtime.isValid(node.getLiteralLexicalForm());
		}
		public Node makeNode(String value) {
			if (!XSDDatatype.XSDtime.isValid(value)) return null;
			return Node.createLiteral(value, null, XSDDatatype.XSDtime);
		}
	}

	private static class DateTimeLiteralNodeType extends LiteralNodeType {
		DateTimeLiteralNodeType() {
			super("", XSDDatatype.XSDdateTime);
		}
		public boolean matches(Node node) {
			return super.matches(node) && XSDDatatype.XSDdateTime.isValid(node.getLiteralLexicalForm());
		}
		public Node makeNode(String value) {
			if (!XSDDatatype.XSDdateTime.isValid(value)) return null;
			return Node.createLiteral(value, null, XSDDatatype.XSDdateTime);
		}
	}

	private static class BooleanLiteralNodeType extends LiteralNodeType {
		private final static Node TRUE = Node.createLiteral("true", null, XSDDatatype.XSDboolean);
		private final static Node FALSE = Node.createLiteral("false", null, XSDDatatype.XSDboolean);
		BooleanLiteralNodeType() {
			super("", XSDDatatype.XSDboolean);
		}
		public boolean matches(Node node) {
			return super.matches(node) && XSDDatatype.XSDboolean.isValid(node.getLiteralLexicalForm());
		}
		public Node makeNode(String value) {
			if ("0".equals(value) || "false".equals(value)) return FALSE;
			if ("1".equals(value) || "true".equals(value)) return TRUE;
			return null;
		}
	}
}


text:
"""
Resource object
"""

from oslo_config import cfg
from oslo_serialization import jsonutils
from oslo_versionedobjects import base
from oslo_versionedobjects import fields
import six

from heat.common import crypt
from heat.db import api as db_api
from heat.objects import fields as heat_fields
from heat.objects import resource_data
from heat.objects import stack

cfg.CONF.import_opt('encrypt_parameters_and_properties', 'heat.common.config')

class Resource(
    base.VersionedObject,
    base.VersionedObjectDictCompat,
    base.ComparableVersionedObject,
):
    fields = {
        'id': fields.IntegerField(),
        'uuid': fields.StringField(),
        'stack_id': fields.StringField(),
        'created_at': fields.DateTimeField(read_only=True),
        'updated_at': fields.DateTimeField(nullable=True),
        'nova_instance': fields.StringField(nullable=True),
        'name': fields.StringField(nullable=True),
        'status': fields.StringField(nullable=True),
        'status_reason': fields.StringField(nullable=True),
        'action': fields.StringField(nullable=True),
        'rsrc_metadata': heat_fields.JsonField(nullable=True),
        'properties_data': heat_fields.JsonField(nullable=True),
        'properties_data_encrypted': fields.BooleanField(default=False),
        'data': fields.ListOfObjectsField(
            resource_data.ResourceData,
            nullable=True
        ),
        'stack': fields.ObjectField(stack.Stack),
        'engine_id': fields.StringField(nullable=True),
        'atomic_key': fields.IntegerField(nullable=True),
        'current_template_id': fields.IntegerField(),
        'needed_by': heat_fields.ListField(nullable=True, default=None),
        'requires': heat_fields.ListField(nullable=True, default=None),
        'replaces': fields.IntegerField(nullable=True),
        'replaced_by': fields.IntegerField(nullable=True),
    }

    @staticmethod
    def _from_db_object(resource, context, db_resource):
        if db_resource is None:
            return None
        for field in resource.fields:
            if field == 'data':
                resource['data'] = map(
                    lambda resd: resource_data.ResourceData._from_db_object(
                        resource_data.ResourceData(context), resd
                    ),
                    db_resource.data
                )
            else:
                resource[field] = db_resource[field]

        if resource.properties_data_encrypted and resource.properties_data:
            properties_data = {}
            for prop_name, prop_value in resource.properties_data.items():
                method, value = prop_value
                decrypted_value = crypt.decrypt(method, value)
                prop_string = jsonutils.loads(decrypted_value)
                properties_data[prop_name] = prop_string
            resource.properties_data = properties_data

        resource._context = context
        resource.obj_reset_changes()
        return resource

    @classmethod
    def get_obj(cls, context, resource_id):
        resource_db = db_api.resource_get(context, resource_id)
        return cls._from_db_object(cls(context), context, resource_db)

    @classmethod
    def get_all(cls, context):
        resources_db = db_api.resource_get_all(context)
        resources = [
            (
                resource_name,
                cls._from_db_object(cls(context), context, resource_db)
            )
            for resource_name, resource_db in six.iteritems(resources_db)
        ]
        return dict(resources)

    @classmethod
    def create(cls, context, values):
        return cls._from_db_object(cls(context), context,
                                   db_api.resource_create(context, values))

    @classmethod
    def delete(cls, context, resource_id):
        resource_db = db_api.resource_get(context, resource_id)
        resource_db.delete()

    @classmethod
    def exchange_stacks(cls, context, resource_id1, resource_id2):
        return db_api.resource_exchange_stacks(
            context,
            resource_id1,
            resource_id2)

    @classmethod
    def get_all_by_stack(cls, context, stack_id):
        resources_db = db_api.resource_get_all_by_stack(context, stack_id)
        resources = [
            (
                resource_name,
                cls._from_db_object(cls(context), context, resource_db)
            )
            for resource_name, resource_db in six.iteritems(resources_db)
        ]
        return dict(resources)

    @classmethod
    def get_by_name_and_stack(cls, context, resource_name, stack_id):
        resource_db = db_api.resource_get_by_name_and_stack(
            context,
            resource_name,
            stack_id)
        return cls._from_db_object(cls(context), context, resource_db)

    @classmethod
    def get_by_physical_resource_id(cls, context, physical_resource_id):
        resource_db = db_api.resource_get_by_physical_resource_id(
            context,
            physical_resource_id)
        return cls._from_db_object(cls(context), context, resource_db)

    def update_and_save(self, values):
        resource_db = db_api.resource_get(self._context, self.id)
        resource_db.update_and_save(values)
        return self._refresh()

    def select_and_update(self, values, expected_engine_id=None,
                          atomic_key=0):
        return db_api.resource_update(self._context, self.id, values,
                                      atomic_key=atomic_key,
                                      expected_engine_id=expected_engine_id)

    def _refresh(self):
        return self.__class__._from_db_object(
            self,
            self._context,
            self.__class__.get_obj(self._context, self.id))

    def refresh(self, attrs=None):
        resource_db = db_api.resource_get(self._context, self.id)
        resource_db.refresh(attrs=attrs)
        return self._refresh()

    @staticmethod
    def encrypt_properties_data(data):
        if cfg.CONF.encrypt_parameters_and_properties and data:
            result = {}
            for prop_name, prop_value in data.items():
                prop_string = jsonutils.dumps(prop_value)
                encrypted_value = crypt.encrypt(prop_string)
                result[prop_name] = encrypted_value
            return (True, result)
        return (False, data)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="2dip"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/grdiViewimageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:scaleType="fitXY"
        android:background="#fff"
        android:src="@drawable/itempdf"
        android:elevation="15dp"/>

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textColor="@color/black"
        android:singleLine="true"
        android:gravity="center"
        android:text="b" />

</LinearLayout>


text:
'use strict';

/**
 * @memberof CollaborativeMap
 * @fileOverview Chat directive. Provides the GUI functionality as well as the WebSocket connection for the chat.
 * @exports CollaborativeMap.chat
 * @author Dennis Wilhelm
 */
angular.module('CollaborativeMap')
  .directive('chatMessage', ['MapHandler', '$compile',
    function(MapHandler, $compile) {
      return {
        template: '

',
        restrict: 'E',
        scope: {
          message: '='
        },
        link: function postLink(scope, element) {

          function exchangeFid() {
            var index = message.indexOf('#');
            if (index > -1) {
              var fidString = message.substring(index).split(' ')[0];
              message = createButton(fidString);
            }
            if (message.indexOf('#') > -1) {
              exchangeFid();
            }
          }

          function createButton(fidString) {
            var fid = fidString.substring(1);
            var className = getClassForFeature(fid);
            if (className) {
              return message.replace(fidString, '

 ');
            } else {
              return fidString;
            }
          }

          function getClassForFeature(fid) {
            var type = MapHandler.getLayerTypeFid(fid);
            if (type === 'point') {
              return 'markerFeature';
            } else if (type === 'line') {
              return 'lineFeature';
            } else if (type === 'area') {
              return 'polygonFeature';
            } else {
              return false;
            }
          }

          scope.panToFeature = function(fid) {
            MapHandler.panToFeature(fid);
            MapHandler.highlightFeatureId(fid);
          };

          var message = '';
          if (scope.message && scope.message.message) {
            message = scope.message.message;
          }

          message = message.replace(/


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.friend;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author padmanava
 */
public class SendMessage extends HttpServlet {

    /**
     * Processes requests for both HTTP GET and POST methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try
        {
           HttpSession session=request.getSession();
           String send_from = (String)session.getAttribute("userid");

           String send_to = request.getParameter("sendto");
           String subject = request.getParameter("subject");
           String message = request.getParameter("message");

           Connection con = DBConnection.getConnection();
           String sql = "insert into message(send_to,send_from,subject,message,message_date,status) values(?,?,?,?,?,?)";
           PreparedStatement ps = con.prepareStatement(sql);
           ps.setString(1, send_to);
           ps.setString(2, send_from);
           ps.setString(3,subject);
           ps.setString(4, message);
           ps.setString(5, DateTime.sysDateTime());
           ps.setString(6, "New");
           ps.executeUpdate();

           RequestDispatcher rd = getServletContext().getRequestDispatcher("/Send_Message.jsp");
           rd.forward(request, response);

        }
        catch(Exception e1)
        {
            e1.printStackTrace();;
        }
        finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP GET method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP POST method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}