text:
use std::mem;

use index::{Point, Column, RangeInclusive, Side, Linear, Line};
use grid::ToRange;

/// The area selected
///
/// Contains all the logic for processing mouse position events and providing
/// necessary info the the renderer.
#[derive(Debug)]
pub enum Selection {
    /// No current selection or start of a selection
    Empty,

    Active {
        start: Point,
        end: Point,
        start_side: Side,
        end_side: Side
    },
}

impl Default for Selection {
    fn default() -> Selection {
        Selection::Empty
    }
}

impl Selection {
    /// Create a selection in the default state
    #[inline]
    pub fn new() -> Selection {
        Default::default()
    }

    /// Clear the active selection
    pub fn clear(&mut self) {
        mem::replace(self, Selection::Empty);
    }

    pub fn is_empty(&self) -> bool {
        match *self {
            Selection::Empty => true,
            _ => false
        }
    }

    pub fn update(&mut self, location: Point, side: Side) {
        let selection = mem::replace(self, Selection::Empty);
        let selection = match selection {
            Selection::Empty => {
                // Start a selection
                Selection::Active {
                    start: location,
                    end: location,
                    start_side: side,
                    end_side: side
                }
            },
            Selection::Active { start, start_side, .. } => {
                // Update ends
                Selection::Active {
                    start: start,
                    start_side: start_side,
                    end: location,
                    end_side: side
                }
            }
        };

        mem::replace(self, selection);
    }

    pub fn span(&self) -> Option<Span> {
        match *self {
            Selection::Active { ref start, ref end, ref start_side, ref end_side } => {
                let (front, tail, front_side, tail_side) = if *start > *end {
                    // Selected upward; start/end are swapped
                    (end, start, end_side, start_side)
                } else {
                    // Selected downward; no swapping
                    (start, end, start_side, end_side)
                };

                debug_assert!(!(tail < front));

                // Single-cell selections are a special case
                if start == end {
                    if start_side == end_side {
                        return None;
                    } else {
                        return Some(Span {
                            ty: SpanType::Inclusive,
                            front: *front,
                            tail: *tail
                        });
                    }
                }

                // The other special case is two adjacent cells with no
                // selection: [ B][E ] or [ E][B ]
                let adjacent = tail.line == front.line && tail.col - front.col == Column(1);
                if adjacent && *front_side == Side::Right && *tail_side == Side::Left {
                    return None;
                }

                Some(match (*front_side, *tail_side) {
                    // [FX][XX][XT]
                    (Side::Left, Side::Right) => Span {
                        front: *front,
                        tail: *tail,
                        ty: SpanType::Inclusive
                    },
                    // [ F][XX][T ]
                    (Side::Right, Side::Left) => Span {
                        front: *front,
                        tail: *tail,
                        ty: SpanType::Exclusive
                    },
                    // [FX][XX][T ]
                    (Side::Left, Side::Left) => Span {
                        front: *front,
                        tail: *tail,
                        ty: SpanType::ExcludeTail
                    },
                    // [ F][XX][XT]
                    (Side::Right, Side::Right) => Span {
                        front: *front,
                        tail: *tail,
                        ty: SpanType::ExcludeFront
                    },
                })
            },
            Selection::Empty => None
        }
    }
}

/// How to interpret the locations of a Span.
#[derive(Debug, Eq, PartialEq)]
pub enum SpanType {
    /// Includes the beginning and end locations
    Inclusive,

    /// Exclude both beginning and end
    Exclusive,

    /// Excludes last cell of selection
    ExcludeTail,

    /// Excludes first cell of selection
    ExcludeFront,
}

/// Represents a span of selected cells
#[derive(Debug, Eq, PartialEq)]
pub struct Span {
    front: Point,
    tail: Point,

    /// The type says whether ends are included or not.
    ty: SpanType,
}

impl Span {
    pub fn to_locations(&self, cols: Column) -> (Point, Point) {
        match self.ty {
            SpanType::Inclusive => (self.front, self.tail),
            SpanType::Exclusive => {
                (Span::wrap_start(self.front, cols), Span::wrap_end(self.tail, cols))
            },
            SpanType::ExcludeFront => (Span::wrap_start(self.front, cols), self.tail),
            SpanType::ExcludeTail => (self.front, Span::wrap_end(self.tail, cols))
        }
    }

    fn wrap_start(mut start: Point, cols: Column) -> Point {
        if start.col == cols - 1 {
            Point {
                line: start.line + 1,
                col: Column(0),
            }
        } else {
            start.col += 1;
            start
        }
    }

    fn wrap_end(end: Point, cols: Column) -> Point {
        if end.col == Column(0) && end.line != Line(0) {
            Point {
                line: end.line - 1,
                col: cols
            }
        } else {
            Point {
                line: end.line,
                col: end.col - 1
            }
        }
    }

    #[inline]
    fn exclude_start(start: Linear) -> Linear {
        start + 1
    }

    #[inline]
    fn exclude_end(end: Linear) -> Linear {
        if end > Linear(0) {
            end - 1
        } else {
            end
        }
    }
}

impl ToRange for Span {
    fn to_range(&self, cols: Column) -> RangeInclusive<Linear> {
        let start = Linear(self.front.line.0 * cols.0 + self.front.col.0);
        let end = Linear(self.tail.line.0 * cols.0 + self.tail.col.0);

        let (start, end) = match self.ty {
            SpanType::Inclusive => (start, end),
            SpanType::Exclusive => (Span::exclude_start(start), Span::exclude_end(end)),
            SpanType::ExcludeFront => (Span::exclude_start(start), end),
            SpanType::ExcludeTail => (start, Span::exclude_end(end))
        };

        RangeInclusive::new(start, end)
    }
}

/// Tests for selection
///
/// There are comments on all of the tests describing the selection. Pictograms
/// are used to avoid ambiguity. Grid cells are represented by a [  ]. Only
/// cells that are comletely covered are counted in a selection. Ends are
/// represented by `B` and `E` for begin and end, respectively.  A selected cell
/// looks like [XX], [BX] (at the start), [XB] (at the end), [XE] (at the end),
/// and [EX] (at the start), or [BE] for a single cell. Partially selected cells
/// look like [ B] and [E ].
#[cfg(test)]
mod test {
    use index::{Line, Column, Side, Point};
    use super::{Selection, Span, SpanType};

    /// Test case of single cell selection
    ///
    /// 1. [  ]
    /// 2. [B ]
    /// 3. [BE]
    #[test]
    fn single_cell_left_to_right() {
        let location = Point { line: Line(0), col: Column(0) };
        let mut selection = Selection::Empty;
        selection.update(location, Side::Left);
        selection.update(location, Side::Right);

        assert_eq!(selection.span().unwrap(), Span {
            ty: SpanType::Inclusive,
            front: location,
            tail: location
        });
    }

    /// Test case of single cell selection
    ///
    /// 1. [  ]
    /// 2. [ B]
    /// 3. [EB]
    #[test]
    fn single_cell_right_to_left() {
        let location = Point { line: Line(0), col: Column(0) };
        let mut selection = Selection::Empty;
        selection.update(location, Side::Right);
        selection.update(location, Side::Left);

        assert_eq!(selection.span().unwrap(), Span {
            ty: SpanType::Inclusive,
            front: location,
            tail: location
        });
    }

    /// Test adjacent cell selection from left to right
    ///
    /// 1. [  ][  ]
    /// 2. [ B][  ]
    /// 3. [ B][E ]
    #[test]
    fn between_adjacent_cells_left_to_right() {
        let mut selection = Selection::Empty;
        selection.update(Point::new(Line(0), Column(0)), Side::Right);
        selection.update(Point::new(Line(0), Column(1)), Side::Left);

        assert_eq!(selection.span(), None);
    }

    /// Test adjacent cell selection from right to left
    ///
    /// 1. [  ][  ]
    /// 2. [  ][B ]
    /// 3. [ E][B ]
    #[test]
    fn between_adjacent_cells_right_to_left() {
        let mut selection = Selection::Empty;
        selection.update(Point::new(Line(0), Column(1)), Side::Left);
        selection.update(Point::new(Line(0), Column(0)), Side::Right);

        assert_eq!(selection.span(), None);
    }

    /// Test selection across adjacent lines
    ///
    ///
    /// 1.  [  ][  ][  ][  ][  ]
    ///     [  ][  ][  ][  ][  ]
    /// 2.  [  ][  ][  ][  ][  ]
    ///     [  ][ B][  ][  ][  ]
    /// 3.  [  ][ E][XX][XX][XX]
    ///     [XX][XB][  ][  ][  ]
    #[test]
    fn across_adjacent_lines_upward_final_cell_exclusive() {
        let mut selection = Selection::Empty;
        selection.update(Point::new(Line(1), Column(1)), Side::Right);
        selection.update(Point::new(Line(0), Column(1)), Side::Right);

        assert_eq!(selection.span().unwrap(), Span {
            front: Point::new(Line(0), Column(1)),
            tail: Point::new(Line(1), Column(1)),
            ty: SpanType::ExcludeFront
        });
    }

    /// Test selection across adjacent lines
    ///
    ///
    /// 1.  [  ][  ][  ][  ][  ]
    ///     [  ][  ][  ][  ][  ]
    /// 2.  [  ][ B][  ][  ][  ]
    ///     [  ][  ][  ][  ][  ]
    /// 3.  [  ][ B][XX][XX][XX]
    ///     [XX][XE][  ][  ][  ]
    /// 4.  [  ][ B][XX][XX][XX]
    ///     [XE][  ][  ][  ][  ]
    #[test]
    fn selection_bigger_then_smaller() {
        let mut selection = Selection::Empty;
        selection.update(Point::new(Line(0), Column(1)), Side::Right);
        selection.update(Point::new(Line(1), Column(1)), Side::Right);
        selection.update(Point::new(Line(1), Column(0)), Side::Right);

        assert_eq!(selection.span().unwrap(), Span {
            front: Point::new(Line(0), Column(1)),
            tail: Point::new(Line(1), Column(0)),
            ty: SpanType::ExcludeFront
        });
    }
}


text:
require 'rails_helper'

