text:
<project name="KBaseKnowledgeEngine" default="compile" basedir=".">

  <description>
      Build JAR and WAR files for KBaseKnowledgeEngine
  </description>

  <!-- set global properties for this build -->
  <property name="src" location="lib/src"/>
  <property name="test.src" location="test/src"/>
  <property name="dist" location="dist"/>
  <property name="classes" location="classes"/>
  <property name="bin" location="bin"/>
  <property name="jar.file" value="KBaseKnowledgeEngine.jar"/>
  <property name="jars.dir" value="/kb/deployment/lib/jars"/>
  <property name="war.file" value="KBaseKnowledgeEngine.war"/>
  <property name="scripts" location="scripts"/>
  <property name="web.xml" location="${scripts}/web.xml"/>
  <property name="exec.cmd.file" value="run_KBaseKnowledgeEngine_async_job.sh"/>
  <property name="startup.cmd.file" value="start_server.sh"/>

  <fileset dir="${jars.dir}" id="lib">
    <include name="ini4j/ini4j-0.5.2.jar"/>
    <include name="jackson/jackson-annotations-2.2.3.jar"/>
    <include name="jackson/jackson-core-2.2.3.jar"/>
    <include name="jackson/jackson-databind-2.2.3.jar"/>
    <include name="jetty/jetty-all-7.0.0.jar"/>
    <include name="jna/jna-3.4.0.jar"/>
    <include name="joda/joda-time-2.2.jar"/>
    <include name="junit/junit-4.9.jar"/>
    <include name="kbase/auth/kbase-auth-0.4.4.jar"/>
    <include name="kbase/common/kbase-common-0.0.23.jar"/>
    <include name="logback/logback-core-1.1.2.jar"/>
    <include name="logback/logback-classic-1.1.2.jar"/>
    <include name="servlet/servlet-api-2.5.jar"/>
    <include name="slf4j/slf4j-api-1.7.7.jar"/>
    <include name="syslog4j/syslog4j-0.9.46.jar"/>
    <include name="kbase/workspace/WorkspaceClient-0.6.0.jar"/>
    <include name="apache_commons/commons-io-2.4.jar"/>
    <include name="mongo/mongo-java-driver-2.13.3.jar"/>
  	<include name="jongo/jongo-0.5-early-20130912-1506.jar"/>
  	<include name="bson4jackson/bson4jackson-2.2.0-2.2.0.jar"/>
  </fileset>

  <path id="compile.classpath">
    <fileset refid="lib"/>
  </path>

  <path id="src.path">
    <pathelement location="${src}" />
    <pathelement location="${test.src}" />
  </path>

  <target name="compile" description="compile the source">
    <mkdir dir="${classes}"/>
    <mkdir dir="${dist}"/>
    <exec executable="git" outputproperty="git.url"><arg line="config --get remote.origin.url"/></exec>
    <exec executable="git" outputproperty="git.branch"><arg line="rev-parse --abbrev-ref HEAD"/></exec>
    <exec executable="git" outputproperty="git.commit"><arg line="rev-parse HEAD"/></exec>
    <echo file="${src}/git.properties">giturl=${git.url}
branch=${git.branch}
commit=${git.commit}</echo>
    <!-- Compile class files-->
    <javac destdir="${classes}" includeantruntime="false"
            target="1.8" source="1.8" debug="true"
            classpathref="compile.classpath" compiler="modern">
      <src refid="src.path"/>
    </javac>
    <!-- Copy resource files-->
    <copy todir="${classes}">
      <fileset dir="${src}">
      </fileset>
    </copy>
    <jar destfile="${dist}/${jar.file}" basedir="${classes}"/>
    <delete dir="${classes}"/>
  </target>

  <target name="war" depends="compile" description="build the WAR file. Assumes compile has been run">
    <!-- make the war file for the server-->
    <mkdir dir="${dist}/lib"/>
    <copy todir="${dist}/lib/" flatten="true">
      <fileset refid="lib"/>
      <resources>
        <file file="${dist}/${jar.file}"/>
      </resources>
    </copy>
    <war destfile="${dist}/${war.file}" webxml="${web.xml}">
      <lib dir="${dist}/lib/"/>
    </war>
    <delete dir="${dist}/lib"/>
    <mkdir dir="${scripts}/webapps"/>
    <copy file="${dist}/${war.file}" tofile="${scripts}/webapps/root.war"/>
  </target>

  <target name="build-executable-script" description="create command-line script">
    <mkdir dir="${bin}"/>
    <property name="jar.absolute.path" location="${dist}/${jar.file}"/>
    <pathconvert targetos="unix" property="lib.classpath" refid="compile.classpath"/>
    <echo file="${bin}/${exec.cmd.file}">#!/bin/bash
java -cp ${jar.absolute.path}:${lib.classpath} kbaseknowledgeengine.KBaseKnowledgeEngineServer $1 $2 $3
    </echo>
    <chmod file="${bin}/${exec.cmd.file}" perm="a+x"/>
  </target>

  <target name="test" description="run all tests">
    <junit printsummary="yes" haltonfailure="yes" fork="true">
      <classpath>
        <pathelement location="${dist}/${jar.file}"/>
        <path refid="compile.classpath"/>
      </classpath>
      <formatter type="plain" usefile="false" />
      <batchtest>
        <fileset dir="${test.src}">
          <include name="**/test/**Test.java"/>
        </fileset>
      </batchtest>
    </junit>
  </target>
</project>


text:
<!DOCTYPE html>

    <title>jQuery WeUI</title>
    <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

<meta name="description" content="Write an awesome description for your new site here. You can edit this line in _config.yml. It will appear in your document head meta (for Google search results) and in your feed.xml site description.
">

<link rel="stylesheet" href="{{static_url('jquery-weui/weui.min.css')}}">
<link rel="stylesheet" href="{{static_url('jquery-weui/jquery-weui.css')}}">
<link rel="stylesheet" href="{{static_url('jquery-weui/css/demos.css')}}">

redpajama_set_name: RedPajamaGithub


text:
@implementation THSettingItem

+ (instancetype)itemWithTitle:(NSString *)title{
    THSettingItem *item = [[THSettingItem alloc] init];
    item.title = title;
    return item;
}

@end


text:
load("test/mjsunit/wasm/wasm-constants.js");
load("test/mjsunit/wasm/wasm-module-builder.js");

function assertMemoryIsValid(memory, shared) {
  assertSame(WebAssembly.Memory.prototype, memory.__proto__);
  assertSame(WebAssembly.Memory, memory.constructor);
  assertTrue(memory instanceof Object);
  assertTrue(memory instanceof WebAssembly.Memory);
  if (shared) {
    assertTrue(memory.buffer instanceof SharedArrayBuffer);
    // Assert that the buffer is frozen when memory is shared.
    assertTrue(Object.isFrozen(memory.buffer));
  }
}

(function TestConstructorWithShared() {
  print("TestConstructorWithShared");
  let memory = new WebAssembly.Memory({
    initial: 0, maximum: 10, shared: true});
  assertMemoryIsValid(memory, true);
})();

(function TestConstructorWithUndefinedShared() {
  print("TestConstructorWithUndefinedShared");
  // Maximum = undefined, shared = undefined.
  let memory = new WebAssembly.Memory({
    initial: 0, maximum: undefined, shared: undefined});
  assertMemoryIsValid(memory);
})();

(function TestConstructorWithNumericShared() {
  print("TestConstructorWithNumericShared");
  // For numeric values, shared = true.
  let memory = new WebAssembly.Memory({
    initial: 0, maximum: 10, shared: 2098665});
  assertMemoryIsValid(memory, true);
})();

(function TestConstructorWithEmptyStringShared() {
  print("TestConstructorWithEmptyStringShared");
  // Maximum = undefined, shared = false.
  let memory = new WebAssembly.Memory({
    initial: 0, maximum: undefined, shared: ""});
  assertMemoryIsValid(memory);
})();

(function TestConstructorWithUndefinedMaxShared() {
  print("TestConstructorWithUndefinedMaxShared");
  // New memory with Maximum = undefined, shared = true => TypeError.
  assertThrows(() => new WebAssembly.Memory({initial: 0, shared: true}),
      TypeError);
})();

(function TestCompileWithUndefinedShared() {
  print("TestCompileWithUndefinedShared");
  let memory = new WebAssembly.Memory({
    initial: 0, maximum: 10, shared: true});
  let builder = new WasmModuleBuilder();
  builder.addImportedMemory("m", "imported_mem", 0, undefined, "shared");
  assertThrows(() => new WebAssembly.Module(builder.toBuffer()),
       WebAssembly.CompileError);
})();

(function TestCompileAtomicOpUndefinedShared() {
  print("TestCompileAtomicOpUndefinedShared");
  let memory = new WebAssembly.Memory({
    initial: 0, maximum: 10, shared: true});
  let builder = new WasmModuleBuilder();
  builder.addFunction("main", kSig_i_ii)
    .addBody([
      kExprGetLocal, 0,
      kExprGetLocal, 1,
      kAtomicPrefix,
      kExprI32AtomicAdd]);
  builder.addImportedMemory("m", "imported_mem");
  assertThrows(() => new WebAssembly.Module(builder.toBuffer()),
       WebAssembly.CompileError);
})();

(function TestInstantiateWithUndefinedShared() {
  print("TestInstantiateWithUndefinedShared");
  let memory = new WebAssembly.Memory({
    initial: 0, maximum: 10, shared: true});
  let builder = new WasmModuleBuilder();
  builder.addImportedMemory("m", "imported_mem");
  let module = new WebAssembly.Module(builder.toBuffer());
  assertThrows(() => new WebAssembly.Instance(module,
         {m: {imported_mem: memory}}), WebAssembly.LinkError);
})();

(function TestInstantiateWithImportNotSharedDefined() {
  print("TestInstantiateWithImportNotSharedDefined");
  let memory = new WebAssembly.Memory({
    initial: 0, maximum: 10, shared: false});
  let builder = new WasmModuleBuilder();
  builder.addImportedMemory("m", "imported_mem", 0, 10, "shared");
  let module = new WebAssembly.Module(builder.toBuffer());
  assertThrows(() => new WebAssembly.Instance(module,
         {m: {imported_mem: memory}}), WebAssembly.LinkError);
})();

(function TestInstantiateWithSharedDefined() {
  print("TestInstantiateWithSharedDefined");
  let builder = new WasmModuleBuilder();
  builder.addMemory(2, 10, true, "shared");
  let module = new WebAssembly.Module(builder.toBuffer());
  let instance = new WebAssembly.Instance(module);
  assertMemoryIsValid(instance.exports.memory, true);
})();

(function TestAtomicOpWithSharedMemoryDefined() {
  print("TestAtomicOpWithSharedMemoryDefined");
  let builder = new WasmModuleBuilder();
  builder.addMemory(2, 10, false, "shared");
  builder.addFunction("main", kSig_i_ii)
    .addBody([
      kExprGetLocal, 0,
      kExprGetLocal, 1,
      kAtomicPrefix,
      kExprI32AtomicAdd, 2, 0])
    .exportFunc();
  let module = new WebAssembly.Module(builder.toBuffer());
  let instance = new WebAssembly.Instance(module);
  assertEquals(0, instance.exports.main(0, 0x11111111));
  assertEquals(0x11111111, instance.exports.main(0, 0x11111111));
})();


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Threading;

