text:
[![Join the chat at https://gitter.im/gunadarma-academy/asde-screaming-airman](https://badges.gitter.im/gunadarma-academy/asde-screaming-airman.svg)](https://gitter.im/gunadarma-academy/asde-screaming-airman?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Kiri Bang! merupakan aplikasi mobile berbasis Android yang memudahkan warga Kota Bogor atau masyarakat yang berkegiatan di Kota Bogor dalam menggunakan sarana transportasi angkot yang terdapat di Kota Bogor. Aplikasi ini memudahkan penggunanya dalam menggunakan angkot di Kota Bogor dengan menampilkan rute angkot yang ada di Kota Bogor

## Team Member

| Name   | Email              | GitHub |
|--------|--------------------|--------|
| Mahesa | mahesa.ss@gmail.com | [@mahesasunts](https://github.com/mahesasunts)
| Anneke | annekeannassia@gmail.com | [@annekeannassia](https://github.com/annekeannassia)
| Hendry | hendry.gustin@gmail.com | [@hendrygustin](https://github.com/hendrygustin)
| Junior | juniorlie22@gmail.com | [@juniorlie](https://github.com/juniorlie)

--------------------------------------------------

## User Documentation

Cara penggunaan aplikasi Kiri Bang! dapat dilihat pada [User Manual] (https://github.com/gunadarma-academy/asde-screaming-airman/blob/master/dokumen/UserManual-KiriBang.pdf)

## Technical Documentation

Pada project ini terdapat beberapa dokumentasi teknis :
+ [Requirements] (https://github.com/gunadarma-academy/asde-screaming-airman/blob/master/dokumen/requirements.md)
+ [Software Requirements Specification] (https://github.com/gunadarma-academy/asde-screaming-airman/blob/master/dokumen/SoftwareRequirementsSpecification.pdf)
+ [Burndown Chart] (https://github.com/gunadarma-academy/asde-screaming-airman/blob/master/dokumen/Burndown.pdf)
+ [Master Test Plan] (https://github.com/gunadarma-academy/asde-screaming-airman-test/tree/master/skenario-tes/PDF%20Version)
+ [Scenario Test and Results] (https://github.com/gunadarma-academy/asde-screaming-airman-test/tree/master/skenario-tes/PDF%20Version/skenario-test-and-result)
+ [UML] (https://github.com/gunadarma-academy/asde-screaming-airman/tree/master/data/UML)
+ [Wireframe] (https://github.com/gunadarma-academy/asde-screaming-airman/tree/master/data/wireframe)
+ [Mockup Prototype 1] (https://github.com/gunadarma-academy/asde-screaming-airman/tree/master/dokumen/mockup/prototype-1)
+ [Mockup Prototype 2] (https://github.com/gunadarma-academy/asde-screaming-airman/tree/master/dokumen/mockup/prototype-2)

--------------------------------------------------

## General Notes

For the most updated notes, see <https://github.com/gunadarma-academy/ASDE>. This README is a template from <https://github.com/gunadarma-academy/asde-project>.

### Materials

+ Introduction
+ Project Management
+ Software Design
+ Design Analysis
+ Evaluation
+ Software Quality
+ Project Presentation

### Development Process

+ Ideation
  + Choose an idea then present it.
  + Constantly improve or iterate on the idea.
  + The idea is a usable software application.
  + Implement the idea using any kind of methods.
+ Build
  + Document the software design and engineering theory sufficiently.
  + Build the software using any kind of libraries or frameworks.
+ Presentation
  + Present the result to the class.
  + The winner will be chosen.


text:
#ifndef MYUTILSIMAGE_VIDEOWRITE_H
#define MYUTILSIMAGE_VIDEOWRITE_H

#include "../myutilsimage_c.h"

#ifndef NO_OPENCV
#include <opencv2/core/core_c.h>

typedef struct VideoWriter VideoWriter;

VideoWriter *newVideoWriter(const char *newFilename, const char *fileExtension,
		const char *codecName, double fps, IplImage *first_frame);
void addVideoFrame(VideoWriter *video_writer, IplImage *frame);
int64_t getCurrentFrame(VideoWriter *video_writer);
char *getFilename(VideoWriter *video_writer);
void closeVideoWriter(VideoWriter *video_writer);

#endif
#endif

redpajama_set_name: RedPajamaGithub


text:
> **NOTE**: You probably don't need this plugin!
>
> Gatsby works with CSS Modules by default, no need for extra plugins. You should only use this if you already know what `babel-plugin-react-css-modules` is and want to enable it for your project.

# gatsby-plugin-react-css-modules

Transforms `styleName` to `className` using compile time CSS module resolution.
See the
[babel-plugin-react-css-modules README](https://github.com/gajus/babel-plugin-react-css-modules/blob/master/README.md)
for details.

## Install

`npm install gatsby-plugin-react-css-modules`

## How to use

```javascript
// In your gatsby-config.js
plugins: [
  {
    resolve: `gatsby-plugin-react-css-modules`,
    options: {
      // *.css files are included by default.
      // To support another syntax (e.g. SCSS),
      // add `postcss-scss` to your project's devDependencies
      // and add the following option here:
      filetypes: {
        ".scss": { syntax: `postcss-scss` },
      },

      // Exclude global styles from the plugin using a RegExp:
      exclude: `\/global\/`,
      // For all the options check babel-plugin-react-css-modules README link provided above
    },
  },
]
```

Files must be named using the pattern `filename.module.css` for Gatsby to treat
them as CSS modules. You can change this behavior using a custom webpack config
https://www.gatsbyjs.com/docs/add-custom-webpack-config/


text:
package io.victoralbertos.jolyglot;

public interface CustomTypes {
  Mock mock();
  MockParameterized<Mock> mockParameterized();
}


text:
const glob = require('glob');
const path = require('path');

const errors = require('./errors');
const getFileSize = require('./get-file-size');
const getFileHash = require('./get-file-hash');

module.exports = (globOptions) => {
  const {
    globDirectory,
    globFollow,
    globIgnores,
    globPattern,
    globStrict,
  } = globOptions;
  let globbedFiles;
  try {
    globbedFiles = glob.sync(globPattern, {
      cwd: globDirectory,
      follow: globFollow,
      ignore: globIgnores,
      strict: globStrict,
    });
  } catch (err) {
    throw new Error(errors['unable-to-glob-files'] + ` '${err.message}'`);
  }

  if (globbedFiles.length === 0) {
    throw new Error(errors['useless-glob-pattern'] + ' ' +
      JSON.stringify({globDirectory, globPattern, globIgnores}, null, 2));
  }

  const fileDetails = globbedFiles.map((file) => {
    const fullPath = path.join(globDirectory, file);
    const fileSize = getFileSize(fullPath);
    if (fileSize === null) {
      return null;
    }

    const fileHash = getFileHash(fullPath);
    return {
      file: `${path.relative(globDirectory, fullPath)}`,
      hash: fileHash,
      size: fileSize,
    };
  });

  // If !== null, means it's a valid file.
  return fileDetails.filter((details) => details !== null);
};


text:
<?php

namespace Symfony\Component\HttpKernel\Tests\DataCollector;

use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\EventDispatcher\EventDispatcher;

class RequestDataCollectorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provider
     */
    public function testCollect(Request $request, Response $response)
    {
        $c = new RequestDataCollector();

        $c->collect($request, $response);

        $this->assertSame('request',$c->getName());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\HeaderBag',$c->getRequestHeaders());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestServer());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestCookies());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestAttributes());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestRequest());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag',$c->getRequestQuery());
        $this->assertEquals('html',$c->getFormat());
        $this->assertEquals(array(),$c->getSessionAttributes());
        $this->assertEquals('en',$c->getLocale());

        $this->assertInstanceOf('Symfony\Component\HttpFoundation\HeaderBag',$c->getResponseHeaders());
        $this->assertEquals('OK',$c->getStatusText());
        $this->assertEquals(200,$c->getStatusCode());
        $this->assertEquals('application/json',$c->getContentType());
    }

    /**
     * Test various types of controller callables.
     *
     * @dataProvider provider
     */
    public function testControllerInspection(Request $request, Response $response)
    {
        // make sure we always match the line number
        $r1 = new \ReflectionMethod($this, 'testControllerInspection');
        $r2 = new \ReflectionMethod($this, 'staticControllerMethod');
        // test name, callable, expected
        $controllerTests = array(
            array(
                '"Regular" callable',
                array($this, 'testControllerInspection'),
                array(
                    'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
                    'method' => 'testControllerInspection',
                    'file' => __FILE__,
                    'line' => $r1->getStartLine()
                ),
            ),

            array(
                'Closure',
                function () { return 'foo'; },
                array(
                    'class' => __NAMESPACE__.'\{closure}',
                    'method' => null,
                    'file' => __FILE__,
                    'line' => __LINE__ - 5,
                ),
            ),

            array(
                'Static callback as string',
                'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest::staticControllerMethod',
                'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest::staticControllerMethod',
            ),

            array(
                'Static callable with instance',
                array($this, 'staticControllerMethod'),
                array(
                    'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
                    'method' => 'staticControllerMethod',
                    'file' => __FILE__,
                    'line' => $r2->getStartLine()
                ),
            ),

            array(
                'Static callable with class name',
                array('Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'staticControllerMethod'),
                array(
                    'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
                    'method' => 'staticControllerMethod',
                    'file' => __FILE__,
                    'line' => $r2->getStartLine()
                ),
            ),

            array(
                'Callable with instance depending on __call()',
                array($this, 'magicMethod'),
                array(
                    'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
                    'method' => 'magicMethod',
                    'file' => 'n/a',
                    'line' => 'n/a'
                ),
            ),

            array(
                'Callable with class name depending on __callStatic()',
                array('Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'magicMethod'),
                array(
                    'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
                    'method' => 'magicMethod',
                    'file' => 'n/a',
                    'line' => 'n/a'
                ),
            ),
        );

        $c = new RequestDataCollector();

        foreach ($controllerTests as $controllerTest) {
            $this->injectController($c, $controllerTest[1], $request);
            $c->collect($request, $response);
            $this->assertEquals($controllerTest[2], $c->getController(), sprintf('Testing: %s', $controllerTest[0]));
        }
    }

    public function provider()
    {
        if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
            return array(array(null, null));
        }

        $request = Request::create('http://test.com/foo?bar=baz');
        $request->attributes->set('foo', 'bar');

        $response = new Response();
        $response->setStatusCode(200);
        $response->headers->set('Content-Type', 'application/json');
        $response->headers->setCookie(new Cookie('foo','bar',1,'/foo','localhost',true,true));
        $response->headers->setCookie(new Cookie('bar','foo',new \DateTime('@946684800')));
        $response->headers->setCookie(new Cookie('bazz','foo','2000-12-12'));

        return array(
            array($request, $response)
        );
    }

    /**
     * Inject the given controller callable into the data collector.
     */
    protected function injectController($collector, $controller, $request)
    {
        $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
        $httpKernel = new HttpKernel(new EventDispatcher(), $resolver);
        $event = new FilterControllerEvent($httpKernel, $controller, $request, HttpKernelInterface::MASTER_REQUEST);
        $collector->onKernelController($event);
    }

    /**
     * Dummy method used as controller callable
     */
    public static function staticControllerMethod()
    {
        throw new \LogicException('Unexpected method call');
    }

    /**
     * Magic method to allow non existing methods to be called and delegated.
     */
    public function __call($method, $args)
    {
        throw new \LogicException('Unexpected method call');
    }

    /**
     * Magic method to allow non existing methods to be called and delegated.
     */
    public static function __callStatic($method, $args)
    {
        throw new \LogicException('Unexpected method call');
    }

}


text:
'use strict';
var slap
  , u = require('util')
  , _ = require('lodash')
  , clc = require('cli-color')
  , context = require('./context')
  , debug = require('debug')('slap')
  , taskFile;

slap = module.exports = function(config, taskSets, taskSetName, callback) {
  'use strict';
  var _err, errMsg, taskSet, logKey, deps, completed, completedPropKey;

  if (taskSets.context) {
    context = taskSets.context
  }

  taskSet = taskSets[taskSetName];
  if (!taskSet) {
    errMsg = u.format("Could not find the taskSet named %s.", taskSetName);
    console.log(clc.bold.red(errMsg));
    callback(new Error(errMsg));
    return;
  }

  logKey = [clc.bold('['), clc.bold.green(taskSetName), clc.bold(']')].join('');

  deps = _.result(taskSet, 'deps');

  if (deps) {
    console.log('%s Running %s dependant task sets ...', logKey, clc.bold.cyan(taskSetName));
    if (_.isString(deps)) {
      deps = [deps];
    }

    // Do the dependencies first.
    _.each(deps, function(depTaskSetName) {
      // console.log('%s %s depends on %s.', logKey, taskSetName, depTaskSetName);
      // console.log();
      slap(config, taskSets, depTaskSetName, function(err) {
        _err = err;
        return false;
      });
    });
  }

  if (!_err && taskSet.tasks && taskSet.tasks.length > 0) {
    completedPropKey = ['slap', taskSetName, 'completed'].join('.');
    completed = context.resolveProperty(completedPropKey, {createIfMissing: false});

    if (!completed) {
      console.log('%s Running %s tasks ...', logKey, clc.bold.cyan(taskSetName));
      _.each(taskSet.tasks, function(taskConfig) {
        'use strict';
        if (taskConfig.task) {
          // taskConfig.task(config, taskSets, taskSetName, taskConfig, function(err) {
          taskConfig.task(taskSetName, taskConfig, taskSets, config, function(err) {
            if (err) _err = err;
          });

          if (_err) return false;

        } else {
          debug("%s Task without a task function specified: %s", logKey, u.inspect(taskConfig));
        }
      });

      if (_err) {
        console.log(clc.bold.red(u.format('%s Unable to complete task set: %s', logKey, taskSetName)));

      } else {
        console.log('%s Finished running %s tasks.', logKey, clc.bold.cyan(taskSetName));
        context.setProperty(completedPropKey, true);

      }

    }

  }

  callback(_err);
};


text:
0.8.5.1 changes
===============

Workaround negative version numbers serialization bug.

Fix out-of-bounds check (Snarfcoin currently does not use this codepath, but we apply this
patch just to match Bitcoin 0.8.5.)

0.8.4.1 changes
===============

CVE-2013-5700 Bloom: filter crash issue - Snarfcoin 0.8.3.7 disabled bloom by default so was
unaffected by this issue, but we include their patches anyway just in case folks want to
enable bloomfilter=1.

CVE-2013-4165: RPC password timing guess vulnerability

CVE-2013-4627: Better fix for the fill-memory-with-orphaned-tx attack

Fix multi-block reorg transaction resurrection.

Fix non-standard disconnected transactions causing mempool orphans.  This bug could cause
nodes running with the -debug flag to crash, although it was lot less likely on Snarfcoin
as we disabled IsDust() in 0.8.3.x.

Mac OSX: use 'FD_FULLSYNC' with LevelDB, which will (hopefully!) prevent the database
corruption issues have experienced on OSX.

Add height parameter to getnetworkhashps.

Fix Norwegian and Swedish translations.

Minor efficiency improvement in block peer request handling.

0.8.3.7 changes
===============

Fix CVE-2013-4627 denial of service, a memory exhaustion attack that could crash low-memory nodes.

Fix a regression that caused excessive writing of the peers.dat file.

Add option for bloom filtering.

Fix Hebrew translation.


text:
.class Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;
.super Ljava/lang/Object;
.source "SVGAndroidRenderer.java"

# interfaces
.implements Lcom/caverock/androidsvg/SVG$PathInterface;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/caverock/androidsvg/SVGAndroidRenderer;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "PathConverter"
.end annotation

# instance fields
.field lastX:F

.field lastY:F

.field path:Landroid/graphics/Path;

.field final synthetic this$0:Lcom/caverock/androidsvg/SVGAndroidRenderer;

# direct methods
.method public constructor <init>(Lcom/caverock/androidsvg/SVGAndroidRenderer;Lcom/caverock/androidsvg/SVG$PathDefinition;)V
    .locals 1

    iput-object p1, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->this$0:Lcom/caverock/androidsvg/SVGAndroidRenderer;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    new-instance v0, Landroid/graphics/Path;

    invoke-direct {v0}, Landroid/graphics/Path;-><init>()V

    iput-object v0, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->path:Landroid/graphics/Path;

    if-eqz p2, :cond_0

    invoke-virtual {p2, p0}, Lcom/caverock/androidsvg/SVG$PathDefinition;->enumeratePath(Lcom/caverock/androidsvg/SVG$PathInterface;)V

    return-void

    :cond_0
    return-void
.end method

# virtual methods
.method public arcTo(FFFZZFF)V
    .locals 11

    iget v1, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->lastX:F

    iget v2, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->lastY:F

    move v3, p1

    move v4, p2

    move v5, p3

    move v6, p4

    move/from16 v7, p5

    move/from16 v8, p6

    move/from16 v9, p7

    move-object v10, p0

    invoke-static/range {v1 .. v10}, Lcom/caverock/androidsvg/SVGAndroidRenderer;->access$700(FFFFFZZFFLcom/caverock/androidsvg/SVG$PathInterface;)V

    move/from16 v0, p6

    iput v0, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->lastX:F

    move/from16 v0, p7

    iput v0, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->lastY:F

    return-void
.end method

.method public close()V
    .locals 1

    iget-object v0, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->path:Landroid/graphics/Path;

    invoke-virtual {v0}, Landroid/graphics/Path;->close()V

    return-void
.end method

.method public cubicTo(FFFFFF)V
    .locals 7

    iget-object v0, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->path:Landroid/graphics/Path;

    move v1, p1

    move v2, p2

    move v3, p3

    move v4, p4

    move v5, p5

    move v6, p6

    invoke-virtual/range {v0 .. v6}, Landroid/graphics/Path;->cubicTo(FFFFFF)V

    iput p5, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->lastX:F

    iput p6, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->lastY:F

    return-void
.end method

.method public getPath()Landroid/graphics/Path;
    .locals 1

    iget-object v0, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->path:Landroid/graphics/Path;

    return-object v0
.end method

.method public lineTo(FF)V
    .locals 1

    iget-object v0, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->path:Landroid/graphics/Path;

    invoke-virtual {v0, p1, p2}, Landroid/graphics/Path;->lineTo(FF)V

    iput p1, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->lastX:F

    iput p2, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->lastY:F

    return-void
.end method

.method public moveTo(FF)V
    .locals 1

    iget-object v0, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->path:Landroid/graphics/Path;

    invoke-virtual {v0, p1, p2}, Landroid/graphics/Path;->moveTo(FF)V

    iput p1, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->lastX:F

    iput p2, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->lastY:F

    return-void
.end method

.method public quadTo(FFFF)V
    .locals 1

    iget-object v0, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->path:Landroid/graphics/Path;

    invoke-virtual {v0, p1, p2, p3, p4}, Landroid/graphics/Path;->quadTo(FFFF)V

    iput p3, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->lastX:F

    iput p4, p0, Lcom/caverock/androidsvg/SVGAndroidRenderer$PathConverter;->lastY:F

    return-void
.end method


text:
<?php

namespace Kunstmaan\FormBundle\Entity;

use ArrayObject;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Form adaptor Interface
 */
interface FormAdaptorInterface
{
    /**
     * Modify the given FormBuilderInterface
     *
     * @param FormBuilderInterface $formBuilder The form builder
     * @param ArrayObject          $fields      The fields
     * @param int                  $sequence    The sequence of the form field
     */
    public function adaptForm(FormBuilderInterface $formBuilder, ArrayObject $fields, $sequence);

    /**
     * Returns a unique id
     *
     * @return string
     */
    public function getUniqueId();
}


text:
import argparse
import getpass
import git
import json
import logging
import os
import re
import requests
import subprocess
import sys

parser = argparse.ArgumentParser(
    epilog = "To avoid having to enter jira/review board username/password every time, setup an "
             "encrypted ~/.apache-cred files as follows:\n"
             "1) Create a file with following single "
             "line: \n{\"jira_username\" : \"appy\", \"jira_password\":\"123\", "
             "\"rb_username\":\"appy\", \"rb_password\" : \"@#$\"}\n"
             "2) Encrypt it with openssl.\n"
             "openssl enc -aes-256-cbc -in <file> -out ~/.apache-creds\n"
             "3) Delete original file.\n"
             "Now onwards, you'll need to enter this encryption key only once per run. If you "
             "forget the key, simply regenerate ~/.apache-cred file again.",
    formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument("-b", "--branch",
                    help = "Branch to use for generating diff. If not specified, tracking branch "
                         "is used. If there is no tracking branch, error will be thrown.")

# Arguments related to Jira.
parser.add_argument("-jid", "--jira-id",
                    help = "Jira id of the issue. If set, we deduce next patch version from "
                           "attachments in the jira and also upload the new patch. Script will "
                           "ask for jira username/password for authentication. If not set, "
                           "patch is named <branch>.patch.")

# Arguments related to Review Board.
parser.add_argument("-srb", "--skip-review-board",
                    help = "Don't create/update the review board.",
                    default = False, action = "store_true")
parser.add_argument("--reviewers",
                    help = "Comma separated list of users to add as reviewers.")

# Misc arguments
parser.add_argument("--patch-dir", default = "~/patches",
                    help = "Directory to store patch files. If it doesn't exist, it will be "
                          "created. Default: ~/patches")
parser.add_argument("--rb-repo", default = "hbase-git",
                    help = "Review board repository. Default: hbase-git")
args = parser.parse_args()

# Setup logger
logging.basicConfig()
logger = logging.getLogger("submit-patch")
logger.setLevel(logging.INFO)

def log_fatal_and_exit(*arg):
    logger.fatal(*arg)
    sys.exit(1)

def assert_status_code(response, expected_status_code, description):
    if response.status_code != expected_status_code:
        log_fatal_and_exit(" Oops, something went wrong when %s. \nResponse: %s %s\nExiting..",
                           description, response.status_code, response.reason)

# Make repo instance to interact with git repo.
try:
    repo = git.Repo(os.getcwd())
    git = repo.git
except git.exc.InvalidGitRepositoryError as e:
    log_fatal_and_exit(" '%s' is not valid git repo directory.\nRun from base directory of "
                       "HBase's git repo.", e)

logger.info(" Active branch: %s", repo.active_branch.name)
# Do not proceed if there are uncommitted changes.
if repo.is_dirty():
    log_fatal_and_exit(" Git status is dirty. Commit locally first.")

# Returns base branch for creating diff.
def get_base_branch():
    # if --branch is set, use it as base branch for computing diff. Also check that it's a valid branch.
    if args.branch is not None:
        base_branch = args.branch
        # Check that given branch exists.
        for ref in repo.refs:
            if ref.name == base_branch:
                return base_branch
        log_fatal_and_exit(" Branch '%s' does not exist in refs.", base_branch)
    else:
        # if --branch is not set, use tracking branch as base branch for computing diff.
        # If there is no tracking branch, log error and quit.
        tracking_branch = repo.active_branch.tracking_branch()
        if tracking_branch is None:
            log_fatal_and_exit(" Active branch doesn't have a tracking_branch. Please specify base "
                               " branch for computing diff using --branch flag.")
        logger.info(" Using tracking branch as base branch")
        return tracking_branch.name

# Returns patch name having format (JIRA).(branch name).(patch number).patch. If no jira is
# specified, patch is name (branch name).patch.
def get_patch_name(branch):
    if args.jira_id is None:
        return branch + ".patch"

    patch_name_prefix = args.jira_id.upper() + "." + branch
    return get_patch_name_with_version(patch_name_prefix)

# Fetches list of attachments from the jira, deduces next version for the patch and returns final
# patch name.
def get_patch_name_with_version(patch_name_prefix):
    # JIRA's rest api is broken wrt to attachments. https://jira.atlassian.com/browse/JRA-27637.
    # Using crude way to get list of attachments.
    url = "https://issues.apache.org/jira/browse/" + args.jira_id
    logger.info("Getting list of attachments for jira %s from %s", args.jira_id, url)
    html = requests.get(url)
    if html.status_code == 404:
        log_fatal_and_exit(" Invalid jira id : %s", args.jira_id)
    if html.status_code != 200:
        log_fatal_and_exit(" Cannot fetch jira information. Status code %s", html.status_code)
    # Iterate over patch names starting from version 1 and return when name is not already used.
    content = unicode(html.content, 'utf-8')
    for i in range(1, 1000):
        name = patch_name_prefix + "." + ('{0:03d}'.format(i)) + ".patch"
        if name not in content:
            return name

# Validates that patch directory exists, if not, creates it.
def validate_patch_dir(patch_dir):
    # Create patch_dir if it doesn't exist.
    if not os.path.exists(patch_dir):
        logger.warn(" Patch directory doesn't exist. Creating it.")
        os.mkdir(patch_dir)
    else:
        # If patch_dir exists, make sure it's a directory.
        if not os.path.isdir(patch_dir):
            log_fatal_and_exit(" '%s' exists but is not a directory. Specify another directory.",
                               patch_dir)

# Make sure current branch is ahead of base_branch by exactly 1 commit. Quits if
# - base_branch has commits not in current branch
# - current branch is same as base branch
# - current branch is ahead of base_branch by more than 1 commits
def check_diff_between_branches(base_branch):
    only_in_base_branch = git.log("HEAD.." + base_branch, oneline = True)
    only_in_active_branch = git.log(base_branch + "..HEAD", oneline = True)
    if len(only_in_base_branch) != 0:
        log_fatal_and_exit(" '%s' is ahead of current branch by %s commits. Rebase "
                           "and try again.", base_branch, len(only_in_base_branch.split("\n")))
    if len(only_in_active_branch) == 0:
        log_fatal_and_exit(" Current branch is same as '%s'. Exiting...", base_branch)
    if len(only_in_active_branch.split("\n")) > 1:
        log_fatal_and_exit(" Current branch is ahead of '%s' by %s commits. Squash into single "
                           "commit and try again.",
                           base_branch, len(only_in_active_branch.split("\n")))

# If ~/.apache-creds is present, load credentials from it otherwise prompt user.
def get_credentials():
    creds = dict()
    creds_filepath = os.path.expanduser("~/.apache-creds")
    if os.path.exists(creds_filepath):
        try:
            logger.info(" Reading ~/.apache-creds for Jira and ReviewBoard credentials")
            content = subprocess.check_output("openssl enc -aes-256-cbc -d -in " + creds_filepath,
                                              shell=True)
        except subprocess.CalledProcessError as e:
            log_fatal_and_exit(" Couldn't decrypt ~/.apache-creds file. Exiting..")
        creds = json.loads(content)
    else:
        creds['jira_username'] = raw_input("Jira username:")
        creds['jira_password'] = getpass.getpass("Jira password:")
        if not args.skip_review_board:
            creds['rb_username'] = raw_input("Review Board username:")
            creds['rb_password'] = getpass.getpass("Review Board password:")
    return creds

def attach_patch_to_jira(issue_url, patch_filepath, creds):
    # Upload patch to jira using REST API.
    headers = {'X-Atlassian-Token': 'no-check'}
    files = {'file': open(patch_filepath, 'rb')}
    jira_auth = requests.auth.HTTPBasicAuth(creds['jira_username'], creds['jira_password'])
    attachment_url = issue_url +  "/attachments"
    r = requests.post(attachment_url, headers = headers, files = files, auth = jira_auth)
    assert_status_code(r, 200, "uploading patch to jira")

def get_jira_summary(issue_url):
    r = requests.get(issue_url + "?fields=summary")
    assert_status_code(r, 200, "fetching jira summary")
    return json.loads(r.content)["fields"]["summary"]

def get_review_board_id_if_present(issue_url, rb_link_title):
    r = requests.get(issue_url + "/remotelink")
    assert_status_code(r, 200, "fetching remote links")
    links = json.loads(r.content)
    for link in links:
        if link["object"]["title"] == rb_link_title:
            res = re.search("reviews.apache.org/r/([0-9]+)", link["object"]["url"])
            return res.group(1)
    return None

base_branch = get_base_branch()
# Remove remote repo name from branch name if present. This assumes that we don't use '/' in
# actual branch names.
base_branch_without_remote = base_branch.split('/')[-1]
logger.info(" Base branch: %s", base_branch)

check_diff_between_branches(base_branch)

patch_dir = os.path.abspath(os.path.expanduser(args.patch_dir))
logger.info(" Patch directory: %s", patch_dir)
validate_patch_dir(patch_dir)

patch_filename = get_patch_name(base_branch_without_remote)
logger.info(" Patch name: %s", patch_filename)
patch_filepath = os.path.join(patch_dir, patch_filename)

diff = git.format_patch(base_branch, stdout = True)
with open(patch_filepath, "w") as f:
    f.write(diff.encode('utf8'))

if args.jira_id is not None:
    creds = get_credentials()
    issue_url = "https://issues.apache.org/jira/rest/api/2/issue/" + args.jira_id

    attach_patch_to_jira(issue_url, patch_filepath, creds)

    if not args.skip_review_board:
        rb_auth = requests.auth.HTTPBasicAuth(creds['rb_username'], creds['rb_password'])

        rb_link_title = "Review Board (" + base_branch_without_remote + ")"
        rb_id = get_review_board_id_if_present(issue_url, rb_link_title)

        # If no review board link found, create new review request and add its link to jira.
        if rb_id is None:
            reviews_url = "https://reviews.apache.org/api/review-requests/"
            data = {"repository" : "hbase-git"}
            r = requests.post(reviews_url, data = data, auth = rb_auth)
            assert_status_code(r, 201, "creating new review request")
            review_request = json.loads(r.content)["review_request"]
            absolute_url = review_request["absolute_url"]
            logger.info(" Created new review request: %s", absolute_url)

            # Use jira summary as review's summary too.
            summary = get_jira_summary(issue_url)
            # Use commit message as description.
            description = git.log("-1", pretty="%B")
            update_draft_data = {"bugs_closed" : [args.jira_id.upper()], "target_groups" : "hbase",
                                 "target_people" : args.reviewers, "summary" : summary,
                                 "description" : description }
            draft_url = review_request["links"]["draft"]["href"]
            r = requests.put(draft_url, data = update_draft_data, auth = rb_auth)
            assert_status_code(r, 200, "updating review draft")

            draft_request = json.loads(r.content)["draft"]
            diff_url = draft_request["links"]["draft_diffs"]["href"]
            files = {'path' : (patch_filename, open(patch_filepath, 'rb'))}
            r = requests.post(diff_url, files = files, auth = rb_auth)
            assert_status_code(r, 201, "uploading diff to review draft")

            r = requests.put(draft_url, data = {"public" : True}, auth = rb_auth)
            assert_status_code(r, 200, "publishing review request")

            # Add link to review board in the jira.
            remote_link = json.dumps({'object': {'url': absolute_url, 'title': rb_link_title}})
            jira_auth = requests.auth.HTTPBasicAuth(creds['jira_username'], creds['jira_password'])
            r = requests.post(issue_url + "/remotelink", data = remote_link, auth = jira_auth,
                              headers={'Content-Type':'application/json'})
        else:
            logger.info(" Updating existing review board: https://reviews.apache.org/r/%s", rb_id)
            draft_url = "https://reviews.apache.org/api/review-requests/" + rb_id + "/draft/"
            diff_url = draft_url + "diffs/"
            files = {'path' : (patch_filename, open(patch_filepath, 'rb'))}
            r = requests.post(diff_url, files = files, auth = rb_auth)
            assert_status_code(r, 201, "uploading diff to review draft")

            r = requests.put(draft_url, data = {"public" : True}, auth = rb_auth)
            assert_status_code(r, 200, "publishing review request")


text:
define("cool/controls/listPicker",
	[
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dojo/_base/array",
    "dojo/dom-construct",
    "dojo/dom-style",
    "dojo/aspect",
    "dojo/on",

    'gridx/Grid',
    "dijit/registry",

    'gridx/core/model/cache/Sync',
    'gridx/core/model/cache/Async',

    'dojo/store/Memory',
    'gridx/allModules',
    'gridx/modules/select/Row',
    "gridx/modules/SingleSort",

    "cool/cool",
    "cool/controls/_control",

    'dijit/_TemplatedMixin',
    'dijit/_WidgetsInTemplateMixin',

    "dojo/text!./templates/listPicker.html"

], function(declare, lang, array, domConstruct, domStyle, aspect, on,
            Grid, registry, SyncCache, AsyncCache,

            memoryStore,
            mods, SelectRow, SingleSort,

            cool, _control, _TemplatedMixin, _WidgetsInTemplateMixin, widgetTpl) {

    return declare("cool.controls.listPicker", [ _control, _TemplatedMixin, _WidgetsInTemplateMixin ], {

        templateString: widgetTpl,

        constructor: function() {
            this.inherited(arguments);
            this.grid1 = {};
            this.grid2 = {};
            this.data = [];
        },

        coolInit : function() {
            this.inherited(arguments);

            this.maindiv.style.cssText = this.cssStyles.join(';');

            var options = this.getParameter('options');

            for(var rowId in options) {
                this.data.push(lang.mixin({id:rowId}, options[rowId]));
            }

            this.grid1 = this._buildGrid();
            this.grid1.placeAt(this.grid1div, "first");
            this.grid1.startup();

            this.grid2 = this._buildGrid();
            this.grid2.placeAt(this.grid2div, "first");
            this.grid2.startup();

            if(this.definition.hasOwnProperty('value')) {
                this.set('value', this.definition.value);
                this.emit("valueInit", {});
            }

            if(this.isReadOnly()) {
                domStyle.set(this.grid1div, "display", "none");
                domStyle.set(this.grid2div, "width", "100%");
                domStyle.set(this.buttonAdd, "display", "none");
            }
        },

		_setValueAttr: function(value) {
            this._setRawValueAttr(JSON.parse(value) || []);
		},

        _setRawValueAttr: function(value) {
            var selectedIds = value || [];

            this.grid1.store.setData([]);
            this.grid2.store.setData([]);

            for(var i=0;i<this.data.length;i++) {
                var row = this.data[i];
                if(selectedIds.indexOf(row.id) >= 0)
                    this.grid2.store.put(row);
                else this.grid1.store.put(row);
            }

            this._refreshGrids();
        },

		_getValueAttr: function() {
            var allItems = this.grid2.store.query();
            var ret = [];
            for(var i=0;i<allItems.length;i++) {
                ret.push(allItems[i].id);
            }
            return JSON.stringify( ret );
		},

        moveToFirstList: function() {
            this._moveItems(this.grid2, this.grid1);
        },

        moveToSecondList: function() {
            this._moveItems(this.grid1, this.grid2);
        },

        _moveItems: function(sourceGrid, targetGrid) {

            var rowID;
            var selectedIds = sourceGrid.select.row.getSelected();
            for(var i=0;i<selectedIds.length;i++) {
                rowID = selectedIds[i];
                var row = sourceGrid.row(rowID).rawData();
                targetGrid.store.add(row);
                sourceGrid.store.remove(rowID);
            }
            this._refreshGrids();
        },

        _refreshGrids: function() {
            this.grid1.model.clearCache();
            this.grid1.body.refresh();

            this.grid2.model.clearCache();
            this.grid2.body.refresh();
        },

        _buildGrid: function() {

            var store = new memoryStore({
                data: []
            });

            var layout = [];

            var columnWidth = Math.floor( 100 / Object.keys(this.data[0]).length)+'%';
            for(var field in this.data[0]) {

                var mix = {};
                if( lang.exists(field, this.definition.columnLayouts) )
                    eval( 'mix = {'+this.definition.columnLayouts[field]+'};' );

                layout.push(
                    lang.mixin({
                        id: field,
                        field: field,
                        name: field,
                        title: this.getContainerWidget().getTranslator().trans(field),
                        sortable: true,
                        width: columnWidth
                    }, mix));
            }

            var grid = Grid({
                cacheClass: SyncCache,
                store: store,
                structure: layout,
                style: 'width:100%; height: 100%;',
                modules: [
                    SelectRow,
                    SingleSort
                ],
                selectRowTriggerOnCell:true
            });

            setTimeout(function(){ grid.resize(); }, 200);

            this.own(grid);

            return grid;
        }

    });

});


text:
var argv = require('minimist')(process.argv.slice(2));

var XLSX = require('./');
var fs = require('fs')
var INFILE = './test_files/pivot_table_test.xlsm';
var TESTFILE = './test_files/pivot_table_test.xlsm.';
//var INFILE = './test_files/formula_stress_test.xlsb';
//var TESTFILE = './test_files/formula_stress_test.xls.';
var INFILE ='./test_files/apachepoi_Tables.xlsx';
var TESTFILE='./test_files/apachepoi_Tables.xlsx.';
var INFILE = './test_files/apachepoi_45540_classic_Footer.xlsx';
var TESTFILE = './test_files/apachepoi_45540_classic_Footer.xlsx.';
var SHEET=argv.p || 0;

function stripbom(x) { return x.replace(/^\ufeff/,""); }
function fixcsv(x) { return stripbom(x).replace(/\t/g,",").replace(/#{255}/g,"").replace(/"/g,"").replace(/[\n\r]+/g,"\n").replace(/\n*$/,""); }

wb = XLSX.readFile(INFILE, {cellNF: true});

//XLSX.writeFile(wb, '/tmp/test-csv.xlsx');
//var wb = XLSX.readFile('/tmp/test-csv.xlsx', {cellNF: true});

wb = XLSX.read(XLSX.write(wb, {type:"buffer", bookType:'xlsx'}), {cellNF: true})

var csv = fixcsv(XLSX.utils.make_csv(wb.Sheets[wb.SheetNames[SHEET]]))
console.log('==================')
console.log( csv);
console.log('------------')
var exp = fixcsv(fs.readFileSync(TESTFILE + SHEET+ '.csv','utf8'))
console.log(exp)
console.log('.............')
console.log(csv==exp);

console.log(csv.length, exp.length)
if (argv.d) {
for (var i=0; i<csv.length; i++) {
  console.log([csv[i], exp[i]], csv[i] ==exp[i]);
}
}
//console.log(wb.Sheets[wb.SheetNames[0]].C2)


text:
require 'bitgirder/core'
require 'stringio'

module BitGirder
module Io

module Testing

    [ :force_encoding, :encode, :encode! ].each do |meth|
        define_method( :"opt_#{meth}" ) do |s, *argv|
            RubyVersions.when_19x( s ) { |s| s.send( meth, *argv ) }
        end
    end

    def new_string_io( str = "" )
        RubyVersions.when_19x( StringIO.new( str ) ) do |io|
            io.set_encoding( "binary" )
        end
    end

    module_function :new_string_io

    def rand_buf( len )

        len = len.bytes if len.is_a?( DataSize )
        File.open( "/dev/random", "rb" ) { |io| Io.read_full( io, len ) }
    end

    module_function :rand_buf
end

end
end


text:
#include <v8.h>
#include "macros.h"

namespace {

JS_METHOD(_resumeProfiler) {
  v8::V8::ResumeProfiler();
  return v8::Undefined();
}

JS_METHOD(_pauseProfiler) {
  v8::V8::PauseProfiler();
  return v8::Undefined();
}

// TODO: Add specific methods to pause / resume the various different types
// of profilers (like heap, etc).

} /* end namespace */

SHARED_INIT() {
  v8::HandleScope handle_scope;

  v8::Handle<v8::Object> profiler = v8::Object::New();

  profiler->Set(JS_STR("resume"),
      v8::FunctionTemplate::New(_resumeProfiler)->GetFunction());
  profiler->Set(JS_STR("pause"),
      v8::FunctionTemplate::New(_pauseProfiler)->GetFunction());

  exports->Set(JS_STR("V8Profiler"), profiler);
}


text:
/*
 * This is sample code generated by rpcgen.
 * These are only templates and you can use them
 * as a guideline for developing your own functions.
 */

#include "calculette.h"
#include "string.h"

int nbCalcul=0;

int *
calculerdouble_1_svc(int *argp, struct svc_req *rqstp)
{
	static int  result;

	nbCalcul++;
	result = (*argp) * 2;

	return &result;
}

int *
calculersomme_1_svc(struct calcul *argp, struct svc_req *rqstp)
{
	static int  result;

	result=(argp->a)+(argp->b);
	nbCalcul++;

	return &result;
}

char **
afficheridentite_1_svc(struct identite *argp, struct svc_req *rqstp)
{
	static char * result;

	char *tmp;

	tmp = strcat(argp->prenom," ");
	tmp = strcat(tmp,argp->nom);
	result=tmp;

	return &result;
}

void *
afficherconcatenationidentite_1_svc(struct identite *argp, struct svc_req *rqstp)
{
	static char * result;

	char *tmp;

	tmp = strcat(argp->prenom," ");
	tmp = strcat(tmp,argp->nom);

	printf("%s\n",tmp);

	return (void *) &result;
}

int *
nombrecalcul_1_svc(void *argp, struct svc_req *rqstp)
{
	static int  result;

	result=nbCalcul;

	return &result;
}


text:
require 'spec_helper'
require 'omnibus-ctl'

RSpec.shared_context 'object storage config' do
  let(:object_config) do
    {
      artifacts: { bucket: 'artifacts' },
      lfs: { bucket: 'lfs-objects' },
      dependency_proxy: { bucket: 'dependency_proxy' },
      external_diffs: { bucket: 'external_diffs' },
      packages: { bucket: 'packages' },
      terraform_state: { enabled: false, bucket: 'terraform' },
      ci_secure_files: { bucket: 'ci_secure_files' },
      uploads: { bucket: 'uploads' },
      pages: { bucket: 'pages' }
    }
  end
  let(:aws_connection_hash) do
    {
      'provider' => 'AWS',
      'region' => 'eu-west-1',
      'aws_access_key_id' => 'AKIAKIAKI',
      'aws_secret_access_key' => 'secret123'
    }
  end
  let(:aws_storage_options_hash) do
    {
      'server_side_encryption' => 'AES256',
      'server_side_encryption_kms_key_id' => 'arn:aws:12345'
    }
  end
  let(:azure_connection_hash) do
    {
      'provider' => 'AzureRM',
      'azure_storage_account_name' => 'testaccount',
      'azure_storage_access_key' => '1234abcd'
    }
  end

  let(:aws_connection_data) { JSON.parse(aws_connection_hash.to_json, symbolize_names: true) }
  let(:aws_storage_options) { JSON.parse(aws_storage_options_hash.to_json, symbolize_names: true) }
end


text:
import json

from django.test import TestCase
from django.http import Http404

from awl.decorators import post_required, json_post_required
from awl.waelsteng import FakeRequest
from logthing.utils import silence_logging

# ============================================================================

class Worked(Exception):
    pass

@post_required
def post_view1(request):
    raise Worked()

@post_required(['foo'])
def post_view2(request):
    raise Worked()

@json_post_required('json_data', 'deserialized')
def json_post_view(request):
    return request.deserialized

@json_post_required('json_data')
def json_post_view2(request):
    return request.json_data

# ============================================================================

class DecoratorTest(TestCase):
    @silence_logging
    def test_post_required(self):
        request = FakeRequest()
        with self.assertRaises(Http404):
            post_view1(request)

        request = FakeRequest(method='POST')
        with self.assertRaises(Worked):
            post_view1(request)

        request = FakeRequest(method='POST', data={ 'foo':'bar', })
        with self.assertRaises(Worked):
            post_view2(request)

        request.POST = {
            'bar':'bar',
        }
        with self.assertRaises(Http404):
            post_view2(request)

    @silence_logging
    def test_json_post_required(self):
        # check that it ensures POST
        request = FakeRequest()
        with self.assertRaises(Http404):
            json_post_view(request)

        # check that it ensures post data
        request = FakeRequest(method='POST')
        with self.assertRaises(Http404):
            json_post_view(request)

        # good case
        content = { 'foo':'bar', }
        data = {
            'json_data':json.dumps(content),
        }
        request = FakeRequest(method='POST', data=data)
        result = json_post_view(request)
        self.assertEqual(content, result)

        # good case with optional request_name
        result = json_post_view2(request)
        self.assertEqual(content, result)


text:
package org.hogel.batchsan.core.db.table.record;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.hogel.batchsan.core.db.dao.JobRecipeDao;

import java.sql.Timestamp;

@Data
@RequiredArgsConstructor
@NoArgsConstructor
@DatabaseTable(tableName = "job_recipe", daoClass = JobRecipeDao.class)
public class JobRecipeRecord implements BatchDatabaseRecord {
    @DatabaseField(generatedId = true)
    private long id;

    @NonNull
    @DatabaseField(canBeNull = false)
    private String name;

    @NonNull
    @DatabaseField(canBeNull = false)
    private String recipe;

    @DatabaseField(columnName = "created_at", readOnly = true)
    private Timestamp createdAt;

    @DatabaseField(columnName = "updated_at", readOnly = true)
    private Timestamp updatedAt;
}


text:
module.exports = function (client, message) {
  let newArray = client.commandarray.group(function (item) {
    return item.group;
  });

  let helpstr = "```";
  helpstr += "Command list:\n"
  for (let i = 0; i < newArray.length; i++) {
    helpstr += "   " + newArray[i].key + " type:\n";
    for (let j = 0; j < newArray[i].data.length; j++) {
      helpstr += "      " + newArray[i].data[j].commandname + "\n";
    }
  }
  helpstr += "\nBUG回報: https://github.com/smallbomb/DiscordBot.js-CGSS/issues\n";
  helpstr += "```";
  message.author.send(helpstr);
};

Object.defineProperty(Array.prototype, 'group', {
  enumerable: false,
  value: function (key) {
    let map = {};
    this.forEach(function (e) {
      let k = key(e);
      map[k] = map[k] || [];
      map[k].push(e);
    });
    return Object.keys(map).map(function (k) {
      return {key: k, data: map[k]};
    });
  },
  configurable: true
});


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef CONF_USI_H_INCLUDED
#define CONF_USI_H_INCLUDED

#include "conf_buart_if.h"
#include "conf_busart_if.h"

/* Port Communications configuration */
#define NUM_PORTS                               1
#define PORT_0 CONF_PORT(UART_TYPE, 0, 115200, TX_UART_BUF0_SIZE, \
		RX_UART_BUF0_SIZE)

/* USI protocols configuration. Enable/Disable protocols */
#define NUM_PROTOCOLS                           1
#define USE_PROTOCOL_ATPL230_PORT       0

#endif /* CONF_USI_H_INCLUDED */


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class qmaze.View.MazeComponents.QMazeRoom</title>
<meta name="date" content="2017-11-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
qmaze.View.MazeComponents.QMazeRoom

Packages that use QMazeRoom

Package
Description

qmaze.Controller

qmaze.View.MazeComponents

Uses of QMazeRoom in qmaze.Controller

Method parameters in qmaze.Controller with type arguments of type QMazeRoom

Modifier and Type
Method and Description

java.util.HashMap<Coordinates,java.util.HashMap<Coordinates,java.lang.Double>>
LearningController.getLearnings(java.util.ArrayList<QMazeRoom> rooms)

void
LearningController.initialiseMaze(java.util.ArrayList<QMazeRoom> rooms,
              int rows,
              int columns)

void
LearningController.startLearning(java.util.ArrayList<QMazeRoom> rooms,
             int rows,
             int columns,
             Coordinates startingState,
             TrainingConfig mazeConfig)

Uses of QMazeRoom in qmaze.View.MazeComponents

Methods in qmaze.View.MazeComponents that return types with arguments of type QMazeRoom

Modifier and Type
Method and Description

java.util.ArrayList<QMazeRoom>
QMazeGrid.getRooms()

Getters/setters

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<?php

namespace Code16\Sharp\Tests\Unit\Form\Layout;

use Code16\Sharp\Form\Layout\FormLayout;
use Code16\Sharp\Form\SharpForm;
use Code16\Sharp\Tests\SharpTestCase;
use Code16\Sharp\Utils\Fields\FieldsContainer;

class FormLayoutTest extends SharpTestCase
{
    /** @test */
    public function we_can_add_a_tab()
    {
        $form = new class extends FormLayoutTestForm
        {
            public function buildFormLayout(FormLayout $formLayout): void
            {
                $formLayout->addTab('label');
            }
        };

        $this->assertCount(1, $form->formLayout()['tabs']);
    }

    /** @test */
    public function we_can_add_a_column()
    {
        $form = new class extends FormLayoutTestForm
        {
            public function buildFormLayout(FormLayout $formLayout): void
            {
                $formLayout->addColumn(2);
            }
        };

        $this->assertCount(1, $form->formLayout()['tabs'][0]['columns']);
    }

    /** @test */
    public function we_can_see_layout_as_array()
    {
        $form = new class extends FormLayoutTestForm
        {
            public function buildFormLayout(FormLayout $formLayout): void
            {
                $formLayout->addTab('label');
            }
        };

        $this->assertArraySubset(
            ['title' => 'label', 'columns' => []],
            $form->formLayout()['tabs'][0],
        );

        $form2 = new class extends FormLayoutTestForm
        {
            public function buildFormLayout(FormLayout $formLayout): void
            {
                $formLayout->addColumn(2);
            }
        };

        $this->assertArraySubset(
            [
                'columns' => [
                    ['size' => 2],
                ],
            ],
            $form2->formLayout()['tabs'][0],
        );
    }

    /** @test */
    public function we_can_set_tabbed_to_false()
    {
        $form = new class extends FormLayoutTestForm
        {
            public function buildFormLayout(FormLayout $formLayout): void
            {
                $formLayout->addTab('label')->setTabbed(false);
            }
        };

        $this->assertFalse($form->formLayout()['tabbed']);
    }
}

abstract class FormLayoutTestForm extends SharpForm
{
    public function find($id): array
    {
        return [];
    }

    public function update($id, array $data)
    {
        return false;
    }

    public function delete($id): void
    {
    }

    public function buildFormFields(FieldsContainer $formFields): void
    {
    }
}


text:
define(function() {

    return {
        /**
         * methodOne; Morbi condimentum lacus vitae velit semper porttitor at nec massa.
         * Fusce ultricies eros at est aliquet, vel laoreet nisl pulvinar.
         *
         * ``
         * moduleC.methodOne('foo', 'bar');
         * ``
         *
         * @param {String} arg1 argument 1
         * @param {String} arg2 argument 2
         * @returns {String} some result
        */
        methodOne: function(arg1, arg2) {
        },

        /**
         * methodTwo; Morbi condimentum lacus vitae velit semper porttitor at nec massa.
         * Fusce ultricies eros at est aliquet, vel laoreet nisl pulvinar.
        */
        methodTwo: function() {
        }
    };

});


text:
package main

import (
	"flag"

	"github.com/edwardchoh/miniscope/cscope"
	"github.com/go-playground/log"
	"github.com/go-playground/log/handlers/console"
)

func main() {
	listenAddr := flag.String("listen", ":8080", "Listen Address (default *:8080)")
	cscopeOutPath := flag.String("path", ".", "Specify path to cscope.out")
	assetsPath := flag.String("assets", "", "Debug mode to load assets from directory")
	flag.Parse()

	cLog := console.New()
	log.RegisterHandler(cLog, log.AllLevels...)
	h, err := cscope.NewHttpServer(*listenAddr, *cscopeOutPath, *assetsPath)

	if err != nil {
		log.Error(err)
		return
	}

	log.Info("Listening on ", *listenAddr, " using database at ", *cscopeOutPath)
	if err = h.ListenAndServe(); err != nil {
		log.Error(err)
		return
	}
}


text:
package bear.session;

import chaschev.util.Exceptions;
import org.eclipse.aether.util.version.GenericVersionScheme;
import org.eclipse.aether.version.InvalidVersionSpecificationException;
import org.eclipse.aether.version.Version;
import org.eclipse.aether.version.VersionConstraint;
import org.eclipse.aether.version.VersionRange;

/**
 * @author Andrey Chaschev chaschev@gmail.com
 */
public class Versions {
    public static final VersionConstraint ANY = newConstConstraint("ANY", true);
    public static final Version ANY_VERSION = newAnyVersion("ANY", 0);

    private static Version newAnyVersion(final String s, final int compareTo) {
        return new Version() {
            @Override
            public int compareTo(Version o) {
                return compareTo;
            }

            @Override
            public String toString() {
                return s;
            }
        };
    }

    public static final VersionConstraint LATEST = newConstConstraint("LATEST", true);
    public static final Version NOT_INSTALLED = newAnyVersion("NOT_INSTALLED", -1);

    public static final GenericVersionScheme VERSION_SCHEME = new GenericVersionScheme();

    private Versions() {
    }

    public static Version newVersion(String version) {
        try {
            return VERSION_SCHEME.parseVersion(version);
        } catch (InvalidVersionSpecificationException e) {
            throw Exceptions.runtime(e);
        }
    }

    public static VersionConstraint newVersionConstraint(String versionConstrain) {
        try {
            if (versionConstrain == null || versionConstrain.equals("*")) {
                return ANY;
            }

            if ("LATEST".equals(versionConstrain)) return LATEST;

            return VERSION_SCHEME.parseVersionConstraint(versionConstrain);
        } catch (InvalidVersionSpecificationException e) {
            throw Exceptions.runtime(e);
        }
    }

    public static String toString(Version v) {
        return ((v == null || v == ANY) ? "" : v.toString());
    }

    public boolean isAny() {
        return this == ANY_VERSION;
    }

    public boolean isLatest() {
        return this == LATEST;
    }

    public static VersionConstraint fromString(String s) {
        return newVersionConstraint(s);
    }

    private static VersionConstraint newConstConstraint(final String name, final boolean value) {
        return new VersionConstraint() {
            @Override
            public VersionRange getRange() {
                throw new UnsupportedOperationException("todo .getRange");
            }

            @Override
            public Version getVersion() {
                throw new UnsupportedOperationException("todo .getVersion");
            }

            @Override
            public boolean containsVersion(Version version) {
                return value;
            }

            @Override
            public String toString() {
                return name;
            }
        };
    }

    public static String getHighest(VersionConstraint versionConstraint){
        if(versionConstraint == LATEST || versionConstraint == ANY){
            return "";
        }

        if (versionConstraint.getRange() == null) {
            return versionConstraint.getVersion().toString();
        } else {
            VersionRange.Bound upperBound = versionConstraint.getRange().getUpperBound();

            if(upperBound == null){
                return "";
            }

            return upperBound.getVersion().toString();
        }
    }
}


text:
package i2p.bote.crypto;

import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import net.i2p.util.Log;

public class CryptoFactory {
    private static List<CryptoImplementation> instances;

    public synchronized static CryptoImplementation getInstance(int id) {
        if (instances == null)
            init();

        for (CryptoImplementation instance: instances)
            if (instance.getId() == id)
                return instance;
        return null;
    }

    public synchronized static List<CryptoImplementation> getInstances() {
        if (instances == null)
            init();

        return instances;
    }

    private static void init() {
        instances = Collections.synchronizedList(new ArrayList<CryptoImplementation>());
        instances.add(new ElGamal2048_DSA1024());
        try {
            instances.add(new ECDH256_ECDSA256());
            instances.add(new ECDH521_ECDSA521());
        }
        catch (GeneralSecurityException e) {
            Log log = new Log(CryptoFactory.class);
            log.error("Error creating ECDH256_ECDSA256 or ECDH521_ECDSA521.", e);
        }
        instances.add(new NTRUEncrypt1087_GMSS512());
    }
}


text:
package org.firstinspires.ftc.teamcode;

import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.AnalogInput;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.CRServoImpl;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorEx;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.ElapsedTime;

import org.firstinspires.ftc.robotcore.external.Telemetry;

@TeleOp( name = "FINAL", group = "FINAL")
public class PickUpDriving extends LinearOpMode {

    DcMotorEx leftMotor0;
    DcMotorEx leftMotor1;
    DcMotorEx rightMotor0;
    DcMotorEx rightMotor1;

    DcMotor pullUpMotor0;
    DcMotor pullUpMotor1;

    DcMotor elevator;
    DcMotor pickUp;

    CRServoImpl sorterServo;

    Servo blueGateServo;
    Servo orangeGateServo;

    CRServoImpl armServo;

    ColorSensor colorSensor;

    private static final int A = 0;
    private static final int B = 1;
    private static final int X = 2;
    private static final int Y = 3;

    private ElapsedTime period = new ElapsedTime();

    private void waitForTick( long periodMS ) throws InterruptedException {
        long remaining = periodMS - (long) period.milliseconds();

        if (remaining > 0) {
            Thread.sleep(remaining);
        }

        period.reset();
    }

    private double abs( double in ) {
        return ( in < 0 )? -in : in;
    }
    //private int sign( double in ) { return ( in > 0 )? 1: -1; }
    private void setHardware() {
        leftMotor0 = (DcMotorEx) hardwareMap.dcMotor.get("leftMotor0");
        leftMotor1 = (DcMotorEx) hardwareMap.dcMotor.get("leftMotor1");
        rightMotor0 = (DcMotorEx) hardwareMap.dcMotor.get("rightMotor0");
        rightMotor1 = (DcMotorEx) hardwareMap.dcMotor.get("rightMotor1");

        elevator = hardwareMap.dcMotor.get("elevator");
        pickUp = hardwareMap.dcMotor.get("pickUp");

        leftMotor0.setDirection(DcMotorSimple.Direction.REVERSE);
        leftMotor0.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
        leftMotor1.setDirection(DcMotorSimple.Direction.REVERSE);
        leftMotor1.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
        rightMotor0.setDirection(DcMotorSimple.Direction.FORWARD);
        rightMotor0.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
        rightMotor1.setDirection(DcMotorSimple.Direction.FORWARD);
        rightMotor1.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);

        pullUpMotor0 = hardwareMap.dcMotor.get("pullUp0");
        pullUpMotor0.setDirection(DcMotorSimple.Direction.REVERSE);
        pullUpMotor1 = hardwareMap.dcMotor.get("pullUp1");
        pullUpMotor1.setDirection(DcMotorSimple.Direction.FORWARD);

        elevator.setDirection(DcMotorSimple.Direction.REVERSE);
        pickUp.setDirection(DcMotorSimple.Direction.FORWARD);

        sorterServo = (CRServoImpl) hardwareMap.crservo.get("sorter");
        sorterServo.setDirection(DcMotorSimple.Direction.REVERSE);
        armServo = (CRServoImpl) hardwareMap.crservo.get("arm");
        armServo.setDirection(DcMotorSimple.Direction.FORWARD);
        blueGateServo = hardwareMap.servo.get("blue");
        orangeGateServo = hardwareMap.servo.get("orange");

        colorSensor = hardwareMap.colorSensor.get("color1");

        blueGateServo.setDirection( Servo.Direction.REVERSE );
        blueGateServo.scaleRange( 0.55, 0.70 );
        orangeGateServo.scaleRange( 0.35, 0.50 );

        elevator.setPower(0);
        pickUp.setPower(0);
    }
    private void drive() {

        //Get input from gamepad
        double RX = gamepad1.right_stick_x;
        double LX = gamepad1.left_stick_x;

        int drive = ( gamepad1.right_trigger > 0.5 || gamepad1.left_trigger > 0.5 ) ? 1 : 0;
        drive *= ( gamepad1.left_trigger > 0.5) ? -1 : 1;

        if ( abs( RX ) > 0.25 ) {
            rightSpeed = -RX;
            leftSpeed = RX;
        } else {
            leftSpeed = drive;
            rightSpeed = drive;

            double T = 1-abs(LX);

            leftSpeed *= (LX > 0.25)? 1-T: T;
            rightSpeed *= (LX < -0.25)? 1-T: T;
        }
    }

    private boolean isGamepadButtonPress( int b ) {
        if ( b == X ) {
            if (gamepad1.x && !isPressingX) {
                isPressingX = true;
                return true;
            }
            if (!gamepad1.x) isPressingX = false;
        } else if ( b == Y) {
            if ( gamepad1.y && !isPressingY ) {
                isPressingY = true;
                return true;
            }
            if ( !gamepad1.y ) isPressingY = false;
        } else if ( b == A) {
            if ( gamepad1.a && !isPressingA ) {
                isPressingA = true;
                return true;
            }
            if ( !gamepad1.a ) isPressingA = false;
        } else if ( b == B) {
            if ( gamepad1.b && !isPressingB ) {
                isPressingB = true;
                return true;
            }
            if ( !gamepad1.b ) isPressingB = false;
        }

        return false;
    }
    private void colorDetection() {

        //Color input
        float blue = colorSensor.blue();
        float red = colorSensor.red();

        orangeTimer -= (orangeTimer > 0)? deltaTime : 0;

        if ( red > blue + 40f && red >  80f  ) {
            sorterServo.setPower(1);
            orangeTimer = 0.7;
            elevatorSpeed = 0.8f;
        }

        if ( orangeTimer <=0 )
        {
            elevatorSpeed = 1;
            sorterServo.setPower(0);
        }

        return;
    }
    private void pickUpSystem() {

        pickUpSystemRunning = ( isGamepadButtonPress(X))? !pickUpSystemRunning : pickUpSystemRunning;
        int _dir = (gamepad1.dpad_right)? -1: 1;
        //Set the pickUpSystem on/off
        elevator.setPower( (pickUpSystemRunning)? 1 * elevatorSpeed * _dir: 0 );
        pickUp.setPower( (pickUpSystemRunning)? 1 * _dir: 0 );
    }
    private void arm() {

        if ( gamepad1.dpad_up ) {
            armSpeed = 1;
            armServoStart = true;
        } else if ( gamepad1.dpad_down ) {
            armSpeed = -1;
            armServoStart = false;
        } else if ( !armServoStart ) {
            armSpeed = 0;
        }

        armServo.setPower(armSpeed);

    }
    private void pullUp() {

        if ( gamepad1.a ) {
            pullUpMotor0.setPower(1);
            pullUpMotor1.setPower(1);
        } else if ( gamepad1.b ) {
            pullUpMotor0.setPower(-1);
            pullUpMotor1.setPower(-1);
        } else {
            pullUpMotor0.setPower(0);
            pullUpMotor1.setPower(0);
        }
    }

    private boolean pickUpSystemRunning = false;
    private float elevatorSpeed = 1;
    private double leftSpeed = 0;
    private double rightSpeed = 0;
    private boolean isPressingX = false;
    private boolean isPressingY = false;
    private boolean isPressingA = false;
    private boolean isPressingB = false;
    private double orangeTimer = 0;
    private boolean armServoStart = false;
    private double armSpeed = 0;

    private double deltaTime;

    public void runOpMode() {

        try {

            setHardware();

            double _largeDeltatime = -1;

            waitForStart();

            ElapsedTime _deltaTimeClock = new ElapsedTime();
            ElapsedTime _time = new ElapsedTime();

            while ( opModeIsActive()) {

                //Gets the time since last time iteration

                deltaTime = _deltaTimeClock.milliseconds() / 1000;
                _deltaTimeClock = new ElapsedTime();

                if ( armServoStart && (int) _time.seconds() % 3 == 0 ) armSpeed = 0.1;
                else armSpeed = 0;

                if ( _time.seconds() > 1 && deltaTime > _largeDeltatime ) _largeDeltatime = deltaTime;

                if ( gamepad1.y ) {
                    int dir = ( _time.milliseconds() % 200 > 100 ) ? -1: 1;
                    leftMotor0.setPower( dir );
                    leftMotor1.setPower( dir );
                    rightMotor0.setPower( dir );
                    rightMotor1.setPower( dir );
                } else {
                    drive();
                }
                colorDetection();

                pickUpSystem();

                arm();

                pullUp();

                telemetry.addData("Y: ", gamepad1.y);
                telemetry.addData("Largest DeltaTime:", _largeDeltatime);
                telemetry.addData("Time: ", _time.seconds());
                telemetry.update();

                blueGateServo.setPosition( (gamepad1.right_bumper)? 1: 0);
                orangeGateServo.setPosition( (gamepad1.left_bumper)? 1: 0);

                //Set the speed of the the motors
                rightMotor0.setPower( rightSpeed );
                rightMotor1.setPower( rightSpeed );
                leftMotor0.setPower( leftSpeed );
                leftMotor1.setPower( leftSpeed );

                waitForTick(40);
            }
        }
        catch (InterruptedException exc) {

            telemetry.addData("ERROR: ", exc );
            telemetry.update();

            leftMotor0.setPower(0);
            leftMotor1.setPower(0);
            rightMotor0.setPower(0);
            rightMotor1.setPower(0);
            pickUp.setPower(0);
            elevator.setPower(0);
            armServo.setPower(0);

            return;
        }
        finally {

        }

    }
}


text:
require 'spec_helper'

describe Krikri::Mapping do

  let(:target_class) { double('target class') }
  let(:parser) { double('parser') }
  let(:parser_args) { [1,2,3] }

  describe '#new' do
    it 'accepts target class, parser, and parser arguments' do
      expect(described_class.new(target_class, parser, *parser_args))
        .to have_attributes(klass: target_class,
                            parser: parser,
                            parser_args: parser_args)
    end
  end

  describe '#process_record' do
    let(:record) { build(:oai_dc_record) }

    it 'creates a DPLA::MAP record' do
      expect(subject.process_record(record)).to be_a DPLA::MAP::Aggregation
    end

    it 'builds target class set in initializer' do
      klass = DPLA::MAP::SourceResource
      new_mapping = Krikri::Mapping.new(klass)
      expect(new_mapping.process_record(record)).to be_a klass
    end

    shared_context 'property declarations' do
      before do
        allow(target_class).to receive(:new).and_return(target_instance)
        allow(target_instance).to receive(:my_property=).and_return('')
        allow(parser).to receive(:parse).and_return(record)
        subject.my_property ''
      end

      subject { described_class.new(target_class, parser, *parser_args) }
      let(:target_instance) { double('target instance') }
    end

    describe 'error handling' do
      include_context 'property declarations'

      before do
        allow(target_instance).to receive(:error_property=).and_raise error
        subject.error_property 'moomin'
      end

      let(:error) { RuntimeError.new }

      it 'catches errors and raises Mapping::Error ' do
        expect { subject.process_record(record) }
          .to raise_error described_class::Error
      end

      it 'tracks failed properties' do
        begin
          subject.process_record(record)
        rescue described_class::Error => err
          expect(err.properties).to contain_exactly :error_property
        end
      end

      it 'stores properties and errors in Mapping::Error' do
        begin
          subject.process_record(record)
        rescue described_class::Error => err
          expect(err.errors[:error_property]).to eq error
        end
      end
    end

    context 'with parser' do
      include_context 'property declarations'

      it 'parses record before mapping' do
        expect(parser)
          .to receive(:parse).with(record, *parser_args).and_return(record)
        subject.process_record(record)
      end
    end

    context 'with static properties' do
      before do
        subject.rightsStatement value
      end

      subject { described_class.new }
      let(:value) { 'Rights Reserved; Moomin Access Only' }

      it 'sets value' do
        expect_any_instance_of(DPLA::MAP::Aggregation)
          .to receive(:rightsStatement=).with(value)
        subject.process_record(record)
      end
    end
  end
end


text:
const Joi = require('joi');

module.exports = Joi.when('provider', {
    is  : ['twitter', 'weibo'],
    then: Joi.string().valid('tweet', 'retweet', 'quote').required(),
}).when('provider', {
    is       : ['unsplash'],
    then     : Joi.string().valid('post').required(),
    otherwise: Joi.forbidden(),
});

// .required() ?


text:
package com.catherine.facade;

public class Coupe implements Model {

	@Override
	public void buildModel() {
		System.out.println("Facade: Coupe");
	}

}


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Template Library</title>

<link rel='stylesheet' type='text/css' media='all' href='../userguide.css' />

<meta http-equiv='expires' content='-1' />
<meta http-equiv= 'pragma' content='no-cache' />
<meta name='robots' content='all' />

Documentation

Author:Phil Sturgeon

Template  ›
Documentation

Template

Method Reference

title()

Set the title of the page.

Parameters

<var>$title1</var> - string REQUIRED - send as many parameters as you like, they will be imploded with <var>$config['title_separator']</var> to create a single string, which can be called with $template['title'];</kdb> in your layouts.

Usage

$this->template->title('Blog', $article->title);

set()

Set data using a chainable method. Provide two strings or an array of data.

Usage

$this->template->set('foo', $bar);

Usage

$this->template->build('welcome_message', array('message' => 'Hi there!'));

prepend_metadata()

Add a line to the start of the <var>$template['metadata']</var> string.

Parameters

<var>$line</var> - string REQUIRED - Metadata line.

Usage

		$this->template->prepend_metadata('<script src="/js/jquery.js"></script>');

append_metadata()

Add a line to the end of the <var>$template['metadata']</var> string.

Parameters

<var>$line</var> - string REQUIRED - Metadata line.

Usage

		$this->template->append_metadata('<script src="/js/jquery.flot.js"></script>');

set_layout()

All Layout files should be in the layout folder and by default will be <var>application/views/layouts/default.php</var>, but this can be changed.

Parameters

<var>$layout</var> - string REQUIRED - name of the theme.

Usage

		$this->template

			->set_layout('two_col') // application/views/layouts/two_col.php
			->build('welcome_message'); // views/welcome_message

set_theme()

Will override the theme set in <var>$config['theme']</var>.

Parameters

<var>$theme</var> - string REQUIRED - name of the theme.

set_partial()

Set Partials from view files.

Parameters

<var>$name</var> - string REQUIRED - assign a name to the partial.

<var>$view</var> - string REQUIRED - name of the view file to look for.

<var>$data</var> - array/object OPTIONAL - assign some extra data JUST for this partial.

Usage

$this->template

	// application/views/some_folder/header
	->set_partial('header', 'some_folder/header')

	// application/views/layouts/two_col.php
	->set_layout('two_col')

	// views/welcome_message
	->build('welcome_message');

inject_partial()

Inject a chunk of HTML as a Partial.

Parameters

<var>$name</var> - string REQUIRED - assign a name to the partial.

<var>$string</var> - string REQUIRED - Chunk of HTML/Text/Whatever to go into the partial.

<var>$data</var> - array/object OPTIONAL - assign some extra data JUST for this partial.

Usage

$this->template

	// application/views/some_folder/header
	->inject_partial('header', '<h1>Hello World!</h1>')

	// application/views/layouts/two_col.php
	->set_layout('two_col')

	// views/welcome_message
	->build('welcome_message');

load_view()

Load views from theme paths if they exist.

Parameters

<var>$view</var>- string REQUIRED - Name of the view to be loaded.

<var>$data</var> - array/object OPTIONAL - assign some extra data for this view.

Return

string. The contents of the rendered view.

build()

Build the entire HTML combining partials, layouts and views.

Parameters

<var>$view</var> - string REQUIRED - Name of the view to use for the template body.

<var>$data</var> - array/object OPTIONAL - Add more data to be mixed with any data already added via $this->template->set();.

Return

string. If the 3rd argument is set to TRUE this method will return the HTML as a string.

Top of Page

CodeIgniter  ·  Copyright © 2010 Phil Sturgeon  ·  Ellislab, Inc.


text:
/*
 * Author:
 *        Faraz Hach (fhach AT cs DOT sfu DOT ca)
 *        Iman Sarrafi (isarrafi AT cs DOT sfu DOT ca)
 */

#ifndef _REF_GENOME_
#define _REF_GENOME_

int		initLoadingRefGenome(char *fileName, char *genomeInfo, int *genomeInfoSize);
void	finalizeLoadingRefGenome();
int		loadRefGenome(char **refGen, char **refGenName, int *refGenOff, int *refGenLen);

#endif


text:
package orm

import (
	"reflect"

	"github.com/go-pg/pg/types"
)

const (
	PrimaryKeyFlag = 1 << iota
	ForeignKeyFlag
	NotNullFlag
	UniqueFlag
)

type Field struct {
	Type reflect.Type

	GoName  string // struct field name, e.g. Id
	ColName types.Q
	SQLName string // SQL name, .e.g. id
	SQLType string
	Index   []int

	flags uint8

	append types.AppenderFunc
	scan   types.ScannerFunc

	isEmpty func(reflect.Value) bool
}

func (f *Field) Copy() *Field {
	copy := *f
	copy.Index = copy.Index[:len(f.Index):len(f.Index)]
	return &copy
}

func (f *Field) Has(flag uint8) bool {
	return f.flags&flag != 0
}

func (f *Field) Value(strct reflect.Value) reflect.Value {
	return strct.FieldByIndex(f.Index)
}

func (f *Field) IsEmpty(strct reflect.Value) bool {
	fv := f.Value(strct)
	return f.isEmpty(fv)
}

func (f *Field) OmitEmpty(strct reflect.Value) bool {
	return !f.Has(NotNullFlag) && f.isEmpty(f.Value(strct))
}

func (f *Field) AppendValue(b []byte, strct reflect.Value, quote int) []byte {
	fv := f.Value(strct)
	if !f.Has(NotNullFlag) && f.isEmpty(fv) {
		return types.AppendNull(b, quote)
	}
	return f.append(b, fv, quote)
}

func (f *Field) ScanValue(strct reflect.Value, b []byte) error {
	fv := fieldByIndex(strct, f.Index)
	return f.scan(fv, b)
}

type Method struct {
	Index int

	flags int8

	appender func([]byte, reflect.Value, int) []byte
}

func (m *Method) Has(flag int8) bool {
	return m.flags&flag != 0
}

func (m *Method) Value(strct reflect.Value) reflect.Value {
	return strct.Method(m.Index).Call(nil)[0]
}

func (m *Method) AppendValue(dst []byte, strct reflect.Value, quote int) []byte {
	mv := m.Value(strct)
	return m.appender(dst, mv, quote)
}


text:
<?php
/**
 * HSMongoLogger
 *
 * A simple logger class using MongoDB (WiP). Requires the MongoDB Driver (PHPLIB).
 */
class HSMongoLogger
{
	/** @var collection The collection holding the logs. */
	private $collection;

	/** @var collection_name Name for the collection. */
	private $collection_name;

	/** @var collection_size Size for the collection in MB. */
	private $collection_size;

	/**
	 * Constructor
	 *
	 * Requires a name and optional size in MB for the collection that will hold the logs.
	 *
	 * @param string $name Name for the collection.
	 *
	 * @param integer $size Size for the collection in MB.
	 *
	 * @return HSMongoLogger.
	 */
	function __construct($name, $size = 1)
	{
		if (empty($name) || !is_string($name)) {
			trigger_error("A collection name is required.", E_USER_ERROR);
		}
		if (empty($size) || !is_numeric($size)) {
			$options['size'] = 1;
		}
		$this->collection_name = $name;
		$this->collection_size = abs((int) $size);
		// validate
		if (!preg_match("/^[a-z][a-z_\d]+$/i", $this->collection_name)) {
			trigger_error(
				"Collection name is not valid. Follow the pattern: /^[a-z][a-z_\\d]+$/i.",
				E_USER_ERROR
			);
		}
		if ($this->collection_size > 100) {
			$this->collection_size = 1;
		}
	}

	/**
	 * Connect to MongoDB
	 *
	 * Connects to the server and creates the collection if necessary. Receives a connection string
	 * and if not provided, the default value is `mongodb://localhost:27017`.
	 *
	 * @param string $conn_string The connection string.
	 *
	 * @return boolean
	 */
	public function connect($conn_string = '')
	{
		// connect to localhost by default
		if (empty($conn_string)) {
			$conn_string = "mongodb://localhost:27017";
		}
		try {
			$client = new MongoDB\Client($conn_string);
			$db = $client->selectDatabase('hs_mongo_logger');
			$cols = $db->listCollections();
			$col_names = array();
			foreach ($cols as $col) {
				$col_names[] = $col->getName();
			}
			$this->collection = false;
			if (!in_array($this->collection_name, $col_names)) {
				// create simple collection
				$opts = array(
					'caped' => true,
					'size' => 1024 * 1024 * $this->collection_size, // 100 MB
				);
				$db->createCollection($this->collection_name, $opts);
				$this->collection = $db->selectCollection($this->collection_name);
				$this->collection->createIndexes([
					[
						'key' => ['timestamp' => 1]
					],
					[
						'key' => ['application' => 1]
					],
				]);
			} else {
				$this->collection = $db->selectCollection($this->collection_name);
			}
		} catch (Exception $e) {
			trigger_error($e->getMessage(), E_USER_ERROR);
			return false;
		}
		return true;
	}

	/**
	 * Save a new log record
	 *
	 * Saves a message to the logs collection. Take the message and an optional tag.
	 *
	 * @param string $message The message to be saved to the logs.
	 *
	 * @param string $application_tag An optional tag to filter the logs.
	 *
	 * @return boolean
	 */
	public function writeLog($message, $application_tag = 'Undefined')
	{
		try {
			$doc = [
				'timestamp' => time(),
				'application' => $application_tag,
				'message' => $message,
			];
			$this->collection->insertOne($doc);
			return true;
		} catch (Exception $e) {
			trigger_error($e->getMessage(), E_USER_ERROR);
			return false;
		}
	}
}


text:
A docker container running ffdiaporama (http://ffdiaporama.tuxfamily.org/)

Since it's no possible to run the current version of ffdiaporama on my Linux Mint 18.1 machine I built this Docker image to run it.

* ffdiaporama is run by a user with UID 1000
* the user is added to the `audio` group to have access to the audio device
** this works fine on my Linux Mint 18.1 host running the container but may not work on different distributions when the id of the audio group is different
* the directory `$HOME/ffdiaporama` is passed as the user's home to the container

## Build and start the container from the scratch

    git clone https://github.com/joemat/docker-ffdiaporama
    cd docker-ffdiaporama

    ## adjust build args for your needs
    sudo docker build --build-arg USERNAME=ffdiaporama --build-arg AUDIOGROUP=29 --build-arg USERID=1000 --tag=ffdiaporama .

	## Pass name of image to start to local version
    sudo bash ./start_ffdiaporama.sh ffdiaporama

## Downlaoding and starting the container from docker hub

### Fast and simple

	## Downloads and starts container from dockerhub if no parameter is passed
    sudo bash ./start_ffdiaporama.sh

### Manually

    mkdir -p "$HOME/ffdiaporama"
    xhost +localhost
    sudo docker run --rm -it \
                    --net host \
                    -v /tmp/.X11-unix:/tmp/.X11-unix \
                    -e DISPLAY \
                    --device /dev/snd \
                    --name ffdiaporama \
                    -v $HOME/ffdiaporama:/home/ffdiaporama \
                    joemat/ffdiaporama


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

/**
 * @fileoverview Behavior for network config elements.
 */

import {OncMojo} from './onc_mojo.js';

/** @polymerBehavior */
export const NetworkConfigElementBehavior = {
  properties: {
    disabled: {
      type: Boolean,
      value: false,
      reflectToAttribute: true,
    },

    /**
     * Network managed property associated with the config element.
     * @type {?OncMojo.ManagedProperty}
     */
    property: {
      type: Object,
      value: null,
    },
  },

  /**
   * @param {boolean} disabled
   * @param {?OncMojo.ManagedProperty} property
   * @return {boolean} True if the element should be disabled.
   * @protected
   */
  getDisabled_(disabled, property) {
    return disabled || (!!property && this.isNetworkPolicyEnforced(property));
  },
};


text:
<?php

/**
 * A Table displays a data table in the framework. This function must
 * be extended because the getData function is table specific.
 *
 * @package Zepi\Web\AccessControl
 * @subpackage Table
 * @author Matthias Zobrist <matthias.zobrist@zepi.net>
 * @copyright Copyright (c) 2015 zepi
 */

namespace Zepi\Web\AccessControl\Table;

use \Zepi\Web\UserInterface\Table\TableAbstract;
use \Zepi\Web\UserInterface\Table\Column;
use \Zepi\DataSource\Core\Entity\DataRequest;

/**
 * A Table displays a data table in the framework. This function must
 * be extended because the getData function is table specific.
 *
 * @author Matthias Zobrist <matthias.zobrist@zepi.net>
 * @copyright Copyright (c) 2015 zepi
 */
class GroupTable extends TableAbstract
{
    /**
     * Returns an array with all data which should be displayed on this page
     *
     * @access public
     * @param \Zepi\DataSource\Core\Entity\DataRequest $request
     * @return array
     */
    public function getData(DataRequest $request)
    {
        $groupManager = $this->framework->getInstance('\\Zepi\\Web\\AccessControl\\Manager\\GroupManager');
        $groups = $groupManager->find($request);

        return $groups;
    }

    /**
     * Returns the total number of entries are available for the given
     * data request object
     *
     * @access public
     * @param \Zepi\DataSource\Core\Entity\DataRequest $request
     * @return integer
     */
    public function countData(DataRequest $request)
    {
        $groupManager = $this->framework->getInstance('\\Zepi\\Web\\AccessControl\\Manager\\GroupManager');
        $numberOfGroups = $groupManager->count($request);

        return $numberOfGroups;
    }

    /**
     * Returns an array with all columns
     *
     * @access public
     * @return array
     */
    public function getColumns()
    {
        $translationManager = $this->framework->getInstance('\\Zepi\\Core\\Language\\Manager\\TranslationManager');

        return array(
            new Column('name', $translationManager->translate('Name', '\\Zepi\\Web\\AccessControl'), 50, true, true, Column::DATA_TYPE_HTML, 'icon-column'),
            new Column('uuid', $translationManager->translate('UUID', '\\Zepi\\Web\\AccessControl'), 50, true, true, Column::DATA_TYPE_STRING),
            new Column('actions', '', Column::WIDTH_AUTO, false, false, Column::DATA_TYPE_HTML, 'auto-width button-column')
        );
    }

    /**
     * Returns the data for the given key and row (object)
     *
     * @access public
     * @param string $key
     * @param mixed $object
     * @return mixed
     */
    public function getDataForRow($key, $object)
    {
        $translationManager = $this->framework->getInstance('\\Zepi\\Core\\Language\\Manager\\TranslationManager');

        switch ($key) {
            case 'name':
                return '' . $object->getName();
            break;

            case 'uuid':
                return $object->getUuid();
            break;

            case 'actions':
                $request = $this->framework->getRequest();
                return 'getFullRoute('administration/groups/modify/' . $object->getUuid()) . '" class="btn btn-primary">'
                     .     $translationManager->translate('Modify', '\\Zepi\\Web\\AccessControl')
                     . ''
                     . 'getFullRoute('administration/groups/delete/' . $object->getUuid()) . '" class="btn btn-danger">'
                     .     $translationManager->translate('Delete', '\\Zepi\\Web\\AccessControl')
                     . '';
            break;

            default:
                return '-';
            break;
        }
    }
}