text:
/** \file
 *
 *  \brief            cuBLAS handles
 *
 *  \date             Created:  Jul 12, 2014
 *  \date             Modified: $Date$
 *
 *  \authors          mauro <mauro@iis.ee.ethz.ch>
 *
 *  \version          $Revision$
 */
#ifndef LINALG_CUDA_CUDA_CUBLAS_H_
#define LINALG_CUDA_CUDA_CUBLAS_H_

#include "../preprocessor.h"

#ifdef HAVE_CUDA

#   include <cuda_runtime.h> // various CUDA routines
#   include <cublas_v2.h>

#   include "../profiling.h"
#   include "cuda_checks.h"
#   include "cuda_common.h"
#   include "../streams.h"

namespace LinAlg {

namespace CUDA {

namespace cuBLAS {

# ifndef USE_LOCAL_CUDA_HANDLES

/// Global array of cuBLAS handles (one for each GPU).
// "Defined" in src/CUDA/cuda_cublas.cc
extern cublasHandle_t* handles;

/** \brief            A wrapper to initialize the global cuBLAS handles
 */
inline void init() {

  PROFILING_FUNCTION_HEADER

  using LinAlg::GPU::GPU_structures_initialized;
  using LinAlg::GPU::n_devices;
  using LinAlg::CUDA::cuBLAS::handles;

  if (GPU_structures_initialized == true) return;

  handles = new cublasHandle_t[n_devices];

  int prev_device;
  checkCUDA(cudaGetDevice(&prev_device));

  for (int device_id = 0; device_id < n_devices; ++device_id) {

    checkCUDA(cudaSetDevice(device_id));
    checkCUBLAS(cublasCreate(&(handles[device_id])));

  }

  checkCUDA(cudaSetDevice(prev_device));

}

/** \brief            Destroy the global cuBLAS handles
 */
inline void destroy() {

  PROFILING_FUNCTION_HEADER

  using LinAlg::GPU::GPU_structures_initialized;
  using LinAlg::GPU::n_devices;
  using LinAlg::CUDA::cuBLAS::handles;

  if (GPU_structures_initialized == false) return;

  for (int device = 0; device < n_devices; ++device) {

    checkCUBLAS(cublasDestroy(handles[device]));

  }

  delete[] handles;

}

# endif /* not USE_LOCAL_CUDA_HANDLES */

/** \brief            Prepare a call to cuBLAS
 *
 *  \param[in]        stream
 *                    Stream to use for the cuBLAS call(s). Note that the
 *                    device to which the stream is bound, will used for the
 *                    subsequent call to cuBLAS.
 *
 *  \param[in,out]    previous_device
 *                    Integer storing the device that was active before the
 *                    cuBLAS call(s)
 *
 *  \param[in,out]    previous_stream
 *                    Stream storing the stream that was active before the
 *                    cuBLAS call(s)
 *
 *  \returns          Pointer to a handle for the cuBLAS call(s)
 *
 *  \note             This function calls cudaSetDevice and cublasSetStream
 *                    without resetting it, so call the cuBLAS function
 *                    immediately after it
 *
 *  \example
 *
 *    using LinAlg::CUDA::cuBLAS::prepare_cublas;
 *    using LinAlg::CUDA::cuBLAS::finish_cublas;
 *
 *    int          prev_device = 0;
 *    cudaStream_t prev_cuda_stream;
 *
 *    auto handle = prepare_cublas(some_stream, &prev_device,
 *                                 &prev_cuda_stream);
 *    BLAS::cuBLAS::xFOO(*handle, some, arguments);
 *    BLAS::cuBLAS::xBAR(*handle, other, arguments);
 *    finish_cublas(some_stream, &prev_device, &prev_cuda_stream, handle);
 *
 *
 */
inline cublasHandle_t* prepare_cublas(Stream& stream, int* previous_device,
                                      cudaStream_t* previous_stream) {

  PROFILING_FUNCTION_HEADER

  checkCUDA(cudaGetDevice(previous_device));

  checkCUDA(cudaSetDevice(stream.device_id));

  cublasHandle_t* handle;

# ifndef USE_LOCAL_CUDA_HANDLES

  using LinAlg::CUDA::cuBLAS::handles;

  checkCUBLAS(cublasGetStream(handles[stream.device_id], previous_stream));

  checkCUBLAS(cublasSetStream(handles[stream.device_id], stream.cuda_stream));

  handle = &(handles[stream.device_id]);

# else

  handle = new cublasHandle_t[1];

  checkCUBLAS(cublasCreate(handle));

  // Here we don't care about storing the  previous_stream of the handle,
  // obviously
  checkCUBLAS(cublasSetStream(*handle, stream.cuda_stream));

# endif

  return handle;

}

/** \brief            Finish a call to cuBLAS
 *
 *  \param[in]        stream
 *                    Stream used for the preceeding cuBLAS call(s).
 *
 *  \param[in]        previous_device
 *                    Integer storing the device that was active before the
 *                    call
 *
 *  \param[in]        previous_stream
 *                    Previous stream
 *
 *  \param[in,out]    handle
 *                    Handle used for the preceeding cuBLAS call(s).
 *
 *  \note             This call will reset the CUDA device to the one that was
 *                    active previous to the call to prepare() above. Call
 *                    immediately after the last cuBLAS call using this
 *                    handle. Don't use the handle after this call.
 *
 *  \example          See prepare();
 */
inline void finish_cublas(Stream& stream, int* previous_device,
                          cudaStream_t* previous_stream,
                          cublasHandle_t* handle) {

  PROFILING_FUNCTION_HEADER

  checkCUDA(cudaSetDevice(*previous_device));

  stream.cuda_synchronized = false;

# ifndef USE_LOCAL_CUDA_HANDLES

  checkCUBLAS(cublasSetStream(handles[stream.device_id], *previous_stream));

# else

  checkCUBLAS(cublasDestroy(*handle));

  delete[] handle;

# endif

}

} /* namespace LinAlg::CUDA::cuBLAS */

} /* namespace LinAlg::CUDA */

} /* namespace LinAlg */

#endif /* HAVE_CUDA */

#endif /* LINALG_CUDA_CUDA_CUBLAS_H_ */


text:
void Features::Init(Handle<Object> target) {
  NanScope();

  NODE_SET_METHOD(target, "ImageSimilarity", Similarity);
}

class AsyncDetectSimilarity: public NanAsyncWorker {
public:
  AsyncDetectSimilarity(NanCallback *callback, cv::Mat image1, cv::Mat image2) :
      NanAsyncWorker(callback),
      image1(image1),
      image2(image2),
      dissimilarity(0) {
  }

  ~AsyncDetectSimilarity() {
  }

  void Execute() {

    cv::Ptr<cv::FeatureDetector> detector = cv::FeatureDetector::create("ORB");
    cv::Ptr<cv::DescriptorExtractor> extractor =
        cv::DescriptorExtractor::create("ORB");
    cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create(
        "BruteForce-Hamming");

    std::vector<cv::DMatch> matches;

    cv::Mat descriptors1 = cv::Mat();
    cv::Mat descriptors2 = cv::Mat();

    std::vector<cv::KeyPoint> keypoints1;
    std::vector<cv::KeyPoint> keypoints2;

    detector->detect(image1, keypoints1);
    detector->detect(image2, keypoints2);

    extractor->compute(image1, keypoints1, descriptors1);
    extractor->compute(image2, keypoints2, descriptors2);

    matcher->match(descriptors1, descriptors2, matches);

    double max_dist = 0;
    double min_dist = 100;

    //-- Quick calculation of max and min distances between keypoints
    for (int i = 0; i < descriptors1.rows; i++) {
      double dist = matches[i].distance;
      if (dist < min_dist) {
        min_dist = dist;
      }
      if (dist > max_dist) {
        max_dist = dist;
      }
    }

    //-- Draw only "good" matches (i.e. whose distance is less than 2*min_dist,
    //-- or a small arbitary value ( 0.02 ) in the event that min_dist is very
    //-- small)
    //-- PS.- radiusMatch can also be used here.
    std::vector<cv::DMatch> good_matches;
    double good_matches_sum = 0.0;

    for (int i = 0; i < descriptors1.rows; i++) {
      double distance = matches[i].distance;
      if (distance <= std::max(2 * min_dist, 0.02)) {
        good_matches.push_back(matches[i]);
        good_matches_sum += distance;
      }
    }

    dissimilarity = (double) good_matches_sum / (double) good_matches.size();
  }

  void HandleOKCallback() {
    NanScope();

    Handle<Value> argv[2];

    argv[0] = NanNull();
    argv[1] = NanNew<Number>(dissimilarity);

    callback->Call(2, argv);
  }

private:
  cv::Mat image1;
  cv::Mat image2;
  double dissimilarity;
};

NAN_METHOD(Features::Similarity) {
  NanScope();

  REQ_FUN_ARG(2, cb);

  cv::Mat image1 = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject())->mat;
  cv::Mat image2 = ObjectWrap::Unwrap<Matrix>(args[1]->ToObject())->mat;

  NanCallback *callback = new NanCallback(cb.As<Function>());

  NanAsyncQueueWorker( new AsyncDetectSimilarity(callback, image1, image2) );
  NanReturnUndefined();
}

#endif

redpajama_set_name: RedPajamaGithub


text:
package commandline.command.help.print;

import commandline.command.CommandDefinition;
import commandline.command.CommandDefinitionList;
import commandline.exception.ArgumentNullException;
import org.jetbrains.annotations.NotNull;
import org.nocrala.tools.texttablefmt.BorderStyle;
import org.nocrala.tools.texttablefmt.Table;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.TreeSet;

public class CommandListHelpPrinter extends HelpPrinter {
	@NotNull
	private final CommandDefinitionList commandDefinitions;

	public CommandListHelpPrinter(@NotNull CommandDefinitionList commandDefinitions, @NotNull OutputStream outputStream) {
		super(outputStream);
		if (commandDefinitions == null) {
			throw new ArgumentNullException();
		}
		this.commandDefinitions = commandDefinitions;
	}

	@NotNull
	public CommandDefinitionList getCommandDefinitions() {
		return this.commandDefinitions;
	}

	@NotNull
	private Table createArgumentsTable() {
		Table table;
		BorderStyle borderStyle;
		TreeSet<CommandDefinition> sortedDefinitions;

		//FIXME Für den unicode style muss unicode in der windows console freigeschaltet werden
		//        borderStyle = BorderStyle.UNICODE_BOX;
		borderStyle = createArgumentsBorderStyle();
		table = new Table(2, borderStyle);
		table.addCell("Command");
		table.addCell("Description");
		sortedDefinitions = new TreeSet<>();
		//Sorts the command list before printing ist.
		for (CommandDefinition definition : getCommandDefinitions().getMap().values()) {
			sortedDefinitions.add(definition);
		}
		for (CommandDefinition definition : sortedDefinitions) {
			table.addCell(definition.getName());
			table.addCell(definition.getDescription());
		}

		return table;
	}

	@NotNull
	private Table createHeaderTable() {
		Table table;
		BorderStyle borderStyle;

		//FIXME Für den unicode style muss unicode in der windows console freigeschaltet werden
		//        borderStyle = BorderStyle.UNICODE_BOX;
		borderStyle = createHeaderBorderStyle();
		table = new Table(2, borderStyle);
		table.addCell("Command List");

		return table;
	}

	@Override
	public void print() {
		Table headerTable;
		Table argumentsTable;
		PrintWriter writer;

		headerTable = createHeaderTable();
		argumentsTable = createArgumentsTable();
		writer = new PrintWriter(getOutputStream());
		writer.println(headerTable.render());
		writer.println(argumentsTable.render());
		writer.println("Execute \"help -c <command-name>\" to show more information of a specific command or use the " +
				"flag \"--help\" or \"-h\" when executing the command, e.g. \"add-browser -h\"");
		writer.flush();
		writer.close();
	}

	@NotNull
	private BorderStyle createArgumentsBorderStyle() {
		return new BorderStyle("", "", "", "", "", "", "", "", "", "", "", "", "", "   ", "", "", "");
	}

