text:
import os
import time
import json
import argparse

import pyrax

_data_centers     = [ 'DFW', 'ORD' ]
_commands         = [ 'list' ]
_config_file      = '~/.rackspace.cfg'
_username         = 'ops'
_server_info_keys = ( 'accessIPv4', 'status', 'name' )
_marker           = '##### auto-generated for rsinfo #####'

_usage = """
  list    list details for the servers
            If a server name is specified, the list will
            only contain that server
            If a datacenter has been given, the list will only
            contain those servers
  hosts   generate output that can be used in /etc/hosts
  ssh     generate output that can be used in ~/.ssh/config

  Config File Format:
      [rackspace_cloud]
      username = USERNAME
      api_key = KEY
"""

def loadConfig():
    parser = argparse.ArgumentParser(epilog=_usage, formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('-c', '--config',     default=_config_file, help='where to retrieve configuration items and the rackspace API keys (default: %(default)s)')
    parser.add_argument('-d', '--datacenter', default='ALL',        help='datacenter to work within (default: %(default)s)', choices=_data_centers)
    parser.add_argument('-s', '--server',                           help='limit output to the named server')

    parser.add_argument('command', choices=['list', 'hosts', 'ssh'])

    return parser.parse_args()

def initCredentials(datacenter):
    pyrax.set_setting("identity_type", "rackspace")
    pyrax.set_credential_file(os.path.expanduser(cfg.config), datacenter)

def loadServers(datacenters):
    # {'OS-EXT-STS:task_state': None,
    #  'addresses': { u'public': [],
    #                 u'private': []
    #               },
    #  'links': [],
    #  'image': { u'id': u'GUID',
    #             u'links': []
    #           },
    #  'manager': <novaclient.v1_1.servers.ServerManager object at 0x101abb450>,
    #  'OS-EXT-STS:vm_state': u'active',
    #  'flavor': { u'id': u'2',
    #              u'links': []
    #            },
    #  'id': u'',
    #  'user_id': u'NNN',
    #  'OS-DCF:diskConfig': u'AUTO',
    #  'accessIPv4': u'',
    #  'accessIPv6': u'',
    #  'progress': 100,
    #  'OS-EXT-STS:power_state': 1,
    #  'metadata': {},
    #  'status': u'ACTIVE',
    #  'updated': u'2013-04-25T05:11:09Z',
    #  'hostId': u'',
    #  'key_name': None,
    #  'name': u'sssss',
    #  'created': u'2013-02-11T19:33:31Z',
    #  'tenant_id': u'NNN',
    #  '_info': {},
    #  'config_drive': u'',
    #  '_loaded': True
    # }
    result = {}
    for dc in datacenters:
        initCredentials(dc)

        print 'searching for servers in', dc
        cs = pyrax.cloudservers
        for s in cs.servers.list(detailed=True):
            if s.name not in result:
                result[s.name] = None
            result[s.name] = s

    print len(result), 'servers processed'
    return result

def loadFileWithoutAutoGeneratedItems(filename, marker):
    print 'loading', filename
    result = []
    f      = False
    for line in open(filename, 'r').readlines():
        if line.startswith(marker):
            f = not f
        else:
            if not f:
                result.append(line)
    return result

def saveFile(filepath, filename, cleandata, newdata, marker, allowAlt=False):
    fullname = os.path.join(filepath, filename)
    print 'saving', fullname
    try:
        h = open(fullname, 'w+')

        h.write(''.join(cleandata))
        h.write('\n%s\n' % marker)
        h.write(''.join(newdata))
        h.write('\n%s\n' % marker)

    except IOError:
        print 'unable to write to', fullname
        if allowAlt:
            print 'attempting alternate location'
            saveFile('/tmp', filename, cleandata, newdata, marker)

def getServerInfo(serverName, serverList):
    result = None

    if cfg.datacenter == 'ALL':
        s = ' in server list'
    else:
        s = ' in datacenter %s' % cfg.datacenter

    if serverName not in serverList:
        print '%s not found %s' % (serverName, s)
    else:
        item   = serverList[serverName]
        result = {}
        for key in _server_info_keys:
            result[key] = item.__getattr__(key)

    return result

_hosts_config = """%(accessIPv4)s\t%(name)s\n"""

def generateHostsFile(servers):
    clean = loadFileWithoutAutoGeneratedItems('/etc/hosts', _marker)
    new   = []

    for s in servers:
        r = getServerInfo(s, servers)
        new.append(_hosts_config % r)

    saveFile('/etc', 'hosts', clean, new, _marker, allowAlt=True)

_ssh_config = """Host %(name)s
User %(username)s
StrictHostKeyChecking no
IdentityFile ~/.ssh/id_rsa

"""

def generateConfigFile(servers):
    clean = loadFileWithoutAutoGeneratedItems('~/.ssh/config', _marker)
    new   = []
    for s in servers:
        r = getServerInfo(s, servers)
        r['username'] = _username
        new.append(_ssh_config % r)

    saveFile('~/.ssh', 'config', clean, new, _marker, allowAlt=True)

def getCommandParam(cmdText, commands):
    try:
        p      = commands.index(cmdText)
        result = commands[p + 1]
    except:
        result = ''
    return result

if __name__ == '__main__':
    cfg = loadConfig()

    if cfg.datacenter == 'ALL':
        datacenters = _data_centers
    else:
        datacenters = [ datacenter ]

    servers = loadServers(datacenters)

    if cfg.command == 'list':
        results = []

        if cfg.server is None:
            for s in servers:
                r = getServerInfo(s, servers)
                if r is not None:
                    results.append(r)
        else:
            r = getServerInfo(cfg.server, servers)
            if r is not None:
                results.append(r)

        print json.dumps(results)

    elif cfg.command == 'hosts':
        generateHostsFile(servers)
    elif cfg.command == 'ssh':
        generateConfigFile(servers)


text:
using System;
using System.Collections.Generic;
using System.CodeDom;

namespace Iyzipay.Model
{
    public class BkmInstallment : RequestStringConvertible
    {
        public long? BankId { get; set; }
        public List<BkmInstallmentPrice> InstallmentPrices { get; set; }

        public String ToPKIRequestString()
        {
            return ToStringRequestBuilder.NewInstance()
                .Append("bankId", BankId)
                .AppendList("installmentPrices", InstallmentPrices)
                .GetRequestString();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Basal\Middleware\Exception;

/**
 * Class MiddlewareDispatcherException.
 */
class MiddlewareDispatcherException extends \Exception
{
}


text:
                <form id ="login_form" class="form-horizontal" role="form" method="post" action="<?=site_url("api/login")?>">

                        Email:

                            <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">

                        Password:

                            <input type="password" class="form-control" id="pwd" name="pwd" placeholder="Enter password">

                            <button type="submit" class="btn btn-lg btn-primary center-block">Login</button>

                </form>


text:
package org.hl7.v3;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="ANY")
@XmlSeeAlso({ANYNonNull.class, BL.class, SLISTPQ.class, CR.class, II.class, SLISTTS.class, GLISTTS.class, URL.class, QTY.class, CD.class, GLISTPQ.class, BIN.class})
public abstract class ANY
{

  @XmlAttribute(name="nullFlavor")
  protected List<String> nullFlavor;

  public List<String> getNullFlavor()
  {
    if (this.nullFlavor == null) {
      this.nullFlavor = new ArrayList();
    }
    return this.nullFlavor;
  }
}


text:
package quickfix.field;
import quickfix.IntField;

public class BidType extends IntField
{
  static final long serialVersionUID = 20050617;

  public static final int FIELD = 394;
  public static final int NON_DISCLOSED = 1;
  public static final int DISCLOSED_STYLE = 2;
  public static final int NO_BIDDING_PROCESS = 3;

  public BidType()
  {
    super(394);
  }

  public BidType(int data)
  {
     super(394, data);
  }

}


text:
#include "paddle/fluid/framework/program_desc.h"

extern "C" {
#include <xxhash.h>
}

#include <algorithm>
#include "paddle/fluid/framework/feed_fetch_type.h"
#include "paddle/fluid/framework/version.h"

namespace paddle {
namespace framework {

BlockDesc *ProgramDesc::AppendBlock(const BlockDesc &parent) {
  auto *b = desc_.add_blocks();
  b->set_parent_idx(parent.ID());
  b->set_idx(desc_.blocks_size() - 1);
  blocks_.emplace_back(new BlockDesc(this, b));
  return blocks_.back().get();
}

void ProgramDesc::Flush() {
  for (auto &block : blocks_) {
    block->Flush();
  }
}

proto::ProgramDesc *ProgramDesc::Proto() {
  Flush();
  return &desc_;
}

proto::OpVersionMap *ProgramDesc::OpVersionMap() {
  return desc_.mutable_op_version_map();
}

int64_t ProgramDesc::Version() const { return desc_.version().version(); }

void ProgramDesc::SetVersion(const int64_t version) {
  desc_.mutable_version()->set_version(version);
}

ProgramDesc::ProgramDesc() {
  SetVersion(kCurProgramVersion);
  auto *block = desc_.mutable_blocks()->Add();
  block->set_idx(kRootBlockIndex);
  block->set_parent_idx(kNoneBlockIndex);
  blocks_.emplace_back(new BlockDesc(this, block));
}

ProgramDesc::ProgramDesc(const ProgramDesc &o) {
  desc_ = o.desc_;
  std::vector<framework::BlockDesc *> old_block_desc;
  for (int i = 0; i < desc_.blocks_size(); ++i) {
    auto *block = desc_.mutable_blocks(i);
    blocks_.emplace_back(new BlockDesc(*o.blocks_[i], block, this));
    // record all block desc's ptr from origin program
    old_block_desc.emplace_back(o.blocks_[i].get());
  }
  for (size_t block_id = 0; block_id < blocks_.size(); ++block_id) {
    auto all_ops = blocks_[block_id]->AllOps();
    for (size_t op_id = 0; op_id < all_ops.size(); ++op_id) {
      auto &op = all_ops[op_id];

      for (const std::string &attr_name : op->AttrNames()) {
        if (op->GetAttrType(attr_name) == proto::AttrType::BLOCK) {
          framework::BlockDesc *block_desc =
              PADDLE_GET_CONST(framework::BlockDesc *, op->GetAttr(attr_name));
          if (std::find(old_block_desc.begin(),
                        old_block_desc.end(),
                        block_desc) != old_block_desc.end()) {
            // The block is owned by the origin program. Just use id to get
            // the corresponding block.
            int sub_block_id =
                o.Block(block_id).Op(op_id)->GetBlockAttrId(attr_name);
            op->SetBlockAttr(attr_name, MutableBlock(sub_block_id));
          } else {
            // The block is not owned by the origin program. Should copy
            // the real block desc instead of logical block in the program.
            VLOG(3) << "Set op's block attr with the original block";
            op->SetBlockAttr(attr_name, block_desc);
          }
        } else if (op->GetAttrType(attr_name) == proto::AttrType::BLOCKS) {
          std::vector<int> sub_block_ids =
              o.Block(block_id).Op(op_id)->GetBlocksAttrIds(attr_name);
          std::vector<BlockDesc *> block_descs;
          for (int block_id : sub_block_ids) {
            block_descs.push_back(MutableBlock(block_id));
          }
          op->SetBlocksAttr(attr_name, block_descs);
        } else if (op->GetAttrType(attr_name, true) == proto::AttrType::VAR) {
          VarDesc *var_desc =
              PADDLE_GET_CONST(VarDesc *, op->GetAttr(attr_name, true));
          op->SetVarAttr(attr_name,
                         o.Block(block_id).FindVarRecursive(var_desc->Name()));
        } else if (op->GetAttrType(attr_name, true) == proto::AttrType::VARS) {
          std::vector<VarDesc *> vars_desc = PADDLE_GET_CONST(
              std::vector<VarDesc *>, op->GetAttr(attr_name, true));
          std::vector<VarDesc *> new_vars_desc;
          std::transform(
              vars_desc.begin(),
              vars_desc.end(),
              std::back_inserter(new_vars_desc),
              [&](VarDesc *var_desc) {
                return o.Block(block_id).FindVarRecursive(var_desc->Name());
              });
          op->SetVarsAttr(attr_name, new_vars_desc);
        }
      }
    }
  }
}

ProgramDesc::ProgramDesc(const proto::ProgramDesc &desc) {
  desc_ = desc;
  InitFromProto();
}

void ProgramDesc::CopyFrom(const proto::ProgramDesc &desc) {
  blocks_.clear();
  desc_ = desc;
  InitFromProto();
}

ProgramDesc::ProgramDesc(const std::string &binary_str) {
  PADDLE_ENFORCE_EQ(desc_.ParseFromString(binary_str),
                    true,
                    platform::errors::InvalidArgument(
                        "Failed to parse program_desc from binary string."));
  InitFromProto();
}

void ProgramDesc::InitFromProto() {
  for (auto &block_desc : *desc_.mutable_blocks()) {
    blocks_.emplace_back(new BlockDesc(this, &block_desc));
  }
  for (auto &block : blocks_) {
    for (auto *op : block->AllOps()) {
      for (const auto &attr : op->Proto()->attrs()) {
        if (attr.type() == proto::AttrType::VAR) {
          std::string var_name = attr.var_name();
          VLOG(3) << "InitFromProto: SetVarAttr " << attr.name() << " from "
                  << var_name;
          op->SetVarAttr(attr.name(), op->FindVarRecursive(var_name));
        } else if (attr.type() == proto::AttrType::VARS) {
          auto vars_name = attr.vars_name();
          std::vector<VarDesc *> vars_desc;
          for (auto &var_name : vars_name) {
            VLOG(3) << "InitFromProto: SetVarsAttr " << attr.name() << " from "
                    << var_name;
            vars_desc.emplace_back(op->FindVarRecursive(var_name));
          }
          op->SetVarsAttr(attr.name(), vars_desc);
        } else if (attr.type() == proto::AttrType::BLOCK) {
          size_t blk_idx = attr.block_idx();
          op->SetBlockAttr(attr.name(), this->MutableBlock(blk_idx));
        } else if (attr.type() == proto::AttrType::BLOCKS) {
          auto blks_idx = attr.blocks_idx();
          std::vector<BlockDesc *> block_descs;
          for (int blk_idx : blks_idx) {
            block_descs.push_back(this->MutableBlock(blk_idx));
          }
          op->SetBlocksAttr(attr.name(), block_descs);
        }
      }
    }
  }
}

const std::vector<std::string> ProgramDesc::GetFeedTargetNames() {
  auto &global_block = Block(0);
  // The order of feed_target_names must follow the index specified in `col`.
  // since feed operator's order doesn't necessary follow 'col'.
  std::vector<std::string> feed_target_names;
  for (auto *op : global_block.AllOps()) {
    if (op->Type() == kFeedOpType) {
      size_t col = PADDLE_GET_CONST(int, op->GetAttr("col"));
      if (col >= feed_target_names.size()) {
        feed_target_names.resize(col + 1);
      }
      feed_target_names[col] = op->Output("Out")[0];
    }
  }
  return feed_target_names;
}

const std::vector<std::string> ProgramDesc::GetFetchTargetNames() {
  auto &global_block = Block(0);
  // The order of fetch_target_names must follow the index specified in `col`.
  // since fetch operator's order doesn't necessary follow 'col'.
  std::vector<std::string> fetch_target_names;
  for (auto *op : global_block.AllOps()) {
    if (op->Type() == kFetchOpType) {
      size_t col = PADDLE_GET_CONST(int, op->GetAttr("col"));
      if (col >= fetch_target_names.size()) {
        fetch_target_names.resize(col + 1);
      }
      fetch_target_names[col] = op->Input("X")[0];
    }
  }
  return fetch_target_names;
}

void ProgramDesc::SetFeedHolderName(const std::string &feed_holder_name) {
  auto *global_block = MutableBlock(0);
  int index = 0;
  for (auto *op : global_block->AllOps()) {
    if (op->Type() == kFeedOpType) {
      // Unify the input's name of all feed_ops to feed_holder_name
      global_block->RemoveVar(op->Input("X")[0]);
      op->SetInput("X", {feed_holder_name});
      op->SetAttr("col", {index});
      op->CheckAttrs();
      index++;
    }
  }

  auto *feed_holder = global_block->Var(feed_holder_name);
  feed_holder->SetType(proto::VarType::FEED_MINIBATCH);
  feed_holder->SetPersistable(true);
}

void ProgramDesc::SetFetchHolderName(const std::string &fetch_holder_name) {
  auto *global_block = MutableBlock(0);
  int index = 0;
  for (auto *op : global_block->AllOps()) {
    if (op->Type() == kFetchOpType) {
      // Unify the output's name of all fetch_ops to fetch_holder_name
      global_block->RemoveVar(op->Output("Out")[0]);
      op->SetOutput("Out", {fetch_holder_name});
      op->SetAttr("col", {index});
      op->CheckAttrs();
      index++;
    }
  }

  auto *fetch_holder = global_block->Var(fetch_holder_name);
  fetch_holder->SetType(proto::VarType::FETCH_LIST);
  fetch_holder->SetPersistable(true);
}

std::string ProgramDesc::CachedHashString() {
  std::string serialize_str;
  if (cached_hash_str_.size() == 0 || NeedUpdate()) {
    Flush();
    desc_.SerializePartialToString(&serialize_str);
    // non-cryptographic is enough
    cached_hash_str_ =
        std::to_string(XXH64(serialize_str.c_str(), serialize_str.size(), 1));
  }
  return cached_hash_str_;
}

bool ProgramDesc::NeedUpdate() const {
  bool need = false;
  for (auto &block : blocks_) {
    if (block->NeedUpdate()) {
      need = true;
      break;
    }
  }
  return need;
}

}  // namespace framework
}  // namespace paddle


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

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <view
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        class="com.larswerkman.holocolorpicker.ColorPicker"
        android:id="@+id/view_color_picker"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:text="Chon"
        android:id="@+id/button_okDialogPick"
        android:layout_below="@+id/view_color_picker"
        android:layout_alignRight="@+id/view_color_picker" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hủy bỏ"
        android:id="@+id/buttonCenDialogPick"
        android:layout_alignBottom="@+id/button_okDialogPick"
        android:layout_alignLeft="@+id/view_color_picker" />
</RelativeLayout><!-- From: file:/home/xdien/AndroidStudioProjects/Sua-anh/app/src/main/res/layout/dialog_color_pick.xml -->


text:
"""Test parenmatch, coverage 91%.

This must currently be a gui test because ParenMatch methods use
several text methods not defined on idlelib.idle_test.mock_tk.Text.
"""
from idlelib.parenmatch import ParenMatch
from test.support import requires
requires('gui')

import unittest
from unittest.mock import Mock
from tkinter import Tk, Text

class DummyEditwin:
    def __init__(self, text):
        self.text = text
        self.indentwidth = 8
        self.tabwidth = 8
        self.prompt_last_line = '>>>' # Currently not used by parenmatch.

class ParenMatchTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.root = Tk()
        cls.root.withdraw()
        cls.text = Text(cls.root)
        cls.editwin = DummyEditwin(cls.text)
        cls.editwin.text_frame = Mock()

    @classmethod
    def tearDownClass(cls):
        del cls.text, cls.editwin
        cls.root.update_idletasks()
        cls.root.destroy()
        del cls.root

    def tearDown(self):
        self.text.delete('1.0', 'end')

    def get_parenmatch(self):
        pm = ParenMatch(self.editwin)
        pm.bell = lambda: None
        return pm

    def test_paren_styles(self):
        """
        Test ParenMatch with each style.
        """
        text = self.text
        pm = self.get_parenmatch()
        for style, range1, range2 in (
                ('opener', ('1.10', '1.11'), ('1.10', '1.11')),
                ('default',('1.10', '1.11'),('1.10', '1.11')),
                ('parens', ('1.14', '1.15'), ('1.15', '1.16')),
                ('expression', ('1.10', '1.15'), ('1.10', '1.16'))):
            with self.subTest(style=style):
                text.delete('1.0', 'end')
                pm.STYLE = style
                text.insert('insert', 'def foobar(a, b')

                pm.flash_paren_event('event')
                self.assertIn('<<parenmatch-check-restore>>', text.event_info())
                if style == 'parens':
                    self.assertTupleEqual(text.tag_nextrange('paren', '1.0'),
                                          ('1.10', '1.11'))
                self.assertTupleEqual(
                        text.tag_prevrange('paren', 'end'), range1)

                text.insert('insert', ')')
                pm.restore_event()
                self.assertNotIn('<<parenmatch-check-restore>>',
                                 text.event_info())
                self.assertEqual(text.tag_prevrange('paren', 'end'), ())

                pm.paren_closed_event('event')
                self.assertTupleEqual(
                        text.tag_prevrange('paren', 'end'), range2)

    def test_paren_corner(self):
        """
        Test corner cases in flash_paren_event and paren_closed_event.

        These cases force conditional expression and alternate paths.
        """
        text = self.text
        pm = self.get_parenmatch()

        text.insert('insert', '# this is a commen)')
        pm.paren_closed_event('event')

        text.insert('insert', '\ndef')
        pm.flash_paren_event('event')
        pm.paren_closed_event('event')

        text.insert('insert', ' a, *arg)')
        pm.paren_closed_event('event')

    def test_handle_restore_timer(self):
        pm = self.get_parenmatch()
        pm.restore_event = Mock()
        pm.handle_restore_timer(0)
        self.assertTrue(pm.restore_event.called)
        pm.restore_event.reset_mock()
        pm.handle_restore_timer(1)
        self.assertFalse(pm.restore_event.called)

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


text:
package edu.cs4730.sqlitedemo;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import edu.cs4730.sqlitedemo.db.ScoreDatabase;
import edu.cs4730.sqlitedemo.db.mySQLiteHelper;

/**
 * A demo of sqlite.  It's very simple and just display some data to a textview.
 *   this is not very efficient and listview/recyclerview are much better suited for it.
 */
public class SqliteDemo_Fragment extends Fragment {

    String TAG = "sqlitedemo_frag";
    Button runAgain;

    TextView output;
    ScoreDatabase db;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View myView = inflater.inflate(R.layout.sqlitedemo_fragment, container, false);
        output = (TextView) myView.findViewById(R.id.textView1);
        db = new ScoreDatabase(requireContext());
        db.open();  //if database doesn't exist, it has now created.
        democode();
        runAgain = (Button) myView.findViewById(R.id.again);
        runAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                democode();
            }
        });
        return myView;
    }

    //a simple method to append information to the Textview
    public void appendthis(String item) {
        output.append(item + "\n");
    }

    //on resume, open the database again.
    @Override
    public void onResume() {
        super.onResume();
        if (db == null)
            db = new ScoreDatabase(requireContext());
        if (!db.isOpen())
            db.open();
    }

    //onclose, we are in the background, so just close the DB.
    @Override
    public void onPause() {
        super.onPause();
        if (db.isOpen())
            db.close();

    }

    /**
    *  This code will insert data into a empty DB and return.
    *  if there is data, then it will display information about the data in the table.
     */
    @SuppressLint("Range")
    public void democode() {
        appendthis("Start of Demo code.");

        Cursor c;
        //check to see if there is any data
        c = db.getAllNames();

        if (c == null) {
            //nothing in the database ?  maybe the database query failed.
            appendthis("No DB found, creating and inserting data");
            //insert data.
            db.insertName("Jim", 3012);
            db.insertName("Brandon", 312);
            return;
        }
        //check to see if no data?
        if (c.getCount() == 0) {
            //no data return
            appendthis("empty DB, inserting data");
            db.insertName("Jim", 3012);
            db.insertName("Brandon", 312);
            return;
        }
        appendthis("There is already data, so just displaying it.");
        //display any data.
        //moveToFirst() should not be needed, but just in case.
        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            //Column: 0 ROWID, 1 name, 2 score
            //We could just use c.getString(1) because we know column 1 is name, but it
            //not very readable and if we were change the DB, then this could would not work
            //instead using a longer, but more readable and DB change method.
            //so not using this appendthis(	c.getString(1) + " " + c.getInt(2));
            appendthis(c.getString(c.getColumnIndex(mySQLiteHelper.KEY_NAME)) + " " +
                    c.getInt(c.getColumnIndex(mySQLiteHelper.KEY_SCORE)));
        }
        c.close();  //release the resources, before I use it again.
        //test on return 1 item.

        c = db.get1name("Jim");  //test of query for 1.
        //A note, get1name only returns two columns, name and score.  while getall returns three
        //columns.

        //c = db.get1nameR("Jim");   //test of rawQuery
        if (c.getCount() == 0) {
            appendthis("failed on select 1 item.");
        } else {
            appendthis("Select on Jim returned: " +
                    c.getString(c.getColumnIndex(mySQLiteHelper.KEY_NAME)) + " " +  //column 0
                    c.getInt(c.getColumnIndex(mySQLiteHelper.KEY_SCORE))            //column 1
            );
        }
        c.close(); //release the resources
    }

}


