text:
<file_sep>package hr.unidu.kz.ocjenefilmova1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private Button oc;
    private RatingBar po;
    private int brojOcjena = 0;
    private float zbrojOcjena = 0.0f;
    private final int A1_OK_CODE = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        oc = findViewById(R.id.ocijeni);
        po = findViewById(R.id.ratingBar);
        oc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pokreniDruguAktivnost();
            }
        });
    }
    private void pokreniDruguAktivnost(){
        Intent intent = new Intent(this, OcjenaActivity.class);
        intent.putExtra("naziv","android");
        startActivityForResult(intent,A1_OK_CODE);
    }
    // Ova metoda se automatski izvodi nakon što pozvana aktivnost završi izvođenje
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Provjerava je li druga aktivnost uspješno završila
        // Služi za identifikaciju određene aktivnosti
        if (requestCode == A1_OK_CODE) {
            if (resultCode == RESULT_OK) {
                // dohvaća podatke kojeje u poslani objekt tipa Intent dodala pozvana aktivnost
                zbrojOcjena += data.getFloatExtra("ocjena", 0.0f);
                brojOcjena++;
                float prosjek = zbrojOcjena/brojOcjena;
                po.setRating(prosjek);
            }
        }
    }
}
<file_sep>include ':app'
rootProject.name='OcjeneFilmova1'

branch_name: refs/heads/master

languages: Java Gradle


text:
<file_sep># Web Assembly playground
My experimentation on webassembly

## Usage

### Copy Glue JS code from golang
```
  make copy_glue
```

### Compile WASM
```
  make compile
```

### Running web server
```
  make run
```<file_sep>package main

import (
	"fmt"
	"net/http"
	"os"
)

func main() {
	fmt.Println("Serving at port 9090")
	err := http.ListenAndServe(":9090", http.FileServer(http.Dir(os.Getenv("STATIC_PATH"))))
	if err != nil {
		fmt.Println("Failed to start server", err)
		return
	}
}
<file_sep>package main

import (
	"fmt"
	"syscall/js"
)

func isPrime(n int) bool {
	for i := 2; i*i <= n; i++ {
		if n%i == 0 {
			return false
		}
	}

	return true
}

func firstNPrime(n int) {
	if n < 1 {
		fmt.Println("N should be >= 1")
		return
	}

	for i := 2; n > 0; i++ {
		if isPrime(i) {
			fmt.Printf("%d,", i)
			n--
		}
	}
	fmt.Println()
}

func primeWrapper() js.Func {
	primeFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
		if len(args) != 1 {
			fmt.Println("Invalid no of arguments passed")
		}
		N := args[0].Int()
		firstNPrime(N)
		return nil
	})
	return primeFunc
}

func main() {
	js.Global().Set("firstNPrimeGolang", primeWrapper())
	<-make(chan bool)
}
<file_sep>#include <stdio.h>
#include <emscripten.h>
typedef int bool;
#define true 1
#define false 0

bool isPrime(int n) {
  for (int i = 2; i*i <= n; i++) {
    if (n % i == 0) {
      return false;
    }
  }
  return true;
}

#ifdef __cplusplus
extern "C" {
#endif

void EMSCRIPTEN_KEEPALIVE firstNPrimeC(int n) {
  if (n < 1) {
    printf("N should be >= 1\n");
  }

  for (int i = 2; n > 0; i++) {
    if (isPrime(i)) {
      printf("%d,",i);
      n--;
    }
  }
  printf("\n");
}

#ifdef __cplusplus
}
#endif<file_sep>ifndef $(GOROOT)
    GOROOT=$(shell go env GOROOT)
    export GOROOT
endif

compile_go:
	GOOS=js GOARCH=wasm go build -o assets/json.wasm cmd/wasm/main.go

compile_c:
	emcc cmd/wasm/main.c -o assets/wasm_c_exec.js -s "EXTRA_EXPORTED_RUNTIME_METHODS=['cwrap']"

compile: compile_go compile_c

copy_glue:
	cp ${GOROOT}/misc/wasm/wasm_exec.js assets/wasm_go_exec.js

run:
	STATIC_PATH="assets" go run cmd/server/main.go

languages: Makefile Markdown C Go

repo_language: Makefile

repo_name: azisak/wasm-playground


text:
<file_sep><?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');

//print_r( $this->eventos );

?>

 Eventos - Lista

<?php foreach ($this->eventos as $evento) { ?>

				<a href="index.php?option=com_eventosmvm&view=evento&id=<?php echo $evento->id;?>">
					<?php echo $evento->foto_mini_banner;?>

				<?php echo JText::_('Nome do Evento:'); ?>

					<a href="index.php?option=com_eventosmvm&view=evento&id=<?php echo $evento->id;?>">
						<?php echo $evento->nome;?>

				<?php echo JText::_('Local do Evento'); ?>:

				<?php echo JText::_('Data do Evento'); ?>:

				<?php echo $evento->local; ?>

				<?php echo " De ".date("d", strtotime($evento->data_inicio))."  a  ".date("d/m/Y", strtotime($evento->data_fim)); ?>

<?php } ?>
	<file_sep><?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// import Joomla view library
jimport('joomla.application.component.view');

// import Joomla html for use with stylesheets
jimport('joomla.html.html');

/**
 * HTML View class for the UpdHelloWorld Component
 */