	@NotNull
	private BorderStyle createHeaderBorderStyle() {
		return new BorderStyle("", "-", "-", "", "", "-", "-", "", "", "-", "-", "", "", "", "", "", "");
	}
}


text:
package org.apache.kerby.kerberos.kerb.type.base;

import org.apache.kerby.asn1.Asn1FieldInfo;
import org.apache.kerby.asn1.EnumType;
import org.apache.kerby.asn1.ExplicitField;
import org.apache.kerby.asn1.type.Asn1Integer;
import org.apache.kerby.asn1.type.Asn1OctetString;
import org.apache.kerby.kerberos.kerb.type.KrbSequenceType;

/**
 * KRB-TOKEN_VALUE ::= SEQUENCE {
 * token-format [0] INTEGER,
 * token-value  [1] OCTET STRING,
 * }
 */
public class KrbTokenBase extends KrbSequenceType {

    protected enum KrbTokenField implements EnumType {
        TOKEN_FORMAT,
        TOKEN_VALUE;

        @Override
        public int getValue() {
            return ordinal();
        }

        @Override
        public String getName() {
            return name();
        }
    }

    static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[]{
            new ExplicitField(KrbTokenField.TOKEN_FORMAT, Asn1Integer.class),
            new ExplicitField(KrbTokenField.TOKEN_VALUE, Asn1OctetString.class)
    };

    /**
     * Default constructor.
     */
    public KrbTokenBase() {
        super(fieldInfos);
    }

    /**
     * Get token format.
     * @return The token format
     */
    public TokenFormat getTokenFormat() {
        Integer value = getFieldAsInteger(KrbTokenField.TOKEN_FORMAT);
        return TokenFormat.fromValue(value);
    }

    /**
     * Set token format.
     * @param tokenFormat The token format
     */
    public void setTokenFormat(TokenFormat tokenFormat) {
        setFieldAsInt(KrbTokenField.TOKEN_FORMAT, tokenFormat.getValue());
    }

    /**
     * Get token value.
     * @return The token value
     */
    public byte[] getTokenValue() {
        return getFieldAsOctets(KrbTokenField.TOKEN_VALUE);
    }

    /**
     * Set token value.
     * @param tokenValue The token value
     */
    public void setTokenValue(byte[] tokenValue) {
        setFieldAsOctets(KrbTokenField.TOKEN_VALUE, tokenValue);
    }

}


text:
const env = process.env.NODE_ENV;

if (env === 'commonjs' || env === 'es') {
  module.exports = {
    ignore: [
      '*.jest.js',
      '*.e2e.js',
      '*.ssr.js',
      '*.example.js',
      'source/demo',
      'source/jest-*.js',
      'source/TestUtils.js',
    ],
    plugins: [
      '@babel/plugin-transform-runtime',
      '@babel/plugin-proposal-class-properties',
      '@babel/plugin-transform-flow-comments',
      ['flow-react-proptypes', {deadCode: true, useESModules: true}],
      ['transform-react-remove-prop-types', {mode: 'wrap'}],
    ],
    presets: [
      ['@babel/preset-env', {modules: false}],
      '@babel/preset-react',
      '@babel/preset-flow',
    ],
  };

  if (env === 'commonjs') {
    module.exports.plugins.push('@babel/plugin-transform-modules-commonjs');
  }
}

if (env === 'rollup') {
  module.exports = {
    comments: false,
    plugins: [
      '@babel/plugin-external-helpers',
      '@babel/plugin-proposal-class-properties',
    ],
    presets: [
      ['@babel/preset-env', {modules: false}],
      '@babel/preset-react',
      '@babel/preset-flow',
    ],
  };
}

if (env === 'development') {
  module.exports = {
    plugins: ['@babel/plugin-proposal-class-properties'],
    presets: ['@babel/preset-react', '@babel/preset-flow'],
  };
}

if (env === 'production') {
  module.exports = {
    comments: false,
    plugins: [
      '@babel/plugin-transform-runtime',
      '@babel/plugin-proposal-class-properties',
    ],
    presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-flow'],
  };
}

if (env === 'test') {
  module.exports = {
    comments: false,

    plugins: [
      '@babel/plugin-transform-modules-commonjs',
      '@babel/plugin-proposal-class-properties',
    ],
    presets: ['@babel/preset-react', '@babel/preset-flow'],
  };
}


text:
/**
 * Created by mac on 04.03.17.
 */
package ru.bildovich.models;


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Functional.Contracts;
using Functional.Implementation;
using Functional.Test;

using Test.Contracts;

using Tests;
namespace Tests {
    [Export(typeof(ISyncTestCase))]
    public class gte_int : ISyncTestCase {
        private const string _Name = "gte int,F_gte_int";
        private const string _Description = "F.gte_int(left,right) works correctly";
        public string TestFile { get { return "TestCaseGte.cs"; } }
        public Func<bool> Run { get; private set; }
        private static bool _Run() {
            bool result = true;
            result = result && (true  == F.gte_int(1,0));
            result = result && (true  == F.gte_int(0,0));
            result = result && (false == F.gte_int(0,1));
            return result;
        }
        private IList<int> coverage = new List<int>();
        private IList<int> feature = new List<int>();
        public int ID { get; private set; }
        public string Name { get; private set; }
        public string Description { get; private set; }

        public IEnumerable<int> Coverage { get { return this.coverage; } }
        public IEnumerable<int> Feature { get { return this.feature; } }
        public gte_int() {
            this.ID = 0;
            this.Name = _Name;
            this.Description = _Description;
            this.Run = _Run;

            this.feature.Add(TestCoverage.Test_All);
            this.feature.Add(TestCoverage.F);
            this.feature.Add(TestCoverage.F_gte);
            this.feature.Add(TestCoverage.F_gte_int);

            this.coverage.Add(TestCoverage.F);
            this.coverage.Add(TestCoverage.F_gte);
            this.coverage.Add(TestCoverage.F_gte_int);
        }
    }

    [Export(typeof(ISyncTestCase))]
    public class gte_long : ISyncTestCase {
        private const string _Name = "gte long,F_gte_long";
        private const string _Description = "F.gte_long(left,right) works correctly";
        public string TestFile { get { return "TestCaseGte.cs"; } }
        public Func<bool> Run { get; private set; }
        private static bool _Run() {
            bool result = true;
            result = result && (true  == F.gte_long(1L,0L));
            result = result && (true  == F.gte_long(0L,0L));
            result = result && (false == F.gte_long(0L,1L));
            return result;
        }
        private IList<int> coverage = new List<int>();
        private IList<int> feature = new List<int>();
        public int ID { get; private set; }
        public string Name { get; private set; }
        public string Description { get; private set; }

        public IEnumerable<int> Coverage { get { return this.coverage; } }
        public IEnumerable<int> Feature { get { return this.feature; } }
        public gte_long() {
            this.ID = 0;
            this.Name = _Name;
            this.Description = _Description;
            this.Run = _Run;

            this.feature.Add(TestCoverage.Test_All);
            this.feature.Add(TestCoverage.F);
            this.feature.Add(TestCoverage.F_gte);
            this.feature.Add(TestCoverage.F_gte_long);

            this.coverage.Add(TestCoverage.F);
            this.coverage.Add(TestCoverage.F_gte);
            this.coverage.Add(TestCoverage.F_gte_long);
        }
    }

    [Export(typeof(ISyncTestCase))]
    public class gte_short : ISyncTestCase {
        private const string _Name = "gte short,F_gte_short";
        private const string _Description = "F.gte_short(left,right) works correctly";
        public string TestFile { get { return "TestCaseGte.cs"; } }
        public Func<bool> Run { get; private set; }
        private static bool _Run() {
            bool result = true;
            result = result && (true  == F.gte_short(1,0));
            result = result && (true  == F.gte_short(0,0));
            result = result && (false == F.gte_short(0,1));
            return result;
        }
        private IList<int> coverage = new List<int>();
        private IList<int> feature = new List<int>();
        public int ID { get; private set; }
        public string Name { get; private set; }
        public string Description { get; private set; }

        public IEnumerable<int> Coverage { get { return this.coverage; } }
        public IEnumerable<int> Feature { get { return this.feature; } }
        public gte_short() {
            this.ID = 0;
            this.Name = _Name;
            this.Description = _Description;
            this.Run = _Run;

            this.feature.Add(TestCoverage.Test_All);
            this.feature.Add(TestCoverage.F);
            this.feature.Add(TestCoverage.F_gte);
            this.feature.Add(TestCoverage.F_gte_short);

            this.coverage.Add(TestCoverage.F);
            this.coverage.Add(TestCoverage.F_gte);
            this.coverage.Add(TestCoverage.F_gte_short);
        }
    }
}


text:
<?php