text:
<?php

/**
 * EchoStatement
 *
 * Produce output according to the type
 */
class EchoStatement
{
	protected $_statement;

	public function __construct($statement)
	{
		$this->_statement = $statement;
	}

	public function compile(CompilationContext $compilationContext)
	{
		foreach ($this->_statement['expressions'] as $expr) {

			$expr = new Expression($expr);
			$expr->setReadOnly(true);
			$resolvedExpr = $expr->compile($compilationContext);

			switch ($resolvedExpr->getType()) {
				case 'int':
					$compilationContext->codePrinter->output('php_printf("%d", ' . $resolvedExpr->getCode() . ');');
					break;
				case 'bool':
					$compilationContext->codePrinter->output('php_printf("%s", ' . $resolvedExpr->getBooleanCode() . ' ? "1": "");');
					break;
				case 'double':
					$compilationContext->codePrinter->output('php_printf("%f", ' . $resolvedExpr->getCode() . ');');
					break;
				case 'char':
					$compilationContext->codePrinter->output('php_printf("%c", \'' . $resolvedExpr->getCode() . '\');');
					break;
				case 'long':
					$compilationContext->codePrinter->output('php_printf("%ld", ' . $resolvedExpr->getCode() . ');');
					break;
				case 'string':
					$compilationContext->codePrinter->output('php_printf("' . Utils::addSlashes($resolvedExpr->getCode()) . '");');
					break;
				case 'variable':
					$variable = $compilationContext->symbolTable->getVariableForRead($resolvedExpr->getCode(), $compilationContext, $expr);
					switch ($variable->getType()) {
						case 'int':
							$compilationContext->codePrinter->output('php_printf("%d", ' . $variable->getName() . ');');
							break;
						case 'long':
							$compilationContext->codePrinter->output('php_printf("%ld", ' . $variable->getName() . ');');
							break;
						case 'char':
							$compilationContext->codePrinter->output('php_printf("%c", ' . $variable->getName() . ');');
							break;
						case 'string':
						case 'variable':
							$compilationContext->codePrinter->output('zend_print_zval(' . $variable->getName() . ', 0);');
							break;
						default:
							throw new CompilerException("Unknown type: " . $variable->getType(), $expr);
					}
					break;
				default:
					throw new CompilerException("Unknown type: " . $resolvedExpr->getType(), $expr);
			}
		}
	}

}


