text:
use crate::{BeaconForkChoiceStore, BeaconSnapshot};
use fork_choice::{CountUnrealized, ForkChoice, PayloadVerificationStatus};
use itertools::process_results;
use proto_array::CountUnrealizedFull;
use slog::{info, warn, Logger};
use state_processing::state_advance::complete_state_advance;
use state_processing::{
    per_block_processing, per_block_processing::BlockSignatureStrategy, ConsensusContext,
    VerifyBlockRoot,
};
use std::sync::Arc;
use std::time::Duration;
use store::{iter::ParentRootBlockIterator, HotColdDB, ItemStore};
use types::{BeaconState, ChainSpec, EthSpec, ForkName, Hash256, SignedBeaconBlock, Slot};

const CORRUPT_DB_MESSAGE: &str = "The database could be corrupt. Check its file permissions or \
                                  consider deleting it by running with the --purge-db flag.";

/// Revert the head to the last block before the most recent hard fork.
///
/// This function is destructive and should only be used if there is no viable alternative. It will
/// cause the reverted blocks and states to be completely forgotten, lying dormant in the database
/// forever.
///
/// Return the `(head_block_root, head_block)` that should be used post-reversion.
pub fn revert_to_fork_boundary<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>>(
    current_slot: Slot,
    head_block_root: Hash256,
    store: Arc<HotColdDB<E, Hot, Cold>>,
    spec: &ChainSpec,
    log: &Logger,
) -> Result<(Hash256, SignedBeaconBlock<E>), String> {
    let current_fork = spec.fork_name_at_slot::<E>(current_slot);
    let fork_epoch = spec
        .fork_epoch(current_fork)
        .ok_or_else(|| format!("Current fork '{}' never activates", current_fork))?;

    if current_fork == ForkName::Base {
        return Err(format!(
            "Cannot revert to before phase0 hard fork. {}",
            CORRUPT_DB_MESSAGE
        ));
    }

    warn!(
        log,
        "Reverting invalid head block";
        "target_fork" => %current_fork,
        "fork_epoch" => fork_epoch,
    );
    let block_iter = ParentRootBlockIterator::fork_tolerant(&store, head_block_root);

    let (block_root, blinded_block) = process_results(block_iter, |mut iter| {
        iter.find_map(|(block_root, block)| {
            if block.slot() < fork_epoch.start_slot(E::slots_per_epoch()) {
                Some((block_root, block))
            } else {
                info!(
                    log,
                    "Reverting block";
                    "block_root" => ?block_root,
                    "slot" => block.slot(),
                );
                None
            }
        })
    })
    .map_err(|e| {
        format!(
            "Error fetching blocks to revert: {:?}. {}",
            e, CORRUPT_DB_MESSAGE
        )
    })?
    .ok_or_else(|| format!("No pre-fork blocks found. {}", CORRUPT_DB_MESSAGE))?;

    let block = store
        .make_full_block(&block_root, blinded_block)
        .map_err(|e| format!("Unable to add payload to new head block: {:?}", e))?;

    Ok((block_root, block))
}

/// Reset fork choice to the finalized checkpoint of the supplied head state.
///
/// The supplied `head_block_root` should correspond to the most recently applied block on
/// `head_state`.
///
/// This function avoids quirks of fork choice initialization by replaying all of the blocks from
/// the checkpoint to the head.
///
/// See this issue for details: https://github.com/ethereum/consensus-specs/issues/2566
///
/// It will fail if the finalized state or any of the blocks to replay are unavailable.
///
/// WARNING: this function is destructive and causes fork choice to permanently forget all
/// chains other than the chain leading to `head_block_root`. It should only be used in extreme
/// circumstances when there is no better alternative.
pub fn reset_fork_choice_to_finalization<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>>(
    head_block_root: Hash256,
    head_state: &BeaconState<E>,
    store: Arc<HotColdDB<E, Hot, Cold>>,
    current_slot: Option<Slot>,
    spec: &ChainSpec,
    count_unrealized_config: CountUnrealized,
    count_unrealized_full_config: CountUnrealizedFull,
) -> Result<ForkChoice<BeaconForkChoiceStore<E, Hot, Cold>, E>, String> {
    // Fetch finalized block.
    let finalized_checkpoint = head_state.finalized_checkpoint();
    let finalized_block_root = finalized_checkpoint.root;
    let finalized_block = store
        .get_full_block(&finalized_block_root)
        .map_err(|e| format!("Error loading finalized block: {:?}", e))?
        .ok_or_else(|| {
            format!(
                "Finalized block missing for revert: {:?}",
                finalized_block_root
            )
        })?;

    // Advance finalized state to finalized epoch (to handle skipped slots).
    let finalized_state_root = finalized_block.state_root();
    let mut finalized_state = store
        .get_state(&finalized_state_root, Some(finalized_block.slot()))
        .map_err(|e| format!("Error loading finalized state: {:?}", e))?
        .ok_or_else(|| {
            format!(
                "Finalized block state missing from database: {:?}",
                finalized_state_root
            )
        })?;
    let finalized_slot = finalized_checkpoint.epoch.start_slot(E::slots_per_epoch());
    complete_state_advance(
        &mut finalized_state,
        Some(finalized_state_root),
        finalized_slot,
        spec,
    )
    .map_err(|e| {
        format!(
            "Error advancing finalized state to finalized epoch: {:?}",
            e
        )
    })?;
    let finalized_snapshot = BeaconSnapshot {
        beacon_block_root: finalized_block_root,
        beacon_block: Arc::new(finalized_block),
        beacon_state: finalized_state,
    };

    let fc_store = BeaconForkChoiceStore::get_forkchoice_store(store.clone(), &finalized_snapshot);

    let mut fork_choice = ForkChoice::from_anchor(
        fc_store,
        finalized_block_root,
        &finalized_snapshot.beacon_block,
        &finalized_snapshot.beacon_state,
        current_slot,
        count_unrealized_full_config,
        spec,
    )
    .map_err(|e| format!("Unable to reset fork choice for revert: {:?}", e))?;

    // Replay blocks from finalized checkpoint back to head.
    // We do not replay attestations presently, relying on the absence of other blocks
    // to guarantee `head_block_root` as the head.
    let blocks = store
        .load_blocks_to_replay(finalized_slot + 1, head_state.slot(), head_block_root)
        .map_err(|e| format!("Error loading blocks to replay for fork choice: {:?}", e))?;

    let mut state = finalized_snapshot.beacon_state;
    let blocks_len = blocks.len();
    for (i, block) in blocks.into_iter().enumerate() {
        complete_state_advance(&mut state, None, block.slot(), spec)
            .map_err(|e| format!("State advance failed: {:?}", e))?;

        let mut ctxt = ConsensusContext::new(block.slot())
            .set_proposer_index(block.message().proposer_index());
        per_block_processing(
            &mut state,
            &block,
            BlockSignatureStrategy::NoVerification,
            VerifyBlockRoot::True,
            &mut ctxt,
            spec,
        )
        .map_err(|e| format!("Error replaying block: {:?}", e))?;

        // Setting this to unverified is the safest solution, since we don't have a way to
        // retro-actively determine if they were valid or not.
        //
        // This scenario is so rare that it seems OK to double-verify some blocks.
        let payload_verification_status = PayloadVerificationStatus::Optimistic;

        // Because we are replaying a single chain of blocks, we only need to calculate unrealized
        // justification for the last block in the chain.
        let is_last_block = i + 1 == blocks_len;
        let count_unrealized = if is_last_block {
            count_unrealized_config
        } else {
            CountUnrealized::False
        };

        fork_choice
            .on_block(
                block.slot(),
                block.message(),
                block.canonical_root(),
                // Reward proposer boost. We are reinforcing the canonical chain.
                Duration::from_secs(0),
                &state,
                payload_verification_status,
                spec,
                count_unrealized,
            )
            .map_err(|e| format!("Error applying replayed block to fork choice: {:?}", e))?;
    }

    Ok(fork_choice)
}


text:
<style>
  body {
    overflow: auto;
  }
</style>

<script>
  window.ANET_DATA = {
    projectVersion: "${projectVersion}",
    currentUser: {
      uuid: "${currentUser.uuid}",
      name: "${currentUser.name!}",
      role: "<#if (currentUser.position)?? >${currentUser.position.type!'ADVISOR'}<#else>ADVISOR</#if>",
      rank: "${currentUser.rank!}",
    },
    adminSettings: [
      { key: "SECURITY_BANNER_TEXT", value: "${securityBannerText!\"Set SECURITY_BANNER_TEXT adminSetting\"}" },
      { key: "SECURITY_BANNER_COLOR", value: "${securityBannerColor!\"green\"}" }
    ],
    dictionary: "${serializedDictionary?no_esc}"
  }
</script>

redpajama_set_name: RedPajamaGithub


text:
package de.adito.propertly.reactive.impl.builder;

import de.adito.propertly.core.spi.*;
import de.adito.propertly.reactive.api.builder.*;
import io.reactivex.rxjava3.core.Observable;
import org.jetbrains.annotations.NotNull;

import java.util.Optional;

/**
 * @author w.glanzer, 09.11.2018
 */
public class BuilderPropertyObservable<S extends IPropertyPitProvider, V> extends AbstractBuilderObservable<IProperty<S, V>>
    implements IBuilderPropertyObservable<S, V>
{

  private final boolean completeWhenInvalid;

  public BuilderPropertyObservable(@NotNull Observable<Optional<IProperty<S, V>>> pProperty, boolean pCompleteWhenInvalid)
  {
    super(pProperty);
    completeWhenInvalid = pCompleteWhenInvalid;
  }

  @NotNull
  @Override
  public <P2 extends IPropertyPitProvider, S2 extends IPropertyPitProvider<P2, S2, T2>, T2>
  IBuilderPropertyPitObservable<P2, S2, T2> asPropertyPit()
  {
    return (IBuilderPropertyPitObservable<P2, S2, T2>) new BuilderPropertyPitObservable(emitValue(), completeWhenInvalid);
  }

  @NotNull
  @Override
  public IBuilderPropertyObservable<IPropertyPitProvider, ?> emitHierarchyValue()
  {
    Observable hierarchyPropObs = getInternalObservable()
        .map(pOpt -> pOpt.map(pProp -> pProp.getHierarchy().getProperty()))
        .distinctUntilChanged();
    return new BuilderPropertyObservable<>(hierarchyPropObs, completeWhenInvalid);
  }

  @NotNull
  @Override
  public Observable<Optional<V>> emitValue()
  {
    return getInternalObservable()
        .map(pOpt -> pOpt
            .filter(IProperty::canRead)
            .map(IProperty::getValue));
  }

}


text:
require 'spec_helper'

RSpec.describe HelloRails::Runner do
  describe '#run' do
    it 'sends create message to app if to cli_handler successful' do
      cli_handler = double('HelloRails::CliHander', get_args: true, app_args: {})
      app         = double('HelloRails::App', create!: true)
      runner      = HelloRails::Runner.new(cli_handler: cli_handler, app: app)

      runner.run
      expect(app).to have_received(:create!).once
    end

    it 'does not send create message to app if cli_handler fails' do
      cli_handler = double('HelloRails::CliHander', get_args: false, app_args: {})
      app         = double('HelloRails::App', create!: true)
      runner      = HelloRails::Runner.new(cli_handler: cli_handler, app: app)

      runner.run
      expect(app).to_not have_received(:create!)
    end
  end
end


text:
package com.mossle.user.support;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mossle.core.mapper.BeanMapper;

import com.mossle.user.persistence.domain.UserAttr;
import com.mossle.user.persistence.domain.UserBase;
import com.mossle.user.persistence.domain.UserSchema;

public class UserBaseWrapper extends UserBase {
    private transient BeanMapper beanMapper = new BeanMapper();
    private transient List<UserAttrWrapper> userAttrWrappers = new ArrayList<UserAttrWrapper>();