use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class RabbitMQQueue {

	const EXCHANGE = 'tweet_exchange';
	const QUEUE = 'tweets';

	/**
	 * @var $channel AMQPChannel
	 */
	protected $channel;

	/**
	 * @var $connection AMQPStreamConnection
	 */
	public $connection;

	public function __construct() {
		$this->connect();
	}

	/**
	 * Open a connection
	 *
	 * @return bool
	 */
	protected function connect() {
		try {
			$this->connection = new AMQPStreamConnection( 'rabbitmq', 5672, 'user', 'pass' );
			$this->channel = $this->connection->channel();
			$this->channel->queue_declare( self::QUEUE, false, false, false, false );
			$this->channel->exchange_declare( self::EXCHANGE, 'direct', false, false, false );
			$this->channel->queue_bind( self::QUEUE, self::EXCHANGE );
		} catch ( Exception $e ) {
			echo "warning: " . $e->getMessage();
			return false;
		}

		return true;
	}

	/**
	 * Clean up the connection
	 */
	protected function disconnect() {
		$this->channel && $this->channel->close();
		$this->connection && $this->connection->close();
	}

	/**
	 * Get the protected channel
	 *
	 * @return AMQPChannel
	 */
	public function getChannel() {
		return $this->channel;
	}

	/**
	 * Send a message to the RabbitMQ queue
	 *
	 * @param string $message
	 */
	public function sendMessage( string $message ) {
		if ( ! $this->connection->isConnected() ) {
			$this->connect();
		}

		try {
			$msg = new AMQPMessage( $message );
			$this->channel->basic_publish( $msg, self::EXCHANGE );
		} catch ( Exception $e ) {

		}
	}
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Epicr. syst. mycol. (Upsaliae) 54 (1838)

#### Original name
Agaricus rasilis Fr., 1838

### Remarks
null


text:
if [[ "$TRAVIS_PULL_REQUEST" != "false" ]]; then
  echo "This is a pull request. No encription will be done."
  exit 0
fi

# removing files "./" protection
BLS_TMP="${BLS_TMP//[[:space:]]/}"
BLS_TMP="${BLS_TMP:=__tmp}"

mkdir -p ./$BLS_TMP

openssl aes-256-cbc -k "$BLS_ENCRYPTION_SECRET" -in scripts/profile/$PROFILE_NAME.mobileprovision.enc -d -a -out ./$BLS_TMP/$PROFILE_NAME.mobileprovision
openssl aes-256-cbc -k "$BLS_ENCRYPTION_SECRET" -in scripts/certs/dist.cer.enc -d -a -out ./$BLS_TMP/dist.cer
openssl aes-256-cbc -k "$BLS_ENCRYPTION_SECRET" -in scripts/certs/dist.p12.enc -d -a -out ./$BLS_TMP/dist.p12

security create-keychain -p travis ios-build.keychain
security default-keychain -s ios-build.keychain
security unlock-keychain -p travis ios-build.keychain
security import ./scripts/certs/apple.cer -k ~/Library/Keychains/ios-build.keychain -T /usr/bin/codesign
security import ./$BLS_TMP/dist.cer -k  ~/Library/Keychains/ios-build.keychain -T /usr/bin/codesign
security import ./$BLS_TMP/dist.p12 -k  ~/Library/Keychains/ios-build.keychain -P $BLS_KEY_PASSWORD -T /usr/bin/codesign
mkdir -p ~/Library/MobileDevice/Provisioning\ Profiles
mv ./$BLS_TMP/$PROFILE_NAME.mobileprovision ~/Library/MobileDevice/Provisioning\ Profiles/


text:
package org.openntf.slack.core;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import lotus.domino.Session;

import com.ibm.xsp.extlib.util.ExtLibUtil;

public abstract class AbstractCommandHandler {

	protected final SlashCommand slashCommand;
	protected final HttpServletResponse response;

	public AbstractCommandHandler(SlashCommand slashCommand, HttpServletResponse response) {
		this.slashCommand = slashCommand;
		this.response = response;
	}

	public SlashCommand getSlashCommand() {
		return slashCommand;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	protected void addResponseHeader(String name, String value) {
		response.addHeader(name, value);
	}

	protected void setContentType(String type) {
		addResponseHeader("Content-Type", type);
	}

	protected void sendBack(String content) {
		PrintWriter writer;

		try {
			writer = response.getWriter();
			writer.append(content);
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public abstract void run();

	// This is a dependency!
	protected Session getSession() {
		return ExtLibUtil.getCurrentSession();
	}

}


text:
#ifndef __TBA_STL_THREADEDCLASS_H
#define __TBA_STL_THREADEDCLASS_H

/*
 * threadedClass.h
 *
 * The C++ way for thread handling.
 *
 * Author: Elad Raz <e@eladraz.com>
 */
#include "xStl/types.h"
#include "xStl/os/thread.h"

/*
 * C++ Thread manager. In order to generate a C++ thread inherit from this class
 *
 * Usage:
 *    class cMyThread : public cThreadedClass {
 *    public:
 *          virtual void run() {
 *            // Do some work here...
 *          }
 *    };
 *
 *    // Open 3 threads
 *    cMyThread a, b, c;
 *    a.start();
 *    b.start();
 *    c.start();
 *
 *    // Wait until all thread executed
 *    a.wait();
 */
class cThreadedClass {
public:
    /*
     * Virtual empty destructor. This class should be inherit from.
     */
    virtual ~cThreadedClass();

    /*
     * Implement here the code of the newly constructed thread.
     */
    virtual void run() = 0;

    /*
     * Generate the thread.
     * Throw exception if the 'start()' command was already being executed.
     */
    void start();

    /*
     * Wait until the thread will finish it's execution.
     * If the thread wasn't start yet, the function immediatly return
     */
    void wait();

    /*
     * Return true if the 'run()' function completed normally
     */
    bool isDone() const;

    /*
     * Return the thread API class.
     *
     * This function is implemented for both const and non-const functions.
     */
    cThread& getThreadHandle();
    const cThread& getThreadHandle() const;

protected:
    /*
     * Default constructor.
     */
    cThreadedClass();

    // Deny copy-constructor and operator =
    cThreadedClass(const cThreadedClass& other);
    cThreadedClass& operator = (const cThreadedClass& other);

    // The instance of the running thread.
    cThread m_theInstance;
    // Set to true when the thread is running.
    volatile bool m_isStarted;
    // Set to true when the thread died.
    volatile bool m_isDone;

private:
    /*
     * Called when the 'start()' function is called.
     *
     * context - The context
     *
     * IMPLEMENTATION NOTE:
     *   Let's consider the following case (bug case):
     *     void generateThread() {
     *        MyThread a;
     *        a.start();
     *     }
     *   The context of 'a' variable will be move to the
     *   'threadedClassThreadFunction' but also a will be terminated by invoking
     *   the class destructor. This caused some kind of a race-condition.
     *   The internal implementation should guarantee that this cases will not
     *   crash the system.
     */
    static void* threadedClassThreadFunction(void* context);

    // Private premature death.
    volatile bool m_isStarted1;
};

#endif // __TBA_STL_THREADEDCLASS_H


text:
#include "stdafx.h"

// textures/windy.cpp*
#include "textures/windy.h"

// WindyTexture Method Definitions
WindyTexture<Float> *CreateWindyFloatTexture(const Transform &tex2world,
                                             const TextureParams &tp) {
    // Initialize 3D texture mapping _map_ from _tp_
    TextureMapping3D *map = new IdentityMapping3D(tex2world);
    return new WindyTexture<Float>(map);
}

WindyTexture<Spectrum> *CreateWindySpectrumTexture(const Transform &tex2world,
                                                   const TextureParams &tp) {
    // Initialize 3D texture mapping _map_ from _tp_
    TextureMapping3D *map = new IdentityMapping3D(tex2world);
    return new WindyTexture<Spectrum>(map);
}


text:
namespace boost { namespace mpl {

template< typename Tag > struct erase_impl;
template< typename Sequence, typename First, typename Last > struct erase;

}}

#endif // BOOST_MPL_ERASE_FWD_HPP_INCLUDED


text:
<?php

namespace app\modules\inventario\models\core;

use Yii;
use app\components\core\IdentificableInterface;
use app\components\core\LoadableActiveRecord;

/**
 * This is the model class for table "TBL_ITEMSCONSUMIBLES".
 *
 * @property integer $ITCO_ID
 * @property integer $ITEM_ID
 * @property integer $estadoConsumible_id
 * @property double $ITCO_MIN
 * @property double $ITCO_MAX
 * @property TBLESTADOSCONSUMIBLE $estadoConsumible
 * @property TBLITEMS $iTEM
 * @property TBLMATERIALES[] $tBLMATERIALESs
 * @property TBLREACTIVOS[] $tBLREACTIVOSs
 */
class ItemConsumible extends LoadableActiveRecord implements IdentificableInterface
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'TBL_ITEMSCONSUMIBLES';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ITEM_ID', 'ESCO_ID', 'ITCO_MIN'], 'required'],
            [['ITEM_ID', 'ESCO_ID'], 'integer'],
            [['ITCO_MIN', 'ITCO_MAX'], 'number'],
            //[['ESCO_ID'], 'exist', 'skipOnError' => true, 'targetClass' => EstadoConsumible::className(), 'targetAttribute' => ['ESCO_ID' => 'ESCO_ID']],
            [['ITEM_ID'], 'exist', 'skipOnError' => true, 'targetClass' => Items::className(), 'targetAttribute' => ['ITEM_ID' => 'ITEM_ID']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ITCO_ID' => 'CONSUMIBLE',
            'ITEM_ID' => 'ID',
            //'ESCO_ID' => 'ESTADO',
            'ITCO_MIN' => 'MINIMAS',
            'ITCO_MAX' => 'MAXIMAS',
        ];
    }

    public function getId()
    {
        return $this->ITCO_ID;
    }
    public function setId($value = 0)
    {
         $this->ITCO_ID = $value;
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    /*public function getEstadoConsumible()
    {
        return $this->hasOne(EstadoConsumible::className(), ['ESCO_ID' => 'ESCO_ID']);
    }*/

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getItem()
    {
        return $this->hasOne(Items::className(), ['ITEM_ID' => 'ITEM_ID']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMateriales()
    {
        return $this->hasMany(Material::className(), ['ITCO_ID' => 'ITCO_ID']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getReactivos()
    {
        return $this->hasMany(Reactivo::className(), ['ITCO_ID' => 'ITCO_ID']);
    }

    public function getRanges( $returnQuery = false )
    {
        $query = RangoConsumible::find()->where( [ "ITCO_ID" => $this->id ] );

        if($returnQuery) {
            return $query;
        }

        $ranges = $query->all();
        // - - - - - - - - - - -
        $ranges = isset($ranges) && !empty($ranges) ? $ranges : RangoConsumible::generateRangeFromStates();

        return $ranges;
    }
}


text:
package main

import (
	"fmt"
	"net/http"

	"github.com/PuerkitoBio/goquery"
	"github.com/goshinobi/client"
	"github.com/goshinobi/ipchecker"
)

func init() {
	ipchecker.RegistChecker(myIPChecker)
}

func myIPChecker(c *http.Client) string {
	result := ""
	url := "http://www.ugtop.com/spill.shtml"
	resp, err := c.Get(url)
	if err != nil {
		return ""
	}
	doc, err := goquery.NewDocumentFromResponse(resp)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	doc.Find("table").Find("tbody").Each(func(i int, s *goquery.Selection) {
		if i == 1 {
			s.Find("tr").Each(func(i int, s *goquery.Selection) {
				if i == 2 {
					result = s.Find("font").Text()
				}
			})
		}
	})

	return result
}

func main() {
	c := client.NewClient(client.ClientCfg{}, client.ClientCfg{}, client.ClientCfg{})
	fmt.Println(c.Len())
	torClient := client.NewClientTor(10)
	c.Add(torClient)

	fmt.Println(c.Len())
}


text:
module Scheme.Printer where

import Scheme.Types
import Data.List

printLisp :: AST -> String
printLisp (ASTAtom name) = name
printLisp (ASTNumber number) = show number
printLisp (ASTLambda args body) = "(lambda (" ++ argsString ++ ") " ++ bodyString ++ ")"
  where argsString = intercalate " " $ map printLisp args
        bodyString = printLisp body
printLisp (ASTList body) = "(" ++ intercalate " " (map printLisp body) ++ ")"


text:
pub use self::accept::Accept;
pub use self::access_control_allow_headers::AccessControlAllowHeaders;
pub use self::access_control_allow_methods::AccessControlAllowMethods;
pub use self::access_control_allow_origin::AccessControlAllowOrigin;
pub use self::access_control_max_age::AccessControlMaxAge;
pub use self::access_control_request_headers::AccessControlRequestHeaders;
pub use self::access_control_request_method::AccessControlRequestMethod;
pub use self::accept_charset::AcceptCharset;
pub use self::accept_encoding::AcceptEncoding;
pub use self::accept_language::AcceptLanguage;
pub use self::accept_ranges::AcceptRanges;
pub use self::allow::Allow;
pub use self::authorization::{Authorization, Scheme, Basic};
pub use self::cache_control::{CacheControl, CacheDirective};
pub use self::connection::{Connection, ConnectionOption};
pub use self::content_length::ContentLength;
pub use self::content_encoding::ContentEncoding;
pub use self::content_language::ContentLanguage;
pub use self::content_type::ContentType;
pub use self::cookie::Cookie;
pub use self::date::Date;
pub use self::etag::ETag;
pub use self::expect::Expect;
pub use self::expires::Expires;
pub use self::from::From;
pub use self::host::Host;
pub use self::if_match::IfMatch;
pub use self::if_modified_since::IfModifiedSince;
pub use self::if_none_match::IfNoneMatch;
pub use self::if_unmodified_since::IfUnmodifiedSince;
pub use self::if_range::IfRange;
pub use self::last_modified::LastModified;
pub use self::location::Location;
pub use self::pragma::Pragma;
pub use self::referer::Referer;
pub use self::server::Server;
pub use self::set_cookie::SetCookie;
pub use self::transfer_encoding::TransferEncoding;
pub use self::upgrade::{Upgrade, Protocol, ProtocolName};
pub use self::user_agent::UserAgent;
pub use self::vary::Vary;

#[macro_export]
macro_rules! bench_header(
    ($name:ident, $ty:ty, $value:expr) => {
        #[cfg(test)]
        #[cfg(feature = "nightly")]
        mod $name {
            use test::Bencher;
            use super::*;

            use header::{Header, HeaderFormatter};

            #[bench]
            fn bench_parse(b: &mut Bencher) {
                let val = $value;
                b.iter(|| {
                    let _: $ty = Header::parse_header(&val[..]).unwrap();
                });
            }

            #[bench]
            fn bench_format(b: &mut Bencher) {
                let val: $ty = Header::parse_header(&$value[..]).unwrap();
                let fmt = HeaderFormatter(&val);
                b.iter(|| {
                    format!("{}", fmt);
                });
            }
        }
    }
);

#[macro_export]
macro_rules! __hyper__deref {
    ($from:ty => $to:ty) => {
        impl ::std::ops::Deref for $from {
            type Target = $to;

            fn deref<'a>(&'a self) -> &'a $to {
                &self.0
            }
        }

        impl ::std::ops::DerefMut for $from {
            fn deref_mut<'a>(&'a mut self) -> &'a mut $to {
                &mut self.0
            }
        }
    }
}

#[macro_export]
macro_rules! __hyper__tm {
    ($id:ident, $tm:ident{$($tf:item)*}) => {
        #[allow(unused_imports)]
        mod $tm{
            use std::str;
            use $crate::header::*;
            use $crate::mime::*;
            use $crate::method::Method;
            use super::$id as HeaderField;
            $($tf)*
        }

    }
}

#[macro_export]
macro_rules! test_header {
    ($id:ident, $raw:expr) => {
        #[test]
        fn $id() {
            use std::ascii::AsciiExt;
            let raw = $raw;
            let a: Vec<Vec<u8>> = raw.iter().map(|x| x.to_vec()).collect();
            let value = HeaderField::parse_header(&a[..]);
            let result = format!("{}", value.unwrap());
            let expected = String::from_utf8(raw[0].to_vec()).unwrap();
            let result_cmp: Vec<String> = result
                .to_ascii_lowercase()
                .split(' ')
                .map(|x| x.to_owned())
                .collect();
            let expected_cmp: Vec<String> = expected
                .to_ascii_lowercase()
                .split(' ')
                .map(|x| x.to_owned())
                .collect();
            assert_eq!(result_cmp.concat(), expected_cmp.concat());
        }
    };
    ($id:ident, $raw:expr, $typed:expr) => {
        #[test]
        fn $id() {
            let a: Vec<Vec<u8>> = $raw.iter().map(|x| x.to_vec()).collect();
            let val = HeaderField::parse_header(&a[..]);
            // Test parsing
            assert_eq!(val, $typed);
            // Test formatting
            if $typed != None {
                let res: &str = str::from_utf8($raw[0]).unwrap();
                assert_eq!(format!("{}", $typed.unwrap()), res);
            }
        }
    }
}

#[macro_export]
macro_rules! header {
    // $a:meta: Attributes associated with the header item (usually docs)
    // $id:ident: Identifier of the header
    // $n:expr: Lowercase name of the header
    // $nn:expr: Nice name of the header

    // List header, zero or more items
    ($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)*) => {
        $(#[$a])*
        #[derive(Clone, Debug, PartialEq)]
        pub struct $id(pub Vec<$item>);
        __hyper__deref!($id => Vec<$item>);
        impl $crate::header::Header for $id {
            fn header_name() -> &'static str {
                $n
            }
            fn parse_header(raw: &[Vec<u8>]) -> Option<Self> {
                $crate::header::parsing::from_comma_delimited(raw).map($id)
            }
        }
        impl $crate::header::HeaderFormat for $id {
            fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                $crate::header::parsing::fmt_comma_delimited(f, &self.0[..])
            }
        }
        impl ::std::fmt::Display for $id {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                use $crate::header::HeaderFormat;
                self.fmt_header(f)
            }
        }
    };
    // List header, one or more items
    ($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)+) => {
        $(#[$a])*
        #[derive(Clone, Debug, PartialEq)]
        pub struct $id(pub Vec<$item>);
        __hyper__deref!($id => Vec<$item>);
        impl $crate::header::Header for $id {
            fn header_name() -> &'static str {
                $n
            }
            fn parse_header(raw: &[Vec<u8>]) -> Option<Self> {
                $crate::header::parsing::from_comma_delimited(raw).map($id)
            }
        }
        impl $crate::header::HeaderFormat for $id {
            fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                $crate::header::parsing::fmt_comma_delimited(f, &self.0[..])
            }
        }
        impl ::std::fmt::Display for $id {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                use $crate::header::HeaderFormat;
                self.fmt_header(f)
            }
        }
    };
    // Single value header
    ($(#[$a:meta])*($id:ident, $n:expr) => [$value:ty]) => {
        $(#[$a])*
        #[derive(Clone, Debug, PartialEq)]
        pub struct $id(pub $value);
        __hyper__deref!($id => $value);
        impl $crate::header::Header for $id {
            fn header_name() -> &'static str {
                $n
            }
            fn parse_header(raw: &[Vec<u8>]) -> Option<Self> {
                $crate::header::parsing::from_one_raw_str(raw).map($id)
            }
        }
        impl $crate::header::HeaderFormat for $id {
            fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                ::std::fmt::Display::fmt(&**self, f)
            }
        }
        impl ::std::fmt::Display for $id {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                ::std::fmt::Display::fmt(&**self, f)
            }
        }
    };
    // List header, one or more items with "*" option
    ($(#[$a:meta])*($id:ident, $n:expr) => {Any / ($item:ty)+}) => {
        $(#[$a])*
        #[derive(Clone, Debug, PartialEq)]
        pub enum $id {
            /// Any value is a match
            Any,
            /// Only the listed items are a match
            Items(Vec<$item>),
        }
        impl $crate::header::Header for $id {
            fn header_name() -> &'static str {
                $n
            }
            fn parse_header(raw: &[Vec<u8>]) -> Option<Self> {
                // FIXME: Return None if no item is in $id::Only
                if raw.len() == 1 {
                    if raw[0] == b"*" {
                        return Some($id::Any)
                    }
                }
                $crate::header::parsing::from_comma_delimited(raw).map(|vec| $id::Items(vec))
            }
        }
        impl $crate::header::HeaderFormat for $id {
            fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                match *self {
                    $id::Any => f.write_str("*"),
                    $id::Items(ref fields) => $crate::header::parsing::fmt_comma_delimited(
                        f, &fields[..])
                }
            }
        }
        impl ::std::fmt::Display for $id {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                use $crate::header::HeaderFormat;
                self.fmt_header(f)
            }
        }
    };

    // optional test module
    ($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)* $tm:ident{$($tf:item)*}) => {
        header! {
            $(#[$a])*
            ($id, $n) => ($item)*
        }

        __hyper__tm! { $id, $tm { $($tf)* }}
    };
    ($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)+ $tm:ident{$($tf:item)*}) => {
        header! {
            $(#[$a])*
            ($id, $n) => ($item)+
        }

        __hyper__tm! { $id, $tm { $($tf)* }}
    };
    ($(#[$a:meta])*($id:ident, $n:expr) => [$item:ty] $tm:ident{$($tf:item)*}) => {
        header! {
            $(#[$a])*
            ($id, $n) => [$item]
        }

        __hyper__tm! { $id, $tm { $($tf)* }}
    };
    ($(#[$a:meta])*($id:ident, $n:expr) => {Any / ($item:ty)+} $tm:ident{$($tf:item)*}) => {
        header! {
            $(#[$a])*
            ($id, $n) => {Any / ($item)+}
        }

        __hyper__tm! { $id, $tm { $($tf)* }}
    };
}

mod accept;
mod access_control_allow_headers;
mod access_control_allow_methods;
mod access_control_allow_origin;
mod access_control_max_age;
mod access_control_request_headers;
mod access_control_request_method;
mod accept_charset;
mod accept_encoding;
mod accept_language;
mod accept_ranges;
mod allow;
mod authorization;
mod cache_control;
mod cookie;
mod connection;
mod content_encoding;
mod content_language;
mod content_length;
mod content_type;
mod date;
mod etag;
mod expect;
mod expires;
mod from;
mod host;
mod if_match;
mod if_modified_since;
mod if_none_match;
mod if_range;
mod if_unmodified_since;
mod last_modified;
mod location;
mod pragma;
mod referer;
mod server;
mod set_cookie;
mod transfer_encoding;
mod upgrade;
mod user_agent;
mod vary;


text:
package com.shc.learning.euler;

import java.math.BigInteger;

public class LargestPrimeFactor {

	private static final BigInteger number = new BigInteger("600851475143");
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		long start = System.currentTimeMillis();
		performOperation();
		long end = System.currentTimeMillis();
		System.out.println(end-start);
	}

	private static void performOperation() {

		BigInteger maxDivider = getMaxDivider(number);

		while(maxDivider.compareTo(BigInteger.ONE) > 0) {

			if(hasRemainder(number, maxDivider)) {
				System.out.println("This is a factor");
				if(isPrime(maxDivider)) {
					System.out.println("... and it is prime");
					System.out.println(maxDivider);
					break;
				}
			}
			maxDivider = maxDivider.subtract(BigInteger.ONE);
		}
	}

	private static boolean isPrime(BigInteger quotient) {
		BigInteger maxDivider = getMaxDivider(quotient);

		BigInteger divider = new BigInteger("2");
		while(maxDivider.compareTo(divider) >= 0) {
			if(!hasRemainder(quotient, divider)) {
				System.out.println("not prime");
				return false;
			}
			divider = divider.add(BigInteger.ONE);
		}
		return true;
	}

	private static BigInteger getMaxDivider(BigInteger number){
		Double d = Math.sqrt(number.doubleValue());
		BigInteger maxDivider = new BigInteger(String.valueOf(d.intValue()));
		maxDivider = maxDivider.add(BigInteger.ONE);

		return maxDivider;
	}

	private static boolean  hasRemainder(BigInteger number, BigInteger divider) {
		BigInteger[] bi = number.divideAndRemainder(divider);
		BigInteger r = bi[1];

		return  r.compareTo(BigInteger.ZERO) != 0;
	}
}


text:
@class ComGoodowRealtimeCoreRegistrations;
@class ComGoodowRealtimeStoreEventTypeEnum;
@class ComGoodowRealtimeStoreImplBaseModelEventImpl;
@class ComGoodowRealtimeStoreImplDocumentBridge;
@class ComGoodowRealtimeStoreImplModelImpl;
@class JavaLangVoid;
@protocol ComGoodowRealtimeChannelMessage;
@protocol ComGoodowRealtimeCoreRegistration;
@protocol ComGoodowRealtimeJsonJsonArray;
@protocol ComGoodowRealtimeJsonJsonObject;
@protocol ComGoodowRealtimeStoreBaseModelEvent;
@protocol ComGoodowRealtimeStoreCollaborator;

#include "J2ObjC_header.h"
#include "com/goodow/realtime/core/Handler.h"
#include "com/goodow/realtime/json/JsonArray.h"
#include "com/goodow/realtime/json/JsonObject.h"
#include "com/goodow/realtime/store/Document.h"

@interface ComGoodowRealtimeStoreImplDocumentImpl : NSObject < ComGoodowRealtimeStoreDocument > {
 @public
  ComGoodowRealtimeCoreRegistrations *handlerRegs_;
  id<ComGoodowRealtimeJsonJsonObject> collaborators_;
}

- (instancetype)initWithComGoodowRealtimeStoreImplDocumentBridge:(ComGoodowRealtimeStoreImplDocumentBridge *)internalApi
                                withComGoodowRealtimeCoreHandler:(id<ComGoodowRealtimeCoreHandler>)errorHandler;

- (id<ComGoodowRealtimeCoreRegistration>)onCollaboratorJoinedWithComGoodowRealtimeCoreHandler:(id<ComGoodowRealtimeCoreHandler>)handler;

- (id<ComGoodowRealtimeCoreRegistration>)onCollaboratorLeftWithComGoodowRealtimeCoreHandler:(id<ComGoodowRealtimeCoreHandler>)handler;

- (id<ComGoodowRealtimeCoreRegistration>)onDocumentSaveStateChangedWithComGoodowRealtimeCoreHandler:(id<ComGoodowRealtimeCoreHandler>)handler;

- (void)close;

- (id<ComGoodowRealtimeJsonJsonArray>)getCollaborators;

- (ComGoodowRealtimeStoreImplModelImpl *)getModel;

- (id<ComGoodowRealtimeCoreRegistration>)addEventListenerWithNSString:(NSString *)objectId
                              withComGoodowRealtimeStoreEventTypeEnum:(ComGoodowRealtimeStoreEventTypeEnum *)type
                                     withComGoodowRealtimeCoreHandler:(id<ComGoodowRealtimeCoreHandler>)handler
                                                          withBoolean:(jboolean)opt_capture;

- (void)scheduleEventWithComGoodowRealtimeStoreBaseModelEvent:(id<ComGoodowRealtimeStoreBaseModelEvent>)event;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoodowRealtimeStoreImplDocumentImpl)

J2OBJC_FIELD_SETTER(ComGoodowRealtimeStoreImplDocumentImpl, handlerRegs_, ComGoodowRealtimeCoreRegistrations *)
J2OBJC_FIELD_SETTER(ComGoodowRealtimeStoreImplDocumentImpl, collaborators_, id<ComGoodowRealtimeJsonJsonObject>)

CF_EXTERN_C_BEGIN
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(ComGoodowRealtimeStoreImplDocumentImpl)

@interface ComGoodowRealtimeStoreImplDocumentImpl_$1 : NSObject < ComGoodowRealtimeCoreHandler > {
}

- (void)handleWithId:(id)ignore;

- (instancetype)initWithComGoodowRealtimeStoreImplDocumentImpl:(ComGoodowRealtimeStoreImplDocumentImpl *)outer$;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoodowRealtimeStoreImplDocumentImpl_$1)

CF_EXTERN_C_BEGIN
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(ComGoodowRealtimeStoreImplDocumentImpl_$1)

@interface ComGoodowRealtimeStoreImplDocumentImpl_$1_$1 : NSObject < ComGoodowRealtimeJsonJsonArray_ListIterator > {
}

- (void)callWithInt:(jint)index
             withId:(ComGoodowRealtimeStoreImplBaseModelEventImpl *)event;

- (instancetype)initWithComGoodowRealtimeStoreImplDocumentImpl_$1:(ComGoodowRealtimeStoreImplDocumentImpl_$1 *)outer$;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoodowRealtimeStoreImplDocumentImpl_$1_$1)