RSpec.describe 'Dark sky areas', type: :system do
  let!(:admin)                  { create(:admin) }
  let(:title)                   { 'Lights out for darker skies' }
  let(:latitude)                { 123.456 }
  let(:longitude)               { -789.012 }
  let(:back_fill_years)         { 5 }

  describe 'when logged in' do
    before(:each) do
      sign_in(admin)
      visit root_path
      click_on 'Manage'
      click_on 'Admin'
      click_on 'Dark Sky Areas'
    end

    it 'can create a new dark sky area' do
      expect(page).to have_content("There are no Dark Sky Areas")

      click_on 'New Dark Sky Area'

      fill_in 'Title', with: title
      fill_in 'Latitude', with: latitude
      fill_in 'Longitude', with: longitude
      fill_in 'Back fill years', with: back_fill_years

      expect { click_on 'Create' }.to change { DarkSkyArea.count }.by(1)

      expect(page).to have_content("New Dark Sky Area created")
      expect(page).to have_content('Dark Sky Areas')
      expect(page).to have_content title
      expect(page).to have_content latitude
      expect(page).to have_content longitude
      expect(page).to have_content back_fill_years
    end

    it 'checks for valid fields' do
      click_on 'New Dark Sky Area'

      fill_in 'Title', with: title
      fill_in 'Latitude', with: latitude

      expect { click_on 'Create' }.to change { DarkSkyArea.count }.by(0)

      expect(page).to have_content("can't be blank")

      fill_in 'Longitude', with: longitude
      expect { click_on 'Create' }.to change { DarkSkyArea.count }.by(1)

      expect(page).to have_content('Dark Sky Areas')
      expect(page).to have_content title
      expect(page).to have_content latitude
      expect(page).to have_content longitude
    end

    context 'with an existing dark sky area' do

      let!(:area) { DarkSkyArea.create!(title: title, latitude: latitude, longitude: longitude) }

      before(:each) do
        click_on 'Manage'
        click_on 'Admin'
        click_on 'Dark Sky Areas'

        expect(DarkSkyArea.count).to be 1
        expect(page).to have_content('Dark Sky Areas')
        expect(page).to have_content title
        expect(page).to have_content latitude
        expect(page).to have_content longitude
      end

      it 'can be edited' do
        expect(DarkSkyArea.count).to be 1
        click_on 'Edit'

        new_latitude = 111.111
        new_longitude = 999.999
        new_back_fill_years = 5
        fill_in 'Latitude', with: new_latitude
        fill_in 'Longitude', with: new_longitude
        fill_in 'Back fill years', with: new_back_fill_years

        click_on 'Update'

        expect(page).to have_content("Dark Sky Area was updated")

        expect(page).to have_content('Dark Sky Areas')
        expect(page).to have_content title
        expect(page).to have_content new_latitude
        expect(page).to have_content new_longitude
        expect(page).to have_content new_back_fill_years
      end

      it 'checks for valid fields on update' do
        click_on 'Edit'

        new_latitude = 111.111
        new_longitude = 999.999

        fill_in 'Latitude', with: ''
        fill_in 'Longitude', with: new_longitude

        click_on 'Update'

        expect(page).to have_content("can't be blank")

        fill_in 'Latitude', with: new_latitude

        click_on 'Update'
        expect(page).to have_content("Dark Sky Area was updated")

        expect(page).to have_content('Dark Sky Areas')
        expect(page).to have_content title
        expect(page).to have_content new_latitude
        expect(page).to have_content new_longitude
      end

      it 'deletes old temperature readings if lat/long changed' do

        DataFeeds::DarkSkyTemperatureReading.create!(
          reading_date: '2020-03-25',
          temperature_celsius_x48: 48.times.map{rand(40.0)},
          area_id: area.id
        )

        expect(area.dark_sky_temperature_readings.count).to eq(1)

        click_on 'Edit'

        new_title = 'New title for this area'
        new_latitude = 111.111
        new_longitude = 999.999

        fill_in 'Title', with: new_title

        click_on 'Update'

        expect(page).to have_content("Dark Sky Area was updated")
        expect(page).to have_content new_title
        expect(area.dark_sky_temperature_readings.count).to eq(1)

        click_on 'Edit'

        fill_in 'Latitude', with: new_latitude
        fill_in 'Longitude', with: new_longitude

        click_on 'Update'

        expect(page).to have_content("Dark Sky Area was updated")
        expect(page).to have_content new_latitude
        expect(page).to have_content new_longitude
        expect(area.dark_sky_temperature_readings.count).to eq(0)

      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.wildfly.security.sasl.util;

import static java.security.AccessController.doPrivileged;

import java.lang.reflect.UndeclaredThrowableException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;

import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;

import org.wildfly.common.Assert;

/**
 * A {@code SaslClient} which evaluates challenges and wrap/unwrap requests in an privileged context.
 *
 * @author David M. Lloyd
 */
public final class PrivilegedSaslClient extends AbstractDelegatingSaslClient implements SaslWrapper {
    private final AccessControlContext accessControlContext;

    PrivilegedSaslClient(final SaslClient delegate, final AccessControlContext accessControlContext) {
        super(delegate);
        Assert.checkNotNullParam("delegate", delegate);
        Assert.checkNotNullParam("accessControlContext", accessControlContext);
        this.accessControlContext = accessControlContext;
    }

    public PrivilegedSaslClient(final SaslClient delegate) {
        this(delegate, AccessController.getContext());
    }

    public byte[] evaluateChallenge(final byte[] challenge) throws SaslException {
        try {
            return doPrivileged((PrivilegedExceptionAction<byte[]>) () -> delegate.evaluateChallenge(challenge), accessControlContext);
        } catch (PrivilegedActionException pae) {
            try {
                throw pae.getCause();
            } catch (SaslException | RuntimeException | Error e) {
                throw e;
            } catch (Throwable throwable) {
                throw new UndeclaredThrowableException(throwable);
            }
        }
    }

    public byte[] unwrap(final byte[] incoming, final int offset, final int len) throws SaslException {
        try {
            return doPrivileged((PrivilegedExceptionAction<byte[]>) () -> delegate.unwrap(incoming, offset, len), accessControlContext);
        } catch (PrivilegedActionException pae) {
            try {
                throw pae.getCause();
            } catch (SaslException | RuntimeException | Error e) {
                throw e;
            } catch (Throwable throwable) {
                throw new UndeclaredThrowableException(throwable);
            }
        }
    }

    public byte[] wrap(final byte[] outgoing, final int offset, final int len) throws SaslException {
        try {
            return doPrivileged((PrivilegedExceptionAction<byte[]>) () -> delegate.wrap(outgoing, offset, len), accessControlContext);
        } catch (PrivilegedActionException pae) {
            try {
                throw pae.getCause();
            } catch (SaslException | RuntimeException | Error e) {
                throw e;
            } catch (Throwable throwable) {
                throw new UndeclaredThrowableException(throwable);
            }
        }
    }
}


text:
require 'open3'
require_relative 'configuration'
require_relative 'output_parser'

module Pronto
  module Tailor
    class Wrapper
      attr_reader :patch

      def initialize(patch)
        @patch = patch
      end

      def lint
        return [] if patch.nil?
        configuration = Configuration.new(ENV)
        path = patch.new_file_full_path.to_s
        stdout, stderr, _status = Open3.capture3(configuration.command_line_for_file(path))
        puts "WARN: pronto-tailor: #{stderr}" if stderr && stderr.size > 0
        return [] if stdout.nil? || stdout.size == 0
        OutputParser.new(path, stdout).parse
      rescue => e
        puts "ERROR: pronto-tailor failed to process a diff: #{e}"
        []
      end
    end
  end
end


text:
@implementation ASPOSECDocumentPropertiesEnvelop

