text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.ServiceModel;

using WindowsPhone.Recipes.Push.Server.Services;

namespace WindowsPhone.Recipes.Push.Server.ViewModels
{
    [Export, PartCreationPolicy(CreationPolicy.Shared)]
    internal class MainViewModel : ViewModelBase
    {
        private PushService _pushService;
        private ImageService _imageService;
        private PushPatternViewModel _activePattern;

        [ImportingConstructor]
        public MainViewModel([ImportMany(typeof(PushPatternViewModel))] IEnumerable<PushPatternViewModel> pushPatterns)
        {
            PushPatterns = pushPatterns;
            ActivePattern = pushPatterns.FirstOrDefault();
        }

        [Import]
        private PushService PushService
        {
            get { return _pushService; }
            set
            {
                _pushService = value;
                _pushService.Subscribed += (s, e) => NotifyPropertyChanged("Subscribers");
                _pushService.Host();
            }
        }

        [Import]
        private ImageService ImageService
        {
            get { return _imageService; }
            set
            {
                _imageService = value;
                _imageService.Host();
            }
        }

        public IEnumerable<PushPatternViewModel> PushPatterns { get; private set; }

        [Import]
        public MessageStatusViewModel MessageStatus { get; private set; }

        public PushPatternViewModel ActivePattern
        {
            get { return _activePattern; }

            set
            {
                if (_activePattern != value)
                {
                    if (_activePattern != null)
                    {
                        // Deactivate old pattern.
                        _activePattern.IsActive = false;
                    }

                    _activePattern = value;
                    if (_activePattern != null)
                    {
                        // Activate new pattern.
                        _activePattern.IsActive = true;
                    }

                    NotifyPropertyChanged("ActivePattern");
                }
            }
        }

        public int Subscribers
        {
            get { return PushService.SubscribersCount; }
        }
    }
}


text:
package de.ifsr.adam;

import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import org.json.*;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;

import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.chart.*; //Make this more specific
import javafx.scene.image.WritableImage;
import javafx.scene.layout.GridPane;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ScrollPane;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javax.imageio.ImageIO;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap;

/**
 * Main class for image output generation.
 *
 * @author Simon
 */
public class ImageGenerator {

    static Logger log = Logger.getLogger(ImageGenerator.class.getName());
    private final JSONArray survey;
    private final JSONArray answerTypes;
    private final Scene scene;
    private String formatName;
    private Integer imageHeight;
    private Integer imageWidth;
    private URI stylesheetURI;

    /**
     * Constructs a new ImageGenerator with a given scene and image output format. Default
     * Constructor.
     *
     * @param formatName One of three basic formats .png, .jpeg or .gif
     * @param scene The scene where the image is printed in
     */
    ImageGenerator(String surveyPath, String answerTypesPath, String stylesheetPath) {
	survey = JSONStuff.importJSONArray(surveyPath);
	answerTypes = JSONStuff.importJSONArray(answerTypesPath);//TODO: Make this more dynamic
	this.setStylesheet(stylesheetPath); //TODO: Make this more dynamic
	imageHeight = Formats.DINA4_HEIGHT;
	imageWidth = Formats.DINA4_WIDTH;
	this.scene = new Scene(new Group());
	formatName = "png";
    }

    //TODO:Remove

    /**
     * Constructs a new ImageGenerator with a given scene and image output format. Only for quick
     * testing.
     *
     * @param formatName One of three basic formats .png, .jpeg or .gif
     * @param scene The scene where the image is printed in
     */
    ImageGenerator(Scene scene, String formatName) {
	survey = JSONStuff.importJSONArray(System.getProperty("user.dir") + "/survey.json");
	answerTypes = JSONStuff.importJSONArray(System.getProperty("user.dir")
		+ "/answerTypes.json");
	this.setStylesheet("C:\\Users\\Simon\\Desktop\\Adam 5.0\\data\\ChartStyle.css");
	imageHeight = Formats.DINA4_HEIGHT;
	imageWidth = Formats.DINA4_WIDTH;
	this.scene = scene;
	this.formatName = formatName;
    }

    //TODO: Remove

    /**
     * Constructs a new ImageGenerator with a given scene and the default format .png Only for quick
     * testing.
     *
     * @param scene The scene where the image is printed in
     */
    ImageGenerator(Scene scene) {
	survey = JSONStuff.importJSONArray(System.getProperty("user.dir") + "/survey.json");
	answerTypes = JSONStuff.importJSONArray(System.getProperty("user.dir")
		+ "/answerTypes.json");
	this.setStylesheet("C:\\Users\\Simon\\Desktop\\Adam 5.0\\data\\ChartStyle.css");
	imageHeight = Formats.DINA4_HEIGHT;
	imageWidth = Formats.DINA4_WIDTH;
	formatName = "png";
	this.scene = scene;
    }

    /**
     * Gets the value of the formatName.
     *
     * @return
     */
    public String getFormatName() {
	return formatName;
    }

    /**
     *
     * @return The Width of the output image.
     */
    public Integer getImageWidth() {
	return this.imageWidth;
    }

    /**
     *
     * @return The height of the output image.
     */
    public Integer getImageHeight() {
	return this.imageHeight;
    }

    /**
     * Sets the value of the formatName.
     *
     * @param formatName
     */
    public void setFormatName(String formatName) {
	this.formatName = formatName;
    }

    /**
     * Sets the height of the output image. Use the static member of Formats for this.
     *
     * @param height
     */
    public void setImageHeight(Integer height) {
	this.imageHeight = height;
    }

    /**
     * Sets the width of the output image. Use the static members of Formats for this.
     *
     * @param width
     */
    public void setImageWidth(Integer width) {
	this.imageWidth = width;
    }

    /**
     * Sets the cascading style sheet for the diagrams
     *
     * @param filePath
     */
    public final void setStylesheet(String filePath) {
	File file = new File(filePath);
	this.stylesheetURI = file.toURI();
    }

    private VBox generateImageVBox(JSONArray resultReport){
	ArrayList<Chart> chartList = generateCharts(resultReport);
	ArrayList<GridPane> gridPaneList = makeLayout(chartList, 3, 2);

	VBox vbox = new VBox();
	vbox.getChildren().addAll(gridPaneList);
	vbox.setPrefHeight(imageHeight * gridPaneList.size());

	return vbox;
    }

        /**
     * Main method for generating an PDF out of a report with it results.
     *
     * @param resultReport The report with it results
     * @param filePath The path to the output file.
     * @return returns true if the generation and saving of the image was successful, false
     * otherwise
     */
    public boolean generatePDF(JSONArray resultReport,String filePath) {
	log.info("PDF generation has started");
	VBox vbox = generateImageVBox(resultReport);
	log.info("End of PDF generation");
	return this.printToPDF(filePath,vbox);
    }

    /**
     * Main method for generating an Preview out of a report with it results.
     *
     * @param resultReport The report with it results
     * @return returns true if the generation and saving of the image was successful, false
     * otherwise
     */
    public Scene generatePreview(JSONArray resultReport) {
	log.info("Preview generation has started");
	VBox vbox = generateImageVBox(resultReport);

	ScrollPane scrollPane = new ScrollPane();
	scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
	scrollPane.setContent(vbox);

	//Gets the screen resulution for scaling.
	GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
	int width = gd.getDisplayMode().getWidth();
	int height = gd.getDisplayMode().getHeight();

	scrollPane.setVmax(100.0);
	scrollPane.setPrefSize(width * 0.65, height * 0.8); //TODO Can I do this better?

	((Group) scene.getRoot()).getChildren().add(scrollPane);
	scene.getStylesheets().add(this.stylesheetURI.toString());

	//The Observer for resizing the scrollpane when the window changes.
	scene.widthProperty().addListener(new ChangeListener<Number>() {
	    @Override public void changed(ObservableValue<? extends Number> observableValue,
		    Number oldSceneWidth, Number newSceneWidth) {
		scrollPane.setPrefWidth(newSceneWidth.doubleValue());
	    }
	});

	//The Observer for resizing the scrollpane when the window changes.
	scene.heightProperty().addListener(new ChangeListener<Number>() {
	    @Override public void changed(ObservableValue<? extends Number> observableValue,
		    Number oldSceneHeight, Number newSceneHeight) {
		scrollPane.setPrefHeight(newSceneHeight.doubleValue());
	    }
	});

	log.info("End of Preview generation");
	return scene;
    }

    /**
     * Puts the charts in chartList into GridPanes as specified by chartsPerColumn and chartsPerRow.
     *
     * @param chartList The ArrayList with the charts.
     * @param chartsPerColumn Number of charts that are in one column.
     * @param chartsPerRow Number of charts that are in one row.
     * @return The list of GridPanes that were generated.
     */
    private ArrayList<GridPane> makeLayout(ArrayList<Chart> chartList, Integer chartsPerColumn, Integer chartsPerRow) {
	ArrayList<GridPane> gridPaneList = new ArrayList<>();
	GridPane gridPane = new GridPane();
	int rowIndex = 0, columnIndex = 0;
	Iterator<Chart> iter = chartList.iterator();

	//int i = 0;//TODO: Remove
	while (iter.hasNext()) {
	    //System.out.println("Run: "+ i + " columnIndex: " + columnIndex + " rowIndex: " + rowIndex);//TODO: Remove
	    //i++;//TODO: Remove

	    Chart chart = iter.next();
	    calculateChartSize(chart, chartsPerColumn, chartsPerRow);
	    gridPane.add(chart, columnIndex, rowIndex);

	    columnIndex++;

	    //Case: Row is full go to next row
	    if (columnIndex >= chartsPerRow) {
		columnIndex = 0;
		rowIndex++;
	    }

	    //Case: Page is full start a new GridPane
	    if (rowIndex >= chartsPerColumn) {
		//The Layout for the gridPane
		gridPane.setHgap(imageWidth * 0.10);
		gridPane.setAlignment(Pos.CENTER);
		gridPane.setPrefWidth(imageWidth);
		gridPane.setPrefHeight(imageHeight);

		gridPaneList.add(gridPane);
		gridPane = new GridPane();
		rowIndex = 0;
	    }
	}

	//This needs to be check, or the last page can be empty
	if (rowIndex != 0 || columnIndex != 0) {
	    gridPaneList.add(gridPane);
	}

	return gridPaneList;
    }

    /**
     * Generates a list of Charts out of a Report. Right now it can only create Cake- and
     * Bardiagrams.
     *
     * @param resultReport The JSON representation of a report.
     * @return
     */
    private ArrayList<Chart> generateCharts(JSONArray resultReport) {
	ArrayList<Chart> chartList = new ArrayList<>();

	for (int i = 0; i < resultReport.length(); i++) {
	    JSONObject currentQuestion = null;
	    String chartName = null;
	    Chart chart;

	    try {
		currentQuestion = resultReport.getJSONObject(i);
		chartName = currentQuestion.getString("view");
	    } catch (JSONException | NullPointerException e) {
		log.fatal(e);
	    }

	    if (chartName != null) {
		if(isValidQuestion(currentQuestion)){
		    switch (chartName) {
			case ("bardiagram"):
			    chart = generateBarChart(currentQuestion);
			    break;
			case ("cakediagram"):
			    chart = generatePieChart(currentQuestion);
			    break;
			default:
			    chart = generateBarChart(currentQuestion);
			    break;
		    }
		    chartList.add(chart);
		} else {
		    log.debug("Question :" + currentQuestion);
		}
	    } else {
		log.debug("ChartName was null of " + currentQuestion);
	    }
	}

	return chartList;
    }