CF_EXTERN_C_BEGIN
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(ComGoodowRealtimeStoreImplDocumentImpl_$1_$1)

@interface ComGoodowRealtimeStoreImplDocumentImpl_$1_$2 : NSObject < ComGoodowRealtimeJsonJsonObject_MapIterator > {
}

- (void)callWithNSString:(NSString *)key
                  withId:(id<ComGoodowRealtimeJsonJsonArray>)events;

- (instancetype)initWithComGoodowRealtimeStoreImplDocumentImpl_$1:(ComGoodowRealtimeStoreImplDocumentImpl_$1 *)outer$;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoodowRealtimeStoreImplDocumentImpl_$1_$2)

CF_EXTERN_C_BEGIN
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(ComGoodowRealtimeStoreImplDocumentImpl_$1_$2)

@interface ComGoodowRealtimeStoreImplDocumentImpl_$1_$3 : NSObject < ComGoodowRealtimeJsonJsonArray_ListIterator > {
}

- (void)callWithInt:(jint)index
             withId:(NSString *)parent;

- (instancetype)initWithComGoodowRealtimeStoreImplDocumentImpl_$1:(ComGoodowRealtimeStoreImplDocumentImpl_$1 *)outer$
                         withComGoodowRealtimeStoreBaseModelEvent:(id<ComGoodowRealtimeStoreBaseModelEvent>)capture$0
                               withComGoodowRealtimeJsonJsonArray:(id<ComGoodowRealtimeJsonJsonArray>)capture$1;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoodowRealtimeStoreImplDocumentImpl_$1_$3)