+ (JSONKeyMapper*)keyMapper {
    NSDictionary *map = @{@"DocumentPropertyList" : @"documentPropertiesList",
                          @"link" : @"link"};

    return [[JSONKeyMapper alloc] initWithDictionary:map];
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
            android:label="@string/action_search"
            android:hint="@string/search_hint"
            android:searchSuggestAuthority="com.zzolta.android.gfrecipes.providers.RecipeSearchRecentSuggestionsProvider"
            android:searchSuggestSelection=" ?"
            android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"/>


text:
// genpseudogenome.cpp : Defines the entry point for the console application.
#include "stdafx.h"

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

#if _WIN32
#include <process.h>
#include "../libbiokanga/commhdrs.h"
#else
#include <sys/mman.h>
#include <pthread.h>
#include "../libbiokanga/commhdrs.h"
#endif

#include "biokanga.h"

const int cMinNSeps = 5;				// allow a minium of 5 N's to be specified as being the length of sequence separators
const int cDfltNSeps = 100;				// default to 100 N's to be specified as being the length of sequence separators
const int cMaxNSeps = 100;				// allow at most 100 N's to be specified as being the length of sequence separators

// processing modes
typedef enum TAG_ePMode {
	ePMdefault,					// default processing mode
	ePMplaceholder				// used to set the enumeration range
	} etPMode;

// output format modes
typedef enum TAG_eFMode {
	eFMdefault,					// default
	eFMplaceholder				// used to set the enumeration rangeP
	} etFMode;

const int cMaxInFileSpecs = 100; // can handle up to this many input files

int
GPGProcess(etPMode PMode,					// processing mode
		etFMode FMode,					// output format mode
		int LenNSeps,					// generate with this number of 'N' bases separating concatenated sequences
		char *pszTrackTitle,			// track title for output UCSC BED
		int NumInputFileSpecs,		  	// number of input file specs
		char *pszInfileSpecs[],		  	// names of inputs files containing multifasta
		char *pszOutGenomeFile,			// output pseudo genome file
		char *pszOutGeneFile);			// output pseudo gene file

#ifdef _WIN32
int genpseudogenome(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int
genpseudogenome(int argc, char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif

int iFileLogLevel;			// level of file diagnostics
int iScreenLogLevel;		// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file
int Rslt = 0;   			// function result code >= 0 represents success, < 0 on failure
int Idx;

int LenNSeps;				// generate with this number of 'N' bases separating concatenated sequences
int PMode;				// processing mode
int FMode;				// format output mode

char szTrackTitle[cMaxDatasetSpeciesChrom];		// track title if output format is UCSC BED

char szOutGenomeFile[_MAX_PATH];			// pseudo genome to this file
char szOutGeneFile[_MAX_PATH];			// pseudo genes to this file
int NumInputFiles;						// number of input files
char *pszInfileSpecs[cMaxInFileSpecs];  // input (wildcards allowed) multifasta files

char szSQLiteDatabase[_MAX_PATH];	// results summaries to this SQLite file
char szExperimentName[cMaxDatasetSpeciesChrom+1];			// experiment name
char szExperimentDescr[1000];		// describes experiment

// command line args
struct arg_lit  *help    = arg_lit0("h","help",                 "print this help and exit");
struct arg_lit  *version = arg_lit0("v","version,ver",			"print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel",		"<int>","Level of diagnostics written to screen and logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>",		"diagnostics log file");

struct arg_int *pmode = arg_int0("m","mode","<int>",		    "generate processing mode: 0 - standard");
struct arg_int *format = arg_int0("M","format","<int>",		    "output format: 0 - output genome as single concatenated fasta)");
struct arg_int *lennseps = arg_int0("n","lennseps","<int>",		    "generate with this number of 'N' bases separating concatenated sequences (default 100, range 5..100)");
struct arg_file *infiles = arg_filen("i","in","<file>",0,cMaxInFileSpecs,"input from these multifasta files, wildcards allowed");
struct arg_file *outgenomefile = arg_file1("o","out","<file>",	"output pseudo genome to this file");
struct arg_file *outgenefile = arg_file1("O","outbed","<file>",	"Output pseudo gene (BED) file");

struct arg_str  *title = arg_str0("t","title","<string>",       "track title");
struct arg_file *summrslts = arg_file0("q","sumrslts","<file>",		"Output results summary to this SQLite3 database file");
struct arg_str *experimentname = arg_str0("w","experimentname","<str>",		"experiment name SQLite3 database file");
struct arg_str *experimentdescr = arg_str0("W","experimentdescr","<str>",	"experiment description SQLite3 database file");

struct arg_end *end = arg_end(200);

void *argtable[] = {help,version,FileLogLevel,LogFile,
					summrslts,experimentname,experimentdescr,
					pmode,lennseps,format,title,infiles,	outgenomefile,outgenefile,
					end};

char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
	argerrors = arg_parse(argerrors,pAllArgs,argtable);

/* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
        {
		printf("\n%s %s %s, Version %s\nOptions ---\n", gszProcName,gpszSubProcess->pszName,gpszSubProcess->pszFullDescr,cpszProgVer);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
		printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
		printf("\n      To invoke this parameter file then precede its name with '@'");
		printf("\n      e.g. %s %s @myparams.txt\n",gszProcName,gpszSubProcess->pszName);
		printf("\nPlease report any issues regarding usage of %s at https://github.com/csiro-crop-informatics/biokanga/issues\n\n",gszProcName);
		return(1);
        }

    /* special case: '--version' takes precedence error reporting */
if (version->count > 0)
        {
		printf("\n%s %s Version %s\n",gszProcName,gpszSubProcess->pszName,cpszProgVer);
		return(1);
        }

if (!argerrors)
	{
	if(FileLogLevel->count && !LogFile->count)
		{
		printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>\n'",FileLogLevel->ival[0]);
		exit(1);
		}

	iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
	if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
		{
		printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d\n",iFileLogLevel,eDLNone,eDLDebug);
		exit(1);
		}

	if(LogFile->count)
		{
		strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
		szLogFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		iFileLogLevel = eDLNone;
		szLogFile[0] = '\0';
		}

	// now that log parameters have been parsed then initialise diagnostics log system
	if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
		{
		printf("\nError: Unable to start diagnostics subsystem\n");
		if(szLogFile[0] != '\0')
			printf(" Most likely cause is that logfile '%s' can't be opened/created\n",szLogFile);
		exit(1);
		}

	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Subprocess %s Version %s starting",gpszSubProcess->pszName,cpszProgVer);
	gExperimentID = 0;
	gProcessID = 0;
	gProcessingID = 0;
	szSQLiteDatabase[0] = '\0';
	szExperimentName[0] = '\0';
	szExperimentDescr[0] = '\0';

	if(experimentname->count)
		{
		strncpy(szExperimentName,experimentname->sval[0],sizeof(szExperimentName));
		szExperimentName[sizeof(szExperimentName)-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(szExperimentName);
		CUtility::ReduceWhitespace(szExperimentName);
		}
	else
		szExperimentName[0] = '\0';

	gExperimentID = 0;
	gProcessID = 0;
	gProcessingID = 0;
	szSQLiteDatabase[0] = '\0';
	szExperimentDescr[0] = '\0';
	if(summrslts->count)
		{
		strncpy(szSQLiteDatabase,summrslts->filename[0],sizeof(szSQLiteDatabase)-1);
		szSQLiteDatabase[sizeof(szSQLiteDatabase)-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(szSQLiteDatabase);
		if(strlen(szSQLiteDatabase) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite database specified with '-q<filespec>' option");
			return(1);
			}

		if(strlen(szExperimentName) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite experiment name specified with '-w<str>' option");
			return(1);
			}
		if(experimentdescr->count)
			{
			strncpy(szExperimentDescr,experimentdescr->sval[0],sizeof(szExperimentDescr)-1);
			szExperimentDescr[sizeof(szExperimentDescr)-1] = '\0';
			CUtility::TrimQuotedWhitespcExtd(szExperimentDescr);
			}
		if(strlen(szExperimentDescr) < 1)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no SQLite experiment description specified with '-W<str>' option");
			return(1);
			}

		gExperimentID = gSQLiteSummaries.StartExperiment(szSQLiteDatabase,false,true,szExperimentName,szExperimentName,szExperimentDescr);
		if(gExperimentID < 1)
			return(1);
		gProcessID = gSQLiteSummaries.AddProcess((char *)gpszSubProcess->pszName,(char *)gpszSubProcess->pszName,(char *)gpszSubProcess->pszFullDescr);
		if(gProcessID < 1)
			return(1);
		gProcessingID = gSQLiteSummaries.StartProcessing(gExperimentID,gProcessID,(char *)cpszProgVer);
		if(gProcessingID < 1)
			return(1);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"Initialised SQLite database '%s' for results summary collection",szSQLiteDatabase);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database experiment identifier for '%s' is %d",szExperimentName,gExperimentID);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database process identifier for '%s' is %d",(char *)gpszSubProcess->pszName,gProcessID);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"SQLite database processing instance identifier is %d",gProcessingID);
		}
	else
		{
		szSQLiteDatabase[0] = '\0';
		szExperimentDescr[0] = '\0';
		}

	PMode = (etPMode)(pmode->count ? pmode->ival[0] : ePMdefault);
	if(PMode < ePMdefault || PMode >= ePMplaceholder)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Processing mode '-m%d' specified outside of range %d..%d\n",PMode,ePMdefault,(int)ePMplaceholder-1);
		exit(1);
		}

	FMode = (etFMode)(format->count ? format->ival[0] : eFMdefault);

	LenNSeps = lennseps->count ? lennseps->ival[0] : cDfltNSeps;
	if(LenNSeps < cMinNSeps || LenNSeps > cMaxNSeps)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Length of 'N' sequence separators '-n%d' specified outside of range %d..%d\n",LenNSeps,cMinNSeps,cMaxNSeps);
		exit(1);
		}

	FMode = (etFMode)(format->count ? format->ival[0] : eFMdefault);
	if(FMode < eFMdefault || FMode >= eFMplaceholder)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Output format mode '-m%d' specified outside of range %d..%d\n",FMode,eFMdefault,(int)eFMplaceholder-1);
		exit(1);
		}

	szTrackTitle[0] = '\0';
	if(title->count)
		{
		strncpy(szTrackTitle,title->sval[0],sizeof(szTrackTitle));
		szTrackTitle[sizeof(szTrackTitle)-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(szTrackTitle);
		CUtility::ReduceWhitespace(szTrackTitle);
		}
	if(szTrackTitle[0] == '\0')
		{
		gDiagnostics.DiagOut(eDLWarn,gszProcName,"Warning: output format requested to be UCSC BED but no track title with '-t<title' specified, defaulting to 'pseudo'\n");
		strcpy(szTrackTitle,"pseudo");
		}

	strcpy(szOutGeneFile,outgenefile->filename[0]);
	strcpy(szOutGenomeFile,outgenomefile->filename[0]);

	for(NumInputFiles=Idx=0;NumInputFiles < cMaxInFileSpecs && Idx < infiles->count; Idx++)
		{
		pszInfileSpecs[Idx] = NULL;
		if(pszInfileSpecs[NumInputFiles] == NULL)
			pszInfileSpecs[NumInputFiles] = new char [_MAX_PATH];
		strncpy(pszInfileSpecs[NumInputFiles],infiles->filename[Idx],_MAX_PATH);
		pszInfileSpecs[NumInputFiles][_MAX_PATH-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(pszInfileSpecs[NumInputFiles]);
		if(pszInfileSpecs[NumInputFiles][0] != '\0')
			NumInputFiles++;
		}

	if(!NumInputFiles)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no input file(s) specified with '-i<filespec>' option)\n");
		exit(1);
		}

// show user current resource limits
#ifndef _WIN32
	gDiagnostics.DiagOut(eDLInfo, gszProcName, "Resources: %s",CUtility::ReportResourceLimits());
#endif

	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Version: %s Processing parameters:",cpszProgVer);

	const char *pszDescr;
	switch(PMode) {
		case ePMdefault:
			pszDescr = "Standard processing";
			break;
		default:
			pszDescr = "Default processing";
			break;
		}
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Processing mode is : '%s'",pszDescr);

	switch(FMode) {
		case eFMdefault:
			pszDescr = "output as single pseudo chrom genome fasta and associated gene BED file";
			break;
		}

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Length of inter-sequence separator N's: %d",LenNSeps);
	for(Idx = 0; Idx < NumInputFiles; Idx++)
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Process from input file (%d): '%s'",Idx+1,pszInfileSpecs[Idx]);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output pseudo genome file : '%s'",szOutGenomeFile);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output pseudo gene (BED) file : '%s'",szOutGeneFile);

	if(szExperimentName[0] != '\0')
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"This processing reference: %s",szExperimentName);

	if(gExperimentID > 0)
		{
		int ParamID;
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szLogFile),"log",szLogFile);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(INT32),"mode",&PMode);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(INT32),"format",&FMode);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(INT32),"lennseps",&LenNSeps);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTInt32,sizeof(INT32),"NumInputFiles",&NumInputFiles);
		for(Idx = 0; Idx < NumInputFiles; Idx++)
			ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(pszInfileSpecs[Idx]),"in",pszInfileSpecs[Idx]);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szOutGenomeFile),"out",szOutGenomeFile);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szOutGeneFile),"outbed",szOutGeneFile);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szTrackTitle),"title",szTrackTitle);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szSQLiteDatabase),"sumrslts",szSQLiteDatabase);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szExperimentName),"experimentname",szExperimentName);
		ParamID = gSQLiteSummaries.AddParameter(gProcessingID,ePTText,(int)strlen(szExperimentDescr),"experimentdescr",szExperimentDescr);
		}

#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
	gStopWatch.Start();
	Rslt = GPGProcess((etPMode)PMode,(etFMode)FMode,LenNSeps,szTrackTitle,NumInputFiles,pszInfileSpecs,szOutGenomeFile,szOutGeneFile);
	Rslt = Rslt >=0 ? 0 : 1;
	if(gExperimentID > 0)
		{
		if(gProcessingID)
			gSQLiteSummaries.EndProcessing(gProcessingID,Rslt);
		gSQLiteSummaries.EndExperiment(gExperimentID);
		}
	gStopWatch.Stop();
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	exit(Rslt);
	}
else
	{
    printf("\n%s %s %s, Version %s\n", gszProcName,gpszSubProcess->pszName,gpszSubProcess->pszFullDescr,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	exit(1);
	}
return 0;
}

int m_hInSrcFile;		// currently opened input file
int m_hOutGenomeFile; // currently opened output pseudo genome file
int m_hOutGeneFile;		// currently opened output bed file

const int cAllocInFasta = 300000000;			// buffer fasta input as being the maximal sized expected single contig or scaffold
const int cAllocOutFasta = 1000000;				// buffer output gene (BED) file
const int cAllocInBED = 1000000;				// buffer output gene (BED) file

UINT8 *m_pInFastaBuff;							// allocd to hold input fasta
char *m_pOutFastaBuff;							// allocd to hold buffered output fasta
char *m_pOutBEDBuff;							// allocd to hold buffred output BED
int m_OutFastaOfs;								// bytes used m_pOutFastaBuff
int m_OutBEDOfs;								// bytes used m_pOutFastaBuff

UINT32 m_GenomeLen;								// total pseudo genome length
int m_TotEntries;								// total number of contigs or scaffolds in pseudo genome
etSeqBase m_100Ns[cMaxNSeps];					// to hold upto 100 eBaseNs used to separate contigs/scaffolds in output pseudo genome
int m_CurFastaCol;								// next fasta col to write into

void
GPGReset(void)
{
if(m_hInSrcFile != -1)
	{
	close(m_hInSrcFile);
	m_hInSrcFile = -1;
	}
if(m_hOutGenomeFile != -1)
	{
	close(m_hOutGenomeFile);
	m_hOutGenomeFile = -1;
	}
if(m_hOutGeneFile != -1)
	{
	close(m_hOutGeneFile);
	m_hOutGeneFile = -1;
	}
if(m_pInFastaBuff != NULL)
	{
	delete m_pInFastaBuff;
	m_pInFastaBuff = NULL;
	}
if(m_pOutFastaBuff != NULL)
	{
	delete m_pOutFastaBuff;
	m_pOutFastaBuff = NULL;
	}
if(m_pOutBEDBuff != NULL)
	{
	delete m_pOutBEDBuff;
	m_pOutBEDBuff = NULL;
	}

m_OutFastaOfs = 0;
m_OutBEDOfs = 0;
m_TotEntries = 0;
m_CurFastaCol = 0;
m_GenomeLen = 0;
memset(m_100Ns,eBaseN,sizeof(m_100Ns));
}

void
GPGInit(void)
{
m_hInSrcFile = -1;
m_hOutGenomeFile = -1;
m_hOutGeneFile = -1;
m_pInFastaBuff = NULL;
m_pOutFastaBuff = NULL;
m_pOutBEDBuff = NULL;
GPGReset();
}

