text:
/* $Id$ */

// Script to create calibration parameters and store them into CDB
// Two sets of calibration parameters can be created:
// 1) equal parameters
// 2) randomly distributed parameters for decalibrated detector silumations

#if !defined(__CINT__)
#include "TControlBar.h"
#include "TString.h"
#include "TRandom.h"
#include "TH1F.h"
#include "TF1.h"
#include "TCanvas.h"

#include "AliRun.h"
#include "AliT0CalibData.h"
//#include "AliT0AlignData.h"
#include "AliT0Align.h"
#include "AliCDBMetaData.h"
#include "AliCDBId.h"
#include "AliCDBEntry.h"
#include "AliCDBManager.h"
#include "AliCDBStorage.h"
#endif

void AliT0SetCDB()
{
  TControlBar *menu = new TControlBar("vertical","T0 CDB");
  menu->AddButton("Set time delay","SetTimeDelay()",
		  "Set time delay");
  menu->AddButton("Set walk","SetWalk()",
		  "Set slewing coorection");
  menu->AddButton("Set Align","SetAC()",
		  "Set alignment coefficients");
  menu->AddButton("Set LookUpTable","SetLookUp()",
                  "Set LookUp table");
  menu->AddButton("Read time delay","GetTimeDelay()",
		  "Read time delay");
  menu->AddButton("Read walk","GetWalk()",
		  "Read amplitude-time correction");
  menu->AddButton("Read alignment CC","GetAC()",
		  "Read face detector position ");
  menu->AddButton("Read Lookup","GetLookUp()",
		  "Read Lookup table ");
  menu->Show();
}

//------------------------------------------------------------------------
void SetAC()
{
  // Writing alignment coefficients into the Condition DB
  // Arguments:

  TString DBFolder;
  Int_t firstRun   =  0;
  Int_t lastRun    = 99999;
  Int_t beamPeriod =  1;
  char* objFormat  = "";

  DBFolder  ="local://Align";
  firstRun  =  0;
  lastRun   =  99999;
  objFormat = "T0 array  positions";

  AliT0Align *al = new AliT0Align(1,835615);
  al->Run();

   /*
  AliT0AlignData *alignda=new AliT0AlignData("T0");
  alignda-> SetZposition (67.9,373);
  alignda->Print();

  //Store calibration data into database
  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
   AliCDBManager::Instance()->SetSpecificStorage("T0",DBFolder.Data());

  AliCDBMetaData md;
  md.SetComment(objFormat);
  md.SetBeamPeriod(beamPeriod);
  md.SetResponsible("Alla");
  TString fPath="T0/Align/Positions";

  //  AliCDBStorage* storage = AliCDBManager::Instance()->GetSpecificStorage("T0");
  AliCDBStorage* storage = AliCDBManager::Instance()->GetDefaultStorage();
  if(storage) {
   AliCDBId id(fPath.Data(),firstRun,lastRun);

   storage->Put(alignda, id, &md);
 }
   */
}
//------------------------------------------------------------------------
void SetTimeDelay()
{
  // Writing calibration coefficients into the Calibration DB
  // Arguments:

  TString DBFolder;
  Int_t firstRun   =  0;
  Int_t lastRun    = 99999;
  Int_t beamPeriod =  1;
  char* objFormat  = "";

  DBFolder  ="local://Calib";
  firstRun  =  0;
  lastRun   =  999999;
  objFormat = "T0 initial time delay";

  AliT0CalibTimeEq *calibda=new AliT0CalibTimeEq("T0");

   Float_t fTimeDelay  = 1000;
 for(Int_t ipmt=0; ipmt<24; ipmt++) {
   calibda->SetTimeEq(ipmt,fTimeDelay+ipmt*100);

  }

  calibda->Print();
  //Store calibration data into database
  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/OCDB");

  //  AliCDBManager::Instance()->SetSpecificStorage("T0",DBFolder.Data());

  AliCDBMetaData md;
  md.SetComment(objFormat);
  md.SetBeamPeriod(beamPeriod);
  md.SetResponsible("Alla");
  TString fPath="T0/Calib/TimeDelay";

  // AliCDBStorage* storage = AliCDBManager::Instance()->GetSpecificStorage("T0");
  AliCDBStorage* storage = AliCDBManager::Instance()->GetDefaultStorage();
  if(storage) {
    AliCDBId id(fPath.Data(),firstRun,lastRun);
    storage->Put(calibda, id, &md);
  }
}

//------------------------------------------------------------------------
void SetWalk()
{
  // Writing calibration coefficients into the Calibration DB
  // Arguments:

  TString DBFolder;
  Int_t firstRun   =  0;
  Int_t lastRun    = 999999;
  Int_t beamPeriod =  1;
  char* objFormat  = "";

  DBFolder  ="local://Calib";
  firstRun  =  0;
  lastRun   =  999999;
  objFormat = "T0 initial slewnig correction";

  AliT0CalibWalk *calibda=new AliT0CalibWalk("T0");

  TRandom rn;

  for(Int_t ipmt=0; ipmt<24; ipmt++) {
    calibda->SetWalk(ipmt);
    calibda->SetAmpLEDRec(ipmt);
  }
  //Store calibration data into database
  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/OCDB");

  //  AliCDBManager::Instance()->SetSpecificStorage("T0",DBFolder.Data());

  AliCDBMetaData md;
  md.SetComment(objFormat);
  md.SetBeamPeriod(beamPeriod);
  md.SetResponsible("Alla");
  TString fPath="T0/Calib/Slewing_Walk";

  // AliCDBStorage* storage = AliCDBManager::Instance()->GetSpecificStorage("T0");
  AliCDBStorage* storage = AliCDBManager::Instance()->GetDefaultStorage();
  if(storage) {
    AliCDBId id(fPath.Data(),firstRun,lastRun);
    storage->Put(calibda, id, &md);
  }
}

//------------------------------------------------------------------------
void GetTimeDelay()
{
  // Read calibration coefficients into the Calibration DB
  // Arguments:

  TString DBFolder;

  DBFolder  ="local://Calib";
  Int_t nRun=gAlice->GetRunNumber();

  AliCDBStorage *stor =AliCDBManager::Instance()->GetStorage("local://$ALICE_ROOT/OCDB");
  AliCDBEntry* entry = stor->Get("T0/Calib/TimeDelay",0);

  AliT0CalibTimeEq *clb = (AliT0CalibTimeEq*)entry->GetObject();
  clb->Print();
  for (Int_t i=0; i<24; i++) {
   cout<<clb->GetTimeEq(i)<<endl;
   //  cout<<" equalizing CFD "<<(clb->GetTimeDelayCFD(i)-clb->GetTimeDelayCFD(0))<<endl;

  }

}
//------------------------------------------------------------------------
void GetWalk()
{
  // Read calibration coefficients into the Calibration DB
  // Arguments:

  TString DBFolder;

  DBFolder  ="local://Calib";
  Int_t nRun=gAlice->GetRunNumber();

   AliCDBStorage *stor =AliCDBManager::Instance()->GetStorage("local://$ALICE_ROOT/OCDB");
   AliCDBEntry* entry = stor->Get("T0/Calib/Slewing_Walk",0);

   AliT0CalibWalk *clb = (AliT0CalibWalk*)entry->GetObject();
   Int_t ipmt=0;
   //  cin>>" enter channel number">>ipmt;
   TGraph *gr = clb->GetAmpLEDRec(ipmt);
   gr->Draw("AP");
}
//------------------------------------------------------------------------
void GetAC()
{
  // Read align coefficients into the Calibration DB
  // Arguments:

  TString DBFolder;

  DBFolder  ="local://Align";
  Int_t nRun=gAlice->GetRunNumber();

  AliCDBManager *man = AliCDBManager::Instance();
  AliCDBStorage *stor2 = man->GetStorage("local://Align");
  AliCDBEntry *entry;
  entry = stor2->Get("T0/Align/Positions", nRun);

  AliT0AlignData *aln = (AliT0AlignData*)entry->GetObject();
  aln->Print();
}
//------------------------------------------------------------------------
void SetLookUp()
{
  // Writing Lookup table into the Calibration DB
  // Arguments:

  TString DBFolder;
  Int_t firstRun   =  0;
  Int_t lastRun    = 10;
  Int_t beamPeriod =  1;
  char* objFormat  = "";

  DBFolder  ="local://Calib";
  firstRun  =  0;
  lastRun   =  10;
  objFormat = "T0 Lookup Table";

  AliT0CalibData *calibda=new AliT0CalibData("T0");

//  calibda->ReadAsciiLookup("lookUpTable.txt");
  calibda->ReadAsciiLookup("lookUpTable_tanay.txt");

  //Store calibration data into database
  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/OCDB");

  //  AliCDBManager::Instance()->SetSpecificStorage("T0",DBFolder.Data());

  AliCDBMetaData md;
  md.SetComment(objFormat);
  md.SetBeamPeriod(beamPeriod);
  md.SetResponsible("Alla");
  TString fPath="T0/Calib/LookUp_Table";

  // AliCDBStorage* storage = AliCDBManager::Instance()->GetSpecificStorage("T0");
  AliCDBStorage* storage = AliCDBManager::Instance()->GetDefaultStorage();
  if(storage) {
    AliCDBId id(fPath.Data(),firstRun,lastRun);
    storage->Put(calibda, id, &md);
  }
}
//------------------------------------------------------------------------
void GetLookUp()
{
  // Read calibration coefficients into the Calibration DB
  // Arguments:

  TString DBFolder;

  //  DBFolder  ="local://Calib";
  //   Int_t nRun=gAlice->GetRunNumber();
  AliCDBManager* cdb      = AliCDBManager::Instance();
  AliCDBStorage *stor = cdb->GetStorage("local://$ALICE_ROOT/OCDB");
  // cout<<" GetLookUp :: "<<stor<<endl;
  AliCDBEntry *entry;
  //entry = stor->Get("T0/Calib/LookUp_Table",2,0,0);
  entry = stor->Get("T0/Calib/LookUp_Table",1);
  //cout<<"entry="<<entry<<endl;
   cout<<" AliT0CalibData ::GetLookUp :: "<<entry<<endl;
  AliT0CalibData *clb = (AliT0CalibData*)entry->GetObject();
  cout<<" AliT0CalibData *clb "<<clb <<endl;
  //cout<<"clb->a="<<clb->GetA()<<endl;
  //  clb->Dump();
  for (Int_t i=0; i<20; i++)
    clb->PrintLookupNames("all",i);

}


text:
<ion-header>
    <ion-navbar color="green">
        <ion-title>Cadastrar Cliente</ion-title>
    </ion-navbar>
</ion-header>

<ion-content>

	<ion-list inset>

		<button ion-button block light class="margin-top-15" (click)="pickType()">TIPO</button>

    	<ion-segment [(ngModel)]="type">
	        <ion-segment-button value="0">Pessoa Física</ion-segment-button>
	        <ion-segment-button value="1">Pessoa Jurídica</ion-segment-button>
	    </ion-segment>

		<ion-item>
			<ion-label>Código</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>Nome</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>Email</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>Telefone</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>Celular</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>Representante Legal</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>CPF</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>Nome Fantasia</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>CNPJ</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>Inscrição estadual</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>CEP</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>Logradouro</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>Número</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>Complemento</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>Bairro</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<ion-item>
			<ion-label>Cidade</ion-label>
			<ion-input type="text"></ion-input>
		</ion-item>

		<button ion-button block light class="margin-top-15" (click)="pickState()">ESTADO</button>

        <button ion-button color="secondary" block class="margin-top-30">BUSCAR</button>

	</ion-list>

