text:
package pro.hirooka.chukasa.domain.service.transcoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import pro.hirooka.chukasa.domain.config.common.HyarukaConfiguration;
import pro.hirooka.chukasa.domain.config.common.type.FfmpegVcodecType;
import pro.hirooka.chukasa.domain.model.hls.ChukasaModel;
import pro.hirooka.chukasa.domain.service.hls.IChukasaModelManagementComponent;

import java.io.*;
import java.util.concurrent.Future;

import static java.util.Objects.requireNonNull;
import static pro.hirooka.chukasa.domain.config.ChukasaConstants.*;

@Service
public class FfmpegAndRecxxxService implements IFfmpegAndRecxxxService {

    private static final Logger log = LoggerFactory.getLogger(FfmpegAndRecxxxService.class);

    private final HyarukaConfiguration hyarukaConfiguration;
    private final IChukasaModelManagementComponent chukasaModelManagementComponent;

    @Autowired
    public FfmpegAndRecxxxService(
            IChukasaModelManagementComponent chukasaModelManagementComponent,
            HyarukaConfiguration hyarukaConfiguration
    ){
        this.chukasaModelManagementComponent = requireNonNull(chukasaModelManagementComponent);
        this.hyarukaConfiguration = requireNonNull(hyarukaConfiguration);
    }

    @Async
    @Override
    public Future<Integer> submit(int adaptiveBitrateStreaming) {

        // TODO: final
        ChukasaModel chukasaModel = chukasaModelManagementComponent.get(adaptiveBitrateStreaming);
        final String STREAM_FILE_EXTENSION = chukasaModel.getStreamFileExtension();
        log.debug("StreamPath: {}", chukasaModel.getStreamPath());

        final FfmpegVcodecType ffmpegVcodecType = chukasaModel.getFfmpegVcodecType();

        final boolean canEncrypt = chukasaModel.getChukasaSettings().isCanEncrypt();
        final String ffmpegOutputPath;
        final String fmp4InitFileOutputPath;
        if(canEncrypt){
            ffmpegOutputPath = chukasaModel.getTempEncPath() + FILE_SEPARATOR + STREAM_FILE_NAME_PREFIX + "%d" + STREAM_FILE_EXTENSION;
            fmp4InitFileOutputPath = chukasaModel.getTempEncPath() + FILE_SEPARATOR + STREAM_FILE_NAME_PREFIX + ".mp4";
        } else {
            ffmpegOutputPath = chukasaModel.getStreamPath() + FILE_SEPARATOR + STREAM_FILE_NAME_PREFIX + "%d" + STREAM_FILE_EXTENSION;
            fmp4InitFileOutputPath = chukasaModel.getStreamPath() + FILE_SEPARATOR + STREAM_FILE_NAME_PREFIX + ".mp4";
        }
        final String ffmpegM3U8OutputPath;
        if(canEncrypt){
            ffmpegM3U8OutputPath = chukasaModel.getTempEncPath() + FILE_SEPARATOR + M3U8_FILE_NAME + M3U8_FILE_EXTENSION;
        } else {
            ffmpegM3U8OutputPath = chukasaModel.getStreamPath() + FILE_SEPARATOR + M3U8_FILE_NAME + M3U8_FILE_EXTENSION;
        }

        chukasaModel = chukasaModelManagementComponent.update(adaptiveBitrateStreaming, chukasaModel);

        final String HYARUKA_USERNAME = getHyarukaUsername();
        final String HYARUKA_PASSWORD = getHyarukaPassword();
        final String HYARUKA_SCHEME = hyarukaConfiguration.getScheme().name();
        final String HYARUKA_HOST = hyarukaConfiguration.getHost();
        final int HYARUKA_PORT = hyarukaConfiguration.getPort();

        final String HYARUKA_URI;
        if(hyarukaConfiguration.isEnabled() && hyarukaConfiguration.isUnixDomainSocketEnabled()){
            HYARUKA_URI = "unix:" + chukasaModel.getUnixDomainSocketPath();
        }else{
            HYARUKA_URI = HYARUKA_SCHEME.toLowerCase() + "://" + HYARUKA_USERNAME + ":" + HYARUKA_PASSWORD + "@" + HYARUKA_HOST + ":" + HYARUKA_PORT
                    + "/api/v1" + "/streams"
                    + "/" + chukasaModel.getChukasaSettings().getChannelRemoteControl();
        }

        final String[] commandArray;

        if(hyarukaConfiguration.isEnabled()){
            if(ffmpegVcodecType == FfmpegVcodecType.H264_OMX){
                commandArray = new String[]{
                        chukasaModel.getSystemConfiguration().getFfmpegPath(),
                        "-i", HYARUKA_URI,
                        "-acodec", "copy",
                        //"-acodec", "aac",
                        //"-ab", chukasaModel.getChukasaSettings().getAudioBitrate() + "k",
                        //"-ar", "44100",
                        //"-ac", "2",
                        "-s", chukasaModel.getChukasaSettings().getVideoResolution(),
                        "-c:v", "h264_omx",
                        "-vf", "yadif",
                        //"-vcodec", "h264_qsv",
                        //"-g", "60",
                        //"-profile:v", "high",
                        //"-level", "4.2",
                        //"-b:v", chukasaModel.getChukasaSettings().getVideoBitrate()+"k",
                        "-threads", Integer.toString(chukasaModel.getSystemConfiguration().getFfmpegThreads()),
                        "-f", "segment",
                        "-segment_format", "mpegts",
                        "-segment_time", Integer.toString(chukasaModel.getHlsConfiguration().getDuration()),
//                  "-segment_list", m3u8OutputPath,
                        ffmpegOutputPath
                };
            } else if(ffmpegVcodecType == FfmpegVcodecType.H264_QSV) {
                commandArray = new String[]{
                        chukasaModel.getSystemConfiguration().getFfmpegPath(),
                        "-i", HYARUKA_URI,
                        "-acodec", "aac",
                        "-ab", chukasaModel.getChukasaSettings().getAudioBitrate() + "k",
                        "-ar", "48000",
                        "-ac", "2",
                        "-s", chukasaModel.getChukasaSettings().getVideoResolution(),
                        "-vcodec", "h264_qsv",
                        "-init_hw_device", "qsv:hw",
                        "-vf", "yadif",
                        "-g", "60",
                        "-profile:v", "high",
                        "-level", "4.2",
                        "-b:v", chukasaModel.getChukasaSettings().getVideoBitrate() + "k",
                        "-threads", Integer.toString(chukasaModel.getSystemConfiguration().getFfmpegThreads()),
                        "-f", "segment",
                        "-segment_format", "mpegts",
                        "-segment_time", Integer.toString(chukasaModel.getHlsConfiguration().getDuration()),
//                    "-segment_list", m3u8OutputPath,
                        ffmpegOutputPath
                };
            }else if(ffmpegVcodecType == FfmpegVcodecType.HEVC_QSV){
                // TODO: not working
                commandArray = new String[]{
                        chukasaModel.getSystemConfiguration().getFfmpegPath(),
                        "-i", HYARUKA_URI,
                        "-acodec", "aac",
                        "-ab", chukasaModel.getChukasaSettings().getAudioBitrate() + "k",
                        "-ar", "48000",
                        "-ac", "2",
                        "-s", chukasaModel.getChukasaSettings().getVideoResolution(),
                        "-vcodec", "hevc_qsv",
                        "-init_hw_device", "qsv:hw",
                        "-load_plugin", "hevc_hw",
                        "-maxrate", "50000k",
                        "-tag:v", "hvc1",
                        "-vf", "yadif",
                        "-g", "60",
                        "-b:v", chukasaModel.getChukasaSettings().getVideoBitrate() + "k",
                        "-threads", Integer.toString(chukasaModel.getSystemConfiguration().getFfmpegThreads()),
                        "-f", "hls",
                        "-hls_segment_type", "fmp4",
                        "-hls_time", Integer.toString(chukasaModel.getHlsConfiguration().getDuration()),
                        "-hls_fmp4_init_filename", fmp4InitFileOutputPath,
                        //"-hls_segment_filename", ffmpegOutputPath,
                        ffmpegM3U8OutputPath
                };
            }else if(ffmpegVcodecType == FfmpegVcodecType.H264_X264) {
                commandArray = new String[]{
                        chukasaModel.getSystemConfiguration().getFfmpegPath(),
                        "-i", HYARUKA_URI,
                        "-acodec", "aac",
                        "-ab", chukasaModel.getChukasaSettings().getAudioBitrate() + "k",
                        "-ar", "48000",
                        "-ac", "2",
                        "-s", chukasaModel.getChukasaSettings().getVideoResolution(),
                        "-vcodec", "libx264",
                        "-vf", "yadif",
                        "-profile:v", "high",
                        "-level", "4.1",
                        "-b:v", chukasaModel.getChukasaSettings().getVideoBitrate() + "k",
                        "-preset:v", "superfast",
                        "-threads", Integer.toString(chukasaModel.getSystemConfiguration().getFfmpegThreads()),
                        "-f", "segment",
                        "-segment_format", "mpegts",
                        "-segment_time", Integer.toString(chukasaModel.getHlsConfiguration().getDuration()),
//                    "-segment_list", m3u8OutputPath,
                        "-x264opts", "keyint=10:min-keyint=10",
                        ffmpegOutputPath
                };
            } else if(ffmpegVcodecType == FfmpegVcodecType.H264_NVENC){
                commandArray = new String[]{
                        chukasaModel.getSystemConfiguration().getFfmpegPath(),
                        "-i", HYARUKA_URI,
                        "-acodec", "aac",
                        "-ab", chukasaModel.getChukasaSettings().getAudioBitrate() + "k",
                        "-ar", "48000",
                        "-ac", "2",
                        "-s", chukasaModel.getChukasaSettings().getVideoResolution(),
                        "-vcodec", "h264_nvenc",
                        "-vf", "yadif",
                        "-g", "10",
                        "-b:v", chukasaModel.getChukasaSettings().getVideoBitrate() + "k",
                        "-threads", Integer.toString(chukasaModel.getSystemConfiguration().getFfmpegThreads()),
                        "-f", "hls",
                        "-hls_time", Integer.toString(chukasaModel.getHlsConfiguration().getDuration()),
                        "-hls_segment_filename", ffmpegOutputPath,
                        ffmpegM3U8OutputPath
                };
            } else if(ffmpegVcodecType == FfmpegVcodecType.HEVC_NVENC) {
                commandArray = new String[]{
                        chukasaModel.getSystemConfiguration().getFfmpegPath(),
                        "-i", HYARUKA_URI,
                        "-acodec", "aac",
                        "-ab", chukasaModel.getChukasaSettings().getAudioBitrate() + "k",
                        "-ar", "48000",
                        "-ac", "2",
                        "-s", chukasaModel.getChukasaSettings().getVideoResolution(),
                        "-vcodec", "hevc_nvenc",
                        "-tag:v", "hvc1",
                        "-vf", "yadif",
                        "-g", "10",
                        "-b:v", chukasaModel.getChukasaSettings().getVideoBitrate() + "k",
                        "-threads", Integer.toString(chukasaModel.getSystemConfiguration().getFfmpegThreads()),
                        "-f", "hls",
                        "-hls_segment_type", "fmp4",
                        "-hls_time", Integer.toString(chukasaModel.getHlsConfiguration().getDuration()),
                        "-hls_fmp4_init_filename", FMP4_INIT_FILE_NAME + FMP4_INIT_FILE_EXTENSION,
                        ffmpegM3U8OutputPath
                };
            } else if (ffmpegVcodecType == FfmpegVcodecType.H264_VIDEOTOOLBOX) {
                commandArray = new String[]{
                        chukasaModel.getSystemConfiguration().getFfmpegPath(),
                        "-i", HYARUKA_URI,
                        "-acodec", "aac",
                        "-ab", chukasaModel.getChukasaSettings().getAudioBitrate() + "k",
                        "-ar", "48000",
                        "-ac", "2",
                        "-s", chukasaModel.getChukasaSettings().getVideoResolution(),
                        "-vcodec", "h264_videotoolbox",
                        "-vf", "yadif",
                        "-g", "10",
                        "-b:v", chukasaModel.getChukasaSettings().getVideoBitrate() + "k",
                        "-threads", Integer.toString(chukasaModel.getSystemConfiguration().getFfmpegThreads()),
                        "-f", "hls",
                        "-hls_time", Integer.toString(chukasaModel.getHlsConfiguration().getDuration()),
                        "-hls_segment_filename", ffmpegOutputPath,
                        ffmpegM3U8OutputPath
                };
            } else if (ffmpegVcodecType == FfmpegVcodecType.HEVC_VIDEOTOOLBOX) {
                commandArray = new String[]{
                        chukasaModel.getSystemConfiguration().getFfmpegPath(),
                        "-i", HYARUKA_URI,
                        "-acodec", "aac",
                        "-ab", chukasaModel.getChukasaSettings().getAudioBitrate() + "k",
                        "-ar", "48000",
                        "-ac", "2",
                        "-s", chukasaModel.getChukasaSettings().getVideoResolution(),
                        "-vcodec", "hevc_videotoolbox",
                        "-tag:v", "hvc1",
                        "-vf", "yadif",
                        "-g", "10",
                        "-b:v", chukasaModel.getChukasaSettings().getVideoBitrate() + "k",
                        "-threads", Integer.toString(chukasaModel.getSystemConfiguration().getFfmpegThreads()),
                        "-f", "hls",
                        "-hls_segment_type", "fmp4",
                        "-hls_time", Integer.toString(chukasaModel.getHlsConfiguration().getDuration()),
                        "-hls_fmp4_init_filename", FMP4_INIT_FILE_NAME + FMP4_INIT_FILE_EXTENSION,
                        ffmpegM3U8OutputPath
                };
            } else {
                commandArray = new String[]{};
                log.error("");
            }
        }else{
            commandArray = new String[]{};
            log.error("");
        }

        String command = "";
        for(int i = 0; i < commandArray.length; i++){
            command += commandArray[i] + " ";
        }
        log.info("{}", command);

        final ProcessBuilder processBuilder = new ProcessBuilder(commandArray);
        final Process process;
        try {
            process = processBuilder.start();
            final long pid = process.pid();
            final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String str = "";
            boolean isTranscoding = false;
            while((str = bufferedReader.readLine()) != null){
                log.debug("{}", str);
                if(str.startsWith("frame=")){
                    if(!isTranscoding){
                        isTranscoding = true;
                        chukasaModel.setTrascoding(isTranscoding);
                        chukasaModel.setFfmpegPID(pid);
                        chukasaModel.setFfmpegProcess(process);
                        chukasaModel = chukasaModelManagementComponent.update(adaptiveBitrateStreaming, chukasaModel);
                    }
                }
            }
            isTranscoding = false;
            chukasaModel.setTrascoding(isTranscoding);
            chukasaModel.setFfmpegPID(-1);
            chukasaModel.setFfmpegProcess(null);
            chukasaModelManagementComponent.update(adaptiveBitrateStreaming, chukasaModel);
            process.getInputStream().close();
            process.getErrorStream().close();
            process.getOutputStream().close();
            bufferedReader.close();
            process.destroy();
        } catch (IOException e) {
            log.warn("{}", e.getMessage());
        } finally {
            log.info("stream is closed.");
        }
        return new AsyncResult<>(0);
    }