class MVMEventsViewMVMEvents extends JView
{
	// Overwriting JView display method
	function display($tpl = null)
	{
		$app		= JFactory::getApplication();
		$params		= $app->getParams();
		$dispatcher = JDispatcher::getInstance();

		// Get some data from the models
		//$this->eventos	= $this->get('Eventos');

		// Check for errors.
		if (count($errors = $this->get('Errors')))
		{
			JError::raiseError(500, implode('
', $errors));
			return false;
		}

		//$this->addDocStyle();

		// Display the view
        parent::display($tpl);

	}

	protected function addDocStyle()
	{
        $doc = JFactory::getDocument();
        $doc->addStyleSheet('media/com_eventosmvm/css/site.style.css');
		/*$doc->addScript('http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js');
		$doc->addScript('media/com_cadastromvm/js/jquery.maskedinput.js');
		$doc->addScriptDeclaration('
			jQuery(function($){
			   $("#jform_fundacao").mask("99/99/9999");
			   $("#jform_telefone").mask("(99) 9999-9999?9");
			   $("#jform_fax").mask("(99) 9999-9999");
			   $("#jform_cpf").mask("999.999.999-99");
			   $("#buscarcpf").mask("999.999.999-99");
			   $("#jform_cnpj").mask("999.999.999/9999-99");
			   $("#jform_cep").mask("99.999-999");
			});
		');*/

    }

}

repo_language: PHP

repo_name: maxwelvm/mvmevents


text:
<repo_name>zxugithub/resource-manager<file_sep>/src/app/resource-list/resource-list.component.scss
.space {
    padding-top:20px;
    padding-left:30px;
    padding-right:30px;
    padding-bottom:20px;
}

.rectangle {
    background-color: cyan;
}

.rectangle1 {
    background-color: rgb(21, 255, 0);
}

div.position {
    position: relative;
    top: 10px;
    left: 20px;
    width: 1150px;

}

/*
   server-side-angular-way.component.css
*/
.no-data-available {
    text-align: center;
  }

  /*
     src/styles.css (i.e. your global style)
  */
  .dataTables_empty {
    display: none;
  }

  .field-length {
    max-width:500px;
  }<file_sep>/src/app/allocating/allocating.component.ts
import { Component, OnInit } from '@angular/core';
import { Resource } from '../shared/resource';
import { Project } from '../shared/project';

@Component({
  selector: 'rcm-allocating',
  templateUrl: './allocating.component.html',
  styleUrls: ['./allocating.component.scss']
})
export class AllocatingComponent implements OnInit {

  constructor() { }

  ngOnInit() {

  }

  onSubmit(allocateItem) {
    console.log(allocateItem);
  }

  resources: Resource[] =
    [
      {
        Id: 1,
        FirstName: "Dan",
        LastName: "Oliver"
      },
      {
        Id: 2,
        FirstName: "Richard",
        LastName: "Li"
      },
      {
        Id: 3,
        FirstName: "Sherif",
        LastName: "Ghonaim"
      },
      {
        Id: 4,
        FirstName: "Zhiming",
        LastName: "Xu"
      }
    ];

    monthYears: any [] =
    [
      {
        month: "Jan-2018"
      },
      {
        month: "Feb-2018"
      },
      {
        month: "Mar-2018"
      },
      {
        month: "Apr-2018"
      },
      {
        month: "May-2018"
      },
      {
        month: "Jun-2018"
      },
      {
        month: "Jul-2018"
      }
    ];

    projects: Project[] =
    [
      {
        Id: 1,
        Name: "Service Pricing"
      },
      {
        Id: 2,
        Name: "Group TFSA"
      },
      {
        Id: 3,
        Name: "Personal Landing"
      },
      {
        Id: 4,
        Name: "Slice"
      },
      {
        Id: 5,
        Name: "Balance Transfer"
      },
      {
        Id: 6,
        Name: "Business Credit Application"
      } ,
      {
        Id: 7,
        Name: "Alpha Banking"
      },
      {
        Id: 8,
        Name: "GIC Renewal and Purchase"
      }
    ];
}
<file_sep>/src/environments/environment.prod.ts
export const environment = {
  production: true,
  apiUrl: 'http://resource.manager/'
};
<file_sep>/src/app/shared/project.ts
export interface Project {
    Id: number;
    Name: string;
    Description?: string;
    TotalBudget?: number;
    StartDate?: Date;
    EndDate?: Date;
    RemainingBudget?: number;
    MsName?: string;
    MsNumber?: number;
    Portfolio?: string;
    Status?: string;
    Comment?: string;
}
<file_sep>/src/app/resource-list/resource-list.component.ts
import { Component, NgZone, OnInit } from '@angular/core';
import { DataTablesModule, DataTableDirective } from 'angular-datatables';
import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import { ApiService } from '../shared/api.service';
import { DataService } from '../shared/data.service';
import { Observer } from 'rxjs/Observer';
import { Observable } from 'rxjs/observable';
import { Subject } from 'rxjs/Subject';
//import { Client } from '_debugger';

@Component({
  selector: 'rcm-resource-list',
  templateUrl: 'resource-list.component.html',
  styleUrls: ['./resource-list.component.scss']
})
export class ResourceListComponent implements OnInit {
  message = '';

  ListData: any = [];

  dtOptions: DataTables.Settings = {};
  dtTrigger: Subject<any> = new Subject();

  constructor(private zone: NgZone, private api: ApiService, private router: Router) { }

  someClickHandler(info: any): void {
    this.router.navigate(['/editResource', info.id]);
//    this.message = info.id + ' - ' + info.firstName;
  }
  ngOnInit(): void {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 10,
      columns: [{
        title: 'ID',
        data: 'id'
      }, {
        title: 'First name',
        data: 'firstName'
      }, {
        title: '<NAME>',
        data: 'lastName'
      }, {
        title: 'Rate',
        data: 'rate'
      }, {
        title: 'Manager ID',
        data: 'managerId'
      }, {
        title: 'Department',
        data: 'department'
      }, {
        title: 'Resource Type',
        data: 'resourceType'
      }, {
        title: 'Hire Date',
        data: 'hireDate'
      }, {
        title: 'End Date',
        data: 'endDate'
      }, {
        title: 'Comment',
        data: 'comment'
      }],

      rowCallback: (row: Node, data: any[] | Object, index: number) => {
        const self = this;
        // Unbind first in order to avoid any duplicate handler
        // (see https://github.com/l-lin/angular-datatables/issues/87)
        $('td', row).unbind('click');
        $('td', row).bind('click', () => {
          self.someClickHandler(data);
        });
        return row;
      }
    }
    this.api.get("resources").subscribe( result => {
      this.ListData = result;
      this.dtTrigger.next();
    });
  }
}
<file_sep>/src/app/resource-details/resource-details.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Resource } from '../shared/resource';

@Component({
  selector: 'rcm-resource-details',
  templateUrl: './resource-details.component.html',
  styleUrls: ['./resource-details.component.scss']
})
export class ResourceDetailsComponent implements OnInit, OnDestroy {

  id: number;
  private sub: any;
  newResource: Resource;

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      this.id = +params['id'];
      console.log(this.id);
    });
  }
  ngOnDestroy() {
    this.sub.unsubscribe();
  }

  onSubmit (reource) {

  }
}
<file_sep>/src/app/shared/resource.ts
export interface Resource {
    Id: number;
    FirstName: string;
    LastName: string;
    Rate?: number;
    ManagerId?: number;
    Department?: string;
    ResourceType?: String;
    HireDate?: Date;
    EndDate?: Date;
    Comment?: String;
}
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ResourceListComponent } from './resource-list/resource-list.component';
import { ResourceDetailsComponent} from './resource-details/resource-details.component';
import { ProjectListComponent } from './project-list/project-list.component';
import { ProjectDetailsComponent } from './project-details/project-details.component';
import { AllocatingComponent } from './allocating/allocating.component';
import { AllocationByResourceComponent } from './allocation-by-resource/allocation-by-resource.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';

const routes: Routes = [

  {
    path: '',
    redirectTo: 'resources',
    pathMatch: 'full'
  },
  {
    path: 'resources',
    component: ResourceListComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'resourceDetails',
    component: ResourceDetailsComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'editResource/:id',
    component: ResourceDetailsComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'projects',
    component: ProjectListComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'projectDetails',
    component: ProjectDetailsComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'allocating',
    component: AllocatingComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'byresource',
    component: AllocationByResourceComponent,
    canActivate: [AuthGuard]
  },

  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: '**',
    redirectTo: 'resources'
  }

];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/src/app/allocation-by-resource/allocation-by-resource.component.ts
import { Component, OnInit } from '@angular/core';
import { Resource } from '../shared/resource';
import { Project } from '../shared/project';

@Component({
  selector: 'rcm-allocation-by-resource',
  templateUrl: './allocation-by-resource.component.html',
  styleUrls: ['./allocation-by-resource.component.scss']
})
export class AllocationByResourceComponent implements OnInit {

  selectedResource: any;
  constructor() { }

  ngOnInit() {
    console.log(this.assignments[1].assigns.length);
  }

  onChange(deviceValue) {
    console.log(deviceValue);
    console.log(this.selectedResource);
  }

  resources: Resource[] =
    [
      {
        Id: 1,
        FirstName: "Dan",
        LastName: "Oliver"
      },
      {
        Id: 2,
        FirstName: "Richard",
        LastName: "Li"
      },
      {
        Id: 3,
        FirstName: "Sherif",
        LastName: "Ghonaim"
      },
      {
        Id: 4,
        FirstName: "Zhiming",
        LastName: "Xu"
      }
    ];

    monthYears: any [] =
    [
      {
        month: "Jan-2018"
      },
      {
        month: "Feb-2018"
      },
      {
        month: "Mar-2018"
      },
      {
        month: "Apr-2018"
      },
      {
        month: "May-2018"
      },
      {
        month: "Jun-2018"
      },
      {
        month: "Jul-2018"
      }
    ];