</ion-content>

redpajama_set_name: RedPajamaGithub


text:
> Open the npm page, Yarn page, or GitHub repo of a package

## Install

```
$ npm install --global npm-home
```

## Usage

```
$ npm-home --help

  Usage
    $ npm-home [name]
    $ nh [name]

  Options
    --github -g  Open the GitHub repo of the package
    --yarn -y    Open the Yarn homepage of the package

  Examples
    $ npm-home
    $ npm-home chalk -g
```

## Related

- [gh-home](https://github.com/sindresorhus/gh-home) - Open the GitHub page of the given or current directory repo

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


text:
/* ###
 * IP: GHIDRA
 *
 * 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.
 */
package agent.dbgeng.jna.dbgeng.breakpoint;

import com.sun.jna.*;
import com.sun.jna.platform.win32.WinDef.ULONG;
import com.sun.jna.platform.win32.WinDef.ULONGByReference;
import com.sun.jna.platform.win32.WinNT.HRESULT;

public class WrapIDebugBreakpoint2 extends WrapIDebugBreakpoint implements IDebugBreakpoint2 {
	public static class ByReference extends WrapIDebugBreakpoint2 implements Structure.ByReference {
	}

	public WrapIDebugBreakpoint2() {
	}

	public WrapIDebugBreakpoint2(Pointer pvInstance) {
		super(pvInstance);
	}

	@Override
	public HRESULT GetCommandWide(char[] Buffer, ULONG BufferSize, ULONGByReference CommandSize) {
		return _invokeHR(VTIndices2.GET_COMMAND_WIDE, getPointer(), Buffer, BufferSize,
			CommandSize);
	}

	@Override
	public HRESULT SetComamndWide(WString Command) {
		return _invokeHR(VTIndices2.SET_COMMAND_WIDE, getPointer(), Command);
	}

	@Override
	public HRESULT GetOffsetExpressionWide(char[] Buffer, ULONG BufferSize,
			ULONGByReference ExpressionSize) {
		return _invokeHR(VTIndices2.GET_OFFSET_EXPRESSION_WIDE, getPointer(), Buffer, BufferSize,
			ExpressionSize);
	}

	@Override
	public HRESULT SetOffsetExpressionWide(WString Expression) {
		return _invokeHR(VTIndices2.SET_OFFSET_EXPRESSION_WIDE, getPointer(), Expression);
	}
}


text:
namespace yycms.entity
{
    using System;
    using System.Collections.Generic;

    public partial class yy_Page_Build_Config
    {
        public long ID { get; set; }
        public long PageTypeID { get; set; }
        public long PageID { get; set; }
        public System.DateTime StartTime { get; set; }
        public System.DateTime EndTime { get; set; }
        public int BuildType { get; set; }
        public string DataTypeIDs { get; set; }
        public System.DateTime CreateTime { get; set; }
    }
}


text:
package net.clgd.ccemux.plugins.builtin;

import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;

import javax.annotation.Nonnull;
import javax.swing.JFrame;

import com.google.auto.service.AutoService;
import net.clgd.ccemux.api.config.ConfigProperty;
import net.clgd.ccemux.api.config.Group;
import net.clgd.ccemux.api.emulation.EmuConfig;
import net.clgd.ccemux.api.emulation.EmulatedComputer;
import net.clgd.ccemux.api.plugins.Plugin;
import net.clgd.ccemux.api.plugins.PluginManager;
import net.clgd.ccemux.api.rendering.Renderer;
import net.clgd.ccemux.api.rendering.RendererFactory;
import net.clgd.ccemux.rendering.awt.AWTRenderer;
import net.clgd.ccemux.rendering.awt.config.ConfigView;

@AutoService(Plugin.class)
public class AWTPlugin extends Plugin {
	private AWTConfig config;

	@Nonnull
	@Override
	public String getName() {
		return "AWT Renderer";
	}

	@Nonnull
	@Override
	public String getDescription() {
		return "A CPU-based renderer using Java AWT.";
	}

	@Nonnull
	@Override
	public Optional<String> getVersion() {
		return Optional.empty();
	}

	@Nonnull
	@Override
	public Collection<String> getAuthors() {
		return Collections.singleton("CLGD");
	}

	@Nonnull
	@Override
	public Optional<String> getWebsite() {
		return Optional.empty();
	}

	@Override
	public void configSetup(@Nonnull Group group) {
		config = new AWTConfig(group);
	}

	@Override
	public void setup(@Nonnull PluginManager manager) {
		manager.addRenderer("AWT", new RendererFactory<Renderer>() {
			private WeakReference<JFrame> lastFrame = null;

			@Override
			public Renderer create(@Nonnull EmulatedComputer computer, @Nonnull EmuConfig cfg) {
				return new AWTRenderer(computer, cfg, config);
			}

			@Override
			public synchronized boolean createConfigEditor(@Nonnull EmuConfig config) {
				if (lastFrame != null) {
					JFrame frame = lastFrame.get();
					if (frame != null && frame.isVisible()) {
						frame.toFront();
						return true;
					}
				}

				JFrame newFrame = new ConfigView(config);
				newFrame.setVisible(true);
				lastFrame = new WeakReference<>(newFrame);

				return true;
			}
		});
	}

	public static class AWTConfig {
		public final ConfigProperty<Boolean> nativePaste;

		AWTConfig(Group group) {
			nativePaste = group.property("nativePaste", boolean.class, false)
				.setName("Use native paste")
				.setDescription("Listen to native paste events instead of Ctrl+V.");
		}
	}
}


text:
dadump
======

Daily dumps management for Postgresql

Creates a directory structure:

    destination/yyyy-mm-dd/dbname.dump

Handles several databases in parallel.
Removes old dumps according to retention configuration.

## Installation

    python setup.py install

In order to store a log file create a directory */var/log/dadump* with rights your user can write to it

## Configuration

Configuration file is placed at */etc/dadump/dadump.conf*

    [pg]
    db = postgresql://postgres@localhost:5432/postgres
    retention = 2
    destination = ~/dumps

In order to manage more database clusters add a separate section:

    [mycluster]
    db = postgresql://postgres@localhost:5432/mydb
        postgresql://postgres@localhost:5432/mydb_00
        postgresql://postgres@localhost:5432/mydb_01
        postgresql://postgres@localhost:5432/mydb_02
        postgresql://postgres@localhost:5432/mydb_03
    retention = 4
    destination = ~/dumps/

## Commands

- **list** - show all dumps
- **drop** - delete a particular dump: drop name yyyy-mm-dd
- **run** - start dumping and cleanup old dumps


text:
import json
import gzip

import numpy as np

import nltk

from inferbeddings.nli import util
from inferbeddings.models.training.util import make_batches

def evaluate(session, eval_path, label_to_index, token_to_index, predictions_op, batch_size,
             sentence1_ph, sentence2_ph, sentence1_len_ph, sentence2_len_ph, dropout_keep_prob_ph,
             has_bos=False, has_eos=False, has_unk=False, is_lower=False,
             bos_idx=1, eos_idx=2, unk_idx=3):
    sentence1_all = []
    sentence2_all = []
    gold_label_all = []

    with gzip.open(eval_path, 'rb') as f:
        for line in f:
            decoded_line = line.decode('utf-8')

            if is_lower:
                decoded_line = decoded_line.lower()

            obj = json.loads(decoded_line)

            gold_label = obj['gold_label']

            if gold_label in ['contradiction', 'entailment', 'neutral']:
                gold_label_all += [label_to_index[gold_label]]

                sentence1_parse = obj['sentence1_parse']
                sentence2_parse = obj['sentence2_parse']

                sentence1_tree = nltk.Tree.fromstring(sentence1_parse)
                sentence2_tree = nltk.Tree.fromstring(sentence2_parse)

                sentence1_tokens = sentence1_tree.leaves()
                sentence2_tokens = sentence2_tree.leaves()

                sentence1_ids = []
                sentence2_ids = []

                if has_bos:
                    sentence1_ids += [bos_idx]
                    sentence2_ids += [bos_idx]

                for token in sentence1_tokens:
                    if token in token_to_index:
                        sentence1_ids += [token_to_index[token]]
                    elif has_unk:
                        sentence1_ids += [unk_idx]

                for token in sentence2_tokens:
                    if token in token_to_index:
                        sentence2_ids += [token_to_index[token]]
                    elif has_unk:
                        sentence2_ids += [unk_idx]

                if has_eos:
                    sentence1_ids += [eos_idx]
                    sentence2_ids += [eos_idx]

                sentence1_all += [sentence1_ids]
                sentence2_all += [sentence2_ids]

    sentence1_all_len = [len(s) for s in sentence1_all]
    sentence2_all_len = [len(s) for s in sentence2_all]

    np_sentence1 = util.pad_sequences(sequences=sentence1_all)
    np_sentence2 = util.pad_sequences(sequences=sentence2_all)

    np_sentence1_len = np.array(sentence1_all_len)
    np_sentence2_len = np.array(sentence2_all_len)

    gold_label = np.array(gold_label_all)

    nb_instances = gold_label.shape[0]
    batches = make_batches(size=nb_instances, batch_size=batch_size)

    predictions = []

    for batch_idx, (batch_start, batch_end) in enumerate(batches):
        feed_dict = {
            sentence1_ph: np_sentence1[batch_start:batch_end],
            sentence2_ph: np_sentence2[batch_start:batch_end],

            sentence1_len_ph: np_sentence1_len[batch_start:batch_end],
            sentence2_len_ph: np_sentence2_len[batch_start:batch_end],

            dropout_keep_prob_ph: 1.0
        }

        _predictions = session.run(predictions_op, feed_dict=feed_dict)
        predictions += _predictions.tolist()

    matches = np.array(predictions) == gold_label
    return np.mean(matches)


text:
'use strict';

let Command = require('./Command');
let Group   = require('../Group');
let User    = require('../User');

/**
 * Enable group user command
 */
class EnableGroupUser extends Command {
  /**
   * Constructor for command
   *
   * @param {User}  user  User
   * @param {Group} group Group
   */
  constructor(user, group) {
    super();

    User.validateUser(user);
    Group.validateGroup(group);

    this.user  = user;
    this.group = group;
  }

  /**
   * Invoke command
   *
   * @param {Client} client Client
   *
   * @return {Promise} Promise for chaining
   */
  invoke(client) {
    let options = {
      method: 'POST',
      path:   `groups/${this.group.id}/enable_user.json`,
      query:  {
        'token': client.apiToken,
        'user':  this.user.id
      }
    };

    return client.getTransport().sendRequest(options)
      .then(result => {
        return true;
      });
  }
}

module.exports = EnableGroupUser;


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.practica1" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <preference name="loglevel" value="DEBUG" />
    <feature name="StatusBar">
        <param name="android-package" value="org.apache.cordova.statusbar.StatusBar" />
        <param name="onload" value="true" />
    </feature>
    <name>Practica1</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <access origin="*" />
    <preference name="StatusBarOverlaysWebView" value="false" />
    <preference name="StatusBarBackgroundColor" value="#FEFEFE" />
    <preference name="StatusBarStyle" value="default" />
    <preference name="webviewbounce" value="false" />
    <preference name="DisallowOverscroll" value="true" />
</widget>


text:
require "spec_helper"
require "chef/knife/google_disk_create"
require "support/shared_examples_for_command"
require "chef/knife/cloud/google_service_helpers"

describe Chef::Knife::Cloud::GoogleDiskCreate do
  let(:tester) { Tester.new }
  let(:command) { described_class.new(%w{disk1}) }
  let(:service) { double("service") }

  before do
    allow(command).to receive(:service).and_return(service)
  end

  it_behaves_like Chef::Knife::Cloud::Command, described_class.new

  describe "#validate_params!" do
    before do
      allow(command).to receive(:check_for_missing_config_values!)
      allow(command).to receive(:valid_disk_size?).and_return(true)
    end

    it "checks for missing config values" do
      expect(command).to receive(:check_for_missing_config_values!).with(:gce_zone, :disk_size, :disk_type)

      command.validate_params!
    end

    it "does not raise an exception if all params are good" do
      expect { command.validate_params! }.not_to raise_error
    end

    it "raises an exception if the disk size is invalid" do
      expect(command).to receive(:valid_disk_size?).and_return(false)
      expect { command.validate_params! }.to raise_error(RuntimeError, "Disk size must be between 10 and 10,000")
    end

    it "raises an exception if the gce_project is missing" do
      ui = double("ui")
      expect(tester).to receive(:ui).and_return(ui)
      expect(ui).to receive(:error).with("The following required parameters are missing: gce_project")
      expect { tester.check_for_missing_config_values! }.to raise_error(RuntimeError)
    end

    context "when no disk name is provided" do
      let(:command) { described_class.new }
      it "raises an exception" do
        expect { command.validate_params! }.to raise_error(RuntimeError, "Please specify a disk name.")
      end
    end
  end

  describe "#execute_command" do
    it "calls the service to create the disk" do
      command.config[:disk_size] = "size"
      command.config[:disk_type] = "type"
      command.config[:disk_source] = "source"
      expect(service).to receive(:create_disk).with("disk1", "size", "type", "source")

      command.execute_command
    end
  end
end


text:
package demo.routes

import demo.components.semanticui._
import demo.pages.SuiPage
import japgolly.scalajs.react.extra.router.RouterConfigDsl
import japgolly.scalajs.react.vdom.html_<^._

object SuiRouteModule {
  case object Info extends LeftRoute("Info", "info", () => SuiInfo())

  case object Button extends LeftRoute("Button", "button", () => SuiButtonDemo())

  case object Container extends LeftRoute("Container", "container", () => SuiContainerDemo())

  case object Divider extends LeftRoute("Divider", "divider", () => SuiDividerDemo())

  case object Flag extends LeftRoute("Flag", "flag", () => SuiFlagDemo())

  case object Header extends LeftRoute("Header", "header", () => SuiHeaderDemo())

  case object Icon extends LeftRoute("Icon", "icon", () => SuiIconDemo())

  case object Input extends LeftRoute("Input", "input", () => SuiInputDemo())

  case object SuiList extends LeftRoute("List", "list", () => SuiListDemo())

  case object Grid extends LeftRoute("Grid", "grid", () => SuiGridDemo())

  val menu: List[LeftRoute] = List(
    Info,
    Button,
    Container,
    Divider,
    Flag,
    Header,
    Icon,
    Input,
    SuiList,
    Grid
  )

  val routes = RouterConfigDsl[LeftRoute].buildRule { dsl =>
    import dsl._
    menu
      .map(i => staticRoute(i.route, i) ~> renderR(r => SuiPage(i, r)))
      .reduce(_ | _)
  }
}


text:
import hug
import part_1
import part_2

@hug.get("/")
def say_hi():
    """This view will be at the path ``/``"""
    return "Hi from root"

@hug.extend_api()
def with_other_apis():
    """Join API endpoints from two other modules

    These will be at ``/part1`` and ``/part2``, the paths being automatically
    generated from function names.

    """
    return [part_1, part_2]


text:
USE [AdventureWorks2014];
-- Cannot use full-text search in master, tempdb, or model database.
GO

-- Need to setup SQL Server for Semantic Search Functions details at:
-- https://raresql.com/2013/05/05/sql-server-2012-semantic-search-install-and-configure-part-1/

IF OBJECT_ID('dbo.tableForFullTextDemo', 'U') IS NOT NULL
	DROP TABLE dbo.tableForFullTextDemo;
GO

IF  EXISTS (SELECT * FROM sysfulltextcatalogs ftc WHERE ftc.name = N'myFullTextCatalog')
	DROP FULLTEXT CATALOG myFullTextCatalog;
GO

-- First create a catalog. I'm using the option to set it as the default catalog which is optional
-- as it the first one I am creating I presume that it would be default anyway.
CREATE FULLTEXT CATALOG myFullTextCatalog
AS DEFAULT;
GO

-- Use a system view to list all the catalogs
SELECT * FROM sys.fulltext_catalogs;
GO

-- Performs a master merge which can help performance on a frequently changing index
-- ... obviously not required here as I have just created it.
ALTER FULLTEXT CATALOG myFullTextCatalog
REORGANIZE;

CREATE TABLE dbo.tableForFullTextDemo
(
	Id			INT	IDENTITY,
	myText		VARCHAR(1024),
	CONSTRAINT PK_Id					-- Name of index
    PRIMARY KEY CLUSTERED (Id)			-- Fields in index
)

-- Out some data in to ve able to create a full text index on
INSERT dbo.tableForFullTextDemo
VALUES	('Lord Of The Rings Trilogy Theatrical Version Blu ray Elijah Wood Ian McKellen Viggo Mortensen Peter Jackson'),
		('Lords of the Bow Conqueror 2 Conn Iggulden'),
		('Lords And Ladies Discworld Novels Terry Pratchett'),
		('Lord of War Blu ray'),
		('Lord of the Rings Aragorn s Quest Wii'),
		('Lord of Arcana Slayer Edition PSP'),
		('Lord of the Flies William Golding'),
		('Lords of the Bow Conqueror 2 Conn Iggulden'),
		('Lord of the Flies York Notes for GCSE 2010 Intermediate Sw Foster'),
		('Lords Of Discipline DVD');

CREATE FULLTEXT INDEX
ON dbo.tableForFullTextDemo(myText)
KEY INDEX PK_Id
WITH CHANGE_TRACKING AUTO;				--< AUTO says to SQL to keep the index updated automatically
GO

-- Need to leave time for the FULL TEXT INDEX to build
WAITFOR DELAY '00:00:10';

-- Return one row
SELECT myText
FROM dbo.tableForFullTextDemo
WHERE CONTAINS(myText, 'Lord AND Slayer')
GO

-- Returns four row
SELECT myText
FROM dbo.tableForFullTextDemo
WHERE CONTAINS(myText, 'Rings OR Flies')
GO

-- Returns four row
SELECT myText
FROM dbo.tableForFullTextDemo
WHERE CONTAINS(myText, '"Lords And"')			--< Note need for extra quotes to prevent AND being seeing as a logical operator
GO

-- Returns four row
SELECT myText
FROM dbo.tableForFullTextDemo
WHERE CONTAINS(myText, '"Lords*"')				--< Wildcard
GO

SELECT myText
FROM dbo.tableForFullTextDemo
WHERE CONTAINS(myText, 'NEAR((Lord, ray), 3)');		--< Only seach for second word within 3 words
GO

-- No rows returned
SELECT myText
FROM dbo.tableForFullTextDemo
WHERE CONTAINS(myText, 'Fly')
GO

-- 2 rows returned
SELECT myText
FROM dbo.tableForFullTextDemo
WHERE CONTAINS(myText, 'FORMSOF(INFLECTIONAL, Fly)')	--< Matches on FLIES
GO

-- 0 rows returned
SELECT myText
FROM dbo.tableForFullTextDemo
WHERE CONTAINS(myText, 'FORMSOF(THESAURUS, Fly)')	--< Would need to update thesaurus XML file to map FLY to other words such as FLOAT or GLIDE
GO

-- FREETEXT looks at variants of the search term so returns variants such as FLIES resulting in two rows
SELECT myText
FROM dbo.tableForFullTextDemo
WHERE FREETEXT(myText, 'Fly')
GO

-- Note JOIN and use of key to join back to primary key
SELECT *
FROM dbo.tableForFullTextDemo fts
INNER JOIN CONTAINSTABLE(dbo.tableForFullTextDemo, myText, 'Lord AND Slayer') AS KEY_TBL
ON fts.Id = KEY_TBL.[Key];
GO

-- Note JOIN and use of key to join back to primary key
SELECT *
FROM dbo.tableForFullTextDemo fts
INNER JOIN FREETEXTTABLE(dbo.tableForFullTextDemo, myText, 'Fly') AS KEY_TBL
ON fts.Id = KEY_TBL.[Key];
GO

--Tidy Up
IF OBJECT_ID('dbo.fullTextSearch', 'U') IS NOT NULL
	DROP TABLE dbo.fullTextSearch;
GO

IF  EXISTS (SELECT * FROM sys.fulltext_indexes fti WHERE fti.object_id = OBJECT_ID(N'dbo.tableForFullTextDemo'))
	DROP FULLTEXT INDEX ON dbo.tableForFullTextDemo;			--< Note the ON part of the statement i.e. it is not deleting dbo.tableForFullTextDemo it is deleting the index on the table
GO

IF  EXISTS (SELECT * FROM sysfulltextcatalogs ftc WHERE ftc.name = N'myFullTextCatalog')
	DROP FULLTEXT CATALOG myFullTextCatalog;
GO


text:
package com.tigertext.lucene;

import java.util.logging.Logger;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.ext.ExtendableQueryParser;
import org.apache.lucene.queryParser.ext.Extensions;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.util.Version;

/**
 * Specialized query parser
 *
 * @author Fernando Benavides <elbrujohalcon@inaka.net>
 *
 */
public class LuceneQueryParser extends ExtendableQueryParser {
	private static final Logger	jlog	= Logger.getLogger(LuceneServer.class
												.getName());

	private DocumentTranslator	documentTranslator;

	/**
	 * Creates a new {@link LuceneQueryParser} instance
	 *
	 * @param version
	 *            the lucene version to use.
	 * @param analyzer
	 *            the analyzer used to find terms in a query string
	 * @param documentTranslator
	 *            The {@link DocumentTranslator} to use to parse fields
	 * @param ext
	 *            the query parser extensions
	 */
	public LuceneQueryParser(Version version, Analyzer analyzer,
			DocumentTranslator documentTranslator, Extensions ext) {
		super(version, "", analyzer, ext);
		this.documentTranslator = documentTranslator;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.apache.lucene.queryParser.QueryParser#getRangeQuery(java.lang.String,
	 * java.lang.String, java.lang.String, boolean)
	 */
	@Override
	protected Query getRangeQuery(String field, String part1, String part2,
			boolean inclusive) throws ParseException {
		TermRangeQuery query = (TermRangeQuery) super.getRangeQuery(field,
				part1, part2, inclusive);
		try {
			switch (this.documentTranslator.getFieldType(field)) {
			case INT:
				return NumericRangeQuery.newIntRange(field,
						(query.getLowerTerm() == null ? Integer.MIN_VALUE
								: Integer.parseInt(query.getLowerTerm())),
						(query.getUpperTerm() == null ? Integer.MAX_VALUE
								: Integer.parseInt(query.getUpperTerm())),
						query.includesLower(), query.includesUpper());
			case LONG:
				return NumericRangeQuery.newLongRange(
						field,
						(query.getLowerTerm() == null ? Long.MIN_VALUE : Long
								.parseLong(query.getLowerTerm())),
						(query.getUpperTerm() == null ? Long.MAX_VALUE : Long
								.parseLong(query.getUpperTerm())), query
								.includesLower(), query.includesUpper());
			case FLOAT:
				return NumericRangeQuery.newFloatRange(
						field,
						(query.getLowerTerm() == null ? Float.MIN_VALUE : Float
								.parseFloat(query.getLowerTerm())), (query
								.getUpperTerm() == null ? Float.MAX_VALUE
								: Float.parseFloat(query.getUpperTerm())),
						query.includesLower(), query.includesUpper());
			case DOUBLE:
				return NumericRangeQuery.newDoubleRange(field,
						(query.getLowerTerm() == null ? Double.MIN_VALUE
								: Double.parseDouble(query.getLowerTerm())),
						(query.getUpperTerm() == null ? Double.MAX_VALUE
								: Double.parseDouble(query.getUpperTerm())),
						query.includesLower(), query.includesUpper());
			default:
				return query;
			}
		} catch (NullPointerException npe) {
			// An unknown field
			jlog.warning("Unknown field: " + field);
			return query;
		} catch (NumberFormatException nfe) {
			jlog.finer("Couldn't parse range: " + field + ":[" + part1 + " TO "
					+ part2 + "]");
			nfe.printStackTrace();
			return query;
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.apache.lucene.queryParser.QueryParser#getFuzzyQuery(java.lang.String,
	 * java.lang.String, float)
	 */
	@Override
	protected Query getFuzzyQuery(String field, String termStr,
			float minSimilarity) throws ParseException {
		jlog.finer("Fuzzy query " + field + ":" + termStr + " | "
				+ minSimilarity);
		return super.getFuzzyQuery(field, termStr, minSimilarity);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.apache.lucene.queryParser.QueryParser#getFieldQuery(java.lang.String,
	 * java.lang.String, boolean)
	 */
	@Override
	protected Query getFieldQuery(String field, String queryText, boolean quoted)
			throws ParseException {
		try {
			switch (this.documentTranslator.getFieldType(field)) {
			case INT:
			case LONG:
			case FLOAT:
			case DOUBLE:
				jlog.finer("Turning " + queryText + " into a range query for "
						+ field);
				return getRangeQuery(field, queryText, queryText, true);
			default:
				return super.getFieldQuery(field, queryText, quoted);
			}
		} catch (NullPointerException npe) {
			// An unknown field
			jlog.warning("Unknown field: " + field);
			return super.getFieldQuery(field, queryText, quoted);
		}
	}
}


text:
package org.apache.jena.atlas.iterator;

import java.util.function.Consumer;

/**
 * @deprecated
 * Prefer {@link Consumer}
 */
@Deprecated
public interface Action<T> extends Consumer<T>
{
}


text:
<?php
namespace Podlove\Modules\SubscribeButton;

use \Podlove\Model\Podcast;
use \Podlove\Model\Feed;
use \Podlove\Cache\TemplateCache;

/**
 * Podlove Subscribe Button
 *
 * Usage:
 *
 * 	$button = new Button($podcast);
 *  echo $button->render(['size' => 'medium', 'language' => 'de']);
 */
class Button {

	private $defaults = [
		'size'     => 'big',
		'format'   => 'cover',
		'width'    => '',
		'style'    => 'filled',
		'language' => 'en',
		'color'    => '#75ad91',
		'buttonid' => NULL,
		'hide'     => false
	];

	private $args = [];

	private $podcast;

	public function __construct(Podcast $podcast) {
		$this->podcast = $podcast;

		if ($podcast->language)
			$this->defaults['language'] = self::language($podcast->language);
	}

	public function render($args = []) {
		$this->args = wp_parse_args($args, $this->defaults);

		// whitelist size parameter
		if (!in_array($this->args['size'], array_keys(Subscribe_Button::sizes())))
			$this->args['size'] = $this->defaults['size'];

		// whitelist style parameter
		if (!in_array($this->args['style'], array_keys(Subscribe_Button::styles())))
			$this->args['style'] = $this->defaults['style'];

		// whitelist format parameter
		if (!in_array($this->args['format'], array_keys(Subscribe_Button::formats())))
			$this->args['format'] = $this->defaults['format'];

		$this->args['data'] = [
			'title'    => $this->podcast->title,
			'subtitle' => $this->podcast->subtitle,
			'description'  => $this->podcast->summary,
			'cover'    => $this->podcast->cover_art()->setWidth(400)->url(),
			'feeds'    => $this->feeds()
		];

		// allow args to override data
		$fields = ['title', 'subtitle', 'description', 'cover'];
		foreach ($fields as $field) {
			if (isset($this->args[$field]) && $this->args[$field]) {
				$this->args['data'][$field] = $this->args[$field];
			}
		}

		// @todo: special treatment for feeds

		return $this->html();
	}

	public static function get_random_string() {
		if (function_exists('openssl_random_pseudo_bytes')) {
			return bin2hex(openssl_random_pseudo_bytes(7));
		} else {
			return dechex(mt_rand());
		}
	}

	private function html() {

		if (!count($this->args['data']['feeds']))
			return '';

		$dataAccessor = 'podcastData' . self::get_random_string();

		$dom = new \Podlove\DomDocumentFragment;

		$script_data_tag = $dom->createElement('script');
		$script_data_tag->appendChild(
			$dom->createTextNode(
				sprintf("window.$dataAccessor = %s;", json_encode($this->args['data']))
			)
		);

		$script_button_tag = $dom->createElement('script');
		$script_button_tag->setAttribute('class', 'podlove-subscribe-button');
		$script_button_tag->setAttribute('src'  , 'https://cdn.podlove.org/subscribe-button/javascripts/app.js');
		$script_button_tag->setAttribute('data-json-data', $dataAccessor);
		$script_button_tag->setAttribute('data-language' , self::language($this->args['language']));
		$script_button_tag->setAttribute('data-size'     , self::size($this->args['size'], $this->args['width']));
		$script_button_tag->setAttribute('data-format'   , $this->args['format']);
		$script_button_tag->setAttribute('data-style'   , $this->args['style']);
		$script_button_tag->setAttribute('data-color'   , $this->args['color']);

		if ($this->args['buttonid'])
			$script_button_tag->setAttribute('data-buttonid', $this->args['buttonid']);

		if ($this->args['hide'] && in_array($this->args['hide'], [1, '1', true, 'true', 'on']))
			$script_button_tag->setAttribute('data-hide', true);

		// ensure there is a closing script tag
		$script_button_tag->appendChild($dom->createTextNode(' '));

		$dom->appendChild($script_data_tag);
		$dom->appendChild($script_button_tag);

		return (string) $dom;
	}

	/**
	 * Feed list, ready for subscribe button.
	 *
	 * @return array list of prepared feed data-objects
	 */
	private function feeds() {
		return TemplateCache::get_instance()->cache_for('podlove_subscribe_button_feeds', function() {

			$feeds = array_map(function($feed) {
				$file_type = $feed->episode_asset()->file_type();

				$feed_data = [
					'type'    => $file_type->type,
					'format'  => self::feed_format($file_type->extension),
					'url'     => $feed->get_subscribe_url(),
					'variant' => 'high'
				];

				$itunes_feed_id = (int) $feed->itunes_feed_id;
				if ($itunes_feed_id > 0) {
					$feed_data['directory-url-itunes'] = 'https://itunes.apple.com/podcast/id' . $itunes_feed_id;
				}

				return $feed_data;
			}, $this->discoverable_feeds());

			return $feeds;
		});
	}

	/**
	 * Get disoverable podcast feeds.
	 *
	 * @return array list of feeds
	 */
	private function discoverable_feeds() {
		return array_filter($this->podcast->feeds(), function($feed) {
			return $feed->discoverable;
		});
	}

	/**
	 * Format string, ready for subscribe button.
	 *
	 * @param  string $extension File extension of feed enclosures
	 * @return string
	 */
	private static function feed_format($extension) {
		switch ($extension) {
			case 'm4a': return 'aac'; break;
			case 'oga': return 'ogg'; break;
			default:
				return $extension;
			break;
		};
	}

	/**
	 * Get button compatible language string.
	 *
	 * Examples:
	 *
	 * 	language('de');    // => 'de'
	 *  language('de-DE'); // => 'de'
	 *  language('en-GB'); // => 'en'
	 *
	 * @param  string $language language identifier
	 * @return string
	 */
	private static function language($language) {
		return strtolower(explode('-', $language)[0]);
	}

	/**
	 * Size string, ready for subscribe button.
	 *
	 * @param  string $size  button size identifier ('small', 'medium', 'big', 'big-logo')
	 * @param  string $width 'auto' for auto-width
	 * @return string
	 */
	private static function size($size, $width) {
		if ($width == 'auto')
			$size .= ' auto';

		return $size;
	}

}


text:
package io.idcache;

/**
 * Created by bong on 15. 4. 23.
 */
public enum LimitationPolicy {
	THROW_EXCEPTION_POLICY,
	INITIALIZE_POLICY,
	ROLL_TO_MINIMUM_POLICY,
	ROLL_TO_MAXIMUM_POLICY
}


text:
class DeactivateGlReportsIfNoCoa < ActiveRecord::DataMigration
  def up
    has_coa = ChartOfAccount.count > 0

    report_type = ReportType.find_by(name: "GL/Accounting Report")
    report_type.update!(active: has_coa)

    report_type.reports.update_all(active: has_coa)

  end
end


text:
using System;
using System.Web.Mvc;
using DAISPizza.Models.BindingModels;
using DAISPizza.Server.Filters;
using DAISPizza.Services;

namespace DAISPizza.Server.Controllers
{
    public class UsersController : Controller
    {
        private UserManager userManager;

        public UsersController()
            : this(new UserManager())
        {
        }

        public UsersController(UserManager userManager)
        {
            this.userManager = userManager;
        }

        [HttpGet]
        [RejectLoggedInUser]
        public ActionResult Register()
        {
            return this.View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [RejectLoggedInUser]
        public ActionResult Register(RegisterUserBindingModel user)
        {
            if (!this.ModelState.IsValid)
            {
                return this.View(user);
            }

            try
            {
                this.userManager.CreateUser(user);
                return this.RedirectToAction("Index", "Home");
            }
            catch (InvalidOperationException ex)
            {
                ViewBag.ValidationMessage = ex.Message;
                return this.View(user);
            }
        }

        [HttpGet]
        [RejectLoggedInUser]
        public ActionResult Login()
        {
            return this.View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [RejectLoggedInUser]
        public ActionResult Login(LoginUserBindingModel user)
        {
            if (!this.ModelState.IsValid)
            {
                return this.View(user);
            }

            try
            {
                var userWithPassword = this.userManager.GetUser(user);
                this.Session["user"] = userWithPassword;
                return this.RedirectToAction("Index", "Home");
            }
            catch (ArgumentException)
            {
                ViewBag.ValidationMessage = "Invalid login!";
                return this.View(user);
            }
        }

        public ActionResult Logout()
        {
            if (this.User != null)
            {
                this.Session["user"] = null;
            }

            return this.RedirectToAction("Index", "Home");
        }
    }
}


text:
//--------------------------------------
// utgb-core Project
//
// FastqEntry.java
// Since: Jun 14, 2010
//
//--------------------------------------
package org.utgenome.format.fastq;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringWriter;

import org.utgenome.UTGBErrorCode;
import org.utgenome.UTGBException;
import org.xerial.silk.SilkWriter;
import org.xerial.util.StringUtil;

/**
 * An entry of FASTQ format
 *
 * @author leo
 *
 */
public class FastqRead {
	public String seqname;
	public String seq;
	public String qual;

	public FastqRead() {
	}

	public FastqRead(String seqname, String seq, String qual) {
		this.seqname = seqname;
		this.seq = seq;
		this.qual = qual;
	}

	public String toFASTQString() {
		StringBuilder buf = new StringBuilder();
		buf.append("@");
		buf.append(seqname);
		buf.append(StringUtil.NEW_LINE);
		buf.append(seq);
		buf.append(StringUtil.NEW_LINE);
		buf.append("+");
		buf.append(StringUtil.NEW_LINE);
		buf.append(qual);
		buf.append(StringUtil.NEW_LINE);
		return buf.toString();
	}

	public static FastqRead parse(BufferedReader reader) throws UTGBException {

		try {
			String seqNameLine = reader.readLine();
			String sequence = reader.readLine();
			reader.readLine();
			String qual = reader.readLine();

			if (seqNameLine == null || sequence == null || qual == null) {
				return null; // no more entry
			}

			if (seqNameLine.length() < 2) {
				throw new UTGBException(UTGBErrorCode.PARSE_ERROR, "invalid sequence name: " + seqNameLine);
			}

			return new FastqRead(seqNameLine.substring(1), sequence, qual);
		}
		catch (IOException e) {
			throw new UTGBException(UTGBErrorCode.PARSE_ERROR, "invalid fastq block");
		}
	}

	public void toSilk(SilkWriter silk) {
		SilkWriter sub = silk.node("fastq");
		sub.leaf("name", seqname);
		sub.leaf("seq", seq);
		sub.leaf("qual", qual);
	}

	public String toSilk() {
		StringWriter w = new StringWriter();
		w.append("-fastq");
		w.append("\n -name:");
		w.append(seqname);
		w.append("\n -seq :");
		w.append(seq);
		w.append("\n -qual:");
		w.append(qual);
		w.append("\n");
		return w.toString();
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Prateek Jadhwani</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="https://prateekjadhwani.github.io/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//prateekjadhwani.github.io/themes/casper/assets/css/screen.css?v=1559046476108" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://prateekjadhwani.github.io/" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="Prateek Jadhwani" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Prateek Jadhwani" />
    <meta property="og:url" content="https://prateekjadhwani.github.io/" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Prateek Jadhwani" />
    <meta name="twitter:url" content="https://prateekjadhwani.github.io/" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="Prateek Jadhwani" href="https://prateekjadhwani.github.io/rss/" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/styles/atom-one-dark.min.css">

Prateek Jadhwani

// Frontend Developer// Gamer// !Nerd// Dreamer

    Scroll Down

        Page 1 of 3
            Older Posts →

Reduced Motion Media Query to Avoid Vestibular Disorders and Seizures

When I was doing my research in Accessibility, I came across the term Vestibular Disorder. I really didn't know much about it at that time. »

            Prateek Jadhwani
             on css3, accessibility, Reduced Motion, prefers-reduced-motion, media query
            <time class="post-date" datetime="2019-05-28">28 May 2019</time>

Picture In Picture API

If you are a software engineer, you must have heard of the term "No code is the best code". It simply means that if you can »

            Prateek Jadhwani
             on javascript, css3, pictureinpicture, picture, video, api
            <time class="post-date" datetime="2019-05-22">22 May 2019</time>

Where is Prateek + a Unity Game?

I know I have been missing in action and haven’t written anything at all in a  really long time. And I will be honest& »

            Prateek Jadhwani
             on Blog
            <time class="post-date" datetime="2019-05-15">15 May 2019</time>

Contextual Styling Demo

After reading Simurai's article on Contextual Styling with Custom Properties, I decided to create a small demo using the same tech. See the Pen CSS Variable »

            Prateek Jadhwani
             on CSS3, checkbox, demo, css variables, css theme, theme, data-theme
            <time class="post-date" datetime="2018-04-02">02 April 2018</time>

Showing or Hiding Password

Got bored while my PS4 was installing Monster Hunter World. And ended up making this concept Show Password by Prekesh Dribbble UI This is what the »

            Prateek Jadhwani
             on CSS3, checkbox, demo, password, show, hide
            <time class="post-date" datetime="2018-03-10">10 March 2018</time>

Building WebComponent based Progressive WebApp in Stencil JS - Part 02

In Part 01, we looked into the hello-world example. In this part, we will be working further on the Mail Client. Observations Here are the various »

            Prateek Jadhwani
             on webcomponents, stencil, stenciljs, helloworld, pwa, webapp
            <time class="post-date" datetime="2018-03-08">08 March 2018</time>

Building WebComponent based Progressive WebApp in Stencil JS - Part 01

Stencil.js is a compiler for WebComponents. It lets you write Web Components in TypeScript and jsx. If you are new to Stencil.js please take »

            Prateek Jadhwani
             on webcomponents, stencil, stenciljs, helloworld, pwa, webapp
            <time class="post-date" datetime="2018-03-03">03 March 2018</time>

Universal Site is the new Accessible Site

When we talk about an accessible website, the first thing that comes to our mind is a user who is unable to see the screen. And »

            Prateek Jadhwani
             on accessibility, book, universal, site, website, screen reader
            <time class="post-date" datetime="2018-03-01">01 March 2018</time>

<dialog> element: Modals for the future.

I recently came across a new spec with the name <dialog> element [1]. And decided to see if it works properly. This is what »

            Prateek Jadhwani
             on dialog, CSS3, focus, pseudo class, demo, backdrop
            <time class="post-date" datetime="2018-02-14">14 February 2018</time>

Accessibility in a modal

It is said that you learn a new thing every day, and so I did. Accessibility has been in the market for a very long time »

            Prateek Jadhwani
             on accessibility, modal, html5, css3, javascript
            <time class="post-date" datetime="2018-02-08">08 February 2018</time>

        Page 1 of 3
            Older Posts →

Prateek Jadhwani © 2019

Proudly published with HubPress


text:
/* eslint-env mocha */
/* eslint-disable padded-blocks, no-unused-expressions */

import { assert } from 'chai'
import TmLabs from '../src/index'
import Account from '../src/Account'
import Command from '../src/Command'
import {
  Status,
  Fetch,
  Hash
} from '../src/command'

describe('Class Tests', () => {
  describe('Class TmLabs', () => {
    it('Empty constructor', () => {
      const tmLabs = new TmLabs()
      assert.isEmpty(tmLabs.history)
    })
    it('Multiple requests. domain requests. throw error for invalid domains', async () => {
      const tmLabs = new TmLabs()
      const domains = ['google.com', 'facebook.com', 'ibm.com', 'example.com', 'assadasf', '127.0.0.1']
      let results
      try {
        results = await tmLabs.fetchBatch('dns', domains.map(domain => ({
          domain: domain
        })), {throw: true})
      } catch (e) {
        assert.isUndefined(results)
        assert.equal(e.message, 'Method required param \'domain\' validation error', 'exception message')
      }
    })
    it('Multiple requests. domain requests. invalid domains error in result array', async () => {
      const tmLabs = new TmLabs()
      const domains = ['google.com', 'facebook.com', 'ibm.com', 'example.com', 'assadasf', '127.0.0.1']
      const results = await tmLabs.fetchBatch('dns', domains.map(domain => ({
        domain: domain
      })))
      assert.lengthOf(results, 6)
    })
    it('Multiple commands. fetch commands. error in results array', async () => {
      const tmLabs = new TmLabs()
      const commands = [[new Fetch({
        method: 'ip'
      }), {
        ip: '127.0.0.1'
      }], [new Fetch({
        method: 'ip'
      }), {
        ip: '173.194.122.233'
      }], [new Command('fetch', {
        method: 'ip'
      }), {
        ip: '173.194.122.234'
      }]]
      let results
      try {
        results = await tmLabs.runBatch(commands.map(command => ({
          command: command[0],
          params: command[1]
        })))
      } catch (e) {
        assert.equal(e.message, 'Method required param \'domain\' validation error', 'exception message')
        // assert.isUndefined(results)
      }
      assert.lengthOf(results, 3)
      assert.equal(results[0].state, 'rejected')
      assert.instanceOf(results[0].reason, Error)
    })
    it('Multiple commands. hash & fetch commands. error in results array', async () => {
      const tmLabs = new TmLabs()
      const commands = [[new Hash(), {
        hash: 'testing hash'
      }], [new Fetch({
        method: 'ip'
      }), {
        ip: '173.194.122.233'
      }], [new Command('fetch', {
        method: 'ip'
      }), {
        ip: '173.194.122.234'
      }], [new Hash(), {
        hash: 'ff2178501f16e2c6ab435cfbabd45c90e7419c0e828d7da9d5c63acf016ba051'
      }], [new Hash(), {
        file: 'bower.json'
      }], [new Status(), false]]
      const results = await tmLabs.runBatch(commands.map(command => ({
        command: command[0],
        params: command[1]
      })))
      assert.lengthOf(results, 6)
      assert.equal(results[0].state, 'rejected')
      assert.instanceOf(results[0].reason, Error)
      assert.equal(results[5].state, 'fulfilled')
      assert.hasAllKeys(results[5].value.content, [
        'balance_remaining', 'subscriptions'
      ], 'has balance & stats keys in body')
    })
    it('Get account subscriptions', async () => {
      const tmLabs = new TmLabs()
      const subscriptions = await tmLabs.getSubscriptions()
      assert.isDefined(subscriptions)
    })
  })
  describe('Class Account', () => {
    it('get account status', async () => {
      const account = new Account()
      const statusData = await account.getStatus()
      assert.hasAllKeys(statusData, ['balance_reset', 'balance_remaining', 'subscriptions'])
    })
    it('get account balance', async () => {
      const account = new Account()
      const statusData = await account.getBalance()
      assert.hasAllKeys(statusData, ['reset', 'remaining'])
    })
    it('get account subscriptions', async () => {
      const account = new Account()
      const statusData = await account.getSubscriptions()
      assert.isDefined(statusData)
    })
  })
})


text:
package work.technie.popularmovies;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

import work.technie.popularmovies.data.MovieContract;
import work.technie.popularmovies.utils.Utility;

/**
 * Created by anupam on 4/12/15.
 */
public class MainActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final String SELECTED_KEY = "selected_position";
    private static final int MOVIE_LOADER = 0;
    private static final String[] MOVIE_COLUMNS = {

            MovieContract.Movies.TABLE_NAME + "." + MovieContract.Movies._ID,
            MovieContract.Movies.PAGE,
            MovieContract.Movies.POSTER_PATH,
            MovieContract.Movies.ADULT,
            MovieContract.Movies.OVERVIEW,
            MovieContract.Movies.RELEASE_DATE,
            MovieContract.Movies.MOVIE_ID,
            MovieContract.Movies.ORIGINAL_TITLE,
            MovieContract.Movies.ORIGINAL_LANGUAGE,
            MovieContract.Movies.TITLE,
            MovieContract.Movies.BACKDROP_PATH,
            MovieContract.Movies.POPULARITY,
            MovieContract.Movies.VOTE_COUNT,
            MovieContract.Movies.VOTE_AVERAGE,
            MovieContract.Movies.FAVOURED
    };
    private static final String[] FAVOURITE_MOVIE_COLUMNS = {

            MovieContract.Favourites.TABLE_NAME + "." + MovieContract.Favourites._ID,
            MovieContract.Favourites.PAGE,
            MovieContract.Favourites.POSTER_PATH,
            MovieContract.Favourites.ADULT,
            MovieContract.Favourites.OVERVIEW,
            MovieContract.Favourites.RELEASE_DATE,
            MovieContract.Favourites.MOVIE_ID,
            MovieContract.Favourites.ORIGINAL_TITLE,
            MovieContract.Favourites.ORIGINAL_LANGUAGE,
            MovieContract.Favourites.TITLE,
            MovieContract.Favourites.BACKDROP_PATH,
            MovieContract.Favourites.POPULARITY,
            MovieContract.Favourites.VOTE_COUNT,
            MovieContract.Favourites.VOTE_AVERAGE,
            MovieContract.Favourites.FAVOURED
    };
    public static int COL_ID = 0;
    public static int COL_PAGE = 1;
    public static int COL_POSTER_PATH = 2;
    public static int COL_ADULT = 3;
    public static int COL_OVERVIEW = 4;
    //private boolean isLoading=false;
    //private TextView loading;
    //private String lastSortingOrder="initial";
    public static int COL_RELEASE_DATE = 5;
    public static int COL_MOVIE_ID = 6;
    public static int COL_ORIGINAL_TITLE = 7;
    public static int COL_ORIGINAL_LANG = 8;
    public static int COL_TITLE = 9;
    public static int COL_BACKDROP_PATH = 10;
    public static int COL_POPULARITY = 11;
    public static int COL_VOTE_COUNT = 12;
    public static int COL_VOTE_AVERAGE = 13;
    public static int COL_FAVOURED = 14;
    private static boolean firstTime = true;
    private MovieArrayAdapter movieListAdapter;
    private int mPosition = ListView.INVALID_POSITION;
    private GridView gridView;
    private ArrayList<MovieInfo> movieList;
    private SwipeRefreshLayout swipeRefreshLayout;
    //private static final int MAX_PAGE=100;
    private int PAGE_LOADED = 0;
    private View rootView;

    public MainActivityFragment() {

    }

    private void updateMovieList() {
        FetchMovieTask weatherTask = new FetchMovieTask(getActivity());
        String sortingOrder = Utility.getPreferredSorting(getActivity());
        if (!sortingOrder.equalsIgnoreCase(getResources().getString(R.string.pref_sort_favourite))) {
            {/*
            if(!sortingOrder.equals(lastSortingOrder)){
                PAGE_LOADED=0;
                lastSortingOrder=sortingOrder;
            }*/
                weatherTask.execute(sortingOrder, String.valueOf(PAGE_LOADED + 1));
            }
        } else if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putParcelableArrayList("movieList", movieList);
        // When tablets rotate, the currently selected list item needs to be saved.
        // When no item is selected, mPosition will be set to GridView.INVALID_POSITION,
        // so check for that before storing.
        if (mPosition != ListView.INVALID_POSITION) {
            outState.putInt(SELECTED_KEY, mPosition);
        }
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (firstTime == true) {
            if (!Utility.hasNetworkConnection(getActivity())) {
                Toast.makeText(getContext(), "Network Not Available!", Toast.LENGTH_LONG).show();
            }
            updateMovieList();
            ContentValues movieValues = new ContentValues();
            movieValues.put(MovieContract.Favourites.PAGE, "0");
            movieValues.put(MovieContract.Favourites.POSTER_PATH, "0");
            movieValues.put(MovieContract.Favourites.ADULT, "0");
            movieValues.put(MovieContract.Favourites.OVERVIEW, "0");
            movieValues.put(MovieContract.Favourites.RELEASE_DATE, "0");
            movieValues.put(MovieContract.Favourites.MOVIE_ID, "0");
            movieValues.put(MovieContract.Favourites.ORIGINAL_TITLE, "0");
            movieValues.put(MovieContract.Favourites.ORIGINAL_LANGUAGE, "0");
            movieValues.put(MovieContract.Favourites.TITLE, "0");
            movieValues.put(MovieContract.Favourites.BACKDROP_PATH, "0");
            movieValues.put(MovieContract.Favourites.POPULARITY, "0");
            movieValues.put(MovieContract.Favourites.VOTE_COUNT, "0");
            movieValues.put(MovieContract.Favourites.VOTE_AVERAGE, "0");
            movieValues.put(MovieContract.Favourites.SORT_BY, "0");
            getActivity().getContentResolver().insert(MovieContract.Favourites.buildMovieUri(), movieValues);
            firstTime = !firstTime;
        }

        if (savedInstanceState == null || !savedInstanceState.containsKey("movieList")) {
            movieList = new ArrayList<>();
        } else {
            movieList = savedInstanceState.getParcelableArrayList("movieList");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // The ArrayAdapter will take data from a source and
        // use it to populate the ListView it's attached to.
        movieListAdapter =
                new MovieArrayAdapter(
                        getActivity(), null, 0);

        rootView = inflater.inflate(R.layout.fragment_main, container, false);

        // Get a reference to the GridView, and attach this adapter to it.
        gridView = (GridView) rootView.findViewById(R.id.gridview_movie);
        gridView.setAdapter(movieListAdapter);
        //loading=(TextView)rootView.findViewById(R.id.loading);

        //startLoad();
        gridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                final int size = gridView.getWidth();
                int numCol = (int) Math.round((double) size / (double) getResources().getDimensionPixelSize(R.dimen.poster_width));
                gridView.setNumColumns(numCol);
                //Log.d("MainActivityFrag", "Value: " +size+" "+numCol+" "+getResources().getDimensionPixelSize(R.dimen.poster_width)+" "+test);
            }
        });

        //gridView.setNumColumns(5);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
                if (cursor != null) {
                    ((Callback) getActivity())
                            .onItemSelected(cursor.getString(COL_MOVIE_ID));
                }
                mPosition = position;
            }
        });
        // If there's instance state, mine it for useful information.
        // The end-goal here is that the user never knows that turning their device sideways
        // does crazy lifecycle related things.  It should feel like some stuff stretched out,
        // or magically appeared to take advantage of room, but data or place in the app was never
        // actually *lost*.
        if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_KEY)) {
            // The listview probably hasn't even been populated yet.  Actually perform the
            // swapout in onLoadFinished.
            mPosition = savedInstanceState.getInt(SELECTED_KEY);
        }

       /*gridView.setOnScrollListener(
                new AbsListView.OnScrollListener() {
                    @Override
                    public void onScrollStateChanged(AbsListView view, int scrollState) {

                    }

                    @Override
                    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                        int lastInScreen = firstVisibleItem + visibleItemCount;
                        if (lastInScreen == totalItemCount) {
                            //Log.e("time to scroll","scroll");
                            startLoad();
                        }
                    }
                }

        );
*/
        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.main_swipe_refresh);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (Utility.hasNetworkConnection(getActivity())) {
                    getActivity().getContentResolver().delete(MovieContract.Movies.CONTENT_URI, null, null);
                    updateMovieList();
                } else {
                    Toast.makeText(getContext(), "Network Not Available!", Toast.LENGTH_SHORT).show();
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        return rootView;
    }

    /*
        private void startLoad(){
            if(isLoading||PAGE_LOADED>=MAX_PAGE){
                return;
            }
            isLoading=true;
            if (loading!=null){
                loading.setVisibility(View.VISIBLE);
            }

            updateMovieList();
        }
        private void stopLoad(){
            if(!isLoading){
                return;
            }
            isLoading=false;
            if (loading!=null){
                loading.setVisibility(View.GONE);
            }
        }*/
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        getLoaderManager().initLoader(MOVIE_LOADER, null, this);
        super.onActivityCreated(savedInstanceState);
    }

    // since we read the new soring order when we create the loader, all we need to do is restart things
    void onSortingChanged() {
        String sorting = Utility.getPreferredSorting(getActivity());
        updateMovieList();
        getLoaderManager().restartLoader(MOVIE_LOADER, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {

        String sortOrder = MovieContract.Movies._ID + " ASC";
        Uri movie = MovieContract.Movies.buildMovieUri();
        Uri fav = MovieContract.Favourites.buildMovieUri();
        String sorting = Utility.getPreferredSorting(getActivity());
        if (sorting.equalsIgnoreCase(getResources().getString(R.string.pref_sort_favourite))) {
            return new CursorLoader(getActivity(),
                    fav,
                    FAVOURITE_MOVIE_COLUMNS,
                    MovieContract.Favourites.FAVOURED + " = ?",
                    new String[]{"1"},
                    sortOrder);
        }
        return new CursorLoader(getActivity(),
                movie,
                MOVIE_COLUMNS,
                MovieContract.Movies.SORT_BY + " = ?",
                new String[]{sorting},
                sortOrder);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        movieListAdapter.swapCursor(cursor);
        swipeRefreshLayout.setRefreshing(false);
        if (mPosition != ListView.INVALID_POSITION) {
            // If we don't need to restart the loader, and there's a desired position to restore
            // to, do so now.
            gridView.smoothScrollToPosition(mPosition);
        }
        try {
            TextView info = (TextView) rootView.findViewById(R.id.empty);
            if (movieListAdapter.getCount() == 0) {
                String sorting = Utility.getPreferredSorting(getActivity());
                if (sorting.equalsIgnoreCase(getResources().getString(R.string.pref_sort_favourite))) {
                    info.setText("Favourite List is Empty!");
                }
                info.setVisibility(View.VISIBLE);
            } else {
                info.setVisibility(View.GONE);
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        movieListAdapter.swapCursor(null);
    }

    /**
     * A callback interface that all activities containing this fragment must
     * implement. This mechanism allows activities to be notified of item
     * selections.
     */
    public interface Callback {
        /**
         * DetailFragmentCallback for when an item has been selected.
         *
         * @param movieUri
         */
        void onItemSelected(String movieUri);
    }
}


text:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Collections.Generic;
using WeifenLuo.WinFormsUI.Docking;

namespace NekoKun.Core
{
    [PadDefaultLocation(WeifenLuo.WinFormsUI.Docking.DockState.DockBottom)]
    public class OutputPad : AbstractPad, IClipboardHandler, IUndoHandler, IDeleteHandler, ISelectAllHandler
    {
        #region Static Members
        private static List<IOutputProvider> providers = new List<IOutputProvider>();

        public static event EventHandler ProviderAttached;
        private static void OnProviderAttached(IOutputProvider sender)
        {
            if (ProviderAttached != null)
                ProviderAttached(sender, EventArgs.Empty);
        }
        public static void Attach(IOutputProvider output)
        {
            providers.Add(output);
            OnProviderAttached(output);
        }

        public static event EventHandler ProviderDetached;
        private static void OnProviderDetatched(IOutputProvider sender)
        {
            if (ProviderDetached != null)
                ProviderDetached(sender, EventArgs.Empty);
        }
        public static void Detach(IOutputProvider output)
        {
            if (providers.Contains(output))
            {
                providers.Remove(output);
                OnProviderDetatched(output);
            }
        }

        public static IOutputProvider[] Providers
        {
            get
            {
                return providers.ToArray();
            }
        }
        #endregion

        protected ToolStrip Toolbar = new ToolStrip();
        protected ToolStripComboBox ItemBox = new ToolStripComboBox();
        protected Panel ViewPanel = new Panel();
        protected IOutputProvider CurrentProvider;
        protected Control CurrentControl;

        public OutputPad()
        {
            var iconO = global::NekoKun.UI.Properties.Resources.OutputWindow.Clone() as Bitmap;
            iconO.MakeTransparent(System.Drawing.Color.Fuchsia);
            this.Icon = Icon.FromHandle(iconO.GetHicon());

            ViewPanel.Dock = DockStyle.Fill;

            ItemBox.AutoSize = false;
            ItemBox.ComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
            ItemBox.Width = 300;
            ItemBox.SelectedIndexChanged += new EventHandler(ItemBox_SelectedIndexChanged);
            ItemBox.Items.AddRange(Providers);
            ItemBox.SelectedIndex = this.ItemBox.Items.Count - 1;
            OutputPad.ProviderAttached += new EventHandler(OutputPad_ProviderAttached);
            OutputPad.ProviderDetached += new EventHandler(OutputPad_ProviderDetached);

            Toolbar.Items.Add(new ToolStripLabel("显示输出来源(&S):"));
            Toolbar.Items.Add(ItemBox);
            Toolbar.GripStyle = ToolStripGripStyle.Hidden;
            Toolbar.Dock = DockStyle.Top;

            this.Text = "输出";
            this.Controls.Add(ViewPanel);
            this.Controls.Add(Toolbar);
        }

        protected override void Dispose(bool disposing)
        {
            OutputPad.ProviderAttached -= new EventHandler(OutputPad_ProviderAttached);
            OutputPad.ProviderDetached -= new EventHandler(OutputPad_ProviderDetached);
            base.Dispose(disposing);
        }

        void OutputPad_ProviderDetached(object sender, EventArgs e)
        {
            IOutputProvider p = sender as IOutputProvider;
            if (p != null)
            {
                this.ItemBox.Items.Remove(p);
                if (CurrentProvider == p)
                {
                    this.ItemBox.SelectedItem = this.ItemBox.Items.Count > 0 ? this.ItemBox.Items[this.ItemBox.Items.Count - 1] : null;
                }
            }
        }

        void OutputPad_ProviderAttached(object sender, EventArgs e)
        {
            IOutputProvider p = sender as IOutputProvider;
            if (p != null)
            {
                this.ItemBox.Items.Add(p);
                this.ItemBox.SelectedIndex = this.ItemBox.Items.Count - 1;
            }
        }

        void ItemBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (CurrentControl != null)
            {
                ViewPanel.Controls.Remove(CurrentControl);
                CurrentControl = null;
            }

            if (CurrentProvider != null)
            {
                CurrentProvider = null;
            }

            if (this.ItemBox.SelectedItem != null)
            {
                CurrentProvider = this.ItemBox.SelectedItem as IOutputProvider;
                CurrentControl = CurrentProvider.OutputViewContent;

                CurrentControl.Dock = DockStyle.Fill;
                ViewPanel.Controls.Add(CurrentControl);
            }
        }

        #region IClipboardHandler, IUndoHandler, IDeleteHandler, ISelectAllHandler 成员
        public bool CanCut
        {
            get {
                var i = CurrentControl as IClipboardHandler;
                return i == null ? i.CanCut : false;
            }
        }

        public bool CanCopy
        {
            get
            {
                var i = CurrentControl as IClipboardHandler;
                return i == null ? i.CanCopy : false;
            }
        }

        public bool CanPaste
        {
            get
            {
                var i = CurrentControl as IClipboardHandler;
                return i == null ? i.CanPaste : false;
            }
        }

        public void Cut()
        {
            var i = CurrentControl as IClipboardHandler;
            if (i == null)
                i.Cut();
        }

        public void Copy()
        {
            var i = CurrentControl as IClipboardHandler;
            if (i == null)
                i.Copy();
        }

        public void Paste()
        {
            var i = CurrentControl as IClipboardHandler;
            if (i == null)
                i.Paste();
        }

        public bool CanUndo
        {
            get
            {
                var i = CurrentControl as IUndoHandler;
                return i == null ? i.CanUndo : false;
            }
        }

        public bool CanRedo
        {
            get
            {
                var i = CurrentControl as IUndoHandler;
                return i == null ? i.CanRedo : false;
            }
        }

        public void Undo()
        {
            var i = CurrentControl as IUndoHandler;
            if (i == null)
                i.Undo();
        }

        public void Redo()
        {
            var i = CurrentControl as IUndoHandler;
            if (i == null)
                i.Redo();
        }

        public bool CanDelete
        {
            get
            {
                var i = CurrentControl as IDeleteHandler;
                return i == null ? i.CanDelete : false;
            }
        }

        public void Delete()
        {
            var i = CurrentControl as IDeleteHandler;
            if (i == null)
                i.Delete();
        }

        public bool CanSelectAll
        {
            get
            {
                var i = CurrentControl as ISelectAllHandler;
                return i == null ? i.CanSelectAll : false;
            }
        }

        public void SelectAll()
        {
            var i = CurrentControl as ISelectAllHandler;
            if (i == null)
                i.SelectAll();
        }

        public bool CanShowFindDialog
        {
            get
            {
                var i = CurrentControl as IFindReplaceHandler;
                return i == null ? i.CanShowFindDialog : false;
            }
        }

        public bool CanShowReplaceDialog
        {
            get
            {
                var i = CurrentControl as IFindReplaceHandler;
                return i == null ? i.CanShowReplaceDialog : false;
            }
        }

        public void ShowFindDialog()
        {
            var i = CurrentControl as IFindReplaceHandler;
            if (i == null)
                i.ShowFindDialog();
        }

        public void ShowReplaceDialog()
        {
            var i = CurrentControl as IFindReplaceHandler;
            if (i == null)
                i.ShowReplaceDialog();
        }
        #endregion
    }
}


text:
// permissive-fov.cc

#include <list>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>

#include "permissive-fov.h"

using std::list;
using std::max;
using std::min;
using std::string;

namespace
{
  struct offsetT
  {
  public:
    offsetT(short newX = 0, short newY = 0)
      : x(newX)
        , y(newY)
    {
    }
  public:
    short x;
    short y;
  };

  std::ostream & operator<<(std::ostream & stream, offsetT const & right)
  {
    stream << "(" << right.x << ", " << right.y << ")";
    return stream;
  }

  struct fovStateT
  {
    offsetT source;
    permissiveMaskT * mask;
    isBlockedFunction isBlocked;
    visitFunction visit;
    void * context;

    offsetT quadrant;
    offsetT extent;
  };

  struct lineT
  {
    lineT(offsetT newNear=offsetT(), offsetT newFar=offsetT())
      : near(newNear)
      , far(newFar)
    {
    }

    bool isBelow(offsetT const & point)
    {
      return relativeSlope(point) > 0;
    }

    bool isBelowOrContains(offsetT const & point)
    {
      return relativeSlope(point) >= 0;
    }

    bool isAbove(offsetT const & point)
    {
      return relativeSlope(point) < 0;
    }

    bool isAboveOrContains(offsetT const & point)
    {
      return relativeSlope(point) <= 0;
    }

    bool doesContain(offsetT const & point)
    {
      return relativeSlope(point) == 0;
    }

    // negative if the line is above the point.
    // positive if the line is below the point.
    // 0 if the line is on the point.
    int relativeSlope(offsetT const & point)
    {
      return (far.y - near.y)*(far.x - point.x)
        - (far.y - point.y)*(far.x - near.x);
    }

    offsetT near;
    offsetT far;
  };

  struct bumpT
  {
    bumpT() : parent(NULL) {}
    offsetT location;
    bumpT * parent;
  };

  struct fieldT
  {
    fieldT() : steepBump(NULL), shallowBump(NULL) {}
    lineT steep;
    lineT shallow;
    bumpT * steepBump;
    bumpT * shallowBump;
  };

  void visitSquare(fovStateT const * state,
                   offsetT const & dest, list<fieldT>::iterator & currentField,
                   list<bumpT> & steepBumps,
                   list<bumpT> & shallowBumps,
                   list<fieldT> & activeFields);
  list<fieldT>::iterator checkField(list<fieldT>::iterator currentField,
                                    list<fieldT> & activeFields);
  void addShallowBump(offsetT const & point,
                      list<fieldT>::iterator currentField,
                      list<bumpT> & steepBumps,
                      list<bumpT> & shallowBumps);
  void addSteepBump(offsetT const & point,
                    list<fieldT>::iterator currentField,
                    list<bumpT> & steepBumps,
                    list<bumpT> & shallowBumps);
  bool actIsBlocked(fovStateT const * state, offsetT const & pos);

  void calculateFovQuadrant(fovStateT const * state)
  {
    list<bumpT> steepBumps;
    list<bumpT> shallowBumps;
    // activeFields is sorted from shallow-to-steep.
    list<fieldT> activeFields;
    activeFields.push_back(fieldT());
    activeFields.back().shallow.near = offsetT(0, 1);
    activeFields.back().shallow.far = offsetT(state->extent.x, 0);
    activeFields.back().steep.near = offsetT(1, 0);
    activeFields.back().steep.far = offsetT(0, state->extent.y);

    offsetT dest(0, 0);

    // Visit the source square exactly once (in quadrant 1).
    if (state->quadrant.x == 1 && state->quadrant.y == 1)
    {
      actIsBlocked(state, dest);
    }

    list<fieldT>::iterator currentField = activeFields.begin();
    short i = 0;
    short j = 0;
    int maxI = state->extent.x + state->extent.y;
    // For each square outline
    for (i = 1; i <= maxI && ! activeFields.empty(); ++i)
    {
      int startJ = max(0, i - state->extent.x);
      int maxJ = min(i, state->extent.y);
      // Visit the nodes in the outline
      for (j = startJ; j <= maxJ && currentField != activeFields.end(); ++j)
      {
        dest.x = i-j;
        dest.y = j;
        visitSquare(state, dest, currentField, steepBumps, shallowBumps,
                    activeFields);
      }
      currentField = activeFields.begin();
    }
  }

  void visitSquare(fovStateT const * state,
                   offsetT const & dest, list<fieldT>::iterator & currentField,
                   list<bumpT> & steepBumps,
                   list<bumpT> & shallowBumps,
                   list<fieldT> & activeFields)
  {
    // The top-left and bottom-right corners of the destination square.
    offsetT topLeft(dest.x, dest.y + 1);
    offsetT bottomRight(dest.x + 1, dest.y);
    while (currentField != activeFields.end()
           && currentField->steep.isBelowOrContains(bottomRight))
    {
      // case ABOVE
      // The square is in case 'above'. This means that it is ignored
      // for the currentField. But the steeper fields might need it.
      ++currentField;
    }
    if (currentField == activeFields.end())
    {
      // The square was in case 'above' for all fields. This means that
      // we no longer care about it or any squares in its diagonal rank.
      return;
    }

    // Now we check for other cases.
    if (currentField->shallow.isAboveOrContains(topLeft))
    {
      // case BELOW
      // The shallow line is above the extremity of the square, so that
      // square is ignored.
      return;
    }
    // The square is between the lines in some way. This means that we
    // need to visit it and determine whether it is blocked.
    bool isBlocked = actIsBlocked(state, dest);
    if (!isBlocked)
    {
      // We don't care what case might be left, because this square does
      // not obstruct.
      return;
    }

    if (currentField->shallow.isAbove(bottomRight)
        && currentField->steep.isBelow(topLeft))
    {
      // case BLOCKING
      // Both lines intersect the square. This current field has ended.
      currentField = activeFields.erase(currentField);
    }
    else if (currentField->shallow.isAbove(bottomRight))
    {
      // case SHALLOW BUMP
      // The square intersects only the shallow line.
      addShallowBump(topLeft, currentField, steepBumps, shallowBumps);
      currentField = checkField(currentField, activeFields);
    }
    else if (currentField->steep.isBelow(topLeft))
    {
      // case STEEP BUMP
      // The square intersects only the steep line.
      addSteepBump(bottomRight, currentField, steepBumps, shallowBumps);
      currentField = checkField(currentField, activeFields);
    }
    else
    {
      // case BETWEEN
      // The square intersects neither line. We need to split into two fields.
      list<fieldT>::iterator steeperField = currentField;
      list<fieldT>::iterator shallowerField = activeFields.insert(currentField, *currentField);
      addSteepBump(bottomRight, shallowerField, steepBumps, shallowBumps);
      checkField(shallowerField, activeFields);
      addShallowBump(topLeft, steeperField, steepBumps, shallowBumps);
      currentField = checkField(steeperField, activeFields);
    }
  }

  list<fieldT>::iterator checkField(list<fieldT>::iterator currentField,
                                    list<fieldT> & activeFields)
  {
    list<fieldT>::iterator result = currentField;
    // If the two slopes are colinear, and if they pass through either
    // extremity, remove the field of view.
    if (currentField->shallow.doesContain(currentField->steep.near)
        && currentField->shallow.doesContain(currentField->steep.far)
        && (currentField->shallow.doesContain(offsetT(0, 1))
            || currentField->shallow.doesContain(offsetT(1, 0))))
    {
      result = activeFields.erase(currentField);
    }
    return result;
  }

  void addShallowBump(offsetT const & point,
                      list<fieldT>::iterator currentField,
                      list<bumpT> & steepBumps,
                      list<bumpT> & shallowBumps)
  {
    // First, the far point of shallow is set to the new point.
    currentField->shallow.far = point;
    // Second, we need to add the new bump to the shallow bump list for
    // future steep bump handling.
    shallowBumps.push_back(bumpT());
    shallowBumps.back().location = point;
    shallowBumps.back().parent = currentField->shallowBump;
    currentField->shallowBump = & shallowBumps.back();
    // Now we have too look through the list of steep bumps and see if
    // any of them are below the line.
    // If there are, we need to replace near point too.
    bumpT * currentBump = currentField->steepBump;
    while (currentBump != NULL)
    {
      if (currentField->shallow.isAbove(currentBump->location))
      {
        currentField->shallow.near = currentBump->location;
      }
      currentBump = currentBump->parent;
    }
  }

  void addSteepBump(offsetT const & point,
                    list<fieldT>::iterator currentField,
                    list<bumpT> & steepBumps,
                    list<bumpT> & shallowBumps)
  {
    currentField->steep.far = point;
    steepBumps.push_back(bumpT());
    steepBumps.back().location = point;
    steepBumps.back().parent = currentField->steepBump;
    currentField->steepBump = & steepBumps.back();
    // Now look through the list of shallow bumps and see if any of them
    // are below the line.
    bumpT * currentBump = currentField->shallowBump;
    while (currentBump != NULL)
    {
      if (currentField->steep.isBelow(currentBump->location))
      {
        currentField->steep.near = currentBump->location;
      }
      currentBump = currentBump->parent;
    }
  }

  bool actIsBlocked(fovStateT const * state, offsetT const & pos)
  {
    offsetT adjustedPos(pos.x*state->quadrant.x + state->source.x,
                        pos.y*state->quadrant.y + state->source.y);
    bool result = state->isBlocked(adjustedPos.x, adjustedPos.y,
                                   state->context) == 1;
    if ((state->quadrant.x * state->quadrant.y == 1
         && pos.x == 0 && pos.y != 0)
        || (state->quadrant.x * state->quadrant.y == -1
            && pos.y == 0 && pos.x != 0)
        || doesPermissiveVisit(state->mask, pos.x*state->quadrant.x,
                               pos.y*state->quadrant.y) == 0)
    {
      return result;
    }
    else
    {
      state->visit(adjustedPos.x, adjustedPos.y, state->context);
      return result;
    }
  }
}

void permissiveSquareFov(short sourceX, short sourceY,
                         int inRadius, isBlockedFunction isBlocked,
                         visitFunction visit, void * context)
{
  int radius = max(inRadius, 0);
  permissiveMaskT mask;
  mask.north = radius;
  mask.south = radius;
  mask.east = radius;
  mask.west = radius;
  mask.width = 2*radius + 1;
  mask.height = 2*radius + 1;
  mask.mask = NULL;
  permissiveFov(sourceX, sourceY, &mask, isBlocked, visit, context);
}

void permissiveFov(short sourceX, short sourceY,
                   permissiveMaskT * mask, isBlockedFunction isBlocked,
                   visitFunction visit, void * context)
{
  fovStateT state;
  state.source = offsetT(sourceX, sourceY);
  state.mask = mask;
  state.isBlocked = isBlocked;
  state.visit = visit;
  state.context = context;

  static const int quadrantCount = 4;
  static const offsetT quadrants[quadrantCount] = {offsetT(1, 1),
                                                   offsetT(-1, 1),
                                                   offsetT(-1, -1),
                                                   offsetT(1, -1)};
  offsetT extents[quadrantCount] = {offsetT(mask->east, mask->north),
                                    offsetT(mask->west, mask->north),
                                    offsetT(mask->west, mask->south),
                                    offsetT(mask->east, mask->south)};
  int quadrantIndex = 0;
  for (; quadrantIndex < quadrantCount; ++quadrantIndex)
  {
    state.quadrant = quadrants[quadrantIndex];
    state.extent = extents[quadrantIndex];
    calculateFovQuadrant(&state);
  }
}

namespace
{
  static const int BITS_PER_INT = sizeof(int)*8;

  #define GET_INT(x,y) (((x)+(y)*mask->width)/BITS_PER_INT)
  #define GET_BIT(x,y) (((x)+(y)*mask->width)%BITS_PER_INT)

  unsigned int * allocateMask(int width, int height)
  {
    int cellCount = width * height;
    int intCount = cellCount / BITS_PER_INT;
    if (cellCount % BITS_PER_INT != 0)
    {
      ++intCount;
    }
    return new unsigned int[intCount];
  }
}

permissiveErrorT initPermissiveMask(permissiveMaskT * mask, int north,
                                    int south, int east, int west)
{
  permissiveErrorT result = PERMISSIVE_NO_FAILURE;
  mask->north = max(north, 0);
  mask->south = max(south, 0);
  mask->east = max(east, 0);
  mask->west = max(west, 0);
  mask->width = mask->west + 1 + mask->east;
  mask->height = mask->south + 1 + mask->north;
  mask->mask = allocateMask(mask->width, mask->height);
  if (mask->mask == NULL)
  {
    result = PERMISSIVE_OUT_OF_MEMORY;
  }
  return result;
}

permissiveErrorT loadPermissiveMask(permissiveMaskT * mask,
                                    char const * fileName)
{
  list<string> input;
  size_t maxLineSize = 1;
  std::ifstream file(fileName, std::ios::in);
  if (!file)
  {
    return PERMISSIVE_FAILED_TO_OPEN_FILE;
  }
  permissiveErrorT result = PERMISSIVE_NO_FAILURE;
  string line;
  getline(file, line);
  while (file)
  {
    maxLineSize = max(maxLineSize, line.size());
    input.push_front(line);
    getline(file, line);
  }
  mask->width = static_cast<int>(maxLineSize);
  mask->height = static_cast<int>(input.size());
  mask->mask = allocateMask(mask->width, mask->height);
  // TODO: Out of memory
  list<string>::iterator inputPos = input.begin();
  unsigned int * intPos = mask->mask;
  int bitPos = 0;
  for (int i = 0; i < mask->height; ++i, ++inputPos)
  {
    for (int j = 0; j < mask->width; ++j)
    {
      char current = '#';
      if (j < static_cast<int>(inputPos->size()))
      {
        current = (*inputPos)[j];
      }
      int bit = 1;
      // TODO: Enforce input restrictions.
      switch (current)
      {
      case '#':
        bit = 0;
        break;
      case '!':
        bit = 0;
        // Deliberate fall-through.
      case '@':
        // Bit is already set properly.
        mask->south = i;
        mask->west = j;
        mask->north = mask->height - 1 - mask->south;
        mask->east = mask->width - 1 - mask->west;
        break;
      case '.':
      default:
        // bit is already 1
        break;
      }
      if (bit == 1)
      {
        *intPos |= 0x1 << bitPos;
      }
      else
      {
        *intPos &= ~(0x1 << bitPos);
      }
      ++bitPos;
      if (bitPos == BITS_PER_INT)
      {
        bitPos = 0;
        ++intPos;
      }
    }
  }
  return result;
}

void cleanupPermissiveMask(permissiveMaskT * mask)
{
  delete [] mask->mask;
  mask->mask = NULL;
}

permissiveErrorT savePermissiveMask(permissiveMaskT * mask,
                                    char const * fileName)
{
  permissiveErrorT result = PERMISSIVE_NO_FAILURE;
  std::ofstream file(fileName, std::ios::out | std::ios::trunc);
  if (!file)
  {
    result = PERMISSIVE_FAILED_TO_OPEN_FILE;
  }
  else
  {
    for (int y = - mask->south; y <= mask->north && file; ++y)
    {
      for (int x = - mask->west; x <= mask->east && file; ++x)
      {
        if (x == 0 && y == 0)
        {
          if (doesPermissiveVisit(mask, x, y))
          {
            file << '@';
          }
          else
          {
            file << '!';
          }
        }
        else
        {
          if (doesPermissiveVisit(mask, x, y))
          {
            file << '.';
          }
          else
          {
            file << '#';
          }
        }
      }
      file << '\n';
    }
    if (!file)
    {
      result = PERMISSIVE_SAVE_WRITE_FAILED;
    }
  }
  return result;
}

void setPermissiveVisit(permissiveMaskT * mask, int x, int y)
{
  if (mask->mask != NULL)
  {
    int index = GET_INT(x + mask->west, y + mask->south);
    int shift = GET_BIT(x + mask->west, y + mask->south);
    mask->mask[index] |= 0x1 << shift;
  }
}

void clearPermissiveVisit(permissiveMaskT * mask, int x, int y)
{
  if (mask->mask != NULL)
  {
    int index = GET_INT(x + mask->west, y + mask->south);
    int shift = GET_BIT(x + mask->west, y + mask->south);
    mask->mask[index] &= ~(0x1 << shift);
  }
}

int doesPermissiveVisit(permissiveMaskT * mask, int x, int y)
{
  if (mask->mask == NULL)
  {
    return 1;
  }
  else
  {
    int index = GET_INT(x + mask->west, y + mask->south);
    int shift = GET_BIT(x + mask->west, y + mask->south);
    return (mask->mask[index] >> shift) & 0x1;
  }
}


text:
package com.example.newbiechen.simpledependencedemo.model.net;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import okhttp3.Call;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by newbiechen on 17-4-3.
 */

public class NetWorkHelper {
    private static NetWorkHelper sInstance;
    private Retrofit mRetrofit;

    private NetWorkHelper(){
        mRetrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(URLManager.BASE_URL)
                .build();
    }

    public static synchronized NetWorkHelper getInstance(){
        if (sInstance == null){
            sInstance = new NetWorkHelper();
        }
        return sInstance;
    }

    public Retrofit getRetrofit(){
        return mRetrofit;
    }
}


text:
* This is a rotating menu, it is very convenient to use.
* Special thanks to the effect of the original author:czda1100.
![cmd-markdown-logo](http://ww3.sinaimg.cn/bmiddle/a47c92bdjw1es8d0dzmayg20a30ibwt7.gif)

# Communication
* If you found a bug, and can provide steps to reliably reproduce it, open an issue.
* If you have a feature request, open an issue.
* If you want to contribute, submit a pull request.

# Installation

* pod 'EFAnimationMenu', '~> 0.0.8'

# Usage
```javascript
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.viewController = ({
    EFAnimationViewController *viewController = [[EFAnimationViewController alloc] init];
    [self.view addSubview:viewController.view];
    [self addChildViewController:viewController];
    [viewController didMoveToParentViewController:self];
    viewController;
    });
}
```

# Feedback
* Have any problem in use, welcome back to me, you can communicate with me with the following contact
* QQMail: 327592992@qq.com

# About author

* With their own strength and speed, go where you want to go!