text:
package groovy.lang;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

/**
 * A wrapper for Map which allows a default value to be specified.
 *
 * @since 1.7.1
 */
public final class MapWithDefault<K, V> implements Map<K, V> {

    private final Map<K, V> delegate;
    private final Closure initClosure;

    private MapWithDefault(Map<K, V> m, Closure initClosure) {
        delegate = m;
        this.initClosure = initClosure;
    }

    public static <K, V> Map<K, V> newInstance(Map<K, V> m, Closure initClosure) {
        return new MapWithDefault<K, V>(m, initClosure);
    }

    @Override
    public int size() {
        return delegate.size();
    }

    @Override
    public boolean isEmpty() {
        return delegate.isEmpty();
    }

    @Override
    public boolean containsKey(Object key) {
        return delegate.containsKey(key);
    }

    @Override
    public boolean containsValue(Object value) {
        return delegate.containsValue(value);
    }

    @Override
    public V get(Object key) {
        if (!delegate.containsKey(key)) {
            delegate.put((K)key, (V)initClosure.call(new Object[]{key}));
        }
        return delegate.get(key);
    }

    @Override
    public V put(K key, V value) {
        return delegate.put(key, value);
    }

    @Override
    public V remove(Object key) {
        return delegate.remove(key);
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        delegate.putAll(m);
    }

    @Override
    public void clear() {
        delegate.clear();
    }

    @Override
    public Set<K> keySet() {
        return delegate.keySet();
    }

    @Override
    public Collection<V> values() {
        return delegate.values();
    }

    @Override
    public Set<Map.Entry<K, V>> entrySet() {
        return delegate.entrySet();
    }

    @Override
    public boolean equals(Object obj) {
        return delegate.equals(obj);
    }

    @Override
    public int hashCode() {
        return delegate.hashCode();
    }
}


text:
<?php use_javascript('convocatoria.js') ?>

<?php slot('title', 'SAF .::Vista Convocatoria::.') ?>
<?php slot('menu_activo_convocatoria','active') ?>

 VISTA CONVOCATORIA  N° <?php echo $convocatoria->getId() ?>

  <?php if ($convocatoria->getStatus() == 'ACTIVA'): ?>
    La convocatoria esta ACTIVA
    <?php if ($sf_user->hasCredential('crear_convocatoria')) : ?>
      para
      <a href="<?php echo url_for('@cambiar_status_convocatoria?id=' . $convocatoria . '&status=EJECUCION') ?>" id="realizar_comite">
         realizar el comité

      en la fecha indicada.
    <?php endif; ?>
  <?php elseif ($convocatoria->getStatus() == 'EJECUCION'): ?>
    La convocatoria esta en EJECUCIÓN. Se esta realizando el comité.
  <?php elseif ($convocatoria->getStatus() == 'TERMINADA'): ?>
    La convocatoria esta TERMINADA. Comité realizado exitosamente.
  <?php elseif ($convocatoria->getStatus() == 'SUSPENDIDA'): ?>
    La convocatoria esta SUSPENDIDA.
    <?php echo $convocatoria->getMotivoSuspencion() ?>
  <?php endif; ?>

      Asunto:
      <?php echo $convocatoria->getAsunto() ?>

      Lugar:
      <?php echo $convocatoria->getLugar() ?>

      Fecha:
      <?php echo substr($convocatoria->getFecha(), 0, 10) . "  de " .
              $convocatoria->getHoraIni(). " a " .$convocatoria->getHoraFin()?>

      Observaciones:

      <?php echo $convocatoria->getObservacion() ?>

        <?php if ($convocatoria->getStatus() == 'ACTIVA' && $sf_user->hasCredential('crear_convocatoria')) : ?>
           Suspender
          <input type="checkbox" id="suspender_convocatoria" value="<?php echo url_for('@cambiar_status_convocatoria?id=' . $convocatoria->getId() . '&status=SUSPENDIDA') ?>" />

        <?php endif; ?>

        Fecha de creación:
        <?php echo $convocatoria->getCreatedAt() ?>

        Fecha de modificación:
        <?php echo $convocatoria->getUpdatedAt() ?>

<?php include_partial('global/eventos', array('eventos' => $eventos, 'no_column_check' => true)) ?>

<a href="<?php echo url_for('@index_convocatoria') ?>">
   Regresar


text:
# Resources

The subdirectories of the resources directory (src/resources and build/resources) contain the pieces that will be
used to create Epilogue resources. Custom resource
specific files should be added to its corresponding resource's
resources folder. The User resource is a special resource.
The Todo and Neighborhood resources are just examples.

```javascript
// An example resource's index.js
import extension from './extension';
import model from './model';
import milestones from './milestones';

const endpoints = ['/todos', '/todos/:id'];
const permissions = 'lcrud|-----|-----|-----';
const isGroup = false;
const autoAssociations = '';

const exportArray = ['Todo', permissions, model, endpoints, extension, autoAssociations, isGroup, milestones];

export default exportArray;
```

## Models

Models are normal sequelize models. They are defined in the
model.js files found in a resource's resource folder. The default
fields that get added to the models are defined in
src/resourcesBuilder/modelFields.js.

## Milestones

By default, milestones will be generated for a resource in
epilogueAuth.js for handling user access to resources and
non-standard effects of their operations (For example: Owning
an instance of a resources as a group or user after creating
it). The milestones.js code in a resource folder is for resource specific milestone code.
This custom milestone code will be merged with the built
in milestones when the resources' milestones are add to the
resources.

## Extensions

Extensions are combined with a resource's model and endpoints
to create a temporary resource object that will used to form
an Epilogue resource. Resource properties that don't belong in
the model or the endpoints, like `associations: true`, should
be put in the resource folder's extension.js file.

## Resource Array

An example of a resource array:

```javascript
const exportArray = ['Todo', permissions, model, endpoints, extension, autoAssociations, isGroup, milestones];
```

There are 8 elements to the resource array, with their purpose
being implied by their names in the example above. Order
matters and if you want to leave an element blank, replace it
with a falsy element rather than leaving it out altogether.

## Auto Associations