int
OutputFasta(int SeqLen,			// sequence length
			etSeqBase *pSeq)	// sequence
{
int NumCols;
int ReadOfs = 0;
int	ReadLenRem = SeqLen;
while(SeqLen)
	{
	if(m_CurFastaCol == 70)
		{
		m_OutFastaOfs += sprintf(&m_pOutFastaBuff[m_OutFastaOfs],"\n");
		m_CurFastaCol = 0;
		}
	NumCols = min(SeqLen, 70 - m_CurFastaCol);
	CSeqTrans::MapSeq2Ascii(&pSeq[ReadOfs],NumCols,&m_pOutFastaBuff[m_OutFastaOfs],'N','U','I',true);
	m_OutFastaOfs += NumCols;
	m_CurFastaCol += NumCols;
	ReadOfs += NumCols;
	SeqLen -= NumCols;
	if((m_OutFastaOfs + 1000) > cAllocOutFasta)
		{
		CUtility::SafeWrite(m_hOutGenomeFile,m_pOutFastaBuff,m_OutFastaOfs);
		m_OutFastaOfs = 0;
		}
	}
return(eBSFSuccess);
}

int
OutputGene(char *pszGenome,
			char *pszName,
           char Strand,
		   UINT32 GeneStart,
		   UINT32 GeneLen)
{

if(m_OutBEDOfs + 1000  > cAllocInBED)
	{
	CUtility::SafeWrite(m_hOutGeneFile,m_pOutBEDBuff,m_OutBEDOfs);
	m_OutBEDOfs = 0;
	}

m_OutBEDOfs += sprintf(&m_pOutBEDBuff[m_OutBEDOfs],"%s\t%d\t%d\t%s\t%d\t%c",pszGenome,GeneStart,GeneStart+GeneLen,pszName,0,Strand);
m_OutBEDOfs += sprintf(&m_pOutBEDBuff[m_OutBEDOfs],"\t%d\t%d\t%d\t%d\t%d,\t%d,\n",GeneStart,GeneStart+GeneLen,0,1,GeneLen,0);
return(eBSFSuccess);
}

int
LoadFasta(int LenNSeps,					// generate with this number of 'N' bases separating concatenated sequences
			char *pszGenome,char *pszFastaFile)
{
CFasta Fasta;
char szName[cBSFSourceSize];
char szDescription[cBSFDescriptionSize];
UINT32 GeneStart;

int SeqLen;
int Descrlen;
bool bFirstEntry;
bool bEntryCreated;
int Rslt;
int SeqID;

int ChromID;
size_t TotLen;

TotLen = 0;
ChromID = 0;

if((Rslt=Fasta.Open(pszFastaFile,true))!=eBSFSuccess)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to open '%s' [%s] %s",pszFastaFile,Fasta.ErrText((teBSFrsltCodes)Rslt),Fasta.GetErrMsg());
	GPGReset();
	return(Rslt);
	}
bFirstEntry = true;
bEntryCreated = false;
SeqID = 0;
ChromID = 0;
TotLen = 0;
while((Rslt = SeqLen = Fasta.ReadSequence(m_pInFastaBuff,cAllocInFasta,true,false)) > eBSFSuccess)
	{
	if(!m_TotEntries || SeqLen == eBSFFastaDescr)		// just read a descriptor line or else the first entry without a descriptor
		{
		m_TotEntries += 1;
		if(SeqLen == eBSFFastaDescr)
			Descrlen = Fasta.ReadDescriptor(szDescription,cBSFDescriptionSize);
		if(SeqLen != eBSFFastaDescr || sscanf(szDescription," %s[ ,]",szName)!=1)
			sprintf(szName,"%s.%d",pszFastaFile,m_TotEntries);
		if(SeqLen == eBSFFastaDescr)
			continue;
		}

	// if not the first entry then separate with SepLen 'N's
	if(m_TotEntries > 1)
		{
		if((Rslt=OutputFasta(LenNSeps,m_100Ns)) < eBSFSuccess)
			break;
		m_GenomeLen += LenNSeps;
		}

	GeneStart = m_GenomeLen;
	// output sequence to fasta here
	if((Rslt=OutputFasta(SeqLen,m_pInFastaBuff)) < eBSFSuccess)
		break;
	m_GenomeLen += SeqLen;
	OutputGene(pszGenome,szName,'+',GeneStart,m_GenomeLen - GeneStart);
	}

if(Rslt < eBSFSuccess)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"LoadFasta [%s] %s",Fasta.ErrText((teBSFrsltCodes)Rslt),Fasta.GetErrMsg());
	GPGReset();
	return(Rslt);
	}

return(eBSFSuccess);
}

int
GPGProcess(etPMode PMode,					// processing mode
		etFMode FMode,					// output format mode
		int LenNSeps,					// generate with this number of 'N' bases separating concatenated sequences
		char *pszGenomeName,			// track title for output UCSC BED and psudeo genome fasta descriptor
		int NumInputFileSpecs,		  	// number of input file specs
		char *pszInfileSpecs[],		  	// names of inputs files containing multifasta
		char *pszOutGenomeFile,			// output pseudo genome file
		char *pszOutGeneFile)			// output pseudo gene file
{
int Rslt;
int Idx;
char *pszInfile;

GPGInit();

#ifdef _WIN32
if((m_hOutGenomeFile = open(pszOutGenomeFile, _O_RDWR | _O_BINARY | _O_SEQUENTIAL | _O_CREAT | _O_TRUNC, _S_IREAD | _S_IWRITE ))==-1)
#else
if((m_hOutGenomeFile = open(pszOutGenomeFile,O_RDWR | O_CREAT |O_TRUNC, S_IREAD | S_IWRITE ))==-1)
#endif
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"OpenDumpFile:Unable to create or truncate  output file %s error: %s",pszOutGenomeFile,strerror(errno));
	GPGReset();
	return(false);
	}

#ifdef _WIN32
if((m_hOutGeneFile = open(pszOutGeneFile, _O_RDWR | _O_BINARY | _O_SEQUENTIAL | _O_CREAT | _O_TRUNC, _S_IREAD | _S_IWRITE ))==-1)
#else
if((m_hOutGeneFile = open(pszOutGeneFile,O_RDWR | O_CREAT |O_TRUNC, S_IREAD | S_IWRITE ))==-1)
#endif
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"Process: Unable to create or truncate  output file %s error: %s",pszOutGeneFile,strerror(errno));
	GPGReset();
	return(false);
	}

if((m_pInFastaBuff = new unsigned char [cAllocInFasta]) == NULL)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"ProcessFastaFile:- Unable to allocate memory (%d bytes) for sequence buffer",cAllocInFasta);
	GPGReset();
	return(eBSFerrMem);
	}

if((m_pOutFastaBuff = new char [cAllocOutFasta]) == NULL)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"ProcessFastaFile:- Unable to allocate memory (%d bytes) for sequence buffer",cAllocOutFasta);
	GPGReset();
	return(eBSFerrMem);
	}

if((m_pOutBEDBuff = new char [cAllocInBED]) == NULL)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"ProcessFastaFile:- Unable to allocate memory (%d bytes) for sequence buffer",cAllocInBED);
	GPGReset();
	return(eBSFerrMem);
	}

m_GenomeLen = 0;
m_TotEntries = 0;
m_OutFastaOfs = sprintf(m_pOutFastaBuff,">%s\n",pszGenomeName);
m_OutBEDOfs = sprintf(m_pOutBEDBuff,"track type=bed name=\"%s\" description=\"%s\"\n",pszGenomeName,pszGenomeName);

// iterate the input files
CSimpleGlob glob(SG_GLOB_FULLSORT);
for(Idx = 0; Idx < NumInputFileSpecs; Idx++)
	{
	glob.Init();
	if(glob.Add(pszInfileSpecs[Idx]) < SG_SUCCESS)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to glob '%s",pszInfileSpecs[Idx]);
		GPGReset();
		return(eBSFerrOpnFile);
		}

	if(glob.FileCount() <= 0)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to locate any input source contig or scaffold fasta files matching '%s",pszInfileSpecs[Idx]);
		continue;
		}

	Rslt = eBSFSuccess;
	for (int FileID = 0; Rslt >= eBSFSuccess &&  FileID < glob.FileCount(); ++FileID)
		{
		pszInfile = glob.File(FileID);
		gDiagnostics.DiagOut(eDLInfo,gszProcName,"Loading and parsing contig or scaffolds from file '%s'\n",pszInfile);
		Rslt = LoadFasta(LenNSeps,pszGenomeName,pszInfile);
		if(Rslt != eBSFSuccess)
			{
			gDiagnostics.DiagOut(eDLFatal,gszProcName,"Process: Load failed for input contig or scaffolds file '%s'\n",pszInfile);
			GPGReset();
			return(Rslt);
			}
		}
	}
if(m_CurFastaCol != 0)
	m_OutFastaOfs += sprintf(&m_pOutFastaBuff[m_OutFastaOfs],"\n");
if(m_hOutGenomeFile != -1)
	{
	if(m_OutFastaOfs > 0)
		{
		CUtility::SafeWrite(m_hOutGenomeFile,m_pOutFastaBuff,m_OutFastaOfs);
		m_OutFastaOfs = 0;
		}
	close(m_hOutGenomeFile);
	m_hOutGenomeFile = -1;
	}

if(m_hOutGeneFile != -1)
	{
	if(m_OutBEDOfs)
		{
		CUtility::SafeWrite(m_hOutGeneFile,m_pOutBEDBuff,m_OutBEDOfs);
		m_OutBEDOfs = 0;
		}
	close(m_hOutGeneFile);
	m_hOutGeneFile = -1;
	}

GPGReset();
return(eBSFSuccess);
}


text:
package org.drools.core.command;

import org.drools.core.command.impl.GenericCommand;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.command.Context;

/**
 *
 * @author salaboy
 */
public class NewKnowledgeBuilderConfigurationCommand implements GenericCommand<Void>{
    private String kbuilderConfId;

    public NewKnowledgeBuilderConfigurationCommand(String kbuilderConfId) {
        this.kbuilderConfId = kbuilderConfId;
    }

    public Void execute(Context context) {

        context.set(kbuilderConfId,
                    KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration());

        return null;
    }

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace NuGet
{
    public class UnzippedPackageRepository : PackageRepositoryBase, IPackageLookup
    {
        public UnzippedPackageRepository(string physicalPath)
            : this(new DefaultPackagePathResolver(physicalPath), new PhysicalFileSystem(physicalPath))
        {
        }

        public UnzippedPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem)
        {
            FileSystem = fileSystem;
            PathResolver = pathResolver;

            Logger = fileSystem.Logger;
        }

        protected IFileSystem FileSystem
        {
            get;
            private set;
        }

        internal IPackagePathResolver PathResolver
        {
            get;
            set;
        }

        public override string Source
        {
            get { return FileSystem.Root; }
        }

        public override bool SupportsPrereleasePackages
        {
            get { return true; }
        }

        public override IQueryable<IPackage> GetPackages()
        {
            return (from file in FileSystem.GetFiles("", "*" + Constants.PackageExtension)
                    let packageName = Path.GetFileNameWithoutExtension(file)
                    where FileSystem.DirectoryExists(packageName)
                    select new UnzippedPackage(FileSystem, packageName)).AsQueryable();
        }

        public IPackage FindPackage(string packageId, SemanticVersion version)
        {
            string packageName = GetPackageFileName(packageId, version);
            if (Exists(packageId, version))
            {
                return new UnzippedPackage(FileSystem, packageName);
            }
            return null;
        }

        public IEnumerable<IPackage> FindPackagesById(string packageId)
        {
            return GetPackages().Where(p => p.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase));
        }

        public bool Exists(string packageId, SemanticVersion version)
        {
            string packageName = GetPackageFileName(packageId, version);
            string packageFile = packageName + Constants.PackageExtension;
            return FileSystem.FileExists(packageFile) && FileSystem.DirectoryExists(packageName);
        }

        private static string GetPackageFileName(string packageId, SemanticVersion version)
        {
            return packageId + "." + version.ToString();
        }
    }
}


text:
<body>
  Defines built-in commands, environments, accent maps, globals and related concepts.
