text:
layout: post
title: Belajar Membuat Foreign Key Pada H2 Database
modified: 2017-06-3T20:15:28+07:00
categories:
description: belajar membuat foreign key pada h2 database
tags: [foreign key, h2 database]
image:
  background: abstract-2.png
comments: true
share: true
date: 2016-04-01T08:55:48+07:00
---

Artikel - artikel yang lalu, penulis membuat tulisan mengenai database PostgreSQL, akan tetapi pada penulisan ini kita akan mencoba menggunakan database h2 :).

## Apa Itu Foreign Key ?

>>Foreign Key adalah sebuah column atau field yang berfungsi sebagai kunci tamu dimana kunci ini akan kita gunakan untuk relasi antar tabel.

Jika anda telah terbiasa dengan database yang memiliki arsitektur RDBMS maka anda tidak asing lagi dengan namanya primary key. Setiap tabel di dalam database wajib memiliki primary key, dikarenakan primary key ini berfungsi sebagai kunci unik untuk membedakan antara 1 row atau record dengan record yang lain.

Apa hubungan antara primary key dan foreign key ? biasanya primary key kita gunakan sebagai kata kunci, sedangkan foreign key biasanya diambil dari primary key sebuah tabel, contoh nya seperti berikut.

|    NPM    | Nama Mahasiswa | Kelas |
|:----------|:---------------|:------|
|58412085   | Rizki Mufrizal | 4IA04 |
|12345678   | Mufrizal       | 4IA00 |
{: rules="groups"}

dan berikut adalah tabel nilai uts.

| ID Nilai | UTS | UAS |    NPM   |
|:---------|:----|:----|:---------:
| N01      | 100 | 100 | 58412085 |
| N02      | 90  | 90  | 12345678 |
| N03      | 80  | 80  | 58412085 |
{: rules="groups"}

Dari kedua tabel diatas dapat dilihat adanya relasi antara tabel mahasiswa dan tabel nilai. Pada tabel mahasiswa terdapat 1 primary key yaitu npm sedangkan pada tabel nilai kita memiliki 1 primary key juga yaitu id nilai. Sesuai dengan pembahasan kita yaitu foreign key, pada kedua tabel diatas terdapat 1 foreign key. Fireign key tersebut berada pada tabel nilai yaitu npm, dimana npm ini adalah primary key yang terdapat pada tabel mahasiswa.

## Bagaimana Cara Menentukan Foreign Key ?

Kebiasaan seorang mahasiswa bingung bagaimana cara menetukan relasi antar tabel, bahkan ada beberapa mahasiswa yang secara langsung membuat aplikasi tanpa membuat normalisasi dan ERD, padahal normalisasi dan ERD adalah sesuatu yang wajib dibuat. Pada artikel ini, kita akan menggunakan cara cepat untuk menentukan relasi antar tabel. Misalkan penulis mempunyai data seperti berikut.

| NB | JB | TK | HSB | JBT | TH | TT | NP | JBD | THPB |
|:------------|:-------------|:-------------------|:--------------------|:-----------------------|:------------|:------------------|:-------------|:---------------------|:-----------------------|
|Rinso|Cair|01-01-2016|Rp 1000|10|Rp 5000|02-02-2016|Rizki|5|Rp 5000|
|Baju|Padat|01-02-2016|Rp 2000|50|Rp 10000|02-02-2016|Rizki|5|Rp 10000|
|Rinso|Cair|01-01-2016|Rp 1000|10|Rp 10000|02-02-2016|Mufrizal|10|Rp 10000|
{: rules="groups"}

Ket :

* NB : Nama Barang
* JB : Jenis Barang
* TK : Tanggal Kadaluarsa
* TH : Total Harga
* TT : Tanggal Transaksi
* NP : Nama Pembeli
* HSB : Harga Satuan Barang
* JBT : Jumlah Barang Tersedia
* JBD : Jumlah Barang Dibeli
* THPB : Total Harga Per Barang

Data diatas merupakan data mentah atau bisa dibilang data diatas masih terdapat duplicate. Biar gampang, silahkan copy data tersebut ke libre office atau excel. Jika sudah kita akan membedakan data - data tersebut. Dari tabel diatas, bisa dilihat bahwa terdapat terdapat column - column yang doubel seperti nama barang, jenis barang, tanggal kadaluarsa, harga satuan barang dan jumlah barang yang tersedia. Column - column tersebut merupakan data barang, dimana data tersebut kita kelompokkan menjadi satu tabel, maka tabel barang akan menjadi seperti berikut.

| ID Barang | Nama Barang | Jenis Barang | Tanggal Kadaluarsa | Harga Satuan Barang | Jumlah Barang Tersedia |
|:----------|:------------|:-------------|:-------------------|:--------------------|:----------------------------|
| B01 | Rinso | Cair | 01-01-2016 | Rp 1000 | 10 |
| B02 | Baju | Padat | 01-02-2016 | Rp 2000 | 50 |
{: rules="groups"}

Pada tabel diatas kita menambahkan satu column yaitu id barang, id barang ditambahkan karena pada tabel sebelum nya belum terdapat primary key. Setelah selesai, langkah selanjutnya kita akan melakukan spesifikasi untuk tabel penjualan, berikut adalah bentuk tabel nya.

| Kode Transaksi Penjualan | Tanggal Transaksi | Nama Pembeli | Total Harga |
|:-------------------------|:------------------|:-------------|:------------|
| T01 | 02-02-2016 | Rizki | Rp 5000 |
| T02 | 02-02-2016 | Mufrizal | Rp 10000 |
{: rules="groups"}

Lagi - lagi penulis menambahkan sebuah column kode transaksi penjualan sebagai primary key. Tabel penjualan ini akan berisi mengenai data - data penjualan dalam sekali transaksi, akan tetapi di dalam sekali transaksi terdapat beberapa barang yang berbeda sehingga kita akan membuat tabel penjualan detail. Tabel penjualan detail ini akan memiliki relasi ke tabel penjualan dan tabel barang, dimana relasi tabel penjualan ke tabel penjualan detail memiliki relasi one to many sama seperti tabel barang dan tabel penjualan detail sehingga seluruh data akan konsisten dan mengurangi kerangkapan data. Berikut adalah tabel penjualan detail.

| Kode Transaksi Penjualan Detail | Jumlah Barang | Total Harga Per Barang | Kode Transaksi Penjualan | ID Barang |
|:--------------------------------|:--------------|:-----------------------|:-------------------------|:-----------|
| TD01 | 5 | Rp 5000 | T01 | B01 |
| TD02 | 5 | Rp 10000 | T01 | B02 |
| TD03 | 10 | Rp 10000 | T02 | B01 |
{: rules="groups"}

Dari tabel diatas terdapat 3 column yang penulis tambahkan yaitu column kode transaksi penjualan detail sebagai primary key, kode transaksi penjualan sebagai foreign key dan id barang sebagai foreign key juga. Berikut adalah tampilan ERD nya seperti berikut.

![Screenshot from 2016-03-26 14:07:44.png](../images/Screenshot from 2016-03-26 14:07:44.png)

Dari ERD diatas penulis membuat 2 garis yang berbeda yaitu ada yang tersambung dan ada garis putus - putus. Perbedaan nya adalah garis tersambung berfungsi sebagai parent child sehingga apabila orang tua nya atau tabel master dihapus maka tabel anak nya atau child nya juga akan dihapus yang sering disebut dengan `identifying relationship`. Berbeda dengan garis putus - putus, jika master tabel dihapus maka child tabel tidak akan dihapus.

Dari tabel diatas kita bisa melihat bahwa jika tabel penjualan dihapus maka secara otomatis si tabel penjualan detail akan dihapus, berbeda dengan tabel barang, jika tabel barang dihapus maka tabel penjualan detail tidak dihapus.

## Implementasi Pada H2 Database

