text:
package com.tribbloids.spookystuff.row

import com.tribbloids.spookystuff.testutils.SpookyEnvFixture

/**
  * Created by peng on 30/03/16.
  */
class DataRowSuite extends SpookyEnvFixture {

  import com.tribbloids.spookystuff.dsl._

  it("interpolate") {
    val map = Map(Field("abc") -> 1, Field("def") -> 2.2)
    val result = DataRow(map).replaceInto("rpk'{abc}aek'{def}")
    assert(result === Some("rpk1aek2.2"))
  }

  it("interpolate returns None when key not found") {

    val map = Map(Field("abc") -> 1, Field("rpk") -> 2.2)
    val result = DataRow(map).replaceInto("rpk'{abc}aek'{def}")
    assert(result === None)
  }

  it("formatNullString") {
    assert(DataRow(Map()).replaceInto(null).isEmpty)
  }

  it("formatEmptyString") {
    assert(DataRow(Map()).replaceInto("").contains(""))
  }

  it("getInt can extract scala Int type") {
    val map = Map(Field("abc") -> 1, Field("def") -> Array("d", "e", "f"))
    val result = DataRow(map).getInt('abc).get
    assert(result == 1)
  }

  it("getInt can extract java.lang.Integer type") {
    val map: Map[Field, Any] = Map(Field("abc") -> (1: java.lang.Integer), Field("def") -> Array("d", "e", "f"))
    val result = DataRow(map).getInt('abc).get
    assert(result == 1)
  }

  it("getTyped can extract scala Int type") {
    val map = Map(Field("abc") -> 1, Field("def") -> Array("d", "e", "f"))
    val result = DataRow(map).getTyped[Int]('abc).get
    assert(result == 1)
  }

  it("getTyped can extract java.lang.Integer type") {
    val map: Map[Field, Any] = Map(Field("abc") -> (1: java.lang.Integer), Field("def") -> Array("d", "e", "f"))
    val result = DataRow(map).getTyped[Int]('abc).get
    assert(result == 1)
  }

  it("getTyped should return None if type is incompatible") {
    val map: Map[Field, Any] = Map(Field("abc") -> (1.1: java.lang.Double), Field("def") -> Array("d", "e", "f"))
    val result = DataRow(map).getTyped[Int]('abc)
    assert(result.isEmpty)
  }

  it("getTypedArray can extract from Array") {
    val map = Map(Field("abc") -> 1, Field("def") -> Array("d", "e", "f"))
    val result = DataRow(map).getTypedArray[String]('def).get
    assert(result.toSeq == Seq("d", "e", "f"))
  }

  it("getTypedArray can extract from Iterator") {
    val map = Map(Field("abc") -> 1, Field("def") -> Seq("d", "e", "f").iterator)
    val result = DataRow(map).getTypedArray[String]('def).get
    assert(result.toSeq == Seq("d", "e", "f"))
  }

  it("getTypedArray can extract from Set") {
    val map = Map(Field("abc") -> 1, Field("def") -> Set("d", "e", "f"))
    val result = DataRow(map).getTypedArray[String]('def).get
    assert(result.toSet == Set("d", "e", "f"))
  }

  it("getTypedArray can extract from Array that has different types") {
    val map = Map(Field("abc") -> 1, Field("def") -> Set(2, 3.3, "def"))
    val result = DataRow(map).getTypedArray[String]('def).get
    assert(result.toSet == Set("def"))
  }

  it("getIntArray can extract from Array") {
    val map = Map(Field("abc") -> 1, Field("def") -> Array[Int](2, 3, 4))
    val result = DataRow(map).getIntArray('def).get
    assert(result.toSeq == Seq(2, 3, 4))
  }

  it("getIntArray can extract from Iterator") {
    val map = Map(Field("abc") -> 1, Field("def") -> Seq[Int](2, 3, 4).iterator)
    val result = DataRow(map).getIntArray('def).get
    assert(result.toSeq == Seq(2, 3, 4))
  }

  it("getIntArray can extract from Set") {
    val map = Map(Field("abc") -> 1, Field("def") -> Set[Int](2, 3, 4))
    val result = DataRow(map).getIntArray('def).get
    assert(result.toSet == Set(2, 3, 4))
  }

  it("getIntArray can extract from Array that has different types") {
    val map = Map(Field("abc") -> 1, Field("def") -> Set(2, 3.3, "def"))
    val result = DataRow(map).getIntArray('def).get
    assert(result.toSet == Set(2))
  }

  it("getIntIterable can extract from Array") {
    val map = Map(Field("abc") -> 1, Field("def") -> Array[Int](2, 3, 4))
    val result = DataRow(map).getIntIterable('def).get
    assert(result.toSeq == Seq(2, 3, 4))
  }

  it("getIntIterable can extract from Iterator") {
    val map = Map(Field("abc") -> 1, Field("def") -> Seq[Int](2, 3, 4).iterator)
    val result = DataRow(map).getIntIterable('def).get
    assert(result.toSeq == Seq(2, 3, 4))
  }

  it("getIntIterable can extract from Set") {
    val map = Map(Field("abc") -> 1, Field("def") -> Set[Int](2, 3, 4))
    val result = DataRow(map).getIntIterable('def).get
    assert(result.toSet == Set(2, 3, 4))
  }

  it("getIntIterable can extract from Array that has different types") {
    val map = Map(Field("abc") -> 1, Field("def") -> Set(2, 3.3, "def"))
    val result = DataRow(map).getIntIterable('def).get
    assert(result.toSet == Set(2))
  }
}


text:
module Puppet::Parser::Functions
  newfunction(:prefix, :type => :rvalue, :doc => <<-EOS
This function applies a prefix to all elements in an array.

*Examles:*

    prefix(['a','b','c'], 'p')

Will return: ['pa','pb','pc']
    EOS
  ) do |arguments|

    # Technically we support two arguments but only first is mandatory ...
    raise(Puppet::ParseError, "prefix(): Wrong number of arguments " +
      "given (#{arguments.size} for 1)") if arguments.size < 1

    array = arguments[0]

    unless array.is_a?(Array)
      raise(Puppet::ParseError, 'prefix(): Requires array to work with')
    end

    prefix = arguments[1] if arguments[1]

    if prefix
      unless prefix.is_a?(String)
        raise(Puppet::ParseError, 'prefix(): Requires string to work with')
      end
    end

    # Turn everything into string same as join would do ...
    result = array.collect do |i|
      i = i.to_s
      prefix ? prefix + i : i
    end

    return result
  end
end

# vim: set ts=2 sw=2 et :

redpajama_set_name: RedPajamaGithub


text:
class SerProc
{
    private:
    SC_HANDLE SCManH;
    LPSERVICE_STATUS STATUS;
    public:
    SerProc::SerProc();
    int SerProc::RemoveSer(const char* Sername);
};

#endif // SERPROC_H_INCLUDED


text:
package com.oufyp.bestpricehk;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.oufyp.bestpricehk.app.AppController;
import com.oufyp.bestpricehk.app.CustomRequest;
import com.oufyp.bestpricehk.app.UserFunctions;
import com.oufyp.bestpricehk.database.DatabaseHandler;
import com.oufyp.bestpricehk.model.Product;

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

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

public class DisplayProductInfo extends Activity {
    public static final String TAG = DisplayProductInfo.class.getSimpleName();
    private Context mContext = this;
    private UserFunctions uf = new UserFunctions();
    private DatabaseHandler db;
    private Product product;
    private String[] price = {"—", "—", "—", "—"};
    private String[] discount = {"—", "—", "—", "—"};
    private String lastDate = "—";
    private ImageView image;
    private TextView description;
    private TextView countFav;
    private TextView countShare;
    private boolean success = false;
    private String selectedQty = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading);
        db = DatabaseHandler.getInstance(mContext);
        Intent intent = getIntent();
        if (intent.getStringExtra("TAG") != null && (intent.getStringExtra("TAG").equals("FavouritesActivity") || intent.getStringExtra("TAG").equals("DisplayShares") || intent.getStringExtra("TAG").equals("CommunityFragment"))) {
            // handle the intent from DisplayShares activity and community fragment
            String pid = intent.getStringExtra("PID");
            product = new Product();
            String url = String.format("http://101.78.220.131:8909/bestpricehk/products.php?pid=%s", pid);
            JsonObjectRequest jsObjRequest = new JsonObjectRequest
                    (url, null, new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            try {
                                JSONObject info = jsonObject.getJSONObject("simple_info");
                                product.setId(info.getString("pid"));
                                product.setName(info.getString("name"));
                                product.setType(info.getString("type"));
                                product.setBrand(info.getString("brand"));
                                product.setCountFav(Integer.parseInt(info.getString("count_fav")));
                                product.setCountShare(Integer.parseInt(info.getString("count_share")));
                                setDetailsView(product.getId());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            VolleyLog.d(TAG, "Error: " + error.getMessage());
                        }
                    });
            AppController.getInstance().addToRequestQueue(jsObjRequest);
        } else {
            product = (Product) intent.getExtras().getSerializable("product");
            setDetailsView(product.getId());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.display_product_info, menu);
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        if (item.getItemId() == R.id.action_map) {
            Intent intent = new Intent(this, MapActivity.class);
            intent.putExtra("PRODUCT", product);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void socialBtnHandler(View v) {
        if (uf.isUserLoggedIn(mContext)) {
            switch (v.getId()) {
                case R.id.button_favourite:
                    if (uf.isGoldMember(mContext) || uf.isSilverMember(mContext)) {
                        if (db.isFavourited(product.getId())) {
                            // remove favourite product
                            new AlertDialog.Builder(this)
                                    .setMessage("Remove product from favourite list? ")
                                    .setPositiveButton("REMOVE", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int whichButton) {
                                            removeFavourite(product);
                                        }
                                    }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    // Do nothing.
                                }
                            }).create().show();
                        }// add favourite product
                        else {
                            if (uf.isGoldMember(mContext)) {
                                setFavourite(product);
                            }else if(db.getFavProductsCount()>= 10){
                                Toast.makeText(mContext,"As a silver member, you can only add at most 10 favourite products",Toast.LENGTH_SHORT).show();
                            }else{
                                setFavourite(product);
                            }
                        }
                    }else{
                        Toast.makeText(mContext,"Only silver and gold member can add favourite products",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.button_share:
                    Intent intent = new Intent(this, ShareActivity.class);
                    intent.putExtra("PRODUCT", product);
                    startActivity(intent);
            }
        } else {
            Toast.makeText(mContext, getString(R.string.please_login), Toast.LENGTH_SHORT).show();
        }
    }

    public void setPriceView(Product product) {
        String[] price = product.getPrice();
        String[] discount = product.getDiscount();
        TextView tv = (TextView) findViewById(R.id.pk_price);
        tv.setText(getString(R.string.tv_price, price[0]));
        tv = (TextView) findViewById(R.id.pk_dicount);
        tv.setText(getString(R.string.tv_discount, discount[0]));
        tv = (TextView) findViewById(R.id.wellcome_price);
        tv.setText(getString(R.string.tv_price, price[1]));
        tv = (TextView) findViewById(R.id.wellcome_dicount);
        tv.setText(getString(R.string.tv_discount, discount[1]));
        tv = (TextView) findViewById(R.id.jusco_price);
        tv.setText(getString(R.string.tv_price, price[2]));
        tv = (TextView) findViewById(R.id.jusco_dicount);
        tv.setText(getString(R.string.tv_discount, discount[2]));
        tv = (TextView) findViewById(R.id.mp_price);
        tv.setText(getString(R.string.tv_price, price[3]));
        tv = (TextView) findViewById(R.id.mp_dicount);
        tv.setText(getString(R.string.tv_discount, discount[3]));
        tv = (TextView) findViewById(R.id.last_updated);
        tv.setText(getString(R.string.last_updated, lastDate));
    }

    public void setDetailsView(String pid) {
        setContentView(R.layout.activity_display_product_info);
        String url = String.format("http://101.78.220.131:8909/bestpricehk/products/details/%s", pid);
        image = (ImageView) findViewById(R.id.productImg);
        description = (TextView) findViewById(R.id.productDescription);
        countFav = (TextView) findViewById(R.id.count_favourite);
        countShare = (TextView) findViewById(R.id.count_share);
        image.setImageResource(product.getImage(product.getType()));
        description.setText(product.getDescription());
        countFav.setText("" + product.getCountFav());
        countShare.setText("" + product.getCountShare());
        JsonObjectRequest jsObjRequest = new JsonObjectRequest
                (url, null, new ResponseListener(), new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        //set default value to price and discount;
                        product.setDiscount(discount);
                        product.setPrice(price);

                        setPriceView(product);
                    }
                });
        AppController.getInstance().addToRequestQueue(jsObjRequest);

    }

    public void browseStore(View view) {
        int id = view.getId();
        Intent intent = new Intent(getApplicationContext(), SearchActivity.class);
        intent.putExtra("type", product.getType());
        switch (id) {
            case R.id.wellcome_img:
                intent.putExtra("store", "Wellcome");
                break;
            case R.id.pk_img:
                intent.putExtra("store", "ParknShop");
                break;
            case R.id.jusco_img:
                intent.putExtra("store", "Jusco");
                break;
            case R.id.mp_img:
                intent.putExtra("store", "Market Place");
                break;
        }
        intent.putExtra("TAG", TAG);
        startActivity(intent);
    }

    public void setFavourite(Product product) {
        if (db.isFavourited(product.getId())) {
            CharSequence text = product.getName() + " has already added to favourite list.";
            Toast toast = Toast.makeText(mContext, text, Toast.LENGTH_SHORT);
            toast.show();
        } else {
            addFavToServer(product);
        }
    }

    public void removeFavourite(Product product) {
        if (db.isFavourited(product.getId())) {
            db.deleteFavProduct(product);
            delFavFromServer(product);
        } else {
            CharSequence text = "Error in removing";
            Toast toast = Toast.makeText(mContext, text, Toast.LENGTH_SHORT);
            toast.show();
        }
    }

    public void addFavToServer(final Product product) {
        final String uid = uf.getUserID(mContext);
        final String url = "http://101.78.220.131:8909/bestpricehk/fav_api/favproducts.php";
        List<String> qtyList = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            qtyList.add("" + i);
        }
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, qtyList);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        final Spinner sp = new Spinner(this);
        sp.setAdapter(dataAdapter);
        new AlertDialog.Builder(this)
                .setTitle("Add to favourite list")
                .setMessage("Select product's quantity: ")
                .setView(sp)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        selectedQty = sp.getSelectedItem().toString();
                        Map<String, String> params = new HashMap<>();
                        params.put("tag", "add");
                        params.put("uid", uid);
                        params.put("pid", product.getId());
                        params.put("qty", selectedQty);
                        CustomRequest request = new CustomRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject obj) {
                                db.addFavProduct(product); // add to local database
                                try {
                                    success = obj.getBoolean("success");
                                    if (success) {
                                        CharSequence text = "Added to favourite list.";
                                        Toast toast = Toast.makeText(mContext, text, Toast.LENGTH_SHORT);
                                        toast.show();
                                    } else {
                                        Toast toast = Toast.makeText(mContext, "Cant add to favourite list", Toast.LENGTH_SHORT);
                                        toast.show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                VolleyLog.d(TAG, "Error: " + error.getMessage());
                            }
                        });
                        AppController.getInstance().addToRequestQueue(request);
                    }
                }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                // Do nothing.
            }
        }).create().show();

    }

    public void delFavFromServer(Product product) {
        String uid = uf.getUserID(mContext);
        String url = "http://101.78.220.131:8909/bestpricehk/fav_api/favproducts.php";
        Map<String, String> params = new HashMap<>();
        params.put("tag", "delete");
        params.put("uid", uid);
        params.put("pid", product.getId());
        CustomRequest request = new CustomRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject obj) {
                try {
                    success = obj.getBoolean("success");
                    if (success) {
                        Toast toast = Toast.makeText(mContext, "Removed from favourite list.", Toast.LENGTH_SHORT);
                        toast.show();
                    } else {
                        Toast toast = Toast.makeText(mContext, "Cant delete to favourite list", Toast.LENGTH_SHORT);
                        toast.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        });
        AppController.getInstance().addToRequestQueue(request);
    }

    public void viewShare(View view) {
        if (uf.isUserLoggedIn(mContext)) {
            Intent intent = new Intent(getApplicationContext(), DisplayShares.class);
            intent.putExtra("TAG", TAG);
            intent.putExtra("PID", product.getId());
            intent.putExtra("UID", uf.getUserID(mContext));
            startActivity(intent);
        } else {
            Toast.makeText(mContext, getString(R.string.please_login), Toast.LENGTH_SHORT).show();
        }
    }

    public void reportProblem(View view) {
        if (uf.isUserLoggedIn(mContext)) {

            if (uf.isGoldMember(mContext)) {
                Intent intent = new Intent(this, ReportProblemActivity.class);
                intent.putExtra("PRODUCT", product);
                startActivity(intent);
            } else {
                Toast.makeText(mContext, getString(R.string.message_no_permission), Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(mContext, getString(R.string.please_login), Toast.LENGTH_SHORT).show();
        }
    }

    private class ResponseListener implements Response.Listener<JSONObject> {
        @Override
        public void onResponse(JSONObject obj) {
            try {
                success = obj.getBoolean("success");
                if (success) {
                    success = obj.getBoolean("success");
                    JSONArray details = obj.getJSONArray("details");
                    JSONObject c = details.getJSONObject(0);
                    //saving price and discount
                    price[0] = c.getString("price1");
                    discount[0] = c.getString("discount1");
                    price[1] = c.getString("price2");
                    discount[1] = c.getString("discount2");
                    price[2] = c.getString("price3");
                    discount[2] = c.getString("discount3");
                    price[3] = c.getString("price4");
                    discount[3] = c.getString("discount4");
                    product.setPrice(price);
                    product.setDiscount(discount);
                    lastDate = c.getString("dDate");
                } else {
                    //set default value to price and discount;
                    product.setDiscount(discount);
                    product.setPrice(price);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            setPriceView(product);
        }
    }

}


text:
package com.clicktravel.cheddar.request.context;

import java.util.Optional;

import com.amazonaws.xray.entities.Segment;

/**
 * Default implementation which stores the AWS XRay Segment context.
 */
public class DefaultAWSXraySegmentContext implements AWSXraySegmentContext {

    private final Optional<Segment> requestSegment;

    public DefaultAWSXraySegmentContext(final Segment requestSegment) {
        this.requestSegment = Optional.ofNullable(requestSegment);
    }

    @Override
    public Optional<Segment> requestSegment() {
        return requestSegment;
    }
}


text:
namespace printing {

namespace {

std::string& GetAgentImpl() {
  static base::NoDestructor<std::string> instance;
  return *instance;
}

}  // namespace

void SetAgent(const std::string& user_agent) {
  GetAgentImpl() = user_agent;
}

const std::string& GetAgent() {
  return GetAgentImpl();
}

}  // namespace printing


text:
Serial LCD
==========

[![GoDoc](https://godoc.org/github.com/augustoroman/serial_lcd?status.svg)](http://godoc.org/github.com/augustoroman/serial_lcd)

A library for communicating with an serial LCD controller.  This is specifically geared towards the Adafruit 16x2 serial backpack LCD kit (http://www.adafruit.com/products/784).

Simple usage:

```go
lcd, err := serial_lcd.Open("COM2", 9600)
lcd.SetSize(16,2)
lcd.SetBG(255,0,0) // R,G,B
lcd.Clear()
fmt.Fprint(lcd, "Hi there!")
```


text:
describe QA::Git::Repository do
  include Helpers::StubENV

  shared_context 'git directory' do
    let(:repository) { described_class.new }
    let(:tmp_git_dir) { Dir.mktmpdir }
    let(:tmp_netrc_dir) { Dir.mktmpdir }

    before do
      stub_env('GITLAB_USERNAME', 'root')
      cd_empty_temp_directory
      set_bad_uri

      allow(repository).to receive(:tmp_home_dir).and_return(tmp_netrc_dir)
    end

    after do
      # Switch to a safe dir before deleting tmp dirs to avoid dir access errors
      FileUtils.cd __dir__
      FileUtils.remove_entry_secure(tmp_git_dir, true)
      FileUtils.remove_entry_secure(tmp_netrc_dir, true)
    end

    def cd_empty_temp_directory
      FileUtils.cd tmp_git_dir
    end

    def set_bad_uri
      repository.uri = 'http://foo/bar.git'
    end
  end

  context 'with default credentials' do
    include_context 'git directory' do
      before do
        repository.use_default_credentials
      end
    end

    describe '#clone' do
      it 'is unable to resolve host' do
        expect { repository.clone }.to raise_error(described_class::RepositoryCommandError, /The command .* failed \(128\) with the following output/)
      end
    end

    describe '#push_changes' do
      before do
        `git init` # need a repo to push from
      end

      it 'fails to push changes' do
        expect { repository.push_changes }.to raise_error(described_class::RepositoryCommandError, /The command .* failed \(1\) with the following output/)
      end
    end

    describe '#git_protocol=' do
      [0, 1, 2].each do |version|
        it "configures git to use protocol version #{version}" do
          expect(repository).to receive(:run).with("git config protocol.version #{version}")
          repository.git_protocol = version
        end
      end

      it 'raises an error if the version is unsupported' do
        expect { repository.git_protocol = 'foo' }.to raise_error(ArgumentError, "Please specify the protocol you would like to use: 0, 1, or 2")
      end
    end

    describe '#fetch_supported_git_protocol' do
      it "reports the detected version" do
        expect(repository).to receive(:run).and_return("packet: git< version 2")
        expect(repository.fetch_supported_git_protocol).to eq('2')
      end

      it 'reports unknown if version is unknown' do
        expect(repository).to receive(:run).and_return("packet: git< version -1")
        expect(repository.fetch_supported_git_protocol).to eq('unknown')
      end

      it 'reports unknown if content does not identify a version' do
        expect(repository).to receive(:run).and_return("foo")
        expect(repository.fetch_supported_git_protocol).to eq('unknown')
      end
    end

    describe '#use_default_credentials' do
      it 'adds credentials to .netrc' do
        expect(File.read(File.join(tmp_netrc_dir, '.netrc')))
          .to eq("machine foo login #{QA::Runtime::User.default_username} password #{QA::Runtime::User.default_password}\n")
      end
    end
  end

  context 'with specific credentials' do
    include_context 'git directory'

    context 'before setting credentials' do
      it 'does not add credentials to .netrc' do
        expect(repository).not_to receive(:save_netrc_content)
      end
    end

    describe '#password=' do
      it 'raises an error if no username was given' do
        expect { repository.password = 'foo' }
          .to raise_error(QA::Git::Repository::InvalidCredentialsError,
            "Please provide a username when setting a password")
      end

      it 'adds credentials to .netrc' do
        repository.username = 'user'
        repository.password = 'foo'

        expect(File.read(File.join(tmp_netrc_dir, '.netrc')))
          .to eq("machine foo login user password foo\n")
      end

      it 'adds credentials with special characters' do
        password = %q[!"#$%&')(*+,-./:;<=>?]
        repository.username = 'user'
        repository.password = password

        expect(File.read(File.join(tmp_netrc_dir, '.netrc')))
          .to eq("machine foo login user password #{password}\n")
      end
    end
  end
end


text:
using System;
using OpenADK.Library;

namespace OpenADK.Library.uk.Learning
{
	///
	/// Defines the set of values that can be specified whenever a GroupTeacherType
	/// is used as a parameter to a method or constructor.
	///
	/// <remarks>
	/// Alternatively, the static
	///  <see cref="Wrap"/> method can be called to encapsulate any string value in
	///  a GroupTeacherType object.
	/// <para>Author: Generated by adkgen</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.3</para>
	/// </remarks>
	[Serializable]
	public class GroupTeacherType : SifEnum
	{
	/// Head-of-Dept/Subject-Leader ("H")
	public static readonly GroupTeacherType H_HEADOFDEPT_SUBJECTLEADER = new GroupTeacherType("H");

	/// other/unspecified ("Z")
	public static readonly GroupTeacherType Z_OTHER_UNSPECIFIED = new GroupTeacherType("Z");

	/// Assistant ("A")
	public static readonly GroupTeacherType A_ASSISTANT = new GroupTeacherType("A");

	///Wrap an arbitrary string value in a GroupTeacherType object.
	///<param name="wrappedValue">The element/attribute value.</param>
	///<remarks>This method does not verify
	///that the value is valid according to the SIF Specification</remarks>
	public static GroupTeacherType Wrap( String wrappedValue ) {
		return new GroupTeacherType( wrappedValue );
	}

	private GroupTeacherType( string enumDefValue ) : base( enumDefValue ) {}
	}
}


text:
/*
 * OnePlusLambdaEvoStrategy.h
 *
 *  Created on: 05/04/2015
 *      Author: vitor
 */

#ifndef ONEPLUSLAMBDAEVOSTRATEGY_H_
#define ONEPLUSLAMBDAEVOSTRATEGY_H_

#include "EvolutionaryStrategy.h"

class OnePlusLambdaEvoStrategy: public EvolutionaryStrategy {
public:
	OnePlusLambdaEvoStrategy(std::mt19937& mt, int population_size,
			GeneticParams genetic_params, FitnessCalculator* fitness_calculator) :
			EvolutionaryStrategy(mt, population_size, genetic_params,
					fitness_calculator) {
	}

	void calcular_fitness(std::vector<Cromossomo>& populacao) {
		if (populacao.size() == 1) {
			for (int i = 0; i < population_size - 1; i++) {
				Cromossomo filho(populacao[0]);
				filho.mutar();
				filho.mutar();
				filho.mutar();
				populacao.emplace_back(filho);
			}
		}
		fitness_calculator->fitness(populacao);
	}

	std::vector<Cromossomo> proxima_geracao(
			std::vector<Cromossomo>& populacao) {
		if (primeira_populacao(populacao)) {
			return instancia_primeira_populacao();
		}
		std::vector<Cromossomo> nova_populacao;
		nova_populacao.emplace_back(melhor_individuo(populacao));
		return nova_populacao;
	}

	Cromossomo& melhor_individuo(std::vector<Cromossomo>& populacao) {
		Cromossomo& melhor = populacao[0];
		for (unsigned int i = 1; i < populacao.size(); i++) {
			if (populacao[i].fitness() >= melhor.fitness()) {
				melhor = populacao[i];
			}
		}
		return melhor;
	}

	bool primeira_populacao(const std::vector<Cromossomo>& populacao) {
		return populacao.empty();
	}

	std::vector<Cromossomo> instancia_primeira_populacao() {
		std::vector<Cromossomo> nova_populacao;
		for (int i = 0; i < population_size; i++) {
			nova_populacao.emplace_back(Cromossomo(mt, genetic_params));
		}
		return nova_populacao;
	}
};

#endif /* ONEPLUSLAMBDAEVOSTRATEGY_H_ */


text:
using UnityEngine;
using System.Collections;
using Jolly;

public class Bouncer : MonoBehaviour
{
	public float DespawnHeight;

	void Update ()
	{
		if (this.transform.position.y < this.DespawnHeight)
		{
			GameObject.Destroy (this.gameObject);
		}
	}
}


text:
/**
 *
 * RelationBox
 *
 */

import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { get, isEmpty, map, startCase } from 'lodash';
import pluralize from 'pluralize';

import { ButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap';
import Input from 'components/InputsIndex';
import styles from './styles.scss';

/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable react/jsx-wrap-multilines */
class RelationBox extends React.Component {
  // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);

    this.state = {
      showMenu: false,
    };
  }

  getPlaceholder = () => {
    switch (true) {
      case this.props.relationType === 'oneToMany' && this.props.isFirstContentType:
        return pluralize(this.props.contentTypeTargetPlaceholder);
      case this.props.relationType === 'manyToOne' && !this.props.isFirstContentType:
        return pluralize(this.props.contentTypeTargetPlaceholder);
      case this.props.relationType === 'manyToMany':
        return pluralize(this.props.contentTypeTargetPlaceholder);
      default:
        return this.props.contentTypeTargetPlaceholder;
    }
  }

  toggle = () => this.setState({ showMenu: !this.state.showMenu });

  renderDropdownMenu = () => (

      <ButtonDropdown
        isOpen={this.state.showMenu}
        toggle={this.toggle}
        style={{ backgroundColor: 'transparent' }}
      >
        <DropdownToggle caret />
        <DropdownMenu className={styles.dropDownContent}>
          {map(this.props.dropDownItems, (value, key) => {
            const id = value.source ? `${value.name}.${value.source}` : `${value.name}. `;
            let divStyle;

            if (
              get(this.props.header, 'name') === value.name &&
              !isEmpty(get(this.props.header, 'source')) &&
              value.source
            ) {
              divStyle = { color: '#323740', fontWeight: 'bold' };
            } else if (
              value.source === get(this.props.header, 'source') &&
              value.name === get(this.props.header, 'name')
            ) {
              divStyle = { color: '#323740', fontWeight: 'bold' };
            } else {
              divStyle = { color: 'rgba(50,55,64,0.75)' };
            }

            return (

                <DropdownItem onClick={this.props.onClick} id={id}>
                  <div style={divStyle} id={`${value.name}.${value.source}`}>
                    <i className={`fa ${value.icon}`} style={divStyle} id={id} />
                    {value.name}
                    {value.source && (
                      <FormattedMessage id="content-type-builder.from">
                        {message => (

                            ({message}: {value.source})

                        )}
                      </FormattedMessage>
                    )}

                </DropdownItem>

            );
          })}
        </DropdownMenu>
      </ButtonDropdown>

  );

  render() {
    return (

          <i className={`fa ${get(this.props.header, 'icon')}`} />
          {startCase(get(this.props.header, 'name'))}

            {get(this.props.header, 'source') ? `(${get(this.props.header, 'source')})` : ''}

          {!isEmpty(this.props.dropDownItems) && this.renderDropdownMenu()}

          <form onSubmit={this.props.onSubmit}>

              <div className={`row ${styles.input}`}>
                {!isEmpty(this.props.input) && (
                  <Input
                    disabled={this.props.relationType === 'oneWay' && this.props.tabIndex === '2'}
                    tabIndex={this.props.tabIndex}
                    type={get(this.props.input, 'type')}
                    onChange={this.props.onChange}
                    label={get(this.props.input, 'label')}
                    name={get(this.props.input, 'name')}
                    value={this.props.value}
                    placeholder={this.getPlaceholder()}
                    customBootstrapClass="col-md-12"
                    validations={get(this.props.input, 'validations')}
                    errors={this.props.errors}
                    didCheckErrors={this.props.didCheckErrors}
                    pluginID="content-type-builder"
                    autoFocus={this.props.autoFocus}
                  />
                )}

          </form>

    );
  }
}

RelationBox.propTypes = {
  autoFocus: PropTypes.bool,
  contentTypeTargetPlaceholder: PropTypes.string,
  didCheckErrors: PropTypes.bool.isRequired,
  dropDownItems: PropTypes.array,
  errors: PropTypes.array,
  header: PropTypes.object,
  input: PropTypes.object,
  isFirstContentType: PropTypes.bool,
  onChange: PropTypes.func.isRequired,
  onClick: PropTypes.func,
  onSubmit: PropTypes.func.isRequired,
  relationType: PropTypes.string,
  tabIndex: PropTypes.string.isRequired,
  value: PropTypes.string,
};

RelationBox.defaultProps = {
  autoFocus: false,
  contentTypeTargetPlaceholder: '',
  dropDownItems: [],
  errors: [],
  header: {},
  input: {},
  isFirstContentType: false,
  onClick: () => {},
  relationType: 'oneToOne',
  value: '',
};

export default RelationBox;


text:
from drf_yasg.inspectors.view import SwaggerAutoSchema
from drf_yasg.openapi import resolve_ref, Schema
from .utils import resolve_lazy_ref
import copy

class ComposableSchema:
    """A composable schema defines a transformation on drf_yasg Operation. These
    schema can then be composed with another composable schema using the composeWith method
    yielding a new composable schema whose transformation is defined as the function composition
    of the transformation of the two source schema.
    """
    def transform_operation(self, operation, resolver):
        """Defines an operation transformation

        Args:
            operation (Operation): the operation to transform
            resolver (Resolver): the schema refs resolver
        """
        pass

    def composeWith(self, schema):
        """Allow two schema to be composed into a new schema.
        Given the caller schema 'self' and another schema 'schema',
        this operation yields a new composable schema whose transform_operation
        if defined as
            transform_operation(op, res) = schema.transform_operation(self.transform_operation(op, res), res)

        Args:
            schema (ComposableSchema): The schema to compose with

        Returns:
            ComposableSchema: the newly composed schema
        """
        op = self.transform_operation

        class _Wrapper(ComposableSchema):
            def transform_operation(self, operation, resolver):
                return schema.transform_operation(op(operation, resolver), resolver)

        return _Wrapper()

    def to_schema(self):
        """Convert the composable schema into a SwaggerAutoSchema that
        can be used with the drf_yasg library code

        Returns:
            SwaggerAutoSchema: the swagger auto schema derived from the composable schema
        """
        op = self.transform_operation

        class _Schema(SwaggerAutoSchema):
            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)

            def get_operation(self, operation_keys):
                operation = super().get_operation(operation_keys)
                return op(operation, self.components)

        return _Schema

class IdentitySchema(ComposableSchema):
    def transform_operation(self, operation, resolver):
        return operation

class ExtraParameters(ComposableSchema):
    """Define a schema that can add parameters to the operation
    """
    def __init__(self, operation_name, extra_parameters, *args, **kwargs):
        """Initialize the schema

        Args:
            operation_name (string): the name of the operation to transform
            extra_parameters (list[Parameter]): list of openapi parameters to add
        """
        super().__init__(*args, **kwargs)
        self._extra_parameters = extra_parameters
        self._operation_name = operation_name

    def transform_operation(self, operation, resolver):
        operation_id = operation["operationId"]
        if not operation_id.endswith(self._operation_name):
            return operation

        for param in self._extra_parameters:
            operation["parameters"].append(resolve_lazy_ref(param, resolver))
        return operation

class ExtraResponseField(ComposableSchema):
    """Define a schema that can add fields to the responses of the operation
    """
    def __init__(self, operation_name, extra_fields, *args, **kwargs):
        """Initialize the schema

        Args:
            operation_name (string): the name of the operation to transform
            extra_fields (dict()): description of the fields to add to the responses. The format is
            {
                parameters: list[openapi.Parameter](params1, params2, ...),
                responses: {
                    code1: {
                        field1: openapi.Schema,
                        field2: openapi.Schema,
                        ...
                    },
                    code2: ...
                }
            }
        """
        super().__init__(*args, **kwargs)
        self._extra_fields = extra_fields
        self._operation_name = operation_name

    def transform_operation(self, operation, resolver):
        operation_id = operation["operationId"]
        if not operation_id.endswith(self._operation_name):
            return operation

        responses = operation["responses"]
        for code, params in self._extra_fields.items():
            if code in responses:
                original_schema = responses[code]["schema"]
                schema = original_schema if type(original_schema) is Schema else resolve_ref(original_schema, resolver)
                schema = copy.deepcopy(schema)

                for name, param in params.items():
                    schema["properties"][name] = resolve_lazy_ref(param, resolver)
                responses[code]["schema"] = schema
        return operation


text:
package com.sun.tools.txw2.model.prop;

/**
 * Immutable object that captures the characterstic
 * of the generated writer method.
 *
 * <p>
 * Instances of this class implement {@link #equals(Object)}
 * and {@link #hashCode()}. By using these we avoid generating
 * the same method twice.
 *
 * @author Kohsuke Kawaguchi
 */
public abstract class Prop {
    /**
     * Default constructor.
     */
    protected Prop() {
    }
}


text:
module Vimeo
  module Simple

    class Album < Vimeo::Simple::Base
      # Returns a list of an album's videos.
      #
      # @param [String] album_id The album's id.
      def self.videos(album_id)
        get("/album/#{album_id}/videos.json")
      end

      # Returns an album's metadata.
      #
      # @param [String] album_id The album's id.
      def self.info(album_id)
        get("/album/#{album_id}/info.json")
      end
    end

  end # Simple
end # Vimeo


text:
<?php
/**
 * Created by PhpStorm.
 * User: daniel
 * Date: 31.08.14
 * Time: 17:29
 */

namespace Cundd\PersistentObjectStore\DataAccess;

interface QueryConstants {
	/*
     * The query types
     */
	const SELECT = 'select';
	const DELETE = 'delete';
	const UPDATE = 'update';
	const INSERT = 'insert';
}


text:
var baseRepeat = require('./_baseRepeat'),
    toInteger = require('./toInteger'),
    toString = require('./toString');

/**
 * Repeats the given string `n` times.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category String
 * @param {string} [string=''] The string to repeat.
 * @param {number} [n=0] The number of times to repeat the string.
 * @returns {string} Returns the repeated string.
 * @example
 *
 * _.repeat('*', 3);
 * // => '***'
 *
 * _.repeat('abc', 2);
 * // => 'abcabc'
 *
 * _.repeat('abc', 0);
 * // => ''
 */
function repeat(string, n) {
  return baseRepeat(toString(string), toInteger(n));
}

module.exports = repeat;


text:
"""
MODULE:    carookee

AUTHOR(S): Holger Mueller <zarath@gmx.de>

PURPOSE:   Script to dump the textual content of a carookee forum

COPYRIGHT: (C) 2013 Holger Mueller

           This Program is free software under the Apache
           License Version 2.0.
"""
from requests import Session
import lxml.html
import re

def _get_pagecount(html):
    """look if there is more then on page of topics or posts"""
    nums = 0
    base = ""
    for ele in html.iter('a'):
        href = ele.get('href', '')
        if href.endswith('#bot'):
            base, nums = href[:-4].split('?p=')
            base += "?p="
            break
    return base, int(nums)

def get_topics(html):
    return [(e.get('href'), e.text)
            for e in html.iter('a')
            if e.get('class', '') == 'topictitle']

class Carookee(Session):
    """requests Session class extended by login and dump
       methods for carookee's forum website"""

    DOMAIN = "http://www.carookee.net"

    RXP_DATE = re.compile(r'''
        ^[^:]+:\s+
        ([0-3][0-9]\.[01][0-9]\.\d{2},\s+[0-2][0-9]:[0-5][0-9])
        \s+[^:]+:\s+(\S.*)
        ''', re.X | re.U)

    def __init__(self, forum, *args, **kwargs):
        Session.__init__(self, *args, **kwargs)
        self.forum = forum

    def get_html(self, url):
        """get the url and parse it with lxml.html
           returns: lxml.html Elementtree"""
        res = self.get(url)
        html = lxml.html.fromstring(res.content)
        html.make_links_absolute(self.DOMAIN)
        return html

    def login(self, username, password):
        html = self.get_html("%s/forum/%s/login" % (self.DOMAIN, self.forum))
        vals = {}
        for elem in html.iter('input'):
            vals[elem.name] = elem.value
        vals['username'] = username
        vals['password'] = password
        action = html.forms[0].action
        res = self.post(action, vals)
        return res.ok

    def list_subforums(self):
        html = self.get_html("%s/forum/%s" % (self.DOMAIN, self.forum))
        subf = []
        for elem in html.iter('a'):
            if elem.get('class', '') == 'forumlink':
                subf.append((elem.get('href'), elem.text))
        return subf

    def list_topics(self, sflink):

        html = self.get_html(sflink)
        topics = []
        topics.extend(get_topics(html))

        # look for more then on page of topics
        base, nums = _get_pagecount(html)
        for i in range(2, nums + 1):
            html = self.get_html("%s%i" % (base, i))
            topics.extend(get_topics(html))
        return topics

    def get_topic(self, tplink):
        html = self.get_html(tplink)
        pages = []
        posts = []
        pages.append(html)

        base, nums = _get_pagecount(html)
        for i in range(2, nums + 1):
            pages.append(self.get_html("%s%i" % (base, i)))

        for page in pages:
            # find table with the content
            for row in page.findall(".//table[@class='forumline']./tr"):
                try:
                    author = row.find(".//span[@class='name']").text_content()
                except:
                    author = ""

                try:
                    detail = row.find(".//span[@class='postdetails'][1]"
                                      ).text_content()
                    date, subject = self.RXP_DATE.search(detail).groups()

                except:
                    date = ""
                    subject = ""

                try:
                    content = row.find(".//span[@class='postbody']"
                                       ).text_content()
                except:
                    content = ""

                if content:
                    posts.append(
                        {
                            'author': author,
                            'date': date,
                            'subject': subject,
                            'content': content,
                        })
        return posts

if __name__ == '__main__':
    import sys
    import json

    forum, username, password = sys.argv[1:]

    c = Carookee(forum)
    c.login(username, password)

    sforums = c.list_subforums()

    print "["

    for link, fname in sforums:
        topics = c.list_topics(link)
        for link, tname in topics:
            t = c.get_topic(link)
            json.dump(
                {
                    'Forum': fname,
                    'Topic': tname,
                    'Thread': t,
                }, sys.stdout, indent=4)
            print ","
    print "{}]"


text:
USER=${MONGODB_USER:-"admin"}
DATABASE=${MONGODB_DATABASE:-"nors_devices"}
PASS=${MONGODB_PASS:-"admin"}
#PASS=${MONGODB_PASS:-$(pwgen -s 12 1)}
_word=$( [ ${MONGODB_PASS} ] && echo "preset" || echo "random" )

RET=1
while [[ RET -ne 0 ]]; do
    echo "=> Waiting for confirmation of MongoDB service startup"
    sleep 5
    mongo admin --eval "help" >/dev/null 2>&1
    RET=$?
done

echo "=> Creating an ${USER} user with a ${_word} password in MongoDB"
mongo admin --eval "db.createUser({user: '$USER', pwd: '$PASS', roles:[{role:'userAdminAnyDatabase',db:'admin'}]});"

if [ "$DATABASE" != "admin" ]; then
    echo "=> Creating an ${USER} user with a ${_word} password in MongoDB"
    mongo admin -u $USER -p $PASS << EOF
use $DATABASE
db.createUser({user: '$USER', pwd: '$PASS', roles:[{role:'dbOwner',db:'$DATABASE'}]})
EOF
fi

echo "=> Done!"
touch /data/db/.mongodb_password_set

echo "========================================================================"
echo "You can now connect to this MongoDB server using:"
echo ""
echo "    mongo $DATABASE -u $USER -p $PASS --host <host> --port <port>"
echo ""
echo "Please remember to change the above password as soon as possible!"
echo "========================================================================"


text:
<?php

// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');

// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
	'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
	'name'=>'My Web Application',

	// preloading 'log' component
	'preload'=>array('log', 'kint'),

	// autoloading model and component classes
	'import'=>array(
		'application.models.*',
		'application.components.*',
		'application.modules.*',
	),

	'modules'=>array(
		// uncomment the following to enable the Gii tool

		'gii'=>array(
			'class'=>'system.gii.GiiModule',
			'password'=>'brandon',
		 	// If removed, Gii defaults to localhost only. Edit carefully to taste.
			'ipFilters'=>array('127.0.0.1','::1'),
		),
		// Yii User Management - Possible Config
		/* 'user' => array(
			'debug' => false,
			'usersTable' => 'user',
			'translationTable' => 'translation',
		),
		'usergroup' => array(
			'usergroupTable' => 'user_group',
			'usergroupMessagesTable' => 'user_group_message',
		),
		'membership' => array(
			'membershipTable' => 'membership',
			'paymentTable' => 'payment',
		),
		'friendship' => array(
			'friendshipTable' => 'friendship',
		),
		'profile' => array(
			'privacySettingTable' => 'privacy_setting',
			'profileFieldsGroupTable' => 'profile_field_group',
			'profileFieldsTable' => 'profile_field',
			'profileTable' => 'profile',
			'profileCommentTable' => 'profile_comment',
			'profileVisitTable' => 'profile_visit',
		),
		'role' => array(
			'rolesTable' => 'role',
			'userHasRoleTable' => 'user_role',
			'actionTable' => 'action',
			'permissionTable' => 'permission',
		),
		'messages' => array(
			'messagesTable' => 'message',
		), */

	),

	// application components
	'components'=>array(
		'user'=>array(
			// enable cookie-based authentication
			'allowAutoLogin'=>true, // overwrite default usser module
			// 'class' => 'application.modules.user.components.YumWebUser',
			// 'allowAutoLogin'=>true,
			// 'loginUrl' => array('//user/user/login'),
		),
		'kint' => array(
			'class' => 'ext.Kint.Kint',
		),
		// uncomment the following to enable URLs in path-format
		/*
		'urlManager'=>array(
			'urlFormat'=>'path',
			'rules'=>array(
				'<controller:\w+>/<id:\d+>'=>'<controller>/view',
				'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
				'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
			),
		),
		*/
		/* 'db'=>array(
			'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
		), */
		// uncomment the following to use a MySQL database

		'db'=>array(
			'connectionString' => 'mysql:host=techsailor.com;dbname=brandonplayground',
			'emulatePrepare' => true,
			'username' => 'brandon1986',
			'password' => 'playground!123',
			'charset' => 'utf8',
			'tablePrefix' => '',
		),

		'errorHandler'=>array(
			// use 'site/error' action to display errors
            'errorAction'=>'site/error',
        ),
		'log'=>array(
			'class'=>'CLogRouter',
			'routes'=>array(
				array(
					'class'=>'CFileLogRoute',
					'levels'=>'error, warning',
				),
				array(
					'class'=>'ext.yii-debug-toolbar.YiiDebugToolbarRoute',
					'ipFilters'=>array('127.0.0.1','192.168.1.215'),
				),
				// uncomment the following to show log messages on web pages
				/*
				array(
					'class'=>'CWebLogRoute',
				),
				*/
			),
		),
	),

	// application-level parameters that can be accessed
	// using Yii::app()->params['paramName']
	'params'=>array(
		// this is used in contact page
		'adminEmail'=>'webmaster@example.com',
	),
);


text:
import argparse
from sys import float_info
from math import ceil
import numpy as np
from numpy.fft import fft, ifft
from scipy.io import wavfile
import matplotlib.pyplot as plt

def stretch(x, alpha, window, num_channels, synthesis_hop_factor):
    """
    Perform time stretch of a factor alpha to signal x
    x: input signal, alpha: time-stretch factor,
    num_channels: ?, synthesis_hop_factor: ?,
    returns: ?
    """

    synthesis_hop_size = ceil(num_channels / synthesis_hop_factor)
    analysis_hop_size = ceil(synthesis_hop_size / alpha)

    # TODO: Should be able to completely reconstruct input signal if alpha == 1
    x = np.pad(x, (synthesis_hop_size,))
    y = np.zeros(max(x.size, ceil(x.size * alpha + x.size / analysis_hop_size * alpha)))

    ys_old = float_info.epsilon
    analysis_hop = synthesis_hop = 0

    while analysis_hop <= x.size - (synthesis_hop_size + num_channels):
        # Spectra of two consecutive windows
        xs = fft(window * x[analysis_hop:analysis_hop + num_channels])
        xt = fft(window * x[analysis_hop + synthesis_hop_size:analysis_hop + synthesis_hop_size + num_channels])

        # IFFT and overlap and add
        ys = xt * (ys_old / xs) / abs(ys_old / xs)
        ys_old = ys

        y_cur = y[synthesis_hop:synthesis_hop + num_channels]
        y_cur = np.add(y_cur, window * np.real_if_close(ifft(ys)), out=y_cur, casting='unsafe')

        analysis_hop += analysis_hop_size
        synthesis_hop += synthesis_hop_size

    # TODO: AM scaling due to window sliding
    return y[synthesis_hop_size: ceil(x.size * alpha)]

def sin_signal(fs, duration, f0):
    """
    Generate a sinusoidal signal
    fs: sample frequency, duration: signal duration, f0: frequency
    returns: sinusoid of frequency f0 and length duration*fs
    """
    return np.sin(2 * np.pi * f0 * np.linspace(0, duration, int(duration * fs), endpoint=False))

def normalize(x):
    """
        Normalize signal from (min(x), max(x)) to (-1, 1)
        see: https://github.com/WeAreROLI/JUCE/blob/master/modules/juce_core/maths/juce_MathsFunctions.h#L127
    """
    return -1 + 2 * (x - x.min()) / x.ptp()

if __name__ == '__main__':
    windows = {'bartlett': np.bartlett, 'blackman': np.blackman, 'hamming': np.hamming, 'hanning': np.hanning,
               'kaiser': np.kaiser}

    parser = argparse.ArgumentParser(description='Phase Vocoder')
    parser.add_argument('--input_filename', type=str, help='Input filename')

    parser.add_argument('--test_duration', type=float, default=1.0, help='Test sin duration')
    parser.add_argument('--test_frequency', type=float, default=440.0, help='Test sin frequency')
    parser.add_argument('--test_sampling_frequency', type=int, default=44100, help='Test sin sampling frequency')

    parser.add_argument('--stretch_factor', type=float, default=2, help='Stretch factor')
    parser.add_argument('--num_channels', type=int, default=1024, help='Number of FFT channels')
    parser.add_argument('--synthesis_hop_factor', type=float, default=4, help='Synthesis hop factor')
    parser.add_argument('--window', choices=windows.keys(), default='hanning', help='Window function')
    parser.add_argument('--window_size', type=int, default=1024, help='Window size')

    parser.add_argument('--generate_figures', action='store_true', help='Should generate figures')

    parser.add_argument('--output_filename', type=str, default='output.wav', help='Output filename')

    args = parser.parse_args()

    (sampling_frequency, input_data), _ = wavfile.read(
        args.input_filename) if args.input_filename else args.test_sampling_frequency, sin_signal(
        args.test_sampling_frequency, args.test_duration, args.test_frequency)

    input_data = normalize(input_data)

    symmetric_window = windows[args.window](args.window_size) + [0]  # symmetric about (size - 1) / 2
    output_data = stretch(input_data,
                          args.stretch_factor,
                          symmetric_window,
                          args.num_channels,
                          args.synthesis_hop_factor)

    output_data = normalize(output_data)
    wavfile.write(args.output_filename, int(sampling_frequency), output_data)

    if args.generate_figures:
        plt.subplot(2, 1, 1)
        plt.plot(np.arange(input_data.size) / sampling_frequency, input_data)
        plt.title('Input')
        plt.xlabel('Time (s)')
        plt.ylabel('Amplitude')

        plt.subplot(2, 1, 2)
        plt.plot(np.arange(output_data.size) / sampling_frequency, output_data)
        plt.title('Output')
        plt.xlabel('Time (s)')
        plt.ylabel('Amplitude')
        plt.show()


text:
module Merb
  module GlobalHelpers
    def account_and_logout_button
      <<-BUTTON

        <form method="post" action="#{url(:logout)}">
          Logged in as #{@user.name} |
          <input type="hidden" value="delete" name="_method"/>
          <input type="hidden" value="#{request.path}" name="destination"/>
          <button type="submit">Logout</button>
        </form>

      BUTTON
      # <<-BUTTON
      #

      #   <form method="post" action="#{url(:logout)}">
      #     Logged in as #{link_to(@user.name, url(:user, @user.id))} |
      #     <input type="hidden" value="delete" name="_method"/>
      #     <button type="submit">Logout</button>
      #   </form>
      #

      # BUTTON
    end

    def login_or_name
      @user.name == 'Anonymous' ? "Anonymous (#{link_to_login})" : @user.name
    end

    def highlighted_link_to(title, url)
      opts = {}
      opts.merge!(:id => 'active') if @page_title && @page_title == title
      link_to(title, url, opts)
    end

    def link_to_login
      link_to 'Login', url(:new_session, :destination => request.path), :id => 'login'
    end

    def link_to_login_or_account
      if @user.name == 'Anonymous'
        link_to_login
      else
        account_and_logout_button
      end
    end

    def title(options)
      if(options.is_a?(Hash))
        merged_title = @site_title = options[:site].dup
        (merged_title << " | #{@page_title}") if @page_title
        return merged_title
      else
        @page_title = options
        return @page_title
      end
    end
  end
end


text:
define([ 'libs/angular', './module', 'templates' ],
function(angular, module, templates) {
    'use strict';

    module
    .directive('appAddOfferComment', function($rootScope, $timeout) {
        return {
            template: templates.addOfferComment,
            replace: true,
            restrict: 'E',
            scope: {
                commentHandler: '&onComment',
                responseHandler: '&onResponse',
                commentParent: '=',
                showOwnerFeatures: '&',
                author: '=',
                className: '@class'
            },
            link: function($scope, $element) {
                $scope.goTo = $rootScope.goTo;
                $scope.i18n = $rootScope.i18n;

                angular.extend($scope, {
                    activeMode: false,
                    inputPlaceholder: {
                        text: ''
                    },
                    comment: {
                        content: ''
                    },
                    activate: function(mode) {
                        $scope.activeMode = mode;

                        if(mode === 'response') {
                            $scope.inputPlaceholder.text = $scope.i18n.offer.response.inputPlaceholder;
                        }

                        $timeout(function() { // after rendering
                            $scope.$broadcast('appFixed.recalculate');
                        }, 0);
                    },
                    deactivate: function() {
                        $scope.activeMode = null;

                        $scope.inputPlaceholder.text = '';

                        $timeout(function() { // after rendering
                            $scope.$broadcast('appFixed.recalculate');
                        }, 0);
                    },
                    addComment: function(comment) {
                        if($scope.activeMode) {
                            $scope.commentHandler({
                                comment: comment
                            });

                            $scope.deactivate();
                        } else {
                            $scope.activate('comment');
                        }
                    },
                    addResponse: function() {
                        if($scope.activeMode) {
                            $scope.responseHandler({
                                comment: $scope.comment
                            });

                            $scope.deactivate();
                        } else {
                            $scope.activate('response');
                        }
                    },
                    cancel: function() {
                        $scope.deactivate();
                    }
                });

                $scope.$on('appAddOfferComment.activate', function(e, mode) {
                    $scope.activate(mode);
                });
            }
        };
    });

});


text:
var fs = require('fs')
var util = require('./util.js')
var path = require('path')

var root = path.resolve(__dirname, '../')

var log = function (str, type) {
    str = `${util.format(new Date())} : [${type ? type : 'N/A'}] ${str}\r\n`

    var filePath = path.resolve(root, './log.md')

    var fd = fs.openSync(filePath, 'a', 0o777)
    fs.writeSync(fd, str, undefined, "utf8")
    fs.closeSync(fd)
    console.log(str)
}

module.exports = log


text:
using System;
using System.Collections.Generic;
using Goedel.Utilities;
using Goedel.Persistence;
using Goedel.Cryptography.Dare;
using Goedel.IO;

namespace Test.Goedel.Mesh {

    /// <summary>
    ///
    /// </summary>
    public partial class TestItem {

        /// <summary>
        /// Primary key to use for the object. Note that a primary key MUST be unique.
        /// </summary>
        public override string _PrimaryKey => AccountID;

        public const string KeyUserProfileUDF = "UserProfileUDF";
        readonly static List<string> Keys = new List<string> { KeyUserProfileUDF };

        /// <summary>
        /// Secondary keys describing the object
        /// </summary>
        public override List<string> _Keys => Keys;

        /// <summary>
        /// Secondary key/values pairs describing the object
        /// </summary>
        public override List<KeyValuePair<string, string>> _KeyValues =>
            new List<KeyValuePair<string, string>>() {
                new KeyValuePair<string, string> (KeyUserProfileUDF, UserProfileUDF)
                };

        /// <summary>
        /// Container header corresponding to persistence store entry
        /// </summary>
        public ContainerHeader ContainerHeader {
            get => _Metadata as ContainerHeader; set => _Metadata = value; }
        }

    public class TestItemContainerPersistenceStore : ContainerPersistenceStore {

        IPersistenceIndex IndexKeyUserProfileUDF;

        /// <summary>
        /// Open or create a persistence store in specified mode with
        /// the specified file name, content type and optional comment.
        /// </summary>
        /// <param name="FileName">Log file.</param>
        /// <param name="ReadOnly">If true, persistence store must exist
        /// and will be opened in read-only mode. If false, persistence store
        /// is opened in read/write mode and a new store will be created
        /// if none exists.</param>
        /// <param name="Type">Type of data to store (the schema name).</param>
        /// <param name="Comment">Comment to be written to the log.</param>
        /// <param name="ContainerType">The Container type.</param>
        /// <param name="FileStatus">The file status in which to open the container.</param>
        public TestItemContainerPersistenceStore (string FileName, string Type = null,
                    string Comment = null, bool ReadOnly = false,
                    FileStatus FileStatus = FileStatus.OpenOrCreate,
                    ContainerType ContainerType = ContainerType.Chain) : base(
                        FileName, Type, Comment, ReadOnly, FileStatus, ContainerType) {
            IndexKeyUserProfileUDF = GetIndex(TestItem.KeyUserProfileUDF);
            }

        TestItem Get (IPersistenceEntry DataItem) {

            return TestItem.FromJSON(DataItem.JSONReader, true);

            }

        /// <summary>
        /// Get the latest value of the TestItem object with the specified unique ID
        /// </summary>
        /// <param name="AccountID">The account identifier</param>
        /// <returns>The test item if found, otherwise null.</returns>
        public TestItem GetAccountID (string AccountID) {
            var Entry = Get(AccountID);
            return Entry != null ? Get(Entry) : null;
            }

        /// <summary>
        /// Get the latest value of the last TestItem object with the specified unique ID that was created.
        /// </summary>
        /// <param name="UserProfileUDF">The user profile UDF</param>
        /// <returns>The test item</returns>
        public TestItem GetUserProfileUDF (string UserProfileUDF) {
            var IndexEntry = IndexKeyUserProfileUDF.Last(UserProfileUDF);
            var DataItem = IndexEntry.Data;
            return Get(DataItem);
            }

        /// <summary>
        /// Get the previous value(s) of a test item version.
        /// </summary>
        /// <param name="TestItem">The base version</param>
        /// <param name="MaxResult">Maximum number of results to return.</param>
        /// <param name="OnOrAfter">Only return versions that are on or after the specified value.</param>
        /// <returns>The list of previous versions.</returns>
        public List<TestItem> GetPrevious (TestItem TestItem, int MaxResult, DateTime OnOrAfter) {
            throw new NYI();
            }

        public TestItem GetRecord (int Record) {
            // read the header and data from container

            //

            throw new NYI();
            }

        }

    }


text:
package all

import _ "github.com/influxdata/telegraf/plugins/outputs/timestream" // register plugin


text:
/*
 * $Id$
 */
package com.mycompany.allinone.api;

import java.util.Properties;

import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.collections.MissingRequiredPropertyException;
import org.xins.common.collections.InvalidPropertyValueException;
import org.xins.common.collections.PropertyReader;
import org.xins.common.manageable.InitializationException;
import org.xins.common.manageable.Manageable;

/**
 * Common object used by the API to shared properties.
 *
 * @version $Revision$ $Date$
 * @author Anthony Goubard
 */
public class SharedInstance extends Manageable {

   /**
    * Constructs a new SharedInstance instance.
    *
    * @param api
    *    the API to which this function belongs, guaranteed to be not
    *    null.
    */
   public SharedInstance(APIImpl api) {
   }

   /**
    * The collection used to store the properties.
    */
   private Properties _sharedProperties;

   protected void initImpl(PropertyReader properties)
   throws MissingRequiredPropertyException,
          InvalidPropertyValueException,
          InitializationException {
      _sharedProperties = new Properties();
   }

   /**
    * Stores a property for the API.
    *
    * @param key
    *    the key of the property, cannot be null.
    * @param value
    *    the value of the property, cannot be null.
    *
    * @throws IllegalArgumentException
    *    if (key == null || value == null).
    */
   public final void put(String key, String value) {

      // Check preconditions
      MandatoryArgumentChecker.check("key", key, "value", value);

      _sharedProperties.put(key, value);
   }

   /**
    * Gets a property from the API.
    *
    * @return
    *    returns the value of the property or null if the value was
    *    not stored.
    */
   public final String get(String key) {
      return _sharedProperties.getProperty(key);
   }
}


text:
@interface RKResourceFileMapParserTests : XCTestCase
@end

@implementation RKResourceFileMapParserTests {
    __strong NSFileHandle *validMapFileHandle;
    __strong NSFileHandle *compressedMapFileHandle;
    __strong RKResourceFileParserPOD *pod;
}

- (void)setUp
{
    [super setUp];
    NSString *validMapPath = [[NSBundle bundleForClass:self.class] pathForResource:@"RsrcMapMetaData" ofType:@"hex"];
    validMapFileHandle = [NSFileHandle fileHandleForReadingAtPath:validMapPath];

    NSString *compressedPath = [[NSBundle bundleForClass:self.class] pathForResource:@"RsrcMapCompressedFlag" ofType:@"hex"];
    compressedMapFileHandle = [NSFileHandle fileHandleForReadingAtPath:compressedPath];

    pod = RKResourceFileParserPOD.new;
    pod.dataOffset = 0xA0;
    pod.mapOffset = 0x100;
    pod.dataSize = 0xFF;
    pod.mapSize = 0xEE;
}

- (void)tearDown
{
    [validMapFileHandle closeFile];
    [compressedMapFileHandle closeFile];
    validMapFileHandle = nil;
    compressedMapFileHandle = nil;
    pod = nil;
    [super tearDown];
}

- (void)testParser_correctlyReadsResourceMapMetaData_setsPODValuesAsExpected
{
    XCTAssertTrue([RKResourceFileMapParser parseData:validMapFileHandle againstObject:pod]);

    XCTAssertEqual(pod.mainFlags, 0);
    XCTAssertEqual(pod.typeListOffset, 0xAABB);
    XCTAssertEqual(pod.nameListOffset, 0xDDEE);
}

- (void)testParser_failsWhenPreambleVerificationFails
{
    pod.dataOffset = 0x00;
    XCTAssertFalse([RKResourceFileMapParser parseData:validMapFileHandle againstObject:pod]);
}

- (void)testParser_failsWhenDataProvidedWithCompressedFlag
{
    XCTAssertFalse([RKResourceFileMapParser parseData:compressedMapFileHandle againstObject:pod]);
}

- (void)testParser_failsWhenNoDataProvided
{
    XCTAssertFalse([RKResourceFileMapParser parseData:nil againstObject:RKResourceFileParserPOD.new]);
}

- (void)testParser_failsWhenNoPODProvided
{
    XCTAssertFalse([RKResourceFileMapParser parseData:validMapFileHandle againstObject:nil]);
}

@end


text:
using System;
using System.Runtime.Serialization;

namespace ClashClient.Clans {
    /// <summary>
    /// Enumeration that contains the options for membership in a clan.
    /// </summary>
    [Serializable]
    public enum MembershipType : int {
        /// <summary>
        /// Default option
        /// </summary>
        [EnumMember(Value = "unknown")]
        Unknown = 0,

        /// <summary>
        /// Anyone can join the clan at any time.
        /// </summary>
        [EnumMember(Value = "open")]
        Open = 1,

        /// <summary>
        /// Only invited users can join.
        /// </summary>
        [EnumMember(Value = "inviteOnly")]
        InviteOnly = 2,

        /// <summary>
        /// Clan is currently not accepting new membership.
        /// </summary>
        [EnumMember(Value = "closed")]
        Closed = 3
    } // end enumeration MembershipType
} // end namespace


text:
title: "What is proxy design pattern and how to use it in PHP?"
read_time: "1 min"
updated: "Mar 04, 2015"
group: "articles"
permalink: "/faq/object-oriented-programming/design-patterns/proxy/"
---

## Intent

Provide a surrogate or placeholder for another object to control access to it.
Use an extra level of indirection to support distributed, controlled, or intelligent access.
Add a wrapper and delegation to protect the real component from undue complexity.

## Problem

You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client.

## Discussion

Design a surrogate, or proxy, object that: instantiates the real object the first time the client makes a request of the proxy, remembers the identity of this real object, and forwards the instigating request to this real object. Then all subsequent requests are simply forwarded directly to the encapsulated real object.

There are four common situations in which the Proxy pattern is applicable.

A virtual proxy is a placeholder for "expensive to create" objects. The real object is only created when a client first requests/accesses the object.
A remote proxy provides a local representative for an object that resides in a different address space. This is what the "stub" code in RPC and CORBA provides.
A protective proxy controls access to a sensitive master object. The "surrogate" object checks that the caller has the access permissions required prior to forwarding the request.
A smart proxy interposes additional actions when an object is accessed. Typical uses include:
Counting the number of references to the real object so that it can be freed automatically when there are no more references (aka smart pointer),
Loading a persistent object into memory when it's first referenced,
Checking that the real object is locked before it is accessed to ensure that no other object can change it.

## Structure

By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.

Example

The Proxy provides a surrogate or place holder to provide access to an object. A check or bank draft is a proxy for funds in an account. A check can be used in place of cash for making purchases and ultimately controls access to cash in the issuer's account.

## Check list

1. Identify the leverage or "aspect" that is best implemented as a wrapper or surrogate.
2. Define an interface that will make the proxy and the original component interchangeable.
3. Consider defining a Factory that can encapsulate the decision of whether a proxy or original object is desirable.
4. The wrapper class holds a pointer to the real class and implements the interface.
5. The pointer may be initialized at construction, or on first use.
6. Each wrapper method contributes its leverage, and delegates to the wrappee object.

## Rules of thumb

* Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface.
* Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests.

## Code

In the proxy pattern one class stands in for and handles all access to another class.

This can be because the real subject is in a different location (server, platform, etc), the real subject is cpu or memory intensive to create and is only created if necessary, or to control access to the real subject. A proxy can also be used to add additional access functionality, such as recording the number of times the real subject is actually called.

In this example, the ProxyBookList is created in place of the more resource intensive BookList. ProxyBookList will only instantiate BookList the first time a method in BookList is called.

```php
<?php

class ProxyBookList {
    private $bookList = NULL;
    //bookList is not instantiated at construct time
    function __construct() {
    }
    function getBookCount() {
        if (NULL == $this->bookList) {
            $this->makeBookList();
        }
        return $this->bookList->getBookCount();
    }
    function addBook($book) {
        if (NULL == $this->bookList) {
            $this->makeBookList();
        }
        return $this->bookList->addBook($book);
    }
    function getBook($bookNum) {
        if (NULL == $this->bookList) {
            $this->makeBookList();
        }
        return $this->bookList->getBook($bookNum);
    }
    function removeBook($book) {
        if (NULL == $this->bookList) {
            $this->makeBookList();
        }
        return $this->bookList->removeBook($book);
    }
    //Create
    function makeBookList() {
        $this->bookList = new bookList();
    }
}

class BookList {
    private $books = array();
    private $bookCount = 0;
    public function __construct() {
    }
    public function getBookCount() {
        return $this->bookCount;
    }
    private function setBookCount($newCount) {
        $this->bookCount = $newCount;
    }
    public function getBook($bookNumberToGet) {
        if ( (is_numeric($bookNumberToGet)) && ($bookNumberToGet <= $this->getBookCount())) {
            return $this->books[$bookNumberToGet];
        } else {
           return NULL;
        }
    }
    public function addBook(Book $book_in) {
        $this->setBookCount($this->getBookCount() + 1);
        $this->books[$this->getBookCount()] = $book_in;
        return $this->getBookCount();
    }
    public function removeBook(Book $book_in) {
        $counter = 0;
        while (++$counter <= $this->getBookCount()) {
          if ($book_in->getAuthorAndTitle() == $this->books[$counter]->getAuthorAndTitle()) {
            for ($x = $counter; $x < $this->getBookCount(); $x++) {
              $this->books[$x] = $this->books[$x + 1];
          }
          $this->setBookCount($this->getBookCount() - 1);
        }
      }
      return $this->getBookCount();
    }
}

class Book {
    private $author;
    private $title;
    function __construct($title_in, $author_in) {
      $this->author = $author_in;
      $this->title  = $title_in;
    }
    function getAuthor() {
        return $this->author;
    }
    function getTitle() {
        return $this->title;
    }
    function getAuthorAndTitle() {
      return $this->getTitle().' by '.$this->getAuthor();
    }
}

  writeln( 'BEGIN TESTING PROXY PATTERN';
  writeln('');

  $proxyBookList = new ProxyBookList();
  $inBook = new Book('PHP for Cats','Aaryadev');
  $proxyBookList->addBook($inBook);

  writeln('test 1 - show the book count after a book is added');
  writeln($proxyBookList->getBookCount());
  writeln('');

  writeln('test 2 - show the book');
  $outBook = $proxyBookList->getBook(1);
  writeln($outBook->getAuthorAndTitle());
  writeln('');

  $proxyBookList->removeBook($outBook);

  writeln('test 3 - show the book count after a book is removed');
  writeln($proxyBookList->getBookCount());
  writeln('');

  writeln('END TESTING PROXY PATTERN');

  function writeln($line_in) {
    echo $line_in."<br/>";
  }
```

## Output

```

BEGIN TESTING PROXY PATTERN

test 1 - show the book count after a book is added
1

test 2 - show the book
PHP for Cats by Aaryadev

test 3 - show the book count after a book is removed
0

END TESTING PROXY PATTERN
```


text:
	local MemoryAddress	= {}

	local memoryFunctions	= {
		byte	= {
			unsigned	= {
				read		= memory.readbyte,
				write		= memory.writebyte,
				},
			signed		= {
				read		= memory.readbytesigned,
				write		= memory.writebytesigned,
				},
			},

		word	= {
			unsigned	= {
				read		= memory.readword,
				write		= memory.writeword,
				},
			signed		= {
				read		= memory.readwordsigned,
				write		= memory.writewordsigned,
				},
			},

		dword	= {
			unsigned	= {
				read		= memory.readdword,
				write		= memory.writedword,
				},
			signed		= {
				read		= memory.readdwordsigned,
				write		= memory.writedwordsigned,
				},
			}
		}

	function MemoryAddress.new(address, _type, _signed)
		local type		= _type and _type or 'byte'
		local signed	= _signed and "signed" or "unsigned"

		local ret	= {
			readfunc	= memoryFunctions[type][signed].read,
			writefunc	= memoryFunctions[type][signed].write,
			address		= address,
			}

		return setmetatable(ret, MemoryAddress)

	end

	function MemoryAddress:read()
		return self.readfunc(self.address)
	end

	function MemoryAddress:write(value)
		--print(string.format("Write %08x = %x", self.address, value))
		return self.writefunc(self.address, value)
	end

	MemoryAddress.__index	= MemoryAddress

	MemoryAddress	= setmetatable(MemoryAddress, {
						__call	= function(_, ...) return MemoryAddress.new(...) end,
						__index	= MemoryAddress
					}
				)

	return MemoryAddress


text:
package com.twu.biblioteca;

import com.twu.biblioteca.libresources.LibraryBook;
import com.twu.biblioteca.libresources.LibraryMovie;
import com.twu.biblioteca.libstores.AllLibraryStores;
import com.twu.biblioteca.libstores.LibraryBookStore;
import com.twu.biblioteca.libstores.LibraryMovieStore;
import com.twu.biblioteca.menus.GuestMainMenu;
import com.twu.biblioteca.menus.MainMenu;
import com.twu.biblioteca.menus.UserMainMenu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

public class BibliotecaApp {

    private static final String MESSAGE_WELCOME = "Welcome to Biblioteca!";
    private static final String MESSAGE_EXIT = "Thank you for using Biblioteca!";
    private static final String MESSAGE_SELECT_OPTION = "Select an option: ";
    private static AllLibraryStores libraryStores;
    private static UserAccountManager userAccountManager;
    private static UserAccountVault userAccountVault;

    static {
        ArrayList<LibraryBook> expectedBooks = new ArrayList<LibraryBook>() {{
            add(new LibraryBook("Book 1", "Author 1", 2001));
            add(new LibraryBook("Book 2", "Author 2", 2002));
            add(new LibraryBook("Book 3", "Author 3", 2003));
        }};

        ArrayList<LibraryMovie> expectedMovies = new ArrayList<LibraryMovie>() {{
            add(new LibraryMovie("Name 1", 2001, "Director 1", 1));
            add(new LibraryMovie("Name 2", 2002, "Director 2", 2));
            add(new LibraryMovie("Name 3", 2003, "Director 3", 3));
        }};

        userAccountVault = new UserAccountVault( new HashMap<LoginCredential, User>() {{
            put(new LoginCredential("000-0001", "password1"), new User("user1", "user1@user1.com", "11111111"));
            put(new LoginCredential("000-0002", "password2"), new User("user2", "user2@user2.com", "22222222"));
        }});

        userAccountManager = new UserAccountManager(userAccountVault);

        libraryStores = new AllLibraryStores(new LibraryBookStore(expectedBooks), new LibraryMovieStore(expectedMovies));
    }

    public static void main(String[] args) {
        BibliotecaApp app = new BibliotecaApp();
        app.start();
    }

    private void start() {
        System.out.println(MESSAGE_WELCOME);
        int input;
        String feedback;
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        do {
            MainMenu mainMenu = getMainMenu();
            printMainMenu(mainMenu);
            input = Integer.parseInt(getInput(reader));
            feedback = mainMenu.selectOption(input, userAccountManager, libraryStores);
            printFeedback(feedback);
        }
        while(feedback != null);
    }

    private void printMainMenu(MainMenu mainMenu) {
        System.out.println();
        System.out.println(MainMenuFormatter.format(mainMenu));
        System.out.print(MESSAGE_SELECT_OPTION);
    }

    private String getInput(BufferedReader reader) {
        String input = "";
        try {
            input = reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return input;
    }

    private void printFeedback(String feedback) {
        if(feedback != null)
            System.out.println(feedback);
        else
            System.out.println(MESSAGE_EXIT);
    }

    public MainMenu getMainMenu() {
        if(userAccountManager.getCurrentUser() == null)
            return new GuestMainMenu();
        else
            return new UserMainMenu();
    }
}


text:
package com.intellij.codeInspection;

import com.intellij.JavaTestUtil;
import com.intellij.codeInspection.ex.LocalInspectionToolWrapper;
import com.intellij.codeInspection.javaDoc.JavaDocLocalInspection;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;

public class JavaDocInspectionTest extends LightCodeInsightFixtureTestCase {
  @Override
  protected String getBasePath() {
    return JavaTestUtil.getRelativeJavaTestDataPath() + "/inspection/javaDocInspection";
  }

  public void testPackageInfo() {
    JavaDocLocalInspection inspection = new JavaDocLocalInspection();
    inspection.IGNORE_DEPRECATED = true;
    inspection.setPackageOption("public", "@author");
    myFixture.testInspection("packageInfo", new LocalInspectionToolWrapper(inspection));
  }
}


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

namespace Joy.Server
{
	public class Validator
	{
		public static void CheckNullReference(params object[] pars)
		{
			const string template = "Null reference detected ({0}.{1}:{2})";
			for (int i = 0; i < pars.Length; i++)
			{
				if (pars[i] == null)
				{
					StackTrace trace = new StackTrace();
					StackFrame frame = trace.GetFrame(1);
					MethodBase method = frame.GetMethod();
					throw new ArgumentNullException(string.Format(template, method.DeclaringType.FullName, method.Name, method.GetParameters()[i]));
				}
			}
		}
	}
}


text:
from sys import argv
from cloudscheduler.unit_tests.unit_test_common import load_settings
from web_common import cleanup, set_setup_required

def main():
    for parameter in argv[1:]:
        if parameter == '--set-setup-required' or '-ssr':
            set_setup_required(True)
        elif parameter == '--cleanup' or '-c':
            cleanup(load_settings(web=True))

if __name__ == '__main__':
    main()


text:
<?php

namespace Wellid\Exception;

/**
 * File not Found Exception
 */
class FileNotFound extends NotFound {
    /**
     * Constructor
     *
     * @param string $file Filename
     * @param string $fileType File type
     * @param int $code Error code
     * @param \Exception $previous Previous Exception
     */
    public function __construct($file, $fileType, $code = 0, \Exception $previous = null) {
        parent::__construct('File '.$file.' ['.$fileType.']', basename($file), $code, $previous);
    }
}


text:
// Copyright 2017 Twitter. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.twitter.heron.api.bolt;

import java.util.Map;

import com.twitter.heron.api.topology.BaseComponent;
import com.twitter.heron.api.topology.TopologyContext;

public abstract class BaseBasicBolt extends BaseComponent implements IBasicBolt {

  private static final long serialVersionUID = 6585146860997305058L;

  @Override
  public void prepare(Map<String, Object> heronConf, TopologyContext context) {
  }

  @Override
  public void cleanup() {
  }
}


text:
<!doctype html>
<html lang="en-US" ng-app="application">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <meta name="apple-mobile-web-app-capable" content="yes" />

  <title>Angular JS Project</title>

  <link rel="shortcut icon" href="favicon.ico">
  <link rel="icon" href="favicon.ico">

  <link rel="stylesheet" type="text/css" href="css/style.css?647bbbabd9b373d2">
  <link rel="stylesheet" href="css/font-awesome/css/font-awesome.min.css?fa5ecf5224f554bb">

  <script type="text/javascript" src="js/libs/jquery.min.js?7fcebda81012b5d1"></script>
  <script type="text/javascript" src="js/libs/angular.min.1.2.0.js?9464d9b19db070c0"></script>
  <script type="text/javascript" src="js/libs/angular-route.min.js?abda35557abf2fbc"></script>
  <script type="text/javascript" src="js/libs/angular-resource.min.js?eba396038326df81"></script>
  <script type="text/javascript" src="js/libs/angular-ui.min.js?09b26dc28424046e"></script>
  <script type="text/javascript" src="js/libs/ui-bootstrap-tpls.min.js?267274e4757b4db2"></script>

  <script type="text/javascript" src="js/libs/jquery.transit.min.js?918ecb0cb0e9528d"></script>
  <script type="text/javascript" src="js/libs/moment.min.js?13b09cb6920c869b"></script>
  <script type="text/javascript" src="js/libs/jquery.waitforimages.min.js?f442e56407bd15b0"></script>

  <script type="text/javascript" src="js/libs/angular-retina.min.js?410633ebd801fb7d"></script>
  <script type="text/javascript" src="js/libs/localStorageModule.js?73985b2ab58153bd"></script>
  <script type="text/javascript" src="js/libs/qdecorator.min.js?eb153c736b4c8180"></script>
  <script type="text/javascript" src="js/lc-touch.min.js?4c612df6b083bdbc"></script>

  <script type="text/javascript" src="js/app.min.js?d068d7a32bd9fcdb"></script>
  <script type="text/javascript" src="js/controllers.min.js?3e4dc1c81af2a8b8"></script>
  <script type="text/javascript" src="js/directives.min.js?499094a0c7a6f4aa"></script>
  <script type="text/javascript" src="js/services.min.js?b61288c2a58a93a6"></script>
  <script type="text/javascript" src="js/filters.min.js?88e97abf3caafcf0"></script>

  <script type="text/javascript" src="http://edge.spot411.com/js/lib/webtoolkit.md5.js"></script>

<!--[if lt IE 9]>
  <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.6.2/html5shiv.js"></script>
<![endif]-->
</head>

<body ng-controller="AppCtrl">

	<script>
    /*
document.body.addEventListener('touchmove', function(event) {
      //console.log(event.source);
      //if (event.source == document.body)
        event.preventDefault();
    }, false);
*/

    window.onresize = function() {
      $(document.body).width(window.innerWidth).height(window.innerHeight);
    }

    $(function() {
      window.onresize();
    });
  </script>

	<div ng-view></div>

	<!-- Prompt IE 6 users to install Chrome Frame. Remove this if you want to support IE 6.
		chromium.org/developers/how-tos/chrome-frame-getting-started -->
	<!--[if lt IE 7 ]>
		<script src="//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js"></script>
		<script>window.attachEvent('onload',function(){CFInstall.check({mode:'overlay'})})</script>
	<![endif]-->
</body>
</html>


text:
package soot.jimple.infoflow.collect;

import java.util.AbstractSet;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * An modifiable set holding up to two elements. Particularly useful within flow functions.
 *
 * @param <E>
 * @see FlowFunction
 *
 * @author Eric Bodden
 * @author Steven Arzt
 */
public class MutableTwoElementSet<E> extends AbstractSet<E> {

	protected E first, second;

	public MutableTwoElementSet() {
		this.first = null;
		this.second = null;
	}

	public MutableTwoElementSet(E first, E second) {
		this.first = first;
		this.second = second;
	}

	public boolean add(E item) {
		if (first == null) {
			first = item;
			return true;
		}
		if (first != null && first.equals(item))
			return false;

		if (second == null) {
			second = item;
			return true;
		}
		if (second != null && second.equals(item))
			return false;

		throw new RuntimeException("Capacity exceeded");
	}

	public static <E> MutableTwoElementSet<E> twoElementSet(E first, E second) {
		return new MutableTwoElementSet<E>(first, second);
	}

	@Override
	public Iterator<E> iterator() {
		return new Iterator<E>() {
			int size = -1;
			int elementsRead = 0;

			@Override
			public boolean hasNext() {
				if (size < 0)
					size = size();
				return elementsRead < size;
			}

			@Override
			public E next() {
				switch(elementsRead) {
				case 0:
					elementsRead++;
					return first;
				case 1:
					elementsRead++;
					return second;
				default:
					throw new NoSuchElementException();
				}
			}

			@Override
			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}

	@Override
	public int size() {
		int size = 0;
		if (first != null)
			size++;
		if (second != null)
			size++;
		return size;
	}
}