    /**
     * Takes a snapshot of the Pane and prints it to a pdf.
     *
     * @return True if no IOException occurred
     */
    private boolean printToPDF(String filePath, Pane pane) {
	//Scene set up
	Group root = new Group();
	Scene printScene = new Scene(root);
	printScene.getStylesheets().add(this.stylesheetURI.toString());

	//Snapshot generation
	ArrayList<WritableImage> images = new ArrayList<>();
	try{
	    ObservableList<Node> panes = pane.getChildren();
	    for(int i=0; i < panes.size(); i++){
		GridPane gridPane = (GridPane)panes.get(i);
		((Group) printScene.getRoot()).getChildren().clear();
		((Group) printScene.getRoot()).getChildren().addAll(gridPane);
		images.add(printScene.snapshot(null));
		panes.add(i, gridPane);
	    }
	}catch(Exception e){
	    log.error(e);
	    return false;
	}

	//PDF Setup
	File outFile = new File(filePath + "." + "pdf");
	Iterator<WritableImage> iterImages = images.iterator();
	PDDocument doc = new PDDocument();

	try{

	    while(iterImages.hasNext()){
		//Page setup
		PDPage page = new PDPage();
		doc.addPage(page);
		PDPageContentStream contentStream = new PDPageContentStream(doc,page,true, false);
	    	//Image setup
		BufferedImage bufImage = SwingFXUtils.fromFXImage(iterImages.next(), null);
		PDPixelMap pixelMap = new PDPixelMap(doc,bufImage);

		int width = (int)(page.getMediaBox().getWidth());
		int height = (int)(page.getMediaBox().getHeight());
		Dimension dim = new Dimension(width,height);
		contentStream.drawXObject(pixelMap, 0, 0, dim.width, dim.height);
		contentStream.close();
	    }

	    doc.save(outFile);
	    return true;
	}catch(IOException | COSVisitorException e){
	    log.error(e);
	    return false;
	}
    }

    /**
     * Takes a snapshot of the Pane and prints it to a file.
     *
     * @return True if no IOException occurred
     */
    private boolean printToFile(String fileName, Pane pane) {
	Group root = new Group();
	Scene printScene = new Scene(root);

	printScene.getStylesheets().add(this.stylesheetURI.toString());

	((Group) printScene.getRoot()).getChildren().addAll(pane);
	WritableImage image = printScene.snapshot(null);
	File outFile = new File(fileName + "." + formatName);

	try {
	    ImageIO.write(SwingFXUtils.fromFXImage(image, null), formatName, outFile);
	    return true;
	} catch (IOException e) {
	    log.error(e);
	    return false;
	}
    }

    /**
     * Generates a bar chart
     *
     * @param question A question JSONObject of a report
     * @return
     */
    private BarChart generateBarChart(JSONObject question) {

	XYChart.Series data;
	BarChart<Number, String> chart;

	JSONObject surveyQuestion;
	JSONObject answerType;
	JSONObject result;

	try {

	    surveyQuestion = getSurveyQuestion(question.getString("question"));
	    try {
		answerType = getAnswerType(surveyQuestion.getString("type"));
	    } catch (NullPointerException e) {
		log.error("The answerType of " + question + " wasnt generated due to a Nullpointer");
		log.debug("", e);
		return null;
	    }

	    result = question.getJSONObject("result");
	    data = generateDataBarChart(result, answerType);

	    //Axis
	    CategoryAxis yAxis = new CategoryAxis();
	    yAxis.setAnimated(false); //Needs to be set, otherwise the labels are not printed to a file in the end.
	    NumberAxis xAxis = new NumberAxis();
	    xAxis.setLabel("Stimmen"); //TODO: Multi Language support.
	    xAxis.setAnimated(false); //Needs to be set, otherwise the labels are not printed to a file in the end.

	    chart = new BarChart<>(xAxis, yAxis);
	    chart.getData().addAll(data);
	    chart.setTitle(surveyQuestion.getString("text"));
	    chart.setLegendVisible(false);
	} catch (JSONException e) {
	    log.error(e);
	    return null;
	}

	return chart;
    }

    /**
     * Creates the data series needed for creating a bar chart.
     *
     * @param result The result JSONObject you wish to transform
     * @param answerType The answer type JSONObject of the question
     * @return
     */
    private XYChart.Series generateDataBarChart(JSONObject result, JSONObject answerType) {
	XYChart.Series series = new XYChart.Series();

	try {
	    JSONObject answers;
	    String[] fieldNames;

	    try {
		answers = answerType.getJSONObject("answers");
		fieldNames = JSONObject.getNames(answers);
	    } catch (NullPointerException e) {
		log.error("Missing JSONObject in result:" + result + " answerType: " + answerType);
		log.debug("", e);
		return series;
	    }

	    for (int i = 1; i < fieldNames.length; i++) { //i initialized with 1 to ignore the empty string result
		String answer = answers.getString(fieldNames[i]);
		Integer value;

		try {
		    value = result.getInt(fieldNames[i]);
		} catch (JSONException e) {
		    value = 0;
		}

		series.getData().add(new XYChart.Data(value, answer));
	    }
	} catch (JSONException e) {
	    log.error(e);
	}
	return series;
    }

    /**
     * Generates a pie chart.
     *
     * @param question A question JSONObject of a report
     * @return
     */
    private PieChart generatePieChart(JSONObject question) {
	ObservableList<PieChart.Data> data;
	PieChart chart;

	JSONObject surveyQuestion;
	JSONObject answerType;
	JSONObject result;

	try {
	    surveyQuestion = getSurveyQuestion(question.getString("question"));
	    try {
		answerType = getAnswerType(surveyQuestion.getString("type"));
	    } catch (NullPointerException e) {
		log.error("The answerType of " + question + " wasnt generated due to a NullPointer");
		log.debug("", e);
		return null;
	    }

	    result = question.getJSONObject("result");
	    data = generateDataPieChart(result, answerType);

	    chart = new PieChart(data);
	    chart.setTitle(surveyQuestion.getString("text"));
	    chart.setLegendVisible(false);
	} catch (JSONException e) {
	    log.error(e);
	    return null;
	}

	return chart;
    }

    /**
     * Creates the data list for a pie chart.
     *
     * @param result The result JSONObject you wish to transform
     * @param answerType The answer type JSONObject of the question
     * @return
     */
    private ObservableList<PieChart.Data> generateDataPieChart(JSONObject result, JSONObject answerType) {
	ArrayList<PieChart.Data> list = new ArrayList<>();

	try {
	    JSONObject answers;
	    String[] fieldNames;

	    try {
		answers = answerType.getJSONObject("answers");
		fieldNames = JSONObject.getNames(result);
	    } catch (NullPointerException e) {
		log.error("Missing JSONObject in result:" + result + " answerType: " + answerType);
		log.debug("", e);
		return FXCollections.observableArrayList(list);
	    }

	    for (int i = 1; i < fieldNames.length; i++) {//i is 1 at the start to ignore the empty String result in the answers
		String answer = answers.getString(fieldNames[i]);
		Integer value = result.getInt(fieldNames[i]);
		list.add(new PieChart.Data(answer, value));
	    }
	} catch (JSONException e) {
	    log.error(e);
	}

	return FXCollections.observableArrayList(list);
    }

    /**
     * Looks up the JSONObject answer type in answerTypes
     *
     * @param answerType The answer type
     * @return The JSONObject for the answer type, or null if the type was not found
     */
    private JSONObject getAnswerType(String answerType) {
	return JSONStuff.getSpecificObject(answerTypes, "type", answerType);
    }

    /**
     * Looks up the JSONObject question in survey
     *
     * @param questionName The question
     * @return The JSONObject for the question, or null if the question was not found
     */
    private JSONObject getSurveyQuestion(String questionName) {
	return JSONStuff.getSpecificObject(survey, "name", questionName);
    }

    /**
     * validates if a question has all required fields, a valid answerType and a valid survey
     * question.
     *
     * @param question
     * @return
     */
    private boolean isValidQuestion(JSONObject question) {

	String questionId;

	if (question == null) {
	    log.debug("JSONObject question is null:");
	    return false;
	}

	try {
	    questionId = question.getString("question");
	} catch (JSONException e) {
	    log.debug("questionID isnt present in:");
	    return false;
	}
	try {
	    question.getString("view");
	} catch (JSONException e) {
	    log.debug("view isnt present in:");
	    return false;
	}
	try{
	    JSONObject result = question.getJSONObject("result");
	    if(result.length() == 0){
		log.debug("no result in:");
		return false;
	    }
	} catch (JSONException e) {
	    log.debug("result is null in:");
	    return false;
	}
	return isValidSurveyQuestion(questionId);
    }

    /**
     *
     * @param questionId
     * @return
     */
    private boolean isValidSurveyQuestion(String questionId) {

	JSONObject surveyQuestion = getSurveyQuestion(questionId);
	String questionType;

	if (surveyQuestion == null) {
	    log.debug("surveyQuestion is null for:");
	    return false;
	}

	try {
	    questionType = surveyQuestion.getString("type");
	} catch (JSONException e) {
	    log.debug("survey type isnt present for:");
	    return false;
	}
	return isValidAnswerType(questionType);
    }

    /**
     *
     * @param questionType
     * @return
     */
    private boolean isValidAnswerType(String questionType) {

	JSONObject answerType = getAnswerType(questionType);
	if(answerType == null){
	    log.debug("answerType isnt present for:");
	}
	return answerType != null;
    }

    /**
     * Calculates the right size of the chart for the given parameters.
     *
     * @param chart
     * @param chartsPerRow
     * @param chartsPerColumn
     */
    private void calculateChartSize(Chart chart, Integer chartsPerColumn, Integer chartsPerRow) {
	Double prefHeight, prefWidth;
	prefHeight = (imageHeight / chartsPerColumn) * 0.95;
	prefWidth = (imageWidth / chartsPerRow) * 0.95;
	chart.setPrefSize(prefWidth, prefHeight);
    }
}

redpajama_set_name: RedPajamaGithub


text:
template<typename T> void f0(T); // expected-note{{here}}
template void f0(int); // expected-error{{explicit instantiation of undefined function template}}

template<typename T>
struct X0 {
  struct Inner;

  void f1(); // expected-note{{here}}

  static T value; // expected-note{{here}}
};

template void X0<int>::f1(); // expected-error{{explicit instantiation of undefined member function}}

template int X0<int>::value; // expected-error{{explicit instantiation of undefined static data member}}

template<> void f0(long); // expected-note{{previous template specialization is here}}
template void f0(long); // expected-warning{{explicit instantiation of 'f0<long>' that occurs after an explicit specialization will be ignored}}

template<> void X0<long>::f1(); // expected-note{{previous template specialization is here}}
template void X0<long>::f1(); // expected-warning{{explicit instantiation of 'f1' that occurs after an explicit specialization will be ignored}}

template<> struct X0<long>::Inner; // expected-note{{previous template specialization is here}}
template struct X0<long>::Inner; // expected-warning{{explicit instantiation of 'Inner' that occurs after an explicit specialization will be ignored}}

template<> long X0<long>::value; // expected-note{{previous template specialization is here}}
template long X0<long>::value; // expected-warning{{explicit instantiation of 'value' that occurs after an explicit specialization will be ignored}}

template<> struct X0<double>; // expected-note{{previous template specialization is here}}
template struct X0<double>; // expected-warning{{explicit instantiation of 'X0<double>' that occurs after an explicit specialization will be ignored}}