>>[H2 Database](http://www.h2database.com/html/main.html) adalah salah satu dbms yang bisa kita gunakan sebagai database server maupun embedded database dan ditulis dengan menggunakan bahasa pemrograman java.

Pada tutorial ini, kita akan menggunakan h2 database untuk membuat relasi dengan menggunakan foreign key. Silahkan download h2 database di [h2 database](http://www.h2database.com/html/download.html). Penulis mendownload file binary yang ada pada bagian Maven (Binary, Javadoc, and Source), kemudian jalankan perintah berikut.

{% highlight bash %}
java -jar h2-1.4.191.jar
{% endhighlight %}

Maka secara otomatis browser akan terbuka dan melakukan akses web h2 database yang akan kita gunakan. Kemudian ubah jdbc url seperti berikut

{% highlight bash %}
jdbc:h2:~/database/belajar_h2
{% endhighlight %}

Kemudian klik connect, secara otomatis h2 database akan membuat database dengan nama belajar_h2.mv.db di dalam folder database. Tampilan web h2 database yang akan tampil seperti berikut.

![Screenshot from 2016-03-26 14:38:54.png](../images/Screenshot from 2016-03-26 14:38:54.png)

Langkah selanjutnya, untuk membuat tabel barang, silahkan jalankan perintah berikut pada web h2 database.

{% highlight sql %}
CREATE TABLE IF NOT EXISTS tb_barang(
    id_barang VARCHAR(150) NOT NULL PRIMARY KEY,
    nama_barang VARCHAR(45) NOT NULL,
    jenis_barang VARCHAR(45) NOT NULL,
    tanggal_kadaluarsa DATE NOT NULL,
    harga_satuan_barang DECIMAL(10) NOT NULL,
    jumlah_tersedia_barang INT(10) NOT NULL
);
{% endhighlight %}

Kemudian untuk tabel penjualan silahkan jalankan perintah berikut.

{% highlight sql %}
CREATE TABLE IF NOT EXISTS tb_penjualan(
    kode_transaksi_penjualan VARCHAR(150) NOT NULL PRIMARY KEY,
    tanggal_transaksi DATE NOT NULL,
    nama_pembeli VARCHAR(45) NOT NULL,
    total_harga DECIMAL(10) NOT NULL
);
{% endhighlight %}

Langkah selanjutnya adalah membuat tabel penjualan detail, silahkan jalankan perintah berikut.

{% highlight sql %}
CREATE TABLE IF NOT EXISTS tb_penjualan_detail(
    kode_transaksi_penjualan_detail VARCHAR(150) NOT NULL PRIMARY KEY,
    jumlah_barang INT(10) NOT NULL,
    total_harga_per_barang DECIMAL(10) NOT NULL,
    kode_transaksi_penjualan VARCHAR(150) NOT NULL,
    id_barang VARCHAR(150) NOT NULL,
    FOREIGN KEY(kode_transaksi_penjualan) REFERENCES tb_penjualan(kode_transaksi_penjualan) ON DELETE CASCADE ON UPDATE CASCADE,
    FOREIGN KEY(id_barang) REFERENCES tb_barang(id_barang)
);
{% endhighlight %}

Untuk dapat mengenerate ERD dari tabel yang telah dibuat maka kita akan menggunakan [Execute Query](http://executequery.org/index.php). Silahkan download aplikasi tersebut, jika sudah langsung buka aplikasi tersebut. Silahkan lakukan konfigurasi driver h2 database, setelah selesai, lakukan konfigurasi seperti berikut.

![Screenshot from 2016-03-26 15:46:35.png](../images/Screenshot from 2016-03-26 15:46:35.png)

Lalu klik connect, silahkan klik nama databasenya kemudian pilih menu database dan pilih generate ERD lalu pilih map existing database maka akan muncul seperti berikut.

![Screenshot from 2016-03-26 15:50:17.png](../images/Screenshot from 2016-03-26 15:50:17.png)

Kemudian pilih schema menjadi public, lalu pilih semua tabel dan pilih select all, maka outputnya akan seperti berikut.

![Screenshot from 2016-03-26 16:03:03.png](../images/Screenshot from 2016-03-26 16:03:03.png)

Setelah selesai, silahkan klik generate. berikut adalah output yang dihasilkan.

![Screenshot from 2016-03-26 16:09:24.png](../images/Screenshot from 2016-03-26 16:09:24.png)

Sekian artikel mengenai belajar membuat foreign key pada h2 database dan terima kasih :).


text:
<?php

declare(strict_types=1);

namespace OAuth2Framework\Component\Server\Endpoint\Authorization\BeforeConsentScreen;

use OAuth2Framework\Component\Server\Endpoint\Authorization\Authorization;
use Psr\Http\Message\ServerRequestInterface;

final class BeforeConsentScreenManager
{
    /**
     * @var BeforeConsentScreenInterface[]
     */
    private $extensions = [];

    /**
     * @param BeforeConsentScreenInterface $extension
     */
    public function add(BeforeConsentScreenInterface $extension)
    {
        $this->extensions[] = $extension;
    }

    /**
     * @param ServerRequestInterface $request
     * @param Authorization          $authorization
     *
     * @return Authorization
     */
    public function process(ServerRequestInterface $request, Authorization $authorization): Authorization
    {
        foreach ($this->extensions as $extension) {
            $authorization = $extension->process($request, $authorization);
        }

        return $authorization;
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace app {
namespace Uno {
namespace Collections {

// This file was generated based on 'C:\ProgramData\Uno\Packages\UnoCore\0.13.2\Source\Uno\Collections\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.

Dictionary2_Bucket__char__Uno_Content_Fonts_BitmapFont_GlyphInfo__uType* Dictionary2_Bucket__char__Uno_Content_Fonts_BitmapFont_GlyphInfo__typeof()
{
    static ::uStaticStrong<Dictionary2_Bucket__char__Uno_Content_Fonts_BitmapFont_GlyphInfo__uType*> type;
    if (type != NULL) return type;

    type = (Dictionary2_Bucket__char__Uno_Content_Fonts_BitmapFont_GlyphInfo__uType*)::uAllocStructType(sizeof(Dictionary2_Bucket__char__Uno_Content_Fonts_BitmapFont_GlyphInfo__uType), "Uno.Collections.Dictionary2_Bucket<char,Uno.Content.Fonts.BitmapFont_GlyphInfo>", sizeof(Dictionary2_Bucket__char__Uno_Content_Fonts_BitmapFont_GlyphInfo), 0, 0, 0);

    return type;
}

// This file was generated based on 'C:\ProgramData\Uno\Packages\UnoCore\0.13.2\Source\Uno\Collections\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.

Dictionary2_Bucket__Fuse_Controls_Internal_DefaultTextRenderer_FontKey__Uno_Content_Fonts_BitmapFont__uType* Dictionary2_Bucket__Fuse_Controls_Internal_DefaultTextRenderer_FontKey__Uno_Content_Fonts_BitmapFont__typeof()
{
    static ::uStaticStrong<Dictionary2_Bucket__Fuse_Controls_Internal_DefaultTextRenderer_FontKey__Uno_Content_Fonts_BitmapFont__uType*> type;
    if (type != NULL) return type;

    type = (Dictionary2_Bucket__Fuse_Controls_Internal_DefaultTextRenderer_FontKey__Uno_Content_Fonts_BitmapFont__uType*)::uAllocStructType(sizeof(Dictionary2_Bucket__Fuse_Controls_Internal_DefaultTextRenderer_FontKey__Uno_Content_Fonts_BitmapFont__uType), "Uno.Collections.Dictionary2_Bucket<Fuse.Controls.Internal.DefaultTextRenderer_FontKey,Uno.Content.Fonts.BitmapFont>", sizeof(Dictionary2_Bucket__Fuse_Controls_Internal_DefaultTextRenderer_FontKey__Uno_Content_Fonts_BitmapFont), 0, 2, 0);

    type->SetStrongRefs(
        "Key", offsetof(Dictionary2_Bucket__Fuse_Controls_Internal_DefaultTextRenderer_FontKey__Uno_Content_Fonts_BitmapFont, Key),
        "Value", offsetof(Dictionary2_Bucket__Fuse_Controls_Internal_DefaultTextRenderer_FontKey__Uno_Content_Fonts_BitmapFont, Value));

    return type;
}

// This file was generated based on 'C:\ProgramData\Uno\Packages\UnoCore\0.13.2\Source\Uno\Collections\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.

Dictionary2_Bucket__int__Fuse_Input_Pointer_PointerRecord__uType* Dictionary2_Bucket__int__Fuse_Input_Pointer_PointerRecord__typeof()
{
    static ::uStaticStrong<Dictionary2_Bucket__int__Fuse_Input_Pointer_PointerRecord__uType*> type;
    if (type != NULL) return type;

    type = (Dictionary2_Bucket__int__Fuse_Input_Pointer_PointerRecord__uType*)::uAllocStructType(sizeof(Dictionary2_Bucket__int__Fuse_Input_Pointer_PointerRecord__uType), "Uno.Collections.Dictionary2_Bucket<int,Fuse.Input.Pointer_PointerRecord>", sizeof(Dictionary2_Bucket__int__Fuse_Input_Pointer_PointerRecord), 0, 1, 0);

    type->SetStrongRefs(
        "Value", offsetof(Dictionary2_Bucket__int__Fuse_Input_Pointer_PointerRecord, Value));

    return type;
}

// This file was generated based on 'C:\ProgramData\Uno\Packages\UnoCore\0.13.2\Source\Uno\Collections\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.

Dictionary2_Bucket__int__Uno_Collections_List_Fuse_Input_Pointer_PELHolder___uType* Dictionary2_Bucket__int__Uno_Collections_List_Fuse_Input_Pointer_PELHolder___typeof()
{
    static ::uStaticStrong<Dictionary2_Bucket__int__Uno_Collections_List_Fuse_Input_Pointer_PELHolder___uType*> type;
    if (type != NULL) return type;

    type = (Dictionary2_Bucket__int__Uno_Collections_List_Fuse_Input_Pointer_PELHolder___uType*)::uAllocStructType(sizeof(Dictionary2_Bucket__int__Uno_Collections_List_Fuse_Input_Pointer_PELHolder___uType), "Uno.Collections.Dictionary2_Bucket<int,Uno.Collections.List<Fuse.Input.Pointer_PELHolder>>", sizeof(Dictionary2_Bucket__int__Uno_Collections_List_Fuse_Input_Pointer_PELHolder_), 0, 1, 0);

    type->SetStrongRefs(
        "Value", offsetof(Dictionary2_Bucket__int__Uno_Collections_List_Fuse_Input_Pointer_PELHolder_, Value));

    return type;
}

// This file was generated based on 'C:\ProgramData\Uno\Packages\UnoCore\0.13.2\Source\Uno\Collections\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.

Dictionary2_Bucket__Uno_Content_Fonts_BitmapFont_CharPair__float__uType* Dictionary2_Bucket__Uno_Content_Fonts_BitmapFont_CharPair__float__typeof()
{
    static ::uStaticStrong<Dictionary2_Bucket__Uno_Content_Fonts_BitmapFont_CharPair__float__uType*> type;
    if (type != NULL) return type;

    type = (Dictionary2_Bucket__Uno_Content_Fonts_BitmapFont_CharPair__float__uType*)::uAllocStructType(sizeof(Dictionary2_Bucket__Uno_Content_Fonts_BitmapFont_CharPair__float__uType), "Uno.Collections.Dictionary2_Bucket<Uno.Content.Fonts.BitmapFont_CharPair,float>", sizeof(Dictionary2_Bucket__Uno_Content_Fonts_BitmapFont_CharPair__float), 0, 0, 0);

    return type;
}

}}}


text:
<?php

namespace ApiBundle\Entity;

use ApiBundle\Mixin\Labelisable;
use Doctrine\ORM\Mapping as ORM;
use ApiBundle\Mixin\BlameableEntity;
use JMS\Serializer\Annotation as JMS;

/**
 * Article
 *
 * @ORM\Table(name="article")
 * @ORM\Entity(repositoryClass="ApiBundle\Repository\ArticleRepository")
 */
class Article
{

    use Labelisable;
    use BlameableEntity;
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     * @JMS\Groups({"getArticles"})
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text")
     * @JMS\Groups({"getArticles"})
     * @JMS\SerializedName("desc")
     */
    private $description;

    /**
     * @ORM\ManyToOne(targetEntity="Categorie", inversedBy="articles")
     * @ORM\JoinColumn(nullable=false)
     */
    private $categorie;

    /**
     * @var float
     *
     * @ORM\Column(name="prix", type="float")
     * @JMS\Groups({"getArticles"})
     */
    private $prix;

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

    /**
     * Set description
     *
     * @param string $description
     *
     * @return Article
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

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

    /**
     * @param mixed $category
     * @return Article
     */
    public function setCategorie($categorie)
    {
        $this->categorie = $categorie;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getCategorie()
    {
        return $this->categorie;
    }

    /**
     * @JMS\VirtualProperty()
     * @JMS\SerializedName("cat")
     * @JMS\Groups({"getArticles"})
     */
    public function getIdCategorie() {
        return $this->getCategorie()->getId();
    }

    /**
     * Set prix
     *
     * @param float $prix
     *
     * @return Article
     */
    public function setPrix($prix)
    {
        $this->prix = $prix;

        return $this;
    }

    /**
     * Get prix
     *
     * @return float
     */
    public function getPrix()
    {
        return $this->prix;
    }
}


text:
@interface TGLoginInactiveUserController ()
{
    UIView *_navigationBarBackgroundView;
    UIView *_stripeView;
}

@property (nonatomic, strong) TGProgressWindow *progressWindow;

@property (nonatomic, strong) TGUser *user;

@property (nonatomic, strong) UIView *interfaceContainer;
@property (nonatomic, strong) UIView *accessDisabledContainer;

@property (nonatomic, strong) TGLetteredAvatarView *avatarView;

@property (nonatomic, strong) UIImage *uploadingAvatarImage;

@property (nonatomic, strong) UIView *titleContainer;
@property (nonatomic, strong) UILabel *titleStatusLabel;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIActivityIndicatorView *titleStatusIndicator;

@end

@implementation TGLoginInactiveUserController

- (id)init
{
    self = [super initWithNibName:nil bundle:nil];
    if (self)
    {
        self.style = TGViewControllerStyleBlack;

        _actionHandle = [[ASHandle alloc] initWithDelegate:self releaseOnMainThread:true];

        [ActionStageInstance() watchForPath:@"/tg/activation" watcher:self];
        [ActionStageInstance() watchForPath:@"/tg/contactListSynchronizationState" watcher:self];
        [ActionStageInstance() watchForPath:@"/tg/removeAndExportActionsRunning" watcher:self];
    }
    return self;
}

- (void)dealloc
{
    [_actionHandle reset];
    [ActionStageInstance() removeWatcher:self];
}

- (void)_loadStatusViews
{
    if (_titleStatusLabel == nil)
    {
        _titleStatusLabel = [[UILabel alloc] init];
        _titleStatusLabel.clipsToBounds = false;
        _titleStatusLabel.backgroundColor = [UIColor clearColor];
        _titleStatusLabel.textColor = [UIColor blackColor];
        _titleStatusLabel.font = TGBoldSystemFontOfSize(16.0f);
        _titleStatusLabel.text = TGLocalized(@"State.Updating");
        _titleStatusLabel.hidden = true;
        [_titleStatusLabel sizeToFit];
        [_titleContainer addSubview:_titleStatusLabel];

        _titleStatusIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _titleStatusIndicator.hidden = true;
        [_titleContainer addSubview:_titleStatusIndicator];
    }
}

- (void)setUpdating:(bool)updating
{
    if (updating)
    {
        _titleLabel.hidden = true;
        _titleStatusLabel.hidden = false;
        _titleStatusIndicator.hidden = false;
        [_titleStatusIndicator startAnimating];
    }
    else
    {
        _titleLabel.hidden = false;
        _titleStatusLabel.hidden = true;
        _titleStatusIndicator.hidden = true;
        [_titleStatusIndicator stopAnimating];
    }
}

- (void)loadView
{
    [super loadView];

    CGSize screenSize = [TGViewController screenSizeForInterfaceOrientation:UIInterfaceOrientationPortrait];
    bool isWidescreen = [TGViewController isWidescreen];

    self.view.backgroundColor = [UIColor whiteColor];

    _titleContainer = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 2.0f, 2.0f)];
    [self setTitleView:_titleContainer];
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.backgroundColor = [UIColor clearColor];
    _titleLabel.textColor = [UIColor blackColor];
    _titleLabel.font = TGBoldSystemFontOfSize(17.0f);
    _titleLabel.text = TGLocalized(@"WelcomeScreen.Title");
    [_titleLabel sizeToFit];
    [_titleContainer addSubview:_titleLabel];
    [self _loadStatusViews];
    [self _layoutTitleViews:self.interfaceOrientation];

    [self setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:TGLocalized(@"WelcomeScreen.Logout") style:UIBarButtonItemStylePlain target:self action:@selector(logoutButtonPressed)]];

    CGFloat containerHeight = TGIsPad() ? 568.0f : ([TGViewController screenSizeForInterfaceOrientation:UIInterfaceOrientationPortrait].height);
    _interfaceContainer = [[UIView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 320.0f) / 2.0f, ((self.view.frame.size.height - containerHeight) / 2.0f), 320.0f, containerHeight)];
    [self.view addSubview:_interfaceContainer];

    if (_user == nil)
        _user = [TGDatabaseInstance() loadUser:TGTelegraphInstance.clientUserId];

    _avatarView = [[TGLetteredAvatarView alloc] initWithFrame:CGRectMake(CGFloor((_interfaceContainer.frame.size.width - 110) / 2.0f), isWidescreen ? 120 : 90, 110, 110)];
    [_avatarView setSingleFontSize:40.0f doubleFontSize:40.0f useBoldFont:false];
    _avatarView.fadeTransition = true;
    [_interfaceContainer addSubview:_avatarView];

    static UIImage *placeholder = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^
    {
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(110, 110), false, 0.0f);
        CGContextRef context = UIGraphicsGetCurrentContext();

        //!placeholder
        CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
        CGContextFillEllipseInRect(context, CGRectMake(0.0f, 0.0f, 110, 110));
        CGContextSetStrokeColorWithColor(context, UIColorRGB(0xd9d9d9).CGColor);
        CGContextSetLineWidth(context, 1.0f);
        CGContextStrokeEllipseInRect(context, CGRectMake(0.5f, 0.5f, 109, 109));

        placeholder = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    });

    [_avatarView loadUserPlaceholderWithSize:CGSizeMake(80.0f, 80.0f) uid:_user.uid firstName:_user.firstName lastName:_user.lastName placeholder:placeholder];

    UILabel *greetingLabel = [[UILabel alloc] init];
    greetingLabel.backgroundColor = [UIColor clearColor];
    greetingLabel.textColor = [UIColor blackColor];
    greetingLabel.font = TGLightSystemFontOfSize(29.0f);
    greetingLabel.text = [[NSString alloc] initWithFormat:TGLocalized(@"WelcomeScreen.Greeting"), _user.displayFirstName];
    [greetingLabel sizeToFit];
    greetingLabel.frame = CGRectMake(CGFloor((_interfaceContainer.frame.size.width - greetingLabel.frame.size.width) / 2.0f), isWidescreen ? 256.0f : 220.0f, greetingLabel.frame.size.width, greetingLabel.frame.size.height);
    [_interfaceContainer addSubview:greetingLabel];

    UILabel *noticeLabel = [[UILabel alloc] init];
    noticeLabel.backgroundColor = [UIColor clearColor];
    noticeLabel.textColor = [UIColor blackColor];
    noticeLabel.font = TGSystemFontOfSize(17.0f);
    noticeLabel.textAlignment = NSTextAlignmentCenter;
    noticeLabel.numberOfLines = 0;
    noticeLabel.lineBreakMode = NSLineBreakByWordWrapping;

    NSString *text = TGLocalized(@"Login.InactiveHelp");

    if ([noticeLabel respondsToSelector:@selector(setAttributedText:)])
    {
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        style.lineSpacing = 5;
        style.lineBreakMode = NSLineBreakByWordWrapping;
        style.alignment = NSTextAlignmentCenter;

        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text attributes:@{
            NSFontAttributeName: noticeLabel.font,
            NSForegroundColorAttributeName: noticeLabel.textColor
        }];

        [attributedString addAttributes:@{NSParagraphStyleAttributeName: style} range:NSMakeRange(0, attributedString.length)];

        NSRange range = [text rangeOfString:@"Telegram"];
        if (range.location != NSNotFound)
            [attributedString addAttributes:@{NSFontAttributeName: TGMediumSystemFontOfSize(17.0f)} range:range];
        noticeLabel.attributedText = attributedString;
    }
    else
        noticeLabel.text = text;

    CGSize textSize = [noticeLabel sizeThatFits:CGSizeMake(_interfaceContainer.frame.size.width - 20, CGFLOAT_MAX)];
    noticeLabel.frame = CGRectMake(CGFloor((_interfaceContainer.frame.size.width - textSize.width) / 2), isWidescreen ? 302 : 280, textSize.width, textSize.height);
    [_interfaceContainer addSubview:noticeLabel];

    TGModernButton *startButton = [[TGModernButton alloc] init];
    startButton.backgroundColor = [UIColor clearColor];
    [startButton setTitleColor:TGAccentColor()];
    startButton.titleLabel.font = TGSystemFontOfSize(21.0f);
    [startButton setTitle:TGLocalized(@"Login.InviteButton") forState:UIControlStateNormal];
    [startButton setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 20.0f)];
    [startButton sizeToFit];
    CGSize buttonSize = startButton.frame.size;
    startButton.frame = CGRectMake(CGFloor((_interfaceContainer.frame.size.width - buttonSize.width) / 2.0f) + 10.0f, isWidescreen ? 430.0f : 400.0f, buttonSize.width, buttonSize.height + 20.0f);

    UIImageView *arrowView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ModernTourButtonRightArrow.png"]];
    CGSize arrowSize = arrowView.frame.size;
    arrowView.frame = CGRectMake(startButton.frame.size.width - arrowSize.width, CGFloor((startButton.frame.size.height - arrowView.frame.size.height) / 2.0f) + 2.0f + TGRetinaPixel, arrowSize.width, arrowSize.height);

    [startButton addSubview:arrowView];
    [startButton addTarget:self action:@selector(inviteButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [_interfaceContainer addSubview:startButton];

    _navigationBarBackgroundView = [TGBackdropView viewWithLightNavigationBarStyle];
    _navigationBarBackgroundView.frame = CGRectMake(0.0f, 0.0f, screenSize.width, 20 + 44);
    [self.view addSubview:_navigationBarBackgroundView];

    _stripeView = [[UIView alloc] init];
    _stripeView.frame = CGRectMake(0.0f, _navigationBarBackgroundView.frame.size.height - (TGIsRetina() ? 0.5f : 1.0f), screenSize.width, TGIsRetina() ? 0.5f : 1.0f);
    _stripeView.backgroundColor = UIColorRGB(0xb2b2b2);
    _stripeView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [_navigationBarBackgroundView addSubview:_stripeView];

    if (![self _updateControllerInset:false])
        [self controllerInsetUpdated:UIEdgeInsetsZero];

    [self updateInterface:self.interfaceOrientation];
}

- (void)doUnloadView
{

}

- (void)viewDidUnload
{
    [self doUnloadView];

    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self rejoinActions];

    [self updateAccessStatus];

    [super viewWillAppear:animated];

    [self updateInterface:self.interfaceOrientation];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];

    [self updateInterface:toInterfaceOrientation];
}