    assignments: any [] =
    [
      {
      month: "Jan-2018", assigns: [
        { proj: "Service Pricing", assign: "20%"},
        { proj: "Group TFSA", assign: "25%" },
        { proj: "Balance Transfer", assign: "40%" },
        { proj: "US Credit Card Payment", assign: "15%"},
        { proj: "Total", assign: "100%"}
      ]},
      {month: "Feb-2018", assigns: [
        { proj: "Service Pricing", assign: "40%"},
        { proj: "Soleil", assign: "30%"},
        { proj: "Alpha Banking Integration", assign: "30%"},
        { proj: "Total", assign: "100%"}
      ]},
      {month: "Mar-2018",assigns: [
        { proj: "Client Appointment Booking", assign: "30%"},
        { proj: "US Credit Card Payment", assign: "30%"},
        { proj: "Alpha Banking Integration", assign: "30%"},
        { proj: "Soleil", assign:  "20%"},
        { proj: "Total", assign:  "110%"}
      ]}
    ];
}
<file_sep>/src/app/project-details/project-details.component.scss
.space {
    padding-top:20px;
    padding-left:30px;
    padding-right:30px;
    padding-bottom:20px;
}

.rectangle {
    background-color: cyan;
}

.rectangle1 {
    background-color: rgb(21, 255, 0);
}<file_sep>/src/app/shared/assignment.ts
export interface Assignment {
    Role: string;
    Allocation: string;
    YearMonth: string;
}
<file_sep>/src/app/allocating/allocating.component.scss
.center {
    margin: auto;
    width: 90%;
    padding: 10px;
}

.cellwidth {
    width: 20%;
    text-align: left;
    vertical-align: top;
    font-size:14px
}

.heighttext{
    float:left;
    height:22px;
    width:120px;
    }

<file_sep>/src/app/shared/vacation.ts
export interface Vacation {
    ResourceId: number;
    StartDate: Date;
    EndDate: Date;
}
<file_sep>/src/app/shared/data.service.ts
import { Injectable } from '@angular/core';
//import { HttpClient } from '@angular/common/http';
import { ApiService } from './api.service';

@Injectable()
export class DataService {

  constructor(private api: ApiService) { }

  loadData() {
    return this.api.get("api/resources")
  }

}

languages: TypeScript SCSS

repo_language: TypeScript

repo_name: zxugithub/resource-manager


text:
<repo_name>mk2382-zz/phpstorm<file_sep>/web/aaaaaaaa.php
<?php
/**
 * Created by PhpStorm.
 * User: mk2382
 * Date: 2016/05/22
 * Time: 17:22
 */


text:
<repo_name>toddheslin/blog-gatsby<file_sep>/README.md
# Being Remarkable Blog

Personal site for <NAME>

## Credits