CF_EXTERN_C_BEGIN
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(ComGoodowRealtimeStoreImplDocumentImpl_$1_$3)

@interface ComGoodowRealtimeStoreImplDocumentImpl_$2 : NSObject < ComGoodowRealtimeCoreHandler > {
}

- (void)handleWithId:(id<ComGoodowRealtimeChannelMessage>)message;

- (instancetype)initWithComGoodowRealtimeCoreHandler:(id<ComGoodowRealtimeCoreHandler>)capture$0;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoodowRealtimeStoreImplDocumentImpl_$2)

CF_EXTERN_C_BEGIN
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(ComGoodowRealtimeStoreImplDocumentImpl_$2)

@interface ComGoodowRealtimeStoreImplDocumentImpl_$3 : NSObject < ComGoodowRealtimeCoreHandler > {
}

- (void)handleWithId:(id<ComGoodowRealtimeChannelMessage>)message;

- (instancetype)initWithComGoodowRealtimeStoreImplDocumentImpl:(ComGoodowRealtimeStoreImplDocumentImpl *)outer$;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoodowRealtimeStoreImplDocumentImpl_$3)

CF_EXTERN_C_BEGIN
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(ComGoodowRealtimeStoreImplDocumentImpl_$3)

@interface ComGoodowRealtimeStoreImplDocumentImpl_$4 : NSObject < ComGoodowRealtimeJsonJsonObject_MapIterator > {
}

- (void)callWithNSString:(NSString *)key
                  withId:(id<ComGoodowRealtimeStoreCollaborator>)collaborator;

- (instancetype)initWithComGoodowRealtimeJsonJsonArray:(id<ComGoodowRealtimeJsonJsonArray>)capture$0;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoodowRealtimeStoreImplDocumentImpl_$4)

CF_EXTERN_C_BEGIN
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(ComGoodowRealtimeStoreImplDocumentImpl_$4)

@interface ComGoodowRealtimeStoreImplDocumentImpl_$5 : NSObject < ComGoodowRealtimeCoreHandler > {
}

- (void)handleWithId:(id<ComGoodowRealtimeChannelMessage>)message;

- (instancetype)initWithComGoodowRealtimeCoreHandler:(id<ComGoodowRealtimeCoreHandler>)capture$0;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoodowRealtimeStoreImplDocumentImpl_$5)

CF_EXTERN_C_BEGIN
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(ComGoodowRealtimeStoreImplDocumentImpl_$5)

#endif // _ComGoodowRealtimeStoreImplDocumentImpl_H_


text:
These notes may help to import data from a pentabarf postgresql database.

Using postgresql as a database for frab is still somewhat untested. The pentabarf
import is however likely to fail, as pentabarf uses text fields instead of char(255)

Imagemagick needs to be installed as we will convert pjpeg and tiff to png.

## postgresql installation

Install postgresql

## postgresql setup

* make it listen on localhost
* create a psql user and grant some access on relations
* add a pentabarf entry for the postgresql database to your rails db environment

## postgresql copy

Make a copy of your postgresql database, as we need to do some changes

    pg_dump -Fc DBNAME > backup.dump
    createdb NEWNAME
    pg_restore -O -d NEWNAME backup.dump > /dev/null

## postgresql permissions

Grant all permissions on the database copy to the import user account:

    psql NEWNAME
    -- generate the grant statements
    select 'grant all on '||schemaname||'.'||tablename||' to frab;' from pg_tables
      order by schemaname, tablename;
    -- copy&paste the generated statements into psql

    -- in case you re-created the NEWNAME copy, re-grant permissions to the user
    REVOKE ALL ON SCHEMA public FROM frab;
    GRANT ALL ON SCHEMA public TO frab;
    REVOKE ALL ON SCHEMA auth FROM frab;
    GRANT ALL ON SCHEMA auth TO frab;

## data migration

Conference acronyms need to be within /^[a-zA-Z0-9_-]*$/
Whitespaces are removed automatically, but you need to replace unicode characters manually.

    -- conference acronyms appear in URLs, they may not contain whitespace in frab:
    UPDATE conference SET acronym = replace(acronym, ' ', '');
    UPDATE conference SET acronym = 'mrmcdX' where conference_id=86; -- mrmcdⅩ

## import

