text:
Pizza !

La doc de l'exercice est au format PDF dans _src/main/resources/doc_.

Les fichiers de tests sont dans _src/main/resources/datasets_.

Le projet prend en charge :
  * un modèle threadsafe de ce qu'est une pizza, et ses parts
  * un mécanisme de traitement en parallèle à l'aide d'un ExecutorService
  * un rendu graphique de la pizza avec ses parts

Reste à faire :
  * implémenter un algorithme qui essaie de partitionner la pizza

Idée d'algorithme :

Mon idée est de générer autant de threads qu'il y a de cellules dans le tableau (donc 1 million dans le cas de big.in), et de faire entrer en compétition tous les threads. Chaque thread regarde si de proche en proche il peut générer une part de pizza éligible (càd qui respecte les conditions de taille et de garniture), en commençant par sa cellule de départ et en y ajoutant des cellules progressivement. S'il trouve une part qui est éligible, il l'ajoute à la liste des parts (le ReentrantReadWriteLock assure que la section critique est bien protégée en écriture). S'il s'avère qu'au moment d'ajouter la part un autre thread l'a battu à la course, et que la part n'est au dernier moment plus éligible (chevauchement), alors il abandonne.


text:
__author__ = 'Michael Montero <mcmontero@gmail.com>'

# ----- Imports ---------------------------------------------------------------

from tinyAPI.base.context import Context
from tinyAPI.base.exception import ContextException

import os
import tinyAPI
import unittest

# ----- Tests -----------------------------------------------------------------

class ContextTestCase(unittest.TestCase):

    def tearDown(self):
        try:
            del os.environ['APP_SERVER_ENV']
            del os.environ['APP_SERVER_DOMAIN']
        except KeyError:
            pass

        Context().reset()

    def test_context_exceptions(self):
        try:
            Context().get_server_env()

            this.fail('Was able to get server environment even though one was '
                      + 'not set.')
        except ContextException as e:
            self.assertEqual(
                'could not find environment variable "APP_SERVER_ENV"',
                e.get_message())

        os.environ['APP_SERVER_ENV'] = 'invalid'

        try:
            Context().get_server_env()

            this.fail('Was able to get server environment even though the '
                      + 'value that was set was invalid.')
        except ContextException as e:
            self.assertEqual(
                'application server environment "invalid" is not valid',
                e.get_message())

        os.environ['APP_SERVER_ENV'] = 'staging'
        os.environ['APP_SERVER_DOMAIN'] = 'invalid'

        try:
            Context().get_server_domain()

            this.fail('Was able to get server environment even though the '
                      + 'domain provided was invalid.')
        except ContextException as e:
            self.assertEqual(
                'unrecognized server domain "invalid"',
                e.get_message()
            )

    def test_getting_server_env(self):
        os.environ['APP_SERVER_ENV'] = Context.LOCAL
        self.assertEqual(Context.LOCAL, Context().get_server_env())

    def test_getting_server_domain(self):
        os.environ['APP_SERVER_DOMAIN'] = Context.DEMO
        self.assertEqual(Context.DEMO, Context().get_server_domain())

    def test_server_env_demo(self):
        os.environ['APP_SERVER_ENV'] = Context.DEMO
        self.assertTrue(tinyAPI.env_demo())

    def test_server_env_local(self):
        os.environ['APP_SERVER_ENV'] = Context.LOCAL
        self.assertTrue(tinyAPI.env_local())

    def test_server_env_staging(self):
        os.environ['APP_SERVER_ENV'] = Context.STAGING
        self.assertTrue(tinyAPI.env_staging())

    def test_server_env_qa(self):
        os.environ['APP_SERVER_ENV'] = Context.QA
        self.assertTrue(tinyAPI.env_qa())

    def test_server_env_prod(self):
        os.environ['APP_SERVER_ENV'] = Context.PRODUCTION
        self.assertTrue(tinyAPI.env_prod())

    def test_server_env_not_prod(self):
        os.environ['APP_SERVER_ENV'] = Context.DEMO
        self.assertTrue(tinyAPI.env_not_prod())

        os.environ['APP_SERVER_ENV'] = Context.LOCAL
        self.assertTrue(tinyAPI.env_not_prod())

        Context().reset()

        os.environ['APP_SERVER_ENV'] = Context.STAGING
        self.assertTrue(tinyAPI.env_not_prod())

        Context().reset()

        os.environ['APP_SERVER_ENV'] = Context.QA
        self.assertTrue(tinyAPI.env_not_prod())

        Context().reset()

        os.environ['APP_SERVER_ENV'] = Context.PRODUCTION
        self.assertFalse(tinyAPI.env_not_prod())

    def test_cli(self):
        Context().set_cli()
        self.assertTrue(Context().is_cli())

    def test_web(self):
        Context().set_web()
        self.assertTrue(Context().is_web())

    def test_unit_test(self):
        Context().set_unit_test()
        self.assertTrue(Context().is_unit_test())

    def test_server_env_demo_from_domain(self):
        os.environ['APP_SERVER_ENV'] = Context.LOCAL
        os.environ['APP_SERVER_DOMAIN'] = 'demo'

        self.assertTrue(tinyAPI.env_local())
        self.assertTrue(tinyAPI.env_demo())

# ----- Main ------------------------------------------------------------------

if __name__ == '__main__':
    unittest.main()

redpajama_set_name: RedPajamaGithub


text:
#include <functional>
#include <memory>

#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/summary.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/histogram/histogram.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace {

static void EXPECT_SummaryMatches(const Summary& actual,
                                  const string& expected_str) {
  Summary expected;
  CHECK(protobuf::TextFormat::ParseFromString(expected_str, &expected));
  EXPECT_EQ(expected.DebugString(), actual.DebugString());
}

// --------------------------------------------------------------------------
// SummaryTensorOpV2
// --------------------------------------------------------------------------
class SummaryTensorOpV2Test : public OpsTestBase {
 protected:
  void MakeOp() {
    TF_ASSERT_OK(NodeDefBuilder("myop", "TensorSummaryV2")
                     .Input(FakeInput(DT_STRING))
                     .Input(FakeInput(DT_STRING))
                     .Input(FakeInput(DT_STRING))
                     .Finalize(node_def()));
    TF_ASSERT_OK(InitOp());
  }
};

TEST_F(SummaryTensorOpV2Test, BasicPluginData) {
  MakeOp();

  // Feed and run
  AddInputFromArray<string>(TensorShape({}), {"tag_foo"});
  AddInputFromArray<string>(TensorShape({}), {"some string tensor content"});

  // Create a SummaryMetadata that stores data for 2 plugins.
  SummaryMetadata summary_metadata;
  SummaryMetadata::PluginData* plugin_data_0 =
      summary_metadata.add_plugin_data();
  plugin_data_0->set_plugin_name("foo");
  plugin_data_0->set_content("content_for_plugin_foo");
  SummaryMetadata::PluginData* plugin_data_1 =
      summary_metadata.add_plugin_data();
  plugin_data_1->set_plugin_name("bar");
  plugin_data_1->set_content("content_for_plugin_bar");
  AddInputFromArray<string>(TensorShape({}),
                            {summary_metadata.SerializeAsString()});

  TF_ASSERT_OK(RunOpKernel());

  // Check the output size.
  Tensor* out_tensor = GetOutput(0);
  ASSERT_EQ(0, out_tensor->dims());
  Summary summary;
  ParseProtoUnlimited(&summary, out_tensor->scalar<string>()());
  ASSERT_EQ(1, summary.value_size());

  // Check the content of the tensor stored in the summary.
  Tensor string_content_tensor;
  CHECK(string_content_tensor.FromProto(summary.value(0).tensor()));
  ASSERT_EQ("some string tensor content",
            string_content_tensor.scalar<string>()());

  // Check plugin-related data.
  ASSERT_EQ("tag_foo", summary.value(0).tag());
  ASSERT_EQ(2, summary.value(0).metadata().plugin_data_size());
  ASSERT_EQ("foo", summary.value(0).metadata().plugin_data(0).plugin_name());
  ASSERT_EQ("content_for_plugin_foo",
            summary.value(0).metadata().plugin_data(0).content());
  ASSERT_EQ("bar", summary.value(0).metadata().plugin_data(1).plugin_name());
  ASSERT_EQ("content_for_plugin_bar",
            summary.value(0).metadata().plugin_data(1).content());
}

}  // namespace
}  // namespace tensorflow


text:
<?php

namespace Google\Service\Contentwarehouse;

class SnippetExtraInfo extends \Google\Collection
{
  protected $collection_key = 'candidateInfo';
  protected $candidateInfoType = SnippetExtraInfoSnippetCandidateInfo::class;
  protected $candidateInfoDataType = 'array';
  /**
   * @var bool
   */
  public $containUserQuotes;
  /**
   * @var bool
   */
  public $containVulgarCandidates;
  /**
   * @var bool
   */
  public $disableQueryFeatures;
  /**
   * @var int
   */
  public $snippetBrainSelectedCandidateIndex;
  protected $snippetsbrainModelInfoType = SnippetExtraInfoSnippetsBrainModelInfo::class;
  protected $snippetsbrainModelInfoDataType = '';