    @Override
    public void execute(int adaptiveBitrateStreaming) {

    }

    @Override
    public void cancel(int adaptiveBitrateStreaming) {
        ChukasaModel chukasaModel = chukasaModelManagementComponent.get(adaptiveBitrateStreaming);
        chukasaModel.setTunerDeviceName("");
        chukasaModel.setFfmpegPID(-1);
        if(chukasaModel.getFfmpegProcess() != null){
            chukasaModel.getFfmpegProcess().destroy();
            chukasaModel.setFfmpegProcess(null);
        }
        chukasaModelManagementComponent.update(adaptiveBitrateStreaming, chukasaModel);
    }

    // TODO:
    private String getHyarukaUsername(){
        if(hyarukaConfiguration.getUsername().equals("")) {
            return DEFAULT_HYARUKA_USERNAME;
        }else{
            return hyarukaConfiguration.getUsername();
        }
    }

    private String getHyarukaPassword(){
        if(hyarukaConfiguration.getPassword().equals("")) {
            return DEFAULT_HYARUKA_PASSWORD;
        }else{
            return hyarukaConfiguration.getPassword();
        }
    }
}


text:
require 'spec_helper'

class ExampleServiceObject < MagLev::ActiveJob::ServiceObject
  argument :name, type: String, guard: :nil

  attr_reader :new_name

  protected

  def on_perform
    @new_name = "new #{name}"
  end
end

describe MagLev::ActiveJob::ServiceObject do
  let(:so) { ExampleServiceObject.new('name') }

  it 'should support arguments' do
    expect(so.name).to eq 'name'
  end

  it 'should mark as performed when enqueued' do
    so.enqueue
    expect(ExampleServiceObject.performed_jobs.first).to be_performed
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <url>
    <loc>http://generacesnazorem.cz/index.html</loc>
    <lastmod>2017-10-03</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2015.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2019.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/asset%2032@2x.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2021-crop-u4192.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2021-crop-u4178.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/asset%2031@2x.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/asset%2030@2x.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2021-crop-u4150.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2021-crop-u4164.png</image:loc>
    </image:image>
  </url>
  <url>
    <loc>http://generacesnazorem.cz/varianta-a.html</loc>
    <lastmod>2017-10-03</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2015.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2021.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%208.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%209.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%207.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%206.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%205.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%201.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2013.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2014.jpg</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2018.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2017.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2016.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2012.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%202.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2019.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2020.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2010.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2011.png</image:loc>
    </image:image>
  </url>
  <url>
    <loc>http://generacesnazorem.cz/varianta-b.html</loc>
    <lastmod>2017-10-03</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2015.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2021.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%208.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%209.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%206.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2013.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2018.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2017.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2016.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2012.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2019.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2010.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2011.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2024.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2023.png</image:loc>
    </image:image>
    <image:image>
      <image:loc>http://generacesnazorem.cz/images/artwork%2022.png</image:loc>
    </image:image>
  </url>
</urlset>


text:
function [f,x,y] = rsgeng2D(N,rL,h,cl,opt)
%
% [f,x,y] = rsgeng2D(N,rL,h,cl,opt)
%
% generates a square isotropic 2-dimensional Gaussian random rough surface
% f(x,y) with NxN surface points. The surface has a Gaussian height distribution
% function and Gaussian autocovariance functions (in both x and y),
% where rL is the length of the surface side, h is the RMS height and cl is
% the correlation length.
%
% Input:    N   - number of surface points (along square side)
%           rL  - length of surface (along square side)
%           h   - rms height
%           cl  - correlation length
%           opt - optional parameter (type 'plot' for plotting surface
%                 profile)
%
% Output:   f  - surface heights
%           x  - surface points
%           y  - surface points
%
% Last updated: 2009-02-23 (David Bergström).
%

% format long;

x = linspace(-rL/2,rL/2,N); y = linspace(-rL/2,rL/2,N);

Z = h.*randn(N,N); % uncorrelated Gaussian random rough surface distribution
                   % with mean 0 and standard deviation h

% Gaussian filter
F = zeros(N,N);
for n = 1:N;
  for m = 1:N;
      F(n,m) = 2/sqrt(pi)*exp(-((x(1,n))^2+(y(1,m))^2)/(cl^2/2));
  end;
end;

%correlation of surface including convolution (faltung), inverse
%Fourier transform and suitable prefactors

f = rL/N/cl*ifft2(fft2(Z).*fft2(F));

% optional plotting
if nargin<5 || isempty(opt)
    return;