- (void)viewDidAppear:(BOOL)animated
{
    if (self.navigationController.viewControllers.count > 2)
    {
        NSArray *newViewControllers = [[NSArray alloc] initWithObjects:[self.navigationController.viewControllers objectAtIndex:0], [self.navigationController.viewControllers lastObject], nil];
        [self.navigationController setViewControllers:newViewControllers animated:false];
    }

    [super viewDidAppear:animated];
}

- (void)rejoinActions
{
    if (_uploadingAvatarImage == nil)
    {
        [ActionStageInstance() dispatchOnStageQueue:^
        {
            NSArray *uploadActions = [ActionStageInstance() rejoinActionsWithGenericPathNow:@"/tg/timeline/@/uploadPhoto/@" prefix:[[NSString alloc] initWithFormat:@"/tg/timeline/(%d)", TGTelegraphInstance.clientUserId] watcher:self];

            if (uploadActions.count != 0)
            {
                UIImage *uploadingAvatar = nil;
                if (uploadActions.count != 0)
                {
                    uploadingAvatar = ((TGTimelineUploadPhotoRequestBuilder *)[ActionStageInstance() executingActorWithPath:uploadActions.lastObject]).currentLoginBigPhoto;
                }

                dispatch_async(dispatch_get_main_queue(), ^
                {
                    _uploadingAvatarImage = uploadingAvatar;
                    [_avatarView loadImage:_uploadingAvatarImage];
                });
            }
        }];
    }
}

- (UIView *)accessDisabledContainer
{
    if (_accessDisabledContainer == nil)
    {
        float topOffset = 30;

        float titleY = topOffset + ([TGViewController isWidescreen] ? 205 : 190);

        CGFloat containerHeight = TGIsPad() ? 568.0f : ([TGViewController screenSizeForInterfaceOrientation:UIInterfaceOrientationPortrait].height);

        _accessDisabledContainer = [[UIView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 320.0f) / 2.0f, ((self.view.frame.size.height - containerHeight) / 2.0f), 320.0f, containerHeight)];
        [self.view addSubview:_accessDisabledContainer];

        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.font = TGSystemFontOfSize(18);
        titleLabel.textColor = UIColorRGB(0x999999);
        [_accessDisabledContainer addSubview:titleLabel];

        titleLabel.text = TGLocalized(@"WelcomeScreen.ContactsAccessDisabled");
        [titleLabel sizeToFit];
        titleLabel.frame = CGRectOffset(titleLabel.frame, floorf((_accessDisabledContainer.frame.size.width - titleLabel.frame.size.width) / 2), titleY);

        UILabel *noticeLabel = [[UILabel alloc] init];
        noticeLabel.font = TGSystemFontOfSize(16);
        noticeLabel.textColor = UIColorRGB(0x999999);
        noticeLabel.text = TGLocalized(@"Login.InactiveHelp");
        noticeLabel.backgroundColor = [UIColor clearColor];
        noticeLabel.lineBreakMode = NSLineBreakByWordWrapping;
        noticeLabel.textAlignment = NSTextAlignmentCenter;
        noticeLabel.contentMode = UIViewContentModeCenter;
        noticeLabel.numberOfLines = 0;

        NSString *model = @"iPhone";
        NSString *rawModel = [[[UIDevice currentDevice] model] lowercaseString];
        if ([rawModel rangeOfString:@"ipod"].location != NSNotFound)
            model = @"iPod";
        else if ([rawModel rangeOfString:@"ipad"].location != NSNotFound)
            model = @"iPad";

        NSString *baseText = [[NSString alloc] initWithFormat:TGLocalized(@"WelcomeScreen.ContactsAccessHelp"), model];

        if ([UILabel instancesRespondToSelector:@selector(setAttributedText:)])
        {
            UIColor *foregroundColor = UIColorRGB(0x999999);

            NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, foregroundColor, NSForegroundColorAttributeName, nil];
            NSDictionary *subAttrs = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:14], NSFontAttributeName, nil];
            const NSRange range = [baseText rangeOfString:TGLocalized(@"WelcomeScreen.ContactsAccessSettings")];

            NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:baseText attributes:attrs];
            [attributedText setAttributes:subAttrs range:range];

            [noticeLabel setAttributedText:attributedText];
        }
        else
        {
            noticeLabel.text = baseText;
        }
        CGSize size = [noticeLabel sizeThatFits:CGSizeMake(270, 1024)];
        noticeLabel.frame = CGRectMake(floorf((_accessDisabledContainer.frame.size.width - size.width) / 2), titleY + 34, size.width, size.height);
        [_accessDisabledContainer addSubview:noticeLabel];

        [self updateInterface:self.interfaceOrientation];
    }

    return _accessDisabledContainer;
}

- (void)updateAccessStatus
{
    TGPhonebookAccessStatus accessStatus = [TGSynchronizeContactsManager instance].phonebookAccessStatus;

    dispatch_async(dispatch_get_main_queue(), ^
    {
        if (accessStatus == TGPhonebookAccessStatusDisabled)
        {
            _interfaceContainer.hidden = true;
            self.accessDisabledContainer.hidden = false;
        }
        else
        {
            _interfaceContainer.hidden = false;
            _accessDisabledContainer.hidden = true;
        }
    });
}

- (void)updateSynchronizationStatus
{
    bool updating = [TGSynchronizeContactsManager instance].contactsSynchronizationStatus;
    bool exporting = [TGSynchronizeContactsManager instance].removeAndExportActionsRunning;

    dispatch_async(dispatch_get_main_queue(), ^
    {
        if (updating || exporting)
        {
            [self setUpdating:true];
        }
        else
        {
            [self setUpdating:false];
        }
    });
}

- (void)controllerInsetUpdated:(UIEdgeInsets)previousInset
{
    [super controllerInsetUpdated:previousInset];

    _navigationBarBackgroundView.frame = CGRectMake(0.0f, self.controllerInset.top - (44 + 20), self.view.frame.size.width, 20 + 44);
}

#pragma mark -