</body>


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../css/app.css">
    <title>Title</title>
</head>
<body>
    <main id="app"></main>
    <script src="https://use.fontawesome.com/28c0357342.js"></script>
    <script type="text/javascript">
        require(__dirname + '/../js/app.js');
    </script>
</body>
</html>


text:
package os.running.leaderboard.app.base;

/**
 * @author Martin "Garth" Zander <garth@new-crusader.de>
 */
public class FriendsAdapterData extends LiveSessionAdapterData
{}


text:
package org.apache.shiro.samples.spring.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.JdbcUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Realm that exists to support salted credentials.  The JdbcRealm implementation needs to be updated in a future
 * Shiro release to handle this.
 */
public class SaltAwareJdbcRealm extends JdbcRealm {

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

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();

        // Null username is invalid
        if (username == null) {
            throw new AccountException("Null usernames are not allowed by this realm.");
        }

        Connection conn = null;
        AuthenticationInfo info = null;
        try {
            conn = dataSource.getConnection();

            String password = getPasswordForUser(conn, username);

            if (password == null) {
                throw new UnknownAccountException("No account found for user [" + username + "]");
            }

            SimpleAuthenticationInfo saInfo = new SimpleAuthenticationInfo(username, password, getName());
            /**
             * This (very bad) example uses the username as the salt in this sample app.  DON'T DO THIS IN A REAL APP!
             *
             * Salts should not be based on anything that a user could enter (attackers can exploit this).  Instead
             * they should ideally be cryptographically-strong randomly generated numbers.
             */
            saInfo.setCredentialsSalt(ByteSource.Util.bytes(username));

            info = saInfo;

        } catch (SQLException e) {
            final String message = "There was a SQL error while authenticating user [" + username + "]";
            if (log.isErrorEnabled()) {
                log.error(message, e);
            }

            // Rethrow any SQL errors as an authentication exception
            throw new AuthenticationException(message, e);
        } finally {
            JdbcUtils.closeConnection(conn);
        }

        return info;
    }

    private String getPasswordForUser(Connection conn, String username) throws SQLException {

        PreparedStatement ps = null;
        ResultSet rs = null;
        String password = null;
        try {
            ps = conn.prepareStatement(authenticationQuery);
            ps.setString(1, username);

            // Execute query
            rs = ps.executeQuery();

            // Loop over results - although we are only expecting one result, since usernames should be unique
            boolean foundResult = false;
            while (rs.next()) {

                // Check to ensure only one row is processed
                if (foundResult) {
                    throw new AuthenticationException("More than one user row found for user [" + username + "]. Usernames must be unique.");
                }

                password = rs.getString(1);

                foundResult = true;
            }
        } finally {
            JdbcUtils.closeResultSet(rs);
            JdbcUtils.closeStatement(ps);
        }

        return password;
    }

}


text:
from lxml import etree as et

import pcbmode.config as config
from . import messages as msg

# pcbmode modules
from . import utils
from . import svg
from .point import Point

def placeShape(shape, svg_layer, invert=False, original=False):
    """
    Places a shape or type 'Shape' onto SVG layer 'svg_layer'.
    'invert'  : placed path should be mirrored
    'original': use the original path, not the transformed one
    """

    sig_dig = config.cfg['significant-digits']

    style_string = shape.getStyleString()
    style_type = shape.getStyleType()
    gerber_lp = shape.getGerberLP()
    location = shape.getLocation()

    if original == False:
        translate = 'translate(%s,%s)' % (round((((1,-1)[invert])*location.x), sig_dig),
                                          round(location.y*config.cfg['invert-y'], sig_dig))
        transform = translate
    else:
        transform = None

    if invert == True:
        path = shape.getTransformedPath(True)
    else:
        if original == True:
            path = shape.getOriginalPath()
        else:
            path = shape.getTransformedPath()

    element = et.SubElement(svg_layer,
                            'path',
                            d=path)
    # Set style string
    element.set('style', style_string)

    # Set style type in pcbmode namespace. This is later used to easliy
    # identify the type when the path is converted to Gerber format
    element.set('{'+config.cfg['ns']['pcbmode']+'}style', style_type)

    if transform != None:
        element.set('transform', transform)

    if gerber_lp != None:
        element.set('{'+config.cfg['ns']['pcbmode']+'}gerber-lp', gerber_lp)

    if shape.getType() == 'text':
        element.set('{'+config.cfg['ns']['pcbmode']+'}text', shape.getText())

    return element

def placeDrill(drill,
               layer,
               location,
               scale,
               soldermask_layers={},
               mask_groups={}):
    """
    Places the drilling point
    """

    diameter = drill.get('diameter')
    offset = utils.to_Point(drill.get('offset') or [0, 0])
    path = svg.drill_diameter_to_path(diameter)
    mask_path = svg.circle_diameter_to_path(diameter)

    sig_dig = config.cfg['significant-digits']
    transform = 'translate(%s %s)' % (round((location.x + offset.x)*scale, sig_dig),
                                      round((-location.y - offset.y)*scale, sig_dig))

    drill_element = et.SubElement(layer, 'path',
                                  transform=transform,
                                  d=path,
                                  id='pad_drill',
                                  diameter=str(diameter))

    pour_buffer = 1.0
    try:
        pour_buffer = board_cfg['distances']['buffer_from_pour_to'].get('drill') or 1.0
    except:
        pass

    # add a mask buffer between pour and board outline
    if mask_groups != {}:
        for pcb_layer in surface_layers:
            mask_group = et.SubElement(mask_groups[pcb_layer], 'g',
                                            id="drill_masks")
            pour_mask = et.SubElement(mask_group, 'path',
                                      transform=transform,
                                      style=MASK_STYLE % str(pour_buffer*2),
                                      gerber_lp="c",
                                      d=mask_path)

    # place the size of the drill; id the drill element has a
    # "show_diameter": "no", then this can be suppressed
    # default to 'yes'
    show_diameter = drill.get('show_diameter') or 'yes'
    if show_diameter.lower() != 'no':
        text = "%s mm" % (str(diameter))
        text_style = config.stl['layout']['drills'].get('text') or None
        if text_style is not None:
            text_style['font-size'] = str(diameter/10.0)+'px'
            text_style = utils.dict_to_style(text_style)
            t = et.SubElement(layer, 'text',
                x=str(location.x),
                # TODO: get rid of this hack
                y=str(-location.y-(diameter/4)),
                style=text_style)
            t.text = text

    # place soldermask unless specified otherwise
    # default is 'yes'
    add_soldermask = drill.get('add_soldermask') or 'yes'
    style = utils.dict_to_style(config.stl['layout']['soldermask'].get('fill'))
    possible_answers = ['yes', 'top', 'top only', 'bottom', 'bottom only', 'top and bottom']
    if (add_soldermask.lower() in possible_answers) and (soldermask_layers != {}):
        # TODO: get this into a configuration parameter
        drill_soldermask_scale_factors = drill.get('soldermask_scale_factors') or {'top':1.2, 'bottom':1.2}
        path_top = svg.circle_diameter_to_path(diameter * drill_soldermask_scale_factors['top'])
        path_bottom = svg.circle_diameter_to_path(diameter * drill_soldermask_scale_factors['bottom'])

        if add_soldermask.lower() == 'yes' or add_soldermask.lower() == 'top and bottom':
            drill_element = et.SubElement(soldermask_layers['top'],
                                          'path',
                                          transform=transform,
                                          style=style,
                                          d=path_top)
            drill_element = et.SubElement(soldermask_layers['bottom'],
                                          'path',
                                          transform=transform,
                                          style=style,
                                          d=path_bottom)
        elif add_soldermask.lower() == 'top only' or add_soldermask.lower() == 'top':
            drill_element = et.SubElement(soldermask_layers['top'],
                                          'path',
                                          transform=transform,
                                          style=style,
                                          d=path_top)
        elif add_soldermask.lower() == 'bottom only' or add_soldermask.lower() == 'bottom':
            drill_element = et.SubElement(soldermask_layers['bottom'],
                                          'path',
                                          transform=transform,
                                          style=style,
                                          d=path_bottom)
        else:
            print("ERROR: unrecognised drills soldermask option")

    return


text:
package morfologik.tools;

/**
 * JAR entry point.
 */
public final class Launcher {
  private Launcher() {}

  @SuppressWarnings("deprecation")
  public static void main(String[] args) {
    CliTool.main(args, new FSACompile(),
                       new FSADump(),
                       new FSADecompile(),
                       new FSABuild(),
                       new FSAInfo(),
                       new DictCompile(),
                       new DictDecompile(),
                       new DictApply());
  }
}


text:
function copyClipboard() {
  var urlEl = document.getElementById("urlVal");
  range = document.createRange();
  range.selectNode(urlEl);
  window.getSelection().addRange(range);
  document.execCommand("copy");
}


text:
import {Declaration} from './declarations';
import {formatComment} from './formatting';
import {Export, Node} from './index';

export interface TsLintDisable {
  ruleName: string;
  why: string;
}

export class Document {
  readonly kind = 'document';
  path: string;
  members: Declaration[];
  referencePaths: Set<string>;
  header: string;
  isEsModule: boolean;
  tsLintDisables: TsLintDisable[];

  constructor(data: {
    path: string,
    members?: Declaration[],
    referencePaths?: Iterable<string>,
    header?: string,
    isEsModule?: boolean, tsLintDisables: TsLintDisable[],
  }) {
    this.path = data.path;
    this.members = data.members || [];
    this.referencePaths = new Set(Array.from(data.referencePaths || []));
    this.header = data.header || '';
    this.isEsModule = data.isEsModule || false;
    this.tsLintDisables = data.tsLintDisables;
  }

  /**
   * Iterate over all nodes in the document, depth first. Includes all
   * recursive ancestors, and the document itself.
   */
  * traverse(): Iterable<Node> {
    for (const m of this.members) {
      yield* m.traverse();
    }
    yield this;
  }

  /**
   * Clean up this AST.
   */
  simplify() {
    for (const node of this.traverse()) {
      if (node.kind === 'union') {
        node.simplify();
      }
    }
  }

  serialize(): string {
    let out = '';
    if (this.header) {
      out += formatComment(this.header, 0) + '\n';
    }
    const disables = this.tsLintDisables.slice();
    for (const node of this.traverse()) {
      if (node.kind === 'name' && node.name === 'any') {
        // TODO: replace `any` with `unknown`
        disables.push({
          ruleName: 'no-any',
          why: 'describes the API as best we are able today'
        });
        break;
      }
    }
    out += '\n';
    for (const disable of disables) {
      out += `// tslint:disable:${disable.ruleName} ${disable.why}\n`;
    }
    out += '\n';
    if (this.referencePaths.size > 0) {
      for (const ref of this.referencePaths) {
        out += `/// <reference path="${ref}" />\n`;
      }
      out += '\n';
    }
    out += this.members.map((m) => m.serialize()).join('\n');
    // If these are typings for an ES module, we want to be sure that TypeScript
    // will treat them as one too, which requires at least one import or export.
    if (this.isEsModule === true &&
        !this.members.some((m) => m.kind === 'import' || m.kind === 'export')) {
      out += '\n' + (new Export({identifiers: []})).serialize();
    }
    return out;
  }
}


text:
import math
import animation
from math import sin, cos
from geometry import Point, dot_product, cross_product

from PIL import Image, ImageDraw

def planar_apply(p, f, axis):
    if axis == "x":
        y,z = f(Point(p.y, p.z)).tuple()
        return Point(p.x, y, z)
    elif axis == "y":
        x,z = f(Point(p.x, p.z)).tuple()
        return Point(x, p.y, z)
    elif axis == "z":
        x,y = f(Point(p.x, p.y)).tuple()
        return Point(x, y, p.z)
    else:
        raise Exception("Unexpected axis {}".format(axis))