// PR 6458
namespace test0 {
  template <class T> class foo {
    int compare(T x, T y);
  };

  template <> int foo<char>::compare(char x, char y);
  template <class T> int foo<T>::compare(T x, T y) {
    // invalid at T=char; if we get a diagnostic here, we're
    // inappropriately instantiating this template.
    void *ptr = x;
  }
  extern template class foo<char>; // expected-warning {{extern templates are a C++11 extension}}
  template class foo<char>;
}


text:
module Tenon
  module TenonContent
    module RowTypes
      class LeftImageRightText < TenonContent::RowTypes::Base
        class << self
          def add_pieces_to(row)
            if row.pieces.empty?
              row.pieces.build(piece_type: 'Image', position: 0, size: 6)
              row.pieces.build(piece_type: 'Text', position: 1, size: 6)
            end
          end
        end
      end
    end
  end
end


text:
<?php

/**
 * This class defines the structure of the 'rss_feed' table.
 *
 *
 *
 * This map class is used by Propel to do runtime db structure discovery.
 * For example, the createSelectSql() method checks the type of a given column used in an
 * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
 * (i.e. if it's a text column type).
 *
 * @package    propel.generator.rss-reader.map
 */
class FeedTableMap extends TableMap
{

    /**
     * The (dot-path) name of this class
     */
    const CLASS_NAME = 'rss-reader.map.FeedTableMap';

    /**
     * Initialize the table attributes, columns and validators
     * Relations are not initialized by this method since they are lazy loaded
     *
     * @return void
     * @throws PropelException
     */
    public function initialize()
    {
        // attributes
        $this->setName('rss_feed');
        $this->setPhpName('Feed');
        $this->setClassname('Feed');
        $this->setPackage('rss-reader');
        $this->setUseIdGenerator(true);
        // columns
        $this->addPrimaryKey('id', 'Id', 'INTEGER', true, null, null);
        $this->addColumn('link', 'Link', 'VARCHAR', true, 255, null);
        $this->addColumn('base_link', 'BaseLink', 'VARCHAR', true, 255, null);
        $this->addColumn('title', 'Title', 'VARCHAR', true, 255, null);
        $this->addColumn('description', 'Description', 'LONGVARCHAR', false, 255, null);
        $this->addColumn('updated', 'Updated', 'TIMESTAMP', false, null, null);
        $this->addColumn('to_update', 'ToUpdate', 'BOOLEAN', false, 1, true);
        $this->addColumn('mark_new_to_read', 'MarkNewToRead', 'BOOLEAN', false, 1, false);
        $this->addForeignKey('category_id', 'CategoryId', 'INTEGER', 'rss_category', 'id', true, null, null);
        $this->addColumn('valid', 'Valid', 'BOOLEAN', false, 1, true);
        $this->addColumn('viewframe', 'Viewframe', 'BOOLEAN', false, 1, false);
        $this->addColumn('cat_order', 'catOrder', 'INTEGER', false, null, 0);
        // validators
    } // initialize()

    /**
     * Build the RelationMap objects for this table relationships
     */
    public function buildRelations()
    {
        $this->addRelation('Category', 'Category', RelationMap::MANY_TO_ONE, array('category_id' => 'id', ), 'CASCADE', null);
        $this->addRelation('Entry', 'Entry', RelationMap::ONE_TO_MANY, array('id' => 'feed_id', ), 'CASCADE', null, 'Entrys');
    } // buildRelations()

} // FeedTableMap


text:
from functools import partial

import pytest
from plumbum.cmd import pg_dump

from pg_grant import parse_acl_item, FunctionInfo, PgObjectType
from pg_grant.query import (
    get_all_function_acls, get_all_sequence_acls, get_all_table_acls,
    get_all_type_acls)

pytestmark = pytest.mark.nocontainer

def _priv_acls(conn, acls, type_, revoke):
    for obj in acls:
        arg_types = None
        if isinstance(obj, FunctionInfo):
            arg_types = obj.arg_types

        if obj.acl is not None:
            for acl in obj.acl:
                parsed = parse_acl_item(acl)

                if revoke:
                    statements = parsed.as_revoke_statements(
                        type_, obj.name, schema=obj.schema, arg_types=arg_types)
                else:
                    statements = parsed.as_grant_statements(
                        type_, obj.name, schema=obj.schema, arg_types=arg_types)

                for stmt in statements:
                    conn.execute(stmt)

grant_table_acls = partial(_priv_acls, type_=PgObjectType.TABLE, revoke=False)
revoke_table_acls = partial(_priv_acls, type_=PgObjectType.TABLE, revoke=True)
grant_sequence_acls = partial(_priv_acls, type_=PgObjectType.SEQUENCE, revoke=False)
revoke_sequence_acls = partial(_priv_acls, type_=PgObjectType.SEQUENCE, revoke=True)
grant_type_acls = partial(_priv_acls, type_=PgObjectType.TYPE, revoke=False)
revoke_type_acls = partial(_priv_acls, type_=PgObjectType.TYPE, revoke=True)
grant_function_acls = partial(_priv_acls, type_=PgObjectType.FUNCTION, revoke=False)
revoke_function_acls = partial(_priv_acls, type_=PgObjectType.FUNCTION, revoke=True)

@pytest.mark.parametrize('get, revoke, grant', [
    (get_all_table_acls, revoke_table_acls, grant_table_acls),
    (get_all_sequence_acls, revoke_sequence_acls, grant_sequence_acls),
    (get_all_type_acls, revoke_type_acls, grant_type_acls),
    (get_all_function_acls, revoke_function_acls, grant_function_acls),
])
def test_revoke_grant_schema_relations(connection, postgres_url, get, revoke, grant):
    cmd = pg_dump['--schema-only', postgres_url]

    code, dump1, _ = cmd.run()
    assert code == 0

    acls = get(connection, 'public')
    revoke(connection, acls)

    code, dump2, _ = cmd.run()
    assert code == 0
    assert dump1 != dump2

    grant(connection, acls)

    code, dump3, _ = cmd.run()
    assert code == 0

    assert dump1 == dump3


text:
ID: 563
post_title: >
  Menghapus Semua Tabel di Sebuah Database
  MySQL
author: Muhammad Ikhsan
post_excerpt: |
  Jika Anda memiliki grep, maka Anda dapat gunakan snippet berikut:

mysqldump -u[username] -p[password] --add-drop-table --no-data [databasename] | grep ^DROP | mysql -u[username] -p[password] [databasename]

  Namun jika Anda di Windows dan tidak memiliki `grep`, Anda dapat gunakan:

mysqldump -u[username] -p[password] --add-drop-table --no-data [databasename] | findstr ^DROP | mysql -u[username] -p[password] [databasename]

layout: snippet
permalink: >
  http://belajarpemrograman.org/snippet/mysql/hapus-semua-tabel-dalam-database-mysql/
published: true
post_date: 2017-09-07 08:36:26
---
Karena alasan tertentu, kadang kala kita perlu mengosongkan sebuah database. Dengan kata lain menghapus semua tabel di sebuah database. Kalau kita memiliki *privilege* untuk `CREATE` dan `DROP` database, kita bisa menghapus database dulu, kemudian dibuat lagi. Ambil amannya saja, saya anggap kita tidak memilikinya.

Jika Anda memiliki `grep`, maka Anda dapat gunakan snippet berikut:

```
mysqldump -u[username] -p[password] --add-drop-table --no-data [databasename] | grep ^DROP | mysql -u[username] -p[password] [databasename]
```

Namun jika Anda di Windows dan tidak memiliki `grep`, Anda dapat gunakan:

```
mysqldump -u[username] -p[password] --add-drop-table --no-data [databasename] | findstr ^DROP | mysql -u[username] -p[password] [databasename]
```

## Penggunaan

- Ganti `[username]`, `[password]`, dan `[databasename]` dengan username, password, dan nama database yang akan dihapus.

- Terutama jika Anda menggunakan Windows, pastikan `mysqldump` dan `mysql` telah berada di *variable environment* `PATH`. Atau, jalankan perintah di atas dengan direktori aktif di lokasi di mana `mysql` terinstal.


text:
package com.kii.thing_if.exception;

/**
 * Thrown when an unsupported action is detected.
 */
public class UnsupportedActionException extends ThingIFException {
    public UnsupportedActionException(String actionName, String alias) {
        super(
                String.format("Action[name=%s] of Alias[name=%s] is not supported. " +
                        "Please register an action class for it. ",
                        actionName,
                        alias));
    }
}


text:
package EnsEMBL::Web::Component::Gene::HistoryReport;

use strict;
use warnings;

sub content {

  my $self    = shift;
  my $protein = shift;
  my $hub     = $self->hub;
  my $object  = $self->object;
  my $archive_object;

  if ($protein == 1) {
    my $transcript = $object->transcript;
    my $translation_object;

    if ($transcript->isa('Bio::EnsEMBL::ArchiveStableId') || $transcript->isa('EnsEMBL::Web::Fake') ){
       my $p = $hub->param('p') || $hub->param('protein');

       if (!$p) {
         my $p_archive = shift @{$transcript->get_all_translation_archive_ids};
         $p = $p_archive->stable_id;
       }
       my $db          = $hub->param('db') || 'core';
       my $db_adaptor  = $hub->database($db);
       my $a           = $db_adaptor->get_ArchiveStableIdAdaptor;
       $archive_object = $a->fetch_by_stable_id($p);
    } else {
       $translation_object = $object->translation_object;
       $archive_object     = $translation_object->get_archive_object;
    }
  } else {  # retrieve archive object
    $archive_object = $object->get_archive_object;
  }

  return unless $archive_object;

  my $latest        = $archive_object->get_latest_incarnation;
  my $id            = $latest->stable_id;
  my $version_html  = [];
  my $status;

  my $release_info = 'Release: ' . $latest->release . ($archive_object->is_current ? ' (current)' : '');

  if ($archive_object->is_current) {
    $status = 'Current'; # this *is* the current version of this stable ID
  } elsif ($archive_object->current_version) {
    $status = 'Old version'; # there is a current version of this stable ID
  } else {
    $status = 'Retired (see below for possible successors)'; # this stable ID no longer exists
    my ($spe,$cies,$bp, $__, $parasite_version) = split "_", $archive_object->db_name;
    $bp = uc($bp);
    my $archive_link = join "/", $SiteDefs::SITE_FTP, 'releases', "WBPS$parasite_version", "species", "${spe}_${cies}" , $bp;
    $release_info .= sprintf(' (FTP Link)', $archive_link);
  }

  push @$version_html, $release_info, 'Assembly: ' . $latest->assembly, 'Database: ' . $latest->db_name;
  return $self->new_twocol(['Stable ID', $id], ['Status', $status], ['Latest Version', join('', map sprintf('
%s
', $_), @$version_html)])->render;

}

1;


text:
<?php namespace Malezha\Sentry\Hashing;

use Illuminate\Support\ServiceProvider;

class SentryHashServiceProvider extends ServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = true;

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['sentry-hash'] = $this->app->share(function($app)
		{
			return new SentryHasher($app['sentry.hasher']);
		});
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array('sentry-hash');
	}

}


text:
'use strict';

angular.module('taxes').directive('format', ['$filter', function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;

            ctrl.$formatters.unshift(function (a) {
                return $filter(attrs.format)(ctrl.$modelValue);
            });

            ctrl.$parsers.unshift(function (viewValue) {
                var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
                elem.val($filter(attrs.format)(plainNumber));
                return plainNumber;
            });
        }
    };
}]);

