branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>caleuanhopkins/portfolio-2015<file_sep>/app/js/modules/core/directives/core.client.directives.js 'use strict'; angular.module('core').directive('parallax', function () { return { restrict: 'A', link: function parallax(scope, element, attrs) { parallax(); $(window).scroll(function(e) { parallax(); }); function parallax(){ var plxBackground = $("#js-parallax-background"); var plxWindow = $("#js-parallax-window"); var plxWindowTopToPageTop = $(plxWindow).offset().top; var windowTopToPageTop = $(window).scrollTop(); var plxWindowTopToWindowTop = plxWindowTopToPageTop - windowTopToPageTop; var plxBackgroundTopToPageTop = $(plxBackground).offset().top; var windowInnerHeight = window.innerHeight; var plxBackgroundTopToWindowTop = plxBackgroundTopToPageTop - windowTopToPageTop; var plxBackgroundTopToWindowBottom = windowInnerHeight - plxBackgroundTopToWindowTop; var plxSpeed = 0.35; plxBackground.css('top', - (plxWindowTopToWindowTop * plxSpeed) + 'px'); } } }; }).directive('header', function() { return { restrict: 'E', link: function headroom(scope, element, attrs){ var myElement = document.querySelector("header"); // construct an instance of Headroom, passing the element var headroom = new Headroom(myElement); // initialise headroom.init(); var menuToggle = $('#js-centered-navigation-mobile-menu').unbind(); $('#js-centered-navigation-menu').removeClass("show"); menuToggle.on('click', function(e) { e.preventDefault(); $('#js-centered-navigation-menu').slideToggle(function(){ if($('#js-centered-navigation-menu').is(':hidden')) { $('#js-centered-navigation-menu').removeAttr('style'); } }); }); } } }); <file_sep>/app/js/modules/core/services/core.client.services.js 'use strict'; //Articles service used for communicating with the articles REST endpoints angular.module('core').factory('dataPassage', ['$http', '$cookies', '$q', '$injector', '$cookieStore', function ($http, $cookies, $q, $injector, $cookieStore) { return { apiQuery: function (passedData){ var url = siteBaseUrl+'/api/1.0/'+passedData.apiController+'/'; if(typeof passedData.apiAction != 'undefined'){ url=url+passedData.apiAction+'/'; } if(typeof passedData.params != 'undefined'){ url=url+passedData.params; } //console.log(url); var req = { method: passedData.method, url: url, headers: { 'contentType': 'application/json' }, data: passedData.data } return $http(req) .success(function(data){ return data; }) .error(function(data, status){ return data; }); } } } ]);<file_sep>/app/js/modules/core/controllers/site.client.controller.js 'use strict'; angular.module('core').controller('HomepageController', ['$scope', '$stateParams', '$state', '$location', function($scope, $stateParams, $state, $location) { } ])<file_sep>/app/js/dist/all.min.js 'use strict'; var siteBaseUrl = "http://port.callumhopkins.com"; // Init the application configuration module for AngularJS application var ApplicationConfiguration = (function() { // Init module configuration options var applicationModuleName = 'portfolio2015'; var applicationModuleVendorDependencies = ['ngResource', 'ngRoute', 'ngCookies', 'ngAnimate', 'ui.select', 'ngTouch', 'ngSanitize', 'ui.router', 'ui.bootstrap', 'ui.utils', 'angular-ladda', 'angular-loading-bar']; // Add a new vertical module var registerModule = function(moduleName, dependencies) { // Create angular module angular.module(moduleName, dependencies || []); // Add the module to the AngularJS configuration file angular.module(applicationModuleName).requires.push(moduleName); }; return { applicationModuleName: applicationModuleName, applicationModuleVendorDependencies: applicationModuleVendorDependencies, registerModule: registerModule }; })(); 'use strict'; var $urlRouterProviderRef = null; var $stateProviderRef = null; var $locationProviderRef = null; angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies); angular.module(ApplicationConfiguration.applicationModuleName).config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$httpProvider', '$uiViewScrollProvider', function($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider, $uiViewScrollProvider) { $urlRouterProviderRef = $urlRouterProvider; $locationProvider.html5Mode(true); $uiViewScrollProvider.useAnchorScroll(); $stateProviderRef = $stateProvider; $locationProviderRef = $locationProvider; $urlRouterProvider.rule(function($injector, $location) { if($location.protocol() === 'file') return; var path = $location.path() // Note: misnomer. This returns a query object, not a search string , search = $location.search() , params ; // check to see if the path already ends in '/' if (path[path.length - 1] === '/') { return; } // If there was no search string / query params, return with a `/` if (Object.keys(search).length === 0) { return path + '/'; } // Otherwise build the search string and return a `/?` prefix params = []; angular.forEach(search, function(v, k){ params.push(k + '=' + v); }); return path + '/?' + params.join('&'); }); } ]); angular.module(ApplicationConfiguration.applicationModuleName).config(['$interpolateProvider','$routeProvider','$locationProvider','$resourceProvider', function($interpolateProvider,$routeProvider,$locationProvider,$resourceProvider) { $interpolateProvider.startSymbol('[{['); $interpolateProvider.endSymbol(']}]'); $resourceProvider.defaults.stripTrailingSlashes = true; } ]); angular.module(ApplicationConfiguration.applicationModuleName).config(['$urlMatcherFactoryProvider', function ($urlMatcherFactoryProvider) { $urlMatcherFactoryProvider.caseInsensitive(true); $urlMatcherFactoryProvider.strictMode(true); } ]); angular.element(document).ready(function() { if (window.location.hash === '#_=_') window.location.hash = '#!'; angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]); }); 'use strict'; // Use Applicaion configuration module to register a new module ApplicationConfiguration.registerModule('core'); 'use strict'; angular.module('core').config(['$stateProvider', '$urlRouterProvider', 'cfpLoadingBarProvider', function($stateProvider, $urlRouterProvider, $cfpLoadingBarProvider) { $cfpLoadingBarProvider.includeSpinner = false; // Redirect to home view when route not found } ]); 'use strict'; // Setting up route angular.module('core').config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$httpProvider', function($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) { // Redirect to home view when route not found $urlRouterProvider.otherwise("/"); $stateProvider .state('public', { abstract: true, template: "<div ui-view />", data: { } }) .state('public.home', { url: '/', controller: 'HomepageController', templateUrl: 'app/js/modules/core/views/homepage.client.view.html', }) .state('public.404', { url: '/404/', templateUrl: 'app/js/modules/core/views/404.client.view.html', }) } ]); 'use strict'; angular.module('core').controller('HomepageController', ['$scope', '$stateParams', '$state', '$location', function($scope, $stateParams, $state, $location) { } ]) 'use strict'; angular.module('core').directive('parallax', function () { return { restrict: 'A', link: function parallax(scope, element, attrs) { parallax(); $(window).scroll(function(e) { parallax(); }); function parallax(){ var plxBackground = $("#js-parallax-background"); var plxWindow = $("#js-parallax-window"); var plxWindowTopToPageTop = $(plxWindow).offset().top; var windowTopToPageTop = $(window).scrollTop(); var plxWindowTopToWindowTop = plxWindowTopToPageTop - windowTopToPageTop; var plxBackgroundTopToPageTop = $(plxBackground).offset().top; var windowInnerHeight = window.innerHeight; var plxBackgroundTopToWindowTop = plxBackgroundTopToPageTop - windowTopToPageTop; var plxBackgroundTopToWindowBottom = windowInnerHeight - plxBackgroundTopToWindowTop; var plxSpeed = 0.35; plxBackground.css('top', - (plxWindowTopToWindowTop * plxSpeed) + 'px'); } } }; }).directive('header', function() { return { restrict: 'E', link: function headroom(scope, element, attrs){ var myElement = document.querySelector("header"); // construct an instance of Headroom, passing the element var headroom = new Headroom(myElement); // initialise headroom.init(); var menuToggle = $('#js-centered-navigation-mobile-menu').unbind(); $('#js-centered-navigation-menu').removeClass("show"); menuToggle.on('click', function(e) { e.preventDefault(); $('#js-centered-navigation-menu').slideToggle(function(){ if($('#js-centered-navigation-menu').is(':hidden')) { $('#js-centered-navigation-menu').removeAttr('style'); } }); }); } } }); 'use strict'; //Articles service used for communicating with the articles REST endpoints angular.module('core').factory('dataPassage', ['$http', '$cookies', '$q', '$injector', '$cookieStore', function ($http, $cookies, $q, $injector, $cookieStore) { return { apiQuery: function (passedData){ var url = siteBaseUrl+'/api/1.0/'+passedData.apiController+'/'; if(typeof passedData.apiAction != 'undefined'){ url=url+passedData.apiAction+'/'; } if(typeof passedData.params != 'undefined'){ url=url+passedData.params; } //console.log(url); var req = { method: passedData.method, url: url, headers: { 'contentType': 'application/json' }, data: passedData.data } return $http(req) .success(function(data){ return data; }) .error(function(data, status){ return data; }); } } } ]);<file_sep>/app/js/modules/core/config/core.client.routes.js 'use strict'; // Setting up route angular.module('core').config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$httpProvider', function($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) { // Redirect to home view when route not found $urlRouterProvider.otherwise("/"); $stateProvider .state('public', { abstract: true, template: "<div ui-view />", data: { } }) .state('public.home', { url: '/', controller: 'HomepageController', templateUrl: 'app/js/modules/core/views/homepage.client.view.html', }) .state('public.404', { url: '/404/', templateUrl: 'app/js/modules/core/views/404.client.view.html', }) } ]);
0a3a472cf2e6bba5ff62c26c3af2888d637f13ee
[ "JavaScript" ]
5
JavaScript
caleuanhopkins/portfolio-2015
adffb9b53f3cfb0cb5727d5cb84aa334b3013449
20d81d30abbbecc49da8d73df42c7c271bfa5eee
refs/heads/master
<repo_name>jdiperi88/styled_components<file_sep>/src/Global.js import { createGlobalStyle } from "styled-components"; import { normalize } from "polished"; const GlobalStyle = createGlobalStyle` ${normalize()}; html{ box-sizing:border-box; } *,*::before, *::after{ box-sizing:inherit; } body{ background: red; padding: 65px 0 0 ; } main{ width: 90%; margin: 0 auto; } `; export default GlobalStyle; <file_sep>/src/layouts/Header.js import React, { Component } from "react"; import logo from "../logo.svg"; import styled from "styled-components"; import { purple } from "../utilties"; import { Elevation, fixed, serif } from "../utilties"; export default class Header extends Component { render() { return ( <AppHeader> <img src={logo} alt="logo" className="logo" /> <h1>Test</h1> </AppHeader> ); } } const AppHeader = styled.header` background: ${purple}; ${Elevation[2]} padding: 10px; width: 100%; ${serif} ${fixed({ x: 0, y: 0 })} .logo { width: 60px; } `;
be8820efa394664c1f6cf774ee7dad19d3688008
[ "JavaScript" ]
2
JavaScript
jdiperi88/styled_components
27b5cc07972d91740f0dc210ff9d1f5888830e7e
74294e1bbde5835f223ff6ec161a8c3c105ea43a
refs/heads/master
<repo_name>AJSO/Laravel-REST-API-Lumen<file_sep>/app/Http/Middleware/Authenticate.php <?php namespace App\Http\Middleware; use Closure; //defining a username and password define('USERNAME','ecurut'); define('PASSWORD', '<PASSWORD>'); class Authenticate { public function handle($request, Closure $next) { //getting values from headers //if the user is authenticated accepting the request if($request->header('PHP_AUTH_USER') == USERNAME && $request->header('PHP_AUTH_PW') == PASSWORD){ return $next($request); //else displaying an unauthorized message }else{ $content = array(); $content['error'] = true; $content['message'] = 'Unauthorized Request'; return response()->json($content, 401); } } }<file_sep>/app/Http/Controllers/AnswerController.php <?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Validator; use Illuminate\Http\Request; use App\Answer; class AnswerController extends Controller { public function submit(Request $request){ $validator = Validator::make($request->all(), [ 'answer'=>'required', 'user_id'=>'required', 'question_id'=>'required' ]); if($validator->fails()){ return array( 'error' => true, 'message' => $validator->errors()->all() ); } $answer = new Answer; $answer->answer = $request->input('answer'); $answer->question_id= $request->input('question_id'); $answer->user_id= $request->input('user_id'); $answer->save(); return array('error'=>false, 'answer'=>$answer); } }<file_sep>/app/Http/Controllers/CategoryController.php <?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Validator; use Illuminate\Http\Request; use App\Category; class CategoryController extends Controller { public function create(Request $request){ $validator = Validator::make($request->all(), [ 'name'=>'required|unique:categories' ]); if($validator->fails()){ return array( 'error' => true, 'message' => $validator->errors()->all() ); } $category = new Category; $category->name = $request->input('name'); $category->save(); return array('error'=>false, 'category'=>$category); } }<file_sep>/app/Http/Controllers/QuestionController.php <?php namespace App\Http\Controllers; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Support\Facades\Validator; use Illuminate\Http\Request; use App\Question; use App\Category; class QuestionController extends Controller { public function create(Request $request){ $validator = Validator::make($request->all(), [ 'question'=>'required', 'user_id'=>'required' ]); if($validator->fails()){ return array( 'error' => true, 'message' => $validator->errors()->all() ); } $question = new Question; $question->question = $request->input('question'); $question->user_id= $request->input('user_id'); $question->category_id= $request->input('category_id'); $question->save(); return array('error'=>false, 'question'=>$question); } public function getAll(){ $questions = Question::all(); foreach($questions as $question){ $question['answercount'] = count($question->answers); unset($question->answers); } return array('error'=>false, 'questions'=>$questions); } public function getByCategory($category_id){ try{ $questions = Category::findOrFail($category_id)->questions; foreach($questions as $question){ $question['answercount'] = count($question->answers); unset($question->answers); } return array('error'=>false, 'questions'=>$questions); }catch(ModelNotFoundException $e){ return array('error'=>true, 'message'=>'Invalid Category ID'); } } }<file_sep>/app/Http/Controllers/UserController.php <?php namespace App\Http\Controllers; use Illuminate\Hashing\BcryptHasher; use Illuminate\Support\Facades\Validator; use Illuminate\Http\Request; use App\User; class UserController extends Controller { //this function is used to register a new user public function create(Request $request) { //creating a validator $validator = Validator::make($request->all(), [ 'username' => 'required|unique:users', 'password' => '<PASSWORD>', 'email' => 'required|unique:users' ]); //if validation fails if ($validator->fails()) { return array( 'error' => true, 'message' => $validator->errors()->all() ); } //creating a new user $user = new User(); //adding values to the users $user->username = $request->input('username'); $user->email = $request->input('email'); $user->password = (new BcryptHasher)-><PASSWORD>($request->input('password')); //saving the user to database $user->save(); //unsetting the password so that it will not be returned unset($user->password); //returning the registered user return array('error' => false, 'user' => $user); } //function for user login public function login(Request $request) { $validator = Validator::make($request->all(), [ 'username' => 'required', 'password' => '<PASSWORD>' ]); if ($validator->fails()) { return array( 'error' => true, 'message' => $validator->errors()->all() ); } $user = User::where('username', $request->input('username'))->first(); if (count($user)) { if (password_verify($request->input('password'), $user->password)) { unset($user->password); return array('error' => false, 'user' => $user); } else { return array('error' => true, 'message' => 'Invalid password'); } } else { return array('error' => true, 'message' => 'User not exist'); } } //getting the questions for a particular user public function getQuestions($id) { $questions = User::find($id)->questions; foreach ($questions as $question) { $question['answercount'] = count($question->answers); unset($question->answers); } return array('error' => false, 'questions' => $questions); } }
2ee2ac9ff28f34937090fd39e2f3c20a3d9af80e
[ "PHP" ]
5
PHP
AJSO/Laravel-REST-API-Lumen
76764e54431c3630e727667be3c62f0828f5da87
d06f16bf5791cbfd61ccdb15898ecc4dce0d77de
refs/heads/master
<file_sep>import pytest def test_1_that_does_not_need_session_resource(): print("test_1_that_does_not_need_session_resource") def test_2_that_does(manually_session_resource): print("test_2_that_does")<file_sep>import pytest """ Уровень фикстуры может принимать следующие возможные значения: “function”, “cls”, “module”, “session”. Значение по умолчанию = “function”. function – фикстура запускается для каждого теста cls – фикстура запускается для каждого класса module – фикстура запускается для каждого модуля session – фикстура запускается для каждой сессии (то есть фактически один раз) """ @pytest.fixture(scope="function") def resource_setup(request): print("\nconnect to db") db = {"Red": 1, "Blue": 2, "Green": 3} def resource_teardown(): print("\ndisconnect") request.addfinalizer(resource_teardown) return db def test_db(resource_setup): for k in resource_setup.keys(): print("color {0} has id {1}".format(k, resource_setup[k])) def test_red(resource_setup): assert resource_setup["Red"] == 1 def test_blue(resource_setup): assert resource_setup["Blue"] != 1 <file_sep>import pytest import sys @pytest.mark.xfail() def test_failed(): assert False @pytest.mark.xfail(sys.platform != "win64", reason="requires windows 64bit") def test_failed_for_not_win32_systems(): assert False @pytest.mark.skipif(sys.platform != "win64", reason="requires windows 64bit") def test_skipped_for_not_win64_systems(): assert False def test_1(): print("test_1") @pytest.mark.critital_tests def test_2(): print("test_2") def test_3(): print("test_3") <file_sep>import pytest @pytest.fixture() def fixture1(request, fixture2): print("fixture1") @pytest.fixture() def fixture2(request, fixture3): print("fixture2") @pytest.fixture() def fixture3(request): print("fixture3") def test_1(fixture1): print("test_1") def test_2(fixture2): print("test_2") <file_sep>import pytest @pytest.fixture(scope="session", autouse=True) def auto_session_resource(request): """ Auto session resource fixture """ print("auto_session_resource_setup") def auto_session_resource_teardown(): print("auto_session_resource_teardown") request.addfinalizer(auto_session_resource_teardown) @pytest.fixture(scope="session") def manually_session_resource(request): """ Manual set session resource fixture """ print("manually_session_resource_setup") def manually_session_resource_teardown(): print("manually_session_resource_teardown") request.addfinalizer(manually_session_resource_teardown) @pytest.fixture(scope="function") def function_resource(request): """ Function resource fixture """ print("function_resource_setup") def function_resource_teardown(): print("function_resource_teardown") request.addfinalizer(function_resource_teardown) <file_sep>import pytest def test_3_that_uses_all_fixtures(manually_session_resource, function_resource): print("test_2_that_does_not")<file_sep>import pytest @pytest.fixture() def resource_setup(request): print("resource_setup") def resource_teardown(): print("resource_teardown") request.addfinalizer(resource_teardown) @pytest.fixture(scope="function", autouse=True) def another_resource_setup_with_autouse(request): print("another_resource_setup_with_autouse") def resource_teardown(): print("another_resource_teardown_with_autouse") request.addfinalizer(resource_teardown) def test_1_that_needs_resource(resource_setup): print("test_1_that_needs_resource") def test_2_that_does_not(): print("test_2_that_does_not") @pytest.mark.usefixtures("resource_setup") def test_3_that_does_again(): print("test_3_that_does_again") <file_sep># -- FILE: pytest.ini (or tox.ini) [pytest] # -- recommended but optional: python_files = tests.py *_tests.py *test.py test*py <file_sep>#!/bin/bash pytest -s simple_py_tests.py pytest -s basic_fixtures_tests.py pytest -s extended_fixtures_tests.py pytest -s extended_fixture2_tests.py pytest -s generator_fixture_tests.py pytest -s levels_fixtures_tests.py cd session\ scope/ pytest -s -v cd .. pytest -v -s request_tests.py pytest -v -s parametrizing_base_tests.py pytest -s -v multiple_fixtures_tests.py pytest -s -v marks_for_tests.py pytest -s -v exceptions_tests.py<file_sep>import pytest @pytest.yield_fixture() def resource_setup(): print("resource_setup") yield print("resource_teardown") def test_1_that_needs_resource(resource_setup): print("test_1_that_needs_resource") def test_2_that_does_not(): print("test_2_that_does_not") def test_3_that_does_again(resource_setup): print("test_3_that_does_again") <file_sep>import pytest def f(): print(1/0) def test_exception(): with pytest.raises(ZeroDivisionError): f() <file_sep>import pytest def strange_string_func(str): if len(str) > 5: return str + "?" elif len(str) < 5: return str + "!" else: return str + "." @pytest.fixture(scope="function", params=[ ("abcdefg", "abcdefg?"), ("abc", "abc!"), ("abcde", "abcde.")], ids=["len>5", "len<5", "len==5"] ) def param_test(request): return request.param def test_strange_string_func(param_test): (input, expected_output) = param_test result = strange_string_func(input) print("input: {0}, output: {1}, expected: {2}".format(input, result, expected_output)) assert result == expected_output def idfn(val): return "params: {0}".format(str(val)) @pytest.fixture(scope="function", params=[ ("abcdefg", "abcdefg?"), ("abc", "abc!"), ("abcde", "abcde.")], ids=idfn ) def param_test_idfn(request): return request.param def test_strange_string_func_with_ifdn(param_test_idfn): (input, expected_output) = param_test_idfn result = strange_string_func(input) print("input: {0}, output: {1}, expected: {2}".format(input, result, expected_output)) assert result == expected_output <file_sep>import pytest @pytest.fixture(scope="function") def resource_setup(request): print(request.fixturename) print(request.scope) print(request.function.__name__) print(request.cls) print(request.module.__name__) print(request.fspath) def test_1(resource_setup): assert True class TestClass(): def test_2(self, resource_setup): assert True
d0641518a452fba44bfc0c4cd39b4b3f7140d3a2
[ "Shell", "Python", "INI" ]
13
Python
levkovalenko/testers_course
aa1f44922ca04fe050d08dfedabc862f4a4d2da6
883d4a4f8071a9d362a2788d64127fba77441b0b
refs/heads/main
<repo_name>ThomasDev6/UbPrimeur<file_sep>/CODE/stock.php <?php require_once("connect.php"); $type = $_POST["type"]; $nom = $_POST["nomMarch"]; $ajout = $_POST["stock"]; if($type == "fru"){ $getQuantite = "SELECT quantiteFruit, idFruit FROM Fruit WHERE nomFruit = '$nom'"; $rep = $co->query($getQuantite); while($row = $rep->fetch_assoc()){ $quant = $row["quantiteFruit"]; $id = $row["idFruit"]; } $newQuant = $ajout + $quant; $req = "UPDATE Fruit SET quantiteFruit = '$newQuant' WHERE idFruit = '$id' "; $rep2 = $co->query($req); }else{ $getQuantite = "SELECT quantiteLeg FROM Legume WHERE nomLeg = '$nom'"; $rep = $co->query($getQuantite); while($row = $rep->fetch_assoc()){ $quant = $row["quantiteLeg"]; } $newQuant = $ajout + $quant; $req = "UPDATE Legume SET quantiteLeg = '$newQuant' WHERE nomLeg = '$nom'"; $rep2 = $co->query($req); } header("Location: webmastermain.php"); exit(); ?><file_sep>/CODE/legumes.php <?php session_start(); if($_SESSION['idCli'] != 0){ $idclient = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } ?> <!DOCTYPE html> <html lang="fr"> <meta charset="UTF-8"> <link rel="stylesheet" href="css/styleFruit.css" /> <title>UberPrimeur</title> <!--Menu de nav--> <div class="header"> <div class="logo"> <a href="accueil.php"><img id="logoNav" src="../LOGOS/logo5.PNG" width=400 height=62 alt></a> </div> <div class="menuNav"> <a href="a_propos.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/apropos.png" height=18 width=18 alt>À propos</a> <a href="nospaniers.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/nospaniers.png" height=18 width=18 alt>Nos paniers</a> <a href="fruits.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/fruit.jpg" height=18 width=18 alt>Fruits</a> <a href="legumes.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/legume.png" height=18 width=18 alt>Légumes</a> <a href="panier.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/panier.png" height=18 width=18 alt>Panier</a> <a href="compte.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/compte.jpg" height=18 width=18 alt>Compte</a> </div> </div> <!--Début du body--> <body> <?php require_once("connect.php"); $req = "SELECT * FROM legume"; $rep = $co->query($req); $count = $rep->num_rows; $count = $count/4; while($row = $rep->fetch_assoc()){ echo "<div id =\"ligne1\" class=\"ligne\">"; echo "<div class=\"fruit\"> <img src=\"../PHOTOS/".$row["nomPhotoLeg"]."\" height=200 width=300 alt> <p class=\"nomfruit\">".$row["nomLeg"]." (".$row["detailVenteLeg"].") "."</p> <p class=\"nomfruit\">".$row["prixLeg"]." € </p> <p class=\"nomfruit\"> Stock disponible : ".$row["quantiteLeg"]."</p> <form method=\"post\" action=\"ajoutPanierL.php?idL=".$row["idLegume"]."\"> <input name=\"quantite\" type=\"number\" value=\"0\" max=\"". $row["quantiteLeg"]."\"> <input name =\"ajout\" id=\"btnAjout\" type=\"submit\" value=\"Ajouter au panier\"> </form> </div>"; echo "</div>"; } ?> </body> <!-- FOOTER --> <div class="footer"> <div id="dispoFoot"> <div id="certif"> <p>Site réalisé par <NAME>, <NAME> et <NAME> ©</p><p id="ita">Tous droits réservés</p> </div> <div class="reseaux"> <a href="https://www.instagram.com/uberprimeur_/"><img src="../PHOTOS/insta.png" height=40 width=40 alt ></a> <a href="https://twitter.com/UPrimeur"><img src="../PHOTOS/twitter.png" height=40 width=40 alt ></a> </div> </div> </br> <a href="webmaster.php" id="webmaster">accès webmaster</a> </div> </html><file_sep>/CODE/ajoutPanierL.php <?php require_once("connect.php"); session_start(); if($_SESSION['idCli'] != 0){ $idclient = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } $idL = $_GET["idL"]; $quantite = $_POST["quantite"]; $testQu = "SELECT quantiteLeg FROM legume WHERE idLegume = $idL"; $repQu = $co->query($testQu); while($rowQu = $repQu->fetch_assoc()){ $stockDispo = $rowQu["quantiteLeg"]; } if( $quantite > $stockDispo){ header("Location: legumes.php"); exit; }else{ if($quantite < 1){ header("Location: legumes.php"); exit; } $test = "SELECT * FROM panierclient WHERE clientPanier = '$idclient'"; $exTest = $co->query($test); $numRows = $exTest->num_rows; if($numRows != 0){ while($row = $exTest->fetch_assoc()){ $idPanierC = $row["idPanierClient"]; } }else{ $sql = "INSERT INTO panierclient VALUES (null,'$idclient')"; $rep = $co->query($sql); $idPanierC = $co->insert_id; } $req = "INSERT INTO lignepanierleg VALUES('$idL','$idclient','$idPanierC','$quantite')"; $ex = $co->query($req); header("Location: legumes.php"); exit; } ?><file_sep>/CODE/mdp.php <?php require_once('connect.php'); session_start(); if($_SESSION['idCli'] != 0){ $idCli = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } $ancienMDP = $_POST['pass']; $pass1 = $_POST['pass1']; $pass2 = $_POST['pass2']; ; $sql = "SELECT mdpClient FROM client WHERE idClient='$idCli'"; $p1 = $co->query($sql); $modif=true; $salt = "*$=²ù€;.?,È{qü=BuÐ8ƒµ´à¤"; $ancienMDP = md5($ancienMDP.$salt); while ($row = $p1->fetch_assoc() ) { $mdp = $row['mdpClient']; } if ($mdp != $ancienMDP) { $modif=false; header('Location: compte.php?modif=1'); } else if ($pass1!=$pass2) { $modif=false; header('Location: compte.php?modif=2'); } if ($modif==true) { $pass1 = md5($pass1.$salt); $sql2="UPDATE client SET mdpClient = '$pass1' WHERE idClient = '$idCli' "; $modif2 = $co->query($sql2); header('Location: compte.php?modif=3'); } ?><file_sep>/CODE/prix.php <?php require_once("connect.php"); $type = $_POST["type"]; $nom = $_POST["nomMarch"]; $new = $_POST["prix"]; if($type == "fru"){ $req = "UPDATE Fruit SET prixFruit = '$new' WHERE nomFruit = '$nom' "; $rep2 = $co->query($req); }else{ $req = "UPDATE Legume SET prixLeg = '$new' WHERE nomLeg = '$nom'"; $rep2 = $co->query($req); } header("Location: webmastermain.php"); exit();<file_sep>/CODE/coWeb.php <?php session_start(); $mdp = $_POST["password"]; if($mdp == "webmaster"){ $_SESSION['auto'] = true; header("Location: webmastermain.php" ); exit; }else{ header("Location: accueil.php"); exit; }<file_sep>/CODE/panier.php <!DOCTYPE html> <html lang="fr"> <meta charset="UTF-8"> <link rel="stylesheet" href="css/stylePanier.css" /> <title>UberPrimeur</title> <!--Début du body--> <body> <div class="header"> <div class="logo"> <a href="accueil.php"><img id="logoNav" src="../LOGOS/logo5.PNG" width=400 height=62 alt></a> </div> <div class="menuNav"> <a href="a_propos.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/apropos.png" height=18 width=18 alt>À propos</a> <a href="nospaniers.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/nospaniers.png" height=18 width=18 alt>Nos paniers</a> <a href="fruits.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/fruit.jpg" height=18 width=18 alt>Fruits</a> <a href="legumes.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/legume.png" height=18 width=18 alt>Légumes</a> <a href="panier.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/panier.png" height=18 width=18 alt>Panier</a> <a href="compte.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/compte.jpg" height=18 width=18 alt>Compte</a> </div> </div> <div class="encadre"> <p class="GT">Résumé du panier<p> <?php require_once('connect.php'); session_start(); if($_SESSION['idCli'] != 0){ $idclient = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } $totalPrixLeg=0; $totalPrixFruit=0; $sql01="SELECT adresseCli FROM client WHERE idClient='$idclient'"; $p01 = $co->query($sql01); while ($row = $p01->fetch_assoc() ) { $numAdresse=$row['adresseCli']; } $sql03="SELECT * FROM adresse WHERE idAdresse = '$numAdresse '"; $p03 = $co->query($sql03); while ($row3 = $p03->fetch_assoc() ) { $CP=$row3['codePostal']; $ville=$row3['ville']; $adresse = $row3['adresse']; } $sql="SELECT idPanierClient FROM panierclient WHERE clientPanier='$idclient'"; $p1 = $co->query($sql); $req="SELECT * FROM lignepanierleg WHERE clientLigneLegP = '$idclient'"; $rep= $co->query($req); $value = $rep->num_rows; $sql00="SELECT * FROM lignepanierfruit WHERE clientLigneP ='$idclient'"; $p00 = $co->query($sql00); $value2= $p00->num_rows; $test = $value + $value2; if ($test ==0) { echo "<img src='../PHOTOS/panierCoeur.jpg' height=200 width=200 alt>"; echo "<p>Votre panier est vide </p>"; } else { echo "<table > <tr> <th>Désignation</th> <th>Prix</th> <th>Détail de vente</th> <th>Quantité</th> <th>Total</th> </tr>"; while ($row = $p1->fetch_assoc() ) { $idpanier = $row['idPanierClient']; } $sql2="SELECT * FROM lignepanierfruit WHERE panierLigneP='$idpanier'"; $p2 = $co->query($sql2); while ($row2 = $p2->fetch_assoc() ) { $idfruit=$row2['fruitLigneP']; $sql3="select * from fruit where idFruit=$idfruit"; $p3 = $co->query($sql3); while ($row3 = $p3->fetch_assoc() ) { echo "<tr>"; echo "<td>".$row3['nomFruit']."</td>"; echo "<td>".$row3['prixFruit']." €</td>"; echo "<td>".$row3['detailVenteFruit']."</td>"; echo "<td>".$row2['quantiteFruitP']."</td>"; $total=$row3['prixFruit']*$row2['quantiteFruitP']; $totalPrixFruit+=$total; echo "<td id=\"avantsupp\">".$total." €</td>"; echo"<td id=\"supp\"><a id=\"btnSupp\" href = 'supprimerFruit.php?id=".$idfruit."'>Supprimer</a></td>"; echo "</tr>"; } } ///////////////////////////////////////////////////////////////////////// $sql4="SELECT * FROM lignepanierleg WHERE panierLigneLegP='$idpanier'"; $p4 = $co->query($sql4); while ($row4 = $p4->fetch_assoc() ) { $idleg=$row4['legLigneP']; $sql5="select * from legume where idLegume=$idleg"; $p5 = $co->query($sql5); while ($row5 = $p5->fetch_assoc() ) { echo "<tr>"; echo "<td>".$row5['nomLeg']."</td>"; echo "<td>".$row5['prixLeg']." €</td>"; echo "<td>".$row5['detailVenteLeg']."</td>"; echo "<td>".$row4['quantiteLegP']."</td>"; $total=$row5['prixLeg']*$row4['quantiteLegP']; $totalPrixLeg+=$total; echo "<td id=\"avantsupp\" >".$total." €</td>"; echo"<td id=\"supp\" ><a id=\"btnSupp\" href = 'supprimerLeg.php?id=".$idleg."'>Supprimer</a></td>"; echo "</tr>"; } } $sousTotal=$totalPrixLeg+$totalPrixFruit; echo "<p class='recap'>Sous total du panier : ".$sousTotal." € </p>"; echo "</table>"; echo "<p class='separationCom'></p>"; echo "<p class='recap'>Adresse de livraison </p>"; echo "<form method='post' action='paimentPanier.php'>"; echo "<div class='form'>"; echo "<p class='name'>Code postal : </p> <input name =\"cp\" class='inpt' value='$CP' >" ; echo "<p class='name'>Ville :</p> <input name =\"ville\" class='inpt' id='pass' value='$ville'> "; echo "<p class='name'>Adresse :</p> <input name = \"addr\" class='inpt' value=\"".$adresse."\" id='pass' > "; echo "</div>"; echo "<input class='btn' type='submit' value='Comfirmez panier et passez au paiement' >"; echo "</form>"; } ?> </div> <div class="footer"> <div id="dispoFoot"> <div id="certif"> <p>Site réalisé par <NAME>, <NAME> et <NAME> ©</p><p id="ita">Tous droits réservés</p> </div> <div class="reseaux"> <a href="https://www.instagram.com/uberprimeur_/"><img src="../PHOTOS/insta.png" height=40 width=40 alt ></a> <a href="https://twitter.com/UPrimeur"><img src="../PHOTOS/twitter.png" height=40 width=40 alt ></a> </div> </div> </br> <a href="webmaster.php" id="webmaster">accès webmaster</a> </div> </body> </html> <file_sep>/CODE/comande.php <?php require_once('connect.php'); $id = $_GET['id']; $dateCom = date("d-m-Y"); $dateliv = date("d-m-Y"); $dateliv = date('d-m-Y', strtotime($dateliv . ' +5 day')); echo $dateliv; $idliv; $sql1="INSERT INTO livraison (idLivraison, adresseChoisie, dateLivraison, groupeMailLiv, typeLiv) VALUES (null, '1', $dateliv,'1', '1')"; $co->query($sql1); $sql2="SELECT * FROM livraison "; $p2=$co->query($sql2); $NombreLigne= mysqli_num_rows($p2); $compteur=0; while ($row = $p2->fetch_assoc() ) { $compteur++; if($compteur==$NombreLigne) { $idliv = $row['idLivraison']; } } $sql3="INSERT INTO commande (idCommande, clientCom, dateCom, livraisonCom) VALUES (null, '$id', '$dateCom', '$idliv')"; $co->query($sql3); $sql4="SELECT * FROM commande "; $p3=$co->query($sql4); $NombreLigneCom= mysqli_num_rows($p3); $compteur2=0; while ($row2 = $p3->fetch_assoc() ) { $compteur2++; if($compteur2==$NombreLigneCom) { $idcom= $row2['idCommande']; } } $sql5="select clientPanier from panierclient where idPanierClient=$id"; $p5 = $co->query($sql5); while ($row3 = $p5->fetch_assoc() ) { $idpanier=$row3['clientPanier']; } $sql6="select * from lignepanierfruit where panierLigneP=$idpanier"; $p6 = $co->query($sql6); while ($row3 = $p6->fetch_assoc() ) { $idfruit=$row3['fruitLigneP']; $quantitéfruit=$row3['quantiteFruitP']; $sql7="INSERT INTO lignefruitcommande (fruitLigne, clientLigneFruitCom, commandeLigneFruitCom, quantiteFruitCom) VALUES ('$idfruit', '$id', '$idcom', '$quantitéfruit')"; $co->query($sql7); } $sql8="select * from lignepanierleg where panierLigneLegP=$idpanier"; $p7 = $co->query($sql8); while ($row4 = $p7->fetch_assoc() ) { $idleg=$row4['legLigneP']; $quantitéleg=$row4['quantiteLegP']; $sql9="INSERT INTO lignelegcommande (legumeLigne, clientLigneLegCom, commandeLegFruitCom, quantiteLegCom) VALUES ('$idleg', '$id', '$idcom', '$quantitéleg')"; $co->query($sql9); } header('Location: compte.php'); ?><file_sep>/CODE/webmastermain.php <?php require_once("connect.php"); session_start(); if(!$_SESSION['auto']){ header("Location: index.html"); exit; } ?> <!DOCTYPE html> <html lang="fr"> <meta charset="UTF-8"> <link rel="stylesheet" href="css/webmaster.css" /> <title>UberPrimeur</title> <div class="header"> <div class="logo"> <a href="accueil.php"><img id="logoNav" src="../LOGOS/logo5.PNG" width=400 height=62 alt></a> </div> <div class="menuNav"> <a href="a_propos.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/apropos.png" height=18 width=18 alt>À propos</a> <a href="nospaniers.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/nospaniers.png" height=18 width=18 alt>Nos paniers</a> <a href="fruits.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/fruit.jpg" height=18 width=18 alt>Fruits</a> <a href="legumes.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/legume.png" height=18 width=18 alt>Légumes</a> <a href="panier.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/panier.png" height=18 width=18 alt>Panier</a> <a href="compte.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/compte.jpg" height=18 width=18 alt>Compte</a> </div> </div> <!--Début du body--> <body style="text-align:center"> <h1> Page webmaster</h1> <div class="tout"> <div class="form"> <h2>Ajout de stock de fruits et légumes </h2> <form method="post" action="stock.php"> <p> Type de marchandise</p> <select name="type" required > <option value="">--Choisissez un type--</option> <option value="fru">Fruit</option> <option value="leg">Légume</option> </select></br> <p>Nom de la marchandise</p> <input type="texte" name="nomMarch" required></br> <p>Ajout de stock</p> <input type="number" name="stock" value="0" required></br> <input id="btnVal" type="submit" value="Valider"> </form> </div> <div class="form"> <h2>Changement de prix d'une marchandise </h2> <form method="post" action="prix.php"> <p> Type de marchandise</p> <select name="type" required> <option value="">--Choisissez un type--</option> <option value="fru">Fruit</option> <option value="leg">Légume</option> </select></br> <p>Nom de la marchandise</p> <input type="texte" name="nomMarch" required></br> <p>Nouveau prix</p> <input type="number" name="prix" value="0" required></br> <input id="btnVal" type="submit" value="Valider"> </form> </div> <div class="form"> <h2>Suppression d'une marchandise </h2> <form method="post" action="retrait.php"> <p> Type de marchandise</p> <select name="type" required> <option value="">--Choisissez un type--</option> <option value="fru">Fruit</option> <option value="leg">Légume</option> </select></br> <p>Nom de la marchandise</p> <input type="texte" name="nomMarch" required></br> <input id="btnVal" type="submit" value="Valider"> </form> </div> <div class="form"> <h2>Ajout de nouveaux fruits et légumes </h2> <form method="post" action="ajoutMarch.php"> <p> Type de marchandise</p> <select name="type" required> <option value="">--Choisissez un type--</option> <option value="fru">Fruit</option> <option value="leg">Légume</option> </select></br> <p>Nom de la marchandise</p> <input type="texte" name="nomMarch" required></br> <p>Nom de la photo</p> <input type="texte" name="nomPh" required></br> <p>Prix à l'unité</p> <input type="number" name="prix" value="0" required></br> <p>Détail de vente</p> <input type="texte" name="detail" required></br> <p>Stock initial</p> <input type="number" name="stockI" value="0" required></br> <p>Famille</p> <input type="texte" name="famille" required></br> <p>Saison</p> <input type="texte" name="saison" required></br> <input id="btnVal" type="submit" value="Valider"> </form> </div> <!-- PARTIE THOMAS --> <div class ="form"> <h2>Ajout de la recette hebdomadaire</h2> <form method ="post" action="ajoutRecetteHebdo.php"> <p>Nom de la recette</p> <input type="text" name="nomRecette" require></br> <p>Nom de la photo</p> <input type="text" name="nomPhre"></br> <p>Temps de préparation</p> <input type="time" name="temps"></br> <p>Ingédients :</p> <table> <tr> <th class ="col">Quantité :</th> <th class ="col">Mesure :</th> <th>Nom ingrédient :</th> </tr> <tr> <td><input type="text" name="qt1" placeholder="100"></td> <td><input type="text" name="m1" placeholder="g"></td> <td><input type="text" name="ing1" placeholder="chocolat" ></td> </tr> <tr> <td><input type="text" name="qt2"></td> <td><input type="text" name="m2"></td> <td><input type="text" name="ing2"></td> </tr> <tr> <td><input type="text" name="qt3"></td> <td><input type="text" name="m3"></td> <td><input type="text" name="ing3"></td> </tr> <tr> <td><input type="text" name="qt4"></td> <td><input type="text" name="m4"></td> <td><input type="text" name="ing4"></td> </tr> <tr> <td><input type="text" name="qt5"></td> <td><input type="text" name="m5"></td> <td><input type="text" name="ing5"></td> </tr> <tr> <td><input type="text" name="qt6"></td> <td><input type="text" name="m6"></td> <td><input type="text" name="ing6"></td> </tr> <tr> <td><input type="text" name="qt7"></td> <td><input type="text" name="m7"></td> <td><input type="text" name="ing7"></td> </tr> <tr> <td><input type="text" name="qt8"></td> <td><input type="text" name="m8"></td> <td><input type="text" name="ing8"></td> </tr> </table> <table id="etp"> <p>Etapes :</p> <tr> <td class="long"><input type="text" name="etape1"></td> </tr> <tr> <td class="long"><input type="text" name="etape2"></td> </tr> <tr> <td class="long"><input type="text" name="etape3"></td> </tr> <tr> <td class="long"><input type="text" name="etape4"></td> </tr> <tr> <td class="long"><input type="text" name="etape5"></td> </tr> <tr> <td class="long"><input type="text" name="etape6"></td> </tr> <tr> <td class="long"><input type="text" name="etape7"></td> </tr> <tr> <td class="long"><input type="text" name="etape8"></td> </tr> <tr> <td class="long"><input type="text" name="etape9"></td> </tr> <tr> <td class="long"><input type="text" name="etape10"></td> </tr> </table> <input id="btnVal" type="submit" value="Valider"> </form> </div> </div> <!-- FIN PARTIE THOMAS --> <h3> Liste des clients ayant accepté l'envoi de mails de notification :</h3> <?php require_once("connect.php"); $req = "SELECT nomClient, prenomClient FROM client WHERE envoiMail = true"; $rep = $co->query($req); while($row = $rep->fetch_assoc()){ echo "<p> - ".$row["nomClient"]." ".$row["prenomClient"]."</p>"; } ?> </body> <div class="footer"> <div id="dispoFoot"> <div id="certif"> <p>Site réalisé par <NAME>, <NAME> et <NAME> ©</p><p id="ita">Tous droits réservés</p> </div> <div class="reseaux"> <a href="https://www.instagram.com/uberprimeur_/"><img src="../PHOTOS/insta.png" height=40 width=40 alt ></a> <a href="https://twitter.com/UPrimeur"><img src="../PHOTOS/twitter.png" height=40 width=40 alt ></a> </div> </div> </br> <a href="webmaster.php" id="webmaster">accès webmaster</a> </div> </html><file_sep>/CODE/ajoutRecetteHebdo.php <?php require_once("connect.php"); $nomR = $_POST['nomRecette']; $nomP = $_POST['nomPhre']; $temps = $_POST['temps']; $quantite = array($_POST['qt1'],$_POST['qt2'],$_POST['qt3'],$_POST['qt4'],$_POST['qt5'], $_POST['qt6'],$_POST['qt7'],$_POST['qt8']); $mesure = array($_POST['m1'],$_POST['m2'],$_POST['m3'],$_POST['m4'],$_POST['m5'], $_POST['m6'],$_POST['m7'],$_POST['m8']); $ing = array($_POST['ing1'],$_POST['ing2'],$_POST['ing3'],$_POST['ing4'],$_POST['ing5'], $_POST['ing6'],$_POST['ing7'],$_POST['ing8']); $etape = array($_POST['etape1'],$_POST['etape2'],$_POST['etape3'],$_POST['etape4'], $_POST['etape5'],$_POST['etape6'],$_POST['etape7'],$_POST['etape8'],$_POST['etape9'], $_POST['etape10']); $ok = false; $a = 0; $y = 0; $getid = "SELECT idRecette FROM recette WHERE nomRecette = $nomR"; $rep2 = mysqli_query($co, $getid); while (1){ if ($nomR != "" && $temps != "" && $nomP != ""){ $strNom = str_replace("'"," ",$nomR); $strNomPh = str_replace("'"," ",$nomP); $req = "UPDATE recettehebdo SET nomRecette = '$strNom ' ,tempsPrep = '$temps', nomPhotoRecette = '$strNomPh' WHERE 1"; $rep = mysqli_query($co, $req); } else{ break; } for($i = 0; $i < sizeof($ing); $i++){ if($ing[0] == null || $quantite[0] == null){ break; } if($ing[$i] == null && $quantite[$i] == null){ $ok = true; break; } else{ if ($ing[$i] == null){ break; } elseif($quantite[$i] == null){ break; } } } if($etape[0] == null){ $ok = false; } break; } if($ok == true){ $delete = "DELETE FROM ingredient WHERE recetteIngredient = 1"; $del = mysqli_query($co, $delete); $delete1 = "DELETE FROM etape WHERE recetteEtape = 1"; $del1 = mysqli_query($co, $delete1); while($ing[$a]!=null) { $toInsertIng = str_replace("'"," ",$ing[$a]); $req3 = "INSERT INTO ingredient VALUES (null, 1, '$quantite[$a]','$mesure[$a]', '$toInsertIng')"; $rep3 = mysqli_query($co, $req3); $a++; } while($etape[$y]!= null){ $toInsert = str_replace("'"," ",$etape[$y]); $req4 = "INSERT INTO etape VALUES (null, 1, '$toInsert')"; $rep4 = mysqli_query($co, $req4); echo " ligne ajoutée : ".$etape[$y]; $y++; } } header("Location: webmastermain.php"); exit; ?><file_sep>/CODE/nospaniers.php <?php session_start(); if($_SESSION['idCli'] != 0){ $idclient = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } ?> <!DOCTYPE html> <html lang="fr"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/stylenosPanier.css" /> <title>UberPrimeur</title> <!--Début du body--> <body> <div class="header"> <div class="logo"> <a href="accueil.php"><img id="logoNav" src="../LOGOS/logo5.PNG" width=400 height=62 alt></a> </div> <div class="menuNav"> <a href="a_propos.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/apropos.png" height=18 width=18 alt>À propos</a> <a href="nospaniers.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/nospaniers.png" height=18 width=18 alt>Nos paniers</a> <a href="fruits.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/fruit.jpg" height=18 width=18 alt>Fruits</a> <a href="legumes.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/legume.png" height=18 width=18 alt>Légumes</a> <a href="panier.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/panier.png" height=18 width=18 alt>Panier</a> <a href="compte.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/compte.jpg" height=18 width=18 alt>Compte</a> </div> </div> <div class="encadre"> <p class="gTitre TA"> <NAME></p> <p class="TA txt" style="font-size:18px;">Nous vous proposons des paniers au gré des saisons qui vous seront livrés le samedi chaque semaine. </p> <p class="TA" style="font-size:18px;">La composition du panier est secrète ! Vous la découvrirez le jour de la livraison, UberPrimeur vous garantie une satisfaction totale. </p> <p class="separationCom"></p> <form method="post" action="paiment.php"> <div class="photoPanier"> <img src="../PHOTOS/petitpanier.jpeg" alt="" /> <p style="font-size:17px;">Ce panier convient à 2/3 personnes</p> <input type="radio" id="" name="Choix" value="petit" > </div> <div class="photoPanier"> <img src="../PHOTOS/moyenpanier.jfif" alt="" /> <p style="font-size:17px;">Ce panier convient à 4/5 personnes</p> <input type="radio" id="" name="Choix" value="moyen" > </div> <div class="photoPanier"> <img src="../PHOTOS/photoPanier.jpg" alt="" /> <p style="font-size:17px;">Ce panier convient à 6/7 personnes</p> <input type="radio" id="" name="Choix" value="grand" > </div> <div class="entoure"> <input class="btnPanier" type="submit" value="Souscrire à l'abonnement" style="font-size:17px;"> </div> </form> </div> <div class="footer"> <div id="dispoFoot"> <div id="certif"> <p>Site réalisé par <NAME>, <NAME> et <NAME> ©</p><p id="ita">Tous droits réservés</p> </div> <div class="reseaux"> <a href="https://www.instagram.com/uberprimeur_/"><img src="../PHOTOS/insta.png" height=40 width=40 alt ></a> <a href="https://twitter.com/UPrimeur"><img src="../PHOTOS/twitter.png" height=40 width=40 alt ></a> </div> </div> </br> <a href="webmaster.php" id="webmaster">accès webmaster</a> </div> </body> </html><file_sep>/CODE/accueil.php <?php require_once('connect.php'); session_start(); if($_SESSION['idCli'] != 0){ $idclient = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } ?> <!DOCTYPE html> <html lang="fr"> <meta charset="UTF-8"> <link rel="stylesheet" href="style.css" /> <title>UberPrimeur</title> <!--Début du body--> <body> <!--Menu de nav--> <div class="header"> <div class="logo"> <a href="accueil.php"><img id="logoNav" src="../LOGOS/logo5.PNG" width=400 height=62 alt></a> </div> <div class="menuNav"> <a href="a_propos.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/apropos.png" height=18 width=18 alt>À propos</a> <a href="nospaniers.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/nospaniers.png" height=18 width=18 alt>Nos paniers</a> <a href="fruits.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/fruit.jpg" height=18 width=18 alt>Fruits</a> <a href="legumes.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/legume.png" height=18 width=18 alt>Légumes</a> <a href="panier.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/panier.png" height=18 width=18 alt>Panier</a> <a href="compte.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/compte.jpg" height=18 width=18 alt>Compte</a> </div> </div> <!--Body--> <div id="logo_accueil"><img src="../PHOTOS/logoferme7.png" alt=""></div> <div id="ptt_primeur"> <p>Produits 100% français, bios et d'origine naturelle !</p> </div> <div id="recette"> <?php //Requête SQL $req_titre ="SELECT * from recettehebdo"; $rep_titre = mysqli_query($co, $req_titre); //Récupération de la réponse + affichage while($row_titre = $rep_titre -> fetch_assoc()){ echo "<h2>".$row_titre['nomRecette']. "</h2>"; echo "<h3> Temps de préparation : ".$row_titre['tempsPrep']."</h3>"; } ?> <div id="ing"> <h3>Ingrédients</h3> <ul> <?php //Requête SQL $req_ing = "SELECT * FROM ingredient"; $rep_ing = mysqli_query($co, $req_ing); //Récupération de la réponse + affichage while ($row_ing = $rep_ing -> fetch_assoc()) { echo "<li> <p>".$row_ing['quantite']." ".$row_ing['mesure']." ".$row_ing['nomIngredient']."</p></li>"; } ?> </ul> </div> <div id="prep"> <h3>Préparation</h3> <ol> <?php //Requête SQL $req_prep = "SELECT * from etape"; $rep_prep = mysqli_query($co,$req_prep); //Récupération de la réponse + affichage while($row_prep = $rep_prep -> fetch_assoc()){ echo "<li><p>".$row_prep['descEtape']."</p></li>"; } ?> </ol> </div> <div id="img_rct"> <?php $req_img = "SELECT * from recettehebdo"; $rep_img = mysqli_query($co,$req_img); //Récupération de la réponse + affichage while ($row_img = $rep_img -> fetch_assoc()){ printf('<img id="image_rct" src="../PHOTOS/%s">', $row_img['nomPhotoRecette']); } ?> </div> </div> <div id="choix_page"> <div id="p_legume"> <a href="legumes.php"><img class="img_choix" src="../PHOTOS/p_leg.jpg" alt=""></a> <div class="desc_choix_p"> <a href="legumes.php"> <span>Légumes</span> </a> </div> </div> <div id="p_fruit"> <a href="fruits.php"><img class="img_choix" src="../PHOTOS/p_fruit.jpg" alt=""></a> <div class="desc_choix_p"> <a href="fruits.php"> <span>Fruits</span> </a> </div> </div> </div> <!--Footer--> <div class="footer"> <div id="dispoFoot"> <div id="certif"> <p>Site réalisé par <NAME>, <NAME> et <NAME> ©</p> <p id="ita">Tous droits réservés</p> </div> <div class="reseaux"> <a href="https://www.instagram.com/uberprimeur_/"><img src="../PHOTOS/insta.png" height=40 width=40 alt></a> <a href="https://twitter.com/UPrimeur"><img src="../PHOTOS/twitter.png" height=40 width=40 alt></a> </div> </div> </br> <a href="webmaster.php" id="webmaster">accès webmaster</a> </div> </body> </html><file_sep>/CODE/retrait.php <?php require_once("connect.php"); $type = $_POST["type"]; $nom = $_POST["nomMarch"]; if($type == "fru"){ $req = "DELETE FROM Fruit WHERE nomFruit = '$nom' "; $rep2 = $co->query($req); }else{ $req = "DELETE FROM Legume WHERE nomLeg = '$nom'"; $rep2 = $co->query($req); } header("Location: webmastermain.php"); exit();<file_sep>/CODE/desabonnement.php <?php require_once("connect.php"); session_start(); if($_SESSION['idCli'] != 0){ $idclient = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } $upd = "UPDATE client SET hebdo = \"\" WHERE idClient = $idclient "; $co->query($upd); header("Location: compte.php"); exit; ?><file_sep>/CODE/commande.php <?php require_once('connect.php'); session_start(); if($_SESSION['idCli'] != 0){ $id = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } $dateCom = date("Y-m-d"); $dateliv = date("Y-m-d"); $dateliv = date('Y-m-d', strtotime($dateliv . ' +7 day')); $idAddr = $_POST["idAddr"]; $sql1= "INSERT INTO livraison VALUES (null, $idAddr, '$dateliv' ,null, 1)"; $rep = $co->query($sql1); $idLiv = $co->insert_id; $sql3="INSERT INTO commande VALUES (null, '$id', '$dateCom', '$idLiv')"; $rep2 = $co->query($sql3); $idCom = $co->insert_id; $sql5="SELECT idPanierClient FROM panierclient WHERE clientPanier = '$id' "; $p5 = $co->query($sql5); while ($row3 = $p5->fetch_assoc() ) { $idpanier=$row3['idPanierClient']; } $sql6="SELECT * FROM lignepanierfruit WHERE panierLigneP = '$idpanier' "; $p6 = $co->query($sql6); while ($row3 = $p6->fetch_assoc() ) { $idfruit = $row3['fruitLigneP']; $quantitefruit = $row3['quantiteFruitP']; $sql7="INSERT INTO lignefruitcommande VALUES ('$idfruit', '$id', '$idCom', '$quantitefruit')"; $co->query($sql7); $prep = "SELECT quantiteFruit FROM fruit WHERE idFruit = $idfruit"; $repEx = $co->query($prep); while($rowEx = $repEx->fetch_assoc()){ $oldQu = $rowEx["quantiteFruit"]; } $newQu = $oldQu - $quantitefruit; $retraitStock = "UPDATE fruit SET quantiteFruit = $newQu WHERE idFruit = $idfruit"; $co->query($retraitStock); } $sql8="SELECT * FROM lignepanierleg WHERE panierLigneLegP = '$idpanier' "; $p7 = $co->query($sql8); while ($row4 = $p7->fetch_assoc() ) { $idleg=$row4['legLigneP']; $quantiteleg=$row4['quantiteLegP']; $sql9="INSERT INTO lignelegcommande VALUES ('$idleg', '$id', '$idCom', '$quantiteleg')"; $co->query($sql9); $prep2 = "SELECT quantiteLeg FROM legume WHERE idLegume = $idleg"; $repEx2 = $co->query($prep2); while($rowEx2 = $repEx2->fetch_assoc()){ $oldQu2 = $rowEx2["quantiteLeg"]; } $newQu2 = $oldQu2 - $quantiteleg; $retraitStock2 = "UPDATE legume SET quantiteLeg = $newQu2 WHERE idLegume = $idleg"; $co->query($retraitStock2); } $del = "DELETE FROM lignepanierfruit WHERE clientLigneP = $id"; $co->query($del); $del2 = "DELETE FROM lignepanierleg WHERE clientLigneLegP = $id"; $co->query($del2); $del3 = "DELETE FROM panierclient WHERE clientPanier = $id"; $co->query($del3); header('Location: compte.php'); exit; ?><file_sep>/CODE/webmaster.php <?php session_start(); if($_SESSION['idCli'] != 0){ $idclient = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } ?> <!DOCTYPE html> <html lang="fr"> <meta charset="UTF-8"> <link rel="stylesheet" href="css/webmaster.css" /> <title>UberPrimeur</title> <div class="header"> <div class="logo"> <a href="accueil.php"><img id="logoNav" src="../LOGOS/logo5.PNG" width=400 height=62 alt></a> </div> <div class="menuNav"> <a href="a_propos.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/apropos.png" height=18 width=18 alt>À propos</a> <a href="nospaniers.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/nospaniers.png" height=18 width=18 alt>Nos paniers</a> <a href="fruits.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/fruit.jpg" height=18 width=18 alt>Fruits</a> <a href="legumes.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/legume.png" height=18 width=18 alt>Légumes</a> <a href="panier.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/panier.png" height=18 width=18 alt>Panier</a> <a href="compte.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/compte.jpg" height=18 width=18 alt>Compte</a> </div> </div> <!--Début du body--> <body style="text-align:center"> <form method="POST" action="coWeb.php"> <h2>Accès webmaster</h2> <p>Entrez le mot de passe webmaster </p> <div> <label id="mdp" for="pass">Mot de passe </label> <input type="<PASSWORD>" id="pass" name="password" required> <input id="btnCo" type="submit" value="Connexion"> </div> </form> <p>La page à laquelle vous tenter d'accéder est privée.</p> <p>Toute tentative non-fructueuse vous ramènera à la page d'accueil.</p> <img src="../PHOTOS/cad.png" alt> </body> <div class="footer"> <div id="dispoFoot"> <div id="certif"> <p>Site réalisé par <NAME>, <NAME> et <NAME> ©</p><p id="ita">Tous droits réservés</p> </div> <div class="reseaux"> <a href="https://www.instagram.com/uberprimeur_/"><img src="../PHOTOS/insta.png" height=40 width=40 alt ></a> <a href="https://twitter.com/UPrimeur"><img src="../PHOTOS/twitter.png" height=40 width=40 alt ></a> </div> </div> </br> <a href="webmaster.php" id="webmaster">accès webmaster</a> </div> </html><file_sep>/CODE/ajoutMarch.php <?php require_once("connect.php"); $type = $_POST["type"]; $nom = $_POST["nomMarch"]; $nomPh = $_POST["nomPh"]; $prix = $_POST["prix"]; $detail = $_POST["detail"]; $stockI = $_POST["stockI"]; $nomfamille = $_POST["famille"]; $nomsaison = $_POST["saison"]; if($type == "fru"){ $getid = "SELECT idFamilleFruit FROM famillefruit WHERE nomFamilleFruit = '$nomfamille'"; $rep = $co->query($getid); while($row = $rep->fetch_assoc()){ $famille = $row["idFamilleFruit"]; } $getid2 = "SELECT idSaison FROM saison WHERE nomSaison = '$nomsaison'"; $rep2 = $co->query($getid2); while($row2 = $rep2->fetch_assoc()){ $saison = $row2["idSaison"]; } $req = "INSERT INTO Fruit VALUES (null, '$nom', $prix, '$detail', $stockI , '$nomPh', null, '$saison', '$famille')"; $insert = $co->query($req); }else{ $getid = "SELECT idFamilleLegume FROM famillelegume WHERE nomFamilleLeg = '$nomfamille'"; $rep = $co->query($getid); while($row = $rep->fetch_assoc()){ $famille = $row["idFamilleLegume"]; } $getid2 = "SELECT idSaison FROM saison WHERE nomSaison = '$nomsaison'"; $rep2 = $co->query($getid2); while($row2 = $rep2->fetch_assoc()){ $saison = $row2["idSaison"]; } $req = "INSERT INTO Legume VALUES (null, '$nom', $prix, $stockI, '$detail', '$nomPh', null, '$saison', '$famille')"; $insert = $co->query($req); } header("Location: webmastermain.php"); exit; ?><file_sep>/CODE/paiement.php <?php require_once('connect.php'); session_start(); if($_SESSION['idCli'] != 0){ $idclient = $_SESSION['idCli']; $choix = $_SESSION['choixP']; }else{ header("Location: index.html"); exit; } $sql="UPDATE client SET hebdo = '$choix' WHERE idClient='$idclient'"; $modif = $co->query($sql); header("Location: compte.php"); exit; ?><file_sep>/CODE/supprimerFruit.php <?php require_once('connect.php'); session_start(); if($_SESSION['idCli'] != 0){ $idclient = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } $id = $_GET['id']; $sql = "DELETE FROM lignepanierfruit WHERE fruitLigneP='$id' AND clientLigneP = '$idclient' "; $co->query($sql); header('Location: panier.php'); exit; ?><file_sep>/CODE/suppCom.php <?php require_once("connect.php"); $idComm = $_GET["idc"]; $delLigneF = "DELETE FROM lignefruitcommande WHERE commandeLigneFruitCom = $idComm "; $co->query($delLigneF); $delLigneL = "DELETE FROM lignelegcommande WHERE commandeLegFruitCom = $idComm "; $co->query($delLigneL); $getIdLiv = "SELECT livraisonCom FROM commande WHERE idCommande = $idComm"; $rep = $co->query($getIdLiv); while($row = $rep->fetch_assoc()){ $idLiv = $row["livraisonCom"]; } $delCommande = "DELETE FROM commande WHERE idCommande = $idComm "; $co->query($delCommande); $delLiv = "DELETE FROM livraison WHERE idLivraison = $idLiv"; $co->query($delLiv); header("Location: compte.php"); exit; ?><file_sep>/CODE/connexion.php <?php require_once("connect.php"); $mail = strip_tags($_POST['username']); $mail = mysqli_real_escape_string($co ,$mail); // Récupération du mdp hashé avec le grain de sel $salt = "*$=²ù€;.?,È{qü=BuÐ8ƒµ´à¤"; $mdp = md5($_POST["password"].$salt); $getId = "SELECT idMail FROM mail WHERE mail ='$mail'"; $rep = $co->query($getId); while($row = $rep->fetch_assoc()){ $idmail = $row["idMail"]; } //Préparation de la vérif mot de passe $connexion = "SELECT mdpClient, idClient FROM client WHERE mailCli = '$idmail'"; $testco = $co->query($connexion); $numrows = $co->num_rows; // Si mail pas trouvé if($numrows === 0){ header("Location: index.html"); exit; } // Récupération du mdp while($row = $testco->fetch_assoc()){ $compMdp = $row["mdpClient"]; $idcli = $row["idClient"]; } // Si les mdp correspondent if($compMdp == $mdp){ session_start(); $_SESSION['idCli'] = $idcli; header("Location: accueil.php"); exit; } header("Location: index.html"); exit; ?><file_sep>/CODE/compte.php <?php require_once('connect.php'); session_start(); if($_SESSION['idCli'] != 0){ $idclient = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } $sql0="SELECT * FROM client WHERE idClient='$idclient'"; if(!empty($_GET['modif'])) { $modifmdp = $_GET['modif']; } $p01 = $co->query($sql0); while ($row0 = $p01->fetch_assoc() ) { $nom=$row0['nomClient']; $prenom=$row0['prenomClient']; $mdp=$row0['mdpClient']; $abo=$row0['hebdo']; $telephone=$row0['telClient']; $numAdresse=$row0['adresseCli']; $groupemail=$row0['mailCli']; } $sql02="select * from mail where idMail=$groupemail"; $p02 = $co->query($sql02); while ($row02 = $p02->fetch_assoc() ) { $mail=$row02['mail']; } $sql03="select * from adresse where idAdresse=$numAdresse"; $p03 = $co->query($sql03); while ($row03 = $p03->fetch_assoc() ) { $CP=$row03['codePostal']; $ville=$row03['ville']; $adresse=$row03['adresse']; } ?> <!DOCTYPE html> <html lang="fr"> <meta charset="UTF-8"> <link rel="stylesheet" href="css/styleCompte.css" /> <title>UberPrimeur</title> <!--Début du body--> <body> <div class="header"> <div class="logo"> <a href="accueil.php"><img id="logoNav" src="../LOGOS/logo5.PNG" width=400 height=62 alt></a> </div> <div class="menuNav"> <a href="a_propos.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/apropos.png" height=18 width=18 alt>À propos</a> <a href="nospaniers.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/nospaniers.png" height=18 width=18 alt>Nos paniers</a> <a href="fruits.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/fruit.jpg" height=18 width=18 alt>Fruits</a> <a href="legumes.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/legume.png" height=18 width=18 alt>Légumes</a> <a href="panier.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/panier.png" height=18 width=18 alt>Panier</a> <a href="compte.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/compte.jpg" height=18 width=18 alt>Compte</a> </div> </div> <div class="encadre"> <p class="gTitre TA"> Informations personnelles</p> <div class="contenue"> <p class="name2" ><b>Nom : </b><?php echo $nom; ?> </p> <p class="name2"><b>Prénom : </b><?php echo $prenom; ?> </p> <p class="separationCom"></p> <form method="post" action="mdp.php"> <div class="form"> <p class="name">Mot de passe actuel : </p> <input class="inpt" type = "password" id="" name="pass" value="" > <p class="name">Nouveau mot de passe :</p> <input class="inpt" type ="password" id="pass" name="pass1"> <p class="name">Confirmer nouveau mot de passe :</p> <input class="inpt" type ="password" id="pass" name="pass2"> </div> <input class="btn" type="submit" value="Valider modifications"> </form> <?php if(!empty($_GET['modif'])) { if ($_GET['modif']==1) { echo "<p>Ancien mot de passe incorrect.</p>"; } if ($_GET['modif']==2) { echo "<p>Les deux mots de passes sont différents.</p>"; } if ($_GET['modif']==3) { echo "<p>Mot de passe modifié. </p>"; } } ?> <p class="separationCom"></p> <form method="post" action="mail.php"> <div class="form"> <p class="name">Adresse mail actuelle :</p> <input class="inpt" type = "text" id="mail" name="" value="<?php echo $mail; ?>" > <p class="name">Nouvelle adresse mail :</p> <input class="inpt" type = "text" id="mail" name="mail" required> </div> <input class="btn" type="submit" value="Valider modifications"> </form> </div> <p class="gTitre TA"> Abonnement</p> <?php if(!empty($_GET['paye'])) { echo "<p class='abonnement'>Le paiement a bien été effectué</p>"; } ?> <?php if (!empty($abo)) { echo "<p class='abonnement' >Vous avez souscrit à un abonnement pour un panier hebdomadaire $abo</p> <a class='btn_abo' type='button' href='desabonnement.php'>Se désabonner</a>"; } else echo "<p class='TA text_abo'> Vous n'avez souscrit à aucun abonnement actuellement</p> <a class='btn_abo' type='button' href='nospaniers.php'>Souscrire à un abonnement</a>"; ?> <p class="gTitre TA"> Adresse</p> <div class="contenue"> <p class="txtAdresse" ><b>Code postal : </b><?php echo $CP; ?> </p> <p class="txtAdresse"><b>Ville : </b><?php echo $ville; ?></p> <p class="txtAdresse"><b>Adresse : </b><?php echo $adresse; ?></p> </div> <p class="gTitre TA"> Historique des commandes <label id="tet">( 3 plus récentes )<label></p> <?php $totalPrixLeg=0; $totalPrixFruit=0; $sql="SELECT idCommande FROM commande WHERE clientCom='$idclient'"; $p1 = $co->query($sql); $NBcommande= mysqli_num_rows($p1); $compteur=1; if ($NBcommande<1) { echo "<p class='tb'> Vous n'avez pas encore commander </p>"; } while ($row = $p1->fetch_assoc() ) { if($compteur<$NBcommande-2) { $compteur++; } else { $idcommande = $row['idCommande']; echo "<p class=' TA'>Numero de commande : ".$idcommande."</p>"; echo " <table > <tr> <th>Désignation</th> <th>Prix</th> <th>Details</th> <th>Quantité</th> <th>Total</th> </tr> "; $sql2="SELECT * FROM lignefruitcommande WHERE commandeLigneFruitCom='$idcommande'"; $p2 = $co->query($sql2); $NBligneFruit= mysqli_num_rows($p2); if ($NBligneFruit>0) { while ($row2 = $p2->fetch_assoc() ) { $idfruit=$row2['fruitLigne']; $sql3="select * from fruit where idFruit=$idfruit"; $p3 = $co->query($sql3); while ($row3 = $p3->fetch_assoc() ) { echo "<tr>"; echo "<td>".$row3['nomFruit']."</td>"; echo "<td>".$row3['prixFruit']." €</td>"; echo "<td>".$row3['detailVenteFruit']."</td>"; echo "<td>".$row2['quantiteFruitCom']."</td>"; $total=$row3['prixFruit']*$row2['quantiteFruitCom']; $totalPrixFruit+=$total; echo "<td>".$total." €</td>"; echo "</tr>"; } } } ///////////////////////////////////////////////////////////////////////// $sql4="SELECT * FROM lignelegcommande WHERE commandeLegFruitCom='$idcommande'"; $p4 = $co->query($sql4); $NBligneLeg= mysqli_num_rows($p4); if ($NBligneLeg>0) { while ($row4 = $p4->fetch_assoc() ) { $idleg=$row4['legumeLigne']; $sql5="select * from legume where idLegume=$idleg"; $p5 = $co->query($sql5); while ($row5 = $p5->fetch_assoc() ) { echo "<tr>"; echo "<td>".$row5['nomLeg']."</td>"; echo "<td>".$row5['prixLeg']." €</td>"; echo "<td>".$row5['detailVenteLeg']."</td>"; echo "<td>".$row4['quantiteLegCom']."</td>"; $total=$row5['prixLeg']*$row4['quantiteLegCom']; $totalPrixLeg+=$total; echo "<td>".$total." €</td>"; echo "</tr>"; } } } echo "</table>"; $sousTotal=$totalPrixLeg+$totalPrixFruit; echo "<p class='TA'>Sous total de la commande : ".$sousTotal." € </p>"; echo "<a class='btn_abo3' type='button' href='suppCom.php?idc=$idcommande'>Annuler la commande</a>"; $sousTotal=0; $totalPrixLeg=0; $totalPrixFruit=0; echo "<p class='separationCom'></p>"; } } ?> <a class="btn_abo2" href="deconnexion.php" type="button"><b>Se déconnecter</b></a> </div> <div class="footer"> <div id="dispoFoot"> <div id="certif"> <p>Site réalisé par <NAME>, <NAME> et <NAME> ©</p><p id="ita">Tous droits réservés</p> </div> <div class="reseaux"> <a href="https://www.instagram.com/uberprimeur_/"><img src="../PHOTOS/insta.png" height=40 width=40 alt ></a> <a href="https://twitter.com/UPrimeur"><img src="../PHOTOS/twitter.png" height=40 width=40 alt ></a> </div> </div> </br> <a href="webmaster.php" id="webmaster">accès webmaster</a> </div> </body> </html><file_sep>/CODE/a_propos.php <?php session_start(); if($_SESSION['idCli'] != 0){ $idclient = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } ?> <!DOCTYPE html> <html lang="fr"> <meta charset="UTF-8"> <link rel="stylesheet" href="css/style_a_propos.css" /> <title>UberPrimeur</title> <!--Début du body--> <body> <!--Menu de nav--> <div class="header"> <div class="logo"> <a href="accueil.php"><img id="logoNav" src="../LOGOS/logo5.PNG" width=400 height=62 alt></a> </div> <div class="menuNav"> <a href="a_propos.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/apropos.png" height=18 width=18 alt>À propos</a> <a href="nospaniers.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/nospaniers.png" height=18 width=18 alt>Nos paniers</a> <a href="fruits.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/fruit.jpg" height=18 width=18 alt>Fruits</a> <a href="legumes.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/legume.png" height=18 width=18 alt>Légumes</a> <a href="panier.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/panier.png" height=18 width=18 alt>Panier</a> <a href="compte.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/compte.jpg" height=18 width=18 alt>Compte</a> </div> </div> <!--Body--> <div id="livraison_explication"> <h1 id="h1_liv">Notre Livraison</h1> <p id="p1_explication_liv"> Il existe deux types de livraison différente. Pour la première il s'agit de la livraison à domicile. Lorsque la prise en compte de la commande aura été confirmée par e-mail au client, la livraison interviendra dans les 24 heures sauf le dimanche. </p> <p id ="p2_explication_liv">Le client s’engage à être présent à l’adresse de livraison durant cette tranche horaire. En cas d’absence du client le transporteur se réserve le droit de déposer la marchandise devant la porte sans que celle-ci ne soit réceptionné par le client directement. UberPrimeur ne pourra être tenue pour responsable si la marchandise était amenée à disparaitre entre le moment de la dépose de la marchandise et la réception de celle-ci par le client. </p> <p id ="p3_explication_liv">Le deuxième type de livraison est lorsque qu'une commande groupée est passée.</p> <p id ="p4_explication_liv">Un mail sera envoyé à chacun des clients participants à la commande groupée. Dans ce mail se trouvera le créneau horaire ainsi que l'emplacement du livreur. Afin que chaque personne aille chercher sa partie de la commande. </p> <div class="separateur1"></div> <button id="btn_cgv" type="button" onclick="toggle_text('span_txt2');"><h1 id="titre_cgv">Conditions générales de vente</h1></button> <span id="span_txt2" > <div id ="details_cgv"> <p id="p_cgv_1">ARTICLE I : ACCEPTATION DES CONDITIONS GENERALES DE VENTE <br> Ces Conditions Générales de Vente peuvent être consultées par le Client à tout moment, simplement en cliquant sur le lien hypertexte. "CGV" accessible depuis la page « à propos ». Le fait de se connecter sur le site de UBERPRIMEUR.FR implique la connaissance des présentes conditions générales dans leur intégralité. Ces conditions générales sont totalement applicables à toutes commandes passées sur le site de UBERPRIMEUR.FR. Le fait pour un utilisateur de réaliser un bon de commande et de confirmer celui-ci vaut acceptation pleine et entière des présentes conditions générales, lesquelles seront seules applicables au contrat ainsi conclu. Toute commande sera régie par ces conditions générales, à l'exclusion de toute autre. UBERPRIMEUR.FR se réserve la possibilité d'adapter ou de modifier à tout moment les présentes Conditions Générales de Vente. En cas de modification, il sera appliqué à chaque commande les Conditions Générales de Vente en vigueur au jour de la commande. Il appartient en conséquence au Client de se référer à la dernière version des Conditions Générales de Vente disponible en permanence sur le site.</p> <p id="p_cgv_2"> ARTICLE II : CONCLUSION DE LA VENTE <br> Le Client passe commande auprès de UBERPRIMEUR.FR en remplissant un panier sur le Site pour un montant minimum de 60 € TTC pour bénéficier de la livraison gratuite. Après avoir validé son panier, le Client doit s'identifier puis transmettre et payer son panier. <br> VALIDATION DE LA COMMANDE : Le Client ayant choisi les produits qu'il souhaite acheter, valide son panier aux vues du récapitulatif affiché à l'écran et recevra un e-mail de confirmation. Le récapitulatif indique notamment : • le libellé des Produits sélectionnés, leur référence et leur prix unitaire • les frais de transport • le prix total à payer par le Client. Aucun droit de rétractation sur les produits périssables avec ou sans DLC ne sera possible une fois la commande validée. <br> IDENTIFICATION DU CLIENT : Après avoir validé sa commande, le Client doit s'identifier. A cette fin, il doit remplir sur le Site un formulaire mis à sa disposition. Il indiquera notamment ses nom et prénom, son adresse e-mail, son adresse postale (et l'adresse de livraison si elle est différente), son numéro de téléphone (et le numéro de téléphone du destinataire s’il est différent). UBERPRIMEUR.FR se réserve le droit de vérifier l'exactitude de toute information saisie par le Client, et notamment ses identités et adresse, avant d'expédier les produits commandés. Les informations énoncées par le Client engagent celui-ci : en cas d'erreur dans le libellé des coordonnées du destinataire, le Site ne saurait être tenu responsable de l'impossibilité dans laquelle il pourrait être de livrer les produits commandés. <br> PAIEMENT : Le Client valide définitivement sa commande en saisissant son numéro de carte bancaire et la date d'expiration de celle-ci. Les paiements par carte bancaire sont sécurisés par le système de paiement en ligne aux normes SSL. br CONFIRMATION : La commande validée par le Client ne sera considérée effective par le Site que lorsque les centres de paiement bancaire concernés auront donné leur accord. Après validation du paiement, la commande est réputée acceptée par UBERPRIMEUR SAS. En cas de refus desdits centres, la commande sera automatiquement annulée et le Client prévenu par e-mail. Les confirmations de commande seront archivées dans les locaux de UBERPRIMEUR.FR et seront considérées comme valant preuve de la nature de la convention et de sa date. Le client ne dispose pas d'un droit de rétractation conformément aux dispositions de l'article L.121-20-2 du Code de la consommation. <br> RESERVES : UBERPRIMEUR.FR se réserve en outre la possibilité de ne pas confirmer une commande pour quelques raisons que ce soit, tenant en particulier à un problème d'approvisionnement des produits en raison de leur caractère périssable, un problème concernant la commande reçue, ou un problème prévisible concernant la livraison à effectuer. <br> </p> </div> <div class="separateur1"></div> </span> <script type="text/javascript"> function toggle_text(id) { var span = document.getElementById(id); if(span.style.display == "none") { span.style.display = "inline"; } else { span.style.display = "none"; } } </script> </div> <!--Footer--> <div class="footer"> <div id="dispoFoot"> <div id="certif"> <p>Site réalisé par <NAME>, <NAME> et <NAME> ©</p> <p id="ita">Tous droits réservés</p> </div> <div class="reseaux"> <a href="https://www.instagram.com/uberprimeur_/"><img src="../PHOTOS/insta.png" height=40 width=40 alt></a> <a href="https://twitter.com/UPrimeur"><img src="../PHOTOS/twitter.png" height=40 width=40 alt></a> </div> </div> </br> <a href="webmaster.php" id="webmaster">accès webmaster</a> </div> </body> </html><file_sep>/CODE/paimentPanier.php <?php require_once("connect.php"); $cp = $_POST["cp"]; $ville = $_POST["ville"]; $addr = $_POST["addr"]; $addr = str_replace("'"," ",$addr); $req = "SELECT idAdresse FROM adresse WHERE codePostal = $cp AND ville = '$ville' AND adresse ='$addr'"; $test = $co->query($req); $nbLignes = $test->num_rows; if($nbLignes > 0){ while($row = $test->fetch_assoc()){ $idAddr = $row["idAdresse"]; } }else{ $sql = "INSERT INTO adresse VALUES(null,'$cp','$ville','$addr')"; $execute = $co->query($sql); $idAddr = $co->insert_id; } ?> <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/stylePaiment.css" /> </head> <body> <div class="header"> <div class="logo"> <a href="accueil.php"><img id="logoNav" src="../LOGOS/logo5.PNG" width=400 height=62 alt></a> </div> <div class="menuNav"> <a href="a_propos.php" class="rubrique"><img id="iconMenu" src="../PHOTOS/apropos.png" height=18 width=18 alt>À propos</a> <a href="nospaniers.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/nospaniers.png" height=18 width=18 alt>Nos paniers</a> <a href="fruits.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/fruit.jpg" height=18 width=18 alt>Fruits</a> <a href="legumes.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/legume.png" height=18 width=18 alt>Légumes</a> <a href="panier.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/panier.png" height=18 width=18 alt>Panier</a> <a href="compte.php"class="rubrique"><img id="iconMenu" src="../PHOTOS/compte.jpg" height=18 width=18 alt>Compte</a> </div> </div> <div class="contenue"> <?php require_once('connect.php'); echo "<form method='post' action='commande.php'>"; echo "<input type=\"hidden\" name=\"idAddr\" value='$idAddr'>"; ?> <div class="row"> <div class="col-50"> <h3>Paiement</h3> <label for="fname">Cartes acceptées</label> <div class="icon-container"> <i class="fa fa-cc-visa" style="color:navy;"></i> <i class="fa fa-cc-amex" style="color:blue;"></i> <i class="fa fa-cc-mastercard" style="color:red;"></i> <i class="fa fa-cc-discover" style="color:orange;"></i> </div> <label >Nom sur la carte</label> <input type="text" id="" name="" placeholder="" required> <label for="">Numéro de carte</label> <input type="text" id="" name="" placeholder="1111-2222-3333-4444"> <label for="">Mois d'expiration </label> <input type="text" id="" name="" placeholder="Septembre" required> <div class="row"> <div class="col-50"> <label for="">Année d'expiration</label> <input type="text" id="" name="" placeholder="2022" required> </div> <div class="col-50"> <label for="">Cryptogramme (CVV)</label> <input type="text" id="" name="" placeholder="352" required> </div> </div> </div> </div> <button class="btn" type="submit">Payer</button> </form> </div> <div class="footer"> <div id="dispoFoot"> <div id="certif"> <p>Site réalisé par <NAME>, <NAME> et <NAME> ©</p><p id="ita">Tous droits réservés</p> </div> <div class="reseaux"> <a href="https://www.instagram.com/uberprimeur_/"><img src="../PHOTOS/insta.png" height=40 width=40 alt ></a> <a href="https://twitter.com/UPrimeur"><img src="../PHOTOS/twitter.png" height=40 width=40 alt ></a> </div> </div> </br> <a href="webmaster.php" id="webmaster">accès webmaster</a> </div> </body> </html> <file_sep>/CODE/mail.php <?php require_once('connect.php'); session_start(); if($_SESSION['idCli'] != 0){ $idcli = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } $mail = $_POST['mail']; $req = "SELECT mailCli FROM client WHERE idClient = '$idcli' "; $rep = $co->query($req); while( $row = $rep->fetch_assoc()){ $idM = $row['mailCli']; } $sql="UPDATE mail SET mail = '$mail' WHERE idMail = '$idM' "; $modif = $co->query($sql); header('Location: compte.php'); ?> <file_sep>/CODE/inscription.php <?php require_once("connect.php"); // Grain de sel pour personnaliser le hachage du mdp $salt = "*$=²ù€;.?,È{qü=BuÐ8ƒµ´à¤"; //Hachage du mdp avec la fonction md5 et le grain de sel $mdp = md5($_POST["mdp"].$salt); $choix = 0; // Récupération du choix if ($_POST["choix"]=="oui"){ $choix = 1; } $hebdo =""; // On évite les failles : $nom = strip_tags($_POST['nom']); $nom = mysqli_real_escape_string($co ,$nom); $prenom = strip_tags($_POST['prenom']); $prenom = mysqli_real_escape_string($co ,$prenom); $mail = strip_tags($_POST['mail']); $mail = mysqli_real_escape_string($co ,$mail); $tel = strip_tags($_POST['tel']); $tel = mysqli_real_escape_string($co ,$tel); $cp = strip_tags($_POST['cp']); $cp = mysqli_real_escape_string($co ,$cp); $ville = strip_tags($_POST['ville']); $ville = mysqli_real_escape_string($co ,$ville); $addr = strip_tags($_POST['addr']); $addr = mysqli_real_escape_string($co ,$addr); $verifMail = "SELECT * FROM client JOIN mail ON (mailCli = idMail) WHERE mail = '$mail' "; $vmail = $co->query($verifMail); $count = $vmail->num_rows; echo $count; if($count > 0){ header("Location: index.html"); exit; } // Création du mail $insertMail = "INSERT INTO mail VALUES (null,'$mail')"; $insmail = $co->query($insertMail); $idmail = $co->insert_id; // Création de l'adresse $addr = str_replace("'"," ",$addr); $insertAddr = "INSERT INTO adresse VALUES(null,'$cp','$ville','$addr')"; $insAd = $co->query($insertAddr); $idAddr = $co->insert_id; $test2 = 1; // Création du client $insert = "INSERT INTO client VALUES (null,'$nom','$prenom','$mdp','$choix','$hebdo','$tel','$idAddr','$idmail')"; $inscli = $co->query($insert); header("Location: index.html"); exit; ?> <file_sep>/CODE/paiment.php <?php require_once('connect.php'); session_start(); if($_SESSION['idCli'] != 0){ $idclient = $_SESSION['idCli']; }else{ header("Location: index.html"); exit; } $choix = $_POST['Choix']; $_SESSION['choixP'] = $choix; header("Location: paiement.html"); exit; ?>
6485bea112fae28e3b057f4c4758519c7d8f0294
[ "PHP" ]
27
PHP
ThomasDev6/UbPrimeur
956fc200506de94e74a54d6099b34710520b38ae
b9703f893e7eafdc20c2828f03f2489f532c99ae
refs/heads/master
<repo_name>AppStateESS/analytics<file_sep>/class/trackers/GoogleAnalytics4Tracker.php <?php /** * MIT License * Copyright (c) 2021 Electronic Student Services @ Appalachian State University * * See LICENSE file in root directory for copyright and distribution permissions. * * @author <NAME> <<EMAIL>> * @license https://opensource.org/licenses/MIT */ \phpws\PHPWS_Core::initModClass('analytics', 'Tracker.php'); class GoogleAnalytics4Tracker extends Tracker { var $account4; public function save() { $result = parent::save(); if (PHPWS_Error::isError($result)) return $result; $db = new PHPWS_DB('analytics_tracker_google_4'); $db->addWhere('id', $this->id); $result = $db->select(); if (PHPWS_Error::logIfError($result)) { return $result; } $db = new PHPWS_DB('analytics_tracker_google_4'); $db->addValue('id', $this->id); $db->addValue('account4', $this->account4); if (count($result) < 1) { $result = $db->insert(false); } else { $result = $db->update(); } if (PHPWS_Error::logIfError($result)) return $result; } public function delete() { $result = parent::delete(); if (PHPWS_Error::isError($result)) return $result; $db = new PHPWS_DB('analytics_tracker_google_4'); $db->addWhere('id', $this->id); $result = $db->delete(); if (PHPWS_Error::logIfError($result)) return $result; } public function track() { $vars = array(); $vars['TRACKER_ID'] = $this->getAccount4(); $code = PHPWS_Template::process($vars, 'analytics', 'GoogleAnalytics4/tracker.tpl'); self::addEndBody($code); } public function trackerType() { return 'GoogleAnalytics4Tracker'; } public function addForm(PHPWS_Form &$form) { $form->addText('account4', $this->getAccount4()); $form->setLabel('account4', 'Account Identifier (ie, G-XXXXXXXXXX)'); $form->setRequired('account4'); } public function processForm(array $values) { parent::processForm($values); $this->setAccount4(PHPWS_Text::parseInput($values['account4'])); } public function joinDb(PHPWS_DB &$db) { $db->addJoin('left outer', 'analytics_tracker', 'analytics_tracker_google_4', 'id', 'id'); $db->addColumn('analytics_tracker_google_4.account4'); } public function getFormTemplate() { return 'GoogleAnalytics4/admin.tpl'; } public function setAccount4($account4) { $this->account4 = $account4; } public function getAccount4() { return $this->account4; } } <file_sep>/tests/TrackerFactoryTest.php <?php /** * Description * @author <NAME> <jtickle at tux dot appstate dot edu> */ require_once(PHPWS_SOURCE_DIR . 'mod/analytics/class/TrackerFactory.php'); class TrackerFactoryTest extends PHPUnit_Framework_TestCase { public function testInstantiateTrackers() { $this->assertTrue( TrackerFactory::newByType('GoogleAnalyticsTracker') instanceof GoogleAnalyticsTracker); $this->assertTrue( TrackerFactory::newByType('GoogleAnalytics4') instanceof GoogleAnalytics4); $this->assertTrue( TrackerFactory::newByType('OpenWebAnalyticsTracker') instanceof OpenWebAnalyticsTracker); $this->assertTrue( TrackerFactory::newByType('PiwikTracker') instanceof PiwikTracker); } } <file_sep>/README.md # analytics Google Analytics module for Canopy <file_sep>/boost/update.php <?php /** * Description * @author <NAME> <jtickle at tux dot appstate dot edu> */ function analytics_update(&$content, $currentVersion) { switch ($currentVersion) { case version_compare($currentVersion, '1.0.1', '<'): $db = new PHPWS_DB('analytics_tracker'); $result = $db->addTableColumn('disable_if_logged', 'int NOT NULL default 0'); if (PHPWS_Error::logIfError($result)) { $content[] = 'Unable to add disable_if_logged column to analytics_tracker table.'; return false; } $files = array('templates/edit.tpl'); if (PHPWS_Boost::updateFiles($files, 'analytics')) { $content[] = '--- Updated templates/edit.tpl'; } case version_compare($currentVersion, '1.1.0', '<'): // install.sql has been wrong for awhile, this should fix any discrepancies $db = new PHPWS_DB('analytics_tracker'); if (!$db->isTableColumn('disable_if_logged')) { $result = $db->addTableColumn('disable_if_logged', 'int NOT NULL default 0'); if (PHPWS_Error::logIfError($result)) { $content[] = 'Unable to add disable_if_logged column to analytics_tracker table.'; return false; } $content[] = '--- Added disable_if_logged option to database'; } // Load new schema $db = new PHPWS_DB; $result = $db->importFile(PHPWS_SOURCE_DIR . 'mod/analytics/boost/update/1.1.0.sql'); if (PHPWS_Error::logIfError($result)) { $content[] = 'Unable to import updated schema for version 1.1.0.'; return false; } $content[] = '--- Updated Analytics schema to 1.1.0'; // Move Google Analytics data to its own table $db = new PHPWS_DB('analytics_tracker'); $db->addColumn('id'); $db->addColumn('account'); $db->addWhere('type', 'GoogleAnalyticsTracker'); $result = $db->select(); if (PHPWS_Error::logIfError($result)) { $content[] = 'Unable to select Google Analytics tracker from analytics_tracker table.'; return false; } foreach ($result as $row) { $db = new PHPWS_DB('analytics_tracker_google'); $db->addValue('id', $row['id']); // Adding UA- into the account identifier to reduce confusion $db->addValue('account', 'UA-' . $row['account']); $db->insert(false); $content[] = "--- Migrated Google Analytics configuration for account UA-{$row['account']}"; } $db = new PHPWS_DB('analytics_tracker'); $result = $db->dropTableColumn('account'); if (PHPWS_Error::logIfError($result)) { $content[] = 'Unable to remove account column from analytics_tracker table.'; return false; } $content[] = '--- Completed migration to Analytics 1.1.0 schema'; case version_compare($currentVersion, '1.1.1', '<'): $content[] = <<<EOF <pre>Version 1.1.1 ------------------- + Piwik fix. + Fixed uninstall script </pre> EOF; case version_compare($currentVersion, '1.1.2', '<'): $content[] = <<<EOF <pre>Version 1.1.2 ------------------- + Updated Google Analytics script </pre> EOF; case version_compare($currentVersion, '1.2.0', '<'): $db = \phpws2\Database::getDB(); $tbl = $db->buildTable('analytics_tracker_google_4'); $dt = $tbl->addDataType('account4', 'varchar'); $dt->setSize(255); $tbl->addPrimaryIndexId(); $tbl->create(); $content[] = <<<EOF <pre>Version 1.2.0 ------------------- + Added Google Analytics 4 script </pre> EOF; case version_compare($currentVersion, '1.3.0', '<'): $db = \phpws2\Database::getDB(); $tbl = $db->buildTable('analytics_tag_google'); $dt = $tbl->addDataType('tagAccount', 'varchar'); $dt->setSize(255); $tbl->addPrimaryIndexId(); $tbl->create(); $content[] = <<<EOF <pre>Version 1.3.0 ------------------- + Added Google Tag script </pre> EOF; } return true; } <file_sep>/boost/install.sql CREATE TABLE analytics_tracker ( id INTEGER NOT NULL PRIMARY KEY, name VARCHAR(255) NOT NULL, type VARCHAR(255) NOT NULL, active SMALLINT NOT NULL DEFAULT 0, disable_if_logged INTEGER NOT NULL DEFAULT 0 ); CREATE TABLE analytics_tracker_google ( id INTEGER NOT NULL PRIMARY KEY, account VARCHAR(255) ); CREATE TABLE analytics_tracker_google_4 ( id INTEGER NOT NULL PRIMARY KEY, account4 VARCHAR(255) ); CREATE TABLE analytics_tag_google ( id INTEGER NOT NULL PRIMARY KEY, tagAccount VARCHAR(255) ); CREATE TABLE analytics_tracker_piwik ( id INTEGER NOT NULL PRIMARY KEY, piwik_url VARCHAR(255), piwik_id INTEGER ); CREATE TABLE analytics_tracker_owa ( id INTEGER NOT NULL PRIMARY KEY, owa_url VARCHAR(255), owa_site_id VARCHAR(32), owa_track_page_view SMALLINT, owa_track_clicks SMALLINT, owa_track_domstream SMALLINT ); <file_sep>/class/Tracker.php <?php /** * Analytics Tracker Abstract Class * @author <NAME> <jtickle at tux dot appstate dot edu> */ abstract class Tracker { var $id; var $name; var $type; var $active; var $disable_if_logged; public function __construct() { $this->type = $this->trackerType(); } public abstract function track(); public abstract function trackerType(); public abstract function addForm(PHPWS_Form &$form); public abstract function joinDb(PHPWS_DB &$db); public abstract function getFormTemplate(); public function processForm(array $values) { $this->setName(PHPWS_Text::parseInput($values['name'])); if (isset($values['active'])) { $this->setActive(); } else { $this->setInactive(); } if (isset($values['disable_if_logged'])) { $this->setDisableIfLogged(true); } else { $this->setDisableIfLogged(false); } } public function delete() { $db = new PHPWS_DB('analytics_tracker'); $db->addWhere('id', $this->id); $result = $db->delete(); if (PHPWS_Error::logIfError($result)) { return $result; } } public function save() { $db = new PHPWS_DB('analytics_tracker'); $result = $db->saveObject($this); if (PHPWS_Error::logIfError($result)) { return $result; } } public static function addEndBody($content) { Layout::add($content, 'analytics', 'end_body'); } public static function addStartBody($content) { Layout::add($content, 'analytics', 'start_body'); } public static function addHead($content) { Layout::add($content, 'analytics', 'head'); } public function getId() { return $this->id; } public function setId($id) { $this->id = $id; } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } public function isActive() { return $this->active != 0; } public function setActive() { $this->active = 1; } public function setInactive() { $this->active = 0; } public function setDisableIfLogged($disable) { $this->disable_if_logged = $disable; } public function getDisableIfLogged() { return $this->disable_if_logged; } } <file_sep>/inc/runtime.php <?php if (\phpws\PHPWS_Core::moduleExists('analytics')) { \phpws\PHPWS_Core::initModClass('analytics', 'Analytics.php'); Analytics::injectTrackers(); } <file_sep>/boost/boost.php <?php /** * @author <NAME> <<EMAIL>> * @version $Id$ */ $proper_name = 'Analytics'; $version = '1.3.0'; $register = false; $unregister = false; $import_sql = true; $version_http = 'http://phpwebsite.appstate.edu/downloads/modules/analytics/check.xml'; $about = true; $priority = 50; $dependency = false; $image_dir = false; <file_sep>/class/trackers/GoogleTagManager.php <?php declare(strict_types=1); /** * MIT License * Copyright (c) 2021 Electronic Student Services @ Appalachian State University * * See LICENSE file in root directory for copyright and distribution permissions. * * @author <NAME> <<EMAIL>> * @license https://opensource.org/licenses/MIT */ class GoogleTagManager extends Tracker { public $tagAccount; public function save() { $result = parent::save(); if (PHPWS_Error::isError($result)) return $result; $db = new PHPWS_DB('analytics_tag_google'); $db->addWhere('id', $this->id); $result = $db->select(); if (PHPWS_Error::logIfError($result)) { return $result; } $db = new PHPWS_DB('analytics_tag_google'); $db->addValue('id', $this->id); $db->addValue('tagAccount', $this->tagAccount); if (count($result) < 1) { $result = $db->insert(false); } else { $result = $db->update(); } if (PHPWS_Error::logIfError($result)) return $result; } public function track() { $vars = array(); $vars['TRACKER_ID'] = $this->tagAccount; $head = PHPWS_Template::process($vars, 'analytics', 'GoogleTagManager/head.tpl'); $body = PHPWS_Template::process($vars, 'analytics', 'GoogleTagManager/body.tpl'); self::addHead($head); self::addStartBody($body); } public function trackerType() { return 'GoogleTagManager'; } public function processForm(array $values) { parent::processForm($values); $this->tagAccount = PHPWS_Text::parseInput($values['tagAccount']); } public function addForm(PHPWS_Form &$form) { $form->addText('tagAccount', $this->tagAccount); $form->setLabel('tagAccount', 'Account Identifier (ie, GTM-XXXXXX)'); $form->setRequired('tagAccount'); } public function joinDb(PHPWS_DB &$db) { $db->addJoin('left outer', 'analytics_tracker', 'analytics_tag_google', 'id', 'id'); $db->addColumn('analytics_tag_google.tagAccount'); } public function getFormTemplate() { return 'GoogleTagManager/admin.tpl'; } } <file_sep>/class/TrackerFactory.php <?php /** * Tracker Factory * @author <NAME> <jtickle at tux dot appstate dot edu> */ \phpws\PHPWS_Core::initModClass('analytics', 'Tracker.php'); class TrackerFactory { public static function getActive() { $db = self::initDb(); $db->addWhere('active', 1); // Exclude certain trackers if the user is logged in if (Current_User::isLogged()) { $db->addWhere('disable_if_logged', 0); } return self::runQuery($db); } public static function getById($id) { $db = self::initDb(); $db->addWhere('id', $id); $trackers = self::runQuery($db); return $trackers[0]; } public static function newByType($type) { \phpws\PHPWS_Core::initModClass('analytics', "trackers/$type.php"); return new $type(); } public static function getAll() { $db = self::initDb(); return self::runQuery($db); } public static function getAvailableClasses() { $tracker_files = scandir(PHPWS_SOURCE_DIR . 'mod/analytics/class/trackers'); $trackers = array(); foreach ($tracker_files as $file) { if (substr($file, -4) != '.php') continue; $trackers[] = substr($file, 0, -4); } return $trackers; } protected static function initDb() { return new PHPWS_DB('analytics_tracker'); } protected static function runQuery(\phpws\PHPWS_DB $db) { self::joinAll($db); $db->addColumn('analytics_tracker.*'); try { $result = $db->select(); } catch (\Exception $e) { if (\Current_User::isDeity()) { \Layout::add('<div class="alert alert-danger">Analytics is returning an error: ' . $e->getMessage() . '</div>', 'analytics'); } return false; } if (PHPWS_Error::logIfError($result)) { return FALSE; } $trackers = array(); foreach ($result as $tracker) { $found = \phpws\PHPWS_Core::initModClass('analytics', "trackers/{$tracker['type']}.php"); if (!$found) { continue; } $trackerType = $tracker['type']; $t = new $trackerType; \phpws\PHPWS_Core::plugObject($t, $tracker); $trackers[] = $t; } return $trackers; } protected static function joinAll(PHPWS_DB &$db) { $trackers = self::getAvailableClasses(); foreach ($trackers as $tracker) { $t = self::newByType($tracker); $t->joinDb($db); } } } <file_sep>/class/Analytics.php <?php /** * Analytics Controller Class * @author <NAME> <jtickle at tux dot appstate dot edu> */ class Analytics { public static function injectTrackers() { \phpws\PHPWS_Core::initModClass('analytics', 'TrackerFactory.php'); $trackers = TrackerFactory::getActive(); if (empty($trackers)) return; foreach ($trackers as $tracker) { $tracker->track(); } } public static function process() { if (!Current_User::authorized('analytics')) Current_User::disallow(); $panel = self::cpanel(); if (isset($_REQUEST['command'])) { $command = $_REQUEST['command']; } else { $command = $panel->getCurrentTab(); } switch ($command) { case 'list': $panel->setContent(self::listTrackers()); break; case 'new': $panel->setContent(self::newTracker()); break; case 'create': $panel->setContent(self::createTracker()); break; case 'edit': $panel->setContent(self::editTracker()); break; case 'delete': $panel->setContent(self::deleteTracker()); break; case 'save_tracker': $panel->setContent(self::saveTracker()); break; } Layout::add(PHPWS_ControlPanel::display($panel->display())); } public static function listTrackers() { \phpws\PHPWS_Core::initModClass('analytics', 'GenericTracker.php'); \phpws\PHPWS_Core::initCoreClass('DBPager.php'); $pager = new DBPager('analytics_tracker', 'GenericTracker'); $pager->addSortHeader('name', 'Name'); $pager->addSortHeader('type', 'Type'); $pager->addSortHeader('active', 'Active'); $pageTags = array(); $pageTags['ACTION'] = 'Action'; $pageTags['ACCOUNT'] = 'Account ID'; $pager->setModule('analytics'); $pager->setTemplate('list.tpl'); $pager->addToggle('class="toggle1"'); $pager->addRowTags('getPagerTags'); $pager->addPageTags($pageTags); $pager->setSearch('name'); $pager->setDefaultOrder('name', 'asc'); $pager->cacheQueries(); return $pager->get(); } public static function newTracker() { $form = new PHPWS_Form('tracker'); $form->addHidden('module', 'analytics'); $form->addHidden('command', 'create'); $form->addSubmit('submit', 'Next'); $classes = TrackerFactory::getAvailableClasses(); $trackers = array(); foreach ($classes as $class) { $trackers[$class] = $class; } $form->addSelect('tracker', $trackers); $form->setLabel('tracker', 'Tracker'); $form->setRequired('tracker'); $tpl = $form->getTemplate(); return PHPWS_Template::process($tpl, 'analytics', 'select.tpl'); } public static function createTracker() { $tracker = TrackerFactory::newByType($_REQUEST['tracker']); return self::showEditForm($tracker); } public static function editTracker() { \phpws\PHPWS_Core::initModClass('analytics', 'TrackerFactory.php'); $tracker = TrackerFactory::getById($_REQUEST['tracker_id']); return self::showEditForm($tracker); } public static function deleteTracker() { \phpws\PHPWS_Core::initModClass('analytics', 'TrackerFactory.php'); $tracker = TrackerFactory::getById($_REQUEST['tracker_id']); $tracker->delete(); self::redirectList(); } public static function saveTracker() { \phpws\PHPWS_Core::initModClass('analytics', 'TrackerFactory.php'); if (isset($_REQUEST['tracker_id'])) { $tracker = TrackerFactory::getById($_REQUEST['tracker_id']); } else { $tracker = TrackerFactory::newByType($_REQUEST['tracker']); } $tracker->processForm($_REQUEST); $tracker->save(); self::redirectList(); } public static function redirectList() { $redirect = PHPWS_Text::linkAddress('analytics', array('tab' => 'list'), true, false, false); header('HTTP/1.1 303 See Other'); header('Location: ' . $redirect); exit(); } public static function showEditForm(Tracker $tracker) { $tpl = array(); $tpl['TRACKER_TYPE'] = $tracker->trackerType(); $form = new PHPWS_Form('tracker'); $form->addHidden('module', 'analytics'); $form->addHidden('command', 'save_tracker'); $form->addSubmit('submit', 'Save Tracker'); if (isset($_REQUEST['tracker'])) { $form->addHidden('tracker', $_REQUEST['tracker']); } if ($tracker->getId() > 0) { $form->addHidden('tracker_id', $tracker->getId()); } $form->addText('name', $tracker->getName()); $form->setLabel('name', 'Friendly Name'); $form->setRequired('name'); $form->addCheck('active', 1); $form->setMatch('active', $tracker->isActive()); $form->setLabel('active', 'Currently Active'); $form->addCheck('disable_if_logged', 1); $form->setMatch('disable_if_logged', $tracker->getDisableIfLogged()); $form->setLabel('disable_if_logged', 'Disable Analytics if a user is logged in'); $tracker->addForm($form); $tpl = array_merge($tpl, $form->getTemplate()); $tpl['TRACKER_FORM'] = PHPWS_Template::process($tpl, 'analytics', $tracker->getFormTemplate()); return PHPWS_Template::process($tpl, 'analytics', 'edit.tpl'); } public static function cpanel() { \phpws\PHPWS_Core::initModClass('controlpanel', 'Panel.php'); $link = PHPWS_Text::linkAddress('analytics', null, false, false, true, false); $tabs['list'] = array('title' => 'List Trackers', 'link' => $link); $tabs['new'] = array('title' => 'New Tracker', 'link' => $link); $panel = new PHPWS_Panel('analyticsPanel'); $panel->enableSecure(); $panel->quickSetTabs($tabs); $panel->setModule('analytics'); $panel->setPanel('panel.tpl'); return $panel; } }
b8569b0b64dd205f6fd364c274cda377e3139a31
[ "Markdown", "SQL", "PHP" ]
11
PHP
AppStateESS/analytics
dd61456f4815b521b777e0e22b9fe5cba54a0aef
f923ed322800d0c436630871e1dac49bb549dc92
refs/heads/master
<file_sep>public class Situation { Node toExplore; // The node that needs to keep tracking int alreadyExplored; // The number of crosses already explored int stepsGiven; // The moves we've made so far (this is absolute and it's important to track traffic lights' state) public Situation(Node toExplore, int alreadyExplored, int stepsGiven) { this.alreadyExplored = alreadyExplored; this.stepsGiven = stepsGiven; this.toExplore = toExplore; } public Node getToExplore() { return toExplore; } public void setToExplore(Node toExplore) { this.toExplore = toExplore; } public int getAlreadyExplored() { return alreadyExplored; } public void setAlreadyExplored(int alreadyExplored) { this.alreadyExplored = alreadyExplored; } public int getStepsGiven() { return stepsGiven; } public void setStepsGiven(int stepsGiven) { this.stepsGiven = stepsGiven; } } <file_sep>public class Node { private char name; // Number of possible routes private int size = 0; private Cross[] crosses; public Node(char name) { this.name = name; crosses = new Cross[10]; } private void add(Node towards, int trafficLight, boolean isFirst) { int i = 0; // As names are chars, comparing them is as simple as subtracting them // to see whether the result is positive or negative // Negative means that we haven't past the alphabetical position // The moment when it gets positive, that is its position int compare = -1; while (i < size && crosses[i] != null && compare < 0) { compare = crosses[i].getDestinationName() - towards.getName(); i++; } if (compare > 0) { i--; System.arraycopy(crosses, i, crosses, i + 1, size - i); } crosses[i] = new Cross(this, towards, trafficLight); size++; if (isFirst) { towards.add(this, trafficLight, false); } } public void add(Node towards, int trafficLight) { add(towards, trafficLight, true); } public Cross[] getCrosses() { return crosses; } public Node getNode(int i) { return crosses[i].getDestination(); } public void showCrosses() { for (int i = 0; i < size; i++) { System.out.println(crosses[i]); } } public char getName() { return name; } public void setName(char name) { this.name = name; } public int getSize() { return size; } @Override public String toString() { String res = "Node " + name + ", connected to: "; for (int i = 0; i < size; i++) { res += crosses[i].getDestinationName(); if (i != size - 1) { res += ", "; } } return res; } @Override public boolean equals(Object o) { if (o instanceof Node) { return this.name == ((Node) o).getName(); } return false; } }
17f9fa02f2b46ef8203f5b9c454581a8288b1e6e
[ "Java" ]
2
Java
JaviAibar/LaberintosVieneses
cff4f5ad6928605bdb7fe1b18c302cf774c02782
9a45046490e889f36ea20c1659b719838835376f
refs/heads/master
<repo_name>StN-/Proyecto1_200925270<file_sep>/ebr_200925270.h //ebr_200925270.h #ifndef EBR_H #define EBR_H /* * * * */ #define SIGUIENTE_EBR(s) ((s)->part_next) #define AJUSTE_EBR(s) ((s)->part_fit) #define POSICION_EBR(s) ((s)->part_start) #define ESTADO_EBR(s) ((s)->part_status) #define NOMBRE_EBR(s) ((s)->part_name) #define TAMANO_EBR(s) ((s)->part_size) struct extend { unsigned int part_start; unsigned int part_size; char part_name[16]; char part_status; char part_fit; int part_next; }; typedef struct extend extend; /* * * * */ static inline extend *nuevo_extend_boot_record (); /* * * * */ static inline extend *nuevo_extend_boot_record () { extend *nueva = malloc ( sizeof( struct extend ) ); strcpy ( NOMBRE_EBR( nueva ), "" ); AJUSTE_EBR( nueva ) = '0'; SIGUIENTE_EBR( nueva ) = -1; POSICION_EBR( nueva ) = 0; ESTADO_EBR( nueva ) = '0'; TAMANO_EBR( nueva ) = 0; return nueva; } #endif // EBR_H<file_sep>/administrador_reporte_200925270.h //administrador_reporte_200925270.h #ifndef ADMINISTRADOR_REPORTE_H #define ADMINISTRADOR_REPORTE_H /* * * * */ inline void validar_creacion_reportes ( parametro **, parametro ** ); /* * * * */ inline void validar_creacion_reportes ( parametro **_parametros, parametro **_errores ) { if(DEPURADOR) printf("\n\t(Entrada Del Administrador de Reportes)"); printf("\n\tValidando Parametros para la Generacion de Reportes."); parametro *errores = NULL; if( cantidad_parametros ( (*_parametros) ) == 0 ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : Debe de ingresar al menos un parametro." ); } /* * ARGUMENTO PATH OBLIGATORIO */ char arg_path[128] = ""; if ( !buscar_parametro ( _parametros, PATH, arg_path ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : No existe el parametro <<path>>" ); } if(DEPURADOR) printf("\n\t(Buscando parametro: PATH)"); /* * ARGUMENTO NAME OBLIGATORIO */ int arg_type_rep = 0; char arg_name[32] = ""; if ( !buscar_parametro ( _parametros, NAME, arg_name ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : No existe el parametro <<name>>" ); } else { convertir_minusculas ( arg_name, arg_name ); (strcmp(arg_name, "mbr") == 0) ? arg_type_rep = 1 : (strcmp(arg_name, "disk") == 0) ? arg_type_rep = 2 : // (strcmp(arg_name, "tree") == 0) ? arg_name_ = REPORTE_TIPO_TREE : // (strcmp(arg_name, "inode") == 0) ? arg_name_ = REPORTE_TIPO_INODE : // (strcmp(arg_name, "block") == 0) ? arg_name_ = REPORTE_TIPO_BLOCK : // (strcmp(arg_name, "sb") == 0) ? arg_name_ = REPORTE_TIPO_SUPER : // (strcmp(arg_name, "bm_inode") == 0) ? arg_name_ = REPORTE_TIPO_BM_INODE : // (strcmp(arg_name, "bm_block") == 0) ? arg_name_ = REPORTE_TIPO_BM_BLOCK : agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : El valor del paramatro <<name>>, debe ser <<mbr>>, <<disk>>, <<inode>>, <<super>>, <<block>> o <<tree>>." ); } if(DEPURADOR) printf("\n\t(Buscando parametro: NAME)"); /* * ARGUMENTO ID OBLIGATORIO */ char arg_id[12] = ""; if ( !buscar_parametro ( _parametros, ID, arg_id ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : No existe el parametro <<id>>" ); } if(DEPURADOR) printf("\n\t(Buscando parametro: ID)"); if( cantidad_parametros ( errores ) > 0 ) { (*_errores) = errores; return; } if( cantidad_parametros ( (*_parametros) ) > 0 ) { return; } verificar_creacion_reporte ( arg_path, arg_type_rep, arg_id ); } #endif // ADMINISTRADOR_REPORTE_H <file_sep>/funciones_200925270.h //funciones_200925270.h #ifndef FUNCION_H #define FUNCION_H /* * * * */ // inline int validar_directorio ( char [] ); void concatenar ( char *, int _cantidad, ... ); void tiempo_actual( char *, int ); int existe_archivo ( char [] ); // void imprimir_v1 ( const char *, ... ); // void imprimir_v2 ( int, ... ); void leer_entrada_formato_cadena ( char *, const char * ); int leer_entrada_formato_decimal ( const char *, int ); int validar_convertir_decimal ( int *, char [] ); void convertir_minusculas ( char *, char [] ); void reemplazar ( char *, char [], char [], int ); /* * * * */ // void imprimir_v1 ( const char *_contenido, ... ) { // va_list listado; // va_start( listado, _contenido ); // vprintf( _contenido, listado ); // va_end( listado ); // } // void imprimir_v2 ( int _cantidad, ... ) { // int i = 0; // va_list vl; // char entrada[256]; // va_start(vl,_cantidad); // for ( ;i < _cantidad; ++i ) { // strcpy( entrada, va_arg( vl, char * ) ); // printf( "\n\t%s", entrada ); // } // va_end(vl); // } void concatenar ( char *_buffer, int _cantidad, ... ) { int i = 0; va_list vl; char cadena[128]; va_start(vl,_cantidad); for (;i < _cantidad; ++i) { strcpy( cadena, va_arg( vl, char * ) ); strcat( _buffer, cadena ); } va_end(vl); } void reemplazar ( char *_buffer, char _sub_cadena[], char _contenido[], int _espacio ) { char *buffer = strstr( _buffer, _sub_cadena ); strncpy ( buffer, _contenido, _espacio ); } // inline int validar_directorio ( char _ruta[] ) { // struct stat st = {0}; // return (stat ( _ruta, &st )==-1)?0:1; // } int existe_archivo ( char _ruta[] ) { return ( access ( _ruta, F_OK ) == -1 ) ? false : true; } void tiempo_actual( char *_fecha, int _tamano ) { time_t ahorita; time( &ahorita ); strncpy( _fecha, ctime(&ahorita), _tamano -1 ); _fecha[_tamano-1] = '\0'; } int leer_entrada_formato_decimal ( const char *_info, int _valor ) { char entrada[5]; printf("%s", _info); if( fgets( entrada, sizeof( entrada ), stdin ) ) sscanf( entrada, "%d", &_valor ); return _valor; } void leer_entrada_formato_cadena ( char *_buffer, const char *_info ) { printf("%s", _info); char entrada[128]; if( fgets( entrada, sizeof( entrada ), stdin ) ) sscanf( entrada, "%[^\n]", _buffer ); } int validar_convertir_decimal ( int *_valor, char _cadena[] ) { int i = 0; for ( ; i < strlen( _cadena ); ++i ) { if ( _cadena[i] != '-' && _cadena[i] != '+' ) if ( !isdigit(_cadena[i]) ) return 0; } sscanf( _cadena, "%d", _valor ); return 1; } void convertir_minusculas ( char *_cadena_min, char _cadena_may[] ) { int i = 0; char buffer[128] = ""; for ( ; i < strlen ( _cadena_may ); ++i ) buffer[i] = (char) tolower ( _cadena_may[i] ); strcpy ( _cadena_min, buffer ); } #endif // FUNCION_H<file_sep>/manejador_disco_200925270.h //manejador_disco_200925270.h #ifndef MANEJADOR_DISCO_H #define MANEJADOR_DISCO_H /* * * * */ inline void verificar_creacion_disco_virtual ( char [], int, int ); inline void verificar_eliminacion_disco_virtual ( char [] ); extern festplatte *festplatten; /* * * * */ inline void verificar_creacion_disco_virtual ( char _arg_path[], int _arg_size, int _tipo ) { if(DEPURADOR) printf("\n\t(Entrada Del Manejador de Disco)"); printf("\n\tValidando Datos para la creacion de Disco."); if ( existe_archivo ( _arg_path ) ) { printf( "\n\t[ERROR] : El archivo <<%s>> Ya exite.", _arg_path ); return; } creacion_disco_virtual ( _arg_path, (_arg_size * _tipo) ); generar_master_boot_record ( _arg_path, (_arg_size * _tipo) ); if(DEPURADOR) imprimir_mbr ( _arg_path ); } inline void verificar_eliminacion_disco_virtual ( char _arg_path[] ) { if(DEPURADOR) printf("\n\t(Entrada Del Manejador de Disco)"); printf("\n\tValidando Datos para la eliminacion de Disco."); if ( !existe_archivo ( _arg_path ) ) { printf( "\n\t[ERROR] : El archivo <<%s>> No exite.", _arg_path ); return; } eliminacion_disco_virtual ( _arg_path ); } inline void verificar_montar_disco ( char _arg_path[], char _arg_name[] ) { if(DEPURADOR) printf("\n\t(Entrada Del Manejador de Disco)"); printf("\n\tValidando Datos para montar particion."); if ( !existe_archivo ( _arg_path ) ) { printf( "\n\t[ERROR] : El archivo <<%s>> No exite.", _arg_path ); return; } master *mbr = recuperar_registro( _arg_path, sizeof( struct master ), 0 ); if ( !verificar_nombre_particion ( _arg_path, mbr->mbr_partition, _arg_name ) ) { printf( "\n\t[ERROR] : No existe la particion con el nombre <<%s>>.", _arg_name ); free ( mbr ); return; } free ( mbr ); montar_particion ( &festplatten, _arg_path, _arg_name ); if(DEPURADOR) imprimir_particiones_montadas ( festplatten ); } inline void verificar_desmontar_disco ( char _arg_id[] ) { if(DEPURADOR) printf("\n\t(Entrada Del Manejador de Disco)"); printf("\n\tValidando Datos para desmontar particion."); if ( !desmontar_particion ( &festplatten, _arg_id ) ) { printf( "\n\t[ERROR] : No existe la Asignacion del id <<%s>>, a una Particion.", _arg_id ); } } #endif // MANEJADOR_DISCO_H<file_sep>/particion_200925270.h //particion_200925270.h #ifndef PARTICION_H #define PARTICION_H /* * * * */ // #define TIPO_AJUSTE_PARTICION(s) ((s)->part_fit) // #define POSICION_PARTICION(s) ((s)->part_start) // #define ESTADO_PARTICION(s) ((s)->part_status) // #define NOMBRE_PARTICION(s) ((s)->part_name) // #define TAMANO_PARTICION(s) ((s)->part_size) // #define TIPO_PARTICION(s) ((s)->part_type) #define TIPO_AJUSTE_PARTICION(s) ((s).part_fit) #define POSICION_PARTICION(s) ((s).part_start) #define ESTADO_PARTICION(s) ((s).part_status) #define NOMBRE_PARTICION(s) ((s).part_name) #define TAMANO_PARTICION(s) ((s).part_size) #define TIPO_PARTICION(s) ((s).part_type) struct particion { unsigned int part_start; unsigned int part_size; char part_name[16]; char part_status; char part_type; char part_fit; }; typedef struct particion particion; /* * * * */ inline particion nueva_particion_vacia (); // inline particion *nueva_particion ( char [], char, char ); /* * * METODO PARA IMPRIMIR LA PARTICION... * */ inline particion nueva_particion_vacia () { particion nueva; //= malloc ( sizeof( struct particion ) ); // strcpy ( NOMBRE_PARTICION( nueva ), "" ); // TIPO_AJUSTE_PARTICION( nueva ) = '0'; // POSICION_PARTICION( nueva ) = 0; // ESTADO_PARTICION ( nueva ) = '0'; // TIPO_PARTICION( nueva ) = '0'; // TAMANO_PARTICION( nueva ) = 0; nueva.part_start = 0; nueva.part_size = 0; strcpy( nueva.part_name, "" ); nueva.part_status = '0'; nueva.part_type = '0'; nueva.part_fit = '0'; return nueva; } // inline particion *nueva_particion ( char _nombre[], char _tipo, char _ajuste ) { // particion *nueva = malloc ( sizeof( struct particion ) ); // strcpy ( NOMBRE_PARTICION ( nueva ), _nombre ); // TIPO_AJUSTE_PARTICION ( nueva ) = _ajuste; // POSICION_PARTICION ( nueva ) = 0; // ESTADO_PARTICION ( nueva ) = '0'; // TIPO_PARTICION ( nueva ) = _tipo; // TAMANO_PARTICION ( nueva ) = 0; // return nueva; // } #endif // PARTICION_H<file_sep>/analizador_200925270.h //analizador_200925270.h #ifndef ANALIZADOR_H #define ANALIZADOR_H /* * * * */ inline void analizar_entrada ( char [], accion ** ); static inline accion *parsear_cadena_entrada ( char [], int ); static inline int validar_instruccion ( char [] ); static inline parametro *validar_formato_parametro ( char [] ); static inline parametro *validar_parametro ( char [], char [] ); /* * * * */ inline void analizar_entrada ( char _entrada[], accion **_instruccion ) { if(DEPURADOR) printf("\n\t(Entrada Del Analizador: %s)", _entrada); printf("\n\tAnalizando Cadena de Entrada."); int longitud = strlen ( _entrada ); (*_instruccion) = parsear_cadena_entrada ( _entrada, longitud ); if(DEPURADOR) printf("\n\t(Salida Del Analizador)"); if ( (*_instruccion) == NULL ) return; if(DEPURADOR) imprimir_instrucciones ( *_instruccion ); } static inline accion *parsear_cadena_entrada ( char _entrada[], int _longitud ) { int i = 0; int estado = 0; char buffer[128] = ""; accion *instruccion = NULL; parametro *parametros = NULL; for ( ; i < _longitud; ++i ) { switch(estado) { case 0: { switch(_entrada[i]) { case ' ': case '\n': case '\t': { estado = 0; } break; case '#': { estado = 1; //generar accion como comentario instruccion = nueva_accion( COMENTARIO ); } break; default: { strncat( buffer, &_entrada[i], 1 ); estado = 2; } break; } } break; case 1: { strncat( buffer, &_entrada[i], 1 ); estado = 1; } break; case 2: { switch(_entrada[i]) { case ' ': case '\n': case '\t': { if(DEPURADOR) printf("\n\t(Accion: %s)", buffer); instruccion = nueva_accion( validar_instruccion ( buffer ) ); strcpy( buffer, "" ); estado = 4; } break; case '#': { if(DEPURADOR) printf("\n\t(Accion: %s)", buffer); instruccion = nueva_accion( validar_instruccion ( buffer ) ); strcpy( buffer, "" ); estado = 1; } break; case '\"': { strncat( buffer, &_entrada[i], 1 ); estado = 3; } break; default: { strncat( buffer, &_entrada[i], 1 ); estado = 2; } break; } } break; case 3: { switch(_entrada[i]) { case '\"': { strncat( buffer, &_entrada[i], 1 ); estado = 2; } break; default: { strncat( buffer, &_entrada[i], 1 ); estado = 3; } break; } } break; case 4: { switch(_entrada[i]) { case ' ': case '\n': case '\t': { estado = 4; } break; case '#': { estado = 1; } break; default: { strncat( buffer, &_entrada[i], 1 ); estado = 5; } break; } } break; case 5: { switch(_entrada[i]) { case ' ': case '\n': case '\t': { if(DEPURADOR) printf("\n\t(Parametro: %s)", buffer); insertar_parametro ( &parametros, validar_formato_parametro ( buffer ) ); strcpy( buffer, "" ); estado = 4; } break; case '#': { if(DEPURADOR) printf("\n\t(Parametro: %s)", buffer); insertar_parametro ( &parametros, validar_formato_parametro ( buffer ) ); strcpy( buffer, "" ); estado = 1; } break; case '\"': { strncat( buffer, &_entrada[i], 1 ); estado = 6; } break; default: { strncat( buffer, &_entrada[i], 1 ); estado = 5; } break; } } break; case 6: { switch(_entrada[i]) { case '\"': { strncat( buffer, &_entrada[i], 1 ); estado = 5; } break; default: { strncat( buffer, &_entrada[i], 1 ); estado = 6; } break; } } break; default: { estado = 0; } break; } } if ( strcmp ( buffer, "" ) != 0 ) { if (instruccion == NULL) { if(DEPURADOR) printf("\n\t(Accion: %s)", buffer); instruccion = nueva_accion( validar_instruccion ( buffer ) ); } else { if(DEPURADOR) printf("\n\t(Parametro: %s)", buffer); insertar_parametro ( &parametros, validar_formato_parametro ( buffer ) ); } } strcpy( buffer, "" ); if (instruccion == NULL && parametros != NULL) { printf( "\n\t[ERROR] : La entrada no concuerda con la sintaxis."); return NULL; } if (instruccion == NULL && parametros == NULL) { return NULL; } instruccion->parametros = parametros; return instruccion; } static inline int validar_instruccion ( char _instruccion[] ) { convertir_minusculas ( _instruccion, _instruccion ); if ( strcmp( _instruccion, "rep" ) == 0 ) return REP; else if ( strcmp( _instruccion, "ren" ) == 0 ) return 0; else if ( strcmp( _instruccion, "rem" ) == 0 ) return 0; else if ( strcmp( _instruccion, "cat" ) == 0 ) return 0; else if ( strcmp( _instruccion, "edit" ) == 0 ) return 0; else if ( strcmp( _instruccion, "mkfs" ) == 0 ) return 0; else if ( strcmp( _instruccion, "exec" ) == 0 ) return EXEC; else if ( strcmp( _instruccion, "exit" ) == 0 ) return EXIT; else if ( strcmp( _instruccion, "mkgrp" ) == 0 ) return 0; else if ( strcmp( _instruccion, "mkusr" ) == 0 ) return 0; else if ( strcmp( _instruccion, "rmgrp" ) == 0 ) return 0; else if ( strcmp( _instruccion, "rmusr" ) == 0 ) return 0; else if ( strcmp( _instruccion, "mkdir" ) == 0 ) return 0; else if ( strcmp( _instruccion, "fdisk" ) == 0 ) return FDISK; else if ( strcmp( _instruccion, "mount" ) == 0 ) return MOUNT; else if ( strcmp( _instruccion, "login" ) == 0 ) return 0; else if ( strcmp( _instruccion, "logout" ) == 0 ) return 0; else if ( strcmp( _instruccion, "mkfile" ) == 0 ) return 0; else if ( strcmp( _instruccion, "mkdisk" ) == 0 ) return MKDISK; else if ( strcmp( _instruccion, "rmdisk" ) == 0 ) return RMDISK; else if ( strcmp( _instruccion, "unmount" ) == 0 ) return UNMOUNT; else if ( strcmp( _instruccion, "" ) == 0 ) { printf(" (Omitido)\n"); return 0; } else { printf( "\n\t[ERROR] : INSTRUCCION NO RECONOCIDA: %s.", _instruccion ); return 0; } } static inline parametro *validar_formato_parametro ( char _argumento[] ) { char nombre_parametro[32]; char valor_parametro[126]; if ( sscanf( _argumento, "-%[^-:]::%[^:]", nombre_parametro, valor_parametro ) == 2 ) { return validar_parametro ( nombre_parametro, valor_parametro ); } else if ( sscanf( _argumento, "–%[^–:]::%[^:]", nombre_parametro, valor_parametro ) == 2 ) { return validar_parametro ( nombre_parametro, valor_parametro ); } else if ( sscanf( _argumento, "+%[^+:]::%[^:]", nombre_parametro, valor_parametro ) == 2 ) { return validar_parametro ( nombre_parametro, valor_parametro ); } else if ( sscanf( _argumento, "-%[^-]", nombre_parametro ) == 1 ) { return validar_parametro ( nombre_parametro, "" ); } else if ( sscanf( _argumento, "–%[^–]", nombre_parametro ) == 1 ) { return validar_parametro ( nombre_parametro, "" ); } else if ( sscanf( _argumento, "+%[^+]", nombre_parametro ) == 1 ) { return validar_parametro ( nombre_parametro, "" ); } else { return validar_parametro ( "error", _argumento ); } return NULL; } static inline parametro *validar_parametro ( char _nombre[], char _valor[] ) { convertir_minusculas ( _nombre, _nombre ); if ( strcmp( _nombre, "fit" ) == 0 ) { convertir_minusculas ( _valor, _valor ); if(DEPURADOR) printf("\n\t(Nombre Parametro: %s)", _nombre); if(DEPURADOR) printf("\n\t(Valor del Parametro: %s)", _valor); return nuevo_parametro ( FIT, _valor ); } else if ( strcmp( _nombre, "add" ) == 0 ) { if(DEPURADOR) printf("\n\t(Nombre Parametro: %s)", _nombre); if(DEPURADOR) printf("\n\t(Valor del Parametro: %s)", _valor); return nuevo_parametro ( ADD, _valor ); } else if ( strcmp( _nombre, "size" ) == 0 ) { if(DEPURADOR) printf("\n\t(Nombre Parametro: %s)", _nombre); if(DEPURADOR) printf("\n\t(Valor del Parametro: %s)", _valor); return nuevo_parametro ( SIZE, _valor ); } else if ( strcmp( _nombre, "unit" ) == 0 ) { convertir_minusculas ( _valor, _valor ); if(DEPURADOR) printf("\n\t(Nombre Parametro: %s)", _nombre); if(DEPURADOR) printf("\n\t(Valor del Parametro: %s)", _valor); return nuevo_parametro ( UNIT, _valor ); } else if ( strcmp( _nombre, "path" ) == 0 ) { sscanf( _valor, "\"%[^\"]\"", _valor ); if(DEPURADOR) printf("\n\t(Nombre Parametro: %s)", _nombre); if(DEPURADOR) printf("\n\t(Valor del Parametro: %s)", _valor); return nuevo_parametro ( PATH, _valor ); } else if ( strcmp( _nombre, "type" ) == 0 ) { convertir_minusculas ( _valor, _valor ); if(DEPURADOR) printf("\n\t(Nombre Parametro: %s)", _nombre); if(DEPURADOR) printf("\n\t(Valor del Parametro: %s)", _valor); return nuevo_parametro ( TYPE, _valor ); } else if ( strcmp( _nombre, "name" ) == 0 ) { sscanf( _valor, "\"%[^\"]\"", _valor ); if(DEPURADOR) printf("\n\t(Nombre Parametro: %s)", _nombre); if(DEPURADOR) printf("\n\t(Valor del Parametro: %s)", _valor); return nuevo_parametro ( NAME, _valor ); } else if ( strcmp( _nombre, "delete" ) == 0 ) { convertir_minusculas ( _valor, _valor ); if(DEPURADOR) printf("\n\t(Nombre Parametro: %s)", _nombre); if(DEPURADOR) printf("\n\t(Valor del Parametro: %s)", _valor); return nuevo_parametro ( DELETE, _valor ); } else if ( strcmp( _nombre, "id" ) == 0 ) { // convertir_minusculas ( _valor, _valor ); if(DEPURADOR) printf("\n\t(Nombre Parametro: %s)", _nombre); if(DEPURADOR) printf("\n\t(Valor del Parametro: %s)", _valor); return nuevo_parametro ( ID, _valor ); } else if ( strcmp( _nombre, "error" ) == 0 ) { if(DEPURADOR) printf("\n\t(Nombre Parametro: %s)", _nombre); if(DEPURADOR) printf("\n\t(Valor del Parametro: %s)", _valor); return nuevo_parametro ( -1, _valor ); } else { if(DEPURADOR) printf("\n\t(Nombre Parametro: %s)", _nombre); if(DEPURADOR) printf("\n\t(Valor del Parametro: %s)", _valor); return nuevo_parametro ( -1, _valor ); } // if ( strcmp( _parametro, "id" ) == 0 ) // return ID; // else /* * * FalTA ID(n) : id1, id2, id3 * */ } #endif // ANALIZADOR_H<file_sep>/unidad_disco_200925270.h //unidad_disco_200925270.h #ifndef UNIDAD_DISCO_H #define UNIDAD_DISCO_H /* * * * */ inline void creacion_disco_virtual ( char [], int ); inline void eliminacion_disco_virtual ( char [] ); /* * * * */ inline void creacion_disco_virtual ( char _arg_path[], int _arg_size ) { FILE *disco_virtual = fopen ( _arg_path, "w+b" ); if (!disco_virtual) { return; } char bloque[1024] = "\0"; register unsigned int i = 0; for ( ; i < _arg_size; i+=1024 ) fwrite ( &bloque, sizeof( bloque ), 1, disco_virtual ); fclose( disco_virtual ); printf( "\n\tEl Disco <<%s>>, se ha Creado Exitosamente.", _arg_path ); } inline void eliminacion_disco_virtual ( char _arg_path[] ) { ( remove( _arg_path ) == 0 ) ? printf( "\n\tEl Disco <<%s>>, se ha Eliminado Exitosamente.", _arg_path ) : printf( "\n\t[ERROR] : El archivo <<%s>> No se pudo Eliminar Correctamente.", _arg_path ); } #endif // UNIDAD_DISCO_H<file_sep>/mbr_200925270.h //mbr_200925270.h #ifndef MBR_H #define MBR_H /* * * * */ #define PARTICION_MBR(s,i) ((s)->mbr_partition[i]) #define FECHA_CREACION_MBR(s) ((s)->mbr_fecha_creacion) #define NUMERO_MAGICO_MBR(s) ((s)->mbr_disk_signature) #define TAMANO_DISCO_MBR(s) ((s)->mbr_tamano) struct master { unsigned int mbr_disk_signature; char mbr_fecha_creacion[24]; particion mbr_partition[4]; unsigned int mbr_tamano; }; typedef struct master master; /* * * * */ inline void generar_master_boot_record ( char [], int ); static inline master *nuevo_master_boot_record ( int ); static inline int cantidad_ebr ( char [], int ); /* * * * */ inline void generar_master_boot_record ( char _arg_path[], int _size ) { register int i = 0; master *mbr = nuevo_master_boot_record ( _size ); for ( ; i < 4; ++i ) PARTICION_MBR( mbr, i) = nueva_particion_vacia (); almacenar_registro_posicion_n ( _arg_path, mbr, sizeof( struct master ), 0 ); free ( mbr ); } inline void imprimir_mbr ( char _arg_path[] ) { master *mbr = recuperar_registro( _arg_path, sizeof( struct master ), 0 ); printf( "\n" ); printf( "\n\t(MASTER BOOT RECORD)" ); printf( "\n\t(Tamano: %d)", TAMANO_DISCO_MBR ( mbr ) ); printf( "\n\t(Fecha: %s)", FECHA_CREACION_MBR ( mbr ) ); printf( "\n\t(Numero Magico: %d)", NUMERO_MAGICO_MBR ( mbr ) ); int i = 0; for ( ; i < 4; ++i) { printf( "\n\t (Localidad: %d)", i ); printf( "\n\t (Posicion: %d)", POSICION_PARTICION ( PARTICION_MBR( mbr, i) ) ); printf( "\n\t (Tipo Particion: %c)", TIPO_PARTICION ( PARTICION_MBR( mbr, i) ) ); printf( "\n\t (Status Particion: %c)", ESTADO_PARTICION ( PARTICION_MBR( mbr, i) ) ); printf( "\n\t (Tamano Particion: %d)", TAMANO_PARTICION ( PARTICION_MBR( mbr, i) ) ); printf( "\n\t (Nombre Particion: %s)", NOMBRE_PARTICION ( PARTICION_MBR( mbr, i) ) ); printf( "\n\t (Tipo Ajuste Particion: %c)", TIPO_AJUSTE_PARTICION ( PARTICION_MBR( mbr, i) ) ); printf( "\n" ); if ( TIPO_PARTICION( PARTICION_MBR( mbr, i) ) == 'E' ) { int posicion = POSICION_PARTICION ( PARTICION_MBR( mbr, i) ); while ( posicion != -1 ) { extend *ebr = recuperar_registro( _arg_path, sizeof( struct extend ), posicion ); printf( "\n\t (Tipo Ajuste Particion: %c)", AJUSTE_EBR( ebr ) ); printf( "\n\t (Nombre Particion: %s)", NOMBRE_EBR( ebr ) ); printf( "\n\t (Tamano Particion: %d)", TAMANO_EBR( ebr ) ); printf( "\n\t (Status Particion: %c)", ESTADO_EBR( ebr ) ); printf( "\n\t (Posicion: %d)", SIGUIENTE_EBR( ebr ) ); printf( "\n\t (Posicion: %d)", POSICION_EBR( ebr ) ); posicion = SIGUIENTE_EBR( ebr ); free( ebr ); } } } free ( mbr ); } inline void crear_reporte_mbr ( char _arg_path[] ) { FILE *archivoReporte = fopen ( "mbr.dot", "w" ); if(!archivoReporte) { printf( " -Error : El archivo <<mbr.dot>> No tiene permisos de escritura.\n" ); return; } fprintf( archivoReporte, "\ndigraph G" ); fprintf( archivoReporte, "\n{" ); fprintf( archivoReporte, "\n\tnode [shape=plaintext];" ); fprintf( archivoReporte, "\n\tsplines=ortho;" ); int i = 0; master *mbr = recuperar_registro( _arg_path, sizeof( struct master ), 0 ); fprintf( archivoReporte, "\n\tnodeA[label=<" ); fprintf( archivoReporte, "\n\t\t<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"2\" CELLPADDING=\"10\">" ); fprintf( archivoReporte, "\n\t\t\t<TR>" ); fprintf( archivoReporte, "\n\t\t\t\t<TD COLSPAN=\"1\" BGCOLOR=\"cadetblue1\">MASTER BOOT RECORDING <BR/> %s</TD>", _arg_path ); fprintf( archivoReporte, "\n\t\t\t</TR>" ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>TAMANO_DISCO_MBR <BR/> %d Bytes</TD></TR>", TAMANO_DISCO_MBR ( mbr ) ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>FECHA_CREACION_PARTICION <BR/> %s</TD></TR>", FECHA_CREACION_MBR ( mbr ) ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>NUMERO_MAGICO_MBR <BR/> %d</TD></TR>", NUMERO_MAGICO_MBR ( mbr ) ); for ( ; i < 4; ++i) { fprintf( archivoReporte, "\n\t\t\t<TR>" ); fprintf( archivoReporte, "\n\t\t\t\t<TD COLSPAN=\"1\" BGCOLOR=\"cyan\">PARTICION<BR/>(%d)</TD>", i ); fprintf( archivoReporte, "\n\t\t\t</TR>" ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>NOMBRE_PARTICION <BR/> %s </TD></TR>", NOMBRE_PARTICION ( PARTICION_MBR( mbr, i) ) ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>POSICION_PARTICION <BR/> %d Bytes</TD></TR>", POSICION_PARTICION ( PARTICION_MBR( mbr, i) ) ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>TIPO_PARTICION <BR/> %c </TD></TR>", TIPO_PARTICION ( PARTICION_MBR( mbr, i) ) ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>STATUS_PARTICION <BR/> %c </TD></TR>", ESTADO_PARTICION ( PARTICION_MBR( mbr, i) ) ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>TAMANO_PARTICION <BR/> %d </TD></TR>", TAMANO_PARTICION ( PARTICION_MBR( mbr, i) ) ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>TIPO_AJUSTE_PARTICION <BR/> %c </TD></TR>", TIPO_AJUSTE_PARTICION ( PARTICION_MBR( mbr, i) ) ); if ( TIPO_PARTICION ( PARTICION_MBR( mbr, i) ) == 'E' ) { int posicion = POSICION_PARTICION ( PARTICION_MBR( mbr, i) ); while ( posicion != -1 ) { extend *ebr = recuperar_registro( _arg_path, sizeof( struct extend ), posicion ); fprintf( archivoReporte, "\n\t\t\t<TR>" ); fprintf( archivoReporte, "\n\t\t\t\t<TD COLSPAN=\"1\" BGCOLOR=\"lawngreen\">PARTICION LOGICA</TD>" ); fprintf( archivoReporte, "\n\t\t\t</TR>" ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>NOMBRE_PARTICION <BR/> %s </TD></TR>", NOMBRE_EBR( ebr ) ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>POSICION_PARTICION <BR/> %d Bytes</TD></TR>", POSICION_EBR( ebr ) ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>SIGUIENTE_PARTICION <BR/> %d </TD></TR>", SIGUIENTE_EBR( ebr ) ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>STATUS_PARTICION <BR/> %c </TD></TR>", ESTADO_EBR( ebr ) ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>TAMANO_PARTICION <BR/> %d </TD></TR>", TAMANO_EBR( ebr ) ); fprintf( archivoReporte, "\n\t\t\t<TR><TD>TIPO_AJUSTE_PARTICION <BR/> %c </TD></TR>", AJUSTE_EBR( ebr ) ); posicion = SIGUIENTE_EBR( ebr ); free( ebr ); } } } fprintf( archivoReporte, "\n\t\t</TABLE>>" ); fprintf( archivoReporte, "\n\t];" ); free (mbr); fprintf( archivoReporte, "\n}" ); fclose( archivoReporte ); } inline void crear_reporte_disk ( char _arg_path[] ) { FILE *archivoReporte = fopen ( "disk.dot", "w" ); fprintf( archivoReporte, "\ndigraph G" ); fprintf( archivoReporte, "\n{" ); fprintf( archivoReporte, "\n\tnode [shape=plaintext];" ); fprintf( archivoReporte, "\n\tsplines=ortho;" ); int i = 0; master *mbr = recuperar_registro( _arg_path, sizeof( struct master ), 0 ); fprintf( archivoReporte, "\n\tnodeA[label=<" ); fprintf( archivoReporte, "\n\t\t<TABLE BORDER=\"0\" CELLBORDER=\"2\" CELLSPACING=\"10\" >" ); fprintf( archivoReporte, "\n\t\t\t<TR>" ); fprintf( archivoReporte, "\n\t\t\t\t<TD ROWSPAN=\"%d\" BGCOLOR=\"cadetblue1\">MBR</TD>", 2 ); int posicion_ext = 0; int cantidad_columnas_ebr = 0; for ( ; i < 4; ++i) { if ( ESTADO_PARTICION ( PARTICION_MBR( mbr, i) ) == '0' ) { fprintf( archivoReporte, "\n\t\t\t\t<TD ROWSPAN=\"%d\" BGCOLOR=\"cadetblue1\">Libre</TD>", 2 ); } else if ( ESTADO_PARTICION ( PARTICION_MBR( mbr, i) ) == 'P' ) { fprintf( archivoReporte, "\n\t\t\t\t<TD ROWSPAN=\"%d\" BGCOLOR=\"cadetblue1\">Primaria<BR/>%d</TD>", 2, TAMANO_PARTICION ( PARTICION_MBR( mbr, i) ) ); } else { posicion_ext = POSICION_PARTICION ( PARTICION_MBR( mbr, i) ); int ebrs = cantidad_ebr ( _arg_path, POSICION_PARTICION ( PARTICION_MBR( mbr, i) ) ); fprintf( archivoReporte, "\n\t\t\t\t<TD COLSPAN=\"%d\" BGCOLOR=\"cadetblue1\">Extendida<BR/>%d Bytes</TD>", ebrs, TAMANO_PARTICION ( PARTICION_MBR( mbr, i) ) ); } } fprintf( archivoReporte, "\n\t\t\t</TR>" ); if (posicion_ext != 0) { fprintf( archivoReporte, "\n\t\t\t<TR>" ); while ( posicion_ext != -1 ) { extend *ebr = recuperar_registro( _arg_path, sizeof( struct extend ), posicion_ext ); fprintf( archivoReporte, "\n\t\t\t\t<TD>EBR</TD>" ); if ( ESTADO_EBR ( ebr ) == '0' ) fprintf( archivoReporte, "\n\t\t\t\t<TD>Libre</TD>" ); else fprintf( archivoReporte, "\n\t\t\t\t<TD>Logica<BR/>%d Bytes</TD>", TAMANO_EBR ( ebr ) ); posicion_ext = SIGUIENTE_EBR( ebr ); free( ebr ); } fprintf( archivoReporte, "\n\t\t\t</TR>" ); } fprintf( archivoReporte, "\n\t\t</TABLE>>" ); fprintf( archivoReporte, "\n\t];" ); free (mbr); fprintf( archivoReporte, "\n}" ); fclose( archivoReporte ); } // nodeA[label=< // <TABLE BORDER="0" CELLBORDER="1" CELLSPACING="2" CELLPADDING="10"> // <TR> // <TD ROWSPAN="2" BGCOLOR="cadetblue1">MBR</TD> // <TD ROWSPAN="2" BGCOLOR="cadetblue1">PARTICION 1</TD> // <TD COLSPAN="4" BGCOLOR="cadetblue1">PARTICION 2<BR/>EXTENDIDA</TD> // <TD ROWSPAN="2" BGCOLOR="cadetblue1">PARTICION 3</TD> // <TD ROWSPAN="2" BGCOLOR="cadetblue1">PARTICION 4</TD> // </TR> // <TR> // <TD>EBR</TD> // <TD>LOGICA 1</TD> // <TD>EBR</TD> // <TD>LOGICA 2</TD> // </TR> // </TABLE>> static inline int cantidad_ebr ( char _arg_path[], int _posicion_inicial ) { int total = 0; while ( _posicion_inicial != -1 ) { extend *ebr = recuperar_registro( _arg_path, sizeof( struct extend ), _posicion_inicial ); total += 2; _posicion_inicial = SIGUIENTE_EBR( ebr ); free( ebr ); } return total; } static inline master *nuevo_master_boot_record ( int _tamano ) { master *nuevo = malloc ( sizeof( struct master) ); // PARTICION_MBR( nuevo, 0 ) = 0; // PARTICION_MBR( nuevo, 1 ) = 0; // PARTICION_MBR( nuevo, 2 ) = 0; // PARTICION_MBR( nuevo, 3 ) = 0; TAMANO_DISCO_MBR( nuevo ) = _tamano; NUMERO_MAGICO_MBR( nuevo ) = 200925270; tiempo_actual( FECHA_CREACION_MBR ( nuevo ), 24 ); return nuevo; } #endif // MBR_H<file_sep>/montar_200925270.h //mountar_200925270.h #ifndef MONTAR_H #define MONTAR_H /* * * * */ struct partition { struct partition *siguiente; char nombre[16]; char id[5]; }; typedef struct partition partition; struct festplatte { struct festplatte *siguiente; partition *partitionen; char ruta[128]; int id; }; typedef struct festplatte festplatte; /* * * * */ inline void montar_particion ( festplatte **, char [], char [] ); static inline void montar_partition ( partition **, char [], int, char ); static inline void montar_festplatte ( festplatte **, char [], char [], int, char ); static inline festplatte *neu_festplatte ( char [], int ); static inline partition *neu_partition ( char [], char [] ); inline void imprimir_particiones_montadas ( festplatte * ); static inline void imprimir_festplatten_montados ( festplatte * ); static inline void imprimir_partitionen_montadas ( partition * ); inline int buscar_id ( festplatte *, char [], char *, char * ); static inline int buscar_id_festplatte ( festplatte *, char [], char *, char * ); static inline int buscar_id_partition ( partition *, char [], char *, char * ); inline int desmontar_particion ( festplatte **, char [] ); static inline int desmontar_id_partition ( partition **, char [] ); static inline int desmontar_id_festplatte ( festplatte **, char [] ); /* * * * */ inline void montar_particion ( festplatte **_festplatten, char _arg_path[], char _arg_name[] ) { montar_festplatte ( _festplatten, _arg_path, _arg_name, 1, 'a' ); } static inline void montar_festplatte ( festplatte **_festplatten, char _arg_path[], char _arg_name[], int _numero, char _letra ) { if ( (*_festplatten) == NULL ) { (*_festplatten) = neu_festplatte ( _arg_path, _numero ); montar_partition ( &(*_festplatten)->partitionen, _arg_name, _numero, _letra ); } else { if( strcmp((*_festplatten)->ruta, _arg_path ) == 0 ) montar_partition ( &(*_festplatten)->partitionen, _arg_name, (*_festplatten)->id, _letra ); else montar_festplatte ( &(*_festplatten)->siguiente, _arg_path, _arg_name, (*_festplatten)->id+1, _letra ); } } static inline void montar_partition ( partition **_partitionen, char _arg_name[], int _numero, char _letra ) { if ( (*_partitionen) == NULL ) { char id[5] = ""; sprintf( id, "vd%c%d", _letra, _numero ); (*_partitionen) = neu_partition ( _arg_name, id ); printf( "\n\tSe Asigno el id <<%s>> a la Particion <<%s>>, exitosamente.", id, _arg_name ); } else { if( strcmp((*_partitionen)->nombre, _arg_name ) != 0 ) montar_partition ( &(*_partitionen)->siguiente, _arg_name, _numero, ++_letra ); else printf("\n\tla particion ya esta montada."); } } inline int buscar_id ( festplatte *_festplatten, char _id[], char *_arg_path, char *_arg_name ) { return ( _festplatten == NULL ) ? false : buscar_id_festplatte ( _festplatten, _id, _arg_path, _arg_name ); } static inline int buscar_id_festplatte ( festplatte *_festplatten, char _id[], char *_arg_path, char *_arg_name ) { if (_festplatten == NULL ) return false; if ( buscar_id_partition ( _festplatten->partitionen, _id, _arg_path, _arg_name ) ) { strcpy ( _arg_path, _festplatten->ruta ); return true; } return buscar_id_festplatte ( _festplatten->siguiente, _id, _arg_path, _arg_name ); } static inline int buscar_id_partition ( partition *_partitionen, char _id[], char *_arg_path, char *_arg_name ) { if ( _partitionen == NULL ) return false; if ( strcmp ( _partitionen->id, _id ) == 0 ) { strcpy ( _arg_name, _partitionen->id ); return true; } return buscar_id_partition ( _partitionen->siguiente, _id, _arg_path, _arg_name ); } inline int desmontar_particion ( festplatte **_festplatten, char _id[] ) { return ( _festplatten == NULL ) ? false : desmontar_id_festplatte ( _festplatten, _id ); } static inline int desmontar_id_festplatte ( festplatte **_festplatten, char _id[] ) { if ( (*_festplatten) == NULL ) return false; if ( desmontar_id_partition ( &(*_festplatten)->partitionen, _id ) ) { if ( (*_festplatten)->partitionen == NULL ) { festplatte *temp = *_festplatten; (*_festplatten) = (*_festplatten)->siguiente; free ( temp ); } return true; } return desmontar_id_festplatte ( &(*_festplatten)->siguiente, _id ); } static inline int desmontar_id_partition ( partition **_partitionen, char _id[] ) { if ( _partitionen == NULL ) return false; if ( strcmp ( (*_partitionen)->id, _id ) == 0 ) { partition *temp = (* _partitionen); (*_partitionen) = (*_partitionen)->siguiente; printf( "\n\tSe Desmonto la partion <<%s>>, exitosamente.", temp->nombre ); free ( temp ); return true; } return desmontar_id_partition ( &(*_partitionen)->siguiente, _id ); } inline void imprimir_particiones_montadas ( festplatte *_festplatten ) { printf("\n"); printf("\n\t(Discos Montados:)"); if ( _festplatten == NULL ) { printf("\n\t (Lista Vacia)"); return; } imprimir_festplatten_montados ( _festplatten ); } static inline void imprimir_festplatten_montados ( festplatte *_festplatten ) { if ( _festplatten == NULL ) return; printf("\n\t (Disco (%d) : %s)", _festplatten->id, _festplatten->ruta ); imprimir_partitionen_montadas ( _festplatten->partitionen ); imprimir_festplatten_montados ( _festplatten->siguiente ); } static inline void imprimir_partitionen_montadas ( partition *_partitionen ) { if ( _partitionen == NULL ) return; printf("\n\t (Particion (%s) : %s)", _partitionen->id, _partitionen->nombre ); imprimir_partitionen_montadas ( _partitionen->siguiente ); } static inline festplatte *neu_festplatte ( char _arg_path[], int _numero ) { festplatte *neu = malloc ( sizeof( struct festplatte ) ); strcpy( neu->ruta, _arg_path ); neu->siguiente = NULL; neu->partitionen = NULL; neu->id = _numero; return neu; } static inline partition *neu_partition ( char _arg_name[], char _id[] ) { partition *neu = malloc ( sizeof( struct partition ) ); strcpy( neu->nombre, _arg_name ); strcpy( neu->id, _id ); neu->siguiente = NULL; return neu; } #endif // MONTAR_H<file_sep>/manejador_particiones_200925270.h //manejador_particiones_200925270.h #ifndef MANEJADOR_PARTICIONES_H #define MANEJADOR_PARTICIONES_H /* * * * */ inline void verificar_creacion_particion ( char [], char [], int, char, char ); static inline void crear_logica ( char [], char [], int, char, char ); static inline void crear_primaria_extendida ( char [], char [], int, char, char ); inline void verificar_eliminacion_particion ( char [], char [], char ); static inline void eliminar_primaria_extendida ( char [], char [], char ); static inline int eliminar_logica ( char [], char [], int, int ); inline void verificar_modificacion_particion ( char [], char [], int ); static inline void modificar_particion ( char [], char [], int ); //static inline int verificar_localidad_particion ( particion [] ); static inline int verificar_nombre_particion ( char [], particion [], char [] ); static inline int verificar_particion_extendida ( particion [] ); static inline int verificar_calcular_posicion_particion ( particion [], int, int, int ); /* * * * */ inline void verificar_creacion_particion ( char _arg_path[], char _arg_name[], int _arg_size, char _arg_type, char _arg_fit ) { if(DEPURADOR) printf("\n\t(Entrada Del Manejador de Particiones)"); printf("\n\tValidando Datos para la Creacion de la Particion."); if ( !existe_archivo ( _arg_path ) ) { printf( "\n\t[ERROR] : El archivo <<%s>> No exite.", _arg_path ); return; } if ( _arg_type == 'L' ) crear_logica ( _arg_path, _arg_name, _arg_size, _arg_type, _arg_fit ); else crear_primaria_extendida ( _arg_path, _arg_name, _arg_size, _arg_type, _arg_fit ); } inline void verificar_eliminacion_particion ( char _arg_path[], char _arg_name[], char _arg_type ) { if(DEPURADOR) printf("\n\t(Entrada Del Manejador de Particiones)"); printf("\n\tValidando Datos para la Eliminacion de la Particion."); if ( !existe_archivo ( _arg_path ) ) { printf( "\n\t[ERROR] : El archivo <<%s>> No exite.", _arg_path ); return; } eliminar_primaria_extendida ( _arg_path, _arg_name, _arg_type ); } inline void verificar_modificacion_particion ( char _arg_path[], char _arg_name[], int _arg_add ) { if(DEPURADOR) printf("\n\t(Entrada Del Manejador de Particiones)"); printf("\n\tValidando Datos para la Modificacion de la Particion."); if ( !existe_archivo ( _arg_path ) ) { printf( "\n\t[ERROR] : El archivo <<%s>> No exite.", _arg_path ); return; } modificar_particion ( _arg_path, _arg_name, _arg_add ); } static inline void modificar_particion ( char _arg_path[], char _arg_name[], int _arg_size ) { } static inline void crear_primaria_extendida ( char _arg_path[], char _arg_name[], int _arg_size, char _arg_type, char _arg_fit ) { master *mbr = recuperar_registro( _arg_path, sizeof( struct master ), 0 ); if ( _arg_size >= TAMANO_DISCO_MBR( mbr ) ) { printf( "\n\t[ERROR] : El Tamano de la Particion es Mayor al Tamano del Disco."); free ( mbr ); return; } if ( _arg_size < (2 * KiB) ) { printf( "\n\t[ERROR] : El Tamano Minimo de la Particion es de 2 KiB."); free ( mbr ); return; } if ( _arg_type == 'E' ) { if(DEPURADOR) printf("\n\t(Validando si ya hay una particion extentida.)"); if ( verificar_particion_extendida ( mbr->mbr_partition ) ) { printf( "\n\t[ERROR] : Ya Existe una Particion Extentida Asignada." ); free ( mbr ); return; } } if(DEPURADOR) printf("\n\t(Validando que no hay otra particion con el mismo nombre.)"); if ( verificar_nombre_particion ( _arg_path, mbr->mbr_partition, _arg_name ) ) { printf( "\n\t[ERROR] : Ya Existe una Particion con el nombre <<%s>>.", _arg_name ); free ( mbr ); return; } if(DEPURADOR) printf("\n\t(Validando la ubicacion y posicion de la particion.)"); int i = 0; int posicion_inicial = sizeof ( struct master ); for (; i < 4; ++i) { if(DEPURADOR) printf("\n\t(Particion: %d)", i); if(DEPURADOR) printf("\n\t(Posicion Inicial: %d)", posicion_inicial ); if ( ESTADO_PARTICION( mbr->mbr_partition[i] ) != '0' ) { posicion_inicial = POSICION_PARTICION( mbr->mbr_partition[i] ) + TAMANO_PARTICION( mbr->mbr_partition[i] ); continue; } int posicion_limite = verificar_calcular_posicion_particion ( mbr->mbr_partition, _arg_size, i + 1, TAMANO_DISCO_MBR( mbr ) ); if(DEPURADOR) printf("\n\t(Posicion Inicial + Tamano: %d)", (posicion_inicial + _arg_size) ); if(DEPURADOR) printf("\n\t(Posicion limite: %d)", posicion_limite); if ( posicion_inicial + _arg_size <= posicion_limite ) { if(DEPURADOR) printf("\n\t(Asignando la nueva particion.)"); POSICION_PARTICION ( mbr->mbr_partition[i] ) = posicion_inicial; strcpy( NOMBRE_PARTICION ( mbr->mbr_partition[i] ), _arg_name ); TIPO_AJUSTE_PARTICION ( mbr->mbr_partition[i] ) = _arg_fit; TAMANO_PARTICION ( mbr->mbr_partition[i] ) = _arg_size; TIPO_PARTICION ( mbr->mbr_partition[i] ) = _arg_type; ESTADO_PARTICION ( mbr->mbr_partition[i] ) = '1'; if ( _arg_type == 'E' ) { if(DEPURADOR) printf("\n\t(Asignando el EBR de la Particion Extendida.)"); extend *ebr = nuevo_extend_boot_record (); almacenar_registro_posicion_n ( _arg_path, ebr, sizeof( struct extend ), posicion_inicial ); free( ebr ); } almacenar_registro_posicion_n ( _arg_path, mbr, sizeof( struct master ), 0 ); free ( mbr ); return; } posicion_inicial = POSICION_PARTICION( mbr->mbr_partition[i] ) + TAMANO_PARTICION( mbr->mbr_partition[i] ); } printf( "\n\t[ERROR] : No Existe Suficiente Espacio para Asignar la Particion <<%s>>.", _arg_name ); free ( mbr ); } static inline void crear_logica ( char _arg_path[], char _arg_name[], int _arg_size, char _arg_type, char _arg_fit ) { master *mbr = recuperar_registro( _arg_path, sizeof( struct master ), 0 ); if ( _arg_size >= TAMANO_DISCO_MBR( mbr ) ) { printf( "\n\t[ERROR] : El Tamano de la Particion es Mayor al Tamano del Disco."); free ( mbr ); return; } if ( _arg_size < (2 * KiB) ) { printf( "\n\t[ERROR] : El Tamano Minimo de la Particion es de 2 KiB."); free ( mbr ); return; } if ( !verificar_particion_extendida ( mbr->mbr_partition ) ) { printf( "\n\t[ERROR] : No Existe una Particion Extentida Asignada." ); free ( mbr ); return; } int i = 0; for (; i < 4; ++i) if ( TIPO_PARTICION ( mbr->mbr_partition[i] ) == 'E' ) break; int posicion = POSICION_PARTICION ( mbr->mbr_partition[i] ); while ( posicion != -1 ) { extend *ebr = recuperar_registro ( _arg_path, sizeof( struct extend ), POSICION_PARTICION ( mbr->mbr_partition[i] ) ); if(DEPURADOR) printf("\n\t(Posicion EBR: %d)", posicion); if ( ESTADO_EBR( ebr ) != '0' ) { posicion = SIGUIENTE_EBR( ebr ); free ( ebr ); continue; } int posicion_inicial = posicion + sizeof ( struct extend ); int posicion_limite = POSICION_PARTICION ( mbr->mbr_partition[i] ) + TAMANO_PARTICION( mbr->mbr_partition[i] ); if(DEPURADOR) printf("\n\t(Posicion Inicial + Tamano + ebr: %d)", ( posicion_inicial + _arg_size + (int)(sizeof ( struct extend )) ) ); if(DEPURADOR) printf("\n\t(Posicion limite: %d)", posicion_limite); if ( ( posicion_inicial + _arg_size + sizeof ( struct extend ) ) > posicion_limite ) { free ( ebr ); break; } SIGUIENTE_EBR( ebr ) = posicion_inicial + _arg_size; POSICION_EBR( ebr ) = posicion_inicial; strcpy( NOMBRE_EBR( ebr ), _arg_name ); TAMANO_EBR( ebr ) = _arg_size; AJUSTE_EBR( ebr ) = _arg_fit; ESTADO_EBR( ebr ) = '1'; if(DEPURADOR) printf( "\n\t(Posicion EBR Siguiente: %d)", SIGUIENTE_EBR( ebr ) ); extend *ebr_sig = nuevo_extend_boot_record (); almacenar_registro_posicion_n ( _arg_path, ebr_sig, sizeof( struct extend ), SIGUIENTE_EBR( ebr ) ); free( ebr_sig ); almacenar_registro_posicion_n ( _arg_path, ebr, sizeof( struct extend ), posicion ); free ( ebr ); if(DEPURADOR) printf("\n\t(Asignando la nueva particion logica.)"); free ( mbr ); return; } printf( "\n\t[ERROR] : No Existe Suficiente Espacio para Asignar la Particion <<%s>>.", _arg_name ); free ( mbr ); } static inline void eliminar_primaria_extendida ( char _arg_path[], char _arg_name[], char _arg_type ) { master *mbr = recuperar_registro( _arg_path, sizeof( struct master ), 0 ); if(DEPURADOR) printf("\n\t(Validando que haya una particion con el nombre indicado.)"); int i = 0; for (; i < 4; ++i) { if ( strcmp ( NOMBRE_PARTICION( mbr->mbr_partition[i] ), _arg_name ) == 0 ) { if(DEPURADOR) printf("\n\t(Borrando Datos de la particion.)"); if ( _arg_type == 'C' ) { if(DEPURADOR) printf("\n\t(Buscar la posicion y agregar los bloques.(PENDIENTE))"); } strcpy( NOMBRE_PARTICION ( mbr->mbr_partition[i] ), "" ); TIPO_AJUSTE_PARTICION ( mbr->mbr_partition[i] ) = '0'; POSICION_PARTICION ( mbr->mbr_partition[i] ) = 0; ESTADO_PARTICION ( mbr->mbr_partition[i] ) = '0'; TAMANO_PARTICION ( mbr->mbr_partition[i] ) = 0; TIPO_PARTICION ( mbr->mbr_partition[i] ) = '0'; almacenar_registro_posicion_n ( _arg_path, mbr, sizeof( struct master ), 0 ); free ( mbr ); return; } if ( TIPO_PARTICION ( mbr->mbr_partition[i] ) == 'E' ) { if( eliminar_logica ( _arg_path, _arg_name, 0, POSICION_PARTICION ( mbr->mbr_partition[i] ) ) ) { free ( mbr ); return; } } } printf( "\n\t[ERROR] : No Existe la Particion con el nombre <<%s>>.", _arg_name ); free ( mbr ); } static inline int eliminar_logica ( char _arg_path[], char _arg_name[], int _indice, int _arg_pos ) { // if ( _arg_pos == -1 ) // return false; // extend *ebr = recuperar_registro( _arg_path, sizeof( struct extend ), _arg_pos ); // if ( strcmp( NOMBRE_EBR( ebr ), _arg_name ) == 0 ) // { // // preguntar si desea eliminar la particion... // printf(" La particion <<%s>>, ha sido eliminada exitosamente.\n", _arg_name ); // _arg_pos = SIGUIENTE_EBR ( ebr ); // } // else // { // eliminar_logica ( _arg_path, _arg_name, SIGUIENTE_EBR( ebr ) ); // almacenar_registro_posicion_n ( _arg_path, ebr, sizeof( struct extend ), _arg_pos ); // } // free ( ebr ); } static inline int verificar_nombre_particion ( char _arg_path[], particion _particion[], char _arg_name[] ) { int i = 0; for ( ; i < 4; ++i ) { if ( strcmp ( NOMBRE_PARTICION( _particion[i] ), _arg_name ) == 0 ) return true; if ( TIPO_PARTICION( _particion[i]) == 'E' ) { int posicion = POSICION_PARTICION ( _particion[i] ); while ( posicion != -1 ) { extend *ebr = recuperar_registro ( _arg_path, sizeof( struct extend ), POSICION_PARTICION ( _particion[i] ) ); if ( strcmp ( NOMBRE_EBR( ebr ), _arg_name ) == 0 ) { free ( ebr ); return true; } posicion = SIGUIENTE_EBR( ebr ); free ( ebr ); } } } return false; } static inline int verificar_particion_extendida ( particion _particion[] ) { int i = 0; for ( ; i < 4; ++i ) if ( TIPO_PARTICION( _particion[i] ) == 'E' ) return true; return false; } static inline int verificar_calcular_posicion_particion ( particion _particion[], int _arg_size, int _posicion, int _size_disk ) { int i = _posicion; for ( ; i < 4; ++i ) { if ( ESTADO_PARTICION( _particion[i] ) != '0' ) return POSICION_PARTICION( _particion[i] ); } return _size_disk; } #endif // MANEJADOR_PARTICIONES_H<file_sep>/librerias_200925270.h //librerias_200925270.h #ifndef LIBRERIA_H #define LIBRERIA_H /* * * * */ #define true 1 #define false 0 #define KiB 1024 #define MiB 1024*KiB #define DEPURADOR false #define ERROR -1 #define COMENTARIO -2 /* * * * */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <time.h> #include <sys/types.h> #include <dirent.h> #include <stdarg.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> /* * * * */ #include "io_200925270.h" #include "funciones_200925270.h" #include "parametro_200925270.h" #include "instruccion_200925270.h" #include "ebr_200925270.h" #include "particion_200925270.h" #include "mbr_200925270.h" #include "manejador_particiones_200925270.h" #include "administrador_particiones_200925270.h" #include "montar_200925270.h" #include "unidad_disco_200925270.h" #include "manejador_disco_200925270.h" #include "administrador_disco_200925270.h" #include "manejador_reportes_200925270.h" #include "administrador_reporte_200925270.h" #include "buffer_entrada_200925270.h" #include "analizador_200925270.h" #include "interprete_200925270.h" /* * * * */ #endif // LIBRERIA_H<file_sep>/buffer_entrada_200925270.h //buffer_entrada_200925270.h #ifndef BUFFER_ENTRADA_H #define BUFFER_ENTRADA_H /* * * * */ inline int leer_entrada_consola ( char * ); static inline int validar_final_linea ( char [] ); /* * * * */ inline int leer_entrada_consola ( char *_cadena ) { char entrada[256] = ""; leer_entrada_formato_cadena( entrada, "\t > " ); int longitud = strlen( entrada ); while ( validar_final_linea ( entrada ) && longitud < 256 ) { char buffer[164]; leer_entrada_formato_cadena( buffer, "\t " ); longitud += strlen ( buffer ) + 1; if( longitud < 255 ) concatenar ( entrada, 1, buffer ); else return false; } if(DEPURADOR) printf("\n\t(Salida Del Buffer: %s)", entrada); strcpy( _cadena, entrada ); return true; } inline int validar_final_linea ( char _cadena[] ) { int longitud = strlen ( _cadena ); --longitud; while ( longitud != 0 ) { switch(_cadena[longitud]) { case '\n': case ' ': { --longitud; } break; case '\\': { _cadena[longitud] = ' '; return true; } default: { return false; } } } return false; } #endif // BUFFER_ENTRADA_H<file_sep>/administrador_disco_200925270.h //administrador_disco_200925270.h #ifndef ADMINISTRADOR_DISCO_H #define ADMINISTRADOR_DISCO_H /* * * * */ inline void validar_eliminacion_disco ( parametro **, parametro ** ); inline void validar_desmontar_disco ( parametro **, parametro ** ); inline void validar_creacion_disco ( parametro **, parametro ** ); inline void validar_montar_disco ( parametro **, parametro ** ); /* * * * */ inline void validar_creacion_disco ( parametro **_parametros, parametro **_errores ) { if(DEPURADOR) printf("\n\t(Entrada Del Administrador de Disco)"); printf("\n\tValidando Parametros Para la creacion de Disco."); parametro *errores = NULL; if( cantidad_parametros ( (*_parametros) ) == 0 ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : Debe de ingresar al menos un parametro." ); } /* * ARGUMENTO PATH OBLIGATORIO */ char arg_path[128] = ""; if ( !buscar_parametro ( _parametros, PATH, arg_path ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : No existe el parametro <<path>>" ); } if(DEPURADOR) printf("\n\t(Buscando parametro: PATH)"); /* * ARGUMENTO SIZE OBLIGATORIO */ char arg_size[5] = ""; if ( !buscar_parametro ( _parametros, SIZE, arg_size ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : No existe el parametro <<size>>" ); } int valor_arg = 0; if ( !validar_convertir_decimal ( &valor_arg, arg_size ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : El valor del paramatro <<size>>, no es numerico." ); } if( valor_arg <= 0) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : El valor del paramatro <<size>>, debe ser mayor a cero." ); } if(DEPURADOR) printf("\n\t(Buscando parametro: SIZE)"); /* * ARGUMENTO UNIT OPCIONAL */ int arg_unit_ = MiB; char arg_unit[3] = ""; if ( buscar_parametro ( _parametros, UNIT, arg_unit ) ) { switch(arg_unit[0]) { case 'm': { arg_unit_ = MiB; } break; case 'k': { arg_unit_ = KiB; } break; default: { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : El valor del paramatro <<unit>>, debe ser <<k>> o <<m>>." ); } break; } } if(DEPURADOR) printf("\n\t(Buscando parametro: UNIT)"); if( cantidad_parametros ( errores ) > 0 ) { (*_errores) = errores; return; } if( cantidad_parametros ( (*_parametros) ) > 0 ) { return; } if(DEPURADOR) printf("\n\t(Si cumple con todos los requisitos para crear un Disco)"); verificar_creacion_disco_virtual ( arg_path, valor_arg, arg_unit_ ); } inline void validar_eliminacion_disco ( parametro **_parametros, parametro **_errores ) { if(DEPURADOR) printf("\n\t(Entrada Del Administrador de Disco)"); printf("\n\tValidando Parametros Para la eliminacion de Disco."); parametro *errores = NULL; if( cantidad_parametros ( (*_parametros) ) == 0 ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : Debe de ingresar al menos un parametro." ); } /* * ARGUMENTO PATH OBLIGATORIO */ char arg_path[128] = ""; if ( !buscar_parametro ( _parametros, PATH, arg_path ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : No existe el parametro <<path>>" ); } if(DEPURADOR) printf("\n\t(Buscando parametro: PATH)"); if( cantidad_parametros ( errores ) > 0 ) { (*_errores) = errores; return; } if( cantidad_parametros ( (*_parametros) ) > 0 ) { return; } if(DEPURADOR) printf("\n\t(Si cumple con todos los requisitos para eliminar un Disco)"); verificar_eliminacion_disco_virtual ( arg_path ); } inline void validar_montar_disco ( parametro **_parametros, parametro **_errores ) { if(DEPURADOR) printf("\n\t(Entrada Del Administrador de Disco)"); printf("\n\tValidando Parametros Para montar particion."); parametro *errores = NULL; if( cantidad_parametros ( (*_parametros) ) == 0 ) { imprimir_particiones_montadas ( festplatten ); return; } /* * ARGUMENTO PATH OBLIGATORIO */ char arg_path[128] = ""; if ( !buscar_parametro ( _parametros, PATH, arg_path ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : No existe el parametro <<path>>" ); } if(DEPURADOR) printf("\n\t(Buscando parametro: PATH)"); /* * ARGUMENTO NAME OBLIGATORIO */ char arg_name[32] = ""; if ( !buscar_parametro ( _parametros, NAME, arg_name ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : No existe el parametro <<name>>" ); } if(DEPURADOR) printf("\n\t(Buscando parametro: NAME)"); if( cantidad_parametros ( errores ) > 0 ) { (*_errores) = errores; return; } if( cantidad_parametros ( (*_parametros) ) > 0 ) { return; } if(DEPURADOR) printf("\n\t(Si cumple con todos los requisitos para montar una Particion)"); verificar_montar_disco ( arg_path, arg_name ); } inline void validar_desmontar_disco ( parametro **_parametros, parametro **_errores ) { if(DEPURADOR) printf("\n\t(Entrada Del Administrador de Disco)"); printf("\n\tValidando Parametros Para desmontar particion."); parametro *errores = NULL; if( cantidad_parametros ( (*_parametros) ) == 0 ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : Debe de ingresar al menos un parametro." ); } /* * ARGUMENTO ID OBLIGATORIO */ char arg_id[12] = ""; if ( !buscar_parametro ( _parametros, ID, arg_id ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : No existe el parametro <<id>>" ); } if(DEPURADOR) printf("\n\t(Buscando parametro: PATH)"); if( cantidad_parametros ( errores ) > 0 ) { (*_errores) = errores; return; } if( cantidad_parametros ( (*_parametros) ) > 0 ) { return; } if(DEPURADOR) printf("\n\t(Si cumple con todos los requisitos para desmontar una Particion)"); verificar_desmontar_disco ( arg_id ); } #endif // ADMINISTRADOR_DISCO_H<file_sep>/parametro_200925270.h //parametro_200925270.h #ifndef PARAMETRO_H #define PARAMETRO_H struct parametro { struct parametro *siguiente; char valor[128]; int tipo; }; typedef struct parametro parametro; enum TIPO_PARAMETRO { SIZE = 0, UNIT, PATH, NAME, TYPE, FIT, DELETE, ADD, ID, K, M, H, I, N, S, LINK }; typedef enum TIPO_PARAMETRO TIPO_PARAMETRO; /* * * * */ void agregar_parametro ( parametro **, int, char [] ); inline void insertar_parametro ( parametro **, parametro * ); int cantidad_parametros ( parametro * ); int buscar_parametro ( parametro **, int, char * ); inline parametro *nuevo_parametro ( int, char [] ); static inline int obtener_parametro ( parametro **, char * ); inline void imprimir_parametros ( parametro * ); static inline void imprimir_lista_parametros ( parametro * ); /* * * * */ void agregar_parametro ( parametro **_lista, int _tipo, char _valor[] ) { insertar_parametro ( _lista, nuevo_parametro ( _tipo, _valor ) ); } inline void insertar_parametro ( parametro **_lista, parametro *_parametro ) { ( (*_lista) == NULL ) ? (*_lista) = _parametro : insertar_parametro ( &(*_lista)->siguiente, _parametro ); } int cantidad_parametros ( parametro *_lista ) { return ( _lista == NULL ) ? 0 : 1 + cantidad_parametros ( _lista->siguiente ); } int buscar_parametro ( parametro **_lista, int _tipo, char *_buffer ) { return ( *_lista == NULL ) ? 0 : ( (*_lista)->tipo == _tipo ) ? obtener_parametro ( _lista, _buffer ) : buscar_parametro ( &(*_lista)->siguiente, _tipo, _buffer ); } inline void imprimir_parametros ( parametro *_lista ) { //printf("\n\t(Parametros:)"); if ( _lista == NULL ) { printf("\n\t (Lista Vacia)"); return; } imprimir_lista_parametros ( _lista ); } static inline void imprimir_lista_parametros ( parametro *_lista ) { if (_lista == NULL) return; printf("\n\t (Parametro -> tipo: %d, valor: %s)", _lista->tipo, _lista->valor ); imprimir_lista_parametros ( _lista->siguiente ); } inline parametro *nuevo_parametro ( int _tipo, char _valor[] ) { parametro *nuevo = malloc ( sizeof( struct parametro ) ); strcpy( nuevo->valor, _valor ); nuevo->siguiente = NULL; nuevo->tipo = _tipo; return nuevo; } static inline int obtener_parametro ( parametro **_lista, char *_buffer ) { parametro *eliminar = (*_lista); strcpy ( _buffer, (*_lista)->valor ); (*_lista) = (*_lista)->siguiente; free ( eliminar ); return true; } #endif // PARAMETRO_H<file_sep>/interprete_200925270.h //interprete_200925270.h #ifndef INTERPRETE_H #define INTERPRETE_H /* * * * */ inline int ejecutar_instrucciones ( accion ** ); inline void validar_ejecucion_archivo ( parametro **, parametro ** ); static inline void verificar_ejecucion_archivo ( char [] ); static inline void ejecutar_archivo_entrada ( FILE ** ); /* * * * */ inline int ejecutar_instrucciones ( accion **_instrucciones ) { accion *instrucciones = (*_instrucciones); if ( instrucciones == NULL ) return true; if(DEPURADOR) printf("\n\t(Entrada Del Interprete)"); printf("\n\tValidando Instruccion a Ejecutar."); parametro *errores = NULL; switch (instrucciones->tipo) { case MKDISK: { //mKdisk -path::"/home/wxqzsvtyk/Plantillas/disk.dk" -size::6 +unit::M validar_creacion_disco ( &(*_instrucciones)->parametros, &errores ); } break; case RMDISK: { // RmDisk -path::"/home/wxqzsvtyk/Plantillas/disk.dk" validar_eliminacion_disco ( &(*_instrucciones)->parametros, &errores ); } break; case FDISK: { // fdisk –Size::512 –path::"/home/wxqzsvtyk/Plantillas/disk.dk" –name::"Particion5" +unit::w +type::l // fdisk –delete::fast –path::"/home/wxqzsvtyk/Plantillas/disk.dk" –name::"Particion3" validar_accion_particion ( &(*_instrucciones)->parametros, &errores ); } break; case MOUNT: { // mount -y::z –path::"/home/wxqzsvtyk/Plantillas/disk.dk" –name::"Particion1" // mount –path::"/home/wxqzsvtyk/Plantillas/disk.dk" –name::"Particion7" validar_montar_disco ( &(*_instrucciones)->parametros, &errores ); } break; case UNMOUNT: { // unmount -id::vda1 validar_desmontar_disco ( &(*_instrucciones)->parametros, &errores ); } break; case REP: { // rep -id::vda1 –path::"/home/wxqzsvtyk/Plantillas/mbr" -name::mbr // rep -id::vda1 –path::"/home/wxqzsvtyk/Plantillas/mbr.png" -name::disk validar_creacion_reportes ( &(*_instrucciones)->parametros, &errores ); } break; case EXEC: { // exec -path::"/home/wxqzsvtyk/Plantillas/ArchivoScript.txt" validar_ejecucion_archivo ( &(*_instrucciones)->parametros, &errores ); } break; case COMENTARIO: { return true; } break; case EXIT: { printf("\n\tSaliendo del Programa."); return false; } break; default: { } break; } if ( errores != NULL ) { printf("\n\t(ERRORES ENCONTRADOS:)"); imprimir_parametros ( errores ); } printf("\n"); if ( instrucciones->parametros != NULL ) { printf("\n\t(LOS SIGUIENTES PARAMETROS NO SE RECONOCIERON:)"); imprimir_parametros ( instrucciones->parametros ); } return true; } inline void validar_ejecucion_archivo ( parametro **_parametros, parametro **_errores ) { if(DEPURADOR) printf("\n\t(Entrada Del Administrador de Archivos)"); printf("\n\tValidando Parametros para la ejecucion del Archivo."); parametro *errores = NULL; if( cantidad_parametros ( (*_parametros) ) == 0 ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : Debe de ingresar al menos un parametro." ); } /* * ARGUMENTO PATH OBLIGATORIO */ char arg_path[128] = ""; if ( !buscar_parametro ( _parametros, PATH, arg_path ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : No existe el parametro <<path>>" ); } if( cantidad_parametros ( errores ) > 0 ) { (*_errores) = errores; return; } if( cantidad_parametros ( (*_parametros) ) > 0 ) { return; } if(DEPURADOR) printf("\n\t(Si cumple con todos los requisitos para crear un Disco)"); verificar_ejecucion_archivo( arg_path ); } static inline void verificar_ejecucion_archivo ( char _arg_path[] ) { if(DEPURADOR) printf("\n\t(Entrada al Manejador de Archivos)"); printf( "\n\tValidando Datos para la ejecucion del Archivo." ); if ( !existe_archivo ( _arg_path ) ) { printf( "\n\t[ERROR] : El archivo <<%s>> No exite.", _arg_path ); return; } FILE *archivo_script = fopen ( _arg_path, "r" ); if(!archivo_script) { printf( "\n\t[ERROR] : El archivo <<%s>> No tiene permisos de lectura.\n", _arg_path ); return; } printf( "\n\tIniciando Lectura del Archivo <<%s>>.\n", _arg_path ); ejecutar_archivo_entrada ( &archivo_script ); printf( "\n\tFinalizando Lectura del Archivo <<%s>>.\n", _arg_path ); fclose (archivo_script); } static inline void ejecutar_archivo_entrada ( FILE **_archivo ) { int numero_linea = 0; char buffer[128] = ""; char cadena[256] = ""; int longitud = 0; while ( fgets ( buffer, sizeof(buffer), *_archivo ) ) { accion *lista = NULL; longitud = strlen( cadena ); if ( validar_final_linea ( buffer ) ) { longitud += strlen ( buffer ) + 1; if( longitud < 255 ) { concatenar ( cadena, 1, buffer ); } else { printf( "\n\t[ERROR] : La cadena es demasiado grande para procesar." ); } continue; } else { longitud += strlen ( buffer ) + 1; if( longitud < 255 ) { concatenar ( cadena, 1, buffer ); } else { printf( "\n\t[ERROR] : La cadena es demasiado grande para procesar." ); continue; } } analizar_entrada ( cadena, &lista ); ejecutar_instrucciones ( &lista ); strcpy ( cadena, "" ); } } #endif // INTERPRETE_H<file_sep>/instruccion_200925270.h //instruccion_200925270.h #ifndef INSTRUCCION_H #define INSTRUCCION_H struct accion { struct parametro *parametros; struct accion *siguiente; int tipo; }; typedef struct accion accion; enum TIPO_ACCION { MKDISK = 0, RMDISK, EXEC, FDISK, MOUNT, UNMOUNT, REP, EXIT }; typedef enum TIPO_ACCION TIPO_ACCION; /* * * * */ void agregar_accion ( accion **, int ); void agregar_instruccion ( accion **, int, parametro ** ); inline void insertar_instruccion ( accion **, accion * ); inline accion *obtener_siguiente_instruccion ( accion ** ); static inline accion *pop_instruccion ( accion ** ); static inline accion *nueva_instruccion ( int, parametro ** ); inline int cantidad_instrucciones ( accion * ); static inline accion *nueva_accion ( int ); inline void imprimir_instrucciones ( accion * ); static inline void imprimir_lista_instrucciones ( accion * ); /* * * * */ void agregar_instruccion ( accion **_lista, int _tipo, parametro **_lista_parametros ) { insertar_instruccion ( _lista, nueva_instruccion ( _tipo, _lista_parametros ) ); } void agregar_accion ( accion **_lista, int _tipo ) { insertar_instruccion ( _lista, nueva_accion ( _tipo ) ); } inline void insertar_instruccion ( accion **_lista, accion *_instruccion ) { ( (*_lista) == NULL ) ? (*_lista) = _instruccion : insertar_instruccion ( &(*_lista)->siguiente, _instruccion ); } inline accion *obtener_siguiente_instruccion ( accion **_lista ) { return ( *_lista == NULL ) ? NULL : pop_instruccion ( _lista ); } static inline accion *pop_instruccion ( accion **_lista ) { accion *temp = *_lista; (*_lista) = (*_lista)->siguiente; return temp; } inline void imprimir_instrucciones ( accion *_lista ) { printf("\n"); printf("\n\t(Instrucciones:)"); if ( _lista == NULL ) { printf("\n\t (Lista Vacia)"); return; } imprimir_lista_instrucciones ( _lista ); printf("\n"); } static inline void imprimir_lista_instrucciones ( accion *_lista ) { if (_lista == NULL) return; printf("\n\t (Instruccion -> tipo: %d)", _lista->tipo ); imprimir_lista_parametros ( _lista->parametros ); imprimir_lista_instrucciones ( _lista->siguiente ); } inline int cantidad_instrucciones ( accion *_lista ) { return ( _lista == NULL ) ? 0 : 1 + cantidad_instrucciones ( _lista->siguiente ); } inline accion *nueva_accion ( int _tipo ) { accion *nueva = malloc ( sizeof( struct accion ) ); nueva->parametros = NULL; nueva->siguiente = NULL; nueva->tipo = _tipo; return nueva; } inline accion *nueva_instruccion ( int _tipo, parametro **_lista ) { accion *nueva = malloc ( sizeof( struct accion ) ); nueva->parametros = (*_lista); nueva->siguiente = NULL; nueva->tipo = _tipo; return nueva; } #endif // INSTRUCCION_H<file_sep>/manejador_reportes_200925270.h //manejador_reportes_200925270.h #ifndef MANEJADOR_REPORTES_H #define MANEJADOR_REPORTES_H /* * * * */ inline void verificar_creacion_particion ( char [], char [], int, char, char ); /* * * * */ inline void verificar_creacion_reporte ( char _arg_file[], int _arg_name, char _arg_id[] ) { printf("\n\tValidando Datos para la Creacion de Reportes."); char arg_path[32] = ""; char arg_name[32] = ""; if ( !buscar_id ( festplatten, _arg_id, arg_path, arg_name ) ) { printf( "\n\t[ERROR] : Error no existe el disco o la particion a montar."); return; } if ( !existe_archivo ( arg_path ) ) { printf( "\n\t[ERROR] : El archivo <<%s>> No exite.", arg_path ); return; } switch(_arg_name) { case 1: { crear_reporte_mbr ( arg_path ); int estado; char ejecutar[256] = ""; concatenar ( ejecutar, 3, "dot -Tpng mbr.dot -o ", _arg_file, ".png" ); system( ejecutar ); wait(estado); } break; case 2: { crear_reporte_disk ( arg_path ); int estado; char ejecutar[256] = ""; concatenar ( ejecutar, 3, "dot -Tpng disk.dot -o ", _arg_file, ".png" ); system( ejecutar ); wait(estado); } break; default: { } break; } } #endif // MANEJADOR_REPORTES_H<file_sep>/main_200925270.c //main_200925270.c #include "librerias_200925270.h" /* * * * */ festplatte *festplatten; static inline void ciclo_programa (); /* * * * */ int main ( int argc, char **argv ) { ciclo_programa (); return 0; } static inline void ciclo_programa () { int opcion = 1; festplatten = NULL; do { printf("\n"); char cadena[256]; accion *lista = NULL; if( !leer_entrada_consola ( cadena ) ) { printf("\n\t Error: La cadena es demasiado grande para procesar."); continue; } analizar_entrada ( cadena, &lista ); opcion = ejecutar_instrucciones ( &lista ); } while (opcion != 0); printf("\n"); }<file_sep>/io_200925270.h //io_200925270.h #ifndef IO_H #define IO_H void almacenar_registro_posicion_n ( char [], void *, int, int ); void almacenar_registro_posicion_final ( char [], void *, int ); void almacenar_registro( char [], void *, int, int ); void *recuperar_registro( char [], int, int ); static inline void escribir_registro_posicion ( FILE **, void *, int, int ); static inline void escribir_registro_final ( FILE **, void *, int ); static inline void *leer_registro ( FILE **, int, int ); /* * * * */ void almacenar_registro_posicion_final ( char _ruta_disco[], void *_objeto, int _tamano ) { FILE *discoVirtual = fopen ( _ruta_disco, "ab" ); if (!discoVirtual) { return; } escribir_registro_final ( &discoVirtual, _objeto, _tamano ); fclose( discoVirtual ); } void almacenar_registro_posicion_n ( char _ruta_disco[], void *_objeto, int _tamano, int _posicion ) { FILE *discoVirtual = fopen ( _ruta_disco, "r+b" ); if (!discoVirtual) { return; } escribir_registro_posicion ( &discoVirtual, _objeto, _tamano, _posicion ); fclose( discoVirtual ); } void *recuperar_registro( char _ruta_disco[], int _tamano, int _posicion ) { FILE *discoVirtual = fopen ( _ruta_disco, "rb" ); if (!discoVirtual) { return NULL; } void *registro = leer_registro ( &discoVirtual, _tamano, _posicion ); fclose( discoVirtual ); return registro; } static inline void escribir_registro_final ( FILE **_discoVirtual, void *_objeto, int _tamano ) { fseek ( *_discoVirtual, 0, SEEK_END ); fwrite ( _objeto, _tamano, 1, *_discoVirtual ); } static inline void escribir_registro_posicion ( FILE **_discoVirtual, void *_objeto, int _tamano, int _posicion ) { fseek ( *_discoVirtual, _posicion, SEEK_SET ); fwrite ( _objeto, _tamano, 1, *_discoVirtual ); } static inline void *leer_registro ( FILE **_discoVirtual, int _tamano, int _posicion ) { void *registro = malloc( _tamano ); fseek ( *_discoVirtual, _posicion, SEEK_SET ); fread( registro, _tamano, 1, *_discoVirtual ); return registro; } #endif // IO_H<file_sep>/administrador_particiones_200925270.h //administrador_particiones_200925270.h #ifndef ADMINISTRADOR_PARTICIONES_H #define ADMINISTRADOR_PARTICIONES_H /* * * * */ inline void validar_accion_particion ( parametro **, parametro ** ); /* * * * */ inline void validar_accion_particion ( parametro **_parametros, parametro **_errores ) { if(DEPURADOR) printf("\n\t(Entrada Del Administrador de Particion)"); printf("\n\tValidando Parametros para la intruccion de Particion."); parametro *errores = NULL; if( cantidad_parametros ( (*_parametros) ) == 0 ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : Debe de ingresar al menos un parametro." ); } /* * ARGUMENTO PATH OBLIGATORIO */ char arg_path[128] = ""; if ( !buscar_parametro ( _parametros, PATH, arg_path ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : No existe el parametro <<path>>" ); } if(DEPURADOR) printf("\n\t(Buscando parametro: PATH)"); /* * ARGUMENTO NAME OBLIGATORIO */ char arg_name[32] = ""; if ( !buscar_parametro ( _parametros, NAME, arg_name ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : No existe el parametro <<name>>" ); } if(DEPURADOR) printf("\n\t(Buscando parametro: NAME)"); /* * ARGUMENTO DELETE OPCIONAL */ char arg_delete_ = '0'; char arg_delete[8] = ""; if ( buscar_parametro ( _parametros, DELETE, arg_delete ) ) { (strcmp(arg_delete, "fast") == 0) ? arg_delete_ = 'R' : (strcmp(arg_delete, "full") == 0) ? arg_delete_ = 'C' : agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : El valor del paramatro <<delete>>, debe ser <<fast>> o <<full>>." ); if(DEPURADOR) printf("\n\t(Buscando parametro: DELETE)"); if( cantidad_parametros ( errores ) > 0 ) { (*_errores) = errores; return; } if( cantidad_parametros ( (*_parametros) ) > 0 ) { return; } if(DEPURADOR) printf("\n\t(Si cumple con todos los requisitos para eliminar una Particion)"); verificar_eliminacion_particion ( arg_path, arg_name, arg_delete_ ); if(DEPURADOR) imprimir_mbr ( arg_path ); return; } /* * ARGUMENTO UNIT OPCIONAL */ int arg_unit_ = KiB; char arg_unit[3] = ""; if ( buscar_parametro ( _parametros, UNIT, arg_unit ) ) { switch(arg_unit[0]) { case 'm': { arg_unit_ = MiB; } break; case 'k': { arg_unit_ = KiB; } break; case 'b': { arg_unit_ = 1; } break; default: { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : El valor del paramatro <<unit>>, debe ser <<k>>, <<m>> o <<b>>." ); } break; } } if(DEPURADOR) printf("\n\t(Buscando parametro: UNIT)"); /* * ARGUMENTO ADD OPCIONAL */ char arg_add[8] = ""; if ( buscar_parametro ( _parametros, ADD, arg_add ) ) { int valor_arg = 0; if (! validar_convertir_decimal ( &valor_arg, arg_add ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : El valor del paramatro <<add>>, no es numerico." ); } if(DEPURADOR) printf("\n\t(Buscando parametro: ADD)"); if( cantidad_parametros ( errores ) > 0 ) { (*_errores) = errores; return; } if( cantidad_parametros ( (*_parametros) ) > 0 ) { return; } if(DEPURADOR) printf("\n\t(Si cumple con todos los requisitos para modificar una Particion)"); // llamar al controlador del particiones... if(DEPURADOR) imprimir_mbr ( arg_path ); return; } /* * ARGUMENTO SIZE OBLIGATORIO */ char arg_size[5] = ""; if ( !buscar_parametro ( _parametros, SIZE, arg_size ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : No existe el parametro <<size>>" ); } if(DEPURADOR) printf("\n\t(Buscando parametro: SIZE)"); int valor_arg = 0; if (! validar_convertir_decimal ( &valor_arg, arg_size ) ) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : El valor del paramatro <<size>>, no es numerico." ); } if( valor_arg <= 0) { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : El valor del paramatro <<size>>, debe ser mayor a cero." ); } /* * ARGUMENTO FIT OPCIONAL */ char arg_fit_ = 'f'; char arg_fit[3] = ""; if ( buscar_parametro ( _parametros, FIT, arg_fit ) ) { (strcmp(arg_fit, "bf") == 0) ? arg_fit_ = 'b' : (strcmp(arg_fit, "ff") == 0) ? arg_fit_ = 'f' : (strcmp(arg_fit, "wf") == 0) ? arg_fit_ = 'w' : agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : El valor del paramatro <<fit>>, debe ser <<bf>>, <<ff>> o <<wf>>." ); } if(DEPURADOR) printf("\n\t(Buscando parametro: FIT)"); /* * ARGUMENTO TYPE OPCIONAL */ char arg_type_ = 'P'; char arg_type[3] = ""; if ( buscar_parametro ( _parametros, TYPE, arg_type ) ) { switch(arg_type[0]) { case 'p': { arg_type_ = 'P'; } break; case 'e': { arg_type_ = 'E'; } break; case 'l': { arg_type_ = 'L'; } break; default: { agregar_parametro ( &errores, ERROR, "\n\t[ERROR] : El valor del paramatro <<type>>, debe ser <<p>>, <<e>> o <<l>>." ); } break; } } if(DEPURADOR) printf("\n\t(Buscando parametro: TYPE)"); if( cantidad_parametros ( errores ) > 0 ) { (*_errores) = errores; return; } if( cantidad_parametros ( (*_parametros) ) > 0 ) { return; } if(DEPURADOR) printf("\n\t(Si cumple con todos los requisitos para crear una Particion)"); verificar_creacion_particion ( arg_path, arg_name, valor_arg*arg_unit_, arg_type_, arg_fit_ ); if(DEPURADOR) imprimir_mbr ( arg_path ); } #endif // ADMINISTRADOR_PARTICIONES_H
55fa2f4fc5a1ddc9309038a09eb07c25dc8f7a0e
[ "C" ]
20
C
StN-/Proyecto1_200925270
bab12128c5b2bb3c913c84c2c6d5c046df92abe2
ee22c947467eb920434240951e6af9260d6d9340
refs/heads/master
<file_sep>import {React,useState,useEffect} from 'react' import './ApartmentRent.css' import ReactPaginate from 'react-paginate' const HometownRent = () => { const [data, setData] = useState([]) useEffect(() => { fetch('/real-estate/get-by-category/townhouses_for_rent', { }).then(res => res.json()) .then(result => { setData(result) }) }, []) const [pageNumber, setPageNumber] = useState(0) const datasPerPage = 15 const pagesVisited = pageNumber * datasPerPage const displayDatas = data.slice(pagesVisited, pagesVisited + datasPerPage) const pageCount = Math.ceil(data.length / datasPerPage) const changePage = ({selected}) => { setPageNumber(selected) } return ( <main> <section className="hogi-search-bar"> <div className="main-form"> <div className="form-group form-search-box"> <div className="form-select"> <select className="form-control"> <option value="ForRent">Cho thuê</option> <option value="ForBuy">Mua Bán</option> </select> </div> <div className="form-search"> <input className="form-control" type="text" autoComplete="off" placeholder="Từ khóa, địa chỉ, quận,..." ></input> <button className="btn btn-primary"> <em className="fa fa-search"></em> </button> </div> </div> <div className="property-location-filter search-dropdown"> <div className="btn-group dropdown" auto-close="outsideClick"> <button type="button" className="btn btn-search-dropdown"> <i className="fa fa-map-marker"></i> <span>Toàn quốc</span> <i className="fa fa-chevron-down"></i> </button> </div> </div> <div className="property-type-filter search-dropdown"> <div className="btn-group dropdown" auto-close="outsideClick"> <button type="button" className="btn btn-search-dropdown"> <i className="fa fa-home"></i> <span>Loại bất động sản</span> <i className="fa fa-chevron-down"></i> </button> </div> </div> <div className="property-price-filter search-dropdown"> <div className="btn-group dropdown" auto-close="outsideClick"> <button type="button" className="btn btn-search-dropdown"> <i className="fa fa-usd"></i> <span>Giá bán</span> <i className="fa fa-chevron-down"></i> </button> </div> </div> </div> </section> <section className="hogi-ds-bds main-section"> <div className="container"> <div className="breadcrumb-scroll"> <ul className="breadcrumb clearfix"> <li className="breadcrumb-item"> <a>Hogi</a> </li> <li className="breadcrumb-item"> <i className="fa fa-chevron-right"></i> <a>Nhà phố</a> </li> </ul> </div> <div className="head-ds-bds"> <h2 className="title">Cho Thuê Nhà Phố</h2> <div className="apartment-number"> <p> <span> {data.length} bất động sản </span> </p> </div> </div> <div className="body-ds-bds"> { displayDatas.map(item => { return ( <div className="col-sm-6 col-lg-4"> <div className="apartment-item"> <div className="item-image"> <a href={`/chi-tiet/${item._id}`}> <img src={item.imgList[0]}></img> </a> </div> <div className="item-caption"> <div className="top-caption"> <div className="caption-title"> <a href={`/chi-tiet/${item._id}`}>{item.name}</a> </div> <div className="caption-address"> <address>{item.full_address}</address> </div> <ul className="caption-list-infor"> <li> <div className="icon bg-selection"></div> <p>{item.area.split(" ",1)} m<sup>2</sup></p> </li> <li> <div className="icon bg-hotel"></div> <p>{item.num_bedroom}</p> </li> <li> <div className="icon bg-bathroom"></div> <p>{item.num_wc}</p> </li> </ul> </div> <div className="bottom-caption"> <div className="caption-price"> <p>{item.price}</p> </div> </div> </div> <div className="view-details"> <a href={`/chi-tiet/${item._id}`}>Xem chi tiết</a> </div> </div> </div> ) }) } </div> <div className="paging"> <ReactPaginate previousLabel={<i className="fa fa-angle-left"></i>} nextLabel={<i className="fa fa-angle-right"></i>} pageCount={pageCount} onPageChange={changePage} containerClassName={"pagination"} activeClassName={"paginationActive"} previousLinkClassName={"previousBtn"} nextLinkClassName={"nextBtn"} disabledClassName={"paginationDisabled"} /> </div> </div> </section> </main> ) } export default HometownRent;<file_sep>import './App.css'; import Header from './components/Header/Header' import Footer from './components/Footer/Footer' import Homepage from './components/screens/Homepage/Homepage' import ApartmentRent from './components/screens/ViewAll/ApartmentRent' import HometownRent from './components/screens/ViewAll/HometownRent' import ApartmentSale from './components/screens/ViewAll/ApartmentSale' import HometownSale from './components/screens/ViewAll/HometownSale' import Detail from './components/screens/ViewDetail/Detail' import React from 'react' import { BrowserRouter, Route, Switch} from 'react-router-dom' const Routing = () => { return ( <Switch> <Route exact path="/"> <Homepage /> </Route> <Route path="/cho-thue/can-ho"> <ApartmentRent /> </Route> <Route path="/cho-thue/nha-pho"> <HometownRent /> </Route> <Route path="/mua-ban/can-ho"> <ApartmentSale /> </Route> <Route path="/mua-ban/nha-pho"> <HometownSale /> </Route> <Route path="/chi-tiet/:id"> <Detail /> </Route> </Switch> ) } function App() { return ( <BrowserRouter> <div className="app"> <header> <Header /> </header> <Routing></Routing> <Footer /> </div> </BrowserRouter> ); } export default App; <file_sep>import React from 'react' import 'bootstrap/dist/css/bootstrap.min.css' import './Header.css'; const Header = () => { return ( <nav> <div className="nav-wrapper white"> <div className="nav-logo"> <a href="/" className="brand-logo">Logo</a> </div> <div className="nav-menu"> <ul className="right"> <li><a href="/mua-ban/can-ho">Mua bán</a></li> <li><a href="/cho-thue/can-ho">Cho thuê</a></li> <li><a href="/du-an">Dự án</a></li> <li><a href="/dang-nhap">Đăng nhập</a></li> <li><a href="/dang-tin" className="dangtin">Đăng tin</a></li> </ul> </div> </div> </nav> ) }; export default Header;
19642261ec0803c7471f2834cdd51a97755ca7ba
[ "JavaScript" ]
3
JavaScript
huyquynh2302/RealEstate-Client
ea541451f8bd6517e8e0f770c9fb79b4123b28fe
c8f32381ae28a813b9f524b8011af8cf56dec98e
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { private bool isJumping = false; [SerializeField] protected Rigidbody2D body = null; [Header("Jump Values")] [SerializeField] protected float jumpVertForce = 500f; [SerializeField] protected int minJumpCount = 7; [SerializeField] protected int maxJumpCount = 30; [SerializeField] protected LayerMask groundedCheckLayerMask = new LayerMask(); protected int jumpCount = 0; // Update is called once per frame void Update() { //Jump function on jump button press if (Input.GetButtonDown("Jump")) { if (GroundedCheck()) { Jump(); } } //Player begins to fall if jump button is released while minimum jump time has passed, or if maximum jump time is reached. if ((!Input.GetButton("Jump") && jumpCount >= minJumpCount) || jumpCount >= maxJumpCount) { isJumping = false; jumpCount = 0; } } private void FixedUpdate() { //Increases height while player continues to hold jump button if (isJumping) { //Adds to the fixed update frames accumulated during the jump jumpCount++; //Increases height based on fixed update time and adjusted jump speed //this.transform.Translate(Vector3.up * AdjustJumpSpeed(jumpVertForce) * Time.fixedDeltaTime); body.AddForce(new Vector2(0, AdjustJumpSpeed(jumpVertForce))); //Resets player's y velocity so he/she won't fall while jumping body.velocity = new Vector2(body.velocity.x, 0f); } } //Changes player state to jumping. Increase movement speed based on perfect and good jump timing. private void Jump() { //Changes player state isJumping = true; //this.transform.Translate(Vector3.up * jumpVertForce * Time.deltaTime); body.AddForce(new Vector2(0f, jumpVertForce)); } //Adjust jump speed and height based on the player's current states private float AdjustJumpSpeed(float initialJumpSpeed) { float currentJumpSpeed = initialJumpSpeed; currentJumpSpeed *= ((float)(maxJumpCount - jumpCount) / (float)maxJumpCount); return currentJumpSpeed; } //Checks grounded state based on two short raycasts, the jump state, and player vertical velocity. private bool GroundedCheck() { Vector2 leftGroundedCheckStart = gameObject.transform.position + Vector3.left * .3f; Vector2 leftGroundedCheckEnd = gameObject.transform.position - Vector3.up * .55f + Vector3.left * .3f; Vector2 rightGroundedCheckStart = gameObject.transform.position + Vector3.right * .3f; Vector2 rightGroundedCheckEnd = gameObject.transform.position - Vector3.up * .55f + Vector3.right * .3f; bool leftGroundedCheck = Physics2D.Linecast(leftGroundedCheckStart, leftGroundedCheckEnd, groundedCheckLayerMask)/* || Physics2D.Linecast(gameObject.transform.position + Vector3.left * .3f, gameObject.transform.position - Vector3.up * .5f + Vector3.left * .3f)*/; bool rightGroundedCheck = Physics2D.Linecast(rightGroundedCheckStart, rightGroundedCheckEnd, groundedCheckLayerMask)/* || Physics2D.Linecast(gameObject.transform.position + Vector3.right * .3f, gameObject.transform.position - Vector3.up * .5f + Vector3.right * .3f)*/; Debug.DrawLine(leftGroundedCheckStart, leftGroundedCheckEnd); Debug.DrawLine(rightGroundedCheckStart, rightGroundedCheckEnd); return ((leftGroundedCheck || rightGroundedCheck) && //body.velocity.y < 0.1f && //body.velocity.y > -0.1f && !isJumping); } } <file_sep>using UnityEngine; using UnityEngine.SceneManagement; using System.Collections; public class UIManager : MonoBehaviour { GameObject[] finishObjects; public GameObject player; public GameObject MusicPlayer; public AudioSource audio; // Use this for initialization void Start () { Time.timeScale = 1; finishObjects = GameObject.FindGameObjectsWithTag("ShowOnFinish"); hideFinished (); } void Update(){ if (Input.GetKey(KeyCode.Escape)) { Application.Quit(); } //shows finish gameobjects if player is dead and timescale = 0 if (Time.timeScale == 0 && player.GetComponent<PlayerManager>().alive == false){ showFinished(); } } //Reloads the Level public void Reload(){ //Application.LoadLevel(Application.loadedLevel); SceneManager.LoadScene(SceneManager.GetActiveScene().name); } public void QuitGame() { Application.Quit(); } //loads inputted level public void LoadLevel(string level){ //Application.LoadLevel(level); SceneManager.LoadScene (level); } //shows objects with ShowOnFinish tag public void showFinished(){ foreach(GameObject g in finishObjects){ g.SetActive(true); MusicPlayer.SetActive(false); } } //hides objects with ShowOnFinish tag public void hideFinished(){ foreach(GameObject g in finishObjects){ g.SetActive(false); } } } <file_sep>using UnityEngine; using System.Collections; public class MusicSwitcher : MonoBehaviour { public AudioSource HappySong; static private AudioSource happySong; public AudioSource EvilSong; static private AudioSource evilSong; private void Start() { happySong = HappySong; evilSong = EvilSong; SongSwitch(false); } static public void SongSwitch(bool isEvil) { if(isEvil) { happySong.volume = 0f; evilSong.volume = 1f; } else { happySong.volume = 1f; evilSong.volume = 0f; } } } <file_sep>using UnityEngine; using System.Collections; public class MonsterManager : MonoBehaviour { private float twoHealthPosition; [SerializeField] private float oneHealthPosition; [SerializeField] private float zeroHealthPosition; private AnimationCurve positionCurve = new AnimationCurve(new Keyframe(0,0), new Keyframe(1,1)); private void Start() { twoHealthPosition = this.transform.position.x; positionCurve = AnimationCurve.Linear(0, oneHealthPosition, 1, twoHealthPosition); } public void MonsterMovement(float timeElapsed, float maxTime) { this.transform.position = new Vector2(positionCurve.Evaluate(timeElapsed / maxTime), this.transform.position.y); } public void DeathMonsterMovement() { this.transform.position = new Vector2(zeroHealthPosition, this.transform.position.y); } } <file_sep>using UnityEngine; using System.Collections; public class Characterfinal : MonoBehaviour { /* public float speed = 10f; public bool isJumping = false; // Condition for whether the player should jump. public float jumpForce = 1000f; // Amount of force added when the player jumps. public bool gamestarted = false; // Is the player currently running? private bool grounded = false; // Whether or not the player is grounded. private Rigidbody2D rigidBody; // Reference to the player's rigidbody */ public float speed = 10f; public bool gamestarted = false; private bool isJumping = false; private bool grounded = false; public AudioSource jump; [SerializeField] protected Rigidbody2D body = null; [Header("Jump Values")] [SerializeField] protected float jumpVertForce = 500f; [SerializeField] protected int minJumpCount = 7; [SerializeField] protected int maxJumpCount = 30; [SerializeField] protected LayerMask groundedCheckLayerMask = new LayerMask(); protected int jumpCount = 0; public Animator anim; // Reference to the player's animator component. void Awake() { } //the moment our character hits the ground we set the grounded to true void OnCollisionEnter2D(Collision2D hit) { grounded = true; } void Start() { body = GetComponent<Rigidbody2D>(); } void Update() { /* if (Input.GetButtonDown("Fire1")) { // If the jump button is pressed and the player is grounded and the character is running forward then the player should jump. if( (grounded == true) && (gamestarted == true)) { jump = true; grounded = false; anim.SetTrigger("Jump"); } // if the game is set now to start the character will start to run forward in the FixedUpdate else { gamestarted = true; anim.SetTrigger("Start"); } } anim.SetBool("Grounded", grounded); */ //Jump function on jump button press if (Input.GetButtonDown("Jump")) { if (grounded ) { Jump(); } } anim.SetBool("Grounded", grounded); //Player begins to fall if jump button is released while minimum jump time has passed, or if maximum jump time is reached. if ((!Input.GetButton("Jump") && jumpCount >= minJumpCount) || jumpCount >= maxJumpCount) { isJumping = false; jumpCount = 0; } } //everything in the physics we set in the fixupdate void FixedUpdate () { // if game is started we move character forward and update the animator... /*if (gamestarted == true) { body.velocity = new Vector2( speed , body.velocity.y ); }*/ // If jump is set to true we are now adding quickly aforce to push the character up if (isJumping) { //Adds to the fixed update frames accumulated during the jump jumpCount++; //Increases height based on fixed update time and adjusted jump speed //this.transform.Translate(Vector3.up * AdjustJumpSpeed(jumpVertForce) * Time.fixedDeltaTime); body.AddForce(new Vector2(0, AdjustJumpSpeed(jumpVertForce))); //Resets player's y velocity so he/she won't fall while jumping body.velocity = new Vector2(body.velocity.x, 0f); } } private void Jump() { //Changes player state isJumping = true; grounded = false; //this.transform.Translate(Vector3.up * jumpVertForce * Time.deltaTime); body.AddForce(new Vector2(0f, jumpVertForce)); jump.Play(); anim.SetTrigger("Jump"); } //Adjust jump speed and height based on the player's current states private float AdjustJumpSpeed(float initialJumpSpeed) { float currentJumpSpeed = initialJumpSpeed; currentJumpSpeed *= ((float)(maxJumpCount - jumpCount) / (float)maxJumpCount); return currentJumpSpeed; } private bool GroundedCheck() { Vector2 leftGroundedCheckStart = gameObject.transform.position + Vector3.left * .3f; Vector2 leftGroundedCheckEnd = gameObject.transform.position - Vector3.up * .55f + Vector3.left * .3f; Vector2 rightGroundedCheckStart = gameObject.transform.position + Vector3.right * .3f; Vector2 rightGroundedCheckEnd = gameObject.transform.position - Vector3.up * .55f + Vector3.right * .3f; bool leftGroundedCheck = Physics2D.Linecast(leftGroundedCheckStart, leftGroundedCheckEnd, groundedCheckLayerMask)/* || Physics2D.Linecast(gameObject.transform.position + Vector3.left * .3f, gameObject.transform.position - Vector3.up * .5f + Vector3.left * .3f)*/; bool rightGroundedCheck = Physics2D.Linecast(rightGroundedCheckStart, rightGroundedCheckEnd, groundedCheckLayerMask)/* || Physics2D.Linecast(gameObject.transform.position + Vector3.right * .3f, gameObject.transform.position - Vector3.up * .5f + Vector3.right * .3f)*/; Debug.DrawLine(leftGroundedCheckStart, leftGroundedCheckEnd); Debug.DrawLine(rightGroundedCheckStart, rightGroundedCheckEnd); return ((leftGroundedCheck || rightGroundedCheck) && //body.velocity.y < 0.1f && //body.velocity.y > -0.1f && !isJumping); } } <file_sep>using UnityEngine; using System.Collections; public class TextureSwap : MonoBehaviour { public Renderer[] renderers; //public bool IsSad = false; public Texture2D hardTextureGround; public Texture2D easyTextureGround; public Texture2D hardTextureSky; public Texture2D easyTextureSky; public Texture2D targetTextureGround; public Texture2D targetTextureSky; public Animator anim; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (HappinessManager.isHard) { targetTextureGround = hardTextureGround; targetTextureSky = hardTextureSky; } else { targetTextureGround = easyTextureGround; targetTextureSky = easyTextureSky; } SwapTexture(targetTextureGround, targetTextureSky); anim.SetBool("IsHard", HappinessManager.isHard); MusicSwitcher.SongSwitch(HappinessManager.isHard); } public void SwapTexture(Texture2D textureGround, Texture2D textureSky) { foreach(var renderer in renderers) { if (renderer.material.mainTexture == textureGround || renderer.material.mainTexture == textureSky) return; else { if(renderer.gameObject.tag == "Sky") { renderer.material.mainTexture = textureSky; } else { renderer.material.mainTexture = textureGround; } } } } } <file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; public class BackgroundSpeedIncrease : MonoBehaviour { [SerializeField] private float maxSpeedMultiplier = 1f; static public float MaxSpeedMultiplier; [SerializeField] private float baseSpeed = 3.8f; [SerializeField] private float baseSkySpeed = .06f; private List<AnimatedTexture> animations = new List<AnimatedTexture>(); [SerializeField] private AnimatedTexture skyAnimation = null; [SerializeField] private float timeForMaxSpeed = 30f; static public float TimeForMaxSpeed = 30f; private float timer = 0f; static public float speedTimer; // Use this for initialization void Start() { foreach (AnimatedTexture textureAnimation in this.gameObject.GetComponentsInChildren<AnimatedTexture>()) { animations.Add(textureAnimation); } speedTimer = timer; TimeForMaxSpeed = timeForMaxSpeed; MaxSpeedMultiplier = maxSpeedMultiplier; } // Update is called once per frame void Update() { if (!HappinessManager.isHard) { timer += Time.deltaTime; timer = Mathf.Clamp(timer, 0, timeForMaxSpeed); foreach (AnimatedTexture texture in animations) { texture.speed = new Vector2(baseSpeed * (1f + maxSpeedMultiplier * (timer / timeForMaxSpeed)), texture.speed.y); } skyAnimation.speed = new Vector2(baseSkySpeed * (1f + maxSpeedMultiplier * (timer / timeForMaxSpeed)), skyAnimation.speed.y); } else { timer = 0f; foreach (AnimatedTexture texture in animations) { texture.speed = new Vector2(baseSpeed, texture.speed.y); } skyAnimation.speed = new Vector2(baseSkySpeed, skyAnimation.speed.y); } speedTimer = timer; } } <file_sep>using UnityEngine; using System.Collections; public class PlayerManager : MonoBehaviour { [Header("Player Health Values")] [Range(0, 2)] private int playerHealth = 2; public bool alive; [Tooltip("The time it takes for the player to regenerate back to full health after taking damage, in seconds.")] [SerializeField] private float healthRegenTime = 10f; private float timer = 0f; [Header("Invulnerability Values")] [SerializeField] private float invulnerabilityTime = 1f; [SerializeField] private float invulnerabilityFlickerTime = .05f; private float flickerTimer = 0f; private bool isInvulnerable = false; private float invulnerableTimer = 0f; [SerializeField] private SpriteRenderer playerSprite = null; [SerializeField] private Animator anim; public AudioSource hit; [Header("Control Lockout Values")] private float controlLockoutTime = .5f; private float lockoutTimer = 0f; private bool isLockedOut = false; private Characterfinal controls = null; [Header("Collectible Values")] [SerializeField] private float happinessGain = 5f; [Header("Monster Values")] [SerializeField] private MonsterManager monster = null; void Awake() { controls = GetComponent<Characterfinal>(); alive = true; } private void Update() { if(playerHealth < 2 && playerHealth > 0) { timer += Time.deltaTime; monster.MonsterMovement(timer, healthRegenTime); if(timer >= healthRegenTime) { playerHealth++; playerHealth = Mathf.Clamp(playerHealth, 0, 2); timer = 0f; } } if (isInvulnerable) { invulnerableTimer += Time.deltaTime; flickerTimer += Time.deltaTime; if(flickerTimer >= invulnerabilityFlickerTime) { playerSprite.color = (playerSprite.color.a > 0) ? new Vector4(playerSprite.color.r, playerSprite.color.g, playerSprite.color.b, 0) : new Vector4(playerSprite.color.r, playerSprite.color.g, playerSprite.color.b, 1); flickerTimer = 0f; } if(invulnerableTimer >= invulnerabilityTime) { EndInvulnerability(); } } if (isLockedOut) { lockoutTimer += Time.deltaTime; if(lockoutTimer >= controlLockoutTime) { EndControlLockout(); } } } private void OnTriggerEnter2D(Collider2D other) { if(other.tag == "Obstacle" && !isInvulnerable) { playerHealth--; playerHealth = Mathf.Clamp(playerHealth, 0, 2); if(playerHealth <= 0) { Death(); return; } StartControlLockout(); StartInvulnerabilityTime(); hit.Play(); } else if(other.tag == "Collectible") { Destroy(other.gameObject); HappinessManager.AddToHappiness(happinessGain); } else if(other.tag == "Monster") { alive = false; Time.timeScale = 0; } } private void StartInvulnerabilityTime() { isInvulnerable = true; anim.SetBool("IsHit", true); } public void EndInvulnerability() { isInvulnerable = false; playerSprite.color = new Vector4(playerSprite.color.r, playerSprite.color.g, playerSprite.color.b, 1); invulnerableTimer = 0f; flickerTimer = 0f; anim.SetBool("IsHit", false); } private void StartControlLockout() { isLockedOut = true; controls.enabled = false; } private void EndControlLockout() { isLockedOut = false; controls.enabled = true; } private void Death() { monster.DeathMonsterMovement(); } } <file_sep>using UnityEngine; using System.Collections; public class PlayerSpeedIncrease : MonoBehaviour { private Animator playerAnimator; // Use this for initialization void Start () { playerAnimator = GetComponentInChildren<Animator>(); } // Update is called once per frame void Update () { playerAnimator.speed = (1f + (BackgroundSpeedIncrease.MaxSpeedMultiplier * (BackgroundSpeedIncrease.speedTimer / BackgroundSpeedIncrease.TimeForMaxSpeed))); } } <file_sep>using UnityEngine; using System.Collections; public class SpawnerSpeedIncrease : MonoBehaviour { // Use this for initialization void Start () { GetComponent<PlatformGenerator>().OnSpawn += IncreaseSpeed; } private void IncreaseSpeed(InstantVelocity spawnedVelocity) { spawnedVelocity.velocity = new Vector2( spawnedVelocity.velocity.x * (1f + (BackgroundSpeedIncrease.MaxSpeedMultiplier * (BackgroundSpeedIncrease.speedTimer / BackgroundSpeedIncrease.TimeForMaxSpeed))), spawnedVelocity.velocity.y); } } <file_sep>using UnityEngine; public class FlipIt : MonoBehaviour { public void Flip() { transform.localScale = new Vector3 (-transform.localScale.x, transform.localScale.y, transform.localScale.z); } } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.UI; public class MeterManager : MonoBehaviour { public Image HappinessMeter; static private Image happinessMeter; private void Start() { happinessMeter = HappinessMeter; } private void Update() { HappinessMeterValue(happinessMeter.fillAmount - Input.GetAxisRaw("Vertical") * .01f); } static public void HappinessMeterValue(float value) { value = Mathf.Clamp(value, 0f, 1f); happinessMeter.fillAmount = value; } } <file_sep>using UnityEngine; using System.Collections; public class HappinessManager : MonoBehaviour { [Header("Happiness Decay Values")] [Tooltip("The starting happiness decay value.")] [SerializeField] private float happinessBaseDecay = 5f; [Tooltip("The maximum value of the happiness decay.")] [SerializeField] private float happinessMaxDecay = 20f; [Tooltip("Time for maximum happiness decay to happen, in seconds.")] [SerializeField] private float timeToMaxDecay = 30f; [Header("Happiness Recharge Values")] [SerializeField] private float happinessRecharge = 5f; private static float totalHappiness = 100f; private float timer = 0f; static public bool isHard = false; void Start() { ResetHappiness(); } // Update is called once per frame void Update () { if (!isHard) { AddToHappiness(-1 * Time.deltaTime * (happinessBaseDecay + (happinessMaxDecay - happinessBaseDecay) * Mathf.Clamp(timer / timeToMaxDecay, 0f, 1f))); timer += Time.deltaTime; if(totalHappiness <= 0f) { isHard = true; timer = 0f; } } else { AddToHappiness(happinessRecharge * Time.deltaTime); if(totalHappiness >= 100f) { isHard = false; } } MeterManager.HappinessMeterValue(totalHappiness * .01f); } static public void AddToHappiness(float value) { totalHappiness += value; totalHappiness = Mathf.Clamp(totalHappiness, 0, 100f); } static public void ResetHappiness() { totalHappiness = 100f; } } <file_sep>using UnityEngine; using System.Collections; public class PlatformGenerator : MonoBehaviour { public GameObject[] platforms; public GameObject happyPrefab; public GameObject hellPrefab; private GameObject targetPrefab = null; public float delay = 2f; public bool active = true; public Vector2 delayRange = new Vector2(1, 2); public delegate void SpawnDelegate(InstantVelocity objectVelocity); public event SpawnDelegate OnSpawn; // private float platformWidth; private int platformSelector = 0; // private float[] platformWidths; // Use this for initialization [SerializeField] private bool affectedByHard = true; [SerializeField] private float hardModeSpeedMultiplier; // Update is called once per frame void Start () { ResetDelay(); StartCoroutine(EnemyGenerator()); } IEnumerator EnemyGenerator() { yield return new WaitForSeconds(delay); if (active) { if (HappinessManager.isHard) { targetPrefab = hellPrefab; } else { targetPrefab = happyPrefab; } GameObject newPlatform = (GameObject)Instantiate(targetPrefab, transform.position, transform.rotation); if (OnSpawn != null) { OnSpawn(newPlatform.GetComponent<InstantVelocity>()); } ResetDelay(); } StartCoroutine(EnemyGenerator()); } void ResetDelay() { delay = Random.Range(delayRange.x, delayRange.y); if (HappinessManager.isHard && affectedByHard) { delay *= hardModeSpeedMultiplier; } } }
4e7eea8538c4a3afdf26bbdeeff6af4e85f2283a
[ "C#" ]
14
C#
raz818/ImmersionCapstone
7da0c2e94d67c961f547442311090a43ed406724
2ab2ab9bad4c226f2ab0bd09e780c544fffa0c62
refs/heads/master
<repo_name>gapeter/a2zz<file_sep>/customer.py #!/usr/bin/python # Import modules for CGI handling import cgi, cgitb cgitb.enable() # Create instance of FieldStorage form = cgi.FieldStorage() print ("Content-type:text/html\r\n\r\n") print ("<html>") print ("<head>") print ("<title>Online Registration Form</title>") print ("</head>") print ("<body>") print ("Registration Form") print ("<form action=\"/cgi-bin/customerins.py\" method=GET>") print (" First Name : <input type=text name=FIRST_NAME value=\"\" size=23>") print (" <br>") print (" Last Name : <input type=text name=LAST_NAME value=\"\" size=23>") print (" <br>") print (" Address : <input type=text name=ADDRESS value=\"\" size=23>") print (" <br>") print (" Contact No : <input type=text name=CONTACT_NO value=\"\" size=23>") print (" <br>") print (" Email: <input type=text name=EMAIL value=\"\" size=23>") print (" <br>") print (" Password: <input type=password name=PASSWORD value=\"\" size=23>") print (" <br>") print (" <input type=submit value=Submit name=B1>") print (" <input type=reset value=Reset name=B2>") print (" </form>") print ("</body>") print ("</html>") <file_sep>/customerins.py #!/usr/bin/python import cgi, cgitb import smtplib import MySQLdb cgitb.enable() #Create instance of FieldStorage form = cgi.FieldStorage() names = form.getvalue('confirm') fname = form.getvalue('FIRST_NAME') lname = form.getvalue('LAST_NAME') address = form.getvalue('ADDRESS') contactno = form.getvalue('CONTACT_NO') email = form.getvalue('EMAIL') password = form.getvalue('PASSWORD') print("Content-type:text/html\r\n\r\n") print("<HTML>") print("Registration Form") print (" <br>") print (" <br>") if(names!='no'): #open database connection db = MySQLdb.connect(host='localhost',user='root',passwd='<PASSWORD>$') #Preapare a cursor object using cursor()method cursor = db.cursor() cursor.execute('use A2Z') # Execute the SQL command cursor.execute('SELECT * from CUSTOMER WHERE EMAIL = ("%s")' % (email)) # Fetch all the rows in a list of lists. results = cursor.fetchall() flag = 0 for row in results: flag = 1 print("E-mail : ", email, "Already exists ************") if flag == 0: cursor.execute('insert into CUSTOMER(FIRST_NAME,LAST_NAME,ADDRESS,CONTACT_NO,EMAIL,PASSWORD) values("%s","%s","%s","%s","%s","%s")' % (fname, lname, address, contactno, email,password )) print("INSERTED") db.commit() #disconnect from server db.close() print("</form>") print("</HTML>") <file_sep>/addtocart.py #!/usr/bin/python import cgi, cgitb import smtplib import MySQLdb cgitb.enable() #Create instance of FieldStorage form = cgi.FieldStorage() names = form.getvalue('confirm') email = form.getvalue('EMAIL') product_id = form.getvalue('PRODUCT_ID') qty = form.getvalue('QTY') print("Content-type:text/html\r\n\r\n") print("<HTML>") print (" <br>") print (" <br>") if(names!='no'): #open database connection db = MySQLdb.connect(host='localhost',user='root',passwd='<PASSWORD>$') #Preapare a cursor object using cursor()method cursor = db.cursor() cursor.execute('use A2Z') # Execute the SQL command cursor.execute('insert into CART(EMAIL,PRODUCT_ID, QTY) values("%s","%s","%d")' % (email, product_id, qty)) print("INSERTED") db.commit() #disconnect from server db.close() print("</form>") print("</HTML>") <file_sep>/getCart.py #!/usr/bin/python import cgi, cgitb import smtplib import MySQLdb cgitb.enable() #Create instance of FieldStorage form = cgi.FieldStorage() names = form.getvalue('confirm') email = form.getvalue('email') print("Content-type:text/html\r\n\r\n") print("<HTML>") #print("<form method=GET action=/cgi-bin/products.py>") print (" <br>") print (" <br>") if(names!='no'): #open database connection db = MySQLdb.connect(host='localhost',user='root',passwd='<PASSWORD>$') #Preapare a cursor object using cursor()method cursor = db.cursor() cursor.execute('use A2Z') # Execute the SQL command cursor.execute("SELECT CART.*, PRODUCT_MASTER.* FROM CART INNER JOIN PRODUCT_MASTER ON CART.PRODUCT_ID = PRODUCT_MASTER.PRODUCT_ID WHERE EMAIL = email") try: # Fetch all the rows in a list of lists. results = cursor.fetchall() for row in results: print(row) print (" <br>") # Now print fetched result except: print ("Error: unable to fetch data") #disconnect from server db.close() print("</form>") print("</HTML>")
f8cb40d931f9f122650d59cc6e764ffdb1f42c22
[ "Python" ]
4
Python
gapeter/a2zz
6bc6e8ef9eb1ef908d6be38668b796eb0024f4ac
cac1b2b4918ae5a86661d4e45d14f9f3881f5f99
refs/heads/master
<file_sep><?php include "db.class.php"; print_r($dbObj); exit; $inAjax = $_GET['inAjax']; $do = $_GET['do']; $do = $do ? $do : 'default'; if (!$inAjax) return false; switch ($do) { case "checkMember": echo time(); break; case 'default': die('nothing'); break; } ?><file_sep>一个小型的ajax库,没有使用jquery,减少加载Jquery库的时间,也不用负担Jquery复杂的逻辑处理带来的性能消耗。其中整合jsonp,方便跨域。 示例: ```bash ajax({ type:"post", url:"", //添加自己的接口链接 timeOut:5000, before:function(){ console.log("before"); }, success:function(str){ console.log(str); }, error:function(){ console.log("error"); } }); ``` 参数表: | 参数 | 默认值 | 描述 | 可选值 | |:----|:----|:----|:----| | url | "" | 请求的链接 | string | | type | get | 请求的方法 | get,post | | data | null | 请求的数据 | object,string | | contentType | "" | 请求头 | string | | dataType | "" | 请求的类型 | jsonp | | async | true | 是否异步 | blooean | | timeOut | undefined | 超时时间 | number | | before | function(){} | 发送之前执行的函数 | function | | error | function(){} | 请求报错执行的函数 | function | | success | function(){} | 请求成功的回调函数 | function | 详细的说明,请看[这里] : http://littleblack.cc/2016/05/04/Javascript/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E5%86%99%E4%B8%80%E4%B8%AAAjax/<file_sep><!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"/> <title>Title</title> <meta name="keywords" content=""/> <meta name="description" content=""/> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/> </head> <body> <?php function createHtmlTag($tag = "") { echo("<p>" . $tag . "</p>"); } $member = array("username", "age"); createHtmlTag(json_encode($member)); createHtmlTag(serialize($member)); ?> <p>json_encode($member) : ["username","age"]</p> <p>serialize($member) : a:2:{i:0;s:8:"username";i:1;s:3:"age";}</p> <?php $array = array("username" => "jack"); createHtmlTag(json_encode($array)); createHtmlTag(serialize($array)); ?> <?php $array1 = array(); $array2 = array(); $array1["username"] = "jack"; $array1["age"] = 25; $array2["member"]["member1"]["username"] = "tom"; $array2["member"]["member1"]["age"] = 26; $array2["member"]["member2"]["username"] = "eric"; $array2["member"]["member2"]["age"] = 27; print_r($array1); echo("<br>"); print_r($array2); echo("<br>"); echo("一维数据转换为JSON:"); createHtmlTag(json_encode($array1)); echo("多维数据转换为JSON:"); createHtmlTag(json_encode($array2)); ?> <p>据说,json中必须用双引号。</p> <?php class muke{ public $name = "public name"; protected $prName = 'protected name'; private $pName = 'private name'; public function getName() { return $this->name; } } $mukeObj = new muke(); print_r($mukeObj); createHtmlTag(json_encode($mukeObj)); ?> <p>对象转换为json数据时,只转换公有变量。</p> <h4>json转数组</h4> <?php $jsonStr = '{"key1":"value1","key2":"value2"}'; $json2Array = json_decode($jsonStr,true); print_r($json2Array); ?> </body> </html> <file_sep># json-study studying from imooc 整合小型ajax插件,我取名为only-ajax
7623aa19b948600d1e1fdf41248de778eb496ca5
[ "Markdown", "Text", "PHP" ]
4
PHP
vdouw123/json-study
d30d69b323e1bddca4f011b9dc3ae23c48c639c9
3c80229c4b16182876d58f20012ae820e6789327
refs/heads/master
<file_sep># learning https://www.w3schools.com/html/ https://www.w3schools.com/css/default.asp https://www.w3schools.com/js/default.asp <file_sep> function msg(){ alert("Hello Virgil!"); }
5efa7feeecebb0176883ff84839f759756d821c3
[ "Markdown", "JavaScript" ]
2
Markdown
Adrian01C/bogdan-project-participation
fbde689fd17ce004a19b81b1ee8f643f10de62cf
86aa37c0c3bf42180de3b6cbcfd696aad1876b00
refs/heads/master
<file_sep>package tests; /** * Created by Nikolay on 19.07.2016. */ public class LoginTest { } <file_sep>package pages; /** * Created by Nikolay on 19.07.2016. */ public class DashBoardPage { }
1df15b4ec9354c340c9dd615a9a75b7940215275
[ "Java" ]
2
Java
nik40fox/PageObjectTestNG
765d8f3fc7943c434a7f5c0207f5cba4a4ef3f10
c22f4f66c63ecd2197d4ae75a68b9cd23b8acdd8
refs/heads/master
<repo_name>hanaffiridzwan/project<file_sep>/app/Http/Controllers/borangPenyeliansController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\borangPenyelian; use App\user; class borangPenyeliansController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('borangPenyelian.index', ['borangPenyelians'=>borangPenyelian::orderBy('id')->get()]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('borangPenyelian.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, ['nama' =>'required', 'noMatrik'=>'required', 'kategoriPelajar'=>'required', 'program'=>'required', 'namaPenyelia'=>'required', 'laporanPerjumpaan'=>'required', 'tarikhPerjumpaan'=>'required', 'laporanPerjumpaan'=>'required', 'tarikhPerjumpaan'=>'required', 'perjalananObjektif'=>'required', 'objektif'=>'required', 'tarikhPerjumpaanSeterusnya' =>'required']); $borangPenyelian = new borangPenyelian; $borangPenyelian->nama = $request->nama; $borangPenyelian->noMatrik = $request->noMatrik; $borangPenyelian ->kategoriPelajar = $request->kategoriPelajar; $borangPenyelian->program = $request->program; $borangPenyelian->namaPenyelia = $request->namaPenyelia; $borangPenyelian->laporanPerjumpaan = $request->laporanPerjumpaan; $borangPenyelian->tarikhPerjumpaan = $request->tarikhPerjumpaan; $borangPenyelian->perjalananObjektif =$request->perjalananObjektif; $borangPenyelian->objektif = $request->objektif; $borangPenyelian->tarikhPerjumpaanSeterusnya = $request->tarikhPerjumpaanSeterusnya; $borangPenyelian->user_id=Auth::user()->id; $borangPenyelian->save(); // dd($borangPenyelian); return redirect()->action('borangPenyeliansController@store')->withMessage('Maklumat anda telah disimpan di dalam sistem'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $borangPenyelian = borangPenyelian::findOrFail($id); return view('borangPenyelian.sah', compact('borangPenyelian')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function simpan(Request $request, $id) { $this->validate($request, ['pengesahan']); $borangPenyelian = borangPenyelian::findOrFail($id); $borangPenyelian->pengesahan = $request->pengesahan; $borangPenyelian->save(); return redirect()->action('borangPenyeliansController@index')->withMessage('Borang berjaya disahkan'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $borangPenyelian = borangPenyelian::findOrFail($id); return view('borangPenyelian.edit', compact('borangPenyelian')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $borangPenyelian = borangPenyelian::findOrFail($id); $borangPenyelian->nama = $request->nama; $borangPenyelian->noMatrik = $request->noMatrik; $borangPenyelian ->kategoriPelajar = $request->kategoriPelajar; $borangPenyelian->program = $request->program; $borangPenyelian->namaPenyelia = $request->namaPenyelia; $borangPenyelian->laporanPerjumpaan = $request->laporanPerjumpaan; $borangPenyelian->tarikhPerjumpaan = $request->tarikhPerjumpaan; $borangPenyelian->perjalananObjektif =$request->perjalananObjektif; $borangPenyelian->objektif = $request->objektif; $borangPenyelian->tarikhPerjumpaanSeterusnya = $request->tarikhPerjumpaanSeterusnya; $borangPenyelian->save(); return redirect()->action('borangPenyeliansController@index')->withMessage('Maklumat anda telah disimpan di dalam sistem'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/app/temujanji.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class temujanji extends Model { public $timestamp =false; //set true if using created at and updated at protected $table = 'temujanjis'; protected $fillable=[ 'nama', 'aktiviti', 'masaMula', 'masaAkhir', 'pengesahan' ]; protected $attributes = ['pengesahan' => 'Dipertimbangkan' ]; } <file_sep>/app/Http/Controllers/TemujanjiController.php <?php namespace App\Http\Controllers; use App\Http\Requests; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; use App\temujanji; use App\user; use DateTime; class TemujanjiController extends Controller { public function see() { return view('temujanji.index'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('temujanji.list', ['temujanjis'=>temujanji::orderBy('masaMula')->get()]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('temujanji.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, ['nama' => 'required', 'aktiviti' => 'required', 'time' => 'required', 'pengesahan']); $time = explode(" - ", $request->input('time')); $temujanji = new temujanji; $temujanji->nama = $request->input('nama'); $temujanji->aktiviti = $request->input('aktiviti'); $temujanji->masaMula = $this->change_date_format($time[0]); $temujanji->masaAkhir = $this->change_date_format($time[1]); $temujanji->user_id = Auth::user()->id; $temujanji->save(); return redirect()->action('TemujanjiController@store')->withMessage('Maklumat telah disimpan'); // $request->session()->flash('success', 'Aktiviti berjaya disimpan!'); // return redirect('temujanjis/create'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function simpan(Request $request, $id) { // $this->validate($request, ['nama' => 'required', 'aktiviti' => 'required', 'time' => 'required', 'pengesahan']); $this->validate($request, ['pengesahan']); $temujanji=temujanji::findOrFail($id); $temujanji->user_id=Auth::user()->id; $temujanji->pengesahan = $request->pengesahan; $temujanji->save(); return redirect()->action('TemujanjiController@index')->withMessage('Temujanji berjaya disimpan'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $temujanji = temujanji::findOrFail($id); // $first_date = new DateTime($temujanji->masaMula); // $second_date = new DateTime($temujanji->masaAkhir); // $difference = $first_date->diff($second_date); // $data = ['temujanji' => $temujanji, 'duration' => $this->format_interval($difference)]; return view('temujanji.view', compact('temujanji')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $temujanji = Temujanji::findOrFail($id); $temujanji->masaMula = $this->change_date_format_fullcalendar($temujanji->masaMula); $temujanji->masaAkhir = $this->change_date_format_fullcalendar($temujanji->masaAkhir); return view('temujanji.edit', compact('temujanji')); // return view('temujanji.edit', ['temujanjis' =>temujanji::findOrFail($id)]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $time = explode(" - ", $request->input('time')); $temujanji = temujanji::findOrFail($id); $temujanji->nama = $request->input('nama'); $temujanji->aktiviti = $request->input('aktiviti'); $temujanji->masaMula = $this->change_date_format($time[0]); $temujanji->masaAkhir = $this->change_date_format($time[1]); $temujanji->save(); return redirect('temujanji'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $temujanji = temujanji::find($id); $temujanji->delete(); return redirect('temujanjis'); } public function change_date_format($date) { $time = DateTime::createFromFormat('d/m/Y H:i:s', $date); return $time->format('Y-m-d H:i:s'); } public function change_date_format_fullcalendar($date) { $time = DateTime::createFromFormat('Y-m-d H:i:s', $date); return $time->format('d/m/Y H:i:s'); } public function format_interval(\DateInterval $interval) { $result = ""; if ($interval->y) { $result .= $interval->format("%y year(s) "); } if ($interval->m) { $result .= $interval->format("%m month(s) "); } if ($interval->d) { $result .= $interval->format("%d day(s) "); } if ($interval->h) { $result .= $interval->format("%h hour(s) "); } if ($interval->i) { $result .= $interval->format("%i minute(s) "); } if ($interval->s) { $result .= $interval->format("%s second(s) "); } return $result; } } <file_sep>/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', 'HomeController@index'); Route::group(['middleware'=> ['auth', 'pelajar']], function() { Route::get('/tugasan', 'TugasanController@getView'); Route::post('tugasan', 'TugasanController@insertFile'); }); Route::group(['middleware'=>['auth', 'penyelia']], function() { Route::get('/muatturun', 'MuatTurunController@downFunc'); Route::get('/borangPenyelian/{borangPenyelian}/sah', 'borangPenyeliansController@show'); Route::patch('/borangPenyelian/{borangPenyelian}/simpan', 'borangPenyeliansController@simpan'); }); Route::group(['before' => 'penyelia|pelajar'], function(){ // $temujanji->url = {profile}url('temujanjis/' . $temujanji->id); Route::get('/profile', 'ProfilesController@index'); Route::patch('/profile', 'ProfilesController@update'); Route::get('/profile/edit', 'ProfilesController@edit'); Route::get('/temujanji/index', 'TemujanjiController@see'); Route::get('/temujanji/list', 'TemujanjiController@index'); Route::get('/temujanji/create', 'TemujanjiController@create'); Route::post('/temujanji/create', 'TemujanjiController@store'); Route::post('temujanji/{temujanji}/simpan', 'TemujanjiController@simpan'); Route::get('/temujanji/view', 'TemujanjiController@show'); Route::get('/temujanji/{temujanji}/edit', 'TemujanjiController@edit'); Route::patch('/temujanji/{temujanji}','TemujanjiController@update'); Route::resource('temujanji', 'TemujanjiController'); Route::get('/laporanPrestasi', 'laporanPrestasisController@index'); Route::get('/laporanPrestasi/create', 'laporanPrestasisController@create'); Route::post('/laporanPrestasi', 'laporanPrestasisController@store'); Route::get('laporanPrestasi/{laporanPrestasi}/edit', 'laporanPrestasisController@edit'); Route::patch('/laporanPrestasi/{laporanPrestasi}', 'laporanPrestasisController@update'); Route::delete('/laporanPrestasi/{laporanPrestasi}', 'laporanPrestasisController@destroy'); Route::get('/borangPenyelian', 'borangPenyeliansController@index'); Route::get('/borangPenyelian/create', 'borangPenyeliansController@create'); Route::post('/borangPenyelian', 'borangPenyeliansController@store'); Route::get('/borangPenyelian/{borangPenyelian}/edit','borangPenyeliansController@edit'); Route::patch('/borangPenyelian/{borangPenyelian}','borangPenyeliansController@update'); Route::get('/api', function() { $temujanjis = DB::table('temujanjis')->select('id', 'nama', 'aktiviti', 'masaMula as start', 'masaAkhir as end')->where('pengesahan','terima')->get(); foreach($temujanjis as $temujanji) { $temujanji->title = $temujanji->aktiviti . ' - ' .$temujanji->nama; $temujanji->url = url('temujanji/' .$temujanji->id); } return $temujanjis; }); });<file_sep>/app/User.php <?php namespace App; use App\Penyelia; use App\Pelajar; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; protected $fillable = [ 'name', 'email', 'password', 'userRole' ]; protected $hidden = [ 'password', 'remember_token' ]; public function Tugasan() { return $this->hasMany(Tugasan::class); } public function borangPenyelian() { return $this->hasMany(borangPenyelian::class); } public function laporanPrestasi() { return $this->hasMany(laporanPrestasi::class); } public function temujanji() { return $this->hasMany(temujanji::class); } public function penyelia() { return $this->hasOne(Penyelia::class, 'user_id'); } public function pelajar() { return $this->hasOne(Pelajar::class, 'user_id'); } public function profile() { if ($this->userRole == 'pelajar') { return $this->pelajar(); } else { return $this->penyelia(); } } } <file_sep>/app/laporanPrestasi.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class laporanPrestasi extends Model { protected $fillable=[ 'namaPelajar', 'namaPenyelia', 'tarikh', 'tajukKajian', 'kemajuan', 'dapatan', 'huraianAktiviti', 'pelan', 'komen' , 'komenPenyelia', 'KemajuanPelajar', 'pelanKajian' ]; } // public function user() { // return $this->belongTo(User::class); // }<file_sep>/app/borangPenyelian.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class borangPenyelian extends Model { protected $fillable = [ 'nama', 'noMatrik', 'kategoriPelajar', 'program', 'namaPenyelia', 'laporanPerjumpaan', 'tarikhPerjumpaan', 'perjalananObjektif', 'objektif', 'tarikhPerjumpaanSeterusnya' ]; protected $attributes = ['pengesahan' => 'belum Disahkan' ]; } // public function User() // { // return $this->belongTo(us) // }<file_sep>/app/Tugasan.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Tugasan extends Model { public $timestamp =true; protected $table="tugasans"; protected $fillable=[ 'namaTugasan', 'dokumen', 'created_at' ]; } <file_sep>/database/migrations/2017_04_11_072220_create_borang_penyelians_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBorangPenyeliansTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('borang_penyelians', function (Blueprint $table) { $table->increments('id'); $table->string('nama'); $table->string('noMatrik'); $table->string('kategoriPelajar'); $table->string('program'); $table->string('namaPenyelia'); $table->string('laporanPerjumpaan'); $table->string('tarikhPerjumpaan'); $table->string('perjalananObjektif'); $table->string('objektif'); $table->string('tarikhPerjumpaanSeterusnya'); $table->string('pengesahan')->default('BelumDisahkan')->nullable(); $table->integer('user_id')->unsigned();; $table->timestamps(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('borang_penyelians'); } } <file_sep>/app/Penyelia.php <?php namespace App; use App\User; use Illuminate\Database\Eloquent\Model; class Penyelia extends Model { protected $table = 'penyelias'; protected $fillable = [ 'nama', 'jabatan', 'noBilik', 'noTelefon', 'gambar' ]; /** * */ public function user() { return $this->belongsTo(User::class); } }<file_sep>/app/Http/Controllers/TugasanController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Redirect; use Session; use Validator; use App\Tugasan; class TugasanController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function getView() { return view('tugasan.uploadfile'); } public function insertFile() { $namatugasan = Input::get('namaTugasan'); $file = Input::file('dokumen'); // echo $namaTugasan; // echo $dokumen; $rules = array( 'namaTugasan' => 'required', 'dokumen' => 'required|max:100000|mimes:doc,docx,pptx,pdf,jpeg,png,jpg' ); $validator = Validator::make(Input::all(), $rules); if ($validator->fails()){ //redirect our user back with error messages $messages= $validator->messages(); //send back to the page with the input data and error return return Redirect::to('uploadfile')->withInput()->withErrors($validator); } else if($validator->passes()){ // echo "success validator"; // checking file validation or not? if (Input::file('dokumen')->isValid()) { $extension = Input::file('dokumen')->getClientOriginalExtension(); //renaming $dokumen = rand(11111, 99999).'.'.$extension; $destinationPath ='up_file'; // means projectfolder/public/ up_file // $file->move($destinationPath, $namaTugasan); $data=array( 'namaTugasan'=>$namatugasan, 'dokumen'=>$dokumen, 'user_id'=> auth()->id(), ); Tugasan::insert($data); $upload_success = $file->move($destinationPath, $dokumen); // $notification = array('message' => 'Dokumen Berjaya Disimpan!', 'alert-type' => 'success'); return redirect()->action('TugasanController@insertFile')->withMessage('Maklumat telah disimpan'); // return Redirect::to('tugasan.uploadfile')->with($notification); } else { return redirect()->action('TugasanController@insertFile')->withMessage('Maklumat tidak disimpan'); // $notification = array('message' => 'Dokumen Tidak Berjaya Disimpan!', 'alert-type' => 'error'); // return Redirect::to('tugasan.uploadfile')->with($notification); } } } // public function upload() // { // $file=array('dokumen' =>Input::file('dokumen'));//getting all of the post data // $rules = array('dokumen' =>'required',);//setting rules // $validator = Validator::make($file. $rules); // if($validator->falis()){ // //send back to the page with the input data , rules and meesages // return redirect::to('upload')->withInput()->withErrors($validator); // } // else //sending back with error message // Session:: // } // } public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/database/migrations/2017_04_12_134933_create_laporan_prestasis_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateLaporanPrestasisTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('laporan_prestasis', function (Blueprint $table) { $table->increments('id'); $table->string('namaPelajar'); $table->string('namaPenyelia'); $table->string('tarikh'); $table->string('tajukKajian'); $table->string('kemajuan'); $table->string('dapatan'); $table->string('huraianAktiviti'); $table->string('pelan'); $table->string('komen'); $table->string('komenPenyelia')->nullable(); $table->string('KemajuanPelajar')->nullable(); $table->string('pelanKajian')->nullable(); $table->integer('user_id')->unsigned();; $table->timestamps(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('laporan_prestasis'); } } <file_sep>/app/Http/Controllers/laporanPrestasisController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\laporanPrestasi; use App\user; class laporanPrestasisController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('laporanPrestasi.index', ['laporanPrestasis'=>laporanPrestasi::orderBy('created_at')->get()]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('laporanPrestasi.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, ['namaPelajar' => 'required', 'namaPenyelia' => 'required', 'tarikh' => 'required', 'tajukKajian' => 'required', 'kemajuan' => 'required', 'dapatan' => 'required', 'huraianAktiviti' => 'required','pelan' => 'required', 'komen' => 'required' ]); $laporanPrestasi = new laporanPrestasi; $laporanPrestasi->namaPelajar = $request->namaPelajar; $laporanPrestasi->namaPenyelia = $request->namaPenyelia; $laporanPrestasi->tarikh = $request->tarikh; $laporanPrestasi->tajukKajian = $request->tajukKajian; $laporanPrestasi->kemajuan = $request->kemajuan; $laporanPrestasi->dapatan = $request->dapatan; $laporanPrestasi->huraianAktiviti = $request->huraianAktiviti; $laporanPrestasi->pelan = $request->pelan; $laporanPrestasi->komen = $request->komen; $laporanPrestasi->komenPenyelia = $request->komenPenyelia; $laporanPrestasi->kemajuanPelajar = $request->kemajuanPelajar; $laporanPrestasi->pelanKajian = $request->pelanKajian; $laporanPrestasi->user_id=Auth::user()->id; $laporanPrestasi->save(); return redirect()->action('laporanPrestasisController@store')->withMessage('Maklumat anda telah disimpan di dalam sistem'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $laporanPrestasi = laporanPrestasi::findOrFail($id); return view('laporanPrestasi.edit', compact('laporanPrestasi')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $laporanPrestasi = laporanPrestasi::find($id); $laporanPrestasi->namaPelajar = $request->namaPelajar; $laporanPrestasi->namaPenyelia = $request->namaPenyelia; $laporanPrestasi->tarikh = $request->tarikh; $laporanPrestasi->tajukKajian = $request->tajukKajian; $laporanPrestasi->kemajuan = $request->kemajuan; $laporanPrestasi->dapatan = $request->dapatan; $laporanPrestasi->huraianAktiviti = $request->huraianAktiviti; $laporanPrestasi->pelan = $request->pelan; $laporanPrestasi->komen = $request->komen; $laporanPrestasi->komenPenyelia = $request->komenPenyelia; $laporanPrestasi->kemajuanPelajar = $request->kemajuanPelajar; $laporanPrestasi->pelanKajian = $request->pelanKajian; $laporanPrestasi->save(); return redirect()->action('laporanPrestasisController@index')->withMessage('Maklumat anda telah disimpan di dalam sistem'); // return redirect('laporanPrestasi'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $laporanPrestasi = laporanPrestasi::findOrFail($id); $laporanPrestasi->delete(); return back()->withError('Maklumat telah berjaya dibuang'); } } <file_sep>/app/Pelajar.php <?php namespace App; use App\User; use Illuminate\Database\Eloquent\Model; class Pelajar extends Model { protected $table = 'pelajars'; protected $fillable = [ 'nama', 'noMatrik', 'kategoriPelajar', 'program', 'noTelefon', 'idDaftar', 'gambar' ]; public function user() { return $this->belongsTo(User::class); } }
1aa0af903856b82d8ea0d9d207804e976f9f608f
[ "PHP" ]
14
PHP
hanaffiridzwan/project
6baaf9edb554bcc680d48564d19ddd2aaddc1f4e
58a864573aa76aa81dc62a85476087fc67749fcd
refs/heads/master
<repo_name>bfsgr/webServerPy<file_sep>/README.md # WebServerPy A simple web server written in python. It only accepts GET requests and only sends 200 and 404 status codes. * The default server port is 35698. * The root is configured to return a index.html file in the directory. * Every file inside the same folder (and bellow) should be accessible. Lauch it with: ``python WebServer.py`` then access http://localhost:35689 <file_sep>/WebServer.py from socket import * import threading import time import os import mimetypes import re from pathlib import Path class ManageGET(threading.Thread): def __init__(self, threadID, conn, request): threading.Thread.__init__(self) self.threadID = threadID self.conn = conn self.request = request def returnGET(self, path): #At this point there is a file to send, so the response is 200 OK header = "HTTP/1.1 200 OK\r\n" #writes the connection type in the response responseRow = "Connection: " + self.request.connection + "\n" #writes current date in GMT responseRow += "Date: " + time.strftime("%a, %d %b %Y %H:%M:%S %Z", time.gmtime()) + "\r\n" #writes server name responseRow += "Server: bfsgr (Fedora)\r\n" #get the last modified date of the file and write it in GMT ltime = os.path.getmtime(path) ltime = time.strftime("%a, %d %b %Y %H:%M:%S %Z", time.gmtime(ltime)) responseRow += "Last-Modified: " + ltime + "\r\n" #Writes file size (in bytes) responseRow += "Content-Length: " + str(os.path.getsize(path)) + "\r\n" #Writes the MIME type responseRow += "Content-Type: " + str(mimetypes.guess_type(path)[0]) + "\r\n\r\n" #lock sending.acquire() #sends header (200 OK) self.conn.send(header.encode()) #sends the rest of the message self.conn.send(responseRow.encode()) #open requested file as ReadOnly in binary openFile = open(path, "rb") #transfer file data to memory data = openFile.read() #sent it self.conn.send(data) #close requested file openFile.close() #release lock sending.release() def return404(self): #404 default message response = "HTTP/1.1 404\r\nDate: " + time.strftime("%a, %d %b %Y %H:%M:%S %Z", time.gmtime()) + "\r\n\r\n" #Lock, send and release message sending.acquire() self.conn.send(response.encode()) sending.release() def run(self): if not self.request: self.return404() #If resquest is 0 then return 404 else: #URL is root? if self.request.url == "/": #If so look for index.html path = Path("./index.html") if path.is_file(): #directory has index.html file, send it self.returnGET(path) else: #index.html not found, send 404 self.return404() else: #URL is not root #Attach '.' to the path (current directory) path = "." + self.request.url path = Path(path) #File exists? if path.is_file(): #send it self.returnGET(path) else: #file not found, send 404 self.return404() #Managing Thread all new connections start here class ManageConnection(threading.Thread): #makes the parameters global inside the object def __init__(self, threadID, conn): threading.Thread.__init__(self) self.threadID = threadID self.conn = conn #loads data from the connection def load(self, oldBuffs, buffer): #Lock, get more data (2048 bytes) and release receiving.acquire() buffer = self.conn.recv(2048).decode() receiving.release() #slipt data in an array (by lines) buffLines = buffer.splitlines() #if the last line is and empty line (Base case) if buffLines[len(buffLines)-1] == "": #concatenate all past buffers with the current buffer and return return oldBuffs+buffer else: #the last line isn't empty. Call load again (Recursion) return self.load(oldBuffs+buffer, buffer) #start point of the thread def run(self): #Lock and get 3 bytes, then release receiving.acquire() buff = self.conn.recv(3).decode() receiving.release() #If the buffer isn't GET then proceed to self 404 message back if buff != "GET": #Set up a thread that will send a 404 message back menage = ManageGET(self.threadID, self.conn, 0) menage.start() #Wait until it completes menage.join() #then close the connection self.conn.close() else: #load the rest of the resquest buff = self.load(buff, buff) #parse the buffer in a HTTPRequest object request = HTTPRequest(buff) #Set a thread to handle the request manage = ManageGET(self.threadID, self.conn, request) manage.start() #Wait until it completes manage.join() #then close the connection self.conn.close() #HTTPRequest class, used to keep the request data class HTTPRequest: def __init__(self, data): #slipt data in an array (by lines) lines = data.splitlines() #slipt the first line by its spaces requestRow = lines[0].split(' ') #The first element is the request type (GET) self.rtype = requestRow[0] #The second element is the requested URL self.url = requestRow[1] #The last element is the HTTP version self.version = requestRow[2] #Match the connection header in the request using a regex self.connection = re.search(r'Connection: (.*)', data) #If found then: if self.connection: #set the connection type as the value found in "(.*)" self.connection = self.connection.group(1) else: #if there isn't a connection header, then assume keep-alive self.connection = "keep-alive\r" #configure server port and create socket serverPort = 35698 serverSocket = socket(AF_INET,SOCK_STREAM) #option so we don't have to wait to reuse socket port (for debuging) serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) #bind to server port and start to listen it serverSocket.bind(('', serverPort)) serverSocket.listen() #set locks for thread sync sending = threading.Lock() receiving = threading.Lock() #forever while True: #wait for a connection, if there isn't one, this thread will sleep here connection, addr = serverSocket.accept() #there is a connection, setting a thread to handle it thread = ManageConnection(addr, connection) thread.start()
6917f7d3f45d27593a42e90f023ce7b0c9b57dc7
[ "Markdown", "Python" ]
2
Markdown
bfsgr/webServerPy
98eb2b143f5e0a6dd79a61f2a6ec6dc5297dc137
8692e921f829c49ff72a0578372056c6ee8f230a
refs/heads/master
<repo_name>Farkash/R<file_sep>/02-rmarkdown-structure-analysis/sd-burritos.md San Diego Burritos ================ <NAME> 2018-01-31 The data ======== Kaggle: SD Burritos ------------------- The data come from [Kaggle.com](https://www.kaggle.com/srcole/burritos-in-san-diego): > Mexican cuisine is often the best food option is southern California. And the burrito is the hallmark of delicious taco shop food: tasty, cheap, and filling. Appropriately, an effort was launched to critique burritos across the county and make this data open to the lay burrito consumer. About the data -------------- There are 50 rows in this data set, with data taken from 16 neighborhoods and there are 29 burrito types. At this time, the data set contains ratings from over 50 burritos fromd 21 restaurants. There are 10 core dimensions of the San Diego burrito: 1. Volume 2. Tortilla quality 3. Temperature 4. Meat quality 5. Non-meat filling quality 6. Meat-to-filling ratio 7. Uniformity 8. Salsa quality 9. Flavor synergy 10. Wrap integrity All of these measures (except for Volume) are rated on a scale from 0 to 5, 0 being terrible, and 5 being optimal. Other information available for each burrito includes an overall rating, cost, Yelp rating of the restaurant, and more. Glimpse at the data ------------------- ``` r glimpse(burritos) ## Observations: 50 ## Variables: 66 ## $ Location <chr> "Donato's taco shop", "Oscar's Mexican food",... ## $ Burrito <chr> "California", "California", "Carnitas", "Carn... ## $ Date <chr> "1/18/2016", "1/24/2016", "1/24/2016", "1/24/... ## $ Neighborhood <chr> "Miramar", "<NAME>", NA, NA, "Carlsbad", ... ## $ Address <chr> "6780 Miramar Rd", "225 S Rancho Santa Fe Rd"... ## $ URL <chr> "http://donatostacoshop.net/", "http://www.ye... ## $ Yelp <dbl> 3.5, 3.5, NA, NA, 4.0, NA, 3.0, NA, 3.0, 4.0,... ## $ Google <dbl> 4.2, 3.3, NA, NA, 3.8, NA, 2.9, NA, 3.7, 4.1,... ## $ Chips <chr> NA, NA, NA, NA, "x", NA, NA, NA, "x", NA, NA,... ## $ Cost <dbl> 6.49, 5.45, 4.85, 5.25, 6.59, 6.99, 7.19, 6.9... ## $ Hunger <dbl> 3.0, 3.5, 1.5, 2.0, 4.0, 4.0, 1.5, 4.0, 3.5, ... ## $ `Mass (g)` <int> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ `Density (g/mL)` <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Length <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Circum <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Volume <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Tortilla <dbl> 3.0, 2.0, 3.0, 3.0, 4.0, 3.0, 2.0, 2.5, 2.0, ... ## $ Temp <dbl> 5.0, 3.5, 2.0, 2.0, 5.0, 4.0, 3.0, 3.0, 4.5, ... ## $ Meat <dbl> 3.00, 2.50, 2.50, 3.50, 4.00, 5.00, 3.00, 3.0... ## $ Fillings <dbl> 3.5, 2.5, 3.0, 3.0, 3.5, 3.5, 2.0, 2.5, 3.5, ... ## $ `Meat:filling` <dbl> 4.0, 2.0, 4.5, 4.0, 4.5, 2.5, 2.5, 3.0, 1.5, ... ## $ Uniformity <dbl> 4.0, 4.0, 4.0, 5.0, 5.0, 2.5, 2.5, 3.5, 3.0, ... ## $ Salsa <dbl> 4.0, 3.5, 3.0, 4.0, 2.5, 2.5, NA, NA, 3.5, 1.... ## $ Synergy <dbl> 4.0, 2.5, 3.0, 4.0, 4.5, 4.0, 2.0, 2.5, 4.0, ... ## $ Wrap <dbl> 4.0, 5.0, 5.0, 5.0, 4.0, 1.0, 3.0, 3.0, 2.0, ... ## $ overall <dbl> 3.80, 3.00, 3.00, 3.75, 4.20, 3.20, 2.60, 3.0... ## $ Rec <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Reviewer <chr> "Scott", "Scott", "Emily", "Ricardo", "Scott"... ## $ Notes <chr> "good fries: 4/5", "Fries: 3/5; too little me... ## $ Unreliable <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ NonSD <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Beef <chr> "x", "x", NA, "x", "x", NA, "x", NA, "x", "x"... ## $ Pico <chr> "x", "x", "x", "x", "x", NA, NA, "x", "x", "x... ## $ Guac <chr> "x", "x", "x", "x", NA, "x", NA, "x", "x", "x... ## $ Cheese <chr> "x", "x", NA, NA, "x", "x", "x", NA, "x", NA,... ## $ Fries <chr> "x", "x", NA, NA, "x", NA, "x", NA, "x", NA, ... ## $ `Sour cream` <chr> NA, NA, NA, NA, NA, "x", "x", NA, "x", NA, NA... ## $ Pork <chr> NA, NA, "x", NA, NA, NA, NA, "x", NA, NA, NA,... ## $ Chicken <chr> NA, NA, NA, NA, NA, "x", NA, NA, NA, NA, NA, ... ## $ Shrimp <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "x", ... ## $ Fish <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Rice <chr> NA, NA, NA, NA, NA, "x", NA, NA, NA, NA, "x",... ## $ Beans <chr> NA, NA, NA, NA, NA, "x", NA, NA, NA, NA, NA, ... ## $ Lettuce <chr> NA, NA, NA, NA, NA, "x", NA, NA, NA, NA, NA, ... ## $ Tomato <chr> NA, NA, NA, NA, NA, "x", NA, NA, NA, NA, NA, ... ## $ `Bell peper` <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "x", ... ## $ Carrots <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "... ## $ Cabbage <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Sauce <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Salsa_1 <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Cilantro <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Onion <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Taquito <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Pineapple <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Ham <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ `Chile relleno` <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Nopales <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Lobster <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Queso <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Egg <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Mushroom <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Bacon <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Sushi <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Avocado <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Corn <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ## $ Zucchini <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N... ``` Exploratory data analysis ========================= Reviewer counts --------------- First let's take a look at who the reviewers are: ## Warning: package 'bindrcpp' was built under R version 3.3.2 ![Frequency Distribution of Reviewers](sd-burritos_files/figure-markdown_github-ascii_identifiers/dist%20prep%20and%20plot%20of%20reviewers%20in%20one%20step-1.png) Seems like Scott has been eating a lot of burritos! Overall rating vs. cost ----------------------- Next we visualize the relationship between the cost and overall rating of the burritos. The relationship appears to be positive, though the one extremely expensive burrito makes it difficult to assess the strength of the relationship. ![](sd-burritos_files/figure-markdown_github-ascii_identifiers/Rating%20vs%20Cost%20plot-1.png) <file_sep>/ttg/lead-consolidation.R # consolidate lead files for TTG # <NAME> library(dplyr) library(data.table) # Association of Christian Schools International acsi <- read.csv("/Users/Steve/Dropbox/programming/Python/web-scraping/data/shared/acsi.csv", header = T) # Association of Gospel Rescue Missions agrm <- read.csv("/Users/Steve/Dropbox/programming/Python/web-scraping/data/shared/agrm.csv", header = T) # Evangelical Council for Financial Accountability ecfa <- read.csv("/Users/Steve/Dropbox/programming/Python/web-scraping/data/shared/ecfa.csv", header = T) # Private School Review psr <- read.csv("/Users/Steve/Dropbox/programming/Python/web-scraping/data/shared/private-school-review.csv", header = T) names(acsi) names(agrm) names(ecfa) names(psr) # conform the names before combining: # give an organization type to each data set acsi$organization_type <- 'School' acsi$lead_source <- "ACSI - Association of Christian Schools International" acsi$lead_source_website <- 'https://www.acsi.org/' agrm$organization_type <- 'Rescue Mission' agrm$lead_source <- 'AGRM - Association of Gospel Rescue Missions' agrm$lead_source_website <- 'http://www.agrm.org/agrm/default.asp' ecfa$organization_type <- 'Ministry' ecfa$lead_source <- 'ECFA - Evangelical Council for Financial Accountability' ecfa$lead_source_website <- 'http://www.ecfa.org/' psr$organization_type <- 'School' psr$lead_source <- 'Private School Review' psr$lead_source_website <- 'https://www.privateschoolreview.com/' names(acsi) <- tolower(gsub('.', '_', names(acsi), fixed = TRUE)) names(acsi)[names(acsi) == "school_name"] <- "organization_name" names(acsi)[names(acsi) == 'school_website'] <- "organization_website" acsi$state_long <- NA names(acsi)[names(acsi) == 'primary_contact_email'] <- 'email_address' acsi$acsi_page <- NULL # drop this field, not valuable names(agrm) <- tolower(gsub('.', '_', names(agrm), fixed = TRUE)) names(agrm)[names(agrm) == 'organization'] <- 'organization_name' names(agrm)[names(agrm) == 'website'] <- 'organization_website' names(agrm)[names(agrm) == 'state'] <- 'state_long' agrm$state <- NA names(ecfa) <- tolower(gsub('.', '_', names(ecfa), fixed = TRUE)) names(ecfa)[names(ecfa) == 'name_of_organization'] <- 'organization_name' names(ecfa)[names(ecfa) == 'website'] <- 'organization_website' names(ecfa)[names(ecfa) == 'membership_type'] <- 'ecfa_membership_type' ecfa$state_long <- NA names(psr) <- tolower(gsub('.', '_', names(psr), fixed = TRUE)) names(psr)[names(psr) == 'state_full'] <- 'state_long' names(psr)[names(psr) == 'school_name'] <- 'organization_name' names(psr)[names(psr) == 'website'] <- 'organization_website' acsi_names_frame <- cbind(source = 'acsi', colname = names(acsi)) agrm_names_frame <- cbind(source = 'agrm', colname = names(agrm)) ecfa_names_frame <- cbind(source = 'ecfa', colname = names(ecfa)) psr_names_frame <- cbind(source = 'psr', colname = names(psr)) # make master list of all names all_names <- c(names(psr), names(acsi), names(ecfa), names(agrm)) all_names <- unique(all_names) # make character vector of names that are not already in each data set # then add all these names to each data set so they all have the same names, regardless of order acsi_names_not <- setdiff(all_names, names(acsi)) acsi[acsi_names_not] <- NA agrm_names_not <- setdiff(all_names, names(agrm)) agrm[agrm_names_not] <- NA ecfa_names_not <- setdiff(all_names, names(ecfa)) ecfa[ecfa_names_not] <- NA psr_names_not <- setdiff(all_names, names(psr)) psr[psr_names_not] <- NA # how to order columns: # start with the most important univeral columns, then add those from the best data sources names_order <- c("organization_name", "organization_type", "email_address", "phone_number", "fax_number", "primary_contact_name", "street_address", "city", "state", "zip_code", "county", "state_long", "year_founded", "organization_website", "grades_offered", "total_students", "student_body_type", "students_of_color_percentage", "total_classroom_teachers", "student_teacher_ratio", "religious_affiliation", "faculty_with_advanced_degree_percentage", "average_class_size", "average_act_score", "yearly_tuition_cost", "acceptance_rate", "total_sports_offered", "total_extracurriculars", "early_education_students", "elementary_students", "middle_school_students", "high_school_students", "i20_compliant", "grade_levels_taught", "acsi_accreditation_status", "grades_accredited", "other_accreditations", "special_needs", "top_leader", "donor_contact", "ecfa_membership_type", "total_revenue", "total_expenses", "total_assets", "total_liabilities", "net_assets", "reporting_period", "membership_start_date", "lead_source", "lead_source_website") # reorder each frame so they're all in the same order setDT(psr) psr <- psr[, names_order, with = FALSE] setDT(ecfa) ecfa <- ecfa[, names_order, with = FALSE] setDT(acsi) acsi <- acsi[, names_order, with = FALSE] setDT(agrm) agrm <- agrm[, names_order, with = FALSE] # bind them together into one master set master_leads <- rbind(psr, acsi, ecfa, agrm) # create state lookup frame to convert short state names to long, and vice-versa state_short <- c( "AK", "AL", "AR", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", "MI", "MN", "MO", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VT", "WA", "WI", "WV", "WY" ) state_long <- c( "Alaska", "Alabama", "Arkansas","Arizona", "California", "Colorado", "Connecticut", "District-Of-Columbia", "Delaware", "Florida", "Georgia", "Hawaii", "Iowa", "Idaho", "Illinois", "Indiana", "Kansas", "Kentucky", "Louisiana", "Massachusetts", "Maryland", "Maine", "Michigan", "Minnesota", "Missouri","Mississippi", "Montana", "North-Carolina", "North-Dakota", "Nebraska", "New-Hampshire", "New-Jersey", "New-Mexico", "Nevada", "New-York", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode-Island", "South-Carolina", "South-Dakota", "Tennessee", "Texas", "Utah", "Virginia", "Vermont", "Washington", "Wisconsin", "West Virginia", "Wyoming" ) state_lookup <- data.frame(cbind(state_short = state_short, state_long = state_long)) as.data.frame(state_lookup) # test the state lookup # base R method: ecfa_copy <- ecfa # ecfa_copy$state_long <- state_lookup$state_long[state_lookup$state_short == ecfa_copy$state] # dplyr method: master_leads <- dplyr::left_join(master_leads, state_lookup, by = c("state" = "state_short")) master_leads$state_long.x <- master_leads$state_long.y master_leads$state_long.y <- NULL names(master_leads)[names(master_leads) == 'state_long.x'] <- "state_long" write.csv(master_leads, "/Users/Steve/Desktop/master-leads.csv", row.names = FALSE)
003bcfb585baa82ee96186ccb20eafcafbacbdc2
[ "Markdown", "R" ]
2
Markdown
Farkash/R
b0817586e25074fa55cedfc584e6e43fa2a31c67
77c3420050219304c93e8dd6d7a600d56b9446cd
refs/heads/main
<file_sep>import Discord from "discord.js"; import Event from "../base/Event"; export default class MessageCreateEvent extends Event { constructor() { super({ name: "messageCreate", }); } override async call(message: Discord.Message) { if (message.author.bot) return; } } <file_sep>import Discord from "discord.js"; interface EventOptions { name: string; once?: boolean; } export default class Event { name: string; once: boolean; constructor(options: EventOptions) { this.name = options.name; this.once = options.once ? options.once : false; } call(args: any) { console.log(`${this.name} event called! To add functionality to this event override this call method.`); } } <file_sep>import fs from "fs"; export function walk(dir: string) { let results: string[] = []; let list = fs.readdirSync(dir); list.forEach(function (file) { file = dir + "/" + file; let stat = fs.statSync(file); if (stat && stat.isDirectory()) { /* Recurse into a subdirectory */ results = results.concat(walk(file)); } else { /* Is a file */ results.push(file); } }); return results; } <file_sep># discord.js-bot-template A modern discord bot template written using TypeScript and the latest discord.js library. <file_sep>import Discord from "discord.js"; import EventHandler from "./handlers/EventHandler"; export default class Bot { readonly token: string; client: Discord.Client; constructor(token: string) { this.token = token; this.client = new Discord.Client({ restTimeOffset: 2000, makeCache: Discord.Options.cacheWithLimits({ MessageManager: { sweepInterval: 300, sweepFilter: Discord.LimitedCollection.filterByLifetime({ lifetime: 3600, getComparisonTimestamp: (e) => e.editedTimestamp ?? e.createdTimestamp, }), }, }), intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES, Discord.Intents.FLAGS.GUILD_MEMBERS], }); } async init() { EventHandler.init(this.client); } async run(): Promise<void> { return this.client.login(this.token); } } <file_sep>import Discord from "discord.js"; import Event from "../base/Event"; import CommandHandler from "../handlers/CommandHandler"; export default class InteractionCreateEvent extends Event { constructor() { super({ name: "interactionCreate", }); } override async call(interaction: Discord.CommandInteraction) { await CommandHandler.callAsSlash(interaction); } } <file_sep>export class MissingPermissionsError extends Error { constructor(permission: string, isUser: boolean) { if (isUser) super(`You need \`${permission}\` to be able to execute this command!`); else if (permission) super(`I need \`${permission}\` to be able to to execute this command!`); else super(`I do not have permission to execute this command on the mentioned user!\n**Make sure I have a higher role than the mentioned user**`); } } <file_sep>import Discord from "discord.js"; import Command from "../../base/Command"; export default class PingCmd extends Command { constructor() { super({ name: "ping", description: "Displays the API/Message Latency", category: "general", }); } override async call(interaction: Discord.CommandInteraction) { await interaction.reply("Pong!"); } } <file_sep>import Discord from "discord.js"; import { SlashCommandBuilder } from "@discordjs/builders"; import { MissingPermissionsError } from "../base/Error"; interface ArgumentOptions { name: string; description: string; required?: boolean; type: Discord.ApplicationCommandOptionType; } interface CommandOptions { name: string; description: string; category: string; args?: ArgumentOptions[]; userPerms?: string[]; botPerms?: string[]; } export default class Command { name: string; description: string; category: string; args: ArgumentOptions[]; userPerms: string[]; botPerms: string[]; data: SlashCommandBuilder; constructor(options: CommandOptions) { this.name = options.name; this.description = options.description; this.category = options.category; this.args = options.args || []; this.userPerms = options.userPerms || []; this.botPerms = options.botPerms || []; this.data = new SlashCommandBuilder().setName(this.name).setDescription(this.description); for (let arg of this.args) { const setOptionData = (option: any) => option.setName(arg.name).setDescription(arg.description).setRequired(arg.required); switch (arg.type) { case "STRING": this.data.addStringOption(setOptionData); break; case "USER": this.data.addUserOption(setOptionData); break; case "CHANNEL": this.data.addChannelOption(setOptionData); break; case "INTEGER": this.data.addIntegerOption(setOptionData); break; } } } checkPermissions(interaction: Discord.CommandInteraction) { for (let p of this.userPerms) if (!(interaction.member!.permissions as Discord.Permissions).has(p as Discord.PermissionResolvable)) throw new MissingPermissionsError(p, true); for (let p of this.botPerms) if (!interaction.guild!.me!.permissions.has(p as Discord.PermissionResolvable)) throw new MissingPermissionsError(p, false); } call(interaction: Discord.CommandInteraction) { console.log(`Command ${this.name} called!`); } } module.exports = Command; <file_sep>import Discord from "discord.js"; import Event from "../base/Event"; import CommandHandler from "../handlers/CommandHandler"; export default class ReadyEvent extends Event { constructor() { super({ name: "ready", once: true, }); } override async call(client: Discord.Client) { console.log(`Logged in as ${client.user!.username}#${client.user!.discriminator}`); await CommandHandler.init(client); } } <file_sep>import dotenv from "dotenv"; dotenv.config(); import Bot from "./Bot"; const bot = new Bot(process.env.BOT_TOKEN!); (async () => { await bot.init(); await bot.run(); })(); <file_sep>import Discord from "discord.js"; import { REST } from "@discordjs/rest"; import { Routes } from "discord-api-types/v9"; import Command from "../base/Command"; import { walk } from "../common/helper"; export default class CommandHandler { static commands: Discord.Collection<string, Command>; static async init(client: Discord.Client) { CommandHandler.commands = new Discord.Collection<string, Command>(); const files = walk("./src/commands").filter((file) => file.endsWith(".ts")); for (const file of files) { const Command = (await import(`../.${file}`)).default; // src/dir/file.js -> dir/file.js const cmd = new Command(); CommandHandler.commands.set(cmd.name, cmd); } const data = CommandHandler.commands.map((c) => c.data.toJSON()); const rest = new REST({ version: "9" }).setToken(client.token!); try { await rest.put(Routes.applicationGuildCommands(client.user!.id, "741149098282975293"), { body: data }); } catch (error) { console.error(error); } } static async callAsSlash(interaction: Discord.CommandInteraction) { const command = CommandHandler.commands.get(interaction.commandName)!; try { await command.checkPermissions(interaction); await command.call(interaction); } catch (err) { // CommandHandler.handleError(cmd, err); } } } <file_sep>import Discord from "discord.js"; import fs from "fs"; export default class EventHandler { static async init(client: Discord.Client) { const files = fs.readdirSync(`./src/events`).filter((file) => file.endsWith(".ts")); for (const file of files) { const Event = (await import(`../events/${file}`)).default; const eventInstance = new Event(); if (eventInstance.once) client.once(eventInstance.name, eventInstance.call); else client.on(eventInstance.name, eventInstance.call); } } }
e4404683d585f4506e339d781a1f2942bde960ac
[ "Markdown", "TypeScript" ]
13
TypeScript
KineticTactic/discord.js-bot-template
60894b669672c264d4c5b7a8a927cf8a2f557a99
bef63747eb946f4099666283fac1761e7e042db0
refs/heads/master
<file_sep># Matrix: Convert to zero Changes the corresponding row and column to have '0' values if the value is '0' in the input matrix. ## Exercise * Design and implement a method that updates the input matrix. The input parameter is a matrix i.e. two-dimensional array contains only '0's and '1's. If any element in the array is found to be '0', the method updates all the elements in the corresponding row as well as the corresponding column to be '0'. * If you think of multiple approaches to solve the problem, implement the solution which minimizes space complexity. Explain the other approaches, and your decision in comments above the code. * For example if the input is: ``` 1 1 1 1 0 1 1 1 1 1 1 0 ``` then, the matrix should get updated to: ``` 1 0 0 0 0 0 1 0 0 0 0 0 ``` * Share and explain the time and space complexities for your solution in the comments above the method implementation. * If the complexity is describes in terms of *n* and *m*, explain what *n* and *m* stand for. <file_sep># Updates the input matrix based on the following rules: # Assumption/ Given: All numbers in the matrix are 0s or 1s # If any number is found to be 0, the method updates all the numbers in the # corresponding row as well as the corresponding column to be 0. # Time complexity: ? # Space complexity: ? def matrix_convert_to_zero(matrix) raise NotImplementedError end
8280dd12752207351ae1665a8e5fdc23114e1f86
[ "Markdown", "Ruby" ]
2
Markdown
AdaGold/matrix-convert-to-zero
433a8f7745c2ef00aafa161bfa63a8772b44f20d
50a67b6121115acb373c036b7ea988cb7c47b581
refs/heads/main
<repo_name>qweasd1/health-home-stroybook<file_sep>/.storybook/main.js module.exports = { "stories": [ "../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)" ], "addons": [ "@storybook/addon-links", "@storybook/addon-essentials", "@storybook/preset-create-react-app", // 'storybook-addon-material-ui' ], babel: async (options) => { // options["presets"].push([ // "@babel/preset-react", // { "runtime": "automatic", "importSource": "@emotion/react" } // ]) // // options["plugins"].push("@emotion/babel-plugin") return options } }
f631bc469850acacf9e2f36e96c517b8e9fe0aab
[ "JavaScript" ]
1
JavaScript
qweasd1/health-home-stroybook
5b3ad42dd95f22fb171bdbd14541bcd6d2016075
c188d665195ef1bb90192a9bb8130d0b74b9e063
refs/heads/master
<repo_name>maximarin/InteligenciaArtificialTP<file_sep>/entrega2.py import itertools import re from datetime import datetime from simpleai.search import (backtrack, CspProblem, LEAST_CONSTRAINING_VALUE, min_conflicts, MOST_CONSTRAINED_VARIABLE) from simpleai.search.viewers import WebViewer, ConsoleViewer, BaseViewer horarios = [10,11,14, 15, 16, 17] variables = ["Django Girls","Introducción a Python","Keynote Diversidad","Keynote Core Developer","APIs Rest", "Diseño Sistemas Accesibles","Unit Testing","Editores de Código","Música Python","Software, negocios, contabilidad y mucho más", "Análisis de Imágenes","Satélites Espaciales","Lib PyPI","Introducción a Pandas"] aulas = { 1: "Magna", 2: "42", 3: "Laboratorio" } def generar_problema_entrega2(): dominios = {variable: [] for variable in variables} restricciones = [] for horario in horarios: # Taller de Django Girls: requiere de computadoras, y se espera una asistencia de 40 personas.# dominios["Django Girls"].append(("Laboratorio", horario)) # Cómo hacer APIs rest en Django: charla normal sin requerimientos de tamaño de sala ni horarios, pero requiere de proyector.# dominios["APIs Rest"].append(("Magna",horario)) dominios["APIs Rest"].append(("42",horario)) # Diseño de sistemas accesibles: charla normal, y el orador no puede subir por escaleras por una dificulta de salud, por lo que no puede ser en la planta alta. dominios["Diseño Sistemas Accesibles"].append(("Magna", horario)) dominios["Diseño Sistemas Accesibles"].append(("Laboratorio", horario)) # Cómo hacer unit testing en Python: charla normal, requiere proyector.# dominios["Unit Testing"].append(("Magna", horario)) dominios["Unit Testing"].append(("42", horario)) # Python para análisis de imágenes: charla normal pero con una demo interactiva que requiere que el público esté bien visible, por lo que no puede darse en el laboratorio.# dominios["Análisis de Imágenes"].append(("Magna", horario)) dominios["Análisis de Imágenes"].append(("42", horario)) # Editores de código para Python: charla normal, requiere proyector y sistema de audio, ya que el disertante no puede esforzar demasiado su voz.# dominios["Editores de Código"].append(("Magna",horario)) # Cómo hacer música con Python: charla normal, requiere proyector, pero el orador es alguien famoso por lo que se espera bastante asistencia, más de 60 personas. dominios["Música Python"].append(("Magna",horario)) dominios["Música Python"].append(("42",horario)) # Cómo publicar tu lib en PyPI: charla normal que requiere proyector. dominios["Lib PyPI"].append(("Magna", horario)) dominios["Lib PyPI"].append(("42", horario)) # Introducción a Pandas para procesamiento de datos: charla normal con proyector, que por requerimientos de conexión a internet solo puede darse en la planta alta (la planta baja no posee conexión) dominios["Introducción a Pandas"].append(("42", horario)) # Taller de introducción a Python: también requiere de computadoras, y debería darse por la mañana, para que los if horario <= 11: dominios["Introducción a Python"].append(("Laboratorio",horario)) # Cómo ser un buen vendedor de software, negocios, contabilidad y mucho más: dominios["Software, negocios, contabilidad y mucho más"].append(("Laboratorio", horario)) dominios["Software, negocios, contabilidad y mucho más"].append(("42", horario)) # Keynote sobre diversidad: al ser keynote se espera que la mayor parte de la conferencia asista, por lo que se if horario > 11: dominios["Keynote Diversidad"].append(("Magna",horario)) dominios["Keynote Core Developer"].append(("Magna",horario)) # Python para satélites espaciales: charla normal que requiere proyector, y darse por la tarde, porque su orador no funciona bien de mañana.# dominios["Satélites Espaciales"].append(("Magna",horario)) dominios["Satélites Espaciales"].append(("42",horario)) def Keynote_SinOtrasCharlas(vars,vals): val1,val2 = vals valor = val1[1] return val1[1] != val2[1] #horarios diferentes def TodasCharlasDiferentes(vars, vals): # Que no haya charlas en una misma aula y en un mismo horario. val1, val2 = vals return not val1 == val2 #Los keynote no pueden tener otras charlas en simultaneo. Son unicas en su horario. for var in variables: if var != "Keynote Diversidad": restricciones.append(((variables[2],var),Keynote_SinOtrasCharlas)) if var != "Keynote Core Developer": restricciones.append(((variables[3],var),Keynote_SinOtrasCharlas)) #Se generan combinaciones de dos variables, para saber si no hay charlas en el mismo lugar y misma hora. for vars in itertools.combinations(variables,2): restricciones.append(((vars[0],vars[1]),TodasCharlasDiferentes)) return CspProblem(variables, dominios, restricciones) def resolver(metodo_busqueda, iteraciones): problema = generar_problema_entrega2() if metodo_busqueda == "backtrack": resultado = backtrack(problema) elif metodo_busqueda == "min_conflicts": resultado = min_conflicts(problema, iterations_limit=iteraciones) return resultado if __name__ == '__main__': metodo = "backtrack" iteraciones = None #viewer = BaseViewer() #metodo = "min_conflicts" #iteraciones = 100 inicio = datetime.now() result = resolver(metodo, iteraciones) print("tiempo {}".format((datetime.now() - inicio).total_seconds())) print(result) print(repr(result)) #problema = generar_problema_entrega2() #conflictos = _find_conflicts(problema, resultado) #print("Numero de conflictos en la solucion: {}".format(len(conflictos))) <file_sep>/entrega1.py from simpleai.search import SearchProblem from simpleai.search.traditional import breadth_first, depth_first, limited_depth_first, iterative_limited_depth_first, \ uniform_cost, greedy, astar from simpleai.search.viewers import WebViewer, ConsoleViewer, BaseViewer posicionMapa=(2,0) posicionSalida=(5,5) def manhatan(pos1, pos2): return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) class entrega1(SearchProblem): def actions(self, state): franceses, piratas = state actions = [] posicion=0 for pirata in piratas: x,y = pirata[0] # derecha if (y < 5): actions.append([(0, 1),posicion]) # izquierda if (y > 0): actions.append([( 0, -1),posicion]) # arriba if (x > 0): actions.append([( -1, 0),posicion]) # abajo if (x < 5): actions.append([(1,0),posicion]) posicion=posicion+1 return actions def result(self, state, action): franceses, piratas = state posicionMover,nroBarco = action lista_Estado = [list(franceses), list(piratas)] nuevapos = (lista_Estado[1][nroBarco][0][0] + posicionMover[0], lista_Estado[1][nroBarco][0][1] +posicionMover[1]) #Si esta en la misma posicion que el mapa if nuevapos == posicionMapa: lista_Estado[1][nroBarco] = (nuevapos, 1) elif nuevapos in lista_Estado[0]: lista_Estado[0].remove(nuevapos) lista_Estado[1].pop(nroBarco) else: lista_Estado[1][nroBarco] = (nuevapos,piratas[nroBarco][1]) franceses =tuple(lista_Estado[0]) piratas =tuple(lista_Estado[1]) return (franceses, piratas) def cost(self, state, action, state2): return 1 def is_goal(self, state): franceses, piratas = state for p in piratas: if p[0]==posicionSalida and p[1]==1: return True return False def heuristic(self, state): franceses, piratas =state listaCosto = [] menor = 0 for pirata in piratas: posicion, mapa = pirata posx,posy = posicion menor = 0 if mapa == 1: #Solo se debe tener en cuenta la distancia a llegada(5,5) porque ya tiene el mapa costo = abs(posx - posicionSalida[0]) + abs(posy - posicionSalida[1]) if(menor == 0): menor = costo else: if(costo < menor): menor = costo else: #distancia hasta el mapa + la distancia del mapa a la llegada costo = (abs(posx - posicionMapa[0]) + abs(posy-posicionMapa[1])) + (abs(posicionMapa[0] - posicionSalida[0]) + abs(posicionMapa[1] - posicionSalida[1])) if(menor == 0): menor = costo else: if(costo < menor): menor = costo return menor def resolver(metodo_busqueda, franceses, piratas): viewer = BaseViewer() barcos_piratas = [] for pirata in piratas: barcos_piratas.append((pirata, 0)) initial = (tuple(franceses), tuple(barcos_piratas)) problem = entrega1(initial) if metodo_busqueda == "breadth_first": resultado = breadth_first(problem, graph_search=True, viewer=viewer) elif metodo_busqueda == "greedy": resultado = greedy(problem, graph_search=True, viewer = viewer) elif metodo_busqueda == "depth_first": resultado = depth_first(problem, graph_search=True, viewer = viewer) elif metodo_busqueda == "astar": resultado = astar(problem, graph_search=True, viewer = viewer) elif metodo_busqueda == "uniform_cost": resultado = uniform_cost(problem, graph_search=True, viewer = viewer) return resultado """" if __name__ == '__main__': #metodo = "greedy" metodo = "breadth_first" #metodo = "astar" #metodo = "uniform_cost" #metodo = "depth_first" franceses = [(0,2), (0,3), (1,2), (1,3), (2,1), (2,2), (2,3), (3,0), (3,1), (3,2), (4,0), (4,1), (5,0)] piratas = [(4,4), (4,5), (5,4)] result = resolver(metodo, franceses, piratas) """
6cef2250f9fe9843107d1091e613e67cad6a2b5f
[ "Python" ]
2
Python
maximarin/InteligenciaArtificialTP
25a938c278e518d6e53dd7848362bd1bf751cedd
24b3eb14c75e889f9230517e1219d150a24da6aa
refs/heads/master
<file_sep>package com.example.lame_tank_360 import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
993a3ef36d10fdb94e5274db73d63290ab8c69ca
[ "Kotlin" ]
1
Kotlin
criusKer/flame_rocker_demo
513659280ed329490c7681f978a203748fabb1f2
54e2cd1972859cea66f7efd5b11089c74c6cde58
refs/heads/master
<repo_name>blackrabbit99/kievjs<file_sep>/city_lang/assets_lvivjs.py from flask.ext.assets import Environment, Bundle def setup_assets(app): assets = Environment(app) assets.init_app(app) css = Bundle( "css/bootstrap.css", "css/layout.css", output="css/_style.css") js = Bundle( "js/jquery.min.js", "js/jquery.router.js", "js/custom.js", output="js/_basic.js") assets.register('css_all', css) assets.register('js_all', js) <file_sep>/city_lang/core/datastore.py # -*- encoding: utf-8 -*- """ flask.ext.security.datastore ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains an user datastore classes. :copyright: (c) 2012 by <NAME>. :license: MIT, see LICENSE for more details. """ from flask.ext.security.datastore import Datastore, UserDatastore from flask.ext.security.utils import encrypt_password from flask.ext.social.datastore import ConnectionDatastore from bson import ObjectId class MongoSetDatastore(Datastore): def put(self, model): if "_id" not in model: model.save(model) else: model.update(model) return model def delete(self, model): model.delete() class MongoSetUserDatastore(MongoSetDatastore, UserDatastore): """A MongoSet datastore implementation for Flask-Security that assumes the use of the Flask-MongoSet extension. """ def __init__(self, db, user_model, role_model): MongoSetDatastore.__init__(self, db) UserDatastore.__init__(self, user_model, role_model) def create_user(self, **kwargs): """Creates and returns a new user from the given parameters.""" kwargs['password'] = <PASSWORD>_<PASSWORD>(kwargs.pop('password')) user = self.user_model(**self._prepare_create_user_args(**kwargs)) return self.put(user) def find_user(self, **kwargs): if 'id' in kwargs: kwargs['_id'] = ObjectId(kwargs.pop('id')) return self.user_model.query.find_one(kwargs) def find_role(self, role): return self.role_model.query.find_one({'name': role}) class MongoSetConnectionDatastore(MongoSetDatastore, ConnectionDatastore): """A MongoSet datastore implementation for Flask-Social.""" def __init__(self, db, connection_model): MongoSetDatastore.__init__(self, db) ConnectionDatastore.__init__(self, connection_model) def _query(self, **kwargs): return self.connection_model.query def find_connection(self, **kwargs): return self._query.find_one(**kwargs) def find_connections(self, **kwargs): return self._query.find(**kwargs) <file_sep>/city_lang/pages/forms.py from flask.ext.wtf import Form, fields, validators class RegistrationForm(Form): name = fields.TextField(u'First & Last name', [validators.Length(min=5)], description=u'<NAME>') email = fields.TextField(u'Email', [validators.Email()], description=u'<EMAIL>') position = fields.TextField(u'Job Position', [validators.Length(min=5)], description=u'Senior Software Developer') company = fields.TextField(u'Company', [validators.Length(min=2)], description=u'Top 10 leader') <file_sep>/manage.py #!/usr/bin/env python from flask.ext.script import Manager from city_lang.application import init_app # from city_lang.commands import ImportVisitors from seed import Seed def main(): app = init_app() manager = Manager(app) manager.add_command('seed', Seed()) # manager.add_command('import', ImportVisitors()) manager.run() return app if __name__ == '__main__': main() <file_sep>/city_lang/admin/__init__.py from flask import Blueprint from city_lang.core.decorators import lazy_rule bp = Blueprint('admin', __name__, url_prefix='/admin') import views lazy_rule(bp, 'speakers', {'id': None}, 'city_lang.admin.views.SpeakerView') lazy_rule(bp, 'sponsors', {'id': None}, 'city_lang.admin.views.SponsorView') lazy_rule(bp, 'pages', {'id': None}, 'city_lang.admin.views.PageView') lazy_rule(bp, 'letters', {'id': None}, 'city_lang.admin.views.LetterView') <file_sep>/city_lang/pages/__init__.py from city_lang.core.datastore import MongoSetUserDatastore from flask import Blueprint, current_app from flask.ext.security import Security from werkzeug.local import LocalProxy bp = Blueprint('pages', __name__, url_prefix="") mongo = LocalProxy(lambda: current_app.extensions['mongoset']) _security = LocalProxy(lambda: current_app.extensions['security']) import views import models user_datastore = MongoSetUserDatastore(mongo, models.User, models.Role) Security(current_app, user_datastore) <file_sep>/city_lang/application.py # import time # from datetime import datetime from celery import Celery from flask import Flask, g from flask.ext.mail import Mail from flask.ext.mongoset import MongoSet # from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.uploads import UploadSet, configure_uploads, patch_request_class from .settings import CURRENT_SITE, DEFAULT_MAIL_SENDER, ADMINS, BROKER_URL celery = Celery('city_lang', backend='mongodb', broker=BROKER_URL) def create_app(conf_module): app = Flask(__name__, static_url_path='/static', static_folder='../static/{}'.format(CURRENT_SITE), template_folder='../templates/{}'.format(CURRENT_SITE)) app.config.from_object(conf_module) # Cache(app) Mail(app) MongoSet(app) # SQLAlchemy(app) app.extensions['celery'] = celery images = UploadSet('image') configure_uploads(app, (images)) patch_request_class(app) # setup local assets try: from city_lang.assets_local import setup_assets setup_assets(app) except ImportError, e: print "No module assets_local: {}".format(e) try: getattr( __import__("city_lang.assets_{}".format(CURRENT_SITE)), "assets_{}".format(CURRENT_SITE)).setup_assets(app) except Exception, e: print "Can't use local assets: {}".format(e) with app.app_context(): from city_lang.admin import bp as admin from city_lang.pages import bp as pages app.register_blueprint(admin) app.register_blueprint(pages) if not app.debug: import logging from logging.handlers import SMTPHandler mail_handler = SMTPHandler('127.0.0.1', DEFAULT_MAIL_SENDER, ADMINS, '{} Failed'.format(CURRENT_SITE)) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) return app def add_processing(app): @app.before_request def setup_session(): g.is_registerable = True g.site_title = app.config['CURRENT_SITE_NAME'] # g.now = time.mktime(datetime.utcnow().timetuple()) @app.errorhandler(404) def page_not_found(error): from city_lang.pages.views import flatpage return flatpage() return app def init_app(conf_module='city_lang.settings'): return add_processing(create_app(conf_module)) <file_sep>/city_lang/admin/views.py # -*- encoding: utf-8 -*- from bson import ObjectId from flask import render_template, request, url_for, redirect from flask.views import MethodView from flask.ext.login import login_required from flask.ext.uploads import UploadSet, UploadNotAllowed from ..admin.forms import SpeakerForm, SponsorForm, PageForm, LetterForm from ..core import http, tasks from ..core.utils import jsonify_status_code from ..pages.models import Speaker, Sponsor, User, Visitor, FlatPage, Letter from .. import settings from . import bp @bp.route('/') @login_required def index(): return render_template('admin/index.html') @bp.route('/visitors/') @login_required def visitors(): context = { 'letters': list(Letter.query.all()), 'visitors': Visitor.query.all(), 'approved': Visitor.query.find({'is_approved': True}).count(), 'declined': Visitor.query.find({'is_declined': True}).count(), 'confirmed': Visitor.confirmations_stats(), 'tshirt_matrix': Visitor.tshirt_matrix() } return render_template('admin/registrations.html', **context) @bp.route("/visitors/confirm/", methods=["GET"]) @login_required def confirmation(): letter = Letter.query.get(request.values["id"]) for visitor in Visitor.query.all(): visitor.send_confirmation(letter) return redirect("/admin/visitors/") @bp.route('/manipulate/<id>', methods=['PUT']) @login_required def manipulate(id): visitor = Visitor.query.get_or_404(id) if 'action' in request.json: if request.json['action'] == 'approve': visitor.update(is_confirmed=True, is_approved=True, is_declined=False, with_reload=False) tasks.send_email(visitor.email, settings.APPROVE_PARTICIPIATION_SUBJECT, 'emails/approve.html', {'visitor': visitor}) response = {'response': 'approved'} elif request.json['action'] == 'decline': visitor.update(is_approved=False, is_declined=True, with_reload=False) tasks.send_email(visitor.email, settings.DECLINE_PARTICIPIATION_SUBJECT, 'emails/decline.html', {'visitor': visitor}) response = {'response': 'declined'} elif request.json['action'] == 'confirmation': letter = Letter.query.get(request.json['letter']) visitor.send_confirmation(letter) response = {"response": "confirmed"} else: response = {} return jsonify_status_code(response) @bp.route('/state/<id>') @login_required def state(id): return render_template('admin/registrations_state.html', visitor=Visitor.query.get_or_404(id)) @bp.route('/action/<id>') @login_required def action(id): return render_template('admin/registrations_action.html', visitor=Visitor.query.get_or_404(id)) @bp.route('/users/') @login_required def users(): context = { 'users': User.query.all(), 'letters': Letter.query.all() } return render_template('admin/users.html', **context) class CRUDView(MethodView): model = None form = None list_template = None item_form_template = 'admin/form_model.html' object_template = None decorators = [login_required] upload_set = UploadSet('image') def extra_context(self, origin): return origin def get(self, id=None): if 'data' in request.args: instance = self.model.query.get_or_404(id) item_url = url_for('.{}'.format(self.__class__.__name__), id=instance.id) form = self.form(obj=instance) return jsonify_status_code({ 'form': render_template(self.item_form_template, form=form, item_url=item_url), 'id': instance.id, 'title': 'Editing {}'.format(self.__class__.__name__) }) elif id is None: context = {'models': self.get_objects()} template = self.list_template else: context = {'model': self.model.query.get_or_404(ObjectId(id))} template = self.list_template context['form'] = self.form() return render_template( template, **self.extra_context(context)) def post(self, id=None): form = self.form(request.form) instance = self.model() if id is not None: instance = self.model.query.get_or_404(id) if request.form and form.validate(): instance_data = form.data.copy() # processing uploaded files if any if 'image' in request.files: try: filename = self.upload_set.save(request.files['image']) instance_data['image'] = self.upload_set.url(filename) except UploadNotAllowed: del instance_data['image'] instance.update(upsert=True, **instance_data) return redirect(url_for('.{}'.format(self.__class__.__name__))) context = { 'models': self.get_objects(), 'form': form } return render_template( self.list_template, **self.extra_context(context)) def delete(self, id): self.model.query.remove({'_id': ObjectId(id)}) return jsonify_status_code({}, http.NO_CONTENT) def get_objects(self, query_args=None): return self.model.query.find(query_args) class SpeakerView(CRUDView): model = Speaker form = SpeakerForm list_template = 'admin/speakers.html' class SponsorView(CRUDView): model = Sponsor form = SponsorForm list_template = 'admin/sponsors.html' class PageView(CRUDView): model = FlatPage form = PageForm list_template = 'admin/pages.html' class LetterView(CRUDView): model = Letter form = LetterForm list_template = 'admin/letters.html' <file_sep>/requirements.txt Flask==0.9 Flask-Assets==0.8 Flask-Login==0.1.3 Flask-Mail==0.7.4 -e git+https://github.com/MediaSapiens/flask-mongoset@92541cbdc86ce21a302d53c8835ab582b6e566bf#egg=flask-mongoset Flask-OAuth==0.12 Flask-Principal==0.3.3 Flask-Script==0.5.2 Flask-Security==1.5.3 Flask-Social==1.5.4 Flask-Uploads==0.1.3 Flask-WTF==0.8.2 Jinja2==2.6 WTForms==1.0.2 Werkzeug==0.8.3 blinker==1.2 httplib2==0.7.7 ipdb==0.7 ipython==0.13.1 itsdangerous==0.17 oauth2==1.5.211 passlib==1.6.1 pymongo==2.4.1 speaklater==1.3 trafaret==0.4.8 webassets==0.8 wsgiref==0.1.2 celery==3.0.16 <file_sep>/static/lvivjs/js/custom.js (function($) { 'use strict'; var organizers = [ { mail: '<EMAIL>', phone: '+380504306225', skype: 'juliya_saviyk' }, { mail: '<EMAIL>', phone: '+380987183482', skype: 'max.klymyshyn' } ]; var showInfo = function(el, org) { el.empty(); el.append('<ul>\ <li>Email: <a href="mailto:' + org.mail+ '">' + org.mail + '</a></li>\ <li>Phone: ' + org.phone + '</li>\ <li>Skype: ' + org.skype + '</li>\ </ul>'); }; var sections = $('section.content'); var navlinks = $('header nav a'); var showSection = function(section) { navlinks.removeClass('active-narrow active-wide active-regular') .filter('a[href="#' + section + '"]') .addClass(function() { return 'active-' + $(this).attr('class').replace('menu-item-', ''); }); sections.hide(); $('#' + section).show(); }; $.router(/\w+/, function(section) { showSection(section); }); if (!window.location.hash) { showSection('topics'); } $('#organizers .span6 .people-info p').each(function(i, el) { showInfo($(el), organizers[i]); }); $('#partners h4 .mailto').each(function() { var email = organizers[0].mail; $(this).html(email).attr('href', 'mailto:' + email); }); })(window.jQuery); <file_sep>/city_lang/settings_local.py DEBUG = False USE_X_SENDFILE = False MONGODB_DATABASE = 'lvivjs' DEFAULT_MAIL_SENDER = '<<EMAIL>>' CURRENT_SITE = 'lvivjs' CURRENT_SITE_NAME = 'LvivJS' DOMAIN = "http://lvivjs.org.ua" ## no trailing slash SQLALCHEMY_DATABASE_URI = "mysql://root@localhost:3360/kharkivjs" BROKER_URL = 'mongodb://localhost:27017/celery' CELERY_RESULT_BACKEND = 'mongodb' MAIL_FAIL_SILENTLY = False MAIL_SERVER = 'localhost' MAIL_PORT = 25 ADMINS = ('<EMAIL>', ) APPROVE_PARTICIPIATION_SUBJECT = "Welcome to LvivJS Conference!" DECLINE_PARTICIPIATION_SUBJECT = "Sorry, you can't participiate LvivJS" <file_sep>/city_lang/assets_kyivjs.py from flask.ext.assets import Environment, Bundle def setup_assets(app): assets = Environment(app) assets.init_app(app) css = Bundle( "stylesheets/foundation.css", "stylesheets/foundation_icons_general/" "stylesheets/general_foundicons.css", "stylesheets/app.css", output="stylesheets/_basic_style.css") js = Bundle( "javascripts/jquery.js", "javascripts/modernizr.foundation.js", "javascripts/galleria.js", "javascripts/app.js", output="javascripts/_basic.js") assets.register('css_all', css) assets.register('js_all', js) <file_sep>/city_lang/pages/views.py # -*- encoding: utf-8 -*- from flask import current_app, render_template, request, \ g, redirect, session from flask.ext.security import current_user from city_lang.core import http from . import bp from .forms import RegistrationForm from .models import FlatPage, Speaker, Visitor, Sponsor @bp.route("/") def speakers(): context = { 'speakers': Speaker.query.all() } return render_template('speakers.html', **context) @bp.route("/partners/") def partners(): partners_set = [] for kind, value in current_app.config['PARTNERS_KINDS']: if Sponsor.query.find({'kind': kind}).count() > 0: partners_set.append((value, Sponsor.query.find({'kind': kind}))) return render_template('partners.html', kinds=partners_set) @bp.route("/venue/") def venue(): return render_template('venue.html', **{}) @bp.route("/organizers/") def organizers(): return render_template('organizers.html', **{}) @bp.route("/confirm/<user_id>/<confirm_id>/") def confirm(user_id, confirm_id): visitor = Visitor.query.get_or_404(user_id) for n, confirm in visitor.confirmations(): if confirm["cid"] == confirm_id: confirm["confirmed"] = True visitor.save_confirmation(confirm, index=n) session["confirm_user_id"] = visitor.id break return redirect("/confirmed/") @bp.route("/update/", methods=["POST"]) def update(): try: user_id = session["confirm_user_id"] except KeyError: return redirect("/update-error/") visitor = Visitor.query.get_or_404(user_id) visitor["tshirt_size"] = request.form["tshirt_size"] visitor.save() return redirect("/updated/") @bp.route("/registration/", methods=['GET', 'POST']) def registration(): g.is_registerable = False form = RegistrationForm(request.form or None) if request.form and form.validate(): visitor = Visitor() form.populate_obj(visitor) visitor.save_registered() return redirect('/thank-you/') context = { 'form': form, 'letters': Visitor.query.all() } return render_template('registration.html', **context) def flatpage(): page = FlatPage.query.find_one({'slug': request.path.strip('/')}) if page is None: return render_template('404.html'), http.NOT_FOUND #if page.login_required and current_user.is_anonymous(): # return render_template('404.html'), http.NOT_FOUND template = page.get('template', 'flatpage.html') return render_template(template, page=page) <file_sep>/city_lang/settings.py # -- Flask-specific settings DEBUG = False SECRET_KEY = "<KEY>" USE_X_SENDFILE = True CSRF_ENABLED = True # SERVER_NAME = 'localhost' # SESSION_COOKIE_SECURE = True # MongoSet configuration ---------------- MONGODB_DATABASE = '' MONGODB_HOST = 'localhost' MONGODB_PORT = 27017 # should we unroll DBRef links to objects MONGODB_AUTOREF = True MONGODB_AUTOINCREMENT = False MONGODB_FALLBACK_LANG = 'en' # Flask-Mail sender for default email sender DEFAULT_MAIL_SENDER = '' MAIL_FAIL_SILENTLY = True # MAIL_SERVER : default 'localhost' # MAIL_PORT : default 25 # MAIL_USE_TLS : default False # MAIL_USE_SSL : default False # MAIL_DEBUG : default app.debug # MAIL_USERNAME : default None # MAIL_PASSWORD : default <PASSWORD> # DEFAULT_MAX_EMAILS : default None # MAIL_SUPPRESS_SEND : default False # Flask-Security settings for default email sender SECURITY_EMAIL_SENDER = DEFAULT_MAIL_SENDER # either user should confirm email after registration or no SECURITY_RECOVERABLE = True # SECURITY_TRACKABLE = True SECURITY_LOGIN_URL = '/admin/login/' SECURITY_LOGOUT_URL = '/admin/logout/' SECURITY_POST_LOGIN_VIEW = '/admin/' SECURITY_PASSWORD_HASH = '<PASSWORD>' SECURITY_PASSWORD_SALT = ')(*<PASSWORD>' # Flask-Social related settings SOCIAL_URL_PREFIX = '/social' SOCIAL_CONNECT_ALLOW_VIEW = "/account/" SOCIAL_CONNECT_DENY_VIEW = "/account/" SOCIAL_TWITTER = { 'consumer_key': '---------', 'consumer_secret': '---------' } SOCIAL_FACEBOOK = { 'consumer_key': '---------', 'consumer_secret': '---------' } # Site specific settings PARTNERS_KINDS = [ ('organizers', u'Organizers'), ('gold', u'Gold'), ('silver', u'Silver'), ('bronse', u'Bronse'), ('host', u'Hosting'), ('informational', u'Informational'), ] CURRENT_SITE = '' CURRENT_SITE_NAME = '' # Users with email adresses listed here will be created as administrators ADMINS = ('<EMAIL>', ) # role name constants USER_ROLE = 'user' ADMIN_ROLE = 'admin' ORGANIZER_ROLE = 'organizer' ROLES = [USER_ROLE, ADMIN_ROLE, ORGANIZER_ROLE] import os rel = lambda *x: os.path.abspath(os.path.join(os.path.dirname(__file__), *x)) UPLOADS_DEFAULT_DEST = rel('../uploads') UPLOADS_DEFAULT_URL = '/uploads/' # settings_local autoimport import sys import importlib try: ls = importlib.import_module('city_lang.settings_local') for attr in dir(ls): if '__' not in attr: setattr(sys.modules[__name__], attr, getattr(ls, attr)) except ImportError: print "settings_local undefined" <file_sep>/city_lang/core/tasks.py from flask import current_app, render_template from flask.ext.mail import Message from jinja2 import Template from werkzeug.local import LocalProxy celery = LocalProxy(lambda: current_app.extensions['celery']) mail = LocalProxy(lambda: current_app.extensions['mail']) @celery.task def send_email(rcpt, subject, template, context, template_text=None, template_html=None): """ Support to send emails with both files templates and plain text """ msg = Message(subject, recipients=[rcpt]) render = lambda body, ctx: Template(body).render(**ctx) if template_text is not None: msg.body = render(template_text, context) elif template is not None: msg.body = render_template("{}.txt".format(template), **context) if template_html is not None: msg.html = render(template_html, context) elif template is not None: msg.html = render_template(template, **context) mail.send(msg) <file_sep>/city_lang/pages/models.py # encoding: utf-8 import uuid import time import trafaret as t from city_lang.core.documents import EmbeddedDocument from datetime import datetime from flask.ext.security import RoleMixin, UserMixin from ..core import tasks from . import mongo from city_lang.settings import DOMAIN @mongo.register class Event(EmbeddedDocument): structure = t.Dict({ 'name': t.String }) @mongo.register class Visitor(EmbeddedDocument): confirm_fields = { "cid": t.String, "sent": t.Bool, "letter_id": t.String, "confirmed_at": t.Float, "confirmed": t.Bool} structure = t.Dict({ 'name': t.String, 'email': t.Email, 'position': t.String, 'company': t.String, 'created_at': t.Type(datetime), 'confirms': t.List(t.Dict(confirm_fields)), 'tshirt_size': t.String(allow_blank=False), t.Key('is_approved', default=False): t.Bool, t.Key('is_declined', default=False): t.Bool, t.Key('is_confirmed', default=False): t.Bool, }) required_fields = ['name', 'email', 'is_approved', 'is_declined', 'confirms'] def confirmations(self): if not hasattr(self, "confirms"): self.confirms = [] return zip( range(1, len(self.confirms) + 1), self.confirms) #map(lambda o: {key: val for key, val in o.as_dict().items() # if key != "id"}, self.confirms)) @classmethod def confirmations_stats(cls): confirms = {} for visitor in cls.query.find({'confirms.confirmed': True}): for n, confirm in visitor.confirmations(): if n not in confirms: confirms[n] = 0 if confirm["confirmed"] is True: confirms[n] += 1 return confirms @classmethod def tshirt_matrix(cls): return {} def one_confirm(self, letter_id): for n, confirm in self.confirmations(): if confirm["letter_id"] == str(letter_id): return confirm return None def save(self, *args, **kwargs): self.save_confirmation(None, commit=True) def save_confirmation(self, confirm, index=None, commit=True): to_save = [] for n, c in self.confirmations(): if n == index: to_save.append(confirm) else: to_save.append(c) if index is None and confirm is not None: to_save.append(confirm) self.confirms = to_save if commit is True: super(Visitor, self).save() def send_confirmation(self, letter, id=None): if id is None: id = str(uuid.uuid1()) for n, conf in self.confirmations(): if "letter_id" in conf and \ conf["letter_id"] == str(letter.id): return False tasks.send_email( self.email, letter.subject, None, { 'visitor': self, 'id': id, 'letter_id': letter.id, 'link': "{}/confirm/{}/{}/".format( DOMAIN, self.id, id)}, template_text=letter.content) self.save_confirmation({ "cid": id, "letter_id": str(letter.id), "sent": True, "confirmed": False, "confirmed_at": time.time()}) return True def save_registered(self): if self.query.find_one({'email': self.email}) is None: self.created_at = datetime.utcnow() return self.save() else: return None @mongo.register class Letter(EmbeddedDocument): structure = t.Dict({ "subject": t.String, "content": t.String, t.Key('content_html', default=None): t.String, }) @mongo.register class FlatPage(EmbeddedDocument): """ A flatpage representation model """ structure = t.Dict({ 'title': t.String, 'slug': t.String, 'content': t.String, 'login_required': t.Bool, t.Key('template', default=''): t.String, }) required_fields = ['title', 'slug', 'content'] @mongo.register class Speaker(EmbeddedDocument): structure = t.Dict({ 'name': t.String, 'speech': t.String, 'intro': t.String }) required_fields = ['name', 'speech'] @mongo.register class Sponsor(EmbeddedDocument): structure = t.Dict({ 'name': t.String, 'description': t.String(allow_blank=True), 'url': t.String(allow_blank=True), 'image': t.String(allow_blank=True), 'kind': t.String }) indexes = ['kind'] required_fields = ['name'] @mongo.register class Role(EmbeddedDocument, RoleMixin): structure = t.Dict({'name': t.String}) @mongo.register class User(EmbeddedDocument, UserMixin): structure = t.Dict({ 'email': t.Email, 'password': <PASSWORD>, 'first_name': t.String, 'last_name': t.String, 'roles': t.List[t.Type(Role)], t.Key('active', default=True): t.Bool, }) required_fields = ['email', 'password', 'active'] <file_sep>/city_lang/core/utils.py # -*- coding: utf-8 -*- import re import types from bson import ObjectId from datetime import datetime from flask import current_app, abort from flask.ext.mail import Message from flask.helpers import json from functools import wraps from importlib import import_module from os.path import abspath, dirname, join from speaklater import _LazyString from werkzeug import import_string, cached_property class LazyResource(object): def __init__(self, import_name, endpoint): self.__module__, self.__name__ = import_name.rsplit('.', 1) self.import_name = import_name self.endpoint = endpoint @cached_property def view(self): return import_string(self.import_name).as_view(self.endpoint) def __call__(self, *args, **kwargs): return self.view(*args, **kwargs) first_cap_re = re.compile('(.)([A-Z][a-z]+)') all_cap_re = re.compile('([a-z0-9])([A-Z])') lazy_cascade = {'lazy': 'dynamic', 'cascade': 'all'} class CustomEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.ctime() if isinstance(obj, ObjectId): return str(obj) if isinstance(obj, _LazyString): return unicode(obj) if hasattr(obj, 'as_dict'): return obj.as_dict() return super(CustomEncoder, self).default(obj) def json_dumps(data): try: return json.dumps(data, indent=2, cls=CustomEncoder) except ValueError as e: current_app.logger.debug("%s: %s", e.message, data) raise e def jsonify_status_code(data=None, status=200): data = data or {} return current_app.response_class(json_dumps(data), status=status, mimetype='application/json') def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'): """ Returns a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. """ if strings_only and isinstance(s, (types.NoneType, int)): return s elif not isinstance(s, basestring): try: return str(s) except UnicodeEncodeError: if isinstance(s, Exception): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. return ' '.join([smart_str(arg, encoding, strings_only, errors) for arg in s]) return unicode(s).encode(encoding, errors) elif isinstance(s, unicode): return s.encode(encoding, errors) elif s and encoding != 'utf-8': return s.decode('utf-8', errors).encode(encoding, errors) else: return s def resolve_class(class_path): """ helper method for importing class by class path string repesentation """ module_name, class_name = class_path.rsplit('.', 1) return getattr(import_module(module_name), class_name) def rules(language): """ helper method for getting plural form rules from the text file """ rule_file = join(dirname(abspath(__file__)), 'rules.%s') % language for line in file(rule_file): pattern, search, replace = line.split() yield lambda word: (re.search(pattern, word) and re.sub(search, replace, word)) def plural_name(noun, language='en'): """ pluralize a noun for the selected language """ for applyRule in rules(language): result = applyRule(noun) if result: return result def underscorize(name): """ Converts CamelCase notation to the camel_case """ s1 = first_cap_re.sub(r'\1_\2', name) return all_cap_re.sub(r'\1_\2', s1).lower() def send_email(to, subject, body): """ Helper that wraps email sending atoms in Flask-Mail calls """ recipients = isinstance(to, basestring) and [to] or to msg = Message(subject=subject, body=body, recipients=recipients) current_app.mail.send(msg) class Permissions(object): """Multiton. Stores permissions names. Call the permission instance by name. Permission is a function contains any user actions decorated in permissions register decorator. """ _instances = {} def register(self, permission): """Register permissions """ if permission.__name__ not in self._instances: self._instances[permission.__name__] = permission return permission def check_permission(self, perm_name, *perm_args, **perm_kwargs): """Check permission decorator """ allowed = self._instances[perm_name] def wrap(f=None): if getattr(f, '__call__', False): @wraps(f) def closure(*args, **kwargs): # extending permission method with the decorated method # argumants and keyword arguments new_args = perm_args + args perm_kwargs.update(kwargs) check_result = allowed(*new_args, **perm_kwargs) return check_result and f(*args, **kwargs) or abort(403) return closure return allowed(*perm_args, **perm_kwargs) return wrap permissions = Permissions() check_permission = permissions.check_permission plural_underscored = lambda noun: plural_name(underscorize(noun)) <file_sep>/confirm.py # -*- encoding: utf-8 -*- from flask import current_app from flask.ext.script import Command from werkzeug.local import LocalProxy __all__ = ['Confirm'] mongo = LocalProxy(lambda: current_app.extensions['mongoset']) class Confirm(Command): def run(self): print "Send confirmation email" return ''' # self.create_roles() # self.create_user() data = user_data name = raw_input("Enter First and Last name: ") first_name, last_name = name.split(" ", 1) _email = raw_input("Enter email: ") _name, email = parseaddr(_email) if not email: raise ValueError("Please, enter valid email") password = <PASSWORD>("Enter password: ") password1 = <PASSWORD>("Repeat password: ") if not password: raise ValueError("Please, enter non-empty password") if password != <PASSWORD>: raise ValueError("Password doesn't match") data.update(dict( password=<PASSWORD>, email=email, first_name=first_name, last_name=last_name)) self.create_admin_user(data).save() _security.datastore.commit() print "User `{}` have been added".format(email) ''' <file_sep>/seed.py # -*- encoding: utf-8 -*- import getpass from email.utils import parseaddr from flask import current_app from flask.ext.script import Command from werkzeug.local import LocalProxy __all__ = ['Seed'] mongo = LocalProxy(lambda: current_app.extensions['mongoset']) _security = LocalProxy(lambda: current_app.extensions['security']) user_data = { 'email': '<EMAIL>', 'password': '<PASSWORD>', 'first_name': 'Max', 'last_name': "K", # 'current_login_at': datetime.utcnow(), # 'current_login_ip': '127.0.0.1', # 'login_count': 0, } class Seed(Command): def create_user(self, data=user_data): user = _security.datastore.create_user(**data) _security.datastore.commit() return user def create_admin_user(self, user_data): current_app.config['ADMINS'] += (user_data['email'], ) return _security.datastore.create_user(**user_data) def create_roles(self): for name in current_app.config['ROLES']: if _security.datastore.find_role(name) is None: _security.datastore.create_role(name=name) def run(self): # self.create_roles() # self.create_user() data = user_data name = raw_input("Enter First and Last name: ") first_name, last_name = name.split(" ", 1) _email = raw_input("Enter email: ") _name, email = parseaddr(_email) if not email: raise ValueError("Please, enter valid email") password = getpass.getpass("Enter password: ") password1 = getpass.getpass("Repeat password: ") if not password: raise ValueError("Please, enter non-empty password") if password != password1: raise ValueError("Password doesn't match") data.update(dict( password=<PASSWORD>, email=email, first_name=first_name, last_name=last_name)) self.create_admin_user(data).save() _security.datastore.commit() print "User `{}` have been added".format(email) <file_sep>/city_lang/core/documents.py # -*- encoding: utf-8 -*- import trafaret as t from bson import ObjectId, DBRef from bson.errors import InvalidId from decorators import classproperty from flask import current_app from flask.ext.mongoset import Model from operator import attrgetter from .utils import plural_underscored class DocumentMixin(Model): """ Base mixin for all mongodb models """ __abstract__ = True inc_id = True structure = t.Dict().allow_extra('id') @classproperty def __collection__(cls): return plural_underscored(cls.__name__) def as_dict(self, api_fields=None, exclude=None): """ Returns instance as dict in selected language """ exclude_by_default = ['_ns', '_int_id', '_class'] if exclude is not None: exclude_by_default.extend(exclude) fields = api_fields or self.keys() fields = set(fields) - set(exclude_by_default) result = dict(zip(fields, attrgetter(*fields)(self))) result['id'] = result.pop('_id') return result @property def id(self): if "_id" in self: return self["_id"] return None class IdDocument(DocumentMixin): """ Base Model for mongodb models with autoicremented id """ __abstract__ = True inc_id = True indexes = ['_int_id'] class Document(DocumentMixin): """ Base Model for mongodb models without autoicremented id """ __abstract__ = True inc_id = False @property def db_ref(self): """ Helper method for DBRef construction """ return DBRef(self.__collection__, self.id) class EmbeddedDocument(DocumentMixin): """ Base Model to keep an instances inside of other mongodb objects, adds attribute '_ns' into stored instance. Doesn't need to be registered """ __abstract__ = True _fallback_lang = current_app.config.get('MONGODB_FALLBACK_LANG') def __init__(self, initial=None, **kwargs): if '_id' not in kwargs: kwargs['_id'] = ObjectId() kwargs['_ns'] = self.__collection__ super(EmbeddedDocument, self).__init__(initial, **kwargs) @classmethod def create(cls, initial=None, **kwargs): return cls(initial, **kwargs) class MongoId(t.String): """ Trafaret type check & convert class """ def __init__(self): super(MongoId, self).__init__() def converter(self, value): try: return ObjectId(value) except InvalidId as e: self._failure(e.message)
ad0c45e8dd23f37ffe8dee5cf540af54195d863b
[ "JavaScript", "Python", "Text" ]
20
Python
blackrabbit99/kievjs
df18a9a67a290199ac6ce7e9356b179c1b896205
cbc0be813c0372b051a68d984cf450ee629a7ba7
refs/heads/master
<repo_name>maosmurf/coderetreat-20200122-session1-ocr<file_sep>/src/main/java/DigitParser.java public class DigitParser { public int parse(String[] lines) { if (lines[0].charAt(1) == ' ') { return 1; } return 0; } }
03095028f216648d9adb1daa21a1a8bf91bfbc74
[ "Java" ]
1
Java
maosmurf/coderetreat-20200122-session1-ocr
25d868e780318c3fdd3eb5c9ae6d83514917f175
f483b73862feabb89438114c7f5eb57014b728dc
refs/heads/master
<repo_name>zhaozeq/init_vue_project<file_sep>/src/store/mutations.js export default { // 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation, 只能同步 increment (state) { state.count++ }, multiple (state, payload) { const { n = 2 } = payload state.count *= n }, mockRequest (state, payload) { const { val = 0 } = payload state.count += val } } <file_sep>/src/router/router.config.js import App from 'src/App' // 代码分割 按需加载 =>require.ensure(dependencies: String[], callback: function(require), chunkName: String) const newpage = () => import(/* webpackChunkName: "new" */ 'page/new') const home = () => import(/* webpackChunkName: "home" */ 'page/home') const test = () => import(/* webpackChunkName: "test" */ 'page/test') const main = () => import(/* webpackChunkName: "main" */ 'page/main') const clock = () => import(/* webpackChunkName: "clock" */ 'page/clock') const boardOne = () => import(/* webpackChunkName: "board_one" */ 'page/board_one') const customFunction = () => import(/* webpackChunkName: "custom_function" */ 'components/common/custom_function') export default [ { path: '/', component: App, children: [ { name: 'new', path: '/new', component: newpage }, { name: 'clock', path: '/clock', component: clock }, { name: 'board_one', path: '/board_one', component: boardOne, children: [ { path: 'model1', component: customFunction }, { path: 'model2', component: customFunction }, { path: 'model3', component: customFunction } ] }, { name: 'home', path: '/home', component: home, children: [ { name: 'test', path: 'test', component: test }, { name: 'main', path: 'main', component: main }, { name: 'sub_home', path: 'home', component: home } ] }, { path: '/test', component: test }, { path: '/main', component: main }, { path: '*', redirect: '/home' } ] } ] <file_sep>/src/store/action.js export default { increment ({ commit }) { commit('increment') }, async1 () { return new Promise(resolve => { mockRequestData(val => { resolve(val + 4) }) }) }, async2 () { return new Promise(resolve => { mockRequestData(val => { resolve(val + 2) }) }) }, multiple ({ commit }, payload) { setTimeout(() => { commit('multiple', payload) console.log('yi步完成') }, 2000) }, mockRequest ({ commit }) { mockRequestData(val => { commit('mockRequest', { val }) }) }, async asyncTest ({ commit, dispatch }) { console.log('同步方法开始执行') const async1val = await dispatch('async1') console.log('async1执行结束,async2开始执行') const async2val = await dispatch('async2') const val = async1val + async2val console.log('所有异步请求结束', val) commit('mockRequest', { val }) } } // 异步方法 const mockRequestData = cb => { setTimeout(() => { const val = 10 cb && cb(val) }, 1000) } <file_sep>/src/store/moduleA/index.js const moduleA = { namespaced: true, state: { a: 1 }, actions: {}, mutations: { add (state, { val, val1 }) { console.log(val) console.log(val1) state.a += val } } } export default moduleA
022d79e01e9357f479be24c17f9675fca43d193e
[ "JavaScript" ]
4
JavaScript
zhaozeq/init_vue_project
91cf31440e9f61680e0d3899cff38c7c925bcc0e
04aa41fba0f94bcad271344bfff500132dfab04e
refs/heads/master
<repo_name>hadSHOT/opendbc<file_sep>/can/tests/test_dbc_parser.py #!/usr/bin/env python3 import glob import os import unittest from opendbc import DBC_PATH from opendbc.can.parser import CANParser class TestDBCParser(unittest.TestCase): @classmethod def setUpClass(cls): cls.dbcs = [] for dbc in glob.glob(f"{DBC_PATH}/*.dbc"): cls.dbcs.append(os.path.basename(dbc).split('.')[0]) def test_parse_all_dbcs(self): """ Dynamic DBC parser checks: - Checksum and counter length, start bit, endianness - Duplicate message addresses and names - Signal out of bounds - All BO_, SG_, VAL_ lines for syntax errors """ for dbc in self.dbcs: with self.subTest(dbc=dbc): CANParser(dbc, [], [], 0) if __name__ == "__main__": unittest.main() <file_sep>/requirements.txt Cython==0.29.14 flake8==3.7.9 Jinja2==3.0.3 numpy==1.21.0 pycapnp==1.0.0 pylint==2.15.4 pyyaml==5.4 scons
729451e5fb73dd360caf2f99d558881a38e8b4b6
[ "Python", "Text" ]
2
Python
hadSHOT/opendbc
cc966f5c471e0bd08428c7d4ff2e4f843b983a20
2147c94cef69af8ab9bbd0f06af8ab96017d7610
refs/heads/main
<repo_name>CastellaniDavide/smartphone<file_sep>/smartphone - Copy.cpp /** * @file smartphone.cpp * * @version 01.01 2020-11-5 * * @brief https://training.olinfo.it/#/task/ois_smartphone/statement * * @ingroup smartphone * (Note: this needs exactly one @defgroup somewhere) * * @author <NAME> * * Contact: <EMAIL> * */ // Includes #include <bits/stdc++.h> using namespace std; // Variabiles long N, actual, actual_price, result; // Main code int main() { // Cncomment the following lines if you want to read/write from files // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // Input cin >> N; actual_price = 0; result = 0; for (int i = 0; i < N; ++i) { cin >> actual; if (actual > actual_price) { actual_price = actual; result += actual_price; } } // Output cout << result; // End return 0; } <file_sep>/smartphone.cpp #include <assert.h> #include <stdio.h> #include <bits/stdc++.h> using namespace std; #define MAXN 1000000 // input data int N; int P[MAXN]; int main() { // uncomment the following lines if you want to read/write from files freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); assert(1 == scanf("%d", &N)); for (int i = 0; i < N; i++) assert(1 == scanf("%d", &P[i])); // insert your code here int res = 0; int prev = 0; sort(P, P+(N/2)); for(int i = 0; i < N; i++){ if(P[i] > prev){ res += P[i]; prev = P[i]; } } printf("%lld\n", res); // print the result return 0; }
3ec4da2ad90d8461dd9f0d8ad134d976e20d6245
[ "C++" ]
2
C++
CastellaniDavide/smartphone
acaa931864308379ab0d991d16ccebe56b13e0ff
d97069ade102897fbbe0831f7eac332c7f1e6f34
refs/heads/master
<repo_name>rajathagasthya/dotfiles<file_sep>/README.md # dotfiles My treasured dotfiles. Symlinks common dotfiles such as `.vimrc`, `.tmux.conf`, `.zshrc`, `.gitconfig` to the home directory and installs `vim` plugins specified in `.vimrc` using `Vundle`. The script takes a backup of existing config files, if you have any. ## Instructions Make sure to have `git` installed before you do this. 1. Clone the repository ``` $ git clone <EMAIL>:rajathagasthya/dotfiles.git ~/dotfiles ``` 2. Execute bootstrap script ``` $ cd ~/dotfiles $ ./bootstrap.sh ``` <file_sep>/generate-vimwiki-diary-template.py #!/usr/bin/env python import datetime import sys template = """# {date} ## Daily checklist ### Work * [ ] ### Personal ## General ## Meetings ## Projects ## Discoveries ## Misc """ print(template.format(date=datetime.date.today().isoformat())) <file_sep>/bootstrap.sh #!/bin/sh # Bootstrap script to configure rc files and install vim plugins set -e # Current directory of the script DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Create symlinks for rc files in home directory declare -a files=(".vimrc" ".tmux.conf" ".zshrc" ".gitconfig" ".ideavimrc") for i in "${files[@]}" do if [ -e "${HOME}/$i" ]; then echo "${HOME}/$i already exists. Creating a backup of the file." mv "${HOME}/$i" "${HOME}/$i.bak" fi echo "Creating symlink ${HOME}/$i -> $DIR/$i" ln -s "$DIR/$i" ${HOME}/"$i" done # Install powerline-fonts # Install z.sh script # Parameterize username and replace it in .zshrc # Tmux plugin manager git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm # Tmux status bar theme git clone https://github.com/jimeh/tmux-themepack.git ~/.tmux-themepack <file_sep>/Brewfile tap "bazelbuild/tap" tap "cjbassi/gotop" tap "golangci/tap" tap "homebrew/bundle" tap "homebrew/cask" tap "homebrew/core" tap "jesseduffield/lazydocker" tap "johanhaleby/kubetail" tap "rockyluke/devops" tap "wagoodman/dive" brew "aws-iam-authenticator" brew "bash" brew "bat" brew "binutils" brew "broot" brew "bzip2" brew "cmake" brew "coreutils" brew "[email protected]" brew "curl" brew "go" brew "dep" brew "diffutils" brew "docker-ls" brew "docker-machine-driver-hyperkit" brew "ed", link: true brew "fd" brew "findutils" brew "fzf" brew "readline" brew "gawk" brew "git" brew "git-delta" brew "git-quick-stats" brew "glide" brew "gnu-indent" brew "gnu-sed" brew "gnu-tar" brew "gnu-which" brew "unbound" brew "gnutls" brew "gnupg" brew "grep" brew "gzip" brew "helm" brew "ncurses" brew "htop" brew "hub" brew "jq" brew "kind" brew "kubernetes-cli" brew "kustomize" brew "lazygit" brew "sqlite" brew "xz" brew "[email protected]" brew "macvim" brew "make" brew "node" brew "pyenv" brew "reattach-to-user-namespace" brew "ripgrep" brew "safe-rm" brew "screen" brew "tmux" brew "tree" brew "watch" brew "wdiff" brew "wget" brew "youtube-dl" brew "zlib" brew "zsh" brew "zsh-completions" brew "golangci/tap/golangci-lint" brew "jesseduffield/lazydocker/lazydocker" brew "wagoodman/dive/dive" <file_sep>/.bash_profile alias vi='vim' alias cl='clear' alias cd1='cd ..;pwd' alias cd2='cd ..;cd ..;pwd' alias cd3='cd ..;cd ..;cd ..;pwd' alias vssh='vagrant ssh' alias vup='vagrant up' alias vhalt='vagrant halt' alias vsuspend='vagrant suspend' alias vreload='vagrant reload' alias pnr='cd /Users/rajagast/Cisco/PNR/openstack-cisco-cpnrdhcp-driver' if [ -f `brew --prefix`/etc/bash_completion ]; then . `brew --prefix`/etc/bash_completion fi export PATH=/usr/local/bin:/usr/local/sbin:$PATH export CLICOLOR=1 export LSCOLORS=GxFxCxDxBxegedabagaced export FPP_EDITOR=vim
698220dff5b012916050836a3553986e9e9b2d11
[ "Markdown", "Python", "Ruby", "Shell" ]
5
Markdown
rajathagasthya/dotfiles
b6e4364fb36f505cd624aa0f1613bb6d88fcd2b5
da20b7238655d4c09bd47112e5d976304fdff6e4
refs/heads/master
<file_sep>// // LargePostTableViewCell.swift // SpiltMilk // // Created by <NAME> on 06/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class LargePostTableViewCell: UITableViewCell { //MARK: - IBOutlets @IBOutlet weak var usuarioLargeImageView: UIImageView! @IBOutlet weak var usuarioLargeLabel: UILabel! @IBOutlet weak var postLargeImageView: UIImageView! @IBOutlet weak var commentLarge: UIButton! @IBOutlet weak var postTextLargeLabel: UILabel! @IBOutlet weak var likesLargeLabel: UILabel! @IBOutlet weak var cardLargeView: UIView! @IBAction func likesLargeButton(_ sender: UIButton) { sender.setImage(UIImage(systemName: "heart.fill"), for: .selected) sender.setImage(UIImage(systemName: "heart"), for: .normal) guard let likes = likesLargeLabel.text, var totalDeLikes = Int(likes) else {return} if sender.isSelected { sender.isSelected = false totalDeLikes -= 1 likesLargeLabel.text = String(totalDeLikes) } else { sender.isSelected = true totalDeLikes += 1 likesLargeLabel.text = String(totalDeLikes) } } @IBAction func favoritesLargeButton(_ sender: UIButton) { sender.setImage(UIImage(systemName: "bookmark.fill"), for: .selected) sender.setImage(UIImage(systemName: "bookmark"), for: .normal) if sender.isSelected { sender.isSelected = false } else { sender.isSelected = true } } override func awakeFromNib() { super.awakeFromNib() self.usuarioLargeImageView.layer.cornerRadius = self.usuarioLargeImageView.frame.size.width / 2 cardLargeView.layer.cornerRadius = 10 cardLargeView.layer.shadowColor = UIColor.black.cgColor cardLargeView.layer.shadowOpacity = 0.2 cardLargeView.layer.shadowOffset = CGSize(width: 0, height: 0) cardLargeView.layer.shadowRadius = 4 } func setPostDataLarge(nomeUsuario: String, imagemUsuario: UIImage, imagemPost:UIImage, textoPost: String){ self.usuarioLargeLabel.text = nomeUsuario self.usuarioLargeImageView.image = imagemUsuario self.postLargeImageView.image = imagemPost self.postTextLargeLabel.text = textoPost } static func identifier() -> String { return "LargePostTableViewCell" } static func nib() -> UINib { return UINib(nibName: LargePostTableViewCell.identifier(), bundle: .main) } } <file_sep>// // CollectionViewCell.swift // SpiltMilk // // Created by <NAME> on 04/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class CollectionViewCell: UICollectionViewCell { //MARK: - IBOutlets @IBOutlet weak var cardLabel: UILabel! @IBOutlet weak var cardImage: UIImageView! static func identifier() -> String{ return "CollectionViewCell" } func config(label: String, image: UIImage){ cardLabel.text = label cardImage.image = image } static func nib() -> UINib{ return UINib(nibName: CollectionViewCell.identifier(), bundle: nil) } override func awakeFromNib() { super.awakeFromNib() self.layer.cornerRadius = 12 } } <file_sep>// // CollectionViewController.swift // SpiltMilk // // Created by <NAME> on 04/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit private let reuseIdentifier = "Cell" enum postContent{ case food case health case education case products case diagnostics case experiences } class CollectionViewController: UICollectionViewController { //MARK: - Atributos let titulosCategorias = ["Receitas", "Sáude", "Educação", "Produtos", "Diagnósticos", "Experiências"] let imagensCategorias = [ UIImage(named: "Cooking")!, UIImage(named: "Health")!, UIImage(named: "Education")!, UIImage(named: "Products")!, UIImage(named: "Diagnostics")!, UIImage(named: "Experiences")! ] override func viewDidLoad() { super.viewDidLoad() let search = UISearchController(searchResultsController: nil) collectionView.register(CollectionViewCell.nib(), forCellWithReuseIdentifier: CollectionViewCell.identifier()) self.navigationItem.searchController = search } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return titulosCategorias.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.identifier(), for: indexPath) as! CollectionViewCell // Configure the cell cell.config(label: titulosCategorias[indexPath.item], image: imagensCategorias[indexPath.item]) print(indexPath.item) return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { performSegue(withIdentifier: "home", sender: nil) } } <file_sep>// // LoginViewController.swift // SpiltMilk // // Created by <NAME> on 05/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class LoginViewController: UIViewController { //MARK: - IBOutlets @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var forgotPasswordButton: UIButton! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var createAccountButton: UIButton! override func viewDidLoad() { super.viewDidLoad() let textFields: [UITextField]! = [emailTextField, passwordTextField] textFields.forEach { configtextField(textField: $0) } loginButton.backgroundColor = UIColor(red: 99/255, green: 179/255, blue: 187/255, alpha: 1.00) loginButton.layer.cornerRadius = 15 passwordTextField.isSecureTextEntry = true NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(sender:)), name: UIResponder.keyboardWillShowNotification, object: nil); NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(sender:)), name: UIResponder.keyboardWillHideNotification, object: nil); self.hideKeyboardWhenTappedAround() self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action:#selector(LoginViewController.dismissKeyboard))) } override func viewWillDisappear(_ animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: false) } override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(false, animated: false) } @objc func keyboardWillShow(sender: NSNotification){ self.view.frame.origin.y = -150 } @objc func keyboardWillHide(sender: NSNotification){ self.view.frame.origin.y = 0 } @objc func dismissKeyboard(){ self.view.endEditing(true) } func hideKeyboardWhenTappedAround(){ let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } func configtextField(textField: UITextField) { let bottomLine = UIView() textField.addSubview(bottomLine) bottomLine.translatesAutoresizingMaskIntoConstraints = false bottomLine.leadingAnchor.constraint(equalTo: textField.leadingAnchor).isActive = true bottomLine.trailingAnchor.constraint(equalTo: textField.trailingAnchor).isActive = true bottomLine.bottomAnchor.constraint(equalTo: textField.bottomAnchor).isActive = true bottomLine.heightAnchor.constraint(equalToConstant: 1).isActive = true bottomLine.backgroundColor = UIColor(red: 0.39, green: 0.70, blue: 0.73, alpha: 1.00) textField.borderStyle = .none } @IBAction func loginActionButton(_ sender: Any) { let users = Users.getUsers() for user in users{ if user.email == emailTextField.text && user.password == <PASSWORD> { performSegue(withIdentifier: "loginSegue", sender: nil) } } } } <file_sep>// // NavigationController.swift // SpiltMilk // // Created by <NAME> on 28/04/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit class NavigationController: UINavigationController{ override func viewDidLoad() { } } <file_sep>// // ModelCategorias.swift // SpiltMilk // // Created by <NAME> on 28/04/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation <file_sep>// // usersModel.swift // SpiltMilk // // Created by <NAME> on 06/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation // its the same from UserProfileModel //struct User{ // var userName: String // var email: String // var password: String // init(userName: String, email: String, password: String) { // self.userName = userName // self.email = email // self.password = <PASSWORD> // } //} struct Users{ static func getUsers() -> [User]{ var users: [User] = [] users.append(User(userName:"admin", email: "admin", password: "<PASSWORD>")) return users } } <file_sep>// // CommentCell.swift // SpiltMilk // // Created by <NAME> on 06/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class CommentCell: UITableViewCell { //MARK: - IBOutlets @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var profileImage: UIImageView! @IBOutlet weak var line: UIView! @IBOutlet weak var commentText: UILabel! @IBOutlet weak var likeNumber: UILabel! // set the nib's name. static func identifier() -> String{ return "CommentCell" } // when nib starts this configurations will be applied. override func awakeFromNib() { super.awakeFromNib() profileImage.layer.cornerRadius = profileImage.frame.width/2 line.layer.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) } // return created nib. static func nib() -> UINib{ return UINib(nibName: CommentCell.identifier(), bundle: nil) } // initialize nib components. func configureCell(name:String, image: UIImage, text: String){ nameLabel.text = name profileImage.image = image commentText.text = text } @IBAction func likeButtonn(_ sender: UIButton) { sender.setImage(UIImage(systemName: "heart.fill"), for: .selected) sender.setImage(UIImage(systemName: "heart"), for: .normal) guard let likes = likeNumber.text, var totalDeLikes = Int(likes) else {return} if sender.isSelected { sender.isSelected = false totalDeLikes -= 1 likeNumber.text = String(totalDeLikes) } else { sender.isSelected = true totalDeLikes += 1 likeNumber.text = String(totalDeLikes) } } } <file_sep>// // posts.swift // mockPosts // // Created by <NAME> on 29/04/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct Post{ var username: String var userPhoto: String var date: String var postImageName: String var postDescription: String init(username: String, userPhoto: String, date: String, postImageName: String, postDescription: String){ self.username = username self.userPhoto = userPhoto self.date = date self.postImageName = postImageName self.postDescription = postDescription } } struct PostSection{ //var posts: [Post] //inserir aqui a leitura do Json static func getPosts() -> [Post]{ var posts = [Post]() posts.append(Post(username: "João da Silva", userPhoto: "joao", date: "29/04/2020", postImageName: "post", postDescription: "kashdkajshdkajs dkajsdkajshdkajshda kajshdkas hdkajhsdkajshdka jsd")) posts.append(Post(username: "Josefino Arruda", userPhoto: "joao", date: "19/04/2017", postImageName: "post", postDescription: "kashdkajshdkajs dkajsdkajshdkajshda kajshdkas hdkajhsdkajshdka jsd")) posts.append(Post(username: "Marcos da Silva", userPhoto: "joao", date: "09/04/2020", postImageName: "post", postDescription: "kashdkajshdkajs dkajsdkajshdkajshda kajshdkas hdkajhsdkajshdka jsd")) return posts } } //MARK: - MOCK POST //let description = "Meu bebê é um bebê muito bebê porque bebês são bebês. Além disso, eu gosto de bebês porque eles são bebês." // //var array: [Any] = [] // //for _ in 0...3 { // array.append(Post(username: "João da Silva", userPhoto: "joao", date: "27/11/2020", postImageName: "post", postDescription: description)) //} <file_sep>// // ProfileEditViewController.swift // SpiltMilk // // Created by <NAME> on 04/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class ProfileEditViewController: UIViewController { //MARK: - IBOutlets @IBOutlet weak var userImage: UIImageView! @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var newPasswordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() //MARK:- Keyboard goes up and down NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(sender:)), name: UIResponder.keyboardWillShowNotification, object: nil); NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(sender:)), name: UIResponder.keyboardWillHideNotification, object: nil); self.hideKeyboardWhenTappedAround() self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action:#selector(ProfileEditViewController.dismissKeyboard))) let textFields: [UITextField]! = [userNameTextField, emailTextField, passwordTextField, newPasswordTextField] textFields.forEach { configtextField(textField: $0) } func configtextField(textField: UITextField) { let bottomLine = UIView() textField.addSubview(bottomLine) bottomLine.translatesAutoresizingMaskIntoConstraints = false bottomLine.leadingAnchor.constraint(equalTo: textField.leadingAnchor).isActive = true bottomLine.trailingAnchor.constraint(equalTo: textField.trailingAnchor).isActive = true bottomLine.bottomAnchor.constraint(equalTo: textField.bottomAnchor).isActive = true bottomLine.heightAnchor.constraint(equalToConstant: 1).isActive = true bottomLine.backgroundColor = UIColor(red: 0.39, green: 0.70, blue: 0.73, alpha: 1.00) textField.borderStyle = .none } } override func viewDidLayoutSubviews() { userImage.image = UIImage(named:"joao") userImage.layer.cornerRadius = userImage.frame.width / 2 } @objc func keyboardWillShow(sender: NSNotification){ self.view.frame.origin.y = -150 } @objc func keyboardWillHide(sender: NSNotification){ self.view.frame.origin.y = 0 } func hideKeyboardWhenTappedAround(){ let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ProfileEditViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } @objc func dismissKeyboard(){ self.view.endEditing(true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let oldPassword = <PASSWORD>TextField.text ?? "" let userEdited = User(userName: userNameTextField.text ?? "" , email: emailTextField.text ?? "", password: <PASSWORD>TextField.text ?? "") let destinyViewController = segue.destination as! ProfileViewController destinyViewController.editedUser = userEdited destinyViewController.oldPassword = <PASSWORD> } } <file_sep>// // ProfileViewController.swift // SpiltMilk // // Created by <NAME> on 03/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class ProfileViewController: UIViewController { //MARK: - IBOutlets @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var logoutButton: UIButton! //MARK: - Variables var user = User(userName: "<NAME>", email: "<EMAIL>", password: "<PASSWORD>") var editedUser: User? var oldPassword: String? override func viewDidLoad() { super.viewDidLoad() userNameTextField.placeholder = user.userName emailTextField.placeholder = user.email passwordTextField.placeholder = user.password let textFields: [UITextField]! = [userNameTextField, emailTextField, passwordTextField] textFields.forEach { configtextField(textField: $0) } func configtextField(textField: UITextField) { textField.borderStyle = .none } logoutButton.backgroundColor = #colorLiteral(red: 0.3882352941, green: 0.7019607843, blue: 0.7333333333, alpha: 1) logoutButton.setTitleColor(.white, for: .normal) logoutButton.layer.cornerRadius = 20 } override func viewDidLayoutSubviews() { userImageView.image = UIImage(named:"joao") userImageView.layer.cornerRadius = userImageView.frame.width / 2 } } extension ProfileViewController{ @IBAction func cancelToProfile(_ segue: UIStoryboardSegue) { } @IBAction func saveProfile(_ segue: UIStoryboardSegue){ if(editedUser?.userName != ""){ user.userName = (editedUser?.userName ?? "") as String } if(editedUser?.email != ""){ user.email = (editedUser?.email ?? "") as String } if(editedUser?.password != "" && oldPassword == user.password){ user.password = (editedUser?.password ?? "") as String } viewDidLoad() } } <file_sep>// // PostsTableViewController.swift // mockPosts // // Created by <NAME> on 29/04/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit var posts = PostSection.getPosts() class PostsTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return posts.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostTableViewCell cell.userNameLabel.text = posts[indexPath.row].username cell.dateLabel.text = posts[indexPath.row].date cell.postImageView.image = UIImage(named: posts[indexPath.row].postImageName) cell.userImageView.image = UIImage(named: posts[indexPath.row].userPhoto) cell.postDescriptionLabel.text = posts[indexPath.row].postDescription return cell } } <file_sep>// // ControllerCategorias.swift // SpiltMilk // // Created by <NAME> on 28/04/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class CategoriasController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //navigationController?.navigationBar.shadowImage = UIImage() let search = UISearchController(searchResultsController: nil) // Declare the searchController self.navigationItem.searchController = search } } <file_sep> <h1 align="center">Welcome to Spilt Milk 🐮 👋</h1> > IOS application interface designed to be a community for people living with CMPA (cow's milk protein allergy). ![0](https://user-images.githubusercontent.com/32069720/87798690-b1768800-c822-11ea-9f1d-1be692b2fb92.jpeg) ## Authors 👤 **<NAME>** * Github: [@beacarlos](https://github.com/beacarlos) * LinkedIn: [<NAME>](https://www.linkedin.com/in/beatriz-carlos-936a07192/) 👤 **<NAME>** * Github: [@jhennyferOliveira](https://github.com/jhennyferOliveira) * LinkedIn: [<NAME>](https://www.linkedin.com/in/jhennyfer-oliveira-35452a1a7/) 👤 **<NAME>** * Github: [@hiagochagas](https://github.com/hiagochagas) * LinkedIn: [<NAME>](https://www.linkedin.com/in/hiago-chagas) 👤 **<NAME>** * Github: [@jessicaguiot](https://github.com/jessicaguiot) * LinkedIn: [<NAME>](https://www.linkedin.com/in/jéssica-guiot-araújo-40644b198) ## Show your support Give a ⭐️ if this project helped you! ## 📝 License Copyright © 2020 [<NAME>](https://github.com/beacarlos), [<NAME>](https://github.com/jhennyferOliveira), [<NAME>](https://github.com/jessicaguiot), [<NAME>](https://github.com/hiagochagas).<br /> This project is [Swift](https://github.com/beacarlos/Spilt-Milk/blob/dev/LICENSE) licensed. <file_sep>// // TabBarController.swift // SpiltMilk // // Created by <NAME> on 07/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit class TabBarController: UITabBarController { @IBOutlet weak var TabBar: UITabBar! override func viewDidLoad() { super.viewDidLoad() self.selectedIndex = 1; } } <file_sep>// // Post.swift // SpiltMilk // // Created by <NAME> on 30/04/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct Post{ var username: String var userPhoto: String var date: String var postImageName: String var postDescription: String init(username: String, userPhoto: String, date: String, postImageName: String, postDescription: String){ self.username = username self.userPhoto = userPhoto self.date = date self.postImageName = postImageName self.postDescription = postDescription } } struct PostSection{ //var posts: [Post] //inserir aqui a leitura do Json static func getPosts() -> [Post]{ var posts = [Post]() posts.append(Post(username: "João da Silva", userPhoto: "joao", date: "29/04/2020", postImageName: "post", postDescription: "kashdkajshdkajs dkajsdkajshdkajshda kajshdkas hdkajhsdkajshdka jsd")) posts.append(Post(username: "Josefino Arruda", userPhoto: "joao", date: "19/04/2017", postImageName: "post", postDescription: "kashdkajshdkajs dkajsdkajshdkajshda kajshdkas hdkajhsdkajshdka jsd")) posts.append(Post(username: "Marcos da Silva", userPhoto: "joao", date: "09/04/2020", postImageName: "post", postDescription: "kashdkajshdkajs dkajsdkajshdkajshda kajshdkas hdkajhsdkajshdka jsd")) return posts } } <file_sep>// // PostPublish.swift // SpiltMilk // // Created by <NAME> on 06/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit protocol PostPublishDelegate: class { func publish(post: postCell) } class PostPublishController: UIViewController { var posts = cellData weak var delegate: PostPublishDelegate? let textView = UITextView() override func viewDidLoad() { super.viewDidLoad() // text view textView.frame = CGRect(x: 0, y: 0, width: 200, height: 100) textView.backgroundColor = .white textView.text = "Escreva um comentário." textView.textColor = UIColor.lightGray view.addSubview(textView) // use auto layout to set my textview frame textView.translatesAutoresizingMaskIntoConstraints = false [textView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 66), textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8), textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8), textView.heightAnchor.constraint(equalToConstant: 50) ].forEach{ $0.isActive = true } textView.font = UIFont.preferredFont(forTextStyle: .body) textView.delegate = self textView.isScrollEnabled = false textViewDidChange(textView) //Looks for single or multiple taps. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard)) view.addGestureRecognizer(tap) } // Ação do botão de cancelar. @IBAction func dismissModal(_ sender: UIButton) { dismiss(animated: true, completion: nil) } // Ao clicar fora do keyboard ele some. @objc func dismissKeyboard() { view.endEditing(true) } // Publicar Post. @IBAction func pusblihPost(_ sender: UIButton) { if let texto = textView.text { if texto.count != 0 { let addNewPublich = postCell(tipo: 0, nomeUsuario: "Joao", imagemUsuario: UIImage(named: "joao")!, textPost: textView.text, imagemPost: nil) delegate?.publish(post: addNewPublich) } } dismiss(animated: true, completion: nil) } } extension PostPublishController : UITextViewDelegate { // função que deixa o tamanho automático de acordo com o que o usúario escrever. func textViewDidChange(_ textView: UITextView) { let size = CGSize(width: view.frame.width, height: .infinity) let estimatedSize = textView.sizeThatFits(size) textView.constraints.forEach { (constraint) in if constraint.firstAttribute == .height { constraint.constant = estimatedSize.height } } } // Retirando o placeholder. func textViewDidBeginEditing(_ textView: UITextView) { if textView.textColor == UIColor.lightGray { textView.text = nil textView.textColor = UIColor.black } } // Quando o usúario limpar o Text View. func textViewDidEndEditing(_ textView: UITextView) { if textView.text.isEmpty { textView.text = "Escreva um comentário." textView.textColor = UIColor.lightGray } } } <file_sep>// // CardsController.swift // SpiltMilk // // Created by <NAME> on 28/04/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class CardsCategorias: UIView { //MARK: - IBOutlets @IBOutlet weak var tituloCard: UILabel? @IBOutlet weak var imagemCard: UIImageView? //MARK: - Variables let nibName = "CardsCategorias" var contentView: UIView? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupXib() } init() { super.init(frame: .zero) setupXib() tituloCard?.text = "Categorias" imagemCard?.image = UIImage() } private func setupXib() { guard let view = loadViewFromNib() else { fatalError("Wrong xib name") } view.frame = self.bounds self.addSubview(view) contentView = view } func loadViewFromNib() -> UIView? { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: nibName, bundle: bundle) return nib.instantiate(withOwner: self, options: nil).first as? UIView } } <file_sep>// // CommentsModel.swift // SpiltMilk // // Created by <NAME> on 07/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit import Foundation struct commentCell{ let name: String let profileImage: UIImage! let text: String } var commentCellData: [commentCell] = [ commentCell(name: "<NAME>", profileImage: UIImage(named: "joana"), text: "Muito difícil essa situação, minha filha está completando ano e procurei uma pessoa na cidade que fizesse bolo para pessoas com APLV e não achei. Eu mesma tive de fazer. "), commentCell(name: "<NAME>", profileImage: UIImage(named: "jose"), text: "Os sintomas do meu filho ao ingerir algum desses alimentos são muito fortes, tenho que levá-lo urgente ao médico.") ] <file_sep>// // InitialController.swift // SpiltMilk // // Created by <NAME> on 04/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit enum tappedButton{ case signIn case register case guest } class InitialController : UIViewController{ //MARK: - IBOutlets @IBOutlet weak var welcomeText: UILabel! @IBOutlet weak var logoImage: UIImageView! @IBOutlet weak var registerButton: UIButton! @IBOutlet weak var logoTitle: UILabel! @IBOutlet weak var signInButton: UIButton! @IBOutlet weak var viewDetail: UIView! override func viewDidLoad() { viewDetail.layer.cornerRadius = 50 logoTitle.text = "Spilt Milk" welcomeText.text = "Discuta, aprenda e compartilhe experiências sobre a Alergia à Proteína do Leite de Vaca." styleSignInButton(button: signInButton) styleRegisterButton(button: registerButton) buttonAction(button: signInButton) buttonAction(button: registerButton) } override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: false) } func styleSignInButton(button: UIButton){ button.backgroundColor = #colorLiteral(red: 0.3882352941, green: 0.7019607843, blue: 0.7333333333, alpha: 1) button.setTitleColor(.white, for: .normal) button.layer.cornerRadius = 27 } func styleRegisterButton(button: UIButton){ button.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) button.setTitleColor(#colorLiteral(red: 0.3882352941, green: 0.7019607843, blue: 0.7333333333, alpha: 1) , for: .normal) button.layer.cornerRadius = 27 button.layer.borderColor = #colorLiteral(red: 0.3882352941, green: 0.7019607843, blue: 0.7333333333, alpha: 1) button.layer.borderWidth = 2 } func buttonAction(button: UIButton){ button.addTarget(self, action: #selector(updateView), for: .touchUpInside) } @objc func updateView(button: UIButton) { var tappedButton: tappedButton let buttonTitle = button.currentTitle if buttonTitle == "Register" { tappedButton = .register } else if buttonTitle == "Sign In"{ tappedButton = .signIn }else{ tappedButton = .guest } switch tappedButton { case .signIn: print("login") case .register: print("register") case .guest: print("guest") } } } extension InitialController{ @IBAction func cancelToInitial(_ segue: UIStoryboardSegue) { } } <file_sep>// // SmallPostTableViewCell.swift // SpiltMilk // // Created by <NAME> on 06/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class SmallPostTableViewCell: UITableViewCell { //MARK: - IBOutlets @IBOutlet weak var usuarioImageView: UIImageView! @IBOutlet weak var nomeUsuarioLabel: UILabel! @IBOutlet weak var textoPostLabel: UILabel! @IBOutlet weak var cardView: UIView! @IBOutlet weak var likesLabel: UILabel! @IBOutlet weak var commentButton: UIButton! //MARK: - IBActions @IBAction func favoritesButton(_ sender: UIButton) { sender.setImage(UIImage(systemName: "bookmark.fill"), for: .selected) sender.setImage(UIImage(systemName: "bookmark"), for: .normal) if sender.isSelected { sender.isSelected = false } else { sender.isSelected = true } } @IBAction func commentButton(sender: UIButton!){ } @IBAction func likesButton(_ sender: UIButton) { sender.setImage(UIImage(systemName: "heart.fill"), for: .selected) sender.setImage(UIImage(systemName: "heart"), for: .normal) guard let likes = likesLabel.text, var totalDeLikes = Int(likes) else {return} if sender.isSelected { sender.isSelected = false totalDeLikes -= 1 likesLabel.text = String(totalDeLikes) } else { sender.isSelected = true totalDeLikes += 1 likesLabel.text = String(totalDeLikes) } } override func awakeFromNib() { super.awakeFromNib() self.usuarioImageView.layer.cornerRadius = self.usuarioImageView.frame.size.width / 2 cardView.layer.cornerRadius = 10 cardView.layer.shadowColor = UIColor.black.cgColor cardView.layer.shadowOpacity = 0.2 cardView.layer.shadowOffset = CGSize(width: 0, height: 0) cardView.layer.shadowRadius = 4 } func setPostData(nomeUsuario: String, imagemUsuario: UIImage, textoPost: String){ self.nomeUsuarioLabel.text = nomeUsuario self.usuarioImageView.image = imagemUsuario self.textoPostLabel.text = textoPost } static func identifier() -> String { return "SmallPostTableViewCell" } static func nib() -> UINib { return UINib(nibName: SmallPostTableViewCell.identifier(), bundle: .main) } } <file_sep>// // RegisterController.swift // SpiltMilk // // Created by <NAME> on 04/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit class RegisterController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { //MARK: - IBOutlets @IBOutlet weak var userImageView: UIImageView! @IBOutlet var textFields: [UITextField]! @IBOutlet weak var nomeTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var senhaTextField: UITextField! @IBOutlet weak var cSenhaTextField: UITextField! @IBOutlet weak var checkBox: UIButton! @IBOutlet weak var signUpButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // desabilitar o dark mode. overrideUserInterfaceStyle = .light // Ativar segurança de texto no senha e confirmar senha. senhaTextField.isSecureTextEntry = true cSenhaTextField.isSecureTextEntry = true // User image view. userImageView.image = #imageLiteral(resourceName: "RegisterLogo") userImageView.layer.cornerRadius = signUpButton.frame.height / 2 // Deixar a sign button redonda. signUpButton.layer.cornerRadius = signUpButton.frame.height / 3 textFields.forEach { configtextField(textField: $0) } NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(sender:)), name: UIResponder.keyboardWillShowNotification, object: nil); NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(sender:)), name: UIResponder.keyboardWillHideNotification, object: nil); self.hideKeyboardWhenTappedAround() self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action:#selector(self.dismissKeyboard))) } override func viewWillDisappear(_ animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: false) } override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(false, animated: false) } func configtextField(textField: UITextField) { let bottomLine = CALayer() bottomLine.frame = CGRect(x: 0, y: textField.frame.height - 2, width: textField.frame.width, height: 2) bottomLine.backgroundColor = UIColor(red: 0.39, green: 0.70, blue: 0.73, alpha: 1.00).cgColor textField.borderStyle = .none textField.layer.addSublayer(bottomLine) } // adicionar o usuário ao model Users e direcioná-lo para o home. @IBAction func registerAction(_ sender: UIButton) { var users = Users.getUsers() guard let senha = senhaTextField.text, let csenha = cSenhaTextField.text, let nome = nomeTextField.text, let email = emailTextField.text, csenha.count != 0, senha.count != 0, email.count != 0, nome.count != 0 else { print("Campos vazios.") return } // verifica se as duas senhas estão iguais. if (senhaTextField.text == cSenhaTextField.text) { users.append(User(userName: nomeTextField.text!, email: emailTextField.text!, password: cSenhaTextField.text!)) performSegue(withIdentifier: "RegisterToHomeSegue", sender: nil) } else { print("Senha e confirmar senha não correspondem.") } } /* DataPiker */ // Ação do botão de selecionar uma imagem @IBAction func chooseImageAction(_ sender: UIButton) { // controlador de seleção de imagens. let imagePickerController = UIImagePickerController() let actionSheet = UIAlertController(title: "Selecione uma foto", message: "Escolhe uma foto.", preferredStyle: .actionSheet) imagePickerController.delegate = self // Opção da câmera actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction) in if UIImagePickerController.isSourceTypeAvailable(.camera) { imagePickerController.sourceType = .camera self.present(imagePickerController, animated: true, completion: nil) } else { print("Camera not available.") } })) // Opção da galeria actionSheet.addAction(UIAlertAction(title: "Galeira de fotos", style: .default, handler: { (action: UIAlertAction) in imagePickerController.sourceType = .photoLibrary self.present(imagePickerController, animated: true, completion: nil) })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(actionSheet, animated: true, completion: nil) } // Colocar a imagem selecionada no Image View func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { let image = info[UIImagePickerController.InfoKey(rawValue: UIImagePickerController.InfoKey.originalImage.rawValue)] as! UIImage userImageView.image = image userImageView.layer.cornerRadius = signUpButton.frame.height / 2 picker.dismiss(animated: true, completion: nil) } // Ao apertar cancelar func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } /* Keyboard */ // Subir o text field quando ativar o keyboard. @objc func keyboardWillShow(sender: NSNotification){ self.view.frame.origin.y = -150 } @objc func keyboardWillHide(sender: NSNotification){ self.view.frame.origin.y = 0 } func hideKeyboardWhenTappedAround(){ let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } @objc func dismissKeyboard(){ self.view.endEditing(true) } // Envia ao controlador de exibição quando o aplicativo recebe um aviso de memória. override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } <file_sep>// // CollectionViewCell.swift // SpiltMilk // // Created by <NAME> on 05/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class CollectionViewCell: UICollectionViewCell { //MARK: -IBOutlets //MARK: -IBActions override func awakeFromNib() { super.awakeFromNib() // Initialization code } static func identifier() -> String { return "CollectionViewCell" } static func nib() -> UINib { return UINib(nibName: CollectionViewCell.identifier(), bundle: nil) } } <file_sep>// // PostCollectionCell.swift // SpiltMilk // // Created by <NAME> on 05/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class PostCollectionCell: UICollectionViewCell { //MARK: - IBOutlets @IBOutlet weak var usuarioImageView: UIImageView! @IBOutlet weak var nomeUsuarioLabel: UILabel! @IBOutlet weak var postImageLabel: UIImageView? @IBOutlet weak var postTextLabel: UILabel! @IBOutlet weak var quantidadeLikesLabel: UILabel! //MARK: - IBActions @IBAction func buttonFavoritos(_ sender: UIButton) { sender.setImage(UIImage(systemName: "bookmark.fill"), for: .selected) sender.setImage(UIImage(systemName: "bookmark"), for: .normal) if sender.isSelected { sender.isSelected = false } else { sender.isSelected = true } } @IBAction func buttonLikes(_ sender: UIButton) { sender.setImage(UIImage(systemName: "heart.fill"), for: .selected) sender.setImage(UIImage(systemName: "heart"), for: .normal) guard let likes = quantidadeLikesLabel.text, var totalDeLikes = Int(likes) else {return} if sender.isSelected { sender.isSelected = false totalDeLikes -= 1 quantidadeLikesLabel.text = String(totalDeLikes) } else { sender.isSelected = true totalDeLikes += 1 quantidadeLikesLabel.text = String(totalDeLikes) } } //MARK: - Métodos. override func awakeFromNib() { super.awakeFromNib() self.usuarioImageView.layer.cornerRadius = self.usuarioImageView.frame.size.width / 2 } func setPostData(nomeUsuario: String, imagemUsuario: UIImage, imagemPost: UIImage?, textoPost: String){ self.nomeUsuarioLabel.text = nomeUsuario self.usuarioImageView.image = imagemUsuario self.postTextLabel.text = textoPost if let _ = imagemPost { self.postImageLabel?.image = imagemPost } else { self.postImageLabel?.isHidden = true } } //MARK: - Configurações XIB. static func identifier() -> String { return "PostCollectionCell" } static func nib() -> UINib { return UINib(nibName: PostCollectionCell.identifier(), bundle: nil) } } <file_sep>// // posts.swift // mockPosts // // Created by <NAME> on 29/04/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit //struct Post{ // var postType: Int // var username: String // var userPhoto: String // var date: String // var postImageName: UIImage? // var postDescription: String // var likesCount: Int // // init(username: String, userPhoto: String, date: String, postImageName: String, postDescription: String,likesCount: Int, type: Int){ // self.username = username // self.userPhoto = userPhoto // self.date = date // self.postImageName = UIImage(named: postImageName) ?? nil // self.postDescription = postDescription // self.likesCount = likesCount // self.postType = type // } //} //struct PostSection{ // //inserir aqui a leitura do Json // static func getPosts() -> [Post]{ // var posts = [Post]() // posts.append(Post(username: "João da Silva", userPhoto: "joao", date: "29/04/2020", postImageName: "post", postDescription: "kashdkajshdkajs dkajsdkajshdkajshda kajshdkas hdkajhsdkajshdka jsd",likesCount: 10, type: 1)) // posts.append(Post(username: "Josefin<NAME>", userPhoto: "joao", date: "19/04/2017", postImageName: "post", postDescription: "kashdkajshdkajs dkajsdkajshdkajshda kajshdkas hdkajhsdkajshdka jsd",likesCount: 10, type: 1)) // posts.append(Post(username: "Marcos da Silva", userPhoto: "joao", date: "09/04/2020", postImageName: "post", postDescription: "kashdkajshdkajs dkajsdkajshdkajshda kajshdkas hdkajhsdkajshdka jsd",likesCount: 10, type: 1)) // posts.append(Post(username: "Marcos da Silva", userPhoto: "joao", date: "09/04/2020", postImageName: "", postDescription: "kashdkajshdkajs dkajsdkajshdkajshda kajshdkas hdkajhsdkajshdka jsd",likesCount: 10, type: 0)) // // // return posts // } //} //struct postCell{ // let tipo: Int // let nomeUsuario: String // let imagemUsuario: UIImage // let textPost: String // let imagemPost: UIImage? //} // // // //let cellData : [postCell] = [ // postCell(tipo: 0, nomeUsuario: "<NAME>", imagemUsuario: UIImage(named: "user1")!, textPost: "Os oito alimentos mais alergênicos são: leite de vaca, soja, ovo, trigo, peixe, frutos do mar, amendoim.", imagemPost: nil), // postCell(tipo: 1, nomeUsuario: "<NAME>", imagemUsuario: UIImage(named: "user2")!, textPost: "Mudança nos costumes alimentares tem repercutido no estado nutricional das crianças e dos adolescentes.", imagemPost: UIImage(named: "post2")!), // postCell(tipo: 0, nomeUsuario: "<NAME>", imagemUsuario: UIImage(named: "user3")!, textPost: "O bebê que se alimenta exclusivamente de leite materno até os seis meses de vida está protegido contra diversas doenças.", imagemPost: nil), // postCell(tipo: 1, nomeUsuario: "<NAME>", imagemUsuario: UIImage(named: "user4")!, textPost: "Receita Empada de liquidificador. Sem leite, sem soja, sem ovo e sem trigo.", imagemPost: UIImage(named: "post1")!), // postCell(tipo: 0, nomeUsuario: "<NAME>", imagemUsuario: UIImage(named: "user5")!, textPost: "O consumo de alimentos pode levar o organismo a reagir de diferentes maneiras. Denomina-se reação adversa a um alimento, qualquer resposta clínica anormal seguida à ingestão de um alimento ou aditivo alimentar.", imagemPost: nil) //] // <file_sep>// // guestController.swift // SpiltMilk // // Created by <NAME> on 07/05/20. // Copyright © 2020 <NAME>. All rights reserved. // <file_sep>// // PostTableViewCell.swift // mockPosts // // Created by <NAME> on 29/04/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class PostTableViewCell: UITableViewCell { @IBOutlet weak var bgView: UIView! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var postImageView: UIImageView! @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var postDescriptionLabel: UILabel! @IBOutlet weak var likeButton: UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code //deixa a foto do usuário redonda userImageView.layer.cornerRadius = userImageView.frame.size.width / 2 // arredonda os cantos da bgview bgView.layer.cornerRadius = 10 //adiciona a sombra nos posts bgView.layer.shadowColor = UIColor.black.cgColor bgView.layer.shadowOpacity = 0.5 bgView.layer.shadowOffset = CGSize(width: 0, height: 0) bgView.layer.shadowRadius = 4 } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>// // CommentTableViewController.swift // SpiltMilk // // Created by <NAME> on 06/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit class CommentTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.register(CommentCell.nib(), forCellReuseIdentifier: CommentCell.identifier()) } // MARK: - Table view data source override func tableView(_: UITableView, numberOfRowsInSection: Int) ->Int{ return commentCellData.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CommentCell.identifier(), for: indexPath) as! CommentCell cell.configureCell(name: commentCellData[indexPath.row].name, image: commentCellData[indexPath.row].profileImage, text: commentCellData[indexPath.row].text) cell.selectionStyle = .none return cell } } <file_sep>// // RecoverPasswordViewController.swift // SpiltMilk // // Created by <NAME> on 05/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class RecoverPasswordViewController: UIViewController, UITextFieldDelegate { //MARK: - IBOutlets @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var enviarEmailButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.emailTextField.delegate = self customButton() customTextField() //View scroll up and down NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(sender:)), name: UIResponder.keyboardWillShowNotification, object: nil); NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(sender:)), name: UIResponder.keyboardWillHideNotification, object: nil); //Adicionando gesture para o teclado sair self.hideKeyboardWhenTappedAround() self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(RecoverPasswordViewController.dismissKeyboard))) } override func viewWillDisappear(_ animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: false) } override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(false, animated: false) } //MARK: - Métodos func customButton() { enviarEmailButton.layer.cornerRadius = 16 } func customTextField() { let textFieldColor = UIColor(red: 0.0, green: 131.0/255.0, blue: 143.0/255.0, alpha: 1) let bottomLine = CALayer() bottomLine.frame = CGRect(x: 0.0, y: 25, width: 263, height: 1.0) bottomLine.backgroundColor = textFieldColor.cgColor emailTextField.borderStyle = .none emailTextField.layer.addSublayer(bottomLine) } @objc func keyboardWillShow(sender: NSNotification){ self.view.frame.origin.y = -95 } @objc func keyboardWillHide(sender: NSNotification){ self.view.frame.origin.y = 0 } func hideKeyboardWhenTappedAround(){ let tap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(RecoverPasswordViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } @objc func dismissKeyboard(){ self.view.endEditing(true) } //MARK: - Text Field Delegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } <file_sep>// // UserProfile.swift // SpiltMilk // // Created by <NAME> on 03/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct User{ var userName: String var email: String var password: String init(userName: String, email: String, password: String) { self.userName = userName self.email = email self.password = <PASSWORD> } } <file_sep>// // FavoritesModel.swift // SpiltMilk // // Created by <NAME> on 06/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit struct postCell{ let tipo: Int let nomeUsuario: String let imagemUsuario: UIImage let textPost: String let imagemPost: UIImage? } var cellData : [postCell] = [ postCell(tipo: 0, nomeUsuario: "<NAME>", imagemUsuario: UIImage(named: "user1")!, textPost: "Os oito alimentos mais alergênicos são: leite de vaca, soja, ovo, trigo, peixe, frutos do mar, amendoim.", imagemPost: nil), postCell(tipo: 1, nomeUsuario: "<NAME>", imagemUsuario: UIImage(named: "user2")!, textPost: "Mudança nos costumes alimentares tem repercutido no estado nutricional das crianças e dos adolescentes.", imagemPost: UIImage(named: "post2")!), postCell(tipo: 0, nomeUsuario: "<NAME>", imagemUsuario: UIImage(named: "user3")!, textPost: "O bebê que se alimenta exclusivamente de leite materno até os seis meses de vida está protegido contra diversas doenças.", imagemPost: nil), postCell(tipo: 1, nomeUsuario: "<NAME>", imagemUsuario: UIImage(named: "user4")!, textPost: "Receita Empada de liquidificador. Sem leite, sem soja, sem ovo e sem trigo.", imagemPost: UIImage(named: "post1")!), postCell(tipo: 0, nomeUsuario: "<NAME>", imagemUsuario: UIImage(named: "user5")!, textPost: "O consumo de alimentos pode levar o organismo a reagir de diferentes maneiras. Denomina-se reação adversa a um alimento, qualquer resposta clínica anormal seguida à ingestão de um alimento ou aditivo alimentar.", imagemPost: nil) ] <file_sep>// // HomeViewController.swift // SpiltMilk // // Created by <NAME> on 02/05/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit //var posts = PostSection.getPosts() class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() //navigationController?.navigationBar.shadowImage = UIImage() let search = UISearchController(searchResultsController: nil) // Declare the searchController self.navigationItem.searchController = search navigationController?.navigationBar.backgroundColor = UIColor(red: 0.62, green: 0.96, blue: 0.94, alpha: 1.00) print("-------------------------------------------------",cellData[cellData.count-1]) tableView.delegate = self tableView.dataSource = self tableView.register(SmallPostTableViewCell.nib(), forCellReuseIdentifier: SmallPostTableViewCell.identifier()) tableView.register(LargePostTableViewCell.nib(), forCellReuseIdentifier: LargePostTableViewCell.identifier()) tableView.separatorStyle = UITableViewCell.SeparatorStyle.none } func commentScreenAction(_ sender: UIButton) { let storyboard = UIStoryboard(name: "CommentTableViewController", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "CommentTableViewController") as UIViewController self.present(vc, animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "addPost" { let destination = segue.destination as! PostPublishController destination.delegate = self } } //MARK: - Table View Data Source func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if cellData[indexPath.row].tipo == 0 { let postCell = tableView.dequeueReusableCell(withIdentifier: SmallPostTableViewCell.identifier(), for: indexPath) as! SmallPostTableViewCell postCell.selectionStyle = .none postCell.setPostData(nomeUsuario: cellData[indexPath.row].nomeUsuario, imagemUsuario: cellData[indexPath.row].imagemUsuario, textoPost: cellData[indexPath.row].textPost) postCell.commentButton.addTarget(self, action: #selector(test), for: .touchUpInside) return postCell } else { let postCell = tableView.dequeueReusableCell(withIdentifier: LargePostTableViewCell.identifier(), for: indexPath) as! LargePostTableViewCell postCell.selectionStyle = .none postCell.setPostDataLarge(nomeUsuario: cellData[indexPath.row].nomeUsuario, imagemUsuario: cellData[indexPath.row].imagemUsuario, imagemPost: cellData[indexPath.row].imagemPost!, textoPost: cellData[indexPath.row].textPost) postCell.commentLarge.addTarget(self, action: #selector(test), for: .touchUpInside) return postCell } } @objc func test(){ let storyboard = UIStoryboard(name: "CommentScreen", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "CommentScreen") as UIViewController self.present(vc, animated: true, completion: nil) } } extension HomeViewController: PostPublishDelegate { func publish(post: postCell) { tableView.beginUpdates() cellData.append(post) tableView.insertRows(at: [IndexPath.init(row: cellData.count-1, section: 0)], with: .automatic) tableView.endUpdates() } } extension UIApplication { var statusBarView: UIView? { if responds(to: Selector(("statusBar"))) { return value(forKey: "statusBar") as? UIView } return nil } }
3324f718bbbdab4b39cebe82a684046888db6a99
[ "Swift", "Markdown" ]
32
Swift
beacarlos/Spilt-Milk
ad94916a05cf54d9013ef0153e64e79bb10991cd
11354e02ee804b444d198372d5fa784c94a33f78
refs/heads/master
<file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { Actions, createEffect, ofType } from '@ngrx/effects'; import { of } from 'rxjs'; import { catchError, concatMap, debounceTime, map, switchMap, tap, } from 'rxjs/operators'; import { ITemplateSummaryDto, ITemplateWithIdDto, } from '../../shared/interfaces'; import { addTemplate, addTemplateFailure, addTemplateSuccess, deleteTemplate, deleteTemplateFailure, deleteTemplateSuccess, getTemplate, getTemplateFailure, getTemplates, getTemplatesFailure, getTemplatesSuccess, getTemplateSuccess, updateTemplate, updateTemplateFailure, updateTemplateSuccess, } from './actions'; @Injectable() export class Effects { private baseUrl = ''; private templateBaseUrl = this.baseUrl + '/api/templates-ngrx'; getTemplates$ = createEffect(() => this.actions$.pipe( ofType(getTemplates), debounceTime(200), switchMap(() => this.http.get<ITemplateWithIdDto[]>(this.templateBaseUrl).pipe( map((ts) => getTemplatesSuccess({ templates: ts.map( (t) => ({ id: t.id, templateName: t.templateName, entityTypeName: t.entityTypeName, } as ITemplateSummaryDto) ), }) ), catchError((error) => of(getTemplatesFailure({ errorMessage: this.handleError(error) })) ) ) ) ) ); getTemplate$ = createEffect(() => this.actions$.pipe( ofType(getTemplate), debounceTime(200), switchMap((props) => this.http .get<ITemplateWithIdDto>(this.templateBaseUrl + '/' + props.id) .pipe( map((t) => getTemplateSuccess({ template: t })), catchError((error) => of( getTemplateFailure({ errorMessage: this.handleError(error), }) ) ) ) ) ) ); addTemplate$ = createEffect(() => this.actions$.pipe( ofType(addTemplate), concatMap((props) => this.http .post<ITemplateWithIdDto>(this.templateBaseUrl, props.template) .pipe( concatMap((t) => [ addTemplateSuccess({ template: t }), getTemplates(), ]), catchError((error) => of( addTemplateFailure({ errorMessage: this.handleError(error), }) ) ) ) ) ) ); updateTemplate$ = createEffect(() => this.actions$.pipe( ofType(updateTemplate), concatMap((props) => this.http .put<void>(this.templateBaseUrl + '/' + props.id, props.template) .pipe( concatMap(() => [ updateTemplateSuccess({ template: { id: props.id, ...props.template }, }), getTemplates(), ]), catchError((error) => of( updateTemplateFailure({ errorMessage: this.handleError(error), }) ) ) ) ) ) ); deleteTemplate$ = createEffect(() => this.actions$.pipe( ofType(deleteTemplate), concatMap((props) => this.http.delete<void>(this.templateBaseUrl + '/' + props.id).pipe( concatMap(() => [deleteTemplateSuccess(), getTemplates()]), catchError((error) => of( deleteTemplateFailure({ errorMessage: this.handleError(error), }) ) ) ) ) ) ); addTemplateSuccess$ = createEffect( () => this.actions$.pipe( ofType(addTemplateSuccess), tap((props) => this.router.navigate(['/templates-ngrx', props.template.id]) ) ), { dispatch: false } ); deleteTemplateSuccess$ = createEffect( () => this.actions$.pipe( ofType(deleteTemplateSuccess), tap(() => this.router.navigate(['/templates-ngrx'])) ), { dispatch: false } ); constructor( private actions$: Actions, private http: HttpClient, private router: Router ) {} // tslint:disable: no-any private handleError(err: any): string { let errorMessage: string; if (err.error instanceof ErrorEvent) { errorMessage = `An error occurred: ${err.error.message}`; } else { errorMessage = `Backend returned code ${err.status}: ${err.message}`; } return errorMessage; } // tslint:enable: no-any } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; import { ITemplateWithIdDto } from '../../shared/interfaces'; import { addTemplate, deleteTemplate, getEmptyTemplate, getTemplate, updateTemplate, } from '../store/actions'; import { AppState, selectTemplate, selectTemplateErrorMessage, selectTemplateLoading, } from '../store/selectors'; @Component({ selector: 'rdt-template-add-edit', templateUrl: './template-add-edit.component.html', styleUrls: ['./template-add-edit.component.scss'], }) export class TemplateAddEditComponent implements OnInit { template$!: Observable<ITemplateWithIdDto | null>; loading$!: Observable<boolean>; errorMessage$!: Observable<string | null>; constructor( private route: ActivatedRoute, private readonly store: Store<AppState> ) {} ngOnInit(): void { this.template$ = this.store.select(selectTemplate); this.loading$ = this.store.select(selectTemplateLoading); this.errorMessage$ = this.store.select(selectTemplateErrorMessage); this.route.params.subscribe((params: Params) => { if (params.id !== undefined) { const id = +params.id; this.store.dispatch(getTemplate({ id })); } else { this.store.dispatch(getEmptyTemplate()); } }); } onSubmit(template: ITemplateWithIdDto): void { if (template?.id) { this.store.dispatch(updateTemplate({ id: template.id, template })); } else if (template) { this.store.dispatch(addTemplate({ template })); } } onDelete(id: number): void { this.store.dispatch(deleteTemplate({ id })); } } <file_sep>import { createAction, props } from '@ngrx/store'; import { ITemplateDto, ITemplateSummaryDto, ITemplateWithIdDto, } from '../../shared/interfaces'; export const getTemplates = createAction('[Templates] Get'); export const getTemplatesSuccess = createAction( '[Templates] Get Success', props<{ templates: ITemplateSummaryDto[] }>() ); export const getTemplatesFailure = createAction( '[Templates] Get Failure', props<{ errorMessage: string }>() ); export const getEmptyTemplate = createAction('[Template] Get Empty'); export const getTemplate = createAction( '[Template] Get', props<{ id: number }>() ); export const getTemplateSuccess = createAction( '[Template] Get Success', props<{ template: ITemplateWithIdDto }>() ); export const getTemplateFailure = createAction( '[Template] Get Failure', props<{ errorMessage: string }>() ); export const addTemplate = createAction( '[Template] Add', props<{ template: ITemplateDto }>() ); export const addTemplateSuccess = createAction( '[Template] Add Success', props<{ template: ITemplateWithIdDto }>() ); export const addTemplateFailure = createAction( '[Template] Add Failure', props<{ errorMessage: string }>() ); export const updateTemplate = createAction( '[Template] Update', props<{ id: number; template: ITemplateDto }>() ); export const updateTemplateSuccess = createAction( '[Template] Update Success', props<{ template: ITemplateWithIdDto }>() ); export const updateTemplateFailure = createAction( '[Template] Update Failure', props<{ errorMessage: string }>() ); export const deleteTemplate = createAction( '[Template] Delete', props<{ id: number }>() ); export const deleteTemplateSuccess = createAction('[Template] Delete Success'); export const deleteTemplateFailure = createAction( '[Template] Delete Failure', props<{ errorMessage: string }>() ); <file_sep>import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { FormUtilsService } from '../../core/services'; import { ITemplateWithIdDto } from '../../shared/interfaces'; @Component({ selector: 'rdt-template-add-edit-form', templateUrl: './template-add-edit-form.component.html', styleUrls: ['./template-add-edit-form.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TemplateAddEditFormComponent implements OnInit, OnChanges { @Input() template: ITemplateWithIdDto | null = null; @Output() submitEvent = new EventEmitter(); @Output() deleteEvent = new EventEmitter(); readOnly = true; fg: FormGroup; constructor( private fb: FormBuilder, private formUtilsService: FormUtilsService ) { this.fg = this.fb.group({ templateName: this.fb.control('', Validators.required), }); } ngOnInit(): void {} ngOnChanges(changes: SimpleChanges): void { if (changes?.template) { const template: ITemplateWithIdDto = changes?.template?.currentValue; this.readOnly = (template?.id || 0) > 0; this.formUtilsService.setValues(this.fg, template); } } onEdit(): void { this.readOnly = false; } onCancel(): void { this.readOnly = true; this.formUtilsService.setValues(this.fg, this.template); } onSubmit(): void { this.formUtilsService.validate(this.fg); if (this.template && this.fg.valid) { const submit: ITemplateWithIdDto = { ...this.template, templateName: this.fg.get('templateName')?.value, }; this.submitEvent.emit(submit); const id = this.template?.id; if (id) { this.readOnly = true; } } } onDelete(): void { const id = this.template?.id; if (id) { this.deleteEvent.emit(id); } } } <file_sep>import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { EffectsModule } from '@ngrx/effects'; import { StoreModule } from '@ngrx/store'; import { StoreDevtoolsModule } from '@ngrx/store-devtools'; import { environment } from '../../environments/environment'; import { SharedModule } from '../shared/shared.module'; import { Effects } from './store/effects'; import * as template from './store/template-reducers'; import * as templates from './store/templates-reducers'; import { TemplateAddEditFormComponent } from './template-add-edit-form/template-add-edit-form.component'; import { TemplateAddEditComponent } from './template-add-edit/template-add-edit.component'; import { TemplateListComponent } from './template-list/template-list.component'; import { TemplatesComponent } from './templates/templates.component'; @NgModule({ declarations: [ TemplateAddEditComponent, TemplateListComponent, TemplatesComponent, TemplateAddEditFormComponent, ], imports: [ CommonModule, SharedModule, RouterModule.forChild([ { path: '', component: TemplatesComponent, children: [ { path: '', component: TemplateAddEditComponent, }, { path: ':id', component: TemplateAddEditComponent, }, ], }, ]), StoreModule.forRoot({ templates: templates.reducer, template: template.reducer, }), !environment.production ? StoreDevtoolsModule.instrument() : [], EffectsModule.forRoot([Effects]), ], }) export class TemplatesNgrxModule {} <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { Observable } from 'rxjs'; import { DataService } from '../../core/services'; import { IObsWithStatusResult, ITemplateWithIdDto, } from '../../shared/interfaces'; @Component({ selector: 'rdt-template-add-edit', templateUrl: './template-add-edit.component.html', styleUrls: ['./template-add-edit.component.scss'], }) export class TemplateAddEditComponent implements OnInit { templateWithStatus$!: Observable<IObsWithStatusResult<ITemplateWithIdDto>>; constructor( private route: ActivatedRoute, private router: Router, private dataService: DataService ) {} ngOnInit(): void { this.templateWithStatus$ = this.dataService.templateWithStatus$; this.route.params.subscribe((params: Params) => { if (params.id !== undefined) { const id = +params.id; this.dataService.selectTemplate(id); } else { this.dataService.selectTemplate(0); } }); } onSubmit(template: ITemplateWithIdDto): void { if (template?.id) { this.dataService.updateTemplate(template.id, template).subscribe(); } else if (template) { this.dataService.addTemplate(template).subscribe((t) => { this.router.navigate(['/templates', t.id]); }); } } onDelete(id: number): void { this.dataService .deleteTemplate(id) .subscribe(() => this.router.navigate(['/templates'])); } } <file_sep>import { Injectable } from '@angular/core'; import { AbstractControl, FormArray, FormGroup } from '@angular/forms'; // tslint:disable: no-any @Injectable({ providedIn: 'root', }) export class FormUtilsService { constructor() {} /** * Attach a factory function to a FormArray so that we can automatically create child controls inside `setValues()` */ setChildControlFactory( control: FormArray, factory: () => AbstractControl ): void { (control as any).__createChildControl = factory; } createChildControl(control: FormArray): AbstractControl { return (control as any).__createChildControl(); } /** * Recursively set the values of a form control, creating new children FormArrays as necessary */ setValues(control: AbstractControl | null, value: any): void { if (control && control instanceof FormGroup) { if (value != null) { Object.keys(value).forEach((name) => { if (control.contains(name)) { this.setValues(control.get(name), value[name]); } }); } } else if (control && control instanceof FormArray) { const length = value ? value.length : 0; // Remove excess controls from the array while (control.length > length) { control.removeAt(control.length - 1); } // Add missing controls while (control.length < length) { control.push(this.createChildControl(control)); } // Update all the values in the array for (let i = 0; i < length; ++i) { this.setValues(control.at(i), value[i]); } } else if (control) { control.setValue(value); } } reset( control: AbstractControl, markAsPristineOpts?: { onlySelf?: boolean; }, markAsUntouchedOpts?: { onlySelf?: boolean; } ): void { if (control instanceof FormGroup) { control.markAsPristine(markAsPristineOpts); control.markAsUntouched(markAsUntouchedOpts); (Object as any).values(control.controls).forEach((c: AbstractControl) => { this.reset(c, markAsPristineOpts, markAsUntouchedOpts); }); } else if (control instanceof FormArray) { control.markAsPristine(markAsPristineOpts); control.markAsUntouched(markAsUntouchedOpts); control.controls.forEach((c) => { this.reset(c, markAsPristineOpts, markAsUntouchedOpts); }); } else { control.markAsPristine(markAsPristineOpts); control.markAsUntouched(markAsUntouchedOpts); } } validate( control: AbstractControl, markAsTouchedOpts?: { onlySelf?: boolean; }, updateValueAndValidityOpts?: { onlySelf?: boolean; emitEvent?: boolean; } ): void { if (control instanceof FormGroup) { control.markAsTouched(markAsTouchedOpts); control.updateValueAndValidity(updateValueAndValidityOpts); (Object as any).values(control.controls).forEach((c: AbstractControl) => { this.validate(c, markAsTouchedOpts, updateValueAndValidityOpts); }); } else if (control instanceof FormArray) { control.markAsTouched(markAsTouchedOpts); control.updateValueAndValidity(updateValueAndValidityOpts); control.controls.forEach((c) => { this.validate(c, markAsTouchedOpts, updateValueAndValidityOpts); }); } else { control.markAsTouched(markAsTouchedOpts); control.updateValueAndValidity(updateValueAndValidityOpts); } } } <file_sep>import { ITemplateDto } from './template-dto'; export interface ITemplateWithIdDto extends ITemplateDto { id: number; } <file_sep>import { Action, createReducer, on } from '@ngrx/store'; import { ITemplateWithIdDto } from '../../shared/interfaces'; import * as Actions from './actions'; export interface TemplateState { template: ITemplateWithIdDto; loading: boolean; errorMessage: string | null; } export const initialState: TemplateState = { template: {} as ITemplateWithIdDto, loading: false, errorMessage: null, }; const templateReducer = createReducer( initialState, on(Actions.getEmptyTemplate, (state) => ({ ...state, template: {} as ITemplateWithIdDto, })), on(Actions.getTemplate, (state) => ({ ...state, loading: true, })), on(Actions.getTemplateSuccess, (state, { template }) => ({ ...state, template, loading: false, })), on(Actions.getTemplateFailure, (state, { errorMessage }) => ({ ...state, errorMessage, loading: false, })), on(Actions.addTemplateSuccess, (state, { template }) => ({ ...state, template, })), on(Actions.addTemplateFailure, (state, { errorMessage }) => ({ ...state, errorMessage, })), on(Actions.updateTemplateSuccess, (state, { template }) => ({ ...state, template, })), on(Actions.updateTemplateFailure, (state, { errorMessage }) => ({ ...state, errorMessage, })), on(Actions.deleteTemplateSuccess, (state) => ({ ...state, template: {} as ITemplateWithIdDto, })), on(Actions.deleteTemplateFailure, (state, { errorMessage }) => ({ ...state, errorMessage, })) ); export function reducer( state: TemplateState | undefined, action: Action ): TemplateState { return templateReducer(state, action); } <file_sep>export interface IObsWithStatusResult<T> { loading?: boolean; value?: T; error?: string; } <file_sep>import { createSelector } from '@ngrx/store'; import { TemplateState } from './template-reducers'; import { TemplatesState } from './templates-reducers'; export interface AppState { templates: TemplatesState; template: TemplateState; } export const selectTemplatesState = (state: AppState) => state.templates; export const selectTemplateState = (state: AppState) => state.template; export const selectTemplates = createSelector( selectTemplatesState, (state: TemplatesState) => state.templates ); export const selectTemplatesLoading = createSelector( selectTemplatesState, (state: TemplatesState) => state.loading ); export const selectTemplatesErrorMessage = createSelector( selectTemplatesState, (state: TemplatesState) => state.errorMessage ); export const selectTemplate = createSelector( selectTemplateState, (state: TemplateState) => state.template ); export const selectTemplateLoading = createSelector( selectTemplateState, (state: TemplateState) => state.loading ); export const selectTemplateErrorMessage = createSelector( selectTemplateState, (state: TemplateState) => state.errorMessage ); <file_sep>import { ChangeDetectionStrategy, Component, Input, OnInit, } from '@angular/core'; import { Router } from '@angular/router'; import { ITemplateSummaryDto } from '../../shared/interfaces'; @Component({ selector: 'rdt-template-list', templateUrl: './template-list.component.html', styleUrls: ['./template-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TemplateListComponent implements OnInit { @Input() public templates: ITemplateSummaryDto[] | null = null; root = 'Templates-NgRx'; constructor(private router: Router) {} ngOnInit(): void {} // tslint:disable-next-line: no-any isActive(currentRoute: any[], exact = true): boolean { return this.router.isActive(this.router.createUrlTree(currentRoute), exact); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { DataService } from '../../core/services'; import { ITemplateSummaryDto } from '../../shared/interfaces'; @Component({ selector: 'rdt-templates', templateUrl: './templates.component.html', styleUrls: ['./templates.component.scss'], }) export class TemplatesComponent implements OnInit { public templates$: Observable<ITemplateSummaryDto[]>; constructor(private dataService: DataService) { this.templates$ = this.dataService.templates$; } ngOnInit(): void {} } <file_sep>import { ITemplateChannelDto } from './template-channel-dto'; export interface ITemplateDto { templateName: string; entityTypeName: string; modelName: string; modelVersion: number | null; templateChannels: ITemplateChannelDto[]; } <file_sep>export * from './obs-with-status-result'; export * from './template-channel-dto'; export * from './template-dto'; export * from './template-summary-dto'; export * from './template-with-id-dto'; <file_sep>import { Component, OnInit } from '@angular/core'; import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { ITemplateSummaryDto } from '../../shared/interfaces'; import { getTemplates } from '../store/actions'; import { AppState, selectTemplates } from '../store/selectors'; @Component({ selector: 'rdt-templates', templateUrl: './templates.component.html', styleUrls: ['./templates.component.scss'], }) export class TemplatesComponent implements OnInit { public templates$: Observable<ITemplateSummaryDto[]>; constructor(private readonly store: Store<AppState>) { this.templates$ = this.store .select(selectTemplates) .pipe(tap((ts) => console.log(JSON.stringify(ts)))); } ngOnInit(): void { this.store.dispatch(getTemplates()); } } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { BehaviorSubject, concat, Observable, of, throwError } from 'rxjs'; import { catchError, debounceTime, distinctUntilChanged, map, switchMap, tap, } from 'rxjs/operators'; import { IObsWithStatusResult, ITemplateDto, ITemplateSummaryDto, ITemplateWithIdDto, } from '../../shared/interfaces'; @Injectable({ providedIn: 'root', }) export class DataService { private baseUrl = ''; private templateBaseUrl = this.baseUrl + '/api/templates'; private selectedTemplateSubject = new BehaviorSubject<number>(0); selectedTemplateAction$ = this.selectedTemplateSubject.asObservable(); private refreshSubject = new BehaviorSubject<boolean>(true); refreshAction$ = this.refreshSubject.asObservable(); templates$ = this.refreshAction$.pipe( debounceTime(200), switchMap(() => this.http.get<ITemplateWithIdDto[]>(this.templateBaseUrl).pipe( map((ts) => ts.map( (t) => ({ id: t.id, templateName: t.templateName, entityTypeName: t.entityTypeName, } as ITemplateSummaryDto) ) ), catchError(this.handleError) ) ) ); template$ = this.selectedTemplateAction$.pipe( debounceTime(200), distinctUntilChanged(), switchMap((id) => id === 0 ? of({} as ITemplateWithIdDto) : this.http .get<ITemplateWithIdDto>(this.templateBaseUrl + '/' + id) .pipe(catchError(this.handleError)) ) ); templateWithStatus$: Observable< IObsWithStatusResult<ITemplateWithIdDto> > = this.selectedTemplateAction$.pipe( debounceTime(200), distinctUntilChanged(), switchMap((id) => concat( of({ loading: true } as IObsWithStatusResult<ITemplateWithIdDto>), id === 0 ? of({ loading: false, value: {} } as IObsWithStatusResult< ITemplateWithIdDto >) : this.http .get<ITemplateWithIdDto>(this.templateBaseUrl + '/' + id) .pipe( map( (value) => ({ loading: false, value } as IObsWithStatusResult< ITemplateWithIdDto >) ), catchError(this.handleErrorWrapped) ) ) ) ); constructor(private http: HttpClient) {} selectTemplate(id: number): void { this.selectedTemplateSubject.next(id); } addTemplate(template: ITemplateDto): Observable<ITemplateWithIdDto> { return this.http .post<ITemplateWithIdDto>(this.templateBaseUrl, template) .pipe( tap(() => this.refreshSubject.next(true)), catchError(this.handleError) ); } updateTemplate(id: number, template: ITemplateDto): Observable<void> { return this.http.put<void>(this.templateBaseUrl + '/' + id, template).pipe( tap(() => this.refreshSubject.next(true)), catchError(this.handleError) ); } deleteTemplate(id: number): Observable<void> { return this.http.delete<void>(this.templateBaseUrl + '/' + id).pipe( tap(() => this.refreshSubject.next(true)), catchError(this.handleError) ); } // tslint:disable: no-any private handleError(err: any): Observable<never> { let errorMessage: string; if (err.error instanceof ErrorEvent) { errorMessage = `An error occurred: ${err.error.message}`; } else { errorMessage = `Backend returned code ${err.status}: ${err.message}`; } console.error(err); return throwError(errorMessage); } private handleErrorWrapped(err: any): Observable<IObsWithStatusResult<any>> { let errorMessage: string; if (err.error instanceof ErrorEvent) { errorMessage = `An error occurred: ${err.error.message}`; } else { errorMessage = `Backend returned code ${err.status}: ${err.message}`; } console.error(err); return of({ error: errorMessage } as IObsWithStatusResult<any>); } // tslint:enable: no-any } <file_sep>export interface ITemplateChannelDto { channelName: string; body: string; } <file_sep>export interface ITemplateSummaryDto { id: number; templateName: string; entityTypeName: string; } <file_sep>import { Action, createReducer, on } from '@ngrx/store'; import { ITemplateSummaryDto } from '../../shared/interfaces'; import * as Actions from './actions'; export interface TemplatesState { templates: ITemplateSummaryDto[]; loading: boolean; errorMessage: string | null; } export const initialState: TemplatesState = { templates: [], loading: false, errorMessage: null, }; const templatesReducer = createReducer( initialState, on(Actions.getTemplates, (state) => ({ ...state, loading: true, })), on(Actions.getTemplatesSuccess, (state, { templates }) => ({ ...state, templates, loading: false, })), on(Actions.getTemplatesFailure, (state, { errorMessage }) => ({ ...state, errorMessage, loading: false, })) ); export function reducer( state: TemplatesState | undefined, action: Action ): TemplatesState { return templatesReducer(state, action); }
5b9677e9e6dc03166cc39df76d0064ed8e987fa9
[ "TypeScript" ]
20
TypeScript
jrdutton/rdt-templates
9d87f01c47a5999a5a8f86c207b45449f1936078
da234429ce03e4d606a8695cb30eb8935c14a6b8
refs/heads/master
<file_sep>""" Student: <NAME> ID: 316011683 Assignment no. 4 Program: grades.py """ def get_students(fileName): '''return a students dictionary sorted by id keys ''' students={} s = open(fileName, "r") #iterate throught every line, split the data into a list for c in s: ls=c.split() if(len(ls)<2): raise Exception('There is an invalid id') students[int(ls[0])]=' '.join(ls[1::]) return students def get_grades(fileName): '''return a grades dictionary sorted by id keys''' #{31829829: [39,90,80]} grades = {} g = open(fileName, 'r') for line in g: ls=line.split(' ') student_id=int(ls[0]) grades[student_id] = [int(ls[i]) for i in range(1,len(ls)) if ls[i].isnumeric()] return grades def valid_id(dict): for Id in dict.keys(): if (len(Id)!= 9) or not str(Id).isnumeric: raise Exception ('There is an invalid id') def merge_dict(dict_A, dict_B): merge_dict = {} for A in dict_A.keys(): for B in dict_B.keys(): if A == B: {dict_A[A]:dict_B[B] for k,v in merge_dict} return merge_dict def avarege_grades(fileName): grades = open('grades.txt', 'r') for line in grades: line_ls = line.splite() gradesOfStudents = line_ls[1::] sum_grades = 0 for grade in gradesOfStudents: sum_grades += int(grade) avg_grades = sum_grades / len(gradesOfStudents) return avg_grades def main(): grades = get_grades('grades.txt') students = get_students('students.txt') merge =merge_dict(students,grades) """ { 575656757:{"name": <NAME>, "average":90}, 698234:{"name": madona, "average":75}, } """ main() <file_sep>""" Student: <NAME> ID: 316011683 Assignment no. 4 Program: vigenere.py """ # sum the new value of latin letters def add_letters(str1: str , str2 : str): if len(str1) != 1 or len(str2) != 1: return None if not (str1.isalpha and str2.isalpha): #de morgan's laws return None str1 = str1.lower() str2 = str2.lower() c = ord('a') #set a new value for the letters with ASCII return chr((((ord(str1[0]) - c) + (ord(str2[0]) - c)) % 26) + c) # marge 2 strings to one that sum all the values def add_string(str1 : str, str2 :str): if not (str1.isalpha and str2.isalpha): #de morgan's laws return None n_str = '' for i in range(min(len(str1), len(str2))): c = add_letters(str1[i], str2[i]) if c == None: return None n_str += c return n_str def vigenere_encrypt(s: str, k: str): if not k.isalpha(): #why not false return None n_s = [c for c in s if c.isalpha()] s = ''.join([str(c) for c in n_s]) n = ((len(s)//len(k))+1) t = str(k*n) return add_string(s, t) def vigenere_decrypt(w: str, k: str): n = ((len(w)//len(k))+1) t = str(k*n) a = ord('a') t = [chr(( ((ord(c) - a) * -1) + 26) + a ) for c in t] t = ''.join([str(c) for c in t]) return add_string(w,t) def main(): r1 = (input('Please choose - e or d ? ')) key = (input('Enter your key: ')) fileName = (input('Enter the file name: ')) if r1 == 'e': with open (f'{fileName}.txt', 'r') as rf: s = rf.read() encrypt = vigenere_encrypt(s, key) with open (f'{fileName}.vig', 'w') as wf: wf.write(encrypt) elif r1 == 'd': with open(f'{fileName}.vig', 'r') as rf: s = rf.read() decrypt = vigenere_decrypt(s, key) print(decrypt) main() <file_sep>""" Student: <NAME> ID: 318298296 Assignment no. 6 Program: minesweeper.py This is the mine-sweeper game """ #make all the classes as the conztnsus #input the board data from the user #add comments import random class MSSquare: """ minesweeper square block class """ def __init__(self, hasMine=False, neighborMines=0): self.__has_mine = hasMine self.__hidden = True self.__neighbor_mines = neighborMines """ all the attributes builders """ @property def neighbor_mines(self): return self.__neighbor_mines @neighbor_mines.setter def neighbor_mines(self, value): self.__neighbor_mines=value @property def hidden(self): return self.__hidden @hidden.setter def hidden(self, value): self.__hidden=value @property def has_mine(self): return self.__has_mine @has_mine.setter def has_mine(self, value): self.__has_mine=value def print_square(self): """ prints the value=num of mines of each class object """ if(self.__hidden): print(" ", end="") else: if(self.__has_mine): print(" X ", end="") else: print(" "+str(self.__neighbor_mines)+" ", end="") class MSBoard: """ This class represents a board object """ def __init__(self, boardWidth=6,numOfMines=4): self.__board_width = boardWidth self.__num_of_mines = numOfMines self.__board_data=[[MSSquare() for x in range(0,boardWidth)] for y in range(0,boardWidth)] for i in range(0,self.__num_of_mines): self.spred_mine() self.initialize_board() @property def board_width(self): return self.__board_width @board_width.setter def board_width(self, value): self.__board_width=value @property def num_of_mines(self): return self.__num_of_mines @num_of_mines.setter def num_of_mines(self, value): self.__num_of_mines=value @property def board_data(self): return self.__board_data def spred_mine(self): """ Spred the mine randomly """ mineX= random.randint(0, self.board_width-1) mineY= random.randint(0, self.board_width-1) if(self.board_data[mineX][mineY].has_mine==True): self.spred_mine() else: self.board_data[mineX][mineY].has_mine=True; def initialize_board(self): """ Go all over the board and set the right value to each square """ #self.print_board() for x in range(0,len(self.board_data)): for y in range(0,len(self.board_data[0])): if(self.board_data[x][y].has_mine): self.set_neighbors(x,y) def set_neighbors(self,x,y): """ If a particular square has a mine, it informes all of its neighbors to increase their value by 1 """ self.set_square_num(x,y-1) self.set_square_num(x,y+1) self.set_square_num(x-1,y-1) self.set_square_num(x+1,y-1) self.set_square_num(x-1,y+1) self.set_square_num(x+1,y+1) self.set_square_num(x-1,y) self.set_square_num(x+1,y) def set_square_num(self,x,y): """ Set the value of num of mine neighbors """ if(x==self.board_width or y==self.board_width or x<0 or y<0 or self.board_data[x][y].has_mine): return else: self.board_data[x][y].neighbor_mines+=1 #self.print_board() def print_board(self): print(" +"+"---+"*self.board_width) for row in self.board_data: print(f"{self.board_data.index(row)+1}|", end="") for col in row: col.print_square() print("|",end="") print("\n +"+"---+"*self.board_width) print(" ",end="") for i in range(1,self.board_width+1): print(f" {i} ",end="") print("\n") def expose_all_mines(self): """ Exposes all the mines in case the player loses""" for row in self.board_data: for col in row: if(col.has_mine): col.hidden=False def expose_square(self,x,y): """ This function decides which and how many squares to expose after the player move, return the number of exposed squares to know when\if the player won without going all over the board each turn """ count_exposed_squares=0 if(self.board_data[x][y].has_mine): self.expose_all_mines() return 0 elif(self.board_data[x][y].hidden==False): return 0 elif(self.board_data[x][y].neighbor_mines!=0): self.board_data[x][y].hidden=False count_exposed_squares+=1 return count_exposed_squares else: count_exposed_squares+=self.expose_zeroes(x,y) return count_exposed_squares def expose_zeroes(self,x,y): """ In case the player hit a square with 0 neighbor mines, I expose all the neighbor 0 squers that linked to the chosen square return the number of exposed squares to know when\if the player won without going all over the board each turn """ count_exposed_squares=0 if(x==self.board_width or y==self.board_width or x<0 or y<0 or self.board_data[x][y].has_mine or self.board_data[x][y].hidden==False): return count_exposed_squares elif(self.board_data[x][y].neighbor_mines!=0): self.board_data[x][y].hidden=False self.print_board() count_exposed_squares+=1 return count_exposed_squares else: self.board_data[x][y].hidden=False self.print_board() count_exposed_squares+=1 count_exposed_squares+=self.expose_zeroes(x+1,y) count_exposed_squares+=self.expose_zeroes(x+1,y-1) count_exposed_squares+=self.expose_zeroes(x+1,y+1) count_exposed_squares+=self.expose_zeroes(x-1,y) count_exposed_squares+=self.expose_zeroes(x-1,y-1) count_exposed_squares+=self.expose_zeroes(x-1,y+1) count_exposed_squares+=self.expose_zeroes(x,y-1) count_exposed_squares+=self.expose_zeroes(x,y+1) return count_exposed_squares def main(): size=int(input("Enter size: ")) numOfMines=int(input("Enter number of mines (no more than twice the size): ")) if(size<4 or size>9): print("Dimentions does not match the required range") return if(numOfMines>2*size or numOfMines<1): print("Number of mines does not match the required range") return board=MSBoard(size,numOfMines) board.print_board() count_exposed_squares=0 while(True): if(count_exposed_squares == board.board_width*board.board_width-board.num_of_mines): print("you won!") return choice=input("Enter your choice with space(row column): ") choice=choice.split() row=int(choice[0])-1 col=int(choice[-1])-1 if(row>=board.board_width or col>=board.board_width): print("invalid choise, you shold choose row and col between 1 to "+str(board.board_width)+". please choose again") continue count_exposed_squares+=board.expose_square(row,col) board.print_board() print(count_exposed_squares) if(board.board_data[row][col].has_mine): print("you lost") return main() <file_sep># -*- coding: utf-8 -*- """ Created on Sat Dec 26 20:36:27 2020 @author: User """ def main(): m = open("output_ex1.txt", "r") t = open("output_ex1_correct.txt", "r") to=t.read() mo=m.read() for x in to: print("ok: ", to==mo) t.close() m.close() main()<file_sep># -*- coding: utf-8 -*- """ Created on Sun Dec 27 09:59:49 2020 @author: Dani """ def modular_power(a,b,n): """ computes a**b (mod n) using iterated squaring assumes b is a nonnegative integer""" result = 1 while b>0: if b%2 == 1: result = (result*a)%n a = (a*a)%n b = b//2 return result <file_sep># -*- coding: utf-8 -*- """ Student: <NAME> ID: 318298296 Assignment no. 3 Program: stats.py This program calculates data which is lists of floats, in order to check validness and achieve the average, median and the standard deviation of the lists. list_to_string* "כתבו פונקציה list_to_string שמקבלת מחרוזת המורכבת ממספרים ממשיים המופרדים ברווחים ומחזירה רשימה המכילה את המספרים האלה" I am totally aware of the output as float: x.0, but since the question requires to output them as numbers, I guess the floating state is the desired one rather than checking every number whether the int casting more suitable or not. """ import math def isfloat(st): ''' return true if the given string is a valid float and false otherwise''' totalPoints=0 i=0 if st[0]=="+" or st[0]=="-": i+=1 if i!=len(st)-1 and st[i]=="0": i+=1 if i!=len(st)-1 and st[i]!=".": return False #iterate throght the rest of the characters and check if they are valid while i<=len(st)-1: if totalPoints>1: return False if st[i]==".": if i==0 or st[i-1].isdigit()==False or i==len(st)-1: return False else: totalPoints+=1 i+=1 continue elif st[i].isdigit()==False: return False i+=1 return True def string_to_list(st): ''' return a list of floats from the given string @st''' strList = st.split() floatList=[] #iterate through the floatList and check whether the items are valid floats, if so it appends the floats in the returned list, if not it returns "none" for x in strList: if(isfloat(x)!=True): return "None" else: #left a comment above# floatList.append(float(x)) return floatList def mean(flist): ''' return the average of the floats in the given list @flist''' average=sum(flist) / len(flist) return average def sd(flist): ''' return the standard deviation of the floats in the given list @flist''' avg=mean(flist) flistSum=0 #iterate throght the list of floats and summerize the remainder of every item with the list average in the power of 2 for x in flist: flistSum+=pow(x-avg,2) return math.sqrt( (1/len(flist))*flistSum ) def newSort(flist): ''' return a sorted float list in an ascending order''' newFlist=flist.copy() #iterate throght the list and compare two consecutive items, #if the smaller is the next item it moves the smaller 1 index down if it can, and check the previous items as well #if not, it continue to the next item for x in range(len(newFlist)-1): item1=newFlist[x] item2=newFlist[x+1] if item2<item1: newFlist[x]=item2 newFlist[x+1]=item1 y=x while y>0: item1=newFlist[y] item2=newFlist[y-1] if item2>item1: newFlist[y]=item2 newFlist[y-1]=item1 y-=1 x+=1 return newFlist def median(flist): ''' return the median of the floats in the given list @flist''' flist=newSort(flist) n=len(flist) if(n%2==0): return (flist[int((n-1)/2)]+flist[int(n/2)])/2 else: return flist[int(n/2)] def main(): f = open("numbers.txt", "r") content=str(f.read()) print(content) f.close() flist = string_to_list(content) if(flist != 'None'): avg=round(mean(flist),2) md=round(median(flist),2) sdf=round(sd(flist),2) cont="mean: "+str(avg)+"\n"+"standard deviation: "+str(sdf)+"\n"+"median: "+str(md) else: cont='illegal input' f = open("stats.txt", "w") f.write(cont) f.close() main()<file_sep># -*- coding: utf-8 -*- """ Student: <NAME> ID: 318298296 Assignment no. 6 Program: line.py This program is a linear functions calculator """ class Point: """ a point in the plane """ def __init__(self, x, y): try: self.__x = float(x) except ValueError: raise ValueError("x coordinate must be a number") try: self.__y = float(y) except ValueError: raise ValueError("y coordinate must be a number") def __str__(self): return "({0:.2f},{1:.2f})".format(self.x,self.y) def __eq__(self, other): return self.x == other.x and self.y == other.y """ all the attributes builders """ @property def x(self): return self.__x @x.setter def x(self, value): try: self.__x = float(value) except ValueError as e: print(e) @property def y(self): return self.__y @y.setter def y(self, value): try: self.__y = float(value) except ValueError as e: print(e) class Line: """ a line in the plane """ def __init__(self, p, q): try: if(p==q): raise Exception('Please enter two different points') if(isinstance(p, Point)==False or isinstance(q, Point)==False): raise ValueError('The arguments type must be Points') else: self.__p = Point(p.x,p.y) self.__q = Point(q.x,q.y) except ValueError as e: print(e) @property def p(self): return self.__p @property def q(self): return self.__q @p.setter def p(self, value): if(isinstance(value, Point)==False): raise ValueError('The argument type must be Point') self.__p = value @q.setter def q(self, value): if(isinstance(value, Point)==False): raise ValueError('The argument type must be Point') self.__q = value def is_vertical(self): """ returns true if the line is verical and false otherwize """ if(self.p.x==self.q.x): return True return False def slope(self): """ returns the line slope """ if(self.p.x-self.q.x==0): return None return (self.p.y-self.q.y)/(self.p.x-self.q.x) def y_intersect(self): """ returns the line y intersection """ m=self.slope() if(m!=None): n=self.p.y-(m*self.p.x) return n return None def __str__(self): """ returns the line equivelent as string """ m=self.slope() n=self.y_intersect() if(m!=None): return "y = {0:.2f}x + {1:.2f}".format(m,n) return "x = {0:.2f}".format(self.p.x) def parallel(self,other): """ returns true if this line is parallel to the line given in the parameter and false otherwize """ if(self.slope()==other.slope()): return True return False def equals(self,other): """ returns true if this line is equal to the line given in the parameter and false otherwize """ if(other.slope()==self.slope() and self.y_intersect()==other.y_intersect()): return True return False def intersection(self,other): """ returns the intersection point between this line and the line given in the parameter""" if(self.parallel(other)): return None myY=self.y_intersect() otherY=other.y_intersect() mySlope=self.slope() otherSlope=other.slope() if(myY and otherY): freeNum=otherY-myY xFactor=mySlope-otherSlope xValue=freeNum/xFactor yValue=xValue*mySlope+myY elif(self.is_vertical()): xValue=self.p.x yValue=xValue*otherSlope+otherY else: xValue=other.p.x yValue=xValue*mySlope+myY return Point(xValue,yValue) def ui(filenum): """this function""" f=open(f"input{filenum}.txt", "r") content="" rowNum=1 linesArr=[] #iterates throght every row in the text file for row in f: try: row=row.strip() arr=row.split(" ") if(len(arr)==4): line=Line( Point(arr[0],arr[1]),Point(arr[2],arr[3]) ) content+=f"line {rowNum}: {str(line)}\n" #iterates throght every line that where calculated before this row for l in linesArr: intersection=line.intersection(l["line"]) otherLineNum=l["lineNum"] content+=f"line {rowNum} " if(intersection): content+=f"with line {otherLineNum}: {intersection}\n" elif( line.equals(l["line"]) ): content+=f"is equal to line {otherLineNum}\n" else: content+=f"is parallel to line {otherLineNum}\n" lineDic={"lineNum":rowNum,"line":line} linesArr.append(lineDic) else: raise Exception(f"Not enough data for line {rowNum}.") except ValueError as e: content+=f"Line {rowNum} error: {e}\n" except Exception as e: content+=f"{e}\n" content+="\n" rowNum+=1 f.close() o = open(f"output{filenum}.txt", "w") o.write(content) o.close() tester(filenum) def tester(filenum): correct=open(f"output{filenum}_correct.txt", "r") mine=open(f"output{filenum}.txt", "r") rowNum=1 ok="OK" for row in correct: validRow= row == mine.readline() if(validRow==False): print(f"row {rowNum} does not match") ok="Err" return rowNum+=1 print(ok) def main(): ui(1) ui(2) ui(3) ui(4) ui(5) ui(6) main() ''' piece and love, best regards, Served under the auspices of <NAME> first of her name mother of cats and breaker of chains '''<file_sep># -*- coding: utf-8 -*- """ Student: <NAME> ID: 318298296 Assignment no. 3 Program: stats.py comment: I know that you have beet tring to teach neasted loops, but I feel in most of the cases - the best practice might be to avoid it where you can since it is not clean and afficiant solotion when you have the choise not to use neasted loops. """ def isfloat(st): totalPoints=0 i=0 if st[0]=="+" or st[0]=="-": i+=1 if i!=len(st)-1 and st[i]=="0": i+=1 if i!=len(st)-1 and st[i]!=".": return False while i<=len(st)-1: if totalPoints>1: return False if st[i]==".": if i==0 or st[i-1].isdigit()==False or i==len(st)-1: return False else: totalPoints+=1 i+=1 continue elif st[i].isdigit()==False: return False i+=1 return True def tester(st): print(st) print(isfloat(st)) print("") def main(): print("all of those should be true: ") tester("0.123") tester("-0.123") tester("+0.123") tester("-4.01") tester("+3.05") tester("3.00") tester("+0") tester("-0") print("all of those should be false: ") tester(".123") tester("+.5") tester("54.6.7") tester("+123+5") tester("45.") tester("00.123") tester("001234") tester("123a4") #isfloat("+3.05")+isfloat("3.00")+isfloat("+0")+isfloat("-0")) #print("all of those should be false: ") #print(isfloat(".123")+isfloat("+.5")+isfloat("54.6.7")+isfloat("+123+5")+isfloat("45.")+isfloat("00.123")+isfloat("001234")+isfloat("123a4")) ''' yourFloat = input("try me beach: ") if(isfloat(yourFloat)): print("ok") else: print("ha ha gut`ya") ''' main()<file_sep># -*- coding: utf-8 -*- """ Student: <NAME> ID: 318298296 Assignment no. 5 Program: num_sums.py This program calculates all the factorization options for a given integer """ def setData(lineArr): ''' return a dictionary which include the integer to factorise and the possible parts if the data invalid returns an error''' parts=[] #iterates throght the line items, if possible cast into integer, if not returns an error for item in lineArr: item=item.strip() if item.isnumeric(): number=int(item) parts.append(number) else: return "Error" n=parts[0] parts=parts[1::] if(len(parts)<1): return "Error" partsCopy=parts.copy() #iterates throght the numbers list by nested loop to ensure theres no duplicate numbers in the list for number in parts: if(number==0): return "Error" currItem=partsCopy.pop(partsCopy.index(number)) for checkItem in partsCopy: if checkItem==currItem: return "Error" return {"n":n,"parts":parts} def num_sums_iterate(n,parts,currentSum): ''' returns an integer which represents all the factorization options for a given integer n''' count=0 if currentSum==n and n!=0: return 1 if currentSum>n: return 0 if currentSum<n or n==0: #iterates throght every part, to calculate all the possibilities in every point on the tree for nextNum in parts: count+= num_sums_iterate(n,parts,currentSum+nextNum) return count def num_sums(n,parts): ''' returns an integer which represents all the factorization options for a given integer n''' return num_sums_iterate(n,parts,0) def main(): f=open("input_ex2.txt", "r") content="" #iterates throght every line in the text file to calculate the factorization options for line in f: lineArr=line.split(" ") data=setData(lineArr) if data=="Error": content+=data+"\n" else: theSum=num_sums(data["n"],data["parts"]) content+= str(theSum) +"\n" f.close() o = open("output_ex2.txt", "w") o.write(content) o.close() main() <file_sep># -*- coding: utf-8 -*- """ Student: <NAME> ID: 318298296 Assignment no. 3 Program: density_primes.py This program takes 100000 random numbers between 10^9 and 10^9\2, and prints the percentage value of the total prime numbers out of them, Then it prints the approximation of the percentage of the total primes between 1 to 10^9 """ import math import random def is_prime(num): """ return true if the given number @num is a prime number and false otherwise """ if(num%2 == 0): if (num != 2): return False for i in range(3,int(math.sqrt(num))+1, 2): if (num%i == 0): return False return True def main(): max=math.pow(10,9) randomList=[random.randint(max/2, max) for i in range(100000)] countPrimes=0 #iterate through all the numbers in the randomList list and count the number of the primes for num in randomList: if is_prime(num): countPrimes+=1 densityOfprimes = round(countPrimes/100000,4) expectedDensity = round(1/math.log(max),4) print("density of primes: "+str(densityOfprimes)+"\n"+"expected density: "+str(expectedDensity)+"\n") main() <file_sep># -*- coding: utf-8 -*- """ Created on Wed Jan 6 19:34:06 2021 @author: User """ def main(): f = open('input_ex2.txt', 'r') lines = f.readlines() invalid_syntax = '' for line in lines: for l in line: if l.isalpha(): lines.remove(line) break; print(lines) main() <file_sep># -*- coding: utf-8 -*- """ Student: <NAME> ID: 318298296 Assignment no. 4 Program: grades.py This program gives information regarding students and grades """ def avg(arr): ''' return the average of the numbers in the array ''' return sum(arr)/len(arr) def dictionary_bubble_sort(dic): ''' sort the dictionary by the average grade each student got ''' arr2D=[ [k,dic[k][0],dic[k][1] ] for k in dic.keys()] n = len(arr2D) # iterate through all array elements and sort for i in range(n): for j in range(0, n-i-1): if arr2D[j][2] < arr2D[j+1][2] : arr2D[j], arr2D[j+1] = arr2D[j+1], arr2D[j] return arr2D def inner_join_students_and_grades_by_id(s,g): ''' return a dictionary defined by student`s id which has both student`s name and student`s average grade ''' students=s.copy() grades=g.copy() joinStudentsNamesAndGrades={} #iterate throught both dectionaries and match student`s name and avg grade for i in students.keys(): for j in grades.keys(): if(i==j): gradesArr=grades.pop(j) gradeAvg=avg(gradesArr) joinStudentsNamesAndGrades[j]=[students[i],gradeAvg] break return joinStudentsNamesAndGrades def get_students(filename): ''' return a students dictionary from the given file ''' students={} s = open(filename, "r") #iterate throught every line, split the data into an array, and if the data is valid, saves the data on the right key for x in s: arr=x.split() if(len(arr)<2): raise Exception("Please avoid empty lines, or empty data after Id") students[int(arr[0])]=" ".join(arr[1::]) return students def get_grades(filename): ''' return a grades dictionary from the given file ''' grades={} g = open(filename, "r") #iterate throught every line, split the data into an array, and if the data is valid, saves the data on the right key for x in g: arr=x.split() if(len(arr)<2): raise Exception("Please avoid empty lines, or empty data after Id") grades[int(arr[0])]=[int(arr[i]) for i in range(1,len(arr))] return grades def find_most_common_grades(gradesDic): ''' return an array of the most common grade ''' #gradesList has only grades gathered in a list gradesList=[g for val in gradesDic.values() for g in val] gradesCountDic={} countMax=1 #iterate throught each grade, put it as a key in the dictionary and the value will be the number of time it appeard for g in gradesList: if g in gradesCountDic: gradesCountDic[g]+=1 if gradesCountDic[g]>countMax: countMax=gradesCountDic[g] else: gradesCountDic[g]=1 mostCommon=[] #fined the grades which has the maximum apperance time, save it in an array and return it for g,c in gradesCountDic.items(): if(c==countMax): mostCommon.append(g) return mostCommon def get_common_elements(list2D): ''' return the grades which more then one student get ''' newL=[] #make each grades list into set to appear only one for each student for g in list2D: newL.append(set(g)) common=set() #go over each student`s grades and search wether they appeard on another students grades for i in range(len(newL)): s=newL[i] tempArr=newL[::] tempArr.pop(i) rest=set.union(*tempArr) cut=s.intersection(rest) common.update(cut) return common def valid_ids(dictionary): ''' raise an exception if some id in the given dictionary does not contain nine digits or does not contain only digits ''' for iD in dictionary.keys(): if( str(iD).isnumeric()==False or len(str(iD))!= 9 ): raise Exception("Id is not valid") def set_of_keys(dic): ''' return a set of keys out of the given dictionary ''' keys=set() for k in dic.keys(): keys.add(k) return keys def id_appear_in_both_dics(students, grades): ''' raise an exception if the two given dictionaries does not contain the same students ''' if set_of_keys(students)!=set_of_keys(grades): raise Exception("Ids does not match") def main(): ''' prints the output, stop the program and raise an error if one or more of the data is not valid ''' try: students=get_students("students.txt") grades=get_grades("grades.txt") #checks valid_ids(students) valid_ids(grades) id_appear_in_both_dics(students,grades) dictionary=inner_join_students_and_grades_by_id(students,grades) sortedArray=dictionary_bubble_sort(dictionary) #prints every student and his\hers grade for s in sortedArray: print(s[1], round(s[2],2)) print("Most common grades: ", find_most_common_grades(grades)) gradesArr=[g for g in grades.values()] common=get_common_elements(gradesArr) print("Grades that more than one student got: ", str(common).replace('{','').replace('}','')) except OSError as err: print(err) main() ''' best regards, Served under the auspices of Noga Banana first of her name hope you enjoyd my code, thank you for waching please don`t forget to subscribe if you liked my content see you soon next week ''' <file_sep># -*- coding: utf-8 -*- """ Student: <NAME> ID: 318298296 Assignment no. 3 Program: stats.py comment: I know that you have beet tring to teach neasted loops, but I feel in most of the cases - the best practice might be to avoid it where you can since it is not clean and afficiant solotion when you have the choise not to use neasted loops. list_to_string* "כתבו פונקציה list_to_string שמקבלת מחרוזת המורכבת ממספרים ממשיים המופרדים ברווחים ומחזירה רשימה המכילה את המספרים האלה" I am totally aware of the output as float: x.0, but since the question requires to output them as numbers, I guess the floating state is the desired one rather than checking every number whether the int casting more suitable or not. """ import math def isfloat(st): totalPoints=0 i=0 if st[0]=="+" or st[0]=="-": i+=1 if i!=len(st)-1 and st[i]=="0": i+=1 if i!=len(st)-1 and st[i]!=".": return False while i<=len(st)-1: if totalPoints>1: return False if st[i]==".": if i==0 or st[i-1].isdigit()==False or i==len(st)-1: return False else: totalPoints+=1 i+=1 continue elif st[i].isdigit()==False: return False i+=1 return True def list_to_string(st): strList = st.split() floatList=[] for x in strList: if(isfloat(x)!=True): return "None" else: #left a comment above# floatList.append(float(x)) return floatList def mean(flist): average=sum(flist) / len(flist) return average def sd(flist): avg=mean(flist) flistSum=0 for x in flist: flistSum+=pow(x-avg,2) return math.sqrt( (1/len(flist))*flistSum ) def newSort(flist): newFlist=flist.copy() for x in range(len(newFlist)-1): item1=newFlist[x] item2=newFlist[x+1] if item2<item1: newFlist[x]=item2 newFlist[x+1]=item1 y=x while y>0: item1=newFlist[y] item2=newFlist[y-1] if item2>item1: newFlist[y]=item2 newFlist[y-1]=item1 y-=1 x+=1 return newFlist def median(flist): flist=newSort(flist) n=len(flist) if(n%2==0): return (flist[int((n-1)/2)]+flist[int(n/2)])/2 else: return flist[int(n/2)] def main(): yourStr = input("type a float str ") flist = list_to_string(yourStr) #avg=mean(flist) std=median(flist) print(newSort(flist)) print(std) main()<file_sep># -*- coding: utf-8 -*- """ Student: <NAME> ID: 318298296 Assignment no. 4 Program: vigenere.py This program encrypt and decrypt text files by a given key """ def split(word): """ utility function: return a splited string into a list of characters """ return [char for char in word] LATINE_LETTERS=split("abcdefghijklmnopqrstuvwxyz") def compileTxt(s): """ utility function: return a string that includes only the latine letters from the given s string parameter """ st="" #loop throght all the s string characters and include only the latine letters for i in s: if i.isalpha(): st+=i.lower() return st def add_letters(str1,str2): """ return a character which indexed by the sum of the two give strings indexes """ if len(str1)==1 and len(str2)==1 and str1.isalpha() and str2.isalpha(): str1l=str1.lower() str2l=str2.lower() res=LATINE_LETTERS.index(str1l)+LATINE_LETTERS.index(str2l) if(res>25): res=res%26 return LATINE_LETTERS[res] else: return 'None' def decrypt_letters(charKey, charRes): """ return the origin character from the result letter encryption with the given character key """ originIndex=LATINE_LETTERS.index(charRes)-LATINE_LETTERS.index(charKey) if(originIndex<0): originIndex=LATINE_LETTERS.index(charRes)+26-LATINE_LETTERS.index(charKey) return LATINE_LETTERS[originIndex] def add_strings(str1,str2): """ return a string which was the result of adding each letter latine index (on the LATINE_LETTERS list) on str1 with the index of letter from str2 in the same position""" length=min(len(str1),len(str2)) res="" #loop as the shortest string length and add to the result the correct letter from the calculation for i in range(length): combine=add_letters(str1[i],str2[i]) if combine!="None": res+=combine else: return "None" return res def decrypt_string(key,res): """ return the compiled origin string which was the input that was encrypted with the given key """ originSt="" #loop as the res string length and decrypt every letter for i in range(len(res)): originSt+= decrypt_letters(key[i], res[i]) return originSt def vigenere_encrypt(s,k): """ return the encrypted text with the given key (k) from the given content (s) """ t="" st=compileTxt(s) #multiple the key to have at least the length of the given content (s) for i in range(0,len(st),len(k)): t+=k return add_strings(t,st) def vigenere_decrypt(k,res): """ return the compiled origin string which was the input that was encrypted with the given key (k)""" t="" #multiple the key to have at least the length of the result encrypted text (res) for i in range(0,len(res),len(k)): t+=k return decrypt_string(t,res) def test_encryption(filename,encryptext): """ utility function: return True if my encryption gave the same result as the example vig and False otherwize """ output_ex_vig = open(filename+"_correct.vig",'r') ex = output_ex_vig.read() print(ex==encryptext) def test_decryption(filename,decryptext): """ utility function: return True if my decryption gave the same result as the compiled origin text and False otherwize """ txtFile = open(filename+".txt",'r') ex = txtFile.read() print(compileTxt(ex)==decryptext) def ui(action,filename,key): """ encrypt or decrypt the given file (filename) with the given key, as you asked: the encryption creates new vig file with the result text and the decryption print the compiled text to the console""" if(action=="e"): suffix=".txt" elif(action=="d"): suffix=".vig" else: return try: f = open(filename+suffix,'r') s = f.read() if(action=="e"): encryptFile = open(filename+".vig", "w") encrypt=vigenere_encrypt(s,key) encryptFile.write(encrypt) #test_encryption(filename,encrypt) elif(action=="d"): decrypt=vigenere_decrypt(key,s) print(decrypt) #test_decryption(filename,decrypt) f.close() except IOError: print("File not accessible") def main(): userChoise=input("for encrypt type 'e', for dycrypt type 'd': ") filename=input("please type the name of the file: ") key=input("please type a key to encrypt: ") ui(userChoise,filename,key) main() <file_sep># -*- coding: utf-8 -*- """ Student: <NAME> ID: 318298296 Assignment no. 5 Program: print_sums.py This program calculates all the factorization options for a given integer """ def setData(lineArr): ''' return a dictionary which include the integer to factorise and the possible parts if the data invalid returns an error''' parts=[] #iterates throght the line items, if possible cast into integer, if not returns an error for item in lineArr: item=item.strip() if item.isnumeric(): number=int(item) parts.append(number) else: return "Error" n=parts[0] parts=parts[1::] if(len(parts)<1): return "Error" partsCopy=parts.copy() #iterates throght the numbers list by nested loop to ensure theres no duplicate numbers in the list for number in parts: if(number==0): return "Error" currItem=partsCopy.pop(partsCopy.index(number)) for checkItem in partsCopy: if checkItem==currItem: return "Error" return {"n":n,"parts":parts} def print_sums_iterate(n,parts,currentSum,concat): ''' returns all the factorization options for a given integer n''' sequense= "" if currentSum==n and n!=0: return str(n)+" = "+concat[:len(concat)-3:]+"\n" if currentSum>n: return "" if currentSum<n or n==0: #iterates throght every part, to calculate all the possibilities in every point on the tree for nextNum in parts: nextStr=str(nextNum) sequense+= print_sums_iterate(n,parts,currentSum+nextNum,concat+nextStr+" + " ) return sequense def print_sums(n,parts): '''call the recrusive function and returns all the factorization options for a given integer n''' content=print_sums_iterate(n,parts,0,"") partstring=str(parts) return "%s as sum of %s:\n%s"%(n,partstring,content) def main(): f=open("input_ex3.txt", "r") content="" #iterates throght every line in the text file to calculate the factorization options for line in f: line=line.strip() lineArr=line.split(" ") data=setData(lineArr) if data=="Error": content+=line+"\nError\n\n" else: theSum=print_sums(data["n"],data["parts"]) content+= theSum +"\n" f.close() o = open("output_ex3.txt", "w") o.write(content) o.close() main() ''' piece and love, best regards, Served under the auspices of <NAME> first of her name mother of cats and breaker of chains ''' <file_sep># -*- coding: utf-8 -*- """ Student: <NAME> ID: 318298296 Assignment no. 3 Program: matrix.py This progream is a matrixes calculator """ def valid_matrix(mat): """ return true if the given matrix is valid and false otherwise """ cols=len(mat) for col in range(1,cols): if len(mat[col])!=len(mat[0]): return False return True def matrix_scalar_mult(A,C): """ multiply the given matrix @A in the given scalar @C """ if valid_matrix(A): return [[A[i][j]*C for j in range(len(A[0]))] for i in range(len(A))] else: return "invalid matrix" def add_matrix(A,B): """ sum the A matrix with B matrix """ return [ [A[i][j]+B[i][j] for j in range(len(A[0]))] for i in range(len(A))] def mult_matrix(A,B): """ multiply the A matrix with B matrix """ return [ [ sum([A[i][k]*B[k][j] for k in range(len(A[0]))]) for j in range(len(B[0])) ] for i in range(len(A)) ] def identy_matrix(n): """ return identy matrix in nxn dimentions """ return [[0 if j != i else 1 for j in range(n)] for i in range(n)] def marix_pow(A,x): """ return the given matrix @A in the power of @x""" powerMat=A #iterate x times and each time multiply the product in A for i in range(1,x): powerMat=mult_matrix(A,powerMat) return powerMat def matrix_polynom(p,A): """ return a new matrix based on a summerized calculation of each item (number) in the given list @p, multiply the matrix in the power of the item index in p""" dim=len(A) polMat=matrix_scalar_mult(identy_matrix(dim),p[0]) #iterate throght the rest of the p list indexes, #summerize the next matrix multiplyed by the value of the current item(number) in p #with the @A matrix in the power of the current item index for i in range(1,len(p)): polMat=add_matrix(polMat,matrix_scalar_mult(marix_pow(A,i),p[i])) return polMat def print_matrix(A,fileLink): '''print the given matrix @A in a pretty wey into the given file address @fileLink''' f = open(fileLink, "w") content="" #iterate throught every row in the matrix, and print it seperatly in a pretty wey for row in A: row=[round(x,2) for x in row] content=str(row).replace("[","").replace("]","").replace(","," ") f.write(content+"\n") f.close() def main(): f = open("example_io/matrix_input3.txt", "r") line=f.readline() matrix=[] #iterate throught every non-empty line in the file, #and append every item in the line into the right row in the matrix while line != '': row=line.split() matrix.append([float(x) for x in row]) line=f.readline() p=matrix.pop(len(matrix)-1) print_matrix(matrix_polynom(p,matrix),"matrix_output.txt") main() ''' piece and love, best regards, Served under the auspices of <NAME> first of her name mother of cats and breaker of chains '''<file_sep># -*- coding: utf-8 -*- """ Student: <NAME> ID: 318298296 Assignment no. 5 Program: primes_check.py This program gets very large integers and calculates whether they are prime numbers or not """ import math import random import powers def odd(k): ''' returns the "even degree" of the given integer k ''' if k%2==0: return odd(k//2) else: return k def even(k): ''' returns the "odd part" of the given integer k ''' s=int(math.log2(k)) while k%(2**s)!=0: s-=1 else: return s def get_even_odd_parts(n): ''' returns a dictionary which has both the "odd part" and the "even degree" of the given integer n ''' return {"t":odd(n),"s":even(n)}; def is_probubly_prime(n, num_iterations): ''' retruns True if the given integer n has big changce of being a prime number''' s=even(n-1) t=odd(n-1) lap=num_iterations #run num_iterations times to increase accuracy while lap>0: if(is_suspected_prime(n,t,s)==False): return False lap-=1 return True def is_suspected_prime(n,t,s): ''' retruns True if the given n integer might be a prime number''' a=random.randint(2,n-1) d=powers.modular_power(a,t,n) if d==1 or d==(n-1): return True for i in range(1,s): d=powers.modular_power(d,2,n) if d==(n-1): return True return False def main(): f = open("input_ex1.txt", "r") output="" #iterates throght every line in the text file to calculate whether the current number is a prime number or not for x in f: x=int(x) if(is_probubly_prime(x,10)): output+=str(x)+" is prime\n" else: output+=str(x)+" is not prime\n" f.close() o = open("output_ex1.txt", "w") o.write(output) o.close() main() <file_sep># -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ def main(): listInt=[] flag=True while flag: getInp=int(input("enter int: ")) for x in listInt: if x==getInp: flag=False break listInt.append(getInp) listInt.sort() if flag: print(listInt) main()
b260f572c57369c10279fa541308f36077ae3ba0
[ "Python" ]
18
Python
nogaanaby/python-mmns
3e24a050bb7335b2c0ec6aa3e55489778204c048
a510eaa6862f8a61d6326b6995806155d075cd69
refs/heads/master
<repo_name>kumar-turlapati/qbsites-app<file_sep>/src/FrameWork/Constants.php <?php namespace FrameWork; class Constants { }<file_sep>/public/js/app.js $(document).ready(function(){ AOS.init({ duration: 800, easing: 'slide', once: false }); $('.cartPlus').on('click', function(){ var thisId = $(this).attr('id').split('_')[1]; var qty = returnNumber(parseInt($('#iqty_'+thisId).val())); var itemRate = returnNumber(parseInt($('#rate_'+thisId).text())); var newQty = qty+1; var totalValue = returnNumber(parseFloat($('#totalAmount').text())); $('#iqty_'+thisId).val(newQty); updateCartTotal(); }); $('.cartMinus').on('click', function(){ var thisId = $(this).attr('id').split('_')[1]; var qty = returnNumber(parseInt($('#iqty_'+thisId).val())); var itemRate = returnNumber(parseInt($('#rate_'+thisId).text())); if(qty > 1) { var newQty = qty-1; var totalValue = returnNumber(parseFloat($('#totalAmount').text())); $('#iqty_'+thisId).val(newQty); updateCartTotal(); } else { bootbox.alert({ message: "Minimum one unit is required to place the order.", }); } }); $('#cb_checkall').on('click', function(){ var isChecked = $(this).prop('checked'); $('.itemCheckboxes').prop("checked", isChecked); }); $('.itemCheckboxes').on('click', function(){ var checked; $('.itemCheckboxes').each(function(i, obj) { checked = $(this).prop('checked'); }); if(checked) { $('#cb_checkall').prop('checked', true); } else { $('#cb_checkall').prop('checked', false); } }); $('.removeItemFromCart').on('click', function(){ var itemCodes = new Array; $('.itemCheckboxes').each(function(i, obj) { var checked = $(this).prop('checked'); if(checked) { var itemCode = $(this).attr('id').split('_')[1]; itemCodes.push(itemCode); } }); if(itemCodes.length === 0) { bootbox.alert({ message: "Please select an item to remove from the Cart", }); return false; } $.ajax("/cart/remove"+'?itemCode='+itemCodes.join()+'&qty=1&cntr=1', { type: "POST", success: function(itemDetails) { window.location.reload(true); }, error: function(e) { bootbox.alert({ message: 'An error occurred :(', }); } }); }); $('#otpBtn').on('click', function(e){ e.preventDefault(); $(this).attr('disabled', true); var mobileNo = $('#mobileNumber').val(); var businessName = $('#businessName').val(); if(businessName.length === 0) { bootbox.alert({ message: 'Please enter your personal name (or) business name first', }); $(this).attr('disabled', false); return; } if(mobileNo.length !== 10 ) { bootbox.alert({ message: 'Invalid mobile no.', }); $('#mobileNumber').val(''); $(this).attr('disabled', false); return; } mobileNo = parseInt(mobileNo); if(Number.isInteger(mobileNo)) { $.ajax("/send-otp/"+mobileNo, { type: "POST", success: function(otpResponse) { // console.log(otpResponse); if(otpResponse.status) { $('#otpBtn').hide(); $('#otp').attr('disabled', false); $('#orderBtn').show(); setTimeout(function() { $("#resendOtpBtn").show(); }, 5000); } else { bootbox.alert({ message: 'An error occurred while sending Otp :(', }); $(this).attr('disabled', false); return false; } }, error: function(e) { bootbox.alert({ message: 'An error occurred :(', }); $(this).attr('disabled', false); return false; } }); } else { bootbox.alert({ message: 'Invalid mobile no.', }); $('#mobileNumber').val(''); $(this).attr('disabled', false); return false; } }); $('#resendOtpBtn').on('click', function(e){ e.preventDefault(); $(this).attr('disabled', true); var mobileNo = $('#mobileNumber').val(); var businessName = $('#businessName').val(); if(businessName.length === 0) { bootbox.alert({ message: 'Please enter your personal name (or) business name first', }); $(this).attr('disabled', false); return; } if(mobileNo.length !== 10 ) { bootbox.alert({ message: 'Invalid mobile no.', }); $('#mobileNumber').val(''); $(this).attr('disabled', false); return; } mobileNo = parseInt(mobileNo); if(Number.isInteger(mobileNo)) { $.ajax("/send-otp/"+mobileNo, { type: "POST", success: function(otpResponse) { if(otpResponse.status) { setTimeout(function() { $("#resendOtpBtn").attr('disabled', false); }, 8000); } else { bootbox.alert({ message: 'An error occurred while sending Otp :(', }); $(this).attr('disabled', false); return false; } }, error: function(e) { bootbox.alert({ message: 'An error occurred :(', }); $(this).attr('disabled', false); return false; } }); } else { bootbox.alert({ message: 'Invalid mobile no.', }); $('#mobileNumber').val(''); $(this).attr('disabled', false); return false; } }); $('#orderSubmit').submit(function(e){ e.preventDefault(); $(this).attr('disabled', true); $('#resendOtpBtn').hide(); var form = $(this); var mobileNo = $('#mobileNumber').val(); var businessName = $('#businessName').val(); var otp = $('#otp').val(); if(businessName.length === 0) { bootbox.alert({ message: 'Please enter your personal name (or) business name', }); $(this).attr('disabled', false); return; } if(mobileNo.length !== 10 ) { bootbox.alert({ message: 'Invalid mobile no.', }); $('#mobileNumber').val(''); $(this).attr('disabled', false); return; } if(otp.length !== 4 ) { bootbox.alert({ message: 'Invalid otp', }); $('#otp').val(''); $(this).attr('disabled', false); return; } mobileNo = parseInt(mobileNo); otp = parseInt(otp); if(Number.isInteger(mobileNo) && Number.isInteger(otp)) { $.ajax({ type: "POST", url: '/order/submit', data: form.serialize(), success: function(orderResponse) { // console.log(orderResponse); if(!orderResponse.status) { bootbox.alert({ message: orderResponse.reason, }); return false; } else { bootbox.alert({ message: 'Your Order has been submitted successfully with Order No. '+orderResponse.orderNo, callback: function() { var ch = $('#ch').val(); window.location.href = '/catalog/view/'+ch; } }); } }, error: function(e) { bootbox.alert({ message: 'An error occurred while submitting your order :(', }); $(this).attr('disabled', false); return false; } }); } else { bootbox.alert({ message: 'Invalid mobile no. (or) otp', }); $('#otp, #mobileNumber').val(''); $(this).attr('disabled', false); return; } }); }); function updateCartTotal() { var totalValue = 0; $('.iqtys').each(function(i, obj) { var itemCode = $(this).attr('id').split('_')[1]; var itemQty = parseFloat($(this).val()); var itemRate = returnNumber(parseFloat($('#rate_'+itemCode).text())); var itemValue = itemQty*itemRate; totalValue += itemValue; }); $('#totalAmount').text(totalValue.toFixed(2)); } function cartOp(itemCode, op, index) { if(itemCode.length > 0) { if(op === 'add' || op === 'remove') { var itemQty = returnNumber(parseInt($('#qty_'+itemCode+'_'+index).val())); if(itemQty <= 0) { alert('Order qty. must be greater than zero :('); return false; } jQuery.ajax("/cart/"+op+'?itemCode='+itemCode+'&qty='+itemQty+'&cntr='+index, { type: "POST", success: function(itemDetails) { var opStatus = itemDetails.status; if(opStatus) { var newCartCount = itemDetails.ic; $('.cartCount').text(newCartCount); bootbox.alert({ message: 'Item added to Cart successfully', }); } else { bootbox.alert({ message: itemDetails.reason, }); } }, error: function(e) { bootbox.alert({ message: 'An error occurred while adding your item to Cart :(', }); } }); } else { bootbox.alert({ message: 'Invalid op!', }); } } else { bootbox.alert({ message: 'Invalid item!', }); } } function returnNumber(val) { if(isNaN(val) || val.length === 0) { return 0; } return val; } $(window).scroll(function () { var scroll = $(window).scrollTop(); if (scroll >= 250) { $("header").addClass("navbarSticky"); } else { $("header").removeClass("navbarSticky"); } }); <file_sep>/src/FrameWork/Utilities.php <?php namespace FrameWork; use Symfony\Component\HttpFoundation\RedirectResponse; use FrameWork\Constants; use FrameWork\ApiCaller; use FrameWork\Config\Config; use User\Model\User; class Utilities { public static function enc_dec_string($action = 'encrypt', $string = '') { $token_config = Config::get_enc_dec_data(); $key = hash('sha256', $token_config['secret_key']); // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning $iv = substr(hash('sha256', $token_config['secret_iv']), 0, 16); if( $action === 'encrypt' ) { $output = openssl_encrypt($string, $token_config['encrypt_method'], $key, 0, $iv); $output = base64_encode($output); } elseif( $action === 'decrypt' ){ $output = openssl_decrypt(base64_decode($string), $token_config['encrypt_method'], $key, 0, $iv); } return $output; } public static function redirect($url, $type='external') { $response = new RedirectResponse($url); $response->send(); exit; } public static function validateDate($date = '') { if(! is_numeric(str_replace('-', '', $date)) ) { return false; } else { $date_a = explode('-', $date); if(checkdate($date_a[1],$date_a[0],$date_a[2])) { return true; } else { return false; } } } public static function validateMonth($month = '') { if(!is_numeric($month) || $month<=0 || $month>12 ) { return false; } else { return true; } } public static function validateYear($year = '') { if(!is_numeric($year) || $year<=2015 ) { return false; } else { return true; } } public static function clean_string($string = '', $breaks_needed=false) { if($breaks_needed) { return trim(strip_tags($string)); } else { return trim(str_replace("\r\n",'',strip_tags($string))); } } public static function validateName($name='') { if(!preg_match("/^[a-zA-Z ]*$/",$name)) { return false; } else { return true; } } public static function validateEmail($email='') { if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { return false; } else { return true; } } public static function validateMobileNo($mobile_no='') { if( strlen(trim(str_replace("\r\n",'',$mobile_no))) !== 10 ) { return false; } elseif(!is_numeric($mobile_no)) { return false; } return true; } public static function set_flash_message($message = '', $error=0) { if(isset($_SESSION['__FLASH'])) { unset($_SESSION['__FLASH']); } $_SESSION['__FLASH']['message'] = $message; $_SESSION['__FLASH']['error'] = $error; } public static function get_flash_message() { if(isset($_SESSION['__FLASH'])) { $message = $_SESSION['__FLASH']['message']; $status = $_SESSION['__FLASH']['error']; unset($_SESSION['__FLASH']); return array('message'=>$message, 'error'=>$status); } else { return ''; } } public static function print_flash_message($return=true) { $flash = Utilities::get_flash_message(); if(is_array($flash) && count($flash)>0) { $flash_message_error = $flash['error']; $flash_message = $flash['message']; } else { $flash_message = ''; } if($flash_message != '' && $flash_message_error) { $message = "<div class='alert alert-danger' role='alert'> <strong>$flash_message</strong> </div>"; } elseif($flash_message != '') { $message = "<div class='alert alert-success' role='alert'> <strong>$flash_message</strong> </div>"; } else { $message = ''; } if($return) { return $message; } else { echo $message; } } public static function get_business_category() { return 2; } public static function get_api_environment() { $business_category = Utilities::get_business_category(); $environment = $_SERVER['apiEnvironment']; $api_urls = Config::get_api_urls(); return $api_urls[$business_category][$environment]; } public static function is_session_started() { if (php_sapi_name()!=='cli') { if ( version_compare(phpversion(), '5.4.0', '>=') ) { return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE; } else { return session_id() === '' ? FALSE : TRUE; } } return FALSE; } } <file_sep>/src/Layout/partials/head.tpl.php <!-- meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Basic Google fonts start here --> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700;800&display=swap" rel="stylesheet"> <!-- Bootstrap 4.4.1 framwork styles --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- card animation styles --> <link rel="stylesheet" href="/assets/css/aos.css"> <link rel="stylesheet" href="/assets/css/fancybox.min.css"> <!-- custom styles --> <link rel="stylesheet" type="text/css" href="/assets/css/custom-styles.css"> <link rel="icon" href="/images/favicon.ico" /> <title><?php echo $page_title ?></title> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-170212035-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-170212035-1'); </script> <file_sep>/src/FrameWork/ApiCaller.php <?php namespace FrameWork; use Curl\Curl; use FrameWork\Utilities; class ApiCaller { private static $instance = null; private $api_url = ''; public function __construct($return_object=false) { if(self::$instance == null) { self::$instance = new Curl(); } if($return_object) { return self::$instance; } } public function sendRequest($method='',$uri='',$param_array=[],$process_response=true,$debug=false,$org_id='') { // prepare headers. self::$instance->setHeader('Content-Type', 'application/json'); self::$instance->setHeader('Org-Id', $org_id); // get api environment $this->api_url = Utilities::get_api_environment(); // prepare end point $end_point = $this->api_url.'/'.$uri; // dump($param_array); // echo 'end point is....'.$end_point; // exit; // initiate CURL request. switch ($method) { case 'post': self::$instance->post($end_point, $param_array); break; case 'get': self::$instance->get($end_point, $param_array); break; case 'update': break; case 'put': self::$instance->put($end_point, $param_array); break; case 'delete': self::$instance->delete($end_point, $param_array); break; } if (self::$instance->error) { if((int)self::$instance->errorCode===500) { $response = json_decode(self::$instance->response, true); if(isset($response['errorcode']) && $response['errortext']) { return array('status'=>'failed', 'reason' => $response['errorcode'].'#'.$response['errortext']); } else { return ['status'=>'failed', 'reason' => '#Unknown error.']; } } else { return array( 'status'=>'failed', 'reason'=> '( '.self::$instance->errorCode.' ) '.self::$instance->errorMessage ); } } elseif($process_response) { return $this->processResponse($uri,self::$instance->response,self::$instance->httpStatusCode,$debug); } else { return self::$instance->response; } } public function processResponse($uri='',$api_response='',$http_status_code=0,$debug=false) { // var_dump($api_response); // exit; if($debug) { echo '<pre>'; var_dump($api_response); echo '</pre>'; exit; } $response = false; $data = json_decode($api_response, true); if( is_array($data) && count($data)>0 && $data['status']==='failed' ) { $response = array('status'=>$data['status'], 'reason'=>$data['errorcode'].'#'.$data['errortext']); } elseif(is_array($data) && count($data)>0 && $data['status']=='success') { $response = array('status'=>'success', 'response'=>$data['response']); } elseif((int)$http_status_code===204) {# for delete methods. $response = array('status'=>'success'); } elseif($uri == 'authorize') { $data = base64_decode($api_response); $response = json_decode($data, true); } if($response === false) { // $response = array( // 'status' => 'failed', // 'reason' => 'No response returned by Upstream server.' // ); echo '<pre>'; var_dump($api_response); echo '</pre>'; exit; } return $response; } }<file_sep>/src/FrameWork/FrameWork.php <?php namespace FrameWork; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\HttpKernel\Controller\ControllerResolver; use Symfony\Component\HttpFoundation\Cookie; use FrameWork\Template; use FrameWork\Utilities; ini_set('date.timezone', 'Asia/Kolkata'); if(Utilities::is_session_started() === FALSE) session_start(); // main class class FrameWork { protected $matcher; protected $resolver; protected $template; protected $response; public function __construct(UrlMatcher $matcher, ControllerResolver $resolver) { $this->matcher = $matcher; $this->resolver = $resolver; $this->template = new Template(__DIR__.'/../Layout/'); $this->response = new Response; } public function handle(Request $request) { $this->matcher->getContext()->fromRequest($request); $path = $request->getPathInfo(); try { $request->attributes->add($this->matcher->match($path)); $controller = $this->resolver->getController($request); $arguments = $this->resolver->getArguments($request, $controller); $controller_response = call_user_func_array($controller, $arguments); if(is_array($controller_response) && count($controller_response)>0) { $controller_output = $controller_response[0]; if(is_array($controller_response[1]) && count($controller_response[1]) > 0) { $view_vars = $controller_response[1]; } else { $view_vars = []; } } else { $controller_output = $controller_response; $view_vars = []; } $page_content = $this->template->render_view('layout', array('content' => $controller_output, 'path_url' => $path, 'view_vars' => $view_vars)); return new Response($page_content); } catch (ResourceNotFoundException $e) { // dump($e); return new Response('Not Found', 404); } catch (\Exception $e) { if($_SERVER['SERVER_ADDR'] === '127.0.0.1') { dump($e); } return new Response('An error occurred', 500); } } } <file_sep>/src/Layout/partials/footer.tpl.php <?php $is_app_exists = $ios_url !== '' || $android_url !== '' ? true : false; ?> <div class="gridContainer"> <div class="footerTop"> <?php if($is_app_exists): ?> <div class="appDownload">For more galleries and latest updates <br /><button class="btn btn-primary">Download APP</button></div> <?php else : ?> <div class="appDownload">Publish your Catalog, Share, Get Orders online <br /><button class="btn btn-primary" onclick="window.open('https://www.qwikbills.com')">Know More</button></div> <?php endif; ?> <div class="poweredBy">Powered by <br /><a href="https://www.qwikbills.com/"><img src="/images/logo.png" alt="" /></a></div> </div> </div><file_sep>/src/Catalogs/Views/view-catalog.tpl.php <?php use FrameWork\Utilities; use FrameWork\Config\Config; $cdn_url = Config::get_cdn_url(); $business_details = $catalog_details['businessDetails']; $catalog_items = $catalog_details['catalogItems']; $catalog_name = $catalog_details['catalogName']; $catalog_desc = $catalog_details['catalogDesc']; // arrange locations in array foreach($catalog_details['businessLocations'] as $location_details) { $business_locations[$location_details['locationID']] = $location_details['locationCode']; } unset($catalog_details['catalogItems']); unset($catalog_details['businessDetails']); unset($catalog_details['businessLocations']); $image_end_point = $cdn_url.'/'.$org_code; // dump($catalog_items); // exit; ?> <div class="productImages"> <?php // main loop for items $cntr = 0; foreach($catalog_items as $catalog_item_details) { $item_name = $catalog_item_details['itemName']; $item_code = $catalog_item_details['itemCode']; $item_rate = $catalog_item_details['itemRate']; $location_code = $business_locations[$catalog_item_details['locationID']]; // each item has images. foreach($catalog_item_details['images'] as $images) { $image_url = $image_end_point.'/'.$location_code.'/'.$images['imageName']; $cntr = $cntr + 1; $_SESSION['catalog_images'][$cntr] = $image_url; ?> <div class="item"> <div data-aos="fade-up"> <img src="<?php echo $image_url ?>" alt="Image" class="img-fluid"> <div class="imageOverlay"></div> <div class="hoverIcons"> <div class="imageView"> <a href="<?php echo $image_url ?>" data-fancybox="gallery"> <img src="/images/ic_view.png" alt="View" /> </a> </div> <div class="qty"> <input type="text" value="1" id="qty_<?php echo $item_code.'_'.$cntr ?>" /> </div> <button class="addToCart" id="btn_<?php echo $item_code.'_'.$cntr ?>" onclick="cartOp('<?php echo $item_code?>', 'add', <?php echo $cntr ?>)"> <img src="/images/ic_buy.png" alt="Add to cart" /> </button> </div> <div class="productInfo"> <div class="infoWrap"> <div class="infoText"> <h3 class="productName"><?php echo $item_name ?></h3> <p class="productText"><?php //echo $item_text ?></p> </div> <?php if((float)$item_rate>0): ?> <div class="price">₹<span><?php echo number_format($item_rate,2,'.','') ?></span></div> <?php endif; ?> </div> </div> </div> </div> <?php } } ?> </div><file_sep>/src/Catalogs/Controller/CatalogsController.php <?php namespace Catalogs\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use FrameWork\Utilities; use FrameWork\Template; use FrameWork\Flash; use FrameWork\Config\Config; use Catalogs\Model\Catalogs; class CatalogsController { protected $views_path,$flash,$catalogs_model,$template; public function __construct() { $this->template = new Template(__DIR__.'/../Views/'); $this->flash = new Flash(); $this->catalogs_model = new Catalogs; } public function viewCatalog(Request $request) { $catalog_hash = !is_null($request->get('catalogCode')) ? Utilities::clean_string($request->get('catalogCode')) : ''; $catalog_params = $this->_validate_catalog_code($catalog_hash); if($catalog_params === false) { Utilities::redirect('/'); } $api_response = $this->catalogs_model->get_catalog_details($catalog_params); if($api_response['status'] && is_array($api_response['response']['catalogItems']) && count($api_response['response']['catalogItems']) > 0) { $catalog_response = $api_response['response']; } else { Utilities::redirect('/'); } // dump($api_response['response']['catalogItems']); // exit; $items_list = []; foreach($api_response['response']['catalogItems'] as $catalog_item_details) { $items_list[$catalog_item_details['itemCode']] = [ 'itemName' => $catalog_item_details['itemName'], 'uomName' => $catalog_item_details['uomName'], 'itemDescription' => $catalog_item_details['itemDescription'], 'itemRate' => $catalog_item_details['itemRate'], ]; } // unset session if already exists if(isset($_SESSION['catalog_hash']) && $_SESSION['catalog_hash'] !== $catalog_hash) { unset($_SESSION['catalog_hash']); unset($_SESSION['catalog_code']); unset($_SESSION['client_code']); unset($_SESSION['org_name']); unset($_SESSION['ios_url']); unset($_SESSION['android_url']); unset($_SESSION['catalog_name']); unset($_SESSION['cart']); } // store catalog hash for future redirects $_SESSION['catalog_hash'] = $catalog_hash; $_SESSION['catalog_code'] = $catalog_params['catalogCode']; $_SESSION['client_code'] = $catalog_params['clientCode']; $_SESSION['catalog'] = $items_list; $_SESSION['org_name'] = $catalog_response['businessDetails']['businessName']; $_SESSION['ios_url'] = $catalog_response['businessDetails']['iosUrl']; $_SESSION['android_url'] = $catalog_response['businessDetails']['androidUrl']; $_SESSION['catalog_name'] = $catalog_response['catalogName']; // prepare form variables. $template_vars = array( 'catalog_details' => $catalog_response, 'org_code' => $catalog_params['clientCode'], ); // build variables $controller_vars = array( 'page_title' => $_SESSION['org_name'].' - '. $_SESSION['catalog_name'], 'org_name' => $catalog_response['businessDetails']['businessName'], 'ios_url' => $catalog_response['businessDetails']['iosUrl'], 'android_url' => $catalog_response['businessDetails']['androidUrl'], 'catalog_name' => $catalog_response['catalogName'], 'catalog_hash' => $catalog_hash, ); // render template return array($this->template->render_view('view-catalog', $template_vars),$controller_vars); } public function orderItems(Request $request) { // dump($_SESSION); // exit; if(!isset($_SESSION['catalog_hash']) ) { Utilities::redirect('/'); } if(isset($_SESSION['orderOtp'])) { unset($_SESSION['orderOtp']); } // dump($_SESSION); // exit; // build variables $controller_vars = array( 'page_title' => 'Place Order'.' - '.$_SESSION['org_name'].' - '. $_SESSION['catalog_name'], 'org_name' => $_SESSION['org_name'], 'ios_url' => $_SESSION['ios_url'], 'android_url' => $_SESSION['android_url'], 'catalog_name' => $_SESSION['catalog_name'], 'catalog_hash' => $_SESSION['catalog_hash'], 'is_cart' => true, ); // render template return array($this->template->render_view('view-cart', []),$controller_vars); } public function cartOperations(Request $request) { $operation = !is_null($request->get('operation')) ? Utilities::clean_string($request->get('operation')) : false; $item_code = !is_null($request->get('itemCode')) ? Utilities::clean_string($request->get('itemCode')) : false; $qty = !is_null($request->get('qty')) ? (int)Utilities::clean_string($request->get('qty')) : false; $cntr = !is_null($request->get('cntr')) && is_numeric($request->get('cntr')) ? (int)Utilities::clean_string($request->get('cntr')) : false; // var_dump($operation, $item_code, $qty); if($operation === false || $qty === false || $item_code === '' || !is_numeric($qty) || $cntr === false) { $response = ['status' => false, 'reason' => 'Invalid input']; echo json_encode($response); exit; } if($operation === 'add' || $operation === 'remove') { if($operation === 'add') { $item_rate = 0; // check item rate is available. if(isset($_SESSION['catalog'][$item_code])) { $item_rate = (int)$_SESSION['catalog'][$item_code]['itemRate']; } // send error if item rate is invalid. if($item_rate <= 0) { $response = ['status' => false, 'reason' => 'Invalid item rate']; header('Content-Type: application/json'); echo json_encode($response); exit; } $_SESSION['cart'][$item_code]['qty'] = $qty; $_SESSION['cart'][$item_code]['imageCntr'] = $cntr; $message = 'Item added to Cart'; } elseif($operation === 'remove') { $item_codes = explode(',', $item_code); foreach($item_codes as $item_code) { unset($_SESSION['cart'][$item_code]); } $message = 'Item removed from Cart'; } $response = ['status' => true, 'reason' => $message, 'ic' => count($_SESSION['cart'])]; header('Content-Type: application/json'); echo json_encode($response); exit; } else { $response = ['status' => false, 'reason' => 'Invalid operation.']; header('Content-Type: application/json'); echo json_encode($response); exit; } } public function sendOtp(Request $request) { $mobile_no = !is_null($request->get('mobileNo')) ? Utilities::clean_string($request->get('mobileNo')) : false; if(is_numeric($mobile_no) && strlen($mobile_no) === 10 && substr($mobile_no, 0, 1) > 5) { $mobile_no_with_country_code = '91'.$mobile_no; // generate random number and assign it to session $digits = 4; $otp = rand(pow(10, $digits-1), pow(10, $digits)-1); // store otp in current user session. if(isset($_SESSION['orderOtp'])) { unset($_SESSION['orderOtp']); } // connect with api and push the message. $sms_gatway_details = Config::get_sms_api_details(); $apiKey = urlencode($sms_gatway_details['apiKey']); // Message details $sender = urlencode('QWIKBL'); $message = rawurlencode("OTP for submitting your order at Qwikbills Platform is $otp"); // Prepare data for POST request $data = array('apikey' => $apiKey, 'numbers' => $mobile_no_with_country_code, "sender" => $sender, "message" => $message); // Send the POST request with cURL $ch = curl_init($sms_gatway_details['apiUrl']); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $response_sms = json_decode($response, true); // print_r($response_sms); // exit; // check status if(is_array($response_sms) && isset($response_sms['status']) ) { $status = $response_sms['status']; if($status === 'success') { $response = ['status' => true, 'reason' => 'OTP sent successfully']; $_SESSION['orderOtp'] = $otp; } else { $response = ['status' => false, 'reason' => 'Unable to send OTP']; $_SESSION['orderOtp'] = '6853'; } } else { $response = ['status' => false, 'reason' => 'Unable to send OTP']; } } else { $response = ['status' => false, 'reason' => 'Invalid mobile no.']; } header('Content-Type: application/json'); echo json_encode($response); exit; } public function orderSubmit(Request $request) { // check whether it is a form submit or not. if(count($request->request->all()) > 0) { $form_data = $request->request->all(); $mobile_number = isset($form_data['mobileNumber']) && is_numeric($form_data['mobileNumber']) ? (int)Utilities::clean_string($form_data['mobileNumber']) : false; $otp = isset($form_data['otp']) && is_numeric($form_data['otp']) ? (int)Utilities::clean_string($form_data['otp']) : false; $business_name = isset($form_data['businessName']) && strlen($form_data['businessName']) > 1 !== '' ? Utilities::clean_string($form_data['businessName']) : false; if($mobile_number === false || $otp === false || $business_name === false) { $response = ['status' => false, 'reason' => 'Invalid input']; } elseif(isset($_SESSION['orderOtp']) && (int)$_SESSION['orderOtp'] === $otp) { // submit order to platform. if(isset($_SESSION['cart']) && count($_SESSION['cart']) > 0 && isset($_SESSION['catalog_code'])) { $order_items = []; foreach($_SESSION['cart'] as $item_code => $cart_details) { $order_items[] = ['itemCode' => $item_code, 'qty' => $cart_details['qty']]; } $order_details = []; $order_details['contact']['mobileNumber'] = $mobile_number; $order_details['contact']['businessName'] = $business_name; $order_details['items'] = $order_items; // hit api // echo json_encode($order_details); // echo // exit; $api_response = $this->catalogs_model->place_order($_SESSION['catalog_code'], $_SESSION['client_code'], $order_details); if($api_response['status']) { unset($_SESSION['cart']); $response = ['status' => true, 'orderNo' => $api_response['response']['orderNo']]; } else { $response = ['status' => false, 'reason' => $api_response['apierror']]; } } else { $response = ['status' => false, 'reason' => 'No items in Cart']; } } else { $response = ['status' => false, 'reason' => 'Invalid otp.']; } } else { $response = ['status' => false, 'reason' => 'Invalid request.']; } header('Content-Type: application/json'); echo json_encode($response); exit; } // validate gallery code private function _validate_catalog_code($catalog_hash = '') { $client_code = substr($catalog_hash, 0, 15); $catalog_code = substr($catalog_hash,15, 15); if(strlen($catalog_hash) === 0 || strlen($client_code) !== 15 && strlen($catalog_code) !== 15) { return false; } else { return ['clientCode' => $client_code, 'catalogCode' => $catalog_code]; } return false; } } <file_sep>/README.md # qbsites This codebase works with Virtual host. a) `composer install` b) Create VH and the site name like `http://qbsites.local/` <file_sep>/src/Catalogs/Views/view-cart.tpl.php <?php use FrameWork\Utilities; $cart_url = '/catalog/view/'.$_SESSION['catalog_hash']; ?> <?php if(isset($_SESSION['cart']) && count($_SESSION['cart']) > 0): ?> <section> <div class="cartSection"> <div class="leftGroup"> <div class="cartForm"> <div class="formHeader"> <div class="checkBox"> <input type="checkbox" id="cb_checkall" /><label for="cb_checkall">Select All</label> </div> <div class="deleteItem"> <button class="removeItemFromCart"><img src="/images/close.svg" alt="Remove" /></button> </div> </div> <div class="formBody"> <?php $total_amount = 0; foreach($_SESSION['cart'] as $item_key => $cart_details): $image_key = $cart_details['imageCntr']; $cart_qty = $cart_details['qty']; $product_name = isset($_SESSION['catalog'][$item_key]['itemName']) ? $_SESSION['catalog'][$item_key]['itemName'] : ''; $product_desc = isset($_SESSION['catalog'][$item_key]['itemDescription']) ? $_SESSION['catalog'][$item_key]['itemDescription'] : ''; $product_rate = isset($_SESSION['catalog'][$item_key]['itemRate']) ? $_SESSION['catalog'][$item_key]['itemRate'] : ''; $product_image = isset($_SESSION['catalog_images'][$image_key]) ? $_SESSION['catalog_images'][$image_key] : ''; $total_amount += round($cart_qty*$product_rate, 2); ?> <?php if($total_amount > 0): ?> <div class="itemRow"> <div class="cartLeftGroup"> <div class="checkBox"> <input type="checkbox" id="cb_<?php echo $item_key ?>" name="cbCartItems" class="itemCheckboxes" /> <label for="cb_<?php echo $item_key ?>">&nbsp;</label> </div> <div class="productImg"> <div class="imgWrap"><img src="<?php echo $product_image ?>" alt="" /></div> </div> <div class="productInfo"> <h3><a href="#"><?php echo $product_name ?></a></h3> <?php if($product_desc !== ''): ?> <p><?php echo $product_desc ?></p> <?php endif; ?> </div> </div> <div class="cartRightGroup"> <div class="qtyGroup"> <button id="cminus_<?php echo $image_key ?>" class="cartMinus"> <img src="/images/ic_minus.png" alt="Remove from Cart" /> </button> <input id="iqty_<?php echo $image_key ?>" type="text" value="<?php echo $cart_qty ?>" class="iqtys" /> <button id="cplus_<?php echo $image_key ?>" class="cartPlus"> <img src="/images/ic_plus.png" alt="Add to Cart" /> </button> </div> <div class="price">₹<span id="rate_<?php echo $image_key ?>"><?php echo number_format($product_rate, 2, '.', '') ?></span></div> </div> </div> <?php endif; ?> <?php endforeach; // redirect user to shopping page, if there are no qtys added. if($total_amount <= 0) { Utilities::redirect($cart_url); } ?> <div class="priceBox"> <div class="priceRow totalPrice"> <span>Total: </span> <div class="price">₹<span id="totalAmount"><?php echo number_format($total_amount, 2 , '.', '') ?></span></div> </div> <div class="noteText">*All items are subject to the availability. Price excludes applicable taxes and duties</div> </div> <!-- bottom actions --> <div class="bottomActions"> <input type="hidden" value="<?php echo $_SESSION['catalog_hash'] ?>" id="ch" /> <form id="orderSubmit" method="POST" autocomplete="off"> <div class="userForm"> <div class="formCol"> <input type="text" placeholder="Business name / Personal name" id="businessName" name="businessName" maxlength="100" /> </div> <div class="formCol"> <input type="text" placeholder="Mobile number" id="mobileNumber" name="mobileNumber" maxlength="10" /> </div> <div class="formCol"> <input type="text" placeholder="Enter OTP" id="otp" name="otp" disabled="disabled" maxlength="4" /> </div> </div> <button class="btn btn-primary" id="orderBtn" name="orderBtn" style="display:none;">Place Order</button>&nbsp; <button class="btn btn-primary" id="otpBtn" name="otpBtn">Send OTP</button> <button class="btn btn-normal" id="resendOtpBtn" name="resendOtpBtn" style="display:none;">Resend OTP</button> </form> </div> </div> </div> </div> </div> </section> <?php else: ?> <section> <div class="cartSection"> Your Cart is empty. <a href="<?php echo $cart_url ?>">Shop Now</a> </div> </section> <?php endif; ?> <?php /* <div class="errorMsg">Your order has failed</div> <div class="successMsg">Your order has been placed successfully</div> */ ?> <file_sep>/src/routes_default.php <?php use Symfony\Component\Routing; use Symfony\Component\HttpFoundation\Response; $routes = new Routing\RouteCollection(); $routes->add('default_route', new Routing\Route('/', array( '_controller' => 'User\\Controller\\UserController::errorActionNotFound', ))); $routes->add('view_catalog', new Routing\Route('/catalog/view/{catalogCode}', array( '_controller' => 'Catalogs\\Controller\\CatalogsController::viewCatalog', 'catalogCode' => null, ))); $routes->add('cart_operations', new Routing\Route('/cart/{operation}', array( '_controller' => 'Catalogs\\Controller\\CatalogsController::cartOperations', 'operation' => null, ))); $routes->add('send_otp', new Routing\Route('/send-otp/{mobileNo}', array( '_controller' => 'Catalogs\\Controller\\CatalogsController::sendOtp', 'mobileNo' => null, ))); $routes->add('order', new Routing\Route('/order', array( '_controller' => 'Catalogs\\Controller\\CatalogsController::orderItems', 'catalogCode' => null, ))); $routes->add('order_submit', new Routing\Route('/order/submit', array( '_controller' => 'Catalogs\\Controller\\CatalogsController::orderSubmit', ))); return $routes;<file_sep>/src/Layout/partials/header.tpl.php <?php $items_in_cart = isset($_SESSION['cart']) && count($_SESSION['cart']) > 0 ? count($_SESSION['cart']) : 0; ?> <div class="gridContainer"> <div class="headerWrap"> <div class="logo"> <a href="/catalog/view/<?php echo $catalog_hash ?>" title="QwikBills"> <img src="/images/logo.png" alt="" /> </a> </div> <div class="catalogName"><?php echo $org_name.' - '. $catalog_name ?></div> <div class="rightGroup"> <ul> <li> <?php if(!isset($is_cart)): ?> <a href="/order"> <span><img src="/images/ic_cart.svg" alt="Cart" /></span> <span class="itemsAdded"> <span class="cartCount"><?php echo $items_in_cart ?></span> items </span> </a> <?php else: ?> <a href="/catalog/view/<?php echo $_SESSION['catalog_hash'] ?>"> <span><img src="/images/ic_cart.svg" alt="Cart" /></span> <span class="itemsAdded"> <span class="cartCount">CONTINUE TO SHOP </span> </a> <?php endif; ?> </li> </ul> </div> </div> </div> <?php /* <li> <a href="share.html"> <span><img src="/images/ic_share.svg" alt="Share" /></span> <span>Share</span> </a> </li> */ ?> <file_sep>/src/Layout/layout.tpl.php <?php extract($view_vars); ?> <!doctype html> <html lang="en"> <head> <?php include_once "partials/head.tpl.php" ?> </head> <body> <div class="pageContainer"> <header> <?php include_once "partials/header.tpl.php" ?> </header> <?php echo $content ?> <footer> <?php include_once "partials/footer.tpl.php" ?> </footer> </div> <?php include_once "partials/footer-scripts.tpl.php" ?> </body> </html><file_sep>/src/User/Controller/UserController.php <?php namespace User\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use FrameWork\Utilities; use FrameWork\Template; class UserController { public function __construct() { $this->template = new Template(__DIR__.'/../Views/'); } /** 404 error template **/ public function errorActionNotFound() { $controller_vars = array( 'page_title' => 'Page not found' ); $template_vars = []; return array($this->template->render_view('error-404', $template_vars),$controller_vars); } }<file_sep>/src/Catalogs/Model/Catalogs.php <?php namespace Catalogs\Model; use FrameWork\ApiCaller; use FrameWork\Utilities; class Catalogs { private $api_caller; public function __construct() { $this->api_caller = new ApiCaller; } public function get_catalog_details($catalog_params = []) { $api_uri = 'qbsites/catalog/details/'.$catalog_params['catalogCode']; $response = $this->api_caller->sendRequest('get',$api_uri,[],true, false, $catalog_params['clientCode']); if($response['status']==='success') { return ['status'=>true,'response'=>$response['response']]; } else { return ['status'=>false,'apierror'=> $response['reason']]; } } public function place_order($catalog_code = '', $client_code='', $order_items = []) { $api_uri = 'qbsites/catalog-order/'.$catalog_code; $response = $this->api_caller->sendRequest('post', $api_uri, $order_items, true, false, $client_code); if($response['status']==='success') { return ['status'=>true,'response'=>$response['response']]; } else { return ['status'=>false,'apierror'=> $response['reason']]; } } }<file_sep>/src/User/Views/error-404.tpl.php <html> <head> <style type="text/css"> body { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABZ0RVh0Q3JlYXRpb24gVGltZQAxMC8yOS8xMiKqq3kAAAAcdEVYdFNvZnR3YXJlAEFkb2JlIEZpcmV3b3JrcyBDUzVxteM2AAABHklEQVRIib2Vyw6EIAxFW5idr///Qx9sfG3pLEyJ3tAwi5EmBqRo7vHawiEEERHS6x7MTMxMVv6+z3tPMUYSkfTM/R0fEaG2bbMv+Gc4nZzn+dN4HAcREa3r+hi3bcuu68jLskhVIlW073tWaYlQ9+F9IpqmSfq+fwskhdO/AwmUTJXrOuaRQNeRkOd5lq7rXmS5InmERKoER/QMvUAPlZDHcZRhGN4CSeGY+aHMqgcks5RrHv/eeh455x5KrMq2yHQdibDO6ncG/KZWL7M8xDyS1/MIO0NJqdULLS81X6/X6aR0nqBSJcPeZnlZrzN477NKURn2Nus8sjzmEII0TfMiyxUuxphVWjpJkbx0btUnshRihVv70Bv8ItXq6Asoi/ZiCbU6YgAAAABJRU5ErkJggg==); } .error-template { padding: 40px 15px;text-align: center; } .error-actions { margin-top:15px;margin-bottom:15px; } .error-actions .btn { margin-right:10px; } </style> </head> <div class="container" style="color:#2c2e36;font-family:'Open Sans',sans-serif;font-size: 18px;"> <div class="row"> <div class="col-md-12"> <div class="error-template"> <h1>Oops!</h1> <h2>404 Not Found</h2> <div class="error-details">The page you are trying to reach does not exist, or has been moved.</div> <div class="error-actions"> <a href="https://www.qwikbills.com" class="btn btn-danger btn-lg"> Return to Home </a> </div> </div> </div> </div> </div> </html> <?php exit; ?><file_sep>/src/Layout/partials/footer-scripts.tpl.php <?php $hash = mt_rand() ?> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="/js/bootbox.min.js"></script> <script src="/js/aos.js"></script> <script src="/js/jquery.fancybox.min.js"></script> <script src="/js/app.js?hash=<?php echo $hash ?>"></script>
5d3819726bdd86d1e11ead4f3fbe4ab842769cc1
[ "JavaScript", "Markdown", "PHP" ]
18
PHP
kumar-turlapati/qbsites-app
eaff19e67420dc42b105c04f1c7bc116e8ecca06
5b7a0df91d6d837723583c47af8ef037d2affe1d
refs/heads/main
<repo_name>saiprabhath2002/weather_report<file_sep>/app.py from flask import request,render_template,Flask import requests app=Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/weather',methods=['POST','GET']) def weather(): url='http://api.openweathermap.org/data/2.5/weather?q={},india&APPID=aac677282727107540ca7a173c69cfca' city=request.form['city'] r=requests.get(url.format(city)).json() print(r) return render_template('result.html',data=r) if(__name__=="__main__"): app.run(debug=True)
1d516d5f755c4d5d379e2e848218cf69513205f5
[ "Python" ]
1
Python
saiprabhath2002/weather_report
6c191c33bd635222a8b15675ddebe50a2075871a
e20a14ab82e82012c12c5794800653f9e01cdb8d
refs/heads/master
<repo_name>jachiu555/recastly-redux<file_sep>/src/config/youtube.example.js // Put your YouTube API keys here! var YOUTUBE_API_KEY = 'YAIzaSyDmSszllnLOWLmbxFe5EiPLaYDhG7LO8oY'; export default YOUTUBE_API_KEY;
98b764cf8ac0a38de77c995dd8b6144111304d3b
[ "JavaScript" ]
1
JavaScript
jachiu555/recastly-redux
ca3effccad9f383f6796a5b44d9ab8c98f0aaa4d
06f34390dc6351a1d62fc0dfd713a0d197e3d190
refs/heads/master
<repo_name>Greved/selenoid.client<file_sep>/Selenoid.Client.Tests/Infrastructure/Common/List/TestListItemConverter.cs using Selenoid.Client.Infrastructure.Common.List; namespace Selenoid.Client.Tests.Infrastructure.Common.List { public class TestListItemConverter : ListItemConverterBase { public TestListItemConverter(ISelenoidClientSettings settings) : base(settings) { } protected override string ItemUrlSegment { get; } = "test1"; } }<file_sep>/Selenoid.Client/Infrastructure/Common/List/ListResponseDeserializer.cs using System.IO; using System.Xml.Serialization; namespace Selenoid.Client.Infrastructure.Common.List { public class ListResponseDeserializer : IListResponseDeserializer { private readonly XmlSerializer responseSerializer = new XmlSerializer(typeof(ListResponse)); public ListResponse Deserialize(string response) { if (string.IsNullOrEmpty(response)) { return null; } using (TextReader reader = new StringReader(response)) { var listResponse = (ListResponse) responseSerializer.Deserialize(reader); return listResponse; } } } }<file_sep>/README.md # selenoid.client Third party implementation of Selenoid's API written in C# and .Net Core <file_sep>/Selenoid.Client/Models/SelenoidListItem.cs using System; namespace Selenoid.Client.Models { public class SelenoidListItem { public string Name { get; set; } public Uri Link { get; set; } } }<file_sep>/Selenoid.Client.Tests/Infrastructure/Common/List/ListItemConverterBaseTests.cs using System; using FakeItEasy; using FluentAssertions; using NUnit.Framework; using Selenoid.Client.Infrastructure.Common.List; using Selenoid.Client.Models; namespace Selenoid.Client.Tests.Infrastructure.Common.List { [TestFixture] public class ListItemConverterBaseTests { private ISelenoidClientSettings settings; private TestListItemConverter itemConverter; [OneTimeSetUp] public void Setup() { settings = A.Fake<ISelenoidClientSettings>(); A.CallTo(() => settings.SelenoidHostUrl).Returns("http://selenoid-host.example.com:4444"); itemConverter = new TestListItemConverter(settings); } [TestCase("")] [TestCase(null)] public void Convert_Should_Return_Null_If_Response_Item_Link_Is_Null_Or_Empty(string link) { var item = new ListResponseItem {Name = "2323", Link = link}; var actual = itemConverter.Convert(item); actual.Should().BeNull(); } [TestCase("name1")] [TestCase("name2")] public void Convert_Should_Return_Item_With_Name_From_Response_Item(string name) { var item = new ListResponseItem {Name = name, Link = "some_link"}; var actual = itemConverter.Convert(item); actual.Name.Should().Be(name); } [TestCase("http://selenoid-host1.example.com:4444")] [TestCase("http://selenoid-host2.example.com:4444")] public void Convert_Should_Return_Item_With_Link_With_Url_Prefix_From_Settings(string url) { A.CallTo(() => settings.SelenoidHostUrl).Returns(url).Once(); var item = new ListResponseItem {Name = "name1", Link = "link1"}; var actual = itemConverter.Convert(item); actual.Link.Should().Be($"{url}/test1/link1"); } [Test] public void Convert_Should_Return_Item_With_Name_And_Link_From_Response_Item() { var item = new ListResponseItem {Name = "name1", Link = "link1"}; var expected = new SelenoidListItem { Name = "name1", Link = new Uri("http://selenoid-host.example.com:4444/test1/link1") }; var actual = itemConverter.Convert(item); actual.Should().BeEquivalentTo(expected); } } }<file_sep>/Selenoid.Client/ISelenoidClientSettings.cs using System; namespace Selenoid.Client { public interface ISelenoidClientSettings { string SelenoidHostUrl { get; } } }<file_sep>/Selenoid.Client/ISelenoidVideoClient.cs using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Selenoid.Client.Models; namespace Selenoid.Client { public interface ISelenoidVideoClient { Task<List<SelenoidListItem>> GetAsync(); Task<Stream> GetAsync(string videoName); Task DeleteAsync(string videoName); } }<file_sep>/Selenoid.Client.Tests/Infrastructure/Common/List/ListItemsConverterTests.cs using System.Collections.Generic; using FakeItEasy; using FluentAssertions; using NUnit.Framework; using Selenoid.Client.Infrastructure.Common.List; using Selenoid.Client.Models; namespace Selenoid.Client.Tests.Infrastructure.Common.List { [TestFixture] public class ListItemsConverterTests { private IListResponseDeserializer deserializer; private IListItemConverter singleItemConverter; private ListItemsConverter<IListItemConverter> itemsConverter; [OneTimeSetUp] public void Setup() { singleItemConverter = A.Fake<IListItemConverter>(); deserializer = A.Fake<IListResponseDeserializer>(); itemsConverter = new ListItemsConverter<IListItemConverter>(singleItemConverter, deserializer); } [TestCaseSource(nameof(Convert_Should_Return_Empty_List_On_Incorrectly_Deserialized_Response_Cases))] public void Convert_Should_Return_Empty_List_On_Incorrectly_Deserialized_Response(ListResponse listResponse) { A.CallTo(() => deserializer.Deserialize(A<string>.Ignored)).Returns(listResponse); var actual = itemsConverter.Convert("some"); actual.Should().BeEquivalentTo(new List<SelenoidListItem>()); } private static IEnumerable<TestCaseData> Convert_Should_Return_Empty_List_On_Incorrectly_Deserialized_Response_Cases() { yield return new TestCaseData(null).SetName("Null response"); yield return new TestCaseData(new ListResponse()).SetName("Null items"); yield return new TestCaseData(new ListResponse{Items = new ListResponseItem[0]}).SetName("Empty items list"); } [Test] public void Convert_Should_Filter_Null_Items_From_Item_Converter() { var listResponse = new ListResponse { Items = new[] { new ListResponseItem(), new ListResponseItem(), new ListResponseItem(), new ListResponseItem() } }; A.CallTo(() => deserializer.Deserialize(A<string>.Ignored)).Returns(listResponse); var firstActualItem = new SelenoidListItem{Name = "1"}; var thirdActualItem = new SelenoidListItem{Name = "3"}; A.CallTo(() => singleItemConverter.Convert(A<ListResponseItem>.Ignored)).Returns(firstActualItem).Once(); A.CallTo(() => singleItemConverter.Convert(A<ListResponseItem>.Ignored)).Returns(null).Once(); A.CallTo(() => singleItemConverter.Convert(A<ListResponseItem>.Ignored)).Returns(thirdActualItem).Once(); A.CallTo(() => singleItemConverter.Convert(A<ListResponseItem>.Ignored)).Returns(null).Once(); var actual = itemsConverter.Convert("some"); var expected = new List<SelenoidListItem> { firstActualItem, thirdActualItem }; actual.Should().BeEquivalentTo(expected); } [Test] public void Convert_Should_Call_Deserializer_On_String_Response() { itemsConverter.Convert("some"); A.CallTo(() => deserializer.Deserialize("some")).MustHaveHappenedOnceExactly(); } [Test] public void Convert_Should_Item_Converter_On_Every_Item_From_Deserialized_Response() { var firstResponseItem = new ListResponseItem(); var secondResponseItem = new ListResponseItem(); var listResponse = new ListResponse { Items = new[] { firstResponseItem, secondResponseItem, } }; A.CallTo(() => deserializer.Deserialize(A<string>.Ignored)).Returns(listResponse); var actual = itemsConverter.Convert("some"); A.CallTo(() => singleItemConverter.Convert(firstResponseItem)).MustHaveHappenedOnceExactly(); A.CallTo(() => singleItemConverter.Convert(secondResponseItem)).MustHaveHappenedOnceExactly(); } } }<file_sep>/Selenoid.Client/Infrastructure/Common/List/IListItemsConverter.cs using System.Collections.Generic; using Selenoid.Client.Models; namespace Selenoid.Client.Infrastructure.Common.List { public interface IListItemsConverter<TItemConverter> where TItemConverter: IListItemConverter { List<SelenoidListItem> Convert(string response); } }<file_sep>/Selenoid.Client/Infrastructure/Common/List/ListResponse.cs using System.Xml.Serialization; namespace Selenoid.Client.Infrastructure.Common.List { [XmlRoot("pre")] public class ListResponse { [XmlElement("a")] public ListResponseItem[] Items { get; set; } } public class ListResponseItem { [XmlAttribute("href")] public string Link { get; set; } [XmlText] public string Name { get; set; } } }<file_sep>/Selenoid.Client/ISelenoidClient.cs namespace Selenoid.Client { public interface ISelenoidClient { ISelenoidVideoClient Video { get; } } }<file_sep>/Selenoid.Client/Infrastructure/Video/List/VideoListItemConverter.cs using Selenoid.Client.Infrastructure.Common.List; namespace Selenoid.Client.Infrastructure.Video.List { public class VideoListItemConverter: ListItemConverterBase { public VideoListItemConverter(ISelenoidClientSettings settings) : base(settings) { } protected override string ItemUrlSegment { get; } = "video"; } }<file_sep>/Selenoid.Client/Infrastructure/Common/List/ListItemsConverter.cs using System.Collections.Generic; using System.Linq; using Selenoid.Client.Models; namespace Selenoid.Client.Infrastructure.Common.List { public class ListItemsConverter<TItemConverter> : IListItemsConverter<TItemConverter> where TItemConverter: IListItemConverter { private readonly TItemConverter itemConverter; private readonly IListResponseDeserializer responseDeserializer; public ListItemsConverter(TItemConverter itemConverter, IListResponseDeserializer responseDeserializer) { this.itemConverter = itemConverter; this.responseDeserializer = responseDeserializer; } public List<SelenoidListItem> Convert(string response) { var listResponse = responseDeserializer.Deserialize(response); var items = listResponse?.Items? .Select(itemConverter.Convert) .Where(x => x != null) .ToList() ?? new List<SelenoidListItem>(0); return items; } } }<file_sep>/Selenoid.Client/Infrastructure/Common/List/IListResponseDeserializer.cs namespace Selenoid.Client.Infrastructure.Common.List { public interface IListResponseDeserializer { ListResponse Deserialize(string response); } }<file_sep>/Selenoid.Client/SelenoidVideoClient.cs using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading.Tasks; using Selenoid.Client.Infrastructure.Common.List; using Selenoid.Client.Infrastructure.Video.List; using Selenoid.Client.Models; namespace Selenoid.Client { public class SelenoidVideoClient : ISelenoidVideoClient { private readonly HttpClient httpClient; private readonly ISelenoidClientSettings settings; private readonly IListItemsConverter<VideoListItemConverter> listItemsConverter; public SelenoidVideoClient(HttpClient httpClient, ISelenoidClientSettings settings, IListItemsConverter<VideoListItemConverter> listItemsConverter) { this.httpClient = httpClient; this.settings = settings; this.listItemsConverter = listItemsConverter; } public async Task<List<SelenoidListItem>> GetAsync() { var stringResponse = await httpClient.GetStringAsync($"{settings.SelenoidHostUrl}/video/").ConfigureAwait(false); var items = listItemsConverter.Convert(stringResponse); return items; } public Task<Stream> GetAsync(string videoName) { var fileUrl = $"{settings.SelenoidHostUrl}/video/{videoName}"; return httpClient.GetStreamAsync(fileUrl); } public Task DeleteAsync(string videoName) { return httpClient.DeleteAsync($"{settings.SelenoidHostUrl}/video/{videoName}."); } } }<file_sep>/Selenoid.Client/Infrastructure/Common/List/IListItemConverter.cs using Selenoid.Client.Models; namespace Selenoid.Client.Infrastructure.Common.List { public interface IListItemConverter { SelenoidListItem Convert(ListResponseItem responseItem); } }<file_sep>/Selenoid.Client/SelenoidClient.cs namespace Selenoid.Client { public class SelenoidClient: ISelenoidClient { public SelenoidClient(ISelenoidVideoClient video) { Video = video; } public ISelenoidVideoClient Video { get; } } }<file_sep>/Selenoid.Client/Infrastructure/Common/List/ListItemConverterBase.cs using System; using Selenoid.Client.Models; namespace Selenoid.Client.Infrastructure.Common.List { public abstract class ListItemConverterBase : IListItemConverter { private readonly ISelenoidClientSettings settings; protected abstract string ItemUrlSegment { get; } public ListItemConverterBase(ISelenoidClientSettings settings) { this.settings = settings; } public SelenoidListItem Convert(ListResponseItem responseItem) { if (string.IsNullOrEmpty(responseItem.Link)) { return null; } var linkUrl = new Uri($"{settings.SelenoidHostUrl}/{ItemUrlSegment}/{responseItem.Link}"); return new SelenoidListItem { Link = linkUrl, Name = responseItem.Name }; } } }<file_sep>/Selenoid.Client.Tests/Infrastructure/Common/List/ListResponseDeserializerTests.cs using System.Collections.Generic; using FluentAssertions; using NUnit.Framework; using Selenoid.Client.Infrastructure.Common.List; namespace Selenoid.Client.Tests.Infrastructure.Common.List { [TestFixture] public class ListResponseDeserializerTests { private ListResponseDeserializer deserializer; [OneTimeSetUp] public void Setup() { deserializer = new ListResponseDeserializer(); } [TestCaseSource(nameof(Deserialize_Should_Correctly_Deserialize_String_Response_Cases))] public void Deserialize_Should_Correctly_Deserialize_String_Response(string input, ListResponse expected) { var actual = deserializer.Deserialize(input); actual.Should().BeEquivalentTo(expected); } private static IEnumerable<TestCaseData> Deserialize_Should_Correctly_Deserialize_String_Response_Cases() { yield return new TestCaseData( @"<pre> <a href=""link_name1"">name1</a> </pre>", new ListResponse { Items = new[] { new ListResponseItem {Link = "link_name1", Name = "name1"}, } }).SetName("Single item"); yield return new TestCaseData( @"<pre> <a href=""link_name1"">name1</a> <a href=""link_name2"">name2</a> </pre>", new ListResponse { Items = new[] { new ListResponseItem {Link = "link_name1", Name = "name1"}, new ListResponseItem {Link = "link_name2", Name = "name2"}, } }).SetName("Multiple items"); yield return new TestCaseData( @"<pre> </pre>", new ListResponse { Items = null }).SetName("No items"); yield return new TestCaseData( "", null).SetName("empty string response"); yield return new TestCaseData( null, null).SetName("null string response"); } } }
3cd63d961d6704e7a6788f115f29ae64052a626d
[ "Markdown", "C#" ]
19
C#
Greved/selenoid.client
e91ebd6e52ea2e32d94c454dcf6807a956cf4ce2
abccf306c77e7885447ef82c6b54f7be2ffdc8c2
refs/heads/master
<repo_name>t-mat/vlc-pause-click-plugin<file_sep>/pause_click.c /***************************************************************************** * pause_click.c : A filter that allows to pause/play a video by a mouse click ***************************************************************************** * Copyright (C) 2014-2017 <NAME> * * Authors: <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include <stdbool.h> #include <stddef.h> #include <stdint.h> #ifdef HAVE_CONFIG_H # include "config.h" #else # define N_(str) (str) #endif #include <vlc_atomic.h> #include <vlc_common.h> #include <vlc_filter.h> #include <vlc_mouse.h> #include <vlc_playlist.h> #include <vlc_plugin.h> #include <vlc_threads.h> #include <vlc/libvlc_version.h> #if LIBVLC_VERSION_MAJOR == 2 && LIBVLC_VERSION_MINOR == 1 # include "vlc_interface-2.1.0-git.h" #elif LIBVLC_VERSION_MAJOR == 2 && LIBVLC_VERSION_MINOR == 2 # include "vlc_interface-2.2.0-git.h" #elif LIBVLC_VERSION_MAJOR >= 3 && LIBVLC_VERSION_MINOR >= 0 # include <vlc_interface.h> #else # error "VLC version " LIBVLC_VERSION_MAJOR "." LIBVLC_VERSION_MINOR " is too old and won't be supported" #endif #define UNUSED(x) (void)(x) #define TO_CHAR(num) ( 'A' + (char)(num) ) #define FROM_CHAR(c) ( (int)( (c) - 'A' ) ) #define MOUSE_BUTTON_LIST \ SELECT_COLUMN(N_("Left Button"), MOUSE_BUTTON_LEFT, 0), \ SELECT_COLUMN(N_("Middle Button"), MOUSE_BUTTON_CENTER, 1), \ SELECT_COLUMN(N_("Right Button"), MOUSE_BUTTON_RIGHT, 2), \ SELECT_COLUMN(N_("Scroll Up"), MOUSE_BUTTON_WHEEL_UP, 3), \ SELECT_COLUMN(N_("Scroll Down"), MOUSE_BUTTON_WHEEL_DOWN, 4), \ SELECT_COLUMN(N_("Scroll Left"), MOUSE_BUTTON_WHEEL_LEFT, 5), \ SELECT_COLUMN(N_("Scroll Right"), MOUSE_BUTTON_WHEEL_RIGHT, 6) #define SELECT_COLUMN(NAME, VALUE, INDEX) NAME static const char *const mouse_button_names[] = { MOUSE_BUTTON_LIST }; #undef SELECT_COLUMN #define SELECT_COLUMN(NAME, VALUE, INDEX) TO_CHAR(VALUE) static const char mouse_button_values_string[] = { MOUSE_BUTTON_LIST , 0 }; #undef SELECT_COLUMN #define SELECT_COLUMN(NAME, VALUE, INDEX) mouse_button_values_string + INDEX static const char *const mouse_button_values[] = { MOUSE_BUTTON_LIST }; #undef SELECT_COLUMN #define SETTINGS_PREFIX "pause-click-" #define MOUSE_BUTTON_SETTING SETTINGS_PREFIX "mouse-button-setting" #define MOUSE_BUTTON_DEFAULT mouse_button_values_string // MOUSE_BUTTON_LEFT #define DOUBLE_CLICK_ENABLED_SETTING SETTINGS_PREFIX "double-click-setting" #define DOUBLE_CLICK_ENABLED_DEFAULT false #define DOUBLE_CLICK_DELAY_SETTING SETTINGS_PREFIX "double-click-delay-setting" #define DOUBLE_CLICK_DELAY_DEFAULT 300 static int OpenFilter(vlc_object_t *); static void CloseFilter(vlc_object_t *); static int OpenInterface(vlc_object_t *); static void CloseInterface(vlc_object_t *); static intf_thread_t *p_intf = NULL; static vlc_timer_t timer; static bool timer_initialized = false; static atomic_bool timer_scheduled; vlc_module_begin() set_description(N_("Pause/Play video on mouse click")) set_shortname(N_("Pause click")) #if LIBVLC_VERSION_MAJOR == 2 set_capability("video filter2", 0) #elif LIBVLC_VERSION_MAJOR >= 3 set_capability("video filter", 0) #endif set_category(CAT_VIDEO) set_subcategory(SUBCAT_VIDEO_VFILTER) set_callbacks(OpenFilter, CloseFilter) add_string(MOUSE_BUTTON_SETTING, MOUSE_BUTTON_DEFAULT, N_("Mouse button"), N_("Defines the mouse button that will pause/play the video."), false) change_string_list(mouse_button_values, mouse_button_names) add_bool(DOUBLE_CLICK_ENABLED_SETTING, DOUBLE_CLICK_ENABLED_DEFAULT, N_("Ignore double clicks"), N_("Useful if you don't want the video to " "pause when double clicking to fullscreen. Note that enabling this " "will delay pause/play action by the double click interval, so the " "experience might not be as snappy as with this option disabled."), false) add_integer_with_range(DOUBLE_CLICK_DELAY_SETTING, DOUBLE_CLICK_DELAY_DEFAULT, 20, 5000, N_("Double click interval (milliseconds)"), N_("Two clicks made during this time interval will be " "treated as a double click and will be ignored."), false) add_submodule() set_capability("interface", 0) set_category(CAT_INTERFACE) set_subcategory(SUBCAT_INTERFACE_CONTROL) set_callbacks(OpenInterface, CloseInterface) vlc_module_end() static void pause_play(void) { if (p_intf == NULL) { return; } playlist_t* p_playlist = pl_Get(p_intf); playlist_Control(p_playlist, (playlist_Status(p_playlist) == PLAYLIST_RUNNING ? PLAYLIST_PAUSE : PLAYLIST_PLAY), 0); } static void timer_callback(void* data) { UNUSED(data); if (!atomic_load(&timer_scheduled)) { return; } pause_play(); atomic_store(&timer_scheduled, false); } static int mouse(filter_t *p_filter, vlc_mouse_t *p_mouse_out, const vlc_mouse_t *p_mouse_old, const vlc_mouse_t *p_mouse_new) { UNUSED(p_mouse_out); // we don't want to process anything if no mouse button was clicked if (p_mouse_new->i_pressed == 0 && !p_mouse_new->b_double_click) { return VLC_EGENERIC; } // get mouse button from settings. updates if user changes the setting char *mouse_button_value = var_InheritString(p_filter, MOUSE_BUTTON_SETTING); if (mouse_button_value == NULL) { return VLC_EGENERIC; } int mouse_button = FROM_CHAR(mouse_button_value[0]); free(mouse_button_value); if (vlc_mouse_HasPressed(p_mouse_old, p_mouse_new, mouse_button) || // on some systems (e.g. Linux) b_double_click is not set for a double-click, so we track any click and // decide if it was a double click on our own. This provides the most uniform cross-platform behaviour. (p_mouse_new->b_double_click && mouse_button == MOUSE_BUTTON_LEFT)) { // if ignoring double click if (var_InheritBool(p_filter, DOUBLE_CLICK_ENABLED_SETTING) && timer_initialized) { if (atomic_load(&timer_scheduled)) { // it's a double click -- cancel the scheduled pause/play, if any atomic_store(&timer_scheduled, false); vlc_timer_schedule(timer, false, 0, 0); } else { // it might be a single click -- schedule pause/play call atomic_store(&timer_scheduled, true); vlc_timer_schedule(timer, false, var_InheritInteger(p_filter, DOUBLE_CLICK_DELAY_SETTING)*1000, 0); } } else { pause_play(); } } // don't propagate any mouse change return VLC_EGENERIC; } static picture_t *filter(filter_t *p_filter, picture_t *p_pic_in) { UNUSED(p_filter); // don't alter picture return p_pic_in; } static int OpenFilter(vlc_object_t *p_this) { filter_t *p_filter = (filter_t *)p_this; p_filter->pf_video_filter = filter; p_filter->pf_video_mouse = mouse; if (vlc_timer_create(&timer, &timer_callback, NULL)) { return VLC_EGENERIC; } timer_initialized = true; atomic_store(&timer_scheduled, false); return VLC_SUCCESS; } static void CloseFilter(vlc_object_t *p_this) { UNUSED(p_this); if (timer_initialized) { vlc_timer_destroy(timer); timer_initialized = false; atomic_store(&timer_scheduled, false); } } static int OpenInterface(vlc_object_t *p_this) { p_intf = (intf_thread_t*) p_this; return VLC_SUCCESS; } static void CloseInterface(vlc_object_t *p_this) { UNUSED(p_this); p_intf = NULL; }
12ae60c0587da0728ace6a2366e67e398c12abb6
[ "C" ]
1
C
t-mat/vlc-pause-click-plugin
a4940a6ffec7acdf16b1b878ffb9ef6487322ab2
6576047ba413d7da879a288365d90a4aa5e3d393
refs/heads/master
<file_sep>#!/usr/bin/python2 import argparse import datetime import glob import os import sys from yRNA_bin import yRNA_lenDist, \ yRNA_fragDist def check_output_directory_path(outPath): ''' holder ''' if not os.path.isdir(outPath): print '\nERROR: The input directory does not exist' print 'Check to make sure path is correct\n' sys.exit() def get_yRNA_summary_file_list(outPath): ''' holder ''' yRNAfiles = [y for y in glob.glob('{}/*/output/*yRNA.txt'.format(outPath))] if len(yRNAfiles) == 0: print '\nERROR: No TAB_3p_summary_yRNA.txt files detected' print 'Check to make sure output path correct and yRNA output exists' print 'in each samples output folder\n' sys.exit() return yRNAfiles def create_output_folder(outPath): ''' Create a uniquely named output folder for final results ''' now = datetime.datetime.now() c = 1 while True: d = '{}/{}_{}_{}_tRNAsummary_{}/'.format(outPath, now.year, now.month, now.day, c) try: os.makedirs(d) break except OSError: c += 1 return d def yRNA_length_distribution(outPath, samples): ''' holder ''' yRNA_lenDist.main(outPath, samples) def yRNA_fragment_distribution(outPath, samples): ''' holder ''' yRNA_fragDist.main(outPath, samples) def main(out_dir): check_output_directory_path(out_dir) yRNAfiles = get_yRNA_summary_file_list(out_dir) outPath = create_output_folder(out_dir) yRNA_length_distribution(outPath, yRNAfiles) yRNA_fragment_distribution(outPath, yRNAfiles) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Runs all the final summary scripts') parser.add_argument( 'out_dir', action='store', help='Path to output directory of miRquant') arg = parser.parse_args() main(arg.out_dir) <file_sep># Load libraries library(ggplot2) library(reshape2) library(plyr) library(gridExtra) # Get command line argument args <- commandArgs(TRUE) # Set working directory setwd(dirname(args[1])) # Load Data df <- read.csv(args[1], header = T, sep = ",") # Get number of samples num_samp = length(unique(df$sample)) ### Create yRNA length distribution on sample by sample basis # Make graph png("yRNA_length_distribution.png", width = 10, height = 3 * num_samp, units = "in", res = 200) gg <- ggplot(df, aes(x = length, y = len_per, fill = prevalence)) + geom_bar(stat="identity") + ylim(0,100) + facet_wrap(~yRNA, nrow = 1) + scale_fill_gradientn(colours = c('#289fd6', '#f4ee42', '#f45041'), limits=c(0, 100)) + theme_bw() + labs(list(title="Length Distribution", x="Read length", y="Percent of total reads")) lp <- dlply(df, "sample", function(d) gg %+% d + ggtitle(unique(d$sample))) grid.arrange(grobs=lp, ncol=1) invisible(dev.off()) ### Create yRNA distribution across samples df <- unique(df[,c("sample","yRNA","prevalence")]) # Get colors color_set = c('#FF8360', '#63A375', '#E8E288', '#3CDBD3') # Make graph png('yRNA_distribution.png', unit='in', width = num_samp + 2, height = 6, res = 200) ggplot(df, aes(sample, prevalence, fill = yRNA)) + geom_bar(stat='identity') + theme_bw() + scale_fill_manual(values=color_set) + labs(list(title="yRNA Distribution", x="Sample", y="Percent of total yRNA reads")) + theme(axis.text.x = element_text(angle = 45, hjust = 1)) invisible(dev.off()) <file_sep>#!/usr/bin/python2 import argparse import os import sys import pandas as pd import numpy as np def create_output_file(outPath): ''' holder ''' output = '{}/yRNA_fragment_distribution.csv'.format(outPath) with open(output, 'w') as fo: fo.write('yRNA,loc,count,sample\n') return output def load_data(fi): ''' Load file ''' return pd.read_csv(fi, sep='\t') def split_name_into_parts(df): ''' Split the yRNA name into parts and subset df. ''' df1 = df['Name'].str.split('_', expand = True) df1['yRNA'] = df1[0].str.split('-').str[1] df2 = pd.concat([df['Name'], df1['yRNA'], df1.iloc[ : , 1:-1], df['Count']], axis=1) df2.columns = ['Name', 'yRNA', 'start', 'end', 'length', 'strand', 'count'] df2 = df2.apply(lambda x: pd.to_numeric(x, errors='ignore')) return df2 def fragment_location_counts(df): ''' holder ''' frag_di = {} for index, row in df.iterrows(): yRNA = row['yRNA'] counts = row['count'] if yRNA not in frag_di: frag_di[yRNA] = {l: 0 for l in range(0, row['length'] + 1)} for n in range(row['start'], row['end'] + 1): try: frag_di[yRNA][n] += counts except KeyError: pass return frag_di def write_fragment_locations(frag_loc, output, name): ''' holder ''' yRNA_name = {'yRNA1' : 'RNY1', 'yRNA2' : 'RNY2', 'yRNA3' : 'RNY3', 'yRNA4' : 'RNY4', 'yRNA5' : 'RNY5'} with open(output, 'a+') as fo: for yRNA, locs in frag_loc.iteritems(): for loc, count in locs.iteritems(): fo.write('{},{},{},{}\n'.format(yRNA_name[yRNA], loc, count, name)) def location_within_yRNA(df): ''' Add whether rna fragment is in the 5', middle, or 3' end of yRNA. ''' type_di = {1 : "5' half", 0 : "middle", -1 : "3' half"} df['type'] = np.where(df['end'] < df['length'] / 2, 1, np.where(df['start'] > df['length'] / 2, -1, 0)) df['type'] = np.where(df['strand'] == '-', df['type'] * -1, np.where(df['strand'] == 'R-', df['type'] * -1, df['type'] * 1)) df['type'].replace(type_di, inplace = True) summ_df = df[['yRNA','type','count']].groupby(['yRNA', 'type']).sum() summ_df.head() return df, summ_df def write_output_files(df, summ_df, name): ''' holder ''' df.to_csv('tRNA_half.csv') summ_df.reset_index().set_index(['yRNA','type']).sortlevel(0).to_csv('tRNA_half_summary.csv') def make_R_figures(r_dir, output): ''' holder ''' os.system('Rscript --vanilla {}/yrnaFragDistGraph.R {}'.format(r_dir, output)) pass def main(outPath, samples): output = create_output_file(outPath) for s in samples: name = s.split('/')[-3] df = load_data(s) df = split_name_into_parts(df) frag_loc = fragment_location_counts(df) write_fragment_locations(frag_loc, output, name) print 'Output saved as: {}'.format(output) make_R_figures(os.path.dirname(__file__), output) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Analyzed the length distribution of trimmed reads') parser.add_argument( 'outPath', action='store', help='Path to where the output file will be located') parser.add_argument( 'samples', action='store', nargs='+', help='Path to where the sample output folders are located') arg = parser.parse_args() main(arg.outPath, arg.samples) <file_sep># Load necessary libraries library(ggplot2) library(plyr) library(gridExtra) # Get command line argument args <- commandArgs(TRUE) # Set working directory setwd(dirname(args[1])) # Load yRNA fragment distribution data df <- read.csv(args[1]) # Normalize so the location with the highest # of counts is 1 yRNAs = unique(df$yRNA) for (sample in unique(df$sample)) { for (yRNA in yRNAs) { max_c = max(df[df$yRNA == yRNA & df$sample == sample, 'count']) df$count = ifelse(df$yRNA == yRNA & df$sample == sample, df$count / max_c, df$count) } } # Graph fragment data with ggplot2 height_multi = length(unique(df$sample)) png("yRNA_fragment_distribution.png", width = 10, height = 3 * height_multi, units = "in", res = 200) gg <- ggplot(df, aes(loc, count)) + geom_bar(stat='identity', width = 1) + scale_x_continuous(name = 'Nucleotide position') + scale_y_continuous(name = 'Fragment amount', breaks = c(0,.25,.5,.75,1)) + facet_wrap(~yRNA, nrow = 1, scales = "free_x") + theme_bw() lp <- dlply(df, "sample", function(d) gg %+% d + ggtitle(unique(d$sample))) grid.arrange(grobs=lp, ncol=1) invisible(dev.off()) <file_sep>#!/usr/bin/python2 usage=''' Usage: python lenDist.py /path/to/sample_output_directory file_list Output saved as lenDist_yRNA.csv and lenDist_yRNA.png Description: Calculates the read length distribution post-trimming across all samples. Create a length distribultion graph for each of the samples. ''' import argparse import os import sys def calculate_yRNA_proportions(yRNA_di): ''' holder ''' tot = sum([sum(l.values()) for l in yRNA_di.values()]) tot_count = {y: sum(l.values()) / tot * 100 for y, l in yRNA_di.iteritems()} return tot_count def calculate_length_percentage(yRNA_di): ''' Calculate the percentage of total reads for each read length on a yRNA-by-yRNA basis ''' for yRNA, lengths in yRNA_di.iteritems(): tot = sum(lengths.values()) for len, count in lengths.iteritems(): yRNA_di[yRNA][len] = count / tot * 100 return yRNA_di def read_lengths_dict(file): ''' Load the length distribution data into a dictionary If the read length is greater than 60% of the yRNA length, don't include in the analysis. ''' yRNA_di = {} lengths = {} yRNAs = {} with open(file, 'r') as fi: fi.next() for l in fi: l = l.split('\t') counts = float(l[5]) name_li = l[0].split('_') yRNA = name_li[0].split('-')[-1] length = int(name_li[2]) - int(name_li[1]) full_length = int(name_li[3]) # Dont include if nearly a full yRNA if length > 50: print l continue if yRNA not in yRNA_di: yRNA_di[yRNA] = {} yRNAs[yRNA] = 1 try: yRNA_di[yRNA][length] += counts except KeyError: yRNA_di[yRNA][length] = counts lengths[length] = 1 tot_count = calculate_yRNA_proportions(yRNA_di) yRNA_di = calculate_length_percentage(yRNA_di) return yRNA_di, lengths, yRNAs, tot_count def process_yRNA_files(samples): ''' For each TAB_3p_summary_yRNA file, get a summary of the read length distribution ''' out_di = {f.split('/')[-3]: {} for f in samples} tot_counts = {f.split('/')[-3]: {} for f in samples} lengths = {} yRNAs = {} for file in samples: f = file.split('/')[-3] out_di[f], tLENGTH, tYRNAs, tot_counts[f] = read_lengths_dict(file) lengths.update(tLENGTH) yRNAs.update(tYRNAs) return out_di, lengths, yRNAs, tot_counts def distributions_output(outPath, lengths, yRNAs, out_di, yRNA_counts): ''' pass ''' yRNA_name = {'yRNA1' : 'RNY1', 'yRNA2' : 'RNY2', 'yRNA3' : 'RNY3', 'yRNA4' : 'RNY4', 'yRNA5' : 'RNY5'} low = int(min(lengths)) high = int(max(lengths)) output = '{}/yRNA_distributions.csv'.format(outPath) print 'Output saved as: {}'.format(output) with open(output, 'w') as f: f.write('sample,yRNA,length,len_per,prevalence\n') for samp in out_di: for y in yRNAs: for l in range(low, high + 1): try: len_per = out_di[samp][y][int(l)] except KeyError: len_per = 0 f.write('{},{},{},{},{}\n'.format(samp, yRNA_name[y], l, len_per, yRNA_counts[samp][y])) return output def make_R_figures(r_dir, fi): ''' Create a length distribution image from the data. Create a yRNA distribution image from the data. ''' os.system('Rscript --vanilla {}/yrnaDistGraph.R {}'.format(r_dir, fi)) def main(outPath, samples): out_di, lengths, yRNAs, tot_counts = process_yRNA_files(samples) output = distributions_output(outPath, lengths, yRNAs, out_di, tot_counts) make_R_figures(os.path.dirname(__file__), output) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Analyzed the length distribution of trimmed reads') parser.add_argument( 'outPath', action='store', help='Path to where the output file will be located') parser.add_argument( 'samples', action='store', nargs='+', help='Path to where the sample output folders are located') arg = parser.parse_args() main(arg.outPath, arg.samples)
b6e3d15b7e908d8cecd756b4d6185f9f325721f6
[ "Python", "R" ]
5
Python
Sethupathy-Lab/yRNA_analysis
15f3f8468257464ed707c58320d847df2755b631
aa9e1bf7741cbe10dc56fb6e97d8ac63a97623f7
refs/heads/master
<file_sep>import json import os.path import logging ## Class that mantains the configuration class Configuration: ## Config parameters parsed here _telegramToken = None _listTelegram = None _mode = None _gtm = 0 def __init__(self): self._telegramToken = "" self._listTelegram = [] self._mode = "" self._gtm = 0 def getCandidateList(self): delegates = [] #process telegrams for telegram in self._listTelegram.keys(): for delegate in self._listTelegram[telegram]: if delegate not in delegates: delegates.append(delegate) return delegates def getMode(self): return self._mode def getGtm(self): if not self._gtm is None: return self._gtm else: return 0 ##Function that return a configuration object def readConfigFile(filename): if not os.path.exists(filename): logging.error("Configuration file %s does not exists", filename) raise Exception("config.json file does not exists") configFile = open(filename, 'r') fileContent = configFile.read() configFile.close() objectJson = json.loads(fileContent) configuration = Configuration() #extract the from file configuration._telegramToken = objectJson['telegram']['token'] objectJson['telegram'].pop('token', None) configuration._listTelegram = objectJson['telegram'] # Working mode configuration._mode = objectJson['mode'] # GTM offset if 'GTM' in objectJson: configuration._gtm = objectJson['GTM'] return configuration <file_sep>## # Generate telegram messages and send to the user ## import telebot import notification_filter from datetime import datetime, timedelta #Singleton telegram bot class TelegramBot: __telegramBot = None def __init__(self): self.__telegramBot = None def getBot(self, apiKey): if self.__telegramBot is None: self.__telegramBot = telebot.TeleBot(apiKey) return self.__telegramBot ## Return the bot with the api key given def setApiKey(self, apiKey): self.__telegramBot = None return self.getBot(apiKey) #Instance for telegram bot telegramBot = TelegramBot() ## Sends a message to the user def __sendTelegramMessage(apiKey, user, msg): bot = telegramBot.getBot(apiKey) bot.send_message(int(user), str(msg) ) # Generate email message for a given delegate def __generateMessageForTelegram( delegateStatus, user, delegateName, currentTime, history): ## TODO fix this filter #check filter. If is not valid notification, not send it #if not notification_filter.checkTelegramNotification(delegateName, delegateStatus, currentTime, history): # return None #Notification ok. Check if is not present on list if delegateStatus[delegateName] is None: return "Delegate " + delegateName + " is not in the 101 top delegates list" # if is present on list msg = "" delegate = delegateStatus[delegateName] if delegate['status'] is None: delegate['status'] = 'Not found' msg = "\n\nDelegate " + delegateName + ": Status=" + delegate['status'] + "\n\t" msg = msg + "Position: " + delegate['position'] + "\tUptime: " + delegate['uptime'] + "\t" + "Approval: " + delegate['approval'] return msg ## Generates a UTC Time def generateUtcTime(): now = datetime.utcnow() return str(now).split('.')[0] ## Generates GTM time with offset def generateGtmTime(offset): now = datetime.utcnow() + timedelta(hours=offset) return str(now).split('.')[0] ## For each user of telegram, send message with notifications def sendTelegramNotifications (apiKey, userList, delegateStatusList,currentTime, history, gtmOffset): for user in userList: msgList = list() ## Generate the msg for each related delegate for delegate in userList[user]: msg = __generateMessageForTelegram(delegateStatusList, user, delegate, currentTime, history) if msg is not None: msgList.append(msg) ## Send mail msgContent = "" for msg in msgList: msgContent = msgContent + msg ### Send notification only if msgContent is available if msgContent != "": msgContent = "[ (GTM+" + str(gtmOffset) + ") " + generateGtmTime(gtmOffset) + ' ]\n' + msgContent try: __sendTelegramMessage(apiKey, user, msgContent) except: print("Cant send message for the user " + str(user)) <file_sep>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from lxml import html from pyvirtualdisplay import Display import os import logging from models.delegate_info import DelegateInfoFactory from models.delegate_info import DelegateInfoStatus ## Static Vars DELEGATE_MONITOR_URL = "https://testnet-explorer.lisk.io/delegateMonitor" CHROME_DRIVER_PATH = "C:/Program Files (x86)/Google/chromedriver_win32/chromedriver.exe" os.environ["webdriver.chrome.driver"] = CHROME_DRIVER_PATH delegateFactory = DelegateInfoFactory() #Check if OS is Linux def osIsLinux(): return os.name == 'posix' ## Generates a DOM object with selenium that mantains the html core read def readDOMDocument(url): driver = None display = None if osIsLinux(): logging.debug('OS is posix') Display(visible=0, size=(800, 600)) display.start() # use the firefox driver or chrome instead try: #driver = webdriver.Chrome(executable_path=r"C:/Program Files (x86)/Google/chromedriver_win32/chromedriver.exe") driver = webdriver.Chrome(CHROME_DRIVER_PATH) except: logging.error('Cant open a browser! Please install Chrome Core') raise Exception("Cant open a browser! Please install Chrome Core") ##Read the doc and close the driver. Wait until the 101 delegates are loaded driver.get(url) try: WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//td[@class="ng-binding" and text() = "101"]'))) except: logging.error('Timeout exceeded. Cannot open the webpage') raise Exception("Timeout exceeded. Cannot open the webpage") code = html.fromstring(driver.page_source) driver.close() driver.quit() if display is not None: logging.debug('Closing virtualenv for posix OS') display.stop() return code ## Read the delegate status from the DOM document with xpath def getDelegateStatus(code, delegateName): ## Get the row which mantais the delegate info and get status + approval delegateParsed = code.xpath('//a[@class="ng-binding" and text() = "'+ delegateName +'"]') ## In case that the delegate is not found if(delegateParsed == None or len(delegateParsed) == 0): delegate = delegateFactory.generateDelegate(delegateName) return delegate ## Delegate is found rowParent = delegateParsed[0].getparent().getparent() rowDetails = rowParent.xpath('.//td') delegate = delegateFactory.generateDelegate(delegateName) delegate['position'] = rowDetails[0].text ## If delegate is on top 101 if int(delegate['position']) < int(102): delegate['uptime'] = rowDetails[5].text delegate['approval'] = rowDetails[6].text ## Check the node status try: statusClass = rowDetails[4].xpath('.//i')[0].attrib['class'] if(statusClass != None): if 'red' in statusClass: status = DelegateInfoStatus.STATUS_NOT_FORGING elif 'orange' in statusClass: status = DelegateInfoStatus.STATUS_CYCLE_LOST elif 'green' in statusClass: status = DelegateInfoStatus.STATUS_FORGING # else: red by default except: status = DelegateInfoStatus.STATUS_NOT_FOUND delegate['status'] = status ## If delegate is not on top 101 else: delegate['uptime'] = rowDetails[3].text delegate['approval'] = rowDetails[4].text return delegate ## Read the delegates status. Must provide a delegate list def readDelegatesStatus(delegateList): #delagate status list as json delegates = {} code = readDOMDocument(DELEGATE_MONITOR_URL) #Check delegate, verify status and add to dict for delegate in delegateList: delegateStats = getDelegateStatus(code, delegate) delegates[delegate] = delegateStats return delegates <file_sep>## ## Core.py ## This file executes the workflow for the scrap bot ## import time import logging from configuration.readConfig import readConfigFile from scrap.scrap_delegates import readDelegatesStatus from telegram.generate_telegrams import sendTelegramNotifications from notification_filter import readLastLog from notification_filter import writeLastLog # Configure log logging.basicConfig(filename='out.log',format='[%(asctime)s -- %(levelname)s] %(message)s', level=logging.DEBUG) logging.debug("Start reading config...") # 1. Read the config file configuration = readConfigFile('configuration/botconfig.json') delegatesList = configuration.getCandidateList() logging.debug("Start reading config... OK") # 2. Process the delegates one by one logging.debug("Processing delegates...") delegateStatusList = readDelegatesStatus(delegatesList) logging.debug("Processing delegates... OK") # 3. Send telegram alarms ##Current time to compute notifications currentTime = time.time() history = readLastLog() # 3.1. Send telegram alerts sendTelegramNotifications(configuration._telegramToken, configuration._listTelegram, delegateStatusList, currentTime, history, configuration.getGtm() ) # 4.Write log of history writeLastLog(delegateStatusList, currentTime) print(delegateStatusList)
ea85792789ecdf1a10aa4f3073b329198a5e35f6
[ "Python" ]
4
Python
20120315PRF/20120315PRF_BT1
b14a90a9a3bc7bac980ec4f3ca0b088f53f5681e
8f08a2fb09161ecb21dc54d69c1a610b9d0c6e77
refs/heads/master
<file_sep>//Fajl: KernSem.cpp //definicije metoda klase KernelSem #include "KernSem.h" #include "semaphor.h" #include "schedule.h" #include "Loom.h" #include "switch.h" KernelSem::KernelSem(int init) { PCB::kernelSwitchDisable(); blocked = new Loom(); value = init; shouldIncValOnWakeUp = 1; PCB::kernelSwitchEnable(); } void KernelSem::blockRunning() { PCB::kernelSwitchDisable(); blocked->Add((PCB*)PCB::running); PCB::blocked->Add((PCB*)PCB::running); PCB::running->status = PCB_blocked; PCB::running->semBlockingMe = this; PCB::ready->Remove((PCB*)PCB::running); PCB::kernelSwitchEnable(); } void KernelSem::unblockSomeone() { PCB::kernelSwitchDisable(); PCB *PCB_to_unblock = blocked->getFirst(); blocked->Remove(PCB_to_unblock); PCB::blocked->Remove(PCB_to_unblock); PCB_to_unblock->status = PCB_ready; PCB_to_unblock->semBlockingMe = 0; PCB::ready->Add(PCB_to_unblock); Scheduler::put(PCB_to_unblock); PCB::kernelSwitchEnable(); } Flag KernelSem::blockingNone() const { return blocked->Count()==0; } void KernelSem::unblockDueToWakeUp(PCB *PCB_to_unblock) { //ovo se poziva samo u wakeUp metodi klase PCB if (PCB_to_unblock==0 || blockingNone()) return; PCB::kernelSwitchDisable(); if (blocked->Remove(PCB_to_unblock)) { PCB::blocked->Remove(PCB_to_unblock); PCB_to_unblock->status = PCB_ready; PCB_to_unblock->semBlockingMe = 0; PCB::ready->Add(PCB_to_unblock); Scheduler::put(PCB_to_unblock); incingValOnWakeUp(); } PCB::kernelSwitchEnable(); //zbog prirode pozivaoca promene konteksta ovde nece biti dozvoljene } int KernelSem::wait() { //po ulasku promene konteksta moraju biti dozvoljene PCB::kernelSwitchDisable(); --value; Flag shouldDispatch = 0; PCB::running->wokenUp = 0; if (value<0) { blockRunning(); shouldDispatch = 1; } else if (semPreempt) { shouldDispatch = 1; } PCB::kernelSwitchEnableDontDispatch(); if (shouldDispatch) dispatch(); if (PCB::running->wokenUp) return 0; else return 1; } void KernelSem::signal() { //po ulasku promene konteksta moraju biti dozvoljene PCB::kernelSwitchDisable(); ++value; if (value<=0) { unblockSomeone(); } PCB::kernelSwitchEnableDontDispatch(); if (semPreempt) dispatch(); } KernelSem::~KernelSem() { delete blocked; }<file_sep># Threads Student project on coding a framework for threads and event-handling. To be used as by writing your code inside userMain's run() method. Threads are used by inheriting the Thread class and overriding its run() method. This was made using an older compiler for C/C++. <file_sep>//Fajl: downThr.cpp //definicije iz downThr.h #include "downThr.h" #include "PCB.h" downtimeThread *downThr; PCB *downPCB; downtimeThread::downtimeThread() : Thread("downT", minimumStackSize, infiniteTimeSlice) { PCB::setDownPCBPointer(this); } void downtimeThread::run() { while (1); }<file_sep>//Fajl: SemGate.h //posebna vrsta semafora koji moze biti otvoren ili zatvoren #ifndef _SEM_GATE_H_ #define _SEM_GATE_H_ #include "KernSem.h" class KernelSemGate : public KernelSem { //zabrana kopiranja KernelSemGate(const KernelSemGate&); KernelSemGate& operator=(const KernelSemGate&); public: KernelSemGate(int init=1) : KernelSem(init) { shouldIncValOnWakeUp = 0; } int wait(); void signal(); void open() { signal(); } void close(); Flag is_open() const { return (value==1 ? 1 : 0); } Flag is_closed() const { return (value==0 ? 1 : 0); } }; #endif<file_sep>//Fajl: PCB.h //definicija klase PCB i nekih stvari vezanih za nju #ifndef _PCB_H_ #define _PCB_H_ #include "misc_os.h" #include "thread.h" class Semaphore; class KernelSem; class KernelSemGate; class Loom; const StackSize minimumStackSize = 256; const StackSize maximumStackSize = 32768; const Time infiniteTimeSlice = 0; const int invalidID = -1; //korisnik ovo mora definisati extern void tick(); extern int userMain (int argc, char* argv[]); class PCB; extern PCB *mainPCB, *downPCB; enum PCB_Status { PCB_created, //tek je pozvan konstruktor PCB_ready, //u redu spremnih ali nije i running PCB_running, //jeste running, ali je i u redu spremnih PCB_ended, //zavrsio se sa izvrsavanjem PCB_blocked, //ceka na nekom semaforu ili dogadjaju PCB_asleep, //nit je pozvala sleep metod PCB_downer //ovo je downtime nit nakon poziva start }; class PCB { static ID lastID; public: static volatile PCB* running; static Loom *ready; //jedan od njih je ujedno i running static Loom *blocked; //na semaforima i dogadjajima static Loom *asleep; //uspavani sleep metodom static Loom *all; //svi PCB-ovi (spremni, blokirani, gotovi, nepokrenuti...) static unsigned int numberOfWaitableThreads; static KernelSemGate *semAllWaitableThreadsCompleted; public: struct cnt_buf { Reg sp; Reg ss; Reg bp; }; struct stack_buf { Reg *mem; StackSize size; stack_buf() : mem(0) {} ~stack_buf() { delete [] mem; } }; public: cnt_buf *context; stack_buf *stack; PCB_Status status; Time givenTimeSlice; Thread *myThread; ID id; TName name; PCB *parent; Semaphore *semChildren; Loom *myChildren; volatile unsigned int childrenCount; KernelSemGate *semWaitingToComplete; Time relSleepTime; //relativno u odnosu na prethodni element u PCB::asleep KernelSem *semBlockingMe; volatile Flag wokenUp; public: PCB(Thread *MyThread, TName Name, StackSize stackSize = defaultStackSize, Time timeSlice = defaultTimeSlice); ID start(); static int sleep(Time timeToSleep); int wakeUp(); static int waitForChildren(); int waitToComplete(); ~PCB(); public: //da li je softverski dozvoljena promena konteksta? static volatile Flag switchingEnabled; //da li je neko zahtevao promenu konteksta? static volatile Flag switchDemanded; private: //za gnezdenje zabrana promena konteksta static volatile unsigned int switchDisableCount; public: //dozvole i zabrane promena konteksta //zabranjuje menjanje konteksta softverski static void kernelSwitchDisable(); //vraca mogucnost promene konteksta ako je kraj gnezdenja static void kernelSwitchEnableDontDispatch(); //kao i prethodno, uz promenu ako je dozvoljena i bila zahtevana static void kernelSwitchEnable(); private: //pomocne metode koje koristi ova klasa void initName(TName); void initStack(StackSize); void initParenthoodAndChildhood(); static void endParenthoodAndChildhood(); static void waitableThreadMayHaveFinished(); static void addRunningToAsleep(Time); static void removeFromAsleep(PCB*); void makeStartingContext(); static void runWrapper(); public: //pomocne metode koje se koriste na raznim mestima static void setDownPCBPointer(const Thread *downThr) { downPCB = downThr->myPCB; } static int waitThreadToComplete(Thread *T) { return T->waitToComplete(); } static void endSleepForNoLongerSleeping(); private: //zabrana kopiranja PCB(const PCB&); PCB& operator=(const PCB&); }; inline Flag nonThreadedID(ID id) { return id==mainPCB->id; } inline Flag isPCBWaitable(const PCB *P) { return (P!=downPCB && P!=mainPCB) ? 1 : 0; } #endif<file_sep>//Fajl: misc_os.cpp //definicije metoda iz misc_os.h #include "misc_os.h" #include <stdio.h> char* string_thread_plus_number(const int &value) { char *temp = new char[13]; //thread(6) + -32767(6) + '\0'(1) = 13 sprintf(temp, "thread%d", value); char *Destination = copy_string(temp); delete [] temp; return Destination; } Flag getIBit() { Reg temp; asm { pushf pop WORD PTR temp } if (temp & onlyIBit) return 1; else return 0; }<file_sep>//Fajl: thread.cpp //sadrzi definicije metoda klase Thread, dispatch je definisan u switch.cpp #include "thread.h" #include "Loom.h" #include "PCB.h" Thread::Thread (TName name, StackSize stackSize, Time timeSlice) { PCB::kernelSwitchDisable(); myPCB = new PCB(this, name, stackSize, timeSlice); PCB::kernelSwitchEnable(); } ID Thread::start() { return myPCB->start(); } int Thread::waitToComplete(ID id) { Thread *target_thread = getThreadById(id); if (target_thread==0) return -1; return target_thread->waitToComplete(); } int Thread::sleep(Time timeToSleep) { return PCB::sleep(timeToSleep); } int Thread::wakeUp(ID id) { Thread *target_thread = getThreadById(id); if (target_thread==0) return -1; return target_thread->myPCB->wakeUp(); } ID Thread::getId() { return myPCB->id; } TName Thread::getName() { return myPCB->name; } Thread* Thread::getThreadById(ID id) { if (nonThreadedID(id)) return 0; Thread *ret = 0; PCB::kernelSwitchDisable(); Loom::Iter *iter; for (iter = PCB::all->getStart(); iter->isIn(); iter->moveNext()) { if (iter->getPCB()->id==id) { ret = iter->getPCB()->myThread; break; } } delete iter; PCB::kernelSwitchEnable(); //ako se nit ne nadje vraca se null return ret; } ID Thread::getIdOf(TName name) { if (name==0) return invalidID; ID ret = invalidID; PCB::kernelSwitchDisable(); Loom::Iter *iter; for (iter = PCB::all->getStart(); iter->isIn(); iter->moveNext()) { if (strcmp(iter->getPCB()->name,name)==0) { ret = iter->getPCB()->id; break; } } delete iter; PCB::kernelSwitchEnable(); return ret; } TName Thread::getName(ID id) { if (id == invalidID) return 0; TName ret = 0; PCB::kernelSwitchDisable(); Loom::Iter *iter; for (iter = PCB::all->getStart(); iter->isIn(); iter->moveNext()) { if (iter->getPCB()->id==id) { ret = copy_string(iter->getPCB()->name); break; } } delete iter; PCB::kernelSwitchEnable(); return ret; } int Thread::waitForChildren() { return PCB::waitForChildren(); } int Thread::waitToComplete() { return myPCB->waitToComplete(); } Thread::~Thread() { delete myPCB; }<file_sep>//Fajl: KernEv.h //klasa KernelEv #ifndef _KERN_EV_H_ #define _KERN_EV_H_ #include "event.h" #include "KernSem.h" class PCB; class IVTEntry; class KernelEv : public KernelSem { //zabrana kopiranja KernelEv(const KernelEv&); void operator=(const KernelEv&); PCB *myAssignedPCB; IVTEntry *myEntry; public: KernelEv(IVTNo ivtNo); int wait(); void signal(); }; #endif<file_sep>//Fajl: KernSem.h //definicija klase KernelSem #ifndef _KERN_SEM_H_ #define _KERN_SEM_H_ #include "PCB.h" class KernelSem { protected: friend class PCB; Loom *blocked; volatile int value; void blockRunning(); void unblockSomeone(); int shouldIncValOnWakeUp; void incingValOnWakeUp() { value += shouldIncValOnWakeUp; } private: void unblockDueToWakeUp(PCB*); //zabrana kopiranja KernelSem(const KernelSem&); KernelSem& operator=(const KernelSem&); public: KernelSem(int init=1); virtual int wait(); virtual void signal(); int val() const { return value; } Flag blockingNone() const; virtual ~KernelSem(); }; #endif<file_sep>//Fajl: Loom.h //klasa Loom koja predstavlja skup PCB-ova i nije vlasnik tih PCB-ova #ifndef _LOOM_H_ #define _LOOM_H_ #include "misc_os.h" class PCB; class Loom { struct Elem { Elem *prev, *next; PCB *info; Elem(PCB *Info) : prev(0), next(0), info(Info) {} }; class Iter; friend class Loom::Iter; Elem *first, *last; unsigned int count; //zabrana kopiranja Loom(const Loom&); Loom& operator=(const Loom&); void Clear(); public: Loom() : first(0), last(0), count(0) {} Flag Add(PCB*); Flag AddOnEnd(PCB *P) { return Add(P); } Flag AddOnStart(PCB*); Flag AddAfter(PCB*, Loom::Iter*); Flag AddBefore(PCB*, Loom::Iter*); Flag RemoveAt(Loom::Iter*); Flag RemoveAfter(Loom::Iter*); Flag RemoveBefore(Loom::Iter*); Flag RemoveFirst(); Flag RemoveLast(); Flag Remove(const PCB*); void Empty(); unsigned int Count() const { return count; } Flag isEmpty() const { return count==0; } Loom::Iter* getStart(); Loom::Iter* getEnd(); Loom::Iter* find(PCB*); PCB* getFirst() { return first==0 ? 0 : first->info; } PCB* getLast() { return last==0 ? 0 : last->info; } ~Loom() { Clear(); } class Iter { friend class Loom; Loom *owner; Loom::Elem *current; Iter(Loom *Owner, Loom::Elem *Current) : owner(Owner), current(Current) {} public: PCB* getPCB() { return current==0 ? 0 : current->info; } PCB* getPrevPCB() { return current==0 || current->prev==0 ? 0 : current->prev->info; } PCB* getNextPCB() { return current==0 || current->next==0 ? 0 : current->next->info; } Loom* getOwner() { return owner; } void movePrev() { if (current!=0) current = current->prev; } void moveNext() { if (current!=0) current = current->next; } void moveStart() { if (owner!=0) current = owner->first; } void moveEnd() { if (owner!=0) current = owner->last; } Flag isFirst() const { return current!=0 && current->prev==0; } Flag isLast() const { return current!=0 && current->next==0; } Flag isOut() const { return current==0; } Flag isIn() const { return current!=0; } Flag isSingle() const { return current!=0 && current->prev==0 && current->next==0; } }; }; #endif<file_sep>//Fajl: arrays.h. //pomocna genericka klasa sa nizom pokazivaca na kopije onoga sto joj se prosledjuje #ifndef _ARRAYS_H_ #define _ARRAYS_H_ #include <iostream.h> #define CLASS_ARRAY_STARTING_CAPACITY 10 #define CLASS_ARRAY_EXPAND_CAPACITY 5 template <class T> class Array { T **array_of_t; unsigned int count, capacity; void Copy(const Array&); void Clear(); void Expand(); int InvalidIndex(const unsigned int &index) const { return index>=count ? 1 : 0; } public: Array():count(0),capacity(CLASS_ARRAY_STARTING_CAPACITY) { array_of_t = new T*[capacity]; } Array(const unsigned int &Capacity):count(0) { if (Capacity == 0) capacity = 1; else capacity = Capacity; array_of_t = new T*[capacity]; } Array(const Array &A) { Copy(A); } Array& operator=(const Array &A) { if (this!=&A) { Clear(); Copy(A); } return *this; } unsigned int Count() const { return count; } unsigned NoElements() const { return count==0 ? 1 : 0; } void Add(const T&); void AddOnEnd(const T &newElem) { Add(newElem); } void Remove(const unsigned int&); void RemoveKeepOrder(const unsigned int&); void RemoveFromEnd() { if (count>0) Remove(count-1); } unsigned RemoveEqualTo(const T&); unsigned RemoveEqualToKeepOrder(const T&); const T& operator[](const unsigned int&) const; T& operator[](const unsigned int&); const T& GetElement(const unsigned int &index) const { return (*this)[index]; } T& GetElement(const unsigned int &index) { return (*this)[index]; } void Empty(); ~Array() { Clear(); } }; template <class T> void Array<T>::Copy(const Array<T> &A) { count = A.count; capacity = A.capacity; array_of_t = new T*[capacity]; for (unsigned int i=0; i<count; i++) array_of_t[i] = new T(*A.array_of_t[i]); } template <class T> void Array<T>::Clear() { Empty(); delete [] array_of_t; capacity = 0; } template <class T> void Array<T>::Expand() { T **temp_array = new T*[capacity+=CLASS_ARRAY_EXPAND_CAPACITY]; for (unsigned int i=0; i<count; i++) temp_array[i] = array_of_t[i]; delete [] array_of_t; array_of_t = temp_array; } template <class T> void Array<T>::Add(const T &newElem) { if (count==capacity) Expand(); array_of_t[count++] = new T(newElem); } template <class T> void Array<T>::Remove(const unsigned int &index) { if (InvalidIndex(index)) { cout<<"GRESKA: Nevalidan indeks :"<<index<<'/'<<count<<'!'<<endl; return; } delete array_of_t[index]; if (index != count-1) array_of_t[index] = array_of_t[count-1]; --count; } template <class T> void Array<T>::RemoveKeepOrder(const unsigned int &index) { if (InvalidIndex(index)) { cout<<"GRESKA: Nevalidan indeks :"<<index<<'/'<<count<<'!'<<endl; return; } delete array_of_t[index]; --count; for (unsigned int i=index; i<count; i++) array_of_t[i] = array_of_t[i+1]; } template <class T> unsigned Array<T>::RemoveEqualTo(const T &ToCompare) { for (unsigned int i=0; i<count; ++i) { if ((*array_of_t[i])==ToCompare) { Remove(i); return 1; } } return 0; } template <class T> unsigned Array<T>::RemoveEqualToKeepOrder(const T &ToCompare) { for (unsigned int i=0; i<count; ++i) { if ((*array_of_t[i])==ToCompare) { RemoveKeepOrder(i); return 1; } } return 0; } template <class T> const T& Array<T>::operator[](const unsigned int &index) const { if (InvalidIndex(index)) cout<<"GRESKA: Nevalidan indeks :"<<index<<'/'<<count<<'!'<<endl; return *array_of_t[index]; } template <class T> T& Array<T>::operator[](const unsigned int &index) { if (InvalidIndex(index)) cout<<"GRESKA: Nevalidan indeks :"<<index<<'/'<<count<<'!'<<endl; return *array_of_t[index]; } template <class T> void Array<T>::Empty() { for (unsigned int i=0; i<count; i++) delete array_of_t[i]; count=0; } #endif<file_sep>//Fajl: program.cpp //sadrzi main koji ce pozvati userMain #include <dos.h> #include "schedule.h" #include "Loom.h" #include "PCB.h" #include "downThr.h" #include "umainThr.h" #include "switch.h" #include "SemGate.h" #include "IVTEntry.h" pInterrupt oldTimerRoutine; PCB *mainPCB; ///////////////////////////////////////////////////////////////////// // // // INICIJALIZACIJA // // // ///////////////////////////////////////////////////////////////////// void createKernelThreads(int argc, char* argv[]) { //nit nad main-om nema roditeljsku nit :-( //razlog sto ova nit postoji je da bi posle zavrsetka userMain-a mogli da vratimo kontekst u main //razlog sto nema pridruzen Thread je zato sto nije potreban i sto bi uvodjenje toga nepotrebno zakomplikovalo kod mainPCB = new PCB(0, "mainPCB", defaultStackSize, infiniteTimeSlice); mainPCB->status = PCB_running; PCB::ready->Add(mainPCB); PCB::running = mainPCB; downThr = new downtimeThread(); umainThr = new userMainThread(argc, argv); } void kernelInitialize(int argc, char* argv[]) { createKernelThreads(argc, argv); PCB::switchingEnabled = 1; //postavljanje nove prekidne rutine uz pamcenje stare oldTimerRoutine = getvect(timerIVTNo); setvect(timerIVTNo, timer); } ///////////////////////////////////////////////////////////////////// // // // IZVRSAVANJE // // // ///////////////////////////////////////////////////////////////////// int kernelExecute() { downThr->start(); umainThr->start(); PCB::semAllWaitableThreadsCompleted->wait(); return umainThr->getReturnValue(); } ///////////////////////////////////////////////////////////////////// // // // RESTAURACIJA // // // ///////////////////////////////////////////////////////////////////// void destroyKernelThreads() { delete mainPCB; delete downThr; delete umainThr; } void destroyPCBStatics() { delete PCB::ready; delete PCB::blocked; delete PCB::asleep; delete PCB::all; delete PCB::semAllWaitableThreadsCompleted; } void destroyIVTEntrys() { delete allIVTEntrys; } void kernelRestore() { PCB::switchingEnabled = 0; PCB::running = 0; destroyKernelThreads(); destroyPCBStatics(); destroyIVTEntrys(); //stara prekidna casovna rutina se postavlja gde je i bila pre menjanja tabele setvect(timerIVTNo, oldTimerRoutine); } ///////////////////////////////////////////////////////////////////// // // // NJEGOVO VISOCANSTVO, METOD MAIN // // // ///////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { kernelInitialize(argc, argv); int return_value = kernelExecute(); kernelRestore(); return return_value; }<file_sep>//Fajl: switch.h //sadrzi metode za promene konteksta #ifndef _SWITCH_H_ #define _SWITCH_H_ extern void interrupt timer(...); extern void dispatch(); #endif<file_sep>//Fajl: KernEv.cpp //def. za iz KernEv.h #include "KernEv.h" #include "semaphor.h" #include "IVTEntry.h" #include "PCB.h" KernelEv::KernelEv(IVTNo ivtNo) : KernelSem(0) { shouldIncValOnWakeUp = 0; myAssignedPCB = (PCB*)PCB::running; myEntry = allIVTEntrys->getEntry(ivtNo); myEntry->addKernelEv(this); } int KernelEv::wait() { if ((PCB*)PCB::running != myAssignedPCB) return -1; Flag shouldDispatch; Flag valueWasOne; lockRememb PCB::running->wokenUp = 0; if (value==1) { value = 0; shouldDispatch = 0; valueWasOne = 1; } else { blockRunning(); shouldDispatch = 1; valueWasOne = 0; } unlockRememb if (shouldDispatch) dispatch(); if (valueWasOne) return 1; if (PCB::running->wokenUp) return 0; else return 1; } void KernelEv::signal() { //ovaj kod se desava unutar prekidne rutine, //pa su prekidi lockovani i ne moze doci do promene konteksta if (blockingNone()) value = 1; else unblockSomeone(); }<file_sep>//Fajl: SemGate.cpp //definicije metoda klase KernelSemGate #include "SemGate.h" #include "semaphor.h" #include "Loom.h" int KernelSemGate::wait() { PCB::kernelSwitchDisable(); Flag shouldDispatch = 0; PCB::running->wokenUp = 0; if (value==0) { blockRunning(); shouldDispatch = 1; } else if (semPreempt) { shouldDispatch = 1; } PCB::kernelSwitchEnableDontDispatch(); if (shouldDispatch) dispatch(); if (PCB::running->wokenUp) return 0; else return 1; } void KernelSemGate::signal() { PCB::kernelSwitchDisable(); value = 1; unsigned int count = blocked->Count(); for (unsigned int i=0; i<count; ++i) unblockSomeone(); PCB::kernelSwitchEnable(); if (semPreempt) dispatch(); } void KernelSemGate::close() { PCB::kernelSwitchDisable(); value = 0; PCB::kernelSwitchEnable(); }<file_sep>//Fajl: IVTEntry.cpp //def. za iz IVTEntry.h #include <dos.h> #include "IVTEntry.h" #include "KernEv.h" #include "PCB.h" ///////////////////////////////////////////////////////////////////// // // // KLASA IVTENTRY // // // ///////////////////////////////////////////////////////////////////// volatile Flag IVTEntry::timerOverriden = 0; IVTEntry::IVTEntry(IVTNo ivtNo, pInterrupt myRoutine, Flag callOldRoutine) : IVTNumber(ivtNo), shouldCallOld(callOldRoutine) { //ovaj kod se poziva jos pre nego sto program pocne //zbog cega ne moramo voditi racuna o mogucnosti promene konteksta allIVTEntrys->setEntry(this, IVTNumber); myKernelEvs = new Array<KernelEv*>(); if (IVTNumber!=timerIVTNo) { oldRoutine = getvect(IVTNumber); setvect(IVTNumber, myRoutine); } else { //u ovoj situaciji callOldRoutine==0 bi se ignorisalo timerOverriden = 1; myTimerRoutine = myRoutine; } } void IVTEntry::addKernelEv(KernelEv *requester) { PCB::kernelSwitchDisable(); myKernelEvs->Add(requester); PCB::kernelSwitchEnable(); } void IVTEntry::signal() { //ovaj kod se desava unutar prekidne rutine, //pa su prekidi lockovani i ne moze doci do promene konteksta if (shouldCallOld && IVTNumber!=timerIVTNo) { oldRoutine(); } for (unsigned int i=0; i<myKernelEvs->Count(); ++i) { myKernelEvs->GetElement(i)->signal(); } PCB::switchDemanded = 1; } IVTEntry::~IVTEntry() { //ovaj kod se poziva nakon zavrsetka konkurentnog dela programa //zbog cega ne moramo voditi racuna o mogucnosti promene konteksta if (IVTNumber!=timerIVTNo) { setvect(IVTNumber, oldRoutine); } if (myKernelEvs!=0) { delete myKernelEvs; } } ///////////////////////////////////////////////////////////////////// // // // KLASA IVTENTRYCONTAINER // // // ///////////////////////////////////////////////////////////////////// IVTEntryContainer::IVTEntryContainer() { myIVTEntrys = new IVTEntry*[256]; for (int i=0; i<256; ++i) myIVTEntrys[i] = 0; } void IVTEntryContainer::setEntry(IVTEntry *newEntry, const IVTNo &index) { myIVTEntrys[index] = newEntry; } IVTEntryContainer::~IVTEntryContainer() { for (int i=0 ;i<256; ++i) delete myIVTEntrys[i]; delete [] myIVTEntrys; } IVTEntryContainer *allIVTEntrys = new IVTEntryContainer();<file_sep>//Fajl: PREPENTR.h //definicija makroa PREPAREENTRY #ifndef _PREP_ENTR_H_ #define _PREP_ENTR_H_ #include "IVTEntry.h" #define PREPAREENTRY(N,F) void interrupt XXXentryInterrupt_##N(...)\ {\ allIVTEntrys->getEntry(N)->signal();\ }\ \ IVTEntry *XXXdummyEntry_##N = new IVTEntry(N, XXXentryInterrupt_##N, F); #endif<file_sep>//Fajl: PCB.cpp //definicije metoda iz PCB.h #include <dos.h> #include "PCB.h" #include "Loom.h" #include "schedule.h" #include "semaphor.h" #include "SemGate.h" volatile PCB* PCB::running = 0; unsigned int PCB::numberOfWaitableThreads = 0; KernelSemGate* PCB::semAllWaitableThreadsCompleted = new KernelSemGate(0); volatile Flag PCB::switchingEnabled = 0; volatile Flag PCB::switchDemanded = 0; volatile unsigned int PCB::switchDisableCount = 0; ID PCB::lastID = 0; Loom* PCB::ready = new Loom(); Loom* PCB::blocked = new Loom(); Loom* PCB::asleep = new Loom(); Loom* PCB::all = new Loom(); ///////////////////////////////////////////////////////////////////// // // // KONSTRUKTOR KLASE PCB // // // ///////////////////////////////////////////////////////////////////// PCB::PCB(Thread *MyThread, TName Name, StackSize stackSize, Time timeSlice) { id = lastID++; PCB::kernelSwitchDisable(); context = new cnt_buf(); stack = new stack_buf(); PCB::kernelSwitchEnable(); myThread = MyThread; initName(Name); initStack(stackSize); givenTimeSlice = timeSlice; initParenthoodAndChildhood(); PCB::kernelSwitchDisable(); semWaitingToComplete = new KernelSemGate(0); PCB::kernelSwitchEnable(); semBlockingMe = 0; PCB::kernelSwitchDisable(); PCB::all->Add(this); PCB::kernelSwitchEnable(); status = PCB_created; } void PCB::initName(TName Name) { if (Name!=0) { PCB::kernelSwitchDisable(); name = copy_string(Name); PCB::kernelSwitchEnable(); } else { PCB::kernelSwitchDisable(); name = string_thread_plus_number(id); PCB::kernelSwitchEnable(); } } void PCB::initStack(StackSize stackSize) { stack->size = stackSize; if (stack->size < minimumStackSize) { stack->size = minimumStackSize; } else if (stack->size > maximumStackSize) { stack->size = maximumStackSize; } PCB::kernelSwitchDisable(); stack->mem = new Reg[stack->size]; PCB::kernelSwitchEnable(); } void PCB::initParenthoodAndChildhood() { //na pocetku running ce biti null, sto je u skladu sa tim sto main nit nema roditeljsku parent = (PCB*)PCB::running; PCB::kernelSwitchDisable(); myChildren = new Loom(); childrenCount = 0; semChildren = new Semaphore(0); PCB::kernelSwitchEnable(); } ///////////////////////////////////////////////////////////////////// // // // START KLASE PCB // // // ///////////////////////////////////////////////////////////////////// ID PCB::start() { if (status!=PCB_created) { //ovo ne bi trebalo da se desi u ispravnom programu return invalidID; } if (isPCBWaitable(this)) { PCB::kernelSwitchDisable(); ++numberOfWaitableThreads; PCB::kernelSwitchEnable(); } if (parent) { PCB::kernelSwitchDisable(); parent->myChildren->Add(this); ++(parent->childrenCount); PCB::kernelSwitchEnable(); } makeStartingContext(); return id; } void PCB::makeStartingContext() { //PRVO: stavlja se pocetni PSW sa setovanim I bitom stack->mem[stack->size-1] = onlyIBit; //DRUGO: na stek ide adresa omotaca za run metod niti stack->mem[stack->size-2] = FP_SEG(PCB::runWrapper); stack->mem[stack->size-3] = FP_OFF(PCB::runWrapper); //TRECE: ostavlja se mesto za registre koji se cuvaju na steku po ulasku u prekidnu rutinu context->ss = FP_SEG(stack->mem + stack->size-12); context->sp = FP_OFF(stack->mem + stack->size-12); context->bp = context->sp; //CETVRTO: postavlja se odgovarajuci status i nit se stavlja u red spremnih (ako nije downPCB) if (this!=downPCB) { status = PCB_ready; PCB::kernelSwitchDisable(); PCB::ready->Add(this); Scheduler::put(this); PCB::kernelSwitchEnable(); } else { status = PCB_downer; } } ///////////////////////////////////////////////////////////////////// // // // RUNWRAPPER KLASE PCB // // // ///////////////////////////////////////////////////////////////////// void PCB::runWrapper() { PCB::running->myThread->run(); PCB::kernelSwitchDisable(); endParenthoodAndChildhood(); waitableThreadMayHaveFinished(); PCB::running->semWaitingToComplete->open(); PCB::running->status = PCB_ended; PCB::ready->Remove((PCB*)PCB::running); PCB::kernelSwitchEnableDontDispatch(); dispatch(); } void PCB::endParenthoodAndChildhood() { if (PCB::running->parent) { PCB::running->parent->semChildren->signal(); PCB::running->parent->myChildren->Remove((PCB*)PCB::running); --(PCB::running->parent->childrenCount); } Loom::Iter *iter; for (iter = PCB::running->myChildren->getStart(); iter->isIn(); iter->moveNext()) { iter->getPCB()->parent = 0; } delete iter; } void PCB::waitableThreadMayHaveFinished() { if (isPCBWaitable((PCB*)PCB::running)) { --numberOfWaitableThreads; if (numberOfWaitableThreads==0) { semAllWaitableThreadsCompleted->open(); } } } ///////////////////////////////////////////////////////////////////// // // // SLEEP // // // ///////////////////////////////////////////////////////////////////// int PCB::sleep(Time timeToSleep) { PCB::running->wokenUp = 0; if (timeToSleep>0) { PCB::kernelSwitchDisable(); addRunningToAsleep(timeToSleep); PCB::running->status = PCB_asleep; PCB::ready->Remove((PCB*)PCB::running); PCB::kernelSwitchEnableDontDispatch(); dispatch(); } if ((PCB::running->wokenUp) != 0) return 0; else return 1; } void PCB::addRunningToAsleep(Time timeToSleep) { PCB::running->relSleepTime = timeToSleep; if (asleep->isEmpty()) { asleep->Add((PCB*)PCB::running); } else { Loom::Iter *iter = asleep->getStart(); while (iter->isIn()) { if (PCB::running->relSleepTime <= iter->getPCB()->relSleepTime) break; else { PCB::running->relSleepTime -= iter->getPCB()->relSleepTime; iter->moveNext(); } } if (iter->isOut()) { asleep->AddOnEnd((PCB*)PCB::running); } else { asleep->AddBefore((PCB*)PCB::running, iter); iter->getPCB()->relSleepTime -= PCB::running->relSleepTime; } delete iter; } } ///////////////////////////////////////////////////////////////////// // // // WAIT FOR CHILDREN I TO COMPLETE // // // ///////////////////////////////////////////////////////////////////// int PCB::waitForChildren() { int returnValue = 1; while (PCB::running->childrenCount>0) { returnValue = PCB::running->semChildren->wait(); if (returnValue == 0) break; //za nit je pozvan wakeUp } return returnValue; } int PCB::waitToComplete() { if (PCB::running==this) return -1; else return semWaitingToComplete->wait(); } ///////////////////////////////////////////////////////////////////// // // // WAKE UP // // // ///////////////////////////////////////////////////////////////////// int PCB::wakeUp() { PCB::kernelSwitchDisable(); if (status!=PCB_blocked && status!=PCB_asleep) { PCB::kernelSwitchEnable(); return 0; } if (status==PCB_blocked) //na semaforu ili eventu je { PCB::kernelSwitchDisable(); semBlockingMe->unblockDueToWakeUp(this); PCB::kernelSwitchEnable(); } else //status je PCB_asleep { PCB::kernelSwitchDisable(); removeFromAsleep(this); endSleepForNoLongerSleeping(); status = PCB_ready; PCB::ready->Add(this); Scheduler::put(this); PCB::kernelSwitchEnable(); } this->wokenUp = 1; PCB::kernelSwitchEnable(); return 1; } void PCB::removeFromAsleep(PCB *toRemove) { Loom::Iter *pos = asleep->find(toRemove); if (pos!=0) { if (!pos->isLast()) pos->getNextPCB()->relSleepTime += toRemove->relSleepTime; asleep->RemoveAt(pos); } delete pos; } ///////////////////////////////////////////////////////////////////// // // // DESTRUKTOR KLASE PCB // // // ///////////////////////////////////////////////////////////////////// PCB::~PCB() { if (isPCBWaitable(this)) waitToComplete(); PCB::kernelSwitchDisable(); PCB::all->Remove(this); delete context; delete stack; delete [] name; delete myChildren; delete semChildren; delete semWaitingToComplete; PCB::kernelSwitchEnable(); } ///////////////////////////////////////////////////////////////////// // // // DOZVOLE I Z<NAME>TEKSTA // // // ///////////////////////////////////////////////////////////////////// void PCB::kernelSwitchDisable() { lockRememb ++switchDisableCount; switchingEnabled = 0; unlockRememb } void PCB::kernelSwitchEnableDontDispatch() { lockRememb if (switchDisableCount>0) --switchDisableCount; if (switchDisableCount==0 && PCB::running!=0) switchingEnabled = 1; unlockRememb } void PCB::kernelSwitchEnable() { kernelSwitchEnableDontDispatch(); if (switchDemanded && switchingEnabled && getIBit()) dispatch(); } ///////////////////////////////////////////////////////////////////// // // // OSTALO // // // ///////////////////////////////////////////////////////////////////// void PCB::endSleepForNoLongerSleeping() { while (!(PCB::asleep->isEmpty()) && PCB::asleep->getFirst()->relSleepTime==0) { PCB *notSleeping = PCB::asleep->getFirst(); PCB::asleep->RemoveFirst(); notSleeping->status = PCB_ready; PCB::ready->Add(notSleeping); Scheduler::put(notSleeping); } }<file_sep>//Fajl: umainThr.h //definicija niti nad userMain-om #ifndef _U_MAIN_H_ #define _U_MAIN_H_ #include "misc_os.h" #include "thread.h" class userMainThread : public Thread { int return_value; int myArgc; char **myArgv; //zabrana kopiranja userMainThread(const userMainThread&); void operator=(const userMainThread&); public: userMainThread(int argc, char **argv); void run(); int getReturnValue() const { return return_value; } }; extern userMainThread *umainThr; extern int userMain (int argc, char* argv[]); #endif<file_sep>//Fajl: switch.cpp //ovde su definicije metoda iz switch.h i globalne promenljive i pomocne metode potrebne za njih #include "switch.h" #include "schedule.h" #include "misc_os.h" #include "Loom.h" #include "PCB.h" #include "IVTEntry.h" //t==temporary, sluze za premestanje Reg tsp; Reg tss; Reg tbp; //koristi se da odredi kada treba promeniti kontekst po isteku givenTimeSlice-a niti //pocetna vrednost predstavlja givenTimeSlice PCB-a glavnog programa volatile Time countdown = infiniteTimeSlice; void kernelClock() { if (PCB::running->givenTimeSlice!=infiniteTimeSlice && countdown>0) --countdown; if (PCB::switchingEnabled) { //ako je dozvoljena promena konteksta to znaci da kernelov kod //trenutno ne radi sa Loomovima, Schedulerom ili alokatorom memorije if (!(PCB::asleep->isEmpty())) { --(PCB::asleep->getFirst()->relSleepTime); PCB::endSleepForNoLongerSleeping(); } } } void getNextToExecute() { if (PCB::running->status==PCB_ready || PCB::running->status==PCB_running) { Scheduler::put((PCB*)PCB::running); PCB::running->status = PCB_ready; } if (PCB::ready->Count()>0) { PCB::running = Scheduler::get(); PCB::running->status = PCB_running; } else { PCB::running = downPCB; } } void interrupt timer(...) { if (PCB::running!=0) { tick(); kernelClock(); if (IVTEntry::timerOverriden) allIVTEntrys->getEntry(timerIVTNo)->signal(); if ((PCB::running->givenTimeSlice!=infiniteTimeSlice && countdown==0) || (PCB::switchDemanded && PCB::ready->Count()>0) || (PCB::running==downPCB && PCB::ready->Count()>0)) { if (PCB::switchingEnabled) { PCB::switchDemanded = 0; //cuvanje trenutnog konteksta asm { mov tsp, sp mov tss, ss mov tbp, bp } PCB::running->context->sp = tsp; PCB::running->context->ss = tss; PCB::running->context->bp = tbp; //nalazenje sledeceg getNextToExecute(); //postavljanje novog konteksta tsp = PCB::running->context->sp; tss = PCB::running->context->ss; tbp = PCB::running->context->bp; asm { mov sp, tsp mov ss, tss mov bp, tbp } countdown = PCB::running->givenTimeSlice; } else { PCB::switchDemanded = 1; } } } //poziv stare prekidne rutine oldTimerRoutine(); } void interrupt switchOutOfTimer(...) { //sigurno je PCB::running!=0 if (PCB::switchingEnabled) { PCB::switchDemanded = 0; //cuvanje trenutnog konteksta asm { mov tsp, sp mov tss, ss mov tbp, bp } PCB::running->context->sp = tsp; PCB::running->context->ss = tss; PCB::running->context->bp = tbp; //nalazenje sledeceg getNextToExecute(); //postavljanje novog konteksta tsp = PCB::running->context->sp; tss = PCB::running->context->ss; tbp = PCB::running->context->bp; asm { mov sp, tsp mov ss, tss mov bp, tbp } countdown = PCB::running->givenTimeSlice; } else { //ovde ne bi trebalo da se dodje PCB::switchDemanded = 1; } } void dispatch() { lockRememb switchOutOfTimer(); unlockRememb }<file_sep>//Fajl: Loom.cpp //definicije metoda klase Loom #include "Loom.h" Flag Loom::Add(PCB *toAdd) { if (toAdd==0) return 0; Elem *newElem = new Elem(toAdd); if (isEmpty()) { first = last = newElem; } else { last->next = newElem; newElem->prev = last; last = last->next; } ++count; return 1; } Flag Loom::AddOnStart(PCB *toAdd) { if (toAdd==0) return 0; Elem *newElem = new Elem(toAdd); if (isEmpty()) { first = last = newElem; } else { first->prev = newElem; newElem->next = first; first = first->prev; } ++count; return 1; } Flag Loom::AddAfter(PCB *toAdd, Loom::Iter *prevPos) { if (toAdd==0 || prevPos==0 || prevPos->isOut() || prevPos->owner!=this) return 0; Elem *newElem = new Elem(toAdd); newElem->prev = prevPos->current; newElem->next = prevPos->current->next; prevPos->current->next = newElem; if (newElem->next==0) last = newElem; else newElem->next->prev = newElem; ++count; return 1; } Flag Loom::AddBefore(PCB *toAdd, Loom::Iter *nextPos) { if (toAdd==0 || nextPos==0 || nextPos->isOut() || nextPos->owner!=this) return 0; Elem *newElem = new Elem(toAdd); newElem->prev = nextPos->current->prev; newElem->next = nextPos->current; nextPos->current->prev = newElem; if (newElem->prev==0) first = newElem; else newElem->prev->next = newElem; ++count; return 1; } Flag Loom::RemoveAt(Loom::Iter *pos) { if (pos==0 || pos->isOut() || pos->owner!=this) return 0; if (pos->isSingle()) { first = last = 0; } else if (pos->isFirst()) //i nije jedini { first = pos->current->next; first->prev = 0; } else if (pos->isLast()) //i nije jedini { last = pos->current->prev; last->next = 0; } else //sa obe strane ima elemenata { pos->current->prev->next = pos->current->next; pos->current->next->prev = pos->current->prev; } delete pos->current; pos->current = 0; --count; return 1; } Flag Loom::RemoveAfter(Loom::Iter *prevPos) { if (prevPos==0 || prevPos->isOut() || prevPos->owner!=this) return 0; Loom::Iter *temp = new Loom::Iter(this, prevPos->current->next); Flag ret = RemoveAt(temp); delete temp; return ret; } Flag Loom::RemoveBefore(Loom::Iter *nextPos) { if (nextPos==0 || nextPos->isOut() || nextPos->owner!=this) return 0; Loom::Iter *temp = new Loom::Iter(this, nextPos->current->prev); Flag ret = RemoveAt(temp); delete temp; return ret; } Flag Loom::RemoveFirst() { if (isEmpty()) return 0; Elem *temp = first; first = first->next; delete temp; if (first==0) last = 0; else first->prev = 0; --count; return 1; } Flag Loom::RemoveLast() { if (isEmpty()) return 0; Elem *temp = last; last = last->prev; delete temp; if (last==0) first = 0; else last->next = 0; --count; return 1; } Flag Loom::Remove(const PCB *toRemove) { if (toRemove==0) return 0; Loom::Iter *it = getStart(); while (it->isIn()) { if (it->current->info == toRemove) { RemoveAt(it); delete it; return 1; } else { it->moveNext(); } } //nije nadjen delete it; return 0; } void Loom::Empty() { Clear(); first = last = 0; count = 0; } Loom::Iter* Loom::getStart() { return new Iter(this, first); } Loom::Iter* Loom::getEnd() { return new Iter(this, last); } Loom::Iter* Loom::find(PCB *toFind) { if (toFind==0) return 0; Loom::Iter *it = getStart(); while (it->isIn()) { if (it->current->info == toFind) { return it; } else { it->moveNext(); } } //nije nadjen delete it; return 0; } void Loom::Clear() { Elem *it = first; while (it!=0) { Elem *temp = it; it = it->next; delete temp; } } <file_sep>//Fajl: umainThr.cpp //definicije za fajl umainThr.h #include "umainThr.h" userMainThread *umainThr; userMainThread::userMainThread(int argc, char **argv) : Thread("userMainT", defaultStackSize, defaultTimeSlice) { myArgc = argc; myArgv = argv; } void userMainThread::run() { return_value = userMain(myArgc, myArgv); }<file_sep>//Fajl: IVTEntry.h //klasa IVTEntry #ifndef _IVT_ENTRY_H_ #define _IVT_ENTRY_H_ #include "Arrays.h" typedef unsigned Flag; typedef void interrupt (*pInterrupt)(...); typedef unsigned char IVTNo; class KernelEv; ///////////////////////////////////////////////////////////////////// // // // KLASA IVTENTRY // // // ///////////////////////////////////////////////////////////////////// class IVTEntry { //zabrana kopiranja IVTEntry(const IVTEntry&); void operator=(const IVTEntry&); IVTNo IVTNumber; Flag shouldCallOld; pInterrupt oldRoutine, myTimerRoutine; Array<KernelEv*> *myKernelEvs; friend class KernelEv; void addKernelEv(KernelEv*); public: IVTEntry(IVTNo, pInterrupt, Flag); void signal(); static volatile Flag timerOverriden; ~IVTEntry(); }; ///////////////////////////////////////////////////////////////////// // // // KLASA IVTENTRYCONTAINER // // // ///////////////////////////////////////////////////////////////////// class IVTEntryContainer { //zabrana kopiranja IVTEntryContainer(const IVTEntryContainer&); void operator=(const IVTEntryContainer&); IVTEntry **myIVTEntrys; public: IVTEntryContainer(); IVTEntry* getEntry(IVTNo index) { return myIVTEntrys[index]; } void setEntry(IVTEntry*, const IVTNo&); ~IVTEntryContainer(); }; extern IVTEntryContainer *allIVTEntrys; #endif<file_sep>//Fajl: misc_os.h //header sa raznim stvarima potrebnim za projekat, misc==miscellaneous==razno #ifndef _MISC_OS_H_ #define _MISC_OS_H_ #include <string.h> inline char* copy_string(const char *Source) { char *Destination=new char[strlen(Source)+1]; strcpy(Destination, Source); return Destination; } char* string_thread_plus_number(const int &value); typedef unsigned Flag; //umesto bool tipa koji ne postoji u ovom kompajleru typedef unsigned Reg; //reg==registar typedef void interrupt (*pInterrupt)(...); //standardna prekidna rutina typedef unsigned char IVTNo; extern pInterrupt oldTimerRoutine; const IVTNo timerIVTNo = 0x08; const Reg onlyIBit = 0x200; Flag getIBit(); //Zabranjuje prekide #define XXXlock asm{ cli } //Dozvoljava prekide #define XXXunlock asm{ sti } //Zabrana i dozvola prekida sa pamcenjem stare situacije #define lockRememb Flag XXXtempI = getIBit();\ XXXlock #define unlockRememb if (XXXtempI)\ XXXunlock #endif<file_sep>//Fajl: downThr.h //definicija klase downtimeThread #ifndef _DOWN_THR_H_ #define _DOWN_THR_H_ #include "thread.h" class downtimeThread : public Thread { //zabrana kopiranja downtimeThread(const downtimeThread&); void operator=(const downtimeThread&); public: downtimeThread(); void run(); }; extern downtimeThread *downThr; extern PCB *downPCB; #endif<file_sep>//Fajl: event.cpp //definicije za iz event.h #include "event.h" #include "KernEv.h" #include "PCB.h" Event::Event(IVTNo ivtNo) { PCB::kernelSwitchDisable(); myImpl = new KernelEv(ivtNo); PCB::kernelSwitchEnable(); } int Event::wait() { return myImpl->wait(); } Event::~Event() { delete myImpl; }
23d9b01dc2642f6cc4abba8718c542775e1e508f
[ "Markdown", "C", "C++" ]
26
C++
OnionBurger/Threads
943d32c0ddf54063c87001821f7ad6f47af1c0b0
604828f9e4c7d308544b26773a2fea46e97292af
refs/heads/master
<file_sep>// inspired by https://exercism.io/tracks/javascript/exercises/etl/solutions/91f99a3cca9548cebe5975d7ebca6a85 const input = require("readline-sync"); const oldPointStructure = { 1: ['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'], 2: ['D', 'G'], 3: ['B', 'C', 'M', 'P'], 4: ['F', 'H', 'V', 'W', 'Y'], 5: ['K'], 8: ['J', 'X'], 10: ['Q', 'Z'] }; //let userWord = ""; function initialPrompt() { let userWord = input.question("Let's play some scrabble! \n \nEnter a word: ") return userWord; } let userWord = initialPrompt(); //console.log(userWord); function oldScrabbleScorer(userWord) { userWord = userWord.toUpperCase(); let letterPoints = ""; for (let i = 0; i < userWord.length; i++) { for (const pointValue in oldPointStructure ){ if (oldPointStructure[pointValue].includes(userWord[i])) { letterPoints += `Points for '${userWord[i]}': ${pointValue}\n` } } } //return console.log(letterPoints); } //let output = oldScrabbleScorer(word); //console.log(letterPoints); function simpleScore(userWord) { userWord = userWord.toUpperCase(); let simpleOutput = userWord.length; return simpleOutput; } //let onePt = simpleScore(userWord); //console.log (onePt); function vowelBonusScore(userWord) { userWord = userWord.toUpperCase(); letterPoints = 0; let vowelBonusPoints = ["A", "E", "I", "O","U"]; for (let i=0; i < userWord.length; i++) { if (vowelBonusPoints.includes(userWord[i])) { letterPoints += 3 } else { letterPoints += 1; } } return letterPoints; } //return a cumulative score for the whole word entered. function scrabbleScore(userWord){ userWord = userWord.toLowerCase() letterPoints = 0 for(let i = 0; i<userWord.length; i++){ letterPoints += newPointStructure[userWord[i]] } return letterPoints }; //return console.log(letterPoints); //let blue = vowelBonusScore(userWord); //console.log(blue); // your job is to finish writing these functions and variables that we've named // // don't change the names or your program won't work as expected. // //let scrabbleScore; let simpleScoreObj = { name: 'Simple Score', description: 'Each letter is worth 1 point', scoringFunction: simpleScore }; let vowelBonusScoreObj = { name: 'Bonus Vowels', description: 'Vowels are 3 points and consonants are 1 point', scoringFunction: vowelBonusScore }; let scrabbleScorerObj = { name: 'Scrabble', description: 'The traditional scoring algorithm', scoringFunction: scrabbleScore } const scoringAlgorithms = [simpleScoreObj, vowelBonusScoreObj, scrabbleScorerObj] function scorerPrompt() { console.log("Which scoring algorithm would you like to use?\n\n"); for(let i = 0; i<scoringAlgorithms.length; i++){ console.log(`${i} – ${scoringAlgorithms[i].name}: ${scoringAlgorithms[i].description}`) } scorerPromptToSave = input.question("Enter 0, 1, or 2: "); scorerPromptToSave = Number(scorerPromptToSave) if (scorerPromptToSave === 0 || scorerPromptToSave === 1|| scorerPromptToSave === 2) { console.log (`Score for '${userWord}': ${scoringAlgorithms[scorerPromptToSave].scoringFunction(userWord)}`) } else {console.log("Please enter the number 0,1, or 2 to select a scoring algorithm. "); scorerPrompt(); }; } function transform(pointStructure) { let newPointStruct = {}; for (key in pointStructure) { for (let i = 0; i < pointStructure[key].length; i++){ let letterItem = pointStructure[key][i]; letterItem = letterItem.toLowerCase(); newPointStruct[`${letterItem}`] = Number(key); }; }; return newPointStruct; }; let newPointStructure = transform(oldPointStructure); newPointStructure[" "] = 0; //console.log(newPointStructure); //let trial = scrabbleScore(userWord); //console.log(trial); function runProgram() { //initialPrompt(); scorerPrompt(); } // Don't write any code below this line // // And don't change these or your program will not run as expected // module.exports = { initialPrompt: initialPrompt, transform: transform, oldPointStructure: oldPointStructure, simpleScore: simpleScore, vowelBonusScore: vowelBonusScore, scrabbleScore: scrabbleScore, scoringAlgorithms: scoringAlgorithms, newPointStructure: newPointStructure, runProgram: runProgram, scorerPrompt: scorerPrompt };
f0a556a31f4c5a26a590307d3d7e823ecf8a5e09
[ "JavaScript" ]
1
JavaScript
LC101-May-2021/assignment-2-scrabble-scorer-lxscurry
e8ca1d55399ebe075fe4c355f04d19a5e9a9dccd
4b8958dd6e40b8d342660b7febc9514724c547b4
refs/heads/master
<file_sep>package com.ouc.onlinexam.service.admin; import java.util.List; import com.ouc.onlinexam.dao.admin.CourseDao; import com.ouc.onlinexam.dao.admin.ICourseDao; import com.ouc.onlinexam.po.Course; public class CourseService implements ICourseService{ private ICourseDao icd= new CourseDao(); @Override public List<Course> findCourses(String name) { // TODO Auto-generated method stub return icd.findAllCourseByInfo(name); } @Override public void addCourse(String name) { // TODO Auto-generated method stub icd.addCourse(name); } @Override public Course findCourseById(int id) { // TODO Auto-generated method stub return icd.findCourseById(id); } @Override public void updateCourseByInfo(Course course) { // TODO Auto-generated method stub icd.updateCourseById(course); } @Override public List<Course> findCoursesByTeacherId(int teaId) { // TODO Auto-generated method stub return icd.findCoursesByTeacherId(teaId); } @Override public void deleteCourse(int id) { // TODO Auto-generated method stub icd.deleteCourse(id); } } <file_sep>package com.ouc.onlinexam.servlet.teacher; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ouc.onlinexam.po.Test; import com.ouc.onlinexam.service.teacher.IQuestionService; import com.ouc.onlinexam.service.teacher.ITestService; import com.ouc.onlinexam.service.teacher.QuestionService; import com.ouc.onlinexam.service.teacher.TestService; @WebServlet("/testCreateServlet") public class TestCreateServlet extends HttpServlet{ ITestService ts = new TestService(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub /** * 之前的准备工作已做好 * 试卷对象已有,获取试卷对象后,调用业务层的方法保存试卷信息即可 * 怎么获得试卷对象 * 因为在上一个servlet中使用了request.getSession.getAttrubute() * 把试卷对象放到了session里,所以这个可以用getAttribute方法得到 */ Test t = (Test) req.getSession().getAttribute("testInfo"); ts.addTest(t); resp.sendRedirect(req.getContextPath()+"/testQueryServlet"); } } <file_sep>package com.ouc.onlinexam.servlet.teacher; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ouc.onlinexam.po.Course; import com.ouc.onlinexam.po.StuClass; import com.ouc.onlinexam.po.Teacher; import com.ouc.onlinexam.po.Test; import com.ouc.onlinexam.service.admin.CourseService; import com.ouc.onlinexam.service.admin.ICourseService; import com.ouc.onlinexam.service.admin.IStuClassService; import com.ouc.onlinexam.service.admin.StuClassService; import com.ouc.onlinexam.service.teacher.IQuestionService; import com.ouc.onlinexam.service.teacher.QuestionService; import com.ouc.onlinexam.util.ToolUtil; @WebServlet("/testAddServlet") public class TestAddServlet extends HttpServlet{ ICourseService cs = new CourseService(); IStuClassService scc = new StuClassService(); IQuestionService qs = new QuestionService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //teacherId从哪里来?从session中来 Teacher loginTeacher = (Teacher) req.getSession().getAttribute("user"); List<Course> courseList = cs.findCoursesByTeacherId(loginTeacher.getId()); List<StuClass> stuClassList = scc.findStuClassesByTeacherId(loginTeacher.getId()); //把业务层的结果放到request里,能够传递到页面上 req.setAttribute("courseList", courseList); req.setAttribute("classesList", stuClassList); req.getRequestDispatcher("/teacher/testadd.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub String courseId = req.getParameter("courseid"); String testName = req.getParameter("testname"); String endDate = req.getParameter("enddate"); String score = req.getParameter("sinscores"); String queNum = req.getParameter("sinnum"); String testTime = req.getParameter("testtime"); //复选框的值如何接收?接收到的是id号 String [] classIds = req.getParameterValues("classCheck"); /** * static类型的方法可以直接调用,不用new对象 * arraytoString方法可以直接使用,功能是把一个数组转换成一个字符串 */ String classIds2 = ToolUtil.arraytoString(classIds); String classNames = scc.findClassNamesByIds(classIds2); Course c = cs.findCourseById(Integer.valueOf(courseId)); /** * 日期格式转换 * 把给定的字符串转换成日期格式 */ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date = new Date(); try { date = formatter.parse(endDate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Teacher loginTeacher = (Teacher) req.getSession().getAttribute("user"); /** * 把试卷信息封装到Test类里 * 冲页面获取的courseId是String类型的,Test类中是int类型,因此需要转换 * Integer.valueOf提供了转换的方法 * date中存了符合日期格式的截止日期 * teacherId从当前登录用户中获取 * */ Test t = new Test(); t.setCourseId(Integer.valueOf(courseId)); t.setName(testName); t.setEndDate(date); t.setTeacherId(loginTeacher.getId()); t.setClassIds(classIds2); t.setTestTime(Integer.valueOf(testTime)); t.setScores(score); List questionList = qs.collectQuestions(Integer.valueOf(courseId),Integer.valueOf(queNum)); t.setQuestions(qs.testQuestionIds(questionList)); req.getSession().setAttribute("testInfo", t); req.setAttribute("quesList", questionList); req.setAttribute("c", c); req.setAttribute("classNames", classNames); req.setAttribute("test", t); req.getRequestDispatcher("teacher/test.jsp").forward(req, resp); } } <file_sep>package com.ouc.onlinexam.servlet.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ouc.onlinexam.service.admin.IScheduleService; import com.ouc.onlinexam.service.admin.ScheduleService; @WebServlet("/scheduleDeleteServlet") public class ScheduleDeleteServlet extends HttpServlet{ private IScheduleService ics = new ScheduleService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub int id = Integer.valueOf(req.getParameter("info")); ics.deleteSchedule(id); resp.sendRedirect(req.getContextPath()+"/scheduleQueryServlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub } } <file_sep>package com.ouc.onlinexam.servlet.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ouc.onlinexam.po.Teacher; import com.ouc.onlinexam.service.admin.ITeacherService; import com.ouc.onlinexam.service.admin.TeacherService; import com.ouc.onlinexam.util.Department; @WebServlet("/teacherAddServlet") public class TeacherAddServlet extends HttpServlet{ private ITeacherService its = new TeacherService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub //req.setAttribute("deptList", Department.values()); req.getRequestDispatcher("manager/teacheradd.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub String id = req.getParameter("num"); String username = req.getParameter("username"); String password = req.getParameter("<PASSWORD>"); //String deptName = req.getParameter("dep"); Teacher t = new Teacher(); t.setId(Integer.valueOf(id)); t.setName(username); t.setPwd(<PASSWORD>); //t.setDeptName(deptName); its.addTeacher(t); resp.sendRedirect(req.getContextPath()+"/teacherQueryServlet"); } } <file_sep>package com.ouc.onlinexam.dao.student; import java.util.List; import java.util.Map; import com.ouc.onlinexam.po.Paper; public interface IPaperDao { public void savePaper(Paper p); public List<Map<String,Object>> findPapersByInfo(int stuId,String name); public List<Map<String,Object>> paperCompareInfo(int teaId); } <file_sep># Driving-School-Test-System This system solves a problem for diving school to test the student learning results. The system can generate the test paper for the teacher conveniently and the students can answer the paper on the Internet. <file_sep>package com.ouc.onlinexam.util; public enum Department { } <file_sep>package com.ouc.onlinexam.dao.admin; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ouc.onlinexam.po.Course; import com.ouc.onlinexam.po.Teacher; import com.ouc.onlinexam.util.DBUtil; public class CourseDao implements ICourseDao { DBUtil db = new DBUtil(); @Override public List<Course> findAllCourseByInfo(String name) { // TODO Auto-generated method stub String sql = "select * from course "; List courseList = new ArrayList(); if(null!=name){ sql=sql+" where name like '%"+name+"%'"; try { courseList=db.getQueryList(Course.class, sql, new Object[]{}); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else{ try { courseList = db.getQueryList(sql); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return courseList; } @Override public void addCourse(String name) { // TODO Auto-generated method stub String sql = "insert into course(name) values(?)"; String sql2 = "select * from course where name = ?"; Course c = new Course(); try { c = (Course) db.getObject(Course.class, sql2, new Object[]{name}); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if(null==c){ try { db.execute(sql,new Object[]{name}); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override public Course findCourseById(int id) { // TODO Auto-generated method stub String sql = "select * from course where id ="+id; Course c = new Course(); try { c = (Course)db.getObject(Course.class, sql, new Object[]{}); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return c; } @Override public void updateCourseById(Course course) { // TODO Auto-generated method stub String sql = "update course set id =?,name = ? where id = ?"; String sql2 = "select * from course where name = ?"; Course c = new Course(); try { c = (Course) db.getObject(Course.class, sql2, new Object[]{course.getName()}); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if(null==c) try { db.execute(sql, new Object[]{course.getId(),course.getName(),course.getId()}); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public List<Course> findCoursesByTeacherId(int teaId) { // TODO Auto-generated method stub String sql = "SELECT * from course where id in (SELECT courseId from teachercourse where teaId = "+ teaId+")"; List courseList = new ArrayList(); try { courseList = db.getQueryList(Course.class, sql, new Object[]{}); } catch (Exception e) { e.printStackTrace(); } if(null == courseList) courseList = new ArrayList(); return courseList; } @Override public void deleteCourse(int id) { // TODO Auto-generated method stub String sql="delete from course where id ="+id; try { db.execute(sql); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package com.ouc.onlinexam.po; public class Student { private int id;//学生学号 private String name;//学生姓名 private String pwd;//<PASSWORD> //private String school;//学校名称 private String sex;//性别 private String born;//出生日期 //private String deptName;// private int classId;//所在班级 public Student(){} public Student(int id,String name ,String pwd,String sex,String born,int classId){ this.id = id; this.name = name; this.pwd = pwd; //this.school = school; this.sex = sex; this.born= born; //this.deptName = deptName; this.classId = classId; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getBorn() { return born; } public void setBorn(String born) { this.born = born; } public int getClassId() { return classId; } public void setClassId(int classId) { this.classId = classId; } } <file_sep>package com.ouc.onlinexam.servlet.admin; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ouc.onlinexam.service.admin.CourseService; import com.ouc.onlinexam.service.admin.ICourseService; @WebServlet("/courseQueryServlet") public class CourseQueryServlet extends HttpServlet{ private ICourseService ics = new CourseService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub String courseSearch = req.getParameter("courseSearch"); if (null != courseSearch) courseSearch = new String(courseSearch.getBytes("ISO-8859-1"), "utf-8"); List courseList = ics.findCourses(courseSearch); req.setAttribute("tcList", courseList); req.getRequestDispatcher("manager/coursemanage.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub } } <file_sep>package com.ouc.onlinexam.util; import com.ouc.onlinexam.po.Course; public class TestDBUtil2 { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { DBUtil db = new DBUtil(); /*String sql = "insert into course(name) values('ssh')"; db.execute(sql);*/ /*String sql1="update course set name='ssh1' where name='ssh'"; db.execute(sql1);*/ /*String sql2 ="insert into teacher(name,pwd,deptName) values(?,?,?) "; db.execute(sql2, new Object[]{"小薇","123","开发"});*/ /*String sql3="update teacher set name =? where name ='小薇'"; db.execute(sql3,new Object[]{"小biang"});*/ String sql4="select * from course where id =?"; Course c = (Course)db.getObject(Course.class,sql4,new Object[]{1}); System.out.println(c.getName()); } } <file_sep>package com.ouc.onlinexam.po; /** * 学生班级 * @author Moons * */ public class StuClass { private int id;//班级编号 private String name;//班级名称 //private String deptName;// 所属方向 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>package com.ouc.onlinexam.po; /** * 教师表 * @author Moons * */ public class Teacher { private int id;//教师工号 private String name;//教师姓名 private String pwd;//教师密码 //private String deptName;//所属方向 //private int role;// public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } /*public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; }*/ /*public int getRole() { return role; } public void setRole(int role) { this.role = role; }*/ } <file_sep>package com.ouc.onlinexam.servlet.admin; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ouc.onlinexam.po.TeacherCourse; import com.ouc.onlinexam.service.admin.CourseService; import com.ouc.onlinexam.service.admin.ICourseService; import com.ouc.onlinexam.service.admin.IScheduleService; import com.ouc.onlinexam.service.admin.IStuClassService; import com.ouc.onlinexam.service.admin.ITeacherService; import com.ouc.onlinexam.service.admin.ScheduleService; import com.ouc.onlinexam.service.admin.StuClassService; import com.ouc.onlinexam.service.admin.TeacherService; @WebServlet("/scheduleAddServlet") public class ScheduleAddServlet extends HttpServlet{ private ICourseService cs = new CourseService(); private ITeacherService ts = new TeacherService(); private IStuClassService scs = new StuClassService(); private IScheduleService ss = new ScheduleService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub List csList = cs.findCourses(null); List tsList = ts.findTeachers(null); List scsList = scs.findAll(null); req.setAttribute("courseList", csList); req.setAttribute("teaList", tsList); req.setAttribute("stuclList", scsList); req.getRequestDispatcher("manager/scheduleadd.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub int cid = Integer.valueOf(req.getParameter("course")); int tid = Integer.valueOf(req.getParameter("teacher")); int scid = Integer.valueOf(req.getParameter("stuclass")); TeacherCourse tc = new TeacherCourse(); tc.setClassId(scid); tc.setTeaId(tid); tc.setCourseId(cid); ss.addSchedule(tc); resp.sendRedirect("scheduleQueryServlet"); } } <file_sep>package com.ouc.onlinexam.service.student; import java.util.List; import java.util.Map; import com.ouc.onlinexam.dao.student.IPaperDao; import com.ouc.onlinexam.dao.student.PaperDao; import com.ouc.onlinexam.po.Paper; public class PaperService implements IPaperService{ private IPaperDao pd = new PaperDao(); @Override public void save(Paper p) { // TODO Auto-generated method stub pd.savePaper(p); } @Override public List<Map<String, Object>> findPapersByInfo(int stuId,String name) { // TODO Auto-generated method stub return pd.findPapersByInfo(stuId,name); } @Override public List<Map<String, Object>> paperCompareInfo(int teaId) { // TODO Auto-generated method stub return pd.paperCompareInfo(teaId); } } <file_sep>package com.ouc.onlinexam.servlet.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ouc.onlinexam.po.StuClass; import com.ouc.onlinexam.service.admin.IStuClassService; import com.ouc.onlinexam.service.admin.StuClassService; import com.ouc.onlinexam.util.Department; @WebServlet("/stuClassAddServlet") public class StuClassAddServlet extends HttpServlet{ private IStuClassService scs = new StuClassService(); /** * 当页面上点击“增加班级”时,访问的方法 *获取页面需要提供的方向名称,并且把数据传递到页面上 *页面跳转 */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub /** * 把servlet中的信息传递到页面上 * Department.values()可以获得所属方向的集合 * 页面上,遍历这个集合的时候起的名字是depList */ //req.setAttribute("depList", Department.values()); req.getRequestDispatcher("manager/stuclassadd.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub /** * 以下三行是从页面上获取输入的信息 * 参数名是页面上的控件name */ String id = req.getParameter("clanum"); String name = req.getParameter("claname"); //String deptName = req.getParameter("depInfo"); /** * 把从页面上提交的属性封装为对象 * request.getParameter获取的值是String类型 * 而StuClass的id是int类型 * 所以需要类型转换 * Integer.valueOf()能够把一个String类型的变量转换成int类型 */ StuClass sc = new StuClass(); sc.setId(Integer.valueOf(id)); sc.setName(name); //sc.setDeptName(deptName); //调用业务层的接口方法,增加课程信息 scs.addStuClass(sc); /** * 添加完后要跳转页面,一般要跳转到查询所有的班级页面 * 之前查询的班级信息里不包括新增加的班级 * 如果想把新增的班级显示出来,必须要再次查询一边数据库 * 而stuClassQueryServlet实现了查询功能,因此可以直接跳转 * 这里添加完成,不需要再往页面上添加信息,因此可以用resp.sendRedirect() */ resp.sendRedirect(req.getContextPath()+"/stuClassQueryServlet"); //req.getRequestDispatcher("/stuClassQueryServlet").forward(req, resp);; } } <file_sep>package com.ouc.onlinexam.dao.student; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.ouc.onlinexam.po.Paper; import com.ouc.onlinexam.util.DBUtil; public class PaperDao implements IPaperDao{ private DBUtil db = new DBUtil(); @Override public void savePaper(Paper p) { // TODO Auto-generated method stub String sql = "insert into papers(testId,courseId,time,score,wrongQueId,wrongAns,studentId,createDate) values(?,?,?,?,?,?,?,?)"; try { db.execute(sql, new Object[]{p.getTestId(),p.getCourseId(),p.getTime(),p.getScore(),p.getWrongQueId(),p.getWrongAns(),p.getStudentId(),p.getCreatDate()}); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public List<Map<String, Object>> findPapersByInfo(int stuId,String name) { // TODO Auto-generated method stub String sql = "select c.name as courseName,t.name as testName,p.time,p.createDate,p.score from course c,test t,papers p where c.id = p.courseId and t.id = p.testId and p.studentId = ?"; if(null!=name){ sql = sql+" and c.name like '%"+name+"%'"; } List paperList = new ArrayList(); try { paperList = db.getQueryList(sql,new Object[]{stuId}); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return paperList; } @Override public List<Map<String, Object>> paperCompareInfo(int teaId) { // TODO Auto-generated method stub String sql = "select DISTINCT sc.name as className,c.name as courseName,t.name testName,t.endDate,avg(p.score) as avgScore from student s,stuclass sc,course c,test t,papers p,teacher te,teachercourse tc where tc.classId = sc.id and tc.teaId = te.id and tc.courseId = c.id and t.teacherId = te.id and p.testId = t.id and p.courseId=c.id and s.classId = sc.id and find_in_set(s.id,t.classIds) and te.id="+teaId; List paperList = new ArrayList(); try { paperList = db.getQueryList(sql); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return paperList; } } <file_sep>package com.ouc.onlinexam.servlet.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ouc.onlinexam.po.StuClass; import com.ouc.onlinexam.po.Teacher; import com.ouc.onlinexam.service.admin.IStuClassService; import com.ouc.onlinexam.service.admin.ITeacherService; import com.ouc.onlinexam.service.admin.StuClassService; import com.ouc.onlinexam.service.admin.TeacherService; import com.ouc.onlinexam.util.Department; @WebServlet("/teacherModifyServlet") public class TeacherModifyServlet extends HttpServlet { private ITeacherService scs= new TeacherService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub int tId = Integer.valueOf(req.getParameter("id")); Teacher teacherMap = scs.findTeacherById(tId); req.setAttribute("teacherInfo", teacherMap); //req.setAttribute("deptList", Department.values()); req.getRequestDispatcher("manager/teachermodify.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub /** * 把从页面上提交的属性查封装为对象 * request.getParameter获取的值是String类型 * 而StuClass的id是int类型 * 所以需要类型转换 * Integer.valueOf()能够把一个String类型的变量转换成int类型 */ String id = req.getParameter("num"); String name = req.getParameter("username"); String password = req.getParameter("password"); //String deptName = req.getParameter("dep"); /** * 把从页面上提交的属性封装为对象 * request.getParameter获取的值是String类型 * 而Teacher的id是int类型 * 所以需要类型转换 * Integer.valueOf()能够把一个String类型的变量转换成int类型 */ Teacher t = new Teacher(); t.setId(Integer.valueOf(id)); t.setName(name); t.setPwd(<PASSWORD>); //t.setDeptName(deptName); scs.updateTeacherById(t); resp.sendRedirect(req.getContextPath()+"/teacherQueryServlet"); } } <file_sep>package com.ouc.onlinexam.dao.admin; import java.util.List; import com.ouc.onlinexam.po.Course; public interface ICourseDao { public List<Course> findAllCourseByInfo(String name) ; public void addCourse(String name); public Course findCourseById(int id); public void updateCourseById(Course course); public void deleteCourse(int id); /** * 根据当前的教师id查询属于这个教师的课程 * @param teaId * @return */ public List<Course> findCoursesByTeacherId(int teaId); } <file_sep>package com.ouc.onlinexam.service.teacher; import java.util.List; import java.util.Map; import com.ouc.onlinexam.po.Test; public interface ITestService { /** * 根据存储页面接受的试卷信息的t添加考试 * @param t */ public void addTest(Test t); /** * 根据学生id号查询即将考试的试卷(test表) * @param id 学生的id号 * @param currData 当前的日期时间 * @return 返回的是test集合 */ public List<Map<String, Object>> getTestByStudent(int id, String currData); /** * 根据学生id号和试卷编号查询试卷信息 * @param studentid * @param testid * @return 返回试卷信息的map */ public Map<String, Object> findStudentTestsById(int studentid,int testid); public List<Map<String, Object>> getRencentTestByTeaId(int id); } <file_sep>package com.ouc.onlinexam.servlet.admin; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ouc.onlinexam.po.TeacherCourse; import com.ouc.onlinexam.service.admin.CourseService; import com.ouc.onlinexam.service.admin.ICourseService; import com.ouc.onlinexam.service.admin.IScheduleService; import com.ouc.onlinexam.service.admin.IStuClassService; import com.ouc.onlinexam.service.admin.ITeacherService; import com.ouc.onlinexam.service.admin.ScheduleService; import com.ouc.onlinexam.service.admin.StuClassService; import com.ouc.onlinexam.service.admin.TeacherService; @WebServlet("/scheduleModifyServlet") public class ScheduleModifyServlet extends HttpServlet{ private ICourseService cs = new CourseService(); private ITeacherService ts = new TeacherService(); private IStuClassService scs = new StuClassService(); private IScheduleService ss = new ScheduleService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub //接受要修改的id号 int tcId = Integer.valueOf(req.getParameter("info")); TeacherCourse tc= ss.findTeacherCourseById(tcId); List csList = cs.findCourses(null); List tsList = ts.findTeachers(null); List scsList = scs.findAll(null); //把要修改的id号再送到页面上s req.setAttribute("teaCourId", tcId); req.setAttribute("courList", csList); req.setAttribute("teaList", tsList); req.setAttribute("stuclList", scsList); req.setAttribute("tc", tc); req.getRequestDispatcher("manager/schedulemodify.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub int tcId = Integer.valueOf(req.getParameter("teaCourId")); //建一个类接受页面上的各项id TeacherCourse ptc = new TeacherCourse(); ptc.setId(tcId); ptc.setTeaId(Integer.valueOf(req.getParameter("teacher"))); ptc.setCourseId(Integer.valueOf(req.getParameter("course"))); ptc.setClassId(Integer.valueOf(req.getParameter("stuclass"))); ss.updateTeacherCourseById(ptc); resp.sendRedirect("scheduleQueryServlet"); } } <file_sep>package com.ouc.onlinexam.dao.admin; import java.util.List; import com.ouc.onlinexam.po.TeacherCourse; import com.ouc.onlinexam.vo.TeacherCourseView; public interface IScheduleDao { /** * 返回一个集合,集合里的每个元素都是TeahcerCourseView类型 * * @return */ public List<TeacherCourseView> findAll(String name); /** * 添加TeacherCourse对象 * 这个对象描述了班级教师课程时间的关系 * @return */ public void addSchedule(TeacherCourse tc); public TeacherCourse findTeacherCourseById(int id); public void updateTCById(TeacherCourse tc); public void deleteSchedule(int id); } <file_sep>package com.ouc.onlinexam.servlet.student; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ouc.onlinexam.po.Student; import com.ouc.onlinexam.service.student.IPaperService; import com.ouc.onlinexam.service.student.PaperService; @WebServlet("/pastTestServlet") public class PastTestServlet extends HttpServlet{ IPaperService ps = new PaperService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub Student s = (Student) req.getSession().getAttribute("user"); String name = req.getParameter("courseSearch"); List paperList = new ArrayList(); paperList = ps.findPapersByInfo(s.getId(), name); req.setAttribute("paperList", paperList); req.getRequestDispatcher("/student/history.jsp").forward(req, resp); } }
0c6e3b7dc5d861a240284c697ea024da874209eb
[ "Markdown", "Java" ]
24
Java
PYGang/Driving-School-Test-System
db60521cb7f6e717dce1919893920ce8bca356cd
66a6262f23f46d0cee7597f964b6a85f5c7c08cc
refs/heads/master
<repo_name>bazhenov/linear-counter<file_sep>/tests/stream_summary.cpp #include <gtest/gtest.h> #include "stream_summary.hpp" using namespace std; TEST(StreamSummary, shouldReturnCountersCount) { StreamSummary summary; summary.offer("first"); summary.offer("second"); ASSERT_EQ(2, summary.getCountersCount()); } TEST(StreamSummary, shouldBeAbleToTrackCounts) { StreamSummary summary; string s = "example string"; for (int i=0; i<5; i++) summary.offer(s); ASSERT_EQ(5, summary.estimateCount(s)); } TEST(StreamSummary, shouldBeAbleToReturnValuesInFrequencyDecreasingOrder) { StreamSummary s; s.offer("first"); s.offer("first"); s.offer("second"); s.offer("second"); s.offer("first"); auto top = s.top(); EXPECT_EQ(2, top.size()); EXPECT_EQ("first", top[0].first); EXPECT_EQ(3, top[0].second); EXPECT_EQ("second", top[1].first); EXPECT_EQ(2, top[1].second); } TEST(StreamSummary, frequency) { StreamSummary s; s.offer("first"); EXPECT_EQ(s.estimateCount("first"), 1); s.offer("first"); EXPECT_EQ(s.estimateCount("first"), 2); } <file_sep>/tests/all-tests.cpp #include <gtest/gtest.h> TEST(SquareRootTest2, PositiveNos) { ASSERT_EQ(6, 3 * 2); } <file_sep>/README.md # Linear counter Simlple CLI utility for making efficient estimate of nunber of unique strings in the given stream. Algorithm doesn't need to store and sort all of the given entries and has space complexity of O(1) and time complexity of O(N) which is way faster than using ` | sort | uniq | wc -l`. ## Installation On the macos: ``` $ brew tap bazhenov/tap $ brew install linear-counter ``` ## Using ``` $ cat "very_large_file" | linear-counter ``` <file_sep>/CMakeLists.txt cmake_minimum_required (VERSION 2.6) project (linear-counter) set (Tutorial_VERSION_MAJOR 0) set (Tutorial_VERSION_MINOR 1) set (CMAKE_CXX_STANDARD 11) set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) set(PROJECT_SOURCE_DIR "./src") configure_file ( "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in" "${PROJECT_BINARY_DIR}/TutorialConfig.h" ) #include_directories("${PROJECT_BINARY_DIR}") add_subdirectory(src/stream-summary) include_directories("${PROJECT_SOURCE_DIR}/stream-summary") add_subdirectory(tests) add_executable (linear-counter "${PROJECT_SOURCE_DIR}/main.cpp" "${PROJECT_SOURCE_DIR}/md5.cpp") target_link_libraries(linear-counter boost_program_options) install (TARGETS linear-counter DESTINATION bin) <file_sep>/src/main.cpp #include <iostream> #include <cmath> #include <boost/program_options.hpp> #include "md5.hpp" using namespace std; using namespace md5; namespace po = boost::program_options; uint32 do_hash(const char* text, size_t length) { md5_context md5; uint8 digest[16]; uint32* result = (uint32*)digest; md5_starts(&md5); md5_update(&md5, (uint8 *)text, length); md5_finish(&md5, digest); return *result; }; int populationCount(int x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0F0F0F0F; x = x + (x >> 8); x = x + (x >> 16); return x & 0x0000003F; } class LinearCounter { private: char* vector; size_t size; public: LinearCounter(int sz) : size(sz) { vector = (char*)malloc(size); memset(vector, 0, size); } ~LinearCounter() { free(vector); } void offer(const char* text, size_t textSize) { uint32 h = do_hash(text, textSize) % ((int)size * 8); uint32 byte = h / 8; uint32 bit = h % 8; vector[byte] |= 1 << bit; } int usedBits() { int* p = (int*)vector; int* last = (int*)(vector + size); int result = 0; while(p < last) { result += populationCount(*(p++)); } return result; } size_t unusedBits() { return length() - usedBits(); } double usedBitsProportion() { return (double)usedBits() / length(); } long cardinalityEstimate() { size_t unused_bits = unusedBits(); if (unused_bits == 0) { return -1; } else { return length() * log((double)length() / unusedBits()); } } size_t length() { return size * 8; } }; int main(int argc, char** argv) { po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("size", po::value<int>()->default_value(125000), "the size of the linear counter in bytes") ("buffer", po::value<int>()->default_value(1024), "the size of the line buffer in bytes"); po::variables_map vm; po::basic_parsed_options<char> opts = po::command_line_parser(argc, argv).options(desc).allow_unregistered().run(); po::store(opts, vm); if (vm.count("help")) { cout << desc << endl; return 1; } int size = vm["size"].as<int>(); string line; LinearCounter a(size); int buffer_size = vm["size"].as<int>(); char buffer[buffer_size]; while (fgets(buffer, buffer_size, stdin)) { a.offer(buffer, strlen(buffer)); } long est = a.cardinalityEstimate(); if (est < 0) { cerr << "Estimate could not be given. Try greater mask (--size)" << endl; return 255; } else { cout << est << endl; return 0; } }<file_sep>/src/stream-summary/stream_summary.hpp #include <string> #include <vector> #include <map> #include <list> class Bucket; class Counter { private: unsigned int _count; const std::list<Bucket> _buckets; public: Counter(unsigned int count) : _count(count), _buckets({}) {} unsigned int getCount(); }; class Bucket { private: std::string _value; unsigned int _count; unsigned int _error; const std::shared_ptr<Counter> _counter; public: Bucket(const std::string& value, const std::shared_ptr<Counter> counter) : _value(value), _counter(counter) {} void increment(); unsigned int value(); }; typedef std::map<std::string, Bucket> ValueMap; class StreamSummary { private: int _countersNo; ValueMap _counter_map; public: StreamSummary(int countersNo) : _countersNo(countersNo) {} StreamSummary() : StreamSummary(500) {} void offer(const std::string& s); std::vector<Bucket> getTop(); int estimateCount(const std::string& s); /** * Возвращает отсортированный по убыванию частоты список позиций */ std::vector<std::pair<std::string, unsigned int>> top(); /** * Возвращает количество отслеживаемых позиций в потоке */ int getCountersCount(); }; <file_sep>/src/stream-summary/CMakeLists.txt file(GLOB sources "*.cpp") add_library(StreamSummary ${sources}) <file_sep>/tests/CMakeLists.txt file(GLOB cases "*.cpp") add_subdirectory(googletest) include_directories("googletest/googletest/include") add_executable(tests ${cases}) target_link_libraries(tests StreamSummary gtest) SET(GCC_COMPILER_FLAGS "-g -O0") SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_COMPILER_FLAGS}" ) <file_sep>/src/stream-summary/stream_summary.cpp #include "stream_summary.hpp" #include <iostream> using namespace std; void Bucket::increment() { _count++; } unsigned int Bucket::value() { return _counter->getCount(); } unsigned int Counter::getCount() { return _count; } void StreamSummary::offer(const string& s) { auto v = _counter_map.find(s); if ( v == _counter_map.end() ) { // new element shared_ptr<Counter> shared = make_shared<Counter>(1); _counter_map.insert(make_pair(s, Bucket(s, shared))); } else { // existing element v->second.increment(); auto& bucket = v->second; } } int StreamSummary::getCountersCount() { return _counter_map.size(); } vector<Bucket> StreamSummary::getTop() { } int StreamSummary::estimateCount(const std::string& s) { auto v = _counter_map.find(s); if ( v == _counter_map.end() ) { return -1; } return v->second.value(); } vector<pair<string, unsigned int>> StreamSummary::top() { auto it = _counter_map.begin(); vector<pair<string, unsigned int>> result; for (; it != _counter_map.end(); it++) { result.push_back(make_pair(it->first, it->second.value())); } return result; }
1f7bc0d0388b2a729e1c1d9c9246fe069ab05d64
[ "Markdown", "CMake", "C++" ]
9
C++
bazhenov/linear-counter
6c5a486cbb9e46865a38d23c29ab6d432ac483e7
cbd96836828251ccc2084dac87059d5afc81ff59
refs/heads/master
<repo_name>adityasingh1995/TheWiki<file_sep>/myorm.py from google.appengine.ext import db from string import letters import random import hashlib ##### page stuff def page_key(name): parent_name = name+'_parent' return db.Key.from_path('pageparent', parent_name) class Page(db.Model): name = db.StringProperty(required = True) content = db.TextProperty() lastmod = db.DateTimeProperty(auto_now_add = True) @classmethod def by_id(cls, name, pid): p = Page.get_by_id(pid, parent = page_key(name)) return p @classmethod def list_all_name(cls, name): new = list() p = cls.all().ancestor(page_key(name)).order('-lastmod') for a in p.run(): new.append(a) return new @classmethod def by_name(cls, name): p = cls.all().ancestor(page_key(name)).order('-lastmod').get() return p @classmethod def newpage(cls, name, content): p = cls(parent = page_key(name), name = name, content=content) return p ##### user stuff def make_salt(length = 5): return ''.join(random.choice(letters) for x in xrange(length)) def make_pw_hash(name, pw, salt = None): if not salt: salt = make_salt() h = hashlib.sha256(name + pw + salt).hexdigest() return '%s,%s' % (salt, h) def valid_pw(name, password, h): salt = h.split(',')[0] return h == make_pw_hash(name, password, salt) def users_key(group = 'default'): return db.Key.from_path('users', group) class User(db.Model): name = db.StringProperty(required = True) pw_hash = db.StringProperty(required = True) email = db.StringProperty() @classmethod def by_id(cls, uid): return User.get_by_id(uid, parent = users_key()) @classmethod def by_name(cls, name): u = User.all().filter('name =', name).get() return u @classmethod def register(cls, name, pw, email = None): pw_hash = make_pw_hash(name, pw) return User(parent = users_key(), name = name, pw_hash = pw_hash, email = email) @classmethod def login(cls, name, pw): u = cls.by_name(name) if u and valid_pw(name, pw, u.pw_hash): return u <file_sep>/myutils.py import os import re import hashlib import jinja2 import hmac template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),autoescape = True) secret = 'sexy' def fix_name(name): if name != '/': return name[1:] else: return name def unfix_name(name): if name == '/': return "" else: return name def render_str(template, **params): t = jinja_env.get_template(template) return t.render(params) def make_secure_val(val): return '%s|%s' % (val, hmac.new(secret, val).hexdigest()) def check_secure_val(secure_val): val = secure_val.split('|')[0] if secure_val == make_secure_val(val): return val USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$") MAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$") PASS_RE = re.compile(r"^.{3,20}$") def valid_username(username): return USER_RE.match(username) and username def valid_password(password): return PASS_RE.match(password) and password def valid_email(email): return not email or MAIL_RE.match(email) <file_sep>/wiki.py import webapp2 import os import re from myorm import * from myutils import * import logging import time class WikiHandler(webapp2.RequestHandler): def write(self, *a, **kw): self.response.out.write(*a, **kw) def render_str(self, template, **params): params['user'] = self.user return render_str(template, **params) def render(self, template, **kw): self.write(self.render_str(template, **kw)) def set_secure_cookie(self, name, val): cookie_val = make_secure_val(val) self.response.headers.add_header( 'Set-Cookie', '%s=%s; Path=/' % (name, cookie_val)) def read_secure_cookie(self, name): cookie_val = self.request.cookies.get(name) return cookie_val and check_secure_val(cookie_val) def login(self, user): self.set_secure_cookie('user_id', str(user.key().id())) def logout(self): self.response.headers.add_header('Set-Cookie', 'user_id=; Path=/') def initialize(self, *a, **kw): webapp2.RequestHandler.initialize(self, *a, **kw) uid = self.read_secure_cookie('user_id') self.user = uid and User.by_id(int(uid)) class Signup(WikiHandler): def get(self): self.render("signup-form.html") def post(self): have_error = False self.username = self.request.get('username') self.password = self.request.get('password') self.verify = self.request.get('verify') self.email = self.request.get('email') params = dict(username = self.username, email = self.email) if not valid_username(self.username): params['error_username'] = "That's not a valid username." have_error = True if not valid_password(self.password): params['error_password'] = "<PASSWORD> valid password." have_error = True elif self.password != self.verify: params['error_verify'] = "Your passwords didn't match." have_error = True if not valid_email(self.email): params['error_email'] = "That's not a valid email." have_error = True if have_error: self.render('signup-form.html', **params) else: u = User.by_name(self.username) if u: msg = 'That user already exists.' self.render('signup-form.html', error_username = msg) else: u = User.register(self.username, self.password, self.email) u.put() self.login(u) self.redirect('/') class Login(WikiHandler): def get(self): self.render('login-form.html') def post(self): username = self.request.get('username') password = <PASSWORD>('<PASSWORD>') u = User.login(username, password) if u: self.login(u) self.redirect('/') else: msg = 'Invalid login' self.render('login-form.html', error = msg) class Logout(WikiHandler): def get(self): self.logout() self.redirect('/') class EditPage(WikiHandler): def get(self, name): if not self.user: logging.error('not logged in, redirecting') self.redirect('/login') else: name = fix_name(name) page_id = self.request.get("page_id") if page_id: p = Page.by_id(name, int(page_id)) else: p = Page.by_name(name) if p: content = p.content else: content = "" self.render('editor.html', name=name, content=content, user = self.user) def post(self, name): name = fix_name(name) if not self.user: self.redirect('/login') content = self.request.get("content") if not name: logging.error('not name, redirecting') self.redirect('/') else: if not content: self.render('editor.html', name= name, user = self.user, error = "please add content") else: p = Page.newpage(name, content) p.put() name = unfix_name(name) time.sleep(0.5) self.redirect('/%s' % name) #class MainPage(WikiHandler): # def get(self): # if self.user: # self.response.out.write("logged in as %s" % self.user.name) # else: # self.response.out.write("not logged in") class WikiPage(WikiHandler): def get(self, name): page_id = self.request.get("page_id") name = fix_name(name) if page_id: p = Page.by_id(name, int(page_id)) else: p = Page.by_name(name) if p: self.render("wikipage.html", name = unfix_name(p.name), content = p.content, user = self.user, page_id = page_id) else: self.redirect("/_edit/%s" % unfix_name(name)) class HistoryPage(WikiHandler): def get(self, name): name = fix_name(name) plist = Page.list_all_name(name) self.render("history.html", name = unfix_name(name), plist = plist, user = self.user) class Create(WikiHandler): def get(self): name = self.request.get("new") if name: self.redirect("/%s" % name.lower()) else: self.redirect("/") ### url handing PAGE_RE = r'(/(?:[a-zA-Z0-9_-]+/?)*)' app = webapp2.WSGIApplication([('/signup', Signup), ('/login', Login), ('/logout', Logout), ('/create', Create), ('/_edit' + PAGE_RE, EditPage), ('/_history' + PAGE_RE, HistoryPage), (PAGE_RE, WikiPage), ], debug=True)
b9176bdbac3530a46271b4007dfa87b066a0c968
[ "Python" ]
3
Python
adityasingh1995/TheWiki
58e7875ee82bc2b9e652e0191fa61479c94b39c1
af7f56b31c469790b19c941903c9e875fe226397
refs/heads/master
<repo_name>AttilaVM/rpi-exstreamer-control<file_sep>/src/rpi-linux-hiassoft/build.sh #!/bin/bash # Yous should run this script at the kernel source directiory, you will also need a cross tool-chain installed at /opt/pi # Make sparet dir fof deployable files if [ ! -d files ];then mkdir files fi # export path prefix for cross-toolchain export CCPREFIX=/opt/pi/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf- # test arm tatget gcc avaliablity targetArch=$(${CCPREFIX}gcc -dumpmachine) if ! echo "$targetArch" | grep --quiet arm-linux-gnueabihf ;then echo "Incorect or non-existing cross-toolchian" exit fi # Generate .config file if it does not exist if [ ! -f .config ];then make ARCH=arm CROSS_COMPILE="$CCPREFIX" bcm2709_defconfig fi # Clean the binary tree to avoid unlikely but very obscure problems # it extremly increase rebulding time # so it can be commented out while this, script is further developed make clean # Compile kernel ARCH=arm CROSS_COMPILE=${CCPREFIX} make -j8 zImage modules dtbs # Generate trailer b'RPTL' about Device Tree blob (DT) compatibility with mkknlimg script # It is needed becuese DT and ATAGs are mutually exclusive # ATAG parameters are used to pass phisical memory layout to the kernel on ARM arch # However a DT compatible kernel does not understand ATAGs # Therefore passing them causes boot faliure # # A trailer is a sequnce of magic bytes at the end of the kermel img # it does not effect the kernel binary as a executable # However when the bootloader detects it, it will not pass any ATAGs to the kernel # # see: # https://www.raspberrypi.org/documentation/configuration/device-tree.md # http://www.simtec.co.uk/products/SWLINUX/files/booting_article.html # https://github.com/raspberrypi/tools/blob/master/mkimage/mkknlimg#L21 # https://github.com/raspberrypi/tools/blob/master/mkimage/mkknlimg#L123 /opt/pi/mkimage/mkknlimg arch/arm/boot/zImage files/cirrus.img # make modules dir if [ ! -d modules ];then mkdir modules fi # clean modules from prevous build rm modules/* # copy modules to modules directory then compress them ARCH=arm CROSS_COMPILE=${CCPREFIX} INSTALL_MOD_PATH=./modules make modules_install (cd modules && tar czf ../files/modules.tgz lib) <file_sep>/generate-inventory.py import yaml vars = yaml.load((open("vars.yml", 'r')).read()) hosts = vars["hosts"] hostsFile = open("hosts", 'w') inventoryFile = open("inventory", 'w') hostsFileContent = "" inventoryFileContent = "" for groupName, group in hosts.iteritems(): inventoryFileContent += "\n[" + groupName + "]\n" for hostName, host in group.iteritems(): hostsFileContent += host["ip"] + "\t\t" + hostName + "\n" inventoryFileContent += hostName + " " for varName, var in host.iteritems(): inventoryFileContent += varName + "=" + str(var) + " " inventoryFileContent += "\n" hostsFile.write(hostsFileContent) inventoryFile.write(inventoryFileContent) hostsFile.close() inventoryFile.close() <file_sep>/readme.md # Exstreamer control # This is the code which we used at Ozora festival to configure and control our Cirrus Logic Audio Card/Raspberry Pi 3 based exstreamers for [radiozora.fm](https://radiozora.fm/) We relied on free and open source technologies, and hopefully the resharing of this code will help others to use them as well. We were a bit hasty so the code is a bit coarse at places, however it worked well in production, and I will refine it a bit in the following months when in my spare time. ## Description ## The Cirrus Logic Audio Card and rpi 3 at this time of writing wont work together with the offical Raspbian images. You must use a patched kernel. Thankfully Matthias "Hias" Reichl made one [this](https://github.com/HiassofT/rpi-linux) for us. He has other nice projects at [http://www.horus.com/~hias/](http://www.horus.com/~hias/), I included the compiled kernel with necessary device tree blobs and overlays and a shell script (src/rpi-linux-hiassoft/build.sh) which I wrote to build the image. It won't work automatically, you need cross tool-chain and such, please check the source for details. However, there is an ansible playbook to deploy the kernel and its components. We used liquidsoap as an excellent icecast2 source client. Sadly, the one that you can install from the Jessie repository is buggy, but we recompiled a well working variant. You can find it at files/apps/liquidsoap, however, there is an Ansible playbook to install it. ## Dependencies ## * python2.7 * ansible-1.9.6 (2.0 and above wont work) * pyyaml ## Usage ## ### Prepare your rpi 3 images ### Ansible uses ssh to remotely control nodes, so you need a sudoer user on your hosts where the local user who runs Ansible can login. So you need to add such a user to the official Raspbian image. Especially if you wish to use RSA or ECC keys (I hope you do...). Then you should set up your exstreammer rpis on your network, with static IPs. ### Write a config file for ansible ### Now you should make a vars.yaml file, which contains all of your variables, including your hosts and their properties. I recommend to use our example file cp vars.yml-example vars.yml Then modify the variables for your needs. The description of the available playbooks can help with that. hints: You can run a playbook with the following command: ansible-playbook -i <inventory file> <playbook name> Ansible needs an inventory file to access hosts, so a generate-inventory.py script is included to generate it. it will use the groups and hosts defined in the hosts dictionary in your vars.yml #### workstations.yml #### These playbooks will deploy a new /etc/hosts file on the machines in the workstations host group containing every other host. It will also generate an emacs tramp proxies file (if you do not need it, delete the part of the code) Variables: The hosts are defined under the hosts' dictionary in groups. ** workstations ** group contains the machines from where the system is controlled, like your machine. ** streamers ** contains your exstreamers. #### exstreamer-kernel-deploy.yml #### At first run it will only expand the rootfs on rpis, then restart them. Warning this will only work if the rootfs is the second partition. So if you used dd to make your cards it will work, but if you used noobs it wont. On later runs, it will deploy your kernel, a modified config.txt into /boot to load the device tree overlays for the sound card. Then the kernel modules, device tree overlays, cirrus sound card control scripts, and a fine working liquidsoap installer .deb files. It will install liquidsoap too, and it will take a lot of time. #### exstreamer-config.yml #### This playbook does many things, perhaps too many... It deploys hosts files and liquidsoap stream scripts, then enable the liquidsoap daemon. For the radioserver it deploys the icecast2 configuration. Finally it sets up dumpers to save the streams. variables: This playbook use many variables from the stream dictionary. #### exstreamer-getinfo #### It will print out temp and disk space infos about the streamers. #### get_secondary_dumps.sh #### Unfortunately Ansible can not fetch multiple files from remote hosts very well, but good ol' bash can do it.
f0c08d3f3a4cefe31a926875aa95a40e82be3875
[ "Markdown", "Python", "Shell" ]
3
Shell
AttilaVM/rpi-exstreamer-control
a277aa6e52e55755c5e806540c19a734e82ae186
eefddb3037593d6afab9008e29e6fee75a8015cf
refs/heads/master
<repo_name>markeu/capstone-frontend<file_sep>/src/store/reducers/feedReducer.js import { updateObject } from '../../utilities'; import { FETCH_FEED_FAIL, FETCH_FEED_SUCCESS, FETCH_FEED_START } from '../actions/actionTypes'; const initialState = { feeds: [], error: null, loading: false, }; const fetchOrderStart = (state, action) => { return updateObject(state, {loading: true}) }; const fetchOrderSuccess = (state, action) => { return updateObject(state, {loading: false, feeds: action.feeds }) }; const fetchOrderFail = (state, action) => { return updateObject(state, {loading: false}) }; const reducer = (state = initialState, action) => { switch(action.type) { case FETCH_FEED_START: return fetchOrderStart(state, action); case FETCH_FEED_SUCCESS: return fetchOrderSuccess(state, action); case FETCH_FEED_FAIL: return fetchOrderFail(state, action); default:return state } }; export default reducer;<file_sep>/src/containers/dashboard/index.js import React, { useState, useEffect } from 'react'; import { connect } from 'react-redux'; import Grid from '@material-ui/core/Grid'; import { fetchFeeds } from '../../store/actions'; import Feeds from '../../components/Feeds'; import Spinners from '../../components/UI/Spinners/Spinners' const Dashboard = props => { const [data, setData] = useState([]); useEffect(() => { props.onFetchFeeds() }); let recentFeedMarkup = props.feeds ? ( props.feeds.map((feed) => <Feeds feed={feed}/>) ) : ( <Spinners /> ) return ( <Grid container spacing={16}> <Grid item sm={8} xs={12}> {recentFeedMarkup} </Grid> <Grid item sm={4} xs={12}> <p>profile.....</p> </Grid> </Grid> ) } const mapStateToProps = state => { return { feeds: state.feeds.feeds, loading: state.feeds.loading }; }; const mapDispatchToProps = dispatch => { return { onFetchFeeds: () => dispatch(fetchFeeds()) } } export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);<file_sep>/src/store/actions/actionTypes.js export const ADD_USER = 'ADD_USER'; export const GET_USERS = 'GET_USERS'; export const USER_ERROR = 'USER_ERROR'; export const USERS_LOADING = 'GET_USERS_LOADING'; export const CLEAR_USERS_ERROR = 'CLEAR_USERS_ERROR'; export const SET_CURRENT_USER = 'SET_CURRENT_USER'; export const AUTH_LOADING = 'AUTH_LOADING'; export const AUTH_ERROR = 'AUTH_ERROR'; export const CLEAR_AUTH_ERROR = 'CLEAR_AUTH_ERROR'; export const GET_ARTICLE = 'GET_ARTICLE'; export const FETCH_FEED_START = 'FETCH_FEED_START'; export const FETCH_FEED_SUCCESS = 'FETCH_FEED_SUCCESS'; export const FETCH_FEED_FAIL = 'FETCH_FEED_FAIL'; <file_sep>/src/App.js import React from 'react'; import { MuiThemeProvider } from '@material-ui/core/styles'; import { createMuiTheme } from '@material-ui/core/styles'; import { BrowserRouter as Router, Route, Switch} from 'react-router-dom'; // import PrivateRoute from './'; import Signin from './containers/login/login'; import NavBar from './components/navBar/navBar'; import Dashboard from './containers/Dashboard'; import './App.css'; const theme = createMuiTheme({ palette: { primary: { light: '#98ee99', main: '#66bb6a', dark: '#338a3e', contrastText: '#000' }, secondary: { light: '#f05545', main: '#b71c1c', dark: '#7f0000', contrastText: '#fff' }, }, typography: { useNextVariants: true } }); const App = () => { return ( <MuiThemeProvider theme={theme}> <div className="App"> <Router> <NavBar /> <div className="container"> <Switch> <Route exact path="/" component={Dashboard} /> {/* <Route exact path="/signin" component={Signin} /> */} {/* <Route exact path="/signup" component={Signup} /> */} </Switch> </div> </Router> </div> </MuiThemeProvider> ); } export default App; <file_sep>/src/utilities/index.js /* eslint-disable consistent-return */ export const makeUrl = (path) => { const base = process.env.BASE_URL; const uri = `${base}${path}`; return uri; }; export const request = async (url, method, data = null, token = null) => { const reqObject = { method, headers: { 'Content-Type': 'application/json', authorization: `Bearer ${token}`, }, }; if (method === 'POST' || method === 'PATCH' || method === 'PUT') { reqObject.body = data ? JSON.stringify(data) : ''; } try { const response = await fetch(url, reqObject); const resData = await response.json(); return { ...resData, statusCode: response.status }; } catch (error) { return error.message; } }; export const capitalize = (word) => { const capital = word.charAt(0).toUpperCase() + word.slice(1); return capital; }; export const updateObject = (oldObject, updateProperties) => { return { ...oldObject, ...updateProperties } }<file_sep>/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware, compose, combineReducers } from 'redux'; import thunk from 'redux-thunk'; import App from './App'; import feedReducer from './store/reducers/feedReducer'; import authReducer from './store/reducers/authReducer'; import userReducer from './store/reducers/usersReducer'; const rootReducer = combineReducers({ feeds: feedReducer, auth: authReducer, users: userReducer, }) const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore(rootReducer, composeEnhancers( applyMiddleware(thunk) )); const app = ( <Provider store={store}> <BrowserRouter> <App /> </BrowserRouter> </Provider> ); ReactDOM.render(app, document.getElementById('root'));
6586cf3de17801bc1095d1aae95c8aa0972f4590
[ "JavaScript" ]
6
JavaScript
markeu/capstone-frontend
400c7c90f4c22e414ceeade392d50eed6291808b
1ea1ffa948639c7d020a1efc0542693e0e74183e
refs/heads/master
<file_sep>package com.frame.model.activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.dhh.rxlifecycle2.RxLifecycle; import com.dhh.websocket.Config; import com.dhh.websocket.RxWebSocket; import com.dhh.websocket.WebSocketInfo; import com.dhh.websocket.WebSocketSubscriber; import com.frame.model.R; import com.frame.model.adapter.ChatAdapter; import com.frame.model.base.BaseActivity; import com.frame.model.base.URLRoot; import com.frame.model.bean.MessageBean; import com.frame.model.bean.MessageResponseBean; import com.frame.model.network.Chats; import com.frame.model.utils.util.LogUtils; import com.frame.model.utils.util.StringUtils; import com.frame.model.utils.util.ToastUtils; import com.google.gson.Gson; import net.sf.json.JSONObject; import butterknife.BindView; import butterknife.OnClick; import io.reactivex.annotations.NonNull; import okhttp3.WebSocket; /** * desc: 聊天页面 * Author:MrZ * CreateDate:2018/6/21 * UpdateDate:2018/6/21 * github:https://github.com/hz38957153 */ public class ChatActivity extends BaseActivity { @BindView(R.id.editText) EditText editText; @BindView(R.id.btn_send) Button btnSend; @BindView(R.id.recycler_list) RecyclerView recyclerList; ChatAdapter adapter; int i = 0; @Override protected int getLayoutId() { return R.layout.activity_chat; } @Override protected void afterCreate(Bundle savedInstanceState) { //initView(); initData(); } @Override protected void initView() { //init config Config config = new Config.Builder() .setShowLog(true) //show log // .setClient(yourClient) //if you want to set your okhttpClient // .setShowLog(true, "your logTag") // .setReconnectInterval(2, TimeUnit.SECONDS) //set reconnect interval // .setSSLSocketFactory(yourSSlSocketFactory, yourX509TrustManager) // wss support .build(); RxWebSocket.setConfig(config); /** * *如果你想将String类型的text解析成具体的实体类,比如, * 请使用 {@link WebSocketSubscriber},仅需要将泛型传入即可 */ RxWebSocket.get(URLRoot.BASE_STOCK) .compose(RxLifecycle.with(this).<WebSocketInfo>bindToLifecycle()) .subscribe(new WebSocketSubscriber() { @Override protected void onOpen(WebSocket webSocket) { super.onOpen(webSocket); LogUtils.a("ChatActivity",true); MessageBean messageBean = new MessageBean(); MessageBean.RequestBean requestBean = new MessageBean.RequestBean(); requestBean.setGroup("1"); requestBean.setUser_id("2022"); messageBean.setType("join"); messageBean.setRequest(requestBean); Gson gson =new Gson(); String message = gson.toJson(messageBean); RxWebSocket.send(URLRoot.BASE_STOCK,message); } /*@Override protected void onMessage(MessageResponseBean responseBean) { LogUtils.a("ChatActivity", responseBean.toString()); if (responseBean.getType().contains("ping")){ RxWebSocket.send(URLRoot.BASE_STOCK,JSONObject.fromObject("{'type':'pong'}").toString()); LogUtils.a("pong"); } if (!responseBean.getType().contains("4097")){ if (responseBean != null){ if (responseBean.getResponse() != null){ adapter.addData(StringUtils.isEmptyResuleString(responseBean.getResponse().getMessage())); LogUtils.a("收到消息"); } } recyclerList.scrollToPosition(adapter.getData().size()-1); } }*/ @Override protected void onMessage(@NonNull String text) { LogUtils.a("ChatActivity", text); if (text.contains("ping")){ //RxWebSocket.send(URLRoot.BASE_STOCK,JSONObject.fromObject("{'type':'pong'}").toString()); LogUtils.a("pong"); } if (!text.contains("4097")){ Gson gson = new Gson(); MessageResponseBean bean = gson.fromJson(text,MessageResponseBean.class); if (bean != null){ if (bean.getResponse() != null){ adapter.addData(StringUtils.isEmptyResuleString(bean.getResponse().getMessage())); LogUtils.a("收到消息"); } } recyclerList.scrollToPosition(adapter.getData().size()-1); } } @Override protected void onReconnect() { super.onReconnect(); LogUtils.a("ChatActivity", "重连"); } }); adapter = new ChatAdapter(R.layout.list_item); recyclerList.setLayoutManager(new LinearLayoutManager(mContext)); recyclerList.setHasFixedSize(false); recyclerList.setAdapter(adapter); } @Override protected void initData() { Chats.joinChat("asd",this); Chats.msgListener(new Chats.ChatListener() { @Override public void onOpen(WebSocket webSocket) { LogUtils.a("ChatActivity",true); } @Override public void onNewMessage(MessageResponseBean responseBean) { adapter.addData(StringUtils.isEmptyResuleString(responseBean.getResponse().getMessage())); LogUtils.a("收到消息"); } @Override public void onReconnect() { LogUtils.a("重连"); } @Override public void onClose() { LogUtils.a("关闭"); } }); adapter = new ChatAdapter(R.layout.list_item); recyclerList.setLayoutManager(new LinearLayoutManager(mContext)); recyclerList.setHasFixedSize(false); recyclerList.setAdapter(adapter); } @Override protected void onDestroy() { super.onDestroy(); /*//注销 Disposable disposable = RxWebSocket.get("ws://sdfs").subscribe(); if (disposable != null && !disposable.isDisposed()) { disposable.dispose(); }*/ //Chats.logout(); } @OnClick({ R.id.btn_send, R.id.recycler_list}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.btn_send: if (StringUtils.isEmpty(editText.getText().toString().trim())){ ToastUtils.showShort("请输入内容"); return; } Chats.send(editText.getText().toString().trim()); break; } } } <file_sep>package com.frame.model.network; import android.provider.Settings; import android.util.Log; import com.frame.model.base.BaseActivity; import com.frame.model.base.Constants; import com.frame.model.utils.util.AppUtils; import com.frame.model.utils.util.ToastUtils; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import okhttp3.FormBody; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; /** * Created by MrZ on 2018/1/24. 16:30 * project delin * Explain 头信息拦截器 */ public class HeadInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { //这个chain里面包含了request和response,所以你要什么都可以从这里拿 Request request = chain.request(); long t1 = System.nanoTime();//请求发起的时间 String method = request.method(); if ("POST".equals(method)) { StringBuilder sb = new StringBuilder(); if (request.body() instanceof FormBody) { FormBody body = (FormBody) request.body(); for (int i = 0; i < body.size(); i++) { sb.append(body.name(i) + "=" + body.value(i) + ","); } sb.delete(sb.length() - 1, sb.length()); Log.i("NET_RELATIVE", String.format("发送请求 %s on %s %n%s %nRequestParams:{%s}", request.url(), chain.connection(), request.headers(), sb.toString())); } } else { Log.i("NET_RELATIVE",String.format("发送请求 %s on %s%n%s", request.url(), chain.connection(), request.headers())); } //重新请求 Response response = chain.proceed(initHead(null,chain)); isTokenExpired(response,chain); long t2 = System.nanoTime();//收到响应的时间 //这里不能直接使用response.body().string()的方式输出日志 //因为response.body().string()之后,response中的流会被关闭,程序会报错,我们需要创建出一 //个新的response给应用层处理 ResponseBody responseBody = response.peekBody(1024 * 1024); Log.i("NET_RELATIVE", String.format("接收响应: [%s] %n返回json:【%s】 %.1fms %n%s", response.request().url(), responseBody.string(), (t2 - t1) / 1e6d, response.headers() )); return response; } /** * @author MrZ * @time 2018/6/12 * @uptime 2018/6/12 * @describe 初始化头信息 */ public Request initHead(File file, Chain chain) { Request.Builder mBuilder = chain.request().newBuilder(); Map<String, String> map = new HashMap<String, String>(); // HeaderUtil.setHeader(map);//ydc 移植注释 if (file != null) { //String mSize = MD5Util.MD5(file.length() + ""); String mSize ="10"; //SharedUtil.setFileSize(mSize);//andy.fang 文件大小MD5保存头信息,方便后台校验 map.put("filesize", mSize);//上传下载文件的MD5值 不需要每个地方都加,在需要的地方加 } Set keys = map.keySet(); if (keys != null) { Iterator iterator = keys.iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); String value = (String) map.get(key); /*if(StrUtil.isNotBlank(key)&& StrUtil.isNotBlank(value)){ mBuilder.addHeader(key, value); }*/ } } //系统级请求参数 mBuilder.header("userToken", "token");// 移植注释 mBuilder.header("version", AppUtils.getAppVersionCode()+""); mBuilder.header("appID",1+""); mBuilder.header("androidId", Settings.System.getString(BaseActivity.mContext.getContentResolver(), Settings.System.ANDROID_ID)); // mBuilder.addHeader("format", "JSON"); // mBuilder.addHeader("appKey", "00001"); Request mRequest = mBuilder.build(); return mRequest; } private void isTokenExpired(Response response, Chain chain) { if (response.code() == 401) { } else if (response.code() == 402) { Constants.loginClearData(false); ToastUtils.showShort("登陆失效,请重新登陆"); } else if(response.code() == 500){ ToastUtils.showShort("服务器内部错误"); } else if(response.code() == 502){ ToastUtils.showShort("服务器内部错误"); } } } <file_sep>package com.frame.model.network; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; import okhttp3.FormBody; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; /** * Created by MrZ on 2018/2/24. 18:19 * project delin * Explain url追加sign拦截器 */ public class SignInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); String url = request.url().toString(); String newUrl = "" ; FormBody newBody = new FormBody.Builder().build(); Request newRequest; if (url.contains("login")&& !url.contains("setDeleteUser")){ if (request.method().equals("POST")){ newBody = setPostUrlSecret(url,request); newRequest = chain.request() .newBuilder() .method(request.method(),newBody) .build(); } else{ newUrl = url + "&sign=" + setGetUrlSecret(url); newRequest = chain.request() .newBuilder() .url(HttpUrl.parse(newUrl)) .build(); } return chain.proceed(newRequest); } else{ return chain.proceed(request); } } /** * @param * @author MrZ * @time 2018/2/26 11:09 * @notes get请求参数拼接 */ private String setGetUrlSecret(String url){ if (!url.contains("?")){ return ""; } String s = url.substring(url.indexOf("?")+1); String ss [] = s.split("&"); SortedMap<String,String> map = new TreeMap<>(); List<String> key = new ArrayList<>(); List<String> value = new ArrayList<>(); for (int i = 0; i < ss.length ; i++) { String sa [] = ss[i].split("="); for (int j = 0; j < sa.length ; j++) { if (j%2 == 0) key.add(sa[j]); else value.add(sa[j]); } } for (int i = 0; i < key.size() ; i++) { String v; if (value.size() != 0){ if (i > value.size()-1) v = ""; else v = value.get(i); } else{ v = ""; } map.put(key.get(i),v); } //return Constants.createSign(map); return "sign"; } /** * @param * @author MrZ * @time 2018/2/26 11:10 * @notes post请求参数拼接 */ private FormBody setPostUrlSecret(String url,Request request){ StringBuilder sb = new StringBuilder(); SortedMap<String ,String > map = new TreeMap<>(); FormBody.Builder bodys = new FormBody.Builder(); if (request.body() instanceof FormBody) { FormBody body = (FormBody) request.body(); for (int i = 0; i < body.size(); i++) { map.put(body.encodedName(i),body.encodedValue(i)); } for (int i = 0; i < body.size()+1; i++) { if (i == body.size()){ //bodys.add("sign",Constants.createSign(map)); bodys.add("sign","sign"); } else{ bodys.add(body.encodedName(i),body.encodedValue(i)); } } } return bodys.build(); } } <file_sep>package com.frame.model.base.mvp; import com.frame.model.base.Feed; import java.util.List; import java.util.Map; import io.reactivex.Flowable; /** * Created by MrZ on 2017/10/11. 15:04 * project delin * Explain 数据仓库中心 */ public class DataRepository implements IDataSource { private static DataRepository INSTANCE = null; private IDataSource mRemoteDataSource;//远程数据源 private IDataSource mLocalDataSource;//本地数据源 Map<String, Feed> mCaches; boolean mCacheIsDirty = false;//緩存是否有效,默认无效 // private DataRepository(IDataSource remoteDataSource,IDataSource localDataSource){ // mRemoteDataSource = remoteDataSource;//远程数据源 // mLocalDataSource = localDataSource;//本地数据源 // } /** * @description 单例数据仓库(引入Dar) * @author ydc * @createDate * @version 1.0 */ public synchronized static DataRepository getInstance(){ if (INSTANCE == null) { INSTANCE = new DataRepository(); } return INSTANCE; } /** * @description 单例数据仓库(引入Dar) * @author ydc * @createDate * @version 1.0 */ // public static DataRepository getInstance(IDataSource remoteDataSource,IDataSource localDataSource) { // if(INSTANCE == null){ // INSTANCE = new DataRepository(remoteDataSource,localDataSource); // } // return INSTANCE; // } /** * @description 清理数据仓库 * @author ydc * @createDate * @version 1.0 */ public static void destroyInstance(){ INSTANCE = null; } @Override public Flowable<List<Feed>> getFeeds() { return null; } @Override public Flowable<Feed> getFeed(Feed feed) { return null; } @Override public void onInvalidData() { } @Override public void saveData(String id) { } @Override public void delData(String id) { } @Override public void delAllData() { } @Override public void refreshData() { } } <file_sep>package com.frame.model.bean; /** * desc: * Author:MrZ * CreateDate:2018/6/21 * UpdateDate:2018/6/21 * github:https://github.com/hz38957153 */ public class MessageResponseBean { /** * type : send_message * response : {"message":"djdjdjfjfj","name":"Mr.Z","head_img":"/public/upload/2018-04-11/20221523428772.jpg","user_id":"2022"} */ private String type; private ResponseBean response; public String getType() { return type; } public void setType(String type) { this.type = type; } public ResponseBean getResponse() { return response; } public void setResponse(ResponseBean response) { this.response = response; } public static class ResponseBean { /** * message : djdjdjfjfj * name : Mr.Z * head_img : /public/upload/2018-04-11/20221523428772.jpg * user_id : 2022 */ private String message; private String name; private String head_img; private String user_id; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getHead_img() { return head_img; } public void setHead_img(String head_img) { this.head_img = head_img; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } } } <file_sep>package com.frame.model.base; import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import com.frame.model.R; import com.frame.model.widget.NetworkStateView; import butterknife.ButterKnife; import butterknife.Unbinder; /** * desc: * Author:MrZ * CreateDate:2018/6/12 * UpdateDate:2018/6/12 * github:https://github.com/hz38957153 */ public abstract class BaseActivity extends AppCompatActivity implements NetworkStateView.OnRefreshListener{ public static Context mContext; private NetworkStateView networkStateView; private Unbinder unbinder; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutId()); unbinder = ButterKnife.bind(this); mContext = getApplicationContext(); afterCreate(savedInstanceState); } @SuppressLint("InflateParams") @Override public void setContentView(@LayoutRes int layoutResID) { View view = getLayoutInflater().inflate(R.layout.activity_base, null); //设置填充activity_base布局 super.setContentView(view); if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { view.setFitsSystemWindows(true); } //加载子类Activity的布局 initDefaultView(layoutResID); } /** * 初始化默认布局的View * @param layoutResId 子View的布局id */ private void initDefaultView(int layoutResId) { networkStateView = (NetworkStateView) findViewById(R.id.nsv_state_view); FrameLayout container = (FrameLayout) findViewById(R.id.fl_activity_child_container); View childView = LayoutInflater.from(this).inflate(layoutResId, null); container.addView(childView, 0); } protected abstract int getLayoutId(); protected abstract void afterCreate(Bundle savedInstanceState); protected abstract void initView(); protected abstract void initData(); /** * 显示加载中的布局 */ public void showLoadingView() { networkStateView.showLoading(); } /** * 显示加载完成后的布局(即子类Activity的布局) */ public void showContentView() { networkStateView.showSuccess(); } /** * 显示没有网络的布局 */ public void showNoNetworkView() { networkStateView.showNoNetwork(); networkStateView.setOnRefreshListener(this); } /** * 显示没有数据的布局 */ public void showEmptyView() { networkStateView.showEmpty(); networkStateView.setOnRefreshListener(this); } /** * 显示数据错误,网络错误等布局 */ public void showErrorView() { networkStateView.showError(); networkStateView.setOnRefreshListener(this); } @Override public void onRefresh() { onNetworkViewRefresh(); } /** * 重新请求网络 */ public void onNetworkViewRefresh() { } @Override protected void onDestroy() { super.onDestroy(); unbinder.unbind(); } } <file_sep>apply plugin: 'com.android.application' android { compileSdkVersion 27 buildToolsVersion "27.0.3" defaultConfig { applicationId "com.frame.model" minSdkVersion 21 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" flavorDimensions "versionCode" multiDexEnabled true } //设置签名,debug运行也用正式签名 ,release 跳过v2验证 signingConfigs { debug { //storeFile file('E:/delin.jks') //storePassword "xxx" //keyAlias "key" //keyPassword "xxx" } release { v1SigningEnabled false v2SigningEnabled true } } productFlavors { productDebug { buildConfigField 'String', 'HOST', '"debug"' minSdkVersion 21 applicationId 'com.frame.model' targetSdkVersion 27 testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner' versionCode 1 versionName '1.0' } productRelease { buildConfigField 'String', 'HOST', '"release"' minSdkVersion 21 applicationId 'com.frame.model' targetSdkVersion 27 testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner' versionCode 1 versionName '1.0' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') /*androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' })*/ compile 'com.android.support:appcompat-v7:27.1.1' testCompile 'junit:junit:4.12' compile 'com.android.support.constraint:constraint-layout:1.0.2' compile 'com.android.support:design:27.1.1' compile 'org.jetbrains:annotations-java5:15.0' //okhttp引用 compile 'com.squareup.okhttp3:okhttp:3.9.0' //retrofit2引用 compile 'com.squareup.retrofit2:retrofit:2.3.0' compile 'com.squareup.retrofit2:converter-gson:2.3.0' compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' //RXJava引用 compile 'io.reactivex.rxjava2:rxjava:2.1.3' compile 'io.reactivex.rxjava2:rxandroid:2.0.1' //RXBinding引用 compile 'com.jakewharton.rxbinding2:rxbinding:2.0.0' //glide引用 compile 'com.github.bumptech.glide:glide:4.0.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.1.1' compile 'com.github.bumptech.glide:okhttp3-integration:4.0.0' compile 'jp.wasabeef:glide-transformations:2.0.0' //butterknife注解引用 compile 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' compile files('libs/json-lib-2.4-jdk15.jar') //刷新 compile 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.0-alpha-7' //调试 compile 'com.facebook.stetho:stetho:1.5.0' //图片 implementation project(':photoview') //lottie compile 'com.airbnb.android:lottie:2.5.4' //socket implementation 'com.dhh:websocket2:2.1.2' compile 'com.dhh:rxlifecycle2:1.5' //BaseRecyclerViewAdapterHelper compile 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.40' } <file_sep>package com.frame.model.utils.util; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; /** * Created by MrZ on 2017/11/15. 10:12 * project delin * Explain 获取资源工具类 */ public class GetResources { /** * @author MrZ * @time 2017/11/15 10:14 * @notes 获取颜色 */ public static int getColor(int color){ return ContextCompat.getColor(Utils.getApp(),color); } /** * @author MrZ * @time 2017/11/15 10:21 * @notes 获取drawable资源 */ public static Drawable getDrawable(int drawable){ return ContextCompat.getDrawable(Utils.getApp(),drawable); } } <file_sep>package com.frame.model.activity; import android.os.Bundle; import com.frame.model.R; import com.frame.model.base.BaseActivity; /** * desc: * Author:MrZ * CreateDate:2018/6/20 * UpdateDate:2018/6/20 * github:https://github.com/hz38957153 */ public class CardViewActivity extends BaseActivity { @Override protected int getLayoutId() { return R.layout.activity_cardview; } @Override protected void afterCreate(Bundle savedInstanceState) { } @Override protected void initView() { } @Override protected void initData() { } } <file_sep>package com.frame.model.base; /** * desc: * Author:MrZ * CreateDate:2018/6/12 * UpdateDate:2018/6/12 * github:https://github.com/hz38957153 */ public final class URLRoot { public static final String BASE_API = ""; public static final String BASE_STOCK="ws://192.168.10.12:8282"; } <file_sep>package com.frame.model.base.mvp; /** * Created by MrZ on 2017/12/22. 14:15 * project delin * Explain */ public class BaseView extends BasePresenter implements Iview { @Override public void showLoading() { } @Override public void showLoading(String msg) { } @Override public void showLoading(String msg, int progress) { } @Override public void hideLoading() { } @Override public void showMsg(String msg) { } @Override public void showErrorMsg(String msg, String content) { } @Override public void close() { } @Override public boolean isActive() { return isViewAttached(); } @Override public void noNetWork() { } @Override public void attachView(Iview view) { } @Override public void subscribe() { } } <file_sep>package com.frame.model.app; import android.app.Application; import android.content.Context; import com.facebook.stetho.Stetho; import com.frame.model.R; import com.frame.model.utils.util.Utils; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator; import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator; import com.scwang.smartrefresh.layout.api.RefreshFooter; import com.scwang.smartrefresh.layout.api.RefreshHeader; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.footer.ClassicsFooter; import com.scwang.smartrefresh.layout.header.ClassicsHeader; /** * desc:项目主application * Author:MrZ * CrateDate:2018/6/12 * UpdateDate:2018/6/12 * github:https://github.com/hz38957153 */ public class MainApplication extends Application { @Override public void onCreate() { super.onCreate(); initSmartRefresh(); Stetho.initializeWithDefaults(this); //初始化 Stetho Utils.init(this); //初始化utils工具 } /** * @author MrZ * @time 2018/6/13 10:27 * @uptime 2018/6/13 10:27 * @describe 全局刷新样式初始化 */ private void initSmartRefresh() { //设置全局的Header构建器 SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() { @Override public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) { layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色 return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header,默认是 贝塞尔雷达Header } }); //设置全局的Footer构建器 SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() { @Override public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) { //指定为经典Footer,默认是 BallPulseFooter return new ClassicsFooter(context).setDrawableSize(20); } }); } } <file_sep>package com.frame.model.network; import android.os.Environment; import com.frame.model.base.URLRoot; import java.io.File; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by MrZ on 2017/10/11. 10:42 * project delin * Explain RX&Retrofit */ public enum RxService { RETROFIT; private Retrofit mRetrofit; private static final int READ_TIMEOUT = 60;//读取超时时间,单位秒 private static final int CONN_TIMEOUT = 50;//连接超时时间,单位秒 /** * @author MrZ * @time 2018/6/12 * @uptime 2018/6/12 * @describe */ public Retrofit createRetrofit() { File httpCacheDirectory = new File(Environment.getExternalStorageDirectory(), "HttpCache");//这里为了方便直接把文件放在了SD卡根目录的HttpCache中,一般放在context.getCacheDir()中 int cacheSize = 10 * 1024 * 1024;//设置缓存文件大小为10M Cache cache = new Cache(httpCacheDirectory, cacheSize); if(mRetrofit == null){ OkHttpClient client = new OkHttpClient.Builder()//初始化一个client,不然retrofit会自己默认添加一个 .addInterceptor(new SignInterceptor()) .addInterceptor(new HeadInterceptor()) .addInterceptor(new TokenInterceptor()) // .addNetworkInterceptor(new REWRITE_CACHE_CONTROL_INTERCEPTOR()) .connectTimeout(CONN_TIMEOUT, TimeUnit.MINUTES)//设置连接时间为50s .readTimeout(READ_TIMEOUT, TimeUnit.MINUTES)//设置读取时间为一分钟 //.cache(cache) .build(); mRetrofit = new Retrofit.Builder() .client(client) .baseUrl(URLRoot.BASE_API) .addConverterFactory(GsonConverterFactory.create())//返回值为Gson的支持(以实体类返回) .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//返回值为Oservable<T>的支持 .build(); } return mRetrofit; } /** * @author MrZ * @time 2018/6/12 * @uptime 2018/6/12 * @describe */ public <T> T createService(final Class<T> service) { validateServiceInterface(service); return (T) RxService.RETROFIT.createRetrofit().create(service); } /** * @author MrZ * @time 2018/6/12 18:25 * @uptime 2018/6/12 18:25 * @describe */ public <T> void validateServiceInterface(Class<T> service) { if (service == null) { //Toast.ShowToast("服务接口不能为空!"); } if (!service.isInterface()) { throw new IllegalArgumentException("API declarations must be interfaces."); } if (service.getInterfaces().length > 0) { throw new IllegalArgumentException("API interfaces must not extend other interfaces."); } } } <file_sep>package com.frame.model.base; /** * desc: * Author:MrZ * CreateDate:2018/6/22 * UpdateDate:2018/6/22 * github:https://github.com/hz38957153 */ public class BaseData { private static BaseData instance = null; /** * 私有默认构造子 */ private BaseData(){} /** * 静态工厂方法 */ public static synchronized BaseData getInstance(){ if(instance == null){ instance = new BaseData(); } return instance; } private int Uid; private String UName; private String UIcon; public int getUid() { return 2022; } public void setUid(int uid) { Uid = 2022; } public String getUName() { return UName; } public void setUName(String UName) { this.UName = UName; } public String getUIcon() { return UIcon; } public void setUIcon(String UIcon) { this.UIcon = UIcon; } }
9fde4dcbc50da3d8fe841777d05acebfb263b25e
[ "Java", "Gradle" ]
14
Java
umqmrz/FrameWorkModel
27e6e42f23bcb5152b56f576fc6233516373c775
1741099ee1040c5a908ba82cf63c6e12e1371821
refs/heads/master
<file_sep> titanic_analysis <- read.csv("D:/GitHub-2/Dataset/titanic.csv", header = TRUE, sep = ",") View(titanic_analysis) table(titanic_analysis$Survived) table(titanic_analysis$Sex) survived <- table(titanic_analysis$Survived, titanic_analysis$Sex) survived barplot(survived, col = rainbow(2), beside = T, legend=T, main="Graph of people who Survived \n \t And Not-survived in Titanic Disaster", xlab = "Gender", ylab = "Number of Death") tt <- table(titanic_analysis$Pclass, titanic_analysis$Survived) barplot(tt, col=rainbow(3), beside = T, legend = T) male_age <- titanic_analysis$Age[titanic_analysis$Sex == 'male'] female_age <- titanic_analysis$Age[titanic_analysis$Sex == 'female'] hist(male_age, xlab = 'Age', main="Age Group of Male Titanic Passenger") hist(female_age, xlab = "Age", main = "Age Group of FeMale Titanic Passenger") summary(male_age) summary(female_age)
67d147ae05ecd09eb3ea9cf9d62872b39a4d7ad4
[ "R" ]
1
R
mahendra-16/R-Assignment-1
89535ebaefd684b2379ed368a088bf497a75cf38
0c776a6f7716be28e47ec4de19b0fee012f5e9f6
refs/heads/master
<file_sep>function GestationalAgeWeeks() { var MILLISECONDS_IN_DAYS = new Number(86400000); var us_EDD = '${Working estimated delivery date}'; var us_date = '${Date of ultrasound}'; var estimateDeliv = new Date(Date.parse(us_EDD.replace(/-/g, '/'))); var ultrasoundDate = new Date(Date.parse(us_date.replace(/-/g, '/'))); var t2 = estimateDeliv.getTime(); var t1 = ultrasoundDate.getTime(); var gestationAgeWeeks = Math.floor((280 - (t2-t1)/(MILLISECONDS_IN_DAYS)) / 7); return gestationAgeWeeks; } function GestationalAgeDays() { var MILLISECONDS_IN_DAYS = new Number(86400000); var us_EDD = '${Working estimated delivery date}'; var us_date = '${Date of ultrasound}'; var estimateDeliv = new Date(Date.parse(us_EDD.replace(/-/g, '/'))); var ultrasoundDate = new Date(Date.parse(us_date.replace(/-/g, '/'))); var t2 = estimateDeliv.getTime(); var t1 = ultrasoundDate.getTime(); var gestationAgeWeeks = Math.floor((280 - (t2-t1)/(MILLISECONDS_IN_DAYS)) / 7); var gestationaAgeDays = gestationAgeWeeks * 7; return gestationaAgeDays; } function dayOfLife() { var MILLISECONDS_IN_DAYS = new Number(86400000); var us_EDD = '${Neonate birthdate}'; var us_date = '${Date of ultrasound}'; var estimateDeliv = new Date(Date.parse(us_EDD.replace(/-/g, '/'))); var ultrasoundDate = new Date(Date.parse(us_date.replace(/-/g, '/'))); var t2 = estimateDeliv.getTime(); var t1 = ultrasoundDate.getTime(); var dayOfLife = Math.floor((t2-t1)/(MILLISECONDS_IN_DAYS)); return dayOfLife; }
c98253cfb2e96dc1ffa36c0b2c084ba1cc8f3d9c
[ "JavaScript" ]
1
JavaScript
AquaSun/NetBeansProjects
e9c87847d34d19c0b691ba4a86b623135463098f
76109e62d4b9a16592f794a3fcacc0905cab8644
refs/heads/master
<repo_name>danielHarris8/danielHarris8.github.io<file_sep>/js/story.js const area = document.querySelectorAll("section"); //const by = document.querySelector("body"); const observer = new IntersectionObserver( entries => { entries.forEach(entry => { if (!entry.isIntersecting) { return; }else{ entry.target.querySelector(".image").style.opacity = 1; entry.target.querySelector(".content").style.opacity = 1; entry.target.querySelector(".image").classList.add("animate__bounceInLeft"); entry.target.querySelector(".content").classList.add("animate__bounceInRight"); observer.unobserve(entry.target); } }); }, { threshold: 0.5 }); area.forEach((el, i) => { observer.observe(el); }); // btnScrollToTop // const btnScrollToTop = document.querySelector("#btnScrollToTop"); btnScrollToTop.addEventListener("click", () =>{ //window.scrollTo(0,0) window.scrollTo({ top:0, left:0, behavior: "smooth" }) })
c14363aa70821fe423813aef0a35847098a04ee8
[ "JavaScript" ]
1
JavaScript
danielHarris8/danielHarris8.github.io
a8a6a2623296a38042230ebc93e049a65d8a8c7c
04c9061c79df18c9f52836a64684b3deb6e5495c
refs/heads/master
<repo_name>mtgill/LetterLoops<file_sep>/LetterLoops/Program.cs using System; using System.Collections.Generic; namespace LetterLoops { class Program { static void Main(string[] args) { List<string> letterList = new List<string>(); Console.WriteLine("Please enter a group of letters"); var inputLetters = Console.ReadLine(); List<string> singleLetterList = new List<string>(); for (var i = 0; i < inputLetters.Length; i++) { singleLetterList.Add(inputLetters[i].ToString()); int numCount = i + 1; string singleLetter = inputLetters[i].ToString().ToLower(); for (var k = 0; k < numCount; k++) { Console.Write((k == 0 ? singleLetter.ToUpper() : singleLetter)); } Console.Write("-"); } } } }
cd4a9d7a077921a8db847baf5d8b372fe780b52a
[ "C#" ]
1
C#
mtgill/LetterLoops
689859eae25fbcbf7c516c530bd6b005af580d95
27bbd7b98c4ecdc2e22dd73e4412000028c903b0
refs/heads/master
<repo_name>avulachandrashekar/notebookApp<file_sep>/src/components/Grid.js import React, {Component} from 'react'; import Single from './Single' class Grid extends Component { displayItems(){ return this.props.notes.map((note) => <Single key={note.Id} note={note} deleteNote={this.props.deleteNote} /> ) } render(){ return( <div className="row"> {this.displayItems()} </div> ) } } export default Grid; <file_sep>/src/components/Form.js import React, {Component} from 'react'; class Form extends Component { constructor(props){ super(props); this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event){ this.props.handleChange(event); } handleSubmit(event){ this.props.handleSubmit(event); } render(){ return( <div className="row"> <form className="col s12" onSubmit={this.handleSubmit}> <div className="row"> <div className="input-field col s3"> <label> Title: </label> <input type="text" className="validate" name="notesTitle" value={this.props.notesTitle} onChange={this.handleChange} /> </div> <div className="input-field col s6"> <label>Notes Details:</label> <input type="text" className="validate" name="notesDetails" value={this.props.notesDetails} onChange={this.handleChange}/> </div> <div className="input-field col s3"> <button className="btn waves-effect waves-light" type="submit" name="action">Add Note</button> </div> </div> </form> </div> ) } } export default Form; <file_sep>/src/App.js import React, { Component } from 'react'; import './App.css'; import Header from './components/Header'; import Grid from './components/Grid'; import Form from './components/Form'; import firebase from 'firebase'; import _ from 'lodash'; import moment from 'moment'; class App extends Component { constructor(props){ super(props); this.state = { notes : [], name :'Chandra', startDate : moment(), notesTitle: '', notesDetails: '' } } handleSubmit(event){ event.preventDefault(); if(this.state.notesTitle === undefined || this.state.notesTitle === ''){ alert("Cannot Save. Title is Empty") }else{ // alert("Your note " + this.state.notesTitle + " has been added"); const data = { Title: this.state.notesTitle, Details: this.state.notesDetails }; firebase.database().ref('/notes').push( data , response => response) this.setState({ notesTitle : '', notesDetails : '' }) } } handleChange(event){ let name = event.target.name; let value = event.target.value; this.setState({ [name] : value }) } componentWillMount(){ firebase.initializeApp({ apiKey: "<KEY>", authDomain: "notepad-d56d7.firebaseapp.com", databaseURL: "https://notepad-d56d7.firebaseio.com", projectId: "notepad-d56d7", storageBucket: "notepad-d56d7.appspot.com", messagingSenderId: "646273750064" }) firebase.database().ref('/notes') .on('value', snapshot => { let fbStore = snapshot.val(); let notesfromDB = _.map(fbStore, (value, key) => { return { Id: key, Title: value.Title, Details: value.Details } }); this.setState({ notes : notesfromDB }) }) } deleteNote(id){ firebase.database().ref(`/notes/${id}`) .remove() alert(`Successfully deleted ${id}`) } onDateChange(event){ alert("Date Changed"); } render() { return ( <div className="App"> <Header user = {this.state.name} /> <Form notesTitle = {this.state.notesTitle} notesDetails = {this.state.notesDetails} handleChange={(event) => this.handleChange(event)} handleSubmit={(event) => this.handleSubmit(event)} /> <Grid notes={this.state.notes} deleteNote={this.deleteNote}/> </div> ); } } export default App; <file_sep>/src/components/Single.js import React from 'react'; const Single = (props) => { return( <div className="col s4"> <div className="card teal lighten-2"> <div className="card-content white-text"> <span className="card-title">{props.note.Title}</span> <p>{props.note.Details}</p> </div> <div className="card-action"> <a className="waves-effect waves-teal btn-flat" onClick={() => props.deleteNote(props.note.Id)}> Delete</a> </div> </div> </div> ) } export default Single;<file_sep>/src/components/Header.js import React from 'react'; const Header = (props) => { return( <div className="navbar-fixed"> <nav> <div className="nav-wrapper teal lighten-2" > <a href="#!" className="brand-logo center">{props.user}'s NotePad</a> </div> </nav> </div> ) } export default Header; <file_sep>/src/components/DatePickerComponent.js import React from 'react'; import DatePicker from 'react-datepicker'; export const DatePickerComponent = (props) => { return ( <DatePicker selected={props.startDate} onChange={props.onDateChange}/> ) }
061bdbb6907a64a9b0adf49cdcf39a72faf56364
[ "JavaScript" ]
6
JavaScript
avulachandrashekar/notebookApp
09fe7684552ab8d23cbe0797e8db8c55c0e535a9
3679ca74077546327d00555bb7fbc0b5fdf7f821
refs/heads/master
<repo_name>LuigiAndMario/Clouds<file_sep>/src/CMakeLists.txt cmake_minimum_required(VERSION 2.8) PROJECT(clouds) find_package(VTK REQUIRED) include(${VTK_USE_FILE}) add_executable(clouds clouds.cpp vtkEasyTransfer.hpp) target_link_libraries(clouds ${VTK_LIBRARIES}) <file_sep>/README.md # Clouds visualisation ## To compile * Open cmake-gui * Select the path to `clouds.cpp` for the source code * Select the path to the parent folder of `clouds.cpp`, and add `/build` for the binaries * Press configure * cmake-gui will crash because it hasn't found the path to VTK - enter the path to VTK in the correct field * Press configure again * Press generate * Press open project <file_sep>/src/vtkEasyTransfer.hpp #ifndef INCLUDE_ONCE_VTK_EASY_TRANSFER #define INCLUDE_ONCE_VTK_EASY_TRANSFER #include <vtkObject.h> #include <vtkSmartPointer.h> #include <vtkObjectFactory.h> #include <vtkColorTransferFunction.h> #include <vtkPiecewiseFunction.h> #include <vtkImageMapper.h> #include <vtkImageCanvasSource2D.h> #include <vtkActor2D.h> #include <vtkImageData.h> #include <vtkInteractorStyleTrackballCamera.h> #include <vtkInteractorStyle.h> #include <algorithm> class vtkEasyTransferInteractorStyle; // Very simplistic transfer function editor for VTK. class vtkEasyTransfer : public vtkObject { public: friend class vtkEasyTransferInteractorStyle; static vtkEasyTransfer* New(); // Constructor. vtkEasyTransfer(); // Sets a default color map. void SetColormapHeat() { mColorTransferFunction->RemoveAllPoints(); mOpacityTransferFunction->RemoveAllPoints(); int numPoints = 256; double minValue = 0, maxValue = 255; for (int i = 0; i < numPoints; ++i) { double t = i / (double)(numPoints - 1); double x = minValue + t * (maxValue - minValue); double r = std::min(std::max(0.0, ((-1.0411*t + 0.4149)*t + 0.0162)*t + 0.9949), 1.0); double g = std::min(std::max(0.0, ((1.7442*t + -2.7388)*t + 0.1454)*t + 0.9971), 1.0); double b = std::min(std::max(0.0, ((0.9397*t + -0.2565)*t + -1.5570)*t + 0.9161), 1.0); mColorTransferFunction->AddRGBPoint(x, r, g, b); mOpacityTransferFunction->AddPoint(x, t); } RefreshImage(); } // Sets a default color map. void SetColormapBlue2Red() { mColorTransferFunction->RemoveAllPoints(); mOpacityTransferFunction->RemoveAllPoints(); int numPoints = 256; double minValue = 0, maxValue = 255; for (int i = 0; i < numPoints; ++i) { double t = i / (double)(numPoints - 1); double x = minValue + t * (maxValue - minValue); double r = std::min(std::max(0.0, (((5.0048*t + -8.0915)*t + 1.1657)*t + 1.4380)*t + 0.6639), 1.0); double g = std::min(std::max(0.0, (((7.4158*t + -15.9415)*t + 7.4696)*t + 1.2767)*t + -0.0013), 1.0); double b = std::min(std::max(0.0, (((6.1246*t + -16.2287)*t + 11.9910)*t + -1.4886)*t + 0.1685), 1.0); mColorTransferFunction->AddRGBPoint(x, r, g, b); mOpacityTransferFunction->AddPoint(x, t); } RefreshImage(); } // Sets the color map range void SetColorRange(double minValue, double maxValue) { double range[2] = { mColorTransferFunction->GetRange()[0], mColorTransferFunction->GetRange()[1] }; double* dataPtr = mColorTransferFunction->GetDataPointer(); int size = mColorTransferFunction->GetSize(); std::vector<double> data(dataPtr, dataPtr + (4 * size)); mColorTransferFunction->RemoveAllPoints(); for (int i = 0; i < size; ++i) { double told = (data[i * 4] - range[0]) / (range[1] - range[0]); double tnew = told * (maxValue - minValue) + minValue; mColorTransferFunction->AddRGBPoint(tnew, data[i * 4 + 1], data[i * 4 + 2], data[i * 4 + 3]); } } // Sets the opacity map range void SetOpacityRange(double minValue, double maxValue) { double range[2] = { mOpacityTransferFunction->GetRange()[0], mOpacityTransferFunction->GetRange()[1] }; double* dataPtr = mOpacityTransferFunction->GetDataPointer(); int size = mOpacityTransferFunction->GetSize(); std::vector<double> data(dataPtr, dataPtr + (2 * size)); mOpacityTransferFunction->RemoveAllPoints(); for (int i = 0; i < size; ++i) { double told = (data[i * 2] - range[0]) / (range[1] - range[0]); double tnew = told * (maxValue - minValue) + minValue; mOpacityTransferFunction->AddPoint(tnew, data[i * 2 + 1]); } } // Gets the color transfer function. vtkSmartPointer<vtkColorTransferFunction> GetColorTransferFunction() { return mColorTransferFunction; } // Gets the opacity transfer function. vtkSmartPointer<vtkPiecewiseFunction> GetOpacityTransferFunction() { return mOpacityTransferFunction; } // Gets the renderer. vtkSmartPointer<vtkRenderer> GetRenderer() { return mRenderer; } // Gets the interactor for user interactions. vtkSmartPointer<vtkInteractorStyle> GetInteractorStyle() { return mInteractorStyle; } // Recomputes the color map images. Call this function, whenever the viewport has changed! (only updates the viewport bounds, if this is already assigned to a vtkRenderWindow) void RefreshImage() { if (mRenderer->GetRenderWindow()) { int* size = mRenderer->GetRenderWindow()->GetSize(); double* viewport = mRenderer->GetViewport(); mCanvasWidth = size[0] * (viewport[2] - viewport[0]); mCanvasHeight = size[1] * (viewport[3] - viewport[1]) / 4; mDrawing->SetExtent(0, size[0] * (viewport[2] - viewport[0]) - 1, 0, size[1] * (viewport[3] - viewport[1]) - 1, 0, 1); } mDrawing->SetDrawColor(1, 1, 1); mDrawing->FillBox(0, mCanvasWidth, 0, 4 * mCanvasHeight); // draw color maps { double range[2] = { mColorTransferFunction->GetRange()[0], mColorTransferFunction->GetRange()[1] }; double* dataPtr = mColorTransferFunction->GetDataPointer(); int size = mColorTransferFunction->GetSize(); std::vector<double> data(dataPtr, dataPtr + (4 * size)); for (int i = 0; i < size; ++i) { int lower = (data[4 * i] - range[0]) / (range[1] - range[0]) * (mCanvasWidth - 1); int upper = i == size - 1 ? mCanvasWidth : ((data[4 * i + 4] - range[0]) / (range[1] - range[0]) * (mCanvasWidth - 1)); int valueR = data[4 * i + 1] * mCanvasHeight; int valueG = data[4 * i + 2] * mCanvasHeight; int valueB = data[4 * i + 3] * mCanvasHeight; mDrawing->SetDrawColor(1.0, 0.1, 0.1); mDrawing->FillBox(lower, upper, 3 * mCanvasHeight, 3 * mCanvasHeight + valueR); mDrawing->SetDrawColor(0.1, 1.0, 0.1); mDrawing->FillBox(lower, upper, 2 * mCanvasHeight, 2 * mCanvasHeight + valueG); mDrawing->SetDrawColor(0.1, 0.1, 1.0); mDrawing->FillBox(lower, upper, 1 * mCanvasHeight, 1 * mCanvasHeight + valueB); } } // draw opacity map { double range[2] = { mOpacityTransferFunction->GetRange()[0], mOpacityTransferFunction->GetRange()[1] }; double* dataPtr = mOpacityTransferFunction->GetDataPointer(); int size = mOpacityTransferFunction->GetSize(); std::vector<double> data(dataPtr, dataPtr + (2 * size)); for (int i = 0; i < size; ++i) { int lower = (data[2 * i] - range[0]) / (range[1] - range[0]) * (mCanvasWidth - 1); int upper = i == size - 1 ? mCanvasWidth : ((data[2 * i + 2] - range[0]) / (range[1] - range[0]) * (mCanvasWidth - 1)); int valueO = data[2 * i + 1] * mCanvasHeight; mDrawing->SetDrawColor(0.3, 0.3, 0.3); mDrawing->FillBox(lower, upper, 0 * mCanvasHeight, 0 * mCanvasHeight + valueO); } } } private: vtkEasyTransfer(const vtkEasyTransfer&); // Not implemented. void operator=(const vtkEasyTransfer&); // Not implemented. vtkSmartPointer<vtkColorTransferFunction> mColorTransferFunction; vtkSmartPointer<vtkPiecewiseFunction> mOpacityTransferFunction; vtkSmartPointer<vtkRenderer> mRenderer; vtkSmartPointer<vtkImageCanvasSource2D> mDrawing; vtkSmartPointer<vtkEasyTransferInteractorStyle> mInteractorStyle; int mCanvasWidth; int mCanvasHeight; }; vtkStandardNewMacro(vtkEasyTransfer); // Interactor style class vtkEasyTransferInteractorStyle : public vtkInteractorStyleTrackballCamera { public: static vtkEasyTransferInteractorStyle* New(); vtkEasyTransferInteractorStyle() : mEasyTransfer(NULL), mMouseDown(false), mLastX(-1), mLastPlot(-1) {} void SetEasyTransfer(vtkEasyTransfer* easyTransfer) { mEasyTransfer = easyTransfer; } virtual void OnLeftButtonDown() override { int* clickPos = this->GetInteractor()->GetEventPosition(); mMouseDown = true; int* size = mEasyTransfer->mRenderer->GetRenderWindow()->GetSize(); double windowRelative[2] = { clickPos[0] / (double)size[0], clickPos[1] / (double)size[1] }; double* viewport = mEasyTransfer->mRenderer->GetViewport(); double viewportRelative[2] = { (windowRelative[0] - viewport[0]) / (viewport[2] - viewport[0]), (windowRelative[1] - viewport[1]) / (viewport[3] - viewport[1]) }; if (0 <= viewportRelative[0] && viewportRelative[0] <= 1 && 0 <= viewportRelative[1] && viewportRelative[1] <= 1) { int x = viewportRelative[0] * mEasyTransfer->mCanvasWidth; mLastX = -1; int yfull = viewportRelative[1] * (mEasyTransfer->mCanvasHeight * 4); int plot = yfull / mEasyTransfer->mCanvasHeight; mLastPlot = plot; processPixel(clickPos); } else mLastPlot = -1; vtkInteractorStyleTrackballCamera::OnLeftButtonDown(); } virtual void OnLeftButtonUp() override { mMouseDown = false; vtkInteractorStyleTrackballCamera::OnLeftButtonUp(); } virtual void OnMouseMove() override { if (mMouseDown) { int* clickPos = this->GetInteractor()->GetEventPosition(); processPixel(clickPos); } vtkInteractorStyleTrackballCamera::OnMouseMove(); } private: bool mMouseDown; int mLastX; int mLastPlot; void processPixel(int* clickPos) { int* size = mEasyTransfer->mRenderer->GetRenderWindow()->GetSize(); double windowRelative[2] = { clickPos[0] / (double)size[0], clickPos[1] / (double)size[1] }; double* viewport = mEasyTransfer->mRenderer->GetViewport(); double viewportRelative[2] = { (windowRelative[0] - viewport[0]) / (viewport[2] - viewport[0]), (windowRelative[1] - viewport[1]) / (viewport[3] - viewport[1]) }; if (0 <= viewportRelative[0] && viewportRelative[0] <= 1 && 0 <= viewportRelative[1] && viewportRelative[1] <= 1) { int x = viewportRelative[0] * mEasyTransfer->mCanvasWidth; int yfull = viewportRelative[1] * (mEasyTransfer->mCanvasHeight * 4); int plot = yfull / mEasyTransfer->mCanvasHeight; if (mLastPlot != plot) return; int y = yfull % mEasyTransfer->mCanvasHeight; // color plots: 3=R, 2=G, 1=B if (plot >= 1) { double range[2] = { mEasyTransfer->mColorTransferFunction->GetRange()[0], mEasyTransfer->mColorTransferFunction->GetRange()[1] }; double* dataPtr = mEasyTransfer->mColorTransferFunction->GetDataPointer(); int size = mEasyTransfer->mColorTransferFunction->GetSize(); std::vector<double> data(dataPtr, dataPtr + (4 * size)); double T = viewportRelative[0] * (range[1] - range[0]) + range[0]; int L = 0, R = size; while (L < R) { int m = (int)((L + R) / 2); if (data[4 * m] < T) L = m + 1; else R = m; } L = std::max(L - 1, 0); data[4 * L + 4 - plot] = y / (double)mEasyTransfer->mCanvasHeight; if (mLastX == -1) mLastX = L; for (int index = mLastX; index <= L + 1; ++index) mEasyTransfer->mColorTransferFunction->AddRGBPoint(data[4 * index], data[4 * (plot == 3 ? L : index) + 1], data[4 * (plot == 2 ? L : index) + 2], data[4 * (plot == 1 ? L : index) + 3]); for (int index = L; index <= mLastX + 1; ++index) mEasyTransfer->mColorTransferFunction->AddRGBPoint(data[4 * index], data[4 * (plot == 3 ? L : index) + 1], data[4 * (plot == 2 ? L : index) + 2], data[4 * (plot == 1 ? L : index) + 3]); mLastX = L; mEasyTransfer->RefreshImage(); } // opacity plot: 0 else { double range[2] = { mEasyTransfer->mOpacityTransferFunction->GetRange()[0], mEasyTransfer->mOpacityTransferFunction->GetRange()[1] }; double* dataPtr = mEasyTransfer->mOpacityTransferFunction->GetDataPointer(); int size = mEasyTransfer->mOpacityTransferFunction->GetSize(); std::vector<double> data(dataPtr, dataPtr + (2 * size)); double T = viewportRelative[0] * (range[1] - range[0]) + range[0]; int L = 0, R = size; while (L < R) { int m = (int)((L + R) / 2); if (data[2 * m] < T) L = m + 1; else R = m; } L = std::max(L - 1, 0); data[2 * L + 1] = y / (double)mEasyTransfer->mCanvasHeight; if (mLastX == -1) mLastX = L; for (int index = mLastX; index <= L + 1; ++index) mEasyTransfer->mOpacityTransferFunction->AddPoint(data[2 * index], data[2 * L + 1]); for (int index = L; index <= mLastX + 1; ++index) mEasyTransfer->mOpacityTransferFunction->AddPoint(data[2 * index], data[2 * L + 1]); mLastX = L; mEasyTransfer->RefreshImage(); } } } vtkEasyTransfer* mEasyTransfer; }; vtkStandardNewMacro(vtkEasyTransferInteractorStyle); vtkEasyTransfer::vtkEasyTransfer() : mCanvasWidth(256), mCanvasHeight(100) { mColorTransferFunction = vtkSmartPointer<vtkColorTransferFunction>::New(); mOpacityTransferFunction = vtkSmartPointer<vtkPiecewiseFunction>::New(); mRenderer = vtkSmartPointer<vtkRenderer>::New(); mRenderer->ResetCamera(); mDrawing = vtkSmartPointer<vtkImageCanvasSource2D>::New(); mDrawing->SetNumberOfScalarComponents(3); mDrawing->SetScalarTypeToUnsignedChar(); mDrawing->SetExtent(0, mCanvasWidth - 1, 0, 4 * mCanvasHeight - 1, 0, 1); vtkSmartPointer<vtkImageMapper> imageMapper = vtkSmartPointer<vtkImageMapper>::New(); imageMapper->SetInputConnection(mDrawing->GetOutputPort()); imageMapper->SetColorWindow(1); imageMapper->SetColorLevel(0); vtkSmartPointer<vtkActor2D> imageActor = vtkSmartPointer<vtkActor2D>::New(); imageActor->SetMapper(imageMapper); mRenderer->AddActor2D(imageActor); mInteractorStyle = vtkSmartPointer<vtkEasyTransferInteractorStyle>::New(); mInteractorStyle->SetEasyTransfer(this); } #endif
ce2674f279e04f7bd48e9e95e63f99bb9c4b9486
[ "Markdown", "CMake", "C++" ]
3
CMake
LuigiAndMario/Clouds
7a15ac20d343cbc3832a6496f39a4177f1b44453
1a2ddfaf7b4426ea955c0697e8c9734d5a5c77e2
refs/heads/master
<file_sep>This is a CLI game that gives a user 5 attempts to guess a number between 1 and 20.<file_sep>the_number = rand(1...20) attempts = 0 guess = 0 puts "Hello! What is your name?" player_name = gets.chomp puts "Nice to meet you, #{player_name}." puts "I am thinking of a number between 1 and 20." puts "You have 5 chances to guess what it is." while attempts < 5 && guess != the_number do puts "Take a guess!" guess = gets.to_i if guess == the_number attempts += 1 puts "You win!" puts "Congratulations, #{player_name}! You guessed it in #{attempts.to_s} tries!" end if guess < 1 || guess > 20 puts "Please enter a number between 1 and 20." end if guess > the_number puts "Your guess is too high." attempts += 1 if attempts < 4 puts "You have #{5 - attempts} attempts left." elsif attempts == 4 puts "You have #{5 - attempts} attempt left." else puts "Sorry, #{player_name}, you've run out of guesses." end end if guess < the_number && guess > 0 puts "Your guess is too low." attempts += 1 if attempts < 4 puts "You have #{5 - attempts} attempts left." elsif attempts == 4 puts "You have #{5 - attempts} attempt left." else puts "Sorry, #{player_name}, you've run out of guesses." end end end puts "The number was #{the_number}." puts "Game Over!"
a38c40f8d9106f54ad3280933524cf8deb18ea21
[ "Markdown", "Ruby" ]
2
Markdown
cmcmcmcm/ruby-guess-the-number
94c2d4e2466181e7ab6bd4db02a1c7347c28d700
2ff74bc2e31714d0a216edc02e42889cc6b4394f
refs/heads/master
<file_sep>Countdown/Countup Timer ==================== A simple timer that counts up until or since a given date. Prerequisites ----------- * [Bower] - A package manager for the web * [Node.js] - Event-driven V8 Javascript runtime Installation ----------- ```sh bower install npm install express ``` Usage ----- ```sh node index.js ``` App is running at localhost:8000/timer. To adjust settings, click the wrench icon in the bottom left-hand corner. To reset the clock, click the red button with your event title. [Bower]:http://bower.io/ [Node.js]:http://nodejs.org <file_sep>var express = require('express'), appPort = 8000, app = express(); // serve static files out of /app directory // available at /timer app.use('/timer', express.static(__dirname + '/app')); app.listen(appPort, function() { console.log('Server listening on port: ' + appPort); }); <file_sep>var tickTock = function() { var datetimepicker = $('#datetimepicker'), MSinDay = 86400000, MSinHour = 3600000, MSinMinute = 60000, MSinSecond = 1000, diff = 0; // reset timer when event button is pressed $('#event').click(function() { datetimepicker.val(moment().format('MM/DD/YYYY h:mm:ss A')); }); diff = moment().diff(datetimepicker.val()); // event is in future if (diff < 0) { $('#since').html('until'); diff = -diff; } // event is in past else { $('#since').html('since'); } // set days, hours, minutes, seconds $('#days').html(Math.floor(diff / MSinDay)); $('#hours').html(Math.floor((diff % MSinDay) / MSinHour)); $('#minutes').html(Math.floor(((diff % MSinDay) % MSinHour) / MSinMinute)); $('#seconds').html(Math.floor((((diff % MSinDay) % MSinHour ) % MSinMinute) / MSinSecond)); // calculate time every 500 ms setTimeout(function() { tickTock(); }, 1000); }; var saveSettings = function() { var defaultDateVal = $('#defaultDate').val(); var eventLabelVal = $('#eventLabel').val(); // if defaultDate isn't empty, fill datetimepicker with value and persist it if (defaultDateVal.length > 0 && localStorageExists) { $('#datetimepicker').val(defaultDateVal); localStorage.setItem('defaultDate', defaultDateVal); } // if eventLabel isn't empty, fill event with value and persist it if (eventLabelVal.length > 0 && localStorageExists) { $('#event').html(eventLabelVal); localStorage.setItem('eventLabel', eventLabelVal); } else { console.log('local storage doesn\'t exist in your browser. Please upgrade at http://browsehappy.com/'); } // hide the modal $('#settingsModal').modal('toggle'); }; $(document).ready(function() { var datetimepicker = $('#datetimepicker'), event = $('#event'), defaultDate = '', eventLabel = ''; // global localStorageExists = false; if (localStorage) { localStorageExists = true; } // respond to click on calendar/time icon $('#dt').datetimepicker(); // respond to click on calendar/time icon for default date $('#default').datetimepicker(); // respond to click on Save button in Settings modal $('#save').on('click', saveSettings); // check for local storage if (localStorageExists) { defaultDate = localStorage.getItem('defaultDate'); eventLabel = localStorage.getItem('eventLabel'); // check for Default Date in local storage if (defaultDate) { datetimepicker.val(defaultDate); } else { datetimepicker.val(moment().format('MM/DD/YYYY h:mm:ss A')); } // check for Event Label in local storage if (eventLabel) { event.html(eventLabel); } else { event.html('Your Event'); } } // just set it to "now" else { datetimepicker.val(moment().format('MM/DD/YYYY h:mm:ss A')); event.html('Your Event'); } // start the timer tickTock(); }); $('#settingsModal').on('shown.bs.modal', function (e) { var defaultDate = '', eventLabel = ''; if (localStorageExists) { defaultDate = localStorage.getItem('defaultDate'); eventLabel = localStorage.getItem('eventLabel'); $('#defaultDate').val(defaultDate); $('#eventLabel').val(eventLabel); } });<file_sep>function init(parameters) { var defaultTitle = 'Your Event', defaultSeconds = moment().unix(), title = parameters.title, seconds = parameters.seconds, doUpdate = false; // don't update URL unnecessarily if (!title || !seconds) { doUpdate = true; } title = title || defaultTitle; seconds = seconds || defaultSeconds; doUpdate && setURL({title: title, seconds: seconds}); setTimeDateDisplay(seconds); setEventTitle(decodeURI(title)); tickTock(); } function setURL(parameters) { var title = encodeURI(parameters.title), seconds = parameters.seconds, firstHalfURL = window.location.href.split('#')[0]; window.location.href = firstHalfURL + '#/' + title + '/' + seconds; } function setTimeDateDisplay(seconds) { var datetimepicker = $('#datetimepicker'), timeDate = moment.unix(seconds).format('MM/DD/YYYY hh:mm:ss A'); datetimepicker.val(timeDate); } function getTimeDateUnix() { return moment($('#datetimepicker').val()).unix(); } function setEventTitle(title) { $('#event').html(title); } function getEventTitle() { return $('#event').html(); } function tickTock() { var datetimepicker = $('#datetimepicker'), MSinDay = 86400000, MSinHour = 3600000, MSinMinute = 60000, MSinSecond = 1000, diff = 0; diff = moment().diff(datetimepicker.val()); // event is in future if (diff < 0) { $('#since').html('until'); diff = -diff; } // event is in past else { $('#since').html('since'); } // set days, hours, minutes, seconds $('#days').html(Math.floor(diff / MSinDay)); $('#hours').html(Math.floor((diff % MSinDay) / MSinHour)); $('#minutes').html(Math.floor(((diff % MSinDay) % MSinHour) / MSinMinute)); $('#seconds').html(Math.floor((((diff % MSinDay) % MSinHour ) % MSinMinute) / MSinSecond)); // calculate time every 500 ms setTimeout(function() { tickTock(); }, 500); } function setupRoutes() { Path.map('#/(:title)(/:seconds)').to(function() { init({title: this.params['title'], seconds: this.params['seconds']}); }); Path.root('#/'); Path.listen(); } function setupListeners() { // respond to click on calendar/time icon $('#dt').datetimepicker({format: 'MM/DD/YYYY hh:mm:ss A'}); $('#dt').on('dp.change', function() { var title = getEventTitle(), seconds = getTimeDateUnix(); setURL({title: title, seconds: seconds}); }); // reset timer when event button is pressed $('#event').on('click', function() { $('#datetimepicker').val(moment(). format('MM/DD/YYYY hh:mm:ss A')). trigger('dp.change'). // trigger dp.change so URL and input box are updated trigger('change'); // trigger change so datetimepicker is updated }); $('.event-dropdown li').on('click', function(evt) { evt.stopPropagation(); }); $('#event-name').change(function(evt) { var currentVal = $(this).val(); if (currentVal && currentVal !== '') { $('#event').html($(this).val()); $('#dt').trigger('dp.change'); } }); $('#info').on('click', function() { $('#myModal').modal(); }); } $(document).ready(function() { setupRoutes(); setupListeners(); });
0f8ddbdb8c39aa383ea611ae191c1457d96703b0
[ "Markdown", "JavaScript" ]
4
Markdown
imjohnbo/countdown-countup-timer
e8d30756b70410137af1860a1c1eff4b034e004d
c47cbc555586319ada903584f1ee49c3ea8cfd43
refs/heads/master
<file_sep>### R code from vignette source 'rspear.Rnw' ### Encoding: UTF-8 ################################################### ### code chunk number 1: rspear.Rnw:42-43 (eval = FALSE) ################################################### ## install.packages('rspear') ################################################### ### code chunk number 2: rspear.Rnw:48-52 (eval = FALSE) ################################################### ## install.packages("devtools") ## require(devtools) ## install_github("rspear", "EDiLD") ## require(rspear) ################################################### ### code chunk number 3: rspear.Rnw:54-55 ################################################### require(rspear) ################################################### ### code chunk number 4: rspear.Rnw:145-147 ################################################### data(spear_example) head(spear_example) ################################################### ### code chunk number 5: rspear.Rnw:165-167 ################################################### require(reshape2) df_wide <- dcast(spear_example, Site + Year ~ Taxon, value.var="Abundance", fill = 0)[ , 1:6] ################################################### ### code chunk number 6: rspear.Rnw:169-170 ################################################### df_wide ################################################### ### code chunk number 7: rspear.Rnw:174-177 ################################################### require(reshape2) df_long <- melt(df_wide, id = c("Site", "Year")) head(df_long) ################################################### ### code chunk number 8: rspear.Rnw:187-189 (eval = FALSE) ################################################### ## sp <- spear(spear_example, ## taxa = "Taxon", abundance = "Abundance", group = c("Year", "Site")) ################################################### ### code chunk number 9: rspear.Rnw:194-199 ################################################### names(spear_example) sp <- spear(spear_example , taxa = names(spear_example)[1], abundance = names(spear_example)[2], group = names(spear_example)[3:4], check = FALSE) ################################################### ### code chunk number 10: rspear.Rnw:222-223 ################################################### head(sp$traits) ################################################### ### code chunk number 11: rspear.Rnw:229-230 ################################################### sp$spear ################################################### ### code chunk number 12: boxplot ################################################### spear_df <- sp$spear plot(SPEAR ~ factor(Year), data = spear_df) ################################################### ### code chunk number 13: rspear.Rnw:247-250 ################################################### traits_modi <- sp$traits traits_modi[traits_modi$taxa_matched %in% "Baetis rhodani", "exposed"] <- c(1,1) head(traits_modi) ################################################### ### code chunk number 14: rspear.Rnw:256-263 ################################################### sp_modi <- spear(spear_example , taxa = names(spear_example)[1], abundance = names(spear_example)[2], group = names(spear_example)[3:4], traits = traits_modi, check = FALSE) head(sp_modi$spear) head(sp_modi$traits) ################################################### ### code chunk number 15: rspear.Rnw:277-278 ################################################### citation("rspear")
fe7ff6e027ee77ccbd4e2c96b9ece1588a040466
[ "R" ]
1
R
cran/rspear
bb586ee84e72bd3507baa3e4079c4ca5d9c767a2
16cf67681282c8089f05378f3d12bdc5fc42be73
refs/heads/master
<file_sep>package org.lff.client.netty; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.handler.codec.http.*; import org.lff.client.callback.DNSCallback; import org.lff.common.messages.RSAEncryptedRequestMessage; import org.lff.common.messages.RSAEncryptedResponseMessage; import org.lff.common.messages.RequestMessage; import org.lff.common.messages.ResponseMessage; import org.lff.rsa.RSACipher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.*; import java.nio.charset.Charset; import java.util.Arrays; /** * User: LFF * Datetime: 2014/12/26 10:22 */ public class NettyDNSClientCallback implements DNSCallback { private static final Logger logger = LoggerFactory.getLogger(NettyDNSClientCallback.class); private final HTTPReader httpReader; public NettyDNSClientCallback(String host, int port) throws URISyntaxException { this.httpReader = new HTTPReader(host, port); } public void callback(RequestMessage message, DatagramSocket socket) { logger.debug("Request Message Hash = " + Arrays.hashCode(message.toByteArray())); RSAEncryptedRequestMessage m = new RSAEncryptedRequestMessage(RSACipher.encrypt(message.toByteArray())); byte[] result = this.httpReader.run(m.getData(), socket); if (result == null) { return; } result = RSACipher.decrypt(result); ResponseMessage response = new ResponseMessage(result); logger.debug("Response Message Hash = " + Arrays.hashCode(response.toByteArray())); logger.debug("Response Data is {} {}", response.getData().length, Arrays.toString(response.getData())); DatagramPacket sendPacket = null; try { logger.debug("Response to " + Arrays.toString(response.getInetaddr()) + " " + response.getPort()); sendPacket = new DatagramPacket(response.getData(), response.getData().length, InetAddress.getByAddress(response.getInetaddr()), response.getPort()); socket.send(sendPacket); } catch (IOException e) { e.printStackTrace(); } finally { } } } <file_sep>package org.lff.client.netty; import org.lff.client.listener.DNSListenerThread; import java.net.URISyntaxException; /** * User: LFF * Datetime: 2014/12/26 10:15 */ public class NettyClient { public static void main(String[] argu) { String host = "192.168.127.12"; int port = 8080; DNSListenerThread t = null; try { t = new DNSListenerThread(new NettyDNSClientCallback(host, port)); } catch (URISyntaxException e) { e.printStackTrace(); return; } new Thread(t).start(); } } <file_sep>package org.lff.client.actors; import akka.actor.*; import org.lff.client.listener.DNSListenerThread; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.DatagramSocket; /** * User: LFF * Datetime: 2014/12/24 11:51 */ public class DNSListenerActor extends UntypedActor { private static final Logger logger = LoggerFactory.getLogger(DNSListenerActor.class); private ActorRef clientActor; private DatagramSocket socket; @Override public void onReceive(Object o) throws Exception { if (o instanceof String) { DNSListenerThread t = new DNSListenerThread(new AkkaDNSClientCallback(this.context())); new Thread(t).start(); return; } } } <file_sep>package org.lff.common.messages; import java.io.Serializable; /** * User: LFF * Datetime: 2014/12/25 10:18 */ public class OKMessage implements Serializable { } <file_sep>package org.lff.client.netty; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.CookieEncoder; import org.jboss.netty.handler.codec.http.DefaultHttpRequest; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpMethod; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpVersion; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.*; public class HTTPReader { private final URI uri; private ClientBootstrap bootstrap; public HTTPReader(String host, int port) throws URISyntaxException { this.uri = new URI("http://" + host + ":" + port + "/"); // Configure the client. bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the event pipeline factory. bootstrap.setPipelineFactory(new HttpSnoopClientPipelineFactory()); } public byte[] run(byte[] msg, DatagramSocket socket) { String host = this.uri.getHost(); int port = this.uri.getPort(); // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.awaitUninterruptibly().getChannel(); if (!future.isSuccess()) { future.getCause().printStackTrace(); return null; } // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded"); ChannelBuffer cb = ChannelBuffers.copiedBuffer(msg); long serial = System.nanoTime(); request.headers().add("Serial", String.valueOf(serial)); request.headers().add(HttpHeaders.Names.CONTENT_LENGTH,cb.readableBytes()); request.setContent(cb); // Send the HTTP request. channel.write(request); // Wait for the server to close the connection. channel.getCloseFuture().awaitUninterruptibly(); try { byte[] result = ResultNotifier.waitFor(String.valueOf(serial)); return result; } catch (InterruptedException e) { return null; } // shutdown(bootstrap); } private void shutdown(ClientBootstrap bootstrap) { // Shut down executor threads to exit. bootstrap.releaseExternalResources(); } public static void main(String[] args) throws Exception { String host = "127.0.0.1"; int port = 8080; HTTPReader r = new HTTPReader(host, port); for (int i=0; i<10; i++) { r.run("AAAAAAAAAAAAAAAAAA".getBytes(), null); } } }<file_sep>package org.lff.common.messages; import java.io.*; /** * User: LFF * Datetime: 2014/12/24 12:11 */ public class ResponseMessage implements Serializable { private byte[] data; private int port; private byte[] inetaddr; public ResponseMessage() { } public ResponseMessage(byte[] data) { ByteArrayInputStream bis = new ByteArrayInputStream(data); DataInputStream dis = new DataInputStream(bis); try { int length = dis.readInt(); this.data = new byte[length]; dis.readFully(this.data); port = dis.readInt(); length = dis.readInt(); this.inetaddr = new byte[length]; dis.readFully(this.inetaddr); } catch (IOException e) { e.printStackTrace(); } } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public byte[] getInetaddr() { return inetaddr; } public void setInetaddr(byte[] inetaddr) { this.inetaddr = inetaddr; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } public byte[] toByteArray() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream ds = new DataOutputStream(bos); try { ds.writeInt(data.length); ds.write(data); ds.writeInt(port); ds.writeInt(inetaddr.length); ds.write(inetaddr); ds.close(); } catch (IOException e) { e.printStackTrace(); } return bos.toByteArray(); } } <file_sep>package org.lff.common.messages; import java.io.*; /** * User: LFF * Datetime: 2014/12/24 11:54 */ public class RequestMessage implements Serializable { private byte[] dnsServer; private byte[] request; private int port; private byte[] inetaddr; public RequestMessage() { } public RequestMessage(byte[] data) { ByteArrayInputStream bis = new ByteArrayInputStream(data); DataInputStream dis = new DataInputStream(bis); try { int length = dis.readInt(); this.request = new byte[length]; dis.readFully(this.request); length = dis.readInt(); this.dnsServer = new byte[length]; dis.readFully(this.dnsServer); this.port = dis.readInt(); length = dis.readInt();; this.inetaddr = new byte[length]; dis.readFully(this.inetaddr); } catch (IOException e) { e.printStackTrace(); } } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public byte[] getInetaddr() { return inetaddr; } public void setInetaddr(byte[] inetaddr) { this.inetaddr = inetaddr; } public byte[] getDnsServer() { return dnsServer; } public void setDnsServer(byte[] dnsServer) { this.dnsServer = dnsServer; } public byte[] getRequest() { return request; } public void setRequest(byte[] request) { this.request = request; } public byte[] toByteArray() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream ds = new DataOutputStream(bos); try { ds.writeInt(request.length); ds.write(request); ds.writeInt(dnsServer.length); ds.write(dnsServer); ds.writeInt(port); ds.writeInt(inetaddr.length); ds.write(inetaddr); ds.close(); } catch (IOException e) { e.printStackTrace(); } return bos.toByteArray(); } } <file_sep>package org.lff.server.netty; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.buffer.DynamicChannelBuffer; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.frame.TooLongFrameException; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.jboss.netty.util.CharsetUtil; import org.lff.common.messages.RSAEncryptedRequestMessage; import org.lff.common.messages.RequestMessage; import org.lff.common.messages.ResponseMessage; import org.lff.rsa.RSACipher; import org.lff.server.worker.Resolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.ws.Response; import java.util.Arrays; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK; import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1; /** * User: LFF * Datetime: 2014/12/26 10:07 */ public class DNSServerHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = LoggerFactory.getLogger(DNSServerHandler.class); @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) e.getMessage(); String uri = request.getUri(); byte[] data = request.getContent().array(); data = RSACipher.decrypt(data); String serial = request.headers().get("Serial"); if (serial == null) { } RequestMessage requestMessage = new RequestMessage(data); logger.debug("Request Message Hash = " + Arrays.hashCode(requestMessage.toByteArray())); byte[] dnsServer = requestMessage.getDnsServer(); byte[] dnsRequest = requestMessage.getRequest(); byte[] result = Resolver.doWork(dnsRequest, dnsServer); if (result != null) { logger.debug("Real DNS Response is {} {}", result.length, Arrays.toString(result)); ResponseMessage m = new ResponseMessage(); m.setData(result); m.setPort(requestMessage.getPort()); m.setInetaddr(requestMessage.getInetaddr()); logger.debug("Response Message Hash = " + Arrays.hashCode(m.toByteArray())); byte[] r = RSACipher.encrypt(m.toByteArray()); logger.debug("Encrypted Response is {} {}", r.length, Arrays.toString(r)); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); ChannelBuffer buffer = new DynamicChannelBuffer(2048); buffer.writeBytes(r); response.setContent(buffer); response.headers().add("Content-Type", "text/html; charset=UTF-8"); response.headers().add("Content-Length", response.getContent().writerIndex()); response.headers().add("Serial", serial); Channel ch = e.getChannel(); // Write the initial line and the header. ch.write(response); ch.disconnect(); ch.close(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { Channel ch = e.getChannel(); Throwable cause = e.getCause(); if (cause instanceof TooLongFrameException) { sendError(ctx, BAD_REQUEST); return; } cause.printStackTrace(); if (ch.isConnected()) { sendError(ctx, INTERNAL_SERVER_ERROR); } } private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status); response.headers().add(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.setContent(ChannelBuffers.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8)); // Close the connection as soon as the error message is sent. ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); } } <file_sep>package org.lff.client.listener; /** * User: LFF * Datetime: 2014/12/27 11:57 */ public class QueryType { public static final int A = 0x01; //指定计算机 IP 地址。   public static final int NS = 0x02; //指定用于命名区域的 DNS 名称服务器。   public static final int MD = 0x03;//指定邮件接收站(此类型已经过时了,使用MX代替)  public static final int MF = 0x04;//指定邮件中转站(此类型已经过时了,使用MX代替)  public static final int CNAME = 0x05;//指定用于别名的规范名称。   public static final int SOA = 0x06;//指定用于 DNS 区域的“起始授权机构”。   public static final int MB = 0x07;//指定邮箱域名。  // public static final int MG = 0x08;//指定邮件组成员。//   public static final int MR = 0x09;//指定邮件重命名域名。//    public static final int NULL = 0x0A;//指定空的资源记录   public static final int WKS = 0x0B;//描述已知服务。   public static final int PTR = 0x0C;//如果查询是 IP 地址,则指定计算机名;否则指定指向其它信息的指针。  public static final int HINFO = 0x0D;//指定计算机 CPU 以及操作系统类型。   public static final int MINFO = 0x0E;//指定邮箱或邮件列表信息。   public static final int MX = 0x0F; //指定邮件交换器。 public static final int TXT=0x10; //指定文本信息。   public static final int UINFO=0x64; //指定用户信息。   public static final int UID=0x65; //指定用户标识符。   public static final int GID=0x66; //指定组名的组标识符。   public static final int ANY=0xFF; //指定所有数据类型。 } <file_sep>package org.lff.client.actors; import akka.actor.ActorRef; import akka.actor.ActorSelection; import akka.actor.ActorSystem; import akka.actor.Props; import akka.pattern.Patterns; import akka.util.Timeout; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.lff.common.messages.OKMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; import java.util.concurrent.TimeoutException; /** * User: LFF * Datetime: 2014/12/24 11:15 */ public class AkkaClientMain { private static final Logger logger = LoggerFactory.getLogger(AkkaClientMain.class); public static void main(String[] argu) { String config = "akka\n{ actor {\n" + "provider = \"akka.remote.RemoteActorRefProvider\"\n" + "typed {\n" + "timeout = 6000s\n" + "}\n" + "}\n" + "remote {\n" + " enabled-transports = [\"akka.remote.netty.tcp\"]\n" + "netty.tcp {\n" + " hostname = \"127.0.0.1\"\n" + " port = 2553\n" + "} } }"; logger.info("Client Started."); Config c = ConfigFactory.parseString(config); ActorSystem system = ActorSystem.create("RelayClient", c); ActorRef d = system.actorOf(Props.create(DNSListenerActor.class), "dnsClientListener"); logger.info("Test remote client started."); Timeout timeout = new Timeout(Duration.create(5, "seconds")); ActorSelection selection = system.actorSelection("akka.tcp://[email protected]:2552/user/dns"); Future<Object> future = Patterns.ask(selection, new OKMessage(), timeout); String result = null; try { result = (String) Await.result(future, timeout.duration()); } catch (TimeoutException te) { logger.error("Remote client did not response in 5 seconds. Please check."); system.shutdown(); return; } catch (Exception e) { e.printStackTrace(); } logger.info("Test result is {}", result); d.tell("START", null); } } <file_sep><project name="DNS Relay" default="Dist" basedir="."> <!-- Get the build time --> <tstamp> <format property="build.timestamp" pattern="MMM dd, yyyy hh:mm:ss a"/> </tstamp> <property name="build.home" value="."></property> <property name="build.dist" value="dist"></property> <property name="build.classes" value="classes"></property> <path id="slf4j.classpath"> <fileset dir="${build.home}/lib/"> <include name="slf4j-api-1.7.7.jar" /> </fileset> </path> <path id="akka.classpath"> <fileset dir="${build.home}/lib/"> <include name="akka*.jar" /> <include name="config*.jar" /> <include name="scala*.jar" /> </fileset> </path> <path id="netty.classpath"> <fileset dir="${build.home}/lib/"> <include name="netty*.jar" /> </fileset> </path> <target name="clean"> <delete dir="${build.classes}"/> <delete dir="${build.dist}"/> <mkdir dir="${build.classes}"/> <mkdir dir="${build.dist}"/> </target> <target name="Message" depends="clean"> <javac srcdir="Message/src" encoding="UTF-8" destdir="${build.classes}/" debug="on"> </javac> </target> <target name="RSA" depends="clean,Message"> <javac srcdir="RSA/src" encoding="UTF-8" destdir="${build.classes}/" debug="on"> <classpath refid="slf4j.classpath"/> </javac> </target> <target name="Client" depends="RSA"> <javac srcdir="Client/src" encoding="UTF-8" destdir="${build.classes}/" debug="on"> <classpath refid="slf4j.classpath"/> <classpath refid="akka.classpath"/> <classpath refid="netty.classpath"/> </javac> </target> <target name="Server" depends="Client"> <javac srcdir="Server/src" encoding="UTF-8" destdir="${build.classes}/" debug="on"> <classpath refid="slf4j.classpath"/> <classpath refid="akka.classpath"/> <classpath refid="netty.classpath"/> </javac> </target> <target name="Dist" depends="Debug"> <jar destfile="${build.dist}/dnsRelay.jar" basedir="${build.classes}" includes="org/**"> </jar> <copy todir="${build.dist}"> <fileset dir="${build.home}/lib/"> <include name="*.jar" /> </fileset> </copy> <copy todir="${build.dist}"> <fileset dir="."> <include name="*.key" /> <include name="Server/src/logback.xml" /> </fileset> </copy> </target> <target name="Debug" depends="clean,Message,RSA,Client,Server"> </target> </project><file_sep>package org.lff.client.callback; import org.lff.common.messages.RequestMessage; import java.net.DatagramSocket; /** * User: LFF * Datetime: 2014/12/26 10:17 */ public interface DNSCallback { public void callback(RequestMessage message, DatagramSocket socket); } <file_sep>DNSRelay ======== A Java based DNS Relayer to go through the GFW. Requirement: 1. JRE/JDK 6+. 2. A VPS server that can access a DNS service. Many domains, are blocked in China. For example, facebook.com and twitter.com. -) If you use a DNS server in China, querying ip addresses for such domains will result a wrong ip address. -) If you use a DNS server outside China(Google Public DNS, OpenDNS, etc), the GFW (Great Fire Wall) will hijacking the DNS Request Packages and reply to you with a fake DNS response. As a result, you cannot get the correct ip addresses for the domain. Current solutions : -) Modify host name file(/etc/host, c:\Windows\System32\Drivers\etc\host). -) Use TCP DNS protocol. But GFW started to hijack the TCP DNS packages. Or, GFW started to hijack the packages to port 53. -) Use a VPN. But today, most VPN services out of China can not be used smoothly, because the port 1723 for PPTP, 1701 for L2TP, GRE ptotocal are all blocked, or interferenced by the firewall. So I created this project. This DNS Relay, has 2 parts, one is client and the other is server. The client side runs locally, which listenes on port 53 for DNS requests from your computer. After the client receives a DNS request, it will encrypt, and send it to the remote server. The remote server receives the encrypted data, decrypt it, and query the DNS. After the remote server gets the response, it will encrypt and send it back the client. At last, the client decrypted it, and response to local computer.
c44980e376bf1fb260ad07671e282574f4721f2c
[ "Markdown", "Java", "Ant Build System" ]
13
Java
lff0305/DNSRelay
266e994dd5342d137de9c7cd859644510429c083
248b3c4786e1412f59e00e0dbb18072f3c817cc8
refs/heads/master
<repo_name>kokhung0802/Solving-Cartpole-DeepQNet<file_sep>/myfile.py # This is a test file def experiment(): print("Helo") # new changes to the file # This is version 2.0 # This is version 3.0
c51dfae21dae28cb8326550c673359178fc2ff64
[ "Python" ]
1
Python
kokhung0802/Solving-Cartpole-DeepQNet
8f85a2beeec38d5e8258dd29177ece3add1a635c
a07a1c2ade25ee16d625b987396f1df958c229e1
refs/heads/master
<file_sep>package cn.lemonit.lemix.util; import android.content.Context; import android.os.Environment; import java.io.File; import java.io.FilenameFilter; /** * Io相关的工具类 * * @author liuri */ public class IoUtil { public static boolean isSDCardExist() { return Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); } public static File getAppDir(Context context) { if (isSDCardExist()) { return context.getExternalFilesDir(""); } else { return context.getFilesDir(); } } public static File getWorkDir(Context context, final String dirName) { File appDir = getAppDir(context); File dir = new File(appDir.getAbsolutePath() + File.separator + dirName); if (!dir.exists() || !dir.isDirectory()) { // 不存在这个文件夹或存在但不是文件夹 dir.mkdirs(); } return dir; } } <file_sep># lemix-android lemix-android混合开发框架Android原生端 <file_sep>include ':lemix-example', ':lemix-lib'
ffa7f74da37afabefb0b15a6d2c54da19a9a22ce
[ "Markdown", "Java", "Gradle" ]
3
Java
LemonITCN/mixer-android
c4c0920e93d56c0f1390ace00d57e2bb1a956332
e05b80667fc3e38d447d7c02751a068a9a06025c
refs/heads/master
<file_sep>/* string_startswith.c <NAME> - 05/10/2016 */ #include <stdio.h> /* string_startswith(s, prefix) Test whether the string s starts with the string prefix. If so, return 1. Otherwise, return 0. Pre-conditions: s and prefix are valid, null terminated C strings. Return value: 1 if string s starts with string prefix. 0 otherwise */ int string_startswith(char s[], char prefix[]) { if(s[0]=='\0' || prefix[0] =='\0') return 0; int i = 0; int flag = 0; while (s[i] != '\0'){ printf("%c\n - %c\n", s[i] prefix[i]); // for debugging if (prefix[i] != s[i]){ flag = 0; break; } i++; } return flag; } int main() { // Add some test cases for string_startswith here... char st1[] = "ABCDE"; char st2[] = "AB"; if (string_startswith(st1, st2)) { printf("%s is found within %s\n", st2, st1); } else { printf("%s is NOT found within %s\n", st2, st1); } return 0; }
a9c55f3485b979921c9eb26d28bb65b5557dd218
[ "C" ]
1
C
JVerwolf/Assignment_1
7dd689cf86ffbbbee00a2ac694b149103fb1d739
1825de3c9a69e0667d6b3fa03ff2f036d54627a1
refs/heads/master
<repo_name>AdrenalineCoffee/ArduinoSketch<file_sep>/Sumo/Sumo.ino #include <Ultrasonic.h> Ultrasonic ultrasonic(11,12); int IN1 = 7; // Input1 подключен к выводу 5 int IN2 = 6; int IN3 = 4; int IN4 = 5; int ENA = 9; int ENB = 3; int b1 = 2; // Бампер слева int b2 = 10; // Бампер справа int IRpin = 3; // ИК передний дальномер float volts = 0.0; float distance = 0.0; void setup() { pinMode (ENA, OUTPUT); pinMode (IN1, OUTPUT); pinMode (IN2, OUTPUT); pinMode (ENB, OUTPUT); pinMode (IN4, OUTPUT); pinMode (IN3, OUTPUT); pinMode(b1, INPUT); pinMode(b2, INPUT); delay(3000); //Wire.begin(); // join i2c bus (address optional for master) //Serial.begin(9600); // start serial for output } void loop() { if (digitalRead(b1) == HIGH && digitalRead(b2) == HIGH){ //Если всё заебись volts = analogRead(IRpin)*0.0048828125; // считываем значение сенсора и переводим в напряжение distance = 65*pow(volts, -1.10); // worked out from graph 65 = theretical distance / (1/Volts)S - luckylarry.co.uk delay(100); //Serial.println(distance); if(distance < 120) up(); else right(); if(ultrasonic.Ranging(CM) < 50) down(); } if (digitalRead(b1) == HIGH && digitalRead(b2) == LOW){ //Если черная линия справа left(); delay(1000); } if (digitalRead(b1) == LOW && digitalRead(b2) == HIGH){// Если черная линия слева right(); delay(1000); } if (digitalRead(b1) == LOW && digitalRead(b2) == LOW){// Если полностью заехали на черную линию down(); delay(1000); left(); delay(1000); } //if(digitalRead(b1) == LOW) left(); //else if(digitalRead(b2) == LOW) right(); //else stopd(); // volts = analogRead(IRpin)*0.0048828125; // считываем значение сенсора и переводим в напряжение // distance = 65*pow(volts, -1.10); // worked out from graph 65 = theretical distance / (1/Volts)S - luckylarry.co.uk // Serial.println(distance); } void down(){ digitalWrite (IN2, LOW); digitalWrite (IN1, HIGH); digitalWrite (IN4, HIGH); digitalWrite (IN3, LOW); analogWrite(ENA, 255); analogWrite(ENB, 255); } void up(){ digitalWrite (IN2, HIGH); digitalWrite (IN1, LOW); digitalWrite (IN4, LOW); digitalWrite (IN3, HIGH); analogWrite(ENA, 255); analogWrite(ENB, 255); } void right(){ digitalWrite (IN2, LOW); digitalWrite (IN1, HIGH); digitalWrite (IN4, LOW); digitalWrite (IN3, HIGH); analogWrite(ENA, 255); analogWrite(ENB, 255); } void left(){ digitalWrite (IN2, HIGH); digitalWrite (IN1, LOW); digitalWrite (IN4, HIGH); digitalWrite (IN3, LOW); analogWrite(ENA, 255); analogWrite(ENB, 255); } void stopd(){ analogWrite(ENA, 0); analogWrite(ENB, 0); }
151d2b53c9972461ea58a76fe13b3061ee9a901b
[ "C++" ]
1
C++
AdrenalineCoffee/ArduinoSketch
215e7089fde50a309b42a3497e1db185333ded94
cdf4823dbd7852d0703930c1a0da43704a148cf9
refs/heads/master
<repo_name>huangtinglin/speech-processing-<file_sep>/Lin/何老师/ReadMe.txt ======================================================================== 控制台应用程序:何老师 项目概述 ======================================================================== 应用程序向导已为您创建了此 何老师 应用程序。 本文件概要介绍组成 何老师 应用程序的每个文件的内容。 何老师.vcxproj 这是使用应用程序向导生成的 VC++ 项目的主项目文件,其中包含生成该文件的 Visual C++ 的版本信息,以及有关使用应用程序向导选择的平台、配置和项目功能的信息。 何老师.vcxproj.filters 这是使用“应用程序向导”生成的 VC++ 项目筛选器文件。它包含有关项目文件与筛选器之间的关联信息。在 IDE 中,通过这种关联,在特定节点下以分组形式显示具有相似扩展名的文件。例如,“.cpp”文件与“源文件”筛选器关联。 何老师.cpp 这是主应用程序源文件。 ///////////////////////////////////////////////////////////////////////////// 其他标准文件: StdAfx.h, StdAfx.cpp 这些文件用于生成名为 何老师.pch 的预编译头 (PCH) 文件和名为 StdAfx.obj 的预编译类型文件。 ///////////////////////////////////////////////////////////////////////////// 其他注释: 应用程序向导使用“TODO:”注释来指示应添加或自定义的源代码部分。 ///////////////////////////////////////////////////////////////////////////// <file_sep>/Lin/何老师/何老师.cpp // 何老师.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" //http://blog.csdn.net/sandeepin/article/details/60866222 #include<iostream> #include<algorithm> #include<vector> #include<stack> #include<queue> #include<string> #include<stdio.h> #include<memory.h> #include<string.h> #include<time.h> #include<armadillo> using namespace std; using namespace arma; int a = 5; class Segment { public: mat begin; mat end; mat duration; Segment(int n) { begin.set_size(1, n); end.set_size(1, n); duration.set_size(1, n); } }; mat enframe(mat x, mat win, int inc) { int len; mat x1 = x; int nx = x1.n_elem; int nwin = win.n_elem; if (nwin == 1) { len = win(0); } else { len = nwin; } if (inc == -1) { inc = len; } int nf = floor((nx - len + inc) / inc); mat frameout(1, nf*len + 1); mat a(nf, 1); for (int i = 0; i < nf; i++) { a(i) = i; } mat indf = inc*a; mat inds(1, len); for (int i = 1; i <= len; i++) { inds(i - 1) = i; } int k = 0; inds = repmat(inds, nf, 1); indf = repmat(indf, 1, len); a = inds + indf; for (int i = 0; i < a.n_elem; i++) { frameout(k++) = x(a(i) - 1); } frameout.reshape(nf, len); if (nwin > 1) { a = win.t(); frameout = frameout%repmat(a, nf, 1); } return frameout; } mat FrameTimeC(int frameNum, int framelen, int inc, int fs) { mat frameTime(1, frameNum); for (int i = 1; i <= frameNum; i++) { double k = i; frameTime(i-1) = ((k - 1)*inc + framelen / 2) / fs; } return frameTime; } /* matlab的Segment数组,属性为begin、end、duration 我的是Segment变量,属性为begin矩阵、end矩阵、duration矩阵 matlab要取soundSegment(1).begin 这里是soundSegment.begin(1) 因为mat一定要声明好大小,所以这里有个循环我做了两次,没写好,不过程序是对的,下标从0开始 */ Segment findSegment(mat express) { int i, k; mat voicedIndex(1, express.n_cols); if (express(0) == 0) { k = 0; for (i = 0; i < express.n_cols; i++) { if (express(i) != 0) voicedIndex(k++) = i + 1; } } else voicedIndex = express; k = 1; for (i = 0; i <= voicedIndex.n_elem - 2; i++) { if (voicedIndex(i + 1) - voicedIndex(i) > 1) k++; } Segment soundSegment(k); k = 0; soundSegment.begin(0) = voicedIndex(0); for (i = 0; i <= voicedIndex.n_elem - 2; i++) { if (voicedIndex(i + 1) - voicedIndex(i) > 1) { soundSegment.end(k) = voicedIndex(i); soundSegment.begin(k + 1) = voicedIndex(i + 1); k++; } } soundSegment.end(k) = voicedIndex(voicedIndex.n_elem - 1); for (i = 0; i <= k; i++) { soundSegment.duration(i) = soundSegment.end(i) - soundSegment.begin(i) + 1; } return soundSegment; } int main() { /*mat express(1, 68); for (int i = 0; i < 50; i++) { express(i) = i + 1; } for (int i = 50; i < 59; i++) { express(i) = i + 2; } for (int i = 59; i < 68; i++) { express(i) = i + 3; } Segment a = findSegment(express); cout << a.begin << endl; cout << a.end << endl; cout << a.duration << endl;*/ //1、构造矩阵A、B /*mat A(2, 2), B(2, 2); for (int i = 0; i < 4; i++) { A(i) = i + 1;//i:以列为排列顺序,矩阵的第i个元素 B(i) = i + 5; } A.print("矩阵A为:"); B.print("矩阵B为:"); //2、矩阵A与矩阵B相加 mat AAddB = A + B; AAddB.print("A + B ="); //3、矩阵A与矩阵B相减 mat AMinusB = A - B; AMinusB.print("A - B ="); //4、矩阵A与矩阵B相乘 //mat AMulB = A * B; //AMulB.print("A * B ="); //5、矩阵A与矩阵B点除 mat ADiviB = A / B; ADiviB.print("A / B ="); //6、矩阵A与矩阵B点乘 mat ADotMulB = A % B; ADotMulB.print("A % B ="); B.col(1) = A.col(1) * 2; cout << endl << B << endl; B.reshape(1, 2); cout << B << endl; //cout << repmat(B, 5, 1) << endl; mat c; c << 0.165300 << 0.454037 << 0.995795 << 0.124098 << 0.047084 << endr << 0.688782 << 0.036549 << 0.552848 << 0.937664 << 0.866401 << endr << 0.348740 << 0.479388 << 0.506228 << 0.145673 << 0.491547 << endr << 0.148678 << 0.682258 << 0.571154 << 0.874724 << 0.444632 << endr << 0.245726 << 0.595218 << 0.409327 << 0.367827 << 0.385736 << endr; cout << c << endl; mat x; x << 5 << endr << 6 << endr << 14 << endr << 11 << endr << 15 << endr << 9 << endr << 7 << endr << 13 << endr << 18 << endr << 17 << endr << 4 << endr << 20 << endr << 16 << endr << 1 << endr << 10 << endr << 19 << endr << 8 << endr << 2 << endr << 12 << endr << 3 << endr; mat win; win << 10 << endr; int inc = 6; cout << enframe(x, win, inc);*/ //cout << FrameTimeC(211, 256, 128, 8000) << endl; return 0; } <file_sep>/README.md # speech-processing- matlab c语言 这是霖转的C语言程序,主要采用的是armadillo库
521b7c2521943254568dda4fb97f49c1903711bb
[ "Markdown", "Text", "C++" ]
3
Text
huangtinglin/speech-processing-
ec4519da0ee3dac43aaf1e6b9ccf68ea49fb0f59
e8ef9705b74f31f0d1923497e6f48ffb45d53c0a
refs/heads/master
<file_sep>(function () { var app = angular.module('app', [ 'roberthodgen.logger' ]); app.config(['LogProvider', function (LogProvider) { /** * LOG_LEVELS * May be configured by setting. */ LogProvider.LOG_LEVELS = ['warn', 'info', 'error']; /** * LOG_LEVELS * Add a single log level. */ LogProvider.LOG_LEVELS.push('test'); /** * LOG_LEVELS * Add a single log level with a hook. */ LogProvider.LOG_LEVELS.push({ name: 'alert', hooks: [function (entry) { alert(entry); }] }); /** * TO_CONSOLE */ LogProvider.TO_CONSOLE = true; /** * ATTACH_TO_WINDOW * When set to true, the Log serice will be attached to the window * thus making it accessible in the JavaScript console. */ LogProvider.ATTACH_TO_WINDOW = true; }]); app.controller('AppController', ['$scope', 'Log', function ($scope, Log) { $scope.init = function () { /** * Simple usage of the info loging level. */ Log.info('AppController: $scope.init'); }; /** * Init */ $scope.init(); }]); })(); <file_sep>describe('roberthodgen.logger', function () { beforeEach(angular.mock.module('roberthodgen.logger')); describe('LogProvider', function () { var LogProvider; beforeEach(angular.mock.module(function (_LogProvider_) { LogProvider = _LogProvider_; })); // Fire the injector beforeEach(angular.mock.inject(function () {})); it('should exist', function () { expect(LogProvider).toBeDefined(); }); }); describe('Log', function () { var Log; beforeEach(angular.mock.inject(function (_Log_) { Log = _Log_; })); it('should exist', function () { expect(Log).toBeDefined(); }); }); describe('LogLevelFactory', function () { var LogLevelFactory; beforeEach(angular.mock.inject(function (_LogLevelFactory_) { LogLevelFactory = _LogLevelFactory_; })); it('should exist', function () { expect(LogLevelFactory).toBeDefined(); expect(LogLevelFactory).toEqual(jasmine.any(Function)); }); describe('return value', function () { var log; beforeEach(function () { log = LogLevelFactory({ name: 'test' }); }); it('should be a Function', function () { expect(log).toBeDefined(); expect(log).toEqual(jasmine.any(Function)); }); it('should initialize an Array in LOG_HOOKS', function () { var LOG_HOOKS; angular.mock.inject(function (_LOG_HOOKS_) { LOG_HOOKS = _LOG_HOOKS_; }); expect(LOG_HOOKS.test).toBeDefined(); expect(LOG_HOOKS.test).toEqual(jasmine.any(Array)); }); it('should initialize an Array in LOG_HISTORY', function () { var LOG_HISTORY; angular.mock.inject(function (_LOG_HISTORY_) { LOG_HISTORY = _LOG_HISTORY_; }); expect(LOG_HISTORY.test).toBeDefined(); expect(LOG_HISTORY.test).toEqual(jasmine.any(Array)); }); it('should have a history property (equal to entry in LOG_HISTORY)', function () { var LOG_HISTORY; angular.mock.inject(function (_LOG_HISTORY_) { LOG_HISTORY = _LOG_HISTORY_; }); expect(log.history).toBeDefined(); expect(log.history).toEqual(LOG_HISTORY.test); }); it('should have an addHook Function', function () { expect(log.addHook).toBeDefined(); expect(log.addHook).toEqual(jasmine.any(Function)); }); describe('invoking with a single argument', function () { it('should push the argument onto LOG_HISTORY', function () { var LOG_HISTORY; angular.mock.inject(function (_LOG_HISTORY_) { LOG_HISTORY = _LOG_HISTORY_; }); log('af154dab-6f59-41bf-a422-3dbc5702a8b9'); expect(LOG_HISTORY.test[0]).toBe('af154dab-6f59-41bf-a422-3dbc5702a8b9'); }); it('should call all hooks with the argument', function () { var val, hook = function (arg) { val = arg; }; log.addHook(hook); log('d3e18832-f64e-4adf-93c9-3e41229280f4'); expect(val).toBe('d3e18832-f64e-4adf-93c9-3e41229280f4'); }); }); }); describe('addHook', function () { var log; beforeEach(function () { log = LogLevelFactory({ name: 'test' }); }); it('should add the Function to LOG_HOOKS Object under the log', function () { var LOG_HOOKS; angular.mock.inject(function (_LOG_HOOKS_) { LOG_HOOKS = _LOG_HOOKS_; }); expect(LOG_HOOKS.test).toBeDefined(); expect(LOG_HOOKS.test).toEqual(jasmine.any(Array)); expect(LOG_HOOKS.test.length).toBe(0); var fn = function () {}; log.addHook(fn); expect(LOG_HOOKS.test.length).toBe(1); expect(LOG_HOOKS.test[0]).toEqual(fn); }); describe('return value', function () { var val; beforeEach(function () { val = log.addHook(function () {}); }); it('should be a Function', function () { expect(val).toBeDefined(); expect(val).toEqual(jasmine.any(Function)); }); it('should remove the hook from LOG_HOOKS when called', function () { var LOG_HOOKS; angular.mock.inject(function (_LOG_HOOKS_) { LOG_HOOKS = _LOG_HOOKS_; }); val(); expect(LOG_HOOKS.test).toBeDefined(); expect(LOG_HOOKS.test).toEqual(jasmine.any(Array)); expect(LOG_HOOKS.test.length).toBe(0); }); }); }); }); }); <file_sep># roberthodgen-logger > Improved logger for AngularJS projects. ## Features - Multiple, customizable log levels. - Log history accessible via JavaScript. - Hooks for error handling. ## Install ``` npm install roberthodgen-logger ``` ## Usage Include the `logger.js` file in your project: ``` <script src="logger.js"></script> ``` Make `roberthodgen.logger` available in your modules, e.g.: ``` var app = angular.module('myAppOrModule', ['roberthodgen.logger']); ``` ### Creating log entries ``` Log.debug('My debug message here...'); ``` Where `debug` property of `Log` should be switched to your defined level. ### Accessing history ``` Log.debug.history ``` A level's history is available through the `history` property. ### Using hooks ``` var deregisterFn = Log.debug.addHook(function (entry) { // Code to handle hook callback... }); ``` A hook may be added via calling `addHook` on a given log level. The function will be called every time the level receives a new entry. Note: `deregisterFn` is a function that removes the hook. It should be called when the hook is no longer needed. E.g. on a controller's $scope `$destroy` event: ``` $scope.$on('$destroy', function () { deregisterFn(); // Other cleanup code... }); ``` ### Defining custom log levels Custom log levels can be defined at the config state using the `LogProvider`. ``` app.config(['LogProvider', function (LogProvider) { LogProvider.LOG_LEVELS = ['info', 'debug', 'warn', 'error']; }]); ``` A working example of defining custom levels can be seen in `example/app.js`. A custom log level may also accept an Object in the following form: ``` { name: 'debug', hooks: [ function (entry) { // Code to handle entry... } ] } ``` Where the `name` property is the name associated with the log level and `hooks` is an Array of callback hook functions. NOTE: When adding hooks during config no deregister functions are saved or returned! ## Tests ``` $ karma run ``` All unit tests are located in the `test` directory. ## Getting access to Log from browser console With `LogProvider.ATTACH_TO_WINDOW` set to `TRUE` at configuration the Log service will be available in the JavaScript console simply as `Log`. ## Write to Console With `LogProvider.TO_CONSOLE` set to `TRUE` at configuration each log level will output to the JavaScript console with a similar name, e.g. warn, or default to `info`. This is accomplished via Angular's `$log` with the following logic: `$log[level.name] || $log.info || angular.noop`
c86b8b1b70695a803631c152f992c0b68b822895
[ "JavaScript", "Markdown" ]
3
JavaScript
roberthodgen/logger
846ba160301ddcf8b1dcb8fb5782938709f80510
bae1c13fa8a665038c3ce4688346787c1154b353
refs/heads/main
<repo_name>jobggun/a2s-check-docker<file_sep>/requirements.txt certifi>=2021.5.30 chardet>=4.0.0 docker>=5.0.0 idna>=2.10 python-a2s>=1.3.0 requests>=2.25.1 six>=1.16.0 urllib3>=1.26.5 websocket-client>=1.1.0 <file_sep>/app.py import socket import docker import os import a2s import time print('Target Container Name:', os.path.expandvars('${SRCDS_CONTAINER_NAME}')) print('Target SRCDS Host:', os.path.expandvars('${SRCDS_HOST}')) print('Target SRCDS Port:', os.path.expandvars('${SRCDS_PORT}')) print('Initial Wating Time:', os.path.expandvars('${INITIAL_WATING_TIME}')) client = docker.from_env() container = client.containers.get(os.path.expandvars('${SRCDS_CONTAINER_NAME}')) address = (os.path.expandvars('${SRCDS_HOST}'), int(os.path.expandvars('${SRCDS_PORT}'))) print(f'Wait for {os.path.expandvars('${INITIAL_WATING_TIME}')} seconds to ensure the server is available on start') time.sleep(int(os.path.expandvars('${INITIAL_WATING_TIME}'))) errorCount = 0 while True: try: a2s.info(address) except socket.timeout: errorCount += 1 print('Socket Timeout, Error Count:', errorCount) except socket.gaierror: errorCount += 1 print('No Route to Host, Error Count:', errorCount) except ConnectionRefusedError: errorCount += 1 print('Connection Refused, Error Count:', errorCount) else: errorCount = 0 finally: if errorCount == 5: print('Server Restarting...') errorCount = 0; container = client.containers.get(os.path.expandvars('${SRCDS_CONTAINER_NAME}')) container.restart() time.sleep(60) time.sleep(12)
e77b0ab3892fab1924024a406b36747e5c487291
[ "Python", "Text" ]
2
Text
jobggun/a2s-check-docker
1d79b9ce25bc72620cb0d185382aa8ceee67fcfb
e16353e8af995682be646c3327c1bc9b3861a995
refs/heads/master
<file_sep> #include "Vec_3D.h" #include <math.h> #define PI 3.1415926535897932384626433832795 #define PIdiv180 (PI/180.0) //Compute euclidean lenght of the vector from the origing inline float Vec3d::lenght() { //Vec3d RetVec; return sqrtf(((this->x *this->x) + (this->y *this->y) + (this->z *this->z))); } //Cross product of vectors Vec3d Vec3d::cross(Vec3d &temp1, Vec3d &temp2) { Vec3d RetVec; RetVec.x = (temp1.y*temp2.z) - (temp1.z*temp2.y); RetVec.y = (temp1.z*temp2.x) - (temp1.x*temp2.z); RetVec.z = (temp1.x*temp2.y) - (temp1.y*temp2.x); return RetVec; } //return dot product float Vec3d::dot(Vec3d &temp1, Vec3d &temp2) { return (temp1.x*temp2.x + temp1.y*temp2.y + temp1.z*temp2.z); } //a.y()*b.z() - a.z()*b.y(), // //a.z()*b.x() - a.x()*b.z(), // notation //a.x()*b.y() - a.y()*b.x()); //Simple vector addition Vec3d &Vec3d::operator+=(const Vec3d& tmp) { this->x = this->x + tmp.x; this->y = this->y + tmp.y; this->z = this->z + tmp.z; return *this; } //Simple vector multiplying Vec3d& Vec3d::operator*=(float tmp) { this->x = this->x * tmp; this->y = this->y * tmp; this->z = this->z * tmp; return *this; } //Simple vector multiplying by a scalar Vec3d Vec3d::operator*(float tmp) { return Vec3d(this->x*tmp, this->y*tmp, this->z*tmp); } //Constructor Vec3d::Vec3d(float newX, float newY, float newZ) { this->x = newX; this->y = newY; this->z = newZ; } //Another constructor Vec3d::Vec3d() { } //Simple vector subtraction Vec3d Vec3d::operator-(const Vec3d tmp1) { return Vec3d(this->x - tmp1.x, this->y - tmp1.y, this->z - tmp1.z); } //Normalize vector to make it unit vecotr void Vec3d::normalize() { float len = this->lenght(); if (len != 0) { this->x = this->x / len; this->y = this->y / len; this->z = this->z / len; } } //Vector assignment Vec3d Vec3d::operator=(const Vec3d tmp1) { //return(Vec3d(tmp1.x, tmp1.y, tmp1.z)); this->x = tmp1.x; this->y = tmp1.y; this->z = tmp1.z; return *this; } //Vector addition by a scalar Vec3d Vec3d::operator+(const Vec3d tmp1) { return Vec3d(this->x + tmp1.x, this->y + tmp1.y, this->z + tmp1.z); } //calculate the angle between two vector on X-Z plane. //using this formula: angle = arctan (sin/cos),while: // sin = (Vec1 (cross) Vec2) // cos = (Vec1 (dot) Vec2 )/ ||Vec1|| *||Vec2|| //the function return value in radian in domain[0,PI], so we convert it to angle between 0-360 degree. float Vec3d::convertViewVectorToAngle(Vec3d &vec2) { Vec3d res_cross= cross(*this, vec2); float dotDivLength = dot(*this, vec2) / ((*this).lenght() * ((vec2).lenght())); if (dotDivLength > 1) //according to calculation that are not accurate dotDivLength = 1; if(dotDivLength<-1) dotDivLength = -1; float angle = acosf(dotDivLength); angle = angle *180/PI; //to make it in range [0,180] angle *= -1; //change the angle orientation if (res_cross.y < 0) // This is assumption that we make angle of the vector on the X-Z plane //that means it in the IV.III quarter of the perpendicular vector of the cross return 360 - angle; else return angle; } <file_sep>#include "DataModel.h" //compute the lenght of quaternion vector double lenght(quaternion quat) { return sqrt(quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w); } //normalize the quaternion vector quaternion normalize(quaternion quat) { double len = lenght(quat); quat.x /= len; quat.y /= len; quat.z /= len; quat.w /= len; return quat; } //compute the conjugate quaternion conjugate(quaternion quat) //הצמוד { quat.x = -quat.x; quat.y = -quat.y; quat.z = -quat.z; //w is scalar (Real) //and w = cos(theha/2) // return quat; } //Compute multiplication between two quaternion //this function is not! commutative quaternion mult(quaternion A, quaternion B) { quaternion C; C.x = A.w*B.x + A.x*B.w + A.y*B.z - A.z*B.y; //just regular quaternion multiply - used by formula C.y = A.w*B.y - A.x*B.z + A.y*B.w + A.z*B.x; // expand by the formula (w1,x1,y1,z1)*(w2,x2,y2,z2) C.z = A.w*B.z + A.x*B.y - A.y*B.x + A.z*B.w; C.w = A.w*B.w - A.x*B.x - A.y*B.y - A.z*B.z; return C; } //return the value that is restrict to range [min,max] int restrictValue(int value, int min, int max) { //assume that max > min if (value > max) return max; if (value < min) return min; return value; } //return the value that is restrict to range [min,max] float restrictValue(float value, float min, float max) { //assume that max > min if (value > max) return max; if (value < min) return min; return value; } <file_sep>#pragma once #include "Vec_3D.h" class Robot { public: Vec3d robot_Pos; // (X,const,Z) position of the robot in the world Vec3d viewDirection; // the view vector is actually summation of (Position +viewDirection) of the whole robot Vec3d viewHeadDirection; //the direction of the head that is looking at. Vec3d up; Vec3d right; //it's actually the cross between :view and up vector. private: int headXAngle = 0, headYAngle = 0; //Head angle float bodyYangle; //Body orientation int shoulderAngle = 0, elbowAngle = 0, wristAngle = 0, plierAngle = 0; //arm angles public: Robot(); void draw(); // the function that draw the robot //change his parameters void move_forward(); void move_backward(); void move_a_side(float delta); // positive means right, negative means left void rotate_body(float angle); void rotate_right(); void rotateShoulder(int angle); void rotateElbow(int angle); void rotateWrist(int angle); void rotateWristAngle(int angle); //change the plier angle void rotateHeadUPDOWN(int angle);//which dimension to move the void rotateHeadToTheSIDES(int angle); //render from the robot point of view void look(); }; <file_sep>#pragma once // a class for regular eulers vectors class Vec3d { public: float x, y, z; public: Vec3d(); Vec3d(float newX, float newY, float newZ); Vec3d multiply(Vec3d temp); float lenght(); Vec3d cross(Vec3d &temp1, Vec3d &temp2); float convertViewVectorToAngle(Vec3d &vec2); void normalize(); //overload the following operators to make a good vector regular operations Vec3d& operator += (const Vec3d& tmp); Vec3d& operator *= (const float tmp); Vec3d operator -(const Vec3d tmp1); Vec3d operator =(const Vec3d tmp1); Vec3d operator +(const Vec3d tmp1); Vec3d operator * (float tmp); float dot(Vec3d &temp1, Vec3d &temp2); }; <file_sep>#include "Robot.h" #include "Robot.h" #include "stdio.h" #include <GL\glut.h> #include "DataModel.h" #define degree 0.0174532925 //1degree = (2pi / 360)radian #include <math.h> const Vec3d robotEyeOffset = Vec3d(0, 4.5, 0); //Vec3d(0.5,4,-2); #define PI 3.14159265358979323846264 //Constructor to initiliaze the values Robot::Robot() { //reset to default values robot_Pos = Vec3d(-7, 1.3, 32); //this shouldn't be hard-coded , it's need to be able take those values in the arguments of the constructors viewDirection = Vec3d(0, 0, 1); viewHeadDirection = Vec3d(0, 0, -1); up = Vec3d(0, 1, 0); right = (right.cross(viewDirection, up)*-1); //right.x = -4; //right.y = 0; //right.z = -15; } void Robot::draw() { GLfloat rotateAngle = (GLfloat)viewDirection.convertViewVectorToAngle(Vec3d(0, 0, 1) ); //draw the body and the Head glPushMatrix(); glPushMatrix(); glColor3f(1.0, 1.0, 0.0); glTranslatef(this->robot_Pos.x, this->robot_Pos.y, this->robot_Pos.z); // Place the robot on the the x-z board glRotatef(rotateAngle, 0, 1, 0); //move the robot according to user request //need to be computed from the view direction :) glPushMatrix(); //This is the Head glPushMatrix(); glTranslatef(0, 2.5, 0); glRotatef(-this->headYAngle, 0, 1, 0); glRotatef(-this->headXAngle, 1, 0, 0); //glTranslatef(0, -0.0, 0); glutSolidSphere(1.0, 10, 10); glColor3f(0.0, 1, 0); //the color of eyes.. glPushMatrix(); //Eye glTranslatef(0.3, 0.5, -0.8); glutSolidSphere(0.2, 10, 10); glPopMatrix(); glPushMatrix(); //Eye glTranslatef(-0.6, 0.5, -0.8); glutSolidSphere(0.2, 10, 10); glPopMatrix(); glPopMatrix(); //This is the Body glPushMatrix(); glColor3f(0.5, 0.9, 0.0); glutSolidCube(3.0); glPopMatrix(); glTranslatef(2.0, 1.0, 0); glRotatef(90, 0.0, 1, 0.0); //The Left hand of the robot /****************/ /*Draw robot arm*/ /****************/ glColor3f(0.8, 0.1, 0.0); //draw shoulder glPushMatrix(); glTranslatef(-1.0, 0.0, 0.0); glRotatef((GLfloat)this->shoulderAngle, 0.0, 0.0, 1.0); glTranslatef(1.0, 0.0, 0.0); glPushMatrix(); glScalef(2.0, 0.4, 1.0); glutSolidCube(1.0); glPopMatrix(); //draw elbow glTranslatef(1.0, 0.0, 0.0); glRotatef((GLfloat)this->elbowAngle, 0.0, 0.0, 1.0); glTranslatef(1.0, 0.0, 0.0); glPushMatrix(); glScalef(2.0, 0.4, 1.0); glutSolidCube(1.0); glPopMatrix(); //one plier glTranslatef(1.0, 0.0, 0.0); glRotatef((GLfloat)this->wristAngle, 0.0, 0.0, 1.0); glRotatef(45 - this->plierAngle, 0.0, 0.0, 1.0); glTranslatef(1.0, 0.0, 0.0); glPushMatrix(); glScalef(2.0, 0.4, 1.0); glutSolidCube(1.0); glPopMatrix(); //Second plier glTranslatef(-1.0, 0.0, 0.0); glRotatef(-90 + 2 * this->plierAngle, 0.0, 0.0, 1.0); glTranslatef(1.0, 0.0, 0.0); glPushMatrix(); glScalef(2.0, 0.4, 1.0); glutSolidCube(1.0); glPopMatrix(); glPopMatrix(); //The legs glPushMatrix(); glTranslatef(0, -3, -1); glScalef(1, 2, 1); glColor3f(0.5, 0.5, 0.5); glutSolidCube(1.0); glTranslated(0, -0.6, 0); //The feet glColor3f(0.0, 0.0, 0.5); glutSolidSphere(0.3, 10, 10); glPopMatrix(); glColor3f(1.0, 1.0, 1.0); glPushMatrix(); glTranslatef(0, -3, -3); glScalef(1, 2, 1); glColor3f(0.5, 0.5, 0.5); glutSolidCube(1.0); glTranslated(0, -0.6, 0); //The second feet glColor3f(0.0, 0.0, 0.5); glutSolidSphere(0.3, 10, 10); glPopMatrix(); glColor3f(1.0, 1.0, 1.0); glPopMatrix(); glPopMatrix(); } //rotate the head up and down according to angle void Robot::rotateHeadUPDOWN(int angle) { this->headXAngle = (this->headXAngle + angle) % 360; //restrict the head movement to 60 degree if (headXAngle > 60) headXAngle = 60; if (headXAngle < -60) headXAngle = -60; viewHeadDirection.y = -sin(headXAngle* PI / 180); //convert also the Head view vector according } //rotate the head to the sides (left , right) void Robot::rotateHeadToTheSIDES(int angle) { this->headYAngle = (this->headYAngle + angle) % 360; //Restrict the head movement to 60 degree if (headYAngle > 60) headYAngle = 60; if (headYAngle < -60) headYAngle = -60; Vec3d temp = viewDirection*-1; //Rotate also the Head view vector in function of the viewDirection this->viewHeadDirection.x = (float)(cos(headYAngle*PI / 180)*temp.x - sin(headYAngle*PI / 180)*temp.z); this->viewHeadDirection.z = (float)(sin(headYAngle*PI / 180)*temp.x + cos(headYAngle*PI / 180)*temp.z); viewHeadDirection.normalize(); } //move the position robot forward void Robot::move_forward() { this->robot_Pos += viewDirection*-1; } //move the position robot backward void Robot::move_backward() { this->robot_Pos += viewDirection; } //move a side , positive value means move right, // negative value means move left void Robot::move_a_side(float delta) { this->robot_Pos+= (right*delta); } //Rotate body according to the angle void Robot::rotate_body(float angle) { bodyYangle += (int)angle % 360; Vec3d temp = this->viewDirection;//this->viewDirection-this->robot_Pos; // this->viewDirection.x = (float)(cos(angle*PI/180)*temp.x - sin(angle*PI/180)*temp.z); // perform a rotation matrix around the y -axis this->viewDirection.z = (float)(sin(angle*PI/180)*temp.x + cos(angle*PI/180)*temp.z); this->viewDirection.normalize();// is it matter? the matrix rotation should be unitary...s //Re-compute the right vector for later calculation this->right = temp.cross(viewDirection, up)*-1; ////// Rotate the head with the body temp = viewDirection*-1; //rotate also the Head view vector in function of the viewDirection this->viewHeadDirection.x = (float)(cos(headYAngle*PI / 180)*temp.x - sin(headYAngle*PI / 180)*temp.z); // perform a rotation matrix around the y - axis this->viewHeadDirection.z = (float)(sin(headYAngle*PI / 180)*temp.x + cos(headYAngle*PI / 180)*temp.z); viewHeadDirection.normalize(); } //Rotate shoulder by an angle void Robot::rotateShoulder(int angle) { if (angle > 0) { if (shoulderAngle < 70)//restriction on the angle of rotation { shoulderAngle = (shoulderAngle + 5) % 360; } } else { if (shoulderAngle > -70)//restriction on the angle of rotation { shoulderAngle = (shoulderAngle - 5) % 360; } } } //Rotate the elbow by an angle void Robot::rotateElbow(int angle) { if (angle > 0) { if (elbowAngle < 70)//restriction on the angle of rotation { elbowAngle = (elbowAngle + 5) % 360; } } else { if (elbowAngle > -70)//restriction on the angle of rotation { elbowAngle = (elbowAngle - 5) % 360; } } } //Rotate the Wrist by an angle void Robot::rotateWrist(int angle) { if (angle > 0) { if (wristAngle < 70)//restriction on the angle of rotation { wristAngle = (wristAngle + 5) % 360; } } else { if (wristAngle > -70)//restriction on the angle of rotation { wristAngle = (wristAngle - 5) % 360; } } } //open the "Pliers" of the robot void Robot::rotateWristAngle(int angle) { if (angle > 0) { if (plierAngle < 35)//restriction on the angle of rotation { plierAngle = (plierAngle + 5) % 360; } } else { if (plierAngle > -35)//restriction on the angle of rotation { plierAngle = (plierAngle - 5) % 360; } } } //set the look into the robot eyes void Robot::look() { Vec3d eyePosition = robot_Pos + robotEyeOffset ; // compute the position where we look according to the robot position. Vec3d center = eyePosition + viewHeadDirection; gluLookAt(eyePosition.x , eyePosition.y, eyePosition.z, //make the position exactly at the robot eye center.x , center.y , center.z, //make the direction as the head 0 , 1 , 0); //Up vector } <file_sep>#pragma once #include <stdio.h> #include "Lights.h" #include <gl/glut.h> //directional Light 0 values: static GLfloat LightAmbientSpot[] = { 1.0f, 1.0f, 1.0f, 1.0f }; //spotlight params RGBA static GLfloat LightDiffuse[] = { 0.2f, 0.8f, 0.1f, 1.0f }; static GLfloat LightSpecular[] = { 0.0f, 0.5f, 0.0f, 1.0f }; static GLfloat LightAmbientGlobal[] = { 0.7, 0.7, 0.7, 0.0 }; //ambient params RGB //ambient Light value: static GLfloat mShininess[] = { 128 }; //set the shininess of the material //Constructor - it's should not be hard-coded Lights::Lights() { pos = Vec3d(20, 9, 4); viewDirection = Vec3d(-0.8, -0.4, 0.5); up = Vec3d(0, 1, 0); right = right.cross(viewDirection, up); ambientLight = true; } //"draw" the lights (ambient +spotlight) void Lights::draw() { glEnable(GL_LIGHTING); //glEnable(GL_FLAT); glEnable(GL_COLOR_MATERIAL); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); //glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE , LightAmbient); glMaterialfv(GL_FRONT_AND_BACK,GL_SHININESS,mShininess); if (ambientLight) { glLightModelfv(GL_LIGHT_MODEL_AMBIENT, LightAmbientGlobal); glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbientSpot); } //Spot light: GLfloat LightPosition[] = { (GLfloat)pos.x, (GLfloat)pos.y, (GLfloat)pos.z, 1.0f }; GLfloat LightDirection[] = { (GLfloat)this->viewDirection.x, (GLfloat)this->viewDirection.y, (GLfloat)this->viewDirection.z }; glEnable(GL_LIGHT0); //glLightfv(GL_LIGHT0, GL_AMBIENT, LightAmbient); //values of colors glLightfv(GL_LIGHT0, GL_AMBIENT, LightAmbientSpot); // Setup The Ambient Light glLightfv(GL_LIGHT0, GL_DIFFUSE, LightDiffuse); // Setup The Diffuse Light glLightfv(GL_LIGHT0, GL_SPECULAR, LightSpecular); // Setup The Specular Light //setting position. glLightfv(GL_LIGHT0, GL_POSITION, LightPosition); // Position The Light glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, LightDirection); // Direction The Light glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 10.0); //printf("Current ambient value are:Red= %f Blue %f Green %f \n", (float)LightAmbientGlobal[0], (float)LightAmbientGlobal[1], (float)LightAmbientGlobal[2]); --for debug only } //Change the amount of ambient color //params: Color = { 1=R, 2=B ,3=G } , amount ={ 0.1 or -0.1} void Lights::setSpotlightAmbientColor(int color, float amount) { //protect the values of colors to change if (amount > 0) { if (LightAmbientSpot[color] >= 1) /// protect from color to be more than 1; return; } else { if (LightAmbientSpot[color] <= 0.0) //protect from color to be less than 0; return; } //otherwise add the amount to the ambient color switch (color) { case 0: //RED LightAmbientSpot[0] += amount; break; case 1: //GREEN LightAmbientSpot[1] += amount; break; case 2: //BLUE LightAmbientSpot[2] += amount; break; default: break; } } //control the light moves void Lights::move(Direction dir) { switch (dir) { case UP: pos += (up*delta); break; case DOWN: pos += (up*-delta); break; case LEFT: pos += (right*-1 * delta); break; case RIGHT: pos += (right*delta); break; case FORWARD: this->pos = this->pos + (viewDirection*delta); break; case BACKWARD: this->pos = this->pos + (viewDirection* delta)*-1; break; default: break; } } //set the point of view of the light to the screen void Lights::look() { Vec3d viewPoint = this->pos + this->viewDirection; gluLookAt((GLdouble)this->pos.x, (GLdouble) this->pos.y, (GLdouble) this->pos.z, (GLdouble)viewPoint.x, (GLdouble)viewPoint.y, (GLdouble)viewPoint.z, (GLdouble) this->up.x, (GLdouble) this->up.y, (GLdouble)this->up.z); //Debug -remove //printf("\n posx=%f , posy=%f , posz =%f \n,viewx=%f ,viexY=%f,viewZ =%f, \n upx = %f, upy = %f, upz = %f \n", this->pos.x, this->pos.y, this->pos.z, // viewPoint.x, viewPoint.y, viewPoint.z, // this->up.x, this->up.y, this->up.z); } //This is copy of the camera roation //The rotation is around a vector(x,y,z) using the quaternion math. // occured on Rotation axis, with that math: NewVector= R*V*R' , where R' is the conjucate vector //each R mult is getting a , and it's done on 4 dim space.. //angle must be a radian... void Lights::RotateAroundQuaternion(double Angle, double x, double y, double z) { quaternion qRotationVector, qViewTemp, result; qRotationVector.x = x * sin(Angle / 2); qRotationVector.y = y * sin(Angle / 2); qRotationVector.z = z * sin(Angle / 2); qRotationVector.w = cos(Angle / 2); qViewTemp.x = this->viewDirection.x; qViewTemp.y = this->viewDirection.y; qViewTemp.z = this->viewDirection.z; qViewTemp.w = 0; result = mult(qRotationVector, mult(qViewTemp, conjugate(qRotationVector))); //The core of the Rotation R*V*R' //the order is not important-according to associative! //now build a rotation matrix, and then this->viewDirection.x = result.x; this->viewDirection.y = result.y; this->viewDirection.z = result.z; } //The objective of the function is to spin the camera around the camera that is pointing. //using quaternions vectors. //params: deltaX =mouse-x axis , deltaY= mouse-Y axis //X axis positive = right ; Y axis positiv = down the sceren //The function is inspied concisely by this site: //http://www.gamedev.net/page/resources/_/technical/math-and-physics/a-simple-quaternion-based-camera-r1997 void Lights::changeViewDirection(float deltaX, float deltaY) { //printf("x:%f ,y:%f \n", deltaX, deltaY); //for debug usage; Vec3d tmp = this->viewDirection -this->pos; Vec3d Axis = tmp.cross(tmp, this->up); //actually this is (view-pos)xup Axis.normalize(); RotateAroundQuaternion(deltaY, Axis.x, Axis.y, Axis.z); RotateAroundQuaternion(deltaX, 0, 1, 0); this->right = (right.cross(viewDirection, up)); //printf("Mousedir : Axis.x=%f , Axis.y=%f , z=%f \n", Axis.x, Axis.y, Axis.z); //for debug } //declare teh ambient values void Lights::setAmbientColor(float red, float green, float blue) { if (red < 0) red = 0; if (red > 1) red = 1; if (green < 0) green = 0; if (green > 1) green = 1; if (blue < 0) blue = 0; if (blue > 1) blue = 1; LightAmbientGlobal[0] = red; LightAmbientGlobal[1] = green; LightAmbientGlobal[2] = blue; } <file_sep> #pragma once //contains: //quaternion +//Usefully Enum's like: Direction,Control mode static const float delta = 0.95; #define PI 3.14159265358979323846264 #include <math.h> enum Direction { UP, DOWN, LEFT, RIGHT, FORWARD, BACKWARD }; enum ControlMode { GHOST, ROBOT,LIGHT }; //struct of quaternion is just a vector in 4 dimension (x*i+y*j+z*k+w) //we will represent it like: struct quaternion { double x, y, z, w; }; //quaternion functions: double lenght(quaternion quat); quaternion normalize(quaternion quat); quaternion conjugate(quaternion quat); quaternion mult(quaternion A, quaternion B);<file_sep>#pragma once #include <gl/glut.h> class World { public: World(); void draw(); private: void roof(); void floor();//draw the rotated roof void table();//basic table, consist 4 legs. void pyramid(); void cube(int i); //Draw a single cube with texture number i void metalValues(); public: int LoadGLTextures(); // A function to load an Texture using SOIL library.. private: GLuint texture[6]; //Array that's hold the textures public: int roofRotational; }; <file_sep>#include "World.h" #include "SOIL.h" //library for the textures loader static GLfloat LightAmbientSpot[] = { 0.0f, 1.0f, 1.0f, 1.0f }; //Gold Metal values (for the teapot) //those value define how much the color can emit from the teapot //this according to http://www.real3dtutorials.com/tut00008.php color chart GLfloat ChromeAmbient[] = { 0.25f, 0.148f, 0.06475f, 1.0f }; GLfloat ChromeDiffuse[] = { 0.4f, 0.2368f, 0.1036f, 1.0f }; GLfloat ChromeSpecular[] = { 0.774597f, 0.458561f, 0.200621f, 1.0f }; GLfloat ChromeShiness[] = { 76.8f }; const int sizecube = 1; //for the floor World::World() { roofRotational = 0; //LoadGLTextures(); } //main function of the world class //draw all the types in the room void World::draw() { glMatrixMode(GL_MODELVIEW_MATRIX); //draw the floor glPushMatrix(); glTranslatef(-30, -3, 0); floor(); glPopMatrix(); //draw the painting glPushMatrix(); glTranslatef(0, 4, 5); glScalef(3, 3, 3); glEnable(GL_TEXTURE_2D); roof(); glDisable(GL_TEXTURE_2D); glPopMatrix(); //draw the teapot glPushMatrix(); glTranslatef(-20, +1, 6); glScalef(0.3, 0.5, 0.3); metalValues(); glutSolidTeapot(2); glPopMatrix(); //draw the table glPushMatrix(); glTranslatef(-20, 0, 6); glScalef(0.6, 0.3, 0.3); table(); glPopMatrix(); //draw the cubes pyramid glPushMatrix(); glTranslatef(0, -1.5, 14); pyramid(); glPopMatrix(); glPopMatrix(); } //draw the roof and it's texture void World::roof() { //To do: check if to remove //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen and Depth Buffer glMatrixMode(GL_MODELVIEW); //glLoadIdentity(); glPushMatrix(); glTranslatef(-3.0f, 0.0f, 1.0f); glRotatef(roofRotational, 0.0, 1.0, 0.0); glScalef(10, 1, 10); glBindTexture(GL_TEXTURE_2D, texture[4]); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1, 3, 0); glTexCoord2f(1.0f, 0.0f); glVertex3f(0, 3, -1); glTexCoord2f(1.0f, 1.0f); glVertex3f(1, 3, 0); glTexCoord2f(0.0f, 1.0f); glVertex3f(0, 3, 1); glEnd(); glPopMatrix(); } void World::floor() { glMaterialfv(GL_FRONT, GL_AMBIENT, LightAmbientSpot); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 80.0f);//make the floor shiny GLfloat white[] = { 1.0f, 1.0f, 1.0f, 1.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white); glBegin(GL_QUADS); for (int x = 0; x < 50; x++) for (int y = 0; y < 50; y++) { { if (((y + x) % 2) == 0) //modulo 2 glColor3f(1.0f, 1.0f, 1.0f); else glColor3f(0.0f, 0.0f, 0.0f); //draw one tile glNormal3f(0, 1, 0); glVertex3f(x*sizecube, 0.5, (y + 1)*sizecube); glNormal3f(0, 1, 0); glVertex3f((x + 1)*sizecube, 0.5, (y + 1)*sizecube); glNormal3f(0, 1, 0); glVertex3f((x + 1)*sizecube, 0.5, y*sizecube); glNormal3f(0, 1, 0); glVertex3f(x*sizecube, 0.5, y*sizecube); } } glEnd(); } void World::table() { glPushMatrix(); glColor3f(0.8, 0.4, 0.0); //Brown Table //the top glPushMatrix(); glScalef(1.9, 0.5, 3); //the size of the top glutSolidCube(3); glPopMatrix(); glTranslatef(-2, -3.6, -2); //construct 4 legs for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { glPushMatrix(); glTranslatef(i * 4, 0, j * 3); glScalef(0.3, 3, 0.3); //the size of the top glutSolidCube(2.9); //put it in the glPopMatrix(); } } glPopMatrix(); } void World::pyramid() { glEnable(GL_TEXTURE_2D); for (int i = 0; i < 3; i++) { glTranslatef(-0.8*i, 0, 0); for (int j = i; j < 3; j++) { glPushMatrix(); glTranslatef(j*2.8, 2 * i, 0); cube(i); glPopMatrix(); } } glDisable(GL_TEXTURE_2D); } void World::cube(int i) { glBindTexture(GL_TEXTURE_2D, texture[i]); glBegin(GL_QUADS); // Front Face glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Back Face glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(1.0f, -1.0f, -1.0f); // Top Face glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, 1.0f, -1.0f); // Bottom Face glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Right face glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(1.0f, -1.0f, 1.0f); // Left Face glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glEnd(); } int World::LoadGLTextures() { /* load an image file directly as a new OpenGL texture */ texture[0] = SOIL_load_OGL_texture ( "Texture/escher2.jpg", // SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y ); texture[1] = SOIL_load_OGL_texture ( "Texture/escher1.jpg", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y ); //..\Texture\escher3.jpg", texture[2] = SOIL_load_OGL_texture ( "Texture/escher3.jpg", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y ); texture[3] = SOIL_load_OGL_texture ( "", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y ); texture[4] = SOIL_load_OGL_texture ( "Texture/TheRoof.jpg", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y ); texture[5] = SOIL_load_OGL_texture ( "Texture/helpme.jpg", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y ); if ((texture[0] == 0) || (texture[1] == 0) || (texture[2] == 0) || (texture[3] == 0) || (texture[4] == 0) || (texture[5] == 0)) return false; // Typical Texture Generation Using Data From The Bitmap glBindTexture(GL_TEXTURE_2D, texture[0]); glBindTexture(GL_TEXTURE_2D, texture[1]); glBindTexture(GL_TEXTURE_2D, texture[2]); glBindTexture(GL_TEXTURE_2D, texture[3]); glBindTexture(GL_TEXTURE_2D, texture[4]); glBindTexture(GL_TEXTURE_2D, texture[5]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); //glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR); //using mipmap for antialias glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); return true; // Return Success } void World::metalValues() { glEnable(GL_COLOR_MATERIAL); glMaterialfv(GL_FRONT, GL_AMBIENT, ChromeAmbient); glMaterialfv(GL_FRONT, GL_DIFFUSE, ChromeDiffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, ChromeSpecular); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, ChromeShiness); } <file_sep>#pragma once #include "Camera.h" #include <gl/glut.h> #include <math.h> #include "Vec_3D.h" #include "DataModel.h" #include "stdio.h" #define PI 3.1415926535897932384626433832795 #define PIdiv180 (PI/180.0) //this camera is inspired by http://www.gamedev.net/page/resources/_/technical/math-and-physics/a-simple-quaternion-based-camera-r1997 tutorial Camera::Camera(void) { //reset to default values this->pos = Vec3d(-10, 4, -23); this->viewDirection = Vec3d(0, 0, 1); this->up = Vec3d(0, 1, 0); this->right = Vec3d(1, 0, 0); //right = cross(view,up) //right(1.0, 0.0, 0.0); //To Remove: angleX, angleY, angleZ = 0; } //deconstructor Camera::~Camera(void) { } void Camera::look(void) { Vec3d viewPoint = this->pos + this->viewDirection; gluLookAt((GLdouble)this->pos.x, (GLdouble) this->pos.y, (GLdouble) this->pos.z, (GLdouble)viewPoint.x, (GLdouble)viewPoint.y, (GLdouble)viewPoint.z, (GLdouble) this->up.x, (GLdouble) this->up.y, (GLdouble)this->up.z); //for debugging: //printf("\n posx=%f , posy=%f , posz =%f \n,viewx=%f ,viexY=%f,viewZ =%f, \n upx = %f, upy = %f, upz = %f \n", this->pos.x, this->pos.y, this->pos.z, // viewPoint.x, viewPoint.y, viewPoint.z, // this->up.x, this->up.y, this->up.z); } //The rotation is around a vector(x,y,z) using the quaternion math. // occured on Rotation axis, with that math: NewVector= R*V*R' , where R' is the conjucate vector //each R mult is getting a , and it's done on 4 dim space.. //angle must be a radian... void Camera::RotateAroundQuaternion(double Angle, double x, double y, double z) { quaternion qRotationVector, qViewTemp, result; qRotationVector.x = x * sin(Angle / 2); qRotationVector.y = y * sin(Angle / 2); qRotationVector.z = z * sin(Angle / 2); qRotationVector.w = cos(Angle / 2); qViewTemp.x = this->viewDirection.x; qViewTemp.y = this->viewDirection.y; qViewTemp.z = this->viewDirection.z; qViewTemp.w = 0; result = mult(qRotationVector,mult( qViewTemp, conjugate(qRotationVector))); //The core of the Rotation R*V*R' //the order is not important-according to associative! //now build a rotation matrix, and then this->viewDirection.x = result.x; this->viewDirection.y = result.y; this->viewDirection.z = result.z; } //This function control the position of the camera according to the direction. void Camera::move(Direction dir) { switch (dir) { case UP: pos += (up*delta); break; case DOWN: pos += (up*-delta); break; case LEFT: pos += (right*delta); break; case RIGHT: pos += (right*delta*-1); break; case FORWARD: this->pos = this->pos + (viewDirection*delta); break; case BACKWARD: this->pos = this->pos + (viewDirection*-1*delta); break; default: break; } } //just initialize the camera values --- maybe not be necessary at the end.. void Camera::setValues(Vec3d newPos, Vec3d newView, Vec3d newUp) //,double positionX,double positionY,double positionZ,double viewX,double viewY,double viewZ,double UpX,double upY,double upZ) { this->pos.x = newPos.x; this->pos.y = newPos.y; this->pos.z = newPos.z; this->viewDirection.x = newView.x; this->viewDirection.y = newView.y; this->viewDirection.z = newView.z; this->up.x = newUp.x; this->up.y = newUp.y; this->up.z = newUp.z; //gluLookAt(positionX,positionY,positionZ,viewX,viewY,viewZ,UpX,upY,upZ); } //The objective of the function is to spin the camera around the camera that is pointing. //using quaternions vectors. //params: deltaX =mouse-x axis , deltaY= mouse-Y axis //X axis positive = right ; Y axis positiv = down the sceren //The function is inspied concisely by this site: //http://www.gamedev.net/page/resources/_/technical/math-and-physics/a-simple-quaternion-based-camera-r1997 void Camera::changeViewDirection(float deltaX, float deltaY) { //printf("x:%f ,y:%f \n",deltaX,deltaY); //for debug usage Vec3d tmp = this->viewDirection -this->pos; Vec3d Axis= tmp.cross(tmp,this->up); //actually this is (view-pos)x up Axis.normalize(); RotateAroundQuaternion(deltaY, Axis.x, Axis.y, Axis.z); RotateAroundQuaternion(deltaX, 0, 1, 0); this->right = (right.cross(viewDirection, up)*-1); // printf("Mousedir : Axis.x=%f , Axis.y=%f , z=%f \n", Axis.x, Axis.y, Axis.z); //for debug } <file_sep> //General libraries #include <math.h> #include <stdlib.h> #include <windows.h> #include <stdio.h> #include "Camera.h" #include "Lights.h" #include "Robot.h" #include "World.h" #include <GL\glut.h> #define ShowUpvector //Libraries that relevant to Open_GL: #include <GL\glut.h> #include "SOIL.h" //library for the textures loader //Camera Camera ghost; //Room objects: Robot rbt; Lights lgt; World w1; ControlMode mode; //Windows parameters int height = 600; int width = 800; int win1, win2; // Contain the glut number for the window. //Mouse parameters bool MouseLeftClicked = false;//control the mouse button state int lastx = 0; //keep the last x mouse coordinate int lasty = 0; //keep the last y mouse coordinate //Rotation of the roof degree int curr_rot = 0; //This method relevant for screen down message. //It's Increase the font of the current Viewpoint void textToScreen(int x, int y, float r, float g, float b, char *string) { //glEnable(GL_TEXTURE_2D); //added this int startMODE; int endMODE; switch (mode) { case GHOST: startMODE = 59; endMODE = 63; break; case ROBOT: startMODE = 65; endMODE =69; break; case LIGHT: startMODE = 71; endMODE = 75; break; default: break; } glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0.0, width, 0.0, height); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glDisable(GL_LIGHTING); //glDisable(GL_TEXTURE_2D); glColor3f(r, g, b); glRasterPos2f(x, y); int len, i; len = (int)strlen(string); for (i = 0; i < len; i++) { if ((i>=startMODE)&&(i<=endMODE)) { glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, string[i]); } else { glutBitmapCharacter(GLUT_BITMAP_9_BY_15, string[i]); } //glColor3f(r, g, b); } glEnable(GL_LIGHTING); //glEnable(GL_TEXTURE_2D); //draw a black rectangle on the background of the letters: glColor3f(0.0, 0.0, 0.0); glBegin(GL_QUADS); glVertex2f(0, 30); glVertex2f(0, 0); glVertex2f(760, 0); glVertex2f(760, 30); glEnd(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } //Callback function that resize the window void reshape(int x, int y) { if (y == 0 || x == 0) return; //Nothing is visible then, so return //Set a new projection matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Angle of view:40 degrees //Near clipping plane distance: 0.5 //Far clipping plane distance: 20.0 gluPerspective(40.0,(GLdouble)x/(GLdouble)y,0.5,400.0); glMatrixMode(GL_MODELVIEW); glViewport(0,0,x,y); //Use the whole window for rendering height = y; width = x; //width = , height = } //The main Display loop to draw the scene void display(void) { glLoadIdentity(); glEnable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //switch which viewPoint should we look switch (mode) { case GHOST: ghost.look(); break; case ROBOT: rbt.look(); break; case LIGHT: lgt.look(); break; default: break; } rbt.draw(); //draw the robot w1.draw(); //draw the world lgt.draw(); //make the light on // put Help text on the bottom of the windows char string[80] = "Shortcuts: F1-Help , Right Mouse-Setting , SPACE TOGGLE - |GHOST|ROBOT|LIGHT|"; textToScreen(0, 10, 0.9, 0.0, 1.0, string); glFlush(); glutSwapBuffers(); } //A function that draw the help window (while pressing - F1). void displayHelp(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_TEXTURE_2D); // Enable Texture Mapping GLuint texture_help = SOIL_load_OGL_texture ( "Texture/helpme.jpg", SOIL_LOAD_RGBA, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y ); if (texture_help == 0) printf("ERRROR::can't load the help descrition!!! Error type:'%s'\n", SOIL_last_result()); glBindTexture(GL_TEXTURE_2D, texture_help); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_LINEAR); //Create the rectangle and the texture on it. glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex3f(-2.4f, -1.8f, -5.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-2.4f,1.8f, -5.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(2.5f, 1.8f, -5.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(2.5f, -1.8f, -5.0f); glEnd(); glDisable(GL_TEXTURE_2D); glutSwapBuffers(); } //Callback function that resize the window of the help window void handleHelpResize(int w , int h) { glViewport(0, 0, (GLsizei)w, (GLsizei)h); glMatrixMode(GL_PROJECTION), glLoadIdentity(); gluPerspective(30.0, 1.0, 1.5, 20.0); glMatrixMode(GL_MODELVIEW); } //An handler for the Camera move void handleSpecialKey(int key, int x, int y) { glLoadIdentity(); if (mode == GHOST) { switch (key) { case GLUT_KEY_UP: //move forward ghost.move(FORWARD); break; case GLUT_KEY_DOWN: //move reverse ghost.move(BACKWARD); break; case GLUT_KEY_LEFT: //move left ghost.move(LEFT); break; case GLUT_KEY_RIGHT: //move right ghost.move(RIGHT); break; case GLUT_KEY_HOME: //move up ghost.move(UP); break; case GLUT_KEY_END: //move down ghost.move(DOWN); break; } } else if (mode==LIGHT) { switch (key) { case GLUT_KEY_UP: //move forward lgt.move(FORWARD); break; case GLUT_KEY_DOWN: //move reverse lgt.move(BACKWARD); break; case GLUT_KEY_LEFT: //move left lgt.move(LEFT); break; case GLUT_KEY_RIGHT: //move right lgt.move(RIGHT); break; case GLUT_KEY_HOME: //move up lgt.move(UP); break; case GLUT_KEY_END: //move down lgt.move(DOWN); break; } } switch (key) { case GLUT_KEY_F1: glutSetWindow(win2); glutShowWindow(); glutSetWindow(win1); display(); break; } display(); } //Keyboard control void keyDown(unsigned char key, int x, int y) { switch (key) { case ' ': mode = (ControlMode)((mode + 1) % 3); display(); break; case 27: //ESC //PostQuitMessage(0); break; case 'w': rbt.move_forward(); break; case 's': rbt.move_backward(); break; case 'a': rbt.move_a_side(-2); break; case 'd': rbt.move_a_side(2); break; /*robot Arm control*/ case 't': rbt.rotateShoulder(5); break; case 'g': rbt.rotateShoulder(-5); break; case 'y': rbt.rotateElbow(5); break; case 'h': rbt.rotateElbow(-5); break; case 'u': rbt.rotateWrist(5); break; case 'j': rbt.rotateWrist(-5); break; //control the angle opening of the robot pilers case 'v': rbt.rotateWristAngle(5); break; case 'b': rbt.rotateWristAngle(-5); break; /*^^^robot Body orientations control^^^^^^*/ case 'e': //rotate right rbt.rotate_body(5); display(); break; case 'q': //roate left rbt.rotate_body(-5); display(); break; // Robot head control: case 'r': //rotate up rbt.rotateHeadUPDOWN(-5); display(); break; case 'f': //rotate up rbt.rotateHeadUPDOWN(5); break; case 'z': rbt.rotateHeadToTheSIDES(-5); break; case 'x': rbt.rotateHeadToTheSIDES(5); break; //Ambient Light Control case '1': //lgt.setlightAmbientColor(0, 0.1); lgt.setSpotlightAmbientColor(0, 0.1); // 0 = RED , + 0.1 amount break; case '2': lgt.setSpotlightAmbientColor(0, -0.1);// 0 = RED , - 0.1 amount break; case '3': lgt.setSpotlightAmbientColor(1, 0.1); // 0 = GREEN, + 0.1 amount break; case '4': lgt.setSpotlightAmbientColor(1, -0.1); // 0 = GREEN, - 0.1 amount break; case '5': lgt.setSpotlightAmbientColor(2, 0.1); // 0 = BLUE, + 0.1 amount break; case '6': lgt.setSpotlightAmbientColor(2, -0.1); // 0 = BLUE, - 0.1 amount break; } display(); } //Handle the menu clicked button void menu(int value) { switch (value) { //int win2;//decleartaion on window2 case 1: //adjust the ambient light mod printf("Adjust ambient colors amount of the colors Red, Green and Blue:\nThe amount must be in range [0,1]:\n---For example 0.9(R value) 0.3(G value) 0.1(B value) for orange color.\n"); //printf("Current value are:Red= %f Blue %f Green %f \n", (float)LightAmbientGlobal[0], (float)LightAmbientGlobal[1], (float)LightAmbientGlobal[2]); float r, g, b; scanf_s("%f%f%f", &r, &g, &b); lgt.setAmbientColor(r, g, b); break; case 2: //show the help window glutSetWindow(win2); glutShowWindow(); break; case 3: // quit exit(0); break; } } //create a menu button options void createMenu(void) { // Create a submenu, this has to be done first. int leftclick = glutCreateMenu(menu); //the handler of this mouse is function:menu // Add sub menu entry glutAddMenuEntry("adjust ambient light", 1); glutAddMenuEntry("help", 2); glutAddMenuEntry("quit", 3); // Let the menu respond on the right mouse button glutAttachMenu(GLUT_RIGHT_BUTTON); } //Callback function when mouuse clicked //it's raise a flag for the camera movement to start void mouseClickFunc(int button, int state, int newMousePosX, int newMousePosY) { if (button == GLUT_LEFT_BUTTON) { lastx = newMousePosX; lastx = newMousePosY; MouseLeftClicked = true; glutSetCursor(GLUT_CURSOR_NONE); if (state == GLUT_UP) { glutSetCursor(GLUT_CURSOR_RIGHT_ARROW); } } else { MouseLeftClicked = false; lastx = newMousePosX; lastx = newMousePosY; } } //Callback function when mouse move //if it's got a move+clicked event, so we need to change //the orientation of our look void mouseMotion(int newMousePosX, int newMousePosY) { if (MouseLeftClicked == true) { static double CurrentRotationAboutX = 0.0; if ((newMousePosX == lastx) && (newMousePosY == lasty)) return; float deltaX = (newMousePosX - lastx) / -15.0f; //divide by a const that control the sensitivity float deltaY = (newMousePosY - lasty) / -15.0f; //constrain the deltas of mouse movement if (abs(deltaX) >= 1) { deltaX = deltaX / (abs(deltaX)); //boud it between [-1,1] } if (abs(deltaY) >= 1) { deltaY = deltaY / (abs(deltaY)); //boud it between [-1,1] } switch (mode) { case GHOST: ghost.changeViewDirection(deltaX, deltaY); break; case ROBOT: break; case LIGHT: lgt.changeViewDirection(deltaX, deltaY); break; default: break; } lastx = newMousePosX; //save the new mouse coordinate lasty = newMousePosY; display(); } } //Timer callback function //intent for the roof rotation void timer(int n) { w1.roofRotational+=5; glutSetWindow(win1); glutTimerFunc(60, timer, 1); display(); } //Init values void init_values() { glEnable(GL_DEPTH_TEST); //opengl value for the depth test glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //another values mode = GHOST; //initial mode start from the GHOST. } //main function - start point of the program int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(width, height); win1 = glutCreateWindow("Robot inside 'Escher' room"); //register to callback functions: glutReshapeFunc(reshape); glutKeyboardFunc(keyDown); glutSpecialFunc(handleSpecialKey); glutMotionFunc(mouseMotion); glutMouseFunc(mouseClickFunc); glutDisplayFunc(display); glutTimerFunc(20,timer, 1); createMenu(); //right click menu w1.LoadGLTextures(); //need to be called after the window created win2 = glutCreateWindow("Help window"); //glutSetWindow(win2); glutDisplayFunc(displayHelp); glutReshapeFunc(reshape); glutHideWindow(); glutSetWindow(win1); display(); glutMainLoop(); return 0; } <file_sep>#pragma once #include "Vec_3d.h" #include <gl/glut.h> #include "DataModel.h" #ifndef Light_h #define Light_h //class that contain: 1 spotlight and 1 ambient light //both can be configure class Lights { public: Lights(void); //constructor - will build the light source. void lightAmbientOff(); void lightAmbientOn(); //control the color of the lights sources. void setSpotlightAmbientColor(int color, float amount); void setAmbientColor(float red, float green, float blue); //control the position void setLightpotPosition(Vec3d position); void move(Direction dir); void RotateAroundQuaternion(double Angle, double x, double y, double z); void changeViewDirection(float deltaX, float deltaY); void draw(); void look(); public: bool ambientLight; // 1= on, 0 =off private: Vec3d pos; Vec3d viewDirection; // the view vector is actually summation of (Position +viewDirection) Vec3d up; Vec3d right;//it's actually the cross between :view and up vector //light0 position values: //int lightPosX, lightPosY, lightPosZ, lightDirX, lightDirY, lightDirZ, lightVol; }; #endif <file_sep>#pragma once #include "Vec_3d.h" #include "DataModel.h" #include <GL/glut.h> class Camera { public: Camera(void); ~Camera(void); void setValues(Vec3d newPos, Vec3d newView, Vec3d newUp); //Transformation void move(Direction dir); //change view funcitons: void changeViewDirection(float deltaX, float deltaY); void rotatebyMouse(Vec3d oldPosition, Vec3d newPosition); void RotateAroundQuaternion(double Angle, double x, double y, double z); void look(); public: Vec3d viewDirection; // the view vector is actually summation of (Position +viewDirection) Vec3d right; //it's actually the cross between :view and up vector. Vec3d up; Vec3d pos; //helpful functions //GLfloat angleX, angleY, angleZ; private: //double rotAngle; //float mouseSensetivity = 5; //toRemove };
2b703dc1e5020bb408b2a6e57cc5b80edf98ae1a
[ "C", "C++" ]
13
C++
infiBoy/EshcerRoom
c846bed8425a822daa600bccd52762e63a5a1e9a
d32af21435a87b741fcdefadd41c3077ced68400
refs/heads/master
<repo_name>mathsyouth/the-practice-of-programming-solutions<file_sep>/Chapter1/exercise1-5.md The values returned by `read(&val)` and `read(&ch)` depend on the order in which the arguments of `insert()` function are evaluated. <file_sep>/README.md # The Practice of Programming Solutions Provide high quality solutions to the exercises in "The Practice of Programming" by <NAME> Pike, also referred to as "tpop". ## Table of Contents * [Chapter 1. Style](#chapter-1-style) ## Chapter 1. Style * Exercise 1-2. Improve this function: ```c ? int smaller(char *s, char *t) { ? if (strcmp(s, t) < 1) ? return 1; ? else ? return 0; ? } ``` [solution](Chapter1/exercise1-2.c) * Exercise 1-4. Improve each of these fragments: ```c ? if ( !(c == 'y' || c == 'Y') ) ? return; ? length = (length < BUFSIZE) ? length : BUFSIZE; ? flag = flag ? 0 : 1; ? quote = (*line == '"') ? 1: 0; ? if (val & 1) ? bit = 1; ? else ? bit = 0; ``` [solution](Chapter1/exercise1-4.c) * Exercise 1-5. What is wrong with this excerpt? ```c ? int read(int *ip) { ? scanf("%d", ip); ? return *ip; ? } ? insert(&graph[vert], read(&val), read(&ch)); ``` [solution](Chapter1/exercise1-5.md) * Exercise 1-6. List all the different outputs this could produce with various orders of evaluation: ```c ? n = 1; ? printf("%d, %d\n", n++, n++); ``` Try it on as many compilers as you can, to see what happens in practice. [solution](exercise1-6.md) <file_sep>/Chapter1/exercise1-6.md Put the following code ```c #include <stdio.h> int main(void) { int n = 1; printf("%d %d\n", n++, n++); } ``` into the `test.c` file. On macOS, if ```shell clang test.c && ./a.out ``` is run, the output is ``` test.c:6:24: warning: multiple unsequenced modifications to 'n' [-Wunsequenced] printf("%d %d\n", n++, n++); ^ ~~ 1 warning generated. 1 2 ``` <file_sep>/Chapter1/exercise1-4.c if (c != 'y' && c != 'Y') return; if (length > BUFSIZE) length = BUFSIZE; flag = !flag; isquote = (*line == '"') ? 1 : 0; bit = val & 1; <file_sep>/Chapter1/exercise1-2.c int issmaller(char *cs, char *ct) { if (strcmp(cs, ct) < 0) return 1; else return 0; }
6f0d6d7e2bcb72c4b9de94963f934b1101612f58
[ "Markdown", "C" ]
5
Markdown
mathsyouth/the-practice-of-programming-solutions
8ecc8025596a6665e13f2be865199383cc5ca1f4
35c2413a2c989f883cc43e1c89683a2e5bde221e
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use App\DetalleIngreso; use App\Http\Requests\IngresoFormRequest; use App\Ingreso; use Illuminate\Http\Request; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Input; class IngresoController extends Controller { public function __construct() { } public function index(Request $request) { if ($request) { //trim — Elimina espacio en blanco (u otro tipo de caracteres) del inicio y el final de la cadena $query = trim($request->get('searchText')); // buscar al inicio o al final con % $ingresos = DB::table('ingreso as i') ->join('persona as p','i.idproveedor','=','p.idpersona') ->join('detalle_ingreso as di','i.idingreso', '=', 'di.idingreso') ->select('i.idingreso','i.fecha_hora','p.nombre','i.tipo_comprobante','i.serie_comprobante','i.num_comprobante','i.impuesto','i.estado', DB::raw('sum(di.cantidad*precio_compra) as total')) ->where('i.num_comprobante', 'LIKE', '%'.$query.'%') ->orderBy('i.idingreso', 'desc') ->groupBy('i.idingreso','i.fecha_hora','p.nombre','i.tipo_comprobante','i.serie_comprobante','i.num_comprobante','i.impuesto','i.estado') ->paginate(7); //buscar por el nombre o por el codigo del articulo //agrupa los elementos repetidos en un solo elemento //dd($ingresos); return view('compras.ingreso.index', compact('ingresos', 'query')); } } public function create() { $personas = DB::table('persona')->where('tipo_persona', '=', 'Proveedor')->get(); $articulos = DB::table('articulo as art') ->select(DB::raw('CONCAT(art.codigo, " ", art.nombre) AS articulo'), 'art.idarticulo') ->where('art.estado', '=', 'Activo') ->get(); return view('compras.ingreso.create', compact('personas', 'articulos')); } public function store(IngresoFormRequest $request) { //con el capturador de excepciones nos aseguramos ingresar //los ingresos y detalle ingresos try{ DB::beginTransaction(); $ingreso = new Ingreso(); $ingreso->idproveedor = $request->get('idproveedor'); $ingreso->tipo_comprobante = $request->get('tipo_comprobante'); $ingreso->serie_comprobante = $request->get('serie_comprobante'); $ingreso->num_comprobante = $request->get('num_comprobante'); $mytime = Carbon::now('America/Lima'); $ingreso->fecha_hora = $mytime->toDateTimeString(); $ingreso->impuesto = '18'; $ingreso->estado = 'A'; $ingreso->save(); $idarticulo = $request->get('idarticulo'); //recibo un array de idarticulos $cantidad = $request->get('cantidad'); $precio_compra = $request->get('precio_compra'); $precio_venta = $request->get('precio_venta'); $cont = 0; while($cont < count($idarticulo)){ $detalle = new DetalleIngreso(); $detalle->idingreso = $ingreso->idingreso; //almacena el idingreso autogenerado al insertar in ingreso $detalle->idarticulo = $idarticulo[$cont]; $detalle->cantidad = $cantidad[$cont]; $detalle->precio_compra = $precio_compra[$cont]; $detalle->precio_venta = $precio_venta[$cont]; $detalle->save(); $cont = $cont + 1; } DB::commit(); }catch(\Exception $e){ DB::rollback(); //anulo la transaccion si hay un error } return redirect('compras/ingreso'); } public function show($id) { $ingreso = DB::table('ingreso as i') ->join('persona as p','i.idproveedor','=','p.idpersona') ->join('detalle_ingreso as di','i.idingreso', '=', 'di.idingreso') ->select('i.idingreso','i.fecha_hora','p.nombre','i.tipo_comprobante','i.serie_comprobante','i.num_comprobante','i.impuesto','i.estado', DB::raw('sum(di.cantidad*precio_compra) as total')) ->where('i.idingreso', '=', $id) ->first(); $detalles = DB::table('detalle_ingreso as d') ->join('articulo as a','d.idarticulo','=','a.idarticulo') ->select('a.nombre as articulo','d.cantidad','d.precio_compra','d.precio_venta') ->where('d.idingreso', '=', $id) ->get(); return view('compras.ingreso.show', compact('ingreso', 'detalles')); } public function destroy($id) { $ingreso = Ingreso::findOrFail($id); $ingreso->estado = 'C'; $ingreso->update(); return redirect('compras/ingreso'); } } <file_sep><?php namespace App\Http\Controllers; use App\Categoria; use App\Http\Requests\CategoriaFormRequest; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class CategoriaController extends Controller { public function __construct() { } public function index(Request $request) { if ($request) { //trim — Elimina espacio en blanco (u otro tipo de caracteres) del inicio y el final de la cadena $query = trim($request->get('searchText')); // buscar al inicio o al final con % $categorias = DB::table('categoria')->where('nombre', 'LIKE', '%'.$query.'%') ->where('condicion','=','1') ->orderBy('idcategoria', 'desc') ->paginate(7); return view('almacen.categoria.index', compact('categorias', 'query')); } } public function create() { return view('almacen.categoria.create'); } public function store(CategoriaFormRequest $request) { $categoria = new Categoria; $categoria->nombre = $request->get('nombre'); $categoria->descripcion = $request->get('descripcion'); $categoria->condicion = '1'; $categoria->save(); return redirect('almacen/categoria'); } public function show($id) { $categoria = Categoria::findOrFail($id); return view('almacen.categoria.show', compact('categoria')); } public function edit($id) { $categoria = Categoria::findOrFail($id); return view('almacen.categoria.edit', compact('categoria')); } public function update(CategoriaFormRequest $request, $id) { $categoria = Categoria::find($id); //dd($categoria); $categoria->nombre = $request->get('nombre'); //dd($categoria->nombre); $categoria->descripcion = $request->get('descripcion'); //$categoria->condicion = '1'; $categoria->save(); //dd($categoria->update()); return redirect('almacen/categoria'); } public function destroy($id) { $categoria = Categoria::findOrFail($id); $categoria->condicion = '0'; $categoria->update(); return redirect('almacen/categoria'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Articulo extends Model { protected $table = 'articulo'; protected $primaryKey = 'idarticulo'; public $timestamps = false; //no registre fechas protected $fillable = [ 'idcategoria', 'codigo', 'nombre', 'stock', 'descripcion', 'imagen', 'estado' ]; }
3381eb7abd9553c52ee694204712f434d28587e5
[ "PHP" ]
3
PHP
devsantoshm/app-ventas
2f064249a6ef4c219bd36a43abdc9872aad89367
d11c03961c292d4561ad3f6d70e32be85427f58e
refs/heads/master
<repo_name>jhonvc/Realm<file_sep>/app/src/main/java/com/example/tecsup/myapplication/MainActivity.java package com.example.tecsup.myapplication; import android.content.Context; import android.content.SharedPreferences; import android.preference.Preference; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import io.realm.Realm; import io.realm.RealmChangeListener; import io.realm.RealmResults; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Dog d= new Dog("Firulais",10); Realm realm=Realm.getDefaultInstance(); realm.beginTransaction(); realm.copyToRealm(d); Person p=realm.createObject(Person.class,2); p.name ="<NAME>"; p.dogs.add(d); realm.commitTransaction(); RealmResults<Dog>cachorros=realm.where(Dog.class).findAll(); Toast.makeText(this,cachorros.size()+"",Toast.LENGTH_SHORT).show(); cachorros.addChangeListener(new RealmChangeListener<RealmResults<Dog>>() { @Override public void onChange(RealmResults<Dog> dogs) { } }); // realm.beginTransaction(); // cachorros.get(0).deleteFromRealm(); // realm.commitTransaction(); } }
93e084d3cfbfbe57a125fc6550d27f6a4ee2b8e6
[ "Java" ]
1
Java
jhonvc/Realm
8d6e78b57e128bf9c2efd818ef0c919dc8fcee68
503b30cab433565b5a051009e35e1b056831ecab
refs/heads/main
<repo_name>wzj207/https-github.com-wzj207-Identifying-Habitat-Elements-from-Bird-Images-Using-Deep-Learning<file_sep>/train55.py from __future__ import print_function, division import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import numpy as np import pandas as pd import torchvision from torchvision import datasets, models, transforms import matplotlib.pyplot as plt import time import os, random import copy import argparse from utils import get_models from PIL import Image from torch import topk def fix_seed(seed=518): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministric = True def get_dataset(resize, mode, data_dir): if mode == 'train': data_transforms = transforms.Compose([ transforms.Resize((int(1.25*resize), int(1.25*resize))), transforms.RandomRotation(20), transforms.ColorJitter(brightness=0.5), transforms.RandomHorizontalFlip(), transforms.CenterCrop((resize, resize)), transforms.ToTensor(), transforms.Normalize(mean, std) ]) else: data_transforms = transforms.Compose([ transforms.Resize((resize, resize)), transforms.ToTensor(), transforms.Normalize(mean, std) ]) data_set = datasets.ImageFolder(root=data_dir, transform=data_transforms) return data_set def train_model(model, criterion, optimizer, scheduler, num_epochs=50): history_save_path = os.path.join(history_folder, 'history-full-{}-{}-{}.txt'.format(run_num, model_name, SEED)) history = open(history_save_path, 'w+') since = time.time() print('Since Time:', since, file=history) best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 best_epoch = 0 for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs - 1)) print('-' * 10) # Each epoch has a training and validation phase for phase in ['train', 'val']: if phase == 'train': model.train() # Set model to training mode else: model.eval() # Set model to evaluate mode running_loss = 0.0 running_corrects = 0 # Iterate over data. for inputs, labels in dataloaders[phase]: inputs = inputs.to(device) labels = labels.to(device) # zero the parameter gradients optimizer.zero_grad() # forward # track history if only in train with torch.set_grad_enabled(phase == 'train'): outputs = model(inputs) _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels) # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() # statistics running_loss += loss.item() * inputs.size(0) running_corrects += torch.sum(preds == labels.data) if phase == 'train': scheduler.step() epoch_loss = running_loss / dataset_sizes[phase] epoch_acc = running_corrects.double() / dataset_sizes[phase] print('{} Epoch: {} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch, epoch_loss, epoch_acc)) print('{},Epoch,{},Loss,{:.4f},Acc,{:.4f}'.format(phase, epoch, epoch_loss, epoch_acc), file=history) # deep copy the model if phase == 'val' and epoch_acc > best_acc: best_epoch = epoch best_acc = epoch_acc best_model_wts = copy.deepcopy(model.state_dict()) #torch.save(model,best_models_folder + model_name + '-{}_{}_{}'.format(SEED, run_num, size)+'.mdl') #print('model - {} saved'.format(model_name)) print() time_elapsed = time.time() - since print('End Time:', time.time(), file=history) print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60)) print('Training complete in: {:.0f}m_{:.0f}s'.format(time_elapsed // 60, time_elapsed % 60), file=history) print('Best val Acc: {:4f}'.format(best_acc)) print('Best val Acc: {:4f}'.format(best_acc), file=history) print('Best Training Epoch: {}'.format(best_epoch)) print('Best Training Epoch: {}'.format(best_epoch), file=history) history.close() # load best model weights model.load_state_dict(best_model_wts) #torch.save(model, best_models_folder + model_name + '-{}_{}_{}'.format(SEED, run_num, size)+'.pkl') return model parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('run_number', type=int, help='Run number') parser.add_argument('model_name', choices=get_models.use_models.keys(), help='model name') parser.add_argument('-sd','--seed', type=int, default=111, help='random seed') parser.add_argument('-eps','--epochs', type=int, default=25, help='loop number') args = parser.parse_args() run_num = args.run_number SEED = args.seed fix_seed(seed=SEED) size = '5_5' root = f'./images/' device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(device) mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] #model_name = 'resnet50' #model_name = 'resnet34' model_name = args.model_name epochs = args.epochs best_models_folder = 'Best_models/5_5/' #best_models_folder = 'best_models/three_fifths/' #best_models_folder = 'best_models/two_fifths/' #best_models_folder = 'best_models/one_fifth/' history_folder = 'History/5_5/' #history_folder = 'history/three_fifths/' #history_folder = 'history/two_fifths/' #history_folder = 'history/one_fifth/' os.makedirs(best_models_folder, exist_ok=True) os.makedirs(history_folder, exist_ok=True) # resize = 224 if model_name.lower() != 'inception_v3' else 299 #data_dir = os.path.join(root, mode) #data_set = get_dataset(resize, mode, data_dir) image_datasets = {x: get_dataset(resize, x, os.path.join(root, x)) for x in ['train', 'val', 'test']} print(image_datasets.keys()) for k in image_datasets.keys(): print(k,':',len(image_datasets[k])) class_to_idx = image_datasets['train'].class_to_idx idx_to_class = {class_to_idx[k]:k for k in class_to_idx.keys()} print(class_to_idx) print(idx_to_class) dataloaders = { 'train': torch.utils.data.DataLoader(image_datasets['train'], batch_size=32, shuffle=True), 'val': torch.utils.data.DataLoader(image_datasets['val'], batch_size=32), 'test': torch.utils.data.DataLoader(image_datasets['test'], batch_size=1) } dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']} #print(dataset_sizes['train']) #print(mode) #print('# of {} set:'.format(mode), len(data_set)) #print('class_to_idx:', data_set.class_to_idx) model_ft = get_models.use_models[model_name] model_ft = model_ft.to(device) criterion = nn.CrossEntropyLoss() # Observe that all parameters are being optimized optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9) #optimizer_ft = optim.Adam(model_ft.parameters(), lr=0.001, momentum=0.9) # Decay LR by a factor of 0.1 every 7 epochs exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1) model = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=epochs) #torch.save(model.state_dict(),best_models_folder + model_name + '-{}_{}'.format(SEED, run_num)+'.mdl') test_folder = './images/test/' test_imgs = [] wrongs = [] wrongs_columns = ('image_path', 'predicted_label', 'true_label') test_result = [] test_result_columns = ['id', 'image_path', 'predicted_label', 'true_label', 'probs'] model.eval() with torch.no_grad(): for cat in os.listdir(test_folder): sub_folder = os.path.join(test_folder, cat) for i,fn in enumerate(os.listdir(sub_folder)): img_path = os.path.join(sub_folder, fn) test_imgs.append(img_path) # print(i, img_path) im = Image.open(img_path).convert("RGB") tf = transforms.Compose([ transforms.Resize((resize, resize)), transforms.ToTensor(), transforms.Normalize(mean, std) ]) tsr = tf(im).unsqueeze(0).to(device) outputs = model(tsr) probs = nn.functional.softmax(outputs, dim=1).squeeze().detach().cpu().numpy() p = idx_to_class[int(probs.argmax())] t = img_path.split('/')[-2] wrong = (p!=t) if wrong: wrongs.append([img_path, p, t]) #print(i, img_path, p, t, probs) # print(i, img_path, p, t) test_result.append([i, img_path, p, t, probs]) res_df = pd.DataFrame(test_result, columns=test_result_columns) res_df.to_csv(f'record_of_test/{model_name}_{run_num}_{size}_{SEED}_res.csv') wrongs_df = pd.DataFrame(data=wrongs, columns=wrongs_columns) wrongs_df.to_csv(f'record_of_test/{model_name}_{run_num}_{size}_{SEED}_wrongs.csv') f = open('test_accs.csv', 'a') print('# of Test Images:', len(test_imgs), file=f) print('# of Wrongs:', len(wrongs), file=f) print('Test Acc:', (1-len(wrongs)/len(test_imgs))) print(f'{model_name}, {size}, {SEED}, {run_num},', (1-len(wrongs)/len(test_imgs)), file=f) f.close() print('=======================================================================') print(wrongs_df) <file_sep>/get_fraction_images.py import pandas as pd import shutil import os categories = os.listdir('images/train') for cat in categories: os.makedirs(os.path.join('images_fraction_1_5', 'train', cat), exist_ok=True) os.makedirs(os.path.join('images_fraction_2_5', 'train', cat), exist_ok=True) os.makedirs(os.path.join('images_fraction_3_5', 'train', cat), exist_ok=True) os.makedirs(os.path.join('images_fraction_4_5', 'train', cat), exist_ok=True) df1 = pd.read_csv('./data_list/fraction_train_15.csv') df2 = pd.read_csv('./data_list/fraction_train_25.csv') df3 = pd.read_csv('./data_list/fraction_train_35.csv') df4 = pd.read_csv('./data_list/fraction_train_45.csv') df1.columns = ['id', 'image_path'] src_imgs1 = list(df1['image_path']) src_imgs1 = [img.strip() for img in src_imgs1] df2.columns = ['id', 'image_path'] src_imgs2 = list(df2['image_path']) src_imgs2 = [img.strip() for img in src_imgs2] df3.columns = ['id', 'image_path'] src_imgs3 = list(df3['image_path']) src_imgs3 = [img.strip() for img in src_imgs3] df4.columns = ['id', 'image_path'] src_imgs4 = list(df4['image_path']) src_imgs4 = [img.strip() for img in src_imgs4] for img in src_imgs1: shutil.copy(src=img, dst=img.replace('images_bkp', 'images_fraction_1_5')) for img in src_imgs2: shutil.copy(src=img, dst=img.replace('images_bkp', 'images_fraction_2_5')) for img in src_imgs3: shutil.copy(src=img, dst=img.replace('images_bkp', 'images_fraction_3_5')) for img in src_imgs4: shutil.copy(src=img, dst=img.replace('images_bkp', 'images_fraction_4_5')) <file_sep>/get_datasets.py import os from PIL import Image root = './images' imgs = [] pngs = [] for folder in os.listdir(root): sub_folder = os.path.join(root, folder) for cat in os.listdir(sub_folder): cat_folder = os.path.join(sub_folder, cat) for img in os.listdir(cat_folder): if img.endswith('png'): pngs.append(os.path.join(cat_folder, img)) else: imgs.append(os.path.join(cat_folder, img)) print(len(imgs)) print(pngs) for img_fn in imgs+pngs: try: img = Image.open(img_fn) #exif_data = img._getexif() except ValueError as err: print(err) print("Error on image: ", img_fn) <file_sep>/cp_images2fractions.py import os import shutil import pandas as pd import numpy as np data_list_path = './data_list' csvfiles = os.listdir(data_list_path) for i,fn in enumerate(csvfiles): if fn.startswith('fraction') and '0.50' in fn: fn_abs = os.path.join(data_list_path, fn) new_fn = fn_abs.replace('0.50', '15') print(i, fn_abs) os.rename(fn_abs, new_fn) print(i, new_fn)
02199c16806329b472b84b322afdfc175d4021d0
[ "Python" ]
4
Python
wzj207/https-github.com-wzj207-Identifying-Habitat-Elements-from-Bird-Images-Using-Deep-Learning
2c3f317c0dbc122724166aeb0209dc1f77714b2e
a72cf11c3087a8eb7b6e82104d7e03e0ade177e5
refs/heads/master
<file_sep>from django.contrib import admin from features.models import Info # Register your models here. class InfoAdmin(admin.ModelAdmin): list_display = ["names", "contact","interests"] admin.site.register(Info, InfoAdmin)<file_sep>from django.db import models # Create your models here. class Info(models.Model): names = models.CharField(max_length=256) contact = models.IntegerField(primary_key=True) interests = models.CharField(max_length=256)
ba82d4bbe763be9798ec962478fec4fb381f919e
[ "Python" ]
2
Python
shiwangi16/python-and-django-
15261bcac9207de3c4766993c38614c5b65cc9e1
40db614dff43fd561536fbac8d59d6a63a4f4083
refs/heads/master
<repo_name>Theosakamg-Sandbox/demojenkins3<file_sep>/README.md # Demo-Jenkins projet de demo CI/CD avec tests. <file_sep>/src/main/java/com/epsi/mycal/Application.java package com.epsi.mycal; /** * Application launcher. * @version 1.0 * */ public class Application { /** * Entry-point of application. * @param args List of arguments when application is launch. */ public static void main(String[] args) { ConsoleUi ui = new ConsoleUi(); ui.process(); } }
aeeb867dcf73b489c9cce56cf57b9807d5437b73
[ "Markdown", "Java" ]
2
Markdown
Theosakamg-Sandbox/demojenkins3
b4262d2245b9745a2db3f8951864c3cfdee92f76
76ff7ceab05d898c95c2e66fc28ebba41af2d87e
refs/heads/master
<repo_name>amyljb/MVC_3<file_sep>/main.lua require "CiderDebugger"; require "util" local contentDataTable = {} local currentPage = 1 local totalNumPages local view = display.newGroup() local function clearView() display.remove(view) -- cleanup view = display.newGroup() end local function getImagesTable() local pageIndex = "page" .. currentPage local pageTable = contentDataTable[pageIndex] return pageTable.images end local function updateView() clearView() local imagesTable = getImagesTable() for i = 1, #imagesTable do local image = display.newImage(imagesTable[i].url, imagesTable[i].xPos, imagesTable[i].yPos) view:insert(image) --transition.to(image, { time=2000, y=100 } ) end end function swipedEventFinished(phase) return phase == "ended" end function swipedRight(event) return event.x > (display.contentWidth / 2) end --function moveToNextPage() --if currentPage >= 1 and currentPage < totalNumPages then --currentPage = currentPage + 1 --end --end --LIMIT TO SPECIFIC PAGES function moveToNextPage() if currentPage >= 1 and currentPage < totalNumPages then currentPage = currentPage + 1 --transition.to(currentPage+1, { time=2000, y=100 } ) --local myImage = currentPage --transition.to(currentPage, { time=2000, y=100 } ) end end function moveToPreviousPage() if currentPage > 1 and currentPage <= totalNumPages then currentPage = currentPage - 1 end end function touchHandler(event) if swipedEventFinished(event.phase) then if swipedRight(event) then --ADD TRANSITION HERE moveToNextPage() else moveToPreviousPage() end updateView() end return true end function init() contentDataTable = loadTable("pageData.json") totalNumPages = length(contentDataTable) updateView() end Runtime:addEventListener("touch", touchHandler) init()
c5fc8e7da120b2c6bac6d8187ea639c296b07e9d
[ "Lua" ]
1
Lua
amyljb/MVC_3
e39e8c30d223036c0c1f4b9fd040783ca2da2899
5084b0e37c54909c236b336d790fefc512b91c8b
refs/heads/master
<file_sep>package com.sku.hoony.calculatorapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Button btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9; Button btnPlus, btnMinus, btnMultiplication, btnDivision, btnCalculation; Button btnPoint, btnReset, btnMark, btnPercent; TextView tv; int num; int result=0; boolean isClickPlus=false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* btn0 = (Button)findViewById(R.id.btn0); btn1 = (Button)findViewById(R.id.btn1); btn2 = (Button)findViewById(R.id.btn2); btn3 = (Button)findViewById(R.id.btn3); btn4 = (Button)findViewById(R.id.btn4); btn5 = (Button)findViewById(R.id.btn5); btn6 = (Button)findViewById(R.id.btn6); btn7 = (Button)findViewById(R.id.btn7); btn8 = (Button)findViewById(R.id.btn8); btn9 = (Button)findViewById(R.id.btn9); btnPlus = (Button)findViewById(R.id.btnPlus); btnMinus = (Button)findViewById(R.id.btnMinus); btnMultiplication = (Button)findViewById(R.id.btnMultiplication); btnDivision = (Button)findViewById(R.id.btnDivision); btnReset = (Button)findViewById(R.id.btnReset); btnMark = (Button)findViewById(R.id.btnMark); btnPercent = (Button)findViewById(R.id.btnPercent); btnPoint = (Button)findViewById(R.id.btnPoint); btnCalculation = (Button)findViewById(R.id.btnCalculation); tv = (TextView)findViewById(R.id.tv);*/ findViewById(R.id.btn0).setOnClickListener(bClickListener); } Button.OnClickListener bClickListener = new View.OnClickListener(){ public void onClick(View v){ TextView tv = (TextView)findViewById(R.id.tv); switch (v.getId()){ case R.id.btn0: if (isClickPlus==true) { result= num+=0; isClickPlus=false; tv.setText(result); } tv.setText("0"); num=0; break; case R.id.btn1: if(isClickPlus==true){ result = num+=1; isClickPlus=false; tv.setText(result); } tv.setText("1"); num=1; break; case R.id.btn2: tv.setText("2"); num=2; break; case R.id.btn3: tv.setText("3"); break; case R.id.btn4: tv.setText("4"); break; case R.id.btn5: tv.setText("5"); break; case R.id.btn6: tv.setText("6"); break; case R.id.btn7: tv.setText("7"); break; case R.id.btn8: tv.setText("8"); break; case R.id.btn9: tv.setText("9"); break; } } }; } <file_sep>package com.example.tkdlx_000.myapplication; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; public class starActivity extends AppCompatActivity { EditText str; TextView result; int number; StringBuilder sb = new StringBuilder(); /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } public void custom(View v) { switch (v.getId()) { case R.id.back: { Toast.makeText(starActivity.this, "돌아가기", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getApplicationContext(), MainActivity.class); finish(); break; } case R.id.input: { sb.delete(0,sb.length()); Toast.makeText(starActivity.this, "calculation...", Toast.LENGTH_SHORT).show(); str = (EditText) findViewById(R.id.number); result = (TextView) findViewById(R.id.star); number = Integer.parseInt(str.getText().toString()); for (int i = number; i > 0; i--) { for (int j = 0; j < i; j++) { sb.append("*"); } sb.append("\n"); } result.setText(sb.toString()); } break; } } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "star Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.example.tkdlx_000.myapplication/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "star Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.example.tkdlx_000.myapplication/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); } }<file_sep>김상국 해야 할 일 네비게이션 분석 및 사용법 익히기<file_sep>package com_0311_01.example.user.myapplication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class IntentTestActivity extends AppCompatActivity { TextView txtName,txtNumber,txtPw,txtMajor; String s; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intent_test); txtName=(TextView)findViewById(R.id.txtName); txtNumber=(TextView)findViewById(R.id.txtNumber); txtPw=(TextView)findViewById(R.id.txtPw); txtMajor=(TextView)findViewById(R.id.txtMajor); Intent intent=getIntent(); txtName.setText(intent.getStringExtra("Name")); txtNumber.setText(intent.getStringExtra("Number")); txtPw.setText(intent.getStringExtra("PassWord")); txtMajor.setText(intent.getStringExtra("Major")); s=intent.getStringExtra("Name")+intent.getStringExtra("Number")+intent.getStringExtra("PassWord"); } public void Go(View v){ switch (v.getId()){ case R.id.btnGo: Intent outIntent=new Intent(getApplicationContext(),MemberActivity.class); outIntent.putExtra("Total",s); setResult(RESULT_OK, outIntent); finish(); } } } <file_sep>package kr.ac.sungkyul.delasy; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class test1 extends AppCompatActivity { EditText edtTxt; Button btnRun; TextView txtView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test1); btnRun = (Button)findViewById(R.id.btn); edtTxt = (EditText)findViewById(R.id.edTxt1); txtView = (TextView)findViewById(R.id.txtV); btnRun.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { txtView.setText(""); String a=edtTxt.getText().toString(); int input = Integer.parseInt(a); for (int i=0;i<=input;i++){ for (int j=0;j<i;j++){ // txtView.setText(txtView.getText()); txtView.setText(txtView.getText().toString()+"*"); } txtView.setText(txtView.getText().toString()+"\n"); } } }); } } <file_sep># GravityStudy 그래비티 동아리에서 스터디로 안드로이드를 이끌면서 만든 깃 레포지트리. 다음에 사용하게 될 누군가를 위해 깃 사용 법이라도 적어두자.. 1. git init : 깃 레포지토리 초기화 2. git clone "git address" : 깃허브 저장소를 현재 로컬로 클론해오는 행위 3. git add [filename] : 커밋을 하기 위해 현재 반영된 파일을 스토리지에 올리는 행위. ex) git add * : 모든 변경 파일을 스토리지에 올리기 4. git commit -m "message" : message라는 커밋 메시지를 입력하여 커밋 5. git push : 변경된 커밋 내용을 원격 저장소 (깃허브)에 반영하는 행위 6. git fetch : 원격 저장소(깃허브)에서 바뀐 내용이 있는지를 확인하는 행위 7. git pull : 원격 저장소(깃허브)에 바뀐 내용을 내 저장소(로컬)로 가져오는 행위 <file_sep>package com.gravity.sk392.navigationtest.notice; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.lang.String; import com.gravity.sk392.navigationtest.R; import java.util.ArrayList; /** * Created by SK392 on 2016-01-14. */ public class ListViewAdapter extends BaseAdapter { private Context mcontext = null; public ArrayList<ItemData> mListData = new ArrayList<ItemData>(); public ListViewAdapter(Context context) { super(); this.mcontext = context; } private class ViewHolder{ public TextView noticetitle; public TextView noticedate; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null){ LayoutInflater myInflater = (LayoutInflater)mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = myInflater.inflate(R.layout.item,parent,false); holder = new ViewHolder(); holder.noticetitle = (TextView)convertView.findViewById(R.id.noticetitle); holder.noticedate = (TextView)convertView.findViewById(R.id.noticedate); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } ItemData mitem = mListData.get(position); holder.noticetitle.setText(mitem.getNotice_title()); holder.noticedate.setText(mitem.getNotice_date()); return convertView ; } @Override public int getCount() { return mListData.size(); } @Override public ItemData getItem(int position) { return mListData.get(position); } @Override public long getItemId(int position) { return position; } public void addItem(String mtitle, String mdate){ ItemData additem = null; additem = new ItemData(); additem.noticetitle = mtitle; additem.noticedate = mdate; mListData.add(additem); dataChange(); } public void remove(int position){ mListData.remove(position); dataChange(); } /* 정렬하는 기능. */ public void sort(){ } public void dataChange(){ notifyDataSetChanged(); } } <file_sep>package kr.ac.sungkyul.delasy; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class DelayActivity extends AppCompatActivity { Button btnWrite; Button btnDelete; EditText edtText; TextView textView; Button btnRun; Button btnCal; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_delay); btnWrite = (Button)findViewById(R.id.btn1); btnDelete = (Button)findViewById(R.id.btn2); edtText = (EditText)findViewById(R.id.edTxt); textView = (TextView)findViewById(R.id.txtV); btnRun=(Button)findViewById(R.id.btnRun); btnCal=(Button)findViewById(R.id.btnCal); btnCal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(), CalActivity.class)); } }); btnWrite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String a = edtText.getText().toString(); textView.setText(a); } }); btnDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String b=" "; textView.setText(b); } }); btnRun.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent it=new Intent(DelayActivity.this,test1.class); startActivity(it); } }); Button btnRun3 = (Button)findViewById(R.id.btnRun3); btnRun3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(),CalActivity.class)); } }); } } <file_sep>package com_0311_01.example.user.myapplication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; public class MemberActivity extends AppCompatActivity { EditText edtName,edtNumber,edtPw; RadioGroup group; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_member); edtName=(EditText)findViewById(R.id.edtName); edtNumber=(EditText)findViewById(R.id.edtNumber); edtPw=(EditText)findViewById(R.id.edtPw); group=(RadioGroup)findViewById(R.id.group); } public void register(View v){ switch (v.getId()){ case R.id.btnResister: RadioButton select=(RadioButton)findViewById(group.getCheckedRadioButtonId()); Intent intent=new Intent(getApplicationContext(),IntentTestActivity.class); intent.putExtra("Name",edtName.getText().toString()); intent.putExtra("Number",edtNumber.getText().toString()); intent.putExtra("PassWord",edtPw.getText().toString()); intent.putExtra("Major",select.getText().toString()); startActivityForResult(intent,0); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode==RESULT_OK){ String name=data.getStringExtra("Total"); Toast.makeText(getApplicationContext(),"a"+name, Toast.LENGTH_SHORT).show(); } } } <file_sep>package com.gravity.sk392.navigationtest; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBarDrawerToggle; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.gravity.sk392.navigationtest.notice.NoticeActivity; public class MainActivity extends ActionBarActivity { ActionBarDrawerToggle drawerToggle; String[] navListSetup= {"Notice", "FriendsList"}; ViewPager pager; Button firstbtn, secondbtn, thirdbtn; int position; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pager = (ViewPager)findViewById(R.id.pager); //ViewPager에 설정할 Adapter 객체 생성 //ListView에서 사용하는 Adapter와 같은 역할. //다만. ViewPager로 스크롤 될 수 있도록 되어 있다는 것이 다름 //PagerAdapter를 상속받은 CustomAdapter 객체 생성 //CustomAdapter에게 LayoutInflater 객체 전달 ViewpagerAdapter pageradapter= new ViewpagerAdapter(getLayoutInflater(),this); //ViewPager에 Adapter 설정 pager.setAdapter(pageradapter); firstbtn = (Button)findViewById(R.id.pager_first_btn); secondbtn = (Button)findViewById(R.id.pager_second_btn); thirdbtn = (Button)findViewById(R.id.pager_third_btn); firstbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { position=pager.getCurrentItem();//현재 보여지는 아이템의 위치를 리턴 //현재 위치(position)에서 -1 을 해서 이전 position으로 변경 //이전 Item으로 현재의 아이템 변경 설정(가장 처음이면 더이상 이동하지 않음) //첫번째 파라미터: 설정할 현재 위치 //두번째 파라미터: 변경할 때 부드럽게 이동하는가? false면 팍팍 바뀜 pager.setCurrentItem(0,true); } }); secondbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { position=pager.getCurrentItem();//현재 보여지는 아이템의 위치를 리턴 //현재 위치(position)에서 -1 을 해서 이전 position으로 변경 //이전 Item으로 현재의 아이템 변경 설정(가장 처음이면 더이상 이동하지 않음) //첫번째 파라미터: 설정할 현재 위치 //두번째 파라미터: 변경할 때 부드럽게 이동하는가? false면 팍팍 바뀜 pager.setCurrentItem(1,true); } }); thirdbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { position=pager.getCurrentItem();//현재 보여지는 아이템의 위치를 리턴 //현재 위치(position)에서 -1 을 해서 이전 position으로 변경 //이전 Item으로 현재의 아이템 변경 설정(가장 처음이면 더이상 이동하지 않음) //첫번째 파라미터: 설정할 현재 위치 //두번째 파라미터: 변경할 때 부드럽게 이동하는가? false면 팍팍 바뀜 pager.setCurrentItem(2,true); } }); getSupportActionBar().setDisplayHomeAsUpEnabled(true); DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.navigationDrawerLayout); //네비게이션 드로우어 생성. ListView listView= (ListView) findViewById(R.id.navList); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, navListSetup); listView.setAdapter(adapter); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close) { @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); } }; drawerLayout.setDrawerListener(drawerToggle); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(getApplicationContext(), "Click" + (position + 1), Toast.LENGTH_SHORT).show(); if(position ==0){ Intent intent = new Intent(); intent.setClass(MainActivity.this,NoticeActivity.class); startActivity(intent); } else if(position ==1){ } } }); } @Override protected void onPostCreate (Bundle savedInstanceState){ super.onPostCreate(savedInstanceState); drawerToggle.syncState(); } @Override public void onConfigurationChanged (Configuration newConfig){ super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected (MenuItem item){ if (drawerToggle.onOptionsItemSelected(item)) return true; return super.onOptionsItemSelected(item); } } <file_sep>방정훈 해야 할 일 계산기 만들어 보기 별찍기 만들어 보기 ----------------- Option : 우선순위 계산기 만들어 보기 ex) 10 + 20 * 30 - (45 + 15) = 550 input : 10 + 20 * 30 - (45 + 15) output : 550<file_sep>package com.sk392.kr.gravity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; public class SignupActivity extends AppCompatActivity { EditText edit_name, edit_studentnum, edit_password, edit_passcheck; RadioButton rb_devel, rb_plan, rb_design; RadioGroup rg_depart; Button btn_signup; TextView tv_ismem; String password,passcheck,name,studentnum,checkdepart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); edit_passcheck = (EditText)findViewById(R.id.edit_passcheck); edit_password = (EditText)findViewById(R.id.edit_password); edit_name = (EditText)findViewById(R.id.edit_name); edit_studentnum = (EditText)findViewById(R.id.edit_studentnum); rg_depart = (RadioGroup)findViewById(R.id.rg_depart); rb_design = (RadioButton)findViewById(R.id.rb_design); rb_devel = (RadioButton)findViewById(R.id.rb_devel); rb_plan = (RadioButton)findViewById(R.id.rb_plan); btn_signup = (Button)findViewById(R.id.btn_signup); tv_ismem = (TextView)findViewById(R.id.tv_ismem); btn_signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { studentnum = edit_studentnum.getText().toString().trim(); password = <PASSWORD>_password.getText().toString().trim(); passcheck = edit_passcheck.getText().toString().trim(); name = edit_name.getText().toString().trim(); rg_depart.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(checkedId == R.id.rb_devel){ checkdepart = "개발부서"; }else if(checkedId == R.id.rb_design){ checkdepart = "디자인부서"; }else { checkdepart = "기획부서"; } } }); if (studentnum.isEmpty() || password.isEmpty() || passcheck.isEmpty() || name.isEmpty()) { Toast.makeText(getApplicationContext(), "입력란을 확인해주세요!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "이름 = " + name +"학번 = "+ studentnum + "password = " + password + "passwordcheck = " +passcheck+" 부서 = " +checkdepart, Toast.LENGTH_SHORT).show(); } } }); tv_ismem.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Intent intent = new Intent(SignupActivity.this, LoginActivity.class); startActivity(intent); finish(); return false; } }); } } <file_sep>package com.android.tkdlx_000.basetest; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void custom(View v) { switch (v.getId()) { case R.id.button1: Toast.makeText(getApplicationContext(), "글씨먼저", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.naver.com")); startActivity(intent); break; case R.id.button2: { Intent meintent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:/119")); startActivity(meintent); break; } case R.id.button3: { Intent meintent = new Intent(Intent.ACTION_VIEW, Uri.parse("content://media/internal/images/media")); startActivity(meintent); break; } case R.id.button4: { finish(); break; } } } } <file_sep>김헌진 해야 할 일 캐나다 가서 기획이나 해보겠습니다.<file_sep>include ':app', ':IndicateLibrary' <file_sep>package sungkyul.ac.kr.gravity.activity.login; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import sungkyul.ac.kr.gravity.R; /** * Created by HunJin on 2016-03-18. */ public class SignInActivity extends AppCompatActivity { EditText edit_studentnum, edit_pass; CheckBox cb_autologin; Button btn_login; TextView tv_findpass, tv_notmem; String id, pass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signin); edit_pass = (EditText) findViewById(R.id.edit_pass); edit_studentnum = (EditText) findViewById(R.id.edit_id); cb_autologin = (CheckBox) findViewById(R.id.cb_autologin); btn_login = (Button) findViewById(R.id.btn_login); tv_findpass = (TextView) findViewById(R.id.tv_findpass); tv_notmem = (TextView) findViewById(R.id.tv_notmem); btn_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { id = edit_studentnum.getText().toString().trim(); pass = edit_pass.getText().toString().trim(); if (id.isEmpty() || pass.isEmpty()) { Toast.makeText(getApplicationContext(), "아이디 혹은 비밀번호를 입력해주세요!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "id = " + id + "password = " + pass + "checked = " + cb_autologin.isChecked(), Toast.LENGTH_SHORT).show(); } } }); tv_findpass.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Intent intent = new Intent(getApplication(), FindpassActivity.class); startActivity(intent); return false; } }); tv_notmem.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Intent intent = new Intent(getApplication(), SignUpActivity.class); startActivity(intent); finish(); return false; } }); } }
421e2d00f26c1859e41f1bd9d331bee3d4957d8a
[ "Markdown", "Java", "Text", "Gradle" ]
16
Java
KimHunJin/GravityStudy
43d6954e6effa48847db7b0b3da6c1622e4621e0
c81f14e926461ec4b8fe0234dbeb4aa8a51182b0
refs/heads/main
<file_sep><h1>Jogo da cobrinha</h1> <h2>Este projeto é parte do curso HTML Web Developer da Digital Innovation One.</h2> <h3>Então o projeto propõe a recriar o jogo da cobrinha utilizando HTML, CSS e JAVASCRIPT.</h3> <p>Aprendi a criar o jogo do zero com javascript puro e incrementei novas funcionalidade. O jogo esta com responsividade podendo abrir no celular e então criei um teclado direcional com as setas podendo jogar no celular. Foi adicionado um placar para o jogador acompanhar os pontos a cada comida da maça.</p> https://beliciobcardoso.github.io/jogo_da_cobrinha/ <img src="./img/web_1.jpg" width="400"> <img src="./img/web_2.jpg" width="400" align="center"> <img src="./img/web_3.jpg" width="400" align="center"> <img src="./img/Screenshot_1.jpg" width="150"> <img src="./img/Screenshot_2.jpg" width="150"> <img src="./img/Screenshot_3.jpg" width="150"> <img src="./img/Screenshot_4.jpg" width="150"> <img src="./img/Screenshot_5.jpg" width="150"> <img src="./img/Screenshot_6.jpg" width="150"> <img src="./img/Screenshot_7.jpg" width="150"> <img src="./img/Screenshot_8.jpg" width="150"> <file_sep>let canvas = document.getElementById("snake"); let context = canvas.getContext("2d"); let direction = "right"; let box = 16; let game; let snake = []; snake[0] = { x: 20 * box, y: 20 * box }; let apple = { x: Math.floor(Math.random() * 39 + 1) * box, y: Math.floor(Math.random() * 39 + 1) * box }; function background() { context.fillStyle = "#c3c4ff"; context.fillRect(0, 0, 40 * box, 40 * box); }; function createSnake() { for (let index = 0; index < snake.length; index++) { context.fillStyle = "black"; context.fillRect(snake[index].x, snake[index].y, box, box); } }; function createApple() { context.fillStyle = "red"; context.fillRect(apple.x, apple.y, box, box); }; function moveSnake() { if (snake[0].x > 39 * box && direction == "right") snake[0].x = 0; if (snake[0].x < 0 * box && direction == "left") snake[0].x = 39 * box; if (snake[0].y > 39 * box && direction == "down") snake[0].y = 0; if (snake[0].y < 0 * box && direction == "up") snake[0].y = 39 * box; let snakeX = snake[0].x; let snakeY = snake[0].y; if (direction == "right") snakeX += box; if (direction == "left") snakeX -= box; if (direction == "down") snakeY += box; if (direction == "up") snakeY -= box; let newHead = { x: snakeX, y: snakeY } snake.unshift(newHead); if (snakeX != apple.x || snakeY != apple.y) { snake.pop(); } else { apple.x = Math.floor(Math.random() * 39 + 1) * box; apple.y = Math.floor(Math.random() * 39 + 1) * box; } }; document.addEventListener('keydown', update); function update(event) { if (event.keyCode == 37 && direction != "right") direction = "left"; if (event.keyCode == 38 && direction != "down") direction = "up"; if (event.keyCode == 39 && direction != "left") direction = "right"; if (event.keyCode == 40 && direction != "up") direction = "down"; }; function keyboard(move) { if (move == 37 && direction != "right") direction = "left"; if (move == 38 && direction != "down") direction = "up"; if (move == 39 && direction != "left") direction = "right"; if (move == 40 && direction != "up") direction = "down"; } function modal_gameStart() { document.querySelector('.modal_gameStart').classList.toggle('active'); }; function modal_Gameover() { location.reload(true); }; function gameover() { for (let index = 1; index < snake.length; index++) { if (snake[0].x == snake[index].x && snake[0].y == snake[index].y) { clearInterval(game); document.querySelector('.modal_Gameover').classList.toggle('active'); } } }; function initGame() { background(); createSnake(); createApple(); moveSnake(); gameover(); document.getElementById("points").innerHTML = "Pontos: " + (snake.length - 1); }; function startGame() { game = setInterval(initGame, 300); modal_gameStart(); };
8a073d711ee25659a234dc5482f4aee62357f538
[ "Markdown", "JavaScript" ]
2
Markdown
beliciobcardoso/jogo_da_cobrinha
ab5c9cd90b121a669c9d1a01d6feabb60dc6f10c
d0687c98a69c20a9c5661be8c9e6bd1b7f9e24c4
refs/heads/master
<file_sep>import { Get, Post, Put, Delete, Controller, Param, Response, Request, Body, UseGuards} from '@nestjs/common'; import { QueueDBService} from './queueDB.service'; import { ApiUseTags, ApiOperation, ApiResponse, ApiImplicitQuery, ApiImplicitParam, ApiImplicitBody } from '@nestjs/swagger'; import { Database } from '../databases/entities/database.entity'; import { QueueDB } from './entities/queueDB.entity'; import { RolesGuard } from '../common/guards/roles.guard'; import { Roles } from '../common/decorators/roles.decorator'; @ApiUseTags('queueDB') @Controller('queueDB') export class QueueDBController { constructor(private queueDBService: QueueDBService){} @ApiOperation({ title: 'Obtiene todas las peticiones de base de datos' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @Roles('ADMIN') @Get('') async getAll() { return await this.queueDBService.getAll(); } @ApiOperation({ title: 'Obtiene una petición de base de datos por id' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'id', description: 'id de la petición ', required: true }) @Roles('ADMIN') @Get(':id') async getById(@Param('id') id: string) { return await this.queueDBService.getById(id); } @ApiOperation({ title: 'Crea una petición para añadir una base de datos' }) @ApiResponse({ status: 201, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @Post('') async createDatabase(@Body() database: QueueDB): Promise<void> { return await this.queueDBService.create(database); } @ApiOperation({ title: 'Borra una petición de base de datos' }) @ApiResponse({ status: 201, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'id', description: 'id de la petición ', required: true }) @Roles('ADMIN') @Delete(':id') async deleteDatabase(@Param('id') id: string) { return await this.queueDBService.delete(id); } @ApiOperation({ title: 'Modifica una petición de base de datos' }) @ApiResponse({ status: 201, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'id', description: 'id de la petición ', required: true }) @Roles('ADMIN') @Put(':id') async updateDatabase(@Param('id') id, @Body() database: QueueDB) { return await this.queueDBService.update(id, database); } } <file_sep>import { Module, MiddlewaresConsumer, RequestMethod } from '@nestjs/common'; import { UserModule} from './user/user.module'; import { MongooseModule } from '@nestjs/mongoose'; import { URL } from './db/db.config'; import { NestModule } from '@nestjs/common/interfaces'; import { AuthoritationMiddleware } from './common/middlewares/auth.middleware'; import { DataBaseModule } from './databases/database.module'; import { VizModule } from './viz/viz.module'; import { QueueDBModule } from './queueDb/queueDB.module'; import { QueueDB} from './queueDb/entities/queueDB.entity'; import { DatabaseController } from './databases/database.controller'; import { VizController } from './viz/viz.controller'; import { QueueDBController } from './queueDb/queueDB.controller'; @Module({ imports: [UserModule, DataBaseModule ,VizModule, QueueDBModule, MongooseModule.forRoot(URL)], }) export class ApplicationModule implements NestModule { configure(consumer: MiddlewaresConsumer): void { consumer.apply(AuthoritationMiddleware).forRoutes( { path: 'user/update-user/:email', method: RequestMethod.PUT }, DatabaseController, VizController, QueueDBController); } } <file_sep>import * as mongoose from 'mongoose'; let OptionsSchema = new mongoose.Schema({ nombre: String, valor: String, }, { _id: false }); export const VizSchema = mongoose.Schema({ nombre: String, url: String, img: { data: Buffer, contentType: String }, databases: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Database' }], options: [OptionsSchema] }); <file_sep>import { Get, Post, Put, Controller,Delete, Param , Response, Request, Body} from '@nestjs/common'; import { ApiUseTags, ApiOperation, ApiResponse, ApiImplicitQuery, ApiImplicitParam, ApiImplicitBody } from '@nestjs/swagger'; import { UserService} from './user.service'; import { User} from './entities/user.entity'; import { Viz } from '../viz/entities/viz.entity'; @ApiUseTags('user') @Controller('user') export class UserController { constructor(private userService: UserService){} @ApiOperation({ title: 'Obtiene todas las visualizaciones de un usuario' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'email', description: 'Email del usuario ', required: true }) @Get('viz/:email') async getViz(@Param('email') email: string) : Promise<User> { return await this.userService.getViz(email); } @ApiOperation({ title: 'Añade una vizualización al usuario con email :email' }) @ApiResponse({ status: 201, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'email', description: 'Email del usuario ', required: true }) @Post('viz/:email') async addViz(@Param('email') email :string, @Body() viz: Viz) { return await this.userService.addViz(email, viz); } @ApiOperation({ title: 'Borra una vizualización al usuario con email :email' }) @ApiResponse({ status: 201, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'email', description: 'Email del usuario ', required: true }) @ApiImplicitParam({ name: 'id', description: 'Id de la visualizacion ', required: true }) @Delete('viz/:email/:id') async deleteVizViz(@Param('email') email: string, @Param('id') id: string) { return await this.userService.deleteViz(email, id); } @ApiOperation({ title: 'Comprueba si existe un usuario con email , :email' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 404, description: 'No existe el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'email', description: 'Email del usuario ', required: true }) @Get('checkemail/:email') checkEmail(@Response() res, @Param('email') email :string) { this.userService.checkEmail(res ,email); } @ApiOperation({ title: 'Crea un usuario ' }) @ApiResponse({ status: 201, description: 'Operación correcta' }) @ApiResponse({ status: 404, description: 'No se ha podido crear el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @Post('register') register(@Response() res, @Body() user: User){ this.userService.createUser(res, user); } @ApiOperation({ title: 'Logueo de usuario ' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 404, description: 'No se ha podido crear un usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @Post('login') login( @Response() res, @Body() user:User) { this.userService.login(res, user); } @ApiOperation({ title: 'Actualizar un usuario ' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 404, description: 'No se ha podido actualizar un usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'email', description: 'Email del usuario ', required: true }) @Put('update-user/:email') updateUser(@Request() req, @Response() res, @Param('email') email : string, @Body() user:User){ this.userService.updateUser(res, req, email, user); } } <file_sep>import { ApiModelProperty } from '@nestjs/swagger'; export class Field { @ApiModelProperty({ type: String }) nombre: string; @ApiModelProperty({ type: String }) tipo: string; } export class Database { @ApiModelProperty({ type: String }) nombre: string; @ApiModelProperty({ type: String }) descripcion: string; @ApiModelProperty({ type: Field , isArray: true}) campos: Array<Field>; } <file_sep> import * as jwt from 'jwt-simple'; import * as moment from 'moment'; var secret = 'datavisualizer_esperoaprobar'; export const createToken = function (user) { var payload = { sub: user._id, name: user.name, email: user.email, role: user.role, iat: moment().unix(), exp: moment().add(30, 'days').unix } return jwt.encode(payload, secret); }<file_sep> import { Model } from 'mongoose'; import { Component } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { User } from './entities/user.entity'; import { UserSchema } from './schemas/user.schema'; import * as bcrypt from 'bcrypt-nodejs'; import * as jwt from '../common/services/jwt.service'; @Component() export class UserService { constructor(@InjectModel(UserSchema) private readonly userModel: Model<User>) { } async createUser(res, params) { var user = new this.userModel(new User); //Retrieve params if (params.password && params.name && params.email) { user.name = params.name; user.email = params.email; user.role = 'USER'; await this.userModel.findOne({ email: user.email.toLowerCase() }, (err, issetUser) => { if (err) { res.status(500).send({ message: 'Error al guardar el usuario' }); } else { if (!issetUser) { //Crypt password bcrypt.hash(params.password, null, null, (err, hash) => { user.password = <PASSWORD>; user.save((err, userStored) => { if (err) { res.status(500).send({ message: 'Error al guardar el usuario' }); } else { if (!userStored) { res.status(404).send({ message: 'No se ha registrado el usuario' }); } else { userStored = this._deletePrivateInfo(userStored); res.status(200).send({ user: userStored }); } } }) }); } else { res.status(200).send({ message: "Ya existe un usuario con ese email" }); } } }); } else { res.status(200).send({ message: "Introduzca los valores correctamente" }); } } async login(res, params) { var email = params.email; var password = params.password if (params.password && params.email) { await this.userModel.findOne({ email: email.toLowerCase() }, (err, issetUser) => { if (err) { res.status(500).send({ message: 'Error al comprobar usuario' }); } else { if (issetUser) { bcrypt.compare(password, issetUser.password, (err, check) => { if (check) { if (params.gettoken) { res.status(200).send({ token: jwt.createToken(issetUser) }); } else { issetUser = this._deletePrivateInfo(issetUser); res.status(200).send({ user: issetUser }); } } else { res.status(404).send({ message: "Contraseña incorrecta" }); } }); } else { res.status(404).send({ message: 'El usuario no existe' }); } } }); } else { res.status(200).send({ message: "Introduzca correctamente los valores" }) } } async updateUser(res, req, email, body) { var userMail = email; var update = body; if (userMail != req.user.email) { return res.status(500).send({ message: 'No tienes permiso para actualizar el usuario' }); } update.role = req.user.role; await this.userModel.findOneAndUpdate({ email: userMail.toLowerCase() }, update, { new: true }, (err, userUpdated) => { if (err) { res.status(500).send({ message: 'Error al actualizar usuario' }); } else { if (!userUpdated) { res.status(404).send({ message: 'No se ha podido actualizar el usuario' }); } else { if (update.password) { bcrypt.hash(update.password, null, null, (err, hash) => { userUpdated.password = hash; this.userModel.findByIdAndUpdate(userUpdated._id, userUpdated, { new: true }, (err, userStored) => { if (err) { res.status(500).send({ message: 'Error al actualizar el usuario' }); } else { if (!userStored) { res.status(404).send({ message: 'No se ha actualizado el usuario' }); } else { res.status(200).send({ token: jwt.createToken(userStored) }); } } }) }); } else { res.status(200).send({ token: jwt.createToken(userUpdated) }); } } } }); } async checkEmail(res, email) { var userMail = email; await this.userModel.findOne({ email: userMail.toLowerCase() }, (err, existMail) => { if (err) { res.status(404).send({ message: 'Error al obtener email' }) } else { if (existMail) { res.status(200).send({ message: existMail.email }) } else { res.status(404).send({ message: "No existe el email" }); } } }); } async getViz(email: string) { return await this.userModel.findOne({ email: email.toLowerCase() }, 'viz').populate('viz').exec(); } async addViz(email, vizId) { try { return await this.userModel.findOneAndUpdate({ email: email.toLowerCase() }, { $push: { viz: vizId } }, { new: true }); } catch (e) { throw e; } } async deleteViz(email, vizId) { try { return await this.userModel.findOneAndUpdate({ email: email.toLowerCase() }, { $pull: { viz: vizId } }, { new: true }); } catch (e) { throw e; } } private _deletePrivateInfo(user) { user.password = <PASSWORD>; user._id = undefined; return user; } }<file_sep> import { Model, Types } from 'mongoose'; import { Component, HttpStatus } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Viz, Option } from './entities/viz.entity'; import { VizSchema } from './schemas/viz.schema'; import { HttpException } from '@nestjs/common'; import { Database } from '../databases/entities/database.entity'; import * as underscore from 'underscore'; @Component() export class VizService { constructor(@InjectModel(VizSchema) private readonly vizModel: Model<Viz>, ) { } async getAll() { return await this.vizModel.find().populate('databases').exec(); } async create(viz: Viz): Promise<void> { const createViz = new this.vizModel(viz); return await createViz.save(); } async getById(id) { try { return await this.vizModel.findById(id).populate('databases').exec(); } catch (e) { throw new HttpException('Not found', HttpStatus.NOT_FOUND); } } async getByOpciones(database, opciones) { try { let arrayOpciones = []; Object.keys(opciones).forEach(function (key) { arrayOpciones.push({ nombre: key, valor: opciones[key] }); }); let result = []; await this.vizModel.find({ databases: database }, (err, vizQuery) => { vizQuery.forEach(viz => { if (JSON.stringify(viz.options) == JSON.stringify(arrayOpciones)) { result = viz; } }); }); return result; } catch (e) { console.log(e); throw new HttpException('Not found', HttpStatus.NOT_FOUND); } } async delete(id) { try { await this.vizModel.findByIdAndRemove(id); } catch (e) { throw new HttpException('Not found', HttpStatus.NOT_FOUND); } } async update(id, viz: Viz) { try { return await this.vizModel.findByIdAndUpdate(id, viz, { new: true }); } catch (e) { throw e; } } }<file_sep>export const URL = 'mongodb://juanjo:<EMAIL>@ds<EMAIL>.<EMAIL>:47180/datavisualizer';<file_sep>import { ApiModelProperty } from '@nestjs/swagger'; export class User { @ApiModelProperty({ type: String }) name: String; @ApiModelProperty({ type: String }) email: String; @ApiModelProperty({ type: String }) password: String; @ApiModelProperty({ type: String }) role: String; @ApiModelProperty({ type: String, isArray: true }) viz: String[]; }<file_sep>import { Module } from '@nestjs/common'; import { DatabaseController } from './database.controller'; import { MongooseModule} from '@nestjs/mongoose'; import {DatabaseSchema} from './schemas/database.schema'; import {DatabaseService} from './database.service'; @Module({ imports: [MongooseModule.forFeature([{ name: 'Database', schema: DatabaseSchema }])], controllers: [DatabaseController], components: [DatabaseService] }) export class DataBaseModule { } <file_sep>import { ApiModelProperty } from '@nestjs/swagger'; export class QueueDB { @ApiModelProperty({ type: String }) nombre: String; @ApiModelProperty({ type: String }) url: String; @ApiModelProperty({ type: String }) descripcion: String; }<file_sep>import { Component, HttpException, HttpStatus } from '@nestjs/common'; import { Model } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { QueueDB } from './entities/queueDB.entity'; import { QueueDBSchema } from './schemas/queueDB.schema'; import * as bcrypt from 'bcrypt-nodejs'; import * as jwt from '../common/services/jwt.service'; @Component() export class QueueDBService { constructor(@InjectModel(QueueDBSchema) private readonly queueDBModel: Model<QueueDB>) { } async getAll() { return await this.queueDBModel.find(); } async create(queueDB: QueueDB): Promise<void> { const createQueueDB = new this.queueDBModel(queueDB); return await createQueueDB.save(); } async getById(id) { try { return await this.queueDBModel.findById(id); } catch (e) { throw new HttpException('Not found', HttpStatus.NOT_FOUND); } } async getByUser(user: string) { try { return await this.queueDBModel.findOne({ usuario: user }); } catch (e) { throw new HttpException('Not found', HttpStatus.NOT_FOUND); } } async delete(id) { try { await this.queueDBModel.findByIdAndRemove(id); } catch (e) { throw new HttpException('Not found', HttpStatus.NOT_FOUND); } } async update(id, queueDB: QueueDB) { try { return await this.queueDBModel.findByIdAndUpdate(id, queueDB, { new: true }); } catch (e) { throw e; } } }<file_sep>import { Database } from "../../databases/entities/database.entity"; import { ApiModelProperty } from '@nestjs/swagger'; export class Option { @ApiModelProperty({ type: String }) nombre: string; @ApiModelProperty({ type: String }) valor: string; constructor(nombre, valor) { this.nombre = nombre; this.valor = valor; } } export class Viz { @ApiModelProperty({ type: String }) nombre: String; @ApiModelProperty({ type: String }) url: String; @ApiModelProperty({ type: String, description: "Imagen previsualización de la viz" }) img: String; @ApiModelProperty({ type: String , isArray: true}) databases: Array<String>; @ApiModelProperty({ type: Option , isArray: true }) options: Array<Option>; } <file_sep> Datavisualizer backend con [Nest](https://github.com/nestjs/nest) framework **TypeScript** <file_sep>import { Module } from '@nestjs/common'; import { VizController } from './viz.controller'; import { MongooseModule} from '@nestjs/mongoose'; import {VizSchema} from './schemas/viz.schema'; import {VizService} from './viz.service'; @Module({ imports: [MongooseModule.forFeature([{ name: 'Viz', schema: VizSchema }])], controllers: [VizController], components: [VizService], }) export class VizModule { } <file_sep>import * as mongoose from 'mongoose'; export const fieldSchema = new mongoose.Schema({ nombre: String, tipo: String, }); export const DatabaseSchema = mongoose.Schema({ nombre: String, descripcion: String, campos: [fieldSchema] }); <file_sep>import { NestFactory } from '@nestjs/core'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import { ApplicationModule } from './app.module'; import * as path from 'path'; import * as express from 'express'; async function bootstrap() { const app = await NestFactory.create(ApplicationModule); app.setGlobalPrefix('api'); app.use('/visualizer', express.static(path.join(__dirname + '/../app/'))); app.use('/visualizer*', (req: any, res: any) => { res.sendFile(path.join(__dirname + '/../app/')); }); const options = new DocumentBuilder() .setTitle('API REST DATAVISUALIZER') .setBasePath('api') .setDescription('API REST de la aplicación datavisualizer') .setVersion('1.0') .build(); const document = await SwaggerModule.createDocument(app, options); SwaggerModule.setup('/doc/api', app, document); var port = +process.env.PORT || 5000; await app.listen(port); } bootstrap(); <file_sep>import { Get, Post, Put, Delete, Controller, Param, Response, Request, Body, Query, UseGuards} from '@nestjs/common'; import { DatabaseService} from './database.service'; import { ApiUseTags, ApiOperation, ApiResponse, ApiImplicitQuery, ApiImplicitParam, ApiImplicitBody } from '@nestjs/swagger'; import { Database, Field } from './entities/database.entity'; import { RolesGuard } from '../common/guards/roles.guard'; import { Roles } from '../common/decorators/roles.decorator'; @ApiUseTags('database') @UseGuards(RolesGuard) @Controller('database') export class DatabaseController { constructor(private databaseService: DatabaseService){} @ApiOperation({ title: 'Obtiene todos las bases de datos ' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @Get('') async getAll(){ return await this.databaseService.getAll(); } @ApiOperation({ title: 'Recupera una base de datos por id ' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 404, description: 'No se ha encontrado la base de datos' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'id', description: 'Id de la base de datos ', required: true }) @Get(':id') async getById(@Param('id') id : string ) { return await this.databaseService.getById(id); } @ApiOperation({ title: 'Recupera una base de datos por su nombre ' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 404, description: 'No se ha encontrado la base de datos' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'nombre', description: 'Nombre de la base de datos ', required: true }) @Get('/nombre/:nombre') async getByName(@Param('nombre') nombre: string){ return await this.databaseService.getByName(nombre); } @ApiOperation({ title: 'Crea una base de datos' }) @ApiResponse({ status: 201, description: 'Operación correcta' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @Roles('ADMIN') @Post('') async createDatabase(@Body() database : Database): Promise<void>{ return await this.databaseService.create(database); } @ApiOperation({ title: 'Borra una base de datos por id ' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 404, description: 'No se ha encontrado la base de datos' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'id', description: 'Id de la base de datos ', required: true }) @Roles('ADMIN') @Delete(':id') async deleteDatabase(@Param('id') id: string) { return await this.databaseService.delete(id); } @ApiOperation({ title: 'Modifica una base de datos por id ' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 404, description: 'No se ha encontrado la base de datos' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'id', description: 'Id de la base de datos ', required: true }) @Roles('ADMIN') @Put(':id') async updateDatabase(@Param('id') id: string, @Body() database : Database){ return await this.databaseService.update(id, database); } @ApiOperation({ title: 'Obtiene los campos de una base de datos con id :id ' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 404, description: 'No se ha encontrado la base de datos' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'id', description: 'id de la base de datos ', required: true }) @Get('/campos/:id') async getCampos(@Param('id') id : string) { return await this.databaseService.getCampos(id); } @ApiOperation({ title: 'Añade a la base de datos con id :id un campo' }) @ApiResponse({ status: 201, description: 'Operación correcta' }) @ApiResponse({ status: 404, description: 'No se ha encontrado la base de datos' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'id', description: 'id de la base de datos ', required: true }) @Roles('ADMIN') @Post('/campos/:id') async addCampos(@Param('id') id :string, @Body('campos') campos: Field): Promise<void> { return await this.databaseService.addCampos(id, campos); } @ApiOperation({ title: 'Borra el campo de una base de datos con id :id ' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 404, description: 'No se ha encontrado la base de datos' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'id', description: 'id de la base de datos ', required: true }) @Roles('ADMIN') @Delete('/campos/:id') async removeCampo(@Param('id') id : string , @Query('campo') campo: string) { return await this.databaseService.removeCampo(id, campo); } } <file_sep>var jwt = require('jwt-simple'); var moment = require('moment'); var secret = 'datavisualizer_esperoaprobar'; import { Middleware, NestMiddleware, ExpressMiddleware } from '@nestjs/common'; @Middleware() export class AuthoritationMiddleware implements NestMiddleware { resolve(): ExpressMiddleware { return (req, res, next) => { if (!req.headers.authorization) { return res.status(403).send({ message: 'La petición no tiene la cabecera de autenticación' }); } var token = req.headers.authorization.replace(/['"']+/g, ''); try { var payload = jwt.decode(token, secret); if (payload.exp <= moment().unix()) { return res.status(401).send({ message: "El token ha expirado" }); } } catch (ex) { return res.status(404).send({ message: 'El token no es válido' }); } req.user = payload; next(); }; } }<file_sep>import * as mongoose from 'mongoose'; export const QueueDBSchema = mongoose.Schema({ nombre: String, url: String, descripcion: String, usuario: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, }); <file_sep>import { Module } from '@nestjs/common'; import { QueueDBController } from './queueDB.controller'; import { MongooseModule} from '@nestjs/mongoose'; import {QueueDBSchema} from './schemas/queueDB.schema'; import {QueueDBService} from './queueDB.service'; @Module({ imports: [MongooseModule.forFeature([{ name: 'queueDB', schema: QueueDBSchema }])], controllers: [QueueDBController], components: [QueueDBService], }) export class QueueDBModule { } <file_sep>import { Model } from 'mongoose'; import { Component, HttpException, HttpStatus } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Database } from './entities/database.entity'; import { DatabaseSchema } from './schemas/database.schema'; @Component() export class DatabaseService { constructor(@InjectModel(DatabaseSchema) private readonly databaseModel: Model<Database>) { } async getAll() { return await this.databaseModel.find(); } async create(dataBase: Database): Promise<void> { const createDataBase = new this.databaseModel(dataBase); return await createDataBase.save(); } async getById(id) { try { return await this.databaseModel.findById(id); } catch (e) { throw new HttpException('Not found', HttpStatus.NOT_FOUND); } } async getByName(name: string) { try { return await this.databaseModel.findOne({nombre : name}); } catch (e) { throw new HttpException('Not found', HttpStatus.NOT_FOUND); } } async delete(id) { try { await this.databaseModel.findByIdAndRemove(id); } catch (e) { throw new HttpException('Not found', HttpStatus.NOT_FOUND); } } async update(id, database: Database){ try { return await this.databaseModel.findByIdAndUpdate(id, database, {new :true}) ; } catch (e){ throw e; } } async getCampos(id){ let result; try { await this.databaseModel.findById(id, (err, document) =>{ result= document.campos; }); } catch (e) { throw new HttpException('Not found', HttpStatus.NOT_FOUND); } return result; } async addCampos(id, campos){ try { return await this.databaseModel.findByIdAndUpdate(id, {$push: {campos :{ $each: campos}}}, { new: true }); } catch (e) { throw e; } } async removeCampo(id, nombreCampo: string){ try { return await this.databaseModel.findByIdAndUpdate(id, { $pull: { campos:{ nombre: "unit" }} }, { new: true }); } catch (e) { throw new HttpException('Not found', HttpStatus.NOT_FOUND); } } }<file_sep>import { Get, Post, Put, Delete, Controller, Param, Response, Request, Body, Query, UseGuards } from '@nestjs/common'; import { VizService } from './viz.service'; import { ApiUseTags, ApiResponse, ApiOperation, ApiImplicitQuery, ApiImplicitParam } from '@nestjs/swagger'; import { RolesGuard } from '../common/guards/roles.guard'; import { Roles } from '../common/decorators/roles.decorator'; import { Viz } from './entities/viz.entity'; @ApiUseTags('viz') @UseGuards(RolesGuard) @Controller('viz') export class VizController { constructor(private vizService: VizService) { } @ApiOperation({ title: 'Obtiene todas las visualizaciones' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @Roles('ADMIN') @Get('') async getAll() { return await this.vizService.getAll(); } @ApiOperation({ title: 'Obtiene las visualizaciones con determinadas opciones' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitQuery({ name: 'database', description: 'Array de id de base de datos', required: true }) @ApiImplicitQuery({ name: 'opciones', description: 'Query con las distintas opciones', required: true }) @Get('opciones') async getByName(@Query('database') database, @Query() query) { delete query.database; return await this.vizService.getByOpciones(database, query); } @ApiOperation({ title: 'Obtiene una visualización por id' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'id', description: 'Id de la visualizacion ', required: true }) @Get(':id') async getById(@Param('id') id: string) { return await this.vizService.getById(id); } @ApiOperation({ title: 'Crea una visualización' }) @ApiResponse({ status: 201, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @Post('') async createViz(@Body() viz: Viz): Promise<void> { return await this.vizService.create(viz); } @ApiOperation({ title: 'Borra una visualización por id' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'id', description: 'Id de la visualizacion ', required: true }) @Roles('ADMIN') @Delete(':id') async deleteViz(@Param('id') id: string) { return await this.vizService.delete(id); } @ApiOperation({ title: 'Actualiza una visualización por id' }) @ApiResponse({ status: 200, description: 'Operación correcta' }) @ApiResponse({ status: 401, description: 'Operación no permitida para el usuario' }) @ApiResponse({ status: 500, description: 'Error en los parámetros de entrada' }) @ApiImplicitParam({ name: 'id', description: 'Id de la visualizacion ', required: true }) @Roles('ADMIN') @Put(':id') async updateViz(@Param('id') id, @Body() viz: Viz) { return this.vizService.update(id, viz); } }
39d9ca0d8fe51ce2cd3e8a59a38eb426e9c6252a
[ "Markdown", "TypeScript" ]
24
TypeScript
juanjo3200/datavisualizer-backend-nestjs
6bf5b09928041626d303a6f0019c65b4bf0c9173
edcf2eb9cbe207a39f60a8f808834be02ae4425d
refs/heads/master
<file_sep>import React from "react"; class Newcomponent extends React.Component{ render(){ return <h1>I am a new class called Button.</h1> } } export default Newcomponent;<file_sep>import React from 'react' const students =[ { name:'kingsley', age: 50, hobbies:['singing', 'dancing'] }, { name:'wole', age: 28, hobbies:'eating' }, { name:'omotola', age: 42, hobbies:'playing' }, { name:'david', age: 22, hobbies:'running' }, { name:'tola', age: 34, hobbies:'coding' }, ]; function mapArray(student){ const nameValue = student.map((value)=>{ return value.name; }) const ageValue = student.map((value)=>{ return value.age; }) const hobbiesValue = student.map((value)=>{ return value.hobbies; }) for(let i = 0; i < student.length; i++) { console.log(`Name: ${nameValue[i]} Age: ${ageValue[i]} Hobbies: ${hobbiesValue[i]} `); } } class Dailychallenge1 extends React.Component{ render(){ return <div> {mapArray(students)} </div> } } export default Dailychallenge1;
21a48d47237ed1ed701a5ea59339ccfd01cbd878
[ "JavaScript" ]
2
JavaScript
Mbbluestalker/levelup-react
3e10bec4a8048e633538f2026d62f73b9a7cfcc2
876097c71f7bf26bb043d6a2c035ac7c923cc338
refs/heads/master
<file_sep>/* * string_reverse-2.c * Reverses a null terminated string * This version doesn't use string.h */ #include <stdio.h> void reverse(char* str); int main(int argc, char** argv) { char str[] = "Edward"; reverse(str); printf("%s\n", str); } void reverse(char* str) { char* end = str; char tmp; if (str) { while (*end) end++; end--; while (str < end) { tmp = *str; *str++ = *end; *end-- = tmp; } } } <file_sep># Palindrome ## Problem Return true if a given word is a palindrome<br> If you use the flag white, ignore spaces ## Solution ### Python Compare the string to the reversed string ## C ## Comments I wouldn't reccomend the C solution in an interview. I made that mistake <file_sep># FizzBuzz ## Problem Here ## Solution There <file_sep>#include <stdio.h> #include <string.h> int main(int argc, char** argv) { if (argc < 2) { printf("usage: %s <word>\n", argv[0]); return 1; } unsigned int len = strlen(argv[1]); char a; unsigned int i; for (i = 0; i < len / 2; i++) { a = argv[1][i]; argv[1][i] = argv[1][len - 1 - i]; argv[1][len - 1 - i ] = a; } printf("%s\n", argv[1]); return 0; } <file_sep># interview-questions Collection of interview questions and code solutions <file_sep># Unique Characters ## Problem Here ## Solution Nor There <file_sep># String Reverse ## Problem Given a string `a` of length `n`, return a string `b` that is the reverse of `a` ## Solution Swap letters <file_sep>#!/usr/bin/env python def isPalindrome(word, white=0): if white != 0: word = word.replace(" ", "") return word == word[::-1] def main(): word = "o tto" if isPalindrome(word, 1): print "PALINDROME!" else: print "nah" if __name__ == "__main__": main() <file_sep># 100 Lockers ## Problem Given 100 lockers and 100 students ## Solution There <file_sep>#include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { if (argc < 2) { printf("usage: %s <limit>\n", argv[0]); return 1; } unsigned int i, limit = atoi(argv[1]); for (i = 1; i <= limit; i++) { if (i % 5 == 0 && i % 3 == 0) printf("FizzBuzz\n"); else if (i % 3 == 0) printf("Fizz\n"); else if (i % 5 == 0) printf("Buzz\n"); } return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { if (argc < 2) { printf("usage: %s <limit>\n", argv[0]); return 1; } unsigned int i, n, limit = atoi(argv[1]); for (i = 1, n = i * i; n <= limit; i++) n += (2 * i) + 1; n -= (2 * --i) + 1; printf("%d: %d\n", i, n); return 0; }
e9e8b67685860ea2bd9ec61d16fccf11688fdf93
[ "Markdown", "C", "Python" ]
11
C
ed-flanagan/interview-questions
1731e442e7e7c98003b380fbc617f082722a72dc
1b36812e597839f890cb4c72f2967cdc3bd6bb21
refs/heads/master
<repo_name>applephagna/thepinrealestate<file_sep>/app/Models/Operator.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Operator extends Model { protected $table = 'phone_operators'; } <file_sep>/app/Http/Controllers/Admin/PropertyController.php <?php namespace App\Http\Controllers\Admin; use App\Models\User; use App\Traits\UploadScope; use Illuminate\Http\Request; use Spatie\Permission\Models\Role; use App\Http\Controllers\Controller; use App\Models\Property; class PropertyController extends Controller { protected $folder_path; protected $folder_name = 'user/profile'; use UploadScope; public function __construct() { $this->middleware(['auth', 'isAdmin']); //isAdmin middleware lets only users with a //specific permission permission to access these resources $this->folder_path = public_path().DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.$this->folder_name.DIRECTORY_SEPARATOR; } public function index() { //Get all properties and pass it to the view $data['properties'] = Property::with(['category','parent','province','district','commune'])->get(); return view('admin.properties.index',$data); } public function create() { //Get all roles and pass it to the view $data = []; $data['roles'] = Role::get(); return view('admin.properties.create',compact('data')); } public function store(AddValidation $request) { if ($request->hasFile('photo')){ $image_name = $this->uploadImages($request, 'photo'); }else{ $image_name = ""; } $user = User::create(['name_en' => $request->name, 'email' => $request->email, 'password' => $<PASSWORD>, 'phone' => $request->phone, 'address' => $request->address, 'photo' => $image_name ]); $roles = $request['roles']; //Retrieving the roles field //Checking if a role was selected if (isset($roles)) { foreach ($roles as $role) { $role_r = Role::where('id', '=', $role)->firstOrFail(); $user->assignRole($role_r); //Assigning role to user } } //Redirect to the users.index view and display message return redirect()->route('admin.users.index') ->with( 'flash_message', 'User successfully added.' ); } public function show($id) { $user = User::findOrFail($id); return view('admin.properties.show', compact('user')); } public function edit($id) { $data = []; if(auth()->user()->id == 1){ if (!$data['row'] = User::find($id)){ return $this->invalidRequest(); } }else{ if (!$data['row'] = User::where('id','<>','1')->find($id)){ return $this->invalidRequest(); } } $data['roles'] = Role::all(); $data['active_roles'] = $data['row']->roles()->pluck('id', 'id')->toArray(); return view('admin.properties.edit', compact('data')); //pass user and roles data to view } public function update(EditValidation $request, $id) { $user = User::findOrFail($id); //Get role specified by id if ($request->hasFile('photo')) { $image_name = $this->uploadImages($request, 'photo'); // remove old image from folder if (file_exists($this->folder_path.$user->photo)) @unlink($this->folder_path.$user->photo); } else { $image_name = $user->photo; } $newPassword = $request->get('password'); if(empty($newPassword)){ $user->update(['name_en' => $request->firstname, 'email' => $request->email, 'phone' => $request->phone, 'address' => $request->address, 'photo' => $image_name ]); }else{ $user->update(['name_en' => $request->firstname, 'email' => $request->email, 'password' => $<PASSWORD>, 'phone' => $request->phone, 'address' => $request->address, 'photo' => $image_name ]); } $roles = $request['roles']; //Retreive all roles if (isset($roles)) { $user->roles()->sync($roles); //If one or more role is selected associate user to roles } else { $user->roles()->detach(); //If no role is selected remove exisiting role associated to a user } return redirect()->route('admin.properties.index') ->with( 'flash_message', 'User successfully edited.' ); } public function destroy($id) { //Find a user with a given id and delete $user = User::findOrFail($id); $user->delete(); return redirect()->route('admin.properties.index') ->with( 'flash_message', 'User successfully deleted.' ); } protected function invalidRequest($message = 'Invalid request!!') { } } <file_sep>/app/Http/Controllers/Admin/ProductController.php <?php namespace App\Http\Controllers\Admin; use App\Models\Product; // use App\Models\ImageGallery; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Intervention\Image\Facades\Image; class ProductController extends Controller { function __construct() { $this->middleware('permission:product-list|product-create|product-edit|product-delete', ['only' => ['index','show']]); $this->middleware('permission:product-create', ['only' => ['create','store']]); $this->middleware('permission:product-edit', ['only' => ['edit','update']]); $this->middleware('permission:product-delete', ['only' => ['destroy']]); } public function index() { $products = Product::latest()->paginate(5); return view('admin.products.index',compact('products')) ->with('i', (request()->input('page', 1) - 1) * 5); } public function create() { return view('admin.products.create'); } public function store(Request $request) { $this->validate($request, [ 'name' => 'required', 'detail' => 'required', ]); if ($request->hasFile('image')) { $image = $request->file('image'); $image_name = uniqid() . '-' . time() . '.' . $image->getClientOriginalExtension(); $destinationPath = public_path('uploads/thumbnail/product'); if (!\file_exists($destinationPath)) { mkdir($destinationPath, 0777, true); } // reisize image before upload $resize_image = Image::make($image->getRealPath()); $resize_image->resize(150, 150, function ($constraint) { $constraint->aspectRatio(); })->save($destinationPath . '/' . $image_name); // upload original image $destinationPath = public_path('uploads/product'); $image->move($destinationPath, $image_name); } else { $image_name = null; } if (isset($request->status)) { $status = true; } else { $status = false; } Product::create([ 'name' => $request->name, 'detail' => $request->detail, 'status' => $status, 'image' => $image_name, ]); return redirect()->route('admin.products.index') ->with('success','Product created successfully.'); } public function show(Product $product) { return view('admin.products.show',compact('product')); } public function edit(Product $product) { return view('admin.products.edit',compact('product')); } public function update(Request $request, Product $product) { $this->validate($request, [ 'name' => 'required', 'detail' => 'required', ]); $old_image = $product->image; $thumbnailPath = public_path('uploads/thumbnail/product'); $destinationPath = public_path('uploads/product'); // return $destinationPath.'/'.$old_image; if ($request->hasFile('image')) { if (!is_null($product->image) && File::exists($thumbnailPath . '/' . $product->image)) { File::delete($thumbnailPath . '/' . $product->image); } if (!is_null($product->image) && File::exists($destinationPath . '/' . $product->image)) { File::delete($destinationPath . '/' . $product->image); } $image = $request->file('image'); $image_name = uniqid() . '-' . time() . '.' . $image->getClientOriginalExtension(); // reisize image before upload if (!\file_exists($thumbnailPath)) { mkdir($thumbnailPath, 0777, true); } $resize_image = Image::make($image->getRealPath()); $resize_image->resize(150, 150, function ($constraint) { $constraint->aspectRatio(); })->save($thumbnailPath . '/' . $image_name); // upload original image $image->move($destinationPath, $image_name); } else { $image_name = $old_image; } if (isset($request->status)) { $status = true; } else { $status = false; } $product->update([ 'name' => $request->name, 'detail' => $request->detail, 'status' => $status, 'image' => $image_name, ]); return redirect()->route('admin.products.index') ->with('success','Product updated successfully'); } public function destroy(Product $product) { $thumbnailPath = public_path('uploads/thumbnail/product'); $destinationPath = public_path('uploads/product'); if (!is_null($product->image) && File::exists($thumbnailPath . '/' . $product->image)) { File::delete($thumbnailPath . '/' . $product->image); } if (!is_null($product->image) && File::exists($destinationPath . '/' . $product->image)) { File::delete($destinationPath . '/' . $product->image); } $product->delete(); return redirect()->route('admin.products.index') ->with('success','Product deleted successfully'); } public function dropzone() { $product = Product::pluck('name','id'); return view('products.image_gallery',compact('product')); } // public function dropzoneStore(Request $request) // { // // $this->validate($request, [ // // 'file' => 'required', // // 'file.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048', // // ]); // $image = $request->file('file'); // $imageName = $image->getClientOriginalName(); // $product_group = str_slug($request->product_group); // $uploadpath = public_path() . '\\uploads\\dropzone\\' . $product_group . '\\'; // $image->move($uploadpath, $imageName); // // $image_name = rand() . '.' . $file->getClientOriginalExtension(); // $image_gallery = new ImageGallery(); // $image_gallery->product_id = $request->product_id; // $image_gallery->product_group = str_slug($request->product_group); // $image_gallery->gallery_image = $imageName; // $image_gallery->save(); // return response()->json(['success'=>$imageName]); // } // public function dropzonedelete(Request $request) // { // $filename = $request->get('filename'); // $delete_image = ImageGallery::where('gallery_image', $filename)->first(); // $product_group = $delete_image->product_group; // $delete_image->delete(); // $uploadpath = public_path() . '\\uploads\\dropzone\\' . $product_group . '\\'; // $path = $uploadpath . $filename; // if (file_exists($path)) { // unlink($path); // } // return $filename; // } // public function gallery_list() // { // return view('products.gallery_list'); // } // public static function imageGalleryUpload($filename,$ObjModel, $path = null,$product_id,$fieldID) // { // if(request()->hasFile($filename)){ // $dir = 'uploads/' . $path .'/'; // foreach (request()->$filename as $file) { // $filename = rand(). '.' . $file->getClientOriginalExtension(); // $ObjModel = new $ObjModel; // $ObjModel->$fieldID = $product_id; // $ObjModel->gallery_image = $filename; // if($ObjModel->save()){ // $file->move($dir,$filename); // } // } // } // } } <file_sep>/app/Http/Controllers/Admin/ReportController.php <?php namespace App\Http\Controllers\Admin; use PDF; use App\Models\User; use App\Models\Category; use App\Models\Property; use App\Models\Province; use Illuminate\Http\Request; use App\Exports\FilterExport; use App\Exports\PropertyExport; use App\Http\Controllers\Controller; use Maatwebsite\Excel\Facades\Excel; class ReportController extends Controller { public function agent(Request $request) { $query= User::role(['Agent','Member']); // for search only if($request->has('filter')){ if($request->input('from_date')){ $query->whereBetween('created_at',array($request->from_date, $request->to_date)); } $data['users'] = $query->get(); // for export to excel } elseif($request->has('excel_export')){ if($request->input('from_date')){ $query->whereBetween('created_at',array($request->from_date, $request->to_date)); } $data['users'] = $query->get(); return Excel::download(new FilterExport($request->from_date, $request->to_date), 'Users-reports.xlsx'); // for export to pdf } elseif($request->has('pdf_export')){ if($request->input('from_date')){ $query->whereBetween('created_at',array($request->from_date, $request->to_date)); } $data['users'] = $query->get(); // return view('admin.reports.export.pdf_export',$data); $pdf = PDF::loadView('admin.reports.export.pdf_export',$data)->setPaper('a4', 'landscape'); return $pdf->download('pdf_export.pdf'); // for firstime loading } else { $data['users'] = $query->get(); } return view('admin.reports.agent.index',$data); } public function property(Request $request) { /* $subtype = Property::with('parent') ->where('category_id',5) ->whereHas('parent',function($query){ $query->whereHas('subtype',function($query){ $query->where('type_id',1); }); }) ->toSql(); dd ($subtype); */ if($request->input('sortby')){ $data['sortby'] = $request->input('sortby'); } else { $data['sortby']=''; } if($request->input('from_date')){ $data['from_date'] = $request->input('from_date'); } else { $data['from_date']=''; } if($request->input('to_date')){ $data['to_date'] = $request->input('to_date'); } else { $data['to_date']=''; } if($request->input('location')){ $data['location'] = $request->input('location'); } else { $data['location']=''; } if($request->input('type')){ $data['type'] = $request->input('type'); } else { $data['type']=''; } if($request->input('purpose')){ $data['purpose'] = $request->input('purpose'); } else { $data['purpose']=''; } $data['rpt_categories'] = Category::where('parent_id',0)->published()->get(); $data['rpt_cattype'] = Category::where('parent_id',5)->published()->get(); $data['rpt_provinces'] = Province::get(); if($request->has('filter')){ $data['properties'] = Property::PropertyReport($request)->get(); } if($request->has('excel_export')){ $data['properties'] = Property::PropertyReport($request)->get(); return Excel::download(new PropertyExport($request), 'Users-reports.xlsx'); } if($request->has('pdf_export')){ $data['properties'] = Property::PropertyReport($request)->get(); // return view('admin.reports.export.property_pdf',$data); $pdf = PDF::loadView('admin.reports.export.property_pdf',$data)->setPaper('a4', 'landscape'); return $pdf->download('pdf_export.pdf'); } return view('admin.reports.property.index',$data); } public function print_entry($placa, $datefecha, $datehora, $tipo) { try { // fill you own connector $connector = new WindowPrintConnector('EPSON20'); // Start the priter $printer = new Printer($connector); // System Var $printer->selectPrntMode(Printer::MODE_DOUBLE_WIDTH); $printer->selectJustification(Printer::JUSTIFY_CENTER); $system_name = $this->db->get_where('setting',array('type'=>'system_name'))->row()->description; $duemo_name =$this->db->get_where('setting',array('type'=>'nombre_demo'))->row()->description; $nit = $this->db->get_where('setting',array('type'=>'nit'))->row()->description; $direction =$this->db->get_where('setting',array('type'=>'address'))->row()->description; $telefono = $this->db->get_where('setting',array('type'=>'phone'))->row()->description; $politicas =$this->db->get_where('setting',array('type'=>'politicas'))->row()->description; $printer->setTextSize(2,2); $printer->text($system_name. "\n"); $printer->feed(); $printer->selectPrintMode(); $printer->text($duemo_name); $printer->text("NIT: ".$nit."\n"); $printer->text("DIR: ".$direction. "\n"); $printer->text("TELEFONO- ".$telefono."\n"); $printer->feed(); // Title of Receipt $printer->setEmphasis(true); $printer->text("INGRESO \n"); $printer->text("---------------------------------------------------\n"); $printer->setTextSize(4,3); $printer->text("Placa ".$placa."\n"); $printer->selectPrintMode(); $printer->text("---------------------------------------------------\n"); $printer->setEmphasis(false); $printer->selectPrintMode(); $printer->text("Fecha Entrada " .$datefecha."\n"); $printer->text("Hora Entrada " .$datehora."\n"); $this->db->select('tipo'); $this->db->from('tipo'); $this->db->where('idtipo',$tipo); $printer->text(); $printer->feed(); $printer->feed(); $printer->feed(); $printer->feed(); } catch (\Throwable $th) { //throw $th; } } } <file_sep>/app/Http/Controllers/Agent/DashboardController.php <?php namespace App\Http\Controllers\Agent; use App\Models\User; use App\Models\Commune; use App\Models\Category; use App\Models\District; use App\Models\Property; use App\Models\Province; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Brian2694\Toastr\Facades\Toastr; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Intervention\Image\Facades\Image; class DashboardController extends Controller { public function index(Request $request) { // $created_at = Property::findOrFail(2)->created_at; // $to = \Carbon\Carbon::createFromFormat('Y-m-d H:s:i', now()); // $from = \Carbon\Carbon::createFromFormat('Y-m-d H:s:i', $created_at); // $diff_in_days = $to->diffInDays($from); // print_r($diff_in_days); // Output: 1 if($request->location){ $data['location'] = $request->location; } else { $data['location'] = ''; } if($request->category){ $data['category'] = $request->category; } else { $data['category'] = ''; } if($request->sort){ $data['sort'] = $request->sort; } else { $data['sort'] = ''; } $data['categories'] = Category::where(['parent_id'=>0])->published()->get(); $data['user'] = User::where('id',Auth::user()->id)->first(); $data['provinces'] = Province::pluck('name_en','id'); $data['properties'] = Property::FilterInProfile($request)->get(); $data['count_properties'] = Property::where('user_id',$data['user']->id) ->expired() ->count(); $data['premium'] = Property::where('user_id',$data['user']->id) ->expired() ->premium() ->get(); $data['count_premium'] = Property::where('user_id',$data['user']->id) ->expired() ->premium() ->count(); $data['expired_property'] = Property::where('user_id',$data['user']->id) ->countexpired() ->get(); $data['count_expired_property'] = Property::where('user_id',$data['user']->id) ->countexpired() ->count(); $data['category_by_user'] = Property::where('user_id',Auth::user()->id) ->groupBy('category_id') ->get(); $data['subcategory_by_user']=Property::where('user_id',Auth::user()->id) ->groupBy('parent_id') ->get(); // return $data['subcategory_by_user']; return view('agent.dashboard',$data); } public function profile(Request $request) { return view('agent.profile'); } public function editProfile() { $data['user'] = User::findOrFail(auth()->id()); $data['categories'] = Category::where(['parent_id'=>0])->published()->get(); $data['provinces'] = Province::pluck('name_en','id'); $data['districts'] =District::where('province_id',$data['user']->province_id)->get(); $data['communes'] =Commune::where('district_id',$data['user']->district_id)->get(); // $user = User::where('id',Auth::user()->id)->first(); // return $user; return view('agent.edit_profile',$data); } public function updateProfile(Request $request,$id) { $this->validate($request, [ 'name_en' => 'required', 'name_kh' => 'required', 'phone' => 'required', 'province_id' => 'required', 'district_id' => 'required', 'commune_id' => 'required', ]); $user = User::findOrFail($id); $old_profile = $user->photo; $old_cover = $user->cover_photo; // check if profile photo is upload if($request->hasFile('profile_photo')){ $image = $request->file('profile_photo'); // $imageName = time().'.'.$request->image->extension(); $profile_image_name = uniqid().'-'.time() . '.' . $image->getClientOriginalExtension(); $destinationPath = public_path('uploads/user/profile'); if(!\file_exists($destinationPath)){ mkdir($destinationPath, 0777, true); } $profile_path = public_path('uploads/user/profile/'); if($old_profile && file_exists($profile_path.$old_profile)){ unlink( $profile_path . $old_profile); } // reisize image before upload $resize_image = Image::make($image->getRealPath()); $resize_image->resize(150, 150, function($constraint){ $constraint->aspectRatio(); })->save($destinationPath . '/' . $profile_image_name); // upload original image // $destinationPath = public_path('uploads/post'); // $image->move($destinationPath, $profile_image_name); } else { if(is_null($old_profile)){ $profile_image_name = 'user.png'; } else { $profile_image_name = $old_profile; } } // check if cover photo is upload if($request->hasFile('img_cover')){ $image = $request->file('img_cover'); $cover_image_name = uniqid().'-'.time() . '.' . $image->getClientOriginalExtension(); $destinationPath = public_path('uploads/user/cover'); if(!\file_exists($destinationPath)){ mkdir($destinationPath, 0777, true); } $cover_path = public_path('uploads/user/cover/'); if($old_cover && file_exists($cover_path.$old_cover)){ unlink( $cover_path . $old_cover); } // reisize image before upload $resize_image = Image::make($image->getRealPath()); $resize_image->resize(865, 325, function($constraint){ $constraint->aspectRatio(); })->save($destinationPath . '/' . $cover_image_name); // // upload original image // $destinationPath = public_path('uploads/post'); // $image->move($destinationPath, $cover_image_name); } else { if(is_null($old_cover)){ $cover_image_name = 'profile_cover.png'; } else { $cover_image_name = $old_cover; } } $data = array( 'firstname' => $request->firstname, 'lastname' => $request->lastname, 'firstname_kh' => $request->firstname_kh, 'lastname_kh' => $request->lastname_kh, 'phone' => $request->phone, 'phone1' => $request->phone1, 'phone2' => $request->phone2, 'province_id' => $request->province_id, 'district_id' => $request->district_id, 'commune_id' => $request->commune_id, 'photo' => $profile_image_name, 'cover_photo' => $cover_image_name, ); $user->update($data); Toastr::success('Profile Successfully Updated!','Success'); return redirect()->back(); } public function changePassword() { $categories = Category::where(['parent_id'=>0])->published()->get(); $user = User::where('id',Auth::user()->id)->first(); return view('agent.change_password',compact('user','categories')); } public function updatePassword(Request $request) { $this->validate($request,[ 'old_password' => '<PASSWORD>', 'password' => '<PASSWORD>' ]); $hashedPassword = Auth::user()->password; if(Hash::check($request->old_password,$hashedPassword)){ if(!Hash::check($request->password,$hashedPassword)){ $user = User::find(Auth::id()); $user->password = <PASSWORD>::<PASSWORD>($request->password); $user->save(); Toastr::success('Password Successfully Changed','Success'); Auth::logout(); return redirect()->route('login'); } else { Toastr::error('New Password can not the same old password','Error'); return redirect()->back(); } } else { Toastr::error('Old Password does not much','Error'); return redirect()->back(); } } public function store() { $categories = Category::where(['parent_id'=>0])->published()->get(); $user = User::where('id',Auth::user()->id)->first(); return view('agent.store_information',compact('user','categories')); } public function storeBanner() { $categories = Category::where(['parent_id'=>0])->published()->get(); $user = User::where('id',Auth::user()->id)->first(); return view('agent.store_baner',compact('user','categories')); } } <file_sep>/resources/lang/km/auth.php <?php return array ( 'failed' => 'ព័ត៌មានបញ្ជាក់អត្តសញ្ញាណទាំងនេះមិនត្រូវគ្នានឹងកំណត់ត្រារបស់យើងទេ។', 'throttle' => 'ការព្យាយាមចូលច្រើនពេក។ សូមព្យាយាមម្តងទៀតក្នុងរយៈពេល: វិនាទីវិនាទី។', ); <file_sep>/app/Http/Controllers/Admin/UserController.php <?php namespace App\Http\Controllers\Admin; use Auth; use App\Models\User; use App\Models\Agent; use App\Models\Commune; use App\Models\District; use App\Models\Province; use App\Traits\UploadScope; use Spatie\Permission\Models\Role; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Hash; use App\Http\Requests\User\AddValidation; use App\Http\Requests\User\EditValidation; class UserController extends Controller { protected $folder_path; protected $folder_name = 'user/profile'; use UploadScope; public function __construct() { $this->middleware(['auth', 'isAdmin']); //isAdmin middleware lets only users with a //specific permission permission to access these resources $this->folder_path = public_path().DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.$this->folder_name.DIRECTORY_SEPARATOR; } public function index() { // $user_referal_user_code = '998877665505'; // $user_referal_user_code1 = '91022613955'; // $user_referal_user_code2 = '81909147235'; // $user_referal_user_code3 = '58741791065'; // if($user_referal_user_code == '99887766550'){ // $level = "G1-"; // } // if ($user_referal_user_code1 == '9102261395' | $user_referal_user_code2 == '8190914723'| $user_referal_user_code3 == '5874179106'){ // $level = "G2-"; // } // return $level; // $usercount = \DB::table('agents') // ->where('referal_user_code','9988776655') // ->count(); // return $usercount; //Get all users and pass it to the view if(Auth::check()){ if(Auth::user()->hasAnyRole(['Super-admin'])){ if (!$data['users'] = User::all()){ return $this->invalidRequest(); } } else if(Auth::user()->hasAnyRole(['Administer','Agent','Member'])){ if (!$data['users'] = User::where('id','<>',1)->get()){ return $this->invalidRequest(); } } } return view('admin.users.index',$data); } public function create() { //Get all roles and pass it to the view $data['provinces'] = Province::pluck('name_en','id'); if(Auth::check()){ if(Auth::user()->hasAnyRole(['Super-admin'])){ if (!$data['roles'] = Role::all()){ return $this->invalidRequest(); } } else if(Auth::user()->hasAnyRole(['Administer','Agent','Member'])){ if (!$data['roles'] = Role::where('id','<>',1)->get()){ return $this->invalidRequest(); } } } return view('admin.users.create',$data); } public function store(AddValidation $request) { $referal_code = $request->referal_code; $ref_group = User::where('referal_code',$referal_code)->first(); $ref_user_count = Agent::where('referal_user_code',$referal_code)->count(); if($ref_group->ref_group=='OWNER'){ $ref_group_level = 'G1'; } elseif($ref_group->ref_group=='G1'){ $ref_group_level = 'G2'; } elseif($ref_group->ref_group=='G2'){ $ref_group_level = 'G3'; } elseif($ref_group->ref_group=='G3'){ $ref_group_level = 'G4'; } elseif($ref_group->ref_group=='G4'){ $ref_group_level = 'G5'; } $ref_level = $ref_group_level.'-'.'00'.($ref_user_count+1); if ($request->hasFile('photo')){ $image_name = $this->uploadImages($request, 'photo'); }else{ $image_name = ""; } $datas = [ 'name_en' => $request->name_en, 'name_kh' => $request->name_kh, 'username' => $request->username, 'referal_code' => mt_rand(1000000000,9999999999), 'ref_group' => $ref_group_level, 'ref_level' => $ref_level, 'phone' => $request->phone, 'phone1' => $request->phone1, 'phone2' => $request->phone2, 'email' => $request->email, 'address' => $request->address, 'province_id' => $request->province_id, 'district_id' => $request->district_id, 'commune_id' => $request->commune_id, 'password' => <PASSWORD>($request->password), 'photo' => $image_name ]; $user = User::create($datas); if($user){ Agent::create([ 'user_id' =>$user->id, 'referal_user_id' =>$request->referal_user_id, 'referal_user_code' =>$request->referal_user_code, 'ref_group' => $ref_group_level, 'ref_level' => $ref_level, 'name_en' =>$request->name_en, 'name_kh' =>$request->name_kh, 'job_title' =>$request->job_title, 'phone' => $request->phone, 'phone1' => $request->phone1, 'phone2' => $request->phone2, 'email' => $request->email, 'address' =>$request->address, 'photo' =>$image_name, ]); } $roles = $request['roles']; //Retrieving the roles field //Checking if a role was selected if (isset($roles)) { foreach ($roles as $role) { $role_r = Role::where('id', '=', $role)->firstOrFail(); $user->assignRole($role_r); //Assigning role to user } } //Redirect to the users.index view and display message return redirect()->route('admin.users.index') ->with( 'flash_message', 'User successfully added.' ); } public function show($id) { $user = User::findOrFail($id); return view('admin.users.show', compact('user')); } public function edit($id) { //Get all users and pass it to the view if(Auth::check()){ if(Auth::user()->hasAnyRole(['Super-admin'])){ if (!$data['row'] = User::find($id)){ return $this->invalidRequest(); } } else if(Auth::user()->hasAnyRole(['Administer','Agent','Member'])){ if (!$data['row'] = User::where('id','<>','1')->find($id)){ return $this->invalidRequest(); } } if(Auth::user()->hasAnyRole(['Super-admin'])){ if (!$data['roles'] = Role::all()){ return $this->invalidRequest(); } } else if(Auth::user()->hasAnyRole(['Administer','Agent','Member'])){ if (!$data['roles'] = Role::where('id','<>',1)->get()){ return $this->invalidRequest(); } } }; $data['provinces'] =Province::pluck('name_en','id'); $data['districts'] =District::where('province_id',$data['row']->province_id)->get(); $data['communes'] =Commune::where('district_id',$data['row']->district_id)->get(); $data['active_roles'] = $data['row']->roles()->pluck('id', 'id')->toArray(); return view('admin.users.edit',$data ); //pass user and roles data to view } public function update(EditValidation $request, $id) { $user = User::with('agent')->findOrFail($id); //Get role specified by id if ($request->hasFile('photo')) { $image_name = $this->uploadImages($request, 'photo'); // remove old image from folder if (file_exists($this->folder_path.$user->photo)){ @unlink($this->folder_path.$user->photo); } } else { $image_name = $user->photo; } $data_nopass =[ 'name_en' => $request->name_en, 'name_kh' => $request->name_kh, 'username' => $request->username, 'referal_code' => $request->referal_code, 'phone' => $request->phone, 'phone1' => $request->phone1, 'phone2' => $request->phone2, 'email' => $request->email, 'address' => $request->address, 'province_id' => $request->province_id, 'district_id' => $request->district_id, 'commune_id' => $request->commune_id, 'photo' => $image_name ]; $data_pass=[ 'name_en' => $request->name_en, 'name_kh' => $request->name_kh, 'username' => $request->username, 'referal_code' => $request->referal_code, 'phone' => $request->phone, 'phone1' => $request->phone1, 'phone2' => $request->phone2, 'email' => $request->email, 'address' => $request->address, 'province_id' => $request->province_id, 'district_id' => $request->district_id, 'commune_id' => $request->commune_id, 'password' => <PASSWORD>($request->password), 'photo' => $image_name ]; $data_agent =[ 'user_id' =>$user->id, 'referal_user_id' =>$request->referal_user_id, 'referal_user_code' =>$request->referal_user_code, 'name_en' =>$request->name_en, 'name_kh' =>$request->name_kh, 'job_title' =>$request->job_title, 'phone' => $request->phone, 'phone1' => $request->phone1, 'phone2' => $request->phone2, 'email' => $request->email, 'address' =>$request->address, 'photo' =>$image_name, ]; $newPassword = $request->get('password'); if(empty($newPassword)){ $user->update($data_nopass); } else { $user->update($data_pass); } Agent::where('user_id',$id)->update($data_agent); $roles = $request['roles']; //Retreive all roles if (isset($roles)) { $user->roles()->sync($roles); //If one or more role is selected associate user to roles } else { $user->roles()->detach(); //If no role is selected remove exisiting role associated to a user } return redirect()->route('admin.users.index') ->with( 'flash_message', 'User successfully edited.' ); } public function destroy($id) { //Find a user with a given id and delete $user = User::findOrFail($id); $user->delete(); return redirect()->route('admin.users.index') ->with( 'flash_message', 'User successfully deleted.' ); } protected function invalidRequest($message = 'Invalid request!!') { request()->session()->flash($this->message_warning, $message); return redirect()->route('users.index'); } public function getProfile() { return view('admin.users.profile'); } } <file_sep>/database/thepin.sql -- -------------------------------------------------------- -- Host: 127.0.0.1 -- Server version: 5.7.26 - MySQL Community Server (GPL) -- Server OS: Win64 -- HeidiSQL Version: 11.0.0.5919 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Dumping database structure for thepinrealestate_social_login DROP DATABASE IF EXISTS `thepinrealestate_social_login`; CREATE DATABASE IF NOT EXISTS `thepinrealestate_social_login` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `thepinrealestate_social_login`; -- Dumping structure for table thepinrealestate_social_login.admins DROP TABLE IF EXISTS `admins`; CREATE TABLE IF NOT EXISTS `admins` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `role_id` int(10) unsigned NOT NULL DEFAULT '0', `firstname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `lastname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `username` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `phone` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `email_verified_at` timestamp NULL DEFAULT NULL, `password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `admins_email_unique` (`email`), UNIQUE KEY `phone` (`phone`), UNIQUE KEY `admins_usernamme_unique` (`username`) USING BTREE ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.admins: 1 rows /*!40000 ALTER TABLE `admins` DISABLE KEYS */; INSERT INTO `admins` (`id`, `role_id`, `firstname`, `lastname`, `username`, `phone`, `email`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES (1, 1, 'Administrator', 'Administrator', '<PASSWORD>', '0128<PASSWORD>', '<EMAIL>', '2020-06-10 17:52:56', '$2y$10$GJnXqe6/2uPZlKgkfGnTaOaoPzZMCJw6oyr7eHnmZlbo7fs2/WLDq', 'LeMAl3D6Lb8FQ9rO435NnPfSX5A4ju9RwUnWDdzKrTW57aft9t8u0D9exky7', '2020-06-10 17:53:09', '2020-06-10 17:53:11'); /*!40000 ALTER TABLE `admins` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.agents DROP TABLE IF EXISTS `agents`; CREATE TABLE IF NOT EXISTS `agents` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `role_id` bigint(20) unsigned NOT NULL DEFAULT '0', `agent_type_id` bigint(20) unsigned NOT NULL DEFAULT '0', `firstname` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `lastname` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `firstname_kh` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `lastname_kh` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `job_title` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `phone` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `phone1` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `phone2` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `phone3` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `phone4` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `facebook` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL, `twitter` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL, `pinterest` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL, `linkedin` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL, `address` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `photo` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `description` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.agents: 4 rows /*!40000 ALTER TABLE `agents` DISABLE KEYS */; INSERT INTO `agents` (`id`, `role_id`, `agent_type_id`, `firstname`, `lastname`, `firstname_kh`, `lastname_kh`, `job_title`, `phone`, `phone1`, `phone2`, `phone3`, `phone4`, `email`, `facebook`, `twitter`, `pinterest`, `linkedin`, `address`, `photo`, `description`, `created_at`, `updated_at`) VALUES (1, 1, 1, 'Administrator', 'Administrator', 'គ្រប់គ្រងរដ្ឋបាល', 'គ្រប់គ្រងរដ្ឋបាល', NULL, '012888999', NULL, NULL, NULL, NULL, '<EMAIL>', '', '', '', '', '', NULL, NULL, '2020-06-10 10:47:43', '2020-06-10 10:47:43'), (2, 3, 1, 'agent', 'agent', 'អេចិន', 'អេចិន', NULL, '01211112222', NULL, NULL, NULL, NULL, '<EMAIL>', '', '', '', '', '', NULL, NULL, '2020-06-11 08:09:52', '2020-06-11 08:09:52'), (3, 3, 1, 'User', 'User', 'យូសសឺ', 'យូសសឺ', NULL, '012123456', NULL, NULL, NULL, NULL, '<EMAIL>', '', '', '', '', '', NULL, NULL, '2020-06-14 08:21:31', '2020-06-14 08:21:31'), (4, 3, 1, 'kaka', 'kaka', 'kaka', 'kaka', NULL, '012666777', NULL, NULL, NULL, NULL, '<EMAIL>', '', '', '', '', '', NULL, NULL, '2020-06-15 07:59:19', '2020-06-15 07:59:19'); /*!40000 ALTER TABLE `agents` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.attributes DROP TABLE IF EXISTS `attributes`; CREATE TABLE IF NOT EXISTS `attributes` ( `id` bigint(20) NOT NULL, `name_kh` varchar(150) DEFAULT NULL, `name_en` varchar(150) DEFAULT NULL, `value` varchar(150) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- Dumping data for table thepinrealestate_social_login.attributes: 0 rows /*!40000 ALTER TABLE `attributes` DISABLE KEYS */; /*!40000 ALTER TABLE `attributes` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.bathrooms DROP TABLE IF EXISTS `bathrooms`; CREATE TABLE IF NOT EXISTS `bathrooms` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `room` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.bathrooms: 9 rows /*!40000 ALTER TABLE `bathrooms` DISABLE KEYS */; INSERT INTO `bathrooms` (`id`, `room`, `created_at`, `updated_at`) VALUES (1, '1', '2020-06-20 12:58:51', '2020-06-20 12:58:53'), (2, '2', '2020-06-20 12:58:52', '2020-06-20 12:58:51'), (3, '3', '2020-06-20 12:58:54', '2020-06-20 12:58:54'), (4, '4', '2020-06-20 12:58:55', '2020-06-20 12:58:55'), (5, '5', '2020-06-20 12:58:56', '2020-06-20 12:58:56'), (6, '6', '2020-06-20 12:58:57', '2020-06-20 12:58:57'), (7, '7', '2020-06-20 12:58:58', '2020-06-20 12:58:59'), (8, '8', '2020-06-20 12:58:59', '2020-06-20 12:59:02'), (9, 'More+', '2020-06-20 12:59:00', '2020-06-20 12:59:00'); /*!40000 ALTER TABLE `bathrooms` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.bedrooms DROP TABLE IF EXISTS `bedrooms`; CREATE TABLE IF NOT EXISTS `bedrooms` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `room` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.bedrooms: 9 rows /*!40000 ALTER TABLE `bedrooms` DISABLE KEYS */; INSERT INTO `bedrooms` (`id`, `room`, `created_at`, `updated_at`) VALUES (1, '1', '2020-06-20 12:55:45', '2020-06-20 12:55:46'), (2, '2', '2020-06-20 12:55:46', '2020-06-20 12:55:48'), (3, '3', '2020-06-20 12:55:47', '2020-06-20 12:55:47'), (4, '4', '2020-06-20 12:55:55', '2020-06-20 12:55:54'), (5, '5', '2020-06-20 12:56:01', '2020-06-20 12:56:02'), (6, '6', '2020-06-20 12:56:08', '2020-06-20 12:56:09'), (7, '7', '2020-06-20 12:56:15', '2020-06-20 12:56:16'), (8, '8', '2020-06-20 12:56:24', '2020-06-20 12:56:24'), (9, 'More+', '2020-06-20 12:58:03', '2020-06-20 12:58:03'); /*!40000 ALTER TABLE `bedrooms` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.categories DROP TABLE IF EXISTS `categories`; CREATE TABLE IF NOT EXISTS `categories` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `parent_id` int(10) unsigned NOT NULL, `type_id` tinyint(4) DEFAULT '0', `sub_type_id` tinyint(4) DEFAULT NULL, `category_name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `category_name_kh` varchar(150) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `slug` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `description` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `form_name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `form_header` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `form_footer` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `icon` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `url` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `is_active` tinyint(4) NOT NULL DEFAULT '0', `deleted_at` timestamp NULL DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=133 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.categories: 132 rows /*!40000 ALTER TABLE `categories` DISABLE KEYS */; INSERT INTO `categories` (`id`, `parent_id`, `type_id`, `sub_type_id`, `category_name`, `category_name_kh`, `slug`, `description`, `form_name`, `form_header`, `form_footer`, `icon`, `url`, `is_active`, `deleted_at`, `created_at`, `updated_at`) VALUES (1, 0, 0, 0, 'Phones & Tablets', NULL, 'phones-and-tablets', NULL, NULL, NULL, NULL, 'mobile-phones-tablets.png', NULL, 0, NULL, NULL, NULL), (2, 0, 0, 0, 'Computers & Accessories', NULL, 'computers-and-accessories', NULL, NULL, NULL, NULL, 'computer-and-accessories.png', NULL, 0, NULL, NULL, NULL), (3, 0, 0, 0, 'Electronics & Appliances', NULL, 'electronics-and-appliances', NULL, NULL, NULL, NULL, 'electronics-appliances.png', NULL, 0, NULL, NULL, NULL), (4, 0, 0, 0, 'Cars and Vehicles', NULL, 'cars-and-vehicles', NULL, NULL, NULL, NULL, 'cars-and-vehicles.png', NULL, 0, NULL, NULL, NULL), (5, 0, 0, 0, ' House & Lands', NULL, 'house-and-land', NULL, NULL, NULL, NULL, 'property-housing-rentals.png', NULL, 1, NULL, NULL, NULL), (6, 0, 0, 0, 'Jobs', NULL, 'jobs', NULL, NULL, NULL, NULL, 'jobs.png', NULL, 0, NULL, NULL, NULL), (7, 0, 0, 0, 'Services', NULL, 'services', NULL, NULL, NULL, NULL, 'services.png', NULL, 1, NULL, NULL, NULL), (8, 0, 0, 0, 'Fashion & Beauty', NULL, 'fashion-and-beauty', NULL, NULL, NULL, NULL, 'fashion-beauty.png', NULL, 0, NULL, NULL, NULL), (9, 0, 0, 0, 'Books, Sports & Hobbies', NULL, 'books-sports-hobbies', NULL, NULL, NULL, NULL, 'books-sports-hobbies.png', NULL, 0, NULL, NULL, NULL), (10, 0, 0, 0, 'Furniture & Decor', NULL, 'furniture-decor', NULL, NULL, NULL, NULL, 'furniture-decor.png', NULL, 0, NULL, NULL, NULL), (11, 0, 0, 0, 'Pets', NULL, 'pets', NULL, NULL, NULL, NULL, 'pets.png', NULL, 0, NULL, NULL, NULL), (12, 0, 0, 0, 'foods', NULL, 'foods', NULL, NULL, NULL, NULL, 'foods.png', NULL, 0, NULL, NULL, NULL), (13, 1, 0, 0, 'Phones, Tablets', NULL, 'phone-and-tablets', NULL, 'phone_tablets.phone', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (14, 1, 0, 0, 'Smart Watches', NULL, 'smart-watches', NULL, 'phone_tablets.watch', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (15, 1, 0, 0, 'Phone Accessories', NULL, 'phone-and-ccessories', NULL, 'phone_tablets.accessories', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (16, 1, 0, 0, 'Phone Numbers', NULL, 'phone-and-numbers', NULL, 'phone_tablets.number', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (17, 2, 0, 0, 'Computers', NULL, 'computers', NULL, 'computer_accessories.computer', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (18, 2, 0, 0, 'Computer accessories', NULL, 'computer-accessories', NULL, 'computer_accessories.accessories', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (19, 2, 0, 0, 'Softwares', NULL, 'softwares', NULL, 'computer_accessories.software', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (20, 3, 0, 0, 'Consumer Electronics', NULL, 'consumer-electronics', NULL, 'electronic_appliances.electronic', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (21, 3, 0, 0, 'Security Camera', NULL, 'security-camera', NULL, 'electronic_appliances.camera', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (22, 3, 0, 0, 'Cameras, camcorders', NULL, 'cameras-and-camcorders', NULL, 'electronic_appliances.camcorder', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (23, 3, 0, 0, 'TVs, Videos and Audios', NULL, 'tv-videos-and-audios', NULL, 'electronic_appliances.appliance_game_tv_video_audio', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (24, 3, 0, 0, 'Home appliances', NULL, 'home-appliances', NULL, 'electronic_appliances.appliance_game_tv_video_audio', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (25, 3, 0, 0, 'Video games, consoles, toys', NULL, 'video-games-consoles-toys', NULL, 'electronic_appliances.appliance_game_tv_video_audio', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (26, 4, 0, 0, 'Cars for Sale', NULL, 'cars-for-sale', NULL, 'car_vehicles.car_sale', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (27, 4, 0, 0, 'Bicycles', NULL, 'bicycles', NULL, 'car_vehicles.bicycle', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (28, 4, 0, 0, 'Motorcycles for Sale', NULL, 'motorcycles-for-sale', NULL, 'car_vehicles.motocycle', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (29, 4, 0, 0, 'Vehicles for Rent', NULL, 'vehicles-for-ent', NULL, 'car_vehicles.vehicle_rent', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (30, 4, 0, 0, 'Car Maintenance & Repair', NULL, 'car-maintenance-and-repair', NULL, 'car_vehicles.repaire_insurance', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (31, 4, 0, 0, 'Lorries & Vans', NULL, 'lorries-and-vans', NULL, 'car_vehicles.accessories_lorries_vans', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (32, 4, 0, 0, 'Financing & Insurance', NULL, 'financing-and-insurance', NULL, 'car_vehicles.repaire_insurance', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (33, 4, 0, 0, 'Car Parts & Accessories', NULL, 'car-parts-and-accessories', NULL, 'car_vehicles.accessories_lorries_vans', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (34, 4, 0, 0, 'Others', NULL, 'others', NULL, 'car_vehicles.others', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (35, 5, 1, 1, 'House for Sale', NULL, 'house-for-sale', NULL, 'house_lands.house', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL), (36, 5, 1, 2, 'House for Rent', NULL, 'house-for-rent', NULL, 'house_lands.house', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL), (37, 5, 3, 1, 'Apartment for Sale', NULL, 'apartment-for-sale', NULL, 'house_lands.land_commercial_apartment_room', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (38, 5, 3, 2, 'Apartment for Rent', NULL, 'apartment-for-rent', NULL, 'house_lands.land_commercial_apartment_room', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (39, 5, 2, 1, 'Land for Sale', NULL, 'land-for-sale', NULL, 'house_lands.land_commercial_apartment_room', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL), (40, 5, 2, 2, 'Land for Rent', NULL, 'land-for-rent', NULL, 'house_lands.land_commercial_apartment_room', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL), (41, 5, 4, 1, 'Commercial for Sale', NULL, 'commercial-for-sale', NULL, 'house_lands.land_commercial_apartment_room', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL), (42, 5, 4, 2, 'Commercial for Rent', NULL, 'commercial-for-rent', NULL, 'house_lands.land_commercial_apartment_room', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL), (43, 5, 5, 2, 'Room for Rent', NULL, 'room-for-rent', NULL, 'house_lands.land_commercial_apartment_room', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL), (44, 5, 6, 3, 'Properties Wanted', NULL, 'properties-wanted', NULL, 'house_lands.properties_wanted_agent_other', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL), (45, 5, 7, 4, 'Agent Services', NULL, 'agent-services', NULL, 'house_lands.properties_wanted_agent_other', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL), (46, 5, 8, 5, 'Others', NULL, 'others', NULL, 'house_lands.properties_wanted_agent_other', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL), (47, 6, 0, 0, 'Accounting', NULL, 'accounting', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (48, 6, 0, 0, 'Administration', NULL, 'administration', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (49, 6, 0, 0, 'Assistant/Secretary', NULL, 'assistant-secretary', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (50, 6, 0, 0, 'Audit/Taxation', NULL, 'audit-taxation', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (51, 6, 0, 0, 'Banking/Insurance', NULL, 'banking-insurance', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (52, 6, 0, 0, 'Cashier/Receptionist', NULL, 'cashier-receptionist', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (53, 6, 0, 0, 'Catering/Restaurant', NULL, 'catering-restaurant', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (54, 6, 0, 0, 'Cleaner/Maid', NULL, 'cleaner-maid', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (55, 6, 0, 0, 'Consultancy', NULL, 'consultancy', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (56, 6, 0, 0, 'Customer Service', NULL, 'customer-service', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (57, 6, 0, 0, 'Design', NULL, 'design', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (58, 6, 0, 0, 'Education/Training', NULL, 'education-training', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (59, 6, 0, 0, 'Finance', NULL, 'finance', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (60, 6, 0, 0, 'Freight/Shipping /Delivery/Warehouse', NULL, 'freight-shipping-delivery-warehouse', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (61, 6, 0, 0, 'Hotel/Hospitality', NULL, 'hotel-hospitality', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (62, 6, 0, 0, 'Human Resource', NULL, 'human-resource', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (63, 6, 0, 0, 'Information Technology', NULL, 'information-technology', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (64, 6, 0, 0, 'Lawyer/Legal Service', NULL, 'lawyer-legal-service', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (65, 6, 0, 0, 'Management', NULL, 'management', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (66, 6, 0, 0, 'Manufacturing', NULL, 'manufacturing', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (67, 6, 0, 0, 'Marketing', NULL, 'marketing', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (68, 6, 0, 0, 'Media/Advertising', NULL, 'media-advertising', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (69, 6, 0, 0, 'Medical/Health/Nursing', NULL, 'medical-health-nursing', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (70, 6, 0, 0, 'Merchandising/Purchasing', NULL, 'merchandising-purchasing', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (71, 6, 0, 0, 'Operations', NULL, 'operations', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (72, 6, 0, 0, 'Project Management', NULL, 'project-management', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (73, 6, 0, 0, 'Quality Control', NULL, 'quality-control', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (74, 6, 0, 0, 'Resort/Casino', NULL, 'resort-casino', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (75, 6, 0, 0, 'Sales', NULL, 'sales', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (76, 6, 0, 0, 'Security/Driver', NULL, 'security-driver', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (77, 6, 0, 0, 'Technician', NULL, 'technician', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (78, 6, 0, 0, 'Telecommunication', NULL, 'telecommunication', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (79, 6, 0, 0, 'Translation/Interpretation', NULL, 'translation-interpretation', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (80, 6, 0, 0, 'Travel Agent/Ticket Sales', NULL, 'travel-agent-and-ticket-sales', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (81, 6, 0, 0, 'Others', NULL, 'others', NULL, 'jobs', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (82, 7, 0, 0, 'Accounting', NULL, 'accounting', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (83, 7, 0, 0, 'Automotive', NULL, 'automotive', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (84, 7, 0, 0, 'Advertising & Media', NULL, 'advertising-and-media', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (85, 7, 0, 0, 'Bridal Services', NULL, 'bridal-services', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (86, 7, 0, 0, 'Cleaning & Maid Services', NULL, 'cleaning-and-maid-services', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (87, 7, 0, 0, 'Construction, Arch. & Interiors', NULL, 'construction', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (88, 7, 0, 0, 'Education & Training', NULL, 'education-and-training', NULL, 'services', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL), (89, 7, 0, 0, 'Engineering', NULL, 'engineering', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (90, 7, 0, 0, 'Insurance', NULL, 'insurance', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (91, 7, 0, 0, 'Massage & Spa', NULL, 'massage-and-spa', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (92, 7, 0, 0, 'Hospitality, Travel & Tourism', NULL, 'hospitality-travel-and-tourism', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (93, 7, 0, 0, 'Health, Medical & Pharma', NULL, 'health-medical-and-pharma', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (94, 7, 0, 0, 'IT & Telecom', NULL, 'it-and-telecom', NULL, 'services', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL), (95, 7, 0, 0, 'Interior Design & Renovation', NULL, 'interior-design-and-renovation', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (96, 7, 0, 0, 'Legal', NULL, 'legal', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (97, 7, 0, 0, 'Movers & Logistics', NULL, 'movers-and-logistics', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (98, 7, 0, 0, 'Plumbing & Electrical', NULL, 'plumbing-and-electrical', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (99, 7, 0, 0, 'Property & Real Estate', NULL, 'property-and-real-estate', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (100, 7, 0, 0, 'Science', NULL, 'science', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (101, 7, 0, 0, 'Supply Chain & Logistics', NULL, 'supply-chain-and-logistics', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (102, 7, 0, 0, 'Printing & Publishing', NULL, 'printing-and-publishing', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (103, 7, 0, 0, 'Other Services', NULL, 'other-services', NULL, 'services', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (104, 8, 0, 0, 'Jewelry, watches', NULL, 'jewelry-watches', NULL, 'fashion_beauty.jewelry_watches', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (105, 8, 0, 0, 'Clothing, accessories', NULL, 'clothing-accessories', NULL, 'fashion_beauty.clothing_accessories', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (106, 8, 0, 0, 'Beauty & Healthcare', NULL, 'beauty-and-healthcare', NULL, 'fashion_beauty.beauty_healthcare', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (107, 9, 0, 0, 'CDS, DVDS, VHS', NULL, 'cds-dvds-vhs', NULL, 'book_sport_hobbies', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (108, 9, 0, 0, 'Books', NULL, 'books', NULL, 'book_sport_hobbies', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (109, 9, 0, 0, 'Sports Equipment', NULL, 'sports-equipment', NULL, 'book_sport_hobbies', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (110, 9, 0, 0, 'Others', NULL, 'others', NULL, 'book_sport_hobbies', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (111, 10, 0, 0, 'Household Items', NULL, 'household-items', NULL, 'furniture_decos', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (112, 10, 0, 0, 'Office Furniture', NULL, 'office-furniture', NULL, 'furniture_decos', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (113, 10, 0, 0, 'Home Furniture', NULL, 'home-furniture', NULL, 'furniture_decos', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (114, 10, 0, 0, 'Kitchenware', NULL, 'kitchenware', NULL, 'furniture_decos', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (115, 10, 0, 0, 'Handicrafts Paintings', NULL, 'handicrafts-paintings', NULL, 'furniture_decos', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (116, 11, 0, 0, 'Dogs', NULL, 'dogs', NULL, 'pets', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (117, 11, 0, 0, 'Cats', NULL, 'cats', NULL, 'pets', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (118, 11, 0, 0, 'Birds', NULL, 'birds', NULL, 'pets', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (119, 11, 0, 0, 'Fish', NULL, 'fish', NULL, 'pets', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (120, 11, 0, 0, 'Pet Food', NULL, 'pet-food', NULL, 'pets', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (121, 11, 0, 0, 'Pet Accessories', NULL, 'pet-accessories', NULL, 'pets', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (122, 11, 0, 0, 'Other', NULL, 'other', NULL, 'pets', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (123, 12, 0, 0, 'Meat', NULL, 'meat', NULL, 'foods', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (124, 12, 0, 0, 'Seafood', NULL, 'seafood', NULL, 'foods', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (125, 12, 0, 0, 'Fruits', NULL, 'fruits', NULL, 'foods', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (126, 12, 0, 0, 'Vegetables', NULL, 'vegetables', NULL, 'foods', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (127, 12, 0, 0, 'Beverages', NULL, 'beverages', NULL, 'foods', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (128, 12, 0, 0, 'Grocery', NULL, 'grocery', NULL, 'foods', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (129, 12, 0, 0, 'Bread & Bakery', NULL, 'bread-and-bakery', NULL, 'foods', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (130, 12, 0, 0, 'Beer & Wine', NULL, 'beer-and-wine', NULL, 'foods', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (131, 12, 0, 0, 'Rice & Cereal', NULL, 'rice-and-cereal', NULL, 'foods', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL), (132, 12, 0, 0, 'Other', NULL, 'others', NULL, 'foods', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL); /*!40000 ALTER TABLE `categories` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.communes DROP TABLE IF EXISTS `communes`; CREATE TABLE IF NOT EXISTS `communes` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `district_id` int(11) DEFAULT NULL, `name_en` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `name_kh` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=912 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.communes: 911 rows /*!40000 ALTER TABLE `communes` DISABLE KEYS */; INSERT INTO `communes` (`id`, `district_id`, `name_en`, `name_kh`, `created_at`, `updated_at`) VALUES (1, 1, '<NAME>', '', NULL, NULL), (2, 1, '<NAME>', '', NULL, NULL), (3, 1, '<NAME>', '', NULL, NULL), (4, 1, '<NAME> 6', '', NULL, NULL), (5, 1, '<NAME>', '', NULL, NULL), (6, 1, '<NAME>', '', NULL, NULL), (7, 2, '<NAME>', '', NULL, NULL), (8, 2, 'Khmuonh', '', NULL, NULL), (9, 2, '<NAME>', '', NULL, NULL), (10, 2, '<NAME>', '', NULL, NULL), (11, 2, '<NAME>', '', NULL, NULL), (12, 3, 'Ovlaok', '', NULL, NULL), (13, 3, 'Kamboul', '', NULL, NULL), (14, 3, 'Kantaok', '', NULL, NULL), (15, 3, '<NAME>', '', NULL, NULL), (16, 3, '<NAME>', '', NULL, NULL), (17, 3, '<NAME>', '', NULL, NULL), (18, 3, '<NAME>', '', NULL, NULL), (19, 3, 'Kakab', '', NULL, NULL), (20, 3, '<NAME>', '', NULL, NULL), (21, 3, 'Snaor', '', NULL, NULL), (22, 4, '<NAME>', '', NULL, NULL), (23, 4, '<NAME>', '', NULL, NULL), (24, 4, '<NAME>', '', NULL, NULL), (25, 4, '<NAME>', '', NULL, NULL), (26, 4, '<NAME>', '', NULL, NULL), (27, 5, 'Ponsang', '', NULL, NULL), (28, 5, '<NAME>', '', NULL, NULL), (29, 5, '<NAME>', '', NULL, NULL), (30, 5, 'Samraong', '', NULL, NULL), (31, 5, '<NAME>', '', NULL, NULL), (32, 6, '<NAME>', '', NULL, NULL), (33, 6, '<NAME>', '', NULL, NULL), (34, 6, '<NAME>', '', NULL, NULL), (35, 6, '<NAME>', '', NULL, NULL), (36, 6, 'Nirouth', '', NULL, NULL), (37, 6, '<NAME>', '', NULL, NULL), (38, 6, '<NAME>', '', NULL, NULL), (39, 6, '<NAME>', '', NULL, NULL), (40, 7, '<NAME>', '', NULL, NULL), (41, 7, '<NAME>', '', NULL, NULL), (42, 7, '<NAME>', '', NULL, NULL), (43, 7, '<NAME>', '', NULL, NULL), (44, 7, '<NAME>', '', NULL, NULL), (45, 7, '<NAME>', '', NULL, NULL), (46, 7, 'Chaktomukh', '', NULL, NULL), (47, 7, '<NAME>', '', NULL, NULL), (48, 7, '<NAME>', '', NULL, NULL), (49, 7, '<NAME>', '', NULL, NULL), (50, 7, '<NAME>', '', NULL, NULL), (51, 8, 'O Reussei 1', '', NULL, NULL), (52, 8, 'O Reussei 2', '', NULL, NULL), (53, 8, 'O Reussei 3', '', NULL, NULL), (54, 8, 'O Reussei 4', '', NULL, NULL), (55, 8, 'Monorom', '', NULL, NULL), (56, 8, 'Mittapheap', '', NULL, NULL), (57, 8, 'Vealvong', '', NULL, NULL), (58, 8, '<NAME>', '', NULL, NULL), (59, 9, '<NAME>', '', NULL, NULL), (60, 9, '<NAME>ot2', '', NULL, NULL), (61, 9, '<NAME>ot3', '', NULL, NULL), (62, 9, '<NAME>', '', NULL, NULL), (63, 9, '<NAME>', '', NULL, NULL), (64, 9, '<NAME>', '', NULL, NULL), (65, 9, '<NAME>', '', NULL, NULL), (66, 9, '<NAME>', '', NULL, NULL), (67, 9, '<NAME>', '', NULL, NULL), (68, 9, '<NAME>', '', NULL, NULL), (69, 10, 'Dangkor', '', NULL, NULL), (70, 10, '<NAME>', '', NULL, NULL), (71, 10, '<NAME>', '', NULL, NULL), (72, 10, '<NAME>', '', NULL, NULL), (73, 10, '<NAME>', '', NULL, NULL), (74, 10, '<NAME>', '', NULL, NULL), (75, 10, '<NAME>', '', NULL, NULL), (76, 10, '<NAME>', '', NULL, NULL), (77, 10, '<NAME>', '', NULL, NULL), (78, 10, '<NAME>', '', NULL, NULL), (79, 10, 'Tien', '', NULL, NULL), (80, 10, '<NAME>', '', NULL, NULL), (81, 11, '<NAME>', '', NULL, NULL), (82, 11, '<NAME>', '', NULL, NULL), (83, 11, '<NAME>', '', NULL, NULL), (84, 11, '<NAME>', '', NULL, NULL), (85, 12, '<NAME>', '', NULL, NULL), (86, 12, '<NAME>', '', NULL, NULL), (87, 12, '<NAME>', '', NULL, NULL), (88, 12, '<NAME>', '', NULL, NULL), (89, 12, 'Olympic', '', NULL, NULL), (90, 12, '<NAME>', '', NULL, NULL), (91, 12, '<NAME>', '', NULL, NULL), (92, 12, '<NAME>', '', NULL, NULL), (93, 12, '<NAME>', '', NULL, NULL), (94, 12, '<NAME>', '', NULL, NULL), (95, 12, '<NAME>', '', NULL, NULL), (96, 12, '<NAME>', '', NULL, NULL), (97, 13, 'Sangkat 1', '', NULL, NULL), (98, 13, 'Sangkat 2', '', NULL, NULL), (99, 13, 'Sangkat 3', '', NULL, NULL), (100, 13, 'Sangkat 4', '', NULL, NULL), (101, 13, '<NAME>', '', NULL, NULL), (102, 14, '<NAME>', '', NULL, NULL), (103, 14, '<NAME>', '', NULL, NULL), (104, 14, '<NAME>', '', NULL, NULL), (105, 14, '<NAME>', '', NULL, NULL), (106, 14, '<NAME>', '', NULL, NULL), (107, 14, 'Ou <NAME>', '', NULL, NULL), (108, 14, '<NAME>', '', NULL, NULL), (109, 14, 'Ream', '', NULL, NULL), (110, 14, 'Sammaki', '', NULL, NULL), (111, 14, 'Somrong', '', NULL, NULL), (112, 14, '<NAME>', '', NULL, NULL), (113, 14, '<NAME>', '', NULL, NULL), (114, 14, '<NAME>', '', NULL, NULL), (115, 14, '<NAME>', '', NULL, NULL), (116, 15, 'Kompenh', '', NULL, NULL), (117, 15, '<NAME>', '', NULL, NULL), (118, 15, '<NAME>', '', NULL, NULL), (119, 15, '<NAME>', '', NULL, NULL), (120, 16, '<NAME>', '', NULL, NULL), (121, 16, '<NAME>', '', NULL, NULL), (122, 16, 'Ou <NAME>', '', NULL, NULL), (123, 16, '<NAME>', '', NULL, NULL), (124, 17, '<NAME>', '', NULL, NULL), (125, 17, '<NAME>', '', NULL, NULL), (126, 17, '<NAME>', '', NULL, NULL), (127, 17, '<NAME>', '', NULL, NULL), (128, 18, 'Ampil', '', NULL, NULL), (129, 18, '<NAME>', '', NULL, NULL), (130, 18, '<NAME>', '', NULL, NULL), (131, 18, 'Kokor', '', NULL, NULL), (132, 18, '<NAME>', '', NULL, NULL), (133, 18, '<NAME>', '', NULL, NULL), (134, 18, '<NAME>', '', NULL, NULL), (135, 18, '<NAME>', '', NULL, NULL), (136, 18, 'Krala', '', NULL, NULL), (137, 18, '<NAME>', '', NULL, NULL), (138, 18, '<NAME>', '', NULL, NULL), (139, 18, 'Rumchek', '', NULL, NULL), (140, 18, 'Srak', '', NULL, NULL), (141, 18, 'Trean', '', NULL, NULL), (142, 18, '<NAME>', '', NULL, NULL), (143, 19, '<NAME>', '', NULL, NULL), (144, 19, '<NAME>', '', NULL, NULL), (145, 19, 'Khchau', '', NULL, NULL), (146, 19, '<NAME>', '', NULL, NULL), (147, 19, '<NAME>', '', NULL, NULL), (148, 19, '<NAME>', '', NULL, NULL), (149, 19, '<NAME>', '', NULL, NULL), (150, 19, 'Roka-a', '', NULL, NULL), (151, 19, 'Roka-koy', '', NULL, NULL), (152, 19, 'Sdau', '', NULL, NULL), (153, 19, '<NAME>', '', NULL, NULL), (154, 20, '<NAME>', '', NULL, NULL), (155, 20, '<NAME>', '', NULL, NULL), (156, 20, 'Tve', '', NULL, NULL), (157, 20, 'Mohaleap', '', NULL, NULL), (158, 20, '<NAME>', '', NULL, NULL), (159, 20, '<NAME>', '', NULL, NULL), (160, 20, 'Pongro', '', NULL, NULL), (161, 20, '<NAME>', '', NULL, NULL), (162, 21, 'Baray', '', NULL, NULL), (163, 21, '<NAME>', '', NULL, NULL), (164, 21, '<NAME>', '', NULL, NULL), (165, 21, 'Mean', '', NULL, NULL), (166, 21, '<NAME>', '', NULL, NULL), (167, 21, '<NAME>', '', NULL, NULL), (168, 21, 'Kor', '', NULL, NULL), (169, 21, 'Krouch', '', NULL, NULL), (170, 21, 'Lvea', '', NULL, NULL), (171, 21, '<NAME>', '', NULL, NULL), (172, 21, '<NAME>', '', NULL, NULL), (173, 21, 'Somrorng', '', NULL, NULL), (174, 21, '<NAME>', '', NULL, NULL), (175, 21, '<NAME>', '', NULL, NULL), (176, 21, '<NAME>', '', NULL, NULL), (177, 22, 'Baray', '', NULL, NULL), (178, 22, 'Chibal', '', NULL, NULL), (179, 22, '<NAME>', '', NULL, NULL), (180, 22, '<NAME>', '', NULL, NULL), (181, 22, '<NAME>', '', NULL, NULL), (182, 22, '<NAME>', '', NULL, NULL), (183, 22, '<NAME>', '', NULL, NULL), (184, 22, '<NAME>', '', NULL, NULL), (185, 22, '<NAME>', '', NULL, NULL), (186, 22, '<NAME>', '', NULL, NULL), (187, 22, '<NAME>', '', NULL, NULL), (188, 22, '<NAME>', '', NULL, NULL), (189, 22, '<NAME>', '', NULL, NULL), (190, 22, '<NAME>', '', NULL, NULL), (191, 23, '<NAME>', '', NULL, NULL), (192, 23, '<NAME>', '', NULL, NULL), (193, 23, '<NAME>', '', NULL, NULL), (194, 23, '<NAME>', '', NULL, NULL), (195, 23, '<NAME>', '', NULL, NULL), (196, 23, '<NAME>', '', NULL, NULL), (197, 23, '<NAME>', '', NULL, NULL), (198, 23, '<NAME>', '', NULL, NULL), (199, 23, 'Sopheas', '', NULL, NULL), (200, 23, '<NAME>', '', NULL, NULL), (201, 23, '<NAME>', '', NULL, NULL), (202, 24, 'Batheay', '', NULL, NULL), (203, 24, '<NAME>', '', NULL, NULL), (204, 24, 'Chealea', '', NULL, NULL), (205, 24, '<NAME>', '', NULL, NULL), (206, 24, '<NAME>', '', NULL, NULL), (207, 24, 'Phav', '', NULL, NULL), (208, 24, 'Sambour', '', NULL, NULL), (209, 24, 'Sandaek', '', NULL, NULL), (210, 24, '<NAME>', '', NULL, NULL), (211, 24, 'Prasat', '', NULL, NULL), (212, 24, '<NAME>', '', NULL, NULL), (213, 24, '<NAME>', '', NULL, NULL), (214, 24, 'Tumnob', '', NULL, NULL), (215, 25, '<NAME>', '', NULL, NULL), (216, 25, '<NAME>', '', NULL, NULL), (217, 25, 'Cheyyou', '', NULL, NULL), (218, 25, '<NAME>', '', NULL, NULL), (219, 25, 'Spueu', '', NULL, NULL), (220, 25, '<NAME>', '', NULL, NULL), (221, 25, '<NAME>', '', NULL, NULL), (222, 25, '<NAME>', '', NULL, NULL), (223, 26, '<NAME>', '', NULL, NULL), (224, 26, '<NAME>', '', NULL, NULL), (225, 26, '<NAME>', '', NULL, NULL), (226, 26, '<NAME>', '', NULL, NULL), (227, 26, '<NAME>', '', NULL, NULL), (228, 26, '<NAME>', '', NULL, NULL), (229, 26, '<NAME>', '', NULL, NULL), (230, 26, 'Soutip', '', NULL, NULL), (231, 26, 'Srama', '', NULL, NULL), (232, 26, '<NAME>', '', NULL, NULL), (233, 27, '<NAME>', 'ចារឈូក', NULL, NULL), (234, 27, '<NAME>', 'ដូនពេង', NULL, NULL), (235, 27, '<NAME>', 'គោកដូង', NULL, NULL), (236, 27, 'Koal', 'គោល', NULL, NULL), (237, 27, 'Nokor Pheas', 'នគរភាស', NULL, NULL), (238, 27, '<NAME>', 'ស្រែខ្វាវ', NULL, NULL), (239, 27, 'Tasoam', 'តាសោម', NULL, NULL), (240, 28, '<NAME>', 'ជប់តាត្រាវ', NULL, NULL), (241, 28, '<NAME>', 'លាងដៃ', NULL, NULL), (242, 28, 'Peak Snaeng', 'ពាក់ស្នែង', NULL, NULL), (243, 28, '<NAME>', 'ស្វាយចេក', NULL, NULL), (244, 29, '<NAME>', 'ខ្នារសណ្តាយ', NULL, NULL), (245, 29, '<NAME>', 'ឃុនរាម', NULL, NULL), (246, 29, '<NAME>', 'ព្រះដាក់', NULL, NULL), (247, 29, 'Romchek', 'រំចេក', NULL, NULL), (248, 29, '<NAME>', 'រុនតាឯក', NULL, NULL), (249, 29, 'Tbaeng', 'ត្បែង', NULL, NULL), (250, 30, '<NAME>', 'អន្លង់សំណរ', NULL, NULL), (251, 30, '<NAME>', 'ជីក្រែង', NULL, NULL), (252, 30, '<NAME>', 'កំពង់ក្តី', NULL, NULL), (253, 30, 'Khvav', 'ខ្វាវ', NULL, NULL), (254, 30, 'Koak Thlok Krom', 'គោកធ្លកក្រោម', NULL, NULL), (255, 30, 'Koak Thlok Leu', 'គោកធ្លកលើ', NULL, NULL), (256, 30, 'Lveng Russei', 'ល្វែងឫស្សី', NULL, NULL), (257, 30, 'Pongro Krom', 'ពង្រក្រោម', NULL, NULL), (258, 30, 'Pongro Leu', 'ពង្រលើ', NULL, NULL), (259, 30, 'Russei Lok', 'ឫស្សីលក', NULL, NULL), (260, 30, 'Songveuy', 'សង្វើយ', NULL, NULL), (261, 30, 'Spean Tnoat', 'ស្ពានត្នោត', NULL, NULL), (262, 31, '<NAME>', 'ជន្លាស់ដៃ', NULL, NULL), (263, 31, '<NAME>', 'កំពង់ថ្កូវ', NULL, NULL), (264, 31, 'Kralanh', 'ក្រឡាញ់', NULL, NULL), (265, 31, 'Krouch Kor', 'ក្រូចគរ', NULL, NULL), (266, 31, '<NAME>', 'រោងគោ', NULL, NULL), (267, 31, 'Sambour', 'សំបួរ', NULL, NULL), (268, 31, '<NAME>', 'សែនសុខ', NULL, NULL), (269, 31, 'Snoul', 'ស្នួល', NULL, NULL), (270, 31, 'Sronal', 'ស្រណាល', NULL, NULL), (271, 31, '<NAME>', 'តាអាន', NULL, NULL), (272, 32, 'Sosor Sdom', 'សសរស្តម្', NULL, NULL), (273, 32, '<NAME>', 'ដូនកែវ', NULL, NULL), (274, 32, '<NAME>', 'ក្តីរុន', NULL, NULL), (275, 32, '<NAME>', 'កែវពណ៌', NULL, NULL), (276, 32, 'Khnat', 'ខ្នាត', NULL, NULL), (277, 32, 'Lvea', 'ល្វា', NULL, NULL), (278, 32, '<NAME>', 'មុខប៉ែន', NULL, NULL), (279, 32, '<NAME>', 'ពោធិទ្រាយ', NULL, NULL), (280, 32, 'Pouk', 'ពួក', NULL, NULL), (281, 32, '<NAME>', 'ព្រៃជ្រូក', NULL, NULL), (282, 32, 'Reul', 'រើស', NULL, NULL), (283, 32, '<NAME>', 'សំរោងយា', NULL, NULL), (284, 32, '<NAME>', 'ត្រីញ័រ', NULL, NULL), (285, 32, 'Yeang', 'យាង', NULL, NULL), (286, 32, '<NAME>', 'ទឹកវិល', NULL, NULL), (287, 32, '<NAME>', 'ក្របីរៀល', NULL, NULL), (288, 33, 'Bakong', 'បាគង', NULL, NULL), (289, 33, 'Balangk', 'បល្ល័ង្គ', NULL, NULL), (290, 33, '<NAME>', 'កំពង់ភ្លុក', NULL, NULL), (291, 33, 'Kantreang', 'កន្ទ្រាំង', NULL, NULL), (292, 33, 'Kandaek', 'កណ្តែក', NULL, NULL), (293, 33, 'Meanchey', 'មានជ័យ', NULL, NULL), (294, 33, 'Rolous', 'រលួស', NULL, NULL), (295, 33, '<NAME>', 'ត្រពាំងធំ', NULL, NULL), (296, 33, 'Ampil', 'អំពិល', NULL, NULL), (297, 34, '<NAME>', 'ស្លក្រាម', NULL, NULL), (298, 34, '<NAME>', 'ស្វាយដង្គំ', NULL, NULL), (299, 34, '<NAME>', 'គោកចក', NULL, NULL), (300, 34, '<NAME>', 'សាលាកំរើក', NULL, NULL), (301, 34, '<NAME>', 'នគរធំ', NULL, NULL), (302, 34, 'Chreav', 'ជ្រាវ', NULL, NULL), (303, 34, '<NAME>', 'ចុងឃ្នៀស', NULL, NULL), (304, 34, 'Sambour', 'សំបួរ', NULL, NULL), (305, 34, '<NAME>', 'សៀមរាប', NULL, NULL), (306, 34, 'Sragnae', 'ស្រង៉ែ', NULL, NULL), (307, 34, 'Ampil', 'អំពិល', NULL, NULL), (308, 34, '<NAME>', 'ក្របីរៀល', NULL, NULL), (309, 34, '<NAME>', 'ទឹកវិល', NULL, NULL), (310, 35, '<NAME>', 'ចាន់ស', NULL, NULL), (311, 35, '<NAME>', 'ដំដែក', NULL, NULL), (312, 35, 'Danrun', 'ដានរុន', NULL, NULL), (313, 35, '<NAME>', 'កំពង់ឃ្លាំង', NULL, NULL), (314, 35, '<NAME>', 'កៀនសង្កែ', NULL, NULL), (315, 35, 'Khchas', 'ខ្ចាស់', NULL, NULL), (316, 35, '<NAME>', 'ខ្នារពោធិ៍', NULL, NULL), (317, 35, 'Popel', 'ពពេល', NULL, NULL), (318, 35, 'Samroang', 'សំរោង', NULL, NULL), (319, 35, '<NAME>', 'តាយ៉ែក', NULL, NULL), (320, 36, '<NAME>', 'ជ្រោយនាងងួន', NULL, NULL), (321, 36, '<NAME>', 'ក្លាំងហាយ', NULL, NULL), (322, 36, '<NAME>', 'ត្រាំសសរ', NULL, NULL), (323, 36, 'Moang', 'មោង', NULL, NULL), (324, 36, 'Brey', 'ប្រីយ៍', NULL, NULL), (325, 36, '<NAME>', 'ស្លែងស្ពាន', NULL, NULL), (326, 37, '<NAME>', 'បឹងមាលា', NULL, NULL), (327, 37, 'Kantout', 'កន្ទួត', NULL, NULL), (328, 37, '<NAME>', 'ខ្នងភ្នំ', NULL, NULL), (329, 37, '<NAME>', 'ស្វាយលើ', NULL, NULL), (330, 37, '<NAME>', 'តាសៀម', NULL, NULL), (331, 38, 'Brasat', 'ប្រាសាទ', NULL, NULL), (332, 38, '<NAME>', 'ល្វាក្រាំង', NULL, NULL), (333, 38, '<NAME>', 'ស្រែណូយ', NULL, NULL), (334, 38, '<NAME>', 'ស្វាយស', NULL, NULL), (335, 38, 'Varin', 'វ៉ារិន', NULL, NULL), (336, 39, '<NAME>', 'កន្ទឺ ១', NULL, NULL), (337, 39, '<NAME>', 'កន្ទឺ ២', NULL, NULL), (338, 39, '<NAME>', 'បាយដំរាំ', NULL, NULL), (339, 39, '<NAME>', ' ឈើទាល', NULL, NULL), (340, 39, '<NAME>', 'ចែងមានជ័យ', NULL, NULL), (341, 39, '<NAME>', 'ភ្នំសំពៅ', NULL, NULL), (342, 39, 'Snoeng', 'ស្នឹង', NULL, NULL), (343, 39, '<NAME>', 'តាគ្រាម', NULL, NULL), (344, 40, '<NAME>', 'តាពូង', NULL, NULL), (345, 40, 'តាម៉ឺន', '<NAME>', NULL, NULL), (346, 40, 'Ou Ta Ki', 'អូរតាគី', NULL, NULL), (347, 40, 'Chrey', 'ជ្រៃ', NULL, NULL), (348, 40, '<NAME>', 'អន្លង់រុន', NULL, NULL), (349, 40, '<NAME>', 'ជ្រោយស្តៅ', NULL, NULL), (350, 40, '<NAME>', 'បឹងព្រីង', NULL, NULL), (351, 40, '<NAME>', 'គោកឃ្មុំ', NULL, NULL), (352, 40, '<NAME>', 'បន្សាយត្រែង', NULL, NULL), (353, 40, '<NAME>', 'រូងជ្រៃ', NULL, NULL), (354, 41, '<NAME>', 'ទួលតាឯក', NULL, NULL), (355, 41, '<NAME>', 'ព្រែកព្រះស្តេច', NULL, NULL), (356, 41, 'Rotanak', 'រតនៈ', NULL, NULL), (357, 41, '<NAME>', 'ចំការសំរោង', NULL, NULL), (358, 41, '<NAME>', 'ស្លាកែត', NULL, NULL), (359, 41, '<NAME>', 'ក្តុលដូនទាវ', NULL, NULL), (360, 41, 'Ou Mal', 'អូរម៉ាល់', NULL, NULL), (361, 41, '<NAME>', 'វត្តគរ', NULL, NULL), (362, 41, 'Ou Char', 'អូរចារ', NULL, NULL), (363, 41, '<NAME>', 'ស្វាយប៉ោ', NULL, NULL), (364, 42, 'Bavel', 'បវេល', NULL, NULL), (365, 42, '<NAME>', 'ខ្នាចរមាស', NULL, NULL), (366, 42, 'Lvea', 'ល្វា', NULL, NULL), (367, 42, '<NAME>', 'ព្រៃខ្ពស់', NULL, NULL), (368, 42, '<NAME>', 'អំពិលប្រាំដើម', NULL, NULL), (369, 42, '<NAME>', 'ក្តុលតាហែន', NULL, NULL), (370, 42, '<NAME>', 'ខ្លាំងមាស', NULL, NULL), (371, 42, '<NAME>', 'បឹងប្រាំ', NULL, NULL), (372, 43, '<NAME>', 'ព្រែកនរិន្ទ', NULL, NULL), (373, 43, '<NAME>', 'សំរោងក្នុង', NULL, NULL), (374, 43, '<NAME>', 'ព្រែកខ្ពប', NULL, NULL), (375, 43, '<NAME>', 'ព្រែកហ្លួង', NULL, NULL), (376, 43, '<NAME>', 'ពាមឯក', NULL, NULL), (377, 43, '<NAME>', 'ព្រៃចាស់', NULL, NULL), (378, 43, '<NAME>', 'កោះជីវាំង', NULL, NULL), (379, 44, 'Moung', 'មោង', NULL, NULL), (380, 44, 'Kear', 'គារ', NULL, NULL), (381, 44, '<NAME>', 'ព្រៃស្វាយ', NULL, NULL), (382, 44, '<NAME>', 'ឫស្សីក្រាំង', NULL, NULL), (383, 44, 'Chrey', 'ជ្រៃ', NULL, NULL), (384, 44, '<NAME>', 'តាលាស់', NULL, NULL), (385, 44, 'Kakaoh', 'កកោះ', NULL, NULL), (386, 44, '<NAME>', 'ព្រៃតូច', NULL, NULL), (387, 44, '<NAME>', 'របស់មង្គល', NULL, NULL), (388, 44, 'Break Chek', 'ព្រែកជីក', NULL, NULL), (389, 44, '<NAME>', 'ព្រៃត្រឡាច', NULL, NULL), (390, 45, 'Sdau', 'ស្តៅ', NULL, NULL), (391, 45, '<NAME>', 'អណ្តើកហែប', NULL, NULL), (392, 45, 'Phlov Meas', 'ផ្លូវមាស', NULL, NULL), (393, 45, 'Traeng', 'ត្រែង', NULL, NULL), (394, 45, 'Reaksmey Sangha', 'រស្មីសង្ហារ', NULL, NULL), (395, 46, '<NAME>', 'អន្លង់វិល', NULL, NULL), (396, 46, 'Norea', 'នរា', NULL, NULL), (397, 46, 'Ta Pon', 'តាប៉ុន', NULL, NULL), (398, 46, 'Roka', 'រកា', NULL, NULL), (399, 46, 'Kampong Preah', 'កំពង់ព្រះ', NULL, NULL), (400, 46, 'Kampong Prieng', 'កំពង់ព្រៀង', NULL, NULL), (401, 46, 'Reang Kesei', 'រាំងកេសី', NULL, NULL), (402, 46, 'Ou Dambang Muoy', 'អូរដំបង ១', NULL, NULL), (403, 46, 'Ou Dambang Pir', 'អូរដំបង ២', NULL, NULL), (404, 46, 'Vaot Ta Muem', 'វត្តតាមិម', NULL, NULL), (405, 47, 'Ta Taok', 'តាតោក', NULL, NULL), (406, 47, 'Kampong Lpou', 'កំពង់ល្ពៅ', NULL, NULL), (407, 47, 'Ou Samrel', 'អូរសំរិល', NULL, NULL), (408, 47, 'Sung', 'ស៊ុង', NULL, NULL), (409, 47, 'Samlout', 'សំឡូត', NULL, NULL), (410, 47, 'Mean Cheay', 'មានជ័យ', NULL, NULL), (411, 47, 'Ta Sanh', 'តាសាញ', NULL, NULL), (412, 48, 'Sampou Lun', 'សំពៅលូន', NULL, NULL), (413, 48, 'Angkor Ban', 'អង្គរបាន', NULL, NULL), (414, 48, 'Ta Sda', 'តាសា្ត', NULL, NULL), (415, 48, 'Santepheap', 'សន្តិភាព', NULL, NULL), (416, 48, 'Serei Maen Cheay', 'សិរីមានជ័យ', NULL, NULL), (417, 48, '<NAME>', 'ជ្រៃសីមា', NULL, NULL), (418, 49, '<NAME>', 'ភ្នំព្រឹក', NULL, NULL), (419, 49, '<NAME>', 'ពេជ្រចិន្តា', NULL, NULL), (420, 49, 'Bou', 'បួរ', NULL, NULL), (421, 49, '<NAME>', 'បារាំងធ្លាក់', NULL, NULL), (422, 49, 'Ou Rumduol', 'អូររំដួល', NULL, NULL), (423, 50, 'Kamrieng', 'កំរៀង', NULL, NULL), (424, 50, '<NAME>', 'បឹងរាំង', NULL, NULL), (425, 50, 'Ou Da', 'អូរដា', NULL, NULL), (426, 50, 'Trang', 'ត្រាង', NULL, NULL), (427, 50, 'Ta Saen', 'តាសែន', NULL, NULL), (428, 50, 'Ta Krai', 'តាក្រី', NULL, NULL), (429, 51, 'Thipakdei', 'ធិបតី', NULL, NULL), (430, 51, 'Koas Krala', 'គាស់ក្រឡ', NULL, NULL), (431, 51, 'Hab', 'ហប់', NULL, NULL), (432, 51, '<NAME>', 'ព្រះផុស', NULL, NULL), (433, 51, '<NAME>', 'ដូនបា', NULL, NULL), (434, 51, '<NAME>', 'ឆ្នាល់មាន់', NULL, NULL), (435, 52, 'Pre<NAME>ik', 'ព្រែកជីក', NULL, NULL), (436, 52, 'prey trolach', 'ព្រៃត្រឡាច', NULL, NULL), (437, 52, 'Basak', 'បាសាក', NULL, NULL), (438, 52, 'Mukrea', 'មុគគ្រា', NULL, NULL), (439, 52, '<NAME>k', 'ស្តុកផ្រូវិក', NULL, NULL), (440, 53, 'Ampov Prey', 'អំពៅព្រៃ', NULL, NULL), (441, 53, '<NAME>', 'អន្លង់រមៀត', NULL, NULL), (442, 53, 'Barku', 'បាគូ', NULL, NULL), (443, 53, '<NAME>', 'បឹងខ្យាង', NULL, NULL), (444, 53, '<NAME>', 'ជើងកើប', NULL, NULL), (445, 53, '<NAME>', 'ដើមឫស', NULL, NULL), (446, 53, 'Kandaok', 'កណ្តោក', NULL, NULL), (447, 53, 'Thmei', 'ថ្មី', NULL, NULL), (448, 53, '<NAME>', 'គោកត្រប់', NULL, NULL), (449, 53, '<NAME>', 'ព្រះពុទ្ធ', NULL, NULL), (450, 53, '<NAME>', 'ព្រែករកា', NULL, NULL), (451, 53, '<NAME>', 'ព្រែកស្លែង', NULL, NULL), (452, 53, 'Roka', 'រកា', NULL, NULL), (453, 53, '<NAME>', 'រលាំងកែន', NULL, NULL), (454, 53, '<NAME>', 'សៀមរាប', NULL, NULL), (455, 53, 'Tbaeng', 'ត្បែងទៀន', NULL, NULL), (456, 53, '<NAME>', 'ត្រពាំងវែង', NULL, NULL), (457, 53, 'Trea', 'ទ្រា', NULL, NULL), (458, 54, '<NAME>', 'ឈើខ្មៅ', NULL, NULL), (459, 54, '<NAME>', 'ជ្រោយតាកែវ', NULL, NULL), (460, 54, '<NAME>', 'កំពង់កុង', NULL, NULL), (461, 54, '<NAME>', 'កោះធំ ក', NULL, NULL), (462, 54, '<NAME>', 'កោះធំ ខ', NULL, NULL), (463, 54, '<NAME>', 'លើកដែក', NULL, NULL), (464, 54, '<NAME>', 'ពោធិ៍បាន', NULL, NULL), (465, 54, '<NAME>', 'ព្រែកជ្រៃ', NULL, NULL), (466, 54, '<NAME>', 'ព្រែកស្ដី', NULL, NULL), (467, 54, '<NAME>', 'ព្រែកថ្មី', NULL, NULL), (468, 54, '<NAME>', 'សំពៅពូន', NULL, NULL), (469, 55, '<NAME>', 'ព្រែកអញ្ចាញ', NULL, NULL), (470, 55, '<NAME>', 'ព្រែកដំបង', NULL, NULL), (471, 55, '<NAME>', 'រកាកោងទី១', NULL, NULL), (472, 55, '<NAME>', 'រកាកោងទី២', NULL, NULL), (473, 55, '<NAME>', 'ឫស្សីជ្រោយ', NULL, NULL), (474, 55, '<NAME>', 'សំបួរមាស', NULL, NULL), (475, 55, '<NAME>', 'ស្វាយអំពារ', NULL, NULL), (476, 56, 'Khpob', 'ខ្ពប', NULL, NULL), (477, 56, '<NAME>', 'កោះអន្លង់ចិន', NULL, NULL), (478, 56, '<NAME>', 'កោះខែល', NULL, NULL), (479, 56, '<NAME>', 'កោះខ្សាច់ទន្លា', NULL, NULL), (480, 56, '<NAME>', 'ក្រាំងយ៉ូវ', NULL, NULL), (481, 56, 'Prasat', 'ប្រាសាទ', NULL, NULL), (482, 56, '<NAME>', 'ព្រែអំបិល', NULL, NULL), (483, 56, '<NAME>', 'ព្រែកគយ', NULL, NULL), (484, 56, '<NAME>', 'រកាខ្ពស់', NULL, NULL), (485, 56, 'Sa ang Phnum', 'ស្អាងភ្នំ', NULL, NULL), (486, 56, 'Setbou', 'សិត្បូ', NULL, NULL), (487, 56, '<NAME>', 'ស្វាយប្រទាល', NULL, NULL), (488, 56, '<NAME>', 'ស្វាយរលំ', NULL, NULL), (489, 56, '<NAME>', 'តាលន់', NULL, NULL), (490, 56, '<NAME>', 'ត្រើយស្លា', NULL, NULL), (491, 56, '<NAME>', 'ទឹកវិល', NULL, NULL), (492, 57, 'Kampong Phnum', 'កំពង់ភ្នំ', NULL, NULL), (493, 57, '<NAME>', 'ក្អមសំណ', NULL, NULL), (494, 57, '<NAME>', 'ខ្ពបអាទាវ', NULL, NULL), (495, 57, '<NAME> ', 'ពាមរាំង', NULL, NULL), (496, 57, '<NAME>', 'ព្រែកដាច់', NULL, NULL), (497, 57, '<NAME>', 'ព្រែកទន្លាប់', NULL, NULL), (498, 57, 'Sandar', 'សណ្ដារ', NULL, NULL), (499, 58, 'Ta Kdol', 'តាក្ដុល', NULL, NULL), (500, 58, '<NAME>', 'ព្រែកឫស្សី', NULL, NULL), (501, 58, '<NAME>', 'ដើមមៀន', NULL, NULL), (502, 58, 'Ta Khmao', 'តាខ្មៅ', NULL, NULL), (503, 58, '<NAME>', 'ព្រែកហូរ', NULL, NULL), (504, 58, '<NAME>', 'កំពង់សំណាញ់', NULL, NULL), (505, 58, '<NAME>', 'ស្វាយរលំ', NULL, NULL), (506, 58, 'Setbou', 'សិត្បូ', NULL, NULL), (507, 58, '<NAME>', 'រកាខ្ពស់', NULL, NULL), (508, 58, '<NAME>', 'កោះអន្លង់ចិន', NULL, NULL), (509, 59, '<NAME>', 'បន្ទាយដែក', NULL, NULL), (510, 59, '<NAME>', 'ឈើទាល', NULL, NULL), (511, 59, '<NAME>', 'ដីឥដ្ឋ', NULL, NULL), (512, 59, '<NAME>', 'កំពង់ស្វាយ', NULL, NULL), (513, 59, 'Kokir', 'គគីរ', NULL, NULL), (514, 59, '<NAME>', 'គគីរធំ', NULL, NULL), (515, 59, '<NAME>', 'ភូមិធំ', NULL, NULL), (516, 59, '<NAME>', 'សំរោងធំ', NULL, NULL), (517, 60, 'Chhveang', 'ឈ្វាំង', NULL, NULL), (518, 60, '<NAME>', 'ជ្រៃលាស់', NULL, NULL), (519, 60, '<NAME>', 'កំពង់ហ្លួង', NULL, NULL), (520, 60, '<NAME>', 'កំពង់អុស', NULL, NULL), (521, 60, '<NAME>', 'កោះចិន', NULL, NULL), (522, 60, '<NAME>', 'ភ្នំបាត', NULL, NULL), (523, 60, '<NAME>', 'ពញាឮ', NULL, NULL), (524, 60, '<NAME>', 'ព្រែកតាទែន', NULL, NULL), (525, 60, '<NAME>', 'ផ្សារដែក', NULL, NULL), (526, 60, '<NAME>', 'ទំនប់ធំ', NULL, NULL), (527, 60, 'Vihear Luong', 'វិហារហ្លួង', NULL, NULL), (528, 61, 'Ariyaksatr', 'អរិយក្សត្រ', NULL, NULL), (529, 61, 'Barong', 'បារុង', NULL, NULL), (530, 61, '<NAME>', 'បឹងគ្រំ', NULL, NULL), (531, 61, '<NAME>', 'កោះកែវ', NULL, NULL), (532, 61, '<NAME>', 'កោះរះ', NULL, NULL), (533, 61, 'L<NAME>', 'ល្វាសរ', NULL, NULL), (534, 61, '<NAME>', 'ពាមឧកញ៉ាអុង', NULL, NULL), (535, 61, '<NAME>', 'ភូមិធំ', NULL, NULL), (536, 61, '<NAME>', 'ព្រែកក្មេង', NULL, NULL), (537, 61, '<NAME>', 'ព្រែករៃ', NULL, NULL), (538, 61, '<NAME>', 'ព្រែកឫស្សី', NULL, NULL), (539, 61, 'Sombour', 'សំបួរ', NULL, NULL), (540, 61, 'Sarikakeo', 'សារិកាកែវ', NULL, NULL), (541, 61, '<NAME>', 'ថ្មគរ', NULL, NULL), (542, 61, '<NAME>', 'ទឹកឃ្លាំង', NULL, NULL), (543, 62, '<NAME>', 'បាក់ដាវ', NULL, NULL), (544, 62, '<NAME>', 'ជ័យធំ', NULL, NULL), (545, 62, '<NAME>', 'កំពង់ចំលង', NULL, NULL), (546, 62, '<NAME>', 'កោះចូរ៉ាម', NULL, NULL), (547, 62, '<NAME>', 'កោះឧកញ៉ាតី', NULL, NULL), (548, 62, '<NAME>', 'ព្រះប្រសប់', NULL, NULL), (549, 62, '<NAME>', 'ព្រែកអំពិល', NULL, NULL), (550, 62, ' <NAME>', 'ព្រែកលួង', NULL, NULL), (551, 62, '<NAME>', 'ព្រែកតាកូវ', NULL, NULL), (552, 62, '<NAME>', 'ព្រែកតាមាក់', NULL, NULL), (553, 62, '<NAME>', 'ពុកឫស្សី', NULL, NULL), (554, 62, '<NAME>', 'រកាជន្លឹង', NULL, NULL), (555, 62, 'Sanlung', 'សន្លុង', NULL, NULL), (556, 62, 'Sithor', 'ស៊ីធរ', NULL, NULL), (557, 62, '<NAME>', 'ស្វាយជ្រុំ', NULL, NULL), (558, 62, '<NAME>', 'ស្វាយរមៀត', NULL, NULL), (559, 62, '<NAME>', 'តាឯក', NULL, NULL), (560, 62, '<NAME>', 'វិហារសួគ៌', NULL, NULL), (561, 88, '<NAME>', 'បាក់ស្នា', NULL, NULL), (562, 88, 'Ballangk', 'បល្ល័ង្ក', NULL, NULL), (563, 88, 'Baray', 'បារាយណ៍', NULL, NULL), (564, 88, 'Boeng', 'បឹង', NULL, NULL), (565, 88, '<NAME>', 'ចើងដើង', NULL, NULL), (566, 88, 'Chraneang', 'ច្រនាង', NULL, NULL), (567, 88, '<NAME>', 'ឈូកខ្សាច់', NULL, NULL), (568, 88, '<NAME>', 'ចុងដូង', NULL, NULL), (569, 88, 'Chrolong', 'ជ្រលង', NULL, NULL), (570, 88, '<NAME> ', 'គគីធំ', NULL, NULL), (571, 88, 'Krava', 'ក្រវ៉ា', NULL, NULL), (572, 88, '<NAME>', 'អណ្ដូងពោធិ៍', NULL, NULL), (573, 88, 'Pongro', 'ពង្រ', NULL, NULL), (574, 88, '<NAME>', 'សូយោង', NULL, NULL), (575, 88, 'Sralau', 'ស្រឡៅ', NULL, NULL), (576, 88, '<NAME>', 'ស្វាយភ្លើង', NULL, NULL), (577, 88, '<NAME>', 'ត្នោតជុំ', NULL, NULL), (578, 88, 'Triel', 'ទ្រៀល', NULL, NULL), (579, 89, '<NAME>', 'ដំរីជាន់ខ្លា', NULL, NULL), (580, 89, '<NAME>', 'កំពង់ធំ', NULL, NULL), (581, 89, '<NAME>', 'កំពង់រទេះ', NULL, NULL), (582, 89, '<NAME>', 'អូរកន្ធរ', NULL, NULL), (583, 89, 'Kampong', 'កំពង់ក្របៅ', NULL, NULL), (584, 89, '<NAME>', 'ព្រៃតាហ៊ូ', NULL, NULL), (585, 89, '<NAME>', 'អាចារ្យលាក់', NULL, NULL), (586, 89, 'Srayov', 'ស្រយ៉ូវ', NULL, NULL), (587, 90, '<NAME> ', 'ឈើទាល', NULL, NULL), (588, 90, '<NAME>', 'ដងកាំបិត', NULL, NULL), (589, 90, 'Klaeng ', 'ក្លែង', NULL, NULL), (590, 90, 'Mean Rith', 'មានរិទ្ធ', NULL, NULL), (591, 90, 'Mean Chey', 'មានជ័យ', NULL, NULL), (592, 90, 'Ngan ', 'ងន', NULL, NULL), (593, 90, 'Sandan', 'សណ្ដាន់', NULL, NULL), (594, 90, 'Sochet', 'សុចិត្រ', NULL, NULL), (595, 90, '<NAME>', 'ទំរីង', NULL, NULL), (596, 91, '<NAME>', 'បន្ទាយស្ទោង', NULL, NULL), (597, 91, '<NAME>', 'ចំណាក្រោម', NULL, NULL), (598, 91, '<NAME>', 'ចំណាលើ', NULL, NULL), (599, 91, '<NAME>', 'កំពង់ចិនជើង', NULL, NULL), (600, 91, '<NAME>', 'ម្សាក្រង', NULL, NULL), (601, 91, '<NAME>', 'ពាមបាង', NULL, NULL), (602, 91, 'Pralay', 'ប្រឡាយ', NULL, NULL), (603, 91, '<NAME>', 'ព្រះដំរី', NULL, NULL), (604, 91, '<NAME>', 'រុងរឿង', NULL, NULL), (605, 91, 'Samprouch', 'សំព្រោជ', NULL, NULL), (606, 91, 'Trea', 'ទ្រា', NULL, NULL), (607, 92, 'Doung ', 'ដូង', NULL, NULL), (608, 92, 'Kraya ', 'ក្រយា', NULL, NULL), (609, 92, '<NAME>', 'ផាន់ញើម', NULL, NULL), (610, 92, 'Sakream ', 'សាគ្រាម', NULL, NULL), (611, 92, '<NAME>', 'សាលាវិស័យ', NULL, NULL), (612, 92, 'Sameakki', 'សាមគ្គី', NULL, NULL), (613, 92, '<NAME>', 'ទួលគ្រើល', NULL, NULL), (614, 93, '<NAME>', 'បឹងល្វា', NULL, NULL), (615, 93, 'Chroab ', 'ជ្រាប់', NULL, NULL), (616, 93, '<NAME> ', 'កំពង់ថ្ម', NULL, NULL), (617, 93, ' Kakaoh ', 'កកោះ', NULL, NULL), (618, 93, 'Kraya ', 'ក្រយា', NULL, NULL), (619, 93, 'Pnov ', 'ព្នៅ', NULL, NULL), (620, 93, 'Prasat ', 'ប្រាសាទ', NULL, NULL), (621, 93, 'Tang Krasang', 'តាំងក្រសាំង', NULL, NULL), (622, 93, 'Ti Pou', 'ទីពោ', NULL, NULL), (623, 93, '<NAME>', 'ត្បូងក្រពើ', NULL, NULL), (624, 94, 'Chhuk', 'ឈូក', NULL, NULL), (625, 94, 'Koul', 'គោល', NULL, NULL), (626, 94, 'Sambour', 'សំបូរណ៍', NULL, NULL), (627, 94, 'Sraeung', 'ស្រើង', NULL, NULL), (628, 94, 'Tang Krasau', 'តាំងក្រសៅ', NULL, NULL), (629, 95, 'Chey', 'ជ័យ', NULL, NULL), (630, 95, 'Damrei Slab', 'ដំរីស្លាប់', NULL, NULL), (631, 95, 'Kamp<NAME>', 'កំពង់គោ', NULL, NULL), (632, 95, '<NAME>', 'កំពង់ស្វាយ', NULL, NULL), (633, 95, 'Nipech', 'នីពេជ', NULL, NULL), (634, 95, '<NAME>', 'ផាត់សណ្ដាយ', NULL, NULL), (635, 95, '<NAME>', 'សាន់គ', NULL, NULL), (636, 95, 'Tbaeng', 'ត្បែង', NULL, NULL), (637, 95, 'Trapeang', 'ត្រពាំងឫស្សី', NULL, NULL), (638, 95, '<NAME>', 'ក្ដីដូង', NULL, NULL), (639, 95, '<NAME>', 'ព្រៃគុយ', NULL, NULL), (640, 114, 'Chhlong', 'ឆ្លូង', NULL, NULL), (641, 114, '<NAME>', 'ដំរីផុង', NULL, NULL), (642, 114, '<NAME>', 'ហាន់ជ័យ', NULL, NULL), (643, 114, 'Kampong Domrei', 'កំពង់ដំរី', NULL, NULL), (644, 114, 'Kanhchor', 'កញ្ជរ', NULL, NULL), (645, 114, '<NAME>', 'ខ្សាច់អណ្ដែត', NULL, NULL), (646, 114, 'Pongro', 'ពង្រ', NULL, NULL), (647, 114, '<NAME>', 'ព្រែកសាម៉ាន់', NULL, NULL), (648, 115, 'Kantout', 'កន្ទួត', NULL, NULL), (649, 115, '<NAME>', 'ថ្មអណ្តើក', NULL, NULL), (650, 115, '<NAME>', 'កោះច្រែង', NULL, NULL), (651, 115, 'Sambok', 'សំបុក', NULL, NULL), (652, 115, '<NAME>', 'គោលាប់', NULL, NULL), (653, 115, 'Thmei', 'ថ្មី', NULL, NULL), (654, 115, 'Dar', 'ដា', NULL, NULL), (655, 115, '<NAME>', 'បុសលាវ', NULL, NULL), (656, 115, 'Changkrorng', 'ចង្ក្រង់', NULL, NULL), (657, 115, '<NAME>', 'ថ្មគ្រែ', NULL, NULL), (658, 116, '<NAME>', 'កោះត្រង់', NULL, NULL), (659, 116, 'Krokor', 'ក្រកូរ', NULL, NULL), (660, 116, 'Kratie', 'ក្រចេះ', NULL, NULL), (661, 116, 'Ou Russei', 'អូរឬស្សី', NULL, NULL), (662, 116, '<NAME>', 'រកាកណ្តាល', NULL, NULL), (663, 117, '<NAME>', 'ក្បាលដំរី', NULL, NULL), (664, 117, '<NAME>', 'កោះខ្ញែរ', NULL, NULL), (665, 117, '<NAME>', 'អូរគ្រៀង', NULL, NULL), (666, 117, '<NAME>', 'រលួសមានជ័យ', NULL, NULL), (667, 117, '<NAME>', 'កំពង់ចាម', NULL, NULL), (668, 117, '<NAME>', 'បឹងចារ', NULL, NULL), (669, 117, 'Sombo', 'សំបូរ', NULL, NULL), (670, 117, 'Sandann', 'សណ្តាន់', NULL, NULL), (671, 117, '<NAME>', 'ស្រែជិះ', NULL, NULL), (672, 117, 'Vadhnak', 'វឌ្ឍនៈ', NULL, NULL), (673, 118, 'Chambok', 'ចំបក់', NULL, NULL), (674, 118, '<NAME>', 'ជ្រោយបន្ទាយ', NULL, NULL), (675, 118, '<NAME>', 'កំពង់គរ', NULL, NULL), (676, 118, '<NAME>', 'ព្រែកប្រសព្', NULL, NULL), (677, 118, '<NAME>', 'ឫស្សីកែវ', NULL, NULL), (678, 118, 'Soab', 'សោប', NULL, NULL), (679, 118, 'Tamao', 'តាម៉ៅ', NULL, NULL), (680, 119, 'Khseum', 'ឃ្សឹម', NULL, NULL), (681, 119, '<NAME>', 'ពីរធ្នូ', NULL, NULL), (682, 119, 'Snoul', 'ស្នួល', NULL, NULL), (683, 119, '<NAME>', 'ស្រែចារ', NULL, NULL), (684, 119, '<NAME>', 'ស្វាយជ្រះ', NULL, NULL), (685, 133, '<NAME>', 'ស្អាង', NULL, NULL), (686, 133, '<NAME>', 'តស៊ូ', NULL, NULL), (687, 133, 'Kchorng', 'ខ្យង', NULL, NULL), (688, 133, 'Chrach', 'ច្រាច់', NULL, NULL), (689, 133, 'Thmea', 'ធ្មា', NULL, NULL), (690, 133, 'Putrea', 'ពុទ្រា', NULL, NULL), (691, 134, 'ស្រអែម', 'ជាំក្សាន្ត', NULL, NULL), (692, 134, '<NAME>', 'ទឹកក្រហម', NULL, NULL), (693, 134, '<NAME>', 'ព្រីងធំ', NULL, NULL), (694, 134, '<NAME>', 'រំដោះស្រែ', NULL, NULL), (695, 134, 'Yeang', 'យាង', NULL, NULL), (696, 134, 'Kantout', 'កន្ទួត', NULL, NULL), (697, 134, 'Sraem', 'ស្រអែម', NULL, NULL), (698, 134, 'Morodok', 'មរតក', NULL, NULL), (699, 135, 'Robeab', 'របៀប', NULL, NULL), (700, 135, 'Reaksmey', 'រស្មី', NULL, NULL), (701, 135, 'Rohas', 'រហ័ស', NULL, NULL), (702, 135, '<NAME>', 'រុងរឿង', NULL, NULL), (703, 135, '<NAME>', 'រីករាយ', NULL, NULL), (704, 135, '<NAME>', 'រួសរាន់', NULL, NULL), (705, 135, 'Ratanak', 'រតនៈ', NULL, NULL), (706, 135, '<NAME>', 'រៀបរយ', NULL, NULL), (707, 135, 'Reaksa', 'រក្សា', NULL, NULL), (708, 135, 'Romdors', 'រំដោះ', NULL, NULL), (709, 135, 'Rumtum', 'រមទម', NULL, NULL), (710, 135, 'Romniy', 'រម្មណីយ', NULL, NULL), (711, 136, '<NAME>', 'រអាង', NULL, NULL), (712, 136, '<NAME>', 'ភ្នំត្បែងមួយ', NULL, NULL), (713, 136, 'Sdao', 'ស្តៅ', NULL, NULL), (714, 136, 'Ranakseh', 'រណសិរ្ស', NULL, NULL), (715, 136, 'Chomreun', 'ចំរើន', NULL, NULL), (716, 137, '<NAME>', 'ឆែបមួយ', NULL, NULL), (717, 137, '<NAME>', 'ឆែបពីរ', NULL, NULL), (718, 137, '<NAME>', 'សង្កែមួយ', NULL, NULL), (719, 137, '<NAME>', 'សង្កែពីរ', NULL, NULL), (720, 137, '<NAME>', 'ម្លូព្រៃមួយ', NULL, NULL), (721, 137, '<NAME>', 'ម្លូព្រៃពីរ', NULL, NULL), (722, 137, '<NAME>', 'កំពង់ស្រឡៅមួយ', NULL, NULL), (723, 137, '<NAME>', 'កំពង់ស្រឡៅពីរ', NULL, NULL), (724, 138, '<NAME>', 'គូលែនត្បូង', NULL, NULL), (725, 138, '<NAME>', 'គូលែនជើង', NULL, NULL), (726, 138, 'Thmei', 'ថ្មី', NULL, NULL), (727, 138, '<NAME>', 'ភ្នំពេញ', NULL, NULL), (728, 138, '<NAME>', 'ភ្នំត្បែងពីរ', NULL, NULL), (729, 138, 'Sroyong', 'ស្រយង់', NULL, NULL), (730, 139, '<NAME>', 'កំពង់ប្រណោក', NULL, NULL), (731, 139, '<NAME>', 'ប៉ាលហាល', NULL, NULL), (732, 139, '<NAME>', 'ឈានមុខ', NULL, NULL), (733, 139, 'Pou', 'ពោធិ៍', NULL, NULL), (734, 139, 'Bromeru', 'ប្រមេរុ', NULL, NULL), (735, 139, '<NAME>', 'ព្រះឃ្លាំង', NULL, NULL), (736, 177, 'Komphun', 'កំភុន', NULL, NULL), (737, 177, '<NAME>', 'ក្បាលរមាស', NULL, NULL), (738, 177, 'Phluk', 'ភ្លុក', NULL, NULL), (739, 177, '<NAME>houy', 'សាមឃួយ', NULL, NULL), (740, 177, 'Sdau', 'ស្ដៅ', NULL, NULL), (741, 177, 'Srae Kor', 'ស្រែគរ', NULL, NULL), (742, 177, 'Ta Lat', 'តាឡាត', NULL, NULL), (743, 178, 'Koh Preah', 'កោះព្រះ', NULL, NULL), (744, 178, 'Koh Sompeay', 'កោះសំពាយ', NULL, NULL), (745, 178, 'Koh Srolay', 'កោះស្រឡាយ', NULL, NULL), (746, 178, 'Ou Mreah', 'អូរម្រះ', NULL, NULL), (747, 178, 'Ou Russei Kandal', 'អូរឫស្សីកណ្តាល', NULL, NULL), (748, 178, 'Siem Bouk', 'សៀមបូក', NULL, NULL), (749, 178, 'Srae Krasang', 'ស្រែក្រសាំង', NULL, NULL), (750, 178, 'Praek Meas', 'ព្រែកមាស', NULL, NULL), (751, 178, 'Sekong', 'សេកុង', NULL, NULL), (752, 178, 'Santipheap', 'សន្តិភាព', NULL, NULL), (753, 178, 'S<NAME>', 'ស្រែសំបូរ', NULL, NULL), (754, 178, '<NAME>', 'ថ្មកែវ', NULL, NULL), (755, 179, '<NAME>', 'អន្លង់ភេ', NULL, NULL), (756, 179, '<NAME>', 'ចំការលើ', NULL, NULL), (757, 179, '<NAME>', 'កាំងចាម', NULL, NULL), (758, 179, '<NAME>', 'កោះស្នែង', NULL, NULL), (759, 179, 'Ou Rai', 'អូររៃ', NULL, NULL), (760, 179, 'Ou Svay', 'អូរស្វាយ', NULL, NULL), (761, 179, '<NAME>', 'ព្រះរំកិល', NULL, NULL), (762, 179, 'Som Ang', 'សំអាង', NULL, NULL), (763, 179, 'Srae Russei', 'ស្រែឫស្សី', NULL, NULL), (764, 179, '<NAME>', 'ថាឡាបរិវ៉ាត់', NULL, NULL), (765, 179, '<NAME>', 'អន្លង់ជ្រៃ', NULL, NULL), (766, 180, '<NAME>', 'ស្ទឹងត្រែង', NULL, NULL), (767, 180, '<NAME>', 'ស្រះឫស្សី', NULL, NULL), (768, 180, '<NAME>', 'ព្រះបាទ', NULL, NULL), (769, 180, 'Sammaki', 'សាមគ្គី', NULL, NULL), (770, 63, '<NAME>', 'បន្ទាយនាង', NULL, NULL), (771, 63, '<NAME>', 'បត់ត្រង់', NULL, NULL), (772, 63, 'Chamnaom', 'ចំណោម', NULL, NULL), (773, 63, '<NAME>', 'គោកបល្ល័ង្គ', NULL, NULL), (774, 63, '<NAME>', 'គយម៉ែង', NULL, NULL), (775, 63, 'Ou Prasat', 'អូរប្រាសាទ', NULL, NULL), (776, 63, 'Ph<NAME>', 'ភ្នំតូច', NULL, NULL), (777, 63, '<NAME>', 'រហាត់ទឹក', NULL, NULL), (778, 63, '<NAME>', 'ឫស្សីក្រោក', NULL, NULL), (779, 63, 'Sambuor', 'សំបួរ', NULL, NULL), (780, 63, 'Soea', 'សឿ', NULL, NULL), (781, 63, '<NAME> ', 'ស្រះរាំង', NULL, NULL), (782, 63, '<NAME>', 'តាឡំ', NULL, NULL), (783, 64, '<NAME>', 'ឈ្នួរមានជ័យ', NULL, NULL), (784, 64, '<NAME>', 'ជប់វារី', NULL, NULL), (785, 64, '<NAME>', 'ភ្នំលៀប', NULL, NULL), (786, 64, 'Prasat', 'ប្រាសាទ', NULL, NULL), (787, 64, '<NAME>', 'ព្រះនេត្រព្រះ', NULL, NULL), (788, 64, 'Rohal', 'រហាល', NULL, NULL), (789, 64, '<NAME>', 'ទានកាំ', NULL, NULL), (790, 64, '<NAME>', 'ទឹកជោរ', NULL, NULL), (791, 65, '<NAME>', 'បុស្បូវ', NULL, NULL), (792, 65, '<NAME>', 'កំពង់ស្វាយ', NULL, NULL), (793, 65, '<NAME>', 'កោះពងសត្វ', NULL, NULL), (794, 65, 'Mkak', 'ម្កាក់', NULL, NULL), (795, 65, '<NAME>', 'អូរអំបិល', NULL, NULL), (796, 65, 'Phniet', 'ភ្នៀត', NULL, NULL), (797, 65, '<NAME>', 'ព្រះពន្លា', NULL, NULL), (798, 65, '<NAME>', 'ទឹកថ្លា', NULL, NULL), (799, 66, 'Phkoam', 'ផ្គាំ', NULL, NULL), (800, 66, 'Sarongk', 'សារង្គ', NULL, NULL), (801, 66, '<NAME>', 'ស្លក្រាម', NULL, NULL), (802, 66, '<NAME>', 'ស្វាយចេក', NULL, NULL), (803, 66, '<NAME>', 'តាបែន', NULL, NULL), (804, 66, 'Ta Phou', 'តាផូ', NULL, NULL), (805, 66, 'Treas', 'ទ្រាស', NULL, NULL), (806, 66, 'Roluos', 'រលួស', NULL, NULL), (807, 67, 'Changha', 'ចង្ហា', NULL, NULL), (808, 67, 'Koub', 'កូប', NULL, NULL), (809, 67, 'Kuttasat', 'គុត្តសត', NULL, NULL), (810, 67, 'Nimitt', 'និមិត្ត', NULL, NULL), (811, 67, 'Samraong', 'សំរោង', NULL, NULL), (812, 67, 'Souphi', 'សូភី', NULL, NULL), (813, 67, 'Soengh', 'សឹង្ហ', NULL, NULL), (814, 67, '<NAME>', 'ប៉ោយប៉ែត', NULL, NULL), (815, 67, '<NAME>', 'អូរបីជាន់', NULL, NULL), (816, 68, '<NAME>', 'បន្ទាយឆ្មារ', NULL, NULL), (817, 68, '<NAME>', 'គោករមៀត', NULL, NULL), (818, 68, '<NAME>', 'ថ្មពួក', NULL, NULL), (819, 68, '<NAME>', 'គោកកឋិន', NULL, NULL), (820, 68, '<NAME>', 'គំរូ', NULL, NULL), (821, 68, 'Kumru', 'ភូមិថ្មី', NULL, NULL), (822, 69, 'Bo<NAME>', 'បឹងបេង', NULL, NULL), (823, 69, 'Malai', 'ម៉ាឡៃ', NULL, NULL), (824, 69, 'Ou Sampor', 'អូរសំព័រ', NULL, NULL), (825, 69, 'Ou Sralau', 'អូរស្រឡៅ', NULL, NULL), (826, 69, 'Tuol Pongro', 'ទួលពង្រ', NULL, NULL), (827, 69, 'Ta Kong', 'តាគង់', NULL, NULL), (828, 70, 'Changha', 'ចង្ហា', NULL, NULL), (829, 70, 'Koub', 'កូប', NULL, NULL), (830, 70, 'Kuttasat', 'គុត្តសត', NULL, NULL), (831, 70, 'Nimitt', 'និមិត្ត', NULL, NULL), (832, 70, 'Samraong', 'សំរោង', NULL, NULL), (833, 70, 'Souphi', 'សូភី', NULL, NULL), (834, 70, 'Soengh', 'សឹង្ហ', NULL, NULL), (835, 70, '<NAME>', 'ប៉ោយប៉ែត', NULL, NULL), (836, 70, '<NAME>', 'អូរបីជាន់', NULL, NULL), (837, 71, '<NAME>', 'ណាំតៅ', NULL, NULL), (838, 71, '<NAME>', 'ប៉ោយចារ', NULL, NULL), (839, 71, 'Ponley', 'ពន្លៃ', NULL, NULL), (840, 71, '<NAME>', 'ស្ពានស្រែង', NULL, NULL), (841, 71, '<NAME>', 'ស្រះជីក', NULL, NULL), (842, 71, '<NAME>', 'ភ្នំដី', NULL, NULL), (843, 72, '<NAME>', 'អញ្ចាញរូង', NULL, NULL), (844, 72, '<NAME>', 'ឆ្នុកទ្រូ', NULL, NULL), (845, 72, 'Chak', 'ចក', NULL, NULL), (846, 72, '<NAME>', 'ខុនរ៉ង', NULL, NULL), (847, 72, '<NAME>', 'កំពង់ព្រះគគីរ', NULL, NULL), (848, 72, 'Melum', 'មេលំ', NULL, NULL), (849, 72, 'Phsar', 'ផ្សារ', NULL, NULL), (850, 72, '<NAME>', 'ពេជ្រចង្វារ', NULL, NULL), (851, 72, 'Popel', 'ពពេល', NULL, NULL), (852, 72, 'Ponley', 'ពន្លៃ', NULL, NULL), (853, 72, '<NAME>', 'ត្រពាំងចាន់', NULL, NULL), (854, 73, '<NAME>', 'ផ្សារឆ្នាំង', NULL, NULL), (855, 73, '<NAME>', 'កំពង់ឆ្នាំង', NULL, NULL), (856, 73, '<NAME>', 'ប្អេរ', NULL, NULL), (857, 73, 'Khsam', 'ខ្សាម', NULL, NULL), (858, 74, '<NAME>', 'អំពិលទឹក', NULL, NULL), (859, 74, '<NAME>', 'ឈូកស', NULL, NULL), (860, 74, 'Chres', 'ច្រេស', NULL, NULL), (861, 74, '<NAME>', 'កំពង់ត្រឡាច', NULL, NULL), (862, 74, 'Longveaek', 'លង្វែក', NULL, NULL), (863, 74, '<NAME>', 'អូរឬស្សី', NULL, NULL), (864, 74, 'Peani', 'ពានី', NULL, NULL), (865, 74, 'Saeb', 'សែប', NULL, NULL), (866, 74, '<NAME>', 'តាជេស', NULL, NULL), (867, 74, '<NAME>', 'ថ្មឥដ្ឋ', NULL, NULL), (868, 75, '<NAME>', 'ឈានឡើង', NULL, NULL), (869, 75, '<NAME>', 'ខ្នាឆ្មារ', NULL, NULL), (870, 75, '<NAME>', 'រាំល្វា', NULL, NULL), (871, 75, 'Peam', 'ពាម', NULL, NULL), (872, 75, 'Sedthei', 'សេដ្ឋី', NULL, NULL), (873, 75, 'Svay', 'ស្វាយ', NULL, NULL), (874, 75, '<NAME>', 'ស្វាយជុក', NULL, NULL), (875, 75, '<NAME>', 'ត្បែងខ្ពស់', NULL, NULL), (876, 75, '<NAME>', 'ធ្លកវៀន', NULL, NULL), (877, 76, 'Chranouk', 'ច្រណូក', NULL, NULL), (878, 76, 'Dar', 'ដារ', NULL, NULL), (879, 76, '<NAME>', 'កំពង់ហៅ', NULL, NULL), (880, 76, '<NAME>', 'ផ្លូវទូក', NULL, NULL), (881, 76, 'Pou', 'ពោធិ៍', NULL, NULL), (882, 76, '<NAME>', 'ប្រឡាយមាស', NULL, NULL), (883, 76, '<NAME>', 'សំរោងសែន', NULL, NULL), (884, 76, '<NAME>', 'ស្វាយរំពារ', NULL, NULL), (885, 76, 'Trangel', 'ត្រងិល', NULL, NULL), (886, 77, '<NAME>', 'ជលសា', NULL, NULL), (887, 77, '<NAME>', 'កោះថ្កូវ', NULL, NULL), (888, 77, '<NAME>', 'កំពង់អុស', NULL, NULL), (889, 77, '<NAME>', 'ពាមឆ្កោក', NULL, NULL), (890, 77, '<NAME>', 'ព្រៃគ្រី', NULL, NULL), (891, 78, '<NAME>', 'អណ្តូងស្នាយ', NULL, NULL), (892, 78, '<NAME>', 'បន្ទាយព្រាល', NULL, NULL), (893, 78, '<NAME>', 'ជើងគ្រាវ', NULL, NULL), (894, 78, '<NAME>', 'ជ្រៃបាក់', NULL, NULL), (895, 78, '<NAME>', 'គោកបន្ទាយ', NULL, NULL), (896, 78, '<NAME>', 'ក្រាំងលាវ', NULL, NULL), (897, 78, 'Pongro', 'ពង្រ', NULL, NULL), (898, 78, 'Prasneb', 'ប្រស្នឹប', NULL, NULL), (899, 78, '<NAME>', 'ព្រៃមូល', NULL, NULL), (900, 78, '<NAME>', 'រលាប្អៀរ', NULL, NULL), (901, 78, '<NAME>', 'ស្រែថ្មី', NULL, NULL), (902, 78, '<NAME>', 'ស្វាយជ្រុំ', NULL, NULL), (903, 78, '<NAME>', 'ទឹកហូត', NULL, NULL), (904, 79, 'Akphivoadth ', 'អភិវឌ្ឍន៍', NULL, NULL), (905, 79, 'Chieb ', 'ជៀប', NULL, NULL), (906, 79, 'Chaong Maong', 'ចោងម៉ោង', NULL, NULL), (907, 79, 'Kbal Tuek', 'ក្បាលទឹក', NULL, NULL), (908, 79, 'Khlong Popok', 'ខ្លុងពពក', NULL, NULL), (909, 79, 'Krang Skear', 'រាំងស្គារ', NULL, NULL), (910, 79, 'Tang Krasang', 'តាំងក្រសាំង', NULL, NULL), (911, 79, 'Tuol Khpos', 'ទួលខ្ពស់', NULL, NULL); /*!40000 ALTER TABLE `communes` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.districts DROP TABLE IF EXISTS `districts`; CREATE TABLE IF NOT EXISTS `districts` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `province_id` int(11) DEFAULT NULL, `name_en` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `name_kh` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=198 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.districts: 197 rows /*!40000 ALTER TABLE `districts` DISABLE KEYS */; INSERT INTO `districts` (`id`, `province_id`, `name_en`, `name_kh`, `created_at`, `updated_at`) VALUES (1, 1, '<NAME>', 'ឫស្សីកែវ', NULL, NULL), (2, 1, 'Saensokh', 'សែនសុខ', NULL, NULL), (3, 1, '<NAME>', 'ពោធិសែនជ័យ', NULL, NULL), (4, 1, '<NAME>', 'ជ្រោយចង្វារ', NULL, NULL), (5, 1, '<NAME>', 'ព្រែកភ្នៅ', NULL, NULL), (6, 1, '<NAME>', 'ច្បារអំពៅ', NULL, NULL), (7, 1, '<NAME>', 'ដូនពេញ', NULL, NULL), (8, 1, '<NAME>', '៧មករា', NULL, NULL), (9, 1, '<NAME>', 'ទួលគោក', NULL, NULL), (10, 1, 'Dangkao', 'ដង្កោ', NULL, NULL), (11, 1, '<NAME>', 'មានជ័យ', NULL, NULL), (12, 1, '<NAME>', 'ចំការមន', NULL, NULL), (13, 2, '<NAME>', 'ព្រះសីហនុ', NULL, NULL), (14, 2, '<NAME>', 'ព្រៃនប់', NULL, NULL), (15, 2, '<NAME>', 'ស្ទឹងហាវ', NULL, NULL), (16, 2, '<NAME>', 'កំពង់សីលា', NULL, NULL), (17, 3, '<NAME>', 'កំពង់ចាម', NULL, NULL), (18, 3, '<NAME>', 'កំពង់សៀម', NULL, NULL), (19, 3, 'KangMeas', 'កងមាស', NULL, NULL), (20, 3, '<NAME>', 'កោះសុទិន', NULL, NULL), (21, 3, '<NAME>', 'ព្រៃឈរ', NULL, NULL), (22, 3, '<NAME>', 'ស្រីសន្ធរ', NULL, NULL), (23, 3, '<NAME>', 'ស្ទឹងត្រង់', NULL, NULL), (24, 3, 'Batheay', 'បាធាយ', NULL, NULL), (25, 3, '<NAME>', 'ចំការលើ', NULL, NULL), (26, 3, '<NAME>', 'ជើងព្រៃ', NULL, NULL), (27, 4, '<NAME>', 'អង្គរជុំ', NULL, NULL), (28, 4, '<NAME>', 'អង្គរធំ', NULL, NULL), (29, 4, '<NAME>', 'បន្ទាយស្រី', NULL, NULL), (30, 4, '<NAME>', 'ជីក្រែង', NULL, NULL), (31, 4, 'Kralanh', 'ក្រឡាញ់', NULL, NULL), (32, 4, 'Pouk', 'ពួក', NULL, NULL), (33, 4, '<NAME>', 'ប្រាសាទបាគង', NULL, NULL), (34, 4, '<NAME>', 'ក្រុងសៀមរាប', NULL, NULL), (35, 4, '<NAME>', 'សុទ្រនិគមន៍', NULL, NULL), (36, 4, '<NAME>', 'ស្រីស្នំ', NULL, NULL), (37, 4, '<NAME>', 'ស្វាយលើ', NULL, NULL), (38, 4, 'Varin', 'វ៉ារិន', NULL, NULL), (39, 5, 'Banan', 'បាណន់', NULL, NULL), (40, 5, '<NAME>', 'ថ្មរគោល', NULL, NULL), (41, 5, '<NAME>', 'ក្រុងបាត់ដំបង', NULL, NULL), (42, 5, 'Bavel', 'បវេល', NULL, NULL), (43, 5, '<NAME>', 'ឯកភ្នំ', NULL, NULL), (44, 5, '<NAME>', 'មោង រស្សី', NULL, NULL), (45, 5, '<NAME>', 'រតនាមណ្ឌល', NULL, NULL), (46, 5, 'Sangkae', 'សង្កៃរ', NULL, NULL), (47, 5, 'Samlout', 'សំឡូត', NULL, NULL), (48, 5, '<NAME>', 'សំពៅលូន', NULL, NULL), (49, 5, '<NAME>', 'ភ្នំព្រឹក', NULL, NULL), (50, 5, 'Kamrieng', 'កំរៀង', NULL, NULL), (51, 5, '<NAME>', 'គាស់ក្រឡ', NULL, NULL), (52, 5, '<NAME>', 'រុក្ខគីរី', NULL, NULL), (53, 6, 'Kandal Stueng', '', NULL, NULL), (54, 6, '<NAME>', '', NULL, NULL), (55, 6, '<NAME>', '', NULL, NULL), (56, 6, '<NAME>', '', NULL, NULL), (57, 6, '<NAME>', '', NULL, NULL), (58, 6, '<NAME>', '', NULL, NULL), (59, 6, '<NAME>', '', NULL, NULL), (60, 6, '<NAME>', '', NULL, NULL), (61, 6, '<NAME>', '', NULL, NULL), (62, 6, '<NAME>', '', NULL, NULL), (63, 7, '<NAME>', '', NULL, NULL), (64, 7, '<NAME>', '', NULL, NULL), (65, 7, '<NAME>', '', NULL, NULL), (66, 7, '<NAME>', '', NULL, NULL), (67, 7, '<NAME>', '', NULL, NULL), (68, 7, '<NAME>', '', NULL, NULL), (69, 7, 'Malai', '', NULL, NULL), (70, 7, '<NAME>', '', NULL, NULL), (71, 7, '<NAME>', '', NULL, NULL), (72, 8, 'Baribour', '', NULL, NULL), (73, 8, '<NAME>', '', NULL, NULL), (74, 8, '<NAME>', '', NULL, NULL), (75, 8, 'Sameakki', '', NULL, NULL), (76, 8, '<NAME>', '', NULL, NULL), (77, 8, '<NAME>', '', NULL, NULL), (78, 8, '<NAME>', '', NULL, NULL), (79, 8, '<NAME>', '', NULL, NULL), (80, 9, 'Basedth', '', NULL, NULL), (81, 9, '<NAME>', '', NULL, NULL), (82, 9, 'Odongk', '', NULL, NULL), (83, 9, '<NAME>', '', NULL, NULL), (84, 9, 'Aoral', '', NULL, NULL), (85, 9, '<NAME>', '', NULL, NULL), (86, 9, '<NAME>', '', NULL, NULL), (87, 9, 'Thpong', '', NULL, NULL), (88, 10, 'Baray', '', NULL, NULL), (89, 10, '<NAME>', '', NULL, NULL), (90, 10, 'Sandaan', '', NULL, NULL), (91, 10, 'Stoung', '', NULL, NULL), (92, 10, '<NAME>', '', NULL, NULL), (93, 10, 'Santuk', '', NULL, NULL), (94, 10, '<NAME>', '', NULL, NULL), (95, 10, '<NAME>', '', NULL, NULL), (96, 11, '<NAME>', '', NULL, NULL), (97, 11, 'Chhuk', '', NULL, NULL), (98, 11, '<NAME>', '', NULL, NULL), (99, 11, '<NAME>', '', NULL, NULL), (100, 11, '<NAME>', '', NULL, NULL), (101, 11, '<NAME>', '', NULL, NULL), (102, 11, '<NAME>', '', NULL, NULL), (103, 11, 'Kampot', '', NULL, NULL), (104, 12, '<NAME>', '', NULL, NULL), (105, 12, '<NAME>', '', NULL, NULL), (106, 12, '<NAME>', '', NULL, NULL), (107, 13, '<NAME>', '', NULL, NULL), (108, 13, '<NAME>', '', NULL, NULL), (109, 13, '<NAME>', '', NULL, NULL), (110, 13, '<NAME>', '', NULL, NULL), (111, 13, '<NAME>', '', NULL, NULL), (112, 13, '<NAME>', '', NULL, NULL), (113, 13, '<NAME>', '', NULL, NULL), (114, 14, 'Chhlong', '', NULL, NULL), (115, 14, '<NAME>', '', NULL, NULL), (116, 14, '<NAME>', '', NULL, NULL), (117, 14, 'Sombo', '', NULL, NULL), (118, 14, '<NAME>', '', NULL, NULL), (119, 14, 'Snoul', '', NULL, NULL), (120, 15, '<NAME>', '', NULL, NULL), (121, 15, '<NAME>', '', NULL, NULL), (122, 15, '<NAME>', '', NULL, NULL), (123, 15, '<NAME>', '', NULL, NULL), (124, 15, '<NAME>', '', NULL, NULL), (125, 16, '<NAME>', '', NULL, NULL), (126, 16, '<NAME>', '', NULL, NULL), (127, 16, '<NAME>', '', NULL, NULL), (128, 16, '<NAME>', '', NULL, NULL), (129, 16, '<NAME>', '', NULL, NULL), (130, 17, '<NAME>', '', NULL, NULL), (131, 17, '<NAME>', '', NULL, NULL), (132, 17, '<NAME>', '', NULL, NULL), (133, 18, '<NAME>', '', NULL, NULL), (134, 18, '<NAME>', '', NULL, NULL), (135, 18, 'Rovieng', '', NULL, NULL), (136, 18, '<NAME>', '', NULL, NULL), (137, 18, 'Chhaeb', '', NULL, NULL), (138, 18, 'Kulen', '', NULL, NULL), (139, 18, '<NAME>', '', NULL, NULL), (140, 18, '<NAME>', '', NULL, NULL), (141, 19, '<NAME>', '', NULL, NULL), (142, 19, 'Kanhchriech', '', NULL, NULL), (143, 19, '<NAME>', '', NULL, NULL), (144, 19, '<NAME>', '', NULL, NULL), (145, 19, '<NAME>', '', NULL, NULL), (146, 19, '<NAME>', '', NULL, NULL), (147, 19, '<NAME>', '', NULL, NULL), (148, 19, '<NAME>', '', NULL, NULL), (149, 19, '<NAME>', '', NULL, NULL), (150, 19, '<NAME>', '', NULL, NULL), (151, 19, '<NAME>', '', NULL, NULL), (152, 19, '<NAME>', '', NULL, NULL), (153, 20, 'Bakan', '', NULL, NULL), (154, 20, 'Krakor', '', NULL, NULL), (155, 20, '<NAME>', '', NULL, NULL), (156, 20, 'Kandieng', '', NULL, NULL), (157, 20, '<NAME>', '', NULL, NULL), (158, 20, '<NAME>', '', NULL, NULL), (159, 21, '<NAME>', '', NULL, NULL), (160, 21, '<NAME>', '', NULL, NULL), (161, 21, '<NAME>', '', NULL, NULL), (162, 21, '<NAME>', '', NULL, NULL), (163, 21, '<NAME>', '', NULL, NULL), (164, 21, 'Lumphat', '', NULL, NULL), (165, 21, '<NAME>', '', NULL, NULL), (166, 21, '<NAME>', '', NULL, NULL), (167, 22, 'Sesan', '', NULL, NULL), (168, 22, '<NAME>', '', NULL, NULL), (169, 22, '<NAME>', '', NULL, NULL), (170, 22, '<NAME>', '', NULL, NULL), (171, 22, '<NAME>', '', NULL, NULL), (172, 23, 'Chantrea', '', NULL, NULL), (173, 23, 'Rumduol', '', NULL, NULL), (174, 23, '<NAME>', '', NULL, NULL), (175, 23, '<NAME>', '', NULL, NULL), (176, 23, '<NAME>', '', NULL, NULL), (177, 23, '<NAME>', '', NULL, NULL), (178, 23, '<NAME>', '', NULL, NULL), (179, 23, '<NAME>', '', NULL, NULL), (180, 24, '<NAME>', '', NULL, NULL), (181, 24, '<NAME>', '', NULL, NULL), (182, 24, 'Samraong', '', NULL, NULL), (183, 24, 'Treang', '', NULL, NULL), (184, 24, 'Bati', '', NULL, NULL), (185, 24, '<NAME>', '', NULL, NULL), (186, 24, '<NAME>', '', NULL, NULL), (187, 24, '<NAME>', '', NULL, NULL), (188, 24, '<NAME>', '', NULL, NULL), (189, 24, '<NAME>', '', NULL, NULL), (190, 24, '<NAME>', '', NULL, NULL), (191, 25, 'Dombae', '', NULL, NULL), (192, 25, 'Memot', '', NULL, NULL), (193, 25, '<NAME>', '', NULL, NULL), (194, 25, '<NAME>', '', NULL, NULL), (195, 25, '<NAME>', '', NULL, NULL), (196, 25, 'Ou Reang Ov', '', NULL, NULL), (197, 25, '<NAME>', '', NULL, NULL); /*!40000 ALTER TABLE `districts` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.facings DROP TABLE IF EXISTS `facings`; CREATE TABLE IF NOT EXISTS `facings` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `facing` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.facings: 8 rows /*!40000 ALTER TABLE `facings` DISABLE KEYS */; INSERT INTO `facings` (`id`, `facing`, `created_at`, `updated_at`) VALUES (1, 'East', '2020-06-20 13:01:27', '2020-06-20 13:01:31'), (2, 'North', '2020-06-20 13:01:27', '2020-06-20 13:01:32'), (3, 'Northeast', '2020-06-20 13:01:28', '2020-06-20 13:01:32'), (4, 'Northwest', '2020-06-20 13:01:28', '2020-06-20 13:01:33'), (5, 'South', '2020-06-20 13:01:29', '2020-06-20 13:01:33'), (6, 'Southeast', '2020-06-20 13:01:30', '2020-06-20 13:01:34'), (7, 'Southwest', '2020-06-20 13:01:30', '2020-06-20 13:01:34'), (8, 'West', '2020-06-20 13:01:31', '2020-06-20 13:01:35'); /*!40000 ALTER TABLE `facings` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.migrations DROP TABLE IF EXISTS `migrations`; CREATE TABLE IF NOT EXISTS `migrations` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `migration` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.migrations: 12 rows /*!40000 ALTER TABLE `migrations` DISABLE KEYS */; INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (1, '2014_10_12_000000_create_users_table', 1), (2, '2014_10_12_100000_create_password_resets_table', 1), (3, '2019_04_10_023959_create_properties_table', 1), (4, '2019_04_10_024114_create_property_galleries_table', 1), (5, '2019_04_10_042644_create_province_district_commune_tables', 1), (6, '2019_05_02_110924_create_admins_table', 1), (7, '2019_05_08_120215_create_phone_operators_table', 1), (8, '2019_05_10_020522_create_categories_table', 1), (9, '2019_05_25_012319_create_property_type_table', 2), (10, '2020_06_20_055247_create_bedrooms_table', 3), (11, '2020_06_20_055307_create_bathrooms_table', 3), (12, '2020_06_20_055322_create_facings_table', 3); /*!40000 ALTER TABLE `migrations` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.password_resets DROP TABLE IF EXISTS `password_resets`; CREATE TABLE IF NOT EXISTS `password_resets` ( `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, KEY `password_resets_email_index` (`email`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.password_resets: 0 rows /*!40000 ALTER TABLE `password_resets` DISABLE KEYS */; /*!40000 ALTER TABLE `password_resets` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.phone_operators DROP TABLE IF EXISTS `phone_operators`; CREATE TABLE IF NOT EXISTS `phone_operators` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `cellcard` varchar(15) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `smart` varchar(15) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `metfone` varchar(15) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `qb` varchar(15) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.phone_operators: 13 rows /*!40000 ALTER TABLE `phone_operators` DISABLE KEYS */; INSERT INTO `phone_operators` (`id`, `cellcard`, `smart`, `metfone`, `qb`, `created_at`, `updated_at`) VALUES (1, '011', '010', '031', '013', NULL, NULL), (2, '012', '015', '060', '080', NULL, NULL), (3, '014', '016', '066', '083', NULL, NULL), (4, '017', '069', '067', '084', NULL, NULL), (5, '061', '070', '068', '', NULL, NULL), (6, '077', '081', '071', '', NULL, NULL), (7, '078', '086', '088', '', NULL, NULL), (8, '079', '087', '090', '', NULL, NULL), (9, '085', '093', '097', '', NULL, NULL), (10, '089', '096', '', '', NULL, NULL), (11, '092', '098', '', '', NULL, NULL), (12, '095', '', '', '', NULL, NULL), (13, '099', '', '', '', NULL, NULL); /*!40000 ALTER TABLE `phone_operators` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.properties DROP TABLE IF EXISTS `properties`; CREATE TABLE IF NOT EXISTS `properties` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `category_id` int(10) unsigned DEFAULT NULL, `parent_id` int(10) unsigned DEFAULT NULL, `title` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `slug` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `bedroom` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `bathroom` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `facing` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `size` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `price` double(8,2) DEFAULT NULL, `description` text COLLATE utf8mb4_unicode_ci, `name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `phone1` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `phone2` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `phone3` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `email` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `province_id` int(11) DEFAULT NULL, `district_id` int(11) DEFAULT NULL, `commune_id` int(11) DEFAULT NULL, `location` text COLLATE utf8mb4_unicode_ci, `save_contact` tinyint(4) DEFAULT '1', `view_count` int(11) DEFAULT '0', `updated_by` int(11) DEFAULT NULL, `expired_day` int(11) DEFAULT '60', `is_expired` tinyint(4) DEFAULT '0', `is_premium` tinyint(4) DEFAULT '1', `renew_date` datetime DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `deleted_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.properties: 1 rows /*!40000 ALTER TABLE `properties` DISABLE KEYS */; INSERT INTO `properties` (`id`, `user_id`, `category_id`, `parent_id`, `title`, `slug`, `bedroom`, `bathroom`, `facing`, `size`, `price`, `description`, `name`, `phone1`, `phone2`, `phone3`, `email`, `province_id`, `district_id`, `commune_id`, `location`, `save_contact`, `view_count`, `updated_by`, `expired_day`, `is_expired`, `is_premium`, `renew_date`, `created_at`, `updated_at`, `deleted_at`) VALUES (1, 2, 5, 46, '2 Bedrooms Apartment for Sale', '2-Bedrooms-Apartment-for-Sale', NULL, NULL, NULL, NULL, NULL, '2 Bedrooms Apartment for Sale', 'Applephagna', '095 267 77', '0319999926', '0883565895', '<EMAIL>', 1, 0, 233, '2 Bedrooms Apartment for Sale Update', 1, 0, 2, 60, 0, 1, NULL, '2020-06-26 05:18:48', '2020-06-26 06:10:19', NULL); /*!40000 ALTER TABLE `properties` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.property_galleries DROP TABLE IF EXISTS `property_galleries`; CREATE TABLE IF NOT EXISTS `property_galleries` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `property_id` int(10) unsigned NOT NULL, `gallery_image` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.property_galleries: 4 rows /*!40000 ALTER TABLE `property_galleries` DISABLE KEYS */; INSERT INTO `property_galleries` (`id`, `property_id`, `gallery_image`, `created_at`, `updated_at`) VALUES (1, 1, '91811151_434191283770111_1140115001211291454_n.jpeg', '2020-06-26 05:18:48', '2020-06-26 05:18:48'), (2, 1, '57661743_578311615193195_6064101915421012139_n.png', '2020-06-26 05:18:48', '2020-06-26 05:18:48'), (3, 1, '71367071_679111111512821_1767625701211744121_n.png', '2020-06-26 05:18:48', '2020-06-26 05:18:48'), (4, 1, '72381141_715321016076661_1712119171212141137_n.jpeg', '2020-06-26 05:18:48', '2020-06-26 05:18:48'); /*!40000 ALTER TABLE `property_galleries` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.property_type DROP TABLE IF EXISTS `property_type`; CREATE TABLE IF NOT EXISTS `property_type` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `parent_id` int(10) unsigned NOT NULL DEFAULT '0', `type_id` int(10) unsigned DEFAULT '1', `name_en` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `name_kh` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `image` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `is_active` tinyint(4) NOT NULL DEFAULT '1', `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=21 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.property_type: 20 rows /*!40000 ALTER TABLE `property_type` DISABLE KEYS */; INSERT INTO `property_type` (`id`, `parent_id`, `type_id`, `name_en`, `name_kh`, `image`, `is_active`, `created_at`, `updated_at`) VALUES (1, 0, 0, 'House', 'ផ្ទះ', 'photo-house.jpg', 1, '2019-05-31 11:27:59', '2019-05-31 11:28:00'), (2, 0, 0, 'Lands', 'ដី', 'photo-land.jpg', 1, '2019-05-31 11:28:26', '2019-05-31 11:28:26'), (3, 0, 0, 'Apartment', 'អាផាតមិន', 'photo-apartment.jpg', 1, '2019-05-31 17:10:38', '2019-05-31 17:10:39'), (4, 0, 0, 'Commercial Properties', 'ទ្រព្យសម្បត្តិ ពាណិជ្ជកម្ម', 'photo-commercial-properties.jpg', 1, '2019-05-31 17:11:11', '2019-05-31 17:11:12'), (5, 0, 0, 'Room', 'បន្ទប់', 'photo-room.jpg', 1, '2019-05-31 17:17:25', '2019-05-31 17:17:26'), (9, 1, 1, 'Buy', 'ទិញ', NULL, 1, '2019-05-31 17:13:59', '2019-05-31 17:13:59'), (10, 1, 2, 'Rent', 'ជួល', NULL, 1, '2019-05-31 17:14:14', '2019-05-31 17:14:15'), (11, 2, 1, 'Buy', 'ទិញ', NULL, 1, '2019-05-31 17:14:33', '2019-05-31 17:14:34'), (12, 2, 2, 'Rent', 'ជួល', NULL, 1, '2019-05-31 17:14:49', '2019-05-31 17:14:49'), (13, 3, 1, 'Buy', 'ទិញ', NULL, 1, '2019-05-31 17:15:07', '2019-05-31 17:15:07'), (14, 3, 2, 'Rent', 'ជួល', NULL, 1, '2019-05-31 17:15:17', '2019-05-31 17:15:17'), (15, 4, 1, 'Buy', 'ទិញ', NULL, 1, '2019-05-31 17:15:27', '2019-05-31 17:15:27'), (16, 4, 2, 'Rent', 'ជួល', NULL, 1, '2019-05-31 17:15:35', '2019-05-31 17:15:36'), (17, 5, 2, 'Rent', 'ជួល', NULL, 1, '2019-05-31 17:15:57', '2019-05-31 17:15:57'), (6, 0, 0, 'Properties Wanted', NULL, NULL, 1, NULL, NULL), (7, 0, 0, 'Agent Services', NULL, NULL, 1, NULL, NULL), (8, 0, 0, 'Other Categories', NULL, NULL, 1, NULL, NULL), (18, 6, 3, 'Properties Wanted', NULL, NULL, 1, NULL, NULL), (19, 7, 4, 'Agent Services', NULL, NULL, 1, NULL, NULL), (20, 8, 5, 'Other Categories', NULL, NULL, 1, NULL, NULL); /*!40000 ALTER TABLE `property_type` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.provinces DROP TABLE IF EXISTS `provinces`; CREATE TABLE IF NOT EXISTS `provinces` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name_en` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `name_kh` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `slug_en` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `slug_kh` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=26 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.provinces: 25 rows /*!40000 ALTER TABLE `provinces` DISABLE KEYS */; INSERT INTO `provinces` (`id`, `name_en`, `name_kh`, `slug_en`, `slug_kh`, `created_at`, `updated_at`) VALUES (1, '<NAME>', 'ភ្នំពេញ', 'phnom-penh', '', NULL, NULL), (2, '<NAME>', 'ព្រះសីហនុ', 'preah-sihanouk', '', NULL, NULL), (3, '<NAME>', 'កំពង់ចាម', 'kampong-cham', '', NULL, NULL), (4, 'Siem Reap', 'សៀមរាប', 'siem-reap', '', NULL, NULL), (5, 'Battambang', 'បាត់ដំបង', 'Battambang', '', NULL, NULL), (6, 'Kandal', 'កណ្តាល', 'Kandal', '', NULL, NULL), (7, 'Banteay Meanchey', 'បន្ទាយមានជ័យ', 'Banteay-Meanchey', '', NULL, NULL), (8, '<NAME>', 'កំពង់ឆ្នាំង', 'Kampong-Chhnang', '', NULL, NULL), (9, '<NAME>u', 'កំពង់ស្ពឺ', 'Kampong-Speu', '', NULL, NULL), (10, 'Kampong Thom', 'កំពង់ធំ', 'Kampong-Thom', '', NULL, NULL), (11, 'Kampot', 'កំពត', 'Kampot', '', NULL, NULL), (12, 'Kep', 'កែប', 'Kep', '', NULL, NULL), (13, '<NAME>ong', 'កោះកុង', 'Koh-Kong', '', NULL, NULL), (14, 'Kratie', 'ក្រចេះ', 'Kratie', '', NULL, NULL), (15, 'Mondulkiri', 'មណ្ឌលគិរី', 'Mondulkiri', '', NULL, NULL), (16, '<NAME>', 'ឧត្តរមានជ័យ', 'Oddar-Meanchey', '', NULL, NULL), (17, 'Pailin', 'ប៉ៃលិន', 'Pailin', '', NULL, NULL), (18, '<NAME>', 'ព្រះវិហារ', 'Preah-Vihear', '', NULL, NULL), (19, '<NAME>', 'ព្រៃវែង', 'Prey-Veng', '', NULL, NULL), (20, 'Pursat', 'ពោធ៌សាត់', 'Pursat', '', NULL, NULL), (21, 'Ratanakiri', 'រតនគីរី', 'Ratanakiri', '', NULL, NULL), (22, '<NAME>', 'ស្ទឹងត្រែង', 'Stung-Treng', '', NULL, NULL), (23, '<NAME>', 'ស្វាយរៀង', 'Svay-Rieng', '', NULL, NULL), (24, 'Takeo', 'តាកែវ', 'Takeo', '', NULL, NULL), (25, '<NAME>', 'ត្បូងឃ្មុំ', 'Tboung-Khmum', '', NULL, NULL); /*!40000 ALTER TABLE `provinces` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.roles DROP TABLE IF EXISTS `roles`; CREATE TABLE IF NOT EXISTS `roles` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name_kh` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `name_en` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `description` text COLLATE utf8mb4_unicode_ci, `view_path` text COLLATE utf8mb4_unicode_ci, `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `roles_name_unique` (`name_kh`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.roles: ~4 rows (approximately) /*!40000 ALTER TABLE `roles` DISABLE KEYS */; INSERT INTO `roles` (`id`, `name_kh`, `name_en`, `description`, `view_path`, `created_at`, `updated_at`) VALUES (1, 'superadmin', 'superadmin', NULL, NULL, '2020-06-10 18:21:21', '2020-06-10 18:21:22'), (2, 'admin', 'admin', NULL, NULL, '2020-06-10 18:22:12', '2020-06-10 18:22:28'), (3, 'agent', 'agent', NULL, NULL, '2020-06-10 18:22:35', '2020-06-10 18:22:34'), (4, 'user', 'user', NULL, NULL, '2020-06-10 18:23:02', '2020-06-10 18:23:06'); /*!40000 ALTER TABLE `roles` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.social DROP TABLE IF EXISTS `social`; CREATE TABLE IF NOT EXISTS `social` ( `id` bigint(20) NOT NULL, `agency_id` bigint(20) DEFAULT NULL, `name_kh` varchar(150) DEFAULT NULL, `name_en` varchar(150) DEFAULT NULL, `link` varchar(250) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- Dumping data for table thepinrealestate_social_login.social: 0 rows /*!40000 ALTER TABLE `social` DISABLE KEYS */; /*!40000 ALTER TABLE `social` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.social_auths DROP TABLE IF EXISTS `social_auths`; CREATE TABLE IF NOT EXISTS `social_auths` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user_id` bigint(20) unsigned NOT NULL, `provider` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `_id` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `_email` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `_avatar` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.social_auths: ~0 rows (approximately) /*!40000 ALTER TABLE `social_auths` DISABLE KEYS */; /*!40000 ALTER TABLE `social_auths` ENABLE KEYS */; -- Dumping structure for table thepinrealestate_social_login.users DROP TABLE IF EXISTS `users`; CREATE TABLE IF NOT EXISTS `users` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `role_id` bigint(20) unsigned NOT NULL DEFAULT '0', `firstname` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `lastname` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `username` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `phone` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `address` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `location` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `profile` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `email_verified_at` timestamp NULL DEFAULT NULL, `password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `users_email_unique` (`email`), UNIQUE KEY `users_username_unique` (`username`), UNIQUE KEY `users_phone_unique` (`phone`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.users: 4 rows /*!40000 ALTER TABLE `users` DISABLE KEYS */; INSERT INTO `users` (`id`, `role_id`, `firstname`, `lastname`, `username`, `phone`, `email`, `address`, `location`, `profile`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES (1, 1, 'Administrator', 'Administrator', 'admin', '012888999', '<EMAIL>', NULL, NULL, NULL, NULL, '$2y$10$GJnXqe6/2uPZlKgkfGnTaOaoPzZMCJw6oyr7eHnmZlbo7fs2/WLDq', 'N8RkNPIf1T2PuwR4jA0YoEuWtx74XEe0eja2Dy9Zeoso2tubeurSxxBAs2a0', '2020-06-10 10:47:43', '2020-06-10 10:47:43'), (2, 3, 'agent', 'agent', '<EMAIL>', '01211112222', '<EMAIL>', NULL, NULL, NULL, NULL, '$2y$10$zx3FmvBUvcrQtPz17hbauOCHKCpBj3lVWKj2CMeGBO/FGtgNBbTTi', '3tqU1PS1aaGKJN2dS9Pnq6YABFh4XqSzLTPjx0WcHBcgcQ5Cy3MloOCDFmmq', '2020-06-11 08:09:52', '2020-06-11 08:09:52'), (3, 3, 'User', 'User', 'user', '012123456', '<EMAIL>', NULL, NULL, NULL, NULL, '$2y$10$A8dRLlELkfue8V8XOWPOCeMYsO7Mo4VMTLkUZebV9qmDqf8vrzrUO', 'j5XEfQV0SAMd8e1IbDboU3ICNGwylL1SkQdU42kBUqYi1OxpMGvpyVAzdf1v', '2020-06-14 08:21:31', '2020-06-14 08:21:31'), (4, 3, 'kaka', 'kaka', '<EMAIL>', '012666777', '<EMAIL>', NULL, NULL, NULL, NULL, '$2y$10$rBTRVmPBAPgrpeYG85FyGOwqqmNYDuRs9MnkSMUwVLv9XQ7EMrAAu', 'psYkWA0V4lUifcu6Ak63ASwgeO9gIKcxCXcVOjFbp6lk8pewNimr0c29oL0c', '2020-06-15 07:59:19', '2020-06-15 07:59:19'); /*!40000 ALTER TABLE `users` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; <file_sep>/app/Models/District.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class District extends Model { public function communes() { return $this->hasMany(Commune::class,'district_id','id'); } public function province() { return $this->belongsTo(Province::class,'province_id','id'); } public function properties() { return $this->hasMany(Property::class,'id','district_id'); } } <file_sep>/app/Http/Controllers/Admin/CategoryController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Models\Category; use Illuminate\Http\Request; class CategoryController extends Controller { public function index() { $data['allcategories'] = Category::where('parent_id','>',0)->published()->get(); return view('admin.categories.index',$data); } public function create() { // } public function store(Request $request) { // } public function show($id) { // } public function edit($id) { // } public function update(Request $request, $id) { // } public function destroy($id) { // } } <file_sep>/database/bedrooms.sql -- -------------------------------------------------------- -- Host: 127.0.0.1 -- Server version: 5.7.26 - MySQL Community Server (GPL) -- Server OS: Win64 -- HeidiSQL Version: 11.0.0.5919 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Dumping structure for table thepinrealestate_social_login.bedrooms DROP TABLE IF EXISTS `bedrooms`; CREATE TABLE IF NOT EXISTS `bedrooms` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `room` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.bedrooms: 9 rows /*!40000 ALTER TABLE `bedrooms` DISABLE KEYS */; INSERT INTO `bedrooms` (`id`, `room`, `created_at`, `updated_at`) VALUES (1, '1', '2020-06-20 12:55:45', '2020-06-20 12:55:46'), (2, '2', '2020-06-20 12:55:46', '2020-06-20 12:55:48'), (3, '3', '2020-06-20 12:55:47', '2020-06-20 12:55:47'), (4, '4', '2020-06-20 12:55:55', '2020-06-20 12:55:54'), (5, '5', '2020-06-20 12:56:01', '2020-06-20 12:56:02'), (6, '6', '2020-06-20 12:56:08', '2020-06-20 12:56:09'), (7, '7', '2020-06-20 12:56:15', '2020-06-20 12:56:16'), (8, '8', '2020-06-20 12:56:24', '2020-06-20 12:56:24'), (9, 'More+', '2020-06-20 12:58:03', '2020-06-20 12:58:03'); /*!40000 ALTER TABLE `bedrooms` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; <file_sep>/app/Models/Property.php <?php namespace App\Models; use Illuminate\Http\Request; use App\Models\Upload as Eloquent; use Illuminate\Database\Eloquent\Model; class Property extends Eloquent { protected $primaryKey = 'id'; protected $table = 'properties'; protected $fillable = [ 'user_id', 'category_id', 'parent_id', 'title', 'slug', 'bedroom', 'bathroom', 'facing', 'size', 'price', 'description', 'name', 'phone1', 'phone2', 'phone3', 'email', 'province_id', 'district_id', 'commune_id', 'location', 'save_contact', 'updated_by', 'expired_day', 'is_expired', 'is_premium', 'renew_date' ]; public function user() { return $this->belongsTo(User::class,'user_id','id'); } public function province() { return $this->belongsTo(Province::class,'province_id','id'); } public function district() { return $this->belongsTo(District::class,'district_id','id'); } public function commune() { return $this->belongsTo(Commune::class,'commune_id','id'); } public function category() { return $this->belongsTo(Category::class,'category_id','id'); } public function parent() { return $this->belongsTo(Category::class,'parent_id','id'); } public function galleries() { return $this->hasMany(PropertyGallery::class,'property_id','id'); } public function scopeExpired($query) { return $query->where('is_expired',0); } public function scopeCountExpired($query) { return $query->where('is_expired',1); } public function scopePremium($query) { return $query->where('is_premium',1); } public static function gallery($property_id, $image_path) { $get = PropertyGallery::where('property_id', $property_id)->orderBy('created_at', 'ASC')->get()->toArray(); if ($get) { $data = []; foreach ($get as $row) { $data[] = [ 'id' => $row['id'], 'image' => $image_path . '/' . $row['gallery_image'], ]; } return $data; } } public function scopeFilterByRequest($query, Request $request) { if ($request->input('location')) { // $query->where('province_id', '=', $request->input('location')); $query->whereHas('province', function ($query) use ($request) { $query->where('slug', $request->input('location')); }); } if ($request->input('category')) { // $query->where('parent_id', $request->input('category')); $query->whereHas('parent', function ($query) use ($request) { $query->where('slug', $request->input('category')); }); } if ($request->input('q')) { $query->where('title', 'LIKE', '%'.$request->input('q').'%'); } return $query; } public function scopeFilterByCategories($query, Request $request) { if ($request->input('location')) { // $query->where('province_id', '=', $request->input('location')); $query->whereHas('province', function ($query) use ($request) { $query->where('slug', $request->input('location')); }); } if ($request->input('district')) { $query->whereHas('district', function ($query) use ($request) { $query->where('slug', $request->input('district')); }); } if ($request->input('commune')) { $query->whereHas('commune', function ($query) use ($request) { $query->where('slug', $request->input('commune')); }); } if ($request->input('category')) { // $query->where('parent_id', $request->input('category')); $query->whereHas('category', function ($query) use ($request) { $query->where('slug', $request->input('category')); }); } return $query; } public function scopeFilterInProfile($query, Request $request) { if(auth()->user()->role_id==1 || auth()->user()->role_id==2){ $query = Property::expired(); } else { $query = Property::where('user_id',auth()->user()->id) ->expired(); } if ($request->input('category')) { $query->where('parent_id', $request->input('category')); } if ($request->input('location')) { $query->where('province_id', '=', $request->input('location')); } if ($request->input('search')) { $query->where('title', 'LIKE', '%'.$request->input('search').'%'); } if ($request->input('from_price') && $request->input('to_price')) { $query->whereBetween('price', [$request->input('from_price'),$request->input('to_price')]); } if ($request->input('sort')) { switch ($request->input('sort')){ case 'posted_date_desc': $query->orderBy('created_at', 'DESC'); break; case 'posted_date_asc': $query->orderBy('created_at', 'ASC'); break; case 'renew_date_desc': $query->orderBy('renew_date', 'DESC'); break; case 'renew_date_asc': $query->orderBy('renew_date', 'ASC'); break; case 'price_desc': $query->orderBy('price', 'DESC'); break; case 'price_asc': $query->orderBy('price', 'ASC'); break; default: $query->orderBy('created_at', 'DESC'); } } return $query; } public function scopeFilterByCategory($query, Request $request) { if ($request->input('ad_bedroom')) { $query->where('bedroom', 'like', '%'.$request->input('ad_bedroom').'%'); } if ($request->input('ad_bathroom')) { $query->where('bathroom', 'like', '%'.$request->input('ad_bathroom').'%'); } if ($request->input('ad_facing')) { $query->where('facing', 'like', '%'.$request->input('ad_facing').'%'); } if ($request->input('from_ad_price')) { $query->where('price', '>=', $request->input('from_ad_price')); } if ($request->input('to_ad_price')) { $query->where('price', '<=', $request->input('to_ad_price')); } if ($request->input('from_ad_size')) { $query->where('size', '>=', $request->input('from_ad_size')); } if ($request->input('to_ad_size')) { $query->where('size', '<=', $request->input('to_ad_size')); } if ($request->input('location')) { $query->whereHas('province', function ($query) use ($request) { $query->where('slug', $request->input('location')); }); } if ($request->input('district')) { $query->whereHas('district', function ($query) use ($request) { $query->where('slug', $request->input('district')); }); } if ($request->input('commune')) { $query->whereHas('commune', function ($query) use ($request) { $query->where('slug', $request->input('commune')); }); } if ($request->input('category')) { $query->whereHas('parent', function ($query) use ($request) { $query->where('slug', $request->input('category')); }); } // if ($request->input('sortby')) { // switch ($request->input('sortby')){ // case 'latestads': // $query->orderBy('latestads', 'ASC'); // break; // case 'newads': // $query->orderBy('newads', 'DESC'); // break; // case 'mosthitads': // $query->orderBy('mosthitads', 'DESC'); // break; // case 'priceasc': // $query->orderBy('renew_date', 'ASC'); // break; // case 'pricedesc': // $query->orderBy('price', 'DESC'); // break; // default: // $query->orderBy('latestads', 'ASC'); // } // } return $query; } public function scopeFilterByType($query, Request $request) { if ($request->input('from_ad_price')) { $query->where('price', '>=', $request->input('from_ad_price')); } if ($request->input('to_ad_price')) { $query->where('price', '<=', $request->input('to_ad_price')); } if ($request->input('from_ad_size')) { $query->where('size', '>=', $request->input('from_ad_size')); } if ($request->input('to_ad_size')) { $query->where('size', '<=', $request->input('to_ad_size')); } if ($request->input('location')) { $query->whereHas('province', function ($query) use ($request) { $query->where('slug', $request->input('location')); }); } if ($request->input('district')) { $query->whereHas('district', function ($query) use ($request) { $query->where('slug', $request->input('district')); }); } if ($request->input('commune')) { $query->whereHas('commune', function ($query) use ($request) { $query->where('slug', $request->input('commune')); }); } if ($request->input('category')) { $query->whereHas('parent', function ($query) use ($request) { $query->where('slug', $request->input('category')); }); } // if ($request->input('sortby')) { // switch ($request->input('sortby')){ // case 'latestads': // $query->orderBy('latestads', 'ASC'); // break; // case 'newads': // $query->orderBy('newads', 'DESC'); // break; // case 'mosthitads': // $query->orderBy('mosthitads', 'DESC'); // break; // case 'priceasc': // $query->orderBy('renew_date', 'ASC'); // break; // case 'pricedesc': // $query->orderBy('price', 'DESC'); // break; // default: // $query->orderBy('latestads', 'ASC'); // } // } return $query; } public function scopePropertyReport($query, Request $request) { $query = Property::with(['category','parent','province','district','commune']) ->where('category_id',5); if($request->input('sortby')!=''){ switch ($request->input('sortby')){ case 'posted_date_desc': $query->orderBy('created_at', 'DESC'); break; case 'posted_date_asc': $query->orderBy('created_at', 'ASC'); break; case 'renew_date_desc': $query->orderBy('renew_date', 'DESC'); break; case 'renew_date_asc': $query->orderBy('renew_date', 'ASC'); break; case 'price_desc': $query->orderBy('price', 'DESC'); break; case 'price_asc': $query->orderBy('price', 'ASC'); break; case 'view_desc': $query->orderBy('view_count', 'DESC'); break; case 'view_asc': $query->orderBy('view_count', 'ASC'); break; default: $query->orderBy('created_at', 'DESC'); } } if($request->input('from_date')!=''){ $query->whereBetween('created_at',array($request->input('from_date'),$request->input('to_date'))); } if($request->input('location')<>0){ $query->where('province_id',$request->input('location')); } if($request->input('type')<>0){ $query->where('parent_id',$request->input('type')); } if($request->input('purpose')<>0){ $query->whereHas('parent',function($query) use ($request){ $query->where('sub_type_id',$request->input('purpose')); }); } return $query; } } <file_sep>/app/Http/Controllers/Auth/LoginController.php <?php namespace App\Http\Controllers\Auth; use App\Models\Category; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Auth; use Illuminate\Foundation\Auth\AuthenticatesUsers; class LoginController extends Controller { use AuthenticatesUsers; // protected $redirectTo = RouteServiceProvider::HOME; // protected $redirectTo; public function __construct() { $this->middleware('guest')->except('logout'); } public function showLoginForm() { $categories = Category::where(['parent_id'=>0])->get(); return view('auth.login',compact('categories')); } protected function credentials(Request $request) { if(is_numeric($request->get('email'))){ return ['phone'=>$request->get('email'),'password'=>$request->get('password')]; } elseif (filter_var($request->get('email'), FILTER_VALIDATE_EMAIL)) { return ['email' => $request->get('email'), 'password'=>$request->get('password')]; } return ['username' => $request->get('email'), 'password'=>$request->get('password')]; } protected function redirectTo() { if(Auth::check()){ if(Auth::user()->hasAnyRole(['Super-admin','Administer'])){ $this->redirectTo = route('admin.dashboard'); return $this->redirectTo; } else if(Auth::user()->hasAnyRole(['Agent','Member'])){ $this->redirectTo = route('agent.dashboard'); return $this->redirectTo; } } } } <file_sep>/database/bathrooms.sql -- -------------------------------------------------------- -- Host: 127.0.0.1 -- Server version: 5.7.26 - MySQL Community Server (GPL) -- Server OS: Win64 -- HeidiSQL Version: 11.0.0.5919 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Dumping structure for table thepinrealestate_social_login.bathrooms DROP TABLE IF EXISTS `bathrooms`; CREATE TABLE IF NOT EXISTS `bathrooms` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `room` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.bathrooms: 9 rows /*!40000 ALTER TABLE `bathrooms` DISABLE KEYS */; INSERT INTO `bathrooms` (`id`, `room`, `created_at`, `updated_at`) VALUES (1, '1', '2020-06-20 12:58:51', '2020-06-20 12:58:53'), (2, '2', '2020-06-20 12:58:52', '2020-06-20 12:58:51'), (3, '3', '2020-06-20 12:58:54', '2020-06-20 12:58:54'), (4, '4', '2020-06-20 12:58:55', '2020-06-20 12:58:55'), (5, '5', '2020-06-20 12:58:56', '2020-06-20 12:58:56'), (6, '6', '2020-06-20 12:58:57', '2020-06-20 12:58:57'), (7, '7', '2020-06-20 12:58:58', '2020-06-20 12:58:59'), (8, '8', '2020-06-20 12:58:59', '2020-06-20 12:59:02'), (9, 'More+', '2020-06-20 12:59:00', '2020-06-20 12:59:00'); /*!40000 ALTER TABLE `bathrooms` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; <file_sep>/resources/lang/th/auth.php <?php return array ( 'failed' => 'ข้อมูลรับรองเหล่านี้ไม่ตรงกับบันทึกของเรา', ); <file_sep>/app/Http/Controllers/Admin/PostController.php <?php namespace App\Http\Controllers\Admin; use App\Post; use File; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Intervention\Image\Facades\Image; class PostController extends Controller { public function __construct() { $this->middleware('permission:post-list|post-create|post-edit|post-delete', ['only' => ['index','show']]); $this->middleware('permission:post-create', ['only' => ['create','store']]); $this->middleware('permission:post-edit', ['only' => ['edit','update']]); $this->middleware('permission:post-delete', ['only' => ['destroy']]); } public function index() { $posts = Post::latest()->paginate(5); return view('posts.index',compact('posts')) ->with('i', (request()->input('page', 1) - 1) * 5); } public function create() { return view('posts.create'); } public function store(Request $request) { $this->validate($request, [ 'title' => 'required', 'body' => 'required', ]); if($request->hasFile('image')){ $image = $request->file('image'); $image_name = uniqid().'-'.time() . '.' . $image->getClientOriginalExtension(); $destinationPath = public_path('uploads/thumbnail/post'); if(!\file_exists($destinationPath)){ mkdir($destinationPath, 0777, true); } // reisize image before upload $resize_image = Image::make($image->getRealPath()); $resize_image->resize(150, 150, function($constraint){ $constraint->aspectRatio(); })->save($destinationPath . '/' . $image_name); // upload original image $destinationPath = public_path('uploads/post'); $image->move($destinationPath, $image_name); } else { $image_name = null; } if (isset($request->status)) { $status = true; } else { $status = false; } Post::create([ 'title' => $request->title, 'body' => $request->body, 'status' => $status, 'image' => $image_name, ]); return redirect()->route('admin.posts.index') ->with('success','Product created successfully.'); } public function show(Post $post) { return view('posts.show',compact('post')); } public function edit(Post $post) { return view('posts.edit',compact('post')); } public function update(Request $request, Post $post) { $this->validate($request, [ 'title' => 'required', 'body' => 'required', ]); $old_image = $post->image; $thumbnailPath = public_path('uploads/thumbnail/post'); $destinationPath =public_path('uploads/post'); // return $destinationPath.'/'.$old_image; if($request->hasFile('image')){ if (!is_null($post->image) && File::exists($thumbnailPath.'/'.$post->image)){ File::delete($thumbnailPath.'/'.$post->image); } if (!is_null($post->image) && File::exists($destinationPath.'/'.$post->image)){ File::delete($destinationPath.'/'.$post->image); } $image = $request->file('image'); $image_name = uniqid().'-'.time() . '.' . $image->getClientOriginalExtension(); // reisize image before upload if(!\file_exists($thumbnailPath)){ mkdir($thumbnailPath, 0777, true); } $resize_image = Image::make($image->getRealPath()); $resize_image->resize(150, 150, function($constraint){ $constraint->aspectRatio(); })->save($thumbnailPath . '/' . $image_name); // upload original image $image->move($destinationPath, $image_name); } else { $image_name = $old_image; } if (isset($request->status)) { $status = true; } else { $status = false; } $post->update([ 'title' => $request->title, 'body' => $request->body, 'status' => $status, 'image' => $image_name, ]); return redirect()->route('admin.posts.index') ->with('success','Product updated successfully'); } public function destroy(Post $post) { $thumbnailPath = public_path('uploads/thumbnail/post'); $destinationPath =public_path('uploads/post'); if (!is_null($post->image) && File::exists($thumbnailPath.'/'.$post->image)){ File::delete($thumbnailPath.'/'.$post->image); } if (!is_null($post->image) && File::exists($destinationPath.'/'.$post->image)){ File::delete($destinationPath.'/'.$post->image); } $post->delete(); return redirect()->route('admin.posts.index') ->with('success','Product deleted successfully'); } } <file_sep>/app/Http/Requests/User/EditValidation.php <?php namespace App\Http\Requests\User; use Illuminate\Foundation\Http\FormRequest; class EditValidation extends FormRequest { public function authorize() { return true; } public function rules() { return [ 'name_en' => 'required|string|max:50', 'name_kh' => 'required|string|max:50', 'username' => 'required|string|max:50', 'email' => 'required|email', 'phone' => 'required', 'referal_code' => 'required', 'province_id' => 'required', 'district_id' => 'required', 'commune_id' => 'required', 'photo' => 'required', ]; } public function messages() { return [ 'name_en.required' => 'Please, Add User Name.', 'name_kh.required' => 'Please, Add User NameKh.', 'username.required' => 'Please, Add User User Name.', 'email.required' => 'Please, Add Email.', 'phone.unique' => 'Please, Add Unique Phone.', 'referal_code.unique' => 'Please, Add Correct Referal Code.', 'province_id.unique' => 'Please, Choose Province.', 'district_id.unique' => 'Please, Choose District.', 'commune_id.unique' => 'Please, Choose the Commune.', 'photo.required' => 'Please, Upload Photo.' ]; } } <file_sep>/public/assets/ksupload/ksupload.js ; (function ($) { $.fn.Upload = function (option = false) { var listImage = $(this), countImage = $('<div></div>'), pages = { init: () => { countImage.text('0/' + pages.files_limit); pages.load_field(); countImage.addClass('pull-right'); listImage.after(countImage); listImage.parent().css({ border: '2px dashed transparent', position: 'relative' }); pages.save(); }, files_limit: option.files_limit ? option.files_limit : (listImage.attr('data-limit-image')), token: option._token ? option.token : (listImage.attr('data-token') ? listImage.attr('data-token') : $('meta[name="_token"]').attr('content')), upload_url: option.upload_url ? option.upload_url : (listImage.attr('data-upload-url')), rotate_url: option.rotate_url ? option.rotate_url : (listImage.attr('data-rotate-url')), delete_url: option.delete_url ? option.delete_url : (listImage.attr('data-delete-url')), allow_size: option.allow_size ? option.allow_size : (listImage.attr('data-allow-size')), allow_file: option.allow_file ? option.allow_file : (listImage.attr('data-allow-file') ? listImage.attr('data-allow-file') : 'image/jpeg,.jpg,image/gif,.gif,image/png,.png,.jpeg'), save_url: option.save_url ? option.save_url : (listImage.parents('form').attr('action')), load_field: function () { var images = listImage.data("images"); if (images) { countImage.text(images.length + '/' + pages.files_limit); } for (var i = 0; i < pages.files_limit; i++) { var file = $('<div></div>'), browse = $('<div></div>'), input = $('<input/>'); file.addClass('file'); file.attr({ id: 'file-' + i }); browse.addClass('browse'); input.attr({ title: '', type: 'file', multiple: true, accept: pages.allow_file, }); input.on('input', function (files) { var self = $(this); pages.files(files.target.files, self); $(this).val(''); }); input.appendTo(browse); browse.appendTo(file); file.appendTo(listImage); if (images) { if (images[i]) { pages.imageView((i + 1), { path: images[i].image, name: images[i].id }); } } } pages.imageDrop(); }, files: function (files, target, kind = 'file') { (function () { if (kind === 'file') { if (window.File && window.FileReader && window.FileList && window.Blob) { if (files.length > pages.files_limit) { return Swal.fire({ type: 'warning', title: 'Oop!', text: 'limit: ' + pages.files_limit + ' image', showConfirmButton: true, }); } else { var e = listImage.find('[type="file"]'), i = 0; e.length && e.each(function () { if ($(this).parent().find('.img').length > 0) { i++; } }); if ((i + files.length) > pages.files_limit) { return Swal.fire({ type: 'warning', title: 'Oop!', html: 'Limit: ' + pages.files_limit + ' image.<br>Need ' + (pages.files_limit - i) + ' more.', showConfirmButton: true, }); } } return pages.uploadImage(files, target); var tmp = []; for (var i = 0; i < files.length; i++) { var file = files[i]; tmp.push({ file: file }); var reader = new FileReader(); if (file.type.match('image.*')) { reader.onload = (function (file) { return function (f) { if (file.size > pages.allow_size) { return Swal.fire({ type: 'warning', title: 'Oop!', html: 'File allow size : ' + pages.bytesToSize(pages.allow_size), showConfirmButton: true, }); } else { var b64 = pages.b64toFile(f.target.result); //pages.uploadImage(b64, file.name, target); } } })(file); reader.readAsDataURL(file); } } pages.uploadImage(tmp, target); } } else if (kind == 'string') { var e = listImage.find('[type="file"]'), i = 0; e.length && e.each(function () { if ($(this).parent().find('.img').length > 0) { i++; } }); if ((i + 1) > pages.files_limit) { return Swal.fire({ type: 'warning', title: 'Oop!', html: 'Limit: ' + pages.files_limit + ' image.<br>Need ' + (pages.files_limit - i) + ' more.', showConfirmButton: true, }); } var xhr = new XMLHttpRequest(), url = files; if (!/^https?:\/\//i.test(url)) { url = '//' + url; } xhr.open("GET", url); xhr.responseType = "blob"; xhr.onload = function response(e) { var reader = new FileReader(); var file = this.response; reader.onload = (function (file) { return function (f) { if (file.size > pages.allow_size) { return Swal.fire({ type: 'warning', title: 'Oop!', html: 'File allow size : ' + pages.bytesToSize(pages.allow_size), showConfirmButton: true, }); } else { if (pages.allow_file.match((file.type).split('/').pop())) { var name = ((file.type).split('/').pop() === 'html') ? 'image.svg' : (file.type).replace('/', '.'); var b64 = pages.b64toFile(f.target.result); pages.uploadImage(b64, target, 'link'); } } }; })(file); reader.readAsDataURL(file); }; xhr.send(); } })(); }, imageDrop: function () { $(document) .on('dragover', function (e) { listImage.parent().css({ border: '2px dashed #75a3f5', }); if (listImage.parent().find('.drag-drop').length === 0) { listImage.parent().append('<div class="drag-drop"><div class="text">Drag Link/Files Here</div></div>'); } e.preventDefault(); }) .on('drop', function (e) { listImage.parent().css({ border: '2px dashed transparent', }); listImage.parent().find('.drag-drop').remove(); e.preventDefault(); return false; }) .on('dragleave', function (e) { listImage.parent().css({ border: '2px dashed transparent', }); }); listImage.parent() .on('dragover', function (e) { var drop = 'Drop Link/Files Here'; var data = e.originalEvent.dataTransfer.items; if (data[0].kind === 'file') { drop = 'Drop Files Here'; } else { drop = 'Drop Link Here'; } listImage.parent().find('.drag-drop').children().html(drop); e.preventDefault(); }).on('dragleave', function (e) { var drop = 'Drop Link/Files Here'; listImage.parent().find('.drag-drop').children().html(drop); e.preventDefault(); }).on('drop', function (e) { var kind = e.originalEvent.dataTransfer.getData("text") ? 'string' : 'file'; if (kind === 'file') { pages.files(e.originalEvent.dataTransfer.files, $(this), kind); } else { pages.files(e.originalEvent.dataTransfer.getData("text"), $(this), kind); } listImage.parent().find('.drag-drop').remove(); e.preventDefault(); }).on('paste', function (e) { pages.files(e.originalEvent.clipboardData.files, $(this)); }); }, imageView: function (file_in_uploading = false, file = false) { if (file_in_uploading) { var imageContainer = $('<div></div>'), btnRotate = $('<a href="javascript:(0);"></a>'), btnDelete = $('<a href="javascript:(0);"></a>'), view = $('<div></div>'), image = $('<img/>'); imageContainer.addClass('img'); btnRotate.addClass('image_rotate'); btnRotate.on('click', function (e) { e.preventDefault(); var id = $(this).parent().find('.img-contain').attr('dataid'); pages.rotateImage(id, imageContainer); }); btnDelete.addClass('image_delete'); btnDelete.on('click', function (e) { e.preventDefault(); var id = $(this).parent().find('.img-contain').attr('dataid'); listImage.find('.file#' + $(this).parent().attr('id')).find('.browse').removeClass('disabled'); pages.deleteImage(id, imageContainer) }); view.addClass('img-view'); image.addClass('img-contain'); image.attr({ src: file ? file.path : '', dataId: file ? file.name : '', }); image.appendTo(view); btnRotate.appendTo(imageContainer); btnDelete.appendTo(imageContainer); view.appendTo(imageContainer); var e = listImage.find('[type="file"]'), i = 1; e.length && e.each(function () { if ($(this).parent().find('.img').length === 0) { var id = $(this).parent().parent().attr('id') imageContainer.attr({ id: id, }); if (file) { $(this).attr({ 'data-files': JSON.stringify(file) }).after(imageContainer); $(this).parent().parent().removeClass('loading').find('.percent').remove(); listImage.find('.file#' + id).find('.browse').addClass('disabled'); return false; } else { var percent = $('<div></div>'); percent.addClass('percent'); $(this).parent().parent().addClass('loading'); $(this).parent().parent().append(percent); if (i === file_in_uploading) return false; i++; } } }); } }, uploadImage: function (files, target = false, from = 'input') { var formData = new FormData(), file_in_uploading = 0; formData.append('_token', pages.token); formData.append('property_id', target.parents("form").find('[name="property_id"]').val()); //formData.append('file', files); //formData.append('name', name); if (from == 'input') { for (var i = 0; i < files.length; i++) { if (files[i].size > pages.allow_size) { continue; } else { formData.append('files[]', files[i]); file_in_uploading++; } } } else if (from == 'link') { formData.append('files[]', files); file_in_uploading++; } $.ajax({ url: pages.upload_url, method: "POST", data: formData, contentType: false, processData: false, xhr: function () { var xhr = new XMLHttpRequest(); xhr.onprogress = function (e) { // For downloads if (e.lengthComputable) { // console.log(parseInt(e.loaded / e.total * 100) + '%'); } }; xhr.upload.onprogress = function (e) { // For uploads if (e.lengthComputable) { pages.imageView(file_in_uploading); var percent = target.parent().parent().find('.percent'); percent.width(parseInt(e.loaded / e.total * 100) + '%'); } }; return xhr; }, success: function (response) { if (response.success) { $.each(response.files, function (i) { pages.imageView((i + 1), this); }) countImage.text(response.count + '/' + pages.files_limit); } }, error: function (error) { var data = error.responseJSON; return Swal.fire({ type: 'error', title: 'Oop!', html: data.message, showConfirmButton: true, }) } }); }, rotateImage: function (id, target = false) { var formData = new FormData(); formData.append('_token', pages.token); formData.append('id', id); $.ajax({ url: pages.rotate_url + id, method: "POST", data: formData, contentType: false, processData: false, success: function (response) { if (response.success) { if (target) { target.parent().find('.img-contain').attr("src", response.image); // var rotate = target.parent().find('.img-contain').attr('data-rotate'); // if (rotate === undefined) { // rotate = 1; // } else { // if (rotate > 3) { // rotate = 0; // } else { // rotate++; // } // } // switch (rotate) { // default: // case 0: // target.parent().find('.img-contain').attr('data-rotate', 0).css('transform', 'rotate(0deg)'); // break; // case 1: // target.parent().find('.img-contain').attr('data-rotate', 1).css('transform', 'rotate(90deg)'); // break; // case 2: // target.parent().find('.img-contain').attr('data-rotate', 2).css('transform', 'rotate(180deg)'); // break; // case 3: // target.parent().find('.img-contain').attr('data-rotate', 3).css('transform', 'rotate(270deg)'); // break; // }; } } }, error: function (error) { console.log(error); } }); }, deleteImage: function (id, target = false) { var formData = new FormData(); formData.append('_token', pages.token); formData.append('id', id); formData.append('property_id', target.parents("form").find('[name="property_id"]').val()); $.ajax({ url: pages.delete_url + id, method: "POST", data: formData, contentType: false, processData: false, success: function (response) { if (response.success) { if (target) { target.parent().parent().find('[data-files]').removeAttr('data-files'); target.remove(); countImage.text(response.count + '/' + pages.files_limit); } return Swal.fire({ type: 'success', title: 'Delete Image', html: response.message, showConfirmButton: true, timer:2000, }); } }, error: function (error) { console.log(error); } }); }, b64toFile: function (dataURI) { const byteString = atob(dataURI.split(',')[1]); const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0] const ab = new ArrayBuffer(byteString.length); const ia = new Uint8Array(ab); for (let i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } const blob = new Blob([ab], { 'type': mimeString }); blob['lastModifiedDate'] = (new Date()).toISOString(); blob['name'] = 'file'; switch (blob.type) { case 'image/jpeg': blob['name'] += '.jpg'; break; case 'image/png': blob['name'] += '.png'; break; } return blob; }, bytesToSize: function (bytes) { var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (bytes == 0) return '0 Bytes'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); return Math.round(bytes / Math.pow(1024, i), 2) + '' + sizes[i]; }, save: () => { listImage.parents('form').on('submit', (e) => { e.preventDefault(); var formData = new FormData(e.target); $.ajax({ url: pages.save_url, method: "POST", data: formData, contentType: false, processData: false, beforeSend: function () { listImage.parent().append('<div class="proccessing"><div class="image"></div>'); listImage.parents('form').find('[type="submit"]').attr('disabled', 'disabled'); }, success: function (response) { if (response.success) { return Swal.fire({ type: 'success', title: response.title, html: response.message, showConfirmButton: true, timer:2500, onClose: function (e) { listImage.parents('form').find('[type="submit"]').removeAttr('disabled'); listImage.parent().find('.proccessing').remove(); return window.location.href = response.redirect; } }); var showContainer = $('<div></div>'); $.each(response.files, function (i, files) { for (var file in files) { var imageContainer = $('<div> ' + files[file].size + ' </div>'), image = $('<img>'); if (files[file].size === "original") { imageContainer.addClass('col-md-12 mt-5').css('border', '1px solid rgb(0,0,0,0.1)'); image.css({ width: '100%', height: '100%', }) } else { imageContainer.addClass('col-md-2 mt-5').css('border', '1px solid rgb(0,0,0,0.1)'); } image.attr({ alt: files[file].name, src: files[file].path, }); image.appendTo(imageContainer); imageContainer.appendTo(showContainer); } }) showContainer.addClass('col-md-12 mt-5 mb-5').css('border', '1px solid rgb(0,0,0,0.1)'); listImage.parents('form').parent().css('display', 'none'); listImage.parents('form').parent().parent().append(showContainer); } else { return Swal.fire({ type: 'success', title: response.title, html: response.message, showConfirmButton: true, timer:2500, onClose: function (e) { listImage.parents('form').find('[type="submit"]').removeAttr('disabled'); listImage.parent().find('.proccessing').remove(); return window.location.href = response.redirect; } }); } }, error: function (error) { console.log(error); } }); }); } }; pages.init(); } })(jQuery); <file_sep>/app/Http/Requests/User/AddValidation.php <?php namespace App\Http\Requests\User; use Illuminate\Foundation\Http\FormRequest; class AddValidation extends FormRequest { public function authorize() { return true; } public function rules() { return [ 'name_en' => 'required|string|max:50', 'name_kh' => 'required|string|max:50', 'username' => 'required|string|max:50|unique:users', 'email' => 'required|email|unique:users', 'phone' => 'required|unique:users', 'referal_code' => 'required', 'referal_user_id' => 'required', 'referal_user_code' => 'required', 'province_id' => 'required', 'district_id' => 'required', 'commune_id' => 'required', 'password' => '<PASSWORD>', 'photo' => 'required', ]; } public function messages() { return [ 'name_en.required' => 'Please, Add Name.', 'name_kh.required' => 'Please, Add NameKh.', 'username.required' => 'Please, Add UserName.', 'email.required' => 'Please, Add Email.', 'email.unique' => 'Please, Add Unique Email.', 'email.required' => 'Please, Add Phone.', 'phone.unique' => 'Please, Add Unique Phone.', 'referal_code.required' => 'Please, Add Correct Referal Code.', 'referal_user_id.required' => 'Please, Add Correct Referal_User_ID.', 'referal_user_code.required' => 'Please, Add Correct Referal_User_Code.', 'province_id.required' => 'Please, Choose Province.', 'district_id.required' => 'Please, Choose District.', 'commune_id.required' => 'Please, Choose the Commune.', 'password.required' => 'Please, Add Password.', 'photo.required' => 'Please, Upload Photo.' ]; } } <file_sep>/app/Models/Facing.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Facing extends Model { public static function facings() { return static::pluck('facing', 'id'); } } <file_sep>/routes/web.php <?php // use Illuminate\Support\Str; // use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Route; //for switching language route Route::get('/locale/{locale}',function($locale){ Session::put('locale',$locale); return redirect()->back(); }); // front page route Route::get('/','HomeController@index')->name('home'); Route::post('/referal/check', 'CheckReferalController@check')->name('referal.check'); Route::prefix('property')->group(function(){ Route::get('/all-properties-in-{slug}','HomeController@property_by_province')->name('property.by.province'); Route::get('/list_by_category','HomeController@listProperties')->name('property.by_category'); Route::get('/allproperties','HomeController@allProperties')->name('property.allProperties'); Route::get('/allproperties-grid','HomeController@allPropertiesGrid')->name('property.allProperties.grid'); Route::get('/detail/{slug}','HomeController@showProperties')->name('property.show'); Route::get('/search','HomeController@mainSearch')->name('property.mainSearch'); Route::get('/search.html','HomeController@searchByCategory')->name('property.searchByCategory'); Route::get('/{slug}','HomeController@property_by_type')->name('property.by.type'); }); Auth::routes(); Route::post('/user/logout', 'Auth\LoginController@userLogout')->name('user.logout'); Route::get('get-district-list','Agent\PostController@getDistrictList'); Route::get('get-commune-list','Agent\PostController@getCommuneList'); Route::get('get-district-search','HomeController@getDistrictSearch'); Route::get('get-commune-search','HomeController@getCommuneSearch'); // Agent Route Route::group(['as'=>'agent.','prefix'=>'agent','namespace'=>'Agent','middleware' =>['auth']],function (){ Route::prefix('post')->group(function(){ Route::get('/','PostController@index')->name('post.index'); Route::get('/{id}/category={cat_id}','PostController@indexEdit')->name('post.indexEdit'); Route::get('/category={cate_id}','PostController@create')->name('post.create'); Route::post('/image_upload_tmp','PostController@store')->name('post.image.upload'); Route::post('/image/rotate/{id}','PostController@rotate')->name('post.image.rotate'); Route::post('/image/delete/{id}','PostController@delete')->name('post.image.delete'); Route::post('/store','PostController@saveProperties')->name('post.store'); Route::get('/property={pro_id}category={cat_id}','PostController@editProperties')->name('post.edit'); Route::put('/{id}/update','PostController@updateProperties')->name('post.update'); Route::post('/destroy','PostController@deleteProperties')->name('post.destroy'); Route::get('/{slug}','PostController@showProperties')->name('post.show'); }); Route::get('/manage_ads', 'DashboardController@index')->name('dashboard'); Route::get('/likes', 'DashboardController@index')->name('likes'); Route::get('/notifications', 'DashboardController@index')->name('notifications'); Route::get('/chats', 'DashboardController@index')->name('chats'); Route::get('/setting', 'DashboardController@index')->name('setting'); Route::get('/manage_ads/paid_ads', 'DashboardController@index')->name('paid_ads'); Route::get('/manage_ads/expired_ads', 'DashboardController@index')->name('expired_ads'); // member route Route::get('/profile','DashboardController@profile')->name('profile'); Route::get('/edit-profile','DashboardController@editProfile')->name('edit-profile'); Route::put('/update-profile/{userid}','DashboardController@updateProfile')->name('update-profile'); Route::get('/change-password','DashboardController@changePassword')->name('change-password'); Route::put('/update-password/{userid}','DashboardController@updatePassword')->name('update-password'); Route::get('/store','DashboardController@store')->name('store'); Route::get('/store-banner','DashboardController@storeBanner')->name('store-banner'); }); // Admin Route Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware' =>['auth']],function (){ Route::get('/', 'DashboardController@index')->name('dashboard')->middleware('isAdmin'); // General Settings Route Route::get('/settings/general/edit', 'WebmasterSettingController@editGeneral')->name('general.edit'); Route::put('/settings/general/update', 'WebmasterSettingController@updateGeneral')->name('general.update'); // activities logs Route::resource('/activitylogs', 'ActivityLogsController'); Route::resource('/settings', 'SettingsController'); Route::get('/generator', ['uses' => 'ProcessController@getGenerator']); Route::post('/generator', ['uses' => 'ProcessController@postGenerator']); // User Role & Permission Route Route::resource('users', 'UserController'); Route::get('/profile','UserController@getProfile')->name('profile'); Route::resource('roles', 'RoleController'); Route::resource('permissions', 'PermissionController'); Route::resource('properties', 'PropertyController'); Route::resource('categories', 'CategoryController'); // Product routes Route::resource('products','ProductController'); Route::get('dropzone/upload','ProductController@dropzone')->name('upload.dropzone'); Route::post('dropzone/upload','ProductController@dropzoneStore')->name('upload.dropzone.store'); Route::post('dropzone/delete', 'ProductController@dropzonedelete')->name('upload.dropzone.delete'); Route::get('dropzone/gallery-list', 'ProductController@gallery_list')->name('upload.dropzone.list'); Route::resource('mails', 'MailController'); Route::get('/upload', 'DropZoneController@upload')->name('dropzone.create'); Route::post('/upload/store', 'DropZoneController@store')->name('dropzone.store'); Route::post('/delete', 'DropZoneController@delete')->name('dropzone.delete'); Route::resource('images','ImageController'); //Route Report Route::get('/report/agent','ReportController@agent')->name('report.agent'); Route::get('/report/property','ReportController@property')->name('report.property'); Route::get('report/agent/management','AgentManagementController@agentChart')->name('agent.chart'); Route::get('agent/list','AgentManagementController@index')->name('agent.list'); Route::get('agent/create','AgentManagementController@create')->name('agent.create'); Route::post('agent/store','AgentManagementController@store')->name('agent.store'); Route::get('agent/management-json/{user_id}','AgentManagementController@agent_json')->name('agent.json'); }); Route::get('/backup','Admin\BackupController@backup'); //Clear Cache facade value: Route::get('/clear-cache', function() { $exitCode = Artisan::call('cache:clear'); return '<h1>Cache facade value cleared</h1>'; }); //Reoptimized class loader: Route::get('/optimize', function() { $exitCode = Artisan::call('optimize'); return '<h1>Reoptimized class loader</h1>'; }); //Route cache: Route::get('/route-cache', function() { $exitCode = Artisan::call('route:cache'); return '<h1>Routes cached</h1>'; }); //Clear Route cache: Route::get('/route-clear', function() { $exitCode = Artisan::call('route:clear'); return '<h1>Route cache cleared</h1>'; }); //Clear View cache: Route::get('/view-clear', function() { $exitCode = Artisan::call('view:clear'); return '<h1>View cache cleared</h1>'; }); //Clear Config cache: Route::get('/config-cache', function() { $exitCode = Artisan::call('config:cache'); return '<h1>Clear Cache cleared</h1>'; }); //Clear Config cache: Route::get('/config-clear', function() { $exitCode = Artisan::call('config:clear'); return '<h1>Clear Config cleared</h1>'; }); Route::get('/insert/user', function() { $exitCode = Artisan::call('db:seed'); return '<h1>User has been inserted Successful</h1>'; }); // copy data from one table to another table // Route::get('/multi_update',function(){ // $districts = DB::table('provinces')->get(); // foreach ($districts as $key => $value) { // $data2[] = array( // 'name_en' => $value->name_en, // 'en' => $value->name_en, // 'kh' => $value->name_kh, // 'slug' => Str::slug($value->name_en), // ); // } // return $data2; // DB::table('provinces1')->insert($data2); // return "Data has been insert"; // }); <file_sep>/app/Http/Controllers/Admin/AgentManagementController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Models\Agent; use Illuminate\Http\Request; use App\Models\User; use DB; class AgentManagementController extends Controller { public function agentChart() { $admin = User::whereIn('id',[1])->select('id as user_id','name_en','referal_code as referal_user_code','ref_level','phone','photo')->get()->toArray(); $agent = Agent::get()->toArray(); $arr_merge = array_merge($admin,$agent); return view('admin.agent_management.agent_chart',compact('arr_merge')); } public function index() { $data['agents'] = Agent::get(); return view('admin.agent_management.agent_list',$data); } public function create() { return view('admin.agent_management.create'); } public function store(Request $request) { $user = DB::table('agents')->latest('user_id')->first(); $user_id=$user->user_id; $request->validate([ 'referal_user_id' => ['required'], 'name_en' => ['required', 'string','max:30'], 'name_kh' => ['required', 'string','max:30'], 'phone' => ['required', 'string','max:15', 'unique:agents'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:agents'], 'photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $datas = [ 'user_id' => $user_id+1, 'referal_user_id' => $request->referal_id, 'referal_user_code' => $request->referal_user_id, 'name_en' => $request->name_en, 'name_kh' => $request->name_kh, 'job_title' => $request->job_title, 'phone' => $request->phone, 'email' => $request->email, 'address' => $request->address, 'photo' => $request->photo, // 'description' => $request, // 'phone1' => $request, // 'phone2' => $request, // 'phone3' => $request, // 'phone4' => $request, // 'facebook' => $request, // 'twitter' => $request, // 'pinterest' => $request, // 'linkedin' => $request, ]; return $datas; Agent::create($datas); return redirect(route('admin.agent.list'))->with('success','New Agent Registration Successfully!'); } public function user_referal($user_id) { if($user_id){ return Agent::where('referal_user_id',$user_id)->get()->map(function($row){ $row->photo = asset('uploads/user/profile/'.$row->photo); $row['children'] = $this->user_referal($row->user_id); return $row; })->toArray(); } } public function agent_json($user_id) { $user = User::where('id',$user_id)->select('id as user_id','name_en','referal_code as referal_user_code','ref_level','phone','photo')->get()->map(function($row){ $row->photo = asset('uploads/user/profile/'.$row->photo); return $row; })->first(); $user['children'] = $this->user_referal($user_id); return $user; } } <file_sep>/resources/lang/km/pagination.php <?php return array ( 'next' => 'ទៅមុខ', 'previous' => 'ថយក្រោយ', ); <file_sep>/app/Http/Middleware/AdminMiddleware.php <?php namespace App\Http\Middleware; use Auth; use Closure; use App\Models\User; class AdminMiddleware { public function handle($request, Closure $next) { $user = User::all()->count(); if (!($user == 1)) { if (!Auth::user()->hasPermissionTo('Administer roles & permissions')) //If user does //not have this permission { abort('403'); } } // if(Auth::check()&& Auth::user()->role->id==1) // { // return $next($request); // } else { // return redirect()->route('login'); // } return $next($request); } } <file_sep>/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use Session; use App\Models\Commune; use App\Models\Category; use App\Models\District; use App\Models\Operator; use App\Models\Property; use App\Models\Province; use App\Models\PropertyType; use Illuminate\Http\Request; use App\Models\PropertyGallery; class HomeController extends Controller { protected $limit = 10; public function getDistrictSearch(Request $request) { $districts = District::whereHas("province",function($query) use ($request){ $query->where('slug',$request->province_id); }) ->pluck("name_en","slug"); return response()->json($districts); } public function getCommuneSearch(Request $request) { $communes = Commune::whereHas("district",function($query) use ($request){ $query->where('slug',$request->district_id); }) ->pluck("name_en","slug"); return response()->json($communes); } public function index(Request $request) { $data['protypes'] = PropertyType::with('cateSub') -> where('parent_id','>',0) ->orderBy('id') ->groupBy('name_en') ->get(); $data['property_types'] = PropertyType::where('parent_id',0)->take(5)->get(); // $data['categories'] = Category::where(['parent_id'=>0])->published()->get(); if($request->location){ $data['location'] = $request->location; } else { $data['location'] = ''; } if($request->category){ $data['s_category'] = $request->category; } else { $data['s_category'] = ''; } $data['properties'] = Property::filterByRequest($request)->get(); $data['provinces'] = Province::get(); $data['category_by_properties'] = Category::where(['parent_id'=>5])->get(); return view('front.property',$data); } public function property_by_province(Request $request,$slug) { $data['search_category']='house-and-land'; $data['districts']=District::whereHas('province',function($query) use ($request){ $query->where('slug','like','%'.$request->location.'%'); })->pluck('name_en','slug'); $data['province_id'] = $slug; if($request->input('district')){ $data['district_id'] = $request->district; } else { $data['district_id'] = ''; } if($request->input('commune')){ $data['commune_id'] = $request->commune; } else { $data['commune_id'] = ''; } $data['categories'] = Category::where(['parent_id'=>0])->published()->get(); $data['pro_type'] = Category::where('slug',$data['search_category'])->first(); $data['cat_type'] = Category::where('id',$data['pro_type']->parent_id)->first(); $data['provinces'] = Province::pluck('name_en','slug'); $data['property_by_province'] = Property::whereHas('province',function($query) use ($slug){ $query->where('slug',$slug); })->paginate($this->limit); return view('front.property_by_province',$data); } public function listProperties() { $properties = Property::where('user_id',auth()->user()->id) ->orderBy('created_at','desc') ->get(); return view('freeads.showAllProperties',compact('properties')); } public function allProperties(Request $request) { $data['search_category']='house-and-land'; $data['protypes'] = PropertyType::where('parent_id','>',0) ->orderBy('id') ->groupBy('name_en') ->get(); $data['category_by_properties'] = Category::where(['parent_id'=>5]) ->Published() ->get(); $data['categories'] = Category::where(['parent_id'=>0])->published()->get(); $data['provinces'] = Province::pluck('name_en','slug'); if($request->input('location')){ $data['province_id'] = $request->input('location'); $data['districts']=District::whereHas('province',function($query) use ($request){ $query->where('slug','like','%'.$request->location.'%'); })->pluck('name_en','slug'); } else { $data['province_id'] = ''; } if($request->input('district')){ $data['district_id'] = $request->district; $data['communes']=Commune::whereHas('district',function($query) use ($request){ $query->where('slug','like','%'.$request->district.'%'); })->pluck('name_en','slug'); } else { $data['district_id'] = ''; } if($request->input('commune')){ $data['commune_id'] = $request->commune; } else { $data['commune_id'] = ''; } if($request->input('location') ||$request->input('district')||$request->input('commune') ){ $data['allProperties'] = Property::FilterByCategories($request)->paginate($this->limit); } else { $data['allProperties'] = Property::orderBy('created_at','desc') ->paginate($this->limit); } return view('front.all_properties',$data); } public function allPropertiesGrid(Request $request) { $data['search_category']='house-and-land'; $data['protypes'] = PropertyType::where('parent_id','>',0) ->orderBy('id') ->groupBy('name_en') ->get(); $data['category_by_properties'] = Category::where(['parent_id'=>5]) ->Published() ->get(); $data['categories'] = Category::where(['parent_id'=>0])->published()->get(); $data['provinces'] = Province::pluck('name_en','slug'); if($request->input('location')){ $data['province_id'] = $request->input('location'); $data['districts']=District::whereHas('province',function($query) use ($request){ $query->where('slug','like','%'.$request->location.'%'); })->pluck('name_en','slug'); } else { $data['province_id'] = ''; } if($request->input('district')){ $data['district_id'] = $request->district; $data['communes']=Commune::whereHas('district',function($query) use ($request){ $query->where('slug','like','%'.$request->district.'%'); })->pluck('name_en','slug'); } else { $data['district_id'] = ''; } if($request->input('commune')){ $data['commune_id'] = $request->commune; } else { $data['commune_id'] = ''; } if($request->input('location') ||$request->input('district')||$request->input('commune') ){ $data['allProperties'] = Property::FilterByCategories($request)->paginate($this->limit); } else { $data['allProperties'] = Property::orderBy('created_at','desc') ->paginate($this->limit); } return view('front.all_properties-grid',$data); } public function property_by_type(Request $request, $type) { $data['search_category'] = $type; if($request->input('location')){ $data['province_id'] = $request->location; $data['district_id']=''; $data['districts']=District::whereHas('province',function($query) use ($request){ $query->where('slug','like','%'.$request->location.'%'); })->pluck('name_en','slug'); } else { $data['province_id'] = ''; } if($request->input('district')){ $data['district_id'] = $request->district; $data['commune_id']=''; $data['communes']=Commune::whereHas('district',function($query) use ($request){ $query->where('slug','like','%'.$request->district.'%'); })->pluck('name_en','slug'); } else { $data['district_id'] = ''; } if($request->input('commune')){ $data['commune_id'] = $request->commune; } else { $data['commune_id'] = ''; } if($request->input('ad_bedroom')){ $data['bedroom'] = $request->ad_bedroom; } else { $data['bedroom'] = ''; } if($request->input('ad_bathroom')){ $data['bathroom'] = $request->ad_bathroom; } else { $data['bathroom'] = ''; } if($request->input('ad_facing')){ $data['face'] = $request->ad_facing; } else { $data['face'] = ''; } if($request->from_ad_price){ $data['from_ad_price']=$request->from_ad_price; } else { $data['from_ad_price']=''; } if($request->to_ad_price){ $data['to_ad_price']=$request->to_ad_price; } else { $data['to_ad_price']=''; } if($request->from_ad_size){ $data['from_ad_size']=$request->from_ad_size; } else { $data['from_ad_size']=''; } if($request->to_ad_size){ $data['to_ad_size']=$request->to_ad_size; } else { $data['to_ad_size']=''; } $data['pro_type'] = Category::where('slug',$type)->first(); $data['cat_type'] = Category::where('id',$data['pro_type']->parent_id)->first(); $data['property_by_categories'] = Property::whereHas('parent',function($query) use ($type){ $query->where('slug',$type); })->get(); $data['categories'] = Category::where(['parent_id'=>0])->published()->get(); $data['provinces'] = Province::pluck('name_en','slug'); if($request->category){ $data['property_by_categories'] = Property::filterByCategory($request)->get(); } return view('front.properties_by_category',$data); } public function showProperties($slug) { $categories = Category::where(['parent_id'=>0])->published()->get(); $property = Property::where('slug',$slug)->first(); $view_name = $property->parent->form_name; $cellcards = Operator::pluck('cellcard')->toArray(); $smarts = Operator::pluck('smart')->toArray(); $metfones = Operator::pluck('metfone')->toArray(); $qbs = Operator::pluck('qb')->toArray(); $operator1 = substr($property->phone1, 0,3); $operator2 = substr($property->phone2, 0,3); $operator3 = substr($property->phone3, 0,3); $phone1 = $property->phone1; $phone2 = $property->phone2; $phone3 = $property->phone3; if ($property->phone1!='') { $operator1 = substr($property->phone1, 0,3); } else { $operator1=''; } if ($property->phone2!='') { $operator2 = substr($property->phone2, 0,3); } else { $operator2=''; } if ($property->phone3!='') { $operator3 = substr($property->phone3, 0,3); } else { $operator3=''; } if($operator1){ if(in_array($operator1, $cellcards)){ $operator_name1 = 'Cellcard'; } else if(in_array($operator1, $smarts)){ $operator_name1 = 'Smart'; } else if(in_array($operator1, $metfones)){ $operator_name1 = 'Metfone'; } else if(in_array($operator1, $qbs)){ $operator_name1 = 'Qb'; } else { $operator_name1 = 'Other'; } } else { $operator_name1 = ''; } if($operator2){ if(in_array($operator2, $cellcards)){ $operator_name2 = 'Cellcard'; } else if(in_array($operator2, $smarts)){ $operator_name2 = 'Smart'; } else if(in_array($operator2, $metfones)){ $operator_name2 = 'Metfone'; } else if(in_array($operator2, $qbs)){ $operator_name2 = 'Qb'; } else { $operator_name2 = 'Other'; } } else { $operator_name2 = ''; } if($operator3){ if(in_array($operator3, $cellcards)){ $operator_name3 = 'Cellcard'; } else if(in_array($operator3, $smarts)){ $operator_name3 = 'Smart'; } else if(in_array($operator3, $metfones)){ $operator_name3 = 'Metfone'; } else if(in_array($operator3, $qbs)){ $operator_name3 = 'Qb'; } else { $operator_name3 = 'Other'; } } else { $operator_name3 = ''; } $blogKey = 'blog_' .$property->id; if(!Session::has($blogKey)){ $property->increment('view_count'); Session::put($blogKey,1); } $random_properties = Property::inRandomOrder()->take(15)->get(); // return $operator_name3; $images = PropertyGallery::where('property_id',$property->id)->get(); return view($view_name.'.show',compact('property','images','categories','operator_name1','operator_name2','operator_name3','random_properties','phone1','phone2','phone3')); } public function mainSearch(Request $request) { if($request->location){ $data['province_id']= $request->input('location'); } else { $data['province_id']=''; } if($request->district){ $data['district_id']= $request->input('district'); } else { $data['district_id']=''; } if($request->commune){ $data['commune_id']= $request->input('commune'); } else { $data['commune_id']=''; } $data['search_category'] = $request->category; $data['location'] = $request->location; $data['pro_type'] = Category::where('slug',$data['search_category'])->first(); $data['cat_type'] = Category::where('id',$data['pro_type']->parent_id)->first(); $data['provinces'] = Province::pluck('name_en','slug'); $data['districts'] = District::whereHas("province",function($query) use ($request){ $query->where('slug',$request->input('location')); }) ->pluck("name_en","slug"); $data['property_by_categories'] = Property::filterByRequest($request)->get(); return view('front.search_form',$data); } public function searchByCategory(Request $request) { $data['search_category'] = $request->category; // if ($data['search_category']=='house-for-sale' || $data['search_category']=='house-for-rent'){ if($request->input('ad_bedroom')){ $data['bedroom'] = $request->ad_bedroom; } else { $data['bedroom'] = ''; } if($request->input('ad_bathroom')){ $data['bathroom'] = $request->ad_bathroom; } else { $data['bathroom'] = ''; } if($request->input('ad_facing')){ $data['face'] = $request->ad_facing; } else { $data['face'] = ''; } // } if($request->input('location')){ $data['province_id'] = $request->location; $data['districts']=District::whereHas('province',function($query) use ($request){ $query->where('slug','like','%'.$request->location.'%'); })->pluck('name_en','slug'); } else { $data['province_id'] = ''; } if($request->input('district')){ $data['district_id'] = $request->district; // return $data['district_id']; $data['communes']=Commune::whereHas('district',function($query) use ($request){ $query->where('slug','like','%'.$request->district.'%'); })->pluck('name_en','slug'); } else { $data['district_id'] = ''; } if($request->input('commune')){ $data['commune_id'] = $request->commune; } else { $data['commune_id'] = ''; } if($request->from_ad_price){ $data['from_ad_price']=$request->from_ad_price; } else { $data['from_ad_price']=''; } if($request->to_ad_price){ $data['to_ad_price']=$request->to_ad_price; } else { $data['to_ad_price']=''; } if($request->from_ad_size){ $data['from_ad_size']=$request->from_ad_size; } else { $data['from_ad_size']=''; } if($request->to_ad_size){ $data['to_ad_size']=$request->to_ad_size; } else { $data['to_ad_size']=''; } $data['pro_type'] = Category::where('slug',$data['search_category'])->first(); $data['cat_type'] = Category::where('id',$data['pro_type']->parent_id)->first(); $data['provinces'] = Province::pluck('name_en','slug'); $data['property_by_categories'] = Property::filterByCategory($request)->get(); // return($data['property_by_categories']); return view('front.search_by_category',$data); } } <file_sep>/app/Models/Category.php <?php namespace App\Models; use App\Models\Upload as upload; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Category extends upload { use SoftDeletes; protected $dates = ['deleted_at']; protected $table = 'categories'; protected $primaryKey = 'id'; protected $fillable = [ 'parent_id','type_id','sub_type_id', 'category_name','category_name_kh', 'description', 'is_active', 'slug','description', 'form_name','form_header','form_footer', 'icon','url', ]; public function childs() { return $this->hasMany(Category::class,'parent_id','id')->published(); } public function scopePublished($query) { return $query->where('is_active',1); } public function type() { return $this->belongsTo(PropertyType::class,'type_id','id'); } public function categorytype() { return $this->belongsTo(PropertyType::class,'type_id','id'); } public function subtype() { return $this->belongsTo(PropertyType::class,'sub_type_id','type_id'); } public function categorysubtype() { return $this->belongsTo(PropertyType::class,'sub_type_id','type_id'); } public function properties() { return $this->hasMany(Property::class,'parent_id','id'); } public function subcate() { return $this->hasOne(Category::class,'id','parent_id')->published(); } public static function categories() { return static::where(['parent_id'=>0])->published()->get();; } public static function parent() { return static::pluck('category_name', 'parent_id'); } } <file_sep>/resources/lang/km/passwords.php <?php return array ( 'reset' => 'ពាក្យសម្ងាត់របស់អ្នកត្រូវបានកំណត់ឡើងវិញហើយ!', 'sent' => 'យើងបានផ្ញើអ៊ីមែលតំណកំណត់លេខសំងាត់របស់អ្នកឡើងវិញ!', 'throttled' => 'សូមរង់ចាំមុនពេលព្យាយាមម្តងទៀត។', 'token' => 'និមិត្តសញ្ញាកំណត់លេខសំងាត់ឡើងវិញគឺមិនត្រឹមត្រូវទេ។', 'user' => 'យើងមិនអាចរកឃើញអ្នកប្រើដែលមានអាសយដ្ឋានអ៊ីមែលនោះទេ។', ); <file_sep>/database/communes.sql -- -------------------------------------------------------- -- Host: 127.0.0.1 -- Server version: 5.7.26 - MySQL Community Server (GPL) -- Server OS: Win64 -- HeidiSQL Version: 11.0.0.5919 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Dumping database structure for thepinrealestate_social_login DROP DATABASE IF EXISTS `thepinrealestate_social_login`; CREATE DATABASE IF NOT EXISTS `thepinrealestate_social_login` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `thepinrealestate_social_login`; -- Dumping structure for table thepinrealestate_social_login.communes DROP TABLE IF EXISTS `communes`; CREATE TABLE IF NOT EXISTS `communes` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `district_id` int(11) DEFAULT NULL, `name_en` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `name_kh` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `slug` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE=MyISAM AUTO_INCREMENT=944 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.communes: 943 rows /*!40000 ALTER TABLE `communes` DISABLE KEYS */; INSERT INTO `communes` (`id`, `district_id`, `name_en`, `name_kh`, `slug`, `created_at`, `updated_at`) VALUES (1, 1, '<NAME>', '', 'svay-pak', NULL, NULL), (2, 1, '<NAME>', '', 'russey-keo', NULL, NULL), (3, 1, '<NAME>', '', 'toul-sangke', NULL, NULL), (4, 1, 'Kilometr Lek 6', '', 'kilometr-lek-6', NULL, NULL), (5, 1, '<NAME> 1', '', 'chrang-chamreh-1', NULL, NULL), (6, 1, '<NAME>', '', 'chrang-chamreh-2', NULL, NULL), (7, 2, '<NAME>', '', 'krang-thnong', NULL, NULL), (8, 2, 'Khmuonh', '', 'khmuonh', NULL, NULL), (9, 2, '<NAME>', '', 'phnom-penh-thmei', NULL, NULL), (10, 2, '<NAME>', '', 'tuek-thla', NULL, NULL), (11, 2, '<NAME>', '', 'obek-kaom', NULL, NULL), (12, 3, 'Ovlaok', '', 'ovlaok', NULL, NULL), (13, 3, 'Kamboul', '', 'kamboul', NULL, NULL), (14, 3, 'Kantaok', '', 'kantaok', NULL, NULL), (15, 3, '<NAME>', '', 'boeng-thum', NULL, NULL), (16, 3, '<NAME>', '', 'phleung-chheh-roteh', NULL, NULL), (17, 3, '<NAME>', '', 'chaom-chau', NULL, NULL), (18, 3, '<NAME>', '', 'trapeang-krasang', NULL, NULL), (19, 3, 'Kakab', '', 'kakab', NULL, NULL), (20, 3, '<NAME>', '', 'samraong-kraom', NULL, NULL), (21, 3, 'Snaor', '', 'snaor', NULL, NULL), (22, 4, '<NAME>', '', 'bak-kheng', NULL, NULL), (23, 4, '<NAME>', '', 'praek-leab', NULL, NULL), (24, 4, '<NAME>', '', 'praek-ta-sek', NULL, NULL), (25, 4, '<NAME>', '', 'chrouy-changvar', NULL, NULL), (26, 4, '<NAME>', '', 'kaoh-dach', NULL, NULL), (27, 5, 'Ponsang', '', 'ponsang', NULL, NULL), (28, 5, '<NAME>', '', 'kouk-roka', NULL, NULL), (29, 5, '<NAME>', '', 'ponhea-pon', NULL, NULL), (30, 5, 'Samraong', '', 'samraong', NULL, NULL), (31, 5, '<NAME>', '', 'praek-phnov', NULL, NULL), (32, 6, '<NAME>', '', 'veal-sbov', NULL, NULL), (33, 6, '<NAME>', '', 'praek-aeng', NULL, NULL), (34, 6, '<NAME>', '', 'chbar-ampov-1', NULL, NULL), (35, 6, '<NAME>', '', 'chbar-ampov-2', NULL, NULL), (36, 6, 'Nirouth', '', 'nirouth', NULL, NULL), (37, 6, '<NAME>', '', 'praek-pra', NULL, NULL), (38, 6, '<NAME>', '', 'praek-thmei', NULL, NULL), (39, 6, '<NAME>', '', 'kbal-kaoh', NULL, NULL), (40, 7, '<NAME>', '', 'psar-thmei1', NULL, NULL), (41, 7, '<NAME>', '', 'psar-thmei2', NULL, NULL), (42, 7, '<NAME>', '', 'psar-thmei3', NULL, NULL), (43, 7, '<NAME>', '', 'boeung-reang', NULL, NULL), (44, 7, '<NAME>', '', 'psar-kandal1', NULL, NULL), (45, 7, '<NAME>', '', 'psar-kandal2', NULL, NULL), (46, 7, 'Chaktomukh', '', 'chaktomukh', NULL, NULL), (47, 7, '<NAME>', '', 'chey-chumneah', NULL, NULL), (48, 7, '<NAME>', '', 'psar-chas', NULL, NULL), (49, 7, '<NAME>', '', 'srah-chork', NULL, NULL), (50, 7, '<NAME>', '', 'vat-phnum', NULL, NULL), (51, 8, 'O Reussei 1', '', 'o-reussei-1', NULL, NULL), (52, 8, 'O Reussei 2', '', 'o-reussei-2', NULL, NULL), (53, 8, 'O Reussei 3', '', 'o-reussei-3', NULL, NULL), (54, 8, 'O Reussei 4', '', 'o-reussei-4', NULL, NULL), (55, 8, 'Monorom', '', 'monorom', NULL, NULL), (56, 8, 'Mittapheap', '', 'mittapheap', NULL, NULL), (57, 8, 'Vealvong', '', 'vealvong', NULL, NULL), (58, 8, '<NAME>', '', 'beung-prolit', NULL, NULL), (59, 9, 'Psar Depot1', '', 'psar-depot1', NULL, NULL), (60, 9, 'Psar Depot2', '', 'psar-depot2', NULL, NULL), (61, 9, 'Psar Depot3', '', 'psar-depot3', NULL, NULL), (62, 9, '<NAME>', '', 'teuk-laork1', NULL, NULL), (63, 9, '<NAME>', '', 'teuk-laork2', NULL, NULL), (64, 9, '<NAME>', '', 'teuk-laork3', NULL, NULL), (65, 9, '<NAME>', '', 'beung-kok1', NULL, NULL), (66, 9, '<NAME>', '', 'beung-kok2', NULL, NULL), (67, 9, '<NAME>', '', 'psar-deumkor', NULL, NULL), (68, 9, '<NAME>', '', 'beung-salang', NULL, NULL), (69, 10, 'Dangkor', '', 'dangkor', NULL, NULL), (70, 10, 'Prey Sa', '', 'prey-sa', NULL, NULL), (71, 10, '<NAME>', '', 'cheung-aek', NULL, NULL), (72, 10, '<NAME>', '', 'spean-thma', NULL, NULL), (73, 10, '<NAME>', '', 'prey-vaeng', NULL, NULL), (74, 10, '<NAME>', '', 'pong-tuek', NULL, NULL), (75, 10, '<NAME>', '', 'prateah-lang', NULL, NULL), (76, 10, '<NAME>', '', 'sak-sampov', NULL, NULL), (77, 10, '<NAME>', '', 'krang-pongro', NULL, NULL), (78, 10, '<NAME>', '', 'kong-noy', NULL, NULL), (79, 10, 'Tien', '', 'tien', NULL, NULL), (80, 10, '<NAME>', '', 'praek-kampues', NULL, NULL), (81, 11, '<NAME>', '', 'stung-meanchey', NULL, NULL), (82, 11, '<NAME>', '', 'boeng-tompun', NULL, NULL), (83, 11, '<NAME>', '', 'chak-angrae-leu', NULL, NULL), (84, 11, '<NAME>', '', 'chak-angrae-kroam', NULL, NULL), (85, 12, '<NAME>', '', 'tonle-bassac', NULL, NULL), (86, 12, '<NAME>', '', 'beung-kengkang1', NULL, NULL), (87, 12, '<NAME>', '', 'beung-kengkang2', NULL, NULL), (88, 12, '<NAME>', '', 'beung-kengkang3', NULL, NULL), (89, 12, 'Olympic', '', 'olympic', NULL, NULL), (90, 12, '<NAME>', '', 'toul-svayprey1', NULL, NULL), (91, 12, '<NAME>', '', 'toul-svayprey2', NULL, NULL), (92, 12, '<NAME>', '', 'tomnub-teuk', NULL, NULL), (93, 12, '<NAME>', '', 'toul-tompung1', NULL, NULL), (94, 12, '<NAME>', '', 'toul-tompung2', NULL, NULL), (95, 12, '<NAME>', '', 'beung-trabaek', NULL, NULL), (96, 12, '<NAME>', '', 'psar-deumtkov', NULL, NULL), (97, 13, 'Sangkat 1', '', 'sangkat-1', NULL, NULL), (98, 13, 'Sangkat 2', '', 'sangkat-2', NULL, NULL), (99, 13, 'Sangkat 3', '', 'sangkat-3', NULL, NULL), (100, 13, 'Sangkat 4', '', 'sangkat-4', NULL, NULL), (101, 13, '<NAME>', '', 'koh-rong', NULL, NULL), (102, 14, '<NAME>', '', 'andong-thmar', NULL, NULL), (103, 14, '<NAME>', '', 'beung-taprum', NULL, NULL), (104, 14, '<NAME>', '', 'bet-trang', NULL, NULL), (105, 14, '<NAME>', '', 'cheung-koar', NULL, NULL), (106, 14, '<NAME>', '', 'ou-chrov', NULL, NULL), (107, 14, '<NAME>', '', 'ou-oknha-heng', NULL, NULL), (108, 14, '<NAME>', '', 'prey-nob', NULL, NULL), (109, 14, 'Ream', '', 'ream', NULL, NULL), (110, 14, 'Sammaki', '', 'sammaki', NULL, NULL), (111, 14, 'Somrong', '', 'somrong', NULL, NULL), (112, 14, '<NAME>', '', 'teuk-laork', NULL, NULL), (113, 14, '<NAME>', '', 'teuk-tla', NULL, NULL), (114, 14, '<NAME>', '', 'toul-toteung', NULL, NULL), (115, 14, '<NAME>', '', 'veal-rinh', NULL, NULL), (116, 15, 'Kompenh', '', 'kompenh', NULL, NULL), (117, 15, '<NAME>', '', 'ou-treh', NULL, NULL), (118, 15, '<NAME>', '', 'tomnob-rolork', NULL, NULL), (119, 15, '<NAME>', '', 'keo-phos', NULL, NULL), (120, 16, '<NAME>', '', 'chomkar-loung', NULL, NULL), (121, 16, '<NAME>', '', 'kampong-seila', NULL, NULL), (122, 16, '<NAME>', '', 'ou-bak-roteh', NULL, NULL), (123, 16, '<NAME>', '', 'steung-chhay', NULL, NULL), (124, 17, '<NAME>', '', 'boeng-kok', NULL, NULL), (125, 17, '<NAME>', '', 'kampong-cham', NULL, NULL), (126, 17, '<NAME>', '', 'sambuor-meas', NULL, NULL), (127, 17, '<NAME>', '', 'veal-vong', NULL, NULL), (128, 18, 'Ampil', '', 'ampil', NULL, NULL), (129, 18, '<NAME>', '', 'hann-chey', NULL, NULL), (130, 18, '<NAME>', '', 'kien-chrey', NULL, NULL), (131, 18, 'Kokor', '', 'kokor', NULL, NULL), (132, 18, '<NAME>', '', 'kaoh-mitt', NULL, NULL), (133, 18, '<NAME>', '', 'kaoh-roka', NULL, NULL), (134, 18, '<NAME>', '', 'kaoh-samraong', NULL, NULL), (135, 18, '<NAME>', '', 'kaoh-tontuem', NULL, NULL), (136, 18, 'Krala', '', 'krala', NULL, NULL), (137, 18, '<NAME>', '', 'ou-svay', NULL, NULL), (138, 18, '<NAME>', '', 'ro-any', NULL, NULL), (139, 18, 'Rumchek', '', 'rumchek', NULL, NULL), (140, 18, 'Srak', '', 'srak', NULL, NULL), (141, 18, 'Trean', '', 'trean', NULL, NULL), (142, 18, '<NAME>', '', 'vihear-thum', NULL, NULL), (143, 19, '<NAME>', '', 'angkor-ban', NULL, NULL), (144, 19, '<NAME>', '', 'kong-taneung', NULL, NULL), (145, 19, 'Khchau', '', 'khchau', NULL, NULL), (146, 19, '<NAME>', '', 'peam-chikong', NULL, NULL), (147, 19, '<NAME>', '', 'prek-koy', NULL, NULL), (148, 19, '<NAME>', '', 'prek-krabau', NULL, NULL), (149, 19, '<NAME>', '', 'reay-pay', NULL, NULL), (150, 19, 'Roka-a', '', 'roka-a', NULL, NULL), (151, 19, 'Roka-koy', '', 'roka-koy', NULL, NULL), (152, 19, 'Sdau', '', 'sdau', NULL, NULL), (153, 19, '<NAME>', '', 'sor-korng', NULL, NULL), (154, 20, '<NAME>', '', 'kampong-reab', NULL, NULL), (155, 20, '<NAME>', '', 'koh-sotin', NULL, NULL), (156, 20, 'Tve', '', 'tve', NULL, NULL), (157, 20, 'Mohaleap', '', 'mohaleap', NULL, NULL), (158, 20, '<NAME>', '', 'moha-knhoung', NULL, NULL), (159, 20, '<NAME>', '', 'peam-brothnous', NULL, NULL), (160, 20, 'Pongro', '', 'pongro', NULL, NULL), (161, 20, '<NAME>', '', 'prek-tanung', NULL, NULL), (162, 21, 'Baray', '', 'baray', NULL, NULL), (163, 21, '<NAME>', '', 'beung-nay', NULL, NULL), (164, 21, '<NAME>', '', 'chrey-vean', NULL, NULL), (165, 21, 'Mean', '', 'mean', NULL, NULL), (166, 21, '<NAME>', '', 'trapeang-preah', NULL, NULL), (167, 21, '<NAME>', '', 'khvet-thum', NULL, NULL), (168, 21, 'Kor', '', 'kor', NULL, NULL), (169, 21, 'Krouch', '', 'krouch', NULL, NULL), (170, 21, 'Lvea', '', 'lvea', NULL, NULL), (171, 21, '<NAME>', '', 'prey-chor', NULL, NULL), (172, 21, '<NAME>', '', 'sor-sen', NULL, NULL), (173, 21, 'Somrorng', '', 'somrorng', NULL, NULL), (174, 21, '<NAME>', '', 'sro-ngae', NULL, NULL), (175, 21, '<NAME>', '', 'thma-poun', NULL, NULL), (176, 21, '<NAME>', '', 'tong-rong', NULL, NULL), (177, 22, 'Baray', '', 'baray', NULL, NULL), (178, 22, 'Chibal', '', 'chibal', NULL, NULL), (179, 22, '<NAME>', '', 'khnar-sor', NULL, NULL), (180, 22, '<NAME>', '', 'koh-andet', NULL, NULL), (181, 22, '<NAME>', '', 'mean-chey', NULL, NULL), (182, 22, '<NAME>', '', 'phteas-kandal', NULL, NULL), (183, 22, '<NAME>', '', 'bram-yam', NULL, NULL), (184, 22, '<NAME>', '', 'prek-dombok', NULL, NULL), (185, 22, '<NAME>', '', 'prek-por', NULL, NULL), (186, 22, '<NAME>', '', 'prek-romdeng', NULL, NULL), (187, 22, '<NAME>', '', 'russey-srok', NULL, NULL), (188, 22, '<NAME>', '', 'svay-por', NULL, NULL), (189, 22, '<NAME>', '', 'svay-ksach-phnom', NULL, NULL), (190, 22, '<NAME>', '', 'torng-trolach', NULL, NULL), (191, 23, '<NAME>', '', 'areak-tnort', NULL, NULL), (192, 23, '<NAME>', '', 'dorng-kdar', NULL, NULL), (193, 23, '<NAME>', '', 'kpob-tangoun', NULL, NULL), (194, 23, '<NAME>', '', 'mesar-chrey', NULL, NULL), (195, 23, '<NAME>', '', 'or-mlou', NULL, NULL), (196, 23, '<NAME>', '', 'peam-koh-sna', NULL, NULL), (197, 23, '<NAME>', '', 'preah-andong', NULL, NULL), (198, 23, '<NAME>', '', 'prek-kork', NULL, NULL), (199, 23, 'Sopheas', '', 'sopheas', NULL, NULL), (200, 23, '<NAME>', '', 'toul-preahkhleang', NULL, NULL), (201, 23, '<NAME>', '', 'toul-sombor', NULL, NULL), (202, 24, 'Batheay', '', 'batheay', NULL, NULL), (203, 24, '<NAME>', '', 'chbar-ampov', NULL, NULL), (204, 24, 'Chealea', '', 'chealea', NULL, NULL), (205, 24, '<NAME>', '', 'cheung-prey', NULL, NULL), (206, 24, '<NAME>', '', 'me-pring', NULL, NULL), (207, 24, 'Phav', '', 'phav', NULL, NULL), (208, 24, 'Sambour', '', 'sambour', NULL, NULL), (209, 24, 'Sandaek', '', 'sandaek', NULL, NULL), (210, 24, '<NAME>', '', 'tang-krang', NULL, NULL), (211, 24, 'Prasat', '', 'prasat', NULL, NULL), (212, 24, '<NAME>', '', 'tang-krasang', NULL, NULL), (213, 24, '<NAME>', '', 'trab-roung', NULL, NULL), (214, 24, 'Tumnob', '', 'tumnob', NULL, NULL), (215, 25, '<NAME>', '', 'bos-khnaor', NULL, NULL), (216, 25, '<NAME>', '', 'chamkar-andoung', NULL, NULL), (217, 25, 'Cheyyou', '', 'cheyyou', NULL, NULL), (218, 25, '<NAME>', '', 'lvea-leu', NULL, NULL), (219, 25, 'Spueu', '', 'spueu', NULL, NULL), (220, 25, '<NAME>', '', 'svay-teab', NULL, NULL), (221, 25, '<NAME>', '', 'ta-ong', NULL, NULL), (222, 25, '<NAME>', '', 'ta-prok', NULL, NULL), (223, 26, '<NAME>', '', 'khnaor-dambang', NULL, NULL), (224, 26, '<NAME>', '', 'kouk-rovieng', NULL, NULL), (225, 26, '<NAME>', '', 'phdau-chum', NULL, NULL), (226, 26, '<NAME>', '', 'prey-char', NULL, NULL), (227, 26, '<NAME>', '', 'pring-chrum', NULL, NULL), (228, 26, '<NAME>', '', 'sampong-chey', NULL, NULL), (229, 26, '<NAME>', '', 'sdaeung-chey', NULL, NULL), (230, 26, 'Soutip', '', 'soutip', NULL, NULL), (231, 26, 'Srama', '', 'srama', NULL, NULL), (232, 26, 'Trapeang Kor', '', 'trapeang-kor', NULL, NULL), (233, 27, 'Char Chhouk', 'ចារឈូក', 'char-chhouk', NULL, NULL), (234, 27, 'Da<NAME>', 'ដូនពេង', 'daun-peng', NULL, NULL), (235, 27, 'Koak Daung', 'គោកដូង', 'koak-daung', NULL, NULL), (236, 27, 'Koal', 'គោល', 'koal', NULL, NULL), (237, 27, 'Nokor Pheas', 'នគរភាស', 'nokor-pheas', NULL, NULL), (238, 27, '<NAME>', 'ស្រែខ្វាវ', 'srae-khvav', NULL, NULL), (239, 27, 'Tasoam', 'តាសោម', 'tasoam', NULL, NULL), (240, 28, '<NAME>', 'ជប់តាត្រាវ', 'chub-tatrav', NULL, NULL), (241, 28, 'Leang Dai', 'លាងដៃ', 'leang-dai', NULL, NULL), (242, 28, 'Peak Snaeng', 'ពាក់ស្នែង', 'peak-snaeng', NULL, NULL), (243, 28, '<NAME>', 'ស្វាយចេក', 'svay-chek', NULL, NULL), (244, 29, '<NAME>', 'ខ្នារសណ្តាយ', 'khnar-sanday', NULL, NULL), (245, 29, '<NAME>', 'ឃុនរាម', 'khun-ream', NULL, NULL), (246, 29, '<NAME>', 'ព្រះដាក់', 'preak-dak', NULL, NULL), (247, 29, 'Romchek', 'រំចេក', 'romchek', NULL, NULL), (248, 29, '<NAME>', 'រុនតាឯក', 'run-ta-aek', NULL, NULL), (249, 29, 'Tbaeng', 'ត្បែង', 'tbaeng', NULL, NULL), (250, 30, '<NAME>', 'អន្លង់សំណរ', 'anlong-samnor', NULL, NULL), (251, 30, 'Chi Kraeng', 'ជីក្រែង', 'chi-kraeng', NULL, NULL), (252, 30, '<NAME>', 'កំពង់ក្តី', 'kampong-kdei', NULL, NULL), (253, 30, 'Khvav', 'ខ្វាវ', 'khvav', NULL, NULL), (254, 30, '<NAME>', 'គោកធ្លកក្រោម', 'koak-thlok-krom', NULL, NULL), (255, 30, 'Ko<NAME> Leu', 'គោកធ្លកលើ', 'koak-thlok-leu', NULL, NULL), (256, 30, 'Lveng Russei', 'ល្វែងឫស្សី', 'lveng-russei', NULL, NULL), (257, 30, 'Pongro Krom', 'ពង្រក្រោម', 'pongro-krom', NULL, NULL), (258, 30, 'Pongro Leu', 'ពង្រលើ', 'pongro-leu', NULL, NULL), (259, 30, 'Russei Lok', 'ឫស្សីលក', 'russei-lok', NULL, NULL), (260, 30, 'Songveuy', 'សង្វើយ', 'songveuy', NULL, NULL), (261, 30, '<NAME>at', 'ស្ពានត្នោត', 'spean-tnoat', NULL, NULL), (262, 31, '<NAME>', 'ជន្លាស់ដៃ', 'chonleas-dai', NULL, NULL), (263, 31, '<NAME>', 'កំពង់ថ្កូវ', 'kampong-thkov', NULL, NULL), (264, 31, 'Kralanh', 'ក្រឡាញ់', 'kralanh', NULL, NULL), (265, 31, 'K<NAME>', 'ក្រូចគរ', 'krouch-kor', NULL, NULL), (266, 31, '<NAME>', 'រោងគោ', 'roang-koar', NULL, NULL), (267, 31, 'Sambour', 'សំបួរ', 'sambour', NULL, NULL), (268, 31, 'Sen Sok', 'សែនសុខ', 'sen-sok', NULL, NULL), (269, 31, 'Snoul', 'ស្នួល', 'snoul', NULL, NULL), (270, 31, 'Sronal', 'ស្រណាល', 'sronal', NULL, NULL), (271, 31, 'Ta An', 'តាអាន', 'ta-an', NULL, NULL), (272, 32, 'Sosor Sdom', 'សសរស្តម្', 'sosor-sdom', NULL, NULL), (273, 32, 'Daun Keo', 'ដូនកែវ', 'daun-keo', NULL, NULL), (274, 32, 'Kdei Run', 'ក្តីរុន', 'kdei-run', NULL, NULL), (275, 32, 'Keo Por', 'កែវពណ៌', 'keo-por', NULL, NULL), (276, 32, 'Khnat', 'ខ្នាត', 'khnat', NULL, NULL), (277, 32, 'Lvea', 'ល្វា', 'lvea', NULL, NULL), (278, 32, '<NAME>', 'មុខប៉ែន', 'mukh-paen', NULL, NULL), (279, 32, '<NAME>', 'ពោធិទ្រាយ', 'pou-treay', NULL, NULL), (280, 32, 'Pouk', 'ពួក', 'pouk', NULL, NULL), (281, 32, '<NAME>', 'ព្រៃជ្រូក', 'prey-chrouk', NULL, NULL), (282, 32, 'Reul', 'រើស', 'reul', NULL, NULL), (283, 32, '<NAME>', 'សំរោងយា', 'somroang-yea', NULL, NULL), (284, 32, '<NAME>', 'ត្រីញ័រ', 'treu-nhoar', NULL, NULL), (285, 32, 'Yeang', 'យាង', 'yeang', NULL, NULL), (286, 32, '<NAME>', 'ទឹកវិល', 'tuek-vil', NULL, NULL), (287, 32, '<NAME>', 'ក្របីរៀល', 'krabei-riel', NULL, NULL), (288, 33, 'Bakong', 'បាគង', 'bakong', NULL, NULL), (289, 33, 'Balangk', 'បល្ល័ង្គ', 'balangk', NULL, NULL), (290, 33, 'Kampong Phluk', 'កំពង់ភ្លុក', 'kampong-phluk', NULL, NULL), (291, 33, 'Kantreang', 'កន្ទ្រាំង', 'kantreang', NULL, NULL), (292, 33, 'Kandaek', 'កណ្តែក', 'kandaek', NULL, NULL), (293, 33, 'Meanchey', 'មានជ័យ', 'meanchey', NULL, NULL), (294, 33, 'Rolous', 'រលួស', 'rolous', NULL, NULL), (295, 33, 'Trapeang Thom', 'ត្រពាំងធំ', 'trapeang-thom', NULL, NULL), (296, 33, 'Ampil', 'អំពិល', 'ampil', NULL, NULL), (297, 34, 'Slor Kram', 'ស្លក្រាម', 'slor-kram', NULL, NULL), (298, 34, '<NAME>', 'ស្វាយដង្គំ', 'svay-dongkum', NULL, NULL), (299, 34, 'Koak Chork', 'គោកចក', 'koak-chork', NULL, NULL), (300, 34, 'Sala Komreuk', 'សាលាកំរើក', 'sala-komreuk', NULL, NULL), (301, 34, 'Nokor Thom', 'នគរធំ', 'nokor-thom', NULL, NULL), (302, 34, 'Chreav', 'ជ្រាវ', 'chreav', NULL, NULL), (303, 34, '<NAME>', 'ចុងឃ្នៀស', 'chong-khneas', NULL, NULL), (304, 34, 'Sambour', 'សំបួរ', 'sambour', NULL, NULL), (305, 34, 'Seam Reap', 'សៀមរាប', 'seam-reap', NULL, NULL), (306, 34, 'Sragnae', 'ស្រង៉ែ', 'sragnae', NULL, NULL), (307, 34, 'Ampil', 'អំពិល', 'ampil', NULL, NULL), (308, 34, '<NAME>', 'ក្របីរៀល', 'krabei-real', NULL, NULL), (309, 34, 'Teuk Vil', 'ទឹកវិល', 'teuk-vil', NULL, NULL), (310, 35, '<NAME>', 'ចាន់ស', 'chan-sor', NULL, NULL), (311, 35, '<NAME>', 'ដំដែក', 'dom-daek', NULL, NULL), (312, 35, 'Danrun', 'ដានរុន', 'danrun', NULL, NULL), (313, 35, '<NAME>', 'កំពង់ឃ្លាំង', 'kampong-khleang', NULL, NULL), (314, 35, 'Ke<NAME>ke', 'កៀនសង្កែ', 'kean-sangke', NULL, NULL), (315, 35, 'Khchas', 'ខ្ចាស់', 'khchas', NULL, NULL), (316, 35, '<NAME>', 'ខ្នារពោធិ៍', 'khnar-pou', NULL, NULL), (317, 35, 'Popel', 'ពពេល', 'popel', NULL, NULL), (318, 35, 'Samroang', 'សំរោង', 'samroang', NULL, NULL), (319, 35, 'Ta Yaek', 'តាយ៉ែក', 'ta-yaek', NULL, NULL), (320, 36, '<NAME>', 'ជ្រោយនាងងួន', 'chroy-neang-ngoun', NULL, NULL), (321, 36, '<NAME>', 'ក្លាំងហាយ', 'klang-hay', NULL, NULL), (322, 36, 'Tram Sosor', 'ត្រាំសសរ', 'tram-sosor', NULL, NULL), (323, 36, 'Moang', 'មោង', 'moang', NULL, NULL), (324, 36, 'Brey', 'ប្រីយ៍', 'brey', NULL, NULL), (325, 36, '<NAME>an', 'ស្លែងស្ពាន', 'slaeng-spean', NULL, NULL), (326, 37, '<NAME>', 'បឹងមាលា', 'beung-mealea', NULL, NULL), (327, 37, 'Kantout', 'កន្ទួត', 'kantout', NULL, NULL), (328, 37, '<NAME>', 'ខ្នងភ្នំ', 'khnorng-phnum', NULL, NULL), (329, 37, '<NAME>', 'ស្វាយលើ', 'svay-leu', NULL, NULL), (330, 37, 'Ta Seam', 'តាសៀម', 'ta-seam', NULL, NULL), (331, 38, 'Brasat', 'ប្រាសាទ', 'brasat', NULL, NULL), (332, 38, 'L<NAME>ang', 'ល្វាក្រាំង', 'lvea-krang', NULL, NULL), (333, 38, 'S<NAME>', 'ស្រែណូយ', 'srae-noy', NULL, NULL), (334, 38, '<NAME>', 'ស្វាយស', 'svay-sor', NULL, NULL), (335, 38, 'Varin', 'វ៉ារិន', 'varin', NULL, NULL), (336, 39, '<NAME>', 'កន្ទឺ ១', 'kantueu-muoy', NULL, NULL), (337, 39, '<NAME>', 'កន្ទឺ ២', 'kantueu-pir', NULL, NULL), (338, 39, 'Bay Damram', 'បាយដំរាំ', 'bay-damram', NULL, NULL), (339, 39, 'Chheu Teal', ' ឈើទាល', 'chheu-teal', NULL, NULL), (340, 39, 'Chaeng Mean Chey', 'ចែងមានជ័យ', 'chaeng-mean-chey', NULL, NULL), (341, 39, 'Phnum Sampov', 'ភ្នំសំពៅ', 'phnum-sampov', NULL, NULL), (342, 39, 'Snoeng', 'ស្នឹង', 'snoeng', NULL, NULL), (343, 39, 'Ta Kream', 'តាគ្រាម', 'ta-kream', NULL, NULL), (344, 40, 'Ta Pung', 'តាពូង', 'ta-pung', NULL, NULL), (345, 40, 'តាម៉ឺន', 'Ta Meun', '', NULL, NULL), (346, 40, 'Ou Ta Ki', 'អូរតាគី', 'ou-ta-ki', NULL, NULL), (347, 40, 'Chrey', 'ជ្រៃ', 'chrey', NULL, NULL), (348, 40, 'Anlong Run', 'អន្លង់រុន', 'anlong-run', NULL, NULL), (349, 40, 'Chrouy Sdau', 'ជ្រោយស្តៅ', 'chrouy-sdau', NULL, NULL), (350, 40, '<NAME>', 'បឹងព្រីង', 'boeng-pring', NULL, NULL), (351, 40, '<NAME>', 'គោកឃ្មុំ', 'kouk-khmum', NULL, NULL), (352, 40, '<NAME>', 'បន្សាយត្រែង', 'bansay-traeng', NULL, NULL), (353, 40, '<NAME>', 'រូងជ្រៃ', 'rung-chrey', NULL, NULL), (354, 41, '<NAME>ek', 'ទួលតាឯក', 'tuol-ta-aek', NULL, NULL), (355, 41, '<NAME>', 'ព្រែកព្រះស្តេច', 'preaek-preah-sdach', NULL, NULL), (356, 41, 'Rotanak', 'រតនៈ', 'rotanak', NULL, NULL), (357, 41, '<NAME>', 'ចំការសំរោង', 'chamkar-samraong', NULL, NULL), (358, 41, 'Sla Kaet', 'ស្លាកែត', 'sla-kaet', NULL, NULL), (359, 41, 'Kdol Doun Teav', 'ក្តុលដូនទាវ', 'kdol-doun-teav', NULL, NULL), (360, 41, 'Ou Mal', 'អូរម៉ាល់', 'ou-mal', NULL, NULL), (361, 41, 'Voat Kor', 'វត្តគរ', 'voat-kor', NULL, NULL), (362, 41, 'Ou Char', 'អូរចារ', 'ou-char', NULL, NULL), (363, 41, 'Svay Pao', 'ស្វាយប៉ោ', 'svay-pao', NULL, NULL), (364, 42, 'Bavel', 'បវេល', 'bavel', NULL, NULL), (365, 42, 'Khnach Romeas', 'ខ្នាចរមាស', 'khnach-romeas', NULL, NULL), (366, 42, 'Lvea', 'ល្វា', 'lvea', NULL, NULL), (367, 42, 'Prey Khpos', 'ព្រៃខ្ពស់', 'prey-khpos', NULL, NULL), (368, 42, 'Ampil Pram Daeum', 'អំពិលប្រាំដើម', 'ampil-pram-daeum', NULL, NULL), (369, 42, 'Kdol Tahen', 'ក្តុលតាហែន', 'kdol-tahen', NULL, NULL), (370, 42, 'Khlang meas', 'ខ្លាំងមាស', 'khlang-meas', NULL, NULL), (371, 42, 'Boeng pram', 'បឹងប្រាំ', 'boeng-pram', NULL, NULL), (372, 43, '<NAME>', 'ព្រែកនរិន្ទ', 'preaek-norint', NULL, NULL), (373, 43, '<NAME>', 'សំរោងក្នុង', 'samraong-knong', NULL, NULL), (374, 43, '<NAME>', 'ព្រែកខ្ពប', 'preaek-khpob', NULL, NULL), (375, 43, '<NAME>', 'ព្រែកហ្លួង', 'preaek-luong', NULL, NULL), (376, 43, '<NAME>', 'ពាមឯក', 'peam-aek', NULL, NULL), (377, 43, '<NAME>', 'ព្រៃចាស់', 'prey-chas', NULL, NULL), (378, 43, '<NAME>', 'កោះជីវាំង', 'kaoh-chiveang-thvang', NULL, NULL), (379, 44, 'Moung', 'មោង', 'moung', NULL, NULL), (380, 44, 'Kear', 'គារ', 'kear', NULL, NULL), (381, 44, '<NAME>', 'ព្រៃស្វាយ', 'prey-svay', NULL, NULL), (382, 44, '<NAME>', 'ឫស្សីក្រាំង', 'ruessei-krang', NULL, NULL), (383, 44, 'Chrey', 'ជ្រៃ', 'chrey', NULL, NULL), (384, 44, 'Ta Loas', 'តាលាស់', 'ta-loas', NULL, NULL), (385, 44, 'Kakaoh', 'កកោះ', 'kakaoh', NULL, NULL), (386, 44, 'Prey Touch', 'ព្រៃតូច', 'prey-touch', NULL, NULL), (387, 44, '<NAME>', 'របស់មង្គល', 'robas-mongkol', NULL, NULL), (388, 44, 'Break Chek', 'ព្រែកជីក', 'break-chek', NULL, NULL), (389, 44, 'Prey Trolach', 'ព្រៃត្រឡាច', 'prey-trolach', NULL, NULL), (390, 45, 'Sdau', 'ស្តៅ', 'sdau', NULL, NULL), (391, 45, '<NAME>', 'អណ្តើកហែប', 'andaeuk-haeb', NULL, NULL), (392, 45, 'Phlov Meas', 'ផ្លូវមាស', 'phlov-meas', NULL, NULL), (393, 45, 'Traeng', 'ត្រែង', 'traeng', NULL, NULL), (394, 45, 'Reaksmey Sangha', 'រស្មីសង្ហារ', 'reaksmey-sangha', NULL, NULL), (395, 46, 'Anlong Vil', 'អន្លង់វិល', 'anlong-vil', NULL, NULL), (396, 46, 'Norea', 'នរា', 'norea', NULL, NULL), (397, 46, 'Ta Pon', 'តាប៉ុន', 'ta-pon', NULL, NULL), (398, 46, 'Roka', 'រកា', 'roka', NULL, NULL), (399, 46, 'Kampong Preah', 'កំពង់ព្រះ', 'kampong-preah', NULL, NULL), (400, 46, 'Kampong Prieng', 'កំពង់ព្រៀង', 'kampong-prieng', NULL, NULL), (401, 46, 'Reang Kesei', 'រាំងកេសី', 'reang-kesei', NULL, NULL), (402, 46, 'Ou Dambang Muoy', 'អូរដំបង ១', 'ou-dambang-muoy', NULL, NULL), (403, 46, 'Ou Dambang Pir', 'អូរដំបង ២', 'ou-dambang-pir', NULL, NULL), (404, 46, 'Vaot Ta Muem', 'វត្តតាមិម', 'vaot-ta-muem', NULL, NULL), (405, 47, 'Ta Taok', 'តាតោក', 'ta-taok', NULL, NULL), (406, 47, 'K<NAME>', 'កំពង់ល្ពៅ', 'kampong-lpou', NULL, NULL), (407, 47, 'Ou Samrel', 'អូរសំរិល', 'ou-samrel', NULL, NULL), (408, 47, 'Sung', 'ស៊ុង', 'sung', NULL, NULL), (409, 47, 'Samlout', 'សំឡូត', 'samlout', NULL, NULL), (410, 47, 'Mean Cheay', 'មានជ័យ', 'mean-cheay', NULL, NULL), (411, 47, 'Ta Sanh', 'តាសាញ', 'ta-sanh', NULL, NULL), (412, 48, 'Sampou Lun', 'សំពៅលូន', 'sampou-lun', NULL, NULL), (413, 48, '<NAME>', 'អង្គរបាន', 'angkor-ban', NULL, NULL), (414, 48, 'Ta Sda', 'តាសា្ត', 'ta-sda', NULL, NULL), (415, 48, 'Santepheap', 'សន្តិភាព', 'santepheap', NULL, NULL), (416, 48, '<NAME>', 'សិរីមានជ័យ', 'serei-maen-cheay', NULL, NULL), (417, 48, '<NAME>', 'ជ្រៃសីមា', 'chrey-sema', NULL, NULL), (418, 49, 'Phnum Proek', 'ភ្នំព្រឹក', 'phnum-proek', NULL, NULL), (419, 49, 'Pech Chenda', 'ពេជ្រចិន្តា', 'pech-chenda', NULL, NULL), (420, 49, 'Bou', 'បួរ', 'bou', NULL, NULL), (421, 49, 'Barang Thleak', 'បារាំងធ្លាក់', 'barang-thleak', NULL, NULL), (422, 49, 'Ou Rumduol', 'អូររំដួល', 'ou-rumduol', NULL, NULL), (423, 50, 'Kamrieng', 'កំរៀង', 'kamrieng', NULL, NULL), (424, 50, 'Boeng Reang', 'បឹងរាំង', 'boeng-reang', NULL, NULL), (425, 50, 'Ou Da', 'អូរដា', 'ou-da', NULL, NULL), (426, 50, 'Trang', 'ត្រាង', 'trang', NULL, NULL), (427, 50, 'Ta Saen', 'តាសែន', 'ta-saen', NULL, NULL), (428, 50, 'Ta Krai', 'តាក្រី', 'ta-krai', NULL, NULL), (429, 51, 'Thipakdei', 'ធិបតី', 'thipakdei', NULL, NULL), (430, 51, 'Koas Krala', 'គាស់ក្រឡ', 'koas-krala', NULL, NULL), (431, 51, 'Hab', 'ហប់', 'hab', NULL, NULL), (432, 51, 'Preah Phos', 'ព្រះផុស', 'preah-phos', NULL, NULL), (433, 51, 'Doun Ba', 'ដូនបា', 'doun-ba', NULL, NULL), (434, 51, '<NAME>', 'ឆ្នាល់មាន់', 'chhnal-moan', NULL, NULL), (435, 52, 'Prek chik', 'ព្រែកជីក', 'prek-chik', NULL, NULL), (436, 52, 'prey trolach', 'ព្រៃត្រឡាច', 'prey-trolach', NULL, NULL), (437, 52, 'Basak', 'បាសាក', 'basak', NULL, NULL), (438, 52, 'Mukrea', 'មុគគ្រា', 'mukrea', NULL, NULL), (439, 52, 'Sduk Provek', 'ស្តុកផ្រូវិក', 'sduk-provek', NULL, NULL), (440, 53, 'Ampov Prey', 'អំពៅព្រៃ', 'ampov-prey', NULL, NULL), (441, 53, '<NAME>', 'អន្លង់រមៀត', 'anlong-romiet', NULL, NULL), (442, 53, 'Barku', 'បាគូ', 'barku', NULL, NULL), (443, 53, '<NAME>', 'បឹងខ្យាង', 'boeng-khyang', NULL, NULL), (444, 53, '<NAME>', 'ជើងកើប', 'cheung-kaeub', NULL, NULL), (445, 53, '<NAME>', 'ដើមឫស', 'daeum-rues', NULL, NULL), (446, 53, 'Kandaok', 'កណ្តោក', 'kandaok', NULL, NULL), (447, 53, 'Thmei', 'ថ្មី', 'thmei', NULL, NULL), (448, 53, '<NAME>', 'គោកត្រប់', 'kouk-trab', NULL, NULL), (449, 53, '<NAME>', 'ព្រះពុទ្ធ', 'preah-putth', NULL, NULL), (450, 53, '<NAME>', 'ព្រែករកា', 'preaek-roka', NULL, NULL), (451, 53, '<NAME>', 'ព្រែកស្លែង', 'preaek-slaeng', NULL, NULL), (452, 53, 'Roka', 'រកា', 'roka', NULL, NULL), (453, 53, 'Roleang Kaen', 'រលាំងកែន', 'roleang-kaen', NULL, NULL), (454, 53, 'Siem Reab', 'សៀមរាប', 'siem-reab', NULL, NULL), (455, 53, 'Tbaeng', 'ត្បែងទៀន', 'tbaeng', NULL, NULL), (456, 53, 'Trapeang Veaeng', 'ត្រពាំងវែង', 'trapeang-veaeng', NULL, NULL), (457, 53, 'Trea', 'ទ្រា', 'trea', NULL, NULL), (458, 54, 'Ch<NAME>u', 'ឈើខ្មៅ', 'chheu-kmau', NULL, NULL), (459, 54, '<NAME>ae', 'ជ្រោយតាកែវ', 'chrouy-ta-kae', NULL, NULL), (460, 54, 'Kampong Kong', 'កំពង់កុង', 'kampong-kong', NULL, NULL), (461, 54, 'Kaoh Thum Ka', 'កោះធំ ក', 'kaoh-thum-ka', NULL, NULL), (462, 54, 'Kaoh Thum Kha', 'កោះធំ ខ', 'kaoh-thum-kha', NULL, NULL), (463, 54, 'Leuk Daek', 'លើកដែក', 'leuk-daek', NULL, NULL), (464, 54, '<NAME>', 'ពោធិ៍បាន', 'pouthi-ban', NULL, NULL), (465, 54, '<NAME>', 'ព្រែកជ្រៃ', 'prea-ek-chrey', NULL, NULL), (466, 54, '<NAME>', 'ព្រែកស្ដី', 'preaek-sdei', NULL, NULL), (467, 54, '<NAME>', 'ព្រែកថ្មី', 'preaek-thmei', NULL, NULL), (468, 54, '<NAME>', 'សំពៅពូន', 'sampeou-poun', NULL, NULL), (469, 55, '<NAME>', 'ព្រែកអញ្ចាញ', 'praek-anchanh', NULL, NULL), (470, 55, '<NAME>', 'ព្រែកដំបង', 'praek-dombong', NULL, NULL), (471, 55, '<NAME>', 'រកាកោងទី១', 'rokakoang-ti-mouy', NULL, NULL), (472, 55, '<NAME>', 'រកាកោងទី២', 'rokakoang-ti-pir', NULL, NULL), (473, 55, '<NAME>', 'ឫស្សីជ្រោយ', 'russei-chroay', NULL, NULL), (474, 55, '<NAME>', 'សំបួរមាស', 'sambour-meas', NULL, NULL), (475, 55, '<NAME>', 'ស្វាយអំពារ', 'svay-ampear', NULL, NULL), (476, 56, 'Khpob', 'ខ្ពប', 'khpob', NULL, NULL), (477, 56, '<NAME>', 'កោះអន្លង់ចិន', 'kaoh-anlong-chen', NULL, NULL), (478, 56, '<NAME>', 'កោះខែល', 'kaoh-khael', NULL, NULL), (479, 56, '<NAME>', 'កោះខ្សាច់ទន្លា', 'kaoh-khsach-tonlea', NULL, NULL), (480, 56, '<NAME>', 'ក្រាំងយ៉ូវ', 'krang-yov', NULL, NULL), (481, 56, 'Prasat', 'ប្រាសាទ', 'prasat', NULL, NULL), (482, 56, '<NAME>', 'ព្រែអំបិល', 'preaek-ambel', NULL, NULL), (483, 56, '<NAME>', 'ព្រែកគយ', 'preaek-koy', NULL, NULL), (484, 56, 'Roka Khpos', 'រកាខ្ពស់', 'roka-khpos', NULL, NULL), (485, 56, 'Sa ang Phnum', 'ស្អាងភ្នំ', 'sa-ang-phnum', NULL, NULL), (486, 56, 'Setbou', 'សិត្បូ', 'setbou', NULL, NULL), (487, 56, 'Svay Prateal', 'ស្វាយប្រទាល', 'svay-prateal', NULL, NULL), (488, 56, 'Svay Rolum', 'ស្វាយរលំ', 'svay-rolum', NULL, NULL), (489, 56, 'Ta Lon', 'តាលន់', 'ta-lon', NULL, NULL), (490, 56, 'Traeuy Sla', 'ត្រើយស្លា', 'traeuy-sla', NULL, NULL), (491, 56, 'Tuek Vil', 'ទឹកវិល', 'tuek-vil', NULL, NULL), (492, 57, 'Kampong Phnum', 'កំពង់ភ្នំ', 'kampong-phnum', NULL, NULL), (493, 57, 'K am Samnar', 'ក្អមសំណ', 'k-am-samnar', NULL, NULL), (494, 57, 'Khpob Ateav', 'ខ្ពបអាទាវ', 'khpob-ateav', NULL, NULL), (495, 57, '<NAME> ', 'ពាមរាំង', 'peam-reang', NULL, NULL), (496, 57, '<NAME>', 'ព្រែកដាច់', 'preaek-dach', NULL, NULL), (497, 57, '<NAME>', 'ព្រែកទន្លាប់', 'preaek-tonloab', NULL, NULL), (498, 57, 'Sandar', 'សណ្ដារ', 'sandar', NULL, NULL), (499, 58, '<NAME>', 'តាក្ដុល', 'ta-kdol', NULL, NULL), (500, 58, '<NAME>', 'ព្រែកឫស្សី', 'prek-ruessey', NULL, NULL), (501, 58, '<NAME>', 'ដើមមៀន', 'doeum-mien', NULL, NULL), (502, 58, 'Ta Khmao', 'តាខ្មៅ', 'ta-khmao', NULL, NULL), (503, 58, '<NAME>', 'ព្រែកហូរ', 'prek-ho', NULL, NULL), (504, 58, '<NAME>', 'កំពង់សំណាញ់', 'kampong-samnanh', NULL, NULL), (505, 58, '<NAME>', 'ស្វាយរលំ', 'svay-rolum', NULL, NULL), (506, 58, 'Setbou', 'សិត្បូ', 'setbou', NULL, NULL), (507, 58, '<NAME>', 'រកាខ្ពស់', 'roka-kpos', NULL, NULL), (508, 58, '<NAME>', 'កោះអន្លង់ចិន', 'khosh-anlong-chien', NULL, NULL), (509, 59, '<NAME>', 'បន្ទាយដែក', 'banteay-daek', NULL, NULL), (510, 59, 'Chheu Teal', 'ឈើទាល', 'chheu-teal', NULL, NULL), (511, 59, '<NAME>', 'ដីឥដ្ឋ', 'dei-edth', NULL, NULL), (512, 59, '<NAME>', 'កំពង់ស្វាយ', 'kampong-svay', NULL, NULL), (513, 59, 'Kokir', 'គគីរ', 'kokir', NULL, NULL), (514, 59, '<NAME>', 'គគីរធំ', 'kokir-thum', NULL, NULL), (515, 59, '<NAME>', 'ភូមិធំ', 'phum-thum', NULL, NULL), (516, 59, '<NAME>', 'សំរោងធំ', 'samraong-thum', NULL, NULL), (517, 60, 'Chhveang', 'ឈ្វាំង', 'chhveang', NULL, NULL), (518, 60, '<NAME>', 'ជ្រៃលាស់', 'chrey-loas', NULL, NULL), (519, 60, '<NAME>', 'កំពង់ហ្លួង', 'kampong-luong', NULL, NULL), (520, 60, 'Kampong Os', 'កំពង់អុស', 'kampong-os', NULL, NULL), (521, 60, '<NAME>', 'កោះចិន', 'kaoh-chen', NULL, NULL), (522, 60, '<NAME>', 'ភ្នំបាត', 'phnum-bat', NULL, NULL), (523, 60, '<NAME>', 'ពញាឮ', 'ponhea-lueu', NULL, NULL), (524, 60, '<NAME>', 'ព្រែកតាទែន', 'preaek-ta-teaen', NULL, NULL), (525, 60, '<NAME>', 'ផ្សារដែក', 'vihear-luong', NULL, NULL), (526, 60, '<NAME>', 'ទំនប់ធំ', 'tumnob-thum', NULL, NULL), (527, 60, '<NAME>', 'វិហារហ្លួង', 'vihear-luong', NULL, NULL), (528, 61, 'Ariyaksatr', 'អរិយក្សត្រ', 'ariyaksatr', NULL, NULL), (529, 61, 'Barong', 'បារុង', 'barong', NULL, NULL), (530, 61, 'Beung Krum', 'បឹងគ្រំ', 'beung-krum', NULL, NULL), (531, 61, 'Koh Keo', 'កោះកែវ', 'koh-keo', NULL, NULL), (532, 61, 'Koh Reah', 'កោះរះ', 'koh-reah', NULL, NULL), (533, 61, 'Lvea Sor', 'ល្វាសរ', 'lvea-sor', NULL, NULL), (534, 61, 'Pe<NAME>ng', 'ពាមឧកញ៉ាអុង', 'peam-okhna-ong', NULL, NULL), (535, 61, 'Ph<NAME>', 'ភូមិធំ', 'phum-thom', NULL, NULL), (536, 61, '<NAME>eng', 'ព្រែកក្មេង', 'praek-kmeng', NULL, NULL), (537, 61, 'Praek Rey', 'ព្រែករៃ', 'praek-rey', NULL, NULL), (538, 61, 'Praek Russei', 'ព្រែកឫស្សី', 'praek-russei', NULL, NULL), (539, 61, 'Sombour', 'សំបួរ', 'sombour', NULL, NULL), (540, 61, 'Sarikakeo', 'សារិកាកែវ', 'sarikakeo', NULL, NULL), (541, 61, '<NAME>', 'ថ្មគរ', 'thma-kor', NULL, NULL), (542, 61, 'Teuk Khleang', 'ទឹកឃ្លាំង', 'teuk-khleang', NULL, NULL), (543, 62, 'Bak Dav', 'បាក់ដាវ', 'bak-dav', NULL, NULL), (544, 62, 'Che<NAME>', 'ជ័យធំ', 'chey-thum', NULL, NULL), (545, 62, 'K<NAME>lang', 'កំពង់ចំលង', 'kampong-chamlang', NULL, NULL), (546, 62, 'Kaoh Chouram', 'កោះចូរ៉ាម', 'kaoh-chouram', NULL, NULL), (547, 62, 'Kaoh Oknha Tei', 'កោះឧកញ៉ាតី', 'kaoh-oknha-tei', NULL, NULL), (548, 62, 'Preah Prasab', 'ព្រះប្រសប់', 'preah-prasab', NULL, NULL), (549, 62, 'Preaek Ampil', 'ព្រែកអំពិល', 'preaek-ampil', NULL, NULL), (550, 62, ' <NAME>', 'ព្រែកលួង', 'preaek-luong', NULL, NULL), (551, 62, '<NAME>', 'ព្រែកតាកូវ', 'preaek-ta-kov', NULL, NULL), (552, 62, 'Preaek Ta Meak', 'ព្រែកតាមាក់', 'preaek-ta-meak', NULL, NULL), (553, 62, '<NAME>', 'ពុកឫស្សី', 'puk-ruessei', NULL, NULL), (554, 62, '<NAME>', 'រកាជន្លឹង', 'roka-chonlueng', NULL, NULL), (555, 62, 'Sanlung', 'សន្លុង', 'sanlung', NULL, NULL), (556, 62, 'Sithor', 'ស៊ីធរ', 'sithor', NULL, NULL), (557, 62, '<NAME>', 'ស្វាយជ្រុំ', 'svay-chrum', NULL, NULL), (558, 62, '<NAME>', 'ស្វាយរមៀត', 'svay-romiet', NULL, NULL), (559, 62, 'Ta Aek', 'តាឯក', 'ta-aek', NULL, NULL), (560, 62, '<NAME>ork', 'វិហារសួគ៌', 'vihear-suork', NULL, NULL), (561, 88, '<NAME>', 'បាក់ស្នា', 'bak-sna', NULL, NULL), (562, 88, 'Ballangk', 'បល្ល័ង្ក', 'ballangk', NULL, NULL), (563, 88, 'Baray', 'បារាយណ៍', 'baray', NULL, NULL), (564, 88, 'Boeng', 'បឹង', 'boeng', NULL, NULL), (565, 88, '<NAME>', 'ចើងដើង', 'chaeung-daeung', NULL, NULL), (566, 88, 'Chraneang', 'ច្រនាង', 'chraneang', NULL, NULL), (567, 88, '<NAME>', 'ឈូកខ្សាច់', 'chhuk-khsach', NULL, NULL), (568, 88, '<NAME>', 'ចុងដូង', 'chong-doung', NULL, NULL), (569, 88, 'Chrolong', 'ជ្រលង', 'chrolong', NULL, NULL), (570, 88, '<NAME> ', 'គគីធំ', 'kokir-thum', NULL, NULL), (571, 88, 'Krava', 'ក្រវ៉ា', 'krava', NULL, NULL), (572, 88, '<NAME>', 'អណ្ដូងពោធិ៍', 'andoung-pou', NULL, NULL), (573, 88, 'Pongro', 'ពង្រ', 'pongro', NULL, NULL), (574, 88, '<NAME>', 'សូយោង', 'sou-young', NULL, NULL), (575, 88, 'Sralau', 'ស្រឡៅ', 'sralau', NULL, NULL), (576, 88, '<NAME>', 'ស្វាយភ្លើង', 'svay-phleung', NULL, NULL), (577, 88, '<NAME>', 'ត្នោតជុំ', 'tnaot-chum', NULL, NULL), (578, 88, 'Triel', 'ទ្រៀល', 'triel', NULL, NULL), (579, 89, '<NAME>', 'ដំរីជាន់ខ្លា', 'damrei-choan-khla', NULL, NULL), (580, 89, '<NAME>', 'កំពង់ធំ', 'kampong-thum', NULL, NULL), (581, 89, '<NAME>', 'កំពង់រទេះ', 'kampong-roteh', NULL, NULL), (582, 89, 'Ou Kanthor', 'អូរកន្ធរ', 'ou-kanthor', NULL, NULL), (583, 89, 'Kampong', 'កំពង់ក្របៅ', 'kampong', NULL, NULL), (584, 89, '<NAME>', 'ព្រៃតាហ៊ូ', 'prey-ta-hu', NULL, NULL), (585, 89, 'Achar Leak', 'អាចារ្យលាក់', 'achar-leak', NULL, NULL), (586, 89, 'Srayov', 'ស្រយ៉ូវ', 'srayov', NULL, NULL), (587, 90, 'Chheu Teal ', 'ឈើទាល', 'chheu-teal', NULL, NULL), (588, 90, 'Dang Kambet', 'ដងកាំបិត', 'dang-kambet', NULL, NULL), (589, 90, 'Klaeng ', 'ក្លែង', 'klaeng', NULL, NULL), (590, 90, 'Mean Rith', 'មានរិទ្ធ', 'mean-rith', NULL, NULL), (591, 90, 'Mean Chey', 'មានជ័យ', 'mean-chey', NULL, NULL), (592, 90, 'Ngan ', 'ងន', 'ngan', NULL, NULL), (593, 90, 'Sandan', 'សណ្ដាន់', 'sandan', NULL, NULL), (594, 90, 'Sochet', 'សុចិត្រ', 'sochet', NULL, NULL), (595, 90, 'Tum Ring', 'ទំរីង', 'tum-ring', NULL, NULL), (596, 91, 'Banteay Stoung', 'បន្ទាយស្ទោង', 'banteay-stoung', NULL, NULL), (597, 91, '<NAME>', 'ចំណាក្រោម', 'chamna-kraom', NULL, NULL), (598, 91, '<NAME>', 'ចំណាលើ', 'chamna-leu', NULL, NULL), (599, 91, '<NAME>', 'កំពង់ចិនជើង', 'kampong-chen-cheung', NULL, NULL), (600, 91, '<NAME>', 'ម្សាក្រង', 'msa-krang', NULL, NULL), (601, 91, '<NAME>', 'ពាមបាង', 'peam-bang', NULL, NULL), (602, 91, 'Pralay', 'ប្រឡាយ', 'pralay', NULL, NULL), (603, 91, '<NAME>', 'ព្រះដំរី', 'preah-damrei', NULL, NULL), (604, 91, '<NAME>', 'រុងរឿង', 'rung-roeang', NULL, NULL), (605, 91, 'Samprouch', 'សំព្រោជ', 'samprouch', NULL, NULL), (606, 91, 'Trea', 'ទ្រា', 'trea', NULL, NULL), (607, 92, 'Doung ', 'ដូង', 'doung', NULL, NULL), (608, 92, 'Kraya ', 'ក្រយា', 'kraya', NULL, NULL), (609, 92, 'Ph<NAME>', 'ផាន់ញើម', 'phan-nheum', NULL, NULL), (610, 92, 'Sakream ', 'សាគ្រាម', 'sakream', NULL, NULL), (611, 92, 'Sala Visai', 'សាលាវិស័យ', 'sala-visai', NULL, NULL), (612, 92, 'Sameakki', 'សាមគ្គី', 'sameakki', NULL, NULL), (613, 92, 'Tuol Kreul', 'ទួលគ្រើល', 'tuol-kreul', NULL, NULL), (614, 93, 'Boeng Lvea', 'បឹងល្វា', 'boeng-lvea', NULL, NULL), (615, 93, 'Chroab ', 'ជ្រាប់', 'chroab', NULL, NULL), (616, 93, 'Kampong Thma ', 'កំពង់ថ្ម', 'kampong-thma', NULL, NULL), (617, 93, ' Kakaoh ', 'កកោះ', 'kakaoh', NULL, NULL), (618, 93, 'Kraya ', 'ក្រយា', 'kraya', NULL, NULL), (619, 93, 'Pnov ', 'ព្នៅ', 'pnov', NULL, NULL), (620, 93, 'Prasat ', 'ប្រាសាទ', 'prasat', NULL, NULL), (621, 93, 'Tang Krasang', 'តាំងក្រសាំង', 'tang-krasang', NULL, NULL), (622, 93, 'Ti Pou', 'ទីពោ', 'ti-pou', NULL, NULL), (623, 93, 'Tboung Krapeu', 'ត្បូងក្រពើ', 'tboung-krapeu', NULL, NULL), (624, 94, 'Chhuk', 'ឈូក', 'chhuk', NULL, NULL), (625, 94, 'Koul', 'គោល', 'koul', NULL, NULL), (626, 94, 'Sambour', 'សំបូរណ៍', 'sambour', NULL, NULL), (627, 94, 'Sraeung', 'ស្រើង', 'sraeung', NULL, NULL), (628, 94, 'Tang Krasau', 'តាំងក្រសៅ', 'tang-krasau', NULL, NULL), (629, 95, 'Chey', 'ជ័យ', 'chey', NULL, NULL), (630, 95, 'Damrei Slab', 'ដំរីស្លាប់', 'damrei-slab', NULL, NULL), (631, 95, 'Kampong Kou', 'កំពង់គោ', 'kampong-kou', NULL, NULL), (632, 95, 'Kampong Svay', 'កំពង់ស្វាយ', 'kampong-svay', NULL, NULL), (633, 95, 'Nipech', 'នីពេជ', 'nipech', NULL, NULL), (634, 95, 'Ph<NAME>ay', 'ផាត់សណ្ដាយ', 'phat-sanday', NULL, NULL), (635, 95, 'San Kor', 'សាន់គ', 'san-kor', NULL, NULL), (636, 95, 'Tbaeng', 'ត្បែង', 'tbaeng', NULL, NULL), (637, 95, 'Trapeang', 'ត្រពាំងឫស្សី', 'trapeang', NULL, NULL), (638, 95, '<NAME>', 'ក្ដីដូង', 'kdei-doung', NULL, NULL), (639, 95, 'Prey Kuy', 'ព្រៃគុយ', 'prey-kuy', NULL, NULL), (640, 114, 'Chhlong', 'ឆ្លូង', 'chhlong', NULL, NULL), (641, 114, '<NAME>', 'ដំរីផុង', 'domrei-phong', NULL, NULL), (642, 114, '<NAME>', 'ហាន់ជ័យ', 'han-chey', NULL, NULL), (643, 114, '<NAME>', 'កំពង់ដំរី', 'kampong-domrei', NULL, NULL), (644, 114, 'Kanhchor', 'កញ្ជរ', 'kanhchor', NULL, NULL), (645, 114, '<NAME>', 'ខ្សាច់អណ្ដែត', 'ksach-andaet', NULL, NULL), (646, 114, 'Pongro', 'ពង្រ', 'pongro', NULL, NULL), (647, 114, '<NAME>', 'ព្រែកសាម៉ាន់', 'praek-samann', NULL, NULL), (648, 115, 'Kantout', 'កន្ទួត', 'kantout', NULL, NULL), (649, 115, '<NAME>', 'ថ្មអណ្តើក', 'thma-andeuk', NULL, NULL), (650, 115, '<NAME>', 'កោះច្រែង', 'koh-chraeng', NULL, NULL), (651, 115, 'Sambok', 'សំបុក', 'sambok', NULL, NULL), (652, 115, '<NAME>', 'គោលាប់', 'kou-lorb', NULL, NULL), (653, 115, 'Thmei', 'ថ្មី', 'thmei', NULL, NULL), (654, 115, 'Dar', 'ដា', 'dar', NULL, NULL), (655, 115, '<NAME>', 'បុសលាវ', 'bos-leav', NULL, NULL), (656, 115, 'Changkrorng', 'ចង្ក្រង់', 'changkrorng', NULL, NULL), (657, 115, '<NAME>', 'ថ្មគ្រែ', 'thma-krae', NULL, NULL), (658, 116, '<NAME>', 'កោះត្រង់', 'koh-trorng', NULL, NULL), (659, 116, 'Krokor', 'ក្រកូរ', 'krokor', NULL, NULL), (660, 116, 'Kratie', 'ក្រចេះ', 'kratie', NULL, NULL), (661, 116, 'Ou Russei', 'អូរឬស្សី', 'ou-russei', NULL, NULL), (662, 116, '<NAME>', 'រកាកណ្តាល', 'roka-kandal', NULL, NULL), (663, 117, '<NAME>', 'ក្បាលដំរី', 'kbal-domrei', NULL, NULL), (664, 117, '<NAME>', 'កោះខ្ញែរ', 'koh-knhae', NULL, NULL), (665, 117, 'Ou Kreang', 'អូរគ្រៀង', 'ou-kreang', NULL, NULL), (666, 117, 'Rolous Meanchey', 'រលួសមានជ័យ', 'rolous-meanchey', NULL, NULL), (667, 117, 'K<NAME>', 'កំពង់ចាម', 'kampong-cham', NULL, NULL), (668, 117, '<NAME>', 'បឹងចារ', 'beung-char', NULL, NULL), (669, 117, 'Sombo', 'សំបូរ', 'sombo', NULL, NULL), (670, 117, 'Sandann', 'សណ្តាន់', 'sandann', NULL, NULL), (671, 117, '<NAME>', 'ស្រែជិះ', 'srae-chis', NULL, NULL), (672, 117, 'Vadhnak', 'វឌ្ឍនៈ', 'vadhnak', NULL, NULL), (673, 118, 'Chambok', 'ចំបក់', 'chambok', NULL, NULL), (674, 118, '<NAME>', 'ជ្រោយបន្ទាយ', 'chroy-banteay', NULL, NULL), (675, 118, '<NAME>', 'កំពង់គរ', 'kampong-kor', NULL, NULL), (676, 118, '<NAME>', 'ព្រែកប្រសព្', 'praek-brosop', NULL, NULL), (677, 118, '<NAME>', 'ឫស្សីកែវ', 'russei-keo', NULL, NULL), (678, 118, 'Soab', 'សោប', 'soab', NULL, NULL), (679, 118, 'Tamao', 'តាម៉ៅ', 'tamao', NULL, NULL), (680, 119, 'Khseum', 'ឃ្សឹម', 'khseum', NULL, NULL), (681, 119, '<NAME>', 'ពីរធ្នូ', 'pir-thnou', NULL, NULL), (682, 119, 'Snoul', 'ស្នួល', 'snoul', NULL, NULL), (683, 119, '<NAME>', 'ស្រែចារ', 'srae-char', NULL, NULL), (684, 119, '<NAME>', 'ស្វាយជ្រះ', 'svay-chreas', NULL, NULL), (685, 133, 'Sa ang', 'ស្អាង', 'sa-ang', NULL, NULL), (686, 133, '<NAME>', 'តស៊ូ', 'tor-sou', NULL, NULL), (687, 133, 'Kchorng', 'ខ្យង', 'kchorng', NULL, NULL), (688, 133, 'Chrach', 'ច្រាច់', 'chrach', NULL, NULL), (689, 133, 'Thmea', 'ធ្មា', 'thmea', NULL, NULL), (690, 133, 'Putrea', 'ពុទ្រា', 'putrea', NULL, NULL), (691, 134, 'ស្រអែម', 'ជាំក្សាន្ត', '', NULL, NULL), (692, 134, '<NAME>', 'ទឹកក្រហម', 'teuk-krahorm', NULL, NULL), (693, 134, '<NAME>', 'ព្រីងធំ', 'pring-thom', NULL, NULL), (694, 134, '<NAME>', 'រំដោះស្រែ', 'romdoh-srae', NULL, NULL), (695, 134, 'Yeang', 'យាង', 'yeang', NULL, NULL), (696, 134, 'Kantout', 'កន្ទួត', 'kantout', NULL, NULL), (697, 134, 'Sraem', 'ស្រអែម', 'sraem', NULL, NULL), (698, 134, 'Morodok', 'មរតក', 'morodok', NULL, NULL), (699, 135, 'Robeab', 'របៀប', 'robeab', NULL, NULL), (700, 135, 'Reaksmey', 'រស្មី', 'reaksmey', NULL, NULL), (701, 135, 'Rohas', 'រហ័ស', 'rohas', NULL, NULL), (702, 135, '<NAME>', 'រុងរឿង', 'rong-reung', NULL, NULL), (703, 135, '<NAME>', 'រីករាយ', 'rik-reay', NULL, NULL), (704, 135, '<NAME>', 'រួសរាន់', 'rous-roan', NULL, NULL), (705, 135, 'Ratanak', 'រតនៈ', 'ratanak', NULL, NULL), (706, 135, '<NAME>', 'រៀបរយ', 'reab-roay', NULL, NULL), (707, 135, 'Reaksa', 'រក្សា', 'reaksa', NULL, NULL), (708, 135, 'Romdors', 'រំដោះ', 'romdors', NULL, NULL), (709, 135, 'Rumtum', 'រមទម', 'rumtum', NULL, NULL), (710, 135, 'Romniy', 'រម្មណីយ', 'romniy', NULL, NULL), (711, 136, 'Ro ang', 'រអាង', 'ro-ang', NULL, NULL), (712, 136, '<NAME>', 'ភ្នំត្បែងមួយ', 'phnom-tbeng-mouy', NULL, NULL), (713, 136, 'Sdao', 'ស្តៅ', 'sdao', NULL, NULL), (714, 136, 'Ranakseh', 'រណសិរ្ស', 'ranakseh', NULL, NULL), (715, 136, 'Chomreun', 'ចំរើន', 'chomreun', NULL, NULL), (716, 137, '<NAME>', 'ឆែបមួយ', 'chhaeb-mouy', NULL, NULL), (717, 137, '<NAME>', 'ឆែបពីរ', 'chhaeb-pir', NULL, NULL), (718, 137, '<NAME>', 'សង្កែមួយ', 'sangke-mouy', NULL, NULL), (719, 137, '<NAME>', 'សង្កែពីរ', 'sangke-pir', NULL, NULL), (720, 137, '<NAME>', 'ម្លូព្រៃមួយ', 'mlouprey-mouy', NULL, NULL), (721, 137, '<NAME>', 'ម្លូព្រៃពីរ', 'mlouprey-pir', NULL, NULL), (722, 137, '<NAME>', 'កំពង់ស្រឡៅមួយ', 'kampong-sralao-mouy', NULL, NULL), (723, 137, '<NAME>', 'កំពង់ស្រឡៅពីរ', 'kampong-sralao-pir', NULL, NULL), (724, 138, '<NAME>', 'គូលែនត្បូង', 'kulen-tbong', NULL, NULL), (725, 138, '<NAME>', 'គូលែនជើង', 'kulen-cheung', NULL, NULL), (726, 138, 'Thmei', 'ថ្មី', 'thmei', NULL, NULL), (727, 138, '<NAME>', 'ភ្នំពេញ', 'phnom-penh', NULL, NULL), (728, 138, '<NAME>', 'ភ្នំត្បែងពីរ', 'phnom-tbeng-pir', NULL, NULL), (729, 138, 'Sroyong', 'ស្រយង់', 'sroyong', NULL, NULL), (730, 139, '<NAME>', 'កំពង់ប្រណោក', 'kompong-bronouk', NULL, NULL), (731, 139, '<NAME>', 'ប៉ាលហាល', 'bal-hal', NULL, NULL), (732, 139, '<NAME>', 'ឈានមុខ', 'chhean-mukh', NULL, NULL), (733, 139, 'Pou', 'ពោធិ៍', 'pou', NULL, NULL), (734, 139, 'Bromeru', 'ប្រមេរុ', 'bromeru', NULL, NULL), (735, 139, '<NAME>', 'ព្រះឃ្លាំង', 'preah-khleang', NULL, NULL), (736, 177, 'Komphun', 'កំភុន', 'komphun', NULL, NULL), (737, 177, '<NAME>', 'ក្បាលរមាស', 'kbal-romeas', NULL, NULL), (738, 177, 'Phluk', 'ភ្លុក', 'phluk', NULL, NULL), (739, 177, '<NAME>', 'សាមឃួយ', 'sam-khouy', NULL, NULL), (740, 177, 'Sdau', 'ស្ដៅ', 'sdau', NULL, NULL), (741, 177, 'S<NAME>', 'ស្រែគរ', 'srae-kor', NULL, NULL), (742, 177, 'Ta Lat', 'តាឡាត', 'ta-lat', NULL, NULL), (743, 178, 'K<NAME>', 'កោះព្រះ', 'koh-preah', NULL, NULL), (744, 178, 'K<NAME>', 'កោះសំពាយ', 'koh-sompeay', NULL, NULL), (745, 178, 'K<NAME>', 'កោះស្រឡាយ', 'koh-srolay', NULL, NULL), (746, 178, 'Ou Mreah', 'អូរម្រះ', 'ou-mreah', NULL, NULL), (747, 178, 'Ou Russei Kandal', 'អូរឫស្សីកណ្តាល', 'ou-russei-kandal', NULL, NULL), (748, 178, '<NAME>', 'សៀមបូក', 'siem-bouk', NULL, NULL), (749, 178, 'S<NAME>ang', 'ស្រែក្រសាំង', 'srae-krasang', NULL, NULL), (750, 178, 'Praek Meas', 'ព្រែកមាស', 'praek-meas', NULL, NULL), (751, 178, 'Sekong', 'សេកុង', 'sekong', NULL, NULL), (752, 178, 'Santipheap', 'សន្តិភាព', 'santipheap', NULL, NULL), (753, 178, '<NAME>', 'ស្រែសំបូរ', 'srae-sombo', NULL, NULL), (754, 178, '<NAME>', 'ថ្មកែវ', 'thma-keo', NULL, NULL), (755, 179, '<NAME>', 'អន្លង់ភេ', 'anlong-phe', NULL, NULL), (756, 179, '<NAME>', 'ចំការលើ', 'chomkar-leu', NULL, NULL), (757, 179, '<NAME>', 'កាំងចាម', 'kang-cham', NULL, NULL), (758, 179, '<NAME>', 'កោះស្នែង', 'koh-snaeng', NULL, NULL), (759, 179, 'Ou Rai', 'អូររៃ', 'ou-rai', NULL, NULL), (760, 179, 'Ou Svay', 'អូរស្វាយ', 'ou-svay', NULL, NULL), (761, 179, 'Preah Romkel', 'ព្រះរំកិល', 'preah-romkel', NULL, NULL), (762, 179, 'Som Ang', 'សំអាង', 'som-ang', NULL, NULL), (763, 179, 'Srae Russei', 'ស្រែឫស្សី', 'srae-russei', NULL, NULL), (764, 179, 'Thala Borivat', 'ថាឡាបរិវ៉ាត់', 'thala-borivat', NULL, NULL), (765, 179, 'An<NAME>', 'អន្លង់ជ្រៃ', 'anlong-chrey', NULL, NULL), (766, 180, 'Stung Trang', 'ស្ទឹងត្រែង', 'stung-trang', NULL, NULL), (767, 180, 'Srah Russei', 'ស្រះឫស្សី', 'srah-russei', NULL, NULL), (768, 180, 'Preah Bat', 'ព្រះបាទ', 'preah-bat', NULL, NULL), (769, 180, 'Sammaki', 'សាមគ្គី', 'sammaki', NULL, NULL), (770, 63, '<NAME>', 'បន្ទាយនាង', 'banteay-neang', NULL, NULL), (771, 63, 'B<NAME>ang', 'បត់ត្រង់', 'bat-trang', NULL, NULL), (772, 63, 'Chamnaom', 'ចំណោម', 'chamnaom', NULL, NULL), (773, 63, 'K<NAME>', 'គោកបល្ល័ង្គ', 'kouk-ballangk', NULL, NULL), (774, 63, '<NAME>', 'គយម៉ែង', 'koy-maeng', NULL, NULL), (775, 63, 'Ou Prasat', 'អូរប្រាសាទ', 'ou-prasat', NULL, NULL), (776, 63, 'Phnum Touch', 'ភ្នំតូច', 'phnum-touch', NULL, NULL), (777, 63, '<NAME>', 'រហាត់ទឹក', 'rohat-tuek', NULL, NULL), (778, 63, 'Ruessei Kraok', 'ឫស្សីក្រោក', 'ruessei-kraok', NULL, NULL), (779, 63, 'Sambuor', 'សំបួរ', 'sambuor', NULL, NULL), (780, 63, 'Soea', 'សឿ', 'soea', NULL, NULL), (781, 63, '<NAME> ', 'ស្រះរាំង', 'srah-reang', NULL, NULL), (782, 63, 'Ta Lam', 'តាឡំ', 'ta-lam', NULL, NULL), (783, 64, 'Chhnuor Mean Chey', 'ឈ្នួរមានជ័យ', 'chhnuor-mean-chey', NULL, NULL), (784, 64, '<NAME>', 'ជប់វារី', 'chob-veari', NULL, NULL), (785, 64, '<NAME>', 'ភ្នំលៀប', 'phnum-lieb', NULL, NULL), (786, 64, 'Prasat', 'ប្រាសាទ', 'prasat', NULL, NULL), (787, 64, '<NAME>', 'ព្រះនេត្រព្រះ', 'preah-netr-preah', NULL, NULL), (788, 64, 'Rohal', 'រហាល', 'rohal', NULL, NULL), (789, 64, 'Tean Kam', 'ទានកាំ', 'tean-kam', NULL, NULL), (790, 64, '<NAME>', 'ទឹកជោរ', 'tuek-chour', NULL, NULL), (791, 65, 'Bos Sbov', 'បុស្បូវ', 'bos-sbov', NULL, NULL), (792, 65, '<NAME>', 'កំពង់ស្វាយ', 'kampong-svay', NULL, NULL), (793, 65, 'Kaoh Pong Satv', 'កោះពងសត្វ', 'kaoh-pong-satv', NULL, NULL), (794, 65, 'Mkak', 'ម្កាក់', 'mkak', NULL, NULL), (795, 65, 'Ou Ambel', 'អូរអំបិល', 'ou-ambel', NULL, NULL), (796, 65, 'Phniet', 'ភ្នៀត', 'phniet', NULL, NULL), (797, 65, 'Preah Ponlea', 'ព្រះពន្លា', 'preah-ponlea', NULL, NULL), (798, 65, 'Tue<NAME>', 'ទឹកថ្លា', 'tuek-thla', NULL, NULL), (799, 66, 'Phkoam', 'ផ្គាំ', 'phkoam', NULL, NULL), (800, 66, 'Sarongk', 'សារង្គ', 'sarongk', NULL, NULL), (801, 66, 'Sla Kram', 'ស្លក្រាម', 'sla-kram', NULL, NULL), (802, 66, 'Svay Chek', 'ស្វាយចេក', 'svay-chek', NULL, NULL), (803, 66, 'Ta Baen', 'តាបែន', 'ta-baen', NULL, NULL), (804, 66, 'Ta Phou', 'តាផូ', 'ta-phou', NULL, NULL), (805, 66, 'Treas', 'ទ្រាស', 'treas', NULL, NULL), (806, 66, 'Roluos', 'រលួស', 'roluos', NULL, NULL), (807, 67, 'Changha', 'ចង្ហា', 'changha', NULL, NULL), (808, 67, 'Koub', 'កូប', 'koub', NULL, NULL), (809, 67, 'Kuttasat', 'គុត្តសត', 'kuttasat', NULL, NULL), (810, 67, 'Nimitt', 'និមិត្ត', 'nimitt', NULL, NULL), (811, 67, 'Samraong', 'សំរោង', 'samraong', NULL, NULL), (812, 67, 'Souphi', 'សូភី', 'souphi', NULL, NULL), (813, 67, 'Soengh', 'សឹង្ហ', 'soengh', NULL, NULL), (814, 67, 'P<NAME>', 'ប៉ោយប៉ែត', 'paoy-paet', NULL, NULL), (815, 67, 'Ou Bei Choan', 'អូរបីជាន់', 'ou-bei-choan', NULL, NULL), (816, 68, '<NAME>', 'បន្ទាយឆ្មារ', 'banteay-chhmar', NULL, NULL), (817, 68, '<NAME>', 'គោករមៀត', 'kouk-romiet', NULL, NULL), (818, 68, '<NAME>', 'ថ្មពួក', 'phum-thmei', NULL, NULL), (819, 68, '<NAME>', 'គោកកឋិន', 'thma-puok', NULL, NULL), (820, 68, '<NAME>', 'គំរូ', 'kouk-kakthen', NULL, NULL), (821, 68, 'Kumru', 'ភូមិថ្មី', 'kumru', NULL, NULL), (822, 69, '<NAME>', 'បឹងបេង', 'boeng-beng', NULL, NULL), (823, 69, 'Malai', 'ម៉ាឡៃ', 'malai', NULL, NULL), (824, 69, 'Ou Sampor', 'អូរសំព័រ', 'ou-sampor', NULL, NULL), (825, 69, 'Ou Sralau', 'អូរស្រឡៅ', 'ou-sralau', NULL, NULL), (826, 69, 'Tuol Pongro', 'ទួលពង្រ', 'tuol-pongro', NULL, NULL), (827, 69, 'Ta Kong', 'តាគង់', 'ta-kong', NULL, NULL), (828, 70, 'Changha', 'ចង្ហា', 'changha', NULL, NULL), (829, 70, 'Koub', 'កូប', 'koub', NULL, NULL), (830, 70, 'Kuttasat', 'គុត្តសត', 'kuttasat', NULL, NULL), (831, 70, 'Nimitt', 'និមិត្ត', 'nimitt', NULL, NULL), (832, 70, 'Samraong', 'សំរោង', 'samraong', NULL, NULL), (833, 70, 'Souphi', 'សូភី', 'souphi', NULL, NULL), (834, 70, 'Soengh', 'សឹង្ហ', 'soengh', NULL, NULL), (835, 70, 'P<NAME>', 'ប៉ោយប៉ែត', 'paoy-paet', NULL, NULL), (836, 70, 'Ou Bei Choan', 'អូរបីជាន់', 'ou-bei-choan', NULL, NULL), (837, 71, 'Nam Tau', 'ណាំតៅ', 'nam-tau', NULL, NULL), (838, 71, 'Paoy Char', 'ប៉ោយចារ', 'paoy-char', NULL, NULL), (839, 71, 'Ponley', 'ពន្លៃ', 'ponley', NULL, NULL), (840, 71, 'Spe<NAME>eng', 'ស្ពានស្រែង', 'spean-sraeng', NULL, NULL), (841, 71, '<NAME>', 'ស្រះជីក', 'srah-chik', NULL, NULL), (842, 71, '<NAME>', 'ភ្នំដី', 'phnum-dei', NULL, NULL), (843, 72, '<NAME>', 'អញ្ចាញរូង', 'anhchanh-rung', NULL, NULL), (844, 72, '<NAME>', 'ឆ្នុកទ្រូ', 'chhnok-tru', NULL, NULL), (845, 72, 'Chak', 'ចក', 'chak', NULL, NULL), (846, 72, '<NAME>', 'ខុនរ៉ង', 'khon-rang', NULL, NULL), (847, 72, '<NAME>', 'កំពង់ព្រះគគីរ', 'kampong-preah-kokir', NULL, NULL), (848, 72, 'Melum', 'មេលំ', 'melum', NULL, NULL), (849, 72, 'Phsar', 'ផ្សារ', 'phsar', NULL, NULL), (850, 72, '<NAME>', 'ពេជ្រចង្វារ', 'pech-changvar', NULL, NULL), (851, 72, 'Popel', 'ពពេល', 'popel', NULL, NULL), (852, 72, 'Ponley', 'ពន្លៃ', 'ponley', NULL, NULL), (853, 72, '<NAME>', 'ត្រពាំងចាន់', 'trapeang-chan', NULL, NULL), (854, 73, '<NAME>', 'ផ្សារឆ្នាំង', 'phsar-chhnang', NULL, NULL), (855, 73, '<NAME>', 'កំពង់ឆ្នាំង', 'kampong-chhnang', NULL, NULL), (856, 73, 'Pha er', 'ប្អេរ', 'pha-er', NULL, NULL), (857, 73, 'Khsam', 'ខ្សាម', 'khsam', NULL, NULL), (858, 74, 'Ampil Tuek', 'អំពិលទឹក', 'ampil-tuek', NULL, NULL), (859, 74, 'Chhuk Sa', 'ឈូកស', 'chhuk-sa', NULL, NULL), (860, 74, 'Chres', 'ច្រេស', 'chres', NULL, NULL), (861, 74, 'K<NAME>', 'កំពង់ត្រឡាច', 'kampong-tralach', NULL, NULL), (862, 74, 'Longveaek', 'លង្វែក', 'longveaek', NULL, NULL), (863, 74, 'Ou Ruessei', 'អូរឬស្សី', 'ou-ruessei', NULL, NULL), (864, 74, 'Peani', 'ពានី', 'peani', NULL, NULL), (865, 74, 'Saeb', 'សែប', 'saeb', NULL, NULL), (866, 74, 'Ta Ches', 'តាជេស', 'ta-ches', NULL, NULL), (867, 74, '<NAME>', 'ថ្មឥដ្ឋ', 'thma-edth', NULL, NULL), (868, 75, '<NAME>', 'ឈានឡើង', 'chhean-laeung', NULL, NULL), (869, 75, '<NAME>', 'ខ្នាឆ្មារ', 'khnar-chhmar', NULL, NULL), (870, 75, '<NAME>', 'រាំល្វា', 'krang-lvea', NULL, NULL), (871, 75, 'Peam', 'ពាម', 'peam', NULL, NULL), (872, 75, 'Sedthei', 'សេដ្ឋី', 'sedthei', NULL, NULL), (873, 75, 'Svay', 'ស្វាយ', 'svay', NULL, NULL), (874, 75, '<NAME>', 'ស្វាយជុក', 'svay-chuk', NULL, NULL), (875, 75, '<NAME>', 'ត្បែងខ្ពស់', 'tbaeng-khpos', NULL, NULL), (876, 75, '<NAME>', 'ធ្លកវៀន', 'thlok-vien', NULL, NULL), (877, 76, 'Chranouk', 'ច្រណូក', 'chranouk', NULL, NULL), (878, 76, 'Dar', 'ដារ', 'dar', NULL, NULL), (879, 76, '<NAME>', 'កំពង់ហៅ', 'kampong-hau', NULL, NULL), (880, 76, '<NAME>', 'ផ្លូវទូក', 'phlov-tuk', NULL, NULL), (881, 76, 'Pou', 'ពោធិ៍', 'pou', NULL, NULL), (882, 76, '<NAME>', 'ប្រឡាយមាស', 'pralay-meas', NULL, NULL), (883, 76, '<NAME>', 'សំរោងសែន', 'samraong-saen', NULL, NULL), (884, 76, '<NAME>', 'ស្វាយរំពារ', 'svay-rumpear', NULL, NULL), (885, 76, 'Trangel', 'ត្រងិល', 'trangel', NULL, NULL), (886, 77, '<NAME>', 'ជលសា', 'chol-sarg', NULL, NULL), (887, 77, '<NAME>', 'កោះថ្កូវ', 'kaoh-thkov', NULL, NULL), (888, 77, 'Kampong Os', 'កំពង់អុស', 'kampong-os', NULL, NULL), (889, 77, '<NAME>', 'ពាមឆ្កោក', 'peam-chhkaok', NULL, NULL), (890, 77, '<NAME>', 'ព្រៃគ្រី', 'prey-kri', NULL, NULL), (891, 78, '<NAME>', 'អណ្តូងស្នាយ', 'andoung-snay', NULL, NULL), (892, 78, '<NAME>', 'បន្ទាយព្រាល', 'banteay-preal', NULL, NULL), (893, 78, '<NAME>', 'ជើងគ្រាវ', 'cheung-kreav', NULL, NULL), (894, 78, '<NAME>', 'ជ្រៃបាក់', 'chrey-bak', NULL, NULL), (895, 78, '<NAME>', 'គោកបន្ទាយ', 'kouk-banteay', NULL, NULL), (896, 78, '<NAME>', 'ក្រាំងលាវ', 'krang-leav', NULL, NULL), (897, 78, 'Pongro', 'ពង្រ', 'pongro', NULL, NULL), (898, 78, 'Prasneb', 'ប្រស្នឹប', 'prasneb', NULL, NULL), (899, 78, '<NAME>', 'ព្រៃមូល', 'prey-mul', NULL, NULL), (900, 78, 'Rolea Ba ier', 'រលាប្អៀរ', 'rolea-ba-ier', NULL, NULL), (901, 78, '<NAME>', 'ស្រែថ្មី', 'srae-thmei', NULL, NULL), (902, 78, '<NAME>', 'ស្វាយជ្រុំ', 'svay-chrum', NULL, NULL), (903, 78, '<NAME>', 'ទឹកហូត', 'tuek-hout', NULL, NULL), (904, 79, 'Akphivoadth ', 'អភិវឌ្ឍន៍', 'akphivoadth', NULL, NULL), (905, 79, 'Chieb ', 'ជៀប', 'chieb', NULL, NULL), (906, 79, '<NAME>', 'ចោងម៉ោង', 'chaong-maong', NULL, NULL), (907, 79, 'K<NAME>k', 'ក្បាលទឹក', 'kbal-tuek', NULL, NULL), (908, 79, 'Khlong Popok', 'ខ្លុងពពក', 'khlong-popok', NULL, NULL), (909, 79, 'Krang Skear', 'រាំងស្គារ', 'krang-skear', NULL, NULL), (910, 79, 'Tang Krasang', 'តាំងក្រសាំង', 'tang-krasang', NULL, NULL), (911, 79, '<NAME>', 'ទួលខ្ពស់', 'tuol-khpos', NULL, NULL), (912, 130, 'Pailin', NULL, 'pailin', NULL, NULL), (913, 130, '<NAME>', NULL, 'ou-tavau', NULL, NULL), (914, 130, '<NAME>', NULL, 'tuol-lvea', NULL, NULL), (915, 130, '<NAME>', NULL, 'ba-yakha', NULL, NULL), (916, 131, '<NAME>', NULL, 'sala-krau', NULL, NULL), (917, 131, '<NAME>', NULL, 'stueng-trang', NULL, NULL), (918, 131, '<NAME>', NULL, 'stueng-kach', NULL, NULL), (919, 131, '<NAME>', NULL, 'ou-andoung', NULL, NULL), (920, 125, '<NAME>', NULL, 'anlong-veaeng', NULL, NULL), (921, 125, '<NAME>', NULL, 'trapeang-tav', NULL, NULL), (922, 125, '<NAME>', NULL, 'trapeang-prei', NULL, NULL), (923, 125, 'Thlat', NULL, 'thlat', NULL, NULL), (924, 125, 'Lumtong', NULL, 'lumtong', NULL, NULL), (925, 126, 'Ampil', NULL, 'ampil', NULL, NULL), (926, 126, 'Beng', NULL, 'beng', NULL, NULL), (927, 126, '<NAME>', NULL, 'kouk-khpos', NULL, NULL), (928, 126, '<NAME>', NULL, 'kouk-mon', NULL, NULL), (929, 127, '<NAME>', NULL, 'cheung-tien', NULL, NULL), (930, 127, '<NAME>', NULL, 'chong-kal', NULL, NULL), (931, 127, 'Krasang', NULL, 'krasang', NULL, NULL), (932, 127, 'Pongro', NULL, 'pongro', NULL, NULL), (933, 128, '<NAME>', NULL, 'bansay-reak', NULL, NULL), (934, 128, '<NAME>', NULL, 'bos-sbov', NULL, NULL), (935, 128, 'Kriel', NULL, 'kriel', NULL, NULL), (936, 128, 'Samraong', NULL, 'samraong', NULL, NULL), (937, 128, '<NAME>', NULL, 'ou-smach', NULL, NULL), (938, 129, '<NAME>', NULL, 'bak-anlung', NULL, NULL), (939, 129, 'Ph\'av', NULL, 'phav', '2020-07-31 12:17:06', NULL), (940, 129, '<NAME>', NULL, 'ou-svay', NULL, NULL), (941, 129, '<NAME>', NULL, 'preah-pralay', NULL, NULL), (942, 129, '<NAME>', NULL, 'tumnob-dach', NULL, NULL), (943, 12, '<NAME>', NULL, 'trapeang-prasat', NULL, NULL); /*!40000 ALTER TABLE `communes` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; <file_sep>/database/seeds/UserTableSeeder.php <?php use Illuminate\Database\Seeder; class UserTableSeeder extends Seeder { public function run() { \DB::table('users')->truncate(); \DB::table('agents')->truncate(); \DB::table('users')->insert([ 'name_en' => 'Super Administrator', 'name_kh' => 'ម្ចាស់ក្រុមហ៊ុន', 'username' => 'superadmin', 'referal_code' => '9988776655', 'ref_group' => 'OWNER', 'ref_level' => 'OWNER', 'phone' => '092374003', 'phone1' => '', 'phone2' => '', 'email' => '<EMAIL>', 'address' => '', 'province_id' => 1, 'district_id' =>1, 'commune_id' => 1, 'password' => <PASSWORD>('<PASSWORD>'), 'photo' => 'superadmin-1598848862-641974319.png' ]); \DB::table('users')->insert([ 'name_en' => 'Administrator', 'name_kh' => 'អ្នកគ្រប់គ្រង', 'username' => 'admin', 'referal_code' => '1122334455', 'ref_group' => 'G1', 'ref_level' => 'G1-001', 'phone' => '012321422', 'phone1' => '', 'phone2' => '', 'email' => '<EMAIL>', 'address' => '', 'province_id' => 1, 'district_id' =>1, 'commune_id' => 1, 'password' => <PASSWORD>('<PASSWORD>'), 'photo' => 'admin-1598849035-1375235290.jpg' ]); \DB::table('agents')->insert([ 'user_id'=>2, 'referal_user_id'=>1, 'referal_user_code'=>'9988776655', 'ref_group' => 'G1', 'ref_level' => 'G1-001', 'name_en' => 'Administrator', 'name_kh' => 'អ្នកគ្រប់គ្រង', 'phone' => '012321422', 'phone1' => '', 'phone2' => '', 'email' => '<EMAIL>', 'address' => '', 'job_title' => 'Administrator', 'description' =>'Administrator', 'photo' => 'admin-1598849035-1375235290.jpg' ]); } } <file_sep>/app/Exports/PropertyExport.php <?php namespace App\Exports; use App\Models\Property; use Maatwebsite\Excel\Events\AfterSheet; use Maatwebsite\Excel\Concerns\Exportable; use Maatwebsite\Excel\Concerns\WithEvents; use Maatwebsite\Excel\Concerns\WithHeadings; use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\ShouldAutoSize; use Maatwebsite\Excel\Concerns\WithMapping; class PropertyExport implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents, WithMapping { use Exportable; protected $request; // varible form and to public function __construct($request) { $this->request = $request; } //function select data from database public function collection() { $properties = Property::PropertyReport($this->request)->get(); return $properties; } public function registerEvents(): array { return [ AfterSheet::class => function(AfterSheet $event) { $cellRange = 'A1:W1'; // All headers $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14); }, ]; } //function header in excel public function headings(): array { return [ 'No', 'Title', 'Price', 'Category', 'Type', 'Post By', 'Province', 'District', 'Commune', 'views', 'Status' ]; } public function map($properties):array { return [ $properties->id, $properties->title, $properties->price, $properties->category->category_name, $properties->parent->category_name, $properties->name, $properties->province->name_en, $properties->district->name_en, $properties->commune->name_en, $properties->view_count, $properties->save_contact, ]; } } <file_sep>/app/Models/Bedroom.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Bedroom extends Model { public static function bedrooms() { return static::pluck('slug', 'room'); } } <file_sep>/app/Models/PropertyType.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class PropertyType extends Model { protected $table = 'property_type'; public function childs() { return $this->hasMany(PropertyType::class,'parent_id','id'); } public function cateType() { return $this->hasMany(Category::class,'type_id','parent_id'); } public function categoryType() { return $this->hasOne(Category::class,'type_id','parent_id'); } public function cateSub() { return $this->hasMany(Category::class,'sub_type_id','type_id'); } public function categorySub() { return $this->hasOne(Category::class,'sub_type_id','type_id'); } } <file_sep>/app/Http/Controllers/Admin/ImageController.php <?php namespace App\Http\Controllers\Admin; use App\Models\Image; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class ImageController extends Controller { public function index() { $images = Image::all(); return view('images.index',compact('images')); } public function create() { return view('images.create'); } public function store(Request $request) { $input = $request->all(); $file = $request->file('file'); if($file){ $filename = $file->getClientOriginalName(); $filesize = $file->getClientSize(); $extension = $file->getClientOriginalExtension(); $file_title = rand().time().'.'.$extension; $uploadpath = \public_path().'/uploads/gallery/'; $file->move($uploadpath,$file_title); $multi_images = Image::create([ 'image_title' => $filename, 'image_name' => $file_title, 'image_size' => $filesize, 'image_extension' => $extension ]); if($multi_images){ echo "True"; } } } public function show($id) { // } public function edit($id) { // } public function update(Request $request, $id) { // } public function destroy($id) { // } } <file_sep>/database/provinces.sql -- -------------------------------------------------------- -- Host: 127.0.0.1 -- Server version: 5.7.26 - MySQL Community Server (GPL) -- Server OS: Win64 -- HeidiSQL Version: 11.0.0.5919 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Dumping database structure for thepinrealestate_social_login DROP DATABASE IF EXISTS `thepinrealestate_social_login`; CREATE DATABASE IF NOT EXISTS `thepinrealestate_social_login` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `thepinrealestate_social_login`; -- Dumping structure for table thepinrealestate_social_login.provinces DROP TABLE IF EXISTS `provinces`; CREATE TABLE IF NOT EXISTS `provinces` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name_en` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `name_kh` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `slug` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=26 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.provinces: 25 rows /*!40000 ALTER TABLE `provinces` DISABLE KEYS */; INSERT INTO `provinces` (`id`, `name_en`, `name_kh`, `slug`, `created_at`, `updated_at`) VALUES (1, '<NAME>', 'ភ្នំពេញ', 'phnom-penh', NULL, NULL), (2, '<NAME>', 'ព្រះសីហនុ', 'preah-sihanouk', NULL, NULL), (3, '<NAME>', 'កំពង់ចាម', 'kampong-cham', NULL, NULL), (4, 'Siem Reap', 'សៀមរាប', 'siem-reap', NULL, NULL), (5, 'Battambang', 'បាត់ដំបង', 'battambang', NULL, NULL), (6, 'Kandal', 'កណ្តាល', 'kandal', NULL, NULL), (7, 'Banteay Meanchey', 'បន្ទាយមានជ័យ', 'banteay-meanchey', NULL, NULL), (8, '<NAME>', 'កំពង់ឆ្នាំង', 'kampong-chhnang', NULL, NULL), (9, '<NAME>', 'កំពង់ស្ពឺ', 'kampong-speu', NULL, NULL), (10, 'Kampong Thom', 'កំពង់ធំ', 'kampong-thom', NULL, NULL), (11, 'Kampot', 'កំពត', 'kampot', NULL, NULL), (12, 'Kep', 'កែប', 'kep', NULL, NULL), (13, '<NAME>', 'កោះកុង', 'koh-Kong', NULL, NULL), (14, 'Kratie', 'ក្រចេះ', 'kratie', NULL, NULL), (15, 'Mondulkiri', 'មណ្ឌលគិរី', 'mondulkiri', NULL, NULL), (16, '<NAME>', 'ឧត្តរមានជ័យ', 'oddar-meanchey', NULL, NULL), (17, 'Pailin', 'ប៉ៃលិន', 'pailin', NULL, NULL), (18, '<NAME>', 'ព្រះវិហារ', 'preah-vihear', NULL, NULL), (19, '<NAME>', 'ព្រៃវែង', 'prey-veng', NULL, NULL), (20, 'Pursat', 'ពោធ៌សាត់', 'pursat', NULL, NULL), (21, 'Ratanakiri', 'រតនគីរី', 'ratanakiri', NULL, NULL), (22, 'St<NAME>', 'ស្ទឹងត្រែង', 'stung-treng', NULL, NULL), (23, 'Sv<NAME>eng', 'ស្វាយរៀង', 'svay-rieng', NULL, NULL), (24, 'Takeo', 'តាកែវ', 'takeo', NULL, NULL), (25, 'Tboung Khmum', 'ត្បូងឃ្មុំ', 'tboung-khmum', NULL, NULL); /*!40000 ALTER TABLE `provinces` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; <file_sep>/database/districts.sql -- -------------------------------------------------------- -- Host: 127.0.0.1 -- Server version: 5.7.26 - MySQL Community Server (GPL) -- Server OS: Win64 -- HeidiSQL Version: 11.0.0.5919 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Dumping database structure for thepinrealestate_social_login DROP DATABASE IF EXISTS `thepinrealestate_social_login`; CREATE DATABASE IF NOT EXISTS `thepinrealestate_social_login` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `thepinrealestate_social_login`; -- Dumping structure for table thepinrealestate_social_login.districts DROP TABLE IF EXISTS `districts`; CREATE TABLE IF NOT EXISTS `districts` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `province_id` int(11) DEFAULT NULL, `name_en` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `name_kh` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `slug` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE=MyISAM AUTO_INCREMENT=198 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.districts: 197 rows /*!40000 ALTER TABLE `districts` DISABLE KEYS */; INSERT INTO `districts` (`id`, `province_id`, `name_en`, `name_kh`, `slug`, `created_at`, `updated_at`) VALUES (1, 1, '<NAME>', 'ឫស្សីកែវ', 'ruessei-kaev', NULL, NULL), (2, 1, 'Saensokh', 'សែនសុខ', 'saensokh', NULL, NULL), (3, 1, 'Por Senchey', 'ពោធិសែនជ័យ', 'por-senchey', NULL, NULL), (4, 1, '<NAME>', 'ជ្រោយចង្វារ', 'chrouy-changva', NULL, NULL), (5, 1, '<NAME>', 'ព្រែកភ្នៅ', 'preaek-pnov', NULL, NULL), (6, 1, '<NAME>', 'ច្បារអំពៅ', 'chbar-ampov', NULL, NULL), (7, 1, '<NAME>', 'ដូនពេញ', 'doun-penh', NULL, NULL), (8, 1, '<NAME>', '៧មករា', 'prampir-meakkara', NULL, NULL), (9, 1, '<NAME>', 'ទួលគោក', 'toul-kouk', NULL, NULL), (10, 1, 'Dangkao', 'ដង្កោ', 'dangkao', NULL, NULL), (11, 1, 'Mean Chey', 'មានជ័យ', 'mean-chey', NULL, NULL), (12, 1, '<NAME>', 'ចំការមន', 'chamkar-mon', NULL, NULL), (13, 2, '<NAME>', 'ព្រះសីហនុ', 'krong-preah-sihanouk', NULL, NULL), (14, 2, '<NAME>', 'ព្រៃនប់', 'prey-nob', NULL, NULL), (15, 2, '<NAME>', 'ស្ទឹងហាវ', 'stueng-hav-chey', NULL, NULL), (16, 2, '<NAME>', 'កំពង់សីលា', 'kompong-seila', NULL, NULL), (17, 3, '<NAME>', 'កំពង់ចាម', 'krong-kampong-cham', NULL, NULL), (18, 3, '<NAME>', 'កំពង់សៀម', 'kampong-siem', NULL, NULL), (19, 3, 'KangMeas', 'កងមាស', 'kangmeas', NULL, NULL), (20, 3, '<NAME>', 'កោះសុទិន', 'kaoh-soutin', NULL, NULL), (21, 3, '<NAME>', 'ព្រៃឈរ', 'prey-chhor', NULL, NULL), (22, 3, '<NAME>', 'ស្រីសន្ធរ', 'srei-santhor', NULL, NULL), (23, 3, '<NAME>', 'ស្ទឹងត្រង់', 'stueng-trang', NULL, NULL), (24, 3, 'Batheay', 'បាធាយ', 'batheay', NULL, NULL), (25, 3, '<NAME>', 'ចំការលើ', 'chamkar-leu', NULL, NULL), (26, 3, 'Cheung Prey', 'ជើងព្រៃ', 'cheung-prey', NULL, NULL), (27, 4, 'An<NAME>', 'អង្គរជុំ', 'angkor-chum', NULL, NULL), (28, 4, 'An<NAME>', 'អង្គរធំ', 'angkor-thom', NULL, NULL), (29, 4, '<NAME>', 'បន្ទាយស្រី', 'banteay-srey', NULL, NULL), (30, 4, 'Chi Kraeng', 'ជីក្រែង', 'chi-kraeng', NULL, NULL), (31, 4, 'Kralanh', 'ក្រឡាញ់', 'kralanh', NULL, NULL), (32, 4, 'Pouk', 'ពួក', 'pouk', NULL, NULL), (33, 4, 'Pr<NAME>akong', 'ប្រាសាទបាគង', 'prasat-bakong', NULL, NULL), (34, 4, 'Krong Siem Reap', 'ក្រុងសៀមរាប', 'krong-siem-reap', NULL, NULL), (35, 4, '<NAME>', 'សុទ្រនិគមន៍', 'soutr-nikum', NULL, NULL), (36, 4, '<NAME>', 'ស្រីស្នំ', 'srei-snam', NULL, NULL), (37, 4, '<NAME>', 'ស្វាយលើ', 'svay-leu', NULL, NULL), (38, 4, 'Varin', 'វ៉ារិន', 'varin', NULL, NULL), (39, 5, 'Banan', 'បាណន់', 'banan', NULL, NULL), (40, 5, '<NAME>', 'ថ្មរគោល', 'thma-koul', NULL, NULL), (41, 5, '<NAME>', 'ក្រុងបាត់ដំបង', 'krong-battambang', NULL, NULL), (42, 5, 'Bavel', 'បវេល', 'bavel', NULL, NULL), (43, 5, '<NAME>', 'ឯកភ្នំ', 'aek-phnum', NULL, NULL), (44, 5, '<NAME>', 'មោង រស្សី', 'moung-ruessei', NULL, NULL), (45, 5, '<NAME>', 'រតនាមណ្ឌល', 'rotonak-mondol', NULL, NULL), (46, 5, 'Sangkae', 'សង្កៃរ', 'sangkae', NULL, NULL), (47, 5, 'Samlout', 'សំឡូត', 'samlout', NULL, NULL), (48, 5, '<NAME>', 'សំពៅលូន', 'sampov-lun', NULL, NULL), (49, 5, '<NAME>', 'ភ្នំព្រឹក', 'phnom-proek', NULL, NULL), (50, 5, 'Kamrieng', 'កំរៀង', 'kamrieng', NULL, NULL), (51, 5, '<NAME>a', 'គាស់ក្រឡ', 'koas-krala', NULL, NULL), (52, 5, '<NAME>', 'រុក្ខគីរី', 'rukhak-kiri', NULL, NULL), (53, 6, '<NAME>', '', 'kandal-stueng', NULL, NULL), (54, 6, '<NAME>', '', 'koh-thum', NULL, NULL), (55, 6, '<NAME>', '', 'mukh-kamphool', NULL, NULL), (56, 6, '<NAME>', '', 'sa-ang', NULL, NULL), (57, 6, '<NAME>', '', 'leuk-daek', NULL, NULL), (58, 6, '<NAME>', '', 'krong-ta-khmau', NULL, NULL), (59, 6, '<NAME>', '', 'kien-svay', NULL, NULL), (60, 6, '<NAME>', '', 'ponhea-leu', NULL, NULL), (61, 6, '<NAME>', '', 'lvea-aem', NULL, NULL), (62, 6, '<NAME>', '', 'khsach-kandal', NULL, NULL), (63, 7, '<NAME>', '', 'mongkol-borei', NULL, NULL), (64, 7, '<NAME>', '', 'preah-netr-preah', NULL, NULL), (65, 7, '<NAME>', '', 'serei-saophoan', NULL, NULL), (66, 7, '<NAME>', '', 'svay-chek', NULL, NULL), (67, 7, '<NAME>', '', 'ou-chrov', NULL, NULL), (68, 7, '<NAME>', '', 'thma-puok', NULL, NULL), (69, 7, 'Malai', '', 'malai', NULL, NULL), (70, 7, '<NAME>', '', 'ou-chrov', NULL, NULL), (71, 7, '<NAME>', '', 'phnum-srok', NULL, NULL), (72, 8, 'Baribour', '', 'baribour', NULL, NULL), (73, 8, '<NAME>', '', 'kampong-chhnang', NULL, NULL), (74, 8, '<NAME>', '', 'kampong-tralach', NULL, NULL), (75, 8, 'Sameakki', '', 'sameakki', NULL, NULL), (76, 8, '<NAME>', '', 'kampong-leaeng', NULL, NULL), (77, 8, '<NAME>', '', 'chol-kiri', NULL, NULL), (78, 8, '<NAME>', '', 'rolea-bier', NULL, NULL), (79, 8, '<NAME>', '', 'tuek-phos', NULL, NULL), (80, 9, 'Basedth', '', 'basedth', NULL, NULL), (81, 9, '<NAME>', '', 'kong-pisei', NULL, NULL), (82, 9, 'Odongk', '', 'odongk', NULL, NULL), (83, 9, '<NAME>', '', 'samraong-tong', NULL, NULL), (84, 9, 'Aoral', '', 'aoral', NULL, NULL), (85, 9, '<NAME>', '', 'phnom-sruoch', NULL, NULL), (86, 9, '<NAME>', '', 'chbar-mon', NULL, NULL), (87, 9, 'Thpong', '', 'thpong', NULL, NULL), (88, 10, 'Baray', '', 'baray', NULL, NULL), (89, 10, '<NAME>', '', 'stueng-saen', NULL, NULL), (90, 10, 'Sandaan', '', 'sandaan', NULL, NULL), (91, 10, 'Stoung', '', 'stoung', NULL, NULL), (92, 10, '<NAME>', '', 'prasat-balangk', NULL, NULL), (93, 10, 'Santuk', '', 'santuk', NULL, NULL), (94, 10, '<NAME>', '', 'prasat-sambour', NULL, NULL), (95, 10, '<NAME>', '', 'kampong-svay', NULL, NULL), (96, 11, '<NAME>', '', 'angkor-chey', NULL, NULL), (97, 11, 'Chhuk', '', 'chhuk', NULL, NULL), (98, 11, '<NAME>', '', 'dorng-tong', NULL, NULL), (99, 11, '<NAME>', '', 'teouk-chhou', NULL, NULL), (100, 11, '<NAME>', '', 'banteay-meas', NULL, NULL), (101, 11, '<NAME>', '', 'kampong-trach', NULL, NULL), (102, 11, '<NAME>', '', 'chum-kiri', NULL, NULL), (103, 11, 'Kampot', '', 'kampot', NULL, NULL), (104, 12, '<NAME>', '', 'krong-kep', NULL, NULL), (105, 12, '<NAME>', '', 'damnak-chang-aeur', NULL, NULL), (106, 12, '<NAME>', '', 'krong-kep', NULL, NULL), (107, 13, '<NAME>', '', 'botum-sakor', NULL, NULL), (108, 13, '<NAME>', '', 'koh-kong', NULL, NULL), (109, 13, '<NAME>', '', 'mondol-seima', NULL, NULL), (110, 13, '<NAME>', '', 'thma-bang', NULL, NULL), (111, 13, '<NAME>', '', 'kiri-sakor', NULL, NULL), (112, 13, '<NAME>', '', 'khemara-phoumin', NULL, NULL), (113, 13, '<NAME>', '', 'srae-ambel', NULL, NULL), (114, 14, 'Chhlong', '', 'chhlong', NULL, NULL), (115, 14, '<NAME>', '', 'chitr-borei', NULL, NULL), (116, 14, '<NAME>', '', 'krong-kratie', NULL, NULL), (117, 14, 'Sombo', '', 'sombo', NULL, NULL), (118, 14, '<NAME>', '', 'preaek-prasob', NULL, NULL), (119, 14, 'Snoul', '', 'snoul', NULL, NULL), (120, 15, '<NAME>', '', 'kaev-seima', NULL, NULL), (121, 15, '<NAME>', '', 'ou-reang', NULL, NULL), (122, 15, '<NAME>', '', 'krong-saen', NULL, NULL), (123, 15, '<NAME>', '', 'pech-chreada', NULL, NULL), (124, 15, '<NAME>', '', 'kaoh-nheaek', NULL, NULL), (125, 16, '<NAME>', '', 'anlong-veaeng', NULL, NULL), (126, 16, '<NAME>', '', 'banteay-ampil', NULL, NULL), (127, 16, '<NAME>', '', 'chong-kal', NULL, NULL), (128, 16, '<NAME>', '', 'krong-samraong', NULL, NULL), (129, 16, '<NAME>', '', 'trapeang-prasat', NULL, NULL), (130, 17, '<NAME>', '', 'krong-pailin', NULL, NULL), (131, 17, '<NAME>', '', 'sala-krau', NULL, NULL), (132, 17, '<NAME>', '', 'chang-kal', NULL, NULL), (133, 18, '<NAME>', '', 'chey-saen', NULL, NULL), (134, 18, '<NAME>', '', 'choam-khsant', NULL, NULL), (135, 18, 'Rovieng', '', 'rovieng', NULL, NULL), (136, 18, '<NAME>', '', 'sangkom-thmei', NULL, NULL), (137, 18, 'Chhaeb', '', 'chhaeb', NULL, NULL), (138, 18, 'Kulen', '', 'kulen', NULL, NULL), (139, 18, '<NAME>', '', 'tbaeng-mean-chey', NULL, NULL), (140, 18, '<NAME>', '', 'krong-preah-vihear', NULL, NULL), (141, 19, '<NAME>', '', 'ba-phnum', NULL, NULL), (142, 19, 'Kanhchriech', '', 'kanhchriech', NULL, NULL), (143, 19, '<NAME>', '', 'peam-ro', NULL, NULL), (144, 19, '<NAME>', '', 'preah-sdach', NULL, NULL), (145, 19, '<NAME>', '', 'me-sang', NULL, NULL), (146, 19, '<NAME>', '', 'pea-reang', NULL, NULL), (147, 19, '<NAME>', '', 'kamchay-mear', NULL, NULL), (148, 19, '<NAME>', '', 'prey-veaeng', NULL, NULL), (149, 19, '<NAME>', '', 'peam-chor', NULL, NULL), (150, 19, '<NAME>', '', 'kampong-trabaek', NULL, NULL), (151, 19, '<NAME>', '', 'por-reang', NULL, NULL), (152, 19, '<NAME>', '', 'svay-ontor', NULL, NULL), (153, 20, 'Bakan', '', 'bakan', NULL, NULL), (154, 20, 'Krakor', '', 'krakor', NULL, NULL), (155, 20, '<NAME>', '', 'krong-pursat', NULL, NULL), (156, 20, 'Kandieng', '', 'kandieng', NULL, NULL), (157, 20, '<NAME>', '', 'phnum-kravanh', NULL, NULL), (158, 20, '<NAME>', '', 'veal-veaeng', NULL, NULL), (159, 21, '<NAME>', '', 'andoung-meas', NULL, NULL), (160, 21, '<NAME>', '', 'koun-mom', NULL, NULL), (161, 21, '<NAME>', '', 'ou-chum', NULL, NULL), (162, 21, '<NAME>', '', 'ta-veaeng', NULL, NULL), (163, 21, '<NAME>', '', 'krong-banlung', NULL, NULL), (164, 21, 'Lumphat', '', 'lumphat', NULL, NULL), (165, 21, '<NAME>', '', 'ou-ya-dav', NULL, NULL), (166, 21, '<NAME>', '', 'bar-kaev', NULL, NULL), (167, 22, 'Sesan', '', 'sesan', NULL, NULL), (168, 22, '<NAME>', '', 'siem-bouk', NULL, NULL), (169, 22, '<NAME>', '', 'siem-pang', NULL, NULL), (170, 22, '<NAME>', '', 'thala-barivat', NULL, NULL), (171, 22, '<NAME>', '', 'krong-stung-treng', NULL, NULL), (172, 23, 'Chantrea', '', 'chantrea', NULL, NULL), (173, 23, 'Rumduol', '', 'rumduol', NULL, NULL), (174, 23, '<NAME>', '', 'svay-chrum', NULL, NULL), (175, 23, '<NAME>', '', 'svay-teab', NULL, NULL), (176, 23, '<NAME>', '', 'kampong-rou', NULL, NULL), (177, 23, '<NAME>', '', 'romeas-haek', NULL, NULL), (178, 23, '<NAME>', '', 'krong-bavet', NULL, NULL), (179, 23, '<NAME>', '', 'krong-svay-rieng', NULL, NULL), (180, 24, '<NAME>', '', 'angkor-borei', NULL, NULL), (181, 24, '<NAME>', '', 'kiri-vong', NULL, NULL), (182, 24, 'Samraong', '', 'samraong', NULL, NULL), (183, 24, 'Treang', '', 'treang', NULL, NULL), (184, 24, 'Bati', '', 'bati', NULL, NULL), (185, 24, '<NAME>', '', 'krong-doun-kaev', NULL, NULL), (186, 24, '<NAME>', '', 'kaoh-andaet', NULL, NULL), (187, 24, '<NAME>', '', 'krong-doun-kaev', NULL, NULL), (188, 24, '<NAME>', '', 'tram-kak', NULL, NULL), (189, 24, '<NAME>', '', 'prey-kabbas', NULL, NULL), (190, 24, '<NAME>', '', 'bourei-cholsar', NULL, NULL), (191, 25, 'Dombae', '', 'dombae', NULL, NULL), (192, 25, 'Memot', '', 'memot', NULL, NULL), (193, 25, '<NAME>', '', 'ponhea-kraek', NULL, NULL), (194, 25, '<NAME>', '', 'krouch-chhma', NULL, NULL), (195, 25, '<NAME>', '', 'tboung-khmum', NULL, NULL), (196, 25, 'Ou Reang Ov', '', 'ou-reang-ov', NULL, NULL), (197, 25, '<NAME>', '', 'krong-suong', NULL, NULL); /*!40000 ALTER TABLE `districts` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; <file_sep>/app/Http/Controllers/Admin/DropZoneController.php <?php namespace App\Http\Controllers\Admin; use App\Models\ImageGallery; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class DropZoneController extends Controller { public function upload() { return view('dropzone'); } public function store(Request $request) { $image = $request->file('file'); $imageName = $image->getClientOriginalName(); $uploadpath = public_path() . '\\uploads\\dropzone\\' . 'product_group' . '\\'; $image->move($uploadpath, $imageName); // $image->move(public_path('images/dropzone/'), $imageName); $imageUpload = new ImageGallery(); $imageUpload -> product_id = 1; $imageUpload -> product_group = 'product_group'; $imageUpload -> gallery_image = $imageName; $imageUpload -> save(); return response()->json(['success' => $imageName]); } public function delete(Request $request) { $filename = $request->get('filename'); ImageGallery::where('gallery_image', $filename)->delete(); $uploadpath = public_path() . '\\uploads\\dropzone\\' . 'product_group' . '\\'; $path = $uploadpath . $filename; if (file_exists($path)) { unlink($path); } return $filename; } // function index() // { // return view('dropzone'); // } // function upload(Request $request) // { // $image = $request->file('file'); // $imageName = time() . '.' . $image->extension(); // $image->move(public_path('images'), $imageName); // return response()->json(['success' => $imageName]); // } // function fetch() // { // $images = \File::allFiles(public_path('images')); // $output = '<div class="row">'; // foreach($images as $image) // { // $output .= ' // <div class="col-md-2" style="margin-bottom:16px;" align="center"> // <img src="'.asset('images/' . $image->getFilename()).'" class="img-thumbnail" width="175" height="175" style="height:175px;" /> // <button type="button" class="btn btn-link remove_image" id="'.$image->getFilename().'">Remove</button> // </div> // '; // } // $output .= '</div>'; // echo $output; // } // function delete(Request $request) // { // if($request->get('name')) // { // \File::delete(public_path('images/' . $request->get('name'))); // } // } } <file_sep>/app/Providers/AppServiceProvider.php <?php namespace App\Providers; use Illuminate\Support\Facades\Schema; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { public function register() { // } public function boot() { Schema::defaultStringLength(191); view()->composer('*', function($view) { $view->with('categories', \App\Models\Category::categories()); $view->with('bedrooms', \App\Models\Bedroom::pluck('slug','room')); $view->with('bathrooms', \App\Models\Bathroom::pluck('slug','room')); $view->with('facings', \App\Models\Facing::pluck('facing','id')); }); } } <file_sep>/app/Exports/FilterExport.php <?php namespace App\Exports; use App\Models\User; use Maatwebsite\Excel\Events\AfterSheet; use Maatwebsite\Excel\Concerns\Exportable; use Maatwebsite\Excel\Concerns\WithEvents; use Illuminate\Contracts\Queue\ShouldQueue; use Maatwebsite\Excel\Concerns\WithMapping; use Maatwebsite\Excel\Concerns\WithHeadings; use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\ShouldAutoSize; class FilterExport implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents { use Exportable; // varible form and to public function __construct(String $from = null , String $to = null) { $this->from = $from; $this->to = $to; } //function select data from database public function collection() { if($this->from !='' && $this->to !=''){ $users = User::role(['Agent','Member'])->whereBetween('created_at',[$this->from,$this->to])->get(); } else { $users = User::role(['Agent','Member'])->get(); } return $users; } public function registerEvents(): array { return [ AfterSheet::class => function(AfterSheet $event) { $cellRange = 'A1:W1'; // All headers $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14); }, ]; } //function header in excel public function headings(): array { return [ 'No', 'name', 'email', 'email_verified_at', 'created_at', 'updated_at', ]; } } <file_sep>/app/Models/Upload.php <?php namespace App\Models; use App\Models\ProductGallery; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\File; class Upload extends Model { //use with store function in controller public static function imageUpload($filename,$ObjModel, $path = null) { if(request()->hasfile($filename)) { $dir = 'uploads/' . $path .'/'; $file = request()->file($filename); $extension = $file->getClientOriginalExtension(); $filename = time().'.'.$extension; $file->move($dir,$filename); $ObjModel->image = $filename; } } //use with update function in controller public static function imageUpdate($filename,$ObjModel, $path = null) { $dir = 'uploads/'. $path .'/'; $oldfilename = $ObjModel->image; if(request()->hasfile($filename)) { if ($ObjModel->image != '' && File::exists($dir . $ObjModel->image)) File::delete($dir . $ObjModel->image); $file = request()->file($filename); $extension = $file->getClientOriginalExtension(); $filename = time().'.'.$extension; $file->move($dir,$filename); $ObjModel->image = $filename; } elseif (request()->remove == 1 && File::exists('uploads/' . $path .'/'. $ObjModel->image)){ File::delete($dir . $ObjModel->image); $ObjModel->image = null; } else { $ObjModel->image = $oldfilename; } } //use with destroy or delete function in controller public static function imageDelete($filename,$ObjModel, $path = null) { $dir = 'uploads/'. $path .'/'; if ($ObjModel->image != '' && File::exists($dir . $ObjModel->image)){ File::delete($dir . $ObjModel->image); } } public static function imageGalleryUpload($filename,$ObjModel, $path = null,$product_id,$fieldID) { if(request()->hasFile($filename)){ $dir = 'uploads/' . $path .'/'; foreach (request()->$filename as $file) { $filename = rand(). '.' . $file->getClientOriginalExtension(); $ObjModel = new $ObjModel; $ObjModel->$fieldID = $product_id; $ObjModel->gallery_image = $filename; if($ObjModel->save()){ $file->move($dir,$filename); } } } } } <file_sep>/app/Traits/UploadScope.php <?php namespace App\Traits; use Illuminate\Http\Request; // use Intervention\Image\Facades\Image; trait UploadScope { protected function uploadImages(Request $request, $image_name) { $image = $request->file($image_name); $image_name = $request->username.'-'.time().'-'.rand() . '.' . $image->getClientOriginalExtension(); $image->move($this->folder_path, $image_name); /* if (config('custom.image_dimensions.'.$this->folder_name.'.main_image')) foreach (config('custom.image_dimensions.'.$this->folder_name.'.main_image') as $dimension) { // open and resize an image file $img = Image::make($this->folder_path.$image_name)->resize($dimension['width'], $dimension['height']); // save the same file as jpeg with default quality $img->save($this->folder_path.$dimension['width'].'_'.$dimension['height'].'_'.$image_name); }*/ return $image_name; } protected function uploadFile(Request $request, $reg_no, $name, $file) { $file = $request->file($file); $file_name = rand(4585, 9857) . '_' . $name . '.' . $file->getClientOriginalExtension(); $file->move($this->folder_path . $reg_no, $file_name); return $file_name; } public function loadImage($image_name, $folder, $dimension = false, $options = []) { if ($image_name) { if (file_exists(public_path() . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . $image_name)) { if ($dimension) { $image_name = $dimension . $image_name; } $img_html = '<img src="' . asset('images/' . $folder . '/' . $image_name) . '" '; if (!empty($options)) { foreach ($options as $key => $option) { $img_html .= $key . '="' . $option . '" '; } } $img_html .= ' />'; return $img_html; } else return '<p>No Image in folder.</p>'; } else return '<p>No Image</p>'; } } <file_sep>/app/Http/Controllers/CheckReferalController.php <?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; class CheckReferalController extends Controller { function check(Request $request) { if($request->get('referal_code')){ $referal_code = $request->get('referal_code'); $data = User::where('referal_code', $referal_code) ->orWhere('phone', $referal_code) ->first(); if($data){ $response = array( 'success' => true, 'data' => $data, 'message' =>'Referal ID is correct', 'type' =>'success' ); } else { $response = array( 'success' => false, 'data' => '', 'message' =>'Referal ID not correct', 'type' =>'error' ); } return $response; } else { $data = User::where('referal_code', '9988776655') ->orWhere('phone', '092374003') ->first(); if($data){ $response = array( 'success' => true, 'data' => $data, 'message' =>'Referal ID is correct', 'type' =>'success' ); } else { $response = array( 'success' => false, 'data' => '', 'message' =>'Referal ID not correct', 'type' =>'error' ); } return $response; } } } <file_sep>/app/Models/Agent.php <?php namespace App\Models; use Spatie\Permission\Traits\HasRoles; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; use Spatie\Activitylog\Traits\LogsActivity; class Agent extends Model { use Notifiable; use HasRoles; use LogsActivity; protected $fillable = [ 'user_id','referal_user_id', 'referal_user_code','level', 'ref_group','ref_level', 'name_en','name_kh', 'job_title','email', 'phone','phone1','phone2', 'facebook','twitter','pinterest','linkedin', 'address','photo','description' ]; public function user(){ return $this->belongsTo(User::class); } } <file_sep>/app/Models/WebmasterSetting.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Spatie\Activitylog\Traits\LogsActivity; class WebmasterSetting extends Model { use LogsActivity; protected $table = 'webmaster_settings'; public function getDescriptionForEvent($eventName) { return __CLASS__ . " model has been {$eventName}"; } } <file_sep>/database/facings.sql -- -------------------------------------------------------- -- Host: 127.0.0.1 -- Server version: 5.7.26 - MySQL Community Server (GPL) -- Server OS: Win64 -- HeidiSQL Version: 11.0.0.5919 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Dumping structure for table thepinrealestate_social_login.facings DROP TABLE IF EXISTS `facings`; CREATE TABLE IF NOT EXISTS `facings` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `facing` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table thepinrealestate_social_login.facings: 8 rows /*!40000 ALTER TABLE `facings` DISABLE KEYS */; INSERT INTO `facings` (`id`, `facing`, `created_at`, `updated_at`) VALUES (1, 'East', '2020-06-20 13:01:27', '2020-06-20 13:01:31'), (2, 'North', '2020-06-20 13:01:27', '2020-06-20 13:01:32'), (3, 'Northeast', '2020-06-20 13:01:28', '2020-06-20 13:01:32'), (4, 'Northwest', '2020-06-20 13:01:28', '2020-06-20 13:01:33'), (5, 'South', '2020-06-20 13:01:29', '2020-06-20 13:01:33'), (6, 'Southeast', '2020-06-20 13:01:30', '2020-06-20 13:01:34'), (7, 'Southwest', '2020-06-20 13:01:30', '2020-06-20 13:01:34'), (8, 'West', '2020-06-20 13:01:31', '2020-06-20 13:01:35'); /*!40000 ALTER TABLE `facings` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; <file_sep>/app/Http/Controllers/Auth/RegisterController.php <?php namespace App\Http\Controllers\Auth; use Auth; use App\Models\User; use App\Models\Agent; use App\Models\Category; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; use Illuminate\Foundation\Auth\RegistersUsers; class RegisterController extends Controller { use RegistersUsers; public function __construct() { $this->middleware('guest'); } public function showRegistrationForm() { $categories = Category::where(['parent_id'=>0])->get(); return view('auth.register',compact('categories')); } protected function validator(array $data) { return Validator::make($data, [ 'name_en' => 'required|string|max:255', 'name_kh' => 'required|string|max:255', 'username' => 'required|string|max:255', 'referal_code' => 'required|max:15', 'referal_user_id' => 'required|max:15', 'referal_user_code' => 'required|max:15', 'phone' => 'required|string|max:255|unique:users,phone', 'email' => 'required|string|email|max:255|unique:users,email', 'password' => '<PASSWORD>', ]); } protected function create(array $data) { $referal_code = $data['referal_code']; $ref_group = User::where('referal_code',$referal_code)->first(); $ref_user_count = Agent::where('referal_user_code',$referal_code)->count(); if($ref_group->ref_group=='OWNER'){ $ref_group_level = 'G1'; } elseif($ref_group->ref_group=='G1'){ $ref_group_level = 'G2'; } elseif($ref_group->ref_group=='G2'){ $ref_group_level = 'G3'; } elseif($ref_group->ref_group=='G3'){ $ref_group_level = 'G4'; } elseif($ref_group->ref_group=='G4'){ $ref_group_level = 'G5'; } $ref_level = $ref_group_level.'-'.'00'.($ref_user_count+1); $user = User::create([ 'name_en' => $data['name_en'], 'name_kh' => $data['name_kh'], 'username' => $data['username'], 'phone' => $data['phone'], 'email' => $data['email'], 'password' => <PASSWORD>($data['password']), 'referal_code' => mt_rand(1000000000,9999999999), 'ref_group' => $ref_group_level, 'ref_level' => $ref_level ]); if($user){ $agent = Agent::create([ 'user_id' => $user->id, 'referal_user_id' => $data['referal_user_id'], 'referal_user_code' => $data['referal_user_code'], 'ref_group' => $ref_group_level, 'ref_level' => $ref_level, 'name_en' => $data['name_en'], 'name_kh' => $data['name_kh'], 'phone' => $data['phone'], 'email' => $data['email'], ]); } $user->assignRole(3); return $user; } protected function redirectTo() { if(Auth::check()){ if(Auth::user()->hasAnyRole(['Super-admin','Administer'])){ $this->redirectTo = route('admin.dashboard'); return $this->redirectTo; } else if(Auth::user()->hasAnyRole(['Agent','Member'])){ $this->redirectTo = route('agent.dashboard'); return $this->redirectTo; } } } } <file_sep>/app/Models/User.php <?php namespace App\Models; // use App\Models\Role; use Spatie\Permission\Traits\HasRoles; use Illuminate\Notifications\Notifiable; use Spatie\Activitylog\Traits\LogsActivity; // use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; use HasRoles; use LogsActivity; protected $guard_name ='web'; protected $fillable = [ 'name_en','name_kh', 'referal_code','ref_group','ref_level', 'username','phone', 'phone1','phone2', 'email', '<PASSWORD>', 'address','location', 'province_id','district_id','commune_id', 'photo','cover_photo' ]; protected $hidden = [ 'password', 'remember_token', ]; public function agent(){ return $this->hasOne(Agent::class); } public function proerties() { return $this->hasMany(Property::class,'id','user_id'); } public function getDescriptionForEvent($eventName) { return __CLASS__ . " model has been {$eventName}"; } } <file_sep>/app/Http/Controllers/Agent/PostController.php <?php namespace App\Http\Controllers\Agent; use App\Models\Commune; use App\Models\Category; use App\Models\District; use App\Models\Operator; use App\Models\Property; use App\Models\Province; use Illuminate\Http\Request; use App\Models\PropertyGallery; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\File; use Intervention\Image\Facades\Image as ImageResize; use Illuminate\Support\Facades\Session; class PostController extends Controller { protected $operator_name1 = ''; protected $operator_name2 = ''; protected $operator_name3 = ''; protected $operator1 = ''; protected $operator2 = ''; protected $operator3 = ''; protected $tmp_path = 'ksupload-tmp'; protected $upload_path = 'uploads'; protected $resizes = [32, 48, 64, 72, 96, 128]; protected $allow_size = (2048 * 1024); protected $allow_file = 'image/jpeg,.jpg,image/gif,.gif,image/png,.png,.jpeg'; protected $limit = 8; public function __construct() { @ini_set('upload_max_filesize', $this->allowsize); } public function getDistrictList(Request $request) { $districts = District::where("province_id",$request->province_id) ->pluck("name_en","id"); return response()->json($districts); } public function getCommuneList(Request $request) { $communes = Commune::where("district_id",$request->district_id) ->pluck("name_en","id"); return response()->json($communes); } public function index() { $categories = Category::where(['parent_id'=>0])->published()->get(); return view('freeads.index',compact('categories')); } public function indexEdit($id) { $categories = Category::where(['parent_id'=>0])->published()->get(); return view('freeads.index',compact('categories')); } public function store(Request $request) { $response = array(); $files = array(); $errors = array(); $file_ini = array(); if(Session::has($this->tmp_path)){ //check max file upload if(count(Session::get($this->tmp_path)) > $this->limit){ return $response = response( array( 'success' => false, 'error' => true, 'message' => 'Limit :'.$this->limit ), 500 ); } } //check user upload file if($request->hasFile('files')){ $files = $request->file('files'); // check max filesize uploads foreach($files as $file){ if($file->getSize() > $this->allow_size){ $response = response( array( 'success' => false, 'error' => true, 'message' => 'File allow size : '.$this->_human_filesize($this->allow_size) ), 500 ); $errors[] = array( 'files' => array( 'name' => $file->getClientOriginalName(), 'type' => $file->getMimeType(), 'size' => $this->_human_filesize($file->getSize()), 'error' => 'File allow size : '.$this->_human_filesize($this->allow_size) ) ); continue; } else { $fileExtension = pathinfo(str_replace('/','.',$file->getMimeType()),PATHINFO_EXTENSION); if(preg_match("/{$fileExtension}/i", $this->allow_file)){ $fileName = $this->generate(8).'_'.$this->generate(15).'_'.$this->generate(19).'_n.'.$fileExtension; // if($file->move(public_path($this->tmp_path), $fileName)){ if($file->move($this->tmp_path, $fileName)){ $file_detail = array( 'name' => $fileName, 'path' => asset($this->tmp_path.'/'.$fileName), 'type' => $fileExtension, // 'size' => File::size(public_path($this->tmp_path).'/'.$fileName) 'size' => File::size($this->tmp_path.'/'.$fileName) ); $file_ini[] = $file_detail; if(Session::has($this->tmp_path)){ Session::push($this->tmp_path,$file_detail); }else{ Session::put($this->tmp_path,$file_ini); } } } } } $response = array( 'success' => true, 'files' => $file_ini, 'errors' => $errors, 'count' => count(session::get($this->tmp_path)), ); if ($request->has('property_id')) { $response['count'] += PropertyGallery::where('property_id', $request->property_id)->count(); } } else { $response = response( array( 'success' => false, 'error' => true, 'message' => 'File allow size : '.$this->_human_filesize($this->allow_size) ), 500 ); } return $response; } public function rotate(Request $request, $id) { $response = array(); if ($request->id) { // rotate image in tmp if (is_file(($this->tmp_path . '/' . $request->id))) { $img = ImageResize::make($this->tmp_path . '/' . $request->id); if ($img->rotate(-90)) { $img->save(); $response = array( 'success' => true, 'message' => 'Rotate successfully.', 'image' => asset($this->tmp_path . '/' . $request->id).'?'.time() ); } } else { // rotate image in table $imgTable = PropertyGallery::findOrFail($id); if (is_file(($this->upload_path . '/property/galleries/' . $imgTable->gallery_image))) { $img = ImageResize::make($this->upload_path . '/property/galleries/' . $imgTable->gallery_image); if ($img->rotate(-90)) { $img->save(); $response = array( 'success' => true, 'message' => 'Rotate successfully.', 'image' => asset($this->upload_path . '/property/galleries/' . $imgTable->gallery_image).'?'.time() ); } } } } return $response; } public function delete(Request $request, $id) { $response = array(); if ($request->id) { if (Session::has($this->tmp_path)) { $get_tmp = Session::get($this->tmp_path); foreach ($get_tmp as $key => $value) { if ($value['name'] === $request->id) { unset($get_tmp[$key]); // if (unlink(public_path($this->tmp_path . '/' . $request->id))) { if (unlink($this->tmp_path . '/' . $request->id)) { Session::put($this->tmp_path, $get_tmp); $response = array( 'success' => true, 'message' => 'Image Delete successfully.', 'errors' => Session::get($this->tmp_path), 'count' => count(Session::get($this->tmp_path)), ); } } } if (!$response) { return $this->delect_gallery_image($id); } } else { return $this->delect_gallery_image($id); } } return $response; } public function delect_gallery_image($id) { $imgTable = PropertyGallery::findOrFail($id); if (is_file($this->upload_path . '/property/galleries/' . $imgTable->gallery_image)) { $delete = PropertyGallery::where('id', $id)->delete(); if ($delete) { unlink($this->upload_path . '/property/galleries/' . $imgTable->gallery_image); return array( 'success' => true, 'message' => 'Image and Data Delete successfully.', 'errors' => null, 'count' => PropertyGallery::where('property_id', $imgTable->property_id)->count(), ); } } } public function create($cate_id) { if(Session::has($this->tmp_path)){ $get_tmp = Session::get($this->tmp_path); foreach ($get_tmp as $value) { @unlink(($this->tmp_path.'/'.$value['name'])); } Session::forget($this->tmp_path); } $data['limit_field'] = $this->limit; $data['upload_url'] = \URL::to('/agent/post/image_upload_tmp'); $data['save_url'] = \URL::to('/agent/post/store'); $data['rotate_url'] = \URL::to('/agent/post/image/rotate').'/'; $data['delete_url'] = \URL::to('/agent/post/image/delete').'/'; $data['allow_size'] = $this->allow_size; $data['provinces'] = Province::pluck('name_en','id'); $data['subcategory'] = Category::where(['id'=>$cate_id])->first(); $data['view_name'] = $data['subcategory']->form_name; $data['category'] = Category::where('id',$data['subcategory']->parent_id)->first(); return view( $data['view_name'].'.create',$data); } public function saveProperties(Request $request) { if (Auth::check()){ $property = new Property(); $status = $request->is_active; $property->user_id = auth()->user()->id; $property->category_id = $request->category_id; $property->parent_id = $request->parent_id; $property->title = $request->title; $property->slug = $this->make_slug($request->title); $property->bedroom = ucwords($request->bedroom); $property->bathroom = ucwords($request->bathroom); $property->facing = $request->facing; $property->size = $request->size; $property->price = $request->price; $property->description = $request->description; $property->name = $request->name; $property->phone1 = $request->phone_1; $property->phone2 = $request->phone_2; $property->phone3 = $request->phone_3; $property->email = $request->email; $property->province_id = $request->province_id; $property->district_id = $request->district_id; $property->commune_id = $request->commune_id; $property->location = $request->location; $property->save_contact = $status; //upload image to property_galleries if($property->save()){ $files = array(); if (!is_dir($this->upload_path)) { mkdir(($this->upload_path),0777,true); } if (!is_dir($this->upload_path .'/property/galleries')) { mkdir($this->upload_path .'/property/galleries',0777,true); } if(Session::has($this->tmp_path)){ $get_tmp = Session::get($this->tmp_path); $i = 0; foreach ($get_tmp as $imagefile) { $PropertyGallery = new PropertyGallery(); $PropertyGallery->property_id = $property->id; $PropertyGallery->gallery_image = $imagefile['name']; $PropertyGallery->save(); if(File::copy($this->tmp_path .'/' .$imagefile['name'], $this->upload_path .'/property/galleries/' .$imagefile['name'])) { $file = array(); $file['original'] = array( 'name' => $imagefile['name'], 'path' => asset($this->upload_path.'/property/galleries/' . $imagefile['name']), 'size' => 'original', ); $files[] = $file; unset($get_tmp[$i]); @unlink(($this->tmp_path.'/'.$imagefile['name'])); } $i++; } $response = array( 'success' => true, 'title' => 'Save Successfully', 'message' => 'Data and Image Save Successfully.', 'files' => $files, 'count' => count(Session::get($this->tmp_path)), 'redirect' => \URL::to('/agent/manage_ads') ); } else { $response = array( 'success' => false, 'error' => true, 'message' => 'No image.', 'count' => count(Session::get($this->tmp_path)), ); } return $response; } } else { return redirect()->route('login'); } } public function editProperties($property_id,$cat_id) { if(Session::has($this->tmp_path)){ $get_tmp = Session::get($this->tmp_path); foreach ($get_tmp as $value) { @unlink(($this->tmp_path.'/'.$value['name'])); } Session::forget($this->tmp_path); } $data['limit_field'] = $this->limit; $data['upload_url'] = \URL::to('/agent/post/image_upload_tmp'); $data['save_url'] = \URL::to('/agent/post/store'); $data['rotate_url'] = \URL::to('/agent/post/image/rotate').'/'; $data['delete_url'] = \URL::to('/agent/post/image/delete').'/'; $data['allow_size'] = $this->allow_size; $data['images'] = Property::gallery($property_id, asset($this->upload_path . '/property/galleries')); $data['count'] = PropertyGallery::where('property_id',$property_id)->count(); $data['property'] =Property::findOrFail($property_id); $data['provinces'] =Province::pluck('name_en','id'); $data['districts'] =District::where('province_id',$data['property']->province_id)->get(); $data['communes'] =Commune::where('district_id',$data['property']->commune->district_id)->get(); $data['subcategory'] =Category::where(['id'=>$cat_id])->first(); $data['view_name'] = $data['subcategory']->form_name; $data['category'] =Category::where('id',$data['property']->category_id)->first(); return view($data['view_name'].'.edit',$data); } public function updateProperties(Request $request, $property_id) { if (Auth::check()){ $status = $request->is_active; $property = Property::findOrFail($property_id); $property->updated_by = auth()->user()->id; $property->category_id = $request->category_id; $property->parent_id = $request->parent_id; $property->title = $request->title; $property->slug = $this->make_slug($request->title); $property->size = $request->size; $property->price = $request->price; $property->description = $request->description; $property->name = $request->name; $property->phone1 = $request->phone_1; $property->phone2 = $request->phone_2; $property->phone3 = $request->phone_3; $property->email = $request->email; $property->province_id = $request->province_id; $property->district_id = $request->district_id; $property->commune_id = $request->commune_id; $property->location = $request->location; $property->bedroom = ucwords($request->bedroom); $property->bathroom = ucwords($request->bathroom); $property->facing = $request->facing; $property->save_contact = $status; if($property->save()){ $files = array(); if (Session::has($this->tmp_path)) { $get_tmp = Session::get($this->tmp_path); $i = 0; foreach ($get_tmp as $imagefile) { $PropertyGallery = new PropertyGallery(); $PropertyGallery->property_id = $property->id; $PropertyGallery->gallery_image = $imagefile['name']; $PropertyGallery->save(); if (File::copy($this->tmp_path . '/' . $imagefile['name'], $this->upload_path . '/property/galleries/' . $imagefile['name'])) { $file = array(); $file['original'] = array( 'name' => $imagefile['name'], 'path' => asset($this->upload_path . '/property/galleries/' . $imagefile['name']), 'size' => 'original', ); $files[] = $file; unset($get_tmp[$i]); @unlink($this->tmp_path . '/' . $imagefile['name']); } $i++; } $response = array( 'success' => true, 'title' => 'Update Successfully', 'message' => 'Data and Image Updated Successfully.', 'files' => $files, 'count' => count(Session::get($this->tmp_path)), 'redirect' => route('agent.dashboard') ); } else { $response = array( 'success' => false, 'error' => true, 'title' => 'Update Successfully', 'message' => 'Only Data has been update!', 'count' => '0', 'redirect' => route('agent.dashboard') ); } return $response; } } else{ return redirect()->route('login'); } } public function deleteProperties(Request $request) { if($request->ajax()){ $property = Property::findOrFail($request->id); $imageGalleries = PropertyGallery::where('property_id',$property->id)->get(); if($property->delete()){ $dir = 'uploads/property/galleries/'; foreach ($imageGalleries as $image) { $image->delete(); File::delete($dir.$image->gallery_image); } } return response(['message'=>'Student Deleated Succeessfully']); } } public function showProperties($slug) { $categories = Category::where(['parent_id'=>0])->published()->get(); $property = Property::where('slug',$slug)->first(); $view_name = $property->parent->form_name; $cellcards = Operator::pluck('cellcard')->toArray(); $smarts = Operator::pluck('smart')->toArray(); $metfones = Operator::pluck('metfone')->toArray(); $qbs = Operator::pluck('qb')->toArray(); $operator1 = substr($property->phone1, 0,3); $operator2 = substr($property->phone2, 0,3); $operator3 = substr($property->phone3, 0,3); $phone1 = $property->phone1; $phone2 = $property->phone2; $phone3 = $property->phone3; if ($property->phone1!='') { $operator1 = substr($property->phone1, 0,3); } else { $operator1=''; } if ($property->phone2!='') { $operator2 = substr($property->phone2, 0,3); } else { $operator2=''; } if ($property->phone3!='') { $operator3 = substr($property->phone3, 0,3); } else { $operator3=''; } if($operator1){ if(in_array($operator1, $cellcards)){ $operator_name1 = 'Cellcard'; } else if(in_array($operator1, $smarts)){ $operator_name1 = 'Smart'; } else if(in_array($operator1, $metfones)){ $operator_name1 = 'Metfone'; } else if(in_array($operator1, $qbs)){ $operator_name1 = 'Qb'; } else { $operator_name1 = 'Other'; } } else { $operator_name1 = ''; } if($operator2){ if(in_array($operator2, $cellcards)){ $operator_name2 = 'Cellcard'; } else if(in_array($operator2, $smarts)){ $operator_name2 = 'Smart'; } else if(in_array($operator2, $metfones)){ $operator_name2 = 'Metfone'; } else if(in_array($operator2, $qbs)){ $operator_name2 = 'Qb'; } else { $operator_name2 = 'Other'; } } else { $operator_name2 = ''; } if($operator3){ if(in_array($operator3, $cellcards)){ $operator_name3 = 'Cellcard'; } else if(in_array($operator3, $smarts)){ $operator_name3 = 'Smart'; } else if(in_array($operator3, $metfones)){ $operator_name3 = 'Metfone'; } else if(in_array($operator3, $qbs)){ $operator_name3 = 'Qb'; } else { $operator_name3 = 'Other'; } } else { $operator_name3 = ''; } $blogKey = 'blog_' .$property->id; if(!Session::has($blogKey)){ $property->increment('view_count'); Session::put($blogKey,1); } $random_properties = Property::inRandomOrder()->take(15)->get(); // return $operator_name3; $images = PropertyGallery::where('property_id',$property->id)->get(); return view($view_name.'.show',compact('property','images','categories','operator_name1','operator_name2','operator_name3','random_properties','phone1','phone2','phone3')); } function make_slug($string) { return preg_replace('/\s+/u', '-', trim($string)); } public static function generate($length = 8) { $chars = "0123456789011121314151617181920"; $str = ''; $size = strlen($chars); for ($i = 0; $i < $length; $i++) { $str .= $chars[rand(0, $size - 1)]; } return $str; } public static function _human_filesize($bytes, $decimals = 2) { $sz = 'BKMGTP'; $factor = floor((strlen($bytes) - 1) / 3); $sz = (@$sz[$factor] == 'B') ? @$sz[$factor]: @$sz[$factor] .'B'; return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) .$sz ; } } <file_sep>/resources/lang/th/passwords.php <?php return array ( 'reset' => 'รีเซ็ตรหัสผ่านของคุณแล้ว!', ); <file_sep>/app/Http/Controllers/Admin/SettingsController.php <?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Models\Setting; class SettingsController extends Controller { public function index(Request $request) { $keyword = $request->get('search'); $perPage = 25; if (!empty($keyword)) { $settings = Setting::where('key', 'LIKE', "%$keyword%") ->orWhere('value', 'LIKE', "%$keyword%") ->orderBy('key')->paginate($perPage); } else { $settings = Setting::orderBy('key')->paginate($perPage); } return view('admin.settings.index', compact('settings')); } public function create() { return view('admin.settings.create'); } public function store(Request $request) { $this->validate( $request, [ 'key' => 'required|string|unique:settings', 'value' => 'required' ] ); $requestData = $request->all(); Setting::create($requestData); return redirect('admin/settings')->with('flash_message', 'Setting added!'); } public function show($id) { $setting = Setting::findOrFail($id); return view('admin.settings.show', compact('setting')); } public function edit($id) { $setting = Setting::findOrFail($id); return view('admin.settings.edit', compact('setting')); } public function update(Request $request, $id) { $this->validate( $request, [ 'key' => 'required|string|unique:settings,key,' . $id, 'value' => 'required' ] ); $requestData = $request->all(); $setting = Setting::findOrFail($id); $setting->update($requestData); return redirect('admin/settings')->with('flash_message', 'Setting updated!'); } public function destroy($id) { Setting::destroy($id); return redirect('admin/settings')->with('flash_message', 'Setting deleted!'); } }
cdcf37d741cdcc14c6f0bc79f9adbb7b8d75a958
[ "JavaScript", "SQL", "PHP" ]
49
PHP
applephagna/thepinrealestate
71c4beeb17a27108d5b9a800274314019cb91db3
030397b311034872b9db80072dfe1becdbd0ef79
refs/heads/master
<file_sep>import time import colorama import sys import os from colorama import Fore, Back, Style colorama.init(autoreset=True) #automaticaly reset colorama original_stdout = sys.stdout n = 1 #setting to 1 # Function for implementing the loading animation def load_animation(): # String to be displayed when the application is loading load_str = "please wait....." ls_len = len(load_str) # String for creating the rotating line animation = "|/-\\" anicount = 0 # used to keep the track of # the duration of animation counttime = 0 # pointer for travelling the loading string i = 0 while (counttime != 40): # used to change the animation speed # smaller the value, faster will be the animation time.sleep(0.075) # converting the string to list # as string is immutable load_str_list = list(load_str) # x->obtaining the ASCII code x = ord(load_str_list[i]) # y->for storing altered ASCII code y = 0 # if the character is "." or " ", keep it unaltered # switch uppercase to lowercase and vice-versa if x != 32 and x != 46: if x>90: y = x-32 else: y = x + 32 load_str_list[i]= chr(y) # for storing the resultant string res ='' for j in range(ls_len): res = res + load_str_list[j] # displaying the resultant string sys.stdout.write("\r"+res + animation[anicount]) sys.stdout.flush() # Assigning loading string # to the resultant string load_str = res anicount = (anicount + 1)% 4 i =(i + 1)% ls_len counttime = counttime + 1 # for windows OS if os.name =="nt": os.system("cls") # for linux / Mac OS else: os.system("clear") # Driver program if __name__ == '__main__': load_animation() print( f"{Fore.GREEN}#####################################################" "\n# #" "\n# Charactors to ASCII decimal and binary #" "\n# #" "\n# Any issues please conatact: #" "\n# #" "\n# <EMAIL> #" #What the software does and contact info "\n# #" "\n# <NAME> #" "\n# 2021 #" "\n#####################################################" ) time.sleep(2) while n == 1: #creating a loop whilst n = 1 char = input("Please enter text: ") #asking user for text to be converted for letter in char: # creating a loop for every charater(s) deciminal = ord(letter) #getting decimal value binary = bin(deciminal) #getting binary value but has b in it a = bin(deciminal) #finding the binary value of the decimal b = bin(deciminal)[2:] #found this to remove b dont know how it works c = b.zfill(8) print() print( "",letter, #print the charactor the user entered. "=", f"{Fore.BLUE}Deciminal:", # printing results in easy to read format deciminal, f"{Fore.MAGENTA}Binary:", c ) print() else: print(f"{Fore.RED}{Back.GREEN}error")
e16149418d8ab0967a843bab7b62353a335c6d43
[ "Python" ]
1
Python
Swimingspud/Convert-text-to-ascii--decimal-and-binary
c3f5a6048bbdada2785ebbb7c204be471dc5bffe
91e3d75d3fa98bbe267bb9ad3bbcbdb439bb1294
refs/heads/master
<file_sep>package ru.timurkasoft.GigaMegaWeather; public interface GMListener { public void run(String temperature); } <file_sep>package ru.timurkasoft.GigaMegaWeather; import android.os.Handler; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class GMModel { private static volatile GMModel gmModel; private GMListener listener; private String city; private String temperature; private String ApiKey = "1d2ad298446fed73b9320707e6cbe1f1"; private static synchronized GMModel get() { if (gmModel == null) { gmModel = new GMModel(); } return gmModel; } public static GMModel city(String city) { get(); gmModel.city = city; return gmModel; } public GMModel listener(GMListener listener) { get(); this.listener = listener; return gmModel; } public void execute() { final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { URL url; HttpURLConnection connection = null; try { url = new URL("http://api.openweathermap.org/data/2.5/weather?q=" + city); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setDoInput(true); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); int i = response.toString().indexOf("\"temp\":"); double d = Double.valueOf(response.toString().substring(i + 7, i + 7 + 6)) - 273.15; d = (double) (Math.round(d * 10)) / 10; Thread.sleep(1000); temperature = String.valueOf(d); if (obtainListener != null) handler.post(obtainListener); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) connection.disconnect(); } } }).start(); } private Runnable obtainListener = new Runnable() { @Override public void run() { listener.run(temperature); } }; } <file_sep># GigaMegaWeather Use MVC Pattern to Android Application Example.
8d70268a56421359e1aa5e3dd531fcfdce42f164
[ "Markdown", "Java" ]
3
Java
TuMoH/GigaMegaWeather
f186ae85d6c23f2de405d673dcac1d167677da23
b3519bdbb14e680354bbcaca89787b39244bfcec
refs/heads/master
<repo_name>jeromepin/hexcat<file_sep>/pkg/hexcat/line.go package hexcat import ( "strings" ) type HexcatLine struct { bytes []*HexcatByte } func (line *HexcatLine) appendByte(hexcatByte *HexcatByte) { line.bytes = append(line.bytes, hexcatByte) } func (line *HexcatLine) toHexString() string { var bytes []string for index := 0; index < len(line.bytes); index++ { bytes = append(bytes, line.bytes[index].colorize()+line.bytes[index].hexValue) } bytes = append(bytes, "\033[0m") return strings.Join(bytes, " ") } func (line *HexcatLine) toHumanString() string { var chars []string for index := 0; index < len(line.bytes); index++ { b := line.bytes[index] chars = append(chars, b.colorize()+b.print()) } chars = append(chars, "\033[0m") return strings.Join(chars, "") } <file_sep>/Makefile GOCMD=go GOBUILD=$(GOCMD) build GOINSTALL=$(GOCMD) install GOCLEAN=$(GOCMD) clean GOTEST=$(GOCMD) test BINARY_NAME=hexcat all: install build: $(GOBUILD) -v install: $(GOINSTALL) -v . .PHONY: test test: $(GOTEST) -v ./pkg/... .PHONY: windows windows: mkdir -p release GOOS=windows GOARCH=amd64 go build -o release/$(BINARY)-v1.0.0-windows-amd64 .PHONY: linux linux: mkdir -p release GOOS=linux GOARCH=amd64 go build -o release/$(BINARY)-v1.0.0-linux-amd64 .PHONY: darwin darwin: mkdir -p release GOOS=darwin GOARCH=amd64 go build -o release/$(BINARY)-v1.0.0-darwin-amd64 .PHONY: release release: windows linux darwin .PHONY: lint lint: gometalinter -j 1 --vendor --exclude=libexec ./... clean: # $(GOCLEAN) rm -f $(GOPATH)/bin/$(BINARY_NAME) <file_sep>/pkg/hexcat/hexcat.go package hexcat import ( "github.com/olekukonko/tablewriter" "io/ioutil" "os" "strconv" ) type Options struct { Colors bool Bytes int File os.File } func check(e error) { if e != nil { panic(e) } } func Run(path string, options *Options) []HexcatLine { file, err := os.Open(path) check(err) stat, err := file.Stat() check(err) fileSize := stat.Size() bytes, err := ioutil.ReadFile(path) check(err) var lines []HexcatLine hexcatLine := HexcatLine{} for seekIndex, element := range bytes { hexcatByte := newHexcatByte(element) // Last byte if seekIndex == int(fileSize)-1 { hexcatLine.appendByte(hexcatByte) lines = append(lines, hexcatLine) } else { if seekIndex > 0 && seekIndex%options.Bytes == 0 { lines = append(lines, hexcatLine) hexcatLine = HexcatLine{} } hexcatLine.appendByte(hexcatByte) } } return lines } func Render(lines []HexcatLine, options *Options) { table := tablewriter.NewWriter(os.Stdout) table.SetAutoWrapText(false) table.SetColumnAlignment([]int{tablewriter.ALIGN_RIGHT, tablewriter.ALIGN_LEFT, tablewriter.ALIGN_LEFT}) var line int for _, element := range lines { table.Append([]string{string(strconv.FormatInt(int64(line), 16)), element.toHexString(), element.toHumanString()}) line = line + options.Bytes } table.Render() } <file_sep>/pkg/hexcat/byte.go package hexcat import ( "encoding/hex" "strings" ) type HexcatByte struct { value int // Decimal representation hexValue string // Hexadecimal representation as a string } func newHexcatByte(seekedByte byte) *HexcatByte { hexcatByte := HexcatByte{} hexcatByte.value = int(seekedByte) hexcatByte.hexValue = hex.EncodeToString([]byte{seekedByte}) return &hexcatByte } func contains(a []int, x int) bool { for _, n := range a { if x == n { return true } } return false } func (b *HexcatByte) isSpace() bool { var SPACE = []int{8, 9, 10, 11, 12, 13, 32} return contains(SPACE, b.value) } func (b *HexcatByte) isPrintable() bool { var PRINTABLE_CHAR = []int{33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126} return contains(PRINTABLE_CHAR, b.value) } func (b *HexcatByte) isControlCode() bool { var CONTROL_CODE = []int{0, 1, 2, 3, 4, 5, 6, 7, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31} return contains(CONTROL_CODE, b.value) } func (b *HexcatByte) colorize() string { if b.isControlCode() { return "\033[1;30m" } else if b.isSpace() { return "\033[0;31m" } else if b.isPrintable() { return "\033[0;32m" } else { return "\033[0;33m" } return "" } func (b *HexcatByte) print() string { str := string(b.value) if b.isControlCode() { str = "•" } else if b.isSpace() || b.isPrintable() { m := make(map[string]string) m["\b"] = "_" m["\t"] = "_" m["\n"] = "_" m["\v"] = "_" m["\f"] = "_" m["\r"] = "_" for k, v := range m { str = strings.Replace(str, k, v, -1) } } else { str = "×" } return str } <file_sep>/README.md Small and badly-written hexadecimal file viewer to discover Golang. ![Screenshot](screenshot.png) Inspired shamelessly from [sharkdp/hexyl](https://github.com/sharkdp/hexyl). <file_sep>/pkg/hexcat/byte_test.go package hexcat import ( "testing" ) func TestIsSpace(t *testing.T) { testCase := []struct { name string input byte expect bool }{ {name: "1", input: 8, expect: true}, {name: "2", input: 13, expect: true}, {name: "3", input: 14, expect: false}, {name: "4", input: 32, expect: true}, {name: "5", input: 120, expect: false}, } for _, test := range testCase { t.Run(test.name, func(t *testing.T) { hexcatByte := newHexcatByte(test.input) output := hexcatByte.isSpace() if output != test.expect { t.Errorf("output %t want %t", output, test.expect) } }) } } <file_sep>/hexcat.go package main import ( "fmt" "github.com/akamensky/argparse" "github.com/jeromepin/hexcat/pkg/hexcat" "os" ) func main() { parser := argparse.NewParser("Hexcat", "Make a hexdump with syntaxic coloration") colors := parser.Flag("c", "colors", &argparse.Options{Required: false, Help: "Whether to print with colors", Default: true}) bytesPerLine := parser.Int("b", "bytes", &argparse.Options{Required: false, Help: "Bytes per lines", Default: 16}) file := parser.File("f", "file", os.O_RDONLY, 0600, &argparse.Options{Required: false, Help: "File"}) err := parser.Parse(os.Args) if err != nil { fmt.Print(parser.Usage(err)) } opts := &hexcat.Options{ Colors: *colors, Bytes: *bytesPerLine, File: *file, } lines := hexcat.Run(file.Name(), opts) hexcat.Render(lines, opts) }
50c3bb0c0a485944e09418968165c09f4852376b
[ "Makefile", "Go", "Markdown" ]
7
Go
jeromepin/hexcat
d74d7c66306aa1cd0dbfa8b914f5e2a38c8bdd9d
96608242508cd0794c5b81937a8e640ad87bc2da
refs/heads/master
<repo_name>bmoliveira/rx-activity<file_sep>/example/build.gradle apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' ext.errorbar = '0.3.0' android { compileSdkVersion versions.sdk.target buildToolsVersion versions.buildTools defaultConfig { applicationId 'com.example.rxactivity' versionName versions.release minSdkVersion versions.sdk.min targetSdkVersion versions.sdk.target } sourceSets { main.manifest.srcFile 'AndroidManifest.xml' main.java.srcDirs 'src' main.res.srcDirs 'res' main.resources.srcDir 'src' } buildTypes { debug { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$versions.kotlin.stdlib" compile "org.jetbrains.anko:anko-commons:$versions.kotlin.anko" compile project(':rx-activity') compile "io.reactivex.rxjava2:rxkotlin:$versions.rxjava" compile "com.hendraanggrian:errorbar:$errorbar" }<file_sep>/rx-activity/src/com/hendraanggrian/rx/activity/ActivityResultException.kt @file:Suppress("UNUSED") package com.hendraanggrian.rx.activity /** * @author <NAME> (<EMAIL>) */ open class ActivityResultException : Exception { val requestCode: Int constructor(resultCode: Int) { this.requestCode = resultCode } constructor(resultCode: Int, name: String) : super(name) { this.requestCode = resultCode } }<file_sep>/example/src/com/example/rxactivity/NextActivity.kt package com.example.rxactivity import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.MenuItem import android.view.View import com.hendraanggrian.kota.app.finishWithResult import kotlinx.android.synthetic.main.activity_next.* /** * @author <NAME> (<EMAIL>) */ class NextActivity : AppCompatActivity(), View.OnClickListener { companion object { const val RESULT_CUSTOM = 9152 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_next) setSupportActionBar(toolbar) buttonOk.setOnClickListener(this) buttonCanceled.setOnClickListener(this) buttonCustom.setOnClickListener(this) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() } return super.onOptionsItemSelected(item) } override fun onClick(v: View) = finishWithResult(when (v) { buttonOk -> RESULT_OK buttonCanceled -> RESULT_CANCELED else -> RESULT_CUSTOM }, Intent()) }<file_sep>/rx-activity/src/com/hendraanggrian/rx/activity/RxActivity.kt @file:JvmName("RxActivity") @file:Suppress("NOTHING_TO_INLINE", "UNUSED") package com.hendraanggrian.rx.activity import android.annotation.SuppressLint import android.annotation.TargetApi import android.app.Activity import android.app.Fragment import android.content.Intent import android.os.Bundle import android.support.annotation.RequiresApi import com.hendraanggrian.kota.collection.containsKey import com.hendraanggrian.rx.activity.internal.ActivityResultEmitter import com.hendraanggrian.rx.activity.internal.QUEUES import com.hendraanggrian.rx.activity.internal.createActivityResultObservables import io.reactivex.Observable inline fun notifyRxActivity(requestCode: Int, resultCode: Int, data: Intent?) { if (QUEUES.containsKey(requestCode)) { val e = QUEUES.get(requestCode) as ActivityResultEmitter if (!e.isDisposed) { if (e.resultCode == resultCode) { e.onNext(data!!) } else { e.onError(ActivityResultException(requestCode, "Activity with request code $requestCode fails expected result code check.")) } e.onComplete() } QUEUES.remove(requestCode) } } @JvmOverloads inline fun Activity.startActivityForResultAsObservable(intent: Intent, result: Int = Activity.RESULT_OK): Observable<Intent> { return createActivityResultObservables(result, { requestCode -> startActivityForResult(intent, requestCode) }) } @RequiresApi(16) @TargetApi(16) @JvmOverloads inline fun Activity.startActivityForResultAsObservable(intent: Intent, options: Bundle?, result: Int = Activity.RESULT_OK): Observable<Intent> { return createActivityResultObservables(result, { requestCode -> startActivityForResult(intent, requestCode, options) }) } @JvmOverloads inline fun Fragment.startActivityForResultAsObservable(intent: Intent, result: Int = Activity.RESULT_OK): Observable<Intent> { return createActivityResultObservables(result, { requestCode -> activity.startActivityForResult(intent, requestCode) }) } @RequiresApi(16) @TargetApi(16) @JvmOverloads inline fun Fragment.startActivityForResultAsObservable(intent: Intent, options: Bundle?, result: Int = Activity.RESULT_OK): Observable<Intent> { return createActivityResultObservables(result, { requestCode -> activity.startActivityForResult(intent, requestCode, options) }) } @JvmOverloads inline fun android.support.v4.app.Fragment.startActivityForResultAsObservable(intent: Intent, result: Int = Activity.RESULT_OK): Observable<Intent> { return createActivityResultObservables(result, { requestCode -> activity.startActivityForResult(intent, requestCode) }) } @SuppressLint("RestrictedApi") @RequiresApi(16) @TargetApi(16) @JvmOverloads inline fun android.support.v4.app.Fragment.startActivityForResultAsObservable(intent: Intent, options: Bundle?, result: Int = Activity.RESULT_OK): Observable<Intent> { return createActivityResultObservables(result, { requestCode -> activity.startActivityForResult(intent, requestCode, options) }) } <file_sep>/settings.gradle include ':rx-activity' include ':example'<file_sep>/rx-activity/src/com/hendraanggrian/rx/activity/internal/ActivityResultEmitter.kt package com.hendraanggrian.rx.activity.internal import android.content.Intent import io.reactivex.ObservableEmitter /** * @author <NAME> (<EMAIL>) */ interface ActivityResultEmitter : ObservableEmitter<Intent> { /** * Ensure that Observable will only emits if result code match. */ val resultCode: Int }<file_sep>/rx-activity/build.gradle apply plugin: 'com.android.library' apply plugin: 'kotlin-android' apply plugin: 'com.novoda.bintray-release' apply from: 'https://raw.githubusercontent.com/HendraAnggrian/hendraanggrian.github.io/master/bintray.gradle' android { compileSdkVersion versions.sdk.target buildToolsVersion versions.buildTools defaultConfig { minSdkVersion versions.sdk.min targetSdkVersion versions.sdk.target } sourceSets { main.manifest.srcFile 'AndroidManifest.xml' main.java.srcDirs 'src' } } dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$versions.kotlin.stdlib" compile "io.reactivex.rxjava2:rxjava:$versions.rxjava" compile "com.android.support:support-fragment:$versions.support" compile "com.hendraanggrian:kota:$versions.kota" } publish { userOrg = bintray.user groupId = bintray.group artifactId = bintray.artifact.rx_activity.id publishVersion = versions.release desc = bintray.artifact.rx_activity.desc website = bintray.artifact.rx_activity.website }<file_sep>/example/src/com/example/rxactivity/MainActivity.kt package com.example.rxactivity import android.content.Intent import android.os.Bundle import android.support.design.widget.errorbar import android.support.v7.app.AppCompatActivity import com.hendraanggrian.rx.activity.notifyRxActivity import com.hendraanggrian.rx.activity.startActivityForResultAsObservable import io.reactivex.rxkotlin.subscribeBy import kotlinx.android.synthetic.main.activity_main.* /** * @author <NAME> (<EMAIL>) */ class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) supportFragmentManager .beginTransaction() .add(R.id.fragmentContent, MainFragment()) .commit() activityButton.setOnClickListener { startActivityForResultAsObservable(Intent(this, NextActivity::class.java)) .subscribeBy( onNext = { _ -> errorbar(activityButton, "onNext", android.R.string.ok, {}) }, onError = { e -> errorbar(activityButton, "onError: ${e.message}", android.R.string.ok, {}) }) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) notifyRxActivity(requestCode, resultCode, data) } }<file_sep>/rx-activity/src/com/hendraanggrian/rx/activity/internal/ActivityResultEmitterImpl.kt package com.hendraanggrian.rx.activity.internal import android.content.Intent import io.reactivex.ObservableEmitter import io.reactivex.disposables.Disposable import io.reactivex.functions.Cancellable /** * @author <NAME> (<EMAIL>) */ class ActivityResultEmitterImpl( override val resultCode: Int, val e: ObservableEmitter<Intent> ) : ActivityResultEmitter { override fun onNext(value: Intent) = e.onNext(value) override fun onError(error: Throwable) = e.onError(error) override fun setCancellable(c: Cancellable?) = e.setCancellable(c) override fun onComplete() = e.onComplete() override fun isDisposed() = e.isDisposed override fun setDisposable(d: Disposable?) = e.setDisposable(d) override fun serialize() = e.serialize() }<file_sep>/example/src/com/example/rxactivity/MainFragment.kt package com.example.rxactivity import android.content.Intent import android.os.Bundle import android.support.design.widget.errorbar import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.hendraanggrian.rx.activity.startActivityForResultAsObservable import io.reactivex.rxkotlin.subscribeBy import kotlinx.android.synthetic.main.fragment_main.* class MainFragment: Fragment() { override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_main, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) fragmentButton.setOnClickListener { startActivityForResultAsObservable(Intent(activity, NextActivity::class.java)) .subscribeBy( onNext = { _ -> errorbar(fragmentButton, "onNext", android.R.string.ok, {}) }, onError = { e -> errorbar(fragmentButton, "onError: ${e.message}", android.R.string.ok, {}) }) } } } <file_sep>/build.gradle buildscript { ext.versions = [ // android sdk : [ min : 14, target: 26, ], buildTools: '26.0.0', // main kotlin : [ stdlib: '1.1.3-2', anko : '0.10.1' ], support : '26.0.0', rxjava : '2.1.0', kota : '0.6.0', release : '0.7' ] repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$versions.kotlin.stdlib" classpath 'com.novoda:bintray-release:0.5.0' } } allprojects { repositories { maven { url 'https://maven.google.com' } jcenter() } tasks.withType(Javadoc) { excludes = ['**/*.kt'] } } task clean(type: Delete) { delete rootProject.buildDir } /** QUICK LINT CHECK BEFORE UPLOAD ./gradlew rx-activity:clean rx-activity:build ./gradlew rx-activity:bintrayUpload -PdryRun=false -PbintrayUser=hendraanggrian -PbintrayKey= */<file_sep>/README.md RxActivity ========== Reactive streams to start activity for result. ```java RxActivity.startForResult(activity, new Intent(Intent.ACTION_GET_CONTENT).setType("image/*")) .subscribe(result -> { if (result.resultCode == Activity.RESULT_OK) { Intent data = result.data; Uri uri = data.getData(); imageView.setImageUri(uri); } }); ``` Usage ----- `RxActivity` is usable in Activity, Fragment and support Fragment once `onActivityResult` is overriden. ```java @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); RxActivity.onActivityResult(requestCode, resultCode, data); } ``` #### Start activity for OK result Start activity that only emits `Intent` result if result code is `Activity.RESULT_OK`. Will throw `ActivityCanceledException` if the result code is `Activity.RESULT_CANCELED`, and `ActivityNotFoundException` if no activity can handle intent input. ```java RxActivity.startForOk(activity, intent) .subscribe(data -> { // result code is Activity.RESULT_OK // proceed to handle activity result }, throwable -> { // result code is Activity.RESULT_CANCELED }); ``` #### Start activity for any result Start actvity that emits `ActivityResult`, which is a tuple of request code, result code, and `Intent` result. Will only throw `ActivityNotFoundException` if no activity can handle intent input. ```java RxActivity.startForAny(activity, intent) .subscribe(activityResult -> { // int requestCode = activityResult.requestCode; int resultCode = activityResult.resultCode; Intent data = activityResult.data; // TODO: use fields }); ``` Download -------- ```gradle repositories { maven { url 'https://maven.google.com' } jcenter() } dependencies { compile 'com.hendraanggrian:rx-activity:0.5' } ``` License ------- Copyright 2017 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. <file_sep>/rx-activity/src/com/hendraanggrian/rx/activity/internal/RxActivityInternal.kt @file:Suppress("NOTHING_TO_INLINE") package com.hendraanggrian.rx.activity.internal import android.content.Intent import android.support.annotation.RestrictTo import android.util.SparseArray import com.hendraanggrian.kota.collection.containsKey import io.reactivex.Observable import java.lang.ref.WeakReference import java.util.* /** * Max range of request code to pass [android.support.v4.app.FragmentActivity.checkForValidRequestCode] precondition. */ const val MAX_REQUEST_CODE = 65535 // 16-bit int /** * Weak reference of Random to generate random number * below [MAX_REQUEST_CODE] * and not already queued in [QUEUES]. */ var RANDOM: WeakReference<Random>? = null /** * Collection of reactive emitters that will emits one-by-one on activity result. * Once emitted, emitter will no longer exists in this collection. */ val QUEUES = SparseArray<ActivityResultEmitter>() @RestrictTo(RestrictTo.Scope.LIBRARY) inline fun createActivityResultObservables(result: Int, noinline activityStarter: (Int) -> Unit) = Observable.create<Intent> { e -> // attempt to get Random instance from WeakReference // when no instance is found, create a new one and save it // at this point instance can be ensured not null var random: Random? if (RANDOM == null) { RANDOM = WeakReference(Random()) } random = RANDOM!!.get() if (random == null) { random = Random() RANDOM = WeakReference(random) } // endless loop until generated request code is unique var requestCode: Int do { requestCode = random.nextInt(MAX_REQUEST_CODE) } while (QUEUES.containsKey(requestCode)) QUEUES.append(requestCode, ActivityResultEmitterImpl(result, e)) activityStarter.invoke(requestCode) }!!
39ce5c99ab149a228c4ead31b295390e94e290e5
[ "Markdown", "Kotlin", "Gradle" ]
13
Gradle
bmoliveira/rx-activity
60c80e32837535cca26717120b6a5af0d5b66791
37e4c52ede7b17d08f33d0859c04724b251df266
refs/heads/master
<file_sep>PageTitle=JSF - Exercise (alternative 1) Header=Web Development Frameworks: Java Server Faces SubHeader=Exercise Alternative 1 CopyrightAuthor=<NAME>\u00E9rez CopyrightYear=2017 LabelAlumnInformation=Student Information LabelUsername=Username LabelDegree=Degree LabelEndYear=End year LabelBirthDate=Birth date Submit=Send SearchResult=Form parameters InputUsernameValidatorMessage=Mandatoy field with at leat 8 characters. InputDegreeValidatorMessage=Mandatory field.<file_sep>package beans; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Optional; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.faces.context.FacesContext; import javax.faces.event.ValueChangeEvent; import javax.inject.Named; import models.Language; @Named @RequestScoped public class BeanLanguage implements Serializable { /** * Serial Version UID */ private static final long serialVersionUID = -2653791053727152497L; private List<Language> languages = new ArrayList<>(); private String selectedShortCode; private Locale locale; public BeanLanguage() { } @PostConstruct public void init() { languages.add(new Language("es", "Español")); languages.add(new Language("en", "English")); locale = FacesContext.getCurrentInstance().getApplication().getDefaultLocale(); initselectedShortCode(); } public List<Language> getLanguages() { return languages; } public String getselectedShortCode() { return selectedShortCode; } public void setSelectedShortCode(String selectedShortCode) { this.selectedShortCode = selectedShortCode; } public Locale getLocale() { return locale; } private void setLocale(String shortCode) { this.locale = new Locale(shortCode); } public void onChangeLanguage(ValueChangeEvent e) { String shortCode = (String) e.getNewValue(); setLocale(shortCode); } private void initselectedShortCode() { String defaultShortCode = locale.getLanguage(); Optional<Language> defaultLanguage = languages.stream().filter(x -> x.getShortCode() == defaultShortCode) .map(Optional::ofNullable).findFirst().orElse(null); if (defaultLanguage.isPresent()) { setSelectedShortCode(defaultLanguage.get().getShortCode()); } } }<file_sep>package beans; import java.io.Serializable; import javax.enterprise.context.RequestScoped; import javax.inject.Named; import models.StudentSearch; @Named @RequestScoped public class BeanSearch implements Serializable { private StudentSearch studentSearch; /** * Serial Version UID */ private static final long serialVersionUID = 2999588664902139092L; public StudentSearch getStudentSearch() { return studentSearch; } public void setStudentSearch(StudentSearch studentSearch) { this.studentSearch = studentSearch; } public String search(StudentSearch studentSearch) { this.studentSearch = studentSearch; return "searchResult"; } } <file_sep>PageTitle=JSF - Ejercicio (alternativa 1) Header=Frameworks de desarrollo web\: Java Server Faces SubHeader=Ejercicio Alternativa 1 CopyrightAuthor=<NAME>\u00E9rez CopyrightYear=2017 LabelAlumnInformation=Informaci\u00F3n del alumno LabelUsername=Nombre de usuario LabelDegree=Titulaci\u00F3n LabelEndYear=A\u00F1o de finalizaci\u00F3n LabelBirthDate=Fecha de nacimiento Submit=Enviar SearchResult=Par\u00E1metros del formulario InputUsernameValidatorMessage=Campo obligatorio con un m\u00EDnimo de 8 caracteres. InputDegreeValidatorMessage=Campo obligatorio.<file_sep>package models; import java.io.Serializable; public class Language implements Serializable { /** * Serial Version UID */ private static final long serialVersionUID = -942670318316956297L; private String shortCode; private String name; public Language() { } public Language(String shortCode, String name) { setShortCode(shortCode); setName(name); } public String getShortCode() { return shortCode; } public void setShortCode(String shortCode) { this.shortCode = shortCode; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
ab239fa986c25062813789a60a5e48cc8d45bc55
[ "Java", "INI" ]
5
INI
deidigitalis/us-mits-daw-jsf
2bb4e367365c3bab09f3759be09d485d9890feef
26026389e97bce588e2f13a3fd2455ff43a9273e
refs/heads/master
<repo_name>lanjuere/my-project-angular<file_sep>/README.md # my-project-angular [Edit on StackBlitz ⚡️](https://stackblitz.com/edit/my-project-angular)<file_sep>/src/worker/counter-worker/counter.worker.ts import { WorkerMessage } from './shared/worker-message.model'; import { WORKER_COMMAND} from './shared/worker-command.constants'; export class AppWorkers { workerCtx: any; created: Date; counter: number; state : string; STATE_ENUM = { RUNNING : "RUNNING", STOPPED : "STOPPED", PAUSED : "PAUSED" }; constructor(workerCtx: any) { this.workerCtx = workerCtx; this.created = new Date(); this.counter = 0; this.state = this.STATE_ENUM.STOPPED; } workerBroker($event: MessageEvent): void { const { topic, data } = $event.data as WorkerMessage; const workerMessage = new WorkerMessage(topic, data); switch (topic) { case WORKER_COMMAND.PLAY: this.run(workerMessage); break; case WORKER_COMMAND.PAUSE: this.state = this.STATE_ENUM.PAUSED; break; case WORKER_COMMAND.RESUME: this.state = this.STATE_ENUM.RUNNING; break; case WORKER_COMMAND.STOP: this.state = this.STATE_ENUM.STOPPED; break; case WORKER_COMMAND.VALUE: this.returnCounter(workerMessage); break; default: // Add support for more workers here console.error('Topic Does Not Match'); } }; run(workerMessage: WorkerMessage){ while(true){ if(this.state == this.STATE_ENUM.STOPPED) { break; } if(this.state == this.STATE_ENUM.PAUSED) { continue; } this.returnCounter(workerMessage); } } returnCounter(workerMessage : WorkerMessage){ this.returnWorkResults(new WorkerMessage(workerMessage.topic, this.counter++)); } /** * Posts results back through to the worker * @param {WorkerMessage} message */ private returnWorkResults(message: WorkerMessage): void { this.workerCtx.postMessage(message); } }<file_sep>/src/annotations/cache.annotation.ts import {Observable,AsyncSubject} from "rxjs"; // Define a function with one parameter: the key under which the data will be cached export function CacheReturnValue(key: string) { // Return our high-order function let observers = {}; let results = {}; let TIMEOUT_KEY = "TIMEOUT_KEY"; return function(target, methodName, descriptor) { // Keep the method store in a local variable let originalMethod = descriptor.value; // Redefine the method value with our own descriptor.value = function(...args) { let self = this; // Execute the method with its initial context and arguments // Return value is stored into a variable instead of being passed to the execution stack let result = JSON.parse(sessionStorage.getItem(key)); if(!observers[key]){ console.log("oserver : ", observers[key]); observers[key] = new AsyncSubject<any>(); <Observable<any>>originalMethod.apply(self, args).subscribe(function(res){ results[key] = res; sessionStorage.setItem(key,JSON.stringify(res)); setTimeout(()=>{ observers[key].next(res); observers[key].complete(); },JSON.parse(sessionStorage.getItem(TIMEOUT_KEY)) ); }); } // Return back the value to the execution stack return observers[key]; }; // Return the descriptorwith the altered value return descriptor; }; };<file_sep>/src/worker/counter-worker/shared/worker-command.constants.ts export const WORKER_COMMAND = { STOP : 'STOP', RESUME :'RESUME', PLAY : 'PLAY', VALUE : 'VALUE', PAUSE : 'PAUSE' };<file_sep>/src/app/app.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import {CacheReturnValue} from '../annotations/cache.annotation'; import { Observable} from 'rxjs'; @Injectable({ providedIn: 'root', }) export class AppService { constructor(private httpClient: HttpClient) {} @CacheReturnValue("key") getValue():Observable<any>{ return this.httpClient.get<any>('https://opendata.paris.fr/api/records/1.0/search/?dataset=velib-disponibilite-en-temps-reel&facet=overflowactivation&facet=creditcard&facet=kioskstate&facet=station_state'); } }<file_sep>/src/app/app.component.ts import { Component } from '@angular/core'; import { AppService } from './app.service'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { name = 'Angular'; results = []; timeout; TIMEOUT_KEY = "TIMEOUT_KEY"; constructor(private appService: AppService) { } callApi(number){ var i = 0; this.results = [] for(i = 0; i< number; i++){ this.appService.getValue().subscribe((result)=>{ this.results.push(result); }); } } changeTimeout(){ sessionStorage.setItem(this.TIMEOUT_KEY,JSON.stringify(this.timeout)); } clearCacheAndReload(){ sessionStorage.clear(); document.location.reload(true); } }
b48cc8cba1db1074279b9688d7ae759f023e38a0
[ "Markdown", "TypeScript" ]
6
Markdown
lanjuere/my-project-angular
47fbccabff8f7f2f6b48d9026185fd475b7d14c8
935814d55b074b0fdd9b043190d65b5f8a73158d
refs/heads/master
<file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //import RecallAndPrecision.BM25; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; import util.TopScoreDocs; /** * * @author bili */ public class Main { public static void main(String[] args) throws CorruptIndexException, IOException { SpellChecking checker = new SpellChecking("spellChecker"); String indexDir = "indexDir"; String docs = "docs"; // String query = "KENNEDY ADMINISTRATION PRESSURE ON NGO DINH DIEM TO STOP SUPPRESSING THE BUDDHISTS"; //// String query = "EFFORTS OF AMBASSADOR <NAME> LODGE TO GET VIET NAM'S PRESIDENT DIEM TO CHANGE HIS POLICIES OF POLITICAL REPRESSION"; //// String query = "viet"; // String field = "contents"; // String stopwordsFile = "time.stop"; // Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36); // StopWordList swl = new StopWordList(name); Directory dir = FSDirectory.open(new File(indexDir)); IndexReader indexReader = IndexReader.open(dir); BM25 bm25 = new BM25(indexReader, docs); if (args.length == 2) { TopScoreDocs score = bm25.score(args[0]); String hitsContent = score.allHits(); System.out.println(score.allHits()); // output to a file File file = new File(args[1] + ".txt"); FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(hitsContent); bw.close(); System.out.println("Done"); } // run ControlView controlView = new ControlView(bm25); } } <file_sep> /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * * @author bili */ public class RelevantList { public List<String> queries; public RelevantList(String name) throws FileNotFoundException { queries = this.importWordList(name); } private List<String> importWordList(String name) throws FileNotFoundException { List<String> wordList = new ArrayList<String>(); Scanner in = new Scanner(new File(name)); String line = ""; while (in.hasNext()) { line = in.nextLine(); if (!line.equals("")) { // System.out.println(line); String[] words = line.split(" "); line = ""; for(int i =1; i<words.length; i++) { // System.out.print(words[1]+ " "); // System.out.println(words[1]); if(!words[i].equals("")) line+=words[i]+" "; } // System.out.println(); wordList.add(line); } } return wordList; } public List<String> getQueries() { return queries; } public static void main(String[] args) throws FileNotFoundException { RelevantList qList = new RelevantList("time.rel"); List<String> q = qList.getQueries(); for(String s : q){ // System.out.println(s.charAt(s.length()-1)); System.out.println(s); } // System.out.println(q.size()); // String s = "1 268 288 304 308 323 326 334"; // String[] ss = s.split(" "); // for(int i = 0; i<ss.length; i++) { // System.out.println(ss[i]); // } } }<file_sep>Search-Engine ============= Search Engine based on BM25 model This serach engine based on BM25 Okapi model famous model use for google search Engine as well. programming language used in this model is JAVA, LUCENE libraries are use in this Search model. <file_sep> //import RecallAndPrecision.StopWordList; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.LimitTokenCountAnalyzer; //import org.apache.lucene.analysis.snowball.SnowballAnalyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author binh */ public class Indexing { private IndexWriter writer; public Indexing(String indexDir) throws IOException { Directory dir = FSDirectory.open(new File(indexDir)); String name = "time.stop"; StopWordList swl = new StopWordList(name); Set<String> words = swl.getWords(); Analyzer stdAn = new StandardAnalyzer(Version.LUCENE_36, words); // Analyzer stdAn = new SnowballAnalyzer(Version.LUCENE_36, "English", words); // Analyzer ltcAn = new LimitTokenCountAnalyzer(stdAn,Integer.MAX_VALUE); IndexWriterConfig iwConf = new IndexWriterConfig(Version.LUCENE_36,stdAn); iwConf.setOpenMode(IndexWriterConfig.OpenMode.CREATE); writer = new IndexWriter(dir, iwConf); } public void close() throws IOException { writer.close(); } public int index(String dataDir, FileFilter filter) throws Exception { File[] files = new File(dataDir).listFiles(); for (File f: files) { if (!f.isDirectory() && !f.isHidden() && f.exists() && f.canRead() && (filter == null || filter.accept(f))) { indexFile(f); } } return writer.numDocs(); // return number of docs indexed } private void indexFile(File f) throws Exception { System.out.println("Indexing "+ f.getCanonicalPath()); Document doc = getDocument(f); writer.addDocument(doc); } private static class TextFilesFilter implements FileFilter{ public boolean accept(File path) { return path.getName().toLowerCase().endsWith(""); } } protected Document getDocument(File f) throws Exception { Document doc = new Document(); doc.add(new Field("contents", new FileReader(f),Field.TermVector.WITH_POSITIONS_OFFSETS)); FileReader fr = new FileReader(f); // fr. // doc.add(new Field("text", new FileReader(f),Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("filename", f.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("fullpath", f.getCanonicalPath(), Field.Store.YES, Field.Index.NOT_ANALYZED)); // doc.add(new Field("wordlength", fileWordLength(f), Field.Store.YES, Field.Index.NOT_ANALYZED)); return doc; } private String fileWordLength(File file) throws IOException{ int l = 0; String line =""; try { BufferedReader in = new BufferedReader(new FileReader(file.getCanonicalPath())); while((line=in.readLine())!=null) { l+=line.split((" ")).length; } } catch (FileNotFoundException ex) { Logger.getLogger(Indexing.class.getName()).log(Level.SEVERE, null, ex); } return l+""; } public static void main(String[] args) throws Exception{ String indexDir = "indexDir"; String dataDir = "docs"; long start = System.currentTimeMillis(); int numIndexed; Indexing indexer = new Indexing(indexDir); try{ numIndexed = indexer.index(dataDir, new TextFilesFilter()); } finally{ indexer.close(); } long end = System.currentTimeMillis(); System.out.println("Indexing " + numIndexed + " files took " + (end - start) + "milliseconds"); } } <file_sep> /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.StringReader; import java.util.Collections; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermDocs; import org.apache.lucene.index.TermFreqVector; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; import snippets.ReadTextFile; import snippets.SentenceProcessor; import snippets.SnippetGenerator; import util.DocumentScorePair; import util.OrderByScore; import util.TopScoreDocs; /** * * @author bili */ public class BM25 { private IndexReader indexReader; public int nD; private String indexDir; public double averageDocLength = 0; public String query = ""; public TopScoreDocs scores; private StopWordList swl = new StopWordList("time.stop"); // public BM25(IndexReader indexReader) throws CorruptIndexException, IOException { // this.indexReader = indexReader; // indexDir = indexReader. // nD = indexReader.maxDoc(); // this.avgDocLength(indexDir); // } public BM25(IndexReader indexReader, String dir) throws CorruptIndexException, IOException { this.indexReader = indexReader; nD = indexReader.maxDoc(); indexDir = dir; scores = new TopScoreDocs(); avgDocLength(indexDir); } /* * Return number of docs in the collections */ // public int getND() throws IOException { // return indexReader.maxDoc(); // // } /* * REturn the number of doc containt term tm */ public int docsContainTerm(Term tm) throws IOException { TermDocs termDocs = indexReader.termDocs(tm); int count = 0; // System.out.println(termDocs.) while (termDocs.next()) { // System.out.println("doc() "+termDocs.doc()); // System.out.println("freq() "+termDocs.freq()); // count += termDocs.freq(); if (indexReader.docFreq(tm) != 0) { count++; } } // System.out.println("count "+count); return count; } public double calIDF(Term term) throws IOException { int nq = docsContainTerm(term); // System.out.println("nq " +nq); // System.out.println(nD-nq+0.5); // getND(); return Math.log((nD - nq + 0.5) / (nq + 0.5)); } public String getContent(String filename) throws IOException { String ans = ""; // BufferedReader br = new BufferedReader(new FileReader(indexDir + "/" + filename)); // String currentLine; // // while ((currentLine = br.readLine()) != null) { // // ans += currentLine + " "; // } // ans = ReadTextFile.readTextFile(new File(filename)); // filename = "docs/"+filename; try { String string = ReadTextFile.readTextFile(new File(indexDir + "/" + filename)); String[] sens = SentenceProcessor.process(string); for (int i = 0; i < sens.length; i++) { // System.out.println(sens[i]); // System.out.println("**********************"); ans += sens[i]; } } catch (Exception e) { } return ans; } public String htmlGetContent(String filename, String query) throws IOException { query = query.toLowerCase(); String ans = getContent(filename); String[] terms = query.split(" "); for (int i = 0; i < terms.length; i++) { if (!swl.getWords().contains(terms[i])) { // System.out.println(terms[i]); ans = ans.replaceAll(" " + terms[i] + " ", " <b style=\"color:blue\">" + terms[i] + "</b> "); } } return ans; } public String htmlString(String str, String word) { word = word.toLowerCase(); String[] words = word.split(" "); // System.out.println(str); for (int i = 0; i < words.length; i++) { if (!swl.getWords().contains(words[i])) { str = str.replaceAll(" " + words[i] + " ", " <b style=\"color:blue\">" + words[i] + "</b> "); } } return str; } public int docLength(String filename) throws IOException { int length = 0; // indexReader. TermFreqVector t = indexReader.getTermFreqVector(0, "contents"); for (int i = 0; i < t.getTermFrequencies().length; i++) { // System.out.println("t "+t.getTermFrequencies()[i]); length += t.getTermFrequencies()[i]; } return length; } public int docLength(int id) throws IOException { int length = 0; // indexReader. TermFreqVector t = indexReader.getTermFreqVector(id, "contents"); // System.out.println("size "+t.size()); // for(int i =0; i<t.size();i++){ // System.out.println("t "+t.getTerms()[i]); // } for (int i = 0; i < t.getTermFrequencies().length; i++) { // System.out.println("t "+t.getTermFrequencies()[i]); length += t.getTermFrequencies()[i]; } return length; } public String[] listOfDocNames(String dir) throws IOException { File f = new File(dir); // String[] fileInDir = f.listFiles(); File[] listFiles = f.listFiles(); String[] names = new String[listFiles.length]; for (int i = 0; i < listFiles.length; i++) { // names[i] = listFiles[i].getCanonicalPath(); names[i] = listFiles[i].getName(); } return names; } public int getID(String dir, String docName) throws CorruptIndexException, IOException { File f = new File(dir); // String[] fileInDir = f.listFiles(); File[] listFiles = f.listFiles(); String[] names = new String[listFiles.length]; for (int i = 0; i < listFiles.length; i++) { // System.out.println(getDocID(i)); if (docName.equals(listFiles[i].getName())) { return i; } } return -1; } public double avgDocLength(String dir) throws CorruptIndexException, IOException { double length = 0.0; String[] files = listOfDocNames(dir); for (int i = 0; i < files.length; i++) { length += docLength(getID(dir, files[i])); } averageDocLength = length / files.length; return length / files.length; } public String getDocID(int docId) throws CorruptIndexException, IOException { indexReader.numDocs(); IndexSearcher searcher = new IndexSearcher(indexReader); // searcher. Document document = searcher.doc(docId); return document.get("filename"); } public int tf(Term tm, String docName) throws IOException { TermDocs termDocs = indexReader.termDocs(tm); while (termDocs.next()) { Document doc = indexReader.document(termDocs.doc()); if (doc.get("filename").equals(docName)) { // System.out.println("doc() " + termDocs.doc()); // System.out.println("freq() " + termDocs.freq()); return termDocs.freq(); } } return 0; } public double part2(Term term, String docName) throws IOException { int tf = tf(term, docName); // System.out.println(tf); final double k1 = 1.2; final double b = 0.75; double avg = this.averageDocLength; int docLength = this.docLength(this.getID(indexDir, docName)); // double up = tf * (k1 + 1); double up = tf; double down = tf + k1 * (1 - b + (b * docLength) / avg); // double down = tf + k1 * (1 - b + (b * docLength) / avg); // System.out.println(up+ " "+down); return up / down; } public TopScoreDocs score(String current) throws FileNotFoundException, CorruptIndexException, IOException { this.query = current; current = current.toLowerCase(); int numDoc = indexReader.maxDoc(); String field = "contents"; scores = new TopScoreDocs(); // QueryList qList = new QueryList("time.queries"); // query = qList.queries.get(82); // System.out.println(current); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36, swl.getWords()); for (int i = 0; i < numDoc; i++) { // for (int j = 0; j < qList.queries.size(); j++) { Document document = indexReader.document(i); double score = 0.0; TokenStream stream = analyzer.tokenStream(field, new StringReader(current)); if (stream != null) { // OffsetAttribute offsetAttribute = stream.getAttribute(OffsetAttribute.class); CharTermAttribute charTermAttribute = stream.getAttribute(CharTermAttribute.class); while (stream.incrementToken()) { // int startOffset = offsetAttribute.startOffset(); // int endOffset = offsetAttribute.endOffset(); String term = charTermAttribute.toString(); Term tm = new Term(field, term); score += this.calIDF(new Term(field, term)) * this.part2(tm, document.get("filename")); } } if (score > 0.0) { scores.add(new DocumentScorePair(document.get("filename"), score)); } } Collections.sort(scores.getList(), new OrderByScore()); return scores; } /* * Method to get content of the snippets */ public String getSnippets(String query, String docID) throws IOException, Exception { String ans = ""; // String content = this.getContent(docID); // String[] terms = query.toLowerCase().split(" "); // for (int i = 0; i < terms.length; i++) { //// System.out.println(content.indexOf(terms[i])); // if (!swl.getWords().contains(terms[i])) { // int index = content.indexOf(terms[i]); // if (index != -1) { //// System.out.println("index " + index); // try { // for (i = index; i < (index + 156); i++) { // // System.out.print(content.charAt(i)); // ans += content.charAt(i); // // } // } catch (StringIndexOutOfBoundsException e) { // } // } // } // } ans = SnippetGenerator.generate(docID, query); return ans; } // public void setQuery(String current) { // query = current; // } public static void main(String[] args) throws CorruptIndexException, IOException { if (args.length == 0) { System.out.println("No Command Line arguments"); } else if (args.length == 2) { String indexDir = "indexDir"; String docs = "docs"; // String query = "KENNEDY ADMINISTRATION PRESSURE ON NGO DINH DIEM TO STOP SUPPRESSING THE BUDDHISTS"; //// String query = "EFFORTS OF AMBASSADOR <NAME> LODGE TO GET VIET NAM'S PRESIDENT DIEM TO CHANGE HIS POLICIES OF POLITICAL REPRESSION"; //// String query = "viet"; // String s = "diem (capricorn), and after what the u.s . officially called his \" brutal \" crackdown on the buddhists, washington obviously could not string along with him"; Directory dir = FSDirectory.open(new File(indexDir)); IndexReader indexReader = IndexReader.open(dir); // BM25 bm25 = new BM25(indexReader, docs); TopScoreDocs score = bm25.score(args[0]); String hitsContent = score.allHits(); System.out.println(score.allHits()); // output to a file File file = new File(args[1] + ".txt"); FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(hitsContent); bw.close(); System.out.println("Done"); } else { System.out.println("Unknown parameters. Enter a query and a filename for ouput"); } // System.out.println(bm25.htmlString(s, "diem")); // bm25.score("KENNEDY ADMINISTRATION PRESSURE ON NGO DINH DIEM TO STOP SUPPRESSING THE BUDDHISTS"); // bm25.scores.top(10); // System.out.println(bm25.getContent("171")); // System.out.println(bm25.htmlGetContent("171", query.toLowerCase())); } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //import RecallAndPrecision.BM25; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.text.html.HTMLEditorKit; import org.apache.lucene.index.CorruptIndexException; import util.DocumentScorePair; import util.TopScoreDocs; /** * * @author bili */ public class ControlView extends JFrame { private void resAll() { searchPane.revalidate(); fullView.revalidate(); bottomPane.revalidate();; leftPane.revalidate(); this.validate(); } private BM25 bm25; // model private SearchPanel searchPane; private OnePage leftPane; private FullView fullView; private int currentClick = 0; private BottomPane bottomPane; // private SpellChecking spellChecker; private CheckerSuggestion checkSuggestions; public ControlView(BM25 bm25) throws IOException { this.bm25 = bm25; // spellChecker = new SpellChecking("spellChecker"); checkSuggestions = new CheckerSuggestion("spellChecker"); bottomPane = new BottomPane(); searchPane = new SearchPanel(); leftPane = new OnePage(); // leftPane.d // leftPane.setPreferredSize(new Dimension(10, 100)); // leftPane.setBorder(BorderFactory.createLineBorder(Color.MAGENTA)); fullView = new FullView(" "); setLayout(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // frame.getContentPane().add(hit); // frame.add(hit); //Set up the content pane. //Use the content pane's default BorderLayout. No need for //setLayout(new BorderLayout()); //Display the window. this.setPreferredSize(new Dimension(900, 600)); this.pack(); this.setVisible(true); } private void setLayout() { Container pane = this.getContentPane(); pane.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.gridx = 0; c.gridwidth = 2; c.gridy = 0; // c.weighty = 0.5; pane.add(searchPane, c); c.fill = GridBagConstraints.BOTH; //// c.ipady = 40; //make this component tall // c.weightx = 1.0; // c.weighty = 1.0; // c.gridwidth = 1; // c.gridx = 0; // c.gridy = 1; // c.ipady = 80; //make this component tall c.weighty = 1.0; // c.weighty = 1.0; c.gridx = 0; c.gridwidth = 1; c.gridy = 1; pane.add(leftPane, c); c.fill = GridBagConstraints.BOTH; c.weighty = 1.0; c.gridx = 1; c.gridwidth = 1; c.gridy = 1; pane.add(fullView, c); c.fill = GridBagConstraints.HORIZONTAL; c.ipady = 0; //reset c.weighty = 0.0; c.gridx = 0; c.gridwidth = 2; c.gridy = 2; pane.add(bottomPane, c); } // for right panel to display full document private class FullView extends JPanel { JTextPane textPane = new JTextPane(); // private String content; // a html style string private JScrollPane scrollPane; JTextArea textArea = new JTextArea(6, 20); public FullView(String content) { // if(content.equals("")) { // padded(); // } // txt = new JTextPane(); // this.content = content; textPane.setEditorKit(new HTMLEditorKit()); textArea = new JTextArea(); textArea.setEnabled(false); textArea.setEditable(false); textArea.setText(content); textArea.setEnabled(false); textArea.setEditable(false); textPane.setText(textArea.getText()); textPane.setEditable(false); scrollPane = new JScrollPane(textPane); this.setLayout(new BorderLayout()); this.add(scrollPane, BorderLayout.CENTER); // setBorder(BorderFactory.createLineBorder(Color.ORANGE)); } public void set(String newContent) { // if(newContent.equals("")){ // padded(); // } textArea.setText(newContent); textPane.setText(textArea.getText()); this.revalidate(); } // private void padded() { // textArea.setText((" ")); // } } private class SearchPanel extends JPanel implements ItemListener { JCheckBox spellOn; JButton search; public JTextField searchBox; private JPanel top; // private JPanel bottom; public CheckerSuggestion checkSuggestions; private SearchPanel() throws IOException { this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); spellOn = new JCheckBox(); spellOn.setSelected(true); top = new JPanel(); checkSuggestions = new CheckerSuggestion("spellChecker"); // bottom.add(new JTextArea("Did you mean:")); search = new JButton("Search"); searchBox = new JTextField(30); search.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Execute when button is pressed String query = searchBox.getText(); try { checkSuggestions.check(query); checkSuggestions.revalidate(); // leftPane.revalidate(); // checkSuggestions.refreshPane(); } catch (IOException ex) { Logger.getLogger(ControlView.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Query: " + query); try { fullView.set(""); currentClick = 0; TopScoreDocs score = bm25.score(query); try { // addLeftPane(); leftPane.addTopScoreDoc(score); } catch (Exception ex) { Logger.getLogger(ControlView.class.getName()).log(Level.SEVERE, null, ex); } score.top(10); } catch (FileNotFoundException ex) { } catch (CorruptIndexException ex) { } catch (IOException ex) { } } }); // spellOn.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent e) { // System.out.println(e.paramString()); //// if(spellOn.get) // spellOn.setSelected(false); // // } // }); spellOn.addItemListener(this); top.add(searchBox); top.add(search); top.add(spellOn); top.add(new JLabel("Spell checker on")); this.add(top); this.add(checkSuggestions); // setBorder(BorderFactory.createLineBorder(Color.ORANGE)); } @Override public void itemStateChanged(ItemEvent itemEvent) { // AbstractButton abstractButton = (AbstractButton) itemEvent.getSource(); int state = itemEvent.getStateChange(); if (state == ItemEvent.SELECTED) { // this.add(bottom); checkSuggestions.setVisible(true); this.revalidate(); } else if (state == ItemEvent.DESELECTED) { // this.add(bottom); checkSuggestions.setVisible(false); this.revalidate(); } } } // inner class for the left pane to display serach result public class OnePage extends JPanel { private class OneHit extends JPanel { // private String displayHTML; private String title; private String content; private HtmlPane contentArea; private HtmlPane titleField; public OneHit(String title, final String content) { // super(); this.title = title; this.content = content; contentArea = new HtmlPane(content, false); contentArea.setEditable(false); titleField = new HtmlPane(title, true); this.setLayout(new BorderLayout()); this.add(titleField, BorderLayout.PAGE_START); this.add(contentArea, BorderLayout.CENTER); // this.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY)); } // private HTML } private List<OneHit> hitList; private int Result_per_page = 7; private JPanel body; // private int currentClick = 0; private OnePage(List<OneHit> hitList) { this.hitList = hitList; this.setLayout(new BorderLayout()); // this.add(body, BorderLayout.CENTER); this.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); disStuff(); } private OnePage() { this.hitList = new ArrayList<OneHit>(); this.setLayout(new BorderLayout()); // this.add(body, BorderLayout.CENTER); this.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); disStuff(); } // private void disStuff() { //// if(hitList>) // for (int i = 0; i < 5; i++) { // this.add(hitList.get(i)); // } // this.validate(); // } private void disStuff() { // this.revalidate(); try { this.remove(body); }catch(NullPointerException e){} // System.out.println("no of hits " +hitList.size()); if ((Result_per_page * currentClick + Result_per_page) < hitList.size()) { // System.out.println("IF"); // try { //// System.out.println("body is "+body); //// if(body!=null) { //// body.setVisible(false); //// body.revalidate(); //// } // } catch (NullPointerException e) { // } // body = new JPanel(); // body.setBorder(BorderFactory.createLineBorder(Color.GREEN)); body.setLayout(new BoxLayout(body, BoxLayout.PAGE_AXIS)); for (int i = Result_per_page * currentClick; i < Result_per_page * currentClick + Result_per_page; i++) { body.add(hitList.get(i)); } body.revalidate(); this.add(body, BorderLayout.CENTER); // this.add(body); this.revalidate(); } else if (Result_per_page * currentClick < hitList.size()) { // System.out.println("ELSE"); // this.remove(body); // this.revalidate(); int newEnd = (Result_per_page * currentClick + Result_per_page) - hitList.size(); // body.setVisible(false); body = new JPanel(); // body.setBorder(BorderFactory.createLineBorder(Color.GREEN)); body.setLayout(new BoxLayout(body, BoxLayout.PAGE_AXIS)); for (int i = Result_per_page * currentClick; i < Result_per_page * currentClick + Result_per_page - newEnd; i++) { body.add(hitList.get(i)); } body.revalidate(); this.add(body, BorderLayout.CENTER); // this.add(body); this.revalidate(); } // this.validate(); // this.repaint(); // this.revalidate(); } public void addTopScoreDoc(TopScoreDocs tops) throws IOException, Exception { // for(OneHit one: hitList) { // Container parent = one.getParent(); // try { this.remove(body); this.revalidate(); // body.setVisible(false); body.revalidate(); this.revalidate(); // body.validate(); // body.repaint(); } catch (NullPointerException e) { this.revalidate(); } // one.setVisible(false); this.hitList.clear(); List<DocumentScorePair> list = tops.getList(); for (DocumentScorePair d : list) { // String s = "" + d.score; String s = bm25.getSnippets(searchPane.searchBox.getText(), d.name); String ss = " "+s; //dirty hack... // System.out.println("s "+s); ss= bm25.htmlString(ss, searchPane.searchBox.getText()); hitList.add(new OneHit(d.name, ss)); } disStuff(); this.revalidate(); } } public class BottomPane extends JPanel { private JButton next, previous; public BottomPane() { next = new JButton("Next"); previous = new JButton("Previous"); next.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (leftPane.hitList.size() > 0 && currentClick * leftPane.Result_per_page + leftPane.Result_per_page < leftPane.hitList.size()) { currentClick++; } fullView.set((" ")); System.out.println(currentClick); leftPane.disStuff(); } }); previous.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (currentClick > 0 && (leftPane.hitList.size() > 0)) { currentClick--; } fullView.set((" ")); System.out.println(currentClick); leftPane.disStuff(); } }); this.add(previous); this.add(next); } } public class HtmlPane extends JTextPane { private JTextArea textArea; private String content; // a html style string private String displayUnderline; // private JScrollPane scrollPane ; private MyAdapter myadapter; public HtmlPane(String text, boolean on) { this.setEditorKit(new HTMLEditorKit()); textArea = new JTextArea(6, 20); this.content = text; textArea.setEditable(false); textArea.setText(underLineTitle()); this.setText(content); if (on) { this.setText(underLineTitle()); myadapter = new MyAdapter(); this.addMouseListener(new MyAdapter()); } } private String underLineTitle() { displayUnderline = "<u>" + content + "</u>"; return displayUnderline; } // public void dis() { // this.removeMouseListener(myadapter); // this.validate(); // } public class MyAdapter extends MouseAdapter { @Override public void mousePressed(MouseEvent event) { try { // System.out.println("prsssed"); // System.out.println(bm25.getContent(content)); // fullView.set(bm25.getContent(content)); fullView.set(bm25.htmlGetContent(content, searchPane.searchBox.getText())); // fullView = new FullView(bm25.getContent(content)); } catch (IOException ex) { // Logger.getLogger(ControlView.class.getName()).log(Level.SEVERE, null, ex); } } } public HtmlPane(boolean on) { this.content = ""; this.setEditorKit(new HTMLEditorKit()); this.setText(content); if (on) { this.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent event) { try { // System.out.println("prsssed"); // System.out.println(bm25.getContent(content)); fullView.set(bm25.getContent(content)); // fullView = new FullView(bm25.getContent(content)); } catch (IOException ex) { // Logger.getLogger(ControlView.class.getName()).log(Level.SEVERE, null, ex); } } }); } } public void set(String content) { this.content = content; this.setEditorKit(new HTMLEditorKit()); this.setText(content); this.revalidate(); } } private class CheckerSuggestion extends JPanel { public SpellChecking checker; private JPanel con; private boolean reset = false; String[] suggests_; // Integer tmp ; public CheckerSuggestion(String dicDir) throws IOException { // setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); con = new JPanel(); // con.setBorder(BorderFactory.createLineBorder(Color.RED)); checker = new SpellChecking(dicDir); // con.add(new JLabel("Did you mean:")); this.add(con); } public void check(String word) throws IOException { word = word.toLowerCase(); suggests_ = checker.suggests(word); // con = new JPanel(); try { this.remove(con); con = new JPanel(); this.add(con); } catch(NullPointerException e) {} if (suggests_.length>1) { con.add(new JLabel("Did you mean:")); con.revalidate(); } for (int i = 0; i < suggests_.length; i++) { final Integer tmp = new Integer(i); final JLabel label = new JLabel("<html><u>" + suggests_[i] + "</u></html>"); // label.addMouseListener(this); // label.setFont(new Font("Serif", Font.BOLD, 24)); label.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { refreshPane(); // searchPane.searchBox.setText(suggests_[tmp.intValue()]); try { fullView.set(""); currentClick = 0; TopScoreDocs score = bm25.score(searchPane.searchBox.getText()); try { // addLeftPane(); // leftPane =new OnePage(); leftPane.addTopScoreDoc(score); } catch (Exception ex) { Logger.getLogger(ControlView.class.getName()).log(Level.SEVERE, null, ex); } score.top(10); leftPane.revalidate(); } catch (FileNotFoundException ex) { } catch (CorruptIndexException ex) { } catch (IOException ex) { } } }); // System.out.println("MEMMEMEMME2"); con.add(label); } this.revalidate(); } public void refreshPane() { // System.out.println("refreshing"); try{ this.remove(con); }catch (NullPointerException e){} // con = new JPanel(); // con.setBorder(BorderFactory.createLineBorder(Color.pink)); // this.add(con); this.revalidate(); } } }
92ade894f54fdeb78cfb7b003af57b606357ef4a
[ "Markdown", "Java" ]
6
Java
Arshadkhan75/Search-Engine
511d801ab99f8a98f856e954292b7a74205e3e42
47ecf98051e29a16fb0012afbc330acf86bceae4
refs/heads/master
<file_sep># Mailbox Mailbox for codepath Submitted by: <NAME> ## Project Requirements * [x] On dragging the message left... * [x] On dragging the message right... * [x] Optional: Panning from the edge should reveal the menu * [x] Optional: If the menu is being revealed when the user lifts their finger, it should continue revealing. * [x] Optional: If the menu is being hidden when the user lifts their finger, it should continue hiding. * [ ] Optional: Tapping on compose should animate to reveal the compose view. * [ ] Optional: Tapping the segmented control in the title should swipe views in from the left or right. * [ ] Optional: Shake to undo. Here's walkthrough demos of implemented user stories: <img src='/mailbox.gif' title='Video Walkthrough' width='' alt='Video Walkthrough' /> <img src='/mailbox-menu.gif' title='Video Walkthrough' width='' alt='Video Walkthrough' /> GIF created with [LiceCap](http://www.cockos.com/licecap/). ## License Copyright [2016] [<NAME>] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. <file_sep>// // MailboxViewController.swift // Mailbox // // Created by <NAME> on 2/20/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class MailboxViewController: UIViewController { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var feedImage: UIImageView! @IBOutlet weak var groupView: UIView! @IBOutlet weak var messageView: UIImageView! @IBOutlet weak var archiveView: UIImageView! @IBOutlet weak var laterView: UIImageView! @IBOutlet weak var listView: UIImageView! @IBOutlet weak var listActionsVIew: UIImageView! @IBOutlet weak var deleteView: UIImageView! @IBOutlet weak var rescheduleView: UIImageView! @IBOutlet weak var menuView: UIImageView! @IBOutlet weak var inboxView: UIView! var messageOriginalX : CGFloat! var archiveOriginalX : CGFloat! var laterOriginalX : CGFloat! var deleteOriginalX : CGFloat! var listOriginalX : CGFloat! var inboxOriginalX : CGFloat! // bg view colors let gray = UIColor(red: 191/255, green: 191/255, blue: 191/255, alpha: 1) let yellow = UIColor(red: 255/255, green: 210/255, blue: 33/255, alpha: 1) let brown = UIColor(red: 216/255.0, green: 165/255.0, blue: 117/255.0, alpha: 1.0) let green = UIColor(red: 98/255, green: 217/255, blue: 98/255, alpha: 1) let red = UIColor(red: 238/255, green: 84/255, blue: 13/255, alpha: 1) override func viewDidLoad() { super.viewDidLoad() scrollView.contentSize = CGSize(width: 320, height: 1281) archiveView.alpha = 0 laterView.alpha = 0 deleteView.alpha = 0 listView.alpha = 0 rescheduleView.alpha = 0 listActionsVIew.alpha = 0 var edgeGesture = UIScreenEdgePanGestureRecognizer(target: self, action: "didPanMenu:") edgeGesture.edges = UIRectEdge.Left inboxView.addGestureRecognizer(edgeGesture) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func didPanMessage(sender: UIPanGestureRecognizer) { let translation = sender.translationInView(view) if sender.state == UIGestureRecognizerState.Began { messageOriginalX = messageView.frame.origin.x archiveOriginalX = archiveView.frame.origin.x laterOriginalX = laterView.frame.origin.x deleteOriginalX = deleteView.frame.origin.x listOriginalX = listView.frame.origin.x laterView.alpha = 0.5 archiveView.alpha = 0.5 deleteView.alpha = 0 listView.alpha = 0 } else if sender.state == UIGestureRecognizerState.Changed { messageView.frame.origin.x = messageOriginalX + translation.x switch translation.x{ case -60...(0): groupView.backgroundColor = gray UIView.animateWithDuration(1.2, animations: { () -> Void in self.laterView.alpha = 1 }) case -260...(-61): groupView.backgroundColor = yellow archiveView.alpha = 0 laterView.alpha = 1 laterView.frame.origin.x = laterOriginalX + translation.x + 65 case -320...(-261): groupView.backgroundColor = brown laterView.alpha = 0 listView.alpha = 1 listView.frame.origin.x = listOriginalX + translation.x + 260 case 1...60: groupView.backgroundColor = gray UIView.animateWithDuration(1, animations: { self.archiveView.alpha = 1 }) case 61...260: groupView.backgroundColor = green archiveView.alpha = 1 archiveView.frame.origin.x = archiveOriginalX + translation.x - 65 case 261...320: groupView.backgroundColor = red laterView.alpha = 0 archiveView.alpha = 0 deleteView.alpha = 1 deleteView.frame.origin.x = deleteOriginalX + translation.x - 270 default: groupView.backgroundColor = gray } } else if sender.state == UIGestureRecognizerState.Ended { switch translation.x{ case -60...(0): UIView.animateWithDuration(0.5, animations: { () -> Void in self.messageView.frame.origin.x = self.messageOriginalX }) laterView.alpha = 0.5 case -260...(-61): UIView.animateWithDuration(0.2, animations: { () -> Void in self.messageView.frame.origin.x = -320 self.laterView.frame.origin.x = 10 self.archiveView.alpha = 0 self.laterView.alpha = 0 }, completion: { (Bool) -> Void in self.rescheduleView.alpha = 1 }) laterView.frame.origin.x = laterOriginalX case -320...(-261): UIView.animateWithDuration(0.2, animations: { () -> Void in self.messageView.frame.origin.x = -320 self.listView.frame.origin.x = 10 self.archiveView.alpha = 0 }, completion: { (Bool) -> Void in self.listActionsVIew.alpha = 1 }) listView.alpha = 0 laterView.frame.origin.x = laterOriginalX listView.frame.origin.x = listOriginalX case 1...60: UIView.animateWithDuration(0.5, animations: { () -> Void in self.messageView.frame.origin.x = self.messageOriginalX }) case 61...260: UIView.animateWithDuration(0.3, animations: { () -> Void in self.messageView.frame.origin.x = 320 self.archiveView.frame.origin.x = 290 self.archiveView.alpha = 0 }) UIView.animateWithDuration(0.3, animations: { () -> Void in self.feedImage.frame.origin.y = self.feedImage.frame.origin.y - self.messageView.frame.height }, completion: { (Bool) -> Void in self.messageView.frame.origin.x = 0 self.feedImage.frame.origin.y = self.feedImage.frame.origin.y + self.messageView.frame.height }) archiveView.frame.origin.x = archiveOriginalX case 261...320: UIView.animateWithDuration(0.3, animations: { () -> Void in self.messageView.frame.origin.x = 320 self.deleteView.frame.origin.x = 290 self.laterView.alpha = 0 self.deleteView.alpha = 0 }) UIView.animateWithDuration(0.3, animations: { () -> Void in self.feedImage.frame.origin.y = self.feedImage.frame.origin.y - self.messageView.frame.height }, completion: { (Bool) -> Void in self.messageView.frame.origin.x = 0 self.feedImage.frame.origin.y = self.feedImage.frame.origin.y + self.messageView.frame.height }) archiveView.frame.origin.x = archiveOriginalX deleteView.frame.origin.x = deleteOriginalX default: groupView.backgroundColor = gray } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ @IBAction func onTapReschedule(sender: AnyObject) { rescheduleView.alpha = 0 // UIView.animateWithDuration(0.4) { () -> Void in // self.feedImage.frame.origin.y = self.feedImage.frame.origin.y - self.messageView.frame.height // } UIView.animateWithDuration(0.5, animations: { () -> Void in self.feedImage.frame.origin.y = self.feedImage.frame.origin.y - self.messageView.frame.height }, completion: { (Bool) -> Void in self.messageView.frame.origin.x = 0 self.feedImage.frame.origin.y = self.feedImage.frame.origin.y + self.messageView.frame.height }) } @IBAction func onTapListActions(sender: AnyObject) { listActionsVIew.alpha = 0 UIView.animateWithDuration(0.5, animations: { () -> Void in self.feedImage.frame.origin.y = self.feedImage.frame.origin.y - self.messageView.frame.height }, completion: { (Bool) -> Void in self.messageView.frame.origin.x = 0 self.feedImage.frame.origin.y = self.feedImage.frame.origin.y + self.messageView.frame.height }) } @IBAction func didPanMenu(sender: UIScreenEdgePanGestureRecognizer) { let translation = sender.translationInView(view) if sender.state == UIGestureRecognizerState.Began { inboxOriginalX = inboxView.frame.origin.x } else if sender.state == UIGestureRecognizerState.Changed { UIView.animateWithDuration(0.3, animations: { () -> Void in self.inboxView.frame.origin.x = self.inboxOriginalX + translation.x }) // UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options:[] , animations: { () -> Void in // self.inboxView.frame.origin.x = self.inboxOriginalX // }, completion: { (Bool) -> Void in // }) } else if sender.state == UIGestureRecognizerState.Ended { switch translation.x { case 160...320: UIView.animateWithDuration(0.6, animations: { () -> Void in self.inboxView.frame.origin.x = self.inboxOriginalX + 320 }) // UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options:[] , animations: { () -> Void in // self.inboxView.frame.origin.x = self.inboxOriginalX + 320 // }, completion: { (Bool) -> Void in // }) case 0...159: // UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options:[] , animations: { () -> Void in // self.inboxView.frame.origin.x = self.inboxOriginalX // }, completion: { (Bool) -> Void in // }) UIView.animateWithDuration(0.3, animations: { () -> Void in self.inboxView.frame.origin.x = self.inboxOriginalX }) default: self.inboxView.frame.origin.x = 0 } } } }
85e72719bb81f84e20e123b82e21766064df728c
[ "Markdown", "Swift" ]
2
Markdown
dnedkova/Mailbox
6813c37dff957ba1dd98bf5ccd0b80f960f72654
e543967903d8f870c53cf2687fb435397c267837
refs/heads/master
<repo_name>m-isaksson84/if<file_sep>/if/Program.cs using System; namespace test { class Program { static void Main(string[] args) { Console.WriteLine("Skriv ditt namn"); string name = Console.ReadLine(); Console.WriteLine("Ditt namn är satt som " + name + " tryck ENTER för att fortsätta"); Console.ReadLine(); Console.Clear(); Console.WriteLine("Du går ut ur ditt hus på väg till skolan klockan 07:00, väljer du att ta SJ eller SL? (SJ/SL)"); string ans1 = Console.ReadLine(); Console.ReadLine(); if (ans1 == "SJ") { Console.Clear(); Console.WriteLine("du kommer 4 timmar sent eftersom SJ suger. Försök igen."); Console.ReadLine(); Console.Clear(); } else if (ans1 == "SL") { Console.Clear(); Console.WriteLine("Du valde rätt! SL fungerar till skillnad från SJ. Du är framme i centralen 8:10 men kommer iallafall fram."); Console.ReadLine(); Console.Clear(); } else { Console.Clear(); Console.WriteLine("Du är en idiot! Skriv något vettigt!"); Console.ReadLine(); Console.Clear(); } Console.Clear(); Console.WriteLine("Efter att du nått centralen måste du dra till skolan, går du till annexet eller Craaford? (Annexet/Craaford)"); string ans2 = Console.ReadLine(); Console.ReadLine(); if (ans2 == "Craaford") { Console.Clear(); Console.WriteLine("Du har koll på schemat vilket sparar dig tid."); Console.ReadLine(); Console.Clear(); } else if (ans2 == "Annexet") { Console.Clear(); Console.WriteLine("Idiot! Det är måndag! Första lektionen är programmering på Craaford, du försenas med 5 minuter. Klockan är nu 8:20"); Console.ReadLine(); Console.Clear(); } else { Console.Clear(); Console.WriteLine("Du är en idiot! Skriv något vettigt!"); Console.ReadLine(); Console.Clear(); } Console.WriteLine("När du når <NAME> går en alkis mot dig och börjar prata, stannar du för att försöka förstå vad han säger? (Ja/Nej)"); string ans3 = Console.ReadLine(); Console.ReadLine(); if (ans3 == "Ja") { Console.Clear(); Console.WriteLine("Du förlorar tid eftersom du stannar, du kommer ytterligare 2 minuter sent."); Console.ReadLine(); Console.Clear(); } else if (ans3 == "Nej") { Console.Clear(); Console.WriteLine("Du inser att det finns bättre saker att göra en att engagera dig i filosofiska diskussioner med alkisar och sparar tid."); Console.ReadLine(); Console.Clear(); } else { Console.Clear(); Console.WriteLine("Du är en idiot! Skriv något vettigt!"); Console.ReadLine(); Console.Clear(); } Console.WriteLine("När du kommer till ingången måste du skriva in koden till entrén, vad är den?"); string ans4 = Console.ReadLine(); Console.ReadLine(); if (ans4 == "1577#") { Console.Clear(); Console.WriteLine("Du kom ihåg koden och tar dig till klassrummet."); Console.ReadLine(); Console.Clear(); } else if (ans4 == "1577") { Console.Clear(); Console.WriteLine("Du kom (typ) ihåg koden och tar dig till klassrummet."); Console.ReadLine(); Console.Clear(); } else { Console.Clear(); Console.WriteLine("Du förlorar tid eftersom du glömde koden"); Console.ReadLine(); Console.Clear(); } Console.WriteLine("På vägen till skolan valde du att åka med " + ans1 + ". Efter du anlände till centralen gick du mot " + ans2 + ". Du stötte sedan på en alkis i Norra Bantorget och när han ville ställa frågor sa du " + ans3 + ". När du väl var framme och skulle skriv in koden skrev du " + ans4 + "."); Console.ReadLine(); } } }
1aa5b2600211356e253a8496fcececa23e318d64
[ "C#" ]
1
C#
m-isaksson84/if
7c61586e575598693e04766690a188b2d1bd2ed8
c8c1f76a1030809e9c912eb34197d0e0b3b6d26a
refs/heads/master
<file_sep>package com.springbatch.demo.step2; import org.springframework.batch.item.ItemWriter; import java.util.List; public class SampleStep2Writer implements ItemWriter { @Override public void write(List list) throws Exception { } }
1bf96f039305418eba11be5c4add6c65f5f03298
[ "Java" ]
1
Java
mamingrui8/springbatch_demo
671214963188feca532e7d4c0b751079261c2978
35a15fd8150383bdb85defc2f3fd4cec820190f4
refs/heads/main
<repo_name>Alexader/pier-rs<file_sep>/src/key.rs mod key; use std::fs; use serde::{Deserialize, Serialize}; use serde_json::Result; #[derive(Serialize, Deserialize)] pub struct Key { pub typ: String, pub cipher: Cipher, } #[derive(Serialize, Deserialize)] pub struct Cipher { pub cipher: String, pub data: String, } fn read_key(path: &String) -> Key { let jsonData = fs::read_to_string(path)?; let key: Key = serde_json::from_str(jsonData)?; return key; }<file_sep>/Cargo.toml [package] name = "pier-rs" version = "0.1.0" authors = ["Alexader <<EMAIL>>"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] structopt = { version = "0.3.13", default-features = false } anyhow = "1.0" serde = "1.0.118" serde_json = "1.0"<file_sep>/src/main.rs use structopt::StructOpt; use anyhow::{Context, Result}; #[derive(StructOpt, Debug)] #[structopt(name = "pier", about="pier related interaction")] struct Pier { #[structopt(name = "repo", short = "r", parse(from_os_str))] repo: std::path::PathBuf, #[structopt(subcommand)] cmd: PierCmd, } #[derive(StructOpt, Debug)] #[structopt(about = "the stupid content tracker")] enum PierCmd { #[structopt(name = "id")] Id(Id), #[structopt(name = "init")] Init(Init), } #[derive(Debug, StructOpt)] struct Init { /// The repo path to init repo: Option<String>, } #[derive(Debug, StructOpt)] struct Id { /// The repo path to get id repo: Option<String>, } fn main() -> Result<()> { let pier = Pier::from_args(); let repo = pier.repo.into_os_string().into_string().unwrap(); match &pier.cmd { PierCmd::Id (cmd) => getPierID(cmd, &repo)?, PierCmd::Init(cmd) => initPier(cmd, &repo)?, _ => {} } Ok(()) } fn initPier(cmd: &Init, repo: &String) -> Result<()> { let cmdRepo = cmd.repo.as_ref().expect("wrong repo"); println!("this is init function for repo {} and {}", repo, cmdRepo); Ok(()) } fn getPierID(cmd: &Id, repo: &String) -> Result<()> { let cmdRepo = cmd.repo.as_ref().expect("wrong repo"); println!("this is id function for repo {} and {}", repo, cmdRepo); Ok(()) }<file_sep>/README.md # pier-rs pier for bitxhub in rust implemention
bbc2f0f9b09870db1cff19efeea6fb6530c11467
[ "TOML", "Rust", "Markdown" ]
4
Rust
Alexader/pier-rs
8261f2b39358490a0758d7a53fad06a755c59800
14d24550d5c27779128a7cd75fc6c08c188e308f
refs/heads/master
<file_sep># Give Better - Client ## Description Give better is a server side rendered Nuxt Progressive Web App for providing users a location to post and share wishlists and view what their friends and family have listed as possible gifts ## Stack This project is only for the client implementation of the progressive web app. This app utilizes: - Nuxt.js - Bulma (css) - Service workers for progressive web app specific functionality Give Better is hosted on Heroku ## Integrations Give Better has 2 key integrations 1) GraphCMS 2) Firebase GraphCMS is utilized for providing a CMS for static labels and non-user provided content for the application Firebase it utilized for a realtime NoSQL database, asset storage, authentication as a service, and analytics ## Build Setup ``` bash # install dependencies $ npm install # serve with hot reload at localhost:3000 # note: deletes sw.js from root $ npm run dev # build for production and launch server $ npm run build $ npm start # generate static project $ npm run generate # generate service worker (sw.js) file $ npm run generate:sw # build SSR app and generate sw.js $ npm run generate:pwa # build SSR app, generate sw.js, and run app $ npm run start:pwa ``` <file_sep>module.exports = { globDirectory: './.nuxt/', globPatterns: [ '**/*.{html,js,css}' ], swDest: './static/sw.js', swSrc: './assets/custom-sw.js' } <file_sep>import firebase from 'firebase/app' import 'firebase/firestore' const db = firebase.firestore() export default { mounted: function () { }, data () { return { } }, computed: { }, methods: { createIdea: function (uid, idea) { if (!uid) { throw new Error('Invalid User ID provided') } if (!idea) { throw new Error('Idea undefined') } if (!idea.url || !idea.description) { throw new Error('Invalid idea properties') } idea.timestamp = new Date() return db .doc('users/' + uid) .collection('ideas') .add(idea) .then(result => { return result }) .catch(console.error) } } } <file_sep>export default function ({store}) { if (!store.getters['user/user']) { store.$router.push({ path: '/login' }) } } <file_sep>import Vue from 'vue' import firebase from 'firebase/app' import 'firebase/auth' import 'firebase/firestore' const firebaseConfig = { apiKey: process.env.FIREBASE_APIKEY, authDomain: process.env.FIREBASE_AUTHDOMAIN, databaseURL: process.env.FIREBASE_DATABASEURL, projectId: process.env.FIREBASE_PROJECTID, storageBucket: process.env.FIREBASE_STORAGEBUCKET, messagingSenderId: process.env.FIREBASE_MESSAGINGSENDERID } const firebasePlugin = { install: (Vue, options) => { if (firebaseConfig && firebaseConfig.apiKey && firebaseConfig.authDomain && firebaseConfig.databaseURL && firebaseConfig.projectId && firebaseConfig.storageBucket && firebaseConfig.messagingSenderId) { if (!firebase.apps.length) { firebase.initializeApp(firebaseConfig) } } else { console.error('Invalid firebase config provided') } } } Vue.use(firebasePlugin)
be4f7e1adf20d27a93b54435438853785df21724
[ "Markdown", "JavaScript" ]
5
Markdown
ah100101/Give-Better-Archived
6e34e21b65632d9768864e842723675ff070de0a
06510e1f3aff80aad3f7f394e0fe1e4d7e71088c
refs/heads/master
<repo_name>Ageenkooo/zafira<file_sep>/sources/zafira-tests/src/test/resources/db.properties db.jdbc.driverClass=org.postgresql.Driver db.jdbc.url=jdbc:postgresql://ci.qaprosoft.com:5433/postgres db.jdbc.user=postgres db.jdbc.password=<PASSWORD> db.c3p0.maxPoolSize=2 <file_sep>/sources/zafira-web/angular/client/app/_services/util.service.js (function () { 'use strict'; angular .module('app.services') .factory('UtilService', ['$rootScope', '$mdToast', '$timeout', UtilService]) function UtilService($rootScope, $mdToast, $timeout) { var service = {}; service.untouchForm = untouchForm; service.truncate = truncate; service.handleSuccess = handleSuccess; service.handleError = handleError; service.isEmpty = isEmpty; service.settingsAsMap = settingsAsMap; service.reconnectWebsocket = reconnectWebsocket; service.websocketConnected = websocketConnected; return service; function untouchForm(form) { form.$setPristine(); form.$setUntouched(); } function truncate(fullStr, strLen) { if (fullStr == null || fullStr.length <= strLen) return fullStr; var separator = '...'; var sepLen = separator.length, charsToShow = strLen - sepLen, frontChars = Math.ceil(charsToShow/2), backChars = Math.floor(charsToShow/2); return fullStr.substr(0, frontChars) + separator + fullStr.substr(fullStr.length - backChars); }; function handleSuccess(res) { return { success: true, data: res.data }; } function handleError(error) { return function (res) { if(res.status == 400 && res.data.validationErrors && res.data.validationErrors.length) { error = res.data.validationErrors.map(function(validation) { return validation.message; }).join('\n'); } return { success: false, message: error, error: res }; }; } function isEmpty(obj) { return jQuery.isEmptyObject(obj); }; function settingsAsMap(settings) { var map = {}; if(settings) settings.forEach(function(setting) { map[setting.name] = setting.value; }); return map; }; // ************** Websockets ************** function reconnectWebsocket(name, func) { if(! $rootScope.disconnectedWebsockets) { $rootScope.disconnectedWebsockets = {}; $rootScope.disconnectedWebsockets.websockets = {}; $rootScope.disconnectedWebsockets.toastOpened = false; } var attempt = $rootScope.disconnectedWebsockets.websockets[name] ? $rootScope.disconnectedWebsockets.websockets[name].attempt - 1 : 3; $rootScope.disconnectedWebsockets.websockets[name] = {function: func, attempt: attempt}; reconnect(name); }; function reconnect (name) { var websocket = $rootScope.disconnectedWebsockets.websockets[name]; if(websocket.attempt > 0) { var delay = 5000; $timeout(function () { tryToReconnect(name); }, delay); } else { if(! $rootScope.disconnectedWebsockets.toastOpened) { $rootScope.disconnectedWebsockets.toastOpened = true; showReconnectWebsocketToast(); } } }; function websocketConnected (name) { if($rootScope.disconnectedWebsockets && $rootScope.disconnectedWebsockets.websockets[name]) { delete $rootScope.disconnectedWebsockets.websockets[name]; } }; function tryToReconnect(name) { $rootScope.$applyAsync($rootScope.disconnectedWebsockets.websockets[name].function); }; function showReconnectWebsocketToast() { $mdToast.show({ hideDelay: 0, position: 'bottom right', scope: $rootScope, preserveScope: true, controller : function ($rootScope, $mdToast) { $rootScope.reconnect = function() { angular.forEach($rootScope.disconnectedWebsockets.websockets, function (websocket, name) { tryToReconnect(name); }); $rootScope.closeToast(); }; $rootScope.closeToast = function() { $rootScope.disconnectedWebsockets.toastOpened = false; $mdToast .hide() .then(function() { }); }; }, templateUrl : 'app/_testruns/websocket-reconnect_toast.html' }); }; } })(); <file_sep>/sources/zafira-tests/src/main/resources/config.properties base_url=http://ci.qaprosoft.com:9000/zafira/#! selenium_host=http://demo:<EMAIL>:4444/wd/hub browser=chrome <file_sep>/sources/zafira-web/angular/client/app/_services/setting.provider.js (function () { 'use strict'; angular .module('app') .provider('SettingProvider', SettingProvider); function SettingProvider() { this.$get = function($cookieStore) { return { getCompanyLogoURl: function() { return $cookieStore.get("companyLogoURL"); }, setCompanyLogoURL: function(logoURL) { $cookieStore.put("companyLogoURL", logoURL); } } }; } })(); <file_sep>/sources/zafira-services/src/main/java/com/qaprosoft/zafira/services/util/FreemarkerUtil.java package com.qaprosoft.zafira.services.util; import com.qaprosoft.zafira.services.exceptions.ServiceException; import freemarker.template.Configuration; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; @Component public class FreemarkerUtil { private Logger LOGGER = Logger.getLogger(FreemarkerUtil.class); @Autowired private Configuration freemarkerConfiguration; public String getFreeMarkerTemplateContent(String template, Object obj) throws ServiceException { StringBuffer content = new StringBuffer(); try { content.append(FreeMarkerTemplateUtils .processTemplateIntoString(freemarkerConfiguration.getTemplate(template), obj)); } catch (Exception e) { LOGGER.error("Problem with free marker template compilation: " + e.getMessage()); throw new ServiceException(e.getMessage()); } return content.toString(); } } <file_sep>/sources/zafira-models/src/main/java/com/qaprosoft/zafira/models/dto/filter/StoredSubject.java package com.qaprosoft.zafira.models.dto.filter; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Component public class StoredSubject { private Subject testRunSubject = new Subject() { { setName(Name.TEST_RUN); setCriterias(new ArrayList<Criteria>() { private static final long serialVersionUID = -3470218714244856071L; { add(new Criteria() { { setName(Name.STATUS); setOperators(Arrays.asList(Operator.EQUALS, Operator.NOT_EQUALS)); } } ); add(new Criteria() { { setName(Name.TEST_SUITE); setOperators(Arrays.asList(Operator.EQUALS, Operator.NOT_EQUALS, Operator.CONTAINS, Operator.NOT_CONTAINS)); } } ); add(new Criteria() { { setName(Name.JOB_URL); setOperators(Arrays.asList(Operator.EQUALS, Operator.NOT_EQUALS, Operator.CONTAINS, Operator.NOT_CONTAINS)); } } ); add(new Criteria() { { setName(Name.ENV); setOperators(Arrays.asList(Operator.EQUALS, Operator.NOT_EQUALS)); } } ); add(new Criteria() { { setName(Name.PLATFORM); setOperators(Arrays.asList(Operator.EQUALS, Operator.NOT_EQUALS)); } } ); add(new Criteria() { { setName(Name.DATE); setOperators(Arrays.asList(Operator.EQUALS, Operator.NOT_EQUALS, Operator.BEFORE, Operator.AFTER, Operator.LAST_24_HOURS, Operator.LAST_7_DAYS, Operator.LAST_14_DAYS, Operator.LAST_30_DAYS)); } } ); add(new Criteria() { { setName(Name.PROJECT); setOperators(Arrays.asList(Operator.EQUALS, Operator.NOT_EQUALS)); } } ); } } ); } }; private List<Subject> subjects = new ArrayList<Subject>() { private static final long serialVersionUID = 3499422182444939573L; { add(testRunSubject); } }; public Subject getTestRunSubject() { return testRunSubject; } public Subject getSubjectByName(Subject.Name name) { return subjects.stream().filter(subject -> subject.getName().equals(name)).findFirst().orElse(null); } } <file_sep>/sources/zafira-services/src/main/java/com/qaprosoft/zafira/services/services/FilterService.java package com.qaprosoft.zafira.services.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.qaprosoft.zafira.dbaccess.dao.mysql.FilterMapper; import com.qaprosoft.zafira.models.db.Filter; import com.qaprosoft.zafira.models.dto.filter.FilterType; import com.qaprosoft.zafira.models.dto.filter.StoredSubject; import com.qaprosoft.zafira.models.dto.filter.Subject; import com.qaprosoft.zafira.services.exceptions.ServiceException; import com.qaprosoft.zafira.services.util.FreemarkerUtil; @Service public class FilterService { @Autowired private FilterMapper filterMapper; @Autowired private StoredSubject storedSubject; @Autowired private FreemarkerUtil freemarkerUtil; public enum Template { TEST_RUN_TEMPLATE("/filters/test_run_search_data.ftl"), TEST_RUN_COUNT_TEMPLATE("/filters/test_run_search_count.ftl"); private String path; Template(String path) { this.path = path; } public String getPath() { return path; } } @Transactional(rollbackFor = Exception.class) public Filter createFilter(Filter filter) throws ServiceException { filterMapper.createFilter(filter); return filter; } @Transactional(readOnly = true) public Filter getFilterById(long id) throws ServiceException { return filterMapper.getFilterById(id); } @Transactional(readOnly = true) public Filter getFilterByName(String name) throws ServiceException { return filterMapper.getFilterByName(name); } @Transactional(readOnly = true) public List<Filter> getAllFilters() throws ServiceException { return filterMapper.getAllFilters(); } @Transactional(readOnly = true) public List<Filter> getAllPublicFilters(Long userId) { return filterMapper.getAllPublicFilters(userId); } @Transactional(readOnly = true) public Integer getFiltersCount() throws ServiceException { return filterMapper.getFiltersCount(); } @Transactional(rollbackFor = Exception.class) public Filter updateFilter(Filter filter, boolean isAdmin) throws ServiceException { Filter dbFilter = getFilterById(filter.getId()); if(dbFilter == null) { throw new ServiceException("No filters found by id: " + filter.getId()); } if(! filter.getName().equals(dbFilter.getName()) && getFilterByName(filter.getName()) != null) { throw new ServiceException("Filter with name '" + filter.getName() + "' already exists"); } dbFilter.setName(filter.getName()); dbFilter.setDescription(filter.getDescription()); dbFilter.setSubject(filter.getSubject()); dbFilter.setPublicAccess(isAdmin && filter.isPublicAccess()); filterMapper.updateFilter(dbFilter); return dbFilter; } @Transactional(rollbackFor = Exception.class) public void deleteFilterById(long id) { filterMapper.deleteFilterById(id); } public Subject getStoredSubject(Subject.Name name) { return storedSubject.getSubjectByName(name); } public String getTemplate(FilterType filter, Template template) throws ServiceException { return freemarkerUtil.getFreeMarkerTemplateContent(template.getPath(), filter); } } <file_sep>/sources/zafira-dbaccess/src/test/resources/com/qaprosoft/zafira/dbaccess/db.properties db.jdbc.driverClass=org.postgresql.Driver db.jdbc.url=jdbc:postgresql://127.0.0.1:5432/postgres db.jdbc.user=postgres db.jdbc.password=<PASSWORD> db.c3p0.maxPoolSize=2 <file_sep>/sources/zafira-models/src/main/java/com/qaprosoft/zafira/models/dto/monitor/MonitorCheckType.java package com.qaprosoft.zafira.models.dto.monitor; import com.fasterxml.jackson.annotation.JsonInclude; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) public class MonitorCheckType implements Serializable { private static final long serialVersionUID = 3232356935782375373L; private Integer actualCode; private boolean success; public MonitorCheckType(Integer actualCode, boolean success) { this.actualCode = actualCode; this.success = success; } public Integer getActualCode() { return actualCode; } public boolean isSuccess() { return success; } } <file_sep>/sources/zafira-models/src/main/java/com/qaprosoft/zafira/models/db/MonitorStatus.java package com.qaprosoft.zafira.models.db; public class MonitorStatus extends AbstractEntity { private static final long serialVersionUID = 496067410211084296L; private Boolean success; public MonitorStatus() { } public MonitorStatus(boolean success) { this.success = success; } public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } } <file_sep>/sources/zafira-tests/src/main/resources/zafira.properties zafira_enabled=true zafira_service_url=http://ci.qaprosoft.com:9000/zafira-ws zafira_access_token=<KEY> zafira_project=UNKNOWN<file_sep>/sources/zafira-services/src/main/java/com/qaprosoft/zafira/services/services/cache/ICacheableService.java package com.qaprosoft.zafira.services.services.cache; import java.io.Serializable; import java.util.function.Function; public interface ICacheableService<T, R> extends Serializable { long serialVersionUID = -1915862222225912222L; Function<T, R> getValue(); } <file_sep>/sources/zafira-services/src/main/java/com/qaprosoft/zafira/services/services/jmx/CryptoService.java /******************************************************************************* * Copyright 2013-2018 QaProSoft (http://www.qaprosoft.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.qaprosoft.zafira.services.services.jmx; import com.qaprosoft.zafira.models.db.Setting; import com.qaprosoft.zafira.services.exceptions.EncryptorInitializationException; import com.qaprosoft.zafira.services.services.SettingsService; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.jasypt.util.text.BasicTextEncryptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jmx.export.annotation.*; import javax.annotation.PostConstruct; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import java.security.NoSuchAlgorithmException; import java.util.List; import static com.qaprosoft.zafira.models.db.Setting.Tool.CRYPTO; import static com.qaprosoft.zafira.models.db.Setting.SettingType.*; /** * Created by irina on 21.7.17. */ @ManagedResource(objectName = "bean:name=cryptoService", description = "Crypto init Managed Bean", currencyTimeLimit = 15, persistPolicy = "OnUpdate", persistPeriod = 200, persistLocation = "foo", persistName = "bar") public class CryptoService implements IJMXService { private static final Logger LOGGER = Logger.getLogger(CryptoService.class); private String type; private int size = 0; private String key; private String salt; private BasicTextEncryptor basicTextEncryptor; @Autowired private SettingsService settingsService; @Override @PostConstruct public void init() { List<Setting> cryptoSettings = null; this.basicTextEncryptor = new BasicTextEncryptor(); try { cryptoSettings = settingsService.getSettingsByTool(CRYPTO); for (Setting setting : cryptoSettings) { switch (Setting.SettingType.valueOf(setting.getName())) { case CRYPTO_KEY_TYPE: type = setting.getValue(); break; case CRYPTO_KEY_SIZE: size = Integer.valueOf(setting.getValue()); break; default: break; } } initCryptoTool(); } catch (Exception e) { LOGGER.error(e); } } @ManagedOperation(description = "Change Crypto initialization") public void initCryptoTool() { try { String dbKey = settingsService.getSettingByType(KEY).getValue(); if (StringUtils.isEmpty(dbKey)) { generateKey(); key = settingsService.getSettingByType(KEY).getValue(); } else { key = dbKey; } if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(salt)) { basicTextEncryptor.setPassword(key + salt); } else { throw new EncryptorInitializationException(); } } catch (Exception e) { LOGGER.error("Unable to initialize Crypto Tool, salt or key might be null: " + e.getMessage(), e); } } public String encrypt(String strToEncrypt) throws Exception { return basicTextEncryptor.encrypt(strToEncrypt); } public String decrypt(String strToDecrypt) throws Exception { return basicTextEncryptor.decrypt(strToDecrypt); } public void generateKey() throws Exception { String key = null; try { key = new String(Base64.encodeBase64(generateKey(type, size).getEncoded())); } catch (Exception e) { LOGGER.error("Unable to generate key: " + e.getMessage()); } Setting keySetting = settingsService.getSettingByType(KEY); keySetting.setValue(key); settingsService.updateSetting(keySetting); } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } @ManagedAttribute(description = "Get cryptoKey") public String getKey() { return key; } public void setKey(String key) { this.key = key; } @Override public boolean isConnected() { boolean connected = false; try { connected = getKey() != null && salt != null; } catch (Exception e) { LOGGER.error("Unable to connect to JIRA", e); } return connected; } public static SecretKey generateKey(String keyType, int size) throws NoSuchAlgorithmException { LOGGER.debug("generating key use algorithm: '" + keyType + "'; size: " + size); KeyGenerator keyGenerator = KeyGenerator.getInstance(keyType); keyGenerator.init(size); return keyGenerator.generateKey(); } } <file_sep>/sources/zafira-services/src/main/java/com/qaprosoft/zafira/services/services/jmx/ldap/LDAPService.java package com.qaprosoft.zafira.services.services.jmx.ldap; import com.qaprosoft.zafira.models.db.Setting; import com.qaprosoft.zafira.services.services.SettingsService; import com.qaprosoft.zafira.services.services.jmx.CryptoService; import com.qaprosoft.zafira.services.services.jmx.IJMXService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.jmx.export.annotation.*; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.security.ldap.authentication.BindAuthenticator; import org.springframework.security.ldap.authentication.LdapAuthenticationProvider; import org.springframework.security.ldap.search.FilterBasedLdapUserSearch; import javax.annotation.PostConstruct; import java.util.List; import static com.qaprosoft.zafira.models.db.Setting.Tool.LDAP; @ManagedResource(objectName="bean:name=ldapService", description="Ldap init Managed Bean", currencyTimeLimit=15, persistPolicy="OnUpdate", persistPeriod=200) public class LDAPService implements IJMXService { private final static Logger LOGGER = Logger.getLogger(LDAPService.class); @Autowired private LDAPUserDetailsContextMapper ldapUserDetailsContextMapper; @Autowired private SettingsService settingsService; @Autowired private CryptoService cryptoService; private LdapContextSource ldapContextSource; private BindAuthenticator bindAuthenticator; private FilterBasedLdapUserSearch filterBasedLdapUserSearch; private LdapAuthenticationProvider ldapAuthenticationProvider; @Override @PostConstruct public void init() { String dn = null; String searchFilter = null; String url = null; String managerUser = null; String managerPassword = <PASSWORD>; try { List<Setting> ldapSettings = settingsService.getSettingsByTool(LDAP); for (Setting setting : ldapSettings) { if(setting.isEncrypted()) { setting.setValue(cryptoService.decrypt(setting.getValue())); } switch (Setting.SettingType.valueOf(setting.getName())) { case LDAP_DN: dn = setting.getValue(); break; case LDAP_SEARCH_FILTER: searchFilter = setting.getValue(); break; case LDAP_URL: url = setting.getValue(); break; case LDAP_MANAGER_USER: managerUser = setting.getValue(); break; case LDAP_MANAGER_PASSWORD: managerPassword = setting.getValue(); break; default: break; } } init(dn, searchFilter, url, managerUser, managerPassword); } catch(Exception e) { LOGGER.error("Setting does not exist", e); } } @ManagedOperation(description="Change Ldap initialization") @ManagedOperationParameters({ @ManagedOperationParameter(name = "dn", description = "Ldap dn"), @ManagedOperationParameter(name = "searchFilter", description = "Ldap search filter"), @ManagedOperationParameter(name = "url", description = "Ldap url"), @ManagedOperationParameter(name = "managerUser", description = "Ldap manager user"), @ManagedOperationParameter(name = "managerPassword", description = "Ldap manager password")}) public void init(String dn, String searchFilter, String url, String managerUser, String managerPassword){ try { this.ldapContextSource = new LdapContextSource(); this.ldapContextSource.setUrl(url); this.ldapContextSource.setUserDn(managerUser); this.ldapContextSource.setPassword(<PASSWORD>); this.ldapContextSource.afterPropertiesSet(); this.filterBasedLdapUserSearch = new FilterBasedLdapUserSearch(dn, searchFilter, ldapContextSource); this.filterBasedLdapUserSearch.setSearchSubtree(true); this.bindAuthenticator = new BindAuthenticator(this.ldapContextSource); this.bindAuthenticator.setUserSearch(this.filterBasedLdapUserSearch); this.ldapAuthenticationProvider = new LdapAuthenticationProvider(this.bindAuthenticator); this.ldapAuthenticationProvider.setUserDetailsContextMapper(this.ldapUserDetailsContextMapper); } catch (Exception e) { LOGGER.error("Unable to initialize Ldap integration: " + e.getMessage()); } } @Override public boolean isConnected() { boolean result = false; try { getLdapContextSource().getContext(this.ldapContextSource.getUserDn(), this.ldapContextSource.getPassword()); result = true; } catch(Exception e) { LOGGER.error(e); } return result; } @ManagedAttribute(description="Get ldap context source") @Bean public LdapContextSource getLdapContextSource() { return this.ldapContextSource; } @ManagedAttribute(description="Get ldap authentication provider") @Bean public LdapAuthenticationProvider getLdapAuthenticationProvider() { return this.ldapAuthenticationProvider; } }
601c0492c9317e5ef696553706828a314365613c
[ "JavaScript", "Java", "INI" ]
14
INI
Ageenkooo/zafira
c4875dbdef106d17e86446d951bfe58e2d3264d8
6c5b7a8c52ba20801c9ff127cba57f085f8e6808
refs/heads/master
<file_sep># alexandria Final project implementation for Auburn University Spring 2018 Software Modeling and Design / COMP 3700 Designed to be a basic library system Coded in a team of two with another student <file_sep>//Alexandria Implementation //Programmed by <NAME> and <NAME> #include <iostream> #include <string> #include <fstream> using namespace std; class User; class Item { friend class User; private: string title; string customer; int status; string type; public: string history [10]; int historyIndex = 0; string getTitle(); void setTitle(string titleIn); void setStatus(int s); int getStatus(); void displayInfo(); void markLost(); void setCustomer(string customerIn); string getCustomer(); void markLate(); void returnItem(); void markDamaged(); void deleteItem(); }; class Book: public Item { private: string author; string publisher; int edition; string ISBN; public: void editItem(); string getAuthor(); void setAuthor(string authorIn); string getPublisher(); void setPublisher(string publisherIn); int getEdition(); void setEdition(int editionIn); string getISBN(); void setISBN(string ISBNIn); void displayInfo(); void deleteItem(); }; class Magazine: public Item { private: string publisher; int year; int issue; public: void editItem(); string getPublisher(); void setPublisher(string publisherIn); int getYear(); void setYear(int yearIn); int getIssue(); void setIssue(int issueIn); void displayInfo(); void deleteItem(); }; class Movie: public Item { private: string director; string dateOfRelease; public: void editItem(); string getDirector(); void setDirector(string directorIn); string getDateOfRelease(); void setDateOfRelease(string dorIn); void displayInfo(); void deleteItem(); }; class CD: public Item { private: string artist; string dateOfRelease; public: void editItem(); string getArtist(); void setArtist(string artistIn); string getDateOfRelease(); void setDateOfRelease(string dorIn); void displayInfo(); void deleteItem(); }; class User { friend class Item; private: string name; string username; string password; int numberOfItems; Item item1; Item item2; Item item3; Item item4; Item item5; Item reserve1; Item reserve2; public: string getUserName(); void setUserName(string u); string getName(); void setName(string nameIn); string getPassword(); void setPassword(string p); int getNumberOfItems(); void setNumberOfItems(int i); Item getItem1(); Item getItem2(); Item getItem3(); Item getItem4(); Item getItem5(); Item getReserve1(); Item getReserve2(); void setItem1(Item i); void setItem2(Item i); void setItem3(Item i); void setItem4(Item i); void setItem5(Item i); void setReserve1(Item r); void setReserve2(Item r); //void selectSearch(Item chosen, int type); }; class Customer: public User { private: string dateJoined; public: bool canCheckout; double fee; double getFee(); void setFee(double f); string getDateJoined(); bool getCanCheckout(); void setDateJoined(string d); void setCanCheckout(bool c); }; class Librarian: public User { private: public: void payFee(int custLoc); int searchCustomers(); void addLibrarian(); void addBook(); void viewHistory(); void addMagazine(); void addMovie(); void addCD(); void checkOut(); void addCustomer(); void displayMenu(Librarian loggedIn); void printReport(); void deleteLibrarian(); void deleteCustomer(); void checkIn(); void reserveItem(); //void removeItem(); //void editItem(); }; void login(string& user, bool& isLibrarian, int& selectedUser); int search(int type); int searchType(); int bookCount = 0; int magCount = 0; int movCount = 0; int cdCount = 0; int libCount = 1; int custCount = 0; Customer cust[10]; Librarian lib[10]; Book books[10]; Magazine magazines[10]; Movie movies[10]; CD cds[10]; int main() { lib[0].setUserName("admin"); lib[0].setPassword("<PASSWORD>"); string currentUser; bool isLibrarian; int selectedUser; login(currentUser, isLibrarian, selectedUser); if (isLibrarian) { Librarian user = lib[selectedUser]; user.displayMenu(user); } else { Customer user = cust[selectedUser]; } } /* Login function which will take in username and password from user and run them through a database. */ void login(string& user, bool& isLibrarian, int& selectedUser) { string username; string password; bool userFound = false; bool passwordFound = false; int i = 0; //type indicates customer or librarian: 1 is customer, 2 is librarian int type = 0; cout << "Username: "; cin >> username; while (i < 10 && userFound == false) { if (username.compare(cust[i].getUserName()) == 0) { userFound = true; type = 1; } else { i++; } } i = 0; while (i < 10 && userFound == false) { if (username.compare(lib[i].getUserName()) == 0) { userFound = true; type = 2; } else { i++; } } if (userFound == false) { cout << "Username not found. Please try again.\n"; login(user, isLibrarian, selectedUser); } else { cout << "Password: "; cin >> password; if (type == 1) { if (password.compare(cust[i].getPassword()) == 0) { cout << "Logged in as " << cust->getUserName() << "\n"; user = username; isLibrarian = false; selectedUser = i; } else { cout << "Password incorrect. \n"; login(user, isLibrarian, selectedUser); } } else { if (password.compare(lib[i].getPassword()) == 0) { cout << "Logged in as " << lib->getUserName() << "\n"; user = username; isLibrarian = true; selectedUser = i; } else { cout << "Password incorrect. \n"; login(user, isLibrarian, selectedUser); } } } } int searchType() { bool selected = false; int select; while (selected == false) { cout << "What type of item?\n"; cout << "1. Book\n2. Magazine\n3. Movie\n4. CD\n"; cin >> select; switch(select) { case 1: { cout << "Book selected.\n"; selected = true; break; } case 2: { cout << "Magazine selected.\n"; selected = true; break; } case 3: { cout << "Movie selected.\n"; selected = true; break; } case 4: { cout << "CD selected.\n"; selected = true; break; } default: { cout << "Invalid input. Please input again.\n"; } } } return select; } int search(int type) { cout << "Please enter the title of the item you wish to see.\n"; bool titleFound = false; while (titleFound == false) { int i = 0; string title; cin >> title; if (type == 1) { i = 0; while (i < 10) { if (title.compare(books[i].getTitle()) == 0) { return i; } else { i++; } } } else if (type == 2) { i = 0; while (i < 10) { if (title.compare(magazines[i].getTitle()) == 0) { return i; } else { i++; } } } else if (type == 3) { i = 0; while (i < 10) { if (title.compare(movies[i].getTitle()) == 0) { return i; } else { i++; } } } else { i = 0; while (i < 10) { if (title.compare(cds[i].getTitle()) == 0) { return i; } else { i++; } } } cout << "No item by that title found. Please input again.\n"; } } //Item getters and Setters string Item::getTitle() { return title; } void Item::setTitle(string titleIn) { title = titleIn; } string Item::getCustomer() { return customer; } void Item::setCustomer(string customerIn) { customer = customerIn; } /* Int value between 1 and 5 determines status of item 1 is Available 2 is Checked out 3 is Lost 4 is Late 5 is Damaged 6 is reserved */ int Item::getStatus() { return status; } void Item::setStatus(int s) { status = s; } void Item::markLost() { setStatus(3); } void Item::markLate() { setStatus(4); } void Item::markDamaged() { setStatus(5); } //Getter and Setters for Books string Book::getAuthor() { return author; } void Book::setAuthor(string authorIn) { author = authorIn; } string Book::getPublisher() { return publisher; } void Book::setPublisher(string publisherIn) { publisher = publisherIn; } int Book::getEdition() { return edition; } void Book::setEdition(int editionIn) { edition = editionIn; } string Book::getISBN() { return ISBN; } void Book::setISBN(string ISBNIn) { ISBN = ISBNIn; } //Getter and Setters for Movie string Movie::getDirector(){ return director; } void Movie::setDirector(string directorIn) { director = directorIn; } string Movie::getDateOfRelease() { return dateOfRelease; } void Movie::setDateOfRelease(string dorIn) { dateOfRelease = dorIn; } //Getter and Setters for Magazine string Magazine::getPublisher() { return publisher; } void Magazine::setPublisher(string publisherIn) { publisher = publisherIn; } int Magazine::getYear() { return year; } void Magazine::setYear(int yearIn) { year = yearIn; } int Magazine::getIssue() { return issue; } void Magazine::setIssue(int issueIn) { issue = issueIn; } //Getter and Setters for CD string CD::getArtist() { return artist; } void CD::setArtist(string artistIn) { artist = artistIn; } string CD::getDateOfRelease() { return dateOfRelease; } void CD::setDateOfRelease(string dorIn) { dateOfRelease = dorIn; } //Display Info functions void Book::displayInfo() { cout << "Title: " << getTitle() << "\nAuthor: " << getAuthor() << "\nPublisher: " << getPublisher() << "\nEdition: " << getEdition() << "\nISBN: " << getISBN() << "\nStatus: "; switch(getStatus()) { case 1: { cout << "Available\n"; break; } case 2: { cout << "Checked out\n"; break; } case 3: { cout << "Lost\n"; break; } case 4: { cout << "Late\n"; break; } case 5: { cout << "Damaged\n"; break; } case 6: { cout << "Reserved\n"; break; } } } void Movie::displayInfo() { cout << "Title: " << getTitle() << "\nDirector: " << getDirector() << "\nDate of Release: " << getDateOfRelease() << "\n"; } void Magazine::displayInfo() { cout << "Title: " << getTitle() << "\nPublisher: " << getPublisher() << "\nYear: " << getYear() << "\nIssue: " << getIssue() << "\n"; } void CD::displayInfo() { cout << "Title: " << getTitle() << "\nArtist: " << getArtist() << "\nDate of Release: " << getDateOfRelease() << "\n"; } void Book::deleteItem() { setTitle(""); setCustomer(""); setStatus(0); setAuthor(""); setPublisher(""); setEdition(0); setISBN(""); bookCount--; } void Magazine::deleteItem() { setTitle(""); setCustomer(""); setStatus(0); setPublisher(""); setYear(0); setIssue(0); magCount--; } void Librarian::deleteLibrarian() { setName(""); setUserName(""); setPassword(""); setNumberOfItems(0); getItem1().deleteItem(); getItem2().deleteItem(); getItem3().deleteItem(); getItem4().deleteItem(); getItem5().deleteItem(); getReserve1().deleteItem(); getReserve2().deleteItem(); libCount--; } void Librarian::deleteCustomer() { cust[custCount].setName(""); cust[custCount].setUserName(""); cust[custCount].setPassword(""); cust[custCount].setNumberOfItems(0); cust[custCount].setFee(0.00); cust[custCount].setDateJoined(""); cust[custCount].setCanCheckout(true); cust[custCount].getItem1().deleteItem(); cust[custCount].getItem2().deleteItem(); cust[custCount].getItem3().deleteItem(); cust[custCount].getItem4().deleteItem(); cust[custCount].getItem5().deleteItem(); cust[custCount].getReserve1().deleteItem(); cust[custCount].getReserve2().deleteItem(); custCount--; } void Movie::deleteItem() { setTitle(""); setCustomer(""); setStatus(0); setDirector(""); setDateOfRelease(""); movCount--; } void CD::deleteItem() { setTitle(""); setCustomer(""); setStatus(0); setArtist(""); setDateOfRelease(""); cdCount--; } void Item::deleteItem() { } void User::setUserName(string u){ username = u; } void User::setPassword(string p) { password = p; } void User::setNumberOfItems(int i) { numberOfItems = i; } string User::getUserName() { return username; } string User::getName() { return name; } void User::setName(string nameIn) { name = nameIn; } string User::getPassword() { return <PASSWORD>; } int User::getNumberOfItems() { return numberOfItems; } Item User::getItem1() { return item1; } Item User::getItem2() { return item2; } Item User::getItem3() { return item3; } Item User::getItem4() { return item4; } Item User::getItem5() { return item5; } Item User::getReserve1() { return reserve1; } Item User::getReserve2() { return reserve2; } void User::setItem1(Item i) { item1 = i; } void User::setItem2(Item i) { item2 = i; } void User::setItem3(Item i) { item3 = i; } void User::setItem4(Item i) { item4 = i; } void User::setItem5(Item i) { item5 = i; } void User::setReserve1(Item r) { reserve1 = r; } void User::setReserve2(Item r) { reserve2 = r; } double Customer::getFee() { return fee; } void Customer::setFee(double f) { fee = f; } string Customer::getDateJoined() { return dateJoined; } bool Customer::getCanCheckout() { return canCheckout; } void Customer::setDateJoined(string d) { dateJoined = d; } void Customer::setCanCheckout(bool c) { canCheckout = c; } void Librarian::displayMenu(Librarian loggedIn) { int currentType; int itemIndex; int select; int choice; bool selected = false; bool logout = false; while(!logout) { selected = false; cout << "Please select an option: \n"; cout << "1. Checkout\n2. Search Item\n3. Return Item\n4. Delete User\n5. Add Customer\n6. Add Librarian\n7. Add Item\n8. Print Report\n9. Pay Fee \n10. Log Out\n11. Reserve Item\n12. View History\n"; cin >> select; while (selected == false) { switch(select) { case 1: { checkOut(); selected = true; break; } case 2: { currentType = searchType(); itemIndex = search(currentType); cout << "What would you like to do with this item? \n1. Mark lost\n2. Mark late\n3. Mark damaged\n4. Remove from system\n5. Edit item\n"; cin >> choice; bool valid = false; while (!valid) { switch(choice) { case 1: { switch(currentType) { case 1: { books[itemIndex].markLost(); valid = true; break; } case 2: { magazines[itemIndex].markLost(); valid = true; break; } case 3: { movies[itemIndex].markLost(); valid = true; break; } case 4: { cds[itemIndex].markLost(); valid = true; break; } } break; } case 2: { switch(currentType) { case 1: { books[itemIndex].markLate(); valid = true; break; } case 2: { magazines[itemIndex].markLate(); valid = true; break; } case 3: { movies[itemIndex].markLate(); valid = true; break; } case 4: { cds[itemIndex].markLate(); valid = true; break; } } break; } case 3: { switch(currentType) { case 1: { books[itemIndex].markDamaged(); valid = true; break; } case 2: { magazines[itemIndex].markDamaged(); valid = true; break; } case 3: { movies[itemIndex].markDamaged(); valid = true; break; } case 4: { cds[itemIndex].markDamaged(); valid = true; break; } } break; } case 4: { switch(currentType) { case 1: { books[itemIndex].deleteItem(); valid = true; break; } case 2: { books[itemIndex].deleteItem(); valid = true; break; } case 3: { books[itemIndex].deleteItem(); valid = true; break; } case 4: { books[itemIndex].deleteItem(); valid = true; break; } } break; } case 5: { switch(currentType) { case 1: { books[itemIndex].editItem(); valid = true; break; } case 2: { magazines[itemIndex].editItem(); valid = true; break; } case 3: { movies[itemIndex].editItem(); valid = true; break; } case 4: { cds[itemIndex].editItem(); valid = true; break; } } break; } default : { cout << "Invalid choice, please try again\n"; cin >> choice; } } } selected = true; break; } case 3: { checkIn(); selected = true; break; } case 4: { /* deleteUser(users[]); */ selected = true; break; } case 5: { addCustomer(); selected = true; break; } case 6: { addLibrarian(); selected = true; break; } case 7: { cout << "Which type of item do you wish to add?\n1. Book\n2. Movie\n3. Magazine\n4. CD\n"; int select; bool valid = false; cin >> select; while (!valid) { switch(select) { case 1: { addBook(); valid = true; break; } case 2: { addMovie(); valid = true; break; } case 3: { addMagazine(); valid = true; break; } case 4: { addCD(); valid = true; break; } default: { cout << "Error invalid input, please pick again\n"; cin >> select; } } } selected = true; break; } case 8: { printReport(); selected = true; break; } case 9: { int custLoc = searchCustomers(); loggedIn.payFee(custLoc); break; } case 10: { selected = true; logout = true; cout << "\nHave a nice day!"; break; } case 11: { reserveItem(); selected = true; break; } case 12: { viewHistory(); } default: { cout << "Invalid input. Please try again.\n"; cin >> select; } } } } } /* Allows an Librarian to set a Item's status in the database to checked out. */ void Librarian::checkOut() { int userLoc = searchCustomers(); int type = searchType(); int itemLoc = search(type); switch(type) { case 1: { if (books[itemLoc].getStatus() != 1) { cout << "Sorry, this book is not currently available for check out.\n"; } else if (cust[userLoc].getFee() > 0) { cout << "Sorry, this user has outstanding fees.\n"; } else { books[itemLoc].setStatus(2); cust[userLoc].setItem1(books[itemLoc]); books[itemLoc].history[books[itemLoc].historyIndex] = cust[userLoc].getName(); books[itemLoc].historyIndex = books[itemLoc].historyIndex + 1; cout << cust[userLoc].getName() << " has checked out " << books[itemLoc].getTitle() << ".\n"; } break; } case 2: { if (magazines[itemLoc].getStatus() != 1) { cout << "Sorry, this book is not currently available for check out.\n"; } else if (cust[userLoc].getFee() > 0) { cout << "Sorry, this user has outstanding fees.\n"; } else { magazines[itemLoc].setStatus(2); cust[userLoc].setItem1(magazines[itemLoc]); cout << cust[userLoc].getName() << " has checked out " << magazines[itemLoc].getTitle() << ".\n"; } break; } case 3: { if (movies[itemLoc].getStatus() != 1) { cout << "Sorry, this book is not currently available for check out.\n"; } else if (cust[userLoc].getFee() > 0) { cout << "Sorry, this user has outstanding fees.\n"; } else { movies[itemLoc].setStatus(2); cust[userLoc].setItem1(movies[itemLoc]); cout << cust[userLoc].getName() << " has checked out " << movies[itemLoc].getTitle() << ".\n"; } break; } case 4: { if (cds[itemLoc].getStatus() != 1) { cout << "Sorry, this book is not currently available for check out.\n"; } else if (cust[userLoc].getFee() > 0) { cout << "Sorry, this user has outstanding fees.\n"; } else { cds[itemLoc].setStatus(2); cust[userLoc].setItem1(cds[itemLoc]); cout << cust[userLoc].getName() << " has checked out " << cds[itemLoc].getTitle() << ".\n"; } break; } } } void Librarian::viewHistory() { int type = searchType(); int itemLoc = search(type); int i = 0; Item selected; switch(type) { case 1: { selected = books[itemLoc]; while (i < selected.historyIndex) { cout << selected.history[i] << "\n"; i++; } break; } case 2: { selected = magazines[itemLoc]; while (i < selected.historyIndex) { cout << selected.history[i] << "\n"; i++; } break; } case 3: { selected = movies[itemLoc]; while (i < selected.historyIndex) { cout << selected.history[i] << "\n"; i++; } break; } case 4: { selected = cds[itemLoc]; while (i < selected.historyIndex) { cout << selected.history[i] << "\n"; i++; } break; } } } void Librarian::reserveItem() { int userLoc = searchCustomers(); int type = searchType(); int itemLoc = search(type); switch(type) { case 1: { if (books[itemLoc].getStatus() != 1) { cout << "Sorry, this book is not currently available for reservation.\n"; } else if (cust[userLoc].getFee() > 0) { cout << "Sorry, this user has outstanding fees.\n"; } else { books[itemLoc].setStatus(6); cust[userLoc].setReserve1(books[itemLoc]); cout << cust[userLoc].getName() << " has reserved out " << books[itemLoc].getTitle() << ".\n"; } break; } case 2: { if (magazines[itemLoc].getStatus() != 1) { cout << "Sorry, this book is not currently available for check out.\n"; } else if (cust[userLoc].getFee() > 0) { cout << "Sorry, this user has outstanding fees.\n"; } else { magazines[itemLoc].setStatus(6); cust[userLoc].setReserve1(magazines[itemLoc]); cout << cust[userLoc].getName() << " has reserved " << magazines[itemLoc].getTitle() << ".\n"; } break; } case 3: { if (movies[itemLoc].getStatus() != 1) { cout << "Sorry, this book is not currently available for check out.\n"; } else if (cust[userLoc].getFee() > 0) { cout << "Sorry, this user has outstanding fees.\n"; } else { movies[itemLoc].setStatus(6); cust[userLoc].setReserve1(movies[itemLoc]); cout << cust[userLoc].getName() << " has reserved " << movies[itemLoc].getTitle() << ".\n"; } break; } case 4: { if (cds[itemLoc].getStatus() != 1) { cout << "Sorry, this book is not currently available for check out.\n"; } else if (cust[userLoc].getFee() > 0) { cout << "Sorry, this user has outstanding fees.\n"; } else { cds[itemLoc].setStatus(6); cust[userLoc].setReserve1(cds[itemLoc]); cout << cust[userLoc].getName() << " has reserved " << cds[itemLoc].getTitle() << ".\n"; } break; } } } void Librarian::payFee(int custLoc) { double custFee = cust[custLoc].getFee(); string temp; double feeIn; bool complete = false; if (custFee > 0) { cout << cust[custLoc].getName() << " has a current fee balance of $" << custFee; cout << "\nHow much of the fee is being paid off now?\n"; while (!complete) { cin >> temp; feeIn = stod(temp); if (feeIn > custFee) { cout << "Submitted amount is greater than fee, please submit a new amount\n"; } else { custFee = custFee - feeIn; cust[custLoc].setFee(custFee); cout << cust[custLoc].getName() << "'s new fee balance is $" << custFee << "\n"; complete = true; } } } else { cout << cust[custLoc].getName() << " currently has no fee.\n"; } } void Librarian::checkIn() { int type = searchType(); int index = search(type); int custIndex = searchCustomers(); switch(type) { case 1: { if (books[index].getStatus() == 2) { books[index].setStatus(1); cust[custIndex].getItem1().deleteItem(); cout << cust[custIndex].getName() << " has returned " << books[index].getTitle() << ".\n"; } else { cout << books[index].getTitle() << " is not currently checked out.\n"; } break; } case 2: { if (magazines[index].getStatus() == 2) { magazines[index].setStatus(1); cust[custIndex].getItem1().deleteItem(); cout << cust[custIndex].getName() << " has returned " << magazines[index].getTitle() << ".\n"; } else { cout << magazines[index].getTitle() << " is not currently checked out.\n"; } break; } case 3: { if (movies[index].getStatus() == 2) { movies[index].setStatus(1); cust[custIndex].getItem1().deleteItem(); cout << cust[custIndex].getName() << " has returned " << movies[index].getTitle() << ".\n"; } else { cout << movies[index].getTitle() << " is not currently checked out.\n"; } break; } case 4: { if (cds[index].getStatus() == 2) { cds[index].setStatus(1); cust[custIndex].getItem1().deleteItem(); cout << cust[custIndex].getName() << " has returned " << cds[index].getTitle() << ".\n"; } else { cout << cds[index].getTitle() << " is not currently checked out.\n"; } break; } default: { cout << "You shouldn't be seeing this idk.\n"; } } } void Librarian::addLibrarian() { cout << "Please input the new librarian's information: \n"; cout << "Name: "; string name; cin >> name; setName(name); cout << "Username: "; string username; string password; string passwordCheck; cin >> username; setUserName(username); cout << "Password: "; cin >> password; cout << "Please enter password again for confirmation: "; cin >> passwordCheck; while (password.compare(passwordCheck) != 0) { cout << "Password entries are not the same. Please re-enter.\n"; cout << "Password: "; cin >> password; cout << "Please enter password again for confirmation: "; cin >> passwordCheck; } setPassword(password); setNumberOfItems(0); cout << "A new librarian has been created."; libCount++; } void Librarian::addCustomer() { cout << "Please input the new customer's information: \n"; cout << "Name: "; string name; cin >> name; cust[custCount].setName(name); cout << "Username: "; string username; string password; string passwordCheck; cin >> username; cust[custCount].setUserName(username); cout << "Password: "; cin >> password; cout << "Please enter password again for confirmation: "; cin >> passwordCheck; while (password.compare(passwordCheck) != 0) { cout << "Password entries are not the same. Please re-enter.\n"; cout << "Password: "; cin >> password; cout << "Please enter password again for confirmation: "; cin >> passwordCheck; } cust[custCount].setPassword(password); cust[custCount].setNumberOfItems(0); cust[custCount].setFee(0.00); string input; cout << "Please input the new customer's date joined: "; cin >> input; cust[custCount].setDateJoined(input); cust[custCount].setCanCheckout(true); cout << "A new customer has been created."; custCount++; } void Librarian::addBook() { string input; int intinput; cout << "What is the title of the book?\n"; cin >> input; books[bookCount].setTitle(input); cout << "Who is the author of the book?\n"; cin >> input; books[bookCount].setAuthor(input); cout << "Who is the publisher?\n"; cin >> input; books[bookCount].setPublisher(input); cout << "What edition?\n"; cin >> intinput; books[bookCount].setEdition(intinput); cout << "What is the ISBN?\n"; cin >> input; books[bookCount].setISBN(input); //books[bookCount].setCatalogueNumber(bookCount); books[bookCount].setCustomer(""); books[bookCount].setStatus(1); bookCount++; } void Librarian::addMagazine() { string input; int intinput; cout << "What is the title of the magazine?\n"; cin >> input; magazines[magCount].setTitle(input); cout << "Who is the publisher?\n"; cin >> input; magazines[magCount].setPublisher(input); cout << "What year?\n"; cin >> intinput; magazines[magCount].setYear(intinput); cout << "What issue?\n"; cin >> intinput; magazines[magCount].setIssue(intinput); magazines[magCount].setCustomer(""); magazines[magCount].setStatus(1); magCount++; } void Librarian::addMovie() { string input; int intinput; cout << "What is the title of the movie?\n"; cin >> input; movies[movCount].setTitle(input); cout << "Who is the director?\n"; cin >> input; movies[movCount].setDirector(input); cout << "What date was it released?\n"; cin >> input; movies[movCount].setDateOfRelease(input); movies[movCount].setCustomer(""); movies[movCount].setStatus(1); movCount++; } void Librarian::addCD() { string input; int intinput; cout << "What is the title of the CD?\n"; cin >> input; cds[cdCount].setTitle(input); cout << "Who is the artist?\n"; cin >> input; cds[cdCount].setArtist(input); cout << "What date was it released?\n"; cin >> input; cds[cdCount].setDateOfRelease(input); cds[cdCount].setCustomer(""); cds[cdCount].setStatus(1); cdCount++; } int Librarian::searchCustomers() { cout << "Please enter the username of a customer.\n"; string name; bool found = false; while (!found) { int i = 0; cin >> name; do { if (name.compare(cust[i].getUserName()) == 0) { found = true; return i; } i++; } while (i < custCount); cout << "No customer of that username found.\n"; } cout << "You saw nothing.\n"; return -1; } void Librarian::printReport() { int i; for (i = 0; i < bookCount; i++) { books[i].displayInfo(); } for (i = 0; i < magCount; i++) { magazines[i].displayInfo(); } for (i = 0; i < movCount; i++) { movies[i].displayInfo(); } for (i = 0; i < cdCount; i++) { cds[i].displayInfo(); } } void Book::editItem() { displayInfo(); string input; int intinput; int choice; cout << "Edit Title?\n1. Yes\n2. No\n"; cin >> choice; if (choice == 1) { cout << "Please input new title\n"; cin >> input; setTitle(input); } cout << "Edit Author?\n1. Yes\n2. No\n"; cin >> choice; if (choice == 1) { cout << "Please input new author\n"; cin >> input; setAuthor(input); } cout << "Edit Publisher?\n1. Yes\n2. No\n"; cin >> choice; if (choice == 1) { cout << "Please input new publisher\n"; cin >> input; setPublisher(input); } cout << "Edit Edition?\n1. Yes\n2. No\n"; cin >> choice; if (choice == 1) { cout << "Please input new edition\n"; cin >> intinput; setEdition(intinput); } cout << "Edit ISBN?\n1. Yes\n2. No\n"; cin >> choice; if (choice == 1) { cout << "Please input new ISBN\n"; cin >> input; setISBN(input); } } void Magazine::editItem() { displayInfo(); cout << "Edit Title?\n1. Yes\n2. No\n"; int choice; cin >> choice; string input; int intinput; if (choice == 1) { cout << "Please input new title\n"; cin >> input; setTitle(input); } cout << "Edit Publisher?\n1. Yes\n2. No\n"; cin >> choice; if (choice == 1) { cout << "Please input new publisher\n"; cin >> input; setPublisher(input); } cout << "Edit Year?\n1. Yes\n2. No\n"; cin >> choice; if (choice == 1) { cout << "Please input new year\n"; cin >> intinput; setYear(intinput); } cout << "Edit Isssue?\n1. Yes\n2. No\n"; cin >> choice; if (choice == 1) { cout << "Please inpu new issue\n"; cin >> intinput; setIssue(intinput); } } void Movie::editItem() { displayInfo(); cout << "Edit Title?\n1. Yes\n2. No\n"; int choice; cin >> choice; string input; int intinput; if (choice == 1) { cout << "Please input new title\n"; cin >> input; setTitle(input); } cout << "Edit Director?\n1. Yes\n2. No\n"; cin >> choice; if (choice == 1) { cout << "Please input new publisher\n"; cin >> input; setDirector(input); } cout << "Edit Date of Release?\n1. Yes\n2. No\n"; cin >> choice; if (choice == 1) { cout << "Please input new date of release\n"; cin >> input; setDateOfRelease(input); } } void CD::editItem() { displayInfo(); cout << "Edit Title?\n1. Yes\n2. No\n"; int choice; cin >> choice; string input; int intinput; if (choice == 1) { cout << "Please input new title\n"; cin >> input; setTitle(input); } cout << "Edit Artist?\n1. Yes\n2. No\n"; cin >> choice; if (choice == 1) { cout << "Please input new artist\n"; cin >> input; setArtist(input); } cout << "Edit Date of Release?\n1. Yes\n2. No\n"; cin >> choice; if (choice == 1) { cout << "Please input new date of release\n"; cin >> input; setDateOfRelease(input); } }
96e5bd6763944671fc850376c97b906ce0c0e510
[ "Markdown", "C++" ]
2
Markdown
CTFogarty/alexandria
c714cb79b4b2bd17060277dc135ac2099587f35e
5125b7d6b187601365a100b7a07261308893c58a
refs/heads/master
<repo_name>zakimandalla/praxis-academy<file_sep>/Week-1/Day-5/52/SerialExample.java import java.io.*; class Emp implements Serializable { private static final long serialversionUID = 129348938L; transient int a; static int b; String nama; int umur; //Default constructor public Emp(String nama, int umur, int a, int b){ this.nama = nama; this.umur = umur; this.a = a; this.b = b; } } public class SerialExample { public static void printData(Emp objek1){ System.out.println("nama = "+objek1.nama); System.out.println("umur = "+objek1.umur); System.out.println("a = "+objek1.a); System.out.println("b = "+objek1.b); } public static void main (String[] args){ Emp objek = new Emp("zaki", 22, 2, 1000); String filename = "siapashubham.txt"; //Serialisasi try{ //Menyimpan objek ke file FileOutputStream file = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file); //Metode serialisasi objek out.writeObject(objek); out.close(); file.close(); System.out.println("Objek telah diserialisasi\n Data sebelum deserialisasi"); printData(objek); //nilai variabel statik berubah objek.b = 2000; } catch(IOException ex){ System.out.println("IOException tertangkap"); } objek = null; //Deserialisasi try{ //Membaca objek dari file FileInputStream file = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file); //Metodenya objek = (Emp)in.readObject(); in.close(); file.close(); System.out.println("Saya capek mengetik\ndata setelah deserialisasi"); printData(objek); } catch (IOException ex){ System.out.println("IOException pokok e"); } catch (ClassNotFoundException ex){ System.out.println("ClassBlablabla lah pokok e"); } } } <file_sep>/Week-2/Day-2/71/Math.java public final class Math { public static int add(int first, int second){ return firstNumber + secondNumber; } public static int multiply(int multiplicand, int multiplier){ return multiplicand*multiplier; } public static double divide(int dividend, int divisor){ if(divisor == 0) throw new IllegalArgumentException("Cannot divide by zero (0)."); return dividend/divisor; } }<file_sep>/Week-1/Day-5/51/Serialisasi.java //kode java untuk serialisasi dan deserialisasi objek java import java.io.*; class Demo implements Serializable { public int a; public String b; //Default constructor public Demo(int a, String b){ this.a = a; this.b = b; } } class Test { public static void main(String[] args){ Demo objek = new Demo(1, "geeksforgeeks"); String filename = "file.user"; //Serialisasi try{ //Menyimpan objek dalam file FileOutputStream file = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file); //Metode untuk serialisasi objek out.writeObject(objek); out.close(); file.close(); System.out.println("Objek telah diserialisasi"); } catch(IOException ex){ System.out.println("IOException tertangkap"); } Demo objek1 = null; //Deserialisasi try { //Membaca objek dari file FileInputStream file = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file); //Metode deserialisasi objek objek1 = (Demo)in.readObject(); in.close(); file.close(); System.out.println("Objek telah dideserialisasi"); System.out.println("a = "+objek1.a); System.out.println("b = "+objek1.b); } catch(IOException ex){ System.out.println("IOException tertangkap"); } catch(ClassNotFoundException ex){ System.out.println("ClassNotFoundException tertangkap"); } } }<file_sep>/README.md Repositori ini milik zaki mandalla untuk belajar <file_sep>/Week-2/Day-3/Concurrent5/src/app/CrawledSites.java package app; import java.util.*; public class CrawledSites { private List<String> crawledSites = new ArrayList<String>(); private List<String> linkedSites = new ArrayList<String>(); public void add(String site){ synchronized(this){ if(!crawledSites.contains(site)){ linkedSites.add(site); } } } public String next(){ if(linkedSites.size()==0){ return null; } synchronized(this){ if(linkedSites.size()>0){ String s = linkedSites.get(0); linkedSites.remove(0); crawledSites.add(s); return s; } return null; } } }<file_sep>/Week-1/Day-3/32/generix.java class Tes<T> { T obj; Tes(T obj) { this.obj = obj; } // constructor public T getObject() { return this.obj; } }
a9bd8ace0d8b5284a0a16874aea031f8ad48aac1
[ "Markdown", "Java" ]
6
Java
zakimandalla/praxis-academy
e4c0aa11a615e83f280d9c9ecf7fcf0b4d8b70ba
da65e4632b06144b4eb89ce1443254079952d6bd
refs/heads/master
<file_sep>const DOMAIN = 'churchofjesuschrist.org'; const VERSION = '0.4'; console.log('In main_popup.js'); const downloadButton = $('#downloadButton'); const annotationSelection = $('#annotationSelection'); const selectAll = $('#selectAll'); // Functions for inspecting UI function getNotebookCheckboxes() { const checkboxes = annotationSelection.find('div>input:checkbox'); console.debug(checkboxes); const notebooks = checkboxes .filter((_, element) => element.id.slice(0, 'notebook_'.length) === 'notebook_'); console.debug(notebooks); return notebooks; } function getSelectedNotebooks() { notebookIds = getNotebookCheckboxes() .filter(':checked') .map((_, element) => element.id.replace('notebook_', '')); return notebookIds.toArray(); } function onCheckboxChange(event) { console.debug(event); const target = event.target; console.debug('target:'); console.debug(target); notebooks = getNotebookCheckboxes(); if (target.id === 'selectAll') { console.debug('selectAll'); console.debug(target); if (target.checked) { notebooks.attr('checked', 'checked'); downloadButton.removeAttr('disabled'); } else { notebooks.removeAttr('checked'); if ($('#unassignedAnnotations:checked').length === 0) { downloadButton.attr('disabled', 'disabled'); } } } else if (target.id === 'unassignedAnnotations') { console.debug('unassignedAnnotations'); console.debug(target); if (target.checked) { downloadButton.removeAttr('disabled'); } else if (notebooks.toArray().every(checkbox => !(checkbox.checked))) { downloadButton.attr('disabled', 'disabled'); } } else { if (notebooks.toArray().every(checkbox => !(checkbox.checked))) { selectAll.removeAttr('checked'); if ($('#unassignedAnnotations:checked').length === 0) { downloadButton.attr('disabled', 'disabled'); } } else { downloadButton.removeAttr('disabled'); if (notebooks.toArray().every(checkbox => checkbox.checked)) { selectAll.attr('checked', 'checked'); } } console.log('notebooks'); console.log(notebooks); } } selectAll.change(onCheckboxChange); // Function to help build dynamic UI elements function addCheckbox(notebook) { // console.debug(notebook); if (notebook.id === '') { return null; } div = $('<div>').insertBefore(downloadButton).addClass('selectionLine'); checkboxId = 'notebook_' + notebook.id; checkbox = $('<input>', { type: 'checkbox', id: checkboxId, name: notebook.name, }).change(onCheckboxChange); div.append(checkbox); const annotationCount = 'order' in notebook ? notebook.order.id.length : 0; if (annotationCount !== notebook.annotationCount) { console.debug( `Number of annotations ${annotationCount} does not match ` + `annotationCount ${notebook.annotationCount} ` + `for notebook ${notebook.id}` ); } lastUsed = new Date(notebook.lastUsed).toDateString(); label = $('<label>', { for: checkboxId, text: `${notebook.name} (${annotationCount})`, title: `Last updated: ${lastUsed}`, }); div.append(label); return div; } // Function for performing download let notesUpperBound = 0; async function fetchNotebook(notebookJson) { urlBase = `https://www.${DOMAIN}/notes/api/v2/annotations?`; let numberRemaining = null; if (notebookJson !== null) { numberRemaining = notebookJson.annotationCount; } else { numberRemaining = notesUpperBound; } numberReturned = 0; annotations = []; while (numberRemaining > 0) { numberToReturn = numberRemaining; url = urlBase; if (notebookJson !== null) { url += `folderId=${notebookJson.id}&`; } url += `numberToReturn=${numberToReturn}&`; url += `start=${numberReturned + 1}&`; url += 'type=highlight%2Cjournal%2Creference'; result = await fetch(url, {credentials: 'same-origin'}).then(response => response.json()); console.debug('fetchNotebook result:'); console.debug(result); annotations = annotations.concat(result); numberRemaining -= result.length; } console.debug('fetchNotebook annotations:'); console.debug(annotations); return annotations; } const bgPage = chrome.extension.getBackgroundPage(); // ready is trivial for now const ready = Promise.resolve(); // Display list when ready let notebooksJson = null; ready .then(_ => fetch(`https://www.${DOMAIN}/notes/api/v2/folders`, {credentials: 'same-origin'})) .then(response => { // console.debug('response:'); console.debug(response); return response.json(); }) .then(json => { if (json.length === 0) { const noNotebooks = $('<p>', {text: 'You have no notebooks'}) .addClass('note'); downloadButton.before(noNotebooks); return null; } notebooksJson = json; let unassigned = null; let trueNotebookCount = 0; json.forEach(notebook => { if (notebook.id === '') { unassigned = notebook.annotationCount; } else { trueNotebookCount++; } notesUpperBound += notebook.annotationCount; addCheckbox(notebook); }); if (trueNotebookCount === 0) { const noNotebooks = $('<p>', {text: 'You have no notebooks'}) .addClass('note'); downloadButton.before(noNotebooks); } if (unassigned === null) { console.warn('No "Unassigned Items" notebook'); unassigned = 0; } return unassigned; }) .then(unassigned => { downloadButton.before($('<hr>')); return unassigned; }) .then(unassigned => { if (unassigned === null || unassigned === 0) { noUnassigned = $('<p>', {text: 'You have no unassigned annotations'}) .addClass('note'); downloadButton.before(noUnassigned); return null; } div = $('<div>').insertBefore(downloadButton).addClass('selectionLine'); checkbox = $('<input>', { type: 'checkbox', id: 'unassignedAnnotations', name: 'unassignedAnnotations', }).change(onCheckboxChange); div.append(checkbox); label = $('<label>', { for: 'unassignedAnnotations', text: `Include all annotations (${unassigned} not assigned to any notebook)`, }); div.append(label); }) .then(_ => downloadButton.before($('<hr>'))) .then(_ => annotationSelection.removeAttr('hidden')) .catch(error => { // console.log(error); // console.log('About to redirect to login'); bgPage.updatePopup(false); window.location.replace(chrome.runtime.getURL('login_popup.html')); }); console.log('Created form'); // Set button behavior downloadButton.click(event => { console.log('About to initiate download'); // find selected notebooks if (notebooksJson === null) { throw Error('download button was clicked with no notebook data loaded'); } let notebooksJsonById = {}; console.debug('notebooksJsonById:'); console.debug(notebooksJsonById); notebooksJson.forEach(notebookJson => { notebooksJsonById[notebookJson.id] = notebookJson }); selectedIds = getSelectedNotebooks(); console.debug(selectedIds); let selectedNotebooksJson = []; selectedIds.forEach(notebookId => {selectedNotebooksJson.push(notebooksJsonById[notebookId])}); console.debug('selectedNotebooksJson:'); console.debug(selectedNotebooksJson); let notebooksAnnotations = null; // Look up annotations if ($('#unassignedAnnotations:checked').length > 0) { fetchAnnotations = fetchNotebook(null).then(allAnnotations => { let aggregateAnnotations = {}; allAnnotations.forEach(annotation => { aggregateAnnotations[annotation.id] = annotation; }); return aggregateAnnotations; }); } else { notebooksAnnotations = selectedIds .map(notebookId => notebooksJsonById[notebookId]) .map(notebookJson => fetchNotebook(notebookJson)); notebooksAnnotations = Promise.all(notebooksAnnotations); fetchAnnotations = notebooksAnnotations.then(notebooks => { let aggregateAnnotations = {}; notebooks.forEach(annotations => { // console.debug('annotations:'); // console.debug(annotations); annotations.forEach(annotation => { const annotationId = annotation.id; // console.debug('annotationId:'); // console.debug(annotationId); if (!(annotationId in aggregateAnnotations)) { aggregateAnnotations[annotationId] = annotation; } }); // console.debug('aggregateAnnotations:'); // console.debug(aggregateAnnotations); return aggregateAnnotations; }) return aggregateAnnotations; }) } // Aggregate fetchAnnotations.then(aggregateAnnotations => { const finalResult = { notebooks: selectedNotebooksJson, annotations: aggregateAnnotations, version: VERSION, } console.log('finalResult:') console.log(finalResult); return finalResult; }).then(finalResult => { const resultBlob = new Blob([JSON.stringify(finalResult, null, 4)], {type: 'application/json'}); blobURL = window.URL.createObjectURL(resultBlob); chrome.downloads.download({url: blobURL, filename: 'notebooks.json', saveAs: true}); console.log('Download complete'); }) }); <file_sep>const DOMAIN = 'churchofjesuschrist.org'; const openLogin = document.getElementById('openLogin'); console.log('In login_popup.js'); openLogin.onclick = element => { console.debug('About to open tab'); const urlGoto = `https%3a%2f%2fwww.${DOMAIN}%2f`; const url = `https://signin.${DOMAIN}/signinRedirect?goto=${urlGoto}`; chrome.tabs.create({url, active: true}); };
8e840dcc9ccfcfbe9f86787f75f187c16894a93e
[ "JavaScript" ]
2
JavaScript
nverhaaren/gospel-library-notebook-sharing
aeafd42156f338c658fd1e75ec4d1ec05758233b
4c9015a74eb4ceefcc31479a7a1702b96b146a9b
refs/heads/master
<repo_name>pabiney-msr/433-Advanced-Mechatronics<file_sep>/HW 5/HW5.X/i2c.h #ifndef I2C__H__ #define I2C__H__ void i2c_init(void); void i2c_start(void); void i2c_restart(void); void i2c_send(unsigned char value); unsigned char i2c_receive(void); void i2c_ack(int value); void i2c_stop(void); void i2c_expander_init(); void i2c_expander_set(char address, char value); char i2c_expander_get(char address); #endif<file_sep>/HW 8/HW8/firmware/src/i2c.c #include <proc/p32mx250f128b.h> #include "i2c.h" void i2c_init(void) { ANSELBbits.ANSB2 = 0; ANSELBbits.ANSB3 = 0; I2C2BRG = 233; I2C2CONbits.ON = 1; } void i2c_start(void) { I2C2CONbits.SEN = 1; while (I2C2CONbits.SEN){;} } void i2c_restart(void) { I2C2CONbits.RSEN = 1; while (I2C2CONbits.RSEN){;} } void i2c_send(unsigned char value) { I2C2TRN = value; while (I2C2STATbits.TRSTAT){;} } unsigned char i2c_receive(void) { I2C2CONbits.RCEN = 1; while (!I2C2STATbits.RBF){;} return I2C2RCV; } void i2c_receive_multiple(unsigned char reg, unsigned char *data, int length) { int i = 0; i2c_start(); i2c_send(SHIFTED_SLAVE_ADDRESS_OR_0); i2c_send(reg); i2c_restart(); i2c_send(SHIFTED_SLAVE_ADDRESS_OR_1); for(; i<length;++i) { data[i] = i2c_receive(); i2c_ack((i != length - 1) ? 0 : 1); } i2c_stop(); } void i2c_ack(int value) { I2C2CONbits.ACKDT = value; I2C2CONbits.ACKEN = 1; while (I2C2CONbits.ACKEN){;} } void i2c_stop(void) { I2C2CONbits.PEN = 1; while (I2C2CONbits.PEN){;} } void i2c_expander_init() { i2c_expander_set(CTRL1_XL, 0x82); i2c_expander_set(CTRL2_G, 0x88); i2c_expander_set(CTRL3_C, 0x04); } void i2c_expander_set(char address, char value) { i2c_start(); i2c_send(SHIFTED_SLAVE_ADDRESS_OR_0); i2c_send(address); i2c_send(value); i2c_stop(); } char i2c_expander_get(char address) { char output; i2c_start(); i2c_send(SHIFTED_SLAVE_ADDRESS_OR_0); i2c_send(address); i2c_restart(); i2c_send(SHIFTED_SLAVE_ADDRESS_OR_1); output = i2c_receive(); i2c_ack(1); i2c_stop(); return output; }<file_sep>/HW 7/HW7.X/main.c #include <xc.h> // processor SFR definitions #include <sys/attribs.h> // __ISR macro #include <stdio.h> #include "ILI9163C.h" #include "i2c.h" // DEVCFG0 #pragma config DEBUG = 0b11 // no debugging (disabled) #pragma config JTAGEN = 0 // no jtag (disabled) #pragma config ICESEL = 0b11 // use PGED1 and PGEC1 #pragma config PWP = OFF // no write protect () #pragma config BWP = 1 // no boot write protect (writeable) #pragma config CP = 1 // no code protect // DEVCFG1 #pragma config FNOSC = 0b011 // use primary oscillator with pll #pragma config FSOSCEN = 0 // turn off secondary oscillator (disabled) #pragma config IESO = 0 // no switching clocks (disabled) #pragma config POSCMOD = 0b10 // high speed crystal mode #pragma config OSCIOFNC = 1 // disable secondary osc #pragma config FPBDIV = 0b00 // divide sysclk freq by 1 for peripheral bus clock #pragma config FCKSM = 0b11 // do not enable clock switch #pragma config WDTPS = 0b10100 // use slowest wdt #pragma config WINDIS = 1 // wdt no window mode #pragma config FWDTEN = 0 // wdt disabled #pragma config FWDTWINSZ = 0b11 // wdt window at 25% //0b11? // DEVCFG2 - get the sysclk clock to 48MHz from the 8MHz crystal #pragma config FPLLIDIV = 0xb001 // divide input clock to be in range 4-5MHz; resonater 8MHZ so divide by 2 #pragma config FPLLMUL = 0b111 // multiply clock after FPLLIDIV; used highest mult #pragma config FPLLODIV = 0b001 // divide clock after FPLLMUL to get 48MHz #pragma config UPLLIDIV = 0b001 // divider for the 8MHz input clock, then multiplied by 12 to get 48MHz for USB #pragma config UPLLEN = 0 // USB clock on (enabled) // DEVCFG3 #pragma config USERID = 0xFFFF // some 16bit userid, doesn't matter what #pragma config PMDL1WAY = 0 // allow multiple reconfigurations #pragma config IOL1WAY = 0 // allow multiple reconfigurations #pragma config FUSBIDIO = 1 // USB pins controlled by USB module #pragma config FVBUSONIO = 1 // USB BUSON controlled by USB module #define dataLen 14 typedef struct { unsigned short x, y, z; } Vector; int main() { char message[100]; Vector gyro, accel; unsigned short temperature; float temp_x, temp_y; unsigned char data[dataLen]; int t; __builtin_disable_interrupts(); // set the CP0 CONFIG register to indicate that kseg0 is cacheable (0x3) __builtin_mtc0(_CP0_CONFIG, _CP0_CONFIG_SELECT, 0xa4210583); // 0 data RAM access wait states BMXCONbits.BMXWSDRM = 0x0; // enable multi vector interrupts INTCONbits.MVEC = 0x1; // disable JTAG to get pins back DDPCONbits.JTAGEN = 0; // do your TRIS and LAT commands here SPI1_init(); LCD_init(); i2c_init(); i2c_expander_init(); __builtin_enable_interrupts(); LCD_clearScreen(BLACK); sprintf(message, "WHOAMI:%d", i2c_expander_get(WHO_AM_I)); LCD_string(message, 10, 80, WHITE, BLACK); while(1) { t = _CP0_GET_COUNT() + 4800000; i2c_receive_multiple(OUT_TEMP_L, data, dataLen); temperature = (data[ 1] << 8) | data[ 0]; gyro.x = (data[ 3] << 8) | data[ 2]; gyro.y = (data[ 5] << 8) | data[ 4]; gyro.z = (data[ 7] << 8) | data[ 6]; accel.x = (data[ 9] << 8) | data[ 8]; accel.y = (data[11] << 8) | data[10]; accel.z = (data[13] << 8) | data[12]; temp_x = accel.x*.0061; temp_y = accel.y*.0061; sprintf(message, "AX: %.2f ", temp_x); LCD_string(message, 10, 100, WHITE, BLACK); sprintf(message, "AY: %.2f ", temp_y); LCD_string(message, 10, 90, WHITE, BLACK); LCD_bar(64,64,-(temp_x),4,50, RED,BLACK,0); LCD_bar(64,64,-(temp_y),4,50,GREEN,BLACK,1); while(_CP0_GET_COUNT() < t){;} } }<file_sep>/HW 4/HW4.X/spi.c #include <proc/p32mx250f128b.h> #include "spi.h" #define CS LATBbits.LATB7 void setVoltage(unsigned int channel, unsigned int voltage) { char bits[] = {0, 0}; bits[0] = (((channel << 3) | 0b0111) << 4) | (voltage >> 4); bits[1] = voltage << 4; CS = 0; SPI1_IO(bits[0]); SPI1_IO(bits[1]); CS = 1; } void initSPI1() { SPI1CON = 0; SPI1BUF; SPI1BRG = 0x1000; // 0x1000 to see on N-scope SPI1STATbits.SPIROV = 0; SPI1CONbits.CKP = 0; SPI1CONbits.CKE = 1; SPI1CONbits.MSTEN = 1; SPI1CONbits.ON = 1; ANSELBbits.ANSB13 = 0; RPB13Rbits.RPB13R = 0b0011; //B13, pin 24, is SDO1 SDI1Rbits.SDI1R = 0b0100; //B8, pin 17, is SDI1 TRISBbits.TRISB7 = 0; //B7, pin 16, is CS } char SPI1_IO(unsigned char write) { SPI1BUF = write; while(!SPI1STATbits.SPIRBF){;} return SPI1BUF; }<file_sep>/HW 10/SerialRead.py #!/usr/bin/env python # -*- coding: utf-8 -*- import serial import matplotlib.pyplot as plt def main(): ser = serial.Serial('/dev/ttyACM0',9600) ser.write('r') raw = [] maf = [] iir = [] fir = [] for i in range(0, 100): serial_vals = ser.readline().split() raw.append(serial_vals[1]) maf.append(serial_vals[2]) iir.append(serial_vals[3]) fir.append(serial_vals[4]) ser.close() #plot plt.plot(raw, label='raw') plt.plot(maf, label='maf') plt.plot(iir, label='iir') plt.plot(fir, label='fir') plt.legend() plt.show() if __name__ == '__main__': main() <file_sep>/HW 5/HW5.X/i2c.c #include <proc/p32mx250f128b.h> #include "i2c.h" #define SLAVE_ADDRESS 0x20 #define SHIFTED_SLAVE_ADDRESS SLAVE_ADDRESS << 1 #define SHIFTED_SLAVE_ADDRESS_OR_0 SHIFTED_SLAVE_ADDRESS | 0 #define SHIFTED_SLAVE_ADDRESS_OR_1 SHIFTED_SLAVE_ADDRESS | 1 void i2c_init(void) { ANSELBbits.ANSB2 = 0; ANSELBbits.ANSB3 = 0; I2C2BRG = 233; I2C2CONbits.ON = 1; } void i2c_start(void) { I2C2CONbits.SEN = 1; while (I2C2CONbits.SEN){;} } void i2c_restart(void) { I2C2CONbits.RSEN = 1; while (I2C2CONbits.RSEN){;} } void i2c_send(unsigned char value) { I2C2TRN = value; while (I2C2STATbits.TRSTAT){;} } unsigned char i2c_receive(void) { I2C2CONbits.RCEN = 1; while (!I2C2STATbits.RBF){;} return I2C2RCV; } void i2c_ack(int value) { I2C2CONbits.ACKDT = value; I2C2CONbits.ACKEN = 1; while (I2C2CONbits.ACKEN){;} } void i2c_stop(void) { I2C2CONbits.PEN = 1; while (I2C2CONbits.PEN){;} } void i2c_expander_init() { //Output: GP0-3 (0) //Input: GP4-7 (0xF0) i2c_expander_set(0, 0xF0); } void i2c_expander_set(char address, char value) { i2c_start(); i2c_send(SHIFTED_SLAVE_ADDRESS_OR_0); i2c_send(address); i2c_send(value); i2c_stop(); } char i2c_expander_get(char address) { char output; i2c_start(); i2c_send(SHIFTED_SLAVE_ADDRESS_OR_0); i2c_send(address); i2c_restart(); i2c_send(SHIFTED_SLAVE_ADDRESS_OR_1); output = i2c_receive(); i2c_ack(1); i2c_stop(); return output; }<file_sep>/README.md # ME433_2017 Course website for Advanced Mechatronics at NU in Spring 2017 All information is on the git wiki! https://github.com/ndm736/ME433_2017/wiki <file_sep>/HW 4/HW4.X/spi.h #ifndef SPI_H_ #define SPI_H_ void initSPI1(); void setVoltage(unsigned int channel, unsigned int voltage); char SPI1_IO(unsigned char write); #endif<file_sep>/HW 8/HW8/firmware/src/i2c.h #ifndef I2C_H__ #define I2C_H__ // Header file for i2c_master_noint.c // helps implement use I2C1 as a master without using interrupts #define SLAVE_ADDRESS 0b1101011 #define SHIFTED_SLAVE_ADDRESS SLAVE_ADDRESS << 1 #define SHIFTED_SLAVE_ADDRESS_OR_0 SHIFTED_SLAVE_ADDRESS | 0 #define SHIFTED_SLAVE_ADDRESS_OR_1 SHIFTED_SLAVE_ADDRESS | 1 #define CTRL1_XL 0x10 #define CTRL2_G 0x11 #define CTRL3_C 0x12 #define OUT_TEMP_L 0x20 #define OUTX_L_XL 0x28 #define WHO_AM_I 0x0F void i2c_init(void); void i2c_start(void); void i2c_restart(void); void i2c_send(unsigned char value); unsigned char i2c_receive(void); void i2c_receive_multiple(unsigned char reg, unsigned char *data, int length); void i2c_ack(int value); void i2c_stop(void); void i2c_expander_init(); void i2c_expander_set(char address, char value); char i2c_expander_get(char address); #endif
2b1a9ccc3f1aad2ebcbd366cec0b025e1b4bfa07
[ "Markdown", "C", "Python" ]
9
C
pabiney-msr/433-Advanced-Mechatronics
c6c0cc8ac8f307beca28a344d8a6060bfa50839a
ccc52f5b00aa876c4d8ed1be7a401a15d880dca8
refs/heads/master
<repo_name>Trotsk/txt2shp<file_sep>/txt2shp.py """This script is a successor to corners.py found here: G:\Lidar\arcGIS_tools\v10 The issue with corners.py is coordinates are converted to doubles format when creating polygon objects in arcpy causing imprecision issues. This script uses the shapely and fiona modules which manipulates vector data and reads/writes geospatial data. ArcGIS is not required. Requires Python 3.6 """ from shapely.geometry import mapping, Polygon import fiona import csv import os from pathlib import Path def tile_coordinates(text): """ group edge coordinates into tuples, returns polygon as a list """ UL = (text[1]), (text[2]) # Upper Left UR = (text[3]), (text[2]) # Upper Right LR = (text[3]), (text[4]) # Lower Right LL = (text[1]), (text[4]) # Lower Left coordinates = (UL, UR, LR, LL) return text[0], [tuple(float(x) for x in xs) for xs in coordinates] path = input('What is the full path of your text file? \n > ') # In addition to polygon geometry there is one property: tile name schema = { 'geometry': 'Polygon', 'properties': {'NAME': 'str'}, } # Input text files are delimited by multiple spaces csv.register_dialect('dialect', delimiter=' ', skipinitialspace=True) # Create and write to folder in path directory dir = Path(path).with_suffix('') if not Path.exists(dir): Path.mkdir(dir) os.chdir(dir) with fiona.open('Tile_Scheme.shp', 'w', 'ESRI Shapefile', schema) as fout: with open(path, 'r') as fin: rdr = csv.reader(fin, dialect='dialect') for row in rdr: parsed_lines = tile_coordinates(row) tile = Polygon(parsed_lines[1]) name = parsed_lines[0] fout.write({ 'geometry': mapping(tile), 'properties': {'NAME': name}, })
7e9874d7c258ed79036feaa39bd47210b8279cd9
[ "Python" ]
1
Python
Trotsk/txt2shp
aae614910697749d9038780bbd9ddccc043643f4
6c07a56b5280bd20dfd62388c76c4767bf8e97df
refs/heads/master
<repo_name>ntesh21/Graph-Data-py2neo-<file_sep>/requirements.txt astroid==2.2.5 blis==0.2.4 certifi==2019.3.9 chardet==3.0.4 Click==7.0 colorama==0.4.1 cymem==2.0.2 idna==2.8 isort==4.3.17 jsonschema==2.6.0 lazy-object-proxy==1.3.1 mccabe==0.6.1 murmurhash==1.0.2 neobolt==1.7.4 neotime==1.7.4 numpy==1.16.3 pkg-resources==0.0.0 plac==0.9.6 preshed==2.0.1 prompt-toolkit==2.0.9 py2neo==4.2.0 Pygments==2.3.1 pylint==2.3.1 pytz==2019.1 requests==2.21.0 six==1.12.0 spacy==2.1.3 srsly==0.0.5 thinc==7.0.4 tqdm==4.31.1 typed-ast==1.3.5 urllib3==1.24.2 wasabi==0.2.2 wcwidth==0.1.7 wrapt==1.11.1 <file_sep>/README.md # Graph-Data-py2neo-<file_sep>/test.py from py2neo import Graph,Node,Relationship import os # import requests import datetime #Use your NEO4J database password graph = Graph('bolt://silver-cathryn-island-ruth.graphstory.cloud:7687', auth=('silver_cathryn_island_ruth','IGyKoMerrcjVwN4CeJxJ8uqLjo7Me')) ''' Data format to make graph database with required labels and properties ''' username = '' person_id = 1 first_name = "Luis" middle_name = "" last_name = "Suarez" gender = 'male' technical_skill = ["Java","Grails","Azure"] non_technical_skill = ["Leadership","Management"] # work = { # 'id': 1, # 'user': 1, # 'job_title': 'Django Programmer', # 'organization': 'Infodev Pvt. Ltd.', # 'location': 'Kathmandu', # 'responsibilities': 'To develop django programs', # 'from_date': datetime.date(2019, 1, 1), # 'to_date': None, # 'currently_working': False # } company = { "companies": [ { 'id': 1, 'user': 1, 'job_title': 'Django Programmer', 'organization': 'Infodev Pvt. Ltd.', 'location': 'Kathmandu', 'responsibilities': 'To develop django programs', 'from_date': datetime.date(2019, 1, 1), 'to_date': None, 'currently_working': False }, { 'id': 2, 'user': 1, 'job_title': 'AI Programmer', 'organization': 'Google Pvt. Ltd.', 'location': 'California', 'responsibilities': 'To develop ML applications', 'from_date': datetime.date(2019, 6, 23), 'to_date': None, 'currently_working': True } ] } education = { "institutes": [ { 'id': 1, 'user': 1, 'program': 'Computer Engineering', 'institution': 'Harvard University', 'location': 'Harvard', 'degree': 'Masters', 'start': datetime.date(2019,1,1), 'end': None }, { 'id': 2, 'user': 1, 'program': '+2', 'institution': 'Harvard High School', 'location': 'Harvard', 'degree': 'High School', 'start': datetime.date(2015,3,1), 'end': None } ] } # ''' # Create a unique contrain on user with unique user id # ''' # graph.run('''CREATE CONSTRAINT ON (p:Person) # ASSERT p.person_id IS UNIQUE # ''') # '''Create a node person with properties # id,firstname,lastname,middlename,gender # ''' # person = Node("Person") # person['person_id'] = person_id # person['first_name'] = first_name # person['middle_name'] = middle_name # person['last_name'] = last_name # person['gender'] = gender # graph.merge(person,"Person",'person_id') # ''' # Create node technical skills # which tracks all the technical skllis possessed by user''' # tech_skills = Node("TechnicalSkills") # tech_skills['type'] = "Technical" # graph.merge(tech_skills,"TechnicalSkills","type") # for i in technical_skill: # t_skills = Node("Technical") # t_skills['skills'] = i # graph.merge(t_skills,'Technical','skills') # user_technical_skills = Relationship(person, "HAS_SKILL", t_skills) # graph.merge(user_technical_skills) # technical_skills = Relationship(t_skills, "IS", tech_skills) # graph.merge(technical_skills) # non_tech_skills = Node("NonTechnicalSkills") # non_tech_skills['name'] = "NonTechnical" # graph.merge(non_tech_skills,"NonTechnicalSkills","name") # for i in non_technical_skill: # n_skills = Node('NonTechnical') # n_skills['skills'] = i # graph.merge(n_skills,"NonTechnical",'skills') # user_non_technical_skills = Relationship(person,"HAS_SKILL",n_skills) # graph.merge(user_non_technical_skills) # non_technical_skills = Relationship(n_skills, "IS", non_tech_skills) # graph.merge(non_technical_skills) # ''' # Create a unique contrain on user work with unique work id # ''' # graph.run('''CREATE CONSTRAINT ON (w:Work) # ASSERT w.work_id IS UNIQUE # ''') # for i in company['companies']: # work_details = Node('Work') # work_details['work_id']= i['id'] # work_details['job_title']= i['job_title'] # work_details['organization'] = i['organization'] # work_details['responsibilities'] = i['responsibilities'] # work_details['from_date'] = i['from_date'] # work_details['to_date'] = i['to_date'] # work_details['currently_working'] = i['currently_working'] # graph.merge(work_details,"Work","work_id") # work_address = Node('CompanyLocation') # work_address['company_location'] = i['location'] # graph.merge(work_address,"CompanyLocation",'company_location') # user_work = Relationship(person, "WORKED_IN", work_details) # work_place = Relationship(work_details, "IS_IN", work_address) # graph.create(user_work) # graph.create(work_place) # graph.run('''CREATE CONSTRAINT ON (i:Institute) # ASSERT i.education_id IS UNIQUE # ''') # for i in education['institutes']: # college = Node('Institute') # college['education_id'] = i['id'] # college['institution'] = i['institution'] # college['degree'] = i['degree'] # college['program'] = i['program'] # college['start'] = i['start'] # college['end'] = i['end'] # graph.merge(college,"Institute","education_id") # college_location = Node('InstituteLocation') # college_location['institute_location'] = i['location'] # graph.merge(college_location,"InstituteLocation",'institute_location') # user_education = Relationship(person, "WENT_TO", college) # college_place = Relationship(college, "IS_IN", college_location) # graph.create(user_education) # graph.create(college_place) # # Make the unique job according to id # ''' # # Create a unique contrain on job with unique job id # # ''' # graph.run('''CREATE CONSTRAINT ON (j:Job) # ASSERT j.job_id IS UNIQUE # ''') # job_id = 4 # job_title = 'BI Analyst' # deadline = datetime.date(2019,5,15) # now= datetime.date.today() # days_remaining = ((deadline - now).days) # job_technical_skill = ["CC","HR","CFO","Manager","Executive"] # job_non_skill = ['Communication','Scheduling','Event Handling',"leadership"] # #Create the job with properties # job = Node("Job") # job['job_id'] = job_id # job['job_title'] = job_title # job['deadline'] = deadline # job['days_remaining'] = days_remaining # graph.merge(job,"Job",'job_title') # for j in job_technical_skill: # t_skills = Node("Technical") # t_skills['skills'] = j # graph.merge(t_skills,'Technical','skills') # job_technical_skills = Relationship(job, "REQUIRED_T_SKILL", t_skills) # graph.merge(job_technical_skills) # technical_skills = Relationship(t_skills, "IS", tech_skills) # graph.merge(technical_skills) # for j in job_non_skill: # n_skills = Node('NonTechnical') # n_skills['skills'] = j # graph.merge(n_skills,"NonTechnical",'skills') # job_non_technical_skills = Relationship(job,"REQUIRED_N_SKILL",n_skills) # graph.merge(job_non_technical_skills) # non_technical_skills = Relationship(n_skills, "IS", non_tech_skills) # graph.merge(non_technical_skills) # #If anyone applies for any job # applied = True # applied_id = 3 #application id # person_applied = 5 #id of the person who applied for the job # applied_job = 4 #id of the job which the person applied # if applied == True: # results = graph.run('''MATCH (p:Person{person_id:{person_applied}}), (j:Job{job_id:{applied_job}}) # MERGE (p)-[:APPLIED_FOR]->(j) # RETURN p,j # ''',person_applied = person_applied, applied_job = applied_job ) # # records = list(results) # #Query for recommendation # recommended_results = graph.run(''' # MATCH (p:Person) WHERE p.first_name CONTAINS 'Theon' # MATCH (j:Job) # WHERE j.days_remaining > 0 # MATCH (p)-[:HAS_SKILL]->(t_skills)<-[:REQUIRED_T_SKILL]-(j) # WHERE NOT EXISTS ((p)-[:APPLIED_FOR]->(j)) # RETURN j.job_title,j.days_remaining, # COUNT(*) AS skillsInCommon, # COLLECT(t_skills.skills) AS skills # ORDER BY skillsInCommon DESC # LIMIT 10 # ''') # recommended_records = list(recommended_results) # for row in recommended_records: # key = row.keys() # value = row.values() # print(key) # print(value) # Update the node person def update_person(person_id,first_name,middle_name,last_name,gender): graph.run('''MERGE (p:Person{person_id: {person_id}}) SET p = {person_id:{person_id},first_name:{first_name},last_name:{last_name},middle_name:{middle_name},gender:{gender}} RETURN p ''', person_id=person_id,first_name=first_name,last_name=last_name,middle_name=middle_name,gender=gender) # update_person(person_id,first_name,middle_name,last_name,gender) #Update user technical skills def update_user_technical_skill(person_id,technical_skill): graph.run('''MATCH (p:Person{person_id:{person_id}})-[r:HAS_SKILL]->(t:Technical) DELETE r ''',person_id=person_id) for i in technical_skill: t_skills = Node("Technical") t_skills['skills'] = i graph.merge(t_skills,'Technical','skills') graph.run('''MATCH (p:Person{person_id:{person_id}}),(t:Technical{skills:{i}}) MERGE (p)-[:HAS_SKILL]->(t) ''',person_id=person_id,i=i) graph.run(''' MATCH (ts:Technical{skills:{i}}),(tss:TechnicalSkills) MERGE (ts)-[:IS]->(tss) ''',i=i) # update_user_technical_skill(person_id,technical_skill) #Update user technical skills def update_user_non_technical_skill(person_id,non_technical_skill): graph.run('''MATCH (p:Person{person_id:{person_id}})-[r:HAS_SKILL]->(nt:NonTechnical) DELETE r ''',person_id=person_id) for i in non_technical_skill: n_skills = Node("NonTechnical") n_skills['skills'] = i graph.merge(n_skills,'NonTechnical','skills') graph.run('''MATCH (p:Person{person_id:{person_id}}),(n:NonTechnical{skills:{i}}) MERGE (p)-[:HAS_SKILL]->(n) ''',person_id=person_id,i=i) graph.run(''' MATCH (nts:NonTechnical{skills:{i}}),(ntss:NonTechnicalSkills) MERGE (nts)-[:IS]->(ntss) ''',i=i) # update_user_non_technical_skill(person_id,non_technical_skill) # for i in company['companies']: # company_location'] = i['location'] work = { 'id': 1, 'user': 1, 'job_title': 'Database Developer', 'organization': 'Infodev Pvt. Ltd.', 'location': 'Sanepa', 'responsibilities': 'To develop database architecture', 'from_date': datetime.date(2019, 3, 1), 'to_date': None, 'currently_working': True } print("YE",work['id']) def update_user_work(person_id,work): work_id = work['id'] title = work['job_title'] organization = work['organization'] company_location = work['location'] responsibility = work['responsibilities'] from_date = work['from_date'] to_date = work['to_date'] currently_working = work['currently_working'] graph.run('''MATCH (w:Work{work_id: {work_id}}) SET w = {work_id:{work_id},job_title:{title},organization:{organization},responsibilities:{responsibility},from_date:{from_date},to_date:{to_date},currenty_working:{currently_working}} RETURN w ''', work_id=work_id,title=title,organization=organization,responsibility=responsibility,from_date=from_date,to_date=to_date,currently_working=currently_working) graph.run('''MATCH (w:Work{work_id:{work_id}}),(l:CompanyLocation) MERGE (w)-[r:IS_IN]->(l) DELETE r ''',work_id=work_id) graph.run('''MERGE (cl:CompanyLocation {company_location:{company_location}}) ''',company_location=company_location) graph.run('''MATCH (wk:Work{work_id:{work_id}}),(clo:CompanyLocation {company_location:{company_location}}) MERGE (wk)-[r:IS_IN]->(clo) RETURN clo ''',work_id=work_id,company_location=company_location) update_user_work(person_id,work) edu = { 'id': 1, 'user': 1, 'program': 'Civil Engineering', 'institution': 'Kathmandu University', 'location': 'Kathmandu', 'degree': 'Bachelor', 'start': datetime.date(2019,3,1), 'end': None } def update_user_education(person_id,edu): education_id = edu['id'] program = edu['program'] institution = edu['institution'] institute_location = edu['location'] degree = edu['degree'] start = edu['start'] end = edu['end'] graph.run('''MATCH (i:Institute{education_id: {education_id}}) SET i = {education_id:{education_id},program:{program},degree:{degree},institution:{institution},start:{start},end:{end}} RETURN i ''', education_id=education_id,program=program,institution=institution,degree=degree,start=start,end=end) graph.run('''MATCH (i:Institute{education_id:{education_id}}),(il:InstituteLocation) MERGE (i)-[r:IS_IN]->(il) DELETE r ''',education_id=education_id) graph.run('''MERGE (il:InstituteLocation {institute_location:{institute_location}}) ''',institute_location=institute_location) graph.run('''MATCH (i:Institute{education_id:{education_id}}),(il:InstituteLocation {institute_location:{institute_location}}) MERGE (i)-[r:IS_IN]->(il) RETURN il ''',education_id=education_id,institute_location=institute_location) update_user_education(person_id,edu) # def update_user_education(person_id,education): # graph.run('''MATCH (p:Person{person_id:{person_id}})-[r:WENT_TO]->(i:Institute) # DELETE r # ''',person_id=person_id) # for i in education['institutes']: # college = Node('Institute') # college['name'] = i['name'] # name = i['name'] # college['degree'] = i['degree'] # # college['program'] = i['program'] # graph.merge(college,"Institute","name") # college_location = Node('InstituteLocation') # college_location['institute_location'] = i['location'] # location = i['location'] # graph.merge(college_location,"InstituteLocation",'institute_location') # # graph.merge(work_address,"CompanyLocation",'company_location') # graph.run('''MATCH (p:Person{person_id:{person_id}}),(c:Institute{name:{name}}) MERGE (p)-[:WENT_TO]->(c) # ''',person_id=person_id,name=name) # graph.run('''MATCH (in:Institute{name:{name}})-[r:IS_IN]->(il:InstituteLocation) # DELETE r # ''',name=name) # graph.run('''MATCH (ins:Institute{name:{name}}),(insl:InstituteLocation{institute_location:{location}}) MERGE (ins)-[:IS_IN]->(insl) # ''',name=name,location=location) # # update_user_education(person_id,education) # Update the node job def update_job(job_id,job_title,deadline,days_remaining): graph.run('''MERGE (j:Job{job_id: {job_id}}) SET j = {job_id:{job_id},job_title:{job_title},deadline:{deadline},days_remaining:{days_remaining}} RETURN j ''', job_id=job_id,job_title=job_title,deadline=deadline,days_remaining=days_remaining) # update_job(job_id,job_title,deadline,days_remaining) #Update job technical skills def update_job_technical_skill(job_id,job_technical_skill): graph.run('''MATCH (j:Job{job_id:{job_id}})-[r:REQUIRED_T_SKILL]->(t:Technical) DELETE r ''',job_id=job_id) for j in job_technical_skill: t_skills = Node("Technical") t_skills['skills'] = j graph.merge(t_skills,'Technical','skills') graph.run('''MATCH (j:Job{job_id:{job_id}}),(t:Technical{skills:{j}}) MERGE (j)-[:REQUIRED_T_SKILL]->(t) ''',job_id=job_id,j=j) graph.run(''' MATCH (ts:Technical{skills:{j}}),(tss:TechnicalSkills) MERGE (ts)-[:IS]->(tss) ''',j=j) # update_job_technical_skill(job_id,job_technical_skill) #Update job non technical skills def update_job_non_technical_skill(job_id,job_non_skill): graph.run('''MATCH (j:Job{job_id:{job_id}})-[r:REQUIRED_N_SKILL]->(nt:NonTechnical) DELETE r ''',job_id=job_id) for j in job_non_skill: n_skills = Node("NonTechnical") n_skills['skills'] = j graph.merge(n_skills,'NonTechnical','skills') graph.run('''MATCH (j:Job{job_id:{job_id}}),(nt:NonTechnical{skills:{j}}) MERGE (j)-[:REQUIRED_N_SKILL]->(nt) ''',job_id=job_id,j=j) graph.run(''' MATCH (nts:NonTechnical{skills:{j}}),(ntss:NonTechnicalSkills) MERGE (nts)-[:IS]->(ntss) ''',j=j) # update_job_non_technical_skill(job_id,job_non_skill) #Remove applied status def remove_applied_status(person_id,job_id): graph.run('''MATCH (p:Person{person_id:{person_id}})-[r:APPLIED_FOR]->(j:Job{job_id:{job_id}}) DELETE r ''',person_id=person_id,job_id=job_id) # remove_applied_status(person_id,job_id)
ed1edf689ae6fa40929beb3642c50527d59c40f1
[ "Markdown", "Python", "Text" ]
3
Text
ntesh21/Graph-Data-py2neo-
d48f1501eeff00529de767c03b31aa219275ee2f
0665f23aa42f0310396cd9dfc3310e754623359f
refs/heads/master
<repo_name>superechnik/Incrementer<file_sep>/App/Api/Controllers/IncrementController.cs using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; using MassTransit; namespace Api.Controllers { [Route("[controller]")] [ApiController] public class IncrementController : ControllerBase { readonly IBus _bus; public IncrementController(IBus bus) { _bus = bus; } /// <summary> /// Accepts body of {Key:string, Value:decimal} and sends the /// body into the rabbitMq queue /// </summary> /// <param name="kvp"></param> /// <returns></returns> [HttpPost] public async Task<IActionResult> Post([FromBody] Lib.KeyValuePair kvp) { if (!ModelState.IsValid) { return BadRequest("Please check you request body, something is not correct"); } else if (kvp.Value < 0) { return BadRequest("Did you mean /Decrement?"); } else if (kvp.Value == 0) { return Ok("This endpoint does not increment by 0"); } var endPoint = await _bus.GetSendEndpoint(new Uri("queue:kvpQueue")); try { await endPoint.Send(kvp); return Ok($"Value: {kvp.Value} has been queued for key: {kvp.Key}"); } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex); } } } } <file_sep>/App/Incrementer/Context/IncrementContext.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Incrementer.Models; namespace Incrementer.Context { public class IncrementContext : DbContext { public IncrementContext(DbContextOptions<IncrementContext> options) : base(options) { } public DbSet<KeyValue> KeyValues { get; set; } } } <file_sep>/App/Incrementer/Services/Repo.cs using Incrementer.Context; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Threading.Tasks; namespace Incrementer.Services { public class Repo : IRepo { private readonly IncrementContext _ctx; public Repo(IncrementContext ctx) { _ctx = ctx; } private async Task<Models.KeyValue> GetValue (Lib.KeyValuePair rec) { var data = await _ctx.KeyValues .Where(x => x.Key == rec.Key) .FirstOrDefaultAsync(); return data; } public async Task<Models.KeyValue> Get (Lib.KeyValuePair data) { //get current value var val = await GetValue(data); return val; } public async Task Upsert(Lib.KeyValuePair data) { //get current val var val = await GetValue(data); if (val != null) { //update val.Value += data.Value; } else { //insert var row = new Models.KeyValue() { Key = data.Key, Value = data.Value }; await _ctx.AddAsync(row); } await _ctx.SaveChangesAsync(); } } } <file_sep>/App/Incrementer/KvpConsumer.cs using MassTransit; using System.Threading.Tasks; using Incrementer.Services; namespace Incrementer { public class KvpConsumer : IConsumer<Lib.KeyValuePair> { private readonly IRepo _repo; public KvpConsumer (IRepo repo) { _repo = repo; } /// <summary> /// dequeues the value from rabbitMq and upserts into the db /// </summary> /// <param name="ctx"></param> /// <returns></returns> public async Task Consume(ConsumeContext<Lib.KeyValuePair> ctx) => await _repo.Upsert(ctx.Message); } } <file_sep>/App/Incrementer/Controllers/IncrementController.cs using Incrementer.Services; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace Incrementer.Controllers { [Route("[controller]")] [ApiController] public class IncrementController : ControllerBase { private readonly IRepo _repo; public IncrementController(IRepo repo) { _repo = repo; } /// <summary> /// Get the current value from the db. /// If being called from another controller protect against null /// </summary> /// <param name="key"></param> /// <returns></returns> [HttpGet("{key}")] public async Task<IActionResult> Get(string key) { if (key==null) { return BadRequest("you must pass a value"); } else { try { var record = new Lib.KeyValuePair(key, 0); var data = await _repo.Get(record); return Ok(data); } catch (System.Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex); } } } } } <file_sep>/README.md # Incrementer This demo application increments a number and stores it in a database in a scalable architecture. ## Installation and use `git pull` this repo `cd Incrementer/App` `docker-compose up --build` This will take a while, especially the first time when the images download. When `docker-compose` is running, you will see errors as the app tries to connect to RabbitMQ. When you see these two services (`api`, `incrementer`) reconnecting after the service `rabbit`, the app is running: ![image](https://user-images.githubusercontent.com/10968503/111924779-86f96080-8a7c-11eb-8545-b8222008ed18.png) To test that the load balancer is up, go to `http://localhost:3333` in a browser and you should see: ![image](https://user-images.githubusercontent.com/10968503/111924837-b60fd200-8a7c-11eb-9b68-18505aea2ea0.png) To use the app: `POST: http://localhost:3333/api/Increment` Body: ` { "key":string, "value":number } ` ![image](https://user-images.githubusercontent.com/10968503/111928290-89ae8280-8a89-11eb-96cc-0bc4e99d509f.png) `GET: http://localhost:3333/api/Increment/{key}` ![image](https://user-images.githubusercontent.com/10968503/111924956-42ba9000-8a7d-11eb-821c-7bb890569aa1.png) To shut down, `CTRL-C` in the `docker-compose` window and then `docker-compose down` If you want to delete all images from your machine, `docker system prune -a`. Be careful. ## Running Tests You can run the test project only if you have the .NET 5 SDK on your machine, which you can find [here](https://dotnet.microsoft.com/download/dotnet). Once you have that, to run the tests do the following: `cd ../LoadBalancer.Tests` `dotnet test -v normal` ![image](https://user-images.githubusercontent.com/10968503/111927377-dfcdf680-8a86-11eb-9f75-7b8abc36213b.png) <file_sep>/LoadBalancer.Tests/IntegrationTests.cs using System.IO; using System.Net.Http; using System.Threading.Tasks; using Xunit; using System.Text.Json; using System.Text; using Sc = System.Net.HttpStatusCode; namespace LoadBalancer.Tests { public class IntegrationTests { private readonly HttpClient _client; public IntegrationTests() { _client = new HttpClient(); } private const string Url = "http://localhost:3333/api/increment/"; private readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; [Fact] public async Task GetIsSuccess() { var response = await Get("foo"); Assert.True(response.IsSuccessStatusCode); } [Fact] public async Task PostIsSuccess() { var data = new Lib.KeyValuePair("buzz", 2); var response = await Post(data); Assert.True(response.IsSuccessStatusCode); await Task.Delay(1000); } [Fact] public async Task PostStoresDataWithin10Seconds() { //get current value var oldResponse = await Get("foo"); var oldData = await DeserializeToKvp(oldResponse); var amountToAdd = 20; //post increment 10 _ = await Post(new Lib.KeyValuePair("foo", amountToAdd)); //wait 10 seconds await Task.Delay(10000); var newResponse = await Get("foo"); var newData = await DeserializeToKvp(newResponse); var shouldBe = oldData.Value + amountToAdd; Assert.Equal(newData.Value, shouldBe); } [Fact] public async Task PostStoresDataWithin10SecondsAtAllowedLoad() { //get current value var oldResponse = await Get("foo"); var oldData = await DeserializeToKvp(oldResponse); //loop and capture amount int acc = 0, val = 20; for (int i = 0; i < 10; i++) { _ = await Post(new Lib.KeyValuePair("foo", val)); acc += val; await Task.Delay(1000); } //get new value var newResponse = await Get("foo"); var newData = await DeserializeToKvp(newResponse); var shouldBe = oldData.Value + acc; Assert.Equal(newData.Value, shouldBe); } [Fact] public async Task RateLimiterLimitsPostsToOnePerSecond() { _ = await Post(new Lib.KeyValuePair("foo", 3)); var second = await Post(new Lib.KeyValuePair("foo", 4)); await Task.Delay(1500); Assert.Equal(Sc.TooManyRequests, second.StatusCode); await Task.Delay(1000); } [Fact] public async Task RateLimiterAllowsPostsAtLimit() { _ = await Post(new Lib.KeyValuePair("foo", 3)); await Task.Delay(1000); var second = await Post(new Lib.KeyValuePair("foo", 4)); Assert.True(second.IsSuccessStatusCode); await Task.Delay(1000); } [Fact] public async Task KeyAndValueAreRequired() { var bodyMissingKey = new StringContent(JsonSerializer.Serialize(new { Value = "Hello" }), Encoding.UTF8, "application/json"); var bodyMissingValue = new StringContent(JsonSerializer.Serialize(new { Key = 3 }), Encoding.UTF8, "application/json"); var missingKey = await _client.PostAsync(Url, bodyMissingKey); await Task.Delay(1000); var missingValue = await _client.PostAsync(Url, bodyMissingValue); await Task.Delay(1000); var missingAll = await _client.PostAsync(Url,null); await Task.Delay(1000); Assert.True( !missingKey.IsSuccessStatusCode && !missingValue.IsSuccessStatusCode && !missingAll.IsSuccessStatusCode ); } private async Task<HttpResponseMessage> Get(string key) => await _client.GetAsync(Path.Combine(Url, key)); private async Task<HttpResponseMessage> Post(Lib.KeyValuePair kvp) { var content = new StringContent(JsonSerializer.Serialize(kvp), Encoding.UTF8, "application/json"); return await _client.PostAsync(Url, content); } private async Task<Lib.KeyValuePair> DeserializeToKvp(HttpResponseMessage msg) => JsonSerializer.Deserialize<Lib.KeyValuePair>(await msg.Content.ReadAsStringAsync(), JsonOptions); } } <file_sep>/App/Lib/KeyValuePair.cs namespace Lib { public record KeyValuePair(string Key, decimal Value); } <file_sep>/App/LoadBalancer/Dockerfile FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base WORKDIR /app EXPOSE 3333 ENV ASPNETCORE_URLS=http://*:3333 FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build WORKDIR /src COPY ["LoadBalancer/LoadBalancer.csproj", "LoadBalancer/"] RUN dotnet restore "LoadBalancer/LoadBalancer.csproj" COPY . . WORKDIR "/src/LoadBalancer" RUN dotnet build "LoadBalancer.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "LoadBalancer.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "LoadBalancer.dll"]<file_sep>/App/Incrementer/Dockerfile FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base WORKDIR /app EXPOSE 3100 ENV ASPNETCORE_URLS=http://*:3100 FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build WORKDIR /src COPY ["Incrementer/Incrementer.csproj", "Incrementer/"] RUN dotnet restore "Incrementer/Incrementer.csproj" COPY . . WORKDIR "/src/Incrementer" RUN dotnet build "Incrementer.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "Incrementer.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "Incrementer.dll"]<file_sep>/App/Incrementer/Startup.cs using Incrementer.Context; using MassTransit; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using GreenPipes; using Incrementer.Services; namespace Incrementer { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped<IRepo, Repo>(); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Incrementer", Version = "v1" }); }); string pgConnString = Configuration.GetSection("ConnectionStrings")["Postgres"]; services.AddEntityFrameworkNpgsql() .AddDbContext<IncrementContext>(ops => ops.UseNpgsql(pgConnString)); services.AddMassTransit(x => { x.AddConsumer<KvpConsumer>(); x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg => { cfg.UseHealthCheck(provider); cfg.Host("rabbit", h => { h.Username("guest"); h.Password("<PASSWORD>"); }); cfg.ReceiveEndpoint("kvpQueue", e => { e.PrefetchCount = 16; e.UseMessageRetry(r => r.Immediate(5)); e.ConfigureConsumer<KvpConsumer>(provider); }); })); }); services.AddMassTransitHostedService(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IncrementContext ctx) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Incrementer v1")); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); ctx.Database.Migrate(); } } } <file_sep>/App/Incrementer/Services/IRepo.cs using System.Threading.Tasks; namespace Incrementer.Services { public interface IRepo { public Task Upsert(Lib.KeyValuePair kvp); public Task<Models.KeyValue> Get(Lib.KeyValuePair kvp); } }
dd12c68803a272338a7a91ae1319b83884d963e6
[ "Markdown", "C#", "Dockerfile" ]
12
C#
superechnik/Incrementer
ce46e907266d4096d3fb5ff2587e976678296f38
83efa49fa7312f73236c61456c6ba5fc4edebbd5
refs/heads/master
<repo_name>summerzh/DragDetailLayout<file_sep>/README.md # DragDetailLayout 仿京东商品详情页面上拉进入详情. * 控件继承自ViewGroup,上下两个页面没有使用ScrollView,而是使用了两个Fragment,更方便的控制生命周期. * 支持WebView,ListView,RecyclerView以及ViewPager * 分别提供两种实现方案:Scroller实现和ViewDragHeler实现.并且ViewDragHelper实现的方案支持滑动阻尼效果. <file_sep>/app/src/main/java/com/it/dragdetaillayout/MainActivity.java package com.it.dragdetaillayout; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.util.Log; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DragDetailLayout2 dragDetailLayout2 = (DragDetailLayout2) findViewById(R.id.dl_container); Log.d("result", "onCreate "); FragmentManager manager = getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); transaction.replace(R.id.fl_top, TopFragment.getInstance(dragDetailLayout2)); transaction.replace(R.id.fl_bottom, new BottomFragment()); transaction.commit(); } }
d0c71d20109a09a4d66fb4712f7a0238580af622
[ "Markdown", "Java" ]
2
Markdown
summerzh/DragDetailLayout
fe47d2df1d65dafae9f5f8eb80fda94c28d95190
c8ad4d82a20690e3c5410ef43cbf7317bf095d02
refs/heads/master
<file_sep>import { connect, connection } from 'mongoose' import { MongoMemoryServer } from 'mongodb-memory-server' // List your collection names here const COLLECTIONS = [] class DBManager { constructor () { this.db = null this.server = new MongoMemoryServer() this.connection = null } async start () { const url = await this.server.getConnectionString() connect(url, { useNewUrlParser: true }) this.db = connection } stop () { this.connection.close() return this.server.stop() } cleanup () { return Promise.all(COLLECTIONS.map(c => this.db.collection(c).remove({}))) } } module.exports = new DBManager() <file_sep>import { Schema, model } from 'mongoose' import paginate from 'mongoose-paginate' const ObjectId = require('mongoose').Types.ObjectId const commentSchema = new Schema({ context: { type: String, required: true }, article_id: { type: ObjectId, required: true }, author_id: { type: ObjectId, required: true }, created_at: { type: Date, default: Date.now }, updated_at: { type: Date, default: Date.now } }) commentSchema.pre('findByIdAndUpdate', async function(next){ await this.updateOne({},{updated_at: new Date()}) next() }) commentSchema.plugin(paginate) export default model('Comment', commentSchema) <file_sep>import Comment from '../models/Comment' import redis from 'async-redis' const client = redis.createClient() const ObjectId = require('mongoose').Types.ObjectId client.on("error", err => console.log("Error " + err)) // comment can only be altered and inserted by user that created the comment class CommentController { async index (req, res) { const { limit = 20, page = 1 } = req.query delete req.query.limit delete req.query.page const filters = req.query || {} const cache = await client.get(`comments?page=${page},limit=${limit}`) if(cache) { return res.status(200).json(JSON.parse(cache)) } else{ const docs = await Comment.paginate(filters, { limit: parseInt(limit), page: parseInt(page), sort: '-created_at' }) client.set(`comments?page=${page},limit=${limit}`,JSON.stringify(docs)) client.expire(`comments?page=${page},limit=${limit}`, 20); return res.status(200).json(docs) } } async show (req, res) { return res.status(200).json(await Comment.findById(req.params.id)) } async store (req, res) { const doc = await Comment.create(req.body) return res.status(201).json(doc) } async update (req, res) { return res.status(200).json({ doc: await Comment.findByIdAndUpdate(req.params.id, req.body, { new: true }) }) } async destroy (req, res) { await Comment.findOneAndDelete({ _id: ObjectId(req.params.id), author_id: req.userId }) return res.status(200).send() } } module.exports = new CommentController() <file_sep>import '@babel/polyfill' import auth from '../../../src/app/middlewares/auth' let request; let response; process.env.APP_SECRET="$2a$10<KEY>" describe('Unit Test for Middleware Auth', () => { beforeEach(() => { request = { headers:{ Accept: "application/json" } } response = { status: function (code) { this.statusCode = code return this }, json: function (data) { this.resp = data } } }) afterEach(() => { request = {}; response= {}; }); it('Auth with no headers', async () => { await auth(request,response,null) expect(response.statusCode).toBe(401) }) it('Auth with wrong code', async() => { request.headers.authorization = 'Bearer <PASSWORD>' await auth(request,response,null) expect(response.resp.error).toBe("Invalid Token") }) }) <file_sep>import Article from '../models/Article' import redis from 'async-redis' const client = redis.createClient() client.on("error", err => console.log("Error " + err)) class ArticleController { async index (req, res) { const { limit = 20, page = 1 } = req.query delete req.query.limit delete req.query.page const filters = req.query || {} const cache = await client.get(`articles?page=${page},limit=${limit}`) if(cache) { return res.status(200).json(JSON.parse(cache)) } else{ const docs = await Article.paginate(filters, { limit: parseInt(limit), page: parseInt(page), sort: '-created_at' }) client.set(`articles?page=${page},limit=${limit}`,JSON.stringify(docs)) client.expire(`articles?page=${page},limit=${limit}`, 20); return res.status(200).json(docs) } } async show (req, res) { return res.status(200).json(await Article.findById(req.params.id)) } async store (req, res) { if(req.body.authors.length===0) return res.status(403).json({error: "The article has to at least 1 author"}) const doc = await Article.create(req.body) return res.status(201).json(doc) } async update (req, res) { return res.status(200).json({ doc: await Article.findByIdAndUpdate(req.params.id, req.body, { new: true }) }) } async destroy (req, res) { await Article.findOneAndDelete(req.params.id) return res.status(200).send() } } module.exports = new ArticleController() <file_sep>import '@babel/polyfill' import dbman from '../../../src/config/mongodb_test'; import CommentController from '../../../src/app/controllers/CommentController' import CommentModel from '../../../src/app/models/Comment' const ObjectId = require('mongoose').Types.ObjectId let request; let response; describe("Integration Test for Comment Controller", ()=> { afterAll(async () => { await dbman.stop(); }); beforeAll(async () => { await dbman.start(); }); beforeEach(()=> { request = { headers:{ Accept: "application/json" }, body:{}, params: {}, query: {} } response = { status: function (code) { this.statusCode = code return this }, json: function (data) { this.resp = data }, send: () => true } }) afterEach(async () => { await dbman.cleanup(); }); const body = { context: "Comment test", author_id: ObjectId("abcdefghijkl"), article_id: ObjectId("abcdefghijkl") } it("STORE Comment", async ()=>{ request.body = body await CommentController.store(request,response) expect(response.resp.context).toBe("Comment test") }) it("SHOW Comments", async () =>{ request.query = {} await CommentController.index(request,response) expect(response.resp.docs.length).toBe(1) }) it("UPDATE Comment", async () => { const comments = await CommentModel.find({}) request.params.id = comments[0]._id await CommentController.update(request,response) expect(response.resp.doc.context).toBe("Comment test") }) it("DELETE Comment", async () => { const comments = await CommentModel.find({}) request.params.id = comments[0]._id const res = await CommentController.destroy(request,response) expect(res).toBeTruthy() }) }) <file_sep>import redis from 'redis' const { env } = process module.exports = redis.createClient(env.REDIS_PORT, env.REDIS_HOST) <file_sep># Javascript API Rest ## Descrição API RESTFULL para um sistema de blog. ## Initial env Settings execute `$ yarn` va para src/config/env/ copie e renomeie arquivo .env.example para .env execute `$ yarn appSecretGenerate segredo` , copie o hash para dentro da variável APP_SECRET dentro do arquivo .env ## Configuração do banco NoSQL (MongoDB) [Site Oficial do MongoDB](https://www.mongodb.com/download-center/community) - Siga as instruções para baixar e instalar o banco na sua máquina local; - execute `$ mongo` no terminal para iniciar o shell do mongo - execute o comandos a seguir dentro do shell do mongo `use database_name` - `db.create({user: "username",pwd:"<PASSWORD>",roles:"readWrite",db:"databasename"})`, lembre-se de trocar os valores de `username`,`pwd` e `databasename` - Agora instancie as credencias do mongodb dentro do arquivo .env nas respectivas variaveis do banco ## Configuração do Redis [Redis Server](https://redis.io/download) - Baixe e configure o redis na sua maquina local - Instacie o arquivo .env com as credenciais (Obs: O .env.example já possui as credencias padrões) ## Iniciar o modo desenvolvedor Execute `$ yarn dev` ## Construir e Executar o servidor de produção Execute `$ yarn prod` ## Rodar os testes unitários e integrados Execute `$ yarn test` ## Instruções para operar a aplicação Usando de um client REST (Insomnia, Postman, etc...), construa requisições para cada entidade (Artigo, Comentário e Autor) usando cada método (GET, POST, PUT, DELETE) e um POST Request de sessão para ativar o jsonwebtoken baseURL = "http://localhost:3000" ### STORE Autor { url: baseURL/authors, method: POST, data:{ name: string, email: string, password: string } } ### Listagem de Autores { url: baseURL/authors, method: GET } ### Busca de Autor por id { url: baseURL/authors/:id, method: GET } ### UPDATE Autor { url: baseURL/authors/:id, method: PUT, data:{ name: string, email: string, password: string } } ### DELETE Autor { url: baseURL/authors/:id, method: DELETE, } ### Listagem de Artigos { url: baseURL/articles, method: GET } ### Busca de Artigo por Id { url: baseURL/articles/:id, method: GET } ### STORE Artigo { url: baseURL/articles, method: POST, data:{ title: string, subTitle: string, context: string, authors:[ AuthorIdA, AuthorIdB, etc... ] } } ### UPDATE Artigo { url: baseURL/articles/:id, method: PUT, data:{ title: string, subTitle: string, context: string, authors:[ AuthorIdA, AuthorIdB, etc... ] } } ### DELETE Artigo { url: baseURL/articles/:id, method: DELETE, } ### Listagem de Comentário { url: baseURL/comments, method: GET } ### Busca de Comentário por Id { url: baseURL/comments/:id, method: GET } ### STORE Comentário { url: baseURL/comments, method: POST, data:{ context: string } } ### UPDATE Comentário { url: baseURL/comments/:id, method: PUT, data:{ context: string } } ### DELETE Comentário { url: baseURL/comments/:id, method: DELETE, headers: { authorization: string } } Obs: Para deletar o comentário deve ser repassado um jwt gerado pela rota /sessions abaixo ### GET JWT TOKEN SESSION { url: baseURL/sessions method: POST, data:{ "email": string, "password": string } } Após a requisição de sessão, será enviado os dados do autor mais um token de authenticação, a autenticação utiliza do protocolo de Bearer Token no headers da requisição. ex: headers: { authentication: "Bearer Token" } Somente a autenticação do autor em que o comentário foi registrado que poderá apagar o comentário ## Lista de TODOS do desafio :heavy_check_mark: Todos os endpoints de listagem devem ter paginação. - Basta passar page como parametro dentro da url para acessar as páginas :heavy_check_mark: Um artigo guarda informações sobre título, subtítulo, data de publicaçnao, data de última atualização, conteúdo do artigo, autor e permalink. :heavy_check_mark: O permalink do artigo deve ser único. :heavy_check_mark: Um artigo contém obrigatoriamente um autor. :heavy_check_mark: Bônus: Buscar comentários de um artigo específico. - Incluido além da busca por artigo específico, adicionei qualquer busca por filtro de atributo ainda seguindo o mesmo padrão de parâmetro na url em todos os endpoints de listagem :heavy_check_mark: Bônus: Possibilidade de passar por parâmetro a quantidade de itens por página - Seguindo o mesmo padrão de parâmetro no método GET o limite pode ser passado como parâmetro na url :heavy_check_mark: Bônus: Possibilidade de buscar um artigo por permalink. :heavy_check_mark: Bônus: Criação de testes - Fiz apenas alguns testes unitários e de integração que me auxiliaram na construção da aplicação. :heavy_check_mark: Bônus: Utilização de cache - Apliquei o banco de cache Redis para trabalhar nos endpoints de listagem para acelerar o desempenho das buscas. :heavy_check_mark: Bônus: Faça uma autenticação para usuário com JWT, permitindo o mesmo deletar seus comentários em uma postagem. - A autenticação é feita no endpoint de sessions que expliquei previamente para poder apagar os comentários. :x: Tratamento de erros - Fiz um tratamento básico de erros, mas não cobri todos os cenários possiveis. <file_sep>import '@babel/polyfill' import dbman from '../../../src/config/mongodb_test'; import AuthorController from '../../../src/app/controllers/AuthorController' import Author from '../../../src/app/models/Author' let request; let response; describe("Integration Test for Author Controller", ()=> { afterAll(async () => { await dbman.stop(); }); beforeAll(async () => { await dbman.start(); }); beforeEach(()=> { request = { headers:{ Accept: "application/json" }, body:{}, params: {}, query: {} } response = { status: function (code) { this.statusCode = code return this }, json: function (data) { this.resp = data }, send: () => true } }) afterEach(async () => { await dbman.cleanup(); }); const body = { name: "<NAME>", email: "<EMAIL>", password: "123" } it("STORE Author", async ()=>{ request.body = body await AuthorController.store(request,response) expect(response.resp.name).toBe("<NAME>") }) it("SHOW Authors", async () =>{ request.query = {} await AuthorController.index(request,response) expect(response.resp.docs.length).toBe(1) }) it("UPDATE Author", async () => { const articles = await Author.find({}) request.params.id = articles[0]._id await AuthorController.update(request,response) expect(response.resp.doc.name).toBe("<NAME>") }) it("DELETE Author", async () => { const authors = await Author.find({}) request.params.id = authors[0]._id const res = await AuthorController.destroy(request,response) expect(res).toBeTruthy() }) }) <file_sep>import { Schema, model } from 'mongoose' import { sign } from 'jsonwebtoken' import paginate from 'mongoose-paginate' const bcrypt = require('bcryptjs') const authorSchema = new Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true, lowercase: true }, password: { type: String, required: true }, created_at: { type: Date, default: Date.now }, updated_at: { type: Date, default: Date.now } }) authorSchema.pre('save', async function (next) { if (!this.isModified('password')) return next() this.password = await bcrypt.hash(this.password, 10) }) authorSchema.methods.compareHash = function (password) { return bcrypt.compare(password, this.password) } authorSchema.statics.generateToken = function ({ id }) { return sign({ id }, process.env.APP_SECRET, { expiresIn: 86400 }) } authorSchema.plugin(paginate) export default model('Author', authorSchema) <file_sep>import '@babel/polyfill' import { config } from 'dotenv' config({ path: 'src/config/env/.env' }) const server = require('./config/server.js') server.listen(process.env.PORT || 3000, () => { console.log( `Server is running on ${ process.env.NODE_ENV } environment on uri http://localhost:${process.env.PORT || 3000}` ) })
4764c40c729a654630000b6c2fac4bd675bef5bc
[ "JavaScript", "Markdown" ]
11
JavaScript
cunhapatrick/Blog-API
b93d3b5115d443ffbda4dcad7d2cc848f1756c05
ff90b4ca2493cb21b65c25fff3dae82ae067894d
refs/heads/master
<repo_name>SquirrelMobile/titanium-template-native-tabgroup<file_sep>/app/controllers/partials/_menu.js /** * @class Controller.partials._menu * Display menu view * */ var currentTab = null; var objTab = {}; (function constructor(args){ _.each(args.menu, function(m){ objTab[m.controller] = Alloy.createController('/partials/_tab', m); $.menu.add(objTab[m.controller].getView()); if(m.id === args.currentController){ objTab[m.controller].enable(); } }); })($.args); function handleClick(e){ var s = e.source, type = s.type; if(type === "menu" || type === "view"){ $.trigger('click', { controller : s.controller, type : type, id : s.idMenu, submenu : true }); if(type === 'menu'){ if(currentTab){ if(objTab[currentTab]){ objTab[currentTab].disable(); } } currentTab = s.controller; if(objTab[s.controller]){ objTab[s.controller].enable(); } } } } <file_sep>/app/controllers/partials/headerExample.js var champs = $.form.getChamps(); champs.filter.faketextField.addEventListener("change", function(e) { e.row["id"] = "filter"; var data = e; $.trigger("change", data); }); champs.style.faketextField.addEventListener("change", function(e) { e.row["id"] = "style"; var data = e; $.trigger("change", data); }); <file_sep>/app/controllers/partials/_navbar.js /** * @class Controller.partials._navbar * Create a _navbar */ /** * @method Controller * Create a _navbar view * @param {Object} args Arguments passed to the controller */ (function constructor(args) { if (args) { load(args); } })($.args); /** * actions - description * * @param {type} e description * @return {type} description */ function actions(e) { $.trigger("click", { type: e.source.type }); } function load(conf) { if (conf.nav) { $.nav.applyProperties(conf.nav); if (conf.nav.backgroundColor) { $.container.backgroundColor = conf.nav.backgroundColor; } } if (conf.btnLeft) { $.btnLeft.applyProperties(conf.btnLeft); } if (conf.btnRight) { $.btnRight.applyProperties(conf.btnRight); } if (conf.logo) { $.logo.applyProperties(conf.logo); } if (conf.title) { $.title.applyProperties(conf.title); } } /** * load - description * * @param {type} conf description * @return {type} description */ $.load = load; <file_sep>/app/controllers/logout.js // Arguments passed into this controller can be accessed via the `$.args` object directly or: var args = $.args; <file_sep>/app/controllers/dashboard.js // Arguments passed into this controller can be accessed via the `$.args` object directly or: var args = $.args; var currentController = null; var objTab = { tab1: $.tab1, tab2: $.tab2, }; (function constructor(args) { if (OS_ANDROID) { $.tabGroup.addEventListener("androidback", function() {}); } else { $.tabGroup.hideNavBar(); } Alloy.Globals.events.off("popToRootWindow"); Alloy.Globals.events.off("openWindowInTab"); })(args); function closeToRoot() { $.tabGroup.activeTab.popToRootWindow(); } Alloy.Globals.events.on("popToRootWindow", closeToRoot); function openWindow(o) { var tab = $.tabGroup.activeTab; _.defaults(o, { data: {}, controller: null, dispatcher: null, openOutSideTab: false, modalOpts: {}, }); var win = Alloy.createController(o.controller, o.data); var currentWin = win.getView(); function close() { if (currentWin) { if (o.openOutSideTab) { currentWin.close(); } else { if (OS_IOS) { tab.close(currentWin); } else { currentWin.close(); } } currentWin = null; } if (win) { win.off("close"); } win = null; } win.on("close", close); win.on("select", function(e) { if (o.dispatcher) { Alloy.Globals.events.trigger(o.dispatcher, e); } close(); }); if (currentController !== o.controller) { if (o.openOutSideTab) { currentWin.open(o.modalOpts); } else { tab.open(currentWin); } } if (o.controller === "win") { currentController = o.data.controller; } else { currentController = o.controller; } } Alloy.Globals.events.on("openWindowInTab", openWindow); function changeTab(e) { if (e.idMenu === "logout") { logout(); } else if (objTab[e.idMenu]) { $.tabGroup.activeTab = objTab[e.idMenu]; } } function handleOpen(e) {} <file_sep>/app/controllers/index.js /** * @class Controller.index * Display index view * */ /** * @method Controller * Display index view, load dashboard or login * @param {Arguments} args Arguments passed to the controller */ (function constructor(args) { if (Ti.App.Properties.getBool("isConnected")) { Alloy.createController("dashboard") .getView() .open(); } else { Alloy.createController("login/login", args) .getView() .open(); } })($.args);
495e0243e5c9cc33a0307b4ca842525c7894127f
[ "JavaScript" ]
6
JavaScript
SquirrelMobile/titanium-template-native-tabgroup
38fa6d17b9738f7700f658b91901fa0987677bd9
3e3a7be6b92ad56420a0de4e36bec5c4e10f055a