Delete any old mappings from previous imports. Maybe delete the old filess, too.

    rm tmp/*mappings.yml
    rm -fr public/system
    RAILS_ENV=production rake db:reset
    RAILS_ENV=production rake pentabarf:import:all

## testing

You can check on the barf data like this:

    RAILS_ENV="development" rails console
    @p = PentabarfImportHelper.new
    @barf = @p.instance_variable_get('@barf')
    @barf.select_all("SELECT * FROM conference")

## privileges

You maybe want to drop all users to the coordinator role, to start fresh.

User.all.select { |u| u.role == "admin" or u.role == "orga" }.each { |u| puts "dropping ${u.email}"; u.role = "coordinator"; u.save }


text:
cd "$( dirname "${BASH_SOURCE[0]}" )"
curl -O http://vision.princeton.edu/marvin/models/alexnet_imagenet/alexnet_imagenet_half.marvin


text:
package operators

import (
	"context"
	"fmt"

	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	corev1 "k8s.io/api/core/v1"
	rbacv1 "k8s.io/api/rbac/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/types"
	"sigs.k8s.io/controller-runtime/pkg/client"

	operatorsv1 "github.com/operator-framework/api/pkg/operators/v1"
	"github.com/operator-framework/operator-lifecycle-manager/pkg/controller/operators/decorators"
	"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/testobj"
)

var _ = Describe("Operator Controller", func() {
	var (
		ctx                            context.Context
		operator                       *operatorsv1.Operator
		name                           types.NamespacedName
		expectedKey                    string
		expectedComponentLabelSelector *metav1.LabelSelector
	)

	BeforeEach(func() {
		ctx = context.Background()
		operator = newOperator(genName("ghost-")).Operator
		name = types.NamespacedName{Name: operator.GetName()}
		expectedKey = decorators.ComponentLabelKeyPrefix + operator.GetName()
		expectedComponentLabelSelector = &metav1.LabelSelector{
			MatchExpressions: []metav1.LabelSelectorRequirement{
				{
					Key:      expectedKey,
					Operator: metav1.LabelSelectorOpExists,
				},
			},
		}

		Expect(k8sClient.Create(ctx, operator)).To(Succeed())
	})

	Describe("operator deletion", func() {
		var originalUID types.UID

		JustBeforeEach(func() {
			originalUID = operator.GetUID()
			Expect(k8sClient.Delete(ctx, operator)).To(Succeed())
		})

		Context("with components bearing its label", func() {
			var (
				objs      []runtime.Object
				namespace string
			)

			BeforeEach(func() {
				namespace = genName("ns-")
				objs = testobj.WithLabel(expectedKey, "",
					testobj.WithName(namespace, &corev1.Namespace{}),
				)

				for _, obj := range objs {
					Expect(k8sClient.Create(ctx, obj.(client.Object))).To(Succeed())
				}
			})

			AfterEach(func() {
				for _, obj := range objs {
					Expect(k8sClient.Delete(ctx, obj.(client.Object), deleteOpts)).To(Succeed())
				}
				Expect(k8sClient.Delete(ctx, operator, deleteOpts)).To(Succeed())
			})

			It("should re-create it", func() {
				// There's a race condition between this test and the controller. By the time,
				// this function is running, we may be in one of three states.
				//   1. The original deletion in the test setup has not yet finished, so the original
				//      operator resource still exists.
				//   2. The operator doesn't exist, and the controller has not yet re-created it.
				//   3. The operator has already been deleted and re-created.
				//
				// To solve this problem, we simply compare the UIDs and expect to eventually see a
				// a different UID.
				Eventually(func() (types.UID, error) {
					err := k8sClient.Get(ctx, name, operator)
					return operator.GetUID(), err
				}, timeout, interval).ShouldNot(Equal(originalUID))
			})
		})
		Context("with no components bearing its label", func() {
			It("should not re-create it", func() {
				// We expect the operator deletion to eventually complete, and then we
				// expect the operator to consistently never be found.
				Eventually(func() bool {
					return apierrors.IsNotFound(k8sClient.Get(ctx, name, operator))
				}, timeout, interval).Should(BeTrue())
				Consistently(func() bool {
					return apierrors.IsNotFound(k8sClient.Get(ctx, name, operator))
				}, timeout, interval).Should(BeTrue())
			})
		})
	})

	Describe("component selection", func() {

		BeforeEach(func() {
			Eventually(func() (*operatorsv1.Components, error) {
				err := k8sClient.Get(ctx, name, operator)
				return operator.Status.Components, err
			}, timeout, interval).ShouldNot(BeNil())

			Eventually(func() (*metav1.LabelSelector, error) {
				err := k8sClient.Get(ctx, name, operator)
				return operator.Status.Components.LabelSelector, err
			}, timeout, interval).Should(Equal(expectedComponentLabelSelector))
		})

		AfterEach(func() {
			Expect(k8sClient.Delete(ctx, operator, deleteOpts)).To(Succeed())
		})

		Context("with no components bearing its label", func() {
			Specify("a status containing no component references", func() {
				Consistently(func() ([]operatorsv1.RichReference, error) {
					err := k8sClient.Get(ctx, name, operator)
					return operator.Status.Components.Refs, err
				}, timeout, interval).Should(BeEmpty())
			})
		})

		Context("with components bearing its label", func() {
			var (
				objs         []runtime.Object
				expectedRefs []operatorsv1.RichReference
				namespace    string
			)

			BeforeEach(func() {
				namespace = genName("ns-")
				objs = testobj.WithLabel(expectedKey, "",
					testobj.WithName(namespace, &corev1.Namespace{}),
				)

				for _, obj := range objs {
					Expect(k8sClient.Create(ctx, obj.(client.Object))).To(Succeed())
				}

				expectedRefs = toRefs(scheme, objs...)
			})

			AfterEach(func() {
				for _, obj := range objs {
					Expect(k8sClient.Delete(ctx, obj.(client.Object), deleteOpts)).To(Succeed())
				}
			})

			Specify("a status containing its component references", func() {
				Eventually(func() ([]operatorsv1.RichReference, error) {
					err := k8sClient.Get(ctx, name, operator)
					return operator.Status.Components.Refs, err
				}, timeout, interval).Should(ConsistOf(expectedRefs))
			})

			Context("when new components are labelled", func() {

				BeforeEach(func() {
					saName := &types.NamespacedName{Namespace: namespace, Name: genName("sa-")}
					newObjs := testobj.WithLabel(expectedKey, "",
						testobj.WithNamespacedName(saName, &corev1.ServiceAccount{}),
						testobj.WithName(genName("sa-admin-"), &rbacv1.ClusterRoleBinding{
							Subjects: []rbacv1.Subject{
								{
									Kind:      rbacv1.ServiceAccountKind,
									Name:      saName.Name,
									Namespace: saName.Namespace,
								},
							},
							RoleRef: rbacv1.RoleRef{
								APIGroup: rbacv1.GroupName,
								Kind:     "ClusterRole",
								Name:     "cluster-admin",
							},
						}),
					)

					for _, obj := range newObjs {
						Expect(k8sClient.Create(ctx, obj.(client.Object))).To(Succeed())
					}

					objs = append(objs, newObjs...)
					expectedRefs = append(expectedRefs, toRefs(scheme, newObjs...)...)
				})

				It("should add the component references", func() {
					Eventually(func() ([]operatorsv1.RichReference, error) {
						err := k8sClient.Get(ctx, name, operator)
						return operator.Status.Components.Refs, err
					}, timeout, interval).Should(ConsistOf(expectedRefs))
				})
			})

			Context("when multiple types of a gvk are labeled", func() {
				BeforeEach(func() {
					newObjs := make([]runtime.Object, 9)

					// Create objects in reverse order to ensure they are eventually ordered alphabetically in the status of the operator.
					for i := 8; i >= 0; i-- {
						newObjs[8-i] = testobj.WithLabels(map[string]string{expectedKey: ""}, testobj.WithNamespacedName(
							&types.NamespacedName{Namespace: namespace, Name: fmt.Sprintf("sa-%d", i)}, &corev1.ServiceAccount{},
						))
					}

					for _, obj := range newObjs {
						Expect(k8sClient.Create(ctx, obj.(client.Object))).To(Succeed())
					}

					objs = append(objs, newObjs...)
					expectedRefs = append(expectedRefs, toRefs(scheme, newObjs...)...)
				})

				It("should list each of the component references in alphabetical order by namespace and name", func() {
					Eventually(func() ([]operatorsv1.RichReference, error) {
						err := k8sClient.Get(ctx, name, operator)
						return operator.Status.Components.Refs, err
					}, timeout, interval).Should(ConsistOf(expectedRefs))

					serviceAccountCount := 0
					for _, ref := range operator.Status.Components.Refs {
						if ref.Kind != rbacv1.ServiceAccountKind {
							continue
						}

						Expect(ref.Name).Should(Equal(fmt.Sprintf("sa-%d", serviceAccountCount)))
						serviceAccountCount++
					}
					Expect(serviceAccountCount).To(Equal(9))
				})
			})

			Context("when component labels are removed", func() {

				BeforeEach(func() {
					for _, obj := range testobj.StripLabel(expectedKey, objs...) {
						Expect(k8sClient.Update(ctx, obj.(client.Object))).To(Succeed())
					}
				})

				It("should remove the component references", func() {
					Eventually(func() ([]operatorsv1.RichReference, error) {
						err := k8sClient.Get(ctx, name, operator)
						return operator.Status.Components.Refs, err
					}, timeout, interval).Should(BeEmpty())
				})
			})
		})
	})
})


text:
var db = require('../config/database');
var table = 'late';
var pk = 'id_Late';//Primary key
var catchError = require('../config/catchError');
var model = require('./model');
var student = require('./student');
var course = require('./course');
var tokenInspector = require('../auth/config/tokenInspector');

var late = {
  getAll: function(req, res){
    if(req.params.idCourse != undefined){//Liste tout les retards d'un cours
      var sql = model.selectWhere('*',table,{"id_Course":req.params.idCourse})
      /*var sql = 'SELECT * FROM '+ table+
                ' WHERE "id_Course"='+req.params.idCourse;*/
    }
    else if(req.params.idStudent != undefined){//Liste toute les retards d'un étudient
      var sql = model.selectWhere('*',table,{"id_Student":req.params.idStudent})
      /*var sql = 'SELECT * FROM '+ table+
                ' WHERE "id_Student"='+req.params.idStudent;*/
    }
    else {//Liste ses retards (étudiant)
      var idStudent = tokenInspector.getUserId(tokenInspector.getToken(req));
      var sql = model.selectWhere('*', table,{"id_Student":idStudent});
      //On récupère l'id_User de l'étudiant
      //var sql = 'SELECT * FROM '+ table+' WHERE "id_Student"='+idStudent);
    }
    db.query(sql, function(lates,err){
      if(err){
        catchError(res,err);
      }
      else if(lates.length == 0){
        res.status(200).send({
          "status": 200,
          "message": "Il n'y a pas de retard",
        });
      }
      else{
        res.status(200).send({
          "status": 200,
          "message": "Retards trouvées",
          "lates": lates
        });
      }
    });
  },
  getOne: function(req, res){//Récupérer une absence
    if(req.params.idCourse != undefined && req.params.idLate != undefined){//Le secrétariat affiche le retard dans un cours
      var sql = model.selectWhere('*',table,{"id_Course":req.params.idCourse,
                                             "id_Late":req.params.idLate
                                            });
      /*var sql = 'SELECT * FROM '+table+
                ' WHERE '+'"id_Late"'+'='+req.params.idLate+
                ' AND '+'"id_Course"'+'='+req.params.idCourse;*/
    }
    else if(req.params.idLate!= undefined && req.params.idStudent!= undefined){//Le secrétariat affiche le retard par rapport à un étudiant
      var sql = model.selectWhere('*',table,{"id_Student":req.params.idStudent,
                                             "id_Late":req.params.idLate
                                            });
      /*var sql = 'SELECT * FROM '+table+
                ' WHERE '+'"id_Late"'+'='+req.params.idLate+
                ' AND '+'"id_Student"'+'='+req.params.idStudent;*/
    }
    else{//L'étudiant affiche son retard
      var idStudent = tokenInspector.getUserId(tokenInspector.getToken(req));
      var sql = model.selectWhere('*',table,{"id_Student":idStudent});
      //var sql= 'SELECT * FROM '+table+' WHERE '+'"id_Student"'+'='+req.params.idStudent;
    }
    db.query(sql, function(late,err){
      if(err){
        catchError(res,err);
      }
      else if(absences.length == 0){
        res.status(200).send({
          "status": 200,
          "message": "Il n'y a pas de retard",
        });
      }
      else{
        res.status(200).send({
          "status": 200,
          "message": "Retard trouvé",
          "late": late
        });
      }
    });
  },
  create: function(req, res){//Crée absence après l'appel
    if(req.params.idCourse != undefined && req.body.idStudent != undefined){
      var sql = model.create(table,{"id_Course":req.params.idCourse,
                                        "id_Student": req.body.idStudent
                                        });

      /*var sql = 'INSERT INTO '+table+' ("id_Course"'+',"id_Student")'+
                ' VALUES ("'+req.params.idCourse+'",'+req.body.idStudent+')';*/
    }
    db.query(sql, function(late,err){
      if(err){
        catchError(res,err);
      }
      else{
        res.status(200).send({
          "status": 201,
          "message": "Retard créé",
          "late": late
        });
      }
    });
  },
  delete: function(req, res){
    var idLate = req.params.id;
    var sql = model.deleteWhere(table,pk,idLate);
    //var sql = 'DELETE FROM '+table+' WHERE "'+pk+'"='+id;
    db.query(sql,function(late,err){
      if(err){
        catchError(res,err);
      }
      else{
        res.status(200).send({
          "status": 200,
          "message": "Retard supprimé",
          "absence": late
        });
      }
    });
  },
  justify: function(req, res){

    if(req.params.idCourse != undefined && req.params.idLate != undefined){//Le secrétariat passe l'absence a justifiee après avoir selectionne l'absence concernée dans le cours
    var sql = model.update(table,{"bool_Justify": 'true'}, {"id_Course":req.params.idCourse,
                                                            "id_Late":req.params.idLate
                                                            });

      /*var sql = 'UPDATE '+table+' SET "bool_Justify" = true'+
                ' WHERE "id_Course"='+req.params.id_Course+
                ' AND "id_Late"='+req.params.idLate;*/
    }
    else if(req.params.idStudent != undefined && req.params.idLate != undefined){//Crée une absence en passant par l'éléve
      var sql = model.update(table,{"bool_Justify": 'true'}, {"id_Student":req.params.idStudent,
                                                              "id_Late":req.params.idLate
                                                              });

      /*var sql = 'UPDATE '+table+' SET "bool_Justify" = true'+
                ' WHERE "id_Student"='+req.params.idStudent+
                ' AND "id_Late"='+req.params.idLate;*/
    }
    db.query(sql,function(late,err){
      if(err){
        catchError(res,err);
      }
      else{
        res.status(200).send({
          "status": 200,
          "message": "Absence devient justifiée"
        });
      }
    });
  }

};
module.exports = late;


text:
package uk.co.itmoore.intellisubsteps.psi.feature.impl;

import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.jetbrains.annotations.NotNull;
import uk.co.itmoore.intellisubsteps.psi.feature.FeatureElementVisitor;
import uk.co.itmoore.intellisubsteps.psi.feature.FeatureFileType;
import uk.co.itmoore.intellisubsteps.psi.feature.FeatureLanguage;
import uk.co.itmoore.intellisubsteps.psi.stepdefinition.SubstepsStepDefinitionFileType;
import uk.co.itmoore.intellisubsteps.psi.stepdefinition.SubstepsStepDefinitionLanguage;

/**
 * Created by ian on 05/07/15.
 */
public class ExamplesBlockImpl extends FeaturePsiElementBase {

    public ExamplesBlockImpl(@NotNull ASTNode node) {
        super(node);
    }

    @Override
    protected void acceptFeature(FeatureElementVisitor featureElementVisitor) {

    }

}


text:
import os
import unittest

class TumblyCLExists(unittest.TestCase):

    def test_file(self):
        file = os.path.isfile('tumbly/database.py')
        self.assertTrue(file)

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


text:
import Ember from 'ember';

export default Ember.Route.extend({
    web3js: Ember.inject.service('web3js'),
    model(){
        // get all journals
    }
});


text:
<!DOCTYPE html>

    <title>Meowsynth</title>
    <link rel="stylesheet" href="screen.css">
    <meta content="charset=UTF-8">

Loading...


text:
package entity;

/**
 * Created by qingwei on 2015/7/15.
 */
public class FieldEntity {

    private String field;
    private String type;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}


text:
<?php
namespace Marchie\LaravelQueueAzureRestarter\Exceptions;

class QueueProcessesNotKilledException extends \Exception {}


text:
namespace lly {

	GLenum to_usage(RenderBuffer::Usage usage)
	{
		if (usage == RenderBuffer::Usage::DEPTH)
			return GL_DEPTH_COMPONENT;
		return GL_DEPTH24_STENCIL8;
	}

	RenderBuffer::RenderBuffer()
	{

	}

	RenderBuffer::~RenderBuffer()
	{
		if (_id > 0)
		{
			glDeleteRenderbuffers(1, &_id);
			_id = 0;
		}
	}