- (void)logoutButtonPressed
{
    _progressWindow = [[TGProgressWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [_progressWindow show:true];

    [ActionStageInstance() requestActor:[NSString stringWithFormat:@"/tg/auth/logout/(%d)", TGTelegraphInstance.clientUserId] options:nil watcher:self];
}

- (void)inviteButtonPressed
{
    TGContactsController *contactsController = [[TGContactsController alloc] initWithContactsMode:TGContactsModeInvite | TGContactsModeModalInvite | TGContactsModeModalInviteWithBack];
    contactsController.loginStyle = true;
    contactsController.watcherHandle = _actionHandle;
    contactsController.drawFakeNavigationBar = true;
    [self.navigationController pushViewController:contactsController animated:true];
}

#pragma mark -

- (void)actionStageResourceDispatched:(NSString *)path resource:(id)resource arguments:(id)__unused arguments
{
    if ([path isEqualToString:@"/tg/activation"])
    {
        dispatch_async(dispatch_get_main_queue(), ^
        {
            if ([((SGraphObjectNode *)resource).object boolValue])
                [TGAppDelegateInstance presentMainController];
        });
    }
    else if ([path isEqualToString:@"/tg/contactListSynchronizationState"])
    {
        if (![((SGraphObjectNode *)resource).object boolValue])
        {
            bool activated = [TGDatabaseInstance() haveRemoteContactUids];

            dispatch_async(dispatch_get_main_queue(), ^
            {
                if (activated)
                    [TGAppDelegateInstance presentMainController];
            });
        }
        else
        {

        }

        [self updateSynchronizationStatus];
        [self updateAccessStatus];
    }
    else if ([path isEqualToString:@"/tg/removeAndExportActionsRunning"])
    {
        [self updateSynchronizationStatus];
    }
}

- (void)actorCompleted:(int)resultCode path:(NSString *)path result:(id)__unused result
{
    if ([path hasPrefix:@"/tg/auth/logout/"])
    {
        dispatch_async(dispatch_get_main_queue(), ^
        {
            [_progressWindow dismiss:true];
            _progressWindow = nil;

            if (resultCode != ASStatusSuccess)
            {
                [[[TGAlertView alloc] initWithTitle:nil message:@"An error occured" delegate:nil cancelButtonTitle:TGLocalized(@"Common.OK") otherButtonTitles:nil] show];
            }

            [self.navigationController popToRootViewControllerAnimated:true];
        });
    }
}

- (void)_layoutTitleViews:(UIInterfaceOrientation)orientation
{
    CGFloat portraitOffset = 0.0f;
    CGFloat landscapeOffset = 0.0f;
    CGFloat indicatorOffset = 0.0f;
    if (iosMajorVersion() >= 7)
    {
        portraitOffset = 1.0f;
        landscapeOffset = 0.0f;
        indicatorOffset = -1.0f;
    }
    else
    {
        portraitOffset = -1.0f;
        landscapeOffset = 1.0f;
        indicatorOffset = 0.0f;
    }

    CGRect titleLabelFrame = _titleLabel.frame;
    titleLabelFrame.origin = CGPointMake(CGFloor((_titleContainer.frame.size.width - titleLabelFrame.size.width) / 2.0f), CGFloor((_titleContainer.frame.size.height - titleLabelFrame.size.height) / 2.0f) + (UIInterfaceOrientationIsPortrait(orientation) ? portraitOffset : landscapeOffset));
    _titleLabel.frame = titleLabelFrame;

    if (_titleStatusLabel != nil)
    {
        CGRect titleStatusLabelFrame = _titleStatusLabel.frame;
        titleStatusLabelFrame.origin = CGPointMake(CGFloor((_titleContainer.frame.size.width - titleStatusLabelFrame.size.width) / 2.0f) + 16.0f, CGFloor((_titleContainer.frame.size.height - titleStatusLabelFrame.size.height) / 2.0f) + (UIInterfaceOrientationIsPortrait(orientation) ? portraitOffset : landscapeOffset));
        _titleStatusLabel.frame = titleStatusLabelFrame;

        CGRect titleIndicatorFrame = _titleStatusIndicator.frame;
        titleIndicatorFrame.origin = CGPointMake(titleStatusLabelFrame.origin.x - titleIndicatorFrame.size.width - 4.0f, titleStatusLabelFrame.origin.y  + indicatorOffset);
        _titleStatusIndicator.frame = titleIndicatorFrame;
    }
}

- (void)updateInterface:(UIInterfaceOrientation)orientation
{
    CGSize screenSize = [TGViewController screenSizeForInterfaceOrientation:orientation];

    _navigationBarBackgroundView.frame = CGRectMake(0.0f, 0.0f, screenSize.width, 20 + 44);
    _stripeView.frame = CGRectMake(0.0f, _navigationBarBackgroundView.frame.size.height - (TGIsRetina() ? 0.5f : 1.0f), screenSize.width, TGIsRetina() ? 0.5f : 1.0f);

    _interfaceContainer.frame = CGRectMake(CGFloor((screenSize.width - _interfaceContainer.frame.size.width) / 2.0f), CGFloor((screenSize.height - _interfaceContainer.frame.size.height) / 2.0f), _interfaceContainer.frame.size.width, _interfaceContainer.frame.size.height);

    _accessDisabledContainer.frame = CGRectMake(CGFloor((screenSize.width - _accessDisabledContainer.frame.size.width) / 2.0f), CGFloor((screenSize.height - _accessDisabledContainer.frame.size.height) / 2.0f), _accessDisabledContainer.frame.size.width, _accessDisabledContainer.frame.size.height);
}

@end


text:
package io.gatling.core.action

import io.gatling.BaseSpec
import io.gatling.core.EmptySession
import io.gatling.core.session.Session

class ActionSpec extends BaseSpec with EmptySession {
  class TestAction extends Action {
    var hasRun = false

    override val name = "test"
    override def execute(session: Session): Unit = hasRun = true
  }

  "An Action" should "call the execute method when receiving a Session" in {
    val testAction = new TestAction

    testAction.hasRun shouldBe false
    testAction ! emptySession
    testAction.hasRun shouldBe true
  }
}


text:
import socket
import sys

#check the number of arguments
if len(sys.argv) != 4:
    print("The number of arguments is invalid")
else:
    host = sys.argv[1]
    portnum = 5555;

    #make the connection to server
    clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    clientsocket.connect((host,portnum))
    #send message
    clientsocket.send(sys.argv[2]+"\r\n")
    clientsocket.send(sys.argv[3]+"\r\n")

    #quit
    clientsocket.close()
    print("Done!")


text:
var FCKSpecialCombo = function( caption, fieldWidth, panelWidth, panelMaxHeight, parentWindow )
{
	// Default properties values.
	this.FieldWidth		= fieldWidth || 100 ;
	this.PanelWidth		= panelWidth || 150 ;
	this.PanelMaxHeight	= panelMaxHeight || 150 ;
	this.Label			= ' ' ;
	this.Caption		= caption ;
	this.Tooltip		= caption ;
	this.Style			= FCK_TOOLBARITEM_ICONTEXT ;

	this.Enabled = true ;

	this.Items = new Object() ;

	this._Panel = new FCKPanel( parentWindow || window ) ;
	this._Panel.AppendStyleSheet( FCKConfig.SkinEditorCSS ) ;
	this._PanelBox = this._Panel.MainNode.appendChild( this._Panel.Document.createElement( 'DIV' ) ) ;
	this._PanelBox.className = 'SC_Panel' ;
	this._PanelBox.style.width = this.PanelWidth + 'px' ;

	this._PanelBox.innerHTML = '

' ;

	this._ItemsHolderEl = this._PanelBox.getElementsByTagName('TD')[0] ;

	if ( FCK.IECleanup )
		FCK.IECleanup.AddItem( this, FCKSpecialCombo_Cleanup ) ;

//	this._Panel.StyleSheet = FCKConfig.SkinPath + 'fck_contextmenu.css' ;
//	this._Panel.Create() ;
//	this._Panel.PanelDiv.className += ' SC_Panel' ;
//	this._Panel.PanelDiv.innerHTML = '

' ;
//	this._ItemsHolderEl = this._Panel.PanelDiv.getElementsByTagName('TD')[0] ;
}

function FCKSpecialCombo_ItemOnMouseOver()
{
	this.className += ' SC_ItemOver' ;
}

function FCKSpecialCombo_ItemOnMouseOut()
{
	this.className = this.originalClass ;
}

function FCKSpecialCombo_ItemOnClick( ev, specialCombo, itemId )
{
	this.className = this.originalClass ;

	specialCombo._Panel.Hide() ;

	specialCombo.SetLabel( this.FCKItemLabel ) ;

	if ( typeof( specialCombo.OnSelect ) == 'function' )
		specialCombo.OnSelect( itemId, this ) ;
}

FCKSpecialCombo.prototype.ClearItems = function ()
{
	if ( this.Items )
		this.Items = {} ;

	var itemsholder = this._ItemsHolderEl ;
	while ( itemsholder.firstChild )
		itemsholder.removeChild( itemsholder.firstChild ) ;
}

FCKSpecialCombo.prototype.AddItem = function( id, html, label, bgColor )
{
	//
Bold 1

	var oDiv = this._ItemsHolderEl.appendChild( this._Panel.Document.createElement( 'DIV' ) ) ;
	oDiv.className = oDiv.originalClass = 'SC_Item' ;
	oDiv.innerHTML = html ;
	oDiv.FCKItemLabel = label || id ;
	oDiv.Selected = false ;

	// In IE, the width must be set so the borders are shown correctly when the content overflows.
	if ( FCKBrowserInfo.IsIE )
		oDiv.style.width = '100%' ;

	if ( bgColor )
		oDiv.style.backgroundColor = bgColor ;

	FCKTools.AddEventListenerEx( oDiv, 'mouseover', FCKSpecialCombo_ItemOnMouseOver ) ;
	FCKTools.AddEventListenerEx( oDiv, 'mouseout', FCKSpecialCombo_ItemOnMouseOut ) ;
	FCKTools.AddEventListenerEx( oDiv, 'click', FCKSpecialCombo_ItemOnClick, [ this, id ] ) ;

	this.Items[ id.toString().toLowerCase() ] = oDiv ;

	return oDiv ;
}

FCKSpecialCombo.prototype.SelectItem = function( item )
{
	if ( typeof item == 'string' )
		item = this.Items[ item.toString().toLowerCase() ] ;

	if ( item )
	{
		item.className = item.originalClass = 'SC_ItemSelected' ;
		item.Selected = true ;
	}
}

FCKSpecialCombo.prototype.SelectItemByLabel = function( itemLabel, setLabel )
{
	for ( var id in this.Items )
	{
		var oDiv = this.Items[id] ;

		if ( oDiv.FCKItemLabel == itemLabel )
		{
			oDiv.className = oDiv.originalClass = 'SC_ItemSelected' ;
			oDiv.Selected = true ;

			if ( setLabel )
				this.SetLabel( itemLabel ) ;
		}
	}
}

FCKSpecialCombo.prototype.DeselectAll = function( clearLabel )
{
	for ( var i in this.Items )
	{
		if ( !this.Items[i] ) continue;
		this.Items[i].className = this.Items[i].originalClass = 'SC_Item' ;
		this.Items[i].Selected = false ;
	}

	if ( clearLabel )
		this.SetLabel( '' ) ;
}

FCKSpecialCombo.prototype.SetLabelById = function( id )
{
	id = id ? id.toString().toLowerCase() : '' ;

	var oDiv = this.Items[ id ] ;
	this.SetLabel( oDiv ? oDiv.FCKItemLabel : '' ) ;
}

FCKSpecialCombo.prototype.SetLabel = function( text )
{
	text = ( !text || text.length == 0 ) ? ' ' : text ;

	if ( text == this.Label )
		return ;

	this.Label = text ;

	var labelEl = this._LabelEl ;
	if ( labelEl )
	{
		labelEl.innerHTML = text ;

		// It may happen that the label is some HTML, including tags. This
		// would be a problem because when the user click on those tags, the
		// combo will get the selection from the editing area. So we must
		// disable any kind of selection here.
		FCKTools.DisableSelection( labelEl ) ;
	}
}

FCKSpecialCombo.prototype.SetEnabled = function( isEnabled )
{
	this.Enabled = isEnabled ;

	// In IE it can happen when the page is reloaded that _OuterTable is null, so check its existence
	if ( this._OuterTable )
		this._OuterTable.className = isEnabled ? '' : 'SC_FieldDisabled' ;
}

FCKSpecialCombo.prototype.Create = function( targetElement )
{
	var oDoc = FCKTools.GetElementDocument( targetElement ) ;
	var eOuterTable = this._OuterTable = targetElement.appendChild( oDoc.createElement( 'TABLE' ) ) ;
	eOuterTable.cellPadding = 0 ;
	eOuterTable.cellSpacing = 0 ;

	eOuterTable.insertRow(-1) ;

	var sClass ;
	var bShowLabel ;

	switch ( this.Style )
	{
		case FCK_TOOLBARITEM_ONLYICON :
			sClass = 'TB_ButtonType_Icon' ;
			bShowLabel = false;
			break ;
		case FCK_TOOLBARITEM_ONLYTEXT :
			sClass = 'TB_ButtonType_Text' ;
			bShowLabel = false;
			break ;
		case FCK_TOOLBARITEM_ICONTEXT :
			bShowLabel = true;
			break ;
	}

	if ( this.Caption && this.Caption.length > 0 && bShowLabel )
	{
		var oCaptionCell = eOuterTable.rows[0].insertCell(-1) ;
		oCaptionCell.innerHTML = this.Caption ;
		oCaptionCell.className = 'SC_FieldCaption' ;
	}

	// Create the main DIV element.
	var oField = FCKTools.AppendElement( eOuterTable.rows[0].insertCell(-1), 'div' ) ;
	if ( bShowLabel )
	{
		oField.className = 'SC_Field' ;
		oField.style.width = this.FieldWidth + 'px' ;
		oField.innerHTML = '

' ;

		this._LabelEl = oField.getElementsByTagName('label')[0] ;		// Memory Leak
		this._LabelEl.innerHTML = this.Label ;
	}
	else
	{
		oField.className = 'TB_Button_Off' ;
		//oField.innerHTML = '' + this.Caption + '

' ;
		//oField.innerHTML = '

' ;

		// Gets the correct CSS class to use for the specified style (param).
		oField.innerHTML = '
' +
				'
' +
					//'	' +
					'	' +
					'' + this.Caption + '	' +
					'	' +
					'	' +
					'	' +
				'
' +
			'
' ;
	}

	// Events Handlers

	FCKTools.AddEventListenerEx( oField, 'mouseover', FCKSpecialCombo_OnMouseOver, this ) ;
	FCKTools.AddEventListenerEx( oField, 'mouseout', FCKSpecialCombo_OnMouseOut, this ) ;
	FCKTools.AddEventListenerEx( oField, 'click', FCKSpecialCombo_OnClick, this ) ;

	FCKTools.DisableSelection( this._Panel.Document.body ) ;
}

function FCKSpecialCombo_Cleanup()
{
	this._LabelEl = null ;
	this._OuterTable = null ;
	this._ItemsHolderEl = null ;
	this._PanelBox = null ;

	if ( this.Items )
	{
		for ( var key in this.Items )
			this.Items[key] = null ;
	}
}

function FCKSpecialCombo_OnMouseOver( ev, specialCombo )
{
	if ( specialCombo.Enabled )
	{
		switch ( specialCombo.Style )
		{
			case FCK_TOOLBARITEM_ONLYICON :
				this.className = 'TB_Button_On_Over';
				break ;
			case FCK_TOOLBARITEM_ONLYTEXT :
				this.className = 'TB_Button_On_Over';
				break ;
			case FCK_TOOLBARITEM_ICONTEXT :
				this.className = 'SC_Field SC_FieldOver' ;
				break ;
		}
	}
}

function FCKSpecialCombo_OnMouseOut( ev, specialCombo )
{
	switch ( specialCombo.Style )
	{
		case FCK_TOOLBARITEM_ONLYICON :
			this.className = 'TB_Button_Off';
			break ;
		case FCK_TOOLBARITEM_ONLYTEXT :
			this.className = 'TB_Button_Off';
			break ;
		case FCK_TOOLBARITEM_ICONTEXT :
			this.className='SC_Field' ;
			break ;
	}
}

function FCKSpecialCombo_OnClick( e, specialCombo )
{
	// For Mozilla we must stop the event propagation to avoid it hiding
	// the panel because of a click outside of it.
//	if ( e )
//	{
//		e.stopPropagation() ;
//		FCKPanelEventHandlers.OnDocumentClick( e ) ;
//	}

	if ( specialCombo.Enabled )
	{
		var oPanel			= specialCombo._Panel ;
		var oPanelBox		= specialCombo._PanelBox ;
		var oItemsHolder	= specialCombo._ItemsHolderEl ;
		var iMaxHeight		= specialCombo.PanelMaxHeight ;

		if ( specialCombo.OnBeforeClick )
			specialCombo.OnBeforeClick( specialCombo ) ;

		// This is a tricky thing. We must call the "Load" function, otherwise
		// it will not be possible to retrieve "oItemsHolder.offsetHeight" (IE only).
		if ( FCKBrowserInfo.IsIE )
			oPanel.Preload( 0, this.offsetHeight, this ) ;

		if ( oItemsHolder.offsetHeight > iMaxHeight )
//		{
			oPanelBox.style.height = iMaxHeight + 'px' ;

//			if ( FCKBrowserInfo.IsGecko )
//				oPanelBox.style.overflow = '-moz-scrollbars-vertical' ;
//		}
		else
			oPanelBox.style.height = '' ;

//		oPanel.PanelDiv.style.width = specialCombo.PanelWidth + 'px' ;

		oPanel.Show( 0, this.offsetHeight, this ) ;
	}

//	return false ;
}

/*
Sample Combo Field HTML output:

*/


text:
FOUNDATION_EXPORT double IntegerExtendTypeVersionNumber;

//! Project version string for UnsignedIntegerExtendType.
FOUNDATION_EXPORT const unsigned char IntegerExtendTypeVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <UnsignedIntegerExtendType/PublicHeader.h>


text:
(function() {
    'use strict';
    var fs = require('fs'),
        clc = require('cli-color'),
        im = require('imagemagick'),
        mkdirp = require('mkdirp'),
        svg2png = require("../util/svg2png"),
        rootDirectory = '/wp8',
        iconDirectory = rootDirectory + '/icons/',
        splashDirectory = rootDirectory + '/splashscreens/',
        iconNameList = ['LockIcon', 'ApplicationIcon', 'IconicTileSmall', 'FlipCycleTileSmall', 'IconicTileMedium', 'FlipCycleTileMedium'],
        numOfIcons = iconNameList.length,
        iconDimensions = [38, 99, 110, 159, 202, 336],
        splashScreenNameList = ['~iphone', '@2x~iphone', '-Portrait~ipad', '-@2x~ipad', '-Landscape~ipad', '-Landscape@2x~ipad', '-568h@2x~iphone'],
        splashScreenDimensions = ['99x99', '159x159', '110x110', '1536x2048', '1024x768', '2048x1536', '640x1136'];

    function _generateIcons(input, output, type, cb) {
        var wstream = fs.createWriteStream(output + rootDirectory + '/wp8.xml');
        wstream.on('finish', function() {
            console.log('wp8 config.xml has been written.');
        });
        wstream.write('<platform name="wp8">\n');

        if (type === 'svg') {
            mkdirp(output + iconDirectory, function(err) {
                if (err) {
                    console.error(err);
                } else {
                    iconNameList.forEach(function(el, index) {
                        var dim = iconDimensions[index];
                        svg2png(input, output + iconDirectory + 'icon' + el + '.png', 'w' + dim, function(err) {
                            if (err) {
                                throw err;
                            }
                            console.log('Converted ' + input + ' to fit within ' + clc.yellowBright(dim + 'x' + dim) + ' under ' + output + iconDirectory + 'icon' + el + '.png');
                            wstream.write('    <icon src="wp8/icons/' + el + '.png" width="' + dim + '" height="' + dim + '" />\n');
                            if (numOfIcons === 1) {
                                numOfIcons = iconNameList.length;
                                wstream.write('</platform>');
                                wstream.end();
                                cb();
                            } else {
                                numOfIcons--;
                            }
                        });
                    });
                }
            });
        } else if (type === 'png') {
            mkdirp(output + iconDirectory, function(err) {
                if (err) {
                    console.error(err);
                } else {
                    iconNameList.forEach(function(el, index) {
                        var dim = iconDimensions[index];
                        im.resize({
                            srcPath: input,
                            dstPath: output + iconDirectory + 'icon' + el + '.png',
                            width: dim,
                            height: dim
                        }, function(err, stdout, stderr) {
                            if (err) {
                                throw err;
                            }
                            console.log('Resized ' + input + ' to fit within ' + clc.yellowBright(dim + 'x' + dim) + ' under ' + output + iconDirectory + 'icon' + el + '.png');
                            wstream.write('    <icon src="wp8/icons/' + el + '.png" width="' + dim + '" height="' + dim + '" />\n');
                            if (numOfIcons === 1) {
                                numOfIcons = iconNameList.length;
                                wstream.write('</platform>');
                                wstream.end();
                                cb();
                            } else {
                                numOfIcons--;
                            }
                        });
                    });
                }
            });
        }
    }

    // function _generateSplashScreens(input) {
    //     splashScreenNameList.forEach( function(el, index ) {
    //         var dim = splashScreenDimensions[index];
    //         im.convert([input, '-resize', dim, splashDirectory+'Default' + el + '.png'],
    //             function (err, stdout, stderr) {
    //                 if (err) {
    //                     throw err;
    //                 }
    //                 console.log('Resized '+input+ ' to fit within '+dim );
    //             }
    //         );
    //     });
    // }

    function _generate(input, output, type, cb) {
        mkdirp(output + rootDirectory, function(err) {
            if (err) {
                console.error(err);
            } else {
                console.log("Created WP8 icon directory.");
                _generateIcons(input, output, type, cb);
            }
        });
        // mkdirp(splashDirectory, function (err) {
        //     if (err) {
        //         console.error(err);
        //     }
        //     else {
        //         console.log( "Created WP8 splashscreen directory.");
        //         _generateSplashScreens(input);
        //     }
        // });
    }

    exports.generate = _generate;

})();


text:
import biketl
import random
import datetime
import unittest

TEST_FIT_FILE = 'testdata/2013-06-08-07-59-08.fit'

class TestPointList(unittest.TestCase):

  def setUp(self):
    self.pointlist = biketl.PointList(TEST_FIT_FILE)

  def test_GetPointsNearestTime(self):
    # Check random locations
    for sample in random.sample(xrange(len(self.pointlist)), 5):
      expected = self.pointlist[sample]
      points = self.pointlist.GetPointsNearestTime(expected.time)
      self.assertEqual(expected, points[-1])

    # Check head of list
    expected = self.pointlist[0]
    t = expected.time - datetime.timedelta(0, 10)
    points = self.pointlist.GetPointsNearestTime(expected.time)
    self.assertEqual(expected, points[-1])

    # Check end of list
    expected = self.pointlist[-1]
    t = expected.time + datetime.timedelta(0, 10)
    points = self.pointlist.GetPointsNearestTime(t)
    self.assertEqual(expected, points[-1])

  def test_GetMapForPoints(self):
    pass

  def test_GetLineGraphForPoints(self):
    end_point = self.pointlist[-1]
    points = self.pointlist.GetPointsNearestTime(end_point.time)
    graph = biketl.GetLineGraphForPoints('/tmp', 'test', points)
    print 'graph=%s' % graph

class FakeImage(object):
  def __init__(self, time):
    self.time = time

class TestCheckImagesAndPointsOverlap(unittest.TestCase):

  def setUp(self):
    self.pointlist = biketl.PointList(TEST_FIT_FILE)

  def test_NoOverlap(self):
    end_time = self.pointlist[-1].time + datetime.timedelta(0, 1, 0)
    images = [FakeImage(end_time)]
    self.assertRaises(biketl.ImagesAndPointsDoNotOverlap, biketl.CheckImagesAndPointsOverlap,
        images, self.pointlist)

  def test_NoImages(self):
    self.assertRaises(biketl.NoImagesFound, biketl.CheckImagesAndPointsOverlap,
        [], self.pointlist)

  def test_NoPoints(self):
    images = [FakeImage(datetime.datetime.now())]
    self.assertRaises(biketl.NoGPSTrack, biketl.CheckImagesAndPointsOverlap,
        images, [])

  def test_Success(self):
    end_time = self.pointlist[-1].time
    images = [FakeImage(end_time)]
    biketl.CheckImagesAndPointsOverlap(images, self.pointlist)

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


text:
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using Exceptionless.Api.Controllers;
using Exceptionless.Api.Serialization;

namespace Exceptionless.Api.Utility.Results {
    public class PermissionActionResult : IHttpActionResult {
        public PermissionActionResult(PermissionResult permission, HttpRequestMessage request) {
            if (permission == null)
                throw new ArgumentNullException(nameof(permission));

            if (request == null)
                throw new ArgumentNullException(nameof(request));

            Permission = permission;
            Request = request;
        }

        public PermissionResult Permission { get; private set; }

        public HttpRequestMessage Request { get; private set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) {
            return Task.FromResult(Execute());
        }

        private HttpResponseMessage Execute() {
            return new HttpResponseMessage(Permission.StatusCode) {
                ReasonPhrase = Permission.Message,
                Content = new ObjectContent<MessageContent>(new MessageContent(Permission.Id, Permission.Message), new ExceptionlessJsonMediaTypeFormatter()),
                RequestMessage = Request
            };
        }
    }
}


text:
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL;

namespace CjClutter.OpenGl.OpenGl
{
    public class Uniform<T>
    {
        private readonly Dictionary<Type, Action<object>> _setterDictionary;
        private readonly int _location;

        private readonly Action<object> _uniformSetter;

        public Uniform(int location)
        {
            _location = location;

            _setterDictionary = new Dictionary<Type, Action<object>>
                                    {
                                        {typeof(Matrix4), SetMatrix4},
                                        {typeof(Vector3), SetVector3},
                                        {typeof(Vector4), SetVector4},
                                        {typeof(Vector2), SetVector2},
                                        {typeof(Matrix3), SetMatrix3},
                                    };

            var type = typeof (T);

            if(!_setterDictionary.ContainsKey(type))
            {
                throw new NotImplementedException("Setter is not implemented for uniform type");
            }

            _uniformSetter = _setterDictionary[type];
        }

        public void Set(T value)
        {
            var o = (object) value;
            _uniformSetter(o);
        }

        private void SetVector4(object obj)
        {
            var vector4 = (Vector4) obj;
            GL.Uniform4(_location, ref vector4);
        }

        private void SetVector3(object obj)
        {
            var vector3 = (Vector3) obj;
            GL.Uniform3(_location, ref vector3);
        }

        private void SetVector2(object obj)
        {
            var vector2 = (Vector2) obj;
            GL.Uniform2(_location, vector2);
        }

        private void SetMatrix4(object value)
        {
            var matrix = (Matrix4)value;
            GL.UniformMatrix4(_location, false, ref matrix);
        }

        private void SetMatrix3(object value)
        {
            var matrix = (Matrix3) value;
            GL.UniformMatrix3(_location, false, ref matrix);
        }
    }
}


text:
/** @file */	// Doxygen marker

#import "CC3Identifiable.h"
#import "CC3PODResource.h"

/** Extensions to CC3Identifiable to support PVR POD data. */
@interface CC3Identifiable (PVRPOD)

/**
 * The index of this object in the POD resource data.
 * This generally means the podIndex'th type of object of the class.
 */
@property(nonatomic, assign) int podIndex;

/**
 * Initializes this instance from the data of this type at
 * the specified index within the specified POD resource.
 */
-(id) initAtIndex: (int) aPODIndex fromPODResource: (CC3PODResource*) aPODRez;

@end


text:
function ShutDownSuccess()
{
  $('#shutdowncomplete').modal();
  $('.jumbotron').fadeOut();
  $('.navbar').fadeOut();
  $('footer').fadeOut();
}
function ShutDown()
{
  $.ajax({url:"/shutitdown",type:"GET",error:ShutDownSuccess,success: function(data) { setTimeout(ShutDown,1000);}});
}
$( document ).ready(function() {
  ShutDown();
});


text:
/*
 * Author: Josue Galeas
 * Last Edit: 2018.08.04
 */

#ifndef DANGER_HPP
#define DANGER_HPP

#include "Board.hpp"
#include <vector>

char flipColor(char);
bool inDanger(int *, char, Board *);
bool inDangerEnemy(int *, char, Board *, std::vector<std::tuple<int, int>> &);

#endif /* DANGER_HPP */


text:
  Saint-Léger-sous-Brienne est
       un village
       situé dans le département de l'Aube en Champagne-Ardenne. Elle totalisait 384 habitants en 2008.

Le nombre de logements, à Saint-Léger-sous-Brienne, se décomposait en 2011 en trois appartements et 178 maisons soit
 un marché relativement équilibré.

Si vous pensez emmenager à Saint-Léger-sous-Brienne, vous pourrez facilement trouver une maison à vendre.

À proximité de Saint-Léger-sous-Brienne sont localisées les communes de
Perthes-lès-Brienne localisée à 4 km, 70 habitants,
Saint-Christophe-Dodinicourt localisée à 4 km, 37 habitants,
Lassicourt située à 4 km, 49 habitants,
Précy-Saint-Martin à 4 km, 213 habitants,
Précy-Notre-Dame à 4 km, 79 habitants,
Blaincourt-sur-Aube localisée à 3 km, 95 habitants,
 entre autres. De plus, Saint-Léger-sous-Brienne est située à seulement 24 km de Bar-sur-Aube.

La ville offre quelques  équipements sportifs, elle dispose, entre autres, de un terrain de sport.


text:
package com.laytonsmith.core.functions;

import com.laytonsmith.abstraction.MCCommandSender;
import com.laytonsmith.abstraction.MCConsoleCommandSender;
import com.laytonsmith.abstraction.MCLocation;
import com.laytonsmith.abstraction.MCPlayer;
import com.laytonsmith.abstraction.MCServer;
import com.laytonsmith.abstraction.MCWorld;
import com.laytonsmith.abstraction.StaticLayer;
import com.laytonsmith.abstraction.blocks.MCBlock;
import com.laytonsmith.abstraction.bukkit.BukkitMCWorld;
import com.laytonsmith.commandhelper.CommandHelperPlugin;
import com.laytonsmith.testing.StaticTest;
import static com.laytonsmith.testing.StaticTest.GetFakeConsoleCommandSender;
import static com.laytonsmith.testing.StaticTest.GetFakeServer;
import static com.laytonsmith.testing.StaticTest.GetOp;
import static com.laytonsmith.testing.StaticTest.GetWorld;
import static com.laytonsmith.testing.StaticTest.Run;
import static com.laytonsmith.testing.StaticTest.SRun;
import java.util.HashSet;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 *
 *
 */
public class PlayerManangementTest {

	MCServer fakeServer;
	MCPlayer fakePlayer;

	public PlayerManangementTest() {
	}

	@BeforeClass
	public static void setUpClass() throws Exception {
		//mockStatic(StaticLayer.class);
	}

	@AfterClass
	public static void tearDownClass() throws Exception {
	}

	@Before
	public void setUp() throws Exception {
		fakeServer = GetFakeServer();
		fakePlayer = GetOp("player", fakeServer);
		StaticTest.InstallFakeConvertor(fakePlayer);
		when(fakePlayer.getServer()).thenReturn(fakeServer);
		CommandHelperPlugin.myServer = fakeServer;
		String name = fakePlayer.getName();
		when(fakeServer.getPlayer(name)).thenReturn(fakePlayer);
	}

	@After
	public void tearDown() {
	}

	@Test(timeout = 10000)
	public void testPlayer() throws Exception {
		String script = "player()";
		assertEquals(fakePlayer.getName(), SRun(script, fakePlayer));
		assertEquals("null", SRun(script, null));
	}

	@Test(timeout = 10000)
	public void testPlayer2() throws Exception {
		String script = "player()";
		MCConsoleCommandSender c = GetFakeConsoleCommandSender();
		assertEquals("~console", SRun(script, c));
	}

	@Test(timeout = 10000)
	public void testPlayer3() throws Exception {
		MCCommandSender c = GetFakeConsoleCommandSender();
		assertEquals("~console", SRun("player()", c));
	}

//	@Test(timeout = 10000)
//	public void testAllPlayers() throws Exception {
//		String script = "all_players()";
//		String done = SRun(script, fakePlayer);
//		//This output is too long to test with msg()
//		assertEquals("{player1, player2, player3, player}", done);
//	}
	@Test
	public void testPloc() throws Exception, Exception {
		String script = "msg(ploc())";
		BukkitMCWorld w = GetWorld("world");
		MCLocation loc = StaticLayer.GetLocation(w, 0, 1, 0);
		when(fakePlayer.getLocation()).thenReturn(loc);
		when(fakePlayer.getWorld()).thenReturn(w);
		SRun(script, fakePlayer);
		verify(fakePlayer).sendMessage("{0: 0.0, 1: 1.0, 2: 0.0, 3: world, 4: 0.0, 5: 0.0, pitch: 0.0, world: world, x: 0.0, y: 1.0, yaw: 0.0, z: 0.0}");
	}

	public void testSetPloc() throws Exception, Exception {
		MCWorld w = GetWorld("world");
		CommandHelperPlugin.myServer = fakeServer;
		String name = fakePlayer.getName();
		when(fakeServer.getPlayer(name)).thenReturn(fakePlayer);
		when(fakePlayer.getWorld()).thenReturn(w);
		MCLocation loc = StaticTest.GetFakeLocation(w, 0, 0, 0);
		when(fakePlayer.getLocation()).thenReturn(loc);

		Run("set_ploc(1, 1, 1)", fakePlayer);
		//when(StaticLayer.GetLocation(w, 1, 2, 1)).thenReturn(loc);
		MCLocation loc1 = StaticTest.GetFakeLocation(w, 1, 2, 1);
		assertEquals(fakePlayer.getLocation().getX(), loc1.getX(), 0.00000000000001); // verify(fakePlayer).teleport(loc1);

		Run("set_ploc(array(2, 2, 2))", fakePlayer);
		verify(fakePlayer).teleport(StaticLayer.GetLocation(w, 2, 3, 2, 0, 0));

		Run("set_ploc('" + fakePlayer.getName() + "', 3, 3, 3)", fakePlayer);
		verify(fakePlayer).teleport(StaticLayer.GetLocation(w, 3, 4, 3, 0, 0));

		Run("set_ploc('" + fakePlayer.getName() + "', array(4, 4, 4))", fakePlayer);
		verify(fakePlayer).teleport(StaticLayer.GetLocation(w, 4, 5, 4, 0, 0));
	}

	@Test(timeout = 10000)
	public void testPcursor() throws Exception, Exception {
		MCBlock b = mock(MCBlock.class);
		CommandHelperPlugin.myServer = fakeServer;
		when(fakeServer.getPlayer(fakePlayer.getName())).thenReturn(fakePlayer);
		when(fakePlayer.getTargetBlock((HashSet) eq(null), anyInt())).thenReturn(b);
		MCWorld w = mock(MCWorld.class);
		MCLocation loc = StaticTest.GetFakeLocation(w, 0, 0, 0);
		when(b.getLocation()).thenReturn(loc);
		when(b.getWorld()).thenReturn(w);
		Run("pcursor()", fakePlayer);
		verify(fakePlayer, times(1)).getTargetBlock((HashSet) eq(null), anyInt());
	}

	@Test(timeout = 10000)
	public void testKill() throws Exception {
		Run("pkill()", fakePlayer);
		Run("pkill('" + fakePlayer.getName() + "')", fakePlayer);
		verify(fakePlayer, times(2)).kill();
	}

	//@Test(timeout=10000)
	public void testPgroup() throws Exception {
		Run("", fakePlayer);
		Run("", fakePlayer);
	}

	@Test
	public void testPlayerNotProvided() throws Exception {
		assertEquals("success", SRun("try(pkill(), assign(@success, 'success')) @success", null));
	}

	@Test
	public void testPlayerFromConsole() throws Exception {
		MCConsoleCommandSender fakeConsole = mock(MCConsoleCommandSender.class);
		when(fakeConsole.getName()).thenReturn("CONSOLE");
		assertEquals("~console", SRun("player()", fakeConsole));
	}

//	//@Test(timeout=10000)
//	public void testPinfo(){
//
//	}
//
//	//@Test(timeout=10000)
//	public void testPworld(){
//
//	}
//
//	//@Test(timeout=10000)
//	public void testKick(){
//
//	}
//
//	//@Test(timeout=10000)
//	public void testSetDisplayName(){
//
//	}
//
//	//@Test(timeout=10000)
//	public void testResetDisplayName(){
//
//	}
//
//	//@Test(timeout=10000)
//	public void testPFacing(){
//
//	}
//
//	//@Test(timeout=10000)
//	public void testPinv(){
//
//	}
//
//	//@Test(timeout=10000)
//	public void testSetPinv(){
//
//	}
}


text:
<!DOCTYPE html>

<title>NotificationDetailInfo_constructor</title>
<meta charset="utf-8">


text:
@extends('blog::master')

@section('body')

{!! Html::link('/blog','Last Post') !!}

{!! Html::link('/','Back to Site') !!}

{!! Html::link('/blog',\Config::get('blog.title')) !!}

     @if(count($last)==0)

Noting to see, go to panel and post something first !

     @else

MOST RECOMMENDED

        getUrl()}}">

        getUrl()}}">
{{$mostRecommended['title']}}

               {{ str_limit(strip_tags($mostRecommended['content']),150) }}...

