text:
<file_sep>#include <iostream>
#include <cassert>

/**
 * @brief A prototype for a unit test
 */
int gcd(int orig_a, int orig_b)
{
  int a = orig_a;
  int b = orig_b;
  /* @pre: a >= 1, b >= 1 */
  while (a != b) {
    /* LI: a, b both divisible by gcd(orig_a, orig_b) */
    if (a > b)
        a = a - b;
    else /* b > a */
        b = b - a;
    /* LI: a, b both divisible by gcd(orig_a, orig_b) */
  }
  /* @post: gcd(orig_a, orig_b) == a */
  return a;
}

int main()
{
  std:: cout << gcd(48, 64) << "\n";
  return 0;
}
<file_sep># CME 212: Lecture 09

## Abstraction Functions and Representation Invariants

Lecture notes available on [Canvas](https://canvas.stanford.edu/courses/74508/files/folder/Notes?preview=2604872).

Loop invariants example is in file [loop.cpp](src/loop.cpp).

<file_sep># CME 212: Lecture 12

## Inheritance and Polymorphism ##

Inheritance is a fundamental motif in object oriented programming.
It allows a class to reuse code of another class and in that way
inherit member variables and methods from that class.
The inheritance can be described as an *is-a* relationship. For
example, a triangle is a shape, or a student is a scholar. Let us explain
basics of inheritance in a simple example. Consider the class `Rectangle`
```c++
class Rectangle
{
public:
  Rectangle(double width, double length)
    : width_(width),
      length_(length),
      area_(width_*length_)
  {
  }

  ~Rectangle()
  {
  }

  /// Same method exists in Circle class.
  double getArea()
  {
    return area_;
  }

private:
  double width_;
  double length_;
  double area_;  ///< Same member exists in Circle class
};
```
and the class `Circle`
(see [inheritance_none.cpp](src/inheritance_none.cpp))
```c++
class Circle
{
public:
  Circle(double x, double y, double radius)
    : radius_(radius),
      area_(radius_*radius_*M_PI)
  {
  }

  ~Circle(){}

  /// Same method exists in Rectangle class.
  double getArea()
  {
    return area_;
  }

private:
  double radius_;
  double area_;  ///< Same member exists in Circle class
};
```
Each class represents a shape, has a member variable `area_`,
and has a method `getArea()`. If we want to add more shapes (like triangles, pentagons, etc.),
we would need to replicate the same variable and the same method
for those shapes, too, since all shapes have an area. If we
want to add another general shape property (e.g. color), we would
have to add it to all classes representing shapes that we created.
This will cause our code to grow quickly as we add more features,
and that will in turn make maintenance of our code expensive.

### Inheritance ###

The inheritance allows us to implement all the common features
of our objects in a *base* class. When we derive a class from the base class,
the *derived* class will inherit the common features implemented in the base,
so we will need to implement only the features specific to the *derived* class.
This approach leads to a leaner and easier to maintain code.
For example, we can create class `Shape` like this:
```c++
class Shape
{
public:
  Shape()
    : area_(0.0)
  {
    std::cout << "Invoking Shape constructor ...\n";
  }

  ~Shape()
  {
    std::cout << "Invoking Shape destructor ...\n";
  }

  double getArea()
  {
    return area_;
  }

protected: // protected instead of private
  double area_;
};
```
Note that we defined variable `area_` as a *protected* rather than
*private* member. Now, we can create a class `Circle`, which
*is a* `Shape` by declaring it as
```c++
Circle : public Shape
{
public:
  Circle(double radius)
    : radius_(radius)
  {
    std::cout << "Invoking Circle constructor ...\n";
    area_ = radius_*radius_*M_PI;
  }

  ~Circle()
  {
    std::cout << "Invoking Circle destructor ...\n";
  }

  double getRadius()
  {
    return radius_;
  }

private:
  double radius_;
};
```
The class `Circle` will inherit member variables and functions from
`Shape`. All public methods and variables from `Shape` will also
be public in `Circle`. We defined variable `area_` as *protected* so
it is accessible by `Circle` and other classes that inherit from `Shape`.
If `area_` was private, `Circle` would inherit it, but it would not
be able to access it.
Note that accessibility in C++ is based on classes and not objects.
Therefore instances of the same class can access each other's private
members.
We can implement class `Rectangle` to inherit from `Shape` in a similar
manner. The complete code is provided in
[inheritance_public.cpp](src/inheritance_public.cpp). Let us look
at the execution of the following code calling shape classes:
```c++
#include <iostream>

int main()
{
  Circle*    pc = new Circle(1.0);
  Rectangle* pr = new Rectangle(3.0, 2.0);

  std::cout << "\n";
  std::cout << "Circle area = " << pc->getArea() << "\n";
  std::cout << "Circle radius = " << pc->getRadius() << "\n";
  std::cout << "Rectangle area = " << pr->getArea() << "\n";
  std::cout << "\n";

  delete pc;
  delete pr;

  return 0;
}
```
The output looks like this:
```
$ ./a.out
Invoking Shape constructor ...
Invoking Circle constructor ...
Invoking Shape constructor ...
Invoking Rectangle constructor ...

Circle area = 3.14159
Circle radius = 1
Rectangle area = 6

Invoking Circle destructor ...
Invoking Shape destructor ...
Invoking Rectangle destructor ...
Invoking Shape destructor ...
$
```
Let us take a look at what is going on here. We first invoke
constructors for `Circle` and `Rectangle`. Each derived
class constructor will call the base class constructor,
which will be executed before the derived class constructor.
After we created a `Circle` and a `Rectangle`, we
can access their own and inherited public features alike.
When the destructor of a derived class is called, it will
call the destructor of the base class. The base class destructor
will be executed after the derived class destructor.
Let us now try something different. Consider following code:
```c++
int main()
{
  Shape* pc = new Circle(2.0);

  std::cout << "\n";
  std::cout << "Circle area = " << pc->getArea() << "\n";
  //std::cout << "Circle radius = " << pc->getRadius() << "\n"; // Compiler error
  std::cout << "\n";

  delete pc; ///< Shape is destroyed, but Circle is not, memory leak!

  return 0;
}
```
We create a `Circle` on the heap, but we access it through
a pointer to `Shape`. The output of this code looks like this:
```
Invoking Shape constructor ...
Invoking Circle constructor ...

Circle area = 12.5664

Invoking Shape destructor ...
```
With pointer to `Shape` as our handle to `Circle`, we can
access only methods that `Circle` inherited from `Shape`.
The compiler will not be aware that the object behind
pointer `pc` is actually a `Circle`. When we try to delete
the object, only `Shape` destructor will be invoked; the `Circle`
part of the object will remain on the heap, only now without a
pointer to access it. We got ourselves a memory leak.

### Virtual Functions and Polymorphism ###

Let us now define `Shape` destructor as a virtual function:
```c++
  virtual ~Shape()
  {
    std::cout << "Invoking Shape destructor ...\n";
  }

```
If we recompile and rerun the earlier code with redefined `Shape`
destructor, the new output will be:
```
Invoking Shape constructor ...
Invoking Circle constructor ...

Circle area = 12.5664

Invoking Circle destructor ...
Invoking Shape destructor ...
```
Even though `Circle` was hiding behind a `Shape` pointer,
the executable was able to figure out at the runtime that
the `Shape` pointer was pointing to a `Circle`. With this
small modification to our code, we can now access any shape
object using only `Shape` pointer without introducing a memory
leak. Furthermore, we are able to override any other
virtual function in the derived class, and
access it through the pointer to the base class. This is
called *runtime polymorphism*. Take a look at the code in
[inheritance_public_polymorphism.cpp](src/inheritance_public_polymorphism.cpp).
There, both, the base class destructor and the `getArea()` method
are virtual. That allows us to override `getArea()` in `Rectangle`
class, for example. The output this code produces looks like:
```
$ ./a.out
Invoking Shape constructor ...
Invoking Shape constructor ...
Invoking Circle constructor ...
Invoking Shape constructor ...
Invoking Rectangle constructor ...

No shape specified; area set to 0
Circle area = 3.14159
Rectangle area =  (using overriden getArea) 6

Invoking Shape destructor ...
Invoking Circle destructor ...
Invoking Shape destructor ...
Invoking Rectangle destructor ...
Invoking Shape destructor ...
$
```
This is particularly helpful when we want to specify default
behavior in the base class, but still be able to override the
default in some derived classes.

### Pure Virtual Methods ###

Sometimes we want to force developers to follow certain standards.
For example, we may want every shape to provide method `getArea()`.
One way to accomplish that is to define base class method `getArea()`
as a pure virtual method. The declaration would look like this:
```c++
virtual double getArea() = 0;
```
Assigning zero to the declaration of a virtual method is C++ way
of saying this is a *pure virtual* method. We do not need to implement
a pure virtual method in the base class. On the other hand, if we
do not implement pure virtual method in any of the derived classes,
the compiler will return an error. An example of using a pure
virtual method is given in [inheritance_pure_virtual.cpp](src/inheritance_pure_virtual.cpp).
A class that has no data and only pure virtual methods is called
an abstract class or an interface class. An example of abstract
`Shape` class and its use is provided in
[inheritance_interface.cpp](src/inheritance_interface.cpp).

### Reading ###

* [Public, protected and private inheritance](https://stackoverflow.com/questions/860339/difference-between-private-public-and-protected-inheritance)
* [Virtual functions](https://stackoverflow.com/questions/2391679/why-do-we-need-virtual-functions-in-c)
* [Interfaces in C++](https://stackoverflow.com/questions/1216750/how-can-i-simulate-interfaces-in-c)

<file_sep># CME212
[Syllabus](https://github.com/cme212/course/blob/master/syllabus.md#cme-212---winter-2019)

<!-- BS : [<NAME>up's Programming in C++](https://g.co/kgs/jQjpRv). -->

## Schedule (WIP)
(If the links are dead, they are intended to simply point to files on Canvas.)
### Week 0
  - Lecture 0 (2019-01-08)
    - [Object size, alignment, declarations, scope, narrowing, lifetime of an object](https://canvas.stanford.edu/files/3928214/download?download_frd=1).
    - [Pointers, arrays, pointer arithmetic, and `const`](https://canvas.stanford.edu/files/3928884/download?download_frd=1).
  - Lecture 1 (2019-01-10)
    - [Debugging in C++](https://github.com/cme212/course/blob/master/notes/lecture-02/debugging.md).
    - [Proxy design patterns](https://github.com/cme212/course/blob/master/notes/lecture-03/proxy.md).
    - [Development tools (Make)](https://github.com/cme212/course/blob/master/notes/lecture-03/make.md)     (and possibly doxygen).
  - [Exercise 0](https://canvas.stanford.edu/files/3926995/download?download_frd=1)                 due Tuesday January 15th at 4:30 P.M. P.S.T.
### Week 1
 - Lecture 2 (2019-01-15)
   - [Pointers and ownership, references, l/rvalue references, and
     examples with templates](https://canvas.stanford.edu/files/3973718/download?download_frd=1).
   - [Lambda expressions and function objects](https://canvas.stanford.edu/files/3973719/download?download_frd=1).
 - Lecture 3 (2019-01-17)
   - [Pre/post conditions, consistent/minimal specifications,
     templates](https://github.com/cme212/course/blob/master/notes/lecture-06/specifications.md).
   - [HW0](https://canvas.stanford.edu/files/3908090/download?download_frd=1) due Friday at 4:30 P.M. P.S.T.
### Week 2
 - Lecture 4 (2019-01-22)
   - Iterators, functors, layout of structs, (bit) fields, unions, examples of
   operator overloading via `Array` class.
 - Lecture 5 (2019-01-24)
   - Abstraction functions and Representation Invariants;
   - Software Testing
 - EX1 due Friday at 4:30 P.M. P.S.T.
### Week 3
 - Lecture 6 (2019-01-29)
   - Free Store memory allocation, RAII, Allocators, List and Type
   Conversions.
   - Exception Handling part 1 (exceptions as control flow, how to define exceptions)
 - Lecture 7 (2019-01-31): Inheritance and Polymorphism
 - HW1 due Friday at 4:30 P.M. P.S.T.
### Week 4
 - Lecture 8 (2019-02-05)
   - Exception Handling part 2 (enforcing invariants);
   - construction, cleanup, and copy initialization.
 - Lecture 9 (2019-02-07)
   - Graph Remove_*; inline functions and typedefs.
 - EX2 due Friday at 4:30 P.M. P.S.T.
### Week 5
 - Lecture 10 (2019-02-12)
   - Defining copy and move semantics, delegating constructors, entanglement, slicing.
   - Template programming part 1 (two phase translation, function and class templates, template paramaters as return types, parameter deduction)
 - Lecture 11 (2019-02-14)
   - Floating point, Under/overflow, relative error, machine tolerance
 - HW2 due Friday at 4:30 P.M. P.S.T.
### Week 6
 - Lecture 12 (2019-02-19)
   - Template Programming part 2

     (non-type template parameters, variadic template parameters, template template parameters);
   - Perfect forwarding, `enable_if`, Concepts and Metafunctions, compile-time programming.
 - Lecture 13
   - Loop invariants, `thrust::transform_iterator`, Cachegrind, optimization
 - EX3 due Friday at 4:30 P.M. P.S.T.
### Week 7
 - Lecture 14
   - Generic programming
 - Lecture 15
   - ???
 - HW3 due Friday at 4:30 P.M. P.S.T.
### Week 8
 - Lecture 16
   - Metaprogramming
 - Lecture 17
   - Compiler Optimizations
 - EX4 due Friday at 4:30 P.M. P.S.T.
### Week 9
 - Lecture 18
   - Regular Expressions
 - Lecture 19
   - Review
 - HW4 due Friday at 4:30 P.M. P.S.T.

languages: Markdown C++

repo_language: Markdown


text:
<file_sep>package codingPrepartatiaon;

import java.util.Scanner;

public class PalindromeNumber {

	public static void main(String[] args) {
		Scanner input =new Scanner(System.in);
		System.out.println("Enter a Number to check  it is palindrome or not : ");
		int givenNumber	=input.nextInt();

		int r,res=0,temp=givenNumber;
		while(givenNumber>0) {

			r=givenNumber%10;
			res=res*10+r;
			givenNumber=givenNumber/10;
		}

		if(res==temp)
			System.out.println("Given Number is a Palindrome");
		else
			System.out.println("Given Number is Not a Palindrome");
	}

}
<file_sep>package codingPrepartatiaon;

import java.util.Arrays;

public class reverceTheWorld {

	public static void main(String[] args) {

		String s="this world is good";
		String result=reverce(s);

//	        System.out.println(ar1);
	        String[] words = result.split(" ");

	        for(int i=words.length-1;i>=0;i--) {
	        	System.out.print(words[i]+" ");
	        }
	}

	public static String reverce(String str){
		char ch[]=str.toCharArray();
	    String rev="";
	    for(int i=ch.length-1;i>=0;i--){
	        rev+=ch[i];
	    }
	    return rev;
	}

	}

<file_sep>package codingPrepartatiaon;

import java.util.Scanner;

public class Factorial {

	public static void main(String[] args) {
		System.out.print("Type number to to find the factorial of given number");
		Scanner input =new Scanner(System.in);
		int number=input.nextInt();

		int fact=1;
		for(int i=1;i<=number;i++) {
			fact=fact*i;
		}

		System.out.println("Factorial of Given Number is : "+fact);

	}

}
<file_sep>package codingPrepartatiaon;

import java.util.Scanner;

public class Palindrome {

	public static void main(String[] args) {
Scanner scan=new Scanner(System.in);

		System.out.println("Enter a string to reverse !");
		String str=scan.nextLine();

		String temp="";

		for(int i=str.length()-1;i>=0;i--) {
			temp+=str.charAt(i);
		}

		if(str.equals(temp))
			System.out.println("Given String is Palindrome !");
		else
			System.out.println("Given String is Not Palindrome !");
	}

}
<file_sep>package collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

public class arraylist1 {

	public static void main(String[] args) {
//			ArrayList<Integer> array=new ArrayList<Integer>();

			 HashSet<Integer> array = new HashSet<Integer>();

			    // Creating an Array of HashSet size
//			    String[] array = new String[hashset.size()];
			    // Converting HashSet to Array using toArray() method
//			    hashset.toArray(array);

			array.add(1);
			array.add(2);
			array.add(9);
			array.add(3);
			array.add(17);
	        array.add(6);
	        array.add(9);
	        array.add(7);
	        array.remove(7);

	     // Converting LinkedList to ArrayList
		    List<Integer> list = new ArrayList<Integer>(array);

	        Collections.reverse(list);
			for(Integer c:array) {
				System.out.println(c+" ");
			}
			System.out.println(array.size());
			if(array.contains(9)) {
				System.out.println("9 is a part of this array");
			}
			else {
				System.out.println("9 is not part of this collection");
			}
//
//			Collections.sort((List<String> array);
//			System.out.println(Arrays.asList(array));
//			System.out.println(array.toArray());
	}

}

branch_name: refs/heads/main

repo_language: Java

repo_name: MadhusudanGT/CodingPratiecs


text:
<repo_name>alitabatabaeiat/Tic-Tac-Toe-iOS<file_sep>/Tic Tac Toe/ViewController.swift
//
//  ViewController.swift
//  Tic Tac Toe
//
//  Created by <NAME> on 9/6/18.
//  Copyright © 2018 <NAME>. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var turnLabel: UILabel!
    var board = Array(repeating: Array(repeating: 0, count: 3), count: 3)
    var activePlayer = 1
    var winner = 0
    var numberOfMoves = 0
    var isSinglePlayer = true

    override func viewDidLoad() {
        super.viewDidLoad()
        setTurnLabel()
    }

    @IBAction func singlePlayerButton(_ sender: Any) {
        if numberOfMoves == 0 {
            isSinglePlayer = true
            setTurnLabel()
        }
    }

    @IBAction func twoPlayerButton(_ sender: Any) {
        if numberOfMoves == 0 {
            isSinglePlayer = false
            setTurnLabel()
        }
    }

    @IBAction func cellOnClick(_ sender: Any) {
        let clickedButton = sender as! UIButton
        play(clickedButton)
    }

    func play(_ clickedButton: UIButton) {
        if clickedButton.currentTitle == nil {
            let row = Int((clickedButton.tag - 1) / 3)
            let col = (clickedButton.tag - 1) % 3
            board[row][col] = activePlayer
            numberOfMoves += 1
            if activePlayer == 1 {
                clickedButton.setTitle("X", for: .normal)
                clickedButton.backgroundColor = UIColor(red: 0/255, green: 84/255, blue: 147/255, alpha: 1)
                activePlayer = 2
            } else {
                clickedButton.setTitle("O", for: .normal)
                clickedButton.backgroundColor = UIColor(red: 115/255, green: 250/255, blue: 121/255, alpha: 1)
                activePlayer = 1
            }
            setTurnLabel()
            findWinner()
            if isSinglePlayer && numberOfMoves < 9 && activePlayer == 2 {
                autoPlay()
            }
        }
    }

    func setTurnLabel() {
        if activePlayer == 2 && !isSinglePlayer {
            turnLabel.text = "Turn: O"
            turnLabel.textColor = UIColor(red: 115/255, green: 250/255, blue: 121/255, alpha: 1)
        } else {
            turnLabel.text = "Turn: X"
            turnLabel.textColor = UIColor(red: 0/255, green: 84/255, blue: 147/255, alpha: 1)
        }

    }

    func findWinner() {
        if (board[0][0] == board[0][1] && board[0][0] == board[0][2] && board[0][0] != 0) {
            winner = board[0][0]
        } else if (board[1][0] == board[1][1] && board[1][0] == board[1][2] && board[1][0] != 0) {
            winner = board[1][0]
        } else if (board[2][0] == board[2][1] && board[2][0] == board[2][2] && board[2][0] != 0) {
            winner = board[2][0]
        } else if (board[0][0] == board[1][0] && board[0][0] == board[2][0] && board[0][0] != 0) {
            winner = board[0][0]
        } else if (board[0][1] == board[1][1] && board[0][1] == board[2][1] && board[0][1] != 0) {
            winner = board[0][1]
        } else if (board[0][2] == board[1][2] && board[0][2] == board[2][2] && board[0][2] != 0) {
            winner = board[0][2]
        } else if (board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] != 0) {
            winner = board[0][0]
        } else if (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] != 0) {
            winner = board[0][2]
        }

        var msg:String?
        if winner == 1 {
            msg = "X is winner"
        } else if winner == 2 {
            msg = "O is winner"
        } else if numberOfMoves == 9 {
            msg = "Tie"
        }
        if msg != nil {
            let alert = UIAlertController(title: "Winner", message: msg, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ok!", style: .default, handler: { (UIAlertAction) -> Void in self.createNewGame()}))
            self.present(alert, animated: true, completion: nil)
        }

    }

    func createNewGame() {
        for view in self.view.subviews as [UIView] {
            if let btn = view as? UIButton {
                if btn.tag > 0 {
                    btn.setTitle(nil, for: .normal)
                    btn.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
                }
            }
        }
        board = Array(repeating: Array(repeating: 0, count: 3), count: 3)
        activePlayer = winner != 0 ? winner : activePlayer == 1 ? 2 : 1
        winner = 0
        numberOfMoves = 0

        setTurnLabel()

        if isSinglePlayer && activePlayer == 2 {
            autoPlay()
        }
    }

    func autoPlay() {
        var emptyCells = [Int]()

        for rowIndex in 0...2 {
            for cellIndex in 0...2 {
                if board[rowIndex][cellIndex] == 0 {
                    emptyCells.append(3 * rowIndex + cellIndex + 1)
                }
            }
        }

        let randomIndex = arc4random_uniform(UInt32(emptyCells.count))
        let cell = emptyCells[Int(randomIndex)]
        for view in self.view.subviews as [UIView] {
            if let btn = view as? UIButton {
                if btn.tag == cell {
                    play(btn)
                }
            }
        }
    }

}

branch_name: refs/heads/master

repo_language: Swift

repo_name: alitabatabaeiat/Tic-Tac-Toe-iOS


text:
<file_sep>bash ./datasets/download_cyclegan_dataset.sh horse2zebra
bash ./datasets/download_cyclegan_dataset.sh apple2orange
bash ./datasets/download_cyclegan_dataset.sh cityscapes

repo_language: Shell


text:
<file_sep>from django.shortcuts import render

def index(request):
    data = {
        'title':'Car listing'
    }
    return render(request, "carlist/carlist.html", data)

def singlecar(request):
    return render(request, "carlist/singlecar.html")
<file_sep>from django.urls import path, include

from . import views

urlpatterns = [
    path('', views.index, name="index"),
    path('about', views.about, name = "about"),
    path('services', views.services, name = "services"),
    path('contactus', views.contact, name = "contact")
]
<file_sep>from django.shortcuts import render

# Create your views here.

def index(request):
    return render(request, 'pages/index.html')

def about(request):
    data = {'title': "About Us"}
    return render(request, 'pages/about.html', data)

def services(request):
    data = {'title': "Our Services"}
    return render(request, 'pages/services.html', data)

def contact(request):
    data = {'title': "Contact Us"}
    return render(request, 'pages/contact.html', data)<file_sep>from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='carslist'),
    path('<int:carslist_id>', views.singlecar, name = "carlist")
]<file_sep>from django.contrib import admin

from .models import CarManager
admin.site.register(CarManager)

repo_language: Python

repo_name: RaisaKulakovska/Some-Django-Project


text:
<repo_name>leomicheloni/qunit-phantom-grunt<file_sep>/test/fixture.js
module("calculadora");

var calculadora = new Calculadora();

test("suma", function(assert){
	var resultado = calculadora.sumar(4,3);
	equal(resultado, 7);
});<file_sep>/README.md
#Qunit Phantom Grunt Example project

A short example on how to convine Qunit, PhantomJS and Gruntjs for continuos testing in Javascript.

##How to run?

First at all you must install dependencies, node and bower.
Go to the terminal and in the directory root type `bower install` and then `npm install`
Ready, you just need to start grunt, type `grunt`
Now you can develop using continuos testing, try to modify the test file fixture.js and the tests will run automatically.

[There's a description (in spanish)](http://www.leomicheloni.com/post/2014/12/23/Testing-continuo-con-Qunit-Phantom-y-Grunt.aspx)

Enjoy.

languages: Markdown JavaScript

repo_name: leomicheloni/qunit-phantom-grunt


text:
<file_sep>const key       = '<KEY>'
const button    = document.querySelector('.submit')
const buttonC   = document.querySelector('.celc')
const buttonF   = document.querySelector('.faren')
const buttonAdd = document.querySelector('.add')
let list        = document.querySelector('.list-group')
let input       = document.querySelector('.input')

const temp_1      = document.getElementById('temperature_1')
const temp_3      = document.getElementById('temperature_3')
const temp_4      = document.getElementById('temperature_4')
const temp_5      = document.getElementById('temperature_5')
const temp_6      = document.getElementById('temperature_6')

const loc_1       = document.getElementById('location_1')

const data_2      = document.getElementById('data_2')
const data_3      = document.getElementById('data_3')
const data_4      = document.getElementById('data_4')
const data_5      = document.getElementById('data_5')

const icon        = document.getElementById('icon-main')
const icon_2      = document.getElementById('icon_2')
const icon_3      = document.getElementById('icon_3')
const icon_4      = document.getElementById('icon_4')
const icon_5      = document.getElementById('icon_5')

const humidity_1  = document.getElementById('humidity_1')
const options   = { weekday: 'long', day: 'numeric' }

button.addEventListener('click',()=>{
    let city = input.value
        const updateByCity = (x) => {
            let url = "https://api.openweathermap.org/data/2.5/forecast?" +
	            "q=" + x +
                "&APPID=" + key
                sendRequest(url)
        }
        input.value = ''
    updateByCity(city)
})

buttonAdd.addEventListener('click', ()=>{
   let cityAdd = input.value
        list.insertAdjacentHTML('beforeend',
        '
'+ cityAdd +'
 ')
     input.value = ''
})

const Faren = (c) => Math.round(c * (9/5) - 459.67)

const Celc = (k) => Math.round(k - 273.15)

const sendRequest = (url) => {
    const link = fetch(url)
        .then(data => data.json())
            .then(data =>{
        const main = () => {
            let weather = {}
                let second  = data.list[5].dt_txt
                let third   = data.list[10].dt_txt
                let fourth  = data.list[18].dt_txt
                let fifth   = data.list[26].dt_txt
                         weather.icon        = data.list[0].weather[0].id
                         weather.icon_2      = data.list[5].weather[0].id
                         weather.icon_3      = data.list[13].weather[0].id
                         weather.icon_4      = data.list[21].weather[0].id
                         weather.icon_5      = data.list[29].weather[0].id
                         weather.humidity    = data.list[0].main.humidity
                         weather.loc         = data.city.name
                         weather.data_2      = new Date(second).toLocaleString('ru', options)
                         weather.data_3      = new Date(third).toLocaleString('ru', options)
                         weather.data_4      = new Date(fourth).toLocaleString('ru', options)
                         weather.data_5      = new Date(fifth).toLocaleString('ru', options)
                         weather.temp_1      = Celc(data.list[1].main.temp)
                         weather.temp_3      = Celc(data.list[10].main.temp)
                         weather.temp_4      = Celc(data.list[18].main.temp)
                         weather.temp_5      = Celc(data.list[26].main.temp)
                         weather.temp_6      = Celc(data.list[34].main.temp)
                    update(weather)

        }
            buttonF.addEventListener('click', ()=> {
                let weather = {}
                let second  = data.list[4].dt_txt
                let third   = data.list[10].dt_txt
                let fourth  = data.list[18].dt_txt
                let fifth   = data.list[26].dt_txt
                         weather.icon        = data.list[0].weather[0].id
                         weather.icon_2      = data.list[5].weather[0].id
                         weather.icon_3      = data.list[13].weather[0].id
                         weather.icon_4      = data.list[21].weather[0].id
                         weather.icon_5      = data.list[29].weather[0].id
                         weather.humidity  = data.list[0].main.humidity
                         weather.loc       = data.city.name
                         weather.data_2    = new Date(second).toLocaleString('ru', options)
                         weather.data_3    = new Date(third).toLocaleString('ru', options)
                         weather.data_4    = new Date(fourth).toLocaleString('ru', options)
                         weather.data_5    = new Date(fifth).toLocaleString('ru', options)
                         weather.temp_1    = Faren(data.list[1].main.temp)
                         weather.temp_3    = Faren(data.list[10].main.temp)
                         weather.temp_4    = Faren(data.list[18].main.temp)
                         weather.temp_5    = Faren(data.list[26].main.temp)
                         weather.temp_6    = Faren(data.list[34].main.temp)
                    update(weather)
                })

            buttonC.addEventListener('click',()=>{
                    main()
                })
    main()
})
        }

const update = (weather) => {
    data_2.innerHTML      = weather.data_2
    data_3.innerHTML      = weather.data_3
    data_4.innerHTML      = weather.data_4
    data_5.innerHTML      = weather.data_5

    temp_1.innerHTML      = weather.temp_1
    temp_3.innerHTML      = weather.temp_3
    temp_4.innerHTML      = weather.temp_4
    temp_5.innerHTML      = weather.temp_5
    temp_6.innerHTML      = weather.temp_6

    loc_1.innerHTML         = weather.loc
    icon.src                = 'img/' + weather.icon + '.svg'
    icon_2.src              = 'img/' + weather.icon_2 + '.svg'
    icon_3.src              = 'img/' + weather.icon_3 + '.svg'
    icon_4.src              = 'img/' + weather.icon_4 + '.svg'
    icon_5.src              = 'img/' + weather.icon_5 + '.svg'

    humidity_1.innerHTML  = weather.humidity

}

const showPosition = (position) => {
    updateByGeo(position.coords.latitude, position.coords.longitude)
}

const updateByGeo = (lat, lon) => {
    let url = 'https://api.openweathermap.org/data/2.5/forecast?'
    +
	"lat=" + lat +
	"&lon=" + lon +
	"&APPID=" + key
    sendRequest(url)
}

    window.addEventListener('load', ()=>{
        if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(showPosition)
        } else {
            alert('No internet connection')
        }
    })

repo_language: JavaScript

repo_name: SerafimPoch/weather


text:
<repo_name>oblivion2009/FaceRecognition-master<file_sep>/FaceRecognition/ImageWidget.cpp
/*
## 创建标识：第五届全国大学生物联网大赛人脸识别demo

## 创建时间：2017-12-20

## 函数功能描述：人脸识别控件

## 开发环境
[Windows10+VS2015+Qt5.6+opencv2.4.11]
**开发语言C++**
**编译环境x64**

## 环境配置
**配置opencv2.4.11的环境**
**配置Qt5.6+VS2015的环境**
**项目属性-链接器-输入-附加依赖项 需要添加相关lib文件

## 技术支持
(http://www.greenorbs.com/)
*/

#include "ImageWidget.h"

ImageWidget::ImageWidget(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);

	ui.removeButton->setIcon(QIcon("icon\\cross.png"));
	ui.removeButton->setIconSize(QSize(30, 30));
	ui.removeButton->setFixedSize(ui.removeButton->iconSize());
	ui.removeButton->setFlat(true);
}

ImageWidget::~ImageWidget()
{
}

void ImageWidget::setPixmap(QPixmap& pixmap)
{

	QSize qImageSize = pixmap.size();
	QSize qLabelSize = ui.label->size();
	double dWidthRatio = 1.0*qImageSize.width() / qLabelSize.width();
	double dHeightRatio = 1.0*qImageSize.height() / qLabelSize.height();
	if (dWidthRatio > dHeightRatio)
	{
		pixmap = pixmap.scaledToWidth(qLabelSize.width());
	}
	else
	{
		pixmap = pixmap.scaledToHeight(qLabelSize.height());
	}

	ui.label->setPixmap(pixmap);
	ui.label->setAlignment(Qt::AlignCenter);
	ui.label->show();
}

void ImageWidget::setText(QString qstring)
{
	text = qstring;
}

QPushButton* ImageWidget::getRemoveBtn()
{
	return ui.removeButton;
}

<file_sep>/FaceRecognition/GeneratedFiles/ui_FaceRecognition.h
/********************************************************************************
** Form generated from reading UI file 'FaceRecognition.ui'
**
** Created by: Qt User Interface Compiler version 5.6.3
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_FACERECOGNITION_H
#define UI_FACERECOGNITION_H

#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QListWidget>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QTextBrowser>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>

QT_BEGIN_NAMESPACE

class Ui_FaceRecognitionClass
{
public:
    QWidget *centralWidget;
    QGridLayout *gridLayout_2;
    QGridLayout *gridLayout;
    QHBoxLayout *horizontalLayout;
    QVBoxLayout *verticalLayout_11;
    QPushButton *uploadButton1;
    QListWidget *imglistWidget;
    QVBoxLayout *verticalLayout_7;
    QHBoxLayout *horizontalLayout_4;
    QPushButton *uploadButton2;
    QLabel *imglabel2;
    QHBoxLayout *horizontalLayout_7;
    QPushButton *faceCompare;
    QVBoxLayout *verticalLayout_2;
    QLabel *resultLabel;
    QTextBrowser *resultBrowser;
    QMenuBar *menuBar;
    QToolBar *mainToolBar;
    QStatusBar *statusBar;

    void setupUi(QMainWindow *FaceRecognitionClass)
    {
        if (FaceRecognitionClass->objectName().isEmpty())
            FaceRecognitionClass->setObjectName(QStringLiteral("FaceRecognitionClass"));
        FaceRecognitionClass->resize(1312, 900);
        centralWidget = new QWidget(FaceRecognitionClass);
        centralWidget->setObjectName(QStringLiteral("centralWidget"));
        gridLayout_2 = new QGridLayout(centralWidget);
        gridLayout_2->setSpacing(6);
        gridLayout_2->setContentsMargins(11, 11, 11, 11);
        gridLayout_2->setObjectName(QStringLiteral("gridLayout_2"));
        gridLayout = new QGridLayout();
        gridLayout->setSpacing(6);
        gridLayout->setObjectName(QStringLiteral("gridLayout"));
        horizontalLayout = new QHBoxLayout();
        horizontalLayout->setSpacing(6);
        horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
        verticalLayout_11 = new QVBoxLayout();
        verticalLayout_11->setSpacing(6);
        verticalLayout_11->setObjectName(QStringLiteral("verticalLayout_11"));
        uploadButton1 = new QPushButton(centralWidget);
        uploadButton1->setObjectName(QStringLiteral("uploadButton1"));
        uploadButton1->setMaximumSize(QSize(250, 16777215));
        QFont font;
        font.setFamily(QString::fromUtf8("\345\256\213\344\275\223"));
        font.setPointSize(16);
        uploadButton1->setFont(font);

        verticalLayout_11->addWidget(uploadButton1, 0, Qt::AlignHCenter);

        imglistWidget = new QListWidget(centralWidget);
        imglistWidget->setObjectName(QStringLiteral("imglistWidget"));
        imglistWidget->setEnabled(true);
        imglistWidget->setMinimumSize(QSize(640, 360));
        imglistWidget->setMaximumSize(QSize(16777215, 16777215));

        verticalLayout_11->addWidget(imglistWidget);

        horizontalLayout->addLayout(verticalLayout_11);

        verticalLayout_7 = new QVBoxLayout();
        verticalLayout_7->setSpacing(6);
        verticalLayout_7->setObjectName(QStringLiteral("verticalLayout_7"));
        horizontalLayout_4 = new QHBoxLayout();
        horizontalLayout_4->setSpacing(6);
        horizontalLayout_4->setObjectName(QStringLiteral("horizontalLayout_4"));
        uploadButton2 = new QPushButton(centralWidget);
        uploadButton2->setObjectName(QStringLiteral("uploadButton2"));
        uploadButton2->setMaximumSize(QSize(180, 16777215));
        uploadButton2->setFont(font);

        horizontalLayout_4->addWidget(uploadButton2);

        verticalLayout_7->addLayout(horizontalLayout_4);

        imglabel2 = new QLabel(centralWidget);
        imglabel2->setObjectName(QStringLiteral("imglabel2"));
        QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        sizePolicy.setHorizontalStretch(0);
        sizePolicy.setVerticalStretch(0);
        sizePolicy.setHeightForWidth(imglabel2->sizePolicy().hasHeightForWidth());
        imglabel2->setSizePolicy(sizePolicy);
        imglabel2->setMinimumSize(QSize(640, 360));
        imglabel2->setMaximumSize(QSize(16777215, 16777215));
        imglabel2->setStyleSheet(QStringLiteral("background-color: rgb(0, 0, 0);"));

        verticalLayout_7->addWidget(imglabel2);

        horizontalLayout->addLayout(verticalLayout_7);

        gridLayout->addLayout(horizontalLayout, 0, 0, 1, 1);

        gridLayout_2->addLayout(gridLayout, 0, 0, 1, 1);

        horizontalLayout_7 = new QHBoxLayout();
        horizontalLayout_7->setSpacing(6);
        horizontalLayout_7->setObjectName(QStringLiteral("horizontalLayout_7"));
        horizontalLayout_7->setContentsMargins(-1, 10, -1, -1);
        faceCompare = new QPushButton(centralWidget);
        faceCompare->setObjectName(QStringLiteral("faceCompare"));
        faceCompare->setMaximumSize(QSize(200, 16777215));
        faceCompare->setFont(font);
        faceCompare->setStyleSheet(QStringLiteral(""));

        horizontalLayout_7->addWidget(faceCompare);

        gridLayout_2->addLayout(horizontalLayout_7, 1, 0, 1, 1);

        verticalLayout_2 = new QVBoxLayout();
        verticalLayout_2->setSpacing(6);
        verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2"));
        resultLabel = new QLabel(centralWidget);
        resultLabel->setObjectName(QStringLiteral("resultLabel"));
        resultLabel->setTextFormat(Qt::AutoText);

        verticalLayout_2->addWidget(resultLabel);

        resultBrowser = new QTextBrowser(centralWidget);
        resultBrowser->setObjectName(QStringLiteral("resultBrowser"));
        QFont font1;
        font1.setFamily(QString::fromUtf8("\345\256\213\344\275\223"));
        font1.setPointSize(12);
        resultBrowser->setFont(font1);

        verticalLayout_2->addWidget(resultBrowser);

        gridLayout_2->addLayout(verticalLayout_2, 2, 0, 1, 1);

        FaceRecognitionClass->setCentralWidget(centralWidget);
        menuBar = new QMenuBar(FaceRecognitionClass);
        menuBar->setObjectName(QStringLiteral("menuBar"));
        menuBar->setGeometry(QRect(0, 0, 1312, 23));
        FaceRecognitionClass->setMenuBar(menuBar);
        mainToolBar = new QToolBar(FaceRecognitionClass);
        mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
        FaceRecognitionClass->addToolBar(Qt::TopToolBarArea, mainToolBar);
        statusBar = new QStatusBar(FaceRecognitionClass);
        statusBar->setObjectName(QStringLiteral("statusBar"));
        FaceRecognitionClass->setStatusBar(statusBar);

        retranslateUi(FaceRecognitionClass);

        QMetaObject::connectSlotsByName(FaceRecognitionClass);
    } // setupUi

    void retranslateUi(QMainWindow *FaceRecognitionClass)
    {
        FaceRecognitionClass->setWindowTitle(QApplication::translate("FaceRecognitionClass", "FaceRecognition", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
        uploadButton1->setToolTip(QApplication::translate("FaceRecognitionClass", "\351\200\211\346\213\251\344\270\200\345\274\240\346\210\226\345\207\240\345\274\240\345\233\276\347\211\207\344\275\234\344\270\272\344\272\272\350\204\270\345\272\223", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
        uploadButton1->setText(QApplication::translate("FaceRecognitionClass", "\350\257\267\351\200\211\346\213\251\344\272\272\350\204\270\345\272\223\345\233\276\347\211\207", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
        uploadButton2->setToolTip(QApplication::translate("FaceRecognitionClass", "\351\200\211\346\213\251\344\270\200\345\274\240\345\233\276\347\211\207\344\270\216\345\257\271\344\272\272\350\204\270\345\272\223\346\257\224\350\276\203", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
        uploadButton2->setText(QApplication::translate("FaceRecognitionClass", "\350\257\267\351\200\211\346\213\251\346\265\213\350\257\225\345\233\276\347\211\207", Q_NULLPTR));
        imglabel2->setText(QString());
        faceCompare->setText(QApplication::translate("FaceRecognitionClass", "\345\274\200\345\247\213", Q_NULLPTR));
        resultLabel->setText(QApplication::translate("FaceRecognitionClass", "\350\276\223\345\207\272", Q_NULLPTR));
    } // retranslateUi

};

namespace Ui {
    class FaceRecognitionClass: public Ui_FaceRecognitionClass {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_FACERECOGNITION_H
<file_sep>/FaceRecognition/GeneratedFiles/ui_ImageWidget.h
/********************************************************************************
** Form generated from reading UI file 'ImageWidget.ui'
**
** Created by: Qt User Interface Compiler version 5.6.3
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_IMAGEWIDGET_H
#define UI_IMAGEWIDGET_H

#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QWidget>

QT_BEGIN_NAMESPACE

class Ui_ImageWidget
{
public:
    QLabel *label;
    QPushButton *removeButton;

    void setupUi(QWidget *ImageWidget)
    {
        if (ImageWidget->objectName().isEmpty())
            ImageWidget->setObjectName(QStringLiteral("ImageWidget"));
        ImageWidget->resize(400, 300);
        label = new QLabel(ImageWidget);
        label->setObjectName(QStringLiteral("label"));
        label->setGeometry(QRect(0, 15, 102, 126));
        label->setStyleSheet(QStringLiteral("background-color: rgb(0, 0, 0);"));
        removeButton = new QPushButton(ImageWidget);
        removeButton->setObjectName(QStringLiteral("removeButton"));
        removeButton->setGeometry(QRect(87, 0, 30, 30));

        retranslateUi(ImageWidget);

        QMetaObject::connectSlotsByName(ImageWidget);
    } // setupUi

    void retranslateUi(QWidget *ImageWidget)
    {
        ImageWidget->setWindowTitle(QApplication::translate("ImageWidget", "ImageWidget", Q_NULLPTR));
        label->setText(QApplication::translate("ImageWidget", "imgLabel", Q_NULLPTR));
        removeButton->setText(QString());
    } // retranslateUi

};

namespace Ui {
    class ImageWidget: public Ui_ImageWidget {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_IMAGEWIDGET_H
<file_sep>/FaceRecognition/FaceRecognitionFun.h
#pragma once
#include <string>
#include <Util.h>
#include "FaceFeature.h"

using namespace std;

class FaceRecognitionFun
{
	FaceFeature face_feature;
	//std::vector<float*> seetaface_train;

	cv::Mat Draw(FaceStruct face_struct, cv::Mat src);

public:
	bool isLoadTrain;
	int detector_num, alignment_num, reconition_num;
	std::vector<FaceStruct> face_struct_train_frame;
	std::vector<FaceStruct> face_struct_train_seetaface;

	void Init();
	void DrawResult(FaceStruct& face_struct, int index, string argmaxName);
	void DrawProcessedFace(std::vector<FaceStruct>& face_struct);
	void Recognition(const std::vector<string> train_path_list, const string test_path,
		std::vector<FaceStruct>& face_struct_train, FaceStruct& face_struct_test, std::vector<std::vector<float>>& result);
};<file_sep>/FaceRecognition/FaceFeature.h
#pragma once
#include <string>
#include "Util.h"
#include <vector>
#include <opencv/cv.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include "facedetect-dll.h"

using std::string;
#define DETECT_BUFFER_SIZE 0x20000

class FaceFeature{

	void FaceFeature::Detect(FaceStruct& face_struct);
public:
	vector<std::vector<float>> Recongnize(std::vector<FaceStruct>& face_struct_train, FaceStruct& face_struct_test);
	std::vector<std::vector<float>> SimCalc(std::vector<cv::Mat> train_feats, FaceStruct& face_struct_test);
};

<file_sep>/FaceRecognition/FaceFeature.cpp
/*
## 创建标识：第五届全国大学生物联网大赛人脸识别demo

## 创建时间：2017-12-20

## 函数功能描述：人脸识别控件

## 开发环境
[Windows10+VS2015+Qt5.6+opencv2.4.11]
**开发语言C++**
**编译环境x64**

## 环境配置
**配置opencv2.4.11的环境**
**配置Qt5.6+VS2015的环境**
**项目属性-链接器-输入-附加依赖项 需要添加相关lib文件

## 技术支持
(http://www.greenorbs.com/)
*/

#include "FaceFeature.h"
#include <opencv2/opencv.hpp>
#include <opencv/cv.h>

//--------------------------------人脸检测----------------------------------------//
void FaceFeature::Detect(FaceStruct& face_struct)
{
	face_struct.image = cv::imread(face_struct.fileName, 1);
	cv::Mat src_img_color = face_struct.image;
	cv::Mat src_img_gray;
	cv::cvtColor(src_img_color, src_img_gray, CV_BGR2GRAY);

	int * pResults = NULL;
	unsigned char * pBuffer = (unsigned char *)malloc(DETECT_BUFFER_SIZE);
	if (!pBuffer)
	{
		fprintf(stderr, "Can not alloc buffer.\n");
		return;
	}
	pResults = facedetect_multiview_reinforce(pBuffer, (unsigned char*)(src_img_gray.ptr(0)),
		src_img_gray.cols, src_img_gray.rows, (int)src_img_gray.step, 1.2f, 2, 80, 0, 0);
	int peopleNUM = (pResults ? *pResults : 0);//几张人脸
	for (int i = 0; i < peopleNUM; i++)
	{
		short * p = ((short*)(pResults + 1)) + 142 * i;
		float area = p[2] * p[3];
		cv::Rect rect(p[0], p[1], p[2], p[3]);
		face_struct.faceRect.push_back(rect);

		cv::Mat Src_Img_Crop_Mat = src_img_color(rect);
		cv::resize(Src_Img_Crop_Mat, Src_Img_Crop_Mat, cv::Size(64, 64));
		cv::Mat train; cv::cvtColor(Src_Img_Crop_Mat, train, CV_BGR2GRAY);

		cv::HOGDescriptor * hog = new cv::HOGDescriptor(cvSize(64, 64), cvSize(16, 16), cvSize(8, 8), cvSize(8, 8), 9);//定义hog特征参数
		std::vector<float>descriptor;
		hog->compute(train, descriptor, cv::Size(8, 8));//提取hog特征
		int descriptorDim = descriptor.size();
		cv::Mat feat = cv::Mat::zeros(1, descriptorDim, CV_32FC1);
		for (int j = 0; j < descriptorDim; j++)//将特征向量复制到矩阵中
		{
			feat.at<float>(0, j) = descriptor[j];
		}
		descriptor.clear();
		face_struct.feats.push_back(feat);
	}
}
//--------------------------------提取训练集和测试集特征并比对----------------------------------------//
std::vector<std::vector<float>> FaceFeature::Recongnize(std::vector<FaceStruct>& face_struct_train,
	FaceStruct& face_struct_test)
{
	std::vector<cv::Mat> train_feats;
	for (int i = 0; i < face_struct_train.size(); i++)
	{
		Detect(face_struct_train[i]);
		if (face_struct_train[i].faceRect.size() > 0)
			train_feats.push_back(face_struct_train[i].feats[0]);//训练仅有一张人脸
		else
			face_struct_train.erase(face_struct_train.begin() + i);
	}

	return SimCalc(train_feats, face_struct_test);
}
//--------------------------------相似度计算----------------------------------------//
std::vector<std::vector<float>> FaceFeature::SimCalc(std::vector<cv::Mat> train_feats,
	FaceStruct& face_struct_test)
{
	std::vector<std::vector<float>> result;
	Detect(face_struct_test);
	if (face_struct_test.feats.size() > 0)
	{
		std::vector<cv::Mat> test_feats = face_struct_test.feats;

		for (auto i = 0; i < test_feats.size(); i++)
		{
			std::vector<float> single_result;
			for (auto j = 0; j < train_feats.size(); j++)
			{
				cv::Mat feat1 = test_feats[i];
				cv::Mat feat2 = train_feats[j];
				double sim = 1 / (1 + norm(feat1, feat2, CV_L2));
				single_result.push_back(sim);
			}
			result.push_back(single_result);
		}
		return result;
	}
}
<file_sep>/README.md
//******************************第五届全国大学生物联网大赛命题赛人脸识别demo********************************//

## 算法实现
[算法实现流程：人脸检测+特征提取+相似度计算]

**人脸匹配50组库文件放置在./FaceRecognition-master/image/FaceMatching/train目录下（不会改变）**
**人脸匹配10组测试图片放置在./FaceRecognition-master/image/FaceMatching/test目录下（仅供测试）**
**人脸标识图片放置在./FaceRecognition-master/image/FaceIdentification目录下（仅供测试）**

## 开发环境
[Windows10+VS2015+Qt5.6+opencv2.4.11]
**开发语言C++**
**编译环境x64**

## 环境配置
**配置opencv的环境，配置过程参见
（http://blog.csdn.net/u011583927/article/details/52434673或http://blog.csdn.net/xsugus/article/details/71023488）**
**配置Qt5.6+VS2015的环境，配置过程参见（https://www.cnblogs.com/findumars/p/5970073.html）**
**项目属性-VC++目录-包含目录 需要添加相应包含文件**
**项目属性-链接器-输入-附加依赖项 需要添加相应库文件**

## 文件下载
[github代码下载链接]（https://github.com/bleakie/FaceRecognition-master）
## 大赛官网
(http://iotcompetition.org/)
## 技术支持
(http://www.greenorbs.com/)
<file_sep>/FaceRecognition/main.cpp
/*
## 创建标识：第五届全国大学生物联网大赛人脸识别demo

## 创建时间：2017-12-20

## 函数功能描述：人脸识别控件

## 开发环境
[Windows10+VS2015+Qt5.6+opencv2.4.11]
**开发语言C++**
**编译环境x64**

## 环境配置
**配置opencv2.4.11的环境**
**配置Qt5.6+VS2015的环境**
**项目属性-链接器-输入-附加依赖项 需要添加相关lib文件

## 技术支持
(http://www.greenorbs.com/)
*/

#include "FaceRecognition.h"
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	FaceRecognition w;
	w.show();
	return a.exec();
}
<file_sep>/FaceRecognition/Util.h
#pragma once
#include <opencv2/opencv.hpp>

using namespace std;

//需要输出数据的结构体
struct FaceStruct
{
	string fileName;
	cv::Mat image;
	std::vector<cv::Rect> faceRect;//bounding box
	std::vector<cv::Mat> feats;
	cv::Mat drawImg;//绘制好的人脸，已转成mat结构
};<file_sep>/FaceRecognition/ImageWidget.h
#pragma once

#include <QWidget>
#include "ui_ImageWidget.h"

class ImageWidget : public QWidget
{
	Q_OBJECT

public:
	ImageWidget(QWidget *parent = Q_NULLPTR);
	~ImageWidget();
	void setPixmap(QPixmap& pixmap);
	void setText(QString);
	QPushButton* getRemoveBtn();

private:
	Ui::ImageWidget ui;
	QString text;

signals:
	void remove();
};
<file_sep>/FaceRecognition/FaceRecognition.cpp
/*
## 创建标识：第五届全国大学生物联网大赛人脸识别demo

## 创建时间：2017-12-20

## 函数功能描述：人脸识别控件

## 开发环境
[Windows10+VS2015+Qt5.6+opencv2.4.11]
**开发语言C++**
**编译环境x64**

## 环境配置
**配置opencv2.4.11的环境**
**配置Qt5.6+VS2015的环境**
**项目属性-链接器-输入-附加依赖项 需要添加相关lib文件

## 技术支持
(http://www.greenorbs.com/)
*/

#include "FaceRecognition.h"
#include <qfiledialog.h>
#include <qmessagebox.h>
#include <QTimer>
#include <QDesktopServices>
#include <QSignalMapper>
#include "ImageWidget.h"
#include <opencv2/core/core.hpp>
#include <opencv2/contrib/contrib.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <ctime>

FaceRecognition::FaceRecognition(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);

	connect(ui.uploadButton1, SIGNAL(clicked()), this, SLOT(UploadClick1()));
	connect(ui.uploadButton2, SIGNAL(clicked()), this, SLOT(UploadClick2()));
	connect(ui.faceCompare, SIGNAL(clicked()), this, SLOT(FaceCompare()));

	fun.Init();
}

QImage Mat2QImage(cv::Mat const& src)
{
	cv::Mat temp; // make the same cv::Mat
	cv::cvtColor(src, temp, CV_BGR2RGB); // cvtColor Makes a copt, that what i need
	QImage dest((const uchar *)temp.data, temp.cols, temp.rows, temp.step, QImage::Format_RGB888);
	dest.bits(); // enforce deep copy, see documentation
				 // of QImage::QImage ( const uchar * data, int width, int height, Format format )
	return dest;
}

void ShowScaledImg(QString path, QLabel* qLabel)
{
	QImage *qImage = new QImage(path);
	QImage qScaledImage;
	QSize qImageSize = qImage->size();
	QSize qLabelSize = qLabel->size();
	double dWidthRatio = 1.0*qImageSize.width() / qLabelSize.width();
	double dHeightRatio = 1.0*qImageSize.height() / qLabelSize.height();
	if (dWidthRatio > dHeightRatio)
	{
		qScaledImage = qImage->scaledToWidth(qLabelSize.width());
	}
	else
	{
		qScaledImage = qImage->scaledToHeight(qLabelSize.height());
	}

	qLabel->setPixmap(QPixmap::fromImage(qScaledImage));
	qLabel->setAlignment(Qt::AlignCenter);
	qLabel->show();
}

void ShowProcessedImg(cv::Mat const& src, QLabel* qLabel)
{
	QImage qImage = Mat2QImage(src);

	QImage qScaledImage;
	QSize qImageSize = qImage.size();
	QSize qLabelSize = qLabel->size();
	double dWidthRatio = 1.0*qImageSize.width() / qLabelSize.width();
	double dHeightRatio = 1.0*qImageSize.height() / qLabelSize.height();
	if (dWidthRatio > dHeightRatio)
	{

		qScaledImage = qImage.scaledToWidth(qLabelSize.width());
	}
	else
	{
		qScaledImage = qImage.scaledToHeight(qLabelSize.height());
	}

	qLabel->setPixmap(QPixmap::fromImage(qScaledImage));
	qLabel->setAlignment(Qt::AlignCenter);
	qLabel->show();
}

void FaceRecognition::UploadClick1()
{
	QFileDialog dialog(this);
	dialog.setDirectory(".");
	dialog.setFileMode(QFileDialog::ExistingFiles);
	dialog.setNameFilter(trUtf8("image Files(*.jpg *.png)"));
	QStringList fileNames;
	if (dialog.exec())
		fileNames = dialog.selectedFiles();

	if (fileNames.length() == 0) {
		ui.resultBrowser->append("You didn't select any files.");
		return;
	}
	path1.clear();
	ui.imglistWidget->clear();

	int icon_width = 102, icon_height = 126;
	ui.imglistWidget->setIconSize(QSize(icon_width, icon_height));
	ui.imglistWidget->setResizeMode(QListView::Adjust);
	ui.imglistWidget->setViewMode(QListView::IconMode);
	ui.imglistWidget->setMovement(QListView::Static);
	ui.imglistWidget->setSpacing(10);

	QSignalMapper *mapper = new QSignalMapper(this);
	connect(mapper, SIGNAL(mapped(QString)), this, SLOT(DelImg(QString)));

	for (int i = 0; i < fileNames.length(); i++)
	{
		path1.push_back(fileNames[i].toStdString());

		QListWidgetItem *item = new QListWidgetItem();
		item->setSizeHint(QSize(icon_width + 30, icon_height));
		ui.imglistWidget->addItem(item);

		ImageWidget* widget = new ImageWidget();
		QPixmap *pixmap = new QPixmap(fileNames[i]);
		widget->setPixmap(*pixmap);
		widget->setText(fileNames[i]);

		ui.imglistWidget->setItemWidget(item, widget);

		connect(widget->getRemoveBtn(), SIGNAL(clicked()), mapper, SLOT(map()));
		mapper->setMapping(widget->getRemoveBtn(), fileNames[i]);
	}
}

void FaceRecognition::UploadClick2()
{
	QString path = QFileDialog::getOpenFileName(this, tr("Open image"), ".", tr("image Files(*.jpg *.png)"));
	if (path.length() == 0) {
		ui.resultBrowser->append("You didn't select any files.");
	}
	else {

		ShowScaledImg(path, ui.imglabel2);

		ui.resultBrowser->append("You selected: " + path);
		path2 = path.toStdString();
	}
}
//--------------------------------人脸比对----------------------------------------//
void FaceRecognition::FaceCompare()
{
	double time_Start = (double)clock();

	if (path2.length() == 0) {
		QMessageBox::information(NULL, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("未选择文件/文件夹"));
		return;
	}
	if (path1.capacity() == 0)
	{
		//select no file
		QMessageBox::information(NULL, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("未选择文件/文件夹"));
		return;
	}

	ui.faceCompare->setDisabled(true);
	qApp->processEvents();

	std::vector<FaceStruct> result1;
	FaceStruct result2;
	std::vector<std::vector<float>> sim;

	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

	fun.Recognition(path1, path2, result1, result2, sim);
	//判断是否定义FACEMATCHING
#ifdef FACEMATCHING
	std::ofstream output_result;//输出结果保存到txt
	output_result.open("./result/result.txt", ios::out);

	for (int i = 0; i < sim.size(); i++)
	{
		output_result << result2.fileName.substr(result2.fileName.length() - 6, 6) << ";";//写入测试图片名
		std::vector<float> OneFaceSim = sim[i];
		if (OneFaceSim.size() == 0)
			continue;
		int argmax = std::distance(OneFaceSim.begin(), std::max_element(OneFaceSim.begin(), OneFaceSim.end()));//找到最大相似度的序号
		string argmaxName = result1[argmax].fileName;
		float score = OneFaceSim[argmax];
		if (score < THRESHOLD)
			output_result << "NULL" << endl;//写入匹配项
		else
		{
			fun.DrawResult(result2, i, argmaxName);//标记测试得到的label
			output_result << argmaxName.substr(argmaxName.length() - 6, 6) << endl;//写入匹配项
		}
		ui.resultBrowser->append("Most similarity image is :" + QString::fromStdString(argmaxName.substr(argmaxName.length() - 6, 6)) + " @ Similarity = " + QString::number(100 * score) + "%");
	}
	output_result.close();
#else
	//人脸标识
	for (int i = 0; i < sim.size(); i++)
	{
		std::vector<float> OneFaceSim = sim[i];
		if (OneFaceSim.size() == 0)
			continue;
		int argmax = std::distance(OneFaceSim.begin(), std::max_element(OneFaceSim.begin(), OneFaceSim.end()));//找到最大相似度的序号
		string argmaxName = result1[argmax].fileName;
		float score = OneFaceSim[argmax];
		if (score < THRESHOLD)
			continue;
		fun.DrawResult(result2, i, argmaxName);//标记测试得到的label
		ui.resultBrowser->append("Most similarity image is :" + QString::fromStdString(argmaxName.substr(argmaxName.length() - 6, 6)) + " @ Similarity = " + QString::number(100 * score) + "%");
	}
	//将标识的结果保存到本地
	char path[256]; int count = 1;
	sprintf(path, "./result/%02d.jpg", count);
	cv::imwrite(path, result2.drawImg);
#endif

	QApplication::restoreOverrideCursor();

	if (result1.size() > 0)
	{
		//clear first, and then show
		ui.imglistWidget->clear();
	}
	for (int i = 0; i < result1.size(); i++)
	{
		if (!result1[i].drawImg.data)
			continue;
		QImage img = Mat2QImage(result1[i].drawImg);
		QPixmap pixmap = QPixmap::fromImage(img);
		QListWidgetItem *pItem = new QListWidgetItem(QIcon(pixmap), NULL);
		//设置单元项的宽度和高度
		int icon_width = 102, icon_height = 126;
		pItem->setSizeHint(QSize(icon_width, icon_height));
		ui.imglistWidget->insertItem(i, pItem);
	}

	if (result2.faceRect.size() == 0)
	{
		ui.resultBrowser->append(QString::fromStdString(path2) + " => [No face detected.]");
	}
	if(result2.drawImg.data)
		ShowProcessedImg(result2.drawImg, ui.imglabel2);

	ui.faceCompare->setDisabled(false);

	//calc time
	QString str;
	str.sprintf("Time elapsed : %.2fms", (double)clock() - time_Start);
	ui.resultBrowser->append(str);
}
<file_sep>/FaceRecognition/FaceRecognitionFun.cpp
/*
## 创建标识：第五届全国大学生物联网大赛人脸识别demo

## 创建时间：2017-12-20

## 函数功能描述：人脸识别控件

## 开发环境
[Windows10+VS2015+Qt5.6+opencv2.4.11]
**开发语言C++**
**编译环境x64**

## 环境配置
**配置opencv2.4.11的环境**
**配置Qt5.6+VS2015的环境**
**项目属性-链接器-输入-附加依赖项 需要添加相关lib文件

## 技术支持
(http://www.greenorbs.com/)
*/

#include "FaceRecognitionFun.h"
#include <opencv2/core/core.hpp>

void FaceRecognitionFun::Init()
{
	isLoadTrain = false;
}
//--------------------------------绘制人脸检测框----------------------------------------//
cv::Mat FaceRecognitionFun::Draw(FaceStruct face_struct, cv::Mat src)
{
	std::vector<cv::Rect> rect = face_struct.faceRect;
	for (int i = 0; i < rect.size(); i++)
		cv::rectangle(src, rect[i], cv::Scalar(0, 0, 255), 2);

	return src;
}
//------------------------------------标记结果----------------------------------------//
void FaceRecognitionFun::DrawResult(FaceStruct& face_struct, int index, string argmaxName)
{
	face_struct.drawImg = face_struct.image;
	cv::rectangle(face_struct.drawImg, face_struct.faceRect[index], cv::Scalar(0, 0, 255), 2);
	cv::Point origin; origin.x = face_struct.faceRect[index].x; origin.y = face_struct.faceRect[index].y;
	string label(argmaxName.substr(argmaxName.length()-6, 6));
	cv::putText(face_struct.drawImg, label, origin, cv::FONT_HERSHEY_COMPLEX, 1, cv::Scalar(0, 255, 255), 1, 8, 0);
}

void FaceRecognitionFun::DrawProcessedFace(std::vector<FaceStruct>& face_struct) {
	for (int i = 0; i < face_struct.size(); i++)
	{
		face_struct[i].drawImg = Draw(face_struct[i], face_struct[i].image);
	}
}

//--------------------------------识别调用公式----------------------------------------//
void FaceRecognitionFun::Recognition(const std::vector<string> train_path_list, const string test_path,
	std::vector<FaceStruct>& face_struct_train, FaceStruct& face_struct_test, std::vector<std::vector<float>>& result)
{
	for (auto i = 0; i < train_path_list.size(); i++)
	{
		FaceStruct face_struct_new;
		face_struct_new.fileName = train_path_list[i];
		face_struct_train.push_back(face_struct_new);
	}
	face_struct_test.fileName = test_path;

	//人脸识别
	result = face_feature.Recongnize(face_struct_train, face_struct_test);
	DrawProcessedFace(face_struct_train);
}
<file_sep>/FaceRecognition/FaceRecognition.h
#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_FaceRecognition.h"
#include <QTimer>
#include <fstream>
#include <iostream>
#include <opencv2/core/core.hpp>
#include "FaceRecognitionFun.h"

//#define FACEMATCHING //定义启用人脸匹配
#define THRESHOLD	0.2 //判定阈值
class FaceRecognition : public QMainWindow
{
	Q_OBJECT

public:
	FaceRecognition(QWidget *parent = Q_NULLPTR);
	std::vector<string> path1;
	std::string path2;

private:
	Ui::FaceRecognitionClass ui;
	QTimer videocapTimer;
	cv::Mat videocapImage;
	cv::VideoCapture videoCap;
	FaceRecognitionFun fun;

public slots:
	void UploadClick1();
	void UploadClick2();
	void FaceCompare();
};


text:
<file_sep># Git Cheatsheet

## The Basics

| Command    | Explanation |
|------------|-------------|
| `git init <directory>` | Create empty Git repo in specified directory. Run with no arguments to initialize the current directory as a git repository. |
| `git clone <repo>` | Clone repo located at `<repo>` onto local machine. Original repo can be located on the local filesystem or on a remote machine via `HTTP` or `SSH`. |
| `git config user.name <name>` | Define author name to be used for all commits in current repo. Devs commonly use `--global` flag to set config options for current user. |
| `git add <directory>` | Stage all changes in `<directory>` for the next commit. Replace `<directory>` with a `<file>` to change a specific file. |
| `git commit -m "<message>"` | Commit the staged snapshot, but instead of launching a text editor, use `<message>` as the commit message. |
| `git status` | List which files are staged, unstaged, and untracked. |
| `git log` | Display the entire commit history using the default format. For customization see additional options. |
| `git diff` | Show unstaged changes between your index and working directory. |

## Undoing Changes

| Command    | Explanation |
|------------|-------------|
| `git revert <commit>` | Create new commit that undoes all of the changes made in `<commit>`, then apply it to the current branch. |
| `git reset <file>` | Remove `<file>` from the staging area, but leave the working directory unchanged. This unstages a file without overwriting any changes. |
| `git clean -n` | Shows which files would be removed from working directory. Use the `-f` flag in place of the `-n` flag to execute the clean. |

## Rewriting Git History

| Command    | Explanation |
|------------|-------------|
| `git commit --amend` | Replace the last commit with the staged changes and last commit combined. Use with nothing staged to edit the last commit’s message. |
| `git rebase <base>` | Rebase the current branch onto `<base>`. `<base>` can be a commit ID, a branch name, a tag, or a relative reference to `HEAD`. |
| `git reflog` | Show a log of changes to the local repository’s `HEAD`. Add `--relative-date` flag to show date info or `--all` to show all refs. |

## Branches

| Command    | Explanation |
|------------|-------------|
| `git branch` | List all of the branches in your repo. Add a `<branch>` argument to create a new branch with the name `<branch>`. |
| `git checkout -b <branch>` | Create and check out a new branch named `<branch>`. Drop the `-b` flag to checkout an existing branch. |
| `git merge <branch>` | Merge `<branch>` into the current branch. |

## Remote Repositories

| Command    | Explanation |
|------------|-------------|
| `git remote add <name> <url>` | Create a new connection to a remote repo. After adding a remote, you can use `<name>` as a shortcut for `<url>` in other commands. |
| `git fetch <remote> <branch>` | Fetches a specific `<branch>`, from the repo. Leave off `<branch>` to fetch all remote refs. |
| `git pull <remote>` | Fetch the specified remote’s copy of current branch and immediately merge it into the local copy. |
| `git push <remote> <branch>` | Push the branch to <remote>, along with necessary commits and objects. Creates named branch in the remote repo if it doesn’t exist. |

# Additional Options

## git config

| Command    | Explanation |
|------------|-------------|
| `git config --global user.name <name>` | Define the author name to be used for all commits by the current user. |
| `git config --global user.email <email>` | Define the author email to be used for all commits by the current user. |
| `git config --global alias. <alias-name> <git-command>` | Create shortcut for a Git command. E.g. `alias.glog log --graph --oneline` will set `git glog` equivalent to `git log --graph --oneline`. |
| `git config --system core.editor <editor>` | Set text editor used by commands for all users on the machine. `<editor>` arg should be the command that launches the desired editor (e.g., vi). |
| `git config --global --edit` | Open the global configuration file in a text editor for manual editing. |

## git log

| Command    | Explanation |
|------------|-------------|
| `git log -<limit>` | Limit number of commits by `<limit>`. E.g. `git log -5` will limit to 5 commits. |
| `git log --oneline` | Condense each commit to a single line. |
| `git log -p` | Display the full diff of each commit. |
| `git log --stat` | Include which files were altered and the relative number of lines that were added or deleted from each of them. |
| `git log --author="<pattern>"` | Search for commits by a particular author. |
| `git log --grep="<pattern>"` | Search for commits with a commit message that matches 	`<pattern>`. |
| `git log <since>..<until>` | Show commits that occur between `<since>` and `<until>`. Args can be a commit ID, branch name, `HEAD`, or any other kind of revision reference. |
| `git log -- <file>` | Only display commits that have the specified file. |
| `git log --graph --decorate` | `--graph` flag draws a text based graph of commits on left side of commit msgs. `--decorate` adds names of branches or tags of commits shown. |

## git diff

| Command    | Explanation |
|------------|-------------|
| `git diff HEAD` | Show difference between working directory and last commit. |
| `git diff --cached` | Show difference between staged changes and last commit. |

## git reset

| Command    | Explanation |
|------------|-------------|
| `git reset` | Reset staging area to match most recent commit, but leave the working directory unchanged. |
| `git reset --hard` | Reset staging area and working directory to match most recent commit and **overwrites all changes** in the working directory. |
| `git reset <commit>` | Move the current branch tip backward to `<commit>`, reset the staging area to match, but leave the working directory alone. |
| `git reset --hard <commit>` | Same as previous, but resets both the staging area & working directory to match. **Deletes** uncommitted changes, and **all commits after** `<commit>`. |

## git rebase

| Command    | Explanation |
|------------|-------------|
| `git rebase -i <base>` | Interactively rebase current branch onto `<base>`. Launches editor to enter commands for how each commit will be transferred to the new base. |

## git pull

| Command    | Explanation |
|------------|-------------|
| `git pull --rebase <remote>` | Fetch the remote’s copy of current branch and rebases it into the local copy. Uses git rebase instead of merge to integrate the branches. |

## git push

| Command    | Explanation |
|------------|-------------|
| `git push <remote> --force` | Forces the `git push` even if it results in a non-fast-forward merge. Do not use the `--force flag` unless you’re absolutely sure you know what you’re doing |
| `git push <remote> --all` | Push all of your local branches to the specified remote. |
| `git push <remote> --tags` | Tags aren’t automatically pushed when you push a branch or use the `--all` flag. The `--tags` flag sends all of your local tags to the remote repo. |

# Credits

Thank you [Atlassian](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet) for the content in this cheat sheet.

## Great resources for Git

- [GitHub's Git resources](https://try.github.io/)
- [Atlassian's Git tutorials](https://www.atlassian.com/git/tutorials)

repo_name: edelstone/git-cheatsheet