Template from @LeKoArts. Visit his [website](https://www.lekoarts.de) or support him on [Patreon](https://www.patreon.com/lekoarts) to get some neat rewards (4K images, project files, tutorial insights).

Also check out the other *gatsby-starters*:
- [gatsby-starter-portfolio-emma](https://github.com/LeKoArts/gatsby-starter-portfolio-emma)
- [gatsby-starter-portfolio-emilia](https://github.com/LeKoArts/gatsby-starter-portfolio-emilia)
- [gatsby-starter-portfolio-bella](https://github.com/LeKoArts/gatsby-starter-portfolio-bella)
- [gatsby-starter-portfolio-cara](https://github.com/LeKoArts/gatsby-starter-portfolio-cara)

Check out the [Gatsby Starter Portfolio Overview](https://gatsby-starter-portfolio.netlify.com/)!

repo_language: Markdown

repo_name: toddheslin/blog-gatsby


text:
<repo_name>asmitnayak/myface<file_sep>/src/face_recog_img.py
import os
import sys
import threading
import time
import face_recognition
import concurrent.futures
import multiprocessing
import pickle
import cv2
from imutils import paths
import face_encoding

def run(multi_proc=False):
    thread_num = str(threading.get_ident())
    if os.path.exists("encodings_cnn.pkl") is False:
        print("[INFO] creating CNN encodings...")
        p1 = multiprocessing.Process(target=face_encoding.run, args=("cnn", True))
        p1.start()
        # the_process = threading.Thread(name='process', target=face_encoding.run, args=["cnn", True])
        # the_process.start()
        time.sleep(5)
        while p1.is_alive():
            face_encoding.animated_loading()

    print()
    print("[INFO] Thread Number: ", thread_num)
    print("[INFO] loading encoding...")
    data = pickle.loads(open("encodings_cnn.temp.pkl", "rb").read())

    # load the input images and convert from BGR to RGB
    # TO-DO
    imagePath = list(paths.list_images("temp"))
    sys.stdout.write("[INFO] recognizing faces...\n")
    for iPath in imagePath:
        image = cv2.imread(iPath)
        rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        # detect the (x, y)-coordinates of the bounding boxes corresponding
        # to each face in the input image, then compute the facial embeddings
        # for each face

        f1 = concurrent.futures.ProcessPoolExecutor().submit(face_recognition.face_locations, rgb, model="cnn")
        # while True:
        #     if f1.done():
        #         break
        #     face_encoding.animated_loading("Recognizing faces...")
        # sys.stdout.flush()
        boxes = f1.result()     # face_recognition.face_locations(rgb, model="cnn")
        encodings = face_recognition.face_encodings(rgb, boxes)

        # initialize the list of names for each face detected
        names = []

        # loop over the facial embeddings
        for encoding in encodings:
            # attempt to match each face in the input image to our known encodings
            matches = face_recognition.compare_faces(data["encodings"], encoding)
            name = "Unknown"

            # check to see if we have found a match
            if True in matches:
                # find the indexes of all matched faces then initialize a
                # dictionary to count the total number of times each face
                # was matched
                matchedIdxs = [i for (i, b) in enumerate(matches) if b]
                counts = {}

                # loop over the matched indexes and maintain a count for
                # each recognized face face
                for i in matchedIdxs:
                    name = data["names"][i]
                    counts[name] = counts.get(name, 0) + 1

                # determine the recognized face with the largest number of
                # votes (note: in the event of an unlikely tie Python will
                # select first entry in the dictionary)
                name = max(counts, key=counts.get)

            # update the list of names
            names.append(name)

        # # loop over the recognized faces
        # for ((top, right, bottom, left), name) in zip(boxes, names):
        #     # draw the predicted face name on the image
        #     cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2)
        #     y = top - 15 if top - 15 > 15 else top + 15
        #     cv2.putText(image, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX,
        #                 0.75, (0, 255, 0), 2)
        if (len(names) == 0 or names[0] is "Unknown") and multi_proc is False:
            # show the output image
            fileName = iPath.split(os.path.sep)[-1].split(".")[0]
            path = "Unknowns/" + str(fileName) + ".png"
            os.replace(str(iPath), path)
            # cv2.imshow("Image", image)
            # cv2.waitKey(0)
            # cv2.destroyWindow("Image")
        elif len(names) > 0 and names[0] is not "Unknown":
            fileName = iPath.split(os.path.sep)[-1].split(".")[0]
            path = "images/" + str(names[0]) + "/" + str(fileName) + ".png"
            os.replace(str(iPath), path)

    print("[INFO] creating new CNN encodings...")
    face_encoding.run("cnn", True)
    # p1 = multiprocessing.Process(target=face_encoding.run, args=("cnn", True))
    # p1.start()
    # # the_process = threading.Thread(name='process', target=face_encoding.run, args=["cnn", True])
    # # the_process.start()
    # if multi_proc is False:
    #     time.sleep(5)
    #     while p1.is_alive():
    #         face_encoding.animated_loading()
    # else:
    #     while p1.is_alive():
    #         pass

    print("[INFO] Advanced Facial Recognition finished...")

if __name__ == "__main__":
    run(multi_proc=False)
<file_sep>/src/interface_face.py
import tkinter

m = tkinter.Tk(className="PyImager")
m.mainloop()<file_sep>/src/faces.py
import numpy as np
import cv2
import pickle
import os
from datetime import datetime

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
image_dir = os.path.join(BASE_DIR, "images")

face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("trainer.yml")

labels = {}
with open("labels.pkl", "rb") as f:
    og_labels = pickle.load(f)
    labels = {v:k for k, v in og_labels.items()}

cap = cv2.VideoCapture(0)

counter = 0

while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=6)

    for (x, y, w, h) in faces:
        counter += 1
        print(x, y, w, h)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = frame[y:y + h, x:x + w]

        # recognize -> deep learn model -> scikit learn, etc
        id_, conf = recognizer.predict(roi_gray)
        if 50 <= conf:
            print(id_)
            print(labels[id_])
            font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX
            name = labels[id_]
            color = (255, 255, 255)
            stroke = 1
            cv2.putText(frame, name, (x, y), font, 1, color, stroke, cv2.LINE_AA)
        print(conf)
        img_item = "my-image.png"
        cv2.imwrite(img_item, roi_gray)

        color = (255, 0, 0)   # BGR 0-255
        stroke = 2
        end_cord_x = x + w;
        end_cord_y = y + h;
        cv2.rectangle(frame, (x, y), (end_cord_x, end_cord_y), color, stroke)

        if counter == 100:
            prmt = "IS THE DETECTED FACE THAT OF " + labels[id_] + "? (Y/N): "
            user_inp = input(prmt)
            if user_inp == 'Y' or user_inp == 'y':
                img_label_dir = os.path.join(image_dir, labels[id_])
                new_name = str(datetime.now()).replace(" ", "_").replace(":", "_")
                completeName = "images/" + str(labels[id_]) + "/" + new_name + ".png"
                print(completeName)
                cv2.imwrite(str(completeName), roi_color)
                exec(open("faces_train.py").read())
                with open("labels.pkl", "rb") as f:
                    og_labels = pickle.load(f)
                    labels = {v: k for k, v in og_labels.items()}

            counter = 0
        print(counter)

    # Display the resulting frame
    cv2.imshow('frame', frame)
    if cv2.waitKey(20) & 0xFF == ord('q'):
        break

# When everything is done
cap.release();
cv2.destroyAllWindows()
<file_sep>/src/alert.py
from notify_run import Notify

notify = Notify()

def alert_me(name):
    message = name + " sat down in front of your PC in your absence!!"
    notify.send(message)

def alert_me2(num):
    message = str(num) + " unknown faces detected!!"
    notify.send(message)
<file_sep>/src/testing.py
import asyncio
import random

# ANSI colors
c = (
    "\033[0m",   # End of color
    "\033[36m",  # Cyan
    "\033[91m",  # Red
    "\033[35m",  # Magenta
)

# async def makerandom(idx: int, threshold: int = 6) -> int:
#     print(c[idx + 1] + f"Initiated makerandom({idx}).")
#     i = random.randint(0, 10)
#     while i <= threshold:
#         print(c[idx + 1] + f"makerandom({idx}) == {i} too low; retrying.")
#         await asyncio.sleep(idx + 1)
#         i = random.randint(0, 10)
#     print(c[idx + 1] + f"---> Finished: makerandom({idx}) == {i}" + c[0])
#     return i
#
#
# async def main():
#     res = await asyncio.gather(*(makerandom(i, 10 - i - 1) for i in range(3)))
#     return res

c = 0
d = 0

def f2():
    global c, d
    print("f2 start")
    i = 0
    c += 1
    while i < 200000:
        i += 1
    d += 1
    print("in f2", i)
    # return "Finished f2: " + str(c)

async def f1():
    await f2()
    global d
    r = d
    print("stuff")
    return r

async def main():
    print("Starting...")
    while c != 5:
        # *(makerandom(i, 10 - i - 1) for i in range(3))
        await asyncio.gather(f2())
    while d != 5:
        print("in d")
        pass
    print("Finished")

if __name__ == "__main__":
    # random.seed(444)
    # r1, r2, r3 = asyncio.run(main())
    # print()
    asyncio.run(main())
    # print(f"r1: {r1}, r2: {r2}, r3: {r3}")

<file_sep>/src/face_encoding.py
from imutils import paths
import face_recognition
import pickle
import cv2
import os
import sys
import time

# CNN: Convolution Neural Network       -> slow (without GPU)
# HoG: Histogram of Oriented Gradient   -> fast (use in Raspberry Pi)
m = "hog"

def animated_loading(mes='Encoding in process...'):
    chars = "/—\|"
    for char in chars:
        sys.stdout.write('\r'+mes+char)
        time.sleep(.5)
        sys.stdout.flush()

def change_model(mod="hog"):
    global m
    m = mod

def run(mod="hog", p=False):
    if p is False:
        print("[INFO] Running facial encoder over face database...")
    change_model(mod)
    print("[INFO] Model in use:", "Histogram of Oriented Gradient" if m is "hog" else "Convolution Neural Network")
    imagePaths = list(paths.list_images("images"))
    knownEncodings = []
    knownNames = []

    # loop over the image paths
    for (i, imagePath) in enumerate(imagePaths):
        # extract the person name from the image path
        if p is False:
            print("[INFO] processing image {}/{}".format(i + 1, len(imagePaths)))
        name = imagePath.split(os.path.sep)[-2]

        # load the input image and convert it from BGR (OpenCV ordering)
        # to dlib ordering (RGB)
        image = cv2.imread(imagePath)
        rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        # detect the (x, y)-coordinates of the bounding boxes
        # corresponding to each face in the input image
        boxes = face_recognition.face_locations(rgb, model=m)

        # compute the facial embedding for the face
        encodings = face_recognition.face_encodings(rgb, boxes, num_jitters=1)

        # loop over the encodings
        for encoding in encodings:
            # add each encoding + name to our set of known names and
            # encodings
            knownEncodings.append(encoding)
            knownNames.append(name)

    # dump the facial encodings + names to disk
    if p is False:
        print("[INFO] serializing encodings...")
    data = {"encodings": knownEncodings, "names": knownNames}
    f = open("encodings_" + m + ".pkl", "wb")
    f.write(pickle.dumps(data))
    f.close()
    return "DONE"

if __name__ == "__main__":
    run()

repo_language: Python

repo_name: asmitnayak/myface


text:
<file_sep># menu

Menú básico realizado para prácticar las herramientas del Canvas.

repo_name: viguimumo/menu


text:
<file_sep>package testcases;

import org.testng.annotations.Test;

public class BuyorSellStockTest
{

	@Test
	public void buyorsellstcokTest()
	{

	}

	@Test
	public void checktransactionhistoryTest()
	{

	}
}

repo_language: Java

repo_name: smingle/Rediffmail


text:
<file_sep>

(use 'clojure.string)

(def atzimes [5 6 7 8 9 6] )
(def vardi ["Alina" "Andrejs" "Aleksejs" "Pavels" "Marina" "Olga"] )
(def list (map vector vardi atzimes))
(def n(num 0))
(def m(num 0))

(dotimes [x (count list)]
    (if (= (ends-with? (first (nth list x)) "a") true)
        (and(def n(+ n (second (nth list x))))(def m(+ m 1)))))

(float(/ n m))<file_sep>package imperative;

import java.util.HashSet;
import java.util.Set;

public class PerfectNumber
{
		enum STATE
		{
			ABUNDANT,
			DEFICIENT,
			PERFECT
		}

		public static Set<Integer> divisors(int n)
		{
			Set<Integer> divs = new HashSet<Integer>();
			for(int i = 1 ; i <= n ; i++)
			{
				if(n % i == 0)
				{
					divs.add(i);
				}
			}
			return divs;
		}

		public static STATE process(int n)
		{
			int sum = 0;

			for(Integer div : divisors(n))
			{
		          sum+= div;
		    }

			sum-=n;

			if (sum == n) return STATE.PERFECT;

			if (sum > n) return STATE.ABUNDANT;

			else return STATE.DEFICIENT;

		}
}

<file_sep>;;НЕ БЕЙТЕ ПОЖАЛУЙСТА, ЭТО ВЕРОЯТНО ВЫГЛЯДИТ КРИВО И НЕ ОПТИМАЛЬНО:)

(use 'clojure.core)
(use 'clojure.string)

(defn translate [str] (replace str #" " {" " "_"}))  ;;STRING SPACE CHANGE FUNCTION

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ENCRYPT STRING;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(def string "aatln_ooaikv")                      ;;INPUT STRING
(def key 3)                                      ;;INPUT KEY
(def newstring (into-array [""""""""""""]))      ;;DEFINE OUTPUT CHAR ARRAY
(def len (count string))                         ;;DEFINE STRING LENGTH
(def down false)                                 ;;DEFINE CIPHER DIRECTION
(def row 0)                                      ;;DEFINE CHAR ARRAY ROWS

(defn encrypt [string key]
  (dotimes [n len]
    (aset newstring row (str (get newstring row ) (subs (translate string) n (+ n 1))))
    (if (= row (- key 1)) (def down false))
    (if (= row 0) (def down true))
    (if (= down true)(def row(inc row))(def row(dec row)))
  )
  (join newstring)
)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;DECRYPT STRING;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(def new (into-array [""""""""""""]))            ;;DEFINE TEMPORARY ARRAY
(def pos 0)                                      ;;DEFINE POSITION COUNTER FOR CHAR SUBSTRINGS

(defn decrypt [string key]

  (encrypt string key)   ;;TO GET AN OUTPUT STRING FROM AN ARRAY, WE NEED TO FIND OUT, HOW MUCH CHARS WILL BE IN EACH ROW

  (dotimes [n key]       ;;INSERT ENCRYPT CHAR SUBSTRINGS INTO ARRAY BY ROWS
    (aset new n (subs (translate string) pos (+ pos (count (get newstring n)))))
    (def pos (+ pos (count (get newstring n))))
  )

  (def down false)           ;;DEFINE CIPHER DIRECTION
  (def row 0)

  (dotimes [n len]            ;;GET OUT AN OUTPUT SEQUENCE OF CHARS FROM AN ARRAY, USING A CIPHER DIRECTION
    (print(subs (get new row ) 0 1))
    (aset new row (replace-first (get new row) (subs (get new row) 0 1) ""))
    (if (= row (- key 1)) (def down false))
    (if (= row 0) (def down true))
    (if (= down true)(def row(inc row))(def row(dec row)))
  )
)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;(encrypt string key)
(decrypt string key)
<file_sep># RTU
Funkcionālā programmēšana
<NAME>
<file_sep>package imperativeLambda;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.IntStream;

public class PerfectNumberLambda
{
		enum STATE
		{
			ABUNDANT,
			DEFICIENT,
			PERFECT
		}

		public static Set<Integer> divisors(int n)
		{
			Set<Integer> divs = new HashSet<Integer>();
			int[] arr = IntStream.rangeClosed(1, n).toArray();
			IntStream stream = Arrays.stream(arr).filter(d -> n % d == 0);
			stream.forEach(s->divs.add(s));
			return divs;
		}

		public static STATE process(int n)
		{
			Set<Integer> divisors = divisors(n);

			Integer sum = divisors.stream().mapToInt(Integer::intValue).sum() -n;

			return sum == n ? STATE.PERFECT
			         : sum < n ? STATE.DEFICIENT
			         : STATE.ABUNDANT;
		}
}

languages: Java Clojure Markdown

repo_name: AlinaKotova/RTU


text:
<file_sep>'use strict';

const crypto = require('crypto');

const { DehydrateError } = require('../errors');

const MAX_PAYLOAD_SIZE = 2048;

const wrapHydrate = (payload) => {
  payload = JSON.stringify(payload);

  if (payload.length > MAX_PAYLOAD_SIZE) {
    throw new DehydrateError(
      `Oops! You passed too much data (${payload.length} bytes) to your dehydration function - try slimming it down under ${MAX_PAYLOAD_SIZE} bytes (usually by just passing the needed IDs).`
    );
  }

  if (process.env._ZAPIER_ONE_TIME_SECRET) {
    payload = Buffer.from(payload).toString('base64');

    const signature = Buffer.from(
      crypto
        .createHmac('sha1', process.env._ZAPIER_ONE_TIME_SECRET)
        .update(payload)
        .digest()
    ).toString('base64');

    payload += ':' + signature;
  }

  return 'hydrate|||' + payload + '|||hydrate';
};

module.exports = wrapHydrate;

repo_language: JavaScript

repo_name: JorgenEvens/zapier-platform


text:
<repo_name>nguyenty1993/Animation<file_sep>/Animation/DetailViewController.swift
//
//  DetailViewController.swift
//  Animation
//
//  Created by <NAME> on 1/11/17.
//  Copyright © 2017 <NAME>. All rights reserved.
//

import UIKit
import MapKit

class DetailViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, NSZoomTransitionAnimating, UIViewControllerTransitioningDelegate {

    @IBOutlet weak var imageView: UIImageView!
    //@IBOutlet weak var mapView: MKMapView!
    var mapView = MKMapView()
    var locationManager = CLLocationManager()
    var imagefromViewMain = UIImage()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        imageView.image = imagefromViewMain
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()

    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        // Don't want to show a custom image if the annotation is the user's location.
        guard !(annotation is MKUserLocation) else {
            return nil
        }

        // Better to make this class property
        let annotationIdentifier = "AnnotationIdentifier"

        var annotationView: MKAnnotationView?
        if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
            annotationView = dequeuedAnnotationView
            annotationView?.annotation = annotation
        }
        else {
            annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
            annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
        }

        if let annotationView = annotationView {
            // Configure your annotation view here
            annotationView.canShowCallout = true
            annotationView.image = UIImage(named: "btn-nav-left")
        }

        return annotationView
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations[0]
        let center = CLLocationCoordinate2D.init(latitude: (location.coordinate.latitude), longitude: (location.coordinate.longitude))
        let region = MKCoordinateRegion.init(center: center, span: MKCoordinateSpan.init(latitudeDelta: 0.01, longitudeDelta: 0.01))
        self.mapView.setRegion(region, animated: true)
        self.mapView.showsUserLocation = true
        //self.locationManager.stopUpdatingLocation()
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error : " + error.localizedDescription)
    }
    class CustomPointAnnotation: MKPointAnnotation {
        var imageName: String!
    }

    func transitionSourceImageView() -> UIImageView {
        return imageView
    }

    func transitionSourceBackgroundColor() -> UIColor {
        return view.backgroundColor!
    }

    func transitionDestinationImageViewFrame() -> CGRect {
        return imageView.frame
    }

    // MARK: - Navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ToMapView" {
            let vc = segue.destination as! MapKitViewController
            vc.transitioningDelegate = self
            vc.image = imagefromViewMain
//            let m = mapView
//            vc.mapView = mapView
        }

    }
    //MARK: UIViewControllerTransitioningDelegate
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let animator = NSZoomTransitionAnimator()
        animator.sourceVC = source
        animator.destinationVC = presented
        animator.goingForward = true
        return animator
    }
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let animator = NSZoomTransitionAnimator()
        animator.sourceVC = dismissed
        animator.destinationVC = self
        animator.goingForward = false
        return animator
    }

}
<file_sep>/Animation/ViewController.swift
//
//  ViewController.swift
//  Animation
//
//  Created by <NAME> on 1/11/17.
//  Copyright © 2017 <NAME>. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UIViewControllerTransitioningDelegate,NSZoomTransitionAnimating{

    var transition = CircularTransition()

    @IBOutlet weak var lbNumberOrdinal: UILabel!
    @IBOutlet weak var imageView: UIImageView!
    let total = 7
    var ordinal = 1
    override func viewDidLoad() {
        super.viewDidLoad()
        //Add many UISwipeGestureRecognizer for view
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
        swipeRight.direction = UISwipeGestureRecognizerDirection.right
        self.view.addGestureRecognizer(swipeRight)
        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
        swipeLeft.direction = UISwipeGestureRecognizerDirection.left
        self.view.addGestureRecognizer(swipeLeft)
        //Customize number ordinal of many images
        let mutableString = NSMutableAttributedString(string: lbNumberOrdinal.text!, attributes: [NSFontAttributeName:UIFont(name: "Arial", size: 17.0)!])
        mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.gray, range: NSRange(location:0,length:1))
        lbNumberOrdinal.attributedText = mutableString

    }

    func respondToSwipeGesture(gesture: UIGestureRecognizer) {
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
            switch swipeGesture.direction {
            case UISwipeGestureRecognizerDirection.right:
                ordinal -= 1;
                if(ordinal < 1){
                    ordinal = 7
                }
                imageView.image = UIImage(named: String(ordinal))
                lbNumberOrdinal.text = String(ordinal) + "/7"
                let myMutableString = NSMutableAttributedString(string: lbNumberOrdinal.text!, attributes: [NSFontAttributeName:UIFont(name: "Arial", size: 17.0)!])
                myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.gray, range: NSRange(location:0,length:1))
                lbNumberOrdinal.attributedText = myMutableString
            case UISwipeGestureRecognizerDirection.down:
                print("Swiped down")
                performSegue(withIdentifier: "Detail", sender: nil)
            case UISwipeGestureRecognizerDirection.left:
                ordinal += 1;
                if(ordinal > 7){
                    ordinal = 1
                }
                imageView.image = UIImage(named: String(ordinal))
                lbNumberOrdinal.text = String(ordinal) + "/7"
                let myMutableString = NSMutableAttributedString(string: lbNumberOrdinal.text!, attributes: [NSFontAttributeName:UIFont(name: "Arial", size: 17.0)!])

                myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.gray, range: NSRange(location:0,length:1))
                lbNumberOrdinal.attributedText = myMutableString
            case UISwipeGestureRecognizerDirection.up: break
                //print("Swiped up")
            default:
                break
            }
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ToDetail" {
            let vc = segue.destination as! DetailViewController
            vc.transitioningDelegate = self
            vc.imagefromViewMain = imageView.image!
        }
    }

    //MARK: NSZoomTransitionAnimating
    func transitionSourceImageView() -> UIImageView {
        return imageView
    }

    func transitionSourceBackgroundColor() -> UIColor {
        return UIColor.black
    }

    func transitionDestinationImageViewFrame() -> CGRect {
        let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
        return rect
    }

    //MARK: UIViewControllerTransitioningDelegate
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let animator = NSZoomTransitionAnimator()
        animator.sourceVC = source
        animator.destinationVC = presented
        animator.goingForward = true
        return animator
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