{{$mostRecommended['author']}}

LATEST

        @foreach($last as $post)

                getUrl()}}">

{{$post['title']}}

 {{substr(strip_tags($post['content']), 0, 150)}}...

                    {{$post['author']}}

        @endforeach

    @endif

Powered by Serverfireteam/panel .

@stop


text:
* Support for CocoaLumberjack 3.0.0 by loosening dependencies' version requirements (#8)

#### Version 1.1.0

* XCDLumberjackNSLogger builds as a framework and is therefore compatible with Carthage (#1)
* tvOS support
* Use filename as tag if no context to tag mapping is found (#5)
* New method to automatically bind a XCDLumberjackNSLogger instance to user defaults

#### Version 1.0.2

* XCDLumberjackNSLogger is less strict about CocoaLumberjack and NSLogger required versions

#### Version 1.0.1

* Log pretty printed NSData as data
* Use proper thread identifier and queue name
* Added a `debugDescription` implementation

#### Version 1.0.0

* Initial version


text: mysqladmin -u root -fp create hd


text:
<?xml version="1.0" encoding="utf-8" ?>
<ResearchProjectDefs>

	<ResearchProjectDef>
		<defName>Refrigeration</defName>
		<label>refrigeration</label>
		<description>Allows you to build refrigerators to extend the lifetime of food.</description>
		<totalCost>700</totalCost>
	</ResearchProjectDef>

</ResearchProjectDefs>


text:
// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.

#ifndef _FASTDDS_RTCP_HEADER_H_
#define _FASTDDS_RTCP_HEADER_H_

#include <fastdds/rtps/common/Types.h>
#include <cstring>
#include <fastcdr/FastCdr.h>
#include <fastcdr/Cdr.h>

#include <fastcdr/exceptions/BadParamException.h>

namespace eprosima {
namespace fastdds {
namespace rtps {

#define TCPHEADER_SIZE 14

// TCP Header structs and enums.
struct TCPHeader
{
    char rtcp[4];
    uint32_t length;
    uint32_t crc;
    uint16_t logical_port;

    TCPHeader()
        : length(TCPHEADER_SIZE)
        , crc(0)
        , logical_port(0)
    {
        // There isn't a explicit constructor because VS2013 doesn't support it.
        rtcp[0] = 'R';
        rtcp[1] = 'T';
        rtcp[2] = 'C';
        rtcp[3] = 'P';
    }

    const fastrtps::rtps::octet* address() const
    {
        return reinterpret_cast<const fastrtps::rtps::octet*>(this);
    }

    fastrtps::rtps::octet* address()
    {
        return (fastrtps::rtps::octet*)this;
    }

    /*!
     * @brief This function returns the maximum serialized size of an object
     * depending on the buffer alignment.
     * @return Maximum serialized size.
     */
    static inline size_t size()
    {
        return TCPHEADER_SIZE;
    }

};

union TCPTransactionId
{
    uint32_t ints[3];
    fastrtps::rtps::octet octets[12];

    TCPTransactionId()
    {
        memset(ints, 0, 3 * sizeof(uint32_t));
    }

    TCPTransactionId(const TCPTransactionId& t)
    {
        memcpy(ints, t.ints, 3 * sizeof(uint32_t));
    }

    TCPTransactionId& operator ++()
    {
        if (ints[0] == 0xffffffff)
        {
            if (ints[1] == 0xffffffff)
            {
                if (ints[2] == 0xffffffff)
                {
                    memset(ints, 0, 3 * sizeof(uint32_t));
                }
                else
                {
                    ints[2] += 1;
                }
            }
            else
            {
                ints[1] += 1;
            }
        }
        else
        {
            ints[0] += 1;
        }
        return *this;
    }

    TCPTransactionId operator ++(
            int)
    {
        TCPTransactionId prev = *this;
        ++(*this);
        return prev;
    }

    TCPTransactionId& operator =(
            const TCPTransactionId& t)
    {
        memcpy(ints, t.ints, 3 * sizeof(uint32_t));
        return *this;
    }

    TCPTransactionId& operator =(
            const fastrtps::rtps::octet* id)
    {
        memcpy(octets, id, 12 * sizeof(fastrtps::rtps::octet));
        return *this;
    }

    TCPTransactionId& operator =(
            const char* id)
    {
        memcpy(octets, id, 12 * sizeof(fastrtps::rtps::octet));
        return *this;
    }

    TCPTransactionId& operator =(
            const uint32_t* id)
    {
        memcpy(ints, id, 3 * sizeof(uint32_t));
        return *this;
    }

    TCPTransactionId& operator =(
            uint32_t id)
    {
        ints[0] = id;
        ints[1] = 0;
        ints[2] = 0;
        return *this;
    }

    TCPTransactionId& operator =(
            uint64_t id)
    {
        memset(ints, 0, sizeof(uint32_t) * 3);
        memcpy(ints, &id, sizeof(uint64_t));
        return *this;
    }

    bool operator ==(
            const TCPTransactionId& t) const
    {
        return memcmp(ints, t.ints, 3 * sizeof(uint32_t)) == 0;
    }

    bool operator <(
            const TCPTransactionId& t) const
    {
        return memcmp(ints, t.ints, 3 * sizeof(uint32_t)) < 0;
    }

};

inline std::ostream& operator <<(
        std::ostream& output,
        const TCPTransactionId& t)
{
    bool printed = false; // Don't skip cases like 99 0 34
    for (int i = 2; i >= 0; --i)
    {
        if (printed || i == 0 || t.ints[i] > 0)
        {
            output << t.ints[i];
            printed = true;
        }
    }
    return output;
}

enum TCPCPMKind : fastrtps::rtps::octet
{
    BIND_CONNECTION_REQUEST =           0xD1,
    BIND_CONNECTION_RESPONSE =          0xE1,
    OPEN_LOGICAL_PORT_REQUEST =         0xD2,
    OPEN_LOGICAL_PORT_RESPONSE =        0xE2,
    CHECK_LOGICAL_PORT_REQUEST =        0xD3,
    CHECK_LOGICAL_PORT_RESPONSE =       0xE3,
    KEEP_ALIVE_REQUEST =                0xD4,
    KEEP_ALIVE_RESPONSE =               0xE4,
    LOGICAL_PORT_IS_CLOSED_REQUEST =    0xD5,
    UNBIND_CONNECTION_REQUEST =         0xD6
};

class TCPControlMsgHeader
{
    TCPCPMKind kind_; // 1 byte
    fastrtps::rtps::octet flags_; // 1 byte
    uint16_t length_; // 2 bytes
    TCPTransactionId transaction_id_; // 12 bytes

public:

    TCPControlMsgHeader()
    {
        kind_ = static_cast<TCPCPMKind>(0x00);
        flags_ = static_cast<fastrtps::rtps::octet>(0x00);
        length_ = 0;
    }

    void kind(
            TCPCPMKind kind)
    {
        kind_ = kind;
    }

    TCPCPMKind kind() const
    {
        return kind_;
    }

    TCPCPMKind& kind()
    {
        return kind_;
    }

    void length(
            uint16_t length)
    {
        length_ = length;
    }

    uint16_t length() const
    {
        return length_;
    }

    uint16_t& length()
    {
        return length_;
    }

    void transaction_id(
            TCPTransactionId transaction_id)
    {
        transaction_id_ = transaction_id;
    }

    TCPTransactionId transaction_id() const
    {
        return transaction_id_;
    }

    TCPTransactionId& transaction_id()
    {
        return transaction_id_;
    }

    void flags(
            bool endianess,
            bool payload,
            bool requires_response)
    {
        //TODO: Optimize receiving a Endianness_t
        fastrtps::rtps::octet e = (endianess) ? BIT(1) : 0x00;
        fastrtps::rtps::octet p = (payload) ? BIT(2) : 0x00;
        fastrtps::rtps::octet r = (requires_response) ? BIT(3) : 0x00;
        flags_ = e | p | r;
    }

    void endianess(
            fastrtps::rtps::Endianness_t endianess)
    {
        // Endianess flag has inverse logic than Endianness_t :-/
        if (endianess == fastrtps::rtps::Endianness_t::BIGEND)
        {
            flags_ &= 0xFE;
        }
        else
        {
            flags_ |= BIT(1);
        }
    }

    void payload(
            bool payload)
    {
        if (payload)
        {
            flags_ |= BIT(2);
        }
        else
        {
            flags_ &= 0xFD;
        }
    }

    void requires_response(
            bool requires_response)
    {
        if (requires_response)
        {
            flags_ |= BIT(3);
        }
        else
        {
            flags_ &= 0xFB;
        }
    }

    bool endianess()
    {
        return (flags_ & BIT(1)) != 0;
    }

    bool payload()
    {
        return (flags_ & BIT(2)) != 0;
    }

    bool requires_response()
    {
        return (flags_ & BIT(3)) != 0;
    }

    static inline size_t size()
    {
        return 16;
    }

};

} // namespace rtps
} // namespace fastdds
} // namespace eprosima

#endif // _FASTDDS_RTCP_HEADER_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" id="com-datamart-wfpk" version="0.5.0">
	<name>Audio Plugin</name>
	<description>Audio Plugin- Allows handling audio stream</description>
	<license>Apache 2.0</license>
	<keywords>cordova,audio, stream</keywords>
	<repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-splashscreen.git</repo>
	<issue>https://issues.apache.org/jira/browse/CB/component/12320653</issue>

	<engines>
		<engine name="cordova-android" version=">3.9.9" /><!-- Requires Gradle building -->
<!--		<engine name="cordova-ios" version=">=1.7.1" />-->
	</engines>

	<js-module src="www/AudioPlugin.js" name="AudioPlugin">
		<clobbers target="AudioPlugin" />
	</js-module>

    <!-- android -->
	<platform name="android">

		<config-file target="res/xml/config.xml" parent="/*">
			<feature name="AudioPlugin">
				<param name="android-package" value="com.datamart.wfpk.AudioPlugin" />
			</feature>
		</config-file>

		<framework src="src/android/audio.gradle" custom="true" type="gradleReference" />
		<source-file src="src/android/AudioPlugin.java" target-dir="src/com/datamart/wfpk" />
        <source-file src="src/android/VolumeChangeCallback.java" target-dir="src/com/datamart/wfpk" />
        <source-file src="src/android/SettingsContentObserver.java" target-dir="src/com/datamart/wfpk" />

	</platform>
</plugin>


text:
'use strict';

var ExtractTextPlugin = require("extract-text-webpack-plugin");
var autoprefixer = require('autoprefixer-core')();
var csswring = require('csswring')();

module.exports = {
  entry: './src/index.js',
  output: {
    path: __dirname + '/public/js',
    filename: './bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader'
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css!postcss')
      }
    ]
  },
  postcss: [
    autoprefixer({
      browsers: ['last 1 version']
    }),
    csswring({
      removeAllComments: true
    })
  ],
  node: {
    fs: 'empty'
  },
  plugins: [
    new ExtractTextPlugin('../css/styles.css')
  ],
  devtool: '#inline-source-map'
};