def exp(radius, angle):
    return Point(radius*math.cos(angle), radius*math.sin(angle))

def rotated(p, angle):
    theta = math.atan2(p.y,p.x)
    theta += angle
    radius = p.magnitude()
    return exp(radius, theta)

def planar_rotated(p, angle, axis):
    f = lambda p: rotated(p, angle)
    return planar_apply(p, f, axis)

#---------------------------------------- end of point geometry stuff ----------------------------------------

def cyclic_pairs(seq):
    for i in range(len(seq)):
        j = (i+1) % len(seq)
        yield seq[i], seq[j]

def frange(start, stop, step):
    i = 0
    while True:
        cur = start + (step * i)
        if cur > stop: break
        yield cur
        i += 1

def dot(draw, p, radius=3, **kwargs):
    kwargs.setdefault("fill", "black")
    draw.chord((p.x-radius, p.y-radius, p.x+radius, p.y+radius), 0, 359, **kwargs)

def angle_3d(a,b):
    return math.acos(dot_product(a,b) / (a.magnitude() * b.magnitude()))

#finds the point of intersection of line ab and segment cd.
def line_segment_intersection(a,b,c,d):
    #a line can be expressed as the set of points p for which
    #(p - p0) dot n = 0
    #where p0 is a point on the line and n is a normal vector to the line.
    #the vector equation for a line segment is
    #p = f*c + (1-f)*d = f*c - f*d + d = f*(c-d) + d
    #where f is a number between 0 and 1 inclusive.
    #
    #(f*(c-d) + d - p0) dot n = 0
    #((f*(c-d)) dot n) - ((p0 - d) dot n) = 0
    #((f*(c-d)) dot n) = ((p0 - d) dot n)
    #f*((c-d) dot n) = ((p0 - d) dot n)
    #f = ((p0 - d) dot n) / ((c-d) dot n)
    p0 = a
    n = exp(1, (a-b).angle() + math.radians(90))
    f = dot_product(p0-d, n) / dot_product(c-d, n)
    if 0 <= f <= 1:
        return (c+d)*f - d
    return None

def segment_segment_intersection(a,b,c,d):
    p = line_segment_intersection(a,b,c,d)
    q = line_segment_intersection(c,d,a,b)
    if p is None or q is None:
        return None
    return p

def get_bbox(poly):
    return (
        min(p.x for p in poly),
        min(p.y for p in poly),
        max(p.x for p in poly),
        max(p.y for p in poly)
    )

def point_in_polygon(p, poly):
    bbox = get_bbox(poly)
    if p.x < bbox[0] or p.y < bbox[1] or p.x > bbox[2] or p.y > bbox[3]:
        return False
    far_away_point = Point(-100, 0)
    count = 0
    for a,b in cyclic_pairs(poly):
        x = segment_segment_intersection(far_away_point, p, a, b)
        if x is not None:
            count += 1
    return count %2 == 1

def lies_behind(p, poly):
    #draw a line from the viewer's position to p, and see if it intersects the plane formed by poly.
    #formula courtesy of https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection
    a,b,c = poly
    n = cross_product(b-a, c-a)
    p0 = a
    l = Point(0,0,1)
    l0 = p

    if dot_product(l,n) == 0:
        #I think this only happens when the poly is viewed edge-on.
        return False
    d = dot_product(p0 - l0, n) / dot_product(l,n)
    return d < 0

def flattened(p):
    return Point(p.x, p.y)
def is_occluded_by(p, poly):
    p = flattened(p)
    poly = map(flattened, poly)
    return point_in_polygon(p, poly)

def make_frame(f):
    def get_torus_point(big_r, little_r, theta, iota):
        return Point(
            (big_r + little_r * cos(theta)) * cos(iota),
            (big_r + little_r * cos(theta)) * sin(iota),
            little_r*sin(theta)
        )
    big_r = 0.66
    little_r = 0.33
    points = []
    normals = []
    slices = []
    minor_resolution = 16
    major_resolution = 32
    minor_offset = -f*2*math.pi/minor_resolution
    major_offset = f*2*math.pi/major_resolution
    for theta in frange(minor_offset, minor_offset+2*math.pi, 2*math.pi / minor_resolution):
        slice = []
        for iota in frange(major_offset, major_offset+2*math.pi, 2*math.pi / major_resolution):
            adjusted_iota = iota + theta/major_resolution
            p = get_torus_point(big_r, little_r, theta, adjusted_iota)
            shell_p = get_torus_point(big_r, little_r+1, theta, adjusted_iota)
            normal = shell_p - p
            points.append(p)
            normals.append(normal)
            slice.append(p)
        slices.append(slice)

    polys = []
    for slice_a, slice_b in cyclic_pairs(slices):
        for (a,b),(c,d) in zip(cyclic_pairs(slice_a), cyclic_pairs(slice_b)):
            polys.append((a,b,c))
            polys.append((d,b,c))

    size = 800
    margin = 50
    to_screen = lambda s: int(((s+1)/2.0)*(size-margin*2)) + margin

    rotations = [
        (math.radians(-45), "x"),
        (math.radians(45), "y")
    ]

    for angle, axis in rotations:
        points =  [planar_rotated(p, angle, axis) for p in points]
        normals = [planar_rotated(p, angle, axis) for p in normals]
        polys =  [[planar_rotated(p, angle, axis) for p in poly  ] for poly in polys]

    img = Image.new("RGB", (size, size), "white")
    draw = ImageDraw.Draw(img)

    dot_size_resolution = 6
    dot_size = lambda z: dot_size_resolution-math.floor(((z + 1)/2)*dot_size_resolution)

    for idx, (p,n) in enumerate(zip(points, normals)):
        #print "{} / {}\r".format(idx, len(points)),

        #backface culling
        angle = angle_3d(n, Point(0,0,1))
        if angle < math.radians(90): continue

        #occlusion culling
        # if any(lies_behind(p, poly) and not any(p == vertex for vertex in poly) and is_occluded_by(p, poly) for poly in polys ):
           # continue

        #0 for points directly facing the camera, 1 for ones perpendicular
        magnitude = (angle - math.radians(180)) / math.radians(-90)
        #magnitude = magnitude ** 1/3.0
        x = int(255*magnitude)
        color = "#{:02x}{:02x}{:02x}".format(x,x,x)

        dot(draw, p.map(to_screen), dot_size(p.z), fill=color)

    draw_edges = False
    if draw_edges:
        for poly in polys:
            for a,b in cyclic_pairs(poly):
                draw.line(flattened(a.map(to_screen)).tuple() + flattened(b.map(to_screen)).tuple(), fill="black")
    return img.resize((size/2, size/2), Image.ANTIALIAS)

images = []
frames = 40
for i in range(frames):
    print i
    images.append(make_frame(float(i)/frames))

animation.make_gif(images)

#make_frame(0).save("output.png")


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  <servlet>
    <servlet-name>Greeting</servlet-name>
    <servlet-class>com.redhat.samples.switchyard.ws.GreetingService</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Greeting</servlet-name>
    <url-pattern>/greeting</url-pattern>
  </servlet-mapping>

</web-app>


text:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :categories
  has_many :expenses, through: :categories

  after_create :create_default_categories

  DEFAULT_CATEGORIES = [
     {name: 'Phone bill'},
     {name: 'Entertainment'},
     {name: 'Rent'},
     {name: 'Travel'},
     {name: 'Parties'},
     {name: 'Gifts'},
     {name: 'Phone bill'},
     {name: 'Miscellaneous'}
  ]

  def create_default_categories
    DEFAULT_CATEGORIES.each do |default_attrs|
      self.categories.build(default_attrs)
    end
  end

end


text:
requirejs.config({
    paths: {
        'text': '../lib/require/text',
        'durandal':'../lib/durandal/js',
        'plugins' : '../lib/durandal/js/plugins',
        'transitions' : '../lib/durandal/js/transitions',
        'knockout': '../lib/knockout/knockout-2.3.0',
        'bootstrap': '../lib/bootstrap/js/bootstrap',
        'jquery': '../lib/jquery/jquery-1.9.1',

    },
    shim: {
        'bootstrap': {
            deps: ['jquery'],
            exports: 'jQuery'
        },
    	'lib': {
    		deps: ['jquery', 'bootstrap']
    	}
    }
});

define(['durandal/system', 'durandal/app', 'durandal/viewLocator', 'lib'],  function (system, app, viewLocator, lib) {
    //>>excludeStart("build", true);
    system.debug(true);
    //>>excludeEnd("build");

    app.title = 'Potato';

    //specify which plugins to install and their configuration
    app.configurePlugins({
        router:true,
        dialog: true,
        widget: {
            kinds: ['expander']
        }
    });

    app.start().then(function () {
        //Replace 'viewmodels' in the moduleId with 'views' to locate the view.
        //Look for partial views in a 'views' folder in the root.
        viewLocator.useConvention();

        //Show the app by setting the root view model for our application.
        app.setRoot('shell');
    });
});


text:
package com.bj58.spat.esbclient.exception;

public class CommunicationException extends Exception {

    private static final long serialVersionUID = -3864991520786547002L;

    public CommunicationException(String message, Throwable cause) {
        super(message, cause);
    }

    public CommunicationException(String message) {
        super(message);
    }

    public CommunicationException(Throwable cause) {
        super(cause);
    }

    public CommunicationException() {
        super("comunication exception");
    }
}


text:
require 'spec_helper'

describe DocxReport::Report do
  subject { DocxReport::Report.new 'spec/files/template.docx' }

  it 'adds text fields' do
    subject.add_field 'name', 'Ahmed Abudaqqa'
    expect(subject.fields.detect do |f|
      f.name == '@name@' && f.value == 'Ahmed Abudaqqa' && f.type == :text
    end).to_not be_nil
  end

  it 'adds hyperlink fields' do
    subject.add_field 'url', 'abudaqqa.com', :hyperlink
    expect(subject.fields.detect do |f|
      f.name == '@url@' && f.value == 'abudaqqa.com' && f.type == :hyperlink
    end).to_not be_nil
  end

  it 'adds table loaded form a collection of data' do
    items = [{ name: 'Item 1', details: 'details of item 1', url: 'web1.com' },
             { name: 'Item 2', details: 'details of item 2', url: 'web2.com' },
             { name: 'Item 3', details: 'details of item 3', url: 'web3.com' }]
    subject.add_table 'table1', items do |table|
      table.add_field(:title, :name)
      table.add_field(:description) { |item| "Details: #{item[:details]}" }
      table.add_field(:url, :url, :hyperlink)
    end
    records = subject.tables.first.records
    expect(records.count).to eq(3)
    expect(records.detect do |r|
      r.fields.any? { |f| f.name == '@title@' && f.value == 'Item 1' } &&
      r.fields.any? do |f|
        f.name == '@description@' && f.value == 'Details: details of item 1'
      end &&
      r.fields.any? do |f|
        f.name == '@url@' && f.value == 'web1.com' && f.type == :hyperlink
      end
    end).not_to be_nil
    expect(records.detect do |r|
      r.fields.any? { |f| f.name == '@title@' && f.value == 'Item 3' } &&
      r.fields.any? do |f|
        f.name == '@description@' && f.value == 'Details: details of item 3'
      end &&
      r.fields.any? do |f|
        f.name == '@url@' && f.value == 'web3.com' && f.type == :hyperlink
      end
    end).not_to be_nil
  end

  it 'generates new docx file after apply changes' do
    temp = Tempfile.new 'output.docx'
    subject.add_field 'photo', 'spec/files/ruby.png', :image
    items = [{ name: 'Item 1', details: 'details of item 1', url: 'web1.com',
               link: 'https://www.ruby-lang.org/images/header-ruby-logo@2x.png',
               subitems: [{ subtitle: 'Item4' }, { subtitle: 'Item5' }] },
             { name: 'Item 2', details: 'details of item 2', url: 'web2.com',
               link: 'spec/files/ruby.png',
               subitems: [{ subtitle: 'Item6' }] },
             { name: 'Item 3', details: 'details of item 3', url: 'web3.com',
               link: 'spec/files/ruby.png',
               subitems: [{ subtitle: 'Item7' }, { subtitle: 'Item8' },
                          { subtitle: 'Item9' }] }]
    subject.add_table 'table1', items do |table|
      table.add_field(:title, :name)
      table.add_field(:description) { |item| "Details: #{item[:details]}" }
      table.add_field(:url, :url, :hyperlink)
      table.add_field(:picture, :link, :image)
      table.add_table(:subtable, :subitems).add_field(:subtitle, :subtitle)
    end
    subject.generate_docx temp.path
    expect(File.exist?(temp.path)).to be true
    temp.close!
  end

  private

  def load_main_xml(filename)
    zip = Zip::File.open(filename)
    main = Nokogiri::XML zip.read('word/document.xml')
    zip.close
    main
  end