<file_sep>/Animation/NSZoomTransitionAnimator.swift
//
//  NSZoomTransitionAnimator.swift
//  NSZoomTransitionAnimator
//
//  Created by naoyashiga on 2015/06/25.
//  Copyright (c) 2015年 naoyashiga. All rights reserved.
//

import UIKit

@objc public protocol NSZoomTransitionAnimating {
    func transitionSourceImageView() -> UIImageView
    func transitionSourceBackgroundColor() -> UIColor
    func transitionDestinationImageViewFrame() -> CGRect
}

let kForwardAnimationDuration: TimeInterval = 0.1
let kForwardCompleteAnimationDuration: TimeInterval = 0.1
let kBackwardAnimationDuration: TimeInterval = 0.1
let kBackwardCompleteAnimationDuration: TimeInterval = 0.1

class NSZoomTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    var goingForward: Bool = false
    var sourceVC = UIViewController()
    var destinationVC = UIViewController()

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        if goingForward {
            return kForwardAnimationDuration + kForwardCompleteAnimationDuration;
        } else {
            return kBackwardAnimationDuration + kBackwardCompleteAnimationDuration;
        }
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let containerView = transitionContext.containerView
        let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
        let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!

        let sourceImageView = UIImageView()
        var destinationImageView = UIImageView()

        var destinationImageViewFrame = CGRect()

        toVC.view.frame = transitionContext.finalFrame(for: toVC)

        containerView.addSubview(fromVC.view)
        containerView.addSubview(toVC.view)

        toVC.view.setNeedsLayout()
        toVC.view.layoutIfNeeded()

        if let sourceViewController = sourceVC as? NSZoomTransitionAnimating {
//            sourceImageView = sourceViewController.transitionSourceImageView()
            sourceImageView.image = sourceViewController.transitionSourceImageView().image
            sourceImageView.frame = sourceViewController.transitionSourceImageView().frame
            containerView.addSubview(sourceImageView)
        }

        if let destinationViewController = destinationVC as? NSZoomTransitionAnimating {
            destinationImageView = destinationViewController.transitionSourceImageView()
            destinationImageView.isHidden = true

            destinationImageViewFrame = destinationViewController.transitionDestinationImageViewFrame()
        }

        if self.goingForward {
            UIView.animate(withDuration: kForwardAnimationDuration, delay: 0, options: .curveEaseOut, animations: {
                sourceImageView.frame = destinationImageViewFrame

                }, completion: {(finished: Bool) in
                    if finished {
                        destinationImageView.isHidden = false
                        sourceImageView.removeFromSuperview()
                    }
                    transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            })
        } else {
            UIView.animate(withDuration: kBackwardAnimationDuration, delay: 0, options: .curveEaseOut, animations: {
                sourceImageView.frame = destinationImageViewFrame
                print(sourceImageView.frame)

                }, completion: {(finished: Bool) in
                    if finished {
                        destinationImageView.removeFromSuperview()

                        print(sourceImageView.frame)
                        sourceImageView.removeFromSuperview()
                    }

                    transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            })
        }
    }
}
<file_sep>/Animation/NavigationController.swift
//
//  NavigationController.swift
//  NSZoomTransitionAnimator
//
//  Created by naoyashiga on 2015/06/29.
//  Copyright (c) 2015年 naoyashiga. All rights reserved.
//