Auto Associations in Epilogue Starter Kit are the same Auto
Associations that are found in Epilogue.
What is unique is how they are assigned to resources. The
default auto association is hasMany. There can be associations
without auto associations. They are the 6th element
of the exported resource array. This element will be converted
to a standard Auto Association format.

#### Format

* String, array, object or boolean.
* The preferred format is the array of objects format.
* Array styles can be mixed.
* Though false is acceptable, an empty string should be used instead if you don't
  want to create an auto-association on that resource. This is because
  an auto-association with that resource could be on another resource,
  making false misleading.

**Examples:**

```javascript
'' => []
false => []
'Cake' => [{ hasMany: 'Cake' }]
'Cake,Soda' => [{ hasMany: 'Cake' }, { hasMany: 'Soda' }]
'Cake|Soda' => [{ hasMany: 'Cake' }, { hasMany: 'Soda' }]
{ hasMany: 'Cake' } => [{ hasMany: 'Cake' }]
['Cake', 'Soda'] => [{ hasMany: 'Cake' }, { hasMany: 'Soda' }]
[{ hasMany: 'Cake' }, { belongsTo: 'Soda' }] => [{ hasMany: 'Cake' }, { belongsTo: 'Soda' }]
['Cake', { belongsTo: 'Soda' }] => [{ hasMany: 'Cake' }, { belongsTo: 'Soda' }]
```

## Permissions

The term operations used here means Epilogue resource
operations (List, Create, Read, Update and Delete).
Permissions are used to determine what operations are
available for certain users. The types of users are the
following: owners of the resource (usually the user who created
the resource), members of a group resource, any non-guest
users and all users. Permissions are similar to auto
associations in that there are multiple formats that can be
used to set them up for a resource.

#### Format

* String, array, number or object.
* 4 bytes. In left to right order: owner, group, non-guest, all.
* 5 bits for each byte. In left to right order: list, create, read, update, destroy.
* 2 special bits (See the Admins and Groups subsections).
* The preferred format is string with | separating user
type bytes, letters (l, c, r, u or d) enabling operations
and - disallowing operations (See the 5th example).
* For number format, the list and read bits are the same. This was
done to make hexadecimal permissions more readable. Decimal, octal
and binary are also valid.

**Examples:**

```javascript
[] => [false, ..., false]
0xFFFF => [true, ..., true]
'lcrudlcrudlcrudlcrud' => [true, ..., true]
'lcrud|lcrud|lcrud|lcrud' => [true, ..., true]
'l-rud|lcrud|lcrud|lcrud' => [true, false, true, true, ..., true]
'lrud|lcrud|lcrud|lcrud' => [true, false, true, true, ..., true]
{owner: ['l', 'c', 'r']} => [true, true, true, false, false, ..., false]
[true, ..., true] => [true, ..., true]
/*
  See test/unitTests/permissions/conversions.js for
  more examples of valid permissions formats
*/
```

## Admins

The enabled bit in `-c---|-----|----|-----` means that admins
can create an instance of that resource. The list of admin
users is in the Admins table, with AdminId being the admin's
user id.

## Groups

Groups and users are linked
through the userGroupXrefs resource. Users can have many groups through group xrefs.

The enabled bit in `-----|-c---|----|-----` enables group permissions.
Group permissions are bitwise ORed with each other and regular resource permissions.

For example, if a group resource called City has the following regular
 permissions:

`l----|-c---|----|-----`

And the following group permissions:

| Resource  | Permissions | Group Name  | Group ID |
| --------- | ---------- | ----------- | -------- |
| City | -----\|l--ud\|-----\|----- | NYC | 1 |
| City | -----\|l-r--\|-crud\|-----  | | |

There will be the following permissions for these City groups:

| Group  | Permissions |
| --------- | ---------- |
| NYC | l----\|lcrud\|-crud\|----- |
| LA | l----\|lcr--\|-crud\|-----  |

## Creating and Deleting Resources

Use the command `gulp new-resource` to create new resources. To delete
a resource, delete its directory in resources/ and update
resources/index.js


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace WebAssembly;

/// <summary>
/// Describes a global variable.
/// </summary>
public class Global
{
    /// <summary>
    /// Type of the value.
    /// </summary>
    public WebAssemblyValueType ContentType { get; set; }

    /// <summary>
    /// When true, the value can be changed by running code.
    /// </summary>
    public bool IsMutable { get; set; }

    [DebuggerBrowsable(DebuggerBrowsableState.Never)] //Wrapped by a property
    private IList<Instruction>? initializerExpression;

    /// <summary>
    /// The initial value of the global.
    /// </summary>
    /// <exception cref="ArgumentNullException">Value cannot be set to null.</exception>
    public IList<Instruction> InitializerExpression
    {
        get => this.initializerExpression ??= new List<Instruction>();
        set => this.initializerExpression = value ?? throw new ArgumentNullException(nameof(value));
    }

    /// <summary>
    /// Creates a new <see cref="Global"/> instance.
    /// </summary>
    public Global()
    {
    }

    /// <summary>
    /// Creates a new <see cref="Global"/> instance with the provided content type.
    /// </summary>
    /// <param name="contentType">The <see cref="ContentType"/> value.</param>
    public Global(WebAssemblyValueType contentType)
    {
        this.ContentType = contentType;
    }

    /// <summary>
    /// Creates a new <see cref="Global"/> instance with the provided content type and initializer expression.
    /// </summary>
    /// <param name="contentType">The <see cref="ContentType"/> value.</param>
    /// <param name="initializerExpression">The <see cref="InitializerExpression"/> value.</param>
    public Global(WebAssemblyValueType contentType, params Instruction[] initializerExpression)
    {
        this.ContentType = contentType;
        this.initializerExpression = initializerExpression;
    }

    internal Global(Reader reader)
    {
        this.ContentType = (WebAssemblyValueType)reader.ReadVarInt7();
        this.IsMutable = reader.ReadVarUInt1() == 1;
        this.InitializerExpression = Instruction.ParseInitializerExpression(reader).ToList();
    }

    internal void WriteTo(Writer writer)
    {
        writer.WriteVar((sbyte)this.ContentType);
        writer.WriteVar(this.IsMutable ? 1u : 0);
        foreach (var instruction in this.InitializerExpression)
            instruction.WriteTo(writer);
    }
}


text:
package io.deepsense.deeplang.doperations

import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll, FreeSpec}

import io.deepsense.deeplang.utils.DataFrameMatchers
import io.deepsense.deeplang.{InMemoryDataFrame, LocalExecutionContext, TestDataSources, TestFiles}

class WriteReadDatasourceIntegSpec
  extends FreeSpec with BeforeAndAfter with BeforeAndAfterAll
    with LocalExecutionContext with InMemoryDataFrame with TestFiles with TestDataSources {

  for (ds <- someDatasourcesForWriting) {
    s"`${ds.getParams.getName}` datasource should be readable and writeable" in {
      val wds = WriteDatasource().setDatasourceId(ds.getId)
      wds.execute(inMemoryDataFrame)(context)

      val rds = ReadDatasource().setDatasourceId(ds.getId)
      val dataframe = rds.execute()(context)

      DataFrameMatchers.assertDataFramesEqual(dataframe, inMemoryDataFrame)
    }
  }

  private val context = LocalExecutionContext.createExecutionContext(datasourceClient)

}


text:
//
// Copyright (c) Microsoft.  All rights reserved.
//
// 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.
//

using System;

namespace Microsoft.Azure.Management.DataFactories.Models
{
    /// <summary>
    /// A copy activity sink.
    /// </summary>
    public abstract class CopySink : CopyLocation
    {
        /// <summary>
        /// Write batch size.
        /// </summary>
        public int WriteBatchSize { get; set; }

        /// <summary>
        /// Write batch timeout.
        /// </summary>
        public TimeSpan WriteBatchTimeout { get; set; }

        /// <summary>
        /// Sink retry count.
        /// </summary>
        public int? SinkRetryCount { get; set; }

        /// <summary>
        /// Sink retry wait.
        /// </summary>
        public TimeSpan? SinkRetryWait { get; set; }

        protected CopySink()
        {
        }

        protected CopySink(int writeBatchSize, TimeSpan writeBatchTimeout)
            : this()
        {
            this.WriteBatchSize = writeBatchSize;
            this.WriteBatchTimeout = writeBatchTimeout;
        }
    }
}


text:
package main

import (
	"encoding/json"
	"fmt"
	"github.com/easy-bot/ackproxy/response"
	"log"
	"net/http"
	"net/url"
	"os"
	"time"
)

var queue []response.Ack
var akey string = os.Getenv("NAGIOS_API_KEY")

func Log(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL)
		h.ServeHTTP(w, r)
	})
}

func Auth(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Query().Get("k") != akey {
			http.Error(w, "forbidden", http.StatusUnauthorized)
			return
		}
		h(w, r)
	}
}

func ackhandler(w http.ResponseWriter, r *http.Request) {

	if r.URL.Query().Get("h") == "" || r.URL.Query().Get("u") == "" {
		http.Error(w, "Invalid", http.StatusBadRequest)
		return
	}

	a := response.Ack{}

	a.User = r.URL.Query().Get("u")
	a.Key = r.URL.Query().Get("k")
	a.Host = r.URL.Query().Get("h")
	a.Date = time.Now().Unix()

	//service names are urlencoded because they can contain spaces
	if r.URL.Query().Get("s") != "" {
		u := &url.URL{Path: r.URL.Query().Get("s")}
		a.Service = u.Path
	}

	log.Printf("Ack{User: %s, Key: %s, Host: %s, Service: %s}\n", a.User, a.Key, a.Host, a.Service)

	if len(queue) >= 25 {
		queue = append(queue[:0], queue[1:]...)
	}

	queue = append(queue, a)

	fmt.Fprintf(w, "Success, %d commands queued.", len(queue))

}

func stats(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "%d commands queued", len(queue))
}

func dequeue(w http.ResponseWriter, r *http.Request) {
	if queue != nil {
		j, _ := json.Marshal(queue)
		fmt.Fprintf(w, "%s", j)
		queue = nil
	}
}

func main() {

	log.Printf("In main queue(%p) = %d", &queue, cap(queue))

	if len(akey) < 30 {
		log.Fatal("Must set NAGIOS_API_KEY to something pretty secure")
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "nope", http.StatusForbidden)
	})
	http.HandleFunc("/stats", Auth(stats))
	http.HandleFunc("/dequeue", Auth(dequeue))
	http.HandleFunc("/ack", Auth(ackhandler))
	http.ListenAndServe(":8080", Log(http.DefaultServeMux))

}


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe "GET" do

  describe "resource(@article, :editors)", :given => "an Article exists" do

    before(:each) do
      @response = request(resource(Article.first, :editor, :new))
    end

    it "should not respond to the :index action" do
      lambda {
        request(resource(Article.first, :editors))
      }.should raise_error(Merb::Router::GenerationError)
    end

  end

  describe "resource(@article, :editor, :new)", :given => "an Article exists" do

    before(:each) do
      @response = request(resource(Article.first, :editor, :new))
    end

    it "should respond successfully" do
      @response.should be_successful
    end

    it "should render the :new template" do
      @response.should have_selector("h2:contains('New Editor')")
    end

  end

  describe "resource(@article, :editor)", :given => "an Editor exists" do

    before(:each) do
      @response = request(resource(Article.first, :editor))
    end

    it "should respond successfully" do
      @response.should be_successful
    end

  end

  describe "resource(@article, :editor, :edit)", :given => "an Editor exists" do

    before(:each) do
      @response = request(resource(Article.first, :editor, :edit))
    end

    it "should respond successfully" do
      @response.should be_successful
    end

  end