  /**
   * @param SnippetExtraInfoSnippetCandidateInfo[]
   */
  public function setCandidateInfo($candidateInfo)
  {
    $this->candidateInfo = $candidateInfo;
  }
  /**
   * @return SnippetExtraInfoSnippetCandidateInfo[]
   */
  public function getCandidateInfo()
  {
    return $this->candidateInfo;
  }
  /**
   * @param bool
   */
  public function setContainUserQuotes($containUserQuotes)
  {
    $this->containUserQuotes = $containUserQuotes;
  }
  /**
   * @return bool
   */
  public function getContainUserQuotes()
  {
    return $this->containUserQuotes;
  }
  /**
   * @param bool
   */
  public function setContainVulgarCandidates($containVulgarCandidates)
  {
    $this->containVulgarCandidates = $containVulgarCandidates;
  }
  /**
   * @return bool
   */
  public function getContainVulgarCandidates()
  {
    return $this->containVulgarCandidates;
  }
  /**
   * @param bool
   */
  public function setDisableQueryFeatures($disableQueryFeatures)
  {
    $this->disableQueryFeatures = $disableQueryFeatures;
  }
  /**
   * @return bool
   */
  public function getDisableQueryFeatures()
  {
    return $this->disableQueryFeatures;
  }
  /**
   * @param int
   */
  public function setSnippetBrainSelectedCandidateIndex($snippetBrainSelectedCandidateIndex)
  {
    $this->snippetBrainSelectedCandidateIndex = $snippetBrainSelectedCandidateIndex;
  }
  /**
   * @return int
   */
  public function getSnippetBrainSelectedCandidateIndex()
  {
    return $this->snippetBrainSelectedCandidateIndex;
  }
  /**
   * @param SnippetExtraInfoSnippetsBrainModelInfo
   */
  public function setSnippetsbrainModelInfo(SnippetExtraInfoSnippetsBrainModelInfo $snippetsbrainModelInfo)
  {
    $this->snippetsbrainModelInfo = $snippetsbrainModelInfo;
  }
  /**
   * @return SnippetExtraInfoSnippetsBrainModelInfo
   */
  public function getSnippetsbrainModelInfo()
  {
    return $this->snippetsbrainModelInfo;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(SnippetExtraInfo::class, 'Google_Service_Contentwarehouse_SnippetExtraInfo');


text:
package com.example.bigquerydatatransfer;

// [START bigquerydatatransfer_quickstart]
// Imports the Google Cloud client library

import com.google.cloud.bigquery.datatransfer.v1.DataSource;
import com.google.cloud.bigquery.datatransfer.v1.DataTransferServiceClient;
import com.google.cloud.bigquery.datatransfer.v1.DataTransferServiceClient.ListDataSourcesPagedResponse;
import com.google.cloud.bigquery.datatransfer.v1.ListDataSourcesRequest;

public class QuickstartSample {
  /** List available data sources for the BigQuery Data Transfer service. */
  public static void main(String... args) throws Exception {
    // Sets your Google Cloud Platform project ID.
    // String projectId = "YOUR_PROJECT_ID";
    String projectId = args[0];

    // Instantiate a client. If you don't specify credentials when constructing a client, the
    // client library will look for credentials in the environment, such as the
    // GOOGLE_APPLICATION_CREDENTIALS environment variable.
    try (DataTransferServiceClient client = DataTransferServiceClient.create()) {
      // Request the list of available data sources.
      String parent = String.format("projects/%s", projectId);
      ListDataSourcesRequest request =
          ListDataSourcesRequest.newBuilder().setParent(parent).build();
      ListDataSourcesPagedResponse response = client.listDataSources(request);

      // Print the results.
      System.out.println("Supported Data Sources:");
      for (DataSource dataSource : response.iterateAll()) {
        System.out.println(dataSource.getDisplayName());
        System.out.printf("\tID: %s%n", dataSource.getDataSourceId());
        System.out.printf("\tFull path: %s%n", dataSource.getName());
        System.out.printf("\tDescription: %s%n", dataSource.getDescription());
      }
    }
  }
}
// [END bigquerydatatransfer_quickstart]


text:
package com.rodrigosaito.mockwebserver.player;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.junit.Rule;
import org.junit.Test;

import java.io.IOException;
import java.net.URL;
import java.util.Date;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class PlayerWithDelayTest extends AbstractHttpTest{

    @Rule
    public Player player = new Player();

    @Test
    @Play(value = "simple_play", delay = 2000)
    public void testPlayerWithDelay() throws IOException {
        URL url = player.getURL("/");

        Date start = new Date();
        CloseableHttpResponse response = executeGet(url.toString());

        String body = EntityUtils.toString(response.getEntity());
        int statusCode = response.getStatusLine().getStatusCode();

        long totalTime = new Date().getTime() - start.getTime();

        assertEquals("Simple Tape", body);
        assertEquals(200, statusCode);
        assertTrue(totalTime > 2000);
    }
}


text:
function dir = datasetsDirectory

% DATASETSDIRECTORY Returns directory where data is stored.
%
%	Description:
%
%	DIR = DATASETSDIRECTORY returns the directory where this file is
%	located, it is assumed that any data sets downloaded have this
%	directory as their base directory.
%	 Returns:
%	  DIR - the directory where this m-file is stored.
%
%
%	See also
%	LVMLOADDATA, MAPLOADDATA

%	Copyright (c) 2005, 2006 Neil D. Lawrence

% by default return the directory where this file is.
fullSpec = which('datasetsDirectory');
ind = max(find(fullSpec == filesep));
dir = fullSpec(1:ind);


text:
---
uid: SolidEdgePart.FeatureGroup.SuppressVariable
summary:
remarks:
---


text:
package org.knowm.yank.demo;

import java.util.Properties;
import org.knowm.yank.PropertiesUtils;
import org.knowm.yank.Yank;

/**
 * Create a table called BOOKS.

 * Demonstrates hardcoding the connection pool properties rather then getting them from a Properties
 * file.

 * Note: myconnectionpoolname can be anything but it needs to match the first String argument in
 * DBProxy.* method calls. See BooksDAO.java.

 *
 * @author timmolter
 */
public class CreateBooksTable {

  public static void main(String[] args) {

    // DB Properties
    Properties dbProps = new Properties();
    dbProps.setProperty("jdbcUrl", "jdbc:mysql://localhost:3306/Yank?serverTimezone=UTC");
    dbProps.setProperty("username", "root");
    dbProps.setProperty("password", "");
    dbProps.setProperty("maximumPoolSize", "5");

    // SQL Statements in Properties file
    Properties sqlProps = PropertiesUtils.getPropertiesFromClasspath("MYSQL_SQL.properties");

    Yank.setupDefaultConnectionPool(dbProps);
    Yank.addSQLStatements(sqlProps);

    // create table
    BooksDAO.createBooksTable();

    Yank.releaseDefaultConnectionPool();
  }
}


text:
CKEDITOR.plugins.setLang( 'placeholder', 'it', {
	title: 'Proprietà segnaposto',
	toolbar: 'Crea segnaposto',
	name: 'Nome segnaposto',
	invalidName: 'Il segnaposto non può essere vuoto e non può contenere nessuno dei seguenti caratteri: [, ], <, >',
	pathName: 'segnaposto'
} );


text:
import MgnlCalculator from '../../js/calculator.js'
import $ from 'jquery'

window.$ = window.jQuery = $

describe('calculator', () => {

  it('returns a Calendar instance', () => {
    expect(new MgnlCalculator('.my-element').parseFormula).toBeTruthy()
  })

  it('parses the formula', () => {
    const formula = '([A] * [B]) / 100'
    const res = new MgnlCalculator('#uid').parseFormula(formula, 10, 20)

    expect(res).toEqual('(10 * 20) / 100')
  })

  it('returns null on empty input', () => {
    const formula = '([A] * [B]) / 100'
    const parser = new MgnlCalculator('#uid').parseFormula

    expect(parser(formula, '', 20)).toEqual(null)
    expect(parser(formula, 20, '')).toEqual(null)
  })

  it('returns null on strings as input', () => {
    const formula = '([A] * [B]) / 100'
    const parser = new MgnlCalculator('#uid').parseFormula

    expect(parser(formula, 20, 'foo')).toEqual(null)
    expect(parser(formula, 'foo', 20)).toEqual(null)
  })

  it('accepts 0 as input', () => {
    const formula = '([A] * [B]) / 100'
    const parser = new MgnlCalculator('#uid').parseFormula

    expect(parser(formula, 0, 10)).toEqual('(0 * 10) / 100')
    expect(parser(formula, 20, 0)).toEqual('(20 * 0) / 100')
  })
})


text:
if [ "${TESTSRC}" = "" ] ; then
   TESTSRC="."
fi

if [ "${TESTCLASSES}" = "" ] ; then
   TESTCLASSES="."
fi

if [ "${TESTJAVA}" = "" ] ; then
   echo "TESTJAVA not set.  Test cannot execute."
   echo "FAILED!!!"
   exit 1
fi

# set platform-dependent variables
OS=`uname -s`
case "$OS" in
  SunOS )
    PATHSEP=":"
    FILESEP="/"
    ;;
  Linux )
    PATHSEP=":"
    FILESEP="/"
    ;;
  Windows* )
    PATHSEP=";"
    FILESEP="\\"
    ;;
  * )
    echo "Unrecognized system!"
    exit 1;
    ;;
esac

# remove old class files
cd ${TESTCLASSES}${FILESEP}
rm -f ClassLoaderDeadlock.class
rm -rf provider
mkdir provider

# compile the test program
${TESTJAVA}${FILESEP}bin${FILESEP}javac \
	-d ${TESTCLASSES}${FILESEP} \
	${TESTSRC}${FILESEP}ClassLoaderDeadlock.java

${TESTJAVA}${FILESEP}bin${FILESEP}javac \
	-d ${TESTCLASSES}${FILESEP}provider${FILESEP} \
	${TESTSRC}${FILESEP}provider${FILESEP}HashProvider.java

# run the test
${TESTJAVA}${FILESEP}bin${FILESEP}java \
	-classpath ${TESTCLASSES}${PATHSEP}${TESTSRC}${FILESEP}Deadlock.jar \
	ClassLoaderDeadlock

exit $?


text:
module Softlayer
  class Network
    class Storage
      class Schedule
        class Property
          class Type < Softlayer::Entity
            SERVICE = 'SoftLayer_Network_Storage_Schedule_Property_Type'
            attr_accessor :description
            attr_accessor :id
            attr_accessor :keyname
            attr_accessor :name
            attr_accessor :nas_type

            def self.get_all_objects
              request(:get_all_objects, Array[Softlayer::Network::Storage::Schedule::Property::Type])
            end

            def get_object
              request(:get_object, Softlayer::Network::Storage::Schedule::Property::Type)
            end

            class Representer < Softlayer::Entity::Representer
              include Representable::Hash
              include Representable::Coercion
              property :description, type: String
              property :id, type: Integer
              property :keyname, type: String
              property :name, type: String
              property :nas_type, type: String
            end
          end
        end
      end
    end
  end
end


text:
.class Lcom/android/systemui/doze/DozeTriggers$1;
.super Ljava/lang/Object;
.source "DozeTriggers.java"