end


text:
<?php

namespace ischenko\yii2\jsloader;

use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
use yii\web\View;

/**
 * The Behavior is used to process asset bundles registered within a view.
 *
 * It listens two events:
 *  - [[\yii\web\View::EVENT_END_BODY]] used to register an asset bundles from the view in the JS loader
 *  - [[\yii\web\View::EVENT_END_PAGE]] used to process other assets registered in the view and perform bootstrap of the JS loader
 *
 * @author Roman Ishchenko <roman@ishchenko.ck.ua>
 * @since 1.0
 *
 * @property View $owner
 */
class Behavior extends \yii\base\Behavior
{
    /**
     * @var LoaderInterface|array
     */
    private $loader = [];

    /**
     * @inheritdoc
     */
    public function events()
    {
        return [
            View::EVENT_END_PAGE => 'processAssets',
            View::EVENT_END_BODY => 'processBundles'
        ];
    }

    /**
     * Starts processing of assets by the loader
     */
    public function processAssets()
    {
        $this->getLoader()->processAssets();
    }

    /**
     * Registers asset bundles in the JS loader
     */
    public function processBundles()
    {
        $this->getLoader()->processBundles();
    }

    /**
     * @return LoaderInterface
     *
     * @throws InvalidConfigException
     */
    public function getLoader()
    {
        if (is_array($this->loader)) {
            $this->loader = \Yii::createObject($this->loader, [$this->ensureView($this->owner)]);
        }

        if (!($this->loader instanceof LoaderInterface)) {
            throw new InvalidConfigException('Unable to instantiate new loader please check configuration');
        }

        return $this->loader;
    }

    /**
     * @param LoaderInterface|array $loader
     *
     * @throws InvalidArgumentException
     */
    public function setLoader($loader)
    {
        if (!is_array($loader) && !($loader instanceof LoaderInterface)) {
            throw new InvalidArgumentException('Argument should be an array or implement LoaderInterface');
        }

        $this->loader = $loader;
    }

    /**
     * Ensures that passed object is an instance of \yii\web\View
     *
     * @param mixed $object
     *
     * @return View
     * @throws InvalidConfigException
     */
    protected function ensureView($object)
    {
        if (!($object instanceof View)) {
            $message = '"yii\web\View" instance expected';

            if (is_object($object)) {
                $message .= ', got "' . get_class($object) . '"';
            }

            throw new InvalidConfigException($message);
        }

        return $object;
    }
}


text:
Rails.application.routes.draw do

      resources :tickets

      root :to => 'tickets#index'

      devise_for :users, controllers: { sessions: "users/sessions", passwords: "users/passwords", registrations: "users/registrations" }, :path_prefix => 'u'

      resources :users, :except => :patch

      get 'deactivated_users', to: 'users#deactivated_user_index'

      resources :users do
        member do
          patch 'deactivate'
          patch 'reactivate'
          get 'change_password'
        end
      end

      devise_for :admins, controllers: { sessions: "admins/sessions", passwords: "admins/passwords", registrations: "admins/registrations" }

      resources :admins, :except => :patch

      get 'deactivated_admins', to: 'admins#deactivated_admin_index'

      resources :admins do
        member do
          patch 'deactivate'
          patch 'reactivate'
          get 'change_password'
          get  'send_smstext'
          get 'smstext'
        end
      end

      get 'admin_dashboard', to: 'admin_dashboard#index'
      get 'admin_dashboard/metrics', to: 'admin_dashboard#metrics'
      get 'admin_dashboard/:id/resolve', to: 'admin_dashboard#resolve', :as => 'resolve_ticket'
      get 'admin_dashboard/:id/show', to: 'admin_dashboard#show', :as => 'show_admin'
      get 'admin_dashboard/activity', to: 'admin_dashboard#activity'
      patch 'admin_dashboard/:id/', to: 'admin_dashboard#update'
      delete 'admin_dashboard/:id/destroy', to: 'admin_dashboard#destroy', :as => 'destroy_ticket'

      resources :conversations, only: [:index, :show, :destroy] do
        member do
          post :reply
          post :restore
          post :mark_as_read
        end
        collection do
          delete :empty_trash
        end
      end

      resources :messages, only: [:new, :create]

      resources :tasks do
        member do
          put :toggle
        end
      end

      get 'cancel', to: 'tasks#cancel'

end


text:
package org.apereo.cas.adaptors.trusted.web.flow;

import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.adaptors.trusted.authentication.principal.PrincipalBearingCredential;
import org.apereo.cas.adaptors.trusted.authentication.principal.RemoteRequestPrincipalAttributesExtractor;
import org.apereo.cas.authentication.Credential;
import org.apereo.cas.authentication.adaptive.AdaptiveAuthenticationPolicy;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.web.flow.AbstractNonInteractiveCredentialsAction;
import org.apereo.cas.web.flow.resolver.CasDelegatingWebflowEventResolver;
import org.apereo.cas.web.flow.resolver.CasWebflowEventResolver;
import org.apereo.cas.web.support.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.webflow.execution.RequestContext;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * This is {@link BasePrincipalFromNonInteractiveCredentialsAction}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
public abstract class BasePrincipalFromNonInteractiveCredentialsAction extends AbstractNonInteractiveCredentialsAction {
    private static final Logger LOGGER = LoggerFactory.getLogger(BasePrincipalFromNonInteractiveCredentialsAction.class);

    /**
     * The principal factory used to construct the final principal.
     */
    protected final PrincipalFactory principalFactory;

    private final RemoteRequestPrincipalAttributesExtractor principalAttributesExtractor;

    public BasePrincipalFromNonInteractiveCredentialsAction(final CasDelegatingWebflowEventResolver initialAuthenticationAttemptWebflowEventResolver,
                                                            final CasWebflowEventResolver serviceTicketRequestWebflowEventResolver,
                                                            final AdaptiveAuthenticationPolicy adaptiveAuthenticationPolicy,
                                                            final PrincipalFactory principalFactory,
                                                            final RemoteRequestPrincipalAttributesExtractor extractor) {
        super(initialAuthenticationAttemptWebflowEventResolver, serviceTicketRequestWebflowEventResolver, adaptiveAuthenticationPolicy);
        this.principalFactory = principalFactory;
        this.principalAttributesExtractor = extractor;
    }

    @Override
    protected Credential constructCredentialsFromRequest(final RequestContext context) {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        final String remoteUser = getRemotePrincipalId(request);

        if (StringUtils.isNotBlank(remoteUser)) {
            LOGGER.debug("User [{}] found in HttpServletRequest", remoteUser);

            final Map<String, Object> attributes = principalAttributesExtractor.getAttributes(request);
            LOGGER.debug("Attributes [{}] found in HttpServletRequest", attributes);

            return new PrincipalBearingCredential(this.principalFactory.createPrincipal(remoteUser, attributes));
        }
        LOGGER.debug("No user found in HttpServletRequest");
        return null;
    }

    /**
     * Gets remote principal id.
     *
     * @param request the request
     * @return the remote principal id
     */
    protected abstract String getRemotePrincipalId(HttpServletRequest request);
}


text:
<?php
use models\ProjectModel;
use models\QuestionListModel;
use models\QuestionModel;

require_once dirname(__FILE__) . '/../TestConfig.php';
require_once SimpleTestPath . 'autorun.php';
require_once TestPath . 'common/MongoTestEnvironment.php';
require_once SourcePath . "models/QuestionModel.php";

class TestQuestionModel extends UnitTestCase
{

    public function testCRUD_Works()
    {
        $e = new MongoTestEnvironment();
        $e->clean();
        $textRef = MongoTestEnvironment::mockId();
        $project = $e->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE);

        // List
        $list = new QuestionListModel($project, $textRef);
        $list->read();
        $this->assertEqual(0, $list->count);

        // Create
        $question = new QuestionModel($project);
        $question->title = "SomeQuestion";
        $question->description = "SomeQuestion";
        $question->textRef->id = $textRef;
        $id = $question->write();
        $this->assertNotNull($id);
        $this->assertIsA($id, 'string');
        $this->assertEqual($id, $question->id->asString());

        // Read back
        $otherQuestion = new QuestionModel($project, $id);
        $this->assertEqual($id, $otherQuestion->id->asString());
        $this->assertEqual('SomeQuestion', $otherQuestion->title);
        $this->assertEqual($textRef, $otherQuestion->textRef->id);

        // Update
        $otherQuestion->description = 'OtherQuestion';
        $otherQuestion->write();

        // Read back
        $otherQuestion = new QuestionModel($project, $id);
        $this->assertEqual('OtherQuestion', $otherQuestion->description);

        // List
        $list->read();
        $this->assertEqual(1, $list->count);

        // Delete
        QuestionModel::remove($project->databaseName(), $id);

        // List
        $list->read();
        $this->assertEqual(0, $list->count);
    }

    public function testTextReference_NullRefValidRef_AllowsNullRef()
    {
        $e = new MongoTestEnvironment();
        $project = $e->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE);

        $mockTextRef = (string) new \MongoId();

        // Test create with null textRef
        $question = new QuestionModel($project);
        $id = $question->write();

        $otherQuestion = new QuestionModel($project, $id);
        $this->assertEqual('', $otherQuestion->textRef->id);

        // Test update with textRef
        $question->textRef->id = $mockTextRef;
        $question->write();

        $otherQuestion = new QuestionModel($project, $id);
        $this->assertEqual($mockTextRef, $otherQuestion->textRef->id);
    }
}