namespace gov.va.medora.mdo.dao
{
    public class MultiSourceQuery
    {
        IndexedHashtable cxnTable = new IndexedHashtable();

	    public MultiSourceQuery(DataSource[] sources)
	    {
		    addConnections(sources);
	    }

        public MultiSourceQuery(IndexedHashtable cxnTable)
        {
            this.cxnTable = cxnTable;
        }

        public IndexedHashtable ConnectionTable
        {
            get { return cxnTable; }
        }

        public void addConnections(DataSource[] sources)
        {
            for (int i = 0; i < sources.Length; i++)
            {
                if (cxnTable.ContainsKey(sources[i].SiteId.Key))
                {
                    continue;
                }
                int protocol = DaoFactory.getConstant(sources[i].Protocol);
                DaoFactory daoFactory = DaoFactory.getDaoFactory(protocol);
                cxnTable.Add(sources[i].SiteId.Key, daoFactory.getConnection(sources[i]));
            }
        }

        public void addConnections(MultiSourceQuery msq2)
        {
            for (int i = 0; i < msq2.cxnTable.Count; i++)
            {
                if (!this.cxnTable.ContainsKey((string)msq2.cxnTable.GetKey(i)))
                {
                    this.cxnTable.Add(msq2.cxnTable.GetKey(i), msq2.cxnTable.GetValue(i));
                }
            }
        }

        public int Count
        {
            get { return cxnTable.Count; }
        }

        public bool siteIsConnected(String sitecode)
        {
            return cxnTable.ContainsKey(sitecode);
        }

        public Connection getConnection(String sitecode)
        {
            if (!siteIsConnected(sitecode))
            {
                throw new Exception("Site is not connected");
            }
            return (Connection)cxnTable.GetValue(sitecode);
        }

        public Connection getConnection(int idx)
        {
            if (cxnTable.Count < (idx + 1))
            {
                throw new Exception("No such connection");
            }
            return (Connection)cxnTable.GetValue(idx);
        }

        public String getDefaultSiteId()
        {
            return (String)cxnTable.GetKey(0);
        }

        public IndexedHashtable connect()
        {
            int lth = cxnTable.Count;
            QueryThread[] queries = new QueryThread[lth];
            Thread[] threads = new Thread[lth];
            for (int i = 0; i < lth; i++)
            {
                queries[i] = new QueryThread(cxnTable.GetValue(i), "connect", new Object[0]);
                //queries[i].execute();
                threads[i] = new Thread(new ThreadStart(queries[i].execute));
                threads[i].Start();
            }
            IndexedHashtable result = new IndexedHashtable(lth);
            for (int i = 0; i < lth; i++)
            {
                string key = (string)cxnTable.GetKey(i);
                threads[i].Join();

                //Need to report result whether it's a connection or an exception.
                if (queries[i].isExceptionResult())
                {
                    result.Add(key,queries[i].Result);
                }
                else
                {
                    result.Add(key,((Connection)cxnTable.GetValue(key)).DataSource);
                }
            }

            //Now for all the results that failed to connect, we remove them from the connection table.
            for (int i = 0; i < lth; i++)
            {
                if (queries[i].isExceptionResult())
                {
                    string key = (string)cxnTable.GetKey(i);
                    cxnTable.Remove(key);
                    cxnTable.Add(key, queries[i].Result);
                }
            }
            return result;
        }

	    public IndexedHashtable disconnect()
	    {
            int lth = cxnTable.Count;
            QueryThread[] queries = new QueryThread[lth];
            Thread[] threads = new Thread[lth];
            for (int i = 0; i < lth; i++)
            {
                queries[i] = new QueryThread(cxnTable.GetValue(i), "disconnect", new Object[0]);
                threads[i] = new Thread(new ThreadStart(queries[i].execute));
                threads[i].Start();
            }
            IndexedHashtable result = new IndexedHashtable(lth);
            for (int i = 0; i < lth; i++)
            {
                string key = (string)cxnTable.GetKey(i);
                threads[i].Join();
                if (queries[i].isExceptionResult())
                {
                    result.Add(key, queries[i].Result);
                }
                else
                {
                    result.Add(key, "OK");
                }
            }
            cxnTable.Clear();
            return result;
        }

        public IndexedHashtable disconnectRemoteSites()
        {
            int lth = cxnTable.Count - 1;
            if (lth <= 0)
            {
                return null;
            }
            QueryThread[] queries = new QueryThread[lth];
            Thread[] threads = new Thread[lth];
            for (int i = 0; i < lth; i++)
            {
                queries[i] = new QueryThread(cxnTable.GetValue(i+1), "disconnect", new Object[0]);
                threads[i] = new Thread(new ThreadStart(queries[i].execute));
                threads[i].Start();
            }
            IndexedHashtable result = new IndexedHashtable(lth);
            for (int i = 0; i < lth; i++)
            {
                string key = (string)cxnTable.GetKey(i + 1);
                threads[i].Join();
                if (queries[i].isExceptionResult())
                {
                    result.Add(key, queries[i].Result);
                }
                else
                {
                    result.Add(key, "OK");
                }
            }
            for (int i = 0; i < result.Count; i++)
            {
                cxnTable.Remove(result.GetKey(i));
            }
            return result;
        }

        public IndexedHashtable execute(String daoName, String methodName, Object[] args)
	    {
            int lth = cxnTable.Count;
		    QueryThread[] queries = new QueryThread[lth];
            Thread[] threads = new Thread[lth];
            for (int i = 0; i < lth; i++)
		    {
                if (cxnTable.GetValue(i).GetType().IsAssignableFrom(typeof(Exception)))
                {
                    continue;
                }
                Object dao = ((Connection)cxnTable.GetValue(i)).getDao(daoName);
                queries[i] = new QueryThread(dao, methodName, args);
                threads[i] = new Thread(new ThreadStart(queries[i].execute));
                threads[i].Start();
            }
            IndexedHashtable result = new IndexedHashtable(cxnTable.Count);
            for (int i=0; i<threads.Length; i++)
            {
                if (cxnTable.GetValue(i).GetType().IsAssignableFrom(typeof(Exception)))
                {
                    result.Add((string)cxnTable.GetKey(i),(Exception)cxnTable.GetValue(i));
                    continue;
                }
                try
                {
				    threads[i].Join();
                    result.Add((String)cxnTable.GetKey(i), queries[i].Result);
                }
                catch (Exception)
                {
                    //throw new MdoException(e);
                }
		    }
		    return result;
	    }

        public Dictionary<string, object> debug(String daoName, String methodName, Object[] args)
        {
            int lth = cxnTable.Count;
            QueryThread[] queries = new QueryThread[lth];
            Dictionary<string, object> result = new Dictionary<string, object>(cxnTable.Count);
            for (int i = 0; i < lth; i++)
            {
                Object dao = ((Connection)cxnTable.GetValue(i)).getDao(daoName);
                queries[i] = new QueryThread(cxnTable.GetValue(i), methodName, args);
                queries[i].execute();
                result.Add((String)cxnTable.GetKey(i), queries[i].Result);
            }
            return result;
        }

        public static IndexedHashtable execute2(IndexedHashtable cxnTable, string daoName, string methodName, Object[] args)
        {
            if (cxnTable == null || cxnTable.Count == 0)
            {
                throw new Exception("No connections!");
            }
            int lth = cxnTable.Count;
            QueryThread[] queries = new QueryThread[lth];
            Thread[] threads = new Thread[lth];
            for (int i = 0; i < lth; i++)
            {
                if (cxnTable.GetValue(i).GetType().IsAssignableFrom(typeof(Exception)))
                {
                    continue;
                }
                Connection cxn = (Connection)cxnTable.GetValue(i);
                if (!cxn.IsConnected)
                {
                    continue;
                }
                Object dao = ((Connection)cxnTable.GetValue(i)).getDao(daoName);
                if (dao == null)
                {
                    continue;
                }
                queries[i] = new QueryThread(dao, methodName, args);
                threads[i] = new Thread(new ThreadStart(queries[i].execute));
                threads[i].Start();
            }
            IndexedHashtable result = new IndexedHashtable(cxnTable.Count);
            for (int i = 0; i < threads.Length; i++)
            {
                if (cxnTable.GetValue(i).GetType().IsAssignableFrom(typeof(Exception)))
                {
                    result.Add((string)cxnTable.GetKey(i), (Exception)cxnTable.GetValue(i));
                    continue;
                }
                Connection cxn = (Connection)cxnTable.GetValue(i);
                if (!cxn.IsConnected)
                {
                    result.Add((string)cxnTable.GetKey(i), new Exception("Source is not connected"));
                    continue;
                }
                Object dao = ((Connection)cxnTable.GetValue(i)).getDao(daoName);
                if (dao == null)
                {
                    result.Add((string)cxnTable.GetKey(i), new Exception("Invalid dao: " + daoName));
                    continue;
                }
                threads[i].Join();
                result.Add((String)cxnTable.GetKey(i), queries[i].Result);
            }
            return result;
        }

    }
}