# interfaces
.implements Lcom/android/systemui/doze/DozeHost$Callback;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/systemui/doze/DozeTriggers;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/systemui/doze/DozeTriggers;

# direct methods
.method constructor <init>(Lcom/android/systemui/doze/DozeTriggers;)V
    .locals 0

    iput-object p1, p0, Lcom/android/systemui/doze/DozeTriggers$1;->this$0:Lcom/android/systemui/doze/DozeTriggers;

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

    return-void
.end method

# virtual methods
.method public onNotificationHeadsUp()V
    .locals 1

    iget-object v0, p0, Lcom/android/systemui/doze/DozeTriggers$1;->this$0:Lcom/android/systemui/doze/DozeTriggers;

    invoke-static {v0}, Lcom/android/systemui/doze/DozeTriggers;->-wrap2(Lcom/android/systemui/doze/DozeTriggers;)V

    return-void
.end method

.method public onPowerSaveChanged(Z)V
    .locals 1

    if-eqz p1, :cond_0

    iget-object v0, p0, Lcom/android/systemui/doze/DozeTriggers$1;->this$0:Lcom/android/systemui/doze/DozeTriggers;

    invoke-static {v0}, Lcom/android/systemui/doze/DozeTriggers;->-wrap3(Lcom/android/systemui/doze/DozeTriggers;)V

    :cond_0
    return-void
.end method


text:
require "rubygems"
require "sinatra/base"

class HelloApp < Sinatra::Base

  get "/hello/:subject" do
    "Hello, #{params[:subject]}"
  end

end


text:
package andexam.ver4_1.c34_sensor;

import andexam.ver4_1.*;
import android.app.*;
import android.content.*;
import android.graphics.*;
import android.hardware.*;
import android.os.*;
import android.view.*;

public class Compass extends Activity {
	SensorManager mSm;
	CompassView mView;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mView = new CompassView(this);
		setContentView(mView);

		mSm = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
	}

	@SuppressWarnings("deprecation")
	protected void onResume() {
		super.onResume();
		mSm.registerListener(mView, mSm.getDefaultSensor(Sensor.TYPE_ORIENTATION),
				SensorManager.SENSOR_DELAY_UI);
	}

	protected void onPause() {
		super.onPause();
		mSm.unregisterListener(mView);
	}

	class CompassView extends View implements SensorEventListener {
		float azimuth;
		float pitch;
		float roll;
		final static int MAX = 30;
		Paint textPnt = new Paint();
		Bitmap compass;
		int width;
		int height;
		int w10;
		int h10;
		int thick;
		int length;

		public CompassView(Context context) {
			super(context);
			textPnt.setColor(Color.BLACK);
			textPnt.setTextSize(20);
			textPnt.setAntiAlias(true);
			compass = BitmapFactory.decodeResource(getResources(), R.drawable.compass);
		}

		public void onSizeChanged(int w, int h, int oldw, int oldh) {
			super.onSizeChanged(w, h, oldw, oldh);
			width = w;
			height = h;
			w10 = width/10;
			h10 = height/10;
			thick = h10;
			length = w10 * 8;
		}

		public void onAccuracyChanged(Sensor sensor, int accuracy) {
		}

		@SuppressWarnings("deprecation")
		public void onSensorChanged(SensorEvent event) {
			float[] v = event.values;
			switch (event.sensor.getType()) {
			case Sensor.TYPE_ORIENTATION:
				if (azimuth != v[0] || pitch != v[1] || roll != v[2]) {
					azimuth = v[0];
					pitch = v[1];
					roll = v[2];
					invalidate();
				}
				break;
			}
		}

		public void onDraw(Canvas canvas) {
			Paint Pnt = new Paint();
			Pnt.setAntiAlias(true);

			// 수평, 수직 막대기 그림
			canvas.drawColor(Color.WHITE);
			Pnt.setColor(Color.BLACK);
			Rect pitchrt = new Rect(w10, h10, w10 + thick, h10 + length);
			canvas.drawRect(pitchrt, Pnt);
			Rect rollrt = new Rect(w10, h10*2 + length, w10*9, h10*2 + length + thick);
			canvas.drawRect(rollrt, Pnt);

			// 롤 값 표시
			float rollvalue = roll < -MAX ? -MAX:roll > MAX ? MAX:roll;
			int rollcenter = rollrt.left + rollrt.width()/2;
			int rolllength = rollrt.width() - thick;
			int rollpos = rollcenter + (int)(rolllength/2 * rollvalue / MAX);
			Pnt.setColor(rollvalue == 0 ? Color.RED:Color.YELLOW);
			canvas.drawCircle(rollpos, rollrt.top + thick/2, (int)(thick/2*0.9), Pnt);
			canvas.drawText("roll:" + (int)roll, rollrt.left, rollrt.top-5, textPnt);

			// 피치값 표시
			float pitchvalue = pitch;
			if ((Math.abs(pitch)) > 90) {
				pitchvalue = 180 - Math.abs(pitch);
				if (pitch < 0) pitchvalue *= -1;
			}
			pitchvalue = pitchvalue < -MAX ? -MAX:pitchvalue > MAX ? MAX:pitchvalue;
			int pitchcenter = pitchrt.top + pitchrt.height()/2;
			int pitchlength = pitchrt.height() - thick;
			int pitchpos = pitchcenter + (int)(pitchlength/2 * pitchvalue / MAX);
			Pnt.setColor(pitchvalue == 0 ? Color.RED:Color.YELLOW);
			canvas.drawCircle(pitchrt.left + thick/2, pitchpos, (int)(thick/2*0.9), Pnt);
			canvas.drawText("pitch:" + (int)pitch, pitchrt.left, pitchrt.top-5, textPnt);

			// 나침반 표시
			Matrix m = new Matrix();
			m.postRotate(-azimuth, compass.getWidth()/2, compass.getHeight()/2);
			m.postTranslate(rollcenter - compass.getWidth()/2 + thick,
					pitchcenter - compass.getHeight()/2);
			canvas.drawBitmap(compass, m, Pnt);
			canvas.drawText("azimuth:" + (int)azimuth, rollcenter,
					pitchcenter - compass.getHeight()/2 - 5, textPnt);
		}
	}
}


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>Index — Editorial Documentation</title>
    <link rel="stylesheet" href="_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Editorial Documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="top" title="Editorial Documentation" href="index.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <meta name = "viewport" content = "width=device-width; initial-scale=1.0; minimum-scale=1.0; maximum-scale=1.0">

Navigation

          index

          modules |

Editorial Documentation »

Index – E

e (in module cmath)

(in module math)

E2BIG (in module errno)

EACCES (in module errno)

EADDRINUSE (in module errno)

EADDRNOTAVAIL (in module errno)

EADV (in module errno)

EAFNOSUPPORT (in module errno)

EAFP

EAGAIN (in module errno)

EALREADY (in module errno)

east_asian_width() (in module unicodedata)

EBADE (in module errno)

EBADF (in module errno)

EBADFD (in module errno)

EBADMSG (in module errno)

EBADR (in module errno)

EBADRQC (in module errno)

EBADSLT (in module errno)

EBCDIC

EBFONT (in module errno)

EBUSY (in module errno)

ECHILD (in module errno)

ECHRNG (in module errno)

ECOMM (in module errno)

ECONNABORTED (in module errno)

ECONNREFUSED (in module errno)

ECONNRESET (in module errno)

EDEADLK (in module errno)

EDEADLOCK (in module errno)

EDESTADDRREQ (in module errno)

edit_action (ui.ListDataSource attribute)

edit_content() (photos.Asset method)

edit_list_dialog() (in module dialogs)

editable (ui.TextView attribute)

editing (ui.TableView attribute)

editor (module)

EDOM (in module errno)

EDOTDOT (in module errno)

EDQUOT (in module errno)

EEXIST (in module errno)

EFAULT (in module errno)

EFBIG (in module errno)

Effect (class in sound)

effective() (in module bdb)

ehlo() (smtplib.SMTP method)

ehlo_or_helo_if_needed() (smtplib.SMTP method)

EHOSTDOWN (in module errno)

EHOSTUNREACH (in module errno)

EIDRM (in module errno)

EILSEQ (in module errno)

EINPROGRESS (in module errno)

EINTR (in module errno)

EINVAL (in module errno)

EIO (in module errno)

EISCONN (in module errno)

EISDIR (in module errno)

EISNAM (in module errno)

EL2HLT (in module errno)

EL2NSYNC (in module errno)

EL3HLT (in module errno)

EL3RST (in module errno)

elapsed (requests.Response attribute), [1]

Element (class in xml.etree.ElementTree)

ElementDeclHandler() (xml.parsers.expat.xmlparser method)

elements() (collections.Counter method)

ElementTree (class in xml.etree.ElementTree)

ELIBACC (in module errno)

ELIBBAD (in module errno)

ELIBEXEC (in module errno)

ELIBMAX (in module errno)

ELIBSCN (in module errno)

elif

keyword

Ellinghouse, Lance

ellipse() (ImageDraw.ImageDraw method)

Ellipsis

object

Ellipsis (built-in variable)

ELLIPSIS (in module doctest)

EllipsisType (in module types)

ELNRNG (in module errno)

ELOOP (in module errno)

else

dangling

keyword, [1], [2], [3], [4]

email (contacts.Person attribute)

(module)

email.charset (module)

email.encoders (module)

email.errors (module)

email.generator (module)

email.header (module)

email.iterators (module)

email.message (module)

email.mime (module)

email.parser (module)

email.utils (module)

EMFILE (in module errno)

emit() (logging.FileHandler method)

(logging.Handler method)

(logging.NullHandler method)

(logging.StreamHandler method)

(logging.handlers.BufferingHandler method)

(logging.handlers.DatagramHandler method)

(logging.handlers.HTTPHandler method)

(logging.handlers.NTEventLogHandler method)

(logging.handlers.RotatingFileHandler method)

(logging.handlers.SMTPHandler method)

(logging.handlers.SocketHandler method)

(logging.handlers.SysLogHandler method)

(logging.handlers.TimedRotatingFileHandler method)

(logging.handlers.WatchedFileHandler method)

EMLINK (in module errno)

empty

list

tuple, [1]

Empty

empty() (Queue.Queue method)

(sched.scheduler method)

