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>adamtracy/env<file_sep>/.bash_profile export SVN_ROOT="svn://svn.ev.affymetrix.com" export JAVA_HOME=`/usr/libexec/java_home` export ANT_HOME=$HOME/apache-ant-1.8.2 export HADOOP_HOME=$HOME/hadoop-0.20.2 export PATH=$HADOOP_HOME/bin:$PATH export PATH=/Developer/usr/bin:$PATH export PATH=$HOME/bin:$PATH alias ll='ls -trl' alias port_fwd_rdesk='affy-http-proxy -lp 3389 -rp 3389 -rh W7DC82V1VR1.affymetrix.com na2.affymetrix.com' ## # Your previous /Users/adamtracy/.bash_profile file was backed up as /Users/adamtracy/.bash_profile.macports-saved_2014-03-10_at_13:47:53 ## # MacPorts Installer addition on 2014-03-10_at_13:47:53: adding an appropriate PATH variable for use with MacPorts. export PATH=/opt/local/bin:/opt/local/sbin:$PATH # Finished adapting your PATH environment variable for use with MacPorts.
113a44d1cf7c3370cc1cefc4ffa562139c9879dc
[ "Shell" ]
1
Shell
adamtracy/env
1e4dced04990ff0fb3d92a99026085644aa46e8c
4dccee1a3b01172533f9f65a6382428d16f69097
refs/heads/master
<repo_name>nikhilesh2/twilio<file_sep>/public/js/app.js var myApp = angular.module('myApp', [ 'ngRoute', 'ui.bootstrap']). config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){ $routeProvider.when('/profile', {templateUrl: 'partials/profile.html', controller: 'profileController'}); $routeProvider.when('/submit', {templateUrl: 'partials/submit.html', controller: 'submitController'}); $routeProvider.when('/dailydose', {templateUrl: 'partials/dailydose.html', controller: 'dailydoseController'}); $routeProvider.otherwise({redirectTo: '/dailydose'}); $locationProvider.html5Mode({enabled: true, requireBase: false}); }]); <file_sep>/public/MainController.js app.controller("MainController", function($scope, $http) { var pat = null; var body = "teeest"; var customNum = null; $http.get('Public/worked.json').success(function(data) { $scope.patients = data; patient = $scope.patients; }).error(function(error){ alert(error); }); var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); $('#calendar').fullCalendar({ editable: true, weekMode: 'liquid', url:'#', events: [ { title: 'TESTING', start: new Date(y, m, 1, 9, 00), end: new Date(y, m, 1, 10, 00), allDay: false }, { title: 'Vestibulum iaculis lacinia', start: new Date(y, m, 2, 16, 00), allDay: false }, { title: 'Integer rutrum ante eu lacus', start: new Date(y, m, 4, 16, 00), allDay: false }, { title: 'Aliquam erat volpat. Duis ac turpis', start: new Date(y, m, 9, 16, 00), allDay: false }, { title: 'Donec in velit vel ipsum', start: new Date(y, m, 10, 16, 00), allDay: false }, { title: 'Praent vestibulum', start: new Date(y, m, 13, 9, 00), allDay: false }, { title: 'Vestibulum iaculis lacinia', start: new Date(y, m, 15, 16, 00), allDay: false }, { title: 'Integer rutrum ante eu lacus', start: new Date(y, m, 17, 16, 00), allDay: false }, { title: 'nteger rutrum ante eu lacusi', start: new Date(y, m, 18, 16, 00), allDay: false }, { title: 'Integer rutrum ante eu lacus', start: new Date(y, m, 19, 16, 00), allDay: false }, { title: 'Integer rutrum ante eu lacus', start: new Date(y, m, 23, 16, 00), allDay: false }, { title: 'nteger rutrum ante eu lacus', start: new Date(y, m, 24, 16, 00), allDay: false }, { title: 'Integer rutrum ante eu lacus', start: new Date(y, m, 27, 16, 00), allDay: false }, { title: 'Integer rutrum ante eu lacus', start: new Date(y, m, 28, 16, 00), allDay: false }, { title: 'Vestibulum iaculis lacinia', start: new Date(y, m, 29, 16, 00), allDay: false }, { title: 'Praent vestibulum', start: new Date(y, m, 30, 9, 00), allDay: false } ] }); $scope.post = function($index) { $( "#button-" + $index ).transition({ scale: 1.03 }, 100, function() { }); $( "#button-" + $index ).transition({ scale: 1.0 }, 100, function() { }); body = "Hello " ; var myEl = angular.element( document.querySelector( '#item-' + $index ) ); myEl.text('yes'); // var myEl2 = angular.element( document.querySelector( '#button-' + $index ) ); // myEl2.text('Reminder sent'); $http.get('/testtwilio', {params: {id: patient[$index].id, name: patient[$index].name, number: patient[$index].number, date: patient[$index].date, body: body, reminded: "yes"}}) // PASS THE DATA AS THE SECOND PARAMETER .success( function(success){ console.log(success) }) .error( function(error){ console.log("error" + error) }); $http.post('/testtwilio'). success(function(data) { console.log("posted successfully"); }).error(function(data) { console.error(error); }) } $scope.deleteName = function($index){ var patient = { id: $scope.patients[$index].id, name: $scope.patients[$index].name, date: $scope.patients[$index].date, number:$scope.patients[$index].number } $http.get('/testtwilio3', {params: {id: patient.id, name: patient.name, number: patient.number, date: patient.date}}) // PASS THE DATA AS THE SECOND PARAMETER .success( function(success){ console.log(success) }) .error( function(error){ console.log("error" + error) }); $scope.patients.splice($index, 1); // $.notify({ // icon: 'pe-7s', // message: "Patient has been deleted" // },{ // type: 'success', // timer: 10 // }); } $scope.addName = function() { name = $scope.input; date = $scope.input3; number = $scope.input2; $http.get('/testtwilio2',{params: {name: name, number:number, date: date, reminded:'no'}}) // PASS THE DATA AS THE SECOND PARAMETER .success( function(data){ $scope.id = data; var patient = { id:$scope.id, name:name, date:date, number:number, reminded:'no' } $scope.patients.push(patient); $.notify({ icon: 'pe-7s', message: "Patient has been added" },{ type: 'success', timer: 10 }); }) .error( function(error){ console.log("error" + error); }); }; // $scope.ngRepeatFinish = function($index){ // alert($index); // $('.sendreminder').click(function(e){ // $( "#req-" + $index ).transition({ // scale: 1.1 // }, 100, function() { // }); // $( "#req-" + $index ).transition({ // scale: 1.0 // }, 100, function() { // }); // }); // } }); // $scope.returnPat = function($index){ // var name = angular.element(document.querySelector( '.theName' ) ); // name.text($scope.patients[$index].name); // var num = angular.element(document.querySelector( '.theNum' ) ); // num.text($scope.patients[$index].number); // var date = angular.element(document.querySelector( '.theDate' ) ); // date.text($scope.patients[$index].date); // customNum = $scope.patients[$index].number; // } // $scope.passPrompt = function($index){ // //var password = prompt("Sending a custom Message requires an adminstrative permission. Please type in the password to continue."); // body = $scope.body; // $http.get('/testtwilio4', {params: {body: body, num: customNum}}) // PASS THE DATA AS THE SECOND PARAMETER // .success( // function(success){ // console.log(success) // }) // .error( // function(error){ // console.log("error" + error) // }); // $http.post('/testtwilio4'). // success(function(data) { // console.log("posted successfully"); // }).error(function(data) { // console.error(error); // }) // } <file_sep>/app/routes/api.js var fs = require('fs'); // var S3FS = require('s3fs'), // s3fsImpl = new S3FS('brenttestbucket123', { // accessKeyId: '<KEY>', // secretAccessKey: '<KEY> // }); // var multiparty = require('connect-multiparty'), // multipartyMiddleware = multiparty(); // Create our bucket if it doesn't exist // s3fsImpl.create(); module.exports = function(router, passport){ // router.use(multipartyMiddleware); router.use(passport.authenticate('bearer', { session: false })); router.use(function(req, res, next){ fs.appendFile('logs.txt', req.path + " token: " + req.query.access_token + "\n", function(err){ next(); }); }); // router.post('/testupload', function (req, res) { // var file = req.files.file; // var stream = fs.createReadStream(file.path); // return s3fsImpl.writeFile(file.originalFilename, stream).then(function () { // fs.unlink(file.path, function (err) { // if (err) { // console.error(err); // } // }); // res.redirect('/profile'); // }); // }); router.get('/testAPI', function(req, res){ res.json({ SecretData: 'abc123' }); }); }<file_sep>/public/tablejquery.js $(function(){ $('.test').on('click',function(){ alert('pressed'); }) $('.addpatient').on('click', function(){ $('.addPat').toggleClass('open'); }); $('.cancel').on('click', function(){ $('.addPat').toggleClass('open'); $('.box1').val(''); $('.box2').val(''); //$('.box3').val(''); }); $('.delete2').on('click',function(){ }) $('.button').on('click', function(){ var text = $('.box1').val() var text2 = $('.box2').val() var text3 = $('.box3').val() if(text === '' || text2 === '' || text3 === ''){ }else{ $('.addPat').toggleClass('open'); $('.box1').val(''); $('.box2').val(''); $('.box3').val(''); $('.button').addClass('disabled'); } }); $('.box1').blur(function(){ if( !$(this).val() ||!$('.box2').val() || !$('.box3').val() ) { $('.button').addClass('disabled'); }else{ $('.button').removeClass("disabled"); } }); $('.box2').blur(function(){ if( !$(this).val() ||!$('.box1').val() || !$('.box3').val() ) { $('.button').addClass('disabled'); }else{ $('.button').removeClass("disabled"); } }); $('.box3').blur(function(){ if( !$(this).val() ||!$('.box1').val() || !$('.box2').val() ) { $('.button').addClass('disabled'); }else{ $('.button').removeClass("disabled"); } }); $('.box3').keypress(function(event) { if( !$(this).val() ||!$('.box1').val() || !$('.box2').val() ) { $('.button').addClass('disabled'); }else{ $('.button').removeClass("disabled"); } }); $("#file").change(function () { $("#form").submit(); $.notify({ icon: 'pe-7s', message: "File uploaded. Please refresh to update page" },{ type: 'info', timer: 10 }); }); $('.upload').on('click', function(){ $('.choosefile').click(); }); }); <file_sep>/public/jquery.js $(function(){ $('#wrapper').on('click','a', function() { alert("CLICKED"); //$.post('/testtwilio'); /* Act on the event */ }); $('.box1').blur(function(){ if( !$(this).val() ||!$('.box2').val() || !$('.box3').val() ) { $('.button').addClass('disabled'); }else{ $('.button').removeClass("disabled"); } }); $('.box2').blur(function(){ if( !$(this).val() ||!$('.box1').val() || !$('.box3').val() ) { $('.button').addClass('disabled'); }else{ $('.button').removeClass("disabled"); } }); $('.box3').blur(function(){ if( !$(this).val() ||!$('.box1').val() || !$('.box2').val() ) { $('.button').addClass('disabled'); }else{ $('.button').removeClass("disabled"); } }); $('.box3').keypress(function(event) { if( !$(this).val() ||!$('.box1').val() || !$('.box2').val() ) { $('.button').addClass('disabled'); }else{ $('.button').removeClass("disabled"); } }); $('.card').on('click', function(){ $('.main-navigation').toggleClass('open'); $('.button').addClass('disabled'); }); $('.button').on('click', function(){ var text = $('.box1').val() var text2 = $('.box2').val() var text3 = $('.box3').val() if(text === '' || text2 === '' || text3 === ''){ }else{ $('.main-navigation').toggleClass('open'); $('.box1').val(''); $('.box2').val(''); $('.box3').val(''); $('.button').addClass('disabled'); } }); $('.names').on('click', ".name2",function(e){ $('.infocard').fadeIn("fast"); $('.side-navigation').removeClass('open'); //angular.element('#MainController').scope().returnPat(); }); $('.send').on('click', function(){ $('.textBox').val(''); }); $('.container').on('click', function(){ $('.infocard').fadeOut("fast"); }); $('.cancel').on('click', function(){ $('.main-navigation').toggleClass('open'); }); $(".main").on('click', function(){ $('.side-navigation').removeClass('open'); }); $(".container").on('click', function(){ $('.side-navigation').removeClass('open'); }); $(".nametext").on('click', function(){ $('.side-navigation').removeClass('open'); }); $(".name2").on('click', function(){ $('.side-navigation').removeClass('open'); }); $(".body").on('click', function(){ $('.side-navigation').removeClass('open'); }); $(".listpatients").on('click', function(){ $('.side-navigation').removeClass('open'); }); $('.search').on('click', function(){ $('.side-navigation').addClass('open'); }); $('.submit').click(function() { window.location.reload(true); }); $('input:file').on("change", function() { $('input:submit').prop('disabled', !$(this).val()); }); }); <file_sep>/public/js/controllers/profileController.js myApp.controller('profileController', ['$scope', function($scope){ $scope.users = [ { name: "<NAME>", age: 29, occupation: "Registered Nurse" }, { name: "<NAME>", age: 26, occupation: "Fire Fighter" }, { name: "<NAME>", age: 28, occupation: "Profressional Gamer" } ]; }]);<file_sep>/public/survey.js $(function(){ var checked = 0; var temp = 0; var checked2= 0; var temp2 = 0; $('.rating').on('mouseover', 'label', function() { temp = $(this).prev().val(); $('.display').empty(); $(".display").append(temp); }); $('.rating').on('click', 'label', function() { checked = $(this).prev().val(); $('.display').empty(); $(".display").append(checked); $( ".rating" ).transition({ scale: 1.1 }, 100, function() { }); $( ".rating" ).transition({ scale: 1.0 }, 100, function() { }); }); $('.rating').on('mouseout', 'label', function() { $('.display').empty(); $(".display").append(checked); }); $('.rating2').on('mouseover', 'label', function() { temp2 = $(this).prev().val(); $('.display2').empty(); $(".display2").append(temp2); }); $('.rating2').on('click', 'label', function() { checked2 = $(this).prev().val(); $('.display2').empty(); $(".display2").append(checked2); $( ".rating2" ).transition({ scale: 1.1 }, 100, function() { }); $( ".rating2" ).transition({ scale: 1.0 }, 100, function() { }); }); $('.rating2').on('mouseout', 'label', function() { $('.display2').empty(); $(".display2").append(checked2); }); $( ".flipbtn" ).click(function() { $( ".main-panel" ).transition({ rotateY: '-180deg' }, 500, function() { }); }); $( ".flipbtn2" ).click(function() { $( ".main-panel" ).transition({ rotateY: '-360deg' }, 500, function() { }); }); });
7bc6613607fc3123306c457f3d0378c5b21c7f70
[ "JavaScript" ]
7
JavaScript
nikhilesh2/twilio
37ec68d7751f25c48c0a1d6f7d884e59432b6295
cbcf07380b2bae564fb2116670a483604058002f
refs/heads/master
<file_sep>package uk.co.gideonparanoid.styleConvertor; import java.io.*; import java.util.ArrayList; /** * small program to convert text with function and variable names with split_with_underscores to camelCase * does not take into account things like libraries used (yet, perhaps further development) * overwrites file specified unless another argument givenr2 * * @author <NAME> * @version 1.0 */ public class StyleConvertor { public static void main(String[] arguments) { if (arguments.length == 0) { System.out.println("Specify a filename."); System.exit(0); } else { fileWriter(convertor(fileReader(arguments[0])), arguments[0], arguments[1]); System.out.println("Success"); } } /** * reads a file * @return an ArrayList<String> of the lines of the file */ public static ArrayList<String> fileReader(String filename) { BufferedReader bufferedReader = null; ArrayList<String> lines = new ArrayList<String>(); try { String currentLine; bufferedReader = new BufferedReader(new FileReader(new File(filename))); while ((currentLine = bufferedReader.readLine()) != null) { lines.add(currentLine); } } catch (IOException iOE) { iOE.printStackTrace(); } finally { try { if (bufferedReader != null) bufferedReader.close(); } catch (IOException iOE) { iOE.printStackTrace(); } } return lines; } /** * converts function and variable names with split_with_underscores to camelCase * @param lines an ArrayList<String> of the lines of the file * @return an ArrayList<String> of the lines of the file after conversion */ public static ArrayList<String> convertor(ArrayList<String> lines) { ArrayList<String> result = new ArrayList<String>(); for (String line : lines) { String[] splitLine = line.split("[_]"); String finalLine = ""; if (splitLine.length > 0) { for (String section : splitLine) { finalLine += Character.toString(section.charAt(0)).toUpperCase() + section.substring(1); } } result.add(finalLine); } return result; } /** * writes the resultant file * @param lines an ArrayList<String> of the lines of the file * @param resultFilename the filename of the file to produce, defaults to original filename if null */ public static void fileWriter(ArrayList<String> lines, String startFilename, String resultFilename) { // compiling the file into a single string String content = ""; for (String line : lines) { content += line + "\n"; } try { File file = new File((startFilename == null) ? resultFilename : startFilename); if (!file.exists()) { file.createNewFile(); } FileWriter fileWriter = new FileWriter(file.getAbsoluteFile()); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(content); bufferedWriter.close(); } catch (IOException iOE) { iOE.printStackTrace(); } } } <file_sep>Not much to say really Small Java program which converts function and variable names written_like_this to ones writtenLikeThis. Possibilities for improvement: * Recognition of filetypes, understanding the language they're written in checking standard library functions. * More dynamic approach, recognising functions and variables properly (following "function" or a privacy declaration and searching the document for their names to rename. Could fix aforementioned issue.
5886b301316561e69aa30aa2617546a34260797d
[ "Markdown", "Java" ]
2
Java
GideonPARANOID/underscores-to-camelcase
5c9cf59a57c6cce93112185cc6e1c5e4a7f47258
a9c43b6c8b301d8cf1de4d20fb236bc0dc74a7e2
refs/heads/master
<file_sep>class Book def initialize (title) @title = title end #Getter for book title attr_reader :title #Getter and Setter for book author, genre, and page count attr_accessor :author, :genre, :page_count #Method that 'turns the page' of the book def turn_page puts "Flipping the page...wow, you read fast!" end end
3ad1a99dc0d73f65c5dc11639781f7be4526cc7f
[ "Ruby" ]
1
Ruby
Rizz0S/ruby-oo-complex-objects-putting-the-pieces-together
71a82074ff18e5ab2185fd0753005a97d31d1e63
124914e8275fdf6acbaba734788bb69bef3c3531
refs/heads/main
<repo_name>man20820/userman-v7-add-mac-api<file_sep>/add-mac.php <?php require('connection/routeros_api.class.php'); $mac= $_GET['mac']; $group= $_GET['group']; $API = new RouterosAPI(); $API->debug = false; if ($API->connect('10.208.1.30', 'belajar', 'api')) { $API->comm("/user-manager/user/add", array( "name" => $mac, "group" => $group, )); print("Oke"); $API->disconnect(); } $url='index.php'; echo '<META HTTP-EQUIV=REFRESH CONTENT="3; '.$url.'">'; ?><file_sep>/README.md # userman-v7-add-mac-api
aea5c504790c0533b360addc8f4c65ed0aef2604
[ "Markdown", "PHP" ]
2
PHP
man20820/userman-v7-add-mac-api
bf40a27377a31a0a68bb29219e75324565b29fc8
4395badcf7ccc2f51e9ca13d83650877b0a5c21c
refs/heads/main
<repo_name>alexmzirai/GAM<file_sep>/.github/actions/macos-install.sh echo "MacOS Version Info According to Python:" python -c "import platform; print(platform.mac_ver())" echo "Xcode versionn:" xcodebuild -version export gampath=dist/gam rm -rf $gampath if [ "$PLATFORM" == "x86_64" ]; then export specfile="gam.spec" else export specfile="gam-universal2.spec" fi $python -OO -m PyInstaller --clean --noupx --strip -F --distpath "${gampath}" "${specfile}" export gam="${gampath}/gam" $gam version extended export GAMVERSION=`$gam version simple` cp LICENSE "${gampath}" cp GamCommands.txt "${gampath}" MACOSVERSION=$(defaults read loginwindow SystemVersionStampAsString) GAM_ARCHIVE="gam-${GAMVERSION}-${GAMOS}-${PLATFORM}-MacOS${MACOSVERSION}.tar.xz" rm "${gampath}/lastupdatecheck.txt" # tar will cd to dist/ and tar up gam/ tar -C dist/ --create --file $GAM_ARCHIVE --xz gam
f00cbc6463a6295ec80376c8a18564dc9e5ea37f
[ "Shell" ]
1
Shell
alexmzirai/GAM
b333816dc8f18ec02ee2d21a2607235de7db6ee4
9a470ee993f7bee7c0e60fb7210056652768d45e
refs/heads/master
<repo_name>sara406/teaching_app<file_sep>/app/controllers/api/sample_pages_controller.rb class Api::SamplePagesController < ApplicationController end <file_sep>/app/helpers/api/sample_pages_helper.rb module Api::SamplePagesHelper end
aaa3cd1351329313f46dd200b7f64d8cb83b8dd1
[ "Ruby" ]
2
Ruby
sara406/teaching_app
2279e98a524f701d0c852af4f25923aae1e9c3a0
f5b4b77284a0c7798be0e4a4b74700072896248b
refs/heads/master
<repo_name>dotunodumosu/full-stack-vue<file_sep>/README.md ### Fullstack Components 1) OKTA Boilerplate for authorization and identity management 2) BootstrapVUE open source Theme "Arbano" 3) Axios HTTP requests from node.js 4) Flexible REST endpoints and controllers from Sequelize models in express 5) TODO: Wrap the sqlite database and app in Electron and setup peer to peer with WebRTC ### Backend API API Allows you to: 1) Fetch all sources and information 2) Fetch a single source’s information in details 3) Fetch all messages for a source 4) Ability to CRUD source information Here is the basic API backend route structure we want to see: ``` localhost:8888/source localhost:8888/source/:id localhost:8888/source/:id/message localhost:8888/message localhost:8888/message/:mid ``` ### Current API capabilities 1) Allow a user to view all sources 2) Allows a user to view a single source - With more details about the source - All the messages for that source - An element that displays the aggreate status of messages for a particular source (error, enqueued, finished, processing). # ------------------------------------------------------------------- OKTA Basic CRUD with Vue.js and Node to start off development # ------------------------------------------------------------------- **Prerequisites:** [Node.js](https://nodejs.org/). > [Okta](https://developer.okta.com/) has Authentication and User Management APIs that reduce development time with instant-on, scalable user infrastructure. ## Getting Started To install this application, run the following commands: ```bash git clone https://github.com/ratherbsurfing/fullstack.git cd fullstack npm install ``` This will get a copy of the project installed locally. To start each app, follow the instructions below. To run the server: ```bash node ./src/server ``` To run the client: ```bash npm run dev ``` ### Create an Application in Okta You will need to [create an OpenID Connect Application in Okta](https://developer.okta.com/blog/2018/02/15/build-crud-app-vuejs-node#add-authentication-with-okta) to get your values to perform authentication. Log in to your Okta Developer account (or [sign up](https://developer.okta.com/signup/) if you don’t have an account) and navigate to **Applications** > **Add Application**. Click **Single-Page App**, click **Next**, and give the app a name you’ll remember, and click **Done**. #### Server Configuration Set the `issuer` and copy the `clientId` into `src/server.js`. ```javascript const oktaJwtVerifier = new OktaJwtVerifier({ clientId: '0oalccuta0fx2kHFl356', issuer: 'https://dev-108751.okta.com/oauth2/default' }) ``` **NOTE:** The value of `{yourOktaDomain}` should be something like `dev-123456.oktapreview`. Make sure you don't include `-admin` in the value! #### Client Configuration Set the `issuer` and copy the `clientId` into `src/router/index.js`. ```javascript Vue.use(Auth, { issuer: 'https://dev-108751.okta.com/oauth2/default', client_id: '0oalccuta0fx2kHFl356', redirect_uri: 'http://localhost:8080/implicit/callback', scope: 'openid profile email' }) ``` ## Links This example uses the following libraries provided by Okta: * [Okta JWT Verifier](https://github.com/okta/okta-oidc-js/tree/master/packages/jwt-verifier) * [Okta Vue SDK](https://github.com/okta/okta-oidc-js/tree/master/packages/okta-vue) ## License Apache 2.0, see [LICENSE](LICENSE). # ------------------------------------------------------------------- Theme-ing components - base evolved from ARBANO VUE.js theme - https://demos.vuejsadmin.com/arbano/free/#/ # ------------------------------------------------------------------- # Arbano - Free vuejs Admin Template [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Arbano%20-%20Free%20Vue%20Admin%20Template%20&url=https://vuejsadmin.com/product/arbano-vuejs-admin-pro/&hashtags=bootstrap,admin,template,dashboard,panel,free,angular,react,vue) [![Bootstrap Admin Templates Bundle](https://vuejsadmin.com/wp-content/uploads/edd/2018/06/arbano-cover.jpg)](https://vuejsadmin.com/product/arbano-vuejs-admin-pro/) ### Check out VueJS Bootstrap Admin Dashboard Template ### # Get More [Free VueJS BootStrap Admin Templates](https://vuejsadmin.com) # Arbano is a Free Template which can be used for both personal and business purpose. The light version is free but if you love to get dedicated support with more options then you with the pro version. **NOTE:** Please remember to **STAR** this project and **FOLLOW** [our Github](https://github.com/litonarefin/arbano) to keep you update with this template. ## [Arbano Free](https://vuejsadmin.com/product/arbano/) ## ### Features * Recent Bootstrap and VueJS version * Built with Vue-CLI to generate components on the fly * Built with SCSS * Tons of Icons * Chart.js – Line Chart, Bar Chart, Doughnut Chart, Pie Chart, Polar Area Chart * Built in Widgets and Components * Advanced Google Maps Integrations- Google Maps, Bubble Maps, Leaflet Maps, Line Maps * Nested Routing with Components Name * Developer friendly code * Animated Progress Bar and Vue Progress Bars * Blazing Fast and LightWeight * Clean and Modern Design * Fully Customizable * Developer Friendly Code * Completely Modular! Every Single Element has its own module ## What's included Within the download you'll find the following directories and files: ``` arbano-vuejs-free/ ├── src/ # Main project Folder │ └── assets/ # CSS + JS + Font's │ └── components/ # Components elements │ └── directives/ # Directives │ └── images/ # Image Folder │ └── layouts/ # HomePage Layouts │ └── pages/ # Login, Register, 404 pages │ └── router/ # Vue-router │ └── store/ # State management │ └── views/ # Render Front End View │ └── App.vue # App File │ └── favicon.ico # Favicon │ └── main.js # Main JS File │ └── nav.js # Nav Js File ├── package.json # Dependency Packages ├── README.md # Read Me ├── webpack.config.js # Webpack Configuration ├── yarn.lock # Yarn Package ├── index.html # Main Index File ``` ### License MIT License Copyright (c) 2018 Jewel Theme Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <file_sep>/test/unit/specs/Takehome.spec import Vue from 'vue' import Hello from '@/components/TakeHome' describe('TakeHome.vue', () => { it('should render correct contents', () => { const Constructor = Vue.extend(TakeHome) const vm = new Constructor().$mount() expect(vm.$el.querySelector('.hello h1').textContent) .to.equal('Welcome to Your Vue.js PWA') }) }) <file_sep>/src/router/index.js import Vue from 'vue' import Router from 'vue-router' import TakeHome from '@/components/TakeHome' import MessagesManager from '@/components/MessagesManager' import SourcesManager from '@/components/SourcesManager' import SourcesManagerDetail from '@/components/SourcesManagerDetail' import Alert from '../components/Alert.vue' import Bootstrap4Table from '../components/Bootstrap4Table.vue' import AnimateNumber from '../components/AnimateNumber.vue' import BootstrapProgressBar from '../components/progressbar/BootstrapProgressBar.vue' import Auth from '@okta/okta-vue' // Dynamic Loading Modules // Views // const Dashboard = resolve => { require.ensure(['../views/Dashboard.vue'], () => { resolve(require('../views/Dashboard.vue')) }) } // Registered Components Vue.component('basix-alert', Alert) // Vue.component('sidebar-collapse', SidebarCollapse) // Vue.component('card', CardTemplate) Vue.component('basix-counter', AnimateNumber) Vue.component('bootstrap-progress-bar', BootstrapProgressBar) // UI Components const Buttons = resolve => { require.ensure(['../components/Buttons.vue'], () => { resolve(require('../components/Buttons.vue')) }) } const Badges = resolve => { require.ensure(['../components/Badges.vue'], () => { resolve(require('../components/Badges.vue')) }) } const Alerts = resolve => { require.ensure(['../components/Alerts.vue'], () => { resolve(require('../components/Alerts.vue')) }) } const ProgressBars = resolve => { require.ensure(['../components/ProgressBars.vue'], () => { resolve(require('../components/ProgressBars.vue')) }) } const BasicForms = resolve => { require.ensure(['../components/forms/BasicForms.vue'], () => { resolve(require('../components/forms/BasicForms.vue')) }) } const Grids = resolve => { require.ensure(['../components/Grids.vue'], () => { resolve(require('../components/Grids.vue')) }) } // const Widgets = resolve => { require.ensure(['../components/Widgets.vue'], () => { resolve(require('../components/Widgets.vue')) }) } const Typography = resolve => { require.ensure(['../components/Typography.vue'], () => { resolve(require('../components/Typography.vue')) }) } const Icons = resolve => { require.ensure(['../components/icons/Icons.vue'], () => { resolve(require('../components/icons/Icons.vue')) }) } const SetsList = resolve => { require.ensure(['../components/icons/SetsList.vue'], () => { resolve(require('../components/icons/SetsList.vue')) }) } const Sets = resolve => { require.ensure(['../components/icons/Set.vue'], () => { resolve(require('../components/icons/Set.vue')) }) } const Tables = resolve => { require.ensure(['../components/tables/Tables.vue'], () => { resolve(require('../components/tables/Tables.vue')) }) } // Charts const ChartJS = resolve => { require.ensure(['../components/charts/ChartJS.vue'], () => { resolve(require('../components/charts/ChartJS.vue')) }) } // Pages const Login = resolve => { require.ensure(['../pages/login/Login.vue'], () => { resolve(require('../pages/login/Login.vue')) }) } const Register = resolve => { require.ensure(['../pages/register/Register.vue'], () => { resolve(require('../pages/register/Register.vue')) }) } const Page404 = resolve => { require.ensure(['../pages/Page404.vue'], () => { resolve(require('../pages/Page404.vue')) }) } const Page500 = resolve => { require.ensure(['../pages/Page500.vue'], () => { resolve(require('../pages/Page500.vue')) }) } Vue.use(Auth, { issuer: 'https://dev-108751.okta.com/oauth2/default', client_id: '0oalccuta0fx2kHFl356', redirect_uri: 'http://localhost:8888/implicit/callback', scope: 'openid profile email' }) Vue.use(Router) let router = new Router({ mode: 'history', routes: [ { path: '/', name: 'TakeHome', component: TakeHome }, { path: '/implicit/callback', component: Auth.handleCallback() }, { path: '/messages-manager', name: 'MessagesManager', component: MessagesManager, meta: { requiresAuth: true } }, { path: '/sources-manager', name: 'SourcesManager', component: SourcesManager, meta: { requiresAuth: true } }, { path: '/sources-manager-detail', name: 'SourcesManagerDetail', component: SourcesManagerDetail, meta: { requiresAuth: true } }, { path: '/bootstrap-4-table', name: 'Bootstrap4Table', component: Bootstrap4Table, meta: { requiresAuth: true } }, // // UI Components { path: '/components/buttons', name: 'buttons', component: Buttons }, { path: '/components/badges', name: 'badges', component: Badges }, { path: '/components/alerts', name: 'alerts', component: Alerts }, { path: '/components/progressbars', name: 'progressbars', component: ProgressBars }, { path: '/components/basic-form', name: 'basic-form', component: BasicForms }, { path: '/components/grids', name: 'grids', component: Grids }, { path: '/components/typography', name: 'typography', component: Typography }, { path: '/components/tables', name: 'tables', component: Tables }, { path: '/components/icons', component: Icons, children: [ { path: '', component: SetsList, name: 'Icons' }, { path: ':name', component: Sets, props: true } ] }, { path: '/components/charts', name: 'Charts', component: { render (c) { return c('router-view') } }, children: [ { path: '/components/chartjs', component: ChartJS, name: 'chart-js' } ] }, { path: '/components/auth', name: 'auth', component: { render (c) { return c('router-view') } }, children: [ { path: '/auth/login', component: Login, name: 'login', meta: { default: false, title: 'Login' } }, { path: '/auth/register', component: Register, name: 'Register' }, { path: '/auth/Page404', component: Page404, name: 'Page404' }, { path: '/auth/Page500', component: Page500, name: 'Page500' } ] } ] }) router.beforeEach(Vue.prototype.$auth.authRedirectGuard()) export default router
bcae24caee8dc38b81d16d40a1ec3db5e86d7dda
[ "Markdown", "Python", "JavaScript" ]
3
Markdown
dotunodumosu/full-stack-vue
a2a6ef06d607258bb7e9ecc753ed088cc2ff95c2
b72ba20a5348d917d5cfc0cf4f00d4105307fe52
refs/heads/master
<file_sep>package com.example.tzForMBOIC.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class ExcelController { @RequestMapping(value = "/excel", method= RequestMethod.GET) public ModelAndView excel() { System.out.println("ExcelPDFController excel is called"); //excelDocument - look excel-pdf-config.xml return new ModelAndView("xlsHandler"); } @RequestMapping(value = "/pdf", method= RequestMethod.GET) public ModelAndView pdf() { System.out.println("ExcelPDFController excel is called"); //excelDocument - look excel-pdf-config.xml return new ModelAndView("generatePDF"); } }
37d8772a836ac269afaa6137601b556a2ca0f18b
[ "Java" ]
1
Java
Stein312/tzForMboicBov
da304e820ac51d3ab7eba4037adc0ec88c545975
386ceef67c6bf5ba35f56f1c12883412f27137e1
refs/heads/master
<file_sep>import {NgModule} from '@angular/core'; import {LhComponent} from './lh/lh'; @NgModule({ declarations: [LhComponent], imports: [], exports: [LhComponent] }) export class ComponentsModule { }
c38fc892d7f150404c283c136abe6a70face45e7
[ "TypeScript" ]
1
TypeScript
654550265/testbaoxian
72f0af75abbaeb5f6da098bdf6ae1385d08151f5
bba5a30b4224f494397d22dec64edb607d6559dc
refs/heads/master
<repo_name>SHocker-Yu/gameSystem<file_sep>/game_vue/src/store/modules/user.js /** * Created by SwiftJ on 17/1/26. */ const state = { fd: null, id: null, room_id: null, rolename: null, avatar: null, status: null, trusteeship: null, game_type: null } const getters = { fd: state => state.fd, user: state => state } const actions = { } const mutations = { // 设置变量的值 使用store.commit 来触发 就像调用方法一样 如果使用store.commit('User.FD', -2) // 就是将state的fd设为-2 用这种方法 页面会跟着刷新 'User.FD'(state, fd) { state.fd = fd }, 'User.ID'(state, id) { state.id = id }, 'User.ROOM.ID'(state, room_id) { state.room_id = room_id }, 'User.ROLENAME'(state, rolename) { state.rolename = rolename }, 'User.STATUS'(state, status) { state.status = status }, 'User.AVATAR'(state, avatar) { state.avatar = avatar }, 'User.TRUSTEESHIP'(state, trusteeship) { state.trusteeship = trusteeship } } export default { state, getters, actions, mutations, } <file_sep>/game_vue/src/store/modules/hall.js /** * Created by SwiftJ on 17/1/27. */ const state = { users: [], messages: [] } const getters = { users: state => state.users, // 对应所有用户 messages: state => state.messages // 对应大厅的所有信息 } const actions = { clearMessage({ commit }) { commit('Hall.CLEARMESSAGE') } } const mutations = { 'Hall.ADDMESSAGE'(state, message) { // Hall大厅.ADDMESSAGE添加信息 state.messages.push(message) }, 'Hall.CLEARMESSAGE'(state) { state.messages.splice(0) }, 'Hall.USERENTER'(state, user) { state.users.push(user) }, 'Hall.USERALL'(state, users) { state.users.push.apply(state.users, users) }, 'Hall.USERLEAVE'(state, id) { var delIndex = -1 for(let [index, user] of state.users.entries()) { if (user.u_id === id) { console.log(user) delIndex = index } } if (delIndex > -1) { state.users.splice(delIndex, 1) } } } export default { state, getters, actions, mutations } <file_sep>/game_vue/src/store/modules/room.js /** * Created by SwiftJ on 17/1/29. */ import Vue from 'vue' import { countdown } from './action' import { send } from '../../game/client' const state = { rooms: [], messages: [], duration: 60, // 60s timeover: false, chessBoard: [], can_chess: false, auto_down: 0 } let timerId = null const getters = { rooms: state => state.rooms, room_messages: state => state.messages, duration: state => state.duration, timeover: state => state.timeover, chessBoard: state => state.chessBoard, can_chess: state => state.can_chess, auto_down: state => state.auto_down } const actions = { clearRoomMessage({ commit }) { commit('Room.CLEARMESSAGE') }, countdown({commit, state}) { commit('TIME_OVER', false) if (timerId) clearInterval(timerId); timerId = setInterval(function() { commit('COUNT_DOWN'); if(state.duration < 1){ clearInterval(timerId); commit('TIME_OVER', true) } }, 1000); }, clearCountDown({commit}) { if (timerId) clearInterval(timerId); } } const mutations = { 'Room.ADDMESSAGE'(state, message) { state.messages.push(message) }, 'Room.CLEARMESSAGE'(state) { state.messages.splice(0) }, 'Room.INIT'(state, rooms) { state.rooms = rooms }, 'Room.SETINFO'(state, room) { let id = room.r_id let room_info = state.rooms[id] if (!room_info) return null let status = room.status if (status) room_info.status = status Vue.set(state.rooms, id, room_info) let users = room.users for (var i = 0; i < users.length; i ++) { let user = users[i] if ((room_info.users[i] != user)) { Vue.set(room_info.users, i, user) } } }, 'Room.BEGIN'(state) { state.duration = 60 }, 'COUNT_DOWN'(state) { state.duration--; }, 'SET_COUNTDOWN'(state, duration) { state.duration = duration }, 'TIME_OVER'(state, over) { state.timeover = over }, 'Chess.BEGIN'(state) { for (var i= 0;i<15;i+=1){ state.chessBoard[i]=[]; for (var j=0;j<15;j+=1){ state.chessBoard[i][j]=0; //遍历数组,值初始化为0; } } }, 'Chess.WHITE'(state, point) { let x = point.x, y = point.y state.chessBoard[x][y] = -1 }, 'Chess.BLACK'(state, point) { let x = point.x, y = point.y state.chessBoard[x][y] = 1 }, 'Chess.CANDOWN'(state) { state.can_chess = true }, 'Chess.CANTDOWN'(state) { state.can_chess = false }, 'Chess.AUTO'(state, chess) { state.auto_down = chess }, 'Chess.RESET'(state) { state.auto_down = 0 } } export default { state, getters, actions, mutations, } <file_sep>/game_vue/static/js/chess.js /** * Created by SwiftJ on 17/2/3. */ <file_sep>/game_vue/src/game/client.js /** * Created by SwiftJ on 17/1/23. */ class Loader { constructor() { this.loader = this._createLoader() this.p = document.createElement('p') this.loader.appendChild(this.p) this.mask = this._createMask() } show(info) { info = info || '......' this.p.innerHTML = info document.body.appendChild(this.mask) this.p.className = 'write-anim' document.body.appendChild(this.loader) } showAutoDismiss(info) { info = info || '......' this.p.innerHTML = info document.body.appendChild(this.mask) this.p.className = 'write-anim' document.body.appendChild(this.loader) setTimeout(() => { this.dismiss() },3000) } showError(error) { this.p.innerHTML = error this.p.className = 'write-center' document.body.appendChild(this.loader) setTimeout(() => { this.dismiss() },1000) } dismiss() { var mask = document.getElementsByClassName('loading')[0] mask && document.body.removeChild(mask) var loading = document.getElementsByClassName('mask')[0] loading && document.body.removeChild(loading) } _createLoader() { if (document.getElementsByClassName('loading').length > 0) { return document.getElementsByClassName('loading')[0] } var loading = document.createElement('div') loading.className = 'loading' var loader = document.createElement('div') loader.className = 'loader' loading.appendChild(loader) var ballInner = document.createElement('div') ballInner.className = 'ball-inner ball-scale-random' loader.appendChild(ballInner) for (var i = 0; i < 3; i++) { ballInner.appendChild(document.createElement('div')) } return loading } _createMask() { if (document.getElementsByClassName('mask').length > 0) { return document.getElementsByClassName('mask')[0] } var mask = document.createElement('div') mask.className = 'mask' return mask } } import store from '../store/store' import { countdown } from '../store/modules/action' // const host = '192.168.127.12' const host = '127.0.0.1' const port = 8888 // client 是客户端与服务端的websocket链接 export const client = new WebSocket(`ws:${host}:${port}`) export const loader = new Loader('waiting...') client.onmessage = function () { } client.onopen = function () { } // send 方法 obj是发送给服务端的参数, export const send = function(obj, show=false) { client.send(JSON.stringify(obj)) // 如果show == true 就弹出 waitting if (show) { loader.show('waiting......') } } export const close = () => { client.close() console.log('close') } client.onopen = event => { console.log('open') } var canvas = null; var context = null; var caswidth = 0 var casheight = 0 client.onmessage = ({ data }) => { let packet = JSON.parse(data) if (packet) { loader.dismiss() let action = packet.header.split('.') if (action[0] == 'login') { if (action[1] == 'success') { store.commit('User.FD', packet.data.w_id) store.commit('User.ID', packet.data.u_id) store.commit('User.ROLENAME', packet.data.rolename) store.commit('User.AVATAR', packet.data.avatar) } if (action[1] == 'error') { loader.showError(packet.msg) } if (action[1] == 'betop') { store.commit('User.FD', null) window.location.reload() alert('By the top number!') } } if (action[0] == 'register') { loader.showError(packet.msg) } if (action[0] == 'user') { if (action[1] == 'enter') { store.commit('Hall.USERENTER', packet.data) } if (action[1] == 'all') { store.commit('Hall.USERALL', packet.data) } if (action[1] == 'leave') { store.commit('Hall.USERLEAVE', packet.data.u_id) } } if (action[0] == 'hall') { if (action[1] == 'message') { store.commit('Hall.ADDMESSAGE', packet.data) } } if (action[0] == 'rooms') { if (action[1] == 'init') { store.commit('Room.INIT', packet.data) } if (action[1] == 'enter') { store.commit('User.ROOM.ID', packet.data) } if (action[1] == 'info') { if (packet.data.status == 'playing') { } store.commit('Room.SETINFO', packet.data) } if (action[1] == 'begin') { store.commit('Room.SETINFO', packet.data) store.commit('Room.BEGIN') if (packet.data.status == 'playing') { store.dispatch('countdown') setTimeout(function() { window.onresize() },10) // console.log(packet.data.game_type) if (packet.data.game_type == 'chess') { store.commit('Chess.BEGIN') } } } if (action[1] == 'willnext') { store.commit('SET_COUNTDOWN', packet.data) } if (action[1] == 'next') { store.commit('Room.SETINFO', packet.data) store.commit('Room.BEGIN') store.dispatch('countdown') if (packet.data.game_type == 'draw') { // setTimeout(function() { window.onresize() // },10) }else { } } if (action[1] == 'turned') { store.commit('Chess.CANDOWN') } if (action[1] == 'leave') { store.commit('User.ROOM.ID', null) store.commit('Room.CLEARMESSAGE') } if (action[1] == 'message') { store.commit('Room.ADDMESSAGE', packet.data) } } if (action[0] == 'draw') { if (action[1] == 'begin') { canvas = document.getElementById('cas') context = canvas.getContext('2d') caswidth = canvas.width casheight = canvas.height context.beginPath() context.strokeStyle = packet.data.color context.lineWidth = parseInt(packet.data.weight) } if (action[1] == 'move') { if (context) { context.lineTo(packet.data.x * caswidth, packet.data.y * casheight) context.stroke() } } if (action[1] == 'end') { context.closePath() } if (action[1] == 'clear') { canvas.height = canvas.height } } if (action[0] == 'chess') { if (action[1] == 'down') { canvas = document.getElementById('cas') context = canvas.getContext('2d') if (context) { window.onresize(); let i = packet.data.i, j = packet.data.j, type = packet.data.army_type var canvasWidth = canvas.width, canvasHeight = canvas.height; var finalWidth = (canvasWidth > canvasHeight ? canvasHeight : canvasWidth) - 30; var width = finalWidth / 14; var left = (canvasWidth - finalWidth) / 2; var top = (canvasHeight - finalWidth) / 2; var x_point = left + i * width; var y_point = top + j * width; if (type == 'black') { store.commit('Chess.BLACK', { x: i, y: j }) }else { store.commit('Chess.WHITE', { x: i, y: j }) } drawChessPiece(context, width / 2, x_point, y_point, type) context.strokeStyle= "rgb(200,0,0)"; context.strokeRect(x_point - width / 2, y_point - width / 2, width, width); // context.stroke(); } } if (action[1] == 'over') { store.commit('SET_COUNTDOWN', 60); store.dispatch('clearCountDown'); } if (action[1] == 'auto') { var i = packet.data.position.x var j = packet.data.position.y console.log(i, j); if (packet.data.army == '黑色方') { // store.commit('Chess.AUTO', 1) }else { // store.commit('Chess.AUTO', -1) } } } } }
3bef25d0130be52a418b72e31e4cccf384ad7e4f
[ "JavaScript" ]
5
JavaScript
SHocker-Yu/gameSystem
2ae4a401490e0614c7169a023abd65270ba8f1e4
9ebf891abd351ffd56c3470938c2218cb60fc48b
refs/heads/main
<file_sep>$(document).ready(function(){ $.fn.myFunction = function(d){ $.get("goods3.php", { art: d }, function(data){ var obj = JSON.parse(data); $('#name_h').text(obj.catName); $('#breed_h').text(obj.breed); $('#gender_h').text(obj.gender); $('#weight_h').text(obj.weight); $('#cost_h').text(obj.cost); }); } $('#op1').click(function(){$.fn.myFunction(1);}).hover(function(){$.fn.myFunction(1);}); $('#op2').click(function(){$.fn.myFunction(2);}).hover(function(){$.fn.myFunction(2);}); $('#op3').click(function(){$.fn.myFunction(3);}).hover(function(){$.fn.myFunction(3);}); }); <file_sep><?php $item1 = array( "catName" => "Peter", "breed" => "Abyssinian", "gender" => "M", "weight" => "8 kg", "cost" => "$199.00" ); $item2 = array( "catName" => "Fila", "breed" => "Birman", "gender" => "F", "weight" => "5 kg", "cost" => "$1199.00" ); $item3 = array( "catName" => "Kate", "breed" => "Chartreux", "gender" => "F", "weight" => "4 kg", "cost" => "$99.00" ); $art = $_GET['art']; if ($art ==1) { echo json_encode($item1); } if ($art ==2) { echo json_encode($item2); } if ($art ==3) { echo json_encode($item3); }
6c27adc61dfcdbd7346ce15c17ef3e9219146fc1
[ "JavaScript", "PHP" ]
2
JavaScript
MarySweetRollStolen/using-ajax-at-first
f058d008da2c05a591c2457289a1d072af5dca1c
70cbe168daaf2ca9b787dfd75b6949aa5592ca3e
refs/heads/master
<file_sep>// Variables // let express = require('express') let app = express() let bodyParser = require('body-parser') let session = require('express-session') let cookie = require('cookie') let Db_interact = require("./models/db_interact") let moment = require('moment') let cookies = null; // Donnée de la base // let allRepas; // Moteur de Template // app.set('view engine', 'ejs') // Middleware // app.use('/assets',express.static('public')) app.use('/sem',express.static('semantic')) app.use('/elite',express.static('eliteA')) app.use('/elite/module',express.static('mod')) app.use('/models',express.static('models')) app.use('/pickmeup',express.static('pickMeUp')) app.use(bodyParser.urlencoded({ extended :false })) app.use(bodyParser.json()) app.use(session({ secret: 'akanzlkrnlkn', resave: false, saveUninitialized: true, cookie: {secure:false} })) app.use(require('./middleware/flash')) // Routes // // GET // app.get('/', (request,response) => { if(cookies != null) response.render('pages/page-wrapper', {isConnected:true,userPseudo:cookies.userPseudo,data_repas:allRepas,monthNext:JSON.stringify(moment().startOf('month').add(1,'months').format('DD-MM-YYYY')),monthPrev:JSON.stringify(moment().startOf('month').subtract(1,'months').format('DD-MM-YYYY'))}) else{ if(request.query.inscription_success) { response.render('pages/index', {isConnected:false,inscription_success:true}) } else{ response.render('pages/index',{isConnected:false}) } } }) app.get('/inscription', (req,res) =>{ res.render('pages/inscription',{isConnected:false}) }) app.get('/index', (req,res) =>{ if(cookies != null) cookies = null res.render('pages/index',{isConnected:false,form_success:null}) }) app.get('/app',(req,res) =>{ if(cookies.userPseudo){ res.render('pages/page-wrapper',{isConnected:true,userPseudo:cookies.userPseudo,data_repas:allRepas,monthNext:JSON.stringify(moment().startOf('month').add(1,'months').format('DD-MM-YYYY')),monthPrev:JSON.stringify(moment().startOf('month').subtract(1,'months').format('DD-MM-YYYY'))}) } else{ res.render('pages/index',{isConnected:false,form_success:null}) } }) // POST // app.post('/', (req,res) =>{ Db_interact.connectToApp(req.body.pseudo,req.body.password, (resultQuery) =>{ if(resultQuery.length > 0){ cookies = cookie.parse(cookie.serialize('userPseudo', String(req.body.pseudo), { httpOnly: true, maxAge: 60 * 60 * 24 * 7 })) Db_interact.getUserRepas(req.body.pseudo,moment().startOf('month').format('YYYY-MM-DD'),(resultQuery) => { allRepas = JSON.stringify(resultQuery) res.render('pages/page-wrapper', {isConnected:true,userPseudo:req.body.pseudo,data_repas:allRepas,monthNext:JSON.stringify(moment().startOf('month').add(1,'months').format('DD-MM-YYYY')),monthPrev:JSON.stringify(moment().startOf('month').subtract(1,'months').format('DD-MM-YYYY'))}) }) } else res.render('pages/index', {form_success:false}) }) }) app.post('/inscription', (req, res) =>{ Db_interact.insertNewUser(req.body.pseudo,req.body.password,req.body.confirmPassword,(resultQuery) =>{ let data = [] if(resultQuery === 'pseudoExist'){ data.push({pseudo_exist:true,form_success:false,notSamePass:false}) res.send(data) } else if(resultQuery === 'emptyInputs'){ data.push({pseudo_exist:false,form_success:true,notSamePass:false}) res.send(data) } else if(resultQuery === 'notSamePass'){ data.push({pseudo_exist:false,form_success:false,notSamePass:true}) res.send(data) } else{ res.send(['redirect']) } }) }) app.post('/addRepas',(req, res) =>{ let d = req.body.date; if(moment(d,'DD-MM-YYYY').month() != req.body.currentMonth) d = moment(d,'DD-MM-YYYY').subtract(1,'months').format('DD-MM-YYYY') Db_interact.addNewRepas(cookies.userPseudo,req.body.type_repas,req.body.date,req.body.heure,() =>{ Db_interact.getUserRepas(cookies.userPseudo,moment(d,'DD-MM-YYYY').format('YYYY-MM-DD'),(resultQuery) => { allRepas = JSON.stringify(resultQuery) let data = [{resultQuery}] res.send(data) }) }) }) app.post('/suppRepas',(req,res)=>{ let d = req.body.date; if(moment(d,'DD-MM-YYYY').month() != req.body.currentMonth) d = moment(d,'DD-MM-YYYY').subtract(1,'months').format('DD-MM-YYYY') Db_interact.suppRepas(cookies.userPseudo, req.body.date, req.body.heure, () =>{ Db_interact.getUserRepas(cookies.userPseudo,moment(d,'DD-MM-YYYY').format('YYYY-MM-DD') ,(resultQuery) => { allRepas = JSON.stringify(resultQuery) let data = [{resultQuery}] console.log("data supp : ") res.send(data) }) }) }) app.post('/nxtMonth',(req,res)=>{ Db_interact.getUserRepas(cookies.userPseudo, moment(req.body.nxt,'DD-MM-YYYY'),(resultQuery) => { let data = [] let data_r = resultQuery data.push({data_r:data_r, nxtMonth:moment(req.body.nxt,'DD-MM-YYYY').add(1,'months').format('DD-MM-YYYY'), prevMonth:moment(req.body.nxt,'DD-MM-YYYY').subtract(1,'months').format('DD-MM-YYYY') }) res.send(data) }) }) app.post('/prevMonth',(req,res)=>{ Db_interact.getUserRepas(cookies.userPseudo, moment(req.body.prev,'DD-MM-YYYY'),(resultQuery) => { let data = [] let data_r = resultQuery data.push({data_r:data_r, nxtMonth:moment(req.body.prev,'DD-MM-YYYY').add(1,'months').format('DD-MM-YYYY'), prevMonth:moment(req.body.prev,'DD-MM-YYYY').subtract(1,'months').format('DD-MM-YYYY') }) res.send(data) }) }) // Port // app.listen(8080)<file_sep>let updateGauge = (data, gaugeVege, gaugePoisson, gaugeViande) =>{ let nb_vege = 0 , nb_viande = 0, nb_poisson = 0 data.forEach(element => { element.type_repas == 1 ? nb_vege++ : element.type_repas == 2 ? nb_viande++ : nb_poisson++; }); let tot = nb_vege + nb_viande + nb_poisson; let percent_viande_mth = Math.round((nb_viande / tot) * 100) let percent_vege_mth = Math.round((nb_vege / tot) * 100) let percent_poisson_mth = Math.round((nb_poisson / tot) * 100) gaugeVege.setValueAnimated(percent_vege_mth,2) gaugePoisson.setValueAnimated(percent_poisson_mth,2) gaugeViande.setValueAnimated(percent_viande_mth,2) }<file_sep>$(function () { "use strict"; Morris.Area({ element: 'synthese-marge-chart' , data: [{ period: '2018-01' , marge: 2837 , va: 80 }, { period: '2018-02' , marge: 2887 , va: 100 }, { period: '2018-03' , marge: 3219 , va: 100 }, { period: '2018-04' , marge: 3919 , va: 100 }, { period: '2018-05' , marge: 4218 , va: 100 }, { period: '2018-06' , marge: 3989 , va: 100 }, { period: '2018-07' , marge: 5430 , va: 100 }, { period: '2018-08' , marge: 6319 , va: 100 }, { period: '2018-09' , marge: 6508 , va: 100 },{ period: '2018-10' , marge: 7120 , va: 100 },{ period: '2018-11' , marge: 7328 , va: 100 },{ period: '2018-12' , marge: 7472 , va: 100 },{ period: '2019-01' , marge: 6598 , va: 10 },{ period: '2019-02' , marge: 6129 , va: 100 },{ period: '2019-03' , marge: 7239 , va: 100 },{ period: '2019-04' , marge: 7692 , va: 100 },{ period: '2019-05' , marge: 8727 , va: 100 }] , xkey: 'period' , ykeys: ['marge', 'va'] , labels: ['Marge', 'VA'] , pointSize: 3 , fillOpacity: 0 , pointStrokeColors: ['#00bfc7', '#fb9678'] , behaveLikeLine: true , gridLineColor: '#e0e0e0' , lineWidth: 3 , hideHover: 'auto' , lineColors: ['#00bfc7', '#fb9678'] , resize: true }); var sparklineLogin = function () { $('#sales1').sparkline([20, 40, 30], { type: 'pie' , height: '130' , resize: true , sliceColors: ['#808f8f', '#fecd36', '#f1f2f7'] }); $('#sales2').sparkline([6, 10, 9, 11, 9, 10, 12], { type: 'bar' , height: '154' , barWidth: '4' , resize: true , barSpacing: '10' , barColor: '#25a6f7' }); $('#synthese-top-marge').sparkline([2930, 3203, 3329, 3782, 3228, 3739, 4228, 3828, 3029, 2782, 3228, 4239], { type: 'bar' , chartRangeMin: 2500 , height: '50' , barWidth: '5' , resize: true , barSpacing: '3' , barColor: '#4caf50' }); $('#sparklinedash2').sparkline([0, 5, 6, 10, 9, 12, 4, 9, 0, 5, 6, 10, 9, 12, 4, 9], { type: 'bar' , height: '50' , barWidth: '5' , resize: true , barSpacing: '3' , barColor: '#9675ce' }); $('#sparklinedash3').sparkline([0, 5, 6, 10, 9, 12, 4, 9, 0, 5, 6, 10, 9, 12, 4, 9], { type: 'bar' , height: '30' , barWidth: '5' , resize: true , barSpacing: '3' , barColor: '#03a9f3' }); $('#sparklinedash4').sparkline([0, 5, 6, 10, 9, 12, 4, 9], { type: 'bar' , height: '30' , barWidth: '4' , resize: true , barSpacing: '5' , barColor: '#f96262' }); $('#prescripteurs-top-nb').sparkline([2930, 3203, 3329, 3782, 3228, 3739, 4228, 3828, 3029, 2782, 3228, 4239], { type: 'bar' , chartRangeMin: 0 , height: '50' , barWidth: '9' , resize: true , barSpacing: '3' , barColor: '#4caf50' }); $('#prescripteurs-devis-mb').sparkline([2930, 3203, 3329, 3782, 3228, 3739, 4228, 3828, 3029, 2782, 3228, 4239], { type: 'bar' , chartRangeMin: 0 , height: '50' , barWidth: '9' , resize: true , barSpacing: '3' , barColor: '#9675ce' }); $('#prescripteur-devis-attente').sparkline([2930, 3203, 3329, 3782, 3228, 3739, 4228, 3828, 3029, 2782, 3228, 4239], { type: 'bar' , chartRangeMin: 0 , height: '50' , barWidth: '9' , resize: true , barSpacing: '3' , barColor: '#03a9f3' }); $('#nouveau_devis').sparkline([2930, 3203, 3329, 3782, 3228, 3739, 4228, 3828, 3029, 2782, 3228, 4239], { type: 'bar' , chartRangeMin: 0 , height: '50' , barWidth: '5' , resize: true , barSpacing: '3' , barColor: '#4caf50' }); $('#devis_valide').sparkline([2930, 3203, 3329, 3782, 3228, 3739, 4228, 3828, 3029, 2782, 3228, 4239], { type: 'bar' , chartRangeMin: 0 , height: '50' , barWidth: '5' , resize: true , barSpacing: '3' , barColor: '#9675ce' }); $('#devis_en_attente').sparkline([2930, 3203, 3329, 3782, 3228, 3739, 4228, 3828, 3029, 2782, 3228, 4239], { type: 'bar' , chartRangeMin: 0 , height: '50' , barWidth: '5' , resize: true , barSpacing: '3' , barColor: '#03a9f3' }); $('#Devis_refuse').sparkline([2930, 3203, 3329, 3782, 3228, 3739, 4228, 3828, 3029, 2782, 3228, 4239], { type: 'bar' , chartRangeMin: 0 , height: '50' , barWidth: '5' , resize: true , barSpacing: '3' , barColor: '#4caf50' }); $('#staffe').sparkline([2930, 3203, 3329, 3782, 3228, 3739, 4228, 3828, 3029, 2782, 3228, 4239], { type: 'bar' , chartRangeMin: 0 , height: '50' , barWidth: '9' , resize: true , barSpacing: '3' , barColor: '#4caf50' }); $('#defaut_paiement').sparkline([2930, 3203, 3329, 3782, 3228, 3739, 4228, 3828, 3029, 2782, 3228, 4239], { type: 'bar' , chartRangeMin: 0 , height: '50' , barWidth: '9' , resize: true , barSpacing: '3' , barColor: '#9675ce' }); $('#frais_de_gestion').sparkline([2930, 3203, 3329, 3782, 3228, 3739, 4228, 3828, 3029, 2782, 3228, 4239], { type: 'bar' , chartRangeMin: 0 , height: '50' , barWidth: '9' , resize: true , barSpacing: '3' , barColor: '#03a9f3' }); $("#sparkline8").sparkline([2, 4, 4, 6, 8, 5, 6, 4, 8, 6, 6, 2], { type: 'line' , width: '100%' , height: '50' , lineColor: '#99d683' , fillColor: '#99d683' , maxSpotColor: '#99d683' , highlightLineColor: 'rgba(0, 0, 0, 0.2)' , highlightSpotColor: '#99d683' }); $("#sparkline9").sparkline([0, 2, 8, 6, 8, 5, 6, 4, 8, 6, 6, 2], { type: 'line' , width: '100%' , height: '50' , lineColor: '#13dafe' , fillColor: '#13dafe' , minSpotColor: '#13dafe' , maxSpotColor: '#13dafe' , highlightLineColor: 'rgba(0, 0, 0, 0.2)' , highlightSpotColor: '#13dafe' }); $("#sparkline10").sparkline([2, 4, 4, 6, 8, 5, 6, 4, 8, 6, 6, 2], { type: 'line' , width: '100%' , height: '50' , lineColor: '#ffdb4a' , fillColor: '#ffdb4a' , maxSpotColor: '#ffdb4a' , highlightLineColor: 'rgba(0, 0, 0, 0.2)' , highlightSpotColor: '#ffdb4a' }); } var sparkResize; $(window).resize(function (e) { clearTimeout(sparkResize); sparkResize = setTimeout(sparklineLogin, 500); }); sparklineLogin(); }); // Sky Icons var icons = new Skycons({ "color": "#ff6849" }) , list = [ "clear-day", "clear-night", "partly-cloudy-day" , "partly-cloudy-night", "cloudy", "rain", "sleet", "snow", "wind" , "fog" ] , i; for (i = list.length; i--;) { var weatherType = list[i] , elements = document.getElementsByClassName(weatherType); for (e = elements.length; e--;) { icons.set(elements[e], weatherType); } } icons.play(); <file_sep>let updateChartCompare = (data,vm,vmApp) => { vm.data_rep = data let type_Vi = 0, type_Ve = 0, type_P = 0 let data_rep = vm.data_rep.filter(el=>{return moment(el.date).month() === vmApp.currentMonth}) data_rep.forEach(element => { element.type_repas === 1 ? type_Ve++ : element.type_repas === 2 ? type_Vi++ : type_P++ }); let dt = [type_Ve,type_Vi,type_P] vm.chartCompare.data.datasets[0].data = dt vm.chartCompare.update() } let updateChartComparePercent = (data_rep, vm, vmApp) => { let repas_s1 = data_rep.filter(el=>{return moment(el.date).date() < 8 && moment(el.date).month() === vmApp.currentMonth}) let repas_s2 = data_rep.filter(el=>{return moment(el.date).date() < 15 && moment(el.date).date() >= 8}) let repas_s3 = data_rep.filter(el=>{return moment(el.date).date() < 22 && moment(el.date).date() >= 15}) let repas_s4 = data_rep.filter(el=>{return moment(el.date).date() >= 22 }) let data_Vege = [], data_Viande = [], data_Poisson = [] fillData(repas_s1,data_Vege,data_Viande,data_Poisson) fillData(repas_s2,data_Vege,data_Viande,data_Poisson) fillData(repas_s3,data_Vege,data_Viande,data_Poisson) fillData(repas_s4,data_Vege,data_Viande,data_Poisson) vm.chartComparePercent.data.datasets[0].data = data_Vege vm.chartComparePercent.data.datasets[1].data = data_Viande vm.chartComparePercent.data.datasets[2].data = data_Poisson vm.chartComparePercent.update() } <file_sep>let create_tdow = (sow) => { let tdow = [{id:0,date:sow.format('DD-MM-YYYY')}] for(i = 1; i < 7; i++ ){ sow = moment(sow).add(1,'days') tdow.push({id:i,date:sow.format('DD-MM-YYYY')}) } return tdow } let createRepas = (tdow,data_r,heure) => { let repas_m = []; let add_repas_template; let vege_template; let viande_template; let poisson_template; let k = 0; tdow.forEach(element => { // TEMPLATE // vege_template = '<div class="card shadow-sm border"><div class="card-body"><div class="d-flex flex-row"><div class="round sm-round align-self-center round-success"><i class="fas fa-carrot" style="vertical-align: text-top;"></i></div><div class="m-l-7 align-self-center" style="display:flex"><h4 class="m-b-0 title-card">Végétarien</h4><button class="btn btn-danger btnSuppRepas" data-date='+element.date+' data-heure='+heure+' data-id='+k+' data-toggle="modal" data-target="#modal-removeRepas"><i class="fas fa-trash-alt"></i></button></div></div></div></div></div>' viande_template = '<div class="card shadow-sm border"><div class="card-body"><div class="d-flex flex-row"><div class="round sm-round align-self-center round-warning"><i class="fas fa-drumstick-bite" style="vertical-align: text-top;"></i></div><div class="m-l-7 align-self-center" style="display:flex"><h4 class="m-b-0 title-card">Viande</h4><button class="btn btn-danger btnSuppRepas" data-date='+element.date+' data-heure='+heure+' data-id='+k+' data-toggle="modal" data-target="#modal-removeRepas"><i class="fas fa-trash-alt"></i></button></div></div></div></div>' poisson_template = '<div class="card shadow-sm border"><div class="card-body"><div class="d-flex flex-row"><div class="round sm-round align-self-center round-info"><i class="fas fa-fish" style="vertical-align: text-top;"></i></div><div class="m-l-7 align-self-center" style="display:flex"><h4 class="m-b-0 title-card">Poisson</h4><button class="btn btn-danger btnSuppRepas" data-date='+element.date+' data-heure='+heure+' data-id='+k+' data-toggle="modal" data-target="#modal-removeRepas"><i class="fas fa-trash-alt"></i></button></div></div></div></div>' add_repas_template = '<button class="ui positive button btnAddRepas verticalyCenter" data-date='+element.date+' data-heure='+heure+' data-id='+k+' data-toggle="modal" data-target="#modal-addRepas"><i class="fa fa-plus iconPlus" aria-hidden="true"></i>Ajouter un repas</button>' let repas = data_r.filter(el=>{ return (element.date === moment(el.date).format('DD-MM-YYYY') && el.heure_repas == heure) }) if(repas.length > 0){ repas[0].type_repas === 1 ? repas_m.push({id:k,type_repas : vege_template}) : repas[0].type_repas === 2 ? repas_m.push({id:k,type_repas : viande_template}) : repas_m.push({id:k,type_repas : poisson_template}) } else repas_m.push({id:k,type_repas : add_repas_template}) k++; }); return repas_m } let setArrayRepas = (heure,date,vm,id,newValue) => { if(moment(date,'DD-MM-YYYY').month() === vm.currentMonth){ if(moment(date,'DD-MM-YYYY').date() < 8) heure === 'midi' ? Vue.set(vm.repas_midi_w1, id, newValue) : Vue.set(vm.repas_soir_w1, id, newValue) else if(moment(date,'DD-MM-YYYY').date() < 15) heure === 'midi' ? Vue.set(vm.repas_midi_w2, id, newValue) : Vue.set(vm.repas_soir_w2, id, newValue) else if(moment(date,'DD-MM-YYYY').date() < 22) heure === 'midi' ? Vue.set(vm.repas_midi_w3, id, newValue) : Vue.set(vm.repas_soir_w3, id, newValue) else if(moment(date,'DD-MM-YYYY').date() < 29) heure === 'midi' ? Vue.set(vm.repas_midi_w4, id, newValue) : Vue.set(vm.repas_soir_w4, id, newValue) else heure === 'midi' ? Vue.set(vm.repas_midi_w5, id, newValue) : Vue.set(vm.repas_soir_w5, id, newValue) } else heure === 'midi' ? Vue.set(vm.repas_midi_w5, id, newValue) : Vue.set(vm.repas_soir_w5, id, newValue) }
e28f9b2257c5bb5b621c9822ea2ff59ae786246b
[ "JavaScript" ]
5
JavaScript
LeRamage/HealthyApp
9d00ee7f38fd8c2e9e723f7a00c57373082b71d2
bf6c02866924dcf212e1836251412d67fffd01f4
refs/heads/master
<file_sep>#include <SPI.h> #include <Adafruit_DotStar.h> const int Num_pixels = 23; const int Data_pin = 4; const int Clock_pin = 5; typedef uint32_t color_t; int head=0, tail=-5; color_t color = 0xFF0000; class Effect { public: virtual color_t color( int pixel, long t ) = 0; long start_time; Adafruit_DotStar strip; Effect( Adafruit_DotStar new_strip ): start_time(millis()), strip(new_strip) { strip.begin(); }; void set() { long t = millis() - start_time; for (int i = 0; i < Num_pixels; ++i) { strip.setPixelColor( i, color( i, t ) ); } }; void show() { strip.show(); } }; class Solid : public Effect { public: color_t my_color; Solid( Adafruit_DotStar new_strip, color_t new_color ): Effect(new_strip), my_color(new_color) {}; virtual color_t color( int pixel, long t ) { return my_color; }; }; class Chaser : public Effect { public: int length; long color_change_t; Chaser(Adafruit_DotStar new_strip, int new_length) : length(new_length), Effect(new_strip), color_change_t( 20*Num_pixels ) {}; virtual color_t base_color( long t ) { return 0xFF0000 >> ((t/color_change_t) % 3)*8; }; int head(long t) { return (t % (20 * Num_pixels)) / Num_pixels; }; virtual color_t color( int pixel, long t ) { int the_head = head(t); int tail = the_head - length; if ((the_head >= pixel) && (pixel >= tail)) { return base_color(t); } else { return 0; } }; }; color_t random_color() { color_t c1 = random(255); color_t c2 = random(255); color_t c3 = random(255); return ( (c3 << 16) | (c2 << 8) | (c1) ); } class Pummer : public Effect { public: int fade_duration; int loop; color_t my_color; Pummer( Adafruit_DotStar new_strip, int new_fade_duration): Effect(new_strip), fade_duration(new_fade_duration), loop(0), my_color(random_color()) {}; virtual color_t base_color(int pixel, long t) { // alternating colors) //return 0xFF0000 >> ((t / fade_duration)%3)*8; int this_loop = t/fade_duration; if (this_loop != loop) { my_color = random_color(); loop = this_loop; } return my_color; }; virtual color_t color(int pixel, long t) { color_t c = base_color(pixel, t); //now fade each component int in_fade = fade_duration - (t % fade_duration)^2; color_t c1 = ((long)(c & 0xff) * in_fade) / fade_duration; color_t c2 = (((long)(c >> 8) & 0xff) * in_fade) / fade_duration; color_t c3 = (((long)(c >> 16) & 0xff) * in_fade) / fade_duration; return ( (c3 << 16) | (c2 << 8) | (c1) ); }; }; class AltPummer : public Pummer { public: color_t my_other_color; AltPummer( Adafruit_DotStar new_strip, int new_fade_duration): Pummer(new_strip, new_fade_duration), my_other_color(random_color()) {}; virtual color_t base_color(int pixel, long t) { int this_loop = t/fade_duration; if (this_loop != loop) { my_color = random_color(); my_other_color = random_color(); loop = this_loop; } switch (pixel % 2) { case 0 : return my_color; break; case 1 : return my_other_color; break; default: return 0; } }; }; class Turn_signal : public Effect { public: boolean is_left; long delay; int width; Turn_signal( Adafruit_DotStar new_strip, boolean new_is_left, long new_delay=800, int new_width=3) : Effect(new_strip), is_left(new_is_left), delay(new_delay), width(new_width) {}; boolean is_on( long t ) { return ((t/delay) % 2) == 1; } virtual color_t color( int pixel, long t ) { if (is_on( t )) { if (is_left && (0 <= pixel) && (pixel <= width)) { return 0x00FF00; } else if ((!is_left) && (pixel <= strip.numPixels()) && ((strip.numPixels()-(width+1)) <= pixel)) { return 0x00FF00; } else { return 0; } } } }; class Reverse : public Effect { public: int width; Reverse(Adafruit_DotStar new_strip, int new_width=3) : Effect(new_strip), width(new_width) {}; virtual color_t color( int pixel, long t) { if (((0 <= pixel) && (pixel <= width)) || ((pixel <= strip.numPixels()) && ((strip.numPixels()-(width+1))<= pixel))) { return 0xFFFFFF; } else { return 0; } } }; class Headlights : public Effect { public: int width; int separation; Headlights(Adafruit_DotStar new_strip, int new_width=2, int new_separation=2): Effect(new_strip), width(new_width), separation(new_separation) {}; boolean is_headlight(int pixel) { int rmax = (strip.numPixels() + separation)/2 + width; int rmin = (strip.numPixels() + separation)/2; int lmax = (strip.numPixels() - separation)/2; int lmin = (strip.numPixels() - separation)/2 - width; return (((rmin <= pixel) && (pixel <= rmax)) || ((lmin <= pixel) && (pixel <= lmax))); } virtual color_t color(int pixel, long t) { if (is_headlight(pixel)) { return 0xFFFFFF; } else { return 0; } } }; Adafruit_DotStar strip = Adafruit_DotStar(Num_pixels, Data_pin, Clock_pin, DOTSTAR_BRG); Solid off(strip, 0); Solid underlight(strip, 0x333333); Chaser chaser(strip, 5); Pummer pummer(strip, 500); AltPummer alt_pummer(strip, 500); Turn_signal left_turn(strip, true); Turn_signal right_turn(strip, false); Reverse reverse(strip); Headlights headlights(strip); const int Pin_input_enable = 8; const int Pin_input = 9; const int Pin_s0 = 10; const int Pin_s1 = 11; const int Pin_s2 = 12; byte read_mux() { byte result = 0; for (int i = 0; i <= 7; ++i) { // select the input digitalWrite(Pin_s0, i & 1); digitalWrite(Pin_s1, (i >> 1) & 1); digitalWrite(Pin_s2, (i >> 2) & 1); // strobe low to read digitalWrite(Pin_input_enable, LOW); result |= (digitalRead( Pin_input ) << i); digitalWrite(Pin_input_enable, HIGH); } return result; } Effect* effects[] = {&off, &underlight, &left_turn, &right_turn, &reverse, &headlights, &pummer, &alt_pummer, &chaser}; int last_selection = 0; Effect* chosen_effect = NULL; void setup() { // put your setup code here, to run once: Serial.begin(9600); strip.begin(); strip.show(); last_selection = 0; chosen_effect = effects[last_selection]; pinMode( Pin_input, INPUT ); pinMode( Pin_input_enable, OUTPUT ); pinMode( Pin_s0, OUTPUT ); pinMode( Pin_s1, OUTPUT ); pinMode( Pin_s2, OUTPUT ); } int selection_from_mux(byte mux) { int result = 0; switch(mux) { case 0: result = 0; break; case 1: result = 1; break; case 2: result = 2; break; case 4: result = 3; break; case 8: result = 4; break; case 16: result = 5; break; case 32: result = 6; break; case 64: result = 7; break; case 128: result = 8; break; default: result = 0; break; } return result; } void loop() { chosen_effect = effects[selection_from_mux(read_mux())]; chosen_effect->set(); chosen_effect->show(); //Serial.println("--"); //Serial.println(chaser.head( millis() )); //Serial.println(chaser.base_color( millis() )); //Serial.println(selection_from_mux(read_mux())); //delay(200); //chaser.set(); //chaser.show(); //headlights.set(); //headlights.show(); /* strip.setPixelColor(head, color); */ /* strip.setPixelColor(tail, 0); */ /* strip.show(); */ /* delay(20); */ /* if (++head >= Num_pixels) { */ /* head = 0; */ /* if ((color >>= 8) == 0) { */ /* color = 0xFF0000; */ /* } */ /* } */ /* if (++tail >= Num_pixels) { */ /* tail = 0; */ /* } */ } <file_sep># scooterbling
a0d34d9ad04340ad02ca9ce1a913e1ceba41609d
[ "Markdown", "C++" ]
2
C++
vputz/scooterbling
1f02ce57b53edd0592f25d67e50848d9a14ece8b
d2d3901c43cd5c5bf207aa5b26268ebdb8d52298
refs/heads/master
<file_sep>import Head from "next/head"; import products from "../products.json"; import styles from '../styles/Home.module.css' import { fromImageToUrl } from "../utils/urls" const Home = () => { return ( <div> <Head> <title>Create Next Appa</title> <meta name="description" content="Generated by create next app" /> <link rel="icon" href="/favicon.ico" /> </Head> Testing 132 {products.map((product) => ( <div key={product.name} className={styles.product}> <div className={styles.product__Row}> <div className={styles.product__ColImg}> <img className={styles.product__Im} src={fromImageToUrl(product.image)} alt="" /> </div> <div className={styles.product__Col}> {product.name} {product.price} </div> </div> </div> ))} </div> ); } export default Home<file_sep>module.exports = { jwtSecret: process.env.JWT_SECRET || '7f05015e-9756-49cd-9a05-a272db5ad21d' };
fd0d4fa0d067cc4efdf660f31139adc875ce5b8f
[ "JavaScript" ]
2
JavaScript
troias/strapi-ecom
e9e2305a9ec392c564eae772195f86aef40e9021
67a8c427e13b5b50a8d050f154b996ef1176be99
refs/heads/master
<repo_name>aunyamanee7112/work-board<file_sep>/src/app/dialog/edittask/edittask.component.ts import { Component, Inject, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { TaskViewComponent } from 'src/app/task-view/task-view.component'; @Component({ selector: 'app-edittask', templateUrl: './edittask.component.html', styleUrls: ['./edittask.component.scss'], }) export class EdittaskComponent implements OnInit { form: FormGroup; get task (){ return this.form.get('task') } constructor( private fb: FormBuilder, private dialogRef: MatDialogRef<TaskViewComponent, any>, @Inject(MAT_DIALOG_DATA) public data: any ) {} ngOnInit() { console.log(this.data); this.initForm(); } private initForm() { this.form = this.fb.group({ task: null, }); this.task.patchValue(this.data); } created() { this.dialogRef.close(this.form.value); } } <file_sep>/src/app/taskservice.service.ts import { Injectable } from '@angular/core'; import { WebRequestService } from './web-request.service'; import { Task } from 'api/db/models/'; @Injectable({ providedIn: 'root' }) export class TaskserviceService { constructor(private webRequest :WebRequestService) { } createList(title:string){ return this.webRequest.post('list',{title}); } createTasks(listId,title){ return this.webRequest.post(`list/${listId}/tasks`,{title}) } getList(){ return this.webRequest.get('list'); } getTasks(listId:string){ return this.webRequest.get(`list/${listId}/tasks`) } deleteList(id){ return this.webRequest.deleter(`list/${id}`) } deleteTask(task){ return this.webRequest.deleter(`list/${task._listId}/tasks/${task._id}`) } updateList(id,title){ return this.webRequest.patch(`list/${id}`,{title}) } updateTask(task,title){ return this.webRequest.patch(`list/${task._listId}/tasks/${task._id}`,{title}) } completed(task,condition){ return this.webRequest.patch(`list/${task._listId}/tasks/${task._id}` ,{completed:condition} )} } <file_sep>/api/db/models/user.model.js const mongoose = require("mongoose"); const jwt = require("jsonwebtoken"); const bcrypt = require("bcryptjs"); //JWT secret const jwtSecret = "<KEY>"; const crypto = require("crypto"); const UserSchema = new mongoose.Schema({ email: { type: String, required: true, minlength: 1, trim: true, unique: true, }, password: { type: String, required: true, minlength: 8, }, sessions: [ { token: { type: String, required: true, }, expiresAt: { type: Number, required: true, }, }, ], }); UserSchema.methods.toJSON = function () { const user = this; const userObject = user.toObject(); // return the doc expect the passwoed and sessions // These shouldn't be made avalible return _.omit(userObject, ["password", "sessions"]); }; UserSchema.methods.generateAccessAuthToken = function () { const user = this; return new Promise((reslove, reject) => { //create json web token and return that jwt.sign( { _id: user._id.toHexString() }, jwtSecret, { expiresIn: "15m" }, (err, token) => { if (!err) { reslove(token); } else { reject(); } } ); }); }; UserSchema.methods.createSession = function () { let user = this; return user.generateRefreshAuthToken().then((refreshToken) => { return saveSessionToDatabase(user, refreshToken) .then((refreshToken) => { return refreshToken; }) .catch((e) => { return Promise.reject("Falied to save session to database" + e); }); }); }; UserSchema.methods.generateRefreshAuthToken = function () { return new Promise((reslove, reject) => { crypto.randomBytes(64, (err, buf) => { let token = buf.toString("Hex"); return reslove(token); }); }); }; /*MODEL METHODS STATIC METHODS*/ UserSchema.statics.findByIdAndToken = function (_id, token) { const User = this; return User.findOne({ _id, "sessions.token": token, }); }; UserSchema.statics.findByCredentials = function (email, password) { let user = this; return user.findOne({ email }).then((user) => { if (!user) return Promise.reject(); return new Promise((reslove, reject) => { bcrypt.compare(password, user.password, (err, res) => { if (res) reslove(user); else { reject(err); } }); }); }); }; UserSchema.statics.hashRefreshTokenExpired = (expireAt) => { let secondsSinceEpoch = Date.now() / 1000; if (expireAt > secondsSinceEpoch) { return false; } else { return true; } }; /*MIDDLE WARE*/ UserSchema.pre("save", function (next) { let user = this; let costFactor = 10; if (user.isDirectModified("password")) { // if the password field has been edited the run this code //Generate salt and hash password bcrypt.genSalt(costFactor, (err, salt) => { bcrypt.hash(user.password, salt, (err, hash) => { user.password = hash; next(); }); }); } else { next(); } }); /*HELPER METHODs*/ let saveSessionToDatabase = (user, refreshToken) => { return new Promise((resolve, reject) => { let expireAt = generateRefreshTokenExpiryTime(); user.sessions.push({ token: refreshToken, expireAt }); user .save() .then(() => { return resolve(refreshToken); }) .catch((e) => { reject(e); }); }); }; let generateRefreshTokenExpiryTime = () => { let dayUntilExpire = 10; let secondUntilExpire = ((dayUntilExpire * 24) * 60 * 60); return ( (Date.now() / 1000) + secondUntilExpire); }; const User = mongoose.model("User", UserSchema); module.exports = { User }; <file_sep>/src/app/web-request.service.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class WebRequestService { readonly ROOT_URL constructor(private http:HttpClient) { this.ROOT_URL = 'http://localhost:3000' } get(url:string){ return this.http.get(`${this.ROOT_URL}/${url}`) } post(url:string, payload:object){ return this.http.post(`${this.ROOT_URL}/${url}`,payload) } patch(url:string, payload:object){ return this.http.patch(`${this.ROOT_URL}/${url}`,payload) } deleter(url:string){ return this.http.delete(`${this.ROOT_URL}/${url}`) } } <file_sep>/src/app/task-view/task-view.component.ts import { Component, OnInit } from '@angular/core'; import { TaskserviceService } from './../taskservice.service'; import { MatDialog, MatDialogRef, MatDialogConfig, } from '@angular/material/dialog'; import { NewlistComponent } from '../dialog/newlist/newlist.component'; import { ActivatedRoute, Params, Router, RouterModule } from '@angular/router'; import { NewtaskComponent } from '../dialog/newtask/newtask.component'; import { threadId } from 'worker_threads'; import { EditlistComponent } from '../dialog/editlist/editlist.component'; import { EdittaskComponent } from '../dialog/edittask/edittask.component'; import { takeUntil, filter, switchMap } from 'rxjs/operators'; // import { Task } from 'api/db/models/' @Component({ selector: 'app-task-view', templateUrl: './task-view.component.html', styleUrls: ['./task-view.component.scss'], }) export class TaskViewComponent implements OnInit { lists; tasks; taskStatus; checklist: boolean = true; title; listId: string; constructor( private TaskService: TaskserviceService, private dialog: MatDialog, private route: ActivatedRoute, private router: Router ) {} ngOnInit(): void { this.getList(); this.listId = this.route.snapshot.paramMap.get('listId'); console.log(this.listId); } createNewList() { this.dialog .open(NewlistComponent) .afterClosed() .subscribe((res) => { console.log(res.listName); if (res) { return this.TaskService.createList(res.listName).subscribe( (responde: any) => { console.log(responde); this.getList(); } ); } }); } getList() { return this.TaskService.getList().subscribe((res) => { console.log(res); this.lists = res; }); } getTask(item) { console.log(item.title); try { this.router.navigate([`list/${item._id}/${item.title}`]).then(() => { this.TaskService.getTasks(item._id).subscribe((res) => { console.log(res); this.title = this.route.snapshot.paramMap.get('title'); this.tasks = res; }); }); } catch (error) { console.log(error); } } getTaskafterDialog(item) { try { this.TaskService.getTasks(item).subscribe((res) => { console.log(res); this.title = this.route.snapshot.paramMap.get('title'); this.tasks = res; }); } catch (error) { console.log(error); } } checkTask(task): void { task.completed = !task.completed; console.log(task.completed); } createTask() { let id = this.listId this.dialog .open(NewtaskComponent) .afterClosed() .subscribe((res) => { console.log(res); try { if (res) { return this.TaskService.createTasks( this.listId, res.task ).subscribe((responde: any) => { // this.getTaskafterDialog(id) console.log(responde); }); } } catch (error) { console.log(error); } }); } deleteList() { this.TaskService.deleteList(this.listId).subscribe(() => { this.getList(); }); } deleteTask(task) { console.log(task); this.TaskService.deleteTask(task).subscribe(() => { this.getTaskafterDialog(task._listId); }); } updateTask(task) { const dialogConfig: MatDialogConfig = { data: task.title, }; this.dialog .open(EdittaskComponent, dialogConfig) .afterClosed() .subscribe((res) => { try { if (res) { return this.TaskService.updateTask(task, res.task).subscribe( (responde: any) => { console.log(responde); this.getTaskafterDialog(task._listId); } ); } } catch (error) { console.log(error); } }); } updateList() { const title = this.route.snapshot.paramMap.get('title'); const dialogConfig: MatDialogConfig = { data: title, }; this.dialog .open(EditlistComponent, dialogConfig) .afterClosed() .subscribe((res) => { console.log(res); try { if (res) { return this.TaskService.updateList( this.listId, res.task ).subscribe((responde: any) => { // this.getTask(this.listId) console.log(responde); }); } } catch (error) { console.log(error); } }); } } <file_sep>/src/app/signup/signup.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.scss'] }) export class SignupComponent implements OnInit { form:FormGroup iconstatus=true; type="password" constructor( private fb:FormBuilder ) { } ngOnInit(): void { this.initForm() } private initForm(){ this.form = this.fb.group({ email:null, password:<PASSWORD> }) } } <file_sep>/api/db/mongoose.js // handle connection to MongoDB const mongoose = require('mongoose'); mongoose.Promise = global.Promise; mongoose.connect('mongodb://localhost:27017/TaskManager', {useNewUrlParser:true}) .then(()=>{ console.log("Connected to MongoDB successfully:)"); }).catch( (err)=>{ console.log("Error while u access to mongo DB"); console.log(err); } ); mongoose.set('useCreateIndex',true); mongoose.set('useFindAndModify',false); module.exports = { mongoose } <file_sep>/api/app.js const express = require("express"); const app = express(); const cors = require("cors"); const mongoose = require("./db/mongoose"); //Load in the moonge models const { List, Task } = require("./db/models"); const bodyParser = require("body-parser"); // Cors handdle app.use( cors({ credentials: true, origin: true, // methods: 'GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS' }) ); // app.use((req, res, next) => { // let refreshToken = req.header('x-refresh-token'); // let _id = req.header('_id') // User.findOneAndToken(_id, token).then((user) => { // if (!user) { // return Promise.reject({ // 'error': 'user not found' // }); // } // req.user_id = user._id; // req.refreshToken = refreshToken; // let isSessionValid // user.sessions.forEach(session => { // if (session.token === refreshToken) { // if (User.hashRefreshTokenExpired(session.expiresAt) === false) { // isSessionValid = true // } // } // }); // if (isSessionValid) { // next(); // } else { // return Promise.reject({ // 'error': 'Refresh token has expired' // }).catch((e) => { // res.status(401).send(e) // }) // } // }) // }) // Load middelware app.use(bodyParser.json()); /*Route Handlers*/ /*LIST ROUTES*/ app.get("/list", (req, res) => { //return all of list in database List.find({}).then((list) => { res.send(list); }); }); app.post("/list", (req, res) => { //new list let title = req.body.title; let newList = new List({ title, }); newList.save().then((listDoc) => { //the full list Document is returned(incl.id) res.send(listDoc); }); }); app.patch("/list/:id", (req, res) => { List.findOneAndUpdate({ _id: req.params.id }, { $set: req.body }).then(() => { res.send({ message: "complete successfull" }); }); }); app.delete("/list/:id", (req, res) => { List.findByIdAndRemove({ _id: req.params.id, }).then((removedListDoc) => { res.send(removedListDoc); }); }); //TaskZone app.get("/list/:listId/tasks", (req, res) => { Task.find({ _listId: req.params.listId, }).then((tasks) => { res.send(tasks); }); }); app.post("/list/:listId/tasks", (req, res) => { let newTask = new Task({ title: req.body.title, _listId: req.params.listId, }); newTask.save().then((newTaskDoc) => { res.send(newTaskDoc); }); }); app.patch("/list/:listId/tasks/:taskId", (req, res) => { Task.findOneAndUpdate( { _id: req.params.taskId, _listId: req.params.listId, }, { $set: req.body, } ).then(() => { res.send({ message: "complete successfull" }); }); }); app.delete("/list/:listId/tasks/:taskId", (req, res) => { Task.findOneAndRemove({ _id: req.params.taskId, _listId: req.params.listId, }).then((taskDoc) => { res.send(taskDoc); }); }); app.get("/list/:listId/tasks/:taskId" ,(req,res)=>{ Task.find({ _id: req.params.taskId, _listId:req.params.listId }).then((task)=>{ res.send(task) }) }); app.listen(3000, () => { console.log("Server is listening on port 3000"); }); /*USER ROUTES*/
ee54bb3b11810dd28091e89f63748088100994f5
[ "JavaScript", "TypeScript" ]
8
TypeScript
aunyamanee7112/work-board
91bfc0257cb569fd1282ed054297043e6eb59ab5
fe6ee8e83a26c09c17f56e80a14351a4224f3643
refs/heads/master
<repo_name>drolean/laravel-video-embed<file_sep>/src/Facades/LaravelVideoEmbed.php <?php namespace Merujan99\LaravelVideoEmbed\Facades; /** * Class Facade */ use Illuminate\Support\Facades\Facade; class LaravelVideoEmbed extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'Merujan99\LaravelVideoEmbed\Services\LaravelVideoEmbed'; } }
232f3f0f4eb4d3d285c5a0fd2feeaa6918b2f013
[ "PHP" ]
1
PHP
drolean/laravel-video-embed
4288ef0c0a553f491f432495d5173eda1ba54656
6ff8f1880e45b0f914b6c1ae6821411a2aa5ec53
refs/heads/master
<file_sep># rancher-update This action helps by updating a service in the Rancher 2 environment with kubernetes. # Examples ## Update service ```yaml on: push: branches: - master jobs: release: runs-on: ubuntu-latest steps: - uses: sekassel-research/[email protected] with: rancher_url: https://rancher.test.de rancher_token: ${{ secrets.RANCHER_TOKEN }} cluster_id: ${{ secrets.CLUSTER_ID }} project_id: ${{ secrets.PROJECT_ID }} namespace: ${{ secrets.NAMESPACE }} deployment: ${{ secrets.DEPLOYMENT }} docker_image: sekassel-research/test-image:latest ``` # Backwards compatibility If you want to use this extension for `Rancher 1.6.x`, you need to use the following version `sekassel-research/[email protected]` ## Example ```yaml on: push: branches: - master jobs: release: runs-on: ubuntu-latest steps: - uses: sekassel-research/[email protected] with: rancher_url: https://rancher.test.de rancher_access: ${{ secrets.RANCHER_ACCESS }} rancher_key: ${{ secrets.RANCHER_KEY }} project_id: 1a5 stack_name: test-stack service_name: test-service docker_image: sekassel-research/test-image:latest ``` <file_sep>const core = require('@actions/core'); const axios = require('axios'); process.on('unhandledRejection', handleError); main().catch(handleError); async function main() { const rancherUrl = core.getInput('rancher_url', {required: true}); const rancherToken = core.getInput('rancher_token', {required: true}); const clusterId = core.getInput('cluster_id', {required: true}); const projectId = core.getInput('project_id', {required: true}); const namespace = core.getInput('namespace', {required: true}); const deployment = core.getInput('deployment', {required: true}); const dockerImage = core.getInput('docker_image', {required: true}); const showErrorLogs = core.getInput('error_logs', {required: false}); try { await axios.patch( `${rancherUrl}/k8s/clusters/${clusterId}/apis/apps/v1/namespaces/${namespace}/deployments/${deployment}`, [ { op: 'replace', path: '/spec/template/spec/containers/0/image', value: dockerImage, }, ], { headers: { 'Content-Type': 'application/json-patch+json', 'Authorization': 'Bearer ' + rancherToken, }, }, ); } catch(e) { if(showErrorLogs) console.log(e); console.log("Provavelmente o workload é um por node, caso n seja envie a env error_logs") } try { await axios.post( `${rancherUrl}/v3/projects/${clusterId}:${projectId}/workloads/deployment:${namespace}:${deployment}?action=redeploy`, {}, { headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + rancherToken, }, }, ); } catch (e) { if(showErrorLogs) console.log(e); console.log("Provavelmente o workload é um por node, caso n seja envie a env error_logs") await axios.post( `${rancherUrl}/v3/projects/${clusterId}:${projectId}/workloads/daemonset:${namespace}:${deployment}?action=redeploy`, {}, { headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + rancherToken, }, }, ); } } function handleError(err) { console.log(err); core.setFailed(err.message); }
2983824de844ce1de2578dc4f3b220fb45b4d5f2
[ "Markdown", "JavaScript" ]
2
Markdown
pessoalize/actions-rancher-update
8aa87f9623a564b5ce4c49aa708aafe2b454a373
13e170f77255bcee56cc6d0cf46b6fae5d7dd32d
refs/heads/master
<repo_name>genchilu/junit-practice<file_sep>/src/main/java/url/genchi/practice/junit/ValidateField.java package url.genchi.practice.junit; import java.util.HashMap; import java.util.regex.Pattern; public class ValidateField { final private static Pattern ipWhitePat = Pattern.compile( "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); final private static Pattern ipBlackPat = Pattern.compile( "^(?:(?:127|172.16|0|255|169|224|192.168).).*"); public static boolean validateIP(String ip) { if(ip == null) { return false; } boolean passWhite = ipWhitePat.matcher(ip).matches(); boolean passBlack = !ipBlackPat.matcher(ip).matches(); return (passWhite && passBlack); } //下面的 pattern 不能 match <EMAIL> //final private static Pattern mailWhilePat = Pattern.compile("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)(\\.[a-zA-Z]{2,})$"); final private static Pattern mailWhilePat = Pattern.compile("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)?(?:\\.[a-zA-Z]{2,})$"); final private static Pattern mailBlackPat = Pattern.compile( ".*(?:-\\.|\\.-).*"); public static boolean validateMail(String mail) { if(mail == null) { return false; } boolean passLowerCase = mail.startsWith(mail.toLowerCase()); boolean passWhite = mailWhilePat.matcher(mail).matches(); boolean passBlack = !mailBlackPat.matcher(mail).matches(); return (passLowerCase && passWhite && passBlack); } private static HashMap<Character, Integer> leter2ValidSum = new HashMap<Character, Integer>(){{ put('A', 1); put('B', 10); put('C', 19); put('D', 28); put('E', 37); put('F', 46); put('G', 55); put('H', 64); put('J', 73); put('K', 82); put('L', 2); put('M', 11); put('N', 20); put('P', 29); put('Q', 38); put('R', 47); put('S', 56); put('T', 65); put('U', 74); put('V', 83); put('X', 3); put('Y', 12); put('W', 21); put('Z', 30); put('I', 39); put('O', 48); }}; private static boolean isValidLocalIdNumber(String idNumber) { int validSum = leter2ValidSum.get(idNumber.charAt(0)); for(int i = 0; i<8;i++){ int digit = Character.getNumericValue(idNumber.charAt(i+1)); validSum += digit*(8-i); } int lastDigit = Character.getNumericValue(idNumber.charAt(9)); validSum += lastDigit; return ((validSum % 10) == 0); } final private static Pattern localIdNumberPat = Pattern.compile("^(?i)[a-hj-z][1-2][0-9]{8}$"); final private static Pattern foreignIdNumberPat = Pattern.compile("^(?i)[i][0-9]{9}$"); public static boolean validateIdNumber(String idNumber) { if(idNumber == null) { return false; } boolean passUpperCase = idNumber.equals(idNumber.toUpperCase()); boolean passLocalIDNumberPat = localIdNumberPat.matcher(idNumber).matches() && ValidateField.isValidLocalIdNumber(idNumber); boolean passForeignIDNumberPat = foreignIdNumberPat.matcher(idNumber).matches(); return passUpperCase && (passLocalIDNumberPat || passForeignIDNumberPat); } public static void main(String args[]) { String tmp = "A368829966"; System.out.println(Character.getNumericValue('3')); } } <file_sep>/src/main/resources/db.properties driver=org.h2.Driver jdbcurl=jdbc:h2:tcp://localhost/~/mydb user=sa pwd= <file_sep>/src/test/java/url/genchi/practice/db/TodoListDaoTest.java package url.genchi.practice.db; import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.UUID; import junit.framework.TestCase; import org.junit.Test; /** * Created by genchi.lu on 2017/5/26. */ public class TodoListDaoTest extends TestCase{ private TodoListDao tdo; private JDBCSource jdbcSource; private TodoList testTdl1 = new TodoList("test 1"); private TodoList testTdl2 = new TodoList("test 2"); @Override protected void setUp() throws Exception { Properties prop = new Properties(); InputStream in = TodoListDao.class.getClassLoader().getResourceAsStream("db.properties"); prop.load(in); in.close(); String driver = prop.getProperty("driver").toString(); String jdbcurl = prop.get("jdbcurl").toString(); String user = prop.get("user").toString(); String pwd = prop.get("pwd").toString(); this.jdbcSource = new JDBCSource(driver, jdbcurl, user, pwd); Statement stmt = jdbcSource.getConn().createStatement(); stmt.execute("CREATE TABLE TODOLIST (\n" + " ID UUID PRIMARY KEY,\n" + " DESCRIPTION char(50),\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8;"); stmt.close(); jdbcSource.getConn().commit(); this.tdo = new TodoListDao(this.jdbcSource); this.tdo.saveTodoList(this.testTdl1); this.tdo.saveTodoList(this.testTdl2); } @Test public void testSaveTodoList() throws Exception { TodoList tdlOri = new TodoList("test save"); this.tdo.saveTodoList(tdlOri); TodoList tdlFromDao = tdo.findOneById(tdlOri.getId().toString()); assertTrue(tdlOri.equals(tdlFromDao)); } @Test public void testUpdateTodoList() throws Exception { this.testTdl1.setDescription("after update"); this.tdo.updateTodolist(testTdl1); TodoList tdlFromDao = tdo.findOneById(testTdl1.getId().toString()); assertTrue(this.testTdl1.equals(testTdl1)); } @Test public void testFindOneById_ExistId() throws Exception { TodoList tdlFromDao = this.tdo.findOneById(testTdl1.getId().toString()); assertTrue(this.testTdl1.equals(tdlFromDao)); } @Test public void testFindOneById_NonExistId_ShouldNull() throws Exception { TodoList tdlFromDao = this.tdo.findOneById(UUID.randomUUID().toString()); assertNull(tdlFromDao); } @Test public void testFindAll() throws Exception { List<TodoList> tdlListFromDao = this.tdo.findAll(); List<TodoList> testTdlList = new LinkedList<>(); testTdlList.add(testTdl1); testTdlList.add(testTdl2); assertTrue(isListEqual(testTdlList, tdlListFromDao)); } static private boolean isListEqual(List<TodoList> list1, List<TodoList> list2){ if(list1.size() != list2.size()) { return false; } for(int i = 0;i<list1.size();i++) { boolean isIdEqual = list1.get(i).getId().toString().equals(list2.get(i).getId().toString()); boolean isDescEqual = list1.get(i).getDescription().equals(list2.get(i).getDescription()); if(!isDescEqual || !isDescEqual) { return false; } } return true; } @Test public void testdeleteTodoList_Delete_ExistId_And_Find_Should_Null() throws Exception { String id = testTdl1.getId().toString(); this.tdo.deleteTodoList(testTdl1); TodoList tdlFromDao = this.tdo.findOneById(id); assertNull(tdlFromDao); } @Override protected void tearDown() throws Exception { Statement stmt = jdbcSource.getConn().createStatement(); stmt.execute("DROP TABLE TODOLIST"); stmt.close(); jdbcSource.getConn().commit(); } } <file_sep>/src/test/java/url/genchi/practice/junit/JvmCheckerTest.java package url.genchi.practice.junit; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.*; import org.junit.Test; import url.genchi.practice.mockito.JvmChecker; import url.genchi.practice.mockito.JvmRuntimeMetricDao; import static org.junit.Assert.assertTrue; /** * Created by genchi.lu on 2017/5/25. */ public class JvmCheckerTest { @Test public void isThreadAlmostExceed_MemExceed_ShouldTrue() throws Exception { JvmRuntimeMetricDao jvmRuntimeMetricDaoMock = mock(JvmRuntimeMetricDao.class); when(jvmRuntimeMetricDaoMock.getMaxmem()).thenReturn(1024l); when(jvmRuntimeMetricDaoMock.getFreemem()).thenReturn(64l); when(jvmRuntimeMetricDaoMock.getTotalmem()).thenReturn(768l); boolean testMemExceedResult = JvmChecker.isMemoryAlmostExceed(jvmRuntimeMetricDaoMock); verify(jvmRuntimeMetricDaoMock).getMaxmem(); verify(jvmRuntimeMetricDaoMock).getFreemem(); verify(jvmRuntimeMetricDaoMock).getTotalmem(); verify(jvmRuntimeMetricDaoMock, never()).getThreadCount(); assertTrue(testMemExceedResult); } @Test public void isThreadAlmostExceed_MemNotExceed_ShouldFalse() throws Exception { JvmRuntimeMetricDao jvmRuntimeMetricDaoMock = mock(JvmRuntimeMetricDao.class); when(jvmRuntimeMetricDaoMock.getMaxmem()).thenReturn(1024l); when(jvmRuntimeMetricDaoMock.getFreemem()).thenReturn(512l); when(jvmRuntimeMetricDaoMock.getTotalmem()).thenReturn(768l); boolean testMemExceedResult = JvmChecker.isMemoryAlmostExceed(jvmRuntimeMetricDaoMock); verify(jvmRuntimeMetricDaoMock).getMaxmem(); verify(jvmRuntimeMetricDaoMock).getFreemem(); verify(jvmRuntimeMetricDaoMock).getTotalmem(); verify(jvmRuntimeMetricDaoMock, never()).getThreadCount(); assertFalse(testMemExceedResult); } @Test public void isThreadAlmostExceed_ThreadExceed_ShouldTrue() throws Exception { JvmRuntimeMetricDao jvmRuntimeMetricDaoMock = mock(JvmRuntimeMetricDao.class); when(jvmRuntimeMetricDaoMock.getThreadCount()).thenReturn(900); boolean testThreadExceedResult = JvmChecker.isThreadAlmostExceed(jvmRuntimeMetricDaoMock); verify(jvmRuntimeMetricDaoMock, never()).getMaxmem(); verify(jvmRuntimeMetricDaoMock, never()).getFreemem(); verify(jvmRuntimeMetricDaoMock, never()).getTotalmem(); verify(jvmRuntimeMetricDaoMock).getThreadCount(); assertTrue(testThreadExceedResult); } @Test public void isThreadAlmostExceed_ThreadExceed_ShouldFalse() throws Exception { JvmRuntimeMetricDao jvmRuntimeMetricDaoMock = mock(JvmRuntimeMetricDao.class); when(jvmRuntimeMetricDaoMock.getThreadCount()).thenReturn(200); boolean testThreadExceedResult = JvmChecker.isThreadAlmostExceed(jvmRuntimeMetricDaoMock); verify(jvmRuntimeMetricDaoMock, never()).getMaxmem(); verify(jvmRuntimeMetricDaoMock, never()).getFreemem(); verify(jvmRuntimeMetricDaoMock, never()).getTotalmem(); verify(jvmRuntimeMetricDaoMock).getThreadCount(); assertFalse(testThreadExceedResult); } } <file_sep>/src/test/resources/db.properties driver=org.h2.Driver jdbcurl=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 user=sa pwd=
8aee2b05bd1579029ce41eb16521cd8230db75ef
[ "Java", "INI" ]
5
Java
genchilu/junit-practice
4336543a9007fabf2145e342880623de744ea760
12741fdd189db8881461661d76a8d5ea1b207342
refs/heads/master
<file_sep>countdown ========= jQuery countdown Plugin DEMO: ========= http://zx12.github.io/countdown/ DESCRIPTION: ========= jQuery countdownu Plugin <file_sep>/*! * countdown.js, v0.1, MIT License * https://github.com/Zx12/countdown * <EMAIL> */ (function ($, window) { 'use strict'; var def = { until: '2077, 01, 01', step: 1000, onTick: false, onExpiry: false }; function getLeft(until, date) { var left = {}, deff = (until - date) / 1000; left.days = parseInt(deff / 86400, 10); deff = deff % 86400; left.hours = parseInt(deff / 3600, 10); deff = deff % 3600; left.minutes = parseInt(deff / 60, 10); left.seconds = parseInt(deff % 60, 10); return left; } window.zCountDown = function (options) { var interval, setting, date, until, onExpiry = function () {}, onTick = function () {}; setting = $.extend({}, def, options); until = new Date(setting.until).getTime(); if (typeof setting.onExpiry === 'function') { onExpiry = setting.onExpiry; } if (typeof setting.onTick === 'function') { onTick = setting.onTick; } function tick() { date = new Date().getTime(); if (until < date) { until = date; window.clearInterval(interval); onExpiry(); } onTick(getLeft(until, date)); } tick(); interval = window.setInterval(tick, setting.step); }; }(jQuery, this));
f22f3265d650dd5b10e50ad07fecc632c72c45ca
[ "Markdown", "JavaScript" ]
2
Markdown
Zx12/countdown
686cd5b255b91533fd369822d134cef03c1d4d18
eb44ae3de76a45c8b9560c472f8527a3bd444a9f
refs/heads/master
<repo_name>MicA-98/TMPS<file_sep>/src/main/java/clients/Client.java package clients; import department.Department; import offer.Offer; public abstract class Client { private Department department; private int clientCode; public Client(Department newDepartment) { department = newDepartment; department.addClient(this); } public void buyOffer(Offer offer) { department.buyOffer(offer, this.clientCode); } public void setClientCode(int clientCode) { this.clientCode = clientCode; } } <file_sep>/src/main/java/offer/Signature.java package offer; //Singleton Pattern public class Signature { private static Signature signature = null; private String sign; private Signature() { } public String getSign() { return this.sign; } public static Signature getInstance() { if (signature == null) { signature = new Signature(); signature.sign = "<NAME>"; } return signature; } } <file_sep>/src/main/java/offer/ChocolateCandyOffer.java package offer; public class ChocolateCandyOffer extends Offer implements CloneableOffer { private String chocolateType; public String getChocolateType() { return chocolateType; } public void setChocolateType(String chocolateType) { this.chocolateType = chocolateType; } public CloneableOffer makeCopyOffer() { ChocolateCandyOffer chocolateCandyOffer = null; try { chocolateCandyOffer = (ChocolateCandyOffer) super.clone(); chocolateCandyOffer.setOfferId(Offer.getNewOfferId()); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return chocolateCandyOffer; } } <file_sep>/src/main/java/offer/CloneableOffer.java package offer; public interface CloneableOffer extends Cloneable { CloneableOffer makeCopyOffer(); } <file_sep>/src/main/java/offer/Offer.java package offer; public abstract class Offer { private String signature; private Integer count; private String typeOfCandy; private int offerId; private static int newOfferId = 0; private static void incrementOfferId(){ newOfferId++; } public static int getNewOfferId(){ return newOfferId; } public int getOfferId(){ return this.offerId; } public void setOfferId(int offerId) { this.offerId = getNewOfferId(); incrementOfferId(); } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public String getTypeOfCandy() { return typeOfCandy; } public void setTypeOfCandy(String typeOfCandy) { this.typeOfCandy = typeOfCandy; } } <file_sep>/src/main/java/clients/Worker.java package clients; import department.Department; import offer.Offer; public class Worker { private Department department; private int workerId; public Worker(Department newDepartment) { department = newDepartment; } public void setOffer(Offer offer) { department.setOffer(offer, offer.getOfferId(), this.workerId); } public int getWorkerId() { return workerId; } public void setWorkerId(int workerId) { this.workerId = workerId; } } <file_sep>/src/main/java/StartCandyFactory.java import candy.Candy; import candy.MainCandy; import candy.toppings.Caramel; import candy.toppings.Chocolate; import candy.toppings.StrawberryJam; import clients.Client; import clients.Metro; import clients.Nr1; import clients.Worker; import conveyer.ChocolateConveyer; import conveyer.ConveyerChain; import conveyer.MarmeladeConveyer; import department.SaleDepartment; import facade.FactoryInterface; import offer.ChocolateCandyOffer; import offer.MarmeladeCandyOffer; import offer.OfferMaker; import offer.Signature; public class StartCandyFactory { public static void main(String[] args) { OfferMaker offerMaker = new OfferMaker(); MarmeladeCandyOffer marmeladeCandyOffer = new MarmeladeCandyOffer(); marmeladeCandyOffer.setOfferId(0); marmeladeCandyOffer.setColor("Red"); marmeladeCandyOffer.setCount(40); marmeladeCandyOffer.setSignature(Signature.getInstance().getSign()); marmeladeCandyOffer.setTypeOfCandy("Marmelade"); ChocolateCandyOffer chocolateCandyOffer = new ChocolateCandyOffer(); chocolateCandyOffer.setOfferId(0); chocolateCandyOffer.setChocolateType("MilkChocolate"); chocolateCandyOffer.setCount(40); chocolateCandyOffer.setSignature(Signature.getInstance().getSign()); chocolateCandyOffer.setTypeOfCandy("Chocolate"); ChocolateCandyOffer clonedChocolateCandyOffer = (ChocolateCandyOffer) offerMaker.getClonedOffer(chocolateCandyOffer); System.out.println(chocolateCandyOffer.getChocolateType()); System.out.println(clonedChocolateCandyOffer.getChocolateType()); System.out.println(clonedChocolateCandyOffer.getSignature()); //---------------------------------------------------------------------------- SaleDepartment saleDepartment = new SaleDepartment(); Worker saleWorker = new Worker(saleDepartment); saleWorker.setWorkerId(100); Client metro = new Metro(saleDepartment); Client nr1 = new Nr1(saleDepartment); metro.buyOffer(chocolateCandyOffer); metro.buyOffer(marmeladeCandyOffer); saleDepartment.getAllOffers(); saleWorker.setOffer(chocolateCandyOffer); saleWorker.setOffer(chocolateCandyOffer); saleDepartment.getAllOffers(); metro.buyOffer(chocolateCandyOffer); saleDepartment.getAllOffers(); saleWorker.setOffer(chocolateCandyOffer); saleWorker.setOffer(marmeladeCandyOffer); saleDepartment.getAllOffers(); nr1.buyOffer(marmeladeCandyOffer); nr1.buyOffer(chocolateCandyOffer); saleDepartment.getAllOffers(); //---------------------------------------------------------------------------- ConveyerChain chocolateConveyer = new ChocolateConveyer(); ConveyerChain marmeladeConveyer = new MarmeladeConveyer(); chocolateConveyer.setNextConveyer(marmeladeConveyer); System.out.println("---------------------------------"); chocolateConveyer.makeCandy("Marmelade"); System.out.println("---------------------------------"); chocolateConveyer.makeCandy("Chocolate"); System.out.println("---------------------------------"); chocolateConveyer.makeCandy("Biscuiti"); System.out.println("---------------------------------"); marmeladeConveyer.makeCandy("Chocolate"); //---------------------------------------------------------------------------- Candy basicCandy = new Chocolate(new Caramel(new StrawberryJam(new Chocolate(new MainCandy())))); Candy basicCandy2 = new Chocolate(new Caramel (new MainCandy())); System.out.println("Ingredients: " + basicCandy.getDescription()); System.out.println("Cost: " + basicCandy.getCost()); System.out.println("Ingredients: " + basicCandy2.getDescription()); System.out.println("Cost: " + basicCandy2.getCost()); //---------------------------------------------------------------------------- saleWorker.setOffer(chocolateCandyOffer); saleWorker.setOffer(marmeladeCandyOffer); FactoryInterface factoryInterface = new FactoryInterface("admin", "1234"); factoryInterface.getAllOffers(saleDepartment); factoryInterface.buyOffer(saleDepartment, chocolateCandyOffer); } } <file_sep>/src/main/java/candy/CandyDecorator.java package candy; public abstract class CandyDecorator implements Candy{ protected Candy tempCandy; public CandyDecorator(Candy newCandy){ tempCandy = newCandy; } public String getDescription(){ return tempCandy.getDescription(); } public double getCost(){ return tempCandy.getCost(); } } <file_sep>/src/main/java/conveyer/ChocolateConveyer.java package conveyer; public class ChocolateConveyer implements ConveyerChain { private ConveyerChain nextInChain; public void setNextConveyer(ConveyerChain nextConveyer) { this.nextInChain = nextConveyer; } public void makeCandy(String typeOfCandy) { if (typeOfCandy.equals("Chocolate")) { System.out.println("a Chocolate candy was created"); } else { System.out.println("this Chocolate conveyer cannot create such candies"); try { nextInChain.makeCandy(typeOfCandy); } catch (Exception e) { System.out.println("There is no conveyers that can create such candies"); } } } } <file_sep>/src/main/java/department/Department.java package department; import clients.Client; import offer.Offer; public interface Department { void setOffer(Offer offer, int offerCode, int workerId); void buyOffer(Offer offer, int offerCode); void addClient(Client client); } <file_sep>/src/main/java/candy/MainCandy.java package candy; public class MainCandy implements Candy { public String getDescription() { return "Starter Candy witch contains: sugar syrup"; } public double getCost() { return 4.00; } } <file_sep>/src/main/java/facade/Welcome.java package facade; public class Welcome { public Welcome(){ System.out.println("Welcome to our factory"); System.out.println("We're glad to see you here :)"); } } <file_sep>/src/main/java/facade/FactoryInterface.java package facade; import department.SaleDepartment; import offer.Offer; public class FactoryInterface { Welcome welcome; private String login = "admin"; private String pass = "<PASSWORD>"; private boolean isLogged = false; public FactoryInterface(String login, String pass) { if (this.login.equals(login) && this.pass.equals(pass)) { welcome = new Welcome(); isLogged = true; } else { System.out.println("Incorrect Data!!!"); } } public void getAllOffers(SaleDepartment department) { if (isLogged) { department.getAllOffers(); } else System.out.println("Login First"); } public void buyOffer(SaleDepartment department, Offer offer) { if (isLogged) { department.buyOffer(offer, offer.getOfferId()); } else System.out.println("Login First"); } } <file_sep>/src/main/java/offer/OfferMaker.java package offer; public class OfferMaker { public CloneableOffer getClonedOffer(CloneableOffer offer){ return offer.makeCopyOffer(); } }
628eb268d0f3fb9d627d8aefa6f97448467545ce
[ "Java" ]
14
Java
MicA-98/TMPS
da657e41a88888c3bcba9f5937dec6995229c486
8fed9ee902670874934d1cc1ebcee06ac3796044
refs/heads/master
<repo_name>intoyuniot/platform-intorobot-ant<file_sep>/README.md # ST STM32: development platform for [IntoYun](https://www.intoyun.com/) The STM32 family of 32-bit Flash MCUs based on the ARM Cortex-M processor is designed to offer new degrees of freedom to MCU users. It offers a 32-bit product range that combines very high performance, real-time capabilities, digital signal processing, and low-power, low-voltage operation, while maintaining full integration and ease of development. # Usage 1. [Install intoyuniot core](http://docs.intoyun.com/devicedev/develop-tools/guide) 2. Install ST STM32 development platform: ```bash # install the latest stable version > intoyuniot platform install ststm32 # install development version > intoyuniot platform install https://github.com/intoyun/platform-ststm32.git ``` <file_sep>/builder/frameworks/intorobot.py # Copyright 2014-present PlatformIO <<EMAIL>> # # 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. """ IntoRobot IntoRobot Wiring-based Framework allows writing cross-platform software to control devices attached to a wide range of Arduino boards to create all kinds of creative coding, interactive objects, spaces or physical experiences. http://www.intorobot.com """ from os.path import isdir, join from SCons.Script import COMMAND_LINE_TARGETS, DefaultEnvironment env = DefaultEnvironment() platform = env.PioPlatform() board = env.BoardConfig() FRAMEWORK_NAME = "framework-intorobot-ant" FRAMEWORK_DIR = platform.get_package_dir(FRAMEWORK_NAME) FRAMEWORK_VERSION = platform.get_package_version(FRAMEWORK_NAME) assert isdir(FRAMEWORK_DIR) env.Replace( LIBS=[], LINKFLAGS=[ "-Os", "-Wl,--gc-sections,--relax", "-mthumb", "-nostartfiles", "-mcpu=%s" % env.BoardConfig().get("build.cpu") ] ) env.Append( ASFLAGS=[ "-fmessage-length=0", ], CFLAGS=[ "-Wno-pointer-sign", "-std=gnu99" ], CCFLAGS=[ "-fno-strict-aliasing", "-Wfatal-errors", "-w", "-fno-common", "-Wno-switch", "-Wno-error=deprecated-declarations", "-fmessage-length=0" ], CXXFLAGS=[ "-fcheck-new", "-std=gnu++11", "-fpermissive" ], LINKFLAGS=[ "%s" % (join(FRAMEWORK_DIR, "variants", board.get("build.variant"), "build", "startup", board.get("build.startup_object"))), "-mlittle-endian", "-Xlinker", "--gc-sections", "-Wl,--defsym,__STACKSIZE__=400", "--specs=nano.specs", "--specs=nosys.specs" ], ) env.Append( CPPDEFINES=[ ("INTOROBOT", 1), ("INTOYUN", 1), ("FIRMLIB_VERSION_STRING", FRAMEWORK_VERSION), ("PLATFORM_THREADING", 1), ("PLATFORM_LOG", 0), ("INTOROBOT_ARCH_ARM"), ("INTOROBOT_PLATFORM"), ("RELEASE_BUILD") ], CPPPATH=[ join(FRAMEWORK_DIR, "cores", board.get("build.core"), "hal", "inc"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "hal", "shared"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "hal", "stm32"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "platform", "shared", "inc"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "platform", "MCU", "shared", "STM32", "inc"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "services", "inc"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "system", "inc"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "user", "inc"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "wiring", "inc"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "platform", "MCU", "STM32L1xx", "IntoRobot_Firmware_Driver", "inc"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "platform", "MCU", "STM32L1xx", "CMSIS", "Include"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "platform", "MCU", "STM32L1xx", "CMSIS", "Device", "ST", "STM32L1xx", "Include"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "platform", "MCU", "STM32L1xx", "STM32L1xx_HAL_Driver", "Inc"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "platform", "MCU", "STM32L1xx", "STM32_USB_Device_Library", "Class", "CDC", "Inc"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "platform", "MCU", "STM32L1xx", "STM32_USB_Device_Library", "Class", "DFU", "Inc"), join(FRAMEWORK_DIR, "cores", board.get("build.core"), "platform", "MCU", "STM32L1xx", "STM32_USB_Device_Library", "Core", "Inc"), join(FRAMEWORK_DIR, "variants", board.get("build.variant"), "hal"), join(FRAMEWORK_DIR, "variants", board.get("build.variant"), "hal", "inc"), join(FRAMEWORK_DIR, "variants", board.get("build.variant"), "wiring_ex", "inc"), join(FRAMEWORK_DIR, "variants", board.get("build.variant"), "wiring_ex", "src"), join(FRAMEWORK_DIR, "variants", board.get("build.variant"), "communication", "lorawan"), join(FRAMEWORK_DIR, "variants", board.get("build.variant"), "communication", "mqtt", "inc") ], LIBPATH=[ join(FRAMEWORK_DIR, "variants", board.get("build.variant"), "lib"), join(FRAMEWORK_DIR, "variants", board.get("build.variant"), "build", "linker") ], LIBS=[ "wiring", "wiring_ex", "hal", "system", "services", "communication", "platform", "gcc", "c" ] ) env.Replace( UPLOADERFLAGS=[ "write", # write in flash "$SOURCES", # firmware path to flash board.get("upload.address") # flash start address ] ) if env.subst("$UPLOAD_PROTOCOL") in ("serial", "dfu"): _upload_tool = "serial_upload" _upload_flags = ["{upload.altID}", "{upload.usbID}"] if env.subst("$UPLOAD_PROTOCOL") == "dfu": _upload_tool = "intorobot_upload" _usbids = env.BoardConfig().get("build.hwids") _upload_flags = [0, "%s:%s" % (_usbids[0][0][2:], _usbids[0][1][2:])] env.Replace( UPLOADER=_upload_tool, UPLOADERFLAGS=["$UPLOAD_PORT"] + _upload_flags, UPLOADCMD=( '$UPLOADER $UPLOADERFLAGS $PROJECT_DIR/$SOURCES %s' % board.get("upload.address")) ) if "__debug" in COMMAND_LINE_TARGETS: env.Append(CPPDEFINES=[ "SERIAL_USB", "GENERIC_BOOTLOADER", ("CONFIG_MAPLE_MINI_NO_DISABLE_DEBUG", "1") ]) env.Prepend(_LIBFLAGS="-Wl,-whole-archive ") env.Append(_LIBFLAGS=" -Wl,-no-whole-archive")
ac13ec384443137b851a838d4ad6f6e67c152e7c
[ "Markdown", "Python" ]
2
Markdown
intoyuniot/platform-intorobot-ant
b9587c45a0593e3570f7367ec8750a2325c737e8
b485f4a2c62c7d45c57f1c9eeb1ef65ff1336667
refs/heads/main
<file_sep><div class="container-fluid mt-3"> <div class="row"> <div class="col-md-4 offset-4"> <div class="card"> <div class="card-header bg-dark"> <center><img src="img/logo.png" width="120px" alt=""></center> </div> <div class="card-body"> <?php if(!empty($_GET['s'])){ if($_GET['s'] == "1"){ ?> <div class="alert alert-warning"> <strong> MAAF </strong>Email Anda Belum Terdaftar...! </div> <?php }else if($_GET['s'] == 2){ ?> <div class="alert alert-danger"> <strong> MAAF </strong>Kata Sandi Anda Salah...! </div> <?php } } ?> <form action="login_proses.php" method="post"> <div class="form-group"> <label for="email"> E-Mail </label> <input type="text" class="form-control" id="email" name="email" placeholder="Masukan E-mail Anda..." required> </div> <div class="form-group"> <label for="password"> Password</label> <input type="password" class="form-control" id="password" name="password" placeholder="Masukan Kata Sandi Anda..." required> </div> <div class="form-group"> <button class="btn btn-info" type="submit">LOGIN</button> </div> </form> </div> </div> </div> </div> </div> <file_sep><div class="container-fluid mt-4"> <div class="col-md-6 offset-3"> <div class="card"> <div class="card-header bg-dark text-white"> FORM REGISTER </div> <div class="card-body"> <form action="register_proses.php" method="post" enctype="multipart/form-data"> <?php if(!empty($_GET['s'])){ if($_GET['s'] == "1"){ ?> <div class="alert alert-success"> <strong> SELAMAT! </strong>Anda Berhasil Daftar, silahkan login! </div> <?php }else{ ?> <div class="alert alert-danger"> <strong> MAAF </strong>Anda Gagal Mendaftar, silahkan ulangi!.! </div> <?php } } ?> <div class="row"> <div class="col"> <div class="form-group"> <label for="nama"> Nama Peserta</label> <input type="text" id="nama" name="nama" class="form-control" placeholder="Masukan Nama Lengkap Anda" > </div> </div> <div class="col"> <div class="form-group"> <label for="NIS"> NIS / NPM</label> <input type="number" id="nis" name="nis" class="form-control" placeholder="Masukan NIS/NPM Anda" > </div> </div> </div> <div class="row"> <div class="col"> <div class="jk">Jenis Kelamin</div> <div class="form-check"> <input class="form-check-input" type="radio" name="jk" id="jk" value="laki-laki" checked> Laki Laki </div> <div class="form-check"> <input class="form-check-input" type="radio" name="jk" id="jk" value="perempuan"> Perempuan </div> </div> <div class="col"> <div class="form-group"> <label for="tgl"> Tempat tanggal lahir </label> <input type="date" id="tgl" name="tgl" class="form-control"> </div> </div> </div> <div class="row"> <div class="col"> <div class="form-group"> <label for="email"> E-mail</label> <input type="email" id="email" name="email" class="form-control" placeholder="Masukan Email Anda" > </div> </div> <div class="col"> <div class="form-group"> <label for="password"> Kata Sandi</label> <input type="password" id="password" name="password" class="form-control" placeholder="Masukan Kata Sandi Anda" > </div> </div> </div> <div class="row"> <div class="col"> <div class="form-group"> <label for="asal"> Asal Pendidikan</label> <input type="text" id="asal" name="asal" class="form-control" placeholder="Masukan Asal Pendiidikan" > </div> </div> <div class="col"> <div class="form-group"> <label for="Alamat">Alamat</label> <textarea class="form-control" id="alamat" name="alamat" rows="3"></textarea> </div> </div> </div> <div class="row"> <div class="col"> <div class="form-group"> <label for="cover">Lampirkan Surat Pengantar/proposal </label> <input type="file" name="cover" id="cover" class="form-control"> </div> </div> </div> <div class="form-group"> <button type="submit" class="btn btn-info"> DAFTAR</label> <button type="reset" class="btn btn-warning">RESET </button> </div> </form> </div> </div> </div> </div> <file_sep><?php include "conec.php"; $nama = $_POST['nama']; $nis = $_POST['nis']; $jk = $_POST['jk']; $tgl = $_POST['tgl']; $asal = $_POST['asal']; $alamat = $_POST['alamat']; $email = $_POST ['email']; $password= $_POST ['password']; $new_password = md5($password); $cover_tmp = $_FILES['cover']['tmp_name']; $cover_name = $_FILES['cover']['name']; $cover_ext = pathinfo($cover_name, PATHINFO_EXTENSION); $new_name = uniqid().".".$cover_ext; move_uploaded_file($cover_tmp, "./img/$new_name"); $simpan = mysqli_query($conec, "insert into users set namapeserta='$nama',nis_npm='$nis', jenis_kelamin='$jk', ttl='$tgl', asal_pendidikan='$asal',alamat='$alamat',email='$email', password='$<PASSWORD>', cover='$new_name'"); if($simpan){ $status = "1"; }else{ $status ="2"; } echo "<script>window.location.href='index.php?h=register&s=$status'</script>";<file_sep><?php $conec = mysqli_connect("localhost","root","","dinas");<file_sep><?php session_start(); include "conec.php"; $email =$_POST['email']; $password =$_POST['<PASSWORD>']; $cek_email = mysqli_query($conec, "select * from users where email='$email'"); //mysqli_num_rows digunakan untukmenghitung jumlah data dari query $jml_data = mysqli_num_rows($cek_email); if($jml_data > 0){ $hasil = mysqli_fetch_array($cek_email); // mysqli_fetch_array digunakan untuk menampilkan hasil query dalam bentuk array $new_password = md5($password); if($new_password == $hasil['<PASSWORD>']){ $_SESSION['iduser'] = $hasil['id']; // menyimpan id dari database ke dalam sesi iduser echo "<script>window.location.href='index.php?h=profil'</script>"; exit(); // digunakan untuk memberhentikan proses }else{ $status ="2"; } }else{ $status ="1"; } echo "<script>window.location.href='index.php?h=login&s=$status'</script>";<file_sep><?php session_start(); include "conec.php"; ?> <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.css"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Viaoda+Libre&display=swap" rel="stylesheet"> <title>Dinas</title> <style> body{ background-color: #cdcdcd; font-family: 'Viaoda Libre', cursive; } label { font-weight:bold; } .jk{ font-weight: bold; } </style> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container "> <a class="navbar-brand " href="index.php"><img src="img/logo.png" width="80" height="50" alt=""></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="index.php">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="index.php?h=visi">Visi - Misi </a> </li> <li class="nav-item active"> <a class="nav-link" href="#">Login Admin </a> </li> <li class="nav-item active"> <a class="nav-link" href="index.php?h=login">Login Peserta </a> </li> </ul> </div> </div> </nav> <?php if(!empty($_GET["h"])){ if($_GET['h']=="login"){ include "login.php"; }else if($_GET['h']== "visi"){ include "profil.php"; }else if($_GET['h']== "detail"){ include "detail.php"; }else{ include "register.php"; } }else{ include "home.php"; }; ?> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://code.jquery.com/jquery-3.5.1.slim.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://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> --> </body> </html>
1cf315bdce640ad35a62393f906fea8d24251c31
[ "PHP" ]
6
PHP
radenaji/DPMD
cf83ffcb2c70aab448b42a2b28854e05a071a9c9
c0861438b8578b74bfb53938c04a00d08d1ad844
refs/heads/master
<file_sep>from .log import Log from .checkpoint import Checkpoint <file_sep>from .EncoderRNN import EncoderRNN from .DecoderRNN import DecoderRNN from .TopKDecoder import TopKDecoder from .seq2seq import Seq2seq from .baseModel import BaseModel from .LanguageModel import LanguageModel
1696f58156c96db388aa6de37dde51377155a617
[ "Python" ]
2
Python
cryptowealth-technology/machine
d78d70ed06652e4b67e3bbc808fe5b35c6424862
a5ecbdb5f21d42708105508a1b3e58fcb4c375c7
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using AzureContainersWebsite.Models; using AzureContainersWebsite.Helpers; namespace AzureContainersWebsite.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetGeneralName(Services service) => Json(PanelsHelper.GetGeneralPanelName(service)); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetGeneral(Services service) => PartialView($"~/Views/{service.ToString()}/General.cshtml"); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetHostingName(Services service) => Json(PanelsHelper.GetHostingPanelName(service)); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetHosting(Services service) => PartialView($"~/Views/{service.ToString()}/Hosting.cshtml"); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetDevOpsName(Services service) => Json(PanelsHelper.GetDevOpsPanelName(service)); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetDevOps(Services service) => PartialView($"~/Views/{service.ToString()}/DevOps.cshtml"); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetScalabilityName(Services service) => Json(PanelsHelper.GetScalabilityPanelName(service)); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetScalability(Services service) => PartialView($"~/Views/{service.ToString()}/Scalability.cshtml"); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetAvailabilityName(Services service) => Json(PanelsHelper.GetAvailabilityPanelName(service)); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetAvailability(Services service) => PartialView($"~/Views/{service.ToString()}/Availability.cshtml"); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetSecurityName(Services service) => Json(PanelsHelper.GetSecurityPanelName(service)); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetSecurity(Services service) => PartialView($"~/Views/{service.ToString()}/Security.cshtml"); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetDiscoveryName(Services service) => Json(PanelsHelper.GetDiscoveryPanelName(service)); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetDiscovery(Services service) => PartialView($"~/Views/{service.ToString()}/Discovery.cshtml"); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetIntegrationName(Services service) => Json(PanelsHelper.GetIntegrationPanelName(service)); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetIntegration(Services service) => PartialView($"~/Views/{service.ToString()}/Integration.cshtml"); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetCostSupportName(Services service) => Json(PanelsHelper.GetCostSupportPanelName(service)); [ResponseCache(NoStore = true, Duration = 0)] public IActionResult GetCostSupport(Services service) => PartialView($"~/Views/{service.ToString()}/CostSupport.cshtml"); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AzureContainersWebsite.Extensions { public static class StringExtensions { public static string SeparateCapitals(this string value) => string.Concat((value ?? string.Empty) .Select(x => Char.IsUpper(x) ? " " + x : x.ToString())) .TrimStart('_') .TrimStart(' '); } } <file_sep>using AzureContainersWebsite.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AzureContainersWebsite.Helpers { public static class PanelsHelper { public static string GetGeneralPanelName(Services service) => $"pnl{service.ToString()}General"; public static string GetHostingPanelName(Services service) => $"pnl{service.ToString()}Hosting"; public static string GetDevOpsPanelName(Services service) => $"pnl{service.ToString()}DevOps"; public static string GetScalabilityPanelName(Services service) => $"pnl{service.ToString()}Scalability"; public static string GetAvailabilityPanelName(Services service) => $"pnl{service.ToString()}Availability"; public static string GetSecurityPanelName(Services service) => $"pnl{service.ToString()}Security"; public static string GetDiscoveryPanelName(Services service) => $"pnl{service.ToString()}Discovery"; public static string GetIntegrationPanelName(Services service) => $"pnl{service.ToString()}Integration"; public static string GetCostSupportPanelName(Services service) => $"pnl{service.ToString()}CostSupport"; } } <file_sep>namespace AzureContainersWebsite.Models { public enum Services { ACI, AKS, AppService, OpenShift, CloudFoundry, ServiceFabric, ServiceFabricMesh, Batch } } <file_sep>using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; namespace AzureContainersWebsite.Extensions { public static class EnumExtensions { /// <summary> /// Generic extension to retrieve an Attribute from an Enum /// </summary> /// <typeparam name="TAttribute"></typeparam> /// <param name="enumValue"></param> /// <returns></returns> public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) where TAttribute : Attribute => enumValue.GetType() .GetMember(enumValue.ToString()) .First() .GetCustomAttribute<TAttribute>(); /// <summary> /// Extension to retrieve the Display Attribute localized value from an Enum /// </summary> /// <param name="enumValue"></param> /// <returns></returns> public static string GetDisplayName(this Enum enumValue) => enumValue.GetAttribute<DisplayAttribute>() .GetName() ?? enumValue.ToString().SeparateCapitals(); /// <summary> /// Extension to retrieve the Display Attribute localized value from an Enum /// </summary> /// <param name="enumValue"></param> /// <returns></returns> public static string GetDisplayName<TEnum>(this TEnum enumValue) => (enumValue as Enum)?.GetAttribute<DisplayAttribute>() ?.GetName() ?? enumValue.ToString().SeparateCapitals(); } } <file_sep>FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base WORKDIR /app EXPOSE 80 EXPOSE 443 FROM microsoft/dotnet:2.1-sdk AS build WORKDIR /src COPY . AzureContainersWebsite/ WORKDIR /src/AzureContainersWebsite RUN dotnet build AzureContainersWebsite.csproj -c Release -o /app FROM build AS publish RUN dotnet publish AzureContainersWebsite.csproj -c Release -o /app FROM base AS final WORKDIR /app COPY --from=publish /app . ENTRYPOINT ["dotnet", "AzureContainersWebsite.dll"] <file_sep># Azure Containers Website ![CI](https://github.com/n3wt0n/AzureContainersWebsite/workflows/CI/badge.svg) This is the repo for the Website of comparison for the Azure Containers services <file_sep>// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification // for details on configuring this project to bundle and minify static web assets. // Write your JavaScript code. $(function () { var $loading = $('#loadingDiv').hide(); $(document) .ajaxStart(function () { $loading.show(); $(".css-checkbox").prop('disabled', true); $(".css-label").prop('disabled', true); $(".css-checkbox").attr('disabled'); $(".css-label").attr('disabled'); }) .ajaxStop(function () { $loading.hide(); $(".css-checkbox").prop('disabled', false); $(".css-label").prop('disabled', false); $(".css-checkbox").removeAttr('disabled'); $(".css-label").removeAttr('disabled'); }); $(".css-checkbox").change(function () { var serviceValue = $(this).val(); LoadServicePanels(serviceValue); }); }); function LoadServicePanels(serviceValue) { GetShowPanel("General", "pnlGeneral", serviceValue); GetShowPanel("Hosting", "pnlHosting", serviceValue); GetShowPanel("DevOps", "pnlDevOps", serviceValue); GetShowPanel("Scalability", "pnlScalability", serviceValue); GetShowPanel("Availability", "pnlAvailability", serviceValue); GetShowPanel("Security", "pnlSecurity", serviceValue); GetShowPanel("Discovery", "pnlDiscovery", serviceValue); GetShowPanel("Integration", "pnlIntegration", serviceValue); GetShowPanel("CostSupport", "pnlCostSupport", serviceValue); } function GetShowPanel(section, panel, serviceValue) { $.ajax({ type: "GET", url: '/Home/Get' + section + 'Name?service=' + serviceValue, dataType: "html", success: function (panelName) { panelName = panelName.replace(/^"(.+(?="$))"$/, '$1'); //Quick workaround to remove the double quotes if (panelName) { if ($("#" + panelName).length) { //it exist $("#" + panelName).remove(); } else { $.ajax({ type: "GET", url: '/Home/Get' + section + '?service=' + serviceValue, dataType: "html", success: function (result) { if (result) { $("#" + panel).append(result); } }, error: function (xhr, ajaxOptions, thrownError) { alert('ERROR appending in ' + panel + ': ' + thrownError); } }) } } }, error: function (xhr, ajaxOptions, thrownError) { alert('ERROR checking name in ' + panel + ': ' + thrownError); } }); }
6505a86228d2fc9b5af997b3e0fa04512f1bbc47
[ "Markdown", "C#", "JavaScript", "Dockerfile" ]
8
C#
JLaxmi-98/AzureContainersWebsite
b9495974aea0a8a6e4085c1aae81268fc4aaec01
4ad0e9d7d179998a2e02e67b36da382052d39682
refs/heads/master
<file_sep>#include "GL/glew.h" #include "GL/glut.h" #include <iostream> #include "EulerOperationUtility.h" #include "SceneDisplay.h" using namespace std; //2014/12/14,作为CAD实验的作业上传了。 //现将问题总结:本程序在SweepDisplay和ChamferDisplay等函数中存在内存泄露。 //可能deleteSolid未能完全删除所有使用过的栈空间。也可能是欧拉操作函数在实现过程中存在问题。 //SceneDisplay渲染框架未能实现视点的迁移和后退,需要使用glFrustum等,但是使用时出了问题,临时取消。以后可改。 //总体而言SceneDisplay框架完善了很多。 Solid* solid1, *solid2; int wireOrNot = 0; int rotateOrNot = 1; //在绘制曲线扫成的时候使用的bezier曲线的四个控制顶点。 GLfloat cp[4][3] = { -5, -5, -1, -1, 6, 1, 5, -5, 1, 5, 4, 6}; SceneDisplay sceneDis; #define NORMAL_MODE 1 #define SWEEP_MODE 2 extern void drawFace(Face* face); extern void drawWireSolid(Solid* solid); extern void calNormal(Solid* solid); extern void deleteSolid(Solid* solid); void drawModel(Solid* s){ if(wireOrNot == 0){ Face* firFace = s->sFaces; Face* tmpFace = firFace; int t = 0; do{ drawFace(tmpFace); tmpFace = tmpFace->nxtFace; t++; }while(tmpFace != firFace); }else{ drawWireSolid(s); } } //倒角操作示例的使用处。 void ChamferDisplay(){ //创建基本的立方体的过程 Vertex* vtx[] = {new Vertex(-4, -4, -4), new Vertex(-4, 4, -4), new Vertex(4, 4, -4), new Vertex(4, -4, -4), new Vertex(-4, -4, 4), new Vertex(-4, 4, 4), new Vertex(4, 4, 4), new Vertex(4, -4, 4)}; Face* face; Loop* loop, *loop2, *loop3; solid1 = mvfs(vtx[0], face); mev(face->fLoops, vtx[0], vtx[1]); mev(face->fLoops, vtx[1], vtx[2]); mev(face->fLoops, vtx[2], vtx[3]); loop = mef(face->fLoops, vtx[3], vtx[0]); mev(loop, vtx[0], vtx[4]); mev(loop, vtx[1], vtx[5]); mev(loop, vtx[2], vtx[6]); mev(loop, vtx[3], vtx[7]); mef(loop, vtx[7], vtx[6]); mef(loop, vtx[6], vtx[5]); mef(loop, vtx[5], vtx[4]); mef(loop, vtx[4], vtx[7]); //创建立方体过程结束。 //开始倒角过程。 //递归的进行倒角,将新生成的点,再倒角一次。 Vertex* reV[3]; for(int i = 0; i < 8; i++){ chamfer(solid1, vtx[i], 3, reV); for(int j = 0; j < 3; j++){ chamfer(solid1, reV[j], 0.9); } } int a = 0; cout << "" << endl; //计算法向量。 calNormal(solid1); //绘制模型。 drawModel(solid1); //以下代码使得输出函数只会执行一次。 static int mark = 0; if(mark == 0){ output(solid1, ".\\euler1.brp"); mark ++; } //删除扫尾。 deleteSolid(solid1); } //扫成操作示例的使用处。 void SweepDisplay(){ Vertex* vtx1, * vtx2, *vtx3, *vtx4; GLfloat length; Point oldV, newV; Face* face; Loop* loop; for(GLfloat i = 0, k = 0; i < 1; i += 0.01, k++){ for(int j = 0; j < 3; j++){ newV.pos[j] = cp[0][j] * pow((1 - i), 3) + cp[1][j] * 3 * i * pow((1 - i), 2) + cp[2][j] * 3 * i * i * (1 - i) + cp[3][j] * i * i * i; } Vector normal = newV + ( -1.0 * oldV); if(k == 1){ GLfloat t = -(normal.pos[0] + normal.pos[1]) / normal.pos[2]; length = sqrt(1 + 1 + t * t); Point p1(4 / length, 4 / length, t * 4 / length); Point p2 = -1.0f * p1; Point p3 = p1.cross(normal); p1 = p1 + oldV; p2 = oldV + p2; p3 = p3 * (4 / p3.length()); p3 = oldV + p3; vtx1 = new Vertex(p1); vtx2 = new Vertex(p2); vtx3 = new Vertex(p3); solid2 = mvfs(vtx1, face); mev(face->fLoops, vtx1, vtx2); mev(face->fLoops, vtx2, vtx3); loop = mef(face->fLoops, vtx3, vtx1); sweep(face, normal, normal.length()); }else if (k > 1){ sweep(face, normal, normal.length()); } if(k >= 1){ glBegin(GL_LINES); glVertex3f(oldV.pos[0], oldV.pos[1], oldV.pos[2]); glVertex3f(newV.pos[0], newV.pos[1], newV.pos[2]); glEnd(); } oldV = newV; } //计算法向量,用于显示。 calNormal(solid2); //显示函数 drawModel(solid2); //以下代码使得输出函数只会执行一次。 static int mark = 0; if(mark == 0){ output(solid2, ".\\euler2.brp"); mark ++; } //清空扫尾。 deleteSolid(solid2); } void myKey(unsigned char key, int x, int y){ switch(key){ case 'c': wireOrNot = ! wireOrNot; //printf("faceC ++\n"); break; case 'v': rotateOrNot = !rotateOrNot; sceneDis.setViewRotate(rotateOrNot); break; } } //对右键的菜单的处理函数。 void processMenu(int bt){ switch(bt){ case NORMAL_MODE: sceneDis.setUsrDisplayFunc(ChamferDisplay); printf("ChamferDisplay..................\n"); break; case SWEEP_MODE: sceneDis.setUsrDisplayFunc(SweepDisplay); printf("SweepDisplay..................\n"); break; } } //喜闻乐见的main函数。 int main(){ int fillMenu = glutCreateMenu(processMenu); glutAddMenuEntry("倒角展示",NORMAL_MODE); glutAddMenuEntry("扫成展示",SWEEP_MODE); // attach the menu to the right button glutAttachMenu(GLUT_RIGHT_BUTTON); sceneDis.setXYZSpan(-10, 10, -10, 10, 1, 30); sceneDis.setUsrDisplayFunc(ChamferDisplay); //开启使用shader的功能 sceneDis.setShaderState(1); sceneDis.setUsrKeyboardFunc(myKey); sceneDis.startTimer(); sceneDis.start(); }<file_sep>#pragma once #include<iostream> class Solid; class Face; class Loop; class HalfEdge; class Edge; class Vertex; //Tuple是三元组类,将被typedef为Vecter和Point两个类,以便见名识意。 class Tuple{ public: double pos[3]; Tuple(){ pos[0] = 0; pos[1] = 0; pos[2] = 0; } Tuple(double x, double y, double z){ pos[0] = x; pos[1] = y; pos[2] = z; } Tuple(double p[]){ pos[0] = p[0]; pos[1] = p[1]; pos[2] = p[2]; } double length(){ return sqrt(pos[0] * pos[0] + pos[1] * pos[1] + pos[2] * pos[2]); } Tuple cross(Tuple p){ return Tuple(pos[1] * p.pos[2] - pos[2] * p.pos[1], pos[2] * p.pos[0] - pos[0] * p.pos[2], pos[0] * p.pos[1] - pos[1] * p.pos[0]); } friend Tuple operator + (Tuple a, Tuple b){ return Tuple(a.pos[0] + b.pos[0], a.pos[1] + b.pos[1], a.pos[2] + b.pos[2]); } friend Tuple operator - (Tuple a, Tuple b){ return Tuple(a.pos[0] - b.pos[0], a.pos[1] - b.pos[1], a.pos[2] - b.pos[2]); } friend Tuple operator * (double a, Tuple b){ return Tuple(a * b.pos[0], a * b.pos[1], a * b.pos[2]); } friend Tuple operator * (Tuple a, double b){ return Tuple(a.pos[0] * b, a.pos[1] * b, a.pos[2] * b); } }; typedef Tuple Point; typedef Tuple Vector; //所有的循环双向链表均已pre和nxt为自己作为判断只有一个的条件。 class Solid{ public: Solid():preSolid(this), nxtSolid(this), sFaces(NULL), sEdges(NULL), sVertices(NULL), vertexCount(0), loopCount(0), faceCount(0) {} Solid* preSolid; Solid* nxtSolid; Face* sFaces; Edge* sEdges;//为了便于生成线框模型,暂时没用到. Vertex* sVertices;//为了便于生成点模型。 int vertexCount;//统计这个solid中的顶点的个数 int loopCount;//统计这个solid中的loop的个数。 int faceCount;//统计这个solid中的face的个数。 }; class Face{ public: Face():fSolid(NULL), preFace(this), nxtFace(this), fLoops(NULL) {} Solid* fSolid; Face* preFace; Face* nxtFace; Loop* fLoops; Vector normal;//用于绘制的时候存储法向量。 }; class Loop{ public: Loop():lFace(NULL), preLoop(this), nxtLoop(this), lHalfEdges(NULL) {} Face* lFace; Loop* preLoop; Loop* nxtLoop; HalfEdge* lHalfEdges; int mark;//后期输出过程中使用。 }; class HalfEdge{ public: HalfEdge():edge(NULL), heLoop(NULL), preHalfEdge(this), nxtHalfEdge(this), heStartVertex(NULL), indexInEdge(0) {} Edge* edge; int indexInEdge;//该条halfEdge在其所属的Edge中的索引。 Loop* heLoop; HalfEdge* preHalfEdge; HalfEdge* nxtHalfEdge; Vertex* heStartVertex; }; class Edge{ public: Edge():preEdge(this), nxtEdge(this) { halfEdge[0] = NULL; halfEdge[1] = NULL; } HalfEdge* halfEdge[2]; Edge* preEdge; Edge* nxtEdge; }; class Vertex{ public: Vertex():preVertex(this), nxtVertex(this){} Vertex(Vertex& v):preVertex(this), nxtVertex(this) { this->point = v.point; } Vertex(double x, double y, double z):preVertex(this), nxtVertex(this) { point = Point(x, y, z); } Vertex(Point _point):preVertex(this), nxtVertex(this) { point = _point; } Point point; Vector normal;//用于绘制的时候存储法向量。 Vertex* preVertex; Vertex* nxtVertex; int mark;//后期输出过程中使用的。 }; <file_sep>#include "EulerBaseDataStructure.h" #include <GL/glut.h> void CALLBACK PolyLine3DBegin(GLenum type) { glBegin(type); } void CALLBACK PolyLine3DVertex ( GLdouble * vertex) { const GLdouble *pointer = (GLdouble *) vertex; glVertex3dv(pointer); } void CALLBACK PolyLine3DEnd() { glEnd(); } GLUtesselator* tesser() { GLUtesselator * tess; tess=gluNewTess(); gluTessCallback(tess,GLU_TESS_BEGIN,(void (CALLBACK*)())&PolyLine3DBegin); gluTessCallback(tess,GLU_TESS_VERTEX,(void (CALLBACK*)())&PolyLine3DVertex); gluTessCallback(tess,GLU_TESS_END,(void (CALLBACK*)())&PolyLine3DEnd); gluTessProperty(tess, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_NONZERO); return tess; } void drawFace(Face* face){ //glClear(GL_STENCIL_BUFFER_BIT); GLUtesselator* tess = tesser(); if (!tess) return; gluTessBeginPolygon(tess,NULL); Loop* firLp = face->fLoops; Loop* tmpLp = firLp; do{ HalfEdge* firHe = tmpLp->lHalfEdges; HalfEdge* tmpHe = firHe; gluTessBeginContour(tess); do{ gluTessVertex(tess, tmpHe->heStartVertex->point.pos, tmpHe->heStartVertex->point.pos); glNormal3dv(face->normal.pos); //以下注释的函数不知道为什么是错的,总之传进去的法向量有问题。再显示的时候不对。使用上面的函数传就可以了。 /*gluTessNormal(tess, tmpHe->heStartVertex->normal.pos[0], tmpHe->heStartVertex->normal.pos[1], tmpHe->heStartVertex->normal.pos[2]);*/ tmpHe = tmpHe->nxtHalfEdge; }while(tmpHe != firHe); gluTessEndContour(tess); tmpLp = tmpLp->nxtLoop; }while(tmpLp != firLp); gluTessEndPolygon(tess); } void drawWireSolid(Solid* solid){ glBegin(GL_LINES); Face* tmpFace = solid->sFaces; do{ Loop* tmpLoop = tmpFace->fLoops; do{ HalfEdge* tmpHe = tmpLoop->lHalfEdges; do{ glVertex3dv(tmpHe->preHalfEdge->heStartVertex->point.pos); glVertex3dv(tmpHe->heStartVertex->point.pos); tmpHe = tmpHe->nxtHalfEdge; }while(tmpHe != tmpLoop->lHalfEdges); tmpLoop = tmpLoop->nxtLoop; }while(tmpLoop != tmpFace->fLoops); tmpFace = tmpFace->nxtFace; }while(tmpFace != solid->sFaces); glEnd(); } void calNormal(Solid* solid){ Face* tmpFace = solid->sFaces; do{ Loop* tmpLoop = tmpFace->fLoops; Point p[3]; p[0] = tmpLoop->lHalfEdges->heStartVertex->point; p[1] = tmpLoop->lHalfEdges->nxtHalfEdge->heStartVertex->point; p[2] = tmpLoop->lHalfEdges->nxtHalfEdge->nxtHalfEdge->heStartVertex->point; Vector normal = (p[1] - p[0]).cross(p[2] - p[1]); normal = normal * (1 / normal.length()); tmpFace->normal = normal; do{ HalfEdge* tmpHe = tmpLoop->lHalfEdges; do{ tmpHe->heStartVertex->normal = tmpHe->heStartVertex->normal + normal; tmpHe = tmpHe->nxtHalfEdge; }while(tmpHe != tmpLoop->lHalfEdges); tmpLoop = tmpLoop->nxtLoop; }while(tmpLoop != tmpFace->fLoops); tmpFace = tmpFace->nxtFace; }while(tmpFace != solid->sFaces); } //删除某个实体中的所有的边,半边,点,环等。 void deleteSolid(Solid* solid){ //首先循环删除所有的半边,环, 面。 Face* tmpFace = solid->sFaces; Face* nxtFace; for(int i = 0; i < solid->faceCount; i++){ Loop* tmpLoop = tmpFace->fLoops; Loop* nxtLoop; //先对环的数目进行统计。 int lpCount = 0; do{ tmpLoop = tmpLoop->nxtLoop; lpCount++; }while(tmpLoop != tmpFace->fLoops); while(lpCount--){ HalfEdge* tmpHe = tmpLoop->lHalfEdges; HalfEdge* nxtHe; //先对半边的数目进行统计 int heCount = 0; do{ tmpHe = tmpHe->nxtHalfEdge; heCount++; }while(tmpHe != tmpLoop->lHalfEdges); while(heCount--){ nxtHe = tmpHe->nxtHalfEdge; delete tmpHe; tmpHe = nxtHe; } nxtLoop = tmpLoop->nxtLoop; delete tmpLoop; tmpLoop = nxtLoop; } nxtFace = tmpFace->nxtFace; delete tmpFace; tmpFace = nxtFace; }; //接着删除所有的顶点 Vertex * tmpV = solid->sVertices, *nxtV; for(int i = 0; i < solid->vertexCount; i++){ nxtV = tmpV->nxtVertex; delete tmpV; tmpV = nxtV; } //删除所有的边。 Edge * tmpE = solid->sEdges, *nxtE; int edgeCount = 0; do{ edgeCount++; tmpE = tmpE->nxtEdge; }while(tmpE != solid->sEdges); while(edgeCount--){ nxtE = tmpE->nxtEdge; delete tmpE; tmpE = nxtE; } }<file_sep>#pragma once #include <iostream> using namespace std; #include "EulerBaseDataStructure.h" //新建一个solid,并在其中穿件一个face和一个顶点,但是face中只含有一个没有HalfEdge的Loop。 Solid* mvfs(Vertex* vertex, Face*& face){ Solid* newSolid = new Solid(); Face* newFace = new Face(); Loop* loop = new Loop(); //对拓扑结构进行调整。 newSolid->sFaces = newFace; //将新的点加入solid的点集合中去。 if(newSolid->sVertices == NULL){ newSolid->sVertices = vertex; }else{ newSolid->sVertices->nxtVertex->preVertex = vertex; vertex->nxtVertex = newSolid->sVertices->nxtVertex; vertex->preVertex = newSolid->sVertices; newSolid->sVertices->nxtVertex = vertex; } newFace->fSolid = newSolid; newFace->fLoops = loop; loop->lFace = newFace; face = newFace; //进行一些数值累加的操作。 newSolid->faceCount++; newSolid->loopCount++; newSolid->vertexCount++; return newSolid; } //创建一个点,和一条边。loop是进行此操作的那个Loop,而vtx1和vtx2是具有一定次序的。 //默认认为vtx1是在loop中了的顶点,而vtx2是新创建的顶点, void mev(Loop* loop, Vertex* vtx1, Vertex* vtx2){ loop->lFace->fSolid->vertexCount++; //初始化的一些操作 HalfEdge* e1 = new HalfEdge(); HalfEdge* e2 = new HalfEdge(); Edge* e = new Edge(); e->halfEdge[0] = e1; e->halfEdge[1] = e2; e1->indexInEdge = 0; e2->indexInEdge = 1; e1->edge = e; e2->edge = e; e1->heStartVertex = vtx1; e2->heStartVertex = vtx2; e1->heLoop = loop; e2->heLoop = loop; //将新的边插入solid的边表里。 Edge* tmpEdge = loop->lFace->fSolid->sEdges; if(tmpEdge == NULL){ loop->lFace->fSolid->sEdges = e; }else{ tmpEdge->nxtEdge->preEdge = e; e->nxtEdge = tmpEdge->nxtEdge; e->preEdge = tmpEdge; tmpEdge->nxtEdge = e; } //将新的点加入solid的点集中。 Vertex* tmpVertex = loop->lFace->fSolid->sVertices; if(tmpVertex == NULL){ loop->lFace->fSolid->sVertices = vtx2; }else{ tmpVertex->nxtVertex->preVertex = vtx2; vtx2->nxtVertex = tmpVertex->nxtVertex; vtx2->preVertex = tmpVertex; tmpVertex->nxtVertex = vtx2; } //将半边e1,e2进行插入loop中。 if(loop->lHalfEdges == NULL){ //将拓扑结构进行设置。 //e1的前半边指针为e2,后半边指针指向e2 //e2的前半边指针为e1,后半边指针指向e1 e1->nxtHalfEdge = e2; e1->preHalfEdge = e2; e2->nxtHalfEdge = e1; e2->preHalfEdge = e1; loop->lHalfEdges = e1; }else{ HalfEdge* tHalfEdge = loop->lHalfEdges; //找到原来的loo中以vtx1为起点的半边。 do{ tHalfEdge = tHalfEdge->nxtHalfEdge; }while(tHalfEdge->heStartVertex != vtx1 && tHalfEdge != loop->lHalfEdges); if(tHalfEdge->heStartVertex != vtx1){ cout << "cannot find any halfedge start from vtx1 in mev function" <<endl; }else{ //对拓扑结构进行修改。 tHalfEdge->preHalfEdge->nxtHalfEdge = e1; e1->preHalfEdge = tHalfEdge->preHalfEdge; e1->nxtHalfEdge = e2; e2->preHalfEdge = e1; e2->nxtHalfEdge = tHalfEdge; tHalfEdge->preHalfEdge = e2; } } } //创建一条边,创建一个新的面。其中vtx1和vtx2的是具有方向性的,不可以乱序了使用。 //函数结束后会将传入的loop修改为指向vtx1向vtx2的方向的那个Loop,而方向的则返回。 //因此使用的时候要注意方向。 Loop* mef(Loop* loop, Vertex* vtx1, Vertex* vtx2){ //边信息简单的初始化。 HalfEdge* e1 = new HalfEdge(); HalfEdge* e2 = new HalfEdge(); Edge* e = new Edge(); //面信息的简单初始化。 Face* newFace = new Face(); Loop* newLoop = new Loop(); e->halfEdge[0] = e1; e->halfEdge[1] = e2; e1->indexInEdge = 0; e2->indexInEdge = 1; e1->edge = e; e2->edge = e; e1->heStartVertex = vtx1; e2->heStartVertex = vtx2; e1->heLoop = loop; e2->heLoop = newLoop; //newFace的拓扑结构填充 newFace->fLoops = newLoop; newFace->fSolid = loop->lFace->fSolid; loop->lFace->nxtFace->preFace = newFace; newFace->preFace = loop->lFace; newFace->nxtFace = loop->lFace->nxtFace; loop->lFace->nxtFace = newFace; newLoop->lFace = newFace; newLoop->lHalfEdges = e2; //添加行的edge到solid的edge集合中。 Edge* tempEdge = loop->lFace->fSolid->sEdges; if(tempEdge == NULL){ loop->lFace->fSolid->sEdges = e; }else{ tempEdge->preEdge->nxtEdge = e; e->preEdge = tempEdge->preEdge; e->nxtEdge = tempEdge; tempEdge->preEdge = e; } HalfEdge* tEdge = loop->lHalfEdges; HalfEdge* vtx1HalfEdge, *vtx2HalfEdge; vtx1HalfEdge = vtx2HalfEdge = NULL; do{ if(tEdge->heStartVertex == vtx1){ vtx1HalfEdge = tEdge; } if(tEdge->heStartVertex == vtx2){ vtx2HalfEdge = tEdge; } tEdge = tEdge->nxtHalfEdge; }while(tEdge != loop->lHalfEdges); //修改两个loop的半边的数据结构。 vtx1HalfEdge->preHalfEdge->nxtHalfEdge = e1; e1->preHalfEdge = vtx1HalfEdge->preHalfEdge; e1->nxtHalfEdge = vtx2HalfEdge; vtx2HalfEdge->preHalfEdge->nxtHalfEdge = e2; e2->preHalfEdge = vtx2HalfEdge->preHalfEdge; e2->nxtHalfEdge = vtx1HalfEdge; vtx2HalfEdge->preHalfEdge = e1; vtx1HalfEdge->preHalfEdge = e2; //修改newLoop中的半边的属性。 tEdge = newLoop->lHalfEdges; do{ tEdge->heLoop = newLoop; tEdge = tEdge->nxtHalfEdge; }while(tEdge != newLoop->lHalfEdges); //修改loop为新的外边框。即按原来的方向的那一个loop。 vtx1 --> vtx2 loop->lHalfEdges = e1; //一些数值的累加 loop->lFace->fSolid->loopCount++; loop->lFace->fSolid->faceCount++; return newLoop; } //默认是从vtx1到vtx2的方向。即以此为潜在要求,not robust Loop* kemr(Loop* loop, Vertex* vtx1, Vertex* vtx2){ loop->lFace->fSolid->loopCount++; HalfEdge* tHalfEdge = loop->lHalfEdges; HalfEdge *delHalfEdge1, *delHalfEdge2; Loop* newLoop = new Loop(); newLoop->lFace = loop->lFace; //找到以vtx1为起点且下一条为以vtx2的HalfEdge while(tHalfEdge->heStartVertex != vtx1 || tHalfEdge->nxtHalfEdge->heStartVertex != vtx2){ tHalfEdge = tHalfEdge->nxtHalfEdge; } delHalfEdge1 = tHalfEdge; //通过Edge的关系找寻对应的另一条半边。 1 - delHalfEdge1->indexInEdge即为对应的 delHalfEdge2 = delHalfEdge1->edge->halfEdge[1 - delHalfEdge1->indexInEdge]; //修改半边的拓扑关系,仅考虑简单情况。复杂情况未考虑。 //修改相应的拓扑结构 delHalfEdge1->preHalfEdge->nxtHalfEdge = delHalfEdge2->nxtHalfEdge; delHalfEdge2->nxtHalfEdge->preHalfEdge = delHalfEdge1->preHalfEdge; loop->lHalfEdges = delHalfEdge1->preHalfEdge; if(delHalfEdge1->nxtHalfEdge != delHalfEdge2){ delHalfEdge1->nxtHalfEdge->preHalfEdge = delHalfEdge2->preHalfEdge; delHalfEdge2->preHalfEdge->nxtHalfEdge = delHalfEdge1->nxtHalfEdge; newLoop->lHalfEdges = delHalfEdge1->nxtHalfEdge; } //删除边在solid的关系 Edge* delEdge = delHalfEdge1->edge; delEdge->preEdge->nxtEdge = delEdge->nxtEdge; delEdge->nxtEdge->preEdge = delEdge->preEdge; //删除为半边和边分配的内存。 delete delHalfEdge1->edge; delete delHalfEdge1; delete delHalfEdge2; loop->nxtLoop->preLoop = newLoop; newLoop->nxtLoop = loop->nxtLoop; newLoop->preLoop = loop; loop->nxtLoop = newLoop; return newLoop; } //实际是删除一个面,但是这个面只含有一个loop,然后将这个loop放置到另一个面上去,即baseLoop所在的面, void kfmrh(Loop* baseLoop, Loop* faceLoop){ baseLoop->lFace->fSolid->faceCount--; if(baseLoop->nxtLoop == baseLoop){ baseLoop->nxtLoop = faceLoop; baseLoop->preLoop = faceLoop; faceLoop->preLoop = baseLoop; faceLoop->nxtLoop = baseLoop; }else{ baseLoop->nxtLoop->preLoop = faceLoop; faceLoop->nxtLoop = baseLoop->nxtLoop; faceLoop->preLoop = baseLoop; baseLoop->nxtLoop = faceLoop; } Face* tmpFace = faceLoop->lFace; faceLoop->lFace = baseLoop->lFace; if(tmpFace->nxtFace != tmpFace){ tmpFace->nxtFace->preFace = tmpFace->preFace; tmpFace->preFace->nxtFace = tmpFace->nxtFace; } delete tmpFace; } //edge 是将要添加新点的边,vtx是添加的新点。每次返回新添加的边,新添加的边是以以前的edge的halfEdge[0]的起点开始的. Edge* semv(Edge* edge, Vertex* vtx){ //边信息简单的初始化。 HalfEdge* e1 = new HalfEdge(); HalfEdge* e2 = new HalfEdge(); Edge* e = new Edge(); //solid的数值记录更新 edge->halfEdge[0]->heLoop->lFace->fSolid->vertexCount++; e->halfEdge[0] = e1; e->halfEdge[1] = e2; e1->indexInEdge = 0; e2->indexInEdge = 1; e1->edge = e; e2->edge = e; e1->heStartVertex = vtx; e2->heStartVertex = edge->halfEdge[0]->heStartVertex; edge->halfEdge[0]->heStartVertex = vtx; e1->heLoop = edge->halfEdge[1]->heLoop; e2->heLoop = edge->halfEdge[0]->heLoop; //考虑特殊情况 if(edge->halfEdge[1]->nxtHalfEdge == edge->halfEdge[0]){ e1->preHalfEdge = edge->halfEdge[1]; e1->nxtHalfEdge = e2; edge->halfEdge[1]->nxtHalfEdge = e1; e2->preHalfEdge = e1; e2->nxtHalfEdge = edge->halfEdge[0]; edge->halfEdge[0]->preHalfEdge = e2; }else{ e1->preHalfEdge = edge->halfEdge[1]; e1->nxtHalfEdge = edge->halfEdge[1]->nxtHalfEdge; edge->halfEdge[1]->nxtHalfEdge->preHalfEdge = e1; edge->halfEdge[1]->nxtHalfEdge = e1; e2->preHalfEdge = edge->halfEdge[0]->preHalfEdge; e2->nxtHalfEdge = edge->halfEdge[0]; edge->halfEdge[0]->preHalfEdge->nxtHalfEdge = e2; edge->halfEdge[0]->preHalfEdge = e2; } //添加新的edge到solid的edge集合中。 Edge* tempEdge = edge->halfEdge[0]->heLoop->lFace->fSolid->sEdges; if(tempEdge == NULL){ edge->halfEdge[0]->heLoop->lFace->fSolid->sEdges = e; }else{ tempEdge->preEdge->nxtEdge = e; e->preEdge = tempEdge->preEdge; e->nxtEdge = tempEdge; tempEdge->preEdge = e; } //添加新的vertex到solid的vertex集合中。 Vertex* tempVertex = edge->halfEdge[0]->heLoop->lFace->fSolid->sVertices; if(tempVertex == NULL){ edge->halfEdge[0]->heLoop->lFace->fSolid->sVertices = vtx; }else{ tempVertex->preVertex->nxtVertex = vtx; vtx->preVertex = tempVertex->preVertex; vtx->nxtVertex = tempVertex; tempVertex->preVertex = vtx; } return e; } //edge是要删除的边,而面则随便删除两个相邻中的一个。 //暂时考虑的是理想情况。大约是两个三角形夹着的一条边被删除。 void kef(Edge* edge){ HalfEdge *e1, *e2, *tmpHe; Edge *tmpE,*firE; e1 = edge->halfEdge[0]; e2 = edge->halfEdge[1]; //solid中数值的更新 edge->halfEdge[0]->heLoop->lFace->fSolid->faceCount--; edge->halfEdge[0]->heLoop->lFace->fSolid->loopCount--; //修改solid的sEdges使其指向有效,并从solid的sEdges中删除该实体边。 //考虑的简单的情况,不考虑只有一条边在的情况。 edge->halfEdge[0]->heLoop->lFace->fSolid->sEdges = edge->nxtEdge; edge->preEdge->nxtEdge = edge->nxtEdge; edge->nxtEdge->preEdge = edge->preEdge; //现在取e1中的face认为是要被去掉的,从face的双向链表中删除,并将下的loop也一并删除。 //此处有假设默认删除的只能是不包含内环的。 Face* f = e1->heLoop->lFace; f->fSolid->sFaces = f->nxtFace; f->preFace->nxtFace = f->nxtFace; f->nxtFace->preFace = f->preFace; Loop* l = e1->heLoop; //将e1所有的半边的所属loop修改为e2所指向的。 tmpHe = e1; do{ tmpHe->heLoop = e2->heLoop; tmpHe = tmpHe->nxtHalfEdge; }while(tmpHe != e1); //修改一下e2的 heLoop,保证其能正确指向。 e2->heLoop->lHalfEdges = e2->nxtHalfEdge; //拓扑关系的修改 e1->nxtHalfEdge->preHalfEdge = e2->preHalfEdge; e2->preHalfEdge->nxtHalfEdge = e1->nxtHalfEdge; e1->preHalfEdge->nxtHalfEdge = e2->nxtHalfEdge; e2->nxtHalfEdge->preHalfEdge = e1->preHalfEdge; //真正删除这些半边和边,face, loop。 delete l; delete f; delete e1; delete e2; delete edge; } //edge是要删除的边,vtx是要删除的顶点。 void kev(Edge* edge, Vertex* vtx){ HalfEdge *e1, *e2; Edge *tmpE,*firE; Vertex *tmpV, *firV; if(edge->halfEdge[0]->heStartVertex == vtx){ e1 = edge->halfEdge[0]; e2 = edge->halfEdge[1]; }else{ e1 = edge->halfEdge[1]; e2 = edge->halfEdge[0]; } //solid中的数值进行更新. edge->halfEdge[0]->heLoop->lFace->fSolid->vertexCount--; //使solid中的sVertices指向有效,从solid的点链表中删除该点。 edge->halfEdge[0]->heLoop->lFace->fSolid->sVertices = vtx->nxtVertex; vtx->preVertex->nxtVertex = vtx->nxtVertex; vtx->nxtVertex->preVertex = vtx->preVertex; //使solid中的sEdges指向有效,并从solid的边表中删除该边。 //考虑的简单的情况,不考虑只有一条边在的情况。 //从边表中取出了该条edge。 edge->halfEdge[0]->heLoop->lFace->fSolid->sEdges = edge->nxtEdge; edge->preEdge->nxtEdge = edge->nxtEdge; edge->nxtEdge->preEdge = edge->preEdge; //修改拓扑关系。 e1->nxtHalfEdge->preHalfEdge = e2->preHalfEdge; e2->preHalfEdge->nxtHalfEdge = e1->nxtHalfEdge; //真正删除edge中的半边,边,以及vtx等。 delete e1; delete e2; delete edge; delete vtx; } //后续操作辅助的数据结构。 class VertexLinker{ public: VertexLinker():next(NULL) {} Vertex* vertex; VertexLinker* next; }; class EdgeLinker{ public: EdgeLinker():next(NULL){} Edge* edge; EdgeLinker* next; }; //扫成操作,face是要被用来扫成的面,dir是扫成的方向,d是在该方向上扫成的距离。 void sweep(Face* face, double dir[], float d){ if(face == NULL){ cout << "face is NULL in sweep function which is illegal..." <<endl; return; } //先对dir进行单位化. float length = sqrt(dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]); dir[0] /= length; dir[1] /= length; dir[2] /= length; Loop* tmpoutLoop = face->fLoops; Loop* firLoop = NULL; do{ Vertex *vtx1, *vtx2; Vertex *addVtx1, *addVtx2, *startAddVtx; HalfEdge* tmpHalfEdge; if(tmpoutLoop != NULL){ tmpHalfEdge = tmpoutLoop->lHalfEdges; }else{ continue; } //创建暂存点集合的链表 VertexLinker* vLinker = NULL, *tmpVLinker; do{ tmpVLinker = new VertexLinker(); tmpVLinker->vertex = tmpHalfEdge->heStartVertex; tmpVLinker->next = NULL; if(vLinker == NULL){ vLinker = tmpVLinker; }else{ tmpVLinker->next = vLinker->next; vLinker->next = tmpVLinker; } tmpHalfEdge = tmpHalfEdge->nxtHalfEdge; }while(tmpHalfEdge != tmpoutLoop->lHalfEdges); Loop* tmpLoop = tmpoutLoop; tmpVLinker = vLinker; vtx1 = tmpVLinker->vertex; addVtx1 = new Vertex(vtx1->point + Point(dir) * d); startAddVtx = addVtx1; mev(tmpLoop, vtx1, addVtx1); while(tmpVLinker->next != NULL){ tmpVLinker = tmpVLinker->next; vtx2 = tmpVLinker->vertex; addVtx2 = new Vertex(vtx2->point + Point(dir) * d); mev(tmpLoop, vtx2, addVtx2); mef(tmpLoop, addVtx2, addVtx1); //mef(tmpLoop, addVtx1, addVtx2); addVtx1 = addVtx2; } mef(tmpLoop, startAddVtx, addVtx1); //mef(tmpLoop, addVtx1, startAddVtx); /*if(tmpoutLoop == face->fLoops){ firLoop = tmpLoop; }else{ kfmrh(firLoop, tmpLoop); }*/ //删除临时创建的点列表。 vLinker; while(vLinker->next != NULL){ tmpVLinker = vLinker->next; delete vLinker; vLinker = tmpVLinker; } delete vLinker; tmpoutLoop = tmpoutLoop->nxtLoop; }while(tmpoutLoop != face->fLoops); } //vtx是要被削平的角顶点, d是在各边上新创建的点到角顶点的距离。reV可以返回新创建的那些顶点。 void chamfer(Solid* solid, Vertex* vtx, float d, Vertex* reV[] = NULL){ int edgeCount = 0; int mark; Edge* tmpE = solid->sEdges; Edge* firE; HalfEdge* tmpHe, *firHe; Vertex *tmpV, *preV; //遍历solid中的所有edge,找到一条以vtx为起点或重点的edge然后停止。 do{ mark = 0; if(tmpE->halfEdge[0]->heStartVertex == vtx || tmpE->halfEdge[1]->heStartVertex == vtx){ mark = 1; firE = tmpE; break; } tmpE = tmpE->nxtEdge; }while(tmpE != solid->sEdges); //确定edge哪条半边的起点是vtx。 if(tmpE->halfEdge[0]->heStartVertex == vtx){ firHe = tmpE->halfEdge[0]; } if(tmpE->halfEdge[1]->heStartVertex == vtx){ firHe = tmpE->halfEdge[1]; } tmpHe = firHe; //遍历记录在vtx周围有多少条边。 EdgeLinker *elinker = NULL, *tmpeLinker; do{ if(elinker == NULL){ //在elinker为空的时候的初始化. tmpeLinker = new EdgeLinker(); tmpeLinker->edge = tmpHe->edge; tmpeLinker->next = NULL; elinker = tmpeLinker; }else{ //在elinker中插入关系,采用头插入链表的方式。 tmpeLinker = new EdgeLinker(); tmpeLinker->edge = tmpHe->edge; tmpeLinker->next = elinker; elinker = tmpeLinker; } edgeCount++; tmpHe = tmpHe->preHalfEdge->edge->halfEdge[1 - tmpHe->preHalfEdge->indexInEdge]; }while(tmpHe != firHe); //按顺序在所有边上进行semv,距离为d. tmpeLinker = elinker; int reC = 0; while(tmpeLinker != NULL){ Point endP; Point startP = vtx->point; if(tmpeLinker->edge->halfEdge[0]->heStartVertex != vtx){ endP = tmpeLinker->edge->halfEdge[0]->heStartVertex->point; }else{ endP = tmpeLinker->edge->halfEdge[1]->heStartVertex->point; } Vector dir = endP + (-1.0 * startP); Point newP = startP + dir * (d / dir.length()); tmpV = new Vertex(newP); //reC和reV返回新创建的点所临时使用的。 if(reV != NULL){ reV[reC] = tmpV; reC++; } tmpE = semv(tmpeLinker->edge, tmpV); if(tmpE->halfEdge[0]->heStartVertex == vtx || tmpE->halfEdge[1]->heStartVertex == vtx){ tmpeLinker->edge = tmpE; } tmpeLinker = tmpeLinker->next; } //按elinker顺序依次进行mef操作。 tmpeLinker = elinker; if(tmpeLinker->edge->halfEdge[0]->heStartVertex != vtx){ preV = tmpeLinker->edge->halfEdge[0]->heStartVertex; }else{ preV = tmpeLinker->edge->halfEdge[1]->heStartVertex; } tmpeLinker = tmpeLinker->next; while(tmpeLinker != NULL){ if(tmpeLinker->edge->halfEdge[0]->heStartVertex != vtx){ Loop* lp = tmpeLinker->edge->halfEdge[1]->heLoop; tmpV = tmpeLinker->edge->halfEdge[0]->heStartVertex; mef(lp, preV, tmpV); }else{ Loop* lp = tmpeLinker->edge->halfEdge[0]->heLoop; tmpV = tmpeLinker->edge->halfEdge[1]->heStartVertex; mef(lp, preV, tmpV); } preV = tmpV; tmpeLinker = tmpeLinker->next; } //以上过程少处理了最后一条边链接到第一条边的那一次mef,故而特殊处理如下。 if(elinker->edge->halfEdge[0]->heStartVertex != vtx){ Loop* lp = elinker->edge->halfEdge[1]->heLoop; tmpV = elinker->edge->halfEdge[0]->heStartVertex; mef(lp, preV, tmpV); }else{ Loop* lp = elinker->edge->halfEdge[0]->heLoop; tmpV = elinker->edge->halfEdge[1]->heStartVertex; mef(lp, preV, tmpV); } //按照tmpeLinker使用kef逐个删除边和面,但是最后一个要使用kev. tmpeLinker = elinker; while(tmpeLinker != NULL){ if(tmpeLinker->next != NULL){ kef(tmpeLinker->edge); }else{ kev(tmpeLinker->edge, vtx); } tmpeLinker = tmpeLinker->next; } } //operation has the override version //扫成操作方便使用的接口 void sweep(Face* face, Vector dir, float d){ double nd[3] = {dir.pos[0], dir.pos[1], dir.pos[2]}; sweep(face, nd, d); }<file_sep>#pragma once #include <iostream> using namespace std; #include "EulerOperation.h" //用来将solid输出成老师提供的框架所规定的格式文件。 void output(Solid* solid, char* path){ if(solid == NULL){ cout << "solid cannot be NULL in output function." <<endl; return; } int vertexCount = 0, loopCount = 0, faceCount = 0, solidCount = 0; Solid* tmpSolid = solid; Face* tmpFace; Loop* tmpLoop; HalfEdge* tmpHF; Vertex* tmpVertex = solid->sVertices; FILE *fp; fp = fopen(path, "w"); fprintf(fp, "BRP\n"); //输出vertex, loop, face, solid的个数信息. do{ solidCount++; faceCount += tmpSolid->faceCount; loopCount += tmpSolid->loopCount; vertexCount += tmpSolid->vertexCount; tmpSolid = tmpSolid->nxtSolid; }while(tmpSolid != solid); fprintf(fp, "%d %d %d %d\n", vertexCount, loopCount, faceCount, solidCount); //输出点的坐标信息,并在过程中给其进行标号。 for(int i = 0; i < vertexCount; i++){ tmpVertex->mark = i; fprintf(fp, "%f %f %f\n", tmpVertex->point.pos[0], tmpVertex->point.pos[1], tmpVertex->point.pos[2]); tmpVertex = tmpVertex->nxtVertex; } //输出loop的信息,并在过程中为其标号。 tmpSolid = solid; loopCount = 0; for(int i = 0; i < solidCount; i++){ tmpFace = tmpSolid->sFaces; do{ tmpLoop = tmpFace->fLoops; do{ tmpLoop->mark = loopCount; loopCount++; tmpHF = tmpLoop->lHalfEdges; int thisVertexCount = 0; do{ thisVertexCount++; tmpHF = tmpHF->nxtHalfEdge; }while(tmpHF != tmpLoop->lHalfEdges); fprintf(fp, "%d", thisVertexCount); do{ fprintf(fp, " %d", tmpHF->heStartVertex->mark); tmpHF = tmpHF->nxtHalfEdge; }while(tmpHF != tmpLoop->lHalfEdges); fprintf(fp, "\n"); tmpLoop = tmpLoop->nxtLoop; }while(tmpLoop != tmpFace->fLoops); tmpFace = tmpFace->nxtFace;// }while(tmpFace != tmpSolid->sFaces); tmpSolid = tmpSolid->nxtSolid;// } tmpSolid = solid; for(int i = 0; i < solidCount; i++){ tmpFace = tmpSolid->sFaces; do{ tmpLoop = tmpFace->fLoops; fprintf(fp, "%d", tmpLoop->mark); int thisLoopCount = 0; do{ thisLoopCount++; tmpLoop = tmpLoop->nxtLoop; }while(tmpLoop != tmpFace->fLoops); fprintf(fp, " %d", thisLoopCount - 1); tmpLoop = tmpLoop->nxtLoop; while(tmpLoop != tmpFace->fLoops){ fprintf(fp, " %d", tmpLoop->mark); tmpLoop = tmpLoop->nxtLoop; } fprintf(fp, " %d\n", i); tmpFace = tmpFace->nxtFace;// }while(tmpFace != tmpSolid->sFaces); tmpSolid = tmpSolid->nxtSolid;// } fclose(fp); }
60754801be07d6db07b2d17ae06d97b5c230aeed
[ "C++" ]
5
C++
vliuzhihua/EulerOperation
4af92acba7637dbe10a4f4f9cf4242b2a5f80d12
5c79ef0b0cedf7e2f110df8db164548308b2a27e
refs/heads/master
<repo_name>Shielc/Multiclipboard<file_sep>/Multiclipboard.py import pyperclip, sys, shelve # Save clipboard content. shelfFile = shelve.open('mydata') if len(sys.argv) == 3 and sys.argv[1].lower() == 'save': shelfFile[sys.argv[2]] = pyperclip.paste() elif len(sys.argv) == 3 and sys.argv[1].lower() == 'get': try: pyperclip.copy(shelfFile[sys.argv[2]]) except KeyError: print("Yor key is not defined,please reffer to the below keys list") klist = list(shelfFile.keys()) print (klist) elif len(sys.argv) == 2 or len(sys.argv) == 1: klist = list(shelfFile.keys()) print (klist) shelfFile.close()
b79ff0f4a1fbeb344cf03c879d1724a006304bed
[ "Python" ]
1
Python
Shielc/Multiclipboard
2356c4184921a9f34300f644e3acd128745acdbb
0c619212b1f1ce25df9b50a5b46bba0e74bc67f9
refs/heads/master
<repo_name>matheuslanduci/dt-money<file_sep>/src/hooks/index.ts import { useContext } from "react"; import { AuthContext } from "../contexts/Auth"; import { TransactionsContext } from "../contexts/Transactions"; export function useTransactions() { return useContext(TransactionsContext); } export function useAuth() { return useContext(AuthContext); }<file_sep>/src/mirage/index.ts import { belongsTo, createServer, Model } from "miragejs"; import jwt from "jsonwebtoken"; import { hashSync, compareSync } from "bcryptjs"; const SECRET_KEY = "123456"; interface TokenResponseProps { username: string; } export function makeServer() { createServer({ models: { transaction: Model.extend({ user: belongsTo("user") }), user: Model }, seeds(server) { server.db.loadData({ transactions: [ { id: 1, title: "Freelance de website", type: "deposit", category: "Dev", amount: 6000, createdAt: new Date("2021-02-12 09:00:00"), userId: 1 }, { id: 2, title: "Aluguel", type: "withdraw", category: "Casa", amount: 1100, createdAt: new Date("2021-02-14 11:00:00"), userId: 1 } ], users: [ { id: 1, username: "admin", password: <PASSWORD>("<PASSWORD>", 8) } ] }); }, routes() { this.namespace = "api"; this.post("/auth", (schema, request) => { const data = JSON.parse(request.requestBody); const user: any = schema .all("user") .models.find(model => model.attrs.username === data.username); if (!user) { return { error: "Não existe um usuário com esse nome." }; } const validatedPassword: any = compareSync( data.password, user.attrs.password ); if (!validatedPassword) { return { error: "Não existe um usuário com esse nome" }; } const token = jwt.sign({ username: data.username }, SECRET_KEY); return { user: { username: data.username, token } }; }); this.post("/signup", (schema, request) => { const data = JSON.parse(request.requestBody); const user: any = schema .all("user") .models.find(model => model.attrs.username === data.username); if (user) { return { error: "Já existe um usuário com esse nome." }; } const newPassword = hashSync(data.password, 8); schema.create("user", { ...data, password: <PASSWORD> }); const token = jwt.sign({ username: data.username }, SECRET_KEY); return { user: { username: data.username, token } }; }); this.get("/transactions", (schema, request) => { const { username, token } = request.requestHeaders; const parsedToken: TokenResponseProps = jwt.verify( token, SECRET_KEY ) as TokenResponseProps; if (parsedToken.username !== username) { return { error: "Envie um token." }; } const user: any = schema .all("user") .models.find(model => model.attrs.username === username); const transactions = schema .all("transaction") .models.filter( transaction => transaction.attrs.userId === parseInt(user.id) ); return { transactions }; }); this.post("/transactions", (schema, request) => { const data = JSON.parse(request.requestBody); const { username, token } = request.requestHeaders; const parsedToken: TokenResponseProps = jwt.verify( token, SECRET_KEY ) as TokenResponseProps; if (parsedToken.username !== username) { return { error: "Envie um token." }; } const user: any = schema .all("user") .models.find(model => model.attrs.username === username); return schema.create("transaction", { ...data, createdAt: new Date(), userId: parseInt(user.id) }); }); } }); } <file_sep>/README.md <img alt="Ignite" src="https://i.imgur.com/eCVyxxy.png"> <h2 align="center"> Ignite - Trilha ReactJS </h2> <p align="center"> Projeto 01: dt money </p> <img alt="dt money" src="https://i.imgur.com/mLTY39l.png"> ## Sobre o projeto O projeto foi baseado no 2º módulo da trilha ReactJS do Ignite. Além do que foi construído na [aula](https://github.com/matheuslanduci/aula02-trilha-react), também foi inserido um sistema de autenticação (via Context API) e também no MirageJS com JWT/Bcrypt. ## 🚀 Como executar - Clone o repositório - Instale as dependências com yarn - Inicie o servidor com yarn start - Agora você pode acessar localhost:3000 do seu navegador. <file_sep>/src/contexts/Auth.ts import { createContext } from "react"; export interface User { username: string; token: string; } export interface UserInput { username: string; password: string; } interface AuthContextData { signed: boolean; user: User | null; Authenticate: (user: UserInput) => Promise<void>; Register: (user: UserInput) => Promise<void>; Logout: () => void; } export const AuthContext = createContext<AuthContextData>( {} as AuthContextData ); <file_sep>/src/contexts/Transactions.ts import { createContext } from "react"; import { TransactionItemProps, NewTransactionInput } from "../containers/TransactionsProvider"; interface TransactionContextData { transactions: TransactionItemProps[]; createTransaction: (transaction: NewTransactionInput) => Promise<void>; } export const TransactionsContext = createContext<TransactionContextData>( {} as TransactionContextData ); <file_sep>/src/pages/Login/styles.ts import styled from "styled-components"; import { transparentize } from "polished"; export const Container = styled.div` width: 100%; min-height: 100vh; display: flex; flex-direction: column; align-items: center; header { width: 100%; height: 6rem; display: flex; justify-content: center; align-items: center; background: var(--blue); } form { margin-top: 1.5rem; width: 100%; max-width: 360px; display: flex; flex-direction: column; align-items: center; h2 { color: var(--text-title); font-size: 1.5rem; margin-bottom: 2rem; } input { width: 100%; padding: 0 1.5rem; height: 3rem; border-radius: 0.25rem; border: 1px solid #d7d7d7; background: #e7e9ee; font-weight: 400; font-size: 1rem; &::placeholder { color: var(--text-body); } & + input { margin-top: 1rem; } } } button, a { width: 100%; padding: 0 1.5rem; height: 3rem; border-radius: 0.25rem; border: 0; font-size: 1rem; font-weight: 600; margin-top: 1rem; display: inline-flex; align-items: center; justify-content: center; text-decoration: none; } button[type="submit"] { background: var(--green); color: #fff; transition: filter 0.2s; &:hover { filter: brightness(0.9); } } a { color: var(--text-title); transition: background-color 0.2s; &:hover { background: ${transparentize(0.9, "#33cc95")}; } } `;
712a61dfeb605e460781b6e00acfd7d584c24b9b
[ "Markdown", "TypeScript" ]
6
TypeScript
matheuslanduci/dt-money
d51f86fff6a94b274db2c6dd5b16dfb5b7ed073d
f8715f65550d74d1716ef99839282c05ca5832e5
refs/heads/master
<repo_name>FunkyTree/ScampiGame<file_sep>/public/javascripts/game.js var topMargin = 0; var imageHeight = 400; var rotationNumber = [3]; var spinning; var busy = false; init(); function init(){ // todo: init game unloadScrollBars(); $(document).keypress(function(e) { if(e.which == 13) { // spin if(!busy) { busy = true; // set rnd spinningwidth var rotationSpeed = (Math.random() % 0.1) + 0.05; var rotationTime = (Math.random() % 1.5) + 1.2; updateSiblingsById("col1", {transition: "all " + rotationSpeed + "s linear 0s"}); updateSiblingsById("col2", {transition: "all " + rotationSpeed + "s linear 0s"}); updateSiblingsById("col3", {transition: "all " + rotationSpeed + "s linear 0s"}); drehen("col1", 1.2, rotationSpeed); drehen("col2", 1.5, rotationSpeed); drehen("col3", 1.9, rotationSpeed); } } }); } function unloadScrollBars() { document.documentElement.style.overflow = 'hidden'; // firefox, chrome } function updateSiblingsById(id, css){ var elements = $("#" + id).children(); for(var i = 0; i < elements.length; i++){ $(elements[i]).css(css); } } // drehen der spalte für s Sekunden mit intervall i function drehen(spalte, s, i){ setTimeout(function(){ clearInterval(spinning); busy = false; }, s * 1000); var spinning = setInterval(function(){ topMargin += imageHeight; var photos = $("#" + spalte).children(); for(var c = 0; c < photos.length; c++){ $(photos[c]).css({top: ((imageHeight * c) + topMargin) + "px"}); } if(topMargin % imageHeight == 0) { rotate(spalte); } }, i * 1000); } function rotate(spalte){ var second = $("#" + spalte).children().first(); // switch last to first var last = $("#" + spalte).children().last(); last.css({top:0}) last.prependTo(last.parent()); topMargin = 0; } <file_sep>/README.md This is a little singlehanded bandit. Have fun. Open with: nodemon bin/www Url: localhost:3000 Trigger with [ENTER] <file_sep>/public/javascripts/game_backup_13-01.js var topMargin = 0; var imageHeight = 400; var rotationNumber = [3]; var spinning; init(); function init(){ // todo: init game $(document).keypress(function(e) { if(e.which == 13) { // set rnd spinningwidth // spin if(!spinning) { drehen("col1", 1.2); drehen("col2", 1.5); drehen("col3", 1.7); } } }); } // drehen für i Sekunden function drehen(spalte, i){ setTimeout(function(){ clearInterval(spinning); }, i * 1000); var spinning = setInterval(function(){ topMargin += imageHeight; var photos = $("#" + spalte).children(); for(var i = 0; i < photos.length; i++){ $(photos[i]).css({top: ((imageHeight * i) + topMargin) + "px"}); } if(topMargin % imageHeight == 0) { rotate(spalte); } }, 200); } function rotate(spalte){ var second = $("#" + spalte).children().first(); // switch last to first var last = $("#" + spalte).children().last(); last.css({top:0}) last.prependTo(last.parent()); topMargin = 0; }
fbbc868de542ed211f17c90bbcc144ae44763336
[ "JavaScript", "Markdown" ]
3
JavaScript
FunkyTree/ScampiGame
17dd52aeb26f6765cee017ac28df2c265369c741
939bf8c175c8013c8327204e064f1a5f68d3656c
refs/heads/master
<repo_name>alvaroserrrano/threaded-mergeInsertSort<file_sep>/A1/Makefile CC = gcc CFLAGS = -g -Wall -Werror -pedantic CFLAGS+= -pthread # CFLAGS = -std=c11 LDLIBS += -lpthread LDLIBS += -lrt a1: a1.o array.o error.o random.o linked.o a1.o: a1.c array.h linked.h array.o: array.c apue.h array.h random.h linked.o: linked.c apue.h linked.h random.h array.h error.o: error.c apue.h random.o: random.c random.h apue.h clean: rm -f *.o a1 *.csv run: ./source <file_sep>/A1/linked.h /* <NAME> CS3240 1/13/2019 Assignment 1 */ #ifndef LINKED_H #define LINKED_H //Define node as pointer of data type struct LinkedList typedef struct node_struct { struct node_struct *next; double val; } node; /* arguments for a thread */ struct thread_arg_linked { int done; node *linked_list; int size; }; // extern node *initialize_linked(int *size); extern node *initialize_linked(int size, double *arr); extern node *create_node(int size); extern int sort_linked(node *innode, int size); extern void *merge_insert_sort_linked(void *thread_args); extern void insert_element_linked(node **head, node *innode); extern void merge_linked(node *head_1, node *head_2, node **target); extern void swap(node **node_1, node **node_2); extern int write_linked(node *linked, int size, char *outfilename); extern void print_linked(node *head); #endif // !LINKED_H <file_sep>/A1/array.c /* <NAME> CS3240 1/13/2019 Assignment 1 */ #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <math.h> #include <pthread.h> #include "apue.h" #include "array.h" #include <time.h> #include "random.h" #include <sys/time.h> #include <sys/resource.h> #include <unistd.h> #define BREAK_SIZE_ARR 1000 //Parent divides in half and spawn 2 threads recursively until size <= 1000 // unsigned int usecs; //the type useseconds_t is an unsigned int that can hold ints ranging [0, 1000000]. It is not used here for portability issues //Generate a random collection of doubles btw 10000 and 12000 elements double *create_array(int *size) { int i; //Random size btw 10000 and 12000 elements *size = make_int(10000, 12000); //Malloc array double *array = malloc((*size) * sizeof(double)); //Fill array for (i = 0; i < *size; i++) { array[i] = make_double(1, 100000); } return array; } //Thread to implement merge_insert_sort, write array to output file ("array.csv"), and free memory location int sort_arr(double *arr, int size) { //Var init int retval = 0; pthread_t thread; struct timespec start, finish; struct thread_arg_arr thread_args = {0, arr, size}; long s; //SECONDS long ns; //NANOSECONDS printf("in array: %d elements\n", size); //init timer clock_gettime(CLOCK_REALTIME, &start); //Wait for the thread to complete pthread_create(&(thread), NULL, &merge_insert_sort_arr, (void *)&(thread_args)); while (!thread_args.done) usleep(1); //terminate thread pthread_join(thread, NULL); //stop timer clock_gettime(CLOCK_REALTIME, &finish); s = finish.tv_sec - start.tv_sec; ns = finish.tv_nsec - start.tv_nsec; if (start.tv_nsec > finish.tv_nsec) { // clock underflow --s; ns += 1000000000; } printf("%s\n", "Sorting done..."); // printf("Seconds without ns: %ld\n", s); printf("Runtime in ns: %ld nanoseconds\n", ns); printf("Runtime in s: %e seconds\n", (double)s + (double)ns / (double)1000000000); printf("Runtime in ms: %ldms miliseconds\n", ns / 1000000); //top parent opens and writes csv file if (!write_output_csv(arr, size, "array.csv")) { retval = -1; } //top parent frees array printf("---------------------------------\n"); return retval; } //a thread is spawned here and merge_insert_sort is implemented void *merge_insert_sort_arr(void *thread_args) { int i, j; double key; struct thread_arg_arr *args = thread_args; //BASE CASE if (args->size <= BREAK_SIZE_ARR) { // do insertion sort for (i = 1; i < args->size; i++) { key = args->arr[i]; j = i - 1; // Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position while (j >= 0 && args->arr[j] > key) { args->arr[j + 1] = args->arr[j]; j = j - 1; } args->arr[j + 1] = key; } } //RECURSIVE CASE else { pthread_t thread_1, thread_2; //Group into at least n/2 pairs of elements, leaving one unpaired if the size of the array is odd int sub_arr_1_size = args->size / 2; int sub_arr_2_size = (args->size / 2) + (args->size % 2); //malloc temp arrays double *sub_arr_1 = malloc(sub_arr_1_size * sizeof(double)); double *sub_arr_2 = malloc(sub_arr_2_size * sizeof(double)); //build temp arrays for (i = 0; i < sub_arr_1_size; i++) { sub_arr_1[i] = args->arr[i]; } for (i = 0; i < sub_arr_2_size; i++) { sub_arr_2[i] = args->arr[i + sub_arr_1_size]; } //Sort both subarrays recursively in ascending order. Span 2 threads (1 for each half) struct thread_arg_arr thread_1_args = {0, sub_arr_1, sub_arr_1_size}; struct thread_arg_arr thread_2_args = {0, sub_arr_2, sub_arr_2_size}; pthread_create(&(thread_1), NULL, &merge_insert_sort_arr, (void *)&(thread_1_args)); pthread_create(&(thread_2), NULL, &merge_insert_sort_arr, (void *)&(thread_2_args)); //Wait for thread to complete while (!thread_1_args.done && !thread_2_args.done) usleep(1); //Finish thread pthread_join(thread_1, NULL); pthread_join(thread_2, NULL); //Merge subarrays merge_arr(sub_arr_1, sub_arr_1_size, sub_arr_2, sub_arr_2_size, args->arr); //Free memory in reverse order than it was allocated free(sub_arr_2); sub_arr_2 = NULL; free(sub_arr_1); sub_arr_2 = NULL; } //Mark thread as completed args->done = 1; //terminate calling thread pthread_exit(0); } // //Insert double into a sorted array of doubles // void insert_element_arr(double *arr, double val, int size) // { // int i; // //shift elements forward // for (i = size - 1; i >= 0 && arr[i] > val; i--) // { // arr[i + 1] = arr[i]; // } // arr[i + 1] = val; // } //Merge 2 subarrays void merge_arr(double *sub_arr_1, int sub_arr_1_size, double *sub_arr_2, int sub_arr_2_size, double *merged_array) { int i = 0, l = 0, r = 0; int n = sub_arr_1_size + sub_arr_2_size; //size of merged_array for (i = 0; i < n; i++) { if (l < sub_arr_1_size && r < sub_arr_2_size) { if (sub_arr_1[l] < sub_arr_2[r]) { merged_array[i] = sub_arr_1[l]; l++; } else { merged_array[i] = sub_arr_2[r]; r++; } } else if (l == sub_arr_1_size) { //reached end of sub_arr_1 // copy remaining elements in sub_arr_2 while (i < n) { merged_array[i] = sub_arr_2[r]; i++; r++; } } else { //reached end of sub_arr_2 //copy remaining elements in sub_arr_2 while (i < n) { merged_array[i] = sub_arr_1[l]; i++; l++; } } } } int write_output_csv(double *arr, int size, char *outfilename) { int i, errnum, retval = 0; FILE *outfile = fopen(outfilename, "w"); if (outfile == NULL) { errnum = errno; err_msg("Error opening file: %s\n", strerror(errnum)); retval = -1; } else { for (i = 0; i < size; i++) { if (!fprintf(outfile, "%f, ", arr[i])) { errnum = errno; err_msg("Error writing to file: %s\n", strerror(errnum)); retval = -1; } else { if ((i + 1) % 10 == 0) { if (!fprintf(outfile, "\n")) { errnum = errno; err_msg("Error writing to file: %s\n", strerror(errnum)); retval = -1; } } } } fclose(outfile); } return retval; } void print_arr(double *arr, int size) { int i; for (i = 0; i < size; i++) { printf(">%f<\n", arr[i]); } } <file_sep>/A1/random.c /* <NAME> CS3240 1/13/2019 Assignment 1 */ #include <time.h> #include <stdio.h> #include <stdlib.h> #include "random.h" #include "apue.h" //Generate a random integer; i.e. to determine size of the array int make_int(int low, int high) { struct timespec spec_struct; clock_gettime(CLOCK_REALTIME, &spec_struct); // Initialize random number generator srand((unsigned long)spec_struct.tv_nsec); //current time as seed return (rand() % (high - low)) + low; } double make_double(int low, int high) { const int decimals = 1.0e4; //4 decimal places return ((double)(make_int(low * decimals, high * decimals)) / decimals); } <file_sep>/A1/README.md A merge-insert sort; divides the original problem into separate collections <=1000. So, if 10,000 will have 10 parts. Insert sorts each collection then merges them together. Parent divides in half and spawns two threads recursively until size <=1000. Sorts the <= 1000 collection using an insert sort you write. When two children die the parent merges the two parts into one. The top program writes the sorted collection to a comma separated file with 10 doubles per line named array.csv or linked.csv <file_sep>/A1/a1.c /* <NAME> CS3240 1/13/2019 Assignment 1 1. A random collection of doubles of random length between 10 000 and 12 000 elements is generated. 2.1. Parent divides in half and spawns two threads recursively until size <=1000. 2.2. The <=1000 elements collection is sorted (Insertion Sort). 3. The sorted collection is written to "array.csv" with 10 doubles per line separated by commas. */ #include "array.h" #include "linked.h" #include <stdlib.h> #include <stdio.h> // #include "apue.h" int main(int argc, char *argv[]) { int size; double *arr = create_array(&size); sort_arr(arr, size); node *linked_list = initialize_linked(size, arr); // node *linked_list = initialize_linked(&size); sort_linked(linked_list, size); free(arr); arr = NULL; free(linked_list); linked_list = NULL; exit(0); } //main <file_sep>/A1/linked.c /* <NAME> CS3240 1/13/2019 Assignment 1 */ #include "apue.h" #include "linked.h" #include "random.h" #include "array.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <pthread.h> #include <time.h> #include <sys/time.h> #include <sys/resource.h> #include <unistd.h> #define BREAK_SIZE_LINKED 1000 //Parent divides in half and spawn 2 threads recursively until size <= 1000 // //Create node // node *create_node() // { // //declare a node // node *cur; // cur = malloc(sizeof(node)); // cur->next = NULL; // cur->val = 0; // return cur; // } //Fill node values with random doubles node *initialize_linked(int size, double *arr) { int i; node *head, *cur; head = create_node(size); cur = head; for (i = 0; i < size; i++) { cur->val = arr[i]; cur = cur->next; } return head; } // node *initialize_linked(int *size) // { // int i; // *size = make_int(10000, 12000); // node *head, *cur; // head = create_node(*size); // cur = head; // for (i = 0; i < *size; i++) // { // cur->val = make_double(1, 100000); // cur = cur->next; // } // return head; // } //Create linked list and allocate memory node *create_node(int size) { int i; node *head, *cur; head = malloc(sizeof(node)); head->next = NULL; head->val = 0.0; cur = head; //point to the head //create subsequent nodes for (i = 0; i < size - 1; i++) { node *new_node = malloc(sizeof(node)); cur->next = new_node; cur->val = 0.0; cur = cur->next; } //tail points to NULL cur->next = NULL; return head; } int sort_linked(node *innode, int size) { int retval = 0; pthread_t thread; struct timespec start, finish; struct thread_arg_linked thread_args = {0, innode, size}; long s; //SECONDS long ns; //NANOSECONDS printf("in linked list: %d elements\n", size); //start timer clock_gettime(CLOCK_REALTIME, &start); //Wait for thread completion pthread_create(&(thread), NULL, &merge_insert_sort_linked, (void *)&(thread_args)); while (!thread_args.done) usleep(1); //terminate thread pthread_join(thread, NULL); //stop timer clock_gettime(CLOCK_REALTIME, &finish); s = finish.tv_sec - start.tv_sec; ns = finish.tv_nsec - start.tv_nsec; if (start.tv_nsec > finish.tv_nsec) { // clock underflow --s; ns += 1000000000; } printf("%s\n", "Sorting done..."); printf("Runtime in ns: %ld nanoseconds\n", ns); printf("Runtime in s: %e seconds\n", (double)s + (double)ns / (double)1000000000); printf("Runtime in ms: %ldms miliseconds\n", ns / 1000000); if (!write_linked(thread_args.linked_list, thread_args.size, "linked.csv")) { retval = -1; } // free(innode); // innode = NULL; printf("---------------------------------\n"); return retval; } //a thread is spawned here and merge_insert_sort is implemented void *merge_insert_sort_linked(void *thread_args) { struct thread_arg_linked *args = thread_args; if (args->size <= BREAK_SIZE_LINKED) { //Insertion sort node *cur, *next; //create result list node *res = create_node(1); //traverse given list and insert current node in sorted way in result list res->val = args->linked_list->val; args->linked_list = args->linked_list->next; cur = args->linked_list; while (cur != NULL) { next = cur->next; insert_element_linked(&res, cur); cur = next; } args->linked_list = res; } else { pthread_t thread_1, thread_2; int sub_linked_1_size = args->size / 2; int sub_linked_2_size = (args->size / 2) + (args->size % 2); node *head_1 = create_node(sub_linked_1_size); node *head_2 = create_node(sub_linked_2_size); node *cur; for (cur = head_1; cur != NULL; cur = cur->next) { cur->val = args->linked_list->val; args->linked_list = args->linked_list->next; } for (cur = head_2; cur != NULL; cur = cur->next) { cur->val = args->linked_list->val; args->linked_list = args->linked_list->next; } //Sort both sublists recursively in ascending order. Spawn 2 threads struct thread_arg_linked thread_1_args = {0, head_1, sub_linked_1_size}; struct thread_arg_linked thread_2_args = {0, head_2, sub_linked_2_size}; //init threads pthread_create(&(thread_1), NULL, &merge_insert_sort_linked, (void *)&(thread_1_args)); pthread_create(&(thread_2), NULL, &merge_insert_sort_linked, (void *)&(thread_2_args)); //wait for threads while (!thread_1_args.done && !thread_2_args.done) { usleep(1); } //finish threads pthread_join(thread_1, NULL); pthread_join(thread_2, NULL); //MERGE sublists merge_linked(thread_1_args.linked_list, thread_2_args.linked_list, &(args->linked_list)); //free memory in reverse order as allocated free(head_2); head_2 = NULL; free(head_1); head_1 = NULL; } args->done = 1; pthread_exit(0); } //Insert node in sorted way in a result linked list. This function expects a pointer to the head as it can modify the head of the input linked list void insert_element_linked(node **head, node *innode) { node *cur; //cursor node //check if list is empty or node's value is less than head's value if (*head == NULL || (innode)->val <= (*head)->val) { innode->next = *head; *head = innode; //inserted node becomes head } else { cur = *head; while (cur->next != NULL && cur->next->val < innode->val) { cur = cur->next; } innode->next = cur->next; cur->next = innode; } } void merge_linked(node *head_1, node *head_2, node **target) { node temp; node *cur = &temp; temp.next = NULL; while (!(head_1 == NULL || head_2 == NULL)) { if (head_1->val <= head_2->val) { swap(&(cur->next), &head_1); } else { swap(&(cur->next), &head_2); } cur = cur->next; } if (head_1 == NULL) { cur->next = head_2; } else if (head_2 == NULL) { cur->next = head_1; } (*target) = temp.next; } //Move node_1 to node_2 and node_2 to node_2->next void swap(node **node_1, node **node_2) { node *temp = *node_2; //temp = sublist_x *node_2 = temp->next; temp->next = *node_1; *node_1 = temp; } void print_linked(node *head) { node *cur; for (cur = head; cur != NULL; cur = cur->next) { printf(">%f\n", cur->val); } } int write_linked(node *head, int size, char *outfilename) { int i = 0, retval = 0; node *cur; double *buffer = malloc(size * sizeof(double)); for (cur = head; cur != NULL; cur = cur->next) { buffer[i] = cur->val; i++; } retval = write_output_csv(buffer, size, outfilename); free(buffer); buffer = NULL; return retval; } <file_sep>/A1/random.h /* <NAME> CS3240 1/13/2019 Assignment 1 */ #ifndef RANDOM_H #define RANDOM_H extern int make_int(int low, int high); extern double make_double(int low, int high); #endif <file_sep>/A1/array.h /* <NAME> CS3240 1/13/2019 Assignment 1 */ #ifndef ARRAY_H #define ARRAY_H //thread arguments struct thread_arg_arr { int done; double *arr; int size; }; extern double * create_array(int *size); extern int sort_arr(double *arr, int size); extern void *merge_insert_sort_arr(void *thread_args); // extern void insert_element_arr(double *arr, double val, int size); extern void merge_arr(double *sub_arr_1, int sub_arr_size_1, double *sub_arr_2, int size_sub_arr_2, double *target); extern int write_output_csv(double *arr, int size, char *outfilename); extern void print_arr(double *arr, int size); #endif
11b644f6acda74d07e301391333fe2faa8877e57
[ "Markdown", "C", "Makefile" ]
9
Makefile
alvaroserrrano/threaded-mergeInsertSort
299fd6d7e54e0f28c61ec7ae36bae4812e7fe9c2
01c39710953d5225dedd23b05abbdbe3a231ba85
refs/heads/master
<repo_name>Mudassirmh119/Admin-App<file_sep>/src/Components/Content/Users/users.jsx import React, { Component } from "react"; import { getUsers, deleteUser } from "../../../Services/userService"; import _ from "lodash"; import Pagination from "../../Common/pagination"; import UsersTable from "./usersTable"; import { paginate } from "../../../utils/paginate"; import SearchBox from "../searchBox"; class Users extends Component { constructor(props) { super(props); this.state = { users: getUsers(), pageSize: 4, currentPage: 1, searchQuery: "", sortColumn: { path: "name", order: "asc" }, }; } handleDelete = (user) => { const users = this.state.users.filter((u) => u.id !== user.id); this.setState({ users }); deleteUser(user.id); }; handlePageChange = (page) => { this.setState({ currentPage: page }); }; handleSearch = (query) => { this.setState({ searchQuery: query, selectedGenre: null, currentPage: 1 }); }; handleSort = (sortColumn) => { this.setState({ sortColumn }); }; getPagedData = () => { const { pageSize, currentPage, sortColumn, searchQuery, users: allUsers, } = this.state; let filtered = allUsers; if (searchQuery) filtered = allUsers.filter((u) => u.name.toLowerCase().startsWith(searchQuery.toLowerCase()) ); const sorted = _.orderBy(filtered, [sortColumn.path], [sortColumn.order]); const users = paginate(sorted, currentPage, pageSize); return { totalCount: filtered.length, data: users }; }; render() { const { length: count } = this.state.users; const { pageSize, currentPage, sortColumn, searchQuery } = this.state; // const { user } = this.props; if (count === 0) return <p>There are no users in the database</p>; const { totalCount, data: users } = this.getPagedData(); return ( <React.Fragment> <p>Showing {totalCount} Users from the database</p> <SearchBox value={searchQuery} onChange={this.handleSearch} /> <UsersTable users={users} sortColumn={sortColumn} onDelete={this.handleDelete} onSort={this.handleSort} /> <div className="row"> <div className="col col-2 offset-5"> <Pagination itemsCount={totalCount} pageSize={pageSize} onPageChange={this.handlePageChange} currentPage={currentPage} /> </div> </div> </React.Fragment> ); } } export default Users; <file_sep>/src/Components/Content/content.jsx import React from "react"; import "./content.css"; import Users from "./Users/users"; import { useParams, Redirect } from "react-router-dom"; import Posts from "./Posts/posts"; const getContent = (content) => { if (content === "posts") return <Posts />; else if (content === "users") return <Users />; else return <Redirect to="/not-found" />; }; const Content = (props) => { const { content: contentToShow } = useParams(); const classes = props.show ? "main open" : "main"; const table = getContent(contentToShow); return ( <div className={classes}> <div className="container"> <h1>{contentToShow}</h1> <div className="table-responsive">{table}</div> </div> </div> ); }; export default Content; <file_sep>/src/Services/userService.js const users = [ { id: "1", name: "<NAME>", username: "Bret", email: "<EMAIL>", address: { street: "Kulas Light", suite: "Apt. 556", city: "Gwenborough", }, phone: "111111111131", website: "hildegard.org", }, { id: "2", name: "<NAME>", username: "Antonette", email: "<EMAIL>", address: { street: "Victor Plains", suite: "Suite 879", city: "Wisokyburgh", }, phone: "1111111111", website: "anastasia.net", }, { id: "3", name: "<NAME>", username: "Samantha", email: "<EMAIL>", address: { street: "Douglas Extension", suite: "Suite 847", city: "McKenziehaven", }, phone: "111111111147", website: "ramiro.info", }, { id: "4", name: "<NAME>", username: "Karianne", email: "<EMAIL>", address: { street: "Hoeger Mall", suite: "Apt. 692", city: "South Elvis", }, phone: "1111111111", website: "kale.biz", }, { id: "5", name: "<NAME>", username: "Kamren", email: "<EMAIL>", address: { street: "Skiles Walks", suite: "Suite 351", city: "Roscoeview", }, phone: "11111111119", website: "<EMAIL>", }, { id: "6", name: "Mrs. <NAME>", username: "Leopoldo_Corkery", email: "<EMAIL>", address: { street: "Norberto Crossing", suite: "Apt. 950", city: "South Christy", }, phone: "1111111111780", website: "ola.org", }, { id: "7", name: "<NAME>", username: "Elwyn.Skiles", email: "<EMAIL>", address: { street: "Rex Trail", suite: "Suite 280", city: "Howemouth", }, phone: "1111111111", website: "elvis.io", }, { id: "8", name: "<NAME>", username: "Maxime_Nienow", email: "<EMAIL>", address: { street: "Ellsworth Summit", suite: "Suite 729", city: "Aliyaview", }, phone: "1111111111", website: "jacynthe.com", }, { id: "9", name: "<NAME>", username: "Delphine", email: "<EMAIL>", address: { street: "Dayna Park", suite: "Suite 449", city: "Bartholomebury", }, phone: "11111111114 ", website: "conrad.com", }, { id: "10", name: "<NAME>", username: "Moriah.Stanton", email: "<EMAIL>", address: { street: "Kattie Turnpike", suite: "Suite 198", city: "Lebsackbury", }, phone: "1111111111", website: "ambrose.net", }, ]; export function getUsers() { return users; } export function getUser(id) { const user = users.find((u) => u.id === id); return user; } export function saveUser(user) { let userInDB = users.find((u) => u.id === user.id) || {}; userInDB.name = user.name; userInDB.username = user.username; userInDB.email = user.email; const address = {}; address.street = user.street; address.suite = user.suite; address.city = user.city; userInDB.address = { ...address }; userInDB.phone = user.phone; userInDB.website = user.website; if (!userInDB.id) { userInDB.id = Date.now().toString(); users.push(userInDB); } return userInDB; } export function deleteUser(id) { let userInDb = users.find((u) => u.id === id); users.splice(users.indexOf(userInDb), 1); return userInDb; } <file_sep>/src/Components/Content/Users/usersTable.jsx import React, { Component } from "react"; import Table from "../../Common/table"; import { Link } from "react-router-dom"; class UsersTable extends Component { columns = [ { path: "name", label: "Name" }, { path: "username", label: "Username" }, { path: "email", label: "Email" }, { path: "address.city", label: "City" }, { path: "phone", label: "Phone" }, { path: "website", label: "Website" }, { key: "edit", content: (user) => ( <Link to={`/register/${user.id}`} className="btn btn-info btn-sm"> Edit </Link> ), }, { key: "delete", content: (user) => ( <button onClick={() => this.props.onDelete(user)} className="btn btn-danger btn-sm" > Delete </button> ), }, ]; render() { const { users, onSort, sortColumn } = this.props; return ( <Table columns={this.columns} data={users} sortColumn={sortColumn} onSort={onSort} /> ); } } export default UsersTable; <file_sep>/src/App.js import React, { Component } from "react"; import Toolbar from "./Components/Toolbar/Toolbar"; import SideDrawer from "./Components/SideDrawer/sideDrawer"; import "./App.css"; import Content from "./Components/Content/content"; import { BrowserRouter as Router, Route, Switch, Redirect, } from "react-router-dom"; import LoginForm from "./Components/loginForm"; import RegisterForm from "./Components/registerForm"; import Users from "./Components/Content/Users/users"; import Posts from "./Components/Content/Posts/posts"; import NotFound from "./Components/notFound"; class App extends Component { state = { sideDrawerOpen: false, }; drawerTogglerClickHandler = () => { this.setState((prevState) => { return { sideDrawerOpen: !prevState.sideDrawerOpen }; }); }; handleBackDropClick = () => { this.setState({ sideDrawerOpen: !this.state.sideDrawerOpen }); }; render() { return ( <div className="App"> <Router> <Switch> <Route path="/register/:id" component={RegisterForm} /> <Route path="/login" component={LoginForm} /> <Route path="/not-found" component={NotFound} /> <Route exact path="/:content"> <Toolbar drawerClickHandler={this.drawerTogglerClickHandler} /> <SideDrawer show={this.state.sideDrawerOpen} /> <Content show={this.state.sideDrawerOpen} /> </Route> <Route path="/users" component={Users} /> <Route path="/posts" component={Posts} /> <Redirect from="/" exact to="/users" /> <Redirect to="/not-found" /> </Switch> </Router> </div> ); } } export default App;
0bc744f299b9bd0f2ca7ab9bbf463f210dc08507
[ "JavaScript" ]
5
JavaScript
Mudassirmh119/Admin-App
4ae168a00bf17ad5a7a399891e2150cc689ae017
490545defca888bc762866e9f3146a500d41e7ad
refs/heads/master
<repo_name>DicoMonteiro/automacao_test<file_sep>/WebSite_BDD/Tests/features/support/page_objects.rb require_relative '../pages/sections' module Pages def login LoginPage.new end def dash DashPage.new end def task TaskPage.new end end<file_sep>/WebSite_BDD/Tests/features/step_definitions/task_steps.rb #encoding:utf-8 #Logar Dado(/^usuario acessa pagina de tasks$/) do login.load login.with('will', 'will') dash.nav.create_menu.click dash.nav.task_menu.click sleep(10) end #Adicionar Dado(/^que eu tenho uma nova task para adicionar$/) do @tarefa = OpenStruct.new hour = %w[01 02 03 04 05 06 07 08 09 10 11 12] minute = %w[00 15 30 45] period = %w[am pm] priority = %w[High Medium Low] status = %w["#{Not} #{Started}" "#{In} #{Progress}" Completed "#{Pending} #{Input}" Deferred] related_to = %w[Account Contact Task Opportunity Bug Case Lead Project "#{Project} #{Task}" Target] @tarefa.name = Faker::Name.title @tarefa.start_date = '07/20/2017' @tarefa.start_hour = hour.sample @tarefa.start_minute = minute.sample @tarefa.start_period = period.sample @tarefa.due_date = '07/30/2017' @tarefa.due_hour = hour.sample @tarefa.due_minute = minute.sample @tarefa.due_period = period.sample @tarefa.priority = priority.sample @tarefa.status = status.sample @tarefa.related_to = related_to.sample if related_to.sample?('Account') @tarefa.related_to_compl = 'P Piper & Sons' elsif related_to.sample?('Contact') @tarefa.related_to_compl = '<NAME>' elsif related_to.sample?('Task') @tarefa.related_to_compl = 'Add to mailing list' elsif related_to.sample?('Opportunity') @tarefa.related_to_compl = 'Riviera Hotels - 1000 units' elsif related_to.sample?('Bug') @tarefa.related_to_compl = 'Broken image appears in home page' elsif related_to.sample?('Case') @tarefa.related_to_compl = 'Having trouble adding new items' elsif related_to.sample?('Lead') @tarefa.related_to_compl = '<NAME>' elsif related_to.sample?('Project') @tarefa.related_to_compl = 'Create new plan for the annual audit' elsif related_to.sample?('Project Task') @tarefa.related_to_compl = 'Create draft of the plan' elsif related_to.sample?('Target') @tarefa.related_to_compl = '<NAME>' end @tarefa.contact_name = '<NAME>' @tarefa.description = Faker::Lorem.characters(50) end Quando(/^faço o cadastro dessa task$/) do task.save(@tarefa) end Então(/^vejo a task cadastrada com sucesso$/) do expect(task.alert.text).to eql @tarefa.name end #Editar Dado(/^que eu tenho uma task para editar$/) do if task.alert.text.eql?(@tarefa.name) task.action.click task.edit.click hour = %w[01 02 03 04 05 06 07 08 09 10 11 12] minute = %w[00 15 30 45] period = %w[am pm] priority = %w[High Medium Low] status = %w["#{Not} #{Started}" "#{In} #{Progress}" Completed "#{Pending} #{Input}" Deferred] related_to = %w[Account Contact Task Opportunity Bug Case Lead Project "#{Project} #{Task}" Target] @tarefa.name = Faker::Name.title @tarefa.start_date = '07/20/2017' @tarefa.start_hour = hour.sample @tarefa.start_minute = minute.sample @tarefa.start_period = period.sample @tarefa.due_date = '07/30/2017' @tarefa.due_hour = hour.sample @tarefa.due_minute = minute.sample @tarefa.due_period = period.sample @tarefa.priority = priority.sample @tarefa.status = status.sample @tarefa.related_to = related_to.sample if related_to.sample?('Account') @tarefa.related_to_compl = 'P Piper & Sons' elsif related_to.sample?('Contact') @tarefa.related_to_compl = '<NAME>' elsif related_to.sample?('Task') @tarefa.related_to_compl = 'Add to mailing list' elsif related_to.sample?('Opportunity') @tarefa.related_to_compl = 'Riviera Hotels - 1000 units' elsif related_to.sample?('Bug') @tarefa.related_to_compl = 'Broken image appears in home page' elsif related_to.sample?('Case') @tarefa.related_to_compl = 'Having trouble adding new items' elsif related_to.sample?('Lead') @tarefa.related_to_compl = '<NAME>' elsif related_to.sample?('Project') @tarefa.related_to_compl = 'Create new plan for the annual audit' elsif related_to.sample?('Project Task') @tarefa.related_to_compl = 'Create draft of the plan' elsif related_to.sample?('Target') @tarefa.related_to_compl = '<NAME>' end @tarefa.contact_name = '<NAME>' @tarefa.description = Faker::Lorem.characters(50) end end Quando(/^faço a edição dessa task$/) do task.edit(@tarefa) end Então(/^vejo a task editada com sucesso$/) do expect(task.alert.text).to eql @tarefa.name end<file_sep>/WebService_API/Tests/features/support/hooks.rb Before '@api' do @tipo_contexto = 'application/json' @numero = Faker::Base.numerify("##") end <file_sep>/WebSite_BDD/Tests/features/support/hooks.rb After do |scenario| nome_cenario = scenario.name.gsub(/\s+/, '__').tr('/', '_') if scenario.failed? screenshot(nome_cenario.downcase!, 'falhou') else screenshot(nome_cenario.downcase!, 'passou') end end <file_sep>/WebSite_BDD/Tests/features/pages/dash.rb class DashPage < SitePrism::Page section :nav, Sections::NavBar, '.tablet-bar' element :view_text, '.hidden-xs' end<file_sep>/WebSite_BDD/Tests/features/pages/sections.rb module Sections class NavBar < SitePrism::Section element :create_menu, '#quickcreatetop a[data-toggle="dropdown"]' element :task_menu, 'a[href="index.php?module=Tasks&action=EditView&return_module=Tasks&return_action=DetailView"]' element :btn_menu, '#globalLinks button[id=usermenucollapsed]' element :logout_link, 'a[href="index.php?module=Users&action=Logout"]' def logout btn_menu.click logout_link.click end end end
1f61422d30a5cd6b9aee14abb2546c8d96cefd24
[ "Ruby" ]
6
Ruby
DicoMonteiro/automacao_test
d10ef6a0096ba2ea438b78b8912aaf277a4f3ecb
1e463d0ba65fef12f5ca61b156d42ad978b8e209
refs/heads/master
<file_sep>Data Journalism using D3 <a target='_blank' href="https://giphy.com/gifs/newspaper-press-v2xIous7mnEYg"><img alt='Newspaper Printing (via GIPHY)' src="http://i.giphy.com/v2xIous7mnEYg.gif" /> <br><em>via GIPHY</em></a> ## Background The Project visualizes correlation between data from U.S census Bureau and BRFSS ## Task 1. To find a correlation between two data variables, each measured state by state and taken from different data sources. 2. Visualize the correlation with a scatter plot and embed the graphic into an .html file. #### 1. Data 1. https://factfinder.census.gov/faces/nav/jsf/pages/searchresults.xhtml. 2. https://chronicdata.cdc.gov/Behavioral-Risk-Factors/BRFSS-2014-Overall/5ra3-ixqq. #### 2. Visualize the Data Using the D3 techniques, create a scatter plot that represents each state with circle elements. * The x-values of the circles is demographic census data, while the y-values represents the risk data. * State abbreviations in the circles. * Chek for correlation between data. Heroku App: https://datajournalism2017.herokuapp.com/ <file_sep>// D3 Scatterplot Assignment // Students: // ========= // Follow your written instructions and create a scatter plot with D3.js. function setOriginalAxisData(xAxisParam, yAxisParam){ console.log("X Axis: ", xAxisParam); console.log("Y Axis: ", yAxisParam); // Define SVG area dimensions var svgWidth = 800; var svgHeight = 600; // Define the chart's margins as an object var margin = { top: 60, right: 60, bottom: 100, left: 160 }; // Define dimensions of the chart area var chartWidth = svgWidth - margin.left - margin.right; var chartHeight = svgHeight - margin.top - margin.bottom; // Select body, append SVG area to it, and set its dimensions var svg = d3 .select("body") .append("svg") .attr("width", svgWidth) .attr("height", svgHeight) // Append a group area, then set its margins .append("g") .attr("transform", "translate(" + margin.left + ", " + margin.top + ")"); factorY = 1; yLabel1 = "Lacks Healthcare (%)"; yLabel2 = "Smokes (%)"; yLabel3 = "Obese (%)"; xLabel1 = "In Poverty (%)"; xLabel2 = "Age (Median)"; xLabel3 = "Household Income (Median)"; if(xAxisParam == "age"){ factorX = 1; }; if(xAxisParam == "poverty"){ factorX = 1; }; if(xAxisParam == "income"){ factorX = 1000; }; // Load data from forcepoints.csv d3.csv("/static/data.csv", function(error, csvData) { minX1 = d3.min(csvData, function(data) { data[xAxisParam] = parseFloat(data[xAxisParam]); return data[xAxisParam]; }) - (1*factorX) ; minY1 = d3.min(csvData, function(data) { data[yAxisParam] = parseFloat(data[yAxisParam]); return data[yAxisParam]; }) - (0.5*factorY); maxX1 = d3.max(csvData, function(data) { data[xAxisParam] = parseFloat(data[xAxisParam]); return data[xAxisParam]; }) + (1.5*factorX); maxY1 = d3.max(csvData, function(data) { data[yAxisParam] = parseFloat(data[yAxisParam]); return data[yAxisParam]; }) + (1*factorY) ; console.log("first:"+"minX:"+minX1+";maxX:"+maxX1+"minY:"+minY1+";maxY:"+maxY1); console.log("Testing3"); // Throw an error if one occurs if (error) throw error; // Print the csvData console.log(csvData); d3.selectAll("circle").remove(); // Format the date and cast the force value to a number csvData.forEach(function(data) { var node = d3.select("svg").append('g'); var xLoc = (chartWidth) - (chartWidth * (((((maxX1-minX1)) - (data[xAxisParam]-minX1) ))/(maxX1-minX1))) + margin.left; var yLoc = (chartHeight) - (chartHeight * 1/(maxY1-minY1) * (data[yAxisParam] - minY1) ) + margin.top var d = data; console.log(d.state); node .append("circle") .attr("class", "circle") .attr("cx", xLoc) .attr("cy", yLoc) .attr("r", 12) .style("fill", "lightblue" ) .append("title") .attr("text-anchor","middle") .text(data['state']+"\n"+'------------------'+"\n"+xAxisParam+": "+data[xAxisParam]+"\n"+yAxisParam+": "+data[yAxisParam]) node .append("text") .attr("text-anchor", "middle") .style("fill","white") .attr("x", xLoc) .attr("y", yLoc+5) .text(data.abbr) }); // Configure a linear scale with a range between 0 and the chartWidth var xLinearScale = d3.scaleLinear().range([0, chartWidth]); // Configure a linear scale with a range between the chartHeight and 0 var yLinearScale = d3.scaleLinear().range([chartHeight, 0]); // Set the domain for the xLinearScale function xLinearScale.domain([ minX1, maxX1]); // Set the domain for the xLinearScale function yLinearScale.domain([ minY1, maxY1 ]); // Create two new functions passing the scales in as arguments // These will be used to create the chart's axes var bottomAxis = d3.axisBottom(xLinearScale); var leftAxis = d3.axisLeft(yLinearScale); // Append an SVG group element to the SVG area, create the left axis inside of it svg.append("g") .attr("class", "y-axis") .call(leftAxis); // Append an SVG group element to the SVG area, create the bottom axis inside of it // Translate the bottom axis to the bottom of the page svg.append("g") .attr("class", "x-axis") .attr("transform", "translate(0, " + chartHeight + ")") .call(bottomAxis); svg .append("g") .attr("transform", "translate(0, " + chartHeight + ")") .append("text") .attr("text-anchor","middle") .attr("class", "healthcare") .attr("transform","rotate(-90)") .attr("x", svgHeight/3) .attr("y", -svgWidth/20) .style("font-weight", 'bold') .style("fill", 'blue') .on("click", function () { console.log("testing111"); setUpdatedAxisData(xAxisParam, "healthcare", svg); }) .text(yLabel1); svg .append("g") .attr("transform", "translate(0, " + chartHeight + ")") .append("text") .attr("text-anchor","middle") .attr("class", "smokes") .attr("transform","rotate(-90)") .attr("x", svgHeight/3) .attr("y", -(svgWidth/20 + (margin.left/8))) .style("font-weight", 'bold') .style("fill", 'black') .on("click", function () { console.log("testing222"); setUpdatedAxisData(xAxisParam, "smokes", svg); }) .text(yLabel2); svg .append("g") .attr("transform", "translate(0, " + chartHeight + ")") .append("text") .attr("text-anchor","middle") .attr("class", "obesity") .attr("transform","rotate(-90)") .attr("x", svgHeight/3) .attr("y", -(svgWidth/20 + (margin.left/4))) .style("font-weight", 'bold') .style("fill", 'black') .on("click", function () { console.log("testing333"); setUpdatedAxisData(xAxisParam, "obesity", svg); }) .text(yLabel3); svg .append("g") .attr("transform", "translate(" + chartWidth + ", 0)") .append("text") .attr("text-anchor","middle") .attr("class", "poverty") .attr("x", -svgWidth/3) .attr("y", chartHeight+margin.top-(margin.bottom/5)) .style("font-weight", 'bold') .style("fill", 'black') .on("click", function () { console.log("testing444"); setUpdatedAxisData("poverty", yAxisParam, svg); }) .text(xLabel1); svg .append("g") .attr("transform", "translate(" + chartWidth + ", 0)") .append("text") .attr("text-anchor","middle") .attr("class", "age") .attr("x", -svgWidth/3) .attr("y", chartHeight+margin.top) .style("font-weight", 'bold') .style("fill", 'black') .on("click", function () { console.log("testing555"); setUpdatedAxisData("age", yAxisParam, svg); }) .text(xLabel2); svg .append("g") .attr("transform", "translate(" + chartWidth + ", 0)") .append("text") .attr("text-anchor","middle") .attr("class", "income") .attr("x", -svgWidth/3) .attr("y", chartHeight+margin.top+(margin.bottom/5)) .style("font-weight", 'bold') .style("fill", 'blue') .on("click", function () { console.log("testing666"); setUpdatedAxisData("income", yAxisParam, svg); }) .text(xLabel3); }); }; function setUpdatedAxisData(xAxisParam, yAxisParam, svg){ console.log("X Axis: ", xAxisParam); console.log("Y Axis: ", yAxisParam); // Define SVG area dimensions var svgWidth = 800; var svgHeight = 600; // // Define the chart's margins as an object var margin = { top: 60, right: 60, bottom: 100, left: 160 }; // Define dimensions of the chart area var chartWidth = svgWidth - margin.left - margin.right; var chartHeight = svgHeight - margin.top - margin.bottom; factorY = 1; yLabel1 = "Lacks Healthcare (%)"; yLabel2 = "Smokes (%)"; yLabel3 = "Obese (%)"; xLabel1 = "In Poverty (%)"; xLabel2 = "Age (Median)"; xLabel3 = "Household Income (Median)"; if(xAxisParam == "age"){ factorX = 1; }; if(xAxisParam == "poverty"){ factorX = 1; }; if(xAxisParam == "income"){ factorX = 1000; }; // Load data from forcepoints.csv d3.csv("../static/data.csv", function(error, csvData) { minX1 = d3.min(csvData, function(data) { data[xAxisParam] = parseFloat(data[xAxisParam]); return data[xAxisParam]; }) - (1*factorX) ; minY1 = d3.min(csvData, function(data) { data[yAxisParam] = parseFloat(data[yAxisParam]); return data[yAxisParam]; }) - (0.5*factorY); maxX1 = d3.max(csvData, function(data) { data[xAxisParam] = parseFloat(data[xAxisParam]); return data[xAxisParam]; }) + (1.5*factorX); maxY1 = d3.max(csvData, function(data) { data[yAxisParam] = parseFloat(data[yAxisParam]); return data[yAxisParam]; }) + (1*factorY) ; console.log("first:"+"minX:"+minX1+";maxX:"+maxX1+"minY:"+minY1+";maxY:"+maxY1); console.log("Testing3"); // Throw an error if one occurs if (error) throw error; // Print the csvData console.log(csvData); d3.selectAll("circle").remove(); // Format the date and cast the force value to a number csvData.forEach(function(data) { var node = d3.select("svg").append('g'); var xLoc = (chartWidth) - (chartWidth * (((((maxX1-minX1)) - (data[xAxisParam]-minX1) ))/(maxX1-minX1))) + margin.left; var yLoc = (chartHeight) - (chartHeight * 1/(maxY1-minY1) * (data[yAxisParam] - minY1) ) + margin.top node .append("circle") .attr("class", "circle") .attr("cx", xLoc) .attr("cy", yLoc) .attr("r", 12) .style("fill", "lightblue" ) .append("title") .attr("text-anchor","middle") .text(data['state']+"\n"+'------------------'+"\n"+xAxisParam+": "+data[xAxisParam]+"\n"+yAxisParam+": "+data[yAxisParam]) node .append("text") .attr("text-anchor", "middle") .style("fill","white") .attr("x", xLoc) .attr("y", yLoc+5) .text(data.abbr) }); // Configure a linear scale with a range between 0 and the chartWidth var xLinearScale = d3.scaleLinear().range([0, chartWidth]); // Configure a linear scale with a range between the chartHeight and 0 var yLinearScale = d3.scaleLinear().range([chartHeight, 0]); // Set the domain for the xLinearScale function xLinearScale.domain([ minX1, maxX1]); // Set the domain for the xLinearScale function yLinearScale.domain([ minY1, maxY1 ]); // Create two new functions passing the scales in as arguments // These will be used to create the chart's axes var bottomAxis = d3.axisBottom(xLinearScale); var leftAxis = d3.axisLeft(yLinearScale); // Update y-axis svg.selectAll("g .y-axis") .call(leftAxis); // Update x-axis svg.selectAll("g .x-axis") .call(bottomAxis); svg .append("g") .attr("transform", "translate(0, " + chartHeight + ")") .append("text") .attr("text-anchor","middle") .attr("class", "healthcare") .attr("transform","rotate(-90)") .attr("x", svgHeight/3) .attr("y", -svgWidth/20) .style("font-weight", 'bold') .on("click", function () { console.log("testing111"); setUpdatedAxisData(xAxisParam, "healthcare", svg); }) .text(yLabel1); svg .append("g") .attr("transform", "translate(0, " + chartHeight + ")") .append("text") .attr("text-anchor","middle") .attr("class", "smokes") .attr("transform","rotate(-90)") .attr("x", svgHeight/3) .attr("y", -(svgWidth/20 + (margin.left/8))) .style("font-weight", 'bold') .on("click", function () { console.log("testing222"); setUpdatedAxisData(xAxisParam, "smokes", svg); }) .text(yLabel2); svg .append("g") .attr("transform", "translate(0, " + chartHeight + ")") .append("text") .attr("text-anchor","middle") .attr("class", "obesity") .attr("transform","rotate(-90)") .attr("x", svgHeight/3) .attr("y", -(svgWidth/20 + (margin.left/4))) .style("font-weight", 'bold') .on("click", function () { console.log("testing333"); setUpdatedAxisData(xAxisParam, "obesity", svg); }) .text(yLabel3); svg .append("g") .attr("transform", "translate(" + chartWidth + ", 0)") .append("text") .attr("text-anchor","middle") .attr("class", "poverty") .attr("x", -svgWidth/3) .attr("y", chartHeight+margin.top-(margin.bottom/5)) .style("font-weight", 'bold') .on("click", function () { console.log("testing444"); setUpdatedAxisData("poverty", yAxisParam, svg); }) .text(xLabel1); svg .append("g") .attr("transform", "translate(" + chartWidth + ", 0)") .append("text") .attr("text-anchor","middle") .attr("class", "age") .attr("x", -svgWidth/3) .attr("y", chartHeight+margin.top) .style("font-weight", 'bold') .on("click", function () { console.log("testing555"); setUpdatedAxisData("age", yAxisParam, svg); }) .text(xLabel2); svg .append("g") .attr("transform", "translate(" + chartWidth + ", 0)") .append("text") .attr("text-anchor","middle") .attr("class", "income") .attr("x", -svgWidth/3) .attr("y", chartHeight+margin.top+(margin.bottom/5)) .style("font-weight", 'bold') .on("click", function () { console.log("testing666"); setUpdatedAxisData("income", yAxisParam, svg); }) .text(xLabel3); d3.selectAll("."+xAxisParam).style("fill", "blue"); d3.selectAll("."+yAxisParam).style("fill", "blue"); }); }; setOriginalAxisData("income", "healthcare");
040bf51cdffcb2d27404634832e4b90b91923850
[ "Markdown", "JavaScript" ]
2
Markdown
AswathyMohan89/DataJournalism
f2a322df9be13ccc0c7a90af97d47b92c2f3d09f
51d8dd9bf5dbbe9819e68bbef6664b9783970463
refs/heads/master
<repo_name>SAP-Cloud-Platform-Integration/GroovyEnv<file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sap.ibso.cpi</groupId> <artifactId>groovyenv</artifactId> <version>1.0.0</version> <name>groovyenv</name> <description>SAP Cloud Integration Groovy Enviroment</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> <poi.version>3.17</poi.version> <groovy.version>2.5.6</groovy.version> <commons.version>1.3.2</commons.version> <lang.version>3.8.1</lang.version> <csv.version>1.1</csv.version> </properties> <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-csv</artifactId> <version>${csv.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${lang.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>${commons.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>${groovy.version}</version> <type>pom</type> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-core</artifactId> <version>2.20.4</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-cxf</artifactId> <version>2.20.4</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-jackson</artifactId> <version>2.20.3</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-groovy</artifactId> <version>2.22.3</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-spring</artifactId> <version>2.8.6</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-test</artifactId> <version>2.12.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-ftp</artifactId> <version>2.15.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-crypto</artifactId> <version>2.24.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.service.blueprint</artifactId> <version>1.0.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.sap.it.public.adapter</groupId> <artifactId>api</artifactId> <version>2.16.0</version> <systemPath>${project.basedir}/libs/com.sap.it.public.adapter.api-2.16.0.jar</systemPath> <scope>system</scope> </dependency> <dependency> <groupId>com.sap.it.public.generic</groupId> <artifactId>api</artifactId> <version>2.16.0</version> <systemPath>${project.basedir}/libs/com.sap.it.public.generic.api-2.16.0.jar</systemPath> <scope>system</scope> </dependency> <dependency> <groupId>cloud.integration.script</groupId> <artifactId>apis</artifactId> <version>1.36.1</version> <systemPath>${project.basedir}/libs/cloud.integration.script.apis-1.36.1.jar</systemPath> <scope>system</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.19.1</version> <configuration> <useSystemClassLoader>false</useSystemClassLoader> <argLine>-Dfile.encoding=UTF-8</argLine> <parallel>methods</parallel> <threadCount>8</threadCount> </configuration> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit47</artifactId> <version>2.19.1</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <groupId>org.codehaus.gmavenplus</groupId> <artifactId>gmavenplus-plugin</artifactId> <version>1.5</version> <executions> <execution> <goals> <goal>addSources</goal> <goal>addTestSources</goal> <goal>generateStubs</goal> <goal>compile</goal> <goal>testGenerateStubs</goal> <goal>testCompile</goal> <goal>removeStubs</goal> <goal>removeTestStubs</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <configuration> <excludeGroupIds>com.sap.it.public.adapter,com.sap.it.public.generic,cloud.integration.script,org.apache.commons,org.apache.camel</excludeGroupIds> <excludeScope>provided</excludeScope> <excludeTransitive>false</excludeTransitive> <stripVersion>true</stripVersion> </configuration> <executions> <execution> <id>copy-dependencies</id> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.6</version> <executions> <execution> <id>make-jar-with-dependencies</id> <phase>prepare-package</phase> <goals> <goal>single</goal> </goals> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <mainClass>com.sap.ibso.cpi.groovyenv.ProcessMessage</mainClass> </manifest> </archive> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.7</version> <configuration> <instrumentation> <excludes> <exclude>com/sap/ibso/cpi/groovyenv/*.class</exclude> <exclude>com/sap/ibso/cpi/groovyenv/testfield/*.class</exclude> <exclude>com/sap/ibso/cpi/groovyenv/libs/types/*.class</exclude> </excludes> </instrumentation> <formats> <format>html</format> <format>xml</format> </formats> <check /> </configuration> </plugin> </plugins> </build> </project><file_sep>/src/test/java/com/sap/ibso/cpi/groovyenv/libs/LibCryptTest.java package com.sap.ibso.cpi.groovyenv.libs; import static org.junit.Assert.*; import org.junit.Test; public class LibCryptTest { @Test public void testDecryptPGP() throws Exception { byte[] encrypted = TestHelper.readBytesFromResrouceFile("/pgp/encrypted_data"); byte[] plain = TestHelper.readBytesFromResrouceFile("/pgp/plain_data"); byte[] secretKey = TestHelper.readBytesFromResrouceFile("/pgp/PGPTestSecretKey.pgp"); byte[] result = LibCrypt.decryptPGP(encrypted, secretKey, "pgptestnew"); assertArrayEquals(plain, result); } @Test public void testEncryptPGP() throws Exception { byte[] plain = TestHelper.readBytesFromResrouceFile("/pgp/plain_data"); byte[] publicKey = TestHelper.readBytesFromResrouceFile("/pgp/PGPTestPublicKey.asc"); byte[] secretKey = TestHelper.readBytesFromResrouceFile("/pgp/PGPTestSecretKey.pgp"); byte[] encryptedResult = LibCrypt.encryptPGP(plain, "hello.txt", publicKey); byte[] decryptedResult = LibCrypt.decryptPGP(encryptedResult, secretKey, "pgptestnew"); assertArrayEquals(plain, decryptedResult); } } <file_sep>/src/test/java/com/sap/ibso/cpi/groovyenv/libs/TestHelper.java package com.sap.ibso.cpi.groovyenv.libs; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; public class TestHelper { public static String readStringFromResrouceFile(String path) throws IOException { InputStream is = TestHelper.class.getResourceAsStream(path); return IOUtils.toString(is, "UTF-8"); } public static byte[] readBytesFromResrouceFile(String path) throws IOException { InputStream is = TestHelper.class.getResourceAsStream(path); return IOUtils.toByteArray(is); } } <file_sep>/src/main/java/com/sap/ibso/cpi/groovyenv/libs/LibString.java package com.sap.ibso.cpi.groovyenv.libs; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; /** * reuse library for string * * @author <NAME> <<EMAIL>> * */ public class LibString { public static String base64Encode(byte[] input) { return Base64.encodeBase64String(input); } public static byte[] base64Decode(String base64Str) { return Base64.decodeBase64(base64Str); } public static String formatDate(Date d, String pattern) { return new SimpleDateFormat(pattern).format(d); } public static Date parseDate(String s, String pattern) throws ParseException { return new SimpleDateFormat(pattern).parse(s); } /** * generate md5 hash * * @param s * @return * @throws NoSuchAlgorithmException */ public static String md5(String s) throws NoSuchAlgorithmException { return new String(Hex.encodeHex(MessageDigest.getInstance("MD5").digest(s.getBytes()))); } public static byte[] concatBytes(byte[] a, byte[] b) { byte[] c = new byte[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } /** * decode url string * * %E4%BD%A0%E5%A5%BD -> 你好 * * @param s * @return * @throws UnsupportedEncodingException */ public static String urlDecode(String s) throws UnsupportedEncodingException { return java.net.URLDecoder.decode(s, "UTF-8"); } /** * encode url string * * 你好 -> %E4%BD%A0%E5%A5%BD * * @param s * @return * @throws UnsupportedEncodingException */ public static String urlEncode(String s) throws UnsupportedEncodingException { return java.net.URLEncoder.encode(s, "UTF-8"); } } <file_sep>/src/main/java/com/sap/ibso/cpi/groovyenv/libs/types/ParsedZipFile.java package com.sap.ibso.cpi.groovyenv.libs.types; import java.util.HashMap; public class ParsedZipFile extends HashMap<String, byte[]> { private static final long serialVersionUID = 2898368779779816187L; } <file_sep>/src/test/java/com/sap/ibso/cpi/groovyenv/libs/LibPOITest.java package com.sap.ibso.cpi.groovyenv.libs; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Workbook; import org.junit.Test; public class LibPOITest { @Test public void testExtractExcelToPlainObject() throws IOException, EncryptedDocumentException, InvalidFormatException { InputStream is = this.getClass().getResourceAsStream("/POITestBase64.txt"); String base64 = IOUtils.toString(is, "UTF-8"); Workbook wb = LibPOI.readExcelFromBase64(base64); assertTrue(LibPOI.extractExcelToPlainObject(wb).containsKey("DemoSheet2")); } @Test public void testReadExcelFromBase64() throws IOException, EncryptedDocumentException, InvalidFormatException { InputStream is = this.getClass().getResourceAsStream("/POITestBase64.txt"); String base64 = IOUtils.toString(is, "UTF-8"); Workbook wb = LibPOI.readExcelFromBase64(base64); assertEquals(wb.getSheetAt(1).getSheetName(), "DemoSheet2"); } } <file_sep>/README.md # SAP Cloud Integration Groovy Environment [![CircleCI](https://circleci.com/gh/SAP-Cloud-Platform-Integration/GroovyEnv.svg?style=shield)](https://circleci.com/gh/SAP-Cloud-Platform-Integration/GroovyEnv) [![codecov](https://codecov.io/gh/SAP-Cloud-Platform-Integration/GroovyEnv/branch/master/graph/badge.svg)](https://codecov.io/gh/SAP-Cloud-Platform-Integration/GroovyEnv) [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=SAP-Cloud-Platform-Integration_GroovyEnv&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=SAP-Cloud-Platform-Integration_GroovyEnv) [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=SAP-Cloud-Platform-Integration_GroovyEnv&metric=security_rating)](https://sonarcloud.io/dashboard?id=SAP-Cloud-Platform-Integration_GroovyEnv) [![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=SAP-Cloud-Platform-Integration_GroovyEnv&metric=vulnerabilities)](https://sonarcloud.io/dashboard?id=SAP-Cloud-Platform-Integration_GroovyEnv) [![Bugs](https://sonarcloud.io/api/project_badges/measure?project=SAP-Cloud-Platform-Integration_GroovyEnv&metric=bugs)](https://sonarcloud.io/dashboard?id=SAP-Cloud-Platform-Integration_GroovyEnv) [![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=SAP-Cloud-Platform-Integration_GroovyEnv&metric=code_smells)](https://sonarcloud.io/dashboard?id=SAP-Cloud-Platform-Integration_GroovyEnv) ## Comments Please use this project only for **very very complex** integration scenario. e.g. * Parse MS excel file & format it into PDF binary. * Parse complex XML from different node with complex logic. * Private authorization method with private encryption algorithm. * Private data format. ## Dependency * Eclipse with [Groovy Development Tools](https://marketplace.eclipse.org/content/groovy-development-tools) (**Please install this plugin before import this project**) ## Target * provide an environment to development groovy script on CPI * this envrionment imported CPI related APIs, and support import external java dependencies by maven * development groovy with rich `maven` libraries, will generated a jar package ## How to use * Clone import this project as maven project. * Develop complex logic in java language. * Invoke java API in `ProcessMessage.groovy`. * [optional] Test with JUnit 4. * Run `maven clean package`. * Upload `target/groovyenv-1.0.0-jar-with-dependencies.jar` to CPI integration flow archive. * Use `Script` component in integration flow and replace content with `ProcessMessage.groovy` ## Advantages * All `maven` libraries support. * Pre-defined build & test logic. * Pre-defined CI configuration. * Pre-defined general CPI API wrapper. * Support code intelligent for groovy. ### With type in java/groovy ![](https://res.cloudinary.com/digf90pwi/image/upload/v1558418907/2019-05-21_14-02-22_banwo2.png) ### Unit test avalible and debug ![](https://res.cloudinary.com/digf90pwi/image/upload/v1558418952/%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_20190521140900_hglwj8.png) ## Roadmap * [ ] Platform APIs document. * [ ] Generate integration flow package directly. * [ ] Deploy to CPI directly. (maybe need plugin support) ## Careful * **Avoid** using groovy to develop new features, because the groovy version used by CPI is `2.2.1`, but the current eclipse and maven plugins only support groovy `2.4` and above. * The CPI integration process package size cannot exceed `40 MB` (maybe, but the size limitation existed). <file_sep>/src/main/java/com/sap/ibso/cpi/groovyenv/libs/LibXMLs.java package com.sap.ibso.cpi.groovyenv.libs; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import groovy.util.Node; import groovy.util.NodeList; import groovy.util.XmlParser; import groovy.xml.QName; public class LibXMLs { /** * find one string by tag name * * <p> * please give the inner tag name for get the correct pure string * <p> * * @param n * Xml Node * @param tNodeName * target Node Name * @return tag inner text, empty when not found, object.toString if not the most * deep-in node name */ public static String findOneStringByTagName(Node n, String tNodeName) { StringBuilder sb = new StringBuilder(); Node findedNode = findOneNodeByTagName(n, tNodeName); if (findedNode != null) { NodeList value = (NodeList) findedNode.value(); if (value.size() == 1) { sb.append(value.get(0).toString()); } else { sb.append(value.toString()); } } return sb.toString(); } public static Node findOneNodeByTagName(Node n, String tNodeName) { for (Object aNode : n.depthFirst()) { if (aNode instanceof Node) { Object cNodeName = ((Node) aNode).name(); if (cNodeName != null) { if (cNodeName instanceof QName) { if (((QName) cNodeName).getLocalPart().equals(tNodeName)) { return (Node) aNode; } } else if (cNodeName instanceof String) { if (cNodeName.equals(tNodeName)) { return (Node) aNode; } } } } } return null; } public static Node parseXml(String xml) throws IOException, SAXException, ParserConfigurationException { return new XmlParser().parseText(xml); } /** * stringify xml node to xml text * * @param node * @return */ public static String stringifyXml(Node node) { return groovy.xml.XmlUtil.serialize(node).replaceAll("/<.xml.*?>/", ""); } } <file_sep>/src/test/java/com/sap/ibso/cpi/groovyenv/libs/LibXMLTest.java package com.sap.ibso.cpi.groovyenv.libs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.xml.sax.SAXException; import groovy.util.Node; public class LibXMLTest { @Test public void testFindOneByNodeName() throws IOException, SAXException, ParserConfigurationException { Node n = LibXMLs.parseXml(IOUtils.toString(this.getClass().getResourceAsStream("/XMLParseTest.xml"), "UTF-8")); String v = LibXMLs.findOneStringByTagName(n, "TermsFile"); assertEquals("TestText", v); v = LibXMLs.findOneStringByTagName(n, "item"); assertNotNull(v); } }
a2f511151bdcfc2f240aba138d824dbc5986b571
[ "Markdown", "Java", "Maven POM" ]
9
Maven POM
SAP-Cloud-Platform-Integration/GroovyEnv
da8d1915e6fe587559731625f5c9c9aa612bd557
c15316bcfff8b548edc92f3e219e7230c6d6eca8
refs/heads/master
<file_sep># !/usr/bin/env python3 import operator, sys, math def get_number(num): return float(num) def do_clear(stack): return [] def do_drop(stack): stack.pop(0) return stack def do_exit(stack): exit() def do_sum(stack): return [sum(stack)] def do_tva(stack): stack.insert(0, stack[0]*0.20) return stack def do_plus(stack): stack.insert(0, stack.pop(0) + stack.pop(0)) return stack def do_minus(stack): stack.insert(0, stack.pop(0) - stack.pop(0)) return stack def do_multi(stack): stack.insert(0, stack.pop(0) * stack.pop(0)) return stack def do_power(stack): stack.insert(0, stack.pop(0) ** stack.pop(0)) return stack def do_modulo(stack): stack.insert(0, stack.pop(0) % stack.pop(0)) return stack def do_squareroot(stack): if stack[0] < 0: print("we do not support complex numbers") else: stack.insert(0, math.sqrt(stack.pop(0))) return stack def do_divi(stack): if stack[1] == 0: print("impossible") else: stack.insert(0, stack.pop(0) / stack.pop(0)) return stack def do_swap(stack): stack.insert(0, stack.pop(1)) return stack def do_duplicate(stack): stack.insert(0, stack[0]) return stack def do_help(stack): for k,v in FUNCTIONS.iteritems(): print(" {} : {}".format(k,v["description"])) return stack ALIAS = { 'c': 'clear', 'd': 'drop', 'q': 'exit', 's': 'swap', 'h': 'help', 'tva': 'vat', 'dup': 'duplicate', 'sqrt': 'squareroot' } FUNCTIONS = { '+': {"card": 2, "func": do_plus, "description": "add the first two numbers of the list"}, '-': {"card": 2, "func": do_minus, "description": "substract the first two numbers of the list"}, '*': {"card": 2, "func": do_multi, "description": "multiply the first two numbers of the list"}, '/': {"card": 2, "func": do_divi, "description": "divise the first two numbers of the list"}, '**': {"card": 2, "func": do_power, "description": "power tool"}, '%': {"card": 2, "func": do_modulo, "description": "modulo tool"}, 'clear': {"card": 0, "func": do_clear, "description": "clear the list"}, 'sum': {"card": 2, "func": do_sum, "description": "add all the numbers of the list"}, 'exit': {"card": 0, "func": do_exit, "description": "exit the calculator"}, 'swap': {"card": 2, "func": do_swap, "description": "swap the first two numbers of the list"}, 'drop': {"card": 1, "func": do_drop, "description": "drop the first number of the list"}, 'help': {"card": 0, "func": do_help, "description": "print the 'help' informations"}, 'vat': {"card": 1, "func": do_tva, "description": "calculate the VAT of the first number of the list (20%)"}, 'duplicate': {"card": 1, "func": do_duplicate, "description": "duplicate the first number of the list"}, 'squareroot': {"card": 1, "func": do_squareroot, "description": "does the squareroot of the first number of the list"} } def rpn_loop(): l = [] while True: a = raw_input() if a in ALIAS: a = ALIAS[a] try: l.insert(0, get_number(a)) except: if not a in FUNCTIONS: print("unknown function") continue if len(l) >= FUNCTIONS[a]["card"]: l = FUNCTIONS[a]["func"](l) else: print("not enough elements") print(l) if __name__ == '__main__': print("**/RPyN\**") print("Welcome user ! Type 'help' for more informations") print("") rpn_loop()
f26edd5479fa0104bb0ce307d966b9be86bdbfc3
[ "Python" ]
1
Python
hugonator/rpyn
cde4328ae8fbd0a7445d31e474aaa40df3c19e64
1513d38ba50b3e6da4d4e509a26ae9280c986bcf
refs/heads/master
<file_sep>var users = require('./../controllers/users'); var path = require('path') module.exports = function(app){ app.post('/login', function(req, res){ users.login(req, res) }) app.get('/sess', function(req, res){ users.checksess(req, res); }) app.get('/logout', function(req, res){ users.logout(req, res); }) app.post('/addquestion', function(req, res){ users.addquestion(req, res); }) app.get('/getall', function(req, res){ users.getall(req, res); }) app.get('/getonequestion/:id', function(req, res){ users.getonequestion(req, res) }) app.get('/remove/:id', function(req, res){ users.deletequestion(req, res); }) app.get('/like1/:id', function(req, res){ users.likeanswer1(req, res) }) app.get('/like2/:id', function(req, res){ users.likeanswer2(req, res) }) app.get('/like3/:id', function(req, res){ users.likeanswer3(req, res) }) app.all('**', (req, res) => {res.sendFile(path.resolve('./client/dist/index.html'))}) }<file_sep>var mongoose = require('mongoose'); var Schema = mongoose.Schema; var QuestionSchema = new Schema({ user: {type: Schema.Types.ObjectId, ref: 'User'}, person: String, question: String, option1: String, option2: String, option3: String, likeoption1: {type: Number, default: 0}, likeoption2: {type: Number, default: 0}, likeoption3: {type: Number, default: 0}, }, {timestamps: true}) mongoose.model('Question', QuestionSchema);<file_sep>var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema({ name: String, questions: [{type: Schema.Types.ObjectId, ref: "Question"}] }) mongoose.model('User', UserSchema)<file_sep>var mongoose = require('mongoose') var User = mongoose.model('User') var Question = mongoose.model('Question') module.exports = { login:function(req, res){ User.find({name: req.body.name}, function(err, users){ if(users.length < 1){ User.create({name: req.body.name}, function(err, user){ req.session.user = user req.session.save() res.json({user: user}) }) } else{ req.session.user = users[0]; req.session.save() res.json({user: users[0]}) } }) }, checksess:function(req, res){ if(req.session.user == undefined){ res.json({user: null}) } else{ res.json({user: req.session.user}) } }, addquestion:function(req, res){ Question.findOne({question: req.body.question, option1: req.body.option1, option2: req.body.option2, option3: req.body.option3}, function(err, questionFound){ if(!questionFound){ Question.create({user: req.session.user, person: req.session.user.name, question:req.body.question, option1: req.body.option1, option2: req.body.option2, option3: req.body.option3}, function(err,questionMade){ console.log(questionMade) return res.json(questionMade) }) } else{ return res.json(questionFound)} }) }, getall:function(req, res){ Question.find({}, function(err, questions){ res.json(questions) }) }, // .populate('comments').exec getonequestion:function(req, res){ Question.findOne({_id: req.params.id}, function(err, questionfound){ res.json(questionfound) }) }, likeanswer1:function(req, res){ Question.findOne({_id: req.params.id}, function(err, question){ question.likeoption1 += 1; question.save() res.redirect('/poll/'+ req.params.id) }) }, likeanswer2:function(req, res){ Question.findOne({_id: req.params.id}, function(err, question){ question.likeoption2 += 1; question.save() res.redirect('/poll/'+ req.params.id) }) }, likeanswer3:function(req, res){ Question.findOne({_id: req.params.id}, function(err, question){ question.likeoption3 += 1; question.save() res.redirect('/poll/'+ req.params.id) }) }, deletequestion:function(req, res){ Question.findOne({_id: req.params.id}, function(err, question){ question.remove() }) res.redirect('/home') }, logout: (req, res) => { req.session.destroy(); res.redirect('/') } }
3f62e80560fc65444bf33e8f7278b1247c5e4265
[ "JavaScript" ]
4
JavaScript
kerby024/finalexam
68d0eaeb8e867d0783e5ed1c8501ab466555cce4
e07274e256f3a5f69dda493e7d99292b3e35f876
refs/heads/master
<repo_name>juniorMatt/Page-Sizer<file_sep>/src/pl/edu/utp/Measurement.java package pl.edu.utp; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import javax.swing.JOptionPane; public class Measurement { static long startTime; static long endTime; static long timeElapsed; public static HttpURLConnection conn; static String field; public static String getField() { return field; } public void pageSize() throws MalformedURLException, IOException { // metoda pobierająca rozmiar strony field = Frame.textFieldURL.getText(); if(field.isEmpty()) { JOptionPane.showMessageDialog(null,"Wprowadz adres strony !"); } conn = (HttpURLConnection) new URL(field).openConnection(); int pom = conn.getContentLength(); System.out.println(pom); if(pom >= 0) { JOptionPane.showMessageDialog(null,"Waga strony : "+ pom/1024+" KB"); } else { } } /* * Metody odpowiedzalne za pomiar czasu */ public void startTiming() { startTime = System.nanoTime(); } public void endTiming() { endTime = System.nanoTime(); } public void differenceTime() { timeElapsed = endTime - startTime; System.err.println("Execution time in nanoseconds : " + timeElapsed); JOptionPane.showMessageDialog(null,"Czas pomiaru : "+ timeElapsed/1000000 +" ms"); } }<file_sep>/README.md # Page-Sizer own project - measuring web page
f04e822a159b1ff00aae2c9ed2b82675a90e1cd8
[ "Markdown", "Java" ]
2
Java
juniorMatt/Page-Sizer
f854db0f4f781630c8bf674d87c734a894480964
7e711c399f37e928a55645a2cf1a1d5033c4562c
refs/heads/master
<file_sep>var weatherUrl = "http://api.openweathermap.org/data/2.5/weather"; var apiKey = "&appid=<KEY>"; var coords = { latitude: 0, longitude: 0 }; var db = new Dexie("history_database"); db.version(1).stores({ history: 'lat,long' }); var selectedOption = ""; function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) } function convertUnix (unix_timestamp) { var date = new Date(unix_timestamp*1000); // Hours part from the timestamp var hours = date.getHours(); // Minutes part from the timestamp var minutes = "0" + date.getMinutes(); // Seconds part from the timestamp var seconds = "0" + date.getSeconds(); var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2); return formattedTime; } function loadCards (URL) { $.get(URL, function (response) { coords.latitude = parseFloat(response.coord.lat); coords.longitude = parseFloat(response.coord.lon); var clone = $(".template1").clone(); clone.find(".location").text(response.name + ", " + response.sys.country); var fahrenheit = ((parseFloat(response.main.temp)-273.15)*1.8)+32; var celcius = (parseFloat(response.main.temp))-273.15; clone.find(".currTemp").text(Math.round(fahrenheit) + "°F | " + Math.round(celcius) + "°C"); clone.find(".weatherConditions").text(response.weather[0].description); fahrenheit = ((parseFloat(response.main.temp_max)-273.15)*1.8)+32; celcius = (parseFloat(response.main.temp_max))-273.15; clone.find(".maxTemp").text("High: " + Math.round(fahrenheit) + "°F | " + Math.round(celcius) + "°C") fahrenheit = ((parseFloat(response.main.temp_min)-273.15)*1.8)+32; celcius = (parseFloat(response.main.temp_min))-273.15; clone.find(".minTemp").text("Low: " + Math.round(fahrenheit) + "°F | " + Math.round(celcius) + "°C"); clone.find(".pressure").text("Pressure: " + response.main.pressure + " hpa"); clone.find(".sunRise").text("Sunrise: " + convertUnix(response.sys.sunrise)); var wind = parseFloat(response.wind.speed); clone.find(".windSpeed").text("Wind: " + Math.round(wind*2.237) + " mph" ); clone.find(".sunSet").text("Sunset: " + convertUnix(response.sys.sunset)); clone.removeClass("template1"); $(".homeInfoWeather").append(clone); var centerlocation = {lat: parseFloat(coords.latitude), lng: parseFloat(coords.longitude)}; var map = new google.maps.Map(document.getElementById('hideMap'), {zoom: 11, center: centerlocation}); var placesCoord = new google.maps.LatLng(parseFloat(coords.latitude),parseFloat(coords.longitude)); selectedOption = $(".mdc-select__native-control").val(); var request = { location: placesCoord, radius: '500', type: selectedOption }; var service = new google.maps.places.PlacesService(map); service.textSearch(request, callback); function callback(results, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { for (var i = 1; i < results.length; i++) { console.log(results[i]); var clone = $(".template3").clone(); clone.find("#placeName").text(results[i].name); clone.find("#address").text("Address: " + results[i].formatted_address); clone.removeClass("template3"); $(".homeInfoPlace").append(clone); } } } }); } $(document).ready(function() { window.mdc.autoInit(); $("#content").load("home.html"); const drawer = $("aside")[0].MDCDrawer; $(".mdc-top-app-bar__navigation-icon").on("click", function(){ drawer.open = true; }); // close the drawer and load the selected screen $("body").on("click", ".mdc-list-item", function (event) { drawer.open = false; $("#content").load($(this).attr("data-screen")); }); $(document).on('click','#searchButton',function(){ input = document.getElementById("inputInfo").value; if (isNumber(input) == true) { var endpoint = weatherUrl + "?zip=" + input + apiKey; } else { var endpoint = weatherUrl + "?q=" + input + apiKey; } loadCards(endpoint); db.history.put({lat: coords.latitude, long: coords.longitude }); }); if ('geolocation' in navigator) { $(document).on('click','#geoButton',function(){ navigator.geolocation.getCurrentPosition(function (location) { var endpoint = weatherUrl + "?lat=" + location.coords.latitude + "&lon=" + location.coords.longitude + apiKey; loadCards(endpoint); db.history.put({lat: coords.latitude, long: coords.longitude }); }); }); } else { target.innerText = 'Geolocation API not supported.'; } });
189b21022bec8f29b070359c35c616a52b4b8b95
[ "JavaScript" ]
1
JavaScript
jli263/it202-big
917305fb81da8d951d0f06be5b8b090e9442e995
b5be9e31ef370f637aa2e42b2be54b8636e023b0
refs/heads/master
<repo_name>craigderington/digital-dispatch<file_sep>/lynx_config.py #! config.py DEBUG = True host = 'localhost' username = '' password = '' database = '' db_port = 3306 PORT = 5555 url = 'https://portal.owlsite.net/api/' tdh = 'tankdata/' tank = 'tanks/' loginusername = '' loginpassword = '' Token = '' tank_id = 1315 file_path = 'data/frontend_tankdatahistory_7026.csv' <file_sep>/tests.py #! .env/bin/python import config import requests from requests.auth import HTTPBasicAuth import json payload = { "network_id": "ORLFL01_7077", "service_address": 1312, "receiver_time": "2017-01-04 13:16:17", "sensor_value": "38.39" } try: s = requests.Session() s.auth = (config.loginusername, config.loginpassword) s.headers.update({'x-test': 'true', 'X-CSRFToken': config.Token}) r = s.get('http://localhost:5880/api-auth/login/', auth=HTTPBasicAuth(username=config.loginusername, password=<PASSWORD>), headers=s.headers) # Interact with the API. tank_id = config.tank_id response = requests.put('http://localhost:5880/api/tanks/' + str(tank_id) + '/', auth=HTTPBasicAuth(username=config.loginusername, password=<PASSWORD>), headers={'X-CSRFToken': config.Token}, data=payload) if response.status_code == 200: print(response.content) else: print(response.content) except requests.HTTPError as e: print 'HTTPError' <file_sep>/README.md # digital-dispatch Digital Dispatch OWL Demo Script This console app will attempt to automate the submission of test data for the Digital Dispatch OWL demo trial. The app reads a CSV data file, gets the first row, builds a dictionary from the CSV data, json encodes the data and sets up requests to send a POST and PUT request to the following endpoints: * [POST] https://portal.owlsite.net/api/tankdata * [PUT] https://portal.owlsite.net/api/tanks/1279 The POST request submits data to frontend_tankdatahistory The PUT request updates the individual tank with the most recent receiver time, sensor value and network ID. <file_sep>/app.py #! .env/bin/python import os import sys import csv import json import requests from requests.auth import HTTPBasicAuth from datetime import datetime import config def main(): """ Digital Dispatch OWL Demo Trial Send a POST and PUT request to the OWL API for tank_id 1279 - Digital Dispatch :param: none :type: main() console app :return: json """ # the tank ID tank_id = config.tank_id # first, open the data file and read the first line with open(config.file_path, 'r') as f: try: reader = csv.reader(f) next(f) row = next(reader) payload = { 'tank': row[1], 'network_id': row[2], 'mtu_id': row[2].split('_')[1:], 'receiver_time': str(datetime.now()), 'sensor_value': row[4], 'service_address': 1312 } hdr = { "Content-Type": "application/json", "Accept": "application/json", "X-CSRFToken": config.Token } url_1 = 'https://portal.owlsite.net/api/tankdata/' url_2 = 'https://portal.owlsite.net/api/tanks/' + str(tank_id) + '/' auth = HTTPBasicAuth(config.loginusername, config.loginpassword) try: # post the data to tank data history r1 = requests.post(url_1, headers=hdr, auth=auth, json=payload) if r1.status_code == 201: print('SUCCESS! ' + r1.content) # update the tank with the latest sensor value r2 = requests.put(url_2, headers=hdr, auth=auth, json=payload) if r2.status_code == 200: print('SUCCESS! ' + r2.content) # open the file and write out the remaining rows try: with open(config.file_path, 'w') as f1: writer = csv.writer(f1) writer.writerows(reader) except csv.Error as e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) else: print('FAIL R2: HTTP returned a ' + str(r2.status_code) + ' status code.') else: print('FAIL R1: HTTP returned a ' + str(r1.status_code) + ' status code.') except requests.HTTPError as e: print('Sorry, a communication error has occurred ' + str(e)) except csv.Error as e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) if __name__ == '__main__': main()
199cd76d24db871a0b19867e1442ac680ddce605
[ "Markdown", "Python" ]
4
Python
craigderington/digital-dispatch
855ecd9596833f52045b99e421fa670d6f29b0aa
30db455878badf1b36865054c790f1dad3cee77c
refs/heads/master
<repo_name>ColinHarrington/sitemesh2<file_sep>/src/java/com/opensymphony/module/sitemesh/multipass/MultipassReplacementPageParser.java package com.opensymphony.module.sitemesh.multipass; import com.opensymphony.module.sitemesh.PageParser; import com.opensymphony.module.sitemesh.Page; import com.opensymphony.module.sitemesh.html.util.CharArray; import com.opensymphony.module.sitemesh.html.HTMLProcessor; import com.opensymphony.module.sitemesh.html.BasicRule; import com.opensymphony.module.sitemesh.html.Tag; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class MultipassReplacementPageParser implements PageParser { private final Page page; private final HttpServletResponse response; public MultipassReplacementPageParser(Page page, HttpServletResponse response) { this.page = page; this.response = response; } public Page parse(char[] data, int length) throws IOException { if (data.length > length) { // todo fix this parser so that it doesn't need to compact the array char[] newData = new char[length]; System.arraycopy(data, 0, newData, 0, length); data = newData; } return parse(data); } public Page parse(char[] data) throws IOException { final CharArray result = new CharArray(4096); HTMLProcessor processor = new HTMLProcessor(data, result); processor.addRule(new BasicRule("sitemesh:multipass") { public void process(Tag tag) { String id = tag.getAttributeValue("id", true); if (!page.isPropertySet("_sitemesh.removefrompage." + id)) { currentBuffer().append(page.getProperty(id)); } } }); processor.process(); result.writeTo(response.getWriter()); return null; } } <file_sep>/src/java/com/opensymphony/module/sitemesh/parser/SuperFastHtmlPage.java package com.opensymphony.module.sitemesh.parser; import com.opensymphony.module.sitemesh.HTMLPage; import java.io.IOException; import java.io.Writer; import java.util.Map; public class SuperFastHtmlPage extends SuperFastPage implements HTMLPage { private final char[] head; public SuperFastHtmlPage(char[] pageData, int pageLength, int bodyStart, int bodyLength, char[] head, String title, Map<String, String> metaAttributes) { super(pageData, pageLength, bodyStart, bodyLength); this.head = head; if (title != null) { addProperty("title", title); } for (Map.Entry<String, String> attribute : metaAttributes.entrySet()) { addProperty("meta." + attribute.getKey(), attribute.getValue()); } } public void writeHead(Writer out) throws IOException { out.write(head); } public String getHead() { return new String(head); } public boolean isFrameSet() { return false; } public void setFrameSet(boolean frameset) { throw new UnsupportedOperationException(); } } <file_sep>/src/java/com/opensymphony/module/sitemesh/parser/SuperFastSimplePageParser.java package com.opensymphony.module.sitemesh.parser; import java.io.CharArrayWriter; import java.io.IOException; import java.nio.CharBuffer; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.opensymphony.module.sitemesh.Page; import com.opensymphony.module.sitemesh.PageParser; /** * Super fast page parser. It uses a single buffer, and never copies anything, apart from the title, meta attributes * and body properties. This page parser makes several assumptions: * <p/> * <ul> <li>If the first tag is an html tag, it's an HTML page, otherwise, it's a fragment, and no head/title/etc * parsing will be done.</li> * </ul> * * @since v2.4 */ public class SuperFastSimplePageParser implements PageParser { private static final Pattern META_PATTERN = Pattern.compile( "<meta\\s+([\\w-]+)=[\"']([^\"']*)[\"']\\s+([\\w-]+)=[\"']([^\"']*)[\"']\\s*/?>", Pattern.CASE_INSENSITIVE); public Page parse(final char[] data) throws IOException { return parse(data, data.length); } public Page parse(final char[] data, final int length) throws IOException { int position = 0; while (position < data.length) { if (data[position++] == '<') { if (position < data.length && data[position] == '!') { // Ignore doctype continue; } if (compareLowerCase(data, length, position, "html")) { // It's an HTML page, handle HTML pages return parseHtmlPage(data, length, position); } else { // The whole thing is the body. return new SuperFastPage(data, length, 0, length); } } } // If we're here, we mustn't have found a tag return new SuperFastPage(data, length, 0, length); } private Page parseHtmlPage(final char[] data, final int length, int position) { int bodyStart = -1; int bodyLength = -1; int headStart = -1; int headLength = -1; // Find head end and start, and body start while (position < length) { if (data[position++] == '<') { if (compareLowerCase(data, length, position, "head")) { position = findEndOf(data, length, position + 4, ">"); headStart = position; // Find end of head position = findStartOf(data, length, position, "</head>"); headLength = position - headStart; position += 7; } else if (compareLowerCase(data, length, position, "body")) { bodyStart = findEndOf(data, length, position + 4, ">"); break; } } } if (bodyStart < 0) { // No body found bodyStart = length; bodyLength = 0; } else { for (int i = length - 8; i > bodyStart; i--) { if (compareLowerCase(data, length, i, "</body>")) { bodyLength = i - bodyStart; break; } } if (bodyLength == -1) { bodyLength = length - bodyStart; } } if (headLength > 0) { String title = null; // Extract title and meta properties. This should be a small amount of data, so regexs are fine CharBuffer buffer = CharBuffer.wrap(data, headStart, headLength); Matcher matcher = META_PATTERN.matcher(buffer); Map<String, String> metaAttributes = new HashMap<String, String>(); while (matcher.find()) { if (matcher.group(1).equals("content")) { metaAttributes.put(matcher.group(4), matcher.group(2)); } else { metaAttributes.put(matcher.group(2), matcher.group(4)); } } // We need a new head buffer because we have to remove the title from it CharArrayWriter head = new CharArrayWriter(); for (int i = headStart; i < headStart + headLength; i++) { char c = data[i]; if (c == '<') { if (compareLowerCase(data, headLength, i + 1, "title")) { int titleStart = findEndOf(data, headLength, i + 6, ">"); int titleEnd = findStartOf(data, headLength, titleStart, "<"); title = new String(data, titleStart, titleEnd - titleStart); i = titleEnd + "</title>".length() - 1; } else { head.append(c); } } else { head.append(c); } } return new SuperFastHtmlPage(data, length, bodyStart, bodyLength, head.toCharArray(), title, metaAttributes); } else { return new SuperFastPage(data, length, bodyStart, bodyLength); } } private static boolean compareLowerCase(final char[] data, final int length, int position, String token) { int l = position + token.length(); if (l > length) { return false; } for (int i = 0; i < token.length(); i++) { // | 32 converts from ASCII uppercase to ASCII lowercase char potential = data[position + i]; char needed = token.charAt(i); if ((Character.isLetter(potential) && (potential | 32) != needed) || potential != needed) { return false; } } return true; } private static int findEndOf(final char[] data, final int length, int position, String token) { for (int i = position; i < length - token.length(); i++) { if (compareLowerCase(data, length, i, token)) { return i + token.length(); } } return length; } private static int findStartOf(final char[] data, final int length, int position, String token) { for (int i = position; i < length - token.length(); i++) { if (compareLowerCase(data, length, i, token)) { return i; } } return length; } } <file_sep>/src/java/com/opensymphony/module/sitemesh/filter/BufferedContent.java package com.opensymphony.module.sitemesh.filter; public class BufferedContent { private final char[] buffer; private final int length; public BufferedContent(char[] buffer) { this.buffer = buffer; this.length = buffer.length; } public BufferedContent(char[] buffer, int length) { this.buffer = buffer; this.length = length; } public char[] getBuffer() { return buffer; } public int getLength() { return length; } }
3ae9bed548f324cba5682bd3975e418d4f714c4e
[ "Java" ]
4
Java
ColinHarrington/sitemesh2
e6f60f01f4632a2730030b02ab7b15fe5ff333f6
be024a6280eea049e0daacdc614058d3138e13f8
refs/heads/master
<file_sep>package pkgEnum; import java.io.Serializable; import java.lang.Comparable; import java.util.Map; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Iterator; public enum eGameDifficulty implements Serializable, Comparable<eGameDifficulty> { EASY (100), MEDIUM (500), HARD (1000); private final int iDifficulty; private static final Map<Integer, eGameDifficulty> lookup = new HashMap<java.lang.Integer,eGameDifficulty>(); static { for (eGameDifficulty d : eGameDifficulty.values()) { lookup.put(d.getiDifficulty(),d); } } private eGameDifficulty(int iDifficulty) { this.iDifficulty = iDifficulty; } public static eGameDifficulty get(int iDifficulty) { Iterator it = lookup.entrySet().iterator(); eGameDifficulty eGD = null; while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); eGameDifficulty enumDifficulty = (eGameDifficulty) pair.getValue(); int iDifficultyValue = (int) pair.getKey(); if (iDifficulty >= iDifficultyValue) { eGD = enumDifficulty; } } return eGD; } public int getiDifficulty() { return iDifficulty; } }
0bc6f3c5d9bc9f666cd4d0e7c7cf60b90783e28f
[ "Java" ]
1
Java
takiyahprice/Sudoku
99f95ae4126d11f9e070809773dd51384c5b060b
dc66169ec32da941bca3de438c95a010027d99e7
refs/heads/master
<file_sep>require 'rails_javascript_helpers/rails_javascript_helpers' <file_sep>== 1.5.1 * Include the rails javascript helper == 1.5 * Use Numeric in place of Fixnum to allow proper functionality of floats == 1.4 * Add RawJS type == 1.3 * Convert strings to single line when checking for function type on conversion == 1.2 * Unport #escape_javascript and let applications deal with fixing rails induced errors if needed * Format hash keys if the key is not a symbol == 1.1 * Remove escaping from function values * Port #escape_javascript from Rails to make more consistent == 1.0 * Initial release <file_sep>$LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__)) + '/lib/' require 'rails_javascript_helpers/version' Gem::Specification.new do |s| s.name = 'rails_javascript_helpers' s.version = RailsJavaScriptHelpers::VERSION s.summary = 'Javascript Helpers for Rails' s.author = '<NAME>' s.email = '<EMAIL>' s.homepage = 'http://github.com/chrisroberts/rails_javascript_helpers' s.description = 'JavaScript helpers for rails' s.require_path = 'lib' s.add_dependency 'rails', '>= 2.3' s.files = Dir.glob("lib/**/*") end
8608817eb6ee5f9ff1dbb1a87c6c9472b789cd6e
[ "RDoc", "Ruby" ]
3
Ruby
chrisroberts/rails_javascript_helpers
72bd78e9acbeff0760d6a5a00653581049c39606
708198427efbf25968f7c9406fdfea804678f24f
refs/heads/master
<repo_name>resyst-cz/cyklo-janicek<file_sep>/administrator/components/com_jbcatalog/views/item/tmpl/edit.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; JHtml::addIncludePath(JPATH_COMPONENT . '/helpers/html'); JHtml::_('behavior.tooltip'); JHtml::_('behavior.calendar'); JHtml::_('behavior.formvalidation'); JHtml::_('formbehavior.chosen', 'select'); if(count($this->plugins['js'])){ foreach($this->plugins['js'] as $js){ echo $js; } } ?> <script> Joomla.submitbutton = function(task) { if (task == 'item.cancel' || document.formvalidator.isValid(document.id('fileupload'))) { <?php echo $this->form->getField('descr')->save(); ?> Joomla.submitform(task, document.getElementById('fileupload')); } } </script> <form action="<?php echo JRoute::_('index.php?option=com_jbcatalog&layout=edit&id='.(int) $this->item->id); ?>" method="post" name="adminForm" id="fileupload" class="form-validate form-horizontal" enctype="multipart/form-data"> <div class="span10 form-horizontal"> <fieldset> <?php echo JHtml::_('bootstrap.startTabSet', 'myTab', array('active' => 'details')); ?> <?php echo JHtml::_('bootstrap.addTab', 'myTab', 'details', JText::_('COM_JBCATALOG_ITEM_DETAILS', true)); ?> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('title'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('title'); ?> </div> </div> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('alias'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('alias'); ?> </div> </div> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('catid'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('catid'); ?> </div> </div> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('descr'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('descr'); ?> </div> </div> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('id'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('id'); ?> </div> </div> <?php echo JHtml::_('bootstrap.endTab'); ?> <?php echo JHtml::_('bootstrap.addTab', 'myTab', 'options', JText::_('COM_JBCATALOG_ADF_LABEL', true)); ?> <script> function getItemAdfs(){ jQuery.ajax({ type: "POST", url: "index.php?option=com_jbcatalog&task=item.showAdfAjax&tmpl=component", data: {'<?php echo JSession::getFormToken()?>':'1', 'catssel':jQuery('#jform_catid').val(), 'item_id':'<?php echo (int) $this->item->id;?>' }, dataType: "html" }).done(function(data) { jQuery('#items_adf_div').html(data); jQuery('#items_adf_div .inputboxsel').chosen(); jQuery('#items_adf_div .inputboxsel').trigger("liszt:updated"); /// jQuery('#items_adf_div .radio').addClass('btn'); jQuery("#items_adf_div label.radio:not(.active)").click(function() { var label = jQuery(this); var input = jQuery('#' + label.attr('for')); if (!input.prop('checked')) { label.closest('#items_adf_div').find("label.radio").removeClass('active btn-success btn-danger btn-primary'); if (input.val() == '') { label.addClass('active btn-primary'); } else if (input.val() == 0) { label.addClass('active btn-danger'); } else { label.addClass('active btn-success'); } input.prop('checked', true); } }); jQuery("#items_adf_div label.radio input[checked=checked]").each(function(el,th) { if (th.value == '') { jQuery("label[for=" + th.id + "]").addClass('active btn-primary'); } else if (th.value == 0) { jQuery("label[for=" + th.id + "]").addClass('active btn-danger'); } else { jQuery("label[for=" + th.id + "]").addClass('active btn-success'); } }); jQuery('#items_adf_div .btn-group').hide(); jQuery('#items_adf_div .controls div.controls').css("margin","0px"); /// if (typeof WFEditor !== 'undefined') { WFEditor.init(WFEditor.settings); } else if (typeof tinyMCE !== 'undefined') { tinyMCE.init({mode : "specific_textareas",editor_selector : "mceEditors"}); } else if (typeof CKEDITOR !== 'undefined'){ //CKEDITOR.remove('extraf_1'); CKEDITOR.replace( 'extraf_1'); } jQuery( "input[name^='caldr[]']" ).each(function(){ Calendar.setup({ inputField: 'extraf_'+jQuery(this).val(), ifFormat: "%Y-%m-%d", button: 'extraf_' + jQuery(this).val() + '_img', align: "Tl", singleClick: true, firstDay: '' }); }); jQuery(".numericOnly").keypress(function (e) { if (String.fromCharCode(e.keyCode).match(/[^0-9\.]/g)) return false; }); }); } getItemAdfs(); </script> <div id="items_adf_div"> </div> <?php echo JHtml::_('bootstrap.endTab'); ?> <?php echo JHtml::_('bootstrap.endTabSet'); ?> </fieldset> <input type="hidden" name="task" value="" /> <?php echo JHtml::_('form.token'); ?> </div> <!-- End Newsfeed --> <!-- Begin Sidebar --> <div class="span2"> <h4><?php echo JText::_('JDETAILS');?></h4> <hr /> <fieldset class="form-vertical"> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('published'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('published'); ?> </div> </div> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('language'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('language'); ?> </div> </div> </fieldset> </div> <!-- End Sidebar --> <?php require_once JPATH_COMPONENT.'/helpers/images.php'; echo ImagesHelper::loaderUI($this->item->images); ?> </form> <file_sep>/modules/mod_jmslideshow/elements/asset.php <?php /* #------------------------------------------------------------------------ # Package - JoomlaMan JMSlideShow # Version 1.0 # ----------------------------------------------------------------------- # Author - JoomlaMan http://www.joomlaman.com # Copyright © 2012 - 2013 JoomlaMan.com. All Rights Reserved. # @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later # Websites: http://www.JoomlaMan.com #------------------------------------------------------------------------ */ //-- No direct access defined('_JEXEC') or die('Restricted access'); jimport('joomla.form.formfield'); class JFormFieldAsset extends JFormField { protected $type = 'Asset'; protected function getInput() { $doc = JFactory::getDocument(); jimport('joomla.version'); $version = new JVersion(); $joomla_version = (int) JVERSION; if ($joomla_version < 3) { $doc->addScript(JURI::root() . $this->element['path'] . 'js/jquery-1.10.2.min.js'); $doc->addScript(JURI::root() . $this->element['path'] . 'js/script.js'); //$doc->addScript(JURI::root() . $this->element['path'] . 'js/jquery.mousewheel.js'); //$doc->addScript(JURI::root() . $this->element['path'] . 'js/jScrollPane.js'); //$doc->addScript(JURI::root() . $this->element['path'] . 'js/jquery.jmfields.js'); $doc->addStyleSheet(JURI::root() . $this->element['path'] . 'css/jm_fields.css'); } elseif ($joomla_version >= 3) { $doc->addScript(JURI::root() . $this->element['path'] . 'js/script3.js'); $doc->addStyleSheet(JURI::root() . $this->element['path'] . 'css/jm_fields30.css'); } return null; } }<file_sep>/modules/mod_jmslideshow/mod_jmslideshow.php <?php /* #------------------------------------------------------------------------ # Package - JoomlaMan JMSlideShow # Version 1.0 # ----------------------------------------------------------------------- # Author - JoomlaMan http://www.joomlaman.com # Copyright © 2012 - 2013 JoomlaMan.com. All Rights Reserved. # @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later # Websites: http://www.JoomlaMan.com #------------------------------------------------------------------------ */ //-- No direct access defined('_JEXEC') or die('Restricted access'); global $jquery_cycle_load; if (!defined('DS')) define('DS', '/'); if (!defined('JM_SLIDESHOW_IMAGE_FOLDER')) { define('JM_SLIDESHOW_IMAGE_FOLDER', JPATH_SITE . DS . 'media' . DS . 'mod_jmslideshow'); } if (!defined('JM_SLIDESHOW_IMAGE_PATH')) { define('JM_SLIDESHOW_IMAGE_PATH', JURI::base(true) . '/media/mod_jmslideshow'); } if (!file_exists(JM_SLIDESHOW_IMAGE_FOLDER)) { @mkdir(JM_SLIDESHOW_IMAGE_FOLDER, 0755) or die('The folder "'. JPATH_SITE . DS . 'media" is not writeable, please change the permission'); } if (!class_exists('JMSlide')) { require_once JPATH_SITE . DS . 'modules' . DS . 'mod_jmslideshow' . DS . 'classes' . DS . 'slide.php'; } // Include the syndicate functions only once require_once (dirname(__file__) . DS . 'helper.php'); $module_id = $module->id; $slides = modJmSlideshowHelper::getSlides($params); $doc = JFactory::getDocument(); $app = JFactory::getApplication(); $custom_css = JPATH_SITE . '/templates/' . modJmSlideshowHelper::getTemplate() . '/css/' . $module->module.'_'.$params->get('jmslideshow_layout', 'default') . '.css'; if (file_exists($custom_css)) { $doc->addStylesheet(JURI::base(true) . '/templates/' . modJmSlideshowHelper::getTemplate() . '/css/' . $module->module.'_'.$params->get('jmslideshow_layout', 'default') . '.css'); } else { $doc->addStylesheet(JURI::base(true) . '/modules/mod_jmslideshow/assets/css/mod_jmslideshow_'.$params->get('jmslideshow_layout', 'default').'.css'); } if ($params->get('jmslideshow_include_jquery', 0) == 1) { $doc->addScript(JURI::base(true) . '/modules/mod_jmslideshow/assets/js/jquery.js'); } $jm_responsive = $params->get('jmslideshow_responsive', 1); $jm_width = $params->get('jmslideshow_width', 1); $jm_speed = $params->get('jmslideshow_speed', 500); $jm_auto = $params->get('jmslideshow_auto', 1); $timeout = $params->get('jmslideshow_timeout', 0); $jm_effect = $params->get('jmslideshow_effect', 'fade'); $jm_pause_onhover = $params->get('jmslideshow_pause_onhover', 0); $jm_show_nav_buttons = $params->get('jmslideshow_show_nav_buttons', 0); $jm_caption_width = $params->get('jmslideshow_caption_width', 500); $jm_show_title = $params->get('jmslideshow_show_title', 0); $jm_show_desc = $params->get('jmslideshow_show_desc', 0); $jm_show_readmore = $params->get('jmslideshow_show_readmore', 0); $jm_readmore_text = $params->get('jmslideshow_readmore_text', 'Read more'); $jm_show_pager = $params->get('jmslideshow_show_pager', 0); $jmslideshow_caption_hidden_mobile = $params->get('jmslideshow_caption_hidden_mobile', 0); $jmslideshow_pager_hidden_mobile = $params->get('jmslideshow_pager_hidden_mobile', 0); $jmslideshow_control_hidden_mobile = $params->get('jmslideshow_control_hidden_mobile', 0); $jm_pager_position = $params->get('jmslideshow_pager_position', 'bottomleft'); $jm_pager_top = $params->get('jmslideshow_pager_top', 30); $jm_pager_left = $params->get('jmslideshow_pager_left', 30); $jm_pager_right = $params->get('jmslideshow_pager_right', 30); $jm_pager_bottom = $params->get('jmslideshow_pager_bottom', 30); $jm_caption_position = $params->get('jmslideshow_caption_position', 'topleft'); $jm_caption_top = $params->get('jmslideshow_caption_top', 30); $jm_caption_left = $params->get('jmslideshow_caption_left', 30); $jm_caption_right = $params->get('jmslideshow_caption_right', 30); $jm_caption_bottom = $params->get('jmslideshow_caption_bottom', 30); $jmslideshow_pager_type = $params->get("jmslideshow_pager_type",1); global $jm_jquery_autoload; if($params->get('jmslideshow_include_jquery')==2 && empty($jm_jquery_autoload)):?> <script type="text/javascript"> var jQueryScriptOutputted = false; function JMInitJQuery() { if (typeof(jQuery) == 'undefined') { if (! jQueryScriptOutputted) { jQueryScriptOutputted = true; document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js\"></scr" + "ipt>"); } setTimeout("JMInitJQuery()", 50); } } JMInitJQuery(); </script> <?php $jm_jquery_autoload = 1; endif; require JModuleHelper::getLayoutPath('mod_jmslideshow', $params->get('jmslideshow_layout', 'default'));<file_sep>/administrator/components/com_jbcatalog/models/adfgroup.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogModelAdfgroup extends JModelAdmin { protected $text_prefix = 'COM_JBCATALOG_ADFGROUP'; public function getForm($data = array(), $loadData = true) { // Get the form. $form = $this->loadForm('com_jbcatalog.adfgroup', 'adfgroup', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } // Determine correct permissions to check. if ($this->getState('adfgroup.id')) { // Existing record. Can only edit in selected categories. $form->setFieldAttribute('catid', 'action', 'core.edit'); } else { // New record. Can only create in selected categories. $form->setFieldAttribute('catid', 'action', 'core.create'); } // Modify the form based on access controls. if (!$this->canEditState((object) $data)) { // Disable fields for display. $form->setFieldAttribute('ordering', 'disabled', 'true'); $form->setFieldAttribute('publish_up', 'disabled', 'true'); $form->setFieldAttribute('publish_down', 'disabled', 'true'); $form->setFieldAttribute('state', 'disabled', 'true'); $form->setFieldAttribute('sticky', 'disabled', 'true'); // Disable fields while saving. // The controller has already verified this is a record you can edit. $form->setFieldAttribute('ordering', 'filter', 'unset'); $form->setFieldAttribute('publish_up', 'filter', 'unset'); $form->setFieldAttribute('publish_down', 'filter', 'unset'); $form->setFieldAttribute('state', 'filter', 'unset'); $form->setFieldAttribute('sticky', 'filter', 'unset'); } return $form; } public function getTable($type = 'Adfgroup', $prefix = 'JBCatalogTable', $config = array()) { return JTable::getInstance($type, $prefix, $config); } public function save($data) { $pk = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('adfgroup.id'); $isNew = true; $table = $this->getTable(); // Load the row if saving an existing item. if ($pk > 0) { $table->load($pk); $isNew = false; } // Bind the data. if (!$table->bind($data)) { $this->setError($table->getError()); return false; } // Alter the title & alias for save as copy. Also, unset the home record. if (!$isNew && $data['id'] == 0) { list($title, $alias) = $this->generateNewTitle($table->parent_id, $table->alias, $table->title); $table->title = $title; $table->alias = $alias; $table->published = 0; } // Check the data. if (!$table->check()) { $this->setError($table->getError()); return false; } // Store the data. if (!$table->store()) { $this->setError($table->getError()); return false; } $this->setState('adfgroup.id', $table->id); //adf groups $db = JFactory::getDbo(); $db->setQuery("DELETE FROM #__jbcatalog_adf_ingroups WHERE groupid={$table->id}"); $db->execute(); if(isset($data['adfs']) && count($data['adfs'])){ foreach($data['adfs'] as $adfs){ $db->setQuery("INSERT INTO #__jbcatalog_adf_ingroups(adfid,groupid)" ." VALUES(".intval($adfs).", {$table->id})"); $db->execute(); } } // Load associated menu items $app = JFactory::getApplication(); $assoc = isset($app->item_associations) ? $app->item_associations : 0; if ($assoc) { // Adding self to the association $associations = $data['associations']; foreach ($associations as $tag => $id) { if (empty($id)) { unset($associations[$tag]); } } // Detecting all item menus $all_language = $table->language == '*'; if ($all_language && !empty($associations)) { JError::raiseNotice(403, JText::_('COM_MENUS_ERROR_ALL_LANGUAGE_ASSOCIATED')); } $associations[$table->language] = $table->id; // Deleting old association for these items $query = $db->getQuery(true) ->delete('#__associations') ->where('context=' . $db->quote('com_jbcatalog.adfgroup')) ->where('id IN (' . implode(',', $associations) . ')'); $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { $this->setError($e->getMessage()); return false; } if (!$all_language && count($associations) > 1) { // Adding new association for these items $key = md5(json_encode($associations)); $query->clear() ->insert('#__associations'); foreach ($associations as $tag => $id) { $query->values($id . ',' . $db->quote('com_jbcatalog.adfgroup') . ',' . $db->quote($key)); } $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { $this->setError($e->getMessage()); return false; } } } // Clean the cache $this->cleanCache(); return true; } public function getItem($pk = null) { if ($item = parent::getItem($pk)) { // Convert the metadata field to an array. /* $registry = new JRegistry; $registry->loadString($item->metadata); $item->metadata = $registry->toArray();*/ } // Load associated contact items $app = JFactory::getApplication(); $assoc = isset($app->item_associations) ? $app->item_associations : 0; if ($assoc) { $item->associations = array(); if ($item->id != null) { $associations = JLanguageAssociations::getAssociations('com_jbcatalog', '#__jbcatalog_adfgroups', 'com_jbcatalog.adfgroups', $item->id); foreach ($associations as $tag => $association) { $item->associations[$tag] = $association->id; } } } $db = $this->getDbo(); $query = "SELECT a.id" ." FROM #__jbcatalog_adf as a" ." JOIN #__jbcatalog_adf_ingroups as b" ." ON b.adfid = a.id" ." WHERE b.groupid = ".intval($item->id) ." ORDER BY a.name"; $db->setQuery($query); $item->adfs = $db->loadColumn(); return $item; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 1.6 */ protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_jbcatalog.edit.adfgroup.data', array()); if (empty($data)) { $data = $this->getItem(); // Prime some default values. if ($this->getState('adfgroup.id') == 0) { $app = JFactory::getApplication(); // $data->set('catid', $app->input->get('catid', $app->getUserState('com_jbcatalog.category.filter.category_id'), 'int')); } } $this->preprocessData('com_jbcatalog.adfgroup', $data); return $data; } public function publish(&$pks, $value = 1) { $table = $this->getTable(); $pks = (array) $pks; // Clean the cache $this->cleanCache(); // Ensure that previous checks doesn't empty the array if (empty($pks)) { return true; } return parent::publish($pks, $value); } } <file_sep>/templates/cyklo/html/mod_articles_news/_item.php <?php /** * upraveny modul pro zobrazeni znacek vyrobcu s popisky * @author <EMAIL> <<EMAIL>> */ defined('_JEXEC') or die; //var_dump($item); //die(); echo $item->introtext; <file_sep>/components/com_jbcatalog/models/categories.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogModelCategories extends JModelList { /** * Model context string. * * @var string */ public $_context = 'com_jbcatalog.categories'; /** * The category context (allows other extensions to derived from this model). * * @var string */ protected $_extension = 'com_jbcatalog'; private $_parent = null; private $_items = null; /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState($ordering = null, $direction = null) { $app = JFactory::getApplication(); $this->setState('filter.extension', $this->_extension); // List state information $ll = $app->getUserState('list_limit_cat', $app->getCfg('list_limit', 0)); $value = $app->input->get('limit', $ll, 'uint'); $this->setState('list.limit', $value); $app->setUserState('list_limit_cat', $value); $value = $app->input->get('limitstart', 0, 'uint'); $this->setState('list.start', $value); // Get the parent id if defined. $parentId = $app->input->getInt('id'); $this->setState('filter.parentId', $parentId); $params = $app->getParams(); $this->setState('params', $params); $this->setState('filter.published', 1); $this->setState('filter.access', true); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * * @return string A store id. */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':'.$this->getState('filter.extension'); $id .= ':'.$this->getState('filter.published'); $id .= ':'.$this->getState('filter.access'); $id .= ':'.$this->getState('filter.parentId'); return parent::getStoreId($id); } /** * redefine the function an add some properties to make the styling more easy * * @return mixed An array of data items on success, false on failure. */ public function getItems() { if (!count($this->_items)) { $app = JFactory::getApplication(); $menu = $app->getMenu(); $active = $menu->getActive(); $params = new JRegistry; if ($active) { $params->loadString($active->params); } $this->_items = $this->_getCats(); $this->_getCatsImg(); } return $this->_items; } protected function getListQuery() { $db = $this->getDbo(); $query = "SELECT * " ." FROM #__jbcatalog_category" ." WHERE parent_id = 1" ." AND published = 1" ." ORDER BY lft ASC"; return $query; } private function _getCats(){ $db = $this->getDbo(); $query = "SELECT * " ." FROM #__jbcatalog_category" ." WHERE parent_id = 1" ." AND published = 1" ." ORDER BY lft ASC"; $db->setQuery($query,$this->getState('list.start'), $this->getState('list.limit')); return $db->loadObjectList(); } private function _getCatsImg(){ $db = $this->getDbo(); for($i=0; $i<count($this->_items); $i++){ $this->_items[$i]->images = null; if($this->_items[$i]->image && is_file(JPATH_ROOT.DIRECTORY_SEPARATOR.$this->_items[$i]->image)){ $this->_items[$i]->images = $this->_items[$i]->image; $info = pathinfo($this->_items[$i]->image); $path_to_thumbs_directory = 'components'.DIRECTORY_SEPARATOR.'com_jbcatalog'.DIRECTORY_SEPARATOR.'libraries'.DIRECTORY_SEPARATOR.'jsupload'.DIRECTORY_SEPARATOR.'server'.DIRECTORY_SEPARATOR.'php'.DIRECTORY_SEPARATOR.'files'.DIRECTORY_SEPARATOR.'thumbnail'; if(is_file(JPATH_ROOT.DIRECTORY_SEPARATOR.$path_to_thumbs_directory.DIRECTORY_SEPARATOR.$this->_items[$i]->id.'_thumb.'.$info['extension'])){ $this->_items[$i]->images = $path_to_thumbs_directory.DIRECTORY_SEPARATOR.$this->_items[$i]->id.'_thumb.'.$info['extension']; } // $file_name_thumb = $id.'_thumb.'.$info['extension']; } } } } <file_sep>/modules/mod_jmslideshow/admin/assets/js/script3.js /* #------------------------------------------------------------------------ # Package - JoomlaMan JMSlideShow # Version 1.0 # ----------------------------------------------------------------------- # Author - JoomlaMan http://www.joomlaman.com # Copyright © 2012 - 2013 JoomlaMan.com. All Rights Reserved. # @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later # Websites: http://www.JoomlaMan.com #------------------------------------------------------------------------ */ jQuery(document).ready(function(){ //Slider source //jQuery('#jform_params___field1-lbl').parent().hide(); JMSlideShow_SourceChange(jQuery('#jform_params_slider_source').val()); JMSlideShow_ReadMoreChange(jQuery('#jform_params_jmslideshow_show_readmore:checked').val()); JMSlideShow_ResponsiveChange(jQuery('[id^=jform_params_jmslideshow_responsive]:checked').val()); JMSlideShow_AutoChange(jQuery('#jform_params_jmslideshow_auto').val()); JMSlideShow_PagerChange(jQuery('#jform_params_jmslideshow_pager_position').val()); JMSlideShow_PagertypeChange(jQuery('#jform_params_jmslideshow_pager_type').val()); JMSlideShow_CaptionChange(jQuery('#jform_params_jmslideshow_caption_position').val()); JMSlideShow_title_toggle(); JMSlideShow_desc_toggle(); jQuery('#jform_params_slider_source').change(function(){ JMSlideShow_SourceChange(jQuery(this).val()); }); jQuery('#jform_params_jmslideshow_show_readmore').change(function(){ JMSlideShow_ReadMoreChange(jQuery(this).is(':checked')); }); jQuery('[id^=jform_params_jmslideshow_responsive]').click(function(){ JMSlideShow_ResponsiveChange(jQuery(this).val()); }); jQuery('#jform_params_jmslideshow_auto').change(function(){ JMSlideShow_AutoChange(jQuery(this).val()); }); jQuery('#jform_params_jmslideshow_pager_position').change(function(){ JMSlideShow_PagerChange(jQuery(this).val()); }); jQuery('#jform_params_jmslideshow_caption_position').change(function(){ JMSlideShow_CaptionChange(jQuery(this).val()); }); jQuery('#jform_params_jmslideshow_show_title').change(function(){ JMSlideShow_title_toggle(); }); jQuery('#jform_params_jmslideshow_show_desc').change(function(){ JMSlideShow_desc_toggle(); }); jQuery('#jform_params_jmslideshow_pager_type').change(function(){ JMSlideShow_PagertypeChange(jQuery(this).val()); }); }) function JMSlideShow_SourceChange(source){ jQuery(".s1, .s2, .s3, .s4, .s5, .s6, .s7, .s8, .s9, .s10").not(".s"+source).parents('.control-group').css({ display:'none' }); jQuery(".s"+source).parents('.control-group').css({ display:'block' }); return true; } function JMSlideShow_ReadMoreChange(source){ if(source){ jQuery('#jform_params_jmslideshow_readmore_text').parents('.control-group').css({ display:'block' }); }else{ jQuery('#jform_params_jmslideshow_readmore_text').parents('.control-group').css({ display:'none' }); } } function JMSlideShow_ResponsiveChange(source){ switch(source){ case '0': jQuery('#jform_params_jmslideshow_width').parents('.control-group').css({ display:'block' }); break; case '1': jQuery('#jform_params_jmslideshow_width').parents('.control-group').css({ display:'none' }); break; } } function JMSlideShow_AutoChange(source){ switch(source){ case '1': jQuery('#jform_params_jmslideshow_timeout').parents('.control-group').css({ display:'block' }); break; case '0': jQuery('#jform_params_jmslideshow_timeout').parents('.control-group').css({ display:'none' }); break; } } function JMSlideShow_PagerChange(source){ switch(source){ case 'topleft': jQuery('#jform_params_jmslideshow_pager_left').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_pager_top').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_pager_bottom').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_pager_right').parents('.control-group').css({ display:'none' }); break; case 'topright': jQuery('#jform_params_jmslideshow_pager_left').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_pager_top').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_pager_bottom').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_pager_right').parents('.control-group').css({ display:'block' }); break; case 'bottomleft': jQuery('#jform_params_jmslideshow_pager_left').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_pager_top').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_pager_bottom').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_pager_right').parents('.control-group').css({ display:'none' }); break; case 'bottomright': jQuery('#jform_params_jmslideshow_pager_left').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_pager_top').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_pager_bottom').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_pager_right').parents('.control-group').css({ display:'block' }); break; } } //Page Type function JMSlideShow_PagertypeChange(source){ switch(source){ case '1': jQuery('#jform_params_jmslideshow_image_thumbnail_width').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_image_thumbnail_height').parents('.control-group').css({ display:'none' }); break; case '2': jQuery('#jform_params_jmslideshow_image_thumbnail_width').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_image_thumbnail_height').parents('.control-group').css({ display:'none' }); break; case '3': jQuery('#jform_params_jmslideshow_image_thumbnail_width').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_image_thumbnail_height').parents('.control-group').css({ display:'block' }); break; } } function JMSlideShow_CaptionChange(source){ switch(source){ case 'topleft': jQuery('#jform_params_jmslideshow_caption_left').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_caption_top').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_caption_bottom').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_caption_right').parents('.control-group').css({ display:'none' }); break; case 'topright': jQuery('#jform_params_jmslideshow_caption_left').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_caption_top').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_caption_bottom').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_caption_right').parents('.control-group').css({ display:'block' }); break; case 'bottomleft': jQuery('#jform_params_jmslideshow_caption_left').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_caption_top').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_caption_bottom').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_caption_right').parents('.control-group').css({ display:'none' }); break; case 'bottomright': jQuery('#jform_params_jmslideshow_caption_left').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_caption_top').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_caption_bottom').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_caption_right').parents('.control-group').css({ display:'block' }); break; } } function JMSlideShow_title_toggle(){ if(jQuery('#jform_params_jmslideshow_show_title').attr('checked')){ jQuery('#jform_params_jmslideshow_title_link').parents('.control-group').css({ display:'block' }); }else{ jQuery('#jform_params_jmslideshow_title_link').parents('.control-group').css({ display:'none' }); } } function JMSlideShow_desc_toggle(){ if(jQuery('#jform_params_jmslideshow_show_desc').attr('checked')){ jQuery('#jform_params_jmslideshow_desc_length').parents('.control-group').css({ display:'block' }); jQuery('#jform_params_jmslideshow_desc_html').parents('.control-group').css({ display:'block' }); }else{ jQuery('#jform_params_jmslideshow_desc_length').parents('.control-group').css({ display:'none' }); jQuery('#jform_params_jmslideshow_desc_html').parents('.control-group').css({ display:'none' }); } }<file_sep>/administrator/components/com_jbcatalog/views/plugin/tmpl/edit.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; JHtml::addIncludePath(JPATH_COMPONENT . '/helpers/html'); JHtml::_('behavior.tooltip'); JHtml::_('behavior.formvalidation'); JHtml::_('formbehavior.chosen', 'select'); ?> <script type="text/javascript"> Joomla.submitbutton = function(task) { if (task == 'adf.cancel' || document.formvalidator.isValid(document.id('bcat-form'))) { Joomla.submitform(task, document.getElementById('bcat-form')); } } </script> <form action="<?php echo JRoute::_('index.php?option=com_jbcatalog&layout=edit&id='.(int) $this->item->id); ?>" method="post" name="adminForm" id="bcat-form" class="form-validate form-horizontal"> <div class="span10 form-horizontal"> <fieldset> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('name'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('name'); ?> </div> </div> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('id'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('id'); ?> </div> </div> <?php if(count($this->plugins['settings'])){ foreach($this->plugins['settings'] as $pl){ ?> <div class="control-group"> <div class="control-label"> <?php echo $pl['label']; ?> </div> <div class="controls"> <?php echo $pl['data']; ?> </div> </div> <?php } } ?> </fieldset> <input type="hidden" name="task" value="" /> <?php echo JHtml::_('form.token'); ?> </div> <!-- End Newsfeed --> <!-- Begin Sidebar --> <div class="span2"> <h4><?php echo JText::_('JDETAILS');?></h4> <hr /> <fieldset class="form-vertical"> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('published'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('published'); ?> </div> </div> </fieldset> </div> <!-- End Sidebar --> </form> <file_sep>/modules/mod_jmslideshow/CHANGELOG.php <?php /** * CHANGELOG * * This is the changelog for JMSlideshow.<br> * <b>Please</b> be patient =;) * * @version SVN $Id$ * @package JoomlaMan JMSlideshow * @subpackage Documentation * @author Expert Team Joomla {@link http://joomlaman.com} * @author Created on 24-Sep-2012 */ //--No direct access to this changelog... defined('_JEXEC') || die('=;)'); //--For phpDocumentor documentation we need to construct a function ;) /** * CHANGELOG * {@source} */ function CHANGELOG() { /* _______________________________________________ _______________________________________________ This is the changelog for slideshowbootstrap Please be patient =;) _______________________________________________ _______________________________________________ Legend: * -> Security Fix # -> Bug Fix + -> Addition ^ -> Change - -> Removed ! -> Note ______________________________________________ 24-Sep-2012 Expert Team Joomla ! Startup */ } //--This is the END<file_sep>/templates/cyklo/js/template.js /** * @package Joomla.Site * @subpackage Templates.cyklo * @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @since 3.2 */ (function ($) { // rozsiri contains selector a udela non-case sensitive verzi $.extend($.expr[":"], { "containsIN": function (elem, i, match, array) { return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0; } }); $(document).ready(function () { $('*[rel=tooltip], *[data-toggle=tooltip]').tooltip(); $('.nav.nav-tabs li:first-child a').each(function () { $(this).trigger('click'); }); // Turn radios into btn-group $('.radio.btn-group label').addClass('btn'); $(".btn-group label:not(.active)").click(function () { var label = $(this); var input = $('#' + label.attr('for')); if (!input.prop('checked')) { label.closest('.btn-group').find("label").removeClass('active btn-success btn-danger btn-primary'); if (input.val() == '') { label.addClass('active btn-primary'); } else if (input.val() == 0) { label.addClass('active btn-danger'); } else { label.addClass('active btn-success'); } input.prop('checked', true); } }); $(".btn-group input[checked=checked]").each(function () { if ($(this).val() == '') { $("label[for=" + $(this).attr('id') + "]").addClass('active btn-primary'); } else if ($(this).val() == 0) { $("label[for=" + $(this).attr('id') + "]").addClass('active btn-danger'); } else { $("label[for=" + $(this).attr('id') + "]").addClass('active btn-success'); } }); /* * Simple image gallery. Uses default settings */ $('.fancybox').fancybox(); /* * Thumbnail helper. Disable animations, hide close button, arrows and slide to next gallery item if clicked */ $('.fancybox-thumbs').fancybox({ prevEffect: 'none', nextEffect: 'none', closeBtn: true, arrows: true, nextClick: true, helpers: { thumbs: { width: 50, height: 50 } } }); /* * Filtr pro kategorii kol */ $('.filtr-tags .kategorie_tag').on('click', function () { var kategorie = $(this).attr('data-filtr_kategorie_id'); $('.catmain_div .product-card').each(function () { if (kategorie == '-1') { $(this).show(400); } else if ($(this).attr('data-kategorie_id') != kategorie) { $(this).hide(400); } else { $(this).show(400); } }); }); /** * Vyhledavani pro kategorii kol */ $('#produkty-search-btn').on('click', function () { var search_string = $('#produkty-search').val(); if (search_string == '') { $(".catmain_div .product-card").show(400); } else { $(".catmain_div .product-card:not(:containsIN('" + search_string + "'))").hide(400); $(".catmain_div .product-card:containsIN('" + search_string + "')").show(400); } }); /** * kliknuti na tlacitko 'chci dalsi informace' v bazaru */ $('.btn-email.modal').click(function (e) { e.preventDefault(); var id = $(this).data('id'), produkt = $(this).closest(".product-card[data-id='" + id + "']"), nazev = produkt.find('h3').text(), cena = produkt.find('.cena:not(.puvodni) > span').text(); $('.bazar-form .predmet > input').val(nazev + ' za ' + cena); }); /** * zobrazeni popisu u znacek */ $(document).on({ mouseenter: function () { $(this).find('.znacka-popis').slideDown(200); }, mouseleave: function () { $(this).find('.znacka-popis').slideUp(200); } }, '.znacka-wrapper'); }); })(jQuery);<file_sep>/administrator/components/com_jbcatalog/tables/item.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogTableItem extends JTable { public function __construct(&$db) { parent::__construct('#__jbcatalog_items', 'id', $db); } } <file_sep>/language/cs-CZ/cs-CZ.tpl_cyklo.ini ; Joomla! Project ; Copyright (C) 2005 - 2015 Open Source Matters. All rights reserved. ; License GNU General Public License version 2 or later; see LICENSE.txt, see LICENSE.php ; Note : All ini files need to be saved as UTF-8 - No BOM TPL_CYKLO_XML_DESCRIPTION="CYKLO is the Joomla 3 site template based on Bootstrap from Twitter and the launch of the Joomla User Interface library (JUI)." TPL_CYKLO_BACKTOTOP="Nahoru" TPL_CYKLO_FLUID="Fluid" TPL_CYKLO_STATIC="Static" TPL_CYKLO_FLUID_LABEL="Fluid Layout" TPL_CYKLO_FLUID_DESC="Use Bootstrap's Fluid or Static Container (both are Responsive)." TPL_CYKLO_LOGO_LABEL="Logo" TPL_CYKLO_LOGO_DESC="Nahrajte logo stránky" TPL_CYKLO_SLOGAN_LABEL="Slogan" TPL_CYKLO_SLOGAN_DESC="Napište váš slogan" TPL_CYKLO_SLOGAN_2_LABEL="Slogan - zvýraznění" TPL_CYKLO_SLOGAN_2_DESC="Napište zbytek sloganu, který bude zvýrazněný" TPL_CYKLO_EMAIL_LABEL="E-mail" TPL_CYKLO_EMAIL_DESC="Váš kontaktní email" TPL_CYKLO_PHONE_LABEL="Telefon" TPL_CYKLO_PHONE_DESC="Váš kontaktní telefon" <file_sep>/templates/cyklo/index.php <?php /** * @package Joomla.Site * @subpackage Templates.cyklo * * @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; define('VERZE', '1.2'); $app = JFactory::getApplication(); $doc = JFactory::getDocument(); $user = JFactory::getUser(); $this->language = $doc->language; $this->direction = $doc->direction; // Getting params from template $params = $app->getTemplate(true)->params; // Detecting Active Variables $option = $app->input->getCmd('option', ''); $view = $app->input->getCmd('view', ''); $layout = $app->input->getCmd('layout', ''); $task = $app->input->getCmd('task', ''); $itemid = $app->input->getCmd('Itemid', ''); $sitename = $app->get('sitename'); if ($task == "edit" || $layout == "form") { $fullWidth = 1; } else { $fullWidth = 0; } // Add JavaScript Frameworks JHtml::_('bootstrap.framework'); JHTML::_('behavior.modal'); $doc->addScript($this->baseurl . '/templates/' . $this->template . '/js/template.js?v=' . VERZE); $doc->addScript('components/com_jbcatalog/libraries/fancybox/source/jquery.fancybox.js?v=2.1.5'); $doc->addScript('components/com_jbcatalog/libraries/fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7'); // Add Stylesheets $doc->addStyleSheet($this->baseurl . '/templates/' . $this->template . '/css/template.css?v=' . VERZE); $doc->addStyleSheet('components/com_jbcatalog/libraries/fancybox/source/jquery.fancybox.css?v=2.1.5'); $doc->addStyleSheet('components/com_jbcatalog/libraries/fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7'); // Load optional RTL Bootstrap CSS JHtml::_('bootstrap.loadCss', false, $this->direction); // Adjusting content width if ($this->countModules('sidebar-right') && $this->countModules('sidebar-left')) { $span = "span6"; } elseif ($this->countModules('sidebar-right') && !$this->countModules('sidebar-left')) { $span = "span9"; } elseif (!$this->countModules('sidebar-right') && $this->countModules('sidebar-left')) { $span = "span9"; } else { $span = "span12"; } // Logo file or site title param if ($this->params->get('logoFile')) { $logo = '<div class="site-logo"><img src="' . JUri::root() . $this->params->get('logoFile') . '" alt="' . $sitename . '" /></div> <span class="site-title">' . htmlspecialchars($this->params->get('sitetitle')) . '</span><br />' . ($params->get('siteslogan') && $params->get('siteslogan-2') ? '<small>' . $params->get('siteslogan') . ' <span class="zelena">' . $params->get('siteslogan-2') . '</span></small>' : ''); } elseif ($this->params->get('sitetitle')) { $logo = '<span class="site-title" title="' . $sitename . '">' . htmlspecialchars($this->params->get('sitetitle')) . '</span>'; } else { $logo = '<span class="site-title" title="' . $sitename . '">' . $sitename . '</span>'; } $googleMapsApiKey = '<KEY>'; $komponenta = $app->input->get('option'); $show_page_header = $show_page_header_bg = false; $add_class = $header_title = ''; $show_page_header_bg = JURI::base() . 'images/clanky_header_images/vychozi_bg.png'; if ($komponenta == 'com_content') { $article_id = $app->input->get('id'); $add_class = ($article_id == '6' ? ' kontakt' : ''); if ($article_id !== null) { $article = JTable::getInstance("content"); $article->load($article_id); // Get Article ID $article_params = json_decode($article->get("attribs")); $article_images = json_decode($article->get("images")); if ($article_params->show_title == '1') { $show_page_header = true; } if (!empty($article_images->image_intro)) { $show_page_header_bg = JURI::base() . $article_images->image_intro; } $header_title = $article->title; } } elseif ($komponenta == 'com_jbcatalog') { $show_page_header = true; $menu = $app->getMenu(); // alternativa - vezme nazev z menu $header_title = $menu->getActive()->title; // aktivni polozka menu } ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" dir="<?php echo $this->direction; ?>"> <head> <!-- <meta name="viewport" content="width=device-width, initial-scale=1.0" /> --> <jdoc:include type="head"/> <!--[if lt IE 9]> <script src="<?php echo JUri::root(true); ?>/media/jui/js/html5.js"></script> <![endif]--> <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/style.css" type="text/css"/> <link href='//fonts.googleapis.com/css?family=Open+Sans:400,400italic&subset=latin,latin-ext' rel='stylesheet' type='text/css'/> <link href='//fonts.googleapis.com/css?family=Kaushan+Script&subset=latin,latin-ext' rel='stylesheet' type='text/css'/> <link rel="apple-touch-icon" sizes="57x57" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/apple-touch-icon-57x57.png"/> <link rel="apple-touch-icon" sizes="60x60" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/apple-touch-icon-60x60.png"/> <link rel="apple-touch-icon" sizes="72x72" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/apple-touch-icon-72x72.png"/> <link rel="apple-touch-icon" sizes="76x76" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/apple-touch-icon-76x76.png"/> <link rel="apple-touch-icon" sizes="114x114" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/apple-touch-icon-114x114.png"/> <link rel="apple-touch-icon" sizes="120x120" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/apple-touch-icon-120x120.png"/> <link rel="apple-touch-icon" sizes="144x144" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/apple-touch-icon-144x144.png"/> <link rel="apple-touch-icon" sizes="152x152" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/apple-touch-icon-152x152.png"/> <link rel="apple-touch-icon" sizes="180x180" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/apple-touch-icon-180x180.png"/> <link rel="icon" type="image/png" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/favicon-32x32.png" sizes="32x32"/> <link rel="icon" type="image/png" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/android-chrome-192x192.png" sizes="192x192"/> <link rel="icon" type="image/png" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/favicon-96x96.png" sizes="96x96"/> <link rel="icon" type="image/png" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/favicon-16x16.png" sizes="16x16"/> <meta name="application-name" content="<NAME>"/> <meta name="msapplication-TileColor" content="#7da90f"/> <meta name="msapplication-TileImage" content="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/mstile-144x144.png"/> <link rel="mask-icon" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/safari-pinned-tab.svg" color="#ffffff"/> <meta name="msapplication-TileColor" content="#ffffff"/> <meta name="msapplication-TileImage" content="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/mstile-144x144.png"/> <meta name="msapplication-config" content="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/favicons/browserconfig.xml"/> <meta name="theme-color" content="#7da90f"/> <?php if ($this->countModules('instagram')) : ?> <script src="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/js/instafeed.min.js"></script> <?php endif; ?> </head> <body class="site <?php echo $option . ' view-' . $view . ($layout ? ' layout-' . $layout : ' no-layout') . ($task ? ' task-' . $task : ' no-task') . ($itemid ? ' itemid-' . $itemid : '') . ($params->get('fluidContainer') ? ' fluid' : '') . $add_class; ?>"> <div id="fb-root"></div> <script>(function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/cs_CZ/sdk.js#xfbml=1&version=v2.3&appId=188936964535953"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <!-- Google Tag Manager --> <noscript> <iframe src="//www.googletagmanager.com/ns.html?id=GTM-NNSQV8" height="0" width="0" style="display:none;visibility:hidden"></iframe> </noscript> <script>(function (w, d, s, l, i) { w[l] = w[l] || []; w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' }); var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src = '//www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f); })(window, document, 'script', 'dataLayer', 'GTM-NNSQV8');</script> <!-- End Google Tag Manager --> <!-- Body --> <div class="body"> <div class="fixed-top"> <div class="body-top"> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <div class="row-fluid"> <div class="top-info span10 text-right"> <?php echo($params->get('siteemail') ? '<span class="email"><a href="mailto:' . $params->get('siteemail') . '">' . $params->get('siteemail') . '</a></span>' : ''); ?> <?php echo($params->get('sitephone') ? '<span class="phone">' . $params->get('sitephone') . '</span>' : ''); ?> </div> <div class="fb-like span2" data-href="https://www.facebook.com/cyklo.janicek" data-layout="button_count" data-action="like" data-show-faces="false" data-share="false"></div> </div> </div> </div> <div class="header-logo-menu"> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <div class="row-fluid"> <div class="span4"> <header class="header" role="banner"> <div class="header-inner clearfix"> <a class="brand pull-left" href="<?php echo $this->baseurl; ?>/"><?php echo $logo; ?></a> </div> </header> </div> <div class="span8"> <?php if ($this->countModules('top-nav')) : ?> <nav class="navigation topmenu" role="navigation"> <jdoc:include type="modules" name="top-nav" style="none"/> </nav> <?php endif; ?> </div> </div> </div> </div> </div> <div class="MainContainer"> <?php if ($show_page_header) { ?> <div <?php echo($show_page_header_bg !== false ? 'class="clanek-main-bg" style="background: rgba(0, 0, 0, 0) url(\'' . $show_page_header_bg . '\') no-repeat scroll 50% 0;"' : ''); ?>> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <?php if ($this->countModules('breadcrumbs')) { ?> <jdoc:include type="modules" name="breadcrumbs" style="none"/> <?php } ?> <h1 class="page-header on-slideshow"><?php echo $header_title; ?></h1> </div> </div> <?php } ?> <?php if ($this->countModules('slideshow')) : ?> <div class="slideshow-full ParallaxContainer"> <jdoc:include type="modules" name="slideshow" style="none"/> </div> <?php endif; ?> <div class="ContentContainer"> <?php if ($this->countModules('sortiment-nav')) : ?> <div class="sortiment-menu"> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <nav class="navigation sortiment" role="navigation"> <jdoc:include type="modules" name="sortiment-nav" style="none"/> </nav> </div> </div> <?php endif; ?> <?php if ($this->countModules('banner-1') || $this->countModules('banner-2')) : ?> <div class="banner1-bg"> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <div class="row banner1-content"> <div class="span6 banner1-left"> <jdoc:include type="modules" name="banner-1" style="none"/> </div> <div class="span6 banner1-right"> <jdoc:include type="modules" name="banner-2" style="none"/> </div> </div> </div> </div> <?php endif; ?> <?php if ($this->countModules('mini-kolo')) : ?> <div class="mini-kolo"></div> <?php endif; ?> <?php if ($this->countModules('banner-3')) : ?> <div class="banner1-bg banner3-bg"> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <div class="row banner1-content"> <div class="span6 banner1-left"> <jdoc:include type="modules" name="banner-3" style="none"/> </div> </div> </div> </div> <?php endif; ?> <?php if ($this->countModules('reference')) : ?> <div class="banner2-bg"> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <jdoc:include type="modules" name="reference" style="xhtml"/> </div> </div> <?php endif; ?> <?php if ($this->countModules('certifikace')) : ?> <div class="banner-white-bg certifikace"> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <jdoc:include type="modules" name="certifikace" style="xhtml"/> </div> </div> <?php endif; ?> <?php if ($this->countModules('testovaci-dny')) : ?> <div class="banner-grey-bg testovaci-dny"> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <jdoc:include type="modules" name="testovaci-dny" style="xhtml"/> </div> </div> <?php endif; ?> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <jdoc:include type="modules" name="banner" style="xhtml"/> <div class="row-fluid"> <?php if ($this->countModules('sidebar-left')) : ?> <!-- Begin Left Sidebar --> <div id="sidebar" class="span3"> <div class="sidebar-nav"> <jdoc:include type="modules" name="sidebar-left" style="xhtml"/> </div> </div> <!-- End Left Sidebar --> <?php endif; ?> <main id="content" role="main" class="<?php echo $span; ?>"> <jdoc:include type="modules" name="position-3" style="xhtml"/> <jdoc:include type="message"/> <jdoc:include type="component"/> <?php if ($this->countModules('znacky')) { ?> <jdoc:include type="modules" name="znacky" style="none"/> <?php } ?> </main> <?php if ($this->countModules('sidebar-right')) : ?> <div id="aside" class="span3"> <!-- Begin Right Sidebar --> <jdoc:include type="modules" name="sidebar-right" style="well"/> <!-- End Right Sidebar --> </div> <?php endif; ?> </div> </div> <?php if ($this->countModules('sponzorujeme')) : ?> <div class="banner-white-bg sponzorujeme"> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <jdoc:include type="modules" name="sponzorujeme" style="xhtml"/> </div> </div> <?php endif; ?> <?php if ($this->countModules('mapka')) : ?> <div class="mapka-full"> <?php if ($this->countModules('mapka-oteviraci-doba')) : ?> <div class="mapka-oteviraci-doba"> <jdoc:include type="modules" name="mapka-oteviraci-doba" style="xhtml"/> </div> <?php endif; ?> <iframe src="https://www.google.com/maps/embed?key=<?php echo $googleMapsApiKey; ?>&pb=!1m18!1m12!1m3!1d5197.629163722493!2d16.010099410052426!3d49.355657893870166!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x470d6fa82a8afed7%3A0xedd9491075a132a4!2zQ3lrbG8gSmFuw63EjWVr!5e0!3m2!1scs!2scz!4v1537385839639" width="100%" height="460" frameborder="0" style="border:0" allowfullscreen></iframe> </div> <?php endif; ?> <?php if ($this->countModules('contact-form')) : ?> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <div class="contact-form"> <jdoc:include type="modules" name="contact-form" style="xhtml"/> </div> </div> <?php endif; ?> <?php if ($this->countModules('bazar-form')) : ?> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <div id="bazarform" class="contact-form bazar-form"> <jdoc:include type="modules" name="bazar-form-title" style="none"/> <jdoc:include type="modules" name="bazar-form" style="xhtml"/> </div> </div> <?php endif; ?> <?php if ($this->countModules('nad-spodni-listou')) : ?> <div class="nad-spodni-listou"> <jdoc:include type="modules" name="nad-spodni-listou" style="xhtml"/> <div class="greenline"> </div> </div> <?php endif; ?> <?php if ($this->countModules('instagram')) : ?> <div class="instagram"> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <jdoc:include type="modules" name="instagram" style="xhtml"/> <div id="instafeed"></div> <script type="text/javascript"> var feed = new Instafeed({ get: 'user', userId: 2141789648, accessToken: '2141789648.467ede5.98d624315fb24d6e908b1877041a200c' }); feed.run(); </script> </div> </div> <?php endif; ?> <div class="spodni-lista"> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <div class="row"> <div class="span12 lista-icon-phone"> <div class="lista-title">Zákaznická podpora</div> <div class="lista-text"> <span class="phone"><?php echo $params->get('sitephone'); ?></span> </div> </div> </div> </div> </div> </div> <!-- Footer --> <footer class="footer" role="contentinfo"> <div class="container<?php echo($params->get('fluidContainer') ? '-fluid' : ''); ?>"> <div class="row"> <div class="footer-module span4"> <jdoc:include type="modules" name="footer-left" style="xhtml"/> </div> <div class="footer-module span4"> <jdoc:include type="modules" name="footer-middle" style="xhtml"/> </div> <div class="footer-module span4"> <h3>Sledujte nás</h3> <div class="fb-page" data-href="https://www.facebook.com/cyklo.janicek" data-width="288" data-height="227" data-hide-cover="true" data-show-facepile="true" data-show-posts="false"> <div class="fb-xfbml-parse-ignore"> <blockquote cite="https://www.facebook.com/cyklo.janicek"> <a href="https://www.facebook.com/cyklo.janicek"><NAME></a> </blockquote> </div> </div> </div> </div> <div class="row margin-top"> <p class="span8 text-right platebni_metody"> <img src="images/footer_ikonky/logo_visa.png" alt="VISA" title="VISA"/> <img src="images/footer_ikonky/logo_maestro.png" alt="Maestro" title="Maestro"/> <img src="images/footer_ikonky/logo_mastercard.png" alt="MasterCard" title="MasterCard"/> </p> <p class="span4"> <a class="fb-icon" href="https://www.facebook.com/cyklo.janicek" data-placement="top" data-toggle="tooltip" data-original-title="<NAME> na Facebooku"><img src="images/footer_ikonky/icon_fb.png" alt="<NAME> na Facebooku"/></a> <span class="autor bondon">Webdesign by <a href="http://www.bondon-webdesign.cz/">Bondon</a></span> <span class="autor resyst">Created by <a href="http://www.resyst.cz/">ReSyst.cz</a></span> </p> </div> </div> </footer> <jdoc:include type="modules" name="debug" style="none"/> </div> </div> </body> </html> <file_sep>/administrator/components/com_jbcatalog/views/category/tmpl/edit.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; JHtml::addIncludePath(JPATH_COMPONENT . '/helpers/html'); JHtml::_('behavior.tooltip'); JHtml::_('behavior.formvalidation'); JHtml::_('formbehavior.chosen', 'select'); $catfilt[] = JHTML::_('select.option', "0", JText::_('JGLOBAL_USE_GLOBAL'), 'id', 'name' ); $catfilt[] = JHTML::_('select.option', "1", JText::_('JHIDE'), 'id', 'name' ); $catfilt[] = JHTML::_('select.option', "2", JText::_('JSHOW'), 'id', 'name' ); $catjs = JHTML::_('select.genericlist', $catfilt, 'catfilter[]', 'class="inputboxsel" size="1"', 'id', 'name', 0 ); $catjs = preg_replace('~[\r\n]+~', '', $catjs); ?> <script type="text/javascript"> Joomla.submitbutton = function(task) { if (task == 'category.cancel' || document.formvalidator.isValid(document.id('fileupload'))) { <?php echo $this->form->getField('descr')->save(); ?> Joomla.submitform(task, document.getElementById('fileupload')); } } function jsAddFieldGroup(){ var groupid = jQuery('#grouplist').val(); if(groupid == 0){ return false; } jQuery.ajax({ url: "<?php echo juri::base()?>" + "index.php?option=com_jbcatalog&task=adfs.getAdfGroupDetails&tmpl=component&groupid="+groupid+"&catid=<?php echo $this->item->id?>", data: {'<?php echo JSession::getFormToken()?>':'1'} }).done(function(data) { jQuery('.jbgroup'+groupid).remove(); jQuery("#jb_addgroupcat > tbody").append(data); jQuery("#grouplist option[value='"+groupid+"']").remove(); jQuery('#grouplist').chosen(); jQuery('#grouplist').trigger("liszt:updated"); }); } function jsRemoveFieldGroup(gid, gname){ jQuery('.jbgroup'+gid).remove(); jQuery("#grouplist").append('<option value="'+gid+'">'+gname+'</option>'); jQuery('#grouplist').chosen(); jQuery('#grouplist').trigger("liszt:updated"); } function jsAddADField(){ var adfid = jQuery('#adflist').val(); if(adfid == 0){ return false; } var adfname = jQuery("#adflist option:selected").text(); var data = '<tr id="jbadftr_'+adfid+'" style="background-color:#eee;font-style:italic;"><td><input type="hidden" name="jbgroups_adf[]" value="0" /><input type="hidden" name="jbgrfields[]" value="'+adfid+'" /><a href="javascript:void(0);" title="<?php echo JText::_('COM_JBCATALOG_REMOVE')?>" onClick="javascript:jsRemoveADf(\''+adfid+'\',\''+adfname+'\');"><img src="<?php echo JURI::base()?>components/com_jbcatalog/images/publish_x.png" title="<?php echo JText::_('COM_JBCATALOG_REMOVE')?>" /></a></td>'; data += '<td>'+adfname+'</td><td><input type="checkbox" value="1" name="showlist['+adfid+']" /></td>'; data += '<td><?php echo $catjs;?></td></tr>'; jQuery("#jb_addadfcat > tbody").append(data); jQuery("#adflist option[value='"+adfid+"']").remove(); jQuery('#adflist').chosen(); jQuery('#adflist').trigger("liszt:updated"); } function jsRemoveADf(gid, gname){ jQuery("#adflist").append('<option value="'+gid+'">'+gname+'</option>'); jQuery('#adflist').chosen(); jQuery('#adflist').trigger("liszt:updated"); jQuery('#jbadftr_'+gid).remove(); } </script> <form action="<?php echo JRoute::_('index.php?option=com_jbcatalog&layout=edit&id='.(int) $this->item->id); ?>" method="post" name="adminForm" id="fileupload" class="form-validate form-horizontal" enctype="multipart/form-data"> <div class="span10 form-horizontal"> <fieldset> <?php echo JHtml::_('bootstrap.startTabSet', 'myTab', array('active' => 'details')); ?> <?php echo JHtml::_('bootstrap.addTab', 'myTab', 'details', JText::_('COM_JBCATALOG_CATEGORY_DETAILS', true)); ?> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('title'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('title'); ?> </div> </div> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('alias'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('alias'); ?> </div> </div> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('parent_id'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('parent_id'); ?> </div> </div> <div class="control-group"> <div class="control-label"><?php echo $this->form->getLabel('image'); ?></div> <div class="controls"><?php echo $this->form->getInput('image'); ?></div> </div> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('descr'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('descr'); ?> </div> </div> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('id'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('id'); ?> </div> </div> <?php echo JHtml::_('bootstrap.endTab'); ?> <?php echo JHtml::_('bootstrap.addTab', 'myTab', 'fields', JText::_('COM_JBCATALOG_ADDFIELDS', true)); ?> <div> <table id="jb_addgroupcat" class="table" style="width:auto;"> <thead> <tr> <th colspan="2"><?php echo JText::_('COM_JBCATALOG_CAT_ADF_GROUPNAME');?></th> <th><?php echo JText::_('COM_JBCATALOG_CAT_SHOWONLIST');?></th> <th><?php echo JText::_('COM_JBCATALOG_DISPLAY_FILTER');?></th> </tr> </thead> <tbody> <?php if(count($this->grval)){ foreach ($this->grval as $gval){ echo '<tr class="jbgroup'.$gval->id.'" style="background-color:#eee;font-size:130%;">'; echo '<td><a href="javascript:void(0);" title="'.JText::_('COM_JBCATALOG_REMOVE').'" onClick="javascript:jsRemoveFieldGroup(\''.$gval->id.'\', \''.$gval->name.'\');"><img src="'.JURI::base().'components/com_jbcatalog/images/publish_x.png" title="'.JText::_('COM_JBCATALOG_REMOVE').'" /></a></td>'; echo '<td colspan="3"><input type="hidden" name="jbgroups[]" value="'.$gval->id.'" />'.$gval->name.'</td>'; echo '</tr>'; for($i=0; $i < count($gval->adfs); $i++){ echo '<tr class="jbgroup'.$gval->id.'" style="background-color:#fefefe;font-style:italic;">'; echo '<td><input type="hidden" name="jbgroups_adf[]" value="'.$gval->id.'" /><input type="hidden" name="jbgrfields[]" value="'.$gval->adfs[$i]->id.'" /></td>'; echo '<td>'.$gval->adfs[$i]->name.'</td>'; echo '<td><input type="checkbox" value="1" name="showlist['.$gval->adfs[$i]->id.']" '.($gval->adfs[$i]->listview?' checked="checked"':'').' /></td>'; echo '<td>'; echo JHTML::_('select.genericlist', $catfilt, 'catfilter[]', 'class="inputboxsel" size="1"', 'id', 'name', $gval->adfs[$i]->filtered, 'catfilter_'.$gval->adfs[$i]->id ); echo '</td>'; echo '</tr>'; } } } ?> </tbody> <tfoot> <tr> <td colspan="2"> <?php echo $this->grouplist;?> </td> <td colspan="2"> <input type="button" value="<?php echo JText::_('COM_JBCATALOG_ADDNEW_ITEMS');?>" onclick="jsAddFieldGroup();"> </td> </tr> </tfoot> </table> <br /> <hr /> <br > <table id="jb_addadfcat" class="table" style="width:auto;"> <thead> <tr> <th colspan="2"><?php echo JText::_('COM_JBCATALOG_CAT_ADF_FIELDNAME');?></th> <th><?php echo JText::_('COM_JBCATALOG_CAT_SHOWONLIST');?></th> <th><?php echo JText::_('COM_JBCATALOG_DISPLAY_FILTER');?></th> </tr> </thead> <tbody> <?php if(count($this->adfval)){ foreach ($this->adfval as $val){ echo '<tr id="jbadftr_'.$val->id.'" style="background-color:#eee;font-style:italic;">'; echo '<td><input type="hidden" name="jbgroups_adf[]" value="0" /><input type="hidden" name="jbgrfields[]" value="'.$val->id.'" /><a href="javascript:void(0);" title="'.JText::_('COM_JBCATALOG_REMOVE').'" onClick="javascript:jsRemoveADf(\''.$val->id.'\',\''.$val->name.'\');"><img src="'.JURI::base().'components/com_jbcatalog/images/publish_x.png" title="'.JText::_('COM_JBCATALOG_REMOVE').'" /></a></td>'; echo '<td>'.$val->name.'</td>'; echo '<td><input type="checkbox" value="1" name="showlist['.$val->id.']" '.($val->listview?' checked="checked"':'').' /></td>'; echo '<td>'; echo JHTML::_('select.genericlist', $catfilt, 'catfilter[]', 'class="inputboxsel" size="1" id="catfilter_'.$val->id.'"', 'id', 'name', $val->filtered ); echo '</td>'; echo '</tr>'; } } ?> </tbody> <tfoot> <tr> <td colspan="2"> <?php echo $this->adflist;?> </td> <td colspan="2"> <input type="button" value="<?php echo JText::_('COM_JBCATALOG_ADDNEW_ITEMS');?>" onclick="jsAddADField();"> </td> </tr> </tfoot> </table> </div> <?php echo JHtml::_('bootstrap.endTab'); ?> <?php echo JHtml::_('bootstrap.endTabSet'); ?> </fieldset> <input type="hidden" name="task" value="" /> <?php echo JHtml::_('form.token'); ?> </div> <!-- End Newsfeed --> <!-- Begin Sidebar --> <div class="span2"> <h4><?php echo JText::_('JDETAILS');?></h4> <hr /> <fieldset class="form-vertical"> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('published'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('published'); ?> </div> </div> <div class="control-group"> <div class="control-label"> <?php echo $this->form->getLabel('language'); ?> </div> <div class="controls"> <?php echo $this->form->getInput('language'); ?> </div> </div> </fieldset> </div> <!-- End Sidebar --> </form> <file_sep>/modules/mod_jmslideshow/elements/directorysource.php <?php /* #------------------------------------------------------------------------ # Package - JoomlaMan JMSlideShow # Version 1.0 # ----------------------------------------------------------------------- # Author - JoomlaMan http://www.joomlaman.com # Copyright © 2012 - 2013 JoomlaMan.com. All Rights Reserved. # @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later # Websites: http://www.JoomlaMan.com #------------------------------------------------------------------------ */ //-- No direct access defined('_JEXEC') or die('Restricted access'); jimport( 'joomla.html.html' ); class JFormFieldDirectorySource extends JFormField { /** * The form field type. * * @var string * @since 11.1 */ protected $type = 'DirectorySource'; /** * Method to get the field input markup for a generic list. * Use the multiple attribute to enable multiselect. * * @return string The field input markup. * * @since 11.1 */ protected function getInput() { $jsons = json_decode($this->value); $items = $this->processjson($jsons); $doc = JURI::root(); $num_items = count($jsons); $html=''; // Initialize variables. $html .="<script src='{$doc}/modules/mod_jmslideshow/admin/assets/js/jquery.ui.min.js'></script> <script> jQuery('#{$this->id}_url').addClass('s9') jQuery(function() { jQuery( '#image_items' ).sortable(); jQuery( '#image_items' ).disableSelection(); }); </script>"; $html .="<div class='s9'>"; $html .="<div> <input id='addnew' class='btn btn-primary' name='addnew' type='button' value='ADD' onclick='addclick()'/> <input class='btn btn-danger' name='deleteall' type='button' value='DELETE ALL' onclick='deleteallclick()' /> <input id='clear' class='btn btn-warning' name='clear' type='button' value='CLEAR' onclick='clearclick()'/> <input id='{$this->id}' type='hidden' name='{$this->name}' value='{$this->value}'/> <input id='juri' name='juri' type='hidden' value='{$doc}'/> <div class='jm_clear'></div> </div> <div id='image_items' class='clearfix'> {$items} </div>"; $html .="<script> var i = {$num_items}; var json= ''; var item_focus = ''; var id_selected = ''; var jm_juri = jQuery('#juri'); var jm_title = jQuery('#{$this->id}_title'); var jm_link = jQuery('#{$this->id}_title_link'); var jm_desc = jQuery('#{$this->id}_desc'); var jm_url = jQuery('#{$this->id}_url'); var jm_bt_add = jQuery('#addnew'); var jm_bt_clear = jQuery('#clear'); var jm_value = jQuery('#{$this->id}'); clearclick(); function clearclick() { if (jm_bt_clear.val() == 'clear') { jm_title.val(''); jm_desc.val(''); jm_url.val(''); jm_link.val(''); } else { jQuery('#item_'+id_selected+'').css('opacity','1'); jm_bt_clear.val('CLEAR'); jm_bt_add.val('ADD'); jm_title.val(''); jm_desc.val(''); jm_url.val(''); jm_link.val(''); } } function addclick() { if ( jm_bt_add.val() == 'ADD'){ if (jm_url.val() != '') { var _json = '{\"url\":\"'+jm_url.val()+'\",\"title\":\"'+encodeURI(jm_title.val())+'\",\"link\":\"'+encodeURI(jm_link.val())+'\",\"desc\":\"'+encodeURI(jm_desc.val())+'\"}'; var _toolstip = 'Title : '+jm_title.val()+'&#10;Link : '+jm_link.val()+'&#10;Desc : '+jm_desc.val()+''; jQuery('#image_items').append('<div id=item_'+i+' class=jm_items ><img class=jm_img src='+jm_juri.val()+jm_url.val()+' onmousemove=processjson() title=\"'+_toolstip+'\" height=60><button class=jm_button type=button onclick=removeclick('+i+') >remove</button><button id=edit_'+i+' class=jm_button type=button onclick=edititem('+i+') >edit</button><input id=value_'+i+' type=hidden value='+_json+' /><div class=jm_clear></div></div>'); processjson(); addEffect('item_'+i+''); i++; } else { alert('Select one image'); } } else { item_focus.focus(); var _json = '{\"url\":\"'+jm_url.val()+'\",\"title\":\"'+encodeURI(jm_title.val())+'\",\"link\":\"'+encodeURI(jm_link.val())+'\",\"desc\":\"'+encodeURI(jm_desc.val())+'\"}'; var _toolstip = 'Title:'+jm_title.val()+'&#10;Link:'+jm_link.val()+'&#10;Desc:'+jm_desc.val()+''; jQuery('#item_'+id_selected+'').html('<img class=jm_img src='+jm_juri.val()+jm_url.val()+' onmousemove=processjson() title=\"'+_toolstip+'\" height=60><button class=jm_button type=button onclick=removeclick('+id_selected+') >remove</button><button id=edit_'+id_selected+' class=jm_button type=button onclick=edititem('+id_selected+') >edit</button><input id=value_'+id_selected+' type=hidden value='+_json+' /><div class=jm_clear></div>'); processjson(); runEffect('item_'+id_selected); id_selected = ''; } clearclick(); jm_bt_add.val('ADD'); jm_bt_clear.val('CLEAR'); } function removeclick(id) { jQuery('#item_'+id+'').addClass('bounceOut animatedbounceOut'); setTimeout(function() { jQuery('#item_'+id+'').remove(); processjson(); }, 1000); } function deleteallclick() { var elem = document.getElementById('image_items'); json = ''; jm_value.val(''); while(elem.firstChild) { elem.removeChild(elem.firstChild); } } function processjson() { json = ''; var s = ','; jQuery('#image_items input').each(function() { var type = jQuery(this).attr('type'); if (type == 'hidden'){ json += jQuery(this).val()+s; } }); _chars = '},]'; json = '['+json+']'; jm_value.val(json.replace(_chars,'}]')); } function edititem(id) { item_focus = jQuery('#edit_'+id+''); if (id_selected != ''){ jQuery('#item_'+id_selected+'').css('opacity','1'); } id_selected = id; var json_obj = JSON.parse(jQuery('#value_'+id+'').val()); jm_bt_add.val('SAVE'); jm_bt_clear.val('CANCEL'); jm_title.val(decodeURI(json_obj.title)); jm_desc.val(decodeURI(json_obj.desc)); jm_url.val(json_obj.url); jm_link.val(decodeURI(json_obj.link)); jm_url.focus(); jQuery('#item_'+id_selected+'').css('opacity','0.4'); } function runEffect(item) { jQuery('#'+item+'').css('opacity','1'); jQuery('#'+item+'').addClass('flipInY animated'); setTimeout(function() { jQuery('#'+item+'').removeClass('flipInY animated'); }, 1000); } function addEffect(item) { jQuery('#'+item+'').addClass('bounceInDown animatedbounceInDown'); setTimeout(function() { jQuery('#'+item+'').removeClass('bounceInDown animatedbounceInDown'); }, 1000); } </script>"; $html .="</div>"; return $html; } private function processjson($jsons) { $html =''; if(count($jsons)>0){ foreach ($jsons as $i => $item) { $json = json_encode($item); $_toolstip = 'Title : '.urldecode($item->title).'&#10;Link : '.urldecode($item->link).'&#10;Desc : '.urldecode($item->desc); $_url = JURI::root().$item->url; $html .= "<div id=item_{$i} class='jm_items' ><img class='jm_img' src='{$_url}' alt='' title='{$_toolstip}' onmousemove=processjson() height=60><button class=jm_button type=button onclick=removeclick('{$i}') >remove</button><button id=edit_{$i} class=jm_button type=button onclick=edititem('{$i}') >edit</button><input id=value_{$i} type=hidden value={$json} /><div class='jm_clear'></div></div>"; } } return $html; } }<file_sep>/templates/cyklo/html/mod_articles_news/horizontal.php <?php /** * upraveny modul pro zobrazeni znacek vyrobcu s popisky * @author <EMAIL> <<EMAIL>> */ defined('_JEXEC') or die; ?> <div class="newsflash-horiz <?php echo $params->get('moduleclass_sfx'); ?>"> <?php for ($i = 0, $n = count($list); $i < $n; $i ++) { $item = $list[$i]; $article_images = json_decode($item->images); ?> <div class="span4"> <div class="znacka-wrapper"> <div class="znacka-logo" <?php if (!empty($article_images->image_intro)) { ?> style="background: transparent url(<?php echo JURI::base() . $article_images->image_intro; ?>) no-repeat 50% 50%;"<?php } ?>> <div class="znacka-popis"> <?php require JModuleHelper::getLayoutPath('mod_articles_news', '_item'); ?> </div> </div> </div> </div> <?php } ?> <div class="clearfix"></div> </div> <file_sep>/administrator/language/cs-CZ/cs-CZ.com_jbcatalog.sys.ini COM_JBCATALOG_ITEM="Položka" COM_JBCATALOG_ITEM_OPTION="Nastavení položky" COM_JBCATALOG_ITEM_DESC="Detail položky" COM_JBCATALOG_CATEGORY="Seznam položek v kategorii" COM_JBCATALOG_CATEGORY_OPTION="Zobrazí všechny položky ve vybrané kategorii" COM_JBCATALOG_CATEGORY_DESC="Zobrazí všechny položky ve vybrané kategorii" COM_JBCATALOG_ALL_CATEGORIES="Všechny kategorie" COM_JBCATALOG_LIST="Seznam kategorií" COM_JBCATALOG_LIST_OPTION="Seznam kategorií" COM_JBCATALOG_LIST_DESC="Zobrazí seznam kategorií" COM_JBCATALOG="JBCatalog" COM_JBCATALOG_DESC="JBcatalog - doplněk pro webový katalog" COM_JBCATALOG_CATEGOTIES="Kategorie" COM_JBCATALOG_ITEMS="Položky" COM_JBCATALOG_ADFGROUPS="Skupiny vlastností" COM_JBCATALOG_ADFS="Vlastnosti položek" COM_JBCATALOG_PLUGINS="Pluginy" COM_JBCATALOG_SELECT_CATEGORY="Vyberte kategorii"<file_sep>/administrator/components/com_jbcatalog/elements/bearlist.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined( '_JEXEC' ) or die( 'Restricted access' ); class JFormFieldbearlist extends JFormField { protected $type = 'bearlist'; public function getInput() { $value=$this->value; $db = JFactory::getDBO(); $db->setQuery($this->element['sql']); $key = ($this->element['key_field']? $this->element['key_field'] : 'value'); $val = ($this->element['value_field'] ?$this->element['value_field'] : 'name'); $options = array(); $rows = $db->loadObjectList(); if($this->element['default'] == ''){ $options = $rows; }else{ $options[] = JHTML::_('select.option', "", $this->element['default'], $key, $val ); if(count($rows)){ $options = array_merge($options,$rows); } } if($options) { return JHTML::_('select.genericlist',$options, $this->name,'', $key, $val, $value, $this->name); } } } ?><file_sep>/administrator/components/com_jbcatalog/models/items.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogModelItems extends JModelList { public function __construct($config = array()) { if (empty($config['filter_fields'])) { $config['filter_fields'] = array( 'id', 'a.id', 'menutype', 'a.menutype', 'title', 'a.title', 'alias', 'a.alias', 'published', 'a.published', 'access', 'a.access', 'access_level', 'language', 'a.language', 'checked_out', 'a.checked_out', 'checked_out_time', 'a.checked_out_time', 'lft', 'a.lft', 'rgt', 'a.rgt', 'level', 'a.level', 'path', 'a.path', 'client_id', 'a.client_id', 'home', 'a.home', ); $app = JFactory::getApplication(); $assoc = isset($app->item_associations) ? $app->item_associations : 0; if ($assoc) { $config['filter_fields'][] = 'association'; } } parent::__construct($config); } /** * Builds an SQL query to load the list data. * * @return JDatabaseQuery A query object. */ protected function getListQuery() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); $user = JFactory::getUser(); $app = JFactory::getApplication(); // Select all fields from the table. $query->select( $this->getState( 'list.select', $db->quoteName( array('a.id', 'a.title', 'a.alias','a.published','a.descr','a.ordering'), array(null, null, null, null, null, null) ) ) ); $query->from($db->quoteName('#__jbcatalog_items') . ' AS a'); $query->leftJoin($db->quoteName('#__jbcatalog_items_cat') .' AS b ON b.item_id = a.id'); $query->group("a.id"); // Exclude the root category. //$query->where('a.id > 1'); // Filter on the published state. $published = $this->getState('filter.published'); if (is_numeric($published)) { $query->where('a.published = ' . (int) $published); } elseif ($published === '') { $query->where('(a.published IN (0, 1))'); } $catid = $this->getState('filter.catid'); if (is_numeric($catid)) { $query->where('b.cat_id = ' . (int) $catid); } // Filter by search in title, alias or id if ($search = trim($this->getState('filter.search'))) { if (stripos($search, 'id:') === 0) { $query->where('a.id = ' . (int) substr($search, 3)); } else { $search = $db->quote('%' . $db->escape($search, true) . '%'); $query->where('(' . 'a.title LIKE ' . $search . ' OR a.alias LIKE ' . $search . ')'); } } // Add the list ordering clause. $query->order($db->escape($this->getState('list.ordering', 'a.ordering')) . ' ' . $db->escape($this->getState('list.direction', 'ASC'))); //echo nl2br(str_replace('#__','jos_',(string)$query)).'<hr/>'; return $query; } protected function populateState($ordering = null, $direction = null) { $published = $this->getUserStateFromRequest($this->context . '.published', 'filter_published', ''); $this->setState('filter.published', $published); $search = $this->getUserStateFromRequest($this->context . '.search', 'filter_search'); $this->setState('filter.search', $search); $catid = $this->getUserStateFromRequest($this->context . '.catid', 'filter_catid'); $this->setState('filter.catid', $catid); // List state information. parent::populateState('a.ordering', 'asc'); } public function getCats(){ $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select('a.id AS value, a.title AS text, a.level') ->from('#__jbcatalog_category AS a') ->join('LEFT', $db->quoteName('#__jbcatalog_category') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt'); // Prevent parenting to children of this item. /* if ($id = $this->form->getValue('id')) { $query->join('LEFT', $db->quoteName('#__jbcatalog_category') . ' AS p ON p.id = ' . (int) $id) ->where('NOT(a.lft >= p.lft AND a.rgt <= p.rgt)'); }*/ $query->where('a.published != -2 AND a.parent_id != 0') ->group('a.id, a.title, a.level, a.lft, a.rgt, a.parent_id, a.published') ->order('a.lft ASC'); // Get the options. $db->setQuery($query); try { $options = $db->loadObjectList(); } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); } // Pad the option text with spaces using depth level as a multiplier. for ($i = 0, $n = count($options); $i < $n; $i++) { $options[$i]->text = str_repeat('- ', $options[$i]->level) . $options[$i]->text; } return $options; } } <file_sep>/components/com_jbcatalog/views/category/tmpl/default_items_table.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; /*plugins*/ JHTML::_('behavior.modal'); if(isset($this->customplugins['script']) && $this->customplugins['script']){ echo $this->customplugins['script']; } /*-*/ echo '<table class="jb_catlist">'; if(count($this->items)){ /*plugins */ if(isset($this->customplugins['head']) && $this->customplugins['head']){ echo $this->customplugins['head']; } /*-*/ echo '<th>&nbsp;</th>'; echo '<th>'.JText::_('COM_JBCATALOG_TITLE').'</th>'; if(isset($this->items[0]->fieldsname) && count($this->items[0]->fieldsname)){ foreach($this->items[0]->fieldsname as $fld){ echo "<th>".$fld->name."</th>"; } } echo '</tr>'; } for($i=0;$i<count($this->items);$i++){ echo "<tr class='jbitemlist'>";//"<div class='jbitemlist'>"; /*plugins*/ if(isset($this->customplugins['checkbox'][$i]) && $this->customplugins['checkbox'][$i]){ echo $this->customplugins['checkbox'][$i]; } /*-*/ echo "<td style='padding:10px 0px;width:60px;text'><div class='catimg_div'>";//"<div class='catimg_div'>"; //echo "<div><a href='index.php?option=com_jbcatalog&view=item&id=".$this->items[$i]->id."'>".$this->items[$i]->title."</a></div>"; if(isset($this->items[$i]->images) && count($this->items[$i]->images)){ echo "<a href='".JRoute::_("index.php?option=com_jbcatalog&view=item&catid=".$this->catid."&id=".$this->items[$i]->id)."'><img src='". JBCatalogImages::getImg($this->items[$i]->images[0], true)."'></a>"; } echo "</div></td>"; echo "<td>";//"<div class='catinfo_div'>"; echo "<div><a href='".JRoute::_("index.php?option=com_jbcatalog&view=item&catid=".$this->catid."&id=".$this->items[$i]->id)."'>".$this->items[$i]->title."</a></div>"; echo "</td>"; if(isset($this->items[$i]->fields) && count($this->items[$i]->fields)){ foreach($this->items[$i]->fields as $fld){ echo "<td>".$fld."</td>"; } } echo "</tr>"; } /*plugins*/ if(isset($this->customplugins['bottom']) && $this->customplugins['bottom']){ echo $this->customplugins['bottom']; } /*-*/ echo '</table>'; ?><file_sep>/modules/mod_jmslideshow/script.php <?php /** * @package com_jm_video_galleries * @version 1.0.0 * Author - JoomlaMan http://www.joomlaman.com * Copyright (C) 2012 - 2013 JoomlaMan.com. All Rights Reserved. * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later * Websites: http://www.JoomlaMan.com * Support: <EMAIL> */ // No direct access to this file defined('_JEXEC') or die('Restricted access'); class mod_jmslideshowInstallerScript { /** * method to install the component * * @return void */ function install($parent) { } /** * method to uninstall the component * * @return void */ function uninstall($parent) { // $parent is the class calling this method } /** * method to update the component * * @return void */ function update($parent) { $db = JFactory::getDbo(); $query = "DELETE FROM #__update_sites WHERE location LIKE 'http://project.joomexp.com/nhk/testupdate/extension.xml'"; $db->setQuery($query); $db->query(); // $parent is the class calling this method } /** * method to run before an install/update/uninstall method * * @return void */ function preflight($type, $parent) { // $parent is the class calling this method // $type is the type of change (install, update or discover_install) } /** * method to run after an install/update/uninstall method * * @return void */ function postflight($type, $parent) { // $parent is the class calling this method // $type is the type of change (install, update or discover_install) } } <file_sep>/administrator/components/com_jbcatalog/jbcatalog.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; if (!JFactory::getUser()->authorise('core.manage', 'com_jbcatalog')) { return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR')); } // Execute the task. $controller = JControllerLegacy::getInstance('JBCatalog'); $controller->execute(JFactory::getApplication()->input->get('task')); $controller->redirect(); <file_sep>/modules/mod_jmslideshow/helper.php <?php /* #------------------------------------------------------------------------ # Package - JoomlaMan JMSlideShow # Version 1.0 # ----------------------------------------------------------------------- # Author - JoomlaMan http://www.joomlaman.com # Copyright © 2012 - 2013 JoomlaMan.com. All Rights Reserved. # @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later # Websites: http://www.JoomlaMan.com #------------------------------------------------------------------------ */ //-- No direct access defined('_JEXEC') or die('Restricted access'); class modJmSlideshowHelper { static function getSlides($params) { $slidesource = $params->get('slider_source', 1); switch ($slidesource) { case 1: return modJmSlideshowHelper::getSlidesFromCategories($params); break; case 2: return modJmSlideshowHelper::getSlidesFromArticleIDs($params); break; case 3: return modJmSlideshowHelper::getSlidesFromK2Categories($params); break; case 4: return modJmSlideshowHelper::getSlidesFromK2IDs($params); break; case 5: return modJmSlideshowHelper::getSlidesFromCategoriesProduct($params); break; case 6: return modJmSlideshowHelper::getSlidesFromProductIDs($params); break; case 7: return modJmSlideshowHelper::getSlidesFeatured($params); break; case 8: return modJmSlideshowHelper::getSlidesK2Featured($params); break; case 9: return modJmSlideshowHelper::getSlidesFromFile($params); break; case 10: return modJmSlideshowHelper::getSlidesFromFoder($params); break; } } /* static function getThumbnail($sliders){ $thumbnails=array(); if(count($sliders)>0){ foreach($sliders as $slider){ // $thumbnails[] } } return $thumbnails; }*/ static function getSlidesFromFile($params){ $slides = array(); $images = json_decode($params->get('jmslideshow_file_image')); $limit = $params->get('jmslideshow_count', 0); foreach ($images as $i=>$image) { if ($limit > 0 && $i <= ($limit-1)) { $slide = new JMSlide($params); $slide->loadFileImages($image); $slides[] = $slide; } elseif($limit <= 0 ) { $slide = new JMSlide($params); $slide->loadFileImages($image); $slides[] = $slide; } } return $slides; } static function getSlidesFromFoder($params){ $slides = array(); $dir = $params->get('jmslideshow_foder_image', 'images'); $limit = $params->get('jmslideshow_count', 0); if(is_dir(JPATH_SITE.DS.$dir)){ $imagesDir = JPATH_SITE.DS.$dir.DS; $exts = array('jpg','jpeg','png','gif','JPG','JPGE','PNG','GIF'); $images = array(); foreach ($exts as $ext){ $tmp = glob($imagesDir.'*.'.$ext); $images = array_merge($images, $tmp); } if (empty($images)) { return $slides; } foreach ($images as $i=>$image) { if ($limit > 0 && $i <= ($limit-1)) { $slide = new JMSlide($params); $slide->loadImages($image); $slides[] = $slide; } elseif($limit <= 0 ) { $slide = new JMSlide($params); $slide->loadImages($image); $slides[] = $slide; } } return $slides; }else{ echo "Folder does not exist or not accessible: <b>".JPATH_SITE.DS.$dir."</b>"; } } static function getSlidesFromCategories($params) { $limit = $params->get('jmslideshow_count', 0); $categories = $params->get('jmslideshow_categories', array()); $categories = implode(',', $categories); $db = JFactory::getDbo(); $ordering = $params->get('jmslideshow_ordering','ASC'); $orderby = $params->get('jmslideshow_orderby',1); if($orderby==1){$field = 'c.title';} elseif($orderby==2){$field = 'c.ordering';} else{$field = 'c.id';} $query = $db->getQuery(true) ->select("c.id") ->from("#__content AS c") ->where("c.catid IN({$categories})") ->where("c.state > 0") ->order($field.' '.$ordering); if ($limit > 0) { $db->setQuery($query, 0, $limit); } else { $db->setQuery($query); } $rows = $db->loadObjectList(); $slides = array(); if (empty($rows)) { return $slides; } foreach ($rows as $row) { $slide = new JMSlide($params); $slide->loadArticle($row->id); $slides[] = $slide; } return $slides; } static function getSlidesFromArticleIDs($params) { $ids = $params->get('jmslideshow_article_ids', ''); $ids = str_replace(' ', '', $ids); $db = JFactory::getDbo(); $ordering = $params->get('jmslideshow_ordering','ASC'); $orderby = $params->get('jmslideshow_orderby',1); if($orderby==1){$field = 'c.title';} elseif($orderby==2){$field = 'c.ordering';} else{$field = 'c.id';} $query = $db->getQuery(true) ->select("c.id") ->from("#__content AS c") ->where("c.state > 0") ->where("c.id IN ({$ids})") ->order($field.' '.$ordering); $db->setQuery($query); $rows = $db->loadObjectList(); if (empty($rows)) { return $slides; } foreach ($rows as $row) { $slide = new JMSlide($params); $slide->loadArticle($row->id); $slides[] = $slide; } return $slides; } static function getSlidesFeatured($params) { $limit = $params->get('jmslideshow_count', 0); $db = JFactory::getDbo(); $ordering = $params->get('jmslideshow_ordering','ASC'); $orderby = $params->get('jmslideshow_orderby',1); if($orderby==1){$field = 'c.title';} elseif($orderby==2){$field = 'cf.ordering';} else{$field = 'c.id';} $query = $db->getQuery(true) ->select("c.id") ->from("#__content AS c") ->innerJoin("#__content_frontpage as cf ON c.id = cf.content_id") ->where("c.state > 0") ->where("c.featured = 1") ->order($field.' '.$ordering); if ($limit > 0) { $db->setQuery($query, 0, $limit); } else { $db->setQuery($query); } $rows = $db->loadObjectList(); $slides = array(); if (empty($rows)) { return $slides; } foreach ($rows as $row) { $slide = new JMSlide($params); $slide->loadArticle($row->id); $slides[] = $slide; } return $slides; } static function getSlidesFromCategoriesProduct($params) { $limit = $params->get('jmslideshow_count', 0); $categories = $params->get('jmslideshow_hikashop_categories', array()); $categories = implode(',', $categories); $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select("p.product_id") ->from("#__hikashop_product AS p") ->leftjoin("#__hikashop_product_category AS c ON p.product_id = c.product_id") ->where("c.category_id IN({$categories})") ->where("p.product_published > 0"); if ($limit > 0) { $db->setQuery($query, 0, $limit); } else { $db->setQuery($query); } $rows = $db->loadObjectList(); $slides = array(); if (empty($rows)) { return $slides; } foreach ($rows as $row) { $slide = new JMSlide($params); $slide->loadProduct($row->product_id); $slides[] = $slide; } return $slides; } static function getSlidesFromProductIDs($params) { $ids = $params->get('jmslideshow_hikashop_ids', ''); $ids = str_replace(' ', '', $ids); if (empty($ids)) return $slides; $ids = explode(',', $ids); $slides = array(); if (empty($ids)) return $slides; foreach ($ids as $id) { $slide = new JMSlide($params); $slide->loadProduct($id); $slides[] = $slide; } return $slides; } static function getSlidesFromK2Categories($params) { $limit = $params->get('jmslideshow_count', 0); $categories = $params->get('jmslideshow_k2_categories', array()); $categories = implode(',', $categories); $ordering = $params->get('jmslideshow_ordering','ASC'); $orderby = $params->get('jmslideshow_orderby',1); if($orderby==1){$field = 'k2.title';} elseif($orderby==2){$field = 'k2.ordering';} else{$field = 'k2.id';} $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select("k2.id") ->from("#__k2_items AS k2") ->where("k2.catid IN({$categories})") ->where("k2.published = 1") ->where("k2.trash = 0") ->order($field.' '.$ordering); if ($limit > 0) { $db->setQuery($query, 0, $limit); } else { $db->setQuery($query); } $rows = $db->loadObjectList(); $slides = array(); if (empty($rows)) { return $slides; } //print_r($rows); foreach ($rows as $row) { $slide = new JMSlide($params); $slide->loadK2($row->id); if($slide->image) $slides[] = $slide; } //print_r($slides); return $slides; } static function getSlidesFromK2IDs($params) { $ids = $params->get('jmslideshow_k2_ids', ''); $ids = str_replace(' ', '', $ids); $db = JFactory::getDbo(); $ordering = $params->get('jmslideshow_ordering','ASC'); $orderby = $params->get('jmslideshow_orderby',1); if($orderby==1){$field = 'k2.title';} elseif($orderby==2){$field = 'k2.ordering';} else{$field = 'k2.id';} $query = $db->getQuery(true) ->select("k2.id") ->from("#__k2_items AS k2") ->where("k2.featured = 1") ->where("k2.id IN ({$ids})") ->where("k2.published = 1") ->where("k2.trash = 0") ->order($field.' '.$ordering); $db->setQuery($query); $rows = $db->loadObjectList(); if (empty($rows)) { return $slides; } foreach ($rows as $row) { $slide = new JMSlide($params); $slide->loadK2($row->id); if($slide->image) $slides[] = $slide; } return $slides; } static function getSlidesK2Featured($params) { $limit = $params->get('jmslideshow_count', 0); $categories = $params->get('jmslideshow_k2_categories', array()); $categories = implode(',', $categories); $db = JFactory::getDbo(); $ordering = $params->get('jmslideshow_ordering','ASC'); $orderby = $params->get('jmslideshow_orderby',1); if($orderby==1){$field = 'k2.title';} elseif($orderby==2){$field = 'k2.ordering';} else{$field = 'k2.id';} $query = $db->getQuery(true) ->select("k2.id") ->from("#__k2_items AS k2") ->where("k2.featured = 1") ->where("k2.published = 1") ->where("k2.trash = 0") ->order($field.' '.$ordering); if ($limit > 0) { $db->setQuery($query, 0, $limit); } else { $db->setQuery($query); } $rows = $db->loadObjectList(); $slides = array(); if (empty($rows)) { return $slides; } foreach ($rows as $row) { $slide = new JMSlide($params); $slide->loadK2($row->id); if($slide->image) $slides[] = $slide; } return $slides; } static function getTemplate(){ $db=JFactory::getDBO(); $query=$db->getQuery(true); $query->select('*'); $query->from('#__template_styles'); $query->where('home=1'); $query->where('client_id=0'); $db->setQuery($query); return $db->loadObject()->template; } }<file_sep>/language/en-GB/en-GB.com_jbcatalog.ini COM_JBCATALOG_SELECT="Select" COM_JBCATALOG_FILTER_APPLY="Apply Filter" COM_JBCATALOG_ITEM_TAB="Main" COM_JBCATALOG_SELCAT="Select Category" COM_JBCATALOG_TO="To" COM_JBCATALOG_FROM="From" COM_JBCATALOG_FE_NOT_RATED="Not rated" COM_JBCATALOG_FILTERS="Filters" COM_JBCATALOG_FILTER_CLEAR="Clear" COM_JBCATALOG_SAVEDSUCC="Succesfully saved" COM_JBCATALOG_TITLE="Title"<file_sep>/modules/mod_jmslideshow/elements/hikashopmulticategories.php <?php /* #------------------------------------------------------------------------ # Package - JoomlaMan JMSlideShow # Version 1.0 # ----------------------------------------------------------------------- # Author - JoomlaMan http://www.joomlaman.com # Copyright © 2012 - 2013 JoomlaMan.com. All Rights Reserved. # @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later # Websites: http://www.JoomlaMan.com #------------------------------------------------------------------------ */ //-- No direct access defined('_JEXEC') or die('Restricted access'); jimport('joomla.html.html'); jimport('joomla.form.formfield'); class JFormFieldHikashopmulticategories extends JFormFieldList { protected $type = 'Hikashopmulticategories'; //the form field type var $options = array(); protected function getInput() { // Initialize variables. $html = array(); $attr = ''; $attr .= $this->element['size'] ? ' size="'.(int) $this->element['size'].'"' : ''; $attr .= $this->multiple ? ' multiple="multiple"' : ''; $attr .= $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; // Get the field options. $options = (array) $this->getOptions(); // Create a read-only list (no name) with a hidden input to store the value. if ((string) $this->element['readonly'] == 'true') { $html[] = JHtml::_('select.genericlist', $options, '', trim($attr), 'value', 'text', $this->value, $this->id); $html[] = '<input type="hidden" name="'.$this->name.'" value="'.$this->value.'"/>'; } // Create a regular list. else { $html[] = JHtml::_('select.genericlist', $options, $this->name, trim($attr), 'value', 'text', $this->value, $this->id); } return implode($html); } protected function getOptions() { // Initialize variables. $session = JFactory::getSession(); $db = JFactory::getDBO(); $query = "SELECT extension_id FROM #__extensions WHERE name IN('hikashop') AND type='component'"; $db->setQuery($query); $result = $db->loadResult(); if(empty($result)){ return array(); } // generating query $db->setQuery("SELECT c.category_name AS name, c.category_id AS id, c.category_parent_id AS parents FROM #__hikashop_category AS c WHERE category_published = 1 ORDER BY c.category_name, c.category_parent_id ASC"); // getting results $results = $db->loadObjectList(); if(count($results)){ // iterating $temp_options = array(); foreach ($results as $item) { //print_r($item); array_push($temp_options, array($item->id, $item->name, $item->parents)); } foreach ($temp_options as $option) { //print_r($option); if($option[2] == 1) { $this->options[] = JHtml::_('select.option', $option[0], $option[1]); $this->recursive_options($temp_options, 1, $option[0]); } } return $this->options; } else { return $this->options; } } // bind function to save function bind( $array, $ignore = '' ) { if (key_exists( 'field-name', $array ) && is_array( $array['field-name'] )) { $array['field-name'] = implode( ',', $array['field-name'] ); } return parent::bind( $array, $ignore ); } function recursive_options($temp_options, $level, $parent){ foreach ($temp_options as $option) { if($option[2] == $parent) { $level_string = ''; for($i = 0; $i < $level; $i++) $level_string .= '- - '; $this->options[] = JHtml::_('select.option', $option[0], $level_string . $option[1]); $this->recursive_options($temp_options, $level+1, $option[0]); } } } } <file_sep>/administrator/components/com_jbcatalog/models/adf.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogModelAdf extends JModelAdmin { protected $text_prefix = 'COM_JBCATALOG_ADF'; public function getForm($data = array(), $loadData = true) { // Get the form. $form = $this->loadForm('com_jbcatalog.adf', 'adf', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } // Determine correct permissions to check. if ($this->getState('adf.id')) { // Existing record. Can only edit in selected categories. $form->setFieldAttribute('catid', 'action', 'core.edit'); } else { // New record. Can only create in selected categories. $form->setFieldAttribute('catid', 'action', 'core.create'); } // Modify the form based on access controls. if (!$this->canEditState((object) $data)) { // Disable fields for display. $form->setFieldAttribute('ordering', 'disabled', 'true'); $form->setFieldAttribute('publish_up', 'disabled', 'true'); $form->setFieldAttribute('publish_down', 'disabled', 'true'); $form->setFieldAttribute('state', 'disabled', 'true'); $form->setFieldAttribute('sticky', 'disabled', 'true'); // Disable fields while saving. // The controller has already verified this is a record you can edit. $form->setFieldAttribute('ordering', 'filter', 'unset'); $form->setFieldAttribute('publish_up', 'filter', 'unset'); $form->setFieldAttribute('publish_down', 'filter', 'unset'); $form->setFieldAttribute('state', 'filter', 'unset'); $form->setFieldAttribute('sticky', 'filter', 'unset'); } return $form; } public function getTable($type = 'Adf', $prefix = 'JBCatalogTable', $config = array()) { return JTable::getInstance($type, $prefix, $config); } public function save($data) { $pk = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('adf.id'); $isNew = true; $table = $this->getTable(); // Load the row if saving an existing item. if ($pk > 0) { $table->load($pk); $isNew = false; } // Bind the data. if (!$table->bind($data)) { $this->setError($table->getError()); return false; } // Alter the title & alias for save as copy. Also, unset the home record. if (!$isNew && $data['id'] == 0) { list($title, $alias) = $this->generateNewTitle($table->parent_id, $table->alias, $table->title); $table->title = $title; $table->alias = $alias; $table->published = 0; } // Check the data. if (!$table->check()) { $this->setError($table->getError()); return false; } // Store the data. if (!$table->store()) { $this->setError($table->getError()); return false; } $this->setState('adf.id', $table->id); $db = JFactory::getDbo(); //adf groups $db->setQuery("DELETE FROM #__jbcatalog_adf_ingroups WHERE adfid={$table->id}"); $db->execute(); if(isset($data['group_id']) && count($data['group_id'])){ foreach($data['group_id'] as $groupid){ $db->setQuery("INSERT INTO #__jbcatalog_adf_ingroups(adfid,groupid)" ." VALUES({$table->id}, ".intval($groupid).")"); $db->execute(); } } //plugin save require_once JPATH_COMPONENT.DIRECTORY_SEPARATOR."plugins".DIRECTORY_SEPARATOR."plugins.php"; $pl = new ParsePlugins('adf', $table->field_type); $pl->getData('saveAdfData', array("adfid" => $table->id)); // Load associated menu items $app = JFactory::getApplication(); $assoc = isset($app->item_associations) ? $app->item_associations : 0; if ($assoc) { // Adding self to the association $associations = $data['associations']; foreach ($associations as $tag => $id) { if (empty($id)) { unset($associations[$tag]); } } // Detecting all item menus $all_language = $table->language == '*'; if ($all_language && !empty($associations)) { JError::raiseNotice(403, JText::_('COM_MENUS_ERROR_ALL_LANGUAGE_ASSOCIATED')); } $associations[$table->language] = $table->id; // Deleting old association for these items $db = JFactory::getDbo(); $query = $db->getQuery(true) ->delete('#__associations') ->where('context=' . $db->quote('com_jbcatalog.adf')) ->where('id IN (' . implode(',', $associations) . ')'); $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { $this->setError($e->getMessage()); return false; } if (!$all_language && count($associations) > 1) { // Adding new association for these items $key = md5(json_encode($associations)); $query->clear() ->insert('#__associations'); foreach ($associations as $tag => $id) { $query->values($id . ',' . $db->quote('com_jbcatalog.adf') . ',' . $db->quote($key)); } $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { $this->setError($e->getMessage()); return false; } } } // Clean the cache $this->cleanCache(); return true; } public function getItem($pk = null) { if ($item = parent::getItem($pk)) { // Convert the metadata field to an array. /*$registry = new JRegistry; $registry->loadString($item->metadata); $item->metadata = $registry->toArray();*/ } // Load associated contact items $app = JFactory::getApplication(); $assoc = isset($app->item_associations) ? $app->item_associations : 0; if ($assoc) { $item->associations = array(); if ($item->id != null) { $associations = JLanguageAssociations::getAssociations('com_jbcatalog', '#__jbcatalog_adf', 'com_jbcatalog.adf', $item->id); foreach ($associations as $tag => $association) { $item->associations[$tag] = $association->id; } } } $db = JFactory::getDbo(); $query = "SELECT a.id" ." FROM #__jbcatalog_adfgroup as a" ." JOIN #__jbcatalog_adf_ingroups as b" ." ON b.groupid = a.id" ." WHERE b.adfid = ".intval($item->id) ." ORDER BY a.name"; $db->setQuery($query); $item->group_id = $db->loadColumn(); return $item; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 1.6 */ protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_jbcatalog.edit.adf.data', array()); if (empty($data)) { $data = $this->getItem(); // Prime some default values. if ($this->getState('adf.id') == 0) { $app = JFactory::getApplication(); // $data->set('catid', $app->input->get('catid', $app->getUserState('com_jbcatalog.category.filter.category_id'), 'int')); } } $this->preprocessData('com_jbcatalog.adf', $data); return $data; } public function publish(&$pks, $value = 1) { $table = $this->getTable(); $pks = (array) $pks; // Clean the cache $this->cleanCache(); // Ensure that previous checks doesn't empty the array if (empty($pks)) { return true; } return parent::publish($pks, $value); } public function getSelVars($pk = null){ $adf_id = (int) $this->getState('adf.id'); $db = JFactory::getDbo(); $db->setQuery( "SELECT * FROM #__jbcatalog_adf_select" ." WHERE field_id = ".$adf_id ." ORDER BY ordering" ); return $db->loadObjectList(); } public function getComplexVars($pk = null){ //$adf_id = (int) $this->getState('adf.id'); $db = JFactory::getDbo(); $db->setQuery( "SELECT id,name FROM #__jbcatalog_complex" ." WHERE level = 1" ." AND published != -2" ." ORDER BY lft" ); return $db->loadObjectList(); } function trash($cid){ $db = JFactory::getDbo(); if(count($cid)){ foreach ($cid as $id){ $db->setQuery( "DELETE FROM #__jbcatalog_adf" ." WHERE id = ".intval($id) ); $db->execute(); $db->setQuery( "DELETE FROM #__jbcatalog_adf_values" ." WHERE adf_id = ".intval($id) ); $db->execute(); $db->setQuery( "DELETE FROM #__jbcatalog_adf_select" ." WHERE field_id = ".intval($id) ); $db->execute(); } } } public function getPlugins($pk = null){ $adf_id = (int) $this->getState('adf.id'); require_once JPATH_COMPONENT.DIRECTORY_SEPARATOR."plugins".DIRECTORY_SEPARATOR."plugins.php"; $pl = new ParsePlugins('adf'); $plugin['js_selected'] = $pl->getData('getAdfViewJSSelected'); $plugin['js'] = $pl->getData('getAdfViewJS'); $plugin['js_selected_pre'] = $pl->getData('getAdfViewJSSelectedPre'); $plugin['adf_extra'] = $pl->getData('getAdfViewExtra', array("adfid" => $adf_id)); return $plugin; } } <file_sep>/administrator/components/com_jbcatalog/helpers/images.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class ImagesHelper { private static function filesize_get($file) { if (!file_exists($file)) return "File doesn't exist"; $filesize = filesize($file); if ($filesize > 1024) { $filesize = ($filesize / 1024); if ($filesize > 1024) { $filesize = ($filesize / 1024); if ($filesize > 1024) { $filesize = ($filesize / 1024); $filesize = round($filesize, 1); return $filesize . " GB"; } else { $filesize = round($filesize, 1); return $filesize . " MB"; } } else { $filesize = round($filesize, 1); return $filesize . " KB"; } } else { $filesize = round($filesize, 1); return $filesize . ""; } } public static function loaderUI($vals, $multi = true) { ?> <!-- CSS to style the file input field as button and adjust the Bootstrap progress bars --> <link rel="stylesheet" href="../components/com_jbcatalog/libraries/jsupload/css/jquery.fileupload-ui.css"> <!-- CSS adjustments for browsers with JavaScript disabled --> <noscript> <link rel="stylesheet" href="../components/com_jbcatalog/libraries/jsupload/css/jquery.fileupload-ui-noscript.css"> </noscript> <!-- The file upload form used as target for the file upload widget --> <!-- Redirect browsers with JavaScript disabled to the origin page --> <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload --> <div class="fileupload-buttonbar"> <div class="span7"> <!-- The fileinput-button span is used to style the file input field as button --> <span class="btn btn-success fileinput-button"> <i class="icon-plus icon-white"></i> <span>Přidat obrázek</span> <input type="file" name="files[]" multiple> </span> <button type="submit" class="btn btn-primary start"> <i class="icon-upload icon-white"></i> <span>Zahájit nahrávání</span> </button> <button type="reset" class="btn btn-warning cancel"> <i class="icon-ban-circle icon-white"></i> <span>Zrušit nahrávání</span> </button> <button type="button" class="btn btn-danger delete delete-resyst-override"> <i class="icon-trash icon-white"></i> <span>Smazat</span> </button> <input type="checkbox" class="toggle"> <!-- The loading indicator is shown during file processing --> <span class="fileupload-loading"></span> </div> <!-- The global progress information --> <div class="span5 fileupload-progress fade"> <!-- The global progress bar --> <div class="progress progress-success progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100"> <div class="bar" style="width:0%;"></div> </div> <!-- The extended global progress information --> <div class="progress-extended">&nbsp;</div> </div> </div> <div class="clearfix"></div> <!-- The table listing the files available for upload/download --> <table role="presentation" class="table table-striped"> <tbody class="files"> <?php if (count($vals)) { foreach ($vals as $val) { ?> <tr class="template-download fade in"> <td> <span class="preview"> <a href="../images/files/<?php echo $val ?>" title="<?php echo $val ?>" download="<?php echo $val ?>" data-gallery=""><img src="../images/files/thumbnail/<?php echo $val ?>"></a> </span> </td> <td> <p class="name"> <a href="../images/files/<?php echo $val ?>" title="<?php echo $val ?>" download="<?php echo $val ?>" data-gallery=""><?php echo $val ?></a> <input type="hidden" name="filnm[]" value="<?php echo $val ?>"> </p> </td> <td> <span class="size"> <?php echo ImagesHelper::filesize_get("../images/files/" . $val) ?> </span> </td> <td> <button class="btn btn-danger delete delete-resyst-override" data-type="DELETE" data-url="../components/com_jbcatalog/libraries/jsupload/server/php/?file=<?php echo $val ?>"> <i class="icon-trash icon-white"></i> <span>Smazat</span> </button> <input type="checkbox" name="delete" value="1" class="toggle"> </td> </tr> <?php } } ?> </tbody> </table> <!-- The template to display files available for upload --> <script id="template-upload" type="text/x-tmpl"> {% for (var i=0, file; file=o.files[i]; i++) { %} <tr class="template-upload fade"> <td> <span class="preview"></span> </td> <td> <p class="name">{%=file.name%}</p> {% if (file.error) { %} <div><span class="label label-important">Error</span> {%=file.error%}</div> {% } %} </td> <td> <p class="size">{%=o.formatFileSize(file.size)%}</p> {% if (!o.files.error) { %} <div class="progress progress-success progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="bar" style="width:0%;"></div></div> {% } %} </td> <td> {% if (!o.files.error && !i && !o.options.autoUpload) { %} <button class="btn btn-primary start"> <i class="icon-upload icon-white"></i> <span>Start</span> </button> {% } %} {% if (!i) { %} <button class="btn btn-warning cancel"> <i class="icon-ban-circle icon-white"></i> <span>Cancel</span> </button> {% } %} </td> </tr> {% } %} </script> <!-- The template to display files available for download --> <script id="template-download" type="text/x-tmpl"> {% for (var i=0, file; file=o.files[i]; i++) { %} <tr class="template-download fade"> <td> <span class="preview"> {% if (file.thumbnailUrl) { %} <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a> {% } %} </span> </td> <td> <p class="name"> <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a> <input type="hidden" name="filnm[]" value="{%=file.name%}" /> </p> {% if (file.error) { %} <div><span class="label label-important">Error</span> {%=file.error%}</div> {% } %} </td> <td> <span class="size">{%=o.formatFileSize(file.size)%}</span> </td> <td> <button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}> <i class="icon-trash icon-white"></i> <span>Delete</span> </button> <input type="checkbox" name="delete" value="1" class="toggle"> </td> </tr> {% } %} </script> <script src="../components/com_jbcatalog/libraries/jsupload/js/vendor/jquery.ui.widget.js"></script> <!-- The Templates plugin is included to render the upload/download listings --> <script src="../components/com_jbcatalog/libraries/jsupload/js/tmpl.min.js"></script> <!-- The Load Image plugin is included for the preview images and image resizing functionality --> <script src="../components/com_jbcatalog/libraries/jsupload/js/load-image.min.js"></script> <!-- The Iframe Transport is required for browsers without support for XHR file uploads --> <script src="../components/com_jbcatalog/libraries/jsupload/js/jquery.iframe-transport.js"></script> <!-- The basic File Upload plugin --> <script src="../components/com_jbcatalog/libraries/jsupload/js/jquery.fileupload.js"></script> <!-- The File Upload processing plugin --> <script src="../components/com_jbcatalog/libraries/jsupload/js/jquery.fileupload-process.js"></script> <!-- The File Upload image preview & resize plugin --> <script src="../components/com_jbcatalog/libraries/jsupload/js/jquery.fileupload-image.js"></script> <!-- The File Upload validation plugin --> <script src="../components/com_jbcatalog/libraries/jsupload/js/jquery.fileupload-validate.js"></script> <!-- The File Upload user interface plugin --> <script src="../components/com_jbcatalog/libraries/jsupload/js/jquery.fileupload-ui.js"></script> <!-- The main application script --> <script src="../components/com_jbcatalog/libraries/jsupload/js/main.js"></script> <?php } } <file_sep>/administrator/components/com_jbcatalog/models/fields/adfs.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('JPATH_BASE') or die; JFormHelper::loadFieldClass('list'); class JFormFieldAdfs extends JFormFieldList { protected $type = 'Adfs'; protected function getOptions() { $options = array(); $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select('a.id AS value, a.name AS text') ->from('#__jbcatalog_adf AS a') ->where('a.published = "1"'); // Get the options. $db->setQuery($query); try { $options = $db->loadObjectList(); } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); } // Merge any additional options in the XML definition. $options = array_merge(parent::getOptions(), $options); return $options; } } <file_sep>/components/com_jbcatalog/controller.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogController extends JControllerLegacy { public function display($cachable = false, $urlparams = false) { $cachable = true; // Get the document object. $document = JFactory::getDocument(); // Set the default view name and format from the Request. $vName = $this->input->get('view', 'categories'); $this->input->set('view', $vName); $user = JFactory::getUser(); $safeurlparams = array('catid' => 'INT', 'id' => 'INT', 'cid' => 'ARRAY', 'year' => 'INT', 'month' => 'INT', 'limit' => 'UINT', 'limitstart' => 'UINT', 'showall' => 'INT', 'return' => 'BASE64', 'filter' => 'STRING', 'filter_order' => 'CMD', 'filter_order_Dir' => 'CMD', 'filter-search' => 'STRING', 'print' => 'BOOLEAN', 'lang' => 'CMD'); parent::display($cachable, $safeurlparams); return $this; } public function rating($cachable = false, $urlparams = false) { $model = $this->getModel_es('Item'); $value = $this->input->getInt('rat', 0); $id = $this->input->getInt('id', 0); $adf_id = $this->input->getInt('adfid', 0); $model->rate_item($id, $adf_id, $value); } public function getModel_es($name = 'form', $prefix = '', $config = array('ignore_request' => true)) { $model = parent::getModel($name, $prefix, $config); return $model; } public function save_position(){ $db = JFactory::getDbo(); $db->setQuery("UPDATE #__jbcatalog_options SET data = '".$db->escape($_POST['data'])."' WHERE name='item_position'"); $db->execute(); die(); } } <file_sep>/administrator/components/com_jbcatalog/controllers/adfs.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogControllerAdfs extends JControllerAdmin { public function __construct($config = array()) { parent::__construct($config); $this->registerTask('unsetDefault', 'setDefault'); } /** * Proxy for getModel * @since 1.6 */ public function getModel($name = 'Adf', $prefix = 'JBCatalogModel', $config = array()) { return parent::getModel($name, $prefix, array('ignore_request' => true)); } public function saveorder() { JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); // Get the arrays from the Request $order = $this->input->post->get('order', null, 'array'); $originalOrder = explode(',', $this->input->getString('original_order_values')); // Make sure something has changed if (!($order === $originalOrder)) { parent::saveorder(); } else { // Nothing to reorder $this->setRedirect(JRoute::_('index.php?option='.$this->option.'&view='.$this->view_list, false)); return true; } } public function saveOrderAjax() { JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); // Get the arrays from the Request $pks = $this->input->post->get('cid', null, 'array'); $order = $this->input->post->get('order', null, 'array'); $originalOrder = explode(',', $this->input->getString('original_order_values')); // Make sure something has changed if (!($order === $originalOrder)) { // Get the model $model = $this->getModel(); // Save the ordering $return = $model->saveorder($pks, $order); if ($return) { echo "1"; } } // Close the application JFactory::getApplication()->close(); } public function getAdfGroupDetails(){ $groupid = $this->input->getInt('groupid', 0); $catid = $this->input->getInt('catid', 0); if(!$groupid){ return ''; } $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select('a.id, a.name') ->from('#__jbcatalog_adfgroup AS a') ->where('a.published = "1"') ->where('a.id = '.$groupid); $db->setQuery($query); $group = $db->loadObject(); $query = $db->getQuery(true) ->select('a.id, a.name, c.listview') ->from('#__jbcatalog_adf AS a') ->innerjoin('#__jbcatalog_adf_ingroups AS i ON a.id = i.adfid') ->leftjoin('#__jbcatalog_category_adfs as c ON (c.adfs_id = a.id AND c.cat_id = '.intval($catid).')') //->where('a.id = i.adfid') ->where('i.groupid = '.$groupid) ->where('a.published = "1"'); $db->setQuery($query); $adfs = $db->loadObjectList(); $catfilt[] = JHTML::_('select.option', "0", JText::_('JGLOBAL_USE_GLOBAL'), 'id', 'name' ); $catfilt[] = JHTML::_('select.option', "1", JText::_('JHIDE'), 'id', 'name' ); $catfilt[] = JHTML::_('select.option', "2", JText::_('JSHOW'), 'id', 'name' ); echo '<tr class="jbgroup'.$group->id.'" style="background-color:#eee;font-size:130%;">'; echo '<td><a href="javascript:void(0);" title="'.JText::_('COM_JBCATALOG_REMOVE').'" onClick="javascript:jsRemoveFieldGroup(\''.$group->id.'\', \''.$group->name.'\');"><img src="'.JURI::base().'components/com_jbcatalog/images/publish_x.png" title="'.JText::_('COM_JBCATALOG_REMOVE').'" /></a></td>'; echo '<td colspan="3"><input type="hidden" name="jbgroups[]" value="'.$group->id.'" />'.$group->name.'</td>'; echo '</tr>'; for($i=0; $i < count($adfs); $i++){ echo '<tr class="jbgroup'.$group->id.'" style="background-color:#fefefe;font-style:italic;">'; echo '<td><input type="hidden" name="jbgroups_adf[]" value="'.$group->id.'" /><input type="hidden" name="jbgrfields[]" value="'.$adfs[$i]->id.'" /></td>'; echo '<td>'.$adfs[$i]->name.'</td>'; echo '<td><input type="checkbox" value="1" name="showlist['.$adfs[$i]->id.']" '.($adfs[$i]->listview?' checked="checked"':'').' /></td>'; echo '<td>'; echo JHTML::_('select.genericlist', $catfilt, 'catfilter[]', 'class="inputboxsel" size="1"', 'id', 'name', 0 ); echo '</td>'; echo '</tr>'; } exit(); //return array("id" => $group->id, "name" => $group->name, "adf" => $adfs); } } <file_sep>/components/com_jbcatalog/libraries/dragbox/js/__drag.js //var dataFromServer = {}; jQuery.noConflict(); var dataToServer = { positions: {}, css: {} }; ////plugin to get outerHTML of the element //usage $(selector).outerHTML() jQuery.fn.outerHTML = function(s) { return s ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html(); }; //plugin to get backgroundColor property as a hex number //not as rgb(int, int, int) jQuery.fn.getHexColor = function(rgb) { rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); function hex(x) { return ("0" + parseInt(x).toString(16)).slice(-2); } return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); } //draggables elements //add new to this array //TODO: add class .drag to draggables var draggables = ['[class*="drag"]']; //droppables elements //add new to array //TODO: add class .drop to droppables var droppables = ['.dropHeader', '.dropLeft', '.dropRight', '.dropFooter']; //maybe will be useful for joomla //disables link clicking //var adminMode = true; //array of Element objects var globalDragElements = []; //possible tabs var globalTabs = { 'text': { title: 'Text options', css: ['font-family', 'font-size', 'color', 'bold', 'underline', 'italic'] //, //apply: ['a', 'span'] }, 'label': { title: 'Label options', css: ['font-family', 'font-size', 'color', 'bold', 'underline', 'italic'], apply: ['label'] }, 'image': { title: 'Image options', css: ['width', 'height', 'border-width', 'border-color'] }, 'margin': { title: 'Margin options', css: ['margin-left', 'margin-bottom', 'margin-right', 'margin-top'] } }; //possible fields var globalFields = { 'font-family': {tag: 'select', values: ['Verdana', 'Arial', 'Times New Roman']}, 'font-size': {tag: 'input', type: 'text', hasPx: true}, 'color': {tag: 'input', type: 'text'}, 'bold': {tag: 'input', type: 'checkbox', name: 'font-weight', value: 'bold'}, 'underline': {tag: 'input', type: 'checkbox', name: 'text-decoration', value: 'underline'}, 'italic': {tag: 'input', type: 'checkbox', name: 'font-style', value: 'italic'}, 'width': {tag: 'input', type: 'text', hasPx: true}, 'height': {tag: 'input', type: 'text', hasPx: true}, 'border-width': {tag: 'input', type: 'text', name: 'padding', hasPx: true}, 'border-color': {tag: 'input', type: 'text', name: 'background-color'}, 'margin-left': {tag: 'input', type: 'text', hasPx: true}, 'margin-bottom': {tag: 'input', type: 'text', hasPx: true}, 'margin-right': {tag: 'input', type: 'text', hasPx: true}, 'margin-top': {tag: 'input', type: 'text', hasPx: true} } //possible types //add these as an element class to the template //{class: [tab1, tab2]} var globalTypes = { dragImage: ['image', 'margin'], dragParam: ['text', 'label', 'margin'], dragText: ['text', 'margin'] } function parseValue(val, hasPx) { if (hasPx) { return parseInt(val); } else { return val; } } function unparseValue(val, hasPx) { if (hasPx) { return val+'px'; } else { return val; } } function findGlobalFieldByName(name) { var searchKey = ''; if (globalFields.hasOwnProperty(name)) { return name; } _.each(globalFields, function(val, key) { if (val.name !== undefined && val.name == name) { searchKey = key; } }) return searchKey; } /** * class describing the input tag * @param {object} options * @param {string} name * @param {string} currentValue * @returns {Input} */ /*function Input(options, name, currentValue, defaultValue, hasPx) { this.tag = options.tag; this.name = name; this.type = options.type; this.currentValue = parseValue(currentValue, hasPx); this.value = options.value; this.defaultValue = parseValue(defaultValue, hasPx); this.hasPx = hasPx; this.$el = {}; } Input.prototype.render = function() { this.$el = jQuery(document.createElement(this.tag)) .attr('name', this.name) .attr('type', this.type) .val(this.currentValue) .attr('value', this.currentValue); if (this.type == 'checkbox') { this.$el.attr('checked', this.currentValue == this.value ? true : false); } return this.$el.outerHTML()+(this.hasPx?'px':''); } Input.prototype.getValue = function($i) { if (this.type == 'checkbox') { return $i.is(':checked') ? this.value : this.defaultValue; } else { return $i.val(); } } Input.prototype.getEvent = function() { if (this.type == 'checkbox') { return 'click'; } else { return 'blur'; } }*/ /** * class describing the select tag * @param {object} options * @param {string} name * @param {string} currentValue * @returns {Select} */ var objJ = { Select: function (options, name, currentValue, defaultValue){ this.tag = options.tag; this.name = name; this.type = options.type; this.currentValue = currentValue; this.values = options.values; this.defaultValue = defaultValue; this.$el = {}; this.render = function() { this.$el = jQuery(document.createElement(this.tag)).attr('name', this.name); var options = _.union(this.values, [this.defaultValue]); for (var i in options) { var opt = options[i]; var $option = {}; if (this.currentValue == opt) { $option = jQuery(document.createElement('option')) .val(this.currentValue) .text(this.currentValue + '(current)') .attr('selected', true); }else { if(typeof opt == 'string'){ $option = jQuery(document.createElement('option')).val(opt).text(opt); } } this.$el.append($option); } return this.$el.outerHTML(); } this.getValue = function($s) { return $s.find(':selected').val(); } this.getEvent = function() { return 'change'; } }, Input: function (options, name, currentValue, defaultValue, hasPx){ this.tag = options.tag; this.name = name; this.type = options.type; this.currentValue = parseValue(currentValue, hasPx); this.value = options.value; this.defaultValue = parseValue(defaultValue, hasPx); this.hasPx = hasPx; this.$el = {}; this.render = function() { this.$el = jQuery(document.createElement(this.tag)) .attr('name', this.name) .attr('type', this.type) .val(this.currentValue) .attr('value', this.currentValue); if (this.type == 'checkbox') { this.$el.attr('checked', this.currentValue == this.value ? true : false); } return this.$el.outerHTML()+(this.hasPx?'px':''); } this.getValue = function($i) { if (this.type == 'checkbox') { return $i.is(':checked') ? this.value : this.defaultValue; } else { return $i.val(); } } this.getEvent = function() { if (this.type == 'checkbox') { return 'click'; } else { return 'blur'; } } } } /*function Select(options, name, currentValue, defaultValue) { this.tag = options.tag; this.name = name; this.type = options.type; this.currentValue = currentValue; this.values = options.values; this.defaultValue = defaultValue; this.$el = {}; } Select.prototype.render = function() { this.$el = jQuery(document.createElement(this.tag)).attr('name', this.name); var options = _.union(this.values, [this.defaultValue]); for (var i in options) { var opt = options[i]; var $option = {}; if (this.currentValue == opt) { $option = jQuery(document.createElement('option')) .val(this.currentValue) .text(this.currentValue + '(current)') .attr('selected', true); } else { $option = jQuery(document.createElement('option')) .val(opt) .text(opt); } this.$el.append($option); } return this.$el.outerHTML(); } Select.prototype.getValue = function($s) { return $s.find(':selected').val(); } Select.prototype.getEvent = function() { return 'change'; }*/ /** * @class {Element} */ function jElement() { /** jquery element*/ this.$el = {}; this.type = ''; this.tabs = []; this.qtip = {}; /** here we will save all changed css properties. Some sort of cache*/ this.css = {}; } /** * Initialize method * @param {Object} el Jquery selector * @param {Object} qtip qtip instance */ jElement.prototype.init = function(el, qtip) { this.$el = el; this.qtip = qtip; this.type = _.intersection(_.keys(globalTypes), this.$el.attr('class').split(' ')); this.tabs = globalTypes[this.type]; this.save(); } jElement.prototype.setModalContent = function(tabs, content) { //console.log(content); jQuery('#modal').html(_.template(jQuery('#modalTemplate').html(), { tabs: tabs, content: content })); } /** * Resets content from modal window */ jElement.prototype.removeTooltipContent = function() { this.setModalContent('', ''); } /** * Helper function for rendering tab content * renders tabs structure * @param {string} tab @see globalTabs */ jElement.prototype.renderTab = function(tab) { var $li = jQuery('<li class="on_tab ui-state-default ui-corner-top"></li>'); var $a = jQuery('<a>' + globalTabs[tab].title + '</a>').attr({'id': '#tab' + tab, 'class': 'ui-tabs-anchor'});//redirect $li.append($a); //console.log($a[0]); return $li.outerHTML(); } jElement.prototype.getSetProperty = function(css) { var setProperty; //alert(css);///тут стили попадают в всплыв. окно! switch (css) { case 'color': setProperty = this.$el.css(css); setProperty = this.$el.getHexColor(setProperty); break; case 'borderColor': setProperty = this.$el.css('borderTopColor'); setProperty = this.$el.getHexColor(setProperty); break; case 'borderWidth': case 'borderHeight': setProperty = this.$el.css(css.substr(0, 6)+'Top'+css.substr(6)); break; case 'width': case 'height': setProperty = this.$el[css](); break; case 'backgroundColor': setProperty = this.$el.css(css); setProperty = this.$el.getHexColor(setProperty); break; case 'padding': setProperty = this.$el.find('img:first').css('padding-top'); break; default: setProperty = this.$el.css(css); break; } return setProperty; } jElement.prototype.getParamsForRenderTag = function(css) { var obj = globalFields[css]; var cssName = obj.name ? obj.name : css; var jQueryCss = jQuery.camelCase(cssName); var setProperty = this.getSetProperty(jQueryCss); var className = obj.tag.charAt(0).toUpperCase() + obj.tag.substr(1); var hasPx = obj.hasOwnProperty('hasPx')?obj.hasPx : false; return { obj: obj, cssName: cssName, jQueryCss: jQueryCss, setProperty: setProperty, className: className, hasPx: hasPx }; } /** * @param {type} css * @returns {jQuery} tag object(input or select) */ jElement.prototype.renderTag = function(css) { var params = this.getParamsForRenderTag(css); return new objJ[params.className](params.obj, params.cssName, params.setProperty, this.css[params.cssName], params.hasPx); //return new window[params.className](params.obj, params.cssName, params.setProperty, this.css[params.cssName], params.hasPx); } /** * Render tab content * _.template @see http://underscorejs.org/#template * @param {int} index * @param {string} tab * @returns {string} */ jElement.prototype.renderTabContent = function(tab) { if(typeof tab == 'string'){ var css = globalTabs[tab].css; ////!!!!!!!!!!!!!! var $container = jQuery('<div></div>').attr('id', 'tab' + tab); $container.append('<table></table>'); var compiled = ""; for (var i in css) { if(typeof css[i] == 'string'){ var input = this.renderTag(css[i]); //console.log(input); compiled = _.template(jQuery('#inputTemplate').html(), { name: css[i], labelText: css[i], element: input.render() }); $container.find('table').append(compiled); } } return $container.outerHTML(); } } jElement.prototype.getCurrentTab = function() { return jQuery('#modal #tabs [id^="tab"]').not(':hidden'); } jElement.prototype.attachCustomEvent = function() { var that = this; jQuery.each(jQuery("#tabs input, #tabs select"), function(index, item) { var $el = jQuery(item); var searchKey = ''; searchKey = findGlobalFieldByName($el.prop("name")); var input = that.renderTag(searchKey); $el.on(input.getEvent(), function(event) { that.applyStyles(jQuery(this).attr('name'), input.getValue(jQuery(this))); }) }) } jElement.prototype.applyStyles = function(name, value) { var tab = globalTabs[this.getCurrentTab().attr('id').substr(3)]; //console.log(tab); if (name == 'width' || name == 'height') { var intV = parseInt(value); if (intV != this.$el[name]()) { var oName = name == 'width'?'height':'width'; var img = this.$el.find('img:first'); this.$el[name](this.$el[name]()); this.$el[oName](this.$el[oName]()); var paddingValue = parseInt(img.css('padding-top')); var elNameVal = this.$el[name]()-2*paddingValue; var elONameVal = this.$el[oName]()-2*paddingValue; var intVPadding = intV - 2*paddingValue; var curImg = { 'width': img.width(), 'height': img.height() }; var nextImg = { 'width': '', 'height': '' } if (curImg[name] / intVPadding < curImg[name] / elNameVal) { nextImg[name] = intVPadding/elNameVal*curImg[name]; nextImg[oName] = nextImg[name]/curImg[name]*curImg[oName]; if (nextImg[oName] > elONameVal) { nextImg[name] = nextImg[name] * elONameVal/nextImg[oName]; nextImg[oName] = elONameVal; } } else { nextImg[name] = intVPadding/elNameVal*curImg[name]; nextImg[oName] = nextImg[name]/curImg[name]*curImg[oName]; if (nextImg[name] > elNameVal) { nextImg[name] = nextImg[name] * elONameVal/nextImg[oName]; nextImg[oName] = elONameVal; } } img.css(nextImg); var m = Math.floor(((name=='height'?intVPadding:elONameVal) - img.height())/2); var mp = m+"px"; img.css("margin-top",mp); } } if (name == 'padding') { var val = parseInt(value); var img = this.$el.find('img:first'); if (val != parseInt(img.css('padding-top'))) { var elWidth = this.$el.width(); var elHeight = this.$el.height(); var nextImg = { width: img.width()*(elWidth-2*val)/elWidth, height: img.height()*(elHeight-2*val)/elHeight, padding: val+'px' } img.css(nextImg); var m = Math.floor((this.$el.height()-2*val - img.height())/2); var mp = m+"px"; img.css("margin-top",mp); } } else { var gf = globalFields[findGlobalFieldByName(name)]; var $el = this.$el; if (tab.hasOwnProperty('apply')) { _.each(tab.apply, function(item){ var $item = $el.find(item); $item.css(jQuery.camelCase(name), gf.hasOwnProperty('hasPx')?unparseValue(value, true):value); }) } else { $el.css(jQuery.camelCase(name), gf.hasOwnProperty('hasPx')?unparseValue(value, true):value); } } } /** * Renders modal window with tabs and content */ jElement.prototype.renderTooltipContent = function() { this.removeTooltipContent(); //render content for each tab var tabsList = '', tabsContent = ''; for (tab in this.tabs) { if(typeof this.tabs[tab] == 'string'){ tabsList += this.renderTab(this.tabs[tab]); tabsContent += this.renderTabContent(this.tabs[tab]); } } this.setModalContent(tabsList, tabsContent); this.attachCustomEvent(); jQuery('#tabs').tabs(); jQuery('#modal').dialog({ height: 'auto', modal: true, draggable: true, resizable: false, width: 'auto' }); jQuery('#tabmargin').css('display','none'); if(jQuery('#tablabel').length){ jQuery('#tablabel').css('display','none'); } jQuery('.on_tab:first').addClass('ui-tabs-active ui-state-active'); if(jQuery('#tabtext').length){ jQuery('#tabtext').css('display','block'); }else{ jQuery('#tabimage').css('display','block'); } jQuery('.on_tab').click(function(){ if(this.children[0].id == '#tabtext'){ jQuery('#tabmargin').css('display','none'); if(jQuery('#tablabel').length){ jQuery('#tablabel').css('display','none'); jQuery('.on_tab').eq(-2).removeClass('ui-tabs-active ui-state-active'); } jQuery('#tabtext').css('display','block'); this.addClass('ui-tabs-active ui-state-active'); jQuery('.on_tab:last').removeClass('ui-tabs-active ui-state-active'); }else if(this.children[0].id == '#tabimage'){ jQuery('#tabmargin').css('display','none'); if(jQuery('#tablabel').length){ jQuery('#tablabel').css('display','none'); } jQuery('#tabimage').css('display','block'); this.addClass('ui-tabs-active ui-state-active'); jQuery('.on_tab:last').removeClass('ui-tabs-active ui-state-active'); } else if(this.children[0].id == '#tabmargin'){ if(jQuery('#tabtext').length){jQuery('#tabtext').css('display','none'); if(jQuery('#tablabel').length){ jQuery('#tablabel').css('display','none'); } }else{ jQuery('#tabimage').css('display','none'); }jQuery('#tabmargin').css('display','block'); this.addClass('ui-tabs-active ui-state-active'); jQuery('.on_tab:first').removeClass('ui-tabs-active ui-state-active');} else if(this.children[0].id == '#tablabel'){ jQuery('#tabmargin').css('display','none'); jQuery('#tabtext').css('display','none'); jQuery('#tablabel').css('display','block'); this.addClass('ui-tabs-active ui-state-active'); jQuery('.on_tab:last').removeClass('ui-tabs-active ui-state-active'); jQuery('.on_tab:first').removeClass('ui-tabs-active ui-state-active'); } }); //<script>window.close();</script> } //TODO jElement.prototype.save = function() { _.each(this.tabs, function(tab, index) { _.each(globalTabs[tab].css, function(cssIndex) { var cssName = globalFields[cssIndex].name ? globalFields[cssIndex].name : cssIndex; this.css[cssName] = this.$el.css(jQuery.camelCase(cssName)); }, this) }, this); } jElement.prototype.getChangedCss = function() { var changedCss = {}; _.each(this.tabs, function(tab, index) { _.each(globalTabs[tab].css, function(cssIndex) { var cssName = globalFields[cssIndex].name ? globalFields[cssIndex].name : cssIndex; var value = this.$el.css(jQuery.camelCase(cssName)); //if (value != this.css[cssName]) { //tratata changedCss[cssName] = value; //} }, this) }, this); return changedCss; } jElement.prototype.getCss = function() { return this.css; } jElement.prototype.getPositions = function() { return _.filter(droppables, function(drop) { return jQuery(drop).find(this.$el).length; }, this); } jElement.prototype.getDataIndex = function() { return this.$el.data('index'); } jQuery(document).ready(function() { init(draggables, droppables); /** click drag link from tooltip */ jQuery('body').on('click', '[href="#drag"]', function(e) { e.preventDefault(); enableDragDrop(draggables, droppables); }) /** click showparams link from tooltip */ jQuery('body').on('click', '[href="#showParams"]', function(e) { e.preventDefault(); /** what element should we use for rendering modal */ var tooltip = _.find(globalDragElements, function(item) { var elements = item.qtip.qtip('api').elements; return jQuery(elements.tooltip).has(jQuery(this)).length; }, this); //console.log(tooltip); tooltip.renderTooltipContent(); }) //alert(dump(dataFromServer, 'dataFromServer')); jQuery('#save').click(function(e) { e.preventDefault(); _.each(droppables, function(item) { dataToServer.positions[item] = new Array(); }) _.each(globalDragElements, function(item) { var index = item.getDataIndex(); //alert(dump(item, 'item')); //console.log(index); //jQuery(".success").after(dump(item, 'item')); dataToServer.positions[item.getPositions()[0]].push(index); dataToServer.css[index] = item.getChangedCss(); }) //console.log(dataToServer); var url_ajax = window.location.pathname+'/index.php?option=com_jbcatalog&task=save_position&tmpl=component'; jQuery.ajax({ // url: 'data.php', url: url_ajax, type: 'POST', data: {data: JSON.stringify(dataToServer)}, success: function(response) { jQuery(window).scrollTop(0); jQuery('.successDIV').show(100, function(){ var that = this; (function(th){ setInterval(function(){ jQuery(th).hide(); }, 5000) })(that); }) }, error: function(response) { } }) }) jQuery('#cancel').click(function(e) { e.preventDefault(); window.location.reload(); }) }) /** * Enables or disables dragging of the element * @param {Object} item Jquery element * @param {boolean} enable whether to enable or disable the dragging of the element */ function doDraggable(item, enable) { jQuery(item).draggable({ containment: ".block", cursor: "crosshair", snap: ".block", disabled: !enable, helper: function() { if (jQuery('#draggableHelper').length == 0) { var $el = jQuery('<div id="draggableHelper"></div>'); $el.appendTo(jQuery('body')); } else { $el = jQuery('#draggableHelper'); } $el.append(jQuery(this).html()); return $el; }, start: function(event, ui) { jQuery.each(droppables, function(index, val) { jQuery.each(jQuery(val), function() { jQuery(this).data('borderStyle', jQuery(this).css('borderStyle')).data('borderColor', jQuery(this).css('borderColor')); jQuery(this).css('borderStyle', 'dotted').css('borderColor', '#ff0000'); }) }); }, stop: function(event, ui) { jQuery.each(droppables, function(index, val) { jQuery.each(jQuery(val), function() { jQuery(this).css('borderStyle', jQuery(this).data('borderStyle')).css('borderColor', jQuery(this).data('borderColor')); }) }); } }); } /** * Enables or disables dropping of the element * @param {Object} item Jquery element * @param {boolean} enable whether to enable or disable the dropping of the element */ function doDroppable(item, enable) { jQuery(item).droppable({ drop: handleDropEvent, hoverClass: "hovered", tolerance: "pointer", disabled: !enable, accept: function() { return true; }, over: function(event, ui) { ui.helper.addClass('dragOver'); }, out: function(event, ui) { ui.helper.removeClass('dragOver'); } }); } /** * function initializes the app, * forms globalDragElements array * @param {array} dragElements * @param {array} dropElements */ function init(dragElements, dropElements) { if (dataFromServer) { var position = {}; _.each(dataFromServer.positions, function(item, index) { _.each(item, function(i) { jQuery("[data-index=" + i + "]").appendTo(jQuery(index)); }) }); for (var i in dataFromServer.css) { applyCss(i, dataFromServer.css[i]); } } if(!adminMode){ return false; } jQuery.each(dragElements, function(index, val) { jQuery.each(jQuery(val), function() { jQuery(this).on('click', 'a', function(e) { if (adminMode) { e.preventDefault(); } jQuery(this).parents('[class^="drag"]').trigger('click'); }) var qtip = jQuery(this).qtip({ content: { text: jQuery('.parameters').clone(), button: true }, show: { event: 'click' }, position: { target: 'mouse', adjust: { mouse: false } } }); var el = new jElement; el.init(jQuery(this), qtip); globalDragElements.push(el); }) }); } function applyCss(cssClass, styles) { _.each(styles, function(value, style) { if (_.indexOf(_.keys(globalFields), style) !== -1) { var name = globalFields[style].name ? globalFields[style].name : style; jQuery('[data-index="' + cssClass + '"]').css(jQuery.camelCase(name), value); }else{ ////+++++new //console.log(style); //console.log(value); var name = style; jQuery('[data-index="' + cssClass + '"]').css(jQuery.camelCase(name), value); } }) } function enableDragDrop(dragElements, dropElements) { jQuery.each(dragElements, function(index, val) { jQuery.each(jQuery(val), function() { doDraggable(jQuery(this), true); }) }); jQuery.each(dropElements, function(index, val) { jQuery.each(jQuery(val), function() { doDroppable(jQuery(this), true); }) }); } function disableDragDrop(dragElements, dropElements) { jQuery.each(dragElements, function(index, val) { jQuery.each(jQuery(val), function() { doDraggable(jQuery(this), false); }) }); jQuery.each(dropElements, function(index, val) { jQuery.each(jQuery(val), function() { doDroppable(jQuery(this), false); }) }); } /** * callback for drop event * @param {Object} event * @param {Object} ui */ function handleDropEvent(event, ui) { reposition(jQuery(ui.draggable), jQuery(event.target)); } function reposition($src, $dest) { $src.appendTo($dest); } <file_sep>/modules/mod_jmslideshow/classes/slide.php <?php ob_start(); /* #------------------------------------------------------------------------ # Package - JoomlaMan JMSlideShow # Version 1.0 # ----------------------------------------------------------------------- # Author - JoomlaMan http://www.joomlaman.com # Copyright © 2012 - 2013 JoomlaMan.com. All Rights Reserved. # @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later # Websites: http://www.JoomlaMan.com #------------------------------------------------------------------------ */ //-- No direct access defined('_JEXEC') or die('Restricted access'); if (!class_exists('JMImage')) { require_once JPATH_SITE . DS . 'modules' . DS . 'mod_jmslideshow' . DS . 'classes' . DS . 'jmimage.class.php'; } class JMSlide extends stdClass { var $id = null; var $category = null; var $image = null; var $title = null; var $description = null; var $link = null; var $params = null; public function JMSlide($params) { $this->params = $params; } public function loadArticle($id) { $article = JTable::getInstance("content"); $article->load($id); $usergroups = JFactory::getUser()->groups; $usergroups[] = "1"; if (in_array($article->get('access'), $usergroups)) { $this->category = $article->get('catid'); if (!class_exists('ContentHelperRoute')) { require_once(JPATH_SITE . DS . 'components' . DS . 'com_content' . DS . 'helpers' . DS . 'route.php'); } if ($article) { $this->title = $article->get('title'); $image_source = $this->params->get('jmslideshow_article_image_source', 1); $imageobj = json_decode($article->images); if ($image_source == 1) { //Intro Image $this->image = $imageobj->image_intro; } elseif ($image_source == 2) { //Full Image $this->image = $imageobj->image_fulltext; } else { $this->image = $this->getFirstImage($article->introtext . $article->fulltext); } $maxleght = $this->params->get('jmslideshow_desc_length', 50); $allowable_tags = $this->params->get('jmslideshow_desc_html', ''); $tags = ""; if ($allowable_tags) { $allowable_tags = explode(',', $allowable_tags); foreach ($allowable_tags as $tag) { $tags .= "<$tag>"; } } $this->description = substr(strip_tags($article->introtext . $article->fulltext, $tags), 0, $maxleght); if ($maxleght < strlen(strip_tags($article->introtext . $article->fulltext, $tags))) { $this->description = preg_replace('/ [^ ]*$/', ' ...', $this->description); } $this->link = JRoute::_(ContentHelperRoute::getArticleRoute($article->id, $article->catid)); $this->id = $id; if ($this->params->get('jmslideshow_title_link')) { $this->title = '<a href="' . $this->link . '">' . $this->title . '</a>'; } } else { return null; } } else { return null; } } public function loadProduct($id) { $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select("p.*,pc.product_category_id") ->select("f.file_path") ->from("#__hikashop_product AS p") ->leftjoin("#__hikashop_file AS f ON p.product_id = f.file_ref_id") ->leftjoin("#__hikashop_product_category AS pc ON pc.product_id = p.product_id") ->leftjoin("#__hikashop_category AS hc ON hc.category_id = pc.category_id") ->where("p.product_id = {$id}") ->where("f.file_type = 'product' "); $product = $db->setQuery($query)->loadObject(); $usergroups = JFactory::getUser()->groups; $usergroups[] = "1"; if (in_array($product->get('access'), $usergroups)) { if ($product) { $this->title = $product->product_name; $image_source = $this->params->get('jmslideshow_image_source', 0); if (empty($image_source)) { $this->image = JPATH_SITE . DS . 'media' . DS . 'com_hikashop' . DS . 'upload' . DS . $product->file_path; } else { $this->image = $this->getFirstImage($product->product_description); } //$this->image = JPATH_SITE . DS . 'media' . DS . 'com_hikashop' . DS . 'upload' . DS . $product->file_path; $maxleght = $this->params->get('jmslideshow_desc_length', 50); $allowable_tags = $this->params->get('jmslideshow_desc_html', ''); $tags = ""; if ($allowable_tags) { $allowable_tags = explode(',', $allowable_tags); foreach ($allowable_tags as $tag) { $tags .= "<$tag>"; } } $this->description = substr(strip_tags($product->product_description, $tags), 0, $maxleght); $this->id = $product->product_id; $this->category = $product->product_category_id; if ($maxleght < strlen(strip_tags($product->product_description, $tags))) { $this->description = preg_replace('/ [^ ]*$/', ' ...', $this->description); } $this->link = JRoute::_("index.php?option=com_hikashop&ctrl=product&task=show&cid={$product->product_id}&name={$product->product_name}"); if ($this->params->get('jmslideshow_title_link')) { $this->title = '<a href=' . $this->link . '>' . $this->title . '</a>'; } } else { return null; } } else { return null; } } public function loadK2($id) { $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select("k2.*") ->from("#__k2_items AS k2") ->where("k2.id = {$id}"); $k2 = $db->setQuery($query)->loadObject(); $usergroups = JFactory::getUser()->groups; $usergroups[] = "1"; if (in_array($k2->access, $usergroups)) { if ($k2) { $this->title = $k2->title; $image_source = $this->params->get('jmslideshow_image_source', 0); if (empty($image_source)) { //$size = XS, S, M, L, XL $size = 'XL'; jimport('joomla.filesystem.file'); if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $k2->id) . '_L.jpg')) { $this->image = JPATH_SITE . '/media/k2/items/cache/' . md5("Image" . $id) . '_' . $size . '.jpg'; } } else { $this->image = $this->getFirstImage($k2->introtext . $k2->fulltext); } $maxleght = $this->params->get('jmslideshow_desc_length', 50); $allowable_tags = $this->params->get('jmslideshow_desc_html', ''); $tags = ""; if ($allowable_tags) { $allowable_tags = explode(',', $allowable_tags); foreach ($allowable_tags as $tag) { $tags .= "<$tag>"; } } $this->description = substr(strip_tags($k2->introtext . $k2->fulltext, $tags), 0, $maxleght); $this->id = $k2->id; $this->category = $k2->catid; if ($maxleght < strlen(strip_tags($k2->introtext . $k2->fulltext, $tags))) { $this->description = preg_replace('/ [^ ]*$/', ' ...', $this->description); } $this->link = JRoute::_('index.php?option=com_k2&view=item&id=' . $k2->id . ':' . $k2->alias); if ($this->params->get('jmslideshow_title_link')) { $this->title = '<a href=' . $this->link . '>' . $this->title . '</a>'; } } else { return null; } } else { return null; } } public function loadImages($image) { $this->image = $image; } public function loadFileImages($image) { $this->image = $image->url; $this->title = urldecode($image->title); $this->description = substr(urldecode($image->desc),0,$this->params->get('jmslideshow_desc_length',150)); $this->link = $image->link; } function getFirstImage($str) { $str = strip_tags($str, '<img>'); preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $str, $matches); if (isset($matches[1][0])) { return $image = $matches[1][0]; } return ''; } function getMainImage() { if (empty($this->image)) { $this->image = JPATH_SITE . '/modules/mod_jmslideshow/images/no-image.jpg'; } elseif (str_replace(array('http://', 'https://'), '', $this->image) != $this->image) { $imageArray = @getimagesize($this->image); if (!$imageArray[0]) { $this->image = JPATH_SITE . '/modules/mod_jmslideshow/images/no-image.jpg'; } } elseif (!file_exists($this->image)) { $this->image = JPATH_SITE . '/modules/mod_jmslideshow/images/no-image.jpg'; } $style = $this->params->get('jmslideshow_image_style', 'fill'); $width = $this->params->get('jmslideshow_image_width'); $height = $this->params->get('jmslideshow_image_height'); if (false === file_get_contents($this->image, 0, null, 0, 1)) { $this->image = JURI::root() . 'modules/mod_jmslideshow/images/no-image.jpg'; } $file = pathinfo($this->image); $basename = $width . 'x' . $height . '_' . $style . '_' . $file['basename']; $safe_name = str_replace(array(' ', '(', ')', '[', ']'), '_', $basename); $newfile = JM_SLIDESHOW_IMAGE_FOLDER . '/' . $safe_name; //print $newfile; die; $flush = isset($_GET['flush']) ? true : false; if (!file_exists($newfile) || $flush) { @unlink($newfile); $jmimage = new JMImage($this->image); switch ($style) { case 'fill': $jmimage->reFill($width, $height); break; case 'fix': $jmimage->scale($width, $height); $jmimage->enlargeCanvas($width, $height, array(0, 0, 0)); break; case 'stretch': $jmimage->resample($width, $height, false); break; } $jmimage->save($newfile); } return JM_SLIDESHOW_IMAGE_PATH . '/' . $safe_name; } function getThumbnail() { $width = $this->params->get('jmslideshow_image_thumbnail_width', 200); $height = $this->params->get('jmslideshow_image_thumbnail_height', 100); if (empty($this->image)){ $this->image = JPATH_SITE . '/modules/mod_jmslideshow/images/no-image.jpg'; } $file = pathinfo($this->image); $basename = $width . 'x' . $height . '_' . $file['basename']; $safe_name = str_replace(array(' ', '(', ')', '[', ']'), '_', $basename); $newfile = JM_SLIDESHOW_IMAGE_FOLDER . '/' . $safe_name; if (!file_exists($newfile)) { //unlink($newfile); $jmimage = new JMImage($this->image); $jmimage->resample($width, $height); $jmimage->enlargeCanvas($width, $height, array(255, 255, 255)); $jmimage->save($newfile); } return JM_SLIDESHOW_IMAGE_PATH . '/' . $safe_name; } } ob_clean();<file_sep>/administrator/components/com_jbcatalog/controller.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogController extends JControllerLegacy { protected $default_view = 'categories'; public function display($cachable = false, $urlparams = false) { $view = $this->input->get('view', 'categories'); $layout = $this->input->get('layout', 'default'); $id = $this->input->getInt('id'); // Check for edit form. if ($view == 'category' && $layout == 'edit' && !$this->checkEditId('com_jbcatalog.edit.category', $id)) { // Somehow the person just went to the form - we don't allow that. $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $id)); $this->setMessage($this->getError(), 'error'); $this->setRedirect(JRoute::_('index.php?option=com_jbcatalog&view=categories', false)); return false; } parent::display(); // require_once JPATH_COMPONENT.'/helpers/footer.php'; FooterCHelper::footHTML(); return $this; } } <file_sep>/administrator/language/cs-CZ/cs-CZ.com_jbcatalog.ini COM_JBCATALOG="JBCatalog" COM_JBCATALOG_CATS_TITLE="Seznam kategorií" COM_JBCATALOG_CATS_SEARCH_FILTER="Hledat kategorii..." COM_JBCATALOG_ITEMS_TITLE="Seznam položek" COM_JBCATALOG_CATEGORY_DETAILS="Detaily kategorie" COM_JBCATALOG_FIELD_NAME_LABEL="Název kategorie" COM_JBCATALOG_FIELD_NAME_DESC="Zadejte název kategorie" COM_JBCATALOG_FIELD_ALIAS_DESC="Zadejte alias kategorie" COM_JBCATALOG_FIELD_PARENTCAT="Nadřazená kategorie" COM_JBCATALOG_FIELD_PARENTCAT_DESC="Vyberte kategorii" COM_JBCATALOG_FIELD_STATUS_DESC="Vyberte stav" COM_JBCATALOG_FIELD_LANGUAGE_DESC="Vyberte jazyk" COM_JBCATALOG_FIELD_INFORMATION_MISC_LABEL="Popis kategorie" COM_JBCATALOG_FIELD_INFORMATION_MISC_DESC="Zadejte popis kategorie" COM_JBCATALOG_FIELD_PARAMS_IMAGE_LABEL="Obrázek kategorie" COM_JBCATALOG_FIELD_PARAMS_IMAGE_DESC="Zadejte obrázek kategorie" COM_JBCATALOG_FIELD_ADF_GROUPS="Skupiny vlastností" COM_JBCATALOG_CATEGORY_ITEMS="Položek v kategorii" COM_JBCATALOG_ITEMS_SEARCH_FILTER="Hledat položku..." COM_JBCATALOG_FIELD_ITEM_NAME_LABEL="Název položky" COM_JBCATALOG_FIELD_ITEM_NAME_DESC="Zadejte název položky" COM_JBCATALOG_FIELD_ITEM_STATE_DESC="Vyberte stav" COM_JBCATALOG_FIELD_ITEM_LANGUAGE_DESC="Vyberte jazyk" COM_JBCATALOG_FIELD_ITEM_INFORMATION_MISC_LABEL="Popis položky" COM_JBCATALOG_FIELD_ITEM_INFORMATION_MISC_DESC="Zadejte popis položky" COM_JBCATALOG_FIELD_ITEM_ALIAS_DESC="Zadejte alias položky" COM_JBCATALOG_ITEM_NEW="Nová položka" COM_JBCATALOG_ITEM_EDIT="Upravit položku" COM_JBCATALOG_ITEM_DETAILS="Detaily položky" COM_JBCATALOG_ADF_LABEL="Vlastnosti položky" COM_JBCATALOG_ADF_FIELDTYPE_LABEL="Typ vlastnosti" COM_JBCATALOG_ADF_FIELDTYPE_DESC="Vyberte typ vlastnosti" COM_JBCATALOG_ADF_FIELDTYPE_TEXT="Text" COM_JBCATALOG_ADF_FIELDTYPE_RADIO="Radio" COM_JBCATALOG_ADF_FIELDTYPE_SELECT="Select" COM_JBCATALOG_ADF_FIELDTYPE_MULTISELECT="MultiSelect" COM_JBCATALOG_ADF_FIELDTYPE_LINK="Odkaz" COM_JBCATALOG_ADF_FIELDTYPE_DATE="Datum" COM_JBCATALOG_ADF_FIELDTYPE_RATING="Hodnocení" COM_JBCATALOG_ADF_FIELDTYPE_EDITOR="Editor" COM_JBCATALOG_ADF_CATEGORY_DESC="Vyberte skupinu vlastností" COM_JBCATALOG_SUB_CATEGORIES="Kategorie" COM_JBCATALOG_SUB_ITEMS="Položky" COM_JBCATALOG_SUB_ADFGROUPS="Skupiny vlastností" COM_JBCATALOG_SUB_ADFS="Vlastnosti položek" COM_JBCATALOG_SUB_PLUGINS="Pluginy" COM_JBCATALOG_CATEGORY_EDIT="Upravit kategorii" COM_JBCATALOG_CATEGORY_NEW="Nová kategorie" COM_JBCATALOG_FILTER_CAT="Vyberte kategorii" COM_JBCATALOG_ADF_EDIT="Upravit vlastnost" COM_JBCATALOG_ADF_NEW="Nová vlastnost" COM_JBCATALOG_ADFGR_SEARCH_FILTER="Vyhledat skupinu..." COM_JBCATALOG_ADF_SEARCH_FILTER="Vyhledat vlastnost..." COM_JBCATALOG_FIELD_DISPLAY_OPTION_LABEL="Zobrazení skupiny" COM_JBCATALOG_FIELD_DISPLAY_OPTION_DESC="Prosím vyberte, jak se bude skupina zobrazovat na webu:<br /> <b>Viditelná</b>: Skupina i vlastnosti se zobrazují, po kliknutí se schovají<br /> <b>Skrytá</b>: Vlastnosti jsou skryté, po kliknutí na skupinu se zobrazí<br /> <b>Záložka</b>: Vlastnosti se zobrazují na zvláštní záložce" COM_JBCATALOG_VISIBLE="Viditelná" COM_JBCATALOG_HIDDEN="Skrytá" COM_JBCATALOG_JASTAB="Záložka" COM_JBCATALOG_ADF_NAME="Název vlastnosti" COM_JBCATALOG_ADF_NAME_DESC="Vložte název vlastnosti" COM_JBCATALOG_SELECT_ITEM="Vyberte položku" COM_JBCATALOG_FILTER_SEARCH_DESC="Filtr" COM_JBCATALOG_N_ITEMS_UNPUBLISHED="Položky zneveřejněny" COM_JBCATALOG_N_ITEMS_PUBLISHED="Položky zveřejněny" COM_JBCATALOG_N_ITEMS_TRASHED="Položky smazány" COM_JBCATALOG_ADF_PREFIX="Prefix" COM_JBCATALOG_ADF_PREFIX_DESC="Tato informace bude zobrazena před hodnotou na webu" COM_JBCATALOG_ADF_POSFIX="Postfix" COM_JBCATALOG_ADF_POSFIX_DESC="Tato informace bude zobrazena po hodnotě na webu. Použijte {sup}{/sup} tagy pro horní index např. m{sup}3{/sup} pro metry krychlové" COM_JBCATALOG_FIELD_ADF_TOOLTIP_LABEL="Tooltip" COM_JBCATALOG_FIELD_ADF_TOOLTIP_DESC="Zobrazí se v tooltipu" COM_JBCATALOG_ADF_FIELDTYPE_COMPLEX="Komplexní pole" COM_JBCATALOG_COMPLEX_FIELD="Seznam komplexních polí" COM_JBCATALOG_ADF_COMPLEX_LABEL="Komplexní kategorie" COM_JBCATALOG_ADF_COMPLEX_DESC="Vyberte komplexní kategorii" COM_JBCATALOG_ADF_FILTER_LABEL="Filtr" COM_JBCATALOG_ADF_FILTER_DESC="Použít vlastnost do filtru na webu?" COM_JBCATALOG_ADDCHOICE="Přidat volbu" COM_JBCATALOG_MOVEUP="Posunout nahoru" COM_JBCATALOG_MOVEDOWN="Posunout dolů" COM_JBCATALOG_ADDNEW_ITEMS="Přidat volbu" COM_JBCATALOG_FIELD_PARENTITEM="Nadřazená položka" COM_JBCATALOG_FIELD_PARENTITEM_DESC="Vyberte nadřazenou položku" COM_JBCATALOG_ADFGROUP_LABEL="Skupina vlastností" COM_JBCATALOG_ADFGROUP_DESC="Vyberte skupinu vlastností" COM_JBCATALOG_ADFS_LABEL="Vlastnosti položky" COM_JBCATALOG_ADFS_DESC="Vyberte vlastnosti položky" COM_JBCATALOG_NO_PARENT="Žádná nadřazená položka" COM_JBCATALOG_ADDNEW="Přidat nový" COM_JBCATALOG_SEL_OPTION="Vyberte" COM_JBCATALOG_ADFGROUP_NEW="Nová skupina" COM_JBCATALOG_ADFGROUP_EDIT="Upravit skupinu" COM_JBCATALOG_ADFGR_NAME_LABEL="Jméno skupiny" COM_JBCATALOG_ADFGR_NAME_DESC="Zadejte jméno skupiny" COM_JBCATALOG_ADF_FIELDTYPE_TEXT_DESC="Textové pole" COM_JBCATALOG_ADF_FIELDTYPE_RADIO_DESC="Radio" COM_JBCATALOG_ADF_FIELDTYPE_SELECT_DESC="Select" COM_JBCATALOG_ADF_FIELDTYPE_MULTISELECT_DESC="MultiSelect" COM_JBCATALOG_ADF_FIELDTYPE_LINK_DESC="Odkaz" COM_JBCATALOG_ADF_FIELDTYPE_DATE_DESC="Datum" COM_JBCATALOG_ADF_FIELDTYPE_RATING_DESC="Hodnocení" COM_JBCATALOG_ADF_FIELDTYPE_EDITOR_DESC="Editor" COM_JBCATALOG_ADF_FIELDTYPE_COMPLEX_DESC="Komplexní pole" COM_JBCATALOG_PLUGINS_TITLE="Seznam pluginů" COM_BCAT_PLUGIN_UNINSTALL="Jste si jistí? Plugin bude odebrán i s daty" COM_BCAT_PLUGIN_UNINSTALL_ALT="Odinstalovat pluginy" COM_BCAT_PLGIN_NAME="Název pluginu" COM_BCAT_PLGIN_DESCRIPTION="Popis" COM_BCAT_PLGIN_TYPE="Typ" COM_BCAT_PLGIN_VERSION="Verze" COM_BCAT_SUBMIT_PLUGIN="Nainstalovat plugin" COM_JBCATALOG_SELECT="Vyberte" COM_JBCATALOG_REMOVE="Odstranit" COM_JBCATALOG_CATEGORY_SAVE_SUCCESS="Kategorie uložena" COM_JBCATALOG_ADF_SAVE_SUCCESS="Vlastnost uložena" COM_JBCATALOG_ADFGROUP_SAVE_SUCCESS="Skupina vlastností uložena" COM_JBCATALOG_PLUGIN_SAVE_SUCCESS="Plugin uložen" COM_JBCATALOG_ADF_FILTER_YES="Zahrnout do filtru na webu" COM_JBCATALOG_ADF_FILTER_NO="Nezahrnout do filtru na webu" COM_JBCATALOG_ADFGROUPS_TITLE="Skupiny vlastností" COM_JBCATALOG_ADFS_TITLE="Vlastnosti položek" COM_JBCATALOG_COMPLEXCAT_TITLE="Seznam komplexních kategorií" COM_JBCATALOG_COMPLEXITEMS_TITLE="Seznam komplexních položek" COM_JBCATALOG_ADDFIELDS="Vlastnosti" COM_JBCATALOG_CAT_ADF_GROUPNAME="Skupina vlastností" COM_JBCATALOG_CAT_ADF_FIELDNAME="Vlastnosti" COM_JBCATALOG_CAT_SHOWONLIST="Zobrazit v seznamu" COM_JBCATALOG_DISPLAY_FILTER="Zahrnout do filtru na webu" COM_JBCATALOG_PLUGIN_NAME="Jméno pluginu" COM_JBCATALOG_PLUGIN_NAME_DESC="Zadejte jméno pluginu"<file_sep>/administrator/language/en-GB/en-GB.com_jbcatalog.sys.ini COM_JBCATALOG_ITEM="Item" COM_JBCATALOG_ITEM_OPTION="Item option" COM_JBCATALOG_ITEM_DESC="Item description" COM_JBCATALOG_CATEGORY="Category Items List" COM_JBCATALOG_CATEGORY_OPTION="Show items from selected category" COM_JBCATALOG_CATEGORY_DESC="Show items from selected category" COM_JBCATALOG_ALL_CATEGORIES="All Categories" COM_JBCATALOG_LIST="Category List" COM_JBCATALOG_LIST_OPTION="Category List" COM_JBCATALOG_LIST_DESC="Display list of categories" COM_JBCATALOG="JBCatalog" COM_JBCATALOG_DESC="JBcatalog - extension for organizing web directory or catalog" COM_JBCATALOG_CATEGOTIES="Categories" COM_JBCATALOG_ITEMS="Items" COM_JBCATALOG_ADFGROUPS="Field Groups" COM_JBCATALOG_ADFS="Item Fields" COM_JBCATALOG_PLUGINS="Plugins" COM_JBCATALOG_SELECT_CATEGORY="Select Category"<file_sep>/administrator/components/com_jbcatalog/plugins/adfrating/adfrating.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class AdfRatingPlugin { public function getItemEdit($params = array()){ $adf = $params["adf"]; $value = $params["value"]; return ' '; } public function getItemFEAdfValue($params = array()){ $adf = $params["adf"]; $value = $params["value"]; $id = $params["itemid"]; $db = JFactory::getDbo(); $user = JFactory::getUser(); if($user->get('id')){ $db->setQuery(" SELECT value FROM #__jbcatalog_adf_rating WHERE rating_id = ".$adf->id." AND item_id = ".$id." AND usr_id = ".$user->get('id')); $value_sel = $db->loadResult(); $db->setQuery(" SELECT AVG(value) FROM #__jbcatalog_adf_rating WHERE rating_id = ".$adf->id." AND item_id = ".$id); $value_avg = $db->loadResult(); $value = '<span style="float:left; margin-right:10px;">'.sprintf("%01.2f", $value_avg).'</span>'; $value .= ' <input name="star2-'.$adf->id.'" value="1" '.($value_sel == '1'?'checked="checked"':"").' type="radio" class="starsik id'.$adf->id.'"/> <input name="star2-'.$adf->id.'" value="2" '.($value_sel == '2'?'checked="checked"':"").' type="radio" class="starsik id'.$adf->id.'"/> <input name="star2-'.$adf->id.'" value="3" '.($value_sel == '3'?'checked="checked"':"").' type="radio" class="starsik id'.$adf->id.'"/> <input name="star2-'.$adf->id.'" value="4" '.($value_sel == '4'?'checked="checked"':"").' type="radio" class="starsik id'.$adf->id.'"/> <input name="star2-'.$adf->id.'" value="5" '.($value_sel == '5'?'checked="checked"':"").' type="radio" class="starsik id'.$adf->id.'"/> <script> //var jsBase = juri::base();?> jQuery("input.id'.$adf->id.'").rating({ callback: function(value, link){ jQuery.ajax({ url: "'.juri::base().'" + "index.php?option=com_jbcatalog&task=rating&tmpl=component&rat="+value+"&id='.$id.'&adfid='.$adf->id.'", }); } }); </script> '; }else{ $db->setQuery(" SELECT AVG(value) FROM #__jbcatalog_adf_rating WHERE rating_id = ".$adf->id." AND item_id = ".$id); $value = $db->loadResult(); if(!$value){ $value = JText::_('COM_JBCATALOG_FE_NOT_RATED'); }else{ $value = sprintf("%01.2f", $value); } } return $value; } public function getAdfFilter($params = array()){ $adf = $params["adf"]; $value = $params["value"]; $selarr = array(); $selarr[] = JHTML::_('select.option', 0, 0, 'id', 'name' ); $selarr[] = JHTML::_('select.option', 1, 1, 'id', 'name' ); $selarr[] = JHTML::_('select.option', 2, 2, 'id', 'name' ); $selarr[] = JHTML::_('select.option', 3, 3, 'id', 'name' ); $selarr[] = JHTML::_('select.option', 4, 4, 'id', 'name' ); $selarr[] = JHTML::_('select.option', 5, 5, 'id', 'name' ); $html = '<div><div>&nbsp;'.JText::_('COM_JBCATALOG_FROM').':&nbsp;</div>'; $html .= JHTML::_('select.genericlist', $selarr, 'adf_filter['.$adf->id.'][]', 'class="inputboxsel" size="1"', 'id', 'name', isset($value[0])?$value[0]:0, 'adf_filter_'.$adf->id.'_0' ); $html .= '</div><div><div>&nbsp;'.JText::_('COM_JBCATALOG_TO').':&nbsp;</div>'; $html .= JHTML::_('select.genericlist', $selarr, 'adf_filter['.$adf->id.'][]', 'class="inputboxsel" size="1"', 'id', 'name', isset($value[1])?$value[1]:5, 'adf_filter_'.$adf->id.'_1' ); $html .= '</div>'; return $html; } public function getAdfFilterSQL($params = array()){ $tbl_pref = $params["adfid"]; $value = $params["value"]; $key = $tbl_pref; if($value[0] == 0){ $sq = ' (SELECT AVG(value) FROM #__jbcatalog_adf_rating WHERE rating_id = '.$key.' AND item_id = a.id) is NULL OR '; }else{ $sq = "{$value[0]} <= (SELECT AVG(value) FROM #__jbcatalog_adf_rating WHERE rating_id = {$key} AND item_id = a.id) AND "; } $filter["sql"] = " AND ( {$sq} {$value[1]} >= (SELECT AVG(value) FROM #__jbcatalog_adf_rating WHERE rating_id = {$key} AND item_id = a.id))"; return $filter; } function __call($method, $args) { return null; } public function install(){ } public function uninstall(){ } public function getPluginItem(){ return null; } public function getPluginItemSave(){ return null; } } <file_sep>/administrator/components/com_jbcatalog/controllers/plugins.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogControllerPlugins extends JControllerAdmin { public function __construct($config = array()) { parent::__construct($config); $this->registerTask('unsetDefault', 'setDefault'); } /** * Proxy for getModel * @since 1.6 */ public function getModel($name = 'Plugin', $prefix = 'JBCatalogModel', $config = array()) { return parent::getModel($name, $prefix, array('ignore_request' => true)); } public function install() { $model = $this->getModel($name = 'Plugins', $prefix = 'JBCatalogModel'); $model->pluginInstall(); $this->setRedirect(JRoute::_('index.php?option='.$this->option.'&view='.$this->view_list, false)); } public function uninstall() { $model = $this->getModel($name = 'Plugins', $prefix = 'JBCatalogModel'); $cid = $this->input->post->get('cid', null, 'array'); $model->pluginUninstall($cid); $this->setRedirect(JRoute::_('index.php?option='.$this->option.'&view='.$this->view_list, false)); } public function saveOrderAjax() { JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); // Get the arrays from the Request $pks = $this->input->post->get('cid', null, 'array'); $order = $this->input->post->get('order', null, 'array'); $originalOrder = explode(',', $this->input->getString('original_order_values')); // Make sure something has changed if (!($order === $originalOrder)) { // Get the model $model = $this->getModel(); // Save the ordering $return = $model->saveorder($pks, $order); if ($return) { echo "1"; } } // Close the application JFactory::getApplication()->close(); } public function publish(){ $model = $this->getModel($name = 'Plugins', $prefix = 'JBCatalogModel'); $cid = $this->input->post->get('cid', null, 'array'); $task = $this->input->post->get('task', null, 'string'); $value = ($task == 'plugins.publish')?1:0; $model->publish($cid, $value); $this->setRedirect(JRoute::_('index.php?option='.$this->option.'&view='.$this->view_list, false)); } } <file_sep>/administrator/components/com_jbcatalog/plugins/plugins.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class ParsePlugins { private $plugins = array(); public function __construct( $type = '', $id = 0, $published = 1) { $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select('a.id AS value, a.name AS text') ->from('#__jbcatalog_plugins AS a'); if($published){ $query->where('a.published = "1"'); } if($type){ $query->where('a.type = "'.$type.'"'); } if($id){ $query->where('a.id = "'.$id.'"'); } // Get the options. $db->setQuery($query); try { $options = $db->loadObjectList(); } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); } if(count($options)){ foreach($options as $plug){ if(is_file(JPATH_COMPONENT_ADMINISTRATOR."/plugins/{$plug->text}/{$plug->text}.php")){ require_once JPATH_COMPONENT_ADMINISTRATOR."/plugins/{$plug->text}/{$plug->text}.php"; $classname = ucfirst($plug->text).'Plugin'; if(class_exists($classname)){ $this->plugins[] = $classname; } } } } } public function getData($view, $params = array()){ $arr = array(); if(count($this->plugins)){ foreach($this->plugins as $plug){ $class = new $plug(); $value = $class->{$view}($params); //var_dump($value); if(is_array($value)){ foreach ($value as $key=>$val){ if($key){ $arr[$key] = $val; }else{ $arr[] = $val; } } }elseif($value){ return $value; } } } return $arr; } }<file_sep>/templates/cyklo/html/com_jbcatalog/category/default_items_table.php <?php /** * zobrazeni kategorie nyni zobrazuje detaily produktu * 2015-08-02 ReSyst.cz * Websites: http://www.resyst.cz */ defined('_JEXEC') or die; /* plugins */ JHTML::_('behavior.modal'); require_once JPATH_COMPONENT . '/helpers/images.php'; // echo JBCatalogImages::includeFancy($this->document); // neni potreba - je includovano v sablone if (isset($this->customplugins['script']) && $this->customplugins['script']) { echo $this->customplugins['script']; } /* plugins */ if (isset($this->customplugins['head']) && $this->customplugins['head']) { echo $this->customplugins['head']; } if (!empty($this->items)) { for ($i = 0; $i < count($this->items); $i++) { ?> <div class="row-fluid"> <div class="product-card span12" data-id="<?php echo $i; ?>" <?php echo (isset($this->items[$i]->resyst_kategorie)) ? "data-kategorie_id='" . $this->items[$i]->resyst_kategorie['id'] . "'" : ""; ?>> <?php /* plugins */ if (isset($this->customplugins['checkbox'][$i]) && $this->customplugins['checkbox'][$i]) { echo $this->customplugins['checkbox'][$i]; } if (isset($this->items[$i]->images) && count($this->items[$i]->images)) { ?> <div class='product-image'> <?php $count = 0; foreach ($this->items[$i]->images as $image) { ?> <a <?php echo $count > 0 ? 'style="display: none;"' : ''; ?> href="<?php echo JBCatalogImages::getImg($image, false); ?>" data-fancybox-group="thumb-<?php echo $i; ?>" class="fancybox-thumbs"> <img src="<?php echo JBCatalogImages::getImg($image, false); ?>" alt="<?php echo $this->items[$i]->title; ?>"/> </a> <?php $count++; } ?> <?php if (isset($this->items[$i]->resyst_kategorie)) { ?> <div class='product-kategorie'> <span class="kategorie_tag"><?php echo $this->items[$i]->resyst_kategorie['kategorie']; ?></span> </div> <?php } ?> </div> <?php } ?> <div class='product-info'> <div class="product-header"> <h3><?php echo $this->items[$i]->title; ?></h3> <?php if (isset($this->items[$i]->resyst_cena)) { $cena = number_format(floatval($this->items[$i]->resyst_cena), 2, ',', ' '); ?> <div class="cena"> Cena: <span><?php echo $cena; ?> Kč</span> </div> <?php } ?> <?php if (!empty($this->items[$i]->resyst_puvodni_cena)) { $puv_cena = number_format(floatval($this->items[$i]->resyst_puvodni_cena), 2, ',', ' '); ?> <div class="cena puvodni"> Původní cena: <span><?php echo $puv_cena; ?> Kč</span> </div> <?php } ?> </div> <ul class="nav nav-tabs"> <?php if (isset($this->items[$i]->resyst_info)) { ?> <li><a data-toggle="tab" href="#informace_<?php echo $i; ?>">Specifikace</a></li> <?php } if (isset($this->items[$i]->descr)) { ?> <li><a data-toggle="tab" href="#popis_<?php echo $i; ?>">Popis produktu</a></li> <?php } ?> </ul> <div class="tab-content"> <?php if (isset($this->items[$i]->resyst_info)) { ?> <div class="tab-pane" id="informace_<?php echo $i; ?>"> <ul> <?php foreach ($this->items[$i]->resyst_info as $info) { ?> <?php if (!empty($info['hodnota'])) { ?> <li class="icon_bg_<?php echo $info['hodnota_id'] ?>" data-toggle="tooltip" data-placement="left" title="<?php echo $info['extra']; ?>"> <span class="icon"></span><?php echo $info['hodnota']; ?> </li> <?php } ?> <?php } ?> </ul> </div> <?php } if (isset($this->items[$i]->descr)) { ?> <div class="tab-pane" id="popis_<?php echo $i; ?>"> <?php echo $this->items[$i]->descr; ?> </div> <?php } ?> </div> </div> <?php if ($this->state->{'category.id'} === 10) { ?> <div class="zeptat-se"> <a href="#bazarform" data-id="<?php echo $i; ?>" class="modal btn-email"><span>Chci další informace</span></a> </div> <?php } ?> </div> </div> <?php } } else { ?> <div class="row-fluid"> <p>Nenalezeny žádné produkty</p> </div> <?php } /* plugins */ if (isset($this->customplugins['bottom']) && $this->customplugins['bottom']) { echo $this->customplugins['bottom']; } <file_sep>/components/com_jbcatalog/jbcatalog.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; $document = JFactory::getDocument(); $document->addStyleSheet(JURI::root(true).'/components/com_jbcatalog/css/jbcatalog.css'); $controller = JControllerLegacy::getInstance('JBCatalog'); $controller->execute(JFactory::getApplication()->input->get('task')); $controller->redirect(); <file_sep>/components/com_jbcatalog/views/categories/tmpl/default.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; JHtml::addIncludePath(JPATH_COMPONENT . '/helpers'); JHtml::_('behavior.caption'); echo JLayoutHelper::render('joomla.jbcatalog.categories_default', $this); echo $this->loadTemplate('items'); ?> <file_sep>/administrator/components/com_jbcatalog/views/adfgroups/view.html.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class jbcatalogViewAdfgroups extends JViewLegacy { protected $items; protected $pagination; protected $state; /** * Display the view */ public function display($tpl = null) { // Initialiase variables. $this->items = $this->get('Items'); $this->pagination = $this->get('Pagination'); $this->state = $this->get('State'); $this->ordering = array(); // Preprocess the list of items to find ordering divisions. if(count($this->items)){ foreach ($this->items as $item) { $this->ordering[] = $item->id; } } $this->addToolbar(); $this->sidebar = JHtmlSidebar::render(); parent::display($tpl); } /** * Add the page title and toolbar. * * @since 1.6 */ protected function addToolbar() { require_once JPATH_COMPONENT.'/helpers/catalog.php'; CatalogHelper::addSubmenu('adfgroups'); // Get the toolbar object instance $bar = JToolBar::getInstance('toolbar'); JToolbarHelper::title(JText::_('COM_JBCATALOG_ADFGROUPS_TITLE'), 'menumgr.png'); JToolbarHelper::addNew('adfgroup.add'); JToolbarHelper::editList('adfgroup.edit'); JToolbarHelper::publish('adfgroups.publish', 'JTOOLBAR_PUBLISH', true); JToolbarHelper::unpublish('adfgroups.unpublish', 'JTOOLBAR_UNPUBLISH', true); JToolbarHelper::trash('adfgroups.trash'); } protected function getSortFields() { return array( 'a.published' => JText::_('JSTATUS'), 'a.name' => JText::_('JGLOBAL_TITLE'), 'a.id' => JText::_('JGRID_HEADING_ID') ); } } <file_sep>/administrator/components/com_jbcatalog/models/category.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogModelCategory extends JModelAdmin { protected $text_prefix = 'COM_JBCATALOG_CATEGORY'; public function getForm($data = array(), $loadData = true) { // Get the form. $form = $this->loadForm('com_jbcatalog.category', 'category', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } // Determine correct permissions to check. if ($this->getState('category.id')) { // Existing record. Can only edit in selected categories. $form->setFieldAttribute('catid', 'action', 'core.edit'); } else { // New record. Can only create in selected categories. $form->setFieldAttribute('catid', 'action', 'core.create'); } // Modify the form based on access controls. if (!$this->canEditState((object) $data)) { // Disable fields for display. $form->setFieldAttribute('ordering', 'disabled', 'true'); $form->setFieldAttribute('publish_up', 'disabled', 'true'); $form->setFieldAttribute('publish_down', 'disabled', 'true'); $form->setFieldAttribute('state', 'disabled', 'true'); $form->setFieldAttribute('sticky', 'disabled', 'true'); // Disable fields while saving. // The controller has already verified this is a record you can edit. $form->setFieldAttribute('ordering', 'filter', 'unset'); $form->setFieldAttribute('publish_up', 'filter', 'unset'); $form->setFieldAttribute('publish_down', 'filter', 'unset'); $form->setFieldAttribute('state', 'filter', 'unset'); $form->setFieldAttribute('sticky', 'filter', 'unset'); } return $form; } public function getTable($type = 'Category', $prefix = 'JBCatalogTable', $config = array()) { return JTable::getInstance($type, $prefix, $config); } public function save($data) { $pk = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('category.id'); $isNew = true; $table = $this->getTable(); // Load the row if saving an existing item. if ($pk > 0) { $table->load($pk); $isNew = false; } if (!$isNew) { if ($table->parent_id == $data['parent_id']) { $table->setLocation($data['parent_id'], 'last-child'); } // Set the new parent id if parent id not matched and put in last position else { $table->setLocation($data['parent_id'], 'last-child'); } } // We have a new item, so it is not a change. elseif ($isNew) { $table->setLocation($data['parent_id'], 'last-child'); } // The menu type has changed so we need to just put this at the bottom // of the root level. else { $table->setLocation(1, 'last-child'); } // Bind the data. if (!$table->bind($data)) { $this->setError($table->getError()); return false; } // Alter the title & alias for save as copy. Also, unset the home record. if (!$isNew && $data['id'] == 0) { list($title, $alias) = $this->generateNewTitle($table->parent_id, $table->alias, $table->title); $table->title = $title; $table->alias = $alias; $table->published = 0; } // Check the data. if (!$table->check()) { $this->setError($table->getError()); return false; } // Store the data. if (!$table->store()) { $this->setError($table->getError()); return false; } // Rebuild the tree path. if (!$table->rebuildPath($table->id)) { $this->setError($table->getError()); return false; } $this->setState('category.id', $table->id); //thumbnails $this->createThumbnail($table->image, $table->id); // $db = JFactory::getDbo(); $db->setQuery("DELETE FROM #__jbcatalog_category_adfs WHERE cat_id={$table->id}"); $db->execute(); if(isset($_POST["jbgrfields"]) && $_POST["jbgrfields"]){ $i=0; foreach($_POST["jbgrfields"] as $asdf ){ $listview = isset($_POST['showlist'][$asdf])?1:0; $db->setQuery("INSERT IGNORE INTO #__jbcatalog_category_adfs(adfs_id,cat_id,group_id,listview,filtered) VALUES({$asdf},{$table->id},".intval($_POST['jbgroups_adf'][$i]).",{$listview}, ".intval($_POST['catfilter'][$i]).")"); $db->execute(); $i++; } } $db->setQuery("DELETE FROM #__jbcatalog_category_adfs_group WHERE cat_id={$table->id}"); $db->execute(); if(isset($_POST["jbgroups"]) && $_POST["jbgroups"]){ $i=0; foreach($_POST["jbgroups"] as $asdf ){ $db->setQuery("INSERT INTO #__jbcatalog_category_adfs_group(cat_id,group_id) VALUES({$table->id}, {$asdf})"); $db->execute(); } } // Load associated menu items $app = JFactory::getApplication(); $assoc = isset($app->item_associations) ? $app->item_associations : 0; if ($assoc) { // Adding self to the association $associations = $data['associations']; foreach ($associations as $tag => $id) { if (empty($id)) { unset($associations[$tag]); } } // Detecting all item menus $all_language = $table->language == '*'; if ($all_language && !empty($associations)) { JError::raiseNotice(403, JText::_('COM_MENUS_ERROR_ALL_LANGUAGE_ASSOCIATED')); } $associations[$table->language] = $table->id; // Deleting old association for these items $db = JFactory::getDbo(); $query = $db->getQuery(true) ->delete('#__associations') ->where('context=' . $db->quote('com_jbcatalog.category')) ->where('id IN (' . implode(',', $associations) . ')'); $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { $this->setError($e->getMessage()); return false; } if (!$all_language && count($associations) > 1) { // Adding new association for these items $key = md5(json_encode($associations)); $query->clear() ->insert('#__associations'); foreach ($associations as $tag => $id) { $query->values($id . ',' . $db->quote('com_jbcatalog.category') . ',' . $db->quote($key)); } $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { $this->setError($e->getMessage()); return false; } } } // Clean the cache $this->cleanCache(); return true; } public function getItem($pk = null) { if ($item = parent::getItem($pk)) { // Convert the metadata field to an array. //$registry = new JRegistry; // $registry->loadString($item->metadata); //$item->metadata = $registry->toArray(); } // Load associated contact items $app = JFactory::getApplication(); $assoc = isset($app->item_associations) ? $app->item_associations : 0; if ($assoc) { $item->associations = array(); if ($item->id != null) { $associations = JLanguageAssociations::getAssociations('com_jbcatalog', '#__jbcatalog_category', 'com_jbcatalog.category', $item->id); foreach ($associations as $tag => $association) { $item->associations[$tag] = $association->id; } } } $db = $this->getDbo(); $query = "SELECT b.id" ." FROM #__jbcatalog_category_adfs as a" ." JOIN #__jbcatalog_adfgroup as b" ." ON a.adfs_id = b.id" ." WHERE a.cat_id = ".intval($item->id) ." ORDER BY b.name"; $db->setQuery($query); $item->adfsgroup = $db->loadColumn(); return $item; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 1.6 */ protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_jbcatalog.edit.category.data', array()); if (empty($data)) { $data = $this->getItem(); // Prime some default values. if ($this->getState('category.id') == 0) { $app = JFactory::getApplication(); // $data->set('catid', $app->input->get('catid', $app->getUserState('com_jbcatalog.category.filter.category_id'), 'int')); } } $this->preprocessData('com_jbcatalog.category', $data); return $data; } public function saveorder($idArray = null, $lft_array = null) { // Get an instance of the table object. $table = $this->getTable(); if (!$table->saveorder($idArray, $lft_array)) { $this->setError($table->getError()); return false; } // Clean the cache $this->cleanCache(); return true; } public function publish(&$pks, $value = 1) { $table = $this->getTable(); $pks = (array) $pks; // Clean the cache $this->cleanCache(); // Ensure that previous checks doesn't empty the array if (empty($pks)) { return true; } return parent::publish($pks, $value); } function trash($cid){ $this->publish($cid, -2); $db = JFactory::getDbo(); if(count($cid)){ foreach ($cid as $id){ $db->setQuery( "SELECT item_id FROM #__jbcatalog_items_cat" ." WHERE cat_id = ".intval($id) ); $ids = $db->loadColumn(); if(count($ids)){ foreach($ids as $id){ $db->setQuery( "SELECT COUNT(c.id) FROM #__jbcatalog_items_cat as i" ." JOIN #__jbcatalog_category as c ON i.cat_id = c.id" ." WHERE i.item_id = ".intval($id) ." AND c.published = 1" ); $count = $db->loadResult(); if(!$count){ $db->setQuery( "UPDATE #__jbcatalog_items" ." SET published = -2" ." WHERE id = ".intval($id) ); $db->execute(); } } } } } } function createThumbnail($filename, $id) { if(!$filename || !is_file(JPATH_ROOT.DIRECTORY_SEPARATOR.$filename)){ return false; } $final_width_of_image = 150; $path_to_thumbs_directory = JPATH_ROOT.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_jbcatalog'.DIRECTORY_SEPARATOR.'libraries'.DIRECTORY_SEPARATOR.'jsupload'.DIRECTORY_SEPARATOR.'server'.DIRECTORY_SEPARATOR.'php'.DIRECTORY_SEPARATOR.'files'.DIRECTORY_SEPARATOR.'thumbnail'; $info = pathinfo($filename); $file_name_thumb = $id.'_thumb.'.$info['extension']; //echo $path_to_thumbs_directory.DIRECTORY_SEPARATOR.$file_name_thumb;die(); /*if(is_file($path_to_thumbs_directory.DIRECTORY_SEPARATOR.$file_name_thumb)){ return ''; }*/ if(preg_match('/[.](jpg)$/i', $filename)) { $im = imagecreatefromjpeg(JPATH_ROOT.DIRECTORY_SEPARATOR.$filename); } else if (preg_match('/[.](gif)$/i', $filename)) { $im = imagecreatefromgif(JPATH_ROOT.DIRECTORY_SEPARATOR.$filename); } else if (preg_match('/[.](png)$/i', $filename)) { $im = imagecreatefrompng(JPATH_ROOT.DIRECTORY_SEPARATOR.$filename); } $ox = imagesx($im); $oy = imagesy($im); $nx = $final_width_of_image; $ny = floor($oy * ($final_width_of_image / $ox)); $nm = imagecreatetruecolor($nx, $ny); imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy); if(!file_exists($path_to_thumbs_directory)) { if(!mkdir($path_to_thumbs_directory)) { die("There was a problem. Please try again!"); } } imagejpeg($nm, $path_to_thumbs_directory .DIRECTORY_SEPARATOR. $file_name_thumb); } function getGroupList(){ $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select('a.id, a.name') ->from('#__jbcatalog_adfgroup AS a') ->where('a.published = "1"') ->where('a.id NOT IN (SELECT group_id FROM #__jbcatalog_category_adfs_group WHERE cat_id = '.intval($this->getState('category.id')).')'); // Get the options. $db->setQuery($query); try { $options = $db->loadObjectList(); } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); } $null_arr[] = JHTML::_('select.option', "", JText::_('COM_JBCATALOG_ADF_FIELDTYPE_SELECT'), 'id', 'name' ); $options = array_merge($null_arr, $options); return JHTML::_('select.genericlist', $options, 'grouplist', 'class="inputboxsel" size="1"', 'id', 'name', 0 ); } function getAdfList(){ $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select('a.id, a.name') ->from('#__jbcatalog_adf AS a') ->where('a.published = "1"') ->where('a.id NOT IN (SELECT adfs_id FROM #__jbcatalog_category_adfs WHERE group_id=0 AND cat_id = '.intval($this->getState('category.id')).')'); // Get the options. $db->setQuery($query); try { $options = $db->loadObjectList(); } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); } $null_arr[] = JHTML::_('select.option', "", JText::_('COM_JBCATALOG_ADF_FIELDTYPE_SELECT'), 'id', 'name' ); $options = array_merge($null_arr, $options); return JHTML::_('select.genericlist', $options, 'adflist', 'class="inputboxsel" size="1"', 'id', 'name', 0 ); } function getGroupVals(){ $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select('a.id, a.name') ->from('#__jbcatalog_adfgroup AS a') ->innerjoin('#__jbcatalog_category_adfs_group as g ON g.group_id = a.id') ->where('g.cat_id = '.intval($this->getState('category.id'))) ->where('a.published = "1"'); $db->setQuery($query); try { $options = $db->loadObjectList(); } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); } if(count($options)){ $i = 0; foreach($options as $option){ $query = $db->getQuery(true) ->select('a.id, a.name, c.listview, c.filtered') ->from('#__jbcatalog_adf AS a') ->innerjoin('#__jbcatalog_adf_ingroups as g ON g.adfid = a.id') ->leftjoin('#__jbcatalog_category_adfs as c ON (c.adfs_id = a.id AND c.cat_id = '.intval($this->getState('category.id')).')') ->where('g.groupid = '.intval($option->id)) ->where('a.published = "1"'); $db->setQuery($query); $options[$i]->adfs = $db->loadObjectList(); $i++; } } return $options; } function getAdfVals(){ $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select('a.id, a.name, g.listview, g.filtered') ->from('#__jbcatalog_adf AS a') ->innerjoin('#__jbcatalog_category_adfs as g ON g.adfs_id = a.id') ->where('g.cat_id = '.intval($this->getState('category.id'))) ->where('g.group_id = 0') ->where('a.published = "1"'); // Get the options. $db->setQuery($query); try { $options = $db->loadObjectList(); } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); } return $options; } } <file_sep>/components/com_jbcatalog/helpers/path.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogPath { public static function getCatsPath($catid, $link = 0){ $db = JFactory::getDbo(); $path = array(); $db->setQuery( "SELECT * FROM #__jbcatalog_category" ." WHERE id = ".intval($catid) ); $cat = $db->loadObject(); if(!empty($cat)){ $path[] = array('title' => $cat->title, 'link' => $link?JRoute::_("index.php?option=com_jbcatalog&view=category&id=".$cat->id):''); $parent = $cat->parent_id; while($parent > 1){ $db->setQuery( "SELECT * FROM #__jbcatalog_category" ." WHERE id = ".intval($parent) ); $parent_obj = $db->loadObject(); //if($parent_obj->parent_id > 1){ $path[] = array('title' => $parent_obj->title, 'link' => JRoute::_("index.php?option=com_jbcatalog&view=category&id=".$parent_obj->id)); //} $parent = $parent_obj->parent_id; } } return $path; } } <file_sep>/administrator/components/com_jbcatalog/controllers/plugin.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogControllerPlugin extends JControllerForm { protected $text_prefix = 'COM_JBCATALOG_PLUGIN'; public function trash(){ $cid = $this->input->post->get('cid', array(), 'array'); $model = $this->getModel('Plugin', '', array()); $model->trash($cid); $this->setRedirect(JRoute::_('index.php?option=com_jbcatalog&view=plugin' . $this->getRedirectToListAppend(), false)); } public function batch($model = null) { JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); // Set the model $model = $this->getModel('Plugin', '', array()); // Preset the redirect $this->setRedirect(JRoute::_('index.php?option=com_jbcatalog&view=plugin' . $this->getRedirectToListAppend(), false)); return parent::batch($model); } } <file_sep>/administrator/components/com_jbcatalog/helpers/catalog.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class CatalogHelper { /** * Defines the valid request variables for the reverse lookup. */ protected static $_filter = array('option', 'view', 'layout'); /** * Configure the Linkbar. * * @param string The name of the active view. */ public static function addSubmenu($vName) { JHtmlSidebar::addEntry( JText::_('COM_JBCATALOG_SUB_CATEGORIES'), 'index.php?option=com_jbcatalog&view=categories', $vName == 'categories' ); JHtmlSidebar::addEntry( JText::_('COM_JBCATALOG_SUB_ITEMS'), 'index.php?option=com_jbcatalog&view=items', $vName == 'items' ); JHtmlSidebar::addEntry( JText::_('COM_JBCATALOG_SUB_ADFGROUPS'), 'index.php?option=com_jbcatalog&view=adfgroups', $vName == 'adfgroups' ); JHtmlSidebar::addEntry( JText::_('COM_JBCATALOG_SUB_ADFS'), 'index.php?option=com_jbcatalog&view=adfs', $vName == 'adfs' ); JHtmlSidebar::addEntry( JText::_('COM_JBCATALOG_SUB_PLUGINS'), 'index.php?option=com_jbcatalog&view=plugins', $vName == 'plugins' ); } } <file_sep>/administrator/components/com_jbcatalog/models/plugin.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogModelPlugin extends JModelAdmin { protected $text_prefix = 'COM_JBCATALOG_PLUGIN'; public function getForm($data = array(), $loadData = true) { // Get the form. $form = $this->loadForm('com_jbcatalog.plugin', 'plugin', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } // Modify the form based on access controls. if (!$this->canEditState((object) $data)) { // Disable fields for display. $form->setFieldAttribute('ordering', 'disabled', 'true'); $form->setFieldAttribute('publish_up', 'disabled', 'true'); $form->setFieldAttribute('publish_down', 'disabled', 'true'); $form->setFieldAttribute('state', 'disabled', 'true'); $form->setFieldAttribute('sticky', 'disabled', 'true'); // Disable fields while saving. // The controller has already verified this is a record you can edit. $form->setFieldAttribute('ordering', 'filter', 'unset'); $form->setFieldAttribute('publish_up', 'filter', 'unset'); $form->setFieldAttribute('publish_down', 'filter', 'unset'); $form->setFieldAttribute('state', 'filter', 'unset'); $form->setFieldAttribute('sticky', 'filter', 'unset'); } return $form; } public function getTable($type = 'Plugin', $prefix = 'JBCatalogTable', $config = array()) { return JTable::getInstance($type, $prefix, $config); } public function save($data) { $pk = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('plugin.id'); $isNew = true; $table = $this->getTable(); // Load the row if saving an existing item. if ($pk > 0) { $table->load($pk); $isNew = false; } // Bind the data. if (!$table->bind($data)) { $this->setError($table->getError()); return false; } // Alter the title & alias for save as copy. Also, unset the home record. if (!$isNew && $data['id'] == 0) { list($title, $alias) = $this->generateNewTitle($table->parent_id, $table->alias, $table->title); $table->title = $title; $table->alias = $alias; $table->published = 0; } // Check the data. if (!$table->check()) { $this->setError($table->getError()); return false; } // Store the data. if (!$table->store()) { $this->setError($table->getError()); return false; } $this->setState('adf.id', $table->id); $db = JFactory::getDbo(); // Clean the cache $this->cleanCache(); return true; } public function getItem($pk = null) { if ($item = parent::getItem($pk)) { // Convert the metadata field to an array. /*$registry = new JRegistry; $registry->loadString($item->metadata); $item->metadata = $registry->toArray();*/ } // Load associated contact items $app = JFactory::getApplication(); $assoc = isset($app->item_associations) ? $app->item_associations : 0; if ($assoc) { $item->associations = array(); if ($item->id != null) { $associations = JLanguageAssociations::getAssociations('com_jbcatalog', '#__jbcatalog_plugin', 'com_jbcatalog.plugin', $item->id); foreach ($associations as $tag => $association) { $item->associations[$tag] = $association->id; } } } return $item; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 1.6 */ protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_jbcatalog.edit.plugin.data', array()); if (empty($data)) { $data = $this->getItem(); // Prime some default values. if ($this->getState('plugin.id') == 0) { $app = JFactory::getApplication(); // $data->set('catid', $app->input->get('catid', $app->getUserState('com_jbcatalog.category.filter.category_id'), 'int')); } } $this->preprocessData('com_jbcatalog.plugin', $data); return $data; } public function publish(&$pks, $value = 1) { $table = $this->getTable(); $pks = (array) $pks; // Clean the cache $this->cleanCache(); // Ensure that previous checks doesn't empty the array if (empty($pks)) { return true; } return parent::publish($pks, $value); } public function getPlugins($pk = null){ $plugin_id = $this->getState('plugin.id'); require_once JPATH_COMPONENT.DIRECTORY_SEPARATOR."plugins".DIRECTORY_SEPARATOR."plugins.php"; $pl = new ParsePlugins('adf', $plugin_id, 0); $plugin['settings'] = $pl->getData('getPluginSettings'); return $plugin; } } <file_sep>/administrator/components/com_jbcatalog/models/plugins.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogModelPlugins extends JModelList { public function __construct($config = array()) { if (empty($config['filter_fields'])) { $config['filter_fields'] = array( 'id', 'a.id', 'menutype', 'a.menutype', 'title', 'a.title', 'alias', 'a.alias', 'published', 'a.published', 'access', 'a.access', 'access_level', 'language', 'a.language', 'checked_out', 'a.checked_out', 'checked_out_time', 'a.checked_out_time', 'lft', 'a.lft', 'rgt', 'a.rgt', 'level', 'a.level', 'path', 'a.path', 'client_id', 'a.client_id', 'home', 'a.home', ); $app = JFactory::getApplication(); $assoc = isset($app->item_associations) ? $app->item_associations : 0; if ($assoc) { $config['filter_fields'][] = 'association'; } } parent::__construct($config); } /** * Builds an SQL query to load the list data. * * @return JDatabaseQuery A query object. */ protected function getListQuery() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); $user = JFactory::getUser(); $app = JFactory::getApplication(); // Select all fields from the table. $query->select( $this->getState( 'list.select', $db->quoteName( array('a.id', 'a.title', 'a.name','a.published','a.description','a.ordering', 'a.version', 'a.type'), array(null, null, null, null, null, null, null, null) ) ) ); $query->from($db->quoteName('#__jbcatalog_plugins') . ' AS a'); //$query->leftJoin($db->quoteName('#__jbcatalog_items_cat') .' AS b ON b.item_id = a.id'); //$query->group("a.id"); // Exclude the root category. //$query->where('a.id > 1'); // Filter on the published state. $published = $this->getState('filter.published'); if (is_numeric($published)) { $query->where('a.published = ' . (int) $published); } elseif ($published === '') { $query->where('(a.published IN (0, 1))'); } $catid = $this->getState('filter.catid'); if (is_numeric($catid)) { $query->where('b.cat_id = ' . (int) $catid); } // Filter by search in title, alias or id if ($search = trim($this->getState('filter.search'))) { if (stripos($search, 'id:') === 0) { $query->where('a.id = ' . (int) substr($search, 3)); } else { $search = $db->quote('%' . $db->escape($search, true) . '%'); $query->where('(' . 'a.title LIKE ' . $search . ' OR a.alias LIKE ' . $search . ')'); } } // Add the list ordering clause. $query->order($db->escape($this->getState('list.ordering', 'a.ordering')) . ' ' . $db->escape($this->getState('list.direction', 'ASC'))); $query->order('a.id'); //echo nl2br(str_replace('#__','jos_',(string)$query)).'<hr/>'; return $query; } protected function populateState($ordering = null, $direction = null) { $published = $this->getUserStateFromRequest($this->context . '.published', 'filter_published', ''); $this->setState('filter.published', $published); $search = $this->getUserStateFromRequest($this->context . '.search', 'filter_search'); $this->setState('filter.search', $search); $catid = $this->getUserStateFromRequest($this->context . '.catid', 'filter_catid'); $this->setState('filter.catid', $catid); // List state information. parent::populateState('a.ordering', 'asc'); } public function pluginInstall(){ jimport('joomla.installer.helper'); jimport('joomla.filesystem.path'); $filename = $_FILES['plugin_installer']['name']; $baseDir = JPATH_ROOT."/tmp/";; if (file_exists( $baseDir )) { if (is_writable( $baseDir )) { if (move_uploaded_file( $_FILES['plugin_installer']['tmp_name'], $baseDir . $filename )) { if (JPath::setPermissions( $baseDir . $filename )) { $msg = ''; } else { $msg = JText::_("BLBE_UPL_PERM"); } } else { $msg = JText::_("BLBE_UPL_MOVE"); } } else { $msg = JText::_("BLBE_UPL_TMP"); } } else { $msg = JText::_("BLBE_UPL_TMPEX"); } if($msg != ''){ JError::raiseError(500, $msg ); //return false; } $retval = JInstallerHelper::unpack($baseDir . $filename); if(count($retval)){ $xml = JFactory::getXML($retval['dir']."/plugin.xml"); if($xml){ if(is_dir($retval['dir'])){ jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); JFolder::create(JPATH_ROOT."/administrator/components/com_jbcatalog/plugins/{$xml->name}", 0755); $uploaded = JFolder::copy($retval['dir'],JPATH_ROOT."/administrator/components/com_jbcatalog/plugins/{$xml->name}", '', true); if(is_dir($retval['dir'].'/BE')){ $uploaded = JFolder::copy($retval['dir'].'/BE/',JPATH_ROOT."/administrator/components/com_jbcatalog/", '', true); //var_dump($uploaded); } if(is_dir($retval['dir'].'/FE')){ $uploaded = JFolder::copy($retval['dir'].'/FE/',JPATH_ROOT."/components/com_jbcatalog/", '', true); } $db = $this->getDbo(); $query = "INSERT IGNORE INTO #__jbcatalog_plugins(name,title,description,version,published,type) VALUES('{$xml->name}','{$xml->title}','{$xml->description}','{$xml->version}','0','{$xml->type}')"; $db->setQuery($query); $db->query(); $plugin_id = $db->insertid(); require_once JPATH_COMPONENT.DIRECTORY_SEPARATOR."plugins".DIRECTORY_SEPARATOR."plugins.php"; $pl = new ParsePlugins('', $plugin_id, 0); $pl->getData('install'); //die(); } }else{ $msg = JText::_("BCAT_XML_FILE_NOT_FOUND"); JError::raiseError(500, $msg ); } } } public function pluginUninstall($cid){ if(count($cid)){ require_once JPATH_COMPONENT.DIRECTORY_SEPARATOR."plugins".DIRECTORY_SEPARATOR."plugins.php"; $db = $this->getDbo(); foreach($cid as $pid){ $pl = new ParsePlugins('', $pid, 0); $pl->getData('uninstall'); $db->setQuery( 'SELECT type FROM #__jbcatalog_plugins WHERE id='.intval($pid) ); //delete additional fields values if($db->loadResult() == 'adf'){ $db->setQuery( "DELETE v,a FROM #__jbcatalog_adf as a" ." LEFT JOIN #__jbcatalog_adf_values as v" ." ON a.id = v.adf_id" ." WHERE a.field_type = ".intval($pid) ); $db->execute(); } jimport('joomla.filesystem.folder'); //delete plugins file and sql $db->setQuery("SELECT name FROM #__jbcatalog_plugins WHERE id = ".intval($pid)); $name = $db->loadResult(); if($name){ JFolder::delete((JPATH_ROOT."/administrator/components/com_jbcatalog/plugins/{$name}")); $db->setQuery( "DELETE FROM #__jbcatalog_plugins WHERE id = ".intval($pid) ); $db->execute(); } } } } public function publish($cid, $value = 1) { if(count($cid)){ $db = $this->getDbo(); foreach($cid as $pid){ $db->setQuery("UPDATE #__jbcatalog_plugins SET published = '".$value."' WHERE id=".intval($pid)); $db->query(); } } } } <file_sep>/components/com_jbcatalog/views/category/tmpl/default_items.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; require_once JPATH_COMPONENT.'/helpers/images.php'; if(count($this->plugins['js'])){ foreach($this->plugins['js'] as $js){ echo $js; } } ?> <script> function hideFltrs(){ if(jQuery('#divfiltr').css('display') == 'block'){ jQuery('#divfiltr').hide(); }else{ jQuery('#divfiltr').show(); } } </script> <?php $sp = ((count($this->items) || $this->filtervar != null) && count($this->filters))?'':' style="display:none;"'; ?> <div <?php echo $sp;?> class="filtershead" onclick="javascript:hideFltrs();"><h5><?php echo JText::_("COM_JBCATALOG_FILTERS");?></h5></div> <div <?php echo $sp;?> id="divfiltr"> <?php if(count($this->filters)){ ?> <div id="divfiltr_area"> <form action="<?php echo JRoute::_("index.php?option=com_jbcatalog&view=category&id=".$this->catid);?>" method="post"> <?php foreach($this->filters as $filtr){ $adcc = ''; if($filtr[1]){ $adcc = 'class="hasTooltip" title="'.htmlspecialchars($filtr[1]).'"'; } echo '<div class="bcfilters"><label '.$adcc.'>'.$filtr[0].":</label><div>".$filtr[2]."</div></div>"; } ?> <div class="bcfilters"> <input type="submit" name="apply_filter" value="<?php echo JText::_("COM_JBCATALOG_FILTER_APPLY");?>" /> <input type="submit" name="clear_filter" value="<?php echo JText::_("COM_JBCATALOG_FILTER_CLEAR");?>" /> </div> <?php ?> </form> </div> <?php } ?> </div> <div class="catmain_div"> <?php echo $this->loadTemplate('items_table'); ?> </div> <div style="padding-top:15px; text-align: center;"> <form method="post"> <?php if(count($this->items)){ echo $this->pagination->getLimitBox(); } ?> </form> </div> <p class="counter"> <?php echo $this->pagination->getPagesCounter(); ?> </p> <div class="pagination"> <?php echo $this->pagination->getPagesLinks(); ?> </div> <file_sep>/administrator/components/com_jbcatalog/views/items/view.html.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; /** * View to edit a banner. * * @package Joomla.Administrator * @subpackage com_banners * @since 1.5 */ class jbcatalogViewItems extends JViewLegacy { protected $items; protected $pagination; protected $state; protected $categories; /** * Display the view */ public function display($tpl = null) { // Initialiase variables. $this->items = $this->get('Items'); $this->pagination = $this->get('Pagination'); $this->state = $this->get('State'); $this->categories = $this->get("Cats"); $this->addToolbar(); $this->sidebar = JHtmlSidebar::render(); parent::display($tpl); } /** * Add the page title and toolbar. * * @since 1.6 */ protected function addToolbar() { require_once JPATH_COMPONENT.'/helpers/catalog.php'; CatalogHelper::addSubmenu('items'); // Get the toolbar object instance $bar = JToolBar::getInstance('toolbar'); JToolbarHelper::title(JText::_('COM_JBCATALOG_ITEMS_TITLE'), 'menumgr.png'); JToolbarHelper::addNew('item.add'); JToolbarHelper::editList('item.edit'); JToolbarHelper::publish('items.publish', 'JTOOLBAR_PUBLISH', true); JToolbarHelper::unpublish('items.unpublish', 'JTOOLBAR_UNPUBLISH', true); JToolbarHelper::trash('items.trash'); JHtmlSidebar::setAction('index.php?option=com_jbcatalog&view=items'); JHtmlSidebar::addFilter( JText::_('JOPTION_SELECT_PUBLISHED'), 'filter_published', JHtml::_('select.options', JHtml::_('jgrid.publishedOptions'), 'value', 'text', $this->state->get('filter.published'), true) ); JHtmlSidebar::addFilter( JText::_('COM_JBCATALOG_FILTER_CAT'), 'filter_catid', JHtml::_('select.options', $this->categories, 'value', 'text', $this->state->get('filter.catid'), true) ); } protected function getSortFields() { return array( 'a.lft' => JText::_('JGRID_HEADING_ORDERING'), 'a.published' => JText::_('JSTATUS'), 'a.title' => JText::_('JGLOBAL_TITLE'), 'a.id' => JText::_('JGRID_HEADING_ID') ); } } <file_sep>/components/com_jbcatalog/models/item.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogModelItem extends JModelItem { /** * Model context string. * * @var string */ public $_context = 'com_jbcatalog.item'; /** * The category context (allows other extensions to derived from this model). * * @var string */ protected $_extension = 'com_jbcatalog'; protected $_item = null; /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState($ordering = null, $direction = null) { $app = JFactory::getApplication(); $this->setState('filter.extension', $this->_extension); $pk = $app->input->getInt('id'); $this->setState('item.id', $pk); $pk = $app->input->getInt('catid'); $this->setState('catid', $pk); $params = $app->getParams(); $this->setState('params', $params); $this->setState('filter.published', 1); $this->setState('filter.access', true); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * * @return string A store id. */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':'.$this->getState('filter.extension'); $id .= ':'.$this->getState('filter.published'); $id .= ':'.$this->getState('filter.access'); $id .= ':'.$this->getState('filter.parentId'); return parent::getStoreId($id); } /** * redefine the function an add some properties to make the styling more easy * * @return mixed An array of data items on success, false on failure. */ public function getItem() { if (!count($this->_item)) { $app = JFactory::getApplication(); $menu = $app->getMenu(); $active = $menu->getActive(); $params = new JRegistry; if ($active) { $params->loadString($active->params); } $id = (int) $this->getState('item.id'); $this->_item = $this->_getItem($id); $this->_item->adf = $this->_getAdfGroups($id, 0); $this->_item->adftab = $this->_getAdfGroups($id, 1); $this->_item->adf_singles = $this->_getAdfSingles($id); $this->_getItemImg($id); } return $this->_item; } private function _getItem($id){ $db = $this->getDbo(); $query = "SELECT * " ." FROM #__jbcatalog_items as a" ." WHERE id = {$id}"; $db->setQuery($query); return $db->loadObject(); } private function _getItemImg($id){ $db = $this->getDbo(); $query = "SELECT name FROM #__jbcatalog_files" ." WHERE catid = 2 AND itemid = ".intval($id)." AND ftype = 1" ." ORDER BY ordering"; $db->setQuery($query); $this->_item->images = $db->loadColumn(); } private function _getAdfGroups($id, $tab){ $db = $this->getDbo(); $query = "SELECT g.*" ." FROM #__jbcatalog_items_cat as a" ." JOIN #__jbcatalog_category as b" ." ON a.cat_id = b.id" ." JOIN #__jbcatalog_category_adfs_group as c" ." ON c.cat_id = b.id" ." JOIN #__jbcatalog_adfgroup as g" ." ON g.id = c.group_id AND g.published = '1'" ." WHERE a.item_id = {$id}" .($tab?" AND g.displayopt = '2'":" AND g.displayopt != '2'") ." GROUP BY g.id" ." ORDER BY g.ordering"; $db->setQuery($query); $adfs_groups = $db->loadObjectList(); for($i = 0; $i < count($adfs_groups); $i++){ $query = "SELECT d.* " ." FROM #__jbcatalog_adf as d" ." JOIN #__jbcatalog_adf_ingroups as i" ." ON i.adfid = d.id" ." WHERE i.groupid = ".$adfs_groups[$i]->id ." AND d.published = '1'" ." ORDER BY d.ordering, d.id"; $db->setQuery($query); $adfs = $db->loadObjectList(); for($j=0; $j<count($adfs); $j++){ ///array_push($array,$this->_getAdfValue($adfs[$j], $id)); $adf_show = array($adfs[$j]->name, $adfs[$j]->adf_tooltip, $this->_getAdfValue($adfs[$j], $id)); $adfs_groups[$i]->adf[] = $adf_show; } } return $adfs_groups; } private function _getAdfSingles($id){ $db = $this->getDbo(); $query = "SELECT d.* " ." FROM #__jbcatalog_adf as d" ." JOIN #__jbcatalog_category_adfs as i" ." ON i.adfs_id = d.id" ." WHERE i.group_id = 0" ." AND d.published = '1'" ." AND i.cat_id = ".intval($this->getState('catid')) ." ORDER BY d.ordering, d.id"; $db->setQuery($query); $adfs = $db->loadObjectList(); for($j=0; $j<count($adfs); $j++){ ///array_push($array,$this->_getAdfValue($adfs[$j], $id)); $adf_show = array($adfs[$j]->name, $adfs[$j]->adf_tooltip, $this->_getAdfValue($adfs[$j], $id)); $adfs[$j]->adf[] = $adf_show; } return $adfs; } private function _getAdfValue($adf, $id){ $db = $this->getDbo(); $db->setQuery( "SELECT adf_value FROM #__jbcatalog_adf_values" ." WHERE adf_id = ".$adf->id ." AND item_id = ".intval($id) ); $value = $db->loadResult(); //plugin get adf value require_once JPATH_COMPONENT_ADMINISTRATOR.DIRECTORY_SEPARATOR."plugins".DIRECTORY_SEPARATOR."plugins.php"; $pl = new ParsePlugins('adf', $adf->field_type); $value = $pl->getData('getItemFEAdfValue', array("adf" => $adf, "value" => $value, 'itemid' => $id)); if($value == array()){ $value = ''; } /* switch ($adf->field_type){ //text case '0': $value = htmlspecialchars($value); if($adf->adf_numeric){ $value = number_format(floatval($value), 0, '.', ' '); } break; //radio case '1': $value = $value?JText::_("Yes"):JText::_("No"); break; //editor case '2': $db->setQuery( "SELECT adf_text FROM #__jbcatalog_adf_values" ." WHERE adf_id = ".$adf->id ." AND item_id = ".intval($id) ); $value = $db->loadResult(); break; //select case '3': $db->setQuery( "SELECT b.name FROM #__jbcatalog_adf_values as a" ." JOIN #__jbcatalog_adf_select as b" ." ON b.id = a.adf_value" ." WHERE a.adf_id = ".$adf->id ." AND a.item_id = ".intval($id) ); $value = $db->loadResult(); break; //multi select case '4': $db->setQuery( "SELECT GROUP_CONCAT(b.name) FROM #__jbcatalog_adf_values as a" ." JOIN #__jbcatalog_adf_select as b" ." ON b.id = a.adf_value" ." WHERE a.adf_id = ".$adf->id ." AND a.item_id = ".intval($id) ); $value = $db->loadResult(); break; //link case '5': $value_link = htmlspecialchars($value); if(substr($value, 0, 4) != 'http'){ $value_link = 'http://'.$value_link; } $value = '<a href="'.$value_link.'" target="_blank">'.$value.'</a>'; break; //date case '6': $value = htmlspecialchars($value); break; //ranking case '7': $user = JFactory::getUser(); if($user->get('id')){ $db->setQuery(" SELECT value FROM #__jbcatalog_adf_rating WHERE rating_id = ".$adf->id." AND item_id = ".$id." AND usr_id = ".$user->get('id')); $value_sel = $db->loadResult(); $db->setQuery(" SELECT AVG(value) FROM #__jbcatalog_adf_rating WHERE rating_id = ".$adf->id." AND item_id = ".$id); $value_avg = $db->loadResult(); $value = '<span style="float:left; margin-right:10px;">'.sprintf("%01.2f", $value_avg).'</span>'; $value .= ' <input name="star2-'.$adf->id.'" value="1" '.($value_sel == '1'?'checked="checked"':"").' type="radio" class="starsik id'.$adf->id.'"/> <input name="star2-'.$adf->id.'" value="2" '.($value_sel == '2'?'checked="checked"':"").' type="radio" class="starsik id'.$adf->id.'"/> <input name="star2-'.$adf->id.'" value="3" '.($value_sel == '3'?'checked="checked"':"").' type="radio" class="starsik id'.$adf->id.'"/> <input name="star2-'.$adf->id.'" value="4" '.($value_sel == '4'?'checked="checked"':"").' type="radio" class="starsik id'.$adf->id.'"/> <input name="star2-'.$adf->id.'" value="5" '.($value_sel == '5'?'checked="checked"':"").' type="radio" class="starsik id'.$adf->id.'"/> <script> //var jsBase = juri::base();?> jQuery("input.id'.$adf->id.'").rating({ callback: function(value, link){ jQuery.ajax({ url: "'.juri::base().'" + "index.php?option=com_jbcatalog&task=rating&tmpl=component&rat="+value+"&id='.$id.'&adfid='.$adf->id.'", }); } }); </script> '; }else{ $db->setQuery(" SELECT AVG(value) FROM #__jbcatalog_adf_rating WHERE rating_id = ".$adf->id." AND item_id = ".$id); $value = $db->loadResult(); if(!$value){ $value = JText::_('COM_JBCATALOG_FE_NOT_RATED'); }else{ $value = sprintf("%01.2f", $value); } } break; case 8: //echo $value; if($value){ $db->setQuery( "SELECT b.title FROM #__jbcatalog_adf_values as a" ." JOIN #__jbcatalog_complex_item as b" ." ON b.id = a.adf_value" ." WHERE b.published != -2 AND a.adf_id = ".$value ); $value1 = $db->loadResult(); $val = $value; $vals = array(); while ($val){ if($val){ $query = 'SELECT title FROM #__jbcatalog_complex_item' .' WHERE id = '.$val; $db->setQuery($query); $title = $db->loadResult(); if($title){ $vals[] = $title; } $query = 'SELECT parent_id FROM #__jbcatalog_complex_item' .' WHERE id = '.$val; $db->setQuery($query); $val = $db->loadResult(); } } $value = ''; if(count($vals) > 1){ for($j=count($vals)-1;$j>=0;$j--){ if($j != count($vals)-1){ $value .= ' / '; } $value .= $vals[$j]; } }else{ $value = $value1; } } break; } */ if($value != ''){ $postf = str_replace('{sup}', '<sup>', $adf->adf_postfix); $postf = str_replace('{/sup}', '</sup>', $postf); $value = $adf->adf_prefix.$value.$postf; } return $value; } public function rate_item($id, $adf_id, $value){ $user = JFactory::getUser(); $db = $this->getDbo(); if($user->get('id') && $value < 6 && $value > 0){ $db->setQuery( "INSERT INTO #__jbcatalog_adf_rating(rating_id,item_id,usr_id,value)" ." VALUES({$adf_id},{$id},{$user->get('id')},{$value})" ." ON DUPLICATE KEY UPDATE value = '".$value."'" ); $db->execute(); }else if($user->get('id') && $value == '0'){ $db->setQuery( "DELETE FROM #__jbcatalog_adf_rating " ." WHERE rating_id = {$adf_id} AND item_id = {$id} AND usr_id = ".$user->get('id') ); $db->execute(); } } public function getIsAdmin(){ $user = JFactory::getUser(); $isAdmin = $user->get('isRoot'); return ($isAdmin); } public function getItemPosition(){ $db = JFactory::getDbo(); $db->setQuery('SELECT data FROM #__jbcatalog_options WHERE name="item_position"'); return $db->loadResult(); return (isset($_POST['edit']) && $isAdmin); } } <file_sep>/administrator/components/com_jbcatalog/models/fields/itemparentcomplex.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('JPATH_BASE') or die; JFormHelper::loadFieldClass('list'); class JFormFieldItemParentComplex extends JFormFieldList { protected $type = 'ItemParentComplex'; protected function getOptions() { $options = array(); $db = JFactory::getDbo(); $catid = 0; if(isset($_SESSION['complexitem.catid'])){ $catid = $_SESSION['complexitem.catid']; $db->setQuery( 'SELECT level FROM #__jbcatalog_complex WHERE id = '.$catid ); $level = $db->loadResult(); } if($this->value){ $db->setQuery( 'SELECT catid FROM #__jbcatalog_complex_item WHERE id = '.$this->value ); $catid = $db->loadResult(); } if(!$catid){ return JText::_("COM_JBCATALOG_NO_PARENT"); } $db->setQuery( 'SELECT level FROM #__jbcatalog_complex WHERE id = '.$catid ); $level = $db->loadResult(); if($level > 1){ if($this->value){ $db->setQuery( 'SELECT title as text, id as value FROM #__jbcatalog_complex_item WHERE catid = '.$catid .' ORDER BY ordering' ); }else{ $db->setQuery( 'SELECT i.title as text, i.id as value' .' FROM #__jbcatalog_complex_item as i' .' JOIN #__jbcatalog_complex as c ON i.catid = c.parent_id AND c.id ='.$catid .' ORDER BY i.ordering' ); } }else{ if($this->value){ $db->setQuery( 'SELECT title as text, id as value FROM #__jbcatalog_complex_item WHERE catid = '.$catid .' ORDER BY ordering' ); }else{ return JText::_("COM_JBCATALOG_NO_PARENT"); } } try { $options = $db->loadObjectList(); } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); } // Merge any additional options in the XML definition. $options = array_merge(parent::getOptions(), $options); return $options; } } <file_sep>/templates/cyklo/html/com_jbcatalog/category/default.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; JHtml::addIncludePath(JPATH_COMPONENT . '/helpers'); JHtml::_('behavior.caption'); echo JLayoutHelper::render('joomla.jbcatalog.categories_default', $this); ?> <div class="catmain_div"> <?php for($i=0;$i<count($this->categories);$i++){ echo "<div class='catimg_div'>"; if(isset($this->categories[$i]->images) && is_file(JPATH_ROOT.'/'.$this->categories[$i]->images)){ echo "<a href='".JRoute::_("index.php?option=com_jbcatalog&view=category&id=".$this->categories[$i]->id)."'><img src='".JURI::base().($this->categories[$i]->images)."'></a>"; } echo "</div>"; echo "<div class='catinfo_div'><a href='".JRoute::_("index.php?option=com_jbcatalog&view=category&id=".$this->categories[$i]->id)."'>".$this->categories[$i]->title."</a>"; echo "<div class='catdescr_div'>".$this->categories[$i]->descr."</div></div>"; echo "<div style='clear:both;margin-bottom:3px;'></div>"; } ?> </div> <?php echo $this->loadTemplate('items'); ?> <file_sep>/components/com_jbcatalog/views/item/tmpl/default.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; JHtml::addIncludePath(JPATH_COMPONENT . '/helpers'); //JHtml::_('behavior.caption'); //JHtml::_('bootstrap.tooltip'); $doc = JFactory::getDocument(); require_once JPATH_COMPONENT.'/helpers/images.php'; echo JBCatalogImages::includeFancy($this->document); /*dropbox*/ $doc->addStyleSheet('components/com_jbcatalog/css/smoothness/jquery-ui-1.10.3.custom.css'); $doc->addStyleSheet('components/com_jbcatalog/css/jquery.qtip.css'); $doc->addStyleSheet('components/com_jbcatalog/css/newproperties.css'); ?> <script type='text/javascript'> var adminMode = '<?php echo $this->isAdmin?true:false;?>'; var dataFromServer = <?php echo $this->pdata;?>;//data from dropbox </script> <script> function js_AdfGr(divid){ var blstat = jQuery('#'+divid).css('display'); if(blstat == 'block'){ jQuery('#'+divid).hide(); }else{ jQuery('#'+divid).show(); } } </script> <div> <div class="successDIV"><?php echo JText::_("COM_JBCATALOG_SAVEDSUCC");?></div> <!--<div> <h3><?php echo $this->item->title?></h3> </div>--> <div class="bc_header drop dropHeader"> <div class="dragText" data-index="index1"><h3><?php echo $this->item->title?></h3></div> </div> <?php if(isset($this->item->adftab) && count($this->item->adftab)){ echo JHtml::_('bootstrap.startTabSet', 'myTab', array('active' => 'details')); echo JHtml::_('bootstrap.addTab', 'myTab', 'details', JText::_('COM_JBCATALOG_ITEM_TAB', true)); } ?> <div class="bc_mainbl"> <div class="bc_mainbl_left drop dropLeft"> <div class='bc_img_block dragImage' data-index='index2'> <?php if(isset($this->item->images) && count($this->item->images)){ echo "<div id='img_t'>".JBCatalogImages::getClickableImg($this->item->images[0])."</div>"; } for($i=1; $i < count($this->item->images);$i++){ echo "<div class='item_miniimg_div'>".JBCatalogImages::getClickableImg($this->item->images[$i])."</div>"; } ?> <div style='clear:both;margin-bottom:3px;'></div> </div> </div> <div class="bc_maibl_right drop dropRight"> <div class="bc_descr_block dragText" data-index="index3"> <?php echo $this->item->descr;?> </div> </div> </div> <div class="bc_footer drop dropFooter"> <?php for($i = 0; $i < count($this->item->adf); $i++){ $show_adftitle = false; if(isset($this->item->adf[$i]->adf) && count($this->item->adf[$i]->adf)){ echo '<div id="adf_view_head_'.($this->item->adf[$i]->id).'" class="bc_adf dragParam" data-index="index'.(4+$i).'">'; echo '<h3 class="adfgroup_name_h3" onclick="javascritp:js_AdfGr(\'adf_view_'.($this->item->adf[$i]->id).'\');">'.$this->item->adf[$i]->name.'</h3>'; echo '<div class="adf_view_div" id="adf_view_'.($this->item->adf[$i]->id).'">'; for($j = 0; $j < count($this->item->adf[$i]->adf); $j++){ $adf = $this->item->adf[$i]->adf[$j]; if($adf[2]){ $show_adftitle = true; $adcc = ''; if($adf[1]){ $adcc = 'class="hasTooltip" title="'.htmlspecialchars($adf[1]).'"'; } echo "<div class='adf_clearfx_div'><label ".$adcc.">".$adf[0].":</label><div>".$adf[2]."</div></div>"; } } echo '</div>'; if($this->item->adf[$i]->displayopt == '0'){ echo '<script>jQuery("#adf_view_'.$this->item->adf[$i]->id.'").hide();</script>'; } echo "</div>"; if(!$show_adftitle){ echo '<script>jQuery("#adf_view_head_'.$this->item->adf[$i]->id.'").hide();</script>'; } } } $index = 4+$i+1; ?> <?php for($i = 0; $i < count($this->item->adf_singles); $i++){ $show_adftitle = false; if(isset($this->item->adf_singles[$i]->adf) && count($this->item->adf_singles[$i]->adf)){ echo '<div id="adfsingle_view_head_'.($this->item->adf_singles[$i]->id).'" class="bc_adf dragParam" data-index="index'.($index).'">'; echo '<div class="adf_view_div" id="adfsingle_view_'.($this->item->adf_singles[$i]->id).'">'; for($j = 0; $j < count($this->item->adf_singles[$i]->adf); $j++){ $adf = $this->item->adf_singles[$i]->adf[$j]; if($adf[2]){ $show_adftitle = true; $adcc = ''; if($adf[1]){ $adcc = 'class="hasTooltip" title="'.htmlspecialchars($adf[1]).'"'; } echo "<div class='adf_clearfx_div'><label ".$adcc.">".$adf[0].":</label><div>".$adf[2]."</div></div>"; } } echo '</div>'; echo "</div>"; $index ++; } } ?> </div> <?php if(isset($this->item->adftab) && count($this->item->adftab)){ echo JHtml::_('bootstrap.endTab'); } ?> <?php if(isset($this->item->adftab) && count($this->item->adftab)){ for($i = 0; $i < count($this->item->adftab); $i++){ if(isset($this->item->adftab[$i]->adf) && count($this->item->adftab[$i]->adf)){ echo JHtml::_('bootstrap.addTab', 'myTab', 'tab'.$this->item->adftab[$i]->id, $this->item->adftab[$i]->name); echo '<div class="adf_view_div dragParam" data-index="index'.($index+$i).'">'; for($j = 0; $j < count($this->item->adftab[$i]->adf); $j++){ $adf = $this->item->adftab[$i]->adf[$j]; if($adf[2]){ $adcc = ''; if($adf[1]){ $adcc = 'class="hasTooltip" title="'.$adf[1].'"'; } echo "<div class='adf_clearfx_div'><label ".$adcc.">".$adf[0].":</label><div>".$adf[2]."</div></div>"; } } echo '</div>'; echo JHtml::_('bootstrap.endTab'); } } } ?> <?php if(isset($this->item->adftab) && count($this->item->adftab)){ echo JHtml::_('bootstrap.endTabSet'); } ?> <?php if($this->isAdmin){ ?> <!---START dropbox--> <div class="parameters"> <div> <a href="#drag">Start drag</a> </div> <div> <a href="#showParams">Show params</a> </div> </div> <input type="button" name="save" value="Save" id="save"/> <input type="button" name="cancel" value="Cancel" id="cancel"/> <div id="modal" title="Edit options"> </div> <!-- underscore parts --> <script type="text/template" id="modalTemplate"> <div id="tabs"> <ul class="tabs"><%= tabs%></ul> <%= content%> </div> </script> <script type="text/template" id="inputTemplate"> <tr> <td><label for="<%= name%>"><%= labelText%></label></td> <td><%= element%></td> </tr> </script> <?php } ?> <script src="components/com_jbcatalog/libraries/dragbox/js/jquery-ui-1.10.3.custom.js"></script> <script src="components/com_jbcatalog/libraries/dragbox/js/underscore.js"></script> <script src="components/com_jbcatalog/libraries/dragbox/js/jquery.qtip.min.js"></script> <script src="components/com_jbcatalog/libraries/dragbox/js/drag.js"></script> </div> <file_sep>/templates/cyklo/html/com_jbcatalog/category/default_items.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; require_once JPATH_COMPONENT.'/helpers/images.php'; if(!empty($this->plugins['js'])){ foreach($this->plugins['js'] as $js){ echo $js; } } ?> <?php if(!empty($this->items)) { $filtr = array(); foreach ($this->items as $produkt) { if (isset($produkt->resyst_kategorie)) { $filtr[$produkt->resyst_kategorie['id']] = $produkt->resyst_kategorie['kategorie']; } } if (!empty($filtr)) { ?> <div class="filtr-box row"> <div class="span8"> <div class="filtr-label">Kategorie</div> <div class="filtr-tags"> <span class="kategorie_tag" data-filtr_kategorie_id="-1">Vše</span> <?php foreach ($filtr as $key=>$kat) { ?> <span class="kategorie_tag" data-filtr_kategorie_id="<?php echo $key; ?>"><?php echo $kat; ?></span> <?php } ?> </div> </div> <div class="span4 text-right"> <input type="text" id="produkty-search" placeholder="Hledaný výraz" /> <img id="produkty-search-btn" src="images/icon_search.png" alt="Hledat" data-toggle="tooltip" data-placement="right" title="Hledat" /> </div> </div> <?php } } ?> <div class="catmain_div"> <?php echo $this->loadTemplate('items_table'); ?> </div> <?php if(!empty($this->items)){ ?> <div class="products-footer"> <form method="post"> Zobrazit <?php echo $this->pagination->getLimitBox(); ?> produktů na stránce </form> <p class="counter"><?php echo $this->pagination->getPagesCounter(); ?> </p> <div class="pagination"> <?php echo $this->pagination->getPagesLinks(); ?> </div> </div> <?php } ?><file_sep>/administrator/components/com_jbcatalog/views/adf/view.html.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class jbcatalogViewAdf extends JViewLegacy { protected $form; protected $item; protected $state; protected $selvars; protected $complexvars; protected $plugins; /** * Display the view */ public function display($tpl = null) { // Initialiase variables. $this->form = $this->get('Form'); $this->item = $this->get('Item'); $this->state = $this->get('State'); $this->selvars = $this->get('SelVars'); $this->complexvars = $this->get('ComplexVars'); $this->plugins = $this->get('Plugins'); // Check for errors. if (count($errors = $this->get('Errors'))) { JError::raiseError(500, implode("\n", $errors)); return false; } $this->addToolbar(); $this->sidebar = JHtmlSidebar::render(); parent::display($tpl); } /** * Add the page title and toolbar. * * @since 1.6 */ protected function addToolbar() { require_once JPATH_COMPONENT.'/helpers/catalog.php'; CatalogHelper::addSubmenu('adfs'); JFactory::getApplication()->input->set('hidemainmenu', true); $user = JFactory::getUser(); $userId = $user->get('id'); $isNew = ($this->item->id == 0); //$checkedOut = !($this->item->checked_out == 0 || $this->item->checked_out == $userId); // Since we don't track these assets at the item level, use the category id. JToolbarHelper::title($isNew ? JText::_('COM_JBCATALOG_ADF_NEW') : JText::_('COM_JBCATALOG_ADF_EDIT'), '1.png'); // If not checked out, can save the item. //if (!$checkedOut || count($user->getAuthorisedCategories('com_jbcatalog', 'core.create')) > 0) { JToolbarHelper::apply('adf.apply'); JToolbarHelper::save('adf.save'); JToolbarHelper::save2new('adf.save2new'); } // If an existing item, can save to a copy. if (!$isNew) { JToolbarHelper::save2copy('adf.save2copy'); } if (empty($this->item->id)) { JToolbarHelper::cancel('adf.cancel'); } else { JToolbarHelper::cancel('adf.cancel', 'JTOOLBAR_CLOSE'); } } } <file_sep>/administrator/language/en-GB/en-GB.com_jbcatalog.ini COM_JBCATALOG="JBCatalog" COM_JBCATALOG_CATS_TITLE="Category List" COM_JBCATALOG_CATS_SEARCH_FILTER="Search Category..." COM_JBCATALOG_ITEMS_TITLE="Item List" COM_JBCATALOG_CATEGORY_DETAILS="Category Details" COM_JBCATALOG_FIELD_NAME_LABEL="Category Name" COM_JBCATALOG_FIELD_NAME_DESC="Category Name Description" COM_JBCATALOG_FIELD_ALIAS_DESC="Category Alias Description" COM_JBCATALOG_FIELD_PARENTCAT="Parent Category" COM_JBCATALOG_FIELD_PARENTCAT_DESC="Parent Category Description" COM_JBCATALOG_FIELD_STATUS_DESC="Status Description" COM_JBCATALOG_FIELD_LANGUAGE_DESC="Language Description" COM_JBCATALOG_FIELD_INFORMATION_MISC_LABEL="Description" COM_JBCATALOG_FIELD_INFORMATION_MISC_DESC="Category Description" COM_JBCATALOG_FIELD_PARAMS_IMAGE_LABEL="Category Image" COM_JBCATALOG_FIELD_PARAMS_IMAGE_DESC="Category Image Description" COM_JBCATALOG_FIELD_ADF_GROUPS="Field Groups" COM_JBCATALOG_CATEGORY_ITEMS="Category items" # COM_JBCATALOG_ITEMS_SEARCH_FILTER="Search Item..." COM_JBCATALOG_FIELD_ITEM_NAME_LABEL="Item Name" COM_JBCATALOG_FIELD_ITEM_NAME_DESC="Item Name Description" COM_JBCATALOG_FIELD_ITEM_STATE_DESC="Item Status Description" COM_JBCATALOG_FIELD_ITEM_LANGUAGE_DESC="Item Language Description" COM_JBCATALOG_FIELD_ITEM_INFORMATION_MISC_LABEL="Item Description" COM_JBCATALOG_FIELD_ITEM_INFORMATION_MISC_DESC="Item Description" COM_JBCATALOG_FIELD_ITEM_ALIAS_DESC="Item Alias Description" COM_JBCATALOG_ITEM_NEW="New Item" COM_JBCATALOG_ITEM_EDIT="Edit Item" COM_JBCATALOG_ITEM_DETAILS="Item Details" COM_JBCATALOG_ADF_LABEL="Item Fields" COM_JBCATALOG_ADF_FIELDTYPE_LABEL="Field Type" COM_JBCATALOG_ADF_FIELDTYPE_DESC="Select Field Type" COM_JBCATALOG_ADF_FIELDTYPE_TEXT="Text" COM_JBCATALOG_ADF_FIELDTYPE_RADIO="Radio" COM_JBCATALOG_ADF_FIELDTYPE_SELECT="Select" COM_JBCATALOG_ADF_FIELDTYPE_MULTISELECT="MultiSelect" COM_JBCATALOG_ADF_FIELDTYPE_LINK="Link" COM_JBCATALOG_ADF_FIELDTYPE_DATE="Date" COM_JBCATALOG_ADF_FIELDTYPE_RATING="Rating" COM_JBCATALOG_ADF_FIELDTYPE_EDITOR="Editor" COM_JBCATALOG_ADF_CATEGORY_DESC="Select field group" COM_JBCATALOG_SUB_CATEGORIES="Categories" COM_JBCATALOG_SUB_ITEMS="Items" COM_JBCATALOG_SUB_ADFGROUPS="Field Groups" COM_JBCATALOG_SUB_ADFS="Item Fields" COM_JBCATALOG_SUB_PLUGINS="Plugins" COM_JBCATALOG_CATEGORY_EDIT="Edit Category" COM_JBCATALOG_CATEGORY_NEW="New Category" COM_JBCATALOG_FILTER_CAT="Select Category" COM_JBCATALOG_ADF_EDIT="Edit item field" COM_JBCATALOG_ADF_NEW="New item field" COM_JBCATALOG_ADFGR_SEARCH_FILTER="Search field group..." COM_JBCATALOG_ADF_SEARCH_FILTER="Search item field..." COM_JBCATALOG_FIELD_DISPLAY_OPTION_LABEL="Field group display option" COM_JBCATALOG_FIELD_DISPLAY_OPTION_DESC="Please specify the way of displaying the Field Group Name and Item Fields on FE: Visible: Group Name and Item Fields are displayed by default, after click on Group Name Item Fields will be hidden Hidden: Item Fields are hidden by default and Group Name is displayed,after click on Group Name Item Fields will be displayed Separate Tab: Item Fields are displayed in the separate tab, tab name is Field Group Name" COM_JBCATALOG_VISIBLE="Expanded" COM_JBCATALOG_HIDDEN="Collapsed" COM_JBCATALOG_JASTAB="In separate tab" COM_JBCATALOG_ADF_NAME="Name" COM_JBCATALOG_ADF_NAME_DESC="Enter item field title" COM_JBCATALOG_SELECT_ITEM="Select item" COM_JBCATALOG_FILTER_SEARCH_DESC="Filter" COM_JBCATALOG_N_ITEMS_UNPUBLISHED="Unpublished" COM_JBCATALOG_N_ITEMS_PUBLISHED="Published" COM_JBCATALOG_N_ITEMS_TRASHED="Items trashed" COM_JBCATALOG_ADF_PREFIX="Prefix" COM_JBCATALOG_ADF_PREFIX_DESC="This information will be shown before the item field value on FE" COM_JBCATALOG_ADF_POSFIX="Postfix" COM_JBCATALOG_ADF_POSFIX_DESC="This information will be shown after the item field value on FE. Use {sup}{/sup} tag to use superscript text" COM_JBCATALOG_FIELD_ADF_TOOLTIP_LABEL="Tooltip" COM_JBCATALOG_FIELD_ADF_TOOLTIP_DESC="Item field description" COM_JBCATALOG_ADF_FIELDTYPE_COMPLEX="Complex field" COM_JBCATALOG_COMPLEX_FIELD="Complex fields list" COM_JBCATALOG_ADF_COMPLEX_LABEL="Complex Category" COM_JBCATALOG_ADF_COMPLEX_DESC="Select complex category" COM_JBCATALOG_ADF_FILTER_LABEL="Filter" COM_JBCATALOG_ADF_FILTER_DESC="Use item field as filter in item list" COM_JBCATALOG_ADDCHOICE="Add select value" COM_JBCATALOG_MOVEUP="Move Up" COM_JBCATALOG_MOVEDOWN="Move Down" COM_JBCATALOG_ADDNEW_ITEMS="Add select value" COM_JBCATALOG_FIELD_PARENTITEM="Parent Item" COM_JBCATALOG_FIELD_PARENTITEM_DESC="Choose parent item" COM_JBCATALOG_ADFGROUP_LABEL="Field Group" COM_JBCATALOG_ADFGROUP_DESC="Select Field Group" COM_JBCATALOG_ADFS_LABEL="Item fields" COM_JBCATALOG_ADFS_DESC="Select item fields" COM_JBCATALOG_NO_PARENT="No Parent Item" COM_JBCATALOG_ADDNEW="Add New" COM_JBCATALOG_SEL_OPTION="Select option" COM_JBCATALOG_ADFGROUP_NEW="New Group" COM_JBCATALOG_ADFGROUP_EDIT="Edit Group" COM_JBCATALOG_ADFGR_NAME_LABEL="Group Name" COM_JBCATALOG_ADFGR_NAME_DESC="Group Description" COM_JBCATALOG_ADF_FIELDTYPE_TEXT_DESC="Item field Textfield" COM_JBCATALOG_ADF_FIELDTYPE_RADIO_DESC="Item field Radio" COM_JBCATALOG_ADF_FIELDTYPE_SELECT_DESC="Item field Select" COM_JBCATALOG_ADF_FIELDTYPE_MULTISELECT_DESC="Item field MultiSelect" COM_JBCATALOG_ADF_FIELDTYPE_LINK_DESC="Item field Link" COM_JBCATALOG_ADF_FIELDTYPE_DATE_DESC="Item field Date" COM_JBCATALOG_ADF_FIELDTYPE_RATING_DESC="Item field Rating" COM_JBCATALOG_ADF_FIELDTYPE_EDITOR_DESC="Item field Editor" COM_JBCATALOG_ADF_FIELDTYPE_COMPLEX_DESC="Complex field" COM_JBCATALOG_PLUGINS_TITLE="Plugin List" COM_BCAT_PLUGIN_UNINSTALL="Are you sure? Plugin will be removed with data" COM_BCAT_PLUGIN_UNINSTALL_ALT="Uninstall plugins" COM_BCAT_PLGIN_NAME="Plugin Name" COM_BCAT_PLGIN_DESCRIPTION="Description" COM_BCAT_PLGIN_TYPE="Type" COM_BCAT_PLGIN_VERSION="Version" COM_BCAT_SUBMIT_PLUGIN="Install plugin" COM_JBCATALOG_SELECT="Select" COM_JBCATALOG_REMOVE="Remove" COM_JBCATALOG_CATEGORY_SAVE_SUCCESS="Category successfully saved" COM_JBCATALOG_ADF_SAVE_SUCCESS="Item field successfully saved" COM_JBCATALOG_ADFGROUP_SAVE_SUCCESS="Field group successfully saved" COM_JBCATALOG_PLUGIN_SAVE_SUCCESS="Plugin successfully saved" COM_JBCATALOG_ADF_FILTER_YES="Include into the Filter in the Category Item List on FE" COM_JBCATALOG_ADF_FILTER_NO="Do not include into the Filter in the Category Item List on FE" COM_JBCATALOG_ADFGROUPS_TITLE="Fields Group List" COM_JBCATALOG_ADFS_TITLE="Item Field List" COM_JBCATALOG_COMPLEXCAT_TITLE="Complex Category List" COM_JBCATALOG_COMPLEXITEMS_TITLE="Complex Item List" COM_JBCATALOG_ADDFIELDS="Fields" COM_JBCATALOG_CAT_ADF_GROUPNAME="Fields Group" COM_JBCATALOG_CAT_ADF_FIELDNAME="Fields" COM_JBCATALOG_CAT_SHOWONLIST="Show on list" COM_JBCATALOG_DISPLAY_FILTER="Display in Filter on FE"<file_sep>/administrator/components/com_jbcatalog/plugins/adfradio/adfradio.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class AdfRadioPlugin { public function getItemEdit($params = array()){ $adf = $params["adf"]; $value = $params["value"]; return JHTML::_('select.booleanlist', 'extraf['.$adf->id.']', 'class="btn-group"', $value, JText::_('JYES'), JText::_('JNO'),'extrf'.$adf->id ); } public function saveItemEdit($params = array()){ $db = JFactory::getDbo(); $adfid = $params["adfid"]; $val = $params["value"]; $itemid = $params["itemid"]; $db->setQuery("INSERT INTO #__jbcatalog_adf_values(item_id,adf_id,adf_value,adf_text)" ." VALUES({$itemid},{$adfid},'".addslashes($val)."','')"); $db->execute(); } public function getItemFEAdfValue($params = array()){ $value = $params["value"]; $value = $value?JText::_("Yes"):JText::_("No"); return $value; } public function getAdfFilter($params = array()){ $adf = $params["adf"]; $value = $params["value"]; return '<input type="checkbox" name="adf_filter['.$adf->id.']" value="1" '.($value?"checked":"").' />'; } public function getAdfFilterSQL($params = array()){ $tbl_pref = $params["adfid"]; $value = $params["value"]; $key = $tbl_pref; $filter['tbl'] = " LEFT JOIN #__jbcatalog_adf_values as v{$tbl_pref} ON a.id=v{$tbl_pref}.item_id" ." JOIN #__jbcatalog_adf as e{$tbl_pref} ON e{$tbl_pref}.id=v{$tbl_pref}.adf_id AND e{$tbl_pref}.published='1'"; $filter['sql'] = " AND (v{$tbl_pref}.adf_value = '{$value}' AND v{$tbl_pref}.adf_id = {$key})"; return $filter; } function __call($method, $args) { return null; } public function install(){ } public function uninstall(){ } public function getPluginItem(){ return null; } public function getPluginItemSave(){ return null; } } <file_sep>/modules/mod_jmslideshow/elements/layout.php <?php /* #------------------------------------------------------------------------ # Package - JoomlaMan JMSlideShow # Version 1.0 # ----------------------------------------------------------------------- # Author - JoomlaMan http://www.joomlaman.com # Copyright © 2012 - 2013 JoomlaMan.com. All Rights Reserved. # @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later # Websites: http://www.JoomlaMan.com #------------------------------------------------------------------------ */ // no direct access defined('_JEXEC') or die('Restricted access'); jimport('joomla.html.html'); jimport('joomla.form.formfield'); class JFormFieldLayout extends JFormField { protected $type = 'Layout'; //the form field type var $options = array(); protected function getInput() { $html=array(); $files=array(); $options = array(); $i=0; $html[]='<select class="jm-field single jm_select" name="'.$this->name.'">'; if(is_dir(JPATH_SITE . '/templates/' . $this->getTemplate() . '/html/mod_jmslideshow/')) if ($handle = opendir(JPATH_SITE . '/templates/' . $this->getTemplate() . '/html/mod_jmslideshow/')) { while (false !== ($entry = readdir($handle))) { $files[$entry]=$entry; if ($entry != "." && $entry != ".." &&$entry!="index.html"){ if($this->value==str_replace('.php','',$entry)) { $selected=" selected=true "; } else $selected=""; //Parser layout name $layout_name = str_replace('.php','',$entry); $order = 9999; ob_start(); readfile(JPATH_SITE . '/templates/' . $this->getTemplate() . '/html/mod_jmslideshow/' . $entry); $file_content = ob_get_clean(); preg_match("'<!--layout:(.*?),order:(.*?)-->'si", $file_content, $match); if(isset($match[1])) $layout_name = $match[1]; if(isset($match[2])) $order = $match[2]; $option_html = '<option '.$selected.' value="'.str_replace('.php','',$entry).'">'.$layout_name.'</option>'; $options[] = array('order'=>$order,'html'=> $option_html); //$html[]='<option '.$selected.' value="'.str_replace('.php','',$entry).'">'.$layout_name.'</option>'; } } closedir($handle); } if ($handle = opendir(JPATH_SITE.'/modules/mod_jmslideshow/tmpl/')) { while (false !== ($entry = readdir($handle))) { if(!in_array($entry,$files)) if ($entry != "." && $entry != ".." &&$entry!="index.html"){ if($this->value==str_replace('.php','',$entry)) { $selected=" selected=true "; } else $selected=""; //Parser layout name $layout_name = str_replace('.php','',$entry); $order = 9999; ob_start(); readfile(JPATH_SITE.'/modules/mod_jmslideshow/tmpl/' . $entry); $file_content = ob_get_clean(); preg_match("'<!--layout:(.*?),order:(.*?)-->'si", $file_content, $match); if(isset($match[1])) $layout_name = $match[1]; if(isset($match[2])) $order = $match[2]; $option_html = '<option '.$selected.' value="'.str_replace('.php','',$entry).'">'.$layout_name.'</option>'; $options[] = array('order'=>$order,'html'=> $option_html); } } closedir($handle); } $orders = array(); foreach($options as $key => $option){ $orders[$key] = $option['order']; } array_multisort($orders, SORT_ASC, $options); $html='<select class="jm-field single jm_select" name="'.$this->name.'">'; foreach($options as $option){ $html .= $option['html']; } $html .= '</select>'; return $html; } function getTemplate(){ $db=JFactory::getDBO(); $query=$db->getQuery(true); $query->select('*'); $query->from('#__template_styles'); $query->where('home=1'); $query->where('client_id=0'); $db->setQuery($query); return $db->loadObject()->template; } }<file_sep>/templates/cyklo/language/en-GB/en-GB.tpl_protostar.ini ; Joomla! Project ; Copyright (C) 2005 - 2015 Open Source Matters. All rights reserved. ; License GNU General Public License version 2 or later; see LICENSE.txt, see LICENSE.php ; Note : All ini files need to be saved as UTF-8 - No BOM TPL_CYKLO_XML_DESCRIPTION="Continuing the space theme (Solarflare from 1.0 and Milkyway from 1.5), Cyklo is the Joomla 3 site template based on Bootstrap from Twitter and the launch of the Joomla User Interface library (JUI)." TPL_CYKLO_BACKGROUND_COLOR_DESC="Choose a background colour for static layouts. If left blank the Default (#f4f6f7) is used." TPL_CYKLO_BACKGROUND_COLOR_LABEL="Background Colour" TPL_CYKLO_BACKTOTOP="Back to Top" TPL_CYKLO_COLOR_DESC="Choose an overall colour for the site template. If left blank the Default (#0088cc) is used." TPL_CYKLO_COLOR_LABEL="Template Colour" TPL_CYKLO_FLUID="Fluid" TPL_CYKLO_FLUID_LABEL="Fluid Layout" TPL_CYKLO_FLUID_DESC="Use Bootstrap's fluid or static container (both are responsive)." TPL_CYKLO_FONT_LABEL="Google Font for Headings" TPL_CYKLO_FONT_DESC="Load a Google font for the headings (H1, H2, H3, etc)." TPL_CYKLO_FONT_NAME_LABEL="Google Font Name" TPL_CYKLO_FONT_NAME_DESC="Example: Open+Sans or Source+Sans+Pro." TPL_CYKLO_LOGO_LABEL="Logo" TPL_CYKLO_LOGO_DESC="Upload a custom logo for the site template." TPL_CYKLO_STATIC="Static" <file_sep>/language/cs-CZ/cs-CZ.com_jbcatalog.ini COM_JBCATALOG_SELECT="Vybrat" COM_JBCATALOG_FILTER_APPLY="Filtrovat" COM_JBCATALOG_ITEM_TAB="Hlavní" COM_JBCATALOG_SELCAT="Vyberte kategorii" COM_JBCATALOG_TO="Do" COM_JBCATALOG_FROM="Od" COM_JBCATALOG_FE_NOT_RATED="Nehodnoceno" COM_JBCATALOG_FILTERS="Filtr" COM_JBCATALOG_FILTER_CLEAR="Vyčistit" COM_JBCATALOG_SAVEDSUCC="Uloženo" COM_JBCATALOG_TITLE="Název"<file_sep>/administrator/components/com_jbcatalog/controllers/item.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogControllerItem extends JControllerForm { public function batch($model = null) { JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); // Set the model $model = $this->getModel('Item', '', array()); // Preset the redirect $this->setRedirect(JRoute::_('index.php?option=com_jbcatalog&view=item' . $this->getRedirectToListAppend(), false)); return parent::batch($model); } public function showAdfAjax(){ JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); // Set the model $model = $this->getModel('Item', '', array()); //$cats = $_POST['catssel']; $item_id = intval($_POST['item_id']); header('Content-type: text/html; charset=UTF-8'); if(!empty($_POST['catssel'])){ echo $model->getItemAdfs($_POST['catssel'], $item_id); } // Close the application JFactory::getApplication()->close(); } } <file_sep>/administrator/components/com_jbcatalog/models/adfs.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogModelAdfs extends JModelList { public function __construct($config = array()) { if (empty($config['filter_fields'])) { $config['filter_fields'] = array( 'id', 'a.id', 'name', 'a.name', 'published', 'a.published', 'g.name', 'g.name', 'field_type', 'a.field_type' ); $app = JFactory::getApplication(); $assoc = isset($app->item_associations) ? $app->item_associations : 0; if ($assoc) { $config['filter_fields'][] = 'association'; } } parent::__construct($config); } /** * Builds an SQL query to load the list data. * * @return JDatabaseQuery A query object. */ protected function getListQuery() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); $user = JFactory::getUser(); $app = JFactory::getApplication(); // Select all fields from the table. $query->select( $this->getState( 'list.select', $db->quoteName( array('a.id', 'a.name', 'a.published', 'a.field_type', 'a.filters', 'a.ordering', 'b.title'), array(null, null, null, null, null, null, null) ) ) ); $query->select('GROUP_CONCAT(g.name ORDER BY g.name SEPARATOR ", ") as adfsgroup'); $query->from($db->quoteName('#__jbcatalog_adf') . ' AS a'); $query->leftJoin($db->quoteName('#__jbcatalog_plugins') .' AS b ON b.id = a.field_type AND b.published="1" AND b.type="adf"'); $query->leftJoin($db->quoteName('#__jbcatalog_adf_ingroups') .' AS i ON a.id = i.adfid'); $query->leftJoin($db->quoteName('#__jbcatalog_adfgroup') .' AS g ON g.id = i.groupid AND g.published != "-2"'); $query->group('a.id'); // Exclude the root category. //$query->where('a.id > 1'); // Filter on the published state. $published = $this->getState('filter.published'); if (is_numeric($published)) { $query->where('a.published = ' . (int) $published); } elseif ($published === '') { $query->where('(a.published IN (0, 1))'); } // Filter by search in title, alias or id if ($search = trim($this->getState('filter.search'))) { if (stripos($search, 'id:') === 0) { $query->where('a.id = ' . (int) substr($search, 3)); } else { $search = $db->quote('%' . $db->escape($search, true) . '%'); $query->where('(' . 'a.name LIKE ' . $search . ')'); } } // Add the list ordering clause. $query->order($db->escape($this->getState('list.ordering', 'a.ordering')) . ' ' . $db->escape($this->getState('list.direction', 'ASC'))); //echo nl2br(str_replace('#__','jos_',(string)$query)).'<hr/>'; return $query; } protected function populateState($ordering = null, $direction = null) { $search = $this->getUserStateFromRequest($this->context . '.search', 'filter_search'); $this->setState('filter.search', $search); // List state information. parent::populateState('a.ordering', 'asc'); } } <file_sep>/language/cs-CZ/cs-CZ.tpl_cyklo.sys.ini ; Joomla! Project ; Copyright (C) 2005 - 2015 Open Source Matters. All rights reserved. ; License GNU General Public License version 2 or later; see LICENSE.txt, see LICENSE.php ; Note : All ini files need to be saved as UTF-8 - No BOM TPL_CYKLO_POSITION_BANNER="Banner" TPL_CYKLO_POSITION_DEBUG="Debug" TPL_CYKLO_POSITION_POSITION-0="Search" TPL_CYKLO_POSITION_POSITION-10="Unused" TPL_CYKLO_POSITION_POSITION-11="Unused" TPL_CYKLO_POSITION_POSITION-12="Unused" TPL_CYKLO_POSITION_POSITION-13="Unused" TPL_CYKLO_POSITION_POSITION-14="Unused" TPL_CYKLO_POSITION_POSITION-15="Unused" TPL_CYKLO_POSITION_POSITION-1="Navigation" TPL_CYKLO_POSITION_POSITION-2="Breadcrumbs" TPL_CYKLO_POSITION_POSITION-3="Top center" TPL_CYKLO_POSITION_POSITION-4="Unused" TPL_CYKLO_POSITION_POSITION-5="Unused" TPL_CYKLO_POSITION_POSITION-6="Unused" TPL_CYKLO_POSITION_POSITION-7="Right" TPL_CYKLO_POSITION_POSITION-8="Left" TPL_CYKLO_POSITION_POSITION-9="Unused" TPL_CYKLO_POSITION_FOOTER="Footer" TPL_CYKLO_XML_DESCRIPTION="CYKLO is the Joomla 3 site template based on Bootstrap from Twitter and the launch of the Joomla User Interface library (JUI)." <file_sep>/modules/mod_jmslideshow/language/en-GB/en-GB.mod_jmslideshow.ini MOD_JMSLIDESHOW="Jm Slideshow Responsive" MOD_JMSLIDESHOW_RESPONSIVE_LBL="Responsive" MOD_JMSLIDESHOW_RESPONSIVE_DESC="Responsive" MOD_JMSLIDESHOW_WIDTH_LBL="Width" MOD_JMSLIDESHOW_WIDTH_DESC="Leave blank to set it auto full width in module position" MOD_JMSLIDESHOW_IMAGE_WIDTH_LBL="Image Width" MOD_JMSLIDESHOW_IMAGE_WIDTH_DESC="Image Width" MOD_JMSLIDESHOW_IMAGE_HEIGHT_LBL="Image Height" MOD_JMSLIDESHOW_IMAGE_HEIGHT_DESC="Image Height" MOD_JMSLIDESHOW_IMAGE_THUMBNAIL_WIDTH_LBL="Thumbnail Width" MOD_JMSLIDESHOW_IMAGE_THUMBNAIL_WIDTH_DESC="Thumbnail Width" MOD_JMSLIDESHOW_IMAGE_THUMBNAIL_HEIGHT_LBL="Thumbnail Height" MOD_JMSLIDESHOW_IMAGE_THUMBNAIL_HEIGHT_DESC="Thumbnail Height" MOD_JMSLIDESHOW_IMAGE_STYLE_LBL="Image style" MOD_JMSLIDESHOW_IMAGE_STYLE_DESC="Choose way to resize image" MOD_JMSLIDESHOW_IMAGE_STYLE_FILL="Fill" MOD_JMSLIDESHOW_IMAGE_STYLE_FIT="Fit" MOD_JMSLIDESHOW_IMAGE_STYLE_STRETCH="Stretch" MOD_JMSLIDESHOW_MODULE_CLASS_SFX_LBL="Module Class SFX" MOD_JMSLIDESHOW_MODULE_CLASS_SFX_DESC="Module Class SFX" MOD_JMSLIDESHOW_SOURCE_TAB_LBL="Source Options" MOD_JMSLIDESHOW_SLIDER_SOURCE_LBL="Slider Source" MOD_JMSLIDESHOW_SLIDER_SOURCE_DESC="Slider Source" MOD_JMSLIDESHOW_FILE_IMAGE_URL_LBL="Select Image" MOD_JMSLIDESHOW_FILE_IMAGE_URL_DESC="Select a image for your slide" MOD_JMSLIDESHOW_FILE_IMAGE_TITLE_LBL="Title" MOD_JMSLIDESHOW_FILE_IMAGE_TITLE_DESC="Fill title of image" MOD_JMSLIDESHOW_FILE_IMAGE_TITLE_LINK_LBL = "Link" MOD_JMSLIDESHOW_FILE_IMAGE_TITLE_LINK_DESC = "Link title" MOD_JMSLIDESHOW_FILE_IMAGE_DESC_LBL="Description" MOD_JMSLIDESHOW_FILE_IMAGE_DESC_DESC="Description" MOD_JMSLIDESHOW_FILE_IMAGE_LBL='List images' MOD_JMSLIDESHOW_FILE_IMAGE_DESC='' MOD_JMSLIDESHOW_FODER_ALL_IMAGE_LBL='Fodel Source' MOD_JMSLIDESHOW_FODER_ALL_IMAGE_DESC='/image/' MOD_JMSLIDESHOW_CATEGORY_LBL="Joomla Categories" MOD_JMSLIDESHOW_CATEGORY_DESC="Joomla Categories" MOD_JMSLIDESHOW_SPECIAL_ARTICLES_IDS_LBL="Special Articles IDs" MOD_JMSLIDESHOW_SPECIAL_ARTICLES_IDS_DESC="Enter article IDs like 1,2,3" MOD_JMSLIDESHOW_K2_CATEGORY_LBL="K2 Categories" MOD_JMSLIDESHOW_K2_CATEGORY_DESC="K2 Categories" MOD_JMSLIDESHOW_K2_SPECIAL_ARTICLES_IDS_LBL="K2 Special Articles IDs" MOD_JMSLIDESHOW_K2_SPECIAL_ARTICLES_IDS_DESC="Enter K2 article IDs like 1,2,3" MOD_JMSLIDESHOW_K2_IMAGE_SOURCE_LBL="Image Source" MOD_JMSLIDESHOW_K2_IMAGE_SOURCE_DESC="Image Source" MOD_JMSLIDESHOW_K2_IMAGE_SOURCE_FIELD="Image field" MOD_JMSLIDESHOW_K2_IMAGE_SOURCE_CONTENT="First image in content" MOD_JMSLIDESHOW_COUNT_LBL="Items" MOD_JMSLIDESHOW_COUNT_DESC="Number of slides. 0 to unlimted." MOD_JMSLIDESHOW_PROFILE_TAB_LBL="Profile Options" MOD_JMSLIDESHOW_SLIDER_THEME_LBL="Theme" MOD_JMSLIDESHOW_SLIDER_THEME_DESC="Theme" MOD_JMSLIDESHOW_EFFECT_LBL="Effect" MOD_JMSLIDESHOW_EFFECT_DESC="Effect" MOD_JMSLIDESHOW_EFFECT_FADE="Fade" MOD_JMSLIDESHOW_EFFECT_FADE_OUT="Fadeout" MOD_JMSLIDESHOW_EFFECT_SCROLLHORZ="ScrollHorz" MOD_JMSLIDESHOW_EFFECT_TITLE_SLIDE="TitleSlide" MOD_JMSLIDESHOW_EFFECT_TITLE_BLIND="TitleBlind" MOD_JMSLIDESHOW_AUTO_LBL="Auto Slide" MOD_JMSLIDESHOW_AUTO_DESC="Slides will automatically transition" MOD_JMSLIDESHOW_SPEED_LBL="Speed" MOD_JMSLIDESHOW_SPEED_DESC="The speed of the transition effect in milliseconds." MOD_JMSLIDESHOW_TIMEOUT_LBL="Timeout" MOD_JMSLIDESHOW_TIMEOUT_DESC="The time between slide transitions in milliseconds." MOD_JMSLIDESHOW_PAUSE_ONHOVER_LBL="Pause on hover" MOD_JMSLIDESHOW_PAUSE_ONHOVER_DESC="If true an auto-running slideshow will be paused while the mouse is over the slideshow." MOD_JMSLIDESHOW_CAPTION_POSITION_LBL="Caption position" MOD_JMSLIDESHOW_CAPTION_POSITION_DESC="Caption position" MOD_JMSLIDESHOW_CAPTION_LEFT_LBL="Caption left" MOD_JMSLIDESHOW_CAPTION_LEFT_DESC="Caption left position" MOD_JMSLIDESHOW_CAPTION_RIGHT_LBL="Caption right" MOD_JMSLIDESHOW_CAPTION_RIGHT_DESC="Caption right position" MOD_JMSLIDESHOW_CAPTION_TOP_LBL="Caption top" MOD_JMSLIDESHOW_CAPTION_TOP_DESC="Caption top position" MOD_JMSLIDESHOW_CAPTION_BOTTOM_LBL="Caption bottom" MOD_JMSLIDESHOW_CAPTION_BOTTOM_DESC="Caption bottom position" MOD_JMSLIDESHOW_CAPTION_WIDTH_LBL="Caption Width" MOD_JMSLIDESHOW_CAPTION_WIDTH_DESC="Caption Width in pixel" MOD_JMSLIDESHOW_SHOW_TITLE_LBL="Show title" MOD_JMSLIDESHOW_SHOW_TITLE_DESC="Show title" MOD_JMSLIDESHOW_SHOW_DESC_LBL="Show description" MOD_JMSLIDESHOW_SHOW_DESC_DESC="Show description" MOD_JMSLIDESHOW_DESC_LENGTH_LBL="Description length" MOD_JMSLIDESHOW_DESC_LENGTH_DESC="Description length" MOD_JMSLIDESHOW_SHOW_READMORE_LBL="Show read more link" MOD_JMSLIDESHOW_SHOW_READMORE_DESC="Show read more link" MOD_JMSLIDESHOW_READMORE_TEXT_LBL="Read more text" MOD_JMSLIDESHOW_READMORE_TEXT_DESC="Read more text" MOD_JMSLIDESHOW_POSITION_TOP_LEFT="Top Left" MOD_JMSLIDESHOW_POSITION_TOP_RIGHT="Top Right" MOD_JMSLIDESHOW_POSITION_BOTTOM_LEFT="Bottom Left" MOD_JMSLIDESHOW_POSITION_BOTTOM_RIGHT="Bottom Right" MOD_JMSLIDESHOW_NAVIGATOR_TAB_LBL="Navigator Options" MOD_JMSLIDESHOW_SHOW_NAV_BUTTONS_LBL="Show next/prev" MOD_JMSLIDESHOW_SHOW_NAV_BUTTONS_DESC="Show next/prev" MOD_JMSLIDESHOW_SHOW_PAGER_LBL="Show Pager" MOD_JMSLIDESHOW_SHOW_PAGER_DESC="Show Pager" MOD_JMSLIDESHOW_PAGER_POSITION_LBL="Pager Position" MOD_JMSLIDESHOW_PAGER_POSITION_DESC="Pager Position" MOD_JMSLIDESHOW_PAGER_LEFT_LBL="Pager left" MOD_JMSLIDESHOW_PAGER_LEFT_DESC="Pager left position" MOD_JMSLIDESHOW_PAGER_RIGHT_LBL="Pager right" MOD_JMSLIDESHOW_PAGER_RIGHT_DESC="Pager right position" MOD_JMSLIDESHOW_PAGER_TOP_LBL="Pager top" MOD_JMSLIDESHOW_PAGER_TOP_DESC="Pager top position" MOD_JMSLIDESHOW_PAGER_BOTTOM_LBL="Pager bottom" MOD_JMSLIDESHOW_PAGER_BOTTOM_DESC="Pager bottom position" MOD_JMSLIDESHOW_INCLUDE_JQUERY_LBL="jQuery" MOD_JMSLIDESHOW_INCLUDE_JQUERY_DESC="Include jQuery?" MOD_JMSLIDESHOW_ABOUT_TAB_LBL="About Us" MOD_JMSLIDESHOW_ABOUT_TAB_DESC="JM Slideshow is developed by JoomlaMan. This module will allow you to showcase images and articles on your joomla website. JoomlaMan is dedicated to bringing you some of the best extensions and templates on the internet. If you need any help with our products, please login to your account at www.joomlaman.com and post your message in our forum." MOD_JMSLIDESHOW_TITLE_LINK_LBL=Title link to content MOD_JMSLIDESHOW_TITLE_LINK_DESC=Title link to content MOD_JMSLIDESHOW_UPDATE_TAB_LBL=Update MOD_JMSLIDESHOW_ARTICLE_IMAGE_SOURCE_LBL="Image source" MOD_JMSLIDESHOW_ARTICLE_IMAGE_SOURCE_DESC="Choose image source" MOD_JMSLIDESHOW_ARTICLE_IMAGE_SOURCE_INTRO_FIELD="Intro Image" MOD_JMSLIDESHOW_ARTICLE_IMAGE_SOURCE_FULL_FIELD="Full article image" MOD_JMSLIDESHOW_IMAGE_SOURCE_CONTENT="First image in content" MOD_JMSLIDESHOW_ORDERING_LBL="Ordering" MOD_JMSLIDESHOW_ORDERING_DESC="Ordering items" MOD_JMSLIDESHOW_ORDER_BY_LBL="Order by" MOD_JMSLIDESHOW_ORDER_BY_DESC="Order by" MOD_JMSLIDESHOW_HIKASHOP_CATEGORY_LBL="Hikashop Categories" MOD_JMSLIDESHOW_HIKASHOP_CATEGORY_DESC="Hikashop Categories" MOD_JMSLIDESHOW_PRODUCT_IDS_LBL="Product IDs" MOD_JMSLIDESHOW_PRODUCT_IDS_DESC="Enter Hikashop Product IDs like 1,2,3" MOD_JMSLIDESHOW_DESC_HTML_LBL="Allowable tags" MOD_JMSLIDESHOW_DESC_HTML_DESC="Allowable HTML tags in description: Example a,br" JASC="Ascending" JDESC="Descending" JPOSTED_DATE="Posted date" JTITLE="Title" JORDERING="Ordering" MOD_JMSLIDESHOW_PAGER_TYPE_LBL="Pager type" MOD_JMSLIDESHOW_PAGER_TYPE_DESC="Pager type" JMBULLET="Bullet" JMNUMBER="Number" JMTHUMBNAIL="Thumbnail" JMAUTO="Auto"<file_sep>/modules/mod_jmslideshow/elements/jeupdate.php <?php /* #------------------------------------------------------------------------ # Package - JoomlaMan JMSlideShow # Version 1.0 # ----------------------------------------------------------------------- # Author - JoomlaMan http://www.joomlaman.com # Copyright © 2012 - 2013 JoomlaMan.com. All Rights Reserved. # @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later # Websites: http://www.JoomlaMan.com #------------------------------------------------------------------------ */ //-- No direct access defined('_JEXEC') or die('Restricted access'); jimport('joomla.html.html'); jimport('joomla.form.formfield'); class JFormFieldJEUpdate extends JFormField { protected $type = 'JEUpdate'; //the form field type var $options = array(); protected function getInput() { $html = ' <div class="update-tab"> <h3>This is Update tab!</h3> </div> '; return $html; } function getLabel() { return ''; } }<file_sep>/modules/mod_responsive_contact_form/mod_responsive_contact_form.php <?php /** * @package Module Responsive Contact Form for Joomla! 3.x * @version 3.0: mod_responsive_contact_form.php Novembar,2013 * @author Joomla Drive Team * @copyright (C) 2013- Joomla Drive * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html * */ defined('_JEXEC') or die; $document = JFactory::getDocument(); $document->addScriptDeclaration('jQuery.noConflict();'); // Javascript // $document->addScript('//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'); // $document->addScript(JURI::base(true) . '/modules/mod_responsive_contact_form/js/jqBootstrapValidation.min.js'); // $document->addScriptDeclaration('jQuery(function () { jQuery("input,select,textarea").not("[type=submit]").jqBootstrapValidation(); } );'); // Stylesheet $document->addStylesheet(JURI::base(true) . '/modules/mod_responsive_contact_form/css/style.css'); require_once('modules/mod_responsive_contact_form/formkey_class.php'); require_once('modules/mod_responsive_contact_form/recaptchalib.php'); $formKey = new formKey(); if ($_SERVER['REQUEST_METHOD'] == 'post') { // Validate the form key if (!isset($_POST['form_key']) || !$formKey->validate()) { // Form key is invalid, show an error $error = "Something went wrong. Please try again."; // kill program and return error message } } if (isset($_POST['sbutton'])) { $captcha_req = $params->get('captcha_req'); if ($captcha_req == 1) { $private_key = $params->get('private_key'); $resp = recaptcha_check_answer($private_key, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { // What happens when the CAPTCHA was entered incorrectly echo "<script>javascript:Recaptcha.reload();</script>"; // reload captcha $error = "Sorry, the verification code wasn't entered correctly. Try again."; // kill program and return error message } else { // Requesting form elements if (isset($_POST['email'])) $email = $_POST['email']; $name = $_POST['name']; if (isset($_POST['phone'])) $phone = $_POST['phone']; if (isset($_POST['type'])) $type = $_POST['type']; if (isset($_POST['message'])) $message = $_POST['message']; // Requesting Configuration elements $admin_email = $params->get('admin_email'); $cc_email = $params->get('cc_email'); $bcc_email = $params->get('bcc_email'); $success_notify = $params->get('success_notify'); $failure_notify = $params->get('failure_notify'); $ffield_name = $params->get('ffield_name'); $sfield_name = $params->get('sfield_name'); $tfield_name = $params->get('tfield_name'); $fofield_name = $params->get('fofield_name'); $fifield_name = $params->get('fifield_name'); // Building Mail Content $formcontent = "\n" . $ffield_name . ": $name"; if (isset($email)) { $formcontent .= "\n\n" . $sfield_name . ": $email"; } if (isset($phone)) { $formcontent .= "\n\n" . $tfield_name . ": $phone"; } if (isset($type)) { $formcontent .= "\n\n" . $fofield_name . ": $type"; } if (isset($message)) { $formcontent .= "\n\n" . $fifield_name . ": $message"; } // Enter a subject, only you will see this so make it useful $subject = $name . " Contacted through " . $_SERVER['HTTP_HOST']; if (isset($type)) { $subject .= " for $type"; } if (isset($_POST['email'])) $sender = array($email, $name); else $sender = $name; // Mail Configuration $mail = JFactory::getMailer(); $mail->setSender($sender); $mail->addRecipient($admin_email); if (isset($cc_email)) $mail->addCC($cc_email); if (isset($bcc_email)) $mail->addBCC($bcc_email); $mail->setSubject($subject); $mail->Encoding = 'base64'; $mail->setBody($formcontent); $status = $mail->Send(); } } else { // Requesting form elements if (isset($_POST['email'])) $email = $_POST['email']; $name = $_POST['name']; if (isset($_POST['phone'])) $phone = $_POST['phone']; if (isset($_POST['type'])) $type = $_POST['type']; if (isset($_POST['message'])) $message = $_POST['message']; // Requesting Configuration elements $admin_email = $params->get('admin_email'); $cc_email = $params->get('cc_email'); $bcc_email = $params->get('bcc_email'); $success_notify = $params->get('success_notify'); $failure_notify = $params->get('failure_notify'); $ffield_name = $params->get('ffield_name'); $sfield_name = $params->get('sfield_name'); $tfield_name = $params->get('tfield_name'); $fofield_name = $params->get('fofield_name'); $fifield_name = $params->get('fifield_name'); // Building Mail Content $formcontent = "\n" . $ffield_name . ": $name"; if (isset($email)) { $formcontent .= "\n\n" . $sfield_name . ": $email"; } if (isset($phone)) { $formcontent .= "\n\n" . $tfield_name . ": $phone"; } if (isset($type)) { $formcontent .= "\n\n" . $fofield_name . ": $type"; } if (isset($message)) { $formcontent .= "\n\n" . $fifield_name . ": $message"; } // Enter a subject, only you will see this so make it useful $subject = $_SERVER['HTTP_HOST'] . ' - kontaktní formulář'; if (isset($_POST['email'])) $sender = array($email, $name); else $sender = $name; // Mail Configuration $mail = JFactory::getMailer(); $mail->setSender($sender); $mail->addRecipient($admin_email); if (isset($cc_email)) $mail->addCC($cc_email); if (isset($bcc_email)) $mail->addBCC($bcc_email); $mail->setSubject($subject); $mail->Encoding = 'base64'; $mail->setBody($formcontent); $status = $mail->Send(); } } ?> <section id="contact"> <script type="text/javascript"> var RecaptchaOptions = { theme: "<?php echo $params->get('captcha_theme'); ?>" }; </script> <form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="POST" class="form-horizontal" id="contact-form" novalidate> <?php $formKey->outputKey(); ?> <fieldset> <!-- Alert Box--> <?php if (isset($status)) { ?> <div class="alert <?php if ($status !== true) { ?> alert-error <?php } else { ?> alert-success <?php } ?>"> <button type="button" class="close" data-dismiss="alert">&times;</button> <strong><?php if ($status !== true) { echo $failure_notify; } else { echo $success_notify; } ?></strong> <br/> <?php if ($status !== true) { echo $status; } ?> </div> <?php } if (isset($error)) { ?> <div class="alert alert-error"> <button type="button" class="close" data-dismiss="alert">&times;</button> <strong> <?= $error; ?></strong> </div> <?php } ?> <div class="control-group"> <?php if ($params->get('subject_publish')) { ?> <div class="span7 predmet"> <input class="input-80" name="type" type="text" id="inputType" placeholder="<?php echo $params->get('fofield_name'); ?>"> </div> <?php } ?> <div class="span4"> <input class="input-80" name="name" type="text" id="inputName" placeholder="<?php echo $params->get('ffield_name'); ?>" required> <input class="input-80" name="email" type="email" id="inputEmail" placeholder="<?php echo $params->get('sfield_name'); ?>" <?php echo $params->get('email_req'); ?>> </div> <div class="span7"> <textarea class="input-80" name="message" rows="12" id="inputMessage" placeholder="<?php echo $params->get('fifield_name'); ?>" required></textarea> </div> </div> <?php if ($params->get('captcha_req') == 1) { ?> <!-- Captcha Field --> <div class="control-group"> <label class="control-label" for="recaptcha">Are you human?</label> <div class="controls" id="recaptcha"> <p> <?php $publickey = $params->get('public_key'); // Add your own public key here echo recaptcha_get_html($publickey); ?> </p> </div> </div> <?php } if ($params->get('admin_email')) { ?> <!-- Submit Button --> <div class="control-group"> <div class="text-right"> <button type="submit" name="sbutton" value="Send" class="btn btn-primary"><?php echo $params->get('bs_name'); ?></button> </div> </div> <?php } else { ?> <p style="font-type:bold">Please Enter Admin E-Mail address in the backend.</p> <?php } ?> </fieldset> </form> </section><file_sep>/administrator/components/com_jbcatalog/plugins/adfmultiselect/adfmultiselect.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class AdfMultiSelectPlugin { private function _getID(){ $db = JFactory::getDbo(); $db->setQuery("SELECT id FROM #__jbcatalog_plugins WHERE name = 'adfmultiselect'"); return $db->loadResult(); } //when this type selected public function getAdfViewJSSelected(){ $js['multiselect'] = 'if(obj.value == '.$this->_getID().'){ jQuery("#seltable").show(); }'; return $js; } public function getAdfViewJSSelectedPre(){ $js['select'] = 'jQuery("#seltable").hide();'; return $js; } function __call($method, $args) { return null; } //add javascript to additional field view public function getAdfViewJS(){ $js = array(); $js['select'] = '<script type="text/javascript"> function Delete_tbl_row(element) { var del_index = element.parentNode.parentNode.sectionRowIndex; var tbl_id = element.parentNode.parentNode.parentNode.parentNode.id; element.parentNode.parentNode.parentNode.deleteRow(del_index); } function getObj(name) { if (document.getElementById) { return document.getElementById(name); } else if (document.all) { return document.all[name]; } else if (document.layers) { return document.layers[name]; } } function add_selval(){ if(!getObj("addsel").value){ return false; } var tbl_elem = getObj("seltable"); var row = tbl_elem.insertRow(tbl_elem.rows.length - 2); var cell1 = document.createElement("td"); var cell2 = document.createElement("td"); var cell3 = document.createElement("td"); var cell4 = document.createElement("td"); cell1.innerHTML = \'<input type="hidden" name="adeslid[]" value="0" /><a href="javascript:void(0);" title="'.JText::_('COM_JBCATALOG_REMOVE').'" onClick="javascript:Delete_tbl_row(this);"><input type="hidden" value="0" name="selid[]" /><img src="'.JURI::base().'components/com_jbcatalog/images/publish_x.png" title="'.JText::_('COM_JBCATALOG_REMOVE').'" /></a>\'; var inp = document.createElement("input"); inp.type="text"; inp.setAttribute("maxlength",255); inp.value = getObj("addsel").value; inp.name = "selnames[]"; inp.setAttribute("size",50); cell2.appendChild(inp); row.appendChild(cell1); row.appendChild(cell2); row.appendChild(cell3); row.appendChild(cell4); getObj("addsel").value = ""; ReAnalize_tbl_Rows("seltable"); } //// function ReAnalize_tbl_Rows( tbl_id ) { start_index =1; var tbl_elem = getObj(tbl_id); if (tbl_elem.rows[start_index]) { for (var i=start_index; i<tbl_elem.rows.length-2; i++) { if (i > 1) { tbl_elem.rows[i].cells[2].innerHTML = \'<a href="javascript: void(0);" onClick="javascript:Up_tbl_row(this); return false;" title="'.JText::_('COM_JBCATALOG_MOVEUP').'"><img src="components/com_jbcatalog/images/up.gif" border="0" alt="'. JText::_('COM_JBCATALOG_MOVEUP').'"></a>\'; } else { tbl_elem.rows[i].cells[2].innerHTML = ""; } if (i < (tbl_elem.rows.length - 3)) { tbl_elem.rows[i].cells[3].innerHTML = \'<a href="javascript: void(0);" onClick="javascript:Down_tbl_row(this); return false;" title="'.JText::_('COM_JBCATALOG_MOVEDOWN').'"><img src="components/com_jbcatalog/images/down.gif" border="0" alt="'.JText::_('COM_JBCATALOG_MOVEDOWN').'"></a>\'; } else { tbl_elem.rows[i].cells[3].innerHTML = ""; } } } } function Up_tbl_row(element) { if (element.parentNode.parentNode.sectionRowIndex > 1) { var sec_indx = element.parentNode.parentNode.sectionRowIndex; var table = element.parentNode.parentNode.parentNode; var tbl_id = table.parentNode.id; var row = table.insertRow(sec_indx - 1); row.appendChild(element.parentNode.parentNode.cells[0]); row.appendChild(element.parentNode.parentNode.cells[0]); //row.appendChild(element.parentNode.parentNode.cells[0]); //row.appendChild(element.parentNode.parentNode.cells[0]); //row.appendChild(element.parentNode.parentNode.cells[0]); //row.appendChild(element.parentNode.parentNode.cells[0]); var cell3 = document.createElement("td"); var cell4 = document.createElement("td"); row.appendChild(cell3); row.appendChild(cell4); element.parentNode.parentNode.parentNode.deleteRow(element.parentNode.parentNode.sectionRowIndex); ReAnalize_tbl_Rows(tbl_id); } } function Down_tbl_row(element) { if (element.parentNode.parentNode.sectionRowIndex < element.parentNode.parentNode.parentNode.rows.length - 1) { var sec_indx = element.parentNode.parentNode.sectionRowIndex; var table = element.parentNode.parentNode.parentNode; var tbl_id = table.parentNode.id; var row = table.insertRow(sec_indx + 2); row.appendChild(element.parentNode.parentNode.cells[0]); row.appendChild(element.parentNode.parentNode.cells[0]); //row.appendChild(element.parentNode.parentNode.cells[0]); //row.appendChild(element.parentNode.parentNode.cells[0]); //row.appendChild(element.parentNode.parentNode.cells[0]); //row.appendChild(element.parentNode.parentNode.cells[0]); var cell3 = document.createElement("td"); var cell4 = document.createElement("td"); row.appendChild(cell3); row.appendChild(cell4); element.parentNode.parentNode.parentNode.deleteRow(element.parentNode.parentNode.sectionRowIndex); ReAnalize_tbl_Rows(tbl_id); } }</script>'; return $js; } public function getAdfViewExtra($params = array()){ $adf_id = (int) $params['adfid']; $db = JFactory::getDbo(); $db->setQuery( "SELECT * FROM #__jbcatalog_adf_select" ." WHERE field_id = ".$adf_id ." ORDER BY ordering" ); $selvars = $db->loadObjectList(); $html = '<div class="control-group"> <hr /> <div class="controls"> <table id="seltable"> <tr> <th width="20">#</th> <th>'.JText::_( 'NAME' ).'</th> </tr>'; for($i=0;$i<count($selvars);$i++){ $html .= "<tr>"; $html .= '<td><input type="hidden" name="adeslid[]" value="'.$selvars[$i]->id.'" /><a href="javascript:void(0);" title="'.JText::_('COM_JBCATALOG_REMOVE').'" onClick="javascript:Delete_tbl_row(this);"><img src="'.JURI::base().'components/com_jbcatalog/images/publish_x.png" title="'.JText::_('COM_JBCATALOG_REMOVE').'" /></a></td>'; $html .= "<td><input type='text' name='selnames[]' size='50' value='".htmlspecialchars(stripslashes($selvars[$i]->name),ENT_QUOTES)."' /></td>"; $html .= '<td>'; if($i > 0){ $html .= '<a href="javascript: void(0);" onClick="javascript:Up_tbl_row(this); return false;" title="'.JText::_('COM_JBCATALOG_MOVEUP').'"><img src="components/com_jbcatalog/images/up.gif" border="0" alt="'.JText::_('COM_JBCATALOG_MOVEUP').'"></a>'; } $html .= '</td>'; $html .= '<td>'; if($i < count($selvars) - 1){ $html .= '<a href="javascript: void(0);" onClick="javascript:Down_tbl_row(this); return false;" title="'.JText::_('COM_JBCATALOG_MOVEDOWN').'"><img src="components/com_jbcatalog/images/down.gif" border="0" alt="'.JText::_('COM_JBCATALOG_MOVEDOWN').'"></a>'; } $html .= '</td>'; $html .= "</tr>"; } $html .= '<tr> <td colspan="2"><hr /></td> </tr> <tr> <th><input type="button" style="cursor:pointer;" value="'.JText::_('COM_JBCATALOG_ADDCHOICE').'" onclick="add_selval();" /></th> <th><input type="text" maxlength="255" size="50" name="addsel" value="" id="addsel" /></th> </tr> </table> </div> <hr /> </div>'; $htmls['select'] = $html; return $htmls; } public function saveAdfData($params = array()){ $adfid = $params['adfid']; $mj = 0; $mjarr = array(); $db = JFactory::getDbo(); if(isset($_POST['selnames']) && count($_POST['selnames'])){ foreach($_POST['selnames'] as $selname){ if($_POST['adeslid'][$mj]){ $db->setQuery("UPDATE #__jbcatalog_adf_select SET name = '".addslashes($selname)."'," ." ordering = {$mj} WHERE id = ".intval($_POST['adeslid'][$mj])); $db->execute(); $mjarr[] = intval($_POST['adeslid'][$mj]); }else{ $db->setQuery("INSERT INTO #__jbcatalog_adf_select(name,field_id,ordering)" ." VALUES('".addslashes($selname)."',{$adfid},{$mj})"); $db->execute(); $mjarr[] = $db->insertid(); } $mj++; } }else{ $db->setQuery("DELETE FROM #__jbcatalog_adf_select WHERE field_id={$adfid}"); $db->execute(); } if(count($mjarr)){ $db->setQuery("DELETE FROM #__jbcatalog_adf_select WHERE field_id={$adfid} AND id NOT IN (".implode(',',$mjarr).")"); $db->execute(); } } public function getItemEdit($params = array()){ $adfid = $params["adf"]->id; $item_id = $params["itemid"]; $db = JFactory::getDbo(); $db->setQuery( "SELECT * FROM #__jbcatalog_adf_select" ." WHERE field_id = ".$adfid ." ORDER BY ordering" ); $selarr = $db->loadObjectList(); $db->setQuery( "SELECT adf_value FROM #__jbcatalog_adf_values" ." WHERE adf_id = ".$adfid ." AND item_id = ".intval($item_id) ); $value = $db->loadColumn(); if(!count($selarr)){ return ''; } return JHTML::_('select.genericlist', $selarr, 'extraf['.$adfid.'][]', 'class="inputboxsel" multiple size="1"', 'id', 'name', $value ); } public function saveItemEdit($params = array()){ $db = JFactory::getDbo(); $adfid = $params["adfid"]; $value = $params["value"]; $itemid = $params["itemid"]; if(count($value)){ foreach($value as $val){ $db->setQuery("INSERT INTO #__jbcatalog_adf_values(item_id,adf_id,adf_value,adf_text)" ." VALUES({$itemid},{$adfid},'".addslashes($val)."','')"); $db->execute(); } } } public function getItemFEAdfValue($params = array()){ $adf = $params["adf"]; $id = $params["itemid"]; $db = JFactory::getDbo(); $db->setQuery( "SELECT GROUP_CONCAT(b.name) FROM #__jbcatalog_adf_values as a" ." JOIN #__jbcatalog_adf_select as b" ." ON b.id = a.adf_value" ." WHERE a.adf_id = ".$adf->id ." AND a.item_id = ".intval($id) ); $value = $db->loadResult(); return $value; } public function getAdfFilter($params = array()){ $adf = $params["adf"]; $value = $params["value"]; $db = JFactory::getDbo(); $db->setQuery( "SELECT * FROM #__jbcatalog_adf_select" ." WHERE field_id = ".$adf->id ." ORDER BY ordering" ); $selarr = $db->loadObjectList(); if(!count($selarr)){ return ''; }else{ $null_arr[] = JHTML::_('select.option', "", JText::_('COM_JBCATALOG_SELECT'), 'id', 'name' ); $selarr = array_merge($null_arr,$selarr); } return JHTML::_('select.genericlist', $selarr, 'adf_filter['.$adf->id.']', 'class="inputboxsel" size="1"', 'id', 'name', $value ); } public function getAdfFilterSQL($params = array()){ $tbl_pref = $params["adfid"]; $value = $params["value"]; $key = $tbl_pref; $filter['tbl'] = " LEFT JOIN #__jbcatalog_adf_values as v{$tbl_pref} ON a.id=v{$tbl_pref}.item_id" ." JOIN #__jbcatalog_adf as e{$tbl_pref} ON e{$tbl_pref}.id=v{$tbl_pref}.adf_id AND e{$tbl_pref}.published='1'"; $filter['sql'] = " AND (v{$tbl_pref}.adf_value = '{$value}' AND v{$tbl_pref}.adf_id = {$key})"; return $filter; } public function install(){ } public function uninstall(){ } public function getPluginItem(){ return null; } public function getPluginItemSave(){ return null; } } <file_sep>/modules/mod_jmslideshow/elements/foldersource.php <?php /* #------------------------------------------------------------------------ # Package - JoomlaMan JMSlideShow # Version 1.0 # ----------------------------------------------------------------------- # Author - JoomlaMan http://www.joomlaman.com # Copyright © 2012 - 2013 JoomlaMan.com. All Rights Reserved. # @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later # Websites: http://www.JoomlaMan.com #------------------------------------------------------------------------ */ //-- No direct access defined('_JEXEC') or die('Restricted access'); class JFormFieldFolderSource extends JFormField { /** * The form field type. * * @var string * @since 11.1 */ protected $type = 'FolderSource'; /** * Method to get the field input markup for a generic list. * Use the multiple attribute to enable multiselect. * * @return string The field input markup. * * @since 11.1 */ protected function getInput() { // Initialize variables. $html = array(); $attr = ''; // Initialize some field attributes. $attr .= $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; // To avoid user's confusion, readonly="true" should imply disabled="true". if ((string) $this->element['readonly'] == 'true' || (string) $this->element['disabled'] == 'true') { $attr .= ' disabled="disabled"'; } $attr .= $this->element['size'] ? ' size="' . (int) $this->element['size'] . '"' : ''; $attr .= $this->multiple ? ' multiple="multiple"' : ''; // Initialize JavaScript field attributes. $attr .= $this->element['onchange'] ? ' onchange="' . (string) $this->element['onchange'] . '"' : ''; // Get the field options. $options = (array) $this->getOptions(); // Create a read-only list (no name) with a hidden input to store the value. if ((string) $this->element['readonly'] == 'true') { $html[] = JHtml::_('select.genericlist', $options, '', trim($attr), 'value', 'text', $this->value, $this->id); $html[] = '<input type="hidden" name="' . $this->name . '" value="' . $this->value . '"/>'; } // Create a regular list. else { $html[] = JHtml::_('select.genericlist', $options, $this->name, trim($attr), 'value', 'text', $this->value, $this->id); } return implode($html); } /** * Method to get the field options. * * @return array The field option objects. * * @since 11.1 */ protected function getOptions() { // Initialize variables. $options = array(); //Joomla Categories Options $options[] = JHtml::_('select.option', 1, 'Joomla Categories'); //Special Articles IDs $options[] = JHtml::_('select.option', 2, 'Special Articles IDs'); $options[] = JHtml::_('select.option',7,'Featured Articles'); //K2 Categories $db = JFactory::getDbo(); $query = "SELECT extension_id FROM #__extensions WHERE name IN('k2','com_k2') AND type='component'"; $db->setQuery($query); $result = $db->loadResult(); if ($result) { $options[] = JHtml::_('select.option', 3, 'K2 Categories'); $options[] = JHtml::_('select.option', 4, 'Special K2 IDs'); $options[] = JHtml::_('select.option',8,'K2 Featured Articles'); } //Hilashop Categories $query = "SELECT extension_id FROM #__extensions WHERE name IN('hikashop') AND type='component'"; $db->setQuery($query); $result = $db->loadResult(); if($result){ $options[] = JHtml::_('select.option',5,'Hikashop Categories'); $options[] = JHtml::_('select.option',6,'Hikashop Product IDs'); } $options[] = JHtml::_('select.option',9,'From directory'); reset($options); return $options; } }<file_sep>/templates/cyklo/html/com_jbcatalog/categories/default_items.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; require_once JPATH_COMPONENT.'/helpers/images.php'; ?> <div class="catmain_div"> <?php for($i=0;$i<count($this->items);$i++){ echo "<div class='catimg_div'>"; if(isset($this->items[$i]->images) && is_file(JPATH_ROOT.'/'.$this->items[$i]->images)){ echo "<a href='".JRoute::_("index.php?option=com_jbcatalog&view=category&id=".$this->items[$i]->id)."'><img src='".JURI::base().($this->items[$i]->images)."'></a>"; } echo "</div>"; echo "<div class='catinfo_div'><a href='".JRoute::_("index.php?option=com_jbcatalog&view=category&id=".$this->items[$i]->id)."'>".$this->items[$i]->title."</a>"; echo "<div class='catdescr_div'>".$this->items[$i]->descr."</div></div>"; echo "<div style='clear:both;margin-bottom:3px;'></div>"; } ?> </div> <div style="padding-top:15px; text-align: center;"> <form method="post"> Zobrazit <?php echo $this->pagination->getLimitBox(); ?> kategorií na stránce </form> </div> <p class="counter"> <?php echo $this->pagination->getPagesCounter(); ?> </p> <div class="pagination"> <?php echo $this->pagination->getPagesLinks(); ?> </div><file_sep>/components/com_jbcatalog/models/category.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogModelCategory extends JModelList { /** * Model context string. * * @var string */ public $_context = 'com_jbcatalog.category'; /** * The category context (allows other extensions to derived from this model). * * @var string */ protected $_extension = 'com_jbcatalog'; private $_items = null; private $adf_filter = null; private $filtr_query = null; /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState($ordering = null, $direction = null) { $app = JFactory::getApplication(); $this->setState('filter.extension', $this->_extension); $pk = $app->input->getInt('id'); $this->setState('category.id', $pk); $params = $app->getParams(); $this->setState('params', $params); $this->adf_filter = $app->input->get('adf_filter', $app->getUserState('adf_filter_'.$pk, null), 'array'); $app->setUserState('adf_filter_'.$pk, $this->adf_filter); //clear filter if(isset($_POST['clear_filter'])){ $app->setUserState('adf_filter_'.$pk, null); $this->adf_filter = array(); } if(isset($_GET['bcatfilters'])){ $bcatfilters = $_GET['bcatfilters']; if(count($bcatfilters)){ if($bcatfilters[count($bcatfilters) - 1]){ $this->setState('category.id', $bcatfilters[count($bcatfilters) - 1]); }elseif(isset($bcatfilters[count($bcatfilters) - 2]) && $bcatfilters[count($bcatfilters) - 2]){ $this->setState('category.id', $bcatfilters[count($bcatfilters) - 2]); } } } //$this->adf_filter = $this->getState('adf_filter'); $params = $app->getParams(); $this->setState('params', $params); //$s = $this->getState('list.limit'); $ll = $app->getUserState('list_limit'.$pk, $app->getCfg('list_limit', 0)); $value = $app->input->get('limit', $ll, 'uint'); $this->setState('list.limit', $value); $app->setUserState('list_limit'.$pk, $value); $value = $app->input->get('limitstart', 0, 'uint'); $this->setState('list.start', $value); $this->setState('filter.published', 1); $this->setState('filter.access', true); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * * @return string A store id. */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':'.$this->getState('filter.extension'); $id .= ':'.$this->getState('filter.published'); $id .= ':'.$this->getState('filter.access'); $id .= ':'.$this->getState('filter.parentId'); return parent::getStoreId($id); } /** * redefine the function an add some properties to make the styling more easy * * @return mixed An array of data items on success, false on failure. */ public function getItems() { if (!count($this->_items)) { $app = JFactory::getApplication(); $menu = $app->getMenu(); $active = $menu->getActive(); $params = new JRegistry; if ($active) { $params->loadString($active->params); } $id = (int) $this->getState('category.id'); $this->_items = $this->_getAItems($id); $this->_getItemsImg(); $this->getResystItemsInfo(); $this->getResystItemsPrice(); $this->getResystItemsOriginalPrice(); $this->getResystItemsBikeCategory(); } return $this->_items; } public function getItem(){ $catid = $this->getState('category.id'); $db = $this->getDbo(); $query = "SELECT * " ." FROM #__jbcatalog_category" ." WHERE id = ".intval($catid) ." AND published = 1"; $db->setQuery($query); return $db->loadObject(); } public function getCategories(){ $catid = $this->getState('category.id'); $db = $this->getDbo(); $query = "SELECT * " ." FROM #__jbcatalog_category" ." WHERE parent_id = ".intval($catid) ." AND published = 1" ." ORDER BY lft ASC"; $db->setQuery($query); $categories = $db->loadObjectList(); for($i=0; $i<count($categories); $i++){ $categories[$i]->images = null; if($categories[$i]->image && is_file(JPATH_ROOT.DIRECTORY_SEPARATOR.$categories[$i]->image)){ $categories[$i]->images = $categories[$i]->image; $info = pathinfo($categories[$i]->image); $path_to_thumbs_directory = 'components'.DIRECTORY_SEPARATOR.'com_jbcatalog'.DIRECTORY_SEPARATOR.'libraries'.DIRECTORY_SEPARATOR.'jsupload'.DIRECTORY_SEPARATOR.'server'.DIRECTORY_SEPARATOR.'php'.DIRECTORY_SEPARATOR.'files'.DIRECTORY_SEPARATOR.'thumbnail'; if(is_file(JPATH_ROOT.DIRECTORY_SEPARATOR.$path_to_thumbs_directory.DIRECTORY_SEPARATOR.$categories[$i]->id.'_thumb.'.$info['extension'])){ $categories[$i]->images = $path_to_thumbs_directory.DIRECTORY_SEPARATOR.$categories[$i]->id.'_thumb.'.$info['extension']; } // $file_name_thumb = $id.'_thumb.'.$info['extension']; } } return $categories; } protected function getListQuery() { if($this->filtr_query){ return $this->filtr_query; } $db = $this->getDbo(); $filter_sql = ''; $filter_tbl = ''; $sql = array(); $tbl_pref = 1; //var_dump($this->adf_filter);//die(); if(count($this->adf_filter)){ foreach ($this->adf_filter as $key=>$value){ $query = "SELECT published FROM #__jbcatalog_adf WHERE id=".intval($key); $db->setQuery($query); $published = $db->loadResult(); if($value && $published){ $query = "SELECT field_type FROM #__jbcatalog_adf WHERE id=".intval($key); $db->setQuery($query); $adftype = $db->loadResult(); //plugin get adf value require_once JPATH_COMPONENT_ADMINISTRATOR.DIRECTORY_SEPARATOR."plugins".DIRECTORY_SEPARATOR."plugins.php"; $pl = new ParsePlugins('adf', $adftype); $sql[] = $pl->getData('getAdfFilterSQL', array("adfid" => $key, "value" => $value)); } /* if(!is_array($value)){ if($value){ if(!$filter_sql){ $filter_sql .= " AND (( IF((e.field_type = 0 OR e.field_type = 2 OR e.field_type = 5),IF(e.field_type = 2, v.adf_text LIKE '%{$value}%', v.adf_value LIKE '%{$value}%'),v.adf_value='{$value}') AND v.adf_id = {$key})"; }else{ $filter_tbl .= " LEFT JOIN #__jbcatalog_adf_values as v{$tbl_pref} ON a.id=v{$tbl_pref}.item_id" ." JOIN #__jbcatalog_adf as e{$tbl_pref} ON e{$tbl_pref}.id=v{$tbl_pref}.adf_id"; $filter_sql .= " AND (IF((e{$tbl_pref}.field_type = 0 OR e{$tbl_pref}.field_type = 2 OR e{$tbl_pref}.field_type = 5),IF(e{$tbl_pref}.field_type = 2,v{$tbl_pref}.adf_text LIKE '%{$value}%',v{$tbl_pref}.adf_value LIKE '%{$value}%'),v{$tbl_pref}.adf_value='{$value}') AND v{$tbl_pref}.adf_id = {$key})"; $tbl_pref++; } } }else{ $query = "SELECT field_type FROM #__jbcatalog_adf WHERE id=".intval($key); $db->setQuery($query); $adftype = $db->loadResult(); //complex fields if($adftype == 8 && count($value)){ $value_par = $value[count($value) - 1]; for($j=0;$j<count($value);$j++){ if($value[count($value) - 1 - $j]){ $value_par = $value[count($value) - 1 - $j]; break; } } if($value_par){ $complex_items = array($value_par); $wh = true; while($wh){ $db->setQuery( "SELECT id FROM #__jbcatalog_complex_item as i" ." WHERE parent_id IN ({$value_par})" ); $ids = $db->loadColumn(); if(!count($ids)){ $wh = false; }else{ $value_par = implode(',', $ids); $complex_items = array_merge($complex_items, $ids); } } if(count($complex_items)){ if(!$filter_sql){ $filter_sql .= ' AND ('; }else{ $filter_sql .= ' AND '; } $filter_tbl .= " LEFT JOIN #__jbcatalog_adf_values as v{$tbl_pref} ON a.id=v{$tbl_pref}.item_id" ." JOIN #__jbcatalog_adf as e{$tbl_pref} ON e{$tbl_pref}.id=v{$tbl_pref}.adf_id"; $filter_sql .= " ( v{$tbl_pref}.adf_value IN (".implode(',',$complex_items).") AND v{$tbl_pref}.adf_id = {$key})"; $tbl_pref++; } //var_dump($complex_items); } }elseif($adftype == 6 && count($value)){ if($value[0] || $value[1]){ if(!$filter_sql){ $filter_sql .= ' AND ('; }else{ $filter_sql .= ' AND '; } $filter_tbl .= " LEFT JOIN #__jbcatalog_adf_values as v{$tbl_pref} ON a.id=v{$tbl_pref}.item_id" ." JOIN #__jbcatalog_adf as e{$tbl_pref} ON e{$tbl_pref}.id=v{$tbl_pref}.adf_id"; $filter_sql .= " ( ".($value[0]?"v{$tbl_pref}.adf_value >= '".$value[0]." 00:00:00' AND":'')." ".($value[1]?" v{$tbl_pref}.adf_value <= '".$value[1]." 00:00:00' AND":'')." v{$tbl_pref}.adf_id = {$key})"; $tbl_pref++; } }elseif($adftype == 7 && count($value)){ //$db->setQuery("SELECT AVG(value) FROM #__jbcatalog_adf_rating WHERE rating_id = {$key} AND i"); //die(); if(!$filter_sql){ $filter_sql .= ' AND ('; }else{ $filter_sql .= ' AND '; } if($value[0] == 0){ $sq = ' (SELECT AVG(value) FROM #__jbcatalog_adf_rating WHERE rating_id = '.$key.' AND item_id = a.id) is NULL OR '; }else{ $sq = "{$value[0]} <= (SELECT AVG(value) FROM #__jbcatalog_adf_rating WHERE rating_id = {$key} AND item_id = a.id) AND "; } $filter_sql .= " ( {$sq} {$value[1]} >= (SELECT AVG(value) FROM #__jbcatalog_adf_rating WHERE rating_id = {$key} AND item_id = a.id))"; //$tbl_pref++; } } */ } /*if($filter_sql){ $filter_sql .= ")"; }*/ if(count($sql)){ foreach($sql as $sq){ if(isset($sq['tbl']) && $sq['tbl']){ $filter_tbl .= $sq['tbl']; } if(isset($sq['sql']) && $sq['sql']){ $filter_sql .= $sq['sql']; } } } } $query = "SELECT a.*" ." FROM #__jbcatalog_items as a" ." JOIN #__jbcatalog_items_cat as b" ." ON a.id = b.item_id" .($this->getState('category.id')?" AND b.cat_id = ".(int) $this->getState('category.id'):"") ." LEFT JOIN #__jbcatalog_adf_values as v ON a.id=v.item_id" ." LEFT JOIN #__jbcatalog_adf as e ON e.id=v.adf_id" .$filter_tbl ." WHERE a.published = '1' " .$filter_sql ." GROUP BY a.id" ." ORDER BY a.ordering"; $this->filtr_query = $query;//die(); return $query; } private function _getAItems($id){ $db = $this->getDbo(); $query = $this->getListQuery(); $db->setQuery($query, $this->getState('list.start'), $this->getState('list.limit')); $items = $db->loadObjectList(); $query = 'SELECT e.* FROM #__jbcatalog_category_adfs as c' .' JOIN #__jbcatalog_adf as e ON e.id=c.adfs_id' .' WHERE c.cat_id = '.$id.' AND c.listview = "1" AND e.published="1"'; $db->setQuery($query); $fields = $db->loadObjectList(); if(count($fields)){ if (!empty($items)) { $items[0]->fieldsname = $fields; for($i = 0; $i < count($items); $i++){ foreach($fields as $fieldid){ $items[$i]->fields[] = $this->_getAdfValue($fieldid, $items[$i]->id); } } } } return $items; } private function _getItemsImg(){ $db = $this->getDbo(); for($i=0; $i<count($this->_items); $i++){ $query = "SELECT name FROM #__jbcatalog_files" ." WHERE catid = 2 AND itemid = ".intval($this->_items[$i]->id)." AND ftype = 1" ." ORDER BY ordering"; $db->setQuery($query); $this->_items[$i]->images = $db->loadColumn(); } } public function getFilters(){ $id = (int) $this->getState('category.id'); $db = $this->getDbo(); $query = "(SELECT d.*" ." FROM #__jbcatalog_items_cat as a" ." JOIN #__jbcatalog_category as b" ." ON a.cat_id = b.id" ." JOIN #__jbcatalog_category_adfs_group as c" ." ON c.cat_id = b.id" ." JOIN #__jbcatalog_adfgroup as g" ." ON g.id = c.group_id AND g.published = '1'" ." JOIN #__jbcatalog_adf_ingroups as i" ." ON i.groupid = g.id" ." JOIN #__jbcatalog_adf as d" ." ON i.adfid = d.id" ." LEFT JOIN #__jbcatalog_category_adfs as j" ." ON j.adfs_id = d.id AND b.id = j.cat_id AND j.group_id != '0'" ." WHERE b.id = ".$id ." AND d.published = '1'" ." AND ((d.filters = '1' AND j.filtered != '1') OR (j.filtered = '2'))" ." GROUP BY d.id" ." ORDER BY g.id, d.ordering, d.id)" ." UNION " ." (SELECT d1.*" ." FROM #__jbcatalog_category_adfs as ad" ." JOIN #__jbcatalog_adf as d1" ." ON d1.id = ad.adfs_id AND ad.group_id = 0 AND ad.cat_id = ".$id ." WHERE d1.published = '1'" ." AND ((d1.filters = '1' AND ad.filtered != '1') OR (ad.filtered = '2'))" ." )" ; $db->setQuery($query); $adfs = $db->loadObjectList(); $html = array(); for($j=0; $j<count($adfs); $j++){ $adf_show = array($adfs[$j]->name, $adfs[$j]->adf_tooltip, $this->getAdfByType($adfs[$j]), $adfs[$j]->field_type); $html[] = $adf_show; //$html[$adfs[$j]->name]= $this->getAdfByType($adfs[$j]); } return $html; } public function getAdfByType($adf){ $db = $this->getDbo(); $value = isset($this->adf_filter[$adf->id])?$this->adf_filter[$adf->id]:null; //plugin for adf require_once JPATH_COMPONENT_ADMINISTRATOR.DIRECTORY_SEPARATOR."plugins".DIRECTORY_SEPARATOR."plugins.php"; $pl = new ParsePlugins('adf', $adf->field_type); $html = $pl->getData('getAdfFilter', array("adf" => $adf, "value" => $value)); /* $html = ''; switch ($adf->field_type){ //text case '0': $html = '<input class="inpfilter" type="text" name="adf_filter['.$adf->id.']" value="'.htmlspecialchars($value).'" />'; break; //radio case '1': $html = '<input type="checkbox" name="adf_filter['.$adf->id.']" value="1" '.($value?"checked":"").' />'; break; //editor case '2': $html = '<input class="inpfilter" type="text" name="adf_filter['.$adf->id.']" value="'.htmlspecialchars($value).'" />'; break; //select & multi select case '3': case '4': //if no options if(!count($selarr)){ return ''; }else{ $null_arr[] = JHTML::_('select.option', "", JText::_('COM_JBCATALOG_SELOPTION'), 'id', 'name' ); $selarr = array_merge($null_arr,$selarr); } $html = JHTML::_('select.genericlist', $selarr, 'adf_filter['.$adf->id.']', 'class="inputboxsel" size="1"', 'id', 'name', $value ); break; //link case '5': $html = '<input class="inpfilter" type="text" name="adf_filter['.$adf->id.']" value="'.htmlspecialchars($value).'" />'; break; //date case '6': $html = JHtml::_('calendar', isset($value[0])?$value[0]:'', 'adf_filter['.$adf->id.'][]', 'extraf_'.$adf->id, "%Y-%m-%d", ' class="inpfilter" readonly = "readonly"'); $html .= '<div>&nbsp;'.JText::_('COM_JBCATALOG_TO').':&nbsp;</div>'; $html .= JHtml::_('calendar', isset($value[1])?$value[1]:'', 'adf_filter['.$adf->id.'][]', 'extraf_'.$adf->id.'_1', "%Y-%m-%d", ' class="inpfilter" readonly = "readonly'); break; //rating case '7': $selarr = array(); $selarr[] = JHTML::_('select.option', 0, 0, 'id', 'name' ); $selarr[] = JHTML::_('select.option', 1, 1, 'id', 'name' ); $selarr[] = JHTML::_('select.option', 2, 2, 'id', 'name' ); $selarr[] = JHTML::_('select.option', 3, 3, 'id', 'name' ); $selarr[] = JHTML::_('select.option', 4, 4, 'id', 'name' ); $selarr[] = JHTML::_('select.option', 5, 5, 'id', 'name' ); $html = JHTML::_('select.genericlist', $selarr, 'adf_filter['.$adf->id.'][]', 'class="inputboxsel" size="1"', 'id', 'name', isset($value[0])?$value[0]:0, 'adf_filter_'.$adf->id.'_0' ); $html .= JHTML::_('select.genericlist', $selarr, 'adf_filter['.$adf->id.'][]', 'class="inputboxsel" size="1"', 'id', 'name', isset($value[1])?$value[1]:5, 'adf_filter_'.$adf->id.'_1' ); break; case '8': if($adf->adf_complex){ $db->setQuery( "SELECT b.title FROM #__jbcatalog_adf_values as a" ." JOIN #__jbcatalog_complex_item as b" ." ON b.id = a.adf_value" ." WHERE b.published != -2 AND a.adf_id = ".$adf->adf_complex ); $value1 = $db->loadResult(); if($value1){ $query = $db->getQuery(true) ->select('a.id , a.title as name') ->from('#__jbcatalog_complex_item AS a') ->where('a.catid = '.intval($adf->adf_complex)) ->order('a.ordering'); $db->setQuery($query); $options_all[] = JHTML::_('select.option', "", JText::_('COM_JBCATALOG_SELOPTION'), 'id', 'name' ); try { $options = $db->loadObjectList(); if($options){ $options_all = array_merge($options_all, $options); } } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); } if(count($value) > 1 && $value[1] != 0){ $html .= $this->getComplexTree($value, $adf->id); }else{ $html .= JHTML::_('select.genericlist', $options_all, 'adf_filter['.$adf->id.'][]', 'class="inputboxsel" size="1" onchange="js_BCAT_cmp_filter('.$adf->id.',1,this.value)"', 'id', 'name', $value[0] ); $html .= '<div id="bzdiv_cmp_'.$adf->id.'"></div>'; } } } break; } */ return $html; } public function getCatID(){ return (int) $this->getState('category.id'); } public function getFilterVar(){ return $this->adf_filter; } public function getPlugins($pk = null){ require_once JPATH_COMPONENT_ADMINISTRATOR.DIRECTORY_SEPARATOR."plugins".DIRECTORY_SEPARATOR."plugins.php"; $pl = new ParsePlugins('adf'); $plugin['js'] = $pl->getData('getCategoryFEViewJS'); return $plugin; } private function _getAdfValue($adf, $id){ $db = $this->getDbo(); $db->setQuery( "SELECT adf_value FROM #__jbcatalog_adf_values" ." WHERE adf_id = ".$adf->id ." AND item_id = ".intval($id) ); $value = $db->loadResult(); //plugin get adf value require_once JPATH_COMPONENT_ADMINISTRATOR.DIRECTORY_SEPARATOR."plugins".DIRECTORY_SEPARATOR."plugins.php"; $pl = new ParsePlugins('adf', $adf->field_type); $value = $pl->getData('getItemFEAdfValue', array("adf" => $adf, "value" => $value, 'itemid' => $id)); if($value == array()){ $value = ''; } if($value != ''){ $postf = str_replace('{sup}', '<sup>', $adf->adf_postfix); $postf = str_replace('{/sup}', '</sup>', $postf); $value = $adf->adf_prefix.$value.$postf; } return $value; } public function getCustomPlugins(){ $id = (int) $this->getState('category.id'); require_once JPATH_COMPONENT_ADMINISTRATOR.DIRECTORY_SEPARATOR."plugins".DIRECTORY_SEPARATOR."plugins.php"; $arr = array(); foreach($this->_items as $items){ $arr[] = $items->id; } $pl = new ParsePlugins('custom'); $value = $pl->getData('getCompareFields', array("c_id" => $id, "items" => $arr)); return $value; } /** * 2015-08-02 ReSyst.cz * Prida k polozkam detaily */ private function getResystItemsInfo() { $db = $this->getDbo(); for($i=0; $i<count($this->_items); $i++){ // adf_id = 9 -> cena, adf_id = 10 -> kategorie kola $query = " SELECT a.name AS extra, v.adf_value AS hodnota, v.adf_id AS hodnota_id FROM #__jbcatalog_adf_values AS v INNER JOIN #__jbcatalog_adf AS a ON (v.adf_id = a.id) WHERE v.item_id = " . intval($this->_items[$i]->id) . " AND v.adf_id NOT IN (9, 10, 11) ORDER BY v.adf_id "; $db->setQuery($query); $this->_items[$i]->resyst_info = $db->loadAssocList(); } } /** * 2015-08-02 ReSyst.cz * Prida k polozkam cenu */ private function getResystItemsPrice() { $db = $this->getDbo(); for($i=0; $i<count($this->_items); $i++){ $query = " SELECT v.adf_value AS cena FROM #__jbcatalog_adf_values AS v INNER JOIN #__jbcatalog_adf AS a ON (v.adf_id = a.id) WHERE v.item_id = " . intval($this->_items[$i]->id) . " AND v.adf_id = 9 "; $db->setQuery($query); $this->_items[$i]->resyst_cena = $db->loadResult(); } } /** * 2016-03-05 ReSyst.cz * Prida k polozkam puvodni cenu */ private function getResystItemsOriginalPrice() { $db = $this->getDbo(); for($i=0; $i<count($this->_items); $i++){ $query = " SELECT v.adf_value AS puvodni_cena FROM #__jbcatalog_adf_values AS v INNER JOIN #__jbcatalog_adf AS a ON (v.adf_id = a.id) WHERE v.item_id = " . intval($this->_items[$i]->id) . " AND v.adf_id = 11 "; $db->setQuery($query); $this->_items[$i]->resyst_puvodni_cena = $db->loadResult(); } } /** * 2015-08-17 ReSyst.cz * Prida k polozkam kategorii kola */ private function getResystItemsBikeCategory() { $db = $this->getDbo(); for($i=0; $i<count($this->_items); $i++){ $query = " SELECT s.id, s.name AS kategorie FROM #__jbcatalog_adf_select AS s INNER JOIN #__jbcatalog_adf_values AS v ON (s.id = v.adf_value) INNER JOIN #__jbcatalog_adf AS a ON (v.adf_id = a.id) WHERE v.item_id = " . intval($this->_items[$i]->id) . " AND v.adf_id = 10 "; $db->setQuery($query); $this->_items[$i]->resyst_kategorie = $db->loadAssoc(); } } } <file_sep>/components/com_jbcatalog/helpers/images.php <?php /*------------------------------------------------------------------------ # JBCatalog # ------------------------------------------------------------------------ # BearDev development company # Copyright (C) 2014 JBCatalog.com. All Rights Reserved. # @license - http://jbcatalog.com/catalog-license/site-articles/license.html GNU/GPL # Websites: http://www.jbcatalog.com # Technical Support: Forum - http://jbcatalog.com/forum/ -------------------------------------------------------------------------*/ defined('_JEXEC') or die; class JBCatalogImages { // const path = 'components/com_jbcatalog/libraries/jsupload/server/php/files'; const path = 'images/files'; public static function getClickableImg($img) { return "<a class='fancybox-thumbs' data-fancybox-group='thumb' href='" . JURI::base() . "/" . self::path . "/" . $img . "'><img src='" . JURI::base() . "/" . self::path . "/thumbnail/" . $img . "'></a>"; } public static function getImg($img, $thumb = false) { return JURI::base() . (self::path . "/" . ($thumb ? "thumbnail/" : "") . $img); } public static function includeFancy($doc) { JHtml::_('bootstrap.framework'); $doc->addScript('components/com_jbcatalog/libraries/fancybox/source/jquery.fancybox.js?v=2.1.5'); $doc->addStyleSheet('components/com_jbcatalog/libraries/fancybox/source/jquery.fancybox.css?v=2.1.5'); $doc->addScript('components/com_jbcatalog/libraries/fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7'); $doc->addStyleSheet('components/com_jbcatalog/libraries/fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7'); $doc->addScript('components/com_jbcatalog/libraries/rating/js/jquery.rating.js'); $doc->addStyleSheet('components/com_jbcatalog/libraries/rating/styles/jquery.rating.css'); ?> <script type="text/javascript"> jQuery(document).ready(function () { /* * Simple image gallery. Uses default settings */ jQuery('.fancybox').fancybox(); /* * Thumbnail helper. Disable animations, hide close button, arrows and slide to next gallery item if clicked */ jQuery('.fancybox-thumbs').fancybox({ prevEffect: 'none', nextEffect: 'none', closeBtn: true, arrows: false, nextClick: true, helpers: { thumbs: { width: 50, height: 50 } } }); }); </script> <?php } public static function isImg($img, $thumb = false) { } }
11a71a5221d8d319fdec8887586f4bae2c8e621f
[ "JavaScript", "PHP", "INI" ]
72
PHP
resyst-cz/cyklo-janicek
ef57c721d023c8a27747c82c60675d1910696e57
7ada0cf4ab4056a6d966e01923d4036f2d7303d5
refs/heads/master
<repo_name>zephir/typo3-seo-data<file_sep>/Configuration/TCA/Overrides/pages.php <?php defined('TYPO3_MODE') || die(); $tmp_meta_data_columns = [ 'meta_title' => [ 'exclude' => true, 'label' => 'LLL:EXT:meta_data/Resources/Private/Language/locallang_db.xlf:tx_metadata_domain_model_page.meta_title', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim' ], ], 'meta_description' => [ 'exclude' => true, 'label' => 'LLL:EXT:meta_data/Resources/Private/Language/locallang_db.xlf:tx_metadata_domain_model_page.meta_description', 'config' => [ 'type' => 'text', 'cols' => 40, 'rows' => 3, 'eval' => 'trim' ] ], 'meta_image' => [ 'exclude' => true, 'label' => 'LLL:EXT:meta_data/Resources/Private/Language/locallang_db.xlf:tx_metadata_domain_model_page.meta_image', 'config' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getFileFieldTCAConfig( 'meta_image', [ 'appearance' => [ 'createNewRelationLinkTitle' => 'LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:images.addFileReference' ], 'foreign_types' => [ '0' => [ 'showitem' => ' --palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette, --palette--;;filePalette' ], \TYPO3\CMS\Core\Resource\File::FILETYPE_TEXT => [ 'showitem' => ' --palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette, --palette--;;filePalette' ], \TYPO3\CMS\Core\Resource\File::FILETYPE_IMAGE => [ 'showitem' => ' --palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette, --palette--;;filePalette' ], \TYPO3\CMS\Core\Resource\File::FILETYPE_AUDIO => [ 'showitem' => ' --palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette, --palette--;;filePalette' ], \TYPO3\CMS\Core\Resource\File::FILETYPE_VIDEO => [ 'showitem' => ' --palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette, --palette--;;filePalette' ], \TYPO3\CMS\Core\Resource\File::FILETYPE_APPLICATION => [ 'showitem' => ' --palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette, --palette--;;filePalette' ] ], 'maxitems' => 1 ], $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] ), ], 'canonical_url' => [ 'exclude' => true, 'label' => 'LLL:EXT:meta_data/Resources/Private/Language/locallang_db.xlf:tx_metadata_domain_model_page.canonical_url', 'config' => [ 'type' => 'input', 'renderType' => 'inputLink', 'size' => 31, 'eval' => 'trim', 'softref' => 'typolink' ], ], ]; \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns('pages',$tmp_meta_data_columns); \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToAllTCAtypes( 'pages', 'canonical_url', '', 'after:title' ); $GLOBALS['TCA']['pages']['palettes']['seo_metadata'] = [ 'showitem' => 'meta_title,meta_description,--linebreak--,meta_image' ]; \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToAllTCAtypes( 'pages', '--palette--;LLL:EXT:meta_data/Resources/Private/Language/locallang_db.xlf:pages.palettes.seo_metadata;seo_metadata', '', 'after:description' );<file_sep>/Configuration/TCA/Overrides/pages_language_overlay.php <?php defined('TYPO3_MODE') || die(); $tmp_meta_data_columns = [ 'meta_title' => [ 'exclude' => true, 'label' => 'LLL:EXT:meta_data/Resources/Private/Language/locallang_db.xlf:tx_metadata_domain_model_page.meta_title', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim' ], ], 'meta_description' => [ 'exclude' => true, 'label' => 'LLL:EXT:meta_data/Resources/Private/Language/locallang_db.xlf:tx_metadata_domain_model_page.meta_description', 'config' => [ 'type' => 'text', 'cols' => 40, 'rows' => 15, 'eval' => 'trim' ] ], ]; \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns('pages_language_overlay',$tmp_meta_data_columns); $GLOBALS['TCA']['pages_language_overlay']['palettes']['seo_metadata'] = [ 'showitem' => 'meta_title,meta_description' ]; \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToAllTCAtypes( 'pages_language_overlay', '--palette--;LLL:EXT:meta_data/Resources/Private/Language/locallang_db.xlf:pages.palettes.seo_metadata;seo_metadata', '', 'after:description' );<file_sep>/ext_tables.sql # # Table structure for table 'pages' # CREATE TABLE pages ( meta_title varchar(255) DEFAULT '' NOT NULL, meta_description text, meta_image int(11) unsigned NOT NULL default '0', canonical_url varchar(255) DEFAULT '' NOT NULL ); # # Table structure for table 'pages' # CREATE TABLE pages_language_overlay ( meta_title varchar(255) DEFAULT '' NOT NULL, meta_description text );
738f09b59bfadf0c1cd7f0099c353bcd127ceb49
[ "SQL", "PHP" ]
3
PHP
zephir/typo3-seo-data
9d2c187a51611c5f90a21aea05e96e5605947480
1612b5aef12aae816f658d1ce24fb3e3d1524e74
refs/heads/master
<repo_name>azad71/Data-Structure-and-Algorithms<file_sep>/Data Structure/Sorting/counting_sort.cpp // implementation of counting sort with c++ map STL #include<bits/stdc++.h> using namespace std; vector<int> counting_sort(vector<int> ara) { map<int, int> elem_frequency; // mapping frequency of each element for(int i = 0; i < ara.size(); i++) { int temp = ara[i]; elem_frequency[temp]++; } int c = 0; for(auto it: elem_frequency) { for(int i = 0; i < it.second; i++) ara[c++] = it.first; } return ara; } int main() { vector<int>ara; int n; cout<<"\nHow many elements: "; cin>>n; int item; cout<<"\nEnter elements: "; while(n--) { cin>>item; ara.push_back(item); } vector<int> sortedArray; sortedArray = counting_sort(ara); cout<<"\nSorted array is: "; for(int i = 0; i < sortedArray.size(); i++) cout<<sortedArray[i]<<" "; return 0; } <file_sep>/Data Structure/Sorting/merge_sort.cpp // implementation of merge sort using recursion #include<bits/stdc++.h> using namespace std; void Merge(int *a, int low, int high, int mid) { // cout<<endl<<"With love from Merge()"<<endl; int i = low, j = mid + 1, k = 0; // auxiliary array int temp[high - low + 1]; while(i <= mid && j <= high) { if(a[i] < a[j]) { temp[k] = a[i]; i++; } else { temp[k] = a[j]; j++; } k++; } while(i <= mid) { temp[k] = a[i]; i++; k++; } while(j <= high) { temp[k] = a[j]; j++; k++; } for(int c = low; c <= high; c++) a[c] = temp[c-low]; /* cout<<endl<<"Array after merged: "; for(int i = 0; i <= high; i++) cout<<a[i]<<" "; cout<<endl; */ } void merge_sort(int *a, int low, int high) { // cout<<endl<<"With love from merge_sort()"<<endl; int mid; if(low < high) { // cout<<endl<<"Low: "<<low<<" "<<"High: "<<high<<endl; mid = (low + high) / 2; merge_sort(a, low, mid); merge_sort(a, mid+1, high); Merge(a, low, high, mid); } } int main() { int n; cout<<"Enter input size : "; cin>>n; int a[n]; cout<<"\nEnter elements into the array : "; for(int i = 0; i < n; i++) cin>>a[i]; merge_sort(a, 0, n-1); cout<<"\nSorted array : "; for(int i = 0; i < n; i++) cout<<a[i]<<" "; return 0; } <file_sep>/Data Structure/Tree/AVL_tree.cpp /* implementation of AVL tree An special implementation of binary search tree that balance itself automatically in every insertion and deletion */ #include<bits/stdc++.h> using namespace std; struct Node { Node* left; int data; int height; Node* right; }; Node* root = NULL; // returns the depth of a node int get_height(Node* p) { if(p == NULL) return 0; int x = get_height(p->left); int y = get_height(p->right); return x > y ? x+1: y+1; } int balance_factor(Node* p) { return get_height(p->left) - get_height(p->right); } Node* LL_rotation(Node* p) { Node* pl = new Node(); Node* plr = new Node(); pl = p->left; plr = pl->right; pl->right = p; p->left = plr; p->height = get_height(p); pl->height= get_height(pl); if(root == p) root = pl; return pl; } Node* LR_rotation(Node* p) { Node* pl = new Node(); Node* plr = new Node(); pl = p->left; plr = pl->right; pl->right = plr->left; p->left = plr->right; plr->right = p; plr->left = pl; pl->height = get_height(pl); p->height = get_height(p); plr->height = get_height(plr); if(root == p) root = plr; return plr; } Node* RR_rotation(Node* p) { Node* pr = new Node(); Node* prl = new Node(); pr = p->right; prl = pr->left; p->right = prl; pr->left = p; p->height = get_height(p); pr->height = get_height(pr); if (root == p) root = pr; return pr; } Node* RL_rotation(Node* p) { Node* pr = new Node(); Node* prl = new Node(); pr = p->right; prl = pr->left; p->right = prl->left; pr->left = prl->right; prl->left = p; prl->right = pr; p->height = get_height(p); pr->height = get_height(pr); prl->height = get_height(prl); if(root == p) root = prl; return prl; } // inserting node, this time we are doing it with recursion Node* insert_node(Node* p, int key) { // base case if(p == NULL) { Node* new_node = new Node(); new_node->data = key; new_node->height = 1; new_node->left = NULL; new_node->right = NULL; cout<<endl<<key<<" is inserted in tree"<<endl; return new_node; } // here's the sauce for recursion if(key < p->data) { p->left = insert_node(p->left, key); } else if(key > p->data) { p->right = insert_node(p->right, key); } p->height = get_height(p); // adjusting balance if(balance_factor(p) == 2 && balance_factor(p->left) == 1) // heavy on the left then left side return LL_rotation(p); else if(balance_factor(p) == 2 && balance_factor(p->left) == -1) // heavy on the left then right return LR_rotation(p); else if(balance_factor(p) == -2 && balance_factor(p->right) == -1) // heavy on the right then right return RR_rotation(p); else if(balance_factor(p) == -2 && balance_factor(p->right) == 1) // heavy on the right then left return RL_rotation(p); return p; } void find_item(int item) { Node* temp = new Node(); temp = root; while(temp != NULL) { if (temp->data == item) { cout<<endl<<item<<" is found in the tree"<<endl; return; } else if(item < temp->data) { temp = temp->left; } else { temp = temp->right; } } cout<<endl<<item<<" is not found in the tree"<<endl; } // returns rightmost leaf node of left side Node* predecessor(Node* p) { while(p != NULL && p->right != NULL) p = p->right; return p; } // returns the leftmost leaf node of right side Node* successor(Node* p) { while(p != NULL && p->left != NULL) p = p->left; return p; } // same as binary search tree deletion // successor or predecessor takes the place of deleted node // then adjust the balance Node* delete_node(Node* p, int item) { Node* q; if(p == NULL) { cout<<endl<<item<<" doesn't exist in the tree"<<endl; return NULL; } if(p->left == NULL && p->right == NULL) { if(p == root) root = NULL; delete p; cout<<endl<<"A node is deleted from the tree"<<endl; return NULL; } if(item < p->data) { p->left = delete_node(p->left, item); } else if(item > p->data) { p->right = delete_node(p->right, item); } else { if(get_height(p->left) > get_height(p->right)) { q = predecessor(p->left); p->data = q->data; p->left = delete_node(p->left, q->data); } else { q = successor(p->right); p->data = q->data; p->right = delete_node(p->right, q->data); } } p->height = get_height(p); // adjusting balance if(balance_factor(p) == 2 && balance_factor(p->left) == 1) // heavy on the left then left side return LL_rotation(p); else if(balance_factor(p) == 2 && balance_factor(p->left) == -1) // heavy on the left then right return LR_rotation(p); else if(balance_factor(p) == -2 && balance_factor(p->right) == -1) // heavy on the right then right return RR_rotation(p); else if(balance_factor(p) == -2 && balance_factor(p->right) == 1) // heavy on the right then left return RL_rotation(p); return p; } void preorder_traversal(Node* root) { if(root != NULL) { cout<<root->data<<" "; preorder_traversal(root->left); preorder_traversal(root->right); } } void inorder_traversal(Node* root) { if(root != NULL) { inorder_traversal(root->left); cout<<root->data<<" "; inorder_traversal(root->right); } } void postorder_traversal(Node* root) { if(root != NULL) { postorder_traversal(root->left); postorder_traversal(root->right); cout<<root->data<<" "; } } int main() { int choice; int temp; cout<<endl<<"Enter a root node first: "; cin>>temp; root = insert_node(root, temp); cout<<endl<<"Enter below numeric value for listed operation\n\n"; while(1) { cout<<"\n1.Insert a node" <<"\n2.Delete a node" <<"\n3.Find a item" <<"\n4.Inorder traversal" <<"\n5.Postorder traversal" <<"\n6.Preorder traversal" <<"\n7.Exit" <<endl; cout<<"Enter your choice: "; cin>>choice; switch(choice) { case 1: { int item; cout<<"\nEnter item to be inserted: "; cin>>item; insert_node(root, item); break; } case 2: { int item; cout<<"\nEnter item to be delete: "; cin>>item; delete_node(root, item); break; } case 3: { int item; cout<<endl<<"Enter a item to search: "; cin>>item; find_item(item); break; } case 4: { cout<<endl<<"Inorder traversal is: "; inorder_traversal(root); cout<<endl; break; } case 5: { cout<<endl<<"Postorder traversal is: "; postorder_traversal(root); cout<<endl; break; } case 6: { cout<<endl<<"Preorder traversal is: "; preorder_traversal(root); cout<<endl; break; } case 7: exit(0); default: cout<<"\nInvalid numeric value\n"; break; } } return 0; } <file_sep>/Data Structure/Sorting/bubble_sort.cpp // bubble sort implementation #include<bits/stdc++.h> using namespace std; // returns a vector of sorted elements vector<int> bubble_sort(vector<int> ara) { int n = ara.size() - 1; // because array index starts from zero for(int i = 0; i < n; i++) { int ptr = 0; while(ptr < n-i) { if(ara[ptr] > ara[ptr+1]) { //cout<<"Before: "<<ara[ptr]<<" "<<ara[ptr+1]<<endl; swap(ara[ptr], ara[ptr+1]); //cout<<"After: "<<ara[ptr]<<" "<<ara[ptr+1]<<endl; } ptr++; } } return ara; } int main() { vector<int>ara; int n; cout<<"\nHow many elements: "; cin>>n; int item; cout<<"\nEnter elements: "; while(n--) { cin>>item; ara.push_back(item); } vector<int>sortedArray; sortedArray = bubble_sort(ara); cout<<"\nSorted array is: "; for(int i = 0; i < sortedArray.size(); i++) cout<<sortedArray[i]<<" "; return 0; } <file_sep>/Data Structure/Sorting/recusive_quick_sort.cpp // implementation of quicksort with recursion #include<bits/stdc++.h> using namespace std; int get_partition(vector<int> &ara, int start_index, int end_index) { // cout<<endl<<"From get_partion()"<<endl; // cout<<start_index<<" "<<end_index<<endl; int pivot = ara[end_index]; int index = start_index; for(int i = start_index; i < end_index; i++) { if(ara[i] <= pivot) { swap(ara[i], ara[index]); index++; } } swap(ara[index], ara[end_index]); /* cout<<endl<<"index: "<<index<<endl; cout<<"Array till index: "<<endl; for(int i = 0; i < index; i++) cout<<ara[i]<<" "; */ return index; } void quick_sort(vector<int> &ara, int start_index, int end_index) { /* cout<<endl<<"From quick_sort"<<endl; cout<<start_index<<" "<<end_index<<endl; */ if(start_index < end_index) { int index = get_partition(ara, start_index, end_index); quick_sort(ara, start_index, index - 1); quick_sort(ara, index + 1, end_index); } } // driver code int main() { vector<int>ara; int n; cout<<"\nHow many elements: "; cin>>n; int item; cout<<"\nEnter elements: "; while(n--) { cin>>item; ara.push_back(item); } int s = ara.size(); quick_sort(ara, 0, s-1); cout<<"\nSorted array is: "; for(int i = 0; i < s; i++) cout<<ara[i]<<" "; return 0; } <file_sep>/Data Structure/Searching/ternary_search.cpp // implementation of ternary search #include<bits/stdc++.h> using namespace std; int ternary_search(vector<int>ara, int value) { int start = 0; int end = ara.size() - 1; while(start <= end) { int left_mid = start + (end - start) / 3; int right_mid = end - (end - start) / 3; // base cases if(ara[left_mid] == value) return left_mid; if(ara[right_mid] == value) return right_mid; if(ara[left_mid] > value) // search value resides in first half // offset end index end = left_mid - 1; else if(ara[right_mid] < value) // search value resides in last half // offset start index start = right_mid + 1; else // search value resides in second half start = left_mid + 1, end = right_mid - 1; } return -1; } int main() { int n; cout<<"\nEnter array size: "; cin>>n; vector<int>ara; cout<<"\nEnter array elements in sorted order: "; while(n--) { int data; cin>>data; ara.push_back(data); } int value; cout<<"\nEnter search value: "; cin>>value; int result = ternary_search(ara, value); if(result == -1) cout<<"\nItem not found"; else cout<<"\nItem found at: "<<result+1<<endl; return 0; } <file_sep>/Data Structure/Queue/Problems/equal_stack.cpp #include<bits/stdc++.h> #include<deque> using namespace std; int main() { deque<int> s1, s2, s3; int n1, n2, n3; cin>>n1>>n2>>n3; while(n1--) { int item; cin>>item; s1.push_back(item); } while(n2--) { int item; cin>>item; s2.push_back(item); } while(n3--) { int item; cin>>item; s3.push_back(item); } int sum1 = accumulate(s1.begin(), s1.end(), 0); int sum2 = accumulate(s2.begin(), s2.end(), 0); int sum3 = accumulate(s3.begin(), s3.end(), 0); int mx = min({sum1, sum2, sum3}); while (mx != 0) { if((mx == sum1) && (mx == sum2) && (mx == sum3)) break; if(mx < sum1) { int temp = s1.front(); s1.pop_front(); sum1 -= temp; } if(mx < sum2) { int temp = s2.front(); s2.pop_front(); sum2 -= temp; } if(mx < sum3) { int temp = s3.front(); s3.pop_front(); sum3 -= temp; } mx = min({sum1, sum2, sum3}); } cout<<mx; return 0; } <file_sep>/Data Structure/Searching/linear_search.cpp // implementation of linear search #include<iostream> using namespace std; int linear_search(int ara[], int value, int n) { for(int i = 0; i < n; i++) { if(ara[i] == value) return i+1; } return -1; } int main() { // allocating memory dynamically int* ara = NULL; int n; cout<<"\nEnter array size: "; cin>>n; ara = new int[n]; cout<<"\nEnter array items: "; for(int i = 0; i < n; i++) { int item; cin>>item; ara[i] = item; } int value; cout<<"\nEnter value to search: "; cin>>value; int pos; pos = linear_search(ara, value, n); // free up memory delete [] ara; ara = NULL; if(pos == -1) cout<<value<<" not found"<<endl; else cout<<value<<" found at: "<<pos<<endl; return 0; } <file_sep>/Data Structure/Tree/binary_search_tree.cpp // implementation of binary search tree #include<bits/stdc++.h> using namespace std; struct Node { int data; Node* left; Node* right; }; Node* root = NULL; Node* add_new_node(int item) { Node* new_node = new Node(); new_node->data = item; new_node->left = NULL; new_node->right = NULL; return new_node; } void insert_node(int item) { Node* temp = root; Node* new_node = add_new_node(item); Node* tail_node = new Node(); // check if tree is empty if(root == NULL) { root = new_node; cout<<endl<<item<<" is added"<<endl; return; } while(temp != NULL) { tail_node = temp; if(item < temp->data) { temp = temp->left; } else if(item > temp->data) { temp = temp->right; } else { // this means node is already exist in tree cout<<endl<<item<<" already exist in the tree"<<endl; return; } } // we made this far...that means item isn't inserted before // now link the newly created node with tail node if(item < tail_node->data) { tail_node->left = new_node; } else { tail_node->right = new_node; } cout<<endl<<item<<" is added"<<endl; } void find_item(int item) { Node* temp = new Node(); temp = root; while(temp != NULL) { if (temp->data == item) { cout<<endl<<item<<" is found in the tree"<<endl; return; } else if(item < temp->data) { temp = temp->left; } else { temp = temp->right; } } cout<<endl<<item<<" is not found in the tree"<<endl; } // returns the height of both side int height(Node* p) { if(p == NULL) return 0; int x = height(p->left); int y = height(p->right); return x > y ? x+1: y+1; } // returns rightmost leaf node of left side Node* predecessor(Node* p) { while(p != NULL && p->right != NULL) p = p->right; return p; } // returns the leftmost leaf node of right side Node* successor(Node* p) { while(p != NULL && p->left != NULL) p = p->left; return p; } Node* delete_node(Node* p, int item) { Node* q; if(p == NULL) { cout<<endl<<item<<" doesn't exist in the tree"<<endl; return NULL; } if(p->left == NULL && p->right == NULL) { if(p == root) root = NULL; delete p; cout<<endl<<"A node is deleted from the tree"<<endl; return NULL; } if(item < p->data) { p->left = delete_node(p->left, item); } else if(item > p->data) { p->right = delete_node(p->right, item); } else { if(height(p->left) > height(p->right)) { q = predecessor(p->left); p->data = q->data; p->left = delete_node(p->left, q->data); } else { q = successor(p->right); p->data = q->data; p->right = delete_node(p->right, q->data); } } return p; } void preorder_traversal(Node* root) { if(root != NULL) { cout<<root->data<<" "; preorder_traversal(root->left); preorder_traversal(root->right); } } void inorder_traversal(Node* root) { if(root != NULL) { inorder_traversal(root->left); cout<<root->data<<" "; inorder_traversal(root->right); } } void postorder_traversal(Node* root) { if(root != NULL) { postorder_traversal(root->left); postorder_traversal(root->right); cout<<root->data<<" "; } } // driver code int main() { int choice; cout<<endl<<"Enter below numeric value for listed operation\n\n"; while(1) { cout<<"\n1.Insert a node" <<"\n2.Delete a node" <<"\n3.Find a item" <<"\n4.Inorder traversal" <<"\n5.Postorder traversal" <<"\n6.Preorder traversal" <<"\n7.Exit" <<endl; cout<<"Enter your choice: "; cin>>choice; switch(choice) { case 1: { int item; cout<<"\nEnter item to be inserted: "; cin>>item; insert_node(item); break; } case 2: { int item; cout<<"\nEnter item to be delete: "; cin>>item; delete_node(root, item); break; } case 3: { int item; cout<<endl<<"Enter a item to search: "; cin>>item; find_item(item); break; } case 4: { cout<<endl<<"Inorder traversal is: "; inorder_traversal(root); cout<<endl; break; } case 5: { cout<<endl<<"Postorder traversal is: "; postorder_traversal(root); cout<<endl; break; } case 6: { cout<<endl<<"Preorder traversal is: "; preorder_traversal(root); cout<<endl; break; } case 7: exit(0); default: cout<<"\nInvalid numeric value\n"; break; } } return 0; } <file_sep>/Data Structure/Sorting/radix_sort.cpp // implementation of radix sort #include<bits/stdc++.h> using namespace std; void count_sort(int ara[], int n, int pos) { int frequency[10] = {0}; int temp[n]; // copying original array into temporary array for(int i = 0; i < n; i++) temp[i] = ara[i]; // counting frequency of each element for(int i = 0; i < n; i++) { ++frequency[(temp[i] / pos) % 10]; } // accumulating frequency for tracing exact position of element for(int i = 1; i < n; i++) { frequency[i] += frequency[i-1]; } // replacing elements by frequency index for(int i = n - 1; i >= 0; i--) { int index = (ara[i]/pos) % 10; temp[--frequency[index]] = ara[i]; } // copying modified temporary array into original array for(int i = 0; i < n; i++) ara[i] = temp[i]; } void radix_sort(int ara[], int n) { int mx = *max_element(ara, ara+n); for(int pos = 1; (mx/pos) > 0; pos = pos*10) { // calling counting sort subroutine count_sort(ara, n, pos); } cout<<"Sorted array: "; for(int i = 0; i < n; i++) cout<<ara[i]<<" "; } // driver code int main() { int n; cout<<"How many elements: "; cin>>n; int ara[n]; cout<<"Enter elements: "; for(int i = 0; i < n; i++) { int temp; cin>>temp; ara[i] = temp; } radix_sort(ara, n); return 0; } <file_sep>/README.md ## Data Structure and Algorithms This is part of my 100 days of data structure and algorithm challange. Each day I will either revisit one DS&ALGo topic I've learned before or learn a new one. Good luck to me! <file_sep>/Data Structure/Sorting/insertion_sort.cpp // implementation of insertion sort #include<bits/stdc++.h> using namespace std; // returns a sorted vector vector<int> insertion_sort(vector<int> ara) { int n = ara.size(); for(int i = 1; i < n; i++) { // for ascending order set ara[0] as partition value // for descending order set ara[n-1] as partition value int current_value = ara[i]; int index = i; // traverse array from right to left(for ascending order) // find the right index current value while(index > 0 && ara[index - 1] > current_value) { ara[index] = ara[index - 1]; index--; } ara[index] = current_value; } return ara; } // driver code int main() { vector<int>ara; int n; cout<<"\nHow many elements: "; cin>>n; int item; cout<<"\nEnter elements: "; while(n--) { cin>>item; ara.push_back(item); } vector<int>sorted_array; sorted_array = insertion_sort(ara); cout<<"\nSorted array is: "; for(int i = 0; i < sorted_array.size(); i++) cout<<sorted_array[i]<<" "; return 0; } <file_sep>/Data Structure/Graph/breadth_first_search.py from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(set) def connect_node(self, fromNode, toNode): self.graph[fromNode].add(toNode) def bfs(self, source): visited = [False] * (max(self.graph) + 1) q = [] q.append(source) visited[source] = True while q: s = q.pop(0) print(s, end=" ") for i in self.graph[s]: if visited[i] == False: q.append(i) visited[i] = True g = Graph() g.connect_node(0,1) g.connect_node(0,2) g.connect_node(1,0) g.connect_node(1,2) g.connect_node(2,0) g.connect_node(2,3) g.connect_node(3,2) g.bfs(3)<file_sep>/Data Structure/Queue/circular_queue.cpp // implementation of circular queue #include<stdio.h> #include<stdlib.h> #define MAX_SIZE 4 // max capacity 5 int QUEUE[MAX_SIZE]; // initial index of QUEUE int FRONT = -1, REAR = -1; /* q_insert() working procedure: 1.Check if queue overflows 2. Set new value of REAR a. Case 1: Set both FRONT & REAR = 0 if inserted for the first time b. Case 2: Offset REAR to 0 if REAR reached to MAX_SIZE c. Case 3: Else increase REAR by 1 3. Push item to REAR index of QUEUE */ void q_insert(int item) { if((FRONT == 0 && REAR == MAX_SIZE) || FRONT == REAR + 1) { printf("\nQueue overflow...\n"); } else { if(FRONT == -1) FRONT = 0, REAR = 0; else if(REAR == MAX_SIZE) REAR = 0; else REAR += 1; QUEUE[REAR] = item; printf("\n%d is inserted at: %dth position\n", item, REAR); } } /* q_delete() working procedure: 1. Check if queue underflows 2. Extract item and position for printing on console(optional) 3. Set new value of FRONT a. Case 1: Offset both FRONT & REAR to negative index if there is only one item b. Case 2: Offset FRONT to 0 if FRONT reached to MAX_SIZE c. Case 3: Else increase FRONT by 1 */ void q_delete() { if(FRONT == -1) printf("\nQueue underflow...\n"); else { int item = QUEUE[FRONT], pos = FRONT; if (FRONT == REAR) FRONT = -1, REAR = -1; else if(FRONT == MAX_SIZE) FRONT = 0; else FRONT += 1; printf("\n%d is deleted from %dth position\n", item, pos); } } /* print_queue() working procedure: 1. Check if queue is empty 2. Loop through the queue a. Case 1: if FRONt <= REAR -> do normal linear looping b. Case 2: if FRONT > REAR -> i. Loop from FRONT to MAX_SIZE ii. Then loop from 0 to REAR */ void print_queue() { if(FRONT == -1 || REAR == -1 ||(FRONT == -1 && REAR == -1)) { printf("\nQueue is empty\n"); } else if (FRONT <= REAR) { // Case 1 printf("\nQueue items are: "); for(int i = FRONT; i <= REAR; i++) printf("%5d", QUEUE[i]); } else { // Case 2 printf("\nQueue items are: "); for(int i = FRONT; i <= MAX_SIZE; i++) printf("%5d", QUEUE[i]); for(int i = 0; i <= REAR; i++) printf("%5d", QUEUE[i]); } } int main() { // driver code int choice; printf("Enter below numeric value for listed queue operations\n\n"); while(1) { printf("\n1.Insert\n2.Delete\n3.Print the queue\n4.Exit\n"); printf("Enter your choice: "); scanf("%d", &choice); switch(choice) { case 1: int item; printf("\nEnter item to be queued: "); scanf("%d", &item); q_insert(item); break; case 2: q_delete(); break; case 3: print_queue(); printf("\n"); break; case 4: exit(0); default: printf("\nInvalid numeric value\n"); break; } } return 0; } <file_sep>/Data Structure/Searching/binary_search.cpp // implementation of binary search #include<bits/stdc++.h> using namespace std; int bin_search(vector<int>ara, int value) { int start = 0; int end = ara.size() - 1; while(start <= end) { int mid = (start + end) / 2; // base case if(ara[mid] == value) return mid; else if(ara[mid] < value) // leave first half start = mid + 1; else if(ara[mid] > value) // leave last half end = mid - 1; } return -1; } int main() { int n; cout<<"\nEnter array size: "; cin>>n; vector<int>ara; cout<<"\nEnter array elements in sorted order: "; while(n--) { int data; cin>>data; ara.push_back(data); } int value; cout<<"\nEnter search value: "; cin>>value; int result = bin_search(ara, value); if(result == -1) cout<<"\nItem not found"; else cout<<"\nItem found at: "<<result+1<<endl; return 0; } <file_sep>/Data Structure/Queue/deque.cpp #include<iostream> #define MAX_SIZE 4 using namespace std; int DEQUE[MAX_SIZE]; int FRONT = -1, REAR = -1; // helper methods // check if full bool is_full() { if((FRONT == 0 && REAR == MAX_SIZE) || FRONT == REAR + 1) return true; return false; } // check if empty bool isEmpty() { if(FRONT == -1) return true; return false; } // insert_front void push_front(int item) { // check if deque is full if(is_full()) { cout<<"\nDeque Overflows...\n"; return; } // find new FRONT index if(isEmpty()) // if deque is empty FRONT = 0, REAR = 0; else if(FRONT == 0) // if FRONT points to first index FRONT = MAX_SIZE; else FRONT -= 1; // if FRONT points to in between first and last index // push item to FRONT index DEQUE[FRONT] = item; cout<<endl<<item<<" is inserted at: "<<FRONT<<endl; } void push_back(int item) { if(is_full()) { cout<<"\nDeque Overflows...\n"; return; } // find new REAR index if(isEmpty()) // if deque is empty FRONT = 0, REAR = 0; else if(REAR == MAX_SIZE) // if REAR points to last index REAR = 0; else // if REAR points to in between first and last index REAR += 1; // push item to REAR index DEQUE[REAR] = item; cout<<endl<<item<<" is inserted at: "<<REAR<<endl; } void pop_front() { // check if empty if(isEmpty()) { cout<<"\nDeque underflows...\n"; return; } // extract item and position for printing on console int item = DEQUE[FRONT]; int pos = FRONT; // find new FRONT index if(FRONT == REAR) // if deque has only one element FRONT = -1, REAR = -1; else if(FRONT == MAX_SIZE) // if FRONT points to last index FRONT = 0; else FRONT += 1; cout<<endl<<item<<" is deleted from: "<<pos<<endl; } void pop_back() { // check if empty if(isEmpty()) { cout<<"\nDeque underflows...\n"; return; } // extract item and position for printing on console int item = DEQUE[REAR]; int pos = REAR; // find new REAR index if(FRONT == REAR) // if deque has only one element FRONT = -1, REAR = -1; else if(REAR == 0) // if REAR points to first index REAR = MAX_SIZE; else // if REAR points in between first and last index REAR -= 1; cout<<endl<<item<<" is deleted from: "<<pos<<endl; } void print_deqeue() { // check if empty if(isEmpty()) { cout<<"\nEmpty deque\n"; return; } if (FRONT <= REAR) { // Case 1 printf("\nDeque items are: "); for(int i = FRONT; i <= REAR; i++) cout<<DEQUE[i]<<" "; } else { // Case 2 printf("\nDeque items are: "); for(int i = FRONT; i <= MAX_SIZE; i++) cout<<DEQUE[i]<<" "; for(int i = 0; i <= REAR; i++) cout<<DEQUE[i]<<" "; } } int main() { // driver code int choice; cout<<"Enter below numeric value for listed deque operations\n\n"; while(1) { cout<<"\n1.Push item at front" <<"\n2.Push item at end" <<"\n3.Delete from front" <<"\n4.Delete from end" <<"\n5.Print Deque" <<"\n6.Exit" <<endl; cout<<"Enter your choice: "; cin>>choice; switch(choice) { case 1: { int item; printf("\nEnter item to be pushed at front: "); scanf("%d", &item); push_front(item); break; } case 2: { int item; printf("\nEnter item to be pushed at end: "); scanf("%d", &item); push_back(item); break; } case 3: pop_front(); break; case 4: pop_back(); break; case 5: print_deqeue(); cout<<endl; break; case 6: exit(0); default: printf("\nInvalid numeric value\n"); break; } } return 0; } <file_sep>/Data Structure/Sorting/selection_sort.cpp // implementation of selection sort #include<bits/stdc++.h> using namespace std; // returns a vector of sorted elements vector<int> selection_sort(vector<int> ara) { int n = ara.size(); for(int i = 0; i < n - 1; i++) { int index = i; // holds the index of current value for(int j = i+1; j < n; j++) { if(ara[index] > ara[j]) index = j; // set new index if lesser value found } swap(ara[i], ara[index]); // swap current index value with index value } return ara; } int main() { vector<int> ara; int n; cout<<"\nHow many elements: "; cin>>n; cout<<"\nEnter elements: "; while(n--) { int data; cin>>data; ara.push_back(data); } vector<int> sorted_array; sorted_array = selection_sort(ara); cout<<"\nArray elements after sorting: "; for(int i = 0; i < sorted_array.size(); i++) cout<<sorted_array[i]<<" "; return 0; } <file_sep>/Data Structure/Tree/binary_tree.py from typing import List class Node(): def __init__(self, data=0, left=None, right=None): self.data = data self.left = left self.right = right def construct_binary_tree(nodeList: List[int], root: Node, i: int, n: int) -> Node: if i < n: root = Node(nodeList[i]) root.left = construct_binary_tree(nodeList, root.left, 2*i+1, n) root.right = construct_binary_tree(nodeList, root.right, 2*i+2, n) return root def inorder(root: Node): if root is None: return inorder(root.left) print(root.data, end=' ') inorder(root.right) def preorder(root: Node): if root is None: return print(root.data, end=' ') preorder(root.left) preorder(root.right) def postorder(root: Node): if root is None: return postorder(root.left) postorder(root.right) print(root.data, end=' ') if __name__ == "__main__": nodeList = [0, 1, 2, 3, 4, 5, 6] root = None root = construct_binary_tree(nodeList, root, 0, len(nodeList)) inorder(root) print('\n') preorder(root) print('\n') postorder(root) <file_sep>/Data Structure/Pattern Matching/kmp.cpp // implementation of Knuth-Morris-Pratt pattern matching algorithm #include<bits/stdc++.h> using namespace std; vector<int> construct_lps(string pattern) { int len = pattern.size(); vector<int> lps(len); lps[0] = 0; int index = 0; int i = 1; while(i < len) { if (pattern[i] == pattern[index]) { lps[i] = index + 1; index++; i++; //cout<<"\nInside pattern[i] "<<index<<" "<<i<<endl; } else { if (index == 0) { lps[i] = index; i++; //cout<<"\nInside index==0 "<<index<<" "<<i<<endl; } else { index = lps[index - 1]; //cout<<index<<" "<<i; } } } return lps; } bool KMP(string text, string pattern) { vector<int> lps = construct_lps(pattern); int text_len = text.size(); int pattern_len = pattern.size(); int i = 0, j = 0; while(i < text_len) { if(text[i] == pattern[j]) i++, j++; else { if(j == 0) i++; else j = lps[j-1]; } if(j == pattern_len) { j = lps[j-1]; return true; } } return false; } int main() { string pattern, text; getline(cin, text); getline(cin, pattern); bool matched = KMP(text, pattern); if(matched) cout<<pattern<<" pattern is found in the text"; else cout<<pattern<<" not found"; return 0; } <file_sep>/Data Structure/Pattern Matching/rabin-karp.cpp // implementation of rabin-karp pattern matching algorithm #include<bits/stdc++.h> #include<cmath> using namespace std; vector<int> rabin_karp_search(string text, string pattern) { int text_len = text.size(); int pattern_len = pattern.size(); vector<int>result; // mod feel like P.I.T.A. so I simply extend int range long long int text_hash = 0, pat_hash = 0; long long int h = 1; // random value to avoid spurious hit int base = 10; // find the offset value for(int i = 0; i < pattern_len-1; i++) h = (h*base); // get hash value pattern and text[pattern_len] for(int i = 0; i < pattern_len; i++) { pat_hash = (base * pat_hash + pattern[i]); text_hash = (base * text_hash + text[i]); } // iteration begins for(int i = 0; i <= text_len - pattern_len; i++) { // checking if pattern hash value and text hash are equivalent if(pat_hash == text_hash) { // j declared outside the loop for scope int j; // check pattern and selected part of text character by character for(j = 0; j < pattern_len; j++) { // if don't match break; if(text[i+j] != pattern[j]) break; } if(j==pattern_len) //cout<<"Pattern matched at: "<<i+1<<endl; result.push_back(i+1); } else if(i < text_len - pattern_len) { // subtract first character hash value and add next character hash value text_hash = (base * (text_hash - text[i]*h) + text[i+pattern_len]); // in case text_hash become negative // offset it by a random value if(text_hash < 0) text_hash = text_hash + 123; } } return result; } int main() { string text, pattern; cout<<"\nEnter text: "; getline(cin, text); cout<<"\nEnter pattern: "; getline(cin, pattern); vector<int>result; result = rabin_karp_search(text, pattern); if(result.empty()) cout<<"\nPattern not found"; else { for(int i = 0; i < result.size(); i++) cout<<endl<<pattern<<" found at: "<<result[i]<<endl; } return 0; } <file_sep>/Data Structure/Stack/stack.cpp // Simple implementation of STACK for fixed size array #include<stdio.h> #include<stdlib.h> // for exit(0) #define STACK_SIZE 9 // max stack capacity is 10 // declared globally for being accessed by all functions int TOP = -1; // current position of stack int STACK[STACK_SIZE]; // stack initialized with 10 capacity /* push function working procedure: 1. Check if current size exceeds max capacity 2. increase TOP by 1 3. Set stack index TOP 4. Push item into current index */ void push(int item) { // checking if stack overflows if(TOP < STACK_SIZE) { // increasing TOP TOP = TOP + 1; // setting index and pushing item to it STACK[TOP] = item; printf("\n%d is inserted at: %dth position\n", item, TOP); } else { printf("\nCurrent stack size exceeds max size, can't insert new item\n"); } } /* pop function working procedure: 1. Check if current stack size underflows 2. Extract item from current stack index for printing(optional) 3. Decrease TOP by 1 */ void pop() { int item; // checking if stack size underflows if(TOP == -1) { printf("\nCurrent stack is empty. Can't pop item\n"); } else { // extracting item from current index item = STACK[TOP]; printf("\n%d is popped from: %dth position\n", item, TOP); // decreasing index by 1 TOP--; } } /* print_stack() working procedure 1. Check if stack size underflows * Current stack size is determined by TOP. 2. Loop till counter variable reached to zero 3. Access and print stack by counter variable */ void print_stack() { // check if stack is empty if(TOP == -1) { printf("\nCurrent stack is empty\n"); } else { printf("\nItems in current stack:\n"); // iterating for(int i = TOP; i >= 0; i--) { printf("%d\n", STACK[i]); } } } /* whats_on_the_top() working procedure 1. Check if current stack size underflows 2. Access most recent item by TOP and print it */ void whats_on_the_top() { if(TOP == -1) { printf("\nCurrent Stack is empty\n"); } else { printf("\nItem on top of stack: %d\n", STACK[TOP]); } } int main() { int choice; // driver code printf("Enter below numeric value for listed stack operation\n\n"); while(1) { printf("\n1.Push\n2.Pop\n3.Print the stack\n4.See what's on the top\n5.Exit\n"); printf("Enter your choice: "); scanf("%d", &choice); switch(choice) { case 1: int item; printf("\nEnter item to be pushed: "); scanf("%d", &item); push(item); break; case 2: pop(); break; case 3: print_stack(); printf("\n"); break; case 4: whats_on_the_top(); break; case 5: exit(0); default: printf("\nInvalid numeric value\n"); break; } } return 0; } <file_sep>/Data Structure/Linked List/linked_list.cpp // implementation of singly linked list #include<iostream> #include<stdlib.h> using namespace std; struct Node { int item; Node* next; }; Node* head = NULL; int list_length() { int count = 0; for(Node* i = head; i != NULL; i = i->next) count++; return count; } void insert_at_front(int item) { Node* new_node = new Node(); new_node->item = item; new_node->next = head; head = new_node; cout<<endl; cout<<item<<" is inserted at memory location: "<<head<<endl; } void insert_at_nth(int item, int pos) { Node* new_node = new Node(); new_node->item = item; new_node->next = NULL; // if inserted at start if(pos == 1) { new_node->next = head; head = new_node; cout<<endl; cout<<item<<" is inserted at memory location: "<<head<<endl; return; } Node* temp = head; for(int i = 0; i < pos-2; i++) { temp = temp->next; } new_node->next = temp->next; temp->next = new_node; cout<<endl; cout<<item<<" is inserted at memory location: "<<temp->next<<endl; } void insert_at_end(int item) { int length = 0; length = list_length(); if(length == 0) { insert_at_front(item); } else { insert_at_nth(item, length+1); } } void delete_first_node() { Node* temp = head; cout<<endl; cout<<temp->item<<" is deleted from memory location: "<<head<<endl; head = temp->next; delete temp; } void delete_nth_node(int pos) { if(pos == 1) { delete_first_node(); } else { Node* temp1 = head; for(int i = 0; i < pos - 2; i++) { temp1 = temp1->next; } Node* temp2 = temp1->next; cout<<endl; cout<<temp2->item<<" is deleted from memory location: "<<temp1->next<<endl; temp1->next = temp2->next; delete temp2; } } void print_list() { Node* temp = head; cout<<"\nList items are: \n"; while(temp != NULL) { cout<<"Item: "<<temp->item<<" "<<"Memory address: "<<temp->next<<endl; temp = temp->next; } cout<<endl; } int main() { int choice; // driver code cout<<"Enter below numeric value for listed stack operation\n\n"; while(1) { cout<<"\n1.Insert item at front" <<"\n2.Insert item at end" <<"\n3.Insert item at nth position" <<"\n4.Delete first item" <<"\n5.Delete nth item" <<"\n6.Print the list" <<"\n7.List length" <<"\n8.Exit" <<endl; cout<<"Enter your choice: "; cin>>choice; switch(choice) { case 1: { int item; cout<<"\nEnter item to be inserted: "; cin>>item; insert_at_front(item); break; } case 2: { int item; cout<<"\nEnter item to be inserted: "; cin>>item; insert_at_end(item); break; } case 3: { int item, pos; cout<<"\nEnter item to be inserted: "; cin>>item; cout<<endl; cout<<"\nEnter insert position: "; cin>>pos; cout<<endl; insert_at_nth(item, pos); break; } case 4: { if(list_length() > 0) { delete_first_node(); } else { cout<<"\nEmpty list...\n"; } break; } case 5: { int pos; cout<<"\nEnter position to delete item: "; cin>>pos; delete_nth_node(pos); } case 6: print_list(); break; case 7: { int length = 0; length = list_length(); cout<<"\nList length is: "<<length<<endl; break; } case 8: exit(0); default: cout<<"\nInvalid numeric value\n"; break; } } return 0; } <file_sep>/Data Structure/Queue/queue.cpp #include<stdio.h> #include<stdlib.h> #define MAX_SIZE 9 int QUEUE[MAX_SIZE+1]; int FRONT = -1, REAR = -1; /* q_insert() working procedure: 1. check if queue already filled 2. Set new value of REAR 3. Insert item into REAR index */ void q_insert(int item) { if(REAR == MAX_SIZE) printf("\nQueue overflows...\n"); else { // if queue initialized for the first time if(FRONT == -1) FRONT = 0; REAR += 1; QUEUE[REAR] = item; printf("\n%d is inserted at: %dth position\n", item, REAR); } } /* q_delete() working procedure: 1. Check if queue underflows 2. Assign current FRONT value to a variable for further use 3. Set new value of FRONT a. If FRONT exceeds REAR, reset FRONT and REAR back to initial state 4. Access deleted item by temp for printing */ void q_delete() { if(FRONT == -1) printf("\nQueue underflows...\n"); else { int temp = FRONT; FRONT += 1; if(FRONT > REAR) { FRONT = -1, REAR = -1; } printf("\n%d is deleted from %dth position\n",QUEUE[temp], temp); } } /* print_queue() working procedure: 1. check if queue is empty 2. Loop through the queue */ void print_queue() { if(FRONT == -1 || REAR == -1 || (FRONT == -1 && REAR == -1)) printf("\nQueue is empty...\n"); else { printf("Items in the queue is: \t"); for(int i = FRONT; i <= REAR; i++) { printf("%5d", QUEUE[i]); } printf("\n\n"); } } int main() { // driver code int choice; printf("Enter below numeric value for listed queue operations\n\n"); while(1) { printf("\n1.Insert\n2.Delete\n3.Print the queue\n4.Exit\n"); printf("Enter your choice: "); scanf("%d", &choice); switch(choice) { case 1: int item; printf("\nEnter item to be queued: "); scanf("%d", &item); q_insert(item); break; case 2: q_delete(); break; case 3: print_queue(); printf("\n"); break; case 4: exit(0); default: printf("\nInvalid numeric value\n"); break; } } return 0; }
ec7fb88def8a70999c7be30bbf44d75b70ce28a3
[ "Markdown", "Python", "C++" ]
23
C++
azad71/Data-Structure-and-Algorithms
9394be7ac2f923f2a271ddadd7b6bad1373697a7
a4ac3494632749032637b48413e2c49677ee55cd
refs/heads/master
<file_sep>'use strict'; exports.roadsigns = { pkg: require('./package.json'), register: async function (server, options) { const statusLookup = { 100: function () { return {status: 'continue', code: 100}; }, 'continue': function () { 100 (); }, 418: function () { return {status: 'I\'m a teapot', code: 418}; }, 'iAmATeapot': function () { 418 (); } }; const rs = function (code) { return this.response(statusLookup[code]); }; server.decorate('toolkit', 'rs', rs); } };
031241115b7c8a1bef949de44d8692f2093aa0c4
[ "JavaScript" ]
1
JavaScript
WebMatrixware/roadsigns
83a1366be779a4ee267bc416f2e2c457408cbcf6
67c56b08f9f6f99e53fc6f09bbde0670151e79a3
refs/heads/master
<file_sep>#include <iomanip> #include <iostream> #include <cmath> using namespace std; int main () { float s,s1; for (int i=1; i<pow(10,9); i++) s+=1.0/pow(i,2); cout<<s<<endl; for (int i=pow(10,9); i>0; i--) s1+=1.0/pow(i,2); cout<<s1<<endl; } <file_sep>#include <iostream> #include <iomanip> #include <math.h> #include<fstream> using namespace std; int main () { ifstream fin("input.txt"); ofstream fout("output.txt"); int n; float s; fin>>n; float **a=new float* [n]; for (int i=0; i<n; i++) a[i]=new float [n]; for (int i=0; i<n; i++) for (int j=0; j<n; j++) { fin>>a[i][j]; } //приводим матрицу к треугольному виду for(int k=0; k<n; k++) for(int i=k+1; i<n;i++) for(int j=0;j<n;j++) a[i][j]=a[i][j]-a[k][j]*(a[i][k]/a[k][k]); /* for (int l=0; l<n; l++) { for (int t=0;t<n;t++) cout<<a[l][t]<<" "; cout<<endl; }*/ //выводим столбец свободных членов cout<<endl; float x[n],b[n]; for(int i=0; i<n;i++) { fin>>b[i]; //cout<<b[i]<<" "; } cout<<endl<<endl; s=0; x[n-1]=b[n-1]/a[n-1][n-1]; for(int i=n-1;i>=0;i--) { for (int j=i+1; j<n;j++) s=s+a[i][j]*x[j]; x[i]=(b[i]-s)/a[i][i]; s=0; } for (int l=0; l<n; l++) { fout<<x[l]<<" "; fout<<endl; } fin.close(); fout.close(); return 0; }
76cce47092cb751267b124672ec6c524eff630fa
[ "C++" ]
2
C++
samylkins/samylkin1
1c1b614f963e8c9a8ecc1dfb5cc0cc86a8b5b329
f36ffa75abddd00f409995ad65e83dd6a0f35ebc
refs/heads/master
<repo_name>nadvolod/sauceday-london-19<file_sep>/LiveDemo/UnitTest1.cs using System; using System.Collections.Generic; using System.Reflection; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Remote; namespace LiveDemo { [TestClass] public class DemoFeature { public IWebDriver _driver; public TestContext TestContext { get; set; } [TestInitialize] public void Setup() { _driver = GetDriver(); } public void Cleanup() { var passed = TestContext.CurrentTestOutcome == UnitTestOutcome.Passed; if (_driver != null) ((IJavaScriptExecutor)_driver).ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed")); _driver?.Quit(); } [TestMethod] public void ShouldBeAbleToLoad() { var loginPage = new LoginPage(_driver); loginPage.Open(); loginPage.IsLoaded().Should().BeTrue(); } [TestMethod] public void ShouldBeAbleToLogin() { var loginPage = new LoginPage(_driver); loginPage.Open(); loginPage.IsLoaded().Should().BeTrue(); loginPage.Login("standard_user", "secret_sauce"); new InventoryPage(_driver).IsLoaded().Should().BeTrue(); } private IWebDriver GetDriver() { //TODO please supply your Sauce Labs user name in an environment variable var sauceUserName = Environment.GetEnvironmentVariable( "SAUCE_USERNAME", EnvironmentVariableTarget.User); //TODO please supply your own Sauce Labs access Key in an environment variable var sauceAccessKey = Environment.GetEnvironmentVariable( "SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User); ChromeOptions options = new ChromeOptions(); options.AddAdditionalCapability(CapabilityType.Version, "latest", true); options.AddAdditionalCapability(CapabilityType.Platform, "Windows 10", true); options.AddAdditionalCapability("username", sauceUserName, true); options.AddAdditionalCapability("accessKey", sauceAccessKey, true); options.AddAdditionalCapability("name", MethodBase.GetCurrentMethod().Name, true); _driver = new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"), options.ToCapabilities(), TimeSpan.FromSeconds(600)); return _driver; } } } <file_sep>/LiveDemo/InventoryPage.cs using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; using System; namespace LiveDemo { internal class InventoryPage { private IWebDriver driver; public InventoryPage(IWebDriver driver) { this.driver = driver; } internal bool IsLoaded() { var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); var element = wait.Until(ExpectedConditions.ElementIsVisible(By.Id("inventory_filter_container"))); return element.Displayed; } } }<file_sep>/LiveDemo/LoginPage.cs using System; using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; namespace LiveDemo { public class LoginPage { private IWebDriver driver; public LoginPage(IWebDriver driver) { this.driver = driver; } internal void Open() { driver.Navigate().GoToUrl("https://www.saucedemo.com"); } internal bool IsLoaded() { var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); var element = wait.Until(ExpectedConditions.ElementIsVisible(By.Id("login_button_container"))); return element.Displayed; } internal void Login(string userName, string password) { driver.FindElement(By.Id("user-name")).SendKeys(userName); driver.FindElement(By.Id("password")).SendKeys(<PASSWORD>); driver.FindElement(By.ClassName("btn_action")).Click(); } } }
b592174199ebb6bff2e16fe7c158a8fae89e34c3
[ "C#" ]
3
C#
nadvolod/sauceday-london-19
cd82a891601b42031ca7aec47164dc0d8305fd7e
721aa0f31f1466398b6fc1c4170a5bed80961751
refs/heads/master
<repo_name>Peternator7/rustplacements<file_sep>/src/lib.rs #![crate_type = "dylib"] #![feature(plugin_registrar, rustc_private)] //! # Rustplacements //! //! This is a compiler plugin for the [Rust language](https://www.rust-lang.org/en-US/) that replaces all of your string literals //! in the source code with random text. Well, it's not really random. You can choose to replace text with items from any of the //! lists on [this page](https://github.com/Peternator7/rustplacements/blob/master/CATEGORIES.md) by simply adding a few //! attributes to your existing Rust code. //! //! ## A Brief Example //! //! Let's start with a simple example like the one below. It prints out the words in the sentence below one word at a time. //! //! ```rust,ignore //! const SENTENCE: [&'static str; 9] = ["The", "Quick", "Brown", "Fox", "Jumped", "Over", "the", //! "Lazy", "Dog"]; //! //! fn main() { //! for word in &SENTENCE { //! println!("{}", word); //! } //! } //! ``` //! //! The output should look like: //! //! ```txt //! The //! Quick //! Brown //! Fox //! Jumped //! Over //! the //! Lazy //! Dog //! ``` //! //! Rustplacements let's us replace all the strings at compile with other values. Let's say we want to replace all the text with //! emojis. Rustplacements can do that. //! //! ```rust,ignore //! #![feature(plugin)] //! #![plugin(rustplacements)] //! //! // Placing it in the module root will replace everything in the module //! #![Rustplacements = "emojis"] //! //! const SENTENCE: [&'static str; 9] = ["The", "Quick", "Brown", "Fox", "Jumped", "Over", "the", //! "Lazy", "Dog"]; //! //! fn main() { //! for word in &SENTENCE { //! println!("{}", word); //! } //! } //! ``` //! //! The new output will look something like this. The output is randomized so it will be re-generated everytime you compile //! your crate. //! //! ```text //! 😢 😫 🤓 //! 😞 😠 😟 😖 😧 //! 😬 😬 😈 😡 😟 //! 😓 😒 😬 //! 😝 😘 🤧 😬 😧 😡 //! 😗 😈 😉 😫 //! 😄 😱 😰 //! 😃 🤡 😅 😯 //! 🤒 😈 😈 //! ``` //! //! ## Using Rustplacements //! //! Compiler plugins like Rustplacements are only available on nightly rust because they require a feature flag to use. To get started, //! Rustplacements is available on [crates.io](https://crates.io/crates/rustplacements). To download the latest version, add the //! following line to the `Cargo.toml`. //! //! ```toml //! [dependencies] //! rustplacements = "*" //! ``` //! //! To enable the compiler plugin, add the following lines on the top of your `main.rs` or `lib.rs`. //! //! ```rust,ignore //! #![feature(plugin)] //! #![plugin(rustplacements)] //! ``` //! //! You can now use the plugin anywhere in the crate by applying the `#[Rustplacements = "one-direction"]` to any language element. //! You can place the element in the root with `#![Rustplacements = "got-quotes"]` and it will transform all the string literals //! in your module. It can also be applied to specific strings / impls / functions for more fine grained control. //! //! That's pretty much all there is to it. Check out the [categories page](https://github.com/Peternator7/rustplacements/blob/master/CATEGORIES.md) for more categories that you can use. extern crate syntax; extern crate rustc_plugin; extern crate rand; #[macro_use] extern crate lazy_static; use rustc_plugin::Registry; use syntax::ext::base::{Annotatable, ExtCtxt, SyntaxExtension}; use syntax::ast::*; use syntax::codemap::Span; use syntax::symbol::Symbol; use syntax::codemap::Spanned; use syntax::ptr::P; mod exprs; struct Context<'a> { text: &'a Vec<&'static str>, } /// Compiler hook for Rust to register plugins. #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_syntax_extension(Symbol::intern("Rustplacements"), SyntaxExtension::MultiModifier(Box::new(rustplace))) } fn rustplace(_: &mut ExtCtxt, _: Span, m: &MetaItem, an: Annotatable) -> Vec<Annotatable> { let category = match m.node { MetaItemKind::List(..) => panic!("This plugin does not support list style attributes."), MetaItemKind::Word => Symbol::intern("fizzbuzz"), MetaItemKind::NameValue(ref l) => { use LitKind::*; match l.node { Str(symbol, _) => symbol, _ => panic!("Only string literals are supported"), } } }; let ctxt = Context { text: exprs::HASHMAP.get(&*category.as_str()).unwrap() }; vec![an.trans(&ctxt)] } trait Rustplace { fn trans(self, ctxt: &Context) -> Self; } impl<T: Rustplace + 'static> Rustplace for P<T> { fn trans(self, ctxt: &Context) -> Self { self.map(|inner| inner.trans(ctxt)) } } impl<T: Rustplace> Rustplace for Vec<T> { fn trans(self, ctxt: &Context) -> Self { self.into_iter().map(|i| i.trans(ctxt)).collect() } } // We can invoke this rule on most of the struct types. macro_rules! Rustplace { // For many of the structs, the field is called "node" so we simplify that case. ($ty:ident) => (Rustplace!($ty,node);); ($ty:ident,$field:tt) => ( impl Rustplace for $ty { fn trans(self, ctxt: &Context) -> Self { $ty { $field: self.$field.trans(ctxt), ..self } } } ) } // We can autoimplement some of the structs because the all change the same field. :) Rustplace!(Item); Rustplace!(TraitItem); Rustplace!(ImplItem); Rustplace!(Stmt); Rustplace!(Expr); // These follow the same basic pattern, but the field has a different name. Rustplace!(Block, stmts); Rustplace!(Field, expr); Rustplace!(Mod, items); // These need 1 extra map so we just wrote them out. impl Rustplace for Local { fn trans(self, ctxt: &Context) -> Self { Local { init: self.init.map(|i| i.trans(ctxt)), ..self } } } impl Rustplace for Arm { fn trans(self, ctxt: &Context) -> Self { Arm { guard: self.guard.map(|i| i.trans(ctxt)), ..self } } } // All the enums need to be manually implemented and we figure out what variants it makes sense // for us to transform. impl Rustplace for Annotatable { fn trans(self, ctxt: &Context) -> Self { use Annotatable::*; match self { Item(item) => Item(item.trans(ctxt)), TraitItem(item) => TraitItem(item.trans(ctxt)), ImplItem(item) => ImplItem(item.trans(ctxt)), } } } impl Rustplace for ItemKind { fn trans(self, ctxt: &Context) -> Self { use ItemKind::*; match self { Fn(a, b, c, d, e, block) => Fn(a, b, c, d, e, block.trans(ctxt)), Static(ty, m, expr) => Static(ty, m, expr.trans(ctxt)), Const(ty, expr) => Const(ty, expr.trans(ctxt)), Trait(u, g, ty, v) => Trait(u, g, ty, v.trans(ctxt)), Impl(a, b, c, d, e, f, v) => Impl(a, b, c, d, e, f, v.trans(ctxt)), Mod(m) => Mod(m.trans(ctxt)), _ => self, } } } impl Rustplace for TraitItemKind { fn trans(self, ctxt: &Context) -> Self { use TraitItemKind::*; match self { Const(ty, Some(expr)) => Const(ty, Some(expr.trans(ctxt))), Method(sig, Some(block)) => Method(sig, Some(block.trans(ctxt))), _ => self, } } } impl Rustplace for ImplItemKind { fn trans(self, ctxt: &Context) -> Self { use ImplItemKind::*; match self { Const(ty, expr) => Const(ty, expr.trans(ctxt)), Method(sig, block) => Method(sig, block.trans(ctxt)), _ => self, } } } impl Rustplace for StmtKind { fn trans(self, ctxt: &Context) -> Self { use StmtKind::*; match self { Local(l) => Local(l.trans(ctxt)), Item(i) => Item(i.trans(ctxt)), Expr(e) => Expr(e.trans(ctxt)), Semi(s) => Semi(s.trans(ctxt)), _ => self, } } } impl Rustplace for ExprKind { fn trans(self, ctxt: &Context) -> Self { use ExprKind::*; match self { Lit(l) => Lit(l.trans(ctxt)), Box(b) => Box(b.trans(ctxt)), InPlace(a, b) => InPlace(a.trans(ctxt), b.trans(ctxt)), Array(v) => Array(v.trans(ctxt)), Call(a, v) => Call(a.trans(ctxt), v.trans(ctxt)), MethodCall(p, v) => MethodCall(p, v.trans(ctxt)), Tup(v) => Tup(v.trans(ctxt)), Binary(op, l, r) => Binary(op, l.trans(ctxt), r.trans(ctxt)), Unary(op, expr) => Unary(op, expr.trans(ctxt)), Cast(expr, ty) => Cast(expr.trans(ctxt), ty), Type(expr, ty) => Type(expr.trans(ctxt), ty), If(cond, iff, els) => { If(cond.trans(ctxt), iff.trans(ctxt), els.map(|i| i.trans(ctxt))) } IfLet(pat, expr, iff, els) => { IfLet(pat, expr.trans(ctxt), iff.trans(ctxt), els.map(|i| i.trans(ctxt))) } While(cond, blk, si) => While(cond.trans(ctxt), blk.trans(ctxt), si), WhileLet(p, expr, blk, si) => WhileLet(p, expr.trans(ctxt), blk.trans(ctxt), si), ForLoop(p, expr, blk, si) => ForLoop(p, expr.trans(ctxt), blk.trans(ctxt), si), Loop(expr, si) => Loop(expr.trans(ctxt), si), Match(expr, v) => Match(expr.trans(ctxt), v.trans(ctxt)), Closure(c, p, blk, s) => Closure(c, p, blk.trans(ctxt), s), Block(blk) => Block(blk.trans(ctxt)), Catch(blk) => Catch(blk.trans(ctxt)), Assign(a, b) => Assign(a.trans(ctxt), b.trans(ctxt)), AssignOp(op, lhs, rhs) => AssignOp(op, lhs.trans(ctxt), rhs.trans(ctxt)), Field(expr, si) => Field(expr.trans(ctxt), si), TupField(expr, span) => TupField(expr.trans(ctxt), span), Index(a, b) => Index(a.trans(ctxt), b.trans(ctxt)), Range(lower, upper, lim) => { Range(lower.map(|i| i.trans(ctxt)), upper.map(|i| i.trans(ctxt)), lim) } AddrOf(m, expr) => AddrOf(m, expr.trans(ctxt)), Break(br, expr) => Break(br, expr.map(|i| i.trans(ctxt))), Ret(opt) => Ret(opt.map(|i| i.trans(ctxt))), Struct(p, v, opt) => Struct(p, v.trans(ctxt), opt.map(|i| i.trans(ctxt))), Repeat(a, b) => Repeat(a.trans(ctxt), b.trans(ctxt)), Paren(expr) => Paren(expr.trans(ctxt)), Try(expr) => Try(expr.trans(ctxt)), _ => self, } } } impl Rustplace for Spanned<LitKind> { fn trans(self, ctxt: &Context) -> Self { use LitKind::*; match self.node { // All that code above just so we can do this one transformation :) Str(s, _) => { let new_string = s.as_str() .lines() .map(|line| { let mut output = String::new(); let mut idx = 0; // Copy the lead whitespace over. for c in line.chars() { if c.is_whitespace() { idx += 1; output.push(c); } else { break; } } let l = line.chars().count(); // Now just append random stuff. while idx < l { let r = rand::random::<usize>() % ctxt.text.len(); output.push_str(ctxt.text[r]); output.push(' '); idx += ctxt.text[r].chars().count(); } // TODO: Remove the trailing ' '. output }) .collect::<Vec<_>>() .join("\n"); Spanned { node: LitKind::Str(Symbol::intern(&*new_string), StrStyle::Cooked), ..self } } _ => self, } } } <file_sep>/src/exprs.rs use std::collections::HashMap; lazy_static! { pub static ref HASHMAP: HashMap<&'static str, Vec<&'static str>> = { let mut m = HashMap::new(); m.insert("fizzbuzz", vec!["1","2","fizz","4","buzz","fizz","7","8","fizz","buzz","11","fizz","13","14","fizzbuzz"]); m.insert("letters-lower", vec!["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]); m.insert("letters-upper", vec!["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]); m.insert("digits", vec!["0","1","2","3","4","5","6","7","8","9"]); m.insert("rainbow", vec!["red","orange","yellow","green","blue","indigo","violet"]); m.insert("grootify", vec!["I am groot.","I AAAMMM GROOT!!", "I am groot?!", "GROOT!#$%?"]); m.insert("planets", vec!["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune", "Pluto?"]); m.insert("puncutation", vec!["!",",",".","!","\\","/","$","^","#","@","*","(",")","-","+","=","%","#"]); m.insert("one-direction", vec!["Niall","Liam","Zayn","Louis","Harry"]); m.insert("pizza-toppings", vec!["Pepperoni","Sausage","Peppers","Onions","Black Olives","Pineapple?","Ham", "Bacon","Spinich","BBQ Sauce","Chicken","Tomatoes","Basil","Cheese","Hot Sauce"]); m.insert("got-quotes",vec![ "Winter is coming", "Chaos is a ladder", "When you play the game of thrones, you win or you die.", "The next time you raise a hand to me will be the last time you have hands.", "The man who passes the sentence should swing the sword.", "Hodor", "Power resides where men believe it resides. No more and no less." ]);; m.insert("alexa", vec![ "Alexa, order 1000 rolls of paper towels.", "Alexa, play Nickelback.", "Alexa, sing me a song.", "Alexa, how old are you?", "Alexa, call grandma.", "Alexa, order me a pizza.", ]); m.insert("friends-quotes", vec![]); m.insert("emojis",vec!["😀", "😃", "😄", "😁", "😆", "😅", "😂", "🤣", "😊", "😇", "🙂", "🙃", "😉", "😌", "😍", "😘", "😗", "😙", "😚", "😋", "😜", "😝", "😛", "🤑", "🤗", "🤓", "😎", "🤡", "🤠", "😏", "😒", "😞", "😔", "😟", "😕", "🙁", "☹️", "😣", "😖", "😫", "😩", "😤", "😠", "😡", "😶", "😐", "😑", "😯", "😦", "😧", "😮", "😲", "😵", "😳", "😱", "😨", "😰", "😢", "😥", "🤤", "😭", "😓", "😪", "😴", "🙄", "🤔", "🤥", "😬", "🤐", "🤢", "🤧", "😷", "🤒", "🤕", "😈", "👿"]); m }; }<file_sep>/CATEGORIES.md # Categories Here's a page of all the categories that Rustplacements can inject into your code. ## Alphanumeric 1. `letters-lower`: a - z 2. `letters-upper`: A - Z 3. `digits`: 0 - 9 4. `fizzbuzz`: 1 - 15 with multiples of 3 replaced with `fizz` and multiples of 5 replaced with `buzz`. ## Quotes 1. `got-quotes`: Game of Thrones quotes 2. `friends-quotes`: Friends (tv) quotes ## Random 1. `Alexa phrases`: send this to text-to-speech and let Alexa help you out. <file_sep>/CONTRIBUTING.md # Contributing Do you have a category that you'd like to add? Feel free to open a PR with your new category, or edits to an existing category. ## `exprs.rs` Add your new category to the `HASHMAP` defined in this module. The plugin wil automatically pick up the new category. You should prefer a lower case name with hyphens seperating words such as `rust-language`. ## `CATEGORIES.md` Add the new category to `CATEGORIES.md`. The description doesn't need to be in-depth, but should give the key used by `Rustplacements`, and a short description of what it replaces your text with. ## Appropriate Content Content should generally be inoffensive. The rust community prides itself on being an inclusive community that welcomes diversity across age, gender, socio-economic status, and race. The categories in this repo should reflect that. Therefore, content deemed inappropriate or offensive will not be merged into this repository. <file_sep>/README.md # Rustplacements This is a compiler plugin for the [Rust language](https://www.rust-lang.org/en-US/) that replaces all of your string literals in the source code with random text. Well, it's not really random. You can choose to replace text with items from any of the lists on [this page](https://github.com/Peternator7/rustplacements/blob/master/CATEGORIES.md) by simply adding a few attributes to your existing Rust code. ## A Brief Example Let's start with a simple example like the one below. It prints out the words in the sentence below one word at a time. ```rust const SENTENCE: [&'static str; 9] = ["The", "Quick", "Brown", "Fox", "Jumped", "Over", "the", "Lazy", "Dog"]; fn main() { for word in &SENTENCE { println!("{}", word); } } ``` The output should look like: ```txt The Quick Brown Fox Jumped Over the Lazy Dog ``` Rustplacements let's us replace all the strings at compile with other values. Let's say we want to replace all the text with emojis. Rustplacements can do that. ```rust #![feature(plugin)] #![plugin(rustplacements)] // Placing it in the module root will replace everything in the module #![Rustplacements = "emojis"] const SENTENCE: [&'static str; 9] = ["The", "Quick", "Brown", "Fox", "Jumped", "Over", "the", "Lazy", "Dog"]; fn main() { for word in &SENTENCE { println!("{}", word); } } ``` The new output will look something like this. The output is randomized so it will be re-generated everytime you compile your crate. ```text 😢 😫 🤓 😞 😠 😟 😖 😧 😬 😬 😈 😡 😟 😓 😒 😬 😝 😘 🤧 😬 😧 😡 😗 😈 😉 😫 😄 😱 😰 😃 🤡 😅 😯 🤒 😈 😈 ``` ## Using Rustplacements Compiler plugins like Rustplacements are only available on nightly rust because they require a feature flag to use. To get started, Rustplacements is available on [crates.io](https://crates.io/crates/rustplacements). To download the latest version, add the following line to the `Cargo.toml`. ``` [dependencies] rustplacements = "*" ``` To enable the compiler plugin, add the following lines on the top of your `main.rs` or `lib.rs`. ``` #![feature(plugin)] #![plugin(rustplacements)] ``` You can now use the plugin anywhere in the crate by applying the `#[Rustplacements = "one-direction"]` to any language element. You can place the element in the root with `#![Rustplacements = "got-quotes"]` and it will transform all the string literals in your module. It can also be applied to specific strings / impls / functions for more fine grained control. That's pretty much all there is to it. Check out the [categories page](https://github.com/Peternator7/rustplacements/blob/master/CATEGORIES.md) for more categories that you can use. ## Contributing Do you have a category that you'd like to add? Feel free to open a PR with your new category, or edits to an existing category. You'll need to change `exprs.rs` and the `CATEGORIES.md` file to include the new category. See the contributing page for more details. All Pull Requests are expected to be professional, inclusive of others, and generally non-offensive. We'll err on the side of more conservative if there's any debate about the appropriateness of a category. <file_sep>/Cargo.toml [package] name = "rustplacements" version = "0.1.0" authors = ["Peternator7 <<EMAIL>>"] description = "A rust compiler plugin for modifying string literals" repository = "https://github.com/Peternator7/rustplacements" keywords = ["plugin","string-literal","compiler-plugin"] category = ["development-tools::procedural-macro-helpers", "text-processing"] license = "MIT" [dependencies] lazy_static = "0.2.8" rand = "0.3.16" [lib] plugin = true
d8b3c74d663079aa29733388c7dbca7c3be71945
[ "Markdown", "Rust", "TOML" ]
6
Rust
Peternator7/rustplacements
ff1bf233b8e73cbd3fb5095e86c6b25cf450e0de
1dbb9a6ff12fa2dd3976ffdfcc96dabef4cc6f9d
refs/heads/master
<repo_name>BedrichVychodil/differ-docs<file_sep>/README.md differ-docs =========== Documentation of a Project Differ link for documentation is at Read The Docs.<file_sep>/exiftool.rst ExifTool ........ .. literalinclude:: outputs/get-exiftool.sh :language: bash .. literalinclude:: outputs/exiftool.raw Significant Properties ~~~~~~~~~~~~~~~~~~~~~~~ ========================== ================================================================================= Information Value from an example ========================== ================================================================================= datum vytvoreni File Modification Date/Time : 2011:12:01 16:21:26+01:00 velikost souboru File Size : 4.1 MB pocet barev 24bitu, 8bitu (grey scale) Bits Per Sample : 8 rozliseni Image Size : 3776x2520 pocet vrstev vzdy 1 vrstva expozice 1/125 vyvazeni bile White Balance : Auto ========================== ================================================================================= prednostne :: velikost souboru typ souboru main type software type 2.1 modified date exif tool version resolution x, y color space : Exif Image Width : 3776 Exif Image Height : 2520 image unique id Compression : JPEG (old-style) Encoding Process : Baseline DCT, Huffman coding Bits Per Sample : 8 Color Components : 3 Image Size : 3776x2520 ostatni veci vlozit do sekce exif. ExifTool Version Number : 8.60 File Name : 2_2_11-Voda-Glitch10.jpg File Modification Date/Time : 2011:12:01 16:21:26+01:00 File Type : JPEG MIME Type : image/jpeg JFIF Version : 1.01 Exif Byte Order : Little-endian (Intel, II) commentaries:: Make : Panasonic X Resolution : 180 Y Resolution : 180 Resolution Unit : inches typ algoritmu :: Y Cb Cr Positioning : Co-sited Exposure Time : 1/125 F Number : 2.8 Exif Version : 0221 exit :: Components Configuration : Y, Cb, Cr, - Compressed Bits Per Pixel : 4 <file_sep>/outputs/get-exiftool.sh #!/bin/bash exiftool '/opt/testovaci-data/2_Set ot TEST images Vlna_testovani-Vysledky_porovnani_obrazku/2_Sada_testovacich_obrazku/2_JPEG/2_2_11-Voda-Glitch10.jpg' > exiftool.raw<file_sep>/outputs/get-fits.sh #!/bin/bash /opt/fits-0.6.1/fits.sh -i '/opt/testovaci-data/ONLINE DIFFER/1TEST-CORRUPTED-1_PAINTING.JPG' > fits.raw<file_sep>/outputs/get-djvudump.sh #!/bin/bash djvudump '/opt/testovaci-data/2_Set ot TEST images Vlna_testovani-Vysledky_porovnani_obrazku/2_Sada_testovacich_obrazku/4_DJVU/4_2_11_01-Voda-Orig-HQ.djvu' > djvudump.raw<file_sep>/_build/html/_sources/jhove.txt JHOVE ..... .. literalinclude:: outputs/get-jhove.sh :language: bash .. literalinclude:: outputs/jhove.raw Significant Properties ~~~~~~~~~~~~~~~~~~~~~~~ ========================== ============================================================================================================ Information Value from an example ========================== ============================================================================================================ datum vytvoreni /jhove/repInfo/lastModified (2012-02-17T22:07:54+01:00) velikost souboru /jhove/repInfo/size (476756) pocet barev 24bitu, 8bitu (grey scale) //mix:ImageColorEncoding/mix:bitsPerSampleValue (8) rozliseni //mix:imageWidth x //mix:imageHeight (512x512) pocet vrstev expozice vyvazeni bile neco dalsiho ========================== ============================================================================================================ identifikace :: <mimeType>image/jp2</mimeType> charakterizace :: <property> <name>EnumCS</name> <values arity="Scalar" type="String"> <value>sRGB</value> </values> </property> uuid :: <property> <name>UUID</name> <values arity="Array" type="Byte"> <value>58</value> <value>13</value> <value>2</value> <value>24</value> <value>10</value> <value>-23</value> <value>65</value> <value>21</value> <value>-77</value> <value>118</value> <value>75</value> <value>-54</value> <value>65</value> <value>-50</value> <value>14</value> <value>113</value> </values> </property> z mix se daji vytahnout vsechny veci. V JHOVE jsou nejdulezitejsi identifikace. .. comments:: komentare <file_sep>/outputs/get-jhove.sh #!/bin/bash jhove -h xml '/opt/testovaci-data/TESTOVACI DATA BEDRICHJ 2012/lena_std lossless.jpf' > jhove.raw
6134a4fedc5f20704422d46b18464a483159b462
[ "Markdown", "reStructuredText", "Shell" ]
7
Markdown
BedrichVychodil/differ-docs
ee1ab4552e707aec15835f85b0ea8446cf9b383b
84366f32282f807dd68f208c037a507274ac6ec6
refs/heads/master
<file_sep>package com.example.projetandroid; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { private static final int REQUEST_CODE_SECOND_ACTIVITY = 1 ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EditText editTextCityName = findViewById(R.id.editText1MainActivity); Button buttonCity = (Button) findViewById(R.id.button1MainActivity); buttonCity.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), CityActivity.class); Bundle bundle1 = new Bundle(); bundle1.putString(CityActivity.INPUT_PARAMETER, editTextCityName.getText().toString()); intent.putExtras(bundle1); startActivityForResult(intent, REQUEST_CODE_SECOND_ACTIVITY); } }); } } <file_sep>package com.example.projetandroid.model; public class City { private String id; private String name; private int postCode; private String population; private String numDepartment; private String nameDepartment; private String numRegion; private String nameRegion; public City(String id, String name, int postCode, String population, String numDepartment, String nameDepartment, String numRegion, String nameRegion) { this.id = id; this.name = name; this.postCode = postCode; this.population = population; this.numDepartment = numDepartment; this.nameDepartment = nameDepartment; this.numRegion = numRegion; this.nameRegion = nameRegion; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPostCode() { return postCode; } public void setPostCode(int postCode) { this.postCode = postCode; } public String getPopulation() { return population; } public void setPopulation(String population) { this.population = population; } public String getNumDepartment() { return numDepartment; } public void setNumDepartment(String numDepartment) { this.numDepartment = numDepartment; } public String getNameDepartment() { return nameDepartment; } public void setNameDepartment(String nameDepartment) { this.nameDepartment = nameDepartment; } public String getNumRegion() { return numRegion; } public void setNumRegion(String numRegion) { this.numRegion = numRegion; } public String getNameRegion() { return nameRegion; } public void setNameRegion(String nameRegion) { this.nameRegion = nameRegion; } } <file_sep>package com.example.projetandroid; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.util.Log; import android.widget.ListView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.projetandroid.adapter.AdapterForCities; import com.example.projetandroid.model.City; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class CityActivity extends Activity { public static final String INPUT_PARAMETER = "input_parameter"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_city); List<City> cities = new ArrayList<>(0); RequestQueue queue = Volley.newRequestQueue(this); String input = getIntent().getExtras().getString(INPUT_PARAMETER); ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { Log.d("Debug", "Connected to internet"); String url = "https://geo.api.gouv.fr/"; String fields = "&fields=nom,code,codesPostaux,codeDepartement,departement,codeRegion,region,population"; String format = "&format=json"; String geometry = "&geometry=centre"; url += "communes?nom=" + input + fields + format + geometry; Log.d("Debug", "URL is " + url); StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("Debug", "IUT Response" + response); try { JSONArray listOfCities = new JSONArray(response); JSONObject jsonItem; City city; for (int i = 0; i < listOfCities.length(); i++) { jsonItem = listOfCities.getJSONObject(i); city = new City(jsonItem.getString("code"), jsonItem.getString("nom"), jsonItem.getJSONArray("codesPostaux").optInt(0), String.format(getString(R.string.populationLayout), jsonItem.getString("population")), jsonItem.getString("codeDepartement"), jsonItem.getJSONObject("departement").getString("nom"), jsonItem.getJSONObject("region").getString("code"), jsonItem.getJSONObject("region").getString("nom")); cities.add(city); } ListView listView = (ListView) findViewById(R.id.listView); AdapterForCities adapterForCities = new AdapterForCities(CityActivity.this, cities); listView.setAdapter(adapterForCities); } catch (JSONException e) { Log.e("Debug", "Error while parsing cities result", e); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast toast = Toast.makeText(getApplicationContext(), "Erreur de requête", Toast.LENGTH_LONG); toast.show(); } }); queue.add(stringRequest); } else { Toast toast = Toast.makeText(getApplicationContext(), "Non connecté à internet", Toast.LENGTH_LONG); toast.show(); finish(); } } }
de71f4b320ceef390b5be1e861a36f1d51ba4ccd
[ "Java" ]
3
Java
rouyc/ProjetAndroid
d04493264255874de6656043d1589ad288321b1e
3fa3a4c9e29513d2c6165bd33d03f3bfb01365bc
refs/heads/main
<repo_name>shivanisharma10/student-feedback-system-<file_sep>/kp.java import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * S * */ public class kp extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { static final long serialVersionUID = 1L; /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#HttpServlet() */ public kp() { super(); } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out=response.getWriter(); try{ String dname=request.getParameter("dname"); String tname=request.getParameter("tname"); String sub=request.getParameter("sub"); String a=request.getParameter("A"); int a1=Integer.parseInt(a); String b=request.getParameter("B"); int b1=Integer.parseInt(b); String c=request.getParameter("C"); int c2=Integer.parseInt(c); String d=request.getParameter("D"); int d2=Integer.parseInt(d); String e=request.getParameter("E"); int e2=Integer.parseInt(e); String f=request.getParameter("F"); int f1=Integer.parseInt(f); String g=request.getParameter("G"); int g1=Integer.parseInt(g); String h=request.getParameter("H"); int h1=Integer.parseInt(h); Class.forName("org.apache.derby.jdbc.ClientDriver"); Connection c1=DriverManager.getConnection("jdbc:derby://localhost:1527/root","root","root"); Statement s =c1.createStatement(); String sql=null; String sql2=null; ResultSet rs=null; int num=0; switch(a1) { case 1: sql2="select * from teacherreportA where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o1")+1; sql="update teacherreportA set o1="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportA values('"+dname+"','"+tname+"','"+sub+"',"+num+",0,0,0)"; } break; case 2: sql2="select * from teacherreportA where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o2")+1; sql="update teacherreportA set o2="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportA values('"+dname+"','"+tname+"','"+sub+"',0,"+num+",0,0)"; } break; case 3: sql2="select * from teacherreportA where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o3")+1; sql="update teacherreportA set o3="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportA values('"+dname+"','"+tname+"','"+sub+"',0,0,"+num+",0)"; } break; case 4: sql2="select * from teacherreportA where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o4")+1; sql="update teacherreportA set o4="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportA values('"+dname+"','"+tname+"','"+sub+"',0,0,0,"+num+")"; } break; } s.execute(sql); switch(b1) { case 1: sql2="select * from teacherreportB where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o1")+1; sql="update teacherreportB set o1="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportB values('"+dname+"','"+tname+"','"+sub+"',"+num+",0,0,0)"; } break; case 2: sql2="select * from teacherreportB where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o2")+1; sql="update teacherreportB set o2="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportB values('"+dname+"','"+tname+"','"+sub+"',0,"+num+",0,0)"; } break; case 3: sql2="select * from teacherreportB where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o3")+1; sql="update teacherreportB set o3="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportB values('"+dname+"','"+tname+"','"+sub+"',0,0,"+num+",0)"; } break; case 4: sql2="select * from teacherreportB where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o4")+1; sql="update teacherreportB set o4="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportB values('"+dname+"','"+tname+"','"+sub+"',0,0,0,"+num+")"; } break; } s.execute(sql); switch(c2) { case 1: sql2="select * from teacherreportC where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o1")+1; sql="update teacherreportC set o1="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportC values('"+dname+"','"+tname+"','"+sub+"',"+num+",0,0,0)"; } break; case 2: sql2="select * from teacherreportC where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o2")+1; sql="update teacherreportC set o2="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportC values('"+dname+"','"+tname+"','"+sub+"',0,"+num+",0,0)"; } break; case 3: sql2="select * from teacherreportC where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o3")+1; sql="update teacherreportC set o3="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportC values('"+dname+"','"+tname+"','"+sub+"',0,0,"+num+",0)"; } break; case 4: sql2="select * from teacherreportC where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o4")+1; sql="update teacherreportC set o4="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportC values('"+dname+"','"+tname+"','"+sub+"',0,0,0,"+num+")"; } break; } s.execute(sql); switch(d2) { case 1: sql2="select * from teacherreportD where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o1")+1; sql="update teacherreportD set o1="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportD values('"+dname+"','"+tname+"','"+sub+"',"+num+",0,0,0)"; } break; case 2: sql2="select * from teacherreportD where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o2")+1; sql="update teacherreportD set o2="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportD values('"+dname+"','"+tname+"','"+sub+"',0,"+num+",0,0)"; } break; case 3: sql2="select * from teacherreportD where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o3")+1; sql="update teacherreportD set o3="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportD values('"+dname+"','"+tname+"','"+sub+"',0,0,"+num+",0)"; } break; case 4: sql2="select * from teacherreportD where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o4")+1; sql="update teacherreportD set o4="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportD values('"+dname+"','"+tname+"','"+sub+"',0,0,0,"+num+")"; } break; } s.execute(sql); switch(e2) { case 1: sql2="select * from teacherreportE where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o1")+1; sql="update teacherreportE set o1="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportE values('"+dname+"','"+tname+"','"+sub+"',"+num+",0,0,0)"; } break; case 2: sql2="select * from teacherreportE where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o2")+1; sql="update teacherreportE set o2="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportE values('"+dname+"','"+tname+"','"+sub+"',0,"+num+",0,0)"; } break; case 3: sql2="select * from teacherreportE where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o3")+1; sql="update teacherreportE set o3="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportE values('"+dname+"','"+tname+"','"+sub+"',0,0,"+num+",0)"; } break; case 4: sql2="select * from teacherreportE where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o4")+1; sql="update teacherreportE set o4="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportE values('"+dname+"','"+tname+"','"+sub+"',0,0,0,"+num+")"; } break; } s.execute(sql); switch(f1) { case 1: sql2="select * from teacherreportF where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o1")+1; sql="update teacherreportF set o1="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportF values('"+dname+"','"+tname+"','"+sub+"',"+num+",0,0,0)"; } break; case 2: sql2="select * from teacherreportF where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o2")+1; sql="update teacherreportF set o2="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportF values('"+dname+"','"+tname+"','"+sub+"',0,"+num+",0,0)"; } break; case 3: sql2="select * from teacherreportF where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o3")+1; sql="update teacherreportF set o3="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportF values('"+dname+"','"+tname+"','"+sub+"',0,0,"+num+",0)"; } break; case 4: sql2="select * from teacherreportF where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o4")+1; sql="update teacherreportF set o4="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportF values('"+dname+"','"+tname+"','"+sub+"',0,0,0,"+num+")"; } break; } s.execute(sql); switch(g1) { case 1: sql2="select * from teacherreportG where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o1")+1; sql="update teacherreportG set o1="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportG values('"+dname+"','"+tname+"','"+sub+"',"+num+",0,0,0)"; } break; case 2: sql2="select * from teacherreportG where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o2")+1; sql="update teacherreportG set o2="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportG values('"+dname+"','"+tname+"','"+sub+"',0,"+num+",0,0)"; } break; case 3: sql2="select * from teacherreportG where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o3")+1; sql="update teacherreportG set o3="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportG values('"+dname+"','"+tname+"','"+sub+"',0,0,"+num+",0)"; } break; case 4: sql2="select * from teacherreportG where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o4")+1; sql="update teacherreportG set o4="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportG values('"+dname+"','"+tname+"','"+sub+"',0,0,0,"+num+")"; } break; } s.execute(sql); switch(h1) { case 1: sql2="select * from teacherreportH where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o1")+1; sql="update teacherreportH set o1="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportH values('"+dname+"','"+tname+"','"+sub+"',"+num+",0,0,0)"; } break; case 2: sql2="select * from teacherreportH where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o2")+1; sql="update teacherreportH set o2="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportH values('"+dname+"','"+tname+"','"+sub+"',0,"+num+",0,0)"; } break; case 3: sql2="select * from teacherreportH where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o3")+1; sql="update teacherreportH set o3="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportH values('"+dname+"','"+tname+"','"+sub+"',0,0,"+num+",0)"; } break; case 4: sql2="select * from teacherreportH where tname='"+tname+"'"; try { rs=s.executeQuery(sql2); rs.next(); num=rs.getInt("o4")+1; sql="update teacherreportH set o4="+num+" where tname='"+tname+"'"; }catch(SQLException e1) { num=1; sql="insert into teacherreportH values('"+dname+"','"+tname+"','"+sub+"',0,0,0,"+num+")"; } break; } s.execute(sql); }catch(Exception e){out.println(e);} response.sendRedirect("home.html"); } }<file_sep>/README.md # student-feedback-system- student feedback system
2089b1bc25ea61bf95db5b94b2a67aa6acbaf6ce
[ "Markdown", "Java" ]
2
Java
shivanisharma10/student-feedback-system-
c1ed960f675a6a8ccfa068b69eb5f3141ef297fb
c02754f52ad39aa76f8985f16e0c081883d24a81
refs/heads/main
<repo_name>rpycgo/table_crop<file_sep>/table_crop.py # -*- coding: utf-8 -*- """ Created on Sun Aug 1 19:28:02 2021 @author: MJH #refer: https://towardsdatascience.com/a-table-detection-cell-recognition-and-text-extraction-algorithm-to-convert-tables-to-excel-files-902edcf289ec """ import pandas as pd import numpy as np import cv2 import pytesseract import matplotlib.pyplot as plt from PIL import Image from pdf2image import convert_from_path def PILtoarray(image): return np.array(image.getdata(), np.uint).reshape(image.size[1], image.size[0], 3) def convert_pdf_to_image(file): return convert_from_path(file, poppler_path = r"C:\Program Files (x86)\poppler-21.03.0\Library\bin", dpi = 600) class TableCrop: def __init__(self, save_path): self.save_path = save_path self.table_houghlinep = '' self.table_kernel = '' self.image = '' def get_table_by_houghlinep(self, image_path): image = cv2.imread(image_path) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 150, apertureSize = 3) plt.imshow(image) lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 30, minLineLength = 300, maxLineGap = 200) for line in lines: x1, y1, x2, y2 = line[0] cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2) plt.imshow(image) self.table_houghlinep = image def get_table_by_kernel(self, image_path): image = cv2.imread(image_path, 0) self.image = image # threshold the image threshold, image_binary = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU) image_binary = 255 - image_binary plt.imshow(image_binary, cmap = 'gray') plt.show() # define a kernel length kernel_length = np.array(image).shape[1] // 50 # vertical kernel of (1 x kernel_length), whichwill detect all the vertical lines from the image vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, kernel_length)) # horizontal kernel of (kernel_length x 1), which will help to detect all the horizontal line from the image. horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_length, 1)) # kernel of (3 x 3) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2)) # morphologial operation to detect vertical lines from an image img_temp1 = cv2.erode(image_binary, vertical_kernel, iterations = 3) vertical_line_image = cv2.dilate(img_temp1, vertical_kernel, iterations = 3) # plt.imshow(vertical_line_image, cmap = 'gray') # cv2.imwrite('c:/etc/test_img/vertial_lines.jpg', vertical_line_image) img_temp2 = cv2.erode(image_binary, horizontal_kernel, iterations = 3) horizontal_line_image = cv2.dilate(img_temp2, horizontal_kernel, iterations = 3) # plt.imshow(horizontal_line_image, cmap = 'gray') # cv2.imwrite('c:/etc/test_img/horizontal_lines.jpg', horizontal_line_image) alpha = 0.5 beta = 1.0 - alpha img_final_bin = cv2.addWeighted(vertical_line_image, alpha, horizontal_line_image, beta, 0.0) img_final_bin = cv2.erode(~img_final_bin, kernel, iterations = 2) threshold, img_final_bin = cv2.threshold(img_final_bin, 122, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU) plt.imshow(img_final_bin, cmap = 'gray') # cv2.imwrite('d:/img_final_bin2.jpg', img_final_bin) self.table_kernel = img_final_bin def save_table_by_houghlinep(self, save_name): cv2.imwrite(''.join([self.save_path, save_name]), self.table_houghlinep) def save_table_by_kernel(self, save_name): cv2.imwrite(''.join([self.save_path, save_name]), self.table_kernel) def save_table_cell_by_kernel(self): contours, img2 = cv2.findContours(self.table_kernel, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) idx = 0 for c in contours[::-1]: x, y, w, h = cv2.boundingRect(c) if (w > 80 and h > 20) and (w > 3 * h): idx += 1 new_img = self.image[y: y + h, x: x + w] cv2.imwrite(''.join([self.save_path, str(idx), '.jpg']), new_img) def sort_contours(self, cnts, method = 'left-to-right'): # initialize the reverse flag and sort index reverse = False i = 0 # handle if we need to sort in reverse if method == "right-to-left" or method == "bottom-to-top": reverse = True # handle if we are sorting against the y-coordinate rather than # the x-coordinate of the bounding box if method == "top-to-bottom" or method == "bottom-to-top": i = 1 # construct the list of bounding boxes and sort them from top to # bottom boundingBoxes = [cv2.boundingRect(c) for c in cnts] (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes), key=lambda b:b[1][i], reverse=reverse)) # return the list of sorted contours and bounding boxes return (cnts, boundingBoxes) def save_table_by_kernel_to_csv(self, save_name): contours, hierarchy = cv2.findContours(self.table_kernel, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours, boundingBoxes = self.sort_contours(contours, method = 'top-to-bottom') # Creating a list of heights for all detected boxes heights = [boundingBoxes[i][3] for i in range(len(boundingBoxes))] #Get mean of heights mean = np.mean(heights) # Create list box to store all boxes in box = [] # Get position (x,y), width and height for every contour and show the contour on image for c in contours: x, y, w, h = cv2.boundingRect(c) if (w < 1000 and h > 500): image = cv2.rectangle(self.image, (x, y), (x + w, y + h), (0, 255, 0), 2) box.append([x, y, w, h]) # Creating two lists to define row and column in which cell is located row = [] column = [] j = 0 for i in range(len(box)): if ( i == 0 ): column.append(box[i]) previous=box[i] else: if ( box[i][1] <= previous[1] + mean / 2 ): column.append(box[i]) previous = box[i] if (i == len(box) - 1): row.append(column) else: row.append(column) column = [] previous = box[i] column.append(box[i]) #calculating maximum number of cells countcol = 0 for i in range(len(row)): countcol = len(row[i]) if countcol > countcol: countcol = countcol # Retrieving the center of each column center = [int(row[i][j][0]+row[i][j][2]/2) for j in range(len(row[i])) if row[0]] center=np.array(center) center.sort() # Regarding the distance to the columns center, the boxes are arranged in respective order finalboxes = [] for i in range(len(row)): lis=[] for k in range(countcol): lis.append([]) for j in range(len(row[i])): diff = abs(center - (row[i][j][0] + row[i][j][2] / 4)) minimum = min(diff) indexing = list(diff).index(minimum) lis[indexing].append(row[i][j]) finalboxes.append(lis) # from every single image-based cell/box the strings are extracted via pytesseract and stored in a list outer=[] for i in range(len(finalboxes)): for j in range(len(finalboxes[i])): inner = '' if (len(finalboxes[i][j]) == 0 ): outer.append(' ') else: for k in range(len(finalboxes[i][j])): y,x,w,h = finalboxes[i][j][k][0], finalboxes[i][j][k][1], finalboxes[i][j][k][2], finalboxes[i][j][k][3] finalimg = self.image[x:x+h, y:y+w] kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 1)) border = cv2.copyMakeBorder(finalimg,2,2,2,2, cv2.BORDER_CONSTANT,value=[255,255]) resizing = cv2.resize(border, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC) dilation = cv2.dilate(resizing, kernel,iterations=1) erosion = cv2.erode(dilation, kernel,iterations=1) out = pytesseract.image_to_string(erosion) if(len(out)==0): out = pytesseract.image_to_string(erosion, config = '--psm 3') inner = inner + ' ' + out outer.append(inner) # Creating a dataframe of the generated OCR list arr = np.array(outer) dataframe = pd.DataFrame(arr.reshape(len(row),countcol)) data = dataframe.style.set_properties(align = 'left') # Converting it in a excel-file data.to_excel(''.join([self.save_path, save_name])) if __name__ == '__main__': financial_statement_image_path = 'financial_statement.jpg' report_image_path = 'report.jpg' table_crop = TableCrop('save/') # financial statement # kernel table_crop.get_table_by_kernel(financial_statement_image_path) table_crop.save_table_by_kernel('financial_statement_kernel.jpg') table_crop.save_table_by_kernel_to_csv('financial_statement_kernel_excel.xlsx') # houghlinep table_crop.get_table_by_houghlinep(financial_statement_image_path) table_crop.save_table_by_houghlinep('financial_statement_houghlinep.jpg') # analyst_report table_crop.get_table_by_kernel(report_image_path) table_crop.save_table_by_kernel('report_kernel.jpg') # houghlinep table_crop.get_table_by_houghlinep(report_image_path) table_crop.save_table_by_houghlinep('report_houghlinep.jpg')
e96d12dcd77e7e43735e6bb2421a5eb4ee0ea845
[ "Python" ]
1
Python
rpycgo/table_crop
76cec01e7e238bacb3db0d9e73228a4e0b564ff9
f43476cfcb78fb77f1a9b3040326d8e51966e7d1
refs/heads/master
<repo_name>devangrose/space_invasion<file_sep>/js/weapons.js function fireWeapon () { if(game.time.now < weaponTimer || player.life <= 0){ return; } var weapon; if(WEAPONS[currentWeapon].name === 'Laser'){ weapon = lasers.getFirstExists(false); pewpew.play(); } else if(WEAPONS[currentWeapon].name == 'Missle'){ weapon = missles.getFirstExists(false); launch.play(); } weapon.reset(player.x + WEAPONS[currentWeapon].offset + 15, player.y + WEAPONS[currentWeapon].offset); weapon.body.velocity.x = WEAPONS[currentWeapon].velocity; weapon.damage = WEAPONS[currentWeapon].damage; weaponTimer = game.time.now + WEAPONS[currentWeapon].timer; } function switchWeapon (){ if(game.time.now < switchTimer){ return; } switchTimer = game.time.now + SWITCH_WEAPON_TIMER; console.log('switch weapon'); currentWeapon++; currentWeapon = currentWeapon % WEAPONS.length; console.log(currentWeapon); } function createGroup (group, imageName, maxNum) { group.enableBody = true; group.physicsBodyType = Phaser.Physics.ARCADE; group.createMultiple(maxNum, imageName); group.setAll('outOfBoundsKill',true); group.setAll('checkWorldBounds',true); } <file_sep>/js/enemies.js function spawnEnemy () { var enemy = enemies.getFirstExists(false); enemy.reset(GAME_WIDTH - 50, game.rnd.integerInRange(50,GAME_HEIGHT - 50)); enemy.body.velocity.x = -ENEMY_SPEED; enemy.health = ENEMY_HEALTH; } function hurtEnemy (enemy, weapon){ enemy.health -= weapon.damage; weapon.kill(); if(enemy.health <= 0){ makeExplosion(enemy); enemy.kill(); player.score += 10; scoreText.text = 'Score: ' + player.score; if(player.score % 100 == 0){ ENEMY_HEALTH += 10; } } } <file_sep>/js/globals.js var GAME_HEIGHT = 500; var GAME_WIDTH = 800; var STARTING_LIFE = 150; var DEFAULT_SPEED = 300; var ENEMY_SPEED = 200; var ENEMY_DAMAGE = 50; var ENEMY_HEALTH = 50; var BACKGROUND_SPEED = -50; var SWITCH_WEAPON_TIMER = 200; var WEAPONS = [ {name: 'Laser', velocity: 650, timer: 180, offset: 20, damage: 10}, {name: 'Missle', velocity: 400, timer: 600, offset: 20, damage: 25} ]; // Global variables var player; var enemies; var lasers, missles, boom; var cursors; var scoreText, hpText; var music, pewpew, launch, explosion; var weaponTimer = 0; var switchTimer = 0; var currentWeapon = 0; <file_sep>/js/main.js var game = new Phaser.Game(GAME_WIDTH, GAME_HEIGHT, Phaser.AUTO, 'game', { init: init, preload: preload, create: create, update: update }); function init () { } function preload () { // Initialize arcade physics game.physics.startSystem(Phaser.Physics.ARCADE); // Load images for later use game.load.image('bg','../assets/img/cool-space-background.jpg'); game.load.image('player','../assets/img/ship.png'); game.load.image('laser','../assets/img/beam.png'); game.load.image('missle','../assets/img/missile.png'); game.load.image('enemy','../assets/img/enemy.png'); game.load.image('enemy2','../assets/img/enemy2.png'); // Load animations game.load.spritesheet('smallboom','../assets/img/explosion.png', 64, 64); // Load audio files for later use game.load.audio ('music','../assets/audio/Shadelike.mp3'); game.load.audio ('pewpew','../assets/audio/laser.ogg','../assets/audio/laser.mp3'); game.load.audio ('launch','../assets/audio/Missile.mp3'); game.load.audio ('boom','../assets/audio/explosion.ogg','../assets/audio/explosion.mp3'); } function create () { // Create the background and make it scroll var background = game.add.tileSprite(0, 0, game.width, game.height, 'bg'); background.autoScroll(BACKGROUND_SPEED,0); // Set up sounds music = game.add.audio('music'); music.play(); pewpew = game.add.audio('pewpew',0.1); launch = game.add.audio('launch',0.1); boom = game.add.audio('explosion',1); // Create the player, place it in the world and give it life player = game.add.sprite(100, 250,'player'); game.physics.arcade.enable(player); player.body.collideWorldBounds = true; player.score = 0; player.life = STARTING_LIFE; // Create laser objects for shooting lasers = game.add.group(); createGroup(lasers,'laser',20); // Create missle objects for shooting missles = game.add.group(); createGroup(missles,'missle',10); // Create enemies group enemies = game.add.group(); createGroup(enemies,'enemy',50); // Create explosions explosions = game.add.group(); explosions.createMultiple(20, 'smallboom'); explosions.setAll('anchor.x',0); explosions.setAll('anchor.y',0); explosions.forEach(function(explosion){ explosion.animations.add('smallboom'); }); // Add keyboard controls cursors = game.input.keyboard.createCursorKeys(); // arrow keys game.input.keyboard.addKeyCapture([Phaser.Keyboard.SPACEBAR, Phaser.Keyboard.ENTER]); // Add Score and HP Text to the screen hpText = game.add.text(GAME_WIDTH - 150, 20,'HP: ' + player.life.toString(),{fill: '#fff'}); scoreText = game.add.text(GAME_WIDTH - 150, GAME_HEIGHT - 50, 'Score: ' + player.score.toString(), {fill: '#fff'}); // Create enemies in a loop game.time.events.loop(Phaser.Timer.SECOND * 2, spawnEnemy); } function update () { player.body.velocity.set(0); if (cursors.left.isDown && cursors.right.isDown) { player.body.velocity.x = 0; } else if(cursors.left.isDown) { player.body.velocity.x = -DEFAULT_SPEED; } else if (cursors.right.isDown) { player.body.velocity.x = DEFAULT_SPEED; } if (cursors.up.isDown) { player.body.velocity.y = -DEFAULT_SPEED; } else if (cursors.down.isDown) { player.body.velocity.y = DEFAULT_SPEED; } if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)){ // Fire the weapon fireWeapon(); } if (game.input.keyboard.isDown(Phaser.Keyboard.ENTER)) { switchWeapon(); } // Define my desired collisions game.physics.arcade.overlap(player, enemies, hurtPlayer); game.physics.arcade.overlap(enemies, lasers, hurtEnemy); game.physics.arcade.overlap(enemies, missles, hurtEnemy); } function hurtPlayer (player, enemy) { boom.play(); makeExplosion(player); // Logic enemy.kill(); player.life -= ENEMY_DAMAGE; hpText.text ='HP: ' + player.life.toString(); if(player.life <= 0){ player.kill(); gameOver(); } if(player.life <= 50){ player.tint = '0xff0000'; } } function makeExplosion (token) { var explosion = explosions.getFirstExists(false); explosion.reset(token.body.x,token.body.y); explosion.play('smallboom', 50, false, true); } function gameOver (){ console.log('game over'); music.pause(); swal({ title: 'You suck!', text: 'Thanks for playing', type: 'warning', showCancelButton: false, confirmButtonText: 'Cool', closeOnConfirm: true }); }
f444fff89f5b50473e0d1c914d6b0203aa7e3e7c
[ "JavaScript" ]
4
JavaScript
devangrose/space_invasion
2ae77e937dbdfa426c304647d85ed2c230ef0dd8
babb7c2c5b58a3ddae9ad1c590b6448a1d6bbc95
refs/heads/master
<repo_name>zollipaul/fullstack-boilerplate-node-js<file_sep>/mobile/App/Config/AppConfig.js // Simple React Native specific changes export default { // font scaling override - RN default is on allowTextFontScaling: true, server: "https://zollipaul-battleships.herokuapp.com/api/", // server: "https://localhost:8443/api/" // server: "https://192.168.1.11.nip.io:8443/api/" }; <file_sep>/mobile/App/Sagas/StartupSagas.js import { put, call } from "redux-saga/effects"; import { getPlacingShipsGridY } from "./PlacingShipsGridPositionSagas"; import GamesActions from "../Redux/GamesRedux"; import ShipsActions from "../Redux/ShipsRedux"; import SalvoActions from "../Redux/SalvoRedux"; import GameViewActions from "../Redux/GameViewRedux"; import TokenActions from "../Redux/TokenRedux"; import { updateGeoLocation } from "./GeolocationSagas"; // // exported to make available for tests // export const selectAvatar = GithubSelectors.selectAvatar // process STARTUP actions export function* startup(action) { yield call(getPlacingShipsGridY); yield put(TokenActions.setTokenFromStore()); yield put(GameViewActions.resetGameView()); yield put(ShipsActions.resetAllShips()); yield put(SalvoActions.resetAllSalvoes()); console.log("startup"); }
0ad94e8e1ddb616c63bfbd5ba76046f3e7f95846
[ "JavaScript" ]
2
JavaScript
zollipaul/fullstack-boilerplate-node-js
4a81d6b66498dd8fc4a0a35cfbfc2fb1aad68730
9bb98376e8c21c17fd0a821fe7542a1ae0c87e7b
refs/heads/master
<file_sep> // restart var restart = document.querySelector('#b'); // all squares var squares = document.querySelectorAll("td"); //clear blocks function clearBlocks() { // body... for (var i = 0; i<squares.length; i++) { squares[i].textContent = ''; } } // after the function creation run by clicking the restart button //so there event is that restart.addEventListener('click',clearBlocks) // Create a function that will check the square marker function maker(){ if(this.textContent == '') { this.textContent = 'X'; } else if(this.textContent == 'X') { this.textContent = 'O'; } else{ this.textContent = ''; } } // Use a for loop to add Event listeners to all the squares for (var i = 0; i < squares.length; i++) { squares[i].addEventListener('click', maker); }
b7dcce7af70c75d482e07f3978195916e4c46575
[ "JavaScript" ]
1
JavaScript
Sem31/Tic-Tac-Toe-game
840e02281f59f320133de4b64e244d3ca828cc11
517056d1565f4d92725cca56f0dabcab8ac26fbd
refs/heads/master
<repo_name>meyer744/oscars-app<file_sep>/src/components/actressContainer.js import React from 'react'; import {ActressList} from '../data/actress'; import ActressSingle from './actress-single'; import Actress from './actress'; import { Route} from 'react-router-dom'; const ActressContainer = (props) => { let actressUrl = ActressList.map((actress,i) => { return ( <Route key={i} path={`/actress/${actress.url}`} render={() => <ActressSingle name={actress.name} image={actress.profile_img} details={actress.description}/>} /> ); }); return ( <React.Fragment> <Route exact path="/actress" render={() => <Actress title="Best Actresses"/>} /> {actressUrl} </React.Fragment> ); } export default ActressContainer;<file_sep>/src/components/home.js import React from 'react'; import { Link } from 'react-router-dom'; const Home = (props) => ( <div className="main-content"> <div className="container"> <h2>{props.title}</h2> <div className="home-image"></div> <div className="thumbnail-container"> <h3 className="thumbnail-heading">Best Actors</h3> <Link to="/actors"><div className="home-thumbnail-1"></div></Link></div> <div className="thumbnail-container"> <h3 className="thumbnail-heading">Best Actresses</h3> <Link to="/actress"><div className="home-thumbnail-2"></div></Link></div> <div className="thumbnail-container"> <h3 className="thumbnail-heading">Best Films</h3> <Link to="/films"><div className="home-thumbnail-3"></div></Link></div> </div> </div> ); export default Home;
919ab906867b8c9e15a55e518a638a05bdc42ab0
[ "JavaScript" ]
2
JavaScript
meyer744/oscars-app
ffc886d1f484490fd1b6d122d220a8ffe91c52cb
42b937493d7662b36eabad82929686889d252043
refs/heads/master
<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/04 20:33:40 by curquiza #+# #+# */ /* Updated: 2016/08/06 22:47:56 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdio.h> int ft_recursive_factorial(int nb); int main(void) { printf("%d\n", ft_recursive_factorial(0)); printf("%d\n", ft_recursive_factorial(1)); printf("%d\n", ft_recursive_factorial(4)); printf("%d\n", ft_recursive_factorial(8)); printf("%d\n", ft_recursive_factorial(13)); printf("%d\n", ft_recursive_factorial(1222)); printf("%d\n", ft_recursive_factorial(-12)); printf("%d\n", ft_recursive_factorial(-1114552)); return (0); } <file_sep>ldapsearch -QLLL uid="z*" cn | grep cn | cut -c5- | sort -frd <file_sep>CREATE TABLE ft_table ( id INT NOT NULL AUTO_INCREMENT, login varchar(8) DEFAULT 'toto' NOT NULL, groupe enum('staff', 'student', 'other') NOT NULL, date_de_creation date NOT NULL, PRIMARY KEY(id) ); <file_sep><?PHP function ft_is_sort($tab) { $tab_sort = $tab; $tab_rsort = $tab; sort($tab_sort); rsort($tab_rsort); if ($tab == $tab_sort) return (TRUE); if ($tab == $tab_rsort) return (TRUE); return (FALSE); } ?> <file_sep> #ifndef NASTYFIVE_HPP #define NASTYFIVE_HPP #include "GameEntity.hpp" class NastyFive: public GameEntity{ private: NastyFive(void); NastyFive &operator = (NastyFive const &Cc); NastyFive(NastyFive const &Cc); public: NastyFive(std::string shape, int px, int py, int dx, int dy, GameEntity *next); ~NastyFive(void); virtual bool updatePosition(int winX, int winY); }; #endif <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_list_push_params.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/19 12:38:51 by curquiza #+# #+# */ /* Updated: 2016/08/19 13:46:38 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_list.h" void ft_list_push_front(t_list **begin_list, void *data) { t_list *new_list; if (*begin_list == 0) *begin_list = ft_create_elem(data); else { new_list = ft_create_elem(data); new_list->next = *begin_list; *begin_list = new_list; } } t_list *ft_list_push_params(int ac, char **av) { int i; t_list *begin_list; begin_list = ft_create_elem(av[0]); i = 1; while (i < ac) { ft_list_push_front(&begin_list, av[i]); i++; } return (begin_list); } <file_sep>SELECT count(`date`) as 'films' FROM historique_membre WHERE (date BETWEEN '2006-10-20' AND '2007-07-27') OR (MONTH(date) = '12' AND DAY(date) = 24); <file_sep>#include <stdio.h> #include <stdlib.h> int ft_is_sort(int *tab, int length, int (*f)(int, int)); int ft_test(int a, int b) { if (a > b) return (1); else if (a < b) return (-1); else return (0); } int main(void) { //int tab[6] = {100, 20, 4, 4, -2, -201}; int tab2[6] = {-4, -4, -4, -4, -4, -4}; int length; length = 6; printf("%d\n", ft_is_sort(tab2, length, &ft_test)); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* colle_2.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/20 15:17:30 by curquiza #+# #+# */ /* Updated: 2016/08/21 11:52:25 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef COLLE_2_H # define COLLE_2_H typedef struct s_colle t_colle; struct s_colle { char up_left; char up_right; char b_left; char b_right; char col; char row; int nb_col; int nb_row; }; # define SIZE_BUF 100000000 # define SIZE 10 char *ft_print_line(char char1, char char2, char char3, int x); void ft_colle(int x, int y, char *str, t_colle colle); void ft_calc_row_col(t_colle *colle, char *buffer); char **ft_complete_all_colles(int x, int y); void ft_find_colle(char *buff, char **str, int x, int y); #endif <file_sep>#include "PresidentialPardonForm.hpp" PresidentialPardonForm::PresidentialPardonForm( void ) : Form::Form("President", 25, 5), _target("home") { std::cout << "PresidentialPardonForm CONSTRUCTOR" << std::endl; return ; } PresidentialPardonForm::PresidentialPardonForm( std::string const target ) : Form::Form("President", 25, 5), _target(target) { std::cout << "PresidentialPardonForm CONSTRUCTOR" << std::endl; return ; } PresidentialPardonForm::PresidentialPardonForm( PresidentialPardonForm const & ) {} PresidentialPardonForm::~PresidentialPardonForm( void ) { std::cout << "PresidentialPardonForm DESTRUCTOR" << std::endl; return ; } void PresidentialPardonForm::executeChildForm() const { std::cout << _target << " has been pardoned by <NAME>." << std::endl; return ; } std::string PresidentialPardonForm::getTarget() { return _target; } /* OVERLOAD */ PresidentialPardonForm & PresidentialPardonForm::operator=( PresidentialPardonForm const & ) { return *this ; }<file_sep>#ifndef SPAN_HPP # define SPAN_HPP # include <iostream> # include <vector> class Span { private: unsigned int _N; std::vector<int> _vect; /* unused */ Span( void ); Span( Span const & ); Span & operator=( Span const & ); public: Span( unsigned int n ); ~Span( void ); std::vector<int> & getVect(); void addNumber(int num); void addVector(std::vector<int> & v); int shortestSpan(); int longestSpan(); }; #endif<file_sep><?php $tab = $_GET; foreach ($tab as $key => $value) { echo $key.": ".$value; echo "<br>"; } ?> <file_sep><?php Class Color { public $red = 0; public $green = 0; public $blue = 0; static $verbose = FALSE; function __construct(array $tab) { if (isset($tab['rgb'])) { $this->red = intval(($tab['rgb'] >> 16) & 0xFF); $this->green = intval(($tab['rgb'] >> 8) & 0xFF); $this->blue = intval($tab['rgb'] & 0xFF); } else { if (isset($tab['red'])) $this->red = intval($tab['red']); else $this->red = 0; if (isset($tab['green'])) $this->green = intval($tab['green']); else $this->green = 0; if (isset($tab['blue'])) $this->blue = intval($tab['blue']); else $this->blue = 0; } if (self::$verbose == TRUE) print("Color( red: ".$this->red.", green: ".$this->green.", blue: ".$this->blue." ) constructed.".PHP_EOL); } function __toString() { return ("Color( red: ".$this->red.", green: ".$this->green.", blue: ".$this->blue." )"); } static function doc() { $file = file_get_contents("Color.doc.txt"); return ($file); } function __clone() { return ; } function add($col) { $instance = clone $col; $instance->red = $col->red + $this->red; $instance->green = $col->green + $this->green; $instance->blue = $col->blue + $this->blue; return ($instance); } function sub($col) { $instance = clone $col; $instance->red = $this->red - $col->red; $instance->green = $this->green - $col->green; $instance->blue = $this->blue - $col->blue; return ($instance); } function mult($fact) { $instance = new Color(array('rgb' => 0)); $instance->red = $this->red * $fact; $instance->green = $this->green * $fact; $instance->blue = $this->blue * $fact; return ($instance); } function __destruct() { if (self::$verbose == TRUE) print("Color( red: ".$this->red.", green: ".$this->green.", blue: ".$this->blue." ) destructed.".PHP_EOL); } } ?> <file_sep>#include <stdio.h> #include <string.h> char *ft_strstr(char *str, char *to_find); int main(void) { char str1[] = "elsaetclem"; char str2[] = "\0"; char str3[] = "elsaetclem"; char str4[] = "\0"; printf("%s %s\n", str1, str2); printf("%s \n\n", ft_strstr(str1, str2)); printf("%s %s\n", str3, str4); printf("%s \n", strstr(str3, str4)); return (0); } <file_sep>#include "phonebook.hpp" int do_command(std::string command, Contact *all_contacts) { static int add_count = 0; (void)all_contacts; if ("ADD" == command) { if (add_count < 8 ) { add_contact(all_contacts, add_count); add_count += 1; } else std::cout << "Error : already 8 contacts added." << std::endl; return 0; } else if ("SEARCH" == command) { if (add_count == 0) std::cout << "Error : no contact yet." << std::endl; else { display_all_contacts(all_contacts, add_count); search_contact(all_contacts, add_count); } return 0; } else if ("EXIT" == command) { std::cout << "Exiting..." << std::endl; return 1; } std::cout << "Error : invalid command." << std::endl; return 0; } int main(void) { std::string line; Contact all_contacts[8]; std::cout << "--- AWESOME PHONEBOOK ---" << std::endl; std::cout << std::endl << "Your command (ADD/SEARCH/EXIT) : "; while (std::getline(std::cin, line)) { if (do_command(line, all_contacts) == 1) break; std::cout << std::endl << "Your command (ADD/SEARCH/EXIT) : "; } return 0; }<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_comb.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/03 22:36:25 by curquiza #+# #+# */ /* Updated: 2016/08/04 11:26:40 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ int ft_putchar(char c); void ft_print_delimiter(void) { ft_putchar(','); ft_putchar(' '); } void ft_print_3_numbers(int number1, int number2, int number3) { ft_putchar(number1); ft_putchar(number2); ft_putchar(number3); } void ft_print_comb(void) { char number1; char number2; char number3; number1 = '0'; number2 = number1 + 1; number3 = number2 + 1; while (number1 < '7') { while (number2 <= '8') { while (number3 <= '9') { ft_print_3_numbers(number1, number2, number3); ft_print_delimiter(); number3++; } number2++; number3 = number2 + 1; } number1++; number2 = number1 + 1; number3 = number2 + 1; } ft_print_3_numbers(number1, number2, number3); } <file_sep>#include "ScavTrap.hpp" ScavTrap::ScavTrap( void ) : _hitPoints(100), _MaxHitPoints(100), _energyPoints(50), _MaxEnergyPoints(50), _level(1), _name("Boby"), _meleeAttackDamage(20), _rangedAttackDamage(15), _armorDamageReducton(3) { srand (time(NULL)); this->initChallenges(); std::cout << "SC4V-TP " << this->_name << " is born 👾" << std::endl; return ; } ScavTrap::ScavTrap( std::string const & name ) : _hitPoints(100), _MaxHitPoints(100), _energyPoints(50), _MaxEnergyPoints(50), _level(1), _name(name), _meleeAttackDamage(20), _rangedAttackDamage(15), _armorDamageReducton(3) { srand (time(NULL)); this->initChallenges(); std::cout << "SC4V-TP " << this->_name << " is born 👾" << std::endl; return ; } ScavTrap::ScavTrap( ScavTrap const & src ) { srand (time(NULL)); *this = src; std::cout << "SC4V-TP " << this->_name << " is born 👾" << std::endl; return ; } ScavTrap::~ScavTrap( void ) { std::cout << "SC4V-TP " << this->_name << " is dead ☠️" << std::endl; return ; } std::string ScavTrap::getName ( void ) const { return this->_name; } ScavTrap & ScavTrap::operator=( ScavTrap const & rhs ) { if ( this != &rhs ) { this->_hitPoints = rhs._hitPoints; this->_MaxHitPoints = rhs._MaxHitPoints; this->_energyPoints = rhs._energyPoints; this->_MaxEnergyPoints = rhs._MaxEnergyPoints; this->_level = rhs._level; this->_name = rhs._name; this->_meleeAttackDamage = rhs._meleeAttackDamage; this->_rangedAttackDamage = rhs._rangedAttackDamage; this->_armorDamageReducton = rhs._armorDamageReducton; this->_challenges[0] = rhs._challenges[0]; this->_challenges[1] = rhs._challenges[1]; this->_challenges[2] = rhs._challenges[2]; this->_challenges[3] = rhs._challenges[3]; this->_challenges[4] = rhs._challenges[4]; } return *this ; } void ScavTrap::initChallenges ( void ) { this->_challenges[0] = &ScavTrap::yugiohDuel; this->_challenges[1] = &ScavTrap::concomberCat; this->_challenges[2] = &ScavTrap::PHPCleanCode; this->_challenges[3] = &ScavTrap::marioKart; this->_challenges[4] = &ScavTrap::rattataChallenge; return ; } void ScavTrap::rangedAttack( std::string const & target ) const { std::cout << "SC4V-TP " << this->_name << " attacks " << target << " at range, causing " << this->_rangedAttackDamage << " points of damage !" << std::endl; return ; } void ScavTrap::meleeAttack( std::string const & target ) const { std::cout << "SC4V-TP " << this->_name << " attacks " << target << " at melee, causing " << this->_meleeAttackDamage << " points of damage !" << std::endl; return ; } void ScavTrap::takeDamage( unsigned int amount ) { std::cout << "SC4V-TP " << this->_name << " takes " << amount - this->_armorDamageReducton << " points of damages !" << std::endl; if (amount - this->_armorDamageReducton < this->_hitPoints) this->_hitPoints -= amount - this->_armorDamageReducton; else this->_hitPoints = 0; std::cout << "SC4V-TP " << this->_name << " hit points : " << this->_hitPoints << "/" << this->_MaxHitPoints << std::endl; return ; } void ScavTrap::beRepaired( unsigned int amount ) { std::cout << "SC4V-TP " << this->_name << " gains " << amount << " hit points !" << std::endl; if (amount + this->_hitPoints <= this->_MaxHitPoints) this->_hitPoints += amount; else this->_hitPoints = this->_MaxHitPoints; std::cout << "SC4V-TP " << this->_name << " hit points : " << this->_hitPoints << "/" << this->_MaxHitPoints << std::endl; return ; } void ScavTrap::yugiohDuel( std::string const & target ) { std::cout << "FR4G-TP " << this->_name << " challenges " << target << " to a Yu-Gi-Oh duel !!!" <<std::endl; std::cout << "It's time to dddddddddddddddddduel !!!!" << std::endl; return ; } void ScavTrap::concomberCat( std::string const & target ) { std::cout << "FR4G-TP " << this->_name << " challenges " << target << " to scare a cat with a concomber !!!" <<std::endl; std::cout << "Miiiew !!! 😿" << std::endl; return ; } void ScavTrap::PHPCleanCode( std::string const & target ) { std::cout << "FR4G-TP " << this->_name << " challenges " << target << " to write a clean code in PHP !!!" <<std::endl; std::cout << target << " gives up." << std::endl; return ; } void ScavTrap::marioKart( std::string const & target ) { std::cout << "FR4G-TP " << this->_name << " challenges " << target << " to Mario Kart with Peach Princess !!!" <<std::endl; std::cout << "Mariiiioo 😍" << std::endl; return ; } void ScavTrap::rattataChallenge( std::string const & target ) { std::cout << "FR4G-TP " << this->_name << " challenges " << target << " to finish Pokemon Silver with one Rattata !!!" <<std::endl; std::cout << target << " would rather play to Pokemon Gold 🤓" << std::endl; return ; } void ScavTrap::challengeNewcomer( std::string const & target ) { int r = rand() % 5; std::cout << "FR4G-TP " << this->_name << " is thinking about a new challenge... 🤔" << std::endl; (this->*_challenges[r])(target); return ; }<file_sep>#include <stdio.h> #include <string.h> int ft_str_is_uppercase(char *str); int main(void) { char str1[] = " DHDH DHDi"; printf("%s \n", str1); printf("%d \n", ft_str_is_uppercase(str1)); return (0); } <file_sep>#!/usr/bin/php <?PHP function ft_split($str) { $tab_vide = array(""); $tab = explode(" ", $str); $tab = array_diff($tab, $tab_vide); $tab = array_values($tab); return ($tab); } if ($argc == 2) { $split = ft_split($argv[1]); $str = implode(" ", $split); if ($str != NULL) echo $str."\n"; } ?> <file_sep>#include <stdio.h> void ft_sort_wordtab(char **tab); char **ft_split_whitespaces(char *str); void ft_print_words_tables(char **tab); int main(int argc, char **argv) { char **tab; if (argc != 2) return (0); tab = ft_split_whitespaces(argv[1]); ft_sort_wordtab(tab); ft_print_words_tables(tab); return (0); } <file_sep>SOURCES = app.ml OCAMLMAKEFILE = OCamlMakefile include $(OCAMLMAKEFILE) <file_sep>#include "ShrubberyCreationForm.hpp" ShrubberyCreationForm::ShrubberyCreationForm( void ) : Form::Form("Shrebbery", 145, 137), _target("home") { std::cout << "ShrubberyCreationForm CONSTRUCTOR" << std::endl; return ; } ShrubberyCreationForm::ShrubberyCreationForm( std::string const target ) : Form::Form("Shrebbery", 145, 137), _target(target) { std::cout << "ShrubberyCreationForm CONSTRUCTOR" << std::endl; return ; } ShrubberyCreationForm::ShrubberyCreationForm( ShrubberyCreationForm const & ) {} ShrubberyCreationForm::~ShrubberyCreationForm( void ) { std::cout << "ShrubberyCreationForm DESTRUCTOR" << std::endl; return ; } void ShrubberyCreationForm::executeChildForm() const { std::ofstream ofs(_target + "_shrubbery"); if (!ofs.is_open()) throw std::ios_base::failure("Error when opening output."); ofs << TREE1 << std::endl; ofs << TREE2 << std::endl; ofs << TREE3 << std::endl; ofs << TREE4 << std::endl; ofs << TREE5 << std::endl; ofs << TREE6 << std::endl; ofs << TREE7 << std::endl; ofs.close(); return ; } std::string ShrubberyCreationForm::getTarget() { return _target; } /* OVERLOAD */ ShrubberyCreationForm & ShrubberyCreationForm::operator=( ShrubberyCreationForm const & ) { return *this ; }<file_sep>rm -rf libft.a rm -rf main.c gcc -Wall -Wextra -Werror -c *c ar rc libft.a *.o ranlib libft.a rm -rf *o rm -rf a.out <file_sep>#include "FragTrap.hpp" FragTrap::FragTrap( void ) : ClapTrap::ClapTrap() { srand (time(NULL)); this->initSpecialAttacks(); std::cout << "FR4G-TP " << this->_name << " is born 🤖" << std::endl; return ; } FragTrap::FragTrap( std::string const & name ) : ClapTrap::ClapTrap(100, 100, 100, 100, 1, name, 30, 20, 5) { srand (time(NULL)); this->initSpecialAttacks(); std::cout << "FR4G-TP " << this->_name << " is born 🤖" << std::endl; return ; } FragTrap::FragTrap( FragTrap const & src ) : ClapTrap::ClapTrap( src ) { srand (time(NULL)); *this = src; std::cout << "FR4G-TP " << this->_name << " is born 🤖" << std::endl; return ; } FragTrap::~FragTrap( void ) { std::cout << "FR4G-TP " << this->_name << " is dead ☠️" << std::endl; return ; } FragTrap & FragTrap::operator=( FragTrap const & rhs ) { if ( this != &rhs ) { this->_hitPoints = rhs._hitPoints; this->_MaxHitPoints = rhs._MaxHitPoints; this->_energyPoints = rhs._energyPoints; this->_MaxEnergyPoints = rhs._MaxEnergyPoints; this->_level = rhs._level; this->_name = rhs._name; this->_meleeAttackDamage = rhs._meleeAttackDamage; this->_rangedAttackDamage = rhs._rangedAttackDamage; this->_armorDamageReducton = rhs._armorDamageReducton; this->_specialAttacks[0] = rhs._specialAttacks[0]; this->_specialAttacks[1] = rhs._specialAttacks[1]; this->_specialAttacks[2] = rhs._specialAttacks[2]; this->_specialAttacks[3] = rhs._specialAttacks[3]; this->_specialAttacks[4] = rhs._specialAttacks[4]; } return *this ; } // SPECIAL ATTACKS void FragTrap::initSpecialAttacks ( void ) { this->_specialAttacks[0] = &FragTrap::trempette; this->_specialAttacks[1] = &FragTrap::frenchBaguette; this->_specialAttacks[2] = &FragTrap::expelliarmus; this->_specialAttacks[3] = &FragTrap::turtleShell; this->_specialAttacks[4] = &FragTrap::kamehameha; return ; } void FragTrap::trempette( std::string const & target ) { std::cout << "FR4G-TP " << this->_name << " attacks " << target << " with its special attack Trempette !!!" <<std::endl; std::cout << "But nothing happened..." << std::endl; return ; } void FragTrap::frenchBaguette( std::string const & target ) { std::cout << "FR4G-TP " << this->_name << " attacks " << target << " with its special attack French Baguette !!!" <<std::endl; std::cout << target << " is really hungry now..." << std::endl; return ; } void FragTrap::expelliarmus( std::string const & target ) { std::cout << "FR4G-TP " << this->_name << " attacks " << target << " with its special attack Expelliarmus !!!" <<std::endl; std::cout << target << " does not care because " << target << " does not have any wand !" << std::endl; return ; } void FragTrap::turtleShell( std::string const & target ) { std::cout << "FR4G-TP " << this->_name << " attacks " << target << " with its special attack Turtle Shell !!!" <<std::endl; std::cout << target << " takes some damages !" << std::endl; return ; } void FragTrap::kamehameha( std::string const & target ) { std::cout << "FR4G-TP " << this->_name << " attacks " << target << " with its special attack KAMEHAMEHA !!!" <<std::endl; std::cout << target << " takes a lot of damages !" << std::endl; return ; } void FragTrap::vaulthunter_dot_exe( std::string const & target ) { int r = rand() % 5; std::cout << "FR4G-TP " << this->_name << " is trying to invoke its special attack..." << std::endl; if (this->_energyPoints < 25) { std::cout << "Impossible !!! FR4G-TP " << this->_name << " does not have enough energy points !" << std::endl; return ; } (this->*_specialAttacks[r])(target); this->_energyPoints -= 25; return ; } <file_sep># Nom de l'executable NAME = gardening # Sources SOURCES = gardening.ml OBJS = $(SOURCES:.ml=.cmo) OPTOBJS = $(SOURCES:.ml=.cmx) TMP = $(OBJS) $(OPTOBJS) $(SOURCES:.ml=.cmi) $(SOURCES:.ml=.o) # Compilateurs CAMLC = ocamlc CAMLOPT = ocamlopt CAMLDEP = ocamldep # Libs LIBS = $(WITHGRAPHICS) WITHGRAPHICS = graphics.cma -cclib -lGraphics ### RULES ###################################################################### all: depend $(NAME) $(NAME): opt byt ln -s $(NAME).byt $(NAME) byt: $(NAME).byt opt: $(NAME).opt $(NAME).byt: $(OBJS) $(CAMLC) -o $@ $(LIBS) $^ $(NAME).opt: $(OPTOBJS) $(CAMLOPT) -o $@ $(LIBS:.cma=.cmxa) $^ # Compilation %.cmo: %.ml $(CAMLC) $(CFLAGS) -c $< -o $@ %.cmi: %.ml $(CAMLC) $(CFLAGS) -c $< -o $@ %.cmx: %.ml $(CAMLOPT) $(CFLAGS) -c $< -o $@ # Clean clean: rm -f $(TMP) fclean: clean rm -f $(NAME) rm -f $(NAME).opt rm -f $(NAME).byt depend: .depend $(CAMLDEP) $(SOURCES) > .depend re: fclean all include .depend <file_sep>grep '<NAME>' $1 <file_sep>#include "ft_list.h" void ft_putstr(char *str); int ft_putchar(char c); void ft_list_push_back(t_list **begin_list, void *data); void ft_printlist(t_list *list) { while (list != 0) { ft_putstr(list->data); ft_putchar('\n'); list = list->next; } } int main(void) { t_list *list; list = 0; list = ft_create_elem("TEST"); ft_list_push_front(&list, "DEBUT"); ft_list_push_back(&list, "FIN"); ft_printlist(list); return (0); } <file_sep>#include <stdio.h> unsigned int ft_active_bits(int value); int main(void) { printf("%d\n", ft_active_bits(2)); printf("%d\n", ft_active_bits(3)); printf("%d\n", ft_active_bits(4)); printf("%d\n", ft_active_bits(12)); return (0); } <file_sep>#ifndef HUMANB_HPP # define HUMANB_HPP #include "Weapon.hpp" class HumanB { public: HumanB( std::string name ); ~HumanB(); void attack( void ) const; void setWeapon( Weapon & weapon ); private: std::string _name; Weapon * _weapon; }; #endif<file_sep>SELECT f.titre as 'Titre', f.resum as 'Resume', f.annee_prod FROM film as f, genre as g WHERE f.id_genre = g.id_genre AND g.nom = 'erotic' ORDER BY annee_prod DESC; <file_sep>#ifndef ARRAY_TPP # define ARRAY_TPP # include <iostream> template <typename T> class Array { private: unsigned int _n; T * _tab; public: Array<T>( void ) : _n(0), _tab(NULL) { std::cout << "Constructor (default)" << std::endl; return; } Array<T>( unsigned int n ) : _n(n), _tab(new T[n]) { std::cout << "Constructor (parametric)" << std::endl; return ; } Array<T>( Array<T> const & src ) : _tab(NULL) { std::cout << "Constructor (copy)" << std::endl; *this = src; return ; } ~Array<T>( void ) { delete [] _tab; std::cout << "Destructor" << std::endl; return ; } unsigned int size() const { return _n; } Array<T> & operator=( Array<T> const & rhs ) { if ( this != &rhs ) { delete [] _tab; _n = rhs._n; _tab = new T[_n]; T * tmp = rhs._tab; for (unsigned int i = 0; i < _n; i++) { _tab[i] = tmp[i]; } } return *this ; } T & operator[](unsigned int pos) { if (pos >= _n) throw std::out_of_range ("invalid access to this part of the array."); return _tab[pos]; } }; #endif<file_sep>#include "Base.hpp" Base * generate(void) { int r = rand() % 3; if (r == 0) return new A; else if (r == 1) return new B; return new C; } void identify_from_pointer( Base * p ) { A * a = dynamic_cast<A *>(p); B * b = dynamic_cast<B *>(p); C * c = dynamic_cast<C *>(p); if (a) std::cout << "A" << std::endl; else if (b) std::cout << "B" << std::endl; else if (c) std::cout << "C" << std::endl; return ; } void identify_from_reference( Base & p ) { try { A & a = dynamic_cast<A &>(p); (void)a; std::cout << "A" << std::endl; } catch (std::bad_cast & e) {} try { B & b = dynamic_cast<B &>(p); (void)b; std::cout << "B" << std::endl; } catch (std::bad_cast & e) {} try { C & c = dynamic_cast<C &>(p); (void)c; std::cout << "C" << std::endl; } catch (std::bad_cast & e) {} } int main(void) { srand (time(NULL)); Base * base = generate(); identify_from_pointer(base); identify_from_reference(*base); return 0; }<file_sep>SOURCES = atom.ml \ molecule.ml \ alkane.ml \ reaction.ml \ main.ml OCAMLMAKEFILE = OCamlMakefile include $(OCAMLMAKEFILE) <file_sep><?PHP function ft_split($str) { $tab_vide = array(""); $tab = explode(" ", $str); $tab = array_diff($tab, $tab_vide); $tab = array_values($tab); sort($tab); return ($tab); } ?> <file_sep># Nom de l'executable NAME = ft_graphics # Sources SOURCES = ft_graphics.ml OBJS = $(SOURCES:.ml=.cmo) OPTOBJS = $(SOURCES:.ml=.cmx) TMP = $(OBJS) $(OPTOBJS) $(SOURCES:.ml=.cmi) $(SOURCES:.ml=.o) # Compilateurs CAMLC = ocamlc CAMLOPT = ocamlopt CAMLDEP = ocamldep # Libs LIBS = $(WITHGRAPHICS) WITHGRAPHICS = graphics.cma -cclib -lGraphics ### RULES ###################################################################### all: depend $(NAME) $(NAME): opt byt ln -s $(NAME).byt $(NAME) byt: $(NAME).byt opt: $(NAME).opt $(NAME).byt: $(OBJS) $(CAMLC) -o $@ $(LIBS) $^ $(NAME).opt: $(OPTOBJS) $(CAMLOPT) -o $@ $(LIBS:.cma=.cmxa) $^ # Compilation #.SUFFIXES: #.SUFFIXES: .ml .mli .cmo .cmi .cmx # #.ml.cmo: # $(CAMLC) -c $< # #.mli.cmi: # $(CAMLC) -c $< # #.ml.cmx: # $(CAMLOPT) -c $< %.cmo: %.ml $(CAMLC) $(CFLAGS) -c $< -o $@ %.cmi: %.ml $(CAMLC) $(CFLAGS) -c $< -o $@ %.cmx: %.ml $(CAMLOPT) $(CFLAGS) -c $< -o $@ # Clean clean: rm -f $(TMP) fclean: clean rm -f $(NAME) rm -f $(NAME).opt rm -f $(NAME).byt depend: .depend $(CAMLDEP) $(SOURCES) > .depend re: fclean all include .depend <file_sep>#include "span.hpp" void displayInt(int n) { std::cout << " " << n; } template <typename T> void displayIntContainer(T & container) { std::for_each(container.begin(), container.end(), displayInt); std::cout << std::endl; } int randomValue() { return (rand()); } std::vector<int> generateRandomVect(int size) { std::vector<int> v = std::vector<int>(size); std::generate_n(v.begin(), size, randomValue); return v; } int main(void) { { std::cout << "\033[1;32mVect OK :\033[0m"; Span s(5); try { s.addNumber(-3); s.addNumber(2); s.addNumber(1); s.addNumber(-13); s.addNumber(0); displayIntContainer(s.getVect()); std::cout << "shortest = " << s.shortestSpan() << std::endl; std::cout << "longest = " << s.longestSpan() << std::endl; } catch (std::exception & e) { std::cerr << std::endl << "Error : " << e.what() << std::endl; } } std::cout << std::endl; { std::cout << "\033[1;32mTrying to push more element than possible :\033[0m"; Span s(2); try { s.addNumber(-3); s.addNumber(2); s.addNumber(1); } catch (std::exception & e) { std::cerr << std::endl << "Error : " << e.what() << std::endl; } } std::cout << std::endl; { std::cout << "\033[1;32mTrying to calc span with only 1 element inside :\033[0m"; Span s(4); try { s.addNumber(12); std::cout << std::endl; std::cout << "shortest = " << s.shortestSpan() << std::endl; std::cout << "longest = " << s.longestSpan() << std::endl; } catch (std::exception & e) { std::cerr << std::endl << "Error : " << e.what() << std::endl; } } std::cout << std::endl; { srand (time(NULL)); std::cout << "\033[1;32mTrying to add randomly 8 elements :\033[0m" << std::endl; Span s(10); std::vector<int> randomV = generateRandomVect(8); try { s.addNumber(1); s.addNumber(-12); std::cout << "before insert :"; displayIntContainer(s.getVect()); s.addVector(randomV); std::cout << "after insert :"; displayIntContainer(s.getVect()); std::cout << "shortest = " << s.shortestSpan() << std::endl; std::cout << "longest = " << s.longestSpan() << std::endl; } catch (std::exception & e) { std::cerr << std::endl << "Error : " << e.what() << std::endl; } } std::cout << std::endl; { srand (time(NULL)); std::cout << "\033[1;32mTrying to add randomly 10 000 elements :\033[0m" << std::endl; Span s(10000); std::vector<int> randomV = generateRandomVect(10000); try { s.addVector(randomV); std::cout << "shortest = " << s.shortestSpan() << std::endl; std::cout << "longest = " << s.longestSpan() << std::endl; } catch (std::exception & e) { std::cerr << std::endl << "Error : " << e.what() << std::endl; } } return 0; }<file_sep>#include <stdio.h> void colle(int x, int y); int main(void) { colle(0,0); colle(1,0); colle(0,1); colle(1,1); //printf("\n______"); //colle(5,6); //printf("\n______"); //colle(1,5); //printf("\n______"); //colle(5,5); //printf("\n______"); //colle(5,1); //printf("\n______"); colle(-12,10); //printf("\n______"); colle(4,-10); //printf("\n______"); colle(-12,-10); //printf("\n______"); return (0); } <file_sep>#include <stdio.h> void ft_swap(int *a, int *b) { int buffer; buffer = *a; *a = *b; *b = buffer; } int main(void) { int a; int b; a = 1; b = 0; ft_swap(&a, &b); printf("a = %d et b=%d", a, b); return (0); } <file_sep>#include "ClapTrap.hpp" ClapTrap::ClapTrap( void ) : _hitPoints(100), _MaxHitPoints(100), _energyPoints(50), _MaxEnergyPoints(50), _level(1), _name("Boby"), _meleeAttackDamage(20), _rangedAttackDamage(10), _armorDamageReducton(5){ std::cout << "CL4P-TP " << this->_name << " is born 👤" << std::endl; return ; } ClapTrap::ClapTrap ( unsigned int hitPoints, unsigned int MaxHitPoints, unsigned int energyPoints, unsigned int MaxEnergyPoints, unsigned int level, std::string const & name, unsigned int meleeAttackDamage, unsigned int rangedAttackDamage, unsigned int armorDamageReducton) : _hitPoints(hitPoints), _MaxHitPoints(MaxHitPoints), _energyPoints(energyPoints), _MaxEnergyPoints(MaxEnergyPoints), _level(level), _name(name), _meleeAttackDamage(meleeAttackDamage), _rangedAttackDamage(rangedAttackDamage), _armorDamageReducton(armorDamageReducton) { std::cout << "CL4P-TP " << this->_name << " is born 👤" << std::endl; return ; } ClapTrap::ClapTrap( ClapTrap const & src ) { *this = src; std::cout << "CL4P-TP " << this->_name << " is born 👤" << std::endl; return ; } ClapTrap::~ClapTrap( void ) { std::cout << "CL4P-TP " << this->_name << " is dead ☠️" << std::endl; return ; } ClapTrap & ClapTrap::operator=( ClapTrap const & rhs) { if ( this != &rhs ) { this->_hitPoints = rhs._hitPoints; this->_MaxHitPoints = rhs._MaxHitPoints; this->_energyPoints = rhs._energyPoints; this->_MaxEnergyPoints = rhs._MaxEnergyPoints; this->_level = rhs._level; this->_name = rhs._name; this->_meleeAttackDamage = rhs._meleeAttackDamage; this->_rangedAttackDamage = rhs._rangedAttackDamage; this->_armorDamageReducton = rhs._armorDamageReducton; } return *this ; } std::string ClapTrap::getName ( void ) const { return this->_name; } void ClapTrap::takeDamage( unsigned int amount ) { std::cout << this->_name << " takes " << amount - this->_armorDamageReducton << " points of damages !" << std::endl; if (amount - this->_armorDamageReducton < this->_hitPoints) this->_hitPoints -= amount - this->_armorDamageReducton; else this->_hitPoints = 0; std::cout << this->_name << "'s hit points : " << this->_hitPoints << "/" << this->_MaxHitPoints << std::endl; return ; } void ClapTrap::beRepaired( unsigned int amount ) { std::cout << this->_name << " gains " << amount << " hit points !" << std::endl; if (amount + this->_hitPoints <= this->_MaxHitPoints) this->_hitPoints += amount; else this->_hitPoints = this->_MaxHitPoints; std::cout << this->_name << "'s hit points : " << this->_hitPoints << "/" << this->_MaxHitPoints << std::endl; return ; } void ClapTrap::rangedAttack( std::string const & target ) const { std::cout << this->_name << " attacks " << target << " at range, causing " << this->_rangedAttackDamage << " points of damage !" << std::endl; return ; } void ClapTrap::meleeAttack( std::string const & target ) const { std::cout << this->_name << " attacks " << target << " at melee, causing " << this->_meleeAttackDamage << " points of damage !" << std::endl; return ; }<file_sep>#include "Array.tpp" int main(void) { std::cout << "---- ARRAY OF INT ----" << std::endl; { std::cout << "Creating a, empty array." << std::endl; Array<int> a; std::cout << "Creating b, array of 5 elements." << std::endl; Array<int> b(5); std::cout << "Creating c, copy of b." << std::endl; Array<int> c(b); std::cout << std::endl; std::cout << "\033[1;32mAssigning 1 to b[0]\033[0m" << std::endl; try { std::cout << "Displaying b[0] before the change : "; std::cout << b[0] << std::endl; b[0] = 1; std::cout << "Displaying b[0] : "; std::cout << b[0] << std::endl; } catch (std::out_of_range & e) { std::cerr << "Error :" << e.what() << std::endl; } std::cout << std::endl; std::cout << "\033[1;32mDisplaying c[0]\033[0m" << std::endl; try { std::cout << "c[0] = " << c[0] << std::endl; } catch (std::out_of_range & e) { std::cerr << "Error :" << e.what() << std::endl; } std::cout << std::endl; std::cout << "\033[1;32mTrying to access to b[5] (wrong)\033[0m" << std::endl; try { b[5] = 12; } catch (std::out_of_range & e) { std::cerr << "Error : " << e.what() << std::endl; } std::cout << std::endl; std::cout << "\033[1;32mTrying to access to a[0] (wrong)\033[0m" << std::endl; try { a[0] = 12; } catch (std::out_of_range & e) { std::cerr << "Error : " << e.what() << std::endl; } std::cout << std::endl; } std::cout << "----------------------" << std::endl; { std::cout << std::endl; std::cout << "-- ARRAY OF STRING --" << std::endl; std::cout << "Creating a, empty array." << std::endl; Array<std::string> a; std::cout << "Creating b, array of 3 elements." << std::endl; Array<std::string> b(3); std::cout << "Creating c, copy of b." << std::endl; Array<std::string> c(b); std::cout << std::endl; std::cout << "\033[1;32mAssigning \"toto\" to b[0]\033[0m" << std::endl; try { std::cout << "Displaying b[0] before the change : "; std::cout << b[0] << std::endl; b[0] = "toto"; std::cout << "Displaying b[0] : "; std::cout << b[0] << std::endl; } catch (std::out_of_range & e) { std::cerr << "Error :" << e.what() << std::endl; } std::cout << std::endl; std::cout << "\033[1;32mDisplaying c[0]\033[0m" << std::endl; try { std::cout << "c[0] = " << c[0] << std::endl; } catch (std::out_of_range & e) { std::cerr << "Error :" << e.what() << std::endl; } std::cout << std::endl; std::cout << "\033[1;32mTrying to access to b[3] (wrong)\033[0m" << std::endl; try { b[3] = 12; } catch (std::out_of_range & e) { std::cerr << "Error : " << e.what() << std::endl; } std::cout << std::endl; std::cout << "\033[1;32mTrying to access to a[0] (wrong)\033[0m" << std::endl; try { a[0] = 12; } catch (std::out_of_range & e) { std::cerr << "Error : " << e.what() << std::endl; } std::cout << std::endl; } std::cout << "----------------------" << std::endl; return 0; }<file_sep># 42_Piscines Introduction to a new language/concept in 2 weeks at 42 school. <file_sep>#include "ZombieHorde.hpp" ZombieHorde::ZombieHorde( int n ) : _number(n) { std::cout << "ZombieHorde is created." << std::endl << std::endl; this->_horde = new Zombie [this->_number]; return; } ZombieHorde::~ZombieHorde( void ) { delete [] this->_horde; std::cout << std::endl << "ZombieHorde is destroyed." << std::endl; return ; } void ZombieHorde::announce( void ) const { for (int i = 0; i < this->_number; i++) { this->_horde[i].announce(); } return ; }<file_sep>#ifndef CONTACT_HPP # define CONTACT_HPP class Contact { public: Contact(); ~Contact(); void setField(std::string line, int field); std::string getField (int field) const; private: std::string _index; std::string _first_name; std::string _last_name; std::string _nickname; std::string _login; std::string _postal_address; std::string _email_address; std::string _phone_number; std::string _birthday_date; std::string _favorite_meal; std::string _underwear_color; std::string _darkest_secret; static int _count; static int getCount(void); static void incCount(void); }; #endif<file_sep>#include "ScavTrap.hpp" #include "FragTrap.hpp" int main ( void ) { std::cout << "---- FRAG TRAP ----" << std::endl; { FragTrap choupi("Choupi"); FragTrap albert("Albert"); std::cout << std::endl; choupi.rangedAttack(albert.getName()); albert.takeDamage(20); std::cout << std::endl; std::cout << "Candy for everyone !!!! 🍭" << std::endl; choupi.beRepaired(5); albert.beRepaired(5); std::cout << std::endl; albert.vaulthunter_dot_exe(choupi.getName()); choupi.takeDamage(45); std::cout << std::endl; std::cout << choupi.getName() << " is very angry... 😡" << std::endl; choupi.meleeAttack(albert.getName()); choupi.meleeAttack(albert.getName()); choupi.meleeAttack(albert.getName()); choupi.meleeAttack(albert.getName()); albert.takeDamage(120); std::cout << std::endl; std::cout << albert.getName() << " is KO but " << choupi.getName() << " is still very angry... 😡 😡" << std::endl; choupi.vaulthunter_dot_exe(albert.getName()); choupi.vaulthunter_dot_exe(albert.getName()); choupi.vaulthunter_dot_exe(albert.getName()); choupi.vaulthunter_dot_exe(albert.getName()); choupi.vaulthunter_dot_exe(albert.getName()); std::cout << std::endl; std::cout << "THE END !!" << std::endl; } std::cout << std::endl; std::cout << "---- SCAV TRAP ----" << std::endl; { ScavTrap titi("Titi"); ScavTrap charly("Charly"); std::cout << std::endl; charly.rangedAttack(titi.getName()); titi.takeDamage(15); std::cout << std::endl; std::cout << "Candy for everyone !!!! 🍭" << std::endl; titi.beRepaired(5); charly.beRepaired(5); std::cout << std::endl; std::cout << titi.getName() << " is very angry... 😡" << std::endl; titi.meleeAttack(charly.getName()); titi.meleeAttack(charly.getName()); titi.meleeAttack(charly.getName()); titi.meleeAttack(charly.getName()); titi.meleeAttack(charly.getName()); titi.meleeAttack(charly.getName()); charly.takeDamage(120); std::cout << std::endl; std::cout << charly.getName() << " is KO but " << titi.getName() << " wants to play..." << std::endl; std::cout << titi.getName() << " gives a medicine to " << charly.getName() << "." << std::endl; charly.beRepaired(50); std::cout << std::endl; std::cout << "Challengs time !!" << std::endl; titi.challengeNewcomer(charly.getName()); charly.challengeNewcomer(titi.getName()); titi.challengeNewcomer(charly.getName()); charly.challengeNewcomer(titi.getName()); titi.challengeNewcomer(charly.getName()); std::cout << std::endl; std::cout << "THE END !!" << std::endl; } std::cout << std::endl; std::cout << "---- CONSTRUCTORS TESTS FRAG TRAP ----" << std::endl; { FragTrap a; FragTrap b("Yoyo"); FragTrap c(a); FragTrap d("titi"); d = a; std::cout << "a name should be Boby -> " << a.getName() << std::endl; std::cout << "b name should be Yoyo -> " << b.getName() << std::endl; std::cout << "c name should be Boby -> " << c.getName() << std::endl; std::cout << "d name should be Boby -> " << d.getName() << std::endl; std::cout << std::endl; std::cout << "Clearing out the energy of a :" << std::endl; a.vaulthunter_dot_exe(b.getName()); a.vaulthunter_dot_exe(b.getName()); a.vaulthunter_dot_exe(b.getName()); a.vaulthunter_dot_exe(b.getName()); a.vaulthunter_dot_exe(b.getName()); std::cout << std::endl; std::cout << "Vault on c (copy of a) :" << std::endl; c.vaulthunter_dot_exe(b.getName()); std::cout << std::endl; std::cout << "Vault on d (= a) :" << std::endl; d.vaulthunter_dot_exe(b.getName()); std::cout << std::endl; } std::cout << std::endl; std::cout << "---- CONSTRUCTORS TESTS SCAV TRAP ----" << std::endl; { ScavTrap a; ScavTrap b("Yoyo"); ScavTrap c(a); ScavTrap d("titi"); d = a; std::cout << "a name should be Boby -> " << a.getName() << std::endl; std::cout << "b name should be Yoyo -> " << b.getName() << std::endl; std::cout << "c name should be Boby -> " << c.getName() << std::endl; std::cout << "d name should be Boby -> " << d.getName() << std::endl; std::cout << std::endl; std::cout << "Clearing out the hit points of a :" << std::endl; a.takeDamage(200); std::cout << std::endl; std::cout << "takeDamage on c (copy of a) :" << std::endl; c.takeDamage(20); std::cout << std::endl; std::cout << "takeDamage on d (= a) :" << std::endl; d.takeDamage(20); std::cout << std::endl; } std::cout << std::endl; std::cout << "---- CONSTRUCTORS TESTS CLAP TRAP ----" << std::endl; { ClapTrap a; ClapTrap b(100, 100, 50, 50, 1, "Yoyo", 20, 10, 1); ClapTrap c(a); ClapTrap d(50, 50, 50, 50, 1, "Titi", 20, 10, 1); d = a; std::cout << "a name should be Boby -> " << a.getName() << std::endl; std::cout << "b name should be Yoyo -> " << b.getName() << std::endl; std::cout << "c name should be Boby -> " << c.getName() << std::endl; std::cout << "d name should be Boby -> " << d.getName() << std::endl; std::cout << std::endl; std::cout << "Clearing out the hit points of a :" << std::endl; a.takeDamage(200); std::cout << std::endl; std::cout << "takeDamage on c (copy of a) :" << std::endl; c.takeDamage(20); std::cout << std::endl; std::cout << "takeDamage on d (= a) :" << std::endl; d.takeDamage(20); std::cout << std::endl; } }<file_sep>#include <stdio.h> void ft_advanced_sort_wordtab(char **tab, int (*f)(char *, char *)); char **ft_split_whitespaces(char *str); void ft_print_words_tables(char **tab); int ft_strlen(char *str); int ft_strcmp(char *s1, char *s2) { int i; int length; i = 0; length = 0; while (s1[length] != '\0') length++; while (i <= length) { if (s1[i] != s2[i]) return (s1[i] - s2[i]); i++; } return (0); } int ft_cmplength(char *s1, char *s2) { if (ft_strlen(s1) > ft_strlen(s2)) return (1); return (0); } int main(int argc, char **argv) { char **tab; if (argc != 2) return (0); tab = ft_split_whitespaces(argv[1]); ft_advanced_sort_wordtab(tab, &ft_strcmp); ft_print_words_tables(tab); return (0); } <file_sep>#ifndef PRESIDENTIALPARDONFORM_HPP # define PRESIDENTIALPARDONFORM_HPP #include "Form.hpp" class PresidentialPardonForm : public Form { private: std::string _target; PresidentialPardonForm & operator=( PresidentialPardonForm const & rhs ); PresidentialPardonForm( PresidentialPardonForm const & src ); public: PresidentialPardonForm( void ); PresidentialPardonForm( std::string const target ); virtual ~PresidentialPardonForm( void ); std::string getTarget(); virtual void executeChildForm() const; }; #endif<file_sep>#include <stdio.h> #include <string.h> int ft_str_is_lowercase(char *str); int main(void) { char str1[] = "\0"; printf("%s \n", str1); printf("%d \n", ft_str_is_lowercase(str1)); return (0); } <file_sep>NAME = colle-2 FLAG = -Wall -Werror -Wextra SRC = colle_2.c ft_basic.c ft_init_colle.c main.c OBJ = $(SRC:.c=.o) all : $(NAME) $(NAME) : gcc $(FLAG) -c $(SRC) gcc $(FLAG) $(OBJ) -o $(NAME) clean : rm -rf $(OBJ) fclean : clean rm -rf $(NAME) re : fclean $(NAME) <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_spy.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/12 11:52:42 by curquiza #+# #+# */ /* Updated: 2016/08/12 14:23:39 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> int ft_strlen(char *str) { int count; count = 0; while (str[count] != '\0') count++; return (count); } int ft_strcmp(char *s1, char *s2) { int i; i = 0; while (i <= ft_strlen(s1)) { if (s1[i] != s2[i]) return (s1[i] - s2[i]); i++; } return (0); } void ft_del_spaces(char *str) { int length; length = ft_strlen(str); while (str[length] < 33) length--; str[length + 1] = '\0'; while (*str < 33) str++; } char *ft_strlowcase(char *str) { int i; i = 0; while (str[i] != '\0') { if (str[i] >= 65 && str[i] <= 90) str[i] = str[i] + 32; i++; } return (str); } int main(int argc, char **argv) { int i; int count; i = 1; count = 0; while (i < argc) { ft_del_spaces(argv[i]); ft_strlowcase(argv[i]); if (ft_strcmp(argv[i], "president") == 0 || ft_strcmp(argv[i], "attack") == 0 || ft_strcmp(argv[i], "powers") == 0) count++; i++; } if (count > 0) write(1, "Alert!!!\n", 9); return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_list_reverse.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/21 14:35:52 by curquiza #+# #+# */ /* Updated: 2016/08/22 19:15:57 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_list.h" int ft_list_size(t_list *begin_list) { int cpt; cpt = 0; while (begin_list != 0) { cpt++; begin_list = begin_list->next; } return (cpt); } t_list *ft_list_at(t_list *begin_list, unsigned int nbr) { t_list *current; unsigned int cpt; cpt = 0; current = begin_list; while (cpt < nbr && current != 0) { current = current->next; cpt++; } if (cpt == nbr) return (current); else return (0); } void ft_list_reverse(t_list **begin_list) { t_list *end; t_list *current; int size; int i; i = 0; if (*begin_list != 0) { size = ft_list_size(*begin_list); end = ft_list_at(*begin_list, size - 1); end->next = *begin_list; *begin_list = end; current = *begin_list; while (i < size - 2) { end = ft_list_at(*begin_list, size - 1); end->next = current->next; current->next = end; current = current->next; i++; } end = ft_list_at(*begin_list, size - 1); end->next = 0; } } <file_sep>#include "Bureaucrat.hpp" #include "Form.hpp" #include "ShrubberyCreationForm.hpp" #include "RobotomyRequestForm.hpp" #include "PresidentialPardonForm.hpp" int main(void) { Bureaucrat ceo("Maxou", 1); Bureaucrat intern("Choupi", 150); PresidentialPardonForm prez("titi"); RobotomyRequestForm robot("tata"); ShrubberyCreationForm shrubbery("toto"); std::cout << std::endl; std::cout << "\033[1;32mAll forms descriptions : \033[0m" << std::endl; std::cout << prez << std::endl; std::cout << "Target : " << prez.getTarget() << std::endl; std::cout << "-------" << std::endl; std::cout << robot << std::endl; std::cout << "Target : " << robot.getTarget() << std::endl; std::cout << "-------" << std::endl; std::cout << shrubbery << std::endl; std::cout << "Target : " << shrubbery.getTarget() << std::endl; std::cout << std::endl; std::cout << "\033[1;32mTrying to execute when the form is not signed: \033[0m" << std::endl; ceo.executeForm(prez); std::cout << "\033[1;32mSigning all the forms : \033[0m" << std::endl; ceo.signForm(prez); ceo.signForm(robot); ceo.signForm(shrubbery); std::cout << "\033[1;32mTrying to execute when the bureaucrat does not have the grade : \033[0m" << std::endl; intern.executeForm(prez); std::cout << "\033[1;32mTrying to execute (president) when the bureaucrat has the right : \033[0m" << std::endl; ceo.executeForm(prez); std::cout << "\033[1;32mTrying to execute (robot) when the bureaucrat has the right : \033[0m" << std::endl; ceo.executeForm(robot); std::cout << "\033[1;32mTrying to execute (shrubbery) when the bureaucrat has the right : \033[0m" << std::endl; ceo.executeForm(shrubbery); std::cout << std::endl; std::cout << "\033[1;32mCreate others robot forms to test random : \033[0m" << std::endl; RobotomyRequestForm robot2("tata2"); RobotomyRequestForm robot3("tata3"); ceo.signForm(robot2); ceo.signForm(robot3); ceo.executeForm(robot2); ceo.executeForm(robot3); std::cout << std::endl; return (0); }<file_sep><?php abstract Class Fighter { public $type = 0; function __construct($warrior) { $this->type = $warrior; } abstract function fight($target); } ?> <file_sep>#include "Pony.hpp" Pony::Pony(std::string name, std::string coat) : _name(name), _coat(coat), _kindness(10) { std::cout << "A poney is born." << std::endl; std::cout << std::endl; return ; } Pony::~Pony( void ) { std::cout << std::endl; std::cout << "A poney is going to heaven." << std::endl; return ; } std::string Pony::getCoat( void ) const { return this->_coat; } void Pony::setCoat( std::string new_coat ) { this->_coat = new_coat; return ; } int Pony::getKindness( void ) const { return this->_kindness; } void Pony::setKindness( int new_kindness ) { this->_kindness = new_kindness; return ; }<file_sep>#ifndef EASYFIND_HPP # define EASYFIND_HPP # include <iostream> # include <algorithm> /* dans T, il y a déjà std::list<int> ou std::vector<int> ... etc */ template <typename T> typename T::iterator easyfind( T & container, int n ) { return std::find(container.begin(), container.end(), n); /* Avec les exceptions */ /* typename T::iterator tmp = std::find(container.begin(), container.end(), n); if (tmp == container.end()) throw std::exception(); // pas ouf, les exceptions doivent rester rare return (tmp); */ } #endif<file_sep>#include "Intern.hpp" Intern::Intern( void ) { initNames(); initActions(); std::cout << "Intern CONSTRUCTOR" << std::endl; return ; } Intern::~Intern( void ) { std::cout << "Intern DESTRCUTOR" << std::endl; return ; } Form * Intern::makeForm(std::string const & name, std::string const & target) { // if (name == "president pardon") // { // std::cout << "Intern creates " << name << " form." << std::endl; // return (new PresidentialPardonForm::PresidentialPardonForm(target)); // } // else if (name == "robotomy request") // { // std::cout << "Intern creates " << name << " form." << std::endl; // return (new RobotomyRequestForm::RobotomyRequestForm(target)); // } // else if (name == "shrubbery creation") // { // std::cout << "Intern creates " << name << " form." << std::endl; // return (new ShrubberyCreationForm::ShrubberyCreationForm(target)); // } for (int i = 0; i < ACTIONS_NB; i++) { if (_validNames[i] == name) { std::cout << "Intern creates " << name << " form." << std::endl; return (this->*_actions[i])(target); } } std::cerr << "Unknown name of form." << std::endl; return (NULL); } void Intern::initNames() { _validNames[0] = "president pardon"; _validNames[1] = "robotomy request"; _validNames[2] = "shrubbery creation"; return ; } void Intern::initActions() { _actions[0] = &Intern::makePresident; _actions[1] = &Intern::makeRobot; _actions[2] = &Intern::makeShrubbery; return ; } Form * Intern::makePresident( std::string const & target ) { return (new PresidentialPardonForm::PresidentialPardonForm(target)); } Form * Intern::makeRobot( std::string const & target ) { return (new RobotomyRequestForm::RobotomyRequestForm(target)); } Form * Intern::makeShrubbery( std::string const & target ) { return (new ShrubberyCreationForm::ShrubberyCreationForm(target)); } /* UNUSED */ Intern::Intern( Intern const & ) {} Intern & Intern::operator=( Intern const & ) { return *this ; } <file_sep>#ifndef SCAVTRAP_HPP # define SCAVTRAP_HPP # include <iostream> # include "ClapTrap.hpp" class ScavTrap : public ClapTrap { public: ScavTrap( void ); ScavTrap( std::string const & name ); ScavTrap( ScavTrap const & src ); ~ScavTrap( void ); ScavTrap & operator=( ScavTrap const & rhs ); void challengeNewcomer( std::string const & target ); private: void (ScavTrap::*_challenges[5])( std::string const & target ); void initChallenges( void ); void yugiohDuel( std::string const & target ); void concomberCat( std::string const & target ); void PHPCleanCode( std::string const & target ); void marioKart( std::string const & target ); void rattataChallenge( std::string const & target ); }; #endif<file_sep>#include <stdio.h> #include <string.h> char ft_strcmp(char *s1, char *s2); int main(void) { char str1[] = "test"; char str2[] = "test1"; char str3[] = "test"; char str4[] = "test1"; printf("%s %s\n", str1, str2); printf("%d \n\n", ft_strcmp(str1, str2)); printf("%s %s\n", str3, str4); printf("%d \n", strcmp(str3, str4)); return (0); } <file_sep><?php Class UnholyFactory { public $fighters = array(); public function absorb($warrior) { if (array_key_exists($warrior->type, $this->fighters) == TRUE) print("(Factory already absorbed a fighter of type ".$warrior->type.")".PHP_EOL); else if (is_a($warrior, "Fighter") == FALSE) print("(Factory can't absorb this, it's not a fighter)".PHP_EOL); else { $this->fighters[$warrior->type] = $warrior; print("(Factory absorbed a fighter of type ".$warrior->type.")".PHP_EOL); } } public function fabricate($rf) { print("(Factory fabricates a fighter of type ".$rf.")".PHP_EOL); $f = $this->fighters[$rf]; return ($f); } } ?> <file_sep>#include "ft_list.h" t_list *ft_create_elem(void *data); void ft_putstr(char *str); //void ft_print_list(t_list *list) int main (int argc, char **argv) { t_list *list; list = 0; if (argc != 2) return (0); list = ft_create_elem(argv[1]); ft_putstr(list->data); return (0); } <file_sep>#ifndef PHONEBOOK_HPP # define PHONEBOOK_HPP # include <iostream> # include <iomanip> # include "Contact.hpp" # define INDEX 0 # define FIRST_NAME 1 # define LAST_NAME 2 # define NICKNAME 3 # define LOGIN 4 # define POSTAL_ADDRESS 5 # define EMAIL_ADDRESS 6 # define PHONE_NUMBER 7 # define BIRTHDAY_DATE 8 # define FAVORITE_MEAL 9 # define UNDERWEAR_COLOR 10 # define DARKEST_SECRET 11 # define MAXWIDTH 10 void add_contact(Contact *all_contacts, int count); void search_contact(Contact *all_contacts, int count); void display_all_contacts(Contact *all_contacts, int count); #endif<file_sep>#ifndef VAR_HPP # define VAR_HPP # include <iostream> # include <climits> # include <cfloat> # define UNDEFINED -1 # define CHAR 0 # define INT 1 # define FLOAT 2 # define DOUBLE 3 # define LITT_VALUE 4 # define LITT_VALUE_NB 3 // # define INDEX_LITT_VALUE -1 class Var { private: std::string const _str; int _type; char _charVar; int _intVar; float _floatVar; double _doubleVar; std::string _floatLittValue[LITT_VALUE_NB]; std::string _doubleLittValue[LITT_VALUE_NB]; int _indexLittValue; int getType(); void convChar(); char * getChar(); void convInt(); int * getInt(); void convFloat(); float * getFloat(); void convDouble(); double * getDouble(); void initLittValueArray(); /* UNUSED */ Var( void ); Var( Var const & src ); Var & operator=( Var const & rhs ); public: Var( std::string const & str ); ~Var( void ); void displayChar(std::ostream & o); void displayInt(std::ostream & o); void displayFloat(std::ostream & o); void displayDouble(std::ostream & o); }; std::ostream & operator<<( std::ostream & o, Var & rhs ); #endif<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_init_colle.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/20 22:02:11 by curquiza #+# #+# */ /* Updated: 2016/08/21 11:36:37 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include "colle_2.h" #include "ft_init_colle.h" void ft_init_colle00(t_colle *colle, int x, int y) { colle->up_left = 'o'; colle->up_right = 'o'; colle->b_left = 'o'; colle->b_right = 'o'; colle->col = '|'; colle->row = '-'; colle->nb_col = x; colle->nb_row = y; } void ft_init_colle01(t_colle *colle, int x, int y) { colle->up_left = '/'; colle->up_right = '\\'; colle->b_left = '\\'; colle->b_right = '/'; colle->col = '*'; colle->row = '*'; colle->nb_col = x; colle->nb_row = y; } void ft_init_colle02(t_colle *colle, int x, int y) { colle->up_left = 'A'; colle->up_right = 'A'; colle->b_left = 'C'; colle->b_right = 'C'; colle->col = 'B'; colle->row = 'B'; colle->nb_col = x; colle->nb_row = y; } void ft_init_colle03(t_colle *colle, int x, int y) { colle->up_left = 'A'; colle->up_right = 'C'; colle->b_left = 'A'; colle->b_right = 'C'; colle->col = 'B'; colle->row = 'B'; colle->nb_col = x; colle->nb_row = y; } void ft_init_colle04(t_colle *colle, int x, int y) { colle->up_left = 'A'; colle->up_right = 'C'; colle->b_left = 'C'; colle->b_right = 'A'; colle->col = 'B'; colle->row = 'B'; colle->nb_col = x; colle->nb_row = y; } <file_sep>#include "Weapon.hpp" Weapon::Weapon( std::string type ) : _type(type) { std::cout << "Weapon created." << std::endl; return; } Weapon::~Weapon( void ) { std::cout << "Weapon destroyed." << std::endl; return; } std::string const & Weapon::getType ( void ) const { return this->_type; } void Weapon::setType ( std::string new_type ) { this->_type = new_type; }<file_sep>#include <stdio.h> #include <string.h> char *ft_strcapitalize(char *str); int main(void) { char str1[] = "heLLo yeye42hdhd lEs 42ii test,teSt-tEst+clem` !!!!"; printf("%s \n", str1); printf("%s \n", ft_strcapitalize(str1)); return (0); } <file_sep>void ft_print_words_tables(char **tab); char **ft_split_whitespaces(char *str); int main(int argc, char **argv) { char **range; int i; i = 0; if (argc != 2) return (0); range = ft_split_whitespaces(argv[1]); ft_print_words_tables(range); return (0); } <file_sep>#include "Zombie.hpp" Zombie::Zombie( ) : _name(this->_randName()), _type("green") { std::cout << "Zombie " << this->_name << " is created." << std::endl; return ; } Zombie::~Zombie() { std::cout << "Zombie " << this->_name << " is destroyed." << std::endl; return ; } void Zombie::announce() const { std::cout << "<"; std::cout << this->_name << " "; std::cout << "(" << this->_type << ") "; std::cout << "> Braiiiiiiinnnssss..." << std::endl; return ; } std::string Zombie::_randName() const { std::string pool[4] = { "toto", "titi", "tutu", "tata" }; int r = rand() % 4; return (pool[r]); }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> char *ft_concat_params(int argc, char **argv); int ft_strlen(char *str); int main(int argc, char **argv) { int index; index = argc; printf("%s", ft_concat_params(argc, argv)); return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strlcat.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/09 22:42:55 by curquiza #+# #+# */ /* Updated: 2016/08/10 12:27:31 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ unsigned int ft_strlen(char *str) { unsigned int count; count = 0; while (str[count] != '\0') count++; return (count); } unsigned int ft_strlcat(char *dest, char *src, unsigned int size) { unsigned int length_src; unsigned int length_dest; unsigned int i; unsigned int j; length_src = ft_strlen(src); length_dest = ft_strlen(dest); i = length_dest; j = 0; while (i < size - 1) { dest[i] = src[j]; i++; j++; } dest[i] = '\0'; if (length_src > size) return (length_dest + size); else return (length_dest + length_src); } <file_sep>#include <stdio.h> #include <stdlib.h> int ft_atoi(char *str); int main(void) { char str[] = " +2147483647"; printf("%d\n", '\n'); printf("%d\n", '\0'); printf("%d\n", '\t'); printf("%d\n", atoi(str)); printf("%d\n", ft_atoi(str)); return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_list_remove_if.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/22 09:58:28 by curquiza #+# #+# */ /* Updated: 2016/08/22 14:17:21 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_list.h" #include <stdlib.h> void ft_suppr_elem(t_list **elem) { t_list *suppr; suppr = *elem; *elem = (*elem)->next; free(suppr); } void ft_list_remove_if(t_list **begin_list, void *data_ref, int (*cmp)()) { t_list *current; if (*begin_list != 0) { current = *begin_list; while (current->next != 0) { if ((*cmp)(current->next->data, data_ref) == 0) ft_suppr_elem(&(current->next)); else current = current->next; } if (*begin_list != 0) { if ((*cmp)((*begin_list)->data, data_ref) == 0) ft_suppr_elem(begin_list); } } } <file_sep>alias rm='cp' <file_sep>#include "ft_list.h" void ft_putstr(char *str); int ft_putchar(char c); t_list *ft_list_push_params(int ac, char **av); void ft_printlist(t_list *list) { while (list != 0) { ft_putstr(list->data); ft_putchar('\n'); list = list->next; } } int main(int argc, char **argv) { t_list *list; //(void)argv; //(void)argc; list = 0; //list = ft_create_elem("TEST"); list = ft_list_push_params(argc, argv); ft_printlist(list); ft_putchar('\n'); ft_list_clear(&list); ft_printlist(list); return (0); } <file_sep>NAME = prog FLAG = -Wall -Werror -Wextra SRC = main.c btree_insert_data.c btree_create_node.c OBJ = $(SCR:.c=.o) LIB = ~/mes_fonctions/libft.a #D_HEADER = #D_SRC = all : $(NAME) $(NAME) : $(SRC) gcc $(FLAG) $(LIB) $(SRC) -o $(NAME) clean : rm -rf *.o fclean : clean rm -rf $(NAME) re : fclean $(NAME) <file_sep>#include "FragTrap.hpp" int main ( void ) { { FragTrap choupi("Choupi"); FragTrap albert("Albert"); std::cout << std::endl; choupi.rangedAttack(albert.getName()); albert.takeDamage(20); std::cout << std::endl; std::cout << "Candy for everyone !!!! 🍭" << std::endl; choupi.beRepaired(5); albert.beRepaired(5); std::cout << std::endl; albert.vaulthunter_dot_exe(choupi.getName()); choupi.takeDamage(45); std::cout << std::endl; std::cout << choupi.getName() << " is very angry... 😡" << std::endl; choupi.meleeAttack(albert.getName()); choupi.meleeAttack(albert.getName()); choupi.meleeAttack(albert.getName()); choupi.meleeAttack(albert.getName()); albert.takeDamage(120); std::cout << std::endl; std::cout << albert.getName() << " is KO but " << choupi.getName() << " is still very angry... 😡 😡" << std::endl; choupi.vaulthunter_dot_exe(albert.getName()); choupi.vaulthunter_dot_exe(albert.getName()); choupi.vaulthunter_dot_exe(albert.getName()); choupi.vaulthunter_dot_exe(albert.getName()); choupi.vaulthunter_dot_exe(albert.getName()); std::cout << std::endl; std::cout << "THE END !!" << std::endl; } std::cout << std::endl; std::cout << "---- CONSTRUCTORS TESTS ----" << std::endl; { FragTrap a; FragTrap b("Yoyo"); FragTrap c(a); FragTrap d("titi"); d = a; std::cout << "a name should be Boby -> " << a.getName() << std::endl; std::cout << "b name should be Yoyo -> " << b.getName() << std::endl; std::cout << "c name should be Boby -> " << c.getName() << std::endl; std::cout << "d name should be Boby -> " << d.getName() << std::endl; std::cout << std::endl; std::cout << "Clearing out the energy of a :" << std::endl; a.vaulthunter_dot_exe(b.getName()); a.vaulthunter_dot_exe(b.getName()); a.vaulthunter_dot_exe(b.getName()); a.vaulthunter_dot_exe(b.getName()); a.vaulthunter_dot_exe(b.getName()); std::cout << std::endl; std::cout << "Vault on c (copy of a) :" << std::endl; c.vaulthunter_dot_exe(b.getName()); std::cout << std::endl; std::cout << "Vault on d (= a) :" << std::endl; d.vaulthunter_dot_exe(b.getName()); std::cout << std::endl; } return 0; }<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_sort_params.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/11 09:26:46 by curquiza #+# #+# */ /* Updated: 2016/08/19 16:20:42 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ int ft_putchar(char c); void ft_putstr(char *str) { int i; i = 0; while (*(str + i) != '\0') { ft_putchar(*(str + i)); i++; } } int ft_strlen(char *str) { int count; count = 0; while (str[count] != '\0') count++; return (count); } int ft_strcmp(char *s1, char *s2) { int i; i = 0; while (i <= ft_strlen(s1)) { if (s1[i] != s2[i]) return (s1[i] - s2[i]); i++; } return (0); } void ft_display_argv(char **argv, int argc) { int i; i = 1; while (i < argc) { ft_putstr(argv[i]); ft_putchar('\n'); i++; } } int main(int argc, char **argv) { int i; char *buffer; i = 1; while (i < argc - 1) { if (ft_strcmp(argv[i], argv[i + 1]) > 0) { buffer = argv[i]; argv[i] = argv[i + 1]; argv[i + 1] = buffer; i = 1; //rendu et valide avec i = 0; } i++; } ft_display_argv(argv, argc); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* colle_2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/20 17:01:23 by curquiza #+# #+# */ /* Updated: 2016/08/20 21:47:11 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> //ATTENTION PRINTF #include "colle_2.h" #define SIZE 400 int ft_putchar(char c) { write(1, &c, 1); return (0); } void ft_putstr(char *str) { int i; i = 0; while (*(str + i) != '\0') { ft_putchar(*(str + i)); i++; } } void ft_putnbr(int nb) { int index; int tab[10]; index = 0; if (nb < 0) ft_putchar('-'); while (index < 10 && (nb >= 10 || nb <= -10)) { tab[index] = (nb % 10); nb = nb / 10; index++; } tab[index] = nb; while (index >= 0) { if (tab[index] < 0) ft_putchar((tab[index] * -1) + '0'); else ft_putchar(tab[index] + '0'); index--; } } int ft_strcmp(char *s1, char *s2) { int i; int length; i = 0; length = 0; while (s1[length] != '\0') length++; while (i <= length) { if (s1[i] != s2[i]) return (s1[i] - s2[i]); i++; } return (0); } int ft_strlen(char *str) { int count; count = 0; while (str[count] != '\0') count++; return (count); } char *ft_strcat(char *dest, char *src) { int i; int j; i = ft_strlen(dest); j = 0; while (src[j] != '\0') { dest[i] = src[j]; i++; j++; } dest[i] = '\0'; return (dest); } char *ft_print_line(char char1, char char2, char char3, int x) { int i; char *str; str = (char *)malloc(sizeof(char) * x); i = 0; while (i < x) { if (i == 0) str[i] = char1; else if (i == x - 1) str[i] = char3; else str[i] = char2; i++; } str[i] = '\0'; return (str); } void ft_colle(int x, int y, char *str, t_colle colle) { int j; j = 0; if (x > 0 && y > 0) { while (j < y) { if (j == 0) str = ft_strcat(str, ft_print_line(colle.up_left, colle.row, colle.up_right, x)); else if (j == y - 1) str = ft_strcat(str, ft_print_line(colle.b_left, colle.row, colle.b_right, x)); else str = ft_strcat(str, ft_print_line(colle.col, ' ', colle.col, x)); while(*str !='\0') str++; *str = '\n'; j++; } str++; *str = '\0'; } } void ft_init_colle00(t_colle *colle, int x, int y) { colle->up_left = 'o'; colle->up_right = 'o'; colle->b_left = 'o'; colle->b_right = 'o'; colle->col = '|'; colle->row = '-'; colle->nb_col = x; colle->nb_row = y; } void ft_init_colle01(t_colle *colle, int x, int y) { colle->up_left = '/'; colle->up_right = '\\'; colle->b_left = '\\'; colle->b_right = '/'; colle->col = '*'; colle->row = '*'; colle->nb_col = x; colle->nb_row = y; } void ft_init_colle02(t_colle *colle, int x, int y) { colle->up_left = 'A'; colle->up_right = 'A'; colle->b_left = 'C'; colle->b_right = 'C'; colle->col = 'B'; colle->row = 'B'; colle->nb_col = x; colle->nb_row = y; } void ft_init_colle03(t_colle *colle, int x, int y) { colle->up_left = 'A'; colle->up_right = 'C'; colle->b_left = 'A'; colle->b_right = 'C'; colle->col = 'B'; colle->row = 'B'; colle->nb_col = x; colle->nb_row = y; } void ft_init_colle04(t_colle *colle, int x, int y) { colle->up_left = 'A'; colle->up_right = 'C'; colle->b_left = 'C'; colle->b_right = 'A'; colle->col = 'B'; colle->row = 'B'; colle->nb_col = x; colle->nb_row = y; } void ft_calc_row_col(t_colle *colle, char *buffer) { int i; i = 0; colle->nb_col = 0; colle->nb_row = 0; while (buffer[i] != '\n') i++; colle->nb_col = i; while (buffer[i] != '\0') { if (buffer[i] == '\n') colle->nb_row = colle->nb_row + 1; i++; } } char **ft_complete_all_colles(int x, int y) { char **str; t_colle *colle; int i; i = 0; colle = (t_colle *)malloc(sizeof(t_colle) * 5); str = (char **)malloc(sizeof(char*) * 6); ft_init_colle00(colle, x, y); ft_init_colle01(colle + 1, x, y); ft_init_colle02(colle + 2, x, y); ft_init_colle03(colle + 3, x, y); ft_init_colle04(colle + 4, x, y); while (i <= 4) { str[i] = (char *)malloc(sizeof(char) * (SIZE + 1)); ft_colle(x, y, str[i], colle[i]); i++; } return (str); } void ft_find_colle(char *buff, char **str, int x, int y) { int i; int cpt; cpt = 0; i = 0; while (i < 5) { if (ft_strcmp(str[i], buff) == 0) { if (cpt > 0) ft_putstr(" || "); ft_putstr("[colle-0"); ft_putnbr(i); ft_putstr("] ["); ft_putnbr(x); ft_putstr("] ["); ft_putnbr(y); ft_putchar(']'); cpt++; } i++; } if (cpt == 0) ft_putstr("aucune"); ft_putchar('\n'); } int main(void) { char *buf; int ret; t_colle colle_buf; char **all_colles; buf = (char *)malloc(sizeof(char) * (SIZE + 1)); ret = read(0, buf, SIZE); if (ret == 0) { ft_putstr("aucune\n"); return (0); } buf[ret] = '\0'; ft_calc_row_col(&colle_buf, buf); all_colles = ft_complete_all_colles(colle_buf.nb_col, colle_buf.nb_row); // TEST du buffer + nb_ligne, nb_col /*printf("%s\n", buf); printf("%d %d\n", colle_buf.nb_col, colle_buf.nb_row); int i = 0; while (i < 5) { printf("%s\n", all_colles[i]); write(1, "\n", 1); i++; }*/ //TEST de ft_colle -> OK /*t_colle colleTEST; char *STR; STR = (char *)malloc(sizeof(char) * (SIZE + 1)); ft_init_colle00(&colleTEST, 4, 5); ft_colle(4, 5, STR, colleTEST); printf("%s", STR);*/ ft_find_colle(buf, all_colles, colle_buf.nb_col, colle_buf.nb_row); return (0); } <file_sep>#include "easyfind.hpp" #include <map> #include <list> #include <vector> #include <array> /* lst.end() déréférencé renvoie la taille du conteneur */ void displayInt(int n) { std::cout << " " << n; } template <typename T> void FindingNemo(T & container, int n) { typename T::iterator cont_it = easyfind(container, n); std::cout << "Finding " << n << " value in the container : " << std::endl; if (cont_it != container.end()) std::cout << "Found ! -> " << *cont_it << std::endl; else std::cerr << "Error : no " << n << " value in the container (return = " << *cont_it << ")" << std::endl; } template <typename T> void displayIntContainer(T & container) { std::for_each(container.begin(), container.end(), displayInt); } int main(void) { std::cout << "----- LIST -----" << std::endl; { std::list<int> lst; lst.push_back(10); lst.push_back(11); lst.push_back(12); lst.push_back(13); std::cout << "Displaying list :"; displayIntContainer(lst); std::cout << std::endl; std::cout << std::endl; FindingNemo(lst, 17); std::cout << std::endl; FindingNemo(lst, 13); } std::cout << "----------------" << std::endl; std::cout << std::endl; std::cout << "---- VECTOR ----" << std::endl; { std::vector<int> vect; vect.push_back(1); vect.push_back(-11); vect.push_back(13); std::cout << "Displaying vector :"; displayIntContainer(vect); std::cout << std::endl; std::cout << std::endl; FindingNemo(vect, -1); std::cout << std::endl; FindingNemo(vect, -11); } std::cout << "----------------" << std::endl; /* std::cout << std::endl; std::cout << "----- ARRAY ----" << std::endl; { std::array<int, 3> tab; tab[0] = 1; tab[1] = 3; tab[2] = 2; std::cout << "Displaying array :"; displayIntContainer(tab); // displayIntContainer<std::array<int, 3> >(tab); -> autre écriture std::cout << std::endl; std::cout << std::endl; FindingNemo(tab, 1); std::cout << std::endl; FindingNemo(tab, -14); } std::cout << "----------------" << std::endl; */ return 0; }<file_sep>#ifndef GAMEMASTER_HPP #define GAMEMASTER_HPP #include <iostream> #include "ncurses.h" #include "GameEntity.hpp" #include "Player.hpp" #define WINBOXX 10 #define WINBOXY 10 #define MIN_TERM_X 50 #define MIN_TERM_Y 30 #define STARS_NB 20 #define DIFFICULTY_SPEED 15000 #define DIFFICULTY_LEVEL 30000 class GameMaster { private: GameMaster(GameMaster const &Cc); GameMaster &operator = (GameMaster const &Cc); int _winX; int _winY; WINDOW *_win; Player _pl; int _ch; int _nEntities; clock_t _begin_time; clock_t _timeScore; clock_t _lastTime; int _difficultyLevel; unsigned int _superFancyPoints; GameEntity _scenery[STARS_NB]; void initScenery(void); void manageCollisionsWith(GameEntity *entity, GameEntity *list); static void resizeHandler(int sig); public: GameMaster(void); ~GameMaster(void); /* Members functions */ void getKey(void); int getCharacter(void); int getDifficultyLevel(void); void movePlayer(void); void moveEnnemies(void); void moveShoots(void); bool checkPlayerCollision(void); void spawnEntity(void); void destroyEntitiesCollision(GameEntity ** start); void destroyEntities(GameEntity ** start); void displayAllEntities(void); void displayBanner(void); void displayScenery(void); bool gameOverBanner(void); void refreshWindow(void); /* Attributes */ GameEntity *ennemies; GameEntity *shoots; }; #endif <file_sep>#!/usr/bin/php <?PHP if ($argc >= 2) { $str = file_get_contents($argv[1]); echo $str."\n\n"; //$str = preg_replace("/<a.*\/a>/isU", "COCO", $str); //preg_match_all("/<a.*>(.*)<.*a>/isU", $str, $tab); //print_r($tab); //preg_match_all("/<a.*title=(.*)[ >].*a>/isU", $str, $tab); //print_r($tab); //$str = preg_replace("/<a(.*)a>/isU", "COCO", $str); preg_match_all("/<a.*>(.*)<.*a>/isU", $str, $tab); print_r($tab); preg_match_all("/<a.*title=\"(.*)\".*a>/isU", $str, $tab); print_r($tab); // echo $str."\n"; } ?> <file_sep>#include <stdio.h> int ft_max(int *tab, int length); int main(void) { int tab[6] = {1, 2, 178, -45, 12457, 0}; printf("%d\n", ft_max(tab, 6)); return (0); } <file_sep>#include "ZombieEvent.hpp" int main ( void ) { ZombieEvent zombies_party; std::cout << "----- WITH RANDOM CHUMP -----" << std::endl; Zombie *z1 = zombies_party.randomChump();; std::cout << std::endl; Zombie *z2 = zombies_party.randomChump();; std::cout << std::endl; Zombie *z3 = zombies_party.randomChump();; std::cout << "-----------------------------" << std::endl; std::cout << std::endl << "Changing the type from green to lazy..." << std::endl; zombies_party.setZombieType("lazy"); std::cout << std::endl << "------ WITH NEW ZOMBIE ------" << std::endl; Zombie *z4 = zombies_party.newZombie("tata yoyo"); std::cout << "Using announce method :" << std::endl; z4->announce(); std::cout << "-----------------------------" << std::endl << std::endl; delete(z1); delete(z2); delete(z3); delete(z4); return 0; }<file_sep>#!/usr/bin/php <?PHP include("ft_split.php"); print_r(ft_split("* Hello a World A AA *** a ")); echo "\n"; print_r(ft_split(" AA ")); echo "\n"; print_r(ft_split("")); echo "\n"; print_r(ft_split(" ")); echo "\n"; print_r(ft_split(NULL)); ?> <file_sep> #include "GameEntity.hpp" #include <ncurses.h> /* UNUSED */ GameEntity::GameEntity(void): _shape("*"), collided(false), next(NULL) { this->_pos.x = COLS; this->_pos.y = LINES/2; this->_dir.x = 1; this->_dir.y = 1; } GameEntity::GameEntity( std::string shape, int px, int py, int dx, int dy, GameEntity *next) : _shape(shape), collided(false), next(next) { this->_pos.x = px; this->_pos.y = py; this->_dir.x = dx; this->_dir.y = dy; } GameEntity::~GameEntity(void) { } /* UNUSED */ GameEntity::GameEntity(GameEntity const &Cc) { *this = Cc; } /* UNUSED */ GameEntity &GameEntity::operator = (GameEntity const &Cc) { if (&Cc == this) return *this; this->_shape = Cc._shape; this->_pos.x = Cc._pos.x; this->_pos.y = Cc._pos.y; return *this; } std::string GameEntity::getShape(void) const { return this->_shape; } int GameEntity::getShapeSize(void) const { return this->_shape.size(); } int GameEntity::getPosX(void) const { return this->_pos.x; } int GameEntity::getPosY(void) const { return this->_pos.y; } bool GameEntity::setShape(std::string shape) { this->_shape = shape; return true; } bool GameEntity::setPosition(int x, int y) { this->_pos.x = x; this->_pos.y = y; return true; } bool GameEntity::updatePosition(int winX, int winY) { if (this->collided == true) return true; this->_pos.x += this->_dir.x; this->_pos.y += this->_dir.y; if (this->_pos.x > winX - 2 || this->_pos.x < 2) { this->collided = true; return false; } if (this->_pos.y > winY - 2 || this->_pos.y < 1) { this->collided = true; return false; } return true; } bool GameEntity::checkCollision(GameEntity *entity) { if (this == entity || entity->collided == true || this->collided == true) return false; int x = entity->getPosX(); int y = entity->getPosY(); if (this->_pos.x == x && this->_pos.y == y) { return true; // collision happened } return false; // no collision } <file_sep>#include "ZombieEvent.hpp" ZombieEvent::ZombieEvent ( void ) : _type("green") { srand (time(NULL)); std::cout << "ZombieEvent created." << std::endl << std::endl; return ; } ZombieEvent::~ZombieEvent () { std::cout << std::endl << "ZombieEvent destroyed." << std::endl; return ; } void ZombieEvent::setZombieType(std::string new_type) { this->_type = new_type; return ; } Zombie* ZombieEvent::newZombie(std::string name) const { Zombie *new_zombie = new Zombie( name, this->_type ); return new_zombie; } Zombie* ZombieEvent::randomChump( void ) const { std::string pool[4] = { "toto", "titi", "tutu", "tata" }; int r = rand() % 4; Zombie *new_zombie = this->newZombie(pool[r]); new_zombie->announce(); return new_zombie; }<file_sep>#include <stdio.h> #include <string.h> char *ft_strncat(char *dest, char *src, int nb); int main(void) { char str1[34] = "test"; char str2[] = "bonjour"; char str3[34] = "test"; char str4[] = "bonjour"; int n; n = 6; //printf("%s %s\n", str1, str2); printf("%s \n", ft_strncat(str1, str2, n)); printf("%s \n", strncat(str3, str4, n)); return (0); } <file_sep><?php Class NightsWatch { public $fighters = array(); public function recruit($perso) { //if (method_exists($perso, "fight") == TRUE) $this->fighters[] = $perso; } public function fight() { if ($this->fighters) { foreach($this->fighters as $elem) { if (method_exists($elem, "fight") == TRUE) $elem->fight(); } } } } ?> <file_sep>#include <stdio.h> #include <string.h> unsigned int ft_strlcat(char *dest, char *src, unsigned int size); int main(void) { char str1[40] = "clementine"; char str2[] = "elsa"; char str3[40] = "clementine"; char str4[] = "elsa"; int n; n = 12; printf("%s %s\n", str1, str2); printf("%d \n", ft_strlcat(str1, str2, n)); printf("%ld \n", strlcat(str3, str4, n)); printf("%s\n", str1); printf("%s\n", str3); return (0); } <file_sep>#include "ft_list.h" #include <stdio.h> void ft_putstr(char *str); int ft_putchar(char c); t_list *ft_list_push_params(int ac, char **av); void ft_list_foreach(t_list *begin_list, void (*f)(void *)); void ft_putTEST(void *str) { printf("%s", str); } void ft_printlist(t_list *list) { while (list != 0) { ft_putstr(list->data); ft_putchar('\n'); list = list->next; } } int main(int argc, char **argv) { t_list *list; //(void)argv; //(void)argc; list = 0; list = ft_list_push_params(argc, argv); ft_printlist(list); ft_putchar('\n'); ft_list_foreach(list, &ft_putTEST); return (0); } <file_sep>#include <unistd.h> int ft_putchar(char c); int ft_putchar(char c) { write(1, &c, 1); return (0); } void ft_print_comb2(void) { int i; int j; i = -1; j = 1; while (i++ <= 97) { while (j <= 99) { ft_putchar('0' + i / 10); ft_putchar('0' + i % 10); ft_putchar(' '); ft_putchar('0' + j / 10); ft_putchar('0' + j % 10); ft_putchar(','); ft_putchar(' '); j++; } j = i + 2; } ft_putchar('0' + i / 10); ft_putchar('0' + i % 10); ft_putchar(' '); ft_putchar('0' + (j - 1) / 10); ft_putchar('0' + (j - 1) % 10); } /*void ft_print_comb2(void) { char number1; char number2; char number3; char number4; number1 = '0'; number2 = '0'; number3 = '0'; number4 = '1'; while (number1 <= '9') { while (number2 <= '8') { while (number3 <= '9') { while (number4 <= '9') { ft_putchar(number1); ft_putchar(number2); ft_putchar(' '); ft_putchar(number3); ft_putchar(number4); ft_putchar(','); ft_putchar(' '); number4++; } number3++; number4 = '0'; ft_putchar('\n'); } number2++; number3 = '0'; } number1++; number2 = '0'; } }*/ int main(void) { ft_print_comb2(); return (0); } <file_sep>#ifndef FRAGTRAP_HPP # define FRAGTRAP_HPP # include <iostream> # include "ClapTrap.hpp" class FragTrap : public ClapTrap { public: FragTrap( void ); FragTrap( std::string const & name ); FragTrap( FragTrap const & src ); ~FragTrap( void ); FragTrap & operator=( FragTrap const & rhs ); void vaulthunter_dot_exe( std::string const & target ); private: void (FragTrap::*_specialAttacks[5])( std::string const & target ); void initSpecialAttacks( void ); void trempette( std::string const & target ); void frenchBaguette( std::string const & target ); void expelliarmus( std::string const & target ); void turtleShell( std::string const & target ); void kamehameha( std::string const & target ); }; #endif<file_sep>#!/usr/bin/php <?PHP if ($argc == 2) { if (strstr($argv[1], "*") != FALSE) { $tab = explode("*", $argv[1]); $op = "*"; } else if (strstr($argv[1], "/") != FALSE) { $tab = explode("/", $argv[1]); $op = "/"; } else if (strstr($argv[1], "%") != FALSE) { $tab = explode("%", $argv[1]); $op = "%"; } else if (strstr($argv[1], "+") != FALSE) { $tab = explode("+", $argv[1]); $op = "+"; } else if (strstr($argv[1], "-") != FALSE) { $tab = explode("-", $argv[1]); $op = "-"; } if (count($tab) != 2) { echo "Syntax Error\n"; return ; } $elem1 = trim($tab[0]); $elem2 = trim($tab[1]); if (is_numeric($elem1) == TRUE && is_numeric($elem2) == TRUE) { if ($op == "+") echo $elem1 + $elem2."\n"; else if ($op == "-") echo $elem1 - $elem2."\n"; else if ($op == "*") echo $elem1 * $elem2."\n"; else if ($op == "/" && intval($elem2) != "0") echo $elem1 / $elem2."\n"; else if ($op == "%" && intval($elem2) != "0") echo $elem1 % $elem2."\n"; } else echo "Syntax Error\n"; } else echo "Incorrect Parameters\n"; ?> <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/23 12:35:53 by curquiza #+# #+# */ /* Updated: 2016/08/23 18:06:47 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/uio.h> #define SIZE 1 int ft_strlen(char *str) { int count; count = 0; while (str[count] != '\0') count++; return (count); } void ft_putstr(char *str) { write(1, str, ft_strlen(str)); } int ft_atoi(char *str) { int test_neg; int i; int result; i = 0; test_neg = 1; result = 0; while (str[i] == '\n' || str[i] == '\t' || str[i] == ' ') i++; if (str[i] == '+') i++; else if (str[i] == '-') { test_neg = -1; i++; } while (str[i] >= 48 && str[i] <= 57) { result = result * 10; result = result + str[i] - 48; i++; } return (test_neg * result); } void ft_print_header(int argc, char *argv) { if (argc > 4) { write(1, "==> ", 4); write(1, argv, ft_strlen(argv)); write(1, " <==\n", 5); } } int ft_read(int argc, char *argv, int fd, int c) { int ret; int length; int cpt; char buf[SIZE + 1]; ret = 0; ft_print_header(argc, argv); length = 0; while ((ret = read(fd, buf, SIZE)) != 0) length++; if(close(fd) == -1) return (0); fd = open(argv, O_RDONLY); cpt = 0; while ((ret = read(fd, buf, SIZE)) != 0) { cpt++; buf[ret] = '\0'; if (cpt > length - c) ft_putstr(buf); } if(close(fd) == -1) return (0); return (1); } int main(int argc, char **argv) { int fd; int i; int c; if (argc < 4) return (0); c = ft_atoi(argv[2]); if (c < 0) c = c * -1; i = 3; while (i < argc) { if((fd = open(argv[i], O_RDONLY)) == -1) { write(1, "tail: ", 6); write(1, argv[i], ft_strlen(argv[i])); write(1, ": No such file or directory\n", 28); } else ft_read(argc, argv[i], fd, c); i++; } return(0); } <file_sep>#include "Pony.hpp" void ponyOnTheStack( void ) { std::cout << "-- PONY ON THE STACK --" << std::endl; Pony pony = Pony("coco", "blue"); std::cout << "Current coat : " << pony.getCoat() << std::endl; std::cout << "The poney is getting a new green coat !!" << std::endl; pony.setCoat("green"); std::cout << "New coat : " << pony.getCoat() << std::endl; std::cout << "-- end of PONY ON THE STACK --" << std::endl; } void ponyOnTheHeap( void ) { std::cout << "-- PONY ON THE HEAP --" << std::endl; Pony *pony = new Pony("titi", "brown"); std::cout << "Current kindness : " << pony->getKindness() << "/10" << std::endl; std::cout << "The poney is getting kindier !!" << std::endl; pony->setKindness(11); std::cout << "New kindness : " << pony->getKindness() << "/10 !!!" << std::endl; delete(pony); std::cout << "-- end of PONY ON THE STACK --" << std::endl; } int main(void) { ponyOnTheStack(); std::cout << std::endl; ponyOnTheHeap(); return 0; }<file_sep>#!/usr/bin/php <?PHP function ft_get_month($str) { $str = strtolower($str); $tab = array("janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "aout", "septembre", "octobre", "novembre", "decembre"); $i = 0; foreach($tab as $elem) { if ($elem == $str) return ($i + 1); $i++; } return (0);; } if ($argc >= 2) { $tab = explode(" ", $argv[1]); if (count($tab) != 5) { echo "Wrong Format\n"; return ; } if (preg_match("/^([Ll]undi|[Mm]ardi|[Mm]ercredi|[Jj]eudi|[Vv]endredi|[Ss]amedi|[Dd]imanche)$/", $tab[0]) == 0) { echo "Wrong Format\n"; return ; } if (preg_match("/^[0-9]{1,2}$/", $tab[1]) == 0) { echo "Wrong Format\n"; return ; } if (preg_match("/^([Jj]anvier|[Ff]evrier|[Mm]ars|[Aa]vril|[Mm]ai|[Jj]uin|[Jj]uillet|[Aa]out|[Ss]eptembre|[Oo]ctobre|[Nn]ovembre|[Dd]ecembre)$/", $tab[2]) == 0) { echo "Wrong Format\n"; return ; } if (preg_match("/^[0-9]{4}$/", $tab[3]) == 0) { echo "Wrong Format\n"; return ; } if (preg_match("/^[0-9]{2}:[0-9]{2}:[0-9]{2}$/", $tab[4]) == 0) { echo "Wrong Format\n"; return ; } $month = ft_get_month($tab[2]); if (checkdate($month, $tab[1], $tab[3]) === FALSE) { echo "Wrong Format\n"; return ; } $str = $tab[3]."-".$month."-".$tab[1]." ".$tab[4]; date_default_timezone_set("Europe/Paris"); $rslt = strtotime($str); if ($rslt === FALSE) echo "Wrong Format\n"; else echo $rslt."\n"; } ?> <file_sep>NAME = convert FLAGS = -Wall -Wextra -Werror -std=c++98 CC = clang++ C_FILES = Var.cpp main.cpp O_FILES = $(C_FILES:%.cpp=%.o) ################################################################################ #################################### RULES ##################################### ################################################################################ all : $(NAME) $(NAME) : $(O_FILES) @$(CC) $(FLAGS) $(O_FILES) -o $@ $(LIB) @echo "\033[1;31m-- EXEC ------------------------\033[0m" @printf "%-45s\033[1;32m%s\033[0m\n" "Make $@" "OK" %.o: %.cpp @$(CC) $(FLAGS) -o $@ -c $< @printf "%-45s\033[1;32m%s\033[0m\n" "Make $@" "OK" clean : @rm -rf $(O_FILES) fclean : clean @rm -rf $(NAME) re : fclean all .PHONY : clean all fclean re <file_sep>#include <stdio.h> #include <string.h> int ft_str_is_numeric(char *str); int main(void) { char str1[] = "4578455"; printf("%s \n", str1); printf("%d \n", ft_str_is_numeric(str1)); return (0); } <file_sep>#include <fcntl.h> #include <sys/types.h> #include <sys/uio.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define SIZE 100 int main(void) { int fd; int ret; char *buffer; buffer = (char *)malloc(sizeof(char) * (SIZE + 1)); fd = open("TRUC", O_RDWR | O_CREAT | O_APPEND, S_IRWXU); if (fd == -1) { printf("erreur1"); return (0); } /* if (write(fd, "truc", 4) == -1) { printf("erreur2"); return (0); }*/ ret = read(fd, buffer, SIZE); if (ret == -1) { printf("erreur3"); return (0); } buffer[ret] = '\0'; printf("%s\n", buffer); printf("%d", ret); if (close(fd) == -1) { printf("erreur4"); return (0); } } <file_sep>#!/usr/bin/php <?PHP function ft_split($str) { $tab_vide = array(""); $tab = explode(" ", $str); $tab = array_diff($tab, $tab_vide); $tab = array_values($tab); return ($tab); } function ft_print_array($tab) { foreach ($tab as $tab) echo $tab."\n"; } function ft_index($c) { $tab = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", " ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "[", "\\", "]", "^", "_", "`", "{", "|", "}", "~"); $i = 0; foreach($tab as $tmp) { if ($tmp == $c) return ($i); $i++; } } function ft_compare($elem1, $elem2) { $tmp1 = strtolower($elem1); $tmp2 = strtolower($elem2); $i = 0; while ($tmp1[$i] != NULL && $tmp2[$i] != NULL && $tmp1[$i] == $tmp2[$i]) $i++; return (ft_index($tmp1[$i]) - ft_index($tmp2[$i])); } if ($argv[1] != NULL) { $i = 0; foreach ($argv as $argv) { if ($i != 0) $str = $str." ".$argv; $i++; } $tab = ft_split($str); usort($tab, "ft_compare"); ft_print_array($tab); } ?> <file_sep>#include <stdio.h> void ft_ft(int *nbr) { *nbr = 42; } int main(void) { int *ptr; ft_ft(ptr); printf("%d", *ptr); return (0); } <file_sep>#include "phonebook.hpp" int Contact::_count = 0; Contact::Contact (void) { this->_index = std::to_string(Contact::getCount()); Contact::incCount(); return ; } Contact::~Contact (void) { return ; } void Contact::setField (std::string line, int field) { switch (field) { case FIRST_NAME: this->_first_name = line; break; case LAST_NAME: this->_last_name = line; break; case NICKNAME: this->_nickname = line; break; case LOGIN: this->_login = line; break; case POSTAL_ADDRESS: this->_postal_address = line; break; case EMAIL_ADDRESS: this->_email_address = line; break; case PHONE_NUMBER: this->_phone_number = line; break; case BIRTHDAY_DATE: this->_birthday_date = line; break; case FAVORITE_MEAL: this->_favorite_meal = line; break; case UNDERWEAR_COLOR: this->_underwear_color = line; break; case DARKEST_SECRET: this->_darkest_secret = line; break; } } std::string Contact::getField (int field) const { switch (field) { case INDEX: return (this->_index); break; case FIRST_NAME: return (this->_first_name); break; case LAST_NAME: return (this->_last_name); break; case NICKNAME: return (this->_nickname); break; case LOGIN: return (this->_login); break; case POSTAL_ADDRESS: return (this->_postal_address); break; case EMAIL_ADDRESS: return (this->_email_address); break; case PHONE_NUMBER: return (this->_phone_number); break; case BIRTHDAY_DATE: return (this->_birthday_date); break; case FAVORITE_MEAL: return (this->_favorite_meal); break; case UNDERWEAR_COLOR: return (this->_underwear_color); break; case DARKEST_SECRET: return (this->_darkest_secret); break; } return (NULL); } // STATIC int Contact::getCount(void) { return (Contact::_count); } void Contact::incCount(void) { Contact::_count += 1; return ; }<file_sep>#include <stdio.h> void ft_ultimate_div_mod(int *a, int *b) { int buffer_a; int buffer_b; buffer_a = *a; buffer_b = *b; *a = buffer_a / buffer_b; *b = buffer_a % buffer_b; } int main(void) { int a; int b; a = 10; b = 3; ft_ultimate_div_mod(&a, &b); printf("a=%d b=%d", a, b); return (0); } <file_sep>#include <stdio.h> #include <string.h> int ft_str_is_printable(char *str); int main(void) { char str1[] = "d jdjd"; printf("%s \n", str1); printf("%d \n", ft_str_is_printable(str1)); return (0); } <file_sep>#include <stdio.h> #include <string.h> unsigned int ft_strlcpy(char *dest, char *src, unsigned int size); int main(void) { char str1[40] = "elsaelsa"; char str2[] = "auroreetclem"; char str3[40] = "elsaelsa"; char str4[] = "auroreetclem"; unsigned int n; n = 9; printf("%d\n", ft_strlcpy(str1, str2, n)); printf("%ld\n", strlcpy(str3, str4, n)); printf("%s %s\n", str1, str2); printf("%s %s\n", str3, str4); return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/23 18:07:45 by curquiza #+# #+# */ /* Updated: 2016/08/23 19:49:24 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/uio.h> #include "ft_basic.h" void ft_multi_arg(char *str, int i) { if (i > 3) write(1, "\n", 1); write(1, "==> ", 4); write(1, str, ft_strlen(str)); write(1, " <==\n", 5); } int ft_nbr_octet(char *str) { int nbr; int ret; int fd; char buf[2]; fd = open(str, O_RDONLY); nbr = 0; if (fd != 1) { while ((ret = read(fd, buf, 1))) { buf[ret] = '\0'; nbr = nbr + ret; } } close(fd); return (nbr); } void ft_print(int nbr_octet, char *src) { int ret; int fd; char buf[2]; int i; i = 0; if ((fd = open(src, O_RDONLY)) == 1) return ; while ((ret = read(fd, buf, 1))) { buf[ret] = '\0'; if (i >= nbr_octet - 1) write(1, buf, ft_strlen(buf)); i++; } close(fd); } int main(int argc, char **argv) { int nbr_octet; int i; if (argc < 4) { write(2, "tail: option requires an argument -- c\n", 39); return (0); } if (ft_strcmp(argv[1], "-c") != 0) return (0); i = 3; while (i < argc) { if (argc > 4) ft_multi_arg(argv[i], i); nbr_octet = ft_nbr_octet(argv[i]); if (argv[2][0] == '+') ft_print(ft_atoi(argv[2]), argv[i]); else ft_print(nbr_octet + 1 - ft_abs(ft_atoi(argv[2])), argv[i]); i++; } return (0); } <file_sep>SOURCES = atom.ml \ main.ml OCAMLMAKEFILE = OCamlMakefile include $(OCAMLMAKEFILE) <file_sep>#include "ft_list.h" #include <stdio.h> #include <stdlib.h> void ft_putstr(char *str); int ft_putchar(char c); int ft_strcmp(char *s1, char *s2); t_list *ft_list_push_params(int ac, char **av); void ft_list_merge(t_list **begin_list1, t_list *begin_list2); void ft_putTEST(void *str) { printf("%s", str); } void ft_printlist(t_list *list) { while (list != 0) { ft_putstr(list->data); ft_putchar('\n'); list = list->next; } } int main(int argc, char **argv) { t_list *list1; t_list *list2; //(void)argv; //(void)argc; list1 = 0; list1 = ft_list_push_params(argc, argv); list2 = 0; list2 = ft_list_push_params(argc, argv); ft_printlist(list1); ft_putchar('\n'); ft_printlist(list2); ft_putchar('\n'); ft_list_merge(&list1, list2); ft_printlist(list1); return (0); } <file_sep>#ifndef CLAPTRAP_HPP # define CLAPTRAP_HPP # include <iostream> class ClapTrap { public: ClapTrap( void ); ClapTrap( unsigned int hitPoints, unsigned int MaxHitPoints, unsigned int energyPoints, unsigned int MaxEnergyPoints, unsigned int level, std::string const & name, unsigned int meleeAttackDamage, unsigned int rangedAttackDamage, unsigned int armorDamageReducton ); ClapTrap( ClapTrap const & src ); ~ClapTrap( void ); std::string getName ( void ) const; ClapTrap & operator=( ClapTrap const & rhs); void rangedAttack( std::string const & target ) const; void meleeAttack( std::string const & target ) const; void takeDamage( unsigned int amount ); void beRepaired( unsigned int amount ); protected: unsigned int _hitPoints; unsigned int _MaxHitPoints; unsigned int _energyPoints; unsigned int _MaxEnergyPoints; unsigned int _level; std::string _name; unsigned int _meleeAttackDamage; unsigned int _rangedAttackDamage; unsigned int _armorDamageReducton; private: }; #endif<file_sep>#include <stdio.h> #include <string.h> char *ft_strcat(char *dest, char *src); int main(void) { char str1[34] = "clem"; char str2[] = "elsa"; char str3[34] = "clem"; char str4[] = "elsa"; printf("%s %s\n", str1, str2); printf("%s \n", ft_strcat(str1, str2)); printf("%s \n", strcat(str3, str4)); return (0); } <file_sep>EXEC = tic-tac-toe SOURCES = Game.ml Eval.ml Move.ml IA.ml Draw.ml main.ml OCAMLMAKEFILE = OCamlMakefile include $(OCAMLMAKEFILE) <file_sep>#include <stdio.h> void ft_div_mod(int a, int b, int *div, int *mod) { *div = a / b; *mod = a % b; } int main(void) { int a; int b; int div; int mod; a = -10; b = -3; ft_div_mod(a, b, &div, &mod); printf("a=%d b=%d div=%d et mod=%d", a, b, div, mod); return (0); } <file_sep><?php //Class Tyrion extends Lannister { // function __construct() { // $this->isCersei = FALSE; // } //} Class Tyrion extends Lannister { } ?> <file_sep>#include <stdio.h> #include <string.h> char *ft_strlowcase(char *str); int main(void) { char str1[] = "HeLLo LEs 42 !!!!"; printf("%s \n", str1); printf("%s \n", ft_strlowcase(str1)); return (0); } <file_sep>#include "GameMaster.hpp" #include "NastyFive.hpp" #include <ncurses.h> #include <signal.h> #include <cstdlib> #include <ctime> #include <unistd.h> GameMaster::GameMaster(void) : _ch(0), _nEntities(0), _begin_time(clock()), _timeScore(0), _lastTime(0), _difficultyLevel(DIFFICULTY_LEVEL), _superFancyPoints(0), ennemies(NULL), shoots(NULL) { initscr(); if (LINES < MIN_TERM_Y || COLS < MIN_TERM_X) { endwin(); std::cerr << "Error : the window is too small." << std::endl; exit(1); } noecho(); cbreak(); // non-blocking manner: it will return ERR if the key input is not ready nodelay(stdscr, TRUE); keypad(stdscr, TRUE); curs_set(FALSE); this->_winY = LINES - (LINES/2); this->_winX = COLS - (LINES/2); this->_win = subwin(stdscr, this->_winY, this->_winX, WINBOXY, WINBOXX); box(_win, '|', '-'); /* this->ennemies = NULL; this->shoots = NULL; this->_nEntities = 0; this->_difficultyLevel = DIFFICULTY_LEVEL; this->_lastTime = 0; */ this->initScenery(); signal(SIGWINCH, &GameMaster::resizeHandler); } GameMaster::~GameMaster(void) { endwin(); /* debug */ /* GameEntity *p = this->ennemies; int i = 0; while (p) { i++; p = p->next; } p = this->shoots; int j = 0; while (p) { j++; p = p->next; } std::cout << "CHAR: " << this->_ch <<std::endl; std::cout << "ENNEMIES: " << i <<std::endl; std::cout << "SHOOTS: " << j <<std::endl; std::cout << "LINES: " << LINES <<std::endl; std::cout << "COLS: " << COLS <<std::endl; std::cout << "_WINX: " << this->_winX <<std::endl; std::cout << "_WINY: " << this->_winY <<std::endl; */ } void GameMaster::resizeHandler(int sig) { if (sig == SIGWINCH) { endwin(); std::cerr << "Error : resize during the game." << std::endl; exit(1); } } void GameMaster::getKey(void) { this->_ch = getch(); } int GameMaster::getCharacter(void) { return this->_ch; } int GameMaster::getDifficultyLevel(void) { return this->_difficultyLevel; } void GameMaster::spawnEntity(void) { srand(std::time(0) * std::time(0)); int r = rand() % this->_winY; this->_nEntities++; if (this->ennemies) { if (r % 2) this->ennemies = new GameEntity("(", this->_winX - 2, r, -1, 0, this->ennemies); else this->ennemies = new NastyFive("5", this->_winX - 2, r, -1, 0, this->ennemies); } else { this->ennemies = new GameEntity("(", this->_winX - 2, r, -1, 0, NULL); } } bool GameMaster::gameOverBanner(void) { int c = 0; std::string msg = " GAMEOVER "; mvwprintw(this->_win, (this->_winY / 2) - 5, (this->_winX / 2) - 10, msg.c_str()); msg = " Replay ? (Y/y) "; mvwprintw(this->_win, (this->_winY / 2) - 4, (this->_winX / 2) - 10, msg.c_str()); wrefresh(this->_win); c = getchar(); //while (c == KEY_LEFT || c == KEY_RIGHT || c == KEY_UP || c == KEY_DOWN || c == ' ') while (c == ' ') { c = getchar(); } msg = " "; mvwprintw(this->_win, (this->_winY / 2) - 5, (this->_winX / 2) - 10, msg.c_str()); mvwprintw(this->_win, (this->_winY / 2) - 4, (this->_winX / 2) - 10, msg.c_str()); mvprintw(WINBOXY - 2, WINBOXX, " "); if (c == 'Y' || c == 'y') { // reinitialize all this->destroyEntities(&this->ennemies); this->destroyEntities(&this->shoots); mvwprintw(this->_win, this->_pl.getPosY(), this->_pl.getPosX(), " "); this->_pl.setPosition(2, 2); this->_begin_time = clock(); this->_timeScore = 0; this->_lastTime = clock(); this->_ch = 0; this->_nEntities = 0; this->_difficultyLevel = DIFFICULTY_LEVEL; this->_superFancyPoints = 0; return true; } return false; } void GameMaster::displayBanner(void) { std::string msg = " TIMESCORE: "; this->_timeScore = float(clock() - this->_begin_time); msg.append(std::to_string(this->_timeScore)); msg.append(" DIFFICULTY: "); msg.append(std::to_string(this->_difficultyLevel)); msg.append(" SUPERFANCYPOINTS: "); msg.append(std::to_string(this->_superFancyPoints)); mvprintw(WINBOXY - 2, WINBOXX, msg.c_str()); mvprintw(WINBOXY - 3, WINBOXX, " "); } void GameMaster::refreshWindow(void) { if (clock() - this->_lastTime > DIFFICULTY_SPEED) { if (this->_difficultyLevel > 10000) this->_difficultyLevel -= 50; this->_lastTime = clock(); } wrefresh(this->_win); } void GameMaster::manageCollisionsWith(GameEntity *entity, GameEntity *list) { GameEntity * current; current = list; while (current) { if (entity->checkCollision(current) == true) { current->collided = true; entity->collided = true; } current = current->next; } } void GameMaster::moveEnnemies(void) { GameEntity *ptr = this->ennemies; while (ptr) { mvwprintw(this->_win, ptr->getPosY(), ptr->getPosX(), " "); ptr->updatePosition(this->_winX, this->_winY); manageCollisionsWith(ptr, this->shoots); ptr = ptr->next; } } void GameMaster::moveShoots(void) { GameEntity *ptr = this->shoots; while (ptr) { mvwprintw(this->_win, ptr->getPosY(), ptr->getPosX(), " "); if (ptr->collided == false) { ptr->updatePosition(this->_winX, this->_winY); manageCollisionsWith(ptr, this->ennemies); } ptr = ptr->next; } } void GameMaster::displayScenery(void) { /* scenery */ for (int i = 0; i < STARS_NB; i++) { mvwprintw(this->_win, this->_scenery[i].getPosY(), this->_scenery[i].getPosX(), this->_scenery[i].getShape().c_str()); } } void GameMaster::displayAllEntities(void) { GameEntity *ptr; /* shoots */ ptr = this->shoots; while (ptr) { mvwprintw(this->_win, ptr->getPosY(), ptr->getPosX(), ptr->getShape().c_str()); ptr = ptr->next; } /* ennemies */ ptr = this->ennemies; while (ptr) { mvwprintw(this->_win, ptr->getPosY(), ptr->getPosX(), ptr->getShape().c_str()); ptr = ptr->next; } } void GameMaster::movePlayer(void) { GameEntity *tmp = NULL; mvwprintw(this->_win, this->_pl.getPosY(), this->_pl.getPosX(), " "); if (this->_ch == KEY_LEFT) { if (this->_pl.getPosX() > 2) this->_pl.setPosition(this->_pl.getPosX() - 1, this->_pl.getPosY()); } else if (this->_ch == KEY_RIGHT) { if (this->_pl.getPosX() < this->_winX - 3) this->_pl.setPosition(this->_pl.getPosX() + 1, this->_pl.getPosY()); } else if (this->_ch == KEY_UP) { if (this->_pl.getPosY() > 1) this->_pl.setPosition(this->_pl.getPosX(), this->_pl.getPosY() - 1); } else if (this->_ch == KEY_DOWN) { if (this->_pl.getPosY() < this->_winY - 2) this->_pl.setPosition(this->_pl.getPosX(), this->_pl.getPosY() + 1); } else if (this->_ch == ' ') { if (this->_pl.getPosX() < this->_winX - 3) { tmp = this->_pl.shoot(this->shoots); this->shoots = (tmp != NULL) ? tmp : this->shoots; } } mvwprintw(this->_win, this->_pl.getPosY(), this->_pl.getPosX(), this->_pl.getShape().c_str()); } bool GameMaster::checkPlayerCollision(void) { GameEntity *ptr; ptr = this->ennemies; while (ptr) { if (this->_pl.getPosX() == ptr->getPosX() && this->_pl.getPosY() == ptr->getPosY()) return true; ptr = ptr->next; } if (this->_pl.getPosX() >= this->_winX - 3) { this->_superFancyPoints++; mvwprintw(this->_win, this->_pl.getPosY(), this->_pl.getPosX(), " "); this->_pl.setPosition(2, this->_pl.getPosY()); } return false; } void GameMaster::destroyEntitiesCollision(GameEntity ** start) { GameEntity *current; GameEntity *suppr; if (*start != NULL) { current = *start; while (current->next != NULL) { if (current->next->collided == true) { suppr = current->next; current->next = current->next->next; delete suppr; this->_nEntities--; } else current = current->next; } if (*start != NULL) { if ((*start)->collided == true) { suppr = *start; *start = (*start)->next; delete suppr; this->_nEntities--; } } } } void GameMaster::initScenery(void) { int r_y; int r_x; srand(std::time(0)); for (int i = 0; i < STARS_NB; i++) { r_x = rand() % (this->_winX - 1); r_y = rand() % (this->_winY - 1); if (r_y <= 1) r_y++; if (r_x <= 1) r_x++; this->_scenery[i].setPosition(r_x, r_y); } } void GameMaster::destroyEntities(GameEntity ** start) { GameEntity *current; GameEntity *suppr; if (*start != NULL) { current = *start; while (current != NULL) { mvwprintw(this->_win, current->getPosY(), current->getPosX(), " "); suppr = current; current = current->next; delete suppr; } *start = NULL; } } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sudoku.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/13 10:10:49 by curquiza #+# #+# */ /* Updated: 2016/08/13 19:55:17 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> int ft_putchar(char c) { write(1, &c, 1); return (0); } int ft_ok_col(int grid[9][9], int value, int i, int j) { i = 0; while (i < 9) { if (grid[i][j] == value) return (0); i++; } return (1); } int ft_ok_row(int grid[9][9], int value, int i, int j) { j = 0; while (j < 9) { if (grid[i][j] == value) return (0); j++; } return (1); } int ft_ok_block(int grid[9][9], int value, int i, int j) { int i0; int j0; i0 = i - i % 3; j0 = j - j % 3; i = i0; j = j0; while (i < i0 + 3) { j = j0; while (j < j0 + 3) { if (grid[i][j] == value) return (0); j++; } i++; } return (1); } int ft_valid_place(int grid[9][9], int value, int i, int j) { if (ft_ok_col(grid, value, i, j) == 1 && ft_ok_row(grid, value, i, j) == 1 && ft_ok_block(grid, value, i, j) == 1) return (1); else return (0); } void ft_atoi_argv(char **argv, int grid[9][9]) { int i; int j; i = 0; j = 0; while (i < 9) { j = 0; while (j < 9) { if (argv[i + 1][j] >= '1' && argv[i + 1][j] <= '9') grid[i][j] = argv[i + 1][j] - '0'; else grid[i][j] = 0; j++; } i++; } } void ft_display_sudoku(int grid[9][9]) { int i; int j; i = 0; j = 0; while (i < 9) { j = 0; while (j < 9) { if (grid[i][j] <= 9) ft_putchar('0' + grid[i][j]); if (j != 8) ft_putchar(' '); j++; } ft_putchar('\n'); i++; } } int ft_solver_sudoku(int grid[9][9], int loc) { int k; int i; int j; k = 1; i = loc / 9; j = loc % 9; if (loc == 81) return (1); else if (grid[i][j] != 0) return (ft_solver_sudoku(grid, loc + 1)); while (k <= 9) { if (ft_valid_place(grid, k, i, j) == 1) { grid[i][j] = k; if (ft_solver_sudoku(grid, loc + 1) == 1) return (1); } k++; } grid[i][j] = 0; return (0); } int ft_check(char *str) { int i; i = 0; while (str[i] != '\0') { if ((str[i] < 49 || str[i] > 57) && str[i] != 46) return (0); i++; } if (i != 9) return (0); else return (1); } int main(int argc, char **argv) { int i; int grid[9][9]; i = 1; if (argc != 10) { write(1, "Error\n", 6); return (0); } while (i <= 9) { if (ft_check(argv[i]) == 0) { write(1, "Error\n", 6); return (0); } i++; } ft_atoi_argv(argv, grid); if (ft_solver_sudoku(grid, 0) == 0) write(1, "Error\n", 6); else ft_display_sudoku(grid); return (0); } <file_sep>SOURCES = try.ml OCAMLMAKEFILE = OCamlMakefile include $(OCAMLMAKEFILE) <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/23 09:57:10 by curquiza #+# #+# */ /* Updated: 2016/08/23 11:41:48 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/types.h> #define SIZE 10 void ft_putstr(char *str) { int i; i = 0; while (str[i] != '\0') i++; write(1, str, i); } int ft_strlen(char *str) { int count; count = 0; while (str[count] != '\0') count++; return (count); } void ft_print_error(char *argv) { write(1, "cat: ", 5); write(1, argv, ft_strlen(argv)); write(1, ": No such file or directory\n", 28); } int main(int argc, char **argv) { int i; int fd; int ret; char buf[SIZE + 1]; fd = 0; i = 1; if (argc == 1) return (0); while (argv[i]) { if ((fd = open(argv[i], O_RDONLY)) == -1) ft_print_error(argv[i]); else { while ((ret = read(fd, buf, SIZE)) != 0) { buf[ret] = '\0'; ft_putstr(buf); } if (close(fd) == -1) return (0); } i++; } } <file_sep>#include "Bureaucrat.hpp" #include "Form.hpp" #include "ShrubberyCreationForm.hpp" #include "RobotomyRequestForm.hpp" #include "PresidentialPardonForm.hpp" #include "Intern.hpp" int main(void) { Intern intern; Form * form1; Form * form2; Form * form3; Form * form4; std::cout << std::endl; std::cout << "\033[1;32mTrying to create president form : \033[0m" << std::endl; form1 = intern.makeForm("president pardon", "Titi"); std::cout << "\033[1;32mTrying to create robot form : \033[0m" << std::endl; form2 = intern.makeForm("robotomy request", "Tata"); std::cout << "\033[1;32mTrying to create shrubbery form : \033[0m" << std::endl; form3 = intern.makeForm("shrubbery creation", "Toto"); std::cout << "\033[1;32mTrying to create ramdom form : \033[0m" << std::endl; form4 = intern.makeForm("yo", "Toto"); std::cout << std::endl; std::cout << "\033[1;32mDisplaying all forms : \033[0m" << std::endl; std::cout << *form1 << std::endl; std::cout << "-----" << std::endl; std::cout << *form2 << std::endl; std::cout << "-----" << std::endl; std::cout << *form3 << std::endl; std::cout << std::endl; delete(form1); delete(form2); delete(form3); return (0); }<file_sep>#include <stdio.h> #include <string.h> int ft_strncmp(char *s1, char *s2, unsigned int n); int main(void) { char str1[] = " H"; char str2[] = " He"; int n; n = 3; printf("%s %s\n", str1, str2); printf("%d \n\n", ft_strncmp(str1, str2, n)); printf("%s %s\n", str1, str2); printf("%d \n", strncmp(str1, str2, n)); return (0); } <file_sep>#include <stdio.h> #include <string.h> char *ft_strdup(char *src); int main(int argc, char **argv) { if (argc != 2) return(0); printf("%s\n", strdup(argv[1])); printf("%s", ft_strdup(argv[1])); return (0); } <file_sep>#ifndef HUMAN_HPP # define HUMAN_HPP # include "Brain.hpp" class Human { public: Human(); ~Human(); Brain const & getBrain( void ) const; std::string identify( void ) const; private: const Brain _brain; }; #endif<file_sep># 42_PisicineOcaml Introduction to Ocaml - 42 school <file_sep>touch -A -000001 -a bomb.txt stat -s bomb.txt | cut -d " " -f 9 | cut -c 10- exec sh <file_sep>#include <stdio.h> #include <string.h> int ft_str_is_alpha(char *str); int main(void) { char str1[] = "ddkkd"; printf("%s \n", str1); printf("%d \n", ft_str_is_alpha(str1)); return (0); } <file_sep>#!/usr/bin/php <?PHP if ($argc == 4) { $elem1 = trim($argv[1]); $op = trim($argv[2]); $elem2 = trim($argv[3]); if ($op == "+") echo $elem1 + $elem2."\n"; else if ($op == "-") echo $elem1 - $elem2."\n"; else if ($op == "*") echo $elem1 * $elem2."\n"; else if ($op == "/" && intval($elem2) != "0") echo $elem1 / $elem2."\n"; else if ($op == "%" && intval($elem2) != "0") echo $elem1 % $elem2."\n"; } else echo "Incorrect Parameters\n"; ?> <file_sep>#include <unistd.h> int ft_putchar(char c) { write(1, &c, 1); return (0); } void ft_putnbr(int nb); int main(void) { ft_putnbr(0); ft_putchar('\n'); ft_putnbr(1); ft_putchar('\n'); ft_putnbr(-1); ft_putchar('\n'); ft_putnbr(12300); ft_putchar('\n'); ft_putnbr(10203); ft_putchar('\n'); ft_putnbr(-56); ft_putchar('\n'); ft_putnbr(2147483647); ft_putchar('\n'); ft_putnbr(-2147483648); ft_putchar('\n'); return (0); } <file_sep><?php Class Lannister { public $isLannister = TRUE; public function sleepWith($perso) { if (/*isset($perso->isLannister) == TRUE && */$perso->isLannister == TRUE) print ("Not even if I'm drunk !".PHP_EOL); else print ("Let's do this.".PHP_EOL); } } //Class Lannister { // public $isLannister = TRUE; // public $isCersei = TRUE; // // public function sleepWith($perso) // { // if (/*isset($perso->isLannister) == TRUE && */$perso->isLannister == TRUE) // print ("Not even if I'm drunk !".PHP_EOL); // else // print ("Let's do this.".PHP_EOL); // } //} ?> <file_sep><?php function ft_get_index($tab, $login, $oldpw) { $i = 0; foreach($tab as $elem) { if ($elem['login'] === $login) { if ($elem['passwd'] === $oldpw) return ($i); else return (-1); } $i++; } return (-1); } if ($_POST['submit'] === "OK" && $_POST['login'] != NULL && $_POST['oldpw'] != NULL && $_POST['newpw'] != NULL) { $oldpw = hash("sha512", $_POST['oldpw']); $newpw = hash("sha512", $_POST['newpw']); $login = $_POST['login']; if (file_exists("../private/passwd") === FALSE) { echo "ERROR\n"; return ; } $file = file_get_contents("../private/passwd"); $tab = unserialize($file); if (($i = ft_get_index($tab, $login, $oldpw)) === -1) { echo "ERROR\n"; return ; } $tab[$i]['passwd'] = $<PASSWORD>; $file = serialize($tab); file_put_contents("../private/passwd", $file."\n"); echo "OK\n"; } else echo "ERROR\n"; ?> <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_show_tab.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/16 17:32:09 by curquiza #+# #+# */ /* Updated: 2016/08/16 19:17:47 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_stock_par.h" void ft_putstr(char *str) { int i; i = 0; while (*(str + i) != '\0') { ft_putchar(*(str + i)); i++; } } void ft_putnbr(int nb) { int index; int tab[10]; index = 0; if (nb < 0) ft_putchar('-'); while (index < 10 && (nb >= 10 || nb <= -10)) { tab[index] = (nb % 10); nb = nb / 10; index++; } tab[index] = nb; while (index >= 0) { if (tab[index] < 0) ft_putchar((tab[index] * -1) + '0'); else ft_putchar(tab[index] + '0'); index--; } } void ft_show_tab(struct s_stock_par *par) { int i; int j; i = 0; while (par[i].str != 0) { ft_putstr(par[i].copy); ft_putchar('\n'); ft_putnbr(par[i].size_param); ft_putchar('\n'); j = 0; while (par[i].tab[j] != 0) { ft_putstr(par[i].tab[j]); ft_putchar('\n'); j++; } i++; } } <file_sep>#include "ft_btree.h" #include <stdlib.h> #include <unistd.h> int ft_strcmp(void *, void *); void btree_insert_data(t_btree **root, void *item, int (*cmpf)(void *, void *)); void ft_putstr(void *str); int main(void) { t_btree *tree; tree = 0; btree_insert_data(&tree, "2", &ft_strcmp); btree_insert_data(&tree, "3", &ft_strcmp); btree_insert_data(&tree, "4", &ft_strcmp); btree_insert_data(&tree, "1", &ft_strcmp); btree_insert_data(&tree, "0", &ft_strcmp); btree_insert_data(&tree, "1", &ft_strcmp); btree_apply_prefix(tree, &ft_putstr); } <file_sep>#include "ft_stock_par.h" int ft_strlen(char *str); char *ft_strdup(char *src); char **ft_split_whitespaces(char *str); int main(int argc, char **argv) { t_stock_par *tab; tab = ft_param_to_tab(argc, argv); ft_show_tab(tab); return (0); } <file_sep>#!/usr/bin/php <?PHP echo "Entrez un nombre: "; while (($nbr = fgets(STDIN)) != FALSE) { $nbr = trim($nbr); $numeric = is_numeric($nbr); if (strstr($nbr, "e") != FALSE || strstr($nbr, "E") != FALSE || strstr($nbr, ".") != FALSE) echo "'$nbr' n'est pas un chiffre\n"; else if ($numeric == FALSE) echo "'$nbr' n'est pas un chiffre\n"; else if (substr($nbr, -1) % 2 == 0) echo "Le chiffre $nbr est Pair\n"; else echo "Le chiffre $nbr est Impair\n"; echo "Entrez un nombre: "; } echo "\n"; ?> <file_sep> #include "NastyFive.hpp" NastyFive::NastyFive( std::string shape, int px, int py, int dx, int dy, GameEntity *next) : GameEntity(shape, px, py, dx, dy, next) { srand(time(0)); int r = rand(); if (r % 2) this->_dir.y = -1; else this->_dir.y = 1; } NastyFive::~NastyFive(void) { } bool NastyFive::updatePosition(int winX, int winY) { this->_pos.x += this->_dir.x; this->_pos.y += this->_dir.y; if (this->_pos.x > winX - 2) { this->_pos.x -= 1; } else if (this->_pos.x < 2) { this->collided = true; return false; } if (this->_pos.y > winY - 2) { this->_pos.y -= 1; this->_dir.y = -1; } if (this->_pos.y < 1) { this->_pos.y += 1; this->_dir.y = 1; } return true; } <file_sep>#include "Var.hpp" Var::Var( std::string const & str ) : _str(str), _type(UNDEFINED), _charVar(0), _intVar(0), _floatVar(0), _doubleVar(0), _indexLittValue(-1) { std::cout << "Constructor" << std::endl; initLittValueArray(); _type = getType(); if ( _type == CHAR ) _charVar = static_cast<char>(*(_str.begin())); if ( _type == INT ) _intVar = atoi(_str.c_str()); if ( _type == FLOAT ) _floatVar = strtod(_str.c_str(), NULL); if ( _type == DOUBLE ) _doubleVar = strtod(_str.c_str(), NULL); convChar(); convInt(); convFloat(); convDouble(); return ; } Var::~Var( void ) { std::cout << "Destructor" << std::endl; return; } void Var::initLittValueArray() { _floatLittValue[0] = "-inff"; _floatLittValue[1] = "+inff"; _floatLittValue[2] = "nanf"; _doubleLittValue[0] = "-inf"; _doubleLittValue[1] = "+inf"; _doubleLittValue[2] = "nan"; } /* DETECT TYPE */ int Var::getType() { for (int i = 0; i < LITT_VALUE_NB; i++) { if (_str == _floatLittValue[i] || _str == _doubleLittValue[i]) { _indexLittValue = i; std::cout << "c'est une VALEUR LITTERALE" << std::endl; return (LITT_VALUE); } } if (_str.find_first_not_of("-0123456789") == std::string::npos) { std::cout << "c'est un INT" << std::endl; return (INT); } if (_str.find_first_not_of("-0123456789.") == std::string::npos) { std::cout << "c'est un DOUBLE" << std::endl; return (DOUBLE); } if (_str.find_first_not_of("-0123456789.f") == std::string::npos && *(_str.end() - 1) == 'f') { std::cout << "c'est un FLOAT" << std::endl; return (FLOAT); } if (_str.length() == 1) { std::cout << "c'est un CHAR" << std::endl; return (CHAR); } std::cout << "c'est de la MERDE" << std::endl; return (UNDEFINED); } /* CONVERSION */ void Var::convChar() { if (_type == INT && _intVar >= SCHAR_MIN && _intVar <= SCHAR_MAX) _charVar = static_cast<char>(_intVar); if (_type == FLOAT && _floatVar >= SCHAR_MIN && _floatVar <= SCHAR_MAX) _charVar = static_cast<char>(_floatVar); if (_type == DOUBLE && _doubleVar >= SCHAR_MIN && _doubleVar <= SCHAR_MAX) _charVar = static_cast<char>(_doubleVar); } char * Var::getChar() { if (_type == CHAR) return (&_charVar); if (_type == INT && _intVar >= SCHAR_MIN && _intVar <= SCHAR_MAX) return (&_charVar); if (_type == FLOAT && _floatVar >= SCHAR_MIN && _floatVar <= SCHAR_MAX) return (&_charVar); if (_type == DOUBLE && _doubleVar >= SCHAR_MIN && _doubleVar <= SCHAR_MAX) return (&_charVar); return (NULL); } void Var::convInt() { if (_type == CHAR) _intVar = static_cast<int>(_charVar); if (_type == FLOAT && _floatVar >= INT_MIN && _floatVar <= INT_MAX) _intVar = static_cast<int>(_floatVar); if (_type == DOUBLE && _doubleVar >= INT_MIN && _doubleVar <= INT_MAX) _intVar = static_cast<int>(_doubleVar); } int * Var::getInt() { if (_type == CHAR) return (&_intVar); if (_type == INT) return (&_intVar); if (_type == FLOAT && _floatVar >= INT_MIN && _floatVar <= INT_MAX) return (&_intVar); if (_type == DOUBLE && _doubleVar >= INT_MIN && _doubleVar <= INT_MAX) return (&_intVar); return (NULL); } void Var::convFloat() { if (_type == CHAR) _floatVar = static_cast<float>(_charVar); if (_type == INT) _floatVar = static_cast<float>(_intVar); if (_type == DOUBLE && _doubleVar >= FLT_MIN && _doubleVar <= FLT_MAX) _floatVar = static_cast<float>(_doubleVar); } float * Var::getFloat() { if (_type == CHAR) return (&_floatVar); if (_type == INT) return (&_floatVar); if (_type == FLOAT) return (&_floatVar); if (_type == DOUBLE && _doubleVar >= FLT_MIN && _doubleVar <= FLT_MAX) return (&_floatVar); return (NULL); } void Var::convDouble() { if (_type == CHAR) _doubleVar = static_cast<double>(_charVar); if (_type == INT) _doubleVar = static_cast<double>(_intVar); if (_type == FLOAT) _doubleVar = static_cast<double>(_floatVar); } double * Var::getDouble() { if (_type == CHAR) return (&_doubleVar); if (_type == INT) return (&_doubleVar); if (_type == FLOAT ) return (&_doubleVar); if (_type == DOUBLE) return (&_doubleVar); return (NULL); } /* DISPLAY */ void Var::displayChar(std::ostream & o) { o << "char: "; if (getChar() != NULL) { if ( isprint(*getChar()) ) o << "'" << *getChar() << "'" << std::endl; else o << "Non displayable" << std::endl; } else o << "impossible" << std::endl; } void Var::displayInt(std::ostream & o) { o << "int: "; if (getInt() != NULL) o << *getInt() << std::endl; else o << "impossible" << std::endl; } void Var::displayFloat(std::ostream & o) { o << "float: "; if (_type == LITT_VALUE) o << _floatLittValue[_indexLittValue] << std::endl; else if (getFloat() != NULL) { std::cout.setf(std::ios::fixed,std::ios::floatfield); std::cout.precision(1); o << *getFloat() << "f" << std::endl; } else o << "impossible" << std::endl; } void Var::displayDouble(std::ostream & o) { o << "double: "; if (_type == LITT_VALUE) o << _doubleLittValue[_indexLittValue]; else if (getDouble() != NULL) { std::cout.setf(std::ios::fixed,std::ios::floatfield); std::cout.precision(1); o << *getDouble(); } else o << "impossible"; } /* OVERLOAD */ std::ostream & operator<<( std::ostream & o, Var & rhs ) { rhs.displayChar(o); rhs.displayInt(o); rhs.displayFloat(o); rhs.displayDouble(o); return o; } /* UNUSED */ Var::Var( void ) {} Var::Var( Var const & ) {} Var & Var::operator=( Var const & ) { return *this ; }<file_sep>#include "HeapManager.hpp" int main () { int i; HeapManager hm; unsigned char * raw; Data * data; std::cout << std::endl; raw = reinterpret_cast<unsigned char *>(hm.serialize()); std::cout << std::endl; std::cout << "---- CHECK VALUES ----" << std::endl; std::cout << "char 1 : "; for (i = CHAR1_START; i < CHAR1_END + 1; i++) { std::cout << *(raw + i); } std::cout << std::endl; std::cout << "int case par case en hex: "; for (i = INT_START; i < INT_START + 4; i++) { std::cout << std::hex << static_cast<int>(*(raw + i)); if (i != INT_START + 3) std::cout << ' '; } std::cout << std::endl; std::cout << std::dec << "int : " <<*(reinterpret_cast<int *>(raw + 8)) << std::endl; std::cout << "char 1 : "; for (i = CHAR2_START; i < CHAR2_END + 1; i++) { std::cout << *(raw + i); } std::cout << std::endl; std::cout << "----------------------" << std::endl; std::cout << std::endl; std::cout << "--- CHECK ADDRESSES --" << std::endl; for (i = 0; i < RAW_SIZE; i++) { std::cout << reinterpret_cast<void *>(raw + i) << std::endl; } std::cout << "----------------------" << std::endl; std::cout << std::endl; std::cout << "----- DESERIALIZE ----" << std::endl; data = hm.deserialize(reinterpret_cast<void *>(raw)); std::cout << "char 1 : " << data->s1 << std::endl; std::cout << "int : " << data->n << std::endl; std::cout << "char 2 : " << data->s2 << std::endl; std::cout << "----------------------" << std::endl; std::cout << std::endl; delete [] raw; delete data; return 0; } /* Reinterpret cast : la disposition des bits ne change pas. Le compilateur va juste re-interpreter la suite de bits */ /* Static cast : il y a une notion de conversion, les bits peuvent donc changer de place suite à cette conversion */<file_sep>#include <stdio.h> char *ft_rot42(char *str); int main (void) { char str[] = "ZagT"; printf("%s\n", ft_rot42(str)); return (0); } <file_sep>#include "span.hpp" Span::Span( unsigned int n ) : _N(n) { return ; } Span::~Span( void ) { return ; } void Span::addNumber(int num) { if (_vect.size() >= _N) throw std::length_error("impossible to add a element, max size reached"); _vect.push_back(num); } void Span::addVector(std::vector<int> & v) { if (v.size() + _vect.size() > _N) throw std::length_error("impossible to add a element, max size reached"); _vect.insert(_vect.begin(), v.begin(), v.end()); std::cout << v.size() << " elements added." << std::endl; } int Span::shortestSpan() { if (_vect.size() <= 1) throw std::logic_error("too few number inside the vector to calculate a span"); int min; std::vector<int>::iterator it = _vect.begin(); std::sort(_vect.begin(), _vect.end()); min = *(it + 1) - *it; for (it = _vect.begin(); it != _vect.end() - 1; it++) { if (*(it + 1) - *it < min) min = *(it + 1) - *it; } return (min); } int Span::longestSpan() { if (_vect.size() <= 1) throw std::logic_error("too few number inside the vector to calculate a span"); return (*max_element(_vect.begin(), _vect.end()) - *min_element(_vect.begin(), _vect.end())); } std::vector<int> & Span::getVect() { return _vect; } /* unused */ Span::Span( void ) {} Span::Span( Span const & ) {} Span & Span::operator=( Span const & ) { return *this ; } <file_sep>#include <iostream> /* template <typename T> void iter(T * array, size_t len, void (*f)(T &)) { for (size_t i = 0; i < len; i++) { f(array[i]); } return ; } */ /* template <typename T> void displayArray(T * array, size_t len) { for (size_t i = 0; i < len; i++) { std::cout << array[i]; if (i != len - 1) std::cout << ", "; } std::cout << std::endl; } */ /* template <typename T> void inc(T & i) { i++; } void cat(std::string & s) { s = s + " et le chat"; } */ template <typename T> void display(T & i) { std::cout << i << std::endl; } template <typename T> void iter(T * array, size_t len, void (*f)(T const &)) { for (size_t i = 0; i < len; i++) { f(array[i]); } return ; } int main(void) { std::cout << "----- INT -----" << std::endl; int intArray[3] = { 1, 2, -1 }; iter(intArray, 3, display); std::cout << std::endl; std::cout << "----- CHAR ----" << std::endl; char charArray[3] = { 'a', 'b', 'c' }; iter(charArray, 3, display); std::cout << std::endl; std::cout << "---- STRING ----" << std::endl; std::string stringArray[3] = { "titi", "toto", "tata" }; iter(stringArray, 3, display); return 0; }<file_sep>#include "mutantstack.hpp" #include <vector> #include <list> void displayInt(int n) { std::cout << " " << n; } template <typename T> void displayIntContainer(T & container) { std::for_each(container.begin(), container.end(), displayInt); std::cout << std::endl; } int main (void) { std::cout << "----- MY MAIN - STACK -----" << std::endl; { MutantStack<int, std::list<int> > m; m.push(1); m.push(2); m.push(3); m.push(4); m.push(9); std::cout << "current stack ="; displayIntContainer(m); std::cout << "begin = " << *m.begin() << std::endl; std::cout << "end = " << *(--m.end()) << std::endl; } std::cout << std::endl; std::cout << "----- MY MAIN - LIST -----" << std::endl; { std::list<int> l; l.push_back(1); l.push_back(2); l.push_back(3); l.push_back(4); l.push_back(9); std::cout << "current stack ="; displayIntContainer(l); std::cout << "begin = " << *l.begin() << std::endl; std::cout << "end = " << *(--l.end()) << std::endl; } std::cout << std::endl; std::cout << "----- ZAZ MAIN ----" << std::endl; { MutantStack<int> mstack; mstack.push(5); mstack.push(17); std::cout << "current stack ="; displayIntContainer(mstack); std::cout << "top = " << mstack.top() << std::endl; mstack.pop(); std::cout << "current stack after pop ="; displayIntContainer(mstack); std::cout << "size = " << mstack.size() << std::endl; mstack.push(3); mstack.push(5); mstack.push(737); //[...] mstack.push(0); std::cout << "current stack after pushes ="; displayIntContainer(mstack); std::cout << std::endl; std::cout << "Display with iterators :" << std::endl; MutantStack<int>::iterator it = mstack.begin(); MutantStack<int>::iterator ite = mstack.end(); ++it; --it; while (it != ite) { std::cout << *it << std::endl; ++it; } std::stack<int> s(mstack); } return 0; }<file_sep>ldapsearch -QLLL | grep sn: | cut -c 4- | grep -i bon | wc -l | tr -d " " <file_sep>#include "Fixed.hpp" #include <iostream> void comparisonOpTest( void ) { Fixed a(42); Fixed b(43); if ( (a > b) == false) std::cout << "> OK" << std::endl; else std::cout << "> KO" << std::endl; if ( (a < b) == true) std::cout << "< OK" << std::endl; else std::cout << "< KO" << std::endl; if ( (a >= b) == false) std::cout << ">= OK" << std::endl; else std::cout << ">= KO" << std::endl; if ( (a <= b) == true) std::cout << "<= OK" << std::endl; else std::cout << "<= KO" << std::endl; if ( (a == b) == false) std::cout << "== OK" << std::endl; else std::cout << "== KO" << std::endl; if ( (a != b) == true) std::cout << "!= OK" << std::endl; else std::cout << "!= KO" << std::endl; Fixed c( a + b); std::cout << c << std::endl; if ( c == 85) std::cout << "+ OK" << std::endl; else std::cout << "+ KO" << std::endl; Fixed d( a - b); std::cout << d << std::endl; if ( d == -1) std::cout << "- OK" << std::endl; else std::cout << "- KO" << std::endl; Fixed e( a * 2 ); std::cout << e << std::endl; if ( e == 84 ) std::cout << "* OK" << std::endl; else std::cout << "* KO" << std::endl; Fixed f( a / 2 ); std::cout << f << std::endl; if ( f == 21 ) std::cout << "/ OK" << std::endl; else std::cout << "/ KO" << std::endl; } void correctionTest() { // Fixed a; // Fixed const b( Fixed( 5.05f ) * Fixed( 2 ) ); // std::cout << a << std::endl; // std::cout << ++a << std::endl; // std::cout << a << std::endl; // std::cout << a++ << std::endl; // std::cout << a << std::endl; // std::cout << b << std::endl; // std::cout << Fixed::max( a, b ) << std::endl; } int main ( void ) { comparisonOpTest(); correctionTest(); return 0; }<file_sep>CREATE DATABASE IF NOT EXISTS db_curquiza; <file_sep>#include "ft_btree.h" #include <stdlib.h> int ft_strcmp(void *, void *); int main(void) { t_btree *tree; tree = 0; btree_insert_data(&tree, "2", &ft_strcmp); btree_insert_data(&tree, "3", &ft_strcmp); btree_insert_data(&tree, "4", &ft_strcmp); btree_insert_data(&tree, "1", &ft_strcmp); btree_insert_data(&tree, "0", &ft_strcmp); btree_insert_data(&tree, "1", &ft_strcmp); } <file_sep>#include <stdio.h> #include <string.h> char *ft_strncpy(char *dest, char *src, unsigned int n); int main(void) { char str1[50] = "clementine"; char str2[] = "on"; char str3[50] = "clementine"; char str4[] = "on"; printf("%s %s\n", str1, str2); ft_strncpy(str1, str2, 5); printf("%s %s\n\n", str1, str2); printf("%s %s\n", str3, str4); strncpy(str3, str4, 5); printf("%s %s\n", str3, str4); return (0); } <file_sep>#include "Fixed.hpp" Fixed::Fixed( void ) : _fpValue(0) { std::cout << "Default constructor called" << std::endl; return ; } Fixed::Fixed( Fixed const & src ) { std::cout << "Copy constructor called" << std::endl; *this = src; return ; } Fixed::~Fixed( void ) { std::cout << "Destructor called" << std::endl; return ; } Fixed & Fixed::operator=( Fixed const & rhs) { std::cout << "Assignation operator called" << std::endl; if ( this != &rhs ) this->_fpValue = rhs.getRawBits(); return *this ; } int Fixed::getRawBits( void ) const { std::cout << "getRawBits member function called" << std::endl; return this->_fpValue; } void Fixed::setRawBits( int const raw ) { this->_fpValue = raw; return ; } const int Fixed::_fractionnal = 8;<file_sep><?php function ft_exists_in_tab($tab, $login) { foreach ($tab as $elem) { if ($elem['login'] == $login) return (TRUE); } return (FALSE); } if ($_POST['submit'] === "OK" && $_POST['login'] != NULL && $_POST['passwd'] != NULL) { $pwd = $_POST['<PASSWORD>']; $pwd = <PASSWORD>("<PASSWORD>", $pwd); $login = $_POST['login']; $account = array('login' => $login, 'passwd' => $pwd); if (file_exists("../private") === FALSE) mkdir("../private"); if (file_exists("../private/passwd") === TRUE) { $file = file_get_contents("../private/passwd"); $tab = unserialize($file); if (ft_exists_in_tab($tab, $login) === FALSE) $tab[] = $account; else { echo "ERROR\n"; return ; } } else $tab = array($account); $file = serialize($tab); file_put_contents("../private/passwd", $file."\n"); echo "OK\n"; } else echo "ERROR\n"; ?> <file_sep>#!/usr/bin/php <?PHP function ft_split($str) { $tab_vide = array(""); $tab = explode(" ", $str); $tab = array_diff($tab, $tab_vide); $tab = array_values($tab); return ($tab); } if ($argv[1] != NULL) { $tab = ft_split($argv[1]); //$tmp = array($tab[0]); //$tab = array_diff($tab, $tmp); //$tab[] = $tmp[0]; //array_push($tab, $tmp[0]); //$tab = array_values($tab); //$str = implode(" ", $tab); //if ($str != NULL) // echo $str."\n"; $i = 0; foreach ($tab as $elem) { if ($i != 0) echo $elem." "; $i++; } if ($tab[0] != NULL) echo $tab[0]."\n"; } ?> <file_sep>#ifndef PONY_HPP # define PONY_HPP # include <iostream> class Pony { public: Pony( std::string name, std::string coat ); ~Pony(); std::string getCoat( void ) const; void setCoat( std::string new_coat ); int getKindness( void ) const; void setKindness( int new_kindness ); private: std::string _name; std::string _coat; int _kindness; }; #endif <file_sep> #ifndef GAMEENTITY_HPP #define GAMEENTITY_HPP #include <iostream> struct s_vector { int x; int y; }; class GameEntity { private: /* UNUSED */ GameEntity &operator = (GameEntity const &Cc); GameEntity(GameEntity const &Cc); protected: std::string _shape; s_vector _pos; s_vector _dir; // TODO: who needs it? clock_t _lastUpdate; public: GameEntity(void); GameEntity(std::string shape, int px, int py, int dx, int dy, GameEntity *next); virtual ~GameEntity(void); /* Function members */ std::string getShape(void) const; int getShapeSize(void) const; int getPosX(void) const; int getPosY(void) const; bool setShape(std::string shape); bool setPosition(int x, int y); virtual bool updatePosition(int winX, int winY); bool checkCollision(GameEntity *entity); /* Attributes */ bool collided; GameEntity *next; }; #endif <file_sep>#include <stdio.h> #include <stdlib.h> int ft_strcmp(char *s1, char *s2); int ft_count_if(char **tab, int (*f)(char*)); int ft_test(char *str) { if (ft_strcmp(str, "42") == 0) return (1); else return (0); } int main(void) { char **tab; int length; length = 3; tab = (char**)malloc(sizeof(char*) * (length + 1)); tab[0] = "elsa"; tab[1] = "42"; tab[2] = "1"; tab[3] = 0; printf("%d\n", ft_count_if(tab, &ft_test)); } <file_sep>#ifndef BRAIN_HPP # define BRAIN_HPP # include <iostream> # include <sstream> class Brain { public: Brain( int weight, std::string color ); ~Brain(); std::string identify( void ) const; private: int _weight; std::string _color; }; #endif<file_sep>function ft_load_cookies() { var tab = document.cookie.split(';'); for (var i = 0; i < tab.length; i++) { tab[i] = tab[i].trim(); start = tab[i].indexOf('='); var cookie_name = tab[i].substr(0, start); var todo_recup = tab[i].substr(start + 1); if (ft_check_cookie_name(cookie_name) == true) ft_add_div(todo_recup, cookie_name); } } function ft_check_cookie_name(name) { if (name.substr(0, 9) != 'd09_ex02_') return false; var nbr = name.substr(9); if (isNaN(+nbr) == true || nbr == "") return false; return true; } function ft_add_div(str, id) { todo = document.createTextNode(str); var div = document.getElementById("ft_list"); var new_div = document.createElement('div'); new_div.setAttribute('class', 'todo'); new_div.setAttribute('id', id); new_div.setAttribute('onclick', 'ft_supp(this)'); new_div.appendChild(todo); div.insertBefore(new_div, div.firstChild); } function ft_add() { var todo_recup = prompt("What do you want to do ?"); if (todo_recup != null && todo_recup != "") { ft_add_div(todo_recup, 'd09_ex02_' + ft_get_cookie_number()); var expires = "expires=Wed, 19 Jul 2017 00:00:00 UTC"; var name = 'd09_ex02_' + ft_get_cookie_number(); document.cookie = name + "=" + todo_recup + " ;" + expires; } } function ft_get_cookie_number() { var nbr = 0; var tmp = 0; var tab = document.cookie.split(';'); for (var i = 0; i < tab.length; i++) { tab[i] = tab[i].trim(); start = tab[i].indexOf('='); tmp = 0; var cookie_name = tab[i].substr(0, start); if (ft_check_cookie_name(cookie_name) == true) { tmp = cookie_name.substr(9); if (+tmp > +nbr) nbr = +tmp; } } return (+nbr + 1); } function ft_supp(elem) { if (confirm("Are you very sure you want to remove your task ?")) { document.cookie = elem.id + "= ;expires= 1 Jan 1970 00:00:00 GMT;"; var div = document.getElementById("ft_list"); div.removeChild(elem); } } <file_sep>SOURCES = arithmetic.ml OCAMLMAKEFILE = OCamlMakefile include $(OCAMLMAKEFILE) <file_sep>#include "HeapManager.hpp" HeapManager::HeapManager( void ) : _alphanumChar("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") { srand (time(NULL)); std::cout << "CONSTRUCTOR" << std::endl; return ; } HeapManager::~HeapManager( void ) { std::cout << "DESTRUCTOR" << std::endl; return ; } void * HeapManager::serialize( void ) { char unsigned * raw = new unsigned char[RAW_SIZE]; /* il aurait été possible de faire une structure */ int r; int i; std::cout << "---- IN SERIALIZE ----" << std::endl; std::cout << "random char 1 : "; for (i = CHAR1_START; i < CHAR1_END + 1; i++) { r = rand() % (_alphanumChar.length() - 1); std::cout << _alphanumChar[r]; raw[i] = _alphanumChar[r]; } std::cout << std::endl; unsigned char *tmp = raw; tmp += INT_START; r = rand(); std::cout << "random int : " << r << std::endl; *(reinterpret_cast<int *>(tmp)) = r; std::cout << "random char 2 : "; for (i = CHAR2_START; i < CHAR2_END + 1; i++) { r = rand() % (_alphanumChar.length() - 1); std::cout << _alphanumChar[r]; raw[i] = _alphanumChar[r]; } std::cout << std::endl; std::cout << "----------------------" << std::endl; return reinterpret_cast<void *>(raw); } Data * HeapManager::deserialize( void * raw ) { struct Data * data = new Data; unsigned char * tmp; tmp = reinterpret_cast<unsigned char *>(raw); data->s1 = std::string(reinterpret_cast<char *>(tmp), 8); tmp += INT_START; data->n = *(reinterpret_cast<int *>(tmp)); tmp += sizeof(int); data->s2 = std::string(reinterpret_cast<char *>(tmp), 8); return data; } /* UNUSED */ HeapManager::HeapManager( HeapManager const & ) {} HeapManager & HeapManager::operator=( HeapManager const & ) { return *this ; } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* colle_2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/20 17:01:23 by curquiza #+# #+# */ /* Updated: 2016/08/21 11:52:54 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "colle_2.h" #include "ft_init_colle.h" #include "ft_basic.h" char *ft_print_line(char char1, char char2, char char3, int x) { int i; char *str; str = (char *)malloc(sizeof(char) * x); i = 0; while (i < x) { if (i == 0) str[i] = char1; else if (i == x - 1) str[i] = char3; else str[i] = char2; i++; } str[i] = '\0'; return (str); } void ft_colle(int x, int y, char *str, t_colle colle) { int j; j = 0; if (x > 0 && y > 0) { while (j < y) { if (j == 0) str = ft_strcat(str, ft_print_line(colle.up_left, colle.row, colle.up_right, x)); else if (j == y - 1) str = ft_strcat(str, ft_print_line(colle.b_left, colle.row, colle.b_right, x)); else str = ft_strcat(str, ft_print_line(colle.col, ' ', colle.col, x)); while (*str != '\0') str++; *str = '\n'; j++; } str++; *str = '\0'; } } void ft_calc_row_col(t_colle *colle, char *buffer) { int i; i = 0; colle->nb_col = 0; colle->nb_row = 0; while (buffer[i] != '\n') i++; colle->nb_col = i; while (buffer[i] != '\0') { if (buffer[i] == '\n') colle->nb_row = colle->nb_row + 1; i++; } } char **ft_complete_all_colles(int x, int y) { char **str; t_colle *colle; int i; i = 0; colle = (t_colle *)malloc(sizeof(t_colle) * 5); str = (char **)malloc(sizeof(char*) * 5); ft_init_colle00(colle, x, y); ft_init_colle01(colle + 1, x, y); ft_init_colle02(colle + 2, x, y); ft_init_colle03(colle + 3, x, y); ft_init_colle04(colle + 4, x, y); while (i <= 4) { str[i] = (char *)malloc(sizeof(char) * (SIZE_BUF + 1)); ft_colle(x, y, str[i], colle[i]); i++; } return (str); } void ft_find_colle(char *buf, char **str, int x, int y) { int i; int cpt; cpt = 0; i = 0; while (i < 5) { if (ft_strcmp(str[i], buf) == 0) { if (cpt > 0) ft_putstr(" || "); ft_putstr("[colle-0"); ft_putnbr(i); ft_putstr("] ["); ft_putnbr(x); ft_putstr("] ["); ft_putnbr(y); ft_putchar(']'); cpt++; } i++; } if (cpt == 0) ft_putstr("aucune"); ft_putchar('\n'); } <file_sep>#ifndef MUTANTSTACK_HPP # define MUTANTSTACK_HPP # include <iostream> # include <stack> # include <deque> // template <typename T> // class MutantStack : public std::stack<T> { // private: // /* unused */ // MutantStack<T>( MutantStack<T> const & ) {}; // MutantStack<T> & operator=( MutantStack<T> const & ) {}; // public: // MutantStack<T>( void ) : std::stack<T>() {}; // virtual ~MutantStack<T>( void ) {}; // typename std::stack<T>::container_type::iterator begin() { return std::stack<T>::c.begin(); } // typename std::stack<T>::container_type::iterator end() { return std::stack<T>::c.end(); } // }; template <typename T, typename C = std::deque<T> > class MutantStack : public std::stack<T, C> { private: /* unused */ MutantStack<T, C>( MutantStack<T, C> const & ) {}; MutantStack<T, C> & operator=( MutantStack<T, C> const & ) {}; public: typedef typename C::iterator iterator; // typedef typename std::stack<T, C>::container_type::iterator iterator; MutantStack<T, C>( void ) : std::stack<T, C>() {}; virtual ~MutantStack<T, C>( void ) {}; iterator begin() { return std::stack<T, C>::c.begin(); } iterator end() { return std::stack<T, C>::c.end(); } }; #endif<file_sep>#!/usr/bin/php <?PHP function ft_split($str) { $tab_vide = array(""); $tab = explode(" ", $str); $tab = array_diff($tab, $tab_vide); $tab = array_values($tab); sort($tab); return ($tab); } function ft_print_array($tab) { foreach ($tab as $elem) echo $elem."\n"; } $i = 0; foreach ($argv as $argv) { if ($i != 0) $str = $str." ".$argv; $i++; } $tab = ft_split($str); ft_print_array($tab); ?> <file_sep>NAME = libft.a FLAG = -Wall -Werror -Wextra HEADERS = includes D_SRC = srcs/ SRC = ft_putstr.c ft_putchar.c ft_strcmp.c ft_strlen.c ft_swap.c OBJ = $(SRC:.c=.o) all : $(NAME) $(NAME) : gcc $(FLAG) -c $(addprefix $(D_SRC), $(SRC)) -I $(HEADERS) ar rc $(NAME) $(OBJ) clean : rm -rf $(OBJ) fclean : clean rm -rf $(NAME) re : fclean $(NAME) <file_sep><?php Class Jaime extends Lannister { public function sleepWith($perso) { if (get_class($perso) == "Cersei") print ("With pleasure, but only in a tower in Winterfell, then.".PHP_EOL); else parent::sleepWith($perso); } } //Class Jaime extends Lannister { // function __construct() { // $this->isCersei = FALSE; // } // public function sleepWith($perso) // { // if (isset($perso->isCersei) && $perso->isCersei == TRUE) // print ("With pleasure, but only in a tower in Winterfell, then.".PHP_EOL); // else // parent::sleepWith($perso); // } //} ?> <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* btree_search_item.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/24 21:53:48 by curquiza #+# #+# */ /* Updated: 2016/08/25 15:53:47 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_btree.h" #include <stdlib.h> void *btree_search_item(t_btree *root, void *data_ref, int (*cmpf)(void *, void *)) { void *result; if (root) { if (root->left) if ((result = btree_search_item(root->left, data_ref, (*cmpf)))) return (result); if ((*cmpf)(root->item, data_ref) == 0) return (root->item); if (root->right) if ((result = btree_search_item(root->right, data_ref, (*cmpf)))) return (result); } return (NULL); } <file_sep>#ifndef ZOMBIEHORDE_HPP # define ZOMBIEHORDE_HPP #include "Zombie.hpp" class ZombieHorde { public: ZombieHorde( int n ); ~ZombieHorde(); void announce( void ) const; private: int _number; Zombie *_horde; }; #endif<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/20 22:16:19 by curquiza #+# #+# */ /* Updated: 2016/08/21 11:54:29 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> #include <stdlib.h> #include "colle_2.h" #include "ft_basic.h" #include "ft_init_colle.h" char *ft_read(void) { char *buf; char text[SIZE + 1]; int ret; ret = 0; buf = (char *)malloc(sizeof(char) * (SIZE_BUF + 1)); while ((ret = read(0, text, SIZE)) != 0) { text[ret] = '\0'; buf = ft_strcat(buf, text); } return (buf); } int main(void) { char *buf; t_colle colle_buf; char **all_colles; buf = ft_read(); if (ft_strcmp(buf, "\0") == 0) { ft_putstr("aucune\n"); return (0); } ft_calc_row_col(&colle_buf, buf); all_colles = ft_complete_all_colles(colle_buf.nb_col, colle_buf.nb_row); ft_find_colle(buf, all_colles, colle_buf.nb_col, colle_buf.nb_row); return (0); } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> int ft_ultimate_range(int **range, int min, int max); int main(int argc, char **argv) { int nb; int *tab; int i; if (argc != 3) return (0); i = 0; tab = NULL; nb = 0; //tab = (int**)malloc(sizeof(tab) * 220); nb = ft_ultimate_range(&tab, atoi(argv[1]), atoi(argv[2])); /*while (i < atoi(argv[2]) - atoi(argv[1])) { printf("%d ", tab[i]); i++; }*/ printf("\n%d", nb); return (0); } <file_sep>NAME = do-op FLAG = -Wall -Werror -Wextra SRC = op.c display.c main.c all : $(NAME) $(NAME) : gcc $(FLAG) $(SRC) -o $(NAME) clean : rm -rf $(NAME) <file_sep>#include "ZombieHorde.hpp" int main ( void ) { srand (time(NULL)); ZombieHorde horde = ZombieHorde (8); std::cout << std::endl << "ANNOUNCEMENT :" << std::endl; horde.announce(); std::cout << std::endl; return 0; }<file_sep>#ifndef BUREAUCRAT_HPP # define BUREAUCRAT_HPP # include <iostream> class Bureaucrat { private: std::string const _name; int _grade; void checkGradeException(int grade); /* unused */ Bureaucrat & operator=( Bureaucrat const & rhs ); Bureaucrat( Bureaucrat const & src ); public: Bureaucrat( void ); Bureaucrat( std::string const name, int grade ); ~Bureaucrat( void ); std::string const getName() const; int getGrade() const; void incGrade( void ); void decGrade( void ); /* EXCEPTIONS */ class GradeTooLowException : public std::exception { private : GradeTooLowException & operator=( GradeTooLowException const & rhs ); public : GradeTooLowException(); GradeTooLowException( GradeTooLowException const & rhs ); virtual ~GradeTooLowException() throw(); virtual const char * what() const throw(); }; class GradeTooHighException : public std::exception { private : GradeTooHighException & operator=( GradeTooHighException const & rhs ); public : GradeTooHighException(); GradeTooHighException( GradeTooHighException const & rhs ); virtual ~GradeTooHighException() throw(); virtual const char * what() const throw(); }; /* end EXCEPTIONS */ }; /* end Bureaucrat */ std::ostream & operator<<( std::ostream & o, Bureaucrat const & rhs ); #endif<file_sep>#include <stdio.h> int *ft_map(int *tab, int length, int(*f)(int)); int ft_test(int nb) { return (nb + 42); } int main(void) { int i; int tab[6] = {0, 1, 2, 3, 4, 5}; int l; int *tab2; l = 6; i = 0; tab2 = ft_map(tab, l, &ft_test); while (i < l) { printf("%d\n", tab2[i]); i++; } return (0); } <file_sep>#include "Bureaucrat.hpp" void catchGradeExceptions(void) { } int main ( void ) { try { std::cout << "\033[1;32mInstanciating employee with grade 151: \033[0m" << std::endl; Bureaucrat employeeTooLow("Toto1", 151); } catch (std::exception const & e) { std::cerr << e.what() << std::endl; } std::cout << std::endl; try { std::cout << "\033[1;32mInstanciating employee with grade 0: \033[0m" << std::endl; Bureaucrat employeeTooHigh("Toto2", 0); } catch (std::exception const & e) { std::cerr << e.what() << std::endl; } std::cout << std::endl; Bureaucrat employee1("Choupi", 1); Bureaucrat employee2("Albert", 150); std::cout << std::endl; try { std::cout << "\033[1;32mEmployee1: \033[0m" << std::endl; std::cout << employee1 << std::endl; std::cout << "\033[1;32mEmployee2: \033[0m" << std::endl; std::cout << employee2 << std::endl; std::cout << "\033[1;32mEmployee1 after decrementing grade: \033[0m" << std::endl; employee1.decGrade(); std::cout << employee1 << std::endl; std::cout << "\033[1;32mEmployee2 after incrementing grade: \033[0m" << std::endl; employee2.incGrade(); std::cout << employee2 << std::endl; std::cout << "\033[1;32mIncrementing Employee1 twice (2 -> 1 -> 0): \033[0m" << std::endl; std::cout << employee1 << std::endl; employee1.incGrade(); std::cout << employee1 << std::endl; employee1.incGrade(); } catch (std::exception const &e) { std::cerr << e.what() << std::endl; std::cerr << employee1 << std::endl; } std::cout << std::endl; try { std::cout << "\033[1;32mDecrementing Employee2 twice (149 -> 150 -> 151): \033[0m" << std::endl; std::cout << employee2 << std::endl; employee2.decGrade(); std::cout << employee2 << std::endl; employee2.decGrade(); } catch (std::exception const &e) { std::cerr << e.what() << std::endl; std::cerr << employee2 << std::endl; } std::cout << std::endl; return (0); } <file_sep>SELECT upper(perso.nom) as 'NOM', perso.prenom, abo.prix FROM abonnement as abo, membre as m, fiche_personne as perso WHERE abo.id_abo = m.id_abo AND abo.prix > 42 AND m.id_fiche_perso = perso.id_perso ORDER BY perso.nom, perso.prenom ASC; <file_sep>#include <unistd.h> void ft_putchar(char c) { write(1, &c, 1); } void ft_print_delimiter(void) { ft_putchar(','); ft_putchar(' '); } void ft_print_3_numbers(int number1, int number2, int number3) { ft_putchar(number1); ft_putchar(number2); ft_putchar(number3); } void ft_print_comb(void) { char number1; char number2; char number3; number1 = '0'; number2 = number1 + 1; number3 = number2 + 1; while (number1 < '7') { while (number2 <= '8') { while (number3 <= '9') { ft_print_3_numbers(number1, number2, number3); ft_print_delimiter(); number3++; } number2++; number3 = number2 + 1; } number1++; number2 = number1 + 1; number3 = number2 + 1; } ft_print_3_numbers(number1, number2, number3); } int main(void) { ft_print_comb(); return (0); } <file_sep>#ifndef FRAGTRAP_HPP # define FRAGTRAP_HPP # include <iostream> class FragTrap { public: FragTrap( void ); FragTrap( std::string const & name ); FragTrap( FragTrap const & src ); ~FragTrap( void ); FragTrap & operator=( FragTrap const & rhs ); std::string getName ( void ) const; void rangedAttack( std::string const & target ) const; void meleeAttack( std::string const & target ) const; void takeDamage( unsigned int amount ); void beRepaired( unsigned int amount ); void vaulthunter_dot_exe( std::string const & target ); private: unsigned int _hitPoints; unsigned int _MaxHitPoints; unsigned int _energyPoints; unsigned int _MaxEnergyPoints; unsigned int _level; std::string _name; unsigned int _meleeAttackDamage; unsigned int _rangedAttackDamage; unsigned int _armorDamageReducton; void (FragTrap::*_specialAttacks[5])( std::string const & target ); void initSpecialAttacks( void ); void trempette( std::string const & target ); void frenchBaguette( std::string const & target ); void expelliarmus( std::string const & target ); void turtleShell( std::string const & target ); void kamehameha( std::string const & target ); }; #endif<file_sep>void ft_foreach(int *tab, int length, void(*f)(int)); void ft_putnbr(int nb); int main(void) { int tab[6] = {0, 12, -1, 13, -2, 14}; ft_foreach(tab, 6, &ft_putnbr); return (0); } <file_sep>#include "ft_list.h" void ft_putstr(char *str); int ft_putchar(char c); void ft_printlist(t_list *list) { while (list != 0) { ft_putstr(list->data); ft_putchar('\n'); list = list->next; } } int main(void) { t_list *list; list = 0; list = ft_create_elem("TEST"); ft_list_push_back(&list, "FIN"); ft_printlist(list); return (0); } <file_sep>#include <iostream> #include <fstream> std::string read_file ( std::string filename ) { std::ifstream ifs(filename); std::string line; std::string file = ""; if (!ifs.is_open()) throw std::ios_base::failure("Error when opening intput."); while (getline(ifs, line)) { file += line; if (!ifs.eof()) file.push_back('\n'); } ifs.close(); return (file); } void replace_all ( std::string & content, std::string s1, std::string s2 ) { size_t start_pos = 0; while((start_pos = content.find(s1, start_pos)) != std::string::npos) { content.replace(start_pos, s1.length(), s2); start_pos += s2.length(); } return ; } int write_in_file( std::string output_file, std::string content ) { std::ofstream ofs(output_file); if (!ofs.is_open()) throw std::ios_base::failure("Error when opening output."); ofs << content; ofs.close(); return 0 ; } int main ( int argc, char ** argv ) { if ( argc != 4 ) { std::cerr << "usage: ./replace file s1 s2" << std::endl; return 1; } std::string s1 = argv[2]; std::string s2 = argv[3]; if (!s1.length() || !s1.length()) { std::cerr << "Error: s2 and s2 must not be empty." << std::endl; return 1; } std::string input_file = argv[1]; std::string output_file = input_file + ".replace"; try { std::string content = read_file(input_file); replace_all(content, s1, s2); write_in_file(output_file, content); } catch (std::exception & e) { std::cerr << e.what() << std::endl; return 1; } return 0; }<file_sep>#include <stdio.h> int ft_bouton(int i, int j, int k); int main (void) { int a; int b; int c; a = 2; b = 1; c = 3; printf("%d\n", ft_bouton(a, b, c)); return (0); } <file_sep>#include "ft_btree.h" #include <stdlib.h> #include <unistd.h> #include <stdio.h> void btree_insert_data(t_btree **root, void *tem, int (*cmpf)(void *, void *)); int ft_strcmp(void *, void *); void ft_putstr(void *str); void btree_apply_infix(t_btree *root, void (*applyf)(void*)) { if (root != 0) { if (root->left) btree_apply_infix(root->left, applyf); (applyf)(root->item); if (root->right) btree_apply_infix(root->right, applyf); } } int main(void) { t_btree *tree; void *result; tree = 0; btree_insert_data(&tree, "2", &ft_strcmp); btree_insert_data(&tree, "3", &ft_strcmp); btree_insert_data(&tree, "4", &ft_strcmp); btree_insert_data(&tree, "1", &ft_strcmp); btree_insert_data(&tree, "0", &ft_strcmp); btree_insert_data(&tree, "1", &ft_strcmp); btree_insert_data(&tree, "2", &ft_strcmp); btree_insert_data(&tree, "6", &ft_strcmp); result = btree_search_item(tree, "2", &ft_strcmp); btree_apply_infix(tree, &ft_putstr); write(1, "\n", 1); printf("%s\n", result); } <file_sep>#include "ft_stock_par.h" #include <stdio.h> int main(int argc, char **argv) { t_stock_par *tab_struct; int i; int j; tab_struct = ft_param_to_tab(argc, argv); i = 0; while (i < argc) { printf("%s\n", tab_struct[i].copy); printf("%d\n", tab_struct[i].size_param); j = 0; while (tab_struct[i].tab[j] != 0) { printf("%s\n", tab_struct[i].tab[j]); j++; } i++; printf("\n"); } return (0); } <file_sep>#include "ft_btree.h" #include <stdlib.h> int ft_strcmp(void *, void *); int main(void) { t_btree *tree; //tree = (t_btree*)malloc(sizeof(t_btree)); tree = btree_create_node("TEST"); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_takes_place.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/11 18:52:26 by curquiza #+# #+# */ /* Updated: 2016/08/11 21:30:10 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> int ft_putchar(char c) { write(1, &c, 1); return (0); } void ft_putnbr(int nb) { int index; int tab[10]; index = 0; if (nb < 0) ft_putchar('-'); while (index < 10 && (nb >= 10 || nb <= -10)) { tab[index] = (nb % 10); nb = nb / 10; index++; } tab[index] = nb; while (index >= 0) { if (tab[index] < 0) ft_putchar((tab[index] * -1) + '0'); else ft_putchar(tab[index] + '0'); index--; } } void ft_display(int hour, int hour2, char c1, char c2) { write(1, "THE FOLLOWING TAKES PLACE BETWEEN ", 34); ft_putnbr(hour); write(1, ".00 ", 4); ft_putchar(c1); write(1, ".M. AND ", 8); ft_putnbr(hour2); write(1, ".00 ", 4); ft_putchar(c2); write(1, ".M.\n", 4); } void ft_special_hours(int *hour, int *hour2, char *c1, char *c2) { if (*hour == 0) { *hour = 12; *hour2 = 1; } if (*hour == 11 && *c1 == 'A') *c2 = 'P'; else if (*hour == 11 && *c1 == 'P') *c2 = 'A'; } void ft_takes_place(int hour) { char c1; char c2; int hour2; c1 = 0; c2 = 0; if (hour >= 0 && hour <= 11) { c1 = 'A'; c2 = 'A'; } else if (hour > 11 && hour < 24) { c1 = 'P'; c2 = 'P'; hour = hour - 12; } hour2 = hour + 1; ft_special_hours(&hour, &hour2, &c1, &c2); ft_display(hour, hour2, c1, c2); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sastantua.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/06 15:53:43 by curquiza #+# #+# */ /* Updated: 2016/08/07 13:10:15 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdio.h> int ft_putchar(char c); int ft_base(int size) { int step; int step_base; int floor; int floor_height; floor = 1; step = 1; step_base = 1; floor_height = 0; while (floor <= size) { floor_height = floor + 2; step = 1; while (step <= floor_height) { step_base = step_base + 2; step++; } floor++; if (floor <= size) step_base = step_base + floor / 2 * 2 + 2; } return (step_base); } void ft_putspace(int base, int step_base) { int i; int nb_spaces; i = 1; nb_spaces = (base - step_base) / 2; while (i <= nb_spaces) { ft_putchar(' '); i++; } } void ft_putbricks(int step_base, int step, int floor, int size) { int i; int door; ft_putchar('/'); door = (floor - 1) / 2 * 2 + 1; // si cest impair ca change rien door = floor, sinon door = floor - 1 i = 1; while (i <= step_base - 2) //jusqua -2 car les / et \ sont deja mis. { if (size >= 5 && floor == size && step > floor + 2 - door && i >= (step_base - door) / 2 && i < (step_base + door) / 2) if (step == floor + 2 - door + (door + 1) / 2 && i == (step_base + door) / 2 - 2) ft_putchar('$'); else ft_putchar('|'); else ft_putchar('*'); i++; } ft_putchar('\\'); } void sastantua(int size) { int floor; int step; int step_base; int i; i = 1; floor = 1; step_base = 1; while (floor <= size) { step = 1; while (step <= floor + 2) { step_base = step_base + 2; ft_putspace(ft_base(size), step_base); ft_putbricks(step_base, step, floor, size); ft_putchar('\n'); step++; } floor++; step_base = step_base + floor / 2 * 2 + 2; // si le floor est pair, ca change rien, sil est impair cela le ramene a un floor pair. } } <file_sep>#ifndef HEAPMANAGER_HPP # define HEAPMANAGER_HPP # include <iostream> # define RAW_SIZE 20 # define CHAR1_START 0 # define CHAR1_END 7 # define INT_START 8 # define CHAR2_START 12 # define CHAR2_END 19 struct Data { std::string s1; int n; std::string s2; }; class HeapManager { private: std::string _alphanumChar; /* UNUSED */ HeapManager & operator=( HeapManager const & ); HeapManager( HeapManager const & ); public: HeapManager( void ); ~HeapManager( void ); void * serialize( void ); Data * deserialize( void * raw ); }; #endif<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* btree_level_count.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/25 09:40:44 by curquiza #+# #+# */ /* Updated: 2016/08/25 10:44:09 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "ft_btree.h" int btree_level_count(t_btree *root) { int count; count = 0; if (root == NULL) return (0); if (btree_level_count(root->left) > btree_level_count(root->right)) return (count + 1 + btree_level_count(root->left)); if (btree_level_count(root->left) <= btree_level_count(root->right)) return (count + 1 + btree_level_count(root->right)); return (1); } <file_sep>#include <stdio.h> int match(char *s1, char *s2); int main(int argc, char **argv) { int i; i = argc; printf("%d\n", match(argv[1], argv[2])); return(0); } <file_sep>#include <unistd.h> #include <stdio.h> char **ft_split_whitespaces(char *str); int ft_nb_words(char *str); int main(int argc, char **argv) { //printf("%d", '\v'); char **range; int i; int nb_words; i = 0; if (argc != 2) return (0); nb_words = ft_nb_words(argv[1]); range = ft_split_whitespaces(argv[1]); while (range[i] != 0) { printf("%s\n", range[i]); i++; } //ft_putstr(argv[1]); return (0); } <file_sep>#include <stdio.h> #include <string.h> char *ft_strcpy(char *dest, char *src); int main(void) { char str1[40] = "elsa"; char str2[] = "auxrore"; char str3[40] = "elsa"; char str4[] = "auxrore"; printf("%s %s\n", str1, str2); ft_strcpy(str1, str2); printf("%s %s\n\n", str1, str2); printf("%s %s\n", str3, str4); strcpy(str3, str4); printf("%s %s\n", str3, str4); return (0); } <file_sep>#ifndef INTERN_HPP # define INTERN_HPP # include <iostream> # include "Form.hpp" # include "ShrubberyCreationForm.hpp" # include "RobotomyRequestForm.hpp" # include "PresidentialPardonForm.hpp" # define ACTIONS_NB 3 class Intern { private: std::string _validNames[ACTIONS_NB]; Form * (Intern::*_actions[ACTIONS_NB])( std::string const & target ); void initNames(); void initActions(); Form * makePresident( std::string const & target ); Form * makeRobot( std::string const & target ); Form * makeShrubbery( std::string const & target ); /* unused */ Intern( Intern const & ); Intern & operator=( Intern const & ); public: Intern( void ); ~Intern( void ); Form * makeForm(std::string const & name, std::string const & target); }; #endif<file_sep>#include "Human.hpp" Human::Human( void ) : _brain(3, "pink") { std::cout << "Human created." << std::endl; return; } Human::~Human( void ) { std::cout << "Human destroyed." << std::endl; return; } Brain const & Human::getBrain( void ) const { return this->_brain; } std::string Human::identify( void ) const { return this->_brain.identify(); }<file_sep>#include <iostream> #include <cctype> char *str_to_upper(char *str) { int i; for (i = 0; str[i] != '\0'; i++) str[i] = toupper(str[i]); return (str); } int main(int argc, char **argv) { int i; if (argc == 1) std::cout << "* LOUD AND UNBEARABLE FEEDBACK NOISE *"; else { for (i = 1; i < argc; i++) std::cout << str_to_upper(argv[i]); } std::cout << std::endl; }<file_sep>#include <iostream> int main ( void ) { std::string brain = "HI THIS IS BRAIN"; std::string* brainPtr = &brain; std::string& brainRef = brain; std::cout << "string : " << brain << std::endl; std::cout << "pointeur : " << *brainPtr << std::endl; std::cout << "reference : " << brainRef << std::endl; }<file_sep>#ifndef WEAPON_HPP # define WEAPON_HPP #include <iostream> class Weapon { public: Weapon( std::string type ); ~Weapon(); std::string const & getType ( void ) const; void setType ( std::string new_type ); private: std::string _type; }; #endif<file_sep>#include "Bureaucrat.hpp" Bureaucrat::Bureaucrat( void ) : _name("Boby"), _grade(150) { std::cout << "CONSTRUCTOR : " << _name << " grade " << _grade << std::endl; return ; } Bureaucrat::Bureaucrat( std::string const name, int grade ) : _name(name), _grade(grade) { checkGradeException(_grade); std::cout << "CONSTRUCTOR : " << _name << " grade " << _grade << std::endl; return ; } Bureaucrat::Bureaucrat( Bureaucrat const & ) {} Bureaucrat::~Bureaucrat( void ) { std::cout << "DESTRUCTOR : " << _name << " grade " << _grade << std::endl; return ; } /* ACCESSORS *********************************************/ std::string const Bureaucrat::getName ( void ) const { return _name; } int Bureaucrat::getGrade ( void ) const { return _grade; } /* EXCEPTIONS *********************************************/ Bureaucrat::GradeTooLowException::GradeTooLowException() {} Bureaucrat::GradeTooLowException::GradeTooLowException( GradeTooLowException const & ) {} Bureaucrat::GradeTooLowException::~GradeTooLowException() throw() {} Bureaucrat::GradeTooHighException::GradeTooHighException() {} Bureaucrat::GradeTooHighException::GradeTooHighException( GradeTooHighException const & ) {} Bureaucrat::GradeTooHighException::~GradeTooHighException() throw() {} const char * Bureaucrat::GradeTooLowException::what() const throw() { return ("The grade can not be lower than 150."); } const char * Bureaucrat::GradeTooHighException::what() const throw() { return ("The grade can not be higher than 1."); } void Bureaucrat::checkGradeException( int grade ) { if (grade < 1) throw Bureaucrat::GradeTooHighException(); if (grade > 150) throw Bureaucrat::GradeTooLowException(); return ; } /* INC/DEC ************************************************/ void Bureaucrat::incGrade( void ) { int tmp = _grade - 1; checkGradeException(tmp); _grade--; } void Bureaucrat::decGrade( void ) { int tmp = _grade + 1; checkGradeException(tmp); _grade++; } /* OVERLOAD ************************************************/ std::ostream & operator<<( std::ostream & o, Bureaucrat const & rhs ) { o << rhs.getName() << ", bureaucrat grade " << rhs.getGrade(); return o; } Bureaucrat & Bureaucrat::operator=( Bureaucrat const & ) { return *this; } <file_sep># Nom de l'executable NAME = cipher # Sources SOURCES = cipher.ml uncipher.ml OBJS = $(SOURCES:.ml=.cmo) OPTOBJS = $(SOURCES:.ml=.cmx) TMP = $(OBJS) $(OPTOBJS) $(SOURCES:.ml=.cmi) $(SOURCES:.ml=.o) # Compilateurs CAMLC = ocamlc CAMLOPT = ocamlopt CAMLDEP = ocamldep ### RULES ###################################################################### all: $(NAME) $(NAME): opt byt ln -s $(NAME).byt $(NAME) byt: $(NAME).byt opt: $(NAME).opt $(NAME).byt: $(OBJS) $(CAMLC) -o $@ $(LIBS) $^ $(NAME).opt: $(OPTOBJS) $(CAMLOPT) -o $@ $(LIBS:.cma=.cmxa) $^ # Compilation %.cmo: %.ml $(CAMLC) $(CFLAGS) -c $< -o $@ %.cmi: %.ml $(CAMLC) $(CFLAGS) -c $< -o $@ %.cmx: %.ml $(CAMLOPT) $(CFLAGS) -c $< -o $@ # Clean clean: rm -f $(TMP) fclean: clean rm -f $(NAME) rm -f $(NAME).opt rm -f $(NAME).byt re: fclean all <file_sep>#ifndef ZOMBIE_EVENT_HPP # define ZOMBIE_EVENT_HPP # include <iostream> #include "Zombie.hpp" class ZombieEvent { public: ZombieEvent(); ~ZombieEvent(); void setZombieType ( std::string new_type ); Zombie* newZombie ( std::string name ) const; Zombie* randomChump ( void ) const; private: std::string _type; }; #endif<file_sep>#include "Fixed.hpp" Fixed::Fixed( void ) : _fpValue(0) { return ; } Fixed::Fixed( int const n ) { this->_fpValue = n << Fixed::_fractionnal; return ; } Fixed::Fixed( float const n ) { this->_fpValue = roundf(n * ( 1 << Fixed::_fractionnal )); return ; } Fixed::Fixed( Fixed const & src ) { *this = src; return ; } Fixed::~Fixed( void ) { return ; } Fixed & Fixed::operator=( Fixed const & rhs) { if ( this != &rhs ) this->_fpValue = rhs.getRawBits(); return *this ; } bool Fixed::operator>( Fixed const & rhs) const { return (this->_fpValue > rhs.getRawBits()); } bool Fixed::operator<( Fixed const & rhs) const { return (this->_fpValue < rhs.getRawBits()); } bool Fixed::operator>=( Fixed const & rhs) const { return (this->_fpValue >= rhs.getRawBits()); } bool Fixed::operator<=( Fixed const & rhs) const { return (this->_fpValue <= rhs.getRawBits()); } bool Fixed::operator==( Fixed const & rhs) const { return (this->_fpValue == rhs.getRawBits()); } bool Fixed::operator!=( Fixed const & rhs) const { return (this->_fpValue != rhs.getRawBits()); } Fixed const Fixed::operator+( Fixed const & rhs ) const { return (Fixed (this->toFloat() + rhs.toFloat())); } Fixed const Fixed::operator-( Fixed const & rhs ) const { return (Fixed (this->toFloat() - rhs.toFloat())); } Fixed const Fixed::operator*( Fixed const & rhs ) const { return (Fixed (this->toFloat() * rhs.toFloat())); } Fixed const Fixed::operator/( Fixed const & rhs ) const { return (Fixed (this->toFloat() / rhs.toFloat())); } int Fixed::getRawBits( void ) const { return this->_fpValue; } void Fixed::setRawBits( int const raw ) { this->_fpValue = raw; return ; } float Fixed::toFloat( void ) const { return (static_cast<float>((this->_fpValue) / ( 1 << Fixed::_fractionnal ))); } int Fixed::toInt( void ) const { return (this->_fpValue) >> Fixed::_fractionnal; } std::ostream & operator<<( std::ostream & o, Fixed const & rhs ) { o << rhs.toFloat(); return o; } const int Fixed::_fractionnal = 8;<file_sep>#include "Form.hpp" #include "Bureaucrat.hpp" int main (void) { try { std::cout << "\033[1;32mInstanciating form with gradeToSign > 150: \033[0m" << std::endl; Form formTooLow("Toto1", 50, 151); } catch (std::exception const & e) { std::cerr << e.what() << std::endl; } std::cout << std::endl; try { std::cout << "\033[1;32mInstanciating form with gradeToExec < 1: \033[0m" << std::endl; Form formTooHigh("Toto2", 0, 50); } catch (std::exception const & e) { std::cerr << e.what() << std::endl; } std::cout << std::endl; Bureaucrat boby("Boby", 50); Bureaucrat tata("Tata", 12); Form form("Toto-Form", 25, 25); std::cout << std::endl; std::cout << "\033[1;32mEmployee Boby: \033[0m" << std::endl; std::cout << boby << std::endl; std::cout << "\033[1;32mEmployee Tata: \033[0m" << std::endl; std::cout << tata << std::endl; std::cout << "\033[1;32mForm Toto-Form: \033[0m" << std::endl; std::cout << form << std::endl; std::cout << std::endl; try { std::cout << "\033[1;32mTrying to sign Toto form with Boby (too low grade) : \033[0m" << std::endl; boby.signForm(form); } catch (std::exception const & e) { std::cerr << e.what() << std::endl; } std::cout << std::endl; std::cout << form << std::endl; std::cout << std::endl; try { std::cout << "\033[1;32mTrying to sign Toto form with Tata (right grade) : \033[0m" << std::endl; tata.signForm(form); } catch (std::exception const & e) { std::cerr << e.what() << std::endl; } std::cout << std::endl; std::cout << form << std::endl; std::cout << std::endl; return (0); }<file_sep>#include "ft_list.h" #include <stdlib.h> void ft_putstr(char *str); int ft_putchar(char c); void ft_printlist(t_list *list) { while (list != 0) { ft_putstr(list->data); ft_putchar('\n'); list = list->next; } } int main(int argc, char **argv) { t_list *list; //char **tab; //(void)argv; (void)argc; list = 0; //tab = NULL; //tab = (char**)malloc(sizeof(char*) * 4); //list = ft_create_elem("TEST"); list = ft_list_push_params(0, argv); ft_printlist(list); return (0); } <file_sep>#include <stdlib.h> void ft_takes_place(int hour); int main(int argc, char **argv) { int index; index = argc; ft_takes_place(atoi(argv[1])); return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/17 18:11:33 by curquiza #+# #+# */ /* Updated: 2016/08/18 14:18:58 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include "op.h" #include "display.h" int ft_check_op(char *op) { int i; i = 0; while (op[i] != '\0') i++; if (i == 1) { if (op[0] == '+' || op[0] == '-' || op[0] == '*' || op[0] == '/' || op[0] == '%') return (1); else return (0); } else return (0); } int ft_atoi(char *str) { int test_neg; int i; int result; i = 0; test_neg = 1; result = 0; while (str[i] == '\n' || str[i] == '\t' || str[i] == ' ') i++; if (str[i] == '+') i++; else if (str[i] == '-') { test_neg = -1; i++; } while (str[i] >= 48 && str[i] <= 57) { result = result * 10; result = result + str[i] - 48; i++; } return (test_neg * result); } void ft_init(char *tab, int (*f[5])(int, int)) { f[0] = &ft_add; f[1] = &ft_sous; f[2] = &ft_mult; f[3] = &ft_div; f[4] = &ft_mod; tab[0] = '+'; tab[1] = '-'; tab[2] = '*'; tab[3] = '/'; tab[4] = '%'; } int main(int argc, char **argv) { int (*f[5])(int, int); char tab[5]; int i; ft_init(tab, f); i = -1; if (argc != 4) return (0); if (ft_check_op(argv[2]) == 0) { write(1, "0\n", 2); return (0); } while (i++ < 6) if (argv[2][0] == tab[i]) { if (argv[2][0] == '/' && ft_atoi(argv[3]) == 0) ft_putstr("Stop : division by zero"); else if (argv[2][0] == '%' && ft_atoi(argv[3]) == 0) ft_putstr("Stop : modulo by zero"); else ft_putnbr(f[i](ft_atoi(argv[1]), ft_atoi(argv[3]))); ft_putchar('\n'); } return (0); } <file_sep>#include "RobotomyRequestForm.hpp" RobotomyRequestForm::RobotomyRequestForm( void ) : Form::Form("Robot", 72, 45), _target("home") { srand (time(NULL)); std::cout << "RobotomyRequestForm CONSTRUCTOR" << std::endl; return ; } RobotomyRequestForm::RobotomyRequestForm( std::string const target ) : Form::Form("Robot", 72, 45), _target(target) { srand (time(NULL)); std::cout << "RobotomyRequestForm CONSTRUCTOR" << std::endl; return ; } RobotomyRequestForm::RobotomyRequestForm( RobotomyRequestForm const & ) {} RobotomyRequestForm::~RobotomyRequestForm( void ) { std::cout << "RobotomyRequestForm DESTRUCTOR" << std::endl; return ; } void RobotomyRequestForm::executeChildForm() const { int r = rand() % 2; if (r == 0) { std::cout << "** VVVVVVVVVVVVVVVVVVO !!! **" << std::endl; std::cout << _target << " has been robotomized successfully." << std::endl; } else std::cout << "FAIL !" << std::endl; return ; } std::string RobotomyRequestForm::getTarget() { return _target; } /* OVERLOAD */ RobotomyRequestForm & RobotomyRequestForm::operator=( RobotomyRequestForm const & ) { return *this ; }<file_sep><?php function auth($login, $passwd) { if (file_exists("../private/passwd") === FALSE) return (FALSE); $file = file_get_contents("../private/passwd"); $tab = unserialize($file); $pw_hash = hash("sha512", $passwd); foreach ($tab as $elem) { if ($elem['login'] == $login && $elem['passwd'] == $pw_hash) return (TRUE); } return (FALSE); } ?> <file_sep>#include "phonebook.hpp" std::string get_add_input(int field) { std::string prompt; std::string line; switch (field) { case FIRST_NAME: prompt = "First name : "; break; case LAST_NAME: prompt = "Last name : "; break; case NICKNAME: prompt = "Nickname : "; break; case LOGIN: prompt = "Login : "; break; case POSTAL_ADDRESS: prompt = "Postal address : "; break; case EMAIL_ADDRESS: prompt = "Email address : "; break; case PHONE_NUMBER: prompt = "Phone number : "; break; case BIRTHDAY_DATE: prompt = "Birthday date : "; break; case FAVORITE_MEAL: prompt = "Favorite meal : "; break; case UNDERWEAR_COLOR: prompt = "Underwear color : "; break; case DARKEST_SECRET: prompt = "Darkest secret : "; break; } std::cout << prompt; std::getline(std::cin, line); return (line); } void add_contact(Contact *all_contacts, int count) { int field = 1; std::string line; std::cout << "Adding a contact..." << std::endl << std::endl; for (field = 1; field <= 11; field++) { line = get_add_input(field); all_contacts[count].setField(line, field); } std::cout << std::endl << "Contact added." << std::endl; }<file_sep>#include "Form.hpp" Form::Form( void ) : _name("Basic"), _signed(false), _gradeToSign(100), _gradeToExec(50) { checkGradeException(_gradeToSign); checkGradeException(_gradeToExec); std::cout << "FORM CONSTRUCTOR : " << _name << std::endl; return ; } Form::Form( std::string const name, int const gradeToSign, int const gradeToExec ) : _name(name), _signed(false), _gradeToSign(gradeToSign), _gradeToExec(gradeToExec) { checkGradeException(_gradeToSign); checkGradeException(_gradeToExec); std::cout << "FORM CONSTRUCTOR : " << _name << std::endl; return ; } Form::Form( Form const & ) : _gradeToSign(100), _gradeToExec(50) {} Form::~Form( void ) { std::cout << "FORM DESTRUCTOR : " << _name << std::endl; return ; } void Form::beSigned(Bureaucrat & b) { if (b.getGrade() <= _gradeToSign) _signed = true; else throw Form::GradeTooLowException("the grade required to sign is too low"); return ; } void Form::execute(Bureaucrat const & executor) const { if (_signed == false) throw NotSignedException("the form is not signed"); if (executor.getGrade() <= _gradeToExec) executeChildForm(); else throw GradeTooLowException("the grade required to sign is too low"); return ; } /* ACCESSORS */ std::string const Form::getName() const { return _name; } int Form::getSigned() const { return _signed; } int Form::getGradeToSign() const { return _gradeToSign; } int Form::getGradeToExec() const { return _gradeToExec; } /* EXCEPTIONS */ Form::GradeTooLowException::GradeTooLowException() : _err("The grade can not be lower than 150.") {} Form::GradeTooLowException::GradeTooLowException( std::string msg ) : _err(msg) {} Form::GradeTooLowException::GradeTooLowException( GradeTooLowException const & ) {} Form::GradeTooLowException::~GradeTooLowException() throw() {} Form::GradeTooHighException::GradeTooHighException() : _err("The grade can not be higher than 1.") {} Form::GradeTooHighException::GradeTooHighException( std::string msg ) : _err(msg) {} Form::GradeTooHighException::GradeTooHighException( GradeTooHighException const & ) {} Form::GradeTooHighException::~GradeTooHighException() throw() {} Form::NotSignedException::NotSignedException() : _err("The form to execute is not signed.") {} Form::NotSignedException::NotSignedException( std::string msg ) : _err(msg) {} Form::NotSignedException::NotSignedException( NotSignedException const & ) {} Form::NotSignedException::~NotSignedException() throw() {} const char * Form::GradeTooLowException::what() const throw() { return (_err.c_str()); } const char * Form::GradeTooHighException::what() const throw() { return (_err.c_str()); } const char * Form::NotSignedException::what() const throw() { return (_err.c_str()); } void Form::checkGradeException( int grade ) { if (grade < 1) throw Form::GradeTooHighException("A grade in the form " + _name + " is higher than 1."); if (grade > 150) throw Form::GradeTooLowException("A grade in the form " + _name + " is lower than 150."); return ; } /* OVERLOAD */ std::ostream & operator<<( std::ostream & o, Form const & rhs ) { o << "Form " << rhs.getName() << std::endl; o << "Signed ? " << rhs.getSigned() << std::endl; o << "Grade to sign : " << rhs.getGradeToSign() << std::endl; o << "Grade to execute : " << rhs.getGradeToExec(); return o; } Form & Form::operator=( Form const & ) { return *this; } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_basic.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/20 22:11:23 by curquiza #+# #+# */ /* Updated: 2016/08/20 22:14:37 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include "ft_basic.h" int ft_putchar(char c) { write(1, &c, 1); return (0); } void ft_putstr(char *str) { int i; i = 0; while (*(str + i) != '\0') { ft_putchar(*(str + i)); i++; } } void ft_putnbr(int nb) { int index; int tab[10]; index = 0; if (nb < 0) ft_putchar('-'); while (index < 10 && (nb >= 10 || nb <= -10)) { tab[index] = (nb % 10); nb = nb / 10; index++; } tab[index] = nb; while (index >= 0) { if (tab[index] < 0) ft_putchar((tab[index] * -1) + '0'); else ft_putchar(tab[index] + '0'); index--; } } int ft_strcmp(char *s1, char *s2) { int i; int length; i = 0; length = 0; while (s1[length] != '\0') length++; while (i <= length) { if (s1[i] != s2[i]) return (s1[i] - s2[i]); i++; } return (0); } char *ft_strcat(char *dest, char *src) { int i; int j; i = 0; while (dest[i] != '\0') i++; j = 0; while (src[j] != '\0') { dest[i] = src[j]; i++; j++; } dest[i] = '\0'; return (dest); } <file_sep>#ifndef FORM_HPP # define FORM_HPP # include <iostream> # include "Bureaucrat.hpp" class Bureaucrat; class Form { private: std::string const _name; bool _signed; int const _gradeToSign; int const _gradeToExec; void checkGradeException( int grade ); /* unused */ Form( Form const & src ); Form & operator=( Form const & rhs ); public: Form( void ); Form( std::string const name, int const gradeToSign, int const gradeToExec ); ~Form( void ); std::string const getName() const; int getSigned() const; int getGradeToSign() const; int getGradeToExec() const; void beSigned(Bureaucrat & b); /* EXCEPTIONS ********************************************************/ class GradeTooLowException : public std::exception { private : std::string _err; GradeTooLowException & operator=( GradeTooLowException const & rhs ); public : GradeTooLowException(); GradeTooLowException( std::string msg ); GradeTooLowException( GradeTooLowException const & rhs ); virtual ~GradeTooLowException() throw(); virtual const char * what() const throw(); }; class GradeTooHighException : public std::exception { private : std::string _err; GradeTooHighException & operator=( GradeTooHighException const & rhs ); public : GradeTooHighException(); GradeTooHighException( std::string msg ); GradeTooHighException( GradeTooHighException const & rhs ); virtual ~GradeTooHighException() throw(); virtual const char * what() const throw(); }; /* end EXCEPTIONS ****************************************************/ }; /* end Form */ std::ostream & operator<<( std::ostream & o, Form const & rhs ); #endif<file_sep>#include "Brain.hpp" Brain::Brain( int weight, std::string color ) { std::cout << "Brain created." << std::endl; this->_weight = weight; this->_color = color; return; } Brain::~Brain( void ) { std::cout << "Brain destroyed." << std::endl; return; } std::string Brain::identify( void ) const { std::stringstream ss; ss << this; return (ss.str()); }<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_retro.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lfabbro <> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/05/30 15:16:28 by lfabbro #+# #+# */ /* Updated: 2018/06/03 15:29:17 by lfabbro ### ########.fr */ /* */ /* ************************************************************************** */ #include <iostream> #include <ncurses.h> #include <string.h> #include <unistd.h> #include "GameMaster.hpp" #include "Player.hpp" #define DELAY 30000 int main(void) { GameMaster GM; play: while(42) { GM.displayBanner(); GM.displayScenery(); GM.getKey(); GM.movePlayer(); GM.spawnEntity(); GM.moveEnnemies(); GM.moveShoots(); if (GM.checkPlayerCollision() == true) break ; GM.destroyEntitiesCollision(&GM.ennemies); GM.destroyEntitiesCollision(&GM.shoots); GM.displayAllEntities(); GM.refreshWindow(); if (GM.getCharacter() == 'q' || GM.getCharacter() == 'Q') break; usleep(GM.getDifficultyLevel()); } if (GM.gameOverBanner() == true) goto play; return 0; } <file_sep>#ifndef SHRUBBERYCREATIONFORM_HPP # define SHRUBBERYCREATIONFORM_HPP # include "Form.hpp" # include <fstream> # define TREE1 " ###" # define TREE2 " #o###" # define TREE3 " #####o###" # define TREE4 " #o#\\#|#/###" # define TREE5 " ###\\|/#o#" # define TREE6 " # }|{ #" # define TREE7 " }|{" class ShrubberyCreationForm : public Form { private: std::string _target; ShrubberyCreationForm & operator=( ShrubberyCreationForm const & rhs ); ShrubberyCreationForm( ShrubberyCreationForm const & src ); public: ShrubberyCreationForm( void ); ShrubberyCreationForm( std::string const target ); virtual ~ShrubberyCreationForm( void ); std::string getTarget(); virtual void executeChildForm() const; }; #endif<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_concat_params.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/14 21:16:08 by curquiza #+# #+# */ /* Updated: 2016/08/15 09:53:46 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> char *ft_strcpy(char *dest, char *src) { int i; i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; return (dest); } int ft_strlen(char *str) { int count; count = 0; while (str[count] != '\0') count++; return (count); } char *ft_concat_params(int argc, char **argv) { int i; int length; char *tab; length = 0; i = 1; while (i < argc) { length = length + ft_strlen(argv[i]) + 1; i++; } tab = (char *)malloc(sizeof(char) * length); i = 1; while (i < argc) { tab = ft_strcpy(tab, argv[i]); tab = tab + ft_strlen(argv[i]); if (i != argc - 1) *tab = '\n'; tab++; i++; } tab = tab - length; return (tab); } <file_sep># include <iostream> template <typename T> void swap(T & x, T & y) { T tmp = x; x = y; y = tmp; } template <typename T> T & min(T & x, T & y) { return (x <= y ? x : y); } template <typename T> T & max(T & x, T & y) { return (x >= y ? x : y); } int main(void) { int a = 2; int b = 3; std::cout << "avant swap : a = " << a << ", b = " << b << std::endl; ::swap( a, b ); std::cout << "apres swap : a = " << a << ", b = " << b << std::endl; std::cout << "min( a, b ) = " << ::min( a, b ) << std::endl; std::cout << "max( a, b ) = " << ::max( a, b ) << std::endl; std::cout << std::endl; std::string c = "chaine1"; std::string d = "chaine2"; std::cout << "avant swap : c = " << c << ", d = " << d << std::endl; ::swap(c, d); std::cout << "apres swap : c = " << c << ", d = " << d << std::endl; std::cout << "min( c, d ) = " << ::min( c, d ) << std::endl; std::cout << "max( c, d ) = " << ::max( c, d ) << std::endl; return 0; }<file_sep>#ifndef ROBOTOMYREQUESTFORM_HPP # define ROBOTOMYREQUESTFORM_HPP #include "Form.hpp" class RobotomyRequestForm : public Form { private: std::string _target; RobotomyRequestForm & operator=( RobotomyRequestForm const & rhs ); RobotomyRequestForm( RobotomyRequestForm const & src ); public: RobotomyRequestForm( void ); RobotomyRequestForm( std::string const target ); virtual ~RobotomyRequestForm( void ); std::string getTarget(); virtual void executeChildForm() const; }; #endif<file_sep>#include <stdio.h> unsigned int ft_collatz_conjecture(unsigned int base); int ft_atoi(char *str); int main(void) { printf("%d\n", ft_collatz_conjecture(1)); printf("%d\n", ft_collatz_conjecture(0)); printf("%d\n", ft_collatz_conjecture(2)); printf("%d\n", ft_collatz_conjecture(3)); printf("%d\n", ft_collatz_conjecture(15)); return (0); } <file_sep>#include "phonebook.hpp" int get_contact_with_index(Contact *all_contacts, std::string index, int count) { int i = 0; for (i = 0; i < count; i++) { if (all_contacts[i].getField(INDEX) == index) return i; } return -1; } void contact_detailed_display(Contact *contact) { std::cout << std::endl; std::cout << "Last name : " << contact->getField(LAST_NAME) << std::endl; std::cout << "First name : " << contact->getField(FIRST_NAME) << std::endl; std::cout << "Nickname : " << contact->getField(NICKNAME) << std::endl; std::cout << "Login : " << contact->getField(LOGIN) << std::endl; std::cout << "Postal address : " << contact->getField(POSTAL_ADDRESS) << std::endl; std::cout << "Email address : " << contact->getField(EMAIL_ADDRESS) << std::endl; std::cout << "Phone number : " << contact->getField(PHONE_NUMBER) << std::endl; std::cout << "Birthday date : " << contact->getField(BIRTHDAY_DATE) << std::endl; std::cout << "Favorite meal : " << contact->getField(FAVORITE_MEAL) << std::endl; std::cout << "Underwear color : " << contact->getField(UNDERWEAR_COLOR) << std::endl; std::cout << "Darkest secret : " << contact->getField(DARKEST_SECRET) << std::endl; } std::string truncated_str(std::string str) { std::string trunc; if (str.length() > 10) { trunc = str.substr(0, 10); if (trunc[9] != '\0') trunc[9] = '.'; return(trunc); } return (str); } void display_all_contacts(Contact *all_contacts, int count) { int i = 0; std::cout << std::endl; std::cout << std::setfill (' ') << std::setw (MAXWIDTH) << "INDEX" << " | "; std::cout << std::setfill (' ') << std::setw (MAXWIDTH) << "FIRST NAME" << " | "; std::cout << std::setfill (' ') << std::setw (MAXWIDTH) << "LAST NAME" << " | "; std::cout << std::setfill (' ') << std::setw (MAXWIDTH) << "NICKNAME" << " | " << std::endl; for (i = 0; i < count; i++) { std::cout << std::setfill (' ') << std::setw (MAXWIDTH) << truncated_str(all_contacts[i].getField(INDEX)) << " | "; std::cout << std::setfill (' ') << std::setw (MAXWIDTH) << truncated_str(all_contacts[i].getField(FIRST_NAME)) << " | "; std::cout << std::setfill (' ') << std::setw (MAXWIDTH) << truncated_str(all_contacts[i].getField(LAST_NAME)) << " | "; std::cout << std::setfill (' ') << std::setw (MAXWIDTH) << truncated_str(all_contacts[i].getField(NICKNAME)) << " | " << std::endl; } std::cout << std::endl; } void search_contact(Contact *all_contacts, int count) { std::string line; int contact_id; std::cout << "Which index ? "; std::getline(std::cin, line); contact_id = get_contact_with_index(all_contacts, line, count); if (contact_id == -1) std::cout << "Error: no contact with this index." << std::endl; else { std::cout << "Searching..." << std::endl; contact_detailed_display(&all_contacts[contact_id]); } }<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_ultimate_range.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/08/13 22:13:01 by curquiza #+# #+# */ /* Updated: 2016/08/15 12:54:50 by curquiza ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> int ft_ultimate_range(int **range, int min, int max) { int i; i = 0; if (min >= max) { range = NULL; return (0); } *range = (int*)malloc(sizeof(int) * (max - min)); while (i < max - min) { //*(*range + i) = min + i; (*range)[i] = min + i; i++; } return (i); } // Dans mon main jai un tableau simple (tab*) et je vais passer en parametre // l'adresse de ce tableau (&tab) pour pouvoir modifier le tableau via son adresse // Cest le meme principe que declarer un int et passer l'adreesse du int en param de la fonction // pour modifier le int via son adresse. /*int ft_ultimate_range(int **range, int min, int max) { int *tab; int i; i = 0; if (min >= max) { range = NULL; return (0); } tab = (int*)malloc(sizeof(int) * (max - min)); while (i < max - min) { tab[i] = min + i; i++; } *range = tab; return (i); }*/ <file_sep>#include "Var.hpp" int main ( int argc, char ** argv ) { if ( argc != 2 ) { std::cerr << "usage : ./convert [input]" << std::endl; return 1; } Var var(argv[1]); std::cout << std::endl; std::cout << var << std::endl; std::cout << std::endl; }<file_sep>INSERT INTO ft_table (login, groupe, date_de_creation) SELECT nom, "other", date_naissance FROM fiche_personne WHERE length(nom) <= 8 AND instr(nom, "a") != 0 ORDER BY nom LIMIT 10; <file_sep> #ifndef PLAYER_HPP #define PLAYER_HPP #include <iostream> #include "GameEntity.hpp" class Player: public GameEntity { private: Player(Player const &Cc); Player &operator = (Player const &Cc); clock_t _lastShot; public: Player(void); virtual ~Player(void); GameEntity *shoot(GameEntity *next); }; #endif
7b3b26997ab3ae3a70fabddc870975f66f002593
[ "SQL", "Markdown", "JavaScript", "Makefile", "PHP", "C", "C++", "Shell" ]
215
C
curquiza/42_Piscines
d4d409c834a779a6e9560c91ef494dd3fb7bcd43
307031181b55e636345b0990653b20b178fa8ac8
refs/heads/main
<repo_name>yasa1995/autokube<file_sep>/scripts/worker-pre-req.sh POD_CIDR=$1 sudo sed -i 's/^\/dev\/mapper\/vgvagrant-swap_1/#\/dev\/mapper\/vgvagrant-swap_1/' /etc/fstab sudo swapoff /dev/mapper/vgvagrant-swap_1 sudo systemctl stop ufw sudo systemctl disable ufw ############ containerd installation cat <<EOF | sudo tee /etc/modules-load.d/containerd.conf overlay br_netfilter EOF sudo modprobe overlay sudo modprobe br_netfilter # Setup required sysctl params, these persist across reboots. cat <<EOF | sudo tee /etc/sysctl.d/99-kubernetes-cri.conf net.bridge.bridge-nf-call-iptables = 1 net.ipv4.ip_forward = 1 net.bridge.bridge-nf-call-ip6tables = 1 EOF # Apply sysctl params without reboot sudo sysctl --system sudo apt-get update && sudo apt-get install -y containerd sudo mkdir -p /etc/containerd sudo containerd config default > /etc/containerd/config.toml sudo systemctl restart containerd ##########install kube* sudo apt-get update && sudo apt-get install -y apt-transport-https curl curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - cat <<EOF | sudo tee /etc/apt/sources.list.d/kubernetes.list deb https://apt.kubernetes.io/ kubernetes-xenial main EOF sudo apt-get update sudo apt-get install -y kubelet kubeadm kubectl sudo apt-mark hold kubelet kubeadm kubectl ########### join the cluster sh /vagrant_data/join.sh ########### correct internal ip for the kubelet ETH0=$(ip -f inet addr show eth1 | grep -Po 'inet \K[\d.]+') sudo sed -i "s/^ExecStart=\/usr\/bin\/kubelet.*/& --node-ip $ETH0/" /etc/systemd/system/kubelet.service.d/10-kubeadm.conf sudo systemctl daemon-reload && sudo systemctl restart kubelet <file_sep>/Vagrantfile # image name to be used as the base image for the hosts IMAGE_NAME = "bento/ubuntu-20.04" # subnet to be used for the nodes SUBNET = "192.168.56." # pod cidr to be used with kubeadm POD_CIDR = "10.10.0.0/16" # number of workers to be deployed N = 2 Vagrant.configure("2") do |config| config.ssh.insert_key = false config.vm.box_check_update = false config.vm.provider "virtualbox" do |v| v.memory = 2048 v.cpus = 2 end config.vm.define "master-1" do |master| master.vm.box = IMAGE_NAME master.vm.network "private_network", ip: SUBNET + "#{10}" master.vm.hostname = "master-1" master.vm.synced_folder "data/", "/vagrant_data" #master.vm.synced_folder "data/", "/vagrant_data", smb_username: "me", smb_password: "<PASSWORD>" master.vm.provision "shell", path: "scripts/master-pre-req.sh" do |s| s.args = [POD_CIDR, SUBNET + "#{10}"] end end (1..N).each do |i| config.vm.define "worker-#{i}" do |node| node.vm.box = IMAGE_NAME node.vm.network "private_network", ip: SUBNET + "#{i + 10}" node.vm.hostname = "worker-#{i}" node.vm.synced_folder "data/", "/vagrant_data" #node.vm.synced_folder "data/", "/vagrant_data", smb_username: "me", smb_password: "<PASSWORD>" node.vm.provision "shell", path: "scripts/worker-pre-req.sh" end end end <file_sep>/scripts/master-pre-req.sh POD_CIDR=$1 API_IP=$2 sudo sed -i 's/^\/dev\/mapper\/vgvagrant-swap_1/#\/dev\/mapper\/vgvagrant-swap_1/' /etc/fstab sudo swapoff /dev/mapper/vgvagrant-swap_1 sudo systemctl stop ufw sudo systemctl disable ufw ############ containerd installation cat <<EOF | sudo tee /etc/modules-load.d/containerd.conf overlay br_netfilter EOF sudo modprobe overlay sudo modprobe br_netfilter # Setup required sysctl params, these persist across reboots cat <<EOF | sudo tee /etc/sysctl.d/99-kubernetes-cri.conf net.bridge.bridge-nf-call-iptables = 1 net.ipv4.ip_forward = 1 net.bridge.bridge-nf-call-ip6tables = 1 EOF # Apply sysctl params without reboot sudo sysctl --system sudo apt-get update && sudo apt-get install -y containerd sudo mkdir -p /etc/containerd sudo containerd config default > /etc/containerd/config.toml sudo systemctl restart containerd ##########install kube* sudo apt-get update && sudo apt-get install -y apt-transport-https curl curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - cat <<EOF | sudo tee /etc/apt/sources.list.d/kubernetes.list deb https://apt.kubernetes.io/ kubernetes-xenial main EOF sudo apt-get update sudo apt-get install -y kubelet kubeadm kubectl sudo apt-mark hold kubelet kubeadm kubectl ########### init cluster sudo kubeadm init --apiserver-advertise-address=$API_IP --pod-network-cidr=$POD_CIDR ########### correct internal ip for the kubelet ETH0=$(ip -f inet addr show eth1 | grep -Po 'inet \K[\d.]+') sudo sed -i "s/^ExecStart=\/usr\/bin\/kubelet.*/& --node-ip $ETH0/" /etc/systemd/system/kubelet.service.d/10-kubeadm.conf sudo systemctl daemon-reload && sudo systemctl restart kubelet ### configure kubectl mkdir -p $HOME/.kube sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config sudo chown $(id -u):$(id -g) $HOME/.kube/config # for vagrant user mkdir -p /home/vagrant/.kube sudo cp -i /etc/kubernetes/admin.conf /home/vagrant/.kube/config sudo chown $(id -u vagrant):$(id -g vagrant) /home/vagrant/.kube/config ###### deploy calico curl https://docs.projectcalico.org/manifests/calico.yaml -O kubectl apply -f calico.yaml ### create join command kubeadm token create --print-join-command > /vagrant_data/join.sh chmod +x /vagrant_data/join.sh
0d4da2b3eee8fc4e84880133ddf5aad9d8eedaaa
[ "Ruby", "Shell" ]
3
Shell
yasa1995/autokube
f146c8d266a1fe752038b79ccdc7a267f969d328
26598762a3ccf1fb0db21800059048ad717fa780
refs/heads/master
<repo_name>rbrunt/RPi-experiments<file_sep>/LED Experiments/README.md LED Experiments =============== This is a collection of Python scripts that make LEDs do stuff (mostly blink) The Experiments: --------------- ### blink.py This script was a first test to see if I could make an LED blink from the GPIO pins on the RPi... ### progressbar.py This script lights up up to 6 LEDs (2 red, 2 yellow, 2 green) in a sort of audio meter style. Might extend it to make it controllable from a web interface / mobile app. <file_sep>/sendIP.py #!/usr/bin/env python ################################################################################### # To make this run at startup, add "/path/to/script/sendIP.py &" to /etc/rc.local # # Make sure that you change your email address and SMTP details below! # ################################################################################### import subprocess import smtplib # Get the output of `ifconfig` and store it in a variable: ipinfo = subprocess.check_output("ifconfig", shell=True) # Setup the Message details: fromaddr = '<EMAIL>' # For multiple addresses, add more to the list. For one address, a string will suffice. toaddrs = ['<EMAIL>'] msg = """From: RaspberryPi <<EMAIL>> To: <NAME> <<EMAIL>> Subject: RPi IP information Here's a print of ifconfig for the RaspberryPi: """ + ipinfo # Credentials for your SMTP server: username = 'username' password = '<PASSWORD>' # Acutally sending the mail: ############################ # This defaults to using google's smtp, change it to yours if it's different server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg) server.quit() <file_sep>/README.md RPi-experiments =============== Lots of experiments with my RaspberryPi (in Python) Prerequisites ------------ Need to have the `RPi.GPIO` library installed from [here](http://pypi.python.org/pypi/RPi.GPIO). You can find installation instructions [here](http://www.raspberrypi-spy.co.uk/2012/05/install-rpi-gpio-python-library/). Pinout Diagram: --------------- Here's a basic pinout diagram of the RPi GPIO headers for quick reference: ``` 3.3V ( ) | ( ) 5V GPIO0 (SDA) ( ) | ( ) -- GPIO1 (SCL) ( ) | ( ) GND GPIO4 (GPCLK0) ( ) | ( ) GPIO14 (TXD) -- ( ) | ( ) GPIO15 (RXD) GPIO17 ( ) | ( ) GPIO18 (PCM_CLK) GPIO21(PCM_DOUT)( ) | ( ) -- GPIO22 ( ) | ( ) GPIO23 -- ( ) | ( ) GPIO24 GPIO10 (MOSI) ( ) | ( ) -- GPIO9 (MISO) ( ) | ( ) GPIO25 GPIO11 (SCKL) ( ) | ( ) GPIO18 (CE0) -- ( ) | ( ) GPIO17 (CE1) ```<file_sep>/LED Experiments/progressbar.py #!/usr/bin/python import RPi.GPIO as GPIO import time # Set to board pin numbering scheme: GPIO.setmode(GPIO.BOARD) # Choose which pin the LED is controlled from: GREEN_1 = 7 GREEN_2 = 11 YELLOW_1 = 12 YELLOW_2 = 13 RED_1 = 15 RED_2 = 16 # Define array of pins: PIN_LIST = [GREEN_1, GREEN_2, YELLOW_1, YELLOW_2, RED_1, RED_2] # Setup output pins from list: def setupoutputs(OUT_LIST) : print "Setting up Output pins:" i = 0 while i < len(OUT_LIST) : GPIO.setup(OUT_LIST[i], GPIO.OUT) print "setting up pin number " + str(OUT_LIST[i]) + " as an output" i += 1 print "setup complete!" # Light up to a certain number of LEDs (by cycling through the list) # Pass a number between 1 and 6: def displayprogress(num) : if num < 7 : # Turn off any LEDs currently lit: #print "turning off LEDs:" i = 0 while i < len(PIN_LIST) : GPIO.output(PIN_LIST[i], False) i += 1 # Now we turn on the LEDs that we want: i = 0 while i < (num) : GPIO.output(PIN_LIST[i], True) i += 1 else : print "You need to pass a number between 1 and 6!" setupoutputs(PIN_LIST) print "" print "turn on 1 LED" displayprogress(1) time.sleep(1) displayprogress(0) time.sleep(0.5) print "turn on 2 LEDs" displayprogress(2) time.sleep(1) displayprogress(0) time.sleep(0.5) print "turn on 3 LEDs" displayprogress(3) time.sleep(1) displayprogress(0) time.sleep(0.5) print "turn on 4 LEDs" displayprogress(4) time.sleep(1) displayprogress(0) time.sleep(0.5) print "turn on 5 LEDs" displayprogress(5) time.sleep(1) displayprogress(0) time.sleep(0.5) print "turn on 6 LEDs" displayprogress(6) time.sleep(1) displayprogress(0) while True : number = int(input("Please enter the number of LED's to light: ")) try: if number < 7 : print "Lighting " + str(number) + " LED's..." displayprogress(number) print "" else : print "you need to enter a number between 0 and 6!" print "" except: print "Please enter a number!"
c3be0a4e898494acb5ed8b53f21977fc4aff2914
[ "Markdown", "Python" ]
4
Markdown
rbrunt/RPi-experiments
37b54738c76d87aead3f20a10828a41e51eaeed5
fcb22666451ebcdca5d8022fbc041204bff237e6
refs/heads/master
<repo_name>zhighest/domaintools<file_sep>/domaintools/tests.py # encoding: utf8 import unittest from . import Domain # input, tld, sld, subdomain, private valid_domains = [ # gtld (u'goat.com', 'com', 'goat', None, False), # gtld with subdomain (u'www.goat.com', 'com', 'goat', 'www', False), # gtld with unicode subdomain (u'рф.goat.com', 'com', 'goat', 'xn--p1ai', False), # gtld with idna subdomain (u'xn--p1ai.goat.com', 'com', 'goat', 'xn--p1ai', False), # cctld (u'goat.ca', 'ca', 'goat', None, False), # 2-piece cctld (u'goat.co.uk', 'co.uk', 'goat', None, False), # 2-piece cctld with subdomain (u'www.goat.co.uk', 'co.uk', 'goat', 'www', False), # private tld (u'uk.com', 'com', 'uk', None, False), # private tld (u'goat.uk.com', 'com', 'uk', 'goat', False), # private tld with subdomain (u'www.goat.uk.com', 'com', 'uk', 'www.goat', False), # unicode tld (u'goat.рф', 'xn--p1ai', 'goat', None, False), # idna tld (u'goat.xn--p1ai', 'xn--p1ai', 'goat', None, False), # unicode tld and sld (u'рф.рф', 'xn--p1ai', 'xn--p1ai', None, False), # unicode tld and sld with subdomain (u'www.рф.рф', 'xn--p1ai', 'xn--p1ai', 'www', False), # unicode tld, sld, and subdomain (u'рф.рф.рф', 'xn--p1ai', 'xn--p1ai', 'xn--p1ai', False), # unicode sld with gtld (u'рф.com', 'com', 'xn--p1ai', None, False), # new gtld (u'goat.wtf', 'wtf', 'goat', None, False), # wildcard (u'goat.com.bn', 'com.bn', 'goat', None, False), # include _ (u'hnzd8.weishangok_com.ag1671.com', 'com', 'ag1671', 'hnzd8.weishangok_com', False), ] valid_private_domains = [ # private tld (u'goat.uk.com', 'uk.com', 'goat', None, True), # private tld with subdomain (u'www.goat.uk.com', 'uk.com', 'goat', 'www', True), ] invalid_domains = [ # invalid tld with no sld u'goat', # invalid tld with sld u'sub.goat', # invalid unicode tld with no sld u'gфat', # invalid unicode tld with sld u'sub.gфat', # invalid idna tld with no sld u'xn--gat-hfd', # invalid idna tld with sld u'sub.xn--gat-hfd', # valid tld with no sld u'com', # wildcard sld value u'goat.bn', # test-period unicode tld (no longer in use) u'test.テスト', # incorrect formatting u'.goat.com', # include , u',.google.com', # start with - u'-a.google.com', # end with - u'a-.google.com', # include * u'*a.google.com', # include * u'*.google.com', ] invalid_private_domains = [ # valid 2-piece tld with no sld u'co.uk', # valid private tld with no sld u'uk.com', ] class TestDomainTools(unittest.TestCase): def test_valid_domain_parsing(self): for domain_name, tld, sld, subdomain, private in valid_domains: domain = Domain(domain_name) self.assertTrue(domain.valid) self.assertTrue(domain.tld == tld) self.assertTrue(domain.sld == sld) self.assertTrue(domain.subdomain == subdomain) self.assertTrue(domain.private == private) def test_private_domain_parsing(self): for domain_name, tld, sld, subdomain, private in valid_private_domains: domain = Domain(domain_name, allow_private=True) self.assertTrue(domain.valid) self.assertTrue(domain.tld == tld) self.assertTrue(domain.sld == sld) self.assertTrue(domain.subdomain == subdomain) self.assertTrue(domain.private == private) def test_invalid_domain_parsing(self): for domain_name in invalid_domains: domain = Domain(domain_name) self.assertFalse(domain.valid) def test_invalid_private_domain_parsing(self): for domain_name in invalid_private_domains: domain = Domain(domain_name, allow_private=True) self.assertFalse(domain.valid) if __name__ == '__main__': unittest.main()
1b9dbeaec622121000ce1aab72450173ea08ee59
[ "Python" ]
1
Python
zhighest/domaintools
535c0625c8c4ff5e378e0eba9af08f47f9bfe2e6
d06fa7b65848998237d0b73f96710e20d63c4991
refs/heads/master
<repo_name>MitjaBezensek/DFSM<file_sep>/README.md DFSM ==== A simple implementation of a deterministic finite state machine in C#. A post about it can be found on my blog: http://bezensek.com/blog/2014/08/13/deterministic-finite-state-machine-implementation-in-c-number/ <file_sep>/FSM_Simple/Program.cs using System.Collections.Generic; namespace FSM_Simple{ internal class Program{ private static void Main(string[] args){ var Q = new List<string>{"q0", "q1", "q2"}; var Sigma = new List<char>{'a'}; var Delta = new List<Transition>{ new Transition("q0", 'a', "q1"), new Transition("q1", 'a', "q2"), new Transition("q2", 'a', "q1") }; var Q0 = "q0"; var F = new List<string>{"q0", "q2"}; var dFSM = new DeterministicFSM(Q, Sigma, Delta, Q0, F); dFSM.Accepts(""); dFSM.Accepts("a"); dFSM.Accepts("aa"); dFSM.Accepts("aaa"); dFSM.Accepts("aaaa"); dFSM.Accepts("aaaaa"); dFSM.Accepts("aaaaaa"); } } }
f1b19021efbe6b08563d021612dd24d24a991229
[ "Markdown", "C#" ]
2
Markdown
MitjaBezensek/DFSM
57dec1710181f5b36cfa2942707df350bd7ca1f4
3b67782419fb1a9623295bd83e5b1b57709d6974
refs/heads/master
<repo_name>krcummings1/YogaEveryDamnDay-client<file_sep>/README.md # YogaEveryDamnDay-client This is the client-side code for my Back-End Capstone at Nashville Software School. I practice yoga and often find myself wanting to do specific, advanced yoga poses, but don't know how to build up the strength and flexibility needed to do them. This app allows users to select a yoga pose from a list and see preparatory poses for the selected, advanced pose. If the user practices the corresponding preparatory poses, he or she will then be targeting the same muscles used in the selected, advanced pose and with time, will get closer to being able to the advanced pose. I wrote my front-end using AngularJS, JavaScript, and Bootstrap. The server-side code is in a separate repository titled, YogaEveryDamnDayCapstone. <file_sep>/app/controllers/MainController.js "use strict"; YEDD.controller('MainController', [ "$scope", "$location", "$route", function ($scope, $location, $route) { } // closes main function ]);<file_sep>/app/controllers/PoseController.js "use strict"; YEDD.controller('PoseController', [ '$scope', '$http', '$route', 'PoseFactory', '$timeout', '$location', function ($scope, $http, $route, PoseFactory, $timeout, $location) { PoseFactory().then( // Handle resolve() from the promise poseCollection => { console.log("resolve", poseCollection); $scope.posesArray = poseCollection; console.log("poses array", $scope.posesArray); $timeout(); console.log("poseId", $scope.posesArray[0].PoseId); }, error => console.log("??", error) ); $scope.seePoseDetails = function(id) { $http({ method: "GET", url: `http://localhost:5000/api/Pose/${id}` }) .then( pose => { console.log("base pose", pose.data); $scope.basePose = pose.data[0]; $scope.prepPoses = pose.data[0].PrepPoses; console.log("prepPoses", $scope.prepPoses); console.log("$scope.basePose", $scope.basePose); } ); } // closes seePoseDetails } // closes main function ]);
db766696d66841d43e95b5b766d552b8c38077f0
[ "Markdown", "JavaScript" ]
3
Markdown
krcummings1/YogaEveryDamnDay-client
40da6d3dbb8b5a2e73926ac6f327c04daf08190e
c92943308d48c8d596c45ada06ad3ca6aa5b6a16
refs/heads/master
<file_sep>const { inspect } = require('util') module.exports = { name: 'eval', execute (msg, args) { try { for (const worker of this.workers) { const out = eval(args.join(' ')) // eslint-disable-line no-eval worker.createMessage(msg.channel.id, `\`\`\`js\n${inspect(out, { depth: 0 })}\`\`\``) } } catch (error) { this.master.client.rest.createMessage(msg.channel.id, error.message) } }, group: 'owner' } <file_sep>module.exports = { name: 'silenteval', execute (msg, args) { try { for (const worker of this.workers) { void (worker) // eslint-disable-line no-void eval(args.join(' ')) // eslint-disable-line no-eval } } catch (error) { this.master.client.rest.createMessage(msg.channel.id, error.message) } }, group: 'owner' } <file_sep>class Command { constructor ({ name, execute, group, options }) { this.name = name || null this.execute = execute || null this.group = group || null this.options = Object.assign({}, options) if (!name) { throw new Error('Name is a required argument that is missing.') } else if (!execute) { throw new Error('Execute is a required argument that is missing.') } } init (commander) { this.commander = commander } get master () { return this.commander.master } get workers () { return this.master.workers } reply (msg, content) { this.commander.createMessage(msg.channel.id, content) } } module.exports = Command <file_sep>module.exports = { name: 'leave', execute (msg) { for (const worker of this.master.workers) { worker.leaveVoiceChannel(msg.guild.id) } }, group: 'admin' }
189a9c706b1cec6d84c2c0953b3e149511417c99
[ "JavaScript" ]
4
JavaScript
Daniihh/Welcomers
a2a4d4050168021a888b3ce47ff12e9efbe85e8c
8699d22dd531952a3ad64b115fa4da386121128d
refs/heads/master
<repo_name>ManojK97/test1<file_sep>/src/com/controller/WelcomeServlet.java package com.controller; import java.io.IOException; import java.util.LinkedList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.dao.DBApplication; import com.model.Product; import com.model.Register; /** * Servlet implementation class WelcomeServlet */ public class WelcomeServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public WelcomeServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("prod"); String s1=request.getParameter("Prodnm"); String s2=request.getParameter("price"); String s3=request.getParameter("stock"); int price=Integer.parseInt(s2); int stock=Integer.parseInt(s3); Product p=new Product(); System.out.println("prodsaveserv3"); p.setProdnm(s1); p.setPrice(price); p.setStock(stock); DBApplication db=new DBApplication(); List<Product> lst=new LinkedList<Product>(); lst.add(p); System.out.println("prodtest1"); List<Product> i=db.prodgetAllData(lst); System.out.println("prodtest2 in value"+i); //creating session String s=request.getParameter("qty"); int qty=Integer.parseInt(s); HttpSession session=request.getSession(true); session.setAttribute("qty", qty); response.sendRedirect("Product.jsp"); } } <file_sep>/src/com/controller/DisplayServlet.java package com.controller; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; import com.dao.DBApplication; import com.model.Register; /** * Servlet implementation class DisplayServlet */ public class DisplayServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DisplayServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath()); System.out.println("dispserv1"); DBApplication db=new DBApplication(); List<Register> lst=db.getAllData(); request.setAttribute("usrLst", lst); RequestDispatcher view=request.getRequestDispatcher("Dispaly.jsp"); view.forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
7445f55ba7b9a9272105001caee779ff22bff9dd
[ "Java" ]
2
Java
ManojK97/test1
f19463e8d2b762b4e0cbf2f5d68e207d56157130
d5277e6f013d7071cf099fc4c6518b28309b84bd
refs/heads/master
<repo_name>ickmund/wotmad<file_sep>/wotmad/stats/views.py from django.http import HttpResponse from django.views.generic import TemplateView, ListView, View from annoying.decorators import JsonResponse from .forms import SubmitStatForm from .models import Stat class StatList(ListView): model = Stat def get_queryset(self): return Stat.objects.order_by('-date_submitted') class ContributeStat(TemplateView): template_name = 'stats/contribute.html' class SubmitStat(View): def get(self, *args, **kwargs): request = self.request ashtml = 'ashtml' in request.GET def make_response(data, code=200): if ashtml: out = [] if 'error' in data: out.append("<h1>Error receiving stat</h1>") out.append("<p>{0}</p>".format(data['error'])) if 'errors' in data: out.append("<p>The following errors were encountered while " "validating your submission:</p>") for field, errors in data['errors'].iteritems(): l = "<li>{0}<ul><li>{1}</li></ul></li>" out.append(l.format(field, "</li><li>".join(errors))) if 'success' in data: out.append("<h1>Success! Your stat was accepted.</h1>") out.append("<br/><br/>") out.append("You may close this window at any time.") resp = HttpResponse("\n".join(out)) else: resp = JsonResponse(data) resp.status_code = code return resp def make_error(msg, errors=None): errors = errors or {} return make_response(dict(error=msg, errors=errors), 400) formdata = request.GET.copy() formdata['klass'] = formdata.get('class', None) # Allow the user to submit full versions of the sex, faction, and class fulltext_maps = { 'sex': { 'male': 'M', 'female': 'F', }, 'faction': { 'human': 'H', 'seanchan': 'S', 'trolloc': 'D', }, 'klass': { 'hunter': 'H', 'rogue': 'R', 'warrior': 'W', 'channeler': 'C', }, } for k, map_ in fulltext_maps.iteritems(): v = formdata.get(k, None) if v and v in map_: formdata[k] = map_[v] # Create the form instance form = SubmitStatForm(formdata) # And see if it's valid if not form.is_valid(): # Rename any errors for `klass` to `class` if form.errors.get('klass'): form.errors['class'] = form.errors['klass'] del form.errors['klass'] return make_error("Submitted data is invalid.", form.errors) # Pull the user out of the form user = form.user clean = form.cleaned_data # At this point, we have valid data and a valid user, so just # create the stat and let them know it was done! try: Stat.objects.create(submitter=user, name=clean.get('name'), sex=clean.get('sex'), faction=clean.get('faction'), klass=clean.get('klass'), homeland=clean.get('homeland'), strength=clean.get('strength'), intel=clean.get('intel'), wil=clean.get('wil'), dex=clean.get('dex'), con=clean.get('con'), ) except: return make_error("Something went wrong accepting your stat.") return make_response(dict(success="Ok")) <file_sep>/wotmad/urls.py from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from wotmad.views import HomeView urlpatterns = patterns( '', url(r'^$', HomeView.as_view(), name='home'), url(r'^accounts/', include('wotmad.accounts.urls', namespace='accounts')), url(r'^art-of-war/', include('wotmad.artofwar.urls', namespace='artofwar')), url(r'^scripts/', include('wotmad.scripts.urls', namespace='scripts')), url(r'^stats/', include('wotmad.stats.urls', namespace='stats')), url(r'^admin/', include(admin.site.urls)), url(r'^browserid/', include('django_browserid.urls')), ) <file_sep>/requirements.txt Django==1.4 path.py==2.2.2 git+https://github.com/mozilla/django-browserid.git@master#egg=django_browserid django-annoying==0.7.6 django-compressor==1.1.2 requests==0.10.8 psycopg2==2.4.4 gunicorn==0.14.2 django-crispy-forms==1.1.3 django-braces==0.1.0 South==0.7.4 <file_sep>/wotmad/stats/models.py from django.db import models SEX_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) FACTION_CHOICES = ( ('H', 'Human'), ('D', 'Darkside'), ('S', 'Seanchan'), ) CLASS_CHOICES = ( ('H', 'Hunter'), ('R', 'Rogue'), ('W', 'Warrior'), ('C', 'Channeler'), ) class Stat(models.Model): submitter = models.ForeignKey('auth.User', related_name='stats') date_submitted = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=64, default='', blank=True) sex = models.CharField(max_length=1, choices=SEX_CHOICES) faction = models.CharField(max_length=1, choices=FACTION_CHOICES) klass = models.CharField(max_length=1, choices=CLASS_CHOICES) homeland = models.CharField(max_length=32) strength = models.PositiveSmallIntegerField() intel = models.PositiveSmallIntegerField() wil = models.PositiveSmallIntegerField() dex = models.PositiveSmallIntegerField() con = models.PositiveSmallIntegerField() def __unicode__(self): parts = [] parts.append("{faction} {sex} {klass} from {homeland}") parts.append("[{strength} {intel} {wil} {dex} {con}]") return " ".join(parts).format(faction=self.get_faction_display(), sex=self.get_sex_display(), klass=self.get_klass_display(), homeland=self.homeland, strength=self.strength, intel=self.intel, wil=self.wil, dex=self.dex, con=self.con) <file_sep>/wotmad/stats/forms.py from django import forms from django.contrib.auth.models import User from .models import Stat class SubmitStatForm(forms.ModelForm): apikey = forms.CharField(max_length=38) strength = forms.IntegerField(min_value=3, max_value=21) intel = forms.IntegerField(min_value=3, max_value=19) wil = forms.IntegerField(min_value=3, max_value=19) dex = forms.IntegerField(min_value=3, max_value=19) con = forms.IntegerField(min_value=3, max_value=19) def clean(self): data = self.cleaned_data klass = data.get('klass', None) faction = data.get('faction', None) # If the klass is C then the faction must be H if klass == 'C' and faction != 'H': raise forms.ValidationError("Only humans can be channelers.") return data def clean_apikey(self): # Ensure they submit a valid api key clean = self.cleaned_data.get('apikey') # Try to find a user with this API key try: user = User.objects.get(apikey__key=clean, is_active=True) self.user = user except User.DoesNotExist: self.user = None raise forms.ValidationError("Invalid API key.") return clean class Meta: model = Stat exclude = ['submitter', 'date_submitted'] <file_sep>/README.mkd # wotmad Features and bugs are tracked on Trello at the [wotmad](https://trello.com/board/wotmad/4f723dc355adc061384f2976) board. The in-development version is running at http://wotmad.herokuapp.com and may be down at any given time and the data may go missing at any time. Logins are handled via [BrowserID](https://browserid.org) because it's much easier for me to use. If you don't want an account through BrowserID, so sorry charlie. <file_sep>/wotmad/stats/urls.py from django.conf.urls import patterns, url from .views import StatList, ContributeStat, SubmitStat urlpatterns = patterns( 'wotmad.stats.views', url(r'^$', StatList.as_view(), name='list'), url(r'^contribute/$', ContributeStat.as_view(), name='contribute'), url(r'^submit/$', SubmitStat.as_view(), name='submit'), ) <file_sep>/wotmad/artofwar/views.py from django.contrib import messages from django.shortcuts import redirect from django.template.defaultfilters import slugify from django.views.generic import DetailView, ListView from django.views.generic.edit import CreateView from braces.views import LoginRequiredMixin from .forms import LogForm from .models import Log, Category class SubmitLog(LoginRequiredMixin, CreateView): model = Log form_class = LogForm def form_valid(self, form): request = self.request log = form.save(commit=False) log.slug = slugify(log.title) log.submitter = request.user log.save() form.save_m2m() messages.success(request, "Score!") return redirect(log.get_absolute_url()) class LogDetail(DetailView): model = Log class LogList(ListView): model = Log def get_context_data(self, *args, **kwargs): ctx = super(LogList, self).get_context_data(*args, **kwargs) ctx.update(categories=Category.objects.all()) return ctx def get_queryset(self): return Log.objects.order_by('-date_submitted')
524f2e28d6282aa726dd24b3c33f75ba665ca4df
[ "Markdown", "Python", "Text" ]
8
Python
ickmund/wotmad
3c0b64cdace3707de2fd19627d1edd00f8ef7446
517de49d5fd013815c3772bb3d3509c2da5d4356
refs/heads/master
<repo_name>daniloq/-hallowmeme<file_sep>/README.md -hallowmeme =========== Ignite's Hallowmeme <file_sep>/source/javascripts/all.js //= require_tree . //= require "wow" //= require "instafeed"
4f682ffda63907adca914fb828360e59b780e087
[ "Markdown", "JavaScript" ]
2
Markdown
daniloq/-hallowmeme
15f8729f6fc7f9c71bbdd3da3b81a4f434c597e9
d418a1d0d403d3a4149e13932d8b2c715ebf6b51
refs/heads/master
<repo_name>aravind-kr/sicktree-backend<file_sep>/src/index.js const cookieParser = require('cookie-parser'); const jwt = require('jsonwebtoken'); // const express = require("express"); const next = require('next'); const rp = require('request-promise'); require('dotenv').config({ path: 'variables.env' }); const createServer = require('./createServer'); const db = require('./db'); const dev = process.env.NODE_ENV !== 'production'; const app = next({ dev }); const handle = app.getRequestHandler(); const server = createServer(); server.express.use(cookieParser()); // /dashboard -> access // app.prepare().then(() => { // const server = express(); // server.get("/dashboard", (req, res) => { // return app.render(req, res, "/dashboard", req.query); // }); // server.get("*", (req, res) => { // return handle(req, res); // }); // server.listen(3000, err => { // if (err) throw err; // console.log("> Ready on http://localhost:3000"); // }); // }); // decode the JWT so we can get the user Id on each request // server.express.use((req, res, next) => { // if(req.headers && req.headers['content-type'] === 'text/plain;charset=UTF-8') { // console.log('text/plain;charset=UTF-8') // bodyParser.text() // } // next(); // }); // server.express.use(bodyParser.text()) // server.express.use((req, res, next) => { // req.headers["content-type"] = "application/json"; // console.log('*****',typeof req.body); // next(); // }) server.express.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', 'http://localhost:7777'); res.header( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept' ); next(); }); server.express.use((req, res, next) => { const { token } = req.cookies; if (token) { const { userId } = jwt.verify(token, process.env.APP_SECRET); // put the userId onto the req for future requests to access req.userId = userId; } next(); }); // 2. Create a middleware that populates the user on each request server.express.use(async (req, res, next) => { // if they aren't logged in, skip this if (!req.userId) return next(); try { const user = await db.query.user( { where: { id: req.userId } }, '{ id, username }' ); req.user = user; } catch (error) { console.log('>>> ', error); } next(); }); server.express.get('/dashboard', async (req, res) => { try { const options = { method: 'POST', uri: 'https://api.instagram.com/oauth/access_token', formData: { client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, grant_type: 'authorization_code', redirect_uri: process.env.REDIRECT_URL, code: req.query.code, }, json: true, }; let result = await rp(options); const user = await db.mutation.upsertUser( { where: { username: result.user.username, }, create: { access_token: result.access_token, username: result.user.username, profile_picture: result.user.profile_picture, full_name: result.user.full_name, bio: result.user.bio, is_business: result.user.is_business, website: result.user.website, }, update: { access_token: result.access_token, profile_picture: result.user.profile_picture, full_name: result.user.full_name, bio: result.user.bio, is_business: result.user.is_business, website: result.user.website, }, }, '{ id, username }' ); const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET); res.cookie('token', token, { httpOnly: true, maxAge: 1000 * 60 * 60 * 24 * 365, // 1 year cookie }); res.redirect('http://localhost:7777/dashboard'); } catch (error) { console.log(error); res.redirect('http://localhost:7777/'); } }); server.start( { cors: { credentials: true, origin: [process.env.FRONTEND_URL], }, }, deets => { console.log( `Server is now running on port http://localhost:${deets.port}` ); } ); <file_sep>/src/resolvers/Mutation.js const jwt = require('jsonwebtoken'); const mutations = { async signup(parent, args, ctx, info) { const user = await ctx.db.mutation.createUser( { data: { name: 'KR', accessToken: '234', }, }, info ); const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET); // We set the jwt as a cookie on the response ctx.response.cookie('token', token, { httpOnly: true, maxAge: 1000 * 60 * 60 * 24 * 365, // 1 year cookie }); console.log('>>>', user, token); return user; }, signout(parent, args, ctx, info) { console.log('comes here'); ctx.response.clearCookie('token'); return { message: 'Goodbye!' } }, }; module.exports = mutations;
3beb236d7314115860ea8413690b3add4a80fa89
[ "JavaScript" ]
2
JavaScript
aravind-kr/sicktree-backend
8f06623066bcbcd17ce647e232798200f406c05b
0a9f372598387d52c90f8a8b847fb0e6e210eacb
refs/heads/master
<repo_name>tatsuya-yokoyama/MKNetworkKitSample<file_sep>/Podfile platform :ios, "6.0" pod "MKNetworkKit" <file_sep>/README.md # MKNetworkKitSample ↓「iOS9対応を見据えて、MKNetworkKitを使ってGETを行うサンプルをいまさら作ってみた」の記事のソースコードです。 http://qiita.com/yonell/items/3497dd0a200b7ce4a8a2
2e3c471e433829459afc8a28faacfcefd3197ba4
[ "Markdown", "Ruby" ]
2
Ruby
tatsuya-yokoyama/MKNetworkKitSample
15205f145bb27f9480c86b0cf54371fc2ce06435
e9dac98dc7a8521be52275cf68156087913737b6
refs/heads/master
<repo_name>Sujay-shetty/Assignment<file_sep>/app/js/routes.js var routesModule = angular.module ( 'MEANCaseStudy.Routes', [ 'ngRoute', 'MEANCaseStudy.Controllers' ]); function MEANCaseStudyRouteProvider(routeService) { routeService.when('/Login', { templateUrl: 'partials/login-view.html', controller: 'AuthenticationController' }); routeService.when('/Logout', { templateUrl: 'partials/login-view.html', controller: 'AuthenticationController' }); routeService.when('/Home', { templateUrl: 'partials/customers.html', controller: 'CustomersController' }); routeService.when('/NewCustomer', { templateUrl: 'partials/new-customer.html', controller: 'NewCustomersController' }); routeService.otherwise({ redirectTo: '/Login' }); } routesModule.config( [ '$routeProvider', MEANCaseStudyRouteProvider ]);<file_sep>/app/js/config.js var configurationModule = angular.module('MEANCaseStudy.Configurations', []); configurationModule.constant('appHeaderUrl', 'partials/header.html'); configurationModule.constant('appFooterUrl', 'partials/footer.html'); configurationModule.constant('customerViewerUrl', 'partials/customer-viewer.html'); configurationModule.constant('restUrl', 'http://localhost:9090/api/customers/:customerId'); configurationModule.constant('restDeleteUrl', 'http://localhost:9090/api/deleteCustomer/:customerId'); configurationModule.constant('restUpdateUrl', 'http://localhost:9090/api/updateCustomer'); configurationModule.constant('webSocketUrl', 'http://localhost:9090'); configurationModule.constant('authenticationUrl', 'http://localhost:9090/authenticate');<file_sep>/app/js/controllers.js var controllersModule = angular.module ( 'MEANCaseStudy.Controllers', [ 'MEANCaseStudy.Services' ]); function CustomersController(rootModel, viewModel, logService, customerService, webSocketUrl) { viewModel.editingData = []; if(customerService) { customerService.getAllCustomers().then( function (data) { viewModel.customers = data; console.log("logged User : ",rootModel.loggedUser); if(viewModel.loggedUser === 'caller'){ var tableContent = document.getElementById('mainTable'); var cells = tableContent.find("th, td").filter(":nth-child(" + 3 + ")"); cells.hide(); console.log("print : ", tableContent); } for (var i = 0, length = viewModel.customers.length; i < length; i++) { viewModel.editingData[viewModel.customers[i].id] = false; /*var col = 3; //col = parseInt(col, 10); //col = col - 1; for (var i = 0; i < tableContent.rows.length; i++) { for (var j = 0; j < tableContent.rows[i].cells.length; j++) { tableContent.rows[i].cells[j].style.display = ""; if (j == col) tableContent.rows[i].cells[j].style.display = "none"; } }*/ } }, function (error) { viewModel.errorMessage = error.toString(); }); } viewModel.modify = function(customer){ viewModel.editingData[customer.id] = true; }; viewModel.loadDetails = function(id) { if(id && customerService) { customerService.getCustomerDetails(id).then( function(details) { viewModel.details = details; }, function(error) { viewModel.errorMessage = error.toString(); }); } }; viewModel.updateDetails = function(customer) { if(customerService) { viewModel.editingData[customer.id] = false; customerService.updateCustomer(customer).then( function(details) { viewModel.details = details; }, function(error) { viewModel.errorMessage = error.toString(); }); } }; viewModel.deleteDetails = function(id) { if(id && customerService) { customerService.deleteCustomer(id).then( function(details) { viewModel.details = details; }, function(error) { viewModel.errorMessage = error.toString(); }); } }; var socketClient = io.connect(webSocketUrl); socketClient.on('NewCustomerRecord', function(data) { if(data) { viewModel.$apply(function() { viewModel.customers.push(data); }); } }); socketClient.on('UpdatedCustomerRecord', function(data) { if(data) { viewModel.$apply(function() { viewModel.customers.push(data); }); } }); socketClient.on('deletedCustomerRecord', function(data) { if(data) { viewModel.$apply(function() { viewModel.customers.splice(data.id); }); } }); logService.info("Customers Controller Initialization with WS Completed!"); } function NewCustomersController(viewModel, exceptionHandler, customerService) { var MIN_NUMBER = 1; var MAX_NUMBER = 50000; function generateId() { return Math.floor( Math.random() * (MAX_NUMBER - MIN_NUMBER) + MIN_NUMBER); } viewModel.newCustomer = { id: generateId() }; viewModel.status = false; viewModel.saveCustomer = function(newCustomer) { var validationStatus = newCustomer && customerService && viewModel.customerForm.$valid; if(validationStatus) { customerService.save(newCustomer).then( function(savedCustomerRecord) { viewModel.status = "Customer Record Successfully Processed!"; }, function(error) { viewModel.errorMessage = error.toString(); exceptionHandler(error.toString(), "Controller Processing"); }); } else throw new Error("Invalid Input Details Specified!"); } viewModel.phoneExpression = /^\d{10}$/; } function AuthenticationController( rootModel, viewModel, globalViewModel, userAgent, httpService, authUrl) { globalViewModel.authenticationStatus = false; viewModel.login = function(userName, password) { delete userAgent.localStorage.token; httpService.post(authUrl, { username: userName, password: <PASSWORD> }).success(function(status) { if(status) { userAgent.localStorage.token = status.token; rootModel.loggedUser = userName; if(userName == 'caller') { var newCustomerContent = document.getElementById('newCustomer');console.log("im here .... "); newCustomerContent.style.display = 'none'; } globalViewModel.authenticationStatus = true; //location.path("#/Home"); } }).error(function(message) { globalViewModel.authenticationStatus = false; viewModel.message = "Login Failed"; }); }; viewModel.logout = function() { delete userAgent.localStorage.token; globalViewModel.authenticationStatus = false; }; } controllersModule.controller('CustomersController', [ '$rootScope', '$scope', '$log', 'CustomerService', 'webSocketUrl', CustomersController ]); controllersModule.controller('NewCustomersController', [ '$scope', '$exceptionHandler', 'CustomerService', NewCustomersController ]); controllersModule.controller('AuthenticationController', [ '$rootScope', '$scope', '$rootScope', '$window', '$http', 'authenticationUrl', AuthenticationController ])<file_sep>/app/js/directives.js var directivesModule = angular.module('MEANCaseStudy.Directives', [ 'MEANCaseStudy.Configurations' ]); function MEANCaseStudyHeader(appHeaderUrl) { return { templateUrl: appHeaderUrl, restrict: 'AE' }; } function MEANCaseStudyFooter(appFooterUrl) { return { templateUrl: appFooterUrl, restrict: 'AE' }; } function CustomerProfileViewer(customerViewerUrl) { return { templateUrl: customerViewerUrl, restrict: 'E', scope: { profile: '=' }, link: function(scope, element, attributes) { scope.$watch("profile", function(newValue, oldValue, model) { if(newValue) { scope.imageUrl = 'img/' + newValue.id + '.jpg'; } }); } }; } directivesModule.directive('meanCaseStudyHeader', [ 'appHeaderUrl', MEANCaseStudyHeader ]); directivesModule.directive('meanCaseStudyFooter', [ 'appFooterUrl', MEANCaseStudyFooter ]); directivesModule.directive('customerProfileViewer', [ 'customerViewerUrl', CustomerProfileViewer ]);<file_sep>/js/server.js var os = require('os'); var http = require('http'); var express = require('express'); var bodyparser = require('body-parser'); var util = require('util'); var socketio = require('socket.io'); var expressjwt = require('express-jwt'); var jwt = require('jsonwebtoken'); var CustomerInfoProvider = require('./DataProvider'); var portNumber = process.env.PORT_NUMBER || 9090; var customerInfoProvider = new CustomerInfoProvider(); var router = new express.Router(); var globalSecretKey = "Schneider Electric, Bangalore 560025"; router.get('/api/customers', function(request, response) { customerInfoProvider.getCustomers( function(results) { response.json(results); }); }); router.get('/api/customers/:customerId', function(request, response) { var customerId = request.params.customerId; customerInfoProvider.getCustomer(customerId, function(customerRecord) { response.json(customerRecord); }); }); router.post('/api/customers', function(request, response) { var customer = request.body; customerInfoProvider.addCustomer(customer, function(result) { var addedRecord = result[0]; sioimpl.sockets.emit('NewCustomerRecord', addedRecord); response.json(addedRecord); }); }); router.get('/api/deleteCustomer/:customerId', function(request, response) { var customerId = request.params.customerId; customerInfoProvider.deleteCustomer(customerId, function(result) { var deletedRecord = result[0]; sioimpl.sockets.emit('deletedCustomerRecord', deletedRecord); response.json(deletedRecord); }); }); router.post('/api/updateCustomer', function(request, response) { var customer = request.body; customerInfoProvider.updateCustomer(customer, function(result) { var updatedRecord = result[0]; sioimpl.sockets.emit('UpdatedCustomerRecord', updatedRecord); response.json(updatedRecord); }); }); router.post('/authenticate', function(request, response) { var username = request.body.username; var password = request.body.password; var users= {"master":"master","caller":"caller"}; var validation = username === username && password === users[username]; if(!validation) { response.status(401).send( "Authorization Failed / Invalid Credentials Specified!"); return; } var profile = { id: 1, name: 'ValidUser', email: '<EMAIL>' }; var encryptedToken = jwt.sign(profile, globalSecretKey, { expiresInMinutes: 10 }); response.json({ token: encryptedToken }); }); var app = new express(); var server = http.createServer(app); var sioimpl = socketio.listen(server); sioimpl.sockets.on('connection', function(socketClient) { console.log('Web Socket Client Connected!'); socketClient.on('disconnect', function() { console.log('Web Socket Client Disconnected!'); }); }); app.use(function(request, response, next) { response.header('Access-Control-Allow-Credentials', 'true'); response.header('Access-Control-Allow-Origin', '*'); response.header('Access-Control-Allow-Methods', '*'); response.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); next(); }); app.use('/api/customers', expressjwt({ secret: globalSecretKey })); app.use(bodyparser.json()); app.use('/', router); server.listen(portNumber); var message = util.format( "REST Service is on .. http://%s:%d/api/customers", os.hostname(), portNumber); console.log(message);<file_sep>/app/js/services.js var servicesModule = angular.module('MEANCaseStudy.Services', [ 'ngResource', 'MEANCaseStudy.Configurations' ]); function CustomerService(restService, restUrl, restDeleteUrl, restUpdateUrl) { var customerRESTService = restService(restUrl, {}, { addNew: { method: 'POST' } }); var customerRESTDeleteService = restService(restDeleteUrl, {}, { deleteCustomerRecord: { method: 'DELETE' } }); var customerRESTUpdateService = restService(restUpdateUrl, {}, { updateCustomerRecord: { method: 'POST' } }); var service = { getAllCustomers: function() { return customerRESTService.query().$promise; }, getCustomerDetails: function(id) { return customerRESTService.get({ customerId: id }).$promise; }, save: function(customerRecord) { return customerRESTService.addNew( customerRecord).$promise; }, deleteCustomer: function(id) { return customerRESTDeleteService.get({ customerId: id }).$promise; }, updateCustomer: function(updateCustomerRecord) { return customerRESTUpdateService.updateCustomerRecord(updateCustomerRecord).$promise; } }; return service; } servicesModule.factory('CustomerService', [ '$resource', 'restUrl', 'restDeleteUrl', 'restUpdateUrl', CustomerService ]);
61f79bad2c3a249b2596d0b58eccc5c4968d8f9f
[ "JavaScript" ]
6
JavaScript
Sujay-shetty/Assignment
ef62b4f895dcb481f8275785c00514e9ee5930ce
0c417cad464bdaab6d974bceecfb656b00d00a39
refs/heads/master
<repo_name>impatient/markdown-es6<file_sep>/src/tokenClasses.js export var NEWLINE = new RegExp(/(\n+)/); export var SPACE = new RegExp(/([^\n][\s\t]+)/); export var WORD = new RegExp(/(\w+)/); export var PUNCT = new RegExp(/([\^\[\]\!\*\+\-`#])/); export default {SPACE, NEWLINE, WORD,PUNCT}; <file_sep>/Gruntfile.js 'use strict'; module.exports = function(grunt) { grunt.initConfig({ traceur: { options: { sourceMaps: true // default: false }, custom: { options: { fileRoot: 'src/', modules:'commonjs' }, files:{ 'bin/': ['src/**/*.js'] // dest : [source files] } } }, mochaTest: { test: { options: { reporter: 'spec' }, src: ['test/**/*.js'] } }, watch: { es6: { files: ['src/*.js'], tasks: ['traceur'] } } }); grunt.loadNpmTasks('grunt-traceur'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.registerTask('default', ['traceur']); }; <file_sep>/src/main.js var traceur = require('traceur'); traceur.require.makeDefault(function(filename) { // don't transpile our dependencies, just our app return filename.indexOf('node_modules') === -1; }); import {Lexer} from './Lexer'; module tokens from './tokenClasses'; import tokenDefault from './tokenClasses'; import {SPACE} from './tokenClasses'; console.log(new Lexer().tokens('\n\n\n\n').next()); console.log('Newline', tokens.NEWLINE, 'end'); console.log('tokenDefault', tokenDefault); console.log('SPACE', SPACE, '||'); <file_sep>/src/Lexer.js require('traceur'); require('source-map-support').install(); import primaryTokens from './tokenClasses'; class Lexer { constructor(){ console.log('Lexer constructor'); } *tokens(input) { var all = input; while(all.length > 0) { var key, value,matched; matched = Object.keys(primaryTokens).find((currentKey) => { var match = primaryTokens[currentKey].exec(all); if(match) { key = currentKey; value = match[0]; return true; } }); if(matched) { all = all.substring(value.length); } else { key = 'unknown'; value = all[0]; all = all.substring(1); } yield {key, value }; } return all[0]; } } export {Lexer};<file_sep>/readme.md Markdown Parser for ES6 Not remotely completed. Pre-pre-pre-pre alpha
f82c5ab5b88c05a0768564953e8faa60923cee52
[ "JavaScript", "Markdown" ]
5
JavaScript
impatient/markdown-es6
072e197eb1e43106545280bf3c505cde66402d5d
70e1a8a67eb9a9373c60eed624cb472e66f4cbd5
refs/heads/master
<repo_name>iGusky/sigfox-backend<file_sep>/controllers/messageController.js const Messages = require('../models/Messages.js'); const Message = require('../models/Messages'); exports.newMessage = async ( req, res, next ) => { const message = new Messages( req.body ); try { await message.save(); res.json({ mensaje: 'Se agrego correctamente' }) } catch (error) { res.send(error); next(); } } exports.getMessages = async ( req, res, next ) => { try { const messages = await Messages.find({}) .sort({time: -1}) .limit(10); res.json({messages}); } catch (error) { res.send(error); } } exports.getAllMessages = async (req, res, next) => { const { page=1, limit=50 } = req.query; try { const messages = await Messages.find({}) .sort({time: -1}) .limit(limit * 1) .skip((page-1) * limit) .exec(); const count = await Messages.countDocuments(); res.json({ messages , totalPages: Math.ceil(count/limit), currentPage: page, totalElements: count }); } catch (error) { console.error(error) } }
6145c2e4f4873ef428c9b0de2a5acc0065e25e65
[ "JavaScript" ]
1
JavaScript
iGusky/sigfox-backend
26432804f2a08d04b3791a55b7ca98ed03eba6c4
e1936b64ca0ad1d8d2f85530e81de986b5d5baae
refs/heads/master
<repo_name>zimniakkajetan/IwM-tomograf<file_sep>/main.py #!/usr/bin/python3 from tkinter import * from tkinter import filedialog from _thread import * from math import * import numpy as np import time from PIL import ImageTk, Image import PIL class obraz(): wejsciowy = [] class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.init_window() #Creation of init_window def init_window(self): # changing the title of our master widget self.master.title("Tomograf") # allowing the widget to take the full space of the root window self.pack(fill=BOTH, expand=1) self.grid(padx=4,pady=4) # creating image canvases self.inputCanvas = Canvas(self,width=200, height=200,bg='white') self.inputCanvas.create_rectangle(2,2,200,200) self.inputCanvas.create_text(100,100,text="Obraz wejściowy") self.inputCanvas.grid(row=0,column=0) self.sinogramCanvas = Canvas(self, width=200,height=200,bg='white') self.sinogramCanvas.create_rectangle(2,2,200,200) self.sinogramCanvas.create_text(100,100,text="Sinogram") self.sinogramCanvas.grid(row=0,column=1) self.outputCanvas = Canvas(self,width=200,height=200,bg='white') self.outputCanvas.create_rectangle(2,2,200,200) self.outputCanvas.create_text(100,100,text="Obraz wyjściowy") self.outputCanvas.grid(row=0,column=2) self.uploadInputButton = Button(self,text="Wgraj obraz",command=self.upload_input_file) self.uploadInputButton.grid(row=1,column=0,pady=2) xpadding=10 top_padding=20 bottom_padding=5 Label(self,text="Parametry:").grid(row=2,column=0,pady=(top_padding,bottom_padding)) Label(self,text="Liczba detektorów:").grid(row=3,column=0,sticky='w',padx=xpadding) self.detectorsEntry=Entry(self,width=4,justify=RIGHT) self.detectorsEntry.grid(row=3,column=0,sticky='e',padx=xpadding) Label(self,text="Kąt przesunięcia:").grid(row=4,column=0,sticky='w',padx=xpadding) self.angleEntry = Entry(self,width=4,justify=RIGHT) self.angleEntry.grid(row=4,column=0,sticky='e',padx=xpadding) Label(self,text="Rozwartość:").grid(row=5,column=0,sticky='w',padx=xpadding) self.coneWidthEntry=Entry(self,width=4,justify=RIGHT) self.coneWidthEntry.grid(row=5,column=0,sticky='e',padx=xpadding) self.filterVar = IntVar(value=1) Checkbutton(self,text="Użyj filtrowania",variable=self.filterVar).grid(row=6,column=0,sticky='w',padx=xpadding) self.gaussVar = IntVar(value=0) Checkbutton(self,text="Użyj rozmycia Gaussa",variable=self.gaussVar).grid(row=7,column=0,sticky='w',padx=xpadding) self.stepsVar = IntVar(value=1) stepsCheckbutton = Checkbutton(self,text="Pokazuj kroki pośrednie",variable=self.stepsVar,command=self.set_speed_visibility) stepsCheckbutton.grid(row=2,column=1,columnspan=2,pady=(top_padding,bottom_padding)) self.speedLabel = Label(self,text="Prędkość:") self.speedLabel.grid(row=3,column=1,columnspan=2) self.speedSlider = Scale(self,from_=0,to=100,orient=HORIZONTAL,length=250) self.speedSlider.grid(row=4,column=1,columnspan=2,rowspan=2) self.startButton = Button(self,text="Start",command=self.makeSinogram1, width=8) self.startButton.grid(row=8,column=2,sticky='e',padx=20,pady=10) self.error = StringVar() Label(self, textvariable=self.error, fg="red", font=("Helvetica", 16)).grid(row=8) self.set_default_values() self.master.update() self.create_filter_kernel() def set_speed_visibility(self): if self.stepsVar.get() == 0: self.speedLabel.grid_forget() self.speedSlider.grid_forget() if self.stepsVar.get() == 1: self.speedLabel.grid(row=3,column=1,columnspan=2) self.speedSlider.grid(row=4,column=1,columnspan=2,rowspan=2) def set_default_values(self): self.speedSlider.set(100) self.detectorsEntry.insert(END,50) self.angleEntry.insert(END,1) self.coneWidthEntry.insert(END,90) def upload_input_file(self): filename = filedialog.askopenfilename(filetypes=[('Image','jpg jpeg png gif')]) if filename != "": self.set_input_image(filename) def set_image(self,path,canvas): img = Image.open(path) print(img) temp = np.array(img.convert('L')) img = img.resize((canvas.winfo_width(), canvas.winfo_height()), Image.ANTIALIAS) obraz.wejsciowy = temp canvas.image = ImageTk.PhotoImage(img) canvas.create_image(0, 0, image=canvas.image, anchor=NW) def set_input_image(self,path): self.set_image(path,self.inputCanvas) def set_sinogram_image(self,path): self.set_image(path,self.sinogramCanvas) def set_output_image(self,path): self.set_image(path,self.outputCanvas) def bresenhamLine(self, x1, y1, x2, y2): line = [] if (x1 <= x2): xi = 1 else: xi = -1 if (y1 <= y2): yi = 1 else: yi = -1 dx = abs(x2 - x1) dy = abs(y2 - y1) x = x1 y = y1 line.append([int(x), int(y)]) if (dx >= dy): ai = (dy - dx) * 2 bi = dy * 2 d = bi - dx while (x != x2): if (d >= 0): x += xi y += yi d += ai else: d += bi x += xi line.append([int(x), int(y)]) else: ai = (dx - dy) * 2 bi = dx * 2 d = bi - dy while (y != y2): if (d >= 0): x += xi y += yi d += ai else: d += bi y += yi line.append([int(x), int(y)]) return line def makeSinogram1(self): self.error.set("") self.sinogramCanvas.create_rectangle(0, 0, self.sinogramCanvas.winfo_width(), self.sinogramCanvas.winfo_height(), fill="black") start_new_thread(self.makeSinogram, ()) def makeSinogram(self): pic = obraz.wejsciowy #numberOfDetectors = 50 numberOfDetectors = int(self.detectorsEntry.get()) #alpha = 1 alpha = float(self.angleEntry.get()) #rozpietosc = 90 rozpietosc = float(self.coneWidthEntry.get()) rozpietoscRadiany = rozpietosc * np.pi / 180; pic_size = len(pic[0]) r = pic_size lines = [] i = 0 finishAngle=360 sinogram=[[0 for x in range(numberOfDetectors)] for y in range(int(finishAngle/alpha))] while i < finishAngle: lines.append([]) katRadiany = i * np.pi / 180 x0 = r * np.cos(katRadiany) y0 = r * np.sin(katRadiany) x0 = int(x0) + np.floor(pic_size / 2) y0 = int(y0) + np.floor(pic_size / 2) for detector in range(0, numberOfDetectors): x1 = r * np.cos(katRadiany + np.pi - rozpietoscRadiany / 2 + detector * ( rozpietoscRadiany / (numberOfDetectors - 1))) y1 = r * np.sin(katRadiany + np.pi - rozpietoscRadiany / 2 + detector * ( rozpietoscRadiany / (numberOfDetectors - 1))) x1 = int(x1) + np.floor(pic_size / 2) y1 = int(y1) + np.floor(pic_size / 2) line = self.bresenhamLine(x0, y0, x1, y1) pixel = np.float(0) pixLicz = int(0) for [x, y] in line: if x >= 0 and y >= 0 and x < pic_size and y < pic_size: pixel += float(pic[x, y]) pixLicz += 1 if pixLicz > 0: sinogram[int(i/alpha)][detector]=(pixel / pixLicz) else: sinogram[int(i/alpha)][detector]=0 lines[-1].append([x0, y0, x1, y1]) i += alpha while self.stepsVar.get()==1 and self.speedSlider.get()==0: pass time.sleep((100-self.speedSlider.get())/1000) if self.stepsVar.get() == 1: self.setSinogramOutput(sinogram) self.setSinogramOutput(sinogram) #obraz.sinogram = np.array(sinogram) start_new_thread(self.makePicture, (sinogram,lines,pic)) return sinogram, lines def setSinogramOutput(self,sin): #self.sinogramCanvas.delete("all") self.sinogramCanvas.image = ImageTk.PhotoImage(PIL.Image.fromarray(np.array(sin)).resize((self.sinogramCanvas.winfo_width(),self.sinogramCanvas.winfo_height()),Image.ANTIALIAS)) self.sinogramCanvas.create_image(0, 0, image=self.sinogramCanvas.image, anchor=NW) def setPicture2Output(self,pic): #self.outputCanvas.delete("all") self.outputCanvas.image = ImageTk.PhotoImage(PIL.Image.fromarray(np.array(pic)).resize((self.outputCanvas.winfo_width(),self.outputCanvas.winfo_height()),Image.ANTIALIAS)) self.outputCanvas.create_image(0, 0, image=self.outputCanvas.image, anchor=NW) def makePicture(self, sinog, lines, pic): print("start make picture") self.outputCanvas.create_rectangle(0, 0, self.outputCanvas.winfo_width(), self.outputCanvas.winfo_height(), fill="black") picture2 = np.zeros([np.shape(pic)[0], np.shape(pic)[1]]) picture2sums = np.zeros([np.shape(pic)[0],np.shape(pic)[1]]) a = np.shape(sinog)[0] b = np.shape(sinog)[1] count = np.zeros([np.shape(pic)[0], np.shape(pic)[1]]) use_filter = self.filterVar.get()==1 for i in range(0, a, 1): if use_filter: view = self.filter(sinog[i]) else: view=sinog[i] for j in range(0, b, 1): x0, y0, x1, y1 = lines[i][j] line = self.bresenhamLine(x0, y0, x1, y1) for [x, y] in line: if x >= 0 and y >= 0 and x < np.shape(pic)[0] and y < np.shape(pic)[1]: picture2sums[x][y]+=view[j] count[x][y]+=1 picture2[x][y]=picture2sums[x][y] if not use_filter: picture2[x][y]=picture2sums[x][y]/count[x][y] while self.stepsVar.get()==1 and self.speedSlider.get()==0: pass time.sleep((100-self.speedSlider.get())/1000) if self.stepsVar.get()==1: self.setPicture2Output(picture2) if self.gaussVar.get()==1: picture2=self.denoise(picture2) self.setPicture2Output(picture2) #print(self.blad(obraz.wejsciowy, picture2)) self.error.set("Błąd: " + str(round(self.blad(obraz.wejsciowy, picture2),2))) return picture2 #OBECNIE denoise oraz average NIEUŻYWANE def denoise(self,picture): picture2 = np.zeros([np.shape(picture)[0], np.shape(picture)[1]]) for i in range(1, picture2.shape[0]): for j in range(1, picture2.shape[1]): picture2[i][j] = self.average(picture, i, j) return picture2 def average(self,picture, x, y): sum = 0 kernel=[[1,4,7,4,1],[4,16,26,16,4],[7,26,41,26,7],[4,16,26,16,4],[1,4,7,4,1]] denominator=273 for i in range(-2, 2): for j in range(-2, 2): if x+i>0 and x+i<np.shape(picture)[0] and y+j>0 and y+j<np.shape(picture)[1]: sum += picture[x + i][y + j]*kernel[i+2][j+2] return int(sum / denominator) def create_filter_kernel(self): self.kernel = np.zeros(40) for i in range(0, 40): index = abs(i - 20) if index % 2 == 0: self.kernel[i] = 0 if index % 2 == 1: self.kernel[i] = (-4.0 / (pi ** 2)) / (index ** 2) if index == 0: self.kernel[i] = 1 def filter(self,view): newView = np.zeros(len(view)) for i in range(0,len(view)): for j in range(0,len(self.kernel)): center = int(len(self.kernel)/2) k=j-center if i+k>0 and i+k<len(view): newView[i]+=view[i+k]*self.kernel[j] return newView def blad(self, pic1, pic2): suma = 0 for row in range(len(pic1)): for col in range(len(pic1[0])): suma += (pic1[row][col] - pic2[row][col]) * (pic1[row][col] - pic2[row][col]) return sqrt(suma / (len(pic1)*len(pic1[0]))) root = Tk() root.geometry("620x460") app=Window(root) root.mainloop()
5d3ba3a877ff6013ed51fa101779388966c1085a
[ "Python" ]
1
Python
zimniakkajetan/IwM-tomograf
51265ed840239abd3c6e03b92e7a277782447e21
00d800840afa20febae86f8429566628dca74934
refs/heads/master
<file_sep>#include "stdio.h" // #include "g2otypes.h" #include "glog/logging.h" #include "eigen3/Eigen/Core" #include "eigen3/Eigen/Geometry" #include "ros/ros.h" #include "fstream" #include <rosbag/bag.h> #include <rosbag/view.h> #include <std_msgs/Int32.h> #include <std_msgs/String.h> #include <sensor_msgs/Imu.h> #include <sensor_msgs/PointCloud2.h> // #include <sensor_msgs/CompressedImage.h> #include <sensor_msgs/Image.h> #include <geometry_msgs/Vector3.h> #include <geometry_msgs/PoseStamped.h> #include <nav_msgs/Odometry.h> // #include "Thirdparty/sophus/sophus/so3.hpp" // #include "Thirdparty/sophus/sophus/se3.hpp" #include "poslvx/INS.h" #include "poslvx/INSRMS.h" #include <boost/foreach.hpp> #define foreach BOOST_FOREACH using namespace std; using namespace Eigen; int main(int argc, char **argv){ // google::InitGoogleLogging(argv[0]); // FLAGS_colorlogtostderr=true; // FLAGS_alsologtostderr = true; // google::InstallFailureSignalHandler(); ros::init(argc, argv, "merge_bag"); ros::start(); ros::NodeHandle pnh("~"); string bagname1, bag_with_imu_name, bag_merge_name; bool getbagname1=pnh.getParam("bag1", bagname1); bool getbagimu=pnh.getParam("bag2_with_imu", bag_with_imu_name); bool getbagmerge=pnh.getParam("bag_merge", bag_merge_name); if(!(getbagimu&&getbagname1&&getbagmerge)){ cout<<"can get bag name"<<endl; } string left_image_name = "/stereo_grey/left/image_raw"; string right_image_name = "/stereo_grey/right/image_raw"; string imu_msg_name = "/xsens/imu_data"; std::vector<string> topics1; // topics1.push_back("/stereo_grey/left/image_raw"); // topics1.push_back("/stereo_grey/right/image_raw"); topics1.push_back("/ins/data"); topics1.push_back("/lidar_center/velodyne_points"); topics1.push_back("/xsens/imu_data"); std::vector<string> topics2; topics2.push_back("/ins/data"); topics2.push_back("/ins/rms"); // topics2.push_back(imu_msg_name); // topics2.push_back(left_image_name); // topics2.push_back(right_image_name); topics2.push_back("/lidar_center/velodyne_points"); rosbag::Bag new_bag_merge, bag1, bag_with_imu; new_bag_merge.open(bag_merge_name, rosbag::bagmode::Write); bag1.open(bagname1, rosbag::bagmode::Read); bag_with_imu.open(bag_with_imu_name, rosbag::bagmode::Read); rosbag::View view1(bag1, rosbag::TopicQuery(topics1)); rosbag::View view_with_imu(bag_with_imu, rosbag::TopicQuery(topics2)); cout<<"----bags opened!----" << endl; foreach(rosbag::MessageInstance const m, view1){ sensor_msgs::ImageConstPtr im_msg_left = m.instantiate<sensor_msgs::Image>(); if((im_msg_left!=nullptr) && (m.getTopic() == left_image_name)){ new_bag_merge.write(left_image_name, im_msg_left->header.stamp, *im_msg_left); }else if((im_msg_left!=nullptr) && (m.getTopic() == right_image_name)){ new_bag_merge.write(right_image_name, im_msg_left->header.stamp, *im_msg_left); } sensor_msgs::ImuConstPtr imu_msg = m.instantiate<sensor_msgs::Imu>(); if((imu_msg!=nullptr) && m.getTopic()==imu_msg_name ){ new_bag_merge.write(imu_msg_name, imu_msg->header.stamp, *imu_msg); } sensor_msgs::PointCloud2Ptr lidar_msg = m.instantiate<sensor_msgs::PointCloud2>(); if((lidar_msg!=nullptr) && (m.getTopic()=="/lidar_center/velodyne_points")){ new_bag_merge.write("/lidar_center/velodyne_points", lidar_msg->header.stamp, *lidar_msg); } poslvx::INSConstPtr gps_msg = m.instantiate<poslvx::INS>(); if((gps_msg!=nullptr) && (m.getTopic()=="/ins/data")){ poslvx::INS new_gps = *gps_msg; new_gps.header.stamp.fromSec(gps_msg->header.stamp.toSec()-6.500); new_bag_merge.write("/ins/data", new_gps.header.stamp, new_gps); // cout << m.getTopic() <<" in ins" << endl; } poslvx::INSRMSConstPtr rms_msg = m.instantiate<poslvx::INSRMS>(); if((rms_msg!=nullptr) && (m.getTopic()=="/ins/rms")){ poslvx::INSRMS new_rms = *rms_msg; new_rms.header.stamp.fromSec(rms_msg->header.stamp.toSec()-6.50); new_bag_merge.write("/ins/rms", new_rms.header.stamp, new_rms); } } cout << "add one bag done!" <<endl; foreach(rosbag::MessageInstance const m, view_with_imu){ poslvx::INSConstPtr gps_msg = m.instantiate<poslvx::INS>(); if((gps_msg!=nullptr) && (m.getTopic()=="/ins/data")){ poslvx::INS new_gps = *gps_msg; new_gps.header.stamp.fromSec(gps_msg->header.stamp.toSec()-6.50); new_bag_merge.write("/ins/data", new_gps.header.stamp, new_gps); } poslvx::INSRMSConstPtr rms_msg= m.instantiate<poslvx::INSRMS>(); if((rms_msg!=nullptr) && (m.getTopic()=="/ins/rms")){ poslvx::INSRMS new_rms = *rms_msg; new_rms.header.stamp.fromSec(rms_msg->header.stamp.toSec()-6.50); new_bag_merge.write("/ins/rms", new_rms.header.stamp, new_rms); } sensor_msgs::PointCloud2Ptr lidar_msg = m.instantiate<sensor_msgs::PointCloud2>(); if((lidar_msg!=nullptr) && (m.getTopic()=="/lidar_center/velodyne_points")){ new_bag_merge.write("/lidar_center/velodyne_points", lidar_msg->header.stamp, *lidar_msg); } sensor_msgs::ImuConstPtr imu_msg = m.instantiate<sensor_msgs::Imu>(); if((imu_msg!=nullptr) &&(m.getTopic()==imu_msg_name)){ new_bag_merge.write(imu_msg_name, imu_msg->header.stamp, *imu_msg); } sensor_msgs::ImageConstPtr im_msg_left = m.instantiate<sensor_msgs::Image>(); if((im_msg_left!=nullptr) && (m.getTopic() == left_image_name)){ new_bag_merge.write(left_image_name, im_msg_left->header.stamp, *im_msg_left); }else if((im_msg_left!=nullptr) && (m.getTopic() == right_image_name)){ new_bag_merge.write(right_image_name, im_msg_left->header.stamp, *im_msg_left); } } cout << "done!" <<endl; new_bag_merge.close(); bag1.close(); bag_with_imu.close(); }<file_sep>cmake_minimum_required(VERSION 2.8.3) project(cyy_tools) ## Compile as C++11, supported in ROS Kinetic and newer add_compile_options(-std=c++11) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/modules) ## Find catkin macros and libraries ## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz) ## is used, also find other catkin packages find_package(Glog REQUIRED) find_package(catkin REQUIRED COMPONENTS cv_bridge eigen_conversions rosbag roscpp roslib tf sensor_msgs geometry_msgs nav_msgs poslvx ) catkin_package( # INCLUDE_DIRS include # LIBRARIES cyy_tools # CATKIN_DEPENDS cv_bridge eigen_conversions rosbag roscpp roslib tf # DEPENDS system_lib ) include_directories( include ${catkin_INCLUDE_DIRS} ${GLOG_INCLUDE_DIRS} ) add_executable(merge_bags_node src/merge_bag.cpp) target_link_libraries(merge_bags_node ${catkin_LIBRARIES} ) install(TARGETS merge_bags_node ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} #RUNTIME DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION } / ${PROJECT_NAME } ) install(DIRECTORY launch DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} )
7ccdf0d210f15a0f1d7a38a95759f2c8a872a4c7
[ "CMake", "C++" ]
2
C++
cyy1992/tool_ws
c422269ee2bd0731cd140aca6ac84923f4d92075
872763038b87e59081dc8fcff79e17eef81d3fdd
refs/heads/master
<file_sep><?php return array( "client_id" => "1044535373669-4bpflbuk0r08inoa9t31upjk4sfo2e04.apps.googleusercontent.com", "service_account_name" => "1044535373669-4bpflbuk0r08inoa9t31upjk4sfo2e04@developer.gserviceaccount.com", "key_file_location" => base_path() . "/app/config/4ba99babbe26eb75355122f662ca72be2368a5a5-privatekey.p12", "timezone" => "+05:30", "calendar_id" => "<EMAIL>", );<file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class AddAvailableOutTimeToLeavesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('leaves', function(Blueprint $table) { $table->time('available_out_time')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('leaves', function(Blueprint $table) { $table->dropColumn('available_out_time'); }); } } <file_sep><?php /* Class Name : Leave author : <NAME> Date : June 02, 2014 Purpose : Model class for leaves table Table referred : leaves Table updated : leaves Most Important Related Files : /app/models/Leave.php */ class Leave extends \Eloquent { const APPROVED_BY_NONE = 0; const APPROVED_BY_SOME = 1; const REJECTED_BY_SOME = 2; const APPROVED_BY_ALL = 3; const REJECTED_BY_ALL = 4; const PENDING = 5; const APPROVED_BY_ADMIN = 6; // Validation Rules public static $rules = [ 'leave_option' => 'required|in:LEAVE,CSR', 'leave_date' => 'required', 'leave_type' => 'required|in:LEAVE,CSR,FH,SH,LONG,MULTI', 'reason' => array('required', 'max:255'), ]; // fillable fields protected $fillable = ['user_id', 'leave_type', 'leave_date', 'leave_to', 'from_time', 'to_time', 'reason']; public function user() { return $this->belongsTo('User'); } public function approvals() { return $this->hasMany('Approval'); } /* Function Name : pendingLeaves Author Name : <NAME> Date : June 20, 2014 Parameters : -- Purpose : This function retuns an array of pending leaves for all users */ public static function pendingLeaves(){ $leaves = Leave::all(); $pendingLeaves = array(); foreach($leaves as $leave){ if($leave->approvalStatus( Leave::PENDING ) && !$leave->approvalStatus( Leave::APPROVED_BY_ADMIN)){ $pendingLeaves[] = $leave; } } return $pendingLeaves; } public function csrs() { return $this->hasMany('Csr'); } /* Function Name : normalizeInput Author Name : <NAME> Date : June 03, 2014 Parameters : array of inputs Purpose : This function used to normalize time slots to save into database */ public static function normalizeInput($inputs) { $row = []; foreach($inputs['from_hour'] as $tempKey => $tempData) { $row[$tempKey] = ['user_id' => $inputs['user_id'], 'leave_date' => $inputs['leave_date'], 'leave_type' => $inputs['leave_type'], 'from_time' => $inputs['from_hour'][$tempKey].':'.$inputs['from_min'][$tempKey], 'to_time' => $inputs['to_hour'][$tempKey].':'.$inputs['to_min'][$tempKey], 'reason' => $inputs['reason'], 'approver_id' => $inputs['approver_id']]; } return $row; } /* Function Name : isApproved Author Name : <NAME> Date : June 03, 2014 Parameters : - Purpose : This function returns boolean value based on $approveStage parameter value Return : one of following values: APPROVED_BY_ALL, REJECTED_BY_ALL, APPROVED_BY_SOME, APPROVED_BY_NONE */ public function approvalStatus($requiredStatus) { $allApprovals = $this->approvals->toArray(); $approvedApprovals = Approval::where("leave_id",$this->id)->where("approved", "YES")->get()->toArray(); $rejectedApprovals = Approval::where("leave_id",$this->id)->where("approved", "NO")->get()->toArray(); $admins = User::where("employeeType","ADMIN")->lists("id","id"); $adminApprovals = Approval::where("leave_id", $this->id)->where("approved","YES")->whereIn("approver_id", $admins)->count(); switch($requiredStatus){ case Leave::APPROVED_BY_ADMIN: return ($adminApprovals > 0); case Leave::APPROVED_BY_SOME: return count($approvedApprovals) >= 1; case Leave::APPROVED_BY_ALL: return count($allApprovals) == count($approvedApprovals); case Leave::APPROVED_BY_NONE: return count($approvedApprovals) == 0; case Leave::REJECTED_BY_ALL: return count($allApprovals) == count($rejectedApprovals); case Leave::REJECTED_BY_SOME: return count($rejectedApprovals) > 0; case Leave::PENDING: return (count($allApprovals) - (count($rejectedApprovals) + count($approvedApprovals))) > 0; } } /* Function Name : leaveStatus Author Name : <NAME> Date : June 19, 2014 Parameters : leaveId Purpose : This function used to return status of a leave (PENDING|APPROVED|REJECTED) */ public function leaveStatus() { if($this->approvalStatus(Leave::APPROVED_BY_ADMIN)){ return "APPROVED"; } if ($this->approvalStatus(Leave::APPROVED_BY_ALL)) return "APPROVED"; elseif($this->approvalStatus(Leave::REJECTED_BY_ALL) || $this->approvalStatus(Leave::REJECTED_BY_SOME)) return "REJECTED"; elseif( $this->approvalStatus( Leave::PENDING ) ) return "PENDING"; } public function leaveNotification($leaveId) { // Get user who has requested a leave or CSR $requesting_user = User::find(Auth::user()->id); // Get approver details $approver_user = User::find($approval->approver_id); // Construct subject line for the email $request_type = TemplateFunction::getFullLeaveTypeName($approval->leave->leave_type); $subject = "$request_type request from $requesting_user->name"; // form a data array to be passed in view $data = []; $data['requesting_user'] = $requesting_user->toArray(); // Get leave details $leave = Leave::find($approval->leave_id); $data['leave'] = $leave->toArray(); // if leave type is a CSR then merge this as well in data if ( "CSR" == $approval->leave->leave_type ) { $data['csr'] = $approval->leave->csrs->toArray(); } //Send email notification to approver Mail::queue('emails.leave_request', $data, function($message) use($approver_user, $subject) { $message->from('<EMAIL>', 'Admin'); $message->to($approver_user->email, $approver_user->name); $message->subject($subject); }); } }<file_sep><?php class ApprovalController extends \BaseController { /* Function Name : pending Author Name : <NAME> Date : June 04, 2014 Parameters : none Purpose : This function used to show pending leave request for approver */ public function pending() { $pending_approvals = Approval::pending(); return View::make('leaves.pending')->with('leaves', $pending_approvals); } /* Function Name : updateStatus Author Name : <NAME> Date : June 04, 2014 Parameters : none Purpose : This function used to update the leave status and calendar event */ public function updateStatus() { $auth_user = Auth::user(); if($auth_user->employeeType == "ADMIN"){ $approval = new Approval(); $approval->approved = "PENDING"; $approval->approver_id = Auth::user()->id; $approval->approval_note = "Status Updated By Admin"; $approval->leave_id = Input::get("leaveId"); $leave = Leave::find(Input::get("leaveId")); $approval->save(); $approval_status = "YES"; } else{ $approval = Approval::findOrFail(Input::get('approvalId')); $leave = $approval->leave()->first(); if($approval->approver_id != Auth::user()->id){ return Response::json(array('status' => true, 'message' => 'You are not allowed to approve this leave')); } $approval_status = Input::get('approvalStatus'); } $approval->approved = $approval_status; $approval->save(); $approval->sendApprovalNotification(); $approval->markCalendarEvent(); // $leaveId = Input::get("leaveId"); $leave_user_id = $leave->user()->get()->first()->id; $fully_approved = $leave->leaveStatus() == "APPROVED" ? true : false; $json_data = array( "leave_user_id" => $leave_user_id, "fully_approved" => $fully_approved, "status" => true ); return Response::json($json_data); } /* Function Name : leaveApprovals Author Name : <NAME> Date : 06, June 2014 Parameters : $id -> id of leave Purpose : this function provides the user with the information on approvals of his/her leave/csr requests */ public function leaveApprovals($id){ $leave = Leave::find($id); return View::make("leaves.leaveapprovals")->with("leave", $leave); } } <file_sep>/** Page Name: common.js author : <NAME> Date: June, 03 2014 Purpose: This page contains javascript used in admin or user panels Table referred: - Table updated: - Most Important Related Files: - */ // Tooltip on Anchors $('a[data-toggle="tooltip"]').tooltip({ animated: 'fade', placement: 'bottom', }); (function ( $ ) { $.blockUI = function(){ $("#blockUI").removeClass("hide"); }; $.unblockUI = function(){ $("#blockUI").addClass("hide"); }; }( jQuery )); if(($(".in_time").length == 1) && $(".in_time").val() == ""){ $(".in_time").val("09:30 AM"); } if(($(".out_time").length == 1) && $(".out_time").val() == ""){ $(".out_time").val("09:30 AM"); } $('#leave_option').on('change', function(elem){ var leave_option = $(this).val(); $csr_container = $('#csr-container'); if( 'CSR' == leave_option ) { $csr_container.removeClass("hide"); $("#leave-type-form-group").addClass("hide"); $("#date-control").addClass("date-single").removeClass("date-multiple").removeClass("date-long"); } else{ if('' == leave_option){ $csr_container.addClass("hide"); $("#leave-type-form-group").addClass("hide"); } else{ $csr_container.addClass("hide"); $("#leave-type-form-group").removeClass("hide"); } } }); $('#leave_type').on('change',function(e){ var leave_type = $(this).val(); $csr_container = $('#csr-container'); if( 'CSR' == leave_type ) { $csr_container.removeClass("hide"); $("#date-control").addClass("date-single").removeClass("date-multiple").removeClass("date-long"); } else if( "LEAVE" == leave_type || "FH" == leave_type || "SH" == leave_type) { $csr_container.removeClass("show").addClass("hide"); $("#date-control").addClass("date-single").removeClass("date-multiple").removeClass("date-long"); } else if("LONG" == leave_type){ $("#date-control").removeClass("date-single").removeClass("date-multiple").addClass("date-long"); } else{ $("#date-control").addClass("date-multiple").removeClass("date-single").removeClass("date-long"); } if($(".date_control").hasClass("date-long")){ $(".date-long").multiDatesPicker({ maxPicks: 2, showOn : "both", dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true, yearRange: "-100:+0" }); } else if($(".date_control").hasClass("date-multiple")){ $(".date-multiple").multiDatesPicker({ maxPicks: 10, showOn : "both", dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true, yearRange: "-100:+0" }); } else{ $(".date_control").multiDatesPicker({ maxPicks: 1, showOn : "both", dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true, yearRange: "-100:+0" }); } $("#date-control").val(''); $("#date-control").multiDatesPicker('resetDates'); }); $(document).on("ready",function(){ if($("#addSlot").length == 1){ if($("#timeSlot").find(".row.form-group").length == 2) { $("#addSlot").remove(); } window.timeSlotHtml = $('#timeSlot').find(".row.form-group").last().html(); $('#addSlot').on('click', function(e){ var slotCount = $("#timeSlot").find(".row.form-group").length.toString(); $('#timeSlot').append("<div class='row form-group has-feedback'></div>") $('#timeSlot .row.form-group:last').append(window.timeSlotHtml); $("#timeSlot").find(".row.form-group").last().find('input').each(function() { $name = $(this).attr('name'); $name = $name.replace(/[0-9]+/g,slotCount); $(this).attr("name",$name); }); if($("#timeSlot").find(".row.form-group").length == 2) { $("#addSlot").remove(); } $('.timepicker').timepicker({ minuteStep: 5, showInputs: true, disableFocus: true, defaultTime: false }); }); } }); $(document).on("ready",function(){ // applies multiselect if( $('.multiselect').length !== 0) { $('.multiselect').multiselect( { enableFiltering: true, filterBehavior : 'text', enableCaseInsensitiveFiltering: true } ); } var leave_type = $('#leave_type'); // if( 'CSR' == leave_type ) // { // $csr_container.removeClass("hide").addClass("show"); // $("#date-control").addClass("date-single").removeClass("date-multiple").removeClass("date-long"); // } // else if( "LEAVE" == leave_type || "FH" == leave_type || "SH" == leave_type) // { // $csr_container.removeClass("show").addClass("hide"); // $("#date-control").addClass("date-single").removeClass("date-multiple").removeClass("date-long"); // } // else if("LONG" == leave_type){ // $("#date-control").removeClass("date-single").removeClass("date-multiple").addClass("date-long"); // } // else{ // $("#date-control").addClass("date-single").removeClass("date-multiple").removeClass("date-long"); // } if( $(".date_control").length !==0 ) { $(".date_control").each(function(){ var $date_control = $(this); console.log($date_control.val()); var date_control_val = $date_control.val().split(","); var dts = []; $.each(date_control_val,function(k,v){ var dt = new Date(v.split('-')[0], parseInt(v.split('-')[1]) - 1, v.split('-')[2]); if(dt){ dts.push(dt); } }); if(dts[0] == "Invalid Date"){ dts = [new Date()]; } if($(".date_control").hasClass("date-long")){ if(date_control_val == ""){ $date_control.multiDatesPicker({ maxPicks: 2, showOn : "both", dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true, yearRange: "-100:+0", addDates: dts }); } else{ $date_control.multiDatesPicker({ maxPicks: 2, showOn : "both", dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true, yearRange: "-100:+0", addDates: dts }); } } else if($(".date_control").hasClass("date-multi")){ if(date_control_val == ""){ $date_control.multiDatesPicker({ showOn : "both", dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true, yearRange: "-100:+0", addDates: dts }); } else{ $date_control.multiDatesPicker({ showOn : "both", dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true, yearRange: "-100:+0", addDates: dts }); } } else{ var dt; if(date_control_val == ""){ $date_control.multiDatesPicker({ maxPicks: 1, showOn : "both", dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true, yearRange: "-100:+0", addDates: dts }); } else{ dt = new Date(date_control_val[0]); $date_control.multiDatesPicker({ maxPicks: 1, showOn : "both", dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true, yearRange: "-100:+0", addDates: [dt] }); } } }) } if($('.multiple-select-with-checkbox').length != 0){ $('.multiple-select-with-checkbox').each(function(){ var options = $(this).find("option"); var $selectbox = $(this); var checkboxHtml = "<div class='row'><div class='col-lg-4'></div>"; checkboxHtml += "<div class='col-lg-4'></div>"; checkboxHtml += "<div class='col-lg-4'></div></div>"; $selectbox.parent().append(checkboxHtml); var checkboxName = $selectbox.attr("name"); options.each(function(k,v){ currentRow = (k % 3) + 1; isChecked = $(this).is(":selected"); $selectbox.parent().find("div.row").find("div:nth-child(" + currentRow + ")").append(getMultipleCheckboxHTML(checkboxName, $(this).val(), $(this).html(), isChecked)); }); }); $('.multiple-select-with-checkbox').remove(); } $(".delete-myleave").on("click", function(){ var $this = $(this); var $parentRow = $(this).closest("tr"); jConfirm("Are you sure you want to delete this leave", "Confirmation", function(r){ if(r){ $.blockUI(); $.ajax({ url: $this.data("url"), type: "get", dataType: "json", success: function(retdata){ $parentRow.remove(); $.unblockUI(); } }); } }); }); }); $(document).on("submit", "#leaves_create_form, #leaves_edit_form",function(e){ e.preventDefault(); if($("#leave_option").val() === "CSR"){ var slotsCount = ($("#timeSlot .timepicker").length / 2); switch(slotsCount){ case 1: var startTime = $("#timeSlot .timepicker.start").first().val(); var endTime = $("#timeSlot .timepicker.end").first().val(); var diff = getHourDifference(startTime, endTime); if(diff < 0){ jAlert("Invalid Date Range selected for CSR time inputs"); return; } if(diff > 2){ jAlert("Please select CSR intervals so that the total CSR time will be less than 2 Hours"); return; } break; case 2: var startTime1 = $("#timeSlot .timepicker.start").first().val(); var endTime1 = $("#timeSlot .timepicker.end").first().val(); var startTime2 = $("#timeSlot .timepicker.start").last().val(); var endTime2 = $("#timeSlot .timepicker.end").last().val(); var diff = getHourDifference(startTime1, endTime1); if(diff < 0){ jAlert("Invalid Date Range selected for CSR(1) time inputs"); return; } if(diff > 2){ jAlert("Please select CSR intervals so that the total CSR time will be less than 2 Hours"); return; } var diff2 = getHourDifference(startTime2,endTime2); if(diff2 < 0){ jAlert("Invalid Date Range selected for CSR(2) time inputs"); return; } diff2 += diff; if(diff2 > 2){ jAlert("Please select CSR intervals so that the total CSR time will be less than 2 Hours"); return; } diff += diff2; break; } } if($(this).attr("id") == "leaves_create_form"){ $("#leaves_create_form")[0].submit(); } else{ $("#leaves_edit_form")[0].submit(); } }); function getHourDifference(startTime, endTime){ var sTime = new Date("10-12-1987 " + startTime); var eTime = new Date("10-12-1987 " + endTime); var diff = (eTime - sTime)/1000/60/60; return diff; } /* reqVal may be hour, min and returns 24 hour format hour if reqVal is hour */ function getTimeInfo(reqVal,inputTime){ switch(reqVal){ case "hour": var hour = parseInt(inputTime.split(":")[0]); var meridian = inputTime.split(":")[1].split(" ")[1]; if(meridian === "PM"){ hour += 12; } else{ hour = hour % 12; } return hour; case "min": return parseInt(inputTime.split(":")[1].split(" ")[0]); } } $(document).on('click','.approve-status-change', function (e) { var approvalStatus = $(this).data("approve_status"); var approvalId = $(this).data("approval_id"); var leaveId = $(this).data("leave_id"); var data; if(typeof approvalId == "undefined"){ data = { approvalStatus: approvalStatus, leaveId: leaveId } } else{ data = { approvalStatus: approvalStatus, approvalId: approvalId } } var approvalUrl = $(this).data("approval_url"); var $this = $(this); $.blockUI(); $.ajax({ type: 'post', url: approvalUrl, data: data, dataType: "json", success: function(data){ if(approvalStatus == "YES"){ $this.parent().html(getApprovedInfoHTML()); } else{ $this.parent().html(getRejectedInfoHTML()); } if(typeof data != "undefined" && typeof data.status != "undefined" && data.status == true){ if(data.fully_approved){ var leave_user_id = data.leave_user_id; console.log(leave_user_id); notification_data = { "noti_name" : "leave_approved", "notification_getter" : [leave_user_id] }; if(typeof socket != "undefined"){ socket.emit("leave_approved", notification_data) } } } $.unblockUI(); } }); }); $(document).on('click', '.view-approvals', function(e){ var url = $(this).data("url"); $.ajax({ url: url, type: "get", success: function(retdata){ $("#user-modal .modal-title").text("Approval Status"); $("#user-modal .modal-body").html(retdata); $("#user-modal").modal('show'); } }); }); $(document).on('dblclick', ".editable", function(){ $(this).prop("readonly",false); }); $(document).on('blur', ".editable", function(){ var url = $(this).data("url"); var model = $(this).data("model"); var column = $(this).data("column"); var value = $(this).val(); var id = $(this).data("id"); var origVal = $(this).data("orig"); var $this = $(this); $.blockUI(); $.ajax({ url: url, data: {model: model, column: column, value: value, id: id}, dataType: "json", success: function(retdata){ if(retdata.status == true){ window.location.reload(); } else{ $this.val(origVal); } $.unblockUI(); } }) $(this).prop("readonly",true); }); $(document).on('keyup', ".editable", function(e){ if(e.keyCode == 13){ var url = $(this).data("url"); var model = $(this).data("model"); var column = $(this).data("column"); var value = $(this).val(); var id = $(this).data("id"); var origVal = $(this).data("orig"); var $this = $(this); $.blockUI(); $.ajax({ url: url, data: {model: model, column: column, value: value, id: id}, dataType: "json", success: function(retdata){ if(retdata.status == true){ window.location.reload(); } else{ jAlert('Alert', 'Carry forward cannot be more than 5', function(){ $this.val(origVal); }); } $.unblockUI(); } }) $(this).prop("readonly",true); } }); function getMultipleCheckboxHTML(name,key,val, checked){ var checkboxinput_checked = ""; if(checked == true){ checkboxinput_checked = " checked"; } return "<input type='checkbox' name='"+name+"' value='" + key +"' " + checkboxinput_checked + "/> <span class='checkbox-text'>" + val + "</span>&nbsp;&nbsp;"; } function getApprovedInfoHTML(){ return '<a href="javascript: void(0);" class="btn btn-xs btn-primary approve-status-change btn-success">'+ '<span class="glyphicon glyphicon-ok" title="Leave Approved"></span>'+ '</a>' } function getRejectedInfoHTML(){ return '<a href="javascript: void(0);" class="btn btn-xs btn-primary approve-status-change btn-danger">'+ '<span class="glyphicon glyphicon-remove btn-danger" title="Leave Rejected"></span>'+ '</a>'; } // new add leave/csr js function timingsContainersDisplay(hideOrShow){ inOutTimeContainerDisplay(hideOrShow); availabilitySlotContainerDisplay(hideOrShow); } function inOutTimeContainerDisplay(hideOrShow){ if(hideOrShow == "hide"){ $(".in-out-time-container").hide(); } else{ $(".in-out-time-container").show(); } } function availabilitySlotContainerDisplay(hideOrShow){ if(hideOrShow == "hide"){ $(".availablity-time-slot-container").hide(); } else{ $(".availablity-time-slot-container").show(); } } var nowTemp = new Date(); var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0); var checkin = $('.from_dt').datepicker({ format: "dd-mm-yyyy", onSelect: function(date) { return date.valueOf() < now.valueOf() ? 'disabled' : ''; } }).on('changeDate', function(ev) { if (ev.date.valueOf() > checkout.date.valueOf()) { var newDate = new Date(ev.date) newDate.setDate(newDate.getDate()); checkout.setValue(newDate); timingsContainersDisplay("hide"); } else{ var coVal; if($.trim($('.to_dt').val()) == ""){ coVal = $('.from_dt').val(); timingsContainersDisplay("show"); } else{ coVal = $('.to_dt').val(); if($.trim($('.to_dt').val()) == $.trim($('.from_dt').val())){ timingsContainersDisplay("show"); } else{ timingsContainersDisplay("hide"); } } checkout.setValue(coVal); } checkin.hide(); // $('.to_dt')[0].focus(); }).data('datepicker'); var checkout = $('.to_dt').datepicker({ format: "dd-mm-yyyy", onRender: function(date) { return date.valueOf() < checkin.date.valueOf() ? 'disabled' : ''; } }).on('changeDate', function(ev) { var coVal; if($.trim($('.to_dt').val()) == $.trim($('.from_dt').val())){ // if from date and to date are same timingsContainersDisplay("show"); } else{ // if from date and to date are different timingsContainersDisplay("hide"); } }).data('datepicker'); $(document).on("focus", ".from_dt", function(){ checkout.hide(); }); $(document).on("focus", ".to_dt", function(){ checkin.hide(); }); window.current_user = {}; window.current_user.lunch_break_start_time = moment($("#input-lunch-break-start-time").val(),"hh:mm A"); window.current_user.lunch_break_end_time = moment($("#input-lunch-break-end-time").val(),"hh:mm A"); window.current_user.lunch_break_hour_diff = window.current_user.lunch_break_end_time.diff(window.current_user.lunch_break_start_time,"minutes") / 60; window.current_user.break_1_start_time = moment($("#input-break-start-time-1").val(),"hh:mm A"); window.current_user.break_1_end_time = moment($("#input-break-end-time-1").val(),"hh:mm A"); window.current_user.break_2_start_time = moment($("#input-break-start-time-2").val(),"hh:mm A"); window.current_user.break_2_end_time = moment($("#input-break-end-time-2").val(),"hh:mm A"); window.current_user.break_1_hour_diff = window.current_user.break_1_end_time.diff(window.current_user.break_1_start_time, "minutes") / 60; window.current_user.break_2_hour_diff = window.current_user.break_2_end_time.diff(window.current_user.break_2_start_time, "minutes") / 60; window.current_user.break_1_slot = [window.current_user.break_1_start_time, window.current_user.break_1_end_time]; window.current_user.break_2_slot = [window.current_user.break_2_start_time, window.current_user.break_2_end_time]; function isSlotInsideTimes(timeStart, inBetweenSlot , timeEnd){ if((timeStart <= inBetweenSlot[0]) && (timeEnd >= inBetweenSlot[1])){ return true; } return false; } // exclusive check (timeBetween is not included in timeStart and timeEnd) function isTimeBetweenTimes(timeStart, timeBetween, timeEnd){ if((timeStart < timeBetween) && (timeEnd > timeBetween)){ return true; } return false; } function changeUserInOutTime(){ window.current_user.inTime = $("#in-time").val(); window.current_user.inTimeObj = moment(window.current_user.inTime, "hh:mm A"); window.current_user.outTime = $("#out-time").val(); window.current_user.outTimeObj = moment(window.current_user.outTime, "hh:mm A"); window.current_user.inTimeMinutes = window.current_user.inTimeObj.hours() * 60 + window.current_user.inTimeObj.minutes(); if(typeof window.current_user.hourDiff != "undefined"){ window.current_user.outTimeMinutes = window.current_user.inTimeMinutes + window.current_user.minuteDiff; var outHour = Math.floor((window.current_user.outTimeMinutes / 60) % 12); var outMin = window.current_user.outTimeMinutes % 60; if(outHour.toString().length == 1) outHour = "0" + outHour; if(outMin.toString().length == 1) outMin = "0" + outMin; $("#out-time").val(outHour + ":" + outMin + " PM"); window.current_user.outTime = $("#out-time").val(); } else{ window.current_user.outTimeMinutes = window.current_user.outTimeObj.hours() * 60 + window.current_user.outTimeObj.minutes(); } window.current_user.minuteDiff = window.current_user.outTimeMinutes - window.current_user.inTimeMinutes; window.current_user.hourDiff = window.current_user.minuteDiff / 60; window.current_user.inBetweenHours = []; for(i=window.current_user.inTimeMinutes+60;true;i+=60){ var ampm = ""; var tmpHour = Math.floor((i / 60)); if(tmpHour > 12){ tmpHour = tmpHour % 12; ampm = "PM"; } else{ ampm = "AM"; } var tmpMin = i % 60; if(tmpHour.toString().length == 1) tmpHour = "0" + tmpHour; if(tmpMin.toString().length == 1) tmpMin = "0" + tmpMin; window.current_user.inBetweenHours.push(tmpHour + ":" + tmpMin + " " + ampm); if(window.current_user.hourDiff == 9.5){ console.log(i); console.log(window.current_user.outTimeMinutes); if(i>=(window.current_user.outTimeMinutes - 30)){ break; } } else{ if(i >= (window.current_user.outTimeMinutes - 60)){ break; } } } if(window.current_user.hourDiff == 9.5){ $(".in-between-hours").removeClass("slot_9").addClass("slot_95"); } else{ $(".in-between-hours").addClass("slot_9").removeClass("slot_95"); } } $(document).on("ready", function(){ $("#in-time").on("change", function(){ changeUserInOutTime(); $("#from-time").html(window.current_user.inTime); $("#to-time").html(window.current_user.outTime); var inBetweenHoursHtml = ""; $(window.current_user.inBetweenHours).each(function(){ inBetweenHoursHtml += "<div><span class='slot-time-value'>" + this + "</span><span class='slotline'></span></div>"; }) $(".in-between-hours").html(inBetweenHoursHtml); if($.trim($(".slider").html()) != ""){ $(".slider").html(""); } $(".slider").slider({ range: true, min: window.current_user.inTimeMinutes, max: window.current_user.outTimeMinutes, step: 5, value: [window.current_user.inTimeMinutes,window.current_user.inTimeMinutes], handle: "round" }).on("slide", function(ui) { var rangeStart = ui.value[0]; var rangeEnd = ui.value[1]; var rangeStartHours = Math.floor(rangeStart / 60); var rangeStartMinutes = rangeStart - (rangeStartHours * 60); var rangeEndHours = Math.floor(rangeEnd / 60); var rangeEndMinutes = rangeEnd - (rangeEndHours * 60); var ampm = "AM"; if(rangeStartHours >= 12){ if(rangeStartHours != 12){ rangeStartHours = rangeStartHours % 12; } if(rangeStartHours.toString().length == 1) rangeStartHours = '0' + rangeStartHours; if(rangeStartMinutes.toString().length == 1) rangeStartMinutes = '0' + rangeStartMinutes; ampm = "PM"; } else{ if(rangeStartHours.toString().length == 1) rangeStartHours = '0' + rangeStartHours; if(rangeStartMinutes.toString().length == 1) rangeStartMinutes = '0' + rangeStartMinutes; ampm = "AM"; } rangeStart = rangeStartHours + ":" + rangeStartMinutes + " " + ampm; if(rangeEndHours >= 12){ if(rangeEndHours != 12){ rangeEndHours = rangeEndHours % 12; } if(rangeEndHours.toString().length == 1) rangeEndHours = '0' + rangeEndHours; if(rangeEndMinutes.toString().length == 1) rangeEndMinutes = '0' + rangeEndMinutes; ampm = "PM"; } else{ if(rangeEndHours.toString().length == 1) rangeEndHours = '0' + rangeEndHours; if(rangeEndMinutes.toString().length == 1) rangeEndMinutes = '0' + rangeEndMinutes; } rangeEnd = rangeEndHours + ":" + rangeEndMinutes + " " + ampm; $('.tooltip-inner').html(rangeStart + " - " + rangeEnd); $("#from-time").html(rangeStart); $("#to-time").html(rangeEnd); $("#input-from-time").val(rangeStart); $("#input-to-time").val(rangeEnd); }); $('.tooltip-inner').html(window.current_user.inTime + " - " + window.current_user.outTime); changeUserInOutTime(); }); $("#in-time").change(); $("#leave_apply").on("click", function(){ var fromDate = $(".from_dt").val(); var toDate = $(".to_dt").val(); var fromDateObj; var toDateObj; var leaveType = "LEAVE"; var leaveData = {}; leaveData["from_date"] = fromDate; leaveData["to_date"] = toDate; if($.trim(fromDate) == ""){ jAlert("Please select From Date"); } else{ fromDateObj = moment(fromDate, "DD-MM-YYYY"); } if(($.trim(toDate) != "")){ toDateObj = moment(toDate, "DD-MM-YYYY"); } var diffDays = toDateObj.diff(fromDateObj, "days"); var leaveDays = diffDays + 1; if(leaveDays > 1){ leaveType = "LONG"; } else{ var fromt = $("#input-from-time").val(); var tot = $("#input-to-time").val(); var fromtObj = moment(fromt, "hh:mm A"); var totObj = moment(tot, "hh:mm A"); if((isTimeBetweenTimes(window.current_user.break_1_start_time, totObj, window.current_user.break_1_end_time)) || (isTimeBetweenTimes(window.current_user.break_2_start_time, totObj, window.current_user.break_2_end_time))){ jAlert("You have selected your out time between break hours"); return; } if((isTimeBetweenTimes(window.current_user.break_1_start_time, fromtObj, window.current_user.break_1_end_time)) || (isTimeBetweenTimes(window.current_user.break_2_start_time, fromtObj, window.current_user.break_2_end_time))){ jAlert("You have selected your in time between break hours"); return; } if(isTimeBetweenTimes(window.current_user.lunch_break_start_time, fromtObj, window.current_user.lunch_break_end_time)){ jAlert("You have selected your in time between Lunch hours"); return; } if(isTimeBetweenTimes(window.current_user.lunch_break_start_time, totObj, window.current_user.lunch_break_end_time)){ jAlert("You have selected your out time between Lunch hours"); return; } if(totObj.diff(fromtObj) == 0){ leaveType = "LEAVE"; } else{ var inHours = totObj.diff(fromtObj,"minutes") / 60; var outHours = window.current_user.hourDiff - inHours; if(outHours <= 2){ jAlert("Your Out Time is approximately 2 Hours, Please fill the CSR form instead"); return; } // var inHours; // var outHours; if(isSlotInsideTimes(fromtObj, [window.current_user.break_1_start_time,window.current_user.break_1_end_time], totObj)){ inHours -= window.current_user.break_1_hour_diff; console.log("break 1 is included in Slot") } if(isSlotInsideTimes(fromtObj, [window.current_user.break_2_start_time,window.current_user.break_2_end_time], totObj)){ inHours -= window.current_user.break_2_hour_diff; console.log("break 2 is included in Slot") } if(isSlotInsideTimes(fromtObj, [window.current_user.lunch_break_start_time,window.current_user.lunch_break_end_time], totObj)){ inHours -= window.current_user.lunch_break_hour_diff; console.log("lunch break is included in Slot") } console.log(inHours); if(inHours < 4) { leaveType = "LEAVE"; } else{ if((inHours >= 4) && (inHours < (window.current_user.hourDiff - 2))){ if(fromtObj.diff(window.current_user.inTimeObj) < window.current_user.outTimeObj.diff(totObj)){ leaveType = "SH"; } else{ leaveType = "FH"; } } else{ if(inHours == 0){ leaveType = "LEAVE"; } else{ jAlert("Your Out Time is approximately 2 Hours, Please fill the CSR form instead"); return; } } } } } leaveData["leaveType"] = leaveType; leaveData["userOfficeInTime"] = window.current_user.inTime; leaveData["userOfficeOutTime"] = window.current_user.outTime; leaveData["userLeaveInTime"] = $("#input-from-time").val(); leaveData["userLeaveOutTime"] = $("#input-to-time").val(); var fullLeaveType = ""; switch(leaveType){ case "FH": fullLeaveType = "First Half"; break; case "SH": fullLeaveType = "Second Half"; break; case "LEAVE": fullLeaveType = "Full Day Leave"; break; case "LONG": fullLeaveType = "Long Leave"; break; } $(".modal-title").html("Leave Summary"); var leaveSummaryBody = ""; if(leaveDays > 1){ // if user selected more than one day of leave(Long Leave) leaveSummaryBody += "<div class='row'>"; leaveSummaryBody += "<label class='control-label col-sm-3'>"; leaveSummaryBody += "Leave Type"; leaveSummaryBody += "</label>"; leaveSummaryBody += "<div class='col-sm-9'>"; leaveSummaryBody += fullLeaveType; leaveSummaryBody += "</div>"; leaveSummaryBody += "</div>"; leaveSummaryBody += "<div class='row'>"; leaveSummaryBody += "<label class='control-label col-sm-3'>From Date</label>"; leaveSummaryBody += "<div class='col-sm-9'>" + fromDate + "</div>"; leaveSummaryBody += "</div>"; leaveSummaryBody += "<div class='row'>"; leaveSummaryBody += "<label class='control-label col-sm-3'>To Date</label>"; leaveSummaryBody += "<div class='col-sm-9'>" + toDate + "</div>"; leaveSummaryBody += "</div>"; leaveSummaryBody += "<div class='row'>"; leaveSummaryBody += "<label class='control-label col-sm-3'>Total Days</label>"; leaveSummaryBody += "<div class='col-sm-9'>" + (parseInt(toDateObj.diff(fromDateObj, "days")) + 1) + " Days</div>"; leaveSummaryBody += "</div>"; leaveData["leaveDays"] = (parseInt(toDateObj.diff(fromDateObj, "days") + 1)); } else{ // if user selected only one day leave if(fromtObj.diff(totObj) != 0){ leaveSummaryBody += "<div class='row'>"; leaveSummaryBody += "<label class='control-label col-sm-3'>"; leaveSummaryBody += "Leave Type"; leaveSummaryBody += "</label>"; leaveSummaryBody += "<div class='col-sm-9'>"; leaveSummaryBody += fullLeaveType; leaveSummaryBody += "</div>"; leaveSummaryBody += "</div>"; leaveSummaryBody += "<div class='row'>"; leaveSummaryBody += "<label class='control-label col-sm-3'>Leave Date</label>"; leaveSummaryBody += "<div class='col-sm-9'>" + fromDate + "</div>"; leaveSummaryBody += "</div>"; leaveSummaryBody += "<div class='row'>"; leaveSummaryBody += "<label class='control-label col-sm-3'>Out Time</label>"; leaveSummaryBody += "<div class='col-sm-9'>"; if(fromtObj.diff(window.current_user.inTimeObj) != 0){ leaveSummaryBody += window.current_user.inTime + " To " + fromt; if(window.current_user.outTimeObj.diff(totObj) != 0){ leaveSummaryBody += "<br>" + tot + " To " + window.current_user.outTime; } } else{ leaveSummaryBody += tot + " To " + window.current_user.outTime; } leaveSummaryBody += "</div>"; leaveSummaryBody += "</div>"; leaveSummaryBody += "<div class='row'>"; leaveSummaryBody += "<label class='control-label col-sm-3'>Total In Time</label>"; var inHoursShow = Math.floor(inHours); var inMinutesShow = Math.floor((inHours - inHoursShow) * 60); leaveSummaryBody += "<div class='col-sm-9'>" + inHoursShow + " Hours, " + inMinutesShow + " Minutes</div>"; leaveSummaryBody += "</div>"; } else{ leaveSummaryBody += "<div class='row'>"; leaveSummaryBody += "<label class='control-label col-sm-3'>"; leaveSummaryBody += "Leave Type"; leaveSummaryBody += "</label>"; leaveSummaryBody += "<div class='col-sm-9'>"; leaveSummaryBody += fullLeaveType; leaveSummaryBody += "</div>"; leaveSummaryBody += "</div>"; leaveSummaryBody += "<div class='row'>"; leaveSummaryBody += "<label class='control-label col-sm-3'>Leave Date</label>"; leaveSummaryBody += "<div class='col-sm-9'>" + fromDate + "</div>"; leaveSummaryBody += "</div>"; } } $(".modal-body").html(leaveSummaryBody); if($("#confirm-leave").length == 0){ $(".modal-footer").prepend('<button type="button" id="confirm-leave" class="btn btn-primary normal-button">Confirm</button>'); } $("#confirm-leave").data("leaveData", leaveData); $(".modal").modal("show"); }); }); $(document).on("click", "#confirm-leave", function(){ var $this = $(this); $form = $("#leaves_create_form"); url = $form.attr("action"); data = $this.data("leaveData"); data["approvals"] = $("#approval-select-box").val(); data["leave_reason"] = $("#leave-reason").val(); $.ajax({ url: url, data: data, type: "post", success: function(retdata){ if(retdata.status == true){ window.location.href = "/leaves/myleaves"; } } }); $(".modal").modal("hide"); }); <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('name', 80); $table->string('fName', 80)->nullable(); $table->string('email', 50); $table->string('password', 80); $table->time('inTime')->nullable(); $table->time('outTime')->nullable(); $table->datetime('dob')->nullable(); $table->datetime('doj')->nullable(); $table->string('bloodGroup', 5)->nullable(); $table->boolean('maritalStatus')->nullable(); $table->string('phone', 15)->nullable(); $table->string('altPhone', 15)->nullable(); $table->text('cAddress', 200)->nullable(); $table->text('pAddress', 200)->nullable(); $table->integer('totalLeaves',false,3)->nullable(); $table->enum('employeeType', array("EMPLOYEE","ADMIN")); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } } <file_sep>/** Page Name: admin_panel.js author : <NAME> Date: June, 03 2014 Purpose: This page contains javascript used in admin_panel Table referred: - Table updated: - Most Important Related Files: - */ // Initialize the datatables function removePaginationLinks(minLength){ if($("ul.pagination li").not(".previous").not(".next").length <= minLength){ $("ul.pagination").hide(); } } $(document).on("ready",function(){ if(0 != $('#usersTable').length) { $('#usersTable').DataTable( { "order": [[ 0, "asc" ]], aoColumnDefs: [ { bSortable: false, aTargets: [ -1 ] } ] } ); } if(0 != $('#leavesTable').length) { $('#leavesTable').DataTable( { aaSorting: [[0, "desc"]], aoColumnDefs: [ { bSortable: false, aTargets: [ -1 ] } ] }); } removePaginationLinks(1); // removes the pagination links if only one pagination link is present. }); $(document).on("submit",".user-form", function(e){ e.preventDefault(); var inTime = $("#inTime").val(); var outTime = $("#outTime").val(); if(($.trim(inTime) == "") || ($.trim(outTime) == "")){ jAlert("Please Fill In/Out Time"); } else{ inTime = new Date("12-10-2014 " + inTime); outTime = new Date("12-10-2014 " + outTime); diffInHours = (outTime - inTime)/(1000*60*60); // if(diffInHours > 9.5){ // jAlert("In/Out Time difference must be less than 9:30 Hours"); // } // else{ $(this)[0].submit(); // } } }); // Initialize timepickers if (0 != $('.timepicker').length) { $('.timepicker').timepicker({ minuteStep: 5, showInputs: true, disableFocus: true, defaultTime: false }); } // opens datepicker calendar on click of calendar icon appended to the date control input element $(document).on("click",".glyphicon-calendar", function(){ $(this).prev(".ui-datepicker-trigger").click(); }); // on keyup of input element with id user-search, makes an ajax call to search for input value $(document).on("keyup", "#user-search",function(e){ if(e.keyCode == 13){ e.preventDefault(); return; } if((e.keyCode != 40) && (e.keyCode != 38)){ var $this = $(this); var view = $(this).data("view"); if(typeof view == "undefined"){ view = null; } var value = $this.val(); var onBlank = $(this).data("onblank"); if(typeof onBlank == "undefined"){ onBlank = ""; } if(window.xhr){ window.xhr.abort(); } window.xhr = $.ajax({ url: $this.data("search_url"), data: {name: value, view: view, onblank: onBlank}, type: "post", success: function(retdata){ $("#user-listing-tbody").html(retdata); $("#user-listing-tbody").closest("table").removeClass("hide"); } }); } }); $(document).on("keydown", "#user-search",function(e){ var $this = $(this); if(e.keyCode == 13){ if(!$("#user-listing-tbody").closest("table").hasClass("hide")){ e.preventDefault(); $("#user-search").val($.trim($("#user-listing-tbody tr.active td").text())); $("#user-listing-tbody").closest("table").addClass("hide"); if(typeof $("#user-search").data("onselect") != "undefined"){ window[$("#user-search").data("onselect")]($("#user-search").data("onselectajaxurl"),$("#user-search").val(), window.currentYear); } } } if(e.keyCode == 40 || e.keyCode == 38){ e.preventDefault(); if(e.keyCode == 40){ var currIndex = $("#user-listing-tbody tr.active").index(); if(currIndex == -1){ $("#user-listing-tbody tr").first().addClass("active"); } else{ if(currIndex == ($("#user-listing-tbody tr").length - 1)){ $("#user-listing-tbody tr.active").removeClass("active"); $("#user-listing-tbody tr").first().addClass("active"); } else{ $("#user-listing-tbody tr.active").next().addClass("active"); $("#user-listing-tbody tr.active").first().removeClass("active"); } } } else{ var currIndex = $("#user-listing-tbody tr.active").index(); if(currIndex == 0){ $("#user-listing-tbody tr").removeClass("active"); $("#user-listing-tbody tr").last().addClass("active"); } else{ $("#user-listing-tbody tr.active").prev().addClass("active"); $("#user-listing-tbody tr.active").last().removeClass("active"); } } } }); $(document).on("submit","#report-form",function(e){ var hasErrors = false; if($("#leave-type").val() != "ALL"){ var $form = $(this); var inputs = $(this).find("input").not(".multiselect-search"); var selects = $(this).find("select"); for(i=0;i<inputs.length;i++){ if($.trim($(inputs[i]).val()) == ""){ hasErrors = true; break; } } if(!hasErrors){ for(i=0;i<selects.length;i++){ if($.trim($(selects[i]).val()) == ""){ hasErrors = true; break; } } } } if(hasErrors){ jAlert("Please enter/select all search inputs first!!"); return false; } else{ $("#report-form")[0].submit(); } }); $(document).on("change","#report-form #leave-type",function(){ var $form = $("#report-form"); var inputs = $form.find("input").not(".multiselect-search"); var selects = $form.find("select").not(".multiselect"); if($(this).val() == "ALL"){ inputs.hide(); selects.hide(); } else{ inputs.show(); selects.show(); } $("#report-form #leave-type").show(); $("input[name='generate_report']").show(); }); $(document).on("change", "#date-option", function(){ var this_val = $(this).val(); switch(this_val){ case "between-dates": $("#date_option_inputs").html(getBetweenDatesInputHTML()); break; case "by-month": $("#date_option_inputs").html(getMonthInputHTML()); break; case "by-year": $("#date_option_inputs").html(getYearInputHTML()); break; case "by-date": $("#date_option_inputs").html(getByDateInputHTML()); break; } $(".date_control").datepicker({ showOn : "both", dateFormat: "mm-dd-yy", changeMonth: true, changeYear: true }); }); $(document).on("click", ".delete-holiday", function(){ var $this = $(this); var $parentRow = $(this).closest("table").closest("tr"); jConfirm("Are you sure you want to delete this holiday", "Confirmation", function(r){ var url = $this.data("url"); if(r){ $.blockUI(); $.ajax({ url: url, type: "post", dataType: "json", success: function(retdata){ $parentRow.remove(); $.unblockUI(); } }); } }); }); $(document).on("click", ".delete-user", function(){ var $this = $(this); var $parentRow = $(this).closest("table").closest("tr"); jConfirm("Are you sure you want to delete this user", "Confirmation", function(r){ var url = $this.data("url"); if(r){ $.blockUI(); $.ajax({ url: url, type: "post", dataType: "json", success: function(retdata){ $parentRow.remove(); $.unblockUI(); } }); } }); }); $(document).on("click","#lm-autosearch table tr td", function(){ $(this).closest("table").addClass("hide"); var name = $(this).html(); var $input = $(this).closest("#lm-autosearch").prev(); $input.val($.trim(name)); if(typeof $input.data("onselect") != "undefined"){ window[$input.data("onselect")]($input.data("onselectajaxurl"),$input.val(), window.currentYear); } }); function getExtraLeaves(ajaxurl, username, year){ $.ajax({ url: ajaxurl, data: {name : username, year: year}, type: "post", success: function(retdata){ $("#extra_leave .row .col-sm-12").html(retdata); $(".date_control").datepicker({ showOn : "both", dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true }); } }); } $(document).on("change","input[name='extra_leaves[leave_type]']", function(){ if($(this).hasClass("extra-leave-leave_type")){ $(".extra-leave-description").removeClass("fade").removeClass('hide'); } else{ $(".extra-leave-description").addClass("hide"); } $("#extra-leave-fromdate").removeClass("fade").removeClass('hide'); }); function getMonthInputHTML(){ var htm = '<div class="col-sm-12"><select class="form-control" id="date-option" name="month">'; for(i=1;i<=12; i++){ htm += '<option value="' + i + '">' + i + '</option>'; } htm += '</select></div>'; return htm; } function getYearInputHTML(){ var htm = '<div class="col-sm-12"><select class="form-control" id="date-option" name="year">'; for(i=2014;i<=2015; i++){ htm += '<option value="' + i + '">' + i + '</option>'; } htm += '</select></div>'; return htm; } function getBetweenDatesInputHTML(){ var htm = '<div class="col-sm-6"><input type="text" name="from_date" class="form-control date_control" placeholder="From"/></div>'; htm += '<div class="col-sm-6"><input type="text" name="to_date" class="form-control date_control" placeholder="To"/></div>'; return htm; } function getByDateInputHTML(){ var htm = '<div class="col-sm-12"><input type="text" name="on_date" class="form-control date_control" placeholder="On Date"/></div>'; return htm; } $(document).on("click", ".settings-tab-links li a", function (e) { $('.message').hide(); e.preventDefault() $(this).tab('show'); }) $(document).on("ready",function(e){ var tabID = location.href.split("#")[1]; if(typeof tabID != "undefined"){ $("a[href='#"+tabID+"']").tab('show'); } if($("#report-form #leave-type").length == 1){ var $form = $("#report-form"); var inputs = $form.find("input"); var selects = $form.find("select"); if($("#report-form #leave-type").val() == "ALL"){ inputs.hide(); selects.hide(); } $("#report-form #leave-type").show(); $("input[name='generate_report']").show(); } }); // code for general report $(document).on("ready", function(){ if(typeof general_report != "undefined" && general_report){ var month = $(".general-report-container-inner table").data("month"); fetchNextMonthGeneralReportData(month); } $(".general-report-container").on("scroll", function(e){ if((($(".general-report-container-inner").height() - $(this).scrollTop() + 35) - $(".general-report-container").height()) < 200){ month = $(".general-report-container-inner table").data("month"); fetchNextMonthGeneralReportData(month); // console.log(($(".general-report-container-inner").height() - $(this).scrollTop() + 35) - $(".general-report-container-inner").height()); } }); }); function fetchNextMonthGeneralReportData(month){ if(month != 0){ if(typeof window.xhr == "undefined"){ window.xhr = $.ajax({ url: general_report_url, data: {month: month}, type: "post", success: function(retdata){ delete(window.xhr); $(".general-report-container-inner table tbody").append(retdata); $(".general-report-container-inner table").data("month",month - 1); } }); } } } // Reset dates to select again $('.date_control').on('click', function(){console.log('clicked'); $(this).multiDatesPicker('resetDates'); }); <file_sep><?php /* Class Name: UsersController author : <NAME> Date: May, 30 2014 Purpose: This class acts as a controller for user management Table referred: users Table updated: users Most Important Related Files: models/User.php */ class UsersController extends \BaseController { public function __construct() { $this->beforeFilter('auth', array( 'except' => array( 'test', 'getLogin', 'postLogin', 'create', 'store', 'getForgotPassword', 'postForgotPassword', 'getChangePassword', 'postChangePassword', 'loginWithGoogle', ) ) ); } public function test(){ return View::make("users.test"); } /* Function Name: getLogin Author Name: <NAME> Date: June, 02 2014 Parameters: username, password Purpose: This function acts as login action which displays user with login form. */ public function getLogin(){ if(Auth::check()){ if(Auth::user()->employeeType == "ADMIN"){ return Redirect::to(URL::route('usersHome')); } else{ return Redirect::to(URL::route('myLeaves')); } } return View::make('users.login'); } /* Function Name : loginWithGoogle Author Name : <NAME> <<EMAIL>> Date : July, 29 2014 Parameters : none Purpose : This function facilitates google sign in */ public function loginWithGoogle() { // get data from input $code = Input::get( 'code' ); // get google service $googleService = OAuth::consumer( 'Google' ); // check if code is valid // if code is provided get user data and sign in if ( !empty( $code ) ) { // This was a callback request from google, get the token $token = $googleService->requestAccessToken( $code ); // Send a request with it $result = json_decode( $googleService->request( 'https://www.googleapis.com/oauth2/v1/userinfo' ), true ); $user = User::whereEmail($result['email'])->get()->first(); // check if user exists in database if( isset($user) && ($user->count() > 0) ) { // check if user is not activated yet if ( $user->status == false ) { return Redirect::to('login')->with('message', 'Your account is not activated. Please contact administrator !'); } // log in the user Auth::loginUsingId($user->id); // take user to dashboard $employeeType = Auth::user()->employeeType; if($employeeType === "EMPLOYEE"){ return Redirect::intended(URL::route('usersHome')); } else{ return Redirect::intended(URL::route('usersListing')); } } // If not redirect back to login page with message $user_data = array( 'name' => $result['name'], 'email' => $result['email'], 'status' => false, 'employeeType' => 'EMPLOYEE'); // create a new user $temp_user = User::create($user_data); // get admin user $admin_user = User::where('employeeType', '=', 'ADMIN')->first(); $data = ['temp_user' => $temp_user, 'admin_user' => $admin_user]; // send an email to admin with user details Mail::send('emails.newuser', $data, function($message) use ($admin_user) { $message->to($admin_user->email, $admin_user->name)->from('<EMAIL>', 'Admin')->subject("Request for a new user for LMS"); }); return Redirect::to('login')->with('message', 'Your request has been sent. Please contact administrator !'); } // if not ask for permission first else { // get googleService authorization $url = $googleService->getAuthorizationUri(); // return to google login url return Redirect::to( (string)$url ); } } /* Function Name: postLogin Author Name: <NAME> Date: June, 02 2014 Parameters: username, password Purpose: This function acts as login action which displays user with login form. */ public function postLogin(){ $formData = Input::all(); $email = $formData["email"]; $password = $formData["password"]; $rememberMe = false; if(key_exists("rememberMe",$formData)){ $rememberMe = true; } if (Auth::attempt(array('email' => $email, 'password' => $password, 'status' => true), $rememberMe)) { $employeeType = Auth::user()->employeeType; if($employeeType === "EMPLOYEE"){ return Redirect::intended(URL::route('usersHome')); } else{ return Redirect::intended(URL::route('usersListing')); } } else{ return Redirect::to(URL::route('userLogin'))->with('error', 'There was a problem loggin you in, Please check your credentials and try again'); } } /* Function Name: logout Author Name: <NAME> Date: June, 02 2014 Parameters: username, password Purpose: This function acts as logout action which logouts the currently logged in user */ public function logout(){ Auth::logout(); return Redirect::to(URL::route('userLogin'))->with('message', 'Your are now logged out!'); } /* Function Name: getForgotPassword Author Name: <NAME> Date: June, 02 2014 Parameters: - Purpose: This function displays forgot password page */ public function getForgotPassword(){ return View::make('users.forgotpassword'); } /* Function Name: postForgotPassword Author Name: <NAME> Date: June, 02 2014 Parameters: - Purpose: This function emails a link to input email id with a change password link */ public function postForgotPassword(){ $email = Input::get("email"); $validator = Validator::make( array("email" => $email), array("email" => "required|email") ); if($validator->fails()){ return Redirect::to(URL::route("userForgotPassword"))->with('error', 'Email Address is not valid'); } else{ $user = User::where("email", $email)->get(); if($user->first()){ $user = $user->first(); $userName = $user->name; } else{ return Redirect::to(URL::route("userForgotPassword"))->with('error', 'Account not found for this Email'); } $token = substr(str_shuffle("<KEY>"), 0, 100); $emailSubject = "Leave Management: Change Your Password"; $data = array( 'token' => $token, 'userName' => $userName, 'email' => $email ); Mail::send('emails.changepassword', $data, function($message) use ($email,$userName, $emailSubject, $user, $token) { $message->to($email, $userName)->from('<EMAIL>', 'Admin')->subject($emailSubject); $user->changePasswordToken = $token; $user->save(); }); return Redirect::to(URL::route("userLogin"))->with("success","An Email has been sent to your email id for change password instructions!"); } } /* Function Name: getChangePassword Author Name: <NAME> Date: June, 02 2014 Parameters: $token - change password token generated at time of submitting forgot password page Purpose: This function provides a change password form to user */ public function getChangePassword($token){ $user = User::where("changePasswordToken",$token)->get(); if($user->first()){ $user = $user->first(); return View::make("users.changepassword")->with("token",$token); } else{ return Redirect::to(URL::route("userLogin"))->with("error","The link you requested is no longer valid!"); } } /* Function Name: postChangePassword Author Name: <NAME> Date: June, 02 2014 Parameters: $token - change password token generated at time of submitting forgot password page Purpose: This function updates user password */ public function postChangePassword($token){ $validator = Validator::make( Input::except("_token"), array( 'password' =>'<PASSWORD>|between:4,8|confirmed', 'password_confirmation'=>'required|between:4,8', ) ); if($validator->fails()){ return Redirect::to(URL::route("userChangePassword",array("token" => $token)))->withErrors($validator)->withInput()->with("error", "This form contains errors, please review and try again"); } else{ $user = User::where("changePasswordToken",$token); if(!$user->first()){ return Redirect::to(URL::route("userLogin"))->with("error","The link you requested is no longer valid!"); } $user = $user->first(); $user->password = <PASSWORD>(Input::get("password")); $user->changePasswordToken = ""; $user->save(); return Redirect::to(URL::route("userLogin"))->with("success","Your password has been updated successfully!"); } } /* Function Name: postSearch Author Name: <NAME> Date: June, 03 2014 Parameters: - Purpose: This function searches for the name of user in database and returns an array of matching users. */ public function postSearch(){ if((Input::get("onblank") && Input::get("onblank") == "nil") && (trim((Input::get('name'))) == "")) { $searchFor = "%1234%"; } else{ $searchFor = "%". Input::get("name") . "%"; } $users = User::where(DB::raw("lower(name)"),"LIKE", $searchFor)->get(); return View::make(Input::get('view') ? 'users.' . Input::get('view') : 'users.listing')->with("users", $users); } /* Function Name: index Author Name: <NAME> Date: June, 03 2014 Parameters: - Purpose: This function acts as an action for displaying all the users in a table */ public function index() { $users = User::orderBy("name")->get(); return View::make('users.index', compact('users')); } /* Function Name: create Author Name: <NAME> Date: June, 03 2014 Parameters: - Purpose: This function acts as an action for displaying user addition form */ public function create() { $user = new User(); $user->employeeType = "EMPLOYEE"; return View::make('users.create')->with("user",$user); } /* Function Name: store Author Name: <NAME> Date: June, 03 2014 Parameters: - Purpose: This function acts as an action for storing the filled information about user to the database table users */ public function store() { $formData = Input::except("_token"); $formData['inTime'] = date('H:i:s', strtotime($formData['inTime'])); $formData['outTime'] = date('H:i:s', strtotime($formData['outTime'])); $formData['lunch_start_time'] = date('H:i:s', strtotime($formData['lunch_start_time'])); $formData['lunch_end_time'] = date('H:i:s', strtotime($formData['lunch_end_time'])); $validator = User::validateRegistrationForm($formData); if($validator->fails()) { return Redirect::to(URL::route('userCreate'))->withErrors($validator)->withInput()->with("error", "This form contains errors, please review and try again"); } else{ $formData["doj"] = date("Y-m-d",strtotime($formData["doj"])); $formData["dob"] = date("Y-m-d",strtotime($formData["dob"])); $user = User::create($formData); $user->totalLeaves = $user->getTotalLeaves(); // new code $token = substr(str_shuffle("<KEY>"), 0, 100); $emailSubject = "Leave Management: Your Account Details"; $data = array( 'token' => $token, ); $data = array_merge($data,array('user'=> $user->toArray())); // Send an email to user Mail::queue('emails.registration', $data, function($message) use ($user, $token, $emailSubject) { $message->to($user->email, $user->name)->from('<EMAIL>', 'Admin')->subject($emailSubject); $user->changePasswordToken = $token; $user->save(); }); return Redirect::to('users')->with('success', 'Account created successfully'); } } /* Function Name: edit Author Name: <NAME> Date: June, 03 2014 Parameters: $id Purpose: This function acts as an action for displaying edit user form, where the retlated to the user can be edited */ public function edit($id) { $user = User::find($id); $user->inTime = preg_replace("/:00$/", "", $user->inTime); $user->outTime = preg_replace("/:00$/", "", $user->outTime); $user->lunch_start_time = preg_replace("/:00$/", "", $user->lunch_start_time); $user->lunch_end_time = preg_replace("/:00$/", "", $user->lunch_end_time); return View::make('users.edit')->with("user", $user); } /* Function Name: update Author Name: <NAME> Date: June, 03 2014 Parameters: $id Purpose: This function updates the given users information to database with the information updated in the edit form */ public function update($id) { $formData = Input::all(); $formData['inTime'] = date('H:i:s', strtotime($formData['inTime'])); $formData['outTime'] = date('H:i:s', strtotime($formData['outTime'])); $formData['lunch_start_time'] = date('H:i:s', strtotime($formData['lunch_start_time'])); $formData['lunch_end_time'] = date('H:i:s', strtotime($formData['lunch_end_time'])); $validator = User::validateRegistrationForm($formData, $id); if($validator->fails()) { return Redirect::to(URL::route('userEdit',array("id" => $id)))->withErrors($validator)->withInput()->with("error", "This form contains errors, please review and try again"); } else{ $formData = Input::except("password_confirmation","_token"); $formData['inTime'] = date('H:i:s', strtotime($formData['inTime'])); $formData['outTime'] = date('H:i:s', strtotime($formData['outTime'])); $formData['lunch_start_time'] = date('H:i:s', strtotime($formData['lunch_start_time'])); $formData['lunch_end_time'] = date('H:i:s', strtotime($formData['lunch_end_time'])); $formData["doj"] = date("Y-m-d",strtotime($formData["doj"])); $formData["dob"] = date("Y-m-d",strtotime($formData["dob"])); if(!empty($formData["password"])){ $formData["password"] = Hash::make($formData["password"]); } else{ unset($formData["password"]); } $user = User::find($id); $user->update($formData); $user->totalLeaves = $user->getTotalLeaves(); $user->save(); return Redirect::to(URL::route('usersListing'))->with('success', 'Account has been updated successfully'); } } /* Function Name: destroy Author Name: <NAME> Date: June, 03 2014 Parameters: $id Purpose: This function removes the specified user from database */ public function destroy($id) { $leave_ids = Leave::where('user_id', '=', $id)->lists('id'); // Delete all approvals he did (if any) Approval::where('approver_id', '=', $id)->delete(); if( count($leave_ids)>0 ) { // Delete all approvals Approval::whereIn('leave_id', $leave_ids)->delete(); // Delete all csrs Csr::whereIn('leave_id', $leave_ids)->delete(); // Delete all leaves Leave::where('user_id', '=', $id)->delete(); // Delete Extra Leaves Extraleave::where('user_id', '=', $id)->delete(); } // Delete the users User::destroy($id); return Response::json(array('status' => true)); } /* Function Name: getSettings Author Name: <NAME> Date: June, 10 2014 Parameters: - Purpose: Display tabbed settings page for admin */ public function getSettings(){ //$this->pre_print(array_combine(range(1,31), array_map(function($d){return sprintf("%02s",$d); }, range(1,31)))); $currYear = date("Y"); $yearStart = YearStart::where("year", $currYear)->first(); // $dayList = array_combine(array_merge(array("" => ""), range(1,31)), array_merge(array("" => "Select Day"),array_map(function($d){return sprintf("%02s",$d); }, range(1,31)))); $dayList = TemplateFunction::getIntegerRangeDropdown(1,31); //$this->pre_print($dayList); //$monList = array_combine(array_merge(array("" => ""), range(1,12)), array_merge(array("" => "Select Month"),array_map(function($d){return sprintf("%02s",$d); }, range(1,12)))); $monList = TemplateFunction::getIntegerRangeDropdown(1,12); if(!$yearStart){ $yearStart = new YearStart(); } $leaveConfig = array(); $leaveConfig["carry_forward_leaves"] = Leaveconfig::getConfig("carry_forward_leaves",$currYear); $leaveConfig["paternity_leaves"] = Leaveconfig::getConfig("paternity_leaves",$currYear); $leaveConfig["maternity_leaves"] = Leaveconfig::getConfig("maternity_leaves",$currYear); $leaveConfig["paid_leaves"] = Leaveconfig::getConfig("paid_leaves",$currYear); return View::make("users.settings")->with("yearStart", $yearStart)->with("dayList", $dayList)->with("monList", $monList)->with("leaveConfig", $leaveConfig); } /* Function Name: postSettings Author Name: <NAME> Date: June, 10 2014 Parameters: - Purpose: Saves/Updates various setting values */ public function postSettings(){ $allSettings = Input::all(); if(isset($allSettings['extra_leaves']['from_date'])){ $allSettings['extra_leaves']['from_date'] = date("Y-m-d",strtotime($allSettings['extra_leaves']['from_date'])); } if(key_exists("gapi",$allSettings)){ $showTab = "#gapi"; $validationRules = array( 'client_id' => array('required'), 'service_account_name' =>'required', 'key_file_location' => 'required', 'timezone' => 'required', 'calendar_id' => 'required' ); $validator = Validator::make( $allSettings["gapi"], $validationRules ); if($validator->fails()){ return Redirect::to(URL::route('users.settings') . $showTab)->withInput($allSettings)->withErrors($validator)->with("error", "This form contains errors, please review and try again"); } else{ $googleSettings = htmlspecialchars('<?php ' . 'return array( "client_id" => "' . $allSettings["gapi"]["client_id"] . '", "service_account_name" => "' . $allSettings["gapi"]["service_account_name"] . '", "key_file_location" => base_path() . "' . $allSettings["gapi"]["key_file_location"] . '", "timezone" => "' . $allSettings["gapi"]["timezone"] . '", "calendar_id" => "' . $allSettings["gapi"]["calendar_id"] . '", );' ); File::put(base_path() . '/app/config/google.php',htmlspecialchars_decode($googleSettings)); } } else{ if(key_exists("admin_account",$allSettings)){ $showTab = "#account"; $validationRules = array( 'email' => array('required','email'), 'password' =>'<PASSWORD>', 'password_confirmation'=>'<PASSWORD>', ); $validator = Validator::make( $allSettings["admin_account"], $validationRules ); // Add password validation only if user has edited it $validator->sometimes( 'password', 'required|confirmed', function($input){ return ( !empty($input->password) || !empty($input->password_confirmation) ); }); $validator->sometimes( 'password_confirmation', 'required', function($input){ return ( !empty($input->password) || !empty($input->password_confirmation) ); }); if($validator->fails()){ return Redirect::to(URL::route('users.settings') . $showTab)->withInput($allSettings)->withErrors($validator)->with("error", "This form contains errors, please review and try again"); } else{ $user = Auth::user(); $user->email = $allSettings["admin_account"]["email"]; // Check if user has entered the password then only update it otherwise update other values (not password) if ( !empty($allSettings["admin_account"]["password"]) && !empty($allSettings["admin_account"]["password_confirmation"]) ) { $user->password = <PASSWORD>::make($allSettings["admin_account"]["password"]); } else { $temp_user = User::find(Auth::user()->id); $user->password = $<PASSWORD>_<PASSWORD>-><PASSWORD>; } $user->save(); } } else{ if(key_exists("leave_setting", $allSettings)){ $showTab = "#leave"; $allSettings["leave_setting"]["new_official_year_date"] = sprintf("%02s", $allSettings["leave_setting"]["official_year_day"]) . "-" . sprintf("%02s", $allSettings["leave_setting"]["official_year_month"]); $validationRules = array( 'carry_forward_leaves' => 'required|numeric', 'paternity_leaves' =>'required|numeric', 'maternity_leaves'=>'required|numeric', 'paid_leaves'=>'required|numeric', 'new_official_year_date' => "required|regex:^[\d]{2}-[\d]{2}^" ); $validator = Validator::make( $allSettings["leave_setting"], $validationRules ); if($validator->fails()){ return Redirect::to(URL::route('users.settings') . $showTab)->withInput($allSettings)->withErrors($validator)->with("error", "This form contains errors, please review and try again"); } else{ $carry_forward_leaves = Leaveconfig::getConfig("carry_forward_leaves",date("Y")); $paternity_leaves = Leaveconfig::getConfig("paternity_leaves",date("Y")); $maternity_leaves = Leaveconfig::getConfig("maternity_leaves",date("Y")); $paid_leaves = Leaveconfig::getConfig("paid_leaves",date("Y")); if(!isset($carry_forward_leaves->id)){ $carry_forward_leaves = new leaveConfig(); $carry_forward_leaves->leave_type = "carry_forward_leaves"; $carry_forward_leaves->year = date("Y"); } $carry_forward_leaves->leave_days = $allSettings["leave_setting"]["carry_forward_leaves"]; if(!isset($paternity_leaves->id)){ $paternity_leaves = new Leaveconfig(); $paternity_leaves->leave_type = "paternity_leaves"; $paternity_leaves->year = date("Y"); } $paternity_leaves->leave_days = $allSettings["leave_setting"]["paternity_leaves"]; if(!isset($maternity_leaves->id)){ $maternity_leaves = new LeaveConfig(); $maternity_leaves->leave_type = "maternity_leaves"; $maternity_leaves->year = date("Y"); } $maternity_leaves->leave_days = $allSettings["leave_setting"]["maternity_leaves"]; if(!isset($paid_leaves->id)){ $paid_leaves = new LeaveConfig(); $paid_leaves->leave_type = "paid_leaves"; $paid_leaves->year = date("Y"); } $paid_leaves->leave_days = $allSettings["leave_setting"]["paid_leaves"]; $carry_forward_leaves->save(); $paternity_leaves->save(); $maternity_leaves->save(); $paid_leaves->save(); $official_year_month = $allSettings["leave_setting"]["official_year_month"]; $official_year_day = $allSettings["leave_setting"]["official_year_day"]; $currYear = date("Y"); $yearStart = YearStart::where("year", $currYear)->first(); if($yearStart){ $yearStart->startDay = $official_year_day; $yearStart->startMonth = $official_year_month; $yearStart->year = $currYear; $yearStart->save(); } else{ $yearStart = new YearStart(); $yearStart->startDay = $official_year_day; $yearStart->startMonth = $official_year_month; $yearStart->year = $currYear; $yearStart->save(); } } } else{ if(key_exists("extra_leaves",$allSettings)){ $showTab = "#extra_leave"; $validationRules = array( 'employee_name' => 'required', 'leave_type' =>'required', 'from_date' => 'required|date' ); $validator = Validator::make( $allSettings["extra_leaves"], $validationRules ); $validator->sometimes( 'leaves_count', 'required|numeric', function($input){ return (isset($input->leave_type) && ($input->leave_type == "extra")); }); $validator->sometimes( 'description', 'required', function($input){ return (isset($input->leave_type) && ($input->leave_type == "extra")); }); if($validator->fails()){ return Redirect::to(URL::route('users.settings') . $showTab)->withInput($allSettings)->withErrors($validator)->with("error", "This form contains errors, please review and try again"); } $empName = $allSettings["extra_leaves"]["employee_name"]; $extraLeaveType = $allSettings["extra_leaves"]["leave_type"]; $carry_forward_leaves = Leaveconfig::getConfig("carry_forward_leaves",date("Y")); $paternity_leaves = Leaveconfig::getConfig("paternity_leaves",date("Y")); $maternity_leaves = Leaveconfig::getConfig("maternity_leaves",date("Y")); $paid_leaves = Leaveconfig::getConfig("paid_leaves",date("Y")); switch($extraLeaveType){ case "paternity": $noOfLeaves = $paternity_leaves->leave_days; $description = "Paternity"; break; case "maternity": $noOfLeaves = $maternity_leaves->leave_days; $description = "Maternity"; break; case "extra": $noOfLeaves = $allSettings["extra_leaves"]["leaves_count"]; $description = $allSettings["extra_leaves"]["description"]; break; } $user = User::where("name",$empName)->first(); $userId = $user->id; $forYear = date("Y"); $fromDate = $allSettings["extra_leaves"]["from_date"]; $fromDate_timestamp = strtotime($fromDate); $toDate_timestamp = $fromDate_timestamp + (((int)$noOfLeaves - 1) * 24 * 60 * 60); $toDate = date("Y-m-d",$toDate_timestamp); $extraLeave = new Extraleave(); $extraLeave->user_id = $userId; $extraLeave->leaves_count = $noOfLeaves; $extraLeave->for_year = date("Y"); $extraLeave->from_date = date("Y-m-d", strtotime($fromDate)); $extraLeave->to_date = $toDate; $extraLeave->description = $description; $extraLeave->save(); } } } } return Redirect::to(URL::route('users.settings') . $showTab)->with('success', 'Settings updated successfully'); } /* Function Name: getExtraLeaves Author Name: <NAME> Date: June, 10 2014 Parameters: - Purpose: this function provides the view for getting extra leaves for a given user name for a given year. */ public function getExtraLeaves(){ $inputs = Input::all(); $username = $inputs["name"]; $year = $inputs["year"]; $user = User::where("name", "LIKE", "%" . $username . "%")->first(); $paternityLeave = Extraleave::getPaternityLeaveInfo($user->id, $year); $maternityLeave = Extraleave::getMaternityLeaveInfo($user->id, $year); if(!$paternityLeave){ $paternityLeave = null; } if(!$maternityLeave){ $maternityLeave = null; } $extraLeaves = Extraleave::getExtraLeavesInfo($user->id, $year); return View::make("users.extra_leaves")->with("data", array("paternityLeave" => $paternityLeave, "maternityLeave" => $maternityLeave, "extraLeaves" => $extraLeaves, "username" => $username)); } } <file_sep><?php class Extraleave extends Eloquent{ public function user(){ return $this->belongsTo("User"); } public static function getPaternityLeaveInfo($userId, $forYear){ return Extraleave::where("user_id", $userId)->where("for_year", $forYear)->where("description", "LIKE", "%Paternity%")->first(); } public static function getMaternityLeaveInfo($userId, $forYear){ return Extraleave::where("user_id", $userId)->where("for_year", $forYear)->where("description", "LIKE", "%Maternity%")->first(); } public static function getExtraLeavesInfo($userId, $forYear){ return Extraleave::where("user_id", $userId)->where("for_year", $forYear)->get(); } } ?><file_sep><?php /** * Class Name : UserController * author : <NAME> * Date : May, 30 2014 * Purpose : This class acts as a controller for user management * Table referred : users * Table updated : users * Most Important Related Files : models/User.php */ class UserController extends \BaseController { public function __construct() { $this->beforeFilter('auth', array( 'except' => array( 'getLogin', 'postLogin', 'getForgotPassword', 'postForgotPassword', 'getChangePassword', 'postChangePassword' ) ) ); } /** * Function Name : getLogin * Author Name : <NAME> * Date : June, 02 2014 * Parameters : username, password * Purpose : This function acts as login action which displays user with login form. */ public function getLogin(){ if(Auth::check()){ if(Auth::user()->employeeType == "ADMIN"){ return Redirect::to(URL::route('leaves.index')); } else{ return Redirect::to(URL::route('leaves.create')); } } return View::make('users.login'); } /** * Function Name : postLogin * Author Name : <NAME> * Date : June, 02 2014 * Parameters : username, password * Purpose : This function acts as login action which displays user with login form. */ public function postLogin(){ $formData = Input::all(); $email = $formData["email"]; $password = $formData["password"]; $rememberMe = false; if(key_exists("rememberMe",$formData)){ $rememberMe = true; } if (Auth::attempt(array('email' => $email, 'password' => $password), $rememberMe)) { $employeeType = Auth::user()->employeeType; if($employeeType === "EMPLOYEE"){ return Redirect::to(URL::route('leaves.create')); } else{ return Redirect::to(URL::route('usersListing')); } } else{ return Redirect::to(URL::route('userLogin'))->with('error', 'Email or Password does not match'); } } /** * Function Name : logout * Author Name : <NAME> * Date : June, 02 2014 * Parameters : username, password * Purpose : This function acts as logout action which logouts the currently logged in user */ public function logout(){ Auth::logout(); return Redirect::to(URL::route('userLogin'))->with('message', 'Your are now logged out!'); } /** * Function Name : getForgotPassword * Author Name : <NAME> * Date : June, 02 2014 * Parameters : none * Purpose : This function displays forgot password page */ public function getForgotPassword(){ return View::make('users.forgotpassword'); } /** * Function Name: postForgotPassword * Author Name: <NAME> * Date: June, 02 2014 * Parameters: - * Purpose: This function emails a link to input email id with a change password link */ public function postForgotPassword(){ $email = Input::get("email"); $validator = Validator::make( array("email" => $email), array("email" => "required|email") ); if($validator->fails()){ return Redirect::to(URL::route("userForgotPassword"))->with('error', 'Email Address is not valid'); } else{ $user = User::where("email", $email)->get(); if($user->first()){ $user = $user->first(); $userName = $user->name; } else{ return Redirect::to(URL::route("userForgotPassword"))->with('error', 'Account not found for this Email'); } $token = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 100); $emailSubject = "Leave Management: Change Your Password"; $data = array( 'token' => $token, 'userName' => $userName, 'email' => $email ); Mail::send('emails.changepassword', $data, function($message) use ($email,$userName, $emailSubject, $user, $token) { $message->to($email, $userName)->from('<EMAIL>', 'Admin')->subject($emailSubject); $user->changePasswordToken = $token; $user->save(); }); return Redirect::to(URL::route("userLogin"))->with("success","An Email has been sent to your email id for change password instructions!"); } } /** * Function Name : getChangePassword * Author Name : <NAME> * Date : June, 02 2014 * Parameters : $token - change password token generated at time of submitting forgot password page * Purpose : This function provides a change password form to user */ public function getChangePassword($token){ $user = User::where("changePasswordToken",$token)->get(); if($user->first()){ $user = $user->first(); return View::make("users.changepassword")->with("token",$token); } else{ return Redirect::to(URL::route("userLogin"))->with("error","The link you requested is no longer valid!"); } } /** * Function Name: postChangePassword * Author Name: <NAME> * Date: June, 02 2014 * Parameters: $token - change password token generated at time of submitting forgot password page * Purpose: This function updates user password */ public function postChangePassword($token){ $validator = Validator::make( Input::except("_token"), array( 'password' =>'required|between:4,8|confirmed', 'password_confirmation'=>'required|between:4,8', ) ); if($validator->fails()){ return Redirect::to(URL::route("userChangePassword",array("token" => $token)))->withErrors($validator)->withInput(); } else{ $user = User::where("changePasswordToken",$token); if(!$user->first()){ return Redirect::to(URL::route("userLogin"))->with("error","The link you requested is no longer valid!"); } $user = $user->first(); $user->password = <PASSWORD>::<PASSWORD>(Input::get("password")); $user->changePasswordToken = ""; $user->save(); return Redirect::to(URL::route("userLogin"))->with("success","Your password has been updated successfully!"); } } /** * Function Name: postSearch * Author Name: <NAME> * Date: June, 03 2014 * Parameters: - * Purpose: This function searches for the name of user in database and returns an array of * matching users. */ public function postSearch(){ $users = User::where("name","LIKE", "%". Input::get("name") . "%")->get(); return View::make('users.listing')->with("users", $users); } /** * Function Name: index * Author Name: <NAME> * Date: June, 03 2014 * Parameters: - * Purpose: This function acts as an action for displaying all the users in a table */ public function index() { $users = User::all(); return View::make('users.index', compact('users')); } /** * Function Name: create * Author Name: <NAME> * Date: June, 03 2014 * Parameters: - * Purpose: This function acts as an action for displaying user addition form */ public function create() { $user = new User(); return View::make('users.create')->with("user",$user); } /** * Function Name: store * Author Name: <NAME> * Date: June, 03 2014 * Parameters: - * Purpose: This function acts as an action for storing the filled information about * user to the database table users */ public function store() { $formData = Input::all(); $validator = User::validateRegistrationForm($formData); if($validator->fails()) { return Redirect::to(URL::route('userCreate'))->withErrors($validator)->withInput(); } else{ $formData = Input::except("password_confirmation","_token"); $formData["password"] = <PASSWORD>($formData["password"]); $user = User::create($formData); $user->totalLeaves = $user->getTotalLeaves(); $user->save(); return Redirect::to(URL::route('usersListing'))->with('success', 'Your account has been created successfully, Please login now!'); } } /** * Function Name: edit * Author Name: <NAME> * Date: June, 03 2014 * Parameters: $id * Purpose: This function acts as an action for displaying edit user form, where the * retlated to the user can be edited */ public function edit($id) { $user = User::find($id); return View::make('users.edit')->with("user", $user); } /** * Function Name: update * Author Name: <NAME> * Date: June, 03 2014 * Parameters: $id * Purpose: This function updates the given users information to database with * the information updated in the edit form */ public function update($id) { $formData = Input::all(); $validator = User::validateRegistrationForm($formData, false); if($validator->fails()) { return Redirect::to(URL::route('userEdit',array("id" => $id)))->withErrors($validator)->withInput(); } else{ $formData = Input::except("password_confirmation","_token"); if(!empty($formData["password"])){ $formData["password"] = <PASSWORD>($formData["password"]); } else{ unset($formData["password"]); } $user = User::find($id); $user->update($formData); $user->totalLeaves = $user->getTotalLeaves(); $user->save(); return Redirect::to(URL::route('usersListing'))->with('success', 'Your account has been created successfully, Please login now!'); } } /** * Function Name: destroy * Author Name: <NAME> * Date: June, 03 2014 * Parameters: $id * Purpose: This function removes the specified user from database */ public function destroy($id) { User::destroy($id); return Redirect::to(URL::route('usersListing')); } } <file_sep><?php /* Class Name: AdminController author : <NAME> Date: June, 02 2014 Purpose: This class acts as a controller for administrator tasks Table referred: users Table updated: users Most Important Related Files: models/User.php */ class AdminController extends \BaseController { /* Function Name: generateReport Author Name: <NAME> Date: June, 02 2014 Parameters: - Purpose: This function takes in various parameters as search inputs and generates a report on the basis of those inputs */ public function generateReport(){ } }<file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateLeavesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('leaves', function(Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); $table->date('leave_date'); $table->time('from_time')->nullable(); $table->time('to_time')->nullable(); $table->enum('leave_type', array('LEAVE', 'CSR', 'FH', 'SH', 'LONG')); $table->text('reason'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('leaves'); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ Route::get('/logingoogle',array("as" => "logingoogle", "uses" => 'UsersController@loginWithGoogle')); // SSL workaround for IRON MQ Route::get('/test', array('as' => 'test', 'uses' => 'UsersController@test')); Route::get('/logingoogle', 'UsersController@loginWithGoogle'); Route::get('/login', array('as' => 'userLogin', 'uses' => 'UsersController@getLogin')); Route::post('/login', array('as' => 'userLoginPost', 'uses' => 'UsersController@postLogin')); Route::get('/logout', array('as' => 'userLogout', 'uses' => 'UsersController@logout')); Route::get('/password/forgot', array('as' => 'userForgotPassword', 'uses' => 'UsersController@getForgotPassword')); Route::post('/password/forgot', array('as' => 'postUserForgotPassword', 'uses' => 'UsersController@postForgotPassword')); Route::get('/password/change/{token}', array('as' => 'userChangePassword', 'uses' => 'UsersController@getChangePassword')); Route::post('/password/change/{token}', array('as' => 'postUserChangePassword', 'uses' => 'UsersController@postChangePassword')); Route::group(array('before' => 'admin_added_or_admin_auth'),function(){ Route::get('/users/create', array('as' => 'userCreate', 'uses' => 'UsersController@create')); Route::post('/users/store', array('as' => 'userStore', 'uses' => 'UsersController@store')); }); Route::group(array('before' => 'auth.admin'), function(){ Route::get('/users/edit/{resource}', array('as' => 'userEdit', 'uses' => 'UsersController@edit')); Route::post('/users/update/{resource}', array('as' => 'userUpdate', 'uses' => 'UsersController@update')); Route::get('/users/remove/{resource}', array('as' => 'userRemove', 'uses' => 'UsersController@destroy')); Route::post('/users/destroy/{id}', array('as' => 'userDestroy', 'uses' => 'UsersController@destroy')); Route::get('/users', array('as' => 'usersListing', 'uses' => 'UsersController@index')); Route::post('/users/search', array('as' => 'usersSearch', 'uses' => 'UsersController@postSearch')); Route::get('/holidays/create', array('as' => 'holidayCreate', 'uses' => 'HolidaysController@create')); Route::post('/holidays/store', array('as' => 'holidayStore', 'uses' => 'HolidaysController@store')); Route::get('/holidays/edit/{resource}', array('as' => 'holidayEdit', 'uses' => 'HolidaysController@edit')); Route::post('/holidays/update/{resource}', array('as' => 'holidayUpdate', 'uses' => 'HolidaysController@update')); Route::post('/holidays/destroy/{id}', array('as' => 'holidayDestroy', 'uses' => 'HolidaysController@destroy')); Route::get('/holidays', array('as' => 'holidaysListing', 'uses' => 'HolidaysController@index')); Route::get('/leaves', array('as' => 'leaves.index', 'uses' => 'LeavesController@index')); Route::get('/leaves/report', array('as' => 'leaves.report', 'uses' => 'LeavesController@getReport')); Route::get('/leaves/report/general', array('as' => 'leaves.general_report', 'uses' => 'LeavesController@generalReport')); Route::post('/leaves/report/general', array('as' => 'leaves.post_general_report', 'uses' => 'LeavesController@fetchGeneralReport')); //Route::post('/leaves/report/generate', array('as' => 'leaves.generateReport', 'uses' => 'LeavesController@generateReport')); Route::get('/leaves/pending', array('as' => 'leaves.pendingLeaves', 'uses' => 'LeavesController@pendingLeaves')); Route::get('/settings', array('as' => 'users.settings', 'uses' => 'UsersController@getSettings')); Route::post('/settings', array('as' => 'users.postSettings', 'uses' => 'UsersController@postSettings')); Route::post('/users/getextraleaves', array('as' => 'users.getExtraLeaves', 'uses' => 'UsersController@getExtraLeaves')); }); Route::group(array('before' => 'auth'),function(){ Route::get('/leaves/create', array('as' => 'leaves.create', 'uses' => 'LeavesController@create')); Route::post('/leaves/store', array('as' => 'leaves.store', 'uses' => 'LeavesController@store')); Route::get('/leaves/{id}/remove', array('as' => 'leaves.destroy', 'uses' => 'LeavesController@destroy')); Route::post('leaves/approve',array('as' => 'approval.updateStatus', 'uses' => 'ApprovalController@updateStatus')); }); Route::get('/editable/save', array('as' => 'base.saveEditable', 'uses' => 'BaseController@saveEditable')); Route::group(array('before' => 'auth.user'),function(){ View::composer('layouts.user_layout', function($view) { $empId = Auth::user()->id; $pendingRequests = Approval::where("approver_id", $empId)->where("approved", "PENDING")->count(); $view->with('pendingRequests', $pendingRequests); }); Route::get('/', array('as' => 'usersHome', 'uses' => 'HomeController@userDashboard')); // Leave Routes Route::get('/leaves/search', 'LeavesController@search'); Route::get('/leaves/myleaves', array('as' => 'myLeaves', 'uses' => 'LeavesController@myLeaves')); Route::get('/leaves/requests', array('as' => 'leaveRequests', 'uses' => 'LeavesController@leaveRequests')); Route::group(array('before' => 'leaves.editable'), function(){ Route::get('/leaves/{id}/edit', array('as' => 'leaves.edit', 'uses' => 'LeavesController@edit')); Route::post('/leaves/{id}/update', array('as' => 'leaves.update', 'uses' => 'LeavesController@update')); Route::post('/leaves/{id}/remove', array('as' => 'leaves.destroy', 'uses' => 'LeavesController@destroy')); }); //Route::get('/leaves/{id}/edit', array('as' => 'leaves.edit', 'uses' => 'LeavesController@edit')); //Route::post('/leaves/{id}/update', array('as' => 'leaves.update', 'uses' => 'LeavesController@update')); //Route::post('/leaves/{id}/remove', array('as' => 'leaves.destroy', 'uses' => 'LeavesController@destroy')); // Route::get('/leaves/create', array('as' => 'leaves.create', 'uses' => 'LeavesController@create')); // Route::post('/leaves/store', array('as' => 'leaves.store', 'uses' => 'LeavesController@store')); }); Route::get('leaves/{resource}/approvals', array('as' => 'approval.leaveApprovals', 'uses' => 'ApprovalController@leaveApprovals')); Route::get('leaves/new/add', array('as' => 'leaves.getAddLeave', 'uses' => 'LeavesController@getAddLeave')); Route::get('leaves/new/{resource}/edit', array('as' => 'leaves.getEditLeave', 'uses' => 'LeavesController@getEditLeave')); Route::get('csr/new/add', array('as' => 'leaves.getAddCSR', 'uses' => 'LeavesController@getAddCSR')); Route::get('csr/new/{resource}/edit', array('as' => 'leaves.getEditCSR', 'uses' => 'LeavesController@getEditCSR')); Route::post('leaves/new/store', array('as' => 'leaves.postAddLeave', 'uses' => 'LeavesController@postAddLeave')); Route::post('leaves/new/{resource}/update', array('as' => 'leaves.postEditLeave', 'uses' => 'LeavesController@postEditLeave')); Route::post('csr/new/store', array('as' => 'leaves.postAddCSR', 'uses' => 'LeavesController@postAddCSR')); Route::post('csr/new/{resource}/update', array('as' => 'leaves.postEditCSR', 'uses' => 'LeavesController@postEditCSR')); <file_sep>var socket = io('http://lms-node.herokuapp.com'); // $(document).on("click", "#notify_others", function(){ // socket.emit("notify_others", {"sender" : "naresh", "text" : parseInt(Math.random() * 10)}) // }); // socket.on("notified", function(data){ // $("#my_notification").html(data.text) // }); $(document).on("ready", function(){ // var options = { // content: notificationHtml(), // placement: "bottom", // trigger: "focus" // } // function notificationHtml(){ // return "I am here"; // } // $('#notification-popover').popover(options); if(typeof notification_data != "undefined"){ var notification_name = notification_data["noti_name"]; var notification_getter = notification_data["noti_getter"]; socket.emit(notification_name, {"notification_getter" : notification_getter}); } }); socket.on("notify_approver", function(data){ if($.inArray(current_user_id, data.notification_getter) != -1){ var pending_request_count = parseInt($("#pending-request-count").html()); pending_request_count += 1; $("#pending-request-count").html(pending_request_count); var notification_method; if(typeof data.message != undefined){ notification_method = data.message; } else{ notification_method = "One new leave request Arrived"; } notification_html = '<div class="row">' + '<div class="col-sm-12">'+notification_method+'</div>' + '</div>'; if($(".notification").length == 0){ notification_html_outer = getNotificationHtmlOuter(); $("#content-panel").prepend(notification_html_outer); } $(".notification").append(notification_html); if($(".notification").hasClass("hide")){ $(".notification").removeClass("hide"); } } }); socket.on("notify_applier", function(data){ if($.inArray(current_user_id, data.notification_getter) != -1){ var notification_method; if(typeof data.message != undefined){ notification_method = data.message; } else{ notification_method = "One of your leaves has been approved"; } notification_html = '<div class="row">' + '<div class="col-sm-12">'+notification_method+'</div>' + '</div>'; if($(".notification").length == 0){ notification_html_outer = getNotificationHtmlOuter(); $("#content-panel").prepend(notification_html_outer); } $(".notification").append(notification_html); if($(".notification").hasClass("hide")){ $(".notification").removeClass("hide"); } } }); function getNotificationHtmlOuter(){ return '<div class="alert alert-info alert-dismissible notification hide">' + '<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>' + '</div>'; }<file_sep><?php /** Class Name: Holiday author : <NAME> Date: June, 03 2014 Purpose: This class acts as a model for holidays table Table referred: holidays Table updated: holidays Most Important Related Files: - */ class Holiday extends Eloquent{ public $fillable = array( 'holidayDate', 'holidayType', 'holidayDescription' ); public static function validateHolidayForm($formData, $id=null){ if($id != null){ $rules = array( 'holidayDate' => array('required','date', 'unique:holidays,holidayDate,' . $id), 'holidayDescription' => array('required', 'max:255') ); } else{ $rules = array( 'holidayDate' => array('required','date','unique:holidays'), 'holidayDescription' => array('required', 'max:255') ); } $validator = Validator::make( $formData, $rules ); return $validator; } } ?><file_sep><?php class YearStart extends Eloquent { /** * The database table used by the model. * * @var string */ protected $table = 'year_start'; }<file_sep><?php /** * * Class Name : LeavesController * author : <NAME> * Date : June 02, 2014 * Purpose : Resourceful controller for leaves * Table referred : leaves, users, approvals * Table updated : leaves, approvals * Most Important Related Files : /app/models/Leave.php */ class LeavesController extends \BaseController { public function __construct() { $this->beforeFilter('auth'); } /** * Function Name : index * Author Name : <NAME> * Date : June 02, 2014 * Parameters : none * Purpose : This function used to list all leaves */ public function index() { $leaves = Leave::all(); $extraLeaves = Extraleave::all(); return View::make('leaves.index')->with("leaves", $leaves)->with('extraLeaves', $extraLeaves); } /** * Function Name : create * Author Name : <NAME> * Date : June 02, 2014 * Parameters : none * Purpose : This function renders leave form with user data */ public function create() { $users = User::where('id', '<>', Auth::user()->id)->employee()->lists('name', 'id'); ksort($users); $leave = new Leave(); $leave->leave_type = ""; $layout = Auth::user()->employeeType == "ADMIN" ? "admin_layout" : "user_layout"; return View::make('leaves.create')->with('users', $users)->with('leave' , $leave)->with("layout", $layout); } /** * Function Name : store * Author Name : <NAME> * Date : June 02, 2014 * Parameters : none * Purpose : This function used to create leave */ public function store() { $validator = []; $validator_leave = []; $validator_csr = []; $inputs = Input::all(); if(isset($inputs['leave']['leave_date'])){ $ldts = explode(",", $inputs['leave']['leave_date']); $temp_ldts = array(); foreach($ldts as $ldt){ $ldt = date("Y-m-d",strtotime($ldt)); $temp_ldts[] = $ldt; } $inputs['leave']['leave_date'] = implode(",",$temp_ldts); } $leave = $inputs['leave']; $leave['leave_option'] = $inputs['leave_option'] ; if($inputs['leave_option'] == 'CSR'){ $leave['leave_type'] = 'CSR'; $inputs['leave']['leave_option'] = 'CSR'; } else{ $inputs['leave']['leave_option'] = ''; } $hasLeaveError = false; $hasApprovalError = false; $hasCsrError = false; $validator_leave = Validator::make($leave, Leave::$rules); $validator_leave->sometimes('leave_date', 'regex:/[\d]{4}-[\d]{2}-[\d]{2}([,][\d]{4}-[\d]{2}-[\d]{2})+/', function($input){ return $input->leave_type === "MULTI"; }); $validator_leave->sometimes('leave_date', 'regex:/[\d]{4}-[\d]{2}-[\d]{2}([,][\d]{4}-[\d]{2}-[\d]{2})/', function($input){ return $input->leave_type === "LONG"; }); $validator_leave->sometimes('leave_date', 'regex:/[\d]{4}-[\d]{2}-[\d]{2}/', function($input){ $ltypes = array('FH','SH','LEAVE','CSR'); return in_array($input->leave_type, $ltypes); }); if($validator_leave->fails()) $hasLeaveError = true; if( 'CSR' == $inputs['leave']['leave_option'] ) { $csrs = $inputs['csr']; foreach($csrs as $key => $csr) { // $csr_slots[$key]['from_time'] = sprintf("%02s", $csr['from']['hour']).':' . sprintf("%02s", $csr['from']['min']); // $csr_slots[$key]['to_time'] = sprintf("%02s", $csr['to']['hour']) . ':' . sprintf("%02s", $csr['to']['min']); $validator_csr[$key] = Validator::make($csr, Csr::$rules); if($validator_csr[$key]->fails()) $hasCsrError = true; } } // check if user has selected any approver or not if(!array_key_exists('approval', $inputs)) $hasApprovalError = true; $hasEmployeeError = false; if(Input::get("employee_id") == -1){ $hasEmployeeError = true; } if($hasLeaveError || $hasApprovalError || $hasCsrError || $hasEmployeeError) { $validator = ($hasLeaveError)? $validator_leave->messages()->toArray() : []; $validator = array_merge($validator, ($hasApprovalError)? ['approval' => ['Please select at least one approval']] : [] ); $validator = array_merge($validator, ($hasEmployeeError) ? ['employee_id' => ['Please select an Employee']] : []); foreach($validator_csr as $vc) { $validator = array_merge($validator, ($hasCsrError)? $vc->messages()->toArray() : [] ); } return Redirect::back()->withErrors($validator)->withInput($inputs)->with("error", "This form contains errors, please review and try again"); } $tempLeave = $leave; $addedLeaves = []; // grab all leave dates in an array $leave_dates = explode(",", $leave['leave_date']); foreach($leave_dates as $key => $ldate){ $leave_dates[$key] = date("Y-m-d",strtotime($ldate)); } //checking if user or admin is adding new leave $user_id = ""; if(Auth::user()->employeeType == "ADMIN"){ $user = User::find(Input::get("employee_id")); $user_id = $user->id; } else{ $user_id = Auth::user()->id; } if($tempLeave["leave_type"] == "MULTI"){ foreach($leave_dates as $leave_date){ $leave = $tempLeave; $leave["leave_date"] = $leave_date; $leave["leave_type"] = "LEAVE"; $leave = array_merge($leave, ['user_id' => $user_id]); $leave = Leave::create($leave); $addedLeaves[] = $leave; } } else{ if($tempLeave["leave_type"] == "LONG"){ $leave = $tempLeave; $leave["leave_date"] = $leave_dates[0]; $leave["leave_to"] = $leave_dates[1]; $leave = array_merge($leave, ['user_id' => $user_id]); $leave = Leave::create($leave); $addedLeaves[] = $leave; } else{ $leave = $tempLeave; $leave["leave_date"] = $leave_dates[0]; $leave = array_merge($leave, ['user_id' => $user_id]); $leave = Leave::create($leave); $addedLeaves[] = $leave; } } if( 'CSR' == $inputs['leave']['leave_option'] ) { foreach($csrs as $key => $slot) { $slot['leave_id'] = $addedLeaves[0]->id; $slot['from_time'] = date('H:i', strtotime($slot['from_time'])); $slot['to_time'] = date('H:i', strtotime($slot['to_time'])); Csr::create($slot); } } $approvals = $inputs['approval']; foreach($addedLeaves as $addedLeave){ foreach($approvals as $approval) { $approval['leave_id'] = $addedLeave->id; $approval['approved'] = 'PENDING'; $approval = Approval::create($approval); if(Auth::user()->employeeType == "ADMIN"){ $approval->approved = 'YES'; $approval->save(); $approval->sendApprovalNotification(); $approval->markCalendarEvent(); } } } if(Auth::user()->employeeType == "ADMIN"){ return Redirect::to(URL::route('leaves.create')) ->with('success', 'Leave successfully Added'); } else{ $approvals = Input::get("approval"); $approval_ids = array(); foreach($approvals as $appr){ $approval_ids[] = (int)$appr["approver_id"]; } return Redirect::to(URL::route('myLeaves'))->with('success', 'Leave successfully applied')->with("notification", array("noti_name" => "leave_added", "noti_getter" => $approval_ids)); } } /** * Function Name : show * Author Name : <NAME> * Date : June 02, 2014 * Parameters : id * Purpose : This function used to show individual leave */ public function show($id) { $leave = Leave::findOrFail($id); return View::make('leaves.show', compact('leave')); } /** * Function Name : edit * Author Name : <NAME> * Date : June 02, 2014 * Parameters : id * Purpose : This function used to render edit form with user information filled in */ public function edit($id) { $layout = "user_layout"; $leave = Leave::find($id); if( 'LONG' == $leave->leave_type ) { $leave->leave_date = date("Y-m-d",strtotime($leave->leave_date)); $leave->leave_to = date("Y-m-d",strtotime($leave->leave_to)); $leave->leave_date .= ','. $leave->leave_to; } else{ $leave->leave_date = date("Y-m-d",strtotime($leave->leave_date)); } $users = User::where('id', '<>', Auth::user()->id)->employee()->lists('name', 'id'); $inputCSRs = array(); if($leave->leave_type == "CSR"){ $csrs = $leave->csrs; foreach($csrs as $csr){ $from_time = preg_replace("/:00$/",'',$csr->from_time); $to_time = preg_replace("/:00$/",'',$csr->to_time); $inputCSRs[] = array("from_time" => $from_time, "to_time" => $to_time); } } return View::make('leaves.edit', array('leave' => $leave, 'users' => $users, 'inputCSRs' => $inputCSRs, 'layout' => $layout)); } /** * Function Name : update * Author Name : <NAME> * Date : June 02, 2014 * Parameters : id * Purpose : This function used to update individual leave */ public function update($id) { $validator = []; $validator_leave = []; $validator_csr = []; $inputs = Input::all(); if(isset($inputs['leave']['leave_date'])){ $ldts = explode(",", $inputs['leave']['leave_date']); $temp_ldts = array(); foreach($ldts as $ldt){ $ldt = date("Y-m-d",strtotime($ldt)); $temp_ldts[] = $ldt; } $inputs['leave']['leave_date'] = implode(",",$temp_ldts); } $leave = $inputs['leave']; $hasLeaveError = false; $hasApprovalError = false; $hasCsrError = false; $leaveObj = Leave::findOrFail($id); $leave['leave_option'] = ($leaveObj->leave_type === 'CSR') ? 'CSR' : 'LEAVE'; $validator_leave = Validator::make($leave, Leave::$rules); $validator_leave->sometimes('leave_date', 'regex:/[\d]{4}-[\d]{2}-[\d]{2}([,][\d]{4}-[\d]{2}-[\d]{2})+/', function($input){ return $input->leave_type === "MULTI"; }); $validator_leave->sometimes('leave_date', 'regex:/[\d]{4}-[\d]{2}-[\d]{2}([,][\d]{4}-[\d]{2}-[\d]{2})/', function($input){ return $input->leave_type === "LONG"; }); $validator_leave->sometimes('leave_date', 'regex:/[\d]{4}-[\d]{2}-[\d]{2}/', function($input){ $ltypes = array('FH','SH','LEAVE','CSR'); return in_array($input->leave_type, $ltypes); }); if($validator_leave->fails()) $hasLeaveError = true; if( 'CSR' == $leave['leave_option'] ) { $csrs = $inputs['csr']; foreach($csrs as $key => $csr) { $validator_csr[$key] = Validator::make($csr, Csr::$rules); if($validator_csr[$key]->fails()) $hasCsrError = true; } } // check if user has selected any approver or not if(!array_key_exists('approval', $inputs)) $hasApprovalError = true; if($hasLeaveError || $hasApprovalError || $hasCsrError) { $validator = ($hasLeaveError)? $validator_leave->messages()->toArray() : []; $validator = array_merge($validator, ($hasApprovalError)? ['approval' => ['Please select at least one approval']] : [] ); foreach($validator_csr as $vc) { $validator = array_merge($validator, ($hasCsrError)? $vc->messages()->toArray() : [] ); } return Redirect::back()->withErrors($validator)->withInput($inputs)->with("error", "This form contains errors, please review and try again"); } $leave = array_merge($leave, ['user_id' => Auth::user()->id]); if($leaveObj->leave_type === "LONG" || $leave["leave_type"] === "LONG"){ $ldates = explode(",",$leave["leave_date"]); $leave_date = $ldates[0]; $leave_to = $ldates[1]; $leave["leave_date"] = date("Y-m-d",strtotime($leave_date)); $leave["leave_to"] = date("Y-m-d",strtotime($leave_to)); } else{ $leave["leave_date"] = $leave["leave_date"]; } $leaveObj->update($leave); if( 'CSR' == $inputs['leave_option'] ) { $leaveObj->csrs()->forceDelete(); foreach($csrs as $slot) { $slot['leave_id'] = $leaveObj->id; $slot['from_time'] = date("H:i",strtotime($slot['from_time'])); $slot['to_time'] = date("H:i",strtotime($slot['to_time'])); Csr::create($slot); } } $approvals = $inputs['approval']; $leaveObj->approvals()->forceDelete(); foreach($approvals as $approval) { $approval['leave_id'] = $leaveObj->id; $approval['approved'] = 'PENDING'; Approval::create($approval); } return Redirect::to(URL::route('myLeaves')) ->with('success', 'Leave successfully applied'); } /** * Function Name : destroy * Author Name : <NAME> * Date : June 02, 2014 * Parameters : id * Purpose : This function used to delete a single leave */ public function destroy($id) { $leave = Leave::find($id); $leave->approvals()->forceDelete(); if($leave->leave_type == "CSR"){ $leave->csrs()->forceDelete(); } Leave::destroy($id); return Response::json(array('status' => true)); } /** * Function Name : myLeaves * Author Name : <NAME> * Date : June 03, 2014 * Parameters : none * Purpose : This function is used for listing all leaves/csrs */ public function myLeaves(){ $leaves = Leave::where('user_id', '=', Auth::user()->id)->get(); return View::make('leaves.myleaves')->with('leaves', $leaves); } /** * Function Name : leaveRequests * Author Name : <NAME> * Date : June 03, 2014 * Parameters : none * Purpose : This function is used for listing all leaves/csrs */ public function leaveRequests(){ $leaveRequests = Approval::where("approver_id",Auth::user()->id)->get(); return View::make('leaves.leaverequests')->with("leaveRequests",$leaveRequests); } public function getReport(){ $searchData = Input::all(); $leaves = null; $users = User::employee()->lists('name', 'id'); $users[0] = "All Employees"; ksort($users); if(!empty($searchData)){ if($searchData["leave_type"] == "ALL"){ if(isset($searchData["employee_id"])){ if($searchData["employee_id"] == 0){ $leaves = Leave::all(); $extraLeaves = Extraleave::where("for_year",date("Y"))->get(); } else{ $leaves = Leave::where("user_id", $searchData["employee_id"])->get(); $extraLeaves = Extraleave::where("for_year",date("Y"))->where("user_id",$searchData["employee_id"])->get(); } } else{ $leaves = Leave::all(); $extraLeaves = Extraleave::where("for_year",date("Y"))->get(); } foreach($extraLeaves as $el){ $le = new Leave(); $le->leave_date = $el->from_date; $le->leave_to = $el->to_date; $le->reason = $el->description; $le->user_id = $el->user_id; $le->leave_type = $el->description; $leaves = $leaves->merge(array($le)); } } else{ $user = User::find($searchData["employee_id"]); $leaveType = $searchData["leave_type"]; if(isset($searchData["employee_id"]) ){ if($searchData["employee_id"] == 0){ $leaves = new Leave(); } else{ $leaves = Leave::where("user_id", $user->id); } } switch($searchData['date_option']){ case "between-dates": $leaves = $leaves->whereBetween("leave_date", array($searchData["from_date"], $searchData["to_date"])) ->where("leave_type", $leaveType) ->get(); break; case "by-date": $leaves = $leaves->where("leave_date", $searchData["on_date"]) ->where("leave_type", $leaveType) ->get(); break; case "by-year": if(Config::get("database.default") == "mysql"){ $leaves = $leaves->where(DB::raw('YEAR(leave_date)'), $searchData["year"]) ->where("leave_type", $leaveType) ->get(); } else{ $leaves = $leaves->where(DB::raw('EXTRACT(YEAR FROM "leave_date"::date)'), $searchData["year"]) ->where("leave_type", $leaveType) ->get(); } break; case "by-month": if(Config::get("database.default") == "mysql"){ $leaves = $leaves->where(DB::raw('YEAR(leave_date)'), date("Y")) ->where(DB::raw('MONTH(leave_date)'), date("m")) ->where("leave_type", $leaveType) ->get(); } else{ $leaves = $leaves->where(DB::raw('EXTRACT(YEAR FROM "leave_date"::date)'), date("Y")) ->where(DB::raw('EXTRACT(MONTH FROM "leave_date"::date)'), date("m")) ->where("leave_type", $leaveType) ->get(); } break; } } } return View::make('leaves.report')->withInput($searchData)->with("leaves",$leaves)->with("users", $users); } public function pendingLeaves(){ $leaves = Leave::pendingLeaves(); return View::make('leaves.index')->with("leaves", $leaves)->with("extraLeaves", array()); } public function generalReport(){ $all_users = User::where("employeeType","!=","ADMIN")->get(); $extra_leave_names = array( "Marriage", "Paternity", "Maternity", "Education", "Other" ); return View::Make("leaves.general_report", array( "all_users" => $all_users, "extra_leave_names" => $extra_leave_names ) ); } public function fetchGeneralReport(){ $month = Input::get("month"); $year = Input::get("year"); $firstDay = 1; $firstDate = new DateTime( date("Y") . "-" . sprintf("%02s",$month) . '-01' ); $lastDay = (int)$firstDate->format("t"); $allUsers = User::where("employeeType","!=","ADMIN")->get(); return View::make("leaves.fetch_next_general_report", array("lastDay" => $lastDay, "allUsers" => $allUsers, "month" => $month, "year" => $year)); } public function getAddLeave(){ $leave = new Leave(); $users = User::where('id', '<>', Auth::user()->id)->employee()->lists('name', 'id'); $layout = Auth::user()->employeeType == "ADMIN" ? "admin_layout" : "user_layout"; return View::make("leaves.newleaves.add_leave", array("leave" => $leave, "layout" => $layout, "users" => $users)); } public function postAddLeave(){ $allInputs = Input::all(); $fromDate = $allInputs["from_date"]; $toDate = $allInputs["to_date"]; $leaveType = $allInputs["leaveType"]; $userOfficeInTime = $allInputs["userOfficeInTime"]; $userOfficeOutTime = $allInputs["userOfficeOutTime"]; $userLeaveInTime = $allInputs["userLeaveInTime"]; $userLeaveOutTime = $allInputs["userLeaveOutTime"]; $leaveReason = $allInputs["leave_reason"]; $user = Auth::user("id"); $leave = new Leave(); $leave->leave_type = $leaveType; $leave->leave_date = date("Y-m-d",strtotime($fromDate)); $leave->reason = $leaveReason; $leave->user_id = $user->id; switch($leaveType){ case "LONG": $leave->leave_to = date("Y-m-d",strtotime($toDate)); break; case "FH": case "SH": $leave->in_time = date('H:i:s', strtotime($userOfficeInTime)); $leave->out_time = date('H:i:s', strtotime($userOfficeOutTime)); $leave->available_in_time = date('H:i:s', strtotime($available_in_time)); $leave->available_out_time = date('H:i:s', strtotime($available_out_time)); break; } $leave->save(); foreach($allInputs["approvals"] as $approver_id){ $approval = new Approval(); $approval->approver_id = $approver_id; $approval->leave_id = $leave->id; $approval->approval_note = ""; $approval->approved = "PENDING"; $approval->save(); unset($approval); } return array( "status" => true ); } public function getEditLeave(){ return View::make("leaves.newleaves.edit_leave"); } public function postEditLeave(){ } public function getAddCSR(){ return View::make("leaves.newleaves.add_csr"); } public function postAddCSR(){ } public function getEditCSR(){ return View::make("leaves.newleaves.edit_csr"); } public function postEditCSR(){ } } <file_sep><?php class Csr extends \Eloquent { protected $fillable = ['leave_id', 'from_time', 'to_time', 'completion_note']; protected $table = "csr"; public static $rules = [ 'from_time' => 'required|date_format:H:i A', 'to_time' => 'required|date_format:H:i A', ]; public function leave() { return $this->belongsTo('leave'); } }<file_sep><?php class Approval extends \Eloquent { protected $fillable = ['approver_id', 'leave_id', 'approved', 'approval_note']; /** * Function Name : boot * Author Name : <NAME> * Date : June 18, 2014 * Parameters : none * Purpose : To listen to Model events for sending email notifications */ public static function boot() { parent::boot(); static::created(function($approval){ // Get user who has requested a leave or CSR $requesting_user = User::find(Auth::user()->id); // Get approver details $approver_user = User::find($approval->approver_id); // Construct subject line for the email $request_type = TemplateFunction::getFullLeaveTypeName($approval->leave->leave_type); $subject = "$request_type request from $requesting_user->name"; // form a data array to be passed in view $data = []; $data['requesting_user'] = $requesting_user->toArray(); // Get leave details $leave = Leave::find($approval->leave_id); $data['leave'] = $leave->toArray(); // if leave type is a CSR then merge this as well in data if ( "CSR" == $approval->leave->leave_type ) { $data['csr'] = $approval->leave->csrs->toArray(); } //Send email notification to approver Mail::queue('emails.leave_request', $data, function($message) use($approver_user, $subject) { $message->from('<EMAIL>', 'Admin'); $message->to($approver_user->email, $approver_user->name); $message->subject($subject); }); }); //end of created } /* Function Name : pending Author Name : <NAME> Date : June 04, 2014 Parameters : none Purpose : This function used to return leave relationship */ public function leave() { return $this->belongsTo('Leave'); } /* Function Name : approver Author Name : <NAME> Date : June 04, 2014 Parameters : none Purpose : This function used to return user relationship */ public function approver() { return $this->belongsTo('User', 'approver_id'); } /* Function Name : pending Author Name : <NAME> Date : June 04, 2014 Parameters : none Purpose : This function used to return pending leave requests for approver */ public static function pending() { return Approval::where('approved', '=', 'PENDING') ->where('approver_id', '=', Auth::user()->id) ->get(); } /* Function Name : sendApprovalNotification Author Name : <NAME> Date : June 04, 2014 Parameters : none Purpose : This function will send notification to leave requesting user providing the information of Approved or Rejected Leave */ public function sendApprovalNotification(){ $approver = $this->approver; $leave = $this->leave; $user = $leave->user; $setSendMail = false; $approvalStatus = "APPROVED"; // checking if approver is admin if($approver->employeeType === "ADMIN"){ // set google calendar event if($leave->approvalStatus(Leave::APPROVED_BY_ADMIN)){ $setSendMail = true; } } else{ // check if all approvers of $leave have approved the leave if($leave->approvalStatus(Leave::APPROVED_BY_ALL)){ $setSendMail = true; } else{ // check if any of the approvers of $leave has rejected the leave if($leave->approvalStatus(Leave::REJECTED_BY_SOME)){ $setSendMail = true; $approvalStatus = "REJECTED"; } } } if($setSendMail){ $subject = "Request For " . TemplateFunction::getFullLeaveTypeName($leave->leave_type) . " Approved"; $requesting_user = $leave->user->toArray(); $approvals = Approval::where('leave_id', '=', $leave->id)->get(); $approver_users = array(); if( $approvals->count()>0) { foreach ($approvals as $approval) { $approver = $approval->approver->toArray(); $approver_users[$approver["id"]] = ['name' => $approver['name'], 'status' => $approval->approved]; } } $data['requesting_user'] = $requesting_user; $data['approver_users'] = $approver_users; if ( "CSR" == $approval->leave->leave_type ) { $csr = $approval->leave->csrs->toArray(); $data['csr'] = $csr; } $data['leave'] = $leave->toArray(); $data['approved_status'] = $approvalStatus; //Send email notification to approver Mail::queue('emails.leave_approval', $data, function($message) use($requesting_user, $subject) { $message->from(Config::get('mail.username', 'Admin'))->to($requesting_user['email'], $requesting_user['name'])->subject($subject); }); } } /* Function Name : markCalendarEvent Author Name : <NAME> Date : June 23, 2014 Parameters : none Purpose : This function marks leave event on google calendar if leave has been approved by ADMIN or all Approvers of the leave */ public function markCalendarEvent(){ $approver = $this->approver; $leave = $this->leave; $user = $leave->user; $setGoogleCalendarEvent = false; if($approver->employeeType === "ADMIN"){ // set google calendar event if($leave->approvalStatus(Leave::APPROVED_BY_ADMIN)){ $setGoogleCalendarEvent = true; } } else{ // check if all approvers of $leave have approved the leave // if yes than set google calendar event if($leave->approvalStatus(Leave::APPROVED_BY_ALL)){ $setGoogleCalendarEvent = true; } } if($setGoogleCalendarEvent){ TemplateFunction::requireGoogleCalendarApi(); $googleCreds = TemplateFunction::getGoogleCalendarCreds(); // Check if google configurations are set properly if ( $googleCreds['clientId'] == '' || !strlen( $googleCreds['serviceAccountName'] ) || !strlen( $googleCreds['keyFileLocation'] )) { echo 'Missing google configurations'; } $client = new Google_Client(); $client->setApplicationName("Leave Management System"); $service = new Google_Service_Calendar($client); if ( Session::has('service_token') ) { $client->setAccessToken( Session::get('service_token') ); } $key = file_get_contents( $googleCreds['keyFileLocation'] ); $cred = new Google_Auth_AssertionCredentials( $googleCreds['serviceAccountName'], array('https://www.googleapis.com/auth/calendar'), $key ); $client->setAssertionCredentials($cred); if($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshTokenWithAssertion($cred); } Session::put('service_token', $client->getAccessToken()); $cal = new Google_Service_Calendar($client); $start = new Google_Service_Calendar_EventDateTime(); $end = new Google_service_Calendar_EventDateTime(); $event = new Google_Service_Calendar_Event(); $summary = $user->name . " " . TemplateFunction::getLeaveTypeSummary($leave->leave_type); switch($leave->leave_type){ case "LEAVE": $startDate = $endDate = $this->leave->leave_date; $start->setDate($startDate); $end->setDate($endDate); break; case "FH": $startTime = $this->leave->leave_date. 'T'. $user->inTime. '.000'. Config::get('google.timezone'); $inTime = strtotime($user->inTime); $outTime = strtotime($user->outTime); $diffTime = ($outTime - $inTime) /2; $outTime = date('H:i:s', ($inTime + $diffTime)); $endTime = $this->leave->leave_date. 'T'. $outTime. '.000'. Config::get('google.timezone'); $start->setDateTime($startTime); $end->setDateTime($endTime); break; case "SH": $inTime = strtotime($user->inTime); $outTime = strtotime($user->outTime); $diffTime = ($outTime - $inTime) / 2; $inTime = date('H:i:s',($outTime - $diffTime)); $startTime = $this->leave->leave_date. 'T'. $inTime. '.000'. Config::get('google.timezone'); $endTime = $this->leave->leave_date. 'T'. $user->outTime. '.000'. Config::get('google.timezone'); $start->setDateTime($startTime); $end->setDateTime($endTime); break; case "LONG": $startDate = $this->leave->leave_date; $endDate = $this->leave->leave_to; $start->setDate($startDate); // Add one day to end date since google doesn't mark event for a day when any time is not provided after midnight $tempDate = new DateTime($endDate); $tempDate->add(new DateInterval('P1D')); // P1D means a period of 1 day $endDate = $tempDate->format('Y-m-d'); $end->setDate($endDate); break; } $arrEventTime = array(); if($leave->leave_type != "CSR"){ $arrEventTime[0]["start"] = $start; $arrEventTime[0]["end"] = $end; // $event->setStart($start); // $event->setEnd($end); } else{ $csrs = Csr::where('leave_id', '=', $leave->id)->get(); foreach($csrs as $key => $csr){ $startTime = $this->leave->leave_date. 'T'. $csr->from_time. '.000'. Config::get('google.timezone'); $endTime = $this->leave->leave_date. 'T'. $csr->to_time. '.000'. Config::get('google.timezone'); $start->setDateTime($startTime); $end->setDateTime($endTime); $arrEventTime[$key]["start"] = $start; $arrEventTime[$key]["end"] = $end; } } try{ foreach($arrEventTime as $etime){ $start = $etime["start"]; $end = $etime["end"]; $event->setStart($start); $event->setEnd($end); $event->setSummary($summary); $createdEvent = $cal->events->insert(Config::get('google.calendar_id'), $event); } } catch(Exception $ex){ die($ex->getMessage()); } } } }<file_sep><?php class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Eloquent::unguard(); $this->call('HolidayTableSeeder'); $this->call('UserTableSeeder'); } } class UserTableSeeder extends Seeder{ public function run(){ DB::table('users')->delete(); $user = new User(); $user->name = "<NAME>"; $user->email = "<EMAIL>"; $user->password = <PASSWORD>("<PASSWORD>"); $user->employeeType = "ADMIN"; $user->save(); } } class HolidayTableSeeder extends Seeder{ public function run(){ DB::table('holidays')->delete(); $monthCount = array(1 => 0,2 => 0,3 => 0,4 => 0,5 => 0,6 => 0,7 => 0,8 => 0,9 => 0,10 => 0,11 => 0,12 => 0); $monthNeeded = false; for($i=1;$i<=8;$i++){ $holiday = new Holiday(); $holiday->holidayDescription = "Test Holiday " . $i; $holiday->holidayType = "OPTIONAL"; $year = date("Y"); while(!$monthNeeded){ $month = rand(1,12); if($monthCount[$month] < 2){ $monthCount[$month] += 1; $monthNeeded = true; break; } } $monthNeeded = false; if($month != 2){ $day = rand(1,30); } else{ $day = rand(1,28); } $holiday->holidayDate = date("Y-m-d",mktime(0,0,0,$month, $day, $year)); $holiday->save(); } } } <file_sep><?php class BaseController extends Controller { public function __construct(){ } /** * Setup the layout used by the controller. * * @return void */ protected function setupLayout() { if ( ! is_null($this->layout)) { $this->layout = View::make($this->layout); } } protected function pre_print($data){ echo "<pre>"; print_r($data); echo "</pre>"; exit; } public function saveEditable(){ $inputs = Input::all(); // $this->pre_print($inputs); $modelName = trim(TemplateFunction::originalName($inputs["model"])); $modelId = trim(TemplateFunction::originalName($inputs["id"])); $columnName = trim(TemplateFunction::originalName($inputs["column"])); $value = trim($inputs["value"]); $saveData = true; if(class_exists($modelName)){ if($modelName == "User" && $columnName == "carry_forward_leaves"){ $year = date("Y"); $maxCarryForwardLeave = Leaveconfig::where("year", $year)->where("leave_type","carry_forward_leaves")->first(); if($maxCarryForwardLeave){ $maxCarryForwardLeave = (int)($maxCarryForwardLeave->leave_days); } else{ $maxCarryForwardLeave = 5; } $value = (int)$value; if($value > $maxCarryForwardLeave){ $saveData = false; } } if($saveData){ $modelObj = $modelName::find($modelId); $modelObj->$columnName = $value; $modelObj->save(); return Response::json(array("status" => true)); } else{ return Response::json(array("status" => false)); } } else{ return Response::json(array("status" => false)); } } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateYearStartTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('year_start', function(Blueprint $table) { $table->increments('id'); $table->integer('startDay'); $table->integer('startMonth'); $table->integer('year'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('year_start'); } } <file_sep><?php /* Class Name: HolidaysController author : <NAME> Date: June, 03 2014 Purpose: This class acts as a controller for holiday management Table referred: holidays Table updated: holidays Most Important Related Files: models/Holiday.php */ class HolidaysController extends \BaseController { public function __construct() { $this->beforeFilter('auth'); } /* Function Name: index Author Name: <NAME> Date: June, 03 2014 Parameters: - Purpose: This function acts as an action for displaying all the users in a table */ public function index(){ $currentYear = date("Y"); if(Config::get("database.default") == "mysql"){ $holidays = Holiday::where(DB::raw('YEAR(holidayDate)'), "=", $currentYear)->orderBy("holidayDate", "asc")->get(); } else{ $holidays = Holiday::where(DB::raw('EXTRACT(YEAR FROM "holidayDate"::date)'), "=", $currentYear)->orderBy("holidayDate", "asc")->get(); } return View::make("holidays.index")->with("holidays",$holidays); } /* Function Name: create Author Name: <NAME> Date: June, 03 2014 Parameters: - Purpose: This function acts as an action for displaying holiday addition form */ public function create(){ $holiday = new Holiday(); return View::make("holidays.create")->with("holiday", $holiday); } /* Function Name: store Author Name: <NAME> Date: June, 03 2014 Parameters: - Purpose: This function acts as an action for storing the filled information about holiday to the database table holidays */ public function store(){ $formData = Input::except("_token"); if(isset($formData['holidayDate'])){ $formData['holidayDate'] = date("Y-m-d",strtotime($formData['holidayDate'])); } $validator = Holiday::validateHolidayForm($formData); if($validator->fails()) { return Redirect::to(URL::route("holidayCreate"))->withErrors($validator)->withInput($formData)->with("error", "This form contains errors, please review and try again"); } else{ $formData["holidayType"] = "OPTIONAL"; Holiday::create($formData); return Redirect::to(URL::route("holidaysListing"))->with("success", "Holiday added successfully"); } } /* Function Name: edit Author Name: <NAME> Date: June, 03 2014 Parameters: $id Purpose: This function acts as an action for displaying edit holiday form, where the retlated to the given holiday can be edited */ public function edit($id){ $holiday = Holiday::find($id); return View::make("holidays.edit")->with("holiday", $holiday); } /* Function Name: edit Author Name: <NAME> Date: June, 03 2014 Parameters: $id Purpose: This function updates the given holidays information to database with the information updated in the edit form */ public function update($id){ $holiday = Holiday::find($id); $formData = Input::except("_token"); if(isset($formData['holidayDate'])){ $formData['holidayDate'] = date("Y-m-d",strtotime($formData['holidayDate'])); } $validator = Holiday::validateHolidayForm($formData, $id); if($validator->fails()) { return Redirect::to(URL::route("holidayEdit",array("id" => $id)))->withErrors($validator)->withInput()->with("error", "This form contains errors, please review and try again"); } else{ $holiday->update($formData); return Redirect::to(URL::route("holidaysListing"))->with("success", "Holiday updated successfully"); } $holiday->update(Input::except("_token")); return Redirect::to(URL::route("holidaysListing")); } /* Function Name: destroy Author Name: <NAME> Date: June, 03 2014 Parameters: $id Purpose: This function removes the specified holiday from database */ public function destroy($id) { Holiday::destroy($id); return Response::json(array('status' => true)); } }<file_sep><?php HTML::macro('nav_link', function($route_name, $link_name, $text) { $routes = array( "usersListing" => "users", "userCreate" => "users", "userEdit" => "users", "leaves.report" => "reports", "leaves.create" => "add_leave", "leaves.edit" => "add_leave", "holidayCreate" => "holidays", "holidayEdit" => "holidays", "holidaysListing" => "holidays", "users.settings" => "settings", "leaves.pendingLeaves" => "pendingLeaves", "myLeaves" =>"myleaves", "leaveRequests" => "leaverequests", "usersHome" => "usersHome", "leaves.getAddLeave" => "leaves.getAddLeave", "leaves.getEditLeave" => "leaves.getEditLeave", "leaves.getAddCSR" => "leaves.getAddCSR", "leaves.getEditCSR" => "leaves.getEditCSR", "leaves.general_report" => "leaves.general_report", ); $menuhrefs = array( "users" => "usersListing", "reports" => "leaves.report", "add_leave" => "leaves.create", "holidays" => "holidaysListing", "settings" => "users.settings", "pendingLeaves" => "leaves.pendingLeaves", "myleaves" => "myLeaves", "leaverequests" => "leaveRequests", "usersHome" => "usersHome", "leaves.getAddLeave" => "leaves.getAddLeave", "leaves.getEditLeave" => "leaves.getEditLeave", "leaves.getAddCSR" => "leaves.getAddCSR", "leaves.getEditCSR" => "leaves.getEditCSR", "leaves.general_report" => "leaves.general_report", ); $class = ""; if($routes[$route_name] == $link_name){ $class="lms-active"; } $href = URL::route($menuhrefs[$link_name]); return '<li class="' . $class . '"><a href="' . $href . '">' . $text . '</a></li>'; });<file_sep><?php use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableInterface; class User extends Eloquent implements UserInterface, RemindableInterface { /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = array('password'); public $fillable = array( 'name', 'email', 'password', 'employeeType', 'inTime', 'outTime', 'lunch_start_time', 'lunch_end_time', 'doj', 'dob', 'phone', 'altPhone', 'remark' ); /* Function Name: scopeEmployee Author Name: <NAME> Date: May, 30 2014 Parameters: Purpose: This function acts as a filter while getting all users which are not admins */ public function scopeEmployee($query){ return $query->where("employeeType", "<>", "ADMIN"); } /** * Get the unique identifier for the user. * * @return mixed */ public function getAuthIdentifier() { return $this->getKey(); } /** * Get the password for the user. * * @return string */ public function getAuthPassword() { return $this->password; } /** * Get the token value for the "remember me" session. * * @return string */ public function getRememberToken() { return $this->remember_token; } /** * Set the token value for the "remember me" session. * * @param string $value * @return void */ public function setRememberToken($value) { $this->remember_token = $value; } /** * Get the column name for the "remember me" token. * * @return string */ public function getRememberTokenName() { return 'remember_token'; } /** * Get the e-mail address where password reminders are sent. * * @return string */ public function getReminderEmail() { return $this->email; } /* Function Name: validateRegistrationForm Author Name: <NAME> Date: May, 30 2014 Parameters: registrationDataArr Purpose: This function will take an array of registration form values and validates them */ public static function validateRegistrationForm($registrationDataArr, $id = null){ if(key_exists("doj", $registrationDataArr) && !empty($registrationDataArr["doj"])){ $registrationDataArr["doj"] = date("Y-m-d",strtotime($registrationDataArr["doj"])); } if(key_exists("dob", $registrationDataArr) && !empty($registrationDataArr["dob"])){ $registrationDataArr["dob"] = date("Y-m-d",strtotime($registrationDataArr["dob"])); } if($id != null){ $validationRules = array( 'name' => array('required', 'min:5'), 'email' => array('required','email', 'unique:users,email,'.$id), 'doj' => array('required','date'), 'dob' => array('required','date'), 'inTime' => array('required', 'date_format:H:i:s'), 'outTime' => array('required', 'date_format:H:i:s'), 'phone' => array('required','regex:/[0-9]{10}/'), 'altPhone' => array('regex:/[0-9]{10}/') ); } else{ $validationRules = array( 'name' => array('required', 'min:5'), 'email' => array('required','email', 'unique:users'), 'doj' => array('required','date'), 'dob' => array('required','date'), 'inTime' => array('required', 'date_format:H:i:s'), 'outTime' => array('required', 'date_format:H:i:s'), 'phone' => array('required','regex:/[0-9]{10}/'), 'altPhone' => array('regex:/[0-9]{10}/') ); } $validator = Validator::make( $registrationDataArr, $validationRules ); return $validator; } /* Function Name: getTotalLeaves Author Name: <NAME> Date: June, 02 2014 Parameters: - Purpose: This function calculates total number of leaves for current year for current user object using his/her date of joining. */ public function getTotalLeaves(){ $currentYear = (int)date("Y"); $previousYear = $currentYear - 1; $thisYearTotalLeaves = $this->getTotalLeavesForYear($currentYear); return $thisYearTotalLeaves; } /* Function Name: getRemainingLeaves Author Name: <NAME> Date: June, 02 2014 Parameters: - Purpose: This function calculates total number of leaves for current year for current user object using his/her date of joining. */ public function getRemainingLeaves(){ return $this->getRemainingLeavesForYear(date("Y")); } /* Function Name : getNormalLeavesForYear Author Name : <NAME> Date : July 30, 2014 Parameters : $year Purpost : this function returns the count of all the normal leaves for current user for a given year. */ public function getNormalLeavesForYear($year){ $januaryOne = new DateTime(date("Y-m-d", mktime(0,0,0,1,1,$year))); $paidLeaves = Leaveconfig::getConfig("paid_leaves", $year)->leave_days; $allLeaves = $paidLeaves; if(Config::get("database.default") == "mysql"){ $optionalHolidays = Holiday::where("holidayType", "=", "OPTIONAL")->where(DB::raw('YEAR(holidayDate)'), "=", $year)->orderBy("holidayDate", "asc")->get(); } else{ $optionalHolidays = Holiday::where("holidayType", "=", "OPTIONAL")->where(DB::raw('EXTRACT( YEAR from "holidayDate"::date)'), "=", $year)->orderBy("holidayDate", "asc")->get(); } $optionalHolidaysCount = count(array_keys($optionalHolidays->toArray())); $dateOfJoining = new DateTime($this->doj); $joiningYear = (int)$dateOfJoining->format("Y"); $joiningYearStart = YearStart::where("year", $joiningYear)->first(); if($joiningYearStart){ $joiningYearStartDay = $joiningYearStart->startDay; $joiningYearStartMonth = $joiningYearStart->startMonth; } else{ $joiningYearStartDay = 15; $joiningYearStartMonth = 1; } $lastLeaveDateInYearOfJoining = new DateTime(date("Y-m-d", mktime(0,0,0,$joiningYearStartMonth,$joiningYearStartDay,$joiningYear))); $yearsInCompany = (int)$januaryOne->format("Y") - (int)$dateOfJoining->format("Y"); $isJoinedInCurrentYear = $yearsInCompany == 0 ? true : false; $isJoinedBeforeLastLeaveDateOfJoiningYear = (((int)$dateOfJoining->format("m") == 1) && ((int)$dateOfJoining->format("d") <= 15)) ? true : false; if(!$isJoinedBeforeLastLeaveDateOfJoiningYear && !$isJoinedInCurrentYear){ $yearsInCompany -= 1; } $allLeaves += $optionalHolidaysCount; $leavesPerMonth = $allLeaves / 12; if($isJoinedInCurrentYear){ $lastYearDateTS = mktime(0,0,0,12,31,$year); $joiningDateTS = mktime(0,0,0,$dateOfJoining->format("m"), $dateOfJoining->format("d"), $dateOfJoining->format("Y")); $diff = $lastYearDateTS - $joiningDateTS; $diffMonths = $diff / (24 * 60 * 60 * 30); $allLeaves = round($diffMonths * $leavesPerMonth); } else{ $allLeaves += $yearsInCompany; } // $extraLeaves = Extraleave::where("user_id", $this->id)->where("for_year", $year)->get(); // foreach($extraLeaves as $extraL){ // $allLeaves += $extraL->leaves_count; // } $currentDate = new DateTime(); $currentYearStart = YearStart::where("year", date("Y"))->first(); $currentYearJan = new DateTime(date("Y-m-d",mktime(0,0,0,1,1,date("Y")))); if($currentYearStart){ $currentYearStartDay = $currentYearStart->startDay; $currentYearStartMonth = $currentYearStart->startMonth; } else{ $currentYearStartDay = 15; $currentYearStartMonth = 1; } $lastLeaveDateInCurrentYear = new DateTime(date("Y-m-d",mktime(0,0,0,$currentYearStartMonth,$currentYearStartDay, date("Y")))); if((int)$year == (int)date("Y")){ if($currentDate >= $currentYearJan && $currentDate <= $lastLeaveDateInCurrentYear){ $allLeaves += $this->getTotalLeavesForYear(((int)$year-1)); } else{ $allLeaves += $this->carry_forward_leaves; } } return $allLeaves; } /* Function Name : getTotalLeavesForYear Author Name : <NAME> Date : June 16, 2014 Parameters : $year Purpost : this function returns the count of all the leaves for current user for a given year. */ public function getTotalLeavesForYear($year){ $januaryOne = new DateTime(date("Y-m-d", mktime(0,0,0,1,1,$year))); $paidLeaves = Leaveconfig::getConfig("paid_leaves", $year)->leave_days; $allLeaves = $paidLeaves; if(Config::get("database.default") == "mysql"){ $optionalHolidays = Holiday::where("holidayType", "=", "OPTIONAL")->where(DB::raw('YEAR(holidayDate)'), "=", $year)->orderBy("holidayDate", "asc")->get(); } else{ $optionalHolidays = Holiday::where("holidayType", "=", "OPTIONAL")->where(DB::raw('EXTRACT( YEAR from "holidayDate"::date)'), "=", $year)->orderBy("holidayDate", "asc")->get(); } $optionalHolidaysCount = count(array_keys($optionalHolidays->toArray())); $dateOfJoining = new DateTime($this->doj); $joiningYear = (int)$dateOfJoining->format("Y"); $joiningYearStart = YearStart::where("year", $joiningYear)->first(); if($joiningYearStart){ $joiningYearStartDay = $joiningYearStart->startDay; $joiningYearStartMonth = $joiningYearStart->startMonth; } else{ $joiningYearStartDay = 15; $joiningYearStartMonth = 1; } $lastLeaveDateInYearOfJoining = new DateTime(date("Y-m-d", mktime(0,0,0,$joiningYearStartMonth,$joiningYearStartDay,$joiningYear))); $yearsInCompany = (int)$januaryOne->format("Y") - (int)$dateOfJoining->format("Y"); $isJoinedInCurrentYear = $yearsInCompany == 0 ? true : false; $isJoinedBeforeLastLeaveDateOfJoiningYear = (((int)$dateOfJoining->format("m") == 1) && ((int)$dateOfJoining->format("d") <= 15)) ? true : false; if(!$isJoinedBeforeLastLeaveDateOfJoiningYear && !$isJoinedInCurrentYear){ $yearsInCompany -= 1; } $allLeaves += $optionalHolidaysCount; $leavesPerMonth = $allLeaves / 12; if($isJoinedInCurrentYear){ $lastYearDateTS = mktime(0,0,0,12,31,$year); $joiningDateTS = mktime(0,0,0,$dateOfJoining->format("m"), $dateOfJoining->format("d"), $dateOfJoining->format("Y")); $diff = $lastYearDateTS - $joiningDateTS; $diffMonths = $diff / (24 * 60 * 60 * 30); $allLeaves = round($diffMonths * $leavesPerMonth); } else{ $allLeaves += $yearsInCompany; } $extraLeaves = Extraleave::where("user_id", $this->id)->where("for_year", $year)->get(); foreach($extraLeaves as $extraL){ $allLeaves += $extraL->leaves_count; } $currentDate = new DateTime(); $currentYearStart = YearStart::where("year", date("Y"))->first(); $currentYearJan = new DateTime(date("Y-m-d",mktime(0,0,0,1,1,date("Y")))); if($currentYearStart){ $currentYearStartDay = $currentYearStart->startDay; $currentYearStartMonth = $currentYearStart->startMonth; } else{ $currentYearStartDay = 15; $currentYearStartMonth = 1; } $lastLeaveDateInCurrentYear = new DateTime(date("Y-m-d",mktime(0,0,0,$currentYearStartMonth,$currentYearStartDay, date("Y")))); if((int)$year == (int)date("Y")){ if($currentDate >= $currentYearJan && $currentDate <= $lastLeaveDateInCurrentYear){ $allLeaves += $this->getTotalLeavesForYear(((int)$year-1)); } else{ $allLeaves += $this->carry_forward_leaves; } } return $allLeaves; } /* Function Name : getRemainingLeavesForYear Author Name : <NAME> Date : June 16, 2014 Parameters : $year Purpost : this function returns the count of all the leaves for current user for a given year. */ public function getRemainingLeavesForYear($year){ $totalLeaves = $this->getTotalLeavesForYear($year); $remainingLeaves = $totalLeaves; $userLeaves = $this->leaves()->get(); foreach($userLeaves as $uLeave){ //$isApproved = true; if($uLeave->leaveStatus() == "APPROVED"){ if($uLeave->leave_type == "FH" || $uLeave->leave_type == "SH"){ $remainingLeaves -= 0.5; } else{ $remainingLeaves -= 1; } } } $extraLeaves = Extraleave::where("user_id", $this->id)->where("for_year", $year)->get(); foreach($extraLeaves as $extraL){ $remainingLeaves -= $extraL->leaves_count; } return $remainingLeaves; } /* Function Name : leaves Author Name : <NAME> Date : June 03, 2014 Parameters : none Purpose : Return leave relationship for eloquent */ public function leaves() { return $this->hasMany('Leave'); } /* Function Name : approvedLeaves Author Name : <NAME> Date : 25 June, 2014 Parameters : $year Purpose : to get the all approved leaves for current user for a given year */ public function approvedLeaves($year){ if(Config::get("database.default") == "mysql"){ $leaves = $this->hasMany('Leave')->where(DB::raw('YEAR(leave_date)'), $year)->get(); } else{ $leaves = $this->hasMany('Leave')->where(DB::raw('EXTRACT(year FROM "leave_date"::date)'), $year)->get(); } $approved = array(); foreach($leaves as $leave){ if($leave->leaveStatus() == "APPROVED"){ $approved[] = $leave; } } return $approved; } /* Function Name : pendingLeaves Author Name : <NAME> Date : 25 June, 2014 Parameters : $year Purpose : to get the all pending leaves for current user for a given year */ public function pendingLeaves($year){ if(Config::get("database.default") == "mysql"){ $leaves = $this->hasMany('Leave')->where(DB::raw('YEAR(leave_date)'), $year)->get(); } else{ $leaves = $this->hasMany('Leave')->where(DB::raw('EXTRACT(year FROM "leave_date"::date)'), $year)->get(); } $pending = array(); foreach($leaves as $leave){ if($leave->leaveStatus() == "PENDING"){ $pending[] = $leave; } } return $pending; } /* Function Name : rejectedLeaves Author Name : <NAME> Date : 25 June, 2014 Parameters : $year Purpose : to get the all rejected leaves for current user for a given year */ public function rejectedLeaves($year){ if(Config::get("database.default") == "mysql"){ $leaves = $this->hasMany('Leave')->where(DB::raw('YEAR(leave_date)'), $year)->get(); } else{ $leaves = $this->hasMany('Leave')->where(DB::raw('EXTRACT(year FROM "leave_date"::date)'), $year)->get(); } $rejected = array(); foreach($leaves as $leave){ if($leave->leaveStatus() == "REJECTED"){ $rejected[] = $leave; } } return $rejected; } /* Function Name : appliedLeaves Author Name : <NAME> Date : 25 June, 2014 Parameters : $year Purpose : to get the all applied leaves for current user for a given year */ public function appliedLeaves($year){ if(Config::get("database.default") == "mysql"){ return $this->hasMany('Leave')->where(DB::raw('DATE(leave_date)'), $year)->get(); } else { return $this->hasMany('Leave')->where(DB::raw('EXTRACT(year FROM "leave_date"::date)'), $year)->get(); } } /* Function Name : extraLeaves Author Name : <NAME> Date : 25 June, 2014 Parameters : $year Purpose : to get the all extra leaves for current user for a given year */ public function extraLeaves($year){ $extraLeaves = Extraleave::where("user_id", $this->id)->where("for_year", $year); return $extraLeaves; } /* Function Name : getExtraLeave Author Name : <NAME> Date : 30 July, 2014 Parameters : $year, $description Purpose : to get marriage leaves for user */ public function getExtraLeave($year, $description){ $extra_leave = $this->extraleaves($year)->where("description", "LIKE", "%" . $description . "%")->first(); if($extra_leave){ return $extra_leave->leaves_count; } return ""; } /* Function Name : dayLeave Author Name : <NAME> Date : 30 July, 2014 Parameters : $year, $description Purpose : this function will return 1 or 0.5 or "" on the basis of leave taken by user on given date, 1 for full day, 0.5 for half day, "" blank for no leave */ public function dayLeave($date){ $leave = $this->hasMany('Leave')->where("leave_date","=", $date)->first(); if($leave && $leave->leaveStatus() == "APPROVED"){ if($leave->leave_type == "FH" || $leave->leave_type == "SH"){ return 0.5; } else{ if($leave->leave_type = "LEAVE"){ return 1; } } } else{ return ""; } } /* Function Name : getMarriageLeaves Author Name : <NAME> Date : 30 July, 2014 Parameters : $year Purpose : to get marriage leaves for user */ // public function getMarriageLeaves($year){ // $marriage_leave = $this->extraleaves(date("Y"))->where("description","LIKE","%Marriage%")->first(); // if($marriage_leave){ // return $marriage_leave->leaves_count; // } // return ""; // } /* Function Name : getPaternityLeaves Author Name : <NAME> Date : 30 July, 2014 Parameters : $year Purpose : to get paternity leaves for user */ // public function getPaternityLeaves($year){ // $paternity_leave = $this->extraleaves(date("Y"))->where("description","LIKE","%Paternity%")->first(); // if($paternity_leave){ // return $paternity_leave->leaves_count; // } // return ""; // } /* Function Name : getMaternityLeaves Author Name : <NAME> Date : 30 July, 2014 Parameters : $year Purpose : to get maternity leaves for user */ // public function getMaternityLeaves($year){ // $maternity_leave = $this->extraleaves(date("Y"))->where("description","LIKE","%Maternity%")->first(); // if($maternity_leave){ // return $maternity_leave->leaves_count; // } // return ""; // } /* Function Name : generatePassword Author Name : <NAME> Date: : June 18, 2014 Parameters : numAlpha, numNonAlpha Purpose : Generate random password for the new user */ public static function generatePassword($numAlpha=6,$numNonAlpha=2) { $listAlpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $listNonAlpha = ',;:!?.$/*-+&@_+;./*&?$-!,'; return str_shuffle( substr(str_shuffle($listAlpha),0,$numAlpha) . substr(str_shuffle($listNonAlpha),0,$numNonAlpha) ); } } <file_sep><?php class HomeController extends BaseController { /* |-------------------------------------------------------------------------- | Default Home Controller |-------------------------------------------------------------------------- | | You may wish to use controllers instead of, or in addition to, Closure | based routes. That's great! Here is an example controller method to | get you started. To route to this controller, just add the route: | | Route::get('/', 'HomeController@showWelcome'); | */ public function userDashboard() { $user = Auth::user(); $totalLeaves = $user->getTotalLeaves(); $approvedLeaves = count($user->approvedLeaves(date("Y"))); $pendingLeaves = count($user->pendingLeaves(date("Y"))); $rejectedLeaves = count($user->rejectedLeaves(date("Y"))); $extraLeaves = count($user->extraLeaves(date("Y"))->get()); $appliedLeaves = count($user->appliedLeaves(date("Y"))); return View::make("users.user_dashboard") ->with("total_leaves", $totalLeaves) ->with("approved_leaves", $approvedLeaves) ->with("pending_leaves", $pendingLeaves) ->with("extra_leaves", $extraLeaves) ->with("applied_leaves", $appliedLeaves); } } <file_sep><?php class Leaveconfig extends Eloquent{ protected $table = 'leaveconfig'; public static function getConfig($leaveType,$year){ // print_r(Leaveconfig::where("leave_type",$leaveType)->where("year",$year)->get());exit; $config = Leaveconfig::where("leave_type",$leaveType)->where("year",$year)->get()->first(); if(!$config){ $config = new Leaveconfig(); $config->leave_type = $leaveType; $config->leave_days = 0; $config->year = date('Y'); } return $config; } } ?><file_sep><?php /* Class Name : TemplateFunctions author : <NAME> Date : June 16, 2014 Purpose : asts as Template functions library contains functions to be used in laravel templates. */ class TemplateFunction{ public static function getIntegerRangeDropdown($from, $to){ $arr = array_map(function($i) { return sprintf("%02s",$i); }, range($from, $to) ); $arr1 = array_combine($arr,$arr); return $arr1; } public static function getFullLeaveTypeName($ltype){ $fullNames = array( "LEAVE" => "Full Day", "FH" => "First Half", "SH" => "Second Half", "CSR" => "CSR", "LONG" => "Long Leave" ); if(array_key_exists($ltype, $fullNames)){ return $fullNames[$ltype]; } else{ return $ltype; } } public static function getLeaveTypeSummary($ltype){ return "(" . $ltype . ")"; } public static function fakeName($name){ $salt = Config::get("app.lms_key"); return base64_encode(TemplateFunction::encrypt($name, $salt)); } public static function originalName($enc_name){ $salt = Config::get("app.lms_key"); return TemplateFunction::decrypt(base64_decode($enc_name), $salt); } /** * Returns an encrypted & utf8-encoded */ public static function encrypt($pure_string, $encryption_key) { $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, utf8_encode($pure_string), MCRYPT_MODE_ECB, $iv); return $encrypted_string; } /** * Returns decrypted original string */ public static function decrypt($encrypted_string, $encryption_key) { $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, $encrypted_string, MCRYPT_MODE_ECB, $iv); return $decrypted_string; } public static function requireGoogleCalendarApi(){ require_once( base_path() . '/vendor/google/apiclient/src/Google/Client.php' ); require_once( base_path() . '/vendor/google/apiclient/src/Google/Service/Calendar.php' ); } public static function getGoogleCalendarCreds(){ $googleCreds = array(); $googleCreds['clientId'] = Config::get('google.client_id'); $googleCreds['serviceAccountName'] = Config::get('google.service_account_name'); $googleCreds['keyFileLocation'] = Config::get('google.key_file_location'); return $googleCreds; } public static function getUIDateClass($leaveOption, $leaveType){ if($leaveOption == "CSR" || $leaveOption == ""){ return "date-single"; } else{ switch($leaveType){ case "MULTI": return "date-multi"; case "LONG": return "date-long"; case "LEAVE": case "FH": case "SH": return "date-single"; default: return "date-single"; } } } }
38e226c2e39b1394ce2b41971f11e7a9b00f9bd1
[ "JavaScript", "PHP" ]
28
PHP
hehe87/leave-management
57f621429940e21d0f64a14fe6ba264145abca66
b8c37134ad6f04b70cb4e30b3fb33de6f059f600
refs/heads/master
<file_sep><?php namespace App\Http\Controllers\Website; class HomeController extends WebsiteController { public function index() { return $this->view('website.home'); } } <file_sep><?php namespace App\Http\Controllers\Admin\LatestActivities; use App\Http\Controllers\Admin\AdminController; use Bpocallaghan\LogActivity\Models\LogActivity; use Bpocallaghan\LogActivity\Models\LogModelActivity; use Illuminate\Http\Request; class LatestActivitiesController extends AdminController { public function website() { $items = LogActivity::getLatest(); return $this->view('admin.latest_activities.website')->with('items', $items); } public function admin() { $items = LogModelActivity::getLatest(); return $this->view('admin.latest_activities.admin')->with('items', $items); } } <file_sep><?php use App\Http\Controllers\Api\AnalyticsController; use App\Http\Controllers\Api\NotificationsController; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ // Route::middleware('auth:api')->get('/user', function (Request $request) { // return $request->user(); // }); // notifications Route::group(['prefix' => 'notifications',], function () { Route::post('/{user}', [NotificationsController::class, 'index']); Route::post('/{user}/unread', [NotificationsController::class, 'unread']); Route::post('/{user}/read/{notification}', [NotificationsController::class, 'read']); Route::post('/actions/latest', [NotificationsController::class, 'getLatestActions']); }); // analytics Route::group(['prefix' => 'analytics'], function () { Route::post('/keywords', [AnalyticsController::class, 'getKeywords']); Route::post('/visitors', [AnalyticsController::class, 'getVisitors']); Route::post('/browsers', [AnalyticsController::class, 'getBrowsers']); Route::post('/referrers', [AnalyticsController::class, 'getReferrers']); Route::post('/page-load', [AnalyticsController::class, 'getAvgPageLoad']); Route::post('/bounce-rate', [AnalyticsController::class, 'getBounceRate']); Route::post('/visited-pages', [AnalyticsController::class, 'getVisitedPages']); Route::post('/active-visitors', [AnalyticsController::class, 'getActiveVisitors']); Route::post('/unique-visitors', [AnalyticsController::class, 'getUniqueVisitors']); Route::post('/visitors-views', [AnalyticsController::class, 'getVisitorsAndPageViews']); Route::post('/visitors/locations', [AnalyticsController::class, 'getVisitorsLocations']); Route::post('/age', [AnalyticsController::class, 'getUsersAge']); Route::post('/devices', [AnalyticsController::class, 'getDevices']); Route::post('/gender', [AnalyticsController::class, 'getUsersGender']); Route::post('/device-category', [AnalyticsController::class, 'getDeviceCategory']); Route::post('/interests-other', [AnalyticsController::class, 'getInterestsOther']); Route::post('/interests-market', [AnalyticsController::class, 'getInterestsMarket']); Route::post('/interests-affinity', [AnalyticsController::class, 'getInterestsAffinity']); }); <file_sep><?php use App\Http\Controllers\Admin\Accounts\AdministratorsController; use App\Http\Controllers\Admin\Accounts\ClientsController; use App\Http\Controllers\Admin\DashboardController; use App\Http\Controllers\Admin\LatestActivities\LatestActivitiesController; use App\Http\Controllers\Admin\ProfileController; use App\Http\Controllers\Admin\Settings\NavigationOrderController; use App\Http\Controllers\Admin\Settings\NavigationsController; use App\Http\Controllers\Admin\Settings\RolesController; use Illuminate\Support\Facades\Route; /* |------------------------------------------ | Admin (when authorized and admin) |------------------------------------------ */ Route::group(['middleware' => ['auth', 'auth.admin'], 'prefix' => 'admin'], function () { Route::get('/', [DashboardController::class, 'index']); // profile Route::get('/profile', [ProfileController::class, 'index']); Route::put('/profile/{user}', [ProfileController::class, 'update']); // accounts Route::group(['prefix' => 'accounts'], function () { // clients Route::resource('clients', ClientsController::class); // users Route::get('administrators', [AdministratorsController::class, 'index']); Route::delete('administrators', [AdministratorsController::class, 'destroy']); }); // history Route::group(['prefix' => 'activities'], function () { Route::get('/', [LatestActivitiesController::class, 'website']); Route::get('/admin', [LatestActivitiesController::class, 'admin']); Route::get('/website', [LatestActivitiesController::class, 'website']); }); // settings Route::group(['prefix' => 'settings'], function () { Route::resource('roles', RolesController::class); // navigation Route::get('navigations/order', [NavigationOrderController::class, 'index']); Route::post('navigations/order', [NavigationOrderController::class, 'updateOrder']); Route::resource('navigations', NavigationsController::class); }); }); <file_sep><?php namespace Tests\Feature\Controllers; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; class VisitWebsitePagesTest extends TestCase { use RefreshDatabase; /** * Setup the test environment. * * @return void */ protected function setUp(): void { parent::setUp(); } /** @test */ public function visit_home() { $this->withoutExceptionHandling(); $response = $this->get('/'); $response->assertStatus(200); $response->assertSeeText(config('app.name')); } } <file_sep><?php namespace App\Http\Controllers\Traits; use Illuminate\Http\UploadedFile; use Intervention\Image\Facades\Image; trait UploadImageHelper { /** * Upload the banner image, create a thumb as well * * @param $file * @param string $path * @param array $size * @return string|void */ protected function uploadImage( UploadedFile $file, $path = '', $size = ['o' => [1920, 500], 'tn' => [576, 150]] ) { $name = token(); $extension = $file->guessClientExtension(); $filename = $name . '.' . $extension; $filenameThumb = $name . '-tn.' . $extension; $imageTmp = Image::make($file->getRealPath()); if (!$imageTmp) { return notify()->error('Oops', 'Something went wrong', 'warning shake animated'); } $path = upload_path_images($path); // original $imageTmp->save($path . $name . '-o.' . $extension); // save the image $image = $imageTmp->fit($size['o'][0], $size['o'][1])->save($path . $filename); $image->fit($size['tn'][0], $size['tn'][1])->save($path . $filenameThumb); return $filename; } /** * Save Image in Storage, crop image and save in public/uploads/images * @param UploadedFile $file * @return string */ private function uploadImageAndKeepAspectRatio(UploadedFile $file, $size = ['l' => [1000, 1000], 't' => [300, 300]]): string { $name = token(); $extension = $file->guessClientExtension(); $largeSize = $size['l']; $thumbSize = $size['t']; $path = upload_path_images(); $filename = "{$name}.{$extension}"; $filenameThumb = "{$name}-tn.{$extension}"; $filenameOriginal = "{$name}-o.{$extension}"; $imageTmp = Image::make($file->getRealPath()); if (!$imageTmp) { return ''; } // save original $imageTmp->save($path . $filenameOriginal); // if height is the biggest - resize on max height if ($imageTmp->width() < $imageTmp->height()) { // resize the image to the large height and constrain aspect ratio (auto width) $imageTmp->resize(null, $largeSize[1], function ($constraint) { $constraint->aspectRatio(); })->save($path . $filename); // resize the image to the thumb height and constrain aspect ratio (auto width) $imageTmp->resize(null, $thumbSize[1], function ($constraint) { $constraint->aspectRatio(); })->save($path . $filenameThumb); } else { // resize the image to the large width and constrain aspect ratio (auto height) $imageTmp->resize($largeSize[0], null, function ($constraint) { $constraint->aspectRatio(); })->save($path . $filename); // resize the image to the thumb width and constrain aspect ratio (auto width) $imageTmp->resize($thumbSize[0], null, function ($constraint) { $constraint->aspectRatio(); })->save($path . $filenameThumb); } return $filename; } protected function moveImage(UploadedFile $file, $path = '') { $name = token(); $extension = $file->guessClientExtension(); $filename = $name . '.' . $extension; $filenameThumb = $name . '-tn.' . $extension; $imageTmp = Image::make($file->getRealPath()); if (!$imageTmp) { return notify()->error( 'Oops', 'Something went wrong', 'warning shake animated' ); } $path = upload_path_images($path); // original $imageTmp->save($path . $name . '-o.' . $extension); $imageTmp->save($path . $filename); $imageTmp->save($path . $filenameThumb); // save the image // resize the image to a width of 300 and constrain aspect ratio (auto height) //$img->resize(300, null, function ($constraint) { // $constraint->aspectRatio(); //}); //$image = $imageTmp->fit($size['o'][0], $size['o'][1])->save($path . $filename); //$image->fit($size['tn'][0], $size['tn'][1])->save($path . $filenameThumb); return $filename; } } <file_sep><?php namespace Database\Seeders; use App\Models\User; use App\Models\Role; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class UsersTableSeeder extends Seeder { public function run() { User::truncate(); DB::table('role_user')->truncate(); //------------------------------------------------- // Developer //------------------------------------------------- $user = User::create([ 'firstname' => 'Ben-Piet', 'lastname' => 'O\'Callaghan', 'cellphone' => '123456789', 'email' => '<EMAIL>', 'gender' => 'ninja', 'password' => bcrypt('ben'), 'email_verified_at' => now() ]); // $user->syncRoles([ // Role::$ADMIN, // Role::$DEVELOPER, // ]); $this->addAllRolesToUser($user); //------------------------------------------------- // GITHUP - PREVIEW //------------------------------------------------- $user = User::create([ 'firstname' => 'Admin', 'lastname' => 'Github', 'cellphone' => '123456789', 'email' => '<EMAIL>', 'gender' => 'male', 'password' => <PASSWORD>('<PASSWORD>'), 'email_verified_at' => now() ]); $this->addAllRolesToUser($user); } /** * Add all the roles to the user * @param $user */ private function addAllRolesToUser($user) { $roles = Role::all()->pluck('keyword', 'id')->values(); $user->syncRoles($roles); } } <file_sep><?php namespace App\Http\Controllers\Website; use App\Http\Controllers\Controller; class WebsiteController extends Controller { protected function view($path, $data = []) { return parent::view($path, $data) ->with('settings', (object) ['description' => config('app.description')]); } }
ed87c1e16e945f36f81dd087dcddfbc48995ebf8
[ "PHP" ]
8
PHP
bpocallaghan/titan-starter
ea69c8e16d8242d77b59f33761e522ad1ffba119
a4169f49b6844e031c2d91440e58425dd6133327
refs/heads/master
<repo_name>carlosdlr/getting-started-python<file_sep>/samples/shorthand_swapping_sample.py # Let's say we want to swap # the values of a and b... a = 23 b = 42 # The "classic" way to do it # with a temporary variable: #tmp = a #a = b #b = tmp # Python also lets us # use this short-hand: a, b = b, a print('The a and b new values {0} {1}'.format(a, b)) <file_sep>/samples/finding_the_most_common_element_in_a_collection.py # collections.Counter lets you find the most common # elements in an iterable: import collections c = collections.Counter('helloworld') print("--"*50) print("Counter result") print(c) print("--"*50) print("The most 3 common elements in the string 'helloworld'") print(c.most_common(3)) <file_sep>/samples/working_with_ip_addresses.py # Python 3 has a std lib # module for working with # IP addresses: import ipaddress print(ipaddress.ip_address('192.168.1.2')) print(ipaddress.ip_address('2001:af3::')) <file_sep>/samples/is_vs_double_equals_object_comparison.py a = [1,2,3] b = a #this will print true because both variables are pointing to the same object print(a is b) #this will print true because both variables have the same values in this case 1,2,3 print(a == b) c = list(a) #this will print true because both variables have the same values in this case 1,2,3 print(a == c) #this will print false becuase these variables are pointing to different objects in this case c is pointing to a new list base on the a values print(a is c) # "is" expressions evaluate to True if two # variables point to the same object # "==" evaluates to True if the objects # referred to by the variables are equal <file_sep>/README.md # Getting Started With Python Different kind of samples using python features <file_sep>/samples/peeking_behind_the_bytecode_curtain.py # You can use Python's built-in "dis" # module to disassemble functions and # inspect their CPython VM bytecode: def greet(name): return 'Hello, ' + name + '!' print(greet('Carlos')) import dis dis.dis(greet)
1e76ca04fb701bb1b17fb8ec5c730ba25450c920
[ "Markdown", "Python" ]
6
Python
carlosdlr/getting-started-python
fe7045f55c1c380bd3dbf2ed1256458e573f9131
9c6ed47238f35c313abdc285a9d0a2d69b228878
refs/heads/master
<file_sep>require './recipe_data' # レシピの管理、出力を行えるようにするクラス class RecipeReader class << self # IDを元にレシピを検索し、標準出力する def print(id=nil,user_name=nil) RecipeData.find_recipe(id,user_name) do |recipe| print_recipe(recipe) end end private # レシピデータを標準出力する def print_recipe(recipe) puts "#{recipe[:id]}: #{recipe[:name]} : #{recipe[:discription]}" end end end # コマンドライン引数を元にレシピ情報への操作を決定する if ARGV[1] RecipeReader.print(ARGV[0],ARGV[1].to_i) else RecipeReader.print(ARGV[0]) end <file_sep>class RecipeData DATA = [ { id: 1, name: 'オムライス', user_name: 'hoge', discription: '卵を焼いてごはんにのせる' }, { id: 2, name: '親子丼', user_name: 'kou', discription: '鶏肉を焼いて卵でとじてごはんにのせる' }, { id: 3, name: '杏仁豆腐', user_name: 'piyo', discription: '牛乳と砂糖をまぜてゼラチンで固める' } ].freeze class << self def find_recipe( user_name=nil, id=nil ) list = DATA; if id list = list.select {|recipe| recipe[:id] == id } end if user_name list = list.select {|recipe| recipe[:user_name] == user_name } end list.each do |recipe| yield recipe end end end end <file_sep># 実行方法 Rubyをインストールしている環境下にて、以下のコマンドを実行。 --------------------------------------------- ruby recipe.rb --------------------------------------------- # データの追加方法 データが定義されているファイル「recipe_data.rb」内にて、配列に以下のフォーマットにしたがって追記。 --------------------------------------------- DATA = [ { id: 1, name: 'オムライス', discription: '卵を焼いてごはんにのせる' }, { id: 2, name: '親子丼', discription: '鶏肉を焼いて卵でとじてごはんにのせる' }, { id: 3, name: '杏仁豆腐', discription: '牛乳と砂糖をまぜてゼラチンで固める' } ].freeze ---------------------------------------------
1e75c8446e4b1784c049b693d91db90991939f66
[ "Text", "Ruby" ]
3
Ruby
furoshiki/tkm-kj-rcw
13fbe1f926ed14546109aafd506a7f77e33aa34d
41abd1bfe6c913e26c44dd99e9f8fa5f32f50912
refs/heads/master
<repo_name>teisia/capstone-project<file_sep>/README.md # Plan Together Plan together is a group trip planning app that enables people to collaborate and keep everything needed for planning a trip in one centralized place. Deployed site: plantogether.co This is a demo app so some of the features are not 100% complete. I will be updating the app in the near future so that it will be fully usable. Please feel free to contact me with any questions you may have before then at <EMAIL> ### Stack * HTML5 * CSS3 * Bootstrap * JavaScript * AngularJS * Express * Node.js * PostgreSQL * Knex * OAuth 2.0 <file_sep>/seeds/tasks.js exports.seed = function(knex, Promise) { return Promise.join( // Deletes ALL existing entries knex('tasks').del(), // Inserts seed entries knex('tasks').insert({user_id: 1, trip_id: 1, description: 'book camp site', due_date: '4/15/16'}), knex('tasks').insert({user_id: 2, trip_id: 1, description: 'get beer', due_date: '5/14/16' }), knex('tasks').insert({user_id: 1, trip_id: 2, description: 'book cabin', due_date: '6/1/16'}), knex('tasks').insert({user_id: 2, trip_id: 2, description: 'make menu', due_date: '6/30/16'}) ); }; <file_sep>/migrations/20160405164524_create_tripuser.js exports.up = function(knex, Promise) { return knex.schema.createTable('trip_user', function(table){ table.integer('trip_id'); table.integer('user_id'); }) }; exports.down = function(knex, Promise) { return knex.schema.dropTable('trip_user'); }; <file_sep>/migrations/20160408192257_create_tripDetails.js exports.up = function(knex, Promise) { return knex.schema.createTable('trip_details', function(table){ table.increments(); table.integer('user_id'); table.integer('trip_id'); table.text('detail'); table.string('url'); }) }; exports.down = function(knex, Promise) { return knex.schema.dropTable('trip_details'); }; <file_sep>/public/js/controllers.js app.controller('LoginCtrl', function($scope, $auth, $location) { $scope.authenticate = function(provider) { $auth.authenticate(provider) .then(function(response) { console.log('You have successfully signed in with ' + provider + '!'); $location.path('/dashboard') }) .catch(function(error) { if (error.error) { // Popup error - invalid redirect_uri, pressed cancel button, etc. console.log(error.error); } else if (error.data) { // HTTP response error from server console.log(error.data.message, error.status); } else { console.log(error); } }); }; }); app.controller('LogOutCtrl', function($scope, $auth, SignOutService) { $scope.logOut = function() { SignOutService.signout = function() { $location.path('/') } } }); app.controller('MainController', ['$scope', '$http', '$routeParams', '$location', '$route', '$window', 'TripService', 'UserService', function($scope, $http, $routeParams, $location, $route, $window, TripService, UserService){ $scope.toggleNewTripForm = function() { $scope.showme = !$scope.showme; } TripService.getTrips().then(function(payload){ $scope.trip_collection = payload.data.payload; }, function(error){ console.log("an error occurred"); }); TripService.getTripsInvited().then(function(payload){ $scope.invited_collection = payload.data; }, function(error){ console.log("an error occurred"); }); $scope.trip = {}; $scope.postTrip = function() { TripService.newTrip($scope.trip).then(function(result) { $route.reload(); console.log("posted trip"); }) } UserService.getUsers().then(function(payload) { $scope.user_collection = payload.data.payload; }, function(error){ console.log("an error occurred"); }) }]) app.controller('SingleTripController', ['$scope', '$http', '$routeParams', '$location', '$route', '$window', 'TripService', 'UserService', 'TaskService', 'MessageService', 'TripDService', 'MemberService', function($scope, $http, $routeParams, $location, $route, $window, TripService, UserService, TaskService, MessageService, TripDService, MemberService){ $scope.toggleAddMembersForm = function () { $scope.showmeAM = !$scope.showmeAM; } $scope.toggleEditTripForm = function () { $scope.showmeET = !$scope.showmeET; } $scope.toggleNewTaskForm = function () { $scope.showmeNT = !$scope.showmeNT; } $scope.toggleEditTaskForm = function () { this.showmeETask = !this.showmeETask; } $scope.toggleNewMessage = function () { $scope.showmeNM = !$scope.showmeNM; } $scope.toggleEditMsgForm = function () { this.showmeEM = !this.showmeEM; } $scope.toggleNewTripDForm = function () { $scope.showmeNTD = !$scope.showmeNTD; } $scope.toggleEditTripDForm = function () { this.showmeETD = !this.showmeETD; } var the_id = $routeParams.id; TripService.getTrip(the_id).then(function(payload){ $scope.singleTrip = payload.data.payload[0]; $scope.admin_id = $scope.singleTrip.admin_id; UserService.getUser($scope.admin_id).then(function(payload2) { $scope.organizer = payload2.data[0].first_name + ' ' + payload2.data[0].last_name; }) }, function(error){ console.log("an error occurred"); }); TripService.editTrip(the_id).then(function(payload) { $scope.tripInfo = payload.data.payload[0]; }) TripService.deleteTrip(the_id).then(function(payload) { console.log("you deleted it"); }) UserService.getUsers().then(function(payload) { $scope.user_collection = payload.data; }, function(error){ console.log("an error occurred"); }) TaskService.getTasks(the_id).then(function(payload){ $scope.task_collection = payload.data; }, function(error){ console.log("an error occurred"); }) $scope.checkTask = function(task) { TaskService.editTask(the_id, task).then(function(payload) { $scope.task_collection = payload.data; }) } $scope.task = {}; $scope.postTask = function() { TaskService.newTask(the_id, $scope.task).then(function() { $route.reload(); console.log("posted task"); }) } $scope.editTask = function (task) { TaskService.editTask(the_id, task).then(function(payload) { console.log("you edited it"); $scope.task_collection = payload.data; }) } $scope.deleteTask = function (taskId) { TaskService.deleteTask(the_id, taskId).then(function(payload) { console.log("you deleted it"); $scope.task_collection = payload.data; }) } MessageService.getMessages(the_id).then(function(payload){ console.log("*****ALL MESSAGES****"); console.log(payload); $scope.message_collection = payload.data.message; }, function(error){ console.log("an error occurred"); }) $scope.message = {}; $scope.postMessage = function() { MessageService.newMessage(the_id, $scope.message).then(function() { $route.reload(); console.log("posted message"); }) } $scope.editMessage = function (message) { MessageService.editMessage(the_id, message).then(function(payload) { console.log("you edited the msg"); $scope.message_collection = payload.data; }) } $scope.deleteMessage = function (messageId) { MessageService.deleteMessage(the_id, messageId).then(function(payload) { console.log("you deleted the msg"); $scope.message_collection = payload.data; }) } TripDService.getTripDs(the_id).then(function(payload){ $scope.tripd_collection = payload.data; }, function(error){ console.log("an error occurred"); }) $scope.tripD = {}; $scope.postTripD = function() { TripDService.newTripD(the_id, $scope.tripD).then(function() { $route.reload(); console.log("posted trip detail"); }) } $scope.editTripD = function (tripd) { TripDService.editTripD(the_id, tripd).then(function(payload) { console.log("you edited the trip detail"); $scope.tripd_collection = payload.data; }) } $scope.deleteTripD = function (tripdId) { TripDService.deleteTripD(the_id, tripdId).then(function(payload) { console.log("you deleted the trip detail"); $scope.tripd_collection = payload.data; }) } $scope.members = {}; $scope.postMembers = function() { MemberService.postMembers(the_id, $scope.members).then(function() { $route.reload(); console.log("posted members"); }) } MemberService.getMembers(the_id).then(function(payload){ $scope.member_collection = payload.data; }, function(error){ console.log("an error occurred"); }) }]) <file_sep>/public/js/services.js app.factory("SignOutService", function($http) { return { signout: function() { return $http.get("/sign-out"); } } }) app.factory("UserService", function($http) { return { getUsers: function() { return $http.get("/users"); }, getUser: function(user_id) { return $http.get("/users/"+user_id); } } }) app.factory("MemberService", function($http) { return { postMembers: function(trip_id, members_object) { console.log(members_object); return $http.post("/trips/"+trip_id+"/members", {user_id: members_object}); }, getMembers: function(trip_id) { return $http.get("/trips/"+trip_id+"/members"); } } }) app.factory("TripService", function($http){ return { getTrips: function() { return $http.get("/trips"); }, getTripsInvited: function() { return $http.get("/trips/invited"); }, getTrip: function(trip_id) { return $http.get("/trips/"+trip_id); }, newTrip: function(trip_object) { return $http.post("/trips", trip_object); }, editTrip: function(trip_id) { return $http.get("/trips/"+trip_id); }, deleteTrip: function(trip_id) { return $http.post("/trips/"+trip_id); } } }); app.factory("TripDService", function($http){ return { getTripDs: function(trip_id) { return $http.get("/trips/"+trip_id+"/tripD"); }, newTripD: function(trip_id, tripd_object) { return $http.post("/trips/"+trip_id+"/tripD", tripd_object); }, editTripD: function(trip_id, tripd) { return $http.post("/trips/"+trip_id+"/tripD/"+tripd.id+"/edit", tripd); }, deleteTripD: function(trip_id, tripd_id) { return $http.post("/trips/"+trip_id+"/tripD/"+tripd_id+"/delete"); } } }); app.factory("TaskService", function($http){ return { getTasks: function(trip_id) { return $http.get("/trips/"+trip_id+"/tasks"); }, newTask: function(trip_id, task_object) { return $http.post("/trips/"+trip_id+"/tasks", task_object); }, editTask: function(trip_id, task) { return $http.post("/trips/"+trip_id+"/tasks/"+task.id+"/edit", task); }, deleteTask: function(trip_id, task_id) { return $http.post("/trips/"+trip_id+"/tasks/"+task_id+"/delete"); } } }); app.factory("MessageService", function($http){ return { getMessages: function(trip_id) { return $http.get("/trips/"+trip_id+"/messages"); }, newMessage: function(trip_id, message_object) { return $http.post("/trips/"+trip_id+"/messages", message_object); }, editMessage: function(trip_id, message) { return $http.post("/trips/"+trip_id+"/messages/"+message.id+"/edit", message); }, deleteMessage: function(trip_id, message_id) { return $http.post("/trips/"+trip_id+"/messages/"+message_id+"/delete"); } } }); <file_sep>/routes/trips.js var express = require('express'); var router = express.Router(); var knex = require('../db/knex'); var moment = require('moment'); function trips() { return knex('trip'); }; function tripUser() { return knex('trip_user'); }; function tasks() { return knex('tasks'); }; function User() { return knex('user_list'); }; function messages() { return knex('messages'); } router.get("/", function(req,res){ trips().select().where({admin_id: req.cookies.user}).then(function(payload){ User().select().then(function(payload2) { res.json({payload: payload, payload2: payload2}); }) }) }); router.get("/invited", function(req,res){ tripUser().select().where({user_id: req.cookies.user}).then(function(payload){ trip_collection = []; for (var i = 0; i < payload.length; i++) { trip_collection.push(parseInt(payload[i].trip_id)); } trips().whereIn('id', trip_collection).then(function(new_stuff){ res.json(new_stuff); }) }) }); router.get("/:id", function(req,res){ trips().select().where({id: req.params.id}).then(function(payload){ User().select().then(function(payload2) { res.json({payload: payload, payload2: payload2}); }) }) }); router.post("/", function(req,res){ var obj = {} obj.title = req.body.title, obj.description= req.body.description, obj.trip_start= req.body.trip_start, obj.trip_end= req.body.trip_end obj.admin_id= req.cookies.user, obj.image = req.body.image, trips().insert(obj).returning('*').then(function(result){ res.json(result); }) }); router.post("/edit", function(req,res) { trips().where("id", req.body.id).update(req.body).then(function(result){ res.redirect('/#/trips/'+req.body.id+''); }) }); router.post("/delete", function(req,res) { trips().where("id", req.body.id).del().then(function(){ res.redirect('/#/dashboard'); }) }); router.post("/:id/members", function(req, res) { var obj = {} console.log(req.body); obj.trip_id = req.params.id, obj.user_id = req.body.user_id, tripUser().insert(obj).then(function(){ res.json({success: true}); }) }) router.get("/:id/members", function(req, res) { tripUser().select().where({trip_id: req.params.id}).then(function(payload){ user_collection = []; for (var i = 0; i < payload.length; i++) { user_collection.push(parseInt(payload[i].user_id)); } User().whereIn('id', user_collection).then(function(new_stuff){ res.json(new_stuff); }) }) }) module.exports = router; <file_sep>/public/js/app.js var app = angular.module('angApp', ['ngRoute', 'satellizer']) app.config(function($routeProvider, $authProvider) { $routeProvider .when('/', { templateUrl: 'partials/splash.html', controller: 'LoginCtrl' }) .when('/dashboard', { templateUrl: 'partials/dashboard.html', controller: 'MainController' }) .when('/trips/:id', { templateUrl: 'partials/trip.html', controller: 'SingleTripController' }) .when('/sign-out', { templateUrl: 'partials/splash.html', controller: 'LogOutCtrl' }) .otherwise({ redirectTo: '/dashboard' }); $authProvider.loginRedirect = '/dashboard'; $authProvider.google({ clientId: '746466032586-fkn4lk9v4pccpa005accokik9u2m13cb.apps.googleusercontent.com' }) $authProvider.google({ url: '/auth/google', authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth', redirectUri: window.location.origin, requiredUrlParams: ['scope'], optionalUrlParams: ['display'], scope: ['profile', 'email', 'https://www.googleapis.com/auth/calendar'], scopePrefix: 'openid', scopeDelimiter: ' ', display: 'popup', type: '2.0', popupOptions: { width: 452, height: 633 } }); }) <file_sep>/routes/messages.js var express = require('express'); var router = express.Router(); var knex = require('../db/knex'); var moment = require('moment'); function trips() { return knex('trip'); }; function messages() { return knex('messages'); }; function User() { return knex('user_list'); }; router.get("/:id/messages", function(req,res){ messages().where({trip_id: +req.params.id}).then(function(msgs) { Promise.all(msgs.map(function(m) { return User().where('id', m.user_id).first().then(function (user) { var messenger = user.first_name + ' ' + user.last_name; m.messenger = messenger; return m; }) })).then(function(msgss) { console.log("*****MESSAGES*****"); console.log(msgs); res.json({message: msgss}); }) }) }); router.post("/:id/messages", function(req,res){ var obj = {} obj.user_id= req.cookies.user, obj.trip_id= req.params.id, obj.message= req.body.message, obj.created_at= moment().calendar(); messages().insert(obj).then(function(){ res.json({success: true}); }) }); router.post("/:id/messages/:message_id/edit", function(req,res) { messages().where("id", req.params.message_id).update(req.body).then(function(result){ res.redirect("/" +req.params.id+ "/messages"); }) }); router.post("/:id/messages/:message_id/delete", function(req,res) { messages().where("id", req.params.message_id).del().then(function(){ res.redirect("/" +req.params.id+ "/messages"); }) }); module.exports = router; <file_sep>/seeds/trips.js exports.seed = function(knex, Promise) { return Promise.join( // Deletes ALL existing entries knex('trip').del(), // Inserts seed entries knex('trip').insert({title: 'moab', description: 'car camping in moab', trip_start: '5/15/16', trip_end: '5/18/16', admin_id: 1, image: 'https://www.moabadventurecenter.com/images/gallery-trips/Cataract%20Canyon-4-5-Day-Gallery/mac-moab-cataract-canyon-0.jpg'}), knex('trip').insert({title: 'wyoming', description: 'cabin in wyoming', trip_start: '7/21/16', trip_end: '7/26/16', admin_id: 2, image: 'https://www.selectregistry.com/Uploads/images/Wyoming.jpg'}) ); }; <file_sep>/routes/tasks.js var express = require('express'); var router = express.Router(); var knex = require('../db/knex'); function trips() { return knex('trip'); }; function tasks() { return knex('tasks'); }; function User() { return knex('user_list'); }; router.get("/:id/tasks", function(req,res){ tasks().select().where({trip_id: +req.params.id}).then(function(payload) { res.json(payload); }) }); router.post("/:id/tasks", function(req,res){ var obj = {} obj.description= req.body.description, obj.due_date= req.body.due_date, obj.admin_id= req.cookies.user, obj.trip_id= req.params.id, obj.completed = req.body.completed, tasks().insert(obj).then(function(){ res.json({success: true}); }) }); router.post("/:id/tasks/:task_id/edit", function(req,res) { tasks().where("id", req.params.task_id).update(req.body).then(function(result){ res.redirect("/" +req.params.id+ "/tasks"); }) }); router.post("/:id/tasks/:task_id/delete", function(req,res) { tasks().where("id", req.params.task_id).del().then(function(){ res.redirect("/" +req.params.id+ "/tasks"); }) }); module.exports = router;
f1ed751bc318ae595e753522fec33b3519e936d8
[ "Markdown", "JavaScript" ]
11
Markdown
teisia/capstone-project
642dec6e1811aac3c01dbad8a43ce4063204d574
528b4deacfb24223aab0f1ed548a7db5b3ee72b2
refs/heads/main
<repo_name>ckuilan/Port-Modification-Script<file_sep>/Port Modification Script.py from netmiko import ConnectHandler import re import sys import paramiko fd = open(r'C:\Users\"insert User here"\\PythonOutput.txt','w') sys.stdout = fd platform = 'cisco_ios' username = 'admin' password = '<PASSWORD>' ##Make this the directory of the IPlist.txt ip_add_file = open(r'C:\Users\"insert User here"\\IPAddressList.txt','r') for host in ip_add_file: device = ConnectHandler(device_type=platform, ip=host, username=username, password=password) output = device.send_command('enable') showIP = device.send_command("show int status | in 174 | 176") #collection of interfaces for modification interfaces = []; for line in showIP.splitlines(): print ("\n############################") print ("Host " +host) xx = line r1 = re.match(r"^Fa.*\/[0-9]|Gi.*\/[0-9]|Gigabitethernet.*\/[0-9]", str(xx)) print(xx) print('Matched Interface ' +r1.group()) if "174" or "176" in line: interfaces.append(r1.group()) #showing interfaces collected print("\nFound these interfaces:") print(interfaces) #creating loop for interface change for intf in interfaces: output = device.send_command("sh int "+intf+" status"); if "trunk" in output: print("\n" +intf) print("Skipping, port is a trunk.") else: print("\n" +intf) print("Modifying now ....Please Wait ") # issue commands to te interface that has been matched config_commands = [ 'int '+intf, 'switchport access vlan 178', 'no shut'] device.send_config_set(config_commands) print("Done!") fd.close()
c499122f7ef942c62d275bcbec37c5247edb35d4
[ "Python" ]
1
Python
ckuilan/Port-Modification-Script
f64f43ca34d1655bc2e930461ca1eb5ddca644e3
1d1f1fe8d716a60d23ac80eb6aa5d354e834133a
refs/heads/main
<file_sep># neural-network-base ![alt text](https://github.com/l-a-motta/neural-network-base/blob/main/neural.png?raw=true) Esta é uma base para uma rede neural em C ++, com feedforwarding, mas sem backpropagation. Também há uma pequena imagem com uma visualização dos valores internos de uma rede neural genérica. ## Installation Você pode simplesmente importar esta classe em seu programa e usá-la como quiser. Há comentários internos sobre como usar, mas segue o uso básico da classe. ## Usage Primeiro você precisa de uma matriz de doubles (que será sua entrada), um double para viés no neurônio e um double para viés na saída ```c double _inputs[] = {6,7}; double _biasNeuron = 0; double _biasOutput = 0; ``` Então você pode inicializar a classe com essas variáveis. ```c RedeNeural n(_inputs, _biasNeuron, _biasOutput); ``` E para que a saída seja alimentada, você usa a função feedForward. ```c n.feedForward(); ``` Inicialmente a rede neural possui 2 inputs, 4 neurons e 2 outputs. Para alterar isso, basta ir no código e mudar as constantes específicas. ```c #define N_INPUTS 2 #define N_NEURONS 4 #define N_OUTPUTS 2 ``` Os axons também estão restritos por MIN e MAX. Mudar esses valores também segue a mesma lógica, eles começam limitados entre -1 e 1. ```c #define MIN_AXON -1 #define MAX_AXON 1 //#define ESCOPO_DECIMAL_AXON 100 ``` Obs.: O limite de escopo decimal foi desabilitado por padrão. Os doubles estão ilimitados. Caso queira limitar as casas decimais, descomente as linhas apropriadas. ## Contributing Pull requests são bem-vindos. Para mudanças importantes, abra um problema primeiro para discutir o que você gostaria de mudar. Certifique-se de atualizar os testes conforme apropriado. ## License [MIT](https://choosealicense.com/licenses/mit/) <file_sep>// <NAME> - ICMC USP 11275338 // POR ALGUM MOTIVO, O OUTPUT FICA COMO nan SE VC NAO USAR getAxon(); ANTES DE CHAMAR UM getOutput(); #include <iostream> #include <vector> #include <list> #include <cstdlib> #include <math.h> #include <time.h> #include <stdlib.h> #include <stdio.h> using namespace std; #define MIN_AXON -1 #define MAX_AXON 1 //#define ESCOPO_DECIMAL_AXON 100 #define N_INPUTS 2 #define N_NEURONS 4 #define N_OUTPUTS 2 /* PARA O USO DA CLASSE: 1. Crie um vetor de doubles com seus inputs, o tamanho do vetor pode ser qualquer um, desde que voce altere o valor da constante N_INPUTS para ficar igual a qtd de inputs 2. Cria um double que sera seu bias dos neuronios e outro para o bias dos outputs 3. Altere o numero de NEURONS e OUTPUTS a vontade, pelas constantes no comeco da classe de respectivo nome 4.1 Instancie a classe e mande os valores dos inputs e do bias no construtor 4.2 ATENCAO: Ao instanciar a classe, ela automaticamente randomiza os axons. Se quiser randomizar os axons novamente, use a funcao populateAxons() 5. Use os gets e sets a vontade, cheque cada um para ver o que eles retornam ou o que eles recebem 6. Use a funcao feedForward() para calcular os neuronios e outputs OBS. Comente os printfs dos metodos se nao quiser que o passo-a-passo seja printado na tela */ class RedeNeural { private: typedef struct { double axonsIn[N_INPUTS][N_NEURONS]; // [x][y] -> [x] é para o input, signifca qual input veio, [y] é para neuronio, signifca para qual neuronio vai double axonsOut[N_NEURONS][N_OUTPUTS]; // [x][y] -> [x] é para o neuronio, signifca qual neuronio veio, [y] é para output, signifca para qual output vai } structAxons; double input[N_INPUTS], output[N_OUTPUTS]; // input e output com seu devido tamanho double neuron[N_NEURONS]; // Neuronios para a camada escondida. Nessa classe, ha somente 1 cada escondida, voce pode talvez precisar de 2 structAxons axons; // Axons para conectar inputs -> neurons -> outputs double biasNeuron, biasOutput; // Biases para os neuronios e os outputs, cada um independente se quiser public: // CONSTRUCTOR RedeNeural(double _input[], double _biasNeuron, double _biasOutput) { for(int i = 0; i < N_INPUTS; i++) { input[i] = _input[i]; } biasNeuron = _biasNeuron; biasOutput = _biasOutput; populateAxons(); // Isso talvez seja removido depois, ja que popular os axons o usuario q faz uma vez so, e nao a cada construcao } // GETTERS double* getInput() { return input; } double* getOutput() { return output; } structAxons getAxons() { return axons; } double* getNeuron() { return neuron; } double getBiasNeuron() { return biasNeuron; } double getBiasOutput() { return biasOutput; } // SETTERS void setInput(double _input[]) { for(int i = 0; i < N_INPUTS; i++) { input[i] = _input[i]; } } void setOutput(double _output[]) { for(int i = 0; i < N_OUTPUTS; i++) { output[i] = _output[i]; } } void setAxonsIn(double _axonsIn[][N_NEURONS]) { for(int i = 0; i < N_INPUTS; i++) { for(int j = 0; j < N_NEURONS; j++) { axons.axonsIn[i][j] = _axonsIn[i][j]; } } } void setAxonsOut(double _axonsOut[][N_OUTPUTS]) { for(int i = 0; i < N_NEURONS; i++) { for(int j = 0; j < N_OUTPUTS; j++) { axons.axonsOut[i][j] = _axonsOut[i][j]; } } } void setNeuron(double _neuron[]) { for(int i = 0; i < N_NEURONS; i++) { neuron[i] = _neuron[i]; } } void setBiasNeuron(double _biasNeuron) { biasNeuron = _biasNeuron; } void setBiasOutput(double _biasOutput) { biasOutput = _biasOutput; } // METODOS void manipulateAxons(double _axonsIn[][N_NEURONS], double _axonsOut[][N_OUTPUTS]) // Forneca os arrays de axons In e Out que quiser que a NN use { // Funcao inutil, so usa dois sets. Era pra testes mesmo setAxonsIn(_axonsIn); setAxonsOut(_axonsOut); } void populateAxons() { srand( (unsigned)time(NULL) ); for(int i = 0; i < N_INPUTS; i++) { for(int j = 0; j < N_NEURONS; j++) { // Randomizamos nossos Axons e dividimos eles para termos um axon decimal, que eh limitado pelos MIN_AXON e MAX_AXON axons.axonsIn[i][j] = ( ((double) rand() / (double) RAND_MAX) * (MAX_AXON - MIN_AXON) ) + MIN_AXON ; // E limitamos as casas decimais. Se quiser 3 casas decimais, use 1.000 no ESCOPO_DECIMAL_AXON, e assim vai //axons.axonsIn[i][j] = round( axons.axonsIn[i][j] * ESCOPO_DECIMAL_AXON) / ESCOPO_DECIMAL_AXON; } } for(int i = 0; i < N_NEURONS; i++) { for(int j = 0; j < N_OUTPUTS; j++) { // Randomizamos nossos Axons e dividimos eles para termos um axon decimal, que eh limitado pelos MIN_AXON e MAX_AXON axons.axonsOut[i][j] = ( ((double) rand() / (double) RAND_MAX) * (MAX_AXON - MIN_AXON) ) + MIN_AXON ; // E limitamos as casas decimais. Se quiser 3 casas decimais, use 1.000 no ESCOPO_DECIMAL_AXON, e assim vai //axons.axonsOut[i][j] = round( axons.axonsOut[i][j] * ESCOPO_DECIMAL_AXON) / ESCOPO_DECIMAL_AXON; } } } double sigmoid(double x) // Funcao sigmoid foi usada para o caminho do feedforward, conforme visto no video { return 1 / (1 + exp(-x)); } double dSigmoid(double x) { return x * (1 - x); } void activatingFunction(double source[], int size) // Funcao de ativacao para ativar qualquer vetor de double que receber, usando sigmoid { printf("\n"); for(int i = 0; i < size; i++) { printf("SIGMOID: Source[%d] era %f... ", i, source[i]); source[i] = sigmoid(source[i]); printf("depois da sigmoid ficou %f\n\n", source[i]); } } void feedForward() // O processo de feedForward, populando os neuronios e os outputs com os calculos vistos { // Calculo do valor dos neuronios conforme visto aos 11:05 de https://www.youtube.com/watch?v=d8U7ygZ48Sc printf("\n\n\tFF DE NEURONIOS\n"); for(int i = 0; i < N_NEURONS; i++) { for(int j = 0; j < N_INPUTS; j++) { printf("\nNEURON[%d]: Adicionando [ input[%d] * axons.axonsIn[%d][%d] >> %f * %f ] = %f, totalizando... ", i, j, j, i, input[j], axons.axonsIn[j][i], input[j]*axons.axonsIn[j][i]); neuron[i] += input[j] * axons.axonsIn[j][i]; printf("%f\n", neuron[i]); } neuron[i] += biasNeuron; printf("\nCom bias final de %f, totalizando %f (neuron[%d])\n\n", biasNeuron, neuron[i], i); } // Para os neuronios na situacao com 2 inputs e 2 neurons, 4 axonsIn, temos que... // neuron[0] = input[0] * axons.axonsIn[0][0] + input[1] * axons.axonsIn[1][0] // neuron[1] = input[0] * axons.axonsIn[0][1] + input[1] * axons.axonsIn[1][1] activatingFunction(neuron, N_NEURONS); // Calculo do valor dos neuronios conforme visto aos 13:58 de https://www.youtube.com/watch?v=d8U7ygZ48Sc printf("\n\n\tFF DE OUTPUTS\n"); for(int i = 0; i < N_OUTPUTS; i++) // A cada neuronio, faca... { for(int j = 0; j < N_NEURONS; j++) // A cada output, faca { printf("\nOUTPUT[%d]: Adicionando [ neuron[%d] * axons.axonsOut[%d][%d] >> %f * %f ] = %f, totalizando... ", i, j, j, i, neuron[j], axons.axonsOut[j][i], neuron[j]*axons.axonsOut[j][i]); output[i] += neuron[j] * axons.axonsOut[j][i]; printf("%f\n", output[i]); } output[i] += biasOutput; printf("\nCom bias final de %f, totalizando %f (output[%d])\n\n", biasOutput, output[i], i); } // Para os outputs na situacao com 2 neurons e 2 outputs, 4 axonsOut, temos que... // output[0] = neuron[0] * axons.axonsOut[0][0] + neuron[1] * axons.axonsOut[1][0] // output[1] = neuron[0] * axons.axonsOut[0][1] + neuron[1] * axons.axonsOut[1][1] activatingFunction(output, N_OUTPUTS); } void printExample() // Exemplo de caso de uso bobinho { double _inputs[] = {1, 2}; double _biasNeuron = 0; double _biasOutput = 0; RedeNeural n(_inputs, _biasNeuron, _biasOutput); n.feedForward(); printf("\n\n\tCASO DE TESTE INPUT [1,2] BIAS TODOS 0\n\n"); for(int i = 0; i < N_INPUTS; i++) printf("Input[%d]: %f\n", i, n.getInput()[i]); printf("----\n"); for(int i = 0; i < N_INPUTS; i++) for(int j = 0; j < N_NEURONS; j++) printf("AxonIn[%d][%d]: %f\n", i, j, n.getAxons().axonsIn[i][j]); printf("----\n"); for(int i = 0; i < N_NEURONS; i++) printf("Neuron[%d]: %f\n", i, n.getNeuron()[i]); printf("----\n"); printf("Bias Neuronio (adicionado no neuronio antes da sigmoid): %f\n", n.getBiasNeuron()); printf("----\n"); for(int i = 0; i < N_NEURONS; i++) for(int j = 0; j < N_OUTPUTS; j++) printf("AxonOut[%d][%d]: %f\n", i, j, n.getAxons().axonsOut[i][j]); printf("----\n"); for(int i = 0; i < N_OUTPUTS; i++) printf("Output[%d]: %f\n", i, n.getOutput()[i]); printf("----\n"); printf("Bias Output (adicionado no output antes da sigmoid): %f\n", n.getBiasOutput()); printf("----\n"); } }; // Um exemplo de main que o dev faria int main() { double _inputs[] = {6,7}; double _biasNeuron = 0; double _biasOutput = 0; RedeNeural n(_inputs, _biasNeuron, _biasOutput); n.feedForward(); printf("\n\n\tRESUMINDO\n\n"); for(int i = 0; i < N_INPUTS; i++) printf("Input[%d]: %f\n", i, n.getInput()[i]); printf("----\n"); for(int i = 0; i < N_INPUTS; i++) for(int j = 0; j < N_NEURONS; j++) printf("AxonIn[%d][%d]: %f\n", i, j, n.getAxons().axonsIn[i][j]); printf("----\n"); for(int i = 0; i < N_NEURONS; i++) printf("Neuron[%d]: %f\n", i, n.getNeuron()[i]); printf("----\n"); printf("Bias Neuronio (adicionado no neuronio antes da sigmoid): %f\n", n.getBiasNeuron()); printf("----\n"); for(int i = 0; i < N_NEURONS; i++) for(int j = 0; j < N_OUTPUTS; j++) printf("AxonOut[%d][%d]: %f\n", i, j, n.getAxons().axonsOut[i][j]); printf("----\n"); for(int i = 0; i < N_OUTPUTS; i++) printf("Output[%d]: %f\n", i, n.getOutput()[i]); printf("----\n"); printf("Bias Output (adicionado no output antes da sigmoid): %f\n", n.getBiasOutput()); printf("----\n"); return 0; }
19d72c74dbe8d100131501c1b60622c3fdb2923b
[ "Markdown", "C++" ]
2
Markdown
l-a-motta/neural-network-base
9ca3587ea989acc39f10ff8de024593ba8afd21c
a384f0da59ae3416884b4db24ae50fa3479f6f91
refs/heads/master
<repo_name>akwa770/upload-excel<file_sep>/src/components/import-modal.js import React, {Component} from 'react'; // import {connect} from 'react-redux'; import {Modal, Button} from 'react-bootstrap'; import {UploadField} from './upload-field'; // import {readExcelFile} from './read-xlsx-files'; export class ImportModal extends Component { state = { showModal: false, } render() { return ( <div className="container"> <Button onClick={()=> this.setState({ showModal: true })}>Upload BOM</Button> <div className="modal-container" style={{ height: 200 }}> <Modal {...this.props} bsSize="large" aria-labelledby="contained-modal-title-sm" show={this.state.showModal} onHide={() => this.setState({ showModal: false }) } > <Modal.Header closeButton> <Modal.Title id="contained-modal-title">Upload BOM</Modal.Title> </Modal.Header> <Modal.Body> <UploadField /> </Modal.Body> <Modal.Footer> <Button onClick={() => this.setState({ showModal: false }) }>Close</Button> </Modal.Footer> </Modal> </div> </div> ); } } // export const ComponentsPage = connect(null, mapDispatchToProps)(ComponentsPageComp); <file_sep>/src/components/read-xlsx-files.js import XLSX from 'xlsx'; export const readExcelFile = file => { return new Promise(resolve => { const reader = new FileReader(); reader.onload = e => { const workbook = XLSX.read(new Uint8Array(e.target.result), {type: 'array'}); const sheets = workbook.SheetNames.map(sheetName => { return {sheetName, content: XLSX.utils.sheet_to_json(workbook.Sheets[sheetName])}; }); resolve(sheets.reduce((all, sheet) => ({ ...all, [sheet.sheetName]: sheet.content }), {})); }; reader.readAsArrayBuffer(file); }); };
2d3e84187557c6d27efe9935b532d9a5610d760c
[ "JavaScript" ]
2
JavaScript
akwa770/upload-excel
e9f7ddccaf39a637225b73762f0b83f3f56bac5c
53b13d5bfe5aec0fd50ebef9812285d243fe610d
refs/heads/master
<repo_name>dgrtwo/dplython<file_sep>/dplython/__init__.py from .data import diamonds from .dplython import * diamonds = DplyFrame(diamonds) <file_sep>/README.md # Dplython: Dplyr for Python [![Build Status](https://travis-ci.org/dodger487/dplython.svg?branch=master)](https://travis-ci.org/dodger487/dplython) Welcome to Dplython: Dplyr for Python. Dplyr is a library for the language R designed to make data analysis fast and easy. The philosophy of Dplyr is to constrain data manipulation to a few simple functions that correspond to the most common tasks. This maps thinking closer to the process of writing code, helping you move closer to analyze data at the "speed of thought". The goal of this project is to implement the functionality of the R package Dplyr on top of Python's pandas. * Dplyr: [Click here](https://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html) * Pandas: [Click here](http://pandas.pydata.org/pandas-docs/stable/10min.html) This is version 0.0.4. It's experimental and subject to change. ## Installation To install, use pip: ``` pip install dplython ``` To get the latest development version, you can clone this repo or use the command: ``` pip install git+https://github.com/dodger487/dplython.git ``` ## Example usage ```python import pandas from dplython import (DplyFrame, X, diamonds, select, sift, sample_n, sample_frac, head, arrange, mutate, group_by, summarize, DelayFunction) # The example `diamonds` DataFrame is included in this package, but you can # cast a DataFrame to a DplyFrame in this simple way: # diamonds = DplyFrame(pandas.read_csv('./diamonds.csv')) # Select specific columns of the DataFrame using select, and # get the first few using head diamonds >> select(X.carat, X.cut, X.price) >> head(5) """ Out: carat cut price 0 0.23 Ideal 326 1 0.21 Premium 326 2 0.23 Good 327 3 0.29 Premium 334 4 0.31 Good 335 """ # Filter out rows using sift diamonds >> sift(X.carat > 4) >> select(X.carat, X.cut, X.depth, X.price) """ Out: carat cut depth price 25998 4.01 Premium 61.0 15223 25999 4.01 Premium 62.5 15223 27130 4.13 Fair 64.8 17329 27415 5.01 Fair 65.5 18018 27630 4.50 Fair 65.8 18531 """ # Sample with sample_n or sample_frac, sort with arrange (diamonds >> sample_n(10) >> arrange(X.carat) >> select(X.carat, X.cut, X.depth, X.price)) """ Out: carat cut depth price 37277 0.23 Very Good 61.5 484 17728 0.30 Very Good 58.8 614 33255 0.32 Ideal 61.1 825 38911 0.33 Ideal 61.6 1052 31491 0.34 Premium 60.3 765 37227 0.40 Premium 61.9 975 2578 0.81 Premium 60.8 3213 15888 1.01 Fair 64.6 6353 26594 1.74 Ideal 62.9 16316 25727 2.38 Premium 62.4 14648 """ # You can: # add columns with mutate (referencing other columns!) # group rows into dplyr-style groups with group_by # collapse rows into single rows using sumarize (diamonds >> mutate(carat_bin=X.carat.round()) >> group_by(X.cut, X.carat_bin) >> summarize(avg_price=X.price.mean())) """ Out: avg_price carat_bin cut 0 863.908535 0 Ideal 1 4213.864948 1 Ideal 2 12838.984078 2 Ideal ... 27 13466.823529 3 Fair 28 15842.666667 4 Fair 29 18018.000000 5 Fair """ # If you have column names that don't work as attributes, you can use an # alternate "get item" notation with X. diamonds["column w/ spaces"] = range(len(diamonds)) diamonds >> select(X["column w/ spaces"]) >> head() """ Out: column w/ spaces 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 """ # It's possible to pass the entire dataframe using X._ diamonds >> sample_n(6) >> select(X.carat, X.price) >> X._.T """ Out: 18966 19729 9445 49951 3087 33128 carat 1.16 1.52 0.9 0.3 0.74 0.31 price 7803.00 8299.00 4593.0 540.0 3315.00 816.00 """ # To pass the DataFrame or columns into functions, apply @DelayFunction @DelayFunction def PairwiseGreater(series1, series2): index = series1.index newSeries = pandas.Series([max(s1, s2) for s1, s2 in zip(series1, series2)]) newSeries.index = index return newSeries diamonds >> PairwiseGreater(X.x, X.y) # Passing entire dataframe and plotting with ggplot from ggplot import ggplot, aes, geom_point, facet_wrap ggplot = DelayFunction(ggplot) # Simple installation (diamonds >> ggplot(aes(x="carat", y="price", color="cut"), data=X._) + geom_point() + facet_wrap("color")) ``` ![Ggplot example 1](http://dodger487.github.com/figs/dplython/ggplot_img1.png) ```python (diamonds >> sift((X.clarity == "I1") | (X.clarity == "IF")) >> ggplot(aes(x="carat", y="price", color="color"), X._) + geom_point() + facet_wrap("clarity")) ``` ![Ggplot example 2](http://dodger487.github.com/figs/dplython/ggplot_img2.png) ```python # Matplotlib works as well! import pylab as pl pl.scatter = DelayFunction(pl.scatter) diamonds >> sample_frac(0.1) >> pl.scatter(X.carat, X.price) ``` ![MPL example 2](http://dodger487.github.com/figs/dplython/plt_img1.png) This is very new and I'm matching changes. Let me know if you'd like to see a feature or think there's a better way I can do something. ## Other approaches * [pandas-ply](http://pythonhosted.org/pandas-ply/) Development of dplython began before I knew pandas-ply existed. After I found it, I chose "X" as the manager to be consistent. Pandas-ply is a great approach and worth taking a look. The main contrasts between the two are that: * dplython uses dplyr-style groups, as opposed to the SQL-style groups of pandas and pandas-ply * dplython maps a little more directly onto dplyr, for example having mutate instead of an expanded select. * Use of operators to connect operations instead of method-chaining <file_sep>/dplython/test.py # <NAME> # 2016-02-21 """Testing for python dplyr.""" import math import unittest import os import pandas as pd from dplython import * def load_diamonds(): root = os.path.abspath(os.path.dirname(__file__)) path = os.path.join(root, 'data', 'diamonds.csv') return DplyFrame(pd.read_csv(path)) class TestLaterStrMethod(unittest.TestCase): def test_column_name(self): foo = X.foo self.assertEqual(foo._str, 'data["foo"]') def test_str(self): foo = X.foo self.assertEqual(str(foo), 'data["foo"]') def test_later_with_method(self): foo = X.foo.mean self.assertEqual(str(foo), 'data["foo"].mean') def test_later_with_method_call(self): foo = X.foo.mean() self.assertEqual(str(foo), 'data["foo"].mean()') foo = X.foo.mean(1) self.assertEqual(str(foo), 'data["foo"].mean(1)') foo = X.foo.mean(1, 2) self.assertEqual(str(foo), 'data["foo"].mean(1, 2)') foo = X.foo.mean(numeric_only=True) self.assertEqual(str(foo), 'data["foo"].mean(numeric_only=True)') # The order is different here, because the original order of the kwargs is # lost when kwargs are passed to the function. To insure consistent results, # the kwargs are sorted alphabetically by key. To help deal with this # issue, support PEP 0468: https://www.python.org/dev/peps/pep-0468/ foo = X.foo.mean(numeric_only=True, level="bar") self.assertEqual(str(foo), 'data["foo"].mean(level="bar", ' 'numeric_only=True)') foo = X.foo.mean(1, numeric_only=True, level="bar") self.assertEqual(str(foo), 'data["foo"].mean(1, level="bar", ' 'numeric_only=True)') foo = X.foo.mean(1, 2, numeric_only=True, level="bar") self.assertEqual(str(foo), 'data["foo"].mean(1, 2, level="bar", ' 'numeric_only=True)') foo = X.foo.mean(X.y.mean()) self.assertEqual(str(foo), 'data["foo"].mean(' 'data["y"].mean())') def test_later_with_delayed_function(self): mylen = DelayFunction(len) foo = mylen(X.foo) self.assertEqual(str(foo), 'len(data["foo"])') def test_more_later_ops_str(self): mylen = DelayFunction(len) foo = mylen(X.foo) + X.y.mean() // X.y.median(X.z) self.assertEqual(str(foo), 'len(data["foo"]).__add__(' 'data["y"].mean().__floordiv__(' 'data["y"].median(data["z"])))') class TestMutates(unittest.TestCase): diamonds = load_diamonds() def test_equality(self): self.assertTrue(self.diamonds.equals(self.diamonds)) def test_addconst(self): diamonds_pd = self.diamonds.copy() diamonds_pd["ones"] = 1 diamonds_dp = self.diamonds >> mutate(ones=1) self.assertTrue(diamonds_pd.equals(diamonds_dp)) def test_newcolumn(self): diamonds_pd = self.diamonds.copy() newcol = range(len(diamonds_pd)) diamonds_pd["newcol"] = newcol diamonds_dp = self.diamonds >> mutate(newcol=newcol) self.assertTrue(diamonds_pd.equals(diamonds_dp)) def test_dupcolumn(self): diamonds_pd = self.diamonds.copy() diamonds_pd["copy_x"] = diamonds_pd["x"] diamonds_dp = self.diamonds >> mutate(copy_x=X.x) self.assertTrue(diamonds_pd.equals(diamonds_dp)) def test_editcolumn(self): diamonds_pd = self.diamonds.copy() diamonds_pd["copy_x"] = 2 * diamonds_pd["x"] diamonds_dp = self.diamonds >> mutate(copy_x=X.x * 2) self.assertTrue(diamonds_pd.equals(diamonds_dp)) def test_multi(self): diamonds_pd = self.diamonds.copy() diamonds_pd["copy_x"] = diamonds_pd["x"] diamonds_pd["copy_y"] = diamonds_pd["y"] diamonds_dp = self.diamonds >> mutate(copy_x=X.x, copy_y=X.y) # Keep the new DplyFrame columns in the original order diamonds_dp = diamonds_dp[diamonds_pd.columns] self.assertTrue(diamonds_pd.equals(diamonds_dp)) def test_combine(self): diamonds_pd = self.diamonds.copy() diamonds_pd["copy_x"] = diamonds_pd["x"] + diamonds_pd["y"] diamonds_dp = self.diamonds >> mutate(copy_x=X.x + X.y) self.assertTrue(diamonds_pd.equals(diamonds_dp)) def test_orignalUnaffect(self): diamonds_pd = self.diamonds.copy() diamonds_dp = self.diamonds >> mutate(copy_x=X.x, copy_y=X.y) self.assertTrue(diamonds_pd.equals(self.diamonds)) def testCallMethodOnLater(self): diamonds_pd = self.diamonds.copy() diamonds_pd["avgX"] = diamonds_pd.x.mean() diamonds_dp = self.diamonds >> mutate(avgX=X.x.mean()) self.assertTrue(diamonds_pd.equals(diamonds_dp)) def testCallMethodOnCombinedLater(self): diamonds_pd = self.diamonds.copy() diamonds_pd["avgX"] = (diamonds_pd.x + diamonds_pd.y).mean() diamonds_dp = self.diamonds >> mutate(avgX=(X.x + X.y).mean()) self.assertTrue(diamonds_pd.equals(diamonds_dp)) def testReverseThings(self): self.diamonds >> mutate(foo=1 - X.carat, bar=7 // X.x, baz=4 % X.y.round()) def testMethodFirst(self): diamonds_dp = self.diamonds >> mutate(avgDiff=X.x.mean() - X.x) diamonds_pd = self.diamonds.copy() diamonds_pd["avgDiff"] = diamonds_pd["x"].mean() - diamonds_pd["x"] self.assertTrue(diamonds_dp["avgDiff"].equals(diamonds_pd["avgDiff"])) def testArgsNotKwargs(self): diamonds_dp = mutate(self.diamonds, X.carat+1) diamonds_pd = self.diamonds.copy() diamonds_pd['data["carat"].__add__(1)'] = diamonds_pd.carat + 1 self.assertTrue(diamonds_pd.equals(diamonds_dp)) def testOrderedKwargs(self): # without __order, is alphabetical diamonds_dp = mutate(self.diamonds, carat2=X.carat+2, carat1=X.carat+1, carat3=X.carat+3) col_names = diamonds_dp.columns.values self.assertEqual(col_names[-3], "carat1") self.assertEqual(col_names[-2], "carat2") self.assertEqual(col_names[-1], "carat3") diamonds_dp = mutate(self.diamonds, carat2=X.carat+2, carat1=X.carat2-1, carat3=X.carat1+2, __order=["carat2", "carat1", "carat3"]) col_names = diamonds_dp.columns.values self.assertEqual(col_names[-3], "carat2") self.assertEqual(col_names[-2], "carat1") self.assertEqual(col_names[-1], "carat3") self.assertTrue((diamonds_dp.carat + 3 == diamonds_dp.carat3).all()) def testOrderedKwargsError(self): self.assertRaisesRegexp(ValueError, "carat2", mutate, self.diamonds, carat1 = X.carat + 1, __order = ["carat1", "carat2"]) self.assertRaisesRegexp(ValueError, "carat3", mutate, self.diamonds, carat1 = X.carat + 1, carat3 = X.carat + 3, __order = ["carat1"]) class TestSelects(unittest.TestCase): diamonds = load_diamonds() def testOne(self): diamonds_pd = self.diamonds.copy() diamonds_pd = diamonds_pd[["cut"]] diamonds_dp = self.diamonds >> select(X.cut) self.assertTrue(diamonds_pd.equals(diamonds_dp)) def testTwo(self): diamonds_pd = self.diamonds.copy() diamonds_pd = diamonds_pd[["cut", "carat"]] diamonds_dp = self.diamonds >> select(X.cut, X.carat) self.assertTrue(diamonds_pd.equals(diamonds_dp)) def testChangeOrder(self): diamonds_pd = self.diamonds.copy() diamonds_pd = diamonds_pd[["carat", "cut"]] diamonds_dp = self.diamonds >> select(X.carat, X.cut) self.assertTrue(diamonds_pd.equals(diamonds_dp)) class TestFilters(unittest.TestCase): diamonds = load_diamonds() def testFilterEasy(self): diamonds_pd = self.diamonds.copy() diamonds_pd = diamonds_pd[diamonds_pd.cut == "Ideal"] diamonds_dp = self.diamonds >> sift(X.cut == "Ideal") self.assertTrue(diamonds_pd.equals(diamonds_dp)) def testFilterNone(self): diamonds_pd = self.diamonds.copy() diamonds_dp = self.diamonds >> sift() self.assertTrue(diamonds_pd.equals(diamonds_dp)) def testFilterWithMultipleArgs(self): diamonds_pd = self.diamonds.copy() diamonds_pd = diamonds_pd[(diamonds_pd.cut == "Ideal") & (diamonds_pd.carat > 3)] diamonds_dp = self.diamonds >> sift(X.cut == "Ideal", X.carat > 3) self.assertTrue(diamonds_pd.equals(diamonds_dp)) def testFilterWithAnd(self): diamonds_pd = self.diamonds.copy() diamonds_pd = diamonds_pd[(diamonds_pd.cut == "Ideal") & (diamonds_pd.carat > 3)] diamonds_dp = self.diamonds >> sift((X.cut == "Ideal") & (X.carat > 3)) self.assertTrue(diamonds_pd.equals(diamonds_dp)) def testFilterWithOr(self): diamonds_pd = self.diamonds.copy() diamonds_pd = diamonds_pd[(diamonds_pd.cut == "Ideal") | (diamonds_pd.carat > 3)] diamonds_dp = self.diamonds >> sift((X.cut == "Ideal") | (X.carat > 3)) self.assertTrue(diamonds_pd.equals(diamonds_dp)) def testFilterMultipleLaterColumns(self): diamonds_pd = self.diamonds.copy() diamonds_pd = diamonds_pd[diamonds_pd.carat > diamonds_pd.x - diamonds_pd.y] diamonds_dp = self.diamonds >> sift(X.carat > X.x - X.y) self.assertTrue(diamonds_pd.equals(diamonds_dp)) # TODO: Add more multiphase tests class TestGroupBy(unittest.TestCase): diamonds = load_diamonds() def testGroupbyDoesntDie(self): self.diamonds >> group_by(X.color) def testUngroupDoesntDie(self): self.diamonds >> ungroup() def testGroupbyAndUngroupDoesntDie(self): self.diamonds >> group_by(X.color) >> ungroup() def testOneGroupby(self): diamonds_pd = self.diamonds.copy() carats_pd = set(diamonds_pd[diamonds_pd.carat > 3.5].groupby('color').mean()["carat"]) diamonds_dp = (self.diamonds >> sift(X.carat > 3.5) >> group_by(X.color) >> mutate(caratMean=X.carat.mean())) carats_dp = set(diamonds_dp["caratMean"].values) self.assertEqual(carats_pd, carats_dp) def testTwoGroupby(self): diamonds_pd = self.diamonds.copy() carats_pd = set(diamonds_pd[diamonds_pd.carat > 3.5].groupby(["color", "cut"]).mean()["carat"]) diamonds_dp = (self.diamonds >> sift(X.carat > 3.5) >> group_by(X.color, X.cut) >> mutate(caratMean=X.carat.mean())) carats_dp = set(diamonds_dp["caratMean"].values) self.assertEqual(carats_pd, carats_dp) def testGroupThenFilterDoesntDie(self): diamonds_dp = (self.diamonds >> group_by(X.color) >> sift(X.carat > 3.5) >> mutate(caratMean=X.carat.mean())) def testGroupThenFilterDoesntDie2(self): diamonds_dp = (self.diamonds >> group_by(X.color) >> sift(X.carat > 3.5, X.color != "I") >> mutate(caratMean=X.carat.mean())) def testGroupUngroupSummarize(self): num_rows = (self.diamonds >> group_by(X.cut) >> ungroup() >> summarize(total=X.price.sum()) >> nrow()) self.assertEqual(num_rows, 1) sum_price = self.diamonds.sum()["price"] sum_price_dp = (self.diamonds >> group_by(X.cut) >> ungroup() >> summarize(total=X.price.sum()) >> X.total[0]) self.assertEqual(sum_price, sum_price_dp) def testDfRemainsGroupedAfterOperation(self): diamonds_dp = (self.diamonds >> group_by(X.color) >> mutate(caratMean1=X.carat.mean()) >> mutate(caratMean2=X.carat.mean())) self.assertTrue(diamonds_dp["caratMean1"].equals(diamonds_dp["caratMean2"])) class TestArrange(unittest.TestCase): diamonds = load_diamonds() def testArrangeDoesntDie(self): self.diamonds >> arrange(X.cut) def testArrangeThenSelect(self): self.diamonds >> arrange(X.color) >> select(X.color) def testMultipleSort(self): self.diamonds >> arrange(X.color, X.cut) >> select(X.color) def testArrangeSorts(self): sortedColor_pd = self.diamonds.copy().sort_values("color")["color"] sortedColor_dp = (self.diamonds >> arrange(X.color))["color"] self.assertTrue(sortedColor_pd.equals(sortedColor_dp)) def testMultiArrangeSorts(self): sortedCarat_pd = self.diamonds.copy().sort_values(["color", "carat"])["carat"] sortedCarat_dp = (self.diamonds >> arrange(X.color, X.carat))["carat"] self.assertTrue(sortedCarat_pd.equals(sortedCarat_dp)) def testArrangeDescending(self): sortedCarat_pd = self.diamonds.copy().sort_values("carat", ascending=False) sortedCarat_dp = self.diamonds >> arrange(-X.carat) self.assertTrue((sortedCarat_pd.carat == sortedCarat_dp.carat).all()) def testArrangeByComputedLater(self): sortedDf = self.diamonds >> arrange((X.carat-3)**2) self.assertEqual((sortedDf.iloc[0].carat-3)**2, min((self.diamonds.carat-3)**2)) self.assertEqual((sortedDf.iloc[-1].carat-3)**2, max((self.diamonds.carat-3)**2)) class TestSample(unittest.TestCase): diamonds = load_diamonds() def testSamplesDontDie(self): self.diamonds >> sample_n(5) self.diamonds >> sample_frac(0.5) def testSamplesGetsRightNumber(self): shouldBe5 = self.diamonds >> sample_n(5) >> X._.__len__() self.assertEqual(shouldBe5, 5) frac = len(self.diamonds) * 0.1 shouldBeFrac = self.diamonds >> sample_frac(0.1) >> X._.__len__() self.assertEqual(shouldBeFrac, frac) def testSampleEqualsPandasSample(self): for i in [1, 10, 100, 1000]: shouldBeI = self.diamonds >> sample_n(i) >> X._.__len__() self.assertEqual(shouldBeI, i) for i in [.1, .01, .001]: shouldBeI = self.diamonds >> sample_frac(i) >> X._.__len__() self.assertEqual(shouldBeI, round(len(self.diamonds)*i)) def testSample0(self): shouldBe0 = self.diamonds >> sample_n(0) >> X._.__len__() self.assertEqual(shouldBe0, 0) shouldBeFrac = self.diamonds >> sample_frac(0) >> X._.__len__() self.assertEqual(shouldBeFrac, 0.) def testGroupedSample(self): num_groups = len(set(self.diamonds["cut"])) for i in [0, 1, 10, 100, 1000]: numRows = self.diamonds >> group_by(X.cut) >> sample_n(i) >> X._.__len__() self.assertEqual(numRows, i*num_groups) for i in [.1, .01, .001]: shouldBeI = self.diamonds >> group_by(X.cut) >> sample_frac(i) >> X._.__len__() out = sum([len(self.diamonds[self.diamonds.cut == c].sample(frac=i)) for c in set(self.diamonds.cut)]) # self.assertEqual(shouldBeI, math.floor(len(self.diamonds)*i)) self.assertEqual(shouldBeI, out) class TestSummarize(unittest.TestCase): diamonds = load_diamonds() def testSummarizeDoesntDie(self): self.diamonds >> summarize(sumX=X.x.sum()) def testSummarizeX(self): diamonds_pd = self.diamonds.copy() sumX_pd = diamonds_pd.sum()["x"] sumX_dp = (self.diamonds >> summarize(sumX=X.x.sum()))["sumX"][0] self.assertEqual(round(sumX_pd), round(sumX_dp)) def testSummarizeGroupedX(self): diamonds_pd = self.diamonds.copy() sumX_pd = diamonds_pd.groupby("cut").sum()["x"] val_pd = sumX_pd.values.copy() val_pd.sort() valX_dp = (self.diamonds >> group_by(X.cut) >> summarize(sumX=X.x.sum()) >> X._["sumX"]).values.copy() valX_dp.sort() for i, j in zip(val_pd, valX_dp): self.assertEqual(round(i), round(j)) class TestAlternateAttrGrab(unittest.TestCase): diamonds = load_diamonds() diamonds["o m g"] = range(len(diamonds)) diamonds["0"] = range(len(diamonds)) def testSelect(self): equality = self.diamonds[["o m g"]] == (self.diamonds >> select(X["o m g"])) self.assertTrue(equality.all()[0]) def testMutate(self): pd = self.diamonds[["0"]] * 2 dp = self.diamonds >> mutate(foo=X["0"]*2) >> select(X.foo) equality = pd["0"] == dp["foo"] self.assertTrue(equality.all()) class TestNrow(unittest.TestCase): diamonds = load_diamonds() def testSimpleNrow(self): diamonds_pd = self.diamonds.copy() self.assertEqual(len(diamonds_pd), self.diamonds >> nrow()) def testMultipleNrow(self): diamonds_pd = self.diamonds.copy() self.assertEqual(len(diamonds_pd), self.diamonds >> nrow()) self.assertEqual(len(diamonds_pd), self.diamonds >> nrow()) small_d = diamonds_pd[diamonds_pd.carat > 4] self.assertEqual( len(small_d), self.diamonds >> sift(X.carat > 4) >> nrow()) class TestFunctionForm(unittest.TestCase): diamonds = load_diamonds() def testsift(self): normal = self.diamonds >> sift(X.carat > 4) function = sift(self.diamonds, X.carat > 4) self.assertTrue(normal.equals(function)) normal = self.diamonds >> sift() function = sift(self.diamonds) self.assertTrue(normal.equals(function)) normal = self.diamonds >> sift(X.carat < 4, X.color == "D") function = sift(self.diamonds, X.carat < 4, X.color == "D") self.assertTrue(normal.equals(function)) normal = self.diamonds >> sift((X.carat < 4) | (X.color == "D"), X.carat >= 4) function = sift(self.diamonds, (X.carat < 4) | (X.color == "D"), X.carat >= 4) self.assertTrue(normal.equals(function)) def testSelect(self): normal = self.diamonds >> select(X.carat) function = select(self.diamonds, X.carat) self.assertTrue(normal.equals(function)) normal = self.diamonds >> select(X.cut, X.carat, X.carat) function = select(self.diamonds, X.cut, X.carat, X.carat) self.assertTrue(normal.equals(function)) def testMutate(self): normal = self.diamonds >> mutate(foo=X.carat) function = mutate(self.diamonds, foo=X.carat) self.assertTrue(normal.equals(function)) normal = self.diamonds >> mutate(a=X.cut, b=X.x/2, c=32) function = mutate(self.diamonds, a=X.cut, b=X.x/2, c=32) self.assertTrue(normal.equals(function)) def testGroupBy(self): normal = (self.diamonds >> sift(X.carat > 3.5) >> group_by(X.color) >> mutate(caratMean=X.carat.mean())) function = self.diamonds >> sift(X.carat > 3.5) function = group_by(function, X.color) function = function >> mutate(caratMean=X.carat.mean()) self.assertTrue(normal.equals(function)) def testGroupBy2(self): normal = (self.diamonds >> group_by(X.color, X.cut) >> mutate(caratMean=X.carat.mean())) function = group_by(self.diamonds, X.color, X.cut) function = function >> mutate(caratMean=X.carat.mean()) self.assertTrue(normal.equals(function)) def testUngroup(self): normal = (self.diamonds >> sift(X.carat > 3.5) >> group_by(X.color) >> ungroup()) function = (self.diamonds >> sift(X.carat > 3.5) >> group_by(X.color)) function = ungroup(function) self.assertTrue(normal.equals(function)) def testArrange(self): normal = self.diamonds >> arrange(X.color, X.carat) function = arrange(self.diamonds, X.color, X.carat) self.assertTrue(normal.equals(function)) normal = self.diamonds >> arrange(X.cut, X.carat, X.y) function = arrange(self.diamonds, X.cut, X.carat, X.y) self.assertTrue(normal.equals(function)) def testSummarize(self): normal = (self.diamonds >> summarize(sumX=X.x.sum())) function = summarize(self.diamonds, sumX=X.x.sum()) self.assertTrue(normal.equals(function)) def testSummarizeGroupedX(self): normal = self.diamonds >> group_by(X.cut) >> summarize(sumX=X.x.sum()) function = self.diamonds >> group_by(X.cut) function = summarize(function, sumX=X.x.sum()) self.assertTrue(normal.equals(function)) def testUtilities(self): normal = self.diamonds >> head() function = head(self.diamonds) self.assertTrue(normal.equals(function)) normal = self.diamonds >> sample_n(10) function = sample_n(self.diamonds, 10) self.assertEqual(len(normal), len(function)) normal = self.diamonds >> sample_frac(0.1) function = sample_frac(self.diamonds, 0.1) self.assertEqual(len(normal), len(function)) if __name__ == '__main__': unittest.main()<file_sep>/dplython/data/__init__.py import os import pandas as pd root = os.path.abspath(os.path.dirname(__file__)) diamonds = pd.read_csv(os.path.join(root, "diamonds.csv")) <file_sep>/dplython/dplython.py # <NAME> # 2016-02-17 """Dplyr-style operations on top of pandas DataFrame.""" import itertools import operator import sys import types import warnings warnings.simplefilter("once") import six from six.moves import range import numpy as np import pandas from pandas import DataFrame __version__ = "0.0.4" # TODOs: # add len to Later # * Descending and ascending for arrange # * diamonds >> select(-X.cut) # * Move special function Later code into Later object # * Add more tests # * Reflection thing in Later -- understand this better # * Should rename some things to be clearer. "df" isn't really a df in the # __radd__ code, for example # * lint # * Let users use strings instead of Laters in certain situations # e.g. select("cut", "carat") # * What about implementing Manager as a container as well? This would help # with situations where column names have spaces. X["type of horse"] # * Should I enforce that output is a dataframe? # For example, should df >> (lambda x: 7) be allowed? # * Pass args, kwargs into sample # Scratch # https://mtomassoli.wordpress.com/2012/03/18/currying-in-python/ # http://stackoverflow.com/questions/16372229/how-to-catch-any-method-called-on-an-object-in-python # Sort of define your own operators: http://code.activestate.com/recipes/384122/ # http://pandas.pydata.org/pandas-docs/stable/internals.html # I think it might be possible to override __rrshift__ and possibly leave # the pandas dataframe entirely alone. # http://www.rafekettler.com/magicmethods.html class Manager(object): """Object which helps create a delayed computational unit. Typically will be set as a global variable X. X.foo will refer to the "foo" column of the DataFrame in which it is later applied. Manager can be used in two ways: (1) attribute notation: X.foo (2) item notation: X["foo"] Attribute notation is preferred but item notation can be used in cases where column names contain characters on which python will choke, such as spaces, periods, and so forth. """ def __getattr__(self, attr): return Later(attr) def __getitem__(self, key): return Later(key) X = Manager() reversible_operators = [ ["__add__", "__radd__"], ["__sub__", "__rsub__"], ["__mul__", "__rmul__"], ["__floordiv__", "__rfloordiv__"], ["__div__", "__rdiv__"], ["__truediv__", "__rtruediv__"], ["__mod__", "__rmod__"], ["__divmod__", "__rdivmod__"], ["__pow__", "__rpow__"], ["__lshift__", "__rlshift__"], ["__rshift__", "__rrshift__"], ["__and__", "__rand__"], ["__or__", "__ror__"], ["__xor__", "__rxor__"], ] normal_operators = [ "__abs__", "__concat__", "__contains__", "__delitem__", "__delslice__", "__eq__", "__file__", "__ge__", "__getitem__", "__getslice__", "__gt__", "__iadd__", "__iand__", "__iconcat__", "__idiv__", "__ifloordiv__", "__ilshift__", "__imod__", "__imul__", "__index__", "__inv__", "__invert__", "__ior__", "__ipow__", "__irepeat__", "__irshift__", "__isub__", "__itruediv__", "__ixor__", "__le__", "__lt__", "__ne__", "__neg__", "__not__", "__package__", "__pos__", "__repeat__", "__setitem__", "__setslice__", "__radd__", "__rsub__", "__rmul__", "__rfloordiv__", "__rdiv__", "__rtruediv__", "__rmod__", "__rdivmod__", "__rpow__", "__rlshift__", "__rand__", "__ror__", "__rxor__", # "__rrshift__", ] def create_reversible_func(func_name): def reversible_func(self, arg): self._UpdateStrAttr(func_name) self._UpdateStrCallArgs([arg], {}) def use_operator(df): if isinstance(arg, Later): altered_arg = arg.applyFcns(self.origDf) else: altered_arg = arg return getattr(operator, func_name)(df, altered_arg) self.todo.append(use_operator) return self return reversible_func def instrument_operator_hooks(cls): def add_hook(name): def op_hook(self, *args, **kwargs): self._UpdateStrAttr(name) self._UpdateStrCallArgs(args, kwargs) if len(args) > 0 and type(args[0]) == Later: self.todo.append(lambda df: getattr(df, name)(args[0].applyFcns(self.origDf))) else: self.todo.append(lambda df: getattr(df, name)(*args, **kwargs)) return self try: setattr(cls, name, op_hook) except (AttributeError, TypeError): pass # skip __name__ and __doc__ and the like for hook_name in normal_operators: add_hook(hook_name) for func_name, rfunc_name in reversible_operators: setattr(cls, func_name, create_reversible_func(func_name)) return cls def _addQuotes(item): return '"' + item + '"' if isinstance(item, str) else item @instrument_operator_hooks class Later(object): """Object which represents a computation to be carried out later. The Later object allows us to save computation that cannot currently be executed. It will later receive a DataFrame as an input, and all computation will be carried out upon this DataFrame object. Thus, we can refer to columns of the DataFrame as inputs to functions without having the DataFrame currently available: In : diamonds >> sift(X.carat > 4) >> select(X.carat, X.price) Out: carat price 25998 4.01 15223 25999 4.01 15223 27130 4.13 17329 27415 5.01 18018 27630 4.50 18531 The special Later name, "_" will refer to the entire DataFrame. For example, In: diamonds >> sample_n(6) >> select(X.carat, X.price) >> X._.T Out: 18966 19729 9445 49951 3087 33128 carat 1.16 1.52 0.9 0.3 0.74 0.31 price 7803.00 8299.00 4593.0 540.0 3315.00 816.00 """ def __init__(self, name): self.name = name if name == "_": self.todo = [lambda df: df] else: self.todo = [lambda df: df[self.name]] self._str = 'data["{0}"]'.format(name) def applyFcns(self, df): self.origDf = df stmt = df for func in self.todo: stmt = func(stmt) return stmt def __str__(self): return "{0}".format(self._str) def __repr__(self): return "{0}".format(self._str) def __getattr__(self, attr): self.todo.append(lambda df: getattr(df, attr)) self._UpdateStrAttr(attr) return self def __call__(self, *args, **kwargs): self.todo.append(lambda foo: foo.__call__(*args, **kwargs)) self._UpdateStrCallArgs(args, kwargs) return self def __rrshift__(self, df): otherDf = DplyFrame(df.copy(deep=True)) return self.applyFcns(otherDf) def _UpdateStrAttr(self, attr): self._str += ".{0}".format(attr) def _UpdateStrCallArgs(self, args, kwargs): # We sort here because keyword arguments get arbitrary ordering inside the # function call. Support PEP 0468 to help fix this issue! # https://www.python.org/dev/peps/pep-0468/ kwargs_strs = sorted(["{0}={1}".format(k, _addQuotes(v)) for k, v in kwargs.items()]) input_strs = list(map(str, args)) + kwargs_strs input_str = ", ".join(input_strs) self._str += "({0})".format(input_str) def CreateLaterFunction(fcn, *args, **kwargs): laterFcn = Later(fcn.__name__) laterFcn.fcn = fcn laterFcn.args = args laterFcn.kwargs = kwargs def apply_function(self, df): self.origDf = df args = [a.applyFcns(self.origDf) if type(a) == Later else a for a in self.args] kwargs = {k: v.applyFcns(self.origDf) if type(v) == Later else v for k, v in six.iteritems(self.kwargs)} return self.fcn(*args, **kwargs) laterFcn.todo = [lambda df: apply_function(laterFcn, df)] laterFcn._str = '{0}'.format(fcn.__name__) laterFcn._UpdateStrCallArgs(args, kwargs) return laterFcn def DelayFunction(fcn): def DelayedFcnCall(*args, **kwargs): # Check to see if any args or kw are Later. If not, return normal fcn. if (len([a for a in args if isinstance(a, Later)]) == 0 and len([v for k, v in kwargs.items() if isinstance(v, Later)]) == 0): return fcn(*args, **kwargs) else: return CreateLaterFunction(fcn, *args, **kwargs) return DelayedFcnCall class DplyFrame(DataFrame): """A subclass of the pandas DataFrame with methods for function piping. This class implements two main features on top of the pandas DataFrame. First, dplyr-style groups. In contrast to SQL-style or pandas style groups, rows are not collapsed and replaced with a function value. Second, >> is overloaded on the DataFrame so that functions on the right-hand side of this equation are called on the object. For example, $ df >> select(X.carat) will call a function (created from the "select" call) on df. Currently, these inputs need to be one of the following: * A "Later" * The "ungroup" function call * A function that returns a pandas DataFrame or DplyFrame. """ _metadata = ["_grouped_on", "_grouped_self"] def __init__(self, *args, **kwargs): super(DplyFrame, self).__init__(*args, **kwargs) self._grouped_on = None self._current_group = None self._grouped_self = None if len(args) == 1 and isinstance(args[0], DplyFrame): self._copy_attrs(args[0]) def _copy_attrs(self, df): for attr in self._metadata: self.__dict__[attr] = getattr(df, attr, None) @property def _constructor(self): return DplyFrame def group_self(self, names): self._grouped_on = names self._grouped_self = self.groupby(names) def ungroup(self): self._grouped_on = None self._grouped_self = None def apply_on_groups(self, delayedFcn): outDf = self._grouped_self.apply(delayedFcn) for grouped_name in outDf.index.names[:-1]: if grouped_name in outDf: outDf.reset_index(level=0, drop=True, inplace=True) else: outDf.reset_index(level=0, inplace=True) outDf.group_self(self._grouped_on) return outDf def __rshift__(self, delayedFcn): if type(delayedFcn) == Later: return delayedFcn.applyFcns(self) if delayedFcn == UngroupDF: otherDf = DplyFrame(self.copy(deep=True)) return delayedFcn(otherDf) if self._grouped_self: outDf = self.apply_on_groups(delayedFcn) return outDf else: otherDf = DplyFrame(self.copy(deep=True)) return delayedFcn(otherDf) def ApplyToDataframe(fcn): def DplyrFcn(*args, **kwargs): data_arg = None if len(args) > 0 and isinstance(args[0], pandas.DataFrame): # data_arg = args[0].copy(deep=True) data_arg = args[0] args = args[1:] fcn_to_apply = fcn(*args, **kwargs) if data_arg is None: return fcn_to_apply else: return data_arg >> fcn_to_apply return DplyrFcn @ApplyToDataframe def sift(*args): """Filters rows of the data that meet input criteria. Giving multiple arguments to sift is equivalent to a logical "and". In: df >> sift(X.carat > 4, X.cut == "Premium") # Out: # carat cut color clarity depth table price x ... # 4.01 Premium I I1 61.0 61 15223 10.14 # 4.01 Premium J I1 62.5 62 15223 10.02 As in pandas, use bitwise logical operators like |, &: In: df >> sift((X.carat > 4) | (X.cut == "Ideal")) >> head(2) # Out: carat cut color clarity depth ... # 0.23 Ideal E SI2 61.5 # 0.23 Ideal J VS1 62.8 """ def f(df): # TODO: This function is a candidate for improvement! final_filter = pandas.Series([True for t in range(len(df))]) final_filter.index = df.index for arg in args: stmt = arg.applyFcns(df) final_filter = final_filter & stmt if final_filter.dtype != bool: raise Exception("Inputs to filter must be boolean") return df[final_filter] return f def dfilter(*args, **kwargs): warnings.warn("'dfilter' is deprecated. Please use 'sift' instead.", DeprecationWarning) return sift(*args, **kwargs) @ApplyToDataframe def select(*args): """Select specific columns from DataFrame. Output will be DplyFrame type. Order of columns will be the same as input into select. In : diamonds >> select(X.color, X.carat) >> head(3) Out: color carat 0 E 0.23 1 E 0.21 2 E 0.23 """ names = [column.name for column in args] return lambda df: df[[column.name for column in args]] @ApplyToDataframe def mutate(*args, **kwargs): """Adds a column to the DataFrame. This can use existing columns of the DataFrame as input. In : (diamonds >> mutate(carat_bin=X.carat.round()) >> group_by(X.cut, X.carat_bin) >> summarize(avg_price=X.price.mean())) Out: avg_price carat_bin cut 0 863.908535 0 Ideal 1 4213.864948 1 Ideal 2 12838.984078 2 Ideal ... 27 13466.823529 3 Fair 28 15842.666667 4 Fair 29 18018.000000 5 Fair """ def addColumns(df): for arg in args: if isinstance(arg, Later): df[str(arg)] = arg.applyFcns(df) else: df[str(arg)] = arg ordered = kwargs.pop("__order", None) if ordered is not None: s1 = set(ordered) s2 = set(kwargs) missing_order = s1 - s2 if (len(missing_order) > 0): raise ValueError(", ".join(missing_order) + " in __order not found in keyword arguments") missing_kwargs = s2 - s1 if (len(missing_kwargs) > 0): raise ValueError(", ".join(missing_kwargs) + " not found in __order") kv = [(key, kwargs[key]) for key in ordered] else: kv = sorted(kwargs.items(), key = lambda e: e[0]) for key, val in kv: if type(val) == Later: df[key] = val.applyFcns(df) else: df[key] = val return df return addColumns @ApplyToDataframe def group_by(*args): def GroupDF(df): df.group_self([arg.name for arg in args]) return df return GroupDF @ApplyToDataframe def summarize(**kwargs): def CreateSummarizedDf(df): input_dict = {k: val.applyFcns(df) for k, val in six.iteritems(kwargs)} if len(input_dict) == 0: return DplyFrame({}, index=index) if hasattr(df, "_current_group") and df._current_group: input_dict.update(df._current_group) index = [0] return DplyFrame(input_dict, index=index) return CreateSummarizedDf def UngroupDF(df): # df._grouped_on = None # df._group_dict = None df.ungroup() return df @ApplyToDataframe def ungroup(): return UngroupDF @ApplyToDataframe def arrange(*args): """Sort DataFrame by the input column arguments. In : diamonds >> sample_n(5) >> arrange(X.price) >> select(X.depth, X.price) Out: depth price 28547 61.0 675 35132 59.1 889 42526 61.3 1323 3468 61.6 3392 23829 62.0 11903 """ names = [column.name for column in args] def f(df): sortby_df = df >> mutate(*args) index = sortby_df.sort_values([str(arg) for arg in args]).index return df.loc[index] return f @ApplyToDataframe def head(*args, **kwargs): """Returns first n rows""" return lambda df: df.head(*args, **kwargs) @ApplyToDataframe def sample_n(n): """Randomly sample n rows from the DataFrame""" return lambda df: DplyFrame(df.sample(n)) @ApplyToDataframe def sample_frac(frac): """Randomly sample `frac` fraction of the DataFrame""" return lambda df: DplyFrame(df.sample(frac=frac)) @ApplyToDataframe def sample(*args, **kwargs): """Convenience method that calls into pandas DataFrame's sample method""" return lambda df: df.sample(*args, **kwargs) @ApplyToDataframe def nrow(): return lambda df: len(df) @DelayFunction def PairwiseGreater(series1, series2): index = series1.index newSeries = pandas.Series([max(s1, s2) for s1, s2 in zip(series1, series2)]) newSeries.index = index return newSeries <file_sep>/setup.py """Install Dplython.""" from setuptools import setup, find_packages setup( name="dplython", version="0.0.4", description="Dplyr-style operations on top of pandas DataFrame.", url="https://github.com/dodger487/dplython", download_url="https://github.com/dodger487/dplython/tarball/0.0.4", packages=find_packages(), license="MIT", keywords="pandas data dplyr", package_data={"dplython": ["data/diamonds.csv"]}, package_dir={"dplython": "dplython"}, install_requires=["numpy", "pandas", "six"], author="<NAME>", author_email="<EMAIL>", maintainer="<NAME>", maintainer_email="<EMAIL>", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Environment :: Web Environment", "Operating System :: OS Independent", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Scientific/Engineering", ] )
2ba63900d0d20ccf7c70f41295aab744f5ebcb4e
[ "Markdown", "Python" ]
6
Python
dgrtwo/dplython
9c36e9e3b9d6a457e8b974c30f6725abde947f1c
65153022882e33f8fa5dc4503155ce2a6d64e0cd
refs/heads/master
<repo_name>sshtel/ahcounter_android<file_sep>/ahcounter/app/src/main/java/sshtel/ahcounter/MainActivity.java package sshtel.ahcounter; import android.app.Fragment; import android.content.Context; import android.os.AsyncTask; import android.os.Build; import android.speech.RecognizerIntent; import android.speech.SpeechRecognizer; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.os.Message; import android.os.Handler; import android.text.format.DateFormat; import android.text.format.Time; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import sshtel.audio_scope.Q; import sshtel.audio_scope.ScopeSurfaceView; public class MainActivity extends ActionBarActivity { private SpeechMassgeHandler speechMessageHandler_ = null; /////////// AUDIO RECORDER ////////////// private ASR myASR; private AudioRecorder myAudioRecorder; /////////// WIDGETS ///////////// LinearLayout mainVertical_linearLayout_; LinearLayout scope_linearLayout_; EditText statementEditText; Button recordButton; private Q audio_buffer_scope_ = new Q(20000); // Record_Thread read the AR and puts it in here. ScopeSurfaceView scope_screen_view_; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setStartButton(); setAnalyzeButton(); mainVertical_linearLayout_ = (LinearLayout)findViewById(R.id.main_vertical_linear_layout); scope_linearLayout_ = (LinearLayout)findViewById(R.id.scope_LinearLayout); scope_screen_view_ = new ScopeSurfaceView(this, audio_buffer_scope_); scope_linearLayout_.addView(scope_screen_view_, 0); //doPollingSpeechResults(); statementEditText = (EditText)findViewById(R.id.currentStatement_editText); recordButton = (Button)findViewById(R.id.start_button); //start ASR (Recognition Listener) speechMessageHandler_ = new SpeechMassgeHandler(); myASR = new ASR(speechMessageHandler_); myASR.create(getApplicationContext()); Context ctx = getApplicationContext(); myAudioRecorder = new AudioRecorder("testAudio", scope_screen_view_, audio_buffer_scope_); } private void startScopeView(){ scope_screen_view_ = new ScopeSurfaceView(this, audio_buffer_scope_); ////////setContentView(scope_screen_view); } private void stopScopeView(){ scope_screen_view_.surfaceDestroyed(scope_screen_view_.getHolder()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } // Default values for the language model and maximum number of recognition results // They are shown in the GUI when the app starts, and they are used when the user selection is not valid private final static int DEFAULT_NUMBER_RESULTS = 10; private final static String DEFAULT_LANG_MODEL = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM; // Attributes private int numberRecoResults = DEFAULT_NUMBER_RESULTS; private String languageModel = DEFAULT_LANG_MODEL; private static final String LOGTAG = "ASRDEMO"; private void setStartButton(){ //Gain reference to speak button Button speak = (Button) findViewById(R.id.start_button); //Set up click listener speak.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Speech recognition does not currently work on simulated devices, //it the user is attempting to run the app in a simulated device //they will get a Toast if ("generic".equals(Build.BRAND.toLowerCase())) { Toast toast = Toast.makeText(getApplicationContext(), "ASR is not supported on virtual devices", Toast.LENGTH_SHORT); toast.show(); Log.d(LOGTAG, "ASR attempt on virtual device"); } else { if (myAudioRecorder.isRecording()) { //myASR.stopListening(); //myAudioRecorder.stopRecording(); myAudioRecorder.stop(); recordButton.setText(getResources().getString(R.string.start_button)); } else { try { //myASR.listen(languageModel, numberRecoResults); //Start listening myAudioRecorder.startRecording(getCurrentTimeString()); recordButton.setText(getResources().getString(R.string.stop_button)); } catch (Exception e) { Toast toast = Toast.makeText(getApplicationContext(), "ASR could not be started: invalid params", Toast.LENGTH_SHORT); toast.show(); Log.e(LOGTAG, "ASR could not be started: invalid params"); } } } } }); } ////// ANALYZER ////// AudioTransform audioTransform_; private void setAnalyzeButton(){ //Gain reference to speak button Button speak = (Button) findViewById(R.id.anylze_button); //Set up click listener speak.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { audioTransform_ = new AudioTransform(); audioTransform_.load("/sdcard/ahcounter/ah.wav"); // audioTransform_.analyzeWithFFT(); audioTransform_.anaylzeWithJtransforms(); } }); } String getCurrentTimeString(){ Time today = new Time(Time.getCurrentTimezone()); today.setToNow(); String temp = today.format("yyyy-mm-dd"); String str = Integer.toString(today.year) + "-"; str += Integer.toString(today.month+1) + "-"; str += Integer.toString(today.monthDay) + "_"; str += Integer.toString(today.hour) + "-"; str += Integer.toString(today.minute) + "-"; str += Integer.toString(today.second); return str; } ArrayList<String> resultArray = new ArrayList<>(); // Handler for speech result class SpeechMassgeHandler extends Handler { public static final int SPEECH_ARRIVED = 0; public static final int THREAD_STOP_MESSAGE = 1; public static final int SPEECH_ERROR_TO_CONTINUE = 2; public static final int SPEECH_ERROR_TIMEOUT = 3; public static final int SPEECH_ERROR_NO_MATCH = 4; public static final int SPEECH_ERROR_AUDIO = 5; public static final int SPEECH_ERROR_EXTRA = 6; @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case SPEECH_ARRIVED: statementEditText.append(myASR.speechResult.get(0)); statementEditText.append("\n"); myASR.speechResult.clear(); try { myASR.listen(languageModel, numberRecoResults); } catch (Exception e) { Toast toast = Toast.makeText(getApplicationContext(), "ASR could not be started: invalid params", Toast.LENGTH_SHORT); toast.show(); Log.e(LOGTAG, "ASR could not be started: invalid params"); } //statementEditText.append(resultArray.get(0)); //resultArray.clear(); break; case THREAD_STOP_MESSAGE: break; case SPEECH_ERROR_TIMEOUT: statementEditText.append("{TIME OUT}\n"); myASR.speechResult.clear(); try { Thread.sleep(500); myASR.listen(languageModel, numberRecoResults); } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { Toast toast = Toast.makeText(getApplicationContext(), "ASR could not be started: invalid params", Toast.LENGTH_SHORT); toast.show(); Log.e(LOGTAG, "ASR could not be started: invalid params"); } break; case SPEECH_ERROR_NO_MATCH: statementEditText.append("{NO MATCH}\n"); myASR.speechResult.clear(); try { Thread.sleep(500); myASR.listen(languageModel, numberRecoResults); } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { Toast toast = Toast.makeText(getApplicationContext(), "ASR could not be started: invalid params", Toast.LENGTH_SHORT); toast.show(); Log.e(LOGTAG, "ASR could not be started: invalid params"); } break; case SPEECH_ERROR_AUDIO: statementEditText.append("{AUDIO!!}\n"); myASR.speechResult.clear(); try { Thread.sleep(500); myASR.listen(languageModel, numberRecoResults); } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { Toast toast = Toast.makeText(getApplicationContext(), "ASR could not be started: invalid params", Toast.LENGTH_SHORT); toast.show(); Log.e(LOGTAG, "ASR could not be started: invalid params"); } break; case SPEECH_ERROR_EXTRA: if(msg.arg1 != SpeechRecognizer.ERROR_RECOGNIZER_BUSY) { statementEditText.append((String) (msg.obj)); statementEditText.append("\n"); myASR.speechResult.clear(); } try { Thread.sleep(500); myASR.listen(languageModel, numberRecoResults); } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { Toast toast = Toast.makeText(getApplicationContext(), "ASR could not be started: invalid params", Toast.LENGTH_SHORT); toast.show(); Log.e(LOGTAG, "ASR could not be started: invalid params"); } break; default: break; } } }; } <file_sep>/ahcounter/app/src/main/java/sshtel/ahcounter/ASR.java package sshtel.ahcounter; /** * Created by sshtel on 2015-06-28. */ import java.util.ArrayList; import java.util.List; import java.util.Queue; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.speech.RecognitionListener; import android.speech.RecognizerIntent; import android.speech.SpeechRecognizer; import android.util.Log; /** * * Abstract class for automatic speech recognition * * Encapsulates the management of the speech recognition engine. * * All the methods necessary to set up and run the speech recognizer are implemented in this class. * Only the methods for processing the ASR output are abstract, so that each app using the ASRLib can * specify a different behavior. * * @author <NAME> * @author <NAME> * @version 2.4, 11/24/13 * */ public class ASR implements RecognitionListener{ private SpeechRecognizer myASR; Context ctx; private static final String LIB_LOGTAG = "ASRLIB"; private final static int DEFAULT_NUMBER_RESULTS = 10; private final static String DEFAULT_LANG_MODEL = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM; private String myLanguageMode = DEFAULT_LANG_MODEL; private int myMaxResults = DEFAULT_NUMBER_RESULTS; Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); Handler speechMessageHandler_; ASR(Handler msgHandler){ this.speechMessageHandler_ = msgHandler; setSpeechStatus(SPEECH_STATUS.STANDBY); } public void create(Context ctx) { this.ctx = ctx; PackageManager packManager = ctx.getPackageManager(); // find out whether speech recognition is supported List<ResolveInfo> intActivities = packManager.queryIntentActivities( new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); if (intActivities.size() != 0) { myASR = SpeechRecognizer.createSpeechRecognizer(ctx); myASR.setRecognitionListener(this); } else myASR = null; // Specify the calling package to identify the application intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, ctx.getPackageName()); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recording..."); //Caution: be careful not to use: getClass().getPackage().getName()); // Specify language model intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, myLanguageMode); // Specify how many results to receive. Results listed in order of confidence intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, myMaxResults); } /** * Starts speech recognition * @param languageModel Type of language model used (see Chapter 3 in the book for further details) * @param maxResults Maximum number of recognition results */ public void listen(String languageModel, int maxResults) throws Exception{ setSpeechStatus(SPEECH_STATUS.LISTENING); myLanguageMode = languageModel; myMaxResults = maxResults; if (myASR == null) { myASR = SpeechRecognizer.createSpeechRecognizer(this.ctx); myASR.setRecognitionListener(this); } if((languageModel.equals(RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) || languageModel.equals(RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH)) && (maxResults>=0)) { // Start recognition myASR.startListening(intent); } else { Log.e(LIB_LOGTAG, "Invalid params to listen method"); throw new Exception("Invalid params to listen method"); //If the input parameters are not valid, it throws an exception } } /** * Stops listening to the user */ public void stopListening(){ setSpeechStatus(SPEECH_STATUS.STANDBY); myASR.stopListening(); } /******************************************************************************************************** * This class implements the {@link android.speech.RecognitionListener} interface, * thus it implements its methods. However not all of them are interesting to us: * ****************************************************************************************************** */ /* * (non-Javadoc) * @see android.speech.RecognitionListener#onResults(android.os.Bundle) */ public ArrayList<String> speechResult = new ArrayList<>(); @Override public void onResults(Bundle results) { Log.d(LIB_LOGTAG, "ASR results provided"); if(results!=null){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { //Checks the API level because the confidence scores are supported only from API level 14: //http://developer.android.com/reference/android/speech/SpeechRecognizer.html#CONFIDENCE_SCORES //Processes the recognition results and their confidences processAsrResults (results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION), results.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES)); // Attention: It is not RecognizerIntent.EXTRA_RESULTS, that is for intents (see the ASRWithIntent app) } else { processAsrResults (results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION), null); } } else { processAsrError(SpeechRecognizer.ERROR_NO_MATCH); } /* if(speechStatus == SPEECH_STATUS.LISTENING){ try { listen(myLanguageMode, myMaxResults); } catch(Exception e){ } } */ } /* * (non-Javadoc) * @see android.speech.RecognitionListener#onReadyForSpeech(android.os.Bundle) */ @Override public void onReadyForSpeech(Bundle arg0) { Log.i(LIB_LOGTAG, "Ready for speech"); processAsrReadyForSpeech(); } /* * (non-Javadoc) * @see android.speech.RecognitionListener#onError(int) */ @Override public void onError(int errorCode) { processAsrError(errorCode); } /* * (non-Javadoc) * @see android.speech.RecognitionListener#onBeginningOfSpeech() */ @Override public void onBeginningOfSpeech() { setSpeechStatus(SPEECH_STATUS.LISTENING); } /* * (non-Javadoc) * @see android.speech.RecognitionListener#onBufferReceived(byte[]) */ @Override public void onBufferReceived(byte[] buffer) { } /* * (non-Javadoc) * @see android.speech.RecognitionListener#onBeginningOfSpeech() */ @Override public void onEndOfSpeech() {} /* * (non-Javadoc) * @see android.speech.RecognitionListener#onEvent(int, android.os.Bundle) */ @Override public void onEvent(int arg0, Bundle arg1) {} /* * (non-Javadoc) * @see android.speech.RecognitionListener#onPartialResults(android.os.Bundle) */ @Override public void onPartialResults(Bundle arg0) {} /* * (non-Javadoc) * @see android.speech.RecognitionListener#onRmsChanged(float) */ @Override public void onRmsChanged(float arg0) { } // extends ASR public enum SPEECH_STATUS { STANDBY, LISTENING, }; private SPEECH_STATUS speechStatus; private void setSpeechStatus(SPEECH_STATUS status) { speechStatus = status; } public SPEECH_STATUS getSpeechStatus() { return speechStatus; } public void processAsrResults(ArrayList<String> nBestList, float [] nBestConfidences){ for(String line:nBestList){ speechResult.add(line); } if(speechStatus == SPEECH_STATUS.LISTENING) { Message msg = speechMessageHandler_.obtainMessage(); msg.what = MainActivity.SpeechMassgeHandler.SPEECH_ARRIVED; String hi = new String("Count Thared 가 동작하고 있습니다."); msg.obj = hi; speechMessageHandler_.sendMessage(msg); } } public void processAsrReadyForSpeech(){ } public void processAsrError(int errorCode){ String errorMessage; Message msg = speechMessageHandler_.obtainMessage(); switch (errorCode) { case SpeechRecognizer.ERROR_SPEECH_TIMEOUT: { msg.what = MainActivity.SpeechMassgeHandler.SPEECH_ERROR_TIMEOUT; errorMessage = "Time out Error"; } break; case SpeechRecognizer.ERROR_AUDIO:{ msg.what = MainActivity.SpeechMassgeHandler.SPEECH_ERROR_AUDIO; errorMessage = "Audio Error"; } break; case SpeechRecognizer.ERROR_NO_MATCH: { msg.what = MainActivity.SpeechMassgeHandler.SPEECH_ERROR_NO_MATCH; errorMessage = "No Match"; } break; case SpeechRecognizer.ERROR_CLIENT: msg.what = MainActivity.SpeechMassgeHandler.SPEECH_ERROR_EXTRA; errorMessage = "Client side error"; break; case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS: msg.what = MainActivity.SpeechMassgeHandler.SPEECH_ERROR_EXTRA; errorMessage = "Insufficient permissions" ; break; case SpeechRecognizer.ERROR_NETWORK: msg.what = MainActivity.SpeechMassgeHandler.SPEECH_ERROR_EXTRA; errorMessage = "Network related error" ; break; case SpeechRecognizer.ERROR_NETWORK_TIMEOUT: msg.what = MainActivity.SpeechMassgeHandler.SPEECH_ERROR_EXTRA; errorMessage = "Network operation timeout"; break; case SpeechRecognizer.ERROR_RECOGNIZER_BUSY: msg.what = MainActivity.SpeechMassgeHandler.SPEECH_ERROR_EXTRA; errorMessage = "RecognitionServiceBusy" ; break; case SpeechRecognizer.ERROR_SERVER: msg.what = MainActivity.SpeechMassgeHandler.SPEECH_ERROR_EXTRA; errorMessage = "Server sends error status"; break; default: msg.what = MainActivity.SpeechMassgeHandler.SPEECH_ERROR_EXTRA; errorMessage = "ASR error"; break; } msg.arg1 = errorCode; msg.obj = errorMessage; speechMessageHandler_.sendMessage(msg); } }
be8ca598cab0c113d031d148eb54a66d20d1de3b
[ "Java" ]
2
Java
sshtel/ahcounter_android
70947b42d6d38b330a355ac9559fa53d300d7d2b
bd3ccf7a1c1fe2cc56f402821cd0d4dcdbcab5ce
refs/heads/master
<file_sep>/** * The MIT License * Copyright © 2018 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.beethoven.dsl; import io.beethoven.partitur.partitur.*; import org.eclipse.emf.ecore.EObject; import org.springframework.http.HttpMethod; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static io.beethoven.dsl.Command.CommandFactory.createCommand; import static io.beethoven.dsl.ConditionFunctionFactory.createCondition; import static java.util.Objects.nonNull; /** * @author <NAME> */ public class PartiturWorkflowSerializer { public Workflow to(PartiturWorkflow partiturWorkflow) { Workflow workflow = new Workflow(); workflow.setName(partiturWorkflow.getName()); workflow.setTasks(convertToTasks(partiturWorkflow.getTasks(), partiturWorkflow.getName())); workflow.setHandlers(convertToHandlers(partiturWorkflow.getHandlers())); return workflow; } private Set<Task> convertToTasks(List<PartiturTask> partiturTasks, String workflowName) { Set<Task> tasks = new HashSet<>(); for (PartiturTask partiturTask : partiturTasks) { String taskName = partiturTask.getName(); HttpMethod method = null; String url = null; List<Header> headers = null; List<Param> params = new ArrayList<>(); List<String> uriVariables = null; String body = null; EObject request = partiturTask.getPartiturHttpRequest(); if (request instanceof HttpGet) { method = HttpMethod.GET; HttpGet httpGet = (HttpGet) request; url = httpGet.getUrl(); uriVariables = convertToUriVariables(httpGet.getUriVariables()); headers = convertToHeaders(httpGet.getHeaders()); params = convertToQueryParams(httpGet.getParams()); } else if (request instanceof HttpPost) { method = HttpMethod.POST; HttpPost httpPost = (HttpPost) request; url = httpPost.getUrl(); uriVariables = convertToUriVariables(httpPost.getUriVariables()); headers = convertToHeaders(httpPost.getHeaders()); body = convertToBody(httpPost.getBody()); } else if (request instanceof HttpPut) { method = HttpMethod.PUT; HttpPut httpPut = (HttpPut) request; url = httpPut.getUrl(); uriVariables = convertToUriVariables(httpPut.getUriVariables()); headers = convertToHeaders(httpPut.getHeaders()); body = convertToBody(httpPut.getBody()); } else if (request instanceof HttpDelete) { method = HttpMethod.DELETE; HttpDelete httpDelete = (HttpDelete) request; url = httpDelete.getUrl(); uriVariables = convertToUriVariables(httpDelete.getUriVariables()); headers = convertToHeaders(httpDelete.getHeaders()); } HttpRequest httpRequest = new HttpRequest(); httpRequest.setMethod(method); httpRequest.setUrl(url); httpRequest.setUriVariables(uriVariables); httpRequest.setHeaders(headers); httpRequest.setParams(params); httpRequest.setBody(body); Task task = new Task(); task.setName(taskName); task.setHttpRequest(httpRequest); task.setWorkflowName(workflowName); tasks.add(task); } return tasks; } private String convertToBody(HttpBody body) { String result = ""; if (nonNull(body)) { result = body.getValue(); } return result; } private List<String> convertToUriVariables(UriVariables uriVariables) { List<String> variables = new ArrayList<>(); if (nonNull(uriVariables)) { variables.addAll(uriVariables.getValues()); } return variables; } private List<Param> convertToQueryParams(List<QueryParam> queryParams) { List<Param> params = new ArrayList<>(); for (QueryParam queryParam : queryParams) { Param param = new Param(); param.setName(queryParam.getName()); param.setValue(queryParam.getValue()); params.add(param); } return params; } private List<Header> convertToHeaders(List<HttpHeader> httpHeaders) { List<Header> headers = new ArrayList<>(); for (HttpHeader httpHeader : httpHeaders) { Header header = new Header(); header.setName(httpHeader.getName()); header.setValue(httpHeader.getValue()); headers.add(header); } return headers; } private Set<Handler> convertToHandlers(List<PartiturHandler> partiturHandlers) { Set<Handler> handlers = new HashSet<>(); for (PartiturHandler partiturHandler : partiturHandlers) { String eventName = partiturHandler.getEvent().getName(); Handler.EventType eventType = Handler.EventType.valueOf(eventName); Handler handler = new Handler(); handler.setName(partiturHandler.getName()); handler.setEventType(eventType); handler.setConditions(convertToConditions(partiturHandler.getConditions())); handler.setCommands(convertToCommands(partiturHandler.getCommands())); handlers.add(handler); } return handlers; } private List<Condition> convertToConditions(List<PartiturCondition> partiturConditions) { List<Condition> conditions = new ArrayList<>(); for (PartiturCondition partiturCondition : partiturConditions) { String function = partiturCondition.getConditionFunction().getName(); String arg = partiturCondition.getArg(); conditions.add(createCondition(function, arg)); } return conditions; } private List<Command> convertToCommands(List<PartiturCommand> partiturCommands) { List<Command> commands = new ArrayList<>(); for (PartiturCommand partiturCommand : partiturCommands) { String commandFunction = partiturCommand.getCommandFunction().getName(); String arg = partiturCommand.getArg(); commands.add(createCommand(commandFunction, arg)); } return commands; } } <file_sep>/** * The MIT License * Copyright © 2018 <NAME> * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.beethoven.service; import akka.actor.ActorSystem; import io.beethoven.dsl.*; import io.beethoven.engine.TaskInstance; import io.beethoven.engine.core.ActorPath; import io.beethoven.engine.core.DeciderActor; import io.beethoven.engine.core.ReporterActor; import io.beethoven.repository.ContextualInputRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.List; import java.util.UUID; import static akka.actor.ActorRef.noSender; import static io.beethoven.engine.core.ActorPath.*; import static io.beethoven.engine.core.ActorPath.DECIDER_ACTOR; import static org.springframework.web.reactive.function.BodyInserters.fromObject; /** * @author <NAME> */ @Service public class TaskExecutorService { @Autowired private ContextualInputRepository contextualInputRepository; @Autowired private WebClient.Builder webClientBuilder; @Autowired private ActorSystem actorSystem; public void execute(Task task, String workflowInstanceName) { TaskInstance taskInstance = buildTaskInstance(task, workflowInstanceName); // Build a http request WebClient.RequestHeadersSpec request = buildHttpRequest( task.getHttpRequest(), task.getWorkflowName(), workflowInstanceName); // Perform the request request.retrieve().bodyToFlux(String.class) .subscribe( response -> handleSuccessResponse( taskInstance, response), throwable -> handleFailureResponse( taskInstance, throwable)); notifyDeciderActor(taskInstance); notifyReporterActor(taskInstance); } private void handleSuccessResponse(TaskInstance taskInstance, String response) { taskInstance.setResponse(response); contextualInputRepository.saveLocalInput(taskInstance.getWorkflowInstanceName(), buildContextualInput(taskInstance)); sendEvent(new DeciderActor.TaskCompletedEvent( taskInstance.getWorkflowName(), taskInstance.getWorkflowInstanceName(), taskInstance.getTaskName())); sendEvent(new ReporterActor.ReportTaskCompletedEvent( taskInstance.getWorkflowName(), taskInstance.getWorkflowInstanceName(), taskInstance.getTaskName(), taskInstance.getTaskInstanceName(), response)); } private void handleFailureResponse(TaskInstance taskInstance, Throwable throwable) { taskInstance.setFailure(throwable); contextualInputRepository.saveLocalInput(taskInstance.getWorkflowInstanceName(), buildContextualInput(taskInstance)); sendEvent(new DeciderActor.TaskFailedEvent( taskInstance.getWorkflowName(), taskInstance.getWorkflowInstanceName(), taskInstance.getTaskName())); sendEvent(new ReporterActor.ReportTaskFailedEvent( taskInstance.getWorkflowName(), taskInstance.getWorkflowInstanceName(), taskInstance.getTaskName(), taskInstance.getTaskInstanceName(), throwable)); } private ContextualInput buildContextualInput(TaskInstance taskInstance) { String inputKey = "${" + taskInstance.getTaskName() + ".response}"; return new ContextualInput(inputKey, taskInstance.getResponse()); } private WebClient.RequestHeadersSpec buildHttpRequest(HttpRequest httpRequest, String workflowName, String workflowInstanceName) { WebClient.RequestHeadersSpec request = null; switch (httpRequest.getMethod()) { case GET: request = buildGetRequest(httpRequest, workflowName, workflowInstanceName); break; case POST: request = buildPostRequest(httpRequest, workflowName, workflowInstanceName); break; case PUT: request = buildPutRequest(httpRequest, workflowName, workflowInstanceName); break; case DELETE: request = buildDeleteRequest(httpRequest, workflowName, workflowInstanceName); break; } return request; } private WebClient.RequestHeadersSpec buildGetRequest(HttpRequest httpRequest, String workflowName, String workflowInstanceName) { List<String> uriVariables = buildUriVariables(httpRequest.getUriVariables(), workflowName, workflowInstanceName); WebClient.RequestHeadersSpec request = webClientBuilder.build().get() .uri(httpRequest.getUrl(), uriVariables); buildHeaders(request, httpRequest.getHeaders(), workflowName, workflowInstanceName); buildQueryParams(request, httpRequest.getParams(), workflowName, workflowInstanceName); return request; } private WebClient.RequestHeadersSpec buildPostRequest(HttpRequest httpRequest, String workflowName, String workflowInstanceName) { List<String> uriVariables = buildUriVariables(httpRequest.getUriVariables(), workflowName, workflowInstanceName); String body = buildBody(httpRequest.getBody(), workflowName, workflowInstanceName); WebClient.RequestHeadersSpec request = webClientBuilder.build().post() .uri(httpRequest.getUrl(), uriVariables) .body(BodyInserters.fromPublisher(Flux.just(body), String.class)); buildHeaders(request, httpRequest.getHeaders(), workflowName, workflowInstanceName); buildQueryParams(request, httpRequest.getParams(), workflowName, workflowInstanceName); return request; } private WebClient.RequestHeadersSpec buildPutRequest(HttpRequest httpRequest, String workflowName, String workflowInstanceName) { List<String> uriVariables = buildUriVariables(httpRequest.getUriVariables(), workflowName, workflowInstanceName); String body = buildBody(httpRequest.getBody(), workflowName, workflowInstanceName); WebClient.RequestHeadersSpec request = webClientBuilder.build().put() .uri(httpRequest.getUrl(), uriVariables) .body(fromObject(body)); buildHeaders(request, httpRequest.getHeaders(), workflowName, workflowInstanceName); buildQueryParams(request, httpRequest.getParams(), workflowName, workflowInstanceName); return request; } private WebClient.RequestHeadersSpec buildDeleteRequest(HttpRequest httpRequest, String workflowName, String workflowInstanceName) { List<String> uriVariables = buildUriVariables(httpRequest.getUriVariables(), workflowName, workflowInstanceName); WebClient.RequestHeadersSpec request = webClientBuilder.build().delete() .uri(httpRequest.getUrl(), uriVariables); buildHeaders(request, httpRequest.getHeaders(), workflowName, workflowInstanceName); buildQueryParams(request, httpRequest.getParams(), workflowName, workflowInstanceName); return request; } private String buildBody(String body, String workflowName, String workflowInstanceName) { return contextualInputRepository.findGlobalContextualInput(workflowName, body) .map(ContextualInput::getValue) .orElseGet( () -> contextualInputRepository.findLocalContextualInput(workflowInstanceName, body) .map(ContextualInput::getValue) .orElse(body)); } private List<String> buildUriVariables(List<String> uriVariables, String workflowName, String workflowInstanceName) { List<String> newVariables = new ArrayList<>(); for (String uriVariable : uriVariables) { contextualInputRepository.findGlobalContextualInput(workflowName, uriVariable) .ifPresent(contextualInput -> newVariables.add(contextualInput.getValue())); contextualInputRepository.findLocalContextualInput(workflowInstanceName, uriVariable) .ifPresent(contextualInput -> newVariables.add(contextualInput.getValue())); } return newVariables; } private void buildHeaders(WebClient.RequestHeadersSpec request, List<Header> headers, String workflowName, String workflowInstanceName) { for (Header header : headers) { request.header(header.getName(), header.getValue()); contextualInputRepository.findGlobalContextualInput(workflowName, header.getValue()) .ifPresent(contextualInput -> request.header(header.getName(), contextualInput.getValue())); contextualInputRepository.findLocalContextualInput(workflowInstanceName, header.getValue()) .ifPresent(contextualInput -> request.header(header.getName(), contextualInput.getValue())); } } private void buildQueryParams(WebClient.RequestHeadersSpec request, List<Param> params, String workflowName, String workflowInstanceName) { for (Param param : params) { request.attribute(param.getName(), param.getValue()); contextualInputRepository.findGlobalContextualInput(workflowName, param.getValue()) .ifPresent(contextualInput -> request.header(param.getName(), contextualInput.getValue())); contextualInputRepository.findLocalContextualInput(workflowInstanceName, param.getValue()) .ifPresent(contextualInput -> request.header(param.getName(), contextualInput.getValue())); } } private TaskInstance buildTaskInstance(Task task, String workflowInstanceName) { String taskInstanceName = UUID.randomUUID().toString(); TaskInstance taskInstance = new TaskInstance(); taskInstance.setWorkflowName(task.getWorkflowName()); taskInstance.setWorkflowInstanceName(workflowInstanceName); taskInstance.setTaskName(task.getName()); taskInstance.setTaskInstanceName(taskInstanceName); return taskInstance; } private void notifyDeciderActor(TaskInstance taskInstance) { sendEvent(new DeciderActor.TaskStartedEvent( taskInstance.getWorkflowName(), taskInstance.getWorkflowInstanceName(), taskInstance.getTaskName())); } private void notifyReporterActor(TaskInstance taskInstance) { sendEvent(new ReporterActor.ReportTaskStartedEvent( taskInstance.getWorkflowName(), taskInstance.getWorkflowInstanceName(), taskInstance.getTaskName(), taskInstance.getTaskInstanceName())); } private void sendEvent(DeciderActor.TaskEvent taskEvent) { actorSystem.actorSelection(DECIDER_ACTOR).tell(taskEvent, noSender()); } private void sendEvent(ReporterActor.ReportTaskEvent reportTaskEvent) { actorSystem.actorSelection(REPORT_ACTOR).tell(reportTaskEvent, noSender()); } } <file_sep>/** * The MIT License * Copyright © 2018 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.beethoven.config; import akka.actor.ActorSystem; import io.beethoven.engine.core.DeciderActor; import io.beethoven.engine.core.ReporterActor; import io.beethoven.engine.core.TaskActor; import io.beethoven.engine.core.WorkflowActor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import static io.beethoven.engine.core.ActorName.ACTOR_SYSTEM; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; /** * A configuration class to create Spring managed Actor Beans and the Actor System. * * @author <NAME> */ @Configuration public class AkkaConfiguration { @Autowired private ApplicationContext applicationContext; @Bean public ActorSystem actorSystem() { ActorSystem actorSystem = ActorSystem.create(ACTOR_SYSTEM); // Initialize the application context in the Akka Spring Extension SpringExtension.SpringExtProvider.get(actorSystem).initialize(applicationContext); return actorSystem; } @Bean @Scope(SCOPE_PROTOTYPE) public WorkflowActor workflowActor() { return new WorkflowActor(); } @Bean @Scope(SCOPE_PROTOTYPE) public DeciderActor deciderActor() { return new DeciderActor(); } @Bean @Scope(SCOPE_PROTOTYPE) public TaskActor taskActor() { return new TaskActor(); } @Bean @Scope(SCOPE_PROTOTYPE) public ReporterActor reporterActor() { return new ReporterActor(); } } <file_sep>/** * The MIT License * Copyright © 2018 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.beethoven.engine.core; import akka.actor.AbstractLoggingActor; import akka.japi.pf.ReceiveBuilder; import io.beethoven.engine.core.support.WorkflowInstanceActor; import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.concurrent.atomic.AtomicInteger; /** * @author <NAME> */ @Component(ActorName.WORKFLOW_ACTOR) @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class WorkflowActor extends AbstractLoggingActor { private final AtomicInteger count = new AtomicInteger(); @Override public Receive createReceive() { Receive receive = ReceiveBuilder.create() .match(ScheduleWorkflowCommand.class, this::onScheduleWorkflowCommand) .match(StartWorkflowCommand.class, this::onStartWorkflowCommand) .match(StopWorkflowCommand.class, this::onStopWorkflowCommand) .match(CancelWorkflowCommand.class, this::onCancelWorkflowCommand) .build(); return receive; } private void onScheduleWorkflowCommand(ScheduleWorkflowCommand scheduleWorkflowCommand) { log().debug("onScheduleWorkflowCommand: " + scheduleWorkflowCommand); String instanceName = generateInstanceName(scheduleWorkflowCommand.workflowName); getContext().actorOf(WorkflowInstanceActor.props(), instanceName); forwardCommand(new WorkflowInstanceActor.CreateWorkflowInstanceCommand(scheduleWorkflowCommand.workflowName, instanceName), instanceName); } private void onStartWorkflowCommand(StartWorkflowCommand startWorkflowCommand) { log().debug("onStartWorkflowCommand: " + startWorkflowCommand); forwardCommand(new WorkflowInstanceActor.CreateWorkflowInstanceCommand(startWorkflowCommand.workflowName, startWorkflowCommand.instanceName), startWorkflowCommand.instanceName); } private void onStopWorkflowCommand(StopWorkflowCommand stopWorkflowCommand) { log().debug("onStopWorkflowCommand: " + stopWorkflowCommand); forwardCommand(new WorkflowInstanceActor.StopWorkflowInstanceCommand(stopWorkflowCommand.workflowName, stopWorkflowCommand.instanceName), stopWorkflowCommand.instanceName); } private void onCancelWorkflowCommand(CancelWorkflowCommand cancelWorkflowCommand) { log().debug("onCancelWorkflowCommand: " + cancelWorkflowCommand); forwardCommand(new WorkflowInstanceActor.CancelWorkflowInstanceCommand(cancelWorkflowCommand.workflowName, cancelWorkflowCommand.instanceName), cancelWorkflowCommand.instanceName); } private void forwardCommand(WorkflowInstanceActor.WorkflowInstanceCommand command, String actorName) { getContext().findChild(actorName).ifPresent(child -> child.forward(command, getContext())); } private String generateInstanceName(String workflowName) { return workflowName + "-" + count.incrementAndGet(); } /******************************************************************************* * * Workflow Commands: SCHEDULE_WORKFLOW, START_WORKFLOW, * STOP_WORKFLOW, CANCEL_WORKFLOW * *******************************************************************************/ public interface WorkflowCommand { } @Data @AllArgsConstructor public static class ScheduleWorkflowCommand implements WorkflowCommand { private String workflowName; } @Data @AllArgsConstructor public static class StartWorkflowCommand implements WorkflowCommand { private String workflowName; private String instanceName; } @Data @AllArgsConstructor public static class StopWorkflowCommand implements WorkflowCommand { private String workflowName; private String instanceName; } @Data @AllArgsConstructor public static class CancelWorkflowCommand implements WorkflowCommand { private String workflowName; private String instanceName; } /*******************************************************************************/ } <file_sep>/** * The MIT License * Copyright © 2018 <NAME> * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.beethoven.engine.core; import akka.actor.AbstractLoggingActor; import akka.japi.pf.ReceiveBuilder; import io.beethoven.dsl.Workflow; import io.beethoven.engine.TaskInstance; import io.beethoven.engine.WorkflowInstance; import io.beethoven.repository.ContextualInputRepository; import io.beethoven.repository.WorkflowRepository; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; import lombok.NonNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static akka.actor.ActorRef.noSender; import static io.beethoven.engine.WorkflowInstance.WorkflowStatus; import static java.util.Objects.nonNull; /** * @author <NAME> */ @Component(ActorName.REPORTER_ACTOR) @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class ReporterActor extends AbstractLoggingActor { @Autowired private ContextualInputRepository contextualInputRepository; @Autowired private WorkflowRepository workflowRepository; private Map<String, WorkflowInstance> instances = new ConcurrentHashMap(); @Override public Receive createReceive() { Receive receive = ReceiveBuilder.create() .match(ReportWorkflowScheduledEvent.class, this::onReportWorkflowScheduledEvent) .match(ReportWorkflowStartedEvent.class, this::onReportWorkflowStartedEvent) .match(ReportWorkflowStoppedEvent.class, this::onReportWorkflowStoppedEvent) .match(ReportWorkflowCompletedEvent.class, this::onReportWorkflowCompletedEvent) .match(ReportWorkflowCanceledEvent.class, this::onReportWorkflowCanceledEvent) .match(ReportWorkflowFailedEvent.class, this::onReportWorkflowFailedEvent) .match(ReportTaskStartedEvent.class, this::onReportTaskStartedEvent) .match(ReportTaskTimeoutEvent.class, this::onReportTaskTimeoutEvent) .match(ReportTaskFailedEvent.class, this::onReportTaskFailedEvent) .match(ReportTaskCompletedEvent.class, this::onReportTaskCompletedEvent) .build(); return receive; } private void onReportWorkflowScheduledEvent(ReportWorkflowScheduledEvent reportWorkflowScheduledEvent) { log().debug("onReportWorkflowScheduledEvent: " + reportWorkflowScheduledEvent); Workflow workflow = workflowRepository.findByName(reportWorkflowScheduledEvent.getWorkflowName()); if (nonNull(workflow)) { WorkflowInstance workflowInstance = new WorkflowInstance(reportWorkflowScheduledEvent); workflowInstance.setStatus(WorkflowStatus.SCHEDULED); workflowInstance.setCountTasks(workflow.getTasks().size()); instances.put(reportWorkflowScheduledEvent.getWorkflowInstanceName(), workflowInstance); } } private void onReportWorkflowStartedEvent(ReportWorkflowStartedEvent reportWorkflowStartedEvent) { log().debug("onReportWorkflowStartedEvent: " + reportWorkflowStartedEvent); WorkflowInstance workflowInstance = instances.get(reportWorkflowStartedEvent.getWorkflowInstanceName()); if (nonNull(workflowInstance)) { workflowInstance.setStatus(WorkflowStatus.RUNNING); workflowInstance.setStartTime(LocalDateTime.now()); } } private void onReportWorkflowStoppedEvent(ReportWorkflowStoppedEvent reportWorkflowStoppedEvent) { log().debug("onReportWorkflowStoppedEvent: " + reportWorkflowStoppedEvent); WorkflowInstance workflowInstance = instances.get(reportWorkflowStoppedEvent.getWorkflowInstanceName()); if (nonNull(workflowInstance)) { workflowInstance.setEndTime(LocalDateTime.now()); report(reportWorkflowStoppedEvent); } } private void onReportWorkflowCompletedEvent(ReportWorkflowCompletedEvent reportWorkflowCompletedEvent) { log().debug("onReportWorkflowCompletedEvent: " + reportWorkflowCompletedEvent); WorkflowInstance workflowInstance = instances.get(reportWorkflowCompletedEvent.getWorkflowInstanceName()); if (nonNull(workflowInstance)) { workflowInstance.setEndTime(LocalDateTime.now()); report(reportWorkflowCompletedEvent); } } private void onReportWorkflowCanceledEvent(ReportWorkflowCanceledEvent reportWorkflowCanceledEvent) { log().debug("onReportWorkflowCanceledEvent: " + reportWorkflowCanceledEvent); WorkflowInstance workflowInstance = instances.get(reportWorkflowCanceledEvent.getWorkflowInstanceName()); if (nonNull(workflowInstance)) { workflowInstance.setEndTime(LocalDateTime.now()); report(reportWorkflowCanceledEvent); } } private void onReportWorkflowFailedEvent(ReportWorkflowFailedEvent reportWorkflowFailedEvent) { log().debug("onReportWorkflowFailedEvent: " + reportWorkflowFailedEvent); WorkflowInstance workflowInstance = instances.get(reportWorkflowFailedEvent.getWorkflowInstanceName()); if (nonNull(workflowInstance)) { workflowInstance.setEndTime(LocalDateTime.now()); report(reportWorkflowFailedEvent); } } private void onReportTaskStartedEvent(ReportTaskStartedEvent reportTaskStartedEvent) { log().debug("onReportTaskStartedEvent: " + reportTaskStartedEvent); WorkflowInstance workflowInstance = instances.get(reportTaskStartedEvent.getWorkflowInstanceName()); if (nonNull(workflowInstance)) { TaskInstance taskInstance = new TaskInstance(reportTaskStartedEvent); taskInstance.setStartTime(LocalDateTime.now()); workflowInstance.getTasks().put(taskInstance.getTaskInstanceName(), taskInstance); checkScheduledWorkflow(workflowInstance); } } private void onReportTaskCompletedEvent(ReportTaskCompletedEvent reportTaskCompletedEvent) { log().debug("onReportTaskCompletedEvent: " + reportTaskCompletedEvent); WorkflowInstance workflowInstance = instances.get(reportTaskCompletedEvent.getWorkflowInstanceName()); if (nonNull(workflowInstance)) { TaskInstance taskInstance = workflowInstance.getTasks().get(reportTaskCompletedEvent.getTaskInstanceName()); if (nonNull(taskInstance)) { taskInstance.setEndTime(LocalDateTime.now()); taskInstance.setResponse(reportTaskCompletedEvent.response); taskInstance.print(); } checkCompletedWorkflow(workflowInstance); } } private void onReportTaskTimeoutEvent(ReportTaskTimeoutEvent reportTaskTimeoutEvent) { log().debug("onReportTaskTimeoutEvent" + reportTaskTimeoutEvent); WorkflowInstance workflowInstance = instances.get(reportTaskTimeoutEvent.getWorkflowInstanceName()); if (nonNull(workflowInstance)) { TaskInstance taskInstance = workflowInstance.getTasks().get(reportTaskTimeoutEvent.getTaskInstanceName()); if (nonNull(taskInstance)) { taskInstance.setEndTime(LocalDateTime.now()); taskInstance.print(); } checkCompletedWorkflow(workflowInstance); } } private void onReportTaskFailedEvent(ReportTaskFailedEvent reportTaskFailedEvent) { log().debug("onReportTaskFailedEvent" + reportTaskFailedEvent); WorkflowInstance workflowInstance = instances.get(reportTaskFailedEvent.getWorkflowInstanceName()); if (nonNull(workflowInstance)) { TaskInstance taskInstance = workflowInstance.getTasks().get(reportTaskFailedEvent.getTaskInstanceName()); if (nonNull(taskInstance)) { taskInstance.setEndTime(LocalDateTime.now()); taskInstance.setFailure(reportTaskFailedEvent.failure); taskInstance.print(); } checkCompletedWorkflow(workflowInstance); } } private void report(ReportWorkflowEvent reportWorkflowEvent) { log().debug("ReportWorkflowEvent" + reportWorkflowEvent); WorkflowInstance workflowInstance = instances.get(reportWorkflowEvent.workflowInstanceName); if (nonNull(workflowInstance)) { workflowInstance.print(); clearWorkflowInstanceResources(workflowInstance); } } private void checkScheduledWorkflow(@NonNull WorkflowInstance workflowInstance) { if (workflowInstance.getStatus().equals(WorkflowStatus.SCHEDULED)) { self().tell(new ReportWorkflowStartedEvent( workflowInstance.getWorkflowName(), workflowInstance.getWorkflowInstanceName()), noSender()); } } private void checkCompletedWorkflow(@NonNull WorkflowInstance workflowInstance) { if (workflowInstance.isTerminated()) { self().tell(new ReportWorkflowCompletedEvent( workflowInstance.getWorkflowName(), workflowInstance.getWorkflowInstanceName()), noSender()); } } private void clearWorkflowInstanceResources(WorkflowInstance workflowInstance) { contextualInputRepository.deleteLocalContextualInput(workflowInstance.getWorkflowInstanceName()); instances.remove(workflowInstance.getWorkflowInstanceName()); } /** * ***************************************************************************** * <p/> * Workflow Events * <p/> * ***************************************************************************** */ @Data @AllArgsConstructor public static abstract class ReportWorkflowEvent { private String workflowName; private String workflowInstanceName; } public static class ReportWorkflowScheduledEvent extends ReportWorkflowEvent { public ReportWorkflowScheduledEvent(String workflowName, String instanceName) { super(workflowName, instanceName); } } public static class ReportWorkflowStartedEvent extends ReportWorkflowEvent { public ReportWorkflowStartedEvent(String workflowName, String instanceName) { super(workflowName, instanceName); } } public static class ReportWorkflowStoppedEvent extends ReportWorkflowEvent { public ReportWorkflowStoppedEvent(String workflowName, String instanceName) { super(workflowName, instanceName); } } public static class ReportWorkflowCompletedEvent extends ReportWorkflowEvent { public ReportWorkflowCompletedEvent(String workflowName, String instanceName) { super(workflowName, instanceName); } } public static class ReportWorkflowFailedEvent extends ReportWorkflowEvent { public ReportWorkflowFailedEvent(String workflowName, String instanceName) { super(workflowName, instanceName); } } public static class ReportWorkflowCanceledEvent extends ReportWorkflowEvent { public ReportWorkflowCanceledEvent(String workflowName, String instanceName) { super(workflowName, instanceName); } } /*******************************************************************************/ /** * ***************************************************************************** * <p/> * Task Events * <p/> * ***************************************************************************** */ @Data @AllArgsConstructor public static abstract class ReportTaskEvent { private String workflowName; private String workflowInstanceName; private String taskName; private String taskInstanceName; } public static class ReportTaskStartedEvent extends ReportTaskEvent { public ReportTaskStartedEvent(String workflowName, String workflowInstanceName, String taskName, String taskInstanceName) { super(workflowName, workflowInstanceName, taskName, taskInstanceName); } } public static class ReportTaskCompletedEvent extends ReportTaskEvent { @Getter private String response; public ReportTaskCompletedEvent(String workflowName, String workflowInstanceName, String taskName, String taskInstanceName, String response) { super(workflowName, workflowInstanceName, taskName, taskInstanceName); this.response = response; } } public static class ReportTaskTimeoutEvent extends ReportTaskEvent { public ReportTaskTimeoutEvent(String workflowName, String workflowInstanceName, String taskName, String taskInstanceName) { super(workflowName, workflowInstanceName, taskName, taskInstanceName); } } public static class ReportTaskFailedEvent extends ReportTaskEvent { @Getter private Throwable failure; public ReportTaskFailedEvent(String workflowName, String workflowInstanceName, String taskName, String taskInstanceName, Throwable failure) { super(workflowName, workflowInstanceName, taskName, taskInstanceName); this.failure = failure; } } /*******************************************************************************/ } <file_sep>/** * The MIT License * Copyright © 2018 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.beethoven.service; import akka.actor.ActorSystem; import io.beethoven.api.dto.BeethovenOperation; import io.beethoven.api.dto.BeethovenOperation.Operation; import io.beethoven.dsl.Workflow; import io.beethoven.engine.core.WorkflowActor.CancelWorkflowCommand; import io.beethoven.engine.core.WorkflowActor.ScheduleWorkflowCommand; import io.beethoven.engine.core.WorkflowActor.StartWorkflowCommand; import io.beethoven.engine.core.WorkflowActor.StopWorkflowCommand; import io.beethoven.repository.ContextualInputRepository; import io.beethoven.repository.WorkflowRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import static akka.actor.ActorRef.noSender; import static io.beethoven.engine.core.ActorPath.WORKFLOW_ACTOR; /** * @author <NAME> */ @Service public class WorkflowService { @Autowired private WorkflowRepository workflowRepository; @Autowired private ContextualInputRepository contextualInputRepository; @Autowired private ActorSystem actorSystem; public void execute(String workflowName, BeethovenOperation operation) { contextualInputRepository.saveGlobalInputs(workflowName, operation.getInputs()); switch (Operation.findById(operation.getOperation())) { case SCHEDULE: actorSystem.actorSelection(WORKFLOW_ACTOR) .tell(new ScheduleWorkflowCommand(workflowName), noSender()); break; case START: System.out.println(); actorSystem.actorSelection(WORKFLOW_ACTOR) .tell(new StartWorkflowCommand(workflowName, operation.getInstanceName()), noSender()); break; case STOP: actorSystem.actorSelection(WORKFLOW_ACTOR) .tell(new StopWorkflowCommand(workflowName, operation.getInstanceName()), noSender()); break; case CANCEL: actorSystem.actorSelection(WORKFLOW_ACTOR) .tell(new CancelWorkflowCommand(workflowName, operation.getInstanceName()), noSender()); break; } } public Workflow save(Workflow workflow) { workflowRepository.save(workflow); return workflow; } public List<Workflow> findAll() { return workflowRepository.findAll(); } public Workflow findByName(String workflowName) { return workflowRepository.findByName(workflowName); } public Workflow update(String workflowName, Workflow workflow) { return save(workflow); } public void delete(String workflowName) { workflowRepository.delete(workflowName); } } <file_sep>/** * The MIT License * Copyright © 2018 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.beethoven.dsl; import io.beethoven.dsl.Condition.ConditionTaskNameEqualsTo; import static io.beethoven.dsl.Condition.ConditionWorkflowNameEqualsTo; /** * @author <NAME> */ public class ConditionFunctionFactory { public static final String TASK_NAME_EQUALS_TO = "taskNameEqualsTo"; public static final String WORKFLOW_NAME_EQUALS_TO = "workflowNameEqualsTo"; public static final String TASK_RESPONSE_EQUALS_TO = "taskResponseEqualsTo"; public static Condition createCondition(String fuction, String arg) { Condition condition = new Condition(); switch (fuction) { case TASK_NAME_EQUALS_TO: ConditionTaskNameEqualsTo conditionTaskNameEqualsTo = new ConditionTaskNameEqualsTo(); conditionTaskNameEqualsTo.setTaskName(arg); condition.setConditionFunction(conditionTaskNameEqualsTo); break; case WORKFLOW_NAME_EQUALS_TO: ConditionWorkflowNameEqualsTo conditionWorkflowNameEqualsTo = new ConditionWorkflowNameEqualsTo(); conditionWorkflowNameEqualsTo.setWorkflowName(arg); condition.setConditionFunction(conditionWorkflowNameEqualsTo); break; case TASK_RESPONSE_EQUALS_TO: break; } return condition; } } <file_sep>/** * The MIT License * Copyright © 2018 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.beethoven.dsl; import lombok.*; import static io.beethoven.dsl.Command.CommandOperation.*; /** * @author <NAME> */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class Command { private CommandOperation operation; private String taskName; private String workflowName; private String input; public enum CommandOperation { START_TASK(""), SCHEDULE_WORKFLOW(""), START_WORKFLOW(""), STOP_WORKFLOW(""), CANCEL_WORKFLOW(""); @Getter private String commandFunction; CommandOperation(String commandFunction) { this.commandFunction = commandFunction; } } public static class CommandFactory { public static final String START_TASK = "startTask"; public static final String START_WORKFLOW = "startWorkflow"; public static final String STOP_WORKFLOW = "stopWorkflow"; public static final String CANCEL_WORKFLOW = "cancelWorkflow"; public static Command createCommand(String commandFunction, String arg) { Command command = null; switch (commandFunction) { case START_TASK: command = startTask(arg); break; case START_WORKFLOW: command = startWorkflow(arg); break; case STOP_WORKFLOW: command = stopWorkflow(arg); break; case CANCEL_WORKFLOW: command = cancelWorkflow(arg); break; } return command; } } public static Command startTask(@NonNull String taskName) { return Command.builder().taskName(taskName).operation(START_TASK).build(); } public static Command startWorkflow(@NonNull String workflowName) { return Command.builder().workflowName(workflowName).operation(START_WORKFLOW).build(); } public static Command stopWorkflow(@NonNull String workflowName) { return Command.builder().workflowName(workflowName).operation(STOP_WORKFLOW).build(); } public static Command cancelWorkflow(@NonNull String workflowName) { return Command.builder().workflowName(workflowName).operation(CANCEL_WORKFLOW).build(); } } <file_sep>/** * The MIT License * Copyright © 2018 <NAME> * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.beethoven.config; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; import io.beethoven.Beethoven; import io.beethoven.api.HandlerResource; import io.beethoven.api.MetricsResource; import io.beethoven.api.TaskResource; import io.beethoven.api.WorkflowResource; import io.beethoven.repository.ContextualInputRepository; import io.beethoven.repository.WorkflowRepository; import io.beethoven.service.HandlerService; import io.beethoven.service.TaskExecutorService; import io.beethoven.service.TaskService; import io.beethoven.service.WorkflowService; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.annotation.Order; import org.springframework.web.reactive.function.client.WebClient; /** * @author <NAME> */ @Configuration @ComponentScan @ConditionalOnBean(BeethovenMarkerConfiguration.Marker.class) @EnableConfigurationProperties(BeethovenProperties.class) @Import(AkkaConfiguration.class) public class BeethovenAutoConfiguration { @Bean @LoadBalanced @ConditionalOnMissingBean public WebClient.Builder webClientBuilder() { return WebClient.builder(); } @Bean @ConditionalOnMissingBean public ObjectMapper mapper() { ObjectMapper mapper = new ObjectMapper() .registerModule(new ParameterNamesModule()) .registerModule(new Jdk8Module()) .registerModule(new JavaTimeModule()); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); return mapper; } @Bean @ConditionalOnMissingBean public WorkflowResource workflowResource() { return new WorkflowResource(); } @Bean @ConditionalOnMissingBean public TaskResource taskResource() { return new TaskResource(); } @Bean @ConditionalOnMissingBean public HandlerResource handlerResource() { return new HandlerResource(); } @Bean @ConditionalOnMissingBean public MetricsResource metricsResource() { return new MetricsResource(); } @Bean @ConditionalOnMissingBean public WorkflowRepository workflowRepository() throws Exception { WorkflowRepository workflowRepository = new WorkflowRepository(); workflowRepository.saveAll(Beethoven.loadWorkflows()); return workflowRepository; } @Bean @ConditionalOnMissingBean public ContextualInputRepository contextualInputRepository() { return new ContextualInputRepository(); } @Bean @ConditionalOnMissingBean public HandlerService eventHandlerService() { return new HandlerService(); } @Bean @ConditionalOnMissingBean public WorkflowService workflowService() { return new WorkflowService(); } @Bean @ConditionalOnMissingBean public TaskService taskService() { return new TaskService(); } @Bean @ConditionalOnMissingBean public TaskExecutorService taskExecutorService() { return new TaskExecutorService(); } @Bean @Order @ConditionalOnMissingBean public BeethovenContext beethovenContext() { return new BeethovenContext(); } }<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath/> </parent> <groupId>io.beethoven</groupId> <artifactId>beethoven-core</artifactId> <version>0.0.1</version> <packaging>jar</packaging> <name>beethoven/beethoven-core</name> <description>Beethoven Core</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> <spring-cloud.version>Finchley.M8</spring-cloud.version> <akka.version>2.5.3</akka.version> <commons-csv.version>1.5</commons-csv.version> <commons-io.version>2.6</commons-io.version> </properties> <dependencies> <!-- Spring Boot dependencies --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </dependency> <!-- END Spring Boot dependencies --> <!-- Jackson dependencies --> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-parameter-names</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jdk8</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency> <!-- END Jackson dependencies --> <!-- Akka dependencies --> <dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-actor_2.11</artifactId> <version>${akka.version}</version> </dependency> <!-- END Akka dependencies --> <!-- Test dependencies --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-test</artifactId> <scope>test</scope> </dependency> <!-- END Test dependencies --> <!-- Other dependencies --> <dependency> <groupId>org.hamcrest</groupId> <artifactId>java-hamcrest</artifactId> <version>2.0.0.0</version> </dependency> <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-csv</artifactId> <version>${commons-csv.version}</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>compile</scope> <optional>true</optional> </dependency> <!-- END Other dependencies --> <!-- Partitur dependencies --> <dependency> <groupId>io.beethoven.partitur</groupId> <artifactId>io.beethoven.partitur</artifactId> <version>1.0.0-SNAPSHOT</version> </dependency> <!-- END Partitur dependencies --> </dependencies> <build> <resources> <resource> <directory>src/main/resources</directory> </resource> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <!--<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <executions> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin>--> <plugin> <groupId>com.mycila</groupId> <artifactId>license-maven-plugin</artifactId> <version>3.0</version> <configuration> <header>com/mycila/maven/plugin/license/templates/MIT.txt</header> <properties> <owner><NAME></owner> <email><EMAIL></email> <project.inceptionYear>2018</project.inceptionYear> </properties> <excludes> <exclude>**/pom.xml</exclude> <exclude>**/README</exclude> <exclude>src/test/resources/**</exclude> <exclude>src/main/resources/**</exclude> </excludes> </configuration> <executions> <execution> <goals> <goal>remove</goal> <goal>format</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> </project> <file_sep>/** * The MIT License * Copyright © 2018 <NAME> * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.beethoven.engine; import io.beethoven.engine.core.ReporterActor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import java.time.Duration; import java.time.LocalDateTime; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; import static java.util.Objects.requireNonNull; /** * @author <NAME> */ @Data @NoArgsConstructor public class TaskInstance { private String workflowName; private String workflowInstanceName; private String taskName; private String taskInstanceName; private LocalDateTime startTime; private LocalDateTime endTime; private String response; private Throwable failure; public TaskInstance(@NonNull ReporterActor.ReportTaskEvent reportTaskEvent) { this.workflowName = reportTaskEvent.getWorkflowName(); this.workflowInstanceName = reportTaskEvent.getWorkflowInstanceName(); this.taskName = reportTaskEvent.getTaskName(); this.taskInstanceName = reportTaskEvent.getTaskInstanceName(); } public Duration elapsedTime() { Duration duration = Duration.ZERO; if (nonNull(startTime) && nonNull(endTime)) { duration = Duration.between(startTime, endTime); } return duration.abs(); } public boolean isTerminated() { return nonNull(startTime) && nonNull(endTime); } public boolean isSuccessfullyExecuted() { return isNull(failure); } public void print() { System.err.println("Task name: " + taskName); System.err.println("Task instance name: " + taskInstanceName); System.err.println("Execution time: " + elapsedTime().toMillis() + " milliseconds"); if (nonNull(response)) System.err.println("Response: " + response); if (nonNull(failure)) System.err.println("Failure: " + failure.getMessage()); } } <file_sep>/** * The MIT License * Copyright © 2018 <NAME> * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.beethoven.engine; import io.beethoven.engine.core.ReporterActor; import io.beethoven.engine.core.support.WorkflowInstanceActor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import java.time.Duration; import java.time.LocalDateTime; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; /** * @author <NAME> */ @Data @NoArgsConstructor public class WorkflowInstance { private String workflowName; private String workflowInstanceName; private Map<String, TaskInstance> tasks = new ConcurrentHashMap<>(); private LocalDateTime startTime; private LocalDateTime endTime; private WorkflowStatus status; private int countTasks; public WorkflowInstance(@NonNull WorkflowInstanceActor.WorkflowInstanceCommand workflowInstanceCommand) { this.workflowName = workflowInstanceCommand.getWorkflowName(); this.workflowInstanceName = workflowInstanceCommand.getWorkflowInstanceName(); } public WorkflowInstance(@NonNull ReporterActor.ReportWorkflowEvent reportWorkflowEvent) { this.workflowName = reportWorkflowEvent.getWorkflowName(); this.workflowInstanceName = reportWorkflowEvent.getWorkflowInstanceName(); } public Duration elapsedTime() { Duration duration = Duration.ZERO; if (nonNull(startTime) && nonNull(endTime)) { duration = Duration.between(startTime, endTime); } return duration.abs(); } public boolean isTerminated() { return countTasks == tasks.values().stream().filter(TaskInstance::isTerminated).count(); } public boolean isSuccessfullyExecuted() { return isTerminated() && tasks.values().stream().filter(TaskInstance::isSuccessfullyExecuted).count() == countTasks; } public void print() { System.err.println("Workflow name: " + workflowName); System.err.println("Instance name: " + workflowInstanceName); System.err.println("Execution time: " + elapsedTime().toMillis() + " milliseconds"); System.err.println("Success: " + isSuccessfullyExecuted()); //tasks.values().forEach(TaskInstance::print); } public enum WorkflowStatus { SCHEDULED, RUNNING, PAUSED, COMPLETED, CANCELLED, FAILED } }
b03fd7f6574bc9e40f777c504909c4acca407545
[ "Java", "Maven POM" ]
12
Java
davimonteiro/beethoven
15adcf046f6a7bc6403c9ac136f154f85a71c2e2
a498093d60fa0a02d066f3dd60bb36d43d0accc5
refs/heads/master
<file_sep>package main import ( "flag" "io" "os" ) var ( append = flag.Bool("a", false, "Append to the end of file") ) func main() { flag.Parse() fFlag := os.O_APPEND | os.O_CREATE | os.O_WRONLY if !*append { fFlag |= os.O_TRUNC } args := flag.Args() if len(args) != 1 { panic("Required output file") } f, err := os.OpenFile(args[0], fFlag, 0644) if err != nil { panic(err) } defer f.Close() out := io.MultiWriter(os.Stdout, f) io.Copy(out, os.Stdin) } <file_sep># Reinvent Just a learning repository. Reinvent basic tools, concept for deeper understanding <file_sep>import socket import os import signal import time import sys class Worker: def __init__(self, sock): self.sock = sock self.pid = os.getpid() def start(self): print("Starting worker {}".format(self.pid)) signal.signal(signal.SIGTERM, self.stop) signal.signal(signal.SIGINT, self.stop) while True: (c, addr) = self.sock.accept() print("[{}] Got a new connection".format(self.pid)) msg = "Response from pid {}\n".format(self.pid) c.send(msg.encode()) c.close() def stop(self, sigNumber, frame): print("Shutting down worker {}".format(self.pid)) sys.exit(0) class Master: def __init__(self, addr, port, workers=5, graceful_timeout=30): self.addr = addr self.port = port self.workers = workers self.graceful_timeout = graceful_timeout self.socket = None self.children = [] self.running = True def fork_worker(self): pid = os.fork() if pid == 0: worker = Worker(self.socket) worker.start() else: self.children.append(pid) def start(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((self.addr, self.port)) self.socket.listen(1) for i in range(self.workers): self.fork_worker() signal.signal(signal.SIGTERM, self.stop) signal.signal(signal.SIGINT, self.stop) # After created workers # Main process should only monitor and recreate worker if needed while True > 0: try: pid, status = os.wait() except OSError as e: # Handle no child process error # Exit the program after all worker had stopped if e.errno == 10: sys.exit(0) print("A child exited") self.children.remove(pid) # Recreate another worker # when there is an unexpected worker killed if self.running: self.fork_worker() def stop(self, sigNumber, frame): print("Parent received signal") self.socket.close() self.running = False # Use OS Signal to avoid blocking main process # which will cause all child worker to enter `defunct` mode after terminated # because main process does not handle `os.wait` # Dont need to send SIGTERM to children because # Processes are in the same process group # Signal will be passed through print("Wait for graceful timeout") signal.signal(signal.SIGALRM, self.exit) signal.alarm(self.graceful_timeout) def exit(self, sigNumber, frame): # Terminate all running worker # then exit for child in self.children: os.kill(child, signal.SIGKILL) sys.exit(0) if __name__ == "__main__": m = Master("0.0.0.0", 8888, graceful_timeout=10) m.start() <file_sep>package main import ( "bufio" "bytes" "fmt" "log" "net" "net/http" "net/http/httputil" "strconv" ) type myReponseWriter struct { conn net.Conn body *bytes.Buffer status int header http.Header } func (rw *myReponseWriter) Header() http.Header { return rw.header } func (rw *myReponseWriter) Write(b []byte) (int, error) { return rw.body.Write(b) } func (rw *myReponseWriter) WriteHeader(status int) { rw.status = status } func (rw *myReponseWriter) flush() error { status := fmt.Sprintf("HTTP/1.1 %d\n", rw.status) if _, err := rw.conn.Write([]byte(status)); err != nil { return err } body := rw.body.Bytes() rw.Header().Set("Content-Length", strconv.Itoa(len(body))) if err := rw.Header().Write(rw.conn); err != nil { return err } rw.conn.Write([]byte("\n")) if _, err := rw.conn.Write(rw.body.Bytes()); err != nil { return err } return nil } func newResponseWriter(conn net.Conn) *myReponseWriter { rw := new(myReponseWriter) rw.conn = conn buf := []byte{} rw.body = bytes.NewBuffer(buf) rw.header = http.Header{} return rw } func handleFunc(r *http.Request, w http.ResponseWriter) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "text/html") w.Write([]byte("<html><body><h1>Hello</h1></body></html>")) } func handleConnection(conn net.Conn) error { r := bufio.NewReader(conn) req, err := http.ReadRequest(r) if err != nil { log.Printf("Cannot parse request. ERR: %v\n", err) return err } message, err := httputil.DumpRequest(req, false) if err != nil { log.Printf("Cannot dump request. ERR: %v\n", err) return err } fmt.Println(string(message)) writer := newResponseWriter(conn) handleFunc(req, writer) return writer.flush() } func main() { fmt.Println("Starting server") ln, err := net.Listen("tcp", ":8080") if err != nil { panic(err) } for { conn, err := ln.Accept() if err != nil { log.Printf("Cannot accept connection. ERR: %v\n", err) continue } handleConnection(conn) conn.Close() } }
21dee241a15120464a72f3fd0d523874706fdffb
[ "Markdown", "Python", "Go" ]
4
Go
vanhtuan0409/reinvent
a81a8b7b15c8e580b1293d24af9a13c479546fed
f898676afc0eccec6514c1db2eded9be6a5ca0f8
refs/heads/master
<repo_name>Biker-nfb/sushi<file_sep>/src/main/main.js import s3 from '../images/s3.webp' import s1 from '../images/s1.webp' import s2 from '../images/s2.webp' import s44 from '../images/s44.webp' import '../main/main.css' import React from 'react' import Slid from './slider' export default function Main() { return ( <div className="App-main"> <h2 className="App-main--tagline">Суши шмастер - лучшее, что есть в твоем городе </h2> <h2 className="App-main--tagline"> Порадуй себя и своих родных</h2> <p className="App-main--infoText">Ниже представлены наши самые популярные позиции за последние пол года работы</p> <h3 className="App-main--info">Актуальные позиции</h3> <div className="App-main--tabs"> <ul> <li className="App-main--tabsLi"> <img src={s3} alt="s3"></img> <h5>Гринобль ролл</h5> <p>Закажи сей вкуссный рол, Он украсит ваший стол, Он порадует ваш глаз, Получи скорей экстаз!</p> <button className="App-main--btnActive">Заказать</button> </li> <li className="App-main--tabsLi"> <img src={s1} alt="s1"></img> <h5>Оранжад ролл</h5> <p>Закажи сей вкуссный рол, Он украсит ваший стол, Он порадует ваш глаз, Получи скорей экстаз!</p> <button>Недоступно к заказу</button> </li> <li> <img src={s2} alt="s2"></img> <h5>Брауни ролл</h5> <p>Закажи сей вкуссный рол, Он украсит ваший стол, Он порадует ваш глаз, Получи скорей экстаз!</p> <button>Недоступно к заказу</button> </li> <li> <img src={s44} alt="s44"></img> </li> </ul> </div> <div className="App-main--bottom"> <h2>Самые выгодные предложения:</h2> <Slid/> </div> </div> ) }<file_sep>/src/header/header.js import clown from '../images/clownfish.webp' import './header.css' export default function Header() { return ( <header className="App-header"> <div className="App-header--container"> <div className="App-header--container-wraper"> <img className="App-header--container-img" src={clown} alt="clown-fish"></img> <h2 className="App-header--container-text">Суши-шмастер</h2> </div> <button className="App-header--container-btn">Сделать заказ</button> </div> </header> ) } <file_sep>/src/components/SliderData.js import vodka from '../images/vodka.webp' import dorado from '../images/dorado.webp' import shrimp from '../images/shrimp.webp' export const SliderData = [ { image: vodka }, { image: dorado }, { image: shrimp } ]; <file_sep>/src/footer/footer.js import './footer.css' export default function Footer() { const year = (new Date().getFullYear()) return ( <div className="App-footer"> <p>Copyright: {year}</p> </div> ) }
6e0605dc92e05f91a2d19739051b86ca9967f0c1
[ "JavaScript" ]
4
JavaScript
Biker-nfb/sushi
336ff61e74eae4ef3dfb0fa10e5d5a9d38a87d2b
392a724b6825d45b3058163e874d1ca3ce8deb8c
refs/heads/master
<file_sep># Maintainer: <NAME> <<EMAIL>> pkgname=replicant pkgver=0.6.0 pkgrel=1 pkgdesc="Tool for creating replicated state machines." arch=('i686' 'x86_64') url="https://github.com/rescrv/Replicant" license=('BSD') source=("http://hyperdex.org/src/${pkgname}-${pkgver}.tar.gz") depends=('libpo6' 'libe' 'busybee' 'hyperleveldb' 'google-glog') md5sums=('0a57d4f3598b7772f2f6dcdcb46d2528') build() { cd "$srcdir/$pkgname-$pkgver" ./configure --prefix=/usr make } check() { cd "$srcdir/$pkgname-$pkgver" make -k check } package() { cd "$srcdir/$pkgname-$pkgver" make DESTDIR="$pkgdir/" install }
9b1839a5d19a994b6eaec455cabf66305174bcd4
[ "Shell" ]
1
Shell
aur-archive/replicant
ebc96249354470b27c3def58a6b6ddec2bfd480d
d8ee8d27fc3c831efc793a429c67fbe088dd1f12
refs/heads/master
<repo_name>zhweifeng/zhweifeng.github.com<file_sep>/README.md # zhweifeng.github.com this is a website <file_sep>/html5/game/js/dieFish.js /** * Author:strive * Date: 2016/1/7 */ function DieFish(type){ this.x=0; this.y=0; this.rotate=0; this.type=type; this.cur=0; this.move(); } DieFish.prototype.draw=function(gd){ var w=FISH_SIZE[this.type].w; var h=FISH_SIZE[this.type].h; gd.save(); gd.translate(this.x,this.y); gd.rotate(d2a(this.rotate)); if(this.rotate>90 && this.rotate<270){ gd.scale(1,-1); } gd.drawImage( JSON['fish'+this.type], 0,h*4+this.cur*h,w,h, -w/2,-h/2,w,h ); gd.restore(); }; DieFish.prototype.move=function(){ var _this=this; setInterval(function(){ _this.cur++; if(_this.cur==4){ _this.cur=0; } },30); }; <file_sep>/js/base.js //用class名字来获取元素,兼容所有,系统的不兼容IE8及以下 开始 function getByClass(oParent,sClass){ if(oParent.getElementsByClassName){ return oParent.getElementsByClassName(sClass); }else{ var arr=[]; //var reg=/\bsClass\b/; var reg=new RegExp('\\b'+sClass+'\\b'); var aEle=oParent.getElementsByTagName('*'); for(var i=0; i<aEle.length; i++){ if(reg.test(aEle[i].className)){ arr.push(aEle[i]); } } return arr; } } //有这个class function hasClass(obj,sClass){ var reg=new RegExp('\\b'+sClass+'\\b'); return reg.test(obj.className); } //添加class function addClass(obj,sClass){ if(obj.className){ if(!hasClass(obj,sClass)){ obj.className+=' '+sClass; } }else{ obj.className=sClass; } } //删除class function removeClass(obj,sClass){ var reg=new RegExp('\\b'+sClass+'\\b','g'); if(hasClass(obj,sClass)){ obj.className=obj.className.replace(reg,'').replace(/^\s+|\s+$/g,'').replace(/\s+/g,' '); } } //切换class名字 function toggleClass(obj,sClass){ if(hasClass(obj,sClass)){ removeClass(obj,sClass); }else{ addClass(obj,sClass); } } //在m-n这个范围内的随机数 function rnd(n, m) { return Math.floor(Math.random()*(m-n)+n); } //判断一个字符串是否在arr这个数组内 开始 function findInArr(arr, n) { for (var i=0; i<arr.length; i++) { if (arr[i] == n) { return true; } } return false; } //判断一个字符串是否在arr这个数组内 结束 //给数字前补零,来填充位数 开始 function toDub(n) { return n<10 ? '0'+n : ''+n; } //事件的绑定 function addEvent(obj, sEv, fn) { if (obj.addEventListener) { obj.addEventListener(sEv, fn, false); // 高级浏览器 } else { obj.attachEvent('on'+sEv, fn); // 低级浏览器 } } //事件的解除 function removeEvent(obj, sEv, fnName) { if (obj.removeEventListener) { obj.removeEventListener(sEv, fnName, false); } else { obj.detachEvent('on'+sEv, fnName); } } //拖拽封装函数 function drag(obj) { addEvent(obj, 'mousedown', function (ev){ var oEvent=ev || event; var disX=oEvent.clientX-obj.offsetLeft; var disY=oEvent.clientY-obj.offsetTop; addEvent(document, 'mousemove', move); addEvent(document, 'mouseup', up); function move(ev) { var oEvent=ev || event; obj.style.left=oEvent.clientX-disX+'px'; obj.style.top=oEvent.clientY-disY+'px'; } function up() { removeEvent(document, 'mousemove', move); removeEvent(document, 'mouseup', up); obj.releaseCapture && obj.releaseCapture(); } obj.setCapture && obj.setCapture(); oEvent.preventDefault && oEvent.preventDefault(); return false; }); } //相当于window.onload 和jquery 里边的$ 符一样 /*function $(fn){ if(document.addEventListener){ document.addEventListener('DOMContentLoaded',fn,false); } else{ document.onreadystatechange=function(){ if(document.readyState == 'complete'){ fn(); } }; } }*/ // 获取非行间样式, oDiv 'width' function getStyle(obj,sName){ return (obj.currentStyle || getComputedStyle(obj, false))[sName]; } //滚轮 /*addWheel(document, function (down){ // 回调函数 // down true下 false上 if (down) { // 下 oDiv.style.height=oDiv.offsetHeight+10+'px'; } else { // 上 oDiv.style.height=oDiv.offsetHeight-10+'px'; } });*/ function addWheel(obj, fn) { // 加事件 if (window.navigator.userAgent.toLowerCase().indexOf('firefox') != -1) { // FF obj.addEventListener('DOMMouseScroll', function (ev){ if (ev.detail > 0) { // 下 fn(true); } else { fn(false); } }, false); } else { obj.onmousewheel=function (){ if (event.wheelDelta > 0) { // 上 fn(false); } else { fn(true); } }; } } function getStyle(obj, sName) { return (obj.currentStyle || getComputedStyle(obj, false))[sName]; } //move函数 function move(obj, json, options) { options=options || {}; var duration=options.duration || 500; var easing=options.easing || Tween.Linear; var start={}; var dis={}; for (var name in json) { start[name]=parseFloat(getStyle(obj, name)); if(isNaN(start[name])){//css的style 没给样式的时候需要这个判断 switch(name){ case 'left': start[name]=obj.offsetLeft; break; case 'top': start[name]=obj.offsetTop; break; case 'width': start[name]=obj.offsetWidth; break; case 'height': start[name]=obj.offsetHeight; break; case 'opacity': start[name]=1; break; //borderWidth fontSize paddingLeft marginLeft //..... } } dis[name]=json[name]-start[name]; } var count=Math.floor(duration/30); var n=0; clearInterval(obj.timer); obj.timer=setInterval(function (){ n++; // 更改样式 for (var name in json) { var cur=easing(duration*n/count, start[name], dis[name], duration); if (name == 'opacity') { obj.style[name]=cur; } else { obj.style[name]=cur+'px'; } } if (n == count) { clearInterval(obj.timer); options.complete && options.complete(); } }, 30); } //版权 ©, 保留所有权利 //t 当前时间 //b 初始值 //c 总距离 //d 总时间 //var cur=fx(t,b,c,d) var Tween = { Linear: function(t,b,c,d){ return c*t/d + b; }, Quad: { easeIn: function(t,b,c,d){ return c*(t/=d)*t + b; }, easeOut: function(t,b,c,d){ return -c *(t/=d)*(t-2) + b; }, easeInOut: function(t,b,c,d){ if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; } }, Cubic: { easeIn: function(t,b,c,d){ return c*(t/=d)*t*t + b; }, easeOut: function(t,b,c,d){ return c*((t=t/d-1)*t*t + 1) + b; }, easeInOut: function(t,b,c,d){ if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; } }, Quart: { easeIn: function(t,b,c,d){ return c*(t/=d)*t*t*t + b; }, easeOut: function(t,b,c,d){ return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOut: function(t,b,c,d){ if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; } }, Quint: { easeIn: function(t,b,c,d){ return c*(t/=d)*t*t*t*t + b; }, easeOut: function(t,b,c,d){ return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOut: function(t,b,c,d){ if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; } }, Sine: { easeIn: function(t,b,c,d){ return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOut: function(t,b,c,d){ return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOut: function(t,b,c,d){ return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; } }, Expo: { easeIn: function(t,b,c,d){ return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOut: function(t,b,c,d){ return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOut: function(t,b,c,d){ if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; } }, Circ: { // 周围的 easeIn: function(t,b,c,d){ return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOut: function(t,b,c,d){ return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOut: function(t,b,c,d){ if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; } }, Elastic: { //弹性 easeIn: function(t,b,c,d,a,p){ if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (!a || a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOut: function(t,b,c,d,a,p){ if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (!a || a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return (a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b); }, easeInOut: function(t,b,c,d,a,p){ if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (!a || a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; } }, Back: { //回来 easeIn: function(t,b,c,d,s){ if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOut: function(t,b,c,d,s){ if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOut: function(t,b,c,d,s){ if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; } }, Bounce: { //反弹 easeIn: function(t,b,c,d){ return c - Tween.Bounce.easeOut(d-t, 0, c, d) + b; }, easeOut: function(t,b,c,d){ if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOut: function(t,b,c,d){ if (t < d/2) return Tween.Bounce.easeIn(t*2, 0, c, d) * .5 + b; else return Tween.Bounce.easeOut(t*2-d, 0, c, d) * .5 + c*.5 + b; } } } <file_sep>/html5/game/js/coin.js /** * Author:strive * Date: 2016/1/7 */ function Coin(type){ this.type=type; this.x=0; this.y=0; this.cur=0; this.move(); } Coin.prototype.draw=function(gd){ gd.save(); gd.translate(this.x,this.y); switch (this.type){ case 1: case 2: case 3: gd.drawImage( JSON.coinAni1, 0,this.cur*60,60,60, -30,-30,60,60 ); break; case 4: case 5: gd.drawImage( JSON.coinAni2, 0,this.cur*60,60,60, -30,-30,60,60 ); break; } gd.restore(); }; Coin.prototype.move=function(){ var _this=this; //钱转 setInterval(function(){ _this.cur++; if(_this.cur==10){ _this.cur=0; } },30); //收钱 setTimeout(function(){ setInterval(function(){ _this.x+=(0-_this.x)/5; _this.y+=(650-_this.y)/5; },30); },300); this.playSong(); }; Coin.prototype.playSong=function(){ var oA=new Audio(); oA.src='snd/coin.wav'; oA.play(); };<file_sep>/js/index.js $(function(){ $('#resume').click(function(){ alert('亲,若要联系本人,请发邮件'); }); $('.page1 h2,').css('-webkit-box-reflect','none'); //page2页图的变化 var timer=null; $('.page2 h2,').toggle(function(){ $(this).parent().css('z-index',3); $(this).css('-webkit-box-reflect','none'); var _this=$(this); $(this).parent().stop().animate({ width:'100%', height:'100%' },{ duration:500, complete:function(){ $('.marquee').hide(); $('.thumb').show(); clearInterval(timer); clearInterval(tiemrH5); } }); },function(){ var _this=$(this); $(this).parent().stop().animate({ width:'50%', height:'50%' },{ duration:500, complete:function(){ _this.parent().css('z-index',0); $('.marquee').show(); $('.thumb').hide(); clearInterval(timer); timer=setInterval(noseam,30); clearInterval(tiemrH5); tiemrH5=setInterval(H5tab,3000); _this.css('-webkit-box-reflect','below 5px -webkit-linear-gradient(rgba(255,0,0,0) 10%,rgba(255,255,255,0.5))'); } }); }); //轮播图 var pmd=$('.marquee ul'); //pmd.get(0).innerHTML+=pmd.get(0).innerHTML; //pmd.html(pmd.html()+pmd.html()); //以上两个都对 第一个是原生js pmd.append(pmd.html()); var now=0; var bFlag=true; if(bFlag){ timer=setInterval(noseam,30); }else{ clearInterval(timer); } bFlag=false; function noseam(){ now+=2; if(now>=(pmd.width()/2)){now=0}; pmd.css('left',-now); } pmd.hover(function(){clearInterval(timer);},function(){timer=setInterval(noseam,30);}); //page3页图的变化 /*$('.page3 h2').toggle(function(){ $(this).parent().css('z-index',2); $(this).css('-webkit-box-reflect','none'); $(this).parent().stop().animate({ width:'100%', height:'100%' },{ duration:500, complete:function(){ clearInterval(timer); } }); },function(){ var _this=$(this); $(this).parent().stop().animate({ width:'50%', height:'50%' },{ duration:500, complete:function(){ _this.parent().css('z-index',0); timer=setInterval(noseam,30); _this.css('-webkit-box-reflect','below 5px -webkit-linear-gradient(rgba(255,0,0,0) 10%,rgba(255,255,255,0.5))'); } }); });*/ //page4页图的变化 $('.page4 h2').toggle(function(){ $(this).parent().css('z-index',2); $(this).css('-webkit-box-reflect','none'); $(this).parent().stop().animate({ width:'100%', height:'100%' },{ duration:500, complete:function(){ clearInterval(timer); clearInterval(tiemrH5); $('.h5').show(); $('#play').hide(); $('.h5 .box').hover(function(){ $(this).css('transform','perspective(800px) rotateY(-180deg)'); },function(){ $(this).css('transform','perspective(800px) rotateY(0deg)'); }); } }); },function(){ var _this=$(this); $(this).parent().stop().animate({ width:'50%', height:'50%' },{ duration:500, complete:function(){ _this.parent().css('z-index',0); clearInterval(timer); timer=setInterval(noseam,30); clearInterval(tiemrH5); tiemrH5=setInterval(H5tab,3000); $('#play').show(); $('.h5').hide(); _this.css('-webkit-box-reflect','below 5px -webkit-linear-gradient(rgba(255,0,0,0) 10%,rgba(255,255,255,0.5))'); } }); }); /* 拉勾网 thumb(拇指) 效果 */ $('#thumb li').mouseenter(function(ev){ var index=$(this).index(); var n=getN($('#thumb li'),ev,index); var oSpan=$('#thumb li a'); switch (n) { case 0: // right oSpan.eq(index).css({left:200,top:0}) break; case 1: // bottom oSpan.eq(index).css({left:0,top:200}) break; case 2: // left oSpan.eq(index).css({left:-200,top:0}) break; case 3: // top oSpan.eq(index).css({left:0,top:-200}) break; } oSpan.eq(index).stop().animate({top:0, left:0}); }); $('#thumb li').mouseleave(function(ev){ var index=$(this).index(); var n=getN($('#thumb li'),ev,index); var oSpan=$('#thumb li a'); switch (n) { case 0: // right oSpan.eq(index).stop().animate({top:0, left:200}); break; case 1: // bottom oSpan.eq(index).stop().animate({top:200, left:0}); break; case 2: // left oSpan.eq(index).stop().animate({top:0, left:-200}); break; case 3: // top oSpan.eq(index).stop().animate({top:-200, left:0}); break; } }); function getN(obj,ev,index) { //alert(index) var x=obj.eq(index).offset().left+obj.eq(index).width()/2-ev.clientX; var y=obj.eq(index).offset().top+obj.eq(index).height()/2-ev.clientY; var n=Math.round((d2a(Math.atan2(y, x))+180)/90)%4; return n; } //弧度转角度 function d2a(d) { return d*180/Math.PI; } var pg3=document.getElementById('page3'); var str='Sorry ! 此分页正在更新中。您可以点击“前端实践”和“HTML5”两个分页,会有意外收获哦 ---建议用chrome浏览器打开 ^_^'; for(var i=0; i<str.length; i++){ var oSpan=document.createElement('span'); oSpan.innerHTML=str.charAt(i); pg3.appendChild(oSpan); } var aSpan=pg3.children; var txtTimer=null; var txtI=0; txtTimer=setInterval(function(){ aSpan[txtI].className='on'; txtI++; if(txtI==aSpan.length){ clearInterval(txtTimer); } },150); var aBtn=document.querySelectorAll('#play ol li'); var oUl=document.querySelector('#play ul'); var aLi=document.querySelectorAll('#play ul li'); var Now=0; for(var i=0; i<aBtn.length; i++){ aBtn[i].index=i; aBtn[i].onclick=function(){ Now=this.index; H5t(); }; } var tiemrH5=setInterval(H5tab,3000); $('#play').hover(function(){ clearInterval(tiemrH5); },function(){ clearInterval(tiemrH5); tiemrH5=setInterval(H5tab,3000); }); function H5tab(){ Now++; Now%=aBtn.length; H5t(); }; function H5t(){ for(var i=0; i<aBtn.length; i++){ aBtn[i].className=''; } aBtn[Now].className='active'; oUl.style.top=-aBtn[Now].index*aLi[0].offsetHeight+'px'; }; }); <file_sep>/html5/game/js/init.js /** * Author:strive * Date: 2016/1/7 */ window.onload=function(){ var oC=document.getElementById('c1'); var gd=oC.getContext('2d'); var out=30; //出界范围 var fishDirection=[-out,oC.width+out]; var rule=0.02; loadImage(arrResource,function(){ //炮 var c=new Cannon(7); //存子弹 var arrBullet=[]; //存鱼 var arrFish=[]; //存金币 var arrCoin=[]; //存渔网 var arrWeb=[]; //存死鱼 var arrDieFish=[]; setInterval(function(){ gd.clearRect(0,0,oC.width,oC.height); //出鱼规则 if(Math.random()<rule){ var f=new Fish(rnd(1,6)); fishDirection.sort(function(){ return Math.random()-0.5; }); if(fishDirection[0]<0){ f.rotate=rnd(-45,45); }else{ f.rotate=rnd(135,225); } f.x=fishDirection[0]; f.y=rnd(100,oC.height-100); arrFish.push(f); } //画鱼 for(var i=0; i<arrFish.length; i++){ arrFish[i].draw(gd); } //画炮台 gd.drawImage( JSON.bottom, 0,0,765,70, 0,532,765,70 ); //画子弹 for(var i=0; i<arrBullet.length; i++){ arrBullet[i].draw(gd); } //画金币 for(var i=0; i<arrCoin.length; i++){ arrCoin[i].draw(gd); } //画渔网 for(var i=0; i<arrWeb.length; i++){ arrWeb[i].scale+=0.03; arrWeb[i].draw(gd); if(arrWeb[i].scale>1.2){ arrWeb.splice(i,1); i--; } } //画死鱼 for(var i=0; i<arrDieFish.length; i++){ arrDieFish[i].draw(gd); } //画炮 c.draw(gd); //检测子弹和鱼碰到 for(var i=0; i<arrFish.length; i++){ for(var j=0; j<arrBullet.length; j++){ if(arrFish[i].isIn(arrBullet[j].x, arrBullet[j].y)){ var type=arrFish[i].type; var x=arrFish[i].x; var y=arrFish[i].y; var rotate=arrFish[i].rotate; //鱼死 arrFish.splice(i,1); i--; //子弹消失 arrBullet.splice(j,1); j--; //生成金币 var coin=new Coin(type); coin.x=x; coin.y=y; arrCoin.push(coin); //生成渔网 var web=new Web(); web.x=x; web.y=y; arrWeb.push(web); //死鱼 var dieFish=new DieFish(type); dieFish.x=x; dieFish.y=y; dieFish.rotate=rotate; arrDieFish.push(dieFish); //死鱼消失 setTimeout(function(){ //for(var i=0; i<arrDieFish.length; i++){ arrDieFish.splice(0,1); //i--; //} },500) } } } //子弹出界,删除 for(var i=0; i<arrBullet.length; i++){ if(arrBullet[i].x<-out || arrBullet[i].x>oC.width+out || arrBullet[i].y<-out || arrBullet[i].y>oC.height+out){ arrBullet.splice(i,1); i--; } } //判断鱼出界、删除 for(var i=0; i<arrFish.length; i++){ if(arrFish[i].x<-out || arrFish[i].x>oC.width+out || arrFish[i].y<-out || arrFish[i].y>oC.height+out){ arrFish.splice(i,1); i--; } } },16); //点击调整炮角度 oC.onmousemove=function(ev){ var a=c.x-(ev.clientX-oC.offsetLeft); var b=c.y-(ev.clientY-oC.offsetTop); var d=a2d(Math.atan2(b,a))-90; c.rotate=d; oC.onclick=function(ev){ //开炮 c.emitChange(); //出子弹 var bullet=new Bullet(c.type); bullet.x= c.x; bullet.y= c.y; bullet.rotate= c.rotate; arrBullet.push(bullet); }; }; }); };<file_sep>/html5/game/js/com.js /** * Author:strive * Date: 2016/1/7 */ var JSON={}; //存图片对象 function d2a(n){ return n*Math.PI/180; } function a2d(n){ return n*180/Math.PI; } function rnd(n,m){ return parseInt(Math.random()*(m-n)+n); } function loadImage(arr,fnSucc,fnLoading){ var count=0; for(var i=0; i<arr.length; i++){ (function(index){ var oImg=new Image(); oImg.onload=function(){ JSON[arr[index]]=this; count++; if(count==arr.length){ fnSucc && fnSucc(); } //loading fnLoading && fnLoading(count,arr.length); }; oImg.src='img/'+arr[i]+'.png'; })(i); } } <file_sep>/html5/game/js/web.js /** * Author:strive * Date: 2016/1/7 */ function Web(){ this.x=0; this.y=0; this.scale=0.5; } Web.prototype.draw=function(gd){ gd.save(); gd.translate(this.x,this.y); gd.scale(this.scale,this.scale); gd.drawImage( JSON.web, 15,414,107,107, -107/2,-107/2,107,107 ); gd.restore(); }; <file_sep>/html5/game/js/resource.js /** * Author:strive * Date: 2016/1/7 */ var arrResource=[ 'fish1', 'fish2', 'fish3', 'fish4', 'fish5', 'bottom', 'cannon1', 'cannon2', 'cannon3', 'cannon4', 'cannon5', 'cannon6', 'cannon7', 'bullet', 'coinAni1', 'coinAni2', 'web' ];
a80e251060609e6e85a1a8e4678d9ee5267a15c3
[ "Markdown", "JavaScript" ]
9
Markdown
zhweifeng/zhweifeng.github.com
264b62d17a20528272e70c7532b624d48b857897
76e3bd31edef4c958feb1b04db36432a6fec8422
refs/heads/master
<repo_name>gleasonjw/WTWJustonGleason<file_sep>/WTWJustonGleason/WTW.Web.API/DataAccess/IResumeRepository.cs using WTW.Web.API.Models; namespace WTW.Web.API.DataAccess { public interface IResumeRepository { Resume GetResumeData(string firstName, string lastName); } } <file_sep>/WTWJustonGleason/WTW.Web.API/DataAccess/ResumeRepositorySql.cs using System; using WTW.Web.API.Models; namespace WTW.Web.API.DataAccess { /// <summary> /// Sample implementation of IResumeRepository. /// </summary> public class ResumeRepositorySql : IResumeRepository { public Resume GetResumeData(string firstName, string lastName) { throw new NotImplementedException(); } } }<file_sep>/WTWJustonGleason/WTW.Web.Client/Scripts/app/ResumeService.js (function (resumeService, $, undefined) { resumeService.displayResume = function (targetElementName, messageSectionName) { // TODO: Replace hard-coded url with configuration value. $(messageSectionName).html('Loading...'); $.getJSON({ url: 'http://localhost:51167/api/Resume/ResumeData', success: function (data) { var jsonString = JSON.stringify(data, undefined, 4); $(targetElementName).html(jsonString); $(messageSectionName).html(''); }, error: function () { $(messageSectionName).html('Error connecting to service.'); } }); }; })(window.ResumeService = window.ResumeService || {}, jQuery);<file_sep>/WTWJustonGleason/WTW.IoC/LifeTime/LifeTimeManager.cs using System; namespace WTW.IoC.LifeTime { /// <summary> /// Base class for IoC lifetime manager implementations. /// </summary> public abstract class LifeTimeManager { public Type DataType { get; set; } public virtual void SetObject(object value) { } public virtual object GetObject() { return null; } } } <file_sep>/WTWJustonGleason/WTW.IoC/WTWContainer.cs using System; using System.Collections.Generic; using System.Reflection; using WTW.IoC.Exceptions; using System.Linq; using WTW.IoC.LifeTime; namespace WTW.IoC { /// <summary> /// Simple IoC container built for WTW code challenge. /// </summary> public class WTWContainer : IWTWContainer { private Dictionary<Type, LifeTimeManager> _registeredTypeManagers = new Dictionary<Type, LifeTimeManager>(); public void Register<TFrom, TTo>() { Register<TFrom, TTo>(new TransientLifeTimeManager()); } public void Register<TFrom, TTo>(LifeTimeManager lifeTimeMgr) { if (lifeTimeMgr == null) { throw new ArgumentNullException(nameof(lifeTimeMgr)); } lifeTimeMgr.DataType = typeof(TTo); _registeredTypeManagers.Add(typeof(TFrom), lifeTimeMgr); } public object Resolve<TFrom>() { Type fromType = typeof(TFrom); return Resolve(fromType); } /// <summary> /// Attempts to resolve the specified type. If the target type has multiple constructors, the constructor /// with the least number of parameters is used. /// </summary> /// <param name="fromType"></param> /// <returns></returns> public object Resolve(Type fromType) { object returnValue = null; if (_registeredTypeManagers.ContainsKey(fromType)) { LifeTimeManager lifeTimeMgr = _registeredTypeManagers[fromType]; returnValue = lifeTimeMgr.GetObject(); if (returnValue == null) { // Use the constructor with the least number of parameters to improve chances of success. ConstructorInfo[] constructors = lifeTimeMgr.DataType.GetConstructors() .OrderBy(c => c.GetParameters().Count()) .ToArray(); ConstructorInfo ctorInfo = constructors.First(); ParameterInfo[] parameters = ctorInfo.GetParameters(); List<object> resolvedParameters = new List<object>(); foreach (ParameterInfo paramInfo in parameters) { // Use recursion to resolve the parameter. object resolvedParam = Resolve(paramInfo.ParameterType); resolvedParameters.Add(resolvedParam); } returnValue = ctorInfo.Invoke(resolvedParameters.ToArray()); lifeTimeMgr.SetObject(returnValue); } } else { throw new ResolutionFailedException(fromType); } return returnValue; } #region Required for the WebAPI dependency resolver. public void Dispose() { // Note: This simple implementation doesn't require disposing of anything. More complex versions may have resources // that need to be released. } #endregion } } <file_sep>/WTWJustonGleason/WTW.IoC/LifeTime/TransientLifeTimeManager.cs  namespace WTW.IoC.LifeTime { /// <summary> /// IoC lifetime manager for transient objects. /// </summary> public class TransientLifeTimeManager : LifeTimeManager { } } <file_sep>/WTWJustonGleason/WTW.Web.API/Models/Employment.cs using System; namespace WTW.Web.API.Models { [Serializable()] public class Employment { public string CompanyName { get; set; } public string JobTitle { get; set; } public string JobDuties { get; set; } public string SkillsUsed { get; set; } } }<file_sep>/WTWJustonGleason/WTW.Ioc.Test/TestHelpers/IUsersController.cs namespace WTW.Ioc.Test.TestHelpers { public interface IUsersController { } }<file_sep>/WTWJustonGleason/WTW.Web.API/Models/Education.cs using System; namespace WTW.Web.API.Models { [Serializable()] public class Education { public string InstitutionName { get; set; } public string Degree { get; set; } } }<file_sep>/WTWJustonGleason/WTW.Ioc.Test/TestHelpers/IDataService.cs  namespace WTW.Ioc.Test.TestHelpers { public interface IDataService { } } <file_sep>/WTWJustonGleason/WTW.Web.API/Controllers/ResumeController.cs using System.Web.Http; using WTW.Web.API.DataAccess; using WTW.Web.API.Models; namespace WTW.Web.API.Controllers { public class ResumeController : ApiController { private IResumeRepository _repository; public ResumeController(IResumeRepository repository) { _repository = repository; } [HttpGet] public Resume ResumeData() { // TODO: Add exception handling. return _repository.GetResumeData(firstName: "Juston", lastName: "Gleason"); } } } <file_sep>/WTWJustonGleason/WTW.Web.API/App_Start/IoCConfig.cs using System.Web.Http; using WTW.IoC; using WTW.Web.API.Controllers; using WTW.Web.API.DataAccess; namespace WTW.Web.API { /// <summary> /// Static class to configure the IoC container used for dependency injection. /// </summary> public static class IoCConfig { public static void Register(HttpConfiguration config) { var container = new WTWContainer(); // Register types. container.Register<ResumeController, ResumeController>(); container.Register<IResumeRepository, ResumeRepositoryXml>(); // Set the DependencyResolver to enable dependency injection in WebAPI controllers. config.DependencyResolver = new WTWDependencyResolver(container); } } }<file_sep>/WTWJustonGleason/WTW.Web.API/App_Start/WTWDependencyResolver.cs using System; using System.Collections.Generic; using System.Web.Http.Dependencies; using WTW.IoC; using WTW.IoC.Exceptions; namespace WTW.Web.API { /// <summary> /// The WTWDependencyResolver class is a wrapper around WTWContainer as required for dependency injection in WebAPI controllers. /// <see cref="https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection"/> /// </summary> public class WTWDependencyResolver : IDependencyResolver { private IWTWContainer _container; public WTWDependencyResolver(IWTWContainer container) { if (container == null) { throw new ArgumentNullException(nameof(container)); } _container = container; } public IDependencyScope BeginScope() { // Note: For this simple implementation, I didn't add support for nested containers. return new WTWDependencyResolver(_container); } public object GetService(Type serviceType) { try { return _container.Resolve(serviceType); } catch (ResolutionFailedException) { return null; } } public IEnumerable<object> GetServices(Type serviceType) { try { // Note: For this simple implementation, the container just resolves the first matching object. List<object> returnValue = new List<object>(); returnValue.Add(_container.Resolve(serviceType)); return returnValue; } catch (ResolutionFailedException) { return new List<object>(); } } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { _container.Dispose(); } } }<file_sep>/WTWJustonGleason/WTW.Ioc.Test/TestHelpers/Calculator.cs  namespace WTW.Ioc.Test.TestHelpers { public class Calculator : ICalculator { } } <file_sep>/WTWJustonGleason/WTW.IoC/Exceptions/ResolutionFailedException.cs using System; namespace WTW.IoC.Exceptions { public class ResolutionFailedException : Exception { public ResolutionFailedException(Type serviceType) : base($"Resolution of type {serviceType.Name} failed.") { } } } <file_sep>/WTWJustonGleason/WTW.Ioc.Test/TestHelpers/IEmailService.cs namespace WTW.Ioc.Test.TestHelpers { public interface IEmailService { } }<file_sep>/WTWJustonGleason/WTW.Web.API/Global.asax.cs using System.Web.Http; namespace WTW.Web.API { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); // Wire up the dependency resolver for dependency injection. GlobalConfiguration.Configure(IoCConfig.Register); } } } <file_sep>/WTWJustonGleason/WTW.Ioc.Test/TestHelpers/ICalculator.cs  namespace WTW.Ioc.Test.TestHelpers { public interface ICalculator { } }<file_sep>/WTWJustonGleason/WTW.Web.API/DataAccess/ReadMe.txt Note: The data access layer is included in the web api project to keep the example simple. If I were building a real system, I would consider using a more layered architecture.<file_sep>/WTWJustonGleason/WTW.Ioc.Test/TestHelpers/UsersController.cs  namespace WTW.Ioc.Test.TestHelpers { public class UsersController : IUsersController { public UsersController(ICalculator calulator, IEmailService emailService) { } public UsersController(ICalculator calulator, IEmailService emailService, IDataService dataService) { } } } <file_sep>/WTWJustonGleason/WTW.Web.API/DataAccess/ResumeRepositoryXml.cs using System.IO; using System.Xml.Serialization; using WTW.Web.API.Models; namespace WTW.Web.API.DataAccess { /// <summary> /// Sample implementation of IResumeRepository. /// </summary> public class ResumeRepositoryXml : IResumeRepository { public Resume GetResumeData(string firstName, string lastName) { Stream xmlResource = this.GetType().Assembly.GetManifestResourceStream($"WTW.Web.API.EmbeddedResources.{firstName}{lastName}Resume.xml"); XmlSerializer serializer = new XmlSerializer(typeof(Resume)); using (StreamReader reader = new StreamReader(xmlResource)) { return (Resume) serializer.Deserialize(reader); } } } }<file_sep>/WTWJustonGleason/WTW.IoC/IWTWContainer.cs using System; using WTW.IoC.LifeTime; namespace WTW.IoC { /// <summary> /// Simple IoC container built for WTW code challenge. /// </summary> public interface IWTWContainer : IDisposable { void Register<TFrom, TTo>(); void Register<TFrom, TTo>(LifeTimeManager lifeTimeMgr); object Resolve<TFrom>(); #region Required for the WebAPI dependency resolver. object Resolve(Type fromType); #endregion } }<file_sep>/WTWJustonGleason/WTW.Ioc.Test/WTWContainerTest.cs using NUnit.Framework; using WTW.Ioc.Test.TestHelpers; using WTW.IoC; using WTW.IoC.LifeTime; namespace WTW.Ioc.Test { [TestFixture] public class WTWContainerTest { [Test] public void TestSimpleTypeRegistration() { IWTWContainer container = new WTWContainer(); container.Register<ICalculator, Calculator>(); } [Test] public void TestSimpleTypeResolution() { IWTWContainer container = new WTWContainer(); container.Register<ICalculator, Calculator>(); var calc = container.Resolve<ICalculator>(); Assert.IsNotNull(calc); } [Test] public void TestSimpleTypeResolutionWithParameter() { IWTWContainer container = new WTWContainer(); container.Register<ICalculator, Calculator>(); var calc = container.Resolve(typeof(ICalculator)); Assert.IsNotNull(calc); } [Test] public void TestResolveUnregisteredType() { IWTWContainer container = new WTWContainer(); TestDelegate testFunction = delegate() { container.Resolve<ICalculator>(); }; Assert.Catch(testFunction); } [Test] public void TestParameterizedConstructorResolution() { IWTWContainer container = new WTWContainer(); container.Register<ICalculator, Calculator>(); container.Register<IEmailService, EmailService>(); container.Register<IUsersController, UsersController>(); var ctrl = container.Resolve<IUsersController>(); Assert.IsNotNull(ctrl); } [Test] public void TestPartiallyRegisteredParameterizedConstructorResolution() { IWTWContainer container = new WTWContainer(); container.Register<ICalculator, Calculator>(); // Missing registration of email service. container.Register<IUsersController, UsersController>(); TestDelegate testFunction = delegate () { container.Resolve<IUsersController>(); }; Assert.Catch(testFunction); } [Test] public void TestTransientLifecycle() { IWTWContainer container = new WTWContainer(); container.Register<ICalculator, Calculator>(new TransientLifeTimeManager()); var calc1 = container.Resolve<ICalculator>(); var calc2 = container.Resolve<ICalculator>(); Assert.AreNotSame(calc1, calc2); } [Test] public void TestTransientLifecycleIsDefault() { IWTWContainer container = new WTWContainer(); container.Register<ICalculator, Calculator>(); var calc1 = container.Resolve<ICalculator>(); var calc2 = container.Resolve<ICalculator>(); Assert.AreNotSame(calc1, calc2); } [Test] public void TestSingletonLifecycle() { IWTWContainer container = new WTWContainer(); container.Register<ICalculator, Calculator>(new SingletonLifeTimeManager()); var calc1 = container.Resolve<ICalculator>(); var calc2 = container.Resolve<ICalculator>(); Assert.AreSame(calc1, calc2); } } } <file_sep>/WTWJustonGleason/WTW.Web.API/Models/Resume.cs using System; using System.Xml.Serialization; namespace WTW.Web.API.Models { [Serializable()] [XmlRoot("Resume")] public class Resume { public string FirstName { get; set; } public string LastName { get; set; } [XmlArray("EducationHistory")] [XmlArrayItem("Education", typeof(Education))] public Education[] EducationHistory { get; set; } [XmlArray("EmploymentHistory")] [XmlArrayItem("Employment", typeof(Employment))] public Employment[] EmploymentHistory { get; set; } } }<file_sep>/WTWJustonGleason/WTW.Ioc.Test/TestHelpers/EmailService.cs  namespace WTW.Ioc.Test.TestHelpers { public class EmailService : IEmailService { } } <file_sep>/WTWJustonGleason/WTW.IoC/LifeTime/SingletonLifeTimeManager.cs  namespace WTW.IoC.LifeTime { /// <summary> /// IoC lifetime manager for singleton objects. /// </summary> public class SingletonLifeTimeManager : LifeTimeManager { private object _storedObject = null; public override object GetObject() { return _storedObject; } public override void SetObject(object value) { _storedObject = value; } } }
5c84ee3e26587fc7763459130f9518fde98739eb
[ "JavaScript", "C#", "Text" ]
26
C#
gleasonjw/WTWJustonGleason
f38b43cc7b0d7b505ceb2ad1c9c7dc62d8426fb5
fbd259b53e2568d493288513f612b744584b10e8
refs/heads/main
<repo_name>Mohamedy74/timeline<file_sep>/src/app/post-detail/post-detail.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { Subscription } from 'rxjs'; import { PostService } from '../post.service'; @Component({ selector: 'app-post-detail', templateUrl: './post-detail.component.html', styleUrls: ['./post-detail.component.scss'] }) export class PostDetailComponent implements OnInit, OnDestroy { private subscription: Subscription[] = []; id: any | undefined; post: any; postForm: FormGroup = new FormGroup({}); editMode = false; loading = false; loadingSenddata = false; constructor( private route: ActivatedRoute, private postService: PostService, private router: Router ) { } ngOnInit(): void { this.subscription.push( this.route.paramMap.subscribe( (params: Params) => { this.id = +params.get('id'); this.getPost(this.id); this.editMode = params.get('id') != null; } ) ); this.initForm(); } getPost(id: number) { this.loading = true; this.postService.getPost(id).subscribe( res => { this.post = res; console.log(this.post); this.initForm(); this.loading = false; }, err => { this.router.navigate(['/posts']); this.loading = false; } ) } updatePost() { this.loadingSenddata = true; const post = { title: this.postForm.get('title')?.value, body: this.postForm.get('body')?.value, }; const id = this.id; this.postService.updatePost(id, post).subscribe( res => { this.post = res; this.loadingSenddata = false; }, err => { this.loadingSenddata = false; } ) } deletePost() { const id = this.id; this.postService.deletePost(id).subscribe( res => { this.router.navigate(['/posts']); }, err => { } ) } initForm() { this.postForm = new FormGroup({ title: new FormControl(''), body: new FormControl('') }); if (this.editMode && this.post) { this.postForm.patchValue({ title: this.post.title, body: this.post.body }); } } ngOnDestroy() { this.subscription.forEach(sub => sub.unsubscribe()); } } <file_sep>/src/app/post.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class PostService { constructor(private http: HttpClient) { } getPosts() { return this.http.get(environment.baseUrl + 'posts'); } getPost(id: number) { return this.http.get(environment.baseUrl + 'posts/' + id); } updatePost(id: number, post: any) { return this.http.put(environment.baseUrl + 'posts/' + id, post); } deletePost(id: number) { return this.http.delete(environment.baseUrl + 'posts/' + id); } } <file_sep>/src/app/post-list/post-list.component.ts import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { PostService } from '../post.service'; import { debounceTime, delay, map, startWith } from 'rxjs/operators'; import { asyncScheduler, Observable } from 'rxjs'; export interface Post { userId: number; id: number; title: string; body: string; } @Component({ selector: 'app-post-list', templateUrl: './post-list.component.html', styleUrls: ['./post-list.component.scss'] }) export class PostListComponent implements OnInit { posts: Post[] = []; searchControl = new FormControl(); filteredPosts: Observable<Post[]> | undefined; loading = false; constructor( private postService: PostService ) { } ngOnInit(): void { this.getPosts(); } getPosts() { this.loading = true; this.postService.getPosts().subscribe( (res: any) => { this.posts = res; this.loading = false; this.filterPosts(); }, err => { } ) } filterPosts() { this.filteredPosts = this.searchControl.valueChanges .pipe( map((value: any) => { return value ? this.posts .filter(post => post.title.toLowerCase().includes(value.toLowerCase())) : this.posts; }), debounceTime(2500), startWith(this.posts, asyncScheduler), delay(0) ) } }
ac22f76e35a84ff10b9a76ce356c8ed647babb8c
[ "TypeScript" ]
3
TypeScript
Mohamedy74/timeline
959b58bbef1b4ce247cb79ddd25eccf45aa30199
0427a23a81f55e11aa923e462cfc4aaf2e9acf82
refs/heads/master
<repo_name>chenyunli6/rails101-3<file_sep>/app/models/group.rb class Group < ApplicationRecord belongs_to :user has_many :posts has_many :group_relationships has_many :members,through: :group_relationships,source: :user validates :title,presence: true end
add00c075600aac74bbb477c83fd345cb4d66c0d
[ "Ruby" ]
1
Ruby
chenyunli6/rails101-3
747bc3c0f76dc961f2f338862694c62ef9cf1d65
d9db0dc26abf02c3de31dbd358884f5c0ee0c121
refs/heads/master
<repo_name>softwaregravy/google-analytics<file_sep>/Readme.md # google-analytics Query Google Analytics data from node. ## Installation $ npm install segmentio/google-analytics ## Example Create a new Google Analytics instance with a `viewId`, and then login: ```js var ga = require('google-analytics')('67032470'); ga.login('<EMAIL>', '<PASSWORD>', function (err) { // login first }); ``` Then you can query unique visitors: ```js ga.query() .visitors() .weekly() .start(new Date('1/1/2014')) .end(new Date('2/1/2014')) .get(function (err, res) { }); ``` Or form a generic query: ```js ga.query() .dimension('ga:source') .metric('ga:visits') .filter('ga:medium==referral') .segment('segment=gaid::10 OR dynamic::ga:medium==referral') .start(new Date('1/1/2014')) .end(new Date('2/1/2014')) .index(10) .results(100) .get(function (err, res) { // .. }); ``` The [data feed request format](https://developers.google.com/analytics/devguides/reporting/core/v2/gdataReferenceDataFeed) explains the different arguments that can be used in a Google Analytics data request. You can play around with sample requests in the [GA dev tools query explorer](http://ga-dev-tools.appspot.com/explorer/?csw=1). ### Custom Dynamic Segments You can create powerful dynamic segments on demand using [filter operators](https://developers.google.com/analytics/devguides/reporting/core/v3/reference#filterOperators), like so: ```js ga.query() .visitors() .daily() .start(start) .end(end) .segment('dynamic::ga:pagePath==/,ga:pagePath==/signup,ga:pagePath==/pricing,ga:pagePath=@/docs') .get(function (err, res) { if (err) return callback(err); var visitors = res.rows.reduce(function (memo, row) { return memo + parseInt(row[1], 10); }, 0); callback(null, visitors); }); ``` ## License MIT<file_sep>/lib/query.js var Dates = require('date-math'); var debug = require('debug')('google-analytics'); var defaults = require('defaults'); var request = require('superagent'); var util = require('util'); /** * Expose `Query`. */ module.exports = Query; /** * Base URL. */ var url = 'https://www.googleapis.com/analytics/v3/data/ga'; /** * Create a new `Query` operation with `options`. * * @param {String} token * @param {String} viewId * @param {Object} options */ function Query (token, viewId, options) { this.token = token; this.viewId = viewId; this.options = defaults(options, { dimensions: [], metrics: [], filters: [], segment: null, sort: null, start: new Date(), end: Dates.month.shift(new Date(), -1), index: 1, results: 100, pretty: true }); var self = this; // add the dimension shortcut methods Object.keys(this.dimensions).forEach(function (method) { var val = self.dimensions[method]; self[method] = function () { return self.dimension(val); }; }); // add the metric shortcut methods Object.keys(this.metrics).forEach(function (method) { var val = self.metrics[method]; self[method] = function () { return self.metric(val); }; }); } /** * Methods to dimensions map. * @type {Object} */ Query.prototype.dimensions = { minutely: 'ga:minute', hourly: 'ga:hour', date: 'ga:date', daily: 'ga:day', weekly: 'ga:week', monthly: 'ga:month', yearly: 'ga:year' }; /** * Methods to metrics map. * @type {Object} */ Query.prototype.metrics = { visitors: 'ga:visits' }; /** * Set a query dimension. * * @param {String} dimension * @return {Query} */ Query.prototype.dimension = function (dimension) { this.options.dimensions.push(dimension); return this; }; /** * Set a query metric. * * @param {String} metric * @return {Query} */ Query.prototype.metric = function (metric) { this.options.metrics.push(metric); return this; }; /** * Set a query filter. * * @param {String} filter * @return {Query} */ Query.prototype.filter = function (filter) { this.options.filters.push(filter); return this; }; /** * Set a query segment. * * @param {String} segment * @return {Query} */ Query.prototype.segment = function (segment) { this.options.segment = segment; return this; }; /** * Set a query start. * * @param {Date} start * @return {Query} */ Query.prototype.start = function (start) { if (util.isDate(start)) start = dateString(start); this.options.start = start; return this; }; /** * Set a query end. * * @param {Date} end * @return {Query} */ Query.prototype.end = function (end) { if (util.isDate(end)) end = dateString(end); this.options.end = end; return this; }; /** * Set a query number of results to return. * * @param {Number} results * @return {Query} */ Query.prototype.results = function (results) { this.options.results = results; return this; }; /** * Run the Google Analytics query. * * @param {Function} callback * @return {Query} */ Query.prototype.get = function (callback) { // docs: https://developers.google.com/analytics/devguides/reporting/core/v3/reference#startDate var payload = { 'ids': 'ga:' + this.viewId, 'dimensions': this.options.dimensions.join(','), 'metrics': this.options.metrics.join(','), 'filters': this.options.filters.join(','), 'start-date': this.options.start, 'end-date': this.options.end, 'max-results': this.options.results, 'prettyprint': false, 'start-index': this.options.index, }; if (this.options.sort) payload.sort = this.options.sort; if (this.options.segment) payload.segment = this.options.segment; if (this.options.filters) payload.filters = this.options.filters; debug('querying %s ..', payload); request .get(url) .set('Authorization', 'GoogleLogin ' + this.token) .query(payload) .end(function (err, res) { if (err) return callback(err); var json = res.text; debug('finished query [%d]: %s', res.statusCode, json); if (res.statusCode !== 200) return callback(new Error('Bad GA query: ' + json)); try { var parsed = JSON.parse(json); callback(null, parsed); } catch (e) { callback(e); } }); return this; }; /** * Return the GA `date` string. * * @param {Date} date * @return {String} */ function dateString (date) { return [ date.getFullYear(), pad(date.getMonth()+1, 2), pad(date.getDate(), 2) ].join('-'); } /** * Pad the `number` with `width` leading zeros. * * Credit: https://github.com/puckey/pad-number/blob/master/index.js * * @param {Number} number * @param {Number} width * @param {Number} padding * @return {String} */ function pad(number, width, padding) { padding = padding || '0'; number = number + ''; var length = number.length; return !width || length >= width ? '' + number : new Array(width - length + 1).join(padding) + number; }
6e9f2b6a090272a4aeda431f4a578e5ab1122e16
[ "Markdown", "JavaScript" ]
2
Markdown
softwaregravy/google-analytics
399a82609a9c794c383610b537cd14ddb329a454
9f0022600a5fd3fc52eaa8e8838b7690f5376afe
refs/heads/main
<repo_name>patrik1300/FGMap<file_sep>/Frisbeegolf sovellus/JSON/radat.js 'use strict' const radat = [ { "course_id": "2855", "name": "<NAME>", "holes": "9", "city": "Espoo", "state": "0", "country": "Finland", "zipcode": "", "latitude": "60.304760", "longitude": "24.550881", "street_addr": "", "reviews": "0", "rating": "0.00", "private": "1", "paytoplay": "1", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=2855", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=2855", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" }, { "course_id": "2856", "name": "<NAME>", "holes": "18", "city": "Espoo", "state": "0", "country": "Finland", "zipcode": "02740", "latitude": "60.240243", "longitude": "24.662271", "street_addr": "Kunnarlantie 33 - 39", "reviews": "1", "rating": "2.50", "private": "0", "paytoplay": "0", "tee_1_clr": "", "tee_2_clr": "00FF00", "tee_3_clr": "", "tee_4_clr": "", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=2856", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=2856", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_2.5.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_2.5.png" }, { "course_id": "8463", "name": "<NAME>", "holes": "14", "city": "Espoo", "state": "0", "country": "Finland", "zipcode": "02210", "latitude": "60.176613", "longitude": "24.697868", "street_addr": "Puolarmaari 12", "reviews": "0", "rating": "0.00", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=8463", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=8463", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" }, { "course_id": "10256", "name": "<NAME>", "holes": "3", "city": "Espoo", "state": "0", "country": "Finland", "zipcode": "02180", "latitude": "60.196100", "longitude": "24.753000", "street_addr": "Taavilantie 19", "reviews": "0", "rating": "0.00", "private": "0", "paytoplay": "0", "tee_1_clr": "", "tee_2_clr": "FFFFFF", "tee_3_clr": "", "tee_4_clr": "", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=10256", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=10256", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" }, { "course_id": "10255", "name": "Vasikkasaari", "holes": "9", "city": "Espoo", "state": "0", "country": "Finland", "zipcode": "02230", "latitude": "60.140600", "longitude": "24.758700", "street_addr": "Iso Vasikkasaari", "reviews": "0", "rating": "0.00", "private": "0", "paytoplay": "0", "tee_1_clr": "", "tee_2_clr": "FFFFFF", "tee_3_clr": "", "tee_4_clr": "", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=10255", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=10255", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" }, { "course_id": "9261", "name": "<NAME>", "holes": "6", "city": "Helsinki", "state": "0", "country": "Finland", "zipcode": "00320", "latitude": "60.214000", "longitude": "24.889600", "street_addr": "Isonnevantie", "reviews": "1", "rating": "0.50", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=9261", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=9261", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.5.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.5.png" }, { "course_id": "7409", "name": "<NAME>", "holes": "6", "city": "Helsinki", "state": "0", "country": "Finland", "zipcode": "00320", "latitude": "60.214000", "longitude": "24.889600", "street_addr": "Isonnevantie", "reviews": "0", "rating": "0.00", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=7409", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=7409", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" }, { "course_id": "5456", "name": "<NAME>", "holes": "6", "city": "Helsinki", "state": "0", "country": "Finland", "zipcode": "", "latitude": "60.214761", "longitude": "24.891565", "street_addr": "Isonnevantie 00320", "reviews": "1", "rating": "0.00", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=5456", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=5456", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" }, { "course_id": "11215", "name": "<NAME>", "holes": "18", "city": "Helsinki", "state": "0", "country": "Finland", "zipcode": "00860 ", "latitude": "60.151300", "longitude": "25.054800", "street_addr": "Santahamina", "reviews": "0", "rating": "0.00", "private": "1", "paytoplay": "1", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=11215", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=11215", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" }, { "course_id": "5741", "name": "Kivikko", "holes": "18", "city": "Helsinki", "state": "0", "country": "Finland", "zipcode": "00940", "latitude": "60.238300", "longitude": "25.056300", "street_addr": "Savikiekontie 8", "reviews": "3", "rating": "3.17", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=5741", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=5741", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_3.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_3.png" }, { "course_id": "2162", "name": "Meilahti", "holes": "16", "city": "Helsinki", "state": "0", "country": "Finland", "zipcode": "", "latitude": "60.190449", "longitude": "24.897487", "street_addr": "", "reviews": "5", "rating": "2.40", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "", "tee_3_clr": "", "tee_4_clr": "", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=2162", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=2162", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_2.5.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_2.5.png" }, { "course_id": "2174", "name": "Munkkiniemi", "holes": "9", "city": "Helsinki", "state": "0", "country": "Finland", "zipcode": "", "latitude": "60.199846", "longitude": "24.869571", "street_addr": "", "reviews": "2", "rating": "0.75", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=2174", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=2174", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_1.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_1.png" }, { "course_id": "2862", "name": "Savela", "holes": "4", "city": "Helsinki", "state": "0", "country": "Finland", "zipcode": "", "latitude": "60.238597", "longitude": "24.998446", "street_addr": "", "reviews": "1", "rating": "0.50", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=2862", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=2862", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.5.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.5.png" }, { "course_id": "2863", "name": "<NAME>", "holes": "18", "city": "Helsinki", "state": "0", "country": "Finland", "zipcode": "00740", "latitude": "60.272961", "longitude": "24.981837", "street_addr": "Pallomäentie", "reviews": "3", "rating": "2.17", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "", "tee_3_clr": "", "tee_4_clr": "", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=2863", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=2863", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_2.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_2.png" }, { "course_id": "2161", "name": "<NAME>", "holes": "18", "city": "Helsinki", "state": "0", "country": "Finland", "zipcode": "", "latitude": "60.213045", "longitude": "24.847212", "street_addr": "", "reviews": "4", "rating": "3.88", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=2161", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=2161", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_4.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_4.png" }, { "course_id": "11167", "name": "Kartanonkoski ", "holes": "9", "city": "Vantaa", "state": "0", "country": "Finland", "zipcode": "01520 ", "latitude": "60.279200", "longitude": "24.956300", "street_addr": "TIlkuntie 9", "reviews": "0", "rating": "0.00", "private": "0", "paytoplay": "0", "tee_1_clr": "", "tee_2_clr": "FFFFFF", "tee_3_clr": "", "tee_4_clr": "", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=11167", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=11167", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" }, { "course_id": "9264", "name": "<NAME>", "holes": "9", "city": "Vantaa", "state": "0", "country": "Finland", "zipcode": "01350", "latitude": "60.315800", "longitude": "25.041100", "street_addr": "Malminiityntie 11", "reviews": "1", "rating": "1.00", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "", "tee_3_clr": "", "tee_4_clr": "", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=9264", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=9264", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_1.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_1.png" }, { "course_id": "11229", "name": "<NAME>", "holes": "3", "city": "Vantaa", "state": "0", "country": "Finland", "zipcode": "01480 ", "latitude": "60.341900", "longitude": "25.091900", "street_addr": "Lyyranpolku", "reviews": "0", "rating": "0.00", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=11229", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=11229", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" }, { "course_id": "2923", "name": "Päiväkumpu", "holes": "10", "city": "Vantaa", "state": "0", "country": "Finland", "zipcode": "01420", "latitude": "60.325222", "longitude": "25.104049", "street_addr": "Ilosjoentie", "reviews": "1", "rating": "2.00", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=2923", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=2923", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_2.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_2.png" }, { "course_id": "2924", "name": "Simonmetsä", "holes": "10", "city": "Vantaa", "state": "0", "country": "Finland", "zipcode": "01350", "latitude": "60.305844", "longitude": "25.028486", "street_addr": "", "reviews": "1", "rating": "2.50", "private": "0", "paytoplay": "0", "tee_1_clr": "FFFFFF", "tee_2_clr": "", "tee_3_clr": "", "tee_4_clr": "", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=2924", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=2924", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_2.5.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_2.5.png" }, { "course_id": "10258", "name": "Varistonniityn", "holes": "18", "city": "Vantaa", "state": "0", "country": "Finland", "zipcode": "01660", "latitude": "60.274000", "longitude": "24.821800", "street_addr": "Rystypolku 6", "reviews": "1", "rating": "4.50", "private": "0", "paytoplay": "0", "tee_1_clr": "", "tee_2_clr": "FFFFFF", "tee_3_clr": "", "tee_4_clr": "", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=10258", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=10258", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_4.5.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_4.5.png" }, { "course_id": "10257", "name": "<NAME>", "holes": "9", "city": "Kauniainen", "state": "0", "country": "Finland", "zipcode": "02700", "latitude": "60.216200", "longitude": "24.718000", "street_addr": "Student Education 11", "reviews": "0", "rating": "0.00", "private": "0", "paytoplay": "0", "tee_1_clr": "", "tee_2_clr": "FFFFFF", "tee_3_clr": "", "tee_4_clr": "", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=10257", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=10257", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" } ]<file_sep>/Frisbeegolf sovellus/JSON/EspoonRadat.js 'use strict' const EspoonRadat = [ { "course_id": "2855", "name": "<NAME>", "holes": "9", "city": "Espoo", "state": "0", "country": "Finland", "zipcode": "", "latitude": "60.304760", "longitude": "24.550881", "street_addr": "", "reviews": "0", "rating": "0.00", "private": "1", "paytoplay": "1", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=2855", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=2855", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" }, { "course_id": "2856", "name": "<NAME>", "holes": "18", "city": "Espoo", "state": "0", "country": "Finland", "zipcode": "02740", "latitude": "60.240243", "longitude": "24.662271", "street_addr": "Kunnarlantie 33 - 39", "reviews": "1", "rating": "2.50", "private": "0", "paytoplay": "0", "tee_1_clr": "", "tee_2_clr": "00FF00", "tee_3_clr": "", "tee_4_clr": "", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=2856", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=2856", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_2.5.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_2.5.png" }, { "course_id": "8463", "name": "<NAME>", "holes": "14", "city": "Espoo", "state": "0", "country": "Finland", "zipcode": "02210", "latitude": "60.176613", "longitude": "24.697868", "street_addr": "Puolarmaari 12", "reviews": "0", "rating": "0.00", "private": "0", "paytoplay": "0", "tee_1_clr": "FF0000", "tee_2_clr": "FFFFFF", "tee_3_clr": "0000CC", "tee_4_clr": "FFCC00", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=8463", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=8463", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" }, { "course_id": "10256", "name": "<NAME>", "holes": "3", "city": "Espoo", "state": "0", "country": "Finland", "zipcode": "02180", "latitude": "60.196100", "longitude": "24.753000", "street_addr": "Taavilantie 19", "reviews": "0", "rating": "0.00", "private": "0", "paytoplay": "0", "tee_1_clr": "", "tee_2_clr": "FFFFFF", "tee_3_clr": "", "tee_4_clr": "", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=10256", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=10256", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" }, { "course_id": "10255", "name": "Vasikkasaari", "holes": "9", "city": "Espoo", "state": "0", "country": "Finland", "zipcode": "02230", "latitude": "60.140600", "longitude": "24.758700", "street_addr": "Iso Vasikkasaari", "reviews": "0", "rating": "0.00", "private": "0", "paytoplay": "0", "tee_1_clr": "", "tee_2_clr": "FFFFFF", "tee_3_clr": "", "tee_4_clr": "", "dgcr_url": "https://www.dgcoursereview.com/course.php?id=10255", "dgcr_mobile_url": "https://www.dgcoursereview.com/mobile/course.php?id=10255", "rating_img": "https://www.dgcoursereview.com/images/rating/discs_0.png", "rating_img_small": "https://www.dgcoursereview.com/images/rating/discs_sm_0.png" } ]
f65c620252aaff43f044b2c4e46bf72c26d99abc
[ "JavaScript" ]
2
JavaScript
patrik1300/FGMap
2463ff1aaf4f96890495e20a81278d8cbc496beb
0a3fd430ca52defae199ba6b731dbf3c663be968
refs/heads/master
<file_sep># SpamFilters Developed SpamFIlter to calculate. Given email containing all keywords and probability of that email is spam . <file_sep>import java.io.Console; import java.util.Scanner; public class SpamFilter { public static void main(String[ ] args) { for (String s: args) { System.out.println(s); } Scanner in = new Scanner(System.in); String[ ] name1 = { "#1", "100% satisfied", "4U", "Accept credit cards", "Act Now!", "Additional Income", "Affordable", "All natural", "All new", "Amazing", "Apply online", "Bargain", "Best price", "Billing address", "Buy direct", "Call", "Call free", "Can't live without","Cards Accepted", "Cents on the dollor", "Check", "Claims", "Click / Click Here / Click Below","Click to remove", "Compare rates", "Congratulation", "Cost / No cost", "Dear friend", "Do it today", "Extra income", "For free", "Form", "Free and FREE", "Free installation", "Free leads", "Free membership", "Free offer", "Free preview", "Free website", "Full refund", "Get it now", "Giving away", "Guarantee", "Here", "Hidden", "Increase sales", "Increase traffic", "Information you requensted", "Insurance", "Investment / no investment", "Investment decision", "Legal", "Lose", "Marketing", "Marketing solution", "Message contains", "Money", "Month trial offer", "Name brand","Never", "No gimmicks", "No Hidden Costs", "No-obligation", "Now", "Offer", "One time / one-time","Opportunity", "Order / Order Now / Order today /Order status", "Orders shipped by priority mail", "Performance", "Phone", "Please read", "potential earnings", "Pre-approved", "Price", "Print out and fax" , "Profits", "Real thing", "Removal instruction", "Remove", "Risk free", "Sales", "Satisfaction guranteed", "Save $", "Save up to", "Search engines","See for yourself", "Serious cash", "Solution", "Special promotion", "Success", "The following form", "Unsolicited", "Unsubscribe", "Urgent", "Us dollars", "Wife", "Wing", "Winner", "Work at home"}; System.out.print("How many Keyword you want to check = "); int n = Integer.parseInt(in.nextLine()); String[] name=new String[n] ; System.out.println(name.length); for(int j = 0;j<n;j++ ) { name[j] = in.nextLine(); } double cal=1;; double N=100; int size=name.length; double probabilityofthatemailisSpam=0.05; double probabilityofthatemailconationsKeywordI=0; double theprobabilitythattheemailcontainsthekeywordI=0; double probabilityofthatemailisspamWithKeywordI=0; int i = 0; for ( i = 0; i < name1.length; i++) { for(int j = 0;j<name.length;j++ ) { if(name1[i].equals(name[j])) { probabilityofthatemailconationsKeywordI = ((i % (N/20)) +size)/(N/20 +size ) ; theprobabilitythattheemailcontainsthekeywordI = ((i % (N/10)) + 1)/(N/10 +1); probabilityofthatemailisspamWithKeywordI = probabilityofthatemailconationsKeywordI * probabilityofthatemailisSpam / theprobabilitythattheemailcontainsthekeywordI; System.out.println(name1[i]+ " is at :" +i); cal = cal * probabilityofthatemailisspamWithKeywordI; } } } System.out.println("Given email containing all keywords and probability of that email is spam is = "+cal); } }
13037aa00a5a718e05211b4302ee65f74288b95d
[ "Markdown", "Java" ]
2
Markdown
jaypatel3/SpamFilters
125a57d2dc9277075e1918e8e9eb59676e21ebe8
8a99944acc870f30779eac341f3b76218ef96c70
refs/heads/master
<file_sep>import { Config, KubeConfig, Core_v1Api, V1ConfigMap } from '@kubernetes/typescript-node'; import * as fs from 'fs'; import * as path from 'path'; import * as requestPromise from 'request-promise-native'; import * as retry from 'bluebird-retry'; // Retry rate limited kubeapi calls const retryOnRateLimit = { predicate: err => err.statusCode && err.statusCode == 429, retryInterval: 500 + (Math.random() - 0.5) * 500, retryCount: 15, retryBackoff: 2, }; class ManualRequestAuthenticator { public applyToRequest: (request) => void; constructor(public basePath: string) {} setDefaultAuthentication(auth: { applyToRequest: (request) => void}) { this.applyToRequest = (request) => auth.applyToRequest(request); } } type KubeApi = { new(basePath?: string): { setDefaultAuthentication(auth: { applyToRequest: (request) => void }) }; }; export class K8sLock { public static SERVICEACCOUNT_ROOT = '/var/run/secrets/kubernetes.io/serviceaccount'; public static SERVICEACCOUNT_CA_PATH = Config.SERVICEACCOUNT_ROOT + '/ca.crt'; public static SERVICEACCOUNT_TOKEN_PATH = Config.SERVICEACCOUNT_ROOT + '/token'; private readonly coreApi: Core_v1Api; private readonly authenticator: ManualRequestAuthenticator; constructor() { [this.coreApi, this.authenticator] = K8sLock.defaultClient([ Core_v1Api, ManualRequestAuthenticator ]); } public static fromFile(filename: string) { let kc = new KubeConfig(); kc.loadFromFile(filename); return (apiClass: KubeApi) => { const api = new apiClass(kc.getCurrentCluster()['server']); api.setDefaultAuthentication(kc); return api; } } public static fromCluster() { let host = process.env.KUBERNETES_SERVICE_HOST let port = process.env.KUBERNETES_SERVICE_PORT // TODO: better error checking here. let caCert = fs.readFileSync(Config.SERVICEACCOUNT_CA_PATH); let token = fs.readFileSync(Config.SERVICEACCOUNT_TOKEN_PATH); return (apiClass: KubeApi) => { const api = new apiClass('https://' + host + ':' + port); api.setDefaultAuthentication({ 'applyToRequest': (opts) => { opts.ca = caCert; opts.headers['Authorization'] = 'Bearer ' + token; } }); return api; } } public static defaultClient(apiClasses: KubeApi[]) { let loader; if (process.env.KUBECONFIG) { loader = K8sLock.fromFile(process.env.KUBECONFIG); } let config = path.join(process.env.HOME, ".kube", "config"); if (fs.existsSync(config)) { loader = K8sLock.fromFile(config); } if (fs.existsSync(Config.SERVICEACCOUNT_TOKEN_PATH)) { loader = K8sLock.fromCluster(); } return apiClasses.map(apiClass => { return loader(apiClass); }); } async aquireLock( namespace: string, lockName: string, leaserName: string, ) { // Check if lock is held by other person let configMap: V1ConfigMap; try { let result = await retry(() => this.coreApi.readNamespacedConfigMap(lockName, namespace), retryOnRateLimit); configMap = result.body; } catch (e) { if (e.body.reason === 'NotFound') { await retry(() => this.coreApi.createNamespacedConfigMap(namespace, { kind: 'ConfigMap', apiVersion: 'v1', metadata: { name: lockName, } as any, data: { locked: leaserName } }), retryOnRateLimit); return true; } throw new Error(e.body.message); } const isLocked = configMap.data['locked'] !== 'false'; if (isLocked) { return false; } // Try to aquire lock const opts = { method: 'PATCH', uri: `${this.authenticator.basePath}/api/v1/namespaces/${namespace}/configmaps/${lockName}`, json: [ { "op": "replace", "path": "/data/locked", "value": "false" }, { "op": "replace", "path": "/metadata/resourceVersion", "value": configMap.metadata.resourceVersion } ], headers: { 'Content-Type': 'application/json-patch+json' } }; this.authenticator.applyToRequest(opts); await retry(() => requestPromise(opts), retryOnRateLimit); return true; } async releaseLock( namespace: string, lockName: string, leaserName: string, ) { const { body } = await retry(() => this.coreApi.readNamespacedConfigMap(lockName, namespace), retryOnRateLimit); const isLockedByUs = body.data['locked'] === leaserName; if (!isLockedByUs) { throw new Error('Cannot release lock that is not held by us. Current leaser is' + body.data['locked']); } // Release lock const opts = { method: 'PATCH', uri: `${this.authenticator.basePath}/api/v1/namespaces/${namespace}/configmaps/${lockName}`, json: [ { "op": "replace", "path": "/data/locked", "value": "false" }, { "op": "replace", "path": "/metadata/resourceVersion", "value": body.metadata.resourceVersion } ], headers: { 'Content-Type': 'application/json-patch+json' } }; this.authenticator.applyToRequest(opts); await retry(() => requestPromise(opts), retryOnRateLimit); return true; } }<file_sep># Node Library for distributed locks utilizing a Kubernetes Cluster<file_sep>#!/usr/bin/env bash set -e source tests/k8s-euft/env.bash yarn yarn test echo "All tests passed :)" <file_sep>import * as bluebird from 'bluebird'; /** * Calls the op function repeatedly until it resolves with a truthy value. * Returns a promise that resolves with that value or errors on timeout. * * @param op operation to perform * @param delay polling interval * @param timeout timeout */ export function repeatUntilSuccessful<T>( op: (...args: any[]) => Promise<T | false> | T | false, delay: number, timeout: number, backoff?: boolean ): Promise<T> { let timedOut = false; let delayWithBackoff = delay; function repeater(): Promise<T> { if (timedOut) { return; } return Promise.resolve().then(op) .then((success) => { if (!success) { return bluebird.delay(delayWithBackoff) .then(() => { if (backoff) { delayWithBackoff *= 1.5; } return repeater() }); } return success; }); } let promise = bluebird.resolve().then(repeater); if (timeout) { promise = promise.timeout(timeout) .catch(bluebird.TimeoutError, (error) => { timedOut = true; throw error; // Rethrow }); } return Promise.resolve(promise); } <file_sep>import 'mocha'; import { K8sLock } from '../src'; import { expect } from './expect'; import { exec } from 'child-process-promise'; describe('K8sLock', () => { beforeEach(async () => { await exec('kubectl delete configmap testlock.com --ignore-not-found=true'); }) after(async () => { await exec('kubectl delete configmap testlock.com --ignore-not-found=true'); }) it('should get a lock when no configmap exists', async () => { const k8sLock = new K8sLock(); const success = await k8sLock.aquireLock('default', 'testlock.com', 'test'); expect(success).to.be.true; }) it('should get and release a lock', async () => { const k8sLock = new K8sLock(); expect(await k8sLock.aquireLock('default', 'testlock.com', 'test')).to.be.true; expect(await k8sLock.releaseLock('default', 'testlock.com', 'test')).to.be.true; }) it('should reaquire a lock after releasing', async () => { const k8sLock = new K8sLock(); expect(await k8sLock.aquireLock('default', 'testlock.com', 'test')).to.be.true; expect(await k8sLock.releaseLock('default', 'testlock.com', 'test')).to.be.true; expect(await k8sLock.aquireLock('default', 'testlock.com', 'test')).to.be.true; }) it('should return false when lock is locked', async () => { const k8sLock = new K8sLock(); expect(await k8sLock.aquireLock('default', 'testlock.com', 'test')).to.be.true; expect(await k8sLock.aquireLock('default', 'testlock.com', 'test')).to.be.false; }) });
6d25ca6b0f188d2f0e6dfc9844a6dda6444abb52
[ "Markdown", "TypeScript", "Shell" ]
5
TypeScript
Kamshak/k8s-lock
cdcdddb8f85eee8332eb993375901185443311f6
0ba83c5ca53c4bd78d6db42b5c72dc161f9f1866
refs/heads/main
<file_sep>from django.urls import path from app2 import views app_name='app2' urlpatterns=[ path('second/',views.second,name='second'), ]<file_sep>from django.shortcuts import render # Create your views here. # content of views.py file def first(request): return render(request,'app1/first.html',context={'name':'Ashu','age':2})<file_sep>from django.urls import path from app1 import views app_name='app1' urlpatterns=[ path('first/',views.first,name='first'), ]
9ec6e64e30e703c8fd951044ae35f3255c98fbb2
[ "Python" ]
3
Python
harshadvali11/specific_template
51fc926f558a3238f6e5629b8b35b6034da9ce91
85bc5bc3cc8a75dfde2f2c6266b7a614bf1972cf
refs/heads/master
<file_sep>fab - Show your output fabulous!! ======================================= Package `fab` was *heavily* inspired by [whatthejeff/fab](https://github.com/whatthejeff/fab). # Status [![Build Status](https://travis-ci.org/ympons/go-fab.png?branch=master)](https://travis-ci.org/ympons/go-fab) # Installation ``` go get -v github.com/ympons/go-fab ``` # Documentation See [GoDoc](http://godoc.org/github.com/ympons/go-fab) or [Go Walker](http://gowalker.org/github.com/ympons/go-fab) for automatically generated documentation. # Example ```go fab := fab.NewSuperFab() fmt.Println(fab.Paint("Making my outputs fabulous!!!")) ``` <file_sep>// Package fab shows your output fabulous!! package fab import ( "bytes" "fmt" "math" "regexp" ) const ( // Start an escape sequence ESC = "\x1b[" // End the escape sequence NND = "\x1b[0m" ) // The Fabulous struct type Fab struct { colors []int count int index int pattern string } // Initializes a new Fab with an optional custom color range func NewFab(c ...int) *Fab { fab := &Fab{pattern: "%s%dm%c%s"} if c == nil { fab.colors = []int{31, 32, 33, 34, 35, 36} } else { fab.colors = append(fab.colors, c...) } fab.count = len(fab.colors) return fab } // Initializes a new Fab with colors appropiate for terminals capable of // displaying 256 colors. func NewSuperFab() *Fab { pi3 := math.Pi / 3 colors := make([]int, 0, 42) // https://github.com/seattlerb/minitest/blob/4373fc7ebf648e156902958466cc4678945eac29/lib/minitest/pride.rb#L78-L96 for c, n := 0.0, 0.0; c <= 42.0; c += 1.0 { n = c * (1.0 / 6) r := (int)(3*math.Sin(n) + 3) g := (int)(3*math.Sin(n+2*pi3) + 3) b := (int)(3*math.Sin(n+4*pi3) + 3) colors = append(colors, 36*r+6*g+b+16) } fab := NewFab(colors...) fab.pattern = "%s38;5;%dm%c%s" return fab } // Paints a string with fabulous colors. func (f *Fab) Paint(s string) string { if len(s) == 0 { return "" } var r bytes.Buffer for _, c := range s { fmt.Fprintf(&r, f.pattern, ESC, f.nextColor(), c, NND) } return r.String() } func (f *Fab) nextColor() int { color := f.colors[f.index%f.count] f.index++ return color } // Gets a proper Fab for a provided terminal emulator. func GetFab(term string) *Fab { p, _ := regexp.Compile(`^xterm|-256color$`) if p.MatchString(term) { return NewSuperFab() } return NewFab() } <file_sep>package fab import ( "testing" "github.com/stretchr/testify/assert" ) func TestFabCustomColors(t *testing.T) { fab := NewFab(31, 32) assert := assert.New(t) assert.Equal("\x1b[31mh\x1b[0m\x1b[32më\x1b[0m\x1b[31ml\x1b[0m\x1b[32ml\x1b[0m\x1b[31mõ\x1b[0m", fab.Paint("hëllõ"), "they should be equal") } func TestFabPaintChar(t *testing.T) { fab := NewFab() assert := assert.New(t) assert.Equal("\x1b[31mh\x1b[0m\x1b[32më\x1b[0m\x1b[33ml\x1b[0m\x1b[34ml\x1b[0m\x1b[35mõ\x1b[0m", fab.Paint("hëllõ"), "they should be equal") } func TestSuperFabPaintChar(t *testing.T) { fab := NewSuperFab() assert := assert.New(t) assert.Equal("\x1b[38;5;154mh\x1b[0m\x1b[38;5;154më\x1b[0m\x1b[38;5;148ml\x1b[0m\x1b[38;5;184ml\x1b[0m\x1b[38;5;184mõ\x1b[0m", fab.Paint("hëllõ"), "they should be equal") }
d0f240e77f42db7d523fb5e59250fbb2c11da4cd
[ "Markdown", "Go" ]
3
Markdown
ympons/go-fab
146bcbc4831d76d37ac9c86c7857d3f221624cb1
59944749fa7dca4761f677f70cc19cf97ad4c7f1
refs/heads/main
<file_sep>//Handle login button event document.getElementById("login-submit").addEventListener('click', function () { // Get user email const emailField = document.getElementById("email-field"); const userEmail = emailField.value; // Get user password const passwordField = document.getElementById("password-field"); const userPassword = passwordField.value; // Verified user checking if (userEmail == '<EMAIL>' && userPassword == '<PASSWORD>') { window.location.href = 'banking.html'; } else { document.getElementById("error-throw").innerText = "Invalid user. Please login into a verified account"; } })
36e5a2aa408eeb07df7d00fd51f7b50c325a5f97
[ "JavaScript" ]
1
JavaScript
mubashwirphero1/functional-bank
00566147c106cc709fd4f2444cb5f5c0b194f1aa
e11363b63e195ee64a2cb01fba9ded73b4885331
refs/heads/master
<repo_name>julenvitoria/FreeplayGBA-TempIndicatorAddon<file_sep>/InstallTempIndicator.sh #!/bin/bash cd /home/pi #HACEMOS UPDATE Y UPGRADE PARA TENER EL SISTEMA ACTUALIZADO sudo apt update && sudo apt upgrade -y #CLONAMOS EL SCRIPT DE TEMPERATURA, INSTALAMOS SUS DEPENDENCIAS, CAMBIAMOS EL SCRIPT POR OTRO #MODIFICADO PARA LA GBA Y CAMBIAMOS TAMBIEN EL CRONTAB PARA QUE LO CARGUE EN EL ARRANQUE git clone https://github.com/LuisDiazUgena/temperatureMonitor sudo apt install -y libpng-dev python-gpiozero python-pkg-resources python3-pkg-resources build-essential python-dev python-smbus python-pip sudo chmod 755 /home/pi/temperatureMonitor/Pngview/pngview #cd /home/pi/FreeplayGBAcm3Addons wget -O- https://raw.githubusercontent.com/julenvitoria/FreeplayGBA-TempIndicatorAddon/master/tempMonitor.py>/home/pi/temperatureMonitor/tempMonitor.py wget -O- https://raw.githubusercontent.com/julenvitoria/FreeplayGBA-TempIndicatorAddon/master/mycron>/home/pi/temperatureMonitor/mycron crontab /home/pi/temperatureMonitor/mycron if [ -f /home/pi/temperatureMonitor/tempMonitor.py ]; then echo "SHUTTING DOWN... PLEASE POWER ON BEFORE" sleep 1 echo "SHUTTING DOWN... PLEASE POWER ON BEFORE" sleep 1 echo "SHUTTING DOWN... PLEASE POWER ON BEFORE" sleep 1 echo "SHUTTING DOWN... PLEASE POWER ON BEFORE" sleep 1 echo "SHUTTING DOWN... PLEASE POWER ON BEFORE" sleep 1 echo "SHUTTING DOWN... PLEASE POWER ON BEFORE" sleep 1 echo "SHUTTING DOWN... PLEASE POWER ON BEFORE" sleep 1 echo "SHUTTING DOWN... PLEASE POWER ON BEFORE" sleep 1 sudo poweroff else echo "SCRIPT WAS NOT INSTALLED PROPERLY" sleep 5 fi <file_sep>/README.md # FreeplayGBA-TemperatureIndicator Repo for Temperature Indicator script based on [the original by LuisDiazUgena](https://github.com/LuisDiazUgena/temperatureMonitor) How to install Connect via ssh or insert this command via terminak on your freeplay wget -O- https://raw.githubusercontent.com/julenvitoria/FreeplayGBA-TempIndicatorAddon/master/InstallTempIndicator.sh | bash NOTE: IT'S NECCESARY THAT YOUR GBA HAS INTERNET CONNECTION. THIS SCRIPT WORKS WITH ABSOLUTE PATHS.
d552a431a396b88dd2c1aba03f6436787db84e8e
[ "Markdown", "Shell" ]
2
Shell
julenvitoria/FreeplayGBA-TempIndicatorAddon
33ebbdf0ad54b4a07663a911cc0a92e0a3c02148
d44aabb252d610fed792c3785f01a3f3eaeca874