end

describe "POST resource(@article, :editor)" do

  describe "Success", :given => "an Article exists" do

    before(:each) do
      Editor.all.destroy!
      @response = request(
        resource(Article.first, :editor),
        :method => "POST",
        :params => {
          :editor => {
            :id => nil,
            :name => "snusnu"
          }
        }
      )
    end

    it "should redirect to resource(@article, :editor)" do
      @response.should redirect_to(
        resource(Article.first, :editor),
        :message => {
          :notice => "Editor was successfully created"
        }
      )
    end

  end

  describe "Failure", :given => "an Article exists" do

    before(:each) do
      Editor.all.destroy!
      @response = request(resource(Article.first, :editor),
        :method => "POST",
        :params => {
          :editor => {
            :id => nil,
            :name => nil
          }
        }
      )
    end

    it "should not be successful" do
      @response.should_not be_successful
      @response.status.should == 406
    end

    it "should render the :new action" do
      @response.should have_selector("h2:contains('New Editor')")
    end

  end

end

describe "PUT resource(@article, :editor)", :given => "an Editor exists" do

  describe "Success" do

    before(:each) do
      @response = request(
        resource(Article.first, :editor),
        :method => "PUT",
        :params => {
          :editor => {
            :id => Editor.first.id,
            :name => "bender"
          }
        }
      )
    end

    it "should redirect to resource(@article, :editor)" do
      @response.should redirect_to(resource(Article.first, :editor))
    end

  end

  describe "Failure" do

    before(:each) do
      @response = request(
        resource(Article.first, :editor),
        :method => "PUT",
        :params => {
          :editor => {
            :id => Editor.first.id,
            :name => nil
          }
        }
      )
    end

    it "should not be successful" do
      @response.should_not be_successful
      @response.status.should == 406
    end

    it "should render the :edit template" do
      @response.should have_selector("h2:contains('Edit Editor')")
    end

  end

end

describe "DELETE resource(@article, @editor)" do

  describe "Success", :given => "an Editor exists" do

    before(:each) do
      @response = request(
        resource(Article.first, :editor),
        :method => "DELETE"
      )
    end

    it "should redirect to resource(@article)" do
      @response.should redirect_to(resource(Article.first))
    end

  end

  describe "Failure", :given => "an Article exists" do

    before(:each) do
      @response = request(
        resource(Article.first, :editor),
        :method => "DELETE"
      )
    end

    it "should not be successful" do
      @response.should_not be_successful
      @response.status.should == 404
    end

  end

end


text:
require_dependency File.join(Gem.loaded_specs['acts_as_activity_logged'].full_gem_path, 'lib', 'activity_log')

class ActivityLog  < ActiveRecord::Base

  enforce_authorization_on_association :activity_loggable,:view
  serialize :data

  scope :no_spider,:conditions=>"(user_agent NOT LIKE '%spider%' OR user_agent IS NULL)"

  #returns items that have duplicates for a given action - NOTE that the result does not contain all the actual duplicates.
  scope :duplicates, lambda {|action|
    {
    :select=>"id,created_at,activity_loggable_type,activity_loggable_id,action,count(activity_loggable_id+activity_loggable_type) as dup_count",
    :conditions=>"action='#{action}' and controller_name!='sessions'",
    :group=>"activity_loggable_type,activity_loggable_id having dup_count>1"
    }
  }

  def self.remove_duplicate_creates
    duplicates=ActivityLog.duplicates "create"
    duplicates.each do |duplicate|
      matches = ActivityLog.where(:activity_loggable_id=>duplicate.activity_loggable_id, :activity_loggable_type=>duplicate.activity_loggable_type, :action=>"create").order("created_at ASC")
      (1...matches.count).to_a.each do |index|
        matches[index].destroy
      end
    end
  end

  def check_loggable_is_viewable
    result = true
    if activity_loggable && !activity_loggable.can_view?
      errors.add(:base,"the asset is not viewable")
      result = false
    end
    result
  end

end


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>My Sample Blog - Sample Author</title>
        <link rel="stylesheet" href="/theme/css/main.css" />
        <link href="/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="My Sample Blog Atom Feed" />

My Sample Blog  Blogs, Blags, and Blagollas

About

Contact

posts

This is a sample post

        ene 01 2014
| tags: blogsample

This is a sample post powered by Pelican.

The fields at the top are meta data about the post. Pelican will read those fields and generate the title, author, dates, and other content based up on it. Most should be self explanatory.

slug refers to the final filename of the post. For example this post is "sample-post-for-pelican-powered-blog.md" so Pelican will generate a file named "sample-post-for-pelican-powered-blog.html" which is what will appear in the address bar of your browser. Note that this can be different that the title of the post. The point of this attribute is to have a consistent name for the page that will never change even if the title/content changes.

tags are comma seperated list of metadata describing your posts. They're optional but if you add them to your posts the Pelican will automatically generate pages listing your posts by tag. For example you could have all your 'foobar' organized together.

summary refers to the text summary that will appear on the front page of your blog.

And here is how you add a image:

    Page 1 / 1

social

atom feed

Powered by Pelican. Theme blueidea, inspired by the default theme.


text:
namespace HelpScout.Conversations.Models.List
{
    public class Source
    {
        public string Type { get; set; }
        public string Via { get; set; }
    }
}


text:
printenv

if [[ -z "$BetaseriesAPIKey" ]]; then
	echo "BetaseriesAPIKey is not defined!"
	exit 1
fi

if [[ -z "$BetaseriesAPISecret" ]]; then
	echo "BetaseriesAPISecret is not defined!"
	exit 1
fi

if [[ -z "$$MixpanelAPIKey" ]]; then
	echo "$MixpanelAPIKey is not defined: setting empty key"
	MixpanelAPIKey="Mixpanel"
fi

if [[ -z "$CRASHLYTICS_BUILD_SECRET" ]]; then
	echo "CRASHLYTICS_BUILD_SECRET is not defined!"
	exit 1
fi

if [[ -z "$CRASHLYTICS_API_KEY" ]]; then
	echo "CRASHLYTICS_API_KEY is not defined!"
	exit 1
fi

echo "Setting values to \`Keys.plist\` file"
/usr/libexec/PlistBuddy -c "Add BetaseriesAPIKey String $BetaseriesAPIKey" Rewatch/Resources/Keys.plist
/usr/libexec/PlistBuddy -c "Add BetaseriesAPISecret String $BetaseriesAPISecret" Rewatch/Resources/Keys.plist
/usr/libexec/PlistBuddy -c "Add MixpanelAPIKey String $MixpanelAPIKey" Rewatch/Resources/Keys.plist

echo "Setting values to \`xcconfig\` file"
echo "CRASHLYTICS_BUILD_SECRET = $CRASHLYTICS_BUILD_SECRET" >> Rewatch/Resources/Rewatch.xcconfig
echo "CRASHLYTICS_API_KEY = $CRASHLYTICS_API_KEY" >> Rewatch/Resources/Rewatch.xcconfig


text:
module Mimi
  class Application
    module DSL
      extend ActiveSupport::Concern

      class_methods do
        #
        #
        def configure(opts = nil, &block)
          if opts
            super(opts)
          else
            register_event_handler(:configure, block)
          end
        end

        # Registers handler
        #
        def on(event, &block)
          register_event_handler(event, block)
        end

        # Registers 'every <sec>' handler
        #
        def every(seconds, &block)
          if !seconds.is_a?(Numeric) || seconds <= 0
            raise ArgumentError, 'Positive number of seconds is expected as an argument'
          end
          wrap_block = proc do
            @every_block_opts ||= {}
            opts = @every_block_opts[block.object_id] || {}
            next_run_at = opts[:next_run_at]
            next if next_run_at && next_run_at >= Time.now
            block.call
            opts[:next_run_at] = Time.now + seconds
            @every_block_opts[block.object_id] = opts
          end
          register_event_handler(:every, wrap_block)
        end

        # Registers event handler
        #
        def register_event_handler(event, block, opts = {})
          @event_handlers ||= []
          @event_handlers << { event: event, block: block, options: opts }
        end

        # Returns list of event handlers, including those defined in a subclass
        #
        def event_handlers
          local_event_handlers = @event_handlers || []
          return local_event_handlers unless superclass.respond_to?(:event_handlers)
          superclass.event_handlers + local_event_handlers
        end
      end
    end # module DSL
  end # class Application
end # module Mimi


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
|	example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
|	http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
|	$route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
|	$route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
|	$route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples:	my-controller/index	-> my_controller/index
|		my-controller/my-method	-> my_controller/my_method
*/
$route['default_controller'] = 'site';
$route['404_override'] = 'site/badrequest';
$route['translate_uri_dashes'] = TRUE;
$route['mapa'] = 'site/map';
$route['map'] = 'site/map';
$route['institucion/alias/(:any)'] = 'site/institutionByAlias/$1';
$route['institution/alias/(:any)'] = 'site/institutionByAlias/$1';
$route['institucion/codigo/(:any)'] = 'site/institutionByCode/$1';
$route['institution/code/(:any)'] = 'site/institutionByCode/$1';
$route['mapa/(:any)'] = 'site/map/$1';
$route['map/(:any)'] = 'site/map/$1';
$route['el-proyecto'] = 'site/theproject';
$route['the-proyecto'] = 'site/theproject';
$route['agregar-institucion'] = 'site/new_institution';
$route['add-institution'] = 'site/new_institution';
$route['formulario-institucion'] = 'site/save_institution';
$route['form-institution'] = 'site/save_institution';
$route['contacto'] = 'site/contactus';
$route['contactus'] = 'site/contactus';
$route['contacto/(:any)'] = 'site/contactus/$1';
$route['contactus/(:any)'] = 'site/contactus/$1';
$route['como-ayudar'] = 'site/helpus';
$route['helpus'] = 'site/helpus';
$route['ayuda'] = 'site/help';
$route['help'] = 'site/help';
$route['announcements'] = 'site/announcements';
$route['anuncios'] = 'site/announcements';
$route['sitio-offline'] = 'site/siteoffline';
$route['site-offline'] = 'site/siteoffline';
$route['confirm'] = 'site/confirm';
$route['buscar'] = 'site/search/$1';
$route['search'] = 'site/search/$1';
$route['confirm/(:any)'] = 'site/confirm/$1';
$route['download/(:any)'] = 'site/download/$1';
$route['enviar-formulario'] = 'site/sendForm';
$route['send-form'] = 'site/sendForm';


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

namespace _05_Compare_Char_Arrays
{
    //Compare two char arrays lexicographically (letter by letter).
    //Print them in alphabetical order, each on separate line.