EMPTY_NAMESPACE (in module xml.dom)

emptyline() (cmd.Cmd method)

EMSGSIZE (in module errno)

EMULTIHOP (in module errno)

enable() (bdb.Breakpoint method)

(in module cgitb)

(in module gc)

enable_callback_tracebacks() (in module sqlite3)

enable_interspersed_args() (optparse.OptionParser method)

enable_load_extension() (sqlite3.Connection method)

enabled (ui.Button attribute)

(ui.ButtonItem attribute)

(ui.DatePicker attribute)

(ui.SegmentedControl attribute)

(ui.Switch attribute)

(ui.TextField attribute)

ENAMETOOLONG (in module errno)

ENAVAIL (in module errno)

encode

Codecs

encode() (codecs.Codec method)

(codecs.IncrementalEncoder method)

(email.header.Header method)

(in module base64)

(in module mimetools)

(in module quopri)

(in module uu)

(json.JSONEncoder method)

(str method)

(xmlrpclib.Binary method)

(xmlrpclib.Boolean method)

(xmlrpclib.DateTime method)

encode_7or8bit() (in module email.encoders)

encode_base64() (in module email.encoders)

encode_contents() (bs4.Tag method)

encode_noop() (in module email.encoders)

encode_quopri() (in module email.encoders)

encode_rfc2231() (in module email.utils)

encode_threshold (SimpleXMLRPCServer.SimpleXMLRPCRequestHandler attribute)

encoded_header_len() (email.charset.Charset method)

EncodedFile() (in module codecs)

encodePriority() (logging.handlers.SysLogHandler method)

encodestring() (in module base64)

(in module quopri)

encoding

base64

quoted-printable

encoding (exceptions.UnicodeError attribute)

(file attribute)

ENCODING (in module tarfile)

encoding (io.TextIOBase attribute)

(requests.Response attribute), [1]

encodings

encodings.idna (module)

encodings.utf_8_sig (module)

encodings_map (in module mimetypes)

(mimetypes.MimeTypes attribute)

end (exceptions.UnicodeError attribute)

end() (re.MatchObject method)

(xml.etree.ElementTree.TreeBuilder method)

end_date (photos.AssetCollection attribute)

END_FINALLY (opcode)

end_headers() (BaseHTTPServer.BaseHTTPRequestHandler method)

end_marker() (multifile.MultiFile method)

end_paragraph() (formatter.formatter method)

EndCdataSectionHandler() (xml.parsers.expat.xmlparser method)

EndDoctypeDeclHandler() (xml.parsers.expat.xmlparser method)

endDocument() (xml.sax.handler.ContentHandler method)

endElement() (xml.sax.handler.ContentHandler method)

EndElementHandler() (xml.parsers.expat.xmlparser method)

endElementNS() (xml.sax.handler.ContentHandler method)

endheaders() (httplib.HTTPConnection method)

ENDMARKER (in module token)

EndNamespaceDeclHandler() (xml.parsers.expat.xmlparser method)

endpos (re.MatchObject attribute)

endPrefixMapping() (xml.sax.handler.ContentHandler method)

endswith() (str method)

ENETDOWN (in module errno)

ENETRESET (in module errno)

ENETUNREACH (in module errno)

ENFILE (in module errno)

enhance() (ImageEnhance.enhancer method)

ENOANO (in module errno)

ENOBUFS (in module errno)

ENOCSI (in module errno)

ENODATA (in module errno)

ENODEV (in module errno)

ENOENT (in module errno)

ENOEXEC (in module errno)

ENOLCK (in module errno)

ENOLINK (in module errno)

ENOMEM (in module errno)

ENOMSG (in module errno)

ENONET (in module errno)

ENOPKG (in module errno)

ENOPROTOOPT (in module errno)

ENOSPC (in module errno)

ENOSR (in module errno)

ENOSTR (in module errno)

ENOSYS (in module errno)

ENOTBLK (in module errno)

ENOTCONN (in module errno)

ENOTDIR (in module errno)

ENOTEMPTY (in module errno)

ENOTNAM (in module errno)

ENOTSOCK (in module errno)

ENOTTY (in module errno)

ENOTUNIQ (in module errno)

enter() (sched.scheduler method)

enterabs() (sched.scheduler method)

entities (xml.dom.DocumentType attribute)

EntityDeclHandler() (xml.parsers.expat.xmlparser method)

entitydefs (in module htmlentitydefs)

EntityResolver (class in xml.sax.handler)

enumerate() (built-in function)

(in module threading)

environ (in module os)

(in module posix)

environment

environment variable

<protocol>_proxy

APPDATA

CC

CFLAGS

COMSPEC, [1]

CPP

CPPFLAGS

HOME, [1], [2]

HOMEDRIVE

HOMEPATH

LANG, [1], [2], [3], [4]

LANGUAGE, [1]

LC_ALL, [1]

LC_MESSAGES, [1]

LDCXXSHARED

LDFLAGS

LOGNAME

PAGER

PATH, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]

POSIXLY_CORRECT

PYTHONCASEOK

PYTHONDOCS

PYTHONDONTWRITEBYTECODE, [1], [2]

PYTHONINSPECT

PYTHONIOENCODING

PYTHONNOUSERSITE

PYTHONPATH, [1], [2], [3], [4], [5]

PYTHONSTARTUP, [1]

PYTHONUSERBASE

PYTHONWARNINGS, [1]

PYTHONY2K, [1], [2]

PYTHON_DOM

SystemRoot

TEMP

TMP, [1]

TMPDIR, [1]

TZ, [1], [2], [3], [4]

USERPROFILE

USER_BASE

Wimp$ScrapDir

ftp_proxy

http_proxy, [1]

no_proxy, [1]

environment variables

deleting

setting

EnvironmentError

EnvironmentVarGuard (class in test.test_support)

ENXIO (in module errno)

eo_fill_rule (ui.Path attribute)

eof (shlex.shlex attribute)

EOFError

EOPNOTSUPP (in module errno)

EOVERFLOW (in module errno)

EPERM (in module errno)

EPFNOSUPPORT (in module errno)

epilogue (email.message.Message attribute)

EPIPE (in module errno)

epoch

epoll() (in module select)

EPROTO (in module errno)

EPROTONOSUPPORT (in module errno)

EPROTOTYPE (in module errno)

eq() (in module operator)

EQEQUAL (in module token)

EQUAL (in module token)

equalize() (in module ImageOps)

ERA (in module locale)

ERA_D_FMT (in module locale)

ERA_D_T_FMT (in module locale)

ERA_T_FMT (in module locale)

ERANGE (in module errno)

EREMCHG (in module errno)

EREMOTE (in module errno)

EREMOTEIO (in module errno)

ERESTART (in module errno)

erf() (in module math)

erfc() (in module math)

EROFS (in module errno)

errcode (xmlrpclib.ProtocolError attribute)

errmsg (xmlrpclib.ProtocolError attribute)

errno

module, [1]

errno (module)

error, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]

Error, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]

error handling

error() (argparse.ArgumentParser method)

(in module logging)

(logging.Logger method)

(mhlib.Folder method)

(mhlib.MH method)

(urllib2.OpenerDirector method)

(xml.sax.handler.ErrorHandler method)

error_body (wsgiref.handlers.BaseHandler attribute)

error_content_type (BaseHTTPServer.BaseHTTPRequestHandler attribute)

error_headers (wsgiref.handlers.BaseHandler attribute)

error_leader() (shlex.shlex method)

error_message_format (BaseHTTPServer.BaseHTTPRequestHandler attribute)

error_output() (wsgiref.handlers.BaseHandler method)

error_perm

error_proto, [1]

error_reply

error_status (wsgiref.handlers.BaseHandler attribute)

error_temp

ErrorByteIndex (xml.parsers.expat.xmlparser attribute)

errorcode (in module errno)

ErrorCode (xml.parsers.expat.xmlparser attribute)

ErrorColumnNumber (xml.parsers.expat.xmlparser attribute)

ErrorHandler (class in xml.sax.handler)

ErrorLineNumber (xml.parsers.expat.xmlparser attribute)

ErrorResponse (class in dropbox.rest)

errors

Errors

(file attribute)

(io.TextIOBase attribute)

(unittest.TestResult attribute)

logging

ErrorString() (in module xml.parsers.expat)

ERRORTOKEN (in module token)

escape (shlex.shlex attribute)

escape sequence

escape() (in module cgi)

(in module re)

(in module xml.sax.saxutils)

escapechar (csv.Dialect attribute)

escapedquotes (shlex.shlex attribute)

ESHUTDOWN (in module errno)

ESOCKTNOSUPPORT (in module errno)

ESPIPE (in module errno)

ESRCH (in module errno)

ESRMNT (in module errno)

ESTALE (in module errno)

ESTRPIPE (in module errno)

ETIME (in module errno)

ETIMEDOUT (in module errno)

Etiny() (decimal.Context method)

ETOOMANYREFS (in module errno)

Etop() (decimal.Context method)

ETXTBSY (in module errno)

EUCLEAN (in module errno)

EUNATCH (in module errno)

EUSERS (in module errno)

eval

built-in function, [1], [2], [3], [4], [5], [6], [7]

eval() (built-in function)

(in module Image)

(in module ImageMath)

eval_js() (ui.WebView method)

evaluate_javascript() (ui.WebView method)

evaluation

order

Event (class in threading)

event scheduling

evernote (module)

EWOULDBLOCK (in module errno)

EX_CANTCREAT (in module os)

EX_CONFIG (in module os)

EX_DATAERR (in module os)

EX_IOERR (in module os)

EX_NOHOST (in module os)

EX_NOINPUT (in module os)

EX_NOPERM (in module os)

EX_NOTFOUND (in module os)

EX_NOUSER (in module os)

EX_OK (in module os)

EX_OSERR (in module os)

EX_OSFILE (in module os)

EX_PROTOCOL (in module os)

EX_SOFTWARE (in module os)

EX_TEMPFAIL (in module os)

EX_UNAVAILABLE (in module os)

EX_USAGE (in module os)

Example (class in doctest)

example (doctest.DocTestFailure attribute)

(doctest.UnexpectedException attribute)

examples (doctest.DocTest attribute)

exc_clear() (in module sys)