import UIKit

class NavigationController: UINavigationController, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {

//        if fromVC.conformsToProtocol(NSZoomTransitionAnimating) && toVC.conformsToProtocol(NSZoomTransitionAnimating) {
//            let animator = NSZoomTransitionAnimator()
//            animator.sourceVC = fromVC
//            animator.destinationVC = toVC
//            animator.goingForward = (operation == UINavigationControllerOperation.push)
//            return animator
//        }
        let animator = NSZoomTransitionAnimator()
        animator.sourceVC = fromVC
        animator.destinationVC = toVC
        animator.goingForward = (operation == UINavigationControllerOperation.push)
        return animator

        //return nil
    }
}
<file_sep>/Animation/MapKitViewController.swift
//
//  MapKitViewController.swift
//  Animation
//
//  Created by <NAME> on 1/25/17.
//  Copyright © 2017 <NAME>. All rights reserved.
//

import UIKit
import MapKit

class MapKitViewController: UIViewController,MKMapViewDelegate, CLLocationManagerDelegate,NSZoomTransitionAnimating, UIViewControllerTransitioningDelegate {
    @IBOutlet weak var mapView: MKMapView!
    var locationManager = CLLocationManager()
    var image = UIImage()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
        self.navigationItem.hidesBackButton = true
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations[0]
        let center = CLLocationCoordinate2D.init(latitude: (location.coordinate.latitude), longitude: (location.coordinate.longitude))
        let region = MKCoordinateRegion.init(center: center, span: MKCoordinateSpan.init(latitudeDelta: 0.01, longitudeDelta: 0.01))
        self.mapView.setRegion(region, animated: true)
        self.mapView.showsUserLocation = true
        //self.locationManager.stopUpdatingLocation()
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error : " + error.localizedDescription)
    }

    func transitionSourceImageView() -> UIImageView {
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        imageView.image = image
        return imageView
    }

    func transitionSourceBackgroundColor() -> UIColor {
        return view.backgroundColor!
    }

    func transitionDestinationImageViewFrame() -> CGRect {
        return mapView.frame
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! DetailViewController
        vc.transitioningDelegate = self
        vc.imagefromViewMain = image

    }
    //MARK: UIViewControllerTransitioningDelegate

    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let animator = NSZoomTransitionAnimator()
        animator.sourceVC = source
        animator.destinationVC = presented
        animator.goingForward = true
        return animator
    }

}