text:
package org.apache.rave.rest.impl;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.rave.portal.service.UserService;
import org.apache.rave.rest.PageUsersResource;
import org.apache.rave.rest.exception.ResourceNotFoundException;
import org.apache.rave.portal.service.PageService;
import org.apache.rave.rest.PagesResource;
import org.apache.rave.rest.RegionsResource;
import org.apache.rave.rest.exception.BadRequestException;
import org.apache.rave.rest.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DefaultPageResource implements PagesResource {

    public static final String SELF = "@self";

    private Logger logger = LoggerFactory.getLogger(getClass());
    private PageService pageService;

    private DefaultRegionsResource regionsResouce;
    private DefaultPageUsersResource pageUsersResource;
    private UserService userService;

    @Override
    public SearchResult<Page> getPages() {
        SearchResult<org.apache.rave.model.Page> fromDb = pageService.getAll();
        return convert(fromDb.getResultSet(), fromDb.getTotalResults());
    }

    @Override
    public SearchResult<Page> getContextPages(String context, String identifier) {
        String contextId = identifier.equals(SELF) ? userService.getAuthenticatedUser().getId() : identifier;
        //TODO Replace when handling supports page member handling as a special case RAVE-1044
        List<org.apache.rave.model.Page> pages;
        try {
            if ("portal".equals(context)) {
                pages = pageService.getAllUserPages(contextId);
            } else if ("profile".equals(context)) {
                pages = Arrays.asList(pageService.getPersonProfilePage(contextId));
            } else {
                pages = pageService.getPages(context, contextId);
            }
        } catch (Exception e) {
            throw new ResourceNotFoundException(contextId);
        }
        if (pages == null) {
            throw new ResourceNotFoundException(contextId);
        }
        return convert(pages, pages.size());
    }

    @Override
    public Page getPage(String id) {
        logger.debug("Retrieving page for export: " + id);
        org.apache.rave.model.Page fromDb = pageService.getPage(id);
        if (fromDb == null) {
            throw new ResourceNotFoundException(id);
        }

        return new Page(fromDb);
    }

    @Override
    public Page createPage(String pageTemplateId, Page page) {
        if (page.getName() == null) {
            throw new BadRequestException("Page name property must be defined.");
        }
        org.apache.rave.model.Page fromDb;
        if(StringUtils.isNotBlank(pageTemplateId)) {
            fromDb = pageService.addNewPage(page.getName(), null, pageTemplateId);
        //TODO: RAVE-977 - when Page type enum is deprecated escape from this logic
        } else if (page.getPageType().equals("user")) {
            if (page.getPageLayoutCode() == null) {
                throw new BadRequestException("Page pageLayoutCode property must be defined.");
            }
            fromDb = pageService.addNewUserPage(page.getName(), page.getPageLayoutCode());
        } else {
            //TODO: RAVE-977 this will change
            throw new BadRequestException("Page pageType property must equal 'user'.");
        }

        return new Page(fromDb);
    }

    @Override
    public Page updatePage(String id, Page page) {
        if (page.getName() == null) {
            throw new BadRequestException("Page name property must be defined.");
        }
        if (page.getPageLayoutCode() == null) {
            throw new BadRequestException("Page pageLayoutCode property must be defined.");
        }
        //TODO: a bad page layout code can corrupt the data
        //As part of the model refactor, this needs to be made more concise and clear what properties of a page are mutable and why
        org.apache.rave.model.Page fromDb = pageService.updatePage(id, page.getName(), page.getPageLayoutCode(), page.getProperties());
        Page responsePage = new Page(fromDb);

        return responsePage;
    }

    @Override
    public Page deletePage(String id) {
        //TODO: this cannot return a 404
        logger.debug("Deleting page " + id);
        pageService.deletePage(id);
        return null;
    }

    @Override
    public Response getPageOmdl(String id) {
        return null;
    }

    @Override
    public RegionsResource getRegionsResource(String pageId) {
        Page page = getPage(pageId);
        regionsResouce.setPage(page);

        return regionsResouce;
    }

    @Override
    public PageUsersResource getPageMembersResource(String pageId) {
        Page page = getPage(pageId);
        pageUsersResource.setPage(page);

        return pageUsersResource;
    }

    private SearchResult<Page> convert(List<org.apache.rave.model.Page> fromDb, int total) {
        List<Page> pages = Lists.newArrayList();
        for (org.apache.rave.model.Page page : fromDb) {
            pages.add(new Page(page));
        }
        return new SearchResult<Page>(pages, total);
    }

    @Inject
    public void setPageService(PageService pageService) {
        this.pageService = pageService;
    }

    @Inject
    public void setRegionsResouce(DefaultRegionsResource regionsResouce) {
        this.regionsResouce = regionsResouce;
    }

    @Inject
    public void setPageUsersResource(DefaultPageUsersResource pageUsersResource) {
        this.pageUsersResource = pageUsersResource;
    }
    @Inject
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}


text:
module DropletKit
  class DropletUpgrade < BaseModel
    attribute :droplet_id
    attribute :date_of_migration
  end
end


text:
<?

	require_once("includes/common.php");

	/*Time for some pseudo code
	1) Get all rows where creator is $_SESSION["id"]
	2) Loop over it, and echo all the values out
	*/
	$creator = $_SESSION["id"];
	$sql = "SELECT id, name FROM groups WHERE group_creator = '$creator'";
	$result = mysql_query($sql) or die(mysql_error());

?>

<!DOCTYPE html>

    <title>Add Homework</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

    <link href="dist/css/bootstrap.css" rel="stylesheet" media="screen">

	<link href='http://fonts.googleapis.com/css?family=Dosis:300,400,600' rel='stylesheet' type='text/css'>
	<link href="styles.css" rel="stylesheet" type="text/css">

	<link rel="stylesheet" type="text/css" href="datepicker.css">

	<link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,300,400,600,700,800"
          rel="stylesheet" type="text/css">

					<?
						if (isset($_SESSION["id"]))
                                                {
                                        		 echo '

Signed in as '.$_SESSION["username"].'

';
					               echo '

Home

';
                                                        echo '

My Classes

';
                                                         echo '

Add homework

';
                                                        echo '

Browse

';
                                                        echo '

Logout

';
                                                }
                                                else
                                                {
                                                        echo '
<button class="signin-button spacing btn btn-md btn-success">Sign in or Sign up</button>
';
                                                }

					?>

Add Homework

						  <form action="newhw2.php" method="post">
							 <?
							 while ($row=mysql_fetch_array($result))
							{
								// Echo out everything
								echo '
';
								echo '
';

								// Name
								echo '
'.$row["name"].'
';

								// Text Input
								echo '<input type="text" name="'.$row["id"].'[text]" class="form-control input-lg" placeholder="Description">';
								echo '
';

								// Date
								echo '
';
								echo '<input type="text" placeholder="Due Date" name="'.$row["id"].'[date]" class="date input-lg form-control">';
								echo '
';
								echo '
';
							}
							?>

									<button class="signin-button btn btn-md btn-success" type="submit">Add Homework</button>

								</form>


text:
from django import forms
from django.conf import settings
from bambu_comments.models import Comment
from bambu_comments.helpers import sanitise

MARKDOWN = getattr(settings, 'COMMENTS_MARKDOWN', True)

class CommentForm(forms.ModelForm):
    h0n3ytr4p = forms.CharField(
        label = u'What is 1 + 1?', required = False,
        help_text = u'Do not enter any text into this field. This is a honeytrap for spam bots.'
    )

    def __init__(self, *args, **kwargs):
        super(CommentForm, self).__init__(*args, **kwargs)
        self.fields['name'].label = u'Your name'
        self.fields['email'].label = u'Email address'
        self.fields['email'].help_text = u'It won\'t be shared'
        self.fields['body'].label = u'Your comment'

    def save(self, commit = True):
        obj = super(CommentForm, self).save(commit = False)
        obj.body = sanitise(self.cleaned_data['body'], MARKDOWN)

        if commit:
            obj.save()

        return obj

    class Meta:
        model = Comment
        fields = ('name', 'email', 'website', 'body')


text:
package threads;

import org.junit.Test;

/**
 * Created by admin on 19.01.2017.
 */
public class SpaceCounterTest {
   /**
    * Test.
    * @throws InterruptedException ex
    */
   @Test
    public void whenWeCountSpaceAtTheStingItShouldBeCounted() throws InterruptedException {
       String test = "Hello 6 qwerty pass top 77";
       SpaceCounter spaceCounter = new SpaceCounter(test);
       Thread t = new Thread(spaceCounter);
       t.start();
       t.join();

//       int checked = 5;
//       int result = spaceCounter.getCounterSpace();

//       assertThat(result, is(checked));
   }
}


text:
package jp.ambrosoli.salmon.command.internal;

import static jp.ambrosoli.salmon.command.CommandState.*;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.IntPredicate;

import jp.ambrosoli.salmon.command.CommandParameter;
import jp.ambrosoli.salmon.command.CommandState;
import jp.ambrosoli.salmon.command.CommandState.Status;
import jp.ambrosoli.salmon.event.EventHandler;

class CommandParameterImpl implements CommandParameter {

    private String command;
    private File directory;
    private long timeout;
    private TimeUnit timeoutUnit;
    private boolean async;
    private File redirectOutput;
    private File redirectError;
    private Consumer<Map<String, String>> environment;
    private Map<Status, List<EventHandler<CommandState>>> handlers = new HashMap<>();
    private List<EventHandler<CommandState>> doneHandlers = new ArrayList<>();
    private IntPredicate successCondition = rc -> rc == RC_SUCCESS_DEFAULT;

    private Collection<String> options;

    @Override
    public String getCommand() {
        return command;
    }

    void setCommand(final String command) {
        this.command = command;
    }

    @Override
    public Collection<String> getOptions() {
        return options;
    }

    void setOptions(final Collection<String> options) {
        this.options = options;
    }

    @Override
    public List<EventHandler<CommandState>> getDoneHandlers() {
        return doneHandlers;
    }

    void setSuccessCondition(final IntPredicate successCondition) {
        this.successCondition = successCondition;
    }

    @Override
    public IntPredicate getSuccessCondition() {
        return successCondition;
    }

    @Override
    public long getTimeout() {
        return timeout;
    }

    void setTimeout(final long timeout) {
        this.timeout = timeout;
    }

    @Override
    public TimeUnit getTimeoutUnit() {
        return timeoutUnit;
    }

    void setTimeoutUnit(final TimeUnit timeoutUnit) {
        this.timeoutUnit = timeoutUnit;
    }

    @Override
    public File getDirectory() {
        return directory;
    }

    void setDirectory(final File directory) {
        this.directory = directory;
    }

    @Override
    public Consumer<Map<String, String>> getEnvironment() {
        return environment;
    }

    void setEnvironment(final Consumer<Map<String, String>> environment) {
        this.environment = environment;
    }

    @Override
    public boolean isAsync() {
        return async;
    }

    void setAsync(final boolean async) {
        this.async = async;
    }

    @Override
    public File getRedirectOutput() {
        return redirectOutput;
    }

    void setRedirectOutput(final File redirectOutput) {
        this.redirectOutput = redirectOutput;
    }

    @Override
    public File getRedirectError() {
        return redirectError;
    }

    void setRedirectError(final File redirectError) {
        this.redirectError = redirectError;
    }

    @Override
    public Map<Status, List<EventHandler<CommandState>>> getHandlers() {
        return handlers;
    }

    void setOnStateChanged(final Status status, final EventHandler<CommandState> handler) {
        List<EventHandler<CommandState>> handlerList = handlers.computeIfAbsent(status, key -> new ArrayList<>());
        handlerList.add(handler);
    }
}


text:
ActiveRecord::Schema.define(version: 20140926071026) do

  create_table "users", force: true do |t|
    t.string   "username"
    t.string   "role"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end


text:
ActiveRecord::Schema.define(version: 20150409225609) do

  create_table "activities", force: :cascade do |t|
    t.integer  "user_id"
    t.string   "action"
    t.integer  "trackable_id"
    t.string   "trackable_type"
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
  end

  add_index "activities", ["trackable_id"], name: "index_activities_on_trackable_id"
  add_index "activities", ["user_id"], name: "index_activities_on_user_id"

  create_table "answers", force: :cascade do |t|
    t.text     "content"
    t.integer  "votes",        default: 0
    t.integer  "question_id"
    t.datetime "created_at",               null: false
    t.datetime "updated_at",               null: false
    t.integer  "responder_id"
  end

  add_index "answers", ["question_id"], name: "index_answers_on_question_id"
  add_index "answers", ["responder_id"], name: "index_answers_on_responder_id"

  create_table "question_tags", force: :cascade do |t|
    t.integer  "question_id"
    t.integer  "tag_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  add_index "question_tags", ["question_id"], name: "index_question_tags_on_question_id"
  add_index "question_tags", ["tag_id"], name: "index_question_tags_on_tag_id"

  create_table "questions", force: :cascade do |t|
    t.string   "title"
    t.text     "content"
    t.integer  "asker_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "questions", ["asker_id"], name: "index_questions_on_asker_id"

  create_table "taggings", force: :cascade do |t|
    t.integer  "tag_id"
    t.integer  "taggable_id"
    t.string   "taggable_type"
    t.integer  "tagger_id"
    t.string   "tagger_type"
    t.string   "context",       limit: 128
    t.datetime "created_at"
  end

  add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true
  add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context"

  create_table "tags", force: :cascade do |t|
    t.string  "name"
    t.integer "taggings_count", default: 0
  end

  add_index "tags", ["name"], name: "index_tags_on_name", unique: true

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.string   "image_url"
    t.string   "provider"
    t.string   "uid"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "title"
  end

  create_table "votes", force: :cascade do |t|
    t.boolean  "vote",          default: false, null: false
    t.integer  "voteable_id",                   null: false
    t.string   "voteable_type",                 null: false
    t.integer  "voter_id"
    t.string   "voter_type"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "votes", ["voteable_id", "voteable_type"], name: "index_votes_on_voteable_id_and_voteable_type"
  add_index "votes", ["voter_id", "voter_type", "voteable_id", "voteable_type"], name: "fk_one_vote_per_user_per_entity", unique: true
  add_index "votes", ["voter_id", "voter_type"], name: "index_votes_on_voter_id_and_voter_type"