    public UserBaseWrapper() {
    }

    public UserBaseWrapper(UserBase userBase) {
        beanMapper.copy(userBase, this);

        if (userBase.getUserRepo() == null) {
            return;
        }

        for (UserSchema userSchema : userBase.getUserRepo().getUserSchemas()) {
            boolean notFound = true;

            for (UserAttr userAttr : userBase.getUserAttrs()) {
                if (userAttr.getUserSchema().getId().equals(userSchema.getId())) {
                    notFound = false;
                    userAttrWrappers.add(new UserAttrWrapper(userAttr));

                    break;
                }
            }

            if (notFound) {
                userAttrWrappers.add(new UserAttrWrapper(userSchema));
            }
        }
    }

    public List<UserAttrWrapper> getUserAttrWrappers() {
        return userAttrWrappers;
    }

    // ~ ======================================================================
    public Map<String, Object> toMap() {
        Map<String, Object> map = new HashMap<String, Object>();
        this.copyUserBase(map, this);

        for (UserAttrWrapper userAttrWrapper : userAttrWrappers) {
            this.copyUserAttr(map, userAttrWrapper);
        }

        return map;
    }

    public void copyUserBase(Map<String, Object> map, UserBase userBase) {
        map.put("id", userBase.getId());
        map.put("username", userBase.getUsername());
        map.put("displayName", userBase.getDisplayName());
        map.put("email", userBase.getEmail());
        map.put("mobile", userBase.getMobile());
        map.put("ref", userBase.getRef());
        map.put("status", userBase.getStatus());
    }

    public void copyUserAttr(Map<String, Object> map,
            UserAttrWrapper userAttrWrapper) {
        map.put(userAttrWrapper.getCode(), userAttrWrapper.getValue());
    }
}


text:
package com.turkcell.gelecegiyazanlar.fragments;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.turkcell.gelecegiyazanlar.R;
import com.turkcell.gelecegiyazanlar.activities.AramaActivity;
import com.turkcell.gelecegiyazanlar.adapterlisteners.IcerikAramaAdapter;
import com.turkcell.gelecegiyazanlar.configurations.AppController;
import com.turkcell.gelecegiyazanlar.configurations.GYConfiguration;
import com.turkcell.gelecegiyazanlar.models.Icerik;
import com.turkcell.gelecegiyazanlar.utilities.YuklenmeEkran;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by asus on 30.9.2015.
 */
public class IcerikAramaFragment extends Fragment implements View.OnClickListener,AramaActivity.IArama {

    //List<Kisi> icerikList = new ArrayList<Kisi>();
    List<Icerik> icerikList = new ArrayList<Icerik>();
    EditText search;

    ImageView btnAra;
    ListView listView;
    TextView tvSonuc;

    //Volley deðiþkenleri
    JsonArrayRequest jsonArrayRequest;
    String url;
    int sayfaNumarasi=1;

    YuklenmeEkran ekran ;

    Toolbar toolbar;

    public IcerikAramaFragment() {

        Log.d("arama:","Icerik");
    }

    public static IcerikAramaFragment newInstance() {
        return new IcerikAramaFragment();
    }

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

        toolbar=(Toolbar)getActivity().findViewById(R.id.tool_bar_ara);
        View rootView= inflater.inflate(R.layout.fragment_arama, container, false);

        url = GYConfiguration.getDomain()+"contentsearch/retrieve?";

        search=(EditText)toolbar.findViewById(R.id.etSearch);

        listView = (ListView) rootView.findViewById(R.id.lvliste);
        tvSonuc = (TextView) rootView.findViewById(R.id.tvSonuc);
        btnAra = (ImageView) toolbar.findViewById(R.id.btnAra);

        ekran=new YuklenmeEkran(getActivity());

//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if (icerikList.get(position) != null) {
//                    Kisi kisi = new Kisi();
//                    kisi.setKullaniciAdi(icerikList.get(position).getKullaniciID());
//                    Intent i=new Intent(getActivity(), ProfilActivity.class);
//                    i.putExtra(Kisi.PROFIL_ID,kisi.getKullaniciAdi());
//                    startActivity(i);
//                }
//            }
//        });

        return rootView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnAra:
                String URL = (url +"keyword="+search.getText()+"&page="+sayfaNumarasi+"&nodeType=article").trim();
                URL = URL.replace(" ", "%20");
                Listele(URL);
                break;

        }

    }

    public void Listele(String url) {
        ekran.surecBasla();
        Log.d("icerikUrl:",url);

        jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                ekran.surecDurdur();

                icerikList.clear();

                for (int i = 0; i < response.length(); i++) {

                    final Icerik tempIcerik = new Icerik();
                    try {
                        tempIcerik.setNodeID(response.getJSONObject(i).getString("nodeID"));
                        tempIcerik.setTitle(response.getJSONObject(i).getString("title"));
                        tempIcerik.setDate(response.getJSONObject(i).getString("date"));
                        tempIcerik.setNodetype(response.getJSONObject(i).getString("nodetype"));
                        tempIcerik.setExcerpt(response.getJSONObject(i).getString("excerpt"));
                        Log.d("TAG", "onResponse: " + tempIcerik.getNodeID());

                        icerikList.add(tempIcerik);

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.d("TAG", e.toString());
                    }

                }

                IcerikAramaAdapter adapter = new IcerikAramaAdapter(getActivity(), icerikList);
                listView.setAdapter(adapter);
                adapter.notifyDataSetChanged();

                Log.d("parse islemi bitti:", "girildi");
                if (icerikList.isEmpty())
                    tvSonuc.setVisibility(View.VISIBLE);
                else tvSonuc.setVisibility(View.GONE);

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        AppController.getInstance().addToRequestQueue(jsonArrayRequest);

        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(search.getWindowToken(), 0);

    }

    @Override
    public void onPageActivated() {
        btnAra.setOnClickListener(this);
    }

    }


text:
describe TwemproxyExporter::Exporter do
  let(:stats_file) { File.open("spec/fixtures/files/stats.json") }
  let(:config) { { "proxies" => ["localhost"] } }
  let(:twemproxy_labels) { { twemproxy: "app-production-redis-twemproxy" } }
  let(:cluster_labels) { twemproxy_labels.merge({ cluster: "app_persistent" }) }

  before do
    expect(TCPSocket).to receive(:new).and_return(stats_file)
  end

  subject { TwemproxyExporter::Exporter.new(config) }

  context "proxies" do
    it "should count stats" do
      subject.proxies.each(&:count)

      # Twemproxy Metrics
      expect(subject.curr_connections.value   twemproxy_labels).to eq(380)
      expect(subject.total_connections.value  twemproxy_labels).to eq(109710)
      expect(subject.uptime.value             twemproxy_labels).to eq(1749519)

      # Cluster Metrics
      expect(subject.client_connections.value cluster_labels).to eq(315)
      expect(subject.client_eof.value         cluster_labels).to eq(109307)
      expect(subject.client_err.value         cluster_labels).to eq(23)
      expect(subject.forward_error.value      cluster_labels).to eq(0)
      expect(subject.fragments.value          cluster_labels).to eq(0)
      expect(subject.server_ejects.value      cluster_labels).to eq(0)

      # Server Metrics
      (0..63).each do |server_id|
        server_labels = cluster_labels.merge({ server: "app_persistent_#{server_id.to_s.rjust(2, "0")}" })

        if server_id == 0
          expect(subject.in_queue.value           server_labels).to eq(0)
          expect(subject.in_queue_bytes.value     server_labels).to eq(0)
          expect(subject.out_queue.value          server_labels).to eq(0)
          expect(subject.out_queue_bytes.value    server_labels).to eq(0)
          expect(subject.request_bytes.value      server_labels).to eq(673319623)
          expect(subject.requests.value           server_labels).to eq(4611711)
          expect(subject.response_bytes.value     server_labels).to eq(35218731)
          expect(subject.responses.value          server_labels).to eq(4611711)
          expect(subject.server_connections.value server_labels).to eq(1)
          expect(subject.server_ejected_at.value  server_labels).to eq(0)
          expect(subject.server_eof.value         server_labels).to eq(0)
          expect(subject.server_err.value         server_labels).to eq(0)
          expect(subject.server_timedout.value    server_labels).to eq(0)
        else
          expect(subject.in_queue.value           server_labels).to be >= 0
          expect(subject.in_queue_bytes.value     server_labels).to be >= 0
          expect(subject.out_queue.value          server_labels).to be >= 0
          expect(subject.out_queue_bytes.value    server_labels).to be >= 0
          expect(subject.request_bytes.value      server_labels).to be >= 0
          expect(subject.requests.value           server_labels).to be >= 0
          expect(subject.response_bytes.value     server_labels).to be >= 0
          expect(subject.responses.value          server_labels).to be >= 0
          expect(subject.server_connections.value server_labels).to be >= 0
          expect(subject.server_ejected_at.value  server_labels).to be >= 0
          expect(subject.server_eof.value         server_labels).to be >= 0
          expect(subject.server_err.value         server_labels).to be >= 0
          expect(subject.server_timedout.value    server_labels).to be >= 0
        end
      end
    end
  end
end


text:
package org.openforis.idm.metamodel.xml.internal.marshal;

import static org.openforis.idm.metamodel.xml.IdmlConstants.DEPRECATED;
import static org.openforis.idm.metamodel.xml.IdmlConstants.SINCE;

import java.io.IOException;

import javax.xml.namespace.QName;

import org.openforis.idm.metamodel.Annotatable;
import org.openforis.idm.metamodel.VersionableSurveyObject;

/**
 *
 * @author G. Miceli
 *
 * @param <T>
 * @param <P>
 */
public abstract class VersionableSurveyObjectXS<T extends VersionableSurveyObject, P>
		extends XmlSerializerSupport<T, P> {

	protected VersionableSurveyObjectXS(String tag) {
		super(tag);
	}

	@Override
	protected void attributes(T o) throws IOException {
		attribute(SINCE, o.getSinceVersionName());
		attribute(DEPRECATED, o.getDeprecatedVersionName());
		if ( o instanceof Annotatable ) {
			Annotatable a= (Annotatable) o;
			for (QName qname : a.getAnnotationNames()) {
				String value = a.getAnnotation(qname);
				attribute(qname.getNamespaceURI(), qname.getLocalPart(), value);
			}
		}
	}
}


text:
<?php

namespace Crakter\BringApi\Clients;

use PHPUnit\Framework\TestCase;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Client;
use Crakter\BringApi\Exception\BringClientException;
use Crakter\BringApi\Exception\ApiEntityNotCorrectException;
use Crakter\BringApi\Entity\BookShipmentsEntity;

class BookShipmentTest extends TestCase
{
    private $class;
    private $json;

    public function setUp(): void
    {
        $this->class = (new Booking\BookShipment);
        $this->json = file_get_contents(dirname(dirname(__DIR__)).'/Data/BookShipmentResponse.json');
        $this->class->setResponse(new Response(200, ['X-Foo' => 'Bar'], $this->json));
    }

    public function testProcessClientUrlVariables(): void
    {
        $this->assertInstanceOf(ClientsInterface::class, $this->class->processClientUrlVariables());
    }

    public function testCheckErrorsException(): void
    {
        $this->expectException(BringClientException::class);
        $this->assertInstanceOf(ClientsInterface::class, $this->class->setResponse(new Response(200, ['X-Foo' => 'Bar'], 'test')));
        $this->class->checkErrors();
    }

    public function testCheckErrors(): void
    {
        $this->assertInstanceOf(ClientsInterface::class, $this->class->setResponse(new Response(200, ['X-Foo' => 'Bar'], '{"q":"testing"}')));
        $this->assertInstanceOf(ClientsInterface::class, $this->class->checkErrors());
    }

    public function testProcessEntityException(): void
    {
        $this->expectException(ApiEntityNotCorrectException::class);
        $this->assertInstanceOf(ClientsInterface::class, $this->class->processEntity());
    }