text:
YouTube Video Linker - MS Windows version of [YTVAL](http://walkman100.github.io/ytvl)

Many thanks to [Deavmi](http://github.com/Deavmi) for his code, quite a bit of the code used in this project I learnt from his projects

Jump to:
- Requirements
- How to use
- What the Links & Flags do
- Suggest a feature
- Debugging

External links:
- [Screenshots](https://walkman100.github.io/ytvl-screenshots)
- [Donate](https://walkman100.github.io/donate)
- [Future releases/ideas](https://github.com/Walkman100/gists/blob/master/ProjectsAndFeatures.md#ytvl)
- [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Walkman100/Walkman?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
- [AppVeyor](http://ci.appveyor.com/) build status:
[![Build status](https://ci.appveyor.com/api/projects/status/ao70dapbuoho2yk2)](https://ci.appveyor.com/project/Walkman100/ytvl)
- The source code is also available on [Visual Studio online](https://walkman.visualstudio.com/DefaultCollection/YTVL).

# Requirements
- Windows `(tested on Windows 7 HP SP1 64-bit & Windows 8.1 Pro Update 1 64-bit)`

- In order for the update checker and the video name loader to work, you need an active internet connection and at least Internet Explorer 7 installed and enabled (even if you don't use it. ever.)

## Compile requirements
See [CompileInstructions.md](https://github.com/Walkman100/gists/blob/master/CompileInstructions.md)

## Download
Get the latest version [here](https://github.com/Walkman100/YTVL/releases), and the latest build from commit
[here](https://ci.appveyor.com/project/Walkman100/YTVL/build/artifacts)
(note that these builds are built for the Debug config and so are not optimised)

# How to use
It is very simple to use this program. Simply paste your YouTube Video ID(1) into the first box, and click the `Video` button to open the page with the video, sharing options and comments; click the `comments` option to view only the comments (useful if you watched the video in Embedded mode); click the `Video Info` button to download a file with the video's info in it; click the `Embed Page Handler` button to open a page that has JUST the video on it, which is even more lightweight than YouTube Feather(2) was; click the `Reset` button to reset the form to how it was  when you opened it. If you expand the window to the right, you will see an `Exit` button, which is not visible by default since it allows you to press Esc to close the program.

If you want to copy the generated URL to the clipboard instead of opening it in the browser, you can right-click an output button and click `Generate URL to Clipboard`, this will generate the URL and copy it to your clipboard.

There is an option to the right of the `Outputs` group box that shows the notification icon. This icon can be useful if you want to open multiple pages without having to open the program again, it has all the options from the `Outputs` group box in it's context menu (when you right-click). It has an option to show the program, to hide the icon (same as unchecking the option in the main program) and to exit the program completely - which also removes the icon until you open the program again.

The `Keep window on top` checkbox at the top-right of the window makes the window stay on top of all other windows. This checkbox and the option in the notification context menu do the same thing.

The `Check for updates automatically` checkbox option, if you are using a version below `v1.3.3`, loads the file at [Walkman.Github.io/ver.txt](http://walkman100.github.io/Walkman/YTVL/ver.txt) and checks the current version against the version listed in that file whenever you tick the option, or if the option is ticked when the program opens. Versions later than and including `v1.3.3` load the url [here](http://github.com/Walkman100/YTVL/releases/latest) instead, since that is automatically redirected to the current version by GitHub, which returns e.g. `https://github.com/Walkman100/YTVL/releases/tag/v1.3.3`.
_______________________________________________________________________________
1. A YouTube Video ID is the random letters at the end of a YouTube video URL, e.g. the id of the URL
> https://www.youtube.com/watch?v=z9Uz1icjwrM

is `z9Uz1icjwrM`. This ID is found in any Page's URL containing a video, even embedded ones.↩

2. As the page on [their website](https://www.youtube.com/feather_beta) said, "The "Feather" project is intended to serve YouTube video watch pages with the lowest latency possible. It achieves this by severely limiting the features available to the viewer and making use of advanced web techniques for reducing the total amount of bytes downloaded by the browser. It is a work in progress and may not work for all videos." Enable it [here](https://www.youtube.com/feather_beta). **Note**: YouTube Feather has been discontinued.↩

# What the Links & Flags do
Links:
- **Original page** goes here: http://walkman100.github.io/Walkman/HTML/YTVL.html
- **Source code** goes here: https://github.com/Walkman100/YTVL/
- **Report a problem** goes here: https://github.com/Walkman100/YTVL/issues/new
- **Latest release** goes here: https://github.com/Walkman100/YTVL/releases/latest where it is automatically redirected to the latest version

Generally, the name of the flag speaks for itself, but here is a short description:

The advanced options are mostly useful for embedded videos:
- **AutoPlay**: if this is set to `1`, the video will automatically begin playing when the page loads

***_`WIP`_***

# Want to suggest a feature?
Go ahead! Anyone is welcome to submit a PR (Pull/Push Request) or an Issue as long as the feature/addition doesn't make the program file size significantly bigger, or increases the time it takes to start. Also, keep in mind the KISS principle (Keep It Simple, Stupid). Notice I haven't added a settings window because there are only three settings, and my application interface has space for those settings without it looking too cluttered.

# Debugging
Press Alt + D to show the Browser windows to the right of the buttons in the Outputs group box.

- The first one shows the object that is loaded to get the video title. It is possible to play videos from this object.
- The second one shows the page that is loaded to get the current version. If this page does not show a valid page, then the program might give an error message. Unchecking the `Check for updates automatically` checkbox will prevent this page from ever being loaded until you select the checkbox again.

[![Screenshot with Debugging info shown][DebuggingScreenshot]][DebuggingScreenshot]

  [DebuggingScreenshot]: http://walkman100.github.io/images/Screenshots/My_Projects/YTVL/AdvancedOptionsWithDebugKeyCombinationPressed.png "Screenshot with Debugging info shown"

### Screenshots
Screenshots available [here](https://walkman100.github.io/ytvl-screenshots).

### Future releases/ideas
See [this gist](https://github.com/Walkman100/gists/blob/master/ProjectsAndFeatures.md#ytvl).


text:
using Senparc.NeuChar.Entities;
using Senparc.NeuChar;

namespace Senparc.Weixin.Work.Entities
{
    public class RequestMessageVoice : WorkRequestMessageBase, IRequestMessageVoice
    {
        public override RequestMsgType MsgType
        {
            get { return RequestMsgType.Voice; }
        }

        /// <summary>
        /// 语音消息媒体id,可以调用多媒体文件下载接口拉取数据。
        /// </summary>
        public string MediaId { get; set; }
        /// <summary>
        /// 语音格式:amr
        /// </summary>
        public string Format { get; set; }
    }
}


text:
/**
 * @classdesc
 * A popup element to be displayed over the map and attached to a single map
 * location.  Like {@link ol.control.Control}, Overlays are visible widgets.
 * Unlike Controls, they are not in a fixed position on the screen, but are tied
 * to a geographical coordinate, so panning the map will move an Overlay but not
 * a Control.
 *
 * Example:
 *
 *     var popup = new ol.Overlay.Popup();
 *     map.addOverlay(popup);
 *     popup.show(coordinate, "Hello!");
 *     popup.hide();
 *
 * @constructor
 * @extends {ol.Overlay}
 * @param {olx.OverlayOptions} options Overlay options
 *		+ popupClass: the a class for the overlay.
 *		+ closeBox: popup has a close box.
 *		+ onclose: callback when close box is clicked.
 *		+ positionning: add 'auto' to let the popup choose a good positioning.
 * @api stable
 */
ol.Overlay.Popup = function (options)
{	var self = this;
	var elt = $("<div>");
	this.element = options.element = elt.get(0);
	this.offsetBox = options.offsetBox;
	// Anchor div
	$("<div>").addClass("anchor").appendTo(elt);
	var d = $("<div>").addClass('ol-overlaycontainer-stopevent').appendTo(elt);
	// Content
	this.content = $("<div>").addClass("content").appendTo(d).get(0);
	// Closebox
	this.closeBox = options.closeBox;
	$("<button>").addClass("closeBox").addClass(options.closeBox?"hasclosebox":"")
				.prependTo(d)
				.click(function()
				{	self.hide();
					if (typeof (options.onclose) == 'function') options.onclose();
				});
	// Stop event
	options.stopEvent=false;
	d.on("mousedown touchstart", function(e){ e.stopPropagation(); })

	ol.Overlay.call(this, options);

	this.setPopupClass(options.popupClass);
	this.setPositioning(options.positioning);
}
ol.inherits(ol.Overlay.Popup, ol.Overlay);

/**
 * Get CSS class of the popup according to its positioning.
 * @private
 */
ol.Overlay.Popup.prototype.getClassPositioning = function ()
{	var c = "";
	var pos = this.getPositioning();
	if (/bottom/.test(pos)) c += "ol-popup-bottom ";
	if (/top/.test(pos)) c += "ol-popup-top ";
	if (/left/.test(pos)) c += "ol-popup-left ";
	if (/right/.test(pos)) c += "ol-popup-right ";
	if (/^center/.test(pos)) c += "ol-popup-middle ";
	if (/center$/.test(pos)) c += "ol-popup-center ";
	return c;
}

/**
 * Set CSS class of the popup.
 * @param {string} class name.
 * @api stable
 */
ol.Overlay.Popup.prototype.setClosebox = function (b)
{	this.closeBox = b;
	if (b) $(this.element).addClass("hasclosebox");
	else $(this.element).removeClass("hasclosebox");
}

/**
 * Set the CSS class of the popup.
 * @param {string} class name.
 * @api stable
 */
ol.Overlay.Popup.prototype.setPopupClass = function (c)
{	$(this.element).removeClass()
		.addClass("ol-popup "+(c||"default")+" "+this.getClassPositioning()+(this.closeBox?" hasclosebox":""));
}

/**
 * Add a CSS class to the popup.
 * @param {string} class name.
 * @api stable
 */
ol.Overlay.Popup.prototype.addPopupClass = function (c)
{	$(this.element).addClass(c);
}

/**
 * Remove a CSS class to the popup.
 * @param {string} class name.
 * @api stable
 */
ol.Overlay.Popup.prototype.removePopupClass = function (c)
{	$(this.element).removeClass(c);
}

/**
 * Remove a CSS class to the popup.
 * @param {string} class name.
 * @api stable
 */
ol.Overlay.Popup.prototype.setPositioning = function (pos)
{	if (/auto/.test(pos))
	{	this.autoPositioning = pos.split('-');
		if (this.autoPositioning.length==1) this.autoPositioning[1]="auto";
	}
	else this.autoPositioning = false;
	pos = pos.replace(/auto/g,"center");
	if (pos=="center") pos = "bottom-center";
	this.setPositioning_(pos);
}
ol.Overlay.Popup.prototype.setPositioning_ = function (pos)
{	ol.Overlay.prototype.setPositioning.call(this, pos);
	$(this.element).removeClass("ol-popup-top ol-popup-bottom ol-popup-left ol-popup-right ol-popup-center ol-popup-middle");
	$(this.element).addClass(this.getClassPositioning());
}

/**
 * Set the position and the content of the popup.
 * @param {ol.Coordinate|string} the coordinate of the popup or the HTML content.
 * @param {string|undefined} the HTML content (undefined = previous content).
 * @api stable
 */
ol.Overlay.Popup.prototype.show = function (coordinate, html)
{	if (!html && typeof(coordinate)=='string')
	{	html = coordinate;
		coordinate = null;
	}

	var self = this;
	var map = this.getMap();
	if (html)
	{	// this.content.innerHTML = html;
		$(this.content).html("").append(html);
		// Refresh when loaded (img)
		$("*", this.content).load(function()
		{	map.renderSync();
		})
	}

	if (coordinate)
	{	// Auto positionning
		if (this.autoPositioning)
		{	var p = map.getPixelFromCoordinate(coordinate);
			var s = map.getSize();
			var pos=[];
			if (this.autoPositioning[0]=='auto')
			{	pos[0] = (p[1]<s[1]/3) ? "top" : "bottom";
			}
			else pos[0] = this.autoPositioning[0];
			pos[1] = (p[0]<2*s[0]/3) ? "left" : "right";
			this.setPositioning_(pos[0]+"-"+pos[1]);
			if (this.offsetBox)
			{	this.setOffset([this.offsetBox[pos[1]=="left"?2:0], this.offsetBox[pos[0]=="top"?3:1] ]);
			}
		}
		// Show
		this.setPosition(coordinate);
		// Set visible class (wait to compute the size/position first)
		$(this.element).parent().show();
		this._tout = setTimeout (function()
		{	$(self.element).addClass("visible");
		}, 0);
	}
}

/**
 * Hide the popup
 * @api stable
 */
ol.Overlay.Popup.prototype.hide = function ()
{	this.setPosition(undefined);
	if (this._tout) clearTimeout(this._tout)
	$(this.element).removeClass("visible");
}