end


text:
exports.up = function(db) {
  db.addColumns('poets_poems', { position: { type: 'int' }});
  db.sql('update poets_poems ' +
    'set position = v.position ' +
    'from ( ' +
    '	select (row_number() over(partition by poem_id))-1 as position, poem_id, poet_id ' +
    '	from poets_poems ' +
    '	where position is null ' +
    ') v ' +
    'where poets_poems.poet_id = v.poet_id ' +
    '  and poets_poems.poem_id = v.poem_id');
};

exports.down = function(db) {
  db.dropColumns('poets_poems', ['position']);
};


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('FOadmin', '0012_auto_20170411_0857'),
    ]

    operations = [
        migrations.AddField(
            model_name='workinggrouppartner',
            name='fo_working_group_admin',
            field=models.BooleanField(default=False, verbose_name='Администратор группы'),
        ),
    ]


text:
import time

import glanceclient.openstack.common.apiclient.exceptions as ge
import novaclient.exceptions as ne

from openstack_env import domain as d
from openstack_env import exceptions as e
from openstack_env import resources as r

class ResourceTypeAware(object):
    def supports(self, resource):
        return isinstance(resource, self.type)

class SecurityRuleResourceManager(ResourceTypeAware, d.ResourceManager):
    type = r.SecurityRuleResourceDefinition

    def upload(self, resource, client):
        try:
            return client.compute.security_group_default_rules.create(
                ip_protocol=resource.protocol,
                from_port=resource.from_port,
                to_port=resource.to_port,
                cidr=resource.cidr,
            )
        except ne.Conflict:
            raise e.ResourceAlreadyExistsException(resource)

class KeyPairResourceManager(ResourceTypeAware, d.ResourceManager):
    type = r.KeyPairResourceDefinition

    def upload(self, resource, client):
        try:
            with open(resource.path) as key_file:
                key = key_file.read()
                return client.compute.keypairs.create(resource.name, key)
        except ne.Conflict:
            raise e.ResourceAlreadyExistsException(resource)

class FlavorResourceManager(ResourceTypeAware, d.ResourceManager):
    type = r.FlavorResourceDefinition

    def upload(self, resource, client):
        try:
            return client.compute.flavors.create(
                name=resource.name,
                ram=resource.ram_size,
                vcpus=resource.cpu_count,
                disk=resource.disk_size,
                flavorid=resource.id,
                ephemeral=resource.ephemeral_disk_size,
                swap=resource.swap_size,
                is_public=resource.is_public,
            )
        except ne.Conflict:
            raise e.ResourceAlreadyExistsException(resource)

class ImageResourceManager(ResourceTypeAware, d.ResourceManager):
    type = r.ImageResourceDefinition

    def exists(self, resource, client):
        try:
            client.images.images.find(name=resource.name)
        except ge.NotFound:
            return False
        else:
            return True

    def upload(self, resource, client):
        if self.exists(resource, client):
            raise e.ResourceAlreadyExistsException(resource)

        image = client.images.images.create(
            name=resource.name,
            copy_from=resource.url,
            disk_format=resource.disk_format,
            container_format=resource.container_format,
            is_public=resource.is_public,
        )

        self.wait_for_status(image, "active", client)

        return image

    def get_status(self, image, client):
        return client.images.images.get(image.id).status

    def wait_for_status(self, image, status, client, timeout=3600, period=10):
        start_time = time.time()

        while time.time() - start_time < timeout:
            if self.get_status(image, client) == status:
                return

            time.sleep(period)

        raise e.TimeoutException()


text:
/*  File Set Declarations */

/*  Copyright (c) 1994 Stanford University

    All rights reserved.

    This software is provided under the terms described in
    the "suif_copyright.h" include file. */

#include <suif_copyright.h>

#ifndef FILESET_H
#define FILESET_H

#pragma interface

RCS_HEADER(fileset_h,
    "$Id: fileset.h,v 1.2 1999/08/25 03:29:10 brm Exp $")

class in_stream;
class out_stream;
class file_set_entry;

DECLARE_DLIST_CLASS(file_set_entry_list, file_set_entry*);

/*
 *  The file_set is basically just a list of file_set_entries.  Its main
 *  function is to handle opening streams to avoid exceeding the OS limit
 *  on the number of open files.  If there are too many open streams, the
 *  file_set will automatically find one to close.  All of this is invisible
 *  to the user.
 */

class file_set {
    friend class file_set_entry;
    friend class proc_sym;

private:
    /* We make explicit copy constructor and assignment operator and
     * make them private to foil C++'s automatic default versions. */
    file_set(const file_set &);
    file_set &operator=(const file_set &);

    file_set_entry_list *files;		/* list of files */
    file_set_entry_list_iter *iter;	/* file iterator */
    global_symtab *globs;		/* global symbol table */
    long open_max;			/* maximum number of open files */
    int open_cnt;			/* current number of open files */
    boolean read_a_file;		/* have we read an input file yet? */

    void open_stream(base_stream *s, file_set_entry *fse);
    void close_stream(base_stream *s);
    void close_other_file(file_set_entry *fse);

public:
    file_set();
    ~file_set();

    global_symtab *globals()		{ return globs; }
    file_set_entry_list *file_list()	{ return files; }

    file_set_entry *add_file(char *in, char *out); /* either may be NULL */

    /* built-in file iterator */
    void reset_iter()			{ iter->reset(files); }
    file_set_entry *next_file()		{ return iter->is_empty() ?
					      NULL : iter->step(); }

    file_set_entry *find_by_num(int file_id);

    long get_max_open_files(void)	{ return open_max; }
    void set_max_open_files(long new_max);
};

EXPORTED_BY_SUIF file_set *fileset;

/*
 *  A file_set_entry keeps track of the input and output streams for a
 *  single source file.  It also includes the file_symtab.  The
 *  reset_proc_iter and next_proc methods provide a convenient means of
 *  visiting all of the procedures that are defined in the input file.
 */

class file_set_entry : public suif_object {
    friend class file_set;
    friend class proc_sym;
    friend class suif_linker;

private:
    file_set *par;			/* parent file_set */
    in_stream *is;			/* input stream */
    out_stream *os;			/* output stream */
    file_symtab *table;			/* corresponding file symtab */
    long symtab_ptr_loc;		/* offset in file for symtab info */
    sym_node_list_iter *global_proc_iter;
    sym_node_list_iter *static_proc_iter;
    int the_id;

    void set_file_id(int new_id)	{ the_id = new_id; }

protected:
    void fill_table();
    void write_table();
    void check_global_symtab(global_symtab *newglobs);
    void get_contents();
    boolean get_machine_param(int *flag, char *annote_name, boolean is_array,
			      boolean read_a_file);
    void save_machine_param(int val, char *annote_name, int ndx);

public:
    file_set_entry(file_set *p, char *inn, char *outn);
    ~file_set_entry();

    object_kinds object_kind()		{ return FILE_OBJ; }

    file_set *parent()			{ return par; }
    file_symtab *symtab()		{ return table; }
    char *name();			/* name of the input (or output) file*/
    char *in_name()			{ return (is ? is->name() : NULL); }
    char *out_name()			{ return (os ? os->name() : NULL); }
    int file_id()			{ return the_id; }

    void set_symtab(file_symtab *new_table) { table = new_table; }
    void add_outfile(char *outn);

    void reset_proc_iter();
    proc_sym *next_proc();		/* find the next procedure */
};

/*
 *  This variable is normally set to FALSE.  It is only set to TRUE if
 *  the ``-no-glob-check'' flag is given as a command-line argument or
 *  if the user program manually changes it to TRUE.  That is, it only
 *  becomes TRUE if the user explicitly sets it to TRUE, whether that
 *  is the run-time user with the command-line or the link-time user
 *  writing the program that uses the SUIF library.
 *
 *  When set to TRUE, the automatic checking that global symbol tables
 *  match when there is more than one file in a file set is disabled.
 *  It is important to note that the requirement that global symbol
 *  tables match is still a requirement, it's just not explicitly
 *  checked.  That means that if the global symbol tables don't match,
 *  the library will probably fail in strange ways instead of giving a
 *  nice error message that the symbol tables don't match.
 *
 *  This is provided strictly for performance reasons.  The checks of
 *  global symbol tables can take a while, so if you're certain they
 *  will be right, you can save that time by not doing the check.
 *
 *  The linksuif pass is normally used to make sure the global symbol
 *  tables match initially.
 */
EXPORTED_BY_SUIF boolean disable_global_symtab_check;

#endif /* FILESET_H */


text:
(function(alpha, bravo, charlie) {
    if (charlie in bravo && bravo[charlie]) {
        var delta, echo = alpha.location,
            foxtrot = /^(alpha|html)$/i;
        alpha.addEventListener("click", function(alpha) {
            delta = alpha.target;
            while (!foxtrot.test(delta.nodeName)) delta = delta.parentNode;
            "href" in delta && (delta.href.indexOf("http") || ~delta.href.indexOf(echo.host)) && (alpha.preventDefault(), echo.href = delta.href)
        }, !1)
    }
})(document, window.navigator, "standalone")


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
PIDSource (2013 FRC Java API)
</TITLE>

<META NAME="date" CONTENT="2013-01-03">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

edu.wpi.first.wpilibj

Interface PIDSource

All Known Implementing Classes:
Accelerometer, AnalogChannel, Encoder, Gyro, Ultrasonic

public interface PIDSource

This interface allows for PIDController to automatically read from this
 object

Author:

dtjones

Method Summary

 double
pidGet()

          Get the result to use in PIDController

Method Detail

pidGet

double pidGet()

Get the result to use in PIDController

Returns:
the result to use in PIDController

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

"For updated information see the Java FRC site"


text:
import expect from 'expect';
import Loader from '../../src/3.loader.js';
import Registry from '../../src/4.registry.js';