text:
package io.indexr.query.plan.logical;

import java.util.Collections;
import java.util.List;

public abstract class LPUnaryNode extends LogicalPlan {
    public LogicalPlan child;

    public LPUnaryNode(LogicalPlan child) {
        this.child = child;
    }

    public LogicalPlan child() {return child;}

    @Override
    public List<LogicalPlan> children() {return Collections.singletonList(child);}
}


text:
from nipype.testing import assert_equal
from nipype.interfaces.freesurfer.preprocess import RobustRegister

def test_RobustRegister_inputs():
    input_map = dict(args=dict(argstr='%s',
    ),
    auto_sens=dict(argstr='--satit',
    mandatory=True,
    xor=['outlier_sens'],
    ),
    environ=dict(nohash=True,
    usedefault=True,
    ),
    est_int_scale=dict(argstr='--iscale',
    ),
    force_double=dict(argstr='--doubleprec',
    ),
    force_float=dict(argstr='--floattype',
    ),
    half_source=dict(argstr='--halfmov %s',
    ),
    half_source_xfm=dict(argstr='--halfmovlta %s',
    ),
    half_targ=dict(argstr='--halfdst %s',
    ),
    half_targ_xfm=dict(argstr='--halfdstlta %s',
    ),
    half_weights=dict(argstr='--halfweights %s',
    ),
    high_iterations=dict(argstr='--highit %d',
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    in_xfm_file=dict(argstr='--transform',
    ),
    init_orient=dict(argstr='--initorient',
    ),
    iteration_thresh=dict(argstr='--epsit %.3f',
    ),
    least_squares=dict(argstr='--leastsquares',
    ),
    mask_source=dict(argstr='--maskmov %s',
    ),
    mask_target=dict(argstr='--maskdst %s',
    ),
    max_iterations=dict(argstr='--maxit %d',
    ),
    no_init=dict(argstr='--noinit',
    ),
    no_multi=dict(argstr='--nomulti',
    ),
    out_reg_file=dict(argstr='--lta %s',
    genfile=True,
    ),
    outlier_limit=dict(argstr='--wlimit %.3f',
    ),
    outlier_sens=dict(argstr='--sat %.4f',
    mandatory=True,
    xor=['auto_sens'],
    ),
    registered_file=dict(argstr='--warp %s',
    ),
    source_file=dict(argstr='--mov %s',
    mandatory=True,
    ),
    subjects_dir=dict(),
    subsample_thresh=dict(argstr='--subsample %d',
    ),
    target_file=dict(argstr='--dst %s',
    mandatory=True,
    ),
    terminal_output=dict(mandatory=True,
    nohash=True,
    ),
    trans_only=dict(argstr='--transonly',
    ),
    weights_file=dict(argstr='--weights %s',
    ),
    write_vo2vox=dict(argstr='--vox2vox',
    ),
    )
    inputs = RobustRegister.input_spec()

    for key, metadata in input_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(inputs.traits()[key], metakey), value

def test_RobustRegister_outputs():
    output_map = dict(half_source=dict(),
    half_source_xfm=dict(),
    half_targ=dict(),
    half_targ_xfm=dict(),
    half_weights=dict(),
    out_reg_file=dict(),
    registered_file=dict(),
    weights_file=dict(),
    )
    outputs = RobustRegister.output_spec()

    for key, metadata in output_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(outputs.traits()[key], metakey), value


text:
package russbot.plugins;
import russbot.Session;
import russbot.Storage;

import java.util.AbstractMap;
import java.util.Base64;

public class ReggiesQuest extends Plugin {

    private AbstractMap<String, String> data;

    public ReggiesQuest(){
        data = Storage.getMap("scorekeeping");
    }

    @Override
    public String getRegexPattern() {
        return "!reggie";
    }

    @Override
    public String[] getChannels() {
        String[] channels = {"test", "random"};
        return channels;
    }

    @Override
    public String getInfo() {
        return "help Reggie find his way back home!";
    }

    @Override
    public String[] getCommands() {
        String[] commands = {
                "!reggie - start/load a game of _Reggie's Quest_",
        };
        return commands;
    }

    @Override
    public void messagePosted(String message, String channel, String username, String userid) {
        if(username.equals("russfeld") || username.equals("russfeldh")) {
            String newChannel = Session.getInstance().registerPrivateChannel(new String[]{username}, this);
            StringBuilder output = new StringBuilder();
            printWelcomeMenu(output);
            Session.getInstance().sendPrivateMessage(output.toString(), newChannel);
        }else{
            Session.getInstance().sendMessage("You aren't my creator...you'll have to wait and see what this does!", channel);
        }
    }

    @Override
    public void privateMessagePosted(String message, String channel, String username, String userid){
        //Important Variables
        byte[] state;
        StringBuilder output = new StringBuilder();
        boolean disconnect = false;
        boolean step = false;

        //Load state from data
        if(data.containsKey(userid)){
            state = Base64.getDecoder().decode(data.get(userid));
        }else{
        //Create new state
            state = new byte[1];
            state[0] = 0;
        }

        String[] input = message.split(" ");

        input[0] = input[0].toLowerCase();

        //Single word commands
        if(input.length == 1){
            switch(input[0]){
                case "new":
                    state = new byte[1];
                    state[0] = 0;
                    step = true;
                    break;
                case "continue":
                    if(state[0] == 0){
                        output.append("_No saved game found on server!_");
                    }else{
                        output.append("_Saved game loaded from server! Continuing..._\n");
                        step = true;
                    }
                    break;
                case "save":
                    output.append("_You can resume your game from this state at any time using the following code:_\n");
                    output.append("`" +  Base64.getEncoder().encodeToString(state) +"`");
                    break;
                case "menu":
                    printWelcomeMenu(output);
                    break;
                case "quit":
                    disconnect = true;
                    output.append("_Thanks for playing!_");
                    break;
                case "yes":
                    state = doAction(output, state, input[0], null);
                    step = true;
                    break;
                case "!help":
                case "!commands":
                case "!about":
                    state = doAction(output, state, "help", null);
                    step = true;
                    break;
                default:
                    printError(output);
                    break;
            }
        }

        //Multiple word commands
        if(input.length == 2){
            switch(input[0]){
                case "load":
                    try{
                        state = Base64.getDecoder().decode(input[1]);
                        output.append("_State loaded!_\n");
                        step = true;
                    }catch(IllegalArgumentException e){
                        output.append("_Unable to load state! Error:_\n");
                        output.append("_"+ e.getMessage() + "_");
                    }
                    break;
                default:
                    printError(output);
                    break;
            }
        }

        if(step){
            state = step(output, state);
        }

        //Save state
        data.put(userid, Base64.getEncoder().encodeToString(state));

        Session.getInstance().sendPrivateMessage(output.toString(), channel);

        if(disconnect){
            Session.getInstance().unregisterPrivateChannel(channel);
        }
    }

    private void printWelcomeMenu(StringBuilder output){
        output.append("*Welcome to _Reggie's Quest_!*\n");
        output.append("`new` - _Start a new game_\n");
        output.append("`continue` - _Continue a game (if available)_\n");
        output.append("`load <code>` - _Load a saved game from a code_\n");
        output.append("`save` - _Save your game to a code_\n");
        output.append("`menu` - _Display this menu_\n");
        output.append("`quit` - _Quit Reggie's Quest_\n");
    }

    private void printError(StringBuilder output){
        output.append("_I don't recognize that command. Type_ `help` _or_ `menu` _for available commands._");
    }

    private byte[] step(StringBuilder output, byte[] state){
        switch(state[0]){
            case 0:
                output.append("~Generic welcome message here.~");
                break;
            case 1:
                output.append("~You have begun the quest.~");
                break;
        }
        return state;
    }

    private byte[] doAction(StringBuilder output, byte[] state, String action, String target){
        switch(action){
            case "yes":
                switch(state[0]){
                    case 0:
                        output.append("_You nod your head in agreement._\n");
                        state[0] = 1;
                        break;
                    default:
                        output.append("_You nod your head vigorously, but nothing happens._\n");
                        break;
                }
                break;
            default:
                printError(output);
                break;
        }
        return state;
    }
}


text:
namespace phi {
namespace funcs {

inline HOSTDEVICE phi::dtype::float16 real_exp(phi::dtype::float16 x) {
  return static_cast<phi::dtype::float16>(::expf(static_cast<float>(x)));
}

inline HOSTDEVICE float real_exp(float x) { return ::expf(x); }

inline HOSTDEVICE double real_exp(double x) { return ::exp(x); }

inline HOSTDEVICE phi::dtype::float16 real_log(phi::dtype::float16 x) {
  return static_cast<phi::dtype::float16>(::logf(static_cast<float>(x)));
}

inline HOSTDEVICE phi::dtype::bfloat16 real_log(phi::dtype::bfloat16 x) {
  return static_cast<phi::dtype::bfloat16>(::logf(static_cast<float>(x)));
}

inline HOSTDEVICE float real_log(float x) { return ::logf(x); }

inline HOSTDEVICE double real_log(double x) { return ::log(x); }

inline HOSTDEVICE float real_min(float x, float y) { return ::fminf(x, y); }

inline HOSTDEVICE double real_min(double x, double y) { return ::fmin(x, y); }

}  // namespace funcs
}  // namespace phi


text:
solar-one
========
Creacion de aplicación para moviles la cual da a conocer en tiempo real, las variables que afectan la piel y oos, además de dar tip de como evitar da;os en estos

Equipo
=========
* Daniel López
* Edison Villegas
*
* Edison feo


text:
package gov.nih.nci.ncicb.cadsr.bulkloader.beans.castor;

import java.util.List;

/**
 *
 * @author Ashwin Mathur
 * @version 1.0, Dec 1, 2008
 * @since
 */

/**
 * @author mathura2
 *
 */
public class ClassificationScheme_ISO11179 extends AdminItem_ISO11179{

	private String typeName;
	private String name;
	private Float version;
	private List<ClassificationSchemeItemRef_ISO11179> containing;

	public String getTypeName() {
		return typeName;
	}
	public void setTypeName(String typeName) {
		this.typeName = typeName;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Float getVersion() {
		return version;
	}
	public void setVersion(Float version) {
		this.version = version;
	}
	public List<ClassificationSchemeItemRef_ISO11179> getContaining() {
		return containing;
	}
	public void setContaining(List<ClassificationSchemeItemRef_ISO11179> containing) {
		this.containing = containing;
	}

}


text:
package org.ethereum.datasource;

import com.google.common.util.concurrent.*;
import org.apache.commons.lang3.concurrent.ConcurrentUtils;
import org.ethereum.util.ALock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by Anton Nashatyrev on 18.01.2017.
 */
public abstract class AsyncWriteCache<Key, Value> extends AbstractCachedSource<Key, Value> implements AsyncFlushable {
    private static final Logger logger = LoggerFactory.getLogger("db");

    private static ListeningExecutorService flushExecutor = MoreExecutors.listeningDecorator(
            Executors.newFixedThreadPool(2, new ThreadFactoryBuilder().setNameFormat("AsyncWriteCacheThread-%d").build()));

    protected volatile WriteCache<Key, Value> curCache;
    protected WriteCache<Key, Value> flushingCache;

    private ListenableFuture<Boolean> lastFlush = Futures.immediateFuture(false);

    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final ALock rLock = new ALock(rwLock.readLock());
    private final ALock wLock = new ALock(rwLock.writeLock());

    private String name = "<null>";

    public AsyncWriteCache(Source<Key, Value> source) {
        super(source);
        flushingCache = createCache(source);
        flushingCache.setFlushSource(true);
        curCache = createCache(flushingCache);
    }

    protected abstract WriteCache<Key, Value> createCache(Source<Key, Value> source);

    @Override
    public Collection<Key> getModified() {
        try (ALock l = rLock.lock()) {
            return curCache.getModified();
        }
    }

    @Override
    public boolean hasModified() {
        try (ALock l = rLock.lock()) {
            return curCache.hasModified();
        }
    }

    @Override
    public void put(Key key, Value val) {
        try (ALock l = rLock.lock()) {
            curCache.put(key, val);
        }
    }

    @Override
    public void delete(Key key) {
        try (ALock l = rLock.lock()) {
            curCache.delete(key);
        }
    }

    @Override
    public Value get(Key key) {
        try (ALock l = rLock.lock()) {
            return curCache.get(key);
        }
    }

    @Override
    public synchronized boolean flush() {
        try {
            flipStorage();
            flushAsync();
            return flushingCache.hasModified();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    Entry<Value> getCached(Key key) {
        return curCache.getCached(key);
    }

    @Override
    public synchronized void flipStorage() throws InterruptedException {
        // if previous flush still running
        try {
            if (!lastFlush.isDone()) logger.debug("AsyncWriteCache (" + name + "): waiting for previous flush to complete");
            lastFlush.get();
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

        try (ALock l = wLock.lock()) {
            flushingCache.cache = curCache.cache;
            curCache = createCache(flushingCache);
        }
    }

    public synchronized ListenableFuture<Boolean> flushAsync() throws InterruptedException {
        logger.debug("AsyncWriteCache (" + name + "): flush submitted");
        lastFlush = flushExecutor.submit(new Callable<Boolean>() {
            @Override
            public Boolean call() {
                logger.debug("AsyncWriteCache (" + name + "): flush started");
                long s = System.currentTimeMillis();
                boolean ret = flushingCache.flush();
                logger.debug("AsyncWriteCache (" + name + "): flush completed in " + (System.currentTimeMillis() - s) + " ms");
                return ret;
            }
        });
        return lastFlush;
    }

    @Override
    public long estimateCacheSize() {
        // 2.0 is upper cache size estimation to take into account there are two
        // caches may exist simultaneously up to doubling cache size
        return (long) (curCache.estimateCacheSize() * 2.0);
    }

    @Override
    protected synchronized boolean flushImpl() {
        return false;
    }

    public AsyncWriteCache<Key, Value> withName(String name) {
        this.name = name;
        return this;
    }
}


text:
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    """
    Creates a token whenever a User is created
    """
    if created:
        Token.objects.create(user=instance)