exc_info (doctest.UnexpectedException attribute)

(in module sys)

exc_info() (in module sys)

exc_msg (doctest.Example attribute)

exc_traceback (in module sys), [1], [2]

exc_type (in module sys), [1]

exc_value (in module sys), [1]

excel (class in csv)

excel_tab (class in csv)

except

bare

keyword

statement

except (2to3 fixer)

excepthook() (in module sys), [1]

Exception

exception, [1]

AssertionError

AttributeError

GeneratorExit

ImportError, [1], [2]

NameError

RuntimeError

StopIteration, [1]

TypeError

ValueError

ZeroDivisionError

handler

raising

exception handler

exception() (in module logging)

(logging.Logger method)

exceptions

in CGI scripts

exceptions (module)

exclusive

or

EXDEV (in module errno)

exec

statement, [1], [2]

exec (2to3 fixer)

exec_prefix (in module sys)

EXEC_STMT (opcode)

execfile

built-in function, [1]

execfile (2to3 fixer)

execfile() (built-in function)

execl() (in module os)

execle() (in module os)

execlp() (in module os)

execlpe() (in module os)

executable (in module sys)

execute() (sqlite3.Connection method)

(sqlite3.Cursor method)

executemany() (sqlite3.Connection method)

(sqlite3.Cursor method)

executescript() (sqlite3.Connection method)

(sqlite3.Cursor method)

execution

frame, [1]

restricted

stack

execution model

execv() (in module os)

execve() (in module os)

execvp() (in module os)

execvpe() (in module os)

EXFULL (in module errno)

exists() (in module os.path)

exit (built-in variable)

exit() (argparse.ArgumentParser method)

(in module sys)

(in module thread)

exitfunc (2to3 fixer)

(in module sys)

(in sys)

exp() (decimal.Context method)

(decimal.Decimal method)

(in module cmath)

(in module math)

expand() (in module ImageOps)

(re.MatchObject method)

expand_tabs (textwrap.TextWrapper attribute)

expandNode() (xml.dom.pulldom.DOMEventStream method)

expandtabs() (in module string)

(str method)

expanduser() (in module os.path)

expandvars() (in module os.path)

Expat

ExpatError

expect() (telnetlib.Telnet method)

expectedFailure() (in module unittest)

expectedFailures (unittest.TestResult attribute)

expires (cookielib.Cookie attribute)

expm1() (in module math)

expovariate() (in module random)

expr() (in module parser)

expression, [1]

Conditional

conditional

generator

lambda

list, [1], [2]

statement

yield

expunge() (imaplib.IMAP4 method)

extend() (array.array method)

(collections.deque method)

(list method)

(xml.etree.ElementTree.Element method)

extend_path() (in module pkgutil)

extended

slicing

extended print statement

extended slice

assignment

operation

extended slicing

EXTENDED_ARG (opcode)

ExtendedContext (class in decimal)

extendleft() (collections.deque method)

extension

module

extension module

extensions_map (SimpleHTTPServer.SimpleHTTPRequestHandler attribute)

External Data Representation, [1]

external_attr (zipfile.ZipInfo attribute)

ExternalClashError

ExternalEntityParserCreate() (xml.parsers.expat.xmlparser method)

ExternalEntityRefHandler() (xml.parsers.expat.xmlparser method)

extra (zipfile.ZipInfo attribute)

extract() (bs4.PageElement method)

(tarfile.TarFile method)

(zipfile.ZipFile method)

extract_cookies() (cookielib.CookieJar method)

extract_stack() (in module traceback)

extract_tb() (in module traceback)

extract_version (zipfile.ZipInfo attribute)

extractall() (tarfile.TarFile method)

(zipfile.ZipFile method)

ExtractError

extractfile() (tarfile.TarFile method)

extsep (in module os)

    © Copyright 1990-2017, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on Jan 16, 2017.
    Found a bug?

    Created using Sphinx 1.0.7.


text:
import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'search-panel',
  templateUrl: './search-panel.html',
  styleUrls: ['./search-panel.scss']
})
export class SearchPanelComponent {

  @Input()
  public get search(): string {
    return this._search;
  }
  public set search(val: string) {
    this._search = val;
    this.searchChange.emit(this._search);
    this.filterChange.emit(this._search);
  }

  @Output()
  public searchChange = new EventEmitter<string>();

  @Output()
  public filterChange = new EventEmitter<string>();

  private _search: string;
}


text:
Authenticate using Apache-style htpasswd files and HTTP Basic Authentication.

`htpasswd` has supported a number of different password hashing schemes over the
decades. Most common and sane ones are supported directly. For some you will need
to add another package.

| Style | Status |
|-------|--------|
| plain | yes+   |
| md5   | yes    |
| sha   | yes    |
| crypt | no (conflicts with plain)     |
| bcrypt | no (can add with another package)   |

The standard set of systems will use *Plain*, *Sha*, and *MD5* systems while filtering out *bcrypt*.
Because of its complexity, *bcrypt* will be in another package which you can import and
add if you need it. *Plain* accepts both Apache style plain text and nginx style where the
password is preceded by {PLAIN}.

## Usage

~~~ go
import (
  "github.com/codegangsta/martini"
  "github.com/jimstudt/http-authentication/basic"
  "log"
)

func main() {
  m := martini.Classic()

  pw,err := basic.New("My Realm", "./my-htpasswd-file", htpasswd.DefaultSystems, nil)
  if ( err != nil) {
    log.Fatalf("Unable to read my htpassword file: %s", err.Error())
  }

  // authenticate every request
  m.Use( pw.ServeHTTP)

  // You will also want to call pw.Reload(nil) to reprocess the password file when it changes.

  // You can use pw.ReloadOn( syscall.SIGHUP, nil ) to make it automatically
  // reload on a HUP signal.

  // And those 'nil' arguments are where you pass a function to be notified about illegally
  // formatted entries, or unsupported hash systems. See the API documents.

  // If you only want to authenticate some requests, then it goes like this...
  //    m.Get("/secure/thing", pw.ServeHTTP, myRealHandler)
  // ... if pw.ServeHTTP does the 401 then your handler will not be called

  m.Run()

}
~~~

## API Documentation