describe('Registry', () => {

    describe('new Loader().registry', () => {
        let registry = new Loader().registry;

        it('is an member of loader', () => {
            expect(registry).toBeAn('object');
        });
        it('.constructor', () => {
            expect(registry.constructor).toBeA('function');
        });
        it('@@iterator', () => {
            expect(registry[Symbol.iterator]).toBeA('function');
        });
        it('.entries', () => {
            expect(registry.entries).toBeA('function');
        });
        it('.keys', () => {
            expect(registry.keys).toBeA('function');
        });
        it('.values', () => {
            expect(registry.values).toBeA('function');
        });
        it('.get', () => {
            expect(registry.get).toBeA('function');
        });
        it('.set', () => {
            expect(registry.set).toBeA('function');
        });
        it('.has', () => {
            expect(registry.has).toBeA('function');
        });
        it('.delete', () => {
            expect(registry.delete).toBeA('function');
        });
        it('cannot be subclasseable', () => {
            let prototype = Object.getPrototypeOf(registry);
            expect(prototype).toBeAn('object');
            function foo () {}
            foo.prototype = Object.create(prototype);
            foo.prototype.constructor = registry.constructor;
            expect(() => {
                new foo();
            }).toThrow();
        });
    });

    describe('new Registry()', () => {
        let loader = new Loader();
        let registry = loader.registry;

        it('cannot be instantiate directly', () => {
            expect(() => {
                new Registry({});
            }).toThrow();
        });
        it('cannot be subclasseable', () => {
            let prototype = Object.getPrototypeOf(registry);
            expect(prototype).toBeAn('object');
            function foo () {}
            foo.prototype = Object.create(prototype);
            foo.prototype.constructor = loader.registry.constructor;
            expect(() => {
                new foo();
            }).toThrow();
        });
    });

});


text:
using CarsSystem.Data.Models;
using CarsSystem.Data.Repositories;
using CarsSystem.Services;
using CarsSystem.Services.Contracts;
using Moq;
using NUnit.Framework;
using System;

namespace CarsSystem.Tests.Services.CarsSystem.Services.CarsServiceTests
{
    [TestFixture]
    public class Should
    {
        [Test]
        public void ThrowArgumentNullException_WhenPassedRepositoryIsNull()
        {
            // Arrange
            IEfGenericRepository<Car> mockedRepository = null;

            // Act & Assert
            Assert.Throws<ArgumentException>(() => new CarsService(mockedRepository));
        }

        [Test]
        public void ThrowArgumentNullExceptionWithExpectedMessage_WhenPassedRepositoryIsNull()
        {
            // Arrange
            IEfGenericRepository<Car> mockedRepository = null;

            // Act
            var expectedMessage = Assert.Throws<ArgumentException>(() => new CarsService(mockedRepository));

            // Assert
            Assert.IsTrue(expectedMessage.Message.Contains("null"));
        }

        [Test]
        public void CreateInstanceOfCarsService_WhenPassedRepositoryIsCorrectly()
        {
            // Arrange
            var mockedRepository = new Mock<IEfGenericRepository<Car>>();

            // Act
            var service = new CarsService(mockedRepository.Object);

            // Assert
            Assert.IsInstanceOf<CarsService>(service);
        }

        [Test]
        public void ImplementsInterfaceICarsService_WhenPassedRepositoryIsCorrectly()
        {
            // Arrange
            var mockedRepository = new Mock<IEfGenericRepository<Car>>();

            // Act
            var service = new CarsService(mockedRepository.Object);

            // Assert
            Assert.IsInstanceOf<ICarsService>(service);
        }
    }
}


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.robitdroid;

public final class R {
    public static final class attr {
    }

    public static final class drawable {
        public static final int about = 0x7f020000;
        public static final int black = 0x7f020001;
        public static final int icon = 0x7f020002;
        public static final int intro = 0x7f020003;
        public static final int robit = 0x7f020004;
    }

    public static final class id {
        public static final int ImageViewAbout = 0x7f050000;
        public static final int ImageViewRobit = 0x7f050009;
        public static final int LinearLayout02 = 0x7f050005;
        public static final int btn_no = 0x7f050007;
        public static final int btn_yes = 0x7f050006;
        public static final int final_number = 0x7f050001;
        public static final int gridview = 0x7f050004;
        public static final int instruction_tv = 0x7f050008;
        public static final int main_menu_button = 0x7f050003;
        public static final int restart_button = 0x7f050002;
    }

    public static final class layout {
        public static final int about_screen = 0x7f030000;
        public static final int final_screen = 0x7f030001;
        public static final int game_screen = 0x7f030002;
        public static final int main = 0x7f030003;
    }

    public static final class string {
        public static final int app_name = 0x7f040000;
        public static final int instructions = 0x7f040004;
        public static final int no = 0x7f040003;
        public static final int self_start = 0x7f040001;
        public static final int yes = 0x7f040002;
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Kew Bull. 37(2): 269 (1982)

#### Original name
Lactarius chromospermus Pegler, 1982

### Remarks
null


text:
/*
 * This script tests the stripped down markup parser.
 */
var strippedDownMarkupParser = require('../src/vdom/strippedDownMarkupParser.js');

//var rootEle = strippedDownMarkupParser.parse('

Col1	Col2

');
var rootEle = strippedDownMarkupParser.parse('<nop>
<INPUT type="text" value="A"></INPUT>
</nop>');
console.log('rootEle = ' + JSON.stringify(rootEle, undefined, 2));


text:
//
//  LPYCheatGamePadDecorator.h
//  LPYFramework
//
//  Created by admin on 16/1/27.
//  Copyright © 2016年 liupuyan. All rights reserved.
//

#import "LPYGamePadDecorator.h"

@interface LPYCheatGamePadDecorator : LPYGamePadDecorator
/**
 *  作弊操作
 */
- (void)cheat;
@end


text:
#pragma once

#include "AppEvent.h"

#include <drivers/gpio.h>

#include <platform/CHIPDeviceLayer.h>

#include <cstdint>

struct k_timer;

class AppTask
{
public:
    CHIP_ERROR StartApp();

    enum Action_t : uint8_t
    {
        ON_ACTION = 0,
        OFF_ACTION,
        LEVEL_ACTION,

        INVALID_ACTION
    };

    void PostLightingActionRequest(Action_t aAction);
    void PostEvent(AppEvent * event);
    void UpdateClusterState();

private:
    friend AppTask & GetAppTask(void);

    CHIP_ERROR Init();

    static void ActionInitiated(AppTask::Action_t aAction, int32_t aActor);
    static void ActionCompleted(AppTask::Action_t aAction, int32_t aActor);

    void DispatchEvent(AppEvent * event);

    static void UpdateStatusLED();
    static void SwitchActionButtonEventHandler(void);
    static void FactoryResetButtonEventHandler(void);
    static void StartThreadButtonEventHandler(void);
    static void StartBleAdvButtonEventHandler(void);

    static void ChipEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg);

    static void FactoryResetHandler(AppEvent * aEvent);
    static void StartThreadHandler(AppEvent * aEvent);
    static void SwitchActionEventHandler(AppEvent * aEvent);
    static void StartBleAdvHandler(AppEvent * aEvent);

    static void InitButtons(void);

    static void ThreadProvisioningHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg);

    static AppTask sAppTask;
};

inline AppTask & GetAppTask(void)
{
    return AppTask::sAppTask;
}


text:
namespace first_party_sets {

// *************** LOCAL STATE PREFS ***************

// A boolean pref indicating whether First-Party Sets is enabled by enterprise
// policy.
const char kFirstPartySetsEnabled[] = "first_party_sets.enabled";

void RegisterLocalStatePrefs(PrefRegistrySimple* registry) {
  registry->RegisterBooleanPref(kFirstPartySetsEnabled, true);
}

}  // namespace first_party_sets


text:
package com.digitalpetri.modbus.responses;

import com.digitalpetri.modbus.FunctionCode;
import io.netty.buffer.ByteBuf;

public class ReadHoldingRegistersResponse extends ByteBufModbusResponse {

    public ReadHoldingRegistersResponse(ByteBuf registers) {
        super(registers, FunctionCode.ReadHoldingRegisters);
    }

    /**
     * The register data in the response message are packed as two bytes per register, with the binary contents right
     * justified within each byte. For each register, the first byte contains the high order bits and the second
     * contains the low order bits.
     *
     * @return the {@link ByteBuf} containing register data, two bytes per register.
     */
    public ByteBuf getRegisters() {
        return super.content();
    }

}


text:
from sympy.utilities.iterables import preorder_traversal

def pprint_nodes(subtrees):
    """
    Prettyprints systems of nodes.

    Example:

    >> print pprint_nodes(["a", "b1\nb2", "c"])
    +-a
    +-b1
    | b2
    +-c
    >>

    """
    def indent(s,type=1):
        x = s.split("\n")
        r = "+-%s\n"%x[0]
        for a in x[1:]:
            if a=="": continue
            if type==1:
                r += "| %s\n"%a
            else:
                r += "  %s\n"%a
        return r
    if len(subtrees)==0: return ""
    f="";
    for a in subtrees[:-1]:
        f += indent(a)
    f += indent(subtrees[-1],2)
    return f

def print_node(node):
    """
    Returns an information about the "node".

    This includes class name, string representation and assumptions.
    """
    s = "%s: %s\n" % (node.__class__.__name__, str(node))
    if len(node._assumptions) > 0:
        for a in node._assumptions:
            s += "%s: %s\n" % (a, node._assumptions[a])
    return s

def tree(node):
    """
    Returns a tree representation of "node" as a string.

    It uses print_node() together with pprint_nodes() on node.args recursively.

    See also: print_tree()
    """
    subtrees = []
    for arg in node.args:
        subtrees.append(tree(arg))
    s = print_node(node)+pprint_nodes(subtrees)
    return s

def print_tree(node):
    """
    Prints a tree representation of "node".

    In [1]: print_tree(x**2)
    Pow: x**2
    +-Symbol: x
    | comparable: False
    | noncommutative: False
    | commutative: True
    +-Integer: 2
      real: True
      comparable: True
      commutative: True
      infinitesimal: False
      nonzero: True
      unbounded: False
      noncommutative: False
      noninteger: False
      zero: False
      complex: True
      bounded: True
      rational: True
      integer: True
      imaginary: False
      finite: True
      irrational: False

    See also: tree()
    """
    print tree(node)


text:
class EnableUnaccent < ActiveRecord::Migration[6.0]
  def change
    enable_extension "unaccent"
  end
end


text:
#include "uv.h"
#include "internal.h"
#include "spinlock.h"

#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <termios.h>
#include <errno.h>
#include <sys/ioctl.h>

static int orig_termios_fd = -1;
static struct termios orig_termios;
static uv_spinlock_t termios_spinlock = UV_SPINLOCK_INITIALIZER;

static int uv__tty_is_slave(const int fd) {
  int result;
#if defined(__linux__) || defined(__FreeBSD__)
  int dummy;

  result = ioctl(fd, TIOCGPTN, &dummy) != 0;
#elif defined(__APPLE__)
  char dummy[256];

  result = ioctl(fd, TIOCPTYGNAME, &dummy) != 0;
#else
  /* Fallback to ptsname
   */
  result = ptsname(fd) == NULL;
#endif
  return result;
}

int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, int fd, int readable) {
  uv_handle_type type;
  int flags;
  int newfd;
  int r;
  int saved_flags;
  char path[256];

  /* File descriptors that refer to files cannot be monitored with epoll.
   * That restriction also applies to character devices like /dev/random
   * (but obviously not /dev/tty.)
   */
  type = uv_guess_handle(fd);
  if (type == UV_FILE || type == UV_UNKNOWN_HANDLE)
    return -EINVAL;

  flags = 0;
  newfd = -1;

  /* Reopen the file descriptor when it refers to a tty. This lets us put the
   * tty in non-blocking mode without affecting other processes that share it
   * with us.
   *
   * Example: `node | cat` - if we put our fd 0 in non-blocking mode, it also
   * affects fd 1 of `cat` because both file descriptors refer to the same
   * struct file in the kernel. When we reopen our fd 0, it points to a
   * different struct file, hence changing its properties doesn't affect
   * other processes.
   */
  if (type == UV_TTY) {
    /* Reopening a pty in master mode won't work either because the reopened
     * pty will be in slave mode (*BSD) or reopening will allocate a new
     * master/slave pair (Linux). Therefore check if the fd points to a
     * slave device.
     */
    if (uv__tty_is_slave(fd) && ttyname_r(fd, path, sizeof(path)) == 0)
      r = uv__open_cloexec(path, O_RDWR);
    else
      r = -1;

    if (r < 0) {
      /* fallback to using blocking writes */
      if (!readable)
        flags |= UV_STREAM_BLOCKING;
      goto skip;
    }

    newfd = r;

    r = uv__dup2_cloexec(newfd, fd);
    if (r < 0 && r != -EINVAL) {
      /* EINVAL means newfd == fd which could conceivably happen if another
       * thread called close(fd) between our calls to isatty() and open().
       * That's a rather unlikely event but let's handle it anyway.
       */
      uv__close(newfd);
      return r;
    }

    fd = newfd;
  }

#if defined(__APPLE__)
  /* Save the fd flags in case we need to restore them due to an error. */
  do
    saved_flags = fcntl(fd, F_GETFL);
  while (saved_flags == -1 && errno == EINTR);

  if (saved_flags == -1) {
    if (newfd != -1)
      uv__close(newfd);
    return -errno;
  }
#endif

  /* Pacify the compiler. */
  (void) &saved_flags;

skip:
  uv__stream_init(loop, (uv_stream_t*) tty, UV_TTY);

  /* If anything fails beyond this point we need to remove the handle from
   * the handle queue, since it was added by uv__handle_init in uv_stream_init.
   */

  if (!(flags & UV_STREAM_BLOCKING))
    uv__nonblock(fd, 1);

#if defined(__APPLE__)
  r = uv__stream_try_select((uv_stream_t*) tty, &fd);
  if (r) {
    int rc = r;
    if (newfd != -1)
      uv__close(newfd);
    QUEUE_REMOVE(&tty->handle_queue);
    do
      r = fcntl(fd, F_SETFL, saved_flags);
    while (r == -1 && errno == EINTR);
    return rc;
  }
#endif

  if (readable)
    flags |= UV_STREAM_READABLE;
  else
    flags |= UV_STREAM_WRITABLE;

  uv__stream_open((uv_stream_t*) tty, fd, flags);
  tty->mode = UV_TTY_MODE_NORMAL;

  return 0;
}

