text:
require 'rails_helper'

describe Akismet do
  let(:client) { Akismet::Client.new(api_key: 'akismetkey', base_url: 'someurl') }

  let(:post_args) do
    {
      content_type: "forum-post",
      permalink: "http://test.localhost/t/this-is-a-test-topic-49/1889/1",
      comment_author: "bruce106",
      comment_content: "This is a test topic 49\n\nHello world",
      comment_author_email: "bruce106@wayne.com"
    }
  end

  describe "#comment_check" do
    it "should return 'spam' if the post is spam" do
      stub_request(:post, 'https://akismetkey.rest.akismet.com/1.1/comment-check').to_return(status: 200, body: 'true')

      expect(client.comment_check(post_args)).to eq('spam')
    end

    it "should return 'ham' if the post is not spam" do
      stub_request(:post, 'https://akismetkey.rest.akismet.com/1.1/comment-check').to_return(status: 200, body: 'false')

      expect(client.comment_check(post_args)).to eq('ham')
    end

    it "should raise an error with the right message if response is not valid" do
      stub_request(:post, 'https://akismetkey.rest.akismet.com/1.1/comment-check')
        .to_return(status: 200, body: 'Some unknown error', headers: { "#{Akismet::Client::DEBUG_HEADER}" => 'Empty "Blog" value' })

      expect {
        client.comment_check(post_args)
      }.to raise_error(Akismet::Error, 'Empty "Blog" value')

      stub_request(:post, 'https://akismetkey.rest.akismet.com/1.1/comment-check').to_return(status: 200, body: 'Some unknown error')

      expect {
        client.comment_check(post_args)
      }.to raise_error(Akismet::Error, Akismet::Client::UNKNOWN_ERROR_MESSAGE)
    end
  end

  describe '#submit_feedback' do
    it "won't submit feedback if `comment_content` is empty" do
      expect(client.submit_feedback('spam', {})).to eq(false)
    end

    shared_examples 'sends feedback to Akismet and handles the response' do
      it "should return true" do
        stub_request(:post, "https://akismetkey.rest.akismet.com/1.1/submit-#{feedback}").to_return(status: 200, body: Akismet::Client::VALID_SUBMIT_RESPONSE)

        expect(client.submit_feedback(feedback, post_args)).to eq(true)
      end

      it "should raise the right error" do
        stub_request(:post, "https://akismetkey.rest.akismet.com/1.1/submit-#{feedback}").to_return(status: 200, body: "Some error")

        expect { client.submit_feedback(feedback, post_args) }
          .to raise_error(Akismet::Error, Akismet::Client::UNKNOWN_ERROR_MESSAGE)
      end
    end

    context 'with spam' do
      let(:feedback) { 'spam' }

      it_behaves_like 'sends feedback to Akismet and handles the response'
    end

    context 'with ham' do
      let(:feedback) { 'ham' }

      it_behaves_like 'sends feedback to Akismet and handles the response'
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace SudokuSolver
{
    /// <summary>
    /// Logique d'interaction pour App.xaml
    /// </summary>
    public partial class App : Application
    {
        public static SudokuViewModel ViewModelSudoku { get; set; }

        static App()
        {
            ViewModelSudoku = new SudokuViewModel();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
A tool for speedup goimports command :dragon:

## Usage

All you have to do run `dragon-imports` command :+1:

```sh
$ dragon-imports
```

After run the command, your goimports will become fast :dizzy:

**goimports time (sec)**

| before | after |
| ------:| -----:|
| 0.893  | 0.019 |

## How dose it work?

`goimports` command searches for a package with the given symbols from stdlib mappings at first. In this case, the command hopefully never have to scan the GOPATH.

`dragon-imports` add GOPATH's libs to stdlib mappings, and install goimports again.

new `goimports` have stdlib and all GOPATH's libs mappings, it's very fast.

**Note:** It supports `.goimportsignore` and ignores `vendor/` directory.

## Return to the original goimports

You can return to the original goimports by the following:

```sh
$ dragon-imports --restore
```

## Installation

```sh
$ go get github.com/monochromegane/dragon-imports/...
```

**Note:**
  dragon-imports supports golang.org/x/tools older than [the revision](https://github.com/golang/tools/commit/5bbcdc15656ef390fab5dd6e8daf95354f7171e3).
  So, I recommend upgrading golang.org/x/tools by `go get -u golang.org/x/tools/...`.

## ToDo

- File system notification.

## Contribution

1. Fork it
2. Create a feature branch
3. Commit your changes
4. Rebase your local changes against the master branch
5. Run test suite with the `go test ./...` command and confirm that it passes
6. Run `gofmt -s`
7. Create new Pull Request

## License

[MIT](https://github.com/monochromegane/dragon-imports/blob/master/LICENSE)

## Author

[monochromegane](https://github.com/monochromegane)


text:
<?xml version="1.0"?>
<EmbeddedProfile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ToolchainID>com.visualgdb.arm-eabi</ToolchainID>
  <BspID>com.sysprogs.arm.mbed</BspID>
  <BspVersion>20161107-beta</BspVersion>
  <McuID>NUCLEO_F446RE</McuID>
  <MCUProperties>
    <Entries>
      <KeyValue>
        <Key>com.sysprogs.bspoptions.arm.floatmode</Key>
        <Value>-mfloat-abi=softfp</Value>
      </KeyValue>
      <KeyValue>
        <Key>com.sysprogs.toolchainoptions.arm.libctype</Key>
        <Value>--specs=nano.specs</Value>
      </KeyValue>
      <KeyValue>
        <Key>com.sysprogs.toolchainoptions.arm.libnosys</Key>
        <Value />
      </KeyValue>
    </Entries>
  </MCUProperties>
  <BSPSourceFolderName>mbed Files</BSPSourceFolderName>
  <MCUMakFile>mbed.mak</MCUMakFile>
  <ReferencedFrameworks>
    <string>com.sysprogs.arm.mbed.rtos</string>
    <string>com.sysprogs.arm.mbed.rtx</string>
    <string>com.sysprogs.arm.mbed.features</string>
  </ReferencedFrameworks>
  <FrameworkProperties>
    <Entries />
  </FrameworkProperties>
</EmbeddedProfile>


text:
class Test::Unit::TestCase
  def login(user)
    @user = user
    stub(@controller).current_user.returns(user)
  end

  share :no_user do
    before do
      User.delete_all
    end
  end

  share :a_user do
    before do
      @user = User.first
    end
  end

  def valid_user_params
    { :first_name      => 'first name',
      :last_name       => 'last name',
      :email           => 'email@email.org',
      :password        => 'a-password-1',
      :homepage        => 'http://homepage.org' }
  end

  share :valid_user_params do
    before { @params = { :user => valid_user_params } }
  end

  share :invalid_user_params do
    before { @params = { :user => valid_user_params.update(:first_name => '') } }
  end

  share :invalid_user_params do
    before { @params = { :user => valid_user_params.update(:email => '') } }
  end

  share :invalid_user_params do
    before { @params = { :user => valid_user_params.update(:password => '') } }
  end
end


text:
'use strict';

module.exports = (it, expect, collect) => {
  it('should create a new collection by invoking the callback a given amount of times', () => {
    const collection = collect().times(10, number => number * 9);

    expect(collection.all()).to.eql([9, 18, 27, 36, 45, 54, 63, 72, 81, 90]);
  });
};


text:
package de.mirkosertic.bytecoder.ssa;

import de.mirkosertic.bytecoder.core.BytecodeClassinfoConstant;
import de.mirkosertic.bytecoder.core.BytecodeOpcodeAddress;

public class CheckCastExpression extends Expression {

    private final BytecodeClassinfoConstant type;

    public CheckCastExpression(final Program aProgram, final BytecodeOpcodeAddress aAddress, final Value aValue, final BytecodeClassinfoConstant aType) {
        super(aProgram, aAddress);
        type = aType;
        receivesDataFrom(aValue);
    }
}


text:
package algorithm;

import static main.Configuration.LIBRARY_DIRECTORY;
import static main.Configuration.RESTORED_DIRECTORY;
import static model.Criterion.CARRIER_PROCESSABILITY;
import static model.Criterion.CARRIER_RESTORABILITY;
import static model.Criterion.COMPRESSION;
import static model.Criterion.DETECTABILITY;
import static model.Criterion.ENCAPSULATION_METHOD;
import static model.Criterion.ENCRYPTION;
import static model.Criterion.PAYLOAD_ACCESSIBILITY;
import static model.Criterion.PAYLOAD_RESTORABILITY;
import static model.Criterion.STANDARDS;
import static model.Criterion.VELOCITY;
import static model.Criterion.VISIBILITY;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.SuffixFileFilter;

import model.PayloadSegment;
import model.RestoredFile;
import model.Scenario;

/**
 * This Plug-In uses the F5 implementation from cgaffga based on Andreas Westfelds work.
 * Because of license incompatibilities the sources of F5 are delivered externally of PeriCAT. Therefore this algorithm
 * will only work if the F5.jar is present.
 */
public class F5Steganography extends AbstractAlgorithm {

    public F5Steganography() {
    }

    @Override
    Scenario defineScenario() {
	Scenario scenario = new Scenario("F5 ideal scenario");
	scenario.description = "This is the ideal scenario to use the F5 algorithm.";
	scenario.setCriterionValue(ENCAPSULATION_METHOD, EMBEDDING);
	scenario.setCriterionValue(VISIBILITY, INVISIBLE);
	scenario.setCriterionValue(DETECTABILITY, NOT_DETECTABLE);
	scenario.setCriterionValue(CARRIER_RESTORABILITY, NO);
	scenario.setCriterionValue(PAYLOAD_RESTORABILITY, YES);
	scenario.setCriterionValue(CARRIER_PROCESSABILITY, YES);
	scenario.setCriterionValue(PAYLOAD_ACCESSIBILITY, NO);
	scenario.setCriterionValue(ENCRYPTION, NO);
	scenario.setCriterionValue(COMPRESSION, YES);
	scenario.setCriterionValue(VELOCITY, YES);
	scenario.setCriterionValue(STANDARDS, NO);
	return scenario;
    }

    @Override
    SuffixFileFilter configureCarrierFileFilter() {
	List<String> supportedFileFormats = new ArrayList<String>();
	supportedFileFormats.add("jpg");
	supportedFileFormats.add("tif");
	supportedFileFormats.add("gif");
	supportedFileFormats.add("bmp");
	return new SuffixFileFilter(supportedFileFormats);
    }

    @Override
    SuffixFileFilter configurePayloadFileFilter() {
	List<String> supportedFileFormats = new ArrayList<String>();
	supportedFileFormats.add("txt");
	supportedFileFormats.add("xml");
	return new SuffixFileFilter(supportedFileFormats);
    }

    @Override
    SuffixFileFilter configureDecapsulationFileFilter() {
	return configureCarrierFileFilter();
    }

    @Override
    public File encapsulate(File carrierFile, List<File> payloadList) throws IOException {
	String carrier = getCarrier(carrierFile);
	String payload = getPayloadPathString(carrierFile, payloadList.get(0));
	String output = getOutputString(carrierFile);
	encapsulate(carrier, payload, output);
	FileUtils.forceDelete(new File(payload)); // tmp
	File outputFile = new File(output);
	if (outputFile.isFile()) {
	    return outputFile;
	}
	return null;
    }

    private void encapsulate(String carrier, String payload, String output) throws IOException {
	try {
	    String[] args = new String[] { "java", "-jar", LIBRARY_DIRECTORY + "f5.jar", "e", "-e", payload, carrier,
		    output };
	    Process process = Runtime.getRuntime().exec(args);
	    process.waitFor();
	    InputStream inputStream = process.getInputStream();
	    byte b[] = new byte[inputStream.available()];
	    inputStream.read(b, 0, b.length);
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
    }

    private String getCarrier(File carrierFile) {
	return "" + carrierFile.toPath();
    }

    private String getPayloadPathString(File carrier, File payload) throws IOException {
	PayloadSegment payloadSegment = new PayloadSegment(carrier, payload, this);
	File payloadSemgentFile = new File("tmp");
	FileUtils.writeByteArrayToFile(payloadSemgentFile, payloadSegment.getPayloadSegmentBytes());
	return "" + payloadSemgentFile.toPath();
    }

    private String getOutputString(File carrier) {
	File outputFile = getOutputFile(carrier);
	outputFile.delete(); // F5 won't override existing files!
	return "" + outputFile.toPath();
    }

    @Override
    public List<RestoredFile> restore(File carrier) throws IOException {
	List<RestoredFile> restoredFiles = new ArrayList<RestoredFile>();
	File tmpPayload = new File("tmp");
	tmpPayload.delete(); // F5 won't override existing files!
	restore("" + tmpPayload.toPath(), "" + carrier.toPath());
	RestoredFile copiedCarrier = new RestoredFile(RESTORED_DIRECTORY + carrier.getName());
	copiedCarrier.wasCarrier = true;
	copiedCarrier.checksumValid = false;
	copiedCarrier.restorationNote = "The carrier can't be restored with this steganography algorithm. It still contains the embedded payload file(s).";
	FileUtils.copyFile(carrier, copiedCarrier);
	byte[] payloadSegmentBytes = FileUtils.readFileToByteArray(tmpPayload);
	PayloadSegment payloadSegment = PayloadSegment.getPayloadSegment(payloadSegmentBytes);
	RestoredFile restoredPayload = new RestoredFile(RESTORED_DIRECTORY + payloadSegment.getPayloadName());
	FileUtils.writeByteArrayToFile(restoredPayload, payloadSegment.getPayloadBytes());
	restoredPayload.validateChecksum(payloadSegment.getPayloadChecksum());
	restoredPayload.restorationNote = "Payload can be restored correctly.";
	restoredPayload.wasPayload = true;
	restoredPayload.originalFilePath = payloadSegment.getPayloadPath();
	copiedCarrier.originalFilePath = payloadSegment.getCarrierPath();
	restoredFiles.add(restoredPayload);
	FileUtils.forceDelete(tmpPayload);
	restoredFiles.add(copiedCarrier);// carrier can not be restored
	for (RestoredFile file : restoredFiles) {
	    file.algorithm = this;
	    for (RestoredFile relatedFile : restoredFiles) {
		if (file != relatedFile) {
		    file.relatedFiles.add(relatedFile);
		}
	    }
	}
	return restoredFiles;
    }

    private void restore(String payload, String carrier) throws IOException {
	try {
	    Process process = Runtime.getRuntime()
		    .exec(new String[] { "java", "-jar", LIBRARY_DIRECTORY + "f5.jar", "x", "-e", payload, carrier });
	    process.waitFor();
	    InputStream inputStream = process.getInputStream();
	    byte b[] = new byte[inputStream.available()];
	    inputStream.read(b, 0, b.length);
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
    }

    @Override
    public String getName() {
	return "F5 Steganography";
    }

    @Override
    public String getDescription() {
	String description = "Note: The used F5 algorithm is used via an external jar f5.jar, because it is "
		+ "distrubuted unter GPL v 2 license and therefore can't be included into the PeriCAT "
		+ "Apache v.2 project. PeriCAT will run without the f5.jar, but then the F5 algorithm "
		+ "can't be used anymore. The f5.jar has to be located in the PeriCAT_libs directory." + "\n"
		+ "\nF5 is a steganography algorithm described in the paper \"F5 - A Steganography "
		+ "Algorithm - High Capacity Despite Better Steganalysis - Andreas Westfeld\".\n"
		+ "F5 works on image carriers of the type jpg, tif, gif, or bmp and text payload. It is "
		+ "possible to restore the payload correctly in every bit, but, as typical for "
		+ "steganography, the carrier can't be brought back into its original state."
		+ "\nThe algorithm embedds payload images in carrier images.\n\n"
		+ "https://code.google.com/p/f5-steganography/\n"
		+ "f5-steganography.googlecode.com/files/F5%20Steganography.pdf\n"
		+ "Abstract. Many steganographic systems are weak against visual and statistical attacks."
		+ " Systems without these weaknesses offer only a relatively small capacity for "
		+ "steganographic messages. The newly developed algorithm F5 withstands visual and "
		+ "statistical attacks, yet it still offers a large steganographic capacity. F5 "
		+ "implements matrix encoding to improve the efficiency of embedding. Thus it "
		+ "reduces the number of nec- essary changes. F5 employs permutative straddling to "
		+ "uniformly spread out the changes over the whole steganogram.";
	if (!new File(LIBRARY_DIRECTORY + "f5.jar").isFile()) {
	    description = "WARNING: f5.jar doesn't exist.\n\n" + description;
	}
	return description;
    }

    @Override
    public boolean fulfilledTechnicalCriteria(File carrier, List<File> payloadList) {
	return carrier.isFile() && payloadList.size() == 1 && new File(LIBRARY_DIRECTORY + "f5.jar").isFile();
    }
}


text:
class ChangeColumnFiscalYearOnCompanies < ActiveRecord::Migration[5.2]
  def up
    change_column :companies, :fiscal_year, :integer, null: true
  end
  def down
    change_column :companies, :fiscal_year, :integer, null: false
  end
end


text:
package Diadoc.Api.counteragent;

import Diadoc.Api.exceptions.DiadocException;
import Diadoc.Api.exceptions.DiadocSdkException;
import Diadoc.Api.helpers.Tools;
import Diadoc.Api.httpClient.DiadocHttpClient;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.net.URISyntaxException;

import static Diadoc.Api.Proto.AcquireCounteragentProtos.*;
import static Diadoc.Api.Proto.AsyncMethodResultProtos.*;
import static Diadoc.Api.Proto.CounteragentProtos.*;

public class CounteragentClient {
    private DiadocHttpClient diadocHttpClient;

    public CounteragentClient(DiadocHttpClient diadocHttpClient) {
        this.diadocHttpClient = diadocHttpClient;
    }

    public AsyncMethodResult acquireCounteragent(String myOrgId, AcquireCounteragentRequest acquireCounteragentRequest) throws DiadocSdkException {
        return acquireCounteragent(myOrgId, null, acquireCounteragentRequest);
    }

    public AsyncMethodResult acquireCounteragent(
            String myOrgId,
            @Nullable String myDepartmentId,
            AcquireCounteragentRequest acquireCounteragentRequest) throws DiadocSdkException {
        if (Tools.isNullOrEmpty(myOrgId)) {
            throw new IllegalArgumentException("myOrgId");
        }

        if (acquireCounteragentRequest == null) {
            throw new IllegalArgumentException("acquireCounteragentRequest");
        }

        try {
            var url = new URIBuilder(diadocHttpClient.getBaseUrl())
                    .setPath("/V2/AcquireCounteragent")
                    .addParameter("myOrgId", myOrgId);

            if (myDepartmentId != null) {
                url.addParameter("myDepartmentId", myDepartmentId);
            }

            var request = RequestBuilder
                    .post(url.build())
                    .setEntity(new ByteArrayEntity(acquireCounteragentRequest.toByteArray()));

            return AsyncMethodResult.parseFrom(diadocHttpClient.performRequest(request));
        } catch (URISyntaxException | IOException e) {
            throw new DiadocSdkException(e);
        }
    }

    public AcquireCounteragentResult waitAcquireCounteragentResult(String taskId, Integer timeoutInMillis) throws DiadocSdkException, DiadocException {
        try {
            byte[] data = diadocHttpClient.waitTaskResult("/AcquireCounteragentResult", taskId, timeoutInMillis);
            return AcquireCounteragentResult.parseFrom(data);
        } catch (IOException e) {
            throw new DiadocSdkException(e);
        }
    }

    public Counteragent getCounteragent(String myOrgId, String counteragentOrgId) throws DiadocSdkException {
        if (Tools.isNullOrEmpty(myOrgId)) {
            throw new IllegalArgumentException("myOrgId");
        }
        if (Tools.isNullOrEmpty(counteragentOrgId)) {
            throw new IllegalArgumentException("counteragentOrgId");
        }

        try {
            var request = RequestBuilder
                    .get(new URIBuilder(diadocHttpClient.getBaseUrl())
                            .setPath("/V2/GetCounteragent")
                            .addParameter("myOrgId", myOrgId)
                            .addParameter("counteragentOrgId", counteragentOrgId)
                            .build());
            return Counteragent.parseFrom(diadocHttpClient.performRequest(request));
        } catch (URISyntaxException | IOException e) {
            throw new DiadocSdkException(e);
        }
    }

    public CounteragentCertificateList getCounteragentCertificates(String myOrgId, String counteragentOrgId) throws DiadocSdkException {
        if (Tools.isNullOrEmpty(myOrgId)) {
            throw new IllegalArgumentException("myOrgId");
        }
        if (Tools.isNullOrEmpty(counteragentOrgId)) {
            throw new IllegalArgumentException("counteragentOrgId");
        }

        try {
            var request = RequestBuilder
                    .get(new URIBuilder(diadocHttpClient.getBaseUrl())
                            .setPath("/GetCounteragentCertificates")
                            .addParameter("myOrgId", myOrgId)
                            .addParameter("counteragentOrgId", counteragentOrgId)
                            .build());
            return CounteragentCertificateList.parseFrom(diadocHttpClient.performRequest(request));
        } catch (URISyntaxException | IOException e) {
            throw new DiadocSdkException(e);
        }
    }

    public CounteragentList getCounteragents(String myOrgId, @Nullable String counteragentStatus, @Nullable String afterIndexKey) throws DiadocSdkException {
        if (Tools.isNullOrEmpty(myOrgId)) {
            throw new IllegalArgumentException("myOrgId");
        }
        try {
            var url = new URIBuilder(diadocHttpClient.getBaseUrl())
                    .setPath("/V2/GetCounteragents")
                    .addParameter("myOrgId", myOrgId);

            if (!Tools.isNullOrEmpty(counteragentStatus)) {
                url.addParameter("counteragentStatus", counteragentStatus);
            }

            if (afterIndexKey != null) {
                url.addParameter("afterIndexKey", afterIndexKey);
            }

            var request = RequestBuilder.get(url.build());
            return CounteragentList.parseFrom(diadocHttpClient.performRequest(request));
        } catch (URISyntaxException | IOException e) {
            throw new DiadocSdkException(e);
        }
    }

    public void breakWithCounteragent(String myOrgId, String counteragentOrgId, @Nullable String comment) throws DiadocSdkException {
        if (Tools.isNullOrEmpty(myOrgId)) {
            throw new IllegalArgumentException("myOrgId");
        }
        if (Tools.isNullOrEmpty(counteragentOrgId)) {
            throw new IllegalArgumentException("counteragentOrgId");
        }

        try {
            var url = new URIBuilder(diadocHttpClient.getBaseUrl())
                    .setPath("/BreakWithCounteragent")
                    .addParameter("myOrgId", myOrgId)
                    .addParameter("counteragentOrgId", counteragentOrgId);

            if (!Tools.isNullOrEmpty(comment)) {
                url.addParameter("comment", comment);
            }

            var request = RequestBuilder.post(url.build());
            diadocHttpClient.performRequest(request);
        } catch (URISyntaxException | IOException e) {
            throw new DiadocSdkException(e);
        }
    }
}


text:
from mower import GrassSession

DEM = "/home/mperry/projects/shortcreek/dem/dem.img"

with GrassSession(DEM) as gs:
    from grass.pygrass.modules.shortcuts import raster

    # Import/Link to External GDAL data
    raster.external(input=DEM, output="dem")

    # Perform calculations
    raster.mapcalc(expression="demft=dem*3.28084")
    raster.slope_aspect(elevation="demft", slope="slope", aspect="aspect")

    # Export from GRASS to GDAL
    from grass.pygrass.gis import Mapset
    m = Mapset()
    for r in m.glist('rast'):
    	if r == "dem":
    		# don't save the original
    		continue

    	raster.out_gdal(r, format="GTiff", output="/tmp/{}.tif".format(r), overwrite=True)


text:
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm, scipy.stats.stats as stats

def main():
	#list of each country in data set
	country_list = ['Angola', 'Benin', 'Cameroon', 'Chad', 'Equatorial_Guinea', 'Eritrea', 'Gabon', 'Gambia', 'Ghana', 'Liberia', 'Malawi', 'Mali', 'Morocco', 'Mozambique', 'Senegal', 'Sierra_Leone', 'Tanzania', 'Togo', 'Uganda', 'Zambia']

	#initialize data frame to store results for each country
	pearson_results = pd.DataFrame(columns = ['country', 'precip', 'f_rain', 'f_cold', 'f_heat'])
	spearman_results = pd.DataFrame(columns = ['country', 'precip', 'f_rain', 'f_cold', 'f_heat'])

	#initialize data frame to store results for each country
	pearson_results = pd.DataFrame(columns = ['country', 'precip', 'f_rain', 'f_cold', 'f_heat'])
	spearman_results = pd.DataFrame(columns = ['country', 'precip', 'f_rain', 'f_cold', 'f_heat'])

	for country in country_list:
		#load data on country
		data = load_data(country)
		#conduct statistical analysis
		pearson_results = pearson_results.append(pearson_correlation(data, country), ignore_index = True)
		spearman_results = spearman_results.append(spearman_correlation(data, country), ignore_index = True)

	#make plots
	for variable in ['precip', 'f_rain', 'f_cold', 'f_heat']:
		make_plot(data[variable], data.Year, '../results/' + variable + '_over_time.pdf')

	#make table containing results
	make_stats_table(pearson_results, spearman_results)

def load_conflict_data(country_name):
	'''This function is used to grab data on conflict occurances in a specific country.
	The function takes one input, which is the name of the country you want to grab data for. Returns the data as a pandas data frame.'''

	#path is a string containing the path for the data files
	path = "../data/ACLED/" + country_name + '.xlsx'

	#read from excel file
	data = pd.read_excel(path)

	#only return necessary columns
	data = data[['YEAR', 'EVENT_TYPE', 'ACTOR1', 'LOCATION', 'FATALITIES']]
	data.columns = ['Year', 'Event_type', 'Actor', 'Location', 'Fatalities']
	data['Count'] = 1

	return data

def load_climate_data(country_name):
	'''This function is used to grab data on climate for each country.
	The function takes one input, which is the name of the country to grab data on. The function returns the data as a pandas data frame.'''

	#extreme filename is a dictionary containing the file extension corresponding to each variable for extreme weather patterns
	extremes_filename = {'f_extreme_heat' : 'TX90p.csiro_mk3_0.abs.txt', 'f_extreme_cold' : 'TX10p.csiro_mk3_0.abs.txt', 'f_heavy_rain' : 'R95pct.csiro_mk3_0.anom.txt'}

	#mean filename is a dictionary containing the file extension corresponding to each variable for mean temperature and precipitation
	mean_filename = {'temperature' : 'temp.csiro_mk3_5.anom.txt', 'precipitation' : 'precip.csiro_mk3_5.anom.txt'}

	#contains the file path for each group of variables
	#Extremes/... contains data on extreme weather, Mean/... contains mean temperature and precipitation data
	directories = ['/Model/Extremes/Timeseries/', '/Model/Mean/Timeseries/Anomalies/']

	#initializes data frame
	data = pd.DataFrame()

	# for each group of variables
	for directory in directories:
		# if the data is for extremes, iterate over extremes_variables and gets the final path for each file to grab
		if directory == '/Model/Extremes/Timeseries/':

			#gets the variable name from a list of variables
			#each variable corresponds to the end of the name of the file
			for file in extremes_filename:
				#variable for column names
				colnames = ['Year', 'Annual_' + file, 'JFM_' + file, 'AMJ_' + file, 'JAS_' + file, 'OND_' + file]

				#path is equal to the file path for the data file containing data on the current variable
				#concatonates country name, directory names and file names to form the specific file path
				path = '../data/climate/' + country_name + directory + country_name + '.ts.' + extremes_filename[file]

				#if the data frame is empty, set data equal to the contents of the first file
				if data.empty:
					data = pd.read_table(path, delimiter = '\s+', header = None, names = colnames, skiprows = 15, nrows = 120, error_bad_lines = True, index_col='Year')

				#if the data frame is not empty, concatonate the data from the second file to the first
				else:
					data_2 = pd.read_table(path, delimiter = '\s+', header = None, names = colnames, skiprows = 15, nrows = 120, error_bad_lines = True, index_col='Year')
					#data_2 = data_2.reset_index()
					#data = data.reset_index(drop = True)
					data = data.join(data_2)

		# if the data is for means, iterate over mean_variables and get the final path for each data file
		elif directory == '/Model/Mean/Timeseries/Anomalies/':

			#gets the variable name from a list of variables
			#each variable corresponds to the end of the name of the file
			for file in mean_filename:
				#for column names
				colnames = ['Year', 'Annual_' + file, 'JFM_' + file, 'AMJ_' + file, 'JAS_' + file, 'OND_' + file]

				#path is equal to the file path for the data file containing data on the current variable
				#concatonates country name, directory names and file names to form the specific file path
				path = '../data/climate/' + country_name + directory + country_name + '.ts.' + mean_filename[file]

				#if the data frame is empty, set data equal to the contents of the first file
				if data.empty:
					data = pd.read_table(path, delimiter = '\s+', header = None, names = colnames, skiprows = 15, nrows = 120, error_bad_lines = True, index_col='Year')

				#if the data frame is not empty, concatonate the data from the second file to the first
				else:
					data_2 = pd.read_table(path, delimiter = '\s+', header = None, names = colnames, skiprows = 15, nrows = 120, error_bad_lines = True, index_col='Year')
					#data_2 = data_2.reset_index()
					#data = data.reset_index(drop = True)
					data = data.join(data_2)

	#reduces the size of the data
	data = data[['Annual_f_extreme_cold', 'Annual_f_extreme_heat', 'Annual_f_heavy_rain', 'Annual_precipitation', 'Annual_temperature']]

	#drop nan rows
	data = data.dropna()

	#drop the last row (inelegant solution to a problem!)
	data = data.drop(data.tail(1).index)

	#return final formatted data frame
	return data

def load_data(current_country):
	'''This function loads and munges data into a pandas data frame.

	Usage: load_data(list_of_countries_to_load)'''

	#load data on climate for the country
	climate_data = load_climate_data(current_country)
	#load data on conflict in the country
	conflict_data = load_conflict_data(current_country)

	#create smaller data set to work with
	climate_small_data = climate_data[['Annual_precipitation', 'Annual_f_heavy_rain', 'Annual_f_extreme_cold', 'Annual_f_extreme_heat']]
	conflict_small_data = conflict_data[['Fatalities', 'Year', 'Count']]

	#rename columns
	climate_small_data.columns = ['precip', 'f_rain', 'f_cold', 'f_heat']

	#group conflict data by year
	conflict_small_data = conflict_small_data.groupby('Year').sum()

	#make indices the same type for merging
	#reset index to make 'Year' a column not an index
	conflict_small_data = conflict_small_data.reset_index().astype(float)
	climate_small_data = climate_small_data.reset_index().astype(float)

	# Generate predicted values for missing climate data from 2000 - 2046
	# Initialize data frame
	data_pred = pd.DataFrame()
	#iterate for each column
	for column in climate_small_data.columns:
		#linear regression for each column variable
		if column != 'Year':
			#linear model
			lm = sm.formula.ols(formula = column + " ~ Year", data = climate_small_data).fit()

			#range of missing date values
			xnew = pd.DataFrame({'Year' : range(2001, 2046)})

			#predict missing values for column variable
			y_pred = lm.predict(xnew)

			#create data frame from predicted values
			y_pred_df = pd.DataFrame({'Year' : range(2001, 2046), column : y_pred})

			#merge data into initialized data frame
			if data_pred.empty:
				data_pred = y_pred_df
			else:
				data_pred = data_pred.merge(y_pred_df)

	#concatenate the predicted values into previous data frame
	climate_small_data = pd.concat([climate_small_data, data_pred]).sort_values('Year')

	#merge the data, and drop Nan to get overlapping data
	final_data = climate_small_data.merge(conflict_small_data, how = 'outer').dropna()

	return final_data

def pearson_correlation(data, country):
	'''This function calculates Pearson's correlation for an input data set.
	Usage: pearson_correlation(dataframe, country_name)

	Output: series containing the results for the test, for each variable.'''
	#initializes series to store results from Pearson's correlation test
	pearson_coefficient = pd.Series(index = ['country', 'precip', 'f_rain', 'f_cold', 'f_heat'])
	pearson_coefficient['country'] = country

	#for each x-variable
	for column in data:
		if (column != 'Year') & (column != 'Fatalities') & (column != 'Count'):
			#conduct statistical test of current variable vs. conflicts/year
			pearson = stats.pearsonr(data[column], data.Count)
			#put results in initialized results array
			pearson_coefficient[column] = pearson

	return pearson_coefficient

def spearman_correlation(data, country):
	'''This function calculates Spearman's rank correlation for an input data set.
	Usage: spearman_correlation(dataframe, country_name)

	Output: series containing the results for the test, for each variable.'''
	#initializes series to store results from Spearman's rank correlation
	spearman_coefficient = pd.Series(index = ['country', 'precip', 'f_rain', 'f_cold', 'f_heat'])
	spearman_coefficient['country'] = country

	#for each x-variable
	for column in data:
		if (column != 'Year') & (column != 'Fatalities') & (column != 'Count'):
			#conduct statistical test of current variable vs. conflicts/year
			spearman = stats.spearmanr(a = data[column], b = data.Count)
			#put results in initialized results array
			spearman_coefficient[column] = spearman

	return spearman_coefficient

def munge_results(coefficient_data, column):
	'''This function compiles the results for a statistical test into a workable data frame.
	Usage: munge_results(dataframe, variable_name)

	output: dataframe containing reformatted results from statistical tests. '''

	#initialize data frame to store mean results of each statistical test
	coefficients = pd.DataFrame()

	#for each country in data set
	for country in coefficient_data['country']:
		# creates a variable containing values for a row
		row = tuple(coefficient_data[coefficient_data.country == country][column])
		#adds row to data frame
		coefficients[country] = row[0]

	#transposes data frame to make country name the index, and 'coefficient' and 'p_value' columns
	coefficients = coefficients.T
	coefficients.columns = ['coefficient', 'p_value']

	return coefficients

def make_stats_table(pearson_data, spearman_data):
	'''This function takes results for each statistical test and finds the mean of the results from all countries. Inputs are data frames containing the results from each statistical test.

	Usage: stats_table(pearson_results, spearman_results)

	Output: saved file containing the mean of the results from the statistical tests. '''

	#initializes column names for results data frame
	mean_results = pd.DataFrame(columns = ['variable', 'pearson_coefficient', 'pearson_p_value', 'spearman_coefficient', 'spearman_p_value'])

	#for each variable in results table
	for column in pearson_data:
		if column != 'country':
			#munge results to get p_value and coefficient values separately
			munged_pearson = munge_results(pearson_data, column).mean()
			munged_spearman = munge_results(spearman_data, column).mean()

			#construct a row from the results for the current variable
			new_row = pd.DataFrame({'variable' : [column], 'pearson_coefficient' : [munged_pearson[0]], 'pearson_p_value' : [munged_pearson[1]],
								   'spearman_coefficient' : [munged_spearman[0]], 'spearman_p_value' : [munged_spearman[1]]})
			#append row to results data frame
			mean_results = mean_results.append(new_row, ignore_index = True)

	#sets index to variable
	mean_results.index = mean_results.variable
	#deletes variable column
	del mean_results['variable']
	#saves the table
	mean_results.to_csv('../results/correlation_results.csv')

def make_plot(y, x, filename):
	'''This function creates line plots from x and y inputs and saves them to file.'''

	#initialize plot
	plt.plot(x, y)

	#label names equal to the input variables
	plt.xlabel(x.name)
	plt.ylabel(y.name)

	#save figure to results directory
	plt.savefig(filename)

	plt.close()

main()


text:
import { put, call, takeEvery } from 'redux-saga/effects'
import * as actions from './actions'

export function* createResource(api, { data }, { resource, thunk }) {
  try {
    // https://github.com/diegohaz/arc/wiki/API-service
    const detail = yield call([api, api.post], `/${resource}`, data)
    // https://github.com/diegohaz/arc/wiki/Actions#async-actions
    yield put(actions.resourceCreateSuccess(resource, detail, { data }, thunk))
  } catch (e) {
    yield put(actions.resourceCreateFailure(resource, e, { data }, thunk))
  }
}

export function* readResourceList(api, { params }, { resource, thunk }) {
  try {
    const list = yield call([api, api.get], `/${resource}`, { params })
    yield put(actions.resourceListReadSuccess(resource, list, { params }, thunk))
  } catch (e) {
    yield put(actions.resourceListReadFailure(resource, e, { params }, thunk))
  }
}

export function* readResourceDetail(api, { needle }, { resource, thunk }) {
  try {
    const detail = yield call([api, api.get], `/${resource}/${needle}`)
    yield put(actions.resourceDetailReadSuccess(resource, detail, { needle }, thunk))
  } catch (e) {
    yield put(actions.resourceDetailReadFailure(resource, e, { needle }, thunk))
  }
}

export function* updateResource(api, { needle, data }, { resource, thunk }) {
  try {
    const detail = yield call([api, api.put], `/${resource}/${needle}`, data)
    yield put(actions.resourceUpdateSuccess(resource, detail, { needle, data }, thunk))
  } catch (e) {
    yield put(actions.resourceUpdateFailure(resource, e, { needle, data }, thunk))
  }
}

export function* deleteResource(api, { needle }, { resource, thunk }) {
  try {
    yield call([api, api.delete], `/${resource}/${needle}`)
    yield put(actions.resourceDeleteSuccess(resource, { needle }, thunk))
  } catch (e) {
    yield put(actions.resourceDeleteFailure(resource, e, { needle }, thunk))
  }
}

export function* watchResourceCreateRequest(api, { payload, meta }) {
  yield call(createResource, api, payload, meta)
}

export function* watchResourceListReadRequest(api, { payload, meta }) {
  yield call(readResourceList, api, payload, meta)
}

export function* watchResourceDetailReadRequest(api, { payload, meta }) {
  yield call(readResourceDetail, api, payload, meta)
}

export function* watchResourceUpdateRequest(api, { payload, meta }) {
  yield call(updateResource, api, payload, meta)
}

export function* watchResourceDeleteRequest(api, { payload, meta }) {
  yield call(deleteResource, api, payload, meta)
}

export default function* ({ api }) {
  yield takeEvery(actions.RESOURCE_CREATE_REQUEST, watchResourceCreateRequest, api)
  yield takeEvery(actions.RESOURCE_LIST_READ_REQUEST, watchResourceListReadRequest, api)
  yield takeEvery(actions.RESOURCE_DETAIL_READ_REQUEST, watchResourceDetailReadRequest, api)
  yield takeEvery(actions.RESOURCE_UPDATE_REQUEST, watchResourceUpdateRequest, api)
  yield takeEvery(actions.RESOURCE_DELETE_REQUEST, watchResourceDeleteRequest, api)
}


text:
package gw.lang.gosuc;

import gw.lang.reflect.IType;
import gw.lang.reflect.module.IModule;

import java.util.List;

public interface IGosuc {
  void initializeGosu();
  List<IType> compile( String moduleName, List<String> typesToCompile );
  List<IType> compile( IModule module, List<String> typesToCompile );
}


text:
@interface ContainerBaseViewController : UIViewController

@end


text:
require 'guard/compat/plugin'
require 'yardstick'
require 'yaml'

module Guard
  # A guard plugin to run yardstick on every save
  class Yardstick < Plugin
    # A hash of options for configuring the plugin
    #
    # @api private
    # @return [Hash]
    attr_reader :options

    # Initializes guard-yardstick
    #
    # @api private
    # @return [Guard::Yardstick]
    def initialize(args = {})
      super

      @options = {
        all_on_start: true,
        config: nil
      }.merge(args)
    end

    # When guard starts will run all files if :all_on_start is set
    #
    # @api private
    # @return [Void]
    def start
      run_all if options[:all_on_start]
    end

    # Will run all files through yardstick
    #
    # @api private
    # @return [Void]
    def run_all
      UI.info 'Inspecting Yarddoc in all files'
      inspect_with_yardstick
    end

    # Will run when files are added
    #
    # @api private
    # @return [Void]
    def run_on_additions(paths)
      run_partially(paths)
    end

    # Will run when files are changed
    #
    # @api private
    # @return [Void]
    def run_on_modifications(paths)
      run_partially(paths)
    end

    private

    # Runs yardstick on a partial set of paths passed in by guard
    #
    # @api private
    # @return [Void]
    def run_partially(paths)
      return if paths.empty?

      displayed_paths = paths.map { |path| smart_path(path) }
      UI.info "Inspecting Yarddocs: #{displayed_paths.join(' ')}"

      inspect_with_yardstick(path: paths)
    end

    # Runs yardstick and outputs results to STDOUT
    #
    # @api private
    # @return [Void]
    def inspect_with_yardstick(yardstick_options = {})
      config = ::Yardstick::Config.coerce(yardstick_config(yardstick_options))
      measurements = ::Yardstick.measure(config)
      measurements.puts
    rescue StandardError => error
      UI.error 'The following exception occurred while running ' \
               "guard-yardstick: #{error.backtrace.first} " \
               "#{error.message} (#{error.class.name})"
    end

    # Returns a path with pwd removed if needed
    #
    # @api private
    # @return [String]
    def smart_path(path)
      if path.start_with?(Dir.pwd)
        Pathname.new(path).relative_path_from(Pathname.getwd).to_s
      else
        path
      end
    end

    # Merge further options with yardstick config file.
    #
    # @api private
    # @return [Hash] Hash of options for yardstick measurement
    def yardstick_config(extra_options = {})
      return options unless options[:config]

      yardstick_options = YAML.load_file(options[:config])
      yardstick_options.merge(extra_options)
    end
  end
end


text:
package com.student.selfworks.todo;

public class TreeImplementationOfHashMap {

}


text:
package core.shape_interface;

import core.Model;
import core.geom.tools.EraserInterface;
import core.shape_interface.editor.ShapeEditInterface;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.SwingUtilities;
import ui.Pad;

/**
 *
 * @author Mithusayel Murmu
 */
public abstract class PadInterface extends MouseAdapter {

    protected Pad pad;
    protected Model model;
    protected ShapeEditInterface sei;

    public void setPad(Pad pad) {
        this.pad = pad;
    }

    public void paint(Graphics2D g2) {
        sei.paintControls(g2);
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        pad.requestFocusInWindow();
        if(Model.getMode() == Model.EDIT_MODE)
            sei.mouseMoved(e);
    }

    @Override
    public void mousePressed(MouseEvent e) {
        if(SwingUtilities.isLeftMouseButton(e))
            mouseDown(e);
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        if(SwingUtilities.isLeftMouseButton(e))
            mouseDrag(e);
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if(SwingUtilities.isLeftMouseButton(e))
            mouseUp(e);
    }

    public void createEditor() {
        sei = new ShapeEditInterface(model);
    }

    public void updateControls() {
        if(sei != null) {
            sei.updateControls();
        }
    }

    public abstract void clearShape();
    protected abstract void mouseDown(MouseEvent e);
    protected abstract void mouseDrag(MouseEvent e);
    protected abstract void mouseUp(MouseEvent e);

    public static PadInterface getFreeShapeControlInstance(Model model) {
        return new FreeShapeInterface(model);
    }

    public static PadInterface getLineControlInstance(Model model) {
        return new LineInterface(model);
    }

    public static PadInterface getRectControlInstance(Model model) {
        return new RectInterface(model);
    }

    public static PadInterface getOvalControlInstance(Model model) {
        return new OvalInterface(model);
    }

    public static PadInterface getCurveControlInstance(Model model) {
        return new CurveInterface(model);
    }

    public static PadInterface getEraserControlInstance(Model model) {
        return new EraserInterface(model);
    }

    public static PadInterface getFillControlInstance(Model model) {
        return new FillInterface(model);
    }
}


text:
import {Vec3f} from "../util/math/Vec3f";
import {Material} from "../gfx/Material";
import {Light} from "../gfx/Light";
import {Intersection} from "../util/math/Intersection";
import {Ray} from "../util/math/Ray";
import {light_types} from "../util/Config";
import {Config} from "../util/Config";
import {material_types} from "../util/Config";

export class Shader
{

	static COLOR_NULL:Vec3f = new Vec3f(0);
	static COLOR_RED:Vec3f = new Vec3f(1,0,0);
	static COLOR_WHITE:Vec3f = new Vec3f(1);

	constructor()
	{

	}

	static main(r:Ray, x:Intersection, l:Light, m:Material):Vec3f
	{
		var C:Vec3f;
        var N:Vec3f = x.norm;
        var L:Vec3f;
        var V:Vec3f;
        var H:Vec3f;

		var NdotL:number;
        var NdotV:number;
        var NdotH:number;
        var VdotH:number;
        var lambertian:number;
        var specular:number;
        var roughness:number;
        var L_length:number;
        var A:number = 1.0;

		if (l.light_type == light_types.DIRECTIONAL)
		{
			L = l.dir.negate().normalize();
			V = r.dir.negate();
			H = V.add(L).normalize();
		} else if (l.light_type == light_types.POINT)
		{
			L = l.pos.sub(x.pos);
			L_length = L.length();
			L = L.normalize();
			V = r.dir.negate();
			H = V.add(L).normalize();
			A = l.constant + l.linear * L_length + l.exponent * L_length * L_length + Config.epsilon;
		} else
		{
			return Shader.COLOR_NULL;
		}

		// Calculate the dot products required for shading
		NdotL = Math.min(N.dot(L), 1.0);
		NdotV = Math.min(N.dot(V), 1.0);
		NdotH = Math.min(N.dot(H), 1.0);
		VdotH = Math.min(V.dot(H), 1.0);

		if (m.material_type == material_types.PHONG)
		{
			C = new Vec3f();

			// Calculate the lambertian term
			lambertian = Math.min(NdotL, 1.0);

			// Calculate the specular term
			if (m.shininess > 0.0)
				specular = Math.pow(NdotH, m.shininess); // Specular
			else
				specular = 0.0;

			// Add all the terms together to C
			C.setVec(C.add(l.color.scale(m.color_diffuse).scaleNumber(lambertian).scaleNumber(l.intensity)));
			C.setVec(C.add(m.color_specular.scaleNumber(specular).scaleNumber(l.intensity)));
		} else if (m.material_type == material_types.COOKTORRANCE)
		{
			C = new Vec3f();

			// Return NULL color if the surface normal and light direction are facing opposite directions
			if (NdotL < Config.epsilon)
				return Shader.COLOR_NULL;

			// Get the surface properties
			var R:number = m.roughness;
			var F:number = m.fresnel;
			var K:number = m.density;

			// Evaluate the geometric term
			var geo_numerator:number = 2.0 * NdotH;
			var geo_denominator:number = VdotH;
			var geo_a:number = (geo_numerator * NdotV) / geo_denominator;
			var geo_b:number = (geo_numerator * NdotL) / geo_denominator;
			lambertian = Math.min(1.0, Math.min(geo_a, geo_b));

			// Evaluate the roughness term
			var roughness_a:number = 1.0 / (4.0 * R * R * Math.pow(NdotH, 4));
			var roughness_b:number = NdotH * NdotH - 1.0;
			var roughness_c:number = R * R * NdotH * NdotH;
			roughness = roughness_a * Math.exp(roughness_b / roughness_c);

			// Evaluate the fresnel term
			specular = Math.pow(1.0 - VdotH, 5);
			specular *= 1.0 - F;
			specular += F;

			// Put all the terms together
			var Rs_numerator:number = lambertian * roughness * specular;
			var Rs_denominator:number = Math.max(NdotV * NdotL, Config.epsilon);
			var Rs:number = Rs_numerator / Rs_denominator;

			// Add all the terms to C
			var final_a:Vec3f = l.color.scaleNumber(NdotL).scaleNumber(l.intensity);
			var final_b:Vec3f = m.color_diffuse.scaleNumber(K).add(m.color_specular.scaleNumber(Rs * (1.0 - K)));
			C.setVec(final_a.scale(final_b));
		} else
		{
			return Shader.COLOR_NULL;
		}

		return C.divideNumber(A);
	}

}


text:
namespace Selenium.WebDriver.Extensions
{
    using System.Diagnostics.CodeAnalysis;
    using OpenQA.Selenium;
    using static System.Globalization.CultureInfo;
    using static System.String;
    using static JavaScriptSnippets;
    using static Softlr.Suppress;
    using static Validate;

    /// Searches the DOM elements using jQuery selector.
    /// <inheritdoc />
    public class JQuerySelector : SelectorBase<JQuerySelector>
    {
        private const string VARIABLE = "window.jQuery";
        private readonly string _chain;

        /// Initializes a new instance of the <see cref="JQuerySelector" /> class.
        /// <param name="selector">A string containing a selector expression.</param>
        /// <remarks>
        /// This constructor cannot be merged with <see
        /// cref="M:Selenium.WebDriver.Extensions.JQuerySelector.#ctor(System.String,Selenium.WebDriver.Extensions.JQuerySelector,System.String,System.String)" />
        /// constructor as it is resolved by reflection.
        /// </remarks>
        public JQuerySelector(string selector)
            : this(selector, null, "jQuery", string.Empty)
        {
        }

        /// Initializes a new instance of the <see cref="JQuerySelector" /> class.
        /// <param name="selector">A string containing a selector expression.</param>
        /// <param name="context">A DOM Element, Document, or jQuery to use as context.</param>
        public JQuerySelector(string selector, JQuerySelector context)
            : this(selector, context, "jQuery", string.Empty)
        {
        }

        /// Initializes a new instance of the <see cref="JQuerySelector" /> class.
        /// <param name="selector">A string containing a selector expression.</param>
        /// <param name="context">A DOM Element, Document, or jQuery to use as context.</param>
        /// <param name="variable">A variable that has been assigned to jQuery.</param>
        public JQuerySelector(string selector, JQuerySelector context, string variable)
            : this(selector, context, variable, string.Empty)
        {
        }

        /// Initializes a new instance of the <see cref="JQuerySelector" /> class.
        /// <param name="selector">A string containing a selector expression.</param>
        /// <param name="variable">A variable that has been assigned to jQuery.</param>
        public JQuerySelector(string selector, string variable)
            : this(selector, null, variable, string.Empty)
        {
        }

        /// Initializes a new instance of the <see cref="JQuerySelector" /> class.
        /// <param name="selector">A string containing a selector expression.</param>
        /// <param name="context">A DOM Element, Document, or jQuery to use as context.</param>
        /// <param name="variable">A variable that has been assigned to jQuery.</param>
        /// <param name="chain">The jQuery method chain.</param>
        public JQuerySelector(string selector, JQuerySelector context, string variable, string chain)
            : base(selector, context)
        {
            _chain = NotNull(() => chain);
            Variable = Required(() => variable);
            Description = $"By.JQuerySelector: {RawSelector}";
        }

        /// Gets the empty selector.
        public static JQuerySelector Empty { get; } = new JQuerySelector("*");

        /// <inheritdoc />
        public override string CheckScript => CheckScriptCode(VARIABLE);

        /// <inheritdoc />
        public override string Selector => $"{Variable}('{RawSelector.Replace('\'', '"')}'"
            + (Context != null ? $", {Context.Selector}" : string.Empty) + $"){_chain}";

        /// Gets the variable that has been assigned to jQuery.
        public virtual string Variable { get; }

        /// <inheritdoc />
        protected override string ResultResolver => ".get()";

        /// Adds elements to the set of matched elements.
        /// <param name="selector">
        /// A string representing a selector expression to find additional elements to add to the set of matched
        /// elements.
        /// </param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Add(string selector) => Chain("add", Required(() => selector));

        /// Adds elements to the set of matched elements.
        /// <param name="selector">
        /// A string representing a selector expression to find additional elements to add to the set of matched
        /// elements.
        /// </param>
        /// <param name="context">The jQuery context selector.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Add(string selector, JQuerySelector context) =>
            ChainWithContext("add", Required(() => selector), NotNull(() => context));

        ///
        /// Add the previous set of elements on the stack to the current set, optionally filtered by a selector.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector AddBack() => AddBack(null);

        ///
        /// Add the previous set of elements on the stack to the current set, optionally filtered by a selector.
        ///
        /// <param name="selector">
        /// A string containing a selector expression to match the current set of elements against.
        /// </param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector AddBack(string selector) => Chain("addBack", NullOrNotEmpty(() => selector));

        /// Add the previous set of elements on the stack to the current set.
        /// <returns>The Selenium jQuery selector.</returns>
        /// <remarks>While this method is obsolete in jQuery 1.8+ we will support it.</remarks>
        public JQuerySelector AndSelf() => Chain("andSelf");

        ///
        /// Get the children of each element in the set of matched elements, optionally filtered by a selector.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Children() => Children(null);

        ///
        /// Get the children of each element in the set of matched elements, optionally filtered by a selector.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Children(string selector) => Chain("children", NullOrNotEmpty(() => selector));

        ///
        /// For each element in the set, get the first element that matches the selector by testing the element itself
        /// and traversing up through its ancestors in the DOM tree.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Closest(string selector) => Chain("closest", Required(() => selector));

        ///
        /// For each element in the set, get the first element that matches the selector by testing the element itself
        /// and traversing up through its ancestors in the DOM tree.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <param name="context">The jQuery context selector.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Closest(string selector, JQuerySelector context) =>
            ChainWithContext("closest", Required(() => selector), NotNull(() => context));

        ///
        /// Get the children of each element in the set of matched elements, including text and comment nodes.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Contents() => Chain("contents");

        ///
        /// End the most recent filtering operation in the current chain and return the set of matched elements to its
        /// previous state.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector End() => Chain("end");

        /// Reduce the set of matched elements to the one at the specified index.
        /// <param name="index">An integer indicating the 0-based position of the element.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Eq(int index) => Chain("eq", index.ToString(InvariantCulture), true);

        /// Reduce the set of matched elements to the even ones in the set, numbered from zero.
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Even() => Chain("even");

        ///
        /// Reduce the set of matched elements to those that match the selector or pass the function's test.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Filter(string selector) => Chain("filter", Required(() => selector));

        ///
        /// Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery
        /// object, or element.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Find(string selector) => Chain("find", Required(() => selector));

        /// Reduce the set of matched elements to the first in the set.
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector First() => Chain("first");

        ///
        /// Reduce the set of matched elements to those that have a descendant that matches the selector or DOM
        /// element.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Has(string selector) => Chain("has", Required(() => selector));

        ///
        /// Check the current matched set of elements against a selector, element, or jQuery object and return
        /// <see langword="true" /> if at least one of these elements matches the given arguments.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Is(string selector) => Chain("is", Required(() => selector));

        /// Reduce the set of matched elements to the final one in the set.
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Last() => Chain("last");

        ///
        /// Get the immediately following sibling of each element in the set of matched elements. If a selector is
        /// provided, it retrieves the next sibling only if it matches that selector.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Next() => Next(null);

        ///
        /// Get the immediately following sibling of each element in the set of matched elements. If a selector is
        /// provided, it retrieves the next sibling only if it matches that selector.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Next(string selector) => Chain("next", NullOrNotEmpty(() => selector));

        ///
        /// Get all following siblings of each element in the set of matched elements, optionally filtered by a
        /// selector.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector NextAll() => NextAll(null);

        ///
        /// Get all following siblings of each element in the set of matched elements, optionally filtered by a
        /// selector.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector NextAll(string selector) => Chain("nextAll", NullOrNotEmpty(() => selector));

        ///
        /// Get all following siblings of each element up to but not including the element matched by the selector,
        /// DOM node, or jQuery object passed.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector NextUntil() => NextUntil(null, null);

        ///
        /// Get all following siblings of each element up to but not including the element matched by the selector,
        /// DOM node, or jQuery object passed.
        ///
        /// <param name="selector">
        /// A string containing a selector expression to indicate where to stop matching following sibling elements.
        /// </param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector NextUntil(string selector) => NextUntil(selector, null);

        ///
        /// Get all following siblings of each element up to but not including the element matched by the selector,
        /// DOM node, or jQuery object passed.
        ///
        /// <param name="selector">
        /// A string containing a selector expression to indicate where to stop matching following sibling elements.
        /// </param>
        /// <param name="filter">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector NextUntil(string selector, string filter)
        {
            var validatedSelector = NullOrNotEmpty(() => selector);
            var validatedFilter = NullOrNotEmpty(() => filter);
            var filteredSelector = validatedSelector == null && validatedFilter != null
                ? string.Empty
                : validatedSelector;
            return Chain("nextUntil", FilteredSelector(filteredSelector, validatedFilter), true);
        }

        /// Remove elements from the set of matched elements.
        /// <param name="selector">
        /// A string containing a selector expression, a DOM element, or an array of elements to match against the set.
        /// </param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Not(string selector) => Chain("not", Required(() => selector));

        /// Reduce the set of matched elements to the odd ones in the set, numbered from zero.
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Odd() => Chain("odd");

        /// Get the closest ancestor element that is positioned.
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector OffsetParent() => Chain("offsetParent");

        ///
        /// Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Parent() => Parent(null);

        ///
        /// Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Parent(string selector) => Chain("parent", NullOrNotEmpty(() => selector));

        ///
        /// Get the ancestors of each element in the current set of matched elements, optionally filtered by a
        /// selector.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Parents() => Parents(null);

        ///
        /// Get the ancestors of each element in the current set of matched elements, optionally filtered by a
        /// selector.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Parents(string selector) => Chain("parents", NullOrNotEmpty(() => selector));

        ///
        /// Get the ancestors of each element in the current set of matched elements, up to but not including the
        /// element matched by the selector, DOM node, or jQuery object.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector ParentsUntil() => ParentsUntil(null, null);

        ///
        /// Get the ancestors of each element in the current set of matched elements, up to but not including the
        /// element matched by the selector, DOM node, or jQuery object.
        ///
        /// <param name="selector">
        /// A string containing a selector expression to indicate where to stop matching ancestor elements.
        /// </param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector ParentsUntil(string selector) => ParentsUntil(selector, null);

        ///
        /// Get the ancestors of each element in the current set of matched elements, up to but not including the
        /// element matched by the selector, DOM node, or jQuery object.
        ///
        /// <param name="selector">
        /// A string containing a selector expression to indicate where to stop matching ancestor elements.
        /// </param>
        /// <param name="filter">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector ParentsUntil(string selector, string filter)
        {
            var validatedSelector = NullOrNotEmpty(() => selector);
            var validatedFilter = NullOrNotEmpty(() => filter);
            var filteredSelector = validatedSelector == null && validatedFilter != null
                ? string.Empty
                : validatedSelector;
            return Chain("parentsUntil", FilteredSelector(filteredSelector, validatedFilter), true);
        }

        ///
        /// Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered
        /// by a selector.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Prev() => Prev(null);

        ///
        /// Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered
        /// by a selector.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Prev(string selector) => Chain("prev", NullOrNotEmpty(() => selector));

        ///
        /// Get all preceding siblings of each element in the set of matched elements, optionally filtered by a
        /// selector.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector PrevAll() => PrevAll(null);

        ///
        /// Get all preceding siblings of each element in the set of matched elements, optionally filtered by a
        /// selector.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector PrevAll(string selector) => Chain("prevAll", NullOrNotEmpty(() => selector));

        ///
        /// Get all preceding siblings of each element up to but not including the element matched by the selector,
        /// DOM node, or jQuery object.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector PrevUntil() => PrevUntil(null, null);

        ///
        /// Get all preceding siblings of each element up to but not including the element matched by the selector,
        /// DOM node, or jQuery object.
        ///
        /// <param name="selector">
        /// A string containing a selector expression to indicate where to stop matching preceding sibling elements.
        /// </param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector PrevUntil(string selector) => PrevUntil(selector, null);

        ///
        /// Get all preceding siblings of each element up to but not including the element matched by the selector,
        /// DOM node, or jQuery object.
        ///
        /// <param name="selector">
        /// A string containing a selector expression to indicate where to stop matching preceding sibling elements.
        /// </param>
        /// <param name="filter">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector PrevUntil(string selector, string filter)
        {
            var validatedSelector = NullOrNotEmpty(() => selector);
            var validatedFilter = NullOrNotEmpty(() => filter);
            var filteredSelector = validatedSelector == null && validatedFilter != null
                ? string.Empty
                : validatedSelector;
            return Chain("prevUntil", FilteredSelector(filteredSelector, validatedFilter), true);
        }

        ///
        /// Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
        ///
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Siblings() => Siblings(null);

        ///
        /// Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
        ///
        /// <param name="selector">A string containing a selector expression to match elements against.</param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Siblings(string selector) => Chain("siblings", NullOrNotEmpty(() => selector));

        /// Reduce the set of matched elements to a subset specified by a range of indexes.
        /// <param name="start">
        /// An integer indicating the 0-based position at which the elements begin to be selected. If negative, it
        /// indicates an offset from the end of the set.
        /// </param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Slice(int start) => Slice(start, null);

        /// Reduce the set of matched elements to a subset specified by a range of indexes.
        /// <param name="start">
        /// An integer indicating the 0-based position at which the elements begin to be selected. If negative, it
        /// indicates an offset from the end of the set.
        /// </param>
        /// <param name="end">
        /// An integer indicating the 0-based position at which the elements stop being selected. If negative, it
        /// indicates an offset from the end of the set. If omitted, the range continues until the end of the set.
        /// </param>
        /// <returns>The Selenium jQuery selector.</returns>
        public JQuerySelector Slice(int start, int? end) =>
            Chain("slice", end.HasValue ? $"{start}, {end}" : start.ToString(InvariantCulture), true);

        /// <inheritdoc />
        protected override JQuerySelector CreateContext(string contextSelector) =>
            new(contextSelector, null, Variable);

        /// <inheritdoc />
        protected override void LoadExternalLibrary(IWebDriver driver) => driver.LoadJQuery();

        [SuppressMessage(SONARQUBE, S3358)]
        private static string FilteredSelector(string selector = null, string filter = null) =>
            selector != null
                ? IsNullOrEmpty(filter)
                    ? $"'{selector.Replace('\'', '"')}'"
                    : $"'{selector.Replace('\'', '"')}', '{filter.Replace('\'', '"')}'"
                : string.Empty;

        [SuppressMessage(SONARQUBE, S3358)]
        private static string GetSelectorString(string selector, bool noWrap = false) =>
            selector == null ? string.Empty : noWrap ? selector.Trim() : $"'{selector.Trim().Replace('\'', '"')}'";

        private JQuerySelector Chain(string name, string selector = null, bool noWrap = false) =>
            new(RawSelector, Context, Variable, $"{_chain}.{name}({GetSelectorString(selector, noWrap)})");

        [SuppressMessage(SONARQUBE, S3242)]
        private JQuerySelector ChainWithContext(string name, string selector, JQuerySelector context) =>
            new(RawSelector, Context, Variable, $".{name}('{selector.Replace('\'', '"')}', {context.Selector})");
    }
}


text:
namespace leaf = boost::leaf;

leaf::result<int *> f();

leaf::result<int> g()
{
    return f(); // Types are incompatible
}


text:
package android.bluetooth;

@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public final class BluetoothUuid
{
  // Fields

  public static final android.os.ParcelUuid AudioSink = null;

  public static final android.os.ParcelUuid AudioSource = null;

  public static final android.os.ParcelUuid AdvAudioDist = null;

  public static final android.os.ParcelUuid HSP = null;

  public static final android.os.ParcelUuid HSP_AG = null;

  public static final android.os.ParcelUuid Handsfree = null;

  public static final android.os.ParcelUuid Handsfree_AG = null;

  public static final android.os.ParcelUuid AvrcpController = null;

  public static final android.os.ParcelUuid AvrcpTarget = null;

  public static final android.os.ParcelUuid ObexObjectPush = null;

  public static final android.os.ParcelUuid Hid = null;

  public static final android.os.ParcelUuid PANU = null;

  public static final android.os.ParcelUuid NAP = null;

  public static final android.os.ParcelUuid BNEP = null;

  public static final android.os.ParcelUuid PBAP_PSE = null;

  public static final android.os.ParcelUuid [] RESERVED_UUIDS = null;

  // Constructors

  public BluetoothUuid(){
  }
  // Methods

  public static boolean isAudioSource(android.os.ParcelUuid arg1){
    return false;
  }
  public static boolean isAudioSink(android.os.ParcelUuid arg1){
    return false;
  }
  public static boolean isAdvAudioDist(android.os.ParcelUuid arg1){
    return false;
  }
  public static boolean isHandsfree(android.os.ParcelUuid arg1){
    return false;
  }
  public static boolean isHeadset(android.os.ParcelUuid arg1){
    return false;
  }
  public static boolean isAvrcpController(android.os.ParcelUuid arg1){
    return false;
  }
  public static boolean isAvrcpTarget(android.os.ParcelUuid arg1){
    return false;
  }
  public static boolean isInputDevice(android.os.ParcelUuid arg1){
    return false;
  }
  public static boolean isPanu(android.os.ParcelUuid arg1){
    return false;
  }
  public static boolean isNap(android.os.ParcelUuid arg1){
    return false;
  }
  public static boolean isBnep(android.os.ParcelUuid arg1){
    return false;
  }
  public static boolean isUuidPresent(android.os.ParcelUuid [] arg1, android.os.ParcelUuid arg2){
    return false;
  }
  public static boolean containsAnyUuid(android.os.ParcelUuid [] arg1, android.os.ParcelUuid [] arg2){
    return false;
  }
  public static boolean containsAllUuids(android.os.ParcelUuid [] arg1, android.os.ParcelUuid [] arg2){
    return false;
  }
  public static int getServiceIdentifierFromParcelUuid(android.os.ParcelUuid arg1){
    return 0;
  }
}


text:
namespace Showcase.Services.Data.Contracts
{
    using System.Collections.Generic;
    using System.Threading.Tasks;

    using Showcase.Data.Models;
    using Showcase.Services.Common;
    using Showcase.Services.Data.Models.Remote;

    public interface IRemoteDataService : IService
    {
        Task<User> Login(string username, string password);

        Task<IEnumerable<User>> UsersInfo(IEnumerable<string> usernames);

        Task<IEnumerable<string>> SearchByUsername(string username, int maxResults = 10);

        Task<RemoteUserProfile> ProfileInfo(string username);

        Task<bool> UsersExist(IEnumerable<string> usernames);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
    android:padding="16dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/dialog_edit_bio"/>
    <EditText
        android:id="@+id/fragment_dialog_edit_bio"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/dialog_edit_location"/>
    <EditText
        android:id="@+id/fragment_dialog_edit_location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

</LinearLayout>


text:
using SolutionsPG.QuickSilver.Core.Exceptions;
using System;

namespace SolutionsPG.QuickSilver.Core.Delegates
{
    public delegate bool FuncTryGet<in T, TResult>(T obj, out TResult result);

    public static partial class DelegateExtensions
    {
        #region " Public methods "

        public static FuncTryGet<T, TResult> AsFuncTryGet<T, TResult>(this Func<T, TResult> action)
        {
            action.ThrowIfArgumentNull(nameof(action));

            return action.AsFuncTryGet_(true);
        }

        public static FuncTryGet<T, TResult> AsFuncTryGet<T, TResult>(this Func<T, TResult> action, bool returnValue)
        {
            action.ThrowIfArgumentNull(nameof(action));

            return action.AsFuncTryGet_(returnValue);
        }

        #endregion //Public methods

        #region " Private methods "

        private static FuncTryGet<T, TResult> AsFuncTryGet_<T, TResult>(this Func<T, TResult> action, bool returnValue)
        {
            return FuncTryGetWrapper;

            bool FuncTryGetWrapper(T t, out TResult result)
            {
                result = action(t);
                return returnValue;
            }
        }

        #endregion //Private methods
    }
}


text:
/**
 * Contains function that dynamically generates the /rtv/metadata
 * JSON file.
 */

import {KV, list, read} from 'worktop/kv';

import {Channel} from './rtv';

// KV Binding via `wrangler.toml` config.
declare const RTV: KV.Namespace;

/**
 * Dynamically generates the /rtv/metadata JSON file.
 *
 * @param origin - origin part of the request URL.
 * @returns Response object with the /rtv/metadata JSON file.
 */
export async function rtvMetadata(origin: string): Promise<Response> {
  console.log('Generating /rtv/metadata');

  const kvSpaces = list(RTV, {metadata: false});
  const rtvs = new Map<string, string>();
  for await (const kvSpace of kvSpaces) {
    await Promise.all(
      kvSpace.keys.map(async (channel) => {
        const rtv = await read<string>(RTV, channel, {
          type: 'text',
        });
        rtvs.set(channel, rtv as string);
      })
    );
  }

  const stableRtv = rtvs.get(Channel.STABLE);
  const ltsRtv = rtvs.get(Channel.LTS);
  const otherRtvs = [...rtvs.values()]
    .filter((rtv) => ![stableRtv, ltsRtv].includes(rtv))
    // Order this list by AMP version number, then by RTV prefix.
    .sort((a, b) => Number(a.slice(0, 2)) - Number(b.slice(0, 2)))
    .sort((a, b) => Number(a.slice(2)) - Number(b.slice(2)));

  return new Response(
    JSON.stringify({
      ampRuntimeVersion: stableRtv,
      ampCssUrl: stableRtv && `${origin}/rtv/${stableRtv}/v0.css`,
      // TODO(danielrozenberg): currently 0, really.
      canaryPercentage: '0.005',
      diversions: otherRtvs,
      ltsRuntimeVersion: ltsRtv,
      ltsCssUrl: ltsRtv && `${origin}/rtv/${ltsRtv}/v0.css`,
    })
  );
}


text:
module DropboxApi::Metadata
  # Example of a serialized {UploadSessionCursor} object:
  #
  # ```json
  # {
  #   "session_id": "AAAAAAAABCJ61k9yZZtn8Q",
  #   "offset":9
  # }
  # ```
  class UploadSessionCursor < Base
    field :session_id, String
    field :offset, Integer

    def offset=(n)
      self[:offset] = n
    end
  end
end


text:
<?php

namespace ApplicationTest\Model\Question;

use Application\Model\Question\Chapter;
use Application\Model\Question\NumericQuestion;

/**
 * @group Model
 */
class ChapterTest extends \ApplicationTest\Model\AbstractModel
{

    public function testQuestionsRelation()
    {
        $chapter = new Chapter();
        $question = new NumericQuestion();

        $this->assertCount(0, $chapter->getQuestions(), 'collection is initialized on creation');

        $question->setChapter($chapter);
        $this->assertCount(1, $chapter->getQuestions(), 'chapter must be notified when question is added');
        $this->assertSame($question, $chapter->getQuestions()->first(), 'original question can be retrieved from chapter');
    }
}


text:
package com.amazonaws.services.budgets.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.budgets.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * DeleteNotificationRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteNotificationRequestMarshaller {

    private static final MarshallingInfo<String> ACCOUNTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("AccountId").build();
    private static final MarshallingInfo<String> BUDGETNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("BudgetName").build();
    private static final MarshallingInfo<StructuredPojo> NOTIFICATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Notification").build();

    private static final DeleteNotificationRequestMarshaller instance = new DeleteNotificationRequestMarshaller();

    public static DeleteNotificationRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(DeleteNotificationRequest deleteNotificationRequest, ProtocolMarshaller protocolMarshaller) {

        if (deleteNotificationRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(deleteNotificationRequest.getAccountId(), ACCOUNTID_BINDING);
            protocolMarshaller.marshall(deleteNotificationRequest.getBudgetName(), BUDGETNAME_BINDING);
            protocolMarshaller.marshall(deleteNotificationRequest.getNotification(), NOTIFICATION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package org.apache.nifi.test.processors;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.ProcessorInitializationContext;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.io.OutputStreamCallback;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DataGeneratorTestProcessor extends AbstractProcessor {

    public static final Relationship REL_SUCCESS = new Relationship.Builder().name("success").build();

    private static final Logger LOG = LoggerFactory.getLogger(DataGeneratorTestProcessor.class);

    private final Set<Relationship> relationships;

    public DataGeneratorTestProcessor() {
        final Set<Relationship> rels = new HashSet<>();
        rels.add(REL_SUCCESS);
        relationships = Collections.unmodifiableSet(rels);
    }

    @Override
    public Set<Relationship> getRelationships() {
        return relationships;
    }

    @Override
    public void onTrigger(final ProcessContext context, final ProcessSession session) {
        FlowFile toRemove = session.get();
        if (toRemove != null) {
            LOG.warn("Removing flow file");
            session.remove(toRemove);
        }

        FlowFile flowFile = session.create();
        final Random random = new Random();
        final byte[] data = new byte[4096];
        random.nextBytes(data);

        flowFile = session.write(flowFile, new OutputStreamCallback() {
            @Override
            public void process(final OutputStream out) throws IOException {
                out.write(data);
            }
        });

        LOG.info("{} transferring {} to success", new Object[]{this, flowFile});
        session.transfer(flowFile, REL_SUCCESS);
        session.commit();
    }

    @Override
    protected void init(final ProcessorInitializationContext context) {
    }

}


text:
import React from 'react';

import Header from '../Components/Header';
import Footer from '../Components/Footer';

const MainLayout = React.createClass({
  render() {
    return (

            {this.props.children}

    );
  },
});

export default MainLayout;


text:
<?php

namespace Kraken\RankingBundle\Controller;

use Doctrine\ORM\EntityRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller as BaseController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Kraken\RankingBundle\Entity\Boiler;
use Kraken\RankingBundle\Entity\Experience;
use Kraken\RankingBundle\Entity\Review;
use Kraken\RankingBundle\Entity\ReviewExperience;
use Kraken\RankingBundle\Form\ReviewForm;

class ReviewController extends BaseController
{
    /**
     * @Route("/dodaj-opinie-o-kotle/{boilerId}", name="ranking_review", defaults={"boilerId" = ""})
     */
    public function reviewAction($boilerId, Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        if (!$this->get('session')->has('review_id')) {
            $review = new Review();

            $form = $this->createFormBuilder($review)
                ->add('boiler', 'entity', [
                    'class' => 'KrakenRankingBundle:Boiler',
                    'label' => 'Wybierz kocioł',
                    'placeholder' => '--- wybierz ---',
                    'query_builder' => function (EntityRepository $er) use ($boilerId) {
                        $qb = $er->createQueryBuilder('b')
                            ->where('b.rejected = false')
                            ->andWhere('b.published = true')
                            ->orderBy('b.name', 'ASC');

                        if ($boilerId) {
                            $qb->andWhere('b.id = :boilerId')
                                ->setParameter('boilerId', $boilerId)
                            ;
                        }

                        return $qb;
                    },
                ])
                ->add('email', 'text', [
                    'label' => 'Twój adres e-mail',
                ])
                ->getForm();
            $form->handleRequest($request);

            if ($form->isValid()) {
                $reviewsPerEmail = $this->getDoctrine()->getRepository('KrakenRankingBundle:Review')->findByEmail($form->get('email')->getData());

                if (count($reviewsPerEmail) > 1) {
                    $this->addFlash('error', 'Z tego adresu e-mail dodane zostały już opinie o dwóch różnych kotłach.');

                    return $this->redirectToRoute('ranking_review');
                }

                $em->persist($review);
                $em->flush();

                $this->get('session')->set('review_id', $review->getId());

                return $this->redirectToRoute('ranking_review');
            }

            return $this->render('KrakenRankingBundle:Ranking:review.html.twig', [
                'form' => $form->createView(),
                'selectedBoiler' => false,
            ]);
        } else {
            $review = $em->getRepository('KrakenRankingBundle:Review')->find($this->get('session')->get('review_id'));

            $form = $this->createForm(ReviewForm::class, $review, ['boiler_id' => $review->getBoiler()->getId()]);

            $form->handleRequest($request);

            if ($form->isValid()) {
                $review->setIp($_SERVER['REMOTE_ADDR']);
                $review->setUserAgent($_SERVER['HTTP_USER_AGENT']);

                $em->persist($review);
                $em->flush();

                $this->get('session')->remove('review_id');

                $this->addFlash(
                    'success',
                    'OK. Twoja opinia została przesłana do poczekalni. Dostaniesz wiadomość jak tylko wejdzie do zestawienia lub skontaktujemy się z tobą gdyby były jakieś wątpliwości.'
                );

                return $this->redirectToRoute('ranking_review');
            }

            return $this->render('KrakenRankingBundle:Ranking:review.html.twig', [
                'form' => $form->createView(),
                'selectedBoiler' => $review->getBoiler(),
            ]);
        }
    }

    /**
     * @Route("/anuluj-opinie-o-kotle/{review}", name="ranking_review_revoke")
     */
    public function revokeReviewAction(Review $review, Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $review->setRevoked(true);
        $em->persist($review);
        $em->flush();

        $this->addFlash(
            'success',
            'OK. Twoja opinia została usunięta z publicznego podsumowania.'
        );

        return $this->redirectToRoute('ranking_review');
    }
}


text:
package io.github.josehsantos.hack.lang.psi.impl;

import com.intellij.lang.ASTNode;
import com.intellij.navigation.ItemPresentation;
import com.intellij.navigation.NavigationItem;
import com.intellij.psi.PsiElement;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.PlatformIcons;
import io.github.josehsantos.hack.lang.psi.HackPsiNamedVariableElement;
import io.github.josehsantos.hack.lang.psi.HackVariableIdentifier;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

import static com.intellij.psi.util.PsiTreeUtil.*;

/**
 * Created by josesantos on 13/11/14.
 */
public abstract class HackPsiNamedVariableElementImpl extends HackPsiElementImpl implements HackPsiNamedVariableElement {

    public HackPsiNamedVariableElementImpl(ASTNode node) {
        super(node);
    }

    @Override
    public PsiElement setName(@NonNls @NotNull String s) throws IncorrectOperationException {
        //getIdentifier().setName(s);
        return this;
    }

    @Override
    public String getName() {
        return getIdentifier().getText();
    }

    @Nullable
    public ItemPresentation getPresentation() {
        final PsiElement parent = getParent();
        if (parent instanceof NavigationItem) {
            return ((NavigationItem) parent).getPresentation();
        }
        final HackPsiNamedVariableElementImpl hackPsiNamedVariableElement = this;
        return new ItemPresentation() {
            @Nullable
            @Override
            public String getPresentableText() {
                return hackPsiNamedVariableElement.getName();
            }

            @Nullable
            @Override
            public String getLocationString() {
                return null;
            }

            @Nullable
            @Override
            public Icon getIcon(boolean b) {
                return PlatformIcons.VARIABLE_ICON;
            }
        };
    }

    @Override
    public Icon getIcon(int flags) {
        final ItemPresentation presentation = getPresentation();
        return presentation == null ? super.getIcon(flags) : presentation.getIcon(true);
    }

    @Nullable
    @Override
    public PsiElement getNameIdentifier() {
        return getIdentifier();
    }

    @NotNull
    @Override
    public HackVariableIdentifier getIdentifier() {
        return findChildOfType(this, HackVariableIdentifier.class);
    }

    @NotNull
    @Override
    public SearchScope getUseScope() {
        //TODO: implements a searchScopeManager class
        return new LocalSearchScope(getContainingFile());
    }
}