	bool RenderBuffer::create(int width, int height, Usage usage)
	{
		glGenRenderbuffers(1, &_id);
		glBindRenderbuffer(GL_RENDERBUFFER, _id);
		glRenderbufferStorage(GL_RENDERBUFFER, to_usage(usage), (GLsizei)width, (GLsizei)height);

		_width = width;
		_height = height;
		_usage = usage;

		return true;
	}

	void RenderBuffer::attach_to_render_target()
	{
		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _id);
		if (_usage == Usage::DEPTH_STENCIL)
			glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _id);
	}
}


text:
package fundingcredit

import (
	"encoding/json"
	"fmt"
)

type CancelRequest struct {
	ID int64
}

func (cr *CancelRequest) ToJSON() ([]byte, error) {
	resp := struct {
		ID int64 `json:"id"`
	}{
		ID: cr.ID,
	}
	return json.Marshal(resp)
}

// MarshalJSON converts the funding credit cancel request into the format required by the
// bitfinex websocket service.
func (cr *CancelRequest) MarshalJSON() ([]byte, error) {
	b, err := cr.ToJSON()
	if err != nil {
		return nil, err
	}
	return []byte(fmt.Sprintf("[0, \"fcc\", null, %s]", string(b))), nil
}


text:
/* -*- c++ -*- */
/*
 * Copyright © 2010 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include "glsl_symbol_table.h"

class symbol_table_entry {
public:
   DECLARE_RALLOC_CXX_OPERATORS(symbol_table_entry);

   bool add_interface(const glsl_type *i, enum ir_variable_mode mode)
   {
      const glsl_type **dest;

      switch (mode) {
      case ir_var_uniform:
         dest = &ibu;
         break;
      case ir_var_shader_in:
         dest = &ibi;
         break;
      case ir_var_shader_out:
         dest = &ibo;
         break;
      default:
         assert(!"Unsupported interface variable mode!");
         return false;
      }

      if (*dest != NULL) {
         return false;
      } else {
         *dest = i;
         return true;
      }
   }

   const glsl_type *get_interface(enum ir_variable_mode mode)
   {
      switch (mode) {
      case ir_var_uniform:
         return ibu;
      case ir_var_shader_in:
         return ibi;
      case ir_var_shader_out:
         return ibo;
      default:
         assert(!"Unsupported interface variable mode!");
         return NULL;
      }
   }

   symbol_table_entry(ir_variable *v)               :
      v(v), f(0), t(0), ibu(0), ibi(0), ibo(0), a(0) {}
   symbol_table_entry(ir_function *f)               :
      v(0), f(f), t(0), ibu(0), ibi(0), ibo(0), a(0) {}
   symbol_table_entry(const glsl_type *t)           :
      v(0), f(0), t(t), ibu(0), ibi(0), ibo(0), a(0) {}
   symbol_table_entry(const glsl_type *t, enum ir_variable_mode mode) :
      v(0), f(0), t(0), ibu(0), ibi(0), ibo(0), a(0)
   {
      assert(t->is_interface());
      add_interface(t, mode);
   }
   symbol_table_entry(const class ast_type_specifier *a):
      v(0), f(0), t(0), ibu(0), ibi(0), ibo(0), a(a) {}

   ir_variable *v;
   ir_function *f;
   const glsl_type *t;
   const glsl_type *ibu;
   const glsl_type *ibi;
   const glsl_type *ibo;
   const class ast_type_specifier *a;
};

glsl_symbol_table::glsl_symbol_table()
{
   this->separate_function_namespace = false;
   this->table = _mesa_symbol_table_ctor();
   this->mem_ctx = ralloc_context(NULL);
}

glsl_symbol_table::~glsl_symbol_table()
{
   _mesa_symbol_table_dtor(table);
   ralloc_free(mem_ctx);
}

void glsl_symbol_table::push_scope()
{
   _mesa_symbol_table_push_scope(table);
}

void glsl_symbol_table::pop_scope()
{
   _mesa_symbol_table_pop_scope(table);
}

bool glsl_symbol_table::name_declared_this_scope(const char *name)
{
   return _mesa_symbol_table_symbol_scope(table, -1, name) == 0;
}

bool glsl_symbol_table::add_variable(ir_variable *v)
{
   if (this->separate_function_namespace) {
      /* In 1.10, functions and variables have separate namespaces. */
      symbol_table_entry *existing = get_entry(v->name);
      if (name_declared_this_scope(v->name)) {
	 /* If there's already an existing function (not a constructor!) in
	  * the current scope, just update the existing entry to include 'v'.
	  */
	 if (existing->v == NULL && existing->t == NULL) {
	    existing->v = v;
	    return true;
	 }
      } else {
	 /* If not declared at this scope, add a new entry.  But if an existing
	  * entry includes a function, propagate that to this block - otherwise
	  * the new variable declaration would shadow the function.
	  */
	 symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(v);
	 if (existing != NULL)
	    entry->f = existing->f;
	 int added = _mesa_symbol_table_add_symbol(table, -1, v->name, entry);
	 assert(added == 0);
	 (void)added;
	 return true;
      }
      return false;
   }

   /* 1.20+ rules: */
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(v);
   return _mesa_symbol_table_add_symbol(table, -1, v->name, entry) == 0;
}

bool glsl_symbol_table::add_type(const char *name, const glsl_type *t)
{
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(t);
   return _mesa_symbol_table_add_symbol(table, -1, name, entry) == 0;
}

bool glsl_symbol_table::add_interface(const char *name, const glsl_type *i,
                                      enum ir_variable_mode mode)
{
   assert(i->is_interface());
   symbol_table_entry *entry = get_entry(name);
   if (entry == NULL) {
      symbol_table_entry *entry =
         new(mem_ctx) symbol_table_entry(i, mode);
      bool add_interface_symbol_result =
         _mesa_symbol_table_add_symbol(table, -1, name, entry) == 0;
      assert(add_interface_symbol_result);
      return add_interface_symbol_result;
   } else {
      return entry->add_interface(i, mode);
   }
}

bool glsl_symbol_table::add_function(ir_function *f)
{
   if (this->separate_function_namespace && name_declared_this_scope(f->name)) {
      /* In 1.10, functions and variables have separate namespaces. */
      symbol_table_entry *existing = get_entry(f->name);
      if ((existing->f == NULL) && (existing->t == NULL)) {
	 existing->f = f;
	 return true;
      }
   }
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(f);
   return _mesa_symbol_table_add_symbol(table, -1, f->name, entry) == 0;
}

void glsl_symbol_table::add_global_function(ir_function *f)
{
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(f);
   int added = _mesa_symbol_table_add_global_symbol(table, -1, f->name, entry);
   assert(added == 0);
   (void)added;
}

ir_variable *glsl_symbol_table::get_variable(const char *name)
{
   symbol_table_entry *entry = get_entry(name);
   return entry != NULL ? entry->v : NULL;
}

const glsl_type *glsl_symbol_table::get_type(const char *name)
{
   symbol_table_entry *entry = get_entry(name);
   return entry != NULL ? entry->t : NULL;
}

const glsl_type *glsl_symbol_table::get_interface(const char *name,
                                                  enum ir_variable_mode mode)
{
   symbol_table_entry *entry = get_entry(name);
   return entry != NULL ? entry->get_interface(mode) : NULL;
}

ir_function *glsl_symbol_table::get_function(const char *name)
{
   symbol_table_entry *entry = get_entry(name);
   return entry != NULL ? entry->f : NULL;
}

symbol_table_entry *glsl_symbol_table::get_entry(const char *name)
{
   return (symbol_table_entry *)
      _mesa_symbol_table_find_symbol(table, -1, name);
}

void
glsl_symbol_table::disable_variable(const char *name)
{
   /* Ideally we would remove the variable's entry from the symbol table, but
    * that would be difficult.  Fortunately, since this is only used for
    * built-in variables, it won't be possible for the shader to re-introduce
    * the variable later, so all we really need to do is to make sure that
    * further attempts to access it using get_variable() will return NULL.
    */
   symbol_table_entry *entry = get_entry(name);
   if (entry != NULL) {
      entry->v = NULL;
   }
}


text:
@implementation YGPicCategoryCell
- (UIImageView *)iconIV {
    if(_iconIV == nil) {
        _iconIV = [[UIImageView alloc] init];
        _iconIV.layer.cornerRadius = 4;
        [self.contentView addSubview:_iconIV];
        CGFloat scale = 12 / 9.0;
        [_iconIV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.offset(0);
            make.height.mas_equalTo(_iconIV.mas_width).multipliedBy(scale);
        }];
    }
    return _iconIV;
}

- (UILabel *)titleLB {
    if(_titleLB == nil) {
        _titleLB = [[UILabel alloc] init];
        [self.contentView addSubview:_titleLB];
        _titleLB.font = [UIFont systemFontOfSize:14];
        _titleLB.textAlignment = NSTextAlignmentCenter;
        [_titleLB mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.iconIV.mas_bottom).offset(5);
            make.centerX.offset(0);
        }];
    }
    return _titleLB;
}
@end


text:
from mcfw.restapi import rest
from mcfw.rpc import returns, arguments
from rogerthat.rpc import users
from solutions.common.bizz.reports import list_incidents, get_incident, update_incident

@rest('/common/reports/incidents', 'get', read_only_access=True, silent_result=True)
@returns(dict)
@arguments(status=unicode, cursor=unicode)
def rest_list_incidents(status=None, cursor=None):
    params = {'status': status}
    if cursor:
        params['cursor'] = cursor
    return list_incidents(users.get_current_user(), params)

@rest('/common/reports/incidents/<incident_id:[^/]+>', 'get', read_only_access=True, silent_result=True)
@returns(dict)
@arguments(incident_id=unicode)
def rest_get_incident(incident_id):
    return get_incident(users.get_current_user(), incident_id)

@rest('/common/reports/incidents/<incident_id:[^/]+>', 'put', read_only_access=True, silent_result=True)
@returns(dict)
@arguments(incident_id=unicode, data=dict)
def rest_update_incident(incident_id, data):
    return update_incident(users.get_current_user(), incident_id, data)


text:
package org.robovm.samples.inapppurchases.ui;

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

import org.robovm.apple.foundation.NSArray;
import org.robovm.apple.foundation.NSByteCountFormatter;
import org.robovm.apple.foundation.NSByteCountFormatterCountStyle;
import org.robovm.apple.foundation.NSDateFormatter;
import org.robovm.apple.foundation.NSDateFormatterStyle;
import org.robovm.apple.foundation.NSIndexPath;
import org.robovm.apple.storekit.SKDownload;
import org.robovm.apple.storekit.SKPaymentTransaction;
import org.robovm.apple.uikit.UITableView;
import org.robovm.apple.uikit.UITableViewCell;
import org.robovm.apple.uikit.UITableViewCellAccessoryType;
import org.robovm.apple.uikit.UITableViewCellSelectionStyle;
import org.robovm.apple.uikit.UITableViewCellStyle;
import org.robovm.apple.uikit.UITableViewController;
import org.robovm.samples.inapppurchases.MyModel;
import org.robovm.samples.inapppurchases.StoreManager;
import org.robovm.samples.inapppurchases.StoreObserver;

public class IOSPurchasesList extends UITableViewController {
    private final List<MyModel> allPurchases = new ArrayList<>();
    private final List<String> sectionNames = new ArrayList<>();

    private final PaymentTransactionDetails transactionDetails;

    public IOSPurchasesList() {
        transactionDetails = new PaymentTransactionDetails();

        allPurchases.add(new MyModel("PURCHASED"));
        allPurchases.add(new MyModel("RESTORED"));
    }

    @Override
    public void viewWillAppear(boolean animated) {
        super.viewWillAppear(animated);

        // Update allPurchases if there are purchased products
        if (StoreObserver.getInstance().hasPurchasedProducts()) {
            MyModel model = allPurchases.get(0);
            model.setElements(StoreObserver.getInstance().getProductsPurchased());
            sectionNames.add("PURCHASED");
        }

        // Update allPurchases if there are restored products
        if (StoreObserver.getInstance().hasRestoredProducts()) {
            MyModel model = allPurchases.get(1);
            model.setElements(StoreObserver.getInstance().getProductsRestored());
            sectionNames.add("RESTORED");
        }
        // Refresh the UI with the above data
        getTableView().reloadData();
    }