static void uv__tty_make_raw(struct termios* tio) {
  assert(tio != NULL);

#ifdef __sun
  /*
   * This implementation of cfmakeraw for Solaris and derivatives is taken from
   * http://www.perkin.org.uk/posts/solaris-portability-cfmakeraw.html.
   */
  tio->c_iflag &= ~(IMAXBEL | IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR |
                    IGNCR | ICRNL | IXON);
  tio->c_oflag &= ~OPOST;
  tio->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  tio->c_cflag &= ~(CSIZE | PARENB);
  tio->c_cflag |= CS8;
#else
  cfmakeraw(tio);
#endif /* #ifdef __sun */
}

int uv_tty_set_mode(uv_tty_t* tty, uv_tty_mode_t mode) {
  struct termios tmp;
  int fd;

  if (tty->mode == (int) mode)
    return 0;

  fd = uv__stream_fd(tty);
  if (tty->mode == UV_TTY_MODE_NORMAL && mode != UV_TTY_MODE_NORMAL) {
    if (tcgetattr(fd, &tty->orig_termios))
      return -errno;

    /* This is used for uv_tty_reset_mode() */
    uv_spinlock_lock(&termios_spinlock);
    if (orig_termios_fd == -1) {
      orig_termios = tty->orig_termios;
      orig_termios_fd = fd;
    }
    uv_spinlock_unlock(&termios_spinlock);
  }

  tmp = tty->orig_termios;
  switch (mode) {
    case UV_TTY_MODE_NORMAL:
      break;
    case UV_TTY_MODE_RAW:
      tmp.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
      tmp.c_oflag |= (ONLCR);
      tmp.c_cflag |= (CS8);
      tmp.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
      tmp.c_cc[VMIN] = 1;
      tmp.c_cc[VTIME] = 0;
      break;
    case UV_TTY_MODE_IO:
      uv__tty_make_raw(&tmp);
      break;
  }

  /* Apply changes after draining */
  if (tcsetattr(fd, TCSADRAIN, &tmp))
    return -errno;

  tty->mode = mode;
  return 0;
}

int uv_tty_get_winsize(uv_tty_t* tty, int* width, int* height) {
  struct winsize ws;
  int err;

  do
    err = ioctl(uv__stream_fd(tty), TIOCGWINSZ, &ws);
  while (err == -1 && errno == EINTR);

  if (err == -1)
    return -errno;

  *width = ws.ws_col;
  *height = ws.ws_row;

  return 0;
}

uv_handle_type uv_guess_handle(uv_file file) {
  struct sockaddr sa;
  struct stat s;
  socklen_t len;
  int type;

  if (file < 0)
    return UV_UNKNOWN_HANDLE;

  if (isatty(file))
    return UV_TTY;

  if (fstat(file, &s))
    return UV_UNKNOWN_HANDLE;

  if (S_ISREG(s.st_mode))
    return UV_FILE;

  if (S_ISCHR(s.st_mode))
    return UV_FILE;  /* XXX UV_NAMED_PIPE? */

  if (S_ISFIFO(s.st_mode))
    return UV_NAMED_PIPE;

  if (!S_ISSOCK(s.st_mode))
    return UV_UNKNOWN_HANDLE;

  len = sizeof(type);
  if (getsockopt(file, SOL_SOCKET, SO_TYPE, &type, &len))
    return UV_UNKNOWN_HANDLE;

  len = sizeof(sa);
  if (getsockname(file, &sa, &len))
    return UV_UNKNOWN_HANDLE;

  if (type == SOCK_DGRAM)
    if (sa.sa_family == AF_INET || sa.sa_family == AF_INET6)
      return UV_UDP;

  if (type == SOCK_STREAM) {
#if defined(_AIX)
    /* on AIX the getsockname call returns an empty sa structure
     * for sockets of type AF_UNIX.  For all other types it will
     * return a properly filled in structure.
     */
    if (len == 0)
      return UV_NAMED_PIPE;
#endif /* defined(_AIX) */

    if (sa.sa_family == AF_INET || sa.sa_family == AF_INET6)
      return UV_TCP;
    if (sa.sa_family == AF_UNIX)
      return UV_NAMED_PIPE;
  }

  return UV_UNKNOWN_HANDLE;
}

/* This function is async signal-safe, meaning that it's safe to call from
 * inside a signal handler _unless_ execution was inside uv_tty_set_mode()'s
 * critical section when the signal was raised.
 */
int uv_tty_reset_mode(void) {
  int saved_errno;
  int err;

  saved_errno = errno;
  if (!uv_spinlock_trylock(&termios_spinlock))
    return -EBUSY;  /* In uv_tty_set_mode(). */

  err = 0;
  if (orig_termios_fd != -1)
    if (tcsetattr(orig_termios_fd, TCSANOW, &orig_termios))
      err = -errno;

  uv_spinlock_unlock(&termios_spinlock);
  errno = saved_errno;

  return err;
}


text:
## SA1025

  TypeName
  SA1025CodeMustNotContainMultipleWhitespaceInARow

  CheckId
  SA1025

  Category
  Spacing Rules

## Cause

The code contains multiple whitespace characters in a row.

## Rule description

A violation of this rule occurs whenever the code contains multiple whitespace characters in a row, unless the
characters come at the beginning or end of a line of code, following a comma or semicolon or preceding a symbol.

## How to fix violations

To fix a violation of this rule, remove the extra whitespace characters are leave only a single space.

## How to suppress violations

```csharp
[SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1025:CodeMustNotContainMultipleWhitespaceInARow", Justification = "Reviewed.")]
```

```csharp
#pragma warning disable SA1025 // CodeMustNotContainMultipleWhitespaceInARow
#pragma warning restore SA1025 // CodeMustNotContainMultipleWhitespaceInARow
```