The API is documented using godoc and also available at [godoc.org](http://godoc.org/github.com/jimstudt/http-authentication/basic)
~~~


text:
describe('view-specific options', function() {
	var options;

	beforeEach(function() {
		options = {
			header: {
				left: 'prev,next',
				center: 'title',
				right: 'month,basicWeek,basicDay,agendaWeek,agendaDay'
			},
			defaultView: 'month',
			titleFormat: '[default]',
			views: { }
		};
		affix('#cal');
	});

	function testEachView(viewsAndVals) {
		$('#cal').fullCalendar(options);
		$.each(viewsAndVals, function(view, val) {
			$('#cal').fullCalendar('changeView', view);
			expect($('h2')).toHaveText(val);
		});
	}

	it('can target a specific view (month)', function() {
		options.views.month = {
			titleFormat: '[special!!!]'
		};
		testEachView({
			month: 'special!!!',
			basicWeek: 'default',
			basicDay: 'default',
			agendaWeek: 'default',
			agendaDay: 'default'
		});
	});

	it('can target a specific view (agendaWeek)', function() {
		options.views.agendaWeek = {
			titleFormat: '[special!!!]'
		};
		testEachView({
			month: 'default',
			basicWeek: 'default',
			basicDay: 'default',
			agendaWeek: 'special!!!',
			agendaDay: 'default'
		});
	});

	it('can target basic views', function() {
		options.views.basic = {
			titleFormat: '[special!!!]'
		};
		testEachView({
			month: 'default', // will NOT target month view
			basicWeek: 'special!!!',
			basicDay: 'special!!!',
			agendaWeek: 'default',
			agendaDay: 'default'
		});
	});

	it('can target agenda views', function() {
		options.views.agenda = {
			titleFormat: '[special!!!]'
		};
		testEachView({
			month: 'default',
			basicWeek: 'default',
			basicDay: 'default',
			agendaWeek: 'special!!!',
			agendaDay: 'special!!!'
		});
	});

	it('can target week views', function() {
		options.views.week = {
			titleFormat: '[special!!!]'
		};
		testEachView({
			month: 'default',
			basicWeek: 'special!!!',
			basicDay: 'default',
			agendaWeek: 'special!!!',
			agendaDay: 'default'
		});
	});

	it('can target day views', function() {
		options.views.day = {
			titleFormat: '[special!!!]'
		};
		testEachView({
			month: 'default',
			basicWeek: 'default',
			basicDay: 'special!!!',
			agendaWeek: 'default',
			agendaDay: 'special!!!'
		});
	});
});


text:
package org.fusesource.fabric.commands;

import java.util.Arrays;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import jline.Terminal;

import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.Option;
import org.fusesource.fabric.api.Constants;
import org.fusesource.fabric.api.Profile;
import org.fusesource.fabric.api.Version;
import org.fusesource.fabric.boot.commands.support.FabricCommand;
import org.fusesource.fabric.commands.support.DatastoreContentManager;
import org.jledit.ConsoleEditor;
import org.jledit.EditorFactory;
import org.osgi.service.cm.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.fusesource.fabric.utils.FabricValidations.validateProfileName;

/**
 *
 */
@Command(name = "profile-edit", scope = "fabric", description = "Edits the specified version of the specified profile (where the version defaults to the current default version)", detailedDescription = "classpath:profileEdit.txt")
public class ProfileEdit extends FabricCommand {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProfileEdit.class);

    static final String FEATURE_PREFIX = "feature.";
    static final String REPOSITORY_PREFIX = "repository.";
    static final String BUNDLE_PREFIX = "bundle.";
    static final String FAB_PREFIX = "fab.";
    static final String OVERRIDE_PREFIX = "override.";
    static final String CONFIG_PREFIX = "config.";
    static final String SYSTEM_PREFIX = "system.";
    static final String DELIMITER = ",";
    static final String PID_KEY_SEPARATOR = "/";

    static final String FILE_INSTALL_FILENAME_PROPERTY = "felix.fileinstall.filename";

    @Option(name = "-r", aliases = {"--repositories"}, description = "Edit the features repositories", required = false, multiValued = true)
    private String[] repositories;

    @Option(name = "-f", aliases = {"--features"}, description = "Edit features, specifying a comma-separated list of features to add (or delete).", required = false, multiValued = true)
    private String[] features;

    @Option(name = "-b", aliases = {"--bundles"}, description = "Edit bundles, specifying a comma-separated list of bundles to add (or delete).", required = false, multiValued = true)
    private String[] bundles;

    @Option(name = "--fabs", description = "Edit fabs, specifying a comma-separated list of fabs to add (or delete).", required = false, multiValued = true)
    private String[] fabs;

    @Option(name = "-o", aliases = {"--overrides"}, description = "Edit overrides, specifying a comma-separated list of overrides to add (or delete).", required = false, multiValued = true)
    private String[] overrides;

    @Option(name = "-p", aliases = {"--pid"}, description = "Edit an OSGi configuration property, specified in the format <PID>/<Property>.", required = false, multiValued = true)
    private String[] pidProperties;

    @Option(name = "-s", aliases = {"--system"}, description = "Edit the Java system properties that affect installed bundles (analogous to editing etc/system.properties in a root container).", required = false, multiValued = true)
    private String[] systemProperties;

    @Option(name = "-c", aliases = {"--config"}, description = "Edit the Java system properties that affect the karaf container (analogous to editing etc/config.properties in a root container).", required = false, multiValued = true)
    private String[] configProperties;

    @Option(name = "-i", aliases = {"--import-pid"}, description = "Imports the pids that are edited, from local OSGi config admin", required = false, multiValued = false)
    private boolean importPid = false;

    @Option(name = "--resource", description = "Selects a resource under the profile to edit. This option should only be used alone.", required = false, multiValued = false)
    private String resource;

    @Option(name = "--set", description = "Set or create values (selected by default).")
    private boolean set = true;

    @Option(name = "--delete", description = "Delete values. This option can be used to delete a feature, a bundle or a pid from the profile.")
    private boolean delete = false;

    @Option(name = "--append", description = "Append value to a delimited list. It is only usable with the system, config & pid options")
    private boolean append = false;

    @Option(name = "--remove", description = "Removes value from a delimited list. It is only usable with the system, config & pid options")
    private boolean remove = false;

    @Option(name = "--delimiter", description = "Specifies the delimiter to use for appends and removals.")
    private String delimiter = ",";

    @Argument(index = 0, name = "profile", description = "The target profile to edit", required = true, multiValued = false)
    private String profileName;

    @Argument(index = 1, name = "version", description = "The version of the profile to edit. Defaults to the current default version.", required = false, multiValued = false)
    private String versionName;

    private EditorFactory editorFactory;

    @Override
    protected Object doExecute() throws Exception {
        checkFabricAvailable();
        validateProfileName(profileName);
        if (delete) {
            set = false;
        }
        Version version = versionName != null ? fabricService.getVersion(versionName) : fabricService.getDefaultVersion();

        for (Profile profile : version.getProfiles()) {
            if (profileName.equals(profile.getId())) {
                editProfile(profile);
            }
        }
        return null;
    }

    private void editProfile(Profile profile) throws Exception {
        boolean editInLine = false;

        if (delete || remove) {
            editInLine = true;
        }

        if (features != null && features.length > 0) {
            editInLine = true;
            handleFeatures(features, profile);
        }
        if (repositories != null && repositories.length > 0) {
            editInLine = true;
            handleFeatureRepositories(repositories, profile);
        }
        if (bundles != null && bundles.length > 0) {
            editInLine = true;
            handleBundles(bundles, profile);
        }
        if (fabs != null && fabs.length > 0) {
            editInLine = true;
            handleFabs(fabs, profile);
        }
        if (overrides != null && overrides.length > 0) {
            editInLine = true;
            handleOverrides(overrides, profile);
        }

        if (pidProperties != null && pidProperties.length > 0) {
            editInLine = handlePid(pidProperties, profile);
        }

        if (systemProperties != null && systemProperties.length > 0) {
            editInLine = true;
            handleSystemProperties(systemProperties, profile);
        }

        if (configProperties != null && configProperties.length > 0) {
            editInLine = true;
            handleConfigProperties(configProperties, profile);
        }

        if (!editInLine) {
            resource = resource != null ? resource : "org.fusesource.fabric.agent.properties";
            //If a single pid has been selected, but not a key value has been specified or import has been selected,
            //then open the resource in the editor.
            if (pidProperties != null && pidProperties.length == 1) {
                resource = pidProperties[0] + ".properties";
            }
            openInEditor(profile, resource);
        }
    }

    /**
     * Adds or remove the specified features to the specified profile.
     * @param features  The array of feature names.
     * @param profile   The target profile.
     */
    private void handleFeatures(String[] features, Profile profile) {
        Map<String, String> conf = profile.getConfiguration(Constants.AGENT_PID);
        for (String feature : features) {
            if (delete) {
                System.out.println("Deleting feature:" + feature + " from profile:" + profile.getId() + " version:" + profile.getVersion());
            } else {
                System.out.println("Adding feature:" + feature + " to profile:" + profile.getId() + " version:" + profile.getVersion());
            }
            updateConfig(conf, FEATURE_PREFIX + feature.replace('/', '_'), feature, set, delete);
            profile.setConfiguration(Constants.AGENT_PID, conf);
        }
    }

    /**
     * Adds or remove the specified feature repositories to the specified profile.
     * @param repositories  The array of feature repositories.
     * @param profile   The target profile.
     */
    private void handleFeatureRepositories(String[] repositories, Profile profile) {
        Map<String, String> conf = profile.getConfiguration(Constants.AGENT_PID);
        for (String repositoryURI : repositories) {
            if (set) {
                System.out.println("Adding feature repository:" + repositoryURI + " to profile:" + profile.getId() + " version:" + profile.getVersion());
            } else if (delete) {
                System.out.println("Deleting feature repository:" + repositoryURI + " from profile:" + profile.getId() + " version:" + profile.getVersion());
            }
            updateConfig(conf, REPOSITORY_PREFIX + repositoryURI.replace('/', '_'), repositoryURI, set, delete);
        }
        profile.setConfiguration(Constants.AGENT_PID, conf);
    }

    /**
     * Adds or remove the specified bundles to the specified profile.
     * @param bundles   The array of bundles.
     * @param profile   The target profile.
     */
    private void handleBundles(String[] bundles, Profile profile) {
        Map<String, String> conf = profile.getConfiguration(Constants.AGENT_PID);
        for (String bundle : bundles) {
            if (set) {
                System.out.println("Adding bundle:" + bundle + " to profile:" + profile.getId() + " version:" + profile.getVersion());
            } else if (delete) {
                System.out.println("Deleting bundle:" + bundle + " from profile:" + profile.getId() + " version:" + profile.getVersion());
            }
            updateConfig(conf, BUNDLE_PREFIX + bundle.replace('/', '_'), bundle, set, delete);
        }
        profile.setConfiguration(Constants.AGENT_PID, conf);
    }

    /**
     * Adds or remove the specified fabs to the specified profile.
     * @param fabs      The array of fabs.
     * @param profile   The target profile.
     */
    private void handleFabs(String[] fabs, Profile profile) {
        Map<String, String> conf = profile.getConfiguration(Constants.AGENT_PID);
        for (String fab : fabs) {
            if (set) {
                System.out.println("Adding FAB:" + fab + " to profile:" + profile.getId() + " version:" + profile.getVersion());
            } else if (delete) {
                System.out.println("Deleting FAB:" + fab + " from profile:" + profile.getId() + " version:" + profile.getVersion());
            }
            updateConfig(conf, FAB_PREFIX + fab.replace('/', '_'), fab, set, delete);
        }
        profile.setConfiguration(Constants.AGENT_PID, conf);
    }

    /**
     * Adds or remove the specified overrides to the specified profile.
     * @param overrides     The array of overrides.
     * @param profile       The target profile.
     */
    private void handleOverrides(String[] overrides, Profile profile) {
        Map<String, String> conf = profile.getConfiguration(Constants.AGENT_PID);
        for (String overrie : overrides) {
            if (set) {
                System.out.println("Adding override:" + overrie + " to profile:" + profile.getId() + " version:" + profile.getVersion());
            } else if (delete) {
                System.out.println("Deleting override:" + overrie + " from profile:" + profile.getId() + " version:" + profile.getVersion());
            }
            updateConfig(conf, OVERRIDE_PREFIX + overrie.replace('/', '_'), overrie, set, delete);
        }
        profile.setConfiguration(Constants.AGENT_PID, conf);
    }

    /**
     * Adds or remove the specified system properties to the specified profile.
     * @param pidProperties         The array of system properties.
     * @param profile               The target profile.
     * @return                      True if the edit can take place in line.
     */
    private boolean handlePid(String[] pidProperties, Profile profile) {
        boolean editInline = true;
        for (String pidProperty : pidProperties) {
            String currentPid = null;

            String keyValuePair = "";
            if (pidProperty.contains(PID_KEY_SEPARATOR)) {
                currentPid = pidProperty.substring(0, pidProperty.indexOf(PID_KEY_SEPARATOR));
                keyValuePair = pidProperty.substring(pidProperty.indexOf(PID_KEY_SEPARATOR) + 1);
            } else {
                currentPid = pidProperty;
            }

            Map<String, String> conf = profile.getConfiguration(currentPid);
            //We only support import when a single pid is specified
            if (pidProperties.length == 1 && importPid) {
                System.out.println("Importing pid:" + currentPid + " to profile:" + profile.getId() + " version:" + profile.getVersion());
                importPidFromLocalConfigAdmin(currentPid, conf);
                profile.setConfiguration(currentPid, conf);
                return true;
            }

            Map<String, String> configMap = extractConfigs(keyValuePair);
            if (configMap.isEmpty() && set) {
                editInline = false;
            } else if (configMap.isEmpty() && delete) {
                editInline = true;
                System.out.println("Deleting pid:" + currentPid + " from profile:" + profile.getId() + " version:" + profile.getVersion());
                Map<String, Map<String,String>> profileConfigs = profile.getConfigurations();
                profileConfigs.remove(currentPid);
                profile.setConfigurations(profileConfigs);
            } else {
                for (Map.Entry<String, String> configEntries : configMap.entrySet()) {
                    String key = configEntries.getKey();
                    String value = configEntries.getValue();
                    if (value == null && delete) {
                        System.out.println("Deleting key:" + key + " from pid:" + currentPid + " and profile:" + profile.getId() + " version:" +  profile.getVersion());
                        conf.remove(key);
                    } else {
                        if (append) {
                            System.out.println("Appending value:" + value + " key:" + key + " to pid:" + currentPid + " and profile:" + profile.getId() + " version:" +  profile.getVersion());
                        } else if (remove) {
                            System.out.println("Removing value:" + value + " key:" + key + " from pid:" + currentPid + " and profile:" + profile.getId() + " version:" +  profile.getVersion());
                        } else if(set) {
                            System.out.println("Setting value:" + value + " key:" + key + " on pid:" + currentPid + " and profile:" + profile.getId() + " version:" +  profile.getVersion());
                        }
                        updatedDelimitedList(conf, key, value, delimiter, set, delete, append, remove);
                    }
                }
                editInline = true;
                profile.setConfiguration(currentPid, conf);
            }
        }
        return editInline;
    }

    /**
     * Adds or remove the specified system properties to the specified profile.
     * @param systemProperties      The array of system properties.
     * @param profile               The target profile.
     */
    private void handleSystemProperties(String[] systemProperties, Profile profile) {
        Map<String, String> conf = profile.getConfiguration(Constants.AGENT_PID);
        for (String systemProperty : systemProperties) {
            Map<String, String> configMap = extractConfigs(systemProperty);
            for (Map.Entry<String, String> configEntries : configMap.entrySet()) {
                String key = configEntries.getKey();
                String value = configEntries.getValue();
                if (append) {
                    System.out.println("Appending value:" + value + " key:" + key + " from system properties and profile:" + profile.getId() + " version:" + profile.getVersion());
                } else if (delete) {
                    System.out.println("Deleting key:" + key + " from system properties and profile:" + profile.getId() + " version:" + profile.getVersion());
                } else if (set) {
                    System.out.println("Setting value:" + value + " key:" + key + " from system properties and profile:" + profile.getId() + " version:" + profile.getVersion());
                } else {
                    System.out.println("Removing value:" + value + " key:" + key + " from system properties and profile:" + profile.getId() + " version:" + profile.getVersion());
                }
                updatedDelimitedList(conf, SYSTEM_PREFIX + key, value, delimiter, set, delete, append, remove);
            }
        }
        profile.setConfiguration(Constants.AGENT_PID, conf);
    }

    /**
     * Adds or remove the specified config properties to the specified profile.
     * @param configProperties      The array of config properties.
     * @param profile               The target profile.
     */
    private void handleConfigProperties(String[] configProperties, Profile profile) {
        Map<String, String> conf = profile.getConfiguration(Constants.AGENT_PID);
        for (String configProperty : configProperties) {
            Map<String, String> configMap = extractConfigs(configProperty);
            for (Map.Entry<String, String> configEntries : configMap.entrySet()) {
                String key = configEntries.getKey();
                String value = configEntries.getValue();
                if (append) {
                    System.out.println("Appending value:" + value + " key:" + key + " from config properties and profile:" + profile + " version:" + versionName);
                } else if (delete) {
                    System.out.println("Deleting key:" + key + " from config properties and profile:" + profile + " version:" + versionName);
                } else if (set) {
                    System.out.println("Setting value:" + value + " key:" + key + " from config properties and profile:" + profile + " version:" + versionName);
                }
                updatedDelimitedList(conf, CONFIG_PREFIX + key, value, delimiter, set, delete, append, remove);
            }
        }
        profile.setConfiguration(Constants.AGENT_PID, conf);
    }

    private void openInEditor(Profile profile, String resource) throws Exception {
        String id = profile.getId();
        String version = profile.getVersion();
        String location = id + " " + version + " " + resource;
        //Call the editor
        ConsoleEditor editor = editorFactory.create("simple",getTerminal(), System.in, System.out);
        editor.setTitle("Profile");
        editor.setOpenEnabled(false);
        editor.setContentManager(new DatastoreContentManager(getFabricService().getDataStore()));
        editor.open(location, id + " " + version);
        editor.start();
    }

    public void updatedDelimitedList(Map<String, String> map, String key, String value, String delimiter, boolean set, boolean delete, boolean append, boolean remove) {
        if (append || remove) {
            String oldValue = map.containsKey(key) ? map.get(key) : "";
            List<String> parts = new LinkedList<String>(Arrays.asList(oldValue.split(delimiter)));
            //We need to remove any possible blanks.
            parts.remove("");
            if (append) {
                parts.add(value);
            }
            if (remove) {
                parts.remove(value);
            }
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < parts.size(); i++) {
                if (i != 0) {
                    sb.append(delimiter);
                }
                sb.append(parts.get(i));
            }
            map.put(key, sb.toString());
        } else if (set) {
            map.put(key, value);
        } else if (delete) {
            map.remove(key);
        }
    }

    public void updateConfig(Map<String, String> map, String key, String value, boolean set, boolean delete) {
        if (set) {
            map.put(key, value);
        } else if (delete) {
            map.remove(key);
        }
    }

    /**
     * Imports the pid to the target Map.
     *
     * @param pid
     * @param target
     */
    private void importPidFromLocalConfigAdmin(String pid, Map<String, String> target) {
        try {
            Configuration[] configuration = configurationAdmin.listConfigurations("(service.pid=" + pid + ")");
            if (configuration != null && configuration.length > 0) {
                Dictionary dictionary = configuration[0].getProperties();
                Enumeration keyEnumeration = dictionary.keys();
                while (keyEnumeration.hasMoreElements()) {
                    String key = String.valueOf(keyEnumeration.nextElement());
                    //file.install.filename needs to be skipped as it specific to the current container.
                    if (!key.equals(FILE_INSTALL_FILENAME_PROPERTY)) {
                        String value = String.valueOf(dictionary.get(key));
                        target.put(key, value);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.warn("Error while importing configuration {} to profile.", pid);
        }
    }

    /**
     * Extracts Key value pairs from a delimited string of key value pairs.
     * Note: The value may contain commas.
     *
     * @param configs
     * @return
     */
    private Map<String, String> extractConfigs(String configs) {
        Map<String, String> configMap = new HashMap<String, String>();
        //If contains key values.
        String key = null;
        String value = null;
        if (configs.contains("=")) {
            key = configs.substring(0, configs.indexOf("="));
            value = configs.substring(configs.indexOf("=") + 1);

        }  else {
            key = configs;
            value = null;
        }
        if (key != null && !key.isEmpty()) {
            configMap.put(key, value);
        }
        return configMap;
    }

    /**
     * Gets the {@link jline.Terminal} from the current session.
     *
     * @return
     * @throws Exception
     */
    private Terminal getTerminal() throws Exception {
        Object terminalObject = session.get(".jline.terminal");
        if (terminalObject instanceof Terminal) {
            return (Terminal) terminalObject;

        }
        throw new IllegalStateException("Could not get Terminal from CommandSession.");
    }

    public EditorFactory getEditorFactory() {
        return editorFactory;
    }

    public void setEditorFactory(EditorFactory editorFactory) {
        this.editorFactory = editorFactory;
    }
}


text:
package pbs.base.service.impl;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import pbs.base.dao.mapper.PbsBikeInfoMapper;
import pbs.base.dao.mapper.PbsBikeInfoMapperCustom;
import pbs.base.pojo.po.PbsBikeInfo;
import pbs.base.pojo.po.PbsBikeInfoExample;
import pbs.base.pojo.vo.PbsBikeInfoCustom;
import pbs.base.pojo.vo.PbsBikeInfoQueryVo;
import pbs.base.process.context.Config;
import pbs.base.process.result.ExceptionResultInfo;
import pbs.base.process.result.ResultInfo;
import pbs.base.process.result.ResultUtil;
import pbs.base.service.BikeService;

public class BikeServiceImpl implements BikeService {

	@Autowired
	private PbsBikeInfoMapperCustom pbsBikeInfoMapperCustom;

	@Autowired
	private PbsBikeInfoMapper pbsBikeInfoMapper;

	@Override
	public List<PbsBikeInfoCustom> findPbsBikeInfoList(
			PbsBikeInfoQueryVo pbsBikeInfoQueryVo) throws Exception {
		return pbsBikeInfoMapperCustom.findPbsBikeInfoList(pbsBikeInfoQueryVo);
	}

	public PbsBikeInfo findPbsBikeInfoByBikebm(String bikeId) throws Exception {
		PbsBikeInfoExample pbsBikeInfoExample = new PbsBikeInfoExample();
		PbsBikeInfoExample.Criteria criteria = pbsBikeInfoExample.createCriteria();
		//设置查询条件
		criteria.andBikeIdEqualTo(bikeId);
		List<PbsBikeInfo> list = pbsBikeInfoMapper.selectByExample(pbsBikeInfoExample);

		if(list != null && list.size() == 1){
			return list.get(0);
		}
		return null;
	}

	@Override
	public int findPbsBikeInfoCount(PbsBikeInfoQueryVo pbsBikeInfoQueryVo)
			throws Exception {
		return pbsBikeInfoMapperCustom.findPbsBikeInfoCount(pbsBikeInfoQueryVo);
	}

	@Override
	public void insertPbsBikeInfo(PbsBikeInfoCustom pbsBikeInfoCustom)
			throws Exception {
		PbsBikeInfo pbsBikeInfo = this.findPbsBikeInfoByBikebm(pbsBikeInfoCustom.getBikeId());

		if(pbsBikeInfo!=null){
			//throw new Exception("编码重复");

			//使用系统自定义异常类
			ResultInfo resultInfo = new ResultInfo();
			resultInfo.setType(ResultInfo.TYPE_RESULT_FAIL);
			resultInfo.setMessage("编码重复");
			throw new ExceptionResultInfo(resultInfo);
		}

		pbsBikeInfoMapper.insert(pbsBikeInfoCustom);
	}

	@Override
	public void deletPbsBikeInfo(String bikeId) throws Exception {

		PbsBikeInfo pbsBikeInfo = this.findPbsBikeInfoByBikebm(bikeId);
		if(pbsBikeInfo==null){

			ResultUtil.throwExcepion(ResultUtil.createFail(Config.MESSAGE, 212, null));
		}

		pbsBikeInfoMapper.deleteByPrimaryKey(pbsBikeInfo.getId());
	}

	@Override
	public void updatePbsBikeInfo(PbsBikeInfoCustom pbsBikeInfoCustom)
			throws Exception {
		PbsBikeInfo pbsBikeInfo = this.findPbsBikeInfoByBikebm(pbsBikeInfoCustom.getBikeId());
		if(pbsBikeInfo==null){
			ResultUtil.throwExcepion(ResultUtil.createFail(Config.MESSAGE, 212, null));
		}
		//pbsBikeInfo.setId(pbsBikeInfoCustom.getId());
		pbsBikeInfo.setBikeId(pbsBikeInfoCustom.getBikeId());
		pbsBikeInfo.setFactory(pbsBikeInfoCustom.getFactory());
		pbsBikeInfo.setProDate(pbsBikeInfoCustom.getProDate());
		pbsBikeInfo.setState(pbsBikeInfoCustom.getState());
		pbsBikeInfo.setDynamicState(pbsBikeInfoCustom.getDynamicState());
		pbsBikeInfo.setRentId(pbsBikeInfoCustom.getRentId());
		pbsBikeInfo.setNodeId(pbsBikeInfoCustom.getNodeId());

		//BeanUtils.copyProperties(pbsBikeInfoCustom, pbsBikeInfo);

		pbsBikeInfoMapper.updateByPrimaryKey(pbsBikeInfo);

	}

}


text:
import _ from "lodash";
import browserify from "browserify";
import buffer from "vinyl-buffer";
import conf from "../config";
import del from "del";
import fs from "fs";
import gulp from "gulp";
import gulpLoadPlugins from "gulp-load-plugins";
import packageJson from "../../package.json";
import runSequence from "run-sequence";
import source from "vinyl-source-stream";

let $ = gulpLoadPlugins();

gulp.task("compile:html", function () {
  var assets = $.useref.assets();
  return gulp.src(`${conf.srcDir}/index.html`)
    .pipe(assets)
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe(gulp.dest(conf.distDir));
  ;
});

gulp.task("clean:dist",
    del.bind(null, [conf.distDir]));

gulp.task("copy:tmpDist", () => {
  let targets = [
    `${conf.tmpDistDir}/main.js`,
    `${conf.tmpDistDir}/assets/**/*`,
    `${conf.tmpDistDir}/runtime/**/*.js`,
  ]
  return gulp.src(targets, {base: conf.tmpDistDir})
    .pipe(gulp.dest(conf.distDir));
});

gulp.task("packageJson", (done) => {
  let json = _.cloneDeep(packageJson);
  json.main = "main.js";
  fs.writeFile(conf.distDir + "/package.json", JSON.stringify(json), (err) => {
    done();
  });
});

gulp.task("browserify", () => {
  return browserify({
    entries: `${conf.tmpDistDir}/app.js`,
    debug: false,
  })
  .bundle()
  .pipe(source("app.js"))
  .pipe(buffer())
  .pipe($.uglify())
  .pipe(gulp.dest(conf.distDir));
});

gulp.task("uglify", () => {
  return gulp.src([
    `${conf.distDir}/main.js`,
    `${conf.distDir}/runtime/**/*.js`],
    {base: conf.distDir})
    .pipe($.uglify())
    .pipe(gulp.dest(conf.distDir));
});

gulp.task("minify", () => {
  return gulp.src(`${conf.srcDir}/styles/*.css`)
      // TODO: style.min.css に名前変えたい
      .pipe($.concat("app.css"))
      .pipe($.minifyCss())
      .pipe(gulp.dest(`${conf.distDir}/styles/`));
});

gulp.task("dist", callback => {
  return runSequence.use(gulp)(
      ["compile:js", "compile:jsx", "compile:css"],
      "clean:dist",
      "copy:tmpDist",
      "packageJson",
      ["compile:html", "browserify", "uglify", "minify"],
      callback
      );
});


text:
require 'test_helper'

module Unicore
  class SupportMailTest < ActionMailer::TestCase
    test "send_to_support" do
      mail = SupportMail.send_to_support
      assert_equal "Send to support", mail.subject
      assert_equal ["to@example.org"], mail.to
      assert_equal ["from@example.com"], mail.from
      assert_match "Hi", mail.body.encoded
    end

    test "send_to_user" do
      mail = SupportMail.send_to_user
      assert_equal "Send to user", mail.subject
      assert_equal ["to@example.org"], mail.to
      assert_equal ["from@example.com"], mail.from
      assert_match "Hi", mail.body.encoded
    end

  end
end


text:
.. Shelter Database documentation master file, created by
   sphinx-quickstart on Sun Jun 19 21:53:46 2016.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Presentation
============

The goal of this application is to list the shelters deployed around the world.

The official instance is available `here <https://shelter-database.org>`_.

Deployment
==========

.. toctree::
    :maxdepth: 3

    deployment
    pdf-generation
    test-server

Database
========

.. toctree::
    :maxdepth: 2

    database-schema
    database-migrations

Web Services
============

.. toctree::
    :maxdepth: 2

    api


text:
from django import forms
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.db.models import Q
from manager import models as pmod
from . import templater
import decimal, datetime
from django.core.mail import send_mail
import requests
from base_app import payment as gateway

# This view processes the payment and creates transactions and journal entries for a repair

def process_request(request):
	print("Below are the paramaters!")
	print(request.urlparams[0])
	if request.method == 'POST':
		billing = request.POST.get('billing')

		redirectParams = ""

		# This checks the options for the order. If not the page goes back to checkout and will display the errors
		if billing is None:
			redirectParams += "b"

		if len(redirectParams) > 0:
			redirect = '/employee/repair_checkout/' + request.urlparams[0] + "/" + redirectParams
			return HttpResponseRedirect(redirect)

		billing = billing.replace("}","")

		user = pmod.User.objects.get(id = request.urlparams[0])

		userbilling = pmod.UserBilling.objects.get(user = user, id = billing)

		seller = request.user
		sellercommission = False

		transactiontype = pmod.TransactionType.objects.get(transactiontype = "Repair")

		# This gets the taxrate for the customer's state
		try:
			taxRate = pmod.TaxRates.objects.get(state = shipping.state)
		except:
			taxRate = pmod.TaxRates.objects.get(state = "default")

		subtotal = 0

		unpaid_repairs = pmod.Repair.objects.filter(user = user, paid=False, date_returned__isnull=False)

		for e in unpaid_repairs:
			subtotal += e.total_charged

		# Here the payment is checked
		payment_passed = gateway.payment()
		payment_passed.setVariables(userbilling, subtotal, taxRate.taxRate)
		if payment_passed.check() == False:
			redirectParams = "c"
			redirect = '/employee/repair_checkout/' + request.urlparams[0] + "/" + redirectParams
			return HttpResponseRedirect(redirect)

		transaction = pmod.Transaction()
		transaction.buyer = user
		transaction.seller = seller
		transaction.subtotal = subtotal
		transaction.transactiontype = transactiontype
		transaction.billing = userbilling
		transaction.taxAmount = subtotal * taxRate.taxRate
		transaction.date = datetime.datetime.now()
		transaction.commissionNeeded = sellercommission
		transaction.save()

		cost = 0

		for e in unpaid_repairs:
			e.paid = True
			e.save()
			rt = pmod.RepairTransaction()
			rt.transaction = transaction
			rt.repair = e
			rt.save()
			cost = e.estimate + e.cost

		# The journal entry is created here
		journalentry = pmod.JournalEntry()
		journalentry.transaction = transaction
		journalentry.note = "Rental to " + user.username + "for $" + str(transaction.subtotal + transaction.taxAmount)
		journalentry.save()

		cashledger = pmod.Subledger.objects.get(type = "Cash")
		saleledger = pmod.Subledger.objects.get(type = "Sales")

		cash = pmod.DebitCredit()
		cash.journalentry = journalentry
		cash.subledger = cashledger
		cash.isDebit = True
		cash.amount = transaction.subtotal + transaction.taxAmount
		cash.save()

		sale = pmod.DebitCredit()
		sale.journalentry = journalentry
		sale.subledger = saleledger
		sale.isDebit = False
		sale.amount = transaction.subtotal + transaction.taxAmount
		sale.save()

		totalcharged = cash.amount

		items = ""
		for e in unpaid_repairs:
			items += "Repair for Item " + e.serial_number + "\r\n   Description: " + e.description + "\r\n    Problem: " + e.problem + "\r\n"

		message = user.first_name + " " + user.last_name + ":\r\n" + "We have received a payment of $" + str(cash.amount) + " for follwing items:\r\n" + items + "\r\nThank you!\r\n\r\nHexPhotos"

		send_mail('HexPhotos Payment Received', message, 'no-reply@hexphotos.com', [user.email], fail_silently=True)

		tvars = {
			'unpaid_repairs': unpaid_repairs,
			'userbilling': userbilling,
			'totalcharged': totalcharged,
		}
		return templater.render_to_response(request, 'repair_complete_order.html', tvars)


text:
import applicationActions from '../../constants/application';
import contentActions from '../../constants/contents';

let debug = require('debug')('tienda765');

export default async function bulkBannerUpdates(context, payload, done) {
    context.dispatch(contentActions.CONTENTS_BULK_SAVE);
    let promises = payload.map(function (banner) {
        let id = banner.id;
        let payload = Object.assign({}, banner);
        delete payload.id;
        delete payload.type;
        delete payload.comments;
        delete payload.createdAt;
        delete payload.updatedAt;
        return context.api.contents.update(id, payload);
    });
    try {
        await * promises;
        context.dispatch(contentActions.CONTENTS_BULK_SAVE_SUCCESS, payload);
        context.dispatch(applicationActions.APPLICATION_POST_NOTIFICATION, {
            type: 'success',
            message: 'Saved'
        });
    } catch (err) {
        context.dispatch(contentActions.CONTENTS_BULK_SAVE_ERROR, err);
        context.dispatch(applicationActions.APPLICATION_POST_NOTIFICATION, {
            type: 'error',
            message: 'Unable to save'
        });
    }
    done && done();
}