    class CompareCharArrays
    {
        static void Main(string[] args)
        {
            char[] firstArray = Console.ReadLine().Split(' ').Select(char.Parse).ToArray();
            char[] secondArray = Console.ReadLine().Split(' ').Select(char.Parse).ToArray();
            int minLength = Math.Min(firstArray.Length, secondArray.Length);
            AlphabeticalOrder(firstArray, secondArray, minLength);
        }
        static void AlphabeticalOrder(char[] firstArray, char[] secondArray, int minLength)
        {
            for (int i = 0; i < minLength; i++)
            {
                if (firstArray[i] < secondArray[i])
                {
                    Console.WriteLine(firstArray);
                    Console.WriteLine(secondArray);
                    break;
                }
                else if (firstArray[i] > secondArray[i])
                {
                    Console.WriteLine(secondArray);
                    Console.WriteLine(firstArray);
                    break;
                }
                else if (firstArray[i] == secondArray[i])
                {
                    checkingLengths(firstArray, secondArray, minLength);
                    break;
                }
            }
        }
        static void checkingLengths(char[] firstArray, char[] secondArray, int minLength)
        {
            if (firstArray.Length == secondArray.Length)
            {
                Console.WriteLine(firstArray);
                Console.WriteLine(secondArray);
            }
            else if (firstArray.Length != secondArray.Length)
            {
                Console.WriteLine(firstArray.Length > secondArray.Length ? secondArray : firstArray);
                Console.WriteLine(firstArray.Length < secondArray.Length ? secondArray : firstArray);
            }
        }
    }
}


text:
<?php
namespace Project\Application\Http\Views\Builders;

use Opulence\Views\Factories\IViewBuilder;
use Opulence\Views\IView;

/**
 * Defines the HTML error page view builder
 */
class HtmlErrorBuilder implements IViewBuilder
{
    /**
     * @inheritdoc
     */
    public function build(IView $view) : IView
    {
        $view->setVar('title', 'Error');

        return $view;
    }
}


text:
<?php

namespace MilleEtangs\RandonneesBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;

class Builder extends ContainerAware
{
    public function mainMenu(FactoryInterface $factory, array $options)
    {
        $menu = $factory->createItem('main');
        $menu->setChildrenAttributes(array('class' => 'nav navbar-nav'));
        $menu->setUri($this->container->get('request')->getRequestUri());

        $menu->addChild('Accueil', array('route' => 'home'));
        $menu->addChild('Actualités', array('route' => 'articles'));
        $menu->addChild('Randonnées', array('route' => 'itinearies'));
        $menu->addChild('Les Mille Étangs', array('route' => 'mille_etangs'));

        return $menu;
    }
}


text:
@interface BSNumber ()

@property (nonatomic, strong, readwrite) BSConnection *connection;
@property (nonatomic, strong, readwrite) BSCountry *country;
@property (nonatomic, strong, readwrite) NSString *numberID;
@property (nonatomic, strong, readwrite) NSNumber *recipientNumber;

@end

@implementation BSNumber

#pragma mark - Properties

- (NSString *)numberID
{
	return [BSHelper isNilOrEmpty:_numberID] ? @"0" : [_numberID isKindOfClass:[NSNumber class]] ? [(NSNumber *)_numberID stringValue] : _numberID;
}

- (NSNumber *)recipientNumber
{
	return _recipientNumber ? _recipientNumber : @0;
}

#pragma mark - Initialization

- (instancetype)initWithID:(NSString *)objectID andTitle:(NSString *)title
{
	if (self = [super initWithID:@"-1" andTitle:@"Irregular number"]) {

	}
	return self;
}

- (BSNumber *)initWithID:(NSString *)nID
				 country:(BSCountry *)nCountry
			  connection:(BSConnection *)nConnection
	  andRecipientNumber:(NSNumber *)nNumber
{
	if (self = [super initWithID:@"0" andTitle:@"Number"]) {

		_numberID = nID;
		_recipientNumber = nNumber;
		_country = nCountry;
		_connection = nConnection;

	}
	return self;
}

@end


text:
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;
using Pizza.Persistence;

namespace Pizza.Framework.Persistence.Config.Conventions
{
    public class VersionedConvention : IVersionConvention
    {
        public void Apply(IVersionInstance instance)
        {
            if (typeof(IVersionable).IsAssignableFrom(instance.EntityType))
            {
                instance.Generated.Always();
            }
        }
    }
}


text:
package com.sasbury.genetik.driver;

import com.sasbury.genetik.reporting.*;

public interface RunContext
{
    public void saveData(String name,String data);
    public void saveRunData(Run run,String name,String data);

    public String getData(String name);
    public String getRunData(Run run,String name);

    public Statistics getStats();
}


text:
@implementation InitialViewController

@synthesize mainViewController, tutorialTableView, tutorialTableViewCell, indicatorView, continueButton, crossButton;
@synthesize informativeLabel, headerLabel, descriptionOneLabel, descriptionTwoLabel, initializeDBOneLabel, initializeDBTwoLabel;
@synthesize imageViewDefault, imageViewProgress, imageViewWireframe, imageViewFeatures, imageViewSwipeArrow;

#pragma mark - Custom initialization

- (void)viewDidLoad{[super viewDidLoad];[self loadObjects];}
- (void)loadObjects{

    // background color
    [self.view setBackgroundColor:[UIColor whiteColor]];
}

#pragma mark - Options

// Welcome : start
- (void)welcomeStart{

    // imageView : default
    imageViewDefault = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[self getCorrectImageName:[NSNumber numberWithInteger:tutorialElementDefaultView]]]];
    imageViewDefault.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, [self getCorrectHeightValue:[NSNumber numberWithInteger:tutorialElementDefaultView]]);imageViewDefault.alpha = 1.0;[self.view addSubview:imageViewDefault];

    // Animate logo
    [UIView animateWithDuration:0.425 delay:0.75 options:UIViewAnimationOptionCurveEaseOut animations:^{imageViewDefault.alpha = zero;} completion:^(BOOL completed){

        // informative label
        informativeLabel = [[UILabel alloc] initWithFrame:CGRectMake(zero, (imageViewDefault.frame.size.height/2), self.view.frame.size.width, tutorialInformativeFontSize + tutorialLabelExtraHeight)];informativeLabel.text = tutorialInformativeText;
        informativeLabel.textAlignment = NSTextAlignmentCenter;informativeLabel.font = [UIFont fontWithName:textFontLight size:tutorialInformativeFontSize];informativeLabel.textColor = [UIColor blackColor];informativeLabel.backgroundColor = [UIColor clearColor];informativeLabel.alpha = zero;[self.view addSubview:informativeLabel];

        // Animate text : fade in
        [UIView animateWithDuration:0.40 delay:0.25 options:UIViewAnimationOptionCurveEaseIn animations:^{informativeLabel.alpha = 1.0;} completion:^(BOOL completed){

            // Animate text : move upwards
            [UIView animateWithDuration:0.25 delay:0.75 options:UIViewAnimationOptionCurveLinear animations:^{informativeLabel.frame = CGRectMake(informativeLabel.frame.origin.x, [self getCorrectYValue:[NSNumber numberWithInteger:tutorialPropertyDescriptionOneLabel]], informativeLabel.frame.size.width, informativeLabel.frame.size.height);informativeLabel.alpha = zero;} completion:^(BOOL completed){[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:viewProcessInitializeDB] forKey:currentInitialViewProcess];[self tutorialProgressZero];}];}];}];
}

// Tutorial : start
- (void)tutorialStart{[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:viewProcessTutorial] forKey:currentInitialViewProcess];[self tutorialProgressZero];}

// Update : start
- (void)updateStart{[UIView animateWithDuration:0.25 animations:^{crossButton.alpha = zero;} completion:^(BOOL completed){[self updateDatabaseProcess];}];}

// iTunes Match : start
- (void)iTunesMatchStart{
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:shouldInformUserAboutMatch] boolValue] && ![[[NSUserDefaults standardUserDefaults] objectForKey:userIsInformedAboutMatch] boolValue])[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:shouldInformUserAboutMatch];
    [UIView animateWithDuration:0.25 animations:^{crossButton.alpha = zero;} completion:^(BOOL completed){[self iTunesMatchDatabaseProcess];}];}

- (void)tutorialProgressZero{

    // Disable interaction with view
    [self setUserInteraction:NO];

    // imageViews
    imageViewProgress = [[UIImageView alloc] initWithImage:[UIImage imageNamed:tutorialProgressStep0Name]];imageViewProgress.frame = CGRectMake(tutorialProgressBarX, [self getCorrectYValue:[NSNumber numberWithInteger:tutorialPropertyImageViewProgress]], tutorialProgressWidth, tutorialProgressHeight);imageViewProgress.alpha = zero;[self.view addSubview:imageViewProgress];
    imageViewWireframe = [[UIImageView alloc] initWithImage:[UIImage imageNamed:tutorialCellViewHomeName]];imageViewWireframe.frame = CGRectMake(tutorialWireframeX, self.view.frame.size.height, tutorialWireframeWidth, tutorialWireframeHeight);[imageViewWireframe setUserInteractionEnabled:YES];[self.view addSubview:imageViewWireframe];

    // cell
    tutorialTableView = [[UITableView alloc] initWithFrame:CGRectMake(tutorialCellX, tutorialCellY, tutorialCellWidth, tutorialCellHeight)];
    UIImageView *tableViewLineBottomTo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:tutorialCellViewLineName]];tableViewLineBottomTo.frame = CGRectMake(zero, tutorialCellHeight - 0.5, tableViewLineBottomTo.frame.size.width, tableViewLineBottomTo.frame.size.height);
    [tutorialTableView addSubview:tableViewLineBottomTo];tutorialTableView.delegate = self;tutorialTableView.dataSource = self;tutorialTableView.scrollEnabled = NO;[imageViewWireframe addSubview:tutorialTableView];

    // buttons
    if (!crossButton){crossButton = [[UIButton alloc] initWithFrame:CGRectMake(tutorialCrossX, [self getCorrectYValue:[NSNumber numberWithInteger:tutorialPropertyCrossButton]], tutorialCrossWidth, tutorialCrossHeight)];[crossButton setImage:[UIImage imageNamed:tutorialCrossName] forState:UIControlStateNormal];
        [crossButton setImage:[UIImage imageNamed:tutorialCrossActiveName] forState:UIControlStateSelected];crossButton.alpha = zero;[self.view addSubview:crossButton];}[crossButton addTarget:self action:@selector(dismissElementsFromScreen) forControlEvents:UIControlEventTouchUpInside];

    // background color
    [UIView animateWithDuration:0.9 animations:^{[self.view setBackgroundColor:tutorialBackgroundColor];}];

    // Animate
    [UIView animateWithDuration:0.40 animations:^{imageViewProgress.alpha = 1.0;crossButton.alpha = 1.0;

        // Wireframe and cell
        imageViewWireframe .frame = CGRectMake(tutorialWireframeX, [self getCorrectYValue:[NSNumber numberWithInteger:tutorialPropertyImageViewWireframe]], tutorialWireframeWidth, tutorialWireframeHeight);} completion:^(BOOL completed){

            // labels
            headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(zero, [self getCorrectYValue:[NSNumber numberWithInteger:tutorialPropertyHeaderLabel]], self.view.frame.size.width, tutorialHeaderFontSize + tutorialLabelExtraHeight)];headerLabel.text = tutorialHeaderStep0Text;
            descriptionOneLabel = [[UILabel alloc] initWithFrame:CGRectMake(zero, [self getCorrectYValue:[NSNumber numberWithInteger:tutorialPropertyDescriptionOneLabel]], self.view.frame.size.width, tutorialDescriptionFontSize + tutorialLabelExtraHeight)];descriptionOneLabel.text = tutorialDescriptionOneStep0Text;
            descriptionTwoLabel = [[UILabel alloc] initWithFrame:CGRectMake(zero, [self getCorrectYValue:[NSNumber numberWithInteger:tutorialPropertyDescriptionTwoLabel]], self.view.frame.size.width, tutorialDescriptionFontSize + tutorialLabelExtraHeight)];descriptionTwoLabel.text = tutorialDescriptionTwoStep0Text;

            headerLabel.textAlignment = NSTextAlignmentCenter;headerLabel.font = [UIFont fontWithName:textFontBold size:tutorialHeaderFontSize];headerLabel.textColor = tutorialHeaderColor;headerLabel.backgroundColor = [UIColor clearColor];
            descriptionOneLabel.textAlignment = NSTextAlignmentCenter;descriptionOneLabel.font = [UIFont fontWithName:textFontLight size:tutorialDescriptionFontSize];descriptionOneLabel.textColor = tutorialDescriptionColor;descriptionOneLabel.backgroundColor = [UIColor clearColor];
            descriptionTwoLabel.textAlignment = NSTextAlignmentCenter;descriptionTwoLabel.font = [UIFont fontWithName:textFontLight size:tutorialDescriptionFontSize];descriptionTwoLabel.textColor = tutorialDescriptionColor;descriptionTwoLabel.backgroundColor = [UIColor clearColor];

            // alpha
            headerLabel.alpha = zero;descriptionOneLabel.alpha = zero;descriptionTwoLabel.alpha = zero;

            // reload
            [tutorialTableView reloadData];

            // add elements to view
            [self.view addSubview:headerLabel];[self.view addSubview:descriptionOneLabel];[self.view addSubview:descriptionTwoLabel];

            // Fade in text
            [UIView animateWithDuration:1 animations:^{headerLabel.alpha = 1.0;descriptionOneLabel.alpha = 1.0;descriptionTwoLabel.alpha = 1.0;} completion:^(BOOL completed){[self setUserInteraction:YES];}];}];
}

