text:
Fac simplifies OOP. Fac wraps the object as Fac-Model which combines the advantages of class and object, is more better than both of them. Fac can be used in [Node.js](https://nodejs.org) and in browsers. "Fac" is the abbreviation of "factory".

Fac is more easy to use than class. Fac-Model uses model and copy instead of class and instance, abandont constructor and super. All descendants automatically inherit from parent and be initialized, without call and / or super.

Fac is more free than class. Fac-Model and its descendants can elegantly extend themselves or create a new model / copy directly, no need to create a subclass (or use assists like decorator) before that.

Fac is better than Object. As we know, the objects copied through Object.create or Object.assign will share the data for array and object, can not have separate data. Fac solved this problem.

Fac has a good [performance](./doc/performance/performance.md) to meet the development needs of most applications. For general application development, Fac is even faster than class. In creating a lot of children, Fac is faster than Object.assign, too.

| Features                      | class | Object | Fac  |
| ----------------------------- | ----- | ------ | ---- |
| Inheritance                   | √     | √      | √    |
| Inheritance with elegant      |       |        | √    |
| Separate data                 | √     |        | √    |
| Default values                | √     | √      | √    |
| Default values with elegant   |       |        | √    |
| Self-extending                |       | √      | √    |
| Self-extending with elegant   |       | √      | √    |
| Create children from the copy |       | √      | √    |

## Install

In Node.js:
```bash
$ npm install fac --save
```

In Web / RequireJS:

Download [fac.js](./dist/fac.js) or [fac.min.js](./dist/fac.min.js).

## Test

Clone the Fac repo first:

```bash
$ git clone https://github.com/tasjs/fac.git
$ cd fac
$ npm install
```

Then run the tests in Node.js:
```bash
$ cd /path/to/fac
$ npm test
```

Or run the tests in your browser:
```bash
$ cd /path/to/fac
$ open test/web/index.html
```

## Demo

To run these demos, please clone the Fac repo and Install the development dependencies first (if you have not done it yet, see details in section "Test"). Then see the **examples/demo** folder. All demos are categorized according to Node.js and Web.

### Inheritance
![](./examples/demo/__res/inheritance-in-es5.png)

Run these demos in Node.js:

```bash
$ cd /path/to/fac
$ node examples/demo/nodejs/inheritance/inheritance.js
$ node examples/demo/nodejs/inheritance/fac-is-more-better.js
```

### Inheritance without constructor and super
![](./examples/demo/__res/inheritance-without-constructor-and-super.png)

Run these demos in Node.js:

```bash
$ cd /path/to/fac
$ node examples/demo/nodejs/default-values/class.js
$ node examples/demo/nodejs/default-values/fac-is-more-better.js
```

### Default values
![](./examples/demo/__res/default-values-in-es6.png)

Run these demos in Node.js:

```bash
$ cd /path/to/fac
$ node examples/demo/nodejs/default-values/class.js
$ node examples/demo/nodejs/default-values/fac-is-more-better.js
```

### Self-extending
![](./examples/demo/__res/self-extending.png)

Run these demos in Node.js:

```bash
$ cd /path/to/fac
$ node examples/demo/nodejs/self-extending/class.js
$ node examples/demo/nodejs/self-extending/fac-is-more-better.js
```

### Create children from the copy
![](./examples/demo/__res/create-children-from-the-copy.png)

Run these demos in Node.js:

```bash
$ cd /path/to/fac
$ node examples/demo/nodejs/create-children-from-the-copy/class.js
$ node examples/demo/nodejs/create-children-from-the-copy/fac-is-more-better.js
```

## Quick Example

### Inheritance

Animal.js (root model)
```js
var fac = require('fac');

// Wrap as Fac-Model. Only for the root object,
// not the descendants, neat!
var Animal = fac({
    name: 'Animal',
    age: 1,
    colors: ['white', 'black'],
    parts: {body: 1},

    init: function(){
        // The init function is not necessary in Fac.
        // If you wanna do something when .new() is called,
        // write it in init. If not, remove init.
    },

    sayHi: function(){
        return 'Hi from ' + this.name;
    }
});

module.exports = Animal;
```

Mammal.js (model extended from Animal)
```js
var Animal = require('./Animal');
var Mammal = Animal.extends({
    name: 'Mammal',
    sex: 'male',
    age: 2,

    default: function(){
        this.colors.push('gray');
        this.parts.mouth = 1;
        this.parts.eye = 2;
        this.parts.foot = 4;
    },

    init: function(){
        // The init function is not necessary in Fac.
        // If you wanna do something when .new() is called,
        // write it in init. If not, remove init.
    },

    run: function(){
        return this.name + ' running...';
    },

    getSex: function(){
        return this.sex;
    }
});

module.exports = Mammal;
```

Dog.js (model extended from Mammal)
```js
var Mammal = require('./Mammal');
var Dog = Mammal.extends({
    name: 'Dog',
    color: 'white',
    age: 3,

    swim: function(){
        return this.name + ' swimming...';
    }
});

module.exports = Dog;
```

**dog.js (a copy of model Dog)**
```js
var Dog = require('./Dog');
var tobe = Dog.new({name: 'Tobe', age: 5, sex: 'boy', color: 'black'});

tobe.name // Tobe
tobe.age // 5
tobe.sex // boy
tobe.color // black

tobe.getSex() // boy
tobe.sayHi() // Hi from Tobe
tobe.run() // Tobe running...
tobe.swim() // Tobe swimming...
```

Run this example in Node.js:

```bash
$ cd /path/to/fac
$ node examples/usage/nodejs/inheritance/Dog.test.js
```

### Multi-Extending

Base.js (root model)
```js
var fac = require('fac');

// Wrap as Fac-Model. Only for the root object,
// not the descendants, neat!
var Base = fac({
    sing: function(){
        return this.name + ' Singing...';
    }
});

module.exports = Base;
```

Dance.js (general object)
```js
var Dance = {
    dance: function(){
        return this.name + ' Dancing...';
    }
};

module.exports = Dance;
```

Fly.js (general object)
```js
var Fly = {
    fly: function(){
        return this.name + ' Flying...';
    }
};

module.exports = Fly;
```

Super.js (model extended from Base, Fly, Dance)
```js
var Base = require('./Base');
var Fly = require('./Fly');
var Dance = require('./Dance');

var Super = Base.extends(Fly, Dance, {
    fight: function(){
        return this.name + ' Fighting...';
    }
});

module.exports = Super;
```

SuperDog.js (model extend from Mamml and Super)
```js
var Mammal = require('./Mammal');
var Super = require('./Super');

var SuperDog = Mammal.extends(Super, {
    name: 'SuperDog',
    color: 'white',
    cloak: 'red',
    age: 4,

    init: function(){
        // The init function is not necessary in Fac.
        // If you wanna do something when .new() is called,
        // write it in init. If not, remove init.
    },

    swim: function(){
        return this.name + ' swimming...';
    }
});

module.exports = SuperDog;
```

**super-dog.js (a copy of model SuperDog)**
```js
var SuperDog = require('./SuperDog');
var dog = SuperDog.new({name: 'SuperTobe', age: 6, sex: 'boy', color: 'black'});

dog.name // SuperTobe
dog.age // 6
dog.sex // boy
dog.color // black
dog.cloak // red

dog.sayHi() // Hi from SuperTobe
dog.run() // SuperTobe running...
dog.swim() // SuperTobe swimming...

dog.fly() // SuperTobe flying...
dog.dance() // SuperTobe dancing...
dog.sing() // SuperTobe singing...
dog.fight() // SuperTobe fighting...
```

Run this example in Node.js:

```bash
$ cd /path/to/fac
$ node examples/usage/nodejs/multi-extending/SuperDog.test.js
```

## Full Examples

To run all examples, please clone the Tas repo and Install the development dependencies first (if you have not done it yet, see details in section "Test"). Then see the **examples/usage** folder. All examples and tests are categorized according to Node.js and Web.

## API

Fac wraps the general object as Fac-Model, then the Fac-Model and its descendants (including models and copies) have the following APIs. See the **examples/usage** folder for more usages.

| API          | Functions                                | Usage                                    |
| ------------ | ---------------------------------------- | ---------------------------------------- |
| .new()       | Create a new copy (child) of this model. | [Usage](./examples/demo/nodejs/inheritance/fac-is-more-better.js) |
| .extends()   | Extend to a new model (child) of this model. | [Usage](./examples/usage/nodejs/__models/Dog.js) |
| .ext()       | Extend this model itself.                | [Usage](./examples/usage/nodejs/self-extending/self-extending.test.js) |
| .spawn()     | Create a new copy (child) of this model (share the data for array and object). | [Usage](./examples/usage/nodejs/spawn/spawn.test.js) |
| this.super() | Call the method of parent or ancestor.   | [Usage](./examples/usage/nodejs/this.super/call-parent-method.js) |

#### Relationships of model and copy

| API          | Functions                 | Usage                                    |
| ------------ | ------------------------- | ---------------------------------------- |
| .isModelOf() | Is a model of some copy ? | [Usage](./examples/usage/nodejs/relationships/model-and-copy.test.js) |
| .isCopyOf()  | Is a copy of some model ? | [Usage](./examples/usage/nodejs/relationships/model-and-copy.test.js) |

#### Relationships of inheritance

| API               | Functions                                | Usage                                    |
| ----------------- | ---------------------------------------- | ---------------------------------------- |
| .isChildOf()      | Is a child (model or copy) of some object ? | [Usage](./examples/usage/nodejs/relationships/inheritance.test.js) |
| .isParentOf()     | Is a parent (model or copy) of some object ? | [Usage](./examples/usage/nodejs/relationships/inheritance.test.js) |
| .isDescendantOf() | Is a descendant (model or copy) of some object ? | [Usage](./examples/usage/nodejs/relationships/inheritance.test.js) |
| .isAncestorOf()   | Is an ancestor (model or copy) of some object ? | [Usage](./examples/usage/nodejs/relationships/inheritance.test.js) |

## Performance

Fac has a good performance to meet the development needs of most applications. For general application development, Fac is even faster than class. For example, run the following to compare the general inheritance:

```bash
$ cd /path/to/fac
$ node benchmark/general-inheritance.js
```

The results will be like below:

```bash
Platform info:
macOS Sierra 10.12 x64
Intel(R) Core(TM) i7-4558U CPU @ 2.80GHz x 4
Total Memory 16 GB
Node.js v6.11.3
V8 5.1.281.107
--------------
fac                  30452    times/sec (100000 times, 3312 ms)  <= winner
native-class         12268    times/sec (100000 times, 8204 ms)
native-inheritance   5047     times/sec (100000 times, 20133 ms)
```

See more details: [Benchmark of performance](./doc/performance/performance.md)

## License

[MIT](LICENSE)

Copyright (c) 2017, Owen Luke


text:
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "BaseAIController.h"
#include "CleverAIController.generated.h"

/**
 *
 */
UCLASS()
class LAB_1_API ACleverAIController : public ABaseAIController
{
    GENERATED_BODY()

public:
    ACleverAIController();

    int GetCurrentOrderNumber();

protected:
    void ActAsMaster();

    void ActAsWorker();

    void TryDeliverOrder();

    void RefillPizzaIfNeeded();

    void SetPendingOrderNumber(int OrderNumber);

    virtual void Tick(float DeltaSeconds) override;

    FVector GetHouseLocation(int HouseNumber);

    float ComputeHouseScore(float Distance, float TimeLeft) const;

    float GetTimeToCoverDistance(float distance);

    bool bDeliveringOrder;
    int CurrentOrderNumber;
    int PendingOrderNumber;
    FVector CurrentDestination;

    float MasterDecisionTimer;

    static constexpr int MASTER_ID = 0;
    static constexpr float MASTER_DECISION_PERIOD = 0.1f;
};

redpajama_set_name: RedPajamaGithub


text:
<!--

     Copyright 2014-2016 CyberVision, Inc.

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.

-->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="org.kaaproject.kaa.demo.smarthousedemo.ProgressFragment" >
    <ProgressBar
            android:id="@+id/progressDark"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:visibility="gone"/>
    <ProgressBar
            android:id="@+id/progressLight"
            style="?android:attr/progressBarStyleLargeInverse"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:visibility="gone"/>
    <TextView
            android:id="@+id/errorTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="?android:attr/textColorPrimary"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:visibility="gone"/>
</RelativeLayout>


text:
from __future__ import absolute_import

import logging

from confluent_kafka import Producer
from django.utils.functional import cached_property

from sentry import quotas
from sentry.models import Organization
from sentry.eventstream.base import EventStream
from sentry.utils import json

logger = logging.getLogger(__name__)

# Beware! Changing this, or the message format/fields themselves requires
# consideration of all downstream consumers.
# Version 1 format: (1, '(insert|delete)', {...event json...}, {...state for post-processing...})
EVENT_PROTOCOL_VERSION = 1

class KafkaEventStream(EventStream):
    def __init__(self, publish_topic='events', producer_configuration=None, **options):
        if producer_configuration is None:
            producer_configuration = {}

        self.publish_topic = publish_topic
        self.producer_configuration = producer_configuration

    @cached_property
    def producer(self):
        return Producer(self.producer_configuration)

    def delivery_callback(self, error, message):
        logger.warning('Could not publish event (error: %s): %r', error, message)

    def publish(self, group, event, is_new, is_sample, is_regression, is_new_group_environment, primary_hash, skip_consume=False):
        project = event.project
        retention_days = quotas.get_event_retention(
            organization=Organization(project.organization_id)
        )

        # Polling the producer is required to ensure callbacks are fired. This
        # means that the latency between a message being delivered (or failing
        # to be delivered) and the corresponding callback being fired is
        # roughly the same as the duration of time that passes between publish
        # calls. If this ends up being too high, the publisher should be moved
        # into a background thread that can poll more frequently without
        # interfering with request handling. (This does `poll` does not act as
        # a heartbeat for the purposes of any sort of session expiration.)
        self.producer.poll(0.0)

        try:
            key = '%s:%s' % (event.project_id, event.event_id)
            value = (EVENT_PROTOCOL_VERSION, 'insert', {
                'group_id': event.group_id,
                'event_id': event.event_id,
                'organization_id': project.organization_id,
                'project_id': event.project_id,
                'message': event.message,
                'platform': event.platform,
                'datetime': event.datetime,
                'data': event.data.data,
                'primary_hash': primary_hash,
                'retention_days': retention_days,
            }, {
                'is_new': is_new,
                'is_sample': is_sample,
                'is_regression': is_regression,
                'is_new_group_environment': is_new_group_environment,
            })
            self.producer.produce(
                self.publish_topic,
                key=key.encode('utf-8'),
                value=json.dumps(value),
                on_delivery=self.delivery_callback,
            )
        except Exception as error:
            logger.warning('Could not publish event: %s', error, exc_info=True)
            raise


text:
step 'you click on the :link_name link' do |link_name|
  click_on "#{link_name}"
end

step 'you should see the :title page' do |title|
  page.should have_content "#{title}"
end

step "you fill in file with :filename" do |filename|
  full_pathname = Rails.root + filename
  page.attach_file("file", full_pathname )
end

step "you should see a :msg message" do |message|
  page.should have_content "#{message}"
end


text:
struct slist {
    void *data;
    struct slist *next;
};

struct slist *slist_append(struct slist *list, void *data)
{
    struct slist *nl = malloc(sizeof(*list));
    if (nl) {
        nl->data = data;
        nl->next = list;
    }

    return nl;
}

void slist_free(struct slist *list, void (*cleanup)(void *data))
{
    while (list) {
        if (list->data)
            cleanup(list->data);
        struct slist *next = list->next;
        free(list);
        list = next;
    }
}

struct slist *slist_remove(struct slist *list, void *data)
{
    if (!list)
        return NULL;

    struct slist *prev = NULL;
    struct slist *head = list;

    do {
        if (list->data == data) {
            if (prev)
                prev->next = list->next;
            else
                head = list->next;
            free(list);
            break;
        }
        prev = list;
        list = list->next;
    } while (list);

    return head;
}

void slist_foreach(
        struct slist *list,
        void (*handler)(void *data, void *userdata),
        void *userdata)
{
    while (list) {
        handler(list->data, userdata);
        list = list->next;
    }
}

struct slist *slist_find(struct slist *list, void *data)
{
    while (list) {
        if (list->data == data)
            break;
        list = list->next;
    }

    return list;
}

struct slist *slist_find_custom(
        struct slist *list,
        bool (*check)(void *data, void *userdata),
        void *userdata)
{
    while (list) {
        if (check(list->data, userdata))
            break;
        list = list->next;
    }

    return list;
}


text:
using System;
using QuantConnect.Data.UniverseSelection;

namespace QuantConnect.Data.Fundamental
{
    /// <summary>
    /// Defines a merged viw of <see cref="FineFundamental"/> and <see cref="CoarseFundamental"/>
    /// </summary>
    public class Fundamentals : FineFundamental
    {
        /// <summary>
        /// Gets the market for this symbol
        /// </summary>
        public string Market { get; set; }

        /// <summary>
        /// Gets the day's dollar volume for this symbol
        /// </summary>
        public decimal DollarVolume { get; set; }

        /// <summary>
        /// Gets the day's total volume
        /// </summary>
        public long Volume { get; set; }

        /// <summary>
        /// Returns whether the symbol has fundamental data for the given date
        /// </summary>
        public bool HasFundamentalData { get; set; }

        /// <summary>
        /// Default constructor
        /// </summary>
        public Fundamentals()
        {
            DataType = MarketDataType.Auxiliary;
        }

        /// <summary>
        /// Return the URL string source of the file. This will be converted to a stream
        /// </summary>
        public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
        {
            throw new NotImplementedException($"{nameof(Fundamentals)}.{nameof(GetSource)} is never intended to be invoked.");
        }

        /// <summary>
        /// Reader converts each line of the data source into BaseData objects. Each data type creates its own factory method, and returns a new instance of the object
        /// each time it is called. The returned object is assumed to be time stamped in the config.ExchangeTimeZone.
        /// </summary>
        public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
        {
            throw new NotImplementedException($"{nameof(Fundamentals)}.{nameof(Reader)} is never intended to be invoked.");
        }
    }
}


text:
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System;
using System.Collections.Generic;
using osu.Framework.Configuration;
using osu.Game.Modes.Objects.Drawables;

namespace osu.Game.Modes
{
    public abstract class ScoreProcessor
    {
        public virtual Score GetScore() => new Score()
        {
            TotalScore = TotalScore,
            Combo = Combo,
            MaxCombo = HighestCombo,
            Accuracy = Accuracy,
            Health = Health,
        };

        public readonly BindableDouble TotalScore = new BindableDouble { MinValue = 0 };

        public readonly BindableDouble Accuracy = new BindableDouble { MinValue = 0, MaxValue = 1 };

        public readonly BindableDouble Health = new BindableDouble { MinValue = 0, MaxValue = 1 };

        public readonly BindableInt Combo = new BindableInt();

        /// <summary>
        /// Are we allowed to fail?
        /// </summary>
        protected bool CanFail => true;

        protected bool HasFailed { get; private set; }

        /// <summary>
        /// Called when we reach a failing health of zero.
        /// </summary>
        public event Action Failed;

        /// <summary>
        /// Keeps track of the highest combo ever achieved in this play.
        /// This is handled automatically by ScoreProcessor.
        /// </summary>
        public readonly BindableInt HighestCombo = new BindableInt();

        public readonly List<JudgementInfo> Judgements;

        /// <summary>
        /// Initializes a new instance of the <see cref="ScoreProcessor"/> class.
        /// </summary>
        /// <param name="hitObjectCount">Number of HitObjects. It is used for specifying Judgements collection Capacity</param>
        public ScoreProcessor(int hitObjectCount = 0)
        {
            Combo.ValueChanged += delegate { HighestCombo.Value = Math.Max(HighestCombo.Value, Combo.Value); };
            Judgements = new List<JudgementInfo>(hitObjectCount);
        }

        public void AddJudgement(JudgementInfo judgement)
        {
            Judgements.Add(judgement);

            UpdateCalculations(judgement);

            judgement.ComboAtHit = (ulong)Combo.Value;
            if (Health.Value == Health.MinValue && !HasFailed)
            {
                HasFailed = true;
                Failed?.Invoke();
            }
        }

        /// <summary>
        /// Update any values that potentially need post-processing on a judgement change.
        /// </summary>
        /// <param name="newJudgement">A new JudgementInfo that triggered this calculation. May be null.</param>
        protected abstract void UpdateCalculations(JudgementInfo newJudgement);
    }
}


text:
package org.batfish.representation.f5_bigip;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;

/** Configuration for a pool of snat-translations. */
@ParametersAreNonnullByDefault
public final class SnatPool implements Serializable {

  private final @Nonnull Set<String> _members;

  private final @Nonnull String _name;

  public SnatPool(String name) {
    _name = name;
    _members = new HashSet<>();
  }

  public @Nonnull Set<String> getMembers() {
    return _members;
  }

  public @Nonnull String getName() {
    return _name;
  }
}


text:
<?php

namespace Sifo\SharedBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * BlogPage
 */
class BlogPage
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $code;

    /**
     * @var string
     */
    private $tittle;

    /**
     * @var text
     */
    private $content;

    /**
     * @var boolean
     */
    private $isActive;

    /**
     * @var \DateTime
     */
    private $createdAt;

    /**
     * @var \DateTime
     */
    private $updatedAt;

    /**
     * @var string
     */
    private $operator;

    /**
     * @var \Doctrine\Common\Collections\Collection
     */
    private $blogMenus;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->blogMenus = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set code
     *
     * @param string $code
     * @return BlogPage
     */
    public function setCode($code)
    {
        $this->code = $code;

        return $this;
    }

    /**
     * Get code
     *
     * @return string
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * Set tittle
     *
     * @param string $tittle
     * @return BlogPage
     */
    public function setTittle($tittle)
    {
        $this->tittle = $tittle;

        return $this;
    }

    /**
     * Get tittle
     *
     * @return string
     */
    public function getTittle()
    {
        return $this->tittle;
    }

    /**
     * Set content
     *
     * @param text $content
     * @return BlogPage
     */
    public function setContent($content)
    {
        $this->content = $content;

        return $this;
    }

    /**
     * Get content
     *
     * @return text
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Set isActive
     *
     * @param boolean $isActive
     * @return BlogPage
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;

        return $this;
    }

    /**
     * Get isActive
     *
     * @return boolean
     */
    public function getIsActive()
    {
        return $this->isActive;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @return BlogPage
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     * @return BlogPage
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set operator
     *
     * @param string $operator
     * @return BlogPage
     */
    public function setOperator($operator)
    {
        $this->operator = $operator;

        return $this;
    }

    /**
     * Get operator
     *
     * @return string
     */
    public function getOperator()
    {
        return $this->operator;
    }

    /**
     * Add blogMenus
     *
     * @param \Sifo\SharedBundle\Entity\BlogMenu $blogMenus
     * @return StudentsGrouping
     */
    public function addBlogMenu(\Sifo\SharedBundle\Entity\BlogMenu $blogMenus)
    {
        $this->blogMenus[] = $blogMenus;

        return $this;
    }

    /**
     * Remove blogMenus
     *
     * @param \Sifo\SharedBundle\Entity\BlogMenu $blogMenus
     */
    public function removeBlogMenu(\Sifo\SharedBundle\Entity\BlogMenu $blogMenus)
    {
        $this->blogMenus->removeElement($blogMenus);
    }

    /**
     * Get blogMenus
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getBlogMenus()
    {
        return $this->blogMenus;
    }

    /**
     * @ORM\PrePersist
     */
    public function setCreatedAtValue()
    {
        if(!$this->getCreatedAt()) {
            $this->createdAt = new \DateTime();
        }
    }

    /**
     * @ORM\PreUpdate
     */
    public function setUpdatedAtValue()
    {
        $this->updatedAt = new \DateTime();
    }

    public function __toString()
    {
        return $this->getCode()." - ".$this->getTittle() ? $this->getCode()." - ".$this->getTittle() : "";
    }
}


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 org.openid4java.discovery.DiscoveryException (OpenID4Java no dependencies 0.9.7-SNAPSHOT API)
</TITLE>

<META NAME="date" CONTENT="2011-05-25">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.openid4java.discovery.DiscoveryException

Packages that use DiscoveryException

org.openid4java.consumer
Provides functionality for OpenID-enabling Consumer (Relying Party) sites.

org.openid4java.discovery

org.openid4java.discovery.html

org.openid4java.discovery.xrds

org.openid4java.discovery.xri

org.openid4java.discovery.yadis

org.openid4java.message

Uses of DiscoveryException in org.openid4java.consumer

Methods in org.openid4java.consumer that throw DiscoveryException

 List
ConsumerManager.discover(String identifier)

          Does discovery on an identifier.

 VerificationResult
ConsumerManager.verify(String receivingUrl,
       ParameterList response,
       DiscoveryInformation discovered)

          Performs verification on the Authentication Response (assertion)
 received from the OpenID Provider.

Uses of DiscoveryException in org.openid4java.discovery

Methods in org.openid4java.discovery that throw DiscoveryException

 List
Discovery.discover(Identifier identifier)

 List
Discovery.discover(String identifier)

static URL
UrlIdentifier.normalize(String text)

static URL
UrlIdentifier.normalize(String text,
          boolean removeFragment)

 Identifier
Discovery.parseIdentifier(String identifier)

 Identifier
Discovery.parseIdentifier(String identifier,
                boolean removeFragment)

static List
Discovery.rpDiscovery(String realm,
            YadisResolver yadisResolver)

          Performs discovery on the Relying Party's realm and returns a list of
 OpenID 2.0 DiscoveryInformation entries.

Constructors in org.openid4java.discovery that throw DiscoveryException

DiscoveryInformation(URL opEndpoint)

DiscoveryInformation(URL opEndpoint,
                     Identifier claimedIdentifier)

DiscoveryInformation(URL opEndpoint,
                     Identifier claimedIdentifier,
                     String version)

DiscoveryInformation(URL opEndpoint,
                     Identifier claimedIdentifier,
                     String delegate,
                     String version)

DiscoveryInformation(URL opEndpoint,
                     Identifier claimedIdentifier,
                     String delegate,
                     String version,
                     Set types)

UrlIdentifier(String identifier)

UrlIdentifier(String identifier,
              boolean removeFragment)

XriIdentifier(String identifier,
              String iriNormalForm,
              String uriNormalForm)

Uses of DiscoveryException in org.openid4java.discovery.html

Methods in org.openid4java.discovery.html that throw DiscoveryException

 List
HtmlResolver.discoverHtml(UrlIdentifier identifier)

          Performs HTML discovery on the supplied URL identifier.

 List
HtmlResolver.discoverHtml(UrlIdentifier identifier,
             HttpFetcher httpFetcher)

          Performs HTML discovery on the supplied URL identifier.

 void
HtmlParser.parseHtml(String htmlData,
          HtmlResult result)

          Parses the HTML data and stores in the result the discovered openid
 information.

 void
CyberNekoDOMHtmlParser.parseHtml(String htmlData,
          HtmlResult result)

 void
HtmlResult.setEndpoint1(String op1Endpoint)

 void
HtmlResult.setEndpoint2(String op2Endpoint)

Uses of DiscoveryException in org.openid4java.discovery.xrds

Methods in org.openid4java.discovery.xrds that throw DiscoveryException

 List
XrdsParserImpl.parseXrds(String input,
          Set targetTypes)

 List
XrdsParser.parseXrds(String input,
          Set targetTypes)

          Parses a XRDS document and extracts the relevant information
 for the specified service endpoint types.

Uses of DiscoveryException in org.openid4java.discovery.xri

Methods in org.openid4java.discovery.xri that throw DiscoveryException

 List
XriResolver.discover(XriIdentifier xri)

          Performs OpenID discovery on the supplied XRI identifier.

 List
XriDotNetProxyResolver.discover(XriIdentifier xri)

 List
LocalXriResolver.discover(XriIdentifier xri)

protected  List
LocalXriResolver.extractDiscoveryInformation(org.openxri.xml.XRDS xrds,
                            XriIdentifier identifier,
                            org.openxri.resolve.Resolver xriResolver)

          Extracts OpenID discovery endpoints from a XRDS discovery result
 for XRI identifiers.

 XriIdentifier
XriResolver.parseIdentifier(String identifier)

 XriIdentifier
XriDotNetProxyResolver.parseIdentifier(String identifier)

 XriIdentifier
LocalXriResolver.parseIdentifier(String identifier)

Uses of DiscoveryException in org.openid4java.discovery.yadis

Subclasses of DiscoveryException in org.openid4java.discovery.yadis

 class
YadisException

Methods in org.openid4java.discovery.yadis that throw DiscoveryException

 List
YadisResolver.discover(String url)

          Performs Yadis discovery on the YadisURL.

 List
YadisResolver.discover(String url,
         HttpFetcher httpFetcher)

          Performs Yadis discovery on the YadisURL.

 List
YadisResolver.discover(String url,
         int maxRedirects)

          Performs Yadis discovery on the YadisURL.

 List
YadisResolver.discover(String url,
         int maxRedirects,
         HttpFetcher httpFetcher)

          Performs Yadis discovery on the YadisURL.

 YadisResult
YadisResolver.discover(String url,
         int maxRedirects,
         HttpFetcher httpFetcher,
         Set serviceTypes)

 YadisResult
YadisResolver.discover(String url,
         int maxRedirects,
         Set serviceTypes)

 List
YadisResolver.discoverRP(String url)

          Performs Relyin Party discovery on the supplied URL.

 List
YadisResult.getDiscoveredInformation(Set targetTypes)

Uses of DiscoveryException in org.openid4java.message

Methods in org.openid4java.message that throw DiscoveryException

 String
AuthSuccess.getIdentity()

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2011 Sxip. All Rights Reserved.


text:
<?php

namespace Cinam\Randomizer;

use Cinam\Randomizer\Exception\InvalidArgumentException;

/**
 * Class for generating random numbers.
 *
 * @author cinam <cinam@hotmail.com>
 */
class NumberGenerator
{
    /**
     * Returns random integer from given range.
     *
     * @param integer $min The minimal value.
     * @param integer $max The maximal value.
     *
     * @return integer
     *
     * @throws InvalidArgumentException If min is greater than max.
     */
    public function getInt($min, $max)
    {
        if ($min > $max) {
            throw new InvalidArgumentException('Min cannot be greater than max');
        }

        return \mt_rand($min, $max);
    }

    /**
     * Returns random float from given range.
     *
     * @param float $min The minimal value.
     * @param float $max The maximal value.
     *
     * @return float
     *
     * @throws InvalidArgumentException If min is greater than max.
     */
    public function getFloat($min, $max)
    {
        if ($min > $max) {
            throw new InvalidArgumentException('Min cannot be greater than max');
        }

        $random01 = \mt_rand() / \mt_getrandmax();

        // [0, 1] -> [min, max]:
        // y = (max - min) * x + min
        return ($max - $min) * $random01 + $min;
    }
}


text:
package nl.fcdonders.fieldtrip.bufferserver.data;

import java.nio.ByteOrder;
import java.util.ArrayList;

import nl.fcdonders.fieldtrip.bufferserver.exceptions.DataException;
import nl.fcdonders.fieldtrip.bufferserver.network.NetworkProtocol;
import nl.fcdonders.fieldtrip.bufferserver.network.Request;
import nl.fcdonders.fieldtrip.bufferserver.network.WaitRequest;

public class RingDataStore extends DataModel {
	protected final ArrayList<WaitRequest> requests = new ArrayList<WaitRequest>();
	protected DataRingBuffer dataBuffer;
	protected final EventRingBuffer eventBuffer;
	protected int nChans;
	protected int nBytes;
	protected int dataType;
	protected Header header = null;
	protected final static ByteOrder NATIVE_ORDER = ByteOrder.nativeOrder();
	protected final int dataBufferSize;

	/**
	 * Constructor
	 *
	 * @param nBuffer
	 *            Capacit of sample and event buffers.
	 */
	public RingDataStore(final int nBuffer) {
		eventBuffer = new EventRingBuffer(nBuffer);
		dataBufferSize = nBuffer;
	}

	/**
	 * Constructor
	 *
	 * @param nSamples
	 *            Capacity of the sample ringbuffer.
	 * @param nEvents
	 *            Capacity of the event ringbuffer.
	 */
	public RingDataStore(final int nSamples, final int nEvents) {
		eventBuffer = new EventRingBuffer(nEvents);
		dataBufferSize = nSamples;
	}

	/**
	 * Adds a thread, with corresponding request, to the list of listeners of
	 * this dataStore. Once the threshold, as defined in request, had been met
	 * the threads waitOver() function will be called.
	 *
	 * @param thread
	 * @param request
	 */
	@Override
	public synchronized void addWaitRequest(final WaitRequest request) {
		requests.add(request);
	}

	/**
	 * Checks for all the listeners, if the conditions have been met, if so
	 * calls the appropriate waitOver function.
	 *
	 * @throws DataException
	 */
	protected synchronized void checkListeners() throws DataException {
		for (int i = 0; i < requests.size(); i++) {

			final int eventThreshold = requests.get(i).nEvents;
			final int sampleThreshold = requests.get(i).nSamples;

			if (getEventCount() > eventThreshold && eventThreshold != -1
					|| getSampleCount() > sampleThreshold
					&& sampleThreshold != -1) {
				requests.get(i).satisfied();
				requests.remove(i);
				i--;
			}
		}
	}

	/**
	 * Removes all data.
	 *
	 * @throws DataException
	 */
	@Override
	public synchronized void flushData() throws DataException {
		dataBuffer.clear();

	}

	/**
	 * Removes all events.
	 *
	 * @throws DataException
	 */
	@Override
	public synchronized void flushEvents() throws DataException {
		eventBuffer.clear();

	}

	/**
	 * Removes the header, and all data & events.
	 *
	 * @throws DataException
	 */
	@Override
	public synchronized void flushHeader() throws DataException {
		dataBuffer.clear();
		eventBuffer.clear();
		dataBuffer = null;
		header = null;
	}

	/**
	 * Returns all data
	 *
	 * @return
	 * @throws DataException
	 */
	@Override
	public synchronized Data getData() throws DataException {
		if (dataBuffer.sampleCount() == 0) {
			throw new DataException("No data stored.");
		}

		final int nSamples = dataBuffer.sampleCount();

		final byte[][][] data = new byte[nSamples][nChans][nBytes];

		int j = 0;
		for (int i = dataBuffer.indexOfOldest(); i < dataBuffer.sampleCount(); i++) {
			data[j++] = dataBuffer.get(i);
		}

		return new Data(nChans, nSamples, dataType, data, NATIVE_ORDER);
	}

	/**
	 * Returns the requested data. Throws DataException if impossible.
	 *
	 * @param request
	 *            Start index and end index of the range requested.
	 * @return
	 * @throws DataException
	 */
	@Override
	public synchronized Data getData(final Request request)
			throws DataException {
		if (dataBuffer.sampleCount() == 0) {
			throw new DataException("No data stored.");
		}

		if (request.begin < 0) {
			throw new DataException("Requesting samples with start index < 0.");
		}

		if (request.end < 0) {
			throw new DataException("Requesting samples with end index < 0.");
		}

		if (request.end < request.begin) {
			throw new DataException(
					"Requesting samples with start index > end index.");
		}

		if (request.end >= dataBuffer.sampleCount()) {
			throw new DataException(
					"Requesting samples that do not exist (end index >= sample count).");
		}

		if (request.begin >= dataBuffer.sampleCount()) {
			throw new DataException(
					"Requesting samples that do not exist (begin index >= sample count).");
		}

		if (request.end < dataBuffer.indexOfOldest()) {
			throw new DataException(
					"Requested samples that do not exist (end index < index of oldest sample in ring)");
		}

		if (request.begin < dataBuffer.indexOfOldest()) {
			throw new DataException(
					"Requested samples that do not exist (begin index < index of oldest sample in ring)");
		}

		final int nSamples = request.end - request.begin + 1;

		final byte[][][] data = new byte[nSamples][nChans][nBytes];

		int i = 0;
		for (int j = request.begin; j <= request.end; j++) {
			data[i++] = dataBuffer.get(j);
		}

		return new Data(nChans, nSamples, dataType, data, NATIVE_ORDER);
	}

	/**
	 * Returns the number of events currently stored. Throws DataException if
	 * impossible.
	 *
	 * @return
	 * @throws DataException
	 */
	@Override
	public synchronized int getEventCount() throws DataException {
		return eventBuffer.eventCount();
	}

	/**
	 * Returns all events
	 *
	 * @return
	 * @throws DataException
	 */
	@Override
	public synchronized Event[] getEvents() throws DataException {
		if (eventBuffer.eventCount() == 0) {
			throw new DataException("No events stored.");
		}

		final Event[] events = new Event[eventBuffer.eventCount()
		                                 - eventBuffer.indexOfOldest()];

		int j = 0;
		for (int i = eventBuffer.indexOfOldest(); i < eventBuffer.eventCount(); i++) {
			events[j++] = eventBuffer.get(i);
		}

		return events;
	}

	/**
	 * Returns the requested events. Throws DataException if impossible.
	 *
	 * @param request
	 *            Start index and end index of the range requested.
	 * @return
	 * @throws DataException
	 */
	@Override
	public synchronized Event[] getEvents(final Request request)
			throws DataException {
		if (eventBuffer.eventCount() == 0) {
			throw new DataException("No events stored.");
		}

		if (request.begin < 0) {
			throw new DataException("Requesting events with start index < 0.");
		}

		if (request.end < 0) {
			throw new DataException("Requesting events with end index < 0.");
		}

		if (request.end < request.begin) {
			throw new DataException(
					"Requesting events with start index > end index.");
		}

		if (request.end >= eventBuffer.eventCount()) {
			throw new DataException(
					"Requesting events that do not exist (end index >= events count).");
		}

		if (request.begin >= eventBuffer.eventCount()) {
			throw new DataException(
					"Requesting events that do not exist (begin index >= events count).");
		}

		if (request.end < eventBuffer.indexOfOldest()) {
			throw new DataException(
					"Requested samples that do not exist (end index < index of oldest sample in ring)");
		}

		if (request.begin < eventBuffer.indexOfOldest()) {
			throw new DataException(
					"Requested samples that do not exist (begin index < index of oldest sample in ring)");
		}

		final int nEvents = request.end - request.begin + 1;

		final Event[] events = new Event[nEvents];

		int j = 0;
		for (int i = request.begin; i <= request.end; i++) {
			events[j++] = eventBuffer.get(i);
		}

		return events;
	}

	/**
	 * Returns the header currently stored. Throws DataException if impossible.
	 *
	 * @return
	 * @throws DataException
	 */
	@Override
	public synchronized Header getHeader() throws DataException {

		// Check if header exists
		if (header == null) {
			throw new DataException("No header.");
		}

		// Return header with correct sample/event counts
		return new Header(header, getSampleCount(), getEventCount());
	}

	/**
	 * Returns the number of currently stored samples. Throws DataException if
	 * impossible.
	 *
	 * @return
	 * @throws DataException
	 */
	@Override
	public synchronized int getSampleCount() throws DataException {
		return dataBuffer.sampleCount();
	}

	/**
	 * Returns true if a header has been initialised.
	 *
	 * @return
	 */
	@Override
	public synchronized boolean headerExists() {
		return header != null;
	}

	/**
	 * Appends the data to the storage. Throws DataException if impossible.
	 *
	 * @param data
	 * @throws DataException
	 */
	@Override
	public synchronized int putData(final Data data) throws DataException {
		if (data.dataType != dataType) {
			throw new DataException("Trying to append data of wrong dataType.");
		}
		if (data.nChans != nChans) {
			throw new DataException(
					"Trying to append data with wrong number of channels");
		}

		// Check if byte order needs to be flipped
		if (data.order != NATIVE_ORDER && nBytes != 1) {
			for (int i = 0; i < data.nSamples; i++) {
				final byte[][] sample = new byte[nChans][nBytes];

				for (int j = 0; j < nChans; j++) {
					for (int k = 0; k < nBytes; k++) {
						sample[j][k] = data.data[i][j][nBytes - k - 1];
					}
				}

				dataBuffer.add(sample);
			}
		} else {
			for (int i = 0; i < data.nSamples; i++) {
				dataBuffer.add(data.data[i]);
			}
		}
		checkListeners();
		return dataBuffer.sampleCount();
	}

	/**
	 * Appends the events to the storage. Throws DataException if impossible.
	 *
	 * @param events
	 * @throws DataException
	 */
	@Override
	public synchronized int putEvents(final Event[] events)
			throws DataException {
		for (final Event event : events) {
			if (event.order != NATIVE_ORDER) {
				final int typeNBytes = NetworkProtocol
						.dataTypeSize(event.typeType);

				final byte[][] type = event.type.clone();
				if (typeNBytes > 1) {
					for (int i = 0; i < event.typeSize; i++) {
						for (int j = 0; j < typeNBytes; j++) {
							type[i * typeNBytes + j] = event.type[i
							                                      * typeNBytes + typeNBytes - j - 1];
						}
					}
				}

				final int valueNBytes = NetworkProtocol
						.dataTypeSize(event.valueType);

				final byte[][] value = event.value.clone();
				if (valueNBytes > 1) {
					for (int i = 0; i < event.valueSize; i++) {
						for (int j = 0; j < valueNBytes; j++) {
							value[i * valueNBytes + j] = event.value[i
							                                         * valueNBytes + valueNBytes - j - 1];
						}
					}
				}

				eventBuffer.add(new Event(event, type, value, NATIVE_ORDER));
			} else {
				eventBuffer.add(event);
			}
		}
		checkListeners();
		return eventBuffer.eventCount();
	}

	/**
	 * Adds the header to the storage. Throws DataException if impossible.
	 *
	 * @param hdr
	 * @throws DataException
	 */
	@Override
	public synchronized void putHeader(Header header) throws DataException {

		final boolean newHeader = header == null;

		// Check if header is in BIG_ENDIAN ByteOrder.
		if (header.order != NATIVE_ORDER) {
			final Chunk[] chunks = header.chunks;

			// Check each chunk, if it is a CHUNK_RESOLUTIONS chunk, flip the
			// byte order.
			for (int i = 0; i < chunks.length; i++) {
				if (chunks[i].type == NetworkProtocol.CHUNK_RESOLUTIONS) {
					final byte[] data = new byte[chunks[i].data.length];

					for (int j = 0; j < header.nChans; j++) {
						for (int k = 0; k < 8; k++) {
							data[j * 8 + k] = chunks[i].data[j * 8 + 7 - k];
						}
					}

					// Replace chunk.
					chunks[i] = new Chunk(chunks[i].type, chunks[i].size, data);
				}
			}

			// Create new header with BIG_ENDIAN ByteOrder
			header = new Header(header, chunks, NATIVE_ORDER);
		}

		if (newHeader) {
			if (nChans != header.nChans) {
				throw new DataException(
						"Replacing header has different number of channels");
			}
			if (dataType != header.dataType) {
				throw new DataException(
						"Replacing header has different data type");
			}
		} else {
			nChans = header.nChans;
			dataType = header.dataType;
			nBytes = NetworkProtocol.dataTypeSize(dataType);
		}

		this.header = header;
		dataBuffer = new DataRingBuffer(dataBufferSize, nChans, nBytes);

	}

	 public void cleanup(){}; // null class

}


text:
wn.provide('wn.views.doclistview');
wn.provide('wn.doclistviews');

wn.views.ListFactory = wn.views.Factory.extend({
	make: function(route) {
		var me = this;
		wn.model.with_doctype(route[1], function() {
			new wn.views.DocListView({
				doctype: route[1],
				page: me.make_page(true)
			});
		});
	}
});

$(document).on("save", function(event, doc) {
	var list_page = "List/" + doc.doctype;
	if(wn.pages[list_page]) {
		if(wn.pages[list_page].doclistview)
			wn.pages[list_page].doclistview.dirty = true;
	}
})

wn.views.DocListView = wn.ui.Listing.extend({
	init: function(opts) {
		$.extend(this, opts)
		this.label = wn._(this.doctype);
		this.dirty = true;
		this.tags_shown = false;
		this.label = (this.label.toLowerCase().substr(-4) == 'list') ?
		 	wn._(this.label) : (wn._(this.label) + ' ' + wn._('List'));
		this.make_page();
		this.setup();

		var me = this;
		$(this.page).on("show", function() {
			me.refresh();
		});
	},

	make_page: function() {
		var me = this;
		this.page.doclistview = this;
		this.$page = $(this.page).css({"min-height": "400px"});

		$('
\

'+wn._('Loading')+'...

')
			.appendTo(this.$page.find(".layout-main-section"));

		$('
\

Show
\

\

<input data-docstatus="0" type="checkbox" \
				checked="checked" /> '+wn._('Drafts')+'
\

<input data-docstatus="1" type="checkbox" \
				checked="checked" /> '+wn._('Submitted')+'
\

<input data-docstatus="2" type="checkbox" \
				/> '+wn._('Cancelled')+'

\

')
			.appendTo(this.$page.find(".layout-side-section"));

		this.$page.find(".layout-main-section")
			.css({"border-right":"1px solid #d7d7d7"})
			.parent().css({"margin-top":"-15px"});
		this.appframe = this.page.appframe;
		var module = locals.DocType[this.doctype].module;

		this.appframe.set_title(wn._(this.doctype) + " " + wn._("List"));
		this.appframe.add_module_icon(module, this.doctype, null, true);
		this.appframe.set_views_for(this.doctype, "list");
	},

	setup: function() {
		this.can_delete = wn.model.can_delete(this.doctype);
		this.meta = locals.DocType[this.doctype];
		this.$page.find('.wnlist-area').empty(),
		this.setup_listview();
		this.setup_docstatus_filter();
		this.init_list();
		this.init_stats();
		this.init_minbar();
		this.show_match_help();
		if(this.listview.settings.onload) {
			this.listview.settings.onload(this);
		}
		this.make_help();
		this.$page.find(".show_filters").css({"padding":"15px", "margin":"0px -15px"});
		var me = this;
		// this.$w.on("render-complete", function() {
		// 	me.set_sidebar_height();
		// });
	},

	set_sidebar_height: function() {
		var h_main = this.$page.find(".layout-main-section").height();
		var h_side = this.$page.find(".layout-side-section").height();
		if(h_side > h_main)
			this.$page.find(".layout-main-section").css({"min-height": h_side});
	},

	show_match_help: function() {
		var me = this;
		var match_rules = wn.perm.get_match_rule(this.doctype);
		if(keys(match_rules).length) {
			var match_text = []
			$.each(match_rules, function(key, values) {
				if(values.length==0) {
					match_text.push(wn._(wn.meta.get_label(me.doctype, key)) + wn._(" is not set"));
				} else if(values.length) {
					match_text.push(wn._(wn.meta.get_label(me.doctype, key)) + " = " + wn.utils.comma_or(values));
				}
			});
			wn.utils.set_footnote(this, this.$page.find(".layout-main-section"),
				wn._("Showing only for") + ": " + match_text.join(" & "));
			$(this.footnote_area).css({"margin-top":"0px", "margin-bottom":"20px"});
		}
	},
	make_help: function() {
		// Help
		if(this.meta.description) {
			this.appframe.add_help_button(this.meta.description);
		}
	},
	setup_docstatus_filter: function() {
		var me = this;
		this.can_submit = $.map(locals.DocPerm || [], function(d) {
			if(d.parent==me.meta.name && d.submit) return 1
			else return null;
		}).length;
		if(this.can_submit) {
			this.$page.find('.show-docstatus').removeClass('hide');
			this.$page.find('.show-docstatus input').click(function() {
				me.run();
			})
		}
	},
	setup_listview: function() {
		this.listview = wn.views.get_listview(this.doctype, this);
		this.wrapper = this.$page.find('.wnlist-area');
		this.page_length = 20;
		this.allow_delete = true;
	},
	init_list: function(auto_run) {
		var me = this;
		// init list
		this.make({
			method: 'webnotes.widgets.reportview.get',
			get_args: this.get_args,
			parent: this.wrapper,
			freeze: true,
			start: 0,
			page_length: this.page_length,
			show_filters: true,
			show_grid: true,
			new_doctype: this.doctype,
			allow_delete: this.allow_delete,
			no_result_message: this.make_no_result(),
			custom_new_doc: me.listview.make_new_doc || undefined,
		});

		// make_new_doc can be overridden so that default values can be prefilled
		// for example - communication list in customer
		$(this.wrapper).on("click", 'button[list_view_doc="'+me.doctype+'"]', function(){
			(me.listview.make_new_doc || me.make_new_doc).apply(me, [me.doctype]);
		});

		if((auto_run !== false) && (auto_run !== 0))
			this.refresh();
	},

	refresh: function() {
		var me = this;
		if(wn.route_options) {
			me.filter_list.clear_filters();
			$.each(wn.route_options, function(key, value) {
				me.filter_list.add_filter(me.doctype, key, "=", value);
			});
			wn.route_options = null;
			me.run();
		} else if(me.dirty) {
			me.run();
		} else {
			if(new Date() - (me.last_updated_on || 0) > 30000) {
				// older than 5 mins, refresh
				me.run();
			}
		}
	},

	run: function(more) {
		// set filter from route
		var route = wn.get_route();
		var me = this;
		if(route[2]) {
			$.each(wn.utils.get_args_dict_from_url(route[2]), function(key, val) {
				me.set_filter(key, val, true);
			});
		}
		this.last_updated_on = new Date();
		this._super(more);
	},

	make_no_result: function() {
		var new_button = wn.boot.profile.can_create.indexOf(this.doctype)!=-1
			? ('

<button class="btn btn-primary" \
				list_view_doc="%(doctype)s">'+
				wn._('Make a new') + ' %(doctype_label)s</button>
')
			: '';
		var no_result_message = repl('
\

' + wn._("No") + ' %(doctype_label)s ' + wn._("found") + '
' + new_button + '
', {
			doctype_label: wn._(this.doctype),
			doctype: this.doctype,
		});

		return no_result_message;
	},
	render_row: function(row, data) {
		data.doctype = this.doctype;
		this.listview.render(row, data, this);
	},
	get_args: function() {
		var docstatus_list = this.can_submit ? $.map(this.$page.find('.show-docstatus :checked'),
			function(inp) {
				return $(inp).attr('data-docstatus');
			}) : []

		var args = {
			doctype: this.doctype,
			fields: this.listview.fields,
			filters: this.filter_list.get_filters(),
			docstatus: docstatus_list,
			order_by: this.listview.order_by || undefined,
			group_by: this.listview.group_by || undefined,
		}

		// apply default filters, if specified for a listing
		$.each((this.listview.default_filters || []), function(i, f) {
		      args.filters.push(f);
		});

		return args;
	},
	init_minbar: function() {
		var me = this;
		this.appframe.add_icon_btn("2", 'icon-tag', wn._('Show Tags'), function() { me.toggle_tags(); });
		this.wrapper.on("click", ".list-tag-preview", function() { me.toggle_tags(); });
		if(this.can_delete || this.listview.settings.selectable) {
			this.appframe.add_icon_btn("2", 'icon-remove', wn._('Delete'), function() { me.delete_items(); });
			this.appframe.add_icon_btn("2", 'icon-ok', wn._('Select All'), function() {
				me.$page.find('.list-delete').prop("checked",
					me.$page.find('.list-delete:checked').length ? false : true);
			});
		}
		if(in_list(user_roles, "System Manager")) {
			var meta = locals.DocType[this.doctype];
			if(meta.allow_import || meta.document_type==="Master") {
				this.appframe.add_icon_btn("2", "icon-upload", wn._("Import"), function() {
					wn.set_route("data-import-tool", {
						doctype: me.doctype
					})
				})
			};
			this.appframe.add_icon_btn("2", "icon-glass", wn._("Customize"), function() {
				wn.set_route("Form", "Customize Form", {
					doctype: me.doctype
				})
			});
		}
	},

	toggle_tags: function() {
		if(this.tags_shown) {
			$(".tag-row").addClass("hide");
			this.tags_shown=false;
		} else {
			$(".tag-row").removeClass("hide");
			this.tags_shown=true;
		}
	},

	get_checked_items: function() {
		return $.map(this.$page.find('.list-delete:checked'), function(e) {
			return $(e).data('data');
		});
	},
	delete_items: function() {
		var me = this;
		var dl = this.get_checked_items();
		if(!dl.length)
			return;

		wn.confirm(wn._('This is permanent action and you cannot undo. Continue?'),
			function() {
				me.set_working(true);
				return wn.call({
					method: 'webnotes.widgets.reportview.delete_items',
					args: {
						items: $.map(dl, function(d, i) { return d.name }),
						doctype: me.doctype
					},
					callback: function() {
						me.set_working(false);
						me.dirty = true;
						me.refresh();
					}
				})
			}
		);
	},
	init_stats: function() {
		var me = this;
		this.sidebar_stats = new wn.views.SidebarStats({
			doctype: this.doctype,
			stats: this.listview.stats,
			parent: this.$page.find('.layout-side-section'),
			set_filter: function(fieldname, label) {
				me.set_filter(fieldname, label);
			},
			doclistview: this
		})
	},
	set_filter: function(fieldname, label, no_run) {
		var filter = this.filter_list.get_filter(fieldname);
		if(filter) {
			var v = cstr(filter.field.get_parsed_value());
			if(v.indexOf(label)!=-1) {
				// already set
				return false;
			} else {
				// second filter set for this field
				if(fieldname=='_user_tags') {
					// and for tags
					this.filter_list.add_filter(this.doctype, fieldname, 'like', '%' + label);
				} else {
					// or for rest using "in"
					filter.set_values(this.doctype, fieldname, 'in', v + ', ' + label);
				}
			}
		} else {
			// no filter for this item,
			// setup one
			if(fieldname=='_user_tags') {
				this.filter_list.add_filter(this.doctype, fieldname, 'like', '%' + label);
			} else {
				this.filter_list.add_filter(this.doctype, fieldname, '=', label);
			}
		}
		if(!no_run)
			this.run();
	}
});


text:
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//using Xunit;

//namespace MetroLog.NetCore.Tests
//{
//    public class SQLiteTargetTests
//    {
//        [Fact]
//        public void TestLogEventInfoToFromJson()
//        {
//            throw new NotImplementedException();
//        }

//        [Fact]
//        public void TestLogEventInfoToFromJsonWithException()
//        {
//            throw new NotImplementedException();
//        }
//    }
//}


text:
fclose('all');
clear all;
clc;
close all hidden;
colordef white;
beep off;
lastfile = [];


text:
require 'cocoa/bindings/NSObject'
module Cocoa
  class CIFeature < Cocoa::NSObject
    attach_method :bounds, :args=>0, :names=>[], :types=>[], :retval=>"{CGRect={CGPoint=dd}{CGSize=dd}}"
    attach_method :type, :args=>0, :names=>[], :types=>[], :retval=>"@"
  end
end


text:
<?php
App::uses('BlockAppModel', 'Model');

class BlockText extends BlockAppModel
{
  public $name = 'BlockText';
  public $useTable = FALSE;
  public $valid = array(
    'add' => array(
    ),
    'update' => array(
      'id' => 'required | isExist'
    ),
  );
  public $columnLabels = array();

  public function __construct($id = false, $table = null, $ds = null)
  {
    parent::__construct($id, $table, $ds);
    $this->columnLabels = array(
      'text' => __('テキスト'),
    );
  }

/**
 * Return initiali data
 *
 * @return mixed array on success. true to ignore. false to occur error.
 */
  public function initialData()
  {
    return array(
      'text' => __('テキストを入力してください。'),
    );
  }

}


text:
<?php
namespace TYPO3\CMS\Backend\Form\Exception;

/**
 * User check did not survive "recordEditAccessInternals" to edit record
 */
class AccessDeniedEditInternalsException extends AccessDeniedException
{
}


text:
RSpec.describe RuboCop::Cop::Style::Next, :config do
  let(:cop_config) { { 'MinBodyLength' => 1 } }

  shared_examples 'iterators' do |condition|
    let(:opposite) { condition == 'if' ? 'unless' : 'if' }

    it "registers an offense for #{condition} inside of downto" do
      expect_offense(<<~RUBY, condition: condition)
        3.downto(1) do
          %{condition} o == 1
          ^{condition}^^^^^^^ Use `next` to skip iteration.
            puts o
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        3.downto(1) do
          next #{opposite} o == 1
          puts o
        end
      RUBY
    end

    it "registers an offense for #{condition} inside of each" do
      expect_offense(<<~RUBY, condition: condition)
        [].each do |o|
          %{condition} o == 1
          ^{condition}^^^^^^^ Use `next` to skip iteration.
            puts o
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        [].each do |o|
          next #{opposite} o == 1
          puts o
        end
      RUBY
    end

    it "registers an offense for #{condition} inside of each_with_object" do
      expect_offense(<<~RUBY, condition: condition)
        [].each_with_object({}) do |o, a|
          %{condition} o == 1
          ^{condition}^^^^^^^ Use `next` to skip iteration.
            a[o] = {}
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        [].each_with_object({}) do |o, a|
          next #{opposite} o == 1
          a[o] = {}
        end
      RUBY
    end

    it "registers an offense for #{condition} inside of for" do
      expect_offense(<<~RUBY, condition: condition)
        for o in 1..3 do
          %{condition} o == 1
          ^{condition}^^^^^^^ Use `next` to skip iteration.
            puts o
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        for o in 1..3 do
          next #{opposite} o == 1
          puts o
        end
      RUBY
    end

    it "registers an offense for #{condition} inside of loop" do
      expect_offense(<<~RUBY, condition: condition)
        loop do
          %{condition} o == 1
          ^{condition}^^^^^^^ Use `next` to skip iteration.
            puts o
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        loop do
          next #{opposite} o == 1
          puts o
        end
      RUBY
    end

    it "registers an offense for #{condition} inside of map" do
      expect_offense(<<~RUBY, condition: condition)
        loop do
          {}.map do |k, v|
            %{condition} v == 1
            ^{condition}^^^^^^^ Use `next` to skip iteration.
              puts k
            end
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        loop do
          {}.map do |k, v|
            next #{opposite} v == 1
            puts k
          end
        end
      RUBY
    end

    it "registers an offense for #{condition} inside of times" do
      expect_offense(<<~RUBY, condition: condition)
        loop do
          3.times do |o|
            %{condition} o == 1
            ^{condition}^^^^^^^ Use `next` to skip iteration.
              puts o
            end
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        loop do
          3.times do |o|
            next #{opposite} o == 1
            puts o
          end
        end
      RUBY
    end

    it "registers an offense for #{condition} inside of collect" do
      expect_offense(<<~RUBY, condition: condition)
        [].collect do |o|
          %{condition} o == 1
          ^{condition}^^^^^^^ Use `next` to skip iteration.
            true
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        [].collect do |o|
          next #{opposite} o == 1
          true
        end
      RUBY
    end

    it "registers an offense for #{condition} inside of select" do
      expect_offense(<<~RUBY, condition: condition)
        [].select do |o|
          %{condition} o == 1
          ^{condition}^^^^^^^ Use `next` to skip iteration.
            true
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        [].select do |o|
          next #{opposite} o == 1
          true
        end
      RUBY
    end

    it "registers an offense for #{condition} inside of select!" do
      expect_offense(<<~RUBY, condition: condition)
        [].select! do |o|
          %{condition} o == 1
          ^{condition}^^^^^^^ Use `next` to skip iteration.
            true
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        [].select! do |o|
          next #{opposite} o == 1
          true
        end
      RUBY
    end

    it "registers an offense for #{condition} inside of reject" do
      expect_offense(<<~RUBY, condition: condition)
        [].reject do |o|
          %{condition} o == 1
          ^{condition}^^^^^^^ Use `next` to skip iteration.
            true
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        [].reject do |o|
          next #{opposite} o == 1
          true
        end
      RUBY
    end

    it "registers an offense for #{condition} inside of reject!" do
      expect_offense(<<~RUBY, condition: condition)
        [].reject! do |o|
          %{condition} o == 1
          ^{condition}^^^^^^^ Use `next` to skip iteration.
            true
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        [].reject! do |o|
          next #{opposite} o == 1
          true
        end
      RUBY
    end

    it "registers an offense for #{condition} inside of nested iterators" do
      expect_offense(<<~RUBY, condition: condition)
        loop do
          until false
            %{condition} o == 1
            ^{condition}^^^^^^^ Use `next` to skip iteration.
              puts o
            end
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        loop do
          until false
            next #{opposite} o == 1
            puts o
          end
        end
      RUBY
    end

    it "registers an offense for #{condition} inside of nested iterators" do
      expect_offense(<<~RUBY, condition: condition)
        loop do
          while true
            %{condition} o == 1
            ^{condition}^^^^^^^ Use `next` to skip iteration.
              puts o
            end
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        loop do
          while true
            next #{opposite} o == 1
            puts o
          end
        end
      RUBY
    end

    it 'registers an offense for a condition at the end of an iterator ' \
       'when there is more in the iterator than the condition' do
      expect_offense(<<~RUBY, condition: condition)
        [].each do |o|
          puts o
          %{condition} o == 1
          ^{condition}^^^^^^^ Use `next` to skip iteration.
            puts o
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        [].each do |o|
          puts o
          next #{opposite} o == 1
          puts o
        end
      RUBY
    end

    it 'allows loops with conditional break' do
      expect_no_offenses(<<~RUBY)
        loop do
          puts ''
          break #{condition} o == 1
        end
      RUBY
    end

    it 'allows loops with conditional return' do
      expect_no_offenses(<<~RUBY)
        loop do
          puts ''
          return #{condition} o == 1
        end
      RUBY
    end

    it "allows loops with #{condition} being the entire body with else" do
      expect_no_offenses(<<~RUBY)
        [].each do |o|
          #{condition} o == 1
            puts o
          else
            puts 'no'
          end
        end
      RUBY
    end

    it "allows loops with #{condition} with else, nested in another condition" do
      expect_no_offenses(<<~RUBY)
        [].each do |o|
          if foo
            #{condition} o == 1
              puts o
            else
              puts 'no'
            end
          end
        end
      RUBY
    end

    it "allows loops with #{condition} with else at the end" do
      expect_no_offenses(<<~RUBY)
        [].each do |o|
          puts o
          #{condition} o == 1
            puts o
          else
            puts 'no'
          end
        end
      RUBY
    end

    it "reports an offense for #{condition} whose body has 3 lines" do
      expect_offense(<<~RUBY, condition: condition)
        arr.each do |e|
          %{condition} something
          ^{condition}^^^^^^^^^^ Use `next` to skip iteration.
            work
            work
            work
          end
        end
      RUBY

      expect_correction(<<~RUBY)
        arr.each do |e|
          next #{opposite} something
          work
          work
          work
        end
      RUBY
    end

    context 'EnforcedStyle: skip_modifier_ifs' do
      let(:cop_config) { { 'EnforcedStyle' => 'skip_modifier_ifs' } }

      it "allows modifier #{condition}" do
        expect_no_offenses(<<~RUBY)
          [].each do |o|
            puts o #{condition} o == 1
          end
        RUBY
      end
    end

    context 'EnforcedStyle: always' do
      let(:cop_config) { { 'EnforcedStyle' => 'always' } }
      let(:opposite) { condition == 'if' ? 'unless' : 'if' }

      it "registers an offense for modifier #{condition}" do
        expect_offense(<<~RUBY, condition: condition)
          [].each do |o|
            puts o #{condition} o == 1 # comment
            ^^^^^^^^{condition}^^^^^^^ Use `next` to skip iteration.
          end
        RUBY

        expect_correction(<<~RUBY)
          [].each do |o|
            next #{opposite} o == 1
            puts o # comment
          end
        RUBY
      end
    end

    it 'auto-corrects a misaligned end' do
      expect_offense(<<~RUBY)
        [1, 2, 3, 4].each do |num|
          if !opts.nil?
          ^^^^^^^^^^^^^ Use `next` to skip iteration.
            puts num
            if num != 2
              puts 'hello'
              puts 'world'
            end
         end
        end
      RUBY

      expect_correction(<<~RUBY)
        [1, 2, 3, 4].each do |num|
          next unless !opts.nil?
          puts num
          next unless num != 2
          puts 'hello'
          puts 'world'
        end
      RUBY
    end
  end

  it 'keeps comments when autocorrecting' do
    expect_offense(<<~RUBY)
      loop do
        if test # keep me
        ^^^^^^^ Use `next` to skip iteration.
          # keep me
          something # keep me
          # keep me

        end # keep me
      end
    RUBY

    expect_correction(<<~RUBY)
      loop do
        next unless test # keep me
        # keep me
        something # keep me
        # keep me

       # keep me
      end
    RUBY
  end

  it 'handles `then` when autocorrecting' do
    expect_offense(<<~RUBY)
      loop do
        if test then
        ^^^^^^^ Use `next` to skip iteration.
          something
        end
      end
    RUBY

    expect_correction(<<~RUBY)
      loop do
        next unless test
        something
      end
    RUBY
  end

  it "doesn't reindent heredoc bodies when autocorrecting" do
    expect_offense(<<~RUBY)
      loop do
        if test
        ^^^^^^^ Use `next` to skip iteration.
          str = <<-BLAH
        this is a heredoc
         nice eh?
          BLAH
          something
        end
      end
    RUBY

    expect_correction(<<~RUBY)
      loop do
        next unless test
        str = <<-BLAH
        this is a heredoc
         nice eh?
        BLAH
        something
      end
    RUBY
  end

  it 'handles nested autocorrections' do
    expect_offense(<<~RUBY)
      loop do
        if test
        ^^^^^^^ Use `next` to skip iteration.
          loop do
            if test
            ^^^^^^^ Use `next` to skip iteration.
              something
            end
          end
        end
      end
    RUBY

    expect_correction(<<~RUBY)
      loop do
        next unless test
        loop do
          next unless test
          something
        end
      end
    RUBY
  end

  it_behaves_like 'iterators', 'if'
  it_behaves_like 'iterators', 'unless'

  it 'allows empty blocks' do
    expect_no_offenses(<<~RUBY)
      [].each do
      end
      [].each { }
    RUBY
  end

  it 'allows loops with conditions at the end with ternary op' do
    expect_no_offenses(<<~RUBY)
      [].each do |o|
        o == x ? y : z
      end
    RUBY
  end

  it 'allows super nodes' do
    # https://github.com/rubocop/rubocop/issues/1115
    expect_no_offenses(<<~RUBY)
      def foo
        super(a, a) { a }
      end
    RUBY
  end

  it 'does not blow up on empty body until block' do
    expect_no_offenses('until sup; end')
  end

  it 'does not blow up on empty body while block' do
    expect_no_offenses('while sup; end')
  end

  it 'does not blow up on empty body for block' do
    expect_no_offenses('for x in y; end')
  end

  it 'does not crash with an empty body branch' do
    expect_no_offenses(<<~RUBY)
      loop do
        if true
        end
      end
    RUBY
  end

  it 'does not crash with empty brackets' do
    expect_no_offenses(<<~RUBY)
      loop do
        ()
      end
    RUBY
  end

  context 'MinBodyLength: 3' do
    let(:cop_config) { { 'MinBodyLength' => 3 } }

    it 'accepts if whose body has 1 line' do
      expect_no_offenses(<<~RUBY)
        arr.each do |e|
          if something
            work
          end
        end
      RUBY
    end
  end

  context 'Invalid MinBodyLength' do
    let(:cop_config) { { 'MinBodyLength' => -2 } }

    it 'fails with an error' do
      source = <<~RUBY
        loop do
          if o == 1
            puts o
          end
        end
      RUBY

      expect { expect_no_offenses(source) }
        .to raise_error('MinBodyLength needs to be a positive integer!')
    end
  end
end


text:
<manifest package="com.escape.quickdevlibrary"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

    <application>

    </application>

</manifest>


text:
.. _vSphere API 5.0: ../../vim/version.rst#vimversionversion7

.. _vim.host.FileSystemVolume: ../../vim/host/FileSystemVolume.rst

vim.host.VfatVolume
===================
  VFAT file system volume.
:extends: vim.host.FileSystemVolume_
:since: `vSphere API 5.0`_

Attributes:


text:
package com.example.hellorammus;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class HelloRammus extends Activity {
	private static final String TAG = "HelloRammus";

	private static final int LOGIN_CHECK = 1;
	private static final int LOGIN_CHECK_RETURN = 222;
	private static final String LOGIN_SUCCESS = "111";

	public static final String PREF = "pref";

	private static final String SEND_BOARDCAST = "SEND_BOARDCAST";

	private TextView tv;
	private EditText et1, et2;
	private Button btn, btnHome, btnBMI, btnAbout, btnSend;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.v(TAG, "onCreate");
		init();

	}
	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			Log.d(TAG, "mBroadcastReceiver onReceive");
//			Intent newintent = new Intent(HelloRammus.this, HelloBMI.class);
//			startActivity(newintent);
		}

	};

	private void init() {
		setContentView(R.layout.login);

		tv = (TextView) findViewById(R.id.login_textView1);
		et1 = (EditText) findViewById(R.id.login_editText1);
		et2 = (EditText) findViewById(R.id.login_editText2);
		btn = (Button) findViewById(R.id.login_button1);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setButtonLogin();
			}
		});

		btnHome = (Button) findViewById(R.id.navigation_buttonHome);
		btnHome.setEnabled(false);

		btnBMI = (Button) findViewById(R.id.navigation_buttonBMI);
		btnBMI.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					Intent intent = new Intent();
					intent.setClass(HelloRammus.this, HelloBMI.class);
					startActivity(intent);
					finish();

				} catch (Exception e) {
					Log.e(TAG, e.toString());
				}
			}
		});

		btnAbout = (Button) findViewById(R.id.navigation_buttonAbout);
		btnAbout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					Intent intent = new Intent();
					intent.setClass(HelloRammus.this, AboutActivity.class);
					startActivity(intent);
					finish();

				} catch (Exception e) {
					Log.e(TAG, e.toString());
				}
			}
		});

		btnSend = (Button) findViewById(R.id.login_btn_send);
		btnSend.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.d(TAG, "btnSend onClick");
				try {
					Intent intent = new Intent(SEND_BOARDCAST);
					HelloRammus.this.sendBroadcast(intent);
				} catch (Exception e) {
					Log.e(TAG, e.toString());
				}
			}
		});

		tv.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				et1.setText("rammus");
				et2.setText("1234");
				return false;
			}
		});
	}

	private void setButtonLogin() {
		Intent intent = new Intent();
		intent.setClass(HelloRammus.this, LoginCheck.class);
		// intent.setClassName("com.example.logincheck",
		// "com.example.logincheck.LoginCheck");

		Bundle b = new Bundle();
		b.putString("KEY_ID", et1.getText().toString());
		b.putString("KEY_PWD", et2.getText().toString());
		intent.putExtras(b);
		try {
			startActivityForResult(intent, LOGIN_CHECK);
		} catch (Exception e) {
			Log.e(TAG, e.toString());
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		SharedPreferences sp = getSharedPreferences(PREF, Context.MODE_PRIVATE);
		SharedPreferences.Editor se = sp.edit();

		if (requestCode == LOGIN_CHECK) {
			if (resultCode == LOGIN_CHECK_RETURN) {
				if (data != null) {
					if (data.getExtras().getString("KEY_RESULT")
							.equalsIgnoreCase(LOGIN_SUCCESS)) {
						se.putBoolean("KEY_IF_LOGIN", true);

						tv.setText(getResources().getString(
								R.string.hello_rammus_login_ok));
						tv.setTextColor(getResources().getColor(
								R.color.col_blue));

					} else {
						se.putBoolean("KEY_IF_LOGIN", false);

						tv.setText(getString(R.string.hello_rammus_login_fail));
						tv.setTextColor(getResources()
								.getColor(R.color.col_red));
					}
				}
			}
		}
		se.commit();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.hello_rammus, menu);

		// MenuItem mi = menu.findItem(R.id.menu_about);
		// Intent intent = new Intent(HelloRammus.this, AboutActivity.class);
		// mi.setIntent(intent);
		// mi.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
		// {
		// @Override
		// public boolean onMenuItemClick(MenuItem item) {
		// finish();
		// return false;
		// }
		// });

		initDeputy();

		return super.onCreateOptionsMenu(menu);
	}

	private ArrayList<String> deputiesList = new ArrayList<String>();
	private String[] deputies;
	private boolean[] checkedItems = null;

	private void initDeputy() {
		deputiesList.add("David");
		deputiesList.add("Rammus");
		deputiesList.add("Ken");
		deputiesList.add("Mary");

		deputies = deputiesList.toArray(new String[deputiesList.size()]);
		checkedItems = new boolean[deputiesList.size()];
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_deputy:
			new AlertDialog.Builder(HelloRammus.this)
					.setTitle(R.string.dialog_deputy)
					.setMultiChoiceItems(deputies, checkedItems,
							new DialogInterface.OnMultiChoiceClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which, boolean isChecked) {
									checkedItems[which] = isChecked;
								}
							})
					.setPositiveButton(R.string.dialog_pos,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									StringBuilder sb = new StringBuilder();
									for (int i = 0; i < deputiesList.size(); i++) {
										if (checkedItems[i]) {
											sb.append(deputiesList.get(i)
													+ "\n");
										}
									}

									tv.setText(sb.toString());

								}
							})
					.setNegativeButton(R.string.dialog_neg,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							}).show();

			break;
		case R.id.menu_about:
			LayoutInflater li = LayoutInflater.from(HelloRammus.this);
			View v = li.inflate(R.layout.about_dialog, null);

			final Dialog aboutDialog = new Dialog(HelloRammus.this);
			aboutDialog.setTitle("Version");
			aboutDialog.setContentView(v);

			TextView textView = (TextView) v
					.findViewById(R.id.about_dialog_textView1);
			try {
				String s = getPackageManager().getPackageInfo(getPackageName(),
						0).versionName;
				textView.setText(s);
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}

			Button button = (Button) v.findViewById(R.id.about_dialog_button1);
			button.setOnClickListener(new Button.OnClickListener() {
				@Override
				public void onClick(View v) {
					aboutDialog.dismiss();
				}
			});

			aboutDialog.show();

			break;
		case R.id.menu_order:
			Intent intent = new Intent(HelloRammus.this, OrderActivity.class);
			startActivity(intent);

			break;
		case R.id.menu_setting:

			break;
		case R.id.menu_exit:
			new AlertDialog.Builder(HelloRammus.this)
					.setTitle(R.string.dialog_title)
					.setMessage(R.string.dialog_message)
					.setPositiveButton(R.string.dialog_pos,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									finish();

								}
							})
					.setNegativeButton(R.string.dialog_neg,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {

								}
							}).show();

			break;

		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.v(TAG, "onStart");
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.v(TAG, "onResume");
		SharedPreferences sp = HelloRammus.this.getSharedPreferences(PREF, Context.MODE_PRIVATE);
		et1.setText(sp.getString("KEY_ID", ""));

		IntentFilter filter = new IntentFilter(SEND_BOARDCAST);
		HelloRammus.this.registerReceiver(mBroadcastReceiver, filter);

	}

	@Override
	protected void onPause() {
		Log.v(TAG, "onPause");
		SharedPreferences sp = HelloRammus.this.getSharedPreferences(PREF,
				Context.MODE_PRIVATE);
		SharedPreferences.Editor se = sp.edit();
		se.putString("KEY_ID", et1.getText().toString());
		se.commit();

		HelloRammus.this.unregisterReceiver(mBroadcastReceiver);
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.v(TAG, "onStop");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.v(TAG, "onDestroy");
	}
}