    @Override
    public long getNumberOfSections(UITableView tableView) {
        int numberOfSections = 0;
        if (!allPurchases.get(0).isEmpty()) {
            numberOfSections++;
        }
        if (!allPurchases.get(1).isEmpty()) {
            numberOfSections++;
        }

        // Return the number of sections.
        return numberOfSections;
    }

    @Override
    public String getTitleForHeader(UITableView tableView, long section) {
        // Fetch the section name at the given index
        String sectionName = sectionNames.get((int) section);
        // Fetch the model whose name matches sectionName
        MyModel model = sectionName.equals("PURCHASED") ? allPurchases.get(0) : allPurchases.get(1);

        // Return the header title for this section
        return !model.isEmpty() ? model.getName() : null;
    }

    @Override
    public long getNumberOfRowsInSection(UITableView tableView, long section) {
        String sectionName = sectionNames.get((int) section);
        MyModel model = sectionName.equals("PURCHASED") ? allPurchases.get(0) : allPurchases.get(1);

        // Return the number of rows in the section.
        return model.getElements().size();
    }

    @SuppressWarnings("unchecked")
    @Override
    public UITableViewCell getCellForRow(UITableView tableView, NSIndexPath indexPath) {
        String sectionName = sectionNames.get((int) indexPath.getSection());
        MyModel model = sectionName.equals("PURCHASED") ? allPurchases.get(0) : allPurchases.get(1);
        List<SKPaymentTransaction> purchases = (List<SKPaymentTransaction>) model.getElements();

        UITableViewCell cell = tableView.dequeueReusableCell("purchasedID", indexPath);
        if (cell == null) {
            cell = new UITableViewCell(UITableViewCellStyle.Default, "purchasedID");
            cell.setSelectionStyle(UITableViewCellSelectionStyle.Blue);
            cell.setAccessoryType(UITableViewCellAccessoryType.DisclosureIndicator);
        }

        SKPaymentTransaction paymentTransaction = purchases.get((int) indexPath.getRow());
        String title = StoreManager.getInstance().getTitleForId(paymentTransaction.getPayment().getProductIdentifier());

        // Display the product's title associated with the payment's product
        // identifier if it exists or the product identifier,
        // otherwise
        cell.getTextLabel().setText(title != null ? title : paymentTransaction.getPayment().getProductIdentifier());

        return cell;
    }

    private NSDateFormatter newDateFormatter() {
        NSDateFormatter myDateFormatter = new NSDateFormatter();
        myDateFormatter.setDateStyle(NSDateFormatterStyle.Short);
        myDateFormatter.setTimeStyle(NSDateFormatterStyle.Short);
        return myDateFormatter;
    }

    @Override
    public void didSelectRow(UITableView tableView, NSIndexPath indexPath) {
        showDetails();
    }

    @SuppressWarnings("unchecked")
    private void showDetails() {
        String sectionName = sectionNames.get((int) getTableView().getIndexPathForSelectedRow().getSection());
        MyModel model = sectionName.equals("PURCHASED") ? allPurchases.get(0) : allPurchases.get(1);

        List<SKPaymentTransaction> purchases = (List<SKPaymentTransaction>) model.getElements();

        SKPaymentTransaction paymentTransaction = purchases.get((int) getTableView().getIndexPathForSelectedRow()
                .getRow());
        List<MyModel> purchaseDetails = new ArrayList<>();

        // Add the product identifier, transaction id, and transaction date to
        // purchaseDetails
        purchaseDetails.add(new MyModel("PRODUCT IDENTIFIER", paymentTransaction.getPayment().getProductIdentifier()));
        purchaseDetails.add(new MyModel("TRANSACTION ID", paymentTransaction.getTransactionIdentifier()));
        purchaseDetails.add(new MyModel("TRANSACTION DATE", newDateFormatter().format(
                paymentTransaction.getTransactionDate())));

        NSArray<SKDownload> allDownloads = paymentTransaction.getDownloads();
        // If this product is hosted, add its first download to purchaseDetails
        if (allDownloads.size() > 0) {
            // We are only showing the first download
            SKDownload firstDownload = allDownloads.first();

            Map<String, String> identifier = newKeyValuePair("Identifier", firstDownload.getContentIdentifier());
            Map<String, String> version = newKeyValuePair("Version", firstDownload.getContentVersion());
            Map<String, String> contentLength = newKeyValuePair("Length",
                    NSByteCountFormatter.format(firstDownload.getContentLength(), NSByteCountFormatterCountStyle.File));

            // Add the identifier, version, and length of a download to
            // purchaseDetails
            purchaseDetails.add(new MyModel("DOWNLOAD", identifier, version, contentLength));
        }

        // If the product is a restored one, add its original transaction's
        // transaction id and transaction date to purchaseDetails
        if (paymentTransaction.getOriginalTransaction() != null) {
            Map<String, String> transactionID = newKeyValuePair("Transaction ID", paymentTransaction
                    .getOriginalTransaction()
                    .getTransactionIdentifier());
            Map<String, String> transactionDate = newKeyValuePair("Transaction Date",
                    newDateFormatter().format(paymentTransaction.getOriginalTransaction().getTransactionDate()));

            purchaseDetails.add(new MyModel("ORIGINAL TRANSACTION", transactionID, transactionDate));
        }

        transactionDetails.setDetails(purchaseDetails);
        transactionDetails.setTitle(StoreManager.getInstance().getTitleForId(
                paymentTransaction.getPayment().getProductIdentifier()));
    }

    private Map<String, String> newKeyValuePair(String key, String value) {
        Map<String, String> pair = new HashMap<>();
        pair.put(key, value);
        return pair;
    }
}


text:
title: Working with Images in Markdown & MDX
---

When building Gatsby sites composed primarily of [markdown](/docs/how-to/routing/adding-markdown-pages/) or [MDX](/docs/how-to/routing/mdx/), insertion of images can enhance the content. You can add images in multiple ways which will be explained below. If you're new to Gatsby we recommend checking out the [main tutorial](/docs/tutorial/) first. The instructions also assume that you already have an existing Gatsby site running with either markdown or MDX.

## Prerequisites

- A Gatsby project set up. (Need help creating one? Follow the [Quick Start](/docs/quick-start/))
- Either markdown or MDX support added to your site. Follow the [MDX instructions](/docs/how-to/routing/mdx/) or [markdown instructions](/docs/how-to/routing/adding-markdown-pages/).

## Featured images with frontmatter metadata

In sites like a blog, you may want to include a featured image that appears at the top of a page. One way to do this is to grab the image filename from a frontmatter field and then transform it with `gatsby-plugin-sharp` in a GraphQL query.

If you want to have a very detailed explanation of this, head to [part 7 of the Gatsby tutorial](/docs/tutorial/part-7/). The tutorial uses MDX, the instructions below will use markdown for the most part. It more or less behaves the same though.

To start out, install the necessary plugins for [gatsby-plugin-image](/docs/how-to/images-and-media/using-gatsby-plugin-image/).

```shell
npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-sharp
```

Then, configure the various plugins in the `gatsby-config` file.

### Configuring for images and posts in the same directory

If your images are in the same directory as the markdown files, sourcing and resolving the images can be done in one configuration. For example, if your markdown files and images are located together in a `src/content` directory, both content types will be automatically picked up by GraphQL as part of Gatsby's data layer.

```js:title=gatsby-config.js
module.exports = {
  plugins: [
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
    `gatsby-transformer-remark`,
    `gatsby-plugin-image`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/content`, // highlight-line
      },
    },
  ],
}
```

Then, in an example markdown file, add a field called `featuredImage`:

```markdown:title=src/content/my-favorite-doggos.md
---
title: My Favorite Doggos
featuredImage: pupperino.png
---

Content goes here!
```

The next step will be to incorporate the data into a template with a GraphQL query, which can be found later in this guide.

### Configuring for images and posts in different directories

There are also occasions when you may want to source images from a different directory than where your markdown posts or pages are located, such as in an external `/images` folder. You can set this up by specifying two distinct sources, one for the markdown files and the other for images:

```js:title=gatsby-config.js
module.exports = {
  plugins: [
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
    `gatsby-transformer-remark`,
    `gatsby-plugin-image`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/content`, // highlight-line
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/images`, // highlight-line
      },
    },
  ],
}
```

Then, in a markdown file, the path to a `featuredImage` would be relative to the page file (in this case, in an `/images` directory up a level):

```markdown:title=src/content/about.md
---
title: About
featuredImage: ../images/team-cat.png
---

Content goes here!
```

### Querying for images from frontmatter

Now that you've sourced markdown and image data, you can query for featured images in GraphQL. If a filepath points to an actual image, it will be transformed into a `File` node in GraphQL and then you can get the image data out of it by using the `childImageSharp` field.

This can be added to the GraphQL query in a markdown template file. In this example, a [Dynamic image](/docs/how-to/images-and-media/using-gatsby-plugin-image/#dynamic-images) is used to make a responsive image. The query below might be different to what you have in your blog post template, however the highlighted section will be relevant nevertheless:

```jsx:title=src/templates/blog-post.jsx
export const query = graphql`
  query PostQuery($id: String) {
    markdownRemark(id: { eq: $id }) {
      html
      frontmatter {
        title
        // highlight-start
        featuredImage {
          childImageSharp {
            gatsbyImageData(width: 800)
          }
        }
        // highlight-end
      }
    }
  }
`
```

In the blog post template, import the `gatsby-plugin-image` package and pass the results of the GraphQL query into an `<GatsbyImage />` component.

```jsx:title=src/templates/blog-post.jsx
import * as React from "react"
import { graphql } from "gatsby"
// highlight-start
import { GatsbyImage, getImage } from "gatsby-plugin-image"
// highlight-end

export default function BlogPost({ data }) {
  let post = data.markdownRemark

  // highlight-start
  let featuredImg = getImage(post.frontmatter.featuredImage?.childImageSharp?.gatsbyImageData)
  // highlight-end

  return (
    <main>
      <h1>{post.frontmatter.title}</h1>
      // highlight-start
      <GatsbyImage image={featuredImg} />
      // highlight-end
      <div dangerouslySetInnerHTML={{ __html: post.html }} />
    </main>
  )
}

export const query = graphql`
  query PostQuery($id: String) {
    markdownRemark(id: { eq: $id }) {
      html
      frontmatter {
        title
        featuredImage {
          childImageSharp {
            gatsbyImageData(width: 800)
          }
        }
      }
    }
  }
`
```

The code example above is just an example, adjust the `<GatsbyImage />` portion to how you'd want to use it in your template.

## Inline images with `gatsby-remark-images`

You may also include images in the markdown/MDX body itself. The plugin [gatsby-remark-images](/plugins/gatsby-remark-images) comes in handy for this.

Start out by installing `gatsby-remark-images`:

```shell
npm install gatsby-remark-images
```

Configure the plugins in your `gatsby-config` file. As with the previous example, either markdown or MDX can be used.

### Using `gatsby-transformer-remark`

Put the `gatsby-remark-images` plugin within the `plugins` option field of `gatsby-transformer-remark`.

```js:title=gatsby-config.js
module.exports = {
  plugins: [
    // Rest of the plugins...
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 800,
            },
          },
        ],
      },
    },
  ],
}
```

### Using `gatsby-plugin-mdx`

`gatsby-remark-images` needs to be a sub-plugin of `gatsby-plugin-mdx`, included in the `gatsbyRemarkPlugins` array.

```js:title=gatsby-config.js
module.exports = {
  plugins: [
    // Rest of your plugins...
    {
      resolve: `gatsby-plugin-mdx`,
      options: {
        gatsbyRemarkPlugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 1200,
            },
          },
        ],
      },
    },
  ],
}
```

With the configurations above, you can use the default markdown syntax for images. They will be processed by sharp and appear as if you placed them in a `gatsby-plugin-image` component.

```markdown
![Hopper The Rabbit](./rabbit-friend.png)
```

## Additional Resources

- [Using gatsby-plugin-image](/docs/how-to/images-and-media/using-gatsby-plugin-image/)
- [Adding MDX pages](/docs/how-to/routing/mdx/)
- [Adding markdown pages](/docs/how-to/routing/adding-markdown-pages/)