text:
package tpr;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import Bundler.Bundler;
import Plaatsers.BoundingBoxBundleCC;
import Plaatsers.PlacementManipulatorIOCLB;
import Plaatsers.Rplace;
import Plaatsers.Vplace;
import PlacementParser.Placement;
import PlacementParser.ReadPlacement;
import TRouter.ConnectionRouterBB;
import TRouter.VerificationModule;
import architecture.FourLutSanitizedDisjoint;
import circuit.Circuit;
import circuit.parser.conlist.ParseException;
import circuit.parser.conlist.Readconlist;
import circuit.writer.PlacementWriter;

import com.lexicalscope.jewel.cli.CliFactory;

public class ExportTPAR {

	/**
	 * @param args
	 * @throws FileNotFoundException
	 * @throws ParseException
	 * @throws architecture.ParseException
	 * @throws PlacementParser.ParseException
	 */
	public static void main(String[] args) throws FileNotFoundException, ParseException, PlacementParser.ParseException {
		System.out.println("Version information: TPack:advanced bundling, TPlace:SA with BB Bundle Estimation, TRoute:CrouteHwithConSmallestBBFirstOrder");
		/*
		String[] testArgs1 = {	"-p", "temp.p",
        							"-n", "testcases/BVHCell-tconmap_out.net",
        							"-w", "8",
        							"-h", "8",
        							"--routeOnly"};
        String[] testArgs2 = { 	"--help" };
		*/
        final Arguments cli = CliFactory.parseArguments(Arguments.class, args);

        if(cli.getPlacementOnly()){
        		if(cli.getRouteOnly()){
        			System.out.println("Error: conflicting command line options; 'Route only' and 'Placement only'");
        		}else{
        			placementOnly(cli.getHeight(),cli.getWidth(),cli.getPlacementEffort(),cli.getNetFilename(),cli.getPlacementFileName(),cli.getLogFileName());
        			DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        			Date date = new Date();
        			writeToFile("---timeStamp---"+dateFormat.format(date)+"\n", cli.getLogFileName());
        		}
        }else if(cli.getRouteOnly()){
        		routeOnly(cli.getHeight(),cli.getWidth(),cli.getChannelWidth(),cli.getNrOfRoutingIterations(),cli.getNetFilename(),cli.getPlacementFileName(),cli.getLogFileName());
    			DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    			Date date = new Date();
    			writeToFile("---timeStamp---"+dateFormat.format(date)+"\n", cli.getLogFileName());
        }else{
    			par(cli.getHeight(), cli.getWidth(), cli.getChannelWidth(), cli.getPlacementEffort(), cli.getNrOfRoutingIterations(), cli.getNetFilename(), cli.getPlacementFileName(), cli.getLogFileName());
    			DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    			Date date = new Date();
    			writeToFile("---timeStamp---"+dateFormat.format(date)+"\n", cli.getLogFileName());
        }
	}
	public static int par(int height, int width, int channelWidth, int placementEffort, int routingIterations, String netFile, String pFile, String logFile) throws FileNotFoundException, circuit.parser.conlist.ParseException{
		//Read in con netlist.
		System.out.println("Read in con netlist "+netFile+".. ");
		Readconlist parser=new Readconlist(new FileInputStream(new File(netFile)));
		Circuit c=parser.read();
		c.createBundles();

		//Architecture Check
		if(c.clbs.size()>(height*width)){
			System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of CLBs in the circuit exceeds the number of physical CLBs present on the FPGA.");
		}
		if(c.inputs.size()>(2*(height+width))){
			System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of inputs in the circuit exceeds the number of physical IOBs present on the FPGA.");
		}
		if(c.outputs.size()>(2*(height+width))){
			System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of outputs in the circuit exceeds the number of physical IOBs present on the FPGA.");
		}

		//Bundler
		System.out.println("Start bundling.. ");
		Bundler blr = new Bundler(c);
		final long startTime0 = System.nanoTime();
		final long endTime0;
		try {
			blr.bundle();
		} finally {
		  endTime0 = System.nanoTime();
		}
		final long duration0 = endTime0 - startTime0;
		System.out.println("Runtime: "+(duration0/1.0E9));
		System.out.println("Connections are bundled in "+c.bundles.size()+" bundles");
//		blr.printBundles();

		//Aanmaken van de architectuur.
		System.out.println("Aanmaken van de architectuur.");
		FourLutSanitizedDisjoint a = new FourLutSanitizedDisjoint(width,height,channelWidth);

		Random rand = new Random(1);
		PlacementManipulatorIOCLB pm0 = new PlacementManipulatorIOCLB(a,c,rand);
		BoundingBoxBundleCC bbbcc = new BoundingBoxBundleCC(c);

		//Random placement
		Rplace.placeCLBsandIOs(c, a, rand);
		pm0.placementCLBsConsistencyCheck();
		System.out.println("Total Cost random placement BBbundle cc: "+bbbcc.calculateTotalCost());

		//Time placement process
		Vplace placer1= new Vplace(pm0,bbbcc);
		final long startTime1 = System.nanoTime();
		final long endTime1;
		try {
			placer1.place(placementEffort);
		} finally {
		  endTime1 = System.nanoTime();
		}
		final long duration1 = endTime1 - startTime1;
		System.out.println("Runtime: "+(duration1/1.0E9));
		System.out.println("Total BB Cost after placement with bb bundle cc: "+bbbcc.calculateTotalCost());

		//Dump placement
		PlacementWriter.dumpPlacement(c, pFile);

		int its = -1;
		ConnectionRouterBB router = new ConnectionRouterBB(c);
		final long startTime2 = System.nanoTime();
		final long endTime2;
		try {
			its = router.crouteHwithConSmallestBBFirstOrder(a, routingIterations);
		} finally {
		  endTime2 = System.nanoTime();
		}
		final long duration2 = endTime2 - startTime2;
		System.out.println("Runtime: "+(duration2/1.0E9));
		System.out.println("Number of wires:  "+c.totalWires());

		if(c.totalWires()>0){
			VerificationModule vfmodule = new VerificationModule(c);
			System.out.println("Starting verification... "+vfmodule.verificateConnectionRouter());
		}

		String line = "Placement effort: "+placementEffort+",\tchannel width: "+channelWidth+"\t, routing iterations: "+routingIterations+",\tnet file: " + netFile
				+ "\n\t" + "Bundling: rt = "+(duration0/1.0E9)+", "+c.bundles.size()+" bundles"
				+ "\n\t" + "Placement: rt = "+(duration1/1.0E9)+", Total BBB Cost: "+bbbcc.calculateTotalCost()
				+ "\n\t" + "Routing: rt = "+(duration2/1.0E9)+", wires = "+c.totalWires()+"\n";

		writeToFile(line,logFile);

		return its;
	}
	public static int routeOnly(int height, int width, int channelWidth, int routingIterations, String netFile, String pFile, String logFile) throws FileNotFoundException, circuit.parser.conlist.ParseException, PlacementParser.ParseException{
		//Read in con netlist.
		System.out.println("Read in con netlist "+netFile+".. ");
		Readconlist parser=new Readconlist(new FileInputStream(new File(netFile)));
		Circuit c=parser.read();
		c.createBundles();

		//Architecture Check
		if(c.clbs.size()>(height*width)){
			System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of CLBs in the circuit exceeds the number of physical CLBs present on the FPGA.");
		}
		if(c.inputs.size()>(2*(height+width))){
			System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of inputs in the circuit exceeds the number of physical IOBs present on the FPGA.");
		}
		if(c.outputs.size()>(2*(height+width))){
			System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of outputs in the circuit exceeds the number of physical IOBs present on the FPGA.");
		}

		//Bundler
		System.out.println("Start bundling.. ");
		Bundler blr = new Bundler(c);
		final long startTime0 = System.nanoTime();
		final long endTime0;
		try {
			blr.bundle();
		} finally {
		  endTime0 = System.nanoTime();
		}
		final long duration0 = endTime0 - startTime0;
		System.out.println("Runtime: "+(duration0/1.0E9));
		System.out.println("Connections are bundled in "+c.bundles.size()+" bundles");
//		blr.printBundles();

		//Aanmaken van de architectuur.
		System.out.println("Aanmaken van de architectuur.");
		FourLutSanitizedDisjoint a = new FourLutSanitizedDisjoint(width,height,channelWidth);

		ReadPlacement plaats_parser=new ReadPlacement(new FileInputStream(pFile));
		Placement p=plaats_parser.read();
		c.applyPlacement(p, a);

		int its = -1;
		ConnectionRouterBB router = new ConnectionRouterBB(c);
		final long startTime2 = System.nanoTime();
		final long endTime2;
		try {
			its = router.crouteHwithConSmallestBBFirstOrder(a, routingIterations);
		} finally {
		  endTime2 = System.nanoTime();
		}
		final long duration2 = endTime2 - startTime2;
		System.out.println("Runtime: "+(duration2/1.0E9));
		System.out.println("Number of wires:  "+c.totalWires());

		if(c.totalWires()>0){
			VerificationModule vfmodule = new VerificationModule(c);
			System.out.println("Starting verification... "+vfmodule.verificateConnectionRouter());
		}

		String line = "Channel Width:"+channelWidth+",\tRouting Iterations:"+routingIterations+ "\t,net file:" + netFile
				+ "\n\t" + "Bundling: rt = "+(duration0/1.0E9)+", "+c.bundles.size()+" bundles"
				+ "\n\t" + "Routing: rt = "+(duration2/1.0E9)+", wires = "+c.totalWires()+"\n";

		writeToFile(line,logFile);

		return its;
	}
	public static void placementOnly(int height, int width, int placementEffort, String netFile, String pFile, String logFile) throws FileNotFoundException, circuit.parser.conlist.ParseException{
		//Read in con netlist.
		System.out.println("Read in con netlist "+netFile+".. ");
		Readconlist parser=new Readconlist(new FileInputStream(new File(netFile)));
		Circuit c=parser.read();
		c.createBundles();

		//Architecture Check
		if(c.clbs.size()>(height*width)){
			System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of CLBs in the circuit exceeds the number of physical CLBs present on the FPGA.");
		}
		if(c.inputs.size()>(2*(height+width))){
			System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of inputs in the circuit exceeds the number of physical IOBs present on the FPGA.");
		}
		if(c.outputs.size()>(2*(height+width))){
			System.out.println("Error: Dimensions of FPGA are too small to realize circuit.\nNumber of outputs in the circuit exceeds the number of physical IOBs present on the FPGA.");
		}

		//Bundler
		System.out.println("Start bundling.. ");
		Bundler blr = new Bundler(c);
		final long startTime0 = System.nanoTime();
		final long endTime0;
		try {
			blr.bundle();
		} finally {
		  endTime0 = System.nanoTime();
		}
		final long duration0 = endTime0 - startTime0;
		System.out.println("Runtime: "+(duration0/1.0E9));
		System.out.println("Connections are bundled in "+c.bundles.size()+" bundles");
//		blr.printBundles();

		//Aanmaken van de architectuur.
		System.out.println("Aanmaken van de architectuur.");
		FourLutSanitizedDisjoint a = new FourLutSanitizedDisjoint(width,height,1);

		Random rand = new Random(1);
		PlacementManipulatorIOCLB pm0 = new PlacementManipulatorIOCLB(a,c,rand);
		BoundingBoxBundleCC bbbcc = new BoundingBoxBundleCC(c);

		//Random placement
		Rplace.placeCLBsandIOs(c, a, rand);
		pm0.placementCLBsConsistencyCheck();
		System.out.println("Total Cost random placement BBbundle cc: "+bbbcc.calculateTotalCost());

		//Time placement process
		Vplace placer1= new Vplace(pm0,bbbcc);
		final long startTime1 = System.nanoTime();
		final long endTime1;
		try {
			placer1.place(placementEffort);
		} finally {
		  endTime1 = System.nanoTime();
		}
		final long duration1 = endTime1 - startTime1;
		System.out.println("Runtime: "+(duration1/1.0E9));
		System.out.println("Total BB Cost after placement with bb bundle cc: "+bbbcc.calculateTotalCost());

		//Dump placement
		PlacementWriter.dumpPlacement(c, pFile);

		String line = "Placement effort: "+placementEffort+",\tnet file: " + netFile
				+ "\n\t" + "Bundling: rt = "+(duration0/1.0E9)+", "+c.bundles.size()+" bundles"
				+ "\n\t" + "Placement: rt = "+(duration1/1.0E9)+", Total BBB Cost: "+bbbcc.calculateTotalCost();

		writeToFile(line,logFile);
	}
	public static void writeToFile(String str, String filename){
		try{
			// Create file
			FileWriter fstream = new FileWriter(filename,true);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(str);
			//Close the output stream
			out.close();
		}catch (Exception e){//Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}
}


text:
#Caller

##Doc
----

>
> The Caller is an Object that helps to get an make call a function/method.
>
>

----

View the Caller notebook on [NbViewer](http://nbviewer.ipython.org/url/shareyour
system.ouvaton.org/Caller.ipynb)

##Code

----

<ClassDocStr>

----

```python
# -*- coding: utf-8 -*-
"""

<DefineSource>
@Date : Fri Nov 14 13:20:38 2014 \n
@Author : Erwan Ledoux \n\n
</DefineSource>

The Caller is an Object that helps to get an make call a function/method.

"""

#<DefineAugmentation>
import ShareYourSystem as SYS
BaseModuleStr="ShareYourSystem.Standards.Objects.Packager"
DecorationModuleStr="ShareYourSystem.Standards.Classors.Tester"
SYS.setSubModule(globals())
#</DefineAugmentation>

#<ImportSpecificModules>
import sys
#</ImportSpecificModules>

#<DefineClass>
@DecorationClass()
class CallerClass(BaseClass):

        #Definition
        RepresentingKeyStrsList=[
'CallingVariable',
'CallingFunctionStr',
                                                                'CallingMethod',
'CallingMethodStr',
'CallingInstanceVariable',
                                                                'CallingClass',
'CallingClassStr',
                                                        ]

        def default_init(self,
                                                _CallingVariable=None,
                                                _CallingFunctionStr="",
                                                _CallingMethod=None,
                                                _CallingMethodStr="",
                                                _CallingInstanceVariable=None,
                                                _CallingClass=None,
                                                _CallingClassStr="",
                                                **_KwargVariablesDict
                                        ):

                #Call the parent init method
                BaseClass.__init__(self,**_KwargVariablesDict)

        #<DefineDoMethod>
        def do_call(self):

                #Module first to know where we are
                self.package()

                #debug
                '''
                print("self.CallingVariable is ",self.CallingVariable)
                print('')
                '''

                #If it was not yet setted or changed
                if self.CallingVariable==None or
self.CallingVariable.__name__!=self.CallingFunctionStr:

                        #debug
                        '''
                        print('Get in the module')
                        print('self.PackagingModuleVariable is
'+str(self.PackagingModuleVariable))
                        print('')
                        '''

                        #Get maybe the one in the module
                        if self.CallingFunctionStr!="":

                                #debug
                                '''
                                print('Get in the module with the function Str')
                                print('self.CallingFunctionStr is
',self.CallingFunctionStr)
                                print('')
                                '''

                                #Get and return
                                self.CallingVariable=getattr(self.PackagedModule
Variable,self.CallingFunctionStr)
                                return self

                #Get the function
                if self.CallingVariable==None or
self.CallingVariable.__name__!=self.CallingMethodStr:

                        #debug
                        '''
                        print('Get in a class')
                        print('self.PackagingModuleVariable is
'+str(self.PackagingModuleVariable))
                        print('self.CallingVariable is ',self.CallingVariable)
                        print('self.CallingMethodStr is ',self.CallingMethodStr)
                        print('self.CallingClass is ',self.CallingClass)
                        print('self.CallingClassStr is ',self.CallingClassStr)
                        print('self.CallingInstanceVariable is
',self.CallingInstanceVariable)
                        print('')
                        '''

                        #Get with the CallingInstanceVariable class maybe
                        if self.CallingClass==None and
self.CallingInstanceVariable!=None:
self.CallingClass=self.CallingInstanceVariable.__class__

                        #Import the module if not already
                        if self.CallingClass==None:
                                if self.CallingClassStr!="":
self.CallingClass=getattr(self.PackagedModuleVariable,self.CallingClassStr)
                                else:
                                        self.CallingClass=getattr(
self.PackagedModuleVariable,
SYS.getClassStrWithNameStr(
SYS.getNameStrWithModuleStr(self.PackagedModuleVariable.__name__)
)
                                                                        )

                        #debug
                        '''
                        print('Now get the unbounded method function')
                        print('self.CallingClass is '+str(self.CallingClass))
                        print('')
                        '''

                        #Check
                        if self.CallingMethodStr!="":

                                #debug
                                '''
                                print('self.CallingMethodStr is
',self.CallingMethodStr)
                                print('')
                                '''

                                #Return
self.CallingVariable=getattr(self.CallingClass,self.CallingMethodStr)

                #Return
                #return self

#</DefineClass>

```

View the Caller sources on Github

##Example

Let's create an empty class, which will automatically receive
special attributes from the decorating ClassorClass,
specially the NameStr, that should be the ClassStr
without the TypeStr in the end.

```python
#ImportModules
import ShareYourSystem as SYS
from ShareYourSystem.Standards.Objects import Caller

#Definition of a Caller instance
MyCaller=Caller.CallerClass()

#Call the _print from the Rep
MyCaller.call(
    _FunctionStr='represent',
    **{
        'PackagingModuleVariable':'ShareYourSystem.Standards.Classors.Representer',
    }
)

#Definition the AttestedStr
SYS._attest(
    [
        'MyCaller is '+SYS._str(
        MyCaller,
        **{
            'RepresentingBaseKeyStrsListBool':False
        }
        )
    ]
)

#Print

```

```console
>>>

*****Start of the Attest *****

MyCaller is < (CallerClass), 4537034384>
   /{
   /  '<New><Instance>IdInt' : 4537034384
   /  '<Spe><Class>CallingClass' : None
   /  '<Spe><Class>CallingClassStr' :
   /  '<Spe><Class>CallingInstanceVariable' : None
   /  '<Spe><Class>CallingMethod' : None
   /  '<Spe><Class>CallingMethodStr' :
   /  '<Spe><Instance>CallingFunctionStr' : represent
   /  '<Spe><Instance>CallingVariable' : <function Watcher@represent at
0x10e4cf1b8>
   /}

*****End of the Attest *****

```

redpajama_set_name: RedPajamaGithub


text:
#import "NSObject.h"

#import "NSCopying-Protocol.h"

@class WDCharacterProperties, WDDocument, WDParagraphProperties, WDStyle, WDTableCellProperties, WDTableRowProperties;

// Not exported
@interface WDTableStyleOverride : NSObject <NSCopying>
{
    WDDocument *mDocument;
    WDStyle *mStyle;
    int mPart;
    WDParagraphProperties *mParagraphProperties;
    WDCharacterProperties *mCharacterProperties;
    WDTableRowProperties *mTableRowProperties;
    WDTableCellProperties *mTableCellStyleProperties;
    unsigned int mParagraphPropertiesOverridden:1;
    unsigned int mCharacterPropertiesOverridden:1;
    unsigned int mTableRowPropertiesOverridden:1;
    unsigned int mTableCellStylePropertiesOverridden:1;
}

- (id)copyWithZone:(struct _NSZone *)arg1;
- (void)setTableCellStylePropertiesOverridden:(_Bool)arg1;
- (_Bool)isTableCellStylePropertiesOverridden;
- (id)mutableTableCellStyleProperties;
- (id)tableCellStyleProperties;
- (void)setTableRowPropertiesOverridden:(_Bool)arg1;
- (_Bool)isTableRowPropertiesOverridden;
- (id)mutableTableRowProperties;
- (id)tableRowProperties;
- (_Bool)isTablePropertiesOverridden;
- (id)tableProperties;
- (void)setCharacterPropertiesOverridden:(_Bool)arg1;
- (_Bool)isCharacterPropertiesOverridden;
- (id)mutableCharacterProperties;
- (id)characterProperties;
- (void)setParagraphPropertiesOverridden:(_Bool)arg1;
- (_Bool)isParagraphPropertiesOverridden;
- (id)mutableParagraphProperties;
- (id)paragraphProperties;
- (void)setPart:(int)arg1;
- (int)part;
- (void)setStyle:(id)arg1;
- (id)style;
- (void)dealloc;
- (id)initWithDocument:(id)arg1;

@end


text:
@extends('layouts.mainlayout')
@section('content')

فرم سفارش برنامه

      <form method="post" action="/programmerorder">

            نام و نام خانوادگی :
            <input type="text" class="form-control " id="nameInput" placeholder="نام و نام خانوادگی را وارد کنید " required="required">

              ایمیل:
              <input type="email" class="form-control " id="emailInput" placeholder="ایمیل خود را وارد کنید" required="required">

              موبایل:
              <input pattern="^09(1[0-9]|3[1-9]|2[1-9])-?[0-9]{3}-?[0-9]{4}$" type="phone" class="form-control" id="phoneInput" placeholder="موبایل" required="required">

              انتخاب نوع سفارش:
              <select class="form-control" id="orderType" required="required">
                <option>وب سایت</option>
                <option>اپلیکیشن اندروید</option>
                <option>اپلیکیشن دسکتاپ</option>
                <option>پروژه ترکیبی</option>
                <option>درخواست همکاری در پروژه </option>
              </select>

              بودجه مورد نظر:
              <input pattern="^[1-9][0-9]*$" type="number" class="form-control" id="budgetInput" placeholder="حداکثر بودجه پروژه"     required="required">

              توضیحات :
              <textarea class="form-control" rows="16" id="orderText" required="required"></textarea>

            شما با ارسال درخواست با تمامی قوانین موافقت میکنید .

متن قوانین برای سفارش پروژه

 some text here.

                  <button type="button" class="btn btn-success" data-dismiss="modal">بستن</button>

          <input type="submit" class="btn btn-block btn-danger" value="ارسال">

      </form>

@endsection


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>RollingFileAppender.AdjustFileBeforeAppend Method</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            log4net SDK Documentation - Microsoft .NET Framework 4.0

RollingFileAppender.AdjustFileBeforeAppend Method

 Performs any required rolling before outputting the next event

        [Visual Basic]

Overridable Protected Sub AdjustFileBeforeAppend()

        [C#]

protected virtual void AdjustFileBeforeAppend();

Remarks

 Handles append time behavior for RollingFileAppender. This checks if a roll over either by date (checked first) or time (checked second) is need and then appends to the file last.

See Also

RollingFileAppender Class | log4net.Appender Namespace
<object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"><param name="Keyword" value="AdjustFileBeforeAppend method"></param><param name="Keyword" value="AdjustFileBeforeAppend method, RollingFileAppender class"></param><param name="Keyword" value="RollingFileAppender.AdjustFileBeforeAppend method"></param></object>

Copyright 2004-2011 The Apache Software Foundation.


text:
Dal 2008 al 2012, la cittadina messicana al confine con gli Stati Uniti, Ciudad de Juarez, è stata ampiamente considerata il luogo più pericoloso della Terra...
*segue su*
Il Dato Mancante

## Fonti Dati
| Fonte | Descrizione | Link |
| ------ | ------ | ------ |
| Istat | Istituto Nazionale di Statistica Italiano |http://dati.istat.it/Index.aspx |
| Eurostat | Ufficio Statistico dell'Unione Europea |http://ec.europa.eu/eurostat/data/database |

## Visualizzazioni
| File | Descrizione |
| ------ | ------ |
| output/omicidi_volontari.html | Distribuzione Omicidi Volontari per Regione Italiana |
| output/Top3_Regioni.csv | Top 3 Regioni Pericolose - Numero Omicidi Volontari |
| output/topcitta.png | Top 10 Città Pericolose Italia - Numero Omicidi Volontari |
| output/omicidi_volontari_eu.html | Distribuzione Omicidi Volontari in Europa |
| output/topeurcitta.png| Top 10 Città Pericolose Europa - Numero Omicidi Volontari |

## Configurazioni
Queste istruzioni ti permetteranno di realizzare una copia del progetto in locale per eseguire il codice.

#### Prerequisiti
1. Installare l'ambiente Anaconda, comprende Jupyter. https://docs.anaconda.com/anaconda/install/
2. Copiare il repository sul proprio account GitHub.
3. Copiare il repository in locale

#### Librerie aggiuntive
Anaconda installa in automatico più di 150 package per analisi dati, in aggiunta è necessario installare:
```
jsonstatpy -> http://jsonstatpy.readthedocs.io/en/latest/index.html
```
```
folium -> https://folium.readthedocs.io/en/latest/
```


text:
namespace signin {

scoped_ptr<KeyedService> BuildTestSigninClient(
    content::BrowserContext* context) {
  return make_scoped_ptr(
      new TestSigninClient(static_cast<Profile*>(context)->GetPrefs()));
}

}  // namespace signin


text:
from django.core.management.base import BaseCommand, CommandError
from notemanagement.models import Category

class Command(BaseCommand):
    help = 'Testing command for note management'

    def handle(self, *args, **options):
        cats = Category.objects.all()
        for cat in cats:
            self.stdout.write('Category: %s\n' % cat)
        self.stdout.write('DONE\n')


text:
'use strict';

const CouchError = require('../util/CouchError');
const debug = require('../util/debug')('main:nano');

async function getGroup(db, name) {
  debug.trace('get group');
  const groups = await db.queryView('groupByName', {
    key: name,
    reduce: false,
    include_docs: true,
  });
  if (!groups || groups.length === 0) {
    debug.trace('group does not exist');
    return null;
  }
  if (groups.length > 1) {
    debug.warn('Getting more than one result for a group name');
  }
  debug.trace('group exists');
  return groups[0].doc;
}

function save(db, entry, user) {
  switch (entry.$type) {
    case 'entry':
      return saveEntry(db, entry, user);
    case 'group':
      return saveGroup(db, entry, user);
    default:
      throw new CouchError(`invalid type: ${entry.$type}`);
  }
}

function saveEntry(db, entry, user) {
  if (entry.$id === undefined) {
    entry.$id = null;
  }
  if (entry.$kind === undefined) {
    entry.$kind = null;
  }
  return saveWithFields(db, entry, user);
}

function saveGroup(db, group, user) {
  return saveWithFields(db, group, user);
}

async function saveWithFields(db, object, user) {
  const now = Date.now();
  let isNew = false;
  object.$lastModification = user;
  object.$modificationDate = now;
  if (object.$creationDate === undefined) {
    object.$creationDate = now;
    isNew = true;
  }

  const result = await db.insertDocument(object);
  result.$modificationDate = object.$modificationDate;
  result.$creationDate = object.$creationDate;
  result.isNew = isNew;
  return result;
}

function getUuidFromId(db, id, user, type) {
  switch (type) {
    case 'group':
      return getUuidFromIdGroup(db, id);
    default:
      throw new CouchError(`invalid type: ${type}`);
  }
}

async function getUuidFromIdGroup(db, id) {
  const owners = await db.queryView('ownerByTypeAndId', {
    key: ['group', id],
  });
  if (owners.length === 0) {
    throw new CouchError('document not found', 'not found');
  }
  if (owners.length !== 1) {
    throw new CouchError(
      `unexpected number of results: ${owners.length}. There should be only one`,
    );
  }
  return owners[0].id;
}

module.exports = {
  getGroup,
  saveEntry,
  saveGroup,
  save,
  getUuidFromId,
};


text:
The Summer Institutes in Computational Social Science

Bringing together graduate students, postdoctoral researchers, and junior faculty for 2 weeks of intensive study and interdisciplinary research


text:
"""Tests for Softsign and SoftsignGrad."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.python.framework import constant_op
from tensorflow.python.ops import gradient_checker
from tensorflow.python.ops import nn_ops
import tensorflow.python.ops.nn_grad  # pylint: disable=unused-import
from tensorflow.python.platform import test

class SoftsignTest(test.TestCase):

  def _npSoftsign(self, np_features):
    return np_features / (1 + np.abs(np_features))

  def _testSoftsign(self, np_features, use_gpu=False):
    np_softsign = self._npSoftsign(np_features)
    with self.cached_session(use_gpu=use_gpu):
      softsign = nn_ops.softsign(np_features)
      tf_softsign = self.evaluate(softsign)
    self.assertAllClose(np_softsign, tf_softsign)
    self.assertShapeEqual(np_softsign, softsign)

  def testNumbers(self):
    for t in [np.float, np.double]:
      self._testSoftsign(
          np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),
          use_gpu=False)
      self._testSoftsign(
          np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),
          use_gpu=True)

  def testGradient(self):
    with self.cached_session():
      x = constant_op.constant(
          [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],
          shape=[2, 5],
          name="x")
      y = nn_ops.softsign(x, name="softsign")
      x_init = np.asarray(
          [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],
          dtype=np.float32,
          order="F")
      err = gradient_checker.compute_gradient_error(
          x, [2, 5], y, [2, 5], x_init_value=x_init)
    print("softsign (float) gradient err = ", err)
    self.assertLess(err, 1e-4)

  def testNoInts(self):
    with self.cached_session():
      with self.assertRaisesRegexp(
          TypeError,
          "'features' has DataType int32 not in list of allowed values"):
        nn_ops.softsign(constant_op.constant(7)).eval()

if __name__ == "__main__":
  test.main()


text:
.. _book.changes:

=======
Changes
=======

This is the combined changelog for packages :mod:`lino`, :mod:`lino_xl` and
:mod:`lino_react`.

General information about how to read and maintain this document in
:ref:`dev.changes`. Make sure to notify us if you run a :term:`production site`
using Lino.  We provide automatic database migration only for applications with
at least one registered production site.

.. toctree::
   :maxdepth: 1

   2021
   2020
   2019
   2018
   old


text:
var list = [
  require("./filters/dealwithSession")
];
var listLength =  list.length;

function loop(flag,req,resp,fn){
    if(flag < 0)
      return fn;
    if(flag === 0){
       return function(){
          list[listLength-1].deal(req,resp,fn);
       }
    }
    return function(){
         list[listLength -1 -flag].deal(req,resp,loop(flag-1,req,resp,fn));
      }
}

exports.filterlist = function(request,response,fn){
  list[0].deal(request,response,loop(listLength-2,request,response,fn));
}

//以上为fastjsonweb处理

//以下为 开发者自定义处理

var systemPathUtils = require('path');

function definedLoop(flag,req,resp,fn,list,listLength,dirPath){
  if(flag < 0)
    return fn;
  if(flag === 0){
      return function(){
         require(getRealPath(dirPath,list[listLength-1])).doFilter(req,resp,fn)
      }
   }
   return function(){
      require(getRealPath(dirPath,list[listLength -1 -flag]))
        .doFilter(req,resp,definedLoop(flag-1,req,resp,fn,list,listLength,dirPath));
   }
}

function getRealPath(dirPath,filePath){
  dirpath = systemPathUtils.join(process.cwd(),dirPath);
  return systemPathUtils.join(dirpath,filePath);
}
exports.definedFilterList = function(request,response,fn){
  var filters = require('./globelsetting').getFilter();
  var filterlist  = filters.sequence;
  var filterLength = filterlist.length;
  var path = filters.path;
  if(!filterLength){
    fn();
    return;
  }
  require(getRealPath(path,filterlist[0]))
    .doFilter(request,response,definedLoop(filterLength-2,request,response,fn,filterlist,filterLength,path));

}


text:
using System;
using System.Globalization;

public class Test
{
    public static int Main()
    {
        try
        {
            CultureInfo ci = new CultureInfo("hu");

	    if (ci.ToString() != "hu")
	    {
	        Console.WriteLine("!!!ERROR-001: Result not as expected; expected value: hu, actual value: " + ci.ToString());
                Console.WriteLine("FAIL");
                return 99;
	    }
	    Console.WriteLine("Pass");
	    return 100;
        }
        catch (Exception e)
        {
            Console.WriteLine("!!!ERROR-XXX: Unexpected exception : " + e);
            Console.WriteLine("FAIL");
            return 101;
        }
    }
}


text:
package com.anrisoftware.simplerest.owncloudocs;

import java.util.Map;

import com.anrisoftware.simplerest.json.AbstractParseJsonResponseFromMap;
import com.anrisoftware.simplerest.ocs.DefaultShareResultMessage;
import com.anrisoftware.simplerest.ocs.ShareResultMessage;
import com.fasterxml.jackson.core.type.TypeReference;

class ShareResultParseJsonResponse extends
        AbstractParseJsonResponseFromMap<ShareResultMessage> {

    protected ShareResultParseJsonResponse() {
        super("ocs",
                new TypeReference<Map<String, DefaultShareResultMessage>>() {
        });
    }

}


text:
#include "condor_common.h"
#include "network_adapter.WINDOWS.h"
#include "my_hostname.h"

#include <iphlpapi.h>

/***************************************************************
 * Ripped from the MS DDK
 ***************************************************************/

/*  {6B29FC40-CA47-1067-B31D-00DD010662DA}
    Length = 1[{] + 32[sizeof(GUID)*2] + 4[-] + 1[}]
    */
#define GUID_STR_LENGTH ((sizeof(GUID)*2)+6)

#define CONDOR_DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
    extern const GUID name \
                = { l, w1, w2, { b1, b2,  b3,  b4,  b5,  b6,  b7,  b8 } }

/*    Guid for Lan Class. (From DDK)
*/
CONDOR_DEFINE_GUID(CONDOR_GUID_NDIS_LAN_CLASS, 0xad498944, 0x762f,
                    0x11d0, 0x8d, 0xcb, 0x00, 0xc0, 0x4f, 0xc3,
                    0x35, 0x8c);

/***************************************************************
 * Defines
 ***************************************************************/

#define WAKE_FROM_ANY_SUPPORTED (PDCAP_WAKE_FROM_D0_SUPPORTED| \
                                 PDCAP_WAKE_FROM_D1_SUPPORTED| \
                                 PDCAP_WAKE_FROM_D2_SUPPORTED| \
                                 PDCAP_WAKE_FROM_D3_SUPPORTED)

/***************************************************************
 * WindowsNetworkAdapter class
 ***************************************************************/

WindowsNetworkAdapter::WindowsNetworkAdapter (void) throw ()
: _exists ( false ) {
    strncpy ( _ip_address, my_ip_string (), IP_STRING_BUF_SIZE );
    _description[0] = '\0';
}

WindowsNetworkAdapter::WindowsNetworkAdapter ( LPCSTR ip_addr,
											   unsigned int /*ip*/) throw ()
: _exists ( false ) {
    strncpy ( _ip_address, ip_addr, IP_STRING_BUF_SIZE );
    _description[0] = '\0';
}

WindowsNetworkAdapter::WindowsNetworkAdapter ( LPCSTR description ) throw ()
: _exists ( false ) {
    strncpy ( _description, description,
        MAX_ADAPTER_DESCRIPTION_LENGTH + 4 );
    _ip_address[0] = '\0';
}

WindowsNetworkAdapter::~WindowsNetworkAdapter (void) throw () {
}

/***************************************************************
 * WindowsNetworkAdapter class
 ***************************************************************/

bool
WindowsNetworkAdapter::initialize (void) {

    PIP_ADAPTER_INFO    adapters    = NULL,
                        current     = NULL;
	DWORD               error       = 0,
                        supports    = 0;
    UINT                length      = 0;
	ULONG               size;
    LPCSTR              other       = NULL;
    LPSTR               offset      = _hardware_address;
    unsigned int        i           = 0;
    PCM_POWER_DATA      power_data  = NULL;
    bool                ok          = false;

    __try {

        /* allocate a very small ammount of ram, which will cause the
           call for information to fail, but will reveal the size
           of the true structure */
        size = sizeof ( IP_ADAPTER_INFO );
        adapters = (PIP_ADAPTER_INFO) malloc ( size );

        if ( ERROR_SUCCESS != GetAdaptersInfo ( adapters, &size ) ) {
            free ( adapters );
            adapters = (PIP_ADAPTER_INFO) malloc ( size );
	    }

        /* now attempt to grab all the information we can for each
           adapter, then search through them until we find the one
           which matches the IP we are looking for */
        if ( NO_ERROR != ( error = GetAdaptersInfo ( adapters, &size ) ) ) {

            /* failed to get the adapter information */
            __leave;

        } else {

            /* initialize the Setup DLL */
            if ( !_setup_dll.load () ) {

                dprintf (
                    D_FULLDEBUG,
                    "WindowsNetworkAdapter::initialize: "
                    "Failed to load setup.dll which is required to "
                    "gather power information for network "
                    "adapters.\n" );

                __leave;

            }

            /* reset any bits set from a previous initialization */
            wolResetSupportBits ();
            wolResetEnableBits ();

            /* got it, lets run through them and the one we
            are interested in */
            current = adapters;

            while ( current ) {

                char *ip = current->IpAddressList.IpAddress.String,
                     *description = current->Description;

                if ( MATCH == strcmp ( _ip_address, ip ) ||
                     MATCH == strcmp ( _description, description ) ) {

                    /* we do exist! */
                    _exists = true;

                    /* record the adapter GUID */
                    strncpy (
                        _adapter_name,
                        current->AdapterName,
                        MAX_ADAPTER_NAME_LENGTH + 4 );

                    /* using the GUID, get the device's power
                    capabilities */
                    power_data = getPowerData ();
                    if ( power_data ) {

                        /* shorten the variable we need to use */
                        supports = power_data->PD_Capabilities;

                        /* do we support waking from any state? */
                        if ( supports & WAKE_FROM_ANY_SUPPORTED ) {

                            dprintf (
                                D_FULLDEBUG,
                                "WOL_MAGIC enabled\n" );

                            wolEnableSupportBit ( WOL_MAGIC );
                            wolEnableEnableBit ( WOL_MAGIC );
                        }

                        LocalFree ( power_data );
                        power_data = NULL;

                    }

                    /* copy over the adapter's subnet */
                    strncpy (
                        _subnet_mask,
                        current->IpAddressList.IpMask.String,
                        IP_STRING_BUF_SIZE );

                    /* finally, format the hardware address in the
                    format our tools expect */
                    length = current->AddressLength;
                    for ( i = 0; i < length; ++i ) {
                        sprintf ( offset, "%.2X%c",
                            current->Address[i],
				            i == length - 1 ? '\0' : ':' );
                        offset += 3;
                    }

                    dprintf (
                        D_FULLDEBUG,
                        "Hardware address: '%s'\n",
                        _hardware_address );

                    /* if we got here, then the world is a happy place */
                    ok = true;

                    /* we found the one we want, so bail out early */
                    __leave;

                }

                /* move on to the next one */
                current = current->Next;

            }

        }

    }
    __finally {

        if ( adapters ) {
            free ( adapters );
        }

    }

    return ok;

}

const char*
WindowsNetworkAdapter::hardwareAddress (void) const {
    return _hardware_address;
}

unsigned
WindowsNetworkAdapter::ipAddress (void) const {
    return 0; /* not used on Windows */
}

const char*
WindowsNetworkAdapter::interfaceName () const
{
	return _description; // _adapter_name;
}

const char*
WindowsNetworkAdapter::subnetMask (void) const {
    return _subnet_mask;
}

bool
WindowsNetworkAdapter::exists (void) const {
    return _exists;
}

/*    The power data registry values requires some preprocessing before
    it can be queried, so we allow a user to specify a function to handle
    preprocessing.
*/
static void
processPowerData ( IN PBYTE p ) {
    PCM_POWER_DATA ppd = (PCM_POWER_DATA) p;
    ppd->PD_Size = sizeof ( ppd );
}

PCM_POWER_DATA
WindowsNetworkAdapter::getPowerData (void) const {

    return (PCM_POWER_DATA) getRegistryProperty (
        SPDRP_DEVICE_POWER_DATA, &processPowerData );

}

PBYTE
WindowsNetworkAdapter::getRegistryProperty (
    IN DWORD registry_property,
    IN PRE_PROCESS_REISTRY_VALUE preprocess ) const {

        PVOID   device_information      = INVALID_HANDLE_VALUE;
        DWORD   error                   = NO_ERROR,
                required                = 0,
                index                   = 0,
                last_error              = ERROR_SUCCESS;
        SetupApiDLL::PSP_DEVICE_INTERFACE_DETAIL_DATA pdidd = NULL;
        PCHAR   short_name              = NULL;
        PBYTE   value                   = NULL;
        BOOL    enumerated_devices      = FALSE,
                got_device_details      = FALSE,
                got_registry_property   = FALSE,
                ok                      = FALSE;

        __try {

            device_information = SetupApiDLL::SetupDiGetClassDevs (
                &CONDOR_GUID_NDIS_LAN_CLASS,
                0,
                0,
                DIGCF_PRESENT | DIGCF_DEVICEINTERFACE );

            if ( INVALID_HANDLE_VALUE == device_information ) {

                last_error = GetLastError ();

                dprintf (
                    D_FULLDEBUG,
                    "WindowsNetworkAdapter::getRegistryProperty: "
                    "SetupDiGetClassDevs call failed: "
                    "(last-error = %d)\n",
                    last_error );

                __leave;

            }

            while ( true ) {

                //
                // We loop indefinitely because the number of
                // interfaces is only known to us when we run
                // out of them: it is at this time that we
                // break out of the loop.
                //

                SetupApiDLL::SP_DEVICE_INTERFACE_DATA did = {
                    sizeof ( SetupApiDLL::SP_DEVICE_INTERFACE_DATA ) };

                enumerated_devices = SetupApiDLL::SetupDiEnumDeviceInterfaces (
                    device_information,
                    NULL,
                    &CONDOR_GUID_NDIS_LAN_CLASS,
                    index++,
                    &did );

                if ( !enumerated_devices ) {

                    last_error = GetLastError ();

                    //
                    // Perhaps there are no more interfaces, in
                    // which case it is ok that we failed.
                    //
                    if ( ERROR_NO_MORE_ITEMS == last_error ) {

                        ok = TRUE;

                    }

                    __leave;

                }

                SetupApiDLL::SP_DEVINFO_DATA dd
                    = { sizeof ( SetupApiDLL::SP_DEVINFO_DATA ) };

                got_device_details = SetupApiDLL::SetupDiGetDeviceInterfaceDetail (
                    device_information,
                    &did,
                    NULL,
                    0,
                    &required,
                    &dd );    // MSDN says this is optional,
                              // but it is not... here...

                if ( !got_device_details ) {

                    last_error = GetLastError ();

                    if ( ERROR_INSUFFICIENT_BUFFER == last_error ) {

                        pdidd = (SetupApiDLL::PSP_DEVICE_INTERFACE_DETAIL_DATA)
                            LocalAlloc (
                                LPTR,
                                required );

                        if  ( !pdidd ) {

                            last_error = GetLastError ();

                            dprintf (
                                D_FULLDEBUG,
                                "WindowsNetworkAdapter::"
                                "getRegistryProperty: "
                                "LocalAlloc call failed: "
                                "(last-error = %d)\n",
                                last_error );

                            __leave;

                        }

                        pdidd->cbSize = sizeof ( *pdidd );

                    } else {

                        dprintf (
                            D_FULLDEBUG,
                            "WindowsNetworkAdapter::"
                            "getRegistryProperty: "
                            "SetupDiGetDeviceInterfaceDetail (1st) "
                            "call failed: (last-error = %d)\n",
                            last_error );

                        __leave;

                    }

                }

                got_registry_property = SetupApiDLL::SetupDiGetDeviceInterfaceDetail (
                    device_information,
                    &did,
                    pdidd,
                    required,
                    NULL,
                    NULL ); // here, however, it *is* optional?!
                            // (WTF!?!--pardon my French)

                if ( !got_registry_property ) {

                    last_error = GetLastError ();

                    dprintf (
                        D_FULLDEBUG,
                        "WindowsNetworkAdapter::getRegistryProperty: "
                        "SetupDiGetDeviceInterfaceDetail (2nd) call "
                        "failed: (last-error = %d)\n",
                        last_error );

                    __leave;

                }

                //dprintf ( D_FULLDEBUG, "DevicePath: %s\n", pdidd->DevicePath );

                //
                // Device paths are of the form:
                //
                // \\?\root#ms_ptiminiport#0000#{ad498944-762f-11d0-8dcb \
                //   -00c04fc3358c}\{5a8445c2-ecd0-407d-a359-e1a98fb299b4}
                //
                // Where the final guid is the device name or
                // "id"; that is to say: it is the part we are
                // interested in.
                //
                short_name = strrchr (
                    pdidd->DevicePath,
                    '\\' ) + 1;

                if ( 0 != strnicmp (
                        _adapter_name,
                        short_name,
                        GUID_STR_LENGTH ) ) {

                    //
                    // If this is not the guid we are looking for,
                    // then keep on searching...
                    //
                    LocalFree ( pdidd );
                    continue;

                }

                //dprintf ( D_FULLDEBUG, "DeviceName: %s\n", _adapter_name );

                got_registry_property = SetupApiDLL::SetupDiGetDeviceRegistryProperty (
                    device_information,
                    &dd,
                    registry_property,
                    NULL,
                    NULL,
                    0,
                    &required );

                //dprintf ( D_FULLDEBUG, "registry_property required: %d\n", required );

                if ( !got_registry_property ) {

                    last_error = GetLastError ();

                    if ( ERROR_INSUFFICIENT_BUFFER == last_error ) {

                        value = (PBYTE) LocalAlloc (
                            LPTR,
                            required );

                        if  ( !value ) {

                            last_error = GetLastError ();

                            dprintf (
                                D_FULLDEBUG,
                                "WindowsNetworkAdapter::"
                                "getRegistryProperty: "
                                "LocalAlloc call "
                                "failed: (last-error = %d)\n",
                                last_error );

                            __leave;

                        }

                    } else {

                        last_error = GetLastError ();

                        dprintf (
                            D_FULLDEBUG,
                            "WindowsNetworkAdapter::"
                            "getRegistryProperty: "
                            "SetupDiGetDeviceRegistryProperty (1st) "
                            "call failed: (last-error = %d)\n",
                            last_error );

                        __leave;

                    }

                }

                //
                // Do any preprocessing that may be required
                //
                if ( preprocess ) {
                    preprocess ( value );
                }

                got_registry_property = SetupApiDLL::SetupDiGetDeviceRegistryProperty (
                    device_information,
                    &dd,
                    registry_property,
                    NULL,
                    value,
                    required,
                    NULL );

                if ( !got_registry_property ) {

                    last_error = GetLastError ();

                    dprintf (
                        D_FULLDEBUG,
                        "WindowsNetworkAdapter::getRegistryProperty: "
                        "SetupDiGetDeviceRegistryProperty (2nd) "
                        "call failed: (last-error = %d)\n",
                        last_error );

                    __leave;

                }

                //
                // If we get here, then it means we have found the
                // device information we were looking for and can
                // return it.
                //
                ok = TRUE;

                __leave;

            }

        }
        __finally {

            //
            // Propagate the last error
            //
            SetLastError ( ok ? ERROR_SUCCESS : last_error );

            if ( INVALID_HANDLE_VALUE != device_information ) {
                SetupApiDLL::SetupDiDestroyDeviceInfoList ( device_information );
            }

            if ( pdidd ) {
                LocalFree ( pdidd );
                pdidd = NULL;
            }

            if ( !ok && value ) {
                LocalFree ( value );
                value = NULL;
            }

        }

        //
        // If we found the device information, the following will be a
        // valid pointer to it; otherwise, it will be NULL.
        //
        return value;

}


text:
const GLchar* vertexSource =
    "#version 150 core\n"
    "in vec2 position;"
    "in vec3 color;"
    "out vec3 Color;"
    "void main() {"
    "   Color = color;"
    "   gl_Position = vec4(position, 0.0, 1.0);"
    "}";
const GLchar* fragmentSource =
    "#version 150 core\n"
    "in vec3 Color;"
    "out vec4 outColor;"
    "void main() {"
    "   outColor = vec4(Color, 1.0);"
    "}";

static void error_callback(int error, const char* description)
{
    fprintf(stderr, "Error %d: %s\n", error, description);
}

int main(int, char**)
{
    // Setup window
    glfwSetErrorCallback(error_callback);
    if (!glfwInit())
        exit(1);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#if __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
    GLFWwindow* window = glfwCreateWindow(1280, 720, "ImGui OpenGL3 example", NULL, NULL);
    glfwMakeContextCurrent(window);
    gl3wInit();

    // Setup ImGui binding
    ImGui_ImplGlfwGL3_Init(window, true);

    // Load Fonts
    // (see extra_fonts/README.txt for more details)
    ImGuiIO& io = ImGui::GetIO();
    //io.Fonts->AddFontDefault();
    // io.Fonts->AddFontFromFileTTF("../extra_fonts/Cousine-Regular.ttf", 15.0f);
    io.Fonts->AddFontFromFileTTF("../extra_fonts/DroidSans.ttf", 16.0f);
    // io.Fonts->AddFontFromFileTTF("../extra_fonts/ProggyClean.ttf", 13.0f);
    //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
    //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());

    // Merge glyphs from multiple fonts into one (e.g. combine default font with another with Chinese glyphs, or add icons)
    //ImWchar icons_ranges[] = { 0xf000, 0xf3ff, 0 };
    //ImFontConfig icons_config; icons_config.MergeMode = true; icons_config.PixelSnapH = true;
    //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 18.0f);
    //io.Fonts->AddFontFromFileTTF("../../extra_fonts/fontawesome-webfont.ttf", 18.0f, &icons_config, icons_ranges);

    bool show_test_window = true;
    bool show_another_window = false;
    ImVec4 clear_color = ImColor(114, 144, 154);
    char lol[100] = "";

    // Main loop
    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();
        ImGui_ImplGlfwGL3_NewFrame();

        ImGui::SetWindowPos(ImVec2(0,0));
        ImGui::SetWindowSize(ImVec2(1280, 720));

        int display_w, display_h;
        glfwGetFramebufferSize(window, &display_w, &display_h);
        glViewport(0, 0, display_w, display_h);
        glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
        glClear(GL_COLOR_BUFFER_BIT);

        // 1. Show a simple window
        // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
        {
            static float f = 0.0f;
            ImGui::Text("Hello, world!");
            ImGui::InputText("Hello input", lol, 100);
            ImGui::InputText("Hello input2", lol, 100);
            if (ImGui::IsItemActive()) {
                std::cout << "Input active" << std::endl;
            }
            // if (ImGui::IsKeyDown('a')) {
            //     std::cout << "Key down: 'a'" << std::endl;
            // }
            // if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) {
            //     std::cout << "active" << std::endl;
            // }
            // if (ImGui::IsItemHovered() && ImGui::IsMouseReleased(0)) {
            //     std::cout << "released" << std::endl;
            // }
            // if (ImGui::IsItemHoveredRect() && ImGui::IsMouseReleased(0)) {
            //     std::cout << "released" << std::endl;
            // }

            ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
            ImGui::ColorEdit3("clear color", (float*)&clear_color);

            ImGui::SameLine();
            if (ImGui::Button("Test Window")) show_test_window ^= 1;
            if (ImGui::Button("Test Window2")) show_test_window ^= 1;
            ImGui::SameLine();
            // if (ImGui::IsItemActive()) {
            //     std::cout << "Item active" << std::endl;
            // }
            // std::cout << "a" << (unsigned int)'a' << std::endl;
            // for (size_t i = 0; i < ImGui::GetIO().InputCharacters[i]; i++) {
            //     std::cout << (char)ImGui::GetIO().InputCharacters[i];
            // } if (ImGui::GetIO().InputCharacters[0]) {
            //     std::cout << "" << std::endl;
            // }
            if (ImGui::IsItemHovered()) {
                std::cout << "Button hovered" << std::endl;
            }

            if (ImGui::IsKeyDown((unsigned int)'a')) {
                std::cout << "Key down: 'a'" << std::endl;
            }

            if (ImGui::Button("Another Window")) show_another_window ^= 1;
            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);

            // ImGui::Canvas("Canvas Test", ImVec2(500,200), [] (const ImDrawList*,const ImDrawCmd* cmd) {
            //     ImVec2 min = ((ImVec2*)cmd->UserCallbackData)[0];
            //     ImVec2 max = ((ImVec2*)cmd->UserCallbackData)[1];
            //     delete (ImVec2*)cmd->UserCallbackData;
            //     double mx, my;
        	// 	int winWidth = 1280, winHeight = 720;
        	// 	int fbWidth = 2560, fbHeight = 1440;
        	// 	float pxRatio = 2;
            //
        	// 	// glfwGetCursorPos(window, &mx, &my);
        	// 	// glfwGetWindowSize(window, &winWidth, &winHeight);
        	// 	// glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
        	// 	// // Calculate pixel ration for hi-dpi devices.
        	// 	// pxRatio = (float)fbWidth / (float)winWidth;
            //
        	// 	// Update and render
        	// 	// glViewport(0, 0, fbWidth, fbHeight);
        	// 	// glClearColor(0,0,0,1);
        	// 	// glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
            //     min.x *= pxRatio;
            //     min.y *= pxRatio;
            //     max.x *= pxRatio;
            //     max.y *= pxRatio;
            //
            //     glViewport(min.x, fbHeight - max.y, max.x - min.x, max.y - min.y);
            //     // Create Vertex Array Object
            //     GLuint vao;
            //     glGenVertexArrays(1, &vao);
            //     glBindVertexArray(vao);
            //
            //     // std::cout << "vao: " << vao << std::endl;
            //
            //     // Create a Vertex Buffer Object and copy the vertex data to it
            //     GLuint vbo;
            //     glGenBuffers(1, &vbo);
            //
            //     GLfloat vertices[] = {
            //         -1.0f,  1.0f, 1.0f, 0.0f, 0.0f, // Top-left
            //          1.0f,  1.0f, 0.0f, 1.0f, 0.0f, // Top-right
            //          1.0f, -1.0f, 0.0f, 0.0f, 1.0f, // Bottom-right
            //         -1.0f, -1.0f, 1.0f, 1.0f, 1.0f  // Bottom-left
            //     };
            //
            //     glBindBuffer(GL_ARRAY_BUFFER, vbo);
            //     glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
            //
            //     // Create an element array
            //     GLuint ebo;
            //     glGenBuffers(1, &ebo);
            //
            //     GLuint elements[] = {
            //         0, 1, 2,
            //         2, 3, 0
            //     };
            //
            //     glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
            //     glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
            //
            //     // Create and compile the vertex shader
            //     GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
            //     glShaderSource(vertexShader, 1, &vertexSource, NULL);
            //     glCompileShader(vertexShader);
            //
            //     // Create and compile the fragment shader
            //     GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
            //     glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
            //     glCompileShader(fragmentShader);
            //
            //     // Link the vertex and fragment shader into a shader program
            //     GLuint shaderProgram = glCreateProgram();
            //     glAttachShader(shaderProgram, vertexShader);
            //     glAttachShader(shaderProgram, fragmentShader);
            //     glBindFragDataLocation(shaderProgram, 0, "outColor");
            //     glLinkProgram(shaderProgram);
            //     glUseProgram(shaderProgram);
            //
            //     // Specify the layout of the vertex data
            //     GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
            //     // std::cout << "posAttrib: " << posAttrib << std::endl;
            //     // std::cout << "posAttrib: " << glGetAttribLocation(shaderProgram, "color") << std::endl;
            //     glEnableVertexAttribArray(posAttrib);
            //     glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), 0);
            //
            //     GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
            //     glEnableVertexAttribArray(colAttrib);
            //     glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat)));
            //     // Clear the screen to black
            //     // glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
            //     // glClear(GL_COLOR_BUFFER_BIT);
            //
            //     // Draw a rectangle from the 2 triangles using 6 indices
            //     glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
            //
            //     glViewport(0,0,fbWidth,fbHeight);
            // });
            if (ImGui::IsItemActive()) {
                std::cout << "Canvas active" << std::endl;
            }
            if (ImGui::IsItemHovered()) {
                std::cout << "Canvas hovered" << std::endl;
            }
        }

        // // 2. Show another simple window, this time using an explicit Begin/End pair
        // if (show_another_window)
        // {
        //     ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
        //     ImGui::Begin("Another Window", &show_another_window);
        //     ImGui::Text("Hello");
        //     ImGui::End();
        // }
        //
        // // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
        // if (show_test_window)
        // {
        //     ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
        //     ImGui::ShowTestWindow(&show_test_window);
        // }

        // Rendering
        // int display_w, display_h;
        // glfwGetFramebufferSize(window, &display_w, &display_h);
        // glViewport(0, 0, display_w, display_h);
        // glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
        // glClear(GL_COLOR_BUFFER_BIT);
        // Create Vertex Array Object
  // GLuint vao;
  // glGenVertexArrays(1, &vao);
  // glBindVertexArray(vao);
  //
  // std::cout << "vao: " << vao << std::endl;
  //
  // // Create a Vertex Buffer Object and copy the vertex data to it
  // GLuint vbo;
  // glGenBuffers(1, &vbo);
  //
  // GLfloat vertices[] = {
  //     -0.5f,  0.5f, 1.0f, 0.0f, 0.0f, // Top-left
  //      0.5f,  0.5f, 0.0f, 1.0f, 0.0f, // Top-right
  //      0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right
  //     -0.5f, -0.5f, 1.0f, 1.0f, 1.0f  // Bottom-left
  // };
  //
  // glBindBuffer(GL_ARRAY_BUFFER, vbo);
  // glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
  //
  // // Create an element array
  // GLuint ebo;
  // glGenBuffers(1, &ebo);
  //
  // GLuint elements[] = {
  //     0, 1, 2,
  //     2, 3, 0
  // };
  //
  // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
  // glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
  //
  // // Create and compile the vertex shader
  // GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
  // glShaderSource(vertexShader, 1, &vertexSource, NULL);
  // glCompileShader(vertexShader);
  //
  // // Create and compile the fragment shader
  // GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
  // glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
  // glCompileShader(fragmentShader);
  //
  // // Link the vertex and fragment shader into a shader program
  // GLuint shaderProgram = glCreateProgram();
  // glAttachShader(shaderProgram, vertexShader);
  // glAttachShader(shaderProgram, fragmentShader);
  // glBindFragDataLocation(shaderProgram, 0, "outColor");
  // glLinkProgram(shaderProgram);
  // glUseProgram(shaderProgram);
  //
  // // Specify the layout of the vertex data
  // GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
  // std::cout << "posAttrib: " << posAttrib << std::endl;
  // std::cout << "posAttrib: " << glGetAttribLocation(shaderProgram, "color") << std::endl;
  // glEnableVertexAttribArray(posAttrib);
  // glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), 0);
  //
  // GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
  // glEnableVertexAttribArray(colAttrib);
  // glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat)));
  // // Clear the screen to black
  // glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
  // glClear(GL_COLOR_BUFFER_BIT);
  //
  //         // Draw a rectangle from the 2 triangles using 6 indices
  //         glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        ImGui::Render();
        glfwSwapBuffers(window);
    }

    // Cleanup
    ImGui_ImplGlfwGL3_Shutdown();
    glfwTerminate();

    return 0;
}