end;
if nargin==5
    if ischar(opt)
        if strcmp(opt,'plot');
            mesh(y,x,f);
            xlabel('x')
            ylabel('y')
            zlabel('z=f(x,y)')
            title('Plot of generated surface z=f(x,y)')
        else fprintf('%s is not a valid option. Type \''help rsgeng2D\'' for further details.\n',opt);
        end;
    else fprintf('Option must be a string. Type \''help rsgeng2D\'' for further details.\n');
    end;
end;


text: """Metadata linking semantic meaning of EIA 860 spreadsheet columns across years."""


text:
<?php

namespace garethp\ews\API\Type;

/**
 * Class representing AlternatePublicFolderItemIdType
 *
 * Represents an alternate public folder item Id.
 * XSD Type: AlternatePublicFolderItemIdType
 *
 * @method string getItemId()
 * @method AlternatePublicFolderItemIdType setItemId(string $itemId)
 */
class AlternatePublicFolderItemIdType extends AlternatePublicFolderIdType
{

    /**
     * @var string
     */
    protected $itemId = null;
}


text:
<?php if (false !== $label): ?>
<?php if ($required) { $label_attr['class'] = trim((isset($label_attr['class']) ? $label_attr['class'] : '').' required'); } ?>
<?php if (!$compound) { $label_attr['for'] = $id; } ?>
<?php if (!$label) { $label = isset($label_format)
    ? strtr($label_format, array('%name%' => $name, '%id%' => $id))
    : $view['form']->humanize($name); } ?>
<label<?php if ($label_attr) { echo ' '.$view['form']->block($form, 'attributes', array('attr' => $label_attr)); } ?>><?php echo $view->escape(false !== $translation_domain ? $view['translator']->trans($label, array(), $translation_domain) : $label) ?></label>
<?php endif ?>


text:
"""
Modprobe configuration - files ``/etc/modprobe.conf`` and ``/etc/modprobe.d/*.conf``
====================================================================================

This parser collects command information from the Modprobe configuration
files and stores information about each module mentioned. Lines such as
comments and those without the commands 'alias', 'blacklist', 'install',
'options', 'remove' and 'softdep' are ignored.

Blacklisted modules simply have True as their value in the dictionary.  Alias
lines list the module last, and these are recorded as a list of aliases.  For
all other commands the module name (after the command) is used as the key,
and the rest of the line is split up and stored as a list.  Any lines that
don't parse, either because they're not long enough or because they don't
start with a valid keyword, are stored in the ``bad_lines`` property list.

Sample file ``/etc/modprobe.conf``::

    alias scsi_hostadapter2 qla2xxx
    alias scsi_hostadapter3 usb-storage
    alias net-pf-10 off
    alias ipv6 off
    alias bond0 bonding
    alias bond1 bonding
    options bonding max_bonds=2
    options bnx2 disable_msi=1

Examples:

    >>> mconf_list = shared[ModProbe] # A list: multiple files may be found
    >>> for mconf in mconf_list:
    ...     print "File:", mconf.file_name
    ...     print "Modules with aliases:", sorted(mconf.data['alias'].keys())
    File: /etc/modprobe.conf
    Modules with aliases: ['bonding', 'off', 'qla2xxx', 'usb-storage']
"""

from collections import defaultdict
from .. import Parser, parser, get_active_lines, LegacyItemAccess
from insights.specs import Specs

@parser(Specs.modprobe)
class ModProbe(LegacyItemAccess, Parser):
    """
    Parse Modprobe configuration files - /etc/modprobe.conf and files in the
    /etc/modprobe.d/ directory.
    """

    COMMAND_LIST = ["alias", "blacklist", "install", "options", "remove", "softdep"]

    def parse_content(self, content):
        self.data = defaultdict(dict)
        self.bad_lines = []
        for line in get_active_lines(content):
            parts = line.split()
            if len(parts) > 1 and parts[0] in self.COMMAND_LIST:
                command = parts[0]
                # Blacklist just gives the module name - set its value to True
                if command == 'blacklist':
                    self.data[command][parts[1]] = True
                elif parts[0] == 'alias':
                    # module name comes second for aliases
                    if len(parts) != 3:
                        self.bad_lines.append(line)
                        continue
                    modname = parts[2]
                    # one module can have multiple aliases
                    if modname not in self.data[command]:
                        self.data[command][modname] = []
                    self.data[command][modname].append(parts[1])
                else:
                    self.data[command][parts[1]] = parts[2:]
            else:
                self.bad_lines.append(line)


text:
package com.alex.fakecall.models;

import android.net.Uri;

import com.alex.fakecall.utils.Utils;

import java.io.File;

public class Voice {
    public static final String TAG = "Voice";
    private String uriString;
    private String name;
    private long duration;
    private int sizeKB;

    public Voice(File file) {
        uriString = Uri.fromFile(file).toString();
        name = file.getName();
        duration = Utils.getDurationOfAudioFile(file);
        sizeKB = (int) (file.length() / 1024);
    }

    public String getUriString() {
        return uriString;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSizeKB() {
        return sizeKB;
    }

    public String getFormattedDuration() {
        int seconds = (int) (duration / 1000) % 60;
        int minutes = (int) ((duration / (1000 * 60)) % 60);
        int hours = (int) ((duration / (1000 * 60 * 60)) % 24);
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }
}


text:
using System.Configuration;

namespace DocStore.Business.Util
{
    /// Class that provides the connection
    /// strings used by the application.
    internal static class Database
    {
        /// Connection string to the DocStore database.
        internal static string DocStoreConnection
        {
            get { return ConfigurationManager.ConnectionStrings["DocStore"].ConnectionString; }
        }
    }
}


text:
// TODO: move to backend, into graph/
#pragma once

#include "common/config.h"
#include "tensors/tensor.h"
#include "tensors/tensor_operators.h"

#include <functional>
#include <random>

namespace marian {

class ExpressionGraph; // Forward declaration

namespace inits {

/**
 * Base class for specialized NodeInitializers.
 *
 * A NodeInitializer is a functor that is associated with parameters
 * and constants, and is invoked on a tensor during node intialization.
 * You need to override NodeIntializer::apply(Tensor) with your own
 * functionality or use a fromLambda intializer.
 *
 * See node_initializers.cpp for examples.
 */
class NodeInitializer {
protected:
  Weak<Allocator> allocator_;

public:
  virtual void apply(Tensor t) = 0;
  void setAllocator(Ptr<Allocator> allocator) { allocator_ = allocator; }
  virtual ~NodeInitializer() {}
};

/**
 * Use a lambda function of form [](Tensor t) { do something with t } to initalize tensor
 */
Ptr<NodeInitializer> fromLambda(std::function<void(Tensor)>&& func);

/**
 * Use a lambda function of form [](Tensor t) { do something with t } to initalize tensor
 * Create temporary tensor of Type intermediateType first, initialize and then copy/convert to actual Tensor
 * Useful for functions that can only operate on a specific type of tensor
 */
Ptr<NodeInitializer> fromLambda(std::function<void(Tensor)>&& func, Type intermediateType);

/**
 * Initialize tensor with given value
 *
 * Creates a NodeInitializer that will intialize the given tensor
 * with `value`. Works with any underlying numeric tensor type.
 *
 * @return A NodeInitializer
 */
Ptr<NodeInitializer> fromValue(float value);

/**
 * Fill tensor with `0`
 *
 * Creates a NodeInitializer that will intialize the given tensor
 * with `0`. Works with any underlying numeric tensor type.
 *
 * @return A NodeInitializer
 */
static Ptr<NodeInitializer> zeros() { return fromValue(0.0f); }

/**
 * Fill tensor with `1`
 *
 * Creates a NodeInitializer that will intialize the given tensor
 * with `1`. Works with any underlying numeric tensor type.
 *
 * @return A NodeInitializer
 */
static Ptr<NodeInitializer> ones() { return fromValue(1.0f); }

/**
 * Set diagonal of two dimensional quadratic matrix to `value`.
 *
 * Sets all values of the tensor to 0 and intializes the diagonal with
 * the given `value`. If no value is specified `1` is used by default.
 *
 * @return A NodeInitializer
 */
Ptr<NodeInitializer> eye(float value = 1.f);

/**
 * Intialize tensor with normally distributed random numbers
 *
 * Be default this generates floating point numbers from the
 * normal distribution Normal(0, 1) unless specified differently.
 *
 * If compiled with `CUDA`, `marian` will use the `cuRand` library
 * for both, GPU and CPU computation. The random sequences generated
 * are the same on both devices.
 *
 * If `marian` is compiled without `CUDA`, a random generator
 * from the C++ standard library is used. These random generators
 * do not have the same random sequences.
 *
 * @return A NodeInitializer
 */
Ptr<NodeInitializer> normal(float mean = 0.f, float stddev = 1.f);

/**
 * Intialize tensor with uniformly distributed random numbers
 *
 * Be default this generates floating point numbers from the
 * uniform distribution Uniform(0, 1) unless specified differently.
 *
 * If compiled with `CUDA`, `marian` will use the `cuRand` library
 * for both, GPU and CPU computation. The random sequences generated
 * are the same on both devices.
 *
 * If `marian` is compiled without `CUDA`, a random generator
 * from the C++ standard library is used. These random generators
 * do not have the same random sequences.
 *
 * @return A NodeInitializer
 */
Ptr<NodeInitializer> uniform(float a = 0.f, float b = 1.f);

// @TODO: add documentation
Ptr<NodeInitializer> bernoulli(float p, float scale = 1.f, float shift = 0.f);

// @TODO: add documentation
Ptr<NodeInitializer> glorotUniform(bool fanIn = false, bool fanOut = false, float scale = 1.f);

// @TODO: add documentation
Ptr<NodeInitializer> glorotNormal(bool fanIn = false, bool fanOut = false, float scale = 1.f);

// @TODO: add documentation
Ptr<NodeInitializer> dropout(float dropoutProbabilty);

/**
 * Intialize with gumbel noise, i.e. -log(-log(u)) where u ~ Uniform(0 + eps, 1 - eps)
 *
 * @return A NodeInitializer
 */
Ptr<NodeInitializer> gumbel(float eps = 1e-5f);

// @TODO: add documentation
template <typename T>
Ptr<NodeInitializer> fromVector(const std::vector<T>& v);
template <typename T>
Ptr<NodeInitializer> fromVector(std::vector<T>&& v);

// @TODO: add documentation
Ptr<NodeInitializer> fromSparseVector(std::pair<std::vector<size_t>, std::vector<float>>& v);

// @TODO: add documentation
Ptr<NodeInitializer> fromItem(const io::Item& item);

// @TODO: add documentation
Ptr<NodeInitializer> fromTensor(Tensor tensor);

// @TODO: add documentation
Ptr<NodeInitializer> fromWord2vec(const std::string& file,
                                  int dimVoc,
                                  int dimEmb,
                                  bool normalize = false);

/**
 * Computes Google's Transformer-style sinusoidal position embeddings
 * starting from position 'start' taking into account batch and time
 * dimensions of the tensor.
 *
 * Expected tensor layout {-2: time, -1: model}
 *
 * Usually gets later reshaped to {time, 1, model} and
 * added with a broadcast to learned embeddings. Positional
 * embeddings are the same for each batch entry and change
 * over time steps.
 */
Ptr<NodeInitializer> sinusoidalPositionEmbeddings(int start);

/**
 * Computes a random rotation matrix for LSH hashing. This is part
 * of a hash function. The values are orthonormal and computed via
 * QR decomposition. Same seed results in same random rotation.
 */
Ptr<NodeInitializer> randomRotation(size_t seed = Config::seed);

/**
 * Computes a range from begin to end-1, like Python's range().
 * The constant being initialized must have one dimension that matches
 * the number of elements being generated, while any other dimension must be 1.
 */
template <typename T>
Ptr<NodeInitializer> range(T begin, T end, T step = (T)1);

}  // namespace inits

}  // namespace marian


text:
As of React JS 0.13 you will be able to define components as classes.

在 React JS 0.13 中,你可以把组件定义为类。

```javascript
class MyComponent extends React.Component {
  constructor() {
    this.state = {message: 'Hello world'};
  }
  render() {
    return (
      <h1>{this.state.message}</h1>
    );
  }
}
```

This gives you a very short and nice syntax for defining components. A drawback with using classes though is the lack of mixins. That said, you are not totally lost. Lets us see how we could still use the important **PureRenderMixin**.

这样能够写出非常短且优雅的语法来定义组件。使用类的缺点是缺乏了很多 mixin,不过,不是所有的不能用,让我们来看看使用重要的 **PureRenderMixin**:

```javascript
import React from 'react/addons';

class Component extends React.Component {
  shouldComponentUpdate() {
    return React.addons.PureRenderMixin.shouldComponentUpdate.apply(this, arguments);
  }
}

class MyComponent extends Component {
  constructor() {
    this.state = {message: 'Hello world'};
  }
  render() {
    return (
      <h1>{this.state.message}</h1>
    );
  }
}
```


text:
using System;
using System.Collections.Generic;
using System.Text;

class ExceptionsHomework
{
    public static T[] Subsequence<T>(T[] arr, int startIndex, int count)
    {
        List<T> result = new List<T>();
        for (int i = startIndex; i < startIndex + count; i++)
        {
            result.Add(arr[i]);
        }
        return result.ToArray();
    }

    public static string ExtractEnding(string str, int count)
    {
        if (count > str.Length)
        {
            throw new ArgumentOutOfRangeException("count");
        }

        StringBuilder result = new StringBuilder();
        for (int i = str.Length - count; i < str.Length; i++)
        {
            result.Append(str[i]);
        }

        return result.ToString();
    }

    public static bool CheckPrime(int number)
    {
        if (number <= 1)
        {
            return false;
        }

        for (int divisor = 2; divisor <= Math.Sqrt(number); divisor++)
        {
            if (number % divisor == 0)
            {
                return false;
            }
        }

        return true;
    }

    static void Main()
    {
        var substr = Subsequence("Hello!".ToCharArray(), 2, 3);
        Console.WriteLine(substr);

        var subarr = Subsequence(new int[] { -1, 3, 2, 1 }, 0, 2);
        Console.WriteLine(String.Join(" ", subarr));

        var allarr = Subsequence(new int[] { -1, 3, 2, 1 }, 0, 4);
        Console.WriteLine(String.Join(" ", allarr));

        var emptyarr = Subsequence(new int[] { -1, 3, 2, 1 }, 0, 0);
        Console.WriteLine(String.Join(" ", emptyarr));

        Console.WriteLine(ExtractEnding("I love C#", 2));
        Console.WriteLine(ExtractEnding("Nakov", 4));
        Console.WriteLine(ExtractEnding("beer", 4));
        // Console.WriteLine(ExtractEnding("Hi", 100));

        Console.WriteLine("23 is" + (CheckPrime(23) ? "" : " not") + " prime.");
        Console.WriteLine("33 is" + (CheckPrime(33) ? "" : " not") + " prime.");

        List<Exam> peterExams = new List<Exam>()
        {
            new SimpleMathExam(2),
            new CSharpExam(55),
            new CSharpExam(100),
            new SimpleMathExam(1),
            new CSharpExam(0),
        };
        Student peter = new Student("Peter", "Petrov", peterExams);
        double peterAverageResult = peter.CalcAverageExamResultInPercents();
        Console.WriteLine("Average results = {0:p0}", peterAverageResult);
    }
}


text:
package modules

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/wx13/genesis"
)

type Mkdir struct {
	Path   string
	Absent bool
	Empty  bool
}

func (mkdir Mkdir) ID() string {
	return fmt.Sprintf("Mkdir: %+v", mkdir)
}

func (mkdir Mkdir) Files() []string {
	return []string{}
}

func (mkdir Mkdir) isExist() bool {
	_, err := os.Stat(mkdir.Path)
	if err == nil {
		return true
	}
	return false
}

func (mkdir Mkdir) isDir() bool {
	s, err := os.Stat(mkdir.Path)
	if err != nil {
		return false
	}
	return s.IsDir()
}

func (mkdir Mkdir) isEmpty() bool {
	f, err := os.Open(mkdir.Path)
	if err != nil {
		return true
	}
	defer f.Close()
	_, err = f.Readdirnames(1)
	if err != nil {
		return true
	}
	return false
}

func (mkdir Mkdir) Status() (genesis.Status, string, error) {

	mkdir.Path = genesis.ExpandHome(mkdir.Path)

	// No matter what, if path points to a file (not a dir),
	// then we are in failure.
	if mkdir.isExist() && !mkdir.isDir() {
		return genesis.StatusFail, "This is a file, not a directory.", nil
	}

	if mkdir.Absent {
		if mkdir.isDir() {
			return genesis.StatusFail, "Directory exists.", nil
		}
		return genesis.StatusPass, "Directory does not exist.", nil
	}

	// Whether empty or not, directory must exist.
	if !mkdir.isDir() {
		return genesis.StatusFail, "Directory does not exist.", nil
	}

	if mkdir.Empty {
		if mkdir.isEmpty() {
			return genesis.StatusPass, "Directory is empty.", nil
		}
		return genesis.StatusFail, "Directory is not empty.", nil
	}

	return genesis.StatusPass, "Directory exists.", nil
}

func (mkdir Mkdir) Remove() (string, error) {
	if mkdir.Absent {
		return "Can't un-remove a directory", nil
	}
	mkdir.Path = genesis.ExpandHome(mkdir.Path)
	err := os.RemoveAll(mkdir.Path)
	if err != nil {
		return "Could not remove directory", err
	}
	return "Removed directory and all its contents", nil
}

func (mkdir Mkdir) Install() (string, error) {

	mkdir.Path = genesis.ExpandHome(mkdir.Path)

	if mkdir.Absent {
		err := os.RemoveAll(mkdir.Path)
		if err != nil {
			return "Could not remove directory", err
		}
		return "Removed directory and all its contents", nil
	}

	err := os.MkdirAll(mkdir.Path, 0755)
	if err != nil {
		return "Could not make directory", err
	}

	if mkdir.Empty {
		err := mkdir.makeEmpty()
		if err != nil {
			return "Could not remove directory contents.", err
		}
		return "Created empty directory", nil
	}

	return "Made directory", nil
}

func (mkdir Mkdir) makeEmpty() error {
	d, err := os.Open(mkdir.Path)
	if err != nil {
		return err
	}
	defer d.Close()
	names, err := d.Readdirnames(-1)
	if err != nil {
		return err
	}
	for _, name := range names {
		err = os.RemoveAll(filepath.Join(mkdir.Path, name))
		if err != nil {
			return err
		}
	}
	return nil
}


text:
/*
 * This file is generated by jOOQ.
*/
package uni.akilis.jooq.generated.tables;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Generated;

import org.jooq.Field;
import org.jooq.Identity;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;

import uni.akilis.jooq.generated.Keys;
import uni.akilis.jooq.generated.Pldb;
import uni.akilis.jooq.generated.tables.records.PlmalfunctionrecordRecord;

/**
 * This class is generated by jOOQ.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.9.1"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Plmalfunctionrecord extends TableImpl<PlmalfunctionrecordRecord> {

    private static final long serialVersionUID = -770790868;

    /**
     * The reference instance of pldb.plmalfunctionrecord
     */
    public static final Plmalfunctionrecord PLMALFUNCTIONRECORD = new Plmalfunctionrecord();

    /**
     * The class holding records for this type
     */
    @Override
    public Class<PlmalfunctionrecordRecord> getRecordType() {
        return PlmalfunctionrecordRecord.class;
    }

    /**
     * The column pldb.plmalfunctionrecord.id.
     */
    public final TableField<PlmalfunctionrecordRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");

    /**
     * The column pldb.plmalfunctionrecord.time. 故障出现的时间
     */
    public final TableField<PlmalfunctionrecordRecord, Timestamp> TIME = createField("time", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "故障出现的时间");

    /**
     * The column pldb.plmalfunctionrecord.type. 故障类型,如传感器、相机等出现故障的设备名称
     */
    public final TableField<PlmalfunctionrecordRecord, String> TYPE = createField("type", org.jooq.impl.SQLDataType.VARCHAR.length(45).nullable(false), this, "故障类型,如传感器、相机等出现故障的设备名称");

    /**
     * The column pldb.plmalfunctionrecord.description. 故障的简单描述
     */
    public final TableField<PlmalfunctionrecordRecord, String> DESCRIPTION = createField("description", org.jooq.impl.SQLDataType.VARCHAR.length(45), this, "故障的简单描述");

    /**
     * Create a pldb.plmalfunctionrecord table reference
     */
    public Plmalfunctionrecord() {
        this("plmalfunctionrecord", null);
    }

    /**
     * Create an aliased pldb.plmalfunctionrecord table reference
     */
    public Plmalfunctionrecord(String alias) {
        this(alias, PLMALFUNCTIONRECORD);
    }

    private Plmalfunctionrecord(String alias, Table<PlmalfunctionrecordRecord> aliased) {
        this(alias, aliased, null);
    }

    private Plmalfunctionrecord(String alias, Table<PlmalfunctionrecordRecord> aliased, Field<?>[] parameters) {
        super(alias, null, aliased, parameters, "");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Schema getSchema() {
        return Pldb.PLDB;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Identity<PlmalfunctionrecordRecord, Integer> getIdentity() {
        return Keys.IDENTITY_PLMALFUNCTIONRECORD;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UniqueKey<PlmalfunctionrecordRecord> getPrimaryKey() {
        return Keys.KEY_PLMALFUNCTIONRECORD_PRIMARY;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<UniqueKey<PlmalfunctionrecordRecord>> getKeys() {
        return Arrays.<UniqueKey<PlmalfunctionrecordRecord>>asList(Keys.KEY_PLMALFUNCTIONRECORD_PRIMARY);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Plmalfunctionrecord as(String alias) {
        return new Plmalfunctionrecord(alias, this);
    }

    /**
     * Rename this table
     */
    @Override
    public Plmalfunctionrecord rename(String name) {
        return new Plmalfunctionrecord(name, null);
    }
}


text:
package slice

import (
	"fmt"
	"reflect"
	"sort"

	"go4.org/reflectutil"
)

// Sort sorts the provided slice using the function less.
// If slice is not a slice, Sort panics.
func Sort(slice interface{}, less func(i, j int) bool) {
	sort.Sort(SortInterface(slice, less))
}

// SortInterface returns a sort.Interface to sort the provided slice
// using the function less.
func SortInterface(slice interface{}, less func(i, j int) bool) sort.Interface {
	sv := reflect.ValueOf(slice)
	if sv.Kind() != reflect.Slice {
		panic(fmt.Sprintf("slice.Sort called with non-slice value of type %T", slice))
	}
	return &funcs{
		length: sv.Len(),
		less:   less,
		swap:   reflectutil.Swapper(slice),
	}
}

type funcs struct {
	length int
	less   func(i, j int) bool
	swap   func(i, j int)
}

func (f *funcs) Len() int           { return f.length }
func (f *funcs) Less(i, j int) bool { return f.less(i, j) }
func (f *funcs) Swap(i, j int)      { f.swap(i, j) }


text:
/**
 * @fileoverview This file contains functions to make it extremely simple
 *     to get something on the screen in o3d. The disadvantage is it
 *     is less flexible and creates inefficient assets.
 *
 * Example
 *
 *

 * <html><body>
 * <script type="text/javascript" src="o3djs/all.js">
 * </script>
 * <script type="text/javascript">
 * window.init = init;
 *
 * function init() {
 *   o3djs.base.makeClients(initStep2);
 * }
 *
 * function initStep2(clientElements) {
 *   var clientElement = clientElements[0];
 *
 *   // Create an o3djs.simple object to manage things in a simple way.
 *   g_simple = o3djs.simple.create(clientElement);
 *
 *   // Create a cube.
 *   g_cube = g_simple.createCube(50);
 *
 *   // DONE!
 * }
 * </script>
 * <div id="o3d" style="width: 600px; height: 600px"></div>
 * </body></html>
 *

 *
 * Some more examples:
 *
 *   g_cube.setDiffuseColor(1, 0, 0, 1);  // Cube is now red.
 *   g_cube.transform.translate(10, 0, 0);  // Cube translates.
 *   g_cube.loadTexture('http://google.com/someimage.jpg"); // Cube is textured
 *
 *
 *     Note: This library is only a sample. It is not meant to be some official
 *     library. It is provided only as example code.
 *
 */

o3djs.provide('o3djs.simple');

o3djs.require('o3djs.math');
o3djs.require('o3djs.material');
o3djs.require('o3djs.effect');
o3djs.require('o3djs.shape');
o3djs.require('o3djs.util');
o3djs.require('o3djs.rendergraph');
o3djs.require('o3djs.pack');
o3djs.require('o3djs.primitives');
o3djs.require('o3djs.io');

/**
 * A Module for using o3d in a very simple way.
 * @namespace
 */
o3djs.simple = o3djs.simple || {};

/**
 * Creates an o3djs.simple library object that helps manage o3d
 * for the extremely simple cases.
 *
 *

 * <html><body>
 * <script type="text/javascript" src="o3djs/all.js">
 * </script>
 * <script type="text/javascript">
 * windows.onload = init;
 *
 * function init() {
 *   o3djs.base.makeClients(initStep2);
 * }
 *
 * function initStep2(clientElements) {
 *   var clientElement = clientElements[0];
 *
 *   // Create an o3djs.simple object to manage things in a simple way.
 *   g_simple = o3djs.simple.create(clientElement);
 *
 *   // Create a cube.
 *   g_cube = g_simple.createCube(50);
 *
 *   // DONE!
 * }
 * </script>
 * <div id="o3d" style="width: 600px; height: 600px"></div>
 * </body></html>
 *

 *
 * @param {!Element} clientObject O3D.Plugin Object.
 * @return {!o3djs.simple.SimpleInfo} Javascript object that hold info for the
 *     simple library.
 *
 */
o3djs.simple.create = function(clientObject) {
  return new o3djs.simple.SimpleInfo(clientObject);
};

/**
 * A SimpleInfo contains information for the simple library.
 * @constructor
 * @param {!Element} clientObject O3D.Plugin Object.
 */
o3djs.simple.SimpleInfo = function(clientObject) {
  this.clientObject = clientObject;
  this.o3d = clientObject.o3d;
  this.math = o3djs.math;
  this.client = clientObject.client;
  this.pack = this.client.createPack();
  this.viewInfo = o3djs.rendergraph.createBasicView(
      this.pack,
      this.client.root,
      this.client.renderGraphRoot);
  this.id = 0;

  // Create 1 non-textured material and 1 textured material.
  //
  // TODO: Refactor.
  // This is slightly backward. What we really want is to be able to request
  // an effect of a specific type from our shader builder but the current shader
  // builder expects a material to already exist. So, we create a material here
  // just to pass it to the shader builder, then we keep the effect it created
  // but throw away the material.
  //
  // TODO: Fix shader builder so it creates diffuseColorMult,
  //   diffuseColorOffset and  diffuseTexture so
  //   diffuse = diffuseTexture * diffuseColorMult + diffuseColorOffset.

  var material = this.pack.createObject('Material');

  o3djs.effect.attachStandardShader(this.pack,
                                         material,
                                         [0, 0, 0],
                                         'phong');

  this.nonTexturedEffect = material.effect;
  this.pack.removeObject(material);

  var material = this.pack.createObject('Material');
  var samplerParam = material.createParam('diffuseSampler', 'ParamSampler');
  o3djs.effect.attachStandardShader(this.pack,
                                         material,
                                         [0, 0, 0],
                                         'phong');

  this.texturedEffect = material.effect;
  this.pack.removeObject(material);

  this.globalParamObject = this.pack.createObject('ParamObject');
  this.lightWorldPosParam = this.globalParamObject.createParam('lightWorldPos',
                                                               'ParamFloat3');
  this.lightColorParam = this.globalParamObject.createParam('lightColor',
                                                            'ParamFloat4');
  this.setLightColor(1, 1, 1, 1);
  this.setLightPosition(255, 150, 150);  // same as camera.

  // Attempt to setup a resonable default perspective matrix.
  this.zNear = 0.1;
  this.zFar = 1000;
  this.fieldOfView = this.math.degToRad(45);
  this.setPerspectiveMatrix_();

  // Attempt to setup a resonable default view.
  this.cameraPosition = [250, 150, 150];
  this.cameraTarget = [0, 0, 0];
  this.cameraUp = [0, 1, 0];
  this.setViewMatrix_();
};

/**
 * Creates a SimpleShape. A SimpleShape manages a transform with 1 shape that
 * holds 1 primitive and 1 unique material.
 * @param {!o3d.Shape} shape that holds 1 primitive and 1 unique material.
 * @param {!o3d.Material} material assigned to shape.
 * @return {!o3djs.simple.SimpleShape} the created SimpleShape.
 */
o3djs.simple.SimpleInfo.prototype.createSimpleShape = function(shape,
                                                               material) {
  shape.createDrawElements(this.pack, null);
  var transform = this.pack.createObject('Transform');
  transform.parent = this.client.root;
  transform.addShape(shape);
  return new o3djs.simple.SimpleShape(this, transform, material);
};

/**
 * Sets the perspective matrix.
 * @private
 */
o3djs.simple.SimpleInfo.prototype.setPerspectiveMatrix_ = function() {
  this.viewInfo.drawContext.projection = this.math.matrix4.perspective(
      this.fieldOfView,
      this.client.width / this.client.height,
      this.zNear,
      this.zFar);
};

/**
 * Sets the view matrix.
 * @private
 */
o3djs.simple.SimpleInfo.prototype.setViewMatrix_ = function() {
  this.viewInfo.drawContext.view = this.math.matrix4.lookAt(
      this.cameraPosition,
      this.cameraTarget,
      this.cameraUp);
};

/**
 * Sets the field of view
 * @param {number} fieldOfView in Radians.
 *
 * For degrees use setFieldOfView(o3djs.math.degToRad(degrees)).
 */
o3djs.simple.SimpleInfo.prototype.setFieldOfView =
  function(fieldOfView) {
  this.fieldOfView = fieldOfView;
  this.setPerspectiveMatrix_();
};

/**
 * Sets the z clip range.
 * @param {number} zNear near z value.
 * @param {number} zFar far z value.
 */
o3djs.simple.SimpleInfo.prototype.setZClip = function(zNear, zFar) {
  this.zNear = zNear;
  this.zFar = zFar;
  this.setPerspectiveMatrix_();
};

/**
 * Sets the light position
 * @param {number} x x position.
 * @param {number} y y position.
 * @param {number} z z position.
 */
o3djs.simple.SimpleInfo.prototype.setLightPosition = function(x, y, z) {
  this.lightWorldPosParam.set(x, y, z);
};

/**
 * Sets the light color
 * @param {number} r red (0-1).
 * @param {number} g green (0-1).
 * @param {number} b blue (0-1).
 * @param {number} a alpha (0-1).
 */
o3djs.simple.SimpleInfo.prototype.setLightColor = function(r, g, b, a) {
  this.lightColorParam.set(r, g, b, a);
};

/**
 * Sets the camera position
 * @param {number} x x position.
 * @param {number} y y position.
 * @param {number} z z position.
 */
o3djs.simple.SimpleInfo.prototype.setCameraPosition = function(x, y, z) {
  this.cameraPosition = [x, y, z];
  this.setViewMatrix_();
};

/**
 * Sets the camera target
 * @param {number} x x position.
 * @param {number} y y position.
 * @param {number} z z position.
 */
o3djs.simple.SimpleInfo.prototype.setCameraTarget = function(x, y, z) {
  this.cameraTarget = [x, y, z];
  this.setViewMatrix_();
};

/**
 * Sets the camera up
 * @param {number} x x position.
 * @param {number} y y position.
 * @param {number} z z position.
 */
o3djs.simple.SimpleInfo.prototype.setCameraUp = function(x, y, z) {
  this.cameraUp = [x, y, z];
  this.setViewMatrix_();
};

/**
 * Create meterial from effect.
 * @param {!o3d.Effect} effect Effect to use for material.
 * @return {!o3d.Material} The created material.
 */
o3djs.simple.SimpleInfo.prototype.createMaterialFromEffect =
    function(effect) {
  var material = this.pack.createObject('Material');
  material.drawList = this.viewInfo.performanceDrawList;
  material.effect = effect;
  effect.createUniformParameters(material);
  material.getParam('lightWorldPos').bind(this.lightWorldPosParam);
  material.getParam('lightColor').bind(this.lightColorParam);
  return material;
};

/**
 * Create a new non-textured material.
 * @param {string} type Type of material 'phong', 'lambert', 'constant'.
 * @return {!o3d.Material} The created material.
 */
o3djs.simple.SimpleInfo.prototype.createNonTexturedMaterial =
    function(type) {
  var material = this.createMaterialFromEffect(this.nonTexturedEffect);
  material.getParam('diffuse').set(1, 1, 1, 1);
  material.getParam('emissive').set(0, 0, 0, 1);
  material.getParam('ambient').set(0, 0, 0, 1);
  material.getParam('specular').set(1, 1, 1, 1);
  material.getParam('shininess').value = 20;
  return material;
};

/**
 * @param {string} type Type of material 'phong', 'lambert', 'constant'.
 * @return {!o3d.Material} The created material.
 */
o3djs.simple.SimpleInfo.prototype.createTexturedMaterial =
    function(type) {
  var material = this.createMaterialFromEffect(this.texturedEffect);
  var samplerParam = material.getParam('diffuseSampler');
  var sampler = this.pack.createObject('Sampler');
  samplerParam.value = sampler;
  return material;
};

/**
 * Creates a cube and adds it to the root of this SimpleInfo's transform graph.
 * @param {number} size Width, height and depth of the cube.
 * @return {!o3djs.simple.SimpleShape} A Javascript object to manage the
 *     shape.
 */
o3djs.simple.SimpleInfo.prototype.createCube = function(size) {
  var material = this.createNonTexturedMaterial('phong');
  var shape = o3djs.primitives.createCube(this.pack, material, size);
  return this.createSimpleShape(shape, material);
};

/**
 * Creates a box and adds it to the root of this SimpleInfo's transform graph.
 * @param {number} width Width of the box.
 * @param {number} height Height of the box.
 * @param {number} depth Depth of the box.
 * @return {!o3djs.simple.SimpleShape} A Javascript object to manage the
 *     shape.
 */
o3djs.simple.SimpleInfo.prototype.createBox = function(width,
                                                       height,
                                                       depth) {
  var material = this.createNonTexturedMaterial('phong');
  var shape = o3djs.primitives.createBox(this.pack,
                                         material,
                                         width,
                                         height,
                                         depth);
  return this.createSimpleShape(shape, material);
};

/**
 * Creates a sphere and adds it to the root of this SimpleInfo's transform
 * graph.
 * @param {number} radius radius of sphere.
 * @param {number} smoothness determines the number of subdivisions.
 * @return {!o3djs.simple.SimpleShape} A Javascript object to manage the
 *     shape.
 */
o3djs.simple.SimpleInfo.prototype.createSphere = function(radius,
                                                          smoothness) {
  var material = this.createNonTexturedMaterial('phong');
  var shape = o3djs.primitives.createSphere(this.pack,
                                            material,
                                            radius,
                                            smoothness * 2,
                                            smoothness);
  return this.createSimpleShape(shape, material);
};

/**
 * Loads a scene from a URL.
 * TODO: Implement
 * @param {string} url Url of scene to load.
 * @return {!o3djs.simple.Scene} A Javascript object to manage the scene.
 */
o3djs.simple.SimpleInfo.prototype.loadScene = function(url) {
  if (true) {
    throw('not implemented');
  }
  return null;
};

/**
 * Moves the camera so everything in the current scene is visible.
 */
o3djs.simple.SimpleInfo.prototype.viewAll = function() {
  var bbox = o3djs.util.getBoundingBoxOfTree(this.client.root);
  var target = this.math.lerpVector(bbox.minExtent, bbox.maxExtent, 0.5);
  this.setCameraTarget(target[0], target[1], target[2]);
  // TODO: Refactor this so it takes a vector from the current camera
  // position to the center of the scene and moves the camera along that
  // vector away from the center of the scene until for the given fieldOfView
  // everything is visible.
  var diag = this.math.distance(bbox.minExtent, bbox.maxExtent);
  var eye = this.math.addVector(target, [
      bbox.maxExtent[0],
      bbox.minExtent[1] + 0.5 * diag,
      bbox.maxExtent[2]]);
  this.setCameraPosition(eye[0], eye[1], eye[2]);
  this.setZClip(diag / 1000, diag * 10);
};

/**
 * A SimpleShape manages a transform with 1 shape that holds 1 primitive
 * and 1 unique material.
 * @constructor
 * @param {!o3djs.simple.SimpleInfo} simpleInfo SimpleInfo to manage this shape.
 * @param {!o3d.Transform} transform Transform with 1 shape that holds 1
 *     primitive and 1 unique material.
 * @param {!o3d.Material} material assigned to shape.
 */
o3djs.simple.SimpleShape = function(simpleInfo, transform, material) {
  /**
   * The SimpleInfo managing this SimpleShape.
   * @type {!o3djs.simple.SimpleInfo}
   */
  this.simpleInfo = simpleInfo;

  /**
   * The transform for this SimpleShape.
   * @type {!o3d.Transform}
   */
  this.transform = transform;

  /**
   * The material for this SimpleShape.
   * @type {!o3d.Material}
   */
  this.material = material;
};

/**
 * Sets the material for this SimpleShape, deleting any old one.
 * @param {!o3d.Material} material new material.
 */
o3djs.simple.SimpleShape.prototype.setMaterial = function(material) {
  var old_material = this.material;
  this.simpleInfo.pack.removeObject(old_material);
  this.transform.shapes[0].elements[0].material = material;
  this.material = material;
};

/**
 * Sets the diffuse color of this shape.
 * @param {number} r Red (0-1).
 * @param {number} g Green (0-1).
 * @param {number} b Blue (0-1).
 * @param {number} a Alpha (0-1).
 */
o3djs.simple.SimpleShape.prototype.setDiffuseColor =
    function(r, g, b, a) {
  var material = this.material;
  material.getParam('diffuse').set(r, g, b, a);
  if (a < 1) {
    material.drawList = this.simpleInfo.viewInfo.zOrderedDrawList;
  } else {
    material.drawList = this.simpleInfo.viewInfo.performanceDrawList;
  }
};

/**
 * Gets the texture on this shape.
 * @return {o3d.Texture} The texture on this shape. May be null.
 */
o3djs.simple.SimpleShape.prototype.getTexture = function() {
  var material = this.material;
  var samplerParam = material.getParam('diffuseSampler');
  if (samplerParam.className == 'o3d.ParamSampler') {
    return samplerParam.texture;
  }
  return null;
};

/**
 * Loads a texture onto the given shape. It will replace the material
 * if it needs to with one that supports a texture. Note that the texture
 * is loaded asynchronously and so the result of this call may appear several
 * seconds after it is called depending on how long it takes to download the
 * texture.
 * @param {string} url Url of texture.
 */
o3djs.simple.SimpleShape.prototype.loadTexture = function(url) {
  var that = this;
  o3djs.io.loadTexture(
      this.simpleInfo.pack,
      url,
      function(texture, exception) {
        if (!exception) {
          // See if this is a textured material.
          var material = that.material;
          if (material.effect != that.simpleInfo.texturedEffect) {
            // replace the material with a textured one.
            var new_material = that.simpleInfo.createTexturedMaterial('phong');
            new_material.copyParams(material);
            // Reset the effect since copy Params just copied the non-textured
            // one.
            new_material.effect = that.simpleInfo.texturedEffect;
            that.setMaterial(new_material);
            material = new_material;
          }
          var samplerParam = material.getParam('diffuseSampler');
          samplerParam.value.texture = texture;
        } else {
          alert('Load texture file returned failure. \n' + exception);
        }
      });
};


text:
<groups xmlns="http://docs.rackspace.com/identity/api/ext/RAX-KSGRP/v1.0">
    <group xmlns="http://docs.rackspace.com/identity/api/ext/RAX-KSGRP/v1.0" id="test_global_group_add">
        <description>A Description of the group</description>
    </group>
</groups>


text:
package org.xlcloud.console.applications.controllers;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import org.junit.Before;
import org.junit.Test;
import org.xlcloud.console.applications.controllers.ApplicationBean;
import org.xlcloud.console.applications.repository.ApplicationsRepository;
import org.xlcloud.console.controllers.request.RequestParameters;
import org.xlcloud.console.controllers.request.path.VcmsGuiPathParams;

import org.xlcloud.service.Application;

/**
 * @author "Konrad Król", AMG.net
 */
public class ApplicationBeanTest {

    private ApplicationBean applicationBean = new ApplicationBean();

    @Before
    public void initialize() {
        initializeRequestParametersMock();
        initializeApplicationRepositoryMock();
        applicationBean.loadApplication();
    }

    @Test
    public void testGetApplication() {
        Application result = applicationBean.getApplication();
        assertNotNull(result);

        assertEquals("Test case application", result.getName());
    }

    private void initializeApplicationRepositoryMock() {
        Application application = getTestCaseApplication();

        ApplicationsRepository applicationsRepository = mock(ApplicationsRepository.class);
        when(applicationsRepository.getApplication(any(Long.class))).thenReturn(application);

        applicationBean.setApplicationsRepository(applicationsRepository);
    }

    private Application getTestCaseApplication() {
        Application applicationMock = mock(Application.class);
        when(applicationMock.getName()).thenReturn("Test case application");

        return applicationMock;
    }

    private void initializeRequestParametersMock() {
        RequestParameters requestParametersMock = mock(RequestParameters.class);
        when(requestParametersMock.getParameterAsLong(VcmsGuiPathParams.APPLICATION_ID))
            .thenReturn(new Long(1));

        applicationBean.setRequestParameters(requestParametersMock);
    }

}


text:
#ifndef RLWE_TESTING_STATUS_MATCHERS_H_
#define RLWE_TESTING_STATUS_MATCHERS_H_

#include <gmock/gmock.h>
#include "absl/status/status.h"
#include "shell_encryption/statusor.h"

namespace rlwe {
namespace testing {

namespace internal {

// This function and its overload allow the same matcher to be used for Status
// and StatusOr tests.
inline absl::Status GetStatus(const absl::Status& status) { return status; }

template <typename T>
inline absl::Status GetStatus(const rlwe::StatusOr<T>& statusor) {
  return statusor.status();
}

template <typename StatusType>
class StatusIsImpl : public ::testing::MatcherInterface<StatusType> {
 public:
  StatusIsImpl(const ::testing::Matcher<absl::StatusCode>& code,
               const ::testing::Matcher<const std::string&>& message)
      : code_(code), message_(message) {}

  bool MatchAndExplain(
      StatusType status,
      ::testing::MatchResultListener* listener) const override {
    ::testing::StringMatchResultListener str_listener;
    absl::Status real_status = GetStatus(status);
    if (!code_.MatchAndExplain(real_status.code(), &str_listener)) {
      *listener << str_listener.str();
      return false;
    }
    if (!message_.MatchAndExplain(
            static_cast<std::string>(real_status.message()), &str_listener)) {
      *listener << str_listener.str();
      return false;
    }
    return true;
  }

  void DescribeTo(std::ostream* os) const override {
    *os << "has a status code that ";
    code_.DescribeTo(os);
    *os << " and a message that ";
    message_.DescribeTo(os);
  }

  void DescribeNegationTo(std::ostream* os) const override {
    *os << "has a status code that ";
    code_.DescribeNegationTo(os);
    *os << " and a message that ";
    message_.DescribeNegationTo(os);
  }

 private:
  ::testing::Matcher<absl::StatusCode> code_;
  ::testing::Matcher<const std::string&> message_;
};

class StatusIsPoly {
 public:
  StatusIsPoly(::testing::Matcher<absl::StatusCode>&& code,
               ::testing::Matcher<const std::string&>&& message)
      : code_(code), message_(message) {}

  // Converts this polymorphic matcher to a monomorphic matcher.
  template <typename StatusType>
  operator ::testing::Matcher<StatusType>() const {
    return ::testing::Matcher<StatusType>(
        new StatusIsImpl<StatusType>(code_, message_));
  }

 private:
  ::testing::Matcher<absl::StatusCode> code_;
  ::testing::Matcher<const std::string&> message_;
};

}  // namespace internal

// This function allows us to avoid a template parameter when writing tests, so
// that we can transparently test both Status and StatusOr returns.
inline internal::StatusIsPoly StatusIs(
    ::testing::Matcher<absl::StatusCode>&& code,
    ::testing::Matcher<const std::string&>&& message) {
  return internal::StatusIsPoly(
      std::forward<::testing::Matcher<absl::StatusCode>>(code),
      std::forward<::testing::Matcher<const std::string&>>(message));
}

}  // namespace testing
}  // namespace rlwe

#endif  // RLWE_TESTING_STATUS_MATCHERS_H_


text:
SYNONYM

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

#### Published in
N. Amer. fl. 34:98. 1915

#### Original name
null

### Remarks
null


text:
require 'spec_helper'

module Brio

  describe Client do

    before :all do
      create_test_rc_file
    end

    after :all do
      delete_test_rc_file
    end

    before :each do
      @client = Client.new
    end

    describe "initialization" do
      it "should load config from rc file" do
        @client.config.empty?.should be_false
        @client.config['token'] == fixture_as_yaml("brio.rc")['config']['token']
      end
    end

    describe 'dynamic methods' do
      it 'should respond to user methods' do
        @client.should respond_to(:get_user)
        @client.should respond_to(:get_user_followers)
        @client.should respond_to(:get_user_following)
        @client.should respond_to(:get_user_muted)
        @client.should respond_to(:create_user_follow)
        @client.should respond_to(:delete_user_follow)
        @client.should respond_to(:create_user_mute)
        @client.should respond_to(:delete_user_mute)
        @client.should respond_to(:get_user_followers_ids)
        @client.should respond_to(:get_user_following_ids)
        @client.should respond_to(:get_user_mentions)
        @client.should respond_to(:get_user_stars)
        @client.should respond_to(:get_user_posts)
        @client.should_not respond_to(:get_something_else)
      end
    end

    describe 'api calls' do
      before :each do
        Resources::User.stub(:create_from_json)
        Resources::Post.stub(:create_from_json)
      end

      describe "get user info - whois" do
        it 'should call my own info' do
          endpoint = stub_get('/stream/0/users/me/')
          @client.get_user
          a_get('/stream/0/users/me/').should have_been_made
        end

        it 'should call user info defined by id' do
          endpoint = stub_get('/stream/0/users/@joe/')
          @client.get_user '@joe'
          a_get('/stream/0/users/@joe/').should have_been_made
        end
      end

      describe "get user followers" do
        it "should call my own followers" do
          endpoint = stub_get('/stream/0/users/me/followers')
          @client.get_user_followers
          a_get('/stream/0/users/me/followers').should have_been_made
        end

        it "should call user followers" do
          endpoint = stub_get('/stream/0/users/@joe/followers')
          @client.get_user_followers '@joe'
          a_get('/stream/0/users/@joe/followers').should have_been_made
        end

        it "should call user followers by ids" do
          endpoint = stub_get('/stream/0/users/@joe/followers/ids')
          response = @client.get_user_followers_ids '@joe'
          a_get('/stream/0/users/@joe/followers/ids').should have_been_made
        end
      end

      describe "get user following" do
        it "should call my own following" do
          endpoint = stub_get('/stream/0/users/me/following')
          @client.get_user_following
          a_get('/stream/0/users/me/following').should have_been_made
        end

        it "should call user following" do
          endpoint = stub_get('/stream/0/users/@joe/following')
          @client.get_user_following '@joe'
          a_get('/stream/0/users/@joe/following').should have_been_made
        end

        it "should call user following by ids" do
          endpoint = stub_get('/stream/0/users/@joe/following/ids')
          response = @client.get_user_following_ids '@joe'
          a_get('/stream/0/users/@joe/following/ids').should have_been_made
        end
      end

      describe "follow/unfollow a user" do
        it 'should call follow a user' do
          endpoint = stub_post('/stream/0/users/@joe/follow')
          @client.create_user_follow '@joe'
          a_post('/stream/0/users/@joe/follow').should have_been_made
        end

        it 'should call unfollow a user' do
          endpoint = stub_delete('/stream/0/users/@joe/follow')
          @client.delete_user_follow '@joe'
          a_delete('/stream/0/users/@joe/follow').should have_been_made
        end
      end

      describe "mute/unmute a user" do
        it 'should call mute a user' do
          endpoint = stub_post('/stream/0/users/@joe/mute')
          @client.create_user_mute '@joe'
          a_post('/stream/0/users/@joe/mute').should have_been_made
        end

        it 'should call unmute a user' do
          endpoint = stub_delete('/stream/0/users/@joe/mute')
          @client.delete_user_mute '@joe'
          a_delete('/stream/0/users/@joe/mute').should have_been_made
        end
      end

      describe "user api calls when returning Post objects" do
        it "should call my mentions" do
          endpoint = stub_get('/stream/0/users/me/mentions')
          @client.get_user_mentions
          a_get('/stream/0/users/me/mentions').should have_been_made
        end

        it "should call user mentions" do
          endpoint = stub_get('/stream/0/users/@joe/mentions')
          @client.get_user_mentions '@joe'
          a_get('/stream/0/users/@joe/mentions').should have_been_made
        end

        it "should call my starts" do
          endpoint = stub_get('/stream/0/users/me/stars')
          @client.get_user_stars
          a_get('/stream/0/users/me/stars').should have_been_made
        end

        it "should call user starts" do
          endpoint = stub_get('/stream/0/users/@joe/stars')
          @client.get_user_stars '@joe'
          a_get('/stream/0/users/@joe/stars').should have_been_made
        end

        it "should call my posts" do
          endpoint = stub_get('/stream/0/users/me/posts')
          @client.get_user_posts
          a_get('/stream/0/users/me/posts').should have_been_made
        end

        it "should call user posts" do
          endpoint = stub_get('/stream/0/users/@joe/posts')
          @client.get_user_posts '@joe'
          a_get('/stream/0/users/@joe/posts').should have_been_made
        end
      end
    end

  end

end


text:
#ifndef FOLLY_DETAIL_MALLOC_H
#define FOLLY_DETAIL_MALLOC_H

#include <stdlib.h>

#include <folly/Portability.h>

extern "C" {

#if FOLLY_HAVE_WEAK_SYMBOLS
void* mallocx(size_t, int) __attribute__((__weak__));
void* rallocx(void*, size_t, int) __attribute__((__weak__));
size_t xallocx(void*, size_t, size_t, int) __attribute__((__weak__));
size_t sallocx(const void*, int) __attribute__((__weak__));
void dallocx(void*, int) __attribute__((__weak__));
size_t nallocx(size_t, int) __attribute__((__weak__));
int mallctl(const char*, void*, size_t*, void*, size_t)
      __attribute__((__weak__));
int mallctlnametomib(const char*, size_t*, size_t*) __attribute__((__weak__));
int mallctlbymib(const size_t*, size_t, void*, size_t*, void*, size_t)
      __attribute__((__weak__));
#else
extern void* (*mallocx)(size_t, int);
extern void* (*rallocx)(void*, size_t, int);
extern size_t (*xallocx)(void*, size_t, size_t, int);
extern size_t (*sallocx)(const void*, int);
extern void (*dallocx)(void*, int);
extern size_t (*nallocx)(size_t, int);
extern int (*mallctl)(const char*, void*, size_t*, void*, size_t);
extern int (*mallctlnametomib)(const char*, size_t*, size_t*);
extern int (*mallctlbymib)(const size_t*, size_t, void*, size_t*, void*,
                           size_t);
#endif

}

#endif


text:
<?php

namespace BoomCMS\FileInfo\Drivers;

class Svg extends Image
{
    /**
     * @var array
     */
    protected $xmlAttrs;

    /**
     * {@inheritdoc}
     *
     * @return float
     */
    public function getAspectRatio(): float
    {
        $attrs = $this->getXmlAttrs();

        if (!isset($attrs->viewBox)) {
            return 0;
        }

        list(, , $width, $height) = explode(' ', $attrs->viewBox);

        return $width / $height;
    }

    /**
     * {@inheritdoc}
     *
     * @return array
     */
    public function getDimensions(): array
    {
        if ($this->dimensions === null) {
            $attrs = $this->getXmlAttrs();

            $this->dimensions = [
                (float) $attrs->width ?? 0,
                (float) $attrs->height ?? 0,
            ];
        }

        return $this->dimensions;
    }

    /**
     * Reads the SVG file and returns the XML attributes as an object.
     *
     * @return object
     */
    protected function getXmlAttrs()
    {
        if ($this->xmlAttrs === null) {
            $xml = simplexml_load_file($this->file->getPathname());
            $this->xmlAttrs = $xml->attributes();
        }

        return $this->xmlAttrs;
    }

    public function readMetadata(): array
    {
        return [];
    }
}


text:
PONY_EXTERN_C_BEGIN

LLVMTypeRef gendesc_type(compile_t* c, gentype_t* g);

void gendesc_init(compile_t* c, gentype_t* g);

LLVMValueRef gendesc_fetch(compile_t* c, LLVMValueRef object);

LLVMValueRef gendesc_trace(compile_t* c, LLVMValueRef object);

LLVMValueRef gendesc_dispatch(compile_t* c, LLVMValueRef object);

LLVMValueRef gendesc_vtable(compile_t* c, LLVMValueRef object, size_t colour);

LLVMValueRef gendesc_fieldcount(compile_t* c, LLVMValueRef desc);

LLVMValueRef gendesc_fielddesc(compile_t* c, LLVMValueRef desc, size_t index);

LLVMValueRef gendesc_istrait(compile_t* c, LLVMValueRef desc, ast_t* trait);

LLVMValueRef gendesc_typeid(compile_t* c, ast_t* type);

PONY_EXTERN_C_END

#endif


text:
import client from '../lib/client';
import { Room } from '../lib/db';

import { SUMMARY_EMAIL_DEFAULT_DOMAIN } from '../constants';

export default function(userId, channelId, email, rawMessage) {
  if (email) {
    const hasDefaultDomain = SUMMARY_EMAIL_DEFAULT_DOMAIN.length;
    const entryHasDomain = email.indexOf('@') !== -1;

    // Slack autoformats emails to something like
    // <mailto:jane@doe.com|jane@doe.com>
    const match = email.match(/<mailto:.*\|(.*)>/);

    if (match) {
      email = match[1];
    }

    const endsWithDefaultDomain =
      entryHasDomain &&
      new RegExp(`@${SUMMARY_EMAIL_DEFAULT_DOMAIN}$`).test(email);

    if (!entryHasDomain && !hasDefaultDomain) {
      client.sayAt(channelId, userId, "I'll need a valid email address");
      return;
    }

    if (hasDefaultDomain && entryHasDomain && !endsWithDefaultDomain) {
      client.sayAt(
        channelId,
        userId,
        `Only email domains ending in @${SUMMARY_EMAIL_DEFAULT_DOMAIN} are allowed.`
      );
      return;
    }

    email = entryHasDomain ? email : `${email}@${SUMMARY_EMAIL_DEFAULT_DOMAIN}`;
  }

  const msg = email
    ? `Ok, I'll email a summary to ${email} whenever standup ends.`
    : 'Ok, email updates disabled.';

  Room.update({ email }, { where: { channelId } }).then(() => {
    client.sayAt(channelId, userId, msg, {
      thread_ts: rawMessage.thread_ts,
    });
  });
}


text:
define([
	'underscore',
	'backbone'
	], function(_, Backbone){

	var Subject = Backbone.Model.extend({

		defaults: {
			subject_name: '',
			subject_abbr: '',
			class_id: 0,
			description: '',
			date_created: 'Just now'
		}

	});

	return Subject;

});


text:
package gnu.commonlisp.lang;
import gnu.bytecode.ClassType;
import gnu.bytecode.CodeAttr;
import gnu.expr.*;
import gnu.lists.LList;
import gnu.lists.Pair;
import gnu.text.SourceMessages;
import kawa.lang.Translator;

public class Lisp2Compilation extends Translator
{
  public Lisp2Compilation (Language language, SourceMessages messages, NameLookup lexical)
  {
    super(language, messages, lexical);
  }

  @Override
  public void emitPushBoolean(boolean value)
  {
    CodeAttr code = getCode();
    if (value)
      code.emitGetStatic(ClassType.make("gnu.commonlisp.lang.Lisp2").getDeclaredField("TRUE"));
    else
      code.emitGetStatic(Compilation.scmListType.getDeclaredField("Empty"));
  }

  /**
   * Process the DECLARE (if any) in a Common Lisp form.
   *
   * @param list The body of this expression.
   */
  @Override
  protected void rewriteBody (LList list)
  {
    if (list.isEmpty())
      return;
    // Declarations are always at the start of a body.
    Object head = ((Pair) list).getCar();
    // The body to rewrite into the new LET body, this is just what follows
    // the DECLARE form in list
    Object body = ((Pair) list).getCdr();

    if (head instanceof Pair && matches(((Pair) head).getCar(), "declare"))
    {
      Object decls = ((Pair) head).getCdr();
      Object vars;

      // Create a new lexical environment for this DECLARE
      letStart();

      while (decls != LList.Empty) {

        if (!( (decls instanceof Pair) &&
               (((Pair) decls).getCar() instanceof Pair) )) {
          errorWithPosition("Arguments to declare must be proper lists", decls);
          break;
        }

        Pair declItem = (Pair) ((Pair) decls).getCar();

        if (!(declItem.getCdr() instanceof Pair))
        {
          errorWithPosition("Bad declare syntax, expected a list but got something else.", declItem);
          break;
        }

        if (matches(declItem.getCar(), "type"))
        {
          // Just skip past TYPE and process the type declarations
          declItem = (Pair) declItem.getCdr();

          if (! (declItem.getCdr() instanceof Pair)) {
            Object save = pushPositionOf(declItem);
            error('e', "A type specifier must be applied to at least one declaration.");
            popPositionOf(save);
            break;
          }

          vars = (Pair) declItem.getCdr();
        }
        // .. other checks could be performed here
        else
        {
          // By default we process type declarations
          vars = (Pair) declItem.getCdr();
        }

        // e.g vars = (x y) or (z) or (k)
        // For each aliased variable, place it in the new lexical environment
        while (vars != LList.Empty)
        {
          if (! (vars instanceof Pair)) {
            Object save = pushPositionOf(vars);
            error('e', "The variable list in a declare form must be a proper list.");
            popPositionOf(save);
            break;
          }

          Object var = ((Pair) vars).getCar();
          Declaration varDecl = lexical.get(var);
          if (varDecl != null)
          {
            Declaration aliasedDecl = new Declaration(varDecl.getSymbol());
            ReferenceExp ref = new ReferenceExp(varDecl);
            letVariable(aliasedDecl, ref);
            aliasedDecl.setType(this.exp2Type(declItem));
            aliasedDecl.setFlag(Declaration.TYPE_SPECIFIED);
            aliasedDecl.setFlag(Declaration.IS_SINGLE_VALUE);
          }
          else
          {
            error('w', "No declaration seen for `" + var + "`");
          }
          vars = ((Pair) vars).getCdr();
        }
        decls = ((Pair) decls).getCdr();
      }
      letEnter();
      formStack.add(letDone(super.rewrite_body(body)));
    } else
      super.rewriteBody(list);
  }
}


text:
package org.apache.gobblin.compaction.verify;

import org.apache.gobblin.dataset.Dataset;

/**
 * An interface which represents a generic verifier for compaction
 */
public interface CompactionVerifier<D extends Dataset> {
   String COMPACTION_VERIFIER_PREFIX = "compaction-verifier-";
   String COMPACTION_VERIFICATION_TIMEOUT_MINUTES = "compaction.verification.timeoutMinutes";
   String COMPACTION_VERIFICATION_ITERATION_COUNT_LIMIT = "compaction.verification.iteration.countLimit";
   String COMPACTION_VERIFICATION_THREADS= "compaction.verification.threads";
   boolean verify(D dataset);
   boolean isRetriable ();
   String getName();
}


text:
home backslash foo backslash bar

#Exercise 2: In /Users/bill/sonnets, what is the home directory? What is the username? Which directory is deepest in the hierarchy?
Users is the home directory. The username is bill. The  sonnets directory is deepest in the hierarchy.

#Exercise 3: For a user with username bill, how do /Users/bill/sonnets and ~/sonnets differ (if at all)?
They are functionally the same.


text:
package org.cloudfoundry.client.v2.serviceinstances;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;

/**
 * The response payload for the the Update Service Instance request.
 */
@JsonDeserialize
@Value.Immutable
abstract class _UpdateServiceInstanceResponse extends AbstractServiceInstanceResource {

}


text:
from absl import logging
from absl.testing import parameterized
import tensorflow as tf

import utils
from tf2 import util_keras

class KerasUtilTest(tf.test.TestCase, parameterized.TestCase):

  @parameterized.named_parameters(
      ('train_local', True, ''), ('eval_local', False, ''),
      ('train_tpu', True, 'tpu'), ('eval_tpu', False, 'tpu'))
  def test_batch_norm(self, is_training, strategy):
    inputs = tf.random.uniform([8, 40, 40, 3])
    expect_results = utils.batch_norm_act(
        inputs, is_training, None, strategy=strategy)

    # Call batch norm layer with is_training parameter.
    bn_layer = util_keras.build_batch_norm(is_training, strategy=strategy)
    self.assertAllClose(expect_results, bn_layer(inputs, is_training))

if __name__ == '__main__':
  logging.set_verbosity(logging.WARNING)
  tf.test.main()


text:
try:
    from itertools import permutations
except ImportError:
    # from http://docs.python.org/library/itertools.html#itertools.permutations
    def permutations(iterable, r=None):
        # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
        # permutations(range(3)) --> 012 021 102 120 201 210
        pool = tuple(iterable)
        n = len(pool)
        r = n if r is None else r
        if r > n:
            return
        indices = range(n)
        cycles = range(n, n-r, -1)
        yield tuple(pool[i] for i in indices[:r])
        while n:
            for i in reversed(range(r)):
                cycles[i] -= 1
                if cycles[i] == 0:
                    indices[i:] = indices[i+1:] + indices[i:i+1]
                    cycles[i] = n - i
                else:
                    j = cycles[i]
                    indices[i], indices[-j] = indices[-j], indices[i]
                    yield tuple(pool[i] for i in indices[:r])
                    break
            else:
                return


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.ApiManagement;

namespace Azure.ResourceManager.ApiManagement.Models
{
    /// <summary> Paged ApiRelease list representation. </summary>
    internal partial class ApiReleaseListResult
    {
        /// <summary> Initializes a new instance of ApiReleaseListResult. </summary>
        internal ApiReleaseListResult()
        {
            Value = new ChangeTrackingList<ApiReleaseData>();
        }

        /// <summary> Initializes a new instance of ApiReleaseListResult. </summary>
        /// <param name="value"> Page values. </param>
        /// <param name="count"> Total record count number across all pages. </param>
        /// <param name="nextLink"> Next page link if any. </param>
        internal ApiReleaseListResult(IReadOnlyList<ApiReleaseData> value, long? count, string nextLink)
        {
            Value = value;
            Count = count;
            NextLink = nextLink;
        }

        /// <summary> Page values. </summary>
        public IReadOnlyList<ApiReleaseData> Value { get; }
        /// <summary> Total record count number across all pages. </summary>
        public long? Count { get; }
        /// <summary> Next page link if any. </summary>
        public string NextLink { get; }
    }
}


text:
module FlashRailsMessages
  class Base
    include ActionView::Context
    include ActionView::Helpers::TagHelper

    attr_reader :options

    def initialize(options = {})
      @options = options
    end

    def render(flash)
      messages(flash).map do |message|
        alert_element(*message)
      end.join.html_safe
    end

    private

    def messages(flash)
      Hash[flash]
        .symbolize_keys
        .keep_if { |key, _| alert_type_classes.include?(key) }
    end

    def alert_element(type, message)
      return unless message.respond_to?(:html_safe)

      content_tag :div, alert_options(type) do
        content = ActiveSupport::SafeBuffer.new
        content += close_element if options.fetch(:dismissible, false)
        content += message.html_safe
        content
      end
    end

    def close_element
      content_tag :a, class: 'close', href: '#' do
        '×'.html_safe
      end
    end

    def alert_options(type)
      default_alert_options
        .merge(options.except(:dismissible))
        .merge(class: alert_classes(type))
    end

    def alert_classes(type)
      [
        default_alert_classes,
        alert_type_classes[type],
        custom_alert_classes,
        options[:class]
      ].compact.join(' ').strip
    end

    def default_alert_options
      {}
    end

    def default_alert_classes
      'alert'
    end

    def alert_type_classes
      {}
    end

    def custom_alert_classes; end
  end
end


text:
Rails.application.routes.draw do
  resources :errors, only: [:show]
  resources :teams, only: [:index, :show, :create]
  resources :team_users, only: [:create, :destroy, :update]
  resources :namespaces, only: [:create, :index, :show] do
    put "toggle_public", on: :member
  end

  resources :repositories, only: [:index, :show] do
    post :toggle_star, on: :member
  end

  devise_for :users, controllers: { registrations: "auth/registrations", sessions: "auth/sessions" }
  resource :dashboard, only: [:index]
  resources :search, only: [:index]

  authenticated :user do
    root "dashboard#index", as: :authenticated_root
  end

  devise_scope :user do
    root to: "auth/sessions#new"
    put "toggle_enabled/:id", to: "auth/registrations#toggle_enabled", as: :toggle_enabled
  end

  namespace :v2, module: "api/v2", defaults: { format: :json } do
    root to: "ping#ping", as: :ping
    resource :token, only: [:show]
    resource :webhooks, only: [] do
      resources :events, only: [:create]
    end
  end

  namespace :admin do
    resources :activities, only: [:index]
    resources :dashboard, only: [:index]
    resources :registries, only: [:index, :create, :new]
    resources :namespaces, only: [:index]
    resources :teams, only: [:index]
    resources :users, only: [:index] do
      put "toggle_admin", on: :member
    end
  end
  match "(errors)/:status", to: "errors#show", constraints: { status: /\d{3}/ }, via: :all

end


text:
/* DO NOT EDIT */
/* This file was generated from team_log_generated.stone */

package com.dropbox.core.v2.teamlog;

import com.dropbox.core.stone.StoneDeserializerLogger;
import com.dropbox.core.stone.StoneSerializers;
import com.dropbox.core.stone.UnionSerializer;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

import java.io.IOException;
import java.util.Arrays;

public enum ExtendedVersionHistoryPolicy {
    // union team_log.ExtendedVersionHistoryPolicy (team_log_generated.stone)
    EXPLICITLY_LIMITED,
    EXPLICITLY_UNLIMITED,
    IMPLICITLY_LIMITED,
    IMPLICITLY_UNLIMITED,
    /**
     * Catch-all used for unknown tag values returned by the Dropbox servers.
     *
     * <p> Receiving a catch-all value typically indicates this SDK version is
     * not up to date. Consider updating your SDK version to handle the new
     * tags. </p>
     */
    OTHER; // *catch_all

    /**
     * For internal use only.
     */
    static class Serializer extends UnionSerializer<ExtendedVersionHistoryPolicy> {
        public static final Serializer INSTANCE = new Serializer();

        @Override
        public void serialize(ExtendedVersionHistoryPolicy value, JsonGenerator g) throws IOException, JsonGenerationException {
            switch (value) {
                case EXPLICITLY_LIMITED: {
                    g.writeString("explicitly_limited");
                    break;
                }
                case EXPLICITLY_UNLIMITED: {
                    g.writeString("explicitly_unlimited");
                    break;
                }
                case IMPLICITLY_LIMITED: {
                    g.writeString("implicitly_limited");
                    break;
                }
                case IMPLICITLY_UNLIMITED: {
                    g.writeString("implicitly_unlimited");
                    break;
                }
                default: {
                    g.writeString("other");
                }
            }
        }

        @Override
        public ExtendedVersionHistoryPolicy deserialize(JsonParser p) throws IOException, JsonParseException {
            ExtendedVersionHistoryPolicy value;
            boolean collapsed;
            String tag;
            if (p.getCurrentToken() == JsonToken.VALUE_STRING) {
                collapsed = true;
                tag = getStringValue(p);
                p.nextToken();
            }
            else {
                collapsed = false;
                expectStartObject(p);
                tag = readTag(p);
            }
            if (tag == null) {
                throw new JsonParseException(p, "Required field missing: " + TAG_FIELD);
            }
            else if ("explicitly_limited".equals(tag)) {
                value = ExtendedVersionHistoryPolicy.EXPLICITLY_LIMITED;
            }
            else if ("explicitly_unlimited".equals(tag)) {
                value = ExtendedVersionHistoryPolicy.EXPLICITLY_UNLIMITED;
            }
            else if ("implicitly_limited".equals(tag)) {
                value = ExtendedVersionHistoryPolicy.IMPLICITLY_LIMITED;
            }
            else if ("implicitly_unlimited".equals(tag)) {
                value = ExtendedVersionHistoryPolicy.IMPLICITLY_UNLIMITED;
            }
            else {
                value = ExtendedVersionHistoryPolicy.OTHER;
            }
            if (!collapsed) {
                skipFields(p);
                expectEndObject(p);
            }
            return value;
        }
    }
}


text:
gulp-starter
============

Basic project boilerplate with [gulp.js](http://gulpjs.com/).

Includes the following tools:

- [Sass](http://sass-lang.com/)
- [Autoprefixer](https://github.com/postcss/autoprefixer)
- [Head.JS](http://headjs.com/)
- [CSS Beautify](https://www.npmjs.org/package/gulp-cssbeautify) (from npm)
- [File includes](https://www.npmjs.org/package/gulp-file-include) (from npm)
- [Spritesmith](https://github.com/twolfson/gulp.spritesmith) (from npm)

## Getting Started

#### 1. Install Node.js

If you've never used Node.js or `npm` before download and install it from [http://nodejs.org/download/](http://nodejs.org/download/).

#### 2. Install gulp.js

```sh
$ npm install -g gulp
```

Gulp must be installed globally.
You may need to use `sudo` to run the install commands as admin.

#### 3. Install Sass (if you haven't already)

```sh
$ gem install sass
```

#### 4. Install npm dependencies

**Important:** Make sure you're in the project directory.

```sh
$ npm install
```

This runs through all dependencies listed in `package.json` and downloads them to a `node_modules` folder in your project directory.

#### 5. Run gulp

```sh
$ gulp
```

## Directory Structure

```
gulp-starter/
|
|– src/
|   img/
|      icons/
|         ...
|   js/
|      lib/
|         head.js
|         jquery.js
|         ...
|      init.js
|      common.js
|   sass/
|      lib/
|         _mixins.sass
|         _sprite.sass
|         ...
|      _reset.sass
|      _layout.sass
|      common.sass
|   *.html
|
|– build/
|   img/
|      sprite.png
|   js/
|      lib/
|         head.js
|         jquery.js
|         ...
|      common.js
|   css/
|      common.css
|   *.html
```

## License

This projected is licensed under the terms of the [MIT license](https://github.com/pismenny/gulp-starter/blob/master/LICENSE.md).