- (void)tutorialProgressOne{

    // disable interaction with view
    [self setUserInteraction:NO];

    // progress
    imageViewProgress.image = [UIImage imageNamed:tutorialProgressStep1Name];[self animateChangeInImage:imageViewProgress duration:1.0];

    // fade out text
    [UIView animateWithDuration:0.40 animations:^{headerLabel.alpha = zero;descriptionOneLabel.alpha = zero;descriptionTwoLabel.alpha = zero;imageViewSwipeArrow.alpha = zero;} completion:^(BOOL completed){headerLabel.text = tutorialHeaderStep1Text;descriptionOneLabel.text = tutorialDescriptionOneStep1Text;descriptionTwoLabel.text = tutorialDescriptionTwoStep1Text;

        // reload
        [tutorialTableView reloadData];

        // animate text
        [UIView animateWithDuration:0.40 delay:0.10 options:UIViewAnimationOptionTransitionNone  animations:^{headerLabel.alpha = 1.0;descriptionOneLabel.alpha = 1.0;descriptionTwoLabel.alpha = 1.0;} completion:^(BOOL completed){[self setUserInteraction:YES];}];}];
}

- (void)tutorialProgressTwo{

    // disable interaction with view
    [self setUserInteraction:NO];

    // progress
    imageViewProgress.image = [UIImage imageNamed:tutorialProgressStep2Name];[self animateChangeInImage:imageViewProgress duration:1.0];

    // fade out text
    [UIView animateWithDuration:0.40 animations:^{headerLabel.alpha = zero;descriptionOneLabel.alpha = zero;descriptionTwoLabel.alpha = zero;imageViewSwipeArrow.alpha = zero;} completion:^(BOOL completed){
        headerLabel.text = tutorialHeaderStep2Text;descriptionOneLabel.text = tutorialDescriptionOneStep2Text;descriptionTwoLabel.text = tutorialDescriptionTwoStep2Text;

        // reload
        [tutorialTableView reloadData];

        // animate text
        [UIView animateWithDuration:0.40 delay:0.10 options:UIViewAnimationOptionTransitionNone animations:^{headerLabel.alpha = 1.0;descriptionOneLabel.alpha = 1.0;descriptionTwoLabel.alpha = 1.0;} completion:^(BOOL completed){[self setUserInteraction:YES];}];}];
}

- (void)tutorialProgressThree{

    // disable interaction with view
    [self setUserInteraction:NO];

    // progress
    imageViewProgress.image = [UIImage imageNamed:tutorialProgressStep3Name];[self animateChangeInImage:imageViewProgress duration:1.0];

    // fade text out
    [UIView animateWithDuration:0.40 animations:^{headerLabel.alpha = zero;descriptionOneLabel.alpha = zero;descriptionTwoLabel.alpha = zero;continueButton.alpha = zero;} completion:^(BOOL completed){[continueButton removeFromSuperview];headerLabel.text = tutorialHeaderStep3Text;descriptionOneLabel.text = tutorialDescriptionOneStep3Text;descriptionTwoLabel.text = tutorialDescriptionTwoStep3Text;

        // reload
        [tutorialTableView reloadData];

        // animate text
        [UIView animateWithDuration:0.40 delay:0.10 options:UIViewAnimationOptionTransitionNone animations:^{headerLabel.alpha = 1.0;descriptionOneLabel.alpha = 1.0;descriptionTwoLabel.alpha = 1.0;tutorialTableViewCell.contentView.backgroundColor = [UIColor whiteColor];} completion:^(BOOL completed){[self setUserInteraction:YES];}];}];
}

- (void)tutorialProgressFour{

    // Disable interaction with view
    [self setUserInteraction:NO];

    // progress
    imageViewProgress.image = [UIImage imageNamed:tutorialProgressStep4Name];[self animateChangeInImage:imageViewProgress duration:1.0];

    // Animate text and pointer
    [UIView animateWithDuration:0.40 animations:^{headerLabel.alpha = zero;descriptionOneLabel.alpha = zero;descriptionTwoLabel.alpha = zero;imageViewSwipeArrow.alpha = zero;} completion:^(BOOL completed){headerLabel.text = tutorialHeaderStep4Text;descriptionOneLabel.text = none;descriptionTwoLabel.text = none;
        [UIView animateWithDuration:0.40 delay:0.10 options:UIViewAnimationOptionTransitionNone animations:^{headerLabel.alpha = 1.0;} completion:^(BOOL completed){

            // Move wireframe
            [UIView animateWithDuration:0.75 animations:^{imageViewWireframe .frame = CGRectMake(tutorialWireframeX, [self getCorrectYValue:[NSNumber numberWithInteger:tutorialPropertyImageViewWireframeMoving]], tutorialWireframeWidth, tutorialWireframeHeight);} completion:^(BOOL completed){

                // Features view
                imageViewFeatures = [[UIImageView alloc] initWithImage:[UIImage imageNamed:tutorialFeaturesName]];imageViewFeatures.frame = CGRectMake(tutorialFeaturesX, [self getCorrectYValue:[NSNumber numberWithInteger:tutorialPropertyImageViewFeatures]], tutorialFeaturesWidth, tutorialFeaturesHeight);imageViewFeatures.alpha = zero;[self.view addSubview:imageViewFeatures];
                [UIView animateWithDuration:0.85 animations:^{imageViewFeatures.alpha = 1.0;} completion:^(BOOL completed){

                    // Create continue button
                    continueButton = [[UIButton alloc] initWithFrame:CGRectMake(zero, [self getCorrectYValue:[NSNumber numberWithInteger:tutorialPropertyContinueButton]], self.view.frame.size.width, tutorialContinueFontSize + tutorialLabelExtraHeight)];[continueButton setTitle:tutorialContinueText forState:UIControlStateNormal];
                    continueButton.titleLabel.textAlignment = NSTextAlignmentCenter;continueButton.titleLabel.font = [UIFont fontWithName:textFontLight size:tutorialContinueFontSize];continueButton.titleLabel.textColor = tutorialContinueColor;continueButton.backgroundColor = [UIColor clearColor];
                    [continueButton addTarget:self action:@selector(dismissElementsFromScreen) forControlEvents:UIControlEventTouchUpInside];continueButton.alpha = zero;[self.view addSubview:continueButton];

                    // Animate continue button
                    [UIView animateWithDuration:0.6 delay:0.05 options:UIViewAnimationOptionTransitionNone animations:^{continueButton.alpha = 1.0;}completion:^(BOOL completed){[self setUserInteraction:YES];}];}];}];}];}];
}

- (void)dismissElementsFromScreen{

    // Disable interaction with view
    [self setUserInteraction:NO];

    // Get all current subviews
    NSArray *subviews = [self.view subviews];

    // Fade out all elements on screen
    [UIView animateWithDuration:0.30 delay:zero options:UIViewAnimationOptionCurveEaseInOut animations:^{for (UIView *view in subviews)view.alpha = zero;} completion:^(BOOL completed){for (UIView *view in subviews){[view removeFromSuperview];}[self getViewProcess];}];
}

- (void)getViewProcess{

    switch ([[[NSUserDefaults standardUserDefaults] valueForKey:currentInitialViewProcess] integerValue]){
        case viewProcessInitializeDB:[self performSelector:@selector(initializeDatabaseProcess) withObject:nil afterDelay:0.40];break;
        case viewProcessTutorial:[mainViewController dismissInitialView];break;
        default:break;}
}

- (void)databaseProcessView:(NSString *)actionText{

    // Create initDB labels
    initializeDBOneLabel = [[UILabel alloc] initWithFrame:CGRectMake(zero, (self.view.frame.size.height/2) - tutorialInitializeDBOnePaddingY, self.view.frame.size.width, tutorialInitializeDBFontSize + tutorialLabelExtraHeight)];initializeDBOneLabel.text = tutorialInitializeDBOneText;initializeDBOneLabel.alpha = zero;
    initializeDBOneLabel.textAlignment = NSTextAlignmentCenter;initializeDBOneLabel.font = [UIFont fontWithName:textFontLight size:tutorialInitializeDBFontSize];initializeDBOneLabel.textColor = [UIColor blackColor];initializeDBOneLabel.backgroundColor = [UIColor clearColor];[self.view addSubview:initializeDBOneLabel];
    initializeDBTwoLabel = [[UILabel alloc] initWithFrame:CGRectMake(zero, initializeDBOneLabel.frame.origin.y + initializeDBOneLabel.frame.size.height - tutorialInitializeDBTwoPaddingY, self.view.frame.size.width, tutorialInitializeDBFontSize + tutorialLabelExtraHeight)];initializeDBTwoLabel.text = actionText;initializeDBTwoLabel.alpha = zero;
    initializeDBTwoLabel.textAlignment = NSTextAlignmentCenter;initializeDBTwoLabel.font = [UIFont fontWithName:textFontLight size:tutorialInitializeDBFontSize];initializeDBTwoLabel.textColor = [UIColor blackColor];initializeDBTwoLabel.backgroundColor = [UIColor clearColor];[self.view addSubview:initializeDBTwoLabel];

    // Indicator
    indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];indicatorView.center = CGPointMake(CGRectGetMidX(self.view.bounds), initializeDBOneLabel.frame.origin.y - tutorialIndicatorPaddingY);indicatorView.alpha = zero;[indicatorView startAnimating];[self.view addSubview:indicatorView];}