text:
{-# LANGUAGE LambdaCase #-}

module Data.Aeson.Validation.Internal.Field
  ( Field
  , flatten
  ) where

import Data.Aeson.Validation.Internal.Pair
import Data.Aeson.Validation.Internal.Prelude
import Data.Aeson.Validation.Internal.Types

import qualified Data.HashMap.Strict as HashMap
import qualified Data.List.NonEmpty as NonEmpty

flatten :: Strict -> [Field] -> [ShallowField]
flatten s xs =
  mapFields (foldr step mempty xs)
  where
    step
      :: Field
      -> HashMap (Pair Demand Text) (Pair FieldMap [Schema])
      -> HashMap (Pair Demand Text) (Pair FieldMap [Schema])
    step (Field req path sch) =
      go (NonEmpty.toList path)
      where
        go :: [Text]
           -> HashMap (Pair Demand Text) (Pair FieldMap [Schema])
           -> HashMap (Pair Demand Text) (Pair FieldMap [Schema])
        go = \case
          [key] ->
            HashMap.alter
              (\case
                Nothing -> Just (Pair mempty [sch])
                Just (Pair m schs) -> Just (Pair m (sch : schs)))
              (Pair req key)
          key:path' ->
            HashMap.alter
              (\case
                Nothing -> val mempty []
                Just (Pair m schs) -> val m schs)
              (Pair req key)
            where
              val :: FieldMap -> [Schema] -> Maybe (Pair FieldMap [Schema])
              val m ss =
                Just (Pair (FieldMap (go path' (unFieldMap m))) ss)

    mapFields
      :: HashMap (Pair Demand Text) (Pair FieldMap [Schema])
      -> [ShallowField]
    mapFields =
      HashMap.toList >=> go
      where
        go
          :: (Pair Demand Text, Pair FieldMap [Schema])
          -> [ShallowField]
        go (Pair req key, Pair m ss) =
          case mapFields (unFieldMap m) of
            [] -> fields
            fs -> objField fs : fields
          where
            fields :: [ShallowField]
            fields =
              map (ShallowField req key) ss

            objField :: [ShallowField] -> ShallowField
            objField fs =
              ShallowField
                { fieldDemand = req
                , fieldKey    = key
                , fieldSchema = SObject s fs
                }

-- A FieldMap is a temporary data structure used during the conversion from
-- [Field] to [ShallowField].
newtype FieldMap
  = FieldMap
  { unFieldMap :: HashMap (Pair Demand Text) (Pair FieldMap [Schema]) }

instance Semigroup FieldMap where
  (FieldMap x) <> (FieldMap y) = FieldMap (x <> y)

instance Monoid FieldMap where
  mempty = FieldMap mempty
  mappend = (<>)


text:
package com.macadamian.blinkup;

public class Extras {
    public static final String EXTRA_DEVELOPER_PLAN_ID = "Extra.DeveloperPlanId";
    public static final String EXTRA_TIMEOUT_MS = "Extra.TimeoutMs";
}


text:
import {Component} from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'progress-bar-a11y',
  templateUrl: 'progress-bar-a11y.html',
})
export class ProgressBarAccessibilityDemo {
  surveyProgress: number = 30;
  videoPlayValue: number = 20;
  videoBufferValue: number = 60;
}


text:
.. currentmodule:: PyQt5.QtGui

QPolygonF
---------

.. class:: QPolygonF

    `C++ documentation <http://doc.qt.io/qt-5/qpolygonf.html>`_


text: export { default } from 'ember-flexberry-designer/routes/fd-association-list-form';


text:
#pragma once

#include "OfflineHandler.h"
#include "Logger.h"
#include "Endpoint.h"
#include "PIConf.h"
#include "Codes.h"
#include "SecureString.h"
#include <Windows.h>
#include <string>
#include <map>
#include <functional>
#include <atomic>

#define PI_ENDPOINT_VALIDATE_CHECK					"/validate/check"
#define PI_ENDPOINT_POLL_TX							"/validate/polltransaction"
#define PI_ENDPOINT_OFFLINE_REFILL					"/validate/offlinerefill"

class PrivacyIDEA
{
public:
	PrivacyIDEA(PICONFIG conf) :
		_realmMap(conf.realmMap),
		_defaultRealm(conf.defaultRealm),
		_logPasswords(conf.logPasswords),
		_endpoint(conf),
		_offlineHandler(conf.offlineFilePath, conf.offlineTryWindow),
		_lastError(0)
	{};

	PrivacyIDEA& operator=(const PrivacyIDEA& privacyIDEA) = delete;

	// Tries to verify with offline otp first. If there is none,
	// sends the parameters to privacyIDEA and checks the response for
	// 1. Offline otp data, 2. Triggered challenges, 3. Authentication success
	// <returns> PI_AUTH_SUCCESS, PI_TRIGGERED_CHALLENGE, PI_AUTH_FAILURE, PI_AUTH_ERROR, PI_ENDPOINT_SETUP_ERROR, PI_WRONG_OFFLINE_SERVER_UNAVAILABLE </returns>
	HRESULT validateCheck(const std::wstring& username, const std::wstring& domain, const SecureWString& otp, const std::string& transaction_id = std::string());

	bool stopPoll();

	// Poll for the given transaction asynchronously. When polling returns success, the transaction is finalized
	// according to https://privacyidea.readthedocs.io/en/latest/configuration/authentication_modes.html#outofband-mode
	// After that, the callback function is called with the result
	void asyncPollTransaction(std::string username, std::string transaction_id, std::function<void(bool)> callback);

	// Poll for a transaction once. Can be used if the plugin wants to control the looping
	// <returns> PI_TRANSACTION_SUCCESS or PI_TRANSACTION_FAILURE </returns>
	HRESULT pollTransaction(std::string transaction_id);

	bool isOfflineDataAvailable(const std::wstring& username);

	Challenge getCurrentChallenge();

	static std::wstring s2ws(const std::string& s);

	static std::string ws2s(const std::wstring& ws);

	static SecureString sws2ss(const SecureWString& sws);

	static SecureWString ss2sws(const SecureString& ss);

	static std::wstring toUpperCase(std::wstring s);

	static std::string longToHexString(long in);

	int getLastError();

	std::wstring getLastErrorMessage();

private:
	HRESULT appendRealm(std::wstring domain, SecureString& data);

	void pollThread(const std::string& transaction_id, const std::string& username, std::function<void(bool)> callback);

	HRESULT tryOfflineRefill(std::string username, SecureString lastOTP);

	std::map<std::wstring, std::wstring> _realmMap;

	std::wstring _defaultRealm = L"";

	Endpoint _endpoint;
	OfflineHandler _offlineHandler;

	Challenge _currentChallenge;

	bool _logPasswords = false;

	std::atomic<bool> _runPoll = false;

	int _lastError = 0;
	std::string _lastErrorMessage;
};


text:
angular.module('forecast-player')
  .service('SoundCloud', function ($window, $q) {
    var SC           = $window.SC,
        localStorage = $window.localStorage,
        SoundCloud   = this;

    SoundCloud.oauthToken = null;

    ipc.on('index:save-token', function (token) {
      localStorage.setItem('soundcloud-token', token);
      $window.location.reload();
    });

    this.initialized = false;

    this.login = function () {
      ipc.send('index:open-login');
    };

    this.init = function () {
      var token = localStorage.getItem('soundcloud-token');
      if(token) {
        SC.initialize({ access_token: token });
        SC._baseUrl = 'http://connect.soundcloud.com';

        SoundCloud.oauthToken = token;
        SoundCloud.initialized = true;
      }
    };

    this.get = function (url) {
      if (SoundCloud.initialized) {
        var deferred = $q.defer();
        SC.get(url, function (response, error) {
          if (response) {
            deferred.resolve(response);
          } else {
            deferred.reject(error);
            SoundCloud.initialized = false;
          }
        });
        return deferred.promise;
      } else {
        return $q.reject();
      }
    };

    this.init();
  })
;


text:
layout: post
title: Smart Sleeper app update
date: 2014-12-07
---

Finally, the app can take a user's bed time and wake up time, and provide a calculated wake up time. Surprisingly, this was more difficult to do that I expected because of arithmetic with time values. Through my self-learning, I have also implemented tools such as bundles and fragments.

Looking forward to sharing the next update: Using an alarm clock API to set an alarm, or implementing an alarm clock that gets set.


text:
(function(w) {

    // Creates the CLog object function
    var CLog = function(options) {
        // On input it assigns a custom color, otherwise it sets the default color
        this.options = {
            group: options.group || null,
            colors: options.colors || null
        };

        this.options.colors.default = "#000000";
    };

    // Returns an array where argument[0] is always a color.
    // Color is set based on input (id or hex) or is set to default (black)
    var _normalizeArguments = function(args) {
        // Get colors from options
        var colors = this.options.colors;
        // Init color
        var color = '';
        // Convert arguments into an Array
        var argumentsArray = [].slice.apply(args);

        // Search in options.colors or set color
        if (!!colors && typeof argumentsArray[0] === "string") {
            if (argumentsArray[0][0] === "#") {
                color = argumentsArray[0];
            } else {
                for (var c in colors) {
                    if (argumentsArray[0] === c) {
                        color = colors[argumentsArray[0]];
                    }
                }
            }
        }

        // If color in the arguments doesn't exist, unshift the default color
        if (color === '') {
            argumentsArray.unshift(this.options.colors.default);
        } else {
            argumentsArray[0] = color;
        }

        return argumentsArray;
    };

    // Formats the output
    var _createOutput = function(args) {
        var output = '%c ';
        var outputArgs = [];
        var isGrouped = this.options.group;

        for (var i = 1; i < args.length; i++) {
            switch (typeof args[i]) {
                case 'string':
                case 'number':
                case 'boolean':
                    output += args[i] + ' ';
                    break;
                case 'undefined':
                    output += "'undefined' ";
                    break;
                case 'object':
                case 'array':
                case 'function':
                    outputArgs.push(args[i]);
                    output += (isGrouped) ? '' : '(%O) ';
                    break;
                default:
                    output += args[i] + ' ';
                    break;
            }

        }

        // If group isn't active, slice the arguments output
        if (!isGrouped) {
            outputArgs.splice(0, 0, output);
            outputArgs.splice(1, 0, "color:" + args[0] + ";");
        }

        return {
            color: args[0],
            message: output,
            args: outputArgs
        }
    };

    // Prints to console
    var _print = function(output) {
        var isGrouped = this.options.group;

        // If group is active, create group in console
        if (isGrouped) {
            console.groupCollapsed(output.message, "color:" + output.color + ";");

            output.args.forEach(function(arg) {
                console.dir(arg);
            });

            console.groupEnd();
        } else {
            console.log.apply(console, output.args);
        }
    };

    //Here's comes the Magic!
    CLog.prototype.log = function() {
        // Check if Browser is Chrome
        if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
            //Returns a normalized array (with [0] being a color)
            var input = _normalizeArguments(arguments);
            var output = _createOutput(input);
            _print(output);

        } else {
            console.log.apply(console, arguments);
        }
    };

    // Clear console if called
    CLog.prototype.clear = function() {
        console.clear();
    };

    // Compatibility for the old require() API. If we're in the browser, add CLog as a global object.
    if (typeof exports !== 'undefined') {
        if (typeof module !== 'undefined' && module.exports) {
            exports = module.exports = CLog;
        }
        exports.CLog = CLog;
    } else {
        w.CLog = CLog;

        if (typeof define === 'function' && define.amd) {
            define('CLog', [], function() {
                return CLog; });
        }
    }
}(this));


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Microsoft.Win32.SafeHandles;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;

namespace System.Net.Sockets
{
    public partial class Socket
    {
        private DynamicWinsockMethods _dynamicWinsockMethods;

        internal void ReplaceHandleIfNecessaryAfterFailedConnect() { /* nop on Windows */ }

        private void EnsureDynamicWinsockMethods()
        {
            if (_dynamicWinsockMethods == null)
            {
                _dynamicWinsockMethods = DynamicWinsockMethods.GetMethods(_addressFamily, _socketType, _protocolType);
            }
        }

        internal unsafe bool AcceptEx(SafeSocketHandle listenSocketHandle,
            SafeSocketHandle acceptSocketHandle,
            IntPtr buffer,
            int len,
            int localAddressLength,
            int remoteAddressLength,
            out int bytesReceived,
            NativeOverlapped* overlapped)
        {
            EnsureDynamicWinsockMethods();
            AcceptExDelegate acceptEx = _dynamicWinsockMethods.GetDelegate<AcceptExDelegate>(listenSocketHandle);

            return acceptEx(listenSocketHandle,
                acceptSocketHandle,
                buffer,
                len,
                localAddressLength,
                remoteAddressLength,
                out bytesReceived,
                overlapped);
        }

        internal void GetAcceptExSockaddrs(IntPtr buffer,
            int receiveDataLength,
            int localAddressLength,
            int remoteAddressLength,
            out IntPtr localSocketAddress,
            out int localSocketAddressLength,
            out IntPtr remoteSocketAddress,
            out int remoteSocketAddressLength)
        {
            EnsureDynamicWinsockMethods();
            GetAcceptExSockaddrsDelegate getAcceptExSockaddrs = _dynamicWinsockMethods.GetDelegate<GetAcceptExSockaddrsDelegate>(_handle);

            getAcceptExSockaddrs(buffer,
                receiveDataLength,
                localAddressLength,
                remoteAddressLength,
                out localSocketAddress,
                out localSocketAddressLength,
                out remoteSocketAddress,
                out remoteSocketAddressLength);
        }

        internal unsafe bool DisconnectEx(SafeSocketHandle socketHandle, NativeOverlapped* overlapped, int flags, int reserved)
        {
            EnsureDynamicWinsockMethods();
            DisconnectExDelegate disconnectEx = _dynamicWinsockMethods.GetDelegate<DisconnectExDelegate>(socketHandle);

            return disconnectEx(socketHandle, overlapped, flags, reserved);
        }

        internal bool DisconnectExBlocking(SafeSocketHandle socketHandle, IntPtr overlapped, int flags, int reserved)
        {
            EnsureDynamicWinsockMethods();
            DisconnectExDelegateBlocking disconnectEx_Blocking = _dynamicWinsockMethods.GetDelegate<DisconnectExDelegateBlocking>(socketHandle);

            return disconnectEx_Blocking(socketHandle, overlapped, flags, reserved);
        }

        internal unsafe bool ConnectEx(SafeSocketHandle socketHandle,
            IntPtr socketAddress,
            int socketAddressSize,
            IntPtr buffer,
            int dataLength,
            out int bytesSent,
            NativeOverlapped* overlapped)
        {
            EnsureDynamicWinsockMethods();
            ConnectExDelegate connectEx = _dynamicWinsockMethods.GetDelegate<ConnectExDelegate>(socketHandle);

            return connectEx(socketHandle, socketAddress, socketAddressSize, buffer, dataLength, out bytesSent, overlapped);
        }

        internal unsafe SocketError WSARecvMsg(SafeSocketHandle socketHandle, IntPtr msg, out int bytesTransferred, NativeOverlapped* overlapped, IntPtr completionRoutine)
        {
            EnsureDynamicWinsockMethods();
            WSARecvMsgDelegate recvMsg = _dynamicWinsockMethods.GetDelegate<WSARecvMsgDelegate>(socketHandle);

            return recvMsg(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
        }

        internal SocketError WSARecvMsgBlocking(IntPtr socketHandle, IntPtr msg, out int bytesTransferred, IntPtr overlapped, IntPtr completionRoutine)
        {
            EnsureDynamicWinsockMethods();
            WSARecvMsgDelegateBlocking recvMsg_Blocking = _dynamicWinsockMethods.GetDelegate<WSARecvMsgDelegateBlocking>(_handle);

            return recvMsg_Blocking(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
        }

        internal unsafe bool TransmitPackets(SafeSocketHandle socketHandle, IntPtr packetArray, int elementCount, int sendSize, NativeOverlapped* overlapped, TransmitFileOptions flags)
        {
            EnsureDynamicWinsockMethods();
            TransmitPacketsDelegate transmitPackets = _dynamicWinsockMethods.GetDelegate<TransmitPacketsDelegate>(socketHandle);

            return transmitPackets(socketHandle, packetArray, elementCount, sendSize, overlapped, flags);
        }

        internal static void SocketListToFileDescriptorSet(IList socketList, Span<IntPtr> fileDescriptorSet)
        {
            int count;
            if (socketList == null || (count = socketList.Count) == 0)
            {
                return;
            }

            Debug.Assert(fileDescriptorSet.Length >= count + 1);

            fileDescriptorSet[0] = (IntPtr)count;
            for (int current = 0; current < count; current++)
            {
                if (!(socketList[current] is Socket))
                {
                    throw new ArgumentException(SR.Format(SR.net_sockets_select, socketList[current].GetType().FullName, typeof(System.Net.Sockets.Socket).FullName), nameof(socketList));
                }

                fileDescriptorSet[current + 1] = ((Socket)socketList[current])._handle.DangerousGetHandle();
            }
        }

        // Transform the list socketList such that the only sockets left are those
        // with a file descriptor contained in the array "fileDescriptorArray".
        internal static void SelectFileDescriptor(IList socketList, Span<IntPtr> fileDescriptorSet)
        {
            // Walk the list in order.
            //
            // Note that the counter is not necessarily incremented at each step;
            // when the socket is removed, advancing occurs automatically as the
            // other elements are shifted down.
            int count;
            if (socketList == null || (count = socketList.Count) == 0)
            {
                return;
            }

            Debug.Assert(fileDescriptorSet.Length >= count + 1);

            int returnedCount = (int)fileDescriptorSet[0];
            if (returnedCount == 0)
            {
                // No socket present, will never find any socket, remove them all.
                socketList.Clear();
                return;
            }

            lock (socketList)
            {
                for (int currentSocket = 0; currentSocket < count; currentSocket++)
                {
                    Socket socket = socketList[currentSocket] as Socket;

                    // Look for the file descriptor in the array.
                    int currentFileDescriptor;
                    for (currentFileDescriptor = 0; currentFileDescriptor < returnedCount; currentFileDescriptor++)
                    {
                        if (fileDescriptorSet[currentFileDescriptor + 1] == socket._handle.DangerousGetHandle())
                        {
                            break;
                        }
                    }

                    if (currentFileDescriptor == returnedCount)
                    {
                        // Descriptor not found: remove the current socket and start again.
                        socketList.RemoveAt(currentSocket--);
                        count--;
                    }
                }
            }
        }

        private Socket GetOrCreateAcceptSocket(Socket acceptSocket, bool checkDisconnected, string propertyName, out SafeSocketHandle handle)
        {
            // If an acceptSocket isn't specified, then we need to create one.
            if (acceptSocket == null)
            {
                acceptSocket = new Socket(_addressFamily, _socketType, _protocolType);
            }
            else if (acceptSocket._rightEndPoint != null && (!checkDisconnected || !acceptSocket._isDisconnected))
            {
                throw new InvalidOperationException(SR.Format(SR.net_sockets_namedmustnotbebound, propertyName));
            }

            handle = acceptSocket._handle;
            return acceptSocket;
        }

        private void SendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
        {
            // Open the file, if any
            FileStream fileStream = OpenFile(fileName);

            SocketError errorCode;
            using (fileStream)
            {
                SafeFileHandle fileHandle = fileStream?.SafeFileHandle;

                // This can throw ObjectDisposedException.
                errorCode = SocketPal.SendFile(_handle, fileHandle, preBuffer, postBuffer, flags);
            }

            if (errorCode != SocketError.Success)
            {
                UpdateStatusAfterSocketErrorAndThrowException(errorCode);
            }

            // If the user passed the Disconnect and/or ReuseSocket flags, then TransmitFile disconnected the socket.
            // Update our state to reflect this.
            if ((flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0)
            {
                SetToDisconnected();
                _remoteEndPoint = null;
            }
        }

        private IAsyncResult BeginSendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
        {
            FileStream fileStream = OpenFile(fileName);

            TransmitFileAsyncResult asyncResult = new TransmitFileAsyncResult(this, state, callback);
            asyncResult.StartPostingAsyncOp(false);

            SocketError errorCode = SocketPal.SendFileAsync(_handle, fileStream, preBuffer, postBuffer, flags, asyncResult);

            // Check for synchronous exception
            if (!CheckErrorAndUpdateStatus(errorCode))
            {
                throw new SocketException((int)errorCode);
            }

            asyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);

            return asyncResult;
        }

        private void EndSendFileInternal(IAsyncResult asyncResult)
        {
            TransmitFileAsyncResult castedAsyncResult = asyncResult as TransmitFileAsyncResult;
            if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
            {
                throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
            }

            if (castedAsyncResult.EndCalled)
            {
                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndSendFile"));
            }

            castedAsyncResult.InternalWaitForCompletion();
            castedAsyncResult.EndCalled = true;

            // If the user passed the Disconnect and/or ReuseSocket flags, then TransmitFile disconnected the socket.
            // Update our state to reflect this.
            if (castedAsyncResult.DoDisconnect)
            {
                SetToDisconnected();
                _remoteEndPoint = null;
            }

            if ((SocketError)castedAsyncResult.ErrorCode != SocketError.Success)
            {
                UpdateStatusAfterSocketErrorAndThrowException((SocketError)castedAsyncResult.ErrorCode);
            }

        }

        internal ThreadPoolBoundHandle GetOrAllocateThreadPoolBoundHandle() =>
            _handle.GetThreadPoolBoundHandle() ??
            GetOrAllocateThreadPoolBoundHandleSlow();

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal ThreadPoolBoundHandle GetOrAllocateThreadPoolBoundHandleSlow()
        {
            // There is a known bug that exists through Windows 7 with UDP and SetFileCompletionNotificationModes.
            // So, don't try to enable skipping the completion port on success in this case.
            bool trySkipCompletionPortOnSuccess = !(CompletionPortHelper.PlatformHasUdpIssue && _protocolType == ProtocolType.Udp);
            return _handle.GetOrAllocateThreadPoolBoundHandle(trySkipCompletionPortOnSuccess);
        }
    }
}


text:
package com.floogulinc.toastweb.controller;

import java.util.HashMap;

import com.floogulinc.toastweb.WebHandler;

import spark.Request;
import spark.Response;

public class IndexController implements Controller {

    public IndexController() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public Object handle(Request request, Response response) throws Exception {

        HashMap<String, Object> map = new HashMap<String, Object>();

//      HashMap<String, Object> map = hashMapOf(
//                Pair("match_number", 0),
//                Pair("match_type", "test")
//        )
        // TODO Auto-generated method stub
        return WebHandler.applyTemplate("index.html", map);

        //return null;
    }

    @Override
    public String address() {
        // TODO Auto-generated method stub
        return "/";
    }

    @Override
    public void init() {
        // TODO Auto-generated method stub

    }

}


text:
<?php
$mysqli = new mysqli("localhost", "root", "123456",
"xsl", 3306);

/* check connection */
if (mysqli_connect_errno()) {
	printf("Connect failed: %s\n", mysqli_connect_error());
	exit();
}

$city = "2";

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT id FROM x_logs WHERE id=?")) {

	/* bind parameters for markers */
	$stmt->bind_param("i", $city);

	/* execute query */
	$stmt->execute();

	/* bind result variables */
	$stmt->bind_result($district);

	/* fetch value */
	$stmt->fetch();

	printf("%s is in district %s\n", $city, $district);

	/* close statement */
	$stmt->close();
}

/* close connection */
$mysqli->close();


text:
<?php

namespace MozGallery\Service;

class Container
{
    private $data;

    /**
     * Set a value for a key
     *
     * @param string  $key    Key
     * @param mixed   $value  Value
     *
     * @return self
     */
    public function set($key, $value)
    {
        $this->data[$key] = $value;
        return $this;
    }

    /**
     * Get the value for a key
     *
     * If the value is a callable, then it gets executed the first time
     * it is requested, then the same object/result is returned on subsequent
     * calls.
     *
     * @param string  $key  Key
     *
     * @return mixed
     */
    public function get($key)
    {
        if (!isset($this->data[$key])) {
            throw new \OutOfBoundsException('Key does not exist');
        }

        if (is_callable($this->data[$key])) {
            $this->data[$key] = $this->data[$key]($this);
            return $this->data[$key];
        }

        return $this->data[$key];
    }

    /**
     * Check if the container has a value for a key
     *
     * @param string  $key
     *
     * @return bool
     */
    public function has($key)
    {
        return isset($this->data[$key]);
    }
}