// Taxes controller
angular.module('taxes').controller('TaxesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Taxes', 'TaxTypes',
	function($scope, $stateParams, $location, Authentication, Taxes, TaxTypes ) {
		$scope.authentication = Authentication;

	    $scope.pagingOptions = {
	        pageSizes: [10, 25, 50],
	        pageSize: 25,
	        currentPage: 1,
	        maxSize: 5
	    };
		$scope.filterOptions = {
	        filterText: '',
	        useExternalFilter: false
	    };

	    $scope.totalServerItems = 0;

	    $scope.setPagingData = function(data, page, pageSize){
	        var pagedData = data.slice((page - 1) * pageSize, page * pageSize);

	        $scope.taxes = pagedData;
	        $scope.totalServerItems = data.length;
	        $scope.pagingOptions.pageSize = pageSize;

	        if (!$scope.$$phase) {
	            $scope.$apply();
	        }
	    };

	    $scope.findAsync = function (pageSize, page, searchText) {
	        setTimeout(function () {
	            var data;
	            if (searchText) {
	                var ft = searchText.toLowerCase();

					Taxes.query().$promise.then(function (largeLoad) {

	                    data = largeLoad.filter(function(item) {
	                        return JSON.stringify(item).toLowerCase().indexOf(ft) !== -1;
	                    });

	                    $scope.setPagingData(data,page,pageSize);
					});

	            } else {
	            	Taxes.query().$promise.then(function (largeLoad) {
	            		$scope.setPagingData(largeLoad,page,pageSize);
	            	});
	            }
	        }, 100);
	    };

	    $scope.$watch('pagingOptions', function (newVal, oldVal) {
	        if (newVal !== oldVal &&
	        	(newVal.currentPage !== oldVal.currentPage || newVal.pageSize !== oldVal.pageSize)) {
	          $scope.findAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
	        }
	    }, true);

	    $scope.$watch('filterOptions', function (newVal, oldVal) {
	        if (newVal !== oldVal) {
	          $scope.findAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
	        }
	    }, true);

		// Create new Tax
		$scope.create = function() {
			// Create new Tax object
			var tax = new Taxes ({
				name: $scope.name,
				type: $scope.selectedType._id,
				value: $scope.value,
				description: $scope.description
			});

			// Redirect after save
			tax.$save(function(response) {
				$location.path('taxes/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Tax
		$scope.remove = function( tax ) {
			if ( tax ) { tax.$remove();

				for (var i in $scope.taxes ) {
					if ($scope.taxes [i] === tax ) {
						$scope.taxes.splice(i, 1);
					}
				}
			} else {
				$scope.tax.$remove(function() {
					$location.path('taxes');
				});
			}
		};

		// Update existing Tax
		$scope.update = function() {
			var tax = $scope.tax;
			//tax.type = $scope.selectedType._id;

			tax.$update(function() {
				$location.path('taxes');
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Taxes
		$scope.find = function() {
			$scope.taxes = Taxes.query();
		};

		// Find existing Tax
		$scope.findOne = function() {
			$scope.tax = Taxes.get({
				taxId: $stateParams.taxId
			});

	        $scope.types = TaxTypes.query();
		};

	    $scope.findTypes = function() {
	        $scope.types = TaxTypes.query();
	    };
	}
]);


text:
namespace base {

namespace {

TaskAnnotator::ObserverForTesting* g_task_annotator_observer = nullptr;

// Returns the TLS slot that stores the PendingTask currently in progress on
// each thread. Used to allow creating a breadcrumb of program counters on the
// stack to help identify a task's origin in crashes.
ThreadLocalPointer<PendingTask>* GetTLSForCurrentPendingTask() {
  static NoDestructor<ThreadLocalPointer<PendingTask>> instance;
  return instance.get();
}

// Returns the TLS slot that stores scoped IPC-related data (IPC hash and/or
// IPC interface name). IPC hash or interface name can be known before the
// associated task object is created; store in the TLS so that this data can be
// affixed to the associated task.
ThreadLocalPointer<TaskAnnotator::ScopedSetIpcHash>*
GetTLSForCurrentScopedIpcHash() {
  static NoDestructor<ThreadLocalPointer<TaskAnnotator::ScopedSetIpcHash>>
      instance;
  return instance.get();
}

}  // namespace

const PendingTask* TaskAnnotator::CurrentTaskForThread() {
  return GetTLSForCurrentPendingTask()->Get();
}

TaskAnnotator::TaskAnnotator() = default;
TaskAnnotator::~TaskAnnotator() = default;

void TaskAnnotator::WillQueueTask(perfetto::StaticString trace_event_name,
                                  PendingTask* pending_task,
                                  const char* task_queue_name) {
  DCHECK(pending_task);
  DCHECK(task_queue_name);
  TRACE_EVENT_INSTANT(
      "toplevel.flow", trace_event_name,
      perfetto::Flow::ProcessScoped(GetTaskTraceID(*pending_task)));

  DCHECK(!pending_task->task_backtrace[0])
      << "Task backtrace was already set, task posted twice??";
  if (pending_task->task_backtrace[0])
    return;

  DCHECK(!pending_task->ipc_interface_name);
  DCHECK(!pending_task->ipc_hash);
  auto* current_ipc_hash = GetTLSForCurrentScopedIpcHash()->Get();
  if (current_ipc_hash) {
    pending_task->ipc_interface_name = current_ipc_hash->GetIpcInterfaceName();
    pending_task->ipc_hash = current_ipc_hash->GetIpcHash();
  }

  const auto* parent_task = CurrentTaskForThread();
  if (!parent_task)
    return;

  pending_task->task_backtrace[0] = parent_task->posted_from.program_counter();
  std::copy(parent_task->task_backtrace.begin(),
            parent_task->task_backtrace.end() - 1,
            pending_task->task_backtrace.begin() + 1);
  pending_task->task_backtrace_overflow =
      parent_task->task_backtrace_overflow ||
      parent_task->task_backtrace.back() != nullptr;
}

void TaskAnnotator::RunTaskImpl(PendingTask& pending_task) {
  debug::ScopedTaskRunActivity task_activity(pending_task);

  TRACE_HEAP_PROFILER_API_SCOPED_TASK_EXECUTION(
      pending_task.posted_from.file_name());

  // Before running the task, store the IPC context and the task backtrace with
  // the chain of PostTasks that resulted in this call and deliberately alias it
  // to ensure it is on the stack if the task crashes. Be careful not to assume
  // that the variable itself will have the expected value when displayed by the
  // optimizer in an optimized build. Look at a memory dump of the stack.
  static constexpr int kStackTaskTraceSnapshotSize =
      PendingTask::kTaskBacktraceLength + 4;
  std::array<const void*, kStackTaskTraceSnapshotSize> task_backtrace;

  // Store a marker to locate |task_backtrace| content easily on a memory
  // dump. The layout is as follows:
  //
  // +------------ +----+---------+-----+-----------+----------+-------------+
  // | Head Marker | PC | frame 0 | ... | frame N-1 | IPC hash | Tail Marker |
  // +------------ +----+---------+-----+-----------+----------+-------------+
  //
  // Markers glossary (compliments of wez):
  //      cool code,do it dude!
  //   0x c001 c0de d0 17 d00d
  //      o dude,i did it biig
  //   0x 0 d00d 1 d1d 17 8119
  task_backtrace.front() = reinterpret_cast<void*>(0xc001c0ded017d00d);
  task_backtrace.back() = reinterpret_cast<void*>(0x0d00d1d1d178119);

  task_backtrace[1] = pending_task.posted_from.program_counter();
  ranges::copy(pending_task.task_backtrace, task_backtrace.begin() + 2);
  task_backtrace[kStackTaskTraceSnapshotSize - 2] =
      reinterpret_cast<void*>(pending_task.ipc_hash);
  debug::Alias(&task_backtrace);

  auto* tls = GetTLSForCurrentPendingTask();
  auto* previous_pending_task = tls->Get();
  tls->Set(&pending_task);

  if (g_task_annotator_observer)
    g_task_annotator_observer->BeforeRunTask(&pending_task);
  std::move(pending_task.task).Run();

  tls->Set(previous_pending_task);

  // Stomp the markers. Otherwise they can stick around on the unused parts of
  // stack and cause |task_backtrace| to be associated with an unrelated stack
  // sample on this thread later in the event of a crash. Alias once again after
  // these writes to make sure the compiler doesn't optimize them out (unused
  // writes to a local variable).
  task_backtrace.front() = nullptr;
  task_backtrace.back() = nullptr;
  debug::Alias(&task_backtrace);
}

uint64_t TaskAnnotator::GetTaskTraceID(const PendingTask& task) const {
  return (static_cast<uint64_t>(task.sequence_num) << 32) |
         ((static_cast<uint64_t>(reinterpret_cast<intptr_t>(this)) << 32) >>
          32);
}

// static
void TaskAnnotator::RegisterObserverForTesting(ObserverForTesting* observer) {
  DCHECK(!g_task_annotator_observer);
  g_task_annotator_observer = observer;
}

// static
void TaskAnnotator::ClearObserverForTesting() {
  g_task_annotator_observer = nullptr;
}

#if BUILDFLAG(ENABLE_BASE_TRACING)
// TRACE_EVENT argument helper, writing the task location data into
// EventContext.
void TaskAnnotator::EmitTaskLocation(perfetto::EventContext& ctx,
                                     const PendingTask& task) const {
  ctx.event()->set_task_execution()->set_posted_from_iid(
      base::trace_event::InternedSourceLocation::Get(
          &ctx, base::trace_event::TraceSourceLocation(task.posted_from)));
}

// TRACE_EVENT argument helper, writing the incoming task flow information
// into EventContext if toplevel.flow category is enabled.
void TaskAnnotator::MaybeEmitIncomingTaskFlow(perfetto::EventContext& ctx,
                                              const PendingTask& task) const {
  static const uint8_t* flow_enabled =
      TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED("toplevel.flow");
  if (!*flow_enabled)
    return;

  perfetto::TerminatingFlow::ProcessScoped(GetTaskTraceID(task))(ctx);
}

void TaskAnnotator::MaybeEmitIPCHashAndDelay(perfetto::EventContext& ctx,
                                             const PendingTask& task) const {
  static const uint8_t* toplevel_ipc_enabled =
      TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
          TRACE_DISABLED_BY_DEFAULT("toplevel.ipc"));
  if (!*toplevel_ipc_enabled)
    return;

  auto* event = ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>();
  auto* annotator = event->set_chrome_task_annotator();
  annotator->set_ipc_hash(task.ipc_hash);
  if (!task.delayed_run_time.is_null()) {
    annotator->set_task_delay_us(
        (task.delayed_run_time - task.queue_time).InMicroseconds());
  }
}
#endif  //  BUILDFLAG(ENABLE_BASE_TRACING)

TaskAnnotator::ScopedSetIpcHash::ScopedSetIpcHash(uint32_t ipc_hash)
    : ScopedSetIpcHash(ipc_hash, nullptr) {}

TaskAnnotator::ScopedSetIpcHash::ScopedSetIpcHash(
    const char* ipc_interface_name)
    : ScopedSetIpcHash(0, ipc_interface_name) {}

TaskAnnotator::ScopedSetIpcHash::ScopedSetIpcHash(
    uint32_t ipc_hash,
    const char* ipc_interface_name) {
  TRACE_EVENT_BEGIN(
      "base", "ScopedSetIpcHash", [&](perfetto::EventContext ctx) {
        auto* mojo_event = ctx.event()->set_chrome_mojo_event_info();
        if (ipc_hash > 0)
          mojo_event->set_ipc_hash(ipc_hash);
        if (ipc_interface_name != nullptr)
          mojo_event->set_mojo_interface_tag(ipc_interface_name);
      });
  auto* tls_ipc_hash = GetTLSForCurrentScopedIpcHash();
  auto* current_ipc_hash = tls_ipc_hash->Get();
  old_scoped_ipc_hash_ = current_ipc_hash;
  ipc_hash_ = ipc_hash;
  ipc_interface_name_ = ipc_interface_name;
  tls_ipc_hash->Set(this);
}

// Static
uint32_t TaskAnnotator::ScopedSetIpcHash::MD5HashMetricName(
    base::StringPiece name) {
  base::MD5Digest digest;
  base::MD5Sum(name.data(), name.size(), &digest);
  uint32_t value;
  DCHECK_GE(sizeof(digest.a), sizeof(value));
  memcpy(&value, digest.a, sizeof(value));
  return base::NetToHost32(value);
}

TaskAnnotator::ScopedSetIpcHash::~ScopedSetIpcHash() {
  auto* tls_ipc_hash = GetTLSForCurrentScopedIpcHash();
  DCHECK_EQ(this, tls_ipc_hash->Get());
  tls_ipc_hash->Set(old_scoped_ipc_hash_.get());
  TRACE_EVENT_END("base");
}

}  // namespace base


text: - [ ] Configure mitogen to run faster commands on playbooks according to (document on tiagopr.nl also): <https://mitogen.readthedocs.io/en/latest/ansible.html>


text:
Environment Management for ExpressionEngine 2.

## Installation

More to come later.

## Issues

Please log any issues or problems here: <https://github.com/themusicman/Envee/issues>


text:
'''
    The purpose of this script is to read a file of questions and store
    it to a JSON format. It was made to suit some NTNU exam that was written
    this way, so that's why it is the way it is.

    The script is built using Python 2.7.

    USAGE:
        Put two .txt files in the same folder, one named <title>.txt and one
        named <title>_solution.txt. Make sure they're in the format given below.

        Run script with python quiz_interpreter.py <title>

    FORMAT <title>.txt
        Everything you write before a line defining the first question
        is ignored. So here you could have an introthing or whatever.

        Below are two questions with alternatives. You can just keep going
        on and on repeating questions.

        Oppgave 01:
        This is a multiline question. Questions can be on one line or more,
        and can be followed by blank lines if you wish. Blank lines can be
        put anywhere, really.

        a) This is an option. Options should start with a letter ('a' and up),
        followed by an end parenthesis and a space. They can also be on
        multiple lines. If I want to, I can add a picture by writing an
        html tag for that: <img src='img/example.jpg' />
        b) Another alternative.
        c) A third alternative.
        d) A forth alternative.

        Oppgave 2:
        Another question. Note that we didn't use 0 in front of the number
        2 this time.
        a) An alternative.
        b) Another alternative.
        c) A third alternative.
        d) A forth alternative.

    FORMAT <title>_solution.txt
        Exam for TIØ4258 fall 2009
        1) a, The number defines the questions it answers, and the letter
        defines the correct alternative. The Format "0) a," is mandatory,
        but the answer can go over multiple lines and, contain more commas
        (or parenthesis)
        2) b, A new answer is defined by a line starting the same way
        3) c, Explainations are not mandatory
        4) d,
        5) c,

'''

class Question:
    """
    A question, initiated with question (string).
    """
    def __init__(self, question):
        self.question = question
        self.alternatives = []
        self.solution = -1  # Int for which alternativ is correct
        self.explaination = "No explaination given"
        self.qnum = 0

    def append_line_to_question(self, more_question):
        '''
        Appends more text to the existing question.
        '''
        self.question += " " + more_question

    def add_alternative(self, alternative):
        '''
        Adds an alternative to the question
        '''
        self.alternatives.append(alternative)

    def append_text_to_last_alternative(self, text):
        '''
        Appends text to the most recently added alternative
        '''
        self.alternatives[-1] += " " + text

    def add_explaination(self, solution, explaination):
        '''
        Sets correct solution (int) and adds an explaination.
        '''
        self.solution = solution
        self.explaination = explaination

    def append_explaination(self, explaination):
        '''
        Appends text to the existing explaination
        '''
        self.explaination += " " + explaination

    def setQuestionNumber(self, number):
        '''
        Sets the question number (int)
        '''
        self.qnum = number

def readQuestions(path):
    '''
    Opens and reads a filepath. Returns an array of Question.
    '''
    lines = read_path_as_array(path)
    questions = {}
    processedQLine = 0
    qnum = 0
    for line in lines:
        # Removes spaces at start an end of line
        line = line.strip()

        # Test if line is of an ignoreable type
        if ignorable_line(line):
            print("IGNORED: " + line)
            continue

        # Check if the line defines a new task
        if line_defines_new_task(line):
            processedQLine = 1
            qnum = get_question_number(line)

        # If we're not 'ready' for a question or an alternativ
        elif processedQLine <= 0:
            print("IGNORED: " + line)
            continue

        # If the previous line defined the task
        elif processedQLine == 1:
            questions[qnum] = Question(line)
            questions[qnum].setQuestionNumber(qnum)
            processedQLine += 1

        # If we're somewhere within a task
        elif processedQLine > 1:
            if line_defines_new_alternative(line):
                # Skips the first three chars, as they're "x) "
                questions[qnum].add_alternative(line[3:])

            # If no alternatives has been added, we're still working on Q
            elif not questions[qnum].alternatives:
                questions[qnum].append_line_to_question(line)

            # If alternatives has been added, we're still working on alternative
            else:
                if line_defines_end_of_tasks(line):
                    print("QUIT AT " + line)
                    return questions

                questions[qnum].append_text_to_last_alternative(line)
    return questions

def applySolutions(questions, solution_path):
    '''
    Applies a solution to existing questions.
    Takes in:
    * questions: a list of Question.
    * solution_path: path to solution file
    '''

    print("applySolutions " + solution_path)
    lines = read_path_as_array(solution_path)

    qnum = 0
    for line in lines:
        line = line.strip()
        if not line_defines_answer(line):
            if line_defines_end_of_tasks(line):
                print("QUIT AT " + line)
                return questions
            elif qnum > 0 and qnum <= 50: # We're inside questions
                questions[qnum].append_explaination(line)
            continue

        qnum, solution = extract_qnum_and_solution(line)
        explaination = extract_explaination(line)

        try:
            questions[qnum].add_explaination(solution, explaination)
        except:
            print("Couldn't add answer to " + str(qnum))
    return questions

def load(dictionary, title):
    '''
    Loads questions and answers into a dictionary.
    '''
    dictionary[title] = applySolutions(
        readQuestions(title + '.txt'), title + '_solution.txt')

def ignorable_line(line):
    '''
    Returns whether or not the line should be ignored.
    '''
    return (
        len(line) < 2
        or (line.lower().startswith('side ') and "av" in line)
        or (line.lower().startswith("oppgaver fra") and ":" in line)
        )

def line_defines_new_task(line):
    '''
    Returns whether or not a line defines the start of a new task
    '''
    return line.lower().startswith('oppgave ') and line[8:10].isdigit()

def get_question_number(line):
    '''
    Returns the number of the question.
    '''
    try:
        return int(line[8:10])
    except:
        return 0

def line_defines_new_alternative(line):
    '''
    Returns whether or not the line defines a new alternative
    '''
    try:
        return line[1] == ')'
    except:
        return False

def line_defines_end_of_tasks(line):
    '''
    Whether or not the line defines end of tasks
    '''
    return (
        (line.lower().startswith('karakter') and ":" in line)
        or line.lower().startswith("karaktergiving")
        )

def read_path_as_array(path):
    '''
    Opens file and returns an array of string. One line = one string.
    '''
    f = open(path, 'r')
    return f.read().split('\n')

def convert_letter_to_num(letter):
    '''
    converts letter to int (a --> 0)
    '''
    return ord(letter.lower())-97

def line_defines_answer(line):
    '''
    Whether or not the line defines an answer.
    '''
    temp = line.split(')', 1)
    return temp[0].isdigit() and len(temp) == 2 and len(temp[1].split(',')[0]) == 2

def extract_qnum_and_solution(line):
    '''
    Returns tuple with question number and solution as int (a -> 0.. etc)
    '''
    temp = line.split(')', 1)
    qnum = int(temp[0])
    solution = temp[1].split(',', 1)[0].strip().lower()
    solution = convert_letter_to_num(solution)
    return qnum, solution

def extract_explaination(line):
    '''
    Returns explaination from an answerline
    '''
    temp = line.split(')', 1)
    if len(temp[1].split(',', 1)) == 2:
        return temp[1].split(',', 1)[1].strip()
    else:
        return "No explaination given"

if __name__ == "__main__":
    import sys

    exams = {}
    args = sys.argv[1:]
    if not args:
        print("Usage: Run as 'python quiz_interpreter.py <title_of_quiz_file>'")
        print("Output will be saved as data.js")
        sys.exit()

    for arg in args:
        print arg
        load(exams, arg)

    print('Starting packing')
    f = open('data.js', 'w')
    f.write('var exams = {')
    for year in exams:
        questions = exams[year]
        f.write('"' + year + '"' + ' : [\n')
        for key in questions:
            f.write('{\n')
            f.write('   "question":"' + questions[key].question + '",\n')
            f.write('   "solution":"' + str(questions[key].solution) + '",\n')
            f.write('   "explaination":"' + questions[key].explaination + '",\n')
            f.write('   "number":"' + str(questions[key].qnum) + '",\n')
            f.write('   "alternatives": [\n')
            for i in range(len(questions[key].alternatives)):
                f.write('      "' + questions[key].alternatives[i] + '"')
                if i+1 < len(questions[key].alternatives):
                    f.write(',')
                f.write('\n')
            f.write('   ]')
            f.write('},\n\n')
        f.write('],\n\n')
    f.write('};')


text:
package capstone.ui;

import com.googlecode.lanterna.input.Key;

/**
 * A superior lanterna-Key class that adds some factory and utility
 * functions as well as a proper equals() implementation.
 */
public class InputKey extends Key
{
    /**
     *
     * Deserializes an InputKey, i.e. returns an
     * InputKey for its string representation.
     *
     * @param serialized The string representation of the InputKey.
     *
     * @return The resulting InputKey.
     */
    public static InputKey fromString(String serialized)
    {
        assert(! serialized.isEmpty());

        if (serialized.length() == 1)
        {
            return new InputKey(serialized.charAt(0));
        }

        else return new InputKey(InputKey.Kind.valueOf(serialized));
    }

    /**
     *
     * Constructs an InputKey from a lanterna-Key.
     *
     * This cannot be a constructor because you cannot do the
     * logic below before calling the lanterna-Key's constructor,
     * i.e. you couldn't perform the checks below before calling
     * super(...).
     *
     * @param key The lanterna-Key.
     *
     * @return The corresponding InputKey.
     */
    public static InputKey fromKey(Key key)
    {
        if (key.getKind() == Kind.NormalKey)
        {
            return new InputKey(key.getCharacter());
        }

        else return new InputKey(key.getKind());
    }

    /**
     *
     * Returns a copy of the InputKey.
     *
     * Cannot be a copy-constructor because of the super() problem
     * (can't do anything before calling super())
     *
     * @param key The InputKey to copy.
     *
     * @return A copy of the InputKey.
     */
    public static InputKey copy(InputKey key)
    {
        return fromKey(key);
    }

    /**
     *
     * Constructs an InputKey from a character.
     *
     * @param character The character to construct this InputKey with.
     */
    public InputKey(char character)
    {
        super(character);
    }

    /**
     *
     * Constructs an InputKey from an InputKey.Kind.
     *
     * @param kind The InputKey.Kind to construct this InputKey with.
     */
    public InputKey(InputKey.Kind kind)
    {
        super(kind);
    }

    /**
     *
     * Checks if this InputKey is equal to another object.
     *
     * @param object The object to check equality for.
     *
     * @return True if the object is an InputKey and
     *         has the same character or kind.
     */
    @Override public boolean equals(Object object)
    {
        if (object == null) return false;

        if (! (object instanceof InputKey)) return false;

        if (object == this) return true;

        InputKey other = (InputKey) object;

        if (! this.getKind().equals(other.getKind())) return false;

        if (this.getKind().equals(Kind.NormalKey))
        {
            return this.getCharacter() == other.getCharacter();
        }

        else return true;
    }

    /**
     * @return A string representation of the InputKey.
     */
    public String toString()
    {
        Kind kind = super.getKind();

        if (kind == Kind.NormalKey)
        {
            // Just need to keep everything lower-case!
            return Character.toString(super.getCharacter()).toLowerCase();
        }

        else return kind.toString();
    }
}


text:
module Devise
  # Add custom G5 controllers to default routing options
  class Mapping
    alias original_initialize initialize

    def initialize(name, options)
      setup_default_g5_controllers(options)
      original_initialize(name, options)
    end

    private

    def setup_default_g5_controllers(options)
      options[:controllers] ||= {}
      options[:controllers].reverse_merge!(
        registrations: 'devise_g5_authenticatable/registrations',
        sessions: 'devise_g5_authenticatable/sessions'
      )
      options
    end
  end
end

module ActionDispatch
  module Routing
    # Add G5 omniauth callbacks to set of routes
    class Mapper
      protected

      def devise_session(mapping, controllers)
        setup_omniauth_path_prefix(mapping)
        build_session_routes(mapping, controllers)
        build_g5_omniauth_routes(mapping, controllers)
      end

      def setup_omniauth_path_prefix(mapping)
        return if ::OmniAuth.config.path_prefix.present?
        path_prefix = Devise.omniauth_path_prefix ||
                      "/#{mapping.fullpath}/auth".squeeze('/')
        set_omniauth_path_prefix!(path_prefix)
      end

      def build_session_routes(mapping, controllers)
        resource(:session, only: [],
                           controller: controllers[:sessions],
                           path: '') do
          get   :new,     path: mapping.path_names[:sign_in],
                          as: :new
          post  :create,  path: mapping.path_names[:sign_in]
          match :destroy, path: mapping.path_names[:sign_out],
                          as: :destroy,
                          via: mapping.sign_out_via
        end
      end

      def build_g5_omniauth_routes(_mapping, controllers)
        match 'auth/g5', controller: controllers[:sessions],
                         action: 'omniauth_passthru',
                         as: :g5_authorize,
                         via: %i[get post]

        match 'auth/g5/callback', controller: controllers[:sessions],
                                  action: 'create',
                                  as: :g5_callback,
                                  via: %i[get post]
      end
    end
  end
end


text:
using System;
using System.Linq;
using Microsoft.Azure.Management.SiteRecovery.Models;

namespace Microsoft.Azure.Management.SiteRecovery.Models
{
    /// <summary>
    /// The definition of a Protection profile object.
    /// </summary>
    public partial class CreateProtectionProfileInput
    {
        private string _name;

        /// <summary>
        /// Optional. the Name of Profile.
        /// </summary>
        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        }

        private string _replicationProvider;

        /// <summary>
        /// Optional. the replication provider.
        /// </summary>
        public string ReplicationProvider
        {
            get { return this._replicationProvider; }
            set { this._replicationProvider = value; }
        }

        private ProtectionProfileProviderSpecificInput _replicationProviderSettings;

        /// <summary>
        /// Optional. the replication provider settings.
        /// </summary>
        public ProtectionProfileProviderSpecificInput ReplicationProviderSettings
        {
            get { return this._replicationProviderSettings; }
            set { this._replicationProviderSettings = value; }
        }

        /// <summary>
        /// Initializes a new instance of the CreateProtectionProfileInput
        /// class.
        /// </summary>
        public CreateProtectionProfileInput()
        {
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@android:color/white"
    android:background="@color/gsensor_mode_list_background"
    android:textSize="@dimen/gsensor_mode_list_text_size"
    android:padding="@dimen/gsensor_mode_list_padding"
/>


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

title: Notification
---

Notification
============

> Visual, audible, and tactile device notifications.

Methods
-------

- [notification.alert](notification.alert.html)
- [notification.confirm](notification.confirm.html)
- [notification.beep](notification.beep.html)
- [notification.vibrate](notification.vibrate.html)

Permissions
-----------

### Android

#### app/res/xml/config.xml

    <plugin name="Notification" value="org.apache.cordova.Notification"/>

#### app/AndroidManifest.xml

    <uses-permission android:name="android.permission.VIBRATE" />

### Bada

#### manifest.xml

    <Privilege>
        <Name>SYSTEM_SERVICE</Name>
    </Privilege>

### BlackBerry WebWorks

#### www/plugins.xml

    <plugin name="Notification" value="org.apache.cordova.notification.Notification" />

#### www/config.xml

    <feature id="blackberry.ui.dialog" />

### iOS

#### config.xml

    <plugin name="Notification" value="CDVNotification" />

### webOS

    No permissions are required.

### Windows Phone

    No permissions are required.

### Tizen

    No permissions are required.


text:
{-# LANGUAGE CPP, DeriveDataTypeable, MultiParamTypeClasses, FlexibleInstances, BangPatterns #-}

-- |
-- Module      : Data.Vector.Mutable
-- Copyright   : (c) Roman Leshchinskiy 2008-2010
-- License     : BSD-style
--
-- Maintainer  : Roman Leshchinskiy <rl@cse.unsw.edu.au>
-- Stability   : experimental
-- Portability : non-portable
--
-- Mutable boxed vectors.
--

module Data.Vector.Mutable (
  -- * Mutable boxed vectors
  MVector(..), IOVector, STVector,

  -- * Accessors

  -- ** Length information
  length, null,

  -- ** Extracting subvectors
  slice, init, tail, take, drop, splitAt,
  unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop,

  -- ** Overlapping
  overlaps,

  -- * Construction

  -- ** Initialisation
  new, unsafeNew, replicate, replicateM, clone,

  -- ** Growing
  grow, unsafeGrow,

  -- ** Restricting memory usage
  clear,

  -- * Accessing individual elements
  read, write, swap,
  unsafeRead, unsafeWrite, unsafeSwap,

  -- * Modifying vectors

  -- ** Filling and copying
  set, copy, move, unsafeCopy, unsafeMove
) where

import           Control.Monad (when)
import qualified Data.Vector.Generic.Mutable as G
import           Data.Primitive.Array
import           Control.Monad.Primitive

import Control.DeepSeq ( NFData, rnf )

import Prelude hiding ( length, null, replicate, reverse, map, read,
                        take, drop, splitAt, init, tail )

import Data.Typeable ( Typeable )

#include "vector.h"

-- | Mutable boxed vectors keyed on the monad they live in ('IO' or @'ST' s@).
data MVector s a = MVector {-# UNPACK #-} !Int
                           {-# UNPACK #-} !Int
                           {-# UNPACK #-} !(MutableArray s a)
        deriving ( Typeable )

type IOVector = MVector RealWorld
type STVector s = MVector s

-- NOTE: This seems unsafe, see http://trac.haskell.org/vector/ticket/54
{-
instance NFData a => NFData (MVector s a) where
    rnf (MVector i n arr) = unsafeInlineST $ force i
        where
          force !ix | ix < n    = do x <- readArray arr ix
                                     rnf x `seq` force (ix+1)
                    | otherwise = return ()
-}

instance G.MVector MVector a where
  {-# INLINE basicLength #-}
  basicLength (MVector _ n _) = n

  {-# INLINE basicUnsafeSlice #-}
  basicUnsafeSlice j m (MVector i n arr) = MVector (i+j) m arr

  {-# INLINE basicOverlaps #-}
  basicOverlaps (MVector i m arr1) (MVector j n arr2)
    = sameMutableArray arr1 arr2
      && (between i j (j+n) || between j i (i+m))
    where
      between x y z = x >= y && x < z

  {-# INLINE basicUnsafeNew #-}
  basicUnsafeNew n
    = do
        arr <- newArray n uninitialised
        return (MVector 0 n arr)

  {-# INLINE basicUnsafeReplicate #-}
  basicUnsafeReplicate n x
    = do
        arr <- newArray n x
        return (MVector 0 n arr)

  {-# INLINE basicUnsafeRead #-}
  basicUnsafeRead (MVector i n arr) j = readArray arr (i+j)

  {-# INLINE basicUnsafeWrite #-}
  basicUnsafeWrite (MVector i n arr) j x = writeArray arr (i+j) x

  {-# INLINE basicUnsafeCopy #-}
  basicUnsafeCopy (MVector i n dst) (MVector j _ src)
    = copyMutableArray dst i src j n

  basicUnsafeMove dst@(MVector iDst n arrDst) src@(MVector iSrc _ arrSrc)
    = case n of
        0 -> return ()
        1 -> readArray arrSrc iSrc >>= writeArray arrDst iDst
        2 -> do
               x <- readArray arrSrc iSrc
               y <- readArray arrSrc (iSrc + 1)
               writeArray arrDst iDst x
               writeArray arrDst (iDst + 1) y
        _
          | overlaps dst src
             -> case compare iDst iSrc of
                  LT -> moveBackwards arrDst iDst iSrc n
                  EQ -> return ()
                  GT | (iDst - iSrc) * 2 < n
                        -> moveForwardsLargeOverlap arrDst iDst iSrc n
                     | otherwise
                        -> moveForwardsSmallOverlap arrDst iDst iSrc n
          | otherwise -> G.basicUnsafeCopy dst src

  {-# INLINE basicClear #-}
  basicClear v = G.set v uninitialised

{-# INLINE moveBackwards #-}
moveBackwards :: PrimMonad m => MutableArray (PrimState m) a -> Int -> Int -> Int -> m ()
moveBackwards !arr !dstOff !srcOff !len =
  INTERNAL_CHECK(check) "moveBackwards" "not a backwards move" (dstOff < srcOff)
  $ loopM len $ \ i -> readArray arr (srcOff + i) >>= writeArray arr (dstOff + i)

{-# INLINE moveForwardsSmallOverlap #-}
-- Performs a move when dstOff > srcOff, optimized for when the overlap of the intervals is small.
moveForwardsSmallOverlap :: PrimMonad m => MutableArray (PrimState m) a -> Int -> Int -> Int -> m ()
moveForwardsSmallOverlap !arr !dstOff !srcOff !len =
  INTERNAL_CHECK(check) "moveForwardsSmallOverlap" "not a forward move" (dstOff > srcOff)
  $ do
      tmp <- newArray overlap uninitialised
      loopM overlap $ \ i -> readArray arr (dstOff + i) >>= writeArray tmp i
      loopM nonOverlap $ \ i -> readArray arr (srcOff + i) >>= writeArray arr (dstOff + i)
      loopM overlap $ \ i -> readArray tmp i >>= writeArray arr (dstOff + nonOverlap + i)
  where nonOverlap = dstOff - srcOff; overlap = len - nonOverlap

-- Performs a move when dstOff > srcOff, optimized for when the overlap of the intervals is large.
moveForwardsLargeOverlap :: PrimMonad m => MutableArray (PrimState m) a -> Int -> Int -> Int -> m ()
moveForwardsLargeOverlap !arr !dstOff !srcOff !len =
  INTERNAL_CHECK(check) "moveForwardsLargeOverlap" "not a forward move" (dstOff > srcOff)
  $ do
      queue <- newArray nonOverlap uninitialised
      loopM nonOverlap $ \ i -> readArray arr (srcOff + i) >>= writeArray queue i
      let mov !i !qTop = when (i < dstOff + len) $ do
            x <- readArray arr i
            y <- readArray queue qTop
            writeArray arr i y
            writeArray queue qTop x
            mov (i+1) (if qTop + 1 >= nonOverlap then 0 else qTop + 1)
      mov dstOff 0
  where nonOverlap = dstOff - srcOff

{-# INLINE loopM #-}
loopM :: Monad m => Int -> (Int -> m a) -> m ()
loopM !n k = let
  go i = when (i < n) (k i >> go (i+1))
  in go 0

uninitialised :: a
uninitialised = error "Data.Vector.Mutable: uninitialised element"

-- Length information
-- ------------------

-- | Length of the mutable vector.
length :: MVector s a -> Int
{-# INLINE length #-}
length = G.length

-- | Check whether the vector is empty
null :: MVector s a -> Bool
{-# INLINE null #-}
null = G.null

-- Extracting subvectors
-- ---------------------

-- | Yield a part of the mutable vector without copying it.
slice :: Int -> Int -> MVector s a -> MVector s a
{-# INLINE slice #-}
slice = G.slice

take :: Int -> MVector s a -> MVector s a
{-# INLINE take #-}
take = G.take

drop :: Int -> MVector s a -> MVector s a
{-# INLINE drop #-}
drop = G.drop

{-# INLINE splitAt #-}
splitAt :: Int -> MVector s a -> (MVector s a, MVector s a)
splitAt = G.splitAt

init :: MVector s a -> MVector s a
{-# INLINE init #-}
init = G.init

tail :: MVector s a -> MVector s a
{-# INLINE tail #-}
tail = G.tail

-- | Yield a part of the mutable vector without copying it. No bounds checks
-- are performed.
unsafeSlice :: Int  -- ^ starting index
            -> Int  -- ^ length of the slice
            -> MVector s a
            -> MVector s a
{-# INLINE unsafeSlice #-}
unsafeSlice = G.unsafeSlice

unsafeTake :: Int -> MVector s a -> MVector s a
{-# INLINE unsafeTake #-}
unsafeTake = G.unsafeTake

unsafeDrop :: Int -> MVector s a -> MVector s a
{-# INLINE unsafeDrop #-}
unsafeDrop = G.unsafeDrop

unsafeInit :: MVector s a -> MVector s a
{-# INLINE unsafeInit #-}
unsafeInit = G.unsafeInit

unsafeTail :: MVector s a -> MVector s a
{-# INLINE unsafeTail #-}
unsafeTail = G.unsafeTail

-- Overlapping
-- -----------

-- | Check whether two vectors overlap.
overlaps :: MVector s a -> MVector s a -> Bool
{-# INLINE overlaps #-}
overlaps = G.overlaps

-- Initialisation
-- --------------

-- | Create a mutable vector of the given length.
new :: PrimMonad m => Int -> m (MVector (PrimState m) a)
{-# INLINE new #-}
new = G.new

-- | Create a mutable vector of the given length. The length is not checked.
unsafeNew :: PrimMonad m => Int -> m (MVector (PrimState m) a)
{-# INLINE unsafeNew #-}
unsafeNew = G.unsafeNew

-- | Create a mutable vector of the given length (0 if the length is negative)
-- and fill it with an initial value.
replicate :: PrimMonad m => Int -> a -> m (MVector (PrimState m) a)
{-# INLINE replicate #-}
replicate = G.replicate

-- | Create a mutable vector of the given length (0 if the length is negative)
-- and fill it with values produced by repeatedly executing the monadic action.
replicateM :: PrimMonad m => Int -> m a -> m (MVector (PrimState m) a)
{-# INLINE replicateM #-}
replicateM = G.replicateM

-- | Create a copy of a mutable vector.
clone :: PrimMonad m => MVector (PrimState m) a -> m (MVector (PrimState m) a)
{-# INLINE clone #-}
clone = G.clone

-- Growing
-- -------

-- | Grow a vector by the given number of elements. The number must be
-- positive.
grow :: PrimMonad m
              => MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a)
{-# INLINE grow #-}
grow = G.grow

-- | Grow a vector by the given number of elements. The number must be
-- positive but this is not checked.
unsafeGrow :: PrimMonad m
               => MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a)
{-# INLINE unsafeGrow #-}
unsafeGrow = G.unsafeGrow

-- Restricting memory usage
-- ------------------------

-- | Reset all elements of the vector to some undefined value, clearing all
-- references to external objects. This is usually a noop for unboxed vectors.
clear :: PrimMonad m => MVector (PrimState m) a -> m ()
{-# INLINE clear #-}
clear = G.clear

-- Accessing individual elements
-- -----------------------------

-- | Yield the element at the given position.
read :: PrimMonad m => MVector (PrimState m) a -> Int -> m a
{-# INLINE read #-}
read = G.read

-- | Replace the element at the given position.
write :: PrimMonad m => MVector (PrimState m) a -> Int -> a -> m ()
{-# INLINE write #-}
write = G.write

-- | Swap the elements at the given positions.
swap :: PrimMonad m => MVector (PrimState m) a -> Int -> Int -> m ()
{-# INLINE swap #-}
swap = G.swap

-- | Yield the element at the given position. No bounds checks are performed.
unsafeRead :: PrimMonad m => MVector (PrimState m) a -> Int -> m a
{-# INLINE unsafeRead #-}
unsafeRead = G.unsafeRead

-- | Replace the element at the given position. No bounds checks are performed.
unsafeWrite :: PrimMonad m => MVector (PrimState m) a -> Int -> a -> m ()
{-# INLINE unsafeWrite #-}
unsafeWrite = G.unsafeWrite

-- | Swap the elements at the given positions. No bounds checks are performed.
unsafeSwap :: PrimMonad m => MVector (PrimState m) a -> Int -> Int -> m ()
{-# INLINE unsafeSwap #-}
unsafeSwap = G.unsafeSwap

-- Filling and copying
-- -------------------

-- | Set all elements of the vector to the given value.
set :: PrimMonad m => MVector (PrimState m) a -> a -> m ()
{-# INLINE set #-}
set = G.set

-- | Copy a vector. The two vectors must have the same length and may not
-- overlap.
copy :: PrimMonad m
                 => MVector (PrimState m) a -> MVector (PrimState m) a -> m ()
{-# INLINE copy #-}
copy = G.copy

-- | Copy a vector. The two vectors must have the same length and may not
-- overlap. This is not checked.
unsafeCopy :: PrimMonad m => MVector (PrimState m) a   -- ^ target
                          -> MVector (PrimState m) a   -- ^ source
                          -> m ()
{-# INLINE unsafeCopy #-}
unsafeCopy = G.unsafeCopy

-- | Move the contents of a vector. The two vectors must have the same
-- length.
--
-- If the vectors do not overlap, then this is equivalent to 'copy'.
-- Otherwise, the copying is performed as if the source vector were
-- copied to a temporary vector and then the temporary vector was copied
-- to the target vector.
move :: PrimMonad m
                 => MVector (PrimState m) a -> MVector (PrimState m) a -> m ()
{-# INLINE move #-}
move = G.move

-- | Move the contents of a vector. The two vectors must have the same
-- length, but this is not checked.
--
-- If the vectors do not overlap, then this is equivalent to 'unsafeCopy'.
-- Otherwise, the copying is performed as if the source vector were
-- copied to a temporary vector and then the temporary vector was copied
-- to the target vector.
unsafeMove :: PrimMonad m => MVector (PrimState m) a   -- ^ target
                          -> MVector (PrimState m) a   -- ^ source
                          -> m ()
{-# INLINE unsafeMove #-}
unsafeMove = G.unsafeMove


text:
require 'delegate'

require_relative 'detectable'
require_relative 'renderable'

module MugMultiples
  class Image < SimpleDelegator
    include MugMultiples::Detectable
    include MugMultiples::Renderable

    attr_reader :filename
    def initialize(fthing)
      if fthing.kind_of?(OpenCV::CvMat)
        @cvimg = fthing
      else
        ## new file
        @filename = fthing

        unless File.exists?(@filename)
          raise ArgumentError, "#{@filename} does not exist"
        end
      end
    end

    # cv_image_object comes from Detectable
    def __getobj__
      __setobj__(cv_image_object)
      super
    end

    private

    def spawn_image(cv_box, klass=self)
      sub_box = cv_image_object.sub_rect(cv_box)

      return klass.new(sub_box)
    end

  end
end

require_relative 'image/source_image'
require_relative 'image/face'


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/kms/v1/service.proto

namespace Google\Cloud\Kms\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Request message for
 * [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey].
 *
 * Generated from protobuf message google.cloud.kms.v1.CreateCryptoKeyRequest
 */
class CreateCryptoKeyRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. The [name][google.cloud.kms.v1.KeyRing.name] of the KeyRing
     * associated with the [CryptoKeys][google.cloud.kms.v1.CryptoKey].
     *
     * Generated from protobuf field string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     */
    private $parent = '';
    /**
     * Required. It must be unique within a KeyRing and match the regular
     * expression `[a-zA-Z0-9_-]{1,63}`
     *
     * Generated from protobuf field string crypto_key_id = 2 [(.google.api.field_behavior) = REQUIRED];
     */
    private $crypto_key_id = '';
    /**
     * Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] with initial field
     * values.
     *
     * Generated from protobuf field .google.cloud.kms.v1.CryptoKey crypto_key = 3 [(.google.api.field_behavior) = REQUIRED];
     */
    private $crypto_key = null;
    /**
     * If set to true, the request will create a
     * [CryptoKey][google.cloud.kms.v1.CryptoKey] without any
     * [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. You must
     * manually call
     * [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]
     * or
     * [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]
     * before you can use this [CryptoKey][google.cloud.kms.v1.CryptoKey].
     *
     * Generated from protobuf field bool skip_initial_version_creation = 5;
     */
    private $skip_initial_version_creation = false;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $parent
     *           Required. The [name][google.cloud.kms.v1.KeyRing.name] of the KeyRing
     *           associated with the [CryptoKeys][google.cloud.kms.v1.CryptoKey].
     *     @type string $crypto_key_id
     *           Required. It must be unique within a KeyRing and match the regular
     *           expression `[a-zA-Z0-9_-]{1,63}`
     *     @type \Google\Cloud\Kms\V1\CryptoKey $crypto_key
     *           Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] with initial field
     *           values.
     *     @type bool $skip_initial_version_creation
     *           If set to true, the request will create a
     *           [CryptoKey][google.cloud.kms.v1.CryptoKey] without any
     *           [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. You must
     *           manually call
     *           [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]
     *           or
     *           [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]
     *           before you can use this [CryptoKey][google.cloud.kms.v1.CryptoKey].
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Kms\V1\Service::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. The [name][google.cloud.kms.v1.KeyRing.name] of the KeyRing
     * associated with the [CryptoKeys][google.cloud.kms.v1.CryptoKey].
     *
     * Generated from protobuf field string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @return string
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * Required. The [name][google.cloud.kms.v1.KeyRing.name] of the KeyRing
     * associated with the [CryptoKeys][google.cloud.kms.v1.CryptoKey].
     *
     * Generated from protobuf field string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @param string $var
     * @return $this
     */
    public function setParent($var)
    {
        GPBUtil::checkString($var, True);
        $this->parent = $var;

        return $this;
    }

    /**
     * Required. It must be unique within a KeyRing and match the regular
     * expression `[a-zA-Z0-9_-]{1,63}`
     *
     * Generated from protobuf field string crypto_key_id = 2 [(.google.api.field_behavior) = REQUIRED];
     * @return string
     */
    public function getCryptoKeyId()
    {
        return $this->crypto_key_id;
    }

    /**
     * Required. It must be unique within a KeyRing and match the regular
     * expression `[a-zA-Z0-9_-]{1,63}`
     *
     * Generated from protobuf field string crypto_key_id = 2 [(.google.api.field_behavior) = REQUIRED];
     * @param string $var
     * @return $this
     */
    public function setCryptoKeyId($var)
    {
        GPBUtil::checkString($var, True);
        $this->crypto_key_id = $var;

        return $this;
    }

    /**
     * Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] with initial field
     * values.
     *
     * Generated from protobuf field .google.cloud.kms.v1.CryptoKey crypto_key = 3 [(.google.api.field_behavior) = REQUIRED];
     * @return \Google\Cloud\Kms\V1\CryptoKey|null
     */
    public function getCryptoKey()
    {
        return $this->crypto_key;
    }

    public function hasCryptoKey()
    {
        return isset($this->crypto_key);
    }

    public function clearCryptoKey()
    {
        unset($this->crypto_key);
    }

    /**
     * Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] with initial field
     * values.
     *
     * Generated from protobuf field .google.cloud.kms.v1.CryptoKey crypto_key = 3 [(.google.api.field_behavior) = REQUIRED];
     * @param \Google\Cloud\Kms\V1\CryptoKey $var
     * @return $this
     */
    public function setCryptoKey($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Kms\V1\CryptoKey::class);
        $this->crypto_key = $var;

        return $this;
    }

    /**
     * If set to true, the request will create a
     * [CryptoKey][google.cloud.kms.v1.CryptoKey] without any
     * [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. You must
     * manually call
     * [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]
     * or
     * [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]
     * before you can use this [CryptoKey][google.cloud.kms.v1.CryptoKey].
     *
     * Generated from protobuf field bool skip_initial_version_creation = 5;
     * @return bool
     */
    public function getSkipInitialVersionCreation()
    {
        return $this->skip_initial_version_creation;
    }

    /**
     * If set to true, the request will create a
     * [CryptoKey][google.cloud.kms.v1.CryptoKey] without any
     * [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. You must
     * manually call
     * [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]
     * or
     * [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]
     * before you can use this [CryptoKey][google.cloud.kms.v1.CryptoKey].
     *
     * Generated from protobuf field bool skip_initial_version_creation = 5;
     * @param bool $var
     * @return $this
     */
    public function setSkipInitialVersionCreation($var)
    {
        GPBUtil::checkBool($var);
        $this->skip_initial_version_creation = $var;

        return $this;
    }

}


text:
import { TutorLeaderboardElement } from 'app/shared/dashboards/tutor-leaderboard/tutor-leaderboard.model';
import { DueDateStat } from 'app/course/dashboards/due-date-stat.model';

export class StatsForDashboard {
    public numberOfStudents = 0;
    public numberOfSubmissions = new DueDateStat();
    public totalNumberOfAssessments = new DueDateStat();
    public numberOfAutomaticAssistedAssessments = new DueDateStat();
    public numberOfComplaints = 0;
    public numberOfOpenComplaints = 0;
    public numberOfMoreFeedbackRequests = 0;
    public numberOfOpenMoreFeedbackRequests = 0;
    public numberOfAssessmentLocks = 0;
    public totalNumberOfAssessmentLocks = 0;
    public complaintsEnabled = true;
    public feedbackRequestEnabled = true;
    public numberOfAssessmentsOfCorrectionRounds = [new DueDateStat()]; // Array with number of assessments for each correction round
    public numberOfLockedAssessmentByOtherTutorsOfCorrectionRound = [new DueDateStat()]; // Array with number of locked assessments for each correction round
    public numberOfRatings = 0;

    public tutorLeaderboardEntries: TutorLeaderboardElement[] = [];

    constructor() {}

    /**
     * Correctly initializes a class instance from a typecasted object.
     * Returns a 'real' class instance that supports all class methods.
     * @param object: The typecasted object
     * @returns The class instance
     */
    static from(object: StatsForDashboard): StatsForDashboard {
        const stats = Object.assign(new StatsForDashboard(), object);
        stats.numberOfSubmissions = Object.assign(new DueDateStat(), stats.numberOfSubmissions);
        stats.totalNumberOfAssessments = Object.assign(new DueDateStat(), stats.totalNumberOfAssessments);
        stats.numberOfAutomaticAssistedAssessments = Object.assign(new DueDateStat(), stats.numberOfAutomaticAssistedAssessments);
        return stats;
    }
}


text:
package com.emc.vipr.swift;

import org.javaswift.joss.client.factory.AccountConfig;
import org.javaswift.joss.client.factory.AccountFactory;
import org.javaswift.joss.model.Account;
import org.javaswift.joss.model.Container;
import org.javaswift.joss.model.StoredObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class swiftapi {

	public static Account ViPRSwiftClient(String username,String password,String dataNode)throws Exception
	{

		   AccountConfig config = new AccountConfig();
		              config.setUsername(username);
		               config.setPassword(password);
		               config.setAuthUrl(dataNode + "/v2.0/tokens");
		               config.setDisableSslValidation(true);
		               Account account = new AccountFactory(config).createAccount();
		   return account;

	}

	public static void CreateObject(String username,String passwod,String dataNode, String container, String key, InputStream content)throws Exception
	{

		Account client= ViPRSwiftClient(username, passwod, dataNode);
		Container myContainer=client.getContainer(container);
		StoredObject object = myContainer.getObject(key);
	    object.uploadObject(content);

	}

	public static InputStream ReadObject(String username,String passwod,String dataNode, String container, String key)throws Exception
	{

		Account client= ViPRSwiftClient(username, passwod, dataNode);
		Container myContainer=client.getContainer(container);
		StoredObject object = myContainer.getObject(key);
	    return object.downloadObjectAsInputStream();

	}

	public static void DeleteObject(String username,String passwod,String dataNode, String container, String key)throws Exception
	{

		Account client= ViPRSwiftClient(username, passwod, dataNode);
		Container myContainer=client.getContainer(container);
		StoredObject object = myContainer.getObject(key);
	    object.delete();
	}

}


text:
This is not an official Google product.

## Background

Dimsum is a portable C++ [SIMD](https://en.wikipedia.org/wiki/SIMD) library,
that is heavily influenced by the C++ standard library proposal
[P0214](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0214r6.pdf).
Currently, the library does not implement P0214, but its ultimate state is a
standard conforming implementation.

During the implementation, we examined all the differences our our intended
interfaces and P0214, and provided a feedback proposal
[P0820](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0820r0.pdf).

Due to prioritization, Dimsum does not currently implement the following list
of features from P0214, including but not limited to:
* simd\_mask<>
* simd\_abi::fixed\_size<>
* simd\_abi::compatible<>
* Non-power-of-two sizes
* SIMD version of \<cmath\>

Dimsum provides an extra set of opreations, mostly as free functions
in the namespace "dimsum" and namespace "dimsum::x86". The extra operations in
"dimsum" include many "horizontal" operations like shuffle, zip, and reduce-add;
the extra operations in "x86" provides some x86-specific semantics, with native
implementations on x86 and emulations on other architectures.

## Documentation

Refer to standard proposals for designs and public interfaces.

For the implementation, all the public interfaces should be documented in comments.

## Status

The above mentioned proposals are not part of the standard yet, nor is this
implementation fully conforming to the proposals. Any part of the API is subject
to change, without providing a fixing tool.

Some functionalities are with strawman implementations, with non-optimal
performance, due to prioritization.

## Requirements

Build system:
* Bazel

Compiler:
* Clang 3.8 or newer

The following sub-architectures are planed to be supported:
* x86 SSE 4.1 or newer
* x86 AVX2
* Power v2.07 VSX

We are also interested in supporting the following toolchain and architectures
in the future:
* (WIP) GCC 4.9 or newer
* (WIP) ARMv8 NEON (64-bit)

## Build and Test

The project is header-only, therefore no build is needed.

For testing, use "CC=clang bazel test --copt='...' <>" to run the unit tests.

For example:
* CC=clang bazel test --copt='-msse4.1' ... # x86 host
* CC=clang bazel test --copt='-mavx2' ... # x86 host
* CC=clang bazel test --copt='-maltivec' ... # Power host

Cross compilation is a bit tricky, but we found the following working, as long as
the toolchains support cross compilation:
* CC=clang bazel build --copt='-target' --copt='powerpc64le-linux-gnu'
      --copt='-maltivec' --linkopt='-target' --linkopt='powerpc64le-linux-gnu'
      ... # x86 host

## Fuzzing

Link dimsum\_fuzz against fuzz engines like libFuzzer, then run the result
binary.

(TODO) Add it to [OSS-Fuzz](https://github.com/google/oss-fuzz)


text:
<!DOCTYPE html>

    <title>fiddle-0005-EarthMoon</title>
    <meta name="description" content="fiddles/three/fiddle-0005-EarthMoon">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="author" content="bradyhouse@gmail.com">
    <link rel="shortcut icon" href="../../resources/images/favicon.ico" id="favicon"/>


text:
/*
 * Create an address, then send two postcards with it - one with a message
 * on the back, and one with a custom PDF back instead.
 * Run me! This example works out of the box, "batteries included".
 */

var lobFactory = require('../lib/index.js');
var Lob = new lobFactory('test_0dc8d51e0acffcb1880e0f19c79b2f5b0cc');

// Create the address
Lob.addresses.create({
  name: 'Test Person',
  email: 'test@gmail.com',
  phone: '123456789',
  address_line1: '123 Test Street',
  address_line2: 'Unit 199',
  address_city: 'Chicago',
  address_state: 'IL',
  address_zip: '60012',
  address_country: 'US',
}, function (err, address) {
  if (err) {
    console.log(err);
  } else {
    // with message
    Lob.postcards.create({
      name: 'My first postcard',
      to: address.id,
      front: 'https://s3-us-west-2.amazonaws.com/lob-assets/postcardfront.pdf',
      message: 'Hello from lob!'
    }, function (err, postcard) {
      if (err) {
        console.log(err);
      } else {
        console.log('The Lob API responded with this postcard object: ', postcard);
      }
    });

    // with custom back
    Lob.postcards.create({
      name: 'My first postcard',
      to: address.id,
      front: 'https://s3-us-west-2.amazonaws.com/lob-assets/postcardfront.pdf',
      back: 'https://s3-us-west-2.amazonaws.com/lob-assets/postcardback.pdf'
    }, function (err, postcard) {
      if (err) {
        console.log(err);
      } else {
        console.log('The Lob API responded with this postcard object: ', postcard);
      }
    });
  }
});