- (void)initializeDatabaseProcess{[self databaseProcessView:tutorialInitializeDBTwoText];[UIView animateWithDuration:0.5 animations:^{[self.view setBackgroundColor:[UIColor whiteColor]];initializeDBOneLabel.alpha = 1.0;initializeDBTwoLabel.alpha = 1.0;indicatorView.alpha = 1.0;} completion:^(BOOL completed){[mainViewController animateEndTransitionInitializeDB];}];}

- (void)updateDatabaseProcess{[self databaseProcessView:tutorialUpdateDBText];[UIView animateWithDuration:0.5 animations:^{initializeDBOneLabel.alpha = 1.0;initializeDBTwoLabel.alpha = 1.0;indicatorView.alpha = 1.0;} completion:^(BOOL completed){[mainViewController animateEndTransitionUpdateDB];}];}
- (void)iTunesMatchDatabaseProcess{[self databaseProcessView:tutorialMatchText];[UIView animateWithDuration:0.5 animations:^{initializeDBOneLabel.alpha = 1.0;initializeDBTwoLabel.alpha = 1.0;indicatorView.alpha = 1.0;} completion:^(BOOL completed){[mainViewController animateEndTransitionUpdateDB];}];}

#pragma mark - Supporting functions

// Correct y-value for interface properties
- (CGFloat)getCorrectYValue:(NSNumber *)propertyNumber{

    // BOOLs
    BOOL isV70 = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7Text);
    BOOL isS40 = SCREEN_SIZE_GREATER_THAN_OR_EQUAL_TO_40;

    // Switch-case based on propertyNumber
    switch ([propertyNumber integerValue]){
        case tutorialPropertyContinueButton:
            if (isS40)return tutorialContinueS40Y;
            else return tutorialContinueS35Y;break;
        case tutorialPropertyCrossButton:
            if (isV70)return tutorialCrossV70Y;
            else return tutorialCrossV60Y;break;
        case tutorialPropertyHeaderLabel:
            if (isV70)return tutorialHeaderV70Y;
            else return tutorialHeaderV60Y;break;
        case tutorialPropertyDescriptionOneLabel:
            if (isV70)return tutorialDescriptionOneV70Y;
            else return tutorialDescriptionOneV60Y;break;
        case tutorialPropertyDescriptionTwoLabel:
            if (isV70)return tutorialDescriptionTwoV70Y;
            else return tutorialDescriptionTwoV60Y;break;
        case tutorialPropertyImageViewProgress:
            if (isV70)return tutorialProgressBarV70Y;
            else return tutorialProgressBarV60Y;break;
        case tutorialPropertyImageViewWireframe:
            if (isV70)return tutorialWireframeV70Y;
            else return tutorialWireframeV60Y;break;
        case tutorialPropertyImageViewWireframeMoving:
            if (isS40)return tutorialWireframeMovingS40Y;
            else return tutorialWireframeMovingS35Y;break;
        case tutorialPropertyImageViewFeatures:
            if (isS40)return tutorialFeaturesS40Y;
            else return tutorialFeaturesS35Y;break;
        default:break;}

    return zero;
}

// Correct image name related to OS version and screen size
- (NSString *)getCorrectImageName:(NSNumber *)elementNumber{

    // BOOLs
    BOOL isV70 = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7Text);
    BOOL isS40 = SCREEN_SIZE_GREATER_THAN_OR_EQUAL_TO_40;

    // Switch-case based on elementNumber
    switch ([elementNumber integerValue]){
        case tutorialElementDefaultView:
            if (isV70 && isS40)return imageViewDefaultV70S40Name;
            else if (isV70 && !isS40)return imageViewDefaultV70S35Name;
            else if (!isV70 && isS40)return imageViewDefaultV60S40Name;
            else if (!isV70 && !isS40)return imageViewDefaultV60S35Name;break;
        default:break;}

    return none;
}

// Correct height for interface properties
- (CGFloat)getCorrectHeightValue:(NSNumber *)propertyNumber{

    // BOOLs
    BOOL isV70 = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7Text);

    // Switch-case based on propertyNumber
    switch ([propertyNumber integerValue]){
        case tutorialElementDefaultView:
            if (isV70)return self.view.frame.size.height;
            else return self.view.frame.size.height - statusBarPixels;break;
        default:break;}

    return zero;
}

// Animate change of picture which normal UIView animateWithDuration doesn't support
- (void)animateChangeInImage:(UIImageView *)imageView duration:(CGFloat)duration{CATransition *transition = [CATransition animation];transition.duration = duration;transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];transition.type = kCATransitionFade;[imageView.layer addAnimation:transition forKey:nil];}

// User interaction
- (void)setUserInteraction:(BOOL)state{self.view.userInteractionEnabled = state;mainViewController.view.userInteractionEnabled = state;}

#pragma UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{return 1;}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{return tutorialCellHeight;}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    // Cell
    MCSwipeTableViewCell *cell = [[MCSwipeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierInitial];

    // For the delegate callback
    [cell setDelegate:self];

    // Content view
    cell.contentView.backgroundColor = [UIColor whiteColor];

    // Background view
    UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(zero, zero, cell.frame.size.width, cell.frame.size.height)];[backgroundView setBackgroundColor:backgroundViewColor];cell.backgroundView = backgroundView;

    // Setting the type of the cell
    cell.typeOfCell = tutorialCellType;
    [cell setMode:MCSwipeTableViewCellModeSwitch];
    [cell correctCellForType:cell.typeOfCell];

    // Styles
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    if (!imageViewSwipeArrow){imageViewSwipeArrow = [[UIImageView alloc] initWithFrame:CGRectMake(tutorialCellArrowX, tutorialCellArrowY, tutorialCellArrowWidth, tutorialCellArrowHeight)];imageViewSwipeArrow.alpha = zero;[tutorialTableView addSubview:imageViewSwipeArrow];}

    // Add to queue
    if ([headerLabel.text isEqualToString:tutorialHeaderStep0Text] ){[cell setFirstStateIconName:queueSwipeCellName firstColor:blueColor secondStateIconName:queueSwipeCellName secondColor:backgroundViewColor thirdIconName:playlistSwipeCellName thirdColor:backgroundViewColor fourthIconName:playlistSwipeCellName fourthColor:backgroundViewColor];[imageViewSwipeArrow setImage:[UIImage imageNamed:tutorialArrowBlueName]];

        // Blue arrow
        [UIView animateWithDuration:0.65 animations:^{imageViewSwipeArrow.alpha = 0.8;} completion:nil];}

    // Delete from queue
    else if ([headerLabel.text isEqualToString:tutorialHeaderStep1Text]){cell.circle.image = [UIImage imageNamed:tutorialCirclesRightName];[cell setFirstStateIconName:queueSwipeCellName firstColor:backgroundViewColor secondStateIconName:queueSwipeCellName secondColor:redColor thirdIconName:playlistSwipeCellName thirdColor:backgroundViewColor fourthIconName:playlistSwipeCellName fourthColor:backgroundViewColor];[imageViewSwipeArrow setImage:[UIImage imageNamed:tutorialArrowRightRedName]];

        // Red arrow
        [UIView animateWithDuration:0.65 animations:^{imageViewSwipeArrow.alpha = 0.8;} completion:nil];}

    // Add to playlist
    else if ([headerLabel.text isEqualToString:tutorialHeaderStep2Text]){cell.circle.image = [UIImage imageNamed:tutorialCirclesNoneName];[cell setFirstStateIconName:queueSwipeCellName firstColor:backgroundViewColor secondStateIconName:queueSwipeCellName secondColor:backgroundViewColor thirdIconName:playlistSwipeCellName thirdColor:orangeColor fourthIconName:playlistSwipeCellName fourthColor:backgroundViewColor];

        // Orange arrow
        imageViewSwipeArrow = [[UIImageView alloc] initWithFrame:CGRectMake(tutorialCellArrowX, tutorialCellArrowY, tutorialCellArrowWidth, tutorialCellArrowHeight)];imageViewSwipeArrow.alpha = zero;[cell.contentView addSubview:imageViewSwipeArrow];
        [imageViewSwipeArrow setImage:[UIImage imageNamed:tutorialArrowOrangeName]];[UIView animateWithDuration:0.65 animations:^{imageViewSwipeArrow.alpha = 0.8;} completion:nil];}

    // Delete from playlist
    else if ([headerLabel.text isEqualToString:tutorialHeaderStep3Text]){cell.circle.image = [UIImage imageNamed:tutorialCirclesLeftName];[cell setFirstStateIconName:queueSwipeCellName firstColor:backgroundViewColor secondStateIconName:queueSwipeCellName secondColor:backgroundViewColor thirdIconName:playlistSwipeCellName thirdColor:backgroundViewColor fourthIconName:playlistSwipeCellName fourthColor:redColor];

        // Orange arrow
        imageViewSwipeArrow = [[UIImageView alloc] initWithFrame:CGRectMake(tutorialCellArrowX, tutorialCellArrowY, tutorialCellArrowWidth, tutorialCellArrowHeight)];imageViewSwipeArrow.alpha = zero;[cell.contentView addSubview:imageViewSwipeArrow];
        [imageViewSwipeArrow setImage:[UIImage imageNamed:tutorialArrowLeftRedName]];[UIView animateWithDuration:0.65 animations:^{imageViewSwipeArrow.alpha = 0.8;} completion:nil];}

    // Values
    cell.title1.text = tutorialCellTitle1Text;
    cell.title2.text = tutorialCellTitle2Text;

    // Hold reference
    tutorialTableViewCell = cell;

    return cell;
}

#pragma mark MCSwipeTableViewCellDelegate

// Triggered state when cell is swiped : actions include insert and delete from a playlist or queue
- (void)swipeTableViewCell:(MCSwipeTableViewCell *)cell didTriggerState:(MCSwipeTableViewCellState)state withMode:(MCSwipeTableViewCellMode)mode withImage:(NSString *)imageName withColor:(UIColor *)color{

    if ([imageName isEqualToString:playlistSwipeCellName]){
        if ([color isEqual:orangeColor]){cell.circle.image = [UIImage imageNamed:tutorialCirclesLeftName];[self tutorialProgressThree];}
        else if ([color isEqual:redColor]){cell.circle.image = [UIImage imageNamed:tutorialCirclesNoneName];[self tutorialProgressFour];}}
    else if ([imageName isEqualToString:queueSwipeCellName]){
        if ([color isEqual:blueColor]){cell.circle.image = [UIImage imageNamed:tutorialCirclesRightName];[self tutorialProgressOne];}
        else if ([color isEqual:redColor]){cell.circle.image = [UIImage imageNamed:tutorialCirclesNoneName];[self tutorialProgressTwo];}}
}

@end