    public function testProcessEntity(): void
    {
        $this->assertInstanceOf(ClientsInterface::class, $this->class->setApiEntity(new BookShipmentsEntity()));
        $this->assertInstanceOf(ClientsInterface::class, $this->class->processEntity());
    }

    public function testSend(): void
    {
        $mock = new MockHandler([$this->class->getResponse()]);
        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler]);
        $this->assertInstanceOf(ClientsInterface::class, $this->class->setClient($client));
        $this->assertInstanceOf(ClientsInterface::class, $this->class->setApiEntity(new BookShipmentsEntity()));
        $this->assertInstanceOf(ClientsInterface::class, $this->class->send());
        $this->assertJsonStringEqualsJsonString($this->json, $this->class->toJson());
    }
}


text:
import {Feature, FeatureCollection, Point} from '@turf/helpers';

/**
 * http://turfjs.org/docs/#pointonsurface
 */
export default function pointOnSurface(
    features: Feature<any> | FeatureCollection<any>
): Feature<Point>;


text:
# Sports Thing
## A statistical tool

[![Tag](https://img.shields.io/github/tag/mpaarating/sports-thing.svg?style=flat)](https://github.com/mpaarating/sports-thing)

## Summary

Frontend consisting of:
- [Angular](https://angularjs.org/) Using paradox41's excellent [angular template](https://github.com/paradox41/app-template)
- [Bootstrap](http://getbootstrap.com/)
- [Gulp](http://gulpjs.com/)
- [Browserify](http://browserify.org/)
- [Karma](https://karma-runner.github.io/)
- [Mocha](http://mochajs.org/)
- [Chai](http://chaijs.com/)

Backend consisting of:
 - [Express](http://expressjs.com/)
 - [Mongodb](https://www.mongodb.org/)
 - [Conventional Changelog](https://github.com/ajoslin/conventional-changelog)

## Usage

Clone the repo or download the zip file. If you cloned, `rm -rf .git`

1. `npm install`

#### For client

1. `cd client/`
2. `gulp`

#### For API

1. `cd api/`
2. `node server.js`

## Build

1. `npm run build`

## Style

### Client JavaScript
- Each module should be totally self-contained. Any functionality shared across modules should be moved into `common/`.
- Modules can have their own directives, services, filters, etc. If multiple files are needed in order to maintain file size,
a folder should be created (`directives/`, `services/`, etc) and the broken up files should be placed into their respective folders
with less abstract naming conventions.
- JavaScript files should always be as close as possible - preferably on the same level - as their HTML partials.
- If a directive has a partial - which they tend to - a new folder should be created that is named accordingly (meaning not something generic)
and the HTML partial and the JavaScript file should be placed together in that folder.

### Sass
- `app.scss` is merely a table of contents. There should be no Sass in the file.
- Each module is responsible for exporting its submodules. In other words, `app.scss` should only import top level modules.
- Sass that needs to be shared among modules should be moved into `assets/stylesheets/`.

### Modules

A typical module will look something like this:

```javascript
import angular from 'angular';

import _ from 'lodash';

class ExampleCtrl {
    constructor(data) {
        this.exampleData = data;
    }

    someMethod() {
        return _.map(this.exampleData, function(data) {
            return (data * 2);
        });
    }

    get data() {
        return this.exampleData;
    }
}

ExampleCtrl.$inject = ['data'];

/*
    Allows us to import exampleModule like so:

    import exampleModule from './example';

    angular.module('foo', [
        exampleModule.name
    ])
*/
export default angular.module('example', [])

.controller('ExampleCtrl', ExampleCtrl)

.config(['$stateProvider', function($stateProvider) {
    $stateProvider.state('app.example', {
        controller: 'ExampleCtrl',
        controllerAs: 'Example',
        url: '/example',
        template: require('./_example.html'),
        resolve: {
            data: [function() {
                return [1, 2, 3, 4, 5, 6];
            }]
        }
    });
}]);
```

### Commit Conventions

Follow [conventional changelog](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md#commit)

### Documentation

Documentation via [JSDoc](http://usejsdoc.org/)

1. `npm run docs`
2. `gulp documentation:serve`


text:
using System;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Baseline;
using Marten.Internal;
using Marten.Internal.Storage;
using Marten.Linq.QueryHandlers;
using Weasel.Postgresql;
using Marten.Schema;
using Marten.Util;

namespace Marten.Storage.Metadata
{
    internal class EntityMetadataQueryHandler: IQueryHandler<DocumentMetadata>
    {
        private readonly object _id;
        private readonly IDocumentStorage _storage;
        private readonly MetadataColumn[] _columns;

        public EntityMetadataQueryHandler(object id, IDocumentStorage storage)
        {
            _id = id;
            _storage = storage;

            SourceType = storage.DocumentType;

            if (storage.Fields is DocumentMapping m)
            {
                _columns = m.Schema.Table.Columns.OfType<MetadataColumn>().ToArray();
            }
            else
            {
                throw new ArgumentOutOfRangeException(nameof(storage));
            }
        }

        public void ConfigureCommand(CommandBuilder sql, IMartenSession session)
        {
            sql.Append("select id, ");

            var fields = _columns.Select(x => x.Name).Join(", ");

            sql.Append(fields);

            sql.Append(" from ");
            sql.Append(_storage.TableName.QualifiedName);
            sql.Append(" where id = :id");

            sql.AddNamedParameter("id", _id);
        }

        public DocumentMetadata Handle(DbDataReader reader, IMartenSession session)
        {
            if (!reader.Read())
                return null;

            var id = reader.GetFieldValue<object>(0);
            var metadata = new DocumentMetadata(id);

            for (var i = 0; i < _columns.Length; i++)
            {
                _columns[i].Apply(session, metadata, i + 1, reader);
            }

            return metadata;
        }

        public async Task<DocumentMetadata> HandleAsync(DbDataReader reader, IMartenSession session,
            CancellationToken token)
        {
            var hasAny = await reader.ReadAsync(token).ConfigureAwait(false);
            if (!hasAny)
                return null;

            var id = await reader.GetFieldValueAsync<object>(0, token).ConfigureAwait(false);
            var metadata = new DocumentMetadata(id);

            for (var i = 0; i < _columns.Length; i++)
            {
                await _columns[i].ApplyAsync(session, metadata, i + 1, reader, token).ConfigureAwait(false);
            }

            return metadata;
        }

        public Task<int> StreamJson(Stream stream, DbDataReader reader, CancellationToken token)
        {
            throw new NotSupportedException();
        }

        public Type SourceType { get; }
    }
}


text:
package com.microsoft.azure.storage;

/**
 * Represents the analytics properties for the service.
 */
public final class ServiceProperties {

    /**
     * The service logging properties. This may not be null.
     */
    private LoggingProperties logging;

    /**
     * The service hour metrics properties.
     */
    private MetricsProperties hourMetrics;

    /**
     * The service minute metrics properties.
     */
    private MetricsProperties minuteMetrics;

    /**
     * The Cross Origin Resource Sharing (CORS) properties.
     */
    private CorsProperties cors;

    /**
     * The default service version for the blob service, or null if no default is specified. This must be null for queue
     * and table service properties.
     */
    private String defaultServiceVersion;

    /**
     * Initializes a new instances of the ServiceProperties class.
     */
    public ServiceProperties() {
        this.setLogging(new LoggingProperties());
        this.setHourMetrics(new MetricsProperties());
        this.setMinuteMetrics(new MetricsProperties());
        this.setCors(new CorsProperties());
    }

    /**
     * Gets the logging properties.
     *
     * @return A {@link LoggingProperties} object which represents the logging properties.
     */
    public LoggingProperties getLogging() {
        return this.logging;
    }

    /**
     * Sets the logging properties.
     *
     * @param logging
     *        A {@link LoggingProperties} object which represents the logging properties.
     */
    public void setLogging(final LoggingProperties logging) {
        this.logging = logging;
    }

    /**
     * Gets the hour metrics properties.
     *
     * @return A {@link MetricsProperties} object which represents the hour metrics properties.
     */
    public MetricsProperties getHourMetrics() {
        return this.hourMetrics;
    }

    /**
     * Sets the hour metrics properties.
     *
     * @param metrics
     *        A {@link MetricsProperties} object which represents the hour metrics properties.
     */
    public void setHourMetrics(final MetricsProperties metrics) {
        this.hourMetrics = metrics;
    }

    /**
     * Gets the minute metrics properties.
     *
     * @return A {@link MetricsProperties} object which represents the minute metrics properties.
     */
    public MetricsProperties getMinuteMetrics() {
        return this.minuteMetrics;
    }

    /**
     * Sets the minute metrics properties.
     *
     * @param metrics
     *        A {@link MetricsProperties} object which represents the minute metrics properties.
     */
    public void setMinuteMetrics(final MetricsProperties metrics) {
        this.minuteMetrics = metrics;
    }

    /**
     * Gets the Cross-Origin Resource Sharing (CORS) properties.
     *
     * @return A {@link CorsProperties} object which represents the CORS properties.
     */
    public CorsProperties getCors() {
        return this.cors;
    }

    /**
     * Sets the Cross-Origin Resource Sharing (CORS) properties.
     *
     * @param cors
     *        A {@link CorsProperties} object which represents the CORS properties.
     */
    public void setCors(final CorsProperties cors) {
        this.cors = cors;
    }

    /**
     * Gets default service version.
     *
     * @return A String which represents the default service version.
     */
    public String getDefaultServiceVersion() {
        return this.defaultServiceVersion;
    }

    /**
     * Sets default service version.
     *
     * @param defaultServiceVersion
     *        A String which represents the default service version.
     */
    public void setDefaultServiceVersion(final String defaultServiceVersion) {
        this.defaultServiceVersion = defaultServiceVersion;
    }
}


text:
#include "tensorflow/core/kernels/data/concatenate_dataset_op.h"

#include <string>
#include <utility>

#include "tensorflow/core/data/name_utils.h"
#include "tensorflow/core/data/split_utils.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"

namespace tensorflow {
namespace data {

// See documentation in ../../ops/dataset_ops.cc for a high-level
// description of the following op.

/* static */ constexpr const char* const ConcatenateDatasetOp::kDatasetType;
/* static */ constexpr const char* const ConcatenateDatasetOp::kInputDataset;
/* static */ constexpr const char* const ConcatenateDatasetOp::kAnotherDataset;
/* static */ constexpr const char* const ConcatenateDatasetOp::kOutputTypes;
/* static */ constexpr const char* const ConcatenateDatasetOp::kOutputShapes;

constexpr char kIndex[] = "i";
constexpr char kInputImplUninitialized[] = "input_impl_uninitialized";

class ConcatenateDatasetOp::Dataset : public DatasetBase {
 public:
  explicit Dataset(OpKernelContext* ctx, const DatasetBase* input,
                   const DatasetBase* to_concatenate)
      : DatasetBase(DatasetContext(ctx)),
        input_(input),
        to_concatenate_(to_concatenate),
        input_cardinality_(input->Cardinality()),
        to_concatenate_cardinality_(to_concatenate_->Cardinality()) {
    input_->Ref();
    to_concatenate_->Ref();

    auto os_input = input->output_shapes();
    auto os_concatenate = to_concatenate->output_shapes();
    for (int i = 0; i < os_input.size(); i++) {
      output_shapes_.push_back(
          MostSpecificCompatibleShape(os_input[i], os_concatenate[i]));
    }
  }
  ~Dataset() override {
    input_->Unref();
    to_concatenate_->Unref();
  }

  std::unique_ptr<IteratorBase> MakeIteratorInternal(
      const string& prefix) const override {
    return std::make_unique<Iterator>(Iterator::Params{
        this, name_utils::IteratorPrefix(kDatasetType, prefix)});
  }

  Status MakeSplitProviders(std::vector<std::unique_ptr<SplitProvider>>*
                                split_providers) const override {
    TF_ASSIGN_OR_RETURN(*split_providers, GetSplitProviders(this));
    return OkStatus();
  }

  const DataTypeVector& output_dtypes() const override {
    return input_->output_dtypes();
  }

  const std::vector<PartialTensorShape>& output_shapes() const override {
    return output_shapes_;
  }

  string DebugString() const override {
    return name_utils::DatasetDebugString(kDatasetType);
  }

  int64_t CardinalityInternal() const override {
    if (input_cardinality_ == kInfiniteCardinality ||
        to_concatenate_cardinality_ == kInfiniteCardinality) {
      return kInfiniteCardinality;
    }
    if (input_cardinality_ == kUnknownCardinality ||
        to_concatenate_cardinality_ == kUnknownCardinality) {
      return kUnknownCardinality;
    }
    return input_cardinality_ + to_concatenate_cardinality_;
  }

  int64_t CardinalityInternal(CardinalityOptions options) const override {
    int64_t input_cardinality = input_->Cardinality(options);
    int64_t to_concatenate_cardinality = to_concatenate_->Cardinality(options);

    if (input_cardinality == kInfiniteCardinality ||
        to_concatenate_cardinality == kInfiniteCardinality) {
      return kInfiniteCardinality;
    }
    if (input_cardinality == kUnknownCardinality ||
        to_concatenate_cardinality == kUnknownCardinality) {
      return kUnknownCardinality;
    }
    return input_cardinality + to_concatenate_cardinality;
  }

  Status InputDatasets(std::vector<const DatasetBase*>* inputs) const override {
    inputs->push_back(input_);
    inputs->push_back(to_concatenate_);
    return OkStatus();
  }

  Status CheckExternalState() const override {
    TF_RETURN_IF_ERROR(input_->CheckExternalState());
    return to_concatenate_->CheckExternalState();
  }

  Status Get(OpKernelContext* ctx, int64 index,
             std::vector<Tensor>* out_tensors) const override {
    TF_RETURN_IF_ERROR(CheckRandomAccessCompatible(index));
    if (index < input_cardinality_) {
      TF_RETURN_IF_ERROR(input_->Get(ctx, index, out_tensors));
    } else {
      TF_RETURN_IF_ERROR(
          to_concatenate_->Get(ctx, index - input_cardinality_, out_tensors));
    }
    return OkStatus();
  }

 protected:
  Status AsGraphDefInternal(SerializationContext* ctx,
                            DatasetGraphDefBuilder* b,
                            Node** output) const override {
    Node* input_graph = nullptr;
    TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph));
    Node* to_concatenate_graph = nullptr;
    TF_RETURN_IF_ERROR(
        b->AddInputDataset(ctx, to_concatenate_, &to_concatenate_graph));
    TF_RETURN_IF_ERROR(
        b->AddDataset(this, {input_graph, to_concatenate_graph}, output));
    return OkStatus();
  }

 private:
  class Iterator : public DatasetIterator<Dataset> {
   public:
    explicit Iterator(const Params& params)
        : DatasetIterator<Dataset>(params), i_(0) {}

    Status Initialize(IteratorContext* ctx) override {
      TF_ASSIGN_OR_RETURN(input_contexts_,
                          CreateInputIteratorContexts(ctx, dataset()));
      return dataset()->input_->MakeIterator(&input_contexts_[0], this,
                                             strings::StrCat(prefix(), "[0]"),
                                             &input_impl_);
    }

    Status GetNextInternal(IteratorContext* ctx,
                           std::vector<Tensor>* out_tensors,
                           bool* end_of_sequence) override {
      mutex_lock l(mu_);
      if (!input_impl_) {
        *end_of_sequence = true;
        return OkStatus();
      }
      while (i_ < 2) {
        TF_RETURN_IF_ERROR(input_impl_->GetNext(&input_contexts_[i_],
                                                out_tensors, end_of_sequence));
        if (!*end_of_sequence) {
          return OkStatus();
        }
        if (++i_ < 2) {
          TF_RETURN_IF_ERROR(dataset()->to_concatenate_->MakeIterator(
              &input_contexts_[i_], this, strings::StrCat(prefix(), "[1]"),
              &input_impl_));
        }
      }
      *end_of_sequence = true;
      input_impl_.reset();
      return OkStatus();
    }

   protected:
    std::shared_ptr<model::Node> CreateNode(
        IteratorContext* ctx, model::Node::Args args) const override {
      return model::MakeKnownRatioNode(std::move(args),
                                       /*ratio=*/1);
    }

    Status SaveInternal(SerializationContext* ctx,
                        IteratorStateWriter* writer) override {
      mutex_lock l(mu_);
      TF_RETURN_IF_ERROR(writer->WriteScalar(full_name(kIndex), i_));
      if (input_impl_) {
        TF_RETURN_IF_ERROR(SaveInput(ctx, writer, input_impl_));
      } else {
        TF_RETURN_IF_ERROR(
            writer->WriteScalar(full_name(kInputImplUninitialized), ""));
      }
      return OkStatus();
    }

    Status RestoreInternal(IteratorContext* ctx,
                           IteratorStateReader* reader) override {
      mutex_lock l(mu_);
      TF_RETURN_IF_ERROR(reader->ReadScalar(full_name(kIndex), &i_));
      if (reader->Contains(full_name(kInputImplUninitialized))) {
        input_impl_.reset();
        return OkStatus();
      }
      if (!TF_PREDICT_TRUE(i_ >= 0 && i_ <= 2))
        return errors::InvalidArgument("i_ must be in range [0, 2].");
      if (i_ == 1) {
        TF_RETURN_IF_ERROR(dataset()->to_concatenate_->MakeIterator(
            ctx, this, strings::StrCat(prefix(), "[1]"), &input_impl_));
      } else if (i_ == 2) {
        input_impl_.reset();
      }
      if (input_impl_) {
        TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
      }
      return OkStatus();
    }

   private:
    mutex mu_;
    int64_t i_ TF_GUARDED_BY(mu_);
    std::unique_ptr<IteratorBase> input_impl_ TF_GUARDED_BY(mu_);
    std::vector<IteratorContext> input_contexts_;
  };

  static PartialTensorShape MostSpecificCompatibleShape(
      const PartialTensorShape& ts1, const PartialTensorShape& ts2) {
    if (ts1.dims() != ts2.dims() || ts1.unknown_rank() || ts2.unknown_rank())
      return PartialTensorShape();
    PartialTensorShape output_tensorshape({});
    auto dims1 = ts1.dim_sizes();
    auto dims2 = ts2.dim_sizes();
    for (int d = 0; d < ts1.dims(); d++) {
      if (dims1[d] == dims2[d])
        output_tensorshape.AddDim(dims1[d]);
      else
        output_tensorshape.AddDim(-1);
    }
    return output_tensorshape;
  }

  const DatasetBase* input_;
  const DatasetBase* to_concatenate_;
  const int64_t input_cardinality_;
  const int64_t to_concatenate_cardinality_;
  std::vector<PartialTensorShape> output_shapes_;
};

ConcatenateDatasetOp::ConcatenateDatasetOp(OpKernelConstruction* ctx)
    : BinaryDatasetOpKernel(ctx) {}

void ConcatenateDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
                                       DatasetBase* to_concatenate,
                                       DatasetBase** output) {
  OP_REQUIRES(ctx, input->output_dtypes() == to_concatenate->output_dtypes(),
              errors::InvalidArgument(
                  "input dataset and dataset to concatenate"
                  " have different output_types %s and %s",
                  (DataTypeVectorString(input->output_dtypes()),
                   DataTypeVectorString(to_concatenate->output_dtypes()))));
  *output = new Dataset(ctx, input, to_concatenate);
}

namespace {
REGISTER_KERNEL_BUILDER(Name("ConcatenateDataset").Device(DEVICE_CPU),
                        ConcatenateDatasetOp);
}  // namespace
}  // namespace data
}  // namespace tensorflow


text:
<?php

/**
 * Singleton class WP_Smush_Common.
 *
 * @since 2.8.0
 */
class WP_Smush_Common {
	/**
	 * Class instance variable.
	 *
	 * @since 2.8.0
	 * @var null|WP_Smush_Common
	 */
	private static $_instance = null;

	/**
	 * WP_Smush_Common constructor.
	 */
	private function __construct() {
		// AJAX Thumbnail Rebuild integration.
		add_filter( 'wp_smush_media_image', array( $this, 'skip_images' ), 10, 2 );
	}

	/**
	 * Get class instance.
	 *
	 * @since 2.8.0
	 *
	 * @return null|WP_Smush_Common
	 */
	public static function get_instance() {
		if ( null !== self::$_instance ) {
			return self::$_instance;
		}

		return new self();
	}

	/**
	 * AJAX Thumbnail Rebuild integration.
	 *
	 * If this is a thumbnail regeneration - only continue for selected thumbs
	 * (no need to regenerate everything else).
	 *
	 * @since 2.8.0
	 *
	 * @param string $smush_image  Image size.
	 * @param string $size_key     Thumbnail size.
	 *
	 * @return bool
	 */
	function skip_images( $smush_image, $size_key ) {
		if ( empty( $_POST['regen'] ) || ! is_array( $_POST['regen'] ) ) { // Input var ok.
			return $smush_image;
		}

		$smush_sizes = wp_unslash( $_POST['regen'] ); // Input var ok.

		if ( in_array( $size_key, $smush_sizes, true ) ) {
			return $smush_image;
		}

		// Do not regenrate other thumbnails for regenerate action.
		return false;
	}

}


text:
from flask import Flask, request, jsonify
from collections import deque
import sys

app = Flask(__name__)
queue = deque([])

@app.route('/init', methods=['GET', 'POST'])
def initialize():
	if request.method == 'POST':
		global queue

		data 	= request.get_json();
		#print( data)
		queue 	= deque(data['list'])

		resp = {
			"Message": "Queue intialized",
			"queue":   list(queue)
		}

		return jsonify(resp)
	else:
		return "Error!"

@app.route('/query', methods=['GET', 'POST'])
def query():
	global queue
	if request.method == 'GET' or request.method == 'POST':
		if len(queue) == 0:
			return jsonify({
				'data':    -1,
				'success': True
			})

		ele = queue.popleft()
		return jsonify({
			'data':    ele,
			'success': True
		})
	else:
		return 'Error'

@app.route('/enqueue', methods=['GET', 'POST'])
def enqueue():
	global queue
	if request.method == 'GET' or request.method == 'POST':
		data = request.get_json()
		ele = queue.append(data['data'])
		return jsonify({
			'data':    ele,
			'success': True
		})
	else:
		return 'Error'

@app.route('/enqueue_list', methods=['GET', 'POST'])
def enqueue_list():
	global queue
	if request.method == 'GET' or request.method == 'POST':
		if len(queue) == 0:
			return jsonify({
				'Error':   True,
				'Message': 'Queue empty'
			})
		else:
			data = request.get_json()
			ele  = queue.extend(data['data'])
			return jsonify({
				'data':    ele,
				'success': True
			})
	else:
		return 'Error'

@app.route('/size', methods=['GET', 'POST'])
def size():
	global queue
	if request.method == 'GET' or request.method == 'POST':
		return jsonify({
			'Size':   len(queue),
			'Message': 'Size of queue'
		})
	else:
		return 'Error'

@app.route('/clear', methods=['GET'])
def clearQueue():
	global queue
	if request.method == 'GET':
		queue = deque([])
		return jsonify({
			'Message': 'Queue successfully cleared'
		})
	else:
		return 'Error!'

@app.route('/check', methods=['GET'])
def checkQueue():
	global queue
	if request.method == 'GET':
		return jsonify({
			'Queue': list(queue)
		})
	else:
		return 'Error!'

if __name__ == "__main__":
	print ("Server Running")
	if len(sys.argv) == 2:
		server_port = int(sys.argv[1])
	else:
		server_port = 7979
	app.run(host= '0.0.0.0', port = server_port)


text:
import { Collection, Model } from 'backbone';
import LocalStorageSync from '../utils/backboneLocalStorage';
import ServerConfig from '../models/ServerConfig';

export default class extends Collection {
  localStorage() {
    return new LocalStorageSync('__serverConfigs');
  }

  sync(...args) {
    return LocalStorageSync.sync.apply(this, args);
  }

  model(attrs, options) {
    return new ServerConfig(attrs, options);
  }

  constructor(models, options) {
    super(models, options);
    this._activeId = localStorage.activeServerConfig;
    this.on('sync', () => this.bindActiveServerChangeHandler());
  }

  get activeServer() {
    return this.get(this._activeId);
  }

  set activeServer(md) {
    if (!md instanceof ServerConfig) {
      throw new Error('Please provide a model as a ServerConfig instance.');
    }

    if (this.models.indexOf(md) === -1) {
      throw new Error('The provided model is not in this collection and must be to' +
        ' set it as the active config.');
    }

    if (!md.id) {
      throw new Error('The provided model must have an id in order to be set as the' +
        ' active config.');
    }

    if (this._active !== md.id) {
      this._activeId = md.id;
      localStorage.activeServerConfig = md.id;
      this.trigger('activeServerChange', md);
      this.bindActiveServerChangeHandler();
    }
  }

  onActiveServerChange(md) {
    this.trigger('activeServerChange', md);
  }

  bindActiveServerChangeHandler() {
    if (this.activeServer) {
      this.activeServer.off('change', this.onActiveServerChange)
        .on('change', this.onActiveServerChange);
    }
  }

  set(models = [], options = {}) {
    const hasDefaultModel = !!this.findWhere({ default: true });

    // Todo: ensure this works via the myriad ways to set this collection

    // Not sure why if I create a model via Collection.Create, a single model
    // is being passed into this method, instead of an array. The documentation
    // does not reflect this.
    const modelsList = models instanceof Model ? [models] : models;

    if (hasDefaultModel &&
      modelsList.filter(md => md.get('default')).length) {
      throw new Error('The collection already has a default model and you' +
        ' are attempting to add another one. Only one default model is allowed.');
    }

    super.set(models, options);
  }
}


text:
package mcjty.rftools.blocks.screens.modulesclient;

import mcjty.lib.gui.widgets.Panel;
import mcjty.rftools.blocks.screens.ModuleGuiChanged;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;

public class ItemStackClientScreenModule implements ClientScreenModule {
    private RenderItem itemRender = new RenderItem();
    private int slot1 = -1;
    private int slot2 = -1;
    private int slot3 = -1;
    private int slot4 = -1;

    @Override
    public TransformMode getTransformMode() {
        return TransformMode.ITEM;
    }

    @Override
    public int getHeight() {
        return 22;
    }

    @Override
    public void render(FontRenderer fontRenderer, int currenty, Object[] screenData, float factor) {
        if (screenData == null) {
            return;
        }

        RenderHelper.enableGUIStandardItemLighting();
//        RenderHelper.enableStandardItemLighting();
        GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);

        GL11.glDepthMask(true);

        boolean lighting = GL11.glIsEnabled(GL11.GL_LIGHTING);
        if (!lighting) {
            GL11.glEnable(GL11.GL_LIGHTING);
        }
        boolean depthTest = GL11.glIsEnabled(GL11.GL_DEPTH_TEST);
        if (!depthTest) {
            GL11.glEnable(GL11.GL_DEPTH_TEST);
        }

        GL11.glPushMatrix();
        float f3 = 0.0075F;
        GL11.glTranslatef(-0.5F, 0.5F, 0.06F);
        GL11.glScalef(f3 * factor, -f3 * factor, 0.0001f);

//        short short1 = 240;
//        short short2 = 240;
//        OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, short1 / 1.0F, short2 / 1.0F);
        int x = 10;
        x = renderSlot(fontRenderer, currenty, screenData, slot1, 0, x);
        x = renderSlot(fontRenderer, currenty, screenData, slot2, 1, x);
        x = renderSlot(fontRenderer, currenty, screenData, slot3, 2, x);
        renderSlot(fontRenderer, currenty, screenData, slot4, 3, x);

        GL11.glPopMatrix();

        GL11.glPushMatrix();
        GL11.glTranslatef(-0.5F, 0.5F, 0.08F);
        GL11.glScalef(f3 * factor, -f3 * factor, 0.0001f);

        x = 10;
        x = renderSlotOverlay(fontRenderer, currenty, screenData, slot1, 0, x);
        x = renderSlotOverlay(fontRenderer, currenty, screenData, slot2, 1, x);
        x = renderSlotOverlay(fontRenderer, currenty, screenData, slot3, 2, x);
        renderSlotOverlay(fontRenderer, currenty, screenData, slot4, 3, x);
        GL11.glPopMatrix();

        if (!lighting) {
            GL11.glDisable(GL11.GL_LIGHTING);
        }
        if (!depthTest) {
            GL11.glDisable(GL11.GL_DEPTH_TEST);
        }

        GL11.glDepthMask(false);
        RenderHelper.enableStandardItemLighting();
    }

    @Override
    public void mouseClick(World world, int x, int y, boolean clicked) {

    }

    private int renderSlot(FontRenderer fontRenderer, int currenty, Object[] screenData, int slot, int index, int x) {
        if (slot != -1) {
            ItemStack itm = null;
            try {
                itm = (ItemStack) screenData[index];
            } catch (Exception e) {
                // Ignore this.
            }
            if (itm != null) {
                itemRender.renderItemAndEffectIntoGUI(fontRenderer, Minecraft.getMinecraft().getTextureManager(), itm, x, currenty);
            }
            x += 30;
        }
        return x;
    }

    private int renderSlotOverlay(FontRenderer fontRenderer, int currenty, Object[] screenData, int slot, int index, int x) {
        if (slot != -1) {
            ItemStack itm = null;
            try {
                itm = (ItemStack) screenData[index];
            } catch (Exception e) {
                // Ignore this.
            }
            if (itm != null) {
//                itemRender.renderItemOverlayIntoGUI(fontRenderer, Minecraft.getMinecraft().getTextureManager(), itm, x, currenty);
                renderItemOverlayIntoGUI(fontRenderer, itm, x, currenty);
            }
            x += 30;
        }
        return x;
    }

    private static void renderItemOverlayIntoGUI(FontRenderer fontRenderer, ItemStack itemStack, int x, int y) {
        if (itemStack != null) {
            int size = itemStack.stackSize;
            if (size > 1) {
                String s1;
                if (size < 10000) {
                    s1 = String.valueOf(size);
                } else if (size < 1000000) {
                    s1 = String.valueOf(size / 1000) + "k";
                } else if (size < 1000000000) {
                    s1 = String.valueOf(size / 1000000) + "m";
                } else {
                    s1 = String.valueOf(size / 1000000000) + "g";
                }
                GL11.glDisable(GL11.GL_LIGHTING);
//                GL11.glDisable(GL11.GL_DEPTH_TEST);
                GL11.glDisable(GL11.GL_BLEND);
                fontRenderer.drawString(s1, x + 19 - 2 - fontRenderer.getStringWidth(s1), y + 6 + 3, 16777215);
                GL11.glEnable(GL11.GL_LIGHTING);
//                GL11.glEnable(GL11.GL_DEPTH_TEST);
            }

            if (itemStack.getItem().showDurabilityBar(itemStack)) {
                double health = itemStack.getItem().getDurabilityForDisplay(itemStack);
                int j1 = (int)Math.round(13.0D - health * 13.0D);
                int k = (int)Math.round(255.0D - health * 255.0D);
                GL11.glDisable(GL11.GL_LIGHTING);
//                GL11.glDisable(GL11.GL_DEPTH_TEST);
                GL11.glDisable(GL11.GL_TEXTURE_2D);
                GL11.glDisable(GL11.GL_ALPHA_TEST);
                GL11.glDisable(GL11.GL_BLEND);
                Tessellator tessellator = Tessellator.instance;
                int l = 255 - k << 16 | k << 8;
                int i1 = (255 - k) / 4 << 16 | 16128;
                renderQuad(tessellator, x + 2, y + 13, 13, 2, 0, 0.0D);
                renderQuad(tessellator, x + 2, y + 13, 12, 1, i1, 0.02D);
                renderQuad(tessellator, x + 2, y + 13, j1, 1, l, 0.04D);
                //GL11.glEnable(GL11.GL_BLEND); // Forge: Disable Bled because it screws with a lot of things down the line.
                GL11.glEnable(GL11.GL_ALPHA_TEST);
                GL11.glEnable(GL11.GL_TEXTURE_2D);
                GL11.glEnable(GL11.GL_LIGHTING);
//                GL11.glEnable(GL11.GL_DEPTH_TEST);
                GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
            }
        }
    }

    private static void renderQuad(Tessellator tessellator, int x, int y, int width, int height, int color, double offset) {
        tessellator.startDrawingQuads();
        tessellator.setColorOpaque_I(color);
        tessellator.addVertex(x, y, offset);
        tessellator.addVertex(x, (y + height), offset);
        tessellator.addVertex((x + width), (y + height), offset);
        tessellator.addVertex((x + width), y, offset);
        tessellator.draw();
    }

    @Override
    public Panel createGui(Minecraft mc, Gui gui, final NBTTagCompound currentData, final ModuleGuiChanged moduleGuiChanged) {
        return new ScreenModuleGuiBuilder(mc, gui, currentData, moduleGuiChanged).
                label("Slot 1:").integer("slot1", "Slot index to show").nl().
                label("Slot 2:").integer("slot2", "Slot index to show").nl().
                label("Slot 3:").integer("slot3", "Slot index to show").nl().
                label("Slot 4:").integer("slot4", "Slot index to show").nl().
                build();
    }

    @Override
    public void setupFromNBT(NBTTagCompound tagCompound, int dim, int x, int y, int z) {
        if (tagCompound != null) {
            if (tagCompound.hasKey("slot1")) {
                slot1 = tagCompound.getInteger("slot1");
            }
            if (tagCompound.hasKey("slot2")) {
                slot2 = tagCompound.getInteger("slot2");
            }
            if (tagCompound.hasKey("slot3")) {
                slot3 = tagCompound.getInteger("slot3");
            }
            if (tagCompound.hasKey("slot4")) {
                slot4 = tagCompound.getInteger("slot4");
            }
        }
    }

    @Override
    public boolean needsServerData() {
        return true;
    }
}


text:
/*!
  \class SoGLTextureEnabledElement SoGLTextureEnabledElement.h Inventor/elements/SoGLTextureEnabledElement.h
  \brief The SoGLTextureEnabledElement class is an element which controls whether texturing is enabled or not.
  \ingroup elements

  \sa SoGLTexture3EnabledElement
*/

/*!
  \enum SoMultiTextureEnabledElement::Mode
*/

/*!
  \var SoGLTextureEnabledElement::Mode SoGLTextureEnabledElement::DISABLED
*/
/*!
  \var SoGLTextureEnabledElement::Mode SoGLTextureEnabledElement::RECTANGLE
*/
/*!
  \var SoGLTextureEnabledElement::Mode SoGLTextureEnabledElement::CUBEMAP
*/

#include <Inventor/elements/SoGLTextureEnabledElement.h>
#include <Inventor/elements/SoShapeStyleElement.h>

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif // HAVE_CONFIG_H

#include <Inventor/system/gl.h>
#include <cassert>

SO_ELEMENT_SOURCE(SoGLTextureEnabledElement);

// doc from parent
void
SoGLTextureEnabledElement::initClass(void)
{
  SO_ELEMENT_INIT_CLASS(SoGLTextureEnabledElement, inherited);
}

/*!
  The destructor.
*/
SoGLTextureEnabledElement::~SoGLTextureEnabledElement(void)
{
}

/*
  Sets the state of this element. Used for enabling GL_TEXTURE_2D and
  disabling GL_TEXTURE_2D, GL_TEXTURE_RECTANGLE_EXT or
  GL_TEXTURE_CUBE_MAP.
*/
void
SoGLTextureEnabledElement::set(SoState * const state,
                               SoNode * const node,
                               const SbBool enabled)
{
  inherited::set(state, node, enabled);
  SoShapeStyleElement::setTextureEnabled(state, enabled);
}

/*!
  Enables GL_TEXTURE_RECTANGLE_EXT/NV. GL_TEXTURE_2D/GL_TEXTURE_CUBE_MAP will be
  disabled if it's enabled earlier.

  \since Coin 2.2
*/
void
SoGLTextureEnabledElement::enableRectangle(SoState * state, SoNode * node)
{
  SoInt32Element::set(classStackIndex, state, node, (int32_t) RECTANGLE);
  SoShapeStyleElement::setTextureEnabled(state, TRUE);
}

/*!
  Enables GL_TEXTURE_CUBE+MAP. GL_TEXTURE_2D and/or
  GL_TEXTURE_RECTANGLE will be disabled if it's enabled earlier.
*/
void
SoGLTextureEnabledElement::enableCubeMap(SoState * state, SoNode * node)
{
  SoInt32Element::set(classStackIndex, state, node, (int32_t) CUBEMAP);
  SoShapeStyleElement::setTextureEnabled(state, TRUE);
}

/*!

  Returns the current texture mode.

*/
SoGLTextureEnabledElement::Mode
SoGLTextureEnabledElement::getMode(SoState * state)
{
  return (Mode) SoInt32Element::get(classStackIndex, state);
}

// doc from parent
void
SoGLTextureEnabledElement::init(SoState * state)
{
  inherited::init(state);
}

// Documented in superclass. Overridden to track GL state.
void
SoGLTextureEnabledElement::push(SoState * state)
{
  SoGLTextureEnabledElement * prev = (SoGLTextureEnabledElement*) this->getNextInStack();

  this->data = prev->data;
  // capture previous element since we might or might not change the
  // GL state in set/pop
  prev->capture(state);
}

// Documented in superclass. Overridden to track GL state.
void
SoGLTextureEnabledElement::pop(SoState * state,
                               const SoElement * prevTopElement)
{
  SoGLTextureEnabledElement * prev = (SoGLTextureEnabledElement*) prevTopElement;
  if (this->data != prev->data) {
    this->updategl((Mode) this->data, (Mode) prev->data);
  }
}

/*!
  Sets the state of the element.
*/
void
SoGLTextureEnabledElement::set(SoState * const state, const SbBool enabled)
{
  SoGLTextureEnabledElement::set(state, NULL, enabled);
}

/*!
  Return current state of this element.
*/
SbBool
SoGLTextureEnabledElement::get(SoState * const state)
{
  return inherited::get(state);
}

/*!
  Returns default state of this element (FALSE).
*/
SbBool
SoGLTextureEnabledElement::getDefault(void)
{
  return inherited::getDefault();
}

void
SoGLTextureEnabledElement::setElt(int32_t value)
{
  if (this->data != value) {
    this->updategl((Mode) value, (Mode)this->data);
    this->data = value;
  }
}

//
// updates GL state (obsoleted)
//
void
SoGLTextureEnabledElement::updategl(void)
{
  assert(0 && "obsoleted");
  if (this->data) glEnable(GL_TEXTURE_2D);
  else glDisable(GL_TEXTURE_2D);
}

void
SoGLTextureEnabledElement::updategl(const Mode newvalue, const Mode oldvalue)
{
  // FIXME: the code below looks fairly non-optimal. Should at least
  // avoid doing glDisable() then glEnable(). 20040802 mortene.
  //
  // We check for this before calling this method. 2005-01-27 pederb.

  switch (oldvalue) {
  case DISABLED:
    break;
  case TEXTURE2D:
    glDisable(GL_TEXTURE_2D);
    break;
  case RECTANGLE:
    glDisable(GL_TEXTURE_RECTANGLE_EXT);
    break;
  case CUBEMAP:
    glDisable(GL_TEXTURE_CUBE_MAP);
    break;
  default:
    assert(0 && "should not happen");
    break;
  }
  switch (newvalue) {
  case DISABLED:
    break;
  case TEXTURE2D:
    glEnable(GL_TEXTURE_2D);
    break;
  case RECTANGLE:
    glEnable(GL_TEXTURE_RECTANGLE_EXT);
    break;
  case CUBEMAP:
    glEnable(GL_TEXTURE_CUBE_MAP);
    break;
  default:
    assert(0 && "should not happen");
    break;
  }
}


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

namespace Orleans.Streams
{
    internal class PersistentStreamProducer<T> : IInternalAsyncBatchObserver<T>
    {
        private readonly StreamImpl<T> stream;
        private readonly IQueueAdapter queueAdapter;

        internal bool IsRewindable { get; private set; }

        internal PersistentStreamProducer(StreamImpl<T> stream, IStreamProviderRuntime providerUtilities, IQueueAdapter queueAdapter, bool isRewindable)
        {
            this.stream = stream;
            this.queueAdapter = queueAdapter;
            IsRewindable = isRewindable;
            var logger = providerUtilities.GetLogger(this.GetType().Name);
            if (logger.IsVerbose) logger.Verbose("Created PersistentStreamProducer for stream {0}, of type {1}, and with Adapter: {2}.",
                stream.ToString(), typeof (T), this.queueAdapter.Name);
        }

        public Task OnNextAsync(T item, StreamSequenceToken token)
        {
            return queueAdapter.QueueMessageAsync(stream.StreamId.Guid, stream.StreamId.Namespace, item, token, Runtime.RequestContext.Export());
        }

        public Task OnNextBatchAsync(IEnumerable<T> batch, StreamSequenceToken token)
        {
            return queueAdapter.QueueMessageBatchAsync(stream.StreamId.Guid, stream.StreamId.Namespace, batch, token, Runtime.RequestContext.Export());
        }

        public Task OnCompletedAsync()
        {
            // Maybe send a close message to the rendezvous?
            throw new NotImplementedException("OnCompletedAsync is not implemented for now.");
        }

        public Task OnErrorAsync(Exception ex)
        {
            // Maybe send a close message to the rendezvous?
            throw new NotImplementedException("OnErrorAsync is not implemented for now.");
        }

        public Task Cleanup()
        {
            return TaskDone.Done;
        }
    }
}


text:
<?php

namespace Respect\Validation\Exceptions;

class UrlException extends ValidationException
{
    public static $defaultTemplates = [
        self::MODE_DEFAULT => [
            self::STANDARD => '{{name}} must be an URL',
        ],
        self::MODE_NEGATIVE => [
            self::STANDARD => '{{name}} must not be an URL',
        ],
    ];
}


text:
tags: technology
layout: post
title: "Outlook only top-posts?"
---

With my new job I've become an Outlook user for the first time. I'm not real keen on this, but since it's integrated with Exchange which we use for groupware stuff as well I can't just use an IMAP client.

So I'm not an Outlook pro yet and this option may be available, but you don't seem to be able to control whether replies are top- or bottom-posted -- they're always top-posted. I can't believe it, but is this really so? Because we all know that top-posting is evil, right? Is this why so many people refuse to trim quoted text, thus wasting untold worldwide hours a few seconds at a shot?


text:
class CreateDeclarations < ActiveRecord::Migration
  def change
    create_table :declarations do |t|
      t.string :prefix
      t.text :parameters

      t.timestamps
    end
  end
end


text:
A Python module to fetch and parse data from Quora user profiles.

### Projects built using pyquora
* [`QUserAPI`](https://github.com/hansika/QUserAPI) – A REST API to get data from Quora user profiles.

## Installation
* You will need [Python 2](https://www.python.org/download/).
* [pip](http://pip.readthedocs.org/en/latest/installing.html) is recommended for installing dependencies.

Install using pip:

    pip install scrape_quora

## Usage

```python

from scrape_quora import Scrape_Quora

name = Scrape_Quora.get_name('Hansika-Hewamalage')

```

## Features
### Currently implemented
Retrieve
* Profile Name
* URL
* Profile Picture Link
* No of Questions
* No of Answers
* No of Followers
* No of Following
* No of Edits

### Todo
Retrieve
* Facebook Profile Link
* Twitter Link
* Wordpress Link
* LinkedIn Link


text:
require 'rails/generators/app_base'

module Rails
  module ActionMethods # :nodoc:
    attr_reader :options

    def initialize(generator)
      @generator = generator
      @options   = generator.options
    end

    private
      %w(template copy_file directory empty_directory inside
         empty_directory_with_keep_file create_file chmod shebang).each do |method|
        class_eval <<-RUBY, __FILE__, __LINE__ + 1
          def #{method}(*args, &block)
            @generator.send(:#{method}, *args, &block)
          end
        RUBY
      end

      # TODO: Remove once this is fully in place
      def method_missing(meth, *args, &block)
        @generator.send(meth, *args, &block)
      end
  end

  # The application builder allows you to override elements of the application
  # generator without being forced to reverse the operations of the default
  # generator.
  #
  # This allows you to override entire operations, like the creation of the
  # Gemfile, README, or JavaScript files, without needing to know exactly
  # what those operations do so you can create another template action.
  class AppBuilder
    def rakefile
      template "Rakefile"
    end

    def readme
      copy_file "README.rdoc", "README.rdoc"
    end

    def gemfile
      template "Gemfile"
    end

    def configru
      template "config.ru"
    end

    def gitignore
      copy_file "gitignore", ".gitignore"
    end

    def app
      directory 'app'

      keep_file  'app/assets/images'
      keep_file  'app/mailers'
      keep_file  'app/models'

      keep_file  'app/controllers/concerns'
      keep_file  'app/models/concerns'
    end

    def bin
      directory "bin" do |content|
        "#{shebang}\n" + content
      end
      chmod "bin", 0755 & ~File.umask, verbose: false
    end

    def config
      empty_directory "config"

      inside "config" do
        template "routes.rb"
        template "application.rb"
        template "environment.rb"

        directory "environments"
        directory "initializers"
        directory "locales"
      end
    end

    def database_yml
      template "config/databases/#{options[:database]}.yml", "config/database.yml"
    end

    def db
      directory "db"
    end

    def lib
      empty_directory 'lib'
      empty_directory_with_keep_file 'lib/tasks'
      empty_directory_with_keep_file 'lib/assets'
    end

    def log
      empty_directory_with_keep_file 'log'
    end

    def public_directory
      directory "public", "public", recursive: false
    end

    def test
      empty_directory_with_keep_file 'test/fixtures'
      empty_directory_with_keep_file 'test/controllers'
      empty_directory_with_keep_file 'test/mailers'
      empty_directory_with_keep_file 'test/models'
      empty_directory_with_keep_file 'test/helpers'
      empty_directory_with_keep_file 'test/integration'

      template 'test/test_helper.rb'
    end

    def tmp
      empty_directory "tmp/cache"
      empty_directory "tmp/cache/assets"
    end

    def vendor
      vendor_javascripts
      vendor_stylesheets
    end

    def vendor_javascripts
      empty_directory_with_keep_file 'vendor/assets/javascripts'
    end

    def vendor_stylesheets
      empty_directory_with_keep_file 'vendor/assets/stylesheets'
    end
  end

  module Generators
    # We need to store the RAILS_DEV_PATH in a constant, otherwise the path
    # can change in Ruby 1.8.7 when we FileUtils.cd.
    RAILS_DEV_PATH = File.expand_path("../../../../../..", File.dirname(__FILE__))
    RESERVED_NAMES = %w[application destroy plugin runner test]

    class AppGenerator < AppBase # :nodoc:
      add_shared_options_for "application"

      # Add bin/rails options
      class_option :version, type: :boolean, aliases: "-v", group: :rails,
                             desc: "Show Rails version number and quit"

      def initialize(*args)
        raise Error, "Options should be given after the application name. For details run: rails --help" if args[0].blank?

        super

        if !options[:skip_active_record] && !DATABASES.include?(options[:database])
          raise Error, "Invalid value for --database option. Supported for preconfiguration are: #{DATABASES.join(", ")}."
        end
      end

      public_task :create_root

      def create_root_files
        build(:readme)
        build(:rakefile)
        build(:configru)
        build(:gitignore) unless options[:skip_git]
        build(:gemfile)   unless options[:skip_gemfile]
      end

      def create_app_files
        build(:app)
      end

      def create_bin_files
        build(:bin)
      end

      def create_config_files
        build(:config)
      end

      def create_boot_file
        template "config/boot.rb"
      end

      def create_active_record_files
        return if options[:skip_active_record]
        build(:database_yml)
      end

      def create_db_files
        build(:db)
      end

      def create_lib_files
        build(:lib)
      end

      def create_log_files
        build(:log)
      end

      def create_public_files
        build(:public_directory)
      end

      def create_test_files
        build(:test) unless options[:skip_test_unit]
      end

      def create_tmp_files
        build(:tmp)
      end

      def create_vendor_files
        build(:vendor)
      end

      def finish_template
        build(:leftovers)
      end

      public_task :apply_rails_template, :run_bundle

    protected

      def self.banner
        "rails new #{self.arguments.map(&:usage).join(' ')} [options]"
      end

      # Define file as an alias to create_file for backwards compatibility.
      def file(*args, &block)
        create_file(*args, &block)
      end

      def app_name
        @app_name ||= (defined_app_const_base? ? defined_app_name : File.basename(destination_root)).tr(".", "_")
      end

      def defined_app_name
        defined_app_const_base.underscore
      end

      def defined_app_const_base
        Rails.respond_to?(:application) && defined?(Rails::Application) &&
          Rails.application.is_a?(Rails::Application) && Rails.application.class.name.sub(/::Application$/, "")
      end

      alias :defined_app_const_base? :defined_app_const_base

      def app_const_base
        @app_const_base ||= defined_app_const_base || app_name.gsub(/\W/, '_').squeeze('_').camelize
      end
      alias :camelized :app_const_base

      def app_const
        @app_const ||= "#{app_const_base}::Application"
      end

      def valid_const?
        if app_const =~ /^\d/
          raise Error, "Invalid application name #{app_name}. Please give a name which does not start with numbers."
        elsif RESERVED_NAMES.include?(app_name)
          raise Error, "Invalid application name #{app_name}. Please give a name which does not match one of the reserved rails words."
        elsif Object.const_defined?(app_const_base)
          raise Error, "Invalid application name #{app_name}, constant #{app_const_base} is already in use. Please choose another application name."
        end
      end

      def app_secret
        SecureRandom.hex(64)
      end

      def mysql_socket
        @mysql_socket ||= [
          "/tmp/mysql.sock",                        # default
          "/var/run/mysqld/mysqld.sock",            # debian/gentoo
          "/var/tmp/mysql.sock",                    # freebsd
          "/var/lib/mysql/mysql.sock",              # fedora
          "/opt/local/lib/mysql/mysql.sock",        # fedora
          "/opt/local/var/run/mysqld/mysqld.sock",  # mac + darwinports + mysql
          "/opt/local/var/run/mysql4/mysqld.sock",  # mac + darwinports + mysql4
          "/opt/local/var/run/mysql5/mysqld.sock",  # mac + darwinports + mysql5
          "/opt/lampp/var/mysql/mysql.sock"         # xampp for linux
        ].find { |f| File.exist?(f) } unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
      end

      def get_builder_class
        defined?(::AppBuilder) ? ::AppBuilder : Rails::AppBuilder
      end
    end
  end
end


text:
		<select id="predictionSurface" class="form-control" onchange="predictionSurfaceChanged(); predictMatch()" data-toggle="tooltip" data-placement="top" title="Select surface">
			<option value="">Unknown surface</option>
			<option th:each="aSurface : ${surfaces}" th:value="${aSurface.code}" th:class="|bg-surface-${aSurface.code}|" value="H" class="bg-surface-H" th:text="${aSurface.text}" th:selected="${aSurface.code == surface}">Hard</option>
		</select>

		<select id="predictionIndoor" class="form-control" onchange="predictMatch()" data-toggle="tooltip" data-placement="top" title="Select outdoor / indoor">
			<option value="">Unknown outdoor / indoor</option>
			<option value="false" th:selected="${indoor == false}">Outdoor</option>
			<option value="true" th:selected="${indoor == true}">Indoor</option>
		</select>

		<select id="predictionLevel" class="form-control" onchange="predictMatch()" data-toggle="tooltip" data-placement="top" title="Select tournament level">
			<option value="">Unknown level</option>
			<option th:each="aLevel : ${levels}" th:value="${aLevel.code}" th:class="|bg-level-${aLevel.code}|" value="G" class="bg-level-G" th:text="${aLevel.text}" th:selected="${aLevel.code == level}">Grand Slam</option>
		</select>

		<select id="predictionRound" class="form-control" onchange="predictMatch()" data-toggle="tooltip" data-placement="top" title="Select round">
			<option value="">Unknown round</option>
			<option th:each="aRound : ${rounds}" th:value="${aRound.code}" th:class="|bg-result-${aRound.baseCode}|" value="F" class="bg-result-F" th:text="${aRound.text}" th:selected="${aRound.code == round}">Final</option>
		</select>

				<input id="predictionSameDate" type="checkbox" th:checked="${sameDates}" onchange="onSameDateChanged()"/> On Same Date

			On Date:
			<input id="predictionDate" type="text" maxlength="10" class="form-control" th:value="${#temporals.format(date, 'dd-MM-yyyy')}" onchange="predictMatch()"/>

		<select id="predictionTournament" class="form-control" onchange="predictMatch()" data-toggle="tooltip" data-placement="top" title="Select tournament">
			<option value="">Unknown tournament</option>
			<optgroup th:each="lts : ${tournaments}" th:label="${lts.key.text}" label="Grand Slam" th:class="'bg-level-' + ${lts.key.code}">
				<option th:each="tournament : ${lts.value}" th:value="${tournament.id}" value="101" th:text="${tournament.name}" th:class="'bg-level-' + ${tournament.level}" th:selected="${tournament.id == tournamentId}">Wimbledon</option>
			</optgroup>
		</select>
		<input id="predictionTournamentEvent" type="hidden" th:value="${tournamentEventId}"/>

		<select id="predictionDateSelector1" class="form-control" onchange="predictMatch()">
			<option value="">Pick date 1</option>
			<option th:if="${player1.active}" value="Today" th:selected="${dateSelector1 == 'Today'}">Today</option>
			<option th:unless="${player1.active}" value="CareerEnd" th:selected="${dateSelector1 == 'CareerEnd'}">Career End</option>
			<option value="PeakRank" th:selected="${dateSelector1 == 'PeakRank'}">Peak ATP Ranking</option>
			<option value="PeakRankPoints" th:selected="${dateSelector1 == 'PeakRankPoints'}">Peak ATP Points</option>
			<option value="PeakEloRank" th:selected="${dateSelector1 == 'PeakEloRank'}">Peak Elo Ranking</option>
			<option value="PeakEloRating" th:selected="${dateSelector1 == 'PeakEloRating'}">Peak Elo Rating</option>

				<option th:value="|Peak${aSurface.text}EloRank|" value="PeakHardEloRank" th:text="|Peak ${aSurface.text} Elo Ranking|" th:class="|bg-surface-${aSurface.code}|" class="bg-surface-H" th:selected="${dateSelector1 == 'Peak' + aSurface.text + 'EloRank'}">Peak Hard Elo Ranking</option>
				<option th:value="|Peak${aSurface.text}EloRating|" value="PeakHardEloRating" th:text="|Peak ${aSurface.text} Elo Rating|" th:class="|bg-surface-${aSurface.code}|" class="bg-surface-H" th:selected="${dateSelector1 == 'Peak' + aSurface.text + 'EloRating'}">Peak Hard Elo Rating</option>

		</select>

			On Date 1:
			<input id="predictionDate1" type="text" maxlength="10" class="form-control" th:value="${#temporals.format(date1, 'dd-MM-yyyy')}" onchange="predictMatch()" th:readonly="${dateSelector1}"/>

			On Date 2:
			<input id="predictionDate2" type="text" maxlength="10" class="form-control" th:value="${#temporals.format(date2, 'dd-MM-yyyy')}" onchange="predictMatch()" th:readonly="${dateSelector2}"/>

		<select id="predictionDateSelector2" class="form-control" onchange="predictMatch()">
			<option value="">Pick date 2</option>
			<option th:if="${player2.active}" value="Today" th:selected="${dateSelector2 == 'Today'}">Today</option>
			<option th:unless="${player2.active}" value="CareerEnd" th:selected="${dateSelector2 == 'CareerEnd'}">Career End</option>
			<option value="PeakRank" th:selected="${dateSelector2 == 'PeakRank'}">Peak ATP Ranking</option>
			<option value="PeakRankPoints" th:selected="${dateSelector2 == 'PeakRankPoints'}">Peak ATP Points</option>
			<option value="PeakEloRank" th:selected="${dateSelector2 == 'PeakEloRank'}">Peak Elo Ranking</option>
			<option value="PeakEloRating" th:selected="${dateSelector2 == 'PeakEloRating'}">Peak Elo Rating</option>

				<option th:value="|Peak${aSurface.text}EloRank|" value="PeakHardEloRank" th:text="|Peak ${aSurface.text} Elo Ranking|" th:class="|bg-surface-${aSurface.code}|" class="bg-surface-H" th:selected="${dateSelector2 == 'Peak' + aSurface.text + 'EloRank'}">Peak Hard Elo Ranking</option>
				<option th:value="|Peak${aSurface.text}EloRating|" value="PeakHardEloRating" th:text="|Peak ${aSurface.text} Elo Rating|" th:class="|bg-surface-${aSurface.code}|" class="bg-surface-H" th:selected="${dateSelector2 == 'Peak' + aSurface.text + 'EloRating'}">Peak Hard Elo Rating</option>

		</select>

				Roger Federer

		vs

				Rafael Nadal

60.0%

		Win Probability

40.0%

1.50

		Odds

3.00

10

		ATP Ranking

15

10400

		ATP Points

5600

2350

		Elo Rating

2250

2350

		Recent Elo Rating

2250

2350

		Hard Elo Rating

2250

2350

		Outdoor Elo Rating

2250

2350

		Set Elo Rating

2250

15

		H2H

9

			<button id="showDetails" class="pct-data btn btn-default btn-xs" onclick="showPredictionDetails(true)" title="Show prediction details">Show Details  </button>
			<button id="hideDetails" class="raw-data btn btn-default btn-xs prediction-details" onclick="showPredictionDetails(false)" title="Hide prediction details">Hide Details  </button>

50.0%

		Predictability

50.0%

50.0%

				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO
				ELO

50.0%

			<button id="showInMatchPrediction" class="pct-data btn btn-default btn-xs" onclick="showInMatchPrediction(true)" title="Show prediction from a point in match">In-Match Prediction  </button>
			<button id="hideInMatchPrediction" class="raw-data btn btn-default btn-xs in-match-prediction" onclick="showInMatchPrediction(false)" title="Hide prediction from a point in match">In-Match Prediction  </button>

			<select id="predictionSets1" class="form-control in-match-score" onchange="predictMatch()">
				<option th:each="set : ${sets}" th:value="${set}" th:text="${set}" th:selected="${set == sets1}">0</option>
			</select>

		Sets

			<select id="predictionSets2" class="form-control in-match-score" onchange="predictMatch()">
				<option th:each="set : ${sets}" th:value="${set}" th:text="${set}" th:selected="${set == sets2}">0</option>
			</select>

			<select id="predictionGames1" class="form-control in-match-score" onchange="predictMatch()">
				<option th:each="game : ${games}" th:value="${game}" th:text="${game}" th:selected="${game == games1}">0</option>
			</select>

		Games

			<select id="predictionGames2" class="form-control in-match-score" onchange="predictMatch()">
				<option th:each="game : ${games}" th:value="${game}" th:text="${game}" th:selected="${game == games2}">0</option>
			</select>

			<select id="predictionPoints1" class="form-control in-match-score" onchange="predictMatch()">
				<option th:each="point : ${points}" th:value="${point.ordinal()}" th:text="${point.text}" th:selected="${point.ordinal() == points1}">0</option>
			</select>

		Points

			<select id="predictionPoints2" class="form-control in-match-score" onchange="predictMatch()">
				<option th:each="point : ${points}" th:value="${point.ordinal()}" th:text="${point.text}" th:selected="${point.ordinal() == points2}">0</option>
			</select>

			<select id="predictionPoints1" class="form-control in-match-score" onchange="predictMatch()">
				<option th:each="tbPoint : ${tbPoints}" th:value="${tbPoint}" th:text="${tbPoint}" th:selected="${tbPoint == points1}">0</option>
			</select>

		Points

			<select id="predictionPoints2" class="form-control in-match-score" onchange="predictMatch()">
				<option th:each="tbPoint : ${tbPoints}" th:value="${tbPoint}" th:text="${tbPoint}" th:selected="${tbPoint == points2}">0</option>
			</select>

			<input id="predictionServe1" type="checkbox" th:checked="${serve == 1}" onchange="$('#predictionServe2').prop('checked', !$(this).prop('checked')); predictMatch()"/>

		Serve

			<input id="predictionServe2" type="checkbox" th:checked="${serve == 2}" onchange="$('#predictionServe1').prop('checked', !$(this).prop('checked')); predictMatch()"/>

65.0%

		In-Match Win Prob.

35.0%

 0.0001 ? 'positive' : (pInMatchSwing1 < -0.0001 ? 'negative' : 'no-diff')}" th:text="${(pInMatchSwing1 > 0.0001 ? '+' : '') + (#uts.isCloseTo(pInMatchSwing1, 0, 0.0001) ? '0.0' : #numbers.formatDecimal(100 * pInMatchSwing1, 1, 1)) + '%'}">+5.0%

		Win Prob. Swing

 0.0001 ? 'positive' : (pInMatchSwing2 < -0.0001 ? 'negative' : 'no-diff')}" th:text="${(pInMatchSwing2 > 0.0001 ? '+' : '') + (#uts.isCloseTo(pInMatchSwing2, 0, 0.0001) ? '0.0' : #numbers.formatDecimal(100 * pInMatchSwing2, 1, 1)) + '%'}">-5.0%

65.0%

		Curr. Set Win Prob.

35.0%

65.0%

		Curr. Game Win Prob.

35.0%

50.0%

		Set Win Prob.

50.0%

50.0%

		Svc. Game Win Prob.

50.0%

50.0%

		Rtn. Game Win Prob.

50.0%

50.0%

		Svc. Pt. Win Prob.

50.0%

50.0%

		Rtn. Pt. Win Prob.

50.0%

	* Match Prediction can be for specific surface, tournament level and/or round.

	Prediction can be for the same date for both players, but also for Hypothetical Matchup between two players on their peaks!


text:
{% extends "base.html" %}

{% block head %}
    <title>Autorski suchar</title>
    <meta name="description" content="Autorski suchar dodany przez użytkownika">
{% endblock %}

{% block autorskie %} class="active"{% endblock %}

{% block jokes %}

            {{ joke.votes }} {{ joke.author }}
            {{ joke.date }}

{{ joke.body|linebreaksbr }}

{% endblock %}


text:
using System;

namespace Alchemy.Plugins.Peek.Controllers.Entries
{
    public class DateEntry
    {
        public string Type { get { return "date"; } }
        public DateTime? Value { get; set; }
        public string Label { get; set; }
        public string User { get; set; }

        public static DateEntry From(DateTime? value, string label)
        {
            return value != null ? new DateEntry { Value = value, Label = label } : null;
        }
    }
}


text:
description: This template enables you to deploy an Azure Relay namespace with standard SKU, a WCF Relay and a HybridConnection.
page_type: sample
products:
- azure
- azure-resource-manager
urlFragment: azure-relay-create-all-resources
languages:
- json
---
# Create an Azure Relay namespace with all resources

![Azure Public Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.relay/azure-relay-create-all-resources/PublicLastTestDate.svg)
![Azure Public Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.relay/azure-relay-create-all-resources/PublicDeployment.svg)

![Azure US Gov Last Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.relay/azure-relay-create-all-resources/FairfaxLastTestDate.svg)
![Azure US Gov Last Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.relay/azure-relay-create-all-resources/FairfaxDeployment.svg)

![Best Practice Check](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.relay/azure-relay-create-all-resources/BestPracticeResult.svg)
![Cred Scan Check](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.relay/azure-relay-create-all-resources/CredScanResult.svg)

[![Deploy To Azure](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazure.svg?sanitize=true)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.relay%2Fazure-relay-create-all-resources%2Fazuredeploy.json)
[![Deploy To Azure US Gov](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazuregov.svg?sanitize=true)](https://portal.azure.us/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.relay%2Fazure-relay-create-all-resources%2Fazuredeploy.json)
[![Visualize](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/visualizebutton.svg?sanitize=true)](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.relay%2Fazure-relay-create-all-resources%2Fazuredeploy.json)

This template creates an Azure Relay namespace, a WCF Relay and a HybridConnection.

`Tags: Microsoft.Relay/Namespaces, wcfRelays, HybridConnections`


text:
<!--
Copyright 2018 Next Century Corporation

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.
-->

<link rel="import" href="../bower_components/iron-flex-layout/iron-flex-layout-classes.html">

<dom-module id="page-styles">
  <template>
    <style include="iron-flex iron-flex-reverse iron-flex-alignment iron-flex-factors iron-positioning"></style>

    <style>
      /* Application theme */
      :root {
        --primary-color: #757575; /* paper-grey-600 */
        --primary-background-color: #f5f5f5; /* paper-grey-100 */
        --primary-text-color: #212121; /* paper-grey-900 */
        --secondary-text-color: #757575; /* paper-grey-600 */
        --disabled-text-color: #e0e0e0; /* paper-grey-300 */
        --divider-color: #e0e0e0; /* paper-grey-300 */
        --navbar-color: #212121; /* paper-grey-900 */
      }

      body {
        /* Flexbox can cause scrollbars to be shown in IE when not needed so hide them. */
        overflow: hidden;
      }

      /*********************************************************
      /*
      /*  New stuff for index.html. Maybe it goes in its own page style,
      /*  because right now this breaks the entity page style.
      /*
      /*********************************************************/

      #logoLink {
        height: 30px;
      }

      #logoLinkBigger {
        height: 50px;
      }

      #logo {
        min-height: 30px;
        max-height: 30px;
        min-width: 70px;
        max-width: 70px;
      }

      #logoBigger {
        min-height: 50px;
        max-height: 50px;
        min-width: 110px;
        max-width: 110px;
      }

      #advancedSearchButton {
        margin-left: 5px;
        --icon-button-color: white;
        --icon-button-active-color: greenyellow;
        --icon-button-hovering-color: greenyellow;
      }

      #menuButton {
        margin-left: 10px;
        --icon-button-color: white;
        --icon-button-active-color: greenyellow;
        --icon-button-hovering-color: greenyellow;
      }

      #toggleDrawerButton {
        margin-right: 10px;
        --icon-button-active-color: greenyellow;
        --icon-button-hovering-color: greenyellow;
      }

      #menuDropdown div[slot="dropdown-content"] {
        background-color: var(--navbar-color);
        border: 1px solid var(--navbar-color);
        border-radius: 2px;
        color: white;
        overflow: hidden;
      }

      #menuDropdown div[slot="dropdown-content"] paper-icon-item {
        --paper-item-icon-width: 20px;
        --paper-item-icon: {
          --iron-icon-height: 20px;
          --iron-icon-width: 20px;
          margin-right: 10px;
        }
        --paper-icon-item: {
          border: 1px solid white;
          cursor: pointer;
          padding: 0 15px;
          /* Below is needed for IE */
          line-height: 48px;
          min-width: 300px;
          /* Above is needed for IE */
        }
        --paper-item-disabled-color: var(--paper-grey-500);
      }

      #menuDropdown div[slot="dropdown-content"] paper-icon-item:hover {
        color: greenyellow;
      }

      export-button {
        margin-left: 10px;
      }

      .fields-menu > div {
        color: var(--secondary-text-color);
        font-size: 16px;
        font-weight: 500;
        line-height: 30px;
        margin-left: 10px;
        min-height: 30px;
        text-transform: uppercase;
      }

      dropdown-menu {
        margin-left: 10px;
      }

      .note {
        font-style: italic;
        color: var(--secondary-text-color);
        font-size: 14px;
        line-height: 20px;
        text-transform: uppercase;
        margin-bottom: 10px;
      }

      loading-spinner {
        margin: 10px;
      }

      /*********************************************************/

      /* Material Design Adaptive Breakpoints */
      /*
        Below you'll find CSS media queries based on the breakpoint guidance
        published by the Material Design team. You can choose to use, customise
        or remove these breakpoints based on your needs.

        http://www.google.com/design/spec/layout/adaptive-ui.html#adaptive-ui-breakpoints
       */

      /* mobile-small */
      @media all and (min-width: 0) and (max-width: 360px) and (orientation: portrait) { }
      /* mobile-large */
      @media all and (min-width: 361px) and (orientation: portrait) { }
      /* mobile-small-landscape */
      @media all and (min-width: 0) and (max-width: 480px) and (orientation: landscape) { }
      /* mobile-large-landscape */
      @media all and (min-width: 481px) and (orientation: landscape) { }
      /* tablet-small-landscape */
      @media all and (min-width: 600px) and (max-width: 960px) and (orientation: landscape) { }
      /* tablet-large-landscape */
      @media all and (min-width: 961px) and (orientation: landscape) { }
      /* tablet-small */
      @media all and (min-width: 600px) and (orientation: portrait) { }
      /* tablet-large */
      @media all and (min-width: 601px) and (max-width: 840px) and (orientation : portrait) { }
      /* desktop-x-small-landscape */
      @media all and (min-width: 0) and (max-width: 480px) and (orientation: landscape) { }
      /* desktop-x-small */
      @media all and (min-width: 0) and (max-width: 480px) and (max-aspect-ratio: 4/3) { }
      /* desktop-small-landscape */
      @media all and (min-width: 481px) and (max-width: 840px) and (orientation: landscape) { }
      /* desktop-small */
      @media all and (min-width: 481px) and (max-width: 840px) and (max-aspect-ratio: 4/3) { }
      /* desktop-medium-landscape */
      @media all and (min-width: 841px) and (max-width: 1280px) and (orientation: landscape) { }
      /* desktop-medium */
      @media all and (min-width: 841px) and (max-width: 1280px) and (max-aspect-ratio: 4/3) { }
      /* desktop-large */
      @media all and (min-width: 1281px) and (max-width: 1600px) { }
      /* desktop-xlarge */
      @media all and (min-width: 1601px) and (max-width: 1920px) { }
    </style>
  </template>
</dom-module>


text:
@section('styles')
{{ HTML::style('assets/lib/fractionslider/css/fractionslider.css'); }}
@stop

                    Create Invoices in Seconds

                    Check out the those great features

                    New colors available

                    45+ pages models

                    Enhanced shopping style

                    Optional sidebar menu

                    Optional header style

                    Now. Faster. Stronger

                    Fresh and adaptive design

                    Complete features

                    Easy to customize

                    Easier to achieve your goals

                    Fully UPDATED

@section('scripts')
{{ HTML::script('assets/lib/fractionslider/jquery.fractionslider.min.js'); }}

@stop