repo_language: Swift


text:
<file_sep>import React from 'react';
import PropTypes from 'prop-types';

function BeerDetail(props) {
  return (

{props.selectedBeer.name}

{props.selectedBeer.brewer}

{props.selectedBeer.description}

{props.selectedBeer.abv}

{props.selectedBeer.price}

{props.selectedBeer.remaining}

  );
}

BeerDetail.propTypes = {
  selectedBeer: PropTypes.object
};

export default BeerDetail;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';

function Beer(props){

;
  const beerInformation =

{props.name}

{props.brewer}

{props.description}

{props.abv}

{props.price}

{props.remaining}

;
  if (props.currentRouterPath === '/admin') {
    return (

 {props.onBeerSelection(props.beerId);}}>
        {beerInformation}

    );
  } else {
    return (

        {beerInformation}

    );
  }

}

Beer.propTypes = {
  name: PropTypes.string.isRequired,
  brewer: PropTypes.string.isRequired,
  description: PropTypes.string,
  abv: PropTypes.string,
  price: PropTypes.string,
  remaining: PropTypes.string
};

export default Beer;
<file_sep>

#ReactTapRoom

# Epicodus TapRoom Website #

#### By_**<NAME>**_ 6/24/18

## Description ##

This is a website that shows a list of beers available at a tap room and allows an admin to add a keg.

## Specifications ##
It should:

* 1. Display a List of available beers
* 2. Display a page detailing each beer
* 3. Include an option for an admin to add beers

## To Deploy ##
Run the following commands in the command line:
* 1. Run npm install
* 2. Run webpack to compile the project
* 3. Run npm run start

## Known bugs ##

_No known bugs_

## Technologies used ##
* HTML5/css
* Javascript
* npm (Node Package Manager)
* React

## WorkFlowDiagram ##

<img src="src/assets/images/EpicodusTapRoom.jpg" width="100 height="10

![](src/assets/images/EpicodusTapRoom.jpg)
<file_sep>import React from 'react';
import Beer from './Beer';
import PropTypes from 'prop-types';

function BeerList(props){
  return (

      {Object.keys(props.beerList).map(function(beerId) {
        var beer =props.beerList[beerId];
        return <Beer
          name={beer.name}
          brewer={beer.brewer}
          description={beer.description}
          abv={beer.abv}
          price={beer.price}
          remaining={beer.remaining}
          currentRouterPath= {props.currentRouterPath}
          key={beerId}
          beerId={beerId}
          onBeerSelection={props.onBeerSelection}/>;
      })}

  );
}

BeerList.propTypes = {
  beerList: PropTypes.object,
  currentRouterPath: PropTypes.string,
  onBeerSelection: PropTypes.func
};

export default BeerList;

languages: Markdown JavaScript

repo_name: Coderoper/ReactTapRoom


text:
<repo_name>logon2ashwin/react_login_UI<file_sep>/src/components/login/Login.jsx
import React, { Component, Fragment, createRef } from "react";
import axios from "axios";
import { connect } from "react-redux";
import { login } from "store/actions";
import config from "../../../config";
import "./Login.scss";

const mapDispatchToProps = () =>  {
  return {
    login
  }
}

class Login extends Component {
  constructor(props) {
    super();
    this.state = {
      isLogin: true,
    };
    //  Refs for loginform
    this.loginUserName = createRef();
    this.loginpassword = createRef();
    //  Refs for signup Form
    this.signupUsername = createRef();
    this.signupFirstname = createRef();
    this.signupLastName = createRef();
    this.signupEmail = createRef();
    this.signupPassword = createRef();
    this.signupGender = createRef();
    this.signupCountry = createRef();
  }
  getLoginForm = () => {
    return (
      <Fragment>

          <input className="login-input" ref={this.loginUserName} type="text" required />
           this.loginUserName.current.focus()} > Username

          <input className="login-input" ref={this.loginpassword} type="password" required />
           this.loginpassword.current.focus()} > Password

      </Fragment>
    );
  };

  getSignupForm = () => {
    return (
      <Fragment>

          <input className="login-input" ref={this.signupUsername} type="text" required />
           this.signupUsername.current.focus()}> Username

          <input className="login-input" ref={this.signupFirstname} type="text" required />
           this.signupFirstname.current.focus()}> First Name

          <input className="login-input" ref={this.signupLastName} type="text" required />
           this.signupLastName.current.focus()}> Last Name

          <input className="login-input" ref={this.signupEmail} type="email" required />
           this.signupEmail.current.focus()}> Email

          <input className="login-input" ref={this.signupPassword} type="password" required />
           this.signupPassword.current.focus()}> Password

           Gender

                <input id="male" name="gender" type="radio" />
                Male

                <input id="female" name="gender" type="radio" />
                Female

        <select className="login-select" ref={this.signupCountry} id="country" name="country" selected="Country">
          <option className="login-select-options" value="0">Country</option>
          <option className="login-select-options" value="india">India</option>
          <option className="login-select-options" value="china">China</option>
          <option className="login-select-options" value="usa">USA</option>
          <option className="login-select-options" value="russia">Russia</option>
        </select>

      </Fragment>
    );
  };

  switchForm = (event) => {
    if(event) event.preventDefault();
    if(this.state.isLogin) {
      this.loginUserName.current.value = "";
      this.loginpassword.current.value = "";
    }else {
      this.signupUsername.current.value = "";
      this.signupFirstname.current.value = "";
      this.signupLastName.current.value = "";
      this.signupEmail.current.value = "";
      this.signupPassword.current.value = "";
      this.signupGender.current.children[1].children[0].firstElementChild.checked = false;
      this.signupGender.current.children[1].children[1].firstElementChild.checked = false;
      this.signupCountry.current.value = "0";
    }
    this.setState({
      isLogin: !this.state.isLogin,
    });
  };

  getBodyData() {
    if(this.state.isLogin) {
      return {
        userName: this.loginUserName.current.value,
        password: <PASSWORD>
      }
    }
    else {
      let gender = '';
      let country = '';
      // Gender Check
      if(this.signupGender.current.children[1].children[0].firstElementChild.checked) {
        gender = 'male';
      }
      else if (this.signupGender.current.children[1].children[1].firstElementChild.checked){
        gender = 'female'
      }
      else {
        alert('Gender not selected');
      }
      // Country Check
      if(this.signupCountry.current.value!=="0") {
        country = this.signupCountry.current.value
      }
      else {
        alert('Country not selected');
      }
      return {
        userName: this.signupUsername.current.value,
        firstName: this.signupFirstname.current.value,
        lastName: this.signupLastName.current.value,
        email: this.signupEmail.current.value,
        password: <PASSWORD>,
        gender,
        country
      }
    }
  };

  postData = (event) => {
    event.preventDefault()
    let url = `http://${config.host}:${config.port}/api/auth/${ this.state.isLogin ? "login" : "signup"}`;
    let data = this.getBodyData();
    let apiConfig = {
      method: this.state.isLogin ? "put" : "post",
      url,
      data,
    };
    let self = this;
    axios(apiConfig)
      .then(function (response) {
        if(self.state.isLogin) {
          self.props.login(response.data);
          self.props.history.push("/dashboard");
        }
        else {
          alert("User has been created login to continue");
          self.switchForm();
        }
      })
      .catch(err => {
        if(err.response.data.message) {
          alert(err.response.data.message);
        }
        if(err.response.data.errors.length) {
          alert(err.response.data.errors[0].msg);
        }
      });
  };

  render() {
    return (

        <form className="login-form-container">
          {this.state.isLogin ? this.getLoginForm() : this.getSignupForm()}

            <button onClick={event=> this.postData(event)}>{this.state.isLogin ? 'Login' : 'SignUp'}</button>
            <button onClick={event => this.switchForm(event)}> {this.state.isLogin ? "New User?" : "Existing User?"} </button>

        </form>

    );
  }
}

export default connect(null,mapDispatchToProps())(Login);
<file_sep>/server/src/config/prod.js
module.exports={
  'app': {
      'host': '0.0.0.0',
      'port': 3000
  },
  'mongo': {
      'host': '127.0.0.1',
      'port': 6379,
      'db': 'loginApp'
  }
}<file_sep>/Readme.md
## Login App Services ##

### Prerequisite ###
Node Version - v13 or above

### Setup Project ###

Run `npm install` or `yarn install` both in server folder and root folder

After that, choose the environment you want to run

```
"export ENVIRONMENT=dev" for mac, linux

"SET ENVIRONMENT=dev" for windows
```

Configure Mongo db port if you have different configuration other than default in your machine.

File path `./server/config/dev.js`

Default config will be
```
'host': '127.0.0.1',
'port': 27017
```

Use `npm run startnode` script from app root directory to start node server.

Use `npm run startApp` script from app root directory to start React application in webpack dev server.

<file_sep>/store/actions/index.js
// Login Component Actions
export const LOGIN_USER = "LOGIN_USER";
export const SIGNOUT_USER = "SIGNOUT_USER";

export const login = (data) => {
  return {
    type : LOGIN_USER,
    payload : data
  };
};

export const signout = () => {
  return {
    type : SIGNOUT_USER
  };
};


text:
<repo_name>luchoguti/scrapingWebParamotrek<file_sep>/src/views/index.hbs
{{#each dataJson as |dataTours nameTypeTour|}}

{{ nameTypeTour }}

    {{#each dataTours as |dataObj key| }}

{{ dataObj.title }}

{{ dataObj.description }}

    {{/each}}

{{/each}}<file_sep>/src/public/js/main.js
$(function () {
    $('#search').on('keyup', function (e) {
        if (e.keyCode === 13) {
            var parameters = { title: $(this).val() };
            $.ajax({
                type: "GET",
                url: '/scraping/findTitle/',
                data: parameters,
                success: function (data) {
                    var htmlDom = htmlDomFilter(data);
                    $('#container').html(htmlDom);
                },
                error: function () {
                    console.log("No se ha podido obtener la información");
                }
            });

        };
    });
});

function htmlDomFilter(arr){
    var htmlDom = '';
    Object.keys(arr).forEach(nameTag => {
        if (arr[nameTag].length > 0) {
            htmlDom += '
' +
                '
' +
                '
' + nameTag + '
' +
                '
';
            for (let j = 0; j < arr[nameTag].length; j++) {
                let toursFilter = arr[nameTag][j];
                htmlDom += '
' +
                    '
' +
                    '' +
                    '
' +
                    '
' + toursFilter.title + '
' +
                    '
' + toursFilter.description + '
' +
                    '
' +
                    '
' +
                    '
';
            }
            htmlDom += '
';
        }
    });

    if(htmlDom == ''){
        htmlDom += '
' +
        '
' +
        '
No results try again!
' +
        '
';
        htmlDom += '
';
    }
    return htmlDom;
}<file_sep>/src/views/partials/navigation.hbs

        <input class="form-control mr-sm-2" id="search" type="search" placeholder="Search in sub-tit + Intro" aria-label="Search">

            View Json Scriping

<file_sep>/src/index.js
const express = require ('express');
const path = require('path');
const exhbs = require('express-handlebars');

//Initilizations
const app = express();

//Settings
app.set('port', process.env.PORT || 3000);
app.set('views',path.join(__dirname,'views'));
app.engine('.hbs',exhbs({
    defaultLayout:'main',
    layoutsDir:path.join(app.get('views'),'layouts'),
    partialsDir:path.join(app.get('views'),'partials'),
    extname:'.hbs'
}));
app.set('view engine','.hbs');

//Routes
app.use(require('./routes/routeHome'));
app.use(require('./routes/routeScraping'));

//Static Files
app.use(express.static(path.join(__dirname,'public')));

//Server is listenning
app.listen(app.get('port'),()=>{
    console.log('Server on port', app.get('port'));
});<file_sep>/src/routes/routeHome.js
const router = require('express').Router();
const LocalStorage =  require('node-localstorage').LocalStorage;
const getJson = require('../models/getJson');
localStorage = new LocalStorage('./scratch');

router.get('/', async(request, response) => {
    const url = "https://scripingwebparamotrek.herokuapp.com/scraping/paramotrek";
    const dataJson = await getJson.getData(url);
    localStorage.setItem('scripingParamotrek',JSON.stringify(dataJson));
    response.render('index',{dataJson});
});

router.get('/scraping/findTitle/',(request, response) => {
    let paramTitle = request.query.title.toLowerCase();
    let localData = JSON.parse(localStorage.getItem('scripingParamotrek'));
    newDataToursResp = {};
    Object.keys(localData).forEach(nameTag => {
        let findInData = localData[nameTag].filter(titleData =>{
            return titleData.title.toLowerCase().indexOf(paramTitle) !== -1
        });
        newDataToursResp[nameTag] = findInData;
    });
    response.json(newDataToursResp);
    response.end();
});

module.exports = router;<file_sep>/src/models/scraping.js
const cheerio = require('cheerio');
const request = require('request');

function doRequest(url) {
    return new Promise(function (resolve, reject) {
        request(url, async (error, response, html) => {
            if (!error && response.statusCode == 200) {
                resolve(html);
            } else {
                reject(error);
            }
        });
    });
}

async function main(datosWeb) {
    const dataTours = {};
    for (let j = 0; j < datosWeb.length; j++) {
        let res = await doRequest(datosWeb[j][1]);
        const dataToursResp = [];
        const $ = cheerio.load(res);
        $('.classic2_cols').each(async (i, element) => {
            const img = $(element).find('.tour_image > img').attr('src').trim();
            const title = $(element).find('div.portfolio_info_wrapper a.tour_link > h4').text().trim();
            const description = $(element).find('div.portfolio_info_wrapper div.tour_excerpt > p').text().trim();
            const moreInformation = $(element).find('.tour_image').attr('href').trim();
            await dataToursResp.push({ title: title, description: description, img: img, moreInformation:moreInformation });
        });
        let namePage = datosWeb[j][0];
        dataTours[namePage] = dataToursResp;
    }
    return dataTours;
}

module.exports = {
    main
}

languages: Handlebars JavaScript

repo_language: Handlebars

repo_name: luchoguti/scrapingWebParamotrek