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>PhamGiaHung/Java<file_sep>/Algorithm/src/com/pgh/QuickSort.java package com.pgh; public class QuickSort { int[] A = {35, 33, 42, 10, 14, 19, 27, 44, 26, 31}; int left = 0; int right = A.length - 1; public void QuickSort() { quickSort(A, left, right); } private void quickSort(int[] A, int left, int right) { int a = partition(A, left, right); if (left == (a - 1)) { if (A[left] >= A[a]) { int b = A[a]; A[a] = A[left]; A[left] = b; } } else { quickSort(A, left, a - 1); quickSort(A, a + 1, right); } } private int partition(int[] A, int left, int right) { int X = A[right]; int i = left; int j = right - 1; do { while ((i <= j) && A[i] <= X) i++; while ((i <= j) && A[j] >= X) { j--; if (j == 0) break; } if (i > j) break; if (A[i] >= X && A[j] <= X) { int mid = A[i]; A[i] = A[j]; A[j] = mid; i++; j--; } } while (i < j); int m = A[i]; A[i - 1] = X; A[right] = m; return j; } } <file_sep>/Algorithm/src/com/pgh/Main.java package com.pgh; public class Main { public static void main(String[] args) { // QuickSort quickSort = new QuickSort(); // quickSort.QuickSort(); BubbleSort bubbleSort = new BubbleSort(); bubbleSort.BubbleSort(); } }
d584e8d9ca3f2acdafda65f526abb0267e064d01
[ "Java" ]
2
Java
PhamGiaHung/Java
1a4f9b9abb35d61ec3b910a0e744b4b25a5c5310
9adcc48575dbde0ddf8108b753f415ef3a95d24f
refs/heads/master
<repo_name>gulp-cookery/gulp-ccr-browserify<file_sep>/index.js /* eslint camelcase: 0 */ 'use strict'; var schema = { title: 'browserify', description: 'Bundle JavaScript things with Browserify.', definitions: { options: { properties: { basedir: { description: 'The directory that browserify starts bundling from for filenames that start with.', type: 'path' }, builtins: { description: 'Sets the list of built-ins to use, which by default is set in lib/builtins.js in this distribution.', type: 'array', items: { type: 'string' } }, bundleExternal: { description: 'Boolean option to set if external modules should be bundled. Defaults to true.', type: 'boolean', default: true }, commondir: { description: 'Sets the algorithm used to parse out the common paths. Use false to turn this off, otherwise it uses the commondir module.', type: ['string', 'boolean'] }, detectGlobals: { description: 'Scan all files for process, global, __filename, and __dirname, defining as necessary. With this option npm modules are more likely to work but bundling takes longer. Default true.', type: 'boolean', default: true }, exclude: { note: 'Browserify options do not support `excludes`, we forward this to browserify.exclude().', description: 'Prevent the module name or file at file from showing up in the output bundle.', alias: ['excludes'], type: 'array', items: { type: 'string' } }, extensions: { description: 'An array of optional extra extensions for the module lookup machinery to use when the extension has not been specified. By default browserify considers only .js and .json files in such cases.', alias: ['extension'], type: 'array', items: { type: 'string' } }, external: { note: 'Browserify options do not support `externals`, we forward this to browserify.external().', description: 'Prevent the module or bundle from being loaded into the current bundle, instead referencing from another bundle.', alias: ['externals'], type: 'array', items: { anyOf: [{ type: 'string' }, { type: 'object', properties: { basedir: { type: 'path' }, file: { type: 'string' } } }] } }, externalRequireName: { description: 'Defaults to `require` in expose mode but you can use another name.', type: 'string', default: 'require' }, fullpaths: { description: 'Disables converting module ids into numerical indexes. This is useful for preserving the original paths that a bundle was generated with.' }, ignore: { note: 'Browserify options do not support `ignores`, we forward this to browserify.ignore().', description: 'Prevent the module name or file at file from showing up in the output bundle.', alias: ['ignores'], type: 'array', items: { type: 'string' } }, insertGlobals: { description: 'Insert `process`, `global`, `__filename`, and `__dirname` without analyzing the AST for faster builds but larger output bundles. Default false.', type: 'boolean', default: false }, insertGlobalVars: { description: 'Override the default inserted variables, or set `insertGlobalVars[name]` to `undefined` to not insert a variable which would otherwise be inserted.' }, noParse: { description: "An array which will skip all `requires` and global parsing for each file in the array. Use this for giant libs like jQuery or threejs that don't have any requires or node-style globals but take forever to parse.", alias: ['noparse'] }, paths: { description: 'An array of directories that browserify searches when looking for modules which are not referenced using relative path. Can be absolute or relative to basedir.', alias: ['path'], type: 'array', items: { type: 'string' } }, plugin: { note: 'Although the options `plugin` is processed properly in constructor of browserify, we still process it explicitly for clarity and make sure plugins are registered before transforms.', description: 'Register plugins.', alias: ['plugins'], type: 'array', items: { type: 'string' } }, require: { note: 'Although the options `require` is processed properly in constructor of browserify, we still process it explicitly for clarity.', description: "Make module available from outside the bundle. The module name is anything that can be resolved by require.resolve(). Use an object with `file` and `expose` property to specify a custom dependency name. `{ file: './vendor/angular/angular.js', options: { expose: 'angular' } }` enables `require('angular')`", alias: ['requires'], type: 'array', items: { anyOf: [{ type: 'string' }, { type: 'object', properties: { file: { type: 'string' }, options: { type: 'object', properties: { basedir: { description: 'The directory that starts searching from for filenames that start with.', type: 'path' }, entry: { description: 'Make the module an entry.', type: 'boolean', default: false }, expose: { description: 'Specify a custom dependency name for the module.', type: 'string' }, external: { note: 'Distingish this option with browserify.external().', description: 'Prevent the module from being loaded into the current bundle, instead referencing from another bundle.', type: 'boolean', default: false }, transform: { note: 'Distingish this option with browserify.option.transform.', description: 'Allow the module to be transformed.', type: 'boolean', default: true } } } } }] } }, sourcemaps: { note: 'Browserify options do not support `sourcemaps`, it uses `debug` for this, we make this clear by name it `sourcemaps` and add option to write external source map file.', description: 'Add a source map inline to the end of the bundle or separate source map to external file. This makes debugging easier because you can see all the original files if you are in a modern enough browser.', alias: ['sourcemap'], anyOf: [{ type: 'string' }, { type: 'boolean' }], default: false }, standalone: { description: 'Create a standalone module with this given name and a umd wrapper. You can use namespaces in the standalone global export using a . in the string name as a separator, for example `A.B.C`. The global export will be sanitized and camel cased.', type: 'string' }, transform: { note: 'Although the options `transform` is processed properly in constructor of browserify, we still process it explicitly for clarity and make sure plugins are registered before transforms.', description: 'Register transforms.', alias: ['transforms'], type: 'array', items: { type: 'string' } }, uglify: { description: 'Uglify bundle file.', anyOf: [{ type: 'boolean', default: false }, { type: 'object', properties: { mangle: { description: 'Pass false to skip mangling names.', type: 'boolean', default: true }, output: { description: 'Pass an object if you wish to specify additional output options. The defaults are optimized for best compression.', type: 'object', properties: { sequences: { description: 'Join consecutive statemets with the "comma operator".', type: 'boolean', default: true }, properties: { description: 'Optimize property access: a["foo"] → a.foo.', type: 'boolean', default: true }, dead_code: { description: 'Discard unreachable code.', type: 'boolean', default: true }, drop_debugger: { description: 'Discard "debugger" statements.', type: 'boolean', default: true }, unsafe: { description: 'Some unsafe optimizations (see below).', type: 'boolean', default: false }, conditionals: { description: 'Optimize if-s and conditional expressions.', type: 'boolean', default: true }, comparisons: { description: 'Optimize comparisons.', type: 'boolean', default: true }, evaluate: { description: 'Evaluate constant expressions.', type: 'boolean', default: true }, booleans: { description: 'Optimize boolean expressions.', type: 'boolean', default: true }, loops: { description: 'Optimize loops.', type: 'boolean', default: true }, unused: { description: 'Drop unused variables/functions.', type: 'boolean', default: true }, hoist_funs: { description: 'Hoist function declarations.', type: 'boolean', default: true }, hoist_vars: { description: 'Hoist variable declarations.', type: 'boolean', default: false }, if_return: { description: 'Optimize if-s followed by return/continue.', type: 'boolean', default: true }, join_vars: { description: 'Join var declarations.', type: 'boolean', default: true }, cascade: { description: 'Try to cascade `right` into `left` in sequences.', type: 'boolean', default: true }, side_effects: { description: 'Drop side-effect-free statements.', type: 'boolean', default: true }, warnings: { description: 'Warn about potentially dangerous optimizations/code.', type: 'boolean', default: true }, global_defs: { description: 'Global definitions.', type: 'array', items: { type: 'object' } } } }, preserveComments: { description: 'A convenience option for options.output.comments. Defaults to preserving no comments.', enum: ['all', 'license'] } } }] } } } }, properties: { bundles: { alias: ['bundle'], type: 'array', items: { description: 'Settings for this bundle.', type: 'object', extends: { $ref: '#/definitions/options' }, properties: { file: { description: 'The name of file to write to disk.', type: 'string' }, entries: { description: 'String, or array of strings. Specifying entry file(s).', alias: ['entry'], type: 'glob' }, options: { description: 'Options for this bundle.', type: 'object', extends: { $ref: '#/definitions/options' } } }, required: ['entries', 'file'] } }, options: { description: 'Common options for all bundles.', type: 'object', extends: { $ref: '#/definitions/options' } }, watch: { description: 'Update any source file and your browserify bundle will be recompiled on the spot.', anyOf: [{ type: 'boolean', default: false }, { type: 'object', properties: { delay: { description: 'The amount of time in milliseconds to wait before emitting an "update" event after a change. Defaults to 100.', type: 'integer', default: 100 }, ignoreWatch: { description: 'Ignores monitoring files for changes. If set to true, then **/node_modules/** will be ignored. For other possible values see Chokidar\'s documentation on "ignored".', type: ['boolean', 'string'] }, poll: { description: 'Enables polling to monitor for changes. If set to true, then a polling interval of 100ms is used. If set to a number, then that amount of milliseconds will be the polling interval. For more info see Chokidar\'s documentation on "usePolling" and "interval".', type: ['boolean', 'integer'] } } }] } }, required: ['bundles'] }; /** * browserify * * Bundle JavaScript things with Browserify! * * Notes * ----- * * Browserify constructor supports the following options: * * entries: string|[string] * noparse|noParse: boolean * basedir: string * browserField: boolean * builtins: boolean|[string] * debug: boolean * detectGlobals: boolean * extensions: [] * insertGlobals: boolean * commondir: boolean * insertGlobalVars: boolean * bundleExternal: boolean * * ignoreTransform: [] * transform: [string|{}|[]] * basedir: string * global: boolean * require: [] * file: string * entry: boolean * external * transform * basedir: string * expose: boolean * plugin: [string|{}|[]] * basedir: string * */ function browserifyTask() { // lazy loading required modules. var Browserify = require('browserify'); var browserSync = require('browser-sync'); var buffer = require('vinyl-buffer'); var log = require('gulp-util').log; var merge = require('merge-stream'); var notify = require('gulp-notify'); var sourcemaps = require('gulp-sourcemaps'); var uglify = require('gulp-uglify'); var vinylify = require('vinyl-source-stream'); var watchify = require('watchify'); var _ = require('lodash'); // NOTE: // 1.Transform must be registered after plugin // 2.Some plugin (e.g. tsify) use transform internally, so make sure transforms are registered right after browserify initialized. var EXCERPTS = ['plugin', 'transform', 'require', 'exclude', 'external', 'ignore']; var gulp = this.gulp; var config = this.config; // Start bundling with Browserify for each bundle config specified return merge(_.map(config.bundles, browserifyThis)); function browserifyThis(bundleConfig) { var options, excerpts, browserify; options = realizeOptions(); excerpts = _.pick(options, EXCERPTS); options = _.omit(options, EXCERPTS); options = prewatch(options); browserify = new Browserify(options).on('log', log); watch(); EXCERPTS.forEach(function (name) { var excerpt = excerpts[name]; _apply(excerpt, function (target) { browserify[name](target); }); }); return bundle(); // Add watchify args function prewatch(theOptions) { if (config.watch) { return _.defaults(theOptions, watchify.args); } return theOptions; } function watch() { if (config.watch) { // Wrap with watchify and rebundle on changes browserify = watchify(browserify, typeof config.watch === 'object' && config.watch); // Rebundle on update browserify.on('update', bundle); // bundleLogger.watch(bundleConfig.file); } } function bundle() { var stream, dest; // Log when bundling starts // bundleLogger.start(bundleConfig.file); stream = browserify .bundle() // Report compile errors .on('error', handleErrors) // Use vinyl-source-stream to make the stream gulp compatible. // Specify the desired output filename here. .pipe(vinylify(options.file)) // optional, remove if you don't need to buffer file contents .pipe(buffer()); if (options.sourcemaps) { // Loads map from browserify file stream = stream.pipe(sourcemaps.init({ loadMaps: true })); } if (options.uglify) { stream = stream.pipe(uglify()); } // Prepares sourcemaps, either internal or external. if (options.sourcemaps === true) { stream = stream.pipe(sourcemaps.write()); } else if (typeof options.sourcemaps === 'string') { stream = stream.pipe(sourcemaps.write(options.sourcemaps)); } // Specify the output destination dest = options.dest || config.dest; return stream .pipe(gulp.dest(dest.path, dest.options)) .pipe(browserSync.reload({ stream: true })); } function realizeOptions() { var result; result = _.defaults({}, _.omit(bundleConfig, ['options']), bundleConfig.options, config.options); result.entries = result.entries.globs; // add sourcemap option if (result.sourcemaps) { // browserify use 'debug' option for sourcemaps, // but sometimes we want sourcemaps even in production mode. result.debug = true; } return result; } function handleErrors() { var args = Array.prototype.slice.call(arguments); // Send error to notification center with gulp-notify notify.onError({ title: 'Browserify Error', message: '<%= error %>' }).apply(this, args); this.emit('end'); } } function _apply(values, fn) { if (Array.isArray(values)) { values.forEach(fn); } else if (values) { fn(values); } } } module.exports = browserifyTask; module.exports.schema = schema; module.exports.type = 'task'; <file_sep>/README.md # gulp-ccr-browserify Bundle JavaScript things with Browserify. A cascading configurable gulp recipe for [gulp-chef](https://github.com/gulp-cookery/gulp-chef). ## Install ``` bash $ npm install --save-dev "gulpjs/gulp#4.0" gulp-chef gulp-ccr-browserify ``` ## Recipe browserify ## Ingredients * [browser-sync](https://github.com/BrowserSync/browser-sync) * [node-browserify](https://github.com/substack/node-browserify) * [gulp-sourcemaps](https://github.com/floridoo/gulp-sourcemaps) * [gulp-uglify](https://github.com/terinjokes/gulp-uglify) * [vinyl-source-stream](https://github.com/hughsk/vinyl-source-stream) * [vinyl-buffer](https://github.com/hughsk/vinyl-buffer) * [watchify](https://github.com/substack/watchify) ## API ### config.options Options for all bundles. See browserify [documentation](https://github.com/substack/node-browserify#browserifyfiles--opts) for all options. #### config.options.basedir The directory that browserify starts bundling from for filenames that start with. #### config.options.builtins Sets the list of built-ins to use, which by default is set in lib/builtins.js in this distribution. Type: array of string. #### config.options.bundleExternal Boolean option to set if external modules should be bundled. Defaults to true. Type: boolean Default: true #### config.options.commondir Sets the algorithm used to parse out the common paths. Use false to turn this off, otherwise it uses the commondir module. Type: string or boolean #### config.options.detectGlobals Scan all files for process, global, __filename, and __dirname, defining as necessary. With this option npm modules are more likely to work but bundling takes longer. Default true. Type: boolean Default: true #### config.options.exclude(s) Prevent the module name or file at file from showing up in the output bundle. Alias: excludes Type: array of string #### config.options.extensions An array of optional extra extensions for the module lookup machinery to use when the extension has not been specified. By default browserify considers only .js and .json files in such cases. Alias: extension Type: array of string #### config.options.external(s) Prevent the module or bundle from being loaded into the current bundle, instead referencing from another bundle. Alias: externals Type: array of string, or array of the object with properties: ``` javascript { basedir: { type: 'path' }, file: { type: 'string' } } ``` #### config.options.externalRequireName Defaults to `require` in expose mode but you can use another name. Type: string Default: 'require' #### config.options.fullpaths Disables converting module ids into numerical indexes. This is useful for preserving the original paths that a bundle was generated with. #### config.options.ignore(s) Prevent the module name or file at file from showing up in the output bundle. Alias: ignores Type: array of string #### config.options.insertGlobals Insert `process`, `global`, `__filename`, and `__dirname` without analyzing the AST for faster builds but larger output bundles. Default false. Type: boolean Default: false #### config.options.insertGlobalVars Override the default inserted variables, or set `insertGlobalVars[name]` to `undefined` to not insert a variable which would otherwise be inserted. #### config.options.noParse An array which will skip all `requires` and global parsing for each file in the array. Use this for giant libs like jQuery or threejs that don't have any requires or node-style globals but take forever to parse. Alias: noparse #### config.options.paths An array of directories that browserify searches when looking for modules which are not referenced using relative path. Can be absolute or relative to basedir. Alias: path Type: array of string #### config.options.plugin(s) Register plugins. Alias: plugins Type: array of string #### config.options.require(s) Make module available from outside the bundle. The module name is anything that can be resolved by require.resolve(). Use an object with `file` and `expose` property to specify a custom dependency name. `{ file: './vendor/angular/angular.js', options: { expose: 'angular' } }` enables `require('angular')`. Alias: requires Type: array of string, or object with the following properties: ``` javascript { file: { type: 'string' }, options: { basedir: { description: 'The directory that starts searching from for filenames that start with.', type: 'path' }, entry: { description: 'Make the module an entry.', type: 'boolean', default: false }, expose: { description: 'Specify a custom dependency name for the module.', type: 'string' }, external: { note: 'Distingish this option with browserify.external().', description: 'Prevent the module from being loaded into the current bundle, instead referencing from another bundle.', type: 'boolean', default: false }, transform: { note: 'Distingish this option with browserify.option.transform.', description: 'Allow the module to be transformed.', type: 'boolean', default: true } } } ``` #### config.options.sourcemaps Add a source map inline to the end of the bundle or separate source map to external file. This makes debugging easier because you can see all the original files if you are in a modern enough browser. Alias: sourcemap Type: string or boolean #### config.options.standalone Create a standalone module with this given name and a umd wrapper. You can use namespaces in the standalone global export using a . in the string name as a separator, for example `A.B.C`. The global export will be sanitized and camel cased. Type: string #### config.options.transform(s) Alias: transforms Register transforms. Type: array of string #### config.options.uglify Type: boolean or object with the following properties: ``` javascript { mangle: { description: 'Pass false to skip mangling names.', type: 'boolean', default: true }, output: { description: 'Pass an object if you wish to specify additional output options. The defaults are optimized for best compression.', sequences: { description: 'Join consecutive statemets with the "comma operator".', type: 'boolean', default: true }, properties: { description: 'Optimize property access: a["foo"] → a.foo.', type: 'boolean', default: true }, dead_code: { description: 'Discard unreachable code.', type: 'boolean', default: true }, drop_debugger: { description: 'Discard "debugger" statements.', type: 'boolean', default: true }, unsafe: { description: 'Some unsafe optimizations (see below).', type: 'boolean', default: false }, conditionals: { description: 'Optimize if-s and conditional expressions.', type: 'boolean', default: true }, comparisons: { description: 'Optimize comparisons.', type: 'boolean', default: true }, evaluate: { description: 'Evaluate constant expressions.', type: 'boolean', default: true }, booleans: { description: 'Optimize boolean expressions.', type: 'boolean', default: true }, loops: { description: 'Optimize loops.', type: 'boolean', default: true }, unused: { description: 'Drop unused variables/functions.', type: 'boolean', default: true }, hoist_funs: { description: 'Hoist function declarations.', type: 'boolean', default: true }, hoist_vars: { description: 'Hoist variable declarations.', type: 'boolean', default: false }, if_return: { description: 'Optimize if-s followed by return/continue.', type: 'boolean', default: true }, join_vars: { description: 'Join var declarations.', type: 'boolean', default: true }, cascade: { description: 'Try to cascade `right` into `left` in sequences.', type: 'boolean', default: true }, side_effects: { description: 'Drop side-effect-free statements.', type: 'boolean', default: true }, warnings: { description: 'Warn about potentially dangerous optimizations/code.', type: 'boolean', default: true }, global_defs: { description: 'Global definitions.', type: 'array', items: { type: 'object' } } }, preserveComments: { description: 'A convenience option for options.output.comments. Defaults to preserving no comments.', enum: ['all', 'license'] } } ``` ### config.watch Update any source file and your browserify bundle will be recompiled on the spot. Options are passed to watchify. ### config.bundles Bundle or array of bundles. Alias: bundle #### bundle.entries String, or array of strings. Specifying entry file(s). #### bundle.file The name of file to write to disk. #### bundle.options Options for this bundle. Accepts any values in config.options. ## Usage ``` javascript var gulp = require('gulp'); var chef = require('gulp-chef'); var meals = chef({ src: 'src/', dest: 'dist/', browserify: { bundles: [{ entries: [ 'services.ts' ], uglify: true }, { entries: [ 'main.ts' ], sourcemaps: '.' }], options: { transforms: ['tsify'] } } }); gulp.registry(meals); ``` ## References * [browserify-handbook](https://github.com/substack/browserify-handbook) * [partitioning](https://github.com/substack/browserify-handbook#partitioning) * [Fast browserify builds with watchify](https://github.com/gulpjs/gulp/blob/master/docs/recipes/fast-browserify-builds-with-watchify.md) * [browserify-handbook - configuring transforms](https://github.com/substack/browserify-handbook#configuring-transforms) * [Browserify + Globs](https://github.com/gulpjs/gulp/blob/master/docs/recipes/browserify-with-globs.md) * [Gulp + Browserify: The Everything Post](http://viget.com/extend/gulp-browserify-starter-faq) * [gulp-starter/gulp/tasks/browserify.js](https://github.com/greypants/gulp-starter/blob/master/gulp/tasks/browserify.js) * [Speedy Browserifying with Multiple Bundles](https://lincolnloop.com/blog/speedy-browserifying-multiple-bundles/) * [gulp + browserify, the gulp-y way](https://medium.com/@sogko/gulp-browserify-the-gulp-y-way-bb359b3f9623) * [node-browserify/index.js](https://github.com/substack/node-browserify/blob/master/index.js) * [pull: Make sure entry paths are always full paths #1248](https://github.com/substack/node-browserify/pull/1248) * [issues: 8.1.1 fails to resolve modules from "browser" field #1072](https://github.com/substack/node-browserify/issues/1072#issuecomment-70323972) * [issues: browser field in package.json no longer works #1250](https://github.com/substack/node-browserify/issues/1250) * [issues: browser field in package.json no longer works #1250 comment](https://github.com/substack/node-browserify/issues/1250#issuecomment-99970224) ## License [MIT](https://opensource.org/licenses/MIT) ## Author [Amobiz](https://github.com/amobiz) <file_sep>/test/index.js /* eslint consistent-this: 0 */ 'use strict'; var expect = require('chai').expect; var _ = require('lodash'); var browserify = require('../'); var cases = { 'Accepts multiple bundles': { config: { src: 'test/_fixtures/app/modules', dest: 'dist', bundles: [{ entries: ['directives/index.js'], file: 'directives.js' }, { entries: ['services/index.js'], file: 'services.js' }] }, expected: { } } }; describe('browserify()', function () { it('should...', function () { // var tasks; // // _ .forEach(testCases, function (testCase, title) { // it(title, function () { // browserify(gulp, testCase.config, null); // }); // }); // var stream = gulp.src('non-existent'); // expect(stream).to.be.an.instanceof(Stream); // expect(stream).to.have.property('on'); }); });
741625be6edf9aece30ea7c11308041256a29461
[ "JavaScript", "Markdown" ]
3
JavaScript
gulp-cookery/gulp-ccr-browserify
f03736aba15e5bdd70c3982dec32833044943435
5f87eead9b2e6c7c553025b4edcd1198ef1e7708
refs/heads/master
<file_sep>import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { UpdateStatusPage } from '../update-status/update-status'; import { Storage } from '@ionic/storage'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { myStatus:string; constructor(public navCtrl: NavController, public storage: Storage) { } openUpdateStatusPage(){ this.navCtrl.push(UpdateStatusPage); } ionViewWillEnter(){ this.storage.get("Status") .then((data)=>{ this.myStatus = data; }) .catch((err) =>{ console.log("Database error") }) } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { Storage } from '@ionic/storage'; @IonicPage() @Component({ selector: 'page-update-status', templateUrl: 'update-status.html', }) export class UpdateStatusPage { myStatus:string; constructor(public navCtrl: NavController, public navParams: NavParams, public storage: Storage) { } ionViewDidLoad() { console.log('ionViewDidLoad UpdateStatusPage'); } saveUpdate(){ console.log(this.myStatus); this.storage.set("Status", this.myStatus); this.navCtrl.pop(); } ionViewWillEnter(){ this.storage.get("Status") .then((data)=>{ this.myStatus = data; }) .catch((err) =>{ console.log("Database error") }) } }
a921a8389f31c1ee6be9d5f93fca7e562d77e283
[ "TypeScript" ]
2
TypeScript
SammarTahir/storageLab
2c3cd2f0eb166427fdd84392fcbd0d73defda80c
ea8185a4588f40051d0e3801dcdf04b173fa843d
refs/heads/master
<file_sep>// // Topic.swift // reddit // // Created by <NAME> on 7/17/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit enum VoteState: String { case upvote case downvote case none } struct Topic { let id: String let user: User let createdDate: Date var content: String var upVote: Int var downVote: Int var voteState: VoteState static func createFakeTopics() -> [Topic] { var topics = [Topic]() let contents = ["Snapchat now allows exact location sharing" , "How can we stop algorithms telling lies? Algorithms can dictate whether you get a mortgage or how much you pay for insurance. But sometimes they’re wrong – and sometimes they are designed to deceive" , "10 startups in Asia that caught our eye. Here’s our newest round-up of the featured startups on our site this week." , "SPRING Singapore commits $73m to co-invest in “deep tech” startups" , "Working in the best tech company to work for. Yesterday, the Singapore Computer Society announced the winners of their Best Tech Company to Work For award, and Carousell was the overall winner for the Start-up category! Needless to say, we were jumping with joy when we heard the news!"] let pictures = ["reddit_logo_green", "reddit_logo_blue", "reddit_logo_pink"] let names = ["alan", "joe_parker", "catlin"] for _ in 0..<4 { for content in contents { let upvotes = Int(arc4random_uniform(16)) let downvotes = Int(arc4random_uniform(10)) let index = Int(arc4random_uniform(3)) let profilePicture = pictures[index] let name = names[index] let topic = Topic(id: Utils.getUUID() , user: User(userId: Utils.getUUID(), userName: name, profilePicture: profilePicture) , createdDate: Date() , content: content , upVote: upvotes , downVote: downvotes , voteState: .none) topics.append(topic) } } return topics } } <file_sep># *Reddit Clone* **Reddit** is a social news aggregation app, powered by their users’ upvotes and downvotes. When a user makes a contribution to their website, other users may upvote or downvote a particular topic, giving rise to a set of topics that are popular and unpopular. Original: https://www.reddit.com/ ## User Stories The following **required** functionality is completed: - [ ] Maintain a list of topics and its upvotes/downvotes. - [ ] Allow the user to submit topics. For this challenge, a “topic” is simply a string that does not exceed 255 characters. - [ ] Allow the user to upvote or downvote a topic. For this challenge, the user may upvote or downvote the same topic multiple times. - [ ] Always return a list of top 20 topics (sorted by upvotes, descending) on the homepage. - [ ] In-memory: Design an in-memory data structure (shared by the same process as your application) that will allow you to keep the topics in memory without using data persistence. It is okay for the topics to disappear after the application restarts. <file_sep>// // Utils.swift // reddit // // Created by <NAME> on 7/17/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit struct Utils { static func getUUID() -> String { return UUID().uuidString } static func display(votes: Int) -> String{ let number = 1000 var result = "" if votes < number { result = "\(votes)" } else { if votes % number == 0 { result = "\(votes/number)k" } else { let votesTotal = Double(votes)/Double(1000) result = String(format: "%.1fk", votesTotal) } } return result } static func format(date: Date) -> String { let min = 60 let hour = min * 60 let day = hour * 24 let week = day * 27 let year = day * 365 let time = Int(Date().timeIntervalSince(date)) if time < min { return "\(time)s" } else if time < hour { let min = time/min return "\(min)m" } else if time < day { let hour = time/hour return "\(hour)h" } else if time < week { let day = time/day return "\(day)d" } else if time < year { let dateFormater = DateFormatter() dateFormater.dateFormat = "dMMM" return dateFormater.string(from: date) } else { let dateFormater = DateFormatter() dateFormater.dateFormat = "dMMM y" return dateFormater.string(from: date) } } } <file_sep>// // Colors.swift // reddit // // Created by <NAME> on 7/16/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit struct Colors { static let gray = UIColor(colorLiteralRed: 237/255, green: 237/255, blue: 237/255, alpha: 1) static let grayPlaceHolder = UIColor(colorLiteralRed: 163/255, green: 163/255, blue: 163/255, alpha: 1) static let grayCountLabel = UIColor(colorLiteralRed: 163/255, green: 163/255, blue: 163/255, alpha: 1) static let purpleDownvoted = UIColor(colorLiteralRed: 163/255, green: 165/255, blue: 207/255, alpha: 1) static let orangeUpvoted = UIColor(colorLiteralRed: 255/255, green: 68/255, blue: 0/255, alpha: 1) static let green = UIColor(colorLiteralRed: 15/255, green: 209/255, blue: 183/255, alpha: 1) } <file_sep>// // ViewController.swift // reddit // // Created by <NAME> on 7/16/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class HomeViewController: BaseViewController { var popularTopics:[Topic] = [] @IBOutlet weak var tableView: UITableView! let refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() initCells() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 tableView.delegate = self tableView.dataSource = self refreshControl.addTarget(self, action: #selector(HomeViewController.refreshData(refreshControl:)), for: UIControlEvents.valueChanged) tableView.insertSubview(refreshControl, at: 0) } override func viewWillAppear(_ animated: Bool) { topics = (tabBarController as! CustomTabBarController).topics popularTopics = getPopularTopics() } func initCells() { tableView.register(UINib(nibName: String(describing: TopicCell.self), bundle: nil), forCellReuseIdentifier: "topicCell") } func footerView() -> UIView { let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 8)) view.backgroundColor = Colors.gray return view } //update newest data from list topics while user had upvotes/downvotes func refreshData(refreshControl: UIRefreshControl) { popularTopics = getPopularTopics() tableView.reloadData() refreshControl.endRefreshing() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "NewTopicVCSegue" { let nav = segue.destination as! UINavigationController let vc = nav.viewControllers.first as! NewTopicViewController vc.hidesBottomBarWhenPushed = true vc.delegate = self } } } extension HomeViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func numberOfSections(in tableView: UITableView) -> Int { return popularTopics.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "topicCell") as! TopicCell cell.topic = popularTopics[indexPath.section] cell.delegate = self return cell } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return footerView() } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { switch section { case popularTopics.count - 1: return 0 default: return 8 } } } extension HomeViewController: NewTopicViewControllerDelegate { //add new topic created by user to list topic func newPost(topic: Topic) { topics.append(topic) (tabBarController as! CustomTabBarController).topics = topics popularTopics = getPopularTopics() tableView.reloadData() } } extension HomeViewController: TopicCellDelegate { //update topic upvoted/downvoted to list topics func topicDidChanged(topic: Topic) { if let index = topics.index(where: { $0.id == topic.id }) { topics[index] = topic (tabBarController as! CustomTabBarController).topics = topics popularTopics = getPopularTopics() } } } <file_sep>// // BaseViewController.swift // reddit // // Created by <NAME> on 7/18/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class BaseViewController: UIViewController { var topics: [Topic] = [] override func viewDidLoad() { super.viewDidLoad() topics = (self.tabBarController as! CustomTabBarController).topics } //return list of topics created by current user func getMyTopics() -> [Topic] { return topics.filter{ $0.user.userId == User.currentUser.userId } } //return list of topics sorted by upvote (decsending) func sortByUpvotes() -> [Topic]{ var result = [Topic]() result = topics.sorted(by: { $0.upVote > $1.upVote }) return result } //return 20 topics from sorted list func getPopularTopics() -> [Topic] { return Array(sortByUpvotes().prefix(20)) } } <file_sep>// // User.swift // reddit // // Created by <NAME> on 7/17/17. // Copyright © 2017 <NAME>. All rights reserved. // import Foundation struct User { let userId: String let userName: String let profilePicture: String static let currentUser = User(userId: Utils.getUUID(), userName: "huy_ngo", profilePicture: "reddit_logo") } <file_sep>// // UtilsTest.swift // reddit // // Created by <NAME> on 7/19/17. // Copyright © 2017 <NAME>. All rights reserved. // import XCTest @testable import reddit class UtilsTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testDisplayVotes() { XCTAssertEqual(Utils.display(votes: 100), "100") XCTAssertEqual(Utils.display(votes: 2000), "2k") XCTAssertEqual(Utils.display(votes: 2200), "2.2k") XCTAssertEqual(Utils.display(votes: 2020), "2.0k") XCTAssertEqual(Utils.display(votes: 2345), "2.3k") } // func testFormatDate() { // let date = Date() // XCTAssertEqual(Utils.format(date: date), "4min") // } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } } <file_sep>// // MyTopicViewController.swift // reddit // // Created by <NAME> on 7/18/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class MyTopicViewController: HomeViewController { @IBOutlet weak var infoLabel: UILabel! var myTopics: [Topic] = [] override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { topics = (tabBarController as! CustomTabBarController).topics myTopics = getMyTopics().reversed() if myTopics.count == 0 { infoLabel.isHidden = false } else { infoLabel.isHidden = true } tableView.reloadData() } override func refreshData(refreshControl: UIRefreshControl) { myTopics = getMyTopics().reversed() tableView.reloadData() refreshControl.endRefreshing() } } extension MyTopicViewController { override func numberOfSections(in tableView: UITableView) -> Int { return myTopics.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "topicCell") as! TopicCell cell.topic = myTopics[indexPath.section] cell.delegate = self return cell } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { switch section { case myTopics.count - 1: return 0 default: return 8 } } } <file_sep>// // TopicCell.swift // reddit // // Created by <NAME> on 7/16/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit protocol TopicCellDelegate { func topicDidChanged(topic: Topic) } class TopicCell: UITableViewCell { @IBOutlet weak var numberUpVotesLabel: UILabel! @IBOutlet weak var numberDownVotesLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var createdTime: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var profileImage: UIImageView! @IBOutlet weak var upvoteButton: UIButton! @IBOutlet weak var downvoteButton: UIButton! var delegate: TopicCellDelegate? var topic: Topic? { didSet { guard let topic = topic else { return } contentLabel.text = topic.content nameLabel.text = topic.user.userName profileImage.image = UIImage(named: topic.user.profilePicture) createdTime.text = Utils.format(date: topic.createdDate) numberDownVotesLabel.text = Utils.display(votes: topic.downVote) numberUpVotesLabel.text = Utils.display(votes: topic.upVote) setVote(state: topic.voteState) } } func setVote(state: VoteState) { switch state { case .none: upvoteButton.isSelected = false downvoteButton.isSelected = false numberUpVotesLabel.textColor = Colors.grayCountLabel numberDownVotesLabel.textColor = Colors.grayCountLabel break case .upvote: downvoteButton.isSelected = false upvoteButton.isSelected = true numberUpVotesLabel.textColor = Colors.orangeUpvoted numberDownVotesLabel.textColor = Colors.grayCountLabel break case .downvote: upvoteButton.isSelected = false downvoteButton.isSelected = true numberDownVotesLabel.textColor = Colors.purpleDownvoted numberUpVotesLabel.textColor = Colors.grayCountLabel } } override func awakeFromNib() { super.awakeFromNib() if let topic = topic { setVote(state: topic.voteState) } let radius = profileImage.layer.bounds.height/2 profileImage.makeRounded(radius: radius) } //update number of downvotes and set state @IBAction func downvoteAction(_ sender: UIButton) { if sender.isSelected { topic?.voteState = .none } else { topic?.downVote += 1 topic?.voteState = .downvote } delegate?.topicDidChanged(topic: self.topic!) } //update number of upvotes and set state @IBAction func upvoteAction(_ sender: UIButton) { if sender.isSelected { topic?.voteState = .none } else { topic?.upVote += 1 topic?.voteState = .upvote } delegate?.topicDidChanged(topic: self.topic!) } } extension UIView { func makeRounded(radius: CGFloat = 4) { self.layer.cornerRadius = radius self.clipsToBounds = true } } <file_sep>// // NewTopicViewController.swift // reddit // // Created by <NAME> on 7/16/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit protocol NewTopicViewControllerDelegate: class { func newPost(topic: Topic) } class NewTopicViewController: UIViewController { @IBOutlet weak var postButton: UIBarButtonItem! @IBOutlet weak var countCharacterLabel: UILabel! @IBOutlet weak var contentTextView: UITextView! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! weak var delegate: NewTopicViewControllerDelegate? let placeHolder = "An interesting title" let limitCharacter: Int = 255 var countCharacter: Int = 255 { didSet { countCharacterLabel.text = "\(countCharacter)" } } var isContentChanged = false override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(NewTopicViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(NewTopicViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) contentTextView.delegate = self initView() } @IBAction func postAction(_ sender: Any) { let topic = Topic(id: Utils.getUUID() , user: User.currentUser , createdDate: Date() , content: contentTextView.text , upVote: 0 , downVote: 0 , voteState: .none) delegate?.newPost(topic: topic) self.dismiss(animated: true, completion: nil) } @IBAction func cancelAction(_ sender: Any) { if isContentChanged { showWarningPopup() } else { self.dismiss(animated: true, completion: nil) } } func initView() { contentTextView.becomeFirstResponder() setPlaceHolder() } func setPlaceHolder() { isContentChanged = false countCharacterLabel.isHidden = true postButton.isEnabled = false contentTextView.text = placeHolder contentTextView.selectedRange = NSRange(location: 0,length: 0) contentTextView.textColor = Colors.grayPlaceHolder } func showWarningPopup() { let title = "Do you want to discard your post?" let alertPopup = UIAlertController(title: title, message: "", preferredStyle: .alert) alertPopup.addAction(UIAlertAction(title: "Keep edditing", style: .cancel) { _ in alertPopup.dismiss(animated: true, completion: nil) }) alertPopup.addAction(UIAlertAction(title: "Discard", style: .default) { _ in alertPopup.dismiss(animated: true, completion: nil) _ = self.navigationController?.popViewController(animated: true) }) self.present(alertPopup, animated: true, completion: nil) } func keyboardWillShow(notification: Notification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { bottomConstraint.constant = keyboardSize.height } } func keyboardWillHide(notification: Notification) { bottomConstraint.constant = 0 } } extension NewTopicViewController: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { countCharacterLabel.isHidden = false isContentChanged = true //limit 255 characters in topic countCharacter = limitCharacter - textView.text.characters.count if countCharacter < 0 { countCharacterLabel.textColor = UIColor.red postButton.isEnabled = false } else { countCharacterLabel.textColor = Colors.grayCountLabel postButton.isEnabled = true } if textView.text.contains(placeHolder) { textView.text = textView.text.components(separatedBy: placeHolder)[0] contentTextView.textColor = UIColor.black } else if textView.text.isEmpty { setPlaceHolder() } } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if textView.text == placeHolder { setPlaceHolder() } return true } } <file_sep>// // CustomTabBarViewController.swift // reddit // // Created by <NAME> on 7/18/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class CustomTabBarController: UITabBarController { var topics: [Topic] = [] override func viewDidLoad() { topics = Topic.createFakeTopics() } } <file_sep># *Reddit Clone* **Reddit** is a social news aggregation app, powered by their users’ upvotes and downvotes. When a user makes a contribution to their website, other users may upvote or downvote a particular topic, giving rise to a set of topics that are popular and unpopular. Original: https://www.reddit.com/ ## User Stories The following **required** functionality is completed: - [x] Maintain a list of topics and its upvotes/downvotes. - [x] Allow the user to submit topics. For this challenge, a “topic” is simply a string that does not exceed 255 characters. - [x] Allow the user to upvote or downvote a topic. For this challenge, the user may upvote or downvote the same topic multiple times. - [x] Always return a list of top 20 topics (sorted by upvotes, descending) on the homepage. - [x] In-memory: Design an in-memory data structure (shared by the same process as your application) that will allow you to keep the topics in memory without using data persistence. It is okay for the topics to disappear after the application restarts. ## Walkthrough <img src='https://user-images.githubusercontent.com/10734967/28406523-1f6a99bc-6d5b-11e7-9b54-02dcfc5c1488.gif' title='Reddit walkthrough' width='' alt='Video Walkthrough' /> GIF created with [LiceCap](http://www.cockos.com/licecap/). ## Documentations Reddit app written in Swift 3.0 - **Maintain a list topics and return 20 topics sorted by upvotes** Create a list of topics. ````swift /* contents: array content of topic pictures: array name of images names : array name of users */ //Topic.swift static func createFakeTopics() -> [Topic] { var topics = [Topic]() for _ in 0..<4 { for content in contents { //random number of upvotes and downvotes let upvotes = Int(arc4random_uniform(16)) let downvotes = Int(arc4random_uniform(10)) //random name and profile picture let index = Int(arc4random_uniform(3)) let profilePicture = pictures[index] let name = names[index] /create a new topic let topic = Topic(id: Utils.getUUID() , user: User(userId: Utils.getUUID(), userName: name, profilePicture: profilePicture) , createdDate: Date() , content: content , upVote: upvotes , downVote: downvotes , voteState: .none) topics.append(topic) } } return topics } ```` Sort topics by upvotes ````swift //BaseViewController.swift func sortByUpvotes() -> [Topic]{ var result = [Topic]() result = topics.sorted(by: { $0.upVote > $1.upVote }) return result } //return 20 topics from sorted list func getPopularTopics() -> [Topic] { return Array(sortByUpvotes().prefix(20)) } ```` - **Alow user submit a new topic** When user click **Done** button, this event will happen. ````swift //NewTopicViewController.swift @IBAction func postAction(_ sender: Any) { //create a new topic with content get from UITextView let topic = Topic(id: Utils.getUUID() , user: User.currentUser , createdDate: Date() , content: contentTextView.text , upVote: 0 , downVote: 0 , voteState: .none) //use delegate to pass newtopic to HomeViewController delegate?.newPost(topic: topic) //go back to Home view _ = navigationController?.popViewController(animated: true) } ```` - **Allow user Upvote/Downvote a topic** Upvote/downvote will happen when user tap to UpvoteButton ````swift //TopicCell.swift @IBAction func upvoteAction(_ sender: UIButton) { if sender.isSelected { //user voted already -> update vote state to unvote topic?.voteState = .none } else { //increase number of upvote topic?.upVote += 1 //set upvote state and update UI topic?.voteState = .upvote } // use delegate to pass topic changed to HomeViewController delegate?.topicDidChanged(topic: self.topic!) } ```` ## Copyright Assets in app from [FlatIcon](http://www.flaticon.com/) and [Icon8](https://icons8.com/) ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details <file_sep>// // BaseViewControllerTest.swift // reddit // // Created by <NAME> on 7/19/17. // Copyright © 2017 <NAME>. All rights reserved. // import XCTest @testable import reddit class BaseViewControllerTest: XCTestCase { let baseVC = BaseViewController() override func setUp() { super.setUp() baseVC.topics.append(Topic(id: Utils.getUUID(), user: User (userId: Utils.getUUID(), userName: "first", profilePicture: ""), createdDate: Date(), content: "Test1", upVote: 12, downVote: 4, voteState: .none)) baseVC.topics.append(Topic(id: Utils.getUUID(), user: User (userId: Utils.getUUID(), userName: "second", profilePicture: ""), createdDate: Date(), content: "Test2", upVote: 20, downVote: 7, voteState: .none)) baseVC.topics.append(Topic(id: Utils.getUUID(), user: User (userId: Utils.getUUID(), userName: "third", profilePicture: ""), createdDate: Date(), content: "Test3", upVote: 4, downVote: 7, voteState: .none)) // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testMyPostExist() { let topic = Topic(id: Utils.getUUID(), user: User.currentUser, createdDate: Date(), content: "test", upVote: 0, downVote: 0, voteState: .none) baseVC.topics.append(topic) let result = 1 XCTAssertEqual(baseVC.getMyTopics().count, result) } func testMyPostNotExist() { let result = 0 XCTAssertEqual(baseVC.getMyTopics().count, result) } func testSortByVote() { XCTAssertEqual(baseVC.sortByUpvotes().first?.user.userName, "second") } func testGetPopularTopics() { baseVC.topics += Topic.createFakeTopics() XCTAssertEqual(baseVC.getPopularTopics().count, 20) XCTAssertEqual(baseVC.sortByUpvotes().first?.user.userName, "second") } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
6e7a50c3616264c89ef6723c947830208ca67790
[ "Swift", "Markdown" ]
14
Swift
quochuyngo/reddit_clone
9ea49dce1c02958808db892430da402e05c133fb
57b8114081682343d6bc00c0e826e5021f80ee06
refs/heads/main
<repo_name>cbcurrier3/TF-GCP-CGIaaS-GW<file_sep>/exports.sh #!/bin/bash #export TF_VAR_org_id=YOUR_ORG_ID export TF_VAR_billing_account=000000-000000-00000 export TF_ADMIN=${USER} export TF_CREDS=terraform-admin.json<file_sep>/README.txt v2.0 10/19/2020 Terraform files To launch with Terraform on GCP a Check Point R80.40 Cloudguard Instance By <NAME> <<EMAIL>> This template will at this time create a gateway with 2 network interfaces. When completed the gateway will be sic'd as a gateway only and ready for policy push. A public IP address will be returned at completion. Needed: 1. copy the SSH user public identity file cp_admin_auth_key or rename the variable in vars.tf ssh_pub_key_file to point to the local user identity file 2. Update in vars.tf the service account email address to one that has permissions to access GCP APIS 3. Update the file terraform-admin.json with GCP IAM credentials for the email account in #2. 4. Update export.sh with credentials information that will be needed by terraform. This then will need to be executed to push the information into the user env. Alternatively copy the export commands with valid credentials and paste in user file ~/.bashrc. When logging in this data will be part of the user environment. 5. update the vars.tf file with relevant project name and update other fields as desired. 6. Be sure there is ssh access to public GCP addresses as post impage deployment requires this. 7. Run terraform init 8. Run terraform plan 9. If all is good run terraform apply - answer yes 10. if you need to remove - run terraform destroy.
da1c80d2de6f79564336abdbe6993e2a2d8f6db1
[ "Text", "Shell" ]
2
Shell
cbcurrier3/TF-GCP-CGIaaS-GW
cb89b511b17b32f1ec452330a4cf179d850ce0b0
48d937a5fc7546b3da29a00f0f6bb9162b3d92f6
refs/heads/main
<repo_name>englergonzalez/JuegoRULETA<file_sep>/js/script.js var negros = ["2","4","6","8","10","11","13","15","17","20","22","24","26","28","29","31","33","35"]; var rojos = ["1","3","5","7","9","12","14","16","18","19","21","23","25","27","30","32","34","36"]; var verdes = ["0","00"]; var tapete = ["1-2A1","2-2A1","3-2A1","PRIMEROS12","SEGUNDOS12","TERCEROS12","1A18","PARES","ROJOS", "NEGROS","IMPARES","19A36","28","9","26","30","11","7","20","32","17","5","22","34", "15","3","24","36","13","1","27","10","25","29","12","8","19","31","18","6","21","33", "16","4","23","35","14","2"]; var ficha = 0; var casilla = 0; var dinero = 0; function capturarJugadas(fichas,casillas,dineros) { this.fichas = fichas; this.casillas = casillas; this.dineros = dineros; } var vectorJugadas = []; var cantidad = 0; function clickaction(n){ // Accion por defecto para Buttons; switch( n.id ){ // metodo para ocultar los botones case "100€": dineroAcumulado(100); document.getElementById("mensaje").style.fontSize = "30px"; document.getElementById("mensaje").innerHTML = "<b>¡En hora buena!</b><br>Compra exitosa..."; $('#box').bounceBoxToggle(); document.getElementById("ventanaCompra").style.display = "none"; break; case "200€": dineroAcumulado(200); document.getElementById("mensaje").style.fontSize = "30px"; document.querySelector("#mensaje").innerHTML = "<b>¡En hora buena!</b><br>Compra exitosa..."; $('#box').bounceBoxToggle(); document.getElementById("ventanaCompra").style.display = "none"; break; case "500€": dineroAcumulado(500); document.getElementById("mensaje").style.fontSize = "30px"; document.querySelector("#mensaje").innerHTML = "<b>¡En hora buena!</b><br>Compra exitosa..."; $('#box').bounceBoxToggle(); document.getElementById("ventanaCompra").style.display = "none"; break; case "b1"://ficha de 20euro cerrarVentana(); if(dinero>0){ if(dinero<20){ avisoOtraFicha(); }else{ ficha = 20; } }else{ avisoComprarFicha(); } break; case "b5": cerrarVentana(); if(dinero>0){ if(dinero<50){ avisoOtraFicha(); }else{ ficha = 50; } }else{ avisoComprarFicha(); } break; case "b10": cerrarVentana(); if(dinero<=0){ avisoComprarFicha(); }else { ficha = 10; } break; case "1-2A1": if(ficha!=0) { insertarFicha(n.id,ficha); } break; case "2-2A1": if(ficha!=0) { insertarFicha(n.id,ficha); } break; case "3-2A1": if(ficha!=0) { insertarFicha(n.id,ficha); } break; case "PRIMEROS12": if(ficha!=0) { insertarFicha(n.id,ficha); } break; case "SEGUNDOS12": if(ficha!=0) { insertarFicha(n.id,ficha); } break; case "TERCEROS12": if(ficha!=0) { insertarFicha(n.id,ficha); } break; case "1A18": if(ficha!=0) { insertarFicha(n.id,ficha); } break; case "PARES": if(ficha!=0) { insertarFicha(n.id,ficha); } break; case "ROJOS": if(ficha!=0) { insertarFicha(n.id,ficha); } break; case "NEGROS": if(ficha!=0) { insertarFicha(n.id,ficha); } break; case "IMPARES": if(ficha!=0) { insertarFicha(n.id,ficha); } break; case "19A36": if(ficha!=0) { insertarFicha(n.id,ficha); } break; default : if(ficha!=0) { for(var i=1; i<=36; i++) { if(n.id==i){ insertarFicha(i,ficha); break; } } }else{ error(); } } } function insertarFicha(id,ficha) { if( document.getElementById(id).style.backgroundImage == ('url("../../img/'+ficha+'.png")') ) { dineroAcumulado(ficha); vectorJugadas.pop(); ficha = 0; casilla = 0; quitarFicha(id); cantidad--; } else { if(dinero>=ficha) { casilla = id; jugadas = new capturarJugadas(ficha,casilla,dinero); //console.log(jugadas); vectorJugadas.push(jugadas); // console.log(vectorJugadas); document.getElementById(id).style.backgroundImage = "url(../../img/"+ficha+".png)"; //console.log(vectorJugadas.length); dineroAcumulado(-ficha); cantidad++; }else { avisoComprarFicha(); } } } function quitarFicha(id) { document.getElementById(id).style.backgroundImage = "url()"; } function girar() { // if (dinero >= 10){ // dinero = dinero - ficha; //if(dinero>=0) // { let rand = Math.random()*7000; // audio.play(); calcular(rand); /* }else { // dinero = dinero + ficha; avisoUtilizarOtraFicha(); } } else { avisoComprarFicha(); }*/ } function avisoOtraFicha() { document.getElementById("mensaje").style.fontSize = "35px"; document.querySelector("#mensaje").innerHTML = "<b>Sólo tienes: " +dinero+"€ </b>¡Intenta con otra ficha!"; $('#box').bounceBoxToggle(); } function avisoComprarFicha(){ document.getElementById("mensaje").style.fontSize = "30px"; document.querySelector("#mensaje").innerHTML = "<b>¡Uups!</b>No tienes suficiente dinero<br>Compra fichas..."; document.getElementById("ventanaCompra").style.display = "block"; $('#box').bounceBoxToggle(); } function dineroAcumulado(d)//dinero que tengo disponible para jugar { dinero = dinero + d; //document.querySelector("#dinero").innerHTML = dinero+"€"; document.getElementById("dinero").innerHTML = dinero+"€"; } var gana = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; function dineroApuesta(dineroFicha,n)//operaciones del juego { var gananciaTotal = 0; for(var j=0; j<vectorJugadas.length; j++){ for(var i=0; i<negros.length; i++) { if( (vectorJugadas[j].casillas==negros[i] || vectorJugadas[j].casillas==rojos[i]) && n==vectorJugadas[j].casillas ) { gana[j]=dineroFicha*35+dineroFicha; //console.log(gana[j]); break; } }} for(var j=0; j<vectorJugadas.length; j++){ for(var i=0; i<negros.length; i++) { if( (vectorJugadas[j].casillas=="NEGROS") && n==negros[i] ) { gana[j]=dineroFicha*2; break; } }} for(var j=0; j<vectorJugadas.length; j++){ for(var i=0; i<rojos.length; i++) { if( (vectorJugadas[j].casillas=="ROJOS") && n==rojos[i] ) { gana[j]=dineroFicha*2; break; } }} for(var j=0; j<vectorJugadas.length; j++){ if(vectorJugadas[j].casillas=="PARES") { if(n%2==0 && (n!="00" || n!="0") ) { gana[j]=dineroFicha*2; } }} for(var j=0; j<vectorJugadas.length; j++){ if(vectorJugadas[j].casillas=="IMPARES") { if(n%2!=0 && (n!="00" || n!="0") ) { gana[j]=dineroFicha*2; } }} for(var j=0; j<vectorJugadas.length; j++){ if(vectorJugadas[j].casillas=="1A18") { for(var i=1;i<=18;i++) { if(i==n) { gana[j]=dineroFicha*2; } } }} for(var j=0; j<vectorJugadas.length; j++){ if(vectorJugadas[j].casillas=="19A36") { for(var i=19;i<=36;i++) { if(i==n) { gana[j]=dineroFicha*2; } } }} for(var j=0; j<vectorJugadas.length; j++){ if(vectorJugadas[j].casillas=="PRIMEROS12") { for(var i=1;i<=12;i++) { if(i==n) { gana[j]=dineroFicha*2+dineroFicha; } } }} for(var j=0; j<vectorJugadas.length; j++){ if(vectorJugadas[j].casillas=="SEGUNDOS12") { for(var i=13;i<=24;i++) { if(i==n) { gana[j]=dineroFicha*2+dineroFicha; } } }} for(var j=0; j<vectorJugadas.length; j++){ if(vectorJugadas[j].casillas=="TERCEROS12") { for(var i=25;i<=36;i++) { if(i==n) { gana[j]=dineroFicha*2+dineroFicha; } } }} for(var j=0; j<vectorJugadas.length; j++){ if(vectorJugadas[j].casillas=="1-2A1") { for(var i=1;i<=34;i=i+3) { if(i==n) { gana[j]=dineroFicha*2+dineroFicha; } } }} for(var j=0; j<vectorJugadas.length; j++){ if(vectorJugadas[j].casillas=="2-2A1") { for(var i=2;i<=35;i=i+3) { if(i==n) { gana[j]=dineroFicha*2+dineroFicha; } } }} for(var j=0; j<vectorJugadas.length; j++){ if(vectorJugadas[j].casillas=="3-2A1") { for(var i=3;i<=36;i=i+3) { if(i==n) { gana[j]=dineroFicha*2+dineroFicha; } } }} for(var j=0; j<vectorJugadas.length; j++){ gananciaTotal = gananciaTotal + gana[j]; } ganaPierde(gananciaTotal,n); } function ganaPierde(gananciaTotal,n) { dineroAcumulado(gananciaTotal); document.getElementById('ventanaGanaPierde').style.display = "block"; var mensaje = '<div id="cerrar"> <a href="javascript:cerrarVentana()"><img src="../../img/cancel.png"></a> </div>'; for(var i=0; i<vectorJugadas.length; i++) { // console.log(gana[i]); if(gana[i] == 0) { //perdió mensaje = mensaje +'<br>¡PERDISTE!<br>Apuesta de: '+vectorJugadas[i].fichas+'€ en: '+vectorJugadas[i].casillas+'<br>'; } else { //Ganó mensaje = mensaje +'<br>¡GANASTE!<br>Apuesta de: '+vectorJugadas[i].fichas+'€ en: '+vectorJugadas[i].casillas+'<br>'; } } mensaje = mensaje +'<br><br>Numero resultado: '+n+'<br>Tenías: '+(vectorJugadas[0].dineros)+'€<br>Ahora tienes: '+dinero+'€' ; document.getElementById('ventanaGanaPierde').innerHTML = mensaje; for(var i=0;i<48;i++) { quitarFicha(tapete[i]); } casilla=0; ficha=0; while(vectorJugadas.length > 0){ vectorJugadas.pop(); gana.pop(); } gana = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; numeroResultado("¿?"); } function cerrarVentana() { document.getElementById('ventanaGanaPierde').style.display = "none"; } function numeroResultado(n) { for(var i=0;i<18;i++) { if(n==negros[i]) { document.getElementById('bola').style.color = "#000"; break; } } for(var i=0;i<18;i++) { if(n==rojos[i]) { document.getElementById('bola').style.color = "red"; break; } } if(n=="0" || n=="00") { document.getElementById('bola').style.color = "rgb(11, 253, 71)"; } if (!/^([0-9])*$/.test(n)) { }else if(n=="00" || n=="0") { dineroApuesta(ficha,n); }else { dineroApuesta(ficha,n); } document.querySelector("#bola").innerHTML = n; } //Calcular en que angulo se detuvo la ruleta para así determinar el numero resultado function calcular(rand){ valor = rand / 360; valor = (valor - parseInt(valor.toString().split(".")[0])) * 360;//queda en valores entre 0-360 document.getElementById('bola').style.color = "rgb(11, 253, 71)"; numeroResultado("¿?"); ruleta.style.transform = "rotate("+rand+"deg)"; ruleta.detenerRotacionRuleta; setTimeout(()=>{ switch(true){ case valor > 4.736842105263 && valor <= 14.210526315763: numeroResultado(31); break; case valor > 14.210526315763 && valor <= 23.684210526263: numeroResultado(19); break; case valor > 23.684210526263 && valor <= 33.157894736763: numeroResultado(8); break; case valor > 33.157894736763 && valor <= 42.631578947263: numeroResultado(12); break; case valor > 42.631578947263 && valor <= 52.105263157763: numeroResultado(29); break; case valor > 52.105263157763 && valor <= 61.578947368263: numeroResultado(25); break; case valor > 61.578947368263 && valor <= 71.052631578763: numeroResultado(10); break; case valor > 71.052631578763 && valor <= 80.526315789263: numeroResultado(27); break; case valor > 80.526315789263 && valor <= 89.999999999763: numeroResultado("00"); break; case valor > 89.999999999763 && valor <= 99.473684210263: numeroResultado(1); break; case valor > 99.473684210263 && valor <= 108.947368420763: numeroResultado(13); break; case valor > 108.94736842076 && valor <= 118.42105263126: numeroResultado(36); break; case valor > 118.42105263126 && valor <= 127.89473684176: numeroResultado(24); break; case valor > 127.89473684176 && valor <= 137.36842105226: numeroResultado(3); break; case valor > 137.36842105226 && valor <= 146.84210526276: numeroResultado(15); break; case valor > 146.84210526276 && valor <= 156.31578947326: numeroResultado(34); break; case valor > 156.31578947326 && valor <= 165.78947368376: numeroResultado(22); break; case valor > 165.78947368376 && valor <= 175.26315789426: numeroResultado(5); break; case valor > 175.26315789426 && valor <= 184.73684210476: numeroResultado(17); break; case valor > 184.73684210476 && valor <= 194.21052631526: numeroResultado(32); break; case valor > 194.21052631526 && valor <= 203.68421052576: numeroResultado(20); break; case valor > 203.68421052576 && valor <= 213.15789473626: numeroResultado(7); break; case valor > 213.15789473626 && valor <= 222.63157894676: numeroResultado(11); break; case valor > 222.63157894676 && valor <= 232.10526315726: numeroResultado(30); break; case valor > 232.10526315726 && valor <= 241.57894736776: numeroResultado(26); break; case valor > 241.57894736776 && valor <= 251.05263157826: numeroResultado(9); break; case valor > 251.05263157826 && valor <= 260.52631578876: numeroResultado(28); break; case valor > 260.52631578876 && valor <= 269.99999999926: numeroResultado(0); break; case valor > 269.99999999926 && valor <= 279.47368420976: numeroResultado(2); break; case valor > 279.47368420976 && valor <= 288.94736842026: numeroResultado(14); break; case valor > 288.94736842026 && valor <= 298.42105263076: numeroResultado(35); break; case valor > 298.42105263076 && valor <= 307.89473684126: numeroResultado(23); break; case valor > 307.89473684126 && valor <= 317.36842105176: numeroResultado(4); break; case valor > 317.36842105176 && valor <= 326.84210526226: numeroResultado(16); break; case valor > 326.84210526226 && valor <= 336.31578947276: numeroResultado(33); break; case valor > 336.31578947276 && valor <= 345.78947368326: numeroResultado(21); break; case valor > 345.78947368326 && valor <= 355.26315789376: ruleta.detenerRotacionRuleta; numeroResultado(6); break; case (valor > 355.2631578937 && valor <=360) || (valor >0 && valor <= 4.7368421052631): numeroResultado(18); break; }},800); } $(document).ready(function(){ /*Convirtiendo el #box div en un bounceBox: */ $('#box').bounceBox(); /* Escuchar el evento de clic y alternar la casilla: */ $('#tablero').click(function(e){ if(ficha==0){ $('#box').bounceBoxToggle(); e.preventDefault(); } else{ $('#box').bounceBoxHide(); } }); $('#tablero2').click(function(e){ if(ficha==0){ $('#box').bounceBoxToggle(); e.preventDefault(); } else{ $('#box').bounceBoxHide(); } }); $('#tablero3').click(function(e){ if(ficha==0){ $('#box').bounceBoxToggle(); e.preventDefault(); } else{ $('#box').bounceBoxHide(); } }); $('#jugar').click(function(e){ cerrarVentana(); if(ficha==0){ error(); e.preventDefault(); }else if(casilla==0){ error(); e.preventDefault(); }else{ for(var i=0; i<48; i++){ if(tapete[i]==casilla) { girar(); break; } } } }); /*Cuando haga clic en el cuadro, escóndelo: */ $('#box').click(function(){ $('#box').bounceBoxHide(); }); $('#ventanaGanaPierde').click(function(){ cerrarVentana(); }); //cerrar }); //DECLARO ENTER var teclas = { ENTER: 13, ESC: 27 }; //OBTENGO LA CAPTURA DEL TECLADO Y LLAMO a mi funcion document.addEventListener("keydown",botonCerrarIniciar); function botonCerrarIniciar(evento) { switch(evento.keyCode) { case teclas.ESC: if( (document.getElementById('ventanaGanaPierde').style.display = "block") ) { cerrarVentana(); } break; case teclas.ENTER: if( (ficha==0) && ( document.getElementById('ventanaGanaPierde').style.display = "none" ) ) { error(); evento.preventDefault(); }else if(casilla==0) { error(); evento.preventDefault(); }else{ for(var i=0; i<48; i++) { if(tapete[i]==casilla) { girar(); break; } } } break; } } function error() { document.getElementById("mensaje").style.fontSize = "20px"; document.querySelector("#mensaje").innerHTML = "<b>¡Falta algo!</b>1. Seleciona una ficha<br>2. Haz tu apuesta en el tablero<br>3. ¡jugar!"; $('#box').bounceBoxToggle(); } /* <audio id="audio" controls> <source type="audio/wav" src="audio.wav"> </audio> #audio{ display: none } */<file_sep>/app/model/Result.php <?php class Result { private $cur_res; public function __construct() { $this->cur_res = NULL; } public function setCur_res($cur_res) { $this->cur_res = $cur_res; } public function getNumberRows(){ if ($this->cur_res != NULL) return ($this->cur_res->num_rows); } public function getRows() { $rows = array(); if ($this->cur_res != NULL){ for($x = 0; $x < $this->cur_res->num_rows; $x++) { $rows[$x] = $this->cur_res->fetch_assoc(); } } return $rows; } public function free(){ $this->cur_res->free(); } } ?><file_sep>/app/model/UserModel.php <?php class UserModel { public $ide_use; public $log_use; public $pas_use; public $nom_use; public $ape_use; public $ema_use; public $cel_use; public $ced_use; public function __construct($ide, $log, $pas, $nom, $ape, $ema, $cel, $ced) { $this->ide_use = $ide; $this->log_use = $log; $this->pas_use = $pas; $this->nom_use = $nom; $this->ape_use = $ape; $this->ema_use = $ema; $this->cel_use = $cel; $this->ced_use = $ced; } public function getIde_use() { return ($this->ide_use); } public function getLog_use() { return ($this->log_use); } public function getPas_use() { return ($this->pas_use); } public function getNom_use() { return ($this->nom_use); } public function getApe_use() { return ($this->ape_use); } public function getEma_use(){ return ($this->ema_use); } public function getCel_use(){ return ($this->cel_use); } public function getCed_use(){ return ($this->ced_use); } public function setIde_use ($ide_use) { $this->ide_use = $ide_use; } public function setLog_use ($log_use) { $this->log_use = $log_use; } public function setPas_use ($pas_use) { $this->pas_use = $pas_use; } public function setNom_use ($nom_use) { $this->nom_use = $nom_use; } public function setApe_use ($ape_use) { $this->ape_use = $ape_use; } public function setEma_use ($ema_use) { $this->ema_use = $ema_use; } public function setCel_use ($cel_use) { $this->cel_use = $cel_use; } public function setCed_use ($ced_use) { $this->ced_use = $ced_use; } } ?> <file_sep>/app/view/WelcomeUserView.php <?php require_once('../model/UserModel.php'); require_once('../controller/UserController.php'); session_start(); if (isset($_SESSION['use'])) { $use = unserialize($_SESSION['use']); ?> <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://fonts.googleapis.com/css?family=Raleway:400,700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css"> <link rel="stylesheet" href="../../css/estilos.css"> <link rel="stylesheet" href="../../css/index.css"> <!-- colocar icono en la barra--> <link rel="stylesheet icon" href="../../images/Logo-miniaturaR.png" type="image/png"> <title><NAME> - MENÚ</title> </head> <body> <header class="header"> <!-- logo --> <figure class="header-brand"> <img src="../../images/LogoR.png" alt="logo de la empresa"> </figure> <!-- menu --> <nav class="header-menu"> <ol> <li><h2><a href="../../index.php">Cerrar Sesion</a></h2></li> </ol> </nav> </header> <!--Cuerpo de la pagina --> <main> <section class="content3"> <div class="contenedor-form"> <div class="form-menu"> <div class="formulario"> <div class="toggle"> <span>Perfil</span> </div> <h1 class="form-title">MENÚ<br><br><br><br></h1> <button type="submit" class="form-button2" id="btn-abrir-popup" >Manual</button><br><br><br> <button type="submit" class="form-button2" id="btn-abrir-popup2">Consejos</button><br><br><br> </div> <div class="formulario"> <div class="toggle"> <span>Ayuda</span> </div> <h1></h1> <p class="form-title-bienvenido">BIENVENIDO(A)<br><br> <br><br><b><?php echo strtoupper("".$use->getNom_use()." ".$use->getApe_use(). "<br>Usuario: ".$use->getLog_use(). "<br>" ) ?></b></p> <br><br><br> <form action="JuegoRULETA.php" method="post"> <input type="submit" value="Jugar"> </form><br><br> <form action="login.php" method="post"> <input type="submit" value="Salir"> </form> </div> </div> <div class="reset-password"> </div> </div> </section> </main> <div class="overlay" id="overlay"> <div class="popup" id="popup"> <a href="#" id="btn-cerrar-popup" class="btn-cerrar-popup"><i class="fas fa-times"></i></a> <h3>Manual de usuario</h3> <form action=""> <div class="contenedor-inputs"> <h4> <p class="centrar-letra"><b>Aqui tienes todo lo que necesitas saber para jugar.</b></p> <br> <b>En qué consiste el Juego:</b> El juego consiste básicamente en seleccionar el monto de dinero con el que se desea iniciar, luego seleccionar una de las tres fichas opcionales para apostar, después elegir uno de los 38 números u otras opciones presentes en el tablero para finalmente presionar el botón jugar. Una vez iniciado el juego se mostrará una pequeña animación de la ruleta girando, cuando la ruleta deja de girar, la casilla se detiene, indica el número ganador de la apuesta. <br><br>El juego contará con tres tipos de fichas, la cual cada ficha contará con un valor y un color diferente, los valores y los colores de las fichas son los siguientes: <br><br> <b>Ficha rosa: valor 10 y equivale a 10 euro.<br>Ficha verde: valor 50 y equivale a 50 euros.<br>Ficha azul: valor 20 y equivale a 20 euros.</b> </h4> </div> </form> </div> </div> <div class="overlay" id="overlay2"> <div class="popup" id="popup2"> <a href="#" id="btn-cerrar-popup2" class="btn-cerrar-popup"><i class="fas fa-times"></i></a> <h3>Posibilidades con las cuales se puede apostar y ganar en la ruleta.</h3> <form action=""> <div class="contenedor-inputs"> <h4> <p class="centrar-letra"><b>Aqui tienes algunas jugadas que debes tener en cuenta.</b></p> <br> <b>Pleno o número completo:</b> Consiste en la apuesta a uno de los 36 números disponibles a excepción del 0 y 00, el pago de esta apuesta corresponde a 35 veces la postura. <br><br> <b>La docena:</b> Como su nombre lo indica este tipo de apuesta abarca 12 números, la primera docena son los números que van del 1 al 12, la segunda docena son los números que van del 13 al 24 y la tercera docena son los números que van del 25 al 36, el pago por la docena es de 2 veces la postura. <br><br> <b>Columna:</b> cuenta con una columna entera y se coloca en la casilla de "2-1" al final de una columna, el pago de esta apuesta corresponde a 2 veces su postura. <br><br> <b>Apuesta sobre colores:</b> cuenta con todos los números rojos o todos los números negros en el paño y se coloca en la casilla de "Rojo" (Todos los números rojos) o en la de "Negro" (todos los números negros), el pago a esta apuesta corresponde a 1 vez su postura. <br><br> <b>Par/Impar:</b> cuenta con todos los números pares o todos los números impares en el paño y las fichas se colocan en la casilla "Par" (todos los números pares) o en la de "impar" (todos los números impares), el pago de esta apuesta corresponde a 1 vez su postura. <br><br> <b>Pasa/Falta:</b> Cuenta con todos los números bajos o todos los números altos, las fichas se colocan en la casilla de "Falta" (números de 1 a 18) o en la de "Pasa" (números del 19 al 36), el pago de esta apuesta corresponde a 1 vez su postura. </h4> </div> </form> </div> </div> <script src="../../js/jquery-3.1.1.min.js"></script> <script src="../../js/main.js"></script> <script src="../../js/popup.js"></script> </div> </div> </body> </html> <?php //Para no permitir acceso a la pagina sin logearse }else{ echo "Acceso no autorizado"; } ?><file_sep>/app/view/JuegoRULETA.php <?php require_once('../model/UserModel.php'); require_once('../controller/UserController.php'); session_start(); if (isset($_SESSION['use'])) { $cuse = new UserController(); $use = unserialize($_SESSION['use']); //$cuse->updateUser( $use , $_POST['money']); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=0.44"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="../../css/estilo.css"> <link rel="stylesheet icon" href="../../images/Logo-miniaturaR.png" type="image/png"> <title>RULETA HAZE - JUEGO</title> </head> <!-- The core Firebase JS SDK is always required and must be listed first --> <script src="https://www.gstatic.com/firebasejs/7.6.0/firebase-app.js"></script> <!-- TODO: Add SDKs for Firebase products that you want to use https://firebase.google.com/docs/web/setup#available-libraries --> <script src="https://www.gstatic.com/firebasejs/7.6.0/firebase-analytics.js"></script> <script> // Your web app's Firebase configuration var firebaseConfig = { apiKey: "<KEY>", authDomain: "juegoruletabd.firebaseapp.com", databaseURL: "https://juegoruletabd.firebaseio.com", projectId: "juegoruletabd", storageBucket: "juegoruletabd.appspot.com", messagingSenderId: "623344972327", appId: "1:623344972327:web:9a34efe1ef2ded3005d402", measurementId: "G-504L618YZV" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); firebase.analytics(); </script> <body> <header class="header"> <!-- logo --> <figure class="header-brand"> </figure> <!-- menu --> <nav class="header-menu"> <ol> <li><h2> <a href="../../app/view/WelcomeUserView.php"><?php echo strtoupper("".$use->getNom_use()." ".$use->getApe_use() )?></a></h2></li> </ol> </nav> </header> <div class="ventana" onclick=clickaction(this) id="ventanaGanaPierde" style="display: none;"> <div id="cerrar"> <a href="javascript:cerrarVentana()"><img src="../../img/cancel.png"></a> </div> </div> <div> <h1 style="color: darkseagreen;"></h1> <h1 id="titulo" style="color: darkseagreen; ">R U L E T A&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A M E R I C A N A</h1> <canvas id="juego" width="1720" height="701"></canvas> <p id="pregunta">¿Cúanto dinero tienes disponible?</p> <div class="button" id="jugar" href ="">Jugar</div> <div class="vara"></div> <img src="../../img/mesa.png" id="ruleta_mesa"> <img src="../../img/imagen.png" id="ruleta"> <div class="bola" id="bola"></div> <div class="dinero" name="dinero" id="dinero">0€</div> <input type="button" class="botonimagen1" value="" onclick=clickaction(this) id="b1"/> <input type="button" class="botonimagen5" value="" onclick=clickaction(this) id="b5"/> <input type="button" class="botonimagen10"value="" onclick=clickaction(this) id="b10"/> <table class="tablero" id ="tablero"> <tr> <td><button onclick=clickaction(this) id="3"></button></td> <td><button onclick=clickaction(this) id="6"></button></td> <td><button onclick=clickaction(this) id="9"></button></td> <td><button onclick=clickaction(this) id="12"></button></td> <td><button onclick=clickaction(this) id="15"></button></td> <td><button onclick=clickaction(this) id="18"></button></td> <td><button onclick=clickaction(this) id="21"></button></td> <td><button onclick=clickaction(this) id="24"></button></td> <td><button onclick=clickaction(this) id="27"></button></td> <td><button onclick=clickaction(this) id="30"></button></td> <td><button onclick=clickaction(this) id="33"></button></td> <td><button onclick=clickaction(this) id="36"></button></td> <td><button onclick=clickaction(this) id="3-2A1"></button></td> </tr> <tr> <td><button onclick=clickaction(this) id="2"></button></td> <td><button onclick=clickaction(this) id="5"></button></td> <td><button onclick=clickaction(this) id="8"></button></td> <td><button onclick=clickaction(this) id="11"></button></td> <td><button onclick=clickaction(this) id="14"></button></td> <td><button onclick=clickaction(this) id="17"></button></td> <td><button onclick=clickaction(this) id="20"></button></td> <td><button onclick=clickaction(this) id="23"></button></td> <td><button onclick=clickaction(this) id="26"></button></td> <td><button onclick=clickaction(this) id="29"></button></td> <td><button onclick=clickaction(this) id="32"></button></td> <td><button onclick=clickaction(this) id="35"></button></td> <td><button onclick=clickaction(this) id="2-2A1"></button></td> </tr> <tr> <td><button onclick=clickaction(this) id="1"></button></td> <td><button onclick=clickaction(this) id="4"></button></td> <td><button onclick=clickaction(this) id="7"></button></td> <td><button onclick=clickaction(this) id="10"></button></td> <td><button onclick=clickaction(this) id="13"></button></td> <td><button onclick=clickaction(this) id="16"></button></td> <td><button onclick=clickaction(this) id="19"></button></td> <td><button onclick=clickaction(this) id="22"></button></td> <td><button onclick=clickaction(this) id="25"></button></td> <td><button onclick=clickaction(this) id="28"></button></td> <td><button onclick=clickaction(this) id="31"></button></td> <td><button onclick=clickaction(this) id="34"></button></td> <td><button onclick=clickaction(this) id="1-2A1"></button></td> </tr> </table> <table class="tablero2" id ="tablero2"> <tr> <td><button onclick=clickaction(this) id="PRIMEROS12"></button></td> <td><button onclick=clickaction(this) id="SEGUNDOS12"></button></td> <td><button onclick=clickaction(this) id="TERCEROS12"></button></td> </tr> </table> <table class="tablero3" id ="tablero3"> <tr> <td><button onclick=clickaction(this) id="1A18"></button></td> <td><button onclick=clickaction(this) id="PARES"></button></td> <td><button onclick=clickaction(this) id="ROJOS"></button></td> <td><button onclick=clickaction(this) id="NEGROS"></button></td> <td><button onclick=clickaction(this) id="IMPARES"></button></td> <td><button onclick=clickaction(this) id="19A36"></button></td> </tr> </table> </div> <div class = "ventanaCompra" id="ventanaCompra" style="display: block;">CAJA <input type="button" class="boton100euro" value="" onclick=clickaction(this) id="100€"/> <input type="button" class="boton200euro" value="" onclick=clickaction(this) id="200€"/> <input type="button" class="boton500euro" value="" onclick=clickaction(this) id="500€"/> </div> <div id="box"> <p id="mensaje"></p> </div> <script src="../../js/dibujo.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="../../js/bouncebox-plugin/jquery.easing.1.3.js"></script> <script type="text/javascript" src="../../js/bouncebox-plugin/jquery.bouncebox.1.0.js"></script> <script type="text/javascript" src="../../js/script.js"></script> </body> </html> <?php //Para no permitir acceso a la pagina sin logearse }else{ echo "Acceso no autorizado"; } ?><file_sep>/app/controller/UserController.php <?php require_once('../model/UserModel.php'); require_once('../model/Connection.php'); class UserController { public $con; public $lis; public $use; public $men; public function __construct() { $lis = array(); } public function login($user, $password) { $find = false; $sql = "SELECT num_use, log_use, pas_use, nom_use, ape_use, ema_use, cel_use, ced_use FROM user WHERE log_use = '".$user."' AND pas_use=md5('".$password."')"; $con = new Connection(); $con->setDat_con('ruleta'); $con->open(); $result = $con->executeSentence($sql); $this->men = $con->getErr_con(); $con->close(); if (is_array($result)) { $this->getUsers($result); $this->use = $this->lis[0]; if ($this->use != NULL) { $find = true; } } return $find; } public function addUser($use) { $sql = "INSERT INTO user(log_use, pas_use, nom_use, ape_use, ema_use, cel_use, ced_use) VALUES ('".$use->getLog_use()."', md5('".$use->getPas_use()."'), '".$use->getNom_use()."', '".$use->getApe_use()."', '".$use->getEma_use()."', '".$use->getCel_use()."', '".$use->getCed_use()."')"; $con = new Connection(); $con->setDat_con('ruleta'); $con->open(); $result = $con->executeSentence($sql); $this->men = $con->getErr_con(); $con->close(); return $result; } public function getUsers($result) { foreach ($result as $value) { $this->lis[] = new UserModel($value['num_use'], $value['log_use'], $value['pas_use'], $value['nom_use'], $value['ape_use'], $value['ema_use'], $value['cel_use'], $value['ced_use']); } } } ?><file_sep>/app/view/login.php <?php require_once('../controller/UserController.php'); require_once('../model/UserModel.php'); //Login if (isset($_POST['user']) && isset($_POST['password'])) { $cuse = new UserController(); $find = $cuse->login($_POST['user'], $_POST['password']); if ($find == true){ session_start(); $_SESSION['use'] = serialize ($cuse->use); header('Location: WelcomeUserView.php'); } } //Registro if (isset($_POST['name']) && isset($_POST['lastname']) && isset($_POST['user']) && isset($_POST['password']) && isset($_POST['email']) && isset($_POST['cel']) && isset($_POST['document'])) { $cuse = new UserController(); $use = new UserModel(0, $_POST['user'], $_POST['password'], $_POST['name'], $_POST['lastname'], $_POST['email'], $_POST['cel'], $_POST['document']); $result = $cuse->addUser($use); if ($result == true){ header('Location: login.php'); } } ?> <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://fonts.googleapis.com/css?family=Raleway:400,700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="../../css/index.css"> <link rel="stylesheet" href="../../css/form.css"> <link rel="stylesheet" href="../../css/inicio.css"> <link rel="stylesheet icon" href="../../images/Logo-miniaturaR.png" type="image/png"> <title>RULETA HAZE - LOGIN</title> </head> <body> <header class="header"> <!-- logo --> <figure class="header-brand"> <img src="../../images/LogoR.png" alt="logo de la empresa"> </figure> <!-- menu --> <nav class="header-menu"> <ol> <li><h2><a href="../../index.php">Menú principal</a></h2></li> </ol> </nav> </header> <div class="contenedor-form"> <div class="toggle"> <span></span> </div> <div class="formulario"> <h2>Iniciar Sesión</h2> <form action="login.php" method="post"> <div class="toggle"> <span>Crear Cuenta</span> </div> <div class="form-error"> <?php if (isset($find)) { if ($find == false) { echo 'Usuario o contraseña incorrecta <br><br> '.$cuse->men.''; } } ?> </div> <input class="form-text" type="text" placeholder="Usuario" name="user" required> <input class="form-text" type="password" placeholder="<PASSWORD>" name="<PASSWORD>" required> <input type="submit" value="Iniciar Sesión"> </form> </div> <div class="formulario"> <h2>Crea tu Cuenta</h2> <form action="login.php" method="post"> <div class="toggle"> <span>Iniciar Sesion</span> </div> <input class="form-text" type="text" placeholder="Nombre" name="name" required> <input class="form-text" type="text" placeholder="Apellido" name="lastname" required> <input class="form-text" type="text" placeholder="Usuario" name="user" required> <input class="form-text" type="password" placeholder="<PASSWORD>" name="password" required> <input class="form-text" type="email" placeholder="Correo Electronico" name="email" required> <input class="form-text" type="text" placeholder="Numero Celular/Telefonico" name="cel" required> <input class="form-text" type="text" placeholder="Documento de Identidad" name="document" required> <p>Al registrarte, aceptas nuestras Condiciones de uso y Política de privacidad.</p> <!--p>¿Ya tienes una cuenta? <b><a class="form-link" href="login.php">Iniciar sesión</a></b></p--> <input type="submit" value="Registrarse"> </form> </div> <div class="reset-password"> </div> </div> <script src="../../js/jquery-3.1.1.min.js"></script> <script src="../../js/main.js"></script> </body> </html><file_sep>/app/model/Connection.php <?php require_once('Result.php'); class Connection { private $hos_con; private $use_con; private $pas_con; private $dat_con; private $lin_con; private $res_con; private $cur_con; private $sec_con; private $err_con; public function __construct($hos_con = 'localhost', $use_con='root', $pas_con='') { $this->hos_con = $hos_con; $this->use_con = $use_con; $this->pas_con = $pas_con; $this->res_con = new Result(); } public function setDat_con($dat_con) { $this->dat_con = $dat_con; } public function getErr_con() { return $this->err_con; } public function getRes_con() { return $this->res_con; } public function open () { $this->lin_con = new mysqli($this->hos_con, $this->use_con, $this->pas_con, $this->dat_con); $this->err_con = $this->lin_con->connect_error; if ($this->lin_con->connect_error) { die('Error de Conexión '. $this->lin_con->connect_error); } else { $acentos = $this->lin_con->query("SET NAMES 'utf8'"); } } public function close () { $this->lin_con->close(); } public function executeSentence($sql) { $rows = false; $this->cur_con = $this->lin_con->query($sql); $this->err_con = $this->lin_con->error; if (is_object($this->cur_con) == true) { if (get_class ($this->cur_con) == "mysqli_result") { $this->res_con->setCur_res($this->cur_con); $rows = $this->res_con->getRows(); } } else { $rows = $this->cur_con; } return $rows; } // // Sends the query to the connection // public function Query($sql) { // $this->result = $this->lin_con->query($sql) or die(mysqlierror($this->result)); // $this->numRows = mysqlinumrows($this->result); // } // // Inserts into databse // public function UpdateDb($sql) { // $this->result = $this->lin_con->query($sql) or die(mysqlierror($this->result)); // return $this->result; // } // // Return the number of rows // public function NumRows() { // return $this->numRows; // } // // Used by other classes to get the connection // public function Getlin_con() { // return $this->lin_con; // } // // Securing input data // public function SecureInput($value) { // return mysqlirealescapestring($this->lin_con, $value); // } } ?><file_sep>/js/animacionEstrella.js var n_estrellas = 50; var cv, cx, estrellas = []; var vel_max = 500; function prepararEstrella(index) { estrellas[index] = { 'color' : 'rgb(' +(Math.random() * 255) + ',' +(Math.random() * 255) + ',' +(Math.random() * 255) + ')', 'vel_x' : (Math.random() * vel_max * 2) - vel_max + 1, 'vel_y' : (Math.random() * vel_max * 2) - vel_max + 1, 'x' : 250, 'y' : 250 }; } function pintar() { // Limpiar el área con un cuadro negro cx.fillStyle = 'transparent'; document.getElementById('juego').style.backgroundColor = "transparent"; cx.fillRect(0,-50,1600,700); cx.fillStyle = '#fff'; for(var i = 0; i < n_estrellas; i++) { var e = estrellas[i]; cx.fillStyle = e.color; if(e.x > 1600 || e.y > 700 || e.x < 0 || e.y < -50) { prepararEstrella(i); } // Hacer el incremento de la posición // de las estrellas en pantalla. e.x += e.vel_x; e.y += e.vel_y; // Pintar la estrella cx.fillRect(e.x,e.y,2, 2); } setTimeout(pintar, 25); } window.onload = function() { cv = document.getElementById('juego'); cx = cv.getContext('2d'); for(var i = 0; i < n_estrellas; i++) { prepararEstrella(i); } pintar(); };<file_sep>/app/model/dineroModel.php <?php class dineroModel { public $dinero; public function __construct($dinero) { $this->dinero = $dinero; } public function getDinero_use(){ return ($this->dinero); } public function setDinero_use ($dinero) { $this->dinero = $dinero; } } ?> <file_sep>/BASE-DE-DATOS/ruleta.sql -- phpMyAdmin SQL Dump -- version 4.9.0.1 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 21-10-2019 a las 21:18:45 -- Versión del servidor: 10.3.16-MariaDB -- Versión de PHP: 7.3.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `ruleta` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `user` -- CREATE TABLE `user` ( `num_use` int(11) NOT NULL, `log_use` varchar(50) NOT NULL, `pas_use` text NOT NULL, `nom_use` varchar(50) NOT NULL, `ape_use` varchar(50) NOT NULL, `ema_use` varchar(50) NOT NULL, `cel_use` int(15) NOT NULL, `ced_use` int(15) NOT NULL, `eda_use` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `user` -- INSERT INTO `user` (`num_use`, `log_use`, `pas_use`, `nom_use`, `ape_use`, `ema_use`, `cel_use`, `ced_use`, `eda_use`) VALUES (30, 'pepe', '81dc9bdb52d04dc20036dbd8313ed055', 'pepe', 'pepe', 'pepe', 0, 0, 0); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`num_use`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `user` -- ALTER TABLE `user` MODIFY `num_use` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=31; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/js/dibujo.js var d = document.getElementById('juego'); var lienzo = d.getContext("2d"); var lineas = 700; var t = document.getElementById('juego'); var tab = t.getContext('2d'); tab.beginPath('tablero'); for(l=0;l<lineas;l++) { dibujarLinea("#fff",0,10*l,10*(l+1),700); } dibujarLinea("#fff",1,1,1,699); dibujarLinea("#fff",1,699,1499,699); function dibujarLinea(color,xInicial,yInicial,xFinal,yFinal) { lienzo.beginPath(); lienzo.strokeStyle = color; lienzo.moveTo(xInicial,yInicial); lienzo.lineTo(xFinal,yFinal); lienzo.stroke(); lienzo.closePath(); } <file_sep>/README.md # JuegoRULETA Juego de la Ruleta, con inicio de sesión y registro, desarrollado en HTML, CSS, JS, PHP, MySQL...
bea23a3f7bffc7bd89e5797b154a88d01ea90f3b
[ "JavaScript", "SQL", "Markdown", "PHP" ]
13
JavaScript
englergonzalez/JuegoRULETA
0771225042d5aff73cdf669f8549e158e7d08c2a
cecb8d9c9232b6dd290b2558b6357b545e69e018
refs/heads/master
<repo_name>leiqing110/C-learning<file_sep>/README.md # C-learning C++learning <file_sep>/2018_2_27/static/static/2.cpp //File2 #include<iostream> using namespace std; extern int n; void fn() { n++; cout<<n<<endl; } <file_sep>/2018_2_27/static/static/1.cpp //File1 #include<iostream> using namespace std; void fn(); int n; //定义静态全局变量 ,尝试加上static关键字是否能成功 int main(void) { n = 20; cout<<n<<endl; fn(); return 0; }
4c4abec32706abbd468cdef392efea2d95bbc6c1
[ "Markdown", "C++" ]
3
Markdown
leiqing110/C-learning
2624fb161e233912ee2f99a4101f3b1f5a376163
9805c98fec5055831904129a1359c6161e9a0ae6
refs/heads/master
<repo_name>themoffatt/sample<file_sep>/sample_web_api_controller/Bookcase.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Morningstar_sample.Models { public class Bookcase { //Excluding validation, business logic, logging, etc public List<Shelf> shelves { get; set; } //Constructor for example purposes only public Bookcase() { //Generate some shelves shelves = new List<Shelf>(); for (int i = 0; i <= 3; i++) { Shelf shelf = new Shelf(); shelf.title = "shelf " + i; shelf.id = "s" + i; shelf.books.Add(new Book("Title " + i)); //shelf.books.Add(new Book("Title 2", generateFakeISBN(), "<NAME>", getRandomGenre())); this.shelves.Add(shelf); } } } }<file_sep>/sample_web_api_controller/Full Sample/Morningstar_homework/Morningstar_homework/Controllers/DataController.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Morningstar_homework.Models; using Newtonsoft.Json; namespace Morningstar_homework.Controllers { public class DataController : ApiController { //For all calls, I'm simply using an instance of the Bookcase class that contains sample data, instead of any database or data file. Bookcase bookCase = new Bookcase(); //SPEC: "GET: A GET on /data/ should return all books" //This will return all books on all shelves, without data indicating which shelves the books are on. //GET api/data public List<Book> Get() { List<Book> books = new List<Book>(); foreach (Shelf shelf in bookCase.shelves) { foreach (Book book in shelf.books) { books.Add(book); } } return books; } //SPEC: "GET: A GET call on /data/<genre> should return all books of a certain genre" // GET api/data/<genre> public List<Book> Get(string input) { //This does return any books that match the genre specified in the request, //but because the 'book case' is being re-generated every time this class is //called, you may or may not see results. You also won't see results from this //based on what is seen when api/data is called by itself. This would obviously //not be the case in a real application where a real data store was being used. List<Book> books = new List<Book>(); foreach (Shelf shelf in bookCase.shelves) { foreach (Book book in shelf.books) { if (book.genre.ToUpper() == input.ToUpper()) { books.Add(book); } } } return books; } //SPEC: PUT: A PUT call with stringified data to /data/ should parse a valid input book and store it in the back-end container // PUT api/data/<bookData> public void Put(Dictionary<string,string> input) { try { string title = ""; string isbn = ""; string author = ""; string genre = ""; if (input.ContainsKey("title")) { title = !string.IsNullOrEmpty(input["title"]) ? input["title"] : "EMPTY TITLE"; } if (input.ContainsKey("isbn")) { isbn = !string.IsNullOrEmpty(input["isbn"]) ? input["isbn"] : "EMPTY ISBN"; } if (input.ContainsKey("author")) { author = !string.IsNullOrEmpty(input["author"]) ? input["author"] : "EMPTY Author"; } if (input.ContainsKey("genre")) { genre = !string.IsNullOrEmpty(input["genre"]) ? input["genre"] : "EMPTY Genre"; } Book book = new Book(title); book.isbn = isbn; book.author = author; book.genre = genre; //For now, we're just storing it on the first shelf of the 'dummy' book case. bookCase.shelves[0].books.Add(book); } catch (Exception ex) { Console.Write(ex.Message); //Parsing the book failed //log.error(ex); } } //SPEC: "POST: A POST call should update the back-end shelf and book with whatever information is provided" // POST api/data public void Post(Dictionary<string, string> input) { //Update the shelf title if the shelf ID is provided if (input.ContainsKey("id")) { var shelf = from s in bookCase.shelves where s.id == input["id"] select s; Shelf uShelf = (Shelf)shelf; uShelf.title = string.IsNullOrEmpty(input["title"]) ? input["title"] : uShelf.title; } //Update any books found by ISBN if (input.ContainsKey("books")) { List<Book> books = new List<Book>(); List<Book> booksToUpdate = parseBookList(input["books"]); foreach (Shelf shelf in bookCase.shelves) { foreach (Book book in shelf.books) { books.Add(book); } } } } private List<Book> parseBookList(string p) { List<Book> books = new List<Book>(); //TODO: parse JSON for each Book object provided in p return books; } //SPEC: "DELETE: A DELETE call to /data/<isbn> should remove the isbn in question from the back-end" // DELETE api/data/<isbn> public HttpResponseMessage Delete(string input) { HttpResponseMessage message = new HttpResponseMessage(); message.StatusCode = HttpStatusCode.NotAcceptable; //Validating for 13 and 10 digit ISBNs if (input.Length == 10 || input.Length == 13) { long isbn; if (long.TryParse(input, out isbn)) { //We have a 'valid' ISBN. There is most likely more logic needed to validate this //Delete this book //deletBook(input); message.StatusCode = HttpStatusCode.OK; } } return message; } } } <file_sep>/sample_web_api_controller/Full Sample/Morningstar_homework/Morningstar_homework/App_Start/WebApiConfig.cs using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace Morningstar_homework { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{input}", defaults: new { input = RouteParameter.Optional } ); //Return JSON by default while still allowing XML //http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); } } } <file_sep>/sample_web_api_controller/Full Sample/Morningstar_homework/Morningstar_homework/Models/Book.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Morningstar_homework.Models { public class Book { //Excluding validation, business logic, logging, etc public string title { get; set; } public string isbn { get; set; } public string author { get; set; } public string genre { get; set; } public Book(string Title) { title = Title; isbn = generateFakeISBN(); author = "<NAME>"; genre = getRandomGenre(); } private string getRandomGenre() { string[] genres = new string[11]; genres[0] = "Horror"; genres[1] = "Sci-Fi"; genres[2] = "Fantasy"; genres[3] = "Mystery"; genres[4] = "Technical"; genres[5] = "History"; genres[6] = "Reference"; genres[7] = "Adventure"; genres[8] = "Religous"; genres[9] = "Medical"; genres[10] = "Romance"; Random rand = new Random(); //If this .Sleep() isn'there, the Random does not work properly. //This is a quick fix that doesn't slow down this sample application, but would not be acceptable in //a production app. System.Threading.Thread.Sleep(100); return genres[rand.Next(0, 11)]; } private string generateFakeISBN() { //Returns a fake 13 digit ISBN number //http://en.wikipedia.org/wiki/International_Standard_Book_Number string isbn = ""; Random rand = new Random(); for (int i = 0; i < 10; i++) { isbn += rand.Next(0, 9).ToString(); } return isbn; } } }<file_sep>/sample_web_api_controller/Full Sample/Morningstar_homework/Morningstar_homework/Models/Shelf.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Morningstar_homework.Models { public class Shelf { //Excluding validation, business logic, logging, etc public string title { get; set; } public string id { get; set; } public List<Book> books { get; set; } public Shelf() { books = new List<Book>(); } } }
2356964d18588fae41a96a781c1720e7dc1317e2
[ "C#" ]
5
C#
themoffatt/sample
81e6b4f4f1101ae6d39d14cfbbf5c777d5ee6eac
ac6fd21a81d1722637e6fe48e11de59960d8eb22
refs/heads/master
<repo_name>DrunkSexTodo/Backend<file_sep>/README.md Backend ======= Used tools: Backend * Python3 * Flask * SQLite3 * SQLAlchemy ( in future ) Frontend * Leafletjs * Twitter Bootstrap * Disqus * <file_sep>/schema.sql drop table if exists alcousers; create table alcousers ( id integer primary key autoincrement, name text not null, latitude real not null, longitude real not null, alco text not null, description text ); <file_sep>/views.py #coding=utf8 # все импорты import sqlite3 import os from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash # создаём наше маленькое приложение :) app = Flask(__name__) app.config.from_object(__name__) @app.route('/') def show_tittle_page(): db = sqlite3.connect('123.db') cur = db.execute('select name, latitude, longitude, alco, description from alcousers') entries = cur.fetchall() return render_template('index.html', entries=entries) @app.route('/postme', methods=['POST']) def get_maps_marker(): name = request.form['name'] longitude = float(request.form['longitude']) latitude = float(request.form['latitude']) alco = request.form['alco'] description = request.form['description'] db = sqlite3.connect('123.db') db.execute (\ "insert into alcousers (name, latitude, longitude, alco, description) VALUES (?,?,?,?,?)",\ (name, latitude, longitude, alco, description)) db.commit() return redirect("http://drunkmaps.aydar.me", code=302) @app.route('/admin') def admin_show(): return render_template('admin.html') if __name__ == '__main__': app.debug = True app.run()
8b99906154cdd239051945553e80241cc8b578e8
[ "Markdown", "SQL", "Python" ]
3
Markdown
DrunkSexTodo/Backend
de60f48d93c9b24bb6145efbaee493df87109b3b
a09b6a65f35eae330ec3c3ff763d11e8cab5513f
refs/heads/master
<repo_name>ELAndrews/CSEU4_Intro_Python_GP<file_sep>/day2.py # Passing by value Vs passing by Ref # define a doubling function that passes args by value def mult2(x): return x * 2 # define a doubling function that passes args by reference def mult2_list(l): for i in range(len(l)): l[i] *= 2 # # try out the functions # a = 12 # new_number = mult2(a) # print(new_number) # lst = [2, 4, 6, 8] # mutable # mult2_list(lst) # for num in lst: # print(num) #=========================================================== # Return the "centered" average of an array of ints, which we'll say is the mean average of the values, # except ignoring the largest and smallest values in the array. # centered_average([1, 2, 3, 4, 100]) → 3 # centered_average([1, 1, 5, 5, 10, 8, 7]) → 5 (1 + 5 + 5 + 8 + 7) // 5 # centered_average([-10, -4, -2, -4, -2, 0]) → -3 # UNDERSTAND # how many integers to work with? (min 3 ints) # if there are more than 1 largest or smallest value what do we do? we remove only 1 # do we need to account for floating points in our answers? no we only want to use int answers // # PLAN & EXECUTE def centered_avg1(ints): pass def centered_avg2(ints): pass # tests numbers = [1, 41, 34, 29, 50, 50] import time start = time.time() for i in range(1000): centered_avg1(numbers) end = time.time() print(end - start) print("-----------------------") start = time.time() for i in range(1000): centered_avg2(numbers) end = time.time() print(end - start) # a = 41 + 34 + 29 + 50 # print(a) # b = a // 4 # print(b)
d69f5e98a3bd08ab0a4e2b99ab3fc16f110b794d
[ "Python" ]
1
Python
ELAndrews/CSEU4_Intro_Python_GP
5b3a1976f65446821138dafbf1eca00e155beada
3b34e75c611e81f005651b84ffc889eba42e4af5
refs/heads/master
<repo_name>HaDeLuxe/ShadowGame<file_sep>/ShadowGame/ShadowCastermine.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShadowGame { class ShadowCastermine { private struct DirectionVector { public int X { get; private set; } public int Y { get; private set; } public DirectionVector(int x, int y) : this() { this.X = x; this.Y = y; } } private struct ColumnPortion { public int X { get; private set; } public DirectionVector bottomVector { get; private set; } public DirectionVector topVector { get; private set; } public ColumnPortion(int x, DirectionVector bottom, DirectionVector top) : this() { this.X = x; this.bottomVector = bottom; this.topVector = top; } } public static void ComputeFieldOfViewWithShadowCasting(int x, int y, int radius, Func<int, int, bool> isOpaque, Action<int, int> setFoV) { Func<int, int, bool> opaque = TranslateOrigin(isOpaque, x, y); Action<int, int> fov = TranslateOrigin(setFoV, x, y); //for (int octant = 0; octant < 8; ++octant) //{ // ComputeFieldOfViewInOctantZero( // TranslateOctant(opaque, octant), // TranslateOctant(fov, octant), // radius); //} ComputeFieldOfViewInOctantZero( opaque,fov, radius); } private static Func<int, int, T> TranslateOrigin<T>(Func<int, int, T> f, int x, int y) { return (a, b) => f(a + x, b + y); } private static Action<int, int> TranslateOrigin(Action<int, int> f, int x, int y) { return (a, b) => f(a + x, b + y); } private static void ComputeFoVColumnPortion(int x, DirectionVector topVector, DirectionVector bottomVector, Func<int, int, bool> isOpaque, Action<int, int> setFieldOfView, int radius, Queue<ColumnPortion> queue) { int topY = x * topVector.X / topVector.Y; int bottomY = x * bottomVector.X / bottomVector.Y; int quotient = ((2 * x + 1) * topVector.Y) / (2 * topVector.X); int remainder = ((2 * x + 1) * topVector.Y) % (2 * topVector.X); bool? wasLastCellOpaque = null; for (int y = topY; y >= bottomY; --y) { bool inRadius = isInRadius(x, y, radius); if (inRadius) { //the current cell is in the view. setFieldOfView(x, y); } bool currentIsOpaque = !inRadius || isOpaque(x, y); if (wasLastCellOpaque != null) { if (currentIsOpaque) { if (!wasLastCellOpaque.Value) { queue.Enqueue(new ColumnPortion(x + 1, new DirectionVector(x * 2 - 1, y * 2 + 1), topVector)); } } else if (wasLastCellOpaque.Value) { topVector = new DirectionVector(x + 2 + 1, y * 2 + 1); } } wasLastCellOpaque = currentIsOpaque; } if (wasLastCellOpaque != null && !wasLastCellOpaque.Value) queue.Enqueue(new ColumnPortion(x + 1, bottomVector, topVector)); } private static bool isInRadius(int x, int y, int radius) { return (2 * x - 1) * (2 * x - 1) + (2 * y - 1) * (2 * y - 1) <= 4 * radius * radius; } private static void ComputeFieldOfViewInOctantZero(Func<int, int, bool> isOpaque, Action<int, int> setFieldOfView, int radius) { var queue = new Queue<ColumnPortion>(); queue.Enqueue(new ColumnPortion(0, new DirectionVector(1, 0), new DirectionVector(1, 1))); while (queue.Count() != 0) { var current = queue.Dequeue(); if (current.X >= radius) continue; ComputeFoVColumnPortion(current.X, current.topVector, current.bottomVector, isOpaque, setFieldOfView, radius, queue); } } private static Func<int, int, T> TranslateOctant<T>(Func<int, int, T> f, int octant) { switch (octant) { default: return f; case 1: return (x, y) => f(y, x); case 2: return (x, y) => f(-y, x); case 3: return (x, y) => f(-x, y); case 4: return (x, y) => f(-x, -y); case 5: return (x, y) => f(-y, -x); case 6: return (x, y) => f(y, -x); case 7: return (x, y) => f(x, -y); } } private static Action<int, int> TranslateOctant(Action<int, int> f, int octant) { switch (octant) { default: return f; case 1: return (x, y) => f(y, x); case 2: return (x, y) => f(-y, x); case 3: return (x, y) => f(-x, y); case 4: return (x, y) => f(-x, -y); case 5: return (x, y) => f(-y, -x); case 6: return (x, y) => f(y, -x); case 7: return (x, y) => f(x, -y); } } } } <file_sep>/ShadowGame/GameObject.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShadowGame { class GameObject { public GameObject(Vector2 gameObjectPosition, Vector2 gameObjectSize, float gameObjectRotation, SpriteEffects gameObjectSpriteEffect, Color gameObjectColor, Texture2D gameObjectTexture) { this.gameObjectPosition = gameObjectPosition; this.gameObjectSize = gameObjectSize; this.gameObjectRotation = gameObjectRotation; this.gameObjectSpriteEffect = gameObjectSpriteEffect; this.gameObjectColor = gameObjectColor; this.gameObjectTexture = gameObjectTexture; } public Vector2 gameObjectPosition = new Vector2(0,0); public Vector2 gameObjectSize { get; set; } = new Vector2(1, 1); private float gameObjectRotation { get; set; } = 0f; SpriteEffects gameObjectSpriteEffect { get; set; } = SpriteEffects.None; Color gameObjectColor { get; set; } = Color.White; Texture2D gameObjectTexture { get; set; } = null; public void draw(SpriteBatch spriteBatch) { spriteBatch.Draw(gameObjectTexture, gameObjectPosition, null, gameObjectColor, gameObjectRotation, Vector2.Zero, gameObjectSize, gameObjectSpriteEffect, 0); } } } <file_sep>/ShadowGame/Game1.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; namespace ShadowGame { /// <summary> /// This is the main type for your game. /// </summary> public class Game1 : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; GameObject tile = null; GameObject player = null; public static int count = 0; SpriteFont font; private Dictionary<string, Texture2D> texturesDictionary = null; private Color[] rectColor; private Color[,] TwoDColor; private bool[,] isLit; private int[,] map; private Texture2D background; private float alpha; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferHeight = 1080; graphics.PreferredBackBufferWidth = 1920; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here texturesDictionary = new Dictionary<string, Texture2D>(); isLit = new bool[graphics.PreferredBackBufferWidth/2, graphics.PreferredBackBufferHeight/2]; map = new int[graphics.PreferredBackBufferWidth/2, graphics.PreferredBackBufferHeight/2]; //rectColor = new Color[graphics.PreferredBackBufferHeight * graphics.PreferredBackBufferWidth]; rectColor = new Color[graphics.PreferredBackBufferWidth * graphics.PreferredBackBufferHeight]; TwoDColor = new Color[graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight]; background = new Texture2D(GraphicsDevice, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight); for (int i = 0; i < rectColor.Length; i++) { rectColor[i] = Color.LightSalmon; } background.SetData(rectColor); alpha = 1; base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); texturesDictionary.Add("GameObject", Content.Load<Texture2D>("Images\\SimpleTile_White")); font = Content.Load<SpriteFont>("fonts\\Arial"); player = new GameObject(new Vector2(200, 200), new Vector2(10, 10), 0f, SpriteEffects.None, Color.Black, texturesDictionary["GameObject"]); tile = new GameObject(new Vector2(500,500), new Vector2(30,30), 0f, SpriteEffects.None, Color.Red, texturesDictionary["GameObject"]); for (int i = 0; i < 1920/2; i++) { for (int j = 0; j < 1080/2; j++) { map[i, j] = 0; } } //map[500, 500] = 1; //map[500, 501] = 1; for (int i = 500/2; i < 530/2; i++) { for (int j = 500/2; j < 530/2; j++) { map[i, j] = 1; } } // TODO: use this.Content to load your game content here } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// game-specific content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); // TODO: Add your update logic here count = 0; if (Keyboard.GetState().IsKeyDown(Keys.W)) player.gameObjectPosition.Y -= 5; if (Keyboard.GetState().IsKeyDown(Keys.S)) player.gameObjectPosition.Y += 5; if (Keyboard.GetState().IsKeyDown(Keys.A)) player.gameObjectPosition.X -= 5; if (Keyboard.GetState().IsKeyDown(Keys.D)) player.gameObjectPosition.X += 5; for (int i = 0; i < rectColor.Length; i++) { rectColor[i] = Color.Black; } for (int j = (int)player.gameObjectPosition.X/2 - 150; j < player.gameObjectPosition.X/2 + 150; j++) for (int k = (int)player.gameObjectPosition.Y/2 - 150; k < player.gameObjectPosition.Y/2 + 150; k++) { if (j < 0) j = 0; if (j > graphics.PreferredBackBufferWidth/2) j = graphics.PreferredBackBufferWidth/2; if (k < 0) k = 0; if (k > graphics.PreferredBackBufferHeight/2) k = graphics.PreferredBackBufferHeight/2; isLit[j, k] = false; } ShadowCaster.ComputeFieldOfViewWithShadowCasting((int)player.gameObjectPosition.X/2, (int)player.gameObjectPosition.Y/2, 100, (x1, y1) => map[x1, y1] == 1, (x2, y2) => { isLit[x2, y2] = true; }); for (int j = (int)player.gameObjectPosition.X/2 - 100; j < player.gameObjectPosition.X/2 + 100; j++) for (int k = (int)player.gameObjectPosition.Y/2 - 100; k < player.gameObjectPosition.Y/2 + 100; k++) { if (isLit[j, k] == true) { TwoDColor[j*2, k*2] = Color.White; rectColor[j*2 + k * 1920 * 2] = TwoDColor[j, k]; } } background.SetData(rectColor); base.Update(gameTime); } float calculateDistance(int x, int y) { return (float)Math.Sqrt((float)Math.Pow((float)x - (float)player.gameObjectPosition.X, 2) + Math.Pow((float)y - (float)player.gameObjectPosition.Y, 2)); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.LightGray); // TODO: Add your drawing code here spriteBatch.Begin(); spriteBatch.Draw(background, new Vector2(0, 0), Color.White); tile.draw(spriteBatch); player.draw(spriteBatch); spriteBatch.DrawString(font, count.ToString(), new Vector2(0, 0), Color.White); spriteBatch.End(); base.Draw(gameTime); } private Color[,] TextureTo2DArray(Texture2D texture) { Color[] colors1D = new Color[texture.Width * texture.Height]; texture.GetData(colors1D); Color[,] colors2D = new Color[texture.Width, texture.Height]; for (int x = 0; x < texture.Height; x++) for (int y = 0; y < texture.Height; y++) colors2D[x, y] = colors1D[x + y * texture.Width]; return colors2D; } } }
87df672ce80dbcb984c4b9ea66d2a67c96b5e192
[ "C#" ]
3
C#
HaDeLuxe/ShadowGame
91a847e9d9de16eb7980fbf96af7a71243bb845b
e7fcd73056ea0896eaed7db045b8b523e2cac041
refs/heads/master
<file_sep>Quick testing environment settings for a brand new Rails project <EMAIL> <file_sep>FactoryGirl.define do factory :bank_account do end end <file_sep>class ExampleUser < ActiveRecord::Base end <file_sep>class BankAccount < ActiveRecord::Base def 存錢(n) update_attributes(amount: self.amount + n) if n.positive? end def 領錢(n) update_attributes(amount: self.amount - n) if n.positive? end def 餘額 amount end end <file_sep>require 'rails_helper' RSpec.describe BankAccount, type: :model do it "可以存錢" do account = BankAccount.create(name: "kk", amount: 100) account.存錢(100) account.存錢(10) expect(account.餘額).to be 210 end it "不可以存負的錢" do account = BankAccount.create(name: "kk", amount: 100) account.存錢(-10) expect(account.餘額).to be 100 end it "可以領錢" do account = BankAccount.create(name: "kk", amount: 100) account.領錢(10) account.領錢(30) expect(account.餘額).to be 60 end it "不可以領負的錢" do account = BankAccount.create(name: "kk", amount: 100) account.領錢(-10) expect(account.餘額).to be 100 end end
225015e8ac9d2d48cafd8ca5bab9a67fc2bd10b4
[ "RDoc", "Ruby" ]
5
RDoc
kaochenlong/second_bank
c17bad6305272928527821341af0340f85eece72
e18c3b84567e7f9ffbd5337ce5e6047abd1d1cec
refs/heads/master
<repo_name>joubertredrat/tumblr.sh<file_sep>/tumblr.sh #!/bin/bash # <NAME> # Data de desenvolvimento 09/08/2014 # Data de Modificação 05/12/2014 PAGINA=$1 NUMEROPAGINA=$2 CRIARPASTA=$3 IMGHD=$4 PASTADESTINO=$5 function INFOHELP() { echo " " echo " " echo "# IMG Tumblr v0.2" echo "# por <NAME>" echo " " echo "# Permissão de execução no arquivo" echo "# chmod +x tumblr.sh" echo " " echo "# ./tumblr.sh %1 %2 %3 %4 %5" echo "# | | | | |" echo "# | | | | Pasta de destino (. pasta local)" echo "# | | | true / false - [true] Imagens em 1280px - [false] Imagens em 500px" echo "# | | true / false - [true] Cria uma pasta a cada 30 páginas verificadas" echo "# | Quantidade de páginas (ex: 10) ou entre as páginas (ex: 5-10)" echo "# URL do tumblr sem http (dominio.com ou site.tumblr.com)" echo " " echo " " exit } if [ "$PAGINA" == "help" ] || [ "$PAGINA" == "--help" ] ; then INFOHELP else NPAGINA=$(echo $NUMEROPAGINA | grep "-") if [ -z "$NPAGINA" ] ; then INICIO=1 MAXIMO=$NUMEROPAGINA else PINICIO=$(echo $NUMEROPAGINA | cut -d "-" -f1) PMAXIMO=$(echo $NUMEROPAGINA | cut -d "-" -f2) INICIO=$PINICIO MAXIMO=$PMAXIMO fi if [ -z "$PASTADESTINO" ] ; then PASTADESTINO=. fi if [ -d "$PASTADESTINO" ] ; then PASTADESTINO=$PASTADESTINO else mkdir $PASTADESTINO PASTADESTINO=$PASTADESTINO fi for ((i=$INICIO; i<=MAXIMO; ++i )) ; do if [ "$CRIARPASTA" == "true" ] || [ "$CRIARPASTA" == "TRUE" ] ; then if [ "$i" == "1" ] ; then mkdir $PASTADESTINO/imagens-0$INICIO GUARDANUMERO=$i PASTA=$PASTADESTINO/imagens-0$INICIO fi ATUAL=$(($i%30)) if [ "$ATUAL" == "0" ] ; then GUARDANUMERO=$(($GUARDANUMERO+1)) GUARDANUMEROATUAL=$GUARDANUMERO if [ "$GUARDANUMERO" -lt "10" ] ; then GUARDANUMERO=0$GUARDANUMERO fi mkdir $PASTADESTINO/imagens-$GUARDANUMERO PASTA=$PASTADESTINO/imagens-$GUARDANUMERO GUARDANUMERO=$GUARDANUMEROATUAL fi elif [ "$CRIARPASTA" == "false" ] || [ "$CRIARPASTA" == "FALSE" ] ; then PASTA=$PASTADESTINO else INFOHELP fi URLTRATADA=${PAGINA%/} PAGINASCP=$(echo $PAGINA | sed 's%\.%\\.%g') PAGINAHTTP="http://$PAGINA" LISTAIMG=`wget -qO- $PAGINAHTTP/page/$i | sed -rn -e "/$PAGINASCP\/post/ s/.*(\"http:\/\/\$PAGINASCP\/post.*\").*/\1/p" | sed -rn -e 's/"([^"|^#]*)(["#].*)/\1/p' | sort | uniq` for POST in $LISTAIMG; do if [ "$IMGHD" == "true" ] ; then IMGURLLISTA=`wget -qO- $POST | sed -rn -e '/="http:\/\/.*media\.tumblr\.com\/.*\/tumblr_([^<]+)._1280.(jpg|jpeg|png)"/ s/.*("http:\/\/.*media\.tumblr\.com\/.*\/tumblr_([^<]+)._1280.(jpg|jpeg|png)").*/\1/p' | sed -rn -e 's/"([^"|^#]*)(["#].*)/\1/p' | sort | uniq` RESOLUCAO="1280px" else IMGURLLISTA=`wget -qO- $POST | sed -rn -e '/="http:\/\/.*media\.tumblr\.com\/.*\/tumblr_([^<]+)._500.(jpg|jpeg|png)"/ s/.*("http:\/\/.*media\.tumblr\.com\/.*\/tumblr_([^<]+)._500.(jpg|jpeg|png)").*/\1/p' | sed -rn -e 's/"([^"|^#]*)(["#].*)/\1/p' | sort | uniq` RESOLUCAO="500px" fi if [ -z "$IMGURLLISTA" ] ; then echo -e "Imagem não encontrada ou menor que $RESOLUCAO. \n" else echo -e "$IMGURLLISTA \n" wget -q $IMGURLLISTA -P $PASTA fi done done fi
dce6a3e6b102390c06a97dea6006cb8c1e7e57a2
[ "Shell" ]
1
Shell
joubertredrat/tumblr.sh
9ff6d21bf9fe26bde9ee97ace5b93ec0eba1f701
551151df719e094cb09097461ea2be71cf5f7f12
refs/heads/master
<repo_name>vasilevdm/parser<file_sep>/www.js let domain = 'https://inaka-fasad.ru'; let urls = [ '/product/cl3401/', '/product/cl3791/', '/product/cl3801/', '/product/cl3811/', '/product/cl3891/', '/product/cl3911/', '/product/cl3921/', '/product/cl3931/', '/product/cl4101/', '/product/cl4171/', '/product/cl4181/', '/product/cl4191/', '/product/cl4461/', '/product/cl4481/', '/product/cl4551/', '/product/cl4681/', '/product/cl5101/', '/product/cw1111/', '/product/cw1134/', '/product/cw1207/', '/product/cw1251/', '/product/cw1548/', '/product/cw1582/', '/product/cw1621/', '/product/cw1811/', '/product/cw1821/', '/product/cw1831/', '/product/cw1841/', '/product/cw1891/', '/product/cw1961/', '/product/cw2031/', '/product/cw2051/', '/product/cw2121/', '/product/cw2131/', '/product/cw2161/', '/product/cw2191/', '/product/cw2201/', '/product/cw2211/', '/product/cw2251/', '/product/nh3121/', '/product/nh3293/', '/product/nh3341/', '/product/nh3641/', '/product/nh3751/', '/product/nh3831/', '/product/nh3841/', '/product/nh3851/', '/product/nh3981/', '/product/nh4051/', '/product/nh4061/', '/product/nh4151/', '/product/nh4311/', '/product/nh4331/', '/product/nh4341/', '/product/nh4431/', '/product/nh4441/', '/product/nh4451/', '/product/nh4524/', '/product/nh4531/', '/product/nh4693/', '/product/nh4711/', '/product/nh4721/', '/product/nh4731/', '/product/nh4741/', '/product/nh4751/', '/product/nh5121/', '/product/nh5134/', '/product/nh5142/', '/product/nh5153/', '/product/nh5201/', '/product/nh5211/', '/product/nh5221/', '/product/nh5231/', '/product/nh5271/', '/product/nh5281/', '/product/nh5291/', '/product/nw3121/', '/product/nw3641/', '/product/nw3751/', '/product/nw3832/', '/product/nw3841/', '/product/nw3852/', '/product/nw4051/', '/product/nw4521/', '/product/nw4531/', '/product/nw4541/', '/product/nw4691/' ] const request = require("request-promise"), cheerio = require("cheerio"); fs = require('fs'); fs.writeFile("input.json", '[]'); var download = function(uri, filename, callback){ request.head(uri, function(err, res, body){ // console.log('content-type:', res.headers['content-type']); // console.log('content-length:', res.headers['content-length']); request(uri).pipe(fs.createWriteStream(filename)).on('close', callback); }); }; // let out = []; let obj; let i = 0; urls.forEach(function(url){ i++ setTimeout( function(i){ request(domain+url, function (error, response, body) { if (!error) { let $ = cheerio.load(body); // console.log('start'); // console.log($); // console.log(); // console.log('end'); let art = $(".fart").html() if (!fs.existsSync('download2/'+art+'/')){ fs.mkdirSync('download2/'+art+'/'); } let props = [] $(".good-prop__item").each(function(){ let label = $(this).find('.good-prop__label').text() let value = $(this).find('.good-prop__value').text() props.push({ label: label.trim(), value: value.replace('\n','').replace(/\t/g,' ').replace(/ /g,' ').replace(/ /g,' ').trim().replace(' мм','').replace(' кг','') }) }) let price = $('.good__price').text().replace('руб./м2','').replace(' ','').trim() let photos = [] $(".catalogTopSlider1 li").each(function(){ let download_image_url = domain+$(this).find('img').attr('src') let name = download_image_url.match(/\/([^\/]+)$/)[1] let local_image_url = 'download2/'+art+'/photo_'+name if(!fs.existsSync(local_image_url)) download(download_image_url, local_image_url, function(){ console.log('done ' + local_image_url); }) photos.push(local_image_url) }) let examples = [] $(".seeSlider li").each(function(){ let download_image_url = domain+$(this).find('a').attr('href') let name = download_image_url.match(/\/([^\/]+)$/)[1] let dir = download_image_url.match(/\/([^\/]+)\/[^\/]+$/)[1] let local_image_url = 'download2/examples/'+dir+'/'+name if (!fs.existsSync('download2/examples/')) fs.mkdirSync('download2/examples/') if (!fs.existsSync('download2/examples/'+dir+'/')) fs.mkdirSync('download2/examples/'+dir+'/') // console.log(download_image_url) // console.log(name) // console.log(dir) // return false if(!fs.existsSync(local_image_url)) download(download_image_url, local_image_url, function(){ console.log('done ' + local_image_url); }) examples.push(local_image_url) }) let obj = { art: art, props: props, price: price, photos: photos, examples: examples } /* if (!fs.existsSync('download2/'+art+'/')){ fs.mkdirSync('download2/'+art+'/'); } photos.forEach(function(el){ let download_image_url = domain+$(this).attr('href'); let download_thumb_url = domain+$(this).children().attr('src'); let name = download_image_url.match(/\/([^\/]+)$/)[1]; let local_image_url = 'download2/'+id+'/'+name; let local_thumb_url = 'download2/'+id+'/thumb_'+name; if(!fs.existsSync(local_image_url)) download(download_image_url, local_image_url, function(){ console.log('done'); }); if(!fs.existsSync(local_thumb_url)) download(download_thumb_url, local_thumb_url, function(){ console.log('done'); }); screenshot_movie.push(local_image_url); screenshot_movie_thumbs.push(local_thumb_url); }); let obj = { art: art, props: props, price: price, photos: photos, examples: examples } console.log(obj) let id = url.match(/^\/([^\-]+).+/)[1]; let title_movie = $(".title_movie").contents().filter(function() { return this.type === 'text'; }).text().trim(); let alt_name = $(".alt_name").html(); if (!fs.existsSync('download2/'+id+'/')){ fs.mkdirSync('download2/'+id+'/'); } let download_poster_movie = domain+$(".poster_movie img").attr('src'); let name = download_poster_movie.match(/\/([^\/]+)$/)[1]; let local_poster_movie = 'download2/'+id+'/poster_'+name; if(!fs.existsSync(local_poster_movie)) download(download_poster_movie, local_poster_movie, function(){ console.log('done'); }); let poster_movie = local_poster_movie; let file = ''; let file_match = $(".sub_right script:last-child").html(); if(file_match){ file_match = file_match.match(/file:"\/\/([^"]+)/); if(file_match) file = file_match[1] } let info_rating_movie = $(".info_rating_movie li").text().replace('Рейтинг: ',''); let info_movie_list = $(".info_movie .info_movie_list").text().trim().replace(/\t\t/g,'').replace(/\n\t\n\t/g,'\n\t'); let text_movie = $(".text_movie p").text().trim(); let screenshot_movie = []; let screenshot_movie_thumbs = []; $(".screenshot_movie a").each(function(){ let download_image_url = domain+$(this).attr('href'); let download_thumb_url = domain+$(this).children().attr('src'); let name = download_image_url.match(/\/([^\/]+)$/)[1]; let local_image_url = 'download2/'+id+'/'+name; let local_thumb_url = 'download2/'+id+'/thumb_'+name; if(!fs.existsSync(local_image_url)) download(download_image_url, local_image_url, function(){ console.log('done'); }); if(!fs.existsSync(local_thumb_url)) download(download_thumb_url, local_thumb_url, function(){ console.log('done'); }); screenshot_movie.push(local_image_url); screenshot_movie_thumbs.push(local_thumb_url); }); let movie_similar = []; $(".movie_similar a").each(function() { movie_similar.push($(this).attr('href')); }); let obj = { id: id, url: domain+url, title_movie: title_movie, alt_name: alt_name, poster_movie: poster_movie, file: file, info_rating_movie: info_rating_movie, info_movie_list: info_movie_list, text_movie: text_movie, screenshot_movie: screenshot_movie, screenshot_movie_thumbs: screenshot_movie_thumbs, movie_similar: movie_similar } */ // console.log('id >'+id+'<'); // console.log('title_movie >'+title_movie+'<'); // console.log('alt_name >'+alt_name+'<'); // console.log('poster_movie >'+poster_movie+'<'); // console.log('file >'+file+'<'); // console.log('info_rating_movie >'+info_rating_movie+'<'); // console.log('info_movie_list >'+info_movie_list+'<'); // console.log('text_movie >'+text_movie+'<'); // console.log(screenshot_movie); // console.log(screenshot_movie_thumbs); // console.log(movie_similar); // out.push(obj); // return obj; // console.log('start'); // console.log(data); // console.log(obj); // console.log('end'); let input; fs.readFile("input.json", 'utf8', function (err, data) { if (err) throw err; input = JSON.parse(data); input = input.concat(obj); fs.writeFile("input.json", JSON.stringify(input), function(err) { if(err) { return console.log(err); } console.log("The file was saved! input.json"); }); }); } else { console.log("Произошла ошибка: " + error); } }); }, 5000 * i); // console.log('asdas'); // return false; }); // console.log(out); console.log(obj);
9b071c53bc073d257eba0610ff749b2c09bb253a
[ "JavaScript" ]
1
JavaScript
vasilevdm/parser
b5288757a23568bf19a70cf94bbdd312fd5e0556
a99ccd880c9b2da2c0e92b30b318b4f8f71172f0
refs/heads/main
<repo_name>Online13/Online13.github.io<file_sep>/README.md # Online13.github.io ## About * Voici mon CV écrit en HTML, SASS, JS. * Les icons proviennent de [flaticon](https://www.flaticon.com/). * aperçu : [https://online13.github.io/](https://online13.github.io/) <file_sep>/assets/scripts/scrollBtn.js window.addEventListener('load', e => { const btn = document.querySelector('.btn-scroll'); const html = document.querySelector('html'); const step = html.getBoundingClientRect().height; btn.addEventListener('click', e => { let options = {}; options = { top: (btn.classList.contains('onbottom')) ? -step : step, left: 0, behavior: 'smooth' } btn.classList.toggle('onbottom'); html.scrollTo(options); }); });<file_sep>/assets/scripts/models.js // .................................................................. const about = { "github": "https://github.com/Online13", "adresse": "Lot B52 Cite <NAME>", "date de naissance": "13 juin 2001", "e-mail": "<EMAIL>", "numero": "034 13 133 73" }; const div_about = document.querySelector('.about'); for (let item in about) { div_about.innerHTML += `<li> <h4>${item.toUpperCase()}</h4> <small class="value">${about[item]}</small> </li>`; } // .................................................................. const langues = { "Français (niveau B2)": 80, "Anglais (niveau Terminal, ecrit)": 40 }; const div_langue = document.querySelector('.langue'); for (let description in langues) { div_langue.innerHTML += ` <div class="progress"> <small class="description"> ${description} </small> <div class="progress-bar"> <div data-value="${langues[description]}"></div> </div> </div>`; } // .................................................................. const hobbies = [ "dessiner", "jeu d'echec", "jeux video", "rubiks cube" ]; const div_hobby = document.querySelector('.ci'); hobbies.forEach(value => { div_hobby.innerHTML += `<li>${value}</li>` }); // .................................................................. const cursus = { "2018 – 2019": "Deuxième année en Mathématiques Informatique à l’Université d’Antananarivo", "2017 – 2018": "Première année en Mathématiques Informatique à l’Université d’Antananarivo", "mars 2018": "Obtention du Diplôme d’Étude en Langue Française (DELF) niveau B2", "2016 – 2017": "Obtention du Baccalauréat série C" }; const div_cursus = document.querySelector('.cursus'); for (let date in cursus) { div_cursus.innerHTML += `<li><small>${date}</small> <span>${cursus[date]}</span> </li>`; } // .................................................................. const form = { "Janvier 2020": "initiation au réseau a la MISA" }; const div_form = document.querySelector('.form'); for (let date in form) { div_form.innerHTML += ` <ul class="form"> <li><small>${date}</small> <span>${form[date]}</span></li> </ul>`; } // .................................................................. const comp = [ "Création de programmes en C/C++", "Création de sites statiques avec HTML5 et CSS3 (autoformation)", "Ajout d’interaction avec l’utilisateur sur un site en utilisant Javascript (autoformation)", "Versionner mes projets avec Git (autoformation)", "Création d’interface utilisateur (UI) avec la bibliothèque ReactJS (autoformation)" ]; const div_comp = document.querySelector('.comp'); comp.forEach(item => { div_comp.innerHTML += `<li>${item}</li>`; })
1540e32ea76be7cc29bcbe007c42518829b9ba33
[ "Markdown", "JavaScript" ]
3
Markdown
Online13/Online13.github.io
0e9048485cec6b6b1926c5a575f2dc1931520cc6
aca726bc8e296937f274566d2500395b7a564000
refs/heads/master
<file_sep>package com.example.michael.pong; /** * Created by Michael on 18/02/2017. */ import android.graphics.Bitmap; import android.graphics.Canvas; public class Background { private Bitmap image; private int x, y, dx; public Background(Bitmap res) { image = res; } public void update() { x+=dx; if(x<-GamePanel.WIDTH){ x=0; } } public void draw(Canvas canvas) { //System.out.print("hhhhhhhhhhhhhhhhh"); Bitmap scaled = Bitmap.createScaledBitmap(image, 900, 500, true); canvas.drawBitmap(scaled, x, y,null); if(x<0) { //Bitmap resized = Bitmap.createScaledBitmap(image,(int)(image.getWidth()), (int)(image.getHeight()), true); canvas.drawBitmap(image, x+GamePanel.WIDTH, y, null); } } public void setVector(int dx) { this.dx = dx; } } <file_sep>package com.example.michael.pong; /** * Created by Michael on 18/02/2017. */ import android.content.Context; import android.graphics.BitmapFactory; import android.graphics.Canvas; //import android.graphics.Matrix; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.lang.*; import java.lang.reflect.Array; import java.util.ArrayList; //import android.widget.ImageView; import static com.example.michael.pong.R.drawable.brick; //import com.example.michael.pong.Player.Player; public class GamePanel extends SurfaceView implements SurfaceHolder.Callback { public static final int WIDTH = 856; public static final int HEIGHT = 480; public static final int MOVESPEED = -5; private MainThread thread; private Background bg; private bastion player; private Player player1; private Player bullet; private int b; private int c; private boolean done = true; private ArrayList<Player> ArrayOfReapers = new ArrayList<Player>(); public static Canvas canvas; public GamePanel(Context context) { super(context); //add the callback to the surfaceholder to intercept events getHolder().addCallback(this); thread = new MainThread(getHolder(), this); //make gamePanel focusable so it can handle events setFocusable(true); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){} @Override public void surfaceDestroyed(SurfaceHolder holder){ boolean retry = true; while(retry) { try{thread.setRunning(false); thread.join(); }catch(InterruptedException e){e.printStackTrace();} retry = false; } } @Override public void surfaceCreated(SurfaceHolder holder){ bg = new Background(BitmapFactory.decodeResource(getResources(), R.drawable.grassbg1)); //int y = GamePanel.HEIGHT / 2; int y = 200; //players arguments are width of frame, height, number of frames, x and y coords //player = new Player(BitmapFactory.decodeResource(getResources(), R.drawable.helicopter), 145, 126, 4, 150, y); player = new bastion(BitmapFactory.decodeResource(getResources(), R.drawable.bastion), 111, 158, 3, 500, 200); int counter = 0; for(int i = 0; i < 12; i++) { if(i % 4 == 0) counter += 100; int x = -1300 + counter; counter+= 80; //player1 = new Player(BitmapFactory.decodeResource(getResources(), R.drawable.helicopter), 145, 126, 4, x, y); player1 = new Player(BitmapFactory.decodeResource(getResources(), R.drawable.helicopter), 72, 63, 4, x, y); ArrayOfReapers.add(player1); } System.out.println("Amount of reapers: " + ArrayOfReapers.size()); //we can safely start the game loop thread.setRunning(true); thread.start(); } @Override public boolean onTouchEvent(MotionEvent event) { if(event.getAction()==MotionEvent.ACTION_DOWN){ if(!player.getPlaying()) { player.setPlaying(true); } else { player.setUp(true); for(int i =0; i < ArrayOfReapers.size(); i ++) { ArrayOfReapers.get(i).setUp(true); //player1.setUp(true); } } return true; } if(event.getAction()==MotionEvent.ACTION_UP) { player.setUp(false); for(int i =0; i < ArrayOfReapers.size(); i ++) { ArrayOfReapers.get(i).setUp(false); //player1.setUp(false); } return true; } return super.onTouchEvent(event); } public void update() { if(player.getPlaying()) { bg.update(); player.update(); //player1.update(); for(int i =0; i < ArrayOfReapers.size(); i ++) { ArrayOfReapers.get(i).update(); } } boolean inside = false; inside = contains(); if (inside == true)//reaper is insides bastions radius { int health; health = player1.minusHealth(); if (health >= 1) { //System.out.println("Health has been taken off"); //updateBastion(); } else { //System.out.println("reaper is dead!"); } } } public boolean contains() { boolean contains = (Math.pow((player1.getX() - player.getX()), 2)) + (Math.pow((player1.getY() - player.getY()), 2)) < (Math.pow((player.getRadius()), 2)); if (contains == true) { //System.out.println("Inside"); int BastionX = player.getX(); int BastionY = player.getY(); bullet = new Player(BitmapFactory.decodeResource(getResources(), R.drawable.helicopter), 72, 63, 4, BastionX, BastionY); if (done != true) { bullet.draw(canvas); } bullet.update(); done = true; double sx = BastionX; double sy = BastionY; double deltaX = player.getX() - sx;//800 - sx; double deltaY = player.getY() - sy;//L - sy; double angle = Math.atan2(deltaY, deltaX); int speed = 4; b += speed * Math.cos(angle); c += speed * Math.sin(angle); bullet.setX(b); bullet.setY(c); } return contains; } @Override public void draw(Canvas canvas) { final float scaleFactorX = getWidth()/(WIDTH*1.f); final float scaleFactorY = getHeight()/(HEIGHT*1.f); if(canvas!=null) { final int savedState = canvas.save(); canvas.scale(scaleFactorX, scaleFactorY); bg.draw(canvas); for(int i =0; i < ArrayOfReapers.size(); i ++) { //player1.draw(canvas); ArrayOfReapers.get(i).draw(canvas); } canvas.rotate(90, player.getX() + (115 / 2), player.getY() + (160 / 2)); player.draw(canvas); //canvas.drawBitmap((BitmapFactory.decodeResource(getResources(), R.drawable.bastion)), 100, 50, null); canvas.restoreToCount(savedState); } } }
7fb102c8ee228915144c2f925db153632e7f2137
[ "Java" ]
2
Java
SuperAwesomeAppz/WatchTower
8ae3b966c2e66b17b19cd18dfcb05a21a4e10e6a
addc226354e553f4199f5c0bb32e511654a82609
refs/heads/master
<repo_name>joelangston/js_sports_game<file_sep>/assets/javascript/game.js const resetButton = document.querySelector ( '#reset-button'); const teamoneShootButton = document.querySelector('#teamone-shoot-button'); const teamTwoShotButton = document.querySelector('#teamtwo-shoot-button'); let shotTwo = document.querySelector('#teamtwo-numshots'); let counterTwo = document.querySelector('#teamtwo-numgoals'); let shotOne = document.querySelector('#teamone-numshots'); let counterOne = document.querySelector('#teamone-numgoals'); let resetCount = document.querySelector('#num-resets'); var reset =new Audio(); reset.src = "https://www.myinstants.com/media/sounds/avengers_.mp3" var cheer = new Audio() cheer.src = "https://www.myinstants.com/media/sounds/crowd-cheer.mp3" let playerOneShotCount = 0 let playerOneGoalCount = 0 let playerTwoShotCount = 0 let playerTwoGoalCount = 0 resetButton.addEventListener ('click', function(){ console.log ('Score Reset, Play Again!'); shotOne.innerHTML = 0; counterOne.innerHTML = 0; shotTwo.innerHTML = 0; counterTwo.innerHTML = 0; let newCounterValue = Number (resetCount.innerHTML) + 1 resetCount.innerHTML = newCounterValue reset.play() }) teamoneShootButton.addEventListener ('click', function(){ console.log ('Team One Shoots') playerOneShotCount += 1 playerOneGoalCount += Math.floor(Math.random() + 0.5) shotOne.innerHTML = playerOneShotCount counterOne.innerHTML = playerOneGoalCount if (playerOneGoalCount === 10){ alert('Team One Wins!!!!!!') cheer.play() } }) teamTwoShotButton.addEventListener ('click', function(){ console.log ('Team Two Shoots') playerTwoShotCount += 1 playerTwoGoalCount += Math.floor(Math.random() + 0.5) shotTwo.innerHTML = playerTwoShotCount counterTwo.innerHTML = playerTwoGoalCount if (playerTwoGoalCount === 10){ alert('Team Two Wins!!!!') cheer.play() } })
76d85cc80eeeeba50786a258ae5231347743dc1a
[ "JavaScript" ]
1
JavaScript
joelangston/js_sports_game
d52babc1b465b595443a4f7a3c793761ceaba6e2
47058e5b9a825e0d9ab3722672fd2c7fa6dc8687
refs/heads/develop
<repo_name>moltenzephyr/ECE444Lab1<file_sep>/helloworld.py print("Hello World Name: <NAME> Number of Years I have been at UofT: 4 \nCollaborator name: <NAME>") <file_sep>/README.md <NAME> c3 --- "this is c3" c4 --- "this is c4" c1 --- "this is c1" c2 --- "this is c2"
5715121a4faea5f99d316652c3aedd4ddebb2283
[ "Markdown", "Python" ]
2
Python
moltenzephyr/ECE444Lab1
33112444ef062b8c98460df9f7814418cd834782
d8a51fdddf18935cbe79d991d074638f8d118254
refs/heads/master
<repo_name>shuxianghuafu/ribll<file_sep>/ribllvmedaq/TModV785.cpp //////////////////////////////////////////// // TModV785.cpp: Implementation of CAEN // module V785AC // All module class must be inherited form // 'TBoard' // <NAME> 07/2012 //////////////////////////////////////////// #include <iostream> using namespace std; #include "TModV785.h" #include "TH1.h" #include "TH1I.h" #include "TString.h" #include "Rtypes.h" #include "caenacq.h" unsigned int TModV785::facqreg[2] = {0x100E, 0x0001}; unsigned int TModV785::fMaxDataVal = 4096; static const short DataHeaderRsh= 24; //Left shift of a int data to check if this is the Data Header static const short DataHeaderLsh= 5; static const short DataHeaderMask= 0x2; static const short DataMarkMask= 0x0; static const short DataEnderMask= 0x4; static const short DataNotValidMask= 0x6; static const short GeoRsh= 27; static const short CrateRsh= 16; static const short CrateLsh= 8; static const short CNTRsh= 8; static const short CNTLsh= 18; static const short ChNumbRsh= 16; static const short ChNumbLsh= 11; static const int UnderThrMask= 0x2000; static const int OverflewMask= 0x1000; static const short DataValueLsh= 20; static const short DataValueRsh= 20; static const int EventCountMask= 0xFFFFFF; static const short GeoAddrOffset= 0x1002; static const short CrateAddrOffset= 0x103C; static const short BitSet1Register= 0x1006; static const short BitClear1Register= 0x1008; static const short CrateNumMask= 0xFF; static const short GeoMask= 0x1F; static const short MaxGeo= 31; static const short MaxCrateNum= 255; static const short AMNESIA_Mask= 0x10; static const short StaReg1AddrOffset= 0x100E; ClassImp(TModV785) void TModV785::Initialization() { his1d = new TH1*[fMaxChannel]; for(unsigned int i=0; i<fMaxChannel; i++) his1d[i] = 0; //chdata = new unsigned short[fMaxChannel]; } //DataReset of V785, do this after the writting of Geo to the module int TModV785::DataReset() { int set = SingleWriteCycle(0x4, 0x4, 0x1032, 16); int clear = SingleWriteCycle(0x4, 0x0, 0x1034, 16); return (set+clear); } //SOFTW. RESET(SR) of this module, SR this module after write GEO int TModV785::SoftReset() { int set = SingleWriteCycle(0x80, 0x00, BitSet1Register, 16); int clear = SingleWriteCycle(0x80, 0x00, BitClear1Register, 16); return (set+clear); } int TModV785::Decode(unsigned int *&data_point) { //CleanChData(); unsigned int tdata = (*data_point); unsigned int ChannelNums = 0; unsigned int ecounter = 0; unsigned int nCh = 0; unsigned int dataMarker = (tdata<<DataHeaderLsh)>>(DataHeaderRsh+DataHeaderLsh); if(dataMarker == DataNotValidMask){return -1;} //for not valid data if(dataMarker == DataHeaderMask) { unsigned int mGeo = (tdata>>GeoRsh); unsigned int mCrate = ( (tdata<<CrateLsh)>>(CrateRsh+CrateLsh) ); if( (mGeo != fGeo) || (mCrate != fCrateNum)) { cout << GetName() << " Data header error. Module Geo " << fGeo << " or Crate number " << fCrateNum <<" do not match." << endl; return 0; } ChannelNums = (tdata<<CNTLsh)>>(CNTRsh+CNTLsh); while( (dataMarker != DataEnderMask) && (nCh<=ChannelNums) ) //loop to the end of the data belongs to this module { //cout << "data val: " << ChannelNums << endl; data_point++; tdata = (*data_point); dataMarker = (tdata<<DataHeaderLsh)>>(DataHeaderRsh+DataHeaderLsh); if(dataMarker == DataEnderMask) { ecounter = tdata&EventCountMask; } if(dataMarker == DataMarkMask) { unsigned int channel = (tdata<<ChNumbLsh)>>(ChNumbRsh+ChNumbLsh); if(channel>=fMaxChannel) { cout << GetName() << " Data error. Channel number > fMaxChannel."<< endl; return 0; } bool dunvalid = (tdata & UnderThrMask)||(tdata & OverflewMask); if(!dunvalid) { unsigned int chd = (tdata<<DataValueLsh)>>DataValueRsh; if(chd<=fMaxDataVal) { chdata[channel] = (unsigned short)chd; if(his1d[channel]) his1d[channel]->Fill(chdata[channel]); } } nCh++; } } } //if( dataMarker == DataEnderMask ) data_point++; //to the next data header return ecounter; } void TModV785::Create1DHistos() { TString hnamet = 'h'; int hisname1 = (fCrateNum*100000 + fGeo*1000); int hisname2 = 0; TString htitle = 'T'; int histitle1 = (fCrateNum*100000 + fGeo*1000); int histitle2 = 0; TString hname, title; for(unsigned int i=0; i<fMaxChannel; i++) { hname = hnamet; hisname2 = hisname1 + i; hname += hisname2; title = htitle; histitle2 = histitle1 + i; title += histitle2; his1d[i] = new TH1I(hname.Data(), title.Data(), fMaxDataVal, 0, fMaxDataVal); } } TModV785::~TModV785() { //SafeDeleteArr(chdata); } int TModV785::WriteCrateNumtoBoard(unsigned int cnum) { if(cnum>MaxCrateNum) { cout << " Crate Number" << cnum << " > " << MaxCrateNum << endl; return 0; } unsigned int cratenum = cnum; unsigned int cratemask = CrateNumMask; // cratenum & cratemask == cratenum int status = SingleWriteCycle(cratenum, cratemask, CrateAddrOffset, 16); return status; } int TModV785::WriteGeoToBoard(unsigned int geo) { unsigned int status_reg1 = 0; int status = SingleReadCycle(status_reg1, StaReg1AddrOffset, 16); if(!status) { cout << "Read Status Register 1 of module: " << geo << " error." << endl; return 0; } if( (status_reg1 & AMNESIA_Mask) > 0 ) { unsigned int wgeo = geo; unsigned int geomask = GeoMask; if(wgeo>MaxGeo) { cout << " Geo " << wgeo << " > " << MaxGeo << endl; return 0; } int wstatus = SingleWriteCycle(wgeo, geomask, GeoAddrOffset, 16); DataReset(); SoftReset(); return wstatus; } else { return 1; } } unsigned int TModV785::GetChannelData(int chnum) { if(chnum>=0 && chnum<fMaxChannel) return chdata[chnum]; return 0; }<file_sep>/ribllvmedaq/TBoard.cpp /////////////////////////////////////////////////////// // VME models class interface // This class define the interface for the // boards implemented in the DAQ. // All true type models must be derived form the // base class, and all the member functions of a // true model must be declared as a pure virtual // function in this base class. // Version 0.01 // Hanjianlong 07/2012 /////////////////////////////////////////////////////// #include <stdio.h> #include <string> #include "TBoard.h" #include "caenacq.h" #include "CAENVMEtypes.h" #include "CAENVMElib.h" #include "Rtypes.h" ClassImp(TBoard) void TBoard::SetName(const char *name) { strncpy(fname, name, sizeof(fname)); } //Use for A32 address mode and D16 data width only int TBoard::SingleWriteCycle(UInt_t data, UInt_t mask, UInt_t addroffset, int datasize) { CVErrorCodes status; bool RWok = true; int rdata=0, loop=20; CVDataWidth data_size = cvD16; if(datasize == 32) data_size = cvD32; long BHandle = GetHandle(); // TBoardError err; unsigned int addr = fBaseAddr | addroffset; int wdata = data & 0x0000ffff; status = CAENVME_WriteCycle(BHandle, addr, &wdata, cvA32_U_DATA, data_size); if(mask != 0x0000) { RWok = false; while(loop--) { status = CAENVME_ReadCycle(BHandle, addr, &rdata, cvA32_U_DATA, data_size); if((rdata & mask) == data) { RWok = true; break; } else { status = CAENVME_WriteCycle(BHandle, addr, &wdata, cvA32_U_DATA, data_size); } } if(RWok==false) { printf("INIT>> Warning: Failed in writing 0x%04x to register 0x%08x\n", wdata, addr); printf("INIT>> Handle=%d ADDR = 0x%08x DATUM_READ = 0x%08x\n\n",BHandle, addr, rdata); } } if(RWok) { return 1; } else { return 0; } } int TBoard::SoftReset(unsigned int data, unsigned int addroffset, int datasize) { int status = SingleWriteCycle(data, 0, addroffset, datasize); return status; } int TBoard::SingleReadCycle(unsigned int& rdata, unsigned int addroffset, int datasize) { CVErrorCodes status; CVDataWidth data_size = cvD16; if(datasize == 32) data_size = cvD32; long BHandle = GetHandle(); if(BHandle<0) return 0; // TBoardError err; unsigned int addr = fBaseAddr | addroffset; status = CAENVME_ReadCycle(BHandle, addr, &rdata, cvA32_U_DATA, data_size); if(status == 0) { return 1; } else { return 0; } }<file_sep>/ribllvmedaq/classDict.cpp // Do NOT change. Changes will be lost next time file is generated #define R__DICTIONARY_FILENAME classDict /*******************************************************************/ #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <assert.h> #define G__DICTIONARY #include "RConfig.h" #include "TClass.h" #include "TDictAttributeMap.h" #include "TInterpreter.h" #include "TROOT.h" #include "TBuffer.h" #include "TMemberInspector.h" #include "TInterpreter.h" #include "TVirtualMutex.h" #include "TError.h" #ifndef G__ROOT #define G__ROOT #endif #include "RtypesImp.h" #include "TIsAProxy.h" #include "TFileMergeInfo.h" #include <algorithm> #include "TCollectionProxyInfo.h" /*******************************************************************/ #include "TDataMember.h" // Since CINT ignores the std namespace, we need to do so in this file. namespace std {} using namespace std; // Header files passed as explicit arguments #include "TBoard.h" #include "TControl.h" #include "TModV785.h" #include "TModV785N.h" #include "TModV775.h" #include "TModV775N.h" #include "TModV830AC.h" #include "TModV792.h" #include "TEvtBuilder.h" #include "TClientEvtBuilder.h" #include "TControlFrame.h" #include "TDataFileBuilder.h" #include "TMasterTask.h" // Header files passed via #pragma extra_include namespace ROOT { static void delete_TBoard(void *p); static void deleteArray_TBoard(void *p); static void destruct_TBoard(void *p); static void streamer_TBoard(TBuffer &buf, void *obj); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const ::TBoard*) { ::TBoard *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TInstrumentedIsAProxy< ::TBoard >(0); static ::ROOT::TGenericClassInfo instance("TBoard", ::TBoard::Class_Version(), "TBoard.h", 21, typeid(::TBoard), ::ROOT::Internal::DefineBehavior(ptr, ptr), &::TBoard::Dictionary, isa_proxy, 16, sizeof(::TBoard) ); instance.SetDelete(&delete_TBoard); instance.SetDeleteArray(&deleteArray_TBoard); instance.SetDestructor(&destruct_TBoard); instance.SetStreamerFunc(&streamer_TBoard); return &instance; } TGenericClassInfo *GenerateInitInstance(const ::TBoard*) { return GenerateInitInstanceLocal((::TBoard*)0); } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::TBoard*)0x0); R__UseDummy(_R__UNIQUE_(Init)); } // end of namespace ROOT namespace ROOT { static void delete_TControl(void *p); static void deleteArray_TControl(void *p); static void destruct_TControl(void *p); static void streamer_TControl(TBuffer &buf, void *obj); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const ::TControl*) { ::TControl *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TInstrumentedIsAProxy< ::TControl >(0); static ::ROOT::TGenericClassInfo instance("TControl", ::TControl::Class_Version(), "TControl.h", 46, typeid(::TControl), ::ROOT::Internal::DefineBehavior(ptr, ptr), &::TControl::Dictionary, isa_proxy, 16, sizeof(::TControl) ); instance.SetDelete(&delete_TControl); instance.SetDeleteArray(&deleteArray_TControl); instance.SetDestructor(&destruct_TControl); instance.SetStreamerFunc(&streamer_TControl); return &instance; } TGenericClassInfo *GenerateInitInstance(const ::TControl*) { return GenerateInitInstanceLocal((::TControl*)0); } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::TControl*)0x0); R__UseDummy(_R__UNIQUE_(Init)); } // end of namespace ROOT namespace ROOT { static void *new_TModV785(void *p = 0); static void *newArray_TModV785(Long_t size, void *p); static void delete_TModV785(void *p); static void deleteArray_TModV785(void *p); static void destruct_TModV785(void *p); static void streamer_TModV785(TBuffer &buf, void *obj); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const ::TModV785*) { ::TModV785 *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TInstrumentedIsAProxy< ::TModV785 >(0); static ::ROOT::TGenericClassInfo instance("TModV785", ::TModV785::Class_Version(), "TModV785.h", 17, typeid(::TModV785), ::ROOT::Internal::DefineBehavior(ptr, ptr), &::TModV785::Dictionary, isa_proxy, 16, sizeof(::TModV785) ); instance.SetNew(&new_TModV785); instance.SetNewArray(&newArray_TModV785); instance.SetDelete(&delete_TModV785); instance.SetDeleteArray(&deleteArray_TModV785); instance.SetDestructor(&destruct_TModV785); instance.SetStreamerFunc(&streamer_TModV785); return &instance; } TGenericClassInfo *GenerateInitInstance(const ::TModV785*) { return GenerateInitInstanceLocal((::TModV785*)0); } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::TModV785*)0x0); R__UseDummy(_R__UNIQUE_(Init)); } // end of namespace ROOT namespace ROOT { static void *new_TModV785N(void *p = 0); static void *newArray_TModV785N(Long_t size, void *p); static void delete_TModV785N(void *p); static void deleteArray_TModV785N(void *p); static void destruct_TModV785N(void *p); static void streamer_TModV785N(TBuffer &buf, void *obj); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const ::TModV785N*) { ::TModV785N *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TInstrumentedIsAProxy< ::TModV785N >(0); static ::ROOT::TGenericClassInfo instance("TModV785N", ::TModV785N::Class_Version(), "TModV785N.h", 17, typeid(::TModV785N), ::ROOT::Internal::DefineBehavior(ptr, ptr), &::TModV785N::Dictionary, isa_proxy, 16, sizeof(::TModV785N) ); instance.SetNew(&new_TModV785N); instance.SetNewArray(&newArray_TModV785N); instance.SetDelete(&delete_TModV785N); instance.SetDeleteArray(&deleteArray_TModV785N); instance.SetDestructor(&destruct_TModV785N); instance.SetStreamerFunc(&streamer_TModV785N); return &instance; } TGenericClassInfo *GenerateInitInstance(const ::TModV785N*) { return GenerateInitInstanceLocal((::TModV785N*)0); } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::TModV785N*)0x0); R__UseDummy(_R__UNIQUE_(Init)); } // end of namespace ROOT namespace ROOT { static void *new_TModV775(void *p = 0); static void *newArray_TModV775(Long_t size, void *p); static void delete_TModV775(void *p); static void deleteArray_TModV775(void *p); static void destruct_TModV775(void *p); static void streamer_TModV775(TBuffer &buf, void *obj); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const ::TModV775*) { ::TModV775 *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TInstrumentedIsAProxy< ::TModV775 >(0); static ::ROOT::TGenericClassInfo instance("TModV775", ::TModV775::Class_Version(), "TModV775.h", 17, typeid(::TModV775), ::ROOT::Internal::DefineBehavior(ptr, ptr), &::TModV775::Dictionary, isa_proxy, 16, sizeof(::TModV775) ); instance.SetNew(&new_TModV775); instance.SetNewArray(&newArray_TModV775); instance.SetDelete(&delete_TModV775); instance.SetDeleteArray(&deleteArray_TModV775); instance.SetDestructor(&destruct_TModV775); instance.SetStreamerFunc(&streamer_TModV775); return &instance; } TGenericClassInfo *GenerateInitInstance(const ::TModV775*) { return GenerateInitInstanceLocal((::TModV775*)0); } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::TModV775*)0x0); R__UseDummy(_R__UNIQUE_(Init)); } // end of namespace ROOT namespace ROOT { static void *new_TModV775N(void *p = 0); static void *newArray_TModV775N(Long_t size, void *p); static void delete_TModV775N(void *p); static void deleteArray_TModV775N(void *p); static void destruct_TModV775N(void *p); static void streamer_TModV775N(TBuffer &buf, void *obj); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const ::TModV775N*) { ::TModV775N *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TInstrumentedIsAProxy< ::TModV775N >(0); static ::ROOT::TGenericClassInfo instance("TModV775N", ::TModV775N::Class_Version(), "TModV775N.h", 17, typeid(::TModV775N), ::ROOT::Internal::DefineBehavior(ptr, ptr), &::TModV775N::Dictionary, isa_proxy, 16, sizeof(::TModV775N) ); instance.SetNew(&new_TModV775N); instance.SetNewArray(&newArray_TModV775N); instance.SetDelete(&delete_TModV775N); instance.SetDeleteArray(&deleteArray_TModV775N); instance.SetDestructor(&destruct_TModV775N); instance.SetStreamerFunc(&streamer_TModV775N); return &instance; } TGenericClassInfo *GenerateInitInstance(const ::TModV775N*) { return GenerateInitInstanceLocal((::TModV775N*)0); } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::TModV775N*)0x0); R__UseDummy(_R__UNIQUE_(Init)); } // end of namespace ROOT namespace ROOT { static void *new_TModV830AC(void *p = 0); static void *newArray_TModV830AC(Long_t size, void *p); static void delete_TModV830AC(void *p); static void deleteArray_TModV830AC(void *p); static void destruct_TModV830AC(void *p); static void streamer_TModV830AC(TBuffer &buf, void *obj); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const ::TModV830AC*) { ::TModV830AC *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TInstrumentedIsAProxy< ::TModV830AC >(0); static ::ROOT::TGenericClassInfo instance("TModV830AC", ::TModV830AC::Class_Version(), "TModV830AC.h", 17, typeid(::TModV830AC), ::ROOT::Internal::DefineBehavior(ptr, ptr), &::TModV830AC::Dictionary, isa_proxy, 16, sizeof(::TModV830AC) ); instance.SetNew(&new_TModV830AC); instance.SetNewArray(&newArray_TModV830AC); instance.SetDelete(&delete_TModV830AC); instance.SetDeleteArray(&deleteArray_TModV830AC); instance.SetDestructor(&destruct_TModV830AC); instance.SetStreamerFunc(&streamer_TModV830AC); return &instance; } TGenericClassInfo *GenerateInitInstance(const ::TModV830AC*) { return GenerateInitInstanceLocal((::TModV830AC*)0); } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::TModV830AC*)0x0); R__UseDummy(_R__UNIQUE_(Init)); } // end of namespace ROOT namespace ROOT { static void *new_TModV792(void *p = 0); static void *newArray_TModV792(Long_t size, void *p); static void delete_TModV792(void *p); static void deleteArray_TModV792(void *p); static void destruct_TModV792(void *p); static void streamer_TModV792(TBuffer &buf, void *obj); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const ::TModV792*) { ::TModV792 *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TInstrumentedIsAProxy< ::TModV792 >(0); static ::ROOT::TGenericClassInfo instance("TModV792", ::TModV792::Class_Version(), "TModV792.h", 17, typeid(::TModV792), ::ROOT::Internal::DefineBehavior(ptr, ptr), &::TModV792::Dictionary, isa_proxy, 16, sizeof(::TModV792) ); instance.SetNew(&new_TModV792); instance.SetNewArray(&newArray_TModV792); instance.SetDelete(&delete_TModV792); instance.SetDeleteArray(&deleteArray_TModV792); instance.SetDestructor(&destruct_TModV792); instance.SetStreamerFunc(&streamer_TModV792); return &instance; } TGenericClassInfo *GenerateInitInstance(const ::TModV792*) { return GenerateInitInstanceLocal((::TModV792*)0); } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::TModV792*)0x0); R__UseDummy(_R__UNIQUE_(Init)); } // end of namespace ROOT namespace ROOT { static TClass *TEvtBuilder_Dictionary(); static void TEvtBuilder_TClassManip(TClass*); static void delete_TEvtBuilder(void *p); static void deleteArray_TEvtBuilder(void *p); static void destruct_TEvtBuilder(void *p); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const ::TEvtBuilder*) { ::TEvtBuilder *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TIsAProxy(typeid(::TEvtBuilder)); static ::ROOT::TGenericClassInfo instance("TEvtBuilder", "TEvtBuilder.h", 22, typeid(::TEvtBuilder), ::ROOT::Internal::DefineBehavior(ptr, ptr), &TEvtBuilder_Dictionary, isa_proxy, 0, sizeof(::TEvtBuilder) ); instance.SetDelete(&delete_TEvtBuilder); instance.SetDeleteArray(&deleteArray_TEvtBuilder); instance.SetDestructor(&destruct_TEvtBuilder); return &instance; } TGenericClassInfo *GenerateInitInstance(const ::TEvtBuilder*) { return GenerateInitInstanceLocal((::TEvtBuilder*)0); } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::TEvtBuilder*)0x0); R__UseDummy(_R__UNIQUE_(Init)); // Dictionary for non-ClassDef classes static TClass *TEvtBuilder_Dictionary() { TClass* theClass =::ROOT::GenerateInitInstanceLocal((const ::TEvtBuilder*)0x0)->GetClass(); TEvtBuilder_TClassManip(theClass); return theClass; } static void TEvtBuilder_TClassManip(TClass* ){ } } // end of namespace ROOT namespace ROOT { static TClass *TClientEvtBuilder_Dictionary(); static void TClientEvtBuilder_TClassManip(TClass*); static void delete_TClientEvtBuilder(void *p); static void deleteArray_TClientEvtBuilder(void *p); static void destruct_TClientEvtBuilder(void *p); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const ::TClientEvtBuilder*) { ::TClientEvtBuilder *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TIsAProxy(typeid(::TClientEvtBuilder)); static ::ROOT::TGenericClassInfo instance("TClientEvtBuilder", "TClientEvtBuilder.h", 21, typeid(::TClientEvtBuilder), ::ROOT::Internal::DefineBehavior(ptr, ptr), &TClientEvtBuilder_Dictionary, isa_proxy, 0, sizeof(::TClientEvtBuilder) ); instance.SetDelete(&delete_TClientEvtBuilder); instance.SetDeleteArray(&deleteArray_TClientEvtBuilder); instance.SetDestructor(&destruct_TClientEvtBuilder); return &instance; } TGenericClassInfo *GenerateInitInstance(const ::TClientEvtBuilder*) { return GenerateInitInstanceLocal((::TClientEvtBuilder*)0); } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::TClientEvtBuilder*)0x0); R__UseDummy(_R__UNIQUE_(Init)); // Dictionary for non-ClassDef classes static TClass *TClientEvtBuilder_Dictionary() { TClass* theClass =::ROOT::GenerateInitInstanceLocal((const ::TClientEvtBuilder*)0x0)->GetClass(); TClientEvtBuilder_TClassManip(theClass); return theClass; } static void TClientEvtBuilder_TClassManip(TClass* ){ } } // end of namespace ROOT namespace ROOT { static void delete_TControlFrame(void *p); static void deleteArray_TControlFrame(void *p); static void destruct_TControlFrame(void *p); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const ::TControlFrame*) { ::TControlFrame *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TInstrumentedIsAProxy< ::TControlFrame >(0); static ::ROOT::TGenericClassInfo instance("TControlFrame", ::TControlFrame::Class_Version(), "TControlFrame.h", 46, typeid(::TControlFrame), ::ROOT::Internal::DefineBehavior(ptr, ptr), &::TControlFrame::Dictionary, isa_proxy, 4, sizeof(::TControlFrame) ); instance.SetDelete(&delete_TControlFrame); instance.SetDeleteArray(&deleteArray_TControlFrame); instance.SetDestructor(&destruct_TControlFrame); return &instance; } TGenericClassInfo *GenerateInitInstance(const ::TControlFrame*) { return GenerateInitInstanceLocal((::TControlFrame*)0); } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::TControlFrame*)0x0); R__UseDummy(_R__UNIQUE_(Init)); } // end of namespace ROOT namespace ROOT { static void delete_TMasterTask(void *p); static void deleteArray_TMasterTask(void *p); static void destruct_TMasterTask(void *p); static void streamer_TMasterTask(TBuffer &buf, void *obj); // Function generating the singleton type initializer static TGenericClassInfo *GenerateInitInstanceLocal(const ::TMasterTask*) { ::TMasterTask *ptr = 0; static ::TVirtualIsAProxy* isa_proxy = new ::TInstrumentedIsAProxy< ::TMasterTask >(0); static ::ROOT::TGenericClassInfo instance("TMasterTask", ::TMasterTask::Class_Version(), "TMasterTask.h", 30, typeid(::TMasterTask), ::ROOT::Internal::DefineBehavior(ptr, ptr), &::TMasterTask::Dictionary, isa_proxy, 16, sizeof(::TMasterTask) ); instance.SetDelete(&delete_TMasterTask); instance.SetDeleteArray(&deleteArray_TMasterTask); instance.SetDestructor(&destruct_TMasterTask); instance.SetStreamerFunc(&streamer_TMasterTask); return &instance; } TGenericClassInfo *GenerateInitInstance(const ::TMasterTask*) { return GenerateInitInstanceLocal((::TMasterTask*)0); } // Static variable to force the class initialization static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::TMasterTask*)0x0); R__UseDummy(_R__UNIQUE_(Init)); } // end of namespace ROOT //______________________________________________________________________________ atomic_TClass_ptr TBoard::fgIsA(0); // static to hold class pointer //______________________________________________________________________________ const char *TBoard::Class_Name() { return "TBoard"; } //______________________________________________________________________________ const char *TBoard::ImplFileName() { return ::ROOT::GenerateInitInstanceLocal((const ::TBoard*)0x0)->GetImplFileName(); } //______________________________________________________________________________ int TBoard::ImplFileLine() { return ::ROOT::GenerateInitInstanceLocal((const ::TBoard*)0x0)->GetImplFileLine(); } //______________________________________________________________________________ TClass *TBoard::Dictionary() { fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TBoard*)0x0)->GetClass(); return fgIsA; } //______________________________________________________________________________ TClass *TBoard::Class() { if (!fgIsA.load()) { R__LOCKGUARD2(gInterpreterMutex); fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TBoard*)0x0)->GetClass(); } return fgIsA; } //______________________________________________________________________________ atomic_TClass_ptr TControl::fgIsA(0); // static to hold class pointer //______________________________________________________________________________ const char *TControl::Class_Name() { return "TControl"; } //______________________________________________________________________________ const char *TControl::ImplFileName() { return ::ROOT::GenerateInitInstanceLocal((const ::TControl*)0x0)->GetImplFileName(); } //______________________________________________________________________________ int TControl::ImplFileLine() { return ::ROOT::GenerateInitInstanceLocal((const ::TControl*)0x0)->GetImplFileLine(); } //______________________________________________________________________________ TClass *TControl::Dictionary() { fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TControl*)0x0)->GetClass(); return fgIsA; } //______________________________________________________________________________ TClass *TControl::Class() { if (!fgIsA.load()) { R__LOCKGUARD2(gInterpreterMutex); fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TControl*)0x0)->GetClass(); } return fgIsA; } //______________________________________________________________________________ atomic_TClass_ptr TModV785::fgIsA(0); // static to hold class pointer //______________________________________________________________________________ const char *TModV785::Class_Name() { return "TModV785"; } //______________________________________________________________________________ const char *TModV785::ImplFileName() { return ::ROOT::GenerateInitInstanceLocal((const ::TModV785*)0x0)->GetImplFileName(); } //______________________________________________________________________________ int TModV785::ImplFileLine() { return ::ROOT::GenerateInitInstanceLocal((const ::TModV785*)0x0)->GetImplFileLine(); } //______________________________________________________________________________ TClass *TModV785::Dictionary() { fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TModV785*)0x0)->GetClass(); return fgIsA; } //______________________________________________________________________________ TClass *TModV785::Class() { if (!fgIsA.load()) { R__LOCKGUARD2(gInterpreterMutex); fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TModV785*)0x0)->GetClass(); } return fgIsA; } //______________________________________________________________________________ atomic_TClass_ptr TModV785N::fgIsA(0); // static to hold class pointer //______________________________________________________________________________ const char *TModV785N::Class_Name() { return "TModV785N"; } //______________________________________________________________________________ const char *TModV785N::ImplFileName() { return ::ROOT::GenerateInitInstanceLocal((const ::TModV785N*)0x0)->GetImplFileName(); } //______________________________________________________________________________ int TModV785N::ImplFileLine() { return ::ROOT::GenerateInitInstanceLocal((const ::TModV785N*)0x0)->GetImplFileLine(); } //______________________________________________________________________________ TClass *TModV785N::Dictionary() { fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TModV785N*)0x0)->GetClass(); return fgIsA; } //______________________________________________________________________________ TClass *TModV785N::Class() { if (!fgIsA.load()) { R__LOCKGUARD2(gInterpreterMutex); fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TModV785N*)0x0)->GetClass(); } return fgIsA; } //______________________________________________________________________________ atomic_TClass_ptr TModV775::fgIsA(0); // static to hold class pointer //______________________________________________________________________________ const char *TModV775::Class_Name() { return "TModV775"; } //______________________________________________________________________________ const char *TModV775::ImplFileName() { return ::ROOT::GenerateInitInstanceLocal((const ::TModV775*)0x0)->GetImplFileName(); } //______________________________________________________________________________ int TModV775::ImplFileLine() { return ::ROOT::GenerateInitInstanceLocal((const ::TModV775*)0x0)->GetImplFileLine(); } //______________________________________________________________________________ TClass *TModV775::Dictionary() { fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TModV775*)0x0)->GetClass(); return fgIsA; } //______________________________________________________________________________ TClass *TModV775::Class() { if (!fgIsA.load()) { R__LOCKGUARD2(gInterpreterMutex); fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TModV775*)0x0)->GetClass(); } return fgIsA; } //______________________________________________________________________________ atomic_TClass_ptr TModV775N::fgIsA(0); // static to hold class pointer //______________________________________________________________________________ const char *TModV775N::Class_Name() { return "TModV775N"; } //______________________________________________________________________________ const char *TModV775N::ImplFileName() { return ::ROOT::GenerateInitInstanceLocal((const ::TModV775N*)0x0)->GetImplFileName(); } //______________________________________________________________________________ int TModV775N::ImplFileLine() { return ::ROOT::GenerateInitInstanceLocal((const ::TModV775N*)0x0)->GetImplFileLine(); } //______________________________________________________________________________ TClass *TModV775N::Dictionary() { fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TModV775N*)0x0)->GetClass(); return fgIsA; } //______________________________________________________________________________ TClass *TModV775N::Class() { if (!fgIsA.load()) { R__LOCKGUARD2(gInterpreterMutex); fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TModV775N*)0x0)->GetClass(); } return fgIsA; } //______________________________________________________________________________ atomic_TClass_ptr TModV830AC::fgIsA(0); // static to hold class pointer //______________________________________________________________________________ const char *TModV830AC::Class_Name() { return "TModV830AC"; } //______________________________________________________________________________ const char *TModV830AC::ImplFileName() { return ::ROOT::GenerateInitInstanceLocal((const ::TModV830AC*)0x0)->GetImplFileName(); } //______________________________________________________________________________ int TModV830AC::ImplFileLine() { return ::ROOT::GenerateInitInstanceLocal((const ::TModV830AC*)0x0)->GetImplFileLine(); } //______________________________________________________________________________ TClass *TModV830AC::Dictionary() { fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TModV830AC*)0x0)->GetClass(); return fgIsA; } //______________________________________________________________________________ TClass *TModV830AC::Class() { if (!fgIsA.load()) { R__LOCKGUARD2(gInterpreterMutex); fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TModV830AC*)0x0)->GetClass(); } return fgIsA; } //______________________________________________________________________________ atomic_TClass_ptr TModV792::fgIsA(0); // static to hold class pointer //______________________________________________________________________________ const char *TModV792::Class_Name() { return "TModV792"; } //______________________________________________________________________________ const char *TModV792::ImplFileName() { return ::ROOT::GenerateInitInstanceLocal((const ::TModV792*)0x0)->GetImplFileName(); } //______________________________________________________________________________ int TModV792::ImplFileLine() { return ::ROOT::GenerateInitInstanceLocal((const ::TModV792*)0x0)->GetImplFileLine(); } //______________________________________________________________________________ TClass *TModV792::Dictionary() { fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TModV792*)0x0)->GetClass(); return fgIsA; } //______________________________________________________________________________ TClass *TModV792::Class() { if (!fgIsA.load()) { R__LOCKGUARD2(gInterpreterMutex); fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TModV792*)0x0)->GetClass(); } return fgIsA; } //______________________________________________________________________________ atomic_TClass_ptr TControlFrame::fgIsA(0); // static to hold class pointer //______________________________________________________________________________ const char *TControlFrame::Class_Name() { return "TControlFrame"; } //______________________________________________________________________________ const char *TControlFrame::ImplFileName() { return ::ROOT::GenerateInitInstanceLocal((const ::TControlFrame*)0x0)->GetImplFileName(); } //______________________________________________________________________________ int TControlFrame::ImplFileLine() { return ::ROOT::GenerateInitInstanceLocal((const ::TControlFrame*)0x0)->GetImplFileLine(); } //______________________________________________________________________________ TClass *TControlFrame::Dictionary() { fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TControlFrame*)0x0)->GetClass(); return fgIsA; } //______________________________________________________________________________ TClass *TControlFrame::Class() { if (!fgIsA.load()) { R__LOCKGUARD2(gInterpreterMutex); fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TControlFrame*)0x0)->GetClass(); } return fgIsA; } //______________________________________________________________________________ atomic_TClass_ptr TMasterTask::fgIsA(0); // static to hold class pointer //______________________________________________________________________________ const char *TMasterTask::Class_Name() { return "TMasterTask"; } //______________________________________________________________________________ const char *TMasterTask::ImplFileName() { return ::ROOT::GenerateInitInstanceLocal((const ::TMasterTask*)0x0)->GetImplFileName(); } //______________________________________________________________________________ int TMasterTask::ImplFileLine() { return ::ROOT::GenerateInitInstanceLocal((const ::TMasterTask*)0x0)->GetImplFileLine(); } //______________________________________________________________________________ TClass *TMasterTask::Dictionary() { fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TMasterTask*)0x0)->GetClass(); return fgIsA; } //______________________________________________________________________________ TClass *TMasterTask::Class() { if (!fgIsA.load()) { R__LOCKGUARD2(gInterpreterMutex); fgIsA = ::ROOT::GenerateInitInstanceLocal((const ::TMasterTask*)0x0)->GetClass(); } return fgIsA; } //______________________________________________________________________________ void TBoard::Streamer(TBuffer &R__b) { // Stream an object of class TBoard. UInt_t R__s, R__c; if (R__b.IsReading()) { Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v) { } R__b >> fGeo; R__b >> fCrateNum; R__b >> MaxChannel; R__b.CheckByteCount(R__s, R__c, TBoard::IsA()); } else { R__c = R__b.WriteVersion(TBoard::IsA(), kTRUE); R__b << fGeo; R__b << fCrateNum; R__b << MaxChannel; R__b.SetByteCount(R__c, kTRUE); } } namespace ROOT { // Wrapper around operator delete static void delete_TBoard(void *p) { delete ((::TBoard*)p); } static void deleteArray_TBoard(void *p) { delete [] ((::TBoard*)p); } static void destruct_TBoard(void *p) { typedef ::TBoard current_t; ((current_t*)p)->~current_t(); } // Wrapper around a custom streamer member function. static void streamer_TBoard(TBuffer &buf, void *obj) { ((::TBoard*)obj)->::TBoard::Streamer(buf); } } // end of namespace ROOT for class ::TBoard //______________________________________________________________________________ void TControl::Streamer(TBuffer &R__b) { // Stream an object of class TControl. UInt_t R__s, R__c; if (R__b.IsReading()) { Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v) { } TQObject::Streamer(R__b); R__b.CheckByteCount(R__s, R__c, TControl::IsA()); } else { R__c = R__b.WriteVersion(TControl::IsA(), kTRUE); TQObject::Streamer(R__b); R__b.SetByteCount(R__c, kTRUE); } } namespace ROOT { // Wrapper around operator delete static void delete_TControl(void *p) { delete ((::TControl*)p); } static void deleteArray_TControl(void *p) { delete [] ((::TControl*)p); } static void destruct_TControl(void *p) { typedef ::TControl current_t; ((current_t*)p)->~current_t(); } // Wrapper around a custom streamer member function. static void streamer_TControl(TBuffer &buf, void *obj) { ((::TControl*)obj)->::TControl::Streamer(buf); } } // end of namespace ROOT for class ::TControl //______________________________________________________________________________ void TModV785::Streamer(TBuffer &R__b) { // Stream an object of class TModV785. UInt_t R__s, R__c; if (R__b.IsReading()) { Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v) { } TBoard::Streamer(R__b); R__b.ReadStaticArray((unsigned short*)chdata); R__b.CheckByteCount(R__s, R__c, TModV785::IsA()); } else { R__c = R__b.WriteVersion(TModV785::IsA(), kTRUE); TBoard::Streamer(R__b); R__b.WriteArray(chdata, 32); R__b.SetByteCount(R__c, kTRUE); } } namespace ROOT { // Wrappers around operator new static void *new_TModV785(void *p) { return p ? new(p) ::TModV785 : new ::TModV785; } static void *newArray_TModV785(Long_t nElements, void *p) { return p ? new(p) ::TModV785[nElements] : new ::TModV785[nElements]; } // Wrapper around operator delete static void delete_TModV785(void *p) { delete ((::TModV785*)p); } static void deleteArray_TModV785(void *p) { delete [] ((::TModV785*)p); } static void destruct_TModV785(void *p) { typedef ::TModV785 current_t; ((current_t*)p)->~current_t(); } // Wrapper around a custom streamer member function. static void streamer_TModV785(TBuffer &buf, void *obj) { ((::TModV785*)obj)->::TModV785::Streamer(buf); } } // end of namespace ROOT for class ::TModV785 //______________________________________________________________________________ void TModV785N::Streamer(TBuffer &R__b) { // Stream an object of class TModV785N. UInt_t R__s, R__c; if (R__b.IsReading()) { Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v) { } TBoard::Streamer(R__b); R__b.ReadStaticArray((unsigned short*)chdata); R__b.CheckByteCount(R__s, R__c, TModV785N::IsA()); } else { R__c = R__b.WriteVersion(TModV785N::IsA(), kTRUE); TBoard::Streamer(R__b); R__b.WriteArray(chdata, 16); R__b.SetByteCount(R__c, kTRUE); } } namespace ROOT { // Wrappers around operator new static void *new_TModV785N(void *p) { return p ? new(p) ::TModV785N : new ::TModV785N; } static void *newArray_TModV785N(Long_t nElements, void *p) { return p ? new(p) ::TModV785N[nElements] : new ::TModV785N[nElements]; } // Wrapper around operator delete static void delete_TModV785N(void *p) { delete ((::TModV785N*)p); } static void deleteArray_TModV785N(void *p) { delete [] ((::TModV785N*)p); } static void destruct_TModV785N(void *p) { typedef ::TModV785N current_t; ((current_t*)p)->~current_t(); } // Wrapper around a custom streamer member function. static void streamer_TModV785N(TBuffer &buf, void *obj) { ((::TModV785N*)obj)->::TModV785N::Streamer(buf); } } // end of namespace ROOT for class ::TModV785N //______________________________________________________________________________ void TModV775::Streamer(TBuffer &R__b) { // Stream an object of class TModV775. UInt_t R__s, R__c; if (R__b.IsReading()) { Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v) { } TBoard::Streamer(R__b); R__b.ReadStaticArray((unsigned short*)chdata); R__b.CheckByteCount(R__s, R__c, TModV775::IsA()); } else { R__c = R__b.WriteVersion(TModV775::IsA(), kTRUE); TBoard::Streamer(R__b); R__b.WriteArray(chdata, 32); R__b.SetByteCount(R__c, kTRUE); } } namespace ROOT { // Wrappers around operator new static void *new_TModV775(void *p) { return p ? new(p) ::TModV775 : new ::TModV775; } static void *newArray_TModV775(Long_t nElements, void *p) { return p ? new(p) ::TModV775[nElements] : new ::TModV775[nElements]; } // Wrapper around operator delete static void delete_TModV775(void *p) { delete ((::TModV775*)p); } static void deleteArray_TModV775(void *p) { delete [] ((::TModV775*)p); } static void destruct_TModV775(void *p) { typedef ::TModV775 current_t; ((current_t*)p)->~current_t(); } // Wrapper around a custom streamer member function. static void streamer_TModV775(TBuffer &buf, void *obj) { ((::TModV775*)obj)->::TModV775::Streamer(buf); } } // end of namespace ROOT for class ::TModV775 //______________________________________________________________________________ void TModV775N::Streamer(TBuffer &R__b) { // Stream an object of class TModV775N. UInt_t R__s, R__c; if (R__b.IsReading()) { Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v) { } TBoard::Streamer(R__b); R__b.ReadStaticArray((unsigned short*)chdata); R__b.CheckByteCount(R__s, R__c, TModV775N::IsA()); } else { R__c = R__b.WriteVersion(TModV775N::IsA(), kTRUE); TBoard::Streamer(R__b); R__b.WriteArray(chdata, 16); R__b.SetByteCount(R__c, kTRUE); } } namespace ROOT { // Wrappers around operator new static void *new_TModV775N(void *p) { return p ? new(p) ::TModV775N : new ::TModV775N; } static void *newArray_TModV775N(Long_t nElements, void *p) { return p ? new(p) ::TModV775N[nElements] : new ::TModV775N[nElements]; } // Wrapper around operator delete static void delete_TModV775N(void *p) { delete ((::TModV775N*)p); } static void deleteArray_TModV775N(void *p) { delete [] ((::TModV775N*)p); } static void destruct_TModV775N(void *p) { typedef ::TModV775N current_t; ((current_t*)p)->~current_t(); } // Wrapper around a custom streamer member function. static void streamer_TModV775N(TBuffer &buf, void *obj) { ((::TModV775N*)obj)->::TModV775N::Streamer(buf); } } // end of namespace ROOT for class ::TModV775N //______________________________________________________________________________ void TModV830AC::Streamer(TBuffer &R__b) { // Stream an object of class TModV830AC. UInt_t R__s, R__c; if (R__b.IsReading()) { Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v) { } TBoard::Streamer(R__b); R__b.ReadStaticArray((unsigned int*)chdata); R__b.CheckByteCount(R__s, R__c, TModV830AC::IsA()); } else { R__c = R__b.WriteVersion(TModV830AC::IsA(), kTRUE); TBoard::Streamer(R__b); R__b.WriteArray(chdata, 32); R__b.SetByteCount(R__c, kTRUE); } } namespace ROOT { // Wrappers around operator new static void *new_TModV830AC(void *p) { return p ? new(p) ::TModV830AC : new ::TModV830AC; } static void *newArray_TModV830AC(Long_t nElements, void *p) { return p ? new(p) ::TModV830AC[nElements] : new ::TModV830AC[nElements]; } // Wrapper around operator delete static void delete_TModV830AC(void *p) { delete ((::TModV830AC*)p); } static void deleteArray_TModV830AC(void *p) { delete [] ((::TModV830AC*)p); } static void destruct_TModV830AC(void *p) { typedef ::TModV830AC current_t; ((current_t*)p)->~current_t(); } // Wrapper around a custom streamer member function. static void streamer_TModV830AC(TBuffer &buf, void *obj) { ((::TModV830AC*)obj)->::TModV830AC::Streamer(buf); } } // end of namespace ROOT for class ::TModV830AC //______________________________________________________________________________ void TModV792::Streamer(TBuffer &R__b) { // Stream an object of class TModV792. UInt_t R__s, R__c; if (R__b.IsReading()) { Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v) { } TBoard::Streamer(R__b); R__b.ReadStaticArray((unsigned short*)chdata); R__b.CheckByteCount(R__s, R__c, TModV792::IsA()); } else { R__c = R__b.WriteVersion(TModV792::IsA(), kTRUE); TBoard::Streamer(R__b); R__b.WriteArray(chdata, 32); R__b.SetByteCount(R__c, kTRUE); } } namespace ROOT { // Wrappers around operator new static void *new_TModV792(void *p) { return p ? new(p) ::TModV792 : new ::TModV792; } static void *newArray_TModV792(Long_t nElements, void *p) { return p ? new(p) ::TModV792[nElements] : new ::TModV792[nElements]; } // Wrapper around operator delete static void delete_TModV792(void *p) { delete ((::TModV792*)p); } static void deleteArray_TModV792(void *p) { delete [] ((::TModV792*)p); } static void destruct_TModV792(void *p) { typedef ::TModV792 current_t; ((current_t*)p)->~current_t(); } // Wrapper around a custom streamer member function. static void streamer_TModV792(TBuffer &buf, void *obj) { ((::TModV792*)obj)->::TModV792::Streamer(buf); } } // end of namespace ROOT for class ::TModV792 namespace ROOT { // Wrapper around operator delete static void delete_TEvtBuilder(void *p) { delete ((::TEvtBuilder*)p); } static void deleteArray_TEvtBuilder(void *p) { delete [] ((::TEvtBuilder*)p); } static void destruct_TEvtBuilder(void *p) { typedef ::TEvtBuilder current_t; ((current_t*)p)->~current_t(); } } // end of namespace ROOT for class ::TEvtBuilder namespace ROOT { // Wrapper around operator delete static void delete_TClientEvtBuilder(void *p) { delete ((::TClientEvtBuilder*)p); } static void deleteArray_TClientEvtBuilder(void *p) { delete [] ((::TClientEvtBuilder*)p); } static void destruct_TClientEvtBuilder(void *p) { typedef ::TClientEvtBuilder current_t; ((current_t*)p)->~current_t(); } } // end of namespace ROOT for class ::TClientEvtBuilder //______________________________________________________________________________ void TControlFrame::Streamer(TBuffer &R__b) { // Stream an object of class TControlFrame. if (R__b.IsReading()) { R__b.ReadClassBuffer(TControlFrame::Class(),this); } else { R__b.WriteClassBuffer(TControlFrame::Class(),this); } } namespace ROOT { // Wrapper around operator delete static void delete_TControlFrame(void *p) { delete ((::TControlFrame*)p); } static void deleteArray_TControlFrame(void *p) { delete [] ((::TControlFrame*)p); } static void destruct_TControlFrame(void *p) { typedef ::TControlFrame current_t; ((current_t*)p)->~current_t(); } } // end of namespace ROOT for class ::TControlFrame //______________________________________________________________________________ void TMasterTask::Streamer(TBuffer &R__b) { // Stream an object of class TMasterTask. UInt_t R__s, R__c; if (R__b.IsReading()) { Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v) { } TControlFrame::Streamer(R__b); R__b.CheckByteCount(R__s, R__c, TMasterTask::IsA()); } else { R__c = R__b.WriteVersion(TMasterTask::IsA(), kTRUE); TControlFrame::Streamer(R__b); R__b.SetByteCount(R__c, kTRUE); } } namespace ROOT { // Wrapper around operator delete static void delete_TMasterTask(void *p) { delete ((::TMasterTask*)p); } static void deleteArray_TMasterTask(void *p) { delete [] ((::TMasterTask*)p); } static void destruct_TMasterTask(void *p) { typedef ::TMasterTask current_t; ((current_t*)p)->~current_t(); } // Wrapper around a custom streamer member function. static void streamer_TMasterTask(TBuffer &buf, void *obj) { ((::TMasterTask*)obj)->::TMasterTask::Streamer(buf); } } // end of namespace ROOT for class ::TMasterTask namespace { void TriggerDictionaryInitialization_classDict_Impl() { static const char* headers[] = { "TBoard.h", "TControl.h", "TModV785.h", "TModV785N.h", "TModV775.h", "TModV775N.h", "TModV830AC.h", "TModV792.h", "TEvtBuilder.h", "TClientEvtBuilder.h", "TControlFrame.h", "TDataFileBuilder.h", "TMasterTask.h", 0 }; static const char* includePaths[] = { "/home/xiaohai/Softwear/root/include", "/home/xiaohai/Github/ribll/ribllvmedaq/", 0 }; static const char* fwdDeclCode = R"DICTFWDDCLS( #line 1 "classDict dictionary forward declarations' payload" #pragma clang diagnostic ignored "-Wkeyword-compat" #pragma clang diagnostic ignored "-Wignored-attributes" #pragma clang diagnostic ignored "-Wreturn-type-c-linkage" extern int __Cling_Autoloading_Map; class __attribute__((annotate("$clingAutoload$TBoard.h"))) TBoard; class __attribute__((annotate("$clingAutoload$TControl.h"))) TControl; class __attribute__((annotate("$clingAutoload$TModV785.h"))) TModV785; class __attribute__((annotate("$clingAutoload$TModV785N.h"))) TModV785N; class __attribute__((annotate("$clingAutoload$TModV775.h"))) TModV775; class __attribute__((annotate("$clingAutoload$TModV775N.h"))) TModV775N; class __attribute__((annotate("$clingAutoload$TModV830AC.h"))) TModV830AC; class __attribute__((annotate("$clingAutoload$TModV792.h"))) TModV792; class __attribute__((annotate("$clingAutoload$TEvtBuilder.h"))) TEvtBuilder; class __attribute__((annotate("$clingAutoload$TClientEvtBuilder.h"))) TClientEvtBuilder; class __attribute__((annotate("$clingAutoload$TControlFrame.h"))) TControlFrame; class __attribute__((annotate("$clingAutoload$TMasterTask.h"))) TMasterTask; )DICTFWDDCLS"; static const char* payloadCode = R"DICTPAYLOAD( #line 1 "classDict dictionary payload" #ifndef G__VECTOR_HAS_CLASS_ITERATOR #define G__VECTOR_HAS_CLASS_ITERATOR 1 #endif #ifndef LINUX #define LINUX 1 #endif #define _BACKWARD_BACKWARD_WARNING_H #include "TBoard.h" #include "TControl.h" #include "TModV785.h" #include "TModV785N.h" #include "TModV775.h" #include "TModV775N.h" #include "TModV830AC.h" #include "TModV792.h" #include "TEvtBuilder.h" #include "TClientEvtBuilder.h" #include "TControlFrame.h" #include "TDataFileBuilder.h" #include "TMasterTask.h" #undef _BACKWARD_BACKWARD_WARNING_H )DICTPAYLOAD"; static const char* classesHeaders[]={ "TBoard", payloadCode, "@", "TClientEvtBuilder", payloadCode, "@", "TControl", payloadCode, "@", "TControlFrame", payloadCode, "@", "TEvtBuilder", payloadCode, "@", "TMasterTask", payloadCode, "@", "TModV775", payloadCode, "@", "TModV775N", payloadCode, "@", "TModV785", payloadCode, "@", "TModV785N", payloadCode, "@", "TModV792", payloadCode, "@", "TModV830AC", payloadCode, "@", nullptr}; static bool isInitialized = false; if (!isInitialized) { TROOT::RegisterModule("classDict", headers, includePaths, payloadCode, fwdDeclCode, TriggerDictionaryInitialization_classDict_Impl, {}, classesHeaders); isInitialized = true; } } static struct DictInit { DictInit() { TriggerDictionaryInitialization_classDict_Impl(); } } __TheDictionaryInitializer; } void TriggerDictionaryInitialization_classDict() { TriggerDictionaryInitialization_classDict_Impl(); } <file_sep>/ribllvmedaq/TOnline.h ///////////////////////////////////////////////////////// // File name: Online.h // // Brief introduction: // // Online program of RIBLL1-DAQ // // // // Version: V1.0 // // Author: <NAME> // // Date: Nov. 2010 // // For: RIBLL1 // ///////////////////////////////////////////////////////// #ifndef Online_ROOT_H #define Online_ROOT_H #ifndef OnlineFrame_H #include "TOnlineFrame.h" #endif //#ifndef OnlineFrame_H class TGWindow; class TGLVEntry; class TFile; class TCanvas; class TThread; class TGTextButton; class TDataReceiver; class TDataAnalyser; class TTree; class TOnline :public TOnlineFrame { protected: TThread *OnlineThread; static bool setonline; static TDataReceiver *datarec; static TDataAnalyser *anadata; public: TOnline(const TGWindow *p, UInt_t w, UInt_t h, TDataAnalyser *dana); virtual ~TOnline(); virtual bool ProcessMessage(Long_t msg, Long_t param1, Long_t); void SetOffline(); static void SetOnline(void *arg); int StartOnline(); TGTextButton *GetBOnline(){return fBonline;} static bool& Getsetonline(){return setonline;} void CreateTH1I(); void CreateTree(); TDataAnalyser *GetDataAnalyser(){return anadata;} friend int GetRawData(int Crate, int Geo, int channel); protected: TOnline(const TOnline &onl); TOnline &operator=(const TOnline &onl); }; extern TOnline *gOnline; #endif //#ifndef Online_ROOT_H <file_sep>/ribllvmedaq/TEvtBuilder.cpp //////////////////////////////////////////////// // TEvtBuilder.cpp: Class to perform the VME // reading and build the 'event' structure. // Use TCrateCBLT to loop reading procedure, // and then build the event in memory, then // send it out to ethernet by using UDP // socket. // <NAME> 07/2012 //////////////////////////////////////////////// #include <iostream> using namespace std; //#include "TUDPClientSocket.h" #include "TEvtBuilder.h" #include "TControl.h" #include "TCrateCBLT.h" #include "TString.h" #include "TThread.h" int TEvtBuilder::fnumcrates = 0; int TEvtBuilder::fevent_counter = 0; unsigned int TEvtBuilder::fnetbuf[NETBUFFER/4]; TEvtBuilder* onlyTEvtBuilder = 0; TEvtBuilder::TEvtBuilder(TConfig &cod, std::vector<TCrateCBLT> &tcrate, unsigned int mastercrate ):fconfig(cod), fcrate(tcrate) { if(onlyTEvtBuilder) { cout<< "TEvtBuilder>> only one instance of TEvtBuilder allowed. " << endl; return; } onlyTEvtBuilder = this; fnumcrates = tcrate.size(); fokstop = true; fmastercrate = 0; // search the index of 'mastercrate' in vector 'fcrate' for(unsigned int i=0; i<fcrate.size(); i++) { //cout << "Crate number: " << fcrate[i].GetCrateNum() << endl; if(fcrate[i].GetCrateNum() == mastercrate) fmastercrate = i; } } bool TEvtBuilder::CheckStop() { bool check = false; TThread::Lock(); check = (TControl::comm == kC_STOP); TThread::UnLock(); return check; }<file_sep>/ribllvmedaq/TOnlineFrame.h ///////////////////////////////////////////////////////// // File name: TOnlineFrame.h // // Brief introduction: // // This class create the main frame for // // Online program of RIBLL1-DAQ // // // // Version: V1.0 // // Author: <NAME> // // Date: Nov. 2010 // // For: RIBLL1 // ///////////////////////////////////////////////////////// #ifndef OnlineFrame_H #define OnlineFrame_H #ifndef ROOT_TGFrame #include "TGFrame.h" #endif //#ifndef ROOT_TGFrame #ifndef ROOT_TString #include "TString.h" #endif //#ifndef ROOT_TString class TGMainFrame; class TGVerticalFrame; class TGWindow; class TGFileContainer; class TGLabel; class TGListView; class TGLVEntry; class TGTextView; class TGComboBox; class TGTextButton; class TGText; class TCanvas; class TString; class TList; class TFile; class TIter; class TTree; class TObject; enum CMDIdentifiers { kB_online, kB_offline, kB_exit, kB_resetcurr, kB_resetall, kB_privious, kB_next, kB_update, kB_integral }; class TOnlineFrame : public TGMainFrame { protected: TGVerticalFrame *fFFileList, *fFButton; TGHorizontalFrame *fFTextView; TGLabel *flabDrawOpt, *flabDivPad, *flabText; TGComboBox *fcomDrawOpt, *fcomAxisOpt, *fcomDivPad; TGListView *flvFile; TGFileContainer *fFileCont; TGTextButton *fBonline, *fBoffline, *fBresetcurr, *fBresetall, *fBprevious, *fBnext, *fBupdate, *fBintegral, *fBexit; TGTextView *fviewText; TCanvas *candaq; TObject *objcurr; TList *ObjList; TFile *datafile; static TTree *tree; TList *TCmlist; //TCavas Contextmenu list TList *THmlist; //TH1F Contextmenu list TList *TH2mlist; //TH2F Contextmenu list public: TOnlineFrame(const TGWindow *p, UInt_t w, UInt_t h); virtual ~TOnlineFrame(); virtual void CloseWindow(); virtual bool ProcessMessage(Long_t msg, Long_t param1, Long_t); const char* GetDrawOpt(); void ShowText(TGText *text); void ShowText(const char *text); virtual void CreateCanvas(); void ClearTextView(); virtual void OnDoubleClick(TGLVEntry* f, Int_t btn); virtual void DisplayFile(const TString &fname); virtual void DisplayObject(const TString& fname,const TString& name); virtual void DisplayDirectory(const TString &fname); virtual void ImB_update(); virtual void ImB_next(); virtual void ImB_previous(); virtual void ImB_integral(); virtual bool ObjListOK(); virtual void DrawObj(TObject *obj); virtual void DrawObj(CMDIdentifiers id); virtual void ResetTH(TObject *obj); virtual void ImB_ResetAllTH(); virtual void ImB_ResetCurrTH(); virtual void GetDivPad(int &nx, int &ny); virtual void RemoveMenuEntry(const char *menuTitle, TList *mlist); virtual void MakeTcMenuList(); virtual void MakeTH1MenuList(); virtual void MakeTH2MenuList(); virtual void GetAxisOpt(unsigned int& lx, unsigned int& ly); friend void OnlineUserFunction(TOnlineFrame *onl); friend void HBOOK1(int id, const char *title, int nxbin, float xlow, float xup, float vmx); friend void HBOOK2(int id, const char *title, int nxbin, float xlow, float xup, int nybin, float ylow, float yup, float vmx); friend void HF1(int id, float value, float weight); friend void HF2(int id, float x, float y, float weight); friend bool HEXIST(int ihist); protected: TOnlineFrame(const TOnlineFrame &onf); TOnlineFrame& operator=(const TOnlineFrame &onf); }; extern TOnlineFrame *gOnlineFrame; #endif //#ifndef OnlineFrame_H <file_sep>/ribllvmedaq/TVMELink.h ////////////////////////////////////////////////////////// // TVMELink.h include file interfaces // TVME class interface: V2718 manager // These classes define the DAQ hardware configuration // E.d.F (08/2007) test version v.07 // (Modified by <NAME> 07/2012) // caen lib wrapper not yet implemented ///////////////////////////////////////////////////////// // The Caen bridge V2718 class #ifndef TVMELink_H #define TVMELink_H #include <map> #include "caenacq.h" #include "CAENVMEtypes.h" using namespace std; class TVMELink { protected: int fHandle; // V2718 handle char fHwrel[32]; // V2718 hardware release number char fSwrel[32]; // V2718 software release number CVErrorCodes fStatus; // V2718 error codes CVBoardTypes fControlBoardType; // V2718 board type short fPCILinkNum; // V2718 PCI device short fVMEControlBoardNum; // V2718 VME-PCI link int fCrate; // virtual crate number associated with V2718 public: static map<int, int> flookup_ind; //map crate-handle corrispondence public: TVMELink(CVBoardTypes ControlBoardType=cvV2718, short PCILinkNum=0, short VMEControlBoardNum=0, int crate=1); TVMELink(TVMELink const &source); virtual ~TVMELink(); void SetCrateNum(int crate) {fCrate=crate;} long GetHandle() {return fHandle;} int GetCrateNum() {return fCrate;} short GetDevice() {return fPCILinkNum;} short GetLink() {return fVMEControlBoardNum;} char *GetHWRel() {return fHwrel;} char *GetSWRel() {return fSwrel;} int Init(); CVErrorCodes EndVMEHandle(); void copy(TVMELink const &source); CVErrorCodes InitIOPort(CVOutputSelect, CVIOPolarity, CVLEDPolarity); CVErrorCodes SetIOPort(CVOutputRegisterBits cvbit); //level up CVErrorCodes ClearIOPort(CVOutputRegisterBits cvbit); //level down CVErrorCodes PulseOutput(CVOutputRegisterBits cvbit); //generate a pulse }; #endif //#ifndef TVMELink_H<file_sep>/ribllvmedaq/TMasterTask.cpp ///////////////////////////////////////////////////////// // File name: TMasterTask.cpp // // Brief introduction: // // Master PC task: Control daq, get data form // // UDP broadcast, save data to file ... // // Version: V1.0 // // Author: <NAME> // // Date: Aug. 2012 // // For: RIBLL1 // ///////////////////////////////////////////////////////// #include <iostream> #include <string> using namespace std; #include "TDataFileBuilder.h" #include "TControl.h" #include "TGClient.h" #include "TGLabel.h" #include "TThread.h" #include "TTimer.h" #include "TTimer.h" #include "TGTextEntry.h" #include "TString.h" #include "TGNumberEntry.h" #include "TGButton.h" #include "TSystem.h" #include "TMasterTask.h" #ifdef WIN32 #include <windows.h> #define sleep Sleep #define WaitSec 1000 #else #include <unistd.h> #define sleep usleep #define WaitSec 1000000 #endif ClassImp(TMasterTask); TMasterTask *gMasterTask=0; TTimer *TMasterTask::showevtimer=0; TTimer *TMasterTask::showconnect=0; TTimer *TMasterTask::checkdfsize=0; bool TMasterTask::TCPConnState = false; bool TMasterTask::TCPAcceptReturned = false; const int msec_singleshot = 2; TMasterTask::TMasterTask(TControl &netcon):TControlFrame(gClient->GetRoot(), 550, 450), mascontrol(netcon) { if(gMasterTask) { cout <<"Only one instance of 'TMasterTask' permitted. "<< endl; return; } gMasterTask = this; fFileBuilder = new TDataFileBuilder(); maxfilesize = fFileBuilder->GetMaxFileSizeMb(); thispcaction = mascontrol.GetPCAction(); if(thispcaction == CONTROL_PC) { InitButt(); } else { SetOnlinePCButt(); } Dfilestate = false; DaqRunning = false; //thshowevt = 0; thtcpaccept = 0; showevtimer = new TTimer(2000); showevtimer->Connect("Timeout()", Class_Name(), this, "ShowEventNumByTimer()"); showconnect = new TTimer(500); showconnect->Connect("Timeout()", Class_Name(), this, "ProcessTCPConnectedTimer()"); checkdfsize = new TTimer(20000); checkdfsize->Connect("Timeout()", Class_Name(), this, "RecrateDFileAuto()"); if(thispcaction == CONTROL_PC) { mascontrol.Connect("MSignalEmit()", Class_Name(), this, "ShowMessageSignal()"); mascontrol.Connect("BMSignalEmit()", Class_Name(), this, "CoutBroadMessageSignal()"); } else { //DAQPC: Connect message to stdio, because signal from thread will cause error if connect to GUI fuctions mascontrol.Connect("MSignalEmit()", Class_Name(), this, "CoutBroadMessageSignal()"); } mascontrol.Connect("CommandSignal(int);", Class_Name(), this, "ProcessControlSignal(int)"); } TMasterTask::~TMasterTask() { delete showevtimer; delete fFileBuilder; //if(thshowevt != NULL) //{ // TThread::Delete(thshowevt); // thshowevt = 0; //} if(thtcpaccept != NULL) { TThread::Delete(thtcpaccept); thtcpaccept = 0; } } void TMasterTask::ShowEventNumByTimer() { //cout << "Timer ..." << endl; static int oldevtnum = 0; int evtnum = TDataFileBuilder::eventcounter; if(evtnum != oldevtnum) { oldevtnum = evtnum; TThread::Lock(); ShowEventNum(evtnum); TThread::UnLock(); } } void TMasterTask::ImB_SetFileName() { TThread::Lock(); //lock the main mutex TString name(fTEfilename->GetText()); TThread::UnLock(); //unlock the main mutex if(name.Length()>0) { if(name.IsWhitespace()) { name.Clear(); name = "RawData"; } name.ReplaceAll(" ", ""); TThread::Lock(); //lock the main mutex fFileBuilder->SetFileName(name.Data()); TString text = "Set File Name: "; text += name; ShowText(text.Data()); TThread::UnLock(); //unlock the main mutex fFileBuilder->SetRunNum(0); //reset the runnumber to 0 TThread::Lock(); //lock the main mutex fTEfilerun->SetNumber(0); TThread::UnLock(); //unlock the main mutex } } void TMasterTask::ImB_SetFileRun() { TThread::Lock(); //lock the main mutex unsigned int num = (unsigned int)fTEfilerun->GetNumber(); TThread::UnLock(); //unlock the main mutex if(num>=0) { TThread::Lock(); //lock the main mutex fFileBuilder->SetRunNum(num); TString text = "Set File RunNum: "; text += num; ShowText(text.Data()); TThread::UnLock(); //unlock the main mutex } } void TMasterTask::ImB_SetFileHeader() { TThread::Lock(); //lock the main mutex TString header(fTEfileheader->GetText()); if(header.Length()>0) { fFileBuilder->SetFileHeader(header.Data()); ShowText("Set File Heaer OK."); } TThread::UnLock(); //unlock the main mutex } bool TMasterTask::ProcessMessage(Long_t msg, Long_t param1, Long_t) { switch (GET_MSG(msg)) { case kC_COMMAND: switch(GET_SUBMSG(msg)) { case kCM_BUTTON: switch (param1) { case kB_setfilename: ImB_SetFileName(); break; case kB_setfilerun: ImB_SetFileRun(); break; case kB_setfileheader: ImB_SetFileHeader(); break; case kB_start: if(thispcaction == CONTROL_PC) ImB_StartDaq(); if(thispcaction == ONLINE_PC ) ImB_StartOnlineDaq(); break; case kB_stop: ImB_StopDaq(); break; case kB_initdaq: ImB_InitDaq(); break; case kB_openf: ImB_OpenFile(); break; case kB_closef: ImB_CloseFile(); break; case kB_exitcon: CloseWindow(); break; case kB_connectodaq: ImB_Connect(); break; case kB_testcomm: ImB_TestComm(); break; case kB_exitdaq: ImB_ExitDaqpc(); break; default: break; } break; } break; default: break; } return true; } void TMasterTask::ShowMessageSignal() { TThread::Lock(); string mess = mascontrol.GetAckMessages(); //ShowText(mess.c_str()); cout << mess.c_str() << endl; TThread::UnLock(); } void TMasterTask::SetEnableAllButt(bool act) { TThread::Lock(); //lock the main mutex //fBSetFileName->SetEnabled(act); //fBSetFileRun->SetEnabled(act); //fBSetFileHeader->SetEnabled(act); fBStart->SetEnabled(act); fBStop->SetEnabled(act); fBInitDAQ->SetEnabled(act); fBOpenF->SetEnabled(act); fBCloseF->SetEnabled(act); //fBConExit->SetEnabled(act); fBConnect->SetEnabled(act); fBTestComm->SetEnabled(act); fBDaqExit->SetEnabled(act); TThread::UnLock(); //unlock the main mutex } void TMasterTask::InitButt() { TThread::Lock(); //lock the main mutex fBStart->SetEnabled(kFALSE); fBStop->SetEnabled(kFALSE); //fBInitDAQ->SetEnabled(kFALSE); fBOpenF->SetEnabled(kFALSE); fBCloseF->SetEnabled(kFALSE); fBTestComm->SetEnabled(kFALSE); fBDaqExit->SetEnabled(kFALSE); TThread::UnLock(); //unlock the main mutex } void* TMasterTask::ConnecttoDAQPC(void *arg) { TMasterTask *pthis = (TMasterTask *)arg; TControl &thismascontrol = pthis->GetControlMas(); TCPAcceptReturned = false; TCPConnState = false; showconnect->TurnOn(); TCPConnState = thismascontrol.AcceptReceiver(); TCPAcceptReturned = true; //cout << "Accept thread: " << conn << endl; //EmitTCPConnectedSignal(arg); return 0; } bool TMasterTask::ImB_Connect() { if(mascontrol.GetTCPSendSocketState()) //Control_PC and DAQ_PC is connected { TThread::Lock(); ShowText("Connection between Control_PC and DAQ_PC is OK."); TThread::UnLock(); return true; } SetEnableAllButt(kFALSE); L100: if(!thtcpaccept) { thtcpaccept = new TThread("TCPACCEPT", (void*(*)(void*))(&TMasterTask::ConnecttoDAQPC), (void*)this); if(thtcpaccept) { thtcpaccept->Run(); TThread::Lock(); ShowText("Wait for connection from DAQ_PC..."); TThread::UnLock(); return true; } else { thtcpaccept = 0; return false; } } else { if(thtcpaccept->GetState() != TThread::kRunningState) thtcpaccept->Run(); TThread::Lock(); ShowText("Wait for connection from DAQ_PC..."); TThread::UnLock(); if(thtcpaccept->GetState() == TThread::kInvalidState) { thtcpaccept = 0; goto L100; } return true; } //ConnecttoDAQPC(this); //return true; } void TMasterTask::ImB_TestComm() { mascontrol.send_TCPcontrol_command(sCommands[0]); } void TMasterTask::ImB_InitDaq() { mascontrol.send_TCPcontrol_command(sCommands[1]); } void TMasterTask::ImB_StartDaq() { bool status = false; if(thispcaction==CONTROL_PC) { status = mascontrol.send_TCPcontrol_command(sCommands[2]); if(status) { TThread::Lock(); //lock the main mutex fBStart->SetEnabled(kFALSE); fBStop->SetEnabled(kTRUE); //enable stop fBInitDAQ->SetEnabled(kFALSE); fBOpenF->SetEnabled(kFALSE); fBCloseF->SetEnabled(kFALSE); fBConExit->SetEnabled(kFALSE); fBConnect->SetEnabled(kFALSE); fBTestComm->SetEnabled(kFALSE); fBDaqExit->SetEnabled(kFALSE); //mascontrol.StartConPCRecErrThread(); checkdfsize->TurnOn(); TThread::UnLock(); //unlock the main mutex } } } void TMasterTask::ImB_StartOnlineDaq() { TThread::Lock(); //lock the main mutex bool state = mascontrol.StartOnlinePCThread(); if(state) { fBStart->SetEnabled(kFALSE); ShowText("OnlinePCThread running..."); } TThread::UnLock(); //unlock the main mutex } void TMasterTask::ImB_StopDaq() { bool status = false; if(thispcaction==CONTROL_PC) { status = mascontrol.send_TCPcontrol_command(sCommands[3]); if(status) { TThread::Lock(); //lock the main mutex fBStart->SetEnabled(true); //enable start fBStop->SetEnabled(kFALSE); //disable stop fBInitDAQ->SetEnabled(true); if(!Dfilestate) fBOpenF->SetEnabled(true); if(Dfilestate) fBCloseF->SetEnabled(true); if(!Dfilestate) fBConExit->SetEnabled(true); fBConnect->SetEnabled(true); fBTestComm->SetEnabled(true); if(!Dfilestate) fBDaqExit->SetEnabled(true); //mascontrol.StopConPCRecErrThread(); checkdfsize->TurnOff(); TThread::UnLock(); //unlock the main mutex } } } void TMasterTask::ImB_ExitDaqpc() { bool status = mascontrol.send_TCPcontrol_command(sCommands[6]); if(status) { InitButt(); mascontrol.ClosTCPimpSocket(); } } void TMasterTask::ProcessTCPConnectedTimer() { if(TCPAcceptReturned) //ConnecttoDAQPC() thread have returned { if(TCPConnState) { TThread::Lock(); //lock the main mutex SetEnableAllButt(true); DiableStopButt(); DiableCloseButt(); ShowText("OK! Control_PC and DAQ_PC connection established."); showconnect->TurnOff(); TThread::UnLock(); //unlock the main mutex } else { TThread::Lock(); //lock the main mutex InitButt(); ShowText("ERROR! Can NOT build connection between Control_PC and DAQ_PC."); showconnect->TurnOff(); TThread::UnLock(); //unlock the main mutex } } } void TMasterTask::SetOnlinePCButt() { TThread::Lock(); //lock the main mutex fBSetFileName->SetEnabled(kFALSE); fBSetFileRun->SetEnabled(kFALSE); fBSetFileHeader->SetEnabled(kFALSE); fBStart->SetEnabled(true); fBStop->SetEnabled(kFALSE); fBInitDAQ->SetEnabled(kFALSE); fBOpenF->SetEnabled(kFALSE); fBCloseF->SetEnabled(kFALSE); fBConExit->SetEnabled(true); fBConnect->SetEnabled(kFALSE); fBTestComm->SetEnabled(kFALSE); fBDaqExit->SetEnabled(kFALSE); TThread::UnLock(); //unlock the main mutex } void TMasterTask::CoutBroadMessageSignal() { TThread::Lock(); string mess = mascontrol.GetAckMessages(); TThread::UnLock(); cout << mess << endl; } bool TMasterTask::ProcessControlSignal(int comm) { if(comm == kC_START) { TThread::Lock(); //lock the main mutex bool state = fFileBuilder->StartWriteDataThread(); TThread::UnLock(); //unlock the main mutex if(state) { showevtimer->TurnOn(); DaqRunning = true; TThread::Lock(); //ShowText("OK! Write Data to File 'Thread' Started."); SetTextLocal("OK! Write Data to File 'Thread' Started."); ShowTextLocal(); //TTimer::SingleShot(msec_singleshot, Class_Name(), (void*)this, "ShowTextByTimer()"); TThread::UnLock(); return true; } else { TThread::Lock(); //ShowText("ERROR! Start Write Data to File 'Thread' Fail."); SetTextLocal("ERROR! Start Write Data to File 'Thread' Fail."); ShowTextLocal(); //TTimer::SingleShot(msec_singleshot, Class_Name(), (void*)this, "ShowTextByTimer()"); TThread::UnLock(); return false; } } if(comm == kC_STOP) { TThread::Lock(); //lock the main mutex bool state = fFileBuilder->StopWriteDataThread(); TThread::UnLock(); //unlock the main mutex if(state) { showevtimer->TurnOff(); DaqRunning = false; TThread::Lock(); //ShowText("OK! Write Data to File 'Thread' Stopped."); SetTextLocal("OK! Write Data to File 'Thread' Stopped."); ShowTextLocal(); //TTimer::SingleShot(msec_singleshot, Class_Name(), (void*)this, "ShowTextByTimer()"); TThread::UnLock(); return true; } return false; } if(comm == kC_FOPEN) { if(thispcaction == ONLINE_PC) { TThread::Lock(); //lock the main mutex //first: get the received File Header from TControl Online_PC TString getfheader = mascontrol.GetFileHeader(); cout << "Broad file header: " << getfheader.Data() << endl; //Second: set the File Header to FileBuilder fFileBuilder->SetBroadFHeader(getfheader.Data()); //Third: extract File Header fFileBuilder->ExtractFNameNumFromBHeader(); //Open Data File Dfilestate = fFileBuilder->OpenDataFile(); TThread::UnLock(); //unlock the main mutex } if(Dfilestate) { TString text; int rnum = fFileBuilder->GetCurrRunNum(); text += rnum; text += "run File Opened."; TThread::Lock(); //lock the main mutex //ShowText(text.Data()); SetTextLocal(text.Data()); ShowTextLocal(); //TTimer::SingleShot(msec_singleshot, Class_Name(), (void*)this, "ShowTextByTimer()"); flabFileStatus->SetText(text.Data()); TThread::UnLock(); //unlock the main mutex return true; } else { return false; } } if(comm == kC_FCLOSE) { bool state = fFileBuilder->CloseDataFile(); if(state) { Dfilestate = false; TString text; int rnum = fFileBuilder->GetCurrRunNum(); text += rnum; text += "run File Closed."; TThread::Lock(); //lock the main mutex //ShowText(text.Data()); SetTextLocal(text.Data()); ShowTextLocal(); //TTimer::SingleShot(msec_singleshot, Class_Name(), (void*)this, "ShowTextByTimer()"); flabFileStatus->SetText(text.Data()); TThread::UnLock(); //unlock the main mutex return true; } else { return false; } } return false; } void TMasterTask::ImB_OpenFile() { if(thispcaction==CONTROL_PC) { //first step build the FileHeader fFileBuilder->FormBroadFHeader(); //Second step set the FileHeader to TControl master for UDP broadcast TString broadfheader = fFileBuilder->GetBroadFHeader(); mascontrol.SetFileHeader(broadfheader.Data()); //implement OPEN File Command //// first: open the local data file, if open error, the command will not send out Dfilestate = fFileBuilder->OpenDataFile(); //Open Data file after FormBroadFHeader() ////send out the command bool status = false; if(Dfilestate) { status = mascontrol.send_TCPcontrol_command(sCommands[4]); if(status) { fBOpenF->SetEnabled(false); fBCloseF->SetEnabled(kTRUE); fBConExit->SetEnabled(false); //Close the File Before Exit fBDaqExit->SetEnabled(false); } } else { TString text = "File "; text += fFileBuilder->GetCurrFName(); text += " already exist."; TThread::Lock(); //lock the main mutex ShowText(text.Data()); TThread::UnLock(); //unlock the main mutex } } } void TMasterTask::ImB_CloseFile() { bool status = false; if(thispcaction==CONTROL_PC) { status = mascontrol.send_TCPcontrol_command(sCommands[5]); if(status) { TThread::Lock(); //lock the main mutex fBOpenF->SetEnabled(true); fBCloseF->SetEnabled(kFALSE); fBConExit->SetEnabled(true); fBDaqExit->SetEnabled(true); TThread::UnLock(); //unlock the main mutex } } } void TMasterTask::RecrateDFileAuto() { unsigned int filesize = fFileBuilder->CheckFileSize(); if(filesize>maxfilesize) { ImB_StopDaq(); sleep(WaitSec); //wait a little time ImB_CloseFile(); sleep(WaitSec); //wait a little time ImB_OpenFile(); sleep(WaitSec); //wait a little time ImB_StartDaq(); } } void TMasterTask::ShowTextLocal() { //ShowText(textmes.Data()); cout << textmes.Data() << endl; } void TMasterTask::SetTextLocal(const char *tex) { textmes.Clear(); textmes = tex; } <file_sep>/ribllvmedaq/TDataAnalyser.h //////////////////////////////////////////////////// // TDataAnalyser.h: Global data decoder, used for // data analysis. // <NAME> (08/2012) /////////////////////////////////////////////////// #ifndef TDataAnalyser_H #define TDataAnalyser_H #include <map> #include <vector> using namespace std; class TConfig; class TBoard; class TDataAnalyser { public: static map<int, TBoard *> CrateGeo_Mod; // <crate*100+Geo, pointer>, pointer = this module (TBoard*) vector<unsigned int> geotable; // pseudo crate_geo table: Crate*100 + Geo public: TDataAnalyser(TConfig *config); virtual ~TDataAnalyser(){}; unsigned int GlobalDecoder(unsigned int * &evtbuf, int num); unsigned int GlobalGeo(const unsigned int *const evtbuf); map<int, TBoard *> *GetCrateGeoMap() const {return &CrateGeo_Mod;} TBoard* GetTBoardPointer(const unsigned int crate, const unsigned int geo); void InitAllBoardData(); unsigned int GetRawData(const unsigned int Crate, const unsigned int Geo, const unsigned int channel); void evcheck(int necounter, int pointerid, TBoard * const mod); //do some check of the event counter of the model void evcheckprint(); //print some check errors }; #endif //#ifndef TDataAnalyser_H <file_sep>/ribllvmedaq/TUDPServerSocket.cpp //////////////////////////////////////////////// // TUDPServerSocket.cpp: // receive broadcasted data UDPSocket // receive data from ethernet // <NAME> 07/2012 test version v.01 //////////////////////////////////////////////// #include <iostream> #include <cstring> using namespace std; #include "TUDPServerSocket.h" #include <stdio.h> TUDPServerSocket::TUDPServerSocket(unsigned int port) { iport = port; OpenInitSocket(); //printf("TUDPServerSocket:: waiting for data on port UDP %u\n", iport); } unsigned int TUDPServerSocket::RecvRaw(char *buff, int max_len) { if(!IsValid()) return 0; int flags =0; #ifdef WIN32 int cliLen = sizeof(cliAddr); #else socklen_t cliLen = sizeof(cliAddr); #endif //#ifdef WIN32 int len = recvfrom(isocket, buff, max_len, flags, (struct sockaddr *)&cliAddr, &cliLen); if(len<0) len = 0; return len; } TUDPServerSocket::~TUDPServerSocket() { CloseCleanSocket(); } bool TUDPServerSocket::CloseCleanSocket() { int sta = 0; if(isocket) { #ifdef WIN32 sta = closesocket(isocket); WSACleanup(); isocket = 0; #else sta = close(isocket); isocket = 0; #endif //#ifdef WIN32 if(sta == 0) return true; else return false; } } bool TUDPServerSocket::OpenInitSocket() { //iport = port; int rc = 0, sset =0; int opt = 1; isocket = -1; #ifdef _WIN32 WSADATA wsaData = {0}; int iResult = 0; /* Initialize Winsock */ iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { wprintf(L"WSAStartup failed: %d\n", iResult); return 0; } /* socket creation */ isocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); #else /* socket creation */ isocket = socket(AF_INET, SOCK_DGRAM, 0); #endif if (isocket<0) { printf("TUDPServerSocket: cannot open socket \n"); isocket = 0; } /* bind local server port */ servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(iport); if(isocket) { sset = setsockopt(isocket,SOL_SOCKET,SO_REUSEADDR,(const char*)&opt,sizeof(opt)); if(sset != 0) { printf("TUDPServerSocket: Set socket option 'SO_REUSEADDR' error on port %d \n", iport); } rc = bind (isocket, (struct sockaddr *) &servAddr, sizeof(servAddr)); if (rc<0) { printf("TUDPServerSocket: cannot bind port number %d \n", iport); } } else { isocket =0; } if(isocket) return true; return false; } bool TUDPServerSocket::SetRcvTimeOutValue(unsigned int millisec) { if( !IsValid() ) return false; int sta = -1; int msec = millisec; unsigned int sec = (unsigned int)millisec/1000; unsigned int usec = (millisec%1000) * 1000; struct timeval tv_out; tv_out.tv_sec = sec; tv_out.tv_usec = usec; #ifdef _WIN32 sta = setsockopt(isocket,SOL_SOCKET,SO_RCVTIMEO,(char *)&msec, sizeof(msec)); #else sta = setsockopt(isocket,SOL_SOCKET,SO_RCVTIMEO,&tv_out, sizeof(tv_out)); #endif if(sta == 0 ) return true; return false; } bool TUDPServerSocket::JoinMemberShip(const char *MC_IP) { if( !IsValid() ) return false; ip_mreq mreq; memset(&mreq, 0, sizeof(mreq)); #ifdef WIN32 mreq.imr_interface.S_un.S_addr = INADDR_ANY; mreq.imr_multiaddr.S_un.S_addr = inet_addr(MC_IP); #else mreq.imr_interface.s_addr = INADDR_ANY; mreq.imr_multiaddr.s_addr = inet_addr(MC_IP); #endif //#ifdef WIN32 int ret = setsockopt(isocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq)); if( ret != 0 ) { cout<<"TUDPCLientSocket>> Error in setsockopt(IP_ADD_MEMBERSHIP). "<<endl; return false; } return true; } <file_sep>/ribllvmedaq/TDAQApplication.h //////////////////////////////////////////////////////// // This class implements a // server readout Application environment // to manage command line options, directory files, etc. // This class must be instantiated exactly once in one // daq server application. Credits: root.cern.ch // E.d.F (c) 3/2008 v. 012 rev. 4/2008 // Chimera Acquisition // ver 0.2 : added "localhost" environment for singal PC // by <NAME> (2013.06.16) ///////////////////////////////////////////////////////// #ifndef TDAQAPPLICATION_H #define TDAQAPPLICATION_H #include <string> using namespace std; #include "caenacq.h" const string gMULTICAST = "172.16.17.32"; //multicast UDP address (def.) //const string gConfPath = "DAQCONFPATH"; //environment file PATH for setup files class TDAQApplication { private: int fargc; //Number of command line arguments char **fargv; //Command line arguments bool fmaster; //This application is the DAQ master (default=true) string fcomm; //Communication mode (unicast,multicast,broadcast) string fmaddr; //Multicast address (default=gMULTICAST=255.0.0.1) string fpathname; //The environment variable ACQConfPATH (if defined) string fserverip; //server ip, or "localhost" public: TDAQApplication(int argc, char **argv, bool ismaster=true); ~TDAQApplication(); void GetOptions(int, char **); void Usage(char *); int Argc() {return fargc;} char **Argv() {return fargv;} char *Argv(int i) {return fargv ? fargv[i] : 0; } string GetComm() {return fcomm;} void SetMulticastAddress(string addr=gMULTICAST) {fmaddr=addr;} string GetMulticastAddress() {return fmaddr;} void Version(); string Get_PathEnvdir() {return fpathname;} bool Get_ServerIP(string &sip); bool IsMaster() {return fmaster;} }; extern TDAQApplication *gDAQApplication; #endif <file_sep>/ribllvmedaq/TCBLT.h ///////////////////////////////////////////////////////////// // TReadout interface // Readout modes for the VME bridge // The TReadout defines the three basic modes // for data readout with a VME bridge interface: // # the BLT (block transfer readout) // # the CBLT (chained block transfer readout) // # Hibrid (CBLT + BLT) readout // # facilities and wrappers for single channel access. // The class defines // the readout basic implementation independently // from the VME configuration that is managed by other // classes. // E.d.F. (08/2007) prototype test version (CBLT only) // (Modified by Hanjianlong 07/2012) //////////////////////////////////////////////////////////// #ifndef TCBLT_H #define TCBLT_H #include "caenacq.h" #include <new> class TReadout { protected: char *fiobuf; //buffer for blt or cblt readout unsigned int fusedsize; //used size in byte unsigned int fbufdim; //dimension of 'fiobuf' public: TReadout(int dim=VME_Crate_BufLENGTH); virtual ~TReadout(); char *GetBLTBuff() {return fiobuf;} unsigned int GetUsedSizeByte() const {return fusedsize;} unsigned int GetBufDimension() const {return fbufdim;} void SetUsedSizeByte(unsigned int nbyte) {fusedsize = nbyte;} void swap32(unsigned int *buf, int max){}; }; //The CBLT class manages the chained block transfer //readout for one or more codifiers chains. The class //mandatory defines a copy constructor and assignment //operator=() definition class TCBLT : public TReadout { private: int fchains; //CBLT chains number int *fnum; //pointer to board number for each chain int *fbase; //pointer to base address for each chain int *fdummy; //pointer to dummy address for each chain int foffset; //offset respect to the first codifier for polling (use for not first board DRDY) int fwait_for_ready; //number of boards to lookup before readout public: TCBLT(int bufsize=VME_Crate_BufLENGTH, int wait=1): TReadout(bufsize), fchains(0), fnum(0), fbase(0), fdummy(0), foffset(0), fwait_for_ready(wait) {} TCBLT(TCBLT const &); //copy constructor TCBLT &operator=(TCBLT const &); //assignement operator virtual ~TCBLT(); int Get_CBLT_Config(string name, int crate); int GetChains() {return fchains;} int *GetNum() {return fnum;} int *GetDummyAddr() {return fdummy;} int GetWait() {return fwait_for_ready;} int GetChainBoard(int chain); void SetOffsetPolling(int off) {foffset=off;} int GetOffsetPolling() {return foffset;} void PrintCBLTInfo(); }; #endif <file_sep>/ribllvmedaq/TOnline.cpp ///////////////////////////////////////////////////////// // File name: Online.cpp // // Brief introduction: // // Online program of RIBLL1-DAQ // // // // Version: V1.0 // // Author: <NAME> // // Date: Nov. 2010 // // For: RIBLL1 // ///////////////////////////////////////////////////////// #include "TApplication.h" #include "TROOT.h" #include "TSystem.h" #include "TGClient.h" #include "TGWindow.h" #include "TGButton.h" #include "TGListView.h" #include "TVirtualPadEditor.h" #include "GuiTypes.h" #include "TGFSContainer.h" #include "WidgetMessageTypes.h" #include "TFile.h" #include "TH1.h" #include "TH2.h" #include "TTree.h" #include "TThread.h" #include "TRint.h" #include "TOnlineFrame.h" #include "TOnline.h" #include "TDataReceiver.h" #include "TDataAnalyser.h" #include "TBoard.h" #ifndef WIN32 #include <sys/ipc.h> #include <sys/shm.h> #include <sys/msg.h> #include <sys/types.h> #endif //#ifndef WIN32 #ifdef WIN32 #include <windows.h> #define sleep Sleep #define WaitSec 600 #else #include <unistd.h> #define sleep usleep #define WaitSec 800000 #endif #include <iostream> #include <map> #include <typeinfo> using namespace std; extern void OnlineUserFunction(TOnlineFrame *onl); extern void UserTH_Init(); extern void UserTH_Fill(); TDataReceiver *TOnline::datarec=0; TDataAnalyser *TOnline::anadata=0; TTree *TOnlineFrame::tree=0; TOnline *gOnline=0; bool TOnline::setonline=false; TOnline::TOnline(const TGWindow *p, UInt_t w, UInt_t h, TDataAnalyser *dana): TOnlineFrame(p, w, h) { if(gOnline) { cout << "TOnline>> only one 'TOnline' object allowed." << endl; return; } gOnline = this; //open datafile first datafile = new TFile("Ronline.root", "RECREATE"); if(!dana) return; anadata = dana; datarec = new TDataReceiver(UDPDataBroadPortMon); UserTH_Init(); //create user defined histograms CreateTH1I(); //create all 1d histogram of each module CreateTree(); //create tree ObjList = datafile->GetList(); objcurr = ObjList->First(); fFileCont->AddFile(datafile->GetName()); fFileCont->Resize(); setonline = true; OnlineThread = 0; fBoffline->SetEnabled(false); MakeTH1MenuList(); RemoveMenuEntry("Delete", THmlist); RemoveMenuEntry("Dump", THmlist); RemoveMenuEntry("SetName", THmlist); RemoveMenuEntry("SetMaximum", THmlist); RemoveMenuEntry("SetMinimum", THmlist); RemoveMenuEntry("ShowBackground", THmlist); MakeTH2MenuList(); RemoveMenuEntry("Delete", TH2mlist); RemoveMenuEntry("Dump", TH2mlist); RemoveMenuEntry("SetName", TH2mlist); RemoveMenuEntry("SetMaximum", TH2mlist); RemoveMenuEntry("SetMinimum", TH2mlist); RemoveMenuEntry("ShowBackground", TH2mlist); OnlineUserFunction(gOnlineFrame); } bool TOnline::ProcessMessage(Long_t msg, Long_t param1, Long_t) { switch (GET_MSG(msg)) { case kC_COMMAND: switch(GET_SUBMSG(msg)) { case kCM_BUTTON: switch (param1) { case kB_online: StartOnline();//SetOnline(); break; case kB_offline: SetOffline(); break; case kB_exit: CloseWindow(); break; case kB_resetall: ImB_ResetAllTH(); OnlineUserFunction(gOnlineFrame); break; case kB_resetcurr: ImB_ResetCurrTH(); OnlineUserFunction(gOnlineFrame); break; case kB_integral: ImB_integral(); break; case kB_privious: ImB_previous(); break; case kB_next: ImB_next(); break; case kB_update: ImB_update(); break; default: break; } break; } break; case kC_CONTAINER: switch(GET_SUBMSG(msg)) { case kCT_ITEMDBLCLICK: if (param1==kButton1) OnDoubleClick((TGLVEntry *)fFileCont->GetLastActive(), param1); break; default: break; } break; default: break; } return true; } TOnline::~TOnline() { //setonline = false; datafile->Close(); SafeDeleteP(datafile); if (TVirtualPadEditor::GetPadEditor(kFALSE) != 0) TVirtualPadEditor::Terminate(); } void TOnline::SetOffline() { setonline = false; sleep(WaitSec); if(OnlineThread) { TThread::Delete(OnlineThread); delete OnlineThread; OnlineThread = 0; TThread::Lock(); //lock the main mutex ShowText("Set Offline Success."); fBonline->SetEnabled(true); fBoffline->SetEnabled(false); TThread::UnLock(); //unlock the main mutex } } int TOnline::StartOnline() { if(!OnlineThread) { setonline = true; OnlineThread = new TThread("MonOnlineThread",(void(*)(void *))(&TOnline::SetOnline), (void*)this); OnlineThread->Run(); TThread::Lock(); //lock the main mutex ShowText("Online thread started."); fBonline->SetEnabled(false); fBoffline->SetEnabled(true); TThread::UnLock(); //unlock the main mutex return 1; } return 0; } void TOnline::SetOnline(void *arg) { unsigned int recbyte = 0; unsigned int *sentinel = datarec->GetDataBuf(); while(Getsetonline()) { recbyte = datarec->ReceiveData(); unsigned int *datap = datarec->GetDataBuf(); do { datap++; //skip the EVENT_HEADER int evtc = anadata->GlobalDecoder(datap, recbyte/sizeof(int)); if(evtc>0) { UserTH_Fill(); tree->Fill(); } }while(datap<(sentinel+recbyte)); } } void TOnline::CreateTH1I() { map<int, TBoard*> *CrateGeoMap = anadata->GetCrateGeoMap(); map<int, TBoard*>::const_iterator it=CrateGeoMap->begin(); for(it; it!=CrateGeoMap->end(); it++) { (*it).second->Create1DHistos(); } } void TOnline::CreateTree() { tree = new TTree("RawData", "ModuleData"); tree->SetCircular(10000); map<int, TBoard*> *CrateGeoMap = anadata->GetCrateGeoMap(); map<int, TBoard*>::const_iterator it=CrateGeoMap->begin(); for(it; it!=CrateGeoMap->end(); it++) { if( (*it).second->GetTreeSwitch() ) { TString tname = (*it).second->Class_Name();//typeid(*((*it).second)).name(); tname += (*it).first; tree->Branch(tname.Data(), (*it).second->Class_Name(), (*it).second); } } } int GetRawData(int Crate, int Geo, int channel) { if(!gOnline) return 0; int CGid = Crate*100 + Geo; int value = 0; TThread::Lock(); //lock the main mutex TDataAnalyser *dataana = gOnline->GetDataAnalyser(); TBoard *mod = dataana->GetTBoardPointer(Crate, Geo); if(mod) { value = mod->GetChannelData(channel); } TThread::UnLock(); //unlock the main mutex return value; } #if !defined(__CINT__) && !defined(__MAKECINT__) //int main(int argc, char *argv[]) //{ // TRint apponline("Online", &argc, argv); // // The Server DAQ Application defining general environment // TDAQApplication ribll(argc, argv, IsMaster); // //where the cblt setup files are // string pathchain = ribll.Get_PathEnvdir() + "/cblt_addr_c"; // //where the filenameqdc and codifier setup file are // string pathfilename = ribll.Get_PathEnvdir() + "/filenamemod.dat"; // // TConfig conf = TConfig(pathfilename.c_str()); // TDataAnalyser anadata = TDataAnalyser(&conf); // // TOnline *onl = new TOnline(gClient->GetRoot(), 100, 200, &anadata); // // // apponline.Run(); // return 0; // //// //TApplication apponline("Online", &argc, argv); //// TRint apponline("Online", &argc, argv); //// //// TOnline *onl = new TOnline(gClient->GetRoot(), 100, 200); //// //// apponline.Run(); //// //// return 0; //} #endif// #if !defined(__CINT__) && !defined(__MAKECINT__) <file_sep>/ribllvmedaq/TDataFileBuilder.cpp ////////////////////////////////////////////////// // TDataFileBuilder.cpp: Data file manager, open // close, write data file. // <NAME> (08/2012) ///////////////////////////////////////////////// #include "TDataFileBuilder.h" #include "stdlib.h" #include <iostream> #include <fstream> #include <string> using namespace std; #ifdef WIN32 #include <io.h> #include <windows.h> #define sleep Sleep #define WaitSec 500 #else #include <unistd.h> #define sleep usleep #define WaitSec 600000 #endif #ifndef WIN32 #define _access access #endif #include "caenacq.h" #include "TThread.h" #include "TString.h" #include "TThread.h" #include "TControl.h" //unsigned int TDataFileBuilder::RunNum = 0; ofstream* TDataFileBuilder::datafile = 0; unsigned int TDataFileBuilder::MaxFileSize = 500; //Mb TDataFileBuilder *gDataFileBuilder = 0; TDataFileBuilder::TDataFileBuilder():TDataReceiver(UDPDataBroadPortCon) { if(gDataFileBuilder) { cout << "Only one instance of 'TDataFileBuilder' permitted." << endl; return; } gDataFileBuilder=this; filename = "RawData"; RunNum = 0; CurrRunNum = RunNum; thread_writedata = 0; fileDir =getenv( gDataPath.c_str() ); void* status = gSystem->OpenDirectory(fileDir.Data()); //check if 'fileDir' exist or not, if not fileDir=pwd if(status == 0) { fileDir.Clear(); } else { gSystem->FreeDirectory(status); } CurrFName = filename; CurrFName += '.'; CurrFName += RunNum; } //Form the fileheader used for UDP broadcast, //this header begin with filename.runnum void TDataFileBuilder::FormBroadFHeader() { if( broadfileheader.Length()>0 ) broadfileheader.Clear(); TString rnum = TString::Format("%04u", RunNum); //format the runnum->0001-9999 broadfileheader = filename; broadfileheader += '.'; broadfileheader += rnum; broadfileheader += "#"; //separate the filenmae and file header broadfileheader += fileheader; cout <<"BroadFile Header: " << broadfileheader.Data() << endl; } //Extract the file name and run number form the braodcasted(received) fileheader bool TDataFileBuilder::ExtractFNameNumFromBHeader() { if( broadfileheader.Length()==0 ) return false; unsigned int pos = broadfileheader.First("#"); TString tfile = broadfileheader(0, pos); pos = tfile.First('.'); filename = tfile(0, pos); TString rnum = tfile(pos+1, 4); RunNum = rnum.Atoi(); //cout << filename.Data() << "." << rnum.Data() << endl; return true; } bool TDataFileBuilder::OpenDataFile() { if(datafile) { bool bclose = CloseDataFile(); if(bclose) cout << "Current datafile: " << CurrFName << " closed." << endl; } if( filename.Length() == 0 ) return false; TString tfilename; TString rnum = TString::Format("%04u", RunNum); TString fname = fileDir; fname += '/'; fname += filename; fname += '.'; fname += rnum; CurrFName = filename; CurrFName += '.'; CurrFName += rnum; if( _access(fname.Data(), 0) != -1 ) //for file already exist { cout << " TDataFileBuilder>>File: " << fname << " already exist." << endl; return false; } try { datafile = new ofstream(fname.Data(), ios_base::binary); } catch (bad_alloc &ex) { cout << "Open Data File Error: " << ex.what() << endl; } if( (!datafile) || (!datafile->good()) ) return false; CurrRunNum = RunNum; //memory the current running file RunNum RunNum += 1; datafile->write(broadfileheader.Data(), FileHeaderLEN); //write the file header to datafile gSystem->Beep(10, 1000); return true; } bool TDataFileBuilder::CloseDataFile() { bool state = false; TThread::Lock(); //Lock(), in case the thread "ReceiveDataToFile(void* arg)" is writing the file if(datafile) { int endv = Event_Header; //add the 'Event_Header' to the last 4byte of the file (*datafile)<<endv; datafile->close(); delete datafile; datafile = 0; state = true; gSystem->Beep(10, 1000); } TThread::UnLock(); return state; } bool TDataFileBuilder::CloseDataFileManual() { //StopWriteDataThread(); return CloseDataFile(); } void* TDataFileBuilder::ReceiveDataToFile(void* arg) { if( !IsUDPValid() ) return 0; TDataFileBuilder *thisp = (TDataFileBuilder*)arg; int nbyte = 0; do { nbyte = ReceiveData(); eventcounter = fdatabuf[1]; //fdatabuf[1]:the first 'Event Count' of this block //cout << "nbyte: " << nbyte << endl; if( IsDataFileValid() && nbyte >0) { datafile->write( (char*)fdatabuf, nbyte ); } }while(!CheckStop()); cout << "Exit form receivedata socket. " << endl; return 0; } bool TDataFileBuilder::IsDataFileValid() { bool valid = false; TThread::Lock(); if(datafile) valid = datafile->good(); TThread::UnLock(); return valid; } bool TDataFileBuilder::CheckStop() { TThread::Lock(); bool check = (TControl::comm == kC_STOP); TThread::UnLock(); if(check) { return true; } return false; } bool TDataFileBuilder::StartWriteDataThread() { if(!thread_writedata) { //if( !IsUDPValid() ) OpenRecDataSocket(); thread_writedata = new TThread("WriteData", (void*(*)(void*))(&TDataFileBuilder::ReceiveDataToFile), (void*)this); if(thread_writedata) { thread_writedata->Run(); cout << thread_writedata->GetName() << " is running..." << endl; return (thread_writedata->GetState() == TThread::kRunningState); } else { thread_writedata = 0; return false; } } else { thread_writedata->Run(); return true; } } bool TDataFileBuilder::StopWriteDataThread() { sleep(WaitSec); //in case 'start' 'stop' very fastly. if(thread_writedata) { string thname = thread_writedata->GetName(); //if( IsUDPValid() ) cout << "Close socket: " << CloseRecDataSocket() << endl; //close the socket TThread::Delete(thread_writedata); delete thread_writedata; thread_writedata = 0; //cout << thname << " stopped. " << endl; return true; } return true; } unsigned int TDataFileBuilder::CheckFileSize() //Mb { if(IsDataFileValid()) { TThread::Lock(); long size_byte = datafile->tellp(); TThread::UnLock(); return (unsigned int)size_byte/10E5; } return 0; } bool TDataFileBuilder::ReCreateFileAuto() { CloseDataFile(); return OpenDataFile(); } <file_sep>/ribllvmedaq/xiaohai.cpp #include "TApplication.h" #include "TDAQApplication.h" #include "TConfig.h" #include "TDataFileReader.h" #include "TDataAnalyser.h" #include "TString.h" #include "TFile.h" #include "TTree.h" #include "TH1F.h" #include "TH2F.h" #include "TSystem.h" #include "TMath.h" #include "TVector3.h" #include "TROOT.h" #include "TApplication.h" #include "TFile.h" #include "TH1.h" #include "TH2.h" #include "TF1.h" #include "TFormula.h" #include "TProfile.h" #include "TNtuple.h" #include "TRandom.h" #include "TApplication.h" #include "TCanvas.h" #include "TDirectory.h" #include "TStyle.h" #include "TText.h" #include "TLatex.h" #include "TLine.h" #include "TPad.h" #include "TObjArray.h" #include "TTree.h" #include "TBranch.h" #include "TStopwatch.h" #include "TGraph.h" #include "TGraphErrors.h" #include "TLegend.h" #include "TFrame.h" #include "TF1.h" #include "TMinuit.h" #include "TBoard.h" #include "TModV830AC.h" #include "TModV785.h" #include "TModV785N.h" #include "TModV775.h" #include "TModV775N.h" #include "TModV792.h" #include <iostream> #include <sstream> #include <fstream> #include <stdlib.h> #include <vector> #include <map> #include<cstdlib> using namespace std; TH2D *testhis = new TH2D("testhis", "testhis", 200, 0, 4000, 200, 0, 4000); int main(int argc,char **argv) { TFile *file = new TFile("../2016gdr0524.root"); TTree *fChain = (TTree*)file->Get("RawData;4");//fChain can be a TChain Int_t nentries; nentries=(Int_t)fChain->GetEntries(); cout<<"All the entry number: "<<nentries<<endl; TBranch *bran103 = 0; TBranch *bran104 = 0; TBranch *bran106 = 0; TBranch *bran108 = 0; TBranch *bran110 = 0; TBranch *bran112 = 0; TBranch *bran114 = 0; TBranch *bran116 = 0; TBranch *bran118 = 0; TBranch *bran120 = 0; TModV830AC *vmod103 = new TModV830AC(); // TModV785 *vmod104 = new TModV785(); //Si1 60um TModV785 *vmod106 = new TModV785(); //Si2 60um TModV785 *vmod108 = new TModV785(); //Si4 100um TModV785 *vmod110 = new TModV785(); //QSD 300um TModV785 *vmod112 = new TModV785(); // TModV785N *vmod114 = new TModV785N(); TModV775N *vmod116 = new TModV775N(); TModV775 *vmod118 = new TModV775(); TModV775 *vmod120 = new TModV775(); fChain->SetBranchAddress("Mod103_TModV830AC",&vmod103,&bran103); fChain->SetBranchAddress("Mod104_TModV785",&vmod104,&bran104); fChain->SetBranchAddress("Mod106_TModV785",&vmod106,&bran106); fChain->SetBranchAddress("Mod108_TModV785",&vmod108,&bran108); fChain->SetBranchAddress("Mod110_TModV785",&vmod110,&bran110); fChain->SetBranchAddress("Mod112_TModV785",&vmod112,&bran112); fChain->SetBranchAddress("Mod114_TModV785N",&vmod114,&bran114); fChain->SetBranchAddress("Mod116_TModV775N",&vmod116,&bran116); fChain->SetBranchAddress("Mod118_TModV775",&vmod118,&bran118); fChain->SetBranchAddress("Mod120_TModV775",&vmod120,&bran120); Long64_t nbytes = 0, nb = 0; for (Long64_t jentry=0; jentry<nentries;jentry++) { Long64_t ientry = fChain->LoadTree(jentry); if (ientry < 0) break; nb = fChain->GetEntry(jentry); nbytes += nb; for (int i = 0; i != vmod104->MaxChannel; ++i) { } } TFile *saveFile = new TFile("saveFile.root", "RECREATE"); testhis->Write(); saveFile->Write(); return 0; } <file_sep>/ribllvmedaq/MonOnline.cpp /////////////////////////////////////////////// // MonOnline.cpp: main() of MonOnline, used // for online Monitoring, show histograms and // trees(if defined) // <NAME> (08/2012) /////////////////////////////////////////////// #include "TApplication.h" #include "TRint.h" #include "TDAQApplication.h" #include "TOnline.h" #include "TConfig.h" #include "TDataAnalyser.h" int main(int argc, char *argv[]) { TRint apponline("Online", &argc, argv); // The Server DAQ Application defining general environment TDAQApplication ribll(argc, argv, false); //where the cblt setup files are string pathchain = ribll.Get_PathEnvdir() + "/cblt_addr_crate"; //where the filenameqdc and codifier setup file are string pathfilename = ribll.Get_PathEnvdir() + "/filenamemod.dat"; TConfig conf(pathfilename.c_str()); TDataAnalyser anadata = TDataAnalyser(&conf); TOnline *onl = new TOnline(gClient->GetRoot(), 100, 200, &anadata); apponline.Run(); return 0; }<file_sep>/ribllvmedaq/TMasterTask.h ///////////////////////////////////////////////////////// // File name: TMasterTask.h // // Brief introduction: // // Master PC task: Control daq, get data form // // UDP broadcast, save data to file ... // // Version: V1.0 // // Author: <NAME> // // Date: Aug. 2012 // // For: RIBLL1 // ///////////////////////////////////////////////////////// #ifndef TMasterTask_H #define TMasterTask_H #include "TControlFrame.h" #ifndef TControl_H #include "TControl.h" #endif #include "Rtypes.h" #include <RQ_OBJECT.h> #include "TQObject.h" #include "TString.h" class TDataFileBuilder; class TThread; class TTimer; class TControl; class TMasterTask: public TControlFrame { //RQ_OBJECT("TMasterTask"); protected: TDataFileBuilder *fFileBuilder; //! TControl &mascontrol; //! eAction thispcaction; //! static TTimer *showevtimer; //! static TTimer *showconnect; //! static TTimer *checkdfsize; //!used to check the data file size, and recreate data file automaticly //TThread *thshowevt; //! TThread *thtcpaccept; //! static bool TCPConnState; //! static bool TCPAcceptReturned; //! bool Dfilestate; //!data file opened or not bool DaqRunning; //!daq is running or not unsigned int maxfilesize; //!max file size form fFileBuilder TString textmes; //!message text to be showed on TGTextView public: TMasterTask(TControl &netcon); virtual ~TMasterTask(); virtual bool ProcessMessage(Long_t msg, Long_t param1, Long_t); TControl& GetControlMas(){return mascontrol;} void ShowMessageSignal(); void CoutBroadMessageSignal(); void ShowEventNumByTimer(); static void* ConnecttoDAQPC(void *arg); void ImB_SetFileName(); void ImB_SetFileRun(); void ImB_SetFileHeader(); void ImB_StartDaq(); void ImB_StartOnlineDaq(); void ImB_StopDaq(); void ImB_InitDaq(); void ImB_OpenFile(); void ImB_CloseFile(); bool ImB_Connect(); void ImB_TestComm(); void ImB_ExitDaqpc(); void ProcessTCPConnectedTimer(); void InitButt(); void SetEnableAllButt(bool act); void DiableStopButt() {DisableButt(fBStop);} void DiableCloseButt(){DisableButt(fBCloseF);} void SetOnlinePCButt(); bool ProcessControlSignal(int comm); void RecrateDFileAuto(); void ShowTextLocal(); //Timer::SingleShot() slot to show text void SetTextLocal(const char* tex); protected: //TMasterTask(TMasterTask const &source){}; ClassDef(TMasterTask, 1); }; extern TMasterTask *gMasterTask; #endif //#ifndef TMasterTask_H<file_sep>/ribllvmedaq/OnlineUserFunc.cpp //////////////////////////////////////////////// // Some Userdefined functions used for // Online program. // <NAME> (08/2012) //////////////////////////////////////////////// #include <iostream> using namespace std; #include "TROOT.h" #include "TH1.h" #include "TH1F.h" #include "TH2F.h" #include "TFile.h" #include "TF1.h" #include "TList.h" #include "TOnlineFrame.h" #include "TOnline.h" void def_TH1F(int hid, const char *hname, int bins, float xmin, float xmax); void hfill1(int hid, float value, float weight); void def_TH2F(int hid, const char *hname, int xbins, float xmin, float xmax, int ybins, float ymin, float ymax); void hfill2(int hid, float x, float y, float weight); extern int GetRawData(int Crate, int Geo, int channel); extern void HBOOK1(int id, const char *title, int nxbin, float xlow, float xup, float vmx); extern void HBOOK2(int id, const char *title, int nxbin, float xlow, float xup, int nybin, float ylow, float yup, float vmx); extern void HF1(int id, float x, float weight); extern void HF2(int id, float x, float y, float weight); extern bool HEXIST(int ihist); void UserTH_Init() { //For safety, use only 'def_TH1F()' and 'def_TH2F()' in this function def_TH1F(1001, "T2-T1", 250, -50, 350.); def_TH1F(1002, "tofcal", 400, 0., 400.); def_TH1F(1003, "dE", 4000, 0.5, 4000.5); def_TH1F(1004, "dEcal", 200, 0.5, 80.5); def_TH2F(1005, "Tof-dE", 250, 50., 400.,300, 0, 4096.); def_TH2F(1006, "Tofcal_dEcal", 120, 160, 240, 180, 0, 90); def_TH2F(2001, "Tofcal-dsi1cal-cut",100,169,184,50,2,5);//added by shicz def_TH2F(2003, "Tofcal-dsi1cal",200,150,250,100,10,50);//added by shicz def_TH1F(2004, "dsi1",200, 10, 3500.);//added by wangyuting def_TH2F(2005, "Tof-dsi1", 150, 0, 150., 500, 500, 3000.);//added by wangyuting def_TH2F(2006, "si1_posi", 16, 0, 16., 16, 0, 16.);//added by wangyuting def_TH2F(2007, "si2_posi", 16, 0, 16., 16, 0, 16.);//added by wangyuting def_TH2F(2008, "si4_posi", 16, 0, 16., 16, 0, 16.);//added by wangyuting def_TH2F(2009,"si3_si2",406,0,4096,406,0,4096);//added by wangyuting def_TH2F(2010,"si4_si3",406,0,4096,406,0,4096);//added by wangyuting } void UserTH_Fill() { //GetRawData(Crate, Geo, channel), channel:[0, ..] int T1 = GetRawData(1, 16, 0); int T2 = GetRawData(1, 16, 1); //*******added by wangyuting**************************** int si1[32]; for(int i=0;i<32;i++) { si1[i]=GetRawData(1,4,i); } int si4[32]; for(int i=0;i<32;i++) { si4[i]=GetRawData(1,8,i); } int si3[4]; for(int i=0;i<4;i++) { si3[i]=GetRawData(1,10,i); } int si2[32]; for(int i=0;i<16;i++) { si2[i]=GetRawData(1,6,i); if(i<8) { si2[i+16]=GetRawData(1,6,23-i); } else { si2[i+16]=GetRawData(1,6,39-i); } } //*******added by wangyuting************************* //**************************added by wangyuting************************************ int si1_p_max=si1[0],si1_p_max_index=0, si1_n_max=si1[0],si1_n_max_index=0; for(int i=0;i<16;i++) { if(si1[i]>si1_p_max) { si1_p_max=si1[i]; si1_p_max_index=i; } if(si1[i+16]>si1_n_max) { si1_n_max=si1[i+16]; si1_n_max_index=i; } } int si4_p_max=si4[0],si4_p_max_index=0, si4_n_max=si4[0],si4_n_max_index=0; for(int i=0;i<16;i++) { if(si4[i]>si4_p_max) { si4_p_max=si4[i]; si4_p_max_index=i; } if(si4[i+16]>si4_n_max) { si4_n_max=si4[i+16]; si4_n_max_index=i; } } int si2_p_max=si2[0],si2_p_max_index=0, si2_n_max=si2[0],si2_n_max_index=0; for(int i=0;i<16;i++) { if(si2[i]>si2_p_max) { si2_p_max=si2[i]; si2_p_max_index=i; } if(si2[i+16]>si2_n_max) { si2_n_max=si2[i+16]; si2_n_max_index=i; } } int si3_max=si3[0],si3_max_index=0; for(int i=0;i<4;i++) { if(si3[i]>si3_max) { si3_max=si3[i]; si3_max_index=i; } } //************************end added by wangyuting******************************* int t21 = T2-T1; hfill1(1001, t21, 1); float tofcal = (T2-T1)*0.30702 + 157.124; hfill1(1002, tofcal, 1); int de = GetRawData(1, 14, 0); hfill1(1003, de, 1); float decal = de*0.02878 -1.59115; hfill1(1004, decal, 1); hfill2(1005, t21, de, 1); //*******added by wangyuting*********************** float si1shicz; si1shicz=si1_p_max*0.01107*1.4-0.68859-0.51; if(tofcal>169&&tofcal<184&&si1shicz>2&&si1shicz<5) hfill2(2001,tofcal,si1shicz,1);//added by shicz if(t21>0&&si1_p_max>100) hfill2(2003,tofcal,si1_p_max*0.01107*1.4-0.68859-0.51,1);//added by shicz hfill1(2004,si1_p_max,1); hfill2(2005,t21,si1_p_max,1); // if(t21>72.36&&t21<84.08&&si1_p_max>1589.14&&si1_p_max<1992.53&&si1_n_max>250) if(si1_p_max>250&&si1_n_max>250) { hfill2(2006,si1_p_max_index,si1_n_max_index,1); } // if(t21>72.36&&t21<84.08&&si1_p_max>1589.14&&si1_p_max<1992.53&&si2_p_max>250&&si2_n_max>250) if(si2_p_max>100&&si2_n_max>100) { hfill2(2007,15-si2_n_max_index,si2_p_max_index,1); } // if(t21>72.36&&t21<84.08&&si1_p_max>1589.14&&si1_p_max<1992.53&&si4_n_max>250) if(si4_p_max>100&&si4_n_max>100) { hfill2(2008,si4_p_max_index,si4_n_max_index,1); } if(si3_max>250&&si2_p_max>250) { hfill2(2009,si3_max,si2_p_max,1); } if(si4_p_max>250&&si3_max>250) { hfill2(2010,si4_p_max,si3_max,1); } //*********ended by wangyuting*********************** hfill2(1006, tofcal, decal, 1); } void OnlineUserFunction(TOnlineFrame *onl) { //TF1 *func1 = new TF1("func1","sqrt(-x*x-10*x)-5" , -10, 0); //TF1 *func2 = new TF1("func1","-sqrt(-x*x-10*x)-5", -10, 0); //if(onl->datafile->Get("h272") ) //{ // TList *thfunclist = ( (TH1*)(onl->datafile->Get("h272") ) )->GetListOfFunctions(); // if(thfunclist) // { // thfunclist->Add(func1); // thfunclist->Add(func2); // } //} } //capsulize of 'TH1F()', for safety void def_TH1F(int hid, const char *hname, int bins, float xmin, float xmax) { if( HEXIST(hid) ) { cout << "Histogram ID: " << hid << " (mod_id*100+ch_num) already exist." << endl; return; } else { char name[30]; strncpy(name, hname, sizeof(name)); HBOOK1(hid, name, bins, xmin, xmax, 0.); } } //capsulize of 'TH2F()', for safety void def_TH2F(int hid, const char *hname, int xbins, float xmin, float xmax, int ybins, float ymin, float ymax) { if( HEXIST(hid) ) { cout << "Histogram ID: " << hid << " (mod_id*100+ch_num) already exist. " << endl; return; } else { char name[30]; strncpy(name, hname, sizeof(name)); HBOOK2(hid, name, xbins, xmin, xmax, ybins, ymin, ymax, 0.); } } //capsulize of 'TH1F::Fill(....)', for safety void hfill1(int hid, float value, float weight=1.) { if(HEXIST(hid)) HF1(hid, value, weight); } //capsulize of 'TH2F::Fill(....)', for safety void hfill2(int hid, float x, float y, float weight = 1.) { if(HEXIST(hid)) HF2(hid, x, y, weight); } <file_sep>/ribllvmedaq/TCrateCBLT.h //////////////////////////////////////////////////////// // TCrateCBLT.h include file interfaces // These classes defined(combination) the CBLTs // in a VME crate // E.d.F (08/2007) test version v.07 // caen lib wrapper not yet implemented // Modified by Hanjianlong 07/2012 /////////////////////////////////////////////////////// #ifndef TCrateCBLT_H #define TCrateCBLT_H #include <string> using namespace std; #include "TVMELink.h" #include "TCBLT.h" #include "TString.h" class TCrateCBLT : public TVMELink { private: TCBLT freadout; int findex; bool fenabled; //enabled for readout (true) or disabled (false) int fwait_for_ready; //number of crates to be wait for readout int fchains; //number of chains int *fcbltnum; //board number for each chain int *fcblt_addr; //dummy address for each chain int *fcbltloop; //max number of cblt loop unsigned int *faddr; unsigned int *fmask; //address and mask cblt TString vmeerror; // Vme error during read data int status; //freadout.Get_CBLT_Config(..) status public: static int fstatus; static bool fready; static bool fokstop; public: TCrateCBLT(TVMELink &link, TCBLT &readout, int index, string configfile); //TCrateCBLT(CVBoardTypes ControlBoardType=cvV2718, short PCILinkNum=0, short VMEControlBoardNum=0, // int fCrate=1, TCBLT readout=0) : //TVMELink(ControlBoardType, PCILinkNum, VMEControlBoardNum, fCrate), freadout(readout) {} // {freadout=readout;} TCrateCBLT(TCrateCBLT const &source); ~TCrateCBLT(); TCBLT &Get_Readout() {return freadout;} void Set_Readout(TCBLT &readout) {freadout=readout;} void SetReadoutEnable(bool status) {fenabled=status;} bool GetReadoutEnable() {return fenabled;} void ReadoutProcsInit(bool print=true); int EnableIRQ(); //make this V2718 answer the IRQ lines int WaitForReady(); void Readout(); void copy(TCrateCBLT const &source); int GetCBLTConfigStatus(){return status;} }; #endif //#ifndef TCrateCBLT_H<file_sep>/ribllvmedaq/TBoard.h /////////////////////////////////////////////////////// // VME models class interface // This class define the interface for the // boards implemented in the DAQ. // All true type models must be derived form the // base class, and all the member functions of a // true model must be declared as a pure virtual // function in this base class. // Version 0.01 // Hanjianlong 07/2012 /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// // Do not modify this class, even the comment lines /////////////////////////////////////////////////////// #ifndef TBoard_H #define TBoard_H #include "Rtypes.h" class TBoard { /// was modifed by xiaohai public: /* protected: */ unsigned int fBaseAddr; //! do not delete the '!', it is used by ROOT long fHandle; //! v2718 handle unsigned int fGeo; // Geo address unsigned int fCrateNum; // which crate is this board blong to char fname[20]; //! name of this class bool bTreeSwitch; //! for onlinetree, if flase this module will not in Tree //TBoard* pSelfObj; //! point to this board object itself unsigned int MaxChannel; //for ROOT Variable Length Arry = fMaxChannel public: TBoard() { bTreeSwitch = false; } // must have the default constructor virtual void Initialization() = 0; virtual ~TBoard() {} virtual int Get_BoardNumber() {return 0;} // get the board serial number, not used here unsigned int GetGeo() const {return fGeo;} unsigned int GetCrateNum() const {return fCrateNum;} virtual long GetHandle() const {return fHandle;} virtual unsigned int GetAcqReg() = 0; // the DRDY register virtual unsigned int GetAcqRegMask() = 0; // the DRDY register mask virtual unsigned int GetBaseAddr(){return fBaseAddr;} const char* GetName(){return fname;} virtual int Get_SerialNumber() {return 0;} // get the board serial number, not used here virtual unsigned int GetMaxChannel() = 0; // maximum number of valid signal input channels virtual unsigned int GetMaxDataVal() = 0; // maximum value of the converted data(4096, 8192 ....) //virtual TBoard* GetSelfObj() const {return pSelfObj;} //! Get the self object pointer virtual bool GetTreeSwitch() {return bTreeSwitch;} virtual unsigned int GetChannelData(int chnum) = 0; virtual void SetGeo(unsigned int geo){fGeo = geo;} virtual void SetBaseAddr(unsigned int Baddr) {fBaseAddr = Baddr;} virtual void SetCrateNum(unsigned int cnum) {fCrateNum = cnum;} virtual void SetName(const char* name); virtual void SetHandle(long handle){fHandle = handle;} virtual int Set_BoardNumber(int b) {return 0;} // not used //virtual void SetSelfObj(TBoard *self) {pSelfObj = self;} // a pointer to this object itself, used to build the root file virtual void SetMaxChannel(unsigned int mchann) = 0; virtual void SetMaxDataVal(unsigned int mdatav) = 0; virtual void SetTreeSwitch(bool onoff) {bTreeSwitch = onoff;} virtual int WriteGeoToBoard(unsigned int geo) = 0; virtual int WriteCrateNumtoBoard(unsigned int cnum) =0; virtual int Decode(unsigned int *&data_point) = 0; virtual void Create1DHistos() = 0; virtual int Init_Board() = 0; virtual void CleanChData() = 0; virtual int DataReset() = 0; virtual int SoftReset() = 0; virtual int SoftReset(unsigned int data, unsigned int addroffset, int datasize); virtual int SingleWriteCycle(unsigned int data, unsigned int mask, unsigned int addroffset, int datasize); virtual int SingleReadCycle(unsigned int& rdata, unsigned int addroffset, int datasize); //virtual const char *Class_Name() = 0; ClassDef(TBoard, 1); }; #endif //#ifndef TBoard_H <file_sep>/ribllvmedaq/TControlFrame.h ///////////////////////////////////////////////////////// // File name: TControlFrame.h // // Brief introduction: // // This class create the main frame for // // Online program of RIBLL1-DAQ // // // // Version: V1.0 // // Author: <NAME> // // Date: Nov. 2010 // // For: RIBLL1 // ///////////////////////////////////////////////////////// #ifndef ControlFrame_H #define ControlFrame_H #include "TGFrame.h" #include "Rtypes.h" class TGMainFrame; class TGVerticalFrame; class TGHorizontalFrame; class TGWindow; class TGLabel; class TGTextView; class TGTextEntry; class TGTextButton; class TGText; class TGNumberEntry; enum CMDBIdentifiers { kB_setfilename, kB_setfilerun, kB_setfileheader, kB_start, kB_stop, kB_initdaq, kB_openf, kB_closef, kB_exitcon, kB_testcomm, kB_connectodaq, kB_exitdaq, }; class TControlFrame : public TGMainFrame { protected: TGHorizontalFrame *fFUpMain, *fFDownMain; //! TGVerticalFrame *fFUpLeftMain, *fFUpRightMain; //! TGTextEntry *fTEfilename, *fTEfileheader; //! TGNumberEntry *fTEfilerun; //! TGLabel *flabFileStatus; //! TGTextButton *fBSetFileName, *fBSetFileRun, *fBSetFileHeader; //! TGTextButton *fBStart, *fBStop, *fBInitDAQ, *fBOpenF, *fBCloseF, *fBConExit, *fBTestComm, *fBConnect, *fBDaqExit; //! TGTextView *fviewText, *fvieweventnum; //! public: TControlFrame(const TGWindow *p, UInt_t w, UInt_t h); virtual ~TControlFrame(); virtual void CloseWindow(); virtual bool ProcessMessage(Long_t msg, Long_t param1, Long_t){return true;}; virtual void ShowText(TGText *text); virtual void ShowText(const char *text); virtual void ClearTextView(); virtual void ShowEventNum(int num); virtual void ClearEventNum(); virtual void DisableButt(TGTextButton *butt); virtual void EnableButt(TGTextButton *butt); virtual void UpdateTextView(); protected: TControlFrame(const TControlFrame &onf); TControlFrame& operator=(const TControlFrame &onf); ClassDef(TControlFrame, 1); }; extern TControlFrame *gControlFrame; #endif //#ifndef ControlFrame_H <file_sep>/ribllvmedaq/TDAQPCTask.cpp ///////////////////////////////////////////////////////// // File name: TDAQPCTask.cpp // // Brief introduction: // // DAQ PC task: Read data form VME modules, send // // data to UDP broadcast, receive command from // // master PC // Version: V1.0 // // Author: <NAME> // // Date: Aug. 2012 // // For: RIBLL1 // ///////////////////////////////////////////////////////// #include <vector> #include <string> #include <exception> #include <iostream> #include "stdlib.h" using namespace std; #include "TDAQPCTask.h" #include "TClientEvtBuilder.h" #include "TControl.h" #include "TThread.h" #include "TConfig.h" #include "TCrateCBLT.h" #include "caenacq.h" TDAQPCTask::TDAQPCTask(const char *ipaddr, TConfig &cod, std::vector<TCrateCBLT> &tcrate, unsigned int mastercrate) { try { DAQPCControl = new TControl(ipaddr, DAQ_PC); //eventbuilder = new TClientEvtBuilder(ipaddr, "BROADCAST", cod, tcrate, mastercrate); //eventbuilder = new TClientEvtBuilder(MULTICAST_IP.c_str(), "MULTICAST", cod, tcrate, mastercrate); string path = getenv(gConfPath.c_str()); path += IPLISTF; eventbuilder = new TClientEvtBuilder(path.c_str(), "IPLIST", cod, tcrate, mastercrate); } catch(bad_alloc &e) { cout << "TDAQPCTask>> " << e.what() << endl; } DAQPCControl->Connect("MSignalEmit()", "TClientEvtBuilder", eventbuilder, "ProcessStopSignal()"); } TDAQPCTask::~TDAQPCTask() { delete eventbuilder; delete DAQPCControl; } TThread *TDAQPCTask::StartDAQPCControlThread() { DAQPCControl->StartDaqPCThread(); return DAQPCControl->GetDaqPCThread(); } TThread *TDAQPCTask::StartDAQThread() { eventbuilder->StartDAQThread(); return eventbuilder->GetDAQThread(); } <file_sep>/ribllvmedaq/TDataFileBuilder.h ////////////////////////////////////////////////// // TDataFileBuilder.h: Data file manager, open // close, write data file. // <NAME> (08/2012) ///////////////////////////////////////////////// #ifndef TDataFileBuilder_H #define TDataFileBuilder_H #include "TDataReceiver.h" #include <TString.h> using namespace std; class TThread; class TDataFileBuilder: public TDataReceiver { protected: TString filename; TString fileheader; TString broadfileheader; unsigned int RunNum; unsigned int CurrRunNum; TString CurrFName; TString fileDir; static ofstream *datafile; TThread *thread_writedata; public: static unsigned int MaxFileSize; public: TDataFileBuilder(); virtual ~TDataFileBuilder(){}; void SetFileName(const char* name) {filename = name;} void SetRunNum(unsigned int rnum) {RunNum = rnum;} void SetFileHeader(const char* fheader) {fileheader = fheader;} void SetBroadFHeader(const char* bfheader){broadfileheader = bfheader;} void FormBroadFHeader(); //Form the fileheader used for UDP broadcast, this header begin with filename.runnum bool ExtractFNameNumFromBHeader(); //Extract the file name and run number form the braodcast fileheader TString GetBroadFHeader(){return broadfileheader;} bool OpenDataFile(); bool CloseDataFile(); bool CloseDataFileManual(); void SetMaxFileSizeMb(unsigned int sizeMb){MaxFileSize = sizeMb;} unsigned int GetMaxFileSizeMb(){return MaxFileSize;} static unsigned int CheckFileSize(); bool ReCreateFileAuto(); static bool IsDataFileValid(); static void* ReceiveDataToFile(void* arg); static bool CheckStop(); unsigned int GetCurrRunNum(){return CurrRunNum;} const char * GetCurrFName(){return CurrFName.Data();} bool StartWriteDataThread(); bool StopWriteDataThread(); TThread* GetWriteDataThread(){return thread_writedata;} }; extern TDataFileBuilder *gDataFileBuilder; #endif //#ifndef TDataFileBuilder_H<file_sep>/ribllvmedaq/TControl.h ///////////////////////////////////////// // TControl.h: Control the daq // This class contents a socket used to // receive 'control commands' from // the cotrol side PC // <NAME> 07/2012 ///////////////////////////////////////// #ifndef TControl_H #define TControl_H #include <string> using namespace std; #include "TString.h" #include <RQ_OBJECT.h> //#include "TQObject.h" class TSocket; class TServerSocket; class TThread; class TUDPClientSocket; class TUDPServerSocket; enum eAction { NULL_PC, // useless, only for initialization DAQ_PC, // DAQ PC CONTROL_PC, // the master control PC ONLINE_PC // the other online PC for online monitoring and save data file }; enum ECommands{kC_WAIT=0, kC_TEST, kC_INIT, kC_START, kC_STOP, kC_FOPEN, kC_FCLOSE, kC_EXIT}; const string sCommName[] = {"WAIT","TEST","INIT","START","STOP","OPEN","CLOSE","EXIT"}; const string sCommands[] = { "TEST CONNECTION", /* CMD = 0 */ "Initialize VME", /* 1 */ "Start Acquisition", /* 2 */ "Stop Acquisition", /* 3 */ "Open Tape File", /* 4 */ "Close Tape File", /* 5 */ "Exit and Put offline" /* 6 */ }; class TControl :public TQObject { //RQ_OBJECT("TControl") private: static TSocket *iRecvSocket; //! DAQ side PC socket, receive commands form control PC static TServerSocket *iSendSocket; //! Control side PC socket, send commands to DAQ PC static TSocket *iSendSocket_imp; //! implementation of the Send() with 'iSendSocket' & 'iRecvSocket' static TUDPClientSocket *iComBroadUDPSock; //! Broadcast the commands to all PC static TUDPServerSocket *iComRevUDPSock; //! Receive the bradcasted commands static TUDPClientSocket *iFHeBroadUDPSock; //! Broadcast the data file header static TUDPServerSocket *iFHeRevUDPSock; //! Receive the data file header TThread *thread_DaqPC; //! thread used by DAQ_PC TThread *thread_OnlinePC; //! thread used by ONLINE_PC TThread *thread_ConPCRevErr; //! thread used by CONTROL_PC to receive some error messages from daqpc //TThread *thread_DaqPC_WaitC; //! waiting for connection from Control_PC static eAction PC_Action; //! eAction value, to assort the action of this 'TControl' object static string sRecvComm; //! static bool TCPwait_command; //! static bool TCPRead_command; //! static bool UDPwait_command; //! static string ControlPCAddr; //! IP address of Control PC static string ack_mess; //! save the acknowlege message form the DAQ_PC //static string other_mess; //! for control_PC, save some no-command messages form Daq_PC public: static ECommands comm; //! static string fheader_file; //! the data file header public: TControl(const char* netaddr, eAction action); virtual ~TControl(); bool send_TCPcontrol_command(string scomm); static void *recv_TCPcontrol_command(void *arg); static void *recv_UDPBroadcontrol_command(void *arg); static void *recv_UDPBroadMessages(void *arg); //for Control_PC use only static int CommandForward(string message); static int BroadMessage(string message); static void acknowledge(); static void BroadFileHeader(); bool AcceptReceiver(); static void ControlSignal(void *arg, int comm); void CommandSignal(int comm); //*SIGNAL* static void MessageSignal(void *arg); void MSignalEmit(); //*SIGNAL* static void BroadMessageSignal(void *arg); void BMSignalEmit(); //*SIGNAL* string GetAckMessages() const {return ack_mess;}; string GetFileHeader() const {return fheader_file;} TSocket* GetTCPSendSocket(){return iSendSocket_imp;} bool GetTCPSendSocketState(); bool ClosTCPimpSocket(); //Close iSendSocket_imp void SetFileHeader(const char* fh) {fheader_file = fh;} int StartDaqPCThread(); bool StartOnlinePCThread(); bool StopOnlinePCThread(); int StartConPCRecErrThread(); void StopConPCRecErrThread(); TThread* GetDaqPCThread(); TThread* GetOnlinePCThread(); string GetNetAddr(){return ControlPCAddr;} eAction GetPCAction(){return PC_Action;} void printsignal(); protected: static bool DaqPCWaitConnection(); ClassDef(TControl, 1); }; extern TControl *onlyControl; #endif //#ifndef TControl_H<file_sep>/ribllvmedaq/TClientEvtBuilder.cpp //////////////////////////////////////////////// // TEvtBuilder.cpp: Class to perform the VME // reading and build the 'event' structure. // Use TCrateCBLT to loop reading procedure, // and then build the event in memory, then // send it out to ethernet by using UDP // socket. // <NAME> 07/2012 //////////////////////////////////////////////// #include "TUDPClientSocket.h" #include "TClientEvtBuilder.h" #include "TControl.h" #include "TCrateCBLT.h" #include "caenacq.h" #include <iostream> #include <string> using namespace std; #include "TString.h" #include "TThread.h" #ifdef WIN32 #include <windows.h> #define sleep Sleep #define WaitSec 400 #else #include <unistd.h> #define sleep usleep #define WaitSec 300000 #endif TUDPClientSocket *TClientEvtBuilder::DataBroadUDPsock = 0; extern int VMEReadBeforeCBLT(unsigned int* &buff, TConfig &gconfig); extern int VMEReadAfterCBLT(unsigned int* &buff, TConfig &gconfig); TClientEvtBuilder::TClientEvtBuilder(std::string addr, string udptype, TConfig &cod, std::vector<TCrateCBLT> &tcrate, unsigned int mastercrate):TEvtBuilder(cod,tcrate, mastercrate) { DAQThread = 0; if(udptype == "MULTICAST") { DataBroadUDPsock = new TUDPClientSocket(addr.c_str(), UDPDataBroadPortCon, true); } else if(udptype == "IPLIST") { DataBroadUDPsock = new TUDPClientSocket(addr.c_str()); // '10' is meaningless figure } else { //Do not used anymore //TString baddr = addr; //int pos = baddr.Last('.'); //baddr.Replace(pos+1, 3, "255"); //DataBroadUDPsock = new TUDPClientSocket(addr.c_str(), UDPDataBroadPortCon); } if(!DataBroadUDPsock->IsValid()) cout << " TClientEvtBuilder>> DataBroadUDPsocket error! " << endl; DataBroadUDPsock->SetSendTimeOutValue(200); //set sendto timeout } TClientEvtBuilder::~TClientEvtBuilder() { SafeDeleteP(DataBroadUDPsock); } int TClientEvtBuilder::CheckErrors(std::string ferror, int merr) { string errmsg; int num=fconfig.GetErrnum(); if(num !=0) { for(int i=0; i<num; i++) { if(i>merr)break; errmsg = ferror + fconfig.GetErrInfo(i); cout << errmsg.c_str() << endl; //TControl::BroadMessage(errmsg); } } return num; } void* TClientEvtBuilder::EventBuilderRun(void *arg) { // arg is a value of 'this' pointer, used to make this // 'static' function to visit the 'unstatic' variables TEvtBuilder *pthis = (TEvtBuilder *)arg; vector <TCrateCBLT> & fcrate = pthis->GetCrateCBLT(); TConfig &fconfig = pthis->GetConfig(); unsigned int fmastercrate = pthis->fmastercrate; enum kmsg {INIT, START, STOP, CLOSE, EXIT}; string ferror="File_Error: Init "; //string werror="20 W_Error"; unsigned int *curr_ptr; string curr_header, errmsg; int const maxmsg = 2; int absize = 0; int status = 0; const char *msg[ ] = { "Initialization ", "Start Acquisition ", "Stop of Acquisition ", "End Of File ", "End Of Program ", " " }; ECommands comm; for (int i=0; i<fnumcrates; i++) { fcrate[i].ReadoutProcsInit(); } while(true) { //control loop, wait for commands { // wait for command, ie the change of TControl::comm TControl::comm = kC_WAIT; comm = TControl::comm; while(comm == kC_WAIT) { sleep(WaitSec); comm = TControl::comm; } if(comm == kC_EXIT) break; } // INITIALIZATION if(comm == kC_INIT) { //master IO-port initialization fcrate[fmastercrate].ClearIOPort(cvOut0Bit); //1st, fcrate[fmastercrate].SetIOPort(cvOut1Bit); //2nd, stop trigger(veto) fcrate[fmastercrate].ClearIOPort(cvOut2Bit); //3rd, clear 'stop program trig' fcrate[fmastercrate].PulseOutput(cvOut0Bit); //4th, clear VME reading busy fconfig.GetConfigNames(); fconfig.Init_Caen_Boards(kInitReg); int errn = pthis->CheckErrors(ferror, maxmsg); //local readout errors if(errn == 0) { //TControl::BroadMessage(msg[INIT]); cout<<"Initialization OK!"<<endl; } else { //TControl::BroadMessage("Initialization Terminated with Errors."); cout<<"Initialization Terminated with Errors"<<endl; } } // start acquisition if(comm == kC_START) { //master IO-port initialization fcrate[fmastercrate].ClearIOPort(cvOut0Bit); //1st, fcrate[fmastercrate].SetIOPort(cvOut1Bit); //2nd, stop trigger fcrate[fmastercrate].ClearIOPort(cvOut2Bit); //3rd, clear 'stop program trig' fcrate[fmastercrate].PulseOutput(cvOut0Bit); //4th, clear VME reading busy fconfig.GetConfigNames(); fconfig.Init_Caen_Boards(kInitReg); int errn = pthis->CheckErrors(ferror, maxmsg); if((errn) == 0) { //TControl::BroadMessage(msg[START]); cout<<"Startup OK. Running now..."<<endl; do{ status = fcrate[fmastercrate].ClearIOPort(cvOut1Bit); //start trigger }while(status != 0); } else { cout<<"Startup Failed: "<<errn<<" error(s)"<<endl; continue; } //fcrate[fmastercrate].SetIOPort(cvOut0Bit); //test only sleep(WaitSec); pthis->fokstop=false; fevent_counter = 0; curr_ptr = fnetbuf; //init curr_ptr int buflen = 0; while(true)//waiting for readout tasks or stop command { // reset dead time: End of VME Reading Busy do{ status = fcrate[fmastercrate].PulseOutput(cvOut0Bit); }while(status != 0); if(CheckStop()) { comm = kC_STOP; break; } int tot = 0; int res = 0; while(tot!=fnumcrates) { tot = 0; res = 0; for(int i=0; i<fnumcrates; i++) { res = fcrate[i].WaitForReady(); tot += res; } //need to catch stop during data-ready if(CheckStop()) { comm = kC_STOP; break; } } if(tot==fnumcrates) { // local buffer header construction fevent_counter++; if(fevent_counter == 0x10000000) fevent_counter=0; // Write the event separator and eventnumber; *(curr_ptr) = Event_Header; curr_ptr++; buflen += sizeof(int); //buflen in byte, same as buflen += 4; *(curr_ptr) = fevent_counter; curr_ptr++; buflen += sizeof(int); //buflen in byte, same as buflen += 4; //Before main CBLT read #ifdef UserVMEFunctionBefore //define in caenacq.h absize = VMEReadBeforeCBLT(curr_ptr, fconfig); buflen += absize; #endif //main readout loop (asyncronous readout) for(int i=0; i<fnumcrates; i++) { if(fcrate[i].GetReadoutEnable()) { fcrate[i].Readout(); } } //After main CBLT read #ifdef UserVMEFunctionAfter //define in caenacq.h absize = VMEReadAfterCBLT(curr_ptr, fconfig); buflen += absize; #endif #ifdef Wait_Data_Ready_IRQ //enable IRQ Lines of master crate V2718 after the all of VME read process //int eirqtot = 0; //int eirqres = 0; //while(eirqtot!=fnumcrates) //{ // eirqtot = 0; // eirqres = 0; // for(int i=0; i<fnumcrates; i++) { // eirqres = fcrate[i].EnableIRQ(); // eirqtot += eirqres; // } //} //fcrate[fmastercrate].EnableIRQ(); #endif //#ifdef Wait_Data_Ready_IRQ // local buffer reconstruction int size; for (int i=0; i<fnumcrates; i++) { if(fcrate[i].GetReadoutEnable()) { size = (fcrate[i].Get_Readout()).GetUsedSizeByte(); memcpy(curr_ptr, (fcrate[i].Get_Readout()).GetBLTBuff(), size); curr_ptr += size>>2; buflen+=size; } } //broadcast data to Ethernet if(buflen >= MAX_NET_LEN) { curr_ptr = fnetbuf; //reset curr_ptr int out_len = DataBroadUDPsock->SendTo((const char *)curr_ptr, buflen); //if (out_len < buflen) TControl::BroadMessage(" Data send out error. Out<source ! "); //cout << "Send out length: " << out_len << " Real length: " << buflen << endl; buflen = 0; //reset buflen } } } //start loop } //if start if(comm==kC_FOPEN) { continue; } if(comm==kC_FCLOSE) { //TControl::BroadMessage(msg[CLOSE]); continue; } //stop acquisition if(comm == kC_STOP) { fcrate[fmastercrate].ClearIOPort(cvOut0Bit); //1st, fcrate[fmastercrate].SetIOPort(cvOut1Bit); //2nd, stop trigger(veto trigger) fcrate[fmastercrate].ClearIOPort(cvOut2Bit); //3rd, sclear 'stop program trig' fcrate[fmastercrate].PulseOutput(cvOut0Bit); //4th, clear VME reading busy pthis->fokstop=true; cout<<" Stop acquisition. "<<endl; continue; } //exit acquisition if(comm == kC_EXIT) { for(int i=0; i<fnumcrates; i++) { fcrate[i].EndVMEHandle(); } break; } } //event builder infinite loop cout << "EventBuilderRun() Stopped." << endl; return 0; } //if there is no trigger the 'Stop' command may not work, //because the program is blocked to 'WaitForIRQ'. //this function receive the 'MessageSignal(void *arg)' //and then use output-2 of V2718 to gernerate a trigger, //in this way the program can breakout form the 'loop' and //then 'Stop' void TClientEvtBuilder::ProcessStopSignal() { // cout << " Process Signal... " << endl; if(CheckStop()) { fcrate[fmastercrate].PulseOutput(cvOut2Bit); //trigger to 'stop' the program } } void TClientEvtBuilder::StartDAQThread() { if(!DAQThread) { DAQThread = new TThread("VMEReadThread", (void*(*)(void*))&TClientEvtBuilder::EventBuilderRun, (void*)this); if(DAQThread) { DAQThread->Run(); cout << DAQThread->GetName() << " runing... " << endl; return; } else { DAQThread = 0; return; } } else { DAQThread->Run(); return; } } TThread* TClientEvtBuilder::GetDAQThread() { if(DAQThread) { TThread::EState stat = DAQThread->GetState(); if(stat == TThread::kRunningState || stat == TThread::kNewState) return DAQThread; } return 0; } <file_sep>/ribllvmedaq/Raw2ROOTsun.cpp /////////////////////////////////////////////// // Raw2ROOT.cpp: main() of Raw2ROOT, used // for offline data analysis. // <NAME> (08/2012) /////////////////////////////////////////////// #include "TApplication.h" #include "TDAQApplication.h" #include "TConfig.h" #include "TDataFileReader.h" #include "TDataAnalyser.h" #include "TBoard.h" #include "TString.h" #include "TFile.h" #include "TTree.h" #include "TSystem.h" #include <iostream> #include <sstream> #include <fstream> #include <stdlib.h> #include <vector> #include <map> using namespace std; //const string gDataPath = "DAQDataPath"; void PrintUsage(char *name); int main(int argc, char *argv[]) { string rawlist, rawfile; string dfname; unsigned int evtana=0; unsigned int startn=0; fstream listf; vector<string> rawdfname; bool inter = false; TTree *tree = 0; TFile *rfile = 0; //prepare the environment // The Server DAQ Application defining general environment TDAQApplication ribll(0, 0, false); //where the cblt setup files are //string pathchain = ribll.Get_PathEnvdir() + "/cblt_addr_crate"; //where the filenameqdc and codifier setup file are string pathfilename = ribll.Get_PathEnvdir() + "/filenamemod.dat"; string datapath = gSystem->Getenv(gDataPath.c_str()); cout<< "RawDataPath: " << datapath << endl; cout << endl; PrintUsage(argv[0]); cout << endl; if(argc == 1) { cout <<"Input RawData File Name: "; cin >> dfname; cout <<"Input Start event number (0 for first event):"; cin >> startn; cout <<"Input Event number to analyze (0 to end of file): "; cin >> evtana; inter = true; } else if(argc == 2) { rawlist = datapath; rawlist += argv[1]; cout <<"List file of raw data files: " << argv[1] << endl; inter = false; } else { PrintUsage(argv[0]); return 0; } // inter=0; if(inter) { rawdfname.push_back(dfname); } else { string item; listf.open( rawlist.c_str() ); if( listf.fail() ) { cout << "File: " << rawlist << " open error!" << endl; return 0; } while( (listf.peek() != EOF) && (!listf.fail()) ) { getline(listf, item); TString tsitem(item); if(tsitem.IsWhitespace()) continue; //skip blank lines if(item.c_str()[0] == '*') continue; //skip the comments istringstream s_item(item); if(item.size() > 0) { s_item >> dfname; rawdfname.push_back(dfname); } item.empty(); } listf.close(); } TConfig conf(pathfilename.c_str()); TDataAnalyser anadata(&conf); TDataFileReader DFReader; //loop on each file for(int i=0; i<rawdfname.size(); i++) { string rdfname = rawdfname[i]; TString pathrdfn = datapath; pathrdfn += '/'; pathrdfn += rdfname; if(!DFReader.OpenDataFile(pathrdfn.Data())) continue; //open root file TString strfname(rdfname); strfname.ReplaceAll(".", ""); strfname += ".root"; TString pathrootfn = datapath; pathrootfn += '/'; pathrootfn += strfname; rfile = new TFile(pathrootfn.Data(), "RECREATE"); //crate 1d histograms //UserTH_Init(); //create user defined histograms map<int, TBoard*> *CrateGeoMap = anadata.GetCrateGeoMap(); map<int, TBoard*>::const_iterator it; for(it=CrateGeoMap->begin(); it!=CrateGeoMap->end(); it++) { (*it).second->Create1DHistos(); } //crate tree tree = new TTree("RawData", "ModuleData"); for(it=CrateGeoMap->begin(); it!=CrateGeoMap->end(); it++) { TString cname(typeid(*((*it).second)).name()); cname.ReplaceAll("class ", ""); //for windows while(true) { TString ttemp(cname(0,1)); if(ttemp.IsDigit()) { cname.Replace(0, 1, ""); } else { break; } } TString tname = "Mod";//(*it).second->Class_Name(); tname += (*it).first; tname += '_'; tname += cname; tree->Branch(tname.Data(), (*it).second->Class_Name(), (*it).second); } bool skiph = DFReader.SkipFileHeader(); cout << "Skip Data File header(true/false): " << boolalpha << skiph << noboolalpha<< endl; unsigned int numevtana = 0; unsigned int vmecount = 0, vmecount_sent = 0; int eventcount_sent = 0; int increment = 0, tinc = 0; int totalevent = 0; unsigned int evtc = 0; if(startn>0) { unsigned int sstartn = startn; do { if( !DFReader.EvtReadingLoop() ) { cout << "File do not have enough events: " << startn <<endl; } sstartn--; }while(sstartn>0); cout << "The first: " << startn << " events skiped." << endl; } //ofstream temp("temp.txt"); while(true) { if(numevtana>=evtana && evtana!=0) break; if( !DFReader.EvtReadingLoop() ) break; //end of file unsigned int len = DFReader.GetEventLength(); unsigned int *evtbuffer = DFReader.GetEvtBuf(); //temp << endl; //for(unsigned int kks =0; kks<len; kks++) //{ // unsigned int da = *(evtbuffer+kks); // temp << da << " " << (da>>27) << " " << ((da<<5)>>29) << " " << ((da<<11)>>27)<< endl; //} evtc = anadata.GlobalDecoder(evtbuffer, len); //calculate vme read count if(evtc>0 && evtc < eventcount_sent) { vmecount += eventcount_sent; //in case 'acqstop' during this file } //calculate Net loss event number if(evtc>0 ) { totalevent++; if(evtc < eventcount_sent) eventcount_sent = 0; if(evtc>eventcount_sent) { tinc = evtc - eventcount_sent; increment += (tinc-1); } eventcount_sent = evtc; } //UserTH_Fill(); tree->Fill(); numevtana++; } rfile->Write(); rfile->Close(); delete rfile; tree = 0; vmecount += evtc; cout <<"VMERead Event Num= " << vmecount << "; File Event Num= " <<totalevent <<"; NetLoss Event Num = " << increment-startn <<endl; cout << rdfname << " Finished!" << endl; } return 0; } void PrintUsage(char *name) { cout<<"Usage: "<<name<<" "<<endl; cout<<"\t Interactive mode." << endl; cout<<"Usage: "<<name<<" listfilename "<<endl; cout<<"\t 'listfilename' is a text file contains the 'raw data file names'."; cout<<endl; } <file_sep>/ribllvmedaq/TUDPClientSocket.h ////////////////////////////////////////////////////// // TUDPClientSocket.h: Broadcast UDPSocket // Broadcast the data to ethernet // <NAME> 07/2012 test version v.01 // v.02 : added "localhost" environment for singal PC // by <NAME> (06/2013) ////////////////////////////////////////////////////// #ifndef TUDPClientSocket_H #define TUDPClientSocket_H #ifdef WIN32 #include <winsock2.h> #include <Ws2tcpip.h> //#include <windows.h> #else #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #endif //#ifdef WIN32 #ifdef WIN32 #pragma comment(lib,"Ws2_32.lib") #endif //#ifdef WIN32 #include <vector> using namespace std; class TUDPClientSocket { private: int isocket; unsigned int iport; vector<struct sockaddr_in> v_addr_info; int addr_len; public: TUDPClientSocket(){isocket = 0;} TUDPClientSocket(const char* netaddress, unsigned int port); TUDPClientSocket(const char* netaddress, unsigned int port, bool multicast); //for multicast udp socket TUDPClientSocket(const char* addrlistfile, unsigned int port, char cf); //for command and data file header udp socket TUDPClientSocket(const char* addrlistfile); virtual ~TUDPClientSocket(); virtual int SendTo(const char* buff, int length); bool IsValid() {return isocket<0 ? false: true;} bool SetSendTimeOutValue(unsigned int usec); bool SetRouteNum(unsigned int rnum); bool SetLoopBack(bool lback); bool JoinMemberShip(const char* MC_IP); int ReadAddrListFileForDS(const char *listfile); //read ip list for data sending int ReadAddrListFileForCF(const char *listfile, unsigned int port); //read ip list for sending command and file header }; #endif //#ifndef TUDPBroadSocket_H <file_sep>/ribllvmedaq/TModV830AC.cpp //////////////////////////////////////////// // TModV830AC.h: Implementation of CAEN // module V830AC // All module class must be inherited form // 'TBoard' // <NAME> 07/2012 //////////////////////////////////////////// #include <iostream> #include <cstring> using namespace std; #include "TModV830AC.h" #include "TH1.h" #include "TH1I.h" #include "TString.h" #include "Rtypes.h" #include "caenacq.h" unsigned int TModV830AC::facqreg[2] = {0x100E, 0x0001}; unsigned int TModV830AC::fMaxDataVal = 200; static const short DataHeaderRsh= 26; //Left shift of a int data to check if this is the Data Header static const short DataHeaderLsh= 5; static const int DataHeaderMask= 0x4000000; static const short DataMarkMask= 0x0; static const short GeoRsh= 27; static const short CNTRsh= 18; static const short CNTLsh= 8; static const short TSLsh= 14; static const short TSRsh= 16; static const short ChNumbRsh= 27; static const short ChNumbLsh= 0; static const short DataValueLsh= 6; static const short DataValueRsh= 6; static const int TriggNumMask= 0xFFFF; static const short GeoAddrOffset= 0x1110; static const short GeoMask= 0x1F; static const short MaxGeo= 31; static const short AMNESIA_Mask= 0x10; static const short StaReg1AddrOffset= 0x100E; static const short ConBitSetReg= 0x110A; static const short EnableDataHeader= 0x20; static const short Enable26bitMode= 0x4; static unsigned int ChTempData[TModV830AC::fMaxChannel]; ClassImp(TModV830AC) /////////////////////////////////////////// // This class definition only for V830AC // which works in 26-bit mode, and with // the Data-Header enabled. /////////////////////////////////////////// void TModV830AC::Initialization() { his1d = new TH1*[fMaxChannel]; for(unsigned int i=0; i<fMaxChannel; i++) his1d[i] = 0; for(int i=0; i<fMaxChannel; i++) //initialize the temp variables { ChTempData[i] = 0; } } int TModV830AC::Decode(unsigned int *&data_point) { //CleanChData(); unsigned int tdata = (*data_point); unsigned short ChannelNums = 0; unsigned int TrigNums = 0, TrigType = 0; unsigned int dataMarker = tdata & DataHeaderMask; unsigned int mGeo = (tdata>>GeoRsh); if(mGeo != fGeo) { cout<< GetName() << " Data header error. Module Geo " << fGeo << " in Crate: " << fCrateNum <<" do not match." << endl; data_point++; return 0; } if(dataMarker>0) { ChannelNums = (tdata<<CNTLsh)>>(CNTLsh+CNTRsh); TrigType = (tdata<<TSLsh)>>(TSLsh+TSRsh); TrigNums = tdata&TriggNumMask; } for(unsigned int ch=0; ch<ChannelNums; ch++) { data_point++; tdata = (*data_point); unsigned short channel = tdata>>ChNumbRsh; dataMarker = tdata & DataHeaderMask; if(dataMarker != 0) { cout<< GetName() << " Data error. Too much headers in Module Geo: " << fGeo << " in Crate: " << fCrateNum << endl; return 0; } if(channel>=fMaxChannel) { cout<< GetName() << " Data header error. Module channel: " << channel << "> fMaxChannel: " << fMaxChannel << endl; continue; } try { unsigned int temp = (tdata<<DataValueLsh)>>DataValueRsh; unsigned int htemp = 0; chdata[channel] = temp; if(temp < ChTempData[channel]) htemp = 0x4000000 + temp - ChTempData[channel]; else htemp = temp - ChTempData[channel]; if(htemp>fMaxDataVal) htemp = fMaxDataVal; ChTempData[channel] = temp; if(htemp>0) { if(his1d[channel]) his1d[channel]->Fill(htemp); } } catch (exception& e) //want to catch the Array Index Out Of Bounds Exception { cerr << "exception caught: " << e.what() << endl; } } //data_point++; //to next data header return TrigNums; } void TModV830AC::Create1DHistos() { TString hnamet = 'h'; int hisname1 = (fCrateNum*100000 + fGeo*1000); int hisname2 = 0; TString htitle = 'T'; int histitle1 = (fCrateNum*100000 + fGeo*1000); int histitle2 = 0; TString hname, title; for(unsigned int i=0; i<fMaxChannel; i++) { hname = hnamet; hisname2 = hisname1 + i; hname += hisname2; title = htitle; histitle2 = histitle1 + i; title += histitle2; his1d[i] = new TH1I(hname.Data(), title.Data(), fMaxDataVal, 0.5, fMaxDataVal+0.5); } } TModV830AC::~TModV830AC() { //SafeDeleteArr(chdata); } ///////////////////////////////////////////////// // There is some spetial func in this function. // The 26-bit mode and Data-Header is enabled // for V830AC. In this way, we make sure that // this class implementation will work for the // data analysis. //////////////////////////////////////////////// int TModV830AC::WriteGeoToBoard(unsigned int geo) { unsigned int wgeo = geo; unsigned int geomask = GeoMask; if(wgeo>MaxGeo) { cout << " Geo " << wgeo << " > " << MaxGeo << endl; return 0; } int wstatus = SingleWriteCycle(wgeo, geomask, GeoAddrOffset, 16); //set the 26-bit mode, and enable the Data-Header int wstatus1 = SingleWriteCycle(Enable26bitMode, 0x0, ConBitSetReg, 16); int wstatus2 = SingleWriteCycle(EnableDataHeader, 0x0, ConBitSetReg, 16); return (wstatus + wstatus1 + wstatus2); } unsigned int TModV830AC::GetChannelData(int chnum) { if(chnum>=0 && chnum<fMaxChannel) return chdata[chnum]; return 0; }<file_sep>/ribllvmedaq/TDAQPCTask.h ///////////////////////////////////////////////////////// // File name: TDAQPCTask.h // // Brief introduction: // // DAQ PC task: Read data form VME modules, send // // data to UDP broadcast, receive command from // // master PC // Version: V1.0 // // Author: <NAME> // // Date: Aug. 2012 // // For: RIBLL1 // ///////////////////////////////////////////////////////// #ifndef DAQPCTask_H #define DAQPCTask_H #include <vector> using namespace std; class TClientEvtBuilder; class TControl; class TThread; class TConfig; class TCrateCBLT; class TDAQPCTask { protected: TClientEvtBuilder *eventbuilder; TControl *DAQPCControl; public: TDAQPCTask(const char* ipaddr, TConfig &cod, std::vector<TCrateCBLT> &tcrate, unsigned int mastercrate); virtual ~TDAQPCTask(); TThread * StartDAQThread(); TThread * StartDAQPCControlThread(); protected: TDAQPCTask(TDAQPCTask const &source){} }; #endif //#ifndef DAQPCTask_H<file_sep>/ribllvmedaq/TOfflineAnalyser.h //////////////////////////////////////////////// // TOfflineAnalyzer.h: Offline analyzer used // for data analysis. // <NAME> (08/2012) //////////////////////////////////////////////// #ifndef TOfflineAnalyzer_H #define TOfflineAnalyzer_H #include <fstream> #include <map> using namespace std; class TDataFileReader; class TDataAnalyser; class TFile; class TBoard; class TTree; class TOfflineAnalyzer { public: static TDataFileReader *freader; static TDataAnalyser *danalyzer; ifstream fnamelist; ifstream datafile; TFile *rootfile; TTree *tree; map<int, TBoard*> *CrateGeoMap; public: TOfflineAnalyzer(TDataFileReader *filer, TDataAnalyser *anadata); virtual ~TOfflineAnalyzer(){} bool SetListFile(const char* listfn); bool LoopLsitFile(const char* listfn); void AnaSingleDataFile(const char* dfile, int nevt_ana); void Analysis(); void CreateTree(); void CreateTH1I(); void OpenRootFile(const char* rfname); void CloseRootFile(); void WriteRootFile(); }; #endif //#ifndef TOfflineAnalyzer_H<file_sep>/ribllvmedaq/TConfig.h /////////////////////////////////////////////////////////// // TConfiguration class interface // TConfiguration class. E.d.F. (2007) // main configuration class for hardware database // and codifier initialization. // Used to read configuration files of boards and write // (implement) the data to boards. // Modified by <NAME> 07/2012 /////////////////////////////////////////////////////////// #ifndef TCONFIG_H #define TCONFIG_H #include <list> #include <vector> using namespace std; #include "caenacq.h" #include "TBoard.h" class TTable; class TBoardError; class TConfig { private: static list <string> fqnames; //list of modules configuration file names static list <TBoard *> fboard; //list of modules definitions static vector<TTable> ftable; //crate sublist handler the first board of each handle(crate) char *ffilename; //the main codifier declaration list vector<TBoardError> fverror; public: TConfig(const char *confname); TConfig(TConfig &); ~TConfig(); int GetConfigNames(); int Init_Caen_Boards(EBoardInit sflag); void Init_Register(int crate, int addr, int data, int datawidth, int mask); long GetHandle(int ); void ShowList(); void ShowBoardList(); void BuildCrateBookmark(); static list<TBoard*>::const_iterator &LookupTable(int handle, int &num); static list<TBoard*>& GetBoardList(); int GetErrnum() {return fverror.size();} string GetErrInfo(int ); int ReadConfigForAnalysis(); private: void EraseNamesList(); void EraseBoardList(); }; //This helper class maintain bookmarks to the first board and number of boards //belonging to a single crate. It is supposed that the main list is //ordered as a function of the handle number by construction. //the table is cleaned and constructed again when Init_Caen_Boards member function //is called. TConfig has full privileges over this class (friend declaration) class TTable { friend class TConfig; private: long fhandle; list <TBoard *>::const_iterator ffirst; int fnum; public: TTable () : fnum(0), fhandle(-1) {} ~TTable () {} }; // This class contains a list of initialization errors class TBoardError { private: int fcrate; int faddr; int fdata; public: TBoardError() : fcrate(0), faddr(0), fdata(0) {} ~TBoardError() {} void SetError(int crate, int addr, int data) {fcrate=crate; faddr=addr, fdata=data;} int GetECrate() {return fcrate;} int GetEAddr() {return faddr;} int GetEData() {return fdata;} }; #endif <file_sep>/ribllvmedaq/TDataReceiver.cpp //////////////////////////////////////////////// // TDataReceiver.cpp: Receive data form UDP // broadcast socket, and write them to disk // file. // <NAME> (08/2012) /////////////////////////////////////////////// #include "TUDPServerSocket.h" #include "TDataReceiver.h" #include "TControl.h" #include "caenacq.h" #include <cstring> unsigned int TDataReceiver::fdatabuf[NETBUFFER/4]; TUDPServerSocket *TDataReceiver::UDPDataRec; int TDataReceiver::eventcounter = 0; TDataReceiver::TDataReceiver(unsigned int iport) { UDPDataRec = new TUDPServerSocket(iport); UDPDataRec->SetRcvTimeOutValue(700); //time out 700 mSec //UDPDataRec->JoinMemberShip(MULTICAST_IP.c_str()); } TDataReceiver::~TDataReceiver() { delete UDPDataRec; } //return the received data length in byte int TDataReceiver::ReceiveData() { memset(fdatabuf, 0x0, NETBUFFER); return UDPDataRec->RecvRaw( (char*)fdatabuf, sizeof(fdatabuf) ); } bool TDataReceiver::IsUDPValid() { return UDPDataRec->IsValid(); } bool TDataReceiver::CloseRecDataSocket() { return UDPDataRec->CloseCleanSocket(); } bool TDataReceiver::OpenRecDataSocket() { return UDPDataRec->OpenInitSocket(); }<file_sep>/ribllvmedaq/TOnlineFrame.cpp ///////////////////////////////////////////////////////// // File name: OnlineFrame.cpp // // Brief introduction: // // This class create the main frame for // // Online program of RIBLL1-DAQ // // // // Version: V1.0 // // Author: <NAME> // // Date: Nov. 2010 // // For: RIBLL1 // ///////////////////////////////////////////////////////// #include "TApplication.h" #include "TSystem.h" #include "TROOT.h" #include "TClass.h" #include "TCanvas.h" #include "TGClient.h" #include "TGWindow.h" #include "GuiTypes.h" #include "TGSplitter.h" #include "TGLayout.h" #include "TVirtualX.h" #include "TG3DLine.h" #include "TGText.h" #include "TGLabel.h" #include "TGComboBox.h" #include "TGListView.h" #include "TGFSContainer.h" #include "TGButton.h" #include "TGTextView.h" #include "TCanvasImp.h" #include "TRootCanvas.h" #include "TStyle.h" #include "TVirtualX.h" #include "TString.h" #include "TObject.h" #include "TDirectory.h" #include "TFile.h" #include "TKey.h" #include "TGFSContainer.h" #include "TVirtualPad.h" #include "TPad.h" #include "TH1.h" #include "TH2.h" #include "TTree.h" #include "TThread.h" #include "TIterator.h" #include "TCollection.h" #include "TMarker.h" #include "TAxis.h" #include "TContextMenu.h" #include "TClassMenuItem.h" #include "TOnlineFrame.h" #include <iostream> #include <ctime> #include <string.h> using namespace std; TOnlineFrame *gOnlineFrame =0; TOnlineFrame::TOnlineFrame(const TGWindow *p, UInt_t w, UInt_t h): TGMainFrame(p, w, h, kHorizontalFrame) { if(gOnlineFrame!=0) { cout<<"Only one instance of 'Online' permitted"<<endl; return; } gOnlineFrame = this; SetCleanup(kDeepCleanup); DontCallClose(); ObjList = 0; objcurr = 0; fFFileList = new TGVerticalFrame(this, 210, 350, kChildFrame|kVerticalFrame|kRaisedFrame|kFixedWidth); AddFrame(fFFileList, new TGLayoutHints(kLineSolid, 1, 1, 1, 1)); TGHorizontalFrame *fFdrawopt = new TGHorizontalFrame(fFFileList, 75, 10); fFFileList->AddFrame(fFdrawopt, new TGLayoutHints(kLHintsNormal, 1, 1, 1, 1)); flabDrawOpt = new TGLabel(fFdrawopt, "DrawOpt: "); fFdrawopt->AddFrame(flabDrawOpt, new TGLayoutHints(kLHintsLeft|kLHintsCenterY, 10, 1, 1, 1)); fcomAxisOpt = new TGComboBox(fFdrawopt); fcomAxisOpt->Resize(65, 25); fcomAxisOpt->AddEntry("LinXY", 0); fcomAxisOpt->AddEntry("LogY", 1); fcomAxisOpt->AddEntry("LogX", 2); fcomAxisOpt->AddEntry("LogXY", 3); fcomAxisOpt->Select(0); fFdrawopt->AddFrame(fcomAxisOpt, new TGLayoutHints(kLHintsRight|kLHintsCenterY, 1, 1, 1,1)); fcomDrawOpt = new TGComboBox(fFdrawopt); fcomDrawOpt->Resize(65, 25); fcomDrawOpt->AddEntry("", 0); fcomDrawOpt->AddEntry("COLZ", 1); fcomDrawOpt->AddEntry("LEGO", 2); fcomDrawOpt->AddEntry("CONT", 3); fcomDrawOpt->AddEntry("SURF", 4); fFdrawopt->AddFrame(fcomDrawOpt, new TGLayoutHints(kLHintsRight|kLHintsCenterY, 1, 1, 1,1)); TGHorizontal3DLine *opsep = new TGHorizontal3DLine(fFFileList, 210, 3); fFFileList->AddFrame(opsep, new TGLayoutHints(kLHintsExpandX, 1, 1, 1, 1)); TGHorizontalFrame *fFDivPad = new TGHorizontalFrame(fFFileList, 210, 15); flabDivPad = new TGLabel(fFDivPad, " Divide Pad: "); fFDivPad->AddFrame(flabDivPad, new TGLayoutHints(kLHintsLeft|kLHintsCenterY, 19, 1, 1, 1)); fcomDivPad = new TGComboBox(fFDivPad); fcomDivPad->Resize(70, 25); fcomDivPad->AddEntry("1 X 1", 0); fcomDivPad->AddEntry("2 X 2", 1); fcomDivPad->AddEntry("2 X 3", 2); fcomDivPad->AddEntry("3 X 3", 3); fcomDivPad->Select(0, false); fFDivPad->AddFrame(fcomDivPad, new TGLayoutHints(kLHintsRight|kLHintsCenterY, 1, 1, 1,1)); fFFileList->AddFrame(fFDivPad, new TGLayoutHints(kLHintsNormal, 1, 1, 1, 1)); TGHorizontal3DLine *pfvsep = new TGHorizontal3DLine(fFFileList, 210, 3); fFFileList->AddFrame(pfvsep, new TGLayoutHints(kLHintsExpandX, 1, 1, 1, 1)); flvFile = new TGListView(fFFileList, 200, 330); fFFileList->AddFrame(flvFile, new TGLayoutHints(kLHintsNormal, 1, 1, 1, 1)); Pixel_t white; gClient->GetColorByName("white", white); fFileCont = new TGFileContainer(flvFile, kSunkenFrame, white); fFileCont->Associate(this); TGHorizontalFrame *fFvsp = new TGHorizontalFrame(this, 5, 400, kChildFrame|kRaisedFrame); TGVSplitter *vsp = new TGVSplitter(fFvsp, 4, 4); vsp->SetFrame(fFFileList, true); fFvsp->AddFrame(vsp, new TGLayoutHints(kLHintsExpandY)); AddFrame(fFvsp, new TGLayoutHints(kLHintsNormal|kLHintsExpandY, 1, 1, 0, 0)); TGVerticalFrame *fFRight = new TGVerticalFrame(this, 300, 400, kChildFrame|kFixedHeight|kFixedWidth); fFButton = new TGVerticalFrame(fFRight, 300, 150, kChildFrame|kRaisedFrame|kFixedWidth|kFixedHeight); TGHorizontalFrame *butt1 = new TGHorizontalFrame(fFButton, 300, 50, kFitWidth); TGLayoutHints *flayoutButt = new TGLayoutHints(kLHintsNormal|kLHintsCenterX|kLHintsCenterY, 5, 5, 7, 7); fBonline = new TGTextButton(butt1, " ONLINE ", kB_online); fBoffline = new TGTextButton(butt1, " OFFLINE ", kB_offline); fBexit = new TGTextButton(butt1, " EXIT ", kB_exit); butt1->AddFrame(fBonline, flayoutButt); butt1->AddFrame(fBoffline, flayoutButt); butt1->AddFrame(fBexit, flayoutButt); TGHorizontalFrame *butt2 = new TGHorizontalFrame(fFButton, 300, 50, kFitWidth); fBresetall = new TGTextButton(butt2, " RESETALL ", kB_resetall); fBresetcurr = new TGTextButton(butt2, " RESETCUR ", kB_resetcurr); fBintegral = new TGTextButton(butt2, " INTEGRAL ", kB_integral); butt2->AddFrame(fBresetcurr, flayoutButt); butt2->AddFrame(fBresetall, flayoutButt); butt2->AddFrame(fBintegral, flayoutButt); TGHorizontalFrame *butt3 = new TGHorizontalFrame(fFButton, 300, 50, kFitWidth); fBprevious = new TGTextButton(butt3, " PREVIOUS ", kB_privious); fBnext = new TGTextButton(butt3, " NEXT ", kB_next); fBupdate = new TGTextButton(butt3, " UPDATE ", kB_update); butt3->AddFrame(fBprevious, flayoutButt); butt3->AddFrame(fBnext, flayoutButt); butt3->AddFrame(fBupdate, flayoutButt); fBonline->Associate(this); fBoffline->Associate(this); fBexit->Associate(this); fBresetall->Associate(this); fBresetcurr->Associate(this); fBintegral->Associate(this); fBprevious->Associate(this); fBnext->Associate(this); fBupdate->Associate(this); fBonline->SetToolTipText("Analyze online"); fBoffline->SetToolTipText("Stop analysis"); fBexit->SetToolTipText("Exit this program"); fBresetall->SetToolTipText("Reset all histograms"); fBresetcurr->SetToolTipText("Reset current histogram"); fBintegral->SetToolTipText("Integral given bins"); fBprevious->SetToolTipText("Draw previous histogram"); fBnext->SetToolTipText("Draw next histogram"); fBupdate->SetToolTipText("Update current histogram"); fFButton->AddFrame(butt1, new TGLayoutHints(kLHintsCenterX, 2, 2, 5, 5)); fFButton->AddFrame(butt2, new TGLayoutHints(kLHintsCenterX, 2, 2, 5, 5)); fFButton->AddFrame(butt3, new TGLayoutHints(kLHintsCenterX, 2, 2, 5, 5)); fFRight->AddFrame(fFButton, new TGLayoutHints(kLHintsCenterX, 2, 2, 8, 8)); TGVerticalFrame *fFvsp2 = new TGVerticalFrame(fFRight, 300, 15, kChildFrame|kRaisedFrame); TGHSplitter *vsp2 = new TGHSplitter(fFvsp2, 5, 5); vsp2->SetFrame(fFButton, true); fFvsp2->AddFrame(vsp2, new TGLayoutHints(kLHintsExpandY|kLHintsExpandX)); fFRight->AddFrame(fFvsp2, new TGLayoutHints(kLHintsNormal|kLHintsExpandX, 1, 1, 0, 0)); TGHorizontalFrame *fFvtext = new TGHorizontalFrame(fFRight, 300, 290, kChildFrame|kRaisedFrame|kFixedHeight|kFixedWidth); fviewText = new TGTextView(fFvtext, 300, 190); fFvtext->AddFrame(fviewText, new TGLayoutHints(kLHintsExpandY|kLHintsExpandX, 2, 2, 6, 2)); fFRight->AddFrame(fFvtext, new TGLayoutHints(kLHintsExpandY|kLHintsExpandX, 2, 2, 6, 2)); AddFrame(fFRight, new TGLayoutHints(kLHintsNormal, 1, 1, 0, 0)); SetWMSizeHints(GetDefaultWidth(), GetDefaultHeight(), GetDefaultWidth(), GetDefaultHeight(), 0, 0); SetWindowName("Online-RIBLL1-DAQ"); MapSubwindows(); MapWindow(); fFileCont->SetDefaultHeaders(); // fFileCont->DisplayDirectory(); // fFileCont->AddFile(".."); // up level directory // fFileCont->Resize(); fFileCont->StopRefreshTimer(); // stop refreshing fFileCont->SetPageDimension(0, 0); fFileCont->SetViewMode(kLVDetails); fFileCont->SetHeaders(2); fFileCont->SetColHeaders(" name ", " title "); Resize(); CreateCanvas(); } TOnlineFrame::~TOnlineFrame() { if(datafile) delete datafile; if(candaq) delete candaq; } void TOnlineFrame::CloseWindow() { DeleteWindow(); gApplication->Terminate(0); } bool TOnlineFrame::ProcessMessage(Long_t msg, Long_t param1, Long_t) { switch(GET_MSG(msg)) { case kC_COMMAND: switch(GET_SUBMSG(msg)) { case kCM_BUTTON: switch(param1) { case kB_exit: CloseWindow(); break; } } break; default: break; } // ShowText(GetDrawOpt()); //cout << ShowText(GetDrawOpt()) << endl; return kTRUE; } const char* TOnlineFrame::GetDrawOpt() { int num = fcomDrawOpt->GetSelected(); switch (num) { case 0: return ""; break; case 1: return "COLZ"; break; case 2: return "LEGO"; break; case 3: return "CONT"; break; case 4: return "SURF"; break; default: return ""; break; } } void TOnlineFrame::GetAxisOpt(unsigned int& lx, unsigned int& ly) { unsigned int num = fcomAxisOpt->GetSelected(); switch(num) { case 0: lx = 0; ly = 0; return; break; case 1: lx = 0; ly = 1; return; break; case 2: lx = 1; ly = 0; return; break; case 3: lx = 1; ly = 1; return; break; default: lx = 0; ly = 0; return; break; } } void TOnlineFrame::ShowText(TGText *text) { TThread::Lock(); //lock the main mutex ClearTextView(); fviewText->AddText(text); fviewText->Update(); fviewText->ShowBottom(); TThread::UnLock(); //unlock the main mutex } void TOnlineFrame::ShowText(const char *text) { TThread::Lock(); //lock the main mutex ClearTextView(); fviewText->AddLineFast(text); fviewText->Update(); //fviewText->AddLine(text); fviewText->ShowBottom(); TThread::UnLock(); //unlock the main mutex } void TOnlineFrame::CreateCanvas() { gStyle->SetTitleFillColor(kWhite); gStyle->SetFrameFillStyle(0); gStyle->SetFrameFillStyle(1001); gStyle->SetFrameFillColor(0); gStyle->SetFuncColor(kRed); gStyle->SetStatColor(kWhite); gStyle->SetStatBorderSize(1); gStyle->SetOptStat("nemr"); gStyle->SetPadBorderMode(0); gStyle->SetPadColor(0); gStyle->SetTitleBorderSize(1); gStyle->SetLegendBorderSize(1); gStyle->SetFillColor(1); gStyle->SetPalette(1); gStyle->SetOptFit(0111); gStyle->SetHistLineWidth(1); gStyle->SetHistLineColor(4); if(!(gROOT->GetListOfCanvases()->FindObject("can_daq"))) { candaq = new TCanvas("can_daq", "RIBLL1_ONLINE"); if(!candaq->GetShowToolBar()) candaq->ToggleToolBar(); if(!candaq->GetShowEventStatus()) candaq->ToggleEventStatus(); candaq->SetBorderMode(0); candaq->SetFillColor(0); candaq->SetFillStyle(0); candaq->SetFrameBorderMode(0); ((TRootCanvas *)candaq->GetCanvasImp())->DontCallClose(); //remove some contextmenu items of TCanvas MakeTcMenuList(); RemoveMenuEntry("SetEditable", TCmlist); RemoveMenuEntry("DrawClonePad", TCmlist); RemoveMenuEntry("DrawClone", TCmlist); RemoveMenuEntry("Dump", TCmlist); RemoveMenuEntry("SetName", TCmlist); } } void TOnlineFrame::ClearTextView() { TThread::Lock(); //lock the main mutex if(fviewText->ReturnLineCount()>=50) { fviewText->GetText()->DelLine(1); } TThread::UnLock(); //unlock the main mutex } void TOnlineFrame::OnDoubleClick(TGLVEntry *f, Int_t btn) { if (btn!=kButton1) return; TThread::Lock(); //lock the main mutex gVirtualX->SetCursor(fFileCont->GetId(),gVirtualX->CreateCursor(kWatch)); TString name(f->GetTitle()); const char* fname = (const char*)f->GetUserData(); if (fname) { DisplayObject(fname,name); } else if (name.EndsWith(".root")) { DisplayFile(name); } else { DisplayDirectory(name); } gVirtualX->SetCursor(fFileCont->GetId(),gVirtualX->CreateCursor(kPointer)); TThread::UnLock(); //unlock the main mutex } void TOnlineFrame::DisplayFile(const TString &fname) { // display content of ROOT file if(!datafile) return; TFile *file = datafile; TThread::Lock(); //lock the main mutex fFileCont->RemoveAll(); // fFileCont->AddFile(gSystem->WorkingDirectory()); fFileCont->SetPagePosition(0,0); // fFileCont->SetHeaders(2); // fFileCont->SetColHeaders("name", "title"); // TIter next(file.GetListOfKeys()); TIter next(file->GetList()); TKey *key; while ((key=(TKey*)next())) { if(!(key->IsA())->InheritsFrom("TH1")) continue; TString cname = key->GetTitle(); TString name = key->GetName(); TGLVEntry *entry = new TGLVEntry(fFileCont,name,cname); entry->SetSubnames(key->GetTitle()); fFileCont->AddItem(entry); // user data is a filename entry->SetUserData((void*)StrDup(fname)); } Resize(); TThread::UnLock(); //unlock the main mutex } void TOnlineFrame::DisplayObject(const TString& fname,const TString& name) { // browse object located in file if(!datafile) return; TDirectory *sav = gDirectory; static TFile *file = 0; TThread::Lock(); //lock the main mutex file = (TFile *) gROOT->GetListOfFiles()->FindObject(fname.Data()); TThread::UnLock(); //unlock the main mutex if(!file) return; TThread::Lock(); //lock the main mutex TObject* obj = file->Get(name); if (obj) { if (!obj->IsFolder()) { candaq->cd(0); DrawObj(obj); } else obj->Print(); } gDirectory = sav; TThread::UnLock(); //unlock the main mutex } void TOnlineFrame::DisplayDirectory(const TString &fname) { // display content of directory TThread::Lock(); //lock the main mutex fFileCont->SetDefaultHeaders(); gSystem->ChangeDirectory(fname); fFileCont->ChangeDirectory(fname); fFileCont->DisplayDirectory(); fFileCont->AddFile(".."); // up level directory Resize(); TThread::UnLock(); //unlock the main mutex } void TOnlineFrame::ImB_update() { if(!candaq) return; if(!ObjListOK()) return; // int nx=1, ny=1; // GetDivPad(nx, ny); TThread::Lock(); //lock the main mutex if(candaq->GetPad(1)) { for(int i=1; i<30; i++) { if(candaq->GetPad(i)) { candaq->cd(i); gPad->Modified(); gPad->Update(); } } } else { gPad->Modified(); gPad->Update(); } TThread::UnLock(); //unlock the main mutex } void TOnlineFrame::ImB_next() { DrawObj(kB_next); //if(!ObjListOK()) return; //do //{ // DrawObj(ObjList->After(objcurr)); //}while(!(objcurr->IsA()->InheritsFrom("TH1"))); } void TOnlineFrame::ImB_previous() { DrawObj(kB_privious); //if(!ObjListOK()) return; //do //{ // DrawObj(ObjList->Before(objcurr)); //}while(!(objcurr->IsA()->InheritsFrom("TH1"))); } bool TOnlineFrame::ObjListOK() { if( objcurr && ObjList ) { return true; } else { return false; } } void TOnlineFrame::DrawObj(TObject *obj) { if(!obj) return; if(!candaq) return; TThread::Lock(); //lock the main mutex obj->Draw(GetDrawOpt()); candaq->Update(); objcurr = obj; TThread::UnLock(); //unlock the main mutex } void TOnlineFrame::DrawObj(CMDIdentifiers id) { if(!ObjListOK()) return; TThread::Lock(); //lock the main mutex candaq->Clear(); int nx=1, ny=1; GetDivPad(nx, ny); if(nx*ny>2) { candaq->Divide(nx, ny); candaq->SetLogy(); } if(id == kB_privious) { for(int np=nx*ny; np>=1; np--) { candaq->cd(np); unsigned int lx =0, ly =0; GetAxisOpt(lx, ly); gPad->SetLogx(lx); gPad->SetLogy(ly); do { TObject *tobj = ObjList->Before(objcurr); if(tobj) { if(tobj->IsEqual(ObjList->First())) { DrawObj(tobj); break; } DrawObj(tobj); } else { break; } }while(!(objcurr->IsA()->InheritsFrom("TH1"))); } } else if(id == kB_next) { for(int np=1; np<=nx*ny; np++) { candaq->cd(np); unsigned int lx =0, ly =0; GetAxisOpt(lx, ly); gPad->SetLogx(lx); gPad->SetLogy(ly); do { TObject* tobj = ObjList->After(objcurr); if(tobj) { if(tobj->IsEqual(ObjList->Last())) { DrawObj(tobj); break; } DrawObj(tobj); } else { break; } }while(!(objcurr->IsA()->InheritsFrom("TH1"))); } } TThread::UnLock(); //unlock the main mutex } void TOnlineFrame::ImB_ResetAllTH() { if(!ObjListOK()) return; TThread::Lock(); //lock the main mutex TIter next(ObjList); while(TObject *obj = next()) { ResetTH(obj); } ImB_update(); if(tree) tree->Reset(); TThread::UnLock(); //unlock the main mutex } void TOnlineFrame::ImB_ResetCurrTH() { if(!ObjListOK()) return; TThread::Lock(); //lock the main mutex ResetTH(objcurr); ImB_update(); TThread::UnLock(); //unlock the main mutex } void TOnlineFrame::ResetTH(TObject *obj) { TThread::Lock(); //lock the main mutex if (obj && (obj->IsA()->InheritsFrom("TH1"))) { ((TH1 *)obj)->Reset(); } TThread::UnLock(); //unlock the main mutex } void TOnlineFrame::ImB_integral() { if(!objcurr) return; if(!candaq) return; if(candaq->GetPad(1)) return; //skip divide pad,pad_0 is not divide TThread::Lock(); //lock the main mutex TString cname = objcurr->IsA()->GetName(); TThread::UnLock(); //unlock the main mutex if(!cname.Contains("TH1", TString::kIgnoreCase)) return; TThread::Lock(); //lock the main mutex ShowText("Select the left bin with mouse:"); TThread::UnLock(); //lock the main mutex TMarker *p1 = (TMarker *)gPad->WaitPrimitive("TMarker"); float left = 0.; if (p1) { p1->SetMarkerStyle(3); p1->SetMarkerColor(2); p1->SetMarkerSize(2.5); p1->Draw(); left = p1->GetX(); } delete p1; TString text_xl = "X1= "; text_xl += left; TThread::Lock(); //lock the main mutex ShowText(text_xl.Data()); ShowText("Select the right bin with mouse:"); TThread::UnLock(); //unlock the main mutex TMarker *p2 = (TMarker *)gPad->WaitPrimitive("TMarker"); float right = 0.; if (p2) { p2->SetMarkerStyle(3); p2->SetMarkerColor(2); p2->SetMarkerSize(2.5); p2->Draw(); right = p2->GetX(); } if(left>right) { float xxt = left; left = right; right = xxt; } p2->Delete(); TString text_xr = "X2= "; text_xr += right; TThread::Lock(); //lock the main mutex ShowText(text_xr.Data()); TAxis *xaxis = ((TH1*)objcurr)->GetXaxis(); int xlbin = xaxis->FindBin(left); int xrbin = xaxis->FindBin(right); double numb = ((TH1*)objcurr)->Integral(xlbin, xrbin); float tentries = ((TH1*)objcurr)->GetEntries(); TThread::UnLock(); //unlock the main mutex float per=0.0; if(tentries>0) { per = numb*100./(tentries); } TString text_inte = "Integral: "; text_inte += numb; TThread::Lock(); ShowText(text_inte); TThread::UnLock(); TString text_per = "Percent: "; //TString data_per = "p"; char s[32]; sprintf(s, "%.5f", per); TString data_per = s; TString data_per1 = data_per(0, 4); text_per += data_per1; text_per += "%"; TThread::Lock(); ShowText(text_per.Data()); TThread::UnLock(); TString stime = "Integral tiem: "; time_t nowtime; time(&nowtime); struct tm * timeinfo; timeinfo = localtime(&nowtime); TString ltime = asctime(timeinfo); stime += ltime(11, 8); TThread::Lock(); ShowText(stime.Data()); ShowText(" "); TThread::UnLock(); // p1->Delete(); // p2->Delete(); } void TOnlineFrame::GetDivPad(int &nx, int &ny) { nx = 1; ny = 1; int n = fcomDivPad->GetSelected(); switch(n) { case 0: nx = 1; ny = 1; break; case 1: nx = 2; ny = 2; break; case 2: nx = 2; ny = 3; break; case 3: nx = 3; ny = 3; break; default: break; } } void TOnlineFrame::RemoveMenuEntry(const char *menuTitle, TList *mlist) { TClassMenuItem *menuItem = 0; TString itemTitle; if(!mlist) return; TIter next(mlist); while( menuItem = (TClassMenuItem *)next() ) { itemTitle = menuItem->GetTitle(); if( itemTitle == menuTitle) { delete menuItem; break; } } } void TOnlineFrame::MakeTcMenuList() { TClass *c_TCanvas = gROOT->GetClass("TCanvas"); if(!c_TCanvas) return; c_TCanvas->MakeCustomMenuList(); TCmlist = c_TCanvas->GetMenuList(); } void TOnlineFrame::MakeTH1MenuList() { TClass *c_TH1 = gROOT->GetClass("TH1F"); if(!c_TH1) return; c_TH1->MakeCustomMenuList(); THmlist = c_TH1->GetMenuList(); } void TOnlineFrame::MakeTH2MenuList() { TClass *c_TH2 = gROOT->GetClass("TH2F"); if(!c_TH2) return; c_TH2->MakeCustomMenuList(); TH2mlist = c_TH2->GetMenuList(); } void HBOOK1(int id, const char *title, int nxbin, float xlow, float xup, float vmx) { if(!(gOnlineFrame->datafile)) return; TString hname = "h"; hname += id; new TH1F(hname.Data(), title, nxbin, xlow, xup); } void HBOOK2(int id, const char *title, int nxbin, float xlow, float xup, int nybin, float ylow, float yup, float vmx) { if(!(gOnlineFrame->datafile)) return; TString hname = "h"; hname += id; new TH2F(hname.Data(), title, nxbin, xlow, xup, nybin, ylow, yup); } void HF1(int id, float x, float weight) { if(!(gOnlineFrame->datafile)) return; TString name = "h"; name += id; if(gOnlineFrame->datafile->Get(name.Data())) ((TH1F *)(gOnlineFrame->datafile->Get(name.Data())))->Fill(x, weight); } void HF2(int id, float x, float y, float weight) { if(!(gOnlineFrame->datafile)) return; TString name = "h"; name += id; if(gOnlineFrame->datafile->Get(name.Data())) ((TH2F *)(gOnlineFrame->datafile->Get(name.Data())))->Fill(x, y, weight); } bool HEXIST(int ihist) { if(!(gOnlineFrame->datafile)) return false; TString name = "h"; name += ihist; if(gOnlineFrame->datafile->Get(name.Data())) return true; return false; } <file_sep>/ribllvmedaq/TCBLT.cpp //////////////////////////////////////////////////////////////// // TREADOUT and TCBLT class source implementation // Modified by <NAME> 07/2012 // Changes: // 1. Add comment lines in cblt setting files, skip using'*' //////////////////////////////////////////////////////////////// #include <string> #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <exception> using namespace std; #include "caenacq.h" #include "TCBLT.h" #include "TString.h" /////////////////////////////////////////// // The TREADOUT class implementation // /////////////////////////////////////////// // swap bytes on 32 bit longword from VME format to // Linux ones //void TReadout::swap32(unsigned int *buffer, int max) //{ // union dwor { // long dat; // unsigned char wrd[4]; // }; // // dwor comp; // unsigned char temp; // unsigned int *p1=buffer, *p2=&buffer[max-1]; // // for(; p1<=p2; p1++) { // comp.dat = *p1; // temp = comp.wrd[0]; // comp.wrd[0] = comp.wrd[3]; // comp.wrd[3] = temp; // temp = comp.wrd[2]; // comp.wrd[2] = comp.wrd[1]; // comp.wrd[1] = temp; // *p1 = comp.dat; // } //} TReadout::TReadout(int dim) { if(dim >= 8192) { fbufdim = dim; } else { fbufdim = VME_Crate_BufLENGTH; } try { fiobuf = new char[fbufdim]; } catch(bad_alloc& ba) { cout << "TReadout>> do not have "<< dim << " bytes memory for allocation." << ba.what() << endl; } if(fiobuf) memset(fiobuf, 0x0, fbufdim); } TReadout::~TReadout() { SafeDeleteArr(fiobuf); } /////////////////////////////////////////// // The TCBLT class implementation // /////////////////////////////////////////// //copy constructor TCBLT::TCBLT(TCBLT const &other) { try { fbase = new int[other.fchains]; fdummy = new int[other.fchains]; fnum = new int[other.fchains]; } catch(exception &ex) { cout<<"TCBLT >> " << ex.what() << endl; } for(int i=0; i<other.fchains; i++) { fbase[i] = other.fbase[i]; fdummy[i] = other.fdummy[i]; fnum[i] = other.fnum[i]; } fchains = other.fchains; fwait_for_ready = other.fwait_for_ready; foffset = other.foffset; } //overloading the assignment operator TCBLT &TCBLT::operator=(TCBLT const &other) { if(this != &other) { SafeDeleteArr(fbase); SafeDeleteArr(fdummy); SafeDeleteArr(fnum); try { fbase = new int[other.fchains]; fdummy = new int[other.fchains]; fnum = new int[other.fchains]; } catch(exception &ex) { cout<<"TCBLT >> " << ex.what() << endl; } for(int i=0; i<other.fchains; i++) { fbase[i] = other.fbase[i]; fdummy[i] = other.fdummy[i]; fnum[i] = other.fnum[i]; } fchains = other.fchains; fwait_for_ready = other.fwait_for_ready; foffset = other.foffset; } return *this; } TCBLT::~TCBLT() { SafeDeleteArr(fnum); SafeDeleteArr(fdummy); SafeDeleteArr(fbase); } //Get CBLT configuration int TCBLT::Get_CBLT_Config(string name, int crate) { int num = 0; unsigned int addr, nboard, mask; const char *fname; char line[300]; TString checkline; ostringstream filen(name,ios::ate); filen<<crate; filen<<".dat"; name = filen.str(); fname = name.c_str(); ifstream in(fname); try{ if(in) { while(in.getline(line, sizeof(line))) // skip the comment lines by using '*' { checkline = line; checkline.ReplaceAll(" ", ""); checkline.ReplaceAll("\t", ""); if(checkline.Length() > 0 && checkline[0] != '*') break; }; if(checkline.IsDigit()) num = checkline.Atoi(); if(num>0) { fchains = num; fbase = new int[num]; fdummy = new int[num]; fnum = new int[num]; for(int i=0; i<num; i++) { in>>hex>>addr; in>>dec>>nboard; in>>hex>>mask>>dec; if(in.fail()) { cout << "Read CBLT setting file: " << name.c_str() << " error!" <<endl; } if(nboard==0)break; fbase[i] = addr; fdummy[i] = addr | mask; fnum[i] = nboard; } } } else { cout << " TCBLT>>Config file: " << fname << " open error. "<< endl; return -1; } } catch(ifstream::failure e) { cout <<" TCBLT>>CBLT file: "<< fname << " read error!" << e.what() << endl; } in.close(); cout<<"TCBLT>>Read CBLT config.: "<<fname<<" for crate "<<crate<<endl; return 0; } int TCBLT :: GetChainBoard(int chain) { if(chain>fchains) return 0; else return fnum[chain-1]; } void TCBLT::PrintCBLTInfo() { cout<<"CBLT>>: chains = "<<fchains<<endl; for(int i=0; i<fchains; i++) { cout<<"CBLT>>: Nboards = "<<setw(2)<<fnum[i]<<" Dummy address = 0x"<<hex<<fdummy[i]<< " Base address = 0x"<<hex<<fbase[i]<<dec<<endl; cout<<dec; } } <file_sep>/ribllvmedaq/TDataReceiver.h //////////////////////////////////////////////// // TDataReceiver.h: Receive data form UDP // broadcast socket, and write them to disk // file. // <NAME> (08/2012) /////////////////////////////////////////////// #ifndef TDataReceiver_H #define TDataReceiver_H #include "caenacq.h" class TUDPServerSocket; class TDataReceiver { protected: static unsigned int fdatabuf[NETBUFFER/4]; static TUDPServerSocket *UDPDataRec; public: static int eventcounter; //value of envent number from received data(the second int value) public: TDataReceiver(unsigned int iport); virtual ~TDataReceiver(); static int ReceiveData(); static bool IsUDPValid(); unsigned int *GetDataBuf(){return fdatabuf;} bool CloseRecDataSocket(); bool OpenRecDataSocket(); }; #endif //#ifndef TDataReceiver_H<file_sep>/ribllvmedaq/UserVMEFuncitons.cpp ///////////////////////////////////////////////////// // UserVMERead.cpp: Define two VME Read Function // Some modules can not be read by using CBLT, or // the user want to read the VME module for some // special purpose, in this case, the user can write // some thing in this file. // <NAME> 08/2012 ///////////////////////////////////////////////////// ////************************************************//// //// All data read form VME modules must be 32bit //// width. If the modules only support 16bit data //// mode, you must completing the data to 32bit. ////************************************************//// #include "caenacq.h" #include "CAENVMEtypes.h" #include "CAENVMElib.h" #include "TConfig.h" /////////////////////////////////////////////////////// // Use the "#define UserVMEFunction.." in 'caenacq.h' // to switch on this two functions. /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// // This function defined some thing you want the // program to do #before# the normal CBLT reading that // you defined in the 'config' files. // Read the content of each function carefully // include the comments carefully before writing // your own function. /////////////////////////////////////////////////////// // Variables Note: // buff: the pointer to the buffer where the read // data to be saved. // buff is a pointer, it need to be increased // with the real read number of 'int's // // gconfig: the TConfig class (always build in the // 'main' function, and then transfer to // the TEvtBuilder), used to get the // Handle by using the 'Crate Number'. // // rsize: return the real read number of 'int' // // All functions defined in "CAENVMElib.h" can be // called in this function. /////////////////////////////////////////////////////// int VMEReadBeforeCBLT(unsigned int*& buff, TConfig &gconfig) { ////************************************************//// //// All data read form VME modules must be 32bit //// width. If the modules only support 16bit data //// mode, you must completing the data to 32bit. ////************************************************//// //unsigned int fCrate = 1; //int fHandle = gconfig.GetHandle(fCrate); // get the VME handle by using the crate number; //if(fHandle) //{ //write the crate header and "data marker" to buff^^^^^^ // const int header_w = 8; // *buff = Crate_Header; // *(buff+1) = fCrate; // buff += header_w; // *buff = 0x2A00FFFF; // buff++; //write the crate header and "data marker" to buff------ // int rlen=0; // int SIZE = 256; // int rsize = 0; // int Address = 0x20040000; // the VME bus address // CVErrorCodes res=CAENVME_BLTReadCycle(fHandle, Address, (unsigned char *)buff, SIZE, cvA32_U_BLT, cvD32, &rlen); // if(res == cvSuccess) // { // rsize = rlen>>2; // rlen is the length in byte, '>>' transfered it to int(very important) // buff += rsize; // increase the pointer 'buff', the pointer 'buff' will be used in the following reading(very important) // return rsize; // return the real length in int size(very important) // } // *buff = 0x2A00FFFF; // buff++; //} return 0; //un-normal return } ////////////////////////////////////////////////////// // This function defined some thing you want the // program to do #after# the normal CBLT reading that // you defined in the 'config' files. // Read the content of each function carefully // include the comments carefully before writing // your own function. ////////////////////////////////////////////////////// // Variables Note: // buff: the pointer to the buffer where the read // data to be saved. // buff is a pointer, it need to be increased // with the real read number of 'int's // // gconfig: the TConfig class (always build in the // 'main' function, and then transfer to // the TEvtBuilder), used to get the // Handle by using the 'Crate Number'. // // rsize: return the real read number of 'int' // // All functions defined in "CAENVMElib.h" can be // called in this function. ////////////////////////////////////////////////////// int VMEReadAfterCBLT(unsigned int* &buff, TConfig &gconfig) { ////************************************************//// //// All data read form VME modules must be 32bit //// width. If the modules only support 16bit data //// mode, you must completing the data to 32bit. ////************************************************//// //unsigned int fCrate = 1; //int fHandle = gconfig.GetHandle(fCrate); // get the VME handle by using the crate number; //if(fHandle) //{ //write the crate header and "data marker" to buff^^^^^^ // const int header_w = 8; // *buff = Crate_Header; // *(buff+1) = fCrate; // buff += header_w; // *buff = 0x2B00FFFF; // buff++; //write the crate header and "data marker" to buff------ // int rlen=0; // int SIZE = 256; // int rsize = 0; // int Address = 0x20040000; // the VME bus address // CVErrorCodes res=CAENVME_BLTReadCycle(fHandle, Address, (unsigned char *)buff, SIZE, cvA32_U_BLT, cvD32, &rlen); // if(res == cvSuccess) // { // rsize = rlen>>2; // rlen is the length in byte, '>>' transfered it to int(very important) // buff += rsize; // increase the pointer 'buff', the pointer 'buff' will be used in the following reading(very important) // return rsize; // return the real length in int size(very important) // } // *buff = 0x2B00FFFF // buff++; //} return 0; //un-normal return } <file_sep>/ribllvmedaq/TVMELink.cpp ////////////////////////////////////////////////////////// // TVMELink.cpp include file interfaces // TVME class interface: V2718 manager // These classes define the DAQ hardware configuration // E.d.F (08/2007) test version v.07 // (Modified by <NAME> 07/2012) // caen lib wrapper not yet implemented ///////////////////////////////////////////////////////// #include <iostream> #include <cstring> using namespace std; #include "TVMELink.h" #include "CAENVMElib.h" ///////////////////////////////////////////////////////////////////////////////// //static variables initialization ///////////////////////////////////////////////////////////////////////////////// map<int,int> TVMELink::flookup_ind; ///////////////////////////////////////////////////////////////////////////////// //constructor ///////////////////////////////////////////////////////////////////////////////// TVMELink::TVMELink(CVBoardTypes ControlBoardType, short PCILinkNum, short VMEControlBoardNum, int crate) { fControlBoardType = ControlBoardType; fPCILinkNum = PCILinkNum; fVMEControlBoardNum = VMEControlBoardNum; fCrate = crate; fStatus = cvGenericError; fHandle = -1; } ///////////////////////////////////////////////////////////////////////////////// //copy constructor ///////////////////////////////////////////////////////////////////////////////// TVMELink::TVMELink(const TVMELink &source) { copy(source); } ///////////////////////////////////////////////////////////////////////////////// //Init PCI-VME link ///////////////////////////////////////////////////////////////////////////////// int TVMELink::Init() { if(fHandle>=0) //protecting multi-call of this Init() { CVErrorCodes check = CAENVME_BoardFWRelease(fHandle, fHwrel); if(check == cvSuccess) { return check; } else { CAENVME_End(fHandle); } } //cout <<"CrateNum: " <<fCrate << " PCILinkNUM: " << fPCILinkNum << " ControlBoardNum: " << fVMEControlBoardNum <<endl; CVErrorCodes res = CAENVME_Init(fControlBoardType, fPCILinkNum, fVMEControlBoardNum, &fHandle); if(res != cvSuccess) { cout<<"Fatal error: "<<res<<" of initializing V2718. PCIDeviceNum "<<fPCILinkNum<<" ControlBoardNum "<<fVMEControlBoardNum << " Handle " <<fHandle<<endl; fHandle = -1; } else { cout<<"V2718>> PCIDeviceNum "<<fPCILinkNum<<" ControlBoardNum "<<fVMEControlBoardNum<<" initialized "<< " Handele " << fHandle<<endl; CAENVME_BoardFWRelease(fHandle, fHwrel); CAENVME_SWRelease(fSwrel); cout<<"Hardware release: "<<fHwrel<<" Software release: "<<fSwrel<<endl; flookup_ind[fCrate] = fHandle; } fStatus = (CVErrorCodes )res; return res; } ///////////////////////////////////////////////////////////////////////////////// //Configure IO-output port ///////////////////////////////////////////////////////////////////////////////// CVErrorCodes TVMELink::InitIOPort(CVOutputSelect out, CVIOPolarity pol, CVLEDPolarity led) { if(fHandle>=0) { return (CVErrorCodes)CAENVME_SetOutputConf(fHandle, out, pol, led, cvManualSW); } else { cout<<"InitIOPort>> no valid handler given"<<endl; return (CVErrorCodes)cvGenericError; } } ///////////////////////////////////////////////////////////////////////////////// //Set the IO-output port ///////////////////////////////////////////////////////////////////////////////// CVErrorCodes TVMELink::SetIOPort(CVOutputRegisterBits cvbit) { if(fHandle>=0) { return (CVErrorCodes)CAENVME_SetOutputRegister(fHandle, cvbit); } else { cout<<"SetIOPort>> "<< cvbit <<" no valid handler given"<<endl; return (CVErrorCodes)cvGenericError; } } ///////////////////////////////////////////////////////////////////////////////// //Clear the IO-output port ///////////////////////////////////////////////////////////////////////////////// CVErrorCodes TVMELink::ClearIOPort(CVOutputRegisterBits cvbit) { if(fHandle>=0) { return (CVErrorCodes)CAENVME_ClearOutputRegister(fHandle, cvbit); } else { cout<<"ClearIOPort>> " << cvbit <<" no valid handler given"<<endl; return (CVErrorCodes)cvGenericError; } } CVErrorCodes TVMELink::PulseOutput(CVOutputRegisterBits cvbit) { if(fHandle>=0) { return (CVErrorCodes)CAENVME_PulseOutputRegister(fHandle, cvbit); } else { cout<<"PulseIOPort>> "<< cvbit << " no valid handler given"<<endl; return (CVErrorCodes)cvGenericError; } } void TVMELink::copy(const TVMELink &source) { fHandle = source.fHandle; strncpy(fHwrel, source.fHwrel, sizeof(fHwrel)); strncpy(fSwrel, source.fSwrel, sizeof(fSwrel)); fStatus = source.fStatus; fControlBoardType = source.fControlBoardType; fPCILinkNum = source.fPCILinkNum; fVMEControlBoardNum = source.fVMEControlBoardNum; fCrate = source.fCrate; } TVMELink::~TVMELink() { //CAENVME_End(fHandle); } CVErrorCodes TVMELink::EndVMEHandle() { if(fHandle>=0) return CAENVME_End(fHandle); return cvInvalidParam; }<file_sep>/ribllvmedaq/TUDPServerSocket.h //////////////////////////////////////////////// // TUDPServerSocket.h: // receive broadcasted data UDPSocket // receive data from ethernet // <NAME> 07/2012 test version v.01 //////////////////////////////////////////////// #ifndef TUDPServerSocket_H #define TUDPServerSocket_H #ifdef _WIN32 #include <winsock2.h> #include <Ws2tcpip.h> #include <windows.h> #pragma comment(lib,"Ws2_32.lib") #else #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> /* close() */ #endif class TUDPServerSocket { private: int isocket; unsigned int iport; struct sockaddr_in cliAddr, servAddr; public: TUDPServerSocket(){isocket = 0;} TUDPServerSocket(unsigned int port); virtual ~TUDPServerSocket(); virtual unsigned int RecvRaw(char *buff, int max_len); bool IsValid(){return isocket < 0 ? false : true;} bool CloseCleanSocket(); bool OpenInitSocket(); bool SetRcvTimeOutValue(unsigned int msec); bool JoinMemberShip(const char *MC_IP); }; #endif//#ifndef TUDPServerSocket_H<file_sep>/ribllvmedaq/ReadRootFile2D.cpp /////////////////////////////////////////////// // An Raw2ROOT.cpp: main() of Raw2ROOT, used // for offline data analysis. // <NAME> (08/2012) /////////////////////////////////////////////// #include "TApplication.h" #include "TDAQApplication.h" #include "TConfig.h" #include "TDataFileReader.h" #include "TDataAnalyser.h" #include "TString.h" #include "TFile.h" #include "TTree.h" #include "TH1F.h" #include "TH2F.h" #include "TSystem.h" #include "TBoard.h" #include "TModV830AC.h" #include "TModV785.h" #include "TModV785N.h" #include "TModV775.h" #include "TModV775N.h" #include "TModV792.h" #include <iostream> #include <sstream> #include <fstream> #include <stdlib.h> #include <vector> #include <map> using namespace std; //const string gDataPath = "DAQDataPath"; void PrintUsage(char *name); int main(int argc, char *argv[]) { string rawlist, rawfile; string dfname; unsigned int evtana=0; unsigned int startn=0; fstream listf; vector<string> rawdfname; bool inter = false; TTree *tree = 0; TFile *rfile = 0; char hname[200],htitle[200],filenm[200]; float CsIPed[] = {791.224, 733.772, 716.835, 752.535, 740.792, 754.421, 785.629, 757.22, 739.371, 753.769, 754.408, 742.717, 776.927, 772.875, 741.235, 730.316, 749.794, 786.005, 782.26, 736.172, 736.419, 746.37, 761.024, 763.659, 787.169, 734.829, 728.259, 761.132, 759.596, 763.009, 738.832, 766.617, 738.109, 751.077, 722.741, 744.124, 732.656, 742.131, 706.622, 732.266, 769.737, 711.194, 708.261, 733.68, 732.049, 738.579, 721.986, 740.498, 747.381, 735.941, 733.564, 747.507, 764.418, 744.072, 699.297, 742.641, 760.289, 752.968, 740.611, 752.148, 710.252, 743.344, 738.181, 749.896}; float StSiJThr[16] = {66.3503, 18.8228, 47.8497, 20.9574, 37.6425, 59.59, 34.9703, 53.3155, 55.4295, 26.5014, 39.3096, 58.5759, 64.7845, 26.2401, 55.5407, 49.6467}; float StSiOThr[16] = {86.2438, 46.0111, 70.3495, 64.9409, 82.8725, 61.7663, 59.014, 41.7415, 86.8275, 71.0645, 82.4644, 52.2838, 68.0827, 44.6543, 87.3318, 42.1333}; float StSiJCali[16][2] = { -0.531595, 0.018054, 0.290962, 0.0182303, -0.177645, 0.0179291, 0.2904, 0.0181098, 0.00194314, 0.0183419, -0.361781, 0.0180004, 0.0444717, 0.0182675, -0.253003, 0.0182711, -0.229327, 0.0176175, 0.255263, 0.0179991, 0.0596223, 0.0181894, -0.267419, 0.0181743, -0.357636, 0.0178602, 0.265927, 0.0183105, -0.269501, 0.0183474, -0.138062, 0.0176564}; float StSiOCali[16][2] = { -0.899932, 0.0183196, -0.113776, 0.0181846, -0.599779, 0.0182771, -0.403109, 0.01824, -0.720776, 0.0181904, -0.42725, 0.0184066, -0.396009, 0.0181221, 0.49317, 0.0172697, -0.908054, 0.0179679, -0.633511, 0.0183386, -0.823064, 0.017952, -0.283395, 0.0176819, -0.60907, 0.0181285, -0.144706, 0.017986, -0.861611, 0.0181782, -0.240838, 0.0179486}; // postion parameters for SiStrip and CsI float posxCsI[64]={-3.5, -3.5, -3.5, -3.5, -3.5, -3.5, -3.5, -3.5, -2.5, -2.5, -2.5, -2.5, -2.5, -2.5, -2.5, -2.5, -1.5, -1.5, -1.5, -1.5, -1.5, -1.5, -1.5, -1.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5,- 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5}; float posyCsI[64]={-3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5}; float posxStSi[16]={-7.5,-6.5,-5.5,-4.5,-3.5,-2.5,-1.5,-0.5,0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5}; float posyStSi[16]={-7.5,-6.5,-5.5,-4.5,-3.5,-2.5,-1.5,-0.5,7.5,6.5,5.5,4.5,3.5,2.5,1.5,0.5}; //float posySiSt[16]={0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,-0.5,-1.5,-2.5,-3.5,-4.5,-5.5,-6.5,-7.5}; TFile fout("/home/vip/data/ppac201407/20140815.root","recreate"); fout.cd(); TH2F *h2SiCsIF[64],*h2SiCsIS[64]; for(int i=0;i<64;i++) { sprintf(hname,"h2SiCsI%dFast",i+1); h2SiCsIF[i]=new TH2F(hname,hname,200,-0.5,4099.5,200,-1.0,49); sprintf(hname,"h2SiCsI%dSlow",i+1); h2SiCsIS[i]=new TH2F(hname,hname,200,-0.5,4099.5,200,-1.0,49); } // TModV785N *vmod104 = new TModV785N(); // Square Si at 0 TModV775N *vmod105 = new TModV775N(); // Timing for TOF && PPAC TModV775N *vmod106 = new TModV775N(); // Timing for TOF && PPAC TModV775N *vmod107 = new TModV775N(); // Timing for PPAC TModV775N *vmod108 = new TModV775N(); // Timing for 10 neutrons at 0-9, for trigger at 10 TModV785 *vmod110 = new TModV785(); // ADC for 16+16 StSi TModV792 *vmod112 = new TModV792(); // QDC for 10 neutron slow(?) gate TModV792 *vmod113 = new TModV792(); // QDC for 10 neutron total(?) gate TModV792 *vmod115 = new TModV792(); // 32 CsI QDC Fast TModV792 *vmod116 = new TModV792(); // 32 CsI QDC Fast TModV792 *vmod118 = new TModV792(); // 32 CsI QDC Slow TModV792 *vmod119 = new TModV792(); // 32 CsI QDC Slow // Loop on file int totalsel; totalsel=0; for (int ifile=210;ifile<211;ifile++) { if(ifile<10) sprintf(filenm,"/home/vip/data/ppac201407/data/Li9Pb208000%d.root",ifile); else if(ifile<100) sprintf(filenm,"/home/vip/data/ppac201407/data/Li9Pb20800%d.root",ifile); else sprintf(filenm,"/home/vip/data/ppac201407/data/Li9Pb2080%d.root",ifile); if(gSystem->AccessPathName(filenm)) { printf("no data existing for %s\n",filenm); continue; } cout<<filenm<<endl; TFile f(filenm) ; TTree *fChain = (TTree*)gFile->Get("RawData");//fChain can be a TChain TBranch *bran103 = 0; TBranch *bran104 = 0; TBranch *bran106 = 0; TBranch *bran107 = 0; TBranch *bran108 = 0; TBranch *bran110 = 0; TBranch *bran112 = 0; TBranch *bran113 = 0; TBranch *bran115 = 0; TBranch *bran116 = 0; TBranch *bran118 = 0; TBranch *bran119 = 0; fChain->SetBranchAddress("Mod104_TModV785N", &vmod104, &bran104); fChain->SetBranchAddress("Mod106_TModV775N", &vmod106, &bran106); fChain->SetBranchAddress("Mod107_TModV775N", &vmod107, &bran107); fChain->SetBranchAddress("Mod110_TModV785", &vmod110, &bran110); fChain->SetBranchAddress("Mod115_TModV792", &vmod115, &bran115); fChain->SetBranchAddress("Mod116_TModV792", &vmod116, &bran116); fChain->SetBranchAddress("Mod118_TModV792", &vmod118, &bran118); fChain->SetBranchAddress("Mod119_TModV792", &vmod119, &bran119); Long64_t nentries = fChain->GetEntriesFast(); cout << "nentries=" << nentries << endl; int MulStSiJ,MulStSiO,MulCsIF,MulCsIS,iSelEvt,iCsIF[64],iCsIS[64],i0; float Threshold,EStSiJ[16],EStSiO[16],xStSi[16],yStSi[16],chCsIF[64],xCsIF[64],yCsIF[64],chCsIS[64],xCsIS[64],yCsIS[64]; iSelEvt=0; float ESiJ,ESiO,EtotJ,EtotO; // for(int ientry=0;ientry<nentries;ientry++) for (Long64_t ientry=0; ientry<5;ientry++) { Long64_t jentry = fChain->LoadTree(ientry); if (jentry < 0) break; fChain->GetEntry(ientry); //do some analysis int t1 = vmod107->chdata[0]; int t2 = vmod107->chdata[1]; int tof = t2-t1; int dE = vmod104->chdata[0]; cout <<" chdata 0 "<< vmod106->chdata[0]<<" chdata 5 "<< vmod106->chdata[5]<<" chdata10 "<< vmod106->chdata[10] << endl; if((tof<-740&&tof>-790&&dE>800&&dE<1100)) continue; // Fill 1D histograms for Si and CsI and do some multiplicity analysis MulStSiJ=0; MulStSiO=0; EtotJ=0; EtotO=0; for(int i=0;i<16;i++) { ESiJ=vmod110->chdata[i]*StSiJCali[i][1]+StSiJCali[i][0]; EtotJ+=ESiJ; ESiO=vmod110->chdata[i+16]*StSiOCali[i][1]+StSiOCali[i][0]; EtotO+=ESiO; if(ESiJ>0.9) { EStSiJ[MulStSiJ]=ESiJ; xStSi[MulStSiJ]=posxStSi[i]*3; MulStSiJ++; } if(ESiO>0.9) { EStSiO[MulStSiO]=ESiO; yStSi[MulStSiO]=posyStSi[i]*3; MulStSiO++; } } MulCsIF=0; MulCsIS=0; for(int i=0;i<32;i++) { if(vmod115->chdata[i]>100) { chCsIF[MulCsIF]=vmod115->chdata[i]; xCsIF[MulCsIF]=posxCsI[i]*25; yCsIF[MulCsIF]=posyCsI[i]*25; iCsIF[MulCsIF]=i; MulCsIF++; } if(vmod116->chdata[i]>100) { chCsIF[MulCsIF]=vmod116->chdata[i]; xCsIF[MulCsIF]=posxCsI[i+32]*25; yCsIF[MulCsIF]=posyCsI[i+32]*25; iCsIF[MulCsIF]=i+32; MulCsIF++; } if(i!=3) { if(vmod118->chdata[i]>150) { chCsIS[MulCsIS]=vmod118->chdata[i]; xCsIS[MulCsIS]=posxCsI[i]*25; yCsIS[MulCsIS]=posyCsI[i]*25; iCsIS[MulCsIS]=i; MulCsIS++; } if(vmod119->chdata[i]>150) { chCsIS[MulCsIS]=vmod119->chdata[i]; xCsIS[MulCsIS]=posxCsI[i+32]*25; yCsIS[MulCsIS]=posyCsI[i+32]*25; iCsIS[MulCsIS]=i+32; MulCsIS++; } } } // if(MulStSiJ==1&&MulStSiO==1&&MulCsIS==1) { for(int i=0;i<MulCsIF;i++) { i0=iCsIF[i]; for(int j=0;j<MulStSiJ;j++) { h2SiCsIF[i0]->Fill(chCsIF[i],EStSiJ[j],1.0); } } for(int i=0;i<MulCsIS;i++) { i0=iCsIS[0]; for(int j=0;j<MulStSiJ;j++) { h2SiCsIS[i0]->Fill(chCsIS[i],EStSiJ[j],1.0); } } // } /* if( MulCsIF>=3&&MulCsIS>=3) { // if(MulStSiJ==1&&MulStSiO==1&&MulCsIS==1) { iSelEvt++; cout << "ievent=" << ientry << endl; cout << "CsI" << endl; for(int i=0;i<MulCsIF;i++) { cout <<"CsI Fast" << i << ": "<< chCsIF[i] << " x=" << xCsIF[i] << " y=" << yCsIF[i] <<endl; } for(int i=0;i<MulCsIS;i++) { cout <<"CsI Slow" << i << ": "<< chCsIS[i] << " x=" << xCsIS[i] << " y=" << yCsIS[i] <<endl; } cout << "StSiJ:" << endl; cout << "EtotJ=" << EtotJ << endl; for(int i=0;i<MulStSiJ;i++) { cout << "StSiJ" << i << ": " << EStSiJ[i] << " x=" << xStSi[i] << endl; } cout << "StSiO:" << endl; cout << "EtotO=" << EtotO << endl; for(int i=0;i<MulStSiO;i++) { cout << "StSiO" << i << ": " << EStSiO[i] << " y=" << yStSi[i] << endl; } cout << endl; } */ } totalsel+=iSelEvt; cout << "ifile=" << ifile<< " iSelEvt=" << iSelEvt << endl; cout << endl; f.Close(); } cout << "total selected events=" << totalsel << endl; fout.cd(); fout.Write(); fout.Close(); return 0; } void PrintUsage(char *name){ cout<<"Usage: "<<name<<" "<<endl; cout<<"\t Interactive mode." << endl; cout<<"Usage: "<<name<<" listfilename "<<endl; cout<<"\t 'listfilename' is a text file contains the 'raw data file names'."; cout<<endl; } <file_sep>/ribllvmedaq/TUDPClientSocket.cpp ///////////////////////////////////////////////////////// // TUDPClientSocket.cpp: Broadcast UDPSocket // Broadcast the data to ethernet // <NAME> 07/2012 test version v.01 // v.02 : added "localhost" environment for singal PC // by <NAME> (06/2013) ///////////////////////////////////////////////////////// #include <iostream> #include <fstream> #include <vector> using namespace std; #include "caenacq.h" #include "TString.h" #include "TUDPClientSocket.h" #include "TSystem.h" #include "TInetAddress.h" TUDPClientSocket::TUDPClientSocket(const char* netaddress, unsigned int port) { iport = port; int opt=1; isocket = -1; TString netaddr = netaddress; netaddr.ReplaceAll(" ", ""); struct sockaddr_in addr_info; addr_info.sin_family=AF_INET; addr_info.sin_addr.s_addr=inet_addr(netaddr.Data()); addr_info.sin_port=htons(port); v_addr_info.push_back(addr_info); addr_len=sizeof(struct sockaddr); #ifdef WIN32 WSADATA wsd; int err; err = WSAStartup(MAKEWORD(2,2),&wsd); #endif //#ifdef WIN32 isocket = socket(AF_INET,SOCK_DGRAM,0); // IPPROTO_UDP if(isocket<0) { cout << "Data Broadcast Socket on ip: " << netaddress << " open error!" << endl; return; } //if the IP is "*.*.*.255", set its "SO_BROADCAST" property TString chaddr = netaddr; int pos = chaddr.Last('.'); TString subaddr = chaddr(pos+1, 3); if( (subaddr.Length() == 3) && (subaddr.Contains("255")) ) { setsockopt(isocket,SOL_SOCKET,SO_BROADCAST,(const char*)&opt,sizeof(opt)); } } TUDPClientSocket::TUDPClientSocket(const char* netaddress, unsigned int port, bool multicast) { iport = port; int opt=1; isocket = -1; TString netaddr = netaddress; netaddr.ReplaceAll(" ", ""); struct sockaddr_in addr_info; addr_info.sin_family=AF_INET; addr_info.sin_addr.s_addr=inet_addr(netaddr.Data()); addr_info.sin_port=htons(port); v_addr_info.push_back(addr_info); addr_len=sizeof(struct sockaddr); #ifdef WIN32 WSADATA wsd; int err; err = WSAStartup(MAKEWORD(2,2),&wsd); #endif //#ifdef WIN32 isocket = socket(AF_INET,SOCK_DGRAM,0); // IPPROTO_UDP if(isocket<0) { cout << "Data Broadcast Socket on ip: " << netaddress << " open error!" << endl; return; } SetRouteNum(RouteNum_TTL); SetLoopBack(MUDPLoopBack); } TUDPClientSocket::TUDPClientSocket(const char *addrlistfile) { iport = 0; int ipnum = ReadAddrListFileForDS(addrlistfile); int opt=1; isocket = -1; addr_len=sizeof(struct sockaddr); #ifdef WIN32 WSADATA wsd; int err; err = WSAStartup(MAKEWORD(2,2),&wsd); #endif //#ifdef WIN32 isocket = socket(AF_INET,SOCK_DGRAM,0); // IPPROTO_UDP if(isocket<0) { cout << "Data Broadcast Socket on 'IPLIST' open error!" << endl; return; } } TUDPClientSocket::TUDPClientSocket(const char *addrlistfile, unsigned int port, char cf) { iport = 0; int ipnum = ReadAddrListFileForCF(addrlistfile, port); int opt=1; isocket = -1; addr_len=sizeof(struct sockaddr); #ifdef WIN32 WSADATA wsd; int err; err = WSAStartup(MAKEWORD(2,2),&wsd); #endif //#ifdef WIN32 isocket = socket(AF_INET,SOCK_DGRAM,0); // IPPROTO_UDP if(isocket<0) { if(cf == 'c') cout << "Command sending (broadcast) socket on 'IPLIST' open error!" << endl; if(cf == 'd') cout << "Data-file header sending (broadcast) socket on 'IPLIST' open error!" << endl; return; } } int TUDPClientSocket::SendTo(const char *buff, int length) { if(!IsValid()) return 0; int sendlen=0; unsigned int i=0; unsigned int sz = v_addr_info.size(); for(i=0; i<sz; i++) sendlen = sendto(isocket, buff, length, 0, (struct sockaddr *)&v_addr_info[i], addr_len); return sendlen; } TUDPClientSocket::~TUDPClientSocket() { if(isocket) { #ifdef WIN32 closesocket(isocket); WSACleanup(); #else close(isocket); #endif //#ifdef WIN32 } } bool TUDPClientSocket::SetSendTimeOutValue(unsigned int usec) { if( !IsValid() ) return false; int sta = -1; int msec; msec = usec/1000; if(msec < 1) msec = 1; unsigned int seco = (unsigned int)usec/1000000; unsigned int useco = usec%1000000; struct timeval tv_out; tv_out.tv_sec = seco; tv_out.tv_usec = useco; #ifdef _WIN32 sta = setsockopt(isocket, SOL_SOCKET, SO_SNDTIMEO, (char *)&msec, sizeof(msec)); #else sta = setsockopt(isocket, SOL_SOCKET, SO_SNDTIMEO, &tv_out, sizeof(tv_out)); #endif if(sta == 0 ) return true; return false; } bool TUDPClientSocket::SetRouteNum(unsigned int rnum) { if( !IsValid() ) return false; int routenum = rnum; int ret = setsockopt(isocket, IPPROTO_IP, IP_MULTICAST_TTL, (char*)&routenum,sizeof(routenum)); if( ret != 0 ) { cout<<"TUDPCLientSocket>> Error in setsockopt(IP_MULTICAST_TTL)."<<endl; return false; } return true; } bool TUDPClientSocket::SetLoopBack(bool lback) { if( !IsValid() ) return false; unsigned int loopback = (unsigned int)lback; int ret = setsockopt(isocket,IPPROTO_IP,IP_MULTICAST_LOOP, (char*)&loopback,sizeof(loopback)); if( ret != 0 ) { cout<<"TUDPCLientSocket>> Error in setsockopt(IP_MULTICAST_LOOP): "<<endl; return false; } return true; } bool TUDPClientSocket::JoinMemberShip(const char *MC_IP) { if( !IsValid() ) return false; ip_mreq mreq; memset(&mreq, 0, sizeof(mreq)); #ifdef WIN32 mreq.imr_interface.S_un.S_addr = INADDR_ANY; mreq.imr_multiaddr.S_un.S_addr = inet_addr(MC_IP); #else mreq.imr_interface.s_addr = INADDR_ANY; mreq.imr_multiaddr.s_addr = inet_addr(MC_IP); #endif //#ifdef WIN32 int ret = setsockopt(isocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq)); if( ret != 0 ) { cout<<"TUDPCLientSocket>> Error in setsockopt(IP_ADD_MEMBERSHIP). "<<endl; return false; } return true; } int TUDPClientSocket::ReadAddrListFileForDS(const char *listfile) { ifstream addlf(listfile); if( !addlf.good() ) { cout << endl << endl; cout << "Open IP list file: " << listfile << " ERROR." << endl; cout << endl << endl; return 0; } struct sockaddr_in addr_info; addr_info.sin_family=AF_INET; char ipline[300]; TString ipcheck, ip; cout << "Data Will Be Send to: " << endl; while(addlf.getline( ipline, sizeof(ipline) )) { ipcheck.Clear(); ip.Clear(); ipcheck = ipline; if(ipcheck.IsWhitespace()) continue; ipcheck.ReplaceAll(" ", ""); if(ipcheck.Length()>15) continue; TInetAddress addip = gSystem->GetHostByName(ipcheck.Data()); ipcheck = addip.GetHostAddress(); ip = ipcheck; if(ipcheck.Contains(".")) { ipcheck.ReplaceAll(".", ""); if(ipcheck.Atoi() == 0) continue; } addr_info.sin_addr.s_addr=inet_addr(ip.Data()); addr_info.sin_port=htons(UDPDataBroadPortCon); v_addr_info.push_back(addr_info); //UDPDataBroadPortCon port addr_info.sin_port=htons(UDPDataBroadPortMon); v_addr_info.push_back(addr_info); //UDPDataBroadPortMon port cout << "\t" << ip.Data() << endl; } return v_addr_info.size(); } int TUDPClientSocket::ReadAddrListFileForCF(const char *listfile, unsigned int port) { ifstream addlf(listfile); if( !addlf.good() ) { cout << endl << endl; cout << "Open IP list file: " << listfile << " ERROR." << endl; cout << endl << endl; return 0; } struct sockaddr_in addr_info; addr_info.sin_family=AF_INET; char ipline[300]; TString ipcheck, ip; while(addlf.getline( ipline, sizeof(ipline) )) { ipcheck.Clear(); ip.Clear(); ipcheck = ipline; if(ipcheck.IsWhitespace()) continue; ipcheck.ReplaceAll(" ", ""); if(ipcheck.Length()>15) continue; TInetAddress addip = gSystem->GetHostByName(ipcheck.Data()); ipcheck = addip.GetHostAddress(); ip = ipcheck; if(ipcheck.Contains(".")) { ipcheck.ReplaceAll(".", ""); if(ipcheck.Atoi() == 0) continue; } addr_info.sin_addr.s_addr=inet_addr(ip.Data()); addr_info.sin_port=htons(port); v_addr_info.push_back(addr_info); //for UDPCommBroadPort/UDPFHBroadPort port } return v_addr_info.size(); }<file_sep>/ribllvmedaq/TControlFrame.cpp ///////////////////////////////////////////////////////// // File name: ControlFrame.cpp // // Brief introduction: // // This class create the main frame for // // Online program of RIBLL1-DAQ // // // // Version: V1.0 // // Author: <NAME> // // Date: Nov. 2010 // // For: RIBLL1 // ///////////////////////////////////////////////////////// #include <iostream> #include <ctime> #include <string.h> using namespace std; #include "TApplication.h" #include "TGClient.h" #include "TGWindow.h" #include "TGFrame.h" #include "GuiTypes.h" #include "TG3DLine.h" #include "TGText.h" #include "TGLabel.h" #include "TGButton.h" #include "TGTextView.h" #include "TGTextEntry.h" #include "TGNumberEntry.h" #include "TGResourcePool.h" #include "TGGC.h" #include "TGFont.h" #include "TString.h" #include "TThread.h" #include "TTimer.h" #include "TControlFrame.h" TControlFrame *gControlFrame =0; ClassImp(TControlFrame); TControlFrame::TControlFrame(const TGWindow *p, UInt_t w, UInt_t h): TGMainFrame(p, w, h, kVerticalFrame) { if(gControlFrame!=0) { cout<<"Only one instance of 'Online' permitted"<<endl; return; } gControlFrame = this; SetCleanup(kDeepCleanup); DontCallClose(); //Start the up main Frame fFUpMain = new TGHorizontalFrame(this, 450, 250, kChildFrame|kVerticalFrame|kRaisedFrame); AddFrame(fFUpMain, new TGLayoutHints(kLineSolid, 1, 1, 1, 1)); // Start of fFUpLeftMain--------------------------------------------------------- fFUpLeftMain = new TGVerticalFrame(fFUpMain, 225, 300, kChildFrame|kVerticalFrame|kRaisedFrame);//|kFixedWidth); fFUpMain->AddFrame(fFUpLeftMain, new TGLayoutHints(kLineSolid, 1, 1, 1, 1)); TGLayoutHints *flayoutButt = new TGLayoutHints(kLHintsNormal|kLHintsCenterX|kLHintsCenterY, 5, 5, 7, 7); TGLayoutHints *flayoutfileb = new TGLayoutHints(kLHintsNormal|kLHintsLeft, 2, 2, 3, 3); TGGroupFrame *fFFileSettings = new TGGroupFrame(fFUpLeftMain, " File Settings ", kVerticalFrame); fFUpLeftMain->AddFrame(fFFileSettings, flayoutfileb); TGHorizontalFrame *fFsetfilename = new TGHorizontalFrame(fFFileSettings, 85, 10, kFitWidth); fFFileSettings->AddFrame(fFsetfilename, flayoutfileb); fTEfilename = new TGTextEntry(fFsetfilename, new TGTextBuffer(50)); fFsetfilename->AddFrame(fTEfilename, flayoutfileb); fTEfilename->Resize(120, fTEfilename->GetDefaultHeight()); fBSetFileName = new TGTextButton(fFsetfilename, " SetFName ", kB_setfilename); fFsetfilename->AddFrame(fBSetFileName, flayoutfileb); fBSetFileName->Resize(40, fBSetFileName->GetDefaultHeight()); TGHorizontalFrame *fFsetfilerun = new TGHorizontalFrame(fFFileSettings, 85, 10, kFitWidth); fFFileSettings->AddFrame(fFsetfilerun, flayoutfileb); fTEfilerun = new TGNumberEntry(fFsetfilerun, 0, 4, 99, TGNumberFormat::kNESInteger, TGNumberFormat::kNEANonNegative, TGNumberFormat::kNELLimitMinMax, 0, 999); fFsetfilerun->AddFrame(fTEfilerun, flayoutfileb); fTEfilerun->Resize(120, fTEfilerun->GetDefaultHeight()); fBSetFileRun = new TGTextButton(fFsetfilerun, " SetRunNum ", kB_setfilerun); fFsetfilerun->AddFrame(fBSetFileRun, flayoutfileb); fBSetFileRun->Resize(40, fBSetFileRun->GetDefaultWidth()); TGHorizontalFrame *fFsetfileheader = new TGHorizontalFrame(fFFileSettings, 85, 10, kFitWidth); fFFileSettings->AddFrame(fFsetfileheader, flayoutfileb); fTEfileheader = new TGTextEntry(fFsetfileheader, new TGTextBuffer(750)); fFsetfileheader->AddFrame(fTEfileheader, flayoutfileb); fTEfileheader->Resize(120, fTEfileheader->GetDefaultHeight()); fBSetFileHeader = new TGTextButton(fFsetfileheader, " SetFHeader ", kB_setfileheader); fFsetfileheader->AddFrame(fBSetFileHeader, flayoutfileb); fBSetFileRun->Resize(40, fBSetFileRun->GetDefaultHeight()); fBSetFileName->Associate(this); fBSetFileRun->Associate(this); fBSetFileHeader->Associate(this); //File status of TGLabel TGGroupFrame *fFfilestatus = new TGGroupFrame(fFUpLeftMain, " File Status ", kHorizontalFrame|kChildFrame|kFixedWidth|kFixedHeight); //cout << fFUpLeftMain->GetDefaultWidth() << endl; fFfilestatus->Resize(fFUpLeftMain->GetDefaultWidth()-4, 45); fFUpLeftMain->AddFrame(fFfilestatus, new TGLayoutHints(kLHintsCenterX|kLHintsCenterY, 1, 1, 1, 1)); TGGC *fTextGC; const TGFont *font = gClient->GetFont("-*-times-bold-r-*-*-18-*-*-*-*-*-*-*"); if (!font) font = gClient->GetResourcePool()->GetDefaultFont(); FontStruct_t labelfont = font->GetFontStruct(); GCValues_t gval; gval.fMask = kGCBackground | kGCFont | kGCForeground; gval.fFont = font->GetFontHandle(); gClient->GetColorByName("yellow", gval.fBackground); fTextGC = gClient->GetGC(&gval, kTRUE); ULong_t bcolor, ycolor, rcolor; gClient->GetColorByName("yellow", ycolor); gClient->GetColorByName("blue", bcolor); gClient->GetColorByName("red", rcolor); flabFileStatus = new TGLabel(fFfilestatus, " Data File Closed ", fTextGC->GetGC(), labelfont, kChildFrame|kFixedWidth, bcolor); flabFileStatus->SetTextColor(ycolor); fFfilestatus->AddFrame(flabFileStatus, new TGLayoutHints(kLHintsNormal, 1, 1, 1, 1)); flabFileStatus->Resize(fFUpLeftMain->GetDefaultWidth()-40, fFfilestatus->GetDefaultHeight()); //end of fFUpLeftMain ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TGVertical3DLine *sepupmain = new TGVertical3DLine(fFUpMain, 6, 200); fFUpMain->AddFrame(sepupmain, new TGLayoutHints(kLHintsNormal|kLHintsExpandY, 1, 1, 1, 1)); //Start of fFUpRightMain-------------------------------------------------- fFUpRightMain = new TGVerticalFrame(fFUpMain, 225, 300, kChildFrame|kVerticalFrame|kRaisedFrame); fFUpMain->AddFrame(fFUpRightMain, new TGLayoutHints(kLHintsNormal, 1, 1, 1, 1)); TGGroupFrame *fFconbutton = new TGGroupFrame(fFUpRightMain, " Control Buttons: ", kVerticalFrame); fFUpRightMain->AddFrame(fFconbutton, new TGLayoutHints(kLHintsNormal, 1, 1, 1, 1)); TGHorizontalFrame *butt1 = new TGHorizontalFrame(fFconbutton, 300, 60); fFconbutton->AddFrame(butt1, new TGLayoutHints(kLHintsNormal, 1, 1, 1, 1)); fBStart = new TGTextButton(butt1, " START ACQ ", kB_start); fBStop = new TGTextButton(butt1, " STOP ACQ ", kB_stop); fBInitDAQ = new TGTextButton(butt1, " INIT ACQ ", kB_initdaq); butt1->AddFrame(fBStart, flayoutButt); butt1->AddFrame(fBStop, flayoutButt); butt1->AddFrame(fBInitDAQ, flayoutButt); TGHorizontalFrame *butt2 = new TGHorizontalFrame(fFconbutton, 300, 40); fFconbutton->AddFrame(butt2, new TGLayoutHints(kLHintsNormal, 1, 1, 1, 1)); fBOpenF = new TGTextButton(butt2, " OPEN FILE ", kB_openf); fBCloseF = new TGTextButton(butt2, " CLOSE FILE ", kB_closef); fBConExit = new TGTextButton(butt2, " EXIT CONTROL ", kB_exitcon); butt2->AddFrame(fBOpenF, flayoutButt); butt2->AddFrame(fBCloseF, flayoutButt); butt2->AddFrame(fBConExit, flayoutButt); TGHorizontalFrame *butt3 = new TGHorizontalFrame(fFconbutton, 300, 40); fFconbutton->AddFrame(butt3, new TGLayoutHints(kLHintsNormal, 1, 1, 1, 1)); fBConnect = new TGTextButton(butt3, " CONNECT ", kB_connectodaq); fBTestComm = new TGTextButton(butt3, " TEST COMM ", kB_testcomm); fBDaqExit = new TGTextButton(butt3, " EXIT DAQ ", kB_exitdaq); butt3->AddFrame(fBConnect, flayoutButt); butt3->AddFrame(fBTestComm, flayoutButt); butt3->AddFrame(fBDaqExit, flayoutButt); fBConExit->ChangeBackground(ycolor); fBDaqExit->ChangeBackground(rcolor); fBStart->Associate(this); fBStop->Associate(this); fBInitDAQ->Associate(this); fBOpenF->Associate(this); fBCloseF->Associate(this); fBConExit->Associate(this); fBConnect->Associate(this); fBTestComm->Associate(this); fBDaqExit->Associate(this); fBStart->SetToolTipText("Start DAQ"); fBStop->SetToolTipText("Stop DAQ"); fBInitDAQ->SetToolTipText("Initialization VMEREAD Process"); fBOpenF->SetToolTipText("Open Data File"); fBCloseF->SetToolTipText("Close Data File"); fBConExit->SetToolTipText("Close This Control Frame"); fBConnect->SetToolTipText("Connect to DAQ PC"); fBTestComm->SetToolTipText("Test The Communication of This PC and DAQ PC"); fBDaqExit->SetToolTipText("Make The VMEREAD Program on DAQPC Exit"); //End of fFUpRightMain^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TGHorizontal3DLine *sepupdownmain = new TGHorizontal3DLine(this, 450, 6, kChildFrame); AddFrame(sepupdownmain, new TGLayoutHints(kLHintsNormal|kLHintsCenterX|kLHintsExpandX, 1, 1, 1, 1)); //Start the down main Frame fFDownMain = new TGHorizontalFrame(this, 550, 300, kChildFrame|kHorizontalFrame|kRaisedFrame); AddFrame(fFDownMain, new TGLayoutHints(kLHintsNormal, 1, 1, 1, 1)); //Start of fFDownRightMain------------------------------------------------- TGGroupFrame *fFmessage = new TGGroupFrame(fFDownMain, " Messages: ", kVerticalFrame); fFDownMain->AddFrame(fFmessage, new TGLayoutHints(kLHintsNormal, 1, 1, 1, 1)); fviewText = new TGTextView(fFmessage, 410, 220); fFmessage->AddFrame(fviewText, new TGLayoutHints(kLHintsExpandY|kLHintsExpandX, 2, 2, 2, 2)); //End of fFDownRightMain^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //Start of fFDownRightMain------------------------------------------------- TGGroupFrame *fFeventnum = new TGGroupFrame(fFDownMain, " Events: ", kVerticalFrame); fFDownMain->AddFrame(fFeventnum, new TGLayoutHints(kLHintsNormal, 1, 1, 1, 1)); fvieweventnum = new TGTextView(fFeventnum, 120, 220); fFeventnum->AddFrame(fvieweventnum, new TGLayoutHints(kLHintsNormal, 1, 1, 1, 1)); //End of fFDownRightMain^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SetWMSizeHints(GetDefaultWidth(), GetDefaultHeight(), GetDefaultWidth(), GetDefaultHeight(), 0, 0); SetWindowName("Control-RIBLL1-DAQ"); MapSubwindows(); MapWindow(); Resize(); gClient->FreeFont(font); } TControlFrame::~TControlFrame(){} void TControlFrame::CloseWindow() { DeleteWindow(); gApplication->Terminate(0); } //bool TControlFrame::ProcessMessage(Long_t msg, Long_t param1, Long_t) //{ // switch(GET_MSG(msg)) // { // case kC_COMMAND: // switch(GET_SUBMSG(msg)) // { // case kCM_BUTTON: // switch(param1) // { // case kB_exitcon: // CloseWindow(); // break; // } // } // break; // // default: // break; // } // return kTRUE; //} void TControlFrame::ShowText(TGText *text) { TThread::Lock(); //lock the main mutex ClearTextView(); fviewText->AddText(text); fviewText->Update(); fviewText->ShowBottom(); TThread::UnLock(); //unlock the main mutex } void TControlFrame::ShowText(const char *text) { TThread::Lock(); //lock the main mutex ClearTextView(); fviewText->AddLineFast(text); fviewText->Update(); fviewText->ShowBottom(); //fviewText->AddLine(text); //TTimer::SingleShot(3, Class_Name(), this, "UpdateTextView()"); TThread::UnLock(); //unlock the main mutex } void TControlFrame::ClearTextView() { TThread::Lock(); //lock the main mutex if(fviewText->ReturnLineCount()>=50) { fviewText->GetText()->DelLine(1); } TThread::UnLock(); //unlock the main mutex } void TControlFrame::ShowEventNum(int num) { TString chnum = TString::Format("%09d", num); TThread::Lock(); //lock the main mutex ClearEventNum(); fvieweventnum->AddLineFast(chnum.Data()); fvieweventnum->Update(); //fvieweventnum->AddLine(chnum.Data()); fvieweventnum->ShowBottom(); TThread::UnLock(); //unlock the main mutex } void TControlFrame::ClearEventNum() { TThread::Lock(); //lock the main mutex if(fvieweventnum->ReturnLineCount()>=50) { fvieweventnum->GetText()->DelLine(1); } TThread::UnLock(); //unlock the main mutex } void TControlFrame::DisableButt(TGTextButton *butt) { TThread::Lock(); //lock the main mutex butt->SetEnabled(kFALSE); TThread::UnLock(); //unlock the main mutex } void TControlFrame::EnableButt(TGTextButton *butt) { TThread::Lock(); //lock the main mutex butt->SetEnabled(kTRUE); TThread::UnLock(); //unlock the main mutex } void TControlFrame::UpdateTextView() { fviewText->Update(); fviewText->ShowBottom(); }<file_sep>/ribllvmedaq/Makefile ###################################### # makefile for RIBLLVMEDAQ # # <NAME> 07/2012 # ###################################### #TQObject.h TGTextEntry.h TGNumberEntry.h TGLabel.h TGButton.h TGTextView.h TThread.h CC=gcc CF=ifort FF=gfortran FFLAG= -w -o2 -fpp CPP=g++ CFLAG = -O2 -D LINUX -g ROOTLIB = $(shell root-config --cflags --glibs) ROOTCINT = rootcint -f SYSLIB= -lstdc++ ROOTINC = -I$(shell root-config --incdir) CRFLAG = $(shell root-config --cflags) ROOTBIN = $(shell root-config --bindir) CAENLibs = -lCAENVME # PROG = DAQPC ControlPC OnlinePC MonOnline Raw2ROOT ReadRootFile2D xiaohai TOF_deltaE Chain_root_Al33 Chain_root_Al27 Chain_root_O16 PROG=xiaohai ##PROG = Chain_root_Al33 Chain_root_O16 ModHeader = TBoard.h TControl.h TModV785.h TModV785N.h TModV775.h TModV775N.h TModV830AC.h TModV792.h\ TEvtBuilder.h TClientEvtBuilder.h TControlFrame.h TDataFileBuilder.h TMasterTask.h OBJS = OnlineUserFunc.o TBoard.o TCBLT.o TClientEvtBuilder.o TConfig.o TControl.o TControlFrame.o\ TCrateCBLT.o TDAQApplication.o TDAQPCTask.o TDataAnalyser.o TDataFileBuilder.o TDataFileReader.o\ TDataReceiver.o TEvtBuilder.o TMasterTask.o TModV775.o TModV775N.o TModV785.o TModV785N.o TModV830AC.o TModV792.o\ TOfflineAnalyser.o TOnline.o TOnlineFrame.o TUDPClientSocket.o TUDPServerSocket.o\ TVMELink.o UserVMEFuncitons.o classDict.o all: $(PROG) DAQPC:DIC $(OBJS) VMEDAQPC.o $(CPP) -o $@ VMEDAQPC.o $(OBJS) $(CFLAG) $(ROOTLIB) $(SYSLIB) $(CAENLibs) ControlPC:DIC $(OBJS) ControlPC.o $(CPP) -o ControlPC ControlPC.o $(OBJS) $(CFLAG) $(ROOTLIB) $(SYSLIB) $(CAENLibs) OnlinePC:DIC $(OBJS) OnlinePC.o $(CPP) -o $@ OnlinePC.o $(OBJS) $(CFLAG) $(ROOTLIB) $(SYSLIB) $(CAENLibs) MonOnline:DIC $(OBJS) MonOnline.o $(CPP) -o $@ MonOnline.o $(OBJS) $(CFLAG) $(ROOTLIB) $(SYSLIB) $(CAENLibs) Raw2ROOT:DIC $(OBJS) Raw2ROOT.o $(CPP) -o $@ Raw2ROOT.o $(OBJS) $(CFLAG) $(ROOTLIB) $(SYSLIB) $(CAENLibs) ReadRootFile2D:DIC $(OBJS) ReadRootFile2D.o $(CPP) -o $@ ReadRootFile2D.o $(OBJS) $(CFLAG) $(ROOTLIB) $(SYSLIB) $(CAENLibs) xiaohai:DIC $(OBJS) xiaohai.o $(CPP) -o $@ xiaohai.o $(OBJS) $(CFLAG) $(ROOTLIB) $(SYSLIB) $(CAENLibs) TOF_deltaE:DIC $(OBJS) TOF_deltaE.o $(CPP) -o $@ TOF_deltaE.o $(OBJS) $(CFLAG) $(ROOTLIB) $(SYSLIB) $(CAENLibs) Chain_root_Al33:DIC $(OBJS) Chain_root_Al33.o $(CPP) -o $@ Chain_root_Al33.o $(OBJS) $(CFLAG) $(ROOTLIB) $(SYSLIB) $(CAENLibs) Chain_root_Al27:DIC $(OBJS) Chain_root_Al27.o $(CPP) -o $@ Chain_root_Al27.o $(OBJS) $(CFLAG) $(ROOTLIB) $(SYSLIB) $(CAENLibs) Chain_root_O16:DIC $(OBJS) Chain_root_O16.o $(CPP) -o $@ Chain_root_O16.o $(OBJS) $(CFLAG) $(ROOTLIB) $(SYSLIB) $(CAENLibs) %.o: %.cpp $(CPP) -c $(CFLAG) $(CRFLAG) -o $@ $< DIC: -rm -f classDict.cpp classDict.h $(ROOTCINT) classDict.cpp -c -DLINUX $(ModHeader) classLinkDef.h clean: -rm *.o -rm $(PROG) <file_sep>/ribllvmedaq/TDAQApplication.cpp /////////////////////////////////////////////////////////////// // TDAQApplication class interface // ver 0.2 : added "localhost" environment for singal PC // by <NAME> (2013.06.16) /////////////////////////////////////////////////////////////// #include <stdlib.h> #include <iostream> #include <cstring> using namespace std; #include "TDAQApplication.h" #include "TString.h" TDAQApplication *gDAQApplication=0; const char gversion[] = "0.1beta"; TDAQApplication::TDAQApplication(int argc, char **argv, bool master) { if (gDAQApplication) { cout<<"TDAQApplication>> only one instance of TDAQApplication allowed"; return; } fmaster = master; if(argc>0) Version(); fmaddr= gMULTICAST; fcomm = "UNICAST"; gDAQApplication = this; if(argc>0) { fargc = argc; fargv = (char **)new char*[fargc]; } else { fargc = 0; fargv = 0; } for (int i = 0; i<fargc; i++) { fargv[i] = new char[strlen(argv[i])+1]; strcpy(fargv[i], argv[i]); } if(argc>0) GetOptions(argc,argv); // obtain th enviroment variable value for gConfPath char *env = getenv(gConfPath.c_str()); if(env==NULL) { fpathname = "."; } else { fpathname = env; } char *sip = getenv(gServerIP.c_str()); if(sip == NULL) { fserverip = "localhost"; } else { string csip(sip); if(csip.size()>0) fserverip = sip; } } void TDAQApplication::GetOptions(int argc, char **argv) { char *cp; char *name = argv[0]; argc--; argv++; while(argc>0 && **argv == '-') { cp=*argv + 1; switch(*cp) { case 'm': fcomm = "MULTICAST"; break; case 'u': fcomm = "UNICAST"; break; //case 'b': // fcomm = "BROADCAST"; // break; case 'h': Usage(name); exit(0); default: cout<<"TDAQApplication>> Unknown option, default values used"<<endl; break; } argc--; argv++; } } bool TDAQApplication::Get_ServerIP(std::string &sip) { if(fserverip.size() == 0) return false; if(fserverip.compare("localhost") == 0) { sip = "localhost"; return true; } TString ipcheck(fserverip); if(ipcheck.IsWhitespace()) return false; ipcheck.ReplaceAll(" ", ""); if(ipcheck.Length()>15) return false; if(ipcheck.Contains(".") && ipcheck.CountChar('.')<3) return false; ipcheck.ReplaceAll(".", ""); if(!ipcheck.IsDigit()) return false; sip = fserverip.c_str(); return true; } TDAQApplication::~TDAQApplication() { for (int i = 0; i<fargc; i++) if (fargv[i]) delete [] fargv[i]; delete [] fargv; } void TDAQApplication::Usage(char *name) { cout<<"Usage: "<<name<<" [-m|-b|-u] -h"<<endl; cout<<"\t -m: enable multicast"<<endl; cout<<"\t -b: enable broadcast"<<endl; cout<<"\t -u: unicast (point to point connection)"<<endl; cout<<"\t -h: this help"<<endl; cout<<endl; } void TDAQApplication::Version() { cout<<"*********************************************"<<endl; cout<<" DAQ ver. "<<gversion<<" RIBLL ACQUISITION "<<endl; cout<<" readout program for RIBLL "<<endl; cout<<" based upon ROOT v5.34 or later "<<endl; cout<<" DAQ for Caen V2718 PCI-VME optical bridge "<<endl; cout<<" <NAME> (2012) "<<endl; cout<<"*********************************************\n\n"; } <file_sep>/ribllvmedaq/TModV792.h //////////////////////////////////////////// // TModV792.h: Implementation of CAEN // module V792AC // All module class must be inherited form // 'TBoard' // <NAME> 07/2012 //////////////////////////////////////////// #ifndef V792_H #define V792_H #include "TBoard.h" #include "Rtypes.h" class TH1; class TModV792: public TBoard { protected: enum MaxCh{fMaxChannel = 32}; //!Max channel of this module protected: static unsigned int facqreg[2]; //! acquisition register and valid data mask static unsigned int fMaxDataVal; //! Maximum valid data value(4095, 8191 ...) public: TH1 **his1d; //![fMaxChannel] pointer to the histograms of this module UShort_t chdata[fMaxChannel]; //channel data public: TModV792(){MaxChannel = (unsigned int)fMaxChannel;} //default constructor, ROOT TClass need this virtual void Initialization(); //initialization the object before use it virtual ~TModV792(); virtual unsigned int GetAcqReg(){return (fBaseAddr | facqreg[0]);} virtual unsigned int GetAcqRegMask(){return facqreg[1];} virtual unsigned int GetMaxChannel(){return fMaxChannel;} virtual unsigned int GetMaxDataVal(){return fMaxDataVal;} virtual unsigned int GetChannelData(int chnum); virtual void SetMaxChannel(unsigned int mchann) {MaxChannel = mchann;} virtual void SetMaxDataVal(unsigned int mdatav) {fMaxDataVal = mdatav;} virtual int WriteGeoToBoard(unsigned int geo); virtual int WriteCrateNumtoBoard(unsigned int cnum); virtual int Decode(unsigned int *&data_point); virtual int DataReset(); // 'Data Reset' command of this module virtual int SoftReset(); // need by WriteGeoToBoard(unsigned int geo) virtual int Init_Board(){return 0;} virtual void CleanChData(){for(int i=0; i<fMaxChannel; i++) chdata[i] =0;} virtual void Create1DHistos(); ClassDef(TModV792, 1); }; #endif //#ifndef V792_H <file_sep>/ribllvmedaq/testmain.cpp //Test main #include <iostream> #include <vector> #include <cstdlib> #include <string> using namespace std; #include "TUDPClientSocket.h" //must be the first 'include' #include "TDAQApplication.h" #include "TControl.h" #include "TVMELink.h" #include "TConfig.h" #include "TCBLT.h" #include "TCrateCBLT.h" #include "TUDPServerSocket.h" #include "TBoard.h" #include "TClientEvtBuilder.h" #include "TDataFileBuilder.h" #include "TThread.h" #include "TSystem.h" #include "TApplication.h" #ifdef WIN32 #include <windows.h> #define sleep Sleep #define WaitSec 1000 #else #include <unistd.h> #define WaitSec 0.3 #endif // show sCommands here //string sCommands[] = //{ // "TEST CONNECTION", /* CMD = 0 */ // "Initialize VME", /* 1 */ // "Start Acquisition", /* 2 */ // "Stop Acquisition", /* 3 */ // "Open Tape File", /* 4 */ // "Close Tape File", /* 5 */ // "Exit and Put offline" /* 6 */ //}; int main(int argc, char*argv[]) { TApplication *app = new TApplication("Control_PC", &argc, argv, 0, 1); int status; bool okCBLT; vector <TVMELink> VMELink; bool IsMaster = true; //this is the acquisition master // The Server DAQ Application defining general environment TDAQApplication ribll(argc, argv, IsMaster); //where the cblt setup files are string pathchain = ribll.Get_PathEnvdir() + "/cblt_addr_c"; //where the filenameqdc and codifier setup file are string pathfilename = ribll.Get_PathEnvdir() + "/filenamemod.dat"; // define bridge and crate parameters // bridge type, link, node, virtual crate VMELink.push_back(TVMELink(cvV2718, 0, 0, 1)); //Crate 1 VMELink.push_back(TVMELink(cvV2718, 0, 1, 2)); //Crate 2 //VMELink.push_back(TVMELink(cvV2718, 0, 2, 3)); //Crate 2 okCBLT = true; vector <TCrateCBLT> tcrate; for(unsigned int i=0; i<VMELink.size(); i++) { TCBLT tread(8192, 1); //cblt buffer in bytes and wait_for_ready boards TCrateCBLT tcr(VMELink[i], tread, i, pathchain.c_str()); status = tcr.Get_Readout().Get_CBLT_Config(pathchain.c_str(), tcr.GetCrateNum()); tcr.ReadoutProcsInit(); //do not delete this line if(status!=0) { okCBLT=false; cout<<"CBLT Initialization failed for crate "<<VMELink[i].GetCrateNum()<<endl; } else { tcrate.push_back(tcr); tcrate[i].Get_Readout().PrintCBLTInfo(); } } // if(okCBLT)gCheck.SetCBLTStatus(true); VMELink.clear(); ////Getting the main list of module configrations TConfig Codif(pathfilename.c_str()); status = Codif.GetConfigNames(); if(status<0) { cout<<"Fatal error reading configuration file"<<endl; exit(1); } else { Codif.ReadConfigForAnalysis(); } char buf[100] = {'a','s','d','f'}; string comm = "stringcomm"; string comm1; //TClientEvtBuilder EvtB("192.168.3.11", Codif, tcrate, 1); //TUDPClientSocket databroad("192.168.1.255", UDPDataBroadPort); //int i = 0; //while(i<5)//(fgets(buf, sizeof(buf), stdin) != NULL) //{ // i++; // int len = strnlen(buf, sizeof(buf)); // databroad.SendTo(comm.c_str(), comm.size()); // if(i==4) databroad.SendTo("stop", 4); //} //TUDPServerSocket revdata(UDPDataBroadPort); //while (strncmp(buf, "stop", 4) !=0) //{ // int n = revdata.RecvRaw(buf, 100); // //buf[n-1] = '\0'; // comm1 = buf; // cout <<"TUDPServerSocket: " << comm1 << " " << n << " bytes." << endl; //} TControl controlmaster("192.168.3.11", CONTROL_PC); controlmaster.AcceptReceiver(); controlmaster.SetFileHeader("..Test File Header.."); for(int i=0; i<6; i++) { cout << "Sending command: " << sCommands[i] << endl; controlmaster.send_TCPcontrol_command(sCommands[i]); cout << "Reply: " << controlmaster.GetAckMessages() << endl; } //TThread *DaqPC_revComm = 0; //TControl controldaq("192.168.3.11", DAQ_PC); //DaqPC_revComm = new TThread("DaqPC_WaitComm", (void*(*)(void *))(&TControl::recv_TCPcontrol_command), 0); //DaqPC_revComm->Run(); //DaqPC_revComm->Join(); //controldaq.StartDaqPCThread(); //(controldaq.GetDaqPCThread())->Join(); //TControl controlonline("192.168.3.11", ONLINE_PC); //controlonline.Connect("MessageSignal(void *)", "TClientEvtBuilder", &EvtB, "ProcessStopSignal()"); //controlonline.recv_UDPBroadcontrol_command(0); //if( controlonline.StartOnlinePCThread())//{cout << " Thread runing..." << endl;} //; //(controlonline.GetOnlinePCThread())->Join();//Ps(); //else cout << " Online thread fail. " << endl; //cout << " I am here... " << endl; //cout << "UDP Reply: " << controlonline.GetAckMessages() << endl; //TDataFileBuilder file; //file.SetFileHeader("File header."); //file.SetFileName("test"); //file.SetRunNum(2); //file.FormBroadFHeader(); //file.ExtractFNameNumFromHeader(); //file.OpenDataFile(); //file.StartWriteDataThread(); ////sleep(1000); //file.StopWriteDataThread(); ////sleep(1000); //file.StartWriteDataThread(); ////sleep(1000); //file.StopWriteDataThread(); //file.CloseDataFile(); //cout << " I am here.. " << endl; //for(int i=0; i<5; i++) file.OpenDataFile(); app->Run(); return 0; }<file_sep>/ribllvmedaq/TConfig.cpp /////////////////////////////////////////////////////////////////////////// // TConfiguration class. E.d.F. (2007) // main configuration class for hardware database // and codifier initialization // Used to read configuration files of boards and write // (implement) the data to boards. // Modified by <NAME> 07/2012 // Changes: // 1. make the program use IRQ for DAQ // 2. rewrite "Init_Caen_Boards(..)" to use "TClass" of ROOT // 3. Add mark '*' for comment lines in configration file /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////// // TConfig class implementation /////////////////////////////////////////////////////////////// #include <fstream> #include <iostream> #include <sstream> #include <list> #include <map> #include <exception> using namespace std; #include "TConfig.h" #include "TVMELink.h" #include "CAENVMEtypes.h" #include "CAENVMElib.h" #include "TDAQApplication.h" #include "TROOT.h" #include "TClass.h" #include "TString.h" // static members initialization list <string> TConfig::fqnames; //list of module configuration file names list <TBoard *> TConfig::fboard; //list of module configuration boards vector <TTable> TConfig::ftable; //vector of first board address in //fboard list for each crate (bookmark crate) TConfig::TConfig(const char *confname) { try { ffilename = new char[strlen(confname)+1]; strcpy(ffilename,confname); } catch(exception &ex) { cout << "TConfig>> " << ex.what() << endl; } }; void TConfig::EraseNamesList() { if(!fqnames.empty()) { fqnames.clear(); } } void TConfig::EraseBoardList() { if(!fboard.empty()) { purge(fboard); fboard.clear(); } ftable.clear(); } TConfig::~TConfig() { delete ffilename; if(!fboard.empty()) { purge(fboard); fboard.clear(); } ftable.clear(); } TConfig::TConfig(TConfig &source) { unsigned int len = strnlen(source.ffilename, 200); char *fnames = new char[len]; ffilename = fnames; fverror = source.fverror; } //read the main codifier name list for all crates //and put result in a container list int TConfig:: GetConfigNames() { const int SZ=300; char line[SZ]; string names; int kqdc = 0; ifstream fqdc(ffilename); if(!fqdc) { cout<<" TConfig>> File "<<ffilename<<" not found. "<<endl; return -1; } //remove all list elements EraseNamesList(); try{ while(fqdc.getline(line,SZ)) { TString checkline(line); while(checkline[0]==' '|| checkline[0]=='\t' ) //erase ' ' and '\t' that at the beginning of the line { checkline.Replace(0, 1, ""); } if(checkline.Length()==0) continue; strcpy(line, checkline.Data()); switch(line[0]) { case '*': break; default: TString tsline = line; if(tsline.IsWhitespace()) break; names = gDAQApplication->Get_PathEnvdir() + "/" + line; if(!names.empty()) { fqnames.push_back(names); kqdc++; } break; } } } catch(ios::failure &e) { cout << "Config file: " << ffilename << " read error!" << e.what()<< endl; } cout<<"Read "<<kqdc<<" names from file \""<<ffilename<<"\""<<endl; fqdc.close(); return kqdc; } //Init all codifiers registers or just check the configuration (default) //Construct the board database list int TConfig::Init_Caen_Boards(EBoardInit sflag=kCheckOnly) { char line[300]; char model[20]; string filename; int nboard; int crate; unsigned int base=0, addr, addroff, data, dataw, mask, geo, treeswitch; bool infmod = false; //base information of this module is ok or not long handle =-1 ; TBoard *bp = 0; TBoardError err; nboard = 0; //remove all list elements EraseBoardList(); //clear the error buffer if(!fverror.empty()) { fverror.clear(); } list<string>::iterator it=fqnames.begin(); try{ while(it!=fqnames.end()) { filename = (*it); ifstream freg(filename.c_str()); if(!freg) { cout<<"TConfig>> File "<<filename<<" can not be opened"<<endl; it++; continue; } int row = 0, lmark = 0; istringstream is; infmod = false; while(freg.getline(line, sizeof(line))) { row++; TString checkline(line); while(checkline[0]==' '|| checkline[0]=='\t' ) //erase ' ' and '\t' that at the beginning of the line { checkline.Replace(0, 1, ""); } if(checkline.Length()==0) { //cout <<"The " << row << " line is empty." << endl; continue; } strcpy(line, checkline.Data()); switch(line[0]) { case '*' : break; case '#' : // obtain board information. check status registers // fill the board database i if(infmod) { cout << " To much '#' lines in file: " << filename << endl; break; } is.str(line+1); is>>model>>crate>>hex>>base>>dec>>geo>>treeswitch; if(is.fail()) { cout<<"File: "<< filename <<" iostream error at line #"<< row << endl; is.clear(); } else { infmod = true; handle = GetHandle(crate); if(handle>=0) { TString modname = "TMod"; modname += model; if((gROOT->GetClass(modname.Data()))) { bp = 0; bp = (TBoard *)((gROOT->GetClass(modname.Data()))->New()); bp->Initialization(); bp->SetHandle(handle); bp->SetBaseAddr(base); bp->SetGeo(geo); bp->SetCrateNum(crate); //bp->SetTreeSwitch(treeswitch); //bp->SetSelfObj(bp); bp->SetName(model); if( !(bp->WriteGeoToBoard(geo)) ) { err.SetError(crate, base, geo); fverror.push_back(err); cout << "Write Geo address: "<< geo << " to board: 0x"<< hex<< base <<dec <<" error!" << endl; }; if( !(bp->WriteCrateNumtoBoard(crate)) ) { err.SetError(crate, base, crate); fverror.push_back(err); cout << "Write Crate Number: "<< crate << " to board: 0x"<< hex<< base <<dec <<" error!" << endl; } fboard.push_back(bp); printf("Board check: %10s %02d %04d (0x%08x) [sn. %d]\n",model, crate, bp->GetGeo(), base, bp->Get_SerialNumber()); } else { cout<<"File: "<<filename<< " Error at line #"<<row<< " Class of Module '" << model << "' do not exist!" << endl; } } else if(sflag==kCheckOnly) { printf("Board check: %10s %02d %04d (0x%08x)\n",model, crate, geo, base); } } break; default: if(infmod) { is.clear(); is.str(line); is>>dec>>lmark>>hex>>addroff>>data>>dec>>dataw>>hex>>mask>>dec; addr = base|(addroff & 0x0000ffff); if(is.fail()) { cout<< "Crate: " << crate << " Geo: " << geo <<" , error at line: "<< row << "| " << line << " |" <<" skipped"<<endl; is.clear(); break; } if(sflag!=kCheckOnly && handle>=0) { Init_Register(crate, addr, data, dataw, mask); } is.clear(); } break; } memset(line, 0, sizeof(line)); } nboard++; it++; freg.close(); } } catch(ios::failure e) { cout <<"TConfig, read configration file: " << filename << " error!" << e.what() << endl; } BuildCrateBookmark(); return nboard; } //Print codifiers list void TConfig::ShowList() { for (list<string>::iterator it=fqnames.begin(); it!=fqnames.end(); ++it) { cout << *it << " "; cout << endl; } } void TConfig::Init_Register(int crate, int addr, int data, int datawidth, int mask) { // Set QDC/TDC registers bool RWok; CVErrorCodes status; int rdata, loop=20; CVDataWidth data_size=cvD16; int wdata=0; if(datawidth == 16) { data_size = cvD16; wdata = data & 0x0000ffff; } else if(datawidth == 32) { data_size = cvD32; wdata = data & 0xffffffff; } else { wdata = data & 0x0000ffff; } TBoardError err; long BHandle = GetHandle(crate); if (BHandle<0) { cout << "Device handle of crate: " << crate << " error." << endl; err.SetError(crate, 0, 0); fverror.push_back(err); return; } status = CAENVME_WriteCycle(BHandle, addr, &wdata, cvA32_U_DATA, data_size); if(status == cvSuccess) { if(mask != 0x0000) { RWok = false; while(loop--) { status = CAENVME_ReadCycle(BHandle, addr, &rdata, cvA32_U_DATA, data_size); if((rdata & mask) == data) { RWok = true; break; } else { status = CAENVME_WriteCycle(BHandle, addr, &wdata, cvA32_U_DATA, data_size); } } if(RWok==false) { printf("INIT>> Warning: Failed in writing %04x to register %08x\n", wdata, addr); printf("INIT>> Handle=%d ADDR = 0x%08x DATUM_READ = 0x%08x\n\n",BHandle,addr,rdata); err.SetError(crate,addr,wdata); fverror.push_back(err); } } } else { cout << "TConfig>> Initialize module in Crate: " << crate << " ,address: 0x" << hex << addr << dec << " error." << endl; } } long TConfig::GetHandle(int crate) { map<int, int> ::iterator it1; int handle; it1 = TVMELink::flookup_ind.find(crate); it1 == TVMELink::flookup_ind.end() ? handle=-1 : handle = (*it1).second; return handle; } //Print codifiers list void TConfig::ShowBoardList() { list<TBoard *>::const_iterator it; cout<<"\n------ Boards database list ------"<<endl; cout<<"There are #"<<fboard.size()<<" boards in the list"<<endl; for (it=fboard.begin(); it!=fboard.end(); ++it) { cout <<"Base addr: "<<showbase<<hex<<(*it)->GetBaseAddr()<< " BHandle: "<<dec<< (*it)->GetHandle()<<" Type: "<<(*it)->GetName()<<endl; } } // Find the first board of each crate void TConfig::BuildCrateBookmark() { int h, oldh; int num = 0; TTable t; list<TBoard *>::const_iterator it; if(fboard.size()==0)return; it=fboard.begin(); h = (*it)->GetHandle(); oldh = h; t.ffirst = it; t.fhandle = h; num++; it++; for (;it!=fboard.end(); it++) { h = (*it)->GetHandle(); if(oldh != h) { t.fnum = num; ftable.push_back(t); oldh = h; t.ffirst = it; t.fhandle = h; num=0; } num++; } //assign the last node found t.fnum = num; ftable.push_back(t); } list<TBoard*>::const_iterator &TConfig::LookupTable(int handle, int &num) { static list<TBoard *>::const_iterator it; num = 0; for(unsigned int i=0; i<ftable.size(); i++) { if(ftable[i].fhandle==handle) { num = ftable[i].fnum; return ftable[i].ffirst; } } return it; //return default iterator for an empty crate } string TConfig::GetErrInfo(int i) { stringstream is; if(i<0) return " "; if(fverror.size()!=0 && i<fverror.size()) { is<<"Error #"<<i<<" of #"<<fverror.size()<<" Crate: "<<fverror[i].GetECrate()<<" Addr: 0x"<<hex<<fverror[i].GetEAddr()<<dec<< " Datum: 0x"<<hex<<fverror[i].GetEData(); return is.str(); } return " "; } // Read the 'config files' for data analysis int TConfig::ReadConfigForAnalysis() { char line[300]; char model[20]; string filename; int nboard = 0; int row=0, crate=0; unsigned int base=0, geo =0; bool treeswitch = 0; //long handle; TBoard *bp = 0; nboard = 0; //remove all list elements EraseBoardList(); //clear the error buffer if(!fverror.empty()) { fverror.clear(); } list<string>::iterator it=fqnames.begin(); try{ while(it!=fqnames.end()) { filename = (*it); ifstream freg(filename.c_str()); if(!freg) { cout<<"TConfig>> File "<<filename<<" can not be opened"<<endl; it++; continue; } row = 0; istringstream is; while(freg.getline(line, sizeof(line))) { row++; TString checkline(line); while(checkline[0]==' '|| checkline[0]=='\t' ) //erase ' ' and '\t' that at the beginning of the line { checkline.Replace(0, 1, ""); } if(checkline.Length()==0) continue; strcpy(line, checkline.Data()); switch(line[0]) { case '*' : break; case '#' : // obtain board information. check status registers // fill the board database i is.str(line+1); is>>model>>crate>>hex>>base>>dec>>geo>>treeswitch; if(is.fail()) { cout<<"File: "<< filename <<" iostream error at line #"<< row << endl; is.clear(); } else { //handle = GetHandle(crate); //if(handle>=0) { TString modname = "TMod"; modname += model; if((gROOT->GetClass(modname.Data()))) { bp = 0; bp = (TBoard *)((gROOT->GetClass(modname.Data()))->New()); bp->Initialization(); //bp->SetHandle(handle); bp->SetBaseAddr(base); bp->SetGeo(geo); bp->SetCrateNum(crate); //bp->SetSelfObj(bp); bp->SetName(model); //#ifdef ONLINETREE //cout << treeswitch << endl; bp->SetTreeSwitch(treeswitch); //#endif //#ifdef ONLINETREE //bp->WriteGeoToBoard(geo); //bp->WriteCrateNumtoBoard(crate); fboard.push_back(bp); printf("Board check: %12s Crate %02d Geo %04d (0x%08x) \n",bp->GetName(), crate, bp->GetGeo(), base); } else { cout<<"File: "<<filename<< " Error at line #"<<row<< " Module name '" << model << "' do not exist!" << endl; } } } break; default: break; } } nboard++; it++; freg.close(); } } catch(ios::failure &e) { cout <<"TConfig, read configration file: " << filename << " error!" << e.what() << endl; return -1; } return nboard; } list<TBoard*>& TConfig::GetBoardList() { return fboard; }<file_sep>/ribllvmedaq/TDataFileReader.h ////////////////////////////////////////////////// // TDataFileReader.h: Read the data file for // offline analysis. Save the 'File header' to // a log file and loop reading to the end of the // file. // <NAME> (08/2012) ////////////////////////////////////////////////// #ifndef TDataFileReader_H #define TDataFileReader_H #include <fstream> using namespace std; class TDataFileReader { public: unsigned int *fevtbuf; unsigned int evtlen; ifstream infile; ofstream logfile; public: TDataFileReader(); virtual ~TDataFileReader(); bool OpenDataFile(const char* fname); void CloseDataFile(); bool EvtReadingLoop(); unsigned int*& GetEvtBuf(){return fevtbuf;} unsigned int GetEventLength(){return evtlen;} bool SkipFileHeader(); }; #endif //#ifndef TDataFileReader_H<file_sep>/ribllvmedaq/classLinkDef.h #ifdef __CINT__ #pragma link C++ class TBoard; #pragma link C++ class TControl; #pragma link C++ class TModV785; #pragma link C++ class TModV785N; #pragma link C++ class TModV775; #pragma link C++ class TModV775N; #pragma link C++ class TModV830AC; #pragma link C++ class TModV792; #pragma link C++ class TEvtBuilder; #pragma link C++ class TClientEvtBuilder; #pragma link C++ class TControlFrame+; #pragma link C++ class TMasterTask; #endif <file_sep>/ribllvmedaq/TOfflineAnalyser.cpp //////////////////////////////////////////////// // TOfflineAnalyzer.cpp: Offline analyzer used // for data analysis. // <NAME> (08/2012) //////////////////////////////////////////////// #include <map> #include <iostream> #include <sstream> #include <string> using namespace std; #include "TOfflineAnalyser.h" #include "TDataAnalyser.h" #include "TDataFileReader.h" #include "TBoard.h" #include "TFile.h" #include "TTree.h" #include "TString.h" TDataFileReader *TOfflineAnalyzer::freader=0; TDataAnalyser *TOfflineAnalyzer::danalyzer=0; typedef struct Str_flist //describe the RAW data list file format { char infilename[80]; unsigned int nevtforana; } D_flist; TOfflineAnalyzer::TOfflineAnalyzer(TDataFileReader *filer, TDataAnalyser *anadata) { freader = filer; danalyzer = anadata; rootfile = 0; CrateGeoMap = danalyzer->GetCrateGeoMap(); } bool TOfflineAnalyzer::SetListFile(const char *listfn) { fnamelist.open(listfn); return ( fnamelist.good() ); } //this function is not used, maybe have mistakes bool TOfflineAnalyzer::LoopLsitFile(const char *listfn) { if(fnamelist.good()) fnamelist.close(); fnamelist.open(listfn); if(!fnamelist.good()) return false; string item; char filename[300]; try { while( (fnamelist.peek() != EOF) && (!fnamelist.fail()) ) { filename[0] = '\0'; getline(fnamelist, item); if(item.c_str()[0] == '*') continue; //skip the comments istringstream s_item(item); if(item.size() > 0) { s_item >>filename; cout << "File: " << filename; bool bopen = freader->OpenDataFile(filename); if(!bopen) continue; OpenRootFile(filename); CreateTH1I(); CreateTree(); freader->SkipFileHeader(); //skip the data file header; bool readsucc = true; do { readsucc = freader->EvtReadingLoop(); danalyzer->GlobalDecoder(freader->GetEvtBuf(), freader->GetEventLength()); //data analysis function tree->Fill(); }while(readsucc); WriteRootFile(); CloseRootFile(); } item.empty(); } } catch(ios::failure &e) { cout << "TOfflineAnalyzer>> file: " << listfn << " read error! " << e.what()<< endl; return false; } return true; } void TOfflineAnalyzer::OpenRootFile(const char* rfname) { if(rootfile) CloseRootFile(); TString tfname = rfname; tfname.ReplaceAll(".", ""); tfname += ".root"; rootfile = new TFile(tfname.Data(), "RECREATE"); } void TOfflineAnalyzer::CloseRootFile() { if(rootfile) rootfile->Close(); rootfile = 0; } void TOfflineAnalyzer::WriteRootFile() { rootfile->Write(); } void TOfflineAnalyzer::CreateTH1I() { map<int, TBoard*>::const_iterator it=CrateGeoMap->begin(); for(it; it!=CrateGeoMap->end(); it++) { (*it).second->Create1DHistos(); } } void TOfflineAnalyzer::CreateTree() { tree = new TTree("RawData", "ModuleData"); map<int, TBoard*>::const_iterator it=CrateGeoMap->begin(); for(it; it!=CrateGeoMap->end(); it++) { TString tname = (*it).second->Class_Name(); tname += (*it).first; tree->Branch(tname.Data(), (*it).second->Class_Name(), (*it).second); } } //this function is not used, maybe have mistakes void TOfflineAnalyzer::AnaSingleDataFile(const char *dfile, int nevt_ana) { bool bopen = freader->OpenDataFile(dfile); if(!bopen) return; OpenRootFile(dfile); CreateTH1I(); CreateTree(); freader->SkipFileHeader(); //skip the data file header; bool readsucc = true, b_nevt = true; int nevtana = 0; do { readsucc = freader->EvtReadingLoop(); danalyzer->GlobalDecoder(freader->GetEvtBuf(), freader->GetEventLength()); //data analysis function tree->Write(); nevtana++; if( nevt_ana>0 && nevtana>=nevt_ana) b_nevt = false; }while(readsucc && b_nevt); WriteRootFile(); CloseRootFile(); }<file_sep>/ribllvmedaq/multicastsocket.cpp //Project Setting -> C/C++ -> Code Generation -> 确认选中"Debug Multithreaded" #include <iostream> #include <winsock2.h> //注意这里的include文件顺序 #include <Ws2tcpip.h> #include <process.h> //_beginthread要求 #pragma comment(lib, "ws2_32.lib") using namespace std; const char* MULTICAST_IP = "172.16.31.10"; //多播组地址 const int MULTICAST_PORT = 2002; //多播组端口 const int BUFFER_SIZE = 1024; void do_send(void* arg); //读取用户输入并发送到多播组线程函数 void do_read(void* arg); //读物多播组数据函数 int main() { WSAData wsaData; if( WSAStartup(MAKEWORD(2,2), &wsaData) != 0 ) { cout<<"Error in WSAStartup"<<endl; return 0; } SOCKET server; server = socket(AF_INET, SOCK_DGRAM, 0); //创建一个UDP套接口 cout<<"create socket: "<<server<<endl; int ret ; const int on = 1; //允许程序的多个实例运行在同一台机器上 ret = setsockopt(server, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)); if( ret == SOCKET_ERROR ) { WSACleanup(); cout<<"Error in setsockopt(SO_REUSEADDR): "<<WSAGetLastError()<<endl; return 0; } const int routenum = 10; ret = setsockopt(server,IPPROTO_IP,IP_MULTICAST_TTL,\ (char*)&routenum,sizeof(routenum)); if( ret == SOCKET_ERROR ) { WSACleanup(); cout<<"Error in setsockopt(IP_MULTICAST_TTL): "<<WSAGetLastError()<<endl; return 0; } const int loopback = 0; //禁止回馈 ret = setsockopt(server,IPPROTO_IP,IP_MULTICAST_LOOP,\ (char*)&loopback,sizeof(loopback)); if( ret == SOCKET_ERROR ) { WSACleanup(); cout<<"Error in setsockopt(IP_MULTICAST_LOOP): "<<WSAGetLastError()<<endl; return 0; } sockaddr_in local; memset(&local, 0, sizeof(local)); local.sin_family = AF_INET; local.sin_port = htons(MULTICAST_PORT); local.sin_addr.S_un.S_addr = INADDR_ANY; ret = bind(server, (sockaddr*)(&local), sizeof(local)); if( ret == SOCKET_ERROR ) { WSACleanup(); cout<<"Error in bind: "<<WSAGetLastError()<<endl; return 0; } ip_mreq mreq; memset(&mreq, 0, sizeof(mreq)); mreq.imr_interface.S_un.S_addr = INADDR_ANY; mreq.imr_multiaddr.S_un.S_addr = inet_addr(MULTICAST_IP); //加入一个多播组 ret = setsockopt(server,IPPROTO_IP,IP_ADD_MEMBERSHIP,\ (char*)&mreq,sizeof(mreq)); if( ret == SOCKET_ERROR ) { WSACleanup(); cout<<"Error in setsockopt(IP_ADD_MEMBERSHIP): "<<WSAGetLastError()<<endl; return 0; } //创建了两个线程,一个读用户输入并发送,一个读多播组数据 HANDLE hHandle[2]; hHandle[0] = (HANDLE)_beginthread(do_send,0,(void*)server); hHandle[1] = (HANDLE)_beginthread(do_read,0,(void*)server); //如果用户输入结束,程序就终止了 WaitForSingleObject(hHandle[0], INFINITE); WSACleanup(); return 0; } void do_send(void* arg) { SOCKET server = (SOCKET)arg; char sendline[BUFFER_SIZE+1]; sockaddr_in remote; memset(&remote, 0, sizeof(remote)); remote.sin_addr.s_addr = inet_addr ( MULTICAST_IP ); remote.sin_family = AF_INET ; remote.sin_port = htons(MULTICAST_PORT); for(;;) //读取用户输入知道用户输入"end" { cin.getline(sendline, BUFFER_SIZE); if(strncmp(sendline,"end",3)==0) break; //发送用户输入的数据到多播组 sendto(server, sendline, strlen(sendline), 0, (sockaddr*)(&remote), sizeof(remote)); } cout<<"do_send end..."<<endl; } void do_read(void* arg) { SOCKET server = (SOCKET)arg; char buf[BUFFER_SIZE+1]; int ret; sockaddr_in client; int clientLen; for(;;) //一直读取知道主线程终止 { clientLen = sizeof(client); memset(&client, 0, clientLen); ret = recvfrom(server, buf, BUFFER_SIZE, 0, (sockaddr*)(&clientLen), &clientLen); if ( ret == 0) //do_read在用户直接回车发送了一个空字符串 { continue; } else if( ret == SOCKET_ERROR ) { if( WSAGetLastError() == WSAEINTR ) //主线程终止recvfrom返回的错 break; cout<<"Error in recvfrom: "<<WSAGetLastError()<<endl; break ; } buf[ret] = '\0'; cout<<"received: "<<buf<<endl; } cout<<"do_read end..."<<endl; }<file_sep>/ribllvmedaq/VMEDAQPC.cpp //////////////////////////////////////////////// // VMEDAQPC.cpp: main() of DAQ. Using // a thread to receive control commands // form 'control pc', and then perform // it. // <NAME> (08/2012) // Ver 0.2 : added "localhost" for singal PC // by <NAME> (06/2013) //////////////////////////////////////////////// #include <iostream> #include <vector> #include <cstdlib> #include <string> #include <cstdlib> using namespace std; #include "TUDPClientSocket.h" //must be the first 'include' #include "TDAQApplication.h" #include "TControl.h" #include "TVMELink.h" #include "TConfig.h" #include "TCBLT.h" #include "TCrateCBLT.h" #include "TUDPServerSocket.h" #include "TBoard.h" #include "TClientEvtBuilder.h" #include "TDataFileBuilder.h" #include "TThread.h" #include "TSystem.h" #include "TApplication.h" #include "TDAQPCTask.h" #ifdef WIN32 #include <windows.h> #define sleep Sleep #define WaitSec 1000 #else #include <unistd.h> #define WaitSec 0.3 #endif int main(int argc, char* argv[]) { TApplication *app = new TApplication("Control_PC", &argc, argv, 0, 1); int status=-1; int MasterCrate_Virtual = 1; //Master Crate Number bool okCBLT, okVME; vector <TVMELink> VMELink; // The Server DAQ Application defining general environment TDAQApplication ribll(argc, argv, false); //where the cblt setup files are string pathchain = ribll.Get_PathEnvdir() + "/cblt_addr_crate"; //where the filenameqdc and codifier setup file are string pathfilename = ribll.Get_PathEnvdir() + "/filenamemod.dat"; // define bridge and crate parameters // Control_Board_type, pci_device_link, control_board_num, virtual_crate_num VMELink.push_back(TVMELink(cvV2718, 0, 0, 1)); //Crate 1, vs file 'cblt_addr_crate1.dat' //VMELink.push_back(TVMELink(cvV2718, 0, 1, 2)); //Crate 2, vs file 'cblt_addr_crate2.dat' //VMELink.push_back(TVMELink(cvV2718, 0, 2, 3)); //Crate 3 vs file 'cblt_addr_crate3.dat' MasterCrate_Virtual = 1; //virtual_crate_num for the master crate; // Initialize bridges and IO ports okVME=true; for(unsigned int i=0; i<VMELink.size(); i++) { status = VMELink[i].Init(); if(status!=0) { okVME=false; cout<<"Initialization failed for crate "<<VMELink[i].GetCrateNum()<< " [Dev="<<VMELink[i].GetDevice()<<",Link="<<VMELink[i].GetLink()<<"]"<<endl; } else { //Set IO port for output signals on channel 0,1,2,3 //channel 0: cpu busy //channel 1: trigger start/stop //channel 2: pulse to end program without trigger VMELink[i].InitIOPort(cvOutput0, cvDirect, cvActiveHigh); VMELink[i].InitIOPort(cvOutput1, cvDirect, cvActiveHigh); VMELink[i].InitIOPort(cvOutput2, cvDirect, cvActiveHigh); VMELink[i].InitIOPort(cvOutput3, cvDirect, cvActiveHigh); VMELink[i].InitIOPort(cvOutput4, cvDirect, cvActiveHigh); VMELink[i].ClearIOPort(cvOut0Bit); VMELink[i].ClearIOPort(cvOut1Bit); VMELink[i].ClearIOPort(cvOut2Bit); VMELink[i].ClearIOPort(cvOut3Bit); VMELink[i].ClearIOPort(cvOut4Bit); } } okCBLT = true; vector <TCrateCBLT> tcrate; //Crate CBLT implementation for(unsigned int i=0; i<VMELink.size(); i++) { int WaitForDReady = 0; if(VMELink[i].GetCrateNum() == MasterCrate_Virtual) WaitForDReady = 1; // this crate wait for the data ready--IRQ TCBLT tread(8192, WaitForDReady); //cblt buffer in bytes and wait_for_ready boards TCrateCBLT tcr(VMELink[i], tread, i, pathchain.c_str()); //status = tcr.Get_Readout().Get_CBLT_Config(pathchain.c_str(), tcr.GetCrateNum()); //tcr.ReadoutProcsInit(); //do not delete this line status = tcr.GetCBLTConfigStatus(); if(status!=0) { okCBLT=false; cout<<"CBLT Initialization failed for crate "<<VMELink[i].GetCrateNum()<<endl; } else { tcrate.push_back(tcr); tcrate[i].Get_Readout().PrintCBLTInfo(); } } if( !(okVME && okCBLT) ) { if(argc>1) { if(strcmp(argv[1], "checkconfig") != 0) exit(0); //only for checking the vme models config } else { exit(0); } } VMELink.clear(); //Getting the main list of module configrations //Initialization all of the boards TConfig Codif(pathfilename.c_str()); status = Codif.GetConfigNames(); //Read the file '/filenamemod.dat' if(status<0) { cout<<"Fatal error reading configuration file"<<endl; exit(1); } else { Codif.Init_Caen_Boards(kCheckOnly); //ReadConfigForAnalysis(); } TThread *Daqthread =0, *DaqControlthread = 0; string serverip; bool bgetip = ribll.Get_ServerIP(serverip); if(!bgetip) { cout << "Get Server IP error!" << endl; exit(1); } cout << "VME Control PC IP: " << serverip.c_str() << endl; //control pc ip, config, crate vector, mastercrate TDAQPCTask daqpctask(serverip.c_str(), Codif, tcrate, MasterCrate_Virtual);//172.16.31.10 //Join() the VMEReadThread DaqControlthread = daqpctask.StartDAQPCControlThread(); //start the rec_TCP_Command thread Daqthread = daqpctask.StartDAQThread(); //start the VME readout thread if(Daqthread) { Daqthread->Join(); } else { cout << "DAQThread run error!" << endl; } //Join the control thread - DAQPCThread if(DaqControlthread) DaqControlthread->Join(); cout << "VMEDAQPC finished, Exit..." << endl; exit(0); app->Run(); return 0; } <file_sep>/ribllvmedaq/TEvtBuilder.h //////////////////////////////////////////////// // TEvtBuilder.h: Class to perform the VME // reading and build the 'event' structure. // Use TCrateCBLT to loop reading procedure, // and then build the event in memory, then // send it out to ethernet by using UDP // socket. // <NAME> 07/2012 //////////////////////////////////////////////// #ifndef TEvtBuilder_H #define TEvtBuilder_H #include <vector> using namespace std; #include <RQ_OBJECT.h> #include "caenacq.h" #include "TConfig.h" #include "TCrateCBLT.h" class TEvtBuilder { protected: TConfig &fconfig; //reference to TConfig class vector <TCrateCBLT> &fcrate; static unsigned int fnetbuf[NETBUFFER/4]; public: static int fnumcrates; static int fevent_counter; unsigned int fmastercrate; // the 'fcrate' vector index (0 is the first element of tcrate vector) bool fokstop; // stop the acquisition ok or not public: TEvtBuilder(TConfig &cod, vector <TCrateCBLT> &tcrate, unsigned int mastercrate); virtual ~TEvtBuilder() {} static bool CheckStop(); virtual int CheckErrors(string, int ) = 0; vector <TCrateCBLT> & GetCrateCBLT() {return fcrate;} TConfig& GetConfig(){return fconfig;} protected: int GetMask(); }; extern TEvtBuilder* onlyTEvtBuilder; #endif //#ifndef TEvtBuilder_H<file_sep>/ribllvmedaq/caenacq.h ///////////////////////////////////////////////// // readout program chimera qdc/tdc // CAEN V2718 Optical-LINK version // 07/2007 v 0.7 // <NAME> <EMAIL> // Modified by <NAME> for RIBLL1 //////////////////////////////////////////////// #ifndef CAENACQ_H #define CAENACQ_H #include <string> using namespace std; #ifdef WIN32 //#include "WTypes.h" typedef short VARIANT_BOOL; #endif ////Path environment const string gConfPath = "DAQCONFPATH"; //environment, file PATH for vme config files const string gDataPath = "DAQDataPath"; //environment, file PATH for data files const string gServerIP = "DAQServerIP"; //environment, server ip //VME Read functions definition #define UserVMEFunctionBefore #define UserVMEFunctionAfter //// Data headers definition #define Event_Header 0xFFFFFFFF #define Crate_Header 0xFFFF0000 ////Socket port definition const unsigned int UDPDataBroadPortCon = 2221; //for control thread write data to disk const unsigned int UDPDataBroadPortMon = 2223; //for mononlie const unsigned int UDPCommBroadPort = 2225; const unsigned int TCPCommPort = 2229; const unsigned int UDPFHBroadPort = 2235; // for data file header broadcast ////For UDP multicast, not used now in this program const string MULTICAST_IP("172.16.17.32"); // multicast ip const int RouteNum_TTL = 2; // Number of IP_MULTICAST_TTL const bool MUDPLoopBack = false; // IP_MULTICAST_LOOP ////For Data transfer, data only send to IPs in this file #define IPLISTF "/IPlist.dat" ////acquisition parameters #define Wait_Data_Ready_IRQ const unsigned int IRQ_Level = 0x7F; // IRQ Levvel 0x7F #define FIFO_Read_Mode #define VME_Crate_BufLENGTH 65536 // VME crate acquisition buffer (bytes) #define NETBUFFER VME_Crate_BufLENGTH*2 // MAX network buffer (128 kbytes) #define FileHeaderLEN 1024 // File header length char (bytes) #define MAX_NET_LEN 4096 // Maximum network buffer for data //#define UserVMEFunctionBefore //#define UserVMEFunctionAfter enum EBoardInit {kCheckOnly, kInitReg}; enum VMError {kSuccess, kBusError, kGenericError, kInvalidParam}; //VME error codes //////////////////////////////////////////////////////////////// // generic garbage manager function for STL containers // Delete pointers in an STL sequence container. //////////////////////////////////////////////////////////////// template<class Seq> void purge(Seq& c) { typename Seq::iterator i; for(i = c.begin(); i != c.end(); ++i) { delete *i; *i = 0; } } // Iterator version: template<class InpIt> void purge(InpIt begin, InpIt end) { while(begin != end) { delete *begin; *begin = 0; ++begin; } #define SafeDeleteArr(p) {if(p) {delete[] p; p = 0;}} #define SafeDeleteP(p) {if(p) {delete p; p = 0;}} } #endif <file_sep>/README.md # ribll For GDR <file_sep>/ribllvmedaq/OnlinePC.cpp ////////////////////////////////////////// // ControlPC.cpp: main() of Control PC, // send commands to DAQ_PC and receive // the reply. Acquire data form UDP // broadcast and save it to file. // <NAME> (08/2012) ////////////////////////////////////////// #include "TApplication.h" #include "TRint.h" #include "TDAQApplication.h" #include "TConfig.h" #include "TDataAnalyser.h" #include "TControlFrame.h" #include "TGClient.h" #include "TMasterTask.h" #include "TControl.h" int main(int argc, char *argv[]) { TApplication apponline("Online", &argc, argv); TControl masterpc("localhost", ONLINE_PC);//172.16.58.3 TMasterTask mastask(masterpc); apponline.Run(); return 0; } <file_sep>/ribllvmedaq/Chain_root_Al27.cpp /////////////////////////////////////////////// // An Chain_root.cpp: main() of torootlevel2, used // for offline data analysis. // <NAME> Modified (05/2016) /////////////////////////////////////////////// #include "TApplication.h" #include "TDAQApplication.h" #include "TConfig.h" #include "TDataFileReader.h" #include "TDataAnalyser.h" #include "TString.h" #include "TFile.h" #include "TTree.h" #include "TH1F.h" #include "TH2F.h" #include "TSystem.h" #include "TMath.h" #include "TVector3.h" #include "TROOT.h" #include "TApplication.h" #include "TFile.h" #include "TH1.h" #include "TH2.h" #include "TF1.h" #include "TFormula.h" #include "TProfile.h" #include "TNtuple.h" #include "TRandom.h" #include "TApplication.h" #include "TCanvas.h" #include "TDirectory.h" #include "TStyle.h" #include "TText.h" #include "TLatex.h" #include "TLine.h" #include "TPad.h" #include "TObjArray.h" #include "TTree.h" #include "TBranch.h" #include "TStopwatch.h" #include "TGraph.h" #include "TGraphErrors.h" #include "TLegend.h" #include "TFrame.h" #include "TF1.h" #include "TMinuit.h" #include "TBoard.h" #include "TModV830AC.h" #include "TModV785.h" #include "TModV785N.h" #include "TModV775.h" #include "TModV775N.h" #include "TModV792.h" #include <iostream> #include <sstream> #include <fstream> #include <stdlib.h> #include <vector> #include <map> #include<cstdlib> using namespace std; int main() { TString filein; int StartNum,EndNum; cout<<"Please enter the start number:"<<endl; cin>>StartNum; cout<<"Please enter the end number:"<<endl; cin>>EndNum; TString raw_file; raw_file="/home/daq/vme-single_201605/vmedata/2016gdr"; //input file name TString root_out_name=Form("%s%04d_%04d.root",raw_file.Data(),StartNum,EndNum); cout<<"The output root file is: "<<root_out_name.Data()<<endl; TFile *rootf=new TFile(root_out_name.Data(),"recreate"); ///output file TTree *ribll_gdr=new TTree("ribll_gdr","gdr"); float scaler[32]; float si1_60_p[16],si1_60_n[16],si2_60_p[16],si2_60_n[16], si3_qsd300[16],si4_1000_p[16],si4_1000_n[16]; float csi_adc_1[16],csi_adc_2[16],csi_adc_3[16]; float tof_si_tdc[16],csi_tdc_1[16],csi_tdc_2[16],csi_tdc_3[32]; memset(scaler, 0, sizeof(scaler)); memset(si1_60_p, 0, sizeof(si1_60_p)); memset(si1_60_n, 0, sizeof(si1_60_p)); memset(si2_60_p, 0, sizeof(si2_60_p)); memset(si2_60_n, 0, sizeof(si2_60_p)); memset(si3_qsd300, 0, sizeof(si3_qsd300)); memset(si4_1000_p, 0, sizeof(si4_1000_p)); memset(si4_1000_n, 0, sizeof(si4_1000_n)); memset(csi_adc_1, 0, sizeof(csi_adc_1)); memset(csi_adc_2, 0, sizeof(csi_adc_2)); memset(csi_adc_3, 0, sizeof(csi_adc_3)); memset(tof_si_tdc, 0, sizeof(tof_si_tdc)); memset(csi_tdc_1, 0, sizeof(csi_tdc_1)); memset(csi_tdc_2, 0, sizeof(csi_tdc_2)); memset(csi_tdc_3, 0, sizeof(csi_tdc_3)); ribll_gdr->Branch("scaler", scaler, "scaler[32]/F"); ribll_gdr->Branch("si1_60_p", si1_60_p, "si1_60_p[16]/F"); ribll_gdr->Branch("si1_60_n", si1_60_n, "si1_60_n[16]/F"); ribll_gdr->Branch("si2_60_p", si2_60_p, "si2_60_p[16]/F"); ribll_gdr->Branch("si2_60_n", si2_60_n, "si2_60_n[16]/F"); ribll_gdr->Branch("si3_qsd300", si3_qsd300, "si3_qsd300[16]/F"); ribll_gdr->Branch("si4_1000_p", si4_1000_p, "si4_1000_p[16]/F"); ribll_gdr->Branch("si4_1000_n", si4_1000_n, "si4_1000_n[16]/F"); ribll_gdr->Branch("csi_adc_1", csi_adc_1, "csi_adc_1[16]/F"); ribll_gdr->Branch("csi_adc_2", csi_adc_2, "csi_adc_2[16]/F"); ribll_gdr->Branch("csi_adc_3", csi_adc_3, "csi_adc_3[16]/F"); ribll_gdr->Branch("tof_si_tdc", tof_si_tdc, "tof_si_tdc[16]/F"); ribll_gdr->Branch("csi_tdc_1", csi_tdc_1, "csi_tdc_1[16]/F"); ribll_gdr->Branch("csi_tdc_2", csi_tdc_2, "csi_tdc_2[16]/F"); ribll_gdr->Branch("csi_tdc_3", csi_tdc_3, "csi_tdc_3[32]/F"); TH2F *h_TOF_deltaE_p=new TH2F("h_TOF_deltaE_p","h_TOF_deltaE_p",200,0,200,1800,800,2600); TH2F *h_TOF_deltaE_n=new TH2F("h_TOF_deltaE_n","h_TOF_deltaE_n",200,0,200,1800,800,2600); TH2F *h_si1_Al27_posi=new TH2F("h_si1_Al27_posi","h_si1_Al27_posi",16,0,16,16,0,16); TH2F *h_si2_Al27_posi=new TH2F("h_si2_Al27_posi","h_si2_Al27_posi",16,0,16,16,0,16); TH2F *h_si3_Al27_posi=new TH2F("h_si3_Al27_posi","h_si3_Al27_posi",2,0,2,2,0,2); TH2F *h_si4_Al27_posi=new TH2F("h_si4_Al27_posi","h_si4_Al27_posi",16,0,16,16,0,16); // scaler vmod103 TH1F *h_scaler_T1=new TH1F("h_scaler_T1","h_scaler_T1",200,0,200); TH1F *h_scaler_T2=new TH1F("h_scaler_T2","h_scaler_T2",200,0,200); TH1F *h_scaler_T1_and_T2=new TH1F("h_scaler_T1&T2","h_scaler_T1&T2",200,0,200); TH1F *h_scaler_Gate=new TH1F("h_scaler_Gate","h_scaler_Gate",200,0,200); TH1F *h_scaler_Si1_P=new TH1F("h_scaler_Si1_P","h_scaler_Si1_P",200,0,200); TH1F *h_scaler_Si2_P=new TH1F("h_scaler_Si2_P","h_scaler_Si2_P",200,0,200); TH1F *h_scaler_Si4_P=new TH1F("h_scaler_Si4_P","h_scaler_Si4_P",200,0,200); TH1F *h_scaler_Si3=new TH1F("h_scaler_Si3","h_scaler_Si3",200,0,200); // si1 TH1F *h_si1_60_p[16]; TH1F *h_si1_60_p_sum=new TH1F("h_Si1_60_P_sum","h_Si1_60_P_sum",4096,0,4096); TH1F *h_si1_60_n[16]; TH1F *h_si1_60_n_sum=new TH1F("h_Si1_60_N_sum","h_Si1_60_N_sum",4096,0,4096); char si1_60_p_name[100]; char si1_60_n_name[100]; for (int i=0;i<16;i++) { sprintf(si1_60_p_name,"h_Si1_60_P%2d",i+1); h_si1_60_p[i]=new TH1F(si1_60_p_name,si1_60_p_name,4096,0,4096); } for (int i=0;i<16;i++) { sprintf(si1_60_n_name,"h_Si1_60_N%2d",i+1); h_si1_60_n[i]=new TH1F(si1_60_n_name,si1_60_n_name,4096,0,4096); } // si2 TH1F *h_si2_60_p[16]; TH1F *h_si2_60_p_sum=new TH1F("h_Si2_60_P_sum","h_Si2_60_P_sum",4096,0,4096); TH1F *h_si2_60_n[16]; TH1F *h_si2_60_n_sum=new TH1F("h_Si2_60_N_sum","h_Si2_60_N_sum",4096,0,4096); char si2_60_p_name[100]; char si2_60_n_name[100]; for (int i=0;i<16;i++) { sprintf(si2_60_p_name,"h_Si2_60_P%2d",i+1); h_si2_60_p[i]=new TH1F(si2_60_p_name,si2_60_p_name,4096,0,4096); } for (int i=0;i<16;i++) { sprintf(si2_60_n_name,"h_Si2_60_N%2d",i+1); h_si2_60_n[i]=new TH1F(si2_60_n_name,si2_60_n_name,4096,0,4096); } // si4 TH1F *h_si4_1000_p[16]; TH1F *h_si4_1000_p_sum=new TH1F("h_Si4_1000_P_sum","h_Si4_1000_P_sum",4096,0,4096); TH1F *h_si4_1000_n[16]; TH1F *h_si4_1000_n_sum=new TH1F("h_Si4_1000_N_sum","h_Si4_1000_N_sum",4096,0,4096); char si4_1000_p_name[100]; char si4_1000_n_name[100]; for (int i=0;i<16;i++) { sprintf(si4_1000_p_name,"h_Si4_1000_P%2d",i+1); h_si4_1000_p[i]=new TH1F(si4_1000_p_name,si4_1000_p_name,4096,0,4096); } for (int i=0;i<16;i++) { sprintf(si4_1000_n_name,"h_Si4_1000_N%2d",i+1); h_si4_1000_n[i]=new TH1F(si4_1000_n_name,si4_1000_n_name,4096,0,4096); } // si3 TH1F *h_si3_qsd300[16]; TH1F *h_si3_qsd300_sum=new TH1F("h_Si3_qsd300_sum","h_Si3_qsd300_sum",4096,0,4096); char si3_qsd300_name[100]; for (int i=0;i<4;i++) { sprintf(si3_qsd300_name,"h_Si3_qsd300_%2d",i+1); h_si3_qsd300[i]=new TH1F(si3_qsd300_name,si3_qsd300_name,4096,0,4096); } // CsI, ADC TH1F *h_csi_adc[42]; TH1F *h_csi_adc_sum=new TH1F("h_CsI_ADC_sum","h_CsI_ADC_sum",4096,0,4096); char csi_adc_name[100]; for (int i=0;i<42;i++) { sprintf(csi_adc_name,"h_CsI_ADC_A%2d",i+1); h_csi_adc[i]=new TH1F(csi_adc_name,csi_adc_name,4096,0,4096); } // TOF&Si, TDC TH1F *h_TOF_T1_TDC=new TH1F("h_TOF_T1_TDC","h_TOF_T1_TDC",4096,0,4096); TH1F *h_TOF_T2_TDC=new TH1F("h_TOF_T2_TDC","h_TOF_T2_TDC",4096,0,4096); TH1F *h_Si1_P_TDC=new TH1F("h_Si1_P_TDC","h_Si1_P_TDC",4096,0,4096); TH1F *h_Si2_P_TDC=new TH1F("h_Si2_P_TDC","h_Si2_P_TDC",4096,0,4096); TH1F *h_Si4_P_TDC=new TH1F("h_Si4_P_TDC","h_Si4_P_TDC",4096,0,4096); TH1F *h_Si3_TDC=new TH1F("h_Si3_TDC","h_Si3_TDC",4096,0,4096); // CsI, TDC TH1F *h_csi_tdc[42]; TH1F *h_csi_tdc_sum=new TH1F("h_CsI_TDC_sum","h_CsI_TDC_sum",4096,0,4096); char csi_tdc_name[100]; for (int i=0;i<42;i++) { sprintf(csi_tdc_name,"h_CsI_TDC_A%2d",i+1); h_csi_tdc[i]=new TH1F(csi_tdc_name,csi_tdc_name,4096,0,4096); } float tof1=0; float tof2=0; float tof=0; int startentries=0; int totalentries=0; int count=0; int Al27_count=0; float dist=0.; float Al27_purity=0.; for (int ii=StartNum;ii<=EndNum;ii++) { //start file loop TFile *f; TString rootfile=Form("%s%04d.root",raw_file.Data(),ii); f=new TFile(rootfile.Data(),"read"); cout<<"The current input root file is: "<<rootfile<<endl; TTree *tree; //get the tree in *.root tree=(TTree*)f->Get("RawData"); Int_t nentries; nentries=(Int_t)tree->GetEntries(); startentries=totalentries; totalentries=totalentries+nentries; cout<<"The entry number of current file is: "<<nentries<<endl; TBranch *bran103 = 0; TBranch *bran104 = 0; TBranch *bran106 = 0; TBranch *bran108 = 0; TBranch *bran110 = 0; TBranch *bran112 = 0; TBranch *bran114 = 0; TBranch *bran116 = 0; TBranch *bran118 = 0; TBranch *bran120 = 0; TModV830AC *vmod103 = new TModV830AC(); // TModV785 *vmod104 = new TModV785(); //Si1 60um TModV785 *vmod106 = new TModV785(); //Si2 60um TModV785 *vmod108 = new TModV785(); //Si4 100um TModV785 *vmod110 = new TModV785(); //QSD 300um TModV785 *vmod112 = new TModV785(); // TModV785N *vmod114 = new TModV785N(); TModV775N *vmod116 = new TModV775N(); TModV775 *vmod118 = new TModV775(); TModV775 *vmod120 = new TModV775(); tree->SetBranchAddress("Mod103_TModV830AC",&vmod103,&bran103); tree->SetBranchAddress("Mod104_TModV785",&vmod104,&bran104); tree->SetBranchAddress("Mod106_TModV785",&vmod106,&bran106); tree->SetBranchAddress("Mod108_TModV785",&vmod108,&bran108); tree->SetBranchAddress("Mod110_TModV785",&vmod110,&bran110); tree->SetBranchAddress("Mod112_TModV785",&vmod112,&bran112); tree->SetBranchAddress("Mod114_TModV785N",&vmod114,&bran114); tree->SetBranchAddress("Mod116_TModV775N",&vmod116,&bran116); tree->SetBranchAddress("Mod118_TModV775",&vmod118,&bran118); tree->SetBranchAddress("Mod120_TModV775",&vmod120,&bran120); for(int ievent =0; ievent<nentries; ievent++)//begin event loop { tree->GetEntry(ievent); tof1 =vmod116->chdata[0]; tof2 = vmod116->chdata[1]; tof = tof2- tof1; float si1_60_p_max_e=0; float si1_60_p_max_index=0; float si1_60_n_max_e=0; float si1_60_n_max_index=0; float si2_60_p_max_e=0; float si2_60_p_max_index=0; float si2_60_n_max_e=0; float si2_60_n_max_index=0; float si3_qsd300_max_e=0; float si3_qsd300_max_x=0; float si3_qsd300_max_y=0; float si4_1000_p_max_e=0; float si4_1000_p_max_index=0; float si4_1000_n_max_e=0; float si4_1000_n_max_index=0; for(int i=0;i<32;i++) //scaler { scaler[i]=vmod103->chdata[i]; } for(int i=0;i<16;i++) { si1_60_p[i]=vmod104->chdata[i]; //si1 si1_60_n[i]=vmod104->chdata[i+16]; if (si1_60_p[i]>si1_60_p_max_e) { si1_60_p_max_e=si1_60_p[i]; si1_60_p_max_index=i; } if (si1_60_n[i]>si1_60_n_max_e) { si1_60_n_max_e=si1_60_n[i]; si1_60_n_max_index=i; } si2_60_p[i]=vmod106->chdata[i]; //si2 if(i<8) { si2_60_n[i]=vmod106->chdata[23-i]; } else { si2_60_n[i]=vmod106->chdata[39-i]; } if (si2_60_p[i]>si2_60_p_max_e) { si2_60_p_max_e=si2_60_p[i]; si2_60_p_max_index=i; } if (si2_60_n[i]>si2_60_n_max_e) { si2_60_n_max_e=si2_60_n[i]; si2_60_n_max_index=i; } si4_1000_p[i]=vmod108->chdata[i]; //si4 si4_1000_n[i]=vmod108->chdata[i+16]; if (si4_1000_p[i]>si4_1000_p_max_e) { si4_1000_p_max_e=si4_1000_p[i]; si4_1000_p_max_index=i; } if (si4_1000_n[i]>si4_1000_n_max_e) { si4_1000_n_max_e=si4_1000_n[i]; si4_1000_n_max_index=i; } si3_qsd300[i]=vmod110->chdata[i]; //si3 if (i==0) { si3_qsd300_max_e=si3_qsd300[i]; si3_qsd300_max_x=0; si3_qsd300_max_y=0; } if (i==1&&si3_qsd300[i]>si3_qsd300_max_e) { si3_qsd300_max_e=si3_qsd300[i]; si3_qsd300_max_x=1; si3_qsd300_max_y=0; } if (i==2&&si3_qsd300[i]>si3_qsd300_max_e) { si3_qsd300_max_e=si3_qsd300[i]; si3_qsd300_max_x=0; si3_qsd300_max_y=1; } if (i==3&&si3_qsd300[i]>si3_qsd300_max_e) { si3_qsd300_max_e=si3_qsd300[i]; si3_qsd300_max_x=1; si3_qsd300_max_y=1; } // // if(ievent<10) // cout<<"si3_qsd300 "<<i<<" "<<si3_qsd300[i]<<endl; csi_adc_1[i]=vmod110->chdata[i+16]; //CsI ADC csi_adc_2[i]=vmod112->chdata[i]; csi_adc_3[i]=vmod112->chdata[i+16]; tof_si_tdc[i]=vmod116->chdata[i]; //TOF, Si TDC csi_tdc_1[i]=vmod118->chdata[i]; //CsI TDC csi_tdc_2[i]=vmod118->chdata[i+16]; } // end 16 loop for(int i=0;i<32;i++) csi_tdc_3[i]=vmod120->chdata[i]; // ribll_gdr->Fill(); //Output the new tree // end get data dist=((si1_60_p_max_e-1760)/200)*((si1_60_p_max_e-1760)/200)+((tof-77)/7)*((tof-77)/7); if(dist<=1) { if(si1_60_p_max_e>500&&si1_60_n_max_e>500) h_si1_Al27_posi->Fill(si1_60_p_max_index,si1_60_n_max_index); if(si2_60_p_max_e>500&&si2_60_n_max_e>500) h_si2_Al27_posi->Fill(15-si2_60_n_max_index,si2_60_p_max_index); if(si3_qsd300_max_e>500) h_si3_Al27_posi->Fill(si3_qsd300_max_x,si3_qsd300_max_y); for (int i=0;i<16;i++) { if(si4_1000_p_max_e>500) h_si4_Al27_posi->Fill(i,15-si4_1000_p_max_index); } // scaler h_scaler_T1->Fill(scaler[0]); h_scaler_T2->Fill(scaler[1]); h_scaler_T1_and_T2->Fill(scaler[2]); h_scaler_Gate->Fill(scaler[3]); h_scaler_Si1_P->Fill(scaler[4]); h_scaler_Si2_P->Fill(scaler[5]); h_scaler_Si4_P->Fill(scaler[6]); h_scaler_Si3->Fill(scaler[7]); // Si for (int i=0;i<16;i++) { //Si1 if (si1_60_p_max_e>500&&si1_60_n_max_e>500&&i==si1_60_p_max_index) { h_si1_60_p[i]->Fill(si1_60_p[i]); h_si1_60_p_sum->Fill(si1_60_p[i]); h_si1_60_n[i]->Fill(si1_60_n[i]); h_si1_60_n_sum->Fill(si1_60_n[i]); } //Si2 if (si2_60_p_max_e>500&&si2_60_n_max_e>500&&i==si2_60_p_max_index) { h_si2_60_p[i]->Fill(si2_60_p[i]); h_si2_60_p_sum->Fill(si2_60_p[i]); h_si2_60_n[i]->Fill(si2_60_n[i]); h_si2_60_n_sum->Fill(si2_60_n[i]); } //Si4 if (si4_1000_n_max_e>500&&i==si4_1000_p_max_index) { h_si4_1000_p[i]->Fill(si4_1000_p[i]); h_si4_1000_p_sum->Fill(si4_1000_p[i]); h_si4_1000_n[i]->Fill(si4_1000_n[i]); h_si4_1000_n_sum->Fill(si4_1000_n[i]); } } for (int i=0;i<4;i++) { if (si3_qsd300_max_e>500) { h_si3_qsd300[i]->Fill(si3_qsd300[i]); h_si3_qsd300_sum->Fill(si3_qsd300[i]); } } //CsI, ADC h_csi_adc[0]->Fill(csi_adc_1[0]); h_csi_adc[1]->Fill(csi_adc_1[9]); h_csi_adc[2]->Fill(csi_adc_1[12]); h_csi_adc[3]->Fill(csi_adc_1[3]); h_csi_adc[4]->Fill(csi_adc_1[11]); h_csi_adc[5]->Fill(csi_adc_1[5]); h_csi_adc[6]->Fill(csi_adc_1[6]); h_csi_adc[7]->Fill(csi_adc_1[7]); h_csi_adc[8]->Fill(csi_adc_1[8]); h_csi_adc[9]->Fill(csi_adc_1[1]); h_csi_adc[10]->Fill(csi_adc_1[10]); h_csi_adc[11]->Fill(csi_adc_1[2]); h_csi_adc[12]->Fill(csi_adc_1[13]); h_csi_adc[13]->Fill(csi_adc_1[4]); h_csi_adc[14]->Fill(csi_adc_1[14]); h_csi_adc[15]->Fill(csi_adc_1[15]); h_csi_adc[16]->Fill(csi_adc_2[0]); h_csi_adc[17]->Fill(csi_adc_2[9]); h_csi_adc[18]->Fill(csi_adc_2[13]); h_csi_adc[19]->Fill(csi_adc_2[3]); h_csi_adc[20]->Fill(csi_adc_2[4]); h_csi_adc[21]->Fill(csi_adc_2[5]); h_csi_adc[22]->Fill(csi_adc_2[6]); h_csi_adc[23]->Fill(csi_adc_2[14]); h_csi_adc[24]->Fill(csi_adc_2[8]); h_csi_adc[25]->Fill(csi_adc_2[15]); h_csi_adc[26]->Fill(csi_adc_2[10]); h_csi_adc[27]->Fill(csi_adc_2[1]); h_csi_adc[28]->Fill(csi_adc_2[2]); h_csi_adc[29]->Fill(csi_adc_2[12]); h_csi_adc[30]->Fill(csi_adc_2[7]); h_csi_adc[31]->Fill(csi_adc_3[11]); h_csi_adc[32]->Fill(csi_adc_3[0]); h_csi_adc[33]->Fill(csi_adc_3[8]); h_csi_adc[34]->Fill(csi_adc_3[9]); h_csi_adc[35]->Fill(csi_adc_3[3]); h_csi_adc[36]->Fill(csi_adc_3[1]); h_csi_adc[37]->Fill(csi_adc_3[2]); h_csi_adc[38]->Fill(csi_adc_3[10]); h_csi_adc[39]->Fill(csi_adc_3[4]); h_csi_adc[40]->Fill(csi_adc_3[12]); h_csi_adc[41]->Fill(csi_adc_3[13]); h_csi_adc_sum->Fill(csi_adc_1[0]); h_csi_adc_sum->Fill(csi_adc_1[9]); h_csi_adc_sum->Fill(csi_adc_1[12]); h_csi_adc_sum->Fill(csi_adc_1[3]); h_csi_adc_sum->Fill(csi_adc_1[11]); h_csi_adc_sum->Fill(csi_adc_1[5]); h_csi_adc_sum->Fill(csi_adc_1[6]); h_csi_adc_sum->Fill(csi_adc_1[7]); h_csi_adc_sum->Fill(csi_adc_1[8]); h_csi_adc_sum->Fill(csi_adc_1[1]); h_csi_adc_sum->Fill(csi_adc_1[10]); h_csi_adc_sum->Fill(csi_adc_1[2]); h_csi_adc_sum->Fill(csi_adc_1[13]); h_csi_adc_sum->Fill(csi_adc_1[4]); h_csi_adc_sum->Fill(csi_adc_1[14]); h_csi_adc_sum->Fill(csi_adc_1[15]); h_csi_adc_sum->Fill(csi_adc_2[0]); h_csi_adc_sum->Fill(csi_adc_2[9]); h_csi_adc_sum->Fill(csi_adc_2[13]); h_csi_adc_sum->Fill(csi_adc_2[3]); h_csi_adc_sum->Fill(csi_adc_2[4]); h_csi_adc_sum->Fill(csi_adc_2[5]); h_csi_adc_sum->Fill(csi_adc_2[6]); h_csi_adc_sum->Fill(csi_adc_2[14]); h_csi_adc_sum->Fill(csi_adc_2[8]); h_csi_adc_sum->Fill(csi_adc_2[15]); h_csi_adc_sum->Fill(csi_adc_2[10]); h_csi_adc_sum->Fill(csi_adc_2[1]); h_csi_adc_sum->Fill(csi_adc_2[2]); h_csi_adc_sum->Fill(csi_adc_2[12]); h_csi_adc_sum->Fill(csi_adc_2[7]); h_csi_adc_sum->Fill(csi_adc_3[11]); h_csi_adc_sum->Fill(csi_adc_3[0]); h_csi_adc_sum->Fill(csi_adc_3[8]); h_csi_adc_sum->Fill(csi_adc_3[9]); h_csi_adc_sum->Fill(csi_adc_3[3]); h_csi_adc_sum->Fill(csi_adc_3[1]); h_csi_adc_sum->Fill(csi_adc_3[2]); h_csi_adc_sum->Fill(csi_adc_3[10]); h_csi_adc_sum->Fill(csi_adc_3[4]); // h_csi_adc_sum->Fill(csi_adc_3[12]); //the gain of A41 and of A42 is different from the others // h_csi_adc_sum->Fill(csi_adc_3[13]); //TOF&Si, TDC h_TOF_T1_TDC->Fill(tof_si_tdc[0]); h_TOF_T2_TDC->Fill(tof_si_tdc[1]); h_Si1_P_TDC->Fill(tof_si_tdc[2]); h_Si2_P_TDC->Fill(tof_si_tdc[3]); h_Si4_P_TDC->Fill(tof_si_tdc[4]); h_Si3_TDC->Fill(tof_si_tdc[5]); //CsI, TDC h_csi_tdc[0]->Fill(csi_tdc_1[0]); h_csi_tdc[1]->Fill(csi_tdc_1[9]); h_csi_tdc[2]->Fill(csi_tdc_1[12]); h_csi_tdc[3]->Fill(csi_tdc_1[3]); h_csi_tdc[4]->Fill(csi_tdc_1[11]); h_csi_tdc[5]->Fill(csi_tdc_1[5]); h_csi_tdc[6]->Fill(csi_tdc_1[6]); h_csi_tdc[7]->Fill(csi_tdc_1[7]); h_csi_tdc[8]->Fill(csi_tdc_1[8]); h_csi_tdc[9]->Fill(csi_tdc_1[1]); h_csi_tdc[10]->Fill(csi_tdc_1[10]); h_csi_tdc[11]->Fill(csi_tdc_1[2]); h_csi_tdc[12]->Fill(csi_tdc_1[13]); h_csi_tdc[13]->Fill(csi_tdc_1[4]); h_csi_tdc[14]->Fill(csi_tdc_1[14]); h_csi_tdc[15]->Fill(csi_tdc_1[15]); h_csi_tdc[16]->Fill(csi_tdc_2[0]); h_csi_tdc[17]->Fill(csi_tdc_2[9]); h_csi_tdc[18]->Fill(csi_tdc_2[13]); h_csi_tdc[19]->Fill(csi_tdc_2[3]); h_csi_tdc[20]->Fill(csi_tdc_2[4]); h_csi_tdc[21]->Fill(csi_tdc_2[5]); h_csi_tdc[22]->Fill(csi_tdc_2[6]); h_csi_tdc[23]->Fill(csi_tdc_2[14]); h_csi_tdc[24]->Fill(csi_tdc_2[8]); h_csi_tdc[25]->Fill(csi_tdc_2[15]); h_csi_tdc[26]->Fill(csi_tdc_2[10]); h_csi_tdc[27]->Fill(csi_tdc_2[1]); h_csi_tdc[28]->Fill(csi_tdc_2[2]); h_csi_tdc[29]->Fill(csi_tdc_2[12]); h_csi_tdc[30]->Fill(csi_tdc_2[7]); h_csi_tdc[31]->Fill(csi_tdc_3[11]); h_csi_tdc[32]->Fill(csi_tdc_3[0]); h_csi_tdc[33]->Fill(csi_tdc_3[8]); h_csi_tdc[34]->Fill(csi_tdc_3[9]); h_csi_tdc[35]->Fill(csi_tdc_3[3]); h_csi_tdc[36]->Fill(csi_tdc_3[1]); h_csi_tdc[37]->Fill(csi_tdc_3[2]); h_csi_tdc[38]->Fill(csi_tdc_3[10]); h_csi_tdc[39]->Fill(csi_tdc_3[4]); h_csi_tdc[40]->Fill(csi_tdc_3[12]); h_csi_tdc[41]->Fill(csi_tdc_3[13]); h_csi_tdc_sum->Fill(csi_tdc_1[0]); h_csi_tdc_sum->Fill(csi_tdc_1[9]); h_csi_tdc_sum->Fill(csi_tdc_1[12]); h_csi_tdc_sum->Fill(csi_tdc_1[3]); h_csi_tdc_sum->Fill(csi_tdc_1[11]); h_csi_tdc_sum->Fill(csi_tdc_1[5]); h_csi_tdc_sum->Fill(csi_tdc_1[6]); h_csi_tdc_sum->Fill(csi_tdc_1[7]); h_csi_tdc_sum->Fill(csi_tdc_1[8]); h_csi_tdc_sum->Fill(csi_tdc_1[1]); h_csi_tdc_sum->Fill(csi_tdc_1[10]); h_csi_tdc_sum->Fill(csi_tdc_1[2]); h_csi_tdc_sum->Fill(csi_tdc_1[13]); h_csi_tdc_sum->Fill(csi_tdc_1[4]); h_csi_tdc_sum->Fill(csi_tdc_1[14]); h_csi_tdc_sum->Fill(csi_tdc_1[15]); h_csi_tdc_sum->Fill(csi_tdc_2[0]); h_csi_tdc_sum->Fill(csi_tdc_2[9]); h_csi_tdc_sum->Fill(csi_tdc_2[13]); h_csi_tdc_sum->Fill(csi_tdc_2[3]); h_csi_tdc_sum->Fill(csi_tdc_2[4]); h_csi_tdc_sum->Fill(csi_tdc_2[5]); h_csi_tdc_sum->Fill(csi_tdc_2[6]); h_csi_tdc_sum->Fill(csi_tdc_2[14]); h_csi_tdc_sum->Fill(csi_tdc_2[8]); h_csi_tdc_sum->Fill(csi_tdc_2[15]); h_csi_tdc_sum->Fill(csi_tdc_2[10]); h_csi_tdc_sum->Fill(csi_tdc_2[1]); h_csi_tdc_sum->Fill(csi_tdc_2[2]); h_csi_tdc_sum->Fill(csi_tdc_2[12]); h_csi_tdc_sum->Fill(csi_tdc_2[7]); h_csi_tdc_sum->Fill(csi_tdc_3[11]); h_csi_tdc_sum->Fill(csi_tdc_3[0]); h_csi_tdc_sum->Fill(csi_tdc_3[8]); h_csi_tdc_sum->Fill(csi_tdc_3[9]); h_csi_tdc_sum->Fill(csi_tdc_3[3]); h_csi_tdc_sum->Fill(csi_tdc_3[1]); h_csi_tdc_sum->Fill(csi_tdc_3[2]); h_csi_tdc_sum->Fill(csi_tdc_3[10]); h_csi_tdc_sum->Fill(csi_tdc_3[4]); Al27_count++; } if(si1_60_p_max_e>500&&tof>0) { h_TOF_deltaE_p->Fill(tof,si1_60_p_max_e); count++; // cout<<si1_60_p_max_e<<endl; } if(si1_60_n_max_e>500&&tof>0) h_TOF_deltaE_n->Fill(tof,si1_60_n_max_e); }//end event loop f->Close(); } //end file loop // h_TOF_deltaE_p->Write(); // h_TOF_deltaE_n->Write(); // h_si1_Al27_posi->Write(); // h_si2_Al27_posi->Write(); // h_si3_Al27_posi->Write(); // h_si4_Al27_posi->Write(); // ribll_gdr->Write(); rootf->Write(); rootf->Close(); Al27_purity=Al27_count*1.0/count; cout<<"Number of total entries:"<<totalentries<<endl; cout<<"Number of events:"<<count<<endl; cout<<"Number of Al27:"<<Al27_count<<endl; cout<<"Purity of Al27:"<<Al27_purity*100<<"%"<<endl; } //end main() <file_sep>/ribllvmedaq/TDataFileReader.cpp ////////////////////////////////////////////////// // TDataFileReader.cpp: Read the data file for // offline analysis. Save the 'File header' to // a log file and loop reading to the end of the // file. // <NAME> (08/2012) ////////////////////////////////////////////////// #include <iostream> #include <fstream> #include <exception> using namespace std; #include "TSystem.h" #include "TString.h" #include "TDataFileReader.h" #include "caenacq.h" //int *TDataFileReader::fevtbuf = 0; //int TDataFileReader::evtlen = 0; //ifstream TDataFileReader::infile; //ofstream TDataFileReader::logfile; TDataFileReader::TDataFileReader() { try { fevtbuf = new unsigned int[VME_Crate_BufLENGTH/4]; } catch(bad_alloc &e) { cout<<"TDataFileReader>> " << e.what() << endl; } TString path_name = gSystem->Getenv(gDataPath.c_str()); path_name += "/DataFile_log.txt"; logfile.open(path_name.Data()); } TDataFileReader::~TDataFileReader() { SafeDeleteArr(fevtbuf); } bool TDataFileReader::OpenDataFile(const char* fname) { infile.open(fname, ios_base::binary); if(infile.fail()) cout<<"Open data file: " << fname << " ERROR!" << endl; return ( infile.good() ); } void TDataFileReader::CloseDataFile() { infile.close(); } bool TDataFileReader::EvtReadingLoop() { if(!infile.good()) return false; //if(infile.eof()) return false; //if(infile.fail()) return false; //if(infile.bad()) return false; unsigned int endmark = Event_Header; unsigned int* read_pointer = fevtbuf; unsigned int end = 0; evtlen = 0; while((end != endmark) && (evtlen<(int)(VME_Crate_BufLENGTH/4))) // one event read while 'Event_Header' met. { if(infile.eof()) return false; if(infile.fail()) return false; infile.read((char*)read_pointer, sizeof(unsigned int)); //read 4-byte, an int value end = *read_pointer; //cout << "this value: " << end << " evtlen: " << evtlen << endl; read_pointer++; evtlen++; //this event length } return true; } bool TDataFileReader::SkipFileHeader() { if(!infile.good()) return false; char *fheader = new char[FileHeaderLEN]; infile.read(fheader, FileHeaderLEN); logfile<<fheader; delete[] fheader; int firstheader = 0; infile.read((char*)&firstheader, sizeof(int)); if (firstheader == Event_Header) return true; return false; }<file_sep>/ribllvmedaq/TDataAnalyser.cpp //////////////////////////////////////////////////// // TDataAnalyser.cpp: Global data decoder, used for // data analysis. // <NAME> (08/2012) /////////////////////////////////////////////////// #include <exception> #include <iostream> #include <fstream> #include <vector> #include <map> #include <list> using namespace std; #include "caenacq.h" #include "TDataAnalyser.h" #include "TConfig.h" #include "TBoard.h" map<int, TBoard *> TDataAnalyser::CrateGeo_Mod; map<int, unsigned int> eventcountermod; bool ecerror = false; TDataAnalyser::TDataAnalyser(TConfig *config) { int status = config->GetConfigNames(); if(status<0) return; status = config->ReadConfigForAnalysis(); if(status<0) return; list<TBoard *> boardlist = config->GetBoardList(); list<TBoard *>::const_iterator it = boardlist.begin(); for(it; it!=boardlist.end(); it++) { unsigned int tcrate = (*it)->GetCrateNum(); unsigned int tgeo = (*it)->GetGeo(); unsigned int pseudocg = tcrate*100 + tgeo; geotable.push_back(pseudocg); //int mod = (*it)->GetCrateNum() * 100 + tgeo; CrateGeo_Mod[pseudocg] = (*it); eventcountermod[pseudocg] = 0; } } //evtbuf: event buffer; num: event length in int unsigned int TDataAnalyser::GlobalDecoder(unsigned int *&evtbuf, int num) { unsigned int eventcount=0, cratenum=0, geo=0; unsigned int pointerid = 0; unsigned int* sentinel = evtbuf; if(evtbuf[0] == Event_Header) return -1; // first data should be the eventcounter(Max:0x10000000) eventcount = evtbuf[0]; evtbuf += 1; //to the crate header if((*evtbuf) != Crate_Header) return -1; // data format error bool geook = false; try { InitAllBoardData(); //set all data to 0 (out of the event 'do' loop) do //crate numbers loop (loop on one event) { if((*evtbuf) == Event_Header) break; evtbuf += 1; //to the crate id cratenum = *evtbuf; evtbuf += 7; //skip 'crate header' data ecerror = false; do //modules numbers loop { if((*evtbuf) == Event_Header) break; if((*evtbuf) == Crate_Header) break; //found 'crate_header' break //this "Geo" function is very important geo = GlobalGeo(evtbuf); pointerid = cratenum*100 + geo; TBoard *mod = GetTBoardPointer(cratenum, geo); int necounter = -1; if(mod) { necounter = mod->Decode(evtbuf); //Send the data to the module classs its self, main analysis procedure. if(necounter>0) { evcheck(necounter, pointerid, mod); } } evtbuf++; //to next data }while(evtbuf<(sentinel + num)); //modules numbers loop evcheckprint(); }while(evtbuf<(sentinel + num)); //crate numbers loop } catch(exception &e) { cerr << "exception caught: " << e.what() << endl; } return eventcount; } //This 'GlobalGeo' function is very important, all modules must be //'identified', i.e. get its unique id, in this function. // //For module V775*, V785*, V830, V792*, this function 'geo = tdata>>27' //For module V1190*, V1290* ... this function is different, and may //confused with other kind of modules(like V7*** family), however you //must manage to identify them. //An alternative way is read the modules which may cause confusion //separately (i.e. do not read them in the main CBLT loop) by calling //the 'VMEReadBeforeCBLT(...)' and 'VMEReadAfterCBLT(...)' function, //in this way you can 'write' a 'mark' value in the data file(similar to //'Event_Header'). //Any how, all modules in the data must be identified in this function. unsigned int TDataAnalyser::GlobalGeo(const unsigned int *const evtbuf) { //do not change the value of 'evtbuf', i.e. do not do something //like: *evtbuf = n, *(evtbuf+1) =n, evtbuf++, evtbuf += 1 ... unsigned int tdata = *evtbuf; unsigned int tgeo = tdata>>27; return tgeo; //an example about how to identify V1290 //example beging------------------------------- //if(tgeo == 8) //data 'global header' of V1290 //{ // tgeo = *(evtbuf+1); // following 'global header' is the 'the TDC Header' // if(tgeo == 1) return (tdata<<27)>>27; // the true 'Geo' of V1290 //} //example end---------------------------------- //an example about how to identify data which is not read by CBLT //example beging------------------------------- //if(tdata == 0x2A00FFFF) return tdata>>26; //if(tdata == 0x2B00FFFF) return tdata>>26; //example end---------------------------------- } //Get the TBoard* pointer by the pseudo id: Crate*100 + Geo TBoard* TDataAnalyser::GetTBoardPointer(const unsigned int crate, const unsigned int geo) { bool cgok = false; unsigned int pseudocg = crate*100 + geo; for(unsigned int i=0; i<geotable.size(); i++) { if(pseudocg == geotable.at(i)) { cgok = true; break; } else { cgok = false; } } if(cgok) { return CrateGeo_Mod[pseudocg]; } else { return 0; } } void TDataAnalyser::InitAllBoardData() { map<int, TBoard *>::iterator it = CrateGeo_Mod.begin(); for(it; it != CrateGeo_Mod.end(); it++) { (*it).second->CleanChData(); } } unsigned int TDataAnalyser::GetRawData(unsigned int Crate, unsigned int Geo, unsigned int channel) { unsigned int CGid = Crate*100 + Geo; unsigned int value = 0; TBoard *mod = GetTBoardPointer(Crate, Geo); if(mod) { value = mod->GetChannelData(channel); } return value; } void TDataAnalyser::evcheck(int necounter, int pointerid, TBoard * const mod) { int diff = -1; diff = necounter - eventcountermod[pointerid]; if(diff>=0 && diff!=1 && eventcountermod[pointerid]!=0) { //cout << "Mod" << pointerid << "-" << mod->GetName() << " eventcounter error? last ec1= " << eventcountermod[pointerid] << " this ec2= " << necounter << endl; //ecerror = true; } eventcountermod[pointerid] = necounter; } void TDataAnalyser::evcheckprint() { if(ecerror) { map<int, unsigned int>::iterator it; for(it=eventcountermod.begin(); it!=eventcountermod.end(); it++) cout << "Mod" << it->first <<" this ec= " << it->second << endl; } } <file_sep>/ribllvmedaq/ana_wangyuting.cpp /////////////////////////////////////////////// // An Raw2ROOT.cpp: main() of Raw2ROOT, used // for offline data analysis. // <NAME> Modified (04/2015) /////////////////////////////////////////////// #include "TApplication.h" #include "TDAQApplication.h" #include "TConfig.h" #include "TDataFileReader.h" #include "TDataAnalyser.h" #include "TString.h" #include "TFile.h" #include "TTree.h" #include "TH1F.h" #include "TH2F.h" #include "TSystem.h" #include "TMath.h" #include "TVector3.h" #include "TROOT.h" #include "TApplication.h" #include "TFile.h" #include "TH1.h" #include "TH2.h" #include "TF1.h" #include "TFormula.h" #include "TProfile.h" #include "TNtuple.h" #include "TRandom.h" #include "TApplication.h" #include "TCanvas.h" #include "TDirectory.h" #include "TStyle.h" #include "TText.h" #include "TLatex.h" #include "TLine.h" #include "TPad.h" #include "TObjArray.h" #include "TTree.h" #include "TBranch.h" #include "TStopwatch.h" #include "TGraph.h" #include "TGraphErrors.h" #include "TLegend.h" #include "TFrame.h" #include "TF1.h" #include "TMinuit.h" #include "TBoard.h" #include "TModV830AC.h" #include "TModV785.h" #include "TModV785N.h" #include "TModV775.h" #include "TModV775N.h" #include "TModV792.h" #include <iostream> #include <sstream> #include <fstream> #include <stdlib.h> #include <vector> #include <map> #include<cstdlib> using namespace std; int main(int argc,char **argv) { int runnum; if(argc==2) { runnum=atoi(argv[1]); } else { cout<<"USAG: ./cali [runnum]"<<endl; return -1; } cout<<"runnum : "<<runnum<<endl; //constant float Pi=3.1415926; TString raw_file; raw_file="/home/daq/vme-single_201605/vmedata/20160518003"; //input file name TFile *f; TString rootfile=Form("%s%04d.root",raw_file.Data(),runnum); f=new TFile(rootfile.Data()); cout<<"The input root file is: "<<rootfile<<endl; TTree *tree; //get the tree in *.root //tree=(TTree*)gFile->Get("RawData"); tree=(TTree*) f->Get("RawData"); Int_t nentries; nentries=(Int_t)tree->GetEntries(); cout<<"All the entry number: "<<nentries<<endl; TBranch *bran103 = 0; TBranch *bran104 = 0; TBranch *bran106 = 0; TBranch *bran108 = 0; TBranch *bran110 = 0; TBranch *bran112 = 0; TBranch *bran114 = 0; TBranch *bran116 = 0; TBranch *bran118 = 0; TBranch *bran120 = 0; TModV830AC *vmod103 = new TModV830AC(); // TModV785 *vmod104 = new TModV785(); //Si1 60um TModV785 *vmod106 = new TModV785(); //Si2 60um TModV785 *vmod108 = new TModV785(); //Si4 100um TModV785 *vmod110 = new TModV785(); //QSD 300um TModV785 *vmod112 = new TModV785(); // TModV785N *vmod114 = new TModV785N(); TModV775N *vmod116 = new TModV775N(); TModV775 *vmod118 = new TModV775(); TModV775 *vmod120 = new TModV775(); tree->SetBranchAddress("Mod103_TModV830AC",&vmod103,&bran103); tree->SetBranchAddress("Mod104_TModV785",&vmod104,&bran104); tree->SetBranchAddress("Mod106_TModV785",&vmod106,&bran106); tree->SetBranchAddress("Mod108_TModV785",&vmod108,&bran108); tree->SetBranchAddress("Mod110_TModV785",&vmod110,&bran110); tree->SetBranchAddress("Mod112_TModV785",&vmod112,&bran112); tree->SetBranchAddress("Mod114_TModV785N",&vmod114,&bran114); tree->SetBranchAddress("Mod116_TModV775N",&vmod116,&bran116); tree->SetBranchAddress("Mod118_TModV775",&vmod118,&bran118); tree->SetBranchAddress("Mod120_TModV775",&vmod120,&bran120); //TH1F *h_si1_60_p1=new TH1F("si1_60_p1","si1_60_p1",4096,0,4096); TFile *rootfile1 = new TFile("../vmedata/gdr2.root","RECREATE"); //rootfile1->Delete("T;*"); //TTree *TT = new TTree("T","../vmedata/DTH.root"); //TCanvas *c1=new TCanvas("c1","c1",700,900); TH2 *h1= new TH2D("h1","Tof dESi1",300, 0., 150., 200, 500, 3500.); TH2 *h2= new TH2D("h2","2D histo",16,0,16,16,0,16); int T1 = vmod116->chdata[0]; int T2 = vmod116->chdata[1]; for(int ievent =0; ievent<1; ievent++)//begin event loop { tree->GetEntry(ievent); int Mch1=0,Mch2=0; int Mch3=0,Mch4=0; int Nch1=0,Nch2=0; for(int i=0;i<16;i++) { Mch1=vmod104->chdata[i]; cout<<vmod104->chdata[i]<<endl; if(Mch1>Mch2)Nch1=i,Mch2=Mch1; Mch3=vmod104->chdata[i+16]; if(Mch3>Mch4)Nch2=i+16,Mch4=Mch3; //cout<<vmod104->chdata[i]<<endl; //Mch1=vmod106->chdata[i]; //if(Mch1>Mch2)Nch1=i,Mch2=Mch1; //Mch3=vmod106->chdata[i+16]; //if(Mch3>Mch4)Nch2=i+16,Mch4=Mch3; //vmod108->chdata[i]; //vmod108->chdata[i+16]; } int t21 = T2-T1; h1->Fill(t21,Mch2); h2->Fill(Nch1,Nch2-16); for(int i=0;i<16;i++) { //vmod110->chdata[i]; } }//end event loop //c1->cd(); //h2->Draw("contz"); h1->Write(); h2->Write(); //c1->SaveAs("../vmedata/for_test-gdr-2.png"); } <file_sep>/ribllvmedaq/TControl.cpp ///////////////////////////////////////// // TControl.cpp: Control the daq // This class contents a socket used to // receive 'control commands' from // the cotrol side PC // <NAME> 07/2012 ///////////////////////////////////////// #include <iostream> #include <string> #include "stdlib.h" #include "TUDPClientSocket.h" #include "TUDPServerSocket.h" #ifdef WIN32 #include <windows.h> #define sleep Sleep #define WaitSec 600 #else #include <unistd.h> #define sleep usleep #define WaitSec 300000 #endif using namespace std; #include "caenacq.h" #include "TControl.h" #include "Rtypes.h" #include "TServerSocket.h" #include "TSocket.h" #include "TString.h" #include "TThread.h" TSocket * TControl::iRecvSocket=0; TServerSocket *TControl::iSendSocket=0; TSocket *TControl::iSendSocket_imp=0; TUDPClientSocket *TControl::iComBroadUDPSock=0; TUDPServerSocket *TControl::iComRevUDPSock=0; TUDPClientSocket *TControl::iFHeBroadUDPSock=0; TUDPServerSocket *TControl::iFHeRevUDPSock=0; eAction TControl::PC_Action; string TControl::sRecvComm; bool TControl::TCPwait_command; bool TControl::TCPRead_command; bool TControl::UDPwait_command; string TControl::ControlPCAddr; string TControl::fheader_file; string TControl::ack_mess; //string TControl::other_mess; ECommands TControl::comm; static string Comm_Acknowlege = " COMMAND ACKNOWLEDGED"; static string Comm_Not_Acknow = " Do not receive acknlwlege form DAQ_PC." ; const string tname = "TControl>> "; TControl *onlyControl = 0; ClassImp(TControl); TControl::TControl(const char *netaddr, eAction action) { if(onlyControl) { cout<< "TControl>> only one instance of TControl allowed. " << endl; return; } onlyControl = this; iRecvSocket = 0; iSendSocket = 0; iSendSocket_imp = 0; iComBroadUDPSock = 0; iComRevUDPSock = 0; iFHeBroadUDPSock = 0; iFHeRevUDPSock = 0; thread_DaqPC = 0; thread_OnlinePC = 0; thread_ConPCRevErr = 0; PC_Action = NULL_PC; TCPwait_command = false; TCPRead_command = false; UDPwait_command = false; comm = kC_WAIT; if(action == DAQ_PC) { PC_Action = DAQ_PC; //iRecvSocket = new TSocket(netaddr, TCPCommPort); ControlPCAddr = netaddr; //TString staddr = netaddr; //int pos = staddr.Last('.'); //staddr.Replace(pos+1, 3, "255"); string path = getenv(gConfPath.c_str()); path += IPLISTF; iComBroadUDPSock = new TUDPClientSocket(path.c_str(), UDPCommBroadPort, 'c'); if(!iComBroadUDPSock->IsValid()) cout << tname << " ComBroadUDPSock error. "<< endl; iFHeBroadUDPSock = new TUDPClientSocket(path.c_str(), UDPFHBroadPort, 'f'); if(!iFHeBroadUDPSock->IsValid()) cout << tname << " FHeBroadUDPSock error. "<< endl; //DaqPCWaitConnection(); TCPwait_command = true; TCPRead_command = true; } else if(action == CONTROL_PC) { PC_Action = CONTROL_PC; iSendSocket = new TServerSocket(TCPCommPort, kTRUE); iComRevUDPSock = new TUDPServerSocket(UDPCommBroadPort); // used to receive some broadcast messages here. if(!iComRevUDPSock->IsValid()) cout << tname << " ComRevUDPSock error. "<< endl; UDPwait_command = true; } else if(action == ONLINE_PC) { PC_Action = ONLINE_PC; iComRevUDPSock = new TUDPServerSocket(UDPCommBroadPort); if(!iComRevUDPSock->IsValid()) cout << tname << " ComRevUDPSock error. "<< endl; iFHeRevUDPSock = new TUDPServerSocket(UDPFHBroadPort); if(!iFHeRevUDPSock->IsValid()) cout << tname << " FHeRevUDPSock error. "<< endl; UDPwait_command = true; } } TControl::~TControl() { SafeDeleteP(iRecvSocket); SafeDeleteP(iSendSocket); SafeDeleteP(iSendSocket_imp); SafeDeleteP(iComBroadUDPSock); SafeDeleteP(iComRevUDPSock); SafeDeleteP(iFHeBroadUDPSock); SafeDeleteP(iFHeRevUDPSock); } ///////////////////////////////////////////////////////////////// // Block the Process ( use while(true) ) to wait for // conneciton form Control_PC // The 'while(true)' infenite loop will block the process // until a success connection to Control PC is established ///////////////////////////////////////////////////////////////// bool TControl::DaqPCWaitConnection() { while(true) //this 'while' will block the process until a success connection to Control PC is established { cout << "Waiting for connection to Control_PC...... " << endl; sleep(WaitSec); L150: if(iRecvSocket) { if(iRecvSocket->IsValid()) { return true; // break out thi } else { delete iRecvSocket; iRecvSocket = 0; goto L150; } } else { iRecvSocket = new TSocket(ControlPCAddr.c_str(), TCPCommPort); if(iRecvSocket->IsValid()) return true; } } } //used for DAQ_PC to receive the control command void* TControl::recv_TCPcontrol_command(void *arg) { DaqPCWaitConnection(); if(!iRecvSocket) { cout << "TControl: Communiction socket for receiving 'command' invalid." << endl; return 0; } TCPwait_command = true; TCPRead_command = true; char commbuf[200]; int bufsize = sizeof(commbuf); char fhbuf[FileHeaderLEN]; int inmess_len = 0, outmess_len = 0; while(TCPwait_command) { sleep(WaitSec); memset(commbuf, 0x0, bufsize); int i=0; while(TCPRead_command) { sleep(WaitSec); if(iRecvSocket->IsValid()) break; // normal break, used while the connection working well if(DaqPCWaitConnection()) break; // if reconnect the Control_PC, if the connection is not valid. } //cout << " Waiting for command ...... " << endl; inmess_len = iRecvSocket->Recv(commbuf, bufsize); sRecvComm = commbuf; //cout << " Got 'command': " << sRecvComm << endl; // test connection if(sRecvComm == sCommands[0]) { comm = kC_TEST; if(outmess_len=iRecvSocket->Send("Server is Alive and Ready") < 0) { cout<<tname<<"Error sending reply message to control master PC."<<endl; } CommandForward(sRecvComm); MessageSignal(arg); continue; } // Initialization if(sRecvComm == sCommands[1]) { comm = kC_INIT; CommandForward(sRecvComm); acknowledge(); MessageSignal(arg); continue; } // Start if(sRecvComm == sCommands[2]) { comm = kC_START; CommandForward(sRecvComm); acknowledge(); MessageSignal(arg); continue; } // Stop if(sRecvComm == sCommands[3]) { comm = kC_STOP; //the master forwards STOP command to all servers CommandForward(sRecvComm); acknowledge(); MessageSignal(arg); continue; } // Open file if(sRecvComm == sCommands[4]) { if(iRecvSocket->Select(TSocket::kRead, 800)) // waiting the control PC to send the data file header { if( (inmess_len = iRecvSocket->Recv(fhbuf, FileHeaderLEN)) <0 ) { cout<<tname<<"Error receiving data file header from control master PC."<<endl; continue; } } else { cout << tname << " Time Out! Wait for the data file header." << endl; continue; } fheader_file = fhbuf; cout<<tname<< " Got File Header: " <<fheader_file<<endl; comm = kC_FOPEN; CommandForward(sRecvComm); sleep(WaitSec); // Wait for other online monitering PC to accept the 'file header' fheader_file BroadFileHeader(); // Broadcast the file header to all online monitering PC acknowledge(); MessageSignal(arg); continue; } // Close File if(sRecvComm == sCommands[5]) { comm = kC_FCLOSE; CommandForward(sRecvComm); acknowledge(); MessageSignal(arg); continue; } //exit and put offline if(sRecvComm == sCommands[6]) { comm = kC_EXIT; CommandForward(sRecvComm); acknowledge(); //comm = kC_WAIT; TCPwait_command = false; MessageSignal(arg); sleep(WaitSec); continue; } // for not a valide 'command' CommandForward(sRecvComm); acknowledge(); } return 0; } int TControl::CommandForward(string message) { int len = 0; if(iComBroadUDPSock && (PC_Action == DAQ_PC) ) { len = iComBroadUDPSock->SendTo(message.c_str(), message.size()); if(len<=0) cout << tname << " Error broadcast commands." << endl; } return len; } void TControl::acknowledge() { if( iRecvSocket && (PC_Action == DAQ_PC) ) { TString ackmess = sRecvComm; ackmess += Comm_Acknowlege; iRecvSocket->Select(TSocket::kWrite, 800); int len = iRecvSocket->Send(ackmess.Data()); if(len<0) cout << tname << "Error sending Acknowledge."<<endl; } } void TControl::BroadFileHeader() { if(iFHeBroadUDPSock && (PC_Action == DAQ_PC) ) { int len = iFHeBroadUDPSock->SendTo(fheader_file.c_str(), fheader_file.size()); if(len<=0) cout << tname << " Error broadcast data file header." << endl; } } TThread * TControl::GetDaqPCThread() { if(thread_DaqPC) { TThread::EState stat = thread_DaqPC->GetState(); if(stat == TThread::kRunningState || stat == TThread::kNewState) return thread_DaqPC; } return 0; } TThread * TControl::GetOnlinePCThread() { return thread_OnlinePC; } void* TControl::recv_UDPBroadcontrol_command(void *arg) { if(!iComRevUDPSock) { cout << "TControl: Communiction UDP socket for receiving UDP broadcasted 'command' invalid." << endl; ack_mess = "TControl: Communiction UDP socket for receiving UDP broadcasted 'command' invalid."; MessageSignal(arg); return 0; } UDPwait_command = true; char commbuf[200]; int bufsize = sizeof(commbuf); char fhbuf[FileHeaderLEN]; int inmess_len = 0, outmess_len = 0; ack_mess = "Not a valid command."; while(UDPwait_command) { memset(commbuf, 0x0, sizeof(commbuf)); memset(fhbuf, 0x0, sizeof(fhbuf)); //cout << " Waiting for command ...... " << endl; inmess_len = iComRevUDPSock->RecvRaw(commbuf, bufsize); if(inmess_len<=0) { MessageSignal(arg); continue; } sRecvComm = commbuf; //cout << " Got command: " << sRecvComm << endl; // test connection if(sRecvComm == sCommands[0]) { comm = kC_TEST; ack_mess = sCommands[0]; ack_mess += Comm_Acknowlege; MessageSignal(arg); continue; } // Initialization if(sRecvComm == sCommands[1]) { comm = kC_INIT; ack_mess = sCommands[1]; ack_mess += Comm_Acknowlege; MessageSignal(arg); continue; } // Start if(sRecvComm == sCommands[2]) { comm = kC_START; ack_mess = sCommands[2]; ack_mess += Comm_Acknowlege; MessageSignal(arg); ControlSignal(arg, kC_START); continue; } // Stop if(sRecvComm == sCommands[3]) { comm = kC_STOP; ack_mess = sCommands[3]; ack_mess += Comm_Acknowlege; MessageSignal(arg); ControlSignal(arg, kC_STOP); continue; } // Open file if(sRecvComm == sCommands[4]) { if( ( inmess_len = iFHeRevUDPSock->RecvRaw(fhbuf, FileHeaderLEN) ) <0 ) { cout<<tname<<"Error receiving data file header from DAQ_PC's UDP broadcasting."<<endl; continue; } fheader_file = fhbuf; //cout<<tname<<fheader_file<<endl; comm = kC_FOPEN; ack_mess = sCommands[4]; ack_mess += Comm_Acknowlege; MessageSignal(arg); ControlSignal(arg, kC_FOPEN); continue; } // Close File if(sRecvComm == sCommands[5]) { comm = kC_FCLOSE; ack_mess = sCommands[5]; ack_mess += Comm_Acknowlege; MessageSignal(arg); ControlSignal(arg, kC_FCLOSE); continue; } //exit and put offline (do not used for OnlinePC) if(sRecvComm == sCommands[6]) { comm = kC_EXIT; ack_mess = sCommands[6]; ack_mess += Comm_Acknowlege; comm = kC_WAIT; MessageSignal(arg); continue; } ack_mess = sRecvComm; MessageSignal(arg); //ack_mess += " Is not a valide command!"; } return 0; } // for control_PC only, used to receive some no-command messages, // such as some errors, maybe useless void* TControl::recv_UDPBroadMessages(void *arg) { if(!iComRevUDPSock) { cout << "TControl: Communiction UDP socket for receiving UDP broadcasted 'command' invalid." << endl; ack_mess = "TControl: Communiction UDP socket for receiving UDP broadcasted 'command' invalid."; //MessageSignal(arg); BroadMessageSignal(arg); return 0; } UDPwait_command = true; char commbuf[200]; int bufsize = sizeof(commbuf); char fhbuf[FileHeaderLEN]; int inmess_len = 0, outmess_len = 0; while(UDPwait_command) { memset(commbuf, 0x0, sizeof(commbuf)); memset(fhbuf, 0x0, sizeof(fhbuf)); //cout << " Waiting for command ...... " << endl; inmess_len = iComRevUDPSock->RecvRaw(commbuf, bufsize); if(inmess_len<=0) continue; sRecvComm = commbuf; //cout << " Got command: " << sRecvComm << endl; // test connection if(sRecvComm == sCommands[0]) { continue; } // Initialization if(sRecvComm == sCommands[1]) { continue; } // Start if(sRecvComm == sCommands[2]) { continue; } // Stop if(sRecvComm == sCommands[3]) { continue; } // Open file if(sRecvComm == sCommands[4]) { continue; } // Close File if(sRecvComm == sCommands[5]) { } // exit and put offline (do not used by OnlinePC) if(sRecvComm == sCommands[6]) { continue; } // for some other messages ack_mess = sRecvComm; BroadMessageSignal(arg); //ack_mess += " Is not a valide command!"; } return 0; } //Waite for a TCP connection form DAQ_PC, even if the CONTROL_PC is power //on later than DAQ_PC. bool TControl::AcceptReceiver() { cout << " Waiting for DAQ_PC connection...... " << endl; if( !iSendSocket || (PC_Action != CONTROL_PC) ) { cout << "TControl: Communiction TCP socket for master control PC invalid." << endl; ack_mess = "TControl: Communiction TCP socket for master control PC invalid."; //MessageSignal(this); return false; } if(!iSendSocket_imp) { ack_mess = "Waiting for TCP connection from DAQPC..."; //MessageSignal(this); iSendSocket_imp = iSendSocket->Accept(); cout << " Communiction TCP socket established between Control_PC and DAQ_PC. " << endl; ack_mess = "Communiction TCP socket established between Control_PC and DAQ_PC. "; //MessageSignal(this); return true; } if(iSendSocket_imp) // for iSendSocket_imp exist, but not valid { if( iSendSocket_imp->IsValid() ) { ack_mess = "Communiction TCP socket established between Control_PC and DAQ_PC. "; //MessageSignal((void*)this); return true; } else { delete iSendSocket_imp; iSendSocket_imp =0; ack_mess = "Waiting for TCP connection from DAQPC..."; //MessageSignal((void*)this); iSendSocket_imp = iSendSocket->Accept(); cout << " Communiction TCP socket established between Control_PC and DAQ_PC. " << endl; ack_mess = " Communiction TCP socket established between Control_PC and DAQ_PC. "; //MessageSignal((void*)this); return true; } } return false; } bool TControl::send_TCPcontrol_command(string scomm) { if(iSendSocket_imp) { if(!iSendSocket_imp->IsValid() ) { cout << tname << "TControl: Communiction TCP socket for master control PC cannot Accept() to DAQ_PC." << endl; ack_mess = "TControl: Communiction TCP socket for master control PC cannot Accept() to DAQ_PC."; MessageSignal((void*)this); return false; } } else { ack_mess = "ERROR! TCP Socket between ControlPC and DAQ_PC not valied."; MessageSignal((void*)this); return false; } char commbuf[200]; int bufsize = sizeof(commbuf); memset(commbuf, 0x0, bufsize); int inmess_len = 0, outmess_len = 0; ack_mess = "Command Send Out Error."; bool sstatus = false; // cout << "Receiver waiting for connection..... " << endl; iSendSocket_imp->Select(TSocket::kWrite); // test connection if(scomm == sCommands[0]){ outmess_len = iSendSocket_imp->Send(sCommands[0].c_str()); if( outmess_len <0 ) { MessageSignal((void*)this); return false; } inmess_len = iSendSocket_imp->Recv(commbuf, bufsize); if(inmess_len) { ack_mess = commbuf; comm = kC_TEST; sstatus = true; } else { ack_mess = sCommands[0]; ack_mess += Comm_Not_Acknow; sstatus = false; } MessageSignal((void*)this); return sstatus; } // Initialization if(scomm == sCommands[1]){ outmess_len = iSendSocket_imp->Send(sCommands[1].c_str()); if( outmess_len <0 ) { MessageSignal((void*)this); return false; } inmess_len = iSendSocket_imp->Recv(commbuf, bufsize); if(inmess_len) { ack_mess = commbuf; comm = kC_INIT; sstatus = true; } else { ack_mess = sCommands[1]; ack_mess += Comm_Not_Acknow; sstatus = false; } MessageSignal((void*)this); return sstatus; } // Start if(scomm == sCommands[2]){ outmess_len = iSendSocket_imp->Send(sCommands[2].c_str()); if( outmess_len <0 ) { MessageSignal((void*)this); return false; } inmess_len = iSendSocket_imp->Recv(commbuf, bufsize); if(inmess_len) { ack_mess = commbuf; comm = kC_START; sstatus = true; ControlSignal((void*)this, kC_START); } else { ack_mess = sCommands[2]; ack_mess += Comm_Not_Acknow; sstatus = false; } MessageSignal((void*)this); return sstatus; } // Stop if(scomm == sCommands[3]){ outmess_len = iSendSocket_imp->Send(sCommands[3].c_str()); if( outmess_len <0 ) { MessageSignal((void*)this); return false; } inmess_len = iSendSocket_imp->Recv(commbuf, bufsize); if(inmess_len) { ack_mess = commbuf; comm = kC_STOP; sstatus = true; ControlSignal((void*)this, kC_STOP); } else { ack_mess = sCommands[3]; ack_mess += Comm_Not_Acknow; sstatus = false; } MessageSignal((void*)this); return sstatus; } // Open file if(scomm == sCommands[4]){ outmess_len = iSendSocket_imp->Send(sCommands[4].c_str()); if( outmess_len <0 ) { MessageSignal((void*)this); return false; } if(iSendSocket_imp->Select(TSocket::kWrite, 800)) { outmess_len = iSendSocket_imp->Send(fheader_file.c_str()); // Send the data file header to DAQ_PC if( outmess_len <0 ) { ack_mess = "TControl: 'File Header' send out ERROR."; MessageSignal((void*)this); return false; } } inmess_len = iSendSocket_imp->Recv(commbuf, bufsize); //cout <<" this message: "<< inmess_len << endl; if(inmess_len) { ack_mess = commbuf; comm = kC_FOPEN; sstatus = true; ControlSignal((void*)this, kC_FOPEN); } else { ack_mess = sCommands[4]; ack_mess += Comm_Not_Acknow; sstatus = false; } MessageSignal((void*)this); return sstatus; } // Close File if(scomm == sCommands[5]){ outmess_len = iSendSocket_imp->Send(sCommands[5].c_str()); if( outmess_len <0 ) { MessageSignal((void*)this); return false; } inmess_len = iSendSocket_imp->Recv(commbuf, bufsize); if(inmess_len) { ack_mess = commbuf; comm = kC_FCLOSE; sstatus = true; ControlSignal((void*)this, kC_FCLOSE); } else { ack_mess = sCommands[5]; ack_mess += Comm_Not_Acknow; sstatus = false; } MessageSignal((void*)this); return sstatus; } //exit and put offline if(scomm == sCommands[6]){ outmess_len = iSendSocket_imp->Send(sCommands[6].c_str()); if( outmess_len <0 ) { MessageSignal((void*)this); return false; } inmess_len = iSendSocket_imp->Recv(commbuf, bufsize); if(inmess_len) { ack_mess = commbuf; comm = kC_EXIT; sstatus = true; } else { ack_mess = sCommands[6]; ack_mess += Comm_Not_Acknow; sstatus = false; } MessageSignal((void*)this); return sstatus; } return false; } int TControl::StartDaqPCThread() { if(!thread_DaqPC) { thread_DaqPC = new TThread("DAQPCThread", (void*(*)(void *))(&TControl::recv_TCPcontrol_command), (void*)this); if(thread_DaqPC) { thread_DaqPC->Run(); cout << thread_DaqPC->GetName() << " is runing..." << endl; return 1; } else { thread_DaqPC = 0; return 0; } } else { thread_DaqPC->Run(); } return 1; } bool TControl::StartOnlinePCThread() { if(!thread_OnlinePC) { thread_OnlinePC = new TThread("OnlinePCThread", (void*(*)(void *))(&TControl::recv_UDPBroadcontrol_command), (void*)this); if(thread_OnlinePC) { thread_OnlinePC->Run(); cout << thread_OnlinePC->GetName() << " is running..." << endl; return (thread_OnlinePC->GetState() == TThread::kRunningState); } else { thread_OnlinePC = 0; return 0; } } else { return 0; } } bool TControl::StopOnlinePCThread() { UDPwait_command = false; sleep(WaitSec); if(thread_OnlinePC) { string thname = thread_OnlinePC->GetName(); int state = TThread::Delete(thread_OnlinePC); delete thread_OnlinePC; thread_OnlinePC = 0; cout << thname << " stopped." << endl; return true; } return true; } int TControl::StartConPCRecErrThread() { if(!thread_ConPCRevErr) { thread_ConPCRevErr = new TThread("ControlPCRevErr", (void*(*)(void*))(&TControl::recv_UDPBroadMessages), (void*)this); if(thread_ConPCRevErr) { thread_ConPCRevErr->Run(); cout<< thread_ConPCRevErr->GetName() << " is running..." << endl; return 1; } else { thread_ConPCRevErr = 0; return 0; } } else { return 0; } } void TControl::StopConPCRecErrThread() { sleep(WaitSec); if(thread_ConPCRevErr) { string thname = thread_ConPCRevErr->GetName(); TThread::Delete(thread_ConPCRevErr); delete thread_ConPCRevErr; thread_ConPCRevErr =0; cout << thname << " stopped." << endl; } } int TControl::BroadMessage(std::string message) { return CommandForward(message); } // Signal function used to Emit a 'ack_mess' changed signal void TControl::MessageSignal(void *arg) { TControl *pthis = (TControl *)arg; //if(pthis) cout << "pthis value ok "<< endl; //pthis->Emit("MessageSignal(void *)"); pthis->Emit("MSignalEmit()"); //cout << "here..."<<endl; } void TControl::BroadMessageSignal(void *arg) { TControl *pthis = (TControl *)arg; pthis->Emit("BMSignalEmit()"); } void TControl::MSignalEmit(){} void TControl::BMSignalEmit(){} bool TControl::GetTCPSendSocketState() { if(iSendSocket_imp) return iSendSocket_imp->IsValid(); return false; } bool TControl::ClosTCPimpSocket() { if(iSendSocket_imp) { delete iSendSocket_imp; iSendSocket_imp = 0; } return true; } void TControl::ControlSignal(void *arg, int comm) { TControl *pthis = (TControl *)arg; pthis->Emit("CommandSignal(int)", comm); } void TControl::CommandSignal(int comm){}; void TControl::printsignal() { cout << ".....Got Signal....." << endl; } <file_sep>/ribllvmedaq/TClientEvtBuilder.h //////////////////////////////////////////////// // TEvtBuilder.h: Class to perform the VME // reading and build the 'event' structure. // Use TCrateCBLT to loop reading procedure, // and then build the event in memory, then // send it out to ethernet by using UDP // socket. // <NAME> 07/2012 //////////////////////////////////////////////// #ifndef TClientEvtBuilder_H #define TClientEvtBuilder_H #include "TEvtBuilder.h" #include <RQ_OBJECT.h> class TUDPClientSocket; class TThread; class TClientEvtBuilder: public TEvtBuilder { RQ_OBJECT("TClientEvtBuilder") protected: static TUDPClientSocket *DataBroadUDPsock; //pointer to a UDP socket TThread * DAQThread; public: TClientEvtBuilder(string addr, string udptype, TConfig &cod, vector <TCrateCBLT> &tcrate, unsigned int mastercrate); ~TClientEvtBuilder(); int CheckErrors(string ferror, int merr); static void* EventBuilderRun(void *arg); void StartDAQThread(); TThread *GetDAQThread(); void ProcessStopSignal(); //for 'stop signal' }; #endif //#ifndef TClientEvtBuilder_H<file_sep>/ribllvmedaq/TCrateCBLT.cpp //////////////////////////////////////////////////////// // TCrateCBLT.cpp source file interfaces // These classes defined(combination) the CBLTs // in a VME crate // E.d.F (08/2007) test version v.07 // caen lib wrapper not yet implemented // Modified by Hanjianlong 07/2012 /////////////////////////////////////////////////////// #include <iostream> #include <list> #include <string> using namespace std; #ifdef WIN32 #include <windows.h> #define sleep Sleep #define WaitSec 100 #else #include <unistd.h> #define sleep usleep #define WaitSec 100000 #endif #include "TCrateCBLT.h" #include "TBoard.h" #include "CAENVMElib.h" #include "TConfig.h" #include "caenacq.h" TCrateCBLT::TCrateCBLT(TVMELink &link, TCBLT &readout, int index, string configfile) : TVMELink(link), freadout(readout) { findex = index; fenabled = false; fcbltnum = 0; fcblt_addr= 0; fcbltloop = 0; faddr = 0; fmask = 0; status = freadout.Get_CBLT_Config(configfile, fCrate); if(status == 0) { if(freadout.GetChains()>0) { fenabled = true; } else { fenabled = false; } } ReadoutProcsInit(); } ///////////////////////////////////////////////////////////////////////////////// //This is the readout process initilization for CBLT readout ///////////////////////////////////////////////////////////////////////////////// void TCrateCBLT::ReadoutProcsInit(bool print) { list <TBoard *>::const_iterator it; int num=0; // preparing readout.... if(print) cout<<"READOUT_PROCESS_INIT>> Crate=#"<<fCrate<<" Handle=#"<<fHandle<<" Index=#"<<findex<<endl; Init(); fwait_for_ready = freadout.GetWait(); //loop number for data ready fchains = freadout.GetChains(); //number of chains fcbltnum = freadout.GetNum(); //board number for each chain fcblt_addr = freadout.GetDummyAddr(); //dummy address for each chain if(fcbltloop) SafeDeleteArr(fcbltloop); fcbltloop = new int[fchains]; for(int i=0; i<fchains; i++) { fcbltloop[i] = fcbltnum[i] + 1; //max number of cblt cycles for chains } int offset = freadout.GetOffsetPolling(); if(faddr) SafeDeleteArr(faddr); faddr = new unsigned int[fwait_for_ready]; if(fmask) SafeDeleteArr(fmask); fmask = new unsigned int[fwait_for_ready]; it = TConfig::LookupTable(fHandle, num); //Get the first board of each handle(crate) if(offset>0) { if(num>0 && (offset+fwait_for_ready-1) <num) { int k=offset; while(k--) { it++; } } else { cout<<"READOUT_PROCESS_INIT>> Crate=#"<<fCrate<< " Request for polling not existing board ignored"<<endl; } } if(num!=0) { for(int i=0; i<fwait_for_ready; i++) { faddr[i] = (*it)->GetAcqReg(); fmask[i] = (*it)->GetAcqRegMask(); it++; } } } ///////////////////////////////////////////////////////////////////////////////// // Polling the status register for data ready ///////////////////////////////////////////////////////////////////////////////// int TCrateCBLT::WaitForReady() { int count=0, status = 0; CVDataWidth data_size = cvD16; if(!fenabled)return 1; #ifndef Wait_Data_Ready_IRQ //use the DRY register of module as strobe CVErrorCodes err; count=0; for(int i=0; i<fwait_for_ready; i++) { int rdata = 0; err = CAENVME_ReadCycle(fHandle, faddr[i], &rdata, cvA32_U_DATA, data_size); rdata &= fmask[i]; if(rdata>0)count++; } if(count==fwait_for_ready) return 1; else return 0; #else if(fwait_for_ready>0) //use IRQ as strobe { status = CAENVME_IRQEnable(fHandle, IRQ_Level); if(status != 0) { cout << "TCrateCBLT>> VMEbus IRQEnable error!" << endl; sleep(WaitSec); return 0; } status = CAENVME_IRQWait(fHandle, IRQ_Level, 10000); if(status == 0) { status = CAENVME_IRQDisable(fHandle, IRQ_Level); if(status != 0) { cout << "TCrateCBLT>> VMEbus IRQDisable error!" << endl; } return 1; } else { return 0; } } else { return 1; } #endif } ///////////////////////////////////////////////////////////////////////////////// // Readout ///////////////////////////////////////////////////////////////////////////////// void TCrateCBLT::Readout() { const int header_w = 8; const int SIZE = 256; unsigned int *acqbuf = (unsigned int *)(freadout.GetBLTBuff());//TEvtBuilder::fevtbuffer[findex].evtbuf; unsigned int *curr_ptr = acqbuf; int data_w, buflen; //Warning: "chains = 1" (chainid=0) only is managed in this version(cancele this rule by <NAME>) const int chainid = 0; int cblt_counter,val[4]={0,0xFF,0xFFFF,0xFFFFFF},act_length; unsigned int bufdimension = freadout.GetBufDimension(); data_w = 0; buflen = 0; *curr_ptr = Crate_Header;// | TEvtBuilder::fevent_counter; *(curr_ptr+1) = fCrate; curr_ptr += header_w; int len = 0; for(int nchain=0; nchain<fchains; nchain++) { #ifndef FIFO_Read_Mode for(int i=0; i<fcbltloop[nchain]; i++) { CVErrorCodes res=CAENVME_BLTReadCycle(fHandle, fcblt_addr[nchain], (unsigned char *)curr_ptr, SIZE, cvA32_U_BLT, cvD32, &len); //int res=CAENVME_FIFOBLTReadCycle(fHandle, fcblt_addr[nchain], (unsigned char *)curr_ptr, SIZE, cvA32_U_BLT, cvD32, &len); data_w +=len; curr_ptr += len>>2; if(res<0) { cout << "CAENVME_FIFOBLTReadCycle Error: " << res << endl; vmeerror.Clear(); vmeerror = "CAENVME_FIFOBLTReadCycle Error: "; vmeerror += res; break; } } #else for(int nb=0; nb<fcbltnum[nchain]+1; nb++) { CVErrorCodes res=CAENVME_FIFOBLTReadCycle(fHandle, fcblt_addr[nchain], (unsigned char *)curr_ptr, bufdimension, cvA32_U_BLT, cvD32, &len); data_w += len; curr_ptr += len>>2; // byte->int //if(len<=0) //{ // cout << "CAENVME_FIFOBLTReadCycle Error: " << res << " Read length: " << len << endl; // vmeerror.Clear(); // vmeerror = "CAENVME_FIFOBLTReadCycle Error: "; // vmeerror += res; // //break; //} if(res<0) break; } #endif } cblt_counter = data_w>>2; // byte->int act_length = (cblt_counter+header_w)<<2; freadout.SetUsedSizeByte(act_length); //set real length of the data in byte //TEvtBuilder::fevtbuffer[findex].size = buflen; } TCrateCBLT::~TCrateCBLT() { fcbltnum = 0; //delete[] in TCBLT fcblt_addr = 0; //delete[] in TCBLT SafeDeleteArr(fcbltloop); SafeDeleteArr(faddr); SafeDeleteArr(fmask); } TCrateCBLT::TCrateCBLT(TCrateCBLT const &source):TVMELink(source) { copy(source); } void TCrateCBLT::copy(TCrateCBLT const &source) { freadout = source.freadout; findex = source.findex; fenabled = source.fenabled; fwait_for_ready = source.fwait_for_ready; fchains = source.fchains; fcbltnum = freadout.GetNum(); fcblt_addr = freadout.GetDummyAddr(); fcbltloop = new int[fchains]; for(int i=0; i<fchains; i++) { fcbltloop[i] = fcbltnum[i] + 1; //max number of cblt cycles for chains } list <TBoard *>::const_iterator it; int num = 0; int offset = freadout.GetOffsetPolling(); faddr = new unsigned int[fwait_for_ready]; fmask = new unsigned int[fwait_for_ready]; it = TConfig::LookupTable(fHandle, num); //Get the first board of each handle(crate) if(offset>0) { if(num>0 && (offset+fwait_for_ready-1) <num) { int k=offset; while(k--) { it++; } } else { cout<<"READOUT_PROCESS_INIT>> Crate=#"<<fCrate<< " Request for polling not existing board ignored"<<endl; } } if(num!=0) { for(int i=0; i<fwait_for_ready; i++) { faddr[i] = (*it)->GetAcqReg(); fmask[i] = (*it)->GetAcqRegMask(); it++; } } //cout << "TCrateCBLT>> Copy constructor... " << fCrate << endl; } int TCrateCBLT::EnableIRQ() { if(fwait_for_ready>0) //use IRQ as strobe { status = CAENVME_IRQEnable(fHandle, IRQ_Level); if(status != 0) { cout << "TCrateCBLT>> VMEbus IRQEnable error!" << endl; sleep(WaitSec); return 0; } } return 1; }
cc638087906ce8a621fe671ef7b808a383d46a8b
[ "Markdown", "C", "Makefile", "C++" ]
62
C++
shuxianghuafu/ribll
6f8f45e77b8d819255ce48628b5f15ba34a93ce0
8f388777a9b8e8f6f0ad7a5f609e3497841ae8cf
refs/heads/master
<file_sep>package main /* Логика. После enable: - GetCapabilities - DiscoverNew c адресом ноды и указанием что это она и есть После docker network create -d rightipam --subnet=192.168.1.0/24 --gateway=192.168.1.1 --ip-range=192.168.1.4/32 -o vlan_id=2000 -o ext_if=eno1 -o bridge_name=vlan2000 net1 - CreateNetwork { deec618526f0cc2c5ddb7b66acb749b6b0ebf056d2ed0df7a3c20e9baaa5f182 map[ com.docker.network.enable_ipv6:false com.docker.network.generic:map[ bridge_name:vlan2000 ext_if:eno1 vlan_id:2000 ] ] [0xc00009b940] IPAMData IPv4 [] } После docker network rm net1 - DeleteNetwork После docker network create -d rightipam:latest --scope swarm --subnet=192.168.1.0/24 --gateway=192.168.1.1 --ip-range=192.168.1.4/32 -o vlan_id=2000 -o ext_if=eno1 -o bridge_name=vlan2000 net1 - ничего но параметры драйвера не передаются. Они теряются. Надо через конфиг После docker stack deploy - CreateEndpoint { o38vug9jkt0ia3a8dcz3lwsa0 f85b2a0c98f126ea3bbf4fcea0e6a4f02a3ddba5e66607a73ebeed2130981c3d 0xc000170d80 map[ com.docker.network.endpoint.exposedports:[ map[ Proto:6 Port:80 ] ] com.docker.network.portmap:[] ] } */ import ( "github.com/docker/go-plugins-helpers/network" "github.com/docker/libnetwork/netlabel" "github.com/milosgajdos/tenus" "net" "github.com/docker/libcontainer/netlink" "errors" "log" ) var ( FeatureNotAvailableErr = errors.New("Feature not Available") ) type NetworkDriver struct { Wrap network.Driver } /* Значение «Scope» должно быть «local» или «global», что указывает, может ли выделение ресурсов для сети этого драйвера выполняться только локально для узла или глобально через кластер узлов. Любое другое значение не выполнит регистрацию драйвера и вернет ошибку вызывающей стороне. Аналогично, значение «ConnectivityScope» должно быть либо «локальным», либо «глобальным», что указывает, может ли сеть драйвера обеспечивать подключение только локально к этому узлу или глобально через кластер узлов. Если значение отсутствует, libnetwork установит для него значение «Scope» */ func (self *NetworkDriver) GetCapabilities() (*network.CapabilitiesResponse, error) { return &network.CapabilitiesResponse{ Scope: network.LocalScope, ConnectivityScope:network.GlobalScope, }, nil } /* NetworkID генерируется LibNetwork, который представляет собой уникальную сеть. Options является произвольная карта, предоставленная прокси-сервером LibNetwork. IPv4Data и IPv6Data - это данные IP-адресации, настроенные пользователем и управляемые драйвером IPAM. Ожидается, что сетевой драйвер будет учитывать данные IP-адресации, предоставленные драйвером IPAM. Данные включают в себя, AddressSpace: уникальная строка представляет изолированное пространство для IP-адресации Pool: диапазон IP-адресов, представленных в формате адреса / маски CIDR. Поскольку драйвер IPAM отвечает за распределение IP-адресов контейнера, сетевой драйвер может использовать эту информацию для целей сетевого подключения. Gateway: При желании драйвер IPAM может предоставить IP-адрес шлюза в формате CIDR для подсети, представленной Пулом. Сетевой драйвер может использовать эту информацию для целей сетевого подключения. AuxAddresses: список предварительно назначенных IP-адресов со связанным идентификатором, предоставленным пользователем, чтобы помочь сетевому драйверу, если для его работы требуются определенные IP-адреса. */ func (self *NetworkDriver) CreateNetwork(r *network.CreateNetworkRequest) error { // Берем параметры и проверяем на вшивость igData := r.Options[netlabel.GenericData] if igData == nil { return errors.New("Driver need params vlan_id, bridge_name, ext_if") } gData := igData.(map[string]interface{}) if gData == nil { return errors.New("Invalid options format") } iVlanId := gData["vlan_id"] iBridgeName := gData["bridge_name"] iExtIf := gData["ext_if"] iRoutes := gData["routes"] if iVlanId == nil { return errors.New("Driver need vlan_id option") } if iBridgeName == nil { return errors.New("Driver need bridge_name option") } if iExtIf == nil { return errors.New("Driver need ext_if option") } vlanId := AnyVal{iVlanId} bridgeName := AnyVal{iBridgeName} extIf := AnyVal{iExtIf} routes := make(NetworkList, 0) if iRoutes != nil { err := routes.Parse(AnyVal{iRoutes}.String()) if err != nil { return err } } // кончили возиться с параметрами n := &Network{} if n.Load(r.NetworkID) == nil { } defer n.Save() n.BridgeName = bridgeName.String() if r.IPv4Data != nil { if len(r.IPv4Data) > 0 { n.Gateway = r.IPv4Data[0].Gateway } } n.Routes = routes n.HostInterface = extIf.String() n.VlanID = vlanId.Int() _, err := n.GetOrCreateBridge() if err != nil { return err } return nil } func (self *NetworkDriver) AllocateNetwork(r *network.AllocateNetworkRequest) (*network.AllocateNetworkResponse, error) { return &network.AllocateNetworkResponse{}, nil } func (self *NetworkDriver) DeleteNetwork(r *network.DeleteNetworkRequest) error { n := &Network{ID: r.NetworkID} return n.Delete() } func (self *NetworkDriver) FreeNetwork(r *network.FreeNetworkRequest) error { return nil } /* Если удаленному процессу было передано непустое значение в интерфейсе, он должен ответить пустым значением интерфейса. LibNetwork будет воспринимать это как ошибку, если она предоставит непустое значение, вернет непустое значение и откатит операцию. */ func (self *NetworkDriver) CreateEndpoint(r *network.CreateEndpointRequest) (*network.CreateEndpointResponse, error) { // подгружаем информацию о сети n := &Network{} err := n.Load(r.NetworkID) defer n.Save() if err != nil { return nil, err } // создаем бридж, если он не создан br, err := n.GetOrCreateBridge() if err != nil { return nil, err } //createVlanAndAddToBridge(br, n.) // генерирую основу имени пары интерфейсов n.VethName = "veth" + r.NetworkID[0:3] + r.EndpointID[0:3] // сздаем парный интерфейс vether, err := tenus.NewVethPairWithOptions(n.HostIfName(), tenus.VethOptions{PeerName: n.ContainerIfName()}) if err != nil { log.Println("Error creating veth pair:", err) return nil, err } defer func() { if err != nil { n.Save() //remove interfaces by error vether.DeletePeerLink() vether.DeleteLink() } }() hostIf, err := net.InterfaceByName(n.HostIfName()) if err != nil { return nil, err } err = br.AddSlaveIfc(hostIf) //containerIf, err := net.InterfaceByName(n.ContainerIfName()) if err != nil { log.Println("Error adding veth to bridge:", err) return nil, err } err = vether.SetLinkUp() if err != nil { log.Println("Error veth host up:", err) return nil, err } err = vether.SetPeerLinkUp() if err != nil { log.Println("Error veth peer up:", err) return nil, err } //r.Interface.MacAddress = containerIf.HardwareAddr.String() return &network.CreateEndpointResponse{Interface: nil}, nil } func (self *NetworkDriver) DeleteEndpoint(r *network.DeleteEndpointRequest) error { // подгружаем информацию о сети n := &Network{} err := n.Load(r.NetworkID) defer n.Save() if err != nil { return err } // берем интерфейс hostIf, err := net.InterfaceByName(n.HostIfName()) if err != nil { return err } // ьерем бридж br, err := n.GetOrCreateBridge() if err != nil { return err } // удаляем из бриджа хостовый конец err = br.RemoveSlaveIfc(hostIf) if err != nil { return err } // удаляем хостовую часть. Есть подозрение что автоматически удалится и слейв. но надо будет проверить err = netlink.NetworkLinkDel(hostIf.Name) return err } func (self *NetworkDriver) EndpointInfo(r *network.InfoRequest) (*network.InfoResponse, error) { return &network.InfoResponse{Value:make(map[string]string)},nil } func (self *NetworkDriver) Join(r *network.JoinRequest) (*network.JoinResponse, error) { // готовим информацию для контейнера res := &network.JoinResponse{StaticRoutes:make([]*network.StaticRoute, 0)} n := &Network{} err := n.Load(r.NetworkID) if err != nil { return nil, err } defer n.Save() res.InterfaceName.SrcName = n.ContainerIfName() res.InterfaceName.DstPrefix = "eth" res.DisableGatewayService = false ipGateway, _, _ := net.ParseCIDR(n.Gateway) res.Gateway = ipGateway.String() if len(n.Routes) > 0 { if res.StaticRoutes == nil { res.StaticRoutes = make([]*network.StaticRoute, 0) } for _, r := range n.Routes { res.StaticRoutes = append(res.StaticRoutes, &network.StaticRoute{Destination: r, RouteType: 0, NextHop: ipGateway.String()}) } //res.StaticRoutes = append(res.StaticRoutes, &network.StaticRoute{Destination: "0.0.0.0/0", RouteType: 0, NextHop: ipGateway.String()}) } return res, nil } func (self *NetworkDriver) Leave(r *network.LeaveRequest) error { return nil } /* Уведомление о данных. Вызывается после GetCapabilities // DiscoveryType represents the type of discovery element the DiscoverNew function is invoked on type DiscoveryType int const ( // NodeDiscovery represents Node join/leave events provided by discovery NodeDiscovery = iota + 1 // DatastoreConfig represents an add/remove datastore event DatastoreConfig // EncryptionKeysConfig represents the initial key(s) for performing datapath encryption EncryptionKeysConfig // EncryptionKeysUpdate represents an update to the datapath encryption key(s) EncryptionKeysUpdate ) */ func (self *NetworkDriver) DiscoverNew(r *network.DiscoveryNotification) error { return nil } func (self *NetworkDriver) DiscoverDelete(r *network.DiscoveryNotification) error { return nil } func (self *NetworkDriver) ProgramExternalConnectivity(r *network.ProgramExternalConnectivityRequest) error { return nil } func (self *NetworkDriver) RevokeExternalConnectivity(r *network.RevokeExternalConnectivityRequest) error { return nil } /* docker network create -d rightipam:latest --subnet=192.168.1.0/24 --gateway=192.168.1.1 --ip-range=192.168.1.4/32 -o vlan_id=2000 -o ext_if=eno1 -o bridge_name=vlan2000 --config-only net1conf docker network create -d rightipam:latest --scope swarm --config-from net1conf net1 */ // "docker.networkdriver/1.0"<file_sep>package main import ( "testing" "os" ) const ( TestDatabase = "test.db" TestDatabaseErr = "/tmp" ) func TestStartDatabase(t *testing.T) { err := StartDatabase(TestDatabase) if err != nil { t.Error(err) } ShutdownDatabase() os.Remove(TestDatabase) } func TestShutdownDatabase(t *testing.T) { err := StartDatabase(TestDatabase) if err != nil { t.Error(err) } ShutdownDatabase() os.Remove(TestDatabase) } func TestStartDatabase2(t *testing.T) { err := StartDatabase(TestDatabaseErr) if err == nil { t.Error() } } <file_sep>package main import ( "github.com/docker/go-plugins-helpers/ipam" "errors" "testing" ) type IPAMTester struct { lastcall string isNil bool returnedNNil bool } func (self *IPAMTester) GetCapabilities() (*ipam.CapabilitiesResponse, error) { self.lastcall = "GetCapabilities" self.isNil = true if self.returnedNNil { return &ipam.CapabilitiesResponse{}, nil } return nil, nil } func (self *IPAMTester) GetDefaultAddressSpaces() (*ipam.AddressSpacesResponse, error) { self.lastcall = "GetDefaultAddressSpaces" self.isNil = true if self.returnedNNil { return &ipam.AddressSpacesResponse{}, nil } return nil, nil } func (self *IPAMTester) RequestPool(r *ipam.RequestPoolRequest) (*ipam.RequestPoolResponse, error) { self.lastcall = "RequestPool" self.isNil = r == nil if self.returnedNNil { return &ipam.RequestPoolResponse{}, nil } return nil, nil } func (self *IPAMTester) ReleasePool(r *ipam.ReleasePoolRequest) error { self.lastcall = "ReleasePool" self.isNil = r == nil if self.returnedNNil { return errors.New("") } return nil } func (self *IPAMTester) RequestAddress(r *ipam.RequestAddressRequest) (*ipam.RequestAddressResponse, error) { self.lastcall = "RequestAddress" self.isNil = r == nil if self.returnedNNil { return &ipam.RequestAddressResponse{}, nil } return nil, nil } func (self *IPAMTester) ReleaseAddress(r *ipam.ReleaseAddressRequest) error { self.lastcall = "ReleaseAddress" self.isNil = r == nil if self.returnedNNil { return errors.New("") } return nil } func PrepareIpamTest() (*IPAMTester, ipam.Ipam) { var res IPAMTester var d DebuggerTest i := &IPAMDebug{Wrap:&res} i.SetLogger(&d) return &res, i } func TestIPAMDebug_GetCapabilities(t *testing.T) { tt, i := PrepareIpamTest() r, err := i.GetCapabilities() if tt.lastcall != "GetCapabilities" && tt.isNil != true && r != nil && err != nil { t.Error() } } func TestIPAMDebug_GetCapabilities2(t *testing.T) { tt, i := PrepareIpamTest() tt.returnedNNil = true r, err := i.GetCapabilities() if tt.lastcall != "GetCapabilities" && tt.isNil != true && r == nil && err != nil { t.Error() } } func TestIPAMDebug_GetDefaultAddressSpaces(t *testing.T) { tt, i := PrepareIpamTest() r, err := i.GetDefaultAddressSpaces() if tt.lastcall != "GetDefaultAddressSpaces" && tt.isNil != true && r != nil && err != nil { t.Error() } } func TestIPAMDebug_GetDefaultAddressSpaces2(t *testing.T) { tt, i := PrepareIpamTest() tt.returnedNNil = true r, err := i.GetDefaultAddressSpaces() if tt.lastcall != "GetDefaultAddressSpaces" && tt.isNil != true && r == nil && err != nil { t.Error() } } func TestIPAMDebug_ReleaseAddress(t *testing.T) { tt, i := PrepareIpamTest() err := i.ReleaseAddress(nil) if tt.lastcall != "ReleaseAddress" && tt.isNil != true && err != nil { t.Error() } } func TestIPAMDebug_ReleaseAddress2(t *testing.T) { tt, i := PrepareIpamTest() err := i.ReleaseAddress(&ipam.ReleaseAddressRequest{}) if tt.lastcall != "ReleaseAddress" && tt.isNil != false && err != nil { t.Error() } } func TestIPAMDebug_ReleaseAddress3(t *testing.T) { tt, i := PrepareIpamTest() tt.returnedNNil = true err := i.ReleaseAddress(nil) if tt.lastcall != "ReleaseAddress" && tt.isNil != true && err == nil { t.Error() } } func TestIPAMDebug_ReleasePool(t *testing.T) { tt, i := PrepareIpamTest() err := i.ReleasePool(nil) if tt.lastcall != "ReleasePool" && tt.isNil != true && err != nil { t.Error() } } func TestIPAMDebug_ReleasePool2(t *testing.T) { tt, i := PrepareIpamTest() err := i.ReleasePool(&ipam.ReleasePoolRequest{}) if tt.lastcall != "ReleasePool" && tt.isNil != false && err != nil { t.Error() } } func TestIPAMDebug_ReleasePool3(t *testing.T) { tt, i := PrepareIpamTest() tt.returnedNNil = true err := i.ReleasePool(nil) if tt.lastcall != "ReleasePool" && tt.isNil != true && err == nil { t.Error() } } func TestIPAMDebug_RequestAddress(t *testing.T) { tt, i := PrepareIpamTest() r, err := i.RequestAddress(nil) if tt.lastcall != "RequestAddress" && tt.isNil != true && r != nil && err != nil { t.Error() } } func TestIPAMDebug_RequestAddress2(t *testing.T) { tt, i := PrepareIpamTest() r, err := i.RequestAddress(&ipam.RequestAddressRequest{}) if tt.lastcall != "RequestAddress" && tt.isNil != false && r != nil && err != nil { t.Error() } } func TestIPAMDebug_RequestAddress3(t *testing.T) { tt, i := PrepareIpamTest() tt.returnedNNil = true r, err := i.RequestAddress(&ipam.RequestAddressRequest{}) if tt.lastcall != "RequestAddress" && tt.isNil != false && r == nil && err != nil { t.Error() } } func TestIPAMDebug_RequestPool(t *testing.T) { tt, i := PrepareIpamTest() r, err := i.RequestPool(nil) if tt.lastcall != "RequestPool" && tt.isNil != true && r != nil && err != nil { t.Error() } } func TestIPAMDebug_RequestPool2(t *testing.T) { tt, i := PrepareIpamTest() r, err := i.RequestPool(&ipam.RequestPoolRequest{}) if tt.lastcall != "RequestPool" && tt.isNil != false && r != nil && err != nil { t.Error() } } func TestIPAMDebug_RequestPool3(t *testing.T) { tt, i := PrepareIpamTest() tt.returnedNNil = true r, err := i.RequestPool(&ipam.RequestPoolRequest{}) if tt.lastcall != "RequestPool" && tt.isNil != false && r == nil && err != nil { t.Error() } } <file_sep># Driver for connecting containers to external vlan by L2 translated by google. ## Prehistory It took me to run several containers in the docker swarm and release their traffic directly to a specific vlan. Everything was ready from the point of view of the classical organization of the network: vlan was created on the router, hung on the gateway and reach on the switches to the port on the servers. Each container must have its own fixed address. Without thinking twice, I created macvlan networks on all nodes and launched one container. All was good. I launched the second container. And then everything was fine. Only here the third container did not want to run ... Let me dig, what could have gone wrong. The container did not start with an error (approx. Translation): "Gateway (ip) cannot to be appointed because he is already appointed somewhere. " Figasse - I think. This address is nowhere to be found, ran through all the interfaces - no, from the word "absolutely." I notice that this does not work on the site where this container is already running or, suddenly, there was an attempt to launch the container. I'm in absolute misunderstanding stopped running containers that are tied to these networks and let's remove the networks. The network itself is gone, but the configs networks do not want to be removed, they say that they are used somewhere. I checked everything, did not find use. I sneaked on their Internet sites: They will come that this is such a bug and it would be necessary to stop the docker service and delete the local storage ... and then you will be lost all local configs and you will be happy ... It's good that so far I have only these local configs. Okay, I started up and began to think. I made a booth on my local computer and reproduced the error. It is reproduced, by the way, very easily: ```bash $ docker network create -d macvlan --subnet=192.168.1.0/24 --gateway=192.168.1.1 --ip-range=192.168.1.2/32 \ --config-only -o parent=eno1.2000 net1conf $ docker network create -d macvlan --subnet=192.168.1.0/24 --gateway=192.168.1.1 --ip-range=192.168.1.3/32 \ --config-only -o parent=eno1.2000 net2conf $ docker network create -d macvlan --scope swarm --config-from net1conf net1 $ docker network create -d macvlan --scope swarm --config-from net2conf net2 $ docker stack deploy -c docker-compose1.yml stack1 # everything is still good here $ docker stack deploy -c docker-compose2.yml stack2 # but it was already a mistake ``` The stacks are very simple: they consist of one nginx service, which in one instance is started and connected to an external one. net1 and net2 respectively. For example, here’s one file: ```yaml version: "3.7" services: nginx: image: nginx:alpine networks: - net1 deploy: restart_policy: condition: any mode: replicated replicas: 1 networks: net1: external: true ``` I downloaded the source code for moby and libnetwork and began to look for what generates such an error. It turned out the driver is IPAM. Such behavior can be corrected if you write your driver and use it. "Well, OK". No sooner said than done. I wrote a driver, where the behavior from the standard differs only in that it does not swear at the gateway at all, he just takes note of it. And here I am full of anticipation and triumph, I launch everything according to the above example and get a hard break. When creating net2 macvlan driver cannot create interface eno1.2000. Garbage question - use the driver bridge. And here everything is fine but only this driver for some horseradish hung the gateway address on the used bridge. And there was no way to convince him. In general, I came to the conclusion that you need to write your network driver. And here he is. ## How it works The driver creates a bridge with the specified name. Creates a sub-interface with the specified vlan tag to the specified interface. Combines the created. And then simply connects the L2 container to this bridge. If the bridge has already been created, the driver does not check for a sub-interface with the specified vlan tag? because he is supposed to already created and working. It is strange why gentlemen programmers from the docker company did not think of this. surely it would be in demand. ## How to use First you need to install the plugin: ```bash $ docker plugin install --alias "l2vlan" blins1999/l2vlan ``` Create a network like this: ```bash $ docker network create -d l2vlan:latest --ipam-driver l2vlan:latest --subnet=192.168.1.0/24 --gateway=192.168.1.1 \ --ip-range=192.168.1.4/32 -o vlan_id=2000 -o ext_if=eno1 -o bridge_name=vlan2000 --config-only net1conf $ docker network create -d l2vlan:latest --scope swarm --config-from net1conf net1 ``` Needless to say that the first command is executed on EVERY cluster node. Then you can add static addresses: ```bash $ docker network create -d l2vlan:latest --ipam-driver l2vlan:latest --subnet=192.168.1.0/24 --gateway=192.168.1.1 \ --ip-range=192.168.1.6/32 -o vlan_id=2000 -o ext_if=eno1 -o bridge_name=vlan2000 --config-only net2conf $ docker network create -d l2vlan:latest --scope swarm --config-from net2conf net2 ``` And all this will be connected to the same brdige (within one narrow course) ## What to do - It is necessary to deal with linux capabilities. I would be happy to help. Well, everything seems :) <file_sep>package main import ( "github.com/docker/go-plugins-helpers/ipam" ) type IPAMDebug struct { Debugger Wrap ipam.Ipam } func (self *IPAMDebug) GetCapabilities() (*ipam.CapabilitiesResponse, error) { self.Println("GetCapabilities call") res, err := self.Wrap.GetCapabilities() self.Println("GetCapabilities result", res, err) return res, err } func (self *IPAMDebug) GetDefaultAddressSpaces() (*ipam.AddressSpacesResponse, error) { self.Println("GetDefaultAddressSpaces call") res, err := self.Wrap.GetDefaultAddressSpaces() self.Println("GetDefaultAddressSpaces result", res, err) return res, err } func (self *IPAMDebug) RequestPool(r *ipam.RequestPoolRequest) (*ipam.RequestPoolResponse, error) { self.Println("RequestPool call", r) res, err := self.Wrap.RequestPool(r) self.Println("RequestPool result", res, err) return res, err } func (self *IPAMDebug) ReleasePool(r *ipam.ReleasePoolRequest) error { self.Println("ReleasePool call", r) err := self.Wrap.ReleasePool(r) self.Println("ReleasePool result", err) return err } func (self *IPAMDebug) RequestAddress(r *ipam.RequestAddressRequest) (*ipam.RequestAddressResponse, error) { self.Println("RequestAddress call", r) res, err := self.Wrap.RequestAddress(r) self.Println("RequestAddress result", res, err) return res, err } func (self *IPAMDebug) ReleaseAddress(r *ipam.ReleaseAddressRequest) error { self.Println("ReleaseAddress call", r) err := self.Wrap.ReleaseAddress(r) self.Println("ReleaseAddress result", err) return err } <file_sep>PLUGIN_NAME=l2vlan clean: rm -rf ./plugin ./bin rm -f ${PLUGIN_NAME} docker plugin disable ${PLUGIN_NAME} || true docker plugin rm ${PLUGIN_NAME} || true docker plugin disable blins1999/${PLUGIN_NAME} || true docker plugin rm blins1999/${PLUGIN_NAME} || true docker rm -vf tmp || true docker rmi ${PLUGIN_NAME}-build-image || true docker rmi ${PLUGIN_NAME}:rootfs || true build: docker build -t ${PLUGIN_NAME}-build-image -f Dockerfile.build . docker create --name tmp ${PLUGIN_NAME}-build-image docker cp tmp:/go/bin/${PLUGIN_NAME} . docker rm -vf tmp #docker rmi ${PLUGIN_NAME}-build-image docker build -t ${PLUGIN_NAME}:rootfs . mkdir -p ./plugin/rootfs docker create --name tmp ${PLUGIN_NAME}:rootfs docker export tmp | tar -x -C ./plugin/rootfs cp config.json ./plugin/ docker rm -vf tmp rm -f ${PLUGIN_NAME} create-plugin: docker plugin create blins1999/${PLUGIN_NAME} ./plugin create-plugin-local: docker plugin create ${PLUGIN_NAME} ./plugin push-plugin: docker plugin push blins1999/${PLUGIN_NAME} rm-plugin: docker plugin rm ${PLUGIN_NAME} || true docker plugin rm blins1999/${PLUGIN_NAME} || true push: clean build create-plugin push-plugin rm-plugin clean<file_sep>package main type DebugLogger interface { Println(...interface{}) } type Debugger struct { logger DebugLogger } func (self *Debugger) Println(v ...interface{}) { self.logger.Println(v...) } func (self *Debugger) SetLogger(l DebugLogger) { self.logger = l } <file_sep>package main import "testing" const ( avIntValue = 1000 avStringValue = "1000" ) type avStringer struct{} func (s avStringer) String() string { return avStringValue } func TestAnyVal_Int(t *testing.T) { var i int = avIntValue av := AnyVal{i} if av.Int() != avIntValue { t.Error() } } func TestAnyVal_Int2(t *testing.T) { var i string = avStringValue av := AnyVal{i} if av.Int() != avIntValue { t.Error() } } func TestAnyVal_Int3(t *testing.T) { var i avStringer av := AnyVal{i} if av.Int() != avIntValue { t.Error() } } func TestAnyVal_Int4(t *testing.T) { var i []byte av := AnyVal{i} if av.Int() != 0 { t.Error() } } func TestAnyVal_String(t *testing.T) { var i int = avIntValue av := AnyVal{i} if av.String() != avStringValue { t.Error() } } func TestAnyVal_String2(t *testing.T) { var i string = avStringValue av := AnyVal{i} if av.String() != avStringValue { t.Error() } } func TestAnyVal_String3(t *testing.T) { var i avStringer av := AnyVal{i} if av.String() != avStringValue { t.Error() } } func TestAnyVal_String4(t *testing.T) { var i []byte av := AnyVal{i} if av.String() != "" { t.Error() } }<file_sep>#!/usr/bin/env bash set -x docker stack rm stack1 stack2 sleep 5 docker network rm net1 net2 sleep 5 docker network rm net1conf net2conf <file_sep>package main import ( "fmt" "net" "go.etcd.io/bbolt" "bytes" "encoding/gob" "errors" ) func NewPoolv4() *Poolv4 { return &Poolv4{ Data: make(map[string]string), } } type Poolv4 struct { ID string Network net.IPNet Subnet net.IPNet Gateway net.IP Data map[string]string } func (pool Poolv4) String() string { return fmt.Sprintf("Pool{ID: %s, Network: %s, Subnet: %s, Gateway: %s}", pool.ID, NetToCIDR(pool.Network), NetToCIDR(pool.Subnet), IpToCIDR(pool.Gateway, pool.Network.Mask)) } // загружает пул по ID из БД func (pool *Poolv4) Load(id string) error { pool.ID = id return db.View(func(tx *bbolt.Tx) error { b := tx.Bucket([]byte(pool.ID)) if b != nil { data := b.Get([]byte("binary")) if data != nil { reader := bytes.NewReader(data) enc := gob.NewDecoder(reader) return enc.Decode(pool) } } return errors.New("Pool not exists") }) } // сохраняет пул func (pool *Poolv4) Save() error { return db.Update(func(tx *bbolt.Tx) error { b, err := tx.CreateBucketIfNotExists([]byte(pool.ID)) if err != nil { return err} var writer bytes.Buffer dec := gob.NewEncoder(&writer) err = dec.Encode(pool) if err != nil { return err } return b.Put([]byte("binary"), writer.Bytes()) }) } // удалить пул из хранилища func (pool *Poolv4) Delete() error { return db.Update(func(tx *bbolt.Tx) error { return tx.DeleteBucket([]byte(pool.ID)) }) } // разбирает адресацию сетей и подсетей func (pool *Poolv4) ParseCIDR(network string, subnet string) error { _, n, err := net.ParseCIDR(network) if err != nil { return err} pool.Network = *n pool.Network.IP = pool.Network.IP.Mask(pool.Network.Mask) if subnet != "" { _, n, err := net.ParseCIDR(subnet) if err != nil { return err} pool.Subnet = *n } return nil } // помечает IP как выданный func (pool *Poolv4) RegisterIP(ip net.IP) error { return db.Update(func(tx *bbolt.Tx) error { b := tx.Bucket([]byte(pool.ID)) if b == nil { return errors.New("Pool not exists") } return b.Put([]byte(ip.String()), []byte("1")) }) } // удаляет IP адрес func (pool *Poolv4) DeregisterIP(ip net.IP) error { return db.Update(func(tx *bbolt.Tx) error { b := tx.Bucket([]byte(pool.ID)) if b == nil { return errors.New("Pool not exists") } return b.Delete([]byte(ip.String())) }) } //проверяет что адрес свободен func (pool *Poolv4) IpIsFree(ip net.IP) bool { // сеть для проверки check := pool.Network if !pool.Subnet.IP.IsUnspecified() { // если определен пул выдаваемых адресов в большой сети, то начинать с него check = pool.Subnet } if !pool.Network.Contains(IncIP(ip)) || check.Contains(ip) { // проверка на broadcast // или что мы не вылезли за диапазон return false } err := db.View(func(tx *bbolt.Tx) error { b := tx.Bucket([]byte(pool.ID)) if b == nil { return errors.New("Pool not exists") } // проверка на существование любого значения с названием адреса. Если значения нет, то адрес свободен if b.Get([]byte(ip.String())) != nil { return errors.New("Ip exists") } return nil }) if err != nil { return false } return true } // возвращает первый свободный адрес func (pool *Poolv4) GetFirstFree() (net.IP, error) { var res net.IP res = IncIP(pool.Network.IP) // сеть для проверки check := pool.Network if !pool.Subnet.IP.IsUnspecified() { // если определен пул выдаваемых адресов в большой сети, то начинать с него res = pool.Subnet.IP check = pool.Subnet } err := db.View(func(tx *bbolt.Tx) error { b := tx.Bucket([]byte(pool.ID)) if b == nil { return errors.New("Pool not exists") } for check.Contains(res) { // проверка, что IP не шлюз по умолчанию. Он всегда посылается сначала для регистрации видать if pool.Gateway.Equal(res) { res = IncIP(res) continue } // проверка на существование любого значения с названием адреса. Если значения нет, то адрес свободен if b.Get([]byte(res.String())) == nil { break } // добавить еденичку res = IncIP(res) } return nil }) if err != nil { return net.ParseIP("0.0.0.0"), errors.New("New ip not available") } if !check.Contains(res) { // или что мы не вылезли за диапазон return net.ParseIP("0.0.0.0"), errors.New("New ip not available") } if !pool.Network.Contains(IncIP(res)) { // проверка на broadcast return net.ParseIP("0.0.0.0"), errors.New("New ip not available") } return res, nil } // Helpers <file_sep>package main import ( "testing" "net" ) func TestHashOfString(t *testing.T) { hash := HashOfString("hello world!") if hash != HashOfString("hello world!") { t.Error() } } func TestIncIP(t *testing.T) { ip := net.ParseIP("192.168.1.0") if IncIP(ip).String() != "192.168.1.1" { t.Error() } } func TestIncIP2(t *testing.T) { ip := net.ParseIP("192.168.1.5") if IncIP(ip).String() != "192.168.1.6" { t.Error() } } func TestIncIP3(t *testing.T) { ip := net.ParseIP("192.168.1.255") if IncIP(ip).String() != "192.168.2.0" { t.Error() } } func TestIncIP4(t *testing.T) { ip := net.ParseIP("192.168.255.255") if IncIP(ip).String() != "172.16.17.32" { t.Error() } } func TestIncNet(t *testing.T) { _, n, _ := net.ParseCIDR("192.168.1.0/24") if NetToCIDR(IncNet(*n)) != "192.168.2.0/24" { t.Error() } } func TestIncNet2(t *testing.T) { _, n, _ := net.ParseCIDR("192.168.255.0/24") if NetToCIDR(IncNet(*n)) != "172.16.17.32/24" { t.Error() } } func TestIncNet3(t *testing.T) { _, n, _ := net.ParseCIDR("192.168.1.0/30") if NetToCIDR(IncNet(*n)) != "192.168.1.4/30" { t.Error() } } func TestIncNet4(t *testing.T) { _, n, _ := net.ParseCIDR("192.168.1.0/27") if NetToCIDR(IncNet(*n)) != "192.168.1.32/27" { t.Error() } } func TestIncNet5(t *testing.T) { _, n, _ := net.ParseCIDR("10.50.0.0/24") if NetToCIDR(IncNet(*n)) != "10.50.1.0/24" { t.Error() } } <file_sep>package main import ( "github.com/docker/go-plugins-helpers/ipam" "github.com/docker/go-plugins-helpers/network" "github.com/docker/go-plugins-helpers/sdk" "net/http" "log" ) const ( manifest = `{"Implements": ["NetworkDriver", "IpamDriver"]}` ipamcapabilitiesPath = "/IpamDriver.GetCapabilities" addressSpacesPath = "/IpamDriver.GetDefaultAddressSpaces" requestPoolPath = "/IpamDriver.RequestPool" releasePoolPath = "/IpamDriver.ReleasePool" requestAddressPath = "/IpamDriver.RequestAddress" releaseAddressPath = "/IpamDriver.ReleaseAddress" networkcapabilitiesPath = "/NetworkDriver.GetCapabilities" allocateNetworkPath = "/NetworkDriver.AllocateNetwork" freeNetworkPath = "/NetworkDriver.FreeNetwork" createNetworkPath = "/NetworkDriver.CreateNetwork" deleteNetworkPath = "/NetworkDriver.DeleteNetwork" createEndpointPath = "/NetworkDriver.CreateEndpoint" endpointInfoPath = "/NetworkDriver.EndpointOperInfo" deleteEndpointPath = "/NetworkDriver.DeleteEndpoint" joinPath = "/NetworkDriver.Join" leavePath = "/NetworkDriver.Leave" discoverNewPath = "/NetworkDriver.DiscoverNew" discoverDeletePath = "/NetworkDriver.DiscoverDelete" programExtConnPath = "/NetworkDriver.ProgramExternalConnectivity" revokeExtConnPath = "/NetworkDriver.RevokeExternalConnectivity" ) // ErrorResponse is a formatted error message that libnetwork can understand type ErrorResponse struct { Err string } // NewErrorResponse creates an ErrorResponse with the provided message func NewErrorResponse(msg string) *ErrorResponse { return &ErrorResponse{Err: msg} } type NetworkIpamHandler struct { ipam ipam.Ipam driver network.Driver sdk.Handler } func NewNetworkIpamHandler(n network.Driver, i ipam.Ipam) *NetworkIpamHandler { h := &NetworkIpamHandler{driver: n, ipam: i, Handler: sdk.NewHandler(manifest)} h.initIpam() h.initDriver() return h } func (h *NetworkIpamHandler) initIpam() { h.HandleFunc(ipamcapabilitiesPath, func(w http.ResponseWriter, r *http.Request) { res, err := h.ipam.GetCapabilities() if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, res, false) }) h.HandleFunc(addressSpacesPath, func(w http.ResponseWriter, r *http.Request) { res, err := h.ipam.GetDefaultAddressSpaces() if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, res, false) }) h.HandleFunc(requestPoolPath, func(w http.ResponseWriter, r *http.Request) { req := &ipam.RequestPoolRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } res, err := h.ipam.RequestPool(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, res, false) }) h.HandleFunc(releasePoolPath, func(w http.ResponseWriter, r *http.Request) { req := &ipam.ReleasePoolRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } err = h.ipam.ReleasePool(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, struct{}{}, false) }) h.HandleFunc(requestAddressPath, func(w http.ResponseWriter, r *http.Request) { req := &ipam.RequestAddressRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } res, err := h.ipam.RequestAddress(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, res, false) }) h.HandleFunc(releaseAddressPath, func(w http.ResponseWriter, r *http.Request) { req := &ipam.ReleaseAddressRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } err = h.ipam.ReleaseAddress(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, struct{}{}, false) }) } func (h *NetworkIpamHandler) initDriver() { h.HandleFunc(networkcapabilitiesPath, func(w http.ResponseWriter, r *http.Request) { res, err := h.driver.GetCapabilities() if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } if res == nil { sdk.EncodeResponse(w, NewErrorResponse("Network driver must implement GetCapabilities"), true) return } sdk.EncodeResponse(w, res, false) }) h.HandleFunc(createNetworkPath, func(w http.ResponseWriter, r *http.Request) { log.Println("Entering go-plugins-helpers createnetwork") req := &network.CreateNetworkRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } err = h.driver.CreateNetwork(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, struct{}{}, false) }) h.HandleFunc(allocateNetworkPath, func(w http.ResponseWriter, r *http.Request) { log.Println("Entering go-plugins-helpers allocatenetwork") req := &network.AllocateNetworkRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } res, err := h.driver.AllocateNetwork(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, res, false) }) h.HandleFunc(deleteNetworkPath, func(w http.ResponseWriter, r *http.Request) { req := &network.DeleteNetworkRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } err = h.driver.DeleteNetwork(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, struct{}{}, false) }) h.HandleFunc(freeNetworkPath, func(w http.ResponseWriter, r *http.Request) { req := &network.FreeNetworkRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } err = h.driver.FreeNetwork(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, struct{}{}, false) }) h.HandleFunc(createEndpointPath, func(w http.ResponseWriter, r *http.Request) { req := &network.CreateEndpointRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } res, err := h.driver.CreateEndpoint(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, res, false) }) h.HandleFunc(deleteEndpointPath, func(w http.ResponseWriter, r *http.Request) { req := &network.DeleteEndpointRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } err = h.driver.DeleteEndpoint(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, struct{}{}, false) }) h.HandleFunc(endpointInfoPath, func(w http.ResponseWriter, r *http.Request) { req := &network.InfoRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } res, err := h.driver.EndpointInfo(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, res, false) }) h.HandleFunc(joinPath, func(w http.ResponseWriter, r *http.Request) { req := &network.JoinRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } res, err := h.driver.Join(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, res, false) }) h.HandleFunc(leavePath, func(w http.ResponseWriter, r *http.Request) { req := &network.LeaveRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } err = h.driver.Leave(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, struct{}{}, false) }) h.HandleFunc(discoverNewPath, func(w http.ResponseWriter, r *http.Request) { req := &network.DiscoveryNotification{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } err = h.driver.DiscoverNew(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, struct{}{}, false) }) h.HandleFunc(discoverDeletePath, func(w http.ResponseWriter, r *http.Request) { req := &network.DiscoveryNotification{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } err = h.driver.DiscoverDelete(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, struct{}{}, false) }) h.HandleFunc(programExtConnPath, func(w http.ResponseWriter, r *http.Request) { req := &network.ProgramExternalConnectivityRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } err = h.driver.ProgramExternalConnectivity(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, struct{}{}, false) }) h.HandleFunc(revokeExtConnPath, func(w http.ResponseWriter, r *http.Request) { req := &network.RevokeExternalConnectivityRequest{} err := sdk.DecodeRequest(w, r, req) if err != nil { return } err = h.driver.RevokeExternalConnectivity(req) if err != nil { sdk.EncodeResponse(w, NewErrorResponse(err.Error()), true) return } sdk.EncodeResponse(w, struct{}{}, false) }) } <file_sep>package main import ( "crypto/sha256" "fmt" "net" "strconv" "math/rand" "time" ) /* SHA256 для string */ func HashOfString(str string) string { sum := sha256.Sum256([]byte(str)) return fmt.Sprintf("%x", sum) } // inc increments `ip` by one address, returning it in `ret` // e.g. 10.0.2.100 -> 10.0.2.101 // 10.0.2.255 -> 10.0.3.0 // 10.0.255.255 -> 10.1.0.0 // `ip` is not modified. // стянул у кого-то из интернета и переобозвал. func IncIP(ip net.IP) (ret net.IP) { ret = make(net.IP, len(ip)) copy(ret, ip) for j := len(ret) - 1; j >= 0; j-- { ret[j]++ if ret[j] > 0 { break } } return } /* Возвращает следующую сеть с той же маской. */ func IncNet(n net.IPNet) (res net.IPNet) { // copying network res.IP = make(net.IP, len(n.IP)) copy(res.IP, n.IP) // mask is ref res.Mask = n.Mask // сколько бит в маске и длинна адреса countBits, ipLen := res.Mask.Size() // стартовый байт в массиве c которого начинать отсчет сетей startByte := countBits / 8 // пограничный случай if countBits % 8 == 0 { startByte -- } firstInc := byte(1 << (uint(ipLen - countBits) % 8)) for j := startByte; j >= 0; j-- { res.IP[j] += firstInc if res.IP[j] > 0 { break } firstInc = 1 } return } /* Возвращает строковое представление IP адреса с маской */ func IpToCIDR(ip net.IP, mask net.IPMask) string { if ip == nil { return "" } postfix, _ := mask.Size() return ip.String() + "/" + strconv.Itoa(postfix) } /* Возвращает строковое представление IP сети с маской В случае, если сеть 0.0.0.0/0, то возвращается пустая строка */ func NetToCIDR(n net.IPNet) string { if n.IP.IsUnspecified() { return "" } return IpToCIDR(n.IP, n.Mask) } /* Генерирует мак случайным образом */ func GenerateMac() net.HardwareAddr { hw := make(net.HardwareAddr, 6) r := rand.New(rand.NewSource(time.Now().Unix())) r.Read(hw) hw[0] = (hw[0] | 2) & 0xfe // Set local bit, ensure unicast address return hw } <file_sep>package main import ( "testing" ) func TestNewPoolv4(t *testing.T) { pool := NewPoolv4() if pool == nil { t.Error() } if pool.Data == nil { t.Error() } } <file_sep>package main import ( "go.etcd.io/bbolt" ) func StartDatabase(dbname string) error { var err error db, err = bbolt.Open(dbname, 0666, nil) return err } func ShutdownDatabase() { db.Close() } var ( db *bbolt.DB ) <file_sep>package main import ( "net" "log" ) const ( DefaultPoolNameIPv4 = "10.50.0.0/24" DriverName = "l2vlan" ) var ( nets *net.IPNet ) func NewNetwork() net.IPNet { if nets == nil { _, nets, _ = net.ParseCIDR(DefaultPoolNameIPv4) } res := IncNet(*nets) copy(nets.IP, res.IP) return res } func main() { err := StartDatabase(DriverName + ".db") if err != nil { log.Panicln("Unable to start", DriverName, ":", err) } defer ShutdownDatabase() /*/// // debug version ipamDriver := &IPAMDebug{Wrap: &IPAMDriver{}} networkDriver := &NetworkDebug{Wrap: &NetworkDriver{}} ipamDriver.SetLogger(log.New(os.Stderr, "IPAM l2vlan", log.LstdFlags)) networkDriver.SetLogger(log.New(os.Stderr, "NETWORK l2vlan ", log.LstdFlags)) /*/// ipamDriver := &IPAMDriver{} networkDriver := &NetworkDriver{} //*/// handler := NewNetworkIpamHandler(networkDriver, ipamDriver) handler.ServeUnix(DriverName, 0666) } /* "CAP_NET_RAW", "CAP_NET_BIND_SERVICE", "CAP_AUDIT_READ", "CAP_AUDIT_WRITE", "CAP_DAC_OVERRIDE", "CAP_SETFCAP", "CAP_SETPCAP", "CAP_SETGID", "CAP_SETUID", "CAP_MKNOD", "CAP_CHOWN", "CAP_FOWNER", "CAP_FSETID", "CAP_KILL", "CAP_SYS_CHROOT", "CAP_NET_BROADCAST", "CAP_SYS_MODULE", "CAP_SYS_RAWIO", "CAP_SYS_PACCT", "CAP_SYS_ADMIN", "CAP_SYS_NICE", "CAP_SYS_RESOURCE", "CAP_SYS_TIME", "CAP_SYS_TTY_CONFIG", "CAP_AUDIT_CONTROL", "CAP_MAC_OVERRIDE", "CAP_MAC_ADMIN", "CAP_NET_ADMIN", "CAP_SYSLOG", "CAP_DAC_READ_SEARCH", "CAP_LINUX_IMMUTABLE", "CAP_IPC_LOCK", "CAP_IPC_OWNER", "CAP_SYS_PTRACE", "CAP_SYS_BOOT", "CAP_LEASE", "CAP_WAKE_ALARM", "CAP_BLOCK_SUSPEND" */ <file_sep>package main import ( "log" "regexp" "strconv" "net" "github.com/milosgajdos/tenus" "strings" "errors" "go.etcd.io/bbolt" "bytes" "encoding/gob" ) func createVlanAndAddToBridge(br tenus.Bridger, parent string, vlanId int) { // checking vlan exists ifName := strings.Join([]string{parent, strconv.Itoa(vlanId)}, ".") vlanif, err := net.InterfaceByName(ifName) if err != nil { // link to external network by vlan vlanif, err := tenus.NewVlanLinkWithOptions(parent, tenus.VlanOptions{Id: uint16(vlanId), Dev: ifName, MacAddr: GenerateMac().String()}) if err != nil { log.Fatalln("error creating vlan:", err) } vlanif.SetLinkUp() br.AddSlaveIfc(vlanif.NetInterface()) } else { log.Println("Vlan interface", ifName, "exists") err = br.AddSlaveIfc(vlanif) if err != nil { log.Println("Error adding interface", ifName, "to bridge:", err) } } } type Network struct { ID string BridgeName string VethName string Gateway string Routes []string HostInterface string VlanID int } func (n *Network) Load(id string) error { n.ID = id return db.View(func(tx *bbolt.Tx) error { b := tx.Bucket([]byte(n.ID)) if b != nil { data := b.Get([]byte("binary")) if data != nil { reader := bytes.NewReader(data) enc := gob.NewDecoder(reader) return enc.Decode(n) } } return errors.New("Network not exists") }) } func (n *Network) Save() error { return db.Update(func(tx *bbolt.Tx) error { b, err := tx.CreateBucketIfNotExists([]byte(n.ID)) if err != nil { return err} var writer bytes.Buffer dec := gob.NewEncoder(&writer) err = dec.Encode(n) if err != nil { return err } return b.Put([]byte("binary"), writer.Bytes()) }) } func (n *Network) Delete() error { return db.Update(func(tx *bbolt.Tx) error { return tx.DeleteBucket([]byte(n.ID)) }) } func (n *Network) GetOrCreateBridge() (tenus.Bridger, error) { br, err := tenus.BridgeFromName(n.BridgeName) if err != nil { br, err = tenus.NewBridgeWithName(n.BridgeName) if err != nil { log.Fatalln("error on creating bridge:", err) return nil, err } br.SetLinkUp() } else { log.Println("Bridge", n.BridgeName, "exists") } createVlanAndAddToBridge(br, n.HostInterface, n.VlanID) return br, err } func (n *Network) HostIfName() string { return n.VethName + "h" } func (n *Network) ContainerIfName() string { return n.VethName + "c" } type NetworkList []string func (list *NetworkList) Parse(str string) error { re := regexp.MustCompile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/?[0-9]*`) res := re.FindAllStringSubmatch(str, -1) rr := make(map[string]bool) for _, v := range res { val := v[0] if i := strings.IndexByte(val, '/'); i < 0 { val += "/32" } _, n, err := net.ParseCIDR(val) if err != nil { return err } val = n.String() rr[val] = true } for val,_ := range rr { *list = append(*list, val) } return nil }<file_sep>#!/usr/bin/env bash set -x PLUGIN=blins1999/l2vlan:latest PREFIX=192.168.1. ETH=eno1 VLAN=2000 docker plugin enable ${PLUGIN} sleep 5 docker network create -d ${PLUGIN} --ipam-driver=${PLUGIN} --subnet=${PREFIX}0/24 --gateway=${PREFIX}1 --ip-range=${PREFIX}2/32 \ -o vlan_id=${VLAN} -o ext_if=${ETH} -o bridge_name=vlan${VLAN} --config-only net1conf docker network create -d ${PLUGIN} --ipam-driver=${PLUGIN} --subnet=${PREFIX}0/24 --gateway=${PREFIX}1 --ip-range=${PREFIX}3/32 \ -o vlan_id=${VLAN} -o ext_if=${ETH} -o bridge_name=vlan${VLAN} --config-only net2conf sleep 3 docker network create -d ${PLUGIN} --scope swarm --config-from net1conf net1 docker network create -d ${PLUGIN} --scope swarm --config-from net2conf net2 sleep 3 docker stack deploy -c docker-compose1.yml stack1 docker stack deploy -c docker-compose2.yml stack2<file_sep>package main /* Логика работы: GetCapabilities GetDefaultAddressSpaces GetCapabilities GetDefaultAddressSpaces (почему 2 раза, не знаю... вероятно как припев в песне) RequestPool RequestAddress + gateway RequestAddress + mac (для каждого контейнера) ... работа ... ReleaseAddress ReleaseAddress + gateway ReleasePool */ import ( "github.com/docker/go-plugins-helpers/ipam" "github.com/docker/libnetwork/ipamapi" "github.com/docker/libnetwork/netlabel" "net" "errors" ) const ( GlobalDefaultAddressSpace = "global" LocalDefaultAddressSpace = "local" ) type IPAMDriver struct { } /* CapabilitiesResponse возвращает, требуется ли для этого IPAM предварительно созданный MAC RequiresMACAddress: Это логическое значение, которое сообщает libnetwork, должен ли драйвер ipam знать MAC-адрес интерфейса для правильной обработки вызова RequestAddress (). Если true, по запросу CreateEndpoint () libnetwork сгенерирует случайный MAC-адрес для конечной точки (если явный MAC-адрес еще не был предоставлен пользователем) и передаст его RequestAddress () при запросе IP-адреса внутри карты параметров. Ключом будет константа netlabel.MacAddress: "com.docker.network.endpoint.macaddress". */ func (d *IPAMDriver) GetCapabilities() (*ipam.CapabilitiesResponse, error) { return &ipam.CapabilitiesResponse{RequiresMACAddress:true}, nil } /* GetDefaultAddressSpaces возвращает имена локального и глобального адресного пространства по умолчанию для этого IPAM. Адресное пространство - это набор непересекающихся пулов адресов, изолированных от пулов других адресных пространств. Другими словами, один и тот же пул может существовать в N разных адресных пространствах. Адресное пространство естественно отображается на имя арендатора. В libnetwork значение, связанное с локальным или глобальным адресным пространством, заключается в том, что локальному адресному пространству не нужно синхронизироваться по всему кластеру, в то время как глобальные адресные пространства делают это. Если в конфигурации IPAM не указано иное, libnetwork будет запрашивать пулы адресов из локального или глобального адресного пространства по умолчанию в зависимости от области создаваемой сети. Например, если в конфигурации не указано иное, libnetwork будет запрашивать пул адресов из локального адресного пространства по умолчанию для мостовой сети, а из глобального адресного пространства по умолчанию для оверлейной сети. */ func (d *IPAMDriver) GetDefaultAddressSpaces() (*ipam.AddressSpacesResponse, error) { return &ipam.AddressSpacesResponse{ GlobalDefaultAddressSpace: GlobalDefaultAddressSpace, LocalDefaultAddressSpace: LocalDefaultAddressSpace, }, nil } /* Этот API предназначен для регистрации пула адресов с драйвером IPAM. Несколько идентичных вызовов должны возвращать один и тот же результат. Драйвер IPAM отвечает за ведение счетчика ссылок для пула. * AddressSpace - пространство IP-адресов. Обозначает набор непересекающихся пулов. * Pool - Пул адресов IPv4 или IPv6 в формате CIDR * SubPool - Необязательное подмножество пула адресов, диапазон ip в формате CIDR * Options - Карта специфичных для драйвера IPAM параметров * V6 - Независимо от IPAM выбранный пул должен быть IPv6 AddressSpace является единственным обязательным полем. Если пул не указан, драйвер IPAM может выбрать возврат самостоятельно выбранного пула адресов. В таком случае флаг V6 должен быть установлен, если вызывающий абонент хочет пул IPv6, выбранный IPAM. Запрос с пустым Пулом и непустым SubPool должен быть отклонен как недействительный. Если пул не указан, IPAM выделит один из пулов по умолчанию. Когда Пул не указан, флаг V6 должен быть установлен, если сети требуется выделение адресов IPv6. В ответе:     PoolID является идентификатором для этого пула. Одинаковые пулы должны иметь одинаковый идентификатор пула.     Pool - это пул в формате CIDR     Data - это метаданные, предоставленные драйвером IPAM для этого пула. */ func (d *IPAMDriver) RequestPool(request *ipam.RequestPoolRequest) (*ipam.RequestPoolResponse, error) { res := ipam.RequestPoolResponse{Data:make(map[string]string)} if request.V6 { // TODO } else { pool := NewPoolv4() // считаем PoolID if request.Pool == "" { if request.SubPool != "" { return nil, errors.New("Invalid request") } request.Pool = NetToCIDR(NewNetwork()) } // считаем ID пула res.PoolID = HashOfString(request.AddressSpace + request.Pool + request.SubPool) // присваиваем ID и делаем попытку загрузить err := pool.Load(res.PoolID) if err == nil { //пул существует!!!!! // чего с этим делать - непонятно } // заполняем его диапазонами pool.ParseCIDR(request.Pool, request.SubPool) // копируем опции for k, v := range request.Options { pool.Data[k] = v } res.Pool = NetToCIDR(pool.Network) // сохраняем в БД pool.Save() } return &res, nil } /* Этот API предназначен для освобождения ранее зарегистрированного пула адресов. */ func (d *IPAMDriver) ReleasePool(request *ipam.ReleasePoolRequest) error { pool := NewPoolv4() pool.Load(request.PoolID) return pool.Delete() } /* Этот API предназначен для резервирования IP-адреса. Параметры запроса:     PoolID - это идентификатор пула     Address - это требуемый адрес в обычной форме IP (A.B.C.D). Если этот адрес не может быть удовлетворен, запрос не выполняется. Если пусто, драйвер IPAM выбирает любой доступный адрес в пуле     Options - это параметры драйвера IPAM В ответе:     Address - это выделенный адрес в формате CIDR (A.B.C.D / MM)     Data - это определенные метаданные драйвера IPAM */ func (d *IPAMDriver) RequestAddress(request *ipam.RequestAddressRequest) (*ipam.RequestAddressResponse, error) { res := ipam.RequestAddressResponse{Data:make(map[string]string)} pool := NewPoolv4() pool.Load(request.PoolID) if v, ok := request.Options[ipamapi.RequestAddressType]; ok { if v == netlabel.Gateway { // шлюз по умолчанию. //назначаем его в пул pool.Gateway = net.ParseIP(request.Address) // формируем CIDR с маской res.Address = IpToCIDR(pool.Gateway, pool.Network.Mask) // сохраняем изменения pool.Save() return &res, nil } } var ip net.IP // остальные адреса if request.Address == "" { // если адрес не задан ip, _ = pool.GetFirstFree() } else { // если у нас есть указание адреса уже ip = net.ParseIP(request.Address) // проверяем его на свободность if !pool.IpIsFree(ip) { // ежели занят return nil, errors.New("Ip already assigned") } } res.Address = IpToCIDR(ip, pool.Network.Mask) // выдаем и регистрируем pool.RegisterIP(ip) return &res, nil } /* Этот API предназначен для освобождения IP-адреса. */ func (d *IPAMDriver) ReleaseAddress(request *ipam.ReleaseAddressRequest) error { pool := NewPoolv4() pool.Load(request.PoolID) ip := net.ParseIP(request.Address) return pool.DeregisterIP(ip) } /* go get github.com/docker/go-plugins-helpers go get go.etcd.io/bbolt/ go get github.com/docker/libnetwork go get github.com/coreos/go-systemd go get github.com/docker/go-connections */ // "docker.ipamdriver/1.0",<file_sep>package main import ( "fmt" "bytes" "testing" ) type DebuggerTest struct { value string } func (dt *DebuggerTest) Println(v ...interface{}) { var buffer bytes.Buffer fmt.Fprintln(&buffer, v...) dt.value = string(buffer.Bytes()) } func TestDebugger_SetLogger(t *testing.T) { var d Debugger d.SetLogger(&DebuggerTest{}) if d.logger == nil { t.Error() } } func TestDebugger_Println(t *testing.T) { var d Debugger var dt DebuggerTest d.SetLogger(&dt) d.Println("test", 1000) if dt.value != "test 1000\n" { t.Error() } }<file_sep># Драйвер для подключения контейнеров во внешний vlan по L2 ## Предистория Понадобилось мне запустить несколько контейнеров в docker swarm и выпустить их траффик непосредственно в определенный vlan. Всё было готово с точки зрения классической организации сети: vlan создан на маршрутизаторе, навешан gateway и дотянут на коммутаторах до порта на серверах. Каждый контейнер должен иметь свой фиксированный адрес. Я недолго думая создал сети macvlan на всех узлах и запустил один контейнер. Всё было хорошо. Я запустил второй контейнер. И тут всё было хорошо. Только вот третий контейнер не хотел запускаться... Давай я копать, что же могло пойти не так. Контейнер не запускался с ошибкой (прим. перевод): "Шлюз (айпишник) не может быть назначен из-за того, что он уже назначен где-то". Фигассе, - думаю. Этого адреса нигде нету, пробежался по все интерфейсам - нету, от слова "совсем". Замечаю, что это не работает на узле где уже запущен этот контейнер или, внезапно, была попытка запуска контейнера. Я в абсолютных непонятках остановил запущенные контейнеры, которые привязаны к этим сетям и давай удалять сети. Сама сеть удалилась, а вот конфиги сетей не хотят удаляться, говорят, что они где-то используются. Всё проверил, не нашел использования. Пошукал в ихних интернетах: пришут что это есть такая бага и надо бы стопануть сервис докера и удалить локальное хранилище... и тогда у тебя пропадут все локальные конфиги и будет тебе счастье... Хорошо, что у меня из локальных конфигов были пока только эти. Ладно, вышарашил и стал думу думать. Сделал стенд у себя на локальном компьютере и воспроизвел ошибку. Воспроизводится она, кстати, очень легко: ```bash $ docker network create -d macvlan --subnet=192.168.1.0/24 --gateway=192.168.1.1 --ip-range=192.168.1.2/32 \ --config-only -o parent=eno1.2000 net1conf $ docker network create -d macvlan --subnet=192.168.1.0/24 --gateway=192.168.1.1 --ip-range=192.168.1.3/32 \ --config-only -o parent=eno1.2000 net2conf $ docker network create -d macvlan --scope swarm --config-from net1conf net1 $ docker network create -d macvlan --scope swarm --config-from net2conf net2 $ docker stack deploy -c docker-compose1.yml stack1 # здесь еще всё хорошо $ docker stack deploy -c docker-compose2.yml stack2 # а вот это уже было ошибкой ``` Стеки очень простые: состоят из одного сервиса nginx, который в одном экземпляре запускается и подключается во внешнюю сеть net1 и net2 соответственно. Для примера приведу один файлик: ```yaml version: "3.7" services: nginx: image: nginx:alpine networks: - net1 deploy: restart_policy: condition: any mode: replicated replicas: 1 networks: net1: external: true ``` Скачал себе исходный код moby и libnetwork и стал искать что генерирует такую ошибку. Оказалось драйвер IPAM. Такое поведение можно исправить, если написать свой драйвер и использовать его. "Ну ок". Сказано - сделано. Написал драйвер, где поведение от стандартного отличается только тем, что он не ругается на адрес gateway совсем, он просто принимает его к сведению. И вот я полный предвкушения и триумфа запускаю всё по выше приведенному примеру и получаю жесткий облом. При создании net2 драйвер macvlan не может создать интерфейс eno1.2000. Фигня вопрос - используем драйвер bridge. А вот тут всё хорошо, но только этот драйвер за каким-то хреном навешивал адрес шлюза на используемый bridge. И никак его было не переубедить. Вобщем пришел к выводу что надо написать свой сетевой драйвер. И вот он. ## Как это работает Драйвер создает bridge с указанным именем. Создает sub-interface с указанным тегом vlan к указанному interface. Объединяет созданное. А дальше просто подсоединяет по L2 контенеры к этому bridge. Если bridge уже создан, то драйвер не проверяет наличие sub-interface с указанным тегом vlan? т.к. предполагается что он уже создан и работает. Странно почему господа программисты из компании docker не додумались до такого. наверняка ведь было бы востребовано. ## Как пользоваться Сначала нужно установить плагин: ```bash $ docker plugin install --alias "l2vlan" blins1999/l2vlan ``` Создавать сеть примерно так: ```bash $ docker network create -d l2vlan:latest --ipam-driver l2vlan:latest --subnet=192.168.1.0/24 --gateway=192.168.1.1 \ --ip-range=192.168.1.4/32 -o vlan_id=2000 -o ext_if=eno1 -o bridge_name=vlan2000 --config-only net1conf $ docker network create -d l2vlan:latest --scope swarm --config-from net1conf net1 ``` Надо ли говорить, что первая команда выполняется на КАЖДОМ узле кластера. Дальше можно добавлять статические адреса: ```bash $ docker network create -d l2vlan:latest --ipam-driver l2vlan:latest --subnet=192.168.1.0/24 --gateway=192.168.1.1 \ --ip-range=192.168.1.6/32 -o vlan_id=2000 -o ext_if=eno1 -o bridge_name=vlan2000 --config-only net2conf $ docker network create -d l2vlan:latest --scope swarm --config-from net2conf net2 ``` И всё это будет подключено к одному и тому же brdige (в рамках одного узка конечно) ## Что надо бы сделать - Надо разобраться с linux сapabilities. Буду рад помощи. Ну и вроде всё :)<file_sep>package main import ( "testing" "github.com/docker/go-plugins-helpers/ipam" ) func TestRightIPAMDriver_GetCapabilities(t *testing.T) { d := IPAMDriver{} r, err := d.GetCapabilities() if err != nil { t.Error(err) } if r == nil { t.Error() } if r.RequiresMACAddress != true { t.Error() } } func TestRightIPAMDriver_GetDefaultAddressSpaces(t *testing.T) { d := IPAMDriver{} r, err := d.GetDefaultAddressSpaces() if err != nil { t.Error(err) } if r == nil { t.Error() } if r.LocalDefaultAddressSpace != LocalDefaultAddressSpace || r.GlobalDefaultAddressSpace != GlobalDefaultAddressSpace { t.Error() } } func TestRightIPAMDriver_RequestPool(t *testing.T) { StartDatabase(TestDatabase) defer ShutdownDatabase() d := IPAMDriver{} request := ipam.RequestPoolRequest{} request.AddressSpace = LocalDefaultAddressSpace request.V6 = false res, err := d.RequestPool(&request) if err != nil { t.Error(err) } if res == nil { t.Error() } if res.PoolID == "" { t.Error() } if res.Pool == "" { t.Error() } if res.Pool == "0.0.0.0/0" { t.Error() } rp_request := ipam.ReleasePoolRequest{PoolID:res.PoolID} err = d.ReleasePool(&rp_request) if err != nil { t.Error(err) } } func TestRightIPAMDriver_RequestPool2(t *testing.T) { StartDatabase(TestDatabase) defer ShutdownDatabase() d := IPAMDriver{} request := ipam.RequestPoolRequest{} request.AddressSpace = LocalDefaultAddressSpace request.SubPool = "192.168.1.2/32" request.V6 = false res, err := d.RequestPool(&request) if err == nil { t.Error(err) } if res != nil { t.Error() } } func TestRightIPAMDriver_RequestPool3(t *testing.T) { StartDatabase(TestDatabase) defer ShutdownDatabase() d := IPAMDriver{} request := ipam.RequestPoolRequest{} request.AddressSpace = LocalDefaultAddressSpace request.V6 = false request.Pool = "192.168.1.1/24" res, err := d.RequestPool(&request) if err != nil { t.Error(err) } if res == nil { t.Error() } if res.PoolID == "" { t.Error() } if res.Pool != "192.168.1.0/24" { t.Error() } rp_request := ipam.ReleasePoolRequest{PoolID:res.PoolID} err = d.ReleasePool(&rp_request) if err != nil { t.Error(err) } } func TestRightIPAMDriver_RequestPool4(t *testing.T) { StartDatabase(TestDatabase) defer ShutdownDatabase() d := IPAMDriver{} request := ipam.RequestPoolRequest{} request.AddressSpace = LocalDefaultAddressSpace request.V6 = false request.Pool = "192.168.1.1/24" request.SubPool = "192.168.1.4/30" res, err := d.RequestPool(&request) if err != nil { t.Error(err) } if res == nil { t.Error() } if res.PoolID == "" { t.Error() } if res.Pool != "192.168.1.0/24" { t.Error() } rp_request := ipam.ReleasePoolRequest{PoolID:res.PoolID} err = d.ReleasePool(&rp_request) if err != nil { t.Error(err) } } func TestRightIPAMDriver_RequestAddress(t *testing.T) { StartDatabase(TestDatabase) defer ShutdownDatabase() d := IPAMDriver{} request := ipam.RequestPoolRequest{} request.AddressSpace = LocalDefaultAddressSpace request.V6 = false request.Pool = "192.168.1.1/24" request.SubPool = "192.168.1.4/30" pool, err := d.RequestPool(&request) r_addr := ipam.RequestAddressRequest{PoolID:pool.PoolID} resp_addr, err := d.RequestAddress(&r_addr) if err != nil { t.Error(err) } if resp_addr == nil { t.Error() } if resp_addr.Address != "192.168.1.4/24" { t.Error() } rp_addr := ipam.ReleaseAddressRequest{PoolID:pool.PoolID, Address:resp_addr.Address} err = d.ReleaseAddress(&rp_addr) if err != nil { t.Error(err) } rp_request := ipam.ReleasePoolRequest{PoolID:pool.PoolID} err = d.ReleasePool(&rp_request) if err != nil { t.Error(err) } } <file_sep>package main import ( "strconv" "fmt" ) /* Чтобы проще было работать со значениями которые передаются вот так неопределенно */ type AnyVal struct{ Value interface{} } /* Возвращает строковое представление. Работает если значение имеет типы: - int - string - fmt.Stringer */ func (v AnyVal) String() string { switch tv := v.Value.(type) { case int: return strconv.Itoa(tv) case string: return tv case fmt.Stringer: return tv.String() } return "" } /* Возвращает целочисленное представление. Работает если значение имеет типы: - int - string - fmt.Stringer */ func (v AnyVal) Int() int { switch tv := v.Value.(type) { case int: return tv case string: i, _ := strconv.Atoi(tv) return i case fmt.Stringer: i,_ := strconv.Atoi(tv.String()) return i } return 0 } <file_sep>package main import ( "github.com/docker/go-plugins-helpers/network" ) type NetworkDebug struct { Wrap network.Driver Debugger } func (self *NetworkDebug) GetCapabilities() (*network.CapabilitiesResponse, error) { self.Println("GetCapabilities call") res, err := self.Wrap.GetCapabilities() self.Println("GetCapabilities result", res, err) return res, err } func (self *NetworkDebug) CreateNetwork(r *network.CreateNetworkRequest) error { self.Println("CreateNetwork call", r) err := self.Wrap.CreateNetwork(r) self.Println("CreateNetwork result", err) return err } func (self *NetworkDebug) AllocateNetwork(r *network.AllocateNetworkRequest) (*network.AllocateNetworkResponse, error) { self.Println("AllocateNetwork call", r) res, err := self.Wrap.AllocateNetwork(r) self.Println("AllocateNetwork result", res, err) return res, err } func (self *NetworkDebug) DeleteNetwork(r *network.DeleteNetworkRequest) error { self.Println("DeleteNetwork call", r) err := self.Wrap.DeleteNetwork(r) self.Println("DeleteNetwork result", err) return err } func (self *NetworkDebug) FreeNetwork(r *network.FreeNetworkRequest) error { self.Println("FreeNetwork call", r) err := self.Wrap.FreeNetwork(r) self.Println("FreeNetwork result", err) return err } func (self *NetworkDebug) CreateEndpoint(r *network.CreateEndpointRequest) (*network.CreateEndpointResponse, error) { self.Println("CreateEndpoint call", r) res, err := self.Wrap.CreateEndpoint(r) self.Println("CreateEndpoint result", res, err) return res, err } func (self *NetworkDebug) DeleteEndpoint(r *network.DeleteEndpointRequest) error { self.Println("DeleteEndpoint call", r) err := self.Wrap.DeleteEndpoint(r) self.Println("DeleteEndpoint result", err) return err } func (self *NetworkDebug) EndpointInfo(r *network.InfoRequest) (*network.InfoResponse, error) { self.Println("EndpointInfo call", r) res, err := self.Wrap.EndpointInfo(r) self.Println("EndpointInfo result", res, err) return res, err } func (self *NetworkDebug) Join(r *network.JoinRequest) (*network.JoinResponse, error) { self.Println("Join call", r) res, err := self.Wrap.Join(r) self.Println("Join result", res, err) return res, err } func (self *NetworkDebug) Leave(r *network.LeaveRequest) error { self.Println("Leave call", r) err := self.Wrap.Leave(r) self.Println("Leave result", err) return err } func (self *NetworkDebug) DiscoverNew(r *network.DiscoveryNotification) error { self.Println("DiscoverNew call", r) err := self.Wrap.DiscoverNew(r) self.Println("DiscoverNew result", err) return err } func (self *NetworkDebug) DiscoverDelete(r *network.DiscoveryNotification) error { self.Println("DiscoverDelete call", r) err := self.Wrap.DiscoverDelete(r) self.Println("DiscoverDelete result", err) return err } func (self *NetworkDebug) ProgramExternalConnectivity(r *network.ProgramExternalConnectivityRequest) error { self.Println("ProgramExternalConnectivity call", r) err := self.Wrap.ProgramExternalConnectivity(r) self.Println("ProgramExternalConnectivity result", err) return err } func (self *NetworkDebug) RevokeExternalConnectivity(r *network.RevokeExternalConnectivityRequest) error { self.Println("RevokeExternalConnectivity call", r) err := self.Wrap.RevokeExternalConnectivity(r) self.Println("RevokeExternalConnectivity result", err) return err } <file_sep>package main import ( "testing" ) func TestNewNetwork(t *testing.T) { ss := NetToCIDR(*nets) n := NewNetwork() if n.IP.IsUnspecified() { t.Error() } if s := NetToCIDR(n); s == ss { t.Error("Invalid", s) } }
9beed73a2f8a5de84ebb13675cd4044c85e41c2c
[ "Markdown", "Go", "Makefile", "Shell" ]
25
Go
blins/l2vlan
02a4f2e28898e447f76ec9d1e90be1b24c29d6e9
094558ec5a4a58feef327611c3c11f79db54a269
refs/heads/master
<file_sep>from django.shortcuts import render from django.http import HttpResponse from .models import table # Create your views here. def home(request): tabs = table.objects.all() return render(request,'index.html', {'tabs': tabs})<file_sep>from django.db import models # Create your models here. class table(models.Model): name = models.TextField(max_length=100) age = models.IntegerField() Qualification = models.TextField(max_length=100) year_of_passing = models.IntegerField() #img = models.Imagefiels(upload_to='filename')
0ed0a6fd69670c491b8597664daa6166a27f1c91
[ "Python" ]
2
Python
nirmal-relevel/project
1751a7cd14fd46a0cf230c85d7944d5df005c80e
74fc5e75e33dc4286c6fbdaee896bf5898811f3a
refs/heads/main
<repo_name>AntonRiab/argv.lib.sh<file_sep>/GNUmakefile all: argv.low.lib.sh argv.mid.lib.sh \ 0.1.sample_small_help_undefine \ 1.1.sample_low_help_define \ 2.1.sample_mid_annotation_undefine \ 3.1.sample_mid_annotation_define \ test argv.low.lib.sh: @cp argv_src/argv.low.lib.sh argv.low.lib.sh argv.mid.lib.sh: @echo "Concate help with low to make mid lib." @cat argv_src/argv.help.lib.sh > argv.mid.lib.sh @cat argv_src/argv.low.lib.sh >> argv.mid.lib.sh argv.lib: argv.low.lib.sh argv.mid.lib.sh 0.1.sample_small_help_undefine: @echo "Embed lib to 0.0.sample_low_help_undefine." @cat 0.0.sample_low_help_undefine | sed '/argv.low.lib.sh/d' > 0.1.sample_low_help_undefine @cat argv.low.lib.sh >> 0.1.sample_low_help_undefine 1.1.sample_low_help_define: @echo "Embed lib to file 1.0.sample_low_help_define." @cat 1.0.sample_low_help_define | sed '/argv.low.lib.sh/d' > 1.1.sample_low_help_define @cat argv.low.lib.sh >> 1.1.sample_low_help_define 2.1.sample_mid_annotation_undefine: @echo "Embed lib to file 2.0.sample_mid_annotation_undefine." @cat 2.0.sample_mid_annotation_undefine | sed '/argv.mid.lib.sh/d' > 2.1.sample_mid_annotation_undefine @cat argv.mid.lib.sh >> 2.1.sample_mid_annotation_undefine 3.1.sample_mid_annotation_define: @echo "Embed lib to file 3.0.sample_mid_annotation_define." @cat 3.0.sample_mid_annotation_define | sed '/argv.mid.lib.sh/d' > 3.1.sample_mid_annotation_define @cat argv.mid.lib.sh >> 3.1.sample_mid_annotation_define 4.1.sample_low_default_other: @echo "Embed lib to file 4.0.sample_low_default_other." @cat 4.0.sample_low_default_other | sed '/argv.mid.lib.sh/d' > 4.1.sample_low_default_other @cat argv.mid.lib.sh >> 4.1.sample_low_default_other 5.1.sample_mid_default_other: @echo "Embed lib to file 5.0.sample_mid_default_other." @cat 5.0.sample_mid_default_other | sed '/argv.mid.lib.sh/d' > 5.1.sample_mid_default_other @cat argv.mid.lib.sh >> 5.1.sample_mid_default_other test_eval: argv.low.lib.sh argv.mid.lib.sh @echo "Run tests eval" @mkdir -p test_output @chmod +x *.sample* @find ./ -maxdepth 1 -name '*.sample*' | sed -r 's#^\./(.*)$$#./\1 > test_output/\1#' | sh test_validation: @printf "Validate test result..." @rm test_result 2>/dev/null || return 0 @ls test_output/ | sed -r 's#^(.*)$$#diff -u test_output/\1 test_reference/\1 >> test_result#' | sh @test -s ./test_result \ && printf "ERROR. \nOutput does not eqvivalent reference. See file test_output!\n" \ || echo "OK" && return 0 test: test_eval test_validation clean: @echo "Remove test result." @rm -r test_output 2>/dev/null || return 0 @rm test_result 2>/dev/null || return 0 clean_all: clean @echo "Remove samples with embeded lib." @rm argv.mid.lib.sh 2>/dev/null || return 0 @rm argv.low.lib.sh 2>/dev/null || return 0 @rm 0.1.sample_low_help_undefine 2>/dev/null || return 0 @rm 1.1.sample_low_help_define 2>/dev/null || return 0 @rm 2.1.sample_mid_annotation_undefine 2>/dev/null || return 0 @rm 3.1.sample_mid_annotation_define 2>/dev/null || return 0 @rm 4.1.sample_low_default_other 2>/dev/null || return 0 @rm 5.1.sample_mid_default_other 2>/dev/null || return 0 <file_sep>/1.0.sample_low_help_define #!/bin/sh test1() { echo "It's test1 with $# arguments: \"$@\"" } test2() { echo "It's test2 with $# arguments: \"$@\"" } help() { printf "It's from help:\n$(echo "$AF" | sed 's/^/\t--/g')\n" return 0 } . ./argv.low.lib.sh <file_sep>/3.1.sample_mid_annotation_define #!/bin/sh firstvar_help="Information about first var" firstvar=${firstvar:-"First var"} othervar_help="Information about second" othervar=${othervar:-"Value of other var"} test1_help="Some help about test1" test1() { echo "It's test1 with $# arguments: \"$@\"" } test2() { echo "It's test2 with $# arguments: \"$@\"" } ############################################################################### ##Copyright (C) <NAME> (AntonRiab) ##Middle part ############################################################################### help() { ALL_HELPS=$(cat "$0" | sed -rn '/^[0-9A-Za-z_]+_help=/{s/_help=.*$//p}') FUNC_W_HELP=$(printf "$ALL_HELPS\n$AF\n" | sort | uniq -D | uniq) VAR_W_HELP=$(printf "$ALL_HELPS\n$FUNC_W_HELP\n" | sort | uniq -u) test "$GLOBAL_HELP" && echo $GLOBAL_HELP test -z "$VAR_W_HELP$FUNC_W_HELP" \ && printf "Avalible functions:\n$(echo "$AF" | sed 's/^/\t--/g')\n" \ && exit 0 test "$VAR_W_HELP" \ && echo "Avalible variables:" && eval $(echo "$VAR_W_HELP" \ | sed -r 's/(.*)/printf "\t\1=\\\"$\1\\\"\t- $\1_help\n"/;') test "$FUNC_W_HELP" \ && echo "Avalible functions:" && eval $(echo "$FUNC_W_HELP" | \ sed -r 's/(.*)/printf "\t--\1\t- $\1_help\n"/;') return 0 } ############################################################################### ##Copyright (C) <NAME> (AntonRiab) ##Small integration argv.low.lib.sh ############################################################################### IFS=$(printf " \t\n");DEFAULT_FUNCTION=${DEFAULT_FUNCTION:-"help"} AF="$(cat $0 | sed -rn 's/^([0-9a-zA-Z_]*)\(\) *\{/\1/p')" test $# -lt 1 && F=$DEFAULT_FUNCTION || F=$@ test "$(echo $F | grep -i help)" -o ! "$F" \ && test -z "$(type help | grep funct)" && echo "$AF" | sed 's/^/\t--/' && exit 0 rf() { F="$1" TR=$(printf "help\n$AF\n" | grep "^$F$") test ! "$TR" && echo "No function $F avalible!" && return if [ $# -lt 2 ]; then eval "$TR"; return $?; fi shift && eval "$TR $@" } IFS='#';for i in $(echo "$F" | sed 's/ *--/#/g;s/^#//');do IFS=' ';rf $i;done <file_sep>/3.0.sample_mid_annotation_define #!/bin/sh firstvar_help="Information about first var" firstvar=${firstvar:-"First var"} othervar_help="Information about second" othervar=${othervar:-"Value of other var"} test1_help="Some help about test1" test1() { echo "It's test1 with $# arguments: \"$@\"" } test2() { echo "It's test2 with $# arguments: \"$@\"" } . ./argv.mid.lib.sh <file_sep>/5.0.sample_mid_default_other #!/bin/sh test1() { echo "It's test1 with $# arguments: \"$@\"" } test2() { echo "It's test2 with $# arguments: \"$@\"" } other() { echo "It's from other function with $# arguments: \"$@\"" return 0 } DEFAULT_FUNCTION="other" . ./argv.mid.lib.sh <file_sep>/0.1.sample_low_help_undefine #!/bin/sh test1() { echo "It's test1 with $# arguments: \"$@\"" } test2() { echo "It's test2 with $# arguments: \"$@\"" } ############################################################################### ##Copyright (C) <NAME> (AntonRiab) ##Small integration argv.low.lib.sh ############################################################################### IFS=$(printf " \t\n");DEFAULT_FUNCTION=${DEFAULT_FUNCTION:-"help"} AF="$(cat $0 | sed -rn 's/^([0-9a-zA-Z_]*)\(\) *\{/\1/p')" test $# -lt 1 && F=$DEFAULT_FUNCTION || F=$@ test "$(echo $F | grep -i help)" -o ! "$F" \ && test -z "$(type help | grep funct)" && echo "$AF" | sed 's/^/\t--/' && exit 0 rf() { F="$1" TR=$(printf "help\n$AF\n" | grep "^$F$") test ! "$TR" && echo "No function $F avalible!" && return if [ $# -lt 2 ]; then eval "$TR"; return $?; fi shift && eval "$TR $@" } IFS='#';for i in $(echo "$F" | sed 's/ *--/#/g;s/^#//');do IFS=' ';rf $i;done <file_sep>/2.0.sample_mid_annotation_undefine #!/bin/sh test1() { echo "It's test1 with $# arguments: \"$@\"" } test2() { echo "It's test2 with $# arguments: \"$@\"" } . ./argv.mid.lib.sh <file_sep>/README.md About =============== It's addition for use with or instead getopts. It's helps you writing scripts faster. Sample of script demo_light ----------------------- $ cat 0.0.sample_low_help_undefine #!/bin/sh test1() { echo "It's test1 with $# arguments: \"$@\"" } test2() { echo "It's test2 with $# arguments: \"$@\"" } . ./argv.low.lib.sh Samples of valid shell calls ----------------------- $ ./0.0.sample_low_help_undefine --test1 --test2 $ ./0.0.sample_low_help_undefine --test1 a b It's test1 with 2 arguments: "a b" Conception =============== How people write large script usually...in my observations: They write a few lines. After some time they append new strings. The exists lines makes some entity and they wrap it into a function. Every new entity needs external call. So it needs to have been added into the argument parses. **You have to edit argument parses everytime when you make or change entity? - the argv.lib.sh solve it!** It work with arguments without your interventions. All possibilities =============== Low version can accelerates your work with next functionality: * **function** call from arguments: function have to begin from start of line and first string of the function have to end with `{` like `myfunction () {` * **argument** of function by arguments: it pass with in default into your function. Middle version to add to low version: * **help** creation: just add variable with end **_help** in the name - it automatic will added to the help output. You can insert library code into end of your script or use link like `. ./argv.mid.lib.sh`. Just see the samples. Recommendation and calls =============== Make variable in you script like next `variable=${variable:-"It's default"}`, it's will gave you opportunity to change it in envirement. You can call it with variables changes `variable1=test ./scriptname function_in_script function_argv` If you make custom help, use space before name function like ` help() {` Samples in current directory =============== You can found it in current directory. Status =============== Stable. Tested on Ubuntu 18.04 Files =============== * argv.lib.low.sh - library without annotated help * argv.lib.mid.sh - library with annotated help * 0.0.sample_low_help_undefine - include external link to lib, without custom help * 0.1.sample_low_help_undefine - concat script and library, without custom help * 1.0.sample_low_help_define - include ex.link to lib, without custom help * 1.1.sample_low_help_define - concat script and library, with custom help * 2.0.sample_mid_annotation_undefine - include ex.link, help lib, without annotation * 2.1.sample_mid_annotation_undefine - concat with lib, help lib, without annotation * 3.0.sample_mid_annotation_define - include ex.link, help lib, with annotation * 3.1.sample_mid_annotation_define - concat with lib, help lib, with annotation * GNUmakefile - it's need for concat src help and low lib to mid version. And test. * test_reference - only for self tests. License ====== MIT License Copyright (c) 2021 <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. <file_sep>/argv_src/argv.help.lib.sh ############################################################################### ##Copyright (C) <NAME> (AntonRiab) ##Middle part ############################################################################### help() { ALL_HELPS=$(cat "$0" | sed -rn '/^[0-9A-Za-z_]+_help=/{s/_help=.*$//p}') FUNC_W_HELP=$(printf "$ALL_HELPS\n$AF\n" | sort | uniq -D | uniq) VAR_W_HELP=$(printf "$ALL_HELPS\n$FUNC_W_HELP\n" | sort | uniq -u) test "$GLOBAL_HELP" && echo $GLOBAL_HELP test -z "$VAR_W_HELP$FUNC_W_HELP" \ && printf "Avalible functions:\n$(echo "$AF" | sed 's/^/\t--/g')\n" \ && exit 0 test "$VAR_W_HELP" \ && echo "Avalible variables:" && eval $(echo "$VAR_W_HELP" \ | sed -r 's/(.*)/printf "\t\1=\\\"$\1\\\"\t- $\1_help\n"/;') test "$FUNC_W_HELP" \ && echo "Avalible functions:" && eval $(echo "$FUNC_W_HELP" | \ sed -r 's/(.*)/printf "\t--\1\t- $\1_help\n"/;') return 0 }
44282062331d35d176af507687ed346179b63fd2
[ "Markdown", "Makefile", "Shell" ]
9
Makefile
AntonRiab/argv.lib.sh
8c3ba7ccc1cf15ba55dbc76cd8614561d2675750
b4d6de6efebcb477c573b5637c00ccad324c1533
refs/heads/master
<file_sep># test for for git # second comment <file_sep># for testing servo positions global servo global direction servo = 0 direction = 1 servo_value = 100 print('Enter 1, 2 or 3 for sun, mask or moon') print('Enter f for forward or r for reverse for servo direct') print('Enter exit to exit') while 1: key_press = input('Press a key ') if key_press == 'exit': exit() if key_press == '1': servo = 0 servo_value = 100 print('Servo sun has been selected, servo_value set to 100') if key_press == '2': servo = 2 servo_value = 100 print('Servo mask has been selected, servo_value set to 100') if key_press == '3': servo = 3 servo_value = 100 print('Servo moon has been selected, servo_value set to 100') if key_press == 'f': print('Direction set to forward') direction = 1 if key_press == 'r': print('Direction set to reverse') direction = -1 if len(key_press) == 0: servo_value += direction print('move servo {} in the direction {} with value {}'.format(servo, direction, servo_value))
5d7e6ddac09073cb5a79b8822dae5478c9cec2f3
[ "Python" ]
2
Python
pomgolian/servo_check
eb7175f6403191b8c07bde61b87c133aada97198
94b35127a191010251a2a855f495e0fb5ff1dcc4
refs/heads/master
<repo_name>earnolmartin/Dynamix-DNS-Client-for-Windows<file_sep>/src/WindowsFormsApplication1/Classes/DynamixSettings.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DynamixDNS.Classes { [Serializable] public class DynamixSettings : DDNSService { } } <file_sep>/src/WindowsFormsApplication1/Helpers/XpertDNSHelper.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using DynamixDNS.Classes; namespace DynamixDNS.Helpers { public static class XpertDNSHelper { public static string settingsFile = AppDomain.CurrentDomain.BaseDirectory + "xpertdns.bin"; public static string endPointURL = "https://www.xpertdns.com/dyndns.php"; public static string serviceName = "XpertDNS"; public static BinaryFormatter bformatter = new BinaryFormatter(); public static XPertDNSSettings LoadOptions(dyndnsServices dyndnsServices = null) { XPertDNSSettings settings = new XPertDNSSettings(); try { if (File.Exists(settingsFile)) { using (Stream stream = File.Open(settingsFile, FileMode.Open)) { settings = (XPertDNSSettings)bformatter.Deserialize(stream); } settings.Password = GenericHelper.DecodeFrom64(settings.Password); } } catch (Exception e) { Console.WriteLine(e); } if (dyndnsServices != null) { dyndnsServices.XPertDNSPass.Text = settings.Password; dyndnsServices.XPertDNSConfirmPass.Text = settings.Password; dyndnsServices.xpertEnable.Checked = settings.Enabled; dyndnsServices.dynIDsXPertDNS.Items.Clear(); if (settings.Hosts.Any()) { dyndnsServices.dynIDsXPertDNS.Items.AddRange(settings.Hosts.ToArray()); } dyndnsServices.login4XPertDNS.Text = settings.Login; } return settings; } public static string SaveOptions(XPertDNSSettings settings, dyndnsServices dyndnsServices = null) { int errors = 0; string errorMessage = string.Empty; if (dyndnsServices != null && settings.Enabled) { // Perform validation if (string.IsNullOrEmpty(dyndnsServices.login4XPertDNS.Text)) { errors++; errorMessage += "You must provide your " + serviceName + " login email address!" + Environment.NewLine; } else { if (!GenericHelper.IsValidEmail(dyndnsServices.login4XPertDNS.Text)) { errors++; errorMessage += "Your " + serviceName + " login must be your email address!" + Environment.NewLine; } } if (dyndnsServices.XPertDNSPass.Text != dyndnsServices.XPertDNSConfirmPass.Text) { errors++; errorMessage += "The " + serviceName + " passwords do not match!" + Environment.NewLine; } else { if (!string.IsNullOrEmpty(dyndnsServices.XPertDNSPass.Text) && !string.IsNullOrEmpty(dyndnsServices.XPertDNSConfirmPass.Text)) { settings.Password = dyndnsServices.XPertDNSPass.Text; } else { errors++; errorMessage += "You must provide your " + serviceName + " password and confirm the password." + Environment.NewLine; } } if (dyndnsServices.dynIDsXPertDNS.Items.Count <= 0) { errors++; errorMessage += "There are no " + serviceName + " host IDs to save!" + Environment.NewLine; } } if (errors == 0) { //serialize settings.Password = GenericHelper.EncodeTo64(settings.Password); using (Stream stream = File.Open(settingsFile, FileMode.Create)) { bformatter.Serialize(stream, settings); } } return errorMessage; } public static string RunUpdates(XPertDNSSettings settings, string IPAddress) { string returnStatus = ""; foreach (string host in settings.Hosts) { string url = endPointURL + "?dynid=" + host + "&ip=" + IPAddress + "&uname=" + settings.Login + "&password=" + settings.MD5Password; string response = GenericHelper.MakeHTTPGETRequest(url); if (response.StartsWith("Exception")) { returnStatus += serviceName + " host ID " + host + " failed to update due to a system exception. " + response.Replace(Environment.NewLine, " ") + Environment.NewLine; } else if (response.Trim() != (host + "=Successfully Updated=") && !response.Trim().StartsWith(host + "=Successfully Updated=")) { returnStatus += serviceName + " host ID " + host + " failed to update to your current IP address. " + response + Environment.NewLine; } else { returnStatus += serviceName + " host ID " + host + " was successfully updated to point to your current IP address. " + response + Environment.NewLine; } } return returnStatus; } } } <file_sep>/src/WindowsFormsApplication1/Helpers/DynamixHelper.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using DynamixDNS.Classes; namespace DynamixDNS.Helpers { public static class DynamixHelper { public static string settingsFile = AppDomain.CurrentDomain.BaseDirectory + "dynamix.bin"; public static string endPointURL = "https://dynamix.run/api/public_api.php"; public static string serviceName = "Dynamix"; public static BinaryFormatter bformatter = new BinaryFormatter(); public static DynamixSettings LoadOptions(dyndnsServices dyndnsServices = null) { DynamixSettings settings = new DynamixSettings(); try { if (File.Exists(settingsFile)) { using (Stream stream = File.Open(settingsFile, FileMode.Open)) { settings = (DynamixSettings)bformatter.Deserialize(stream); } settings.Password = GenericHelper.DecodeFrom64(settings.Password); } } catch (Exception e) { Console.WriteLine(e); } if (dyndnsServices != null) { if (settings.Hosts.Any()) { dyndnsServices.hostsBoxDynamix.Items.Clear(); dyndnsServices.hostsBoxDynamix.Items.AddRange(settings.Hosts.Select(c => c).ToArray()); } dyndnsServices.enableDynamixCB.Checked = settings.Enabled; dyndnsServices.dynamix_user_key_TB.Text = settings.Password; } return settings; } public static string SaveOptions(DynamixSettings settings) { int errors = 0; string errorMessage = string.Empty; if (string.IsNullOrEmpty(settings.Password) && settings.Enabled) { errors++; errorMessage += "You cannot leave the Dynamix user key field blank!" + Environment.NewLine; } if (!settings.Hosts.Any() && settings.Enabled) { errors++; errorMessage += "There are no " + serviceName + " hosts to save!" + Environment.NewLine ; } if (errors == 0) { //serialize settings.Password = GenericHelper.EncodeTo64(settings.Password); using (Stream stream = File.Open(settingsFile, FileMode.Create)) { bformatter.Serialize(stream, settings); } } return errorMessage; } public static string RunUpdates(DynamixSettings settings, string IPAddress) { string returnStatus = ""; foreach (string host in settings.Hosts) { SubdomainDomain info = DomainHelper.getSubdomainDomainFromString(host); if (info != null && !string.IsNullOrEmpty(info.domain)) { string url = endPointURL + "?key=" + settings.Password + "&action=ddns&subaction=update"; url += (!string.IsNullOrEmpty(info.subdomain) ? "&subdomain=" + info.subdomain : ""); url += "&domain=" + info.domain + "&ip=" + IPAddress; string response = GenericHelper.MakeHTTPGETRequest(url); if (response == "1") { returnStatus += serviceName + " host " + host + " was successfully updated to your current IP address." + Environment.NewLine; } else if (response == "0") { returnStatus += serviceName + " host " + host + " failed to update to your current IP address." + Environment.NewLine; } else if (response.StartsWith("Exception")) { returnStatus += serviceName + " host " + host + " failed to update due to a system exception. " + response.Replace(Environment.NewLine, " ") + Environment.NewLine; } else if (response.StartsWith("error=")) { returnStatus += serviceName + " host " + host + " failed to update. " + response.Replace("error=", ""); } } } return returnStatus; } public static List<string> CurrentHosts(string accountKey) { List<string> hosts = new List<string>(); try { string url = endPointURL + "?action=ddns&subaction=getHosts&key=" + accountKey; string response = GenericHelper.MakeHTTPGETRequest(url); StringReader strReader = new StringReader(response); string line = string.Empty; while (!string.IsNullOrEmpty(line = strReader.ReadLine())) { hosts.Add(line); } } catch { } return hosts; } } } <file_sep>/src/WindowsFormsApplication1/Helpers/AppHelper.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using DynamixDNS.Classes; namespace DynamixDNS.Helpers { public static class AppHelper { public static string settingsFile = AppDomain.CurrentDomain.BaseDirectory + "appSettings.bin"; public static BinaryFormatter bformatter = new BinaryFormatter(); public static DynamixDNSSettings LoadOptions(options options = null) { DynamixDNSSettings settings = new DynamixDNSSettings(); try { if (File.Exists(settingsFile)) { using (Stream stream = File.Open(settingsFile, FileMode.Open)) { settings = (DynamixDNSSettings)bformatter.Deserialize(stream); } } } catch (Exception e) { Console.WriteLine(e); } if (options != null) { switch (settings.TimeIntervalMode) { case 1: default: options.timeSeconds.Checked = true; break; case 2: options.timeMinutes.Checked = true; break; case 3: options.timeHours.Checked = true; break; } options.intTimeInserted.Text = settings.TimeInterval.ToString(); options.autoStart.Checked = settings.AutoStart; switch (settings.IPService) { case 1: options.dynamix.Checked = true; break; case 2: options.grabIP.Checked = true; break; default: case 3: options.dinofly.Checked = true; break; } options.dynServicesBox.Checked = settings.RunDynamicServices; if (settings.ExternalScriptToRun.Any()) { options.scriptText.Text = String.Join(",", settings.ExternalScriptToRun); } } return settings; } public static string SaveOptions(options options) { string errorMessage = string.Empty; DynamixDNSSettings settings = new DynamixDNSSettings(); if (options.timeSeconds.Checked) { settings.TimeIntervalMode = 1; } else if (options.timeMinutes.Checked) { settings.TimeIntervalMode = 2; } else if (options.timeHours.Checked) { settings.TimeIntervalMode = 3; } else { settings.TimeInterval = 1; } if (!string.IsNullOrEmpty(options.intTimeInserted.Text) && GenericHelper.IsNumeric(options.intTimeInserted.Text)) { settings.TimeInterval = Convert.ToInt32(options.intTimeInserted.Text); if (settings.TimeInterval < 10 && settings.TimeIntervalMode == 1) { settings.TimeInterval = 10; options.intTimeInserted.Text = "10"; } } else { settings.TimeInterval = 60; } if (options.dynamix.Checked == true) { settings.IPService = 1; } else if (options.dinofly.Checked == true) { settings.IPService = 3; } else if (options.grabIP.Checked == true) { settings.IPService = 2; } else { settings.IPService = 1; } if (options.dynServicesBox.Checked) { settings.RunDynamicServices = true; } else { settings.RunDynamicServices = false; } if (!string.IsNullOrEmpty(options.scriptText.Text)) { settings.ExternalScriptToRun = options.scriptText.Text.Split(',').ToList(); } //serialize using (Stream stream = File.Open(settingsFile, FileMode.Create)) { bformatter.Serialize(stream, settings); } return errorMessage; } } } <file_sep>/src/WindowsFormsApplication1/phpExecutablePrompt.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace DynamixDNS { public partial class phpExecutablePrompt : Form { string PHPPath = ""; int success = 0; public phpExecutablePrompt() { InitializeComponent(); } private void browseButton_Click(object sender, EventArgs e) { DialogResult result = openPHPDialog.ShowDialog(); if (result == DialogResult.OK) { PHPPath = openPHPDialog.FileName; phpPathEXE.Text = PHPPath; } } private void okButton_Click(object sender, EventArgs e) { if (PHPPath != "" & PHPPath != null) { checkPath(); if (success == 1) { if (!File.Exists(mainDynamix.phpPathFile)) { FileStream fs = File.Open(mainDynamix.phpPathFile, FileMode.CreateNew); fs.Close(); using (StreamWriter outfile = new StreamWriter(mainDynamix.phpPathFile)) { outfile.Write(PHPPath); outfile.Close(); } } this.Close(); } else { MessageBox.Show("Error!", "The path you selected is invalid. The path must end with php.exe", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void checkPath() { if (PHPPath.Substring(PHPPath.LastIndexOf("\\") + 1) != "php.exe") { success = 0; } else { success = 1; } } private void cancelButton_Click(object sender, EventArgs e) { this.Close(); } internal string getPath() { if (PHPPath != "" & PHPPath != null) { return PHPPath; } else { return ""; } } } } <file_sep>/src/WindowsFormsApplication1/Classes/DDNSService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DynamixDNS.Classes { [Serializable] public class DDNSService { public DDNSService() { Hosts = new List<string>(); Enabled = false; } public string Login { get; set; } public string Password {get;set;} public bool Enabled { get; set; } public List<string> Hosts { get; set; } } } <file_sep>/src/WindowsFormsApplication1/Classes/NoIPDNSSettings.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DynamixDNS.Classes { [Serializable] public class NoIPDNSSettings : DDNSService { } } <file_sep>/src/WindowsFormsApplication1/Classes/AfraidDNSSettings.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using DynamixDNS.Helpers; namespace DynamixDNS.Classes { [Serializable] public class AfraidDNSSettings : DDNSService { public string HashedLogin { get { return GenericHelper.HashCode(Login + "|" + Password, new UTF8Encoding()); } } } } <file_sep>/src/WindowsFormsApplication1/Helpers/GenericHelper.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Security.Cryptography; using DynamixDNS.Classes; using System.Text.RegularExpressions; namespace DynamixDNS.Helpers { public static class GenericHelper { static GenericHelper() { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)3072; } public static string EncodeTo64(string toEncode) { if (!string.IsNullOrEmpty(toEncode)) { byte[] toEncodeAsBytes = ASCIIEncoding.ASCII.GetBytes(toEncode); string returnValue = System.Convert.ToBase64String(toEncodeAsBytes); return returnValue; } return String.Empty; } public static string DecodeFrom64(string encodedData) { if (!string.IsNullOrEmpty(encodedData)) { byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData); string returnValue = ASCIIEncoding.ASCII.GetString(encodedDataAsBytes); return returnValue; } return String.Empty; } public static string MakeHTTPGETRequest(string url, WebAuthentication auth = null) { try { string textResponse; WebRequest request; request = WebRequest.Create(url); request.Timeout = 5000; WebResponse response; if (auth != null) { HttpWebRequest webRequest = (HttpWebRequest)request; webRequest.Credentials = auth.CredCache; if (!string.IsNullOrEmpty(auth.Agent)) { webRequest.UserAgent = auth.Agent; } response = webRequest.GetResponse(); } else { response = request.GetResponse(); } StreamReader stream = new StreamReader(response.GetResponseStream()); textResponse = stream.ReadToEnd(); stream.Close(); response.Close(); if (!string.IsNullOrEmpty(textResponse)) { return textResponse; } } catch(Exception e) { return "Exception: " + e.ToString(); } return string.Empty; } public static bool IsNumeric(string str) { bool textIsNumeric = true; try { int.Parse(str); } catch { textIsNumeric = false; } return textIsNumeric; } public static string GetMD5Hash(string input) { // step 1, calculate MD5 hash from input MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); byte[] hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } return sb.ToString(); } public static string HashCode(string text, Encoding enc) { byte[] buffer = enc.GetBytes(text); SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider(); string hash = BitConverter.ToString( cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", ""); return hash; } public static bool IsValidEmail(string email) { try { var addr = new System.Net.Mail.MailAddress(email); return addr.Address == email; } catch { return false; } } public static string ParseIPv4Addr(string ip) { try { Regex ipCheck = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"); MatchCollection result = ipCheck.Matches(ip); ip = result[0].ToString(); } catch { Regex rgx = new Regex(@"[^0-9\.]"); ip = rgx.Replace(ip, ""); } return ip.ToLower(); } public static bool CheckIPValid(string strIP) { IPAddress result = null; return !String.IsNullOrEmpty(strIP) && IPAddress.TryParse(strIP, out result); } } } <file_sep>/src/WindowsFormsApplication1/Classes/XPertDNSSettings.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using DynamixDNS.Helpers; namespace DynamixDNS.Classes { [Serializable] public class XPertDNSSettings : DDNSService { public string MD5Password { get { return GenericHelper.GetMD5Hash(Password); } } } } <file_sep>/src/WindowsFormsApplication1/options.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Net; using DynamixDNS.Helpers; using DynamixDNS.Classes; namespace DynamixDNS { public partial class options : Form { string scriptPath = ""; DynamixDNSSettings appSettings = new DynamixDNSSettings(); public options() { InitializeComponent(); } private void saveSettings_Click(object sender, EventArgs e) { AppHelper.SaveOptions(this); this.Close(); } private void options_Load(object sender, EventArgs e) { getSavedOptions(); } private void getSavedOptions() { appSettings = AppHelper.LoadOptions(this); } private void browseScriptButton_Click(object sender, EventArgs e) { scriptPath = ""; DialogResult result = openFileDialog1.ShowDialog(); if (result == DialogResult.OK) { scriptPath = openFileDialog1.FileName; } if (File.Exists(scriptPath)) { if (!string.IsNullOrEmpty(scriptPath)) { if (!string.IsNullOrEmpty(scriptText.Text)) { scriptText.Text += "," + scriptPath; } else { scriptText.Text += scriptPath; } } } else { if (scriptPath != "" & scriptPath != null) { MessageBox.Show(scriptPath + " is not a valid file to run.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show("No script file was selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } scriptPath = ""; } } private void clearScripts_Click(object sender, EventArgs e) { scriptText.Text = ""; } private void configOtherDynDNS_Click(object sender, EventArgs e) { dyndnsServices configure = new dyndnsServices(); configure.ShowDialog(); } } } <file_sep>/src/WindowsFormsApplication1/Classes/WebAuthentication.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; namespace DynamixDNS.Classes { public class WebAuthentication { public WebAuthentication() { CredCache = new CredentialCache(); } public CredentialCache CredCache { get; set; } public string Agent { get; set; } } } <file_sep>/README.md # Dynamix DNS Client for Windows Official client for https://dynamix.run ## Dynamic DNS Dynamix (https://dynamix.run) offers free Dynamic DNS services with subdomain and custom domain support. Run your servers off of your residential internet connection. Have a dynamic IP address? No problem, you can still run servers without a static IP address. Be free and do what you want with your internet! <img src="https://dynamix.run/files/main.png" alt="Dynamix DNS Client for Windows Screenshot"> ## Synchronization The Dynamix DNS Client is our official open source synchronization tool for Windows. Dynamix DNS Client scans for IP address changes, runs external configurable applications when your IP address changes, and also uses our API to update your records minimizing any potential downtime an IP address change might cause. When an IP address change is detected, selected dynamic DNS hosts are updated to point to your latest IP address. Run this application on your Windows server. ## Services Supported Dynamix DNS Client supports and also integrates with the following Dynamic DNS service providers: * [Dynamix](https://dynamix.run) * [XpertDNS](http://www.xpertdns.com/) * [No-IP](https://www.noip.com/) * [Afraid FreeDNS](https://freedns.afraid.org/) ## Full Documentation [Dynamix DNS Client Documentation](https://dynamix.run/files/Dynamix%20DNS%20Client%20Documentation.pdf) ## Requirements * Any version of Windows XP and greater (including all server versions). * .NET 4.0 <file_sep>/src/WindowsFormsApplication1/dyndnsServices.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Net; using System.Security.Cryptography; using System.Text.RegularExpressions; using DynamixDNS.Classes; using DynamixDNS.Helpers; namespace DynamixDNS { public partial class dyndnsServices : Form { Encoding utf = new UTF8Encoding(); string saveSuccess = ""; int errorCount = 0, successCount = 0; DynamixSettings dynamixSettings = new DynamixSettings(); XPertDNSSettings xpertDNSSettings = new XPertDNSSettings(); AfraidDNSSettings afraidDNSSettings = new AfraidDNSSettings(); NoIPDNSSettings noIPSettings = new NoIPDNSSettings(); public dyndnsServices() { InitializeComponent(); } private void AddExpertDNS_Click(object sender, EventArgs e) { if (xpertHostIDField.Text != "" & xpertHostIDField.Text != null & !dynIDsXPertDNS.Items.Contains(xpertHostIDField.Text)) { double Num; bool isNum = double.TryParse(xpertHostIDField.Text, out Num); if (isNum) { // Adds entry to list box dynIDsXPertDNS.Items.Add(xpertHostIDField.Text); } else { MessageBox.Show("Host IDs must be numeric!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("No Host ID was entered, the host was entered improperly, or the host already exists in the item list!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } xpertHostIDField.Text = ""; xpertHostIDField.Focus(); } private void removeXPertDNS_Click(object sender, EventArgs e) { if (dynIDsXPertDNS.SelectedIndex != -1) { int toRemove = dynIDsXPertDNS.SelectedIndex; dynIDsXPertDNS.Items.RemoveAt(toRemove); } dynIDsXPertDNS.Focus(); } private void saveButton_Click(object sender, EventArgs e) { /* if(xpertEnable.Checked == false & (login4XPertDNS.Text != "" | XPertDNSPass.Text != "" | XPertDNSConfirmPass.Text != "" | dynIDsXPertDNS.Items.Count > 0)){ MessageBox.Show("Warning: Your updated settings will not save unless you enable this server!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } */ errorCount = 0; saveSuccess = ""; successCount = 0; saveAllSettings(); if (successCount > 0) { success Yes = new success(saveSuccess); Yes.Show(); } } private void saveXpertSettings() { XPertDNSSettings xSettings = new XPertDNSSettings(); xSettings.Enabled = xpertEnable.Checked; xSettings.Hosts = dynIDsXPertDNS.Items.Cast<String>().ToList(); xSettings.Login = login4XPertDNS.Text; var success = XpertDNSHelper.SaveOptions(xSettings, this); if (string.IsNullOrEmpty(success)) { successCount++; saveSuccess += "Your " + XpertDNSHelper.serviceName + " settings were successfully saved! \n"; } else { customError err = new customError("You have the following problems with your " + XpertDNSHelper.serviceName + " Settings!", success); err.intervalForTimer = 30000; err.Show(); errorCount++; } } public string CalculateMD5Hash(string input) { // step 1, calculate MD5 hash from input MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); byte[] hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } return sb.ToString(); } public string HashCode(string text, Encoding enc) { byte[] buffer = enc.GetBytes(text); SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider(); string hash = BitConverter.ToString( cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", ""); return hash; } private void dyndnsServices_Load(object sender, EventArgs e) { getXpertSettings(); getNoIPSettings(); getFreeDNSSettings(); getDynamixSettings(); } private void getXpertSettings() { xpertDNSSettings = XpertDNSHelper.LoadOptions(this); } private void getNoIPSettings() { noIPSettings = NoIPHelper.LoadOptions(this); } private void getFreeDNSSettings() { afraidDNSSettings = AfraidDNSHelper.LoadOptions(this); } private void getDynamixSettings() { dynamixSettings = DynamixHelper.LoadOptions(this); } private void noIPAdd_Click(object sender, EventArgs e) { if (noIPHost.Text != "" & noIPHost.Text != null & noIPHost.Text.IndexOf(".") != -1) { string filteredDomain = DomainHelper.filterDomain(noIPHost.Text.ToString()); if (DomainHelper.isValidSubdomainOrDomain(filteredDomain)) { if (!noIPHosts.Items.Contains(filteredDomain)) { // Adds entry to list box noIPHosts.Items.Add(filteredDomain); } else { MessageBox.Show("The host of " + filteredDomain + " already exists in the item list!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("The host of " + filteredDomain + " is invalid!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("No Host ID was entered or the host was entered improperly.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } noIPHost.Text = ""; noIPHost.Focus(); } private void noIPRemove_Click(object sender, EventArgs e) { if (noIPHosts.SelectedIndex != -1) { int toRemove = noIPHosts.SelectedIndex; noIPHosts.Items.RemoveAt(toRemove); } noIPHosts.Focus(); } private void saveDynamixSettings() { saveDynamixSettingsLogic(); } private void saveDynamixSettingsLogic() { // UI to class DynamixSettings updatedSettings = new DynamixSettings(); updatedSettings.Enabled = enableDynamixCB.Checked; updatedSettings.Password = <PASSWORD>; updatedSettings.Hosts = hostsBoxDynamix.Items.Cast<String>().ToList(); // Save the options using our static class string result = DynamixHelper.SaveOptions(updatedSettings); // Display any errors if (result != string.Empty) { customError err = new customError("You have the following problems with your Dynamix settings!", result); err.intervalForTimer = 30000; err.Show(); errorCount++; } else { successCount++; saveSuccess += "Your " + DynamixHelper.serviceName + " settings were successfully saved! \n"; } } private void saveNoIPSettings() { NoIPDNSSettings noIPSettings = new NoIPDNSSettings(); noIPSettings.Enabled = noIPEnabled.Checked; noIPSettings.Hosts = noIPHosts.Items.Cast<String>().ToList(); noIPSettings.Login = noIPLogin.Text; string result = NoIPHelper.SaveOptions(noIPSettings, this); if (result != string.Empty) { customError err = new customError("You have the following problems with your " + NoIPHelper.serviceName + " settings!", result); err.intervalForTimer = 30000; err.Show(); errorCount++; } else { successCount++; saveSuccess += "Your " + NoIPHelper.serviceName + " settings were successfully saved! \n"; } } private void saveFreeDNSSettings() { AfraidDNSSettings aSettings = new AfraidDNSSettings(); aSettings.Enabled = freeDNSEnable.Checked; aSettings.Hosts = freeDNSHosts.Items.Cast<String>().ToList(); aSettings.Login = freeDNSLogin.Text; var success = AfraidDNSHelper.SaveOptions(aSettings, this); if (string.IsNullOrEmpty(success)) { successCount++; saveSuccess += "Your " + AfraidDNSHelper.serviceName + " settings were successfully saved! \n"; } else { customError err = new customError("You have the following problems with your " + AfraidDNSHelper.serviceName + " Settings!", success); err.intervalForTimer = 30000; err.Show(); errorCount++; } } private void cancelButton_Click(object sender, EventArgs e) { this.Close(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { errorCount = 0; saveSuccess = ""; successCount = 0; saveAllSettings(); if (successCount > 0) { success Yes = new success(saveSuccess); Yes.Show(); } } private void saveAllSettings() { saveXpertSettings(); saveNoIPSettings(); saveFreeDNSSettings(); saveDynamixSettings(); } private void retreiveHostsButton_Click(object sender, EventArgs e) { AfraidDNSSettings temp = new AfraidDNSSettings(); temp.Login = freeDNSLogin.Text; temp.Password = <PASSWORD>; var hosts = AfraidDNSHelper.CurrentHosts(temp); if (hosts.Any()) { freeDNSHosts.Items.Clear(); foreach (var host in hosts) { freeDNSHosts.Items.Add(host.entry); } } else { MessageBox.Show("Failed to retrieve hosts from " + AfraidDNSHelper.serviceName + "! Please make sure you've entered your login and password." + Environment.NewLine + Environment.NewLine + AfraidDNSHelper.errorMessage, "Generic Failure", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void freeDNSRemove_Click_1(object sender, EventArgs e) { if (freeDNSHosts.SelectedIndex != -1) { freeDNSHosts.Items.RemoveAt(freeDNSHosts.SelectedIndex); } freeDNSHosts.Focus(); } private void removeDynamixHost_Click(object sender, EventArgs e) { if (hostsBoxDynamix.SelectedIndex != -1) { int toRemove = hostsBoxDynamix.SelectedIndex; hostsBoxDynamix.Items.RemoveAt(toRemove); } hostsBoxDynamix.Focus(); } private void retrieveDynamixHostsButton_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(dynamix_user_key_TB.Text)) { var hosts = DynamixHelper.CurrentHosts(dynamix_user_key_TB.Text); if (hosts.Any()) { hostsBoxDynamix.Items.Clear(); foreach (var host in hosts) { hostsBoxDynamix.Items.Add(host); } } else { MessageBox.Show("Failed to retrieve " + DynamixHelper.serviceName + " hosts.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Enter your account user key first before attempting to retrieve hosts.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } <file_sep>/src/WindowsFormsApplication1/Classes/SubdomainDomain.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DynamixDNS.Classes { public class SubdomainDomain { public string subdomain { get; set; } public string domain { get; set; } public string fullHost { get { return subdomain + "." + domain; } } } } <file_sep>/src/WindowsFormsApplication1/mainDynamix.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Net; using System.Diagnostics; using System.Text.RegularExpressions; using DynamixDNS.Classes; using DynamixDNS.Helpers; namespace DynamixDNS { public partial class mainDynamix : Form { string IPAddress = "", oldIP, urlForIPCheck = "", dynamixStartupEntryName = "Dynamix DNS Client.lnk"; public string phpPath = ""; DynamixSettings dynamixSettings = new DynamixSettings(); DynamixDNSSettings appSettings = new DynamixDNSSettings(); XPertDNSSettings XpertDNSSettings = new XPertDNSSettings(); AfraidDNSSettings afraidDNSSettings = new AfraidDNSSettings(); NoIPDNSSettings noIPDNSSettings = new NoIPDNSSettings(); int seconds = 0, minutes = 0, hours = 0; public static string oldIPFile = AppDomain.CurrentDomain.BaseDirectory + "oldip.txt"; public static string phpPathFile = AppDomain.CurrentDomain.BaseDirectory + "phpPath.txt"; public mainDynamix() { InitializeComponent(); ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)3072; } private void Dynamix_Load(object sender, EventArgs e) { checkOptionsExist(); // Getting External IP IPAddress = getExternalIP(); if (!string.IsNullOrEmpty(IPAddress)) { currentIP.Text = IPAddress; updateIP(); } } private string getExternalIP() { try { if (string.IsNullOrEmpty(urlForIPCheck)) { urlForIPCheck = "https://dynamix.run/ip.php"; } var response = GenericHelper.MakeHTTPGETRequest(urlForIPCheck); //Search for the ip in the html int first = response.IndexOf("Address: ") + 9; int last = response.LastIndexOf("</body>"); if (first != -1 && last != -1) { response = response.Substring(first, last - first); } response = GenericHelper.ParseIPv4Addr(response); //Write the IP to oldip.txt if (!string.IsNullOrEmpty(response) && GenericHelper.CheckIPValid(response)) { if (!File.Exists(oldIPFile)) { writeOldIP(response); oldIP = response; } else { oldIP = loadOldIP(); } currentIP.Text = response; } resetTimeLabels(); return response; } catch { resetTimeLabels(); customError unableToConnect = new customError("Unable to determine your external IP address.", "Unable to contact " + urlForIPCheck + "\nA firewall has blocked the connection!\nYou have no connection to the internet!"); if (timer1.Enabled == true) { if (timer1.Interval > 10000) { unableToConnect.intervalForTimer = timer1.Interval; } else { unableToConnect.intervalForTimer = 10000; } } else { unableToConnect.intervalForTimer = 10000; } unableToConnect.Show(); //MessageBox.Show(" \n\tPossible causes:\n\t No internet connection\n\t DynDns IP service down.", "Error Determining IP", MessageBoxButtons.OK, MessageBoxIcon.Error); return ""; } } private void scanButton_Click(object sender, EventArgs e) { startScanning(); } private string loadOldIP() { if (File.Exists(oldIPFile)) { return File.ReadAllText(oldIPFile); } return string.Empty; } private void writeOldIP(string IP) { File.WriteAllText(oldIPFile, IP); } private void updateIP() { if (oldIP != IPAddress && GenericHelper.CheckIPValid(IPAddress) && GenericHelper.CheckIPValid(oldIP)) { stopScanningInterval(); // Run configured external applications for when the IP address changes and pass in the parameters runExternalApps(); // Run IP updating services runInternetServices(); writeOldIP(IPAddress); oldIPLabel.Text = oldIP; oldIPLabel.Visible = true; oldIPLabelText.Visible = true; // Restart the scanning startScanning(); } } private void runExternalApps() { if (appSettings.ExternalScriptToRun.Any()) { string errorsForScripts = "", successesForScripts = ""; foreach (string prog in appSettings.ExternalScriptToRun) { // Add the positonal parameters // Send oldIP and newIP values for to all executables string parameters = " " + oldIP + " " + IPAddress; string extension = ""; if (File.Exists(prog)) { // Check and see if the program has a valid extension. If it is, run it... if not, show error! if (prog.LastIndexOf('.') == -1) { extension = "NO_EXTENSION"; } else { extension = prog.Substring(prog.LastIndexOf('.')); } switch (extension) { case ".php": // Add the positonal parameters // Send oldIP and newIP values for to all executables string runPHPProg = "\"" + prog + "\"" + parameters; // phpPath will not be set to "" if they were prompted in the past for a PHP path since it didn't exist where it was supposed to be (perhaps no installation of Dynamix DNS). if (phpPath != "") { processRun(phpPath, runPHPProg); successesForScripts += prog + " ran successfully!\n"; } else { phpExecutablePrompt phpNew = new phpExecutablePrompt(); if (Application.OpenForms.OfType<phpExecutablePrompt>().Count() > 0) { } else { phpNew.ShowDialog(); } string returnedPath = phpNew.getPath(); phpPath = returnedPath; if (returnedPath != "") { processRun(returnedPath, runPHPProg); successesForScripts += prog + " ran successfully!\n"; } else { errorsForScripts += "Unable to find the php.exe executable on your system! Until the path is entered, you cannot run .php scripts!"; } } break; case ".exe": processRun(prog, parameters); successesForScripts += prog + " ran successfully!\n"; break; case ".bat": processRun(prog, parameters); successesForScripts += prog + " ran successfully!\n"; break; case ".jar": processRun(prog, parameters); successesForScripts += prog + " ran successfully!\n"; break; default: errorsForScripts += prog + " has an invalid extension of " + extension + "! Only .exe, .php, .bat, and .jar are allowed!\n"; break; } } else { errorsForScripts += prog + " doesn't even exist!"; } } if (errorsForScripts != "") { customError newError = new customError("The following scripts did not run because:", errorsForScripts); newError.Show(); //MessageBox.Show(errorsForScripts, "Error Running Scripts", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (successesForScripts != "") { success scriptsHaveRan = new success(successesForScripts); scriptsHaveRan.Show(); } } } private void timer1_Tick(object sender, EventArgs e) { IPAddress = getExternalIP(); if (!string.IsNullOrEmpty(IPAddress)) { updateIP(); } } private void optiToolStripMenuItem_Click(object sender, EventArgs e) { stopScanningInterval(); options showOptions = new options(); showOptions.ShowDialog(); getSavedOptions(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Environment.Exit(0); } private void timer2_Tick(object sender, EventArgs e) { updateTimerLabels(); } private void updateTimerLabels() { seconds = int.Parse(secondsLabel.Text); seconds++; if (seconds == 60) { minutes++; seconds = 0; } if (minutes == 60) { hours++; minutes = 0; } string secondsAdd, minutesAdd, hoursAdd; if (seconds < 10) { secondsAdd = "0" + seconds.ToString(); } else { secondsAdd = seconds.ToString(); } if (minutes < 10) { minutesAdd = "0" + minutes.ToString(); } else { minutesAdd = minutes.ToString(); } if (hours < 10) { hoursAdd = "0" + hours.ToString(); } else { hoursAdd = hours.ToString(); } secondsLabel.Text = secondsAdd; minutesLabel.Text = minutesAdd; hoursLabel.Text = hoursAdd; } private void stopScanButton_Click(object sender, EventArgs e) { stopScanningInterval(); } private void resetTimeLabels() { secondsLabel.Text = "00"; minutesLabel.Text = "00"; hoursLabel.Text = "00"; seconds = 0; minutes = 0; hours = 0; } private void stopScanningInterval() { if (timer1.Enabled != false) { timer1.Enabled = false; } if (timer2.Enabled != false) { timer2.Enabled = false; } resetTimeLabels(); scanButton.Visible = true; stopScanButton.Visible = false; timer1.Stop(); timer2.Stop(); } private void getSavedOptions() { appSettings = AppHelper.LoadOptions(); // Reading Saved Options: switch (appSettings.TimeIntervalMode) { default: case 1: timer1.Interval = appSettings.TimeInterval * 1000; break; case 2: timer1.Interval = appSettings.TimeInterval * 1000 * 60; break; case 3: timer1.Interval = appSettings.TimeInterval * 1000 * 3600; break; } if (appSettings.AutoStart) { timer1.Enabled = true; timer2.Enabled = true; scanButton.Visible = false; stopScanButton.Visible = true; } else { timer1.Enabled = false; timer2.Enabled = false; scanButton.Visible = true; stopScanButton.Visible = false; } switch (appSettings.IPService) { case 1: urlForIPCheck = "https://dynamix.run/ip.php"; break; case 3: urlForIPCheck = "http://dinofly.com/misc/ipcheck.php"; break; case 2: urlForIPCheck = "http://grabip.tk"; break; default: urlForIPCheck = "https://dynamix.run/ip.php"; break; } if (File.Exists(phpPathFile)) { phpPath = File.ReadAllText(phpPathFile); } if (appSettings.RunDynamicServices) { XpertDNSSettings = XpertDNSHelper.LoadOptions(); dynamixSettings = DynamixHelper.LoadOptions(); afraidDNSSettings = AfraidDNSHelper.LoadOptions(); noIPDNSSettings = NoIPHelper.LoadOptions(); } } private void addToStartupProgramsToolStripMenuItem_Click(object sender, EventArgs e) { addToStartUp(); } private void addToStartUp() { string pathToStartUp = Environment.GetFolderPath(Environment.SpecialFolder.Startup); if (!File.Exists(pathToStartUp + "\\" + dynamixStartupEntryName)) { using (ShellLink shortcut = new ShellLink()) { shortcut.Target = Application.ExecutablePath; shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath); shortcut.Description = "Dynamix DNS Client"; shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal; //MessageBox.Show(pathToStartUp, "info"); shortcut.Save(pathToStartUp + "\\" + dynamixStartupEntryName); } success StartUpCreated = new success("A startup entry for the Dynamix DNS Client was successfully created.\n\nDynamix DNS Client will start with Windows!"); StartUpCreated.ShowDialog(); } else { MessageBox.Show("The startup entry already exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void removeFromStartUp() { string pathToStartUp = Environment.GetFolderPath(Environment.SpecialFolder.Startup); if (File.Exists(pathToStartUp + "\\" + dynamixStartupEntryName)) { File.Delete(pathToStartUp + "\\" + dynamixStartupEntryName); success StartUpRemoved = new success("The startup entry for the Dynamix DNS Client was successfully deleted.\n\nDynamix DNS Client will NOT start with Windows!"); StartUpRemoved.ShowDialog(); } else { MessageBox.Show("There is no startup entry to delete!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void removeFromStartupProgramsToolStripMenuItem_Click(object sender, EventArgs e) { removeFromStartUp(); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { about showAbout = new about(); showAbout.ShowDialog(); } private void processRun(string process, string parameter) { try { ProcessStartInfo startBindSync = new ProcessStartInfo(); startBindSync.FileName = (!process.StartsWith("\"") ? "\"" + process + "\"" : process); startBindSync.Arguments = parameter; string oldWorkingDirectory = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\") + 1); string ranFromDirectory = process.Substring(0, process.LastIndexOf("\\") + 1); startBindSync.WorkingDirectory = ranFromDirectory; Process.Start(startBindSync); // Had to reset the working directory to the old directory due to a C# bug that starts writing settings into the working directory of the process run... startBindSync.WorkingDirectory = oldWorkingDirectory; } catch(Exception e) { MessageBox.Show("Unable to run script " + process + Environment.NewLine + e, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void runInternetServices() { runXPertDNSUpdate(); runDynamixDNSUpdate(); runAfraidDNSUpdate(); runNoIPUpdate(); } private void runDynamixDNSUpdate() { if (dynamixSettings.Hosts.Any() && !string.IsNullOrEmpty(dynamixSettings.Password) && dynamixSettings.Enabled) { string messages = DynamixHelper.RunUpdates(dynamixSettings, IPAddress); parseMessagesAndShowResults(messages); } } private void runXPertDNSUpdate() { if (XpertDNSSettings.Hosts.Any() && !string.IsNullOrEmpty(XpertDNSSettings.Login) && !string.IsNullOrEmpty(XpertDNSSettings.Password) && XpertDNSSettings.Enabled) { string messages = XpertDNSHelper.RunUpdates(XpertDNSSettings, IPAddress); parseMessagesAndShowResults(messages); } } private void runAfraidDNSUpdate() { if (afraidDNSSettings.Hosts.Any() && !string.IsNullOrEmpty(afraidDNSSettings.Login) && !string.IsNullOrEmpty(afraidDNSSettings.Password) && afraidDNSSettings.Enabled) { string messages = AfraidDNSHelper.RunUpdates(afraidDNSSettings); parseMessagesAndShowResults(messages); } } private void runNoIPUpdate() { if (noIPDNSSettings.Hosts.Any() && !string.IsNullOrEmpty(noIPDNSSettings.Login) && !string.IsNullOrEmpty(noIPDNSSettings.Password) && noIPDNSSettings.Enabled) { string messages = NoIPHelper.RunUpdates(noIPDNSSettings, IPAddress); parseMessagesAndShowResults(messages); } } private void parseMessagesAndShowResults(string messages) { string success = string.Empty; string error = string.Empty; string[] finalMessages = messages.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (string mess in finalMessages) { if (mess.IndexOf("failed") == -1) { success += mess + Environment.NewLine; } else { error += mess + Environment.NewLine; } } if (error != "" & error != null) { customError showError = new customError("Error Synchronizing to Service", error); showError.intervalForTimer = 60000; showError.Show(); } if (success != "" & success != null) { success synced = new success(success); synced.Show(); } } private void startScanning() { scanButton.Visible = false; stopScanButton.Visible = true; if (timer1.Enabled != true) { timer1.Enabled = true; } if (timer2.Enabled != true) { timer2.Enabled = true; } timer1.Start(); timer2.Start(); } private void checkOptionsExist() { if (!File.Exists(AppHelper.settingsFile)) { MessageBox.Show("No options have been set. Please set them now.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); stopScanningInterval(); options showOptions = new options(); showOptions.ShowDialog(); } getSavedOptions(); } } } <file_sep>/src/WindowsFormsApplication1/customError.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace DynamixDNS { public partial class customError : Form { // default 10 seconds. int intervalTimer = 10000; string errorMessage = ""; public int intervalForTimer { get { return intervalTimer; } set { intervalTimer = value; } } public customError(string message) { InitializeComponent(); errorMessage = message; } public customError(string message, string boxMessage) { InitializeComponent(); errorMessage = message; errorBox.Text = boxMessage; } private void connectionError_Load(object sender, EventArgs e) { //MessageBox.Show(intervalTimer.ToString()); timer1.Interval = intervalTimer - 3000; timer1.Enabled = true; mainError.Text = errorMessage; } private void timer1_Tick(object sender, EventArgs e) { this.Close(); } private void okButton_Click(object sender, EventArgs e) { this.Close(); } } } <file_sep>/src/WindowsFormsApplication1/Helpers/AfraidDNSHelper.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using DynamixDNS.Classes; namespace DynamixDNS.Helpers { public static class AfraidDNSHelper { public static string settingsFile = AppDomain.CurrentDomain.BaseDirectory + "afraid.bin"; public static string endPointURL = "http://freedns.afraid.org/api/?action=getdyndns&sha="; public static string serviceName = "FreeDNS Afraid"; public static BinaryFormatter bformatter = new BinaryFormatter(); public static string errorMessage = string.Empty; public static AfraidDNSSettings LoadOptions(dyndnsServices dyndnsServices = null) { AfraidDNSSettings settings = new AfraidDNSSettings(); try { if (File.Exists(settingsFile)) { using (Stream stream = File.Open(settingsFile, FileMode.Open)) { settings = (AfraidDNSSettings)bformatter.Deserialize(stream); } settings.Password = <PASSWORD>Helper.DecodeFrom64(settings.Password); } } catch (Exception e) { Console.WriteLine(e); } if (dyndnsServices != null) { dyndnsServices.freeDNSPass.Text = settings.Password; dyndnsServices.freeDNSPassVerify.Text = settings.Password; dyndnsServices.freeDNSEnable.Checked = settings.Enabled; dyndnsServices.freeDNSHosts.Items.Clear(); if (settings.Hosts.Any()) { dyndnsServices.freeDNSHosts.Items.AddRange(settings.Hosts.ToArray()); } dyndnsServices.freeDNSLogin.Text = settings.Login; } return settings; } public static string SaveOptions(AfraidDNSSettings settings, dyndnsServices dyndnsServices = null) { int errors = 0; string errorMessage = string.Empty; if (dyndnsServices != null && settings.Enabled) { // Perform validation if (string.IsNullOrEmpty(dyndnsServices.freeDNSLogin.Text)) { errors++; errorMessage += "You must provide your " + serviceName + " login!" + Environment.NewLine; } if (dyndnsServices.freeDNSPass.Text != dyndnsServices.freeDNSPassVerify.Text) { errors++; errorMessage += "The " + serviceName + " passwords do not match!" + Environment.NewLine; } else { if (!string.IsNullOrEmpty(dyndnsServices.freeDNSPass.Text) && !string.IsNullOrEmpty(dyndnsServices.freeDNSPass.Text)) { settings.Password = dyndnsServices.freeDNSPass.Text; } else { errors++; errorMessage += "You must provide your " + serviceName + " password and confirm the password." + Environment.NewLine; } } if (dyndnsServices.freeDNSHosts.Items.Count <= 0) { errors++; errorMessage += "There are no " + serviceName + " hosts to save!" + Environment.NewLine; } } if (errors == 0) { //serialize settings.Password = GenericHelper.EncodeTo64(settings.Password); using (Stream stream = File.Open(settingsFile, FileMode.Create)) { bformatter.Serialize(stream, settings); } } return errorMessage; } public static string RunUpdates(AfraidDNSSettings settings) { string returnStatus = ""; List<FreeDNSURL> hostsToUpdateURLs = CurrentHosts(settings); if (hostsToUpdateURLs.Any()) { foreach (FreeDNSURL url in hostsToUpdateURLs) { string response = GenericHelper.MakeHTTPGETRequest(url.url); if (response.StartsWith("Exception")) { returnStatus += serviceName + " host " + url.entry + " failed to update due to a system exception. " + response.Replace(Environment.NewLine, " ") + Environment.NewLine; } else if (response.StartsWith("ERROR")) { returnStatus += serviceName + " host " + url.entry + " failed to update to your current IP address. " + response + Environment.NewLine; } else { returnStatus += serviceName + " host " + url.entry + " was successfully updated to point to your current IP address. " + response + Environment.NewLine; } } } return returnStatus; } public static List<FreeDNSURL> CurrentHosts(AfraidDNSSettings settings) { List<FreeDNSURL> updateURLs = new List<FreeDNSURL>(); try { string url = endPointURL + settings.HashedLogin; string response = GenericHelper.MakeHTTPGETRequest(url); StringReader strReader = new StringReader(response); string line = string.Empty; while (!string.IsNullOrEmpty(line = strReader.ReadLine())) { string[] parts = line.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 3) { if (settings == null || !settings.Hosts.Any() || settings.Hosts.Contains(parts[0])) { updateURLs.Add(new FreeDNSURL() { url = parts[2], entry = parts[0] }); } } } } catch(Exception e) { errorMessage = e.ToString(); } return updateURLs; } } public class FreeDNSURL { public string url { get; set; } public string entry { get; set; } } } <file_sep>/src/WindowsFormsApplication1/Classes/DynamixDNSSettings.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DynamixDNS.Classes { [Serializable] public class DynamixDNSSettings { public DynamixDNSSettings() { TimeIntervalMode = 1; TimeInterval = 120; AutoStart = true; IPService = 1; RunDynamicServices = true; ExternalScriptToRun = new List<string>(); } public int TimeIntervalMode { get; set; } public int TimeInterval { get; set; } public bool AutoStart { get; set; } public int IPService { get; set; } public bool RunDynamicServices { get; set; } public List<string> ExternalScriptToRun { get; set; } } } <file_sep>/src/WindowsFormsApplication1/Helpers/DomainHelper.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using DynamixDNS.Classes; namespace DynamixDNS.Helpers { public static class DomainHelper { public static string filterDomain(string filtered) { // Check for https:// if (filtered.IndexOf("https://") != -1) { filtered = filtered.Replace("https://", ""); } // Check for http:// if (filtered.IndexOf("http://") != -1) { filtered = filtered.Replace("http://", ""); } filtered = filtered.ToLower(); Regex rgx = new Regex(@"[^a-z0-9\-\.]"); filtered = rgx.Replace(filtered, ""); return filtered.ToLower(); } public static bool isValidSubdomainOrDomain(string filtered) { string[] parts = filtered.Split(new string[]{"."}, StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 2 || parts.Length > 3) { return false; } if (parts[0].Length > 63) { return false; } if (parts[1].Length > 63) { return false; } return true; } public static SubdomainDomain getSubdomainDomainFromString(string str) { SubdomainDomain subDom = new SubdomainDomain(); string[] parts = str.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 3) { subDom.subdomain = parts[0]; subDom.domain = parts[1] + "." + parts[2]; } else if (parts.Length == 2) { subDom.subdomain = string.Empty; subDom.domain = parts[0] + "." + parts[1]; } else { return null; } return subDom; } } } <file_sep>/src/WindowsFormsApplication1/Helpers/NoIPHelper.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using DynamixDNS.Classes; using System.Net; namespace DynamixDNS.Helpers { public static class NoIPHelper { public static string settingsFile = AppDomain.CurrentDomain.BaseDirectory + "noip.bin"; public static string endPointURL = "http://dynupdate.no-ip.com/nic/update?hostname="; public static string serviceName = "No-IP"; public static BinaryFormatter bformatter = new BinaryFormatter(); public static NoIPDNSSettings LoadOptions(dyndnsServices dyndnsServices = null) { NoIPDNSSettings settings = new NoIPDNSSettings(); try { if (File.Exists(settingsFile)) { using (Stream stream = File.Open(settingsFile, FileMode.Open)) { settings = (NoIPDNSSettings)bformatter.Deserialize(stream); } settings.Password = GenericHelper.DecodeFrom64(settings.Password); } } catch (Exception e) { Console.WriteLine(e); } if (dyndnsServices != null) { dyndnsServices.noIPPass.Text = settings.Password; dyndnsServices.noIPPassVerify.Text = settings.Password; dyndnsServices.noIPEnabled.Checked = settings.Enabled; dyndnsServices.noIPHosts.Items.Clear(); if (settings.Hosts.Any()) { dyndnsServices.noIPHosts.Items.AddRange(settings.Hosts.ToArray()); } dyndnsServices.noIPLogin.Text = settings.Login; } return settings; } public static string SaveOptions(NoIPDNSSettings settings, dyndnsServices dyndnsServices = null) { int errors = 0; string errorMessage = string.Empty; if (dyndnsServices != null && settings.Enabled) { // Perform validation if (string.IsNullOrEmpty(dyndnsServices.noIPLogin.Text)) { errors++; errorMessage += "You must provide your " + serviceName + " login email address!" + Environment.NewLine; } else { if (!GenericHelper.IsValidEmail(dyndnsServices.noIPLogin.Text)) { errors++; errorMessage += "You must provide a valid " + serviceName + " login email address!" + Environment.NewLine; } } if (dyndnsServices.noIPPass.Text != dyndnsServices.noIPPassVerify.Text) { errors++; errorMessage += "The " + serviceName + " passwords do not match!" + Environment.NewLine; } else { if (!string.IsNullOrEmpty(dyndnsServices.noIPPass.Text) && !string.IsNullOrEmpty(dyndnsServices.noIPPassVerify.Text)) { settings.Password = dyndnsServices.noIPPass.Text; } else { errors++; errorMessage += "You must provide your " + serviceName + " password and confirm the password." + Environment.NewLine; } } if (dyndnsServices.noIPHosts.Items.Count <= 0) { errors++; errorMessage += "There are no " + serviceName + " hosts to save!" + Environment.NewLine; } } if (errors == 0) { //serialize settings.Password = GenericHelper.EncodeTo64(settings.Password); using (Stream stream = File.Open(settingsFile, FileMode.Create)) { bformatter.Serialize(stream, settings); } } return errorMessage; } public static string RunUpdates(NoIPDNSSettings settings, string IPAddress) { string returnStatus = ""; foreach (string host in settings.Hosts) { string url = endPointURL + host + "&myip=" + IPAddress; WebAuthentication auth = new WebAuthentication(); auth.CredCache.Add(new Uri(url), "Basic", new NetworkCredential(settings.Login, settings.Password)); auth.Agent = "Dynamix DNS Update Client/172.16.58.3 <EMAIL> - dynamix.run"; string response = GenericHelper.MakeHTTPGETRequest(url, auth); if (response.StartsWith("Exception")) { returnStatus += serviceName + " host " + host + " failed to update due to a system exception. " + response.Replace(Environment.NewLine, " ") + Environment.NewLine; } else if (response.Trim() != ("good " + IPAddress) && !response.Trim().StartsWith("good " + IPAddress)) { returnStatus += serviceName + " host " + host + " failed to update to your current IP address. " + response + Environment.NewLine; } else { returnStatus += serviceName + " host " + host + " was successfully updated to your current IP address. " + response + Environment.NewLine; } } return returnStatus; } } }
9316c4f3d513f0327a823795f67d429958a1b69e
[ "Markdown", "C#" ]
21
C#
earnolmartin/Dynamix-DNS-Client-for-Windows
23847860d62e6e8c8d5132dfb998e8f8a802d5ca
4f36e36d78149245280e25b70f5da2d3d10c7e1f
refs/heads/master
<repo_name>XinFinOrg/gnosis-safe-client-gateway<file_sep>/src/routes/balances.rs use crate::cache::cache_operations::CacheResponse; use crate::config::balances_cache_duration; use crate::services::balances::*; use crate::utils::context::Context; use crate::utils::errors::ApiResult; use rocket::response::content; #[get("/v1/safes/<safe_address>/balances/<fiat>?<trusted>&<exclude_spam>")] pub async fn get_balances( context: Context<'_>, safe_address: String, fiat: String, trusted: Option<bool>, exclude_spam: Option<bool>, ) -> ApiResult<content::Json<String>> { CacheResponse::new(context.uri()) .duration(balances_cache_duration()) .resp_generator(|| { balances( &context, safe_address.as_str(), fiat.as_str(), trusted.unwrap_or(false), exclude_spam.unwrap_or(true), ) }) .execute(context.cache()) .await } #[get("/v1/balances/supported-fiat-codes")] pub async fn get_supported_fiat(context: Context<'_>) -> ApiResult<content::Json<String>> { CacheResponse::new(context.uri()) .resp_generator(|| fiat_codes(&context)) .execute(context.cache()) .await } <file_sep>/src/routes/hooks.rs use crate::cache::cache_operations::{Invalidate, InvalidationPattern}; use crate::config::webhook_token; use crate::models::backend::webhooks::Payload; use crate::services::hooks::invalidate_caches; use crate::utils::context::Context; use crate::utils::errors::ApiResult; use rocket_contrib::json::Json; #[post("/v1/hook/update/<token>", format = "json", data = "<update>")] pub fn update(context: Context<'_>, token: String, update: Json<Payload>) -> ApiResult<()> { if token != webhook_token() { bail!("Invalid token"); } invalidate_caches(context.cache(), &update) } #[get("/v1/flush_all/<token>")] pub fn flush_all(context: Context<'_>, token: String) -> ApiResult<()> { if token != webhook_token() { bail!("Invalid token"); } Invalidate::new(InvalidationPattern::FlushAll).execute(context.cache()); Ok(()) } #[get("/v1/flush_tokens/<token>")] pub fn flush_token_info(context: Context, token: String) -> ApiResult<()> { if token != webhook_token() { bail!("Invalid token"); } Invalidate::new(InvalidationPattern::Tokens).execute(context.cache()); Ok(()) } <file_sep>/src/models/service/transactions/details.rs use super::*; use crate::models::commons::{DataDecoded, Operation}; use crate::providers::info::{SafeAppInfo, TokenInfo}; use serde::Serialize; use std::collections::HashMap; #[derive(Serialize, Debug, PartialEq)] #[serde(rename_all = "camelCase")] pub struct TransactionDetails { pub executed_at: Option<i64>, pub tx_status: TransactionStatus, pub tx_info: TransactionInfo, pub tx_data: Option<TransactionData>, pub detailed_execution_info: Option<DetailedExecutionInfo>, pub tx_hash: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub safe_app_info: Option<SafeAppInfo>, } #[derive(Serialize, Debug, PartialEq)] #[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")] pub enum DetailedExecutionInfo { Multisig(MultisigExecutionDetails), Module(ModuleExecutionDetails), } #[derive(Serialize, Debug, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MultisigExecutionDetails { pub submitted_at: i64, pub nonce: u64, pub safe_tx_gas: usize, pub base_gas: usize, pub gas_price: String, pub gas_token: String, pub refund_receiver: String, pub safe_tx_hash: String, pub executor: Option<String>, pub signers: Vec<String>, pub confirmations_required: u64, pub confirmations: Vec<MultisigConfirmation>, #[serde(skip_serializing_if = "Option::is_none")] pub rejectors: Option<Vec<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub gas_token_info: Option<TokenInfo>, } #[derive(Serialize, Debug, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MultisigConfirmation { pub signer: String, pub signature: Option<String>, pub submitted_at: i64, } #[derive(Serialize, Debug, PartialEq)] #[serde(rename_all = "camelCase")] pub struct ModuleExecutionDetails { pub address: String, } #[derive(Serialize, Debug, PartialEq)] #[serde(rename_all = "camelCase")] pub struct TransactionData { pub hex_data: Option<String>, pub data_decoded: Option<DataDecoded>, pub to: String, pub value: Option<String>, pub operation: Operation, #[serde(skip_serializing_if = "Option::is_none")] pub address_info_index: Option<HashMap<String, AddressInfo>>, } <file_sep>/src/routes/collectibles.rs use crate::cache::cache_operations::RequestCached; use crate::config::{base_transaction_service_url, collectibles_request_timeout}; use crate::utils::context::Context; use crate::utils::errors::ApiResult; use rocket::response::content; #[get("/v1/safes/<safe_address>/collectibles?<trusted>&<exclude_spam>")] pub async fn list( context: Context<'_>, safe_address: String, trusted: Option<bool>, exclude_spam: Option<bool>, ) -> ApiResult<content::Json<String>> { let url = format!( "{}/v1/safes/{}/collectibles/?trusted={}&exclude_spam={}", base_transaction_service_url(), safe_address, trusted.unwrap_or(false), exclude_spam.unwrap_or(true) ); Ok(content::Json( RequestCached::new(url) .request_timeout(collectibles_request_timeout()) .execute(context.client(), context.cache()) .await?, )) } <file_sep>/src/models/mod.rs pub mod backend; pub mod commons; pub mod converters; pub mod service; #[cfg(test)] mod tests; <file_sep>/src/models/service/about.rs use serde::Serialize; #[derive(Serialize, Debug)] #[serde(rename_all = "camelCase")] pub struct About { pub transaction_service_base_url: String, pub name: String, pub version: String, pub build_number: Option<String>, } <file_sep>/src/routes/transactions.rs use crate::cache::cache_operations::CacheResponse; use crate::models::service::transactions::requests::{ ConfirmationRequest, MultisigTransactionRequest, }; use crate::services::{ transactions_details, transactions_history, transactions_proposal, transactions_queued, }; use crate::utils::context::Context; use crate::utils::errors::ApiResult; use rocket::response::content; use rocket_contrib::json::Json; use rocket_contrib::json::JsonError; #[get("/v1/transactions/<details_id>")] pub async fn details(context: Context<'_>, details_id: String) -> ApiResult<content::Json<String>> { CacheResponse::new(context.uri()) .resp_generator(|| transactions_details::get_transactions_details(&context, &details_id)) .execute(context.cache()) .await } #[post( "/v1/transactions/<safe_tx_hash>/confirmations", format = "application/json", data = "<tx_confirmation_request>" )] pub async fn submit_confirmation<'e>( context: Context<'_>, safe_tx_hash: String, tx_confirmation_request: Result<Json<ConfirmationRequest>, JsonError<'e>>, ) -> ApiResult<content::Json<String>> { transactions_proposal::submit_confirmation( &context, &safe_tx_hash, &tx_confirmation_request?.0.signed_safe_tx_hash, ) .await?; CacheResponse::new(context.uri()) .resp_generator(|| transactions_details::get_transactions_details(&context, &safe_tx_hash)) .execute(context.cache()) .await } #[get("/v1/safes/<safe_address>/transactions/history?<page_url>&<timezone_offset>")] pub async fn history_transactions( context: Context<'_>, safe_address: String, page_url: Option<String>, timezone_offset: Option<String>, ) -> ApiResult<content::Json<String>> { CacheResponse::new(context.uri()) .resp_generator(|| { transactions_history::get_history_transactions( &context, &safe_address, &page_url, &timezone_offset, ) }) .execute(context.cache()) .await } #[get("/v1/safes/<safe_address>/transactions/queued?<page_url>&<timezone_offset>&<trusted>")] pub async fn queued_transactions( context: Context<'_>, safe_address: String, page_url: Option<String>, timezone_offset: Option<String>, trusted: Option<bool>, ) -> ApiResult<content::Json<String>> { CacheResponse::new(context.uri()) .resp_generator(|| { transactions_queued::get_queued_transactions( &context, &safe_address, &page_url, &timezone_offset, &trusted, ) }) .execute(context.cache()) .await } #[post( "/v1/transactions/<safe_address>/propose", format = "application/json", data = "<multisig_transaction_request>" )] pub async fn propose_transaction<'e>( context: Context<'_>, safe_address: String, multisig_transaction_request: Result<Json<MultisigTransactionRequest>, JsonError<'e>>, ) -> ApiResult<()> { transactions_proposal::propose_transaction( &context, &safe_address, &multisig_transaction_request?.0, ) .await } <file_sep>/src/routes/mod.rs extern crate rocket; use rocket::response::Redirect; use rocket::Catcher; use rocket::Route; use rocket_contrib::json::JsonValue; pub mod about; pub mod balances; pub mod collectibles; pub mod health; pub mod hooks; pub mod safes; pub mod transactions; pub fn active_routes() -> Vec<Route> { routes![ root, about::backbone, about::info, about::redis, balances::get_balances, balances::get_supported_fiat, collectibles::list, safes::safe_info, transactions::details, transactions::history_transactions, transactions::queued_transactions, transactions::submit_confirmation, transactions::propose_transaction, hooks::update, hooks::flush_all, hooks::flush_token_info, health::health ] } pub fn error_catchers() -> Vec<Catcher> { catchers![not_found, panic] } #[catch(404)] fn not_found() -> JsonValue { json!({ "status": "error", "reason": "Resource was not found." }) } #[catch(500)] fn panic() -> JsonValue { json!({ "status": "error", "reason": "Server error occurred." }) } #[get("/")] pub fn root() -> Redirect { Redirect::temporary("https://github.com/gnosis/safe-client-gateway/wiki") } <file_sep>/src/models/service/transactions/summary.rs use super::*; use crate::providers::info::SafeAppInfo; use serde::Serialize; #[derive(Serialize, Debug, PartialEq)] #[serde(rename_all = "camelCase")] pub struct TransactionSummary { pub id: String, pub timestamp: i64, pub tx_status: TransactionStatus, pub tx_info: TransactionInfo, #[serde(skip_serializing_if = "Option::is_none")] pub execution_info: Option<ExecutionInfo>, #[serde(skip_serializing_if = "Option::is_none")] pub safe_app_info: Option<SafeAppInfo>, } #[derive(Serialize, Debug, PartialEq)] #[serde(rename_all = "camelCase")] pub struct ExecutionInfo { pub nonce: u64, pub confirmations_required: u64, pub confirmations_submitted: u64, #[serde(skip_serializing_if = "Option::is_none")] pub missing_signers: Option<Vec<String>>, } #[derive(Serialize, Debug, PartialEq)] #[serde(tag = "type")] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum TransactionListItem { #[serde(rename_all = "camelCase")] Transaction { transaction: TransactionSummary, conflict_type: ConflictType, }, DateLabel { timestamp: i64, }, Label { label: Label, }, ConflictHeader { nonce: u64, }, } #[derive(Serialize, Debug, PartialEq)] pub enum Label { Next, Queued, } #[derive(Serialize, Debug, PartialEq, Clone)] pub enum ConflictType { None, HasNext, End, } <file_sep>/src/models/service/transactions/requests.rs use crate::models::commons::Operation; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ConfirmationRequest { pub signed_safe_tx_hash: String, } #[derive(Serialize, Deserialize, Debug, PartialEq)] #[serde(rename_all = "camelCase")] pub struct MultisigTransactionRequest { pub to: String, pub value: String, pub data: Option<String>, pub nonce: String, pub operation: Operation, pub safe_tx_gas: String, pub base_gas: String, pub gas_price: String, pub gas_token: String, pub refund_receiver: Option<String>, #[serde(rename(serialize = "contractTransactionHash"))] pub safe_tx_hash: String, pub sender: String, pub signature: String, pub origin: Option<String>, } <file_sep>/src/main.rs #![feature(async_closure, proc_macro_hygiene, decl_macro, option_result_contains)] #![deny(unused_must_use)] extern crate log; extern crate semver; #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; extern crate dotenv; #[macro_use] pub mod macros; mod cache; mod config; mod models; mod monitoring; mod providers; mod routes; mod services; mod utils; #[cfg(test)] mod json; use crate::routes::error_catchers; use cache::redis::create_pool; use dotenv::dotenv; use routes::active_routes; use std::time::Duration; use utils::cors::CORS; #[launch] fn rocket() -> _ { dotenv().ok(); env_logger::init(); let client = reqwest::Client::builder() .connect_timeout(Duration::from_millis( config::internal_client_connect_timeout(), )) .build() .unwrap(); rocket::build() .mount("/", active_routes()) .register("/", error_catchers()) .manage(create_pool()) .manage(client) .attach(monitoring::performance::PerformanceMonitor()) .attach(CORS()) }
16023b2ab32c249fd31b44a40dafe6ffe96a9d02
[ "Rust" ]
11
Rust
XinFinOrg/gnosis-safe-client-gateway
e10a4856c1dd718aa49a3185965c8bee64013f8c
3c8f96132eec63751daf2983a00fbd7411ae8b44
refs/heads/master
<file_sep>import scrapy from scrapy.spiders import CrawlSpider, Rule from mycrawler.items import MycrawlerItem class MyspiderSpider(scrapy.Spider): name = 'myspider' allowed_domains = ['news.yahoo.co.jp'] start_urls = ['https://www.kokoro-yuyu.com/entry/2016/08/12/210000'] def parse(self, response): item = MycrawlerItem() item["image_urls"] = [] for image_url in response.xpath("//img/@src").extract(): if "http" not in image_url: item["image_urls"].append(response.url.rsplit("/", 1)[0] + "/" + image_url) else: item["image_urls"].append(image_url) return item <file_sep># rename.py import glob import os import sys indir = sys.argv[1] prefix = sys.argv[2] # ディレクトリ下のファイル名を再帰的に取得する path = os.path.join(indir, "**/*.*") all_imgs = glob.glob(path, recursive=True) all_imgs.sort() # ファイル数が何桁か調べる digit = len(str(len(all_imgs))) for index, img in enumerate(all_imgs, 1): # 元のディレクトリ構造とファイル名、拡張子を取得する ori_dir, ori_name = os.path.split(img) filename, suffix = os.path.splitext(ori_name) # 自分自身はリネームしない if ori_name == "rename.py": continue # 通し番号の桁を揃える num = str(index-1) # 新しいファイル名の生成、ディレクトリと拡張子は元のまま new_name = "{0}{1}".format(num, suffix) new_path = os.path.join(ori_dir, new_name) # 変更後と同じ名前のファイルが存在する場合はスキップ if os.path.exists(new_path): sys.stderr.write( "{0} already exists\n".format(new_path)) continue # リネーム os.rename(img, new_path) print("{0} -> {1}".format(ori_name, new_name)) <file_sep># -*- coding: utf-8 -*- import os import glob from PIL import Image # Setting(ここを変更して希望のサイズに変換) dir_location =r'C:\Users\mkou0\Desktop\Ironman\mycrawler\images\full' #変換したい画像ファイルがあるフォルダを指定 ['']内を変更 save_location =r'C:\Users\mkou0\Desktop\Ironman\mycrawler\images\output' #変換した画像ファイルを保存するフォルダを指定 ['']内を変更 ratio_fixed = 1 #縦横比を固定する場合は、1 しない場合は 0 width = 100 #画像の横サイズ height = 100 #画像の縦サイズ # 取得ファイル形式一覧 ext_list =('/*.jpg','/*.jpeg','/*.gif','/*.png') # for n in range(len(ext_list)): file_path = dir_location + ext_list[n] file_list = glob.glob(file_path) for f in file_list: img = Image.open(f) if ratio_fixed == 1: img.thumbnail((width, height)) else: img = img.resize((width, height)) full_file, ext = os.path.splitext(f) name = os.path.basename(full_file) img.save(save_location +'/'+ name + ext) print(name+'変換完了!') print('画像の変換完了') <file_sep># New_project 目標 GANを利用してアイアンマンの画像を自動生成しオリジナルアイアンマンを作る! それをアプリ化したいと思ってたのですが残念な結果だったため断念.
1c24dc8f174f8c16cc6122a6a380cac5ed6f33f8
[ "Markdown", "Python" ]
4
Python
KoMurase/Ironman_GAN
80acffb2bbb2856e74c55ab66de49458e8d38e2d
9db19c102da3888f580511e38eda334f070b6978
refs/heads/master
<repo_name>skochaver/urban_forest_ranges<file_sep>/raster_clipper.py import os import arcpy from arcpy.sa import * __author__ = '<NAME>' arcpy.CheckOutExtension('Spatial') def get_band_list(raster): """ Returns a list of all the band names in a raster. :param raster: The path to the raster dataset. :return: List of band names as strings. """ describe = arcpy.Describe(raster) # Arc Description object of raster band_list = [band.name for band in describe.children] return band_list def bands_to_raster_obj(raster, band_list): ''' Saves a list of Raster objects to memory. One for each band given for a raster dataset. :param raster: The path of the raster dataset holding the band_list bands. :param band_list: List of all the band names within the raster dataset. :return: List object of full band paths. ''' raster_list = [Raster(os.path.join(raster, band)) for band in band_list] return raster_list def custom_nodata(rlist): ''' Mask creation specific to Ryan Sword's aviris .bsq data. Takes the list of bands Plus1.96, PlusStDev, Mean, MinusStDev, and Minus1.96 and uses the specific signature of no data values (0 for all bands and the values listed below) to create a mask of the meaningful part of the image. :param rlist: :return: Returns raster object in memory ''' val_1 = 2.1812543869018555 # Plus 1.96 val_2 = 1.8875709772109985 # Plus StDev val_3 = 1.581650972366333 # Mean val_4 = 1.2757309675216675 # Minus StDev val_5 = 0.9820476770401001 # Minus 1.96 # Conditional sets new raster values to zero if all band values are also zero new_raster = Con(((rlist[0] == 0) & (rlist[1] == 0) & (rlist[2] == 0) & (rlist[3] == 0) & (rlist[4] == 0)), 0, 1) # Conditional sets new raster values to zero if equal to above values and not within previous conditional scope new_raster = Con(new_raster == 1, Con(((rlist[0] == val_1) & (rlist[1] == val_2) & (rlist[2] == val_3) & (rlist[3] == val_4) & (rlist[4] == val_5)), 0, 1), new_raster) # Set zero to null in new raster. Only retain data where there is meaningful data in original. new_raster = SetNull(new_raster == 0, new_raster) return new_raster def raster_to_polygon(raster_path, output_path): ''' Creates a polygon footprint of a binary (1 or 0) raster. :param raster_path: The path to the raster you want to turn into a polygon :param output_path: The path to where you want the output to go. :return: ''' raster = Raster(raster_path) mask_raster = Con((raster == 0) | (raster == 1), 1, 0) arcpy.RasterToPolygon_conversion(mask_raster, output_path, "NO_SIMPLIFY") return def raster_obj_to_polygon(raster_obj, output_path): ''' Creates a polygon footprint of a binary (1 or 0) raster. :param raster_path: The path to the raster you want to turn into a polygon :param output_path: The path to where you want the output to go. :return: ''' raster = raster_obj mask_raster = Con((raster == 0) | (raster == 1), 1, 0) arcpy.RasterToPolygon_conversion(mask_raster, output_path, "NO_SIMPLIFY") return<file_sep>/top_runner.py from raster_clipper import * from stdev_rangefinder import get_date, check_stdev_range, check_196stdev_range from raster_adder import add_small_rasters, total_intersection import arcpy from rasterizer import add_to_raster from arcpy.sa import * import tempfile import shutil import os __author__ = '<NAME>' def listdir_fullpath(directory): return [os.path.join(directory, name) for name in os.listdir(directory)] def get_files_of_ext(directory, extension): return [path for path in listdir_fullpath(directory) if os.path.splitext(path)[1].lower() == extension] def create_path_footprints(image_directory, burn_raster_path): ''' Given a directory containing .tif images and a path to an 0 constant raster this function will add 1 to every raster pixel where there is meaningful data in the raster. Converts to shapefile in directory and burns based on the output polygon geometry. Puts those shapefiles into a temporary directory then removes the directory. :param image_directory: The directory containing the raster images :param burn_raster_path: The path to the 0 constant raster. Should be of an extent that contains all the paths. :return: ''' temp_dir = tempfile.mkdtemp() for image in get_files_of_ext(image_directory, '.tif'): image_name = os.path.splitext(os.path.basename(image))[0] # con_raster = custom_nodata(bands_to_raster_obj(image, get_band_list(image))) for bsq images raster = Raster(image) mask_raster = Con((raster == 0) | (raster == 1), 1, 0) output_path = os.path.join(temp_dir, image_name + '.shp') arcpy.RasterToPolygon_conversion(mask_raster, output_path, "NO_SIMPLIFY") add_to_raster(burn_raster_path, output_path) shutil.rmtree(temp_dir) return def stdev_analysis(image_directory, template_raster_path, int_count_raster, type): ''' Does the standard deviation analysis for the .bsq images in the given image directory. Creates a directory of all the analysis outputs in said directory then creates a count raster of all those outputs. :param image_directory: The directory of the images (N, LIG, or LMA) for analysis. :param template_raster_path: The zero constant raster of the maximum extent of all the paths. :return: ''' stdev_dir = os.path.join(image_directory, 'stdev_outs') if not os.path.exists(stdev_dir): os.makedirs(stdev_dir) meaningful_files = get_files_of_ext(image_directory, '.bsq') remaining_files = meaningful_files[:] for raster_file in meaningful_files: print raster_file remaining_files.remove(raster_file) for compare_file in remaining_files: print '\t' + compare_file output_path = os.path.join(os.getcwd(), stdev_dir, get_date(raster_file) + '_TO_' + get_date(compare_file) + '.tif') try: check_stdev_range(raster_file, compare_file, output_path, template_raster_path) except: pass true_count_path = os.path.join(stdev_dir, type+'_stdev_true_count.tif') add_small_rasters(stdev_dir, template_raster_path, true_count_path) per_raster_path = os.path.join(stdev_dir, type+'_stdev_percent.tif') per_calc = Raster(true_count_path) * 1.0 / Raster(int_count_raster) * 1.0 per_calc.save(per_raster_path) return def _196stdev_analysis(image_directory, template_raster_path, int_count_raster, type): ''' Does the standard deviation analysis for the .bsq images in the given image directory. Creates a directory of all the analysis outputs in said directory then creates a count raster of all those outputs. :param image_directory: The directory of the images (N, LIG, or LMA) for analysis. :param template_raster_path: The zero constant raster of the maximum extent of all the paths. :return: ''' stdev_dir = os.path.join(image_directory, '196stdev_outs') if not os.path.exists(stdev_dir): os.makedirs(stdev_dir) meaningful_files = get_files_of_ext(image_directory, '.bsq') remaining_files = meaningful_files[:] for raster_file in meaningful_files: print raster_file remaining_files.remove(raster_file) for compare_file in remaining_files: print '\t' + compare_file output_path = os.path.join(os.getcwd(), stdev_dir, get_date(raster_file) + '_TO_' + get_date(compare_file) + '.tif') try: check_196stdev_range(raster_file, compare_file, output_path) except: pass true_count_path = os.path.join(stdev_dir, type+'_196stdev_true_count.tif') add_small_rasters(stdev_dir, template_raster_path, true_count_path) per_raster_path = os.path.join(stdev_dir, type+'_196stdev_percent.tif') per_calc = Raster(true_count_path) * 1.0 / Raster(int_count_raster) * 1.0 per_calc.save(per_raster_path) return n_path = r"C:\_sword_analysis\4-14-15\Resampled_AVG\N" lma_path = r"C:\_sword_analysis\4-14-15\Resampled_AVG\LMA" lig_path = r"C:\_sword_analysis\4-14-15\Resampled_AVG\LIG" path_count = r"C:\_sword_analysis\4-14-15\Resampled_AVG\path_counts.tif" template_raster_path = r"C:\_sword_analysis\4-8-15\empty_raster.tif" # total_intersection(n_path, template_raster_path, path_count) # stdev_analysis(n_path, template_raster_path, path_count, 'n') # _196stdev_analysis(n_path, template_raster_path, path_count, 'n') # stdev_analysis(lma_path, template_raster_path, path_count, 'lma') _196stdev_analysis(lma_path, template_raster_path, path_count, 'lma') stdev_analysis(lig_path, template_raster_path, path_count, 'lig') _196stdev_analysis(lig_path, template_raster_path, path_count, 'lig') <file_sep>/stdev_rangefinder.py import os import arcpy from arcpy import env from arcpy.sa import * import raster_clipper import ntpath print 'Packages Loaded' env.overwriteOutput = True __author__ = '<NAME>' def remove_nodata(in_raster_path): ''' Sets logical NoData values to Null in a 5 band raster. Assumes that the NoData values are those values where the pixel in every band is equal to 0. :param in_raster_path: The path to the five band raster in question. :return: Returns and Arc Raster object with the new Null pixels. ''' band_list = raster_clipper.get_band_list(in_raster_path) rlist = raster_clipper.bands_to_raster_obj(in_raster_path, band_list) in_raster = Raster(in_raster_path) # Conditional statement finding pixels where all bands are 0 and sets to Null. new_raster = SetNull(((rlist[0] == 0) & (rlist[1] == 0) & (rlist[2] == 0) & (rlist[3] == 0) & (rlist[4] == 0)), in_raster) return new_raster def raster_intersection(raster_1_path, raster_2_path): ''' Given two rasters this function will find data-full intersection between them and create an unsimplified polygon (i.e. the polygon will follow the exact edges of the pixels) of that intersection. :param raster_1_path: The path to one of the raster datasets. :param raster_2_path: The path to the other raster. :return: Returns and Arc polygon object as well as the path (in memory) to the shapefile containing that polygon. ''' raster_1 = remove_nodata(raster_1_path) raster_2 = remove_nodata(raster_2_path) rintersection = Con((raster_1 == True) & (raster_2 == True), 1, 0) pmemory = 'in_memory//poly' ext_poly = arcpy.RasterToPolygon_conversion(rintersection, pmemory, "NO_SIMPLIFY") return ext_poly, pmemory def check_stdev_range(raster_1_path, raster_2_path, con_raster_path, template_raster_path): ''' A custom conditional function that creates a binary raster from two five band rasters. Assumes the third band is the mean of the data, and the 2nd and 4th bands are the maximum and minimum of a single standard deviation respectively. If the mean of raster 1 falls within the range of raster 2 a value of 1 (True) is given to the output raster. Otherwise 0 (False). :param raster_1_path: The path to raster 1 (mean raster) :param raster_2_path: The path to raster 2 (range raster) :param con_raster_path: The location of the final conditional output. :return: ''' bound_poly, pmemory = raster_intersection(raster_1_path, raster_2_path) env.snapRaster = template_raster_path band_list_1 = raster_clipper.get_band_list(raster_1_path) rlist1 = raster_clipper.bands_to_raster_obj(raster_1_path, band_list_1) band_list_2 = raster_clipper.get_band_list(raster_2_path) rlist2 = raster_clipper.bands_to_raster_obj(raster_2_path, band_list_2) in_range_raster = Con((rlist1[2] >= rlist2[3]) & (rlist1[2] <= rlist2[1]), 1, 0) arcpy.Clip_management(in_range_raster, '#', con_raster_path, bound_poly, '255', "ClippingGeometry") arcpy.Delete_management(pmemory) return def check_196stdev_range(raster_1_path, raster_2_path, con_raster_path): ''' Does the same thing as the check_stdev_range function with the same assumptions using band 1 and 5 as the range. :param raster_1_path: The path to raster 1 (mean raster) :param raster_2_path: The path to raster 2 (range raster) :param con_raster_path: The location of the final conditional output :return: ''' bound_poly, pmemory = raster_intersection(raster_1_path, raster_2_path) band_list_1 = raster_clipper.get_band_list(raster_1_path) rlist1 = raster_clipper.bands_to_raster_obj(raster_1_path, band_list_1) band_list_2 = raster_clipper.get_band_list(raster_2_path) rlist2 = raster_clipper.bands_to_raster_obj(raster_2_path, band_list_2) in_range_raster = Con((rlist1[2] >= rlist2[4]) & (rlist1[2] <= rlist2[0]), 1, 0) arcpy.Clip_management(in_range_raster, '#', con_raster_path, bound_poly, '255', "ClippingGeometry") arcpy.Delete_management(pmemory) return def create_const_raster(base_raster_path, constant): ''' Given a raster dataset and any integer number this function will create a constant raster at the same extent as the input raster. :param base_raster_path: The path to the raster we'll use as a template. :param constant: The integer value to use in the constant. :return: ''' base_raster = Raster(base_raster_path) data_type = "INTEGER" cell_size = arcpy.GetRasterProperties_management(base_raster, "CELLSIZEX") x_min = arcpy.GetRasterProperties_management(base_raster, "LEFT") x_max = arcpy.GetRasterProperties_management(base_raster, "RIGHT") y_min = arcpy.GetRasterProperties_management(base_raster, "BOTTOM") y_max = arcpy.GetRasterProperties_management(base_raster, "TOP") extent = Extent(x_min, y_min, x_max, y_max) constant_raster = CreateConstantRaster(constant, data_type, cell_size, extent) return constant_raster def get_date(file_path): ''' Takes the file names specific to these five band rasters and slices strings until you have a unique date identifier. :param file_path: The full path to the file we need the date from :return: The date string we cut from the file path ''' name = ntpath.basename(file_path) date = name[1:7] full_date = date + '_' + name[14:16] return full_date def run_stdev_finder(): ''' !!!No longer relevant but I'll keep it here for nostalgia's sake!!! This is a runner function that goes through each .bsq five band file and creates comparison files for each other .bsq five band file of a later date. Puts the conditional comparisons into a folder in the current working directory called "stdev_outs". :return: ''' meaningful_files = [thing for thing in os.listdir(os.getcwd()) if '.bsq' in thing] remaining_files = meaningful_files[:] for raster_file in meaningful_files: print raster_file remaining_files.remove(raster_file) for compare_file in remaining_files: print '\t' + compare_file output_path = os.path.join(os.getcwd(), "stdev_outs//", get_date(raster_file) + '_TO_' + get_date(compare_file) + '.tif') try: check_stdev_range(raster_file, compare_file, output_path) except: pass return def run_196stdev_finder(): ''' !!!No longer relevant but I'll keep it here for nostalgia's sake!!! Runs the 1.96 standard deviation finder in the same manner as the run_stdev_finder function. :return: ''' meaningful_files = [thing for thing in os.listdir(os.getcwd()) if '.bsq' in thing] remaining_files = meaningful_files[:] for raster_file in meaningful_files: print raster_file remaining_files.remove(raster_file) for compare_file in remaining_files: print '\t' + compare_file output_path = os.path.join(os.getcwd(), "196stdev_outs//", get_date(raster_file) + '_TO_' + get_date(compare_file) + '.tif') try: check_196stdev_range(raster_file, compare_file, output_path) except RuntimeError: pass return<file_sep>/raster_adder.py import os import arcpy from stdev_rangefinder import get_date, check_stdev_range from arcpy.sa import * from arcpy import env import tempfile import shutil import time arcpy.CheckOutExtension("Spatial") env.overwriteOutput = True __author__ = '<NAME>' def listdir_fullpath(directory): return [os.path.join(directory, name) for name in os.listdir(directory)] def get_files_of_ext(directory, extension): return [path for path in listdir_fullpath(directory) if os.path.splitext(path)[1].lower() == extension] def make_it_big(small_raster_path, big_raster_path): ''' Takes a raster and redefines the extent to the match the template raster defined in our environment variables. :param small_raster: The raster with the extent that's smaller than the one you want to add it to. :return: Returns the Raster object ''' name, ext = os.path.splitext(big_raster_path) temp_raster = name + '-temp' + ext arcpy.CopyRaster_management(small_raster_path, temp_raster) big_raster = Raster(temp_raster) # Gives null value pixels a value of 0 for the purposes of adding to other rasters of the same (new) extent. # Saves it in the in-memory raster object and also as a new variable if it needs to be saved somewhere else. new_raster = Con(IsNull(temp_raster), 0, temp_raster) new_raster.save(big_raster_path) arcpy.Delete_management(temp_raster) return def add_small_rasters(small_directory, template_raster_path, final_raster_path): env.mask = template_raster_path env.extent = template_raster_path env.snapRaster = template_raster_path template_raster = Raster(template_raster_path) temp_dir = tempfile.mkdtemp() for image in get_files_of_ext(small_directory, '.tif'): image_name = os.path.splitext(os.path.basename(image))[0] big_path = os.path.join(temp_dir, image_name+'.tif') make_it_big(image, big_path) template_raster = template_raster + big_path template_raster.save(final_raster_path) shutil.rmtree(temp_dir) return def total_intersection(in_raster_dir, template_raster_path, final_raster_path): temp_dir_1 = tempfile.mkdtemp() temp_dir_2 = tempfile.mkdtemp() meaningful_files = get_files_of_ext(in_raster_dir, '.bsq') remaining_files = meaningful_files[:] for raster_file in meaningful_files: remaining_files.remove(raster_file) for compare_file in remaining_files: output_path = os.path.join(temp_dir_1, get_date(raster_file) + '_TO_' + get_date(compare_file) + '.tif') try: check_stdev_range(raster_file, compare_file, output_path, template_raster_path) except: pass for image in get_files_of_ext(temp_dir_1, '.tif'): image_name = os.path.basename(image) my_raster = Raster(image) con_raster = Con(((my_raster == 1) | (my_raster == 0)), 1, 0) con_raster.save(os.path.join(temp_dir_2, image_name)) con_raster = None my_raster = None add_small_rasters(temp_dir_2, template_raster_path, final_raster_path) shutil.rmtree(temp_dir_1) shutil.rmtree(temp_dir_2) return
d36376b7e704da3a42f15c59e3edca4eadb3a4c9
[ "Python" ]
4
Python
skochaver/urban_forest_ranges
28e4ef38f4f5fcbda36f1c1a0998e81db738875c
bd338225375c9cb45215b01d3a4e127d1d225167
refs/heads/master
<repo_name>HeleneMCasanova/Blog<file_sep>/_posts/2019-01-11-Blog-One.md --- title: Blog One layout: default date: 2019-01-11 image: comments: true --- This week was an adventuous one! Learning the difference between functional and non-functional has helped in understanding how to start any software or program. Functional Requirements have to do with the functionality of the system or what the system does with the computation. Non-functional Requirements refers to non-functional properties or systems qualities. Examples include security accuracy, performance, cost or usability. Do not always have clear satisfaction criteria. I have a tendency to start projects and focus on the details; this tendency was discussed in the video from this week. This tendecy leads me often drop projects I'm working on halfway through. There were several different points that were dicussed to avoid this habit. I am going to take these tips into this class as well as into my future projects and classes.<file_sep>/_posts/2019-01-24-Blog-Two.md --- title: Blog Two layout: default date: 2019-01-24 image: comments: true --- This week was learning more about the difference between features and requirements. It was imperative to understand why we need to define requirements before we start building anything because if going into a project with unclear goals and objectives is just a recipe for disaster. People tend to fall into the trap, at the requirements level, by focusing on the features and functionalities of a software product. At the requirements level, you should be focusing on the "what" and not the "how". Before starting this class, I will admit that I would have fallen into this trap whenever I would begin a new project and I would begin focusing on details that may have taken me longer then if I would have followed this model. From now one, when I tackle a new project, I will look at it from the perspective of a client and work my from there because in the end there will always be a client to satisfy. This week I also got about 2/3 of the way through <i>Don't Make Me Think Revisited</i> and so far I have gotten a lot of useful information that I never would have thought apploed in webpage development. One major idea that I thought was imperative was usability testing, one topic which the author seems to be extremly passionate about. The reason for this is because a lot of usability testing tends to get don’t too little, too late and for all the wrong reasons.<file_sep>/_site/post_update.sh #!/bin/bash git init git add . git commit -m "Adding a new blog post" git push -u origin master
59785a13bca044fee943baecbcc95c51dcb0eae3
[ "Markdown", "Shell" ]
3
Markdown
HeleneMCasanova/Blog
9fb1bd860144c4c96ac5cfacb571b5ed3093d1b8
749e333f2c3badb6ddb2c581ea455b22b4825dc8
refs/heads/main
<file_sep>from gensim.models import KeyedVectors from nltk.corpus import stopwords import numpy as np import keras import predict_grade #predictions based on the lstm model trained on HP dataset for 10 and 12 as a maximum grade. #Word2vec embedding is used model_10 = keras.models.load_model("final_lstm.h5") model_12 = keras.models.load_model("final_lstm_12.h5") def essay_to_wordlist(essay_v, remove_stopwords): words = essay_v.lower().split() if remove_stopwords: stops = set(stopwords.words("english")) words = [w for w in words if not w in stops] return (words) def essay_to_sentences(essay_v, remove_stopwords): """Sentence tokenize the essay and call essay_to_wordlist() for word tokenization.""" tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') raw_sentences = tokenizer.tokenize(essay_v.strip()) sentences = [] for raw_sentence in raw_sentences: if len(raw_sentence) > 0: sentences.append(essay_to_wordlist(raw_sentence, remove_stopwords)) return sentences def makeFeatureVec(words, model, num_features): """Make Feature Vector from the words list of an Essay.""" featureVec = np.zeros((num_features,),dtype="float32") num_words = 0. index2word_set = set(model.wv.index2word) for word in words: if word in index2word_set: num_words += 1 featureVec = np.add(featureVec,model[word]) featureVec = np.divide(featureVec,num_words) return featureVec def getAvgFeatureVecs(essays, model, num_features): """Main function to generate the word vectors for word2vec model.""" counter = 0 essayFeatureVecs = np.zeros((len(essays),num_features),dtype="float32") for essay in essays: essayFeatureVecs[counter] = makeFeatureVec(essay, model, num_features) counter = counter + 1 return essayFeatureVecs #all predictions combined and average is calculated def predict_level(text): num_features = 300 model = KeyedVectors.load_word2vec_format( "word2vecmodel.bin", binary=True ) clean_test_essays = [] clean_test_essays.append( essay_to_wordlist( text, remove_stopwords=True ) ) testDataVecs = getAvgFeatureVecs( clean_test_essays, model, num_features ) testDataVecs = np.array(testDataVecs) testDataVecs = np.reshape( testDataVecs, (testDataVecs.shape[0], 1, testDataVecs.shape[1]) ) preds_1 = int(np.around(model_10.predict(testDataVecs))) preds_2 = int(np.around(model_12.predict(testDataVecs))) preds_3 = predict_grade.text_predict(text)/16.66 preds = round((preds_1+preds_2+preds_3)/3) return preds <file_sep>from dataclasses import dataclass from typing import Dict, List class CorrectionType(Dict): correct: List[str] position: int @dataclass class SuggestCorrection: data: Dict[str, CorrectionType] percentage_of_incorrect: float <file_sep>import logging from typing import List import streamlit from Spell_check import spell_check_js, spell_check_norvig, spell_check_enchant from domain import SuggestCorrection from grammar_check import grammar_check from grammar_check import nlp_rule_check from utils import percentage_of_incorrect from write_results import write_results logger = logging.getLogger(__name__) def _calculate_actual_percentage_of_incorrect(text:str, mistake_keys: List[str]) -> float: text_keys = text.split() errors_count = len(mistake_keys) text_keys_without_error_count = len(text_keys) - errors_count return percentage_of_incorrect(text_keys_without_error_count, errors_count) def example_check(text: str): # spell_enchant_result = spell_check_enchant(text) # spell_norvig_result = spell_check_norvig(text) # grammar_result = grammar_check(text) # spell_jamspell_result = spell_check_js(text) # nlp_rule_result = nlp_rule_check(text) suggestions_data = {} checkers = [ grammar_check, nlp_rule_check ] attempt_check_count = len(checkers) for checker in [ grammar_check, nlp_rule_check ]: try: result = checker(text) suggestions_data.update(result.data) except Exception as error: logger.error("Something is going wrong...", exc_info=error) attempt_check_count -= 1 pass if attempt_check_count: result = SuggestCorrection( data=suggestions_data, percentage_of_incorrect=_calculate_actual_percentage_of_incorrect(text, suggestions_data.keys()) ) write_results(text, result.percentage_of_incorrect, result.data) else: streamlit.write("Sorry, temporary unavailable") <file_sep>streamlit run Streamlit_app.py <file_sep>from textblob import TextBlob import nltk from domain import SuggestCorrection from utils import percentage_of_incorrect from write_results import write_results #this function compares the raw input text and corrected text which is the base for def compare(text1, text2): l1 = text1.split() l2 = text2.split() correct = 0 incorrect = 0 dict_of_incorrect = {} for i in range(0, len(l1)): if l1[i] != l2[i]: incorrect += 1 dict_of_incorrect[l1[i]] = {'incorrect': l1[i], 'correct': l2[i], 'position': i, 'message': 'Possible spelling mistake found.'} else: correct += 1 return (correct, incorrect), dict_of_incorrect def tokenize_input(text): words = nltk.word_tokenize(text) text = [word for word in words if word.isalnum()] return text def correct_percentage_and_mistakes(text): text = tokenize_input(text) text = " ".join(text) text_corrected = TextBlob(text).correct() tuple_of_words, dict_of_incorrect = compare(text, text_corrected) percentage = percentage_of_incorrect(tuple_of_words[0], tuple_of_words[1]) return percentage, dict_of_incorrect def correct_percentage_and_mistakes_js(text): text = tokenize_input(text) text = " ".join(text) corrector = jamspell.TSpellCorrector() corrector.LoadLangModel('en.bin') text_corrected = corrector.FixFragment(text) tuple_of_words, dict_of_incorrect = compare(text, text_corrected) percentage = percentage_of_incorrect(tuple_of_words[0], tuple_of_words[1]) return percentage, dict_of_incorrect def spell_check_js(text): p, d = correct_percentage_and_mistakes_js(text) return SuggestCorrection( data=d, percentage_of_incorrect=p ) def spell_check_enchant_with_print_result(text): result = spell_check_enchant(text) write_results(text, result.percentage_of_incorrect, result.data) def spell_check_jamspell_print_results(text): result = spell_check_js(text) write_results(text, result.percentage_of_incorrect, result.data) def spell_check_norvig_print_results(text): result = spell_check_norvig(text) write_results(text, result.percentage_of_incorrect, result.data) def spell_check_norvig(text): spell = SpellChecker() splitted_text = text.split() misspelled = spell.unknown(splitted_text) d = OrderedDict() for word in misspelled: index = 0 message = 'Possible spelling mistake found.' for i in range(len(splitted_text)): if splitted_text[i] == word: index = i+1 d[word] = {'incorrect': word, 'correct': spell.correction(word),'position': index, 'message': message} p = percentage_of_incorrect(len(text.split())-len(misspelled),len(misspelled)) return SuggestCorrection( data=d, percentage_of_incorrect=p ) def spell_check_enchant(text): glossary = enchant.Dict("en_US") splitted_text = text.split() d = OrderedDict() misspelled = [] for word in splitted_text: if glossary.check(word): continue else: misspelled.append(word) for word in misspelled: message = 'Possible spelling mistake found.' for i in range(len(splitted_text)): if splitted_text[i].lower() == word: index = i + 1 d[word] = {'incorrect': word, 'correct': glossary.suggest(word)[0], 'position': index, 'message':message} p = percentage_of_incorrect(len(text.split()) - len(misspelled), len(misspelled)) return SuggestCorrection( data=d, percentage_of_incorrect=p ) <file_sep>pandas numpy scikit-learn sklearn==0.0 spacy scipy streamlit streamlit-lottie==0.0.2 st-annotated-text==1.0.1 tensorflow==2.6.0 textblob==0.15.3 nltk==3.5 keras==2.6.0 Keras-Preprocessing==1.1.2 language-tool-python==2.5.5 htbuilder==0.3.0 collection==0.1.6 pyspellchecker==0.6.2 regex==2020.11.13 nlprule==0.6.4 gensim==3.8.3 altair==4.1.0 h5py==3.1.0 pickleshare <file_sep>""" Tfidf model for topics recognition. There are 15 topics chosen on EAQUALs standards for CEFR levels. Dataset was created manually. """ import pickle import re from sklearn.feature_extraction.text import TfidfVectorizer from nltk.corpus import stopwords from sklearn.multiclass import OneVsRestClassifier topic_classifier: OneVsRestClassifier = pickle.load(open("topic_recognition_model.pkl", "rb")) vocab = pickle.load(open("topics_vocabulary.pkl", "rb")) def predict_topic(text): try: REPLACE_BY_SPACE_RE = re.compile( '[/(){}\[\]\|@,;]' ) BAD_SYMBOLS_RE = re.compile( '[^0-9a-z #+_]' ) STOPWORDS = set( stopwords.words( 'english' ) ) text = text.lower() # lowercase text text = text.replace( "\n", " " ) text = REPLACE_BY_SPACE_RE.sub( ' ', text ) # replace REPLACE_BY_SPACE_RE symbols by space in text text = BAD_SYMBOLS_RE.sub( '', text ) # delete symbols which are in BAD_SYMBOLS_RE from text text = [word for word in text.split() if word not in STOPWORDS] # delete stopwors from text tfidf_vectorizer = TfidfVectorizer(token_pattern='(\S+)', vocabulary=vocab) r = tfidf_vectorizer.fit_transform( text ) prediction = topic_classifier.predict( r ) mlb = pickle.load(open("binarizer.pkl", "rb")) prediction = mlb.inverse_transform( prediction ) prediction = list( set( [i[0] for i in prediction if len( i ) > 0] ) )[:3] if len(prediction) == 0: message = 'It is hard to define your topic' if len(prediction) != 0: return ', '.join( prediction ) return message except Exception: pass<file_sep>import language_tool_python from domain import SuggestCorrection from write_results import write_results from nlprule import Tokenizer, Rules def compare(text1, text2): l1 = text1.split() l2 = text2.split() correct = 0 incorrect = 0 dict_of_incorrect = {} for i in range(0, len(l2)): if l1[i] != l2[i]: incorrect += 1 message = 'Error' dict_of_incorrect[l1[i]] = {'incorrect': l1[i],'correct': l2[i], 'position': i, 'message': message} else: correct += 1 return (correct, incorrect), dict_of_incorrect def nlp_rule_check(text): splitted_text = text.split() tokenizer = Tokenizer.load("en") rules = Rules.load("en", tokenizer) d = {} index = -1 for s in rules.suggest(text): start = s.start end = s.end mistake_word = text[start:end] message = s.message correct = s.replacements[:2] for i in range(len(splitted_text)): if splitted_text[i].lower() == mistake_word.lower(): index = i + 1 d[mistake_word] = {'incorrect': mistake_word, 'correct': correct, 'position': index, 'message': message} return SuggestCorrection( data=d, percentage_of_incorrect=0 ) def nlp_rule_print_results(text): result = nlp_rule_check(text) write_results(text, result.percentage_of_incorrect, result.data) def grammar_check(text: str): tool = language_tool_python.LanguageTool( 'en-US' ) splitted_text = text.split() is_bad_rule = lambda rule: rule.message == 'Possible spelling mistake found.' and len(rule.replacements) and \ rule.replacements[0][0].isupper() matches = tool.check(text) matches = [rule for rule in matches if not is_bad_rule(rule)] from collections import OrderedDict d = {} index = -1 for match in matches: mistake_word = text[match.offset:match.offset + match.errorLength] message = match.message for i in range( len( splitted_text ) ): if splitted_text[i].lower() == mistake_word.lower(): index = i + 1 d[mistake_word] = {'incorrect': mistake_word, 'correct': match.replacements[:2], 'position': index, 'message': message} return SuggestCorrection( data=d, percentage_of_incorrect=0 ) def grammar_check_with_print_result(text: str): result = grammar_check(text) write_results(text, result.percentage_of_incorrect, result.data) <file_sep> def percentage_of_incorrect(correct_count:int, incorrect_count: int ): total_count = correct_count + incorrect_count if total_count <= 0: return 0 else: return (incorrect_count / total_count) * 100 <file_sep>import base64 import time import streamlit as st from PIL import Image import grammar_spell as spell_with_grammar_checker import lexical_complexity_level_count as lcx import topic_recognition import predict_grade import calculate_final_level @st.cache( allow_output_mutation=True ) def get_base64_of_bin_file(bin_file): with open( bin_file, 'rb' ) as f: data = f.read() return base64.b64encode( data ).decode() def set_png_as_page_bg(png_file): bin_str = get_base64_of_bin_file(png_file) page_bg_img = ''' <style> body { background-image: url("data:image/png;base64,%s"); background-size: cover; } </style> '''% bin_str st.markdown(page_bg_img, unsafe_allow_html=True) return set_png_as_page_bg('language app.png') st.title('Typewriter :heart::flag-gb:') img = Image.open("typewriter.png") st.image(img) st.subheader('This tool can help assess your English based on your writing. It will also give recommendations on how to improve it.') color = st.select_slider('Rate yourself as an English writer', options=['Terrible', 'Quite bad', 'Decent', 'Pretty Good', 'Excellent']) st.write("Now you can check what the 'Typewriter' says. Write your text or paste from a document and see the results.") option = st.selectbox('Choose what you want to check: ', ['Check your writing', 'Understand the results']) if option == 'Check your writing': my_slot = st.empty() st.write( "Please, fill in the text field with your great writing." ) text = st.text_area( label='writing', value="Type here..." ) answer = my_slot.radio( 'Which aspect of your writing do you want to check?', ['1. Spelling and Grammar', '2. Lexis and topics complexity', '3. Predicted grade'] ) if answer == '1. Spelling and Grammar': st.write("You can see if you have any mistakes and their percent % in the whole text. Lower number means fewer mistakes.") my_bar = st.progress(0) for percent_complete in range(100): time.sleep(0.1) my_bar.progress(percent_complete + 1) with st.spinner('Please wait while we are checking your work'): time.sleep(10) st.success('Done!') spell_with_grammar_checker.example_check(text) elif answer == '2. Lexis and topics complexity': st.write("The more advanced vocabulary you use, the higher is your level of English.") st.write( 'There are 6 levels of English where 1 means "Beginner" and 6 is "Proficient".' ) st.write( "Lexical density shows the percentage of words of each level in the whole text." ) st.write("The words were taken from the Language Portfolio which is the minimum of words chosen for each level. There are 1500-2500 words for a level approximately.") st.write('Predicted topic: {topic}.'.format(topic= topic_recognition.predict_topic(text))) lcx.topic_level(text) lcx.write_lex_density(text) elif answer == '3. Predicted grade': st.write("Your predicted grade is {num}% which corresponds to grade {letter}.".format(num=predict_grade.text_predict(text), letter= predict_grade.grade_converter(predict_grade.text_predict(text)))) elif option == 'Understand the results': text = st.text_area(label='writing', value="Type here..." ) st.write("There are six levels of English according to CEFR.") st.write( "Your calculated level is marked RED." ) chart = calculate_final_level._build_graph(text) st.altair_chart(chart) st.write("See what your level is and read descriptions of each level.") <file_sep>import lexical_complexity_level_count as lex_cx import models_grade_prediction as mod_pred import pandas as pd import grammar_spell import altair as alt def _calculate_grade(text): grade_1 = lex_cx.lex_dens_level(text) grade_2 = lex_cx.topic_level(text) grade_3 = mod_pred.predict_level(text) grade_final = round((grade_1+grade_2+grade_3)/3) return grade_final def _build_graph(text): grade_final = _calculate_grade(text) df = pd.DataFrame.from_records( [ {"CEFR level": "Basic user", "level": "A1", "number level": 1, "level description": "Can write simple isolated phrases and sentences on familiar topics of daily life situations (family, hobbies and pasttimes, holidays, leisure activities, shopping, and work and jobs)."}, {"CEFR level": "Basic user", "level": "A2", "number level": 2, "level description": 'Can write a series of simple sentences on a familiar subject (education, hobbies and leisure activities, shopping, work and jobs, holidays) linked with simple connectors like "and", "but", and "because".'}, {"CEFR level": "Independent user", "level": "B1", "number level": 3, "level description": "Can write straightforward connected texts on a range of familiar subjects (books, film, education, media, news, lifestyles and current affairs) within the field of interest, by linking a shorter discrete elements into a linear sequence."}, {"CEFR level": "Independent user", "level": "B2", "number level": 4, "level description": "Can write clear, detailed texts on variety of subjects related to the field of interest (arts, books, film, media, news, and current affairs) synthesizing and evaluating information and arguments from a number of sources."}, {"CEFR level": "Proficient user", "level": "C1", "number level": 5, "level description": "Can write clear, well-structured texts of complex subjects (scientific developments, technical and legal language, media, news, arts), underlining the relevant salient issues, expanding and supporting points of view at some length with subsidiary points, reasons and relevalnt examples, and rounding off with an appropriate conclusion."}, {"CEFR level": "Proficient user", "level": "C2", "number level": 6, "level description": "Can write clear, smoothly flowing texts in an appropriate and effective style and a logical structure which helps the reader to find significant points."}, ] ) graph = alt.Chart(df).mark_bar().encode( x='level', y='number level', column='CEFR level', color=alt.condition( alt.FieldEqualPredicate(field='number level', equal = grade_final), alt.value('red'), alt.value('silver') ), tooltip=['level description'], ).interactive() return graph<file_sep>from __future__ import print_function, unicode_literals import topic_recognition import streamlit as st from nltk.tokenize import word_tokenize from operator import itemgetter from nltk.stem import WordNetLemmatizer import nltk nltk.download('wordnet') import os def round_num(score): decimal = score - int(score) if decimal >= 0.5: return int(score)+1 else: return int(score) def topic_level(text): # interpret topic recognition results try: points = [] predictions = topic_recognition.predict_topic(text) topics = predictions.split(', ') for i in range(0, len(topics)): topic = topics[i] if topic == 'family': point = 1 elif (topic == 'hobbies and pasttimes') or (topic =='holidays') or (topic =='shopping') or (topic =='work and jobs'): point = 2 elif (topic == 'education') or (topic =='leisure activities'): point = 2.5 elif (topic == 'books and literature') or (topic == 'arts') or (topic=='media') or (topic =='news, lifestyles and current affairs') or (topic == 'film'): point = 4 elif (topic == 'scientific developments') or (topic == 'technical and legal'): point = 5 else: point = 0 points.append(point) level_topic = round_num(sum(points)/len(points)) return level_topic except Exception: pass def _lang_level(text): try: #tokenization and lemmatization of the input text sentence_words = word_tokenize(text) wordnet_lemmatizer = WordNetLemmatizer() lemmas =[] punctuations = "?:!.,;" for word in sentence_words: if word in punctuations: sentence_words.remove(word) lemma = wordnet_lemmatizer.lemmatize(word, pos="v") lemmas.append(lemma) except Exception: pass #reading the vocabulary lists into the dictionary with key as the name of level dict_vocab = {} for filename in os.listdir("vocabulary lists"): if filename.endswith("vocabulary list.txt"): with open("vocabulary lists/" + filename, 'r') as d: dict_vocab[filename[:2]]=d.read().split('\n') for word in dict_vocab['C1']: word.lower() #st.write(dict_vocab) set_A1 = set(dict_vocab['A1']) set_A2 = set(dict_vocab['A2']).difference(set_A1) set_B1 = set( dict_vocab['B1'] ).difference(set_A1) set_B1 = set_B1.difference(set_A2) set_B2 = set(dict_vocab['B2']).difference(set_B1) set_C1 = set(dict_vocab['C1']).difference(set_B2) set_C2 = set( dict_vocab['C2'] ).difference(set_C1) vocab_lists_sets =[set_A1,set_A2,set_B1,set_B2,set_C1,set_C2] #count lexical density for each level set_essay = set(lemmas) words_found = [] words_counts = [] for i in range(0, len(vocab_lists_sets)): words_from_dict = vocab_lists_sets[i].intersection(set_essay) words_found.append(words_from_dict) for i in range(0, len(words_found)): word_count = len(words_found[i]) words_counts.append(word_count) total_count = len(lemmas) lex_dens_list = [] for i in range(0, len(words_counts)): lex_density = round((words_counts[i]/total_count) * 100, 2) lex_dens_list.append(lex_density) return lex_dens_list, words_found #calculate lexical density def lex_dens_level(text): lex_dens_list,words_found =_lang_level(text) indices, L_sorted = zip(*sorted(enumerate(lex_dens_list), key=itemgetter(1))) level_ld = (indices[0]+indices[1])/2 return level_ld def write_lex_density(text): try: level_ld = lex_dens_level(text) level_topic = topic_level(text) if level_topic > 0: level_av = round_num((level_ld + level_topic)/2) else: level_av = round_num(level_ld) lex_dens_list,words_found = _lang_level(text) st.write('Based on your topic and vocabulary complexity, your level of English is {level_av}.'.format(level_av=level_av)) for i in range (0,len(lex_dens_list)): st.write('Percentage of words from level {num} in your text is: {lex_density}% : {words}'.format(num = i+1, lex_density=lex_dens_list[i], words = words_found[i])) i +=1 except Exception: pass <file_sep>import re import nltk import streamlit as st from __init__ import annotated_text def tokenize_input(text): words = nltk.word_tokenize(text) text = [word for word in words if word.isalnum()] return text def write_results(text:str, p:float, d:dict): text_copy = text[:] st.write("Percentage of mistakes: " + str(round(p, 2)) + "%") #print(f"{text=}, {p=}, {d=}") splitted_text = text_copy.split() l = len(splitted_text) / 13 * 28 errors_metadata = [] for key, value in d.items(): mistake_word = value['incorrect'] if mistake_word not in text_copy: continue if mistake_word in text_copy: find_the_word = re.finditer('[^A-Za-z]'+mistake_word+'[^A-Za-z]', text ) for match in find_the_word: start = match.start() end = match.end() # start = text.find(mistake_word) # end = start + len(mistake_word) errors_metadata.append( (start, end) ) text_with_annotations = [] prev_end = 0 for start, end in sorted(errors_metadata): if prev_end == 0: pass text_with_annotations.append(text[prev_end:start]) text_with_annotations.append((text[start:end], "", "#faa")) prev_end = end if prev_end < len(text): text_with_annotations.append(text[prev_end:]) annotated_text(l, *text_with_annotations ) st.write("Mistakes found: ") for key, value in d.items(): corrects = value['correct'] corrects_of_list = corrects if type(corrects) is list else [corrects] corrects_text = str.join(" or ", corrects_of_list) message = value['message'] annotated_text(50, "Instead of ", (key, "", "#faa"), " should be ", (corrects_text, "", "#afa"), " Explanation: ",message) """st.write("Percentage of mistakes: " + str(round(p, 2)) + "%") splitted_text = text.split() positions_of_incorrect = [i['position'] for i in d.values()] for i in range(1, len(splitted_text)+1): if not i in positions_of_incorrect: splitted_text[i-1] = " " + splitted_text[i-1] + " " if i in positions_of_incorrect: splitted_text[i-1] = (splitted_text[i-1], "", "#faa") l = len(splitted_text) / 13 * 28 annotated_text(l, *splitted_text) st.write("Incorrect: ") for key, value in d.items(): annotated_text(35, (key, "", "#faa"), " must be written as ", (str(value['correct']), "", "#afa")) for index in range(len(splitted_text)): if splitted_text[index].lower() == mistake_word.lower(): positions_of_incorrect = index index+=1 if not i in positions_of_incorrect: splitted_text[i - 1] = " " + splitted_text[i - 1] + " " if i in positions_of_incorrect: splitted_text[i - 1] = (splitted_text[i - 1], "", "#faa") """<file_sep>import numpy as np import nltk import re from nltk.corpus import stopwords import math import keras #here we use the lstm model trained on the Hewlett-Packard dataset that returns the grade from 0-100% which is then converted to letter grade (A-F) #glove.6B.200d emmebeddings are used lstm_model = keras.models.load_model("good_model_scoring.h5") def essay_to_wordlist(essay_v, remove_stopwords): """Remove the tagged labels and word tokenize the sentence.""" essay_v = re.sub("[^a-zA-Z]", " ", essay_v) words = essay_v.lower().split() if remove_stopwords: stops = set(stopwords.words("english")) words = [w for w in words if not w in stops] return words def essay_to_sentences(essay_v, remove_stopwords): """Sentence tokenize the essay and call essay_to_wordlist() for word tokenization.""" tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') raw_sentences = tokenizer.tokenize(essay_v.strip()) sentences = [] for raw_sentence in raw_sentences: if len(raw_sentence) > 0: sentences.append(essay_to_wordlist(raw_sentence, remove_stopwords)) return sentences def makeFeatureVec(words, model, num_features): """Make Feature Vector from the words list of an Essay.""" featureVec = np.zeros((num_features,),dtype="float32") num_words = 0. # index2word_set = set(model.wv.index2word) for word in words: if word in model: num_words += 1 featureVec = np.add(featureVec, model[word]) featureVec = np.divide(featureVec,num_words) return featureVec def getAvgFeatureVecs(essays, model, num_features): """Main function to generate the word vectors for word2vec model.""" counter = 0 essayFeatureVecs = np.zeros((len(essays),num_features),dtype="float32") for essay in essays: essayFeatureVecs[counter] = makeFeatureVec(essay, model, num_features) counter = counter + 1 return essayFeatureVecs def text_predict(text): try: embedding_dict={} with open('glove.6B.200d.txt','r') as f: for line in f: values = line.split() word = values[0] vectors = np.asarray(values[1:],'float32') embedding_dict[word] = vectors model = embedding_dict if len(text) > 20: num_features = 200 clean_test_essays = [] clean_test_essays.append( essay_to_wordlist(text, remove_stopwords=True ) ) testDataVecs = getAvgFeatureVecs( clean_test_essays, model, num_features ) testDataVecs = np.array(testDataVecs) testDataVecs = np.reshape(testDataVecs, (testDataVecs.shape[0], 1, testDataVecs.shape[1])) preds = lstm_model.predict(testDataVecs) preds = list(preds)[0][0] if math.isnan(preds): preds = 0 else: preds = np.round( preds ) if preds < 0: preds = 0 else: preds = 0 preds = int(preds) return preds except Exception: pass def grade_converter(preds): if preds >= 93: grade = 'A+' elif preds <= 92 and preds >= 85: grade = 'A' elif preds <= 84 and preds >= 75: grade = 'B' elif preds <= 74 and preds >= 70: grade = 'B' elif preds <= 69 and preds >= 65: grade = 'C+' elif preds <= 64 and preds >= 60: grade = 'C' elif preds <= 59 and preds >= 55: grade = 'D+' elif preds <= 54 and preds >= 50: grade = 'D' else: grade = 'F' return grade<file_sep># Writing-Aid This is the web application for assessing English writing. It can: - find spelling and grammar and spelling mistakes, highlight them in text and suggest corrections - define the complexity of your topic and calculate lexical density (percent of words of each level in your text) Full description and examples could be found in this video! https://player.vimeo.com/video/601283925?badge=0&amp;autopause=0&amp;player_id=0&amp;app_id=58479&amp;h=500476c5ac for the predict_grade.py you will need glove.6B.200d.txt file which could be found at https://www.kaggle.com/incorpes/glove6b200d. <file_sep>import os import streamlit.components.v1 as components import streamlit as st from htbuilder import HtmlElement, div, span, styles, classes, fonts from htbuilder.units import percent, px, rem, em def annotation(body, label="", background="#ddd", color="#333", **style): if "font_family" not in style: style["font_family"] = "sans-serif" return span( style=styles( background=background, border_radius=rem(0.43), color=color, padding=(rem(0.05), rem(0.02)), display="inline-flex", justify_content="center", align_items="center", **style, ) )( body, span( style=styles( color=color, font_size=em(0.67), opacity=0.5, text_transform="uppercase" ) )(label) ) def annotated_text(l, *args, **kwargs): out = div(style=styles( font_family="sans-serif", line_height="1.3", font_size=px(16), )) for arg in args: if isinstance(arg, str): h = len(arg)/16*35 out(arg) elif isinstance(arg, HtmlElement): out(arg) elif isinstance(arg, tuple): out(annotation(*arg)) else: raise Exception("Oh noes!") components.html(str(out), height=l, **kwargs) _RELEASE = False if not _RELEASE: _st_lottie = components.declare_component( "streamlit_lottie", url="http://localhost:3001", ) else: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") _st_lottie = components.declare_component("streamlit_lottie", path=build_dir) def st_lottie(): pass<file_sep>import pandas as pd from sklearn.model_selection import train_test_split import re from nltk.corpus import stopwords import numpy as np from scipy import sparse as sp_sparse from collections import Counter from sklearn.preprocessing import MultiLabelBinarizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.multiclass import OneVsRestClassifier from sklearn.tree import DecisionTreeClassifier import pickle from sklearn.metrics import accuracy_score from sklearn.metrics import f1_score from sklearn.metrics import average_precision_score df = pd.read_csv('topics eaquals.csv') df_topic = df[["Tags", "Description"]] df_topic['Text'] = df_topic['Description'] df_topic = df_topic.dropna().reset_index() df_topic['Tags'] = [tag.split('\n') for tag in df_topic['Tags']] df_topic = df_topic.reset_index(drop = True) d = {} for i in range(len(df_topic)): for j in df_topic.loc[i, 'Tags']: if j in d: d[j] += 1 else: d[j] = 1 d_new = list({k: v for k, v in d.items() if v <= 30}.keys()) for i in range(len(df_topic)): for index, tag in enumerate(list(df_topic.loc[i,'Tags'])): if tag in d_new: df_topic.loc[i, 'Tags'][index] = 0 #df_topic.loc[i,'Tags'] = [0 if j in d_new else j for j in df_topic.loc[i, 'Tags']] for i in range(len(df_topic)): for index, tag in enumerate(list(df_topic.loc[i,'Tags'])): if tag in d_new: df_topic.loc[i, 'Tags'][index] = 0 #df_topic.loc[i,'Tags'] = [0 if j in d_new else j for j in df_topic.loc[i, 'Tags']] k = 1 while k: try: df_topic.loc[i, 'Tags'].remove(0) except: k = 0 for i in range(len(df_topic)): if len(df_topic.loc[i,'Tags']) == 0: df_topic = df_topic.drop(i) X, Y = df_topic['Text'].values, df_topic['Tags'].values df_topic = df_topic.reset_index(drop=True) d_tags = {} for i in range(len(df_topic)): for j in df_topic.loc[i, 'Tags']: if j in d_tags: d_tags[j] += 1 else: d_tags[j] = 1 REPLACE_BY_SPACE_RE = re.compile('[/(){}\[\]\|@,;]') BAD_SYMBOLS_RE = re.compile('[^0-9a-z #+_]') STOPWORDS = set(stopwords.words('english')) def text_prepare(text): text = text.lower() # lowercase text text = text.replace("\n", " ") text = REPLACE_BY_SPACE_RE.sub(' ', text) # replace REPLACE_BY_SPACE_RE symbols by space in text text =BAD_SYMBOLS_RE.sub('', text) # delete symbols which are in BAD_SYMBOLS_RE from text text = ' '.join([word for word in text.split() if word not in STOPWORDS]) # delete stopwors from text text = text.strip() return text X = [text_prepare(x) for x in X] X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.1, random_state = 1145) tags_counts = {} # Dictionary of all words from train corpus with their counts. words_counts = {} words_counts = Counter([word for line in X for word in line.split(' ')]) most_common_words = sorted(words_counts.items(), key=lambda x: x[1], reverse=True) DICT_SIZE = 5000 WORDS_TO_INDEX = {p[0]:i for i,p in enumerate(most_common_words[:DICT_SIZE])} INDEX_TO_WORDS = {WORDS_TO_INDEX[k]:k for k in WORDS_TO_INDEX} ALL_WORDS = WORDS_TO_INDEX.keys() def my_bag_of_words(text, words_to_index, dict_size): result_vector = np.zeros(dict_size) for word in text.split(): if word in words_to_index: result_vector[words_to_index[word]]+=1 return result_vector X_train_mybag = sp_sparse.vstack([sp_sparse.csr_matrix(my_bag_of_words(text, WORDS_TO_INDEX, DICT_SIZE)) for text in X_train]) X_test_mybag = sp_sparse.vstack([sp_sparse.csr_matrix(my_bag_of_words(text, WORDS_TO_INDEX, DICT_SIZE)) for text in X_test]) print('X_train shape ', X_train_mybag.shape) print('X_test shape ', X_test_mybag.shape) def tfidf_features(X_train, X_test): tfidf_vectorizer = TfidfVectorizer(token_pattern='(\S+)', min_df=5, max_df=0.9, ngram_range=(1,2)) tfidf_vectorizer.fit(X_train) X_train = tfidf_vectorizer.transform(X_train) X_test = tfidf_vectorizer.transform(X_test) return X_train, X_test, tfidf_vectorizer.vocabulary_ X_train_tfidf, X_test_tfidf, tfidf_vocab = tfidf_features(X_train, X_test) tfidf_reversed_vocab = {i:word for word,i in tfidf_vocab.items()} filename = open("topics_vocabulary.pkl", "wb") pickle.dump(tfidf_vocab, filename) filename.close() """Create the dictionary of tags and their counts. """ d_new_reversed = list({k: v for k, v in d.items() if v > 30}.keys()) mlb = MultiLabelBinarizer(classes=sorted(d_new_reversed)) y_train = mlb.fit_transform(Y_train) y_test = mlb.fit_transform(Y_test) pkl_filename = "binarizer.pkl" with open(pkl_filename, 'wb') as file: pickle.dump(mlb, file) def train_classifier(X_train, y_train,C=2.0,penalty='l2'): # Create and fit LogisticRegression wrapped into OneVsRestClassifier. lr = DecisionTreeClassifier() ovr = OneVsRestClassifier(lr) ovr.fit(X_train, y_train) return ovr classifier_mybag = train_classifier(X_train_mybag, y_train) classifier_tfidf = train_classifier(X_train_tfidf, y_train) y_val_predicted_labels_tfidf = classifier_tfidf.predict(X_test_tfidf) y_val_predicted_labels_mybag = classifier_mybag.predict(X_test_mybag) y_val_pred_inversed = mlb.inverse_transform(y_val_predicted_labels_tfidf) y_val_inversed = mlb.inverse_transform(y_test) for i in range(15): print('Title:\t{}\nTrue labels:\t{}\nPredicted labels:\t{}\n\n'.format( X_test[i], ','.join(y_val_inversed[i]), ','.join(y_val_pred_inversed[i]) )) def print_evaluation_scores(y_val, predicted): accuracy=accuracy_score(y_val,predicted) f1_macro=f1_score(y_val,predicted,average='macro') f1_micro=f1_score(y_val,predicted,average='micro') f1_weighted=f1_score(y_val,predicted,average='weighted') precision_macro=average_precision_score(y_val,predicted,average='macro') precision_micro=average_precision_score(y_val,predicted,average='micro') precision_weighted=average_precision_score(y_val,predicted,average='weighted') print(accuracy) print('Bag-of-words') print_evaluation_scores(y_test, y_val_predicted_labels_mybag) print('Tfidf') print_evaluation_scores(y_test, y_val_predicted_labels_tfidf) pkl_filename = "topic_recognition_model.pkl" with open(pkl_filename, 'wb') as file: pickle.dump(classifier_tfidf, file)
2907402a9b675f4b7f3cababaddfba9604c84141
[ "Markdown", "Python", "Text", "Shell" ]
17
Python
dushesms/Writing-Aid
45abc68760546d5f1db7f08b47d2f6795a381607
c9a6476d8860c7e892f1e14c8d6a95931a2da4fa
refs/heads/master
<file_sep> #include "stdafx.h" #include "telegram_connector.h" #include "custom_STRING.h" #include "json/json.h" #define API_URL "https://api.telegram.org/bot" #define GET_ME "/getme" #define GET_UPDATES "/getUpdates" #define SEND_MESSAGE "/sendMessage?" namespace Main { string TelegramConnector::_last_message; string TelegramConnector::_bot_identity; FILE* TelegramConnector::_file[TYPE_COUNT]; //////////////////////////////////////////////////////////////////////////////////////////////// //! //////////////////////////////////////////////////////////////////////////////////////////////// TelegramConnector::TelegramConnector() : _curl(nullptr), _last_update(0) { } //////////////////////////////////////////////////////////////////////////////////////////////// //! //////////////////////////////////////////////////////////////////////////////////////////////// BOOL TelegramConnector::initialize(VOID) { _curl = curl_easy_init(); if (nullptr == _curl) { return false; } char current_dir[1024] = { 0, }; GetCurrentDirectoryA(1024, current_dir); string file_name = current_dir; file_name.append("\\"); file_name.append("bot_seq.txt"); char buffer[1024] = { 0, }; _file[SEQ_FILE] = fopen(file_name.c_str(), "a+"); fread(buffer, 1, 1024, _file[SEQ_FILE]); _last_update = atoi(buffer); file_name = current_dir; file_name.append("\\"); file_name.append("bot_id.txt"); _file[ID_FILE] = fopen(file_name.c_str(), "a+"); fgets(buffer, 1024, _file[ID_FILE]); _bot_identity = buffer; // Get Me string recv_data; string request = API_URL; request.append(_bot_identity); request.append(GET_ME); curl_easy_setopt(_curl, CURLOPT_URL, request.c_str()); curl_easy_setopt(_curl, CURLOPT_SSL_VERIFYPEER, false); curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, http_init_data); curl_easy_setopt(_curl, CURLOPT_WRITEDATA, recv_data); const CURLcode result = curl_easy_perform(_curl); if (CURLE_OK != result) { cerr << "Error from cURL: " << curl_easy_strerror(result) << endl; return false; } send_message(91271537, "시작합니다."); return true; } //////////////////////////////////////////////////////////////////////////////////////////////// //! //////////////////////////////////////////////////////////////////////////////////////////////// VOID TelegramConnector::close(VOID) { if (nullptr != _curl) { curl_easy_cleanup(_curl); } fclose(_file[SEQ_FILE]); fclose(_file[ID_FILE]); } //////////////////////////////////////////////////////////////////////////////////////////////// //! //////////////////////////////////////////////////////////////////////////////////////////////// VOID TelegramConnector::monitor(VOID) { parse_string(); string recv_data; string request = API_URL; request.append(_bot_identity); request.append(GET_UPDATES); curl_easy_setopt(_curl, CURLOPT_URL, request.c_str()); curl_easy_setopt(_curl, CURLOPT_SSL_VERIFYPEER, false); curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, http_receive_data); curl_easy_setopt(_curl, CURLOPT_WRITEDATA, recv_data); const CURLcode result = curl_easy_perform(_curl); if (CURLE_OK != result) { cerr << "Error from cURL: " << curl_easy_strerror(result) << endl; } } //////////////////////////////////////////////////////////////////////////////////////////////// //! //////////////////////////////////////////////////////////////////////////////////////////////// VOID TelegramConnector::update_last_seq(INT32 seq_in) { _last_update = seq_in; } //////////////////////////////////////////////////////////////////////////////////////////////// //! //////////////////////////////////////////////////////////////////////////////////////////////// BOOL TelegramConnector::validate_last_seq(INT32 seq_in) { if (_last_update < seq_in) return true; return false; } //////////////////////////////////////////////////////////////////////////////////////////////// //! //////////////////////////////////////////////////////////////////////////////////////////////// VOID TelegramConnector::send_message(INT32 chat_id_in, string message_in) { string request = API_URL; request.append(_bot_identity); request.append(SEND_MESSAGE); message_in = CustomString::AnsiToUTF8(message_in); string encoding_STRING = CustomString::replace_all(message_in, "\n", "%20"); request += "chat_id=" + std::to_string(chat_id_in) + "&"; request += "text=" + encoding_STRING; curl_easy_reset(_curl); curl_easy_setopt(_curl, CURLOPT_URL, request.c_str()); curl_easy_setopt(_curl, CURLOPT_SSL_VERIFYPEER, false); curl_easy_setopt(_curl, CURLOPT_FORBID_REUSE, true); curl_easy_setopt(_curl, CURLOPT_FRESH_CONNECT, true); const CURLcode result = curl_easy_perform(_curl); if (CURLE_OK != result) { cerr << "Error from cURL: " << curl_easy_strerror(result) << endl; } } //////////////////////////////////////////////////////////////////////////////////////////////// //! //////////////////////////////////////////////////////////////////////////////////////////////// SIZE_T TelegramConnector::http_init_data(char* contents, SIZE_T size, SIZE_T nmemb, VOID* user_data) { string contents_str = contents; cout << contents_str.c_str() << endl; Json::Reader reader; Json::Value root; if (!reader.parse(contents_str, root)) { cerr << "failed read json result!!" << endl; } Json::Value result = root["result"]; cout << "id: " << CustomString::UTF8ToAnsi(result["id"].asString()) << endl; cout << "first name: " << CustomString::UTF8ToAnsi(result["first_name"].asString()) << endl; cout << "user name: " << CustomString::UTF8ToAnsi(result["username"].asString()) << endl; return size * nmemb; } //////////////////////////////////////////////////////////////////////////////////////////////// //! //////////////////////////////////////////////////////////////////////////////////////////////// SIZE_T TelegramConnector::http_receive_data(char* contents, SIZE_T size, SIZE_T nmemb, VOID* user_data) { _last_message = contents; string contents_str = contents; return size * nmemb; } //////////////////////////////////////////////////////////////////////////////////////////////// //! //////////////////////////////////////////////////////////////////////////////////////////////// VOID TelegramConnector::parse_string(VOID) { Json::Reader reader; Json::Value root; if (!reader.parse(_last_message, root, false)) { cerr << "failed read json result!!" << endl; return; } Json::Value result = root["result"]; int update_id = 0; for (auto ii : result) { update_id = ii["update_id"].asInt(); if (!validate_last_seq(update_id)) { update_id = 0; continue; } cout << "update id: " << ii["update_id"] << endl; Json::Value message = ii["message"]; cout << "message id: " << message["message_id"] << endl; Json::Value chat = message["chat"]; cout << "chat id: " << chat["id"] << endl; string msg = CustomString::UTF8ToAnsi(message["text"].asString()); cout << "message: " << msg << endl; parse_command(msg); update_last_seq(update_id); } if (0 != update_id) { fpos_t position = 0; fsetpos(_file[SEQ_FILE], &position); string seq = to_string(update_id); fputs(seq.c_str(), _file[SEQ_FILE]); fflush(_file[SEQ_FILE]); } return VOID(); } //////////////////////////////////////////////////////////////////////////////////////////////// //! //////////////////////////////////////////////////////////////////////////////////////////////// VOID TelegramConnector::parse_command(string & command) { SIZE_T pos = string::npos; command = CustomString::ltrim(command); if (command[0] != '/') return; pos = command.find(" "); string cmd = command.substr(1, pos); if ("search" == cmd) { string argument = command.substr(pos + 1); cerr << cmd << ", " << argument << endl; } return VOID(); } }<file_sep>/////////////////////////////////////////////////////////////////////////// //! @file telegram_connector.h //! @brief 텔레그램과 통신을 하는 커넥터. //! @author sehyun, cho /////////////////////////////////////////////////////////////////////////// #pragma once #include "singleton.h" #include "libcurl\include\curl.h" namespace Main { enum FILE_TYPE { SEQ_FILE, ID_FILE, TYPE_COUNT }; /////////////////////////////////////////////////////////////////////////// //! @class TelegramConnector //! @brief 싱글턴으로서 텔레그램과 통신을 하기 위한 모듈. //! /////////////////////////////////////////////////////////////////////////// class TelegramConnector : public Singleton<TelegramConnector> { public: //! @brief 생성자 TelegramConnector(); public: //! @brief 초기화 함수 //! @return 성공시, true BOOL initialize(VOID); //! @brief 종료 함수 VOID close(VOID); public: //! @brief 모니터링 루프 VOID monitor(VOID); //! @brief 메세지를 텔레그램으로 보낸다. //! @param chat_id_in[IN] 보낼 채팅방의 아이디 //! @param message_in[IN] 보낼 메세지. 이는 encoding 이 완료된 메세지어야 함. VOID send_message(INT32 chat_id_in, string message_in); public: //! @brief GET/SET Functions VOID update_last_seq(INT32 seq_in); BOOL validate_last_seq(INT32 seq_in); VOID update_last_message(const string& message_in) { _last_message = message_in; } protected: //! @brief 텔레그램으로부터 도착한 메세지를 처리하기 위한 콜백. 초기화 메세지를 처리함. //! @param contents_in[IN] 도착한 메세지 포인터 //! @param size_in[IN] 메세지의 데이터 타입 크기 //! @param nmemb_in[IN] 메세지의 길이 //! @param user_data_in[IN] static SIZE_T http_init_data(char* contents_in, SIZE_T size_in, SIZE_T nmemb_in, VOID* user_data_in); static SIZE_T http_receive_data(char* contents_in, SIZE_T size_in, SIZE_T nmemb_in, VOID* user_data_in); VOID parse_string(VOID); VOID parse_command(string& command); private: CURL* _curl; INT32 _last_update; static string _last_message; static FILE* _file[TYPE_COUNT]; static string _bot_identity; }; }<file_sep>#include "stdafx.h" #include "custom_string.h" #include "libcurl/include/curl.h" const char HEX2DEC[256] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ /* 0 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 1 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 2 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 3 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1, /* 4 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 5 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 6 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 7 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 8 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* 9 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* A */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* B */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* C */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* D */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* E */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, /* F */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1 }; const char SAFE[256] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ /* 0 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* 1 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* 2 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* 3 */ 1,1,1,1, 1,1,1,1, 1,1,0,0, 0,0,0,0, /* 4 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, /* 5 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0, /* 6 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, /* 7 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0, /* 8 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* 9 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* A */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* B */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* C */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* D */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* E */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, /* F */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }; string CustomString::trim(__in string& s, __in const string& drop /*= " " */) { string r = s.erase(s.find_last_not_of(drop) + 1); return r.erase(0, r.find_first_not_of(drop)); } string CustomString::rtrim(__in string s, __in const string& drop /*= " " */) { string r = s.erase(s.find_last_not_of(drop) + 1); return r; } string CustomString::ltrim(__in string s, __in const string& drop /*= " " */) { string r = s.erase(0, s.find_first_not_of(drop)); return r; } string CustomString::trim_custom(__in string& s, __in const string& drop /*= " " */) { string r = s.erase(0, s.find_first_not_of(" ")); r = r.erase(0, r.find_first_not_of("\n")); r = r.erase(r.find_last_not_of(drop) + 1); r = r.erase(r.find_last_not_of("\n") + 1); r = CustomString::replace_all(r, "\n \n", "\n"); r = CustomString::replace_all(r, "\n\n", "\n"); return r.erase(0, r.find_first_not_of(drop)); } string CustomString::replace_all(__in const string &message, __in const string &pattern, __in const string &replace) { string result = message; string::size_type pos = 0; string::size_type offset = 0; while ((pos = result.find(pattern, offset)) != string::npos) { result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace); offset = pos + replace.size(); } return result; } string CustomString::urlencode(__in const string &source) { string result_string; char hex[4]; for (const char &c : source) { if ((c > 47 && c < 57) || (c > 64 && c < 92) || (c > 96 && c < 123) || c == '-' || c == '.' || c == '_') result_string += c; else { sprintf_s(hex, "%%%02X", (unsigned char)c); result_string.append(hex); } } return result_string; } string CustomString::urldecode(__in const string &source) { // Note from RFC1630: "Sequences which start with a percent // sign but are not followed by two hexadecimal characters // (0-9, A-F) are reserved for future extension" const unsigned char * pSrc = (const unsigned char *)source.c_str(); const int SRC_LEN = source.length(); const unsigned char * const SRC_END = pSrc + SRC_LEN; // last decodable '%' const unsigned char * const SRC_LAST_DEC = SRC_END - 2; char * const pStart = new char[SRC_LEN]; char * pEnd = pStart; while (pSrc < SRC_LAST_DEC) { if (*pSrc == '%') { char dec1, dec2; if (-1 != (dec1 = HEX2DEC[*(pSrc + 1)]) && -1 != (dec2 = HEX2DEC[*(pSrc + 2)])) { *pEnd++ = (dec1 << 4) + dec2; pSrc += 3; continue; } } *pEnd++ = *pSrc++; } // the last 2- chars while (pSrc < SRC_END) *pEnd++ = *pSrc++; string sResult(pStart, pEnd); delete[] pStart; return sResult; } // string UriEncode( const string & sSrc ) // { // const char DEC2HEX[16 + 1] = "0123456789ABCDEF"; // const unsigned char * pSrc = (const unsigned char *)sSrc.c_str(); // const int SRC_LEN = sSrc.length(); // unsigned char * const pStart = new unsigned char[SRC_LEN * 3]; // unsigned char * pEnd = pStart; // const unsigned char * const SRC_END = pSrc + SRC_LEN; // // for ( ; pSrc < SRC_END; ++pSrc ) // { // if ( SAFE[*pSrc] ) // *pEnd++ = *pSrc; // else // { // // escape this char // *pEnd++ = '%'; // *pEnd++ = DEC2HEX[*pSrc >> 4]; // *pEnd++ = DEC2HEX[*pSrc & 0x0F]; // } // } // // string sResult( (char *)pStart, (char *)pEnd ); // delete[] pStart; // return sResult; // } string CustomString::urlencode2(__in const string &source) { string result_string; char hex[6]; for (const char &c : source) { if ((c > 47 && c < 57) || (c > 64 && c < 92) || (c > 96 && c < 123) || c == '-' || c == '.' || c == '_') result_string += c; else { sprintf_s(hex, "%%25%02X", c); result_string.append(hex); } } return result_string; } string CustomString::UTF8ToAnsi(__in string _in) { string result; int nLength = MultiByteToWideChar(CP_UTF8, 0, _in.c_str(), _in.length() + 1, NULL, NULL); BSTR bstrWide = SysAllocStringLen(NULL, nLength); MultiByteToWideChar(CP_UTF8, 0, _in.c_str(), _in.length() + 1, bstrWide, nLength); nLength = WideCharToMultiByte(CP_ACP, 0, bstrWide, -1, NULL, 0, NULL, NULL); char *pszAnsi = new char[nLength]; WideCharToMultiByte(CP_ACP, 0, bstrWide, -1, pszAnsi, nLength, NULL, NULL); SysFreeString(bstrWide); result = pszAnsi; delete[] pszAnsi; return result; } string CustomString::AnsiToUTF8(__in string _in) { string result; int nLength, nLength2; BSTR bstrCode; char* pszUTFCode = NULL; nLength = MultiByteToWideChar(CP_ACP, 0, _in.c_str(), lstrlenA(_in.c_str()) + 1, NULL, NULL); bstrCode = SysAllocStringLen(NULL, nLength); memset(bstrCode, 0, nLength + 2); MultiByteToWideChar(CP_ACP, 0, _in.c_str(), lstrlenA(_in.c_str()) + 1, bstrCode, nLength); nLength2 = WideCharToMultiByte(CP_UTF8, 0, bstrCode, -1, pszUTFCode, 0, NULL, NULL); pszUTFCode = new char[nLength2 + 1]; memset(pszUTFCode, 0, nLength2 + 1); WideCharToMultiByte(CP_UTF8, 0, bstrCode, -1, pszUTFCode, nLength2, NULL, NULL); result = pszUTFCode; delete[] pszUTFCode; return result; } <file_sep>#pragma once #include <string> class CustomString { public: static string trim(__in string& s, __in const string& drop = " "); static string rtrim(__in string s, __in const string& drop = " "); static string ltrim(__in string s, __in const string& drop = " "); static string trim_custom(__in string& s, __in const string& drop); static string replace_all(__in const string &message, __in const string &pattern, __in const string &replace); static string urlencode(__in const string &source); static string urldecode(__in const string &source); static string urlencode2(__in const string &source); static string UTF8ToAnsi(__in string _in); static string AnsiToUTF8(__in string _in); }; <file_sep>// telegram_bot.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "telegram_connector.h" ////////////////////////////////////////////////////////////////////////// #if _MSC_VER >= 1900 # pragma comment(lib, "legacy_stdio_definitions.lib") FILE _iob[] = { *stdin, *stdout, *stderr }; extern "C" FILE * __cdecl __iob_func(void) { return _iob; } #endif ////////////////////////////////////////////////////////////////////////// using namespace Main; int main() { curl_global_init(CURL_GLOBAL_ALL); TelegramConnector::instance()->initialize(); while (true) { TelegramConnector::instance()->monitor(); Sleep(1000); } TelegramConnector::instance()->close(); curl_global_cleanup(); TelegramConnector::desctroy(); return 0; } <file_sep>// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #include <stdio.h> #include <tchar.h> // TODO: reference additional headers your program requires here #pragma comment( lib, "ws2_32.lib" ) #pragma comment( lib, "wldap32.lib" ) #if defined(_DEBUG) # pragma comment(lib, "libeay32MTd.lib") # pragma comment(lib, "ssleay32MTd.lib") # pragma comment(lib, "libcurld.lib") #else # pragma comment(lib, "libcurl32MT.lib") #endif #include <iostream> #include <string> using namespace std; typedef std::basic_string<TCHAR> STRING; <file_sep> #pragma once template <typename T> class Singleton { protected: Singleton() { } ~Singleton() { } public: static T* instance(void) { if (nullptr == _instance) _instance = new T; return _instance; } static void desctroy(void) { if (nullptr != _instance) delete _instance; _instance = nullptr; } private: static T* _instance; }; template<typename T> T* Singleton<T>::_instance = nullptr;<file_sep>======================================================================== CONSOLE APPLICATION : telegram_bot Project Overview ======================================================================== AppWizard has created this telegram_bot application for you. This file contains a summary of what you will find in each of the files that make up your telegram_bot application. telegram_bot.vcxproj This is the main project file for VC++ projects generated using an Application Wizard. It contains information about the version of Visual C++ that generated the file, and information about the platforms, configurations, and project features selected with the Application Wizard. telegram_bot.vcxproj.filters This is the filters file for VC++ projects generated using an Application Wizard. It contains information about the association between the files in your project and the filters. This association is used in the IDE to show grouping of files with similar extensions under a specific node (for e.g. ".cpp" files are associated with the "Source Files" filter). telegram_bot.cpp This is the main application source file. ///////////////////////////////////////////////////////////////////////////// Other standard files: StdAfx.h, StdAfx.cpp These files are used to build a precompiled header (PCH) file named telegram_bot.pch and a precompiled types file named StdAfx.obj. ///////////////////////////////////////////////////////////////////////////// Other notes: AppWizard uses "TODO:" comments to indicate parts of the source code you should add to or customize. ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// Code Convention 1. 기본적으로 소문자 + 언더바로 표기한다. 2. 클래스명은 예외적으로 낙타를 사용한다.(C로 시작하지 말것.) 3. 함수명 및 변수의 맴버 여부는 앞의 언더바로 구분한다. 4. 함수 인자의 경우는 _in, _out 을 끝에 붙여서 인자의 성격을 알려준다. 5. TCHAR 를 기본으로 사용한다.(이와 관련된 API 들도 모두 포함.) string의 경우 typedef basic_string<TCHAR> string 을 사용한다. 6. 데이터 타입은 윈도우 표준인 대문자로 사용한다.(INT8, INT16, INT32, INT64, 등등) 7. doxygen 형식의 주석으로 코드를 문서화 한다. /////////////////////////////////////////////////////////////////////////////
263463d5a393bdd937aadbc4a4b19467dec1936e
[ "Text", "C++" ]
8
C++
sehyuns/telegram_bot
a631b19df26830e64e809bbc42f183cbc55f18c4
becb93ee5afa8cbdfeeca239f77075e69b4680a7
refs/heads/master
<file_sep>package com.ontotext.cesparenttreefilter.service; import com.ontotext.cesparenttreefilter.util.ResourceUtil; import com.ontotext.docio.DocumentIOException; import com.ontotext.docio.DocumentIOJson; import com.ontotext.docio.model.Document; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; /** **/ public class CESParentTreeFilterService { public static final String CONTENT_JSON_FILENAME = "document/chp-generic-doc_xpected.GENERIC_DOCUMENT_JSON_VALUE.json"; public static final String CONTENT_JSON = ResourceUtil.getResourceFileAsString(CONTENT_JSON_FILENAME); public Document contentDocument; public CESParentTreeFilterService() { DocumentIOJson jsonDoc = new DocumentIOJson(); try { contentDocument = jsonDoc.read(new ByteArrayInputStream(CONTENT_JSON.getBytes(StandardCharsets.UTF_8))); } catch (DocumentIOException dioe) { throw new RuntimeException(dioe); } } public Document getContentDocument() { return this.contentDocument; } } <file_sep>#!/usr/bin/env bash java -jar target/cesparenttreefilter-0.0.1-SNAPSHOT.jar server cesparenttreefilter-comfiguration.yml<file_sep>FROM centos RUN \ yum update -y && \ yum install -y java-1.8.0-openjdk && \ yum install -y wget && \ mkdir -p /data/ces-filter-parent-tree-api \ mkdir -p /data/ces-filter-parent-tree-api/work \ mkdir -p /data/ces-filter-parent-tree-api/target WORKDIR data/ces-filter-parent-tree-api COPY start.sh /data/ces-filter-parent-tree-api COPY target/cesparenttreefilter-0.0.1-SNAPSHOT.jar /data/ces-filter-parent-tree-api/target COPY cesparenttreefilter-comfiguration.yml /data/ces-filter-parent-tree-api EXPOSE 9107 EXPOSE 9108 ENV JAVA_HOME /usr/lib/jvm/jre-1.8.0-openjdk CMD /data/ces-filter-parent-tree-api/start.sh<file_sep>CES ParentTree Mock API = Very, very simple and dumb CES ParentTree Mock API. Echos CES document request with additional prefLabelTree features of the form: ``` { "name": { "type": "XS_STRING", "name": "prefLabelTree" }, "value": { "type": "XS_STRING", "lang": null, "value": "/mock/pref/label/tree/here" } } ``` # Quick REST test ``` docker-compose up -d ``` ## For swagger documentation ``` http://localhost:9108/swagger ``` ## Curl Requests ### Request ``` curl -X POST --header 'Content-Type: application/vnd.ontotext.ces.document+json; charset=utf-8' --header 'Accept: application/vnd.ontotext.ces+json' -d '{ "id":"http://www.platts.com/chp/data/doc1", "feature-set":[ ], "document-parts":{ "feature-set":[ { "name":{ "type":"XS_STRING", "name":"isDebugMode" }, "value":{ "type":"XS_BOOLEAN", "lang":null, "value":"false" } }, { "name":{ "type":"XS_STRING", "name":"encoding" }, "value":{ "type":"XS_STRING", "lang":null, "value":"UTF-8" } } ], "document-part":[ { "feature-set":[ ], "id":"1", "part":"HEADLINE", "content":{ "text":" US beats Argentina to win men\u0027s volleyball World Cup ", "node":[ { "id":"12", "offset":12 }, { "id":"21", "offset":21 } ] } }, { "feature-set":[ ], "id":"2", "part":"BODY", "content":{ "text":" TOKYO (AP) — The United States won its first men\u0027s volleyball World Cup in 30 years on Wednesday with a 25-20, 25-21, 17-25, 25-20 win over Argentina. <NAME> scored 18 points as the U.S. team won the\n event for the first time since 1985 and secured a berth at the Olympics in Rio de Janeiro. \"It\u0027s a stressful challenge for any coach to qualify for the Olympics,\" U.S. coach <NAME> said. \"I thought our serve was good throughout the tournament and our\n blocking got better as we went along.\" Italy also wrapped up an Olympic spot by finishing second with a 26-24, 22-25, 25-22, 25-19 win over world champion Poland, which lost its first match and finished third. \n The United States, Italy and Poland all finished with 10 wins and one loss. The final ranking was determined by fewest sets lost. <NAME> of the U.S. finished the\n tournament with 172 points and was named MVP. Defending champion Russia beat host Japan 27-29, 25-17, 21-25, 25-17, 15-13 to finish fourth. 273\n Russia Japan 1 29 2 25 17 21 25 4 25 17 Some bold text. Some italics text. Some underlined text. \n Some strikethrough text. Item 1 Item 2 Item 3 Link to google. ", "node":[ { "id":"64", "offset":3 }, { "id":"69", "offset":8 }, { "id":"81", "offset":20 }, { "id":"94", "offset":33 }, { "id":"204", "offset":143 }, { "id":"213", "offset":152 }, { "id":"222", "offset":161 }, { "id":"234", "offset":173 }, { "id":"356", "offset":295 }, { "id":"382", "offset":321 }, { "id":"687", "offset":626 }, { "id":"698", "offset":637 }, { "id":"831", "offset":770 }, { "id":"836", "offset":775 }, { "id":"932", "offset":871 }, { "id":"953", "offset":892 }, { "id":"1029", "offset":968 }, { "id":"1042", "offset":981 }, { "id":"1044", "offset":983 }, { "id":"1049", "offset":988 }, { "id":"1054", "offset":993 }, { "id":"1060", "offset":999 }, { "id":"1433", "offset":1372 }, { "id":"1446", "offset":1385 }, { "id":"1814", "offset":1753 }, { "id":"1817", "offset":1756 }, { "id":"1826", "offset":1765 }, { "id":"1851", "offset":1790 } ] } } ] }, "annotation-sets":[ { "name":"Final", "ref":null, "annotation":[ { "feature-set":[ { "name":{ "type":"XS_STRING", "name":"overallScore" }, "value":{ "type":"XS_DOUBLE", "lang":null, "value":"0.55520644166736" } }, { "name":{ "type":"XS_STRING", "name":"confidence" }, "value":{ "type":"XS_DOUBLE", "lang":null, "value":"0.7550477262559766" } }, { "name":{ "type":"XS_STRING", "name":"inst" }, "value":{ "type":"XS_STRING", "lang":null, "value":"http://data.platts.com/Port/London" } }, { "name":{ "type":"XS_STRING", "name":"class" }, "value":{ "type":"XS_STRING", "lang":null, "value":"http://www.w3.org/2004/02/skos/core#Concept" } }, { "name":{ "type":"XS_STRING", "name":"relevanceScore" }, "value":{ "type":"XS_DOUBLE", "lang":null, "value":"0.35536515707874333" } } ], "id":"1420", "startnode":"687", "endnode":"698", "type":"Location", "status":"Suggested", "generated":true } ] } ] } ' 'http://localhost:9108/worker/extract?debug=false' ``` #### Response ``` { "id": "http://www.platts.com/chp/data/doc1", "feature-set": [], "document-parts": { "feature-set": [ { "name": { "type": "XS_STRING", "name": "isDebugMode" }, "value": { "type": "XS_BOOLEAN", "lang": null, "value": "false" } }, { "name": { "type": "XS_STRING", "name": "encoding" }, "value": { "type": "XS_STRING", "lang": null, "value": "UTF-8" } } ], "document-part": [ { "feature-set": [], "id": "1", "part": "HEADLINE", "content": { "text": "<p>US beats Argentina to win men's volleyball World Cup</p>", "node": [ { "id": "12", "offset": 12 }, { "id": "21", "offset": 21 } ] } }, { "feature-set": [], "id": "2", "part": "BODY", "content": { "text": "<p>TOKYO (AP) — The United States won its first men's volleyball World Cup in 30 years on Wednesday with a 25-20, 25-21, 17-25, 25-20 win over Argentina.</p> <p><NAME> scored 18 points as the U.S. team won the\n event for the first time since 1985 and secured a berth at the Olympics in Rio de Janeiro.<chpembed class=\"hoverable\" title=\"Picture\" contents=\"DEMOMMGLLINK000000000942\" link=\"DEMOMMGLLINK000000000942\" source=\"DEMOMMGLPICT000000023097\"\n type=\"chpembed-image\" version=\"c\"></chpembed>&nbsp;</p> <p>\"It's a stressful challenge for any coach to qualify for the Olympics,\" U.S. coach <NAME> said. \"I thought our serve was good throughout the tournament and our\n blocking got better as we went along.\"</p> <p>Italy also wrapped up an Olympic spot by finishing second with a 26-24, 22-25, 25-22, 25-19 win over world champion Poland, which lost its first match and finished third.</p>\n <p>The United States, Italy and Poland all finished with 10 wins and one loss. The <a class=\"inlinenotes_production\" title=\"1. Production Administrator 2016-03-15 12:28, This is an example of an annotation.\" modifiedat=\"2016-03-15 12:28\"\n modifiedby=\"Administrator\" notehtmlcontent=\"This is an example of an annotation.\" noteindex=\"1\">final ranking</a> was determined by fewest sets lost.</p> <p><NAME> of the U.S. <a class=\"inlinenotes_productionstrike\"\n title=\"2. Production strikethrough Administrator 2016-03-15 12:28, Another example of an annotation.\" modifiedat=\"2016-03-15 12:28\" modifiedby=\"Administrator\" notehtmlcontent=\"Another example of an annotation.\" noteindex=\"2\">finished the\n tournament</a> with 172 points and was named MVP.</p> <p>Defending champion Russia beat host Japan 27-29, 25-17, 21-25, 25-17, 15-13 to finish fourth.</p> <p>&nbsp;</p> <table border=\"1\" cellspacing=\"0\"\n cellpadding=\"0\"> <tbody> <tr> <td width=\"200px\"><br></td><td width=\"200px\">Russia</td><td width=\"200px\">Japan</td></tr> <tr> <td width=\"200px\">1</td><td\n width=\"200px\">27</td><td width=\"200px\">29</td> </tr> <tr> <td width=\"200px\">2</td><td width=\"200px\">25</td><td width=\"200px\">17</td> </tr> <tr> <td\n width=\"200px\">3</td><td width=\"200px\">21</td><td width=\"200px\">25</td> </tr> <tr> <td width=\"200px\">4</td><td width=\"200px\">25</td><td width=\"200px\">17</td> </tr>\n </tbody> </table> <p>&nbsp;</p> <p><strong>Some bold text.</strong></p> <p><em>Some italics text.</em></p> <p><u>Some underlined text.</u></p>\n <p><strike>Some strikethrough text.</strike></p> <p>&nbsp;</p> <ul> <li>Item 1</li><li>Item 2</li><li>Item 3</li> </ul> <p>Link to <a\n title=\"http://www.google.com\" href=\"http://www.google.com\" target=\"_blank\">google</a>.</p>", "node": [ { "id": "64", "offset": 3 }, { "id": "69", "offset": 8 }, { "id": "81", "offset": 20 }, { "id": "94", "offset": 33 }, { "id": "204", "offset": 143 }, { "id": "213", "offset": 152 }, { "id": "222", "offset": 161 }, { "id": "234", "offset": 173 }, { "id": "356", "offset": 295 }, { "id": "382", "offset": 321 }, { "id": "687", "offset": 626 }, { "id": "698", "offset": 637 }, { "id": "831", "offset": 770 }, { "id": "836", "offset": 775 }, { "id": "932", "offset": 871 }, { "id": "953", "offset": 892 }, { "id": "1029", "offset": 968 }, { "id": "1042", "offset": 981 }, { "id": "1044", "offset": 983 }, { "id": "1049", "offset": 988 }, { "id": "1054", "offset": 993 }, { "id": "1060", "offset": 999 }, { "id": "1433", "offset": 1372 }, { "id": "1446", "offset": 1385 }, { "id": "1814", "offset": 1753 }, { "id": "1817", "offset": 1756 }, { "id": "1826", "offset": 1765 }, { "id": "1851", "offset": 1790 } ] } } ] }, "annotation-sets": [ { "name": "Final", "ref": null, "annotation": [ { "feature-set": [ { "name": { "type": "XS_STRING", "name": "overallScore" }, "value": { "type": "XS_DOUBLE", "lang": null, "value": "0.55520644166736" } }, { "name": { "type": "XS_STRING", "name": "confidence" }, "value": { "type": "XS_DOUBLE", "lang": null, "value": "0.7550477262559766" } }, { "name": { "type": "XS_STRING", "name": "inst" }, "value": { "type": "XS_STRING", "lang": null, "value": "http://data.platts.com/Port/London" } }, { "name": { "type": "XS_STRING", "name": "class" }, "value": { "type": "XS_STRING", "lang": null, "value": "http://www.w3.org/2004/02/skos/core#Concept" } }, { "name": { "type": "XS_STRING", "name": "relevanceScore" }, "value": { "type": "XS_DOUBLE", "lang": null, "value": "0.35536515707874333" } }, { "name": { "type": "XS_STRING", "name": "prefLabelTree" }, "value": { "type": "XS_STRING", "lang": null, "value": "/mock/pref/label/tree/here" } } ], "id": "1420", "startnode": "687", "endnode": "698", "type": "Location", "status": "Suggested", "generated": true } ] } ] } ``` # Docker ## Build ``` docker build . ``` ## Tag ### Get the image id ``` docker images ``` ## Push to quay ### Login ``` docker login -e="." -u="ontotext+ontotext" -p="XXXX" quay.io ``` ### tag ``` docker tag ${IMAGE} cesparenttreefiltermock docker tag ${IMAGE} quay.io/ontotext/cesparenttreefiltermock ``` ### push to quay ``` docker push quay.io/ontotext/cesparenttreefiltermock ``` ## Run Interactive ``` docker run --name cesparenttreefiltermock -it cesparenttreefiltermock /bin/bash ``` ## Run Daemon ``` docker run --name cesparenttreefiltermock -d cesparenttreefiltermock ``` ## Shell to docker container ### Get container ids ``` docker ps -a ``` ``` docker exec -i -t ${CONTAINER_ID} /bin/bash ``` ## Invoke ## Run via docker-compose ### Environment Create a .env file with the correct environment settings ``` SOME_THING=XXX ``` ### Interactive ``` docker-compose up ``` ### Daemon ``` docker-compose up -d
c4d48322d1ffdcd1070f04f4886a140c23bf391b
[ "Markdown", "Java", "Dockerfile", "Shell" ]
4
Java
jazzyray/cesparenttreefilter
601264a1ec30b43a82e5a062f182aba6cb0f626a
c5259ec8d63665db044f0bfc3f417bb60c23d63f
refs/heads/master
<repo_name>rsri/GestureDetector<file_sep>/app/src/main/java/com/srika/gesturedetector/GestureListAdapter.java package com.srika.gesturedetector; import android.content.Context; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Created by manan on 2/2/2015. */ public class GestureListAdapter extends ArrayAdapter<GestureHolder> { private List<GestureHolder> mGestureList; private Context mContext; public GestureListAdapter(ArrayList<GestureHolder> gestureList, Context context) { super(context, R.layout.gestures_list, gestureList); this.mGestureList = gestureList; this.mContext = context; } @NonNull public View getView(int position, View convertView, @NonNull ViewGroup parent) { View v = convertView; GestureViewHolder holder; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = inflater.inflate(R.layout.gesture_list_item, parent, false); // fill the layout with the right values TextView nameView = (TextView) v.findViewById(R.id.gesture_name); ImageView gestureImageView = (ImageView) v.findViewById(R.id.gesture_image); holder = new GestureViewHolder(); holder.gestureName = nameView; holder.gestureImage = gestureImageView; final ImageView mMenuItemButton = (ImageView)v.findViewById(R.id.menu_item_options); mMenuItemButton.setClickable(true); v.setTag(holder); } else { holder = (GestureViewHolder) v.getTag(); } GestureHolder gestureHolder = mGestureList.get(position); holder.gestureName.setText(gestureHolder.getName()); try { holder.gestureImage.setImageBitmap(gestureHolder.getGesture().toBitmap(30, 30, 3, ContextCompat.getColor(getContext(), R.color.colorPrimary))); } catch (Exception e) { e.printStackTrace(); } //holder.gestureImage.setImageResource(R.drawable.ic_launcher); return v; } private class GestureViewHolder { TextView gestureName; ImageView gestureImage; } } <file_sep>/app/src/main/java/com/srika/gesturedetector/GestureActivity.java package com.srika.gesturedetector; import android.gesture.Gesture; import android.gesture.GestureLibraries; import android.gesture.GestureLibrary; import android.gesture.GestureOverlayView; import android.gesture.GestureOverlayView.OnGesturePerformedListener; import android.gesture.GestureStore; import android.gesture.Prediction; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import java.util.ArrayList; public class GestureActivity extends AppCompatActivity { private GestureLibrary gLib; private static final String TAG = "GestureActivity"; private GestureOverlayView mGestureOverlayView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); gLib = GestureLibraries.fromFile(getExternalFilesDir(null) + "/" + "gesture.txt"); gLib.setSequenceType(GestureStore.SEQUENCE_INVARIANT); gLib.load(); mGestureOverlayView = (GestureOverlayView) findViewById(R.id.gestures); mGestureOverlayView.addOnGesturingListener(mGesturingListener); // gestureOverlayView.addOnGestureListener(mGestureListener); // gestureOverlayView.addOnGesturePerformedListener(handleGestureListener); mGestureOverlayView.setGestureStrokeAngleThreshold(90.0f); // gestureOverlayView.setGestureStrokeLengthThreshold(20); } GestureOverlayView.OnGesturingListener mGesturingListener = new GestureOverlayView.OnGesturingListener() { private boolean started = false; private Runnable clearRunnable = new Runnable() { @Override public void run() { if (!started && !mGestureOverlayView.isGesturing()) { mGestureOverlayView.clear(false); } } }; @Override public void onGesturingStarted(GestureOverlayView overlay) { overlay.removeCallbacks(clearRunnable); started = true; } @Override public void onGesturingEnded(final GestureOverlayView gestureView) { predict(gestureView.getGesture()); started = false; gestureView.postDelayed(clearRunnable, 2000); } }; /** * our gesture listener */ private OnGesturePerformedListener handleGestureListener = new OnGesturePerformedListener() { @Override public void onGesturePerformed(GestureOverlayView gestureView, Gesture gesture) { predict(gesture); } }; private void predict(Gesture gesture) { ArrayList<Prediction> predictions = gLib.recognize(gesture); if (!predictions.isEmpty()) { double maxScore = Double.MIN_VALUE; Prediction maxPrediction = null; for (Prediction prediction : predictions) { double currentMaxScore = maxScore; maxScore = Math.max(maxScore, prediction.score); if (currentMaxScore != maxScore) { maxPrediction = prediction; } } if (maxPrediction != null && maxPrediction.score > 1.0) { Log.d(TAG, maxPrediction.name); Toast.makeText(GestureActivity.this, maxPrediction.name, Toast.LENGTH_SHORT).show(); } } } }
3dc472c167f3ae256e73dcbc9a77a3a1b81b1795
[ "Java" ]
2
Java
rsri/GestureDetector
d5aa6ebd8271e9960bdbbc332b338710df1c1922
18fbe1c9db189427a5eb73e9ce4cc9d18758952e
refs/heads/master
<file_sep>from django.db import models class Category(models.Model): class Meta: verbose_name = 'category' verbose_name_plural = 'categories' name = models.CharField(max_length=30, unique=True) def __str__(self): return self.name class Good(models.Model): class Meta: ordering = ["-price", "name"] unique_together = ("category", "price", "name") verbose_name = 'good' verbose_name_plural = 'goods' name = models.CharField(max_length=50, unique=True, verbose_name='Name') description = models.TextField() price = models.FloatField() in_stock = models.BooleanField(default=True, db_index=True, verbose_name='In stock') category = models.ForeignKey(Category) def get_in_stock(self): if self.in_stock: return "+" else: return "" def __str__(self): s = self.name if not self.in_stock: s += " (not in stock)" return s class BlogArticle(models.Model): title = models.CharField(max_length=30, unique_for_date='pubdate') pubdate = models.DateField() updated = models.DateTimeField(auto_now=True) <file_sep>from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^(?:(?P<cat_id>\d+)/)?$', views.index, name='index'), url(r'^good/(?P<good_id>\d+)/$', views.good, name='good'), ]
df309c755f40c88884e90d71208794e4eb328380
[ "Python" ]
2
Python
SergeyChmil/django_site
52976389f77405e3d1be7994d6ea6dc20f7fbd24
29d1c3f1f45fd5e91b069f6858af12bc6bdde6ba
refs/heads/master
<repo_name>Connoropolous/sim2h<file_sep>/crates/sim2h_server/src/main.rs use lib3h::transport::{ protocol::DynTransportActor, websocket::{actor::GhostTransportWebsocket, tls::TlsConfig}, }; use lib3h_protocol::{uri::Builder, Address}; use log::error; use sim2h::Sim2h; use std::process::exit; fn create_websocket_transport() -> DynTransportActor { Box::new(GhostTransportWebsocket::new( Address::from("sim2h-worker-transport"), TlsConfig::Unencrypted, Address::from("sim2h-network"), )) } fn main() { env_logger::init(); let transport = create_websocket_transport(); let host = "wss://127.0.0.1/"; let port = 9000; let uri = Builder::with_raw_url(host) .unwrap_or_else(|e| panic!("with_raw_url: {:?}", e)) .with_port(port) .build(); let mut sim2h = Sim2h::new(transport, uri); loop { let result = sim2h.process(); if let Err(e) = result { if e.to_string().contains("Bind error:") { println!("{:?}", e); exit(1) } else { error!("{}", e.to_string()) } } std::thread::sleep(std::time::Duration::from_millis(1)); } } <file_sep>/crates/sim2h/Cargo.toml [package] name = "sim2h" version = "0.0.1" authors = ["Holochain Core Dev Team <<EMAIL>>"] edition = "2018" description = "A simulation of lib3h" keywords = ["holochain", "holo", "p2p", "network", "simulation"] categories = ["network-programming"] license = "Apache-2.0" readme = "readme.md" documentation = "https://github.com/holochain/sim2h" repository = "https://github.com/holochain/sim2h" [dependencies] hcid = "=0.0.6" holochain_persistence_api = "=0.0.8" holochain_json_api = "=0.0.17" lib3h = "=0.0.13" lib3h_protocol = "=0.0.13" lib3h_zombie_actor = "=0.0.13" detach = "=0.0.13" holochain_tracing = "=0.0.1" #holochain_core_types = "=0.0.8" holochain_core_types = { git = "https://github.com/holochain/holochain-rust", branch = "sim2h" } uuid = { version = "0.4", features = ["v4"] } log = "=0.4.8" env_logger = "=0.6.1" lazy_static = "=1.2.0" url = "=2.1.0" crossbeam-channel = "=0.3.8" snowflake = "=1.3.0" parking_lot = "=0.8.0" serde = "=1.0.89" serde_derive = "=1.0.89" serde_json = "=1.0.39" rand = "0.7.2"<file_sep>/crates/sim2h/src/lib.rs extern crate env_logger; //#[macro_use] extern crate log; #[macro_use] extern crate detach; #[macro_use] extern crate serde; pub mod cache; pub mod connected_agent; pub mod error; pub mod wire_message; use crate::error::*; use cache::*; use connected_agent::*; pub use wire_message::WireMessage; use detach::prelude::*; use holochain_tracing::Span; use lib3h::transport::protocol::*; use lib3h_protocol::{ data_types::{EntryData, FetchEntryData, GetListData, Opaque, SpaceData, StoreEntryAspectData}, protocol::*, types::SpaceHash, uri::Lib3hUri, Address, }; use lib3h_zombie_actor::prelude::*; use log::*; use parking_lot::RwLock; use std::{ collections::HashMap, convert::TryFrom, }; use rand::Rng; pub struct Sim2h { pub bound_uri: Option<Lib3hUri>, connection_states: RwLock<HashMap<Lib3hUri, ConnectedAgent>>, spaces: HashMap<SpaceHash, RwLock<Space>>, transport: Detach<TransportActorParentWrapperDyn<Self>>, } impl Sim2h { pub fn new(transport: DynTransportActor, bind_spec: Lib3hUri) -> Self { let t = Detach::new(TransportActorParentWrapperDyn::new(transport, "transport_")); let mut sim2h = Sim2h { bound_uri: None, connection_states: RwLock::new(HashMap::new()), spaces: HashMap::new(), transport: t, }; debug!("Trying to bind to {}...", bind_spec); let _ = sim2h.transport.request( Span::fixme(), RequestToChild::Bind { spec: bind_spec }, Box::new(|me, response| match response { GhostCallbackData::Response(Ok(RequestToChildResponse::Bind(bind_result))) => { debug!("Bound as {}", &bind_result.bound_url); me.bound_uri = Some(bind_result.bound_url); Ok(()) } GhostCallbackData::Response(Err(e)) => Err(format!("Bind error: {}", e).into()), GhostCallbackData::Timeout(bt) => Err(format!("timeout: {:?}", bt).into()), r => Err(format!( "Got unexpected response from transport actor during bind: {:?}", r ) .into()), }), ); sim2h } fn request_authoring_list( &mut self, uri: Lib3hUri, space_address: SpaceHash, provider_agent_id: AgentId, ) { let wire_message = WireMessage::Lib3hToClient(Lib3hToClient::HandleGetAuthoringEntryList(GetListData { request_id: "".into(), space_address, provider_agent_id, })); self.send(uri, &wire_message); } fn request_gossiping_list( &mut self, uri: Lib3hUri, space_address: SpaceHash, provider_agent_id: AgentId, ) { let wire_message = WireMessage::Lib3hToClient(Lib3hToClient::HandleGetGossipingEntryList(GetListData { request_id: "".into(), space_address, provider_agent_id, })); self.send(uri, &wire_message); } // adds an agent to a space fn join(&mut self, uri: &Lib3hUri, data: &SpaceData) -> Sim2hResult<()> { if let Some(ConnectedAgent::Limbo) = self.get_connection(uri) { let _ = self.connection_states.write().insert( uri.clone(), ConnectedAgent::JoinedSpace(data.space_address.clone(), data.agent_id.clone()), ); if !self.spaces.contains_key(&data.space_address) { self.spaces .insert(data.space_address.clone(), RwLock::new(Space::new())); info!( "\n\n+++++++++++++++\nNew Space: {}\n+++++++++++++++\n", data.space_address ); } self.spaces .get(&data.space_address) .unwrap() .write() .join_agent(data.agent_id.clone(), uri.clone()); info!( "Agent {:?} joined space {:?}", data.agent_id, data.space_address ); self.request_authoring_list( uri.clone(), data.space_address.clone(), data.agent_id.clone(), ); self.request_gossiping_list( uri.clone(), data.space_address.clone(), data.agent_id.clone(), ); Ok(()) } else { Err(format!("no agent found in limbo at {} ", uri).into()) } } // removes an agent from a space fn leave(&self, uri: &Lib3hUri, data: &SpaceData) -> Sim2hResult<()> { if let Some(ConnectedAgent::JoinedSpace(space_address, agent_id)) = self.get_connection(uri) { if (data.agent_id != agent_id) || (data.space_address != space_address) { Err(SPACE_MISMATCH_ERR_STR.into()) } else { self.disconnect(uri); Ok(()) } } else { Err(format!("no joined agent found at {} ", &uri).into()) } } // removes a uri from connection and from spaces fn disconnect(&self, uri: &Lib3hUri) { if let Some(ConnectedAgent::JoinedSpace(space_address, agent_id)) = self.connection_states.write().remove(uri) { self.spaces .get(&space_address) .unwrap() .write() .remove_agent(&agent_id); } } // get the connection status of an agent fn get_connection(&self, uri: &Lib3hUri) -> Option<ConnectedAgent> { let reader = self.connection_states.read(); reader.get(uri).map(|ca| (*ca).clone()) } // find out if an agent is in a space or not and return its URI fn lookup_joined(&self, space_address: &SpaceHash, agent_id: &AgentId) -> Option<Lib3hUri> { self.spaces .get(&space_address)? .read() .agent_id_to_uri(agent_id) } // handler for incoming connections fn handle_incoming_connect(&self, uri: Lib3hUri) -> Sim2hResult<bool> { info!("New connection from {:?}", uri); if let Some(_old) = self .connection_states .write() .insert(uri.clone(), ConnectedAgent::new()) { println!("TODO should remove {}", uri); //TODO }; Ok(true) } // handler for messages sent to sim2h fn handle_message(&mut self, uri: &Lib3hUri, message: WireMessage) -> Sim2hResult<()> { let agent = self .get_connection(uri) .ok_or_else(|| format!("no connection for {}", uri))?; match agent { // if the agent sending the message is in limbo, then the only message // allowed is a join message. ConnectedAgent::Limbo => { if let WireMessage::ClientToLib3h(ClientToLib3h::JoinSpace(data)) = message { self.join(uri, &data) } else { error!("Got message while still in LIMBO: {:?}", message); Err(format!("no agent validated at {} ", uri).into()) } } //ConnectionState::RequestedJoiningSpace => self.process_join_request(agent), // if the agent sending the messages has been vetted and is in the space // then build a message to be proxied to the correct destination, and forward it ConnectedAgent::JoinedSpace(space_address, agent_id) => { if let Some((is_request, to_uri, message)) = self.prepare_proxy(uri, &space_address, &agent_id, message)? { if is_request { self.send(to_uri, &message); Ok(()) } else { unimplemented!() } } else { Ok(()) } } } } // process transport and incoming messages from it pub fn process(&mut self) -> Sim2hResult<()> { detach_run!(&mut self.transport, |t| t.process(self)).map_err(|e| format!("{:?}", e))?; for mut transport_message in self.transport.drain_messages() { match transport_message .take_message() .expect("GhostMessage must have a message") { RequestToParent::ReceivedData { uri, payload } => { match WireMessage::try_from(&payload) { Ok(wire_message) => if let Err(error) = self.handle_message(&uri, wire_message) { error!("Error handling message: {:?}", error); }, Err(error) => error!( "Could not deserialize received payload into WireMessage!\nError: {:?}\nPayload was: {:?}", error, payload ) } } RequestToParent::IncomingConnection { uri } => { if let Err(error) = self.handle_incoming_connect(uri) { error!("Error handling incomming connection: {:?}", error); } } RequestToParent::ErrorOccured { uri, error } => { if error.to_string() == "Protocol(\"Connection reset without closing handshake\")" { debug!("Disconnecting {} after connection reset", uri); self.disconnect(&uri); } else { error!( "Transport error occured on connection to {:?}: {:?}", uri, error, ) } } } } Ok(()) } // given an incoming messages, prepare a proxy message and whether it's an publish or request fn prepare_proxy( &mut self, uri: &Lib3hUri, space_address: &SpaceHash, agent_id: &AgentId, message: WireMessage, ) -> Sim2hResult<Option<(bool, Lib3hUri, WireMessage)>> { debug!( ">>IN>> {} from {}", message.message_type(), agent_id.to_string() ); match message { // First make sure we are not receiving a message in the wrong direction. // Panic for now so we can easily spot a mistake. // Should maybe break up WireMessage into two different structs so we get the // error already when parsing an incoming payload. WireMessage::Lib3hToClient(_) | WireMessage::ClientToLib3hResponse(_) => panic!("This is soo wrong. Clients should never send a message that only servers can send."), // -- Space -- // WireMessage::ClientToLib3h(ClientToLib3h::JoinSpace(_)) => { Err("join message should have been processed elsewhere and can't be proxied".into()) } WireMessage::ClientToLib3h(ClientToLib3h::LeaveSpace(data)) => { self.leave(uri, &data).map(|_| None) } // -- Direct Messaging -- // // Send a message directly to another agent on the network WireMessage::ClientToLib3h(ClientToLib3h::SendDirectMessage(dm_data)) => { if (dm_data.from_agent_id != *agent_id) || (dm_data.space_address != *space_address) { return Err(SPACE_MISMATCH_ERR_STR.into()); } let to_url = self .lookup_joined(space_address, &dm_data.to_agent_id) .ok_or_else(|| format!("unvalidated proxy agent {}", &dm_data.to_agent_id))?; Ok(Some(( true, to_url, WireMessage::Lib3hToClient(Lib3hToClient::HandleSendDirectMessage(dm_data)), ))) } // Direct message response WireMessage::Lib3hToClientResponse(Lib3hToClientResponse::HandleSendDirectMessageResult( dm_data, )) => { if (dm_data.from_agent_id != *agent_id) || (dm_data.space_address != *space_address) { return Err(SPACE_MISMATCH_ERR_STR.into()); } let to_url = self .lookup_joined(space_address, &dm_data.to_agent_id) .ok_or_else(|| format!("unvalidated proxy agent {}", &dm_data.to_agent_id))?; Ok(Some(( true, to_url, WireMessage::Lib3hToClient(Lib3hToClient::SendDirectMessageResult(dm_data)), ))) } WireMessage::ClientToLib3h(ClientToLib3h::PublishEntry(data)) => { if (data.provider_agent_id != *agent_id) || (data.space_address != *space_address) { return Err(SPACE_MISMATCH_ERR_STR.into()); } self.handle_new_entry_data(data.entry, space_address.clone(), agent_id.clone()); Ok(None) } WireMessage::Lib3hToClientResponse(Lib3hToClientResponse::HandleGetAuthoringEntryListResult(list_data)) => { debug!("GOT AUTHORING LIST from {}", agent_id); if (list_data.provider_agent_id != *agent_id) || (list_data.space_address != *space_address) { return Err(SPACE_MISMATCH_ERR_STR.into()); } let unseen_aspects = AspectList::from(list_data.address_map) .diff(self.spaces .get(space_address) .expect("This function should not get called if we don't have this space") .read() .all_aspects() ); debug!("UNSEEN ASPECTS:\n{}", unseen_aspects.pretty_string()); for entry_address in unseen_aspects.entry_addresses() { if let Some(aspect_address_list) = unseen_aspects.per_entry(entry_address) { let wire_message = WireMessage::Lib3hToClient( Lib3hToClient::HandleFetchEntry(FetchEntryData { request_id: "".into(), space_address: space_address.clone(), provider_agent_id: agent_id.clone(), entry_address: entry_address.clone(), aspect_address_list: Some(aspect_address_list.clone()) }) ); self.send(uri.clone(), &wire_message); } } Ok(None) } WireMessage::Lib3hToClientResponse(Lib3hToClientResponse::HandleGetGossipingEntryListResult(list_data)) => { debug!("GOT GOSSIPING LIST from {}", agent_id); if (list_data.provider_agent_id != *agent_id) || (list_data.space_address != *space_address) { return Err(SPACE_MISMATCH_ERR_STR.into()); } let (agents_in_space, aspects_missing_at_node) = { let space = self.spaces .get(space_address) .expect("This function should not get called if we don't have this space") .read(); let aspects_missing_at_node = space .all_aspects() .diff(&AspectList::from(list_data.address_map)); warn!("MISSING ASPECTS at {}:\n{}", agent_id, aspects_missing_at_node.pretty_string()); let agents_in_space = space .all_agents() .keys() .cloned() .collect::<Vec<Address>>(); (agents_in_space, aspects_missing_at_node) }; if agents_in_space.len() == 1 { error!("MISSING ASPECTS and no way to get them. Agent is alone in space.."); } else { let other_agents = agents_in_space .into_iter() .filter(|a| a!=agent_id) .collect::<Vec<_>>(); let mut rng = rand::thread_rng(); let random_agent_index = rng.gen_range(0, other_agents.len()); let random_agent = other_agents .get(random_agent_index) .expect("Random generator must work as documented"); debug!("FETCHING missing contents from RANDOM AGENT: {}", random_agent); let maybe_url = self.lookup_joined(space_address, random_agent); if maybe_url.is_none() { error!("Could not find URL for randomly selected agent. This should not happen!"); return Ok(None) } let random_url = maybe_url.unwrap(); for entry_address in aspects_missing_at_node.entry_addresses() { if let Some(aspect_address_list) = aspects_missing_at_node.per_entry(entry_address) { let wire_message = WireMessage::Lib3hToClient( Lib3hToClient::HandleFetchEntry(FetchEntryData { request_id: agent_id.clone().into(), space_address: space_address.clone(), provider_agent_id: random_agent.clone(), entry_address: entry_address.clone(), aspect_address_list: Some(aspect_address_list.clone()) }) ); debug!("SENDING FeTCH with ReQUest ID: {:?}", wire_message); self.send(random_url.clone(), &wire_message); } } } Ok(None) } WireMessage::Lib3hToClientResponse( Lib3hToClientResponse::HandleFetchEntryResult(fetch_result)) => { if (fetch_result.provider_agent_id != *agent_id) || (fetch_result.space_address != *space_address) { return Err(SPACE_MISMATCH_ERR_STR.into()); } debug!("HANDLE FETCH ENTRY RESULT: {:?}", fetch_result); if fetch_result.request_id == String::from("") { debug!("Got FetchEntry result form {} without request id - must be from authoring list", agent_id); self.handle_new_entry_data(fetch_result.entry, space_address.clone(), agent_id.clone()); } else { debug!("Got FetchEntry result with request id {} - this is for gossiping to agent with incomplete data", fetch_result.request_id); let to_agent_id = Address::from(fetch_result.request_id); let maybe_url = self.lookup_joined(space_address, &to_agent_id);; if maybe_url.is_none() { error!("Got FetchEntryResult with request id that is not a known agent id. My hack didn't work?"); return Ok(None) } let url = maybe_url.unwrap(); for aspect in fetch_result.entry.aspect_list { let store_message = WireMessage::Lib3hToClient(Lib3hToClient::HandleStoreEntryAspect( StoreEntryAspectData { request_id: "".into(), space_address: space_address.clone(), provider_agent_id: agent_id.clone(), entry_address: fetch_result.entry.entry_address.clone(), entry_aspect: aspect, }, )); self.send(url.clone(), &store_message); } } Ok(None) } _ => { warn!("Ignoring unimplemented message: {:?}", message ); Err(format!("Message not implemented: {:?}", message).into()) } } } fn handle_new_entry_data( &mut self, entry_data: EntryData, space_address: SpaceHash, provider: Address, ) { let aspect_addresses = entry_data .aspect_list .iter() .cloned() .map(|aspect_data| aspect_data.aspect_address) .collect::<Vec<_>>(); let mut map = HashMap::new(); map.insert(entry_data.entry_address.clone(), aspect_addresses); let aspect_list = AspectList::from(map); debug!("GOT NEW ASPECTS:\n{}", aspect_list.pretty_string()); for aspect in entry_data.aspect_list { // 1. Add hashes to our global list of all aspects in this space: { let mut space = self .spaces .get(&space_address) .expect("This function should not get called if we don't have this space") .write(); space.add_aspect( entry_data.entry_address.clone(), aspect.aspect_address.clone(), ); debug!( "Space {} now knows about these aspects:\n{}", space_address, space.all_aspects().pretty_string() ); } // 2. Create store message let store_message = WireMessage::Lib3hToClient(Lib3hToClient::HandleStoreEntryAspect( StoreEntryAspectData { request_id: "".into(), space_address: space_address.clone(), provider_agent_id: provider.clone(), entry_address: entry_data.entry_address.clone(), entry_aspect: aspect, }, )); // 3. Send store message to everybody in this space if let Err(e) = self.broadcast(space_address.clone(), &store_message) { error!("Error during broadcast: {:?}", e); } } } fn broadcast(&mut self, space: SpaceHash, msg: &WireMessage) -> Sim2hResult<()> { debug!("Broadcast in space: {:?}", space); let all_uris = self .spaces .get(&space) .ok_or("No such space")? .read() .all_agents() .values() .cloned() .collect::<Vec<_>>(); for uri in all_uris { debug!("Broadcast: Sending to {:?}", uri); self.send(uri, msg); } Ok(()) } fn send(&mut self, uri: Lib3hUri, msg: &WireMessage) { debug!(">>OUT>> {} to {}", msg.message_type(), uri); let payload: Opaque = msg.clone().into(); let send_result = self.transport.request( Span::fixme(), RequestToChild::SendMessage { uri, payload }, Box::new(|_me, response| match response { GhostCallbackData::Response(Ok(RequestToChildResponse::SendMessageSuccess)) => { Ok(()) } GhostCallbackData::Response(Err(e)) => Err(e.into()), GhostCallbackData::Timeout(bt) => Err(format!("timeout: {:?}", bt).into()), _ => Err("bad response type".into()), }), ); if let Err(e) = send_result { error!("GhostError during broadcast send: {:?}", e) } } } #[cfg(test)] pub mod tests { use super::*; use lib3h::transport::memory_mock::{ ghost_transport_memory::*, memory_server::get_memory_verse, }; use lib3h_protocol::data_types::*; // for this to actually show log entries you also have to run the tests like this: // RUST_LOG=lib3h=debug cargo test -- --nocapture pub fn enable_logging_for_test(enable: bool) { // wait a bit because of non monotonic clock, // otherwise we could get negative substraction panics // TODO #211 std::thread::sleep(std::time::Duration::from_millis(10)); if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "debug"); } let _ = env_logger::builder() .default_format_timestamp(false) .default_format_module_path(false) .is_test(enable) .try_init(); } fn make_test_agent() -> AgentId { "fake_agent_id".into() } fn make_test_space_data() -> SpaceData { SpaceData { request_id: "".into(), space_address: "fake_space_address".into(), agent_id: make_test_agent(), } } fn make_test_space_data_with_agent(agent_id: AgentId) -> SpaceData { SpaceData { request_id: "".into(), space_address: "fake_space_address".into(), agent_id, } } fn make_test_join_message() -> WireMessage { make_test_join_message_with_space_data(make_test_space_data()) } fn make_test_join_message_with_space_data(space_data: SpaceData) -> WireMessage { WireMessage::ClientToLib3h(ClientToLib3h::JoinSpace(space_data)) } fn make_test_leave_message() -> WireMessage { WireMessage::ClientToLib3h(ClientToLib3h::LeaveSpace(make_test_space_data())) } fn make_test_dm_data_with(from: AgentId, to: AgentId, content: &str) -> DirectMessageData { DirectMessageData { request_id: "".into(), space_address: "fake_space_address".into(), from_agent_id: from, to_agent_id: to, content: content.into(), } } fn make_test_dm_data() -> DirectMessageData { make_test_dm_data_with(make_test_agent(), "fake_to_agent_id".into(), "foo") } fn make_test_dm_message() -> WireMessage { make_test_dm_message_with(make_test_dm_data()) } fn make_test_dm_message_with(data: DirectMessageData) -> WireMessage { WireMessage::ClientToLib3h(ClientToLib3h::SendDirectMessage(data)) } fn make_test_dm_message_response_with(data: DirectMessageData) -> WireMessage { WireMessage::Lib3hToClientResponse(Lib3hToClientResponse::HandleSendDirectMessageResult( data, )) } fn make_test_err_message() -> WireMessage { WireMessage::Err("fake_error".into()) } fn make_test_sim2h_nonet() -> Sim2h { let transport = Box::new(GhostTransportMemory::new("null".into(), "nullnet".into())); Sim2h::new(transport, Lib3hUri::with_undefined()) } fn make_test_sim2h_memnet(netname: &str) -> Sim2h { let transport_id = "test_transport".into(); let transport = Box::new(GhostTransportMemory::new(transport_id, netname)); Sim2h::new(transport, Lib3hUri::with_undefined()) } #[test] pub fn test_constructor() { let mut sim2h = make_test_sim2h_nonet(); { let reader = sim2h.connection_states.read(); assert_eq!(reader.len(), 0); } let result = sim2h.process(); assert_eq!(result, Ok(())); assert_eq!( "Some(Lib3hUri(\"mem://addr_1/\"))", format!("{:?}", sim2h.bound_uri) ); } #[test] pub fn test_incomming_connection() { let sim2h = make_test_sim2h_nonet(); // incoming connections get added to the map in limbo let uri = Lib3hUri::with_memory("addr_1"); let result = sim2h.handle_incoming_connect(uri.clone()); assert_eq!(result, Ok(true)); let result = sim2h.get_connection(&uri).clone(); assert_eq!("Some(Limbo)", format!("{:?}", result)); // pretend the agent has joined the space let _ = sim2h.connection_states.write().insert( uri.clone(), ConnectedAgent::JoinedSpace("fake_agent".into(), "fake_space".into()), ); // if we get a second incoming connection, the state should be reset. let result = sim2h.handle_incoming_connect(uri.clone()); assert_eq!(result, Ok(true)); let result = sim2h.get_connection(&uri).clone(); assert_eq!("Some(Limbo)", format!("{:?}", result)); } #[test] pub fn test_join() { let mut sim2h = make_test_sim2h_nonet(); let uri = Lib3hUri::with_memory("addr_1"); let data = make_test_space_data(); // you can't join if you aren't in limbo let result = sim2h.join(&uri, &data); assert_eq!( result, Err(format!("no agent found in limbo at {} ", &uri).into()) ); // but you can if you are TODO: real membrane check let _result = sim2h.handle_incoming_connect(uri.clone()); let result = sim2h.join(&uri, &data); assert_eq!(result, Ok(())); assert_eq!( sim2h.lookup_joined(&data.space_address, &data.agent_id), Some(uri.clone()) ); let result = sim2h.get_connection(&uri).clone(); assert_eq!( "Some(JoinedSpace(SpaceHash(HashString(\"fake_space_address\")), HashString(\"fake_agent_id\")))", format!("{:?}", result) ); } #[test] pub fn test_leave() { let mut sim2h = make_test_sim2h_nonet(); let uri = Lib3hUri::with_memory("addr_1"); let mut data = make_test_space_data(); // leaving a space not joined should produce an error let result = sim2h.leave(&uri, &data); assert_eq!( result, Err(format!("no joined agent found at {} ", &uri).into()) ); let _result = sim2h.handle_incoming_connect(uri.clone()); let result = sim2h.leave(&uri, &data); assert_eq!( result, Err(format!("no joined agent found at {} ", &uri).into()) ); let _result = sim2h.join(&uri, &data); // a leave on behalf of someone else should fail data.agent_id = "someone_else_agent_id".into(); let result = sim2h.leave(&uri, &data); assert_eq!(result, Err(SPACE_MISMATCH_ERR_STR.into())); // a valid leave should work data.agent_id = make_test_agent(); let result = sim2h.leave(&uri, &data); assert_eq!(result, Ok(())); let result = sim2h.get_connection(&uri).clone(); assert_eq!(result, None); assert_eq!( sim2h.lookup_joined(&data.space_address, &data.agent_id), None ); } #[test] pub fn test_prepare_proxy() { let mut sim2h = make_test_sim2h_nonet(); let uri = Lib3hUri::with_memory("addr_1"); let _ = sim2h.handle_incoming_connect(uri.clone()); let _ = sim2h.join(&uri, &make_test_space_data()); let message = make_test_join_message(); let data = make_test_space_data(); // you can't proxy a join message let result = sim2h.prepare_proxy(&uri, &data.space_address, &data.agent_id, message); assert!(result.is_err()); // you can't proxy for someone else, i.e. the message contents must match the // space joined let message = make_test_dm_message(); let result = sim2h.prepare_proxy( &uri, &data.space_address, &"fake_other_agent".into(), message, ); assert_eq!(Err("space/agent id mismatch".into()), result); // you can't proxy to someone not in the space let message = make_test_dm_message(); let result = sim2h.prepare_proxy(&uri, &data.space_address, &data.agent_id, message.clone()); assert_eq!( Err("unvalidated proxy agent fake_to_agent_id".into()), result, ); // proxy a dm message // first we have to setup the to agent in the space let to_agent_data = make_test_space_data_with_agent("fake_to_agent_id".into()); let to_uri = Lib3hUri::with_memory("addr_2"); let _ = sim2h.handle_incoming_connect(to_uri.clone()); let _ = sim2h.join(&to_uri, &to_agent_data); let result = sim2h.prepare_proxy(&uri, &data.space_address, &data.agent_id, message); assert_eq!( "Ok(Some((true, Lib3hUri(\"mem://addr_2/\"), Lib3hToClient(HandleSendDirectMessage(DirectMessageData { space_address: SpaceHash(HashString(\"fake_space_address\")), request_id: \"\", to_agent_id: HashString(\"fake_to_agent_id\"), from_agent_id: HashString(\"fake_agent_id\"), content: \"foo\" })))))", format!("{:?}", result) ); // proxy a dm message response // for this test we just pretend the same agent set up above is making a response let message = make_test_dm_message_response_with(make_test_dm_data()); let result = sim2h.prepare_proxy(&uri, &data.space_address, &data.agent_id, message); assert_eq!( "Ok(Some((true, Lib3hUri(\"mem://addr_2/\"), Lib3hToClient(SendDirectMessageResult(DirectMessageData { space_address: SpaceHash(HashString(\"fake_space_address\")), request_id: \"\", to_agent_id: HashString(\"fake_to_agent_id\"), from_agent_id: HashString(\"fake_agent_id\"), content: \"foo\" })))))", format!("{:?}", result) ); // proxy a leave space message should remove the agent from the space let message = make_test_leave_message(); let result = sim2h.prepare_proxy(&uri, &data.space_address, &data.agent_id, message); assert_eq!("Ok(None)", format!("{:?}", result)); let result = sim2h.get_connection(&uri).clone(); assert_eq!(result, None); } #[test] pub fn test_message() { let netname = "test_message"; let mut sim2h = make_test_sim2h_memnet(netname); let network = { let mut verse = get_memory_verse(); verse.get_network(netname) }; let uri = network.lock().unwrap().bind(); // a message from an unconnected agent should return an error let result = sim2h.handle_message(&uri, make_test_err_message()); assert_eq!(result, Err(format!("no connection for {}", &uri).into())); // a non-join message from an unvalidated but connected agent should return an error let _result = sim2h.handle_incoming_connect(uri.clone()); let result = sim2h.handle_message(&uri, make_test_err_message()); assert_eq!( result, Err(format!("no agent validated at {} ", &uri).into()) ); // a valid join message from a connected agent should update its connection status let result = sim2h.handle_message(&uri, make_test_join_message()); assert_eq!(result, Ok(())); let result = sim2h.get_connection(&uri).clone(); assert_eq!( "Some(JoinedSpace(SpaceHash(HashString(\"fake_space_address\")), HashString(\"fake_agent_id\")))", format!("{:?}", result) ); // dm // first we have to setup the to agent on the in-memory-network and in the space let to_uri = network.lock().unwrap().bind(); let _ = sim2h.handle_incoming_connect(to_uri.clone()); let to_agent_data = make_test_space_data_with_agent("fake_to_agent_id".into()); let _ = sim2h.join(&to_uri, &to_agent_data); // then we can make a message and handle it. let message = make_test_dm_message(); let result = sim2h.handle_message(&uri, message); assert_eq!(result, Ok(())); // which should result in showing up in the to_uri's inbox in the in-memory netowrk let result = sim2h.process(); assert_eq!(result, Ok(())); let mut reader = network.lock().unwrap(); let server = reader .get_server(&to_uri) .expect("there should be a server for to_uri"); if let Ok((did_work, events)) = server.process() { assert!(did_work); let dm = &events[3]; assert_eq!( "ReceivedData(Lib3hUri(\"mem://addr_3/\"), \"{\\\"Lib3hToClient\\\":{\\\"HandleSendDirectMessage\\\":{\\\"space_address\\\":\\\"fake_space_address\\\",\\\"request_id\\\":\\\"\\\",\\\"to_agent_id\\\":\\\"fake_to_agent_id\\\",\\\"from_agent_id\\\":\\\"fake_agent_id\\\",\\\"content\\\":\\\"Zm9v\\\"}}}\")", format!("{:?}", dm)) } else { assert!(false) } } #[test] pub fn test_end_to_end() { enable_logging_for_test(true); let netname = "test_end_to_end"; let mut sim2h = make_test_sim2h_memnet(netname); let _result = sim2h.process(); let sim2h_uri = sim2h.bound_uri.clone().expect("should have bound"); // set up two other agents on the memory-network let network = { let mut verse = get_memory_verse(); verse.get_network(netname) }; let agent1_uri = network.lock().unwrap().bind(); let agent2_uri = network.lock().unwrap().bind(); // connect them to sim2h with join messages let space_data1 = make_test_space_data_with_agent("agent1".into()); let space_data2 = make_test_space_data_with_agent("agent2".into()); let join1: Opaque = make_test_join_message_with_space_data(space_data1.clone()).into(); let join2: Opaque = make_test_join_message_with_space_data(space_data2.clone()).into(); { let mut net = network.lock().unwrap(); let server = net .get_server(&sim2h_uri) .expect("there should be a server for to_uri"); server.request_connect(&agent1_uri).expect("can connect"); let result = server.post(&agent1_uri, &join1.to_vec()); assert_eq!(result, Ok(())); server.request_connect(&agent2_uri).expect("can connect"); let result = server.post(&agent2_uri, &join2.to_vec()); assert_eq!(result, Ok(())); } let _result = sim2h.process(); assert_eq!( sim2h.lookup_joined(&space_data1.space_address, &space_data1.agent_id), Some(agent1_uri.clone()) ); assert_eq!( sim2h.lookup_joined(&space_data2.space_address, &space_data2.agent_id), Some(agent2_uri.clone()) ); // now send a direct message from agent1 through sim2h which should arrive at agent2 let data = make_test_dm_data_with( space_data1.agent_id, space_data2.agent_id, "come here watson", ); let message: Opaque = make_test_dm_message_with(data).into(); { let mut net = network.lock().unwrap(); let server = net .get_server(&sim2h_uri) .expect("there should be a server for to_uri"); let result = server.post(&agent1_uri, &message.to_vec()); assert_eq!(result, Ok(())); } let _result = sim2h.process(); let _result = sim2h.process(); { let mut net = network.lock().unwrap(); let server = net .get_server(&agent2_uri) .expect("there should be a server for to_uri"); if let Ok((did_work, events)) = server.process() { assert!(did_work); let dm = &events[3]; assert_eq!( "ReceivedData(Lib3hUri(\"mem://addr_1/\"), \"{\\\"Lib3hToClient\\\":{\\\"HandleSendDirectMessage\\\":{\\\"space_address\\\":\\\"fake_space_address\\\",\\\"request_id\\\":\\\"\\\",\\\"to_agent_id\\\":\\\"agent2\\\",\\\"from_agent_id\\\":\\\"agent1\\\",\\\"content\\\":\\\"Y29tZSBoZXJlIHdhdHNvbg==\\\"}}}\")", format!("{:?}", dm)) } else { assert!(false) } } } } <file_sep>/crates/sim2h/src/connected_agent.rs //! represents the state of connected agents use lib3h_protocol::{types::SpaceHash, Address}; pub type AgentId = Address; #[derive(PartialEq, Debug, Clone)] pub enum ConnectedAgent { Limbo, // RequestedJoiningSpace(SpaceHash, AgentId), JoinedSpace(SpaceHash, AgentId), } impl ConnectedAgent { pub fn new() -> ConnectedAgent { ConnectedAgent::Limbo } } #[cfg(test)] pub mod tests { use super::*; #[test] pub fn test_connected_agent() { let ca = ConnectedAgent::new(); assert_eq!(ca, ConnectedAgent::Limbo); } }
4acee11a6e41ab7d21d07f3baca7d7e91ad8feed
[ "TOML", "Rust" ]
4
Rust
Connoropolous/sim2h
6e2ee9fc77b41296e5f1e0d472e091a16c17110a
8daac3cd343bd87c59ad3e9c8d88d0ecf2fbaa3b
refs/heads/master
<file_sep>'use strict'; var fs = require('fs'); var assert = require('assert'); describe('filerev', function () { it('should revision files based on content', function () { var original = fs.statSync('test/fixtures/file.png').size; var revisioned= fs.statSync('test/tmp/file.a0539763.png').size; assert(revisioned === original); }); it('should accept options', function () { var original = fs.statSync('test/fixtures/cfgfile.png').size; var revisioned= fs.statSync('test/tmp/cfgfile.f64f.png').size; assert(revisioned === original); }); it('should allow a dest directory option', function () { var original = fs.statSync('test/fixtures/file.png').size; var revisioned= fs.statSync('test/tmp/dest/file.a0539763.png').size; assert(revisioned === original); }); it('should allow sources defined with expand', function () { var original = fs.statSync('test/fixtures/file.png').size; var revisioned= fs.statSync('test/tmp/expand/file.a0539763.png').size; assert(revisioned === original); }); it('should copy the file when copy option is true', function () { var original = fs.statSync('test/fixtures/another.png').size; var revisioned= fs.statSync('test/tmp/another.37ba.png').size; assert(revisioned === original); var fileExists = fs.existsSync('test/tmp/another.png'); assert(fileExists === true); }); it('should move the file when copy option is false', function () { var original = fs.statSync('test/fixtures/movedfile.png').size; var revisioned= fs.statSync('test/tmp/copyfalse/movedfile.37ba.png').size; assert(revisioned === original); var fileExists = fs.existsSync('test/tmp/movedfile.png'); assert(fileExists === false); }); });
166b345222b04c607db9f32f18145f603b9c5710
[ "JavaScript" ]
1
JavaScript
Paxata/grunt-filerev
d8294be594946f9a2341f1610afae3f2c6bd5678
d41357cdb0845eccf434b578a1b51f7d1e4d6dc3
refs/heads/master
<repo_name>KKRainbow/My-Linux-Environment<file_sep>/java.sh #!/usr/bin/env zsh install_url="http://ghaffarian.net/downloads/Java/JDK/jdk-8u45-linux-x64.tar.gz" install_dir="/opt/java" tmp_dir="/tmp/java/" tmp_filename=`basename $install_url` tmp_path=$tmp_dir$tmp_filename #添加java环境变量 count=`grep -c JAVA_HOME /etc/profile` if [ $count -gt "0" ];then echo "JAVA环境变量已存在,请删除后重新尝试" exit fi sudo mkdir -p $install_dir sudo mkdir -p $tmp_dir echo "选择是否重新下载Jdk:(y/n)" ans=`read -E` if [ ! -f $tmp_path ] && [ `ls $tmp_dir|grep -c jdk` -eq 0 ] && [ $ans -eq "y" ];then echo "正在下载JDK" sudo curl $install_url -L > $tmp_path fi if [ ! $? -eq 0 ]; then echo "下载失败,请重试" exit fi tmp_path=`ls $tmp_dir` (cd $tmp_dir;sudo tar -xzvf $tmp_path;tmp_path=`find -maxdepth 1 -type d -name "jdk*"`;echo $tmp_path;sudo cp $tmp_path $install_dir/ -r) java_home=`find $install_dir -name "jdk*" -type d -nowarn -maxdepth 2` echo "Java Home被配置为"$java_home jre_home=`find $install_dir -name "jre" -type d -nowarn -maxdepth 4` echo "Jre Home被配置为"$jre_home echo "classpath 被配置为\$JAVA_HOME=.:\$JAVA_HOME/lib:\$JRE_HOME/lib:\$CLASSPATH" envs=""" JAVA_HOME=$java_home JRE_HOME=$jre_home CLASSPATH=.:\$JAVA_HOME/lib:\$JRE_HOME/lib:\$CLASSPATH PATH=\$JAVA_HOME/bin:\$JRE_HOME/bin:\$PATH export JAVA_HOME export JRE_HOME export CLASSPATH export PATH """ sudo chmod a+w /etc/profile echo $envs >> /etc/profile sudo chmod 644 /etc/profile <file_sep>/packages.sh #!/usr/bin/env zsh source ./common.sh install_ohmyzsh() { curl -L https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh | sh } install_composer() { curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer } install_ss5() { sudo add-apt-repository ppa:hzwhuang/ss-qt5 sudo apt-get update sudo apt-get install shadowsocks-qt5 } install_wine() { sudo add-apt-repository ppa:ubuntu-wine/ppa sudo apt-get update sudo apt-get install wine1.7 -y } config_apache() { } base=("build-essential" "curl" "git" "cmake" "g++" "vim" "qemu-system-i386" "meld" "svn" "zsh" "apache2" "nfs-common" "mysql-client" "mysql-server-5.6" "php5" "kdevelop" "wget" "xorriso" "qemu-kvm" "virt-manager" "ctags") php=("php5" "php5-mcrypt" "php5-curl" "php5-cli" "php5-mysql" "php5-dev") install $base install $php install_ohmyzsh install_composer install_ss5 <file_sep>/vim.sh #!/usr/bin/env zsh source ./common.sh install vim cat ./configs/vimrc > ~/.vimrc mkdir -p ~/.vim/bundle/ #下载Vundle git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim #安装插件 vim +BundleInstall +qall <file_sep>/common.sh #!/usr/bin/env zsh function join_str { local dst local arr if [ $# -eq 2 ];then dst=$2 else arr=(${*[@]:2:$#}) dst=$arr[1] for i in $arr do if [ $i -gt 1 ];then dst=${dst}$1$arr[$i] fi done fi echo $dst } install() { local p for i in $* do echo "正在安装"${i} sudo apt-get install $i -y done } <file_sep>/git.sh #!/usr/bin/env bash install() { sudo apt-get install $1 -y -qq } git config --global user.email "<EMAIL>" git config --global user.name "孙思杰" git config --global push.default simple # 检查依赖 install vim git config --global core.editor "vim" install meld git config --global diff.tool "meld"
310b00021d65fcbd211587589bcbd5ab3ba1a022
[ "Shell" ]
5
Shell
KKRainbow/My-Linux-Environment
da4a8aa8028d7b07f894d1380ec5ab28b5f89831
5d473241161a49ca08a41cf1a7f2c5c18fdc6430
refs/heads/master
<file_sep>package com.example.yumuranaoki.asynctaskloader import android.content.Context import android.support.v4.content.AsyncTaskLoader import org.json.JSONObject import java.io.BufferedInputStream import java.io.BufferedReader import java.io.InputStream import java.io.InputStreamReader import java.net.URL import javax.net.ssl.HttpsURLConnection class ResultLoader(context: Context): AsyncTaskLoader<String>(context) { override fun loadInBackground(): String? { val response = httpGet("http://localhost:3000") if (response != null) { // 取得に成功したら、パースして返す val jsonResponse: JSONObject? = parseJson(response) if (jsonResponse != null) { val publicKey = jsonResponse.getString("publicKey") ?: "no keys found" return publicKey } } return null } override fun onStartLoading() { forceLoad() } override fun onStopLoading() { cancelLoad() } override fun onReset() { super.onReset() onStopLoading() } } fun httpGet(url: String) : InputStream? { // 通信接続用のオブジェクトを作る val con = URL(url).openConnection() as HttpsURLConnection // 接続の設定を行う con.apply { requestMethod = "GET" // メソッド connectTimeout = 3000 // 接続のタイムアウト(ミリ秒) readTimeout = 5000 // 読み込みのタイムアウト(ミリ秒) instanceFollowRedirects = true // リダイレクト許可 } // 接続する con.connect() // ステータスコードの確認 if (con.responseCode in 200..299) { // 成功したら、レスポンスの入力ストリームを、BufferedInputStreamとして返す return BufferedInputStream(con.inputStream) } // 失敗 return null } fun parseJson(inputStream: InputStream): JSONObject? { val response = BufferedReader(InputStreamReader(inputStream)) var result: String? = null try { result = response.readLine() inputStream.close() } catch (ex: Exception) { } if (result != null) { return JSONObject(result) } return null } <file_sep>package com.example.yumuranaoki.asynctaskloader import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v4.app.LoaderManager import android.support.v4.content.Loader import android.widget.TextView class MainActivity : AppCompatActivity(), LoaderManager.LoaderCallbacks<String> { override fun onCreateLoader(id: Int, args: Bundle?): Loader<String> = ResultLoader(this) override fun onLoadFinished(loader: Loader<String>, data: String?) { if (data != null) { val publicKeyText = findViewById<TextView>(R.id.publicKey) publicKeyText.text = data } supportLoaderManager.destroyLoader(0) } override fun onLoaderReset(loader: Loader<String>) { } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) supportLoaderManager.initLoader(0, null, this) } }
8e6e307cd4c03fc138af0f790a67d5978367c169
[ "Kotlin" ]
2
Kotlin
yumuranaoki/async-task-loader-practice
643cad83e27322f629ae6261dbc41592f9c839b1
1dd87f1381871ee46d4939b7e486b27509b685d7
refs/heads/master
<repo_name>paulhylam/Intro_Python<file_sep>/Assignment/entertainment_center.py # This program contains the information and running codes import media import fresh_tomatoes # Instances are created for each movie based on the class Movie toy_story = media.Movie('Toy Story', 'A story of a boy and his toys that come to life', 'http://upload.wikimedia.org/wikipedia/en/1/13/' 'Toy_Story.jpg', 'https://www.youtube.com/watch?v=nCqtQLmJTl0') avatar = media.Movie('Avatar', 'A marine on an alien planet', 'https://upload.wikimedia.org/wikipedia/en/b/b0/' 'Avatar-Teaser-Poster.jpg', 'https://www.youtube.com/watch?v=5PSNL1qE6VY') school_of_rock = media.Movie('School of Rock', 'A marine on an alien planet', 'https://i.ytimg.com/vi/eAry-ZV_gfs/' 'movieposter.jpg', 'https://www.youtube.com/watch?v=yMvpJDbWX_c') hunger_game = media.Movie('Hunger Game', 'A marine on an alien planet', 'https://images-na.ssl-images-amazon.com/images/' 'I/91ikvZgoHZL._SL1500_.jpg', 'https://www.youtube.com/watch?v=n-7K_OjsDCQ') # This code will create the webpage. movies = [toy_story, avatar, school_of_rock, hunger_game] fresh_tomatoes.open_movies_page(movies) # print(media.Movie.VALID_RATINGS) # print(toy_story.storyline) # print(avatar.storyline) # calling instance methods # avatar.show_trailer() <file_sep>/Draw squares.py import turtle def draw_square(some_turtle): for j in range(1,5): some_turtle.forward(100) some_turtle.right(90) def draw_trangle(some_turtle): for i in range(1,3): some_turtle.forward(100) some_turtle.left(120) some_turtle.forward(100) some_turtle.left(120) some_turtle.forward(100) def draw_circle(): window = turtle.Screen() window.bgcolor("red") # define the class for turtle - which is used to create different turtle-based objects (instances) brad = turtle.Turtle() # now the attributes for 'brad' is changed brad.color("yellow") brad.shape("turtle") brad.speed(50) #loop the square to create a circle for i in range(1,72): draw_square(brad) brad.right(5) # Another object based on the class turtle, called angie # angie = turtle.Turtle() # angie.color("blue") # angie.speed(2) # angie.circle(100) # angie.shape("arrow") window.exitonclick() def draw_flower(): window = turtle.Screen() window.bgcolor("red") top = turtle.Turtle() top.shape("arrow") top.speed(40) stem = turtle.Turtle() for i in range(1,36): draw_trangle(top) top.right(10) stem.right(90) stem.forward(225) window.exitonclick() # draw_circle() draw_flower() <file_sep>/gambler.py import random import sys stake = 10 goal = 40 trials = 1000 bets = 0 wins = 0 for t in range (0, trials): # run one experiment cash = stake while (cash > 0) and (cash < goal): bets += 1 if random.randrange(0,2)==0: cash -= 1 else: cash += 1 if cash == goal: wins += 1 win_prob = wins/trials Avgbets = bets/trials print(win_prob) print(Avgbets) <file_sep>/check_profanity.py def read_file(): quotes = open("/Users/paul/Downloads/movie_quotes.txt") contents_of_file = quotes.read() print(contents_of_file) quotes.close() read_file() # urllib is a module in the standard library # urlopen is a function in the module # removing testing #check github
699b10606ea29cec9c8a57636b9a04a7fab5a597
[ "Python" ]
4
Python
paulhylam/Intro_Python
3d2211f2cee9a8d3638ee81ec68af8e9e4212784
eadce731ed28cac77dd399b9fb73bbe97a916b57
refs/heads/master
<file_sep>export const ActivityCardSource = [ { lostWeight : -4, levelUp : 8, progress : 520 }, { lostWeight : -8, levelUp : 8, progress : 220 }, { lostWeight : +1, levelUp : 1, progress : 520 }, { lostWeight : -9, levelUp : 10, progress : 730 } ] export const breakfastDataSource = [ { title : "yep", name:"blah1", description: "Praesent scelerisque cursus ege stas. Sed ullamcorper at mauris nec imperdiet. Maecenas sed mauris et magna dignissim faucibus sed sit amet augue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla sit amet mattis mi. Suspendisse accumsan tempus velit.", imgUrl:"https://images.kitchenstories.io/communityImages/f4604e05f6a9eaca99afddd69e849005_c02485d4-0841-4de6-b152-69deb38693f2/f4604e05f6a9eaca99afddd69e849005_c02485d4-0841-4de6-b152-69deb38693f2-large-landscape-150.jpg" }, { title : "yep1", name:"blah2", description: "Praesent scelerisque cursus egestas. Sed ullamcorper at mauris nec imperdiet. Maecenas sed mauris et magna dignissim faucibus sed sit amet augue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla sit amet mattis mi. Suspendisse accumsan tempus velit.", imgUrl:"https://ifoodreal.com/wp-content/uploads/2019/08/fg-heathy-breakfast-sandwich.jpg" }, { title : "yep2", name:"blah3", description: "Praesent scelerisque cursus egestas. Sed ullamcorper at mauris nec imperdiet. Maecenas sed mauris et magna dignissim faucibus sed sit amet augue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla sit amet mattis mi. Suspendisse accumsan tempus velit.", imgUrl:"https://static.onecms.io/wp-content/uploads/sites/44/2019/08/26232310/6183602.jpg" } ] export const foodsDataSource = [ { title : "yep", name:"blah1", description: "Praesent scelerisque cursus ege stas. Sed ullamcorper at mauris nec imperdiet. Maecenas sed mauris et magna dignissim faucibus sed sit amet augue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla sit amet mattis mi. Suspendisse accumsan tempus velit.", imgUrl:"https://images.immediate.co.uk/production/volatile/sites/2/2016/08/25471.jpg" }, { title : "yep1", name:"blah2", description: "Praesent scelerisque cursus egestas. Sed ullamcorper at mauris nec imperdiet. Maecenas sed mauris et magna dignissim faucibus sed sit amet augue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla sit amet mattis mi. Suspendisse accumsan tempus velit.", imgUrl:"https://2rdnmg1qbg403gumla1v9i2h-wpengine.netdna-ssl.com/wp-content/uploads/sites/3/2020/08/cancerDiet-1161928875-770x533-1-650x428.jpg" }, { title : "yep2", name:"blah3", description: "Praesent scelerisque cursus egestas. Sed ullamcorper at mauris nec imperdiet. Maecenas sed mauris et magna dignissim faucibus sed sit amet augue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla sit amet mattis mi. Suspendisse accumsan tempus velit.", imgUrl:"https://static.independent.co.uk/s3fs-public/thumbnails/image/2019/07/09/18/healthy-eating.jpg?width=982&height=726" } ] export const dinnerDataSource = [ { title : "yep", name:"blah1", description: "Praesent scelerisque cursus ege stas. Sed ullamcorper at mauris nec imperdiet. Maecenas sed mauris et magna dignissim faucibus sed sit amet augue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla sit amet mattis mi. Suspendisse accumsan tempus velit.", imgUrl:"https://images.immediate.co.uk/production/volatile/sites/2/2016/02/20501.jpg?quality=90&resize=768,574" }, { title : "yep1", name:"blah2", description: "Praesent scelerisque cursus egestas. Sed ullamcorper at mauris nec imperdiet. Maecenas sed mauris et magna dignissim faucibus sed sit amet augue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla sit amet mattis mi. Suspendisse accumsan tempus velit.", imgUrl:"https://images.immediate.co.uk/production/volatile/sites/30/2019/12/tandoori-trout-bb9fe6c.jpg?quality=90&resize=960,872" }, { title : "yep2", name:"blah3", description: "Praesent scelerisque cursus egestas. Sed ullamcorper at mauris nec imperdiet. Maecenas sed mauris et magna dignissim faucibus sed sit amet augue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla sit amet mattis mi. Suspendisse accumsan tempus velit.", imgUrl:"https://i1.wp.com/blog.hellofresh.com.au/wp-content/uploads/2018/01/HF171207_R10_W03_AUS_MAIN_low.jpg?resize=1050%2C700" } ] <file_sep>import React, { Component } from 'react' import { StyleSheet, Text, View, Image } from 'react-native' import {Button} from 'react-native-elements' import Swiper from 'react-native-swiper' const styles = StyleSheet.create({ wrapper: {}, slide1: { flex: 1, // justifyContent: 'center', // alignItems: 'center', backgroundColor: '#d7f4e5' }, slide2: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#97CAE5' }, slide3: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#92BBD9' }, text: { color: '#f2f2f2', fontSize: 30, fontWeight: 'bold' }, textSmallSize : { color: '#f2f2f2', fontSize: 14, fontWeight: 'bold' } }) export default function SwiperComponent (props) { return ( <Swiper style={styles.wrapper} showsButtons={false}> <View style={styles.slide1}> <Image style={{width:"100%", height:"100%", resizeMode:"cover", position:"absolute", top:0, zIndex:-9}} source={{uri : "https://www.thespruceeats.com/thmb/-PRqKVOQOLYYIYFuqLj_WWhf0Z0=/1280x960/filters:fill(auto,1)/eggpizzas5-568e859a3df78ccc1574b6be-5b2a7b38a474be00377ecb70.jpg"}}/> <View style={{flex:1, justifyContent:"center", alignItems:"center", backgroundColor:"rgba(0,33,73,0.5)"}}> <View style={{ justifyContent:"center", alignItems:"center"}}> <Text style={[styles.text, {textAlign:"center"}]}>Best tips for your diet</Text> <Text style={[styles.textSmallSize, {marginTop:10, textAlign:"center"}]}>Vestibulum in tellus ac lacus aliquet mollis. Nulla gravida sem in ornare pulvinar. Nam egestas urna quis erat molestie, eget vulputate dolor fringilla.</Text> </View> </View> </View> <View style={styles.slide2}> <Image style={{width:"100%", height:"100%", resizeMode:"cover", position:"absolute", top:0, zIndex:-9}} source={{uri : "https://cdn.aarp.net/content/dam/aarp/research/surveys_statistics/health/2016/Images/1140-healthy-lifestyle-beliefs-behaviors.web.jpg"}}/> <View style={{flex:1, justifyContent:"center", alignItems:"center", backgroundColor:"rgba(0,33,73,0.5)"}}> <View style={{justifyContent:"center", alignItems:"center"}}> <Text style={[styles.text, {textAlign:"center"}]}>One must eat to live, not live to eat. ...</Text> <Text style={[styles.textSmallSize, {marginTop:10, textAlign:"center"}]}>Vestibulum in tellus ac lacus aliquet mollis. Nulla gravida sem in ornare pulvinar. Nam egestas urna quis erat molestie, eget vulputate dolor fringilla.</Text> </View> </View> </View> <View style={styles.slide3}> <Image style={{width:"100%", height:"100%", resizeMode:"cover", position:"absolute", top:0, zIndex:-9}} source={{uri : "https://static.independent.co.uk/s3fs-public/thumbnails/image/2019/07/09/18/healthy-eating.jpg?width=982&height=726"}}/> <View style={{flex:1, justifyContent:"center", alignItems:"center", backgroundColor:"rgba(0,33,73,0.5)"}}> <View style={{justifyContent:"center", alignItems:"center"}}> <Text style={[styles.text, {textAlign:"center"}]}>It takes five minutes to consume 500 calories.</Text> <Text style={[styles.textSmallSize, {marginTop:10, textAlign:"center"}]}>Vestibulum in tellus ac lacus aliquet mollis. Nulla gravida sem in ornare pulvinar. Nam egestas urna quis erat molestie, eget vulputate dolor fringilla.</Text> </View> <View style={{alignSelf:"center", marginTop:10}}> <Button titleStyle={{color:"white"}} buttonStyle={{backgroundColor:"#6ac57b", width:100}} title="Go Back" onPress={() => props.navigation.goBack()} /> </View> </View> </View> </Swiper> ) }<file_sep>import React from "react" import {View,Text, StyleSheet} from "react-native" import { color } from "react-native-reanimated" export default function NutritionalCard () { return ( <View style={style.mainContent}> <Text style={{textAlign:"center", color:"#002149", fontSize:22, marginVertical:10}}>Nutritional Information</Text> <View style={style.nutritionalInfo}> <View style={style.nutritionalInfoContent}> <Text style={{color:"#c68487", fontSize:20, fontWeight:"bold"}}>243</Text> <Text>Calorias</Text> </View> <View style={style.nutritionalInfoContent}> <Text style={{color:"#002149", fontSize:20, fontWeight:"bold"}}>2,3g</Text> <Text>grasas</Text> </View> <View style={style.nutritionalInfoContent}> <Text style={{color:"#002149", fontSize:20, fontWeight:"bold"}}>2,4g</Text> <Text>carbohidratos</Text> </View> <View style={style.nutritionalInfoContent}> <Text style={{color:"#002149", fontSize:20, fontWeight:"bold"}}>9,8g</Text> <Text>proteinas</Text> </View> </View> </View> ) } const style = StyleSheet.create({ mainContent : { borderRadius:5, justifyContent:"center", }, nutritionalInfo : { flexDirection:"row", justifyContent:"space-around", alignItems:"center" }, nutritionalInfoContent : { justifyContent:"center", alignItems:"center" } }) <file_sep>import firebase from 'firebase/app'; const firebaseConfig = { apiKey: "AIzaSyDmaN7cVDZ2r_31HRcWa79c67Aje1rn2T4", authDomain: "regcitas-a03ee.firebaseapp.com", projectId: "regcitas-a03ee", storageBucket: "regcitas-a03ee.appspot.com", messagingSenderId: "240343262113", appId: "1:240343262113:web:af3a0173ff40e44ec221e0" }; export const firebaseApp = firebase.initializeApp(firebaseConfig); <file_sep>import React from "react" import Icon from 'react-native-vector-icons/FontAwesome'; import {View, Image} from "react-native" Icon.loadFont(); export default function FoodCard (props) { return ( <View style={{marginHorizontal:10, paddingVertical:10}}> <Image style={{width:180, resizeMode:"cover", flex:1}} source={{uri: props.imgUrl}}/> <Icon raised style={{position:"absolute", bottom:20, right:5}} size={40} name='arrow-circle-right' type='fontawesome' color='white' onPress={() => props.navigation.navigate("FoodDetails", { ...props })} /> </View> ) } <file_sep> <!-- PROJECT LOGO --> <br /> <p align="center"> <a> <img src="logo_avena.png" alt="Logo" width="80" height="80"> </a> <h3 align="center">Avenaio-Template</h3> <p align="center"> <NAME> </p> </p> <!-- ABOUT THE PROJECT --> ## About The Project a small demo for Avena.io ### Built With Frameworks used in this project. * [ReactNative](https://reactnative.dev/) ### Prerequisites This is a list things you need to use the software and how to install them. * npm ```sh npm install npm@latest -g ``` ### Installation 1. Clone the repo ```sh git clone https://github.com/Zeroxys/avenaio.git ``` 2. Install NPM packages ```sh npm install ``` <file_sep>import React from "react" import {View, Text, StyleSheet, TouchableOpacity, Platform} from "react-native" // import Icon from 'react-native-vector-icons/FontAwesome'; export default function CustomTabBar ({state, navigation, descriptors}) { console.log(state.routes) return ( <View style={style.mainContent}> {state.routes.map( (route, index) => { const { options } = descriptors[route.key]; const label = options.tabBarLabel !== undefined ? options.tabBarLabel : options.title !== undefined ? options.title : route.name; const isFocused = state.index === index; const onPress = () => { const event = navigation.emit({ type: 'tabPress', target: route.key, }); if (!isFocused && !event.defaultPrevented) { navigation.navigate(route.name); } }; const onLongPress = () => { navigation.emit({ type: 'tabLongPress', target: route.key, }); }; return ( <View key={index} style={{borderRadius:10,height:28, justifyContent:"center", backgroundColor: isFocused ? "#69d39e" : "transparent"}}> <TouchableOpacity accessibilityRole="button" accessibilityStates={isFocused ? ['selected'] : []} accessibilityLabel={options.tabBarAccessibilityLabel} testID={options.tabBarTestID} onPress={onPress} onLongPress={onLongPress} style={{flexDirection:"row", width:80, justifyContent:"space-around"}} > <Text style={{ color: isFocused ? 'white' : '#222', fontWeight:"bold" }}> {label} </Text> </TouchableOpacity> </View> ); })} </View> ) } const style = StyleSheet.create({ mainContent : { height:50, borderWidth: Platform.OS == "ios" ? 1 : 0, borderColor:"lightgray", borderTopRightRadius: 10, borderTopLeftRadius: 10, elevation:3, justifyContent:"space-around", alignItems:"center", flexDirection:"row" } }) <file_sep>import React from "react" import {View, Text, StyleSheet} from "react-native" import { AnimatedCircularProgress } from 'react-native-circular-progress'; export default function ActivityCard (props) { return ( <View style={styles.activityCard}> <Text style={{paddingLeft:10, fontWeight:"bold"}}>Results of the week</Text> <View style={styles.activityCardColumns}> <View style={{justifyContent:"center", alignItems:"center"}}> <Text style={{color:"gray", fontWeight:"600"}}>you have lost</Text> <Text style={{color:"#6ac57b", fontWeight:"bold"}}>{`${props.lostWeight}kg`}</Text> </View> <View style={{justifyContent:"center", alignItems:"center"}}> <Text style={{color:"gray", fontWeight:"600"}}>you level up</Text> <Text style={{color:"#6ac57b", fontWeight:"bold"}}>{`Level ${props.levelUp}`}</Text> </View> <View style={{justifyContent:"center", alignItems:"center"}}> <View> <AnimatedCircularProgress size={50} width={3} fill={70} tintColor="#6ac57b" backgroundColor="gray" /> <Text style={{fontSize:9, position:"absolute", top:20, left:5}}>{`${props.progress} Kcal`}</Text> </View> </View> </View> <View style={{flexDirection:"row", justifyContent:"center"}}> <Text style={{fontSize:12}}>Never give up. </Text> <Text style={{fontSize:12, color:"#6ac57b"}}>Know more</Text> </View> </View> ) } const styles = StyleSheet.create({ activityCard : { width:300, marginVertical:10, marginHorizontal:5, borderRadius:10, height:110, backgroundColor:"white", justifyContent:"center", shadowColor: "#000", shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 3.84, elevation: 5, }, activityCardColumns : { flexDirection:"row", justifyContent:"space-around", alignItems:"center", } })
aada08886739bc83acbb9b696c76aa5484fcfa6e
[ "JavaScript", "Markdown" ]
8
JavaScript
Zeroxys/avenaio
a8643b15228d9142faf978c945af11df62ab2fd4
8c1ac961d559b544ed035195e930227b138d5991
refs/heads/master
<repo_name>quentinalais/webtodolist<file_sep>/src/com/quentin/web/jdbc/LoginServlet.java package com.quentin.web.jdbc; import java.io.IOException; import javax.annotation.Resource; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; /** * Servlet implementation class LoginServlet */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Resource(name="jdbc/webtodolist") private DataSource dataSource; protected AccountDBUtil accountdbu; @Override public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub super.init(config); accountdbu =new AccountDBUtil(dataSource); } /** * @see HttpServlet#HttpServlet() */ public LoginServlet() { 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()); request.getRequestDispatcher("/login.jsp").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 String name= request.getParameter("Name"); String code= request.getParameter("Code"); Account temp=new Account(name,code); if(accountdbu.CheckAccount(temp)) { System.out.println("Welcome in the dodolist "+name); } else { System.out.println("Username or password incorrect ! "); } } }
9bfbd00cb0e6a376dae994600956148963a2c5b9
[ "Java" ]
1
Java
quentinalais/webtodolist
46e77f50720957ccbc82915104a1c8d9b704154b
bc546a77e3b9ce66e1a58103ab46c309531cd712
refs/heads/master
<file_sep>#Program to accept the first name and last name from user and print them in reverse order with space seperator #Accept the first name and store it in fname variable fname = input("Input your First Name : ") #Accept the Last name and store it in a lname variable lname = input("Input your Last Name : ") #Print in reverse order with space seperator print (lname + " " + fname)
43ed9baa089bffe0a8e911b541f1bc30075fa03e
[ "Python" ]
1
Python
sumalatha2020/Assignment-1.3
bc86af026f2f3cfa0664d2ccbe2053e375bc8871
9f926384d83e10eb66c7242e107be267a3fa7580
refs/heads/master
<file_sep>import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, OnInit, ViewChild} from '@angular/core'; import {ChatService} from '../../shared/chat.service'; import {DataModel} from '../../shared/models/data.model'; @Component({ selector: 'rs-messages', templateUrl: './messages.component.html', styleUrls: ['./messages.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class MessagesComponent implements OnInit { constructor( private chatService: ChatService, private changeDetector: ChangeDetectorRef, ) {} data: DataModel[] = []; @ViewChild('viewier', {static: false}) private viewer: ElementRef; ngOnInit(): void { this.chatService.messagesResponse .subscribe( (req: DataModel[]) => { this.data = this.data.concat(req); this.changeDetector.detectChanges(); this.scroll(); } ); } private scroll(): void { setTimeout(() => { this.scrollToBottom(); }, 100); } private getDiff(): number { if (!this.viewer) { return -1; } const nativeElement = this.viewer.nativeElement; return nativeElement.scrollHeight - (nativeElement.scrollTop + nativeElement.clientHeight); } private scrollToBottom(t = 1, b = 0): void { if (b < 1) { b = this.getDiff(); } if (b > 0 && t <= 120) { setTimeout(() => { const diff = this.easeInOutSin(t / 120) * this.getDiff(); this.viewer.nativeElement.scrollTop += diff; this.scrollToBottom(++t, b); }, 1 / 60); } } private easeInOutSin(t): number { return (1 + Math.sin(Math.PI * t - Math.PI / 2)) / 2; } public getSenderInitials(sender: string): string { return sender && sender.substring(0, 2).toLocaleUpperCase(); } public getSenderColor(sender: string): string { const alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZ'; const initials = this.getSenderInitials(sender); const value = Math.ceil((alpha.indexOf(initials[0]) + alpha.indexOf(initials[1])) * 255 * 255 * 255 / 50); return '#' + value.toString(16).padEnd(6, '0'); } } <file_sep>export interface DataModel { from: string; message: string; id: string; time: number; } export interface RequestMessage { from: string; message: string; } export class Message { constructor( public from: string, public message: string, ) {} } <file_sep>import {NgModule} from '@angular/core'; import {ChatComponent} from './chat.component'; import {CommonModule} from '@angular/common'; import {MaterialModule} from '../shared/material/material.module'; import {ReactiveFormsModule} from '@angular/forms'; import { MessagesComponent } from './messages/messages.component'; import { InputMessageComponent } from './input-message/input-message.component'; import {ChatRoutingModule} from './chat-routing.module'; @NgModule({ declarations: [ ChatComponent, MessagesComponent, InputMessageComponent ], imports: [ CommonModule, MaterialModule, ReactiveFormsModule, ChatRoutingModule ], exports: [ ChatComponent ] }) export class ChatModule {} <file_sep>import {EventEmitter, Injectable} from '@angular/core'; import {Message} from './models/data.model'; import {WebSocketSubject} from 'rxjs/webSocket'; import {map} from 'rxjs/operators'; @Injectable() export class ChatService { messagesResponse = new EventEmitter(); // private url = 'ws://st-chat.shas.tel'; private url = 'wss://wssproxy.herokuapp.com/ '; public serverMessages = []; public clientMessage = ''; public sender = window.localStorage.getItem('nickname'); private socket$: WebSocketSubject<any>; constructor() { if (this.sender == null) { this.sender = 'Username'; } this.connect(); // this.socket$ = new WebSocketSubject(this.url); // this.socket$ // .pipe( // map( message => message.reverse() ) // ) // .subscribe( // (message) => this.messagesResponse.emit(message), // (err) => this.socket$.retry(), // () => console.warn('Completed!') // ); } public send(requestMessage): void { this.clientMessage = requestMessage; const message = new Message(this.sender, this.clientMessage); this.serverMessages.push(message); this.socket$.next(message); this.clientMessage = ''; } public connect() { console.log('reconnect'); this.socket$ = new WebSocketSubject(this.url); this.socket$ .pipe( map( message => message.reverse() ) ) .subscribe( (message) => this.messagesResponse.emit(message), () => { setTimeout( () => { this.connect(); }, 1000 ); }, () => { setTimeout( () => { this.connect(); }, 1000 ); } ); } public changeName(newName: string) { this.sender = newName; } } <file_sep>import {Injectable} from '@angular/core'; @Injectable() export class WebsocketService { ws = new WebsocketService(); } <file_sep>import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core'; import {FormControl, FormGroup} from '@angular/forms'; import {ChatService} from '../../shared/chat.service'; @Component({ selector: 'rs-input-message', templateUrl: './input-message.component.html', styleUrls: ['./input-message.component.scss'] }) export class InputMessageComponent implements OnInit, AfterViewInit { form: FormGroup; @ViewChild('name', {static: false}) private nickname: ElementRef; constructor( private chatService: ChatService ) { } ngAfterViewInit(): void { if (window.localStorage.getItem('nickname')) { this.nickname.nativeElement.value = window.localStorage.getItem('nickname'); } else { this.nickname.nativeElement.value = 'Username'; } } ngOnInit() { this.form = new FormGroup({ request: new FormControl(''), }); } sendMessage() { const request = this.form.value.request; this.form.reset(); this.chatService.send(request); } updateName() { console.log(this.nickname.nativeElement.value); let newName = this.nickname.nativeElement.value; if (newName.length === 0) { newName = 'I forgot to come up with a nickname'; } window.localStorage.setItem('nickname', newName); this.chatService.changeName(newName); } } <file_sep>import {Component, OnInit} from '@angular/core'; import {ChatService} from '../shared/chat.service'; import {DataModel} from '../shared/models/data.model'; import {FormControl, FormGroup, Validators} from '@angular/forms' @Component({ selector: 'rs-chat', templateUrl: './chat.component.html', styleUrls: ['./chat.component.scss'] }) export class ChatComponent implements OnInit { constructor(private chatService: ChatService) {} private url = 'ws://st-chat.shas.tel'; data: DataModel; form: FormGroup; ngOnInit(): void { // this.form = new FormGroup({ // request: new FormControl('', Validators.required), // }); // // this.chatService.connect(this.url); // this.chatService.messagesResponse // .subscribe( // (req) => { // console.log(req); // this.data = req; // // Здесь вручную запустить обновление контента // } // ); } }
5951210eede56536645982299eaf64ad85517276
[ "TypeScript" ]
7
TypeScript
greatorangejuice/rs-chat
ce1d65264f08beb135a28857a0adb6dee2b074fd
3e1a330d3e474ebf538267d0f94764ff86b4697c
refs/heads/master
<repo_name>wckgo/topology_demo<file_sep>/src/chart/topology/storage.ts namespace storage { export interface NodeEntity extends d3.SimulationNodeDatum { id: string; name: string; type: string; active: boolean; connected: boolean; source?: Array<any>; target?: Array<any>; totalCount?: number; layerIndex?: number; childNodes?: Array<NodeEntity>; expand?: boolean; } export function isNodeEntity(object): object is NodeEntity { return object && object.connected !== undefined; } } export default storage; <file_sep>/src/main.ts import * as $ from 'jquery'; import wgcharts from './wgcharts'; import * as d3 from 'd3'; class Initializer { public static initSideBar(): void { $('#left').children().click((e) => { $('#left').children().removeClass('dzB-a dbj-m'); const input = $(e.currentTarget).addClass('dzB-a dbj-m').find('input'); const name = input.attr('name'); $.getJSON(`public/data/${name}.json`, (data) => { const chart = wgcharts.init(document.getElementById('drawing-board')); const flat = chart.flatTopology(data); flat.onNodeClick((d) => { $.getJSON('public/data/topo.json', (data) => { chart.treeTopology(data); }); }); flat.onNodeOutLink(() => { console.log('node out link') }); }); }); } } Initializer.initSideBar();<file_sep>/src/util/guid.ts let idStart:number = 0x0907; function guid():number { return idStart++; } export default guid;<file_sep>/src/wgcharts.ts import * as d3 from 'd3'; import guid from './util/guid'; import FlatTopology from './chart/topology/flat-topology'; import TreeTopology from './chart/topology/tree-topology'; export default class wgcharts { private static instances: Map<number, WGChart> = new Map(); public static init(dom: Element): WGChart { const id = guid(); const chart = new WGChart(id, dom); this.instances.set(id, chart); return chart; } } class WGChart { private id: number; private svg: d3.Selection<d3.BaseType, {}, null, undefined> constructor(id: number, dom: Element) { this.id = id; this.svg = d3.select(dom).html(null).append('svg').attr('id', id) .attr('width', '100%').attr('height', '100%'); } public flatTopology(data: any): FlatTopology { const chart = new FlatTopology(this.svg); chart.draw(data); return chart; } public treeTopology(data: any): TreeTopology { const chart = new TreeTopology(this.svg); chart.draw(data); return chart; } }<file_sep>/src/util/common-util.ts import * as d3 from 'd3'; class CommonUtil { public static calculateFontWidth(fontsize: string, text: string): number { const font = d3.select('#font-test-area'); if (!font.size()) { d3.select('body').append('text').attr('id','font-test-area').attr('style', 'color:black;line-height:1.2;white-space:nowrap;top:0px;left:0px;position:fixed;display:block;visibility:hidden;'); } return d3.select('#font-test-area').style('font-size', fontsize).text(text).property('clientWidth'); } } export default CommonUtil;<file_sep>/src/chart/chart.ts abstract class Chart { abstract draw(data: any); } export default Chart;<file_sep>/webpack.common.js const path = require('path'); const copyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: ['babel-polyfill', './src/main.ts'], resolve: { extensions: ['.ts', '.js', '.json'] }, plugins: [ new copyWebpackPlugin([{ from: __dirname + '/src/public', //打包的静态资源目录地址 to: './public' //打包到dist下面的public }]) ] };<file_sep>/src/chart/topology/flat-topology.ts import Topology from './topology'; import * as d3 from 'd3'; import storage from './storage'; class FlatTopology extends Topology { private randomNormal = d3.randomNormal(150, 10); draw(data: Array<storage.NodeEntity>): void { // const disperseNodeEntities: Array<storage.NodeEntity> = []; // const connectedNodeEntities: Array<storage.NodeEntity> = []; // data.map((item) => { // if (item.connected) { // connectedNodeEntities.push(item); // } else { // disperseNodeEntities.push(item); // } // }); // if (disperseNodeEntities.length) { // this.circularDispersion(disperseNodeEntities); // } // if (connectedNodeEntities.length) { // this.simulatedDispersion(connectedNodeEntities); // } this.simulatedDispersionV2(data); } private simulatedDispersionV2(data: Array<storage.NodeEntity>): void { const width = this.svg.property('clientWidth'); const height = this.svg.property('clientHeight'); const links = []; data.forEach(item => { if (item.target && item.target.length > 0) { const sourceId = item.id; item.target.forEach((item: any) => { const link = { source: sourceId, target: item }; links.push(link); }); } }); const isolate = (force, filter) => { var initialize = force.initialize; force.initialize = function () { initialize.call(force, data.filter(filter)); }; return force; } const forceRadial = d3.forceRadial(height / 2).x(width / 2).y(height / 2) //.strength(353 / (300 * 300)); const g = this.creatNode(data); const force = d3.forceSimulation(data) .force('link', d3.forceLink(links).id((d: any) => { return d.id; }).distance(() => { return this.randomNormal() })) .force("charge", d3.forceManyBody().strength((d: any) => { return d.connected ? -300 : -30 })) .force('charge2', d3.forceCollide(50)) .force("center", d3.forceCenter(width / 2, height / 2)) //.force('r', isolate(forceRadial, (d) => {return !d.connected})) .force('y', d3.forceY(height / 2).strength((d: any) => { return d.connected ? 0.05 : 0.01 })) .force('x', d3.forceX(width / 2).strength((d: any) => { return d.connected ? 0.05 : 0.01 })) .on('tick', () => { g.attr('transform', d => { return `translate(${d.x}, ${d.y})`; }) }) .on('end', () => { this.creatNodeLinks(data, 'common'); }) //force.tick(); // while(force.alpha() >= force.alphaMin()) { // force.tick(); // } // for (let i = 0, n = Math.ceil(Math.log(force.alphaMin()) / Math.log(1 - force.alphaDecay())); i < n; ++i) { // force.tick(); // } links.forEach((link, index) => { if (index == 0) { link.source.source = []; link.source.target = []; link.target.target = []; link.target.source = []; } link.source.target.push(link.target); link.target.source.push(link.source); }); } private simulatedDispersion(data: Array<storage.NodeEntity>): void { const width = this.svg.property('clientWidth'); const height = this.svg.property('clientHeight'); const links = []; data.forEach(item => { if (item.target && item.target.length > 0) { const sourceId = item.id; item.target.forEach((item: any) => { const link = { source: sourceId, target: item }; links.push(link); }); } }); const force = d3.forceSimulation(data) .force('link', d3.forceLink(links).id((d: any) => { return d.id; }).distance(() => { return this.randomNormal() })) .force("charge", d3.forceManyBody().strength((d: any) => { return d.connected ? -30 : -600 })) .force('charge', d3.forceCollide(110)) .force("center", d3.forceCenter(width / 2, height / 2)) .force('x', d3.forceX()) .force('y', d3.forceY()) .stop(); for (let i = 0, n = Math.ceil(Math.log(force.alphaMin()) / Math.log(1 - force.alphaDecay())); i < n; ++i) { force.tick(); } links.forEach((link, index) => { if (index == 0) { link.source.source = []; link.source.target = []; link.target.target = []; link.target.source = []; } link.source.target.push(link.target); link.target.source.push(link.source); }); this.creatNodeLinks(data, 'common'); this.creatNode(data); } private circularDispersion(data: Array<storage.NodeEntity>): void { const perRadian = 2 * Math.PI / data.length; const width = this.svg.property('clientWidth'); const height = this.svg.property('clientHeight'); const xAxisOffset = width / 2; const yAxisOffset = height / 2; let radius = width < height ? width * 0.4 : height * 0.4; if (radius < 45 * data.length / Math.PI) { radius = 45 * data.length / Math.PI; } for (let i = 0; i < data.length; i++) { const alpha = perRadian * i; data[i].x = (Math.cos(alpha) * radius) + xAxisOffset; data[i].y = (Math.sin(alpha) * radius) + yAxisOffset; } this.creatNode(data); } } export default FlatTopology;<file_sep>/src/chart/topology/tree-topology.ts import Topology from './topology'; import * as d3 from 'd3'; import storage from './storage'; class TreeTopology extends Topology { draw(data: any): void { const map = new Map(); for (let key in data.node2Group) { map.set(key, data.node2Group[key]); } data.node2Group = map; this.hierarchicalDispersion(data.data, data.node2Group); } private hierarchicalDispersion(data: Array<Array<storage.NodeEntity>>, node2Group: Map<string, string>): void { const width = this.svg.property('clientWidth'); const height = this.svg.property('clientHeight'); const perHeight = height / data.length; const nodesGroup = []; let allNodes = []; data.forEach((groups, index) => { const nodes = []; const groupY = perHeight * index + perHeight / 2; groups.forEach((group, index) => { if (group.totalCount > 1) { if (group.expand) { group.childNodes.forEach((node, index) => { node.y = perHeight; this.calculatePostion(nodes, node, index == 1 ? 55 : 10, width); nodes.push(node); }); group.x = group.childNodes[0].x; group.y = groupY; nodesGroup.push(group); } else { let sourceSet = new Array<string>(); let targetSet = new Array<string>(); group.childNodes.forEach((node) => { if(node.source) { sourceSet = sourceSet.concat(node.source); } if(node.target) { targetSet = targetSet.concat(node.target); } }); group.source = Array.from(new Set(sourceSet)); group.target = Array.from(new Set(targetSet)); group.y = groupY; this.calculatePostion(nodes, group, 55, width); nodes.push(group); } } else if (group.totalCount == 1) { group.childNodes[0].y = groupY; this.calculatePostion(nodes, group.childNodes[0], 55, width); nodes.push(group.childNodes[0]) } }); allNodes = allNodes.concat(nodes); }); this.calculateLinks(allNodes, node2Group); this.creatNode(allNodes); this.creatNodeLinks(allNodes,'vertical'); } private calculateLinks(nodes: Array<storage.NodeEntity>, node2Group: Map<string, string>) { const map = new Map(); nodes.forEach((node) => { map.set(node.id, node); }); nodes.forEach((node) => { const sources = []; const targets = []; node.source && node.source.forEach((item) => { map.has(item) ? sources.push(map.get(item)) : sources.push(map.get(node2Group.get(item))); }); node.target && node.target.forEach((item) => { map.has(item) ? targets.push(map.get(item)) : targets.push(map.get(node2Group.get(item))); }); node.source = sources; node.target = targets; }); } private calculatePostion(nodes: Array<storage.NodeEntity>, node: storage.NodeEntity, offset: number, width: number) { if (nodes.length == 0) { node.x = width / 2; } else { node.x = nodes[nodes.length - 1].x + offset; nodes.forEach(node => { node.x -= offset; }); } } private creatNodeGroup(group: storage.NodeEntity) { console.log('to creat a group', group); } } export default TreeTopology;<file_sep>/README.md # A simple example of creating a topology with D3.js<file_sep>/src/chart/topology/topology.ts import CommonUtil from '../../util/common-util'; import Chart from '../chart'; import storage from './storage'; import * as d3 from 'd3'; abstract class Topology extends Chart { protected svg: d3.Selection<d3.BaseType, {}, HTMLElement, any>; protected context: d3.Selection<d3.BaseType, {}, HTMLElement, any>; protected nodeClickListener: (date?, index?, group?) => void; protected nodeOutLinkListener: (date?, index?, group?) => void; protected height: number; protected width: number; constructor(svg: d3.Selection<d3.BaseType, {}, HTMLElement, any>) { super(); this.svg = svg; this.initBoard(); } onNodeClick(listener: (date?, index?, group?) => void): void { this.nodeClickListener = listener; } onNodeOutLink(listener: (date?, index?, group?) => void): void { this.nodeOutLinkListener = listener; } protected creatNodeLinks(nodes: Array<storage.NodeEntity>, type: string): void { const g = this.context.insert('g', ':first-child'); nodes.forEach((node) => { node.target && node.target.forEach((item) => { let path switch (type) { case 'common': path = g.append('path').attr('class', 'dhc-e').attr('id', `wg-node-link-${node.id}-${item.id}`).attr('d', this.link({ source: node, target: item })); break; case 'vertical': const link = d3.linkVertical()({ source: [node.x, node.y], target: [item.x, item.y] }); path = g.append('path').attr('class', 'dhc-e').attr('id', `wg-node-link-${node.id}-${item.id}`).attr('d', link.toString()); break; } if (!item.active) { path.classed('dhc-p', true); } }); }); } protected link(link: any): string { const dx = link.target.x - link.source.x; const dy = link.target.y - link.source.y; const dr = Math.sqrt(dx * dx + dy * dy); return `M ${link.source.x} ${link.source.y} , A ${dr} , ${dr} 0 0, 1 ${link.target.x} , ${link.target.y}`; } protected creatNodeCard(data: storage.NodeEntity): void { if (this.context.select('#nodeCardContext').size()) { this.context.select('#nodeCardContext').remove(); } const translate = `translate(${data.x}, ${data.y})`; const cardContext = this.context.append('g').datum(data).attr('cursor', 'pointer').attr('id', 'nodeCardContext'); const cardGroup = cardContext.append('g').attr('transform', translate).attr('class', 'dic-y dic-a dic-q'); let font = data.name.length > data.type.length ? data.name : data.type; const fontWidth = CommonUtil.calculateFontWidth('13px', font); let width = fontWidth + 80; if (font.length > 100) { width = 100 } const pathA = `M -27 0 a 27 27 0 1 0 54 0 a 27 27 0 1 0 -54 0 z M 0 29 A 29 29 0 1 1 0 -29 h ${width} v 51 a 7 7 0 0 1 -7 7 z`; const pathB = d3.path(); pathB.arc(0, 0, 27, 0, 2 * Math.PI); cardGroup.append('path').attr('d', pathA).attr('class', 'dic-I'); const card = cardGroup.append('path').attr('d', pathB.toString()).attr('class', 'dic-J'); cardGroup.append('text').style('font-size', '13px').attr('x', '35px').attr('y', '-9px').text(data.name); cardGroup.append('text').style('font-size', '10px').attr('x', '35px').attr('y', '13px').text(data.type); const gotoTranslate = `translate(${data.x + width}, ${data.y - 29})`; const goto = cardContext.append('g').attr('transform', gotoTranslate).attr('class', 'dic-z dic-q'); goto.append('path').attr('d', 'M 0 0 v 51 a 7 7 0 0 1 -7 7 h -25 v -58 z').attr('class', 'dic-s'); goto.append('g').attr('transform', 'translate(-21 9)').attr('class', 'dic-i').append('use').attr('xlink:href', '#gotoIcon'); if (data.totalCount) { this.creatCountCard(cardGroup, data.totalCount, `wg-node-${data.id}`); } cardContext.on('mouseleave ', () => { this.context.select('#nodeCardContext').remove(); if (data.source && data.source.length > 0) { data.source.forEach(item => { this.context.select(`#wg-node-${item.id}`).select('circle').attr('stroke', '#607d8b'); this.context.select(`#wg-node-link-${item.id}-${data.id}`).classed('dhc-n dhc-q', false).attr('marker-mid', null); }); } if (data.target && data.target.length > 0) { data.target.forEach(item => { this.context.select(`#wg-node-${item.id}`).select('circle').attr('stroke', '#607d8b'); this.context.select(`#wg-node-link-${data.id}-${item.id}`).classed('dhc-n dhc-q', false).attr('marker-mid', null); }); } if (data.totalCount) { this.creatCountCard(d3.select(`wg-node-${data.id}`), data.totalCount, `wg-node-${data.id}`); } }); if (this.nodeClickListener) { d3.selectAll(cardGroup.nodes()).on('click', this.nodeClickListener); } if (this.nodeOutLinkListener) { goto.on('click', this.nodeOutLinkListener); } card.on('click', null); card.on('clcik', (data, index, node) => { const nodeCoordinate:any = (<Element>node[index]).getBoundingClientRect(); const offsetX = this.width / 2 - nodeCoordinate.x; const offsetY = this.height / 2 - nodeCoordinate.y; const t = d3.zoomIdentity.translate(offsetX, offsetY).scale(1.5); this.context.attr("transform", t.toString()); }) } protected creatNode(data: storage.NodeEntity[]): d3.Selection<d3.BaseType, storage.NodeEntity, d3.BaseType, {}> { const g = this.context.selectAll('g').data(data, (d: any, i) => { return d == undefined || d.id == undefined ? i : d.id }) .enter().append('g'); g.transition() //.duration(200).delay(100).ease(d3.easeLinear) .attr('transform', d => { return `translate(${d.x}, ${d.y})`; }) .attr('id', d => { return `wg-node-${d.id}` }); g.append('circle').attr('fill-opacity', 1.0) .attr('cx', 0).attr('cy', 0).attr('r', (d) => { return d.totalCount ? 27 : 20 }) .attr('stroke', '#607d8b').attr('fill', '#cccccc').attr('stroke-width', '1.5'); g.append('g').attr('transform', 'translate(-10, -10)').append('use').attr('xlink:href', '#icon'); g.each((d, i, g) => { if (d.totalCount) { this.creatCountCard(d3.select(g[i]), d.totalCount, d.id); } }) g.on('mouseover', (data, index, node) => { if (data.totalCount) { d3.select(`#wg-node-${data.id}-countCard`).remove(); } if (data.source && data.source.length > 0) { data.source.forEach(item => { this.context.select(`#wg-node-${item.id}`).select('circle').attr('stroke', '#00a0f2'); this.context.select(`#wg-node-link-${item.id}-${data.id}`).classed('dhc-n dhc-q', true).attr('marker-mid', 'url(#wg-marker)'); }); } if (data.target && data.target.length > 0) { data.target.forEach(item => { this.context.select(`#wg-node-${item.id}`).select('circle').attr('stroke', '#00a0f2'); this.context.select(`#wg-node-link-${data.id}-${item.id}`).classed('dhc-n dhc-q', true).attr('marker-mid', 'url(#wg-marker)'); }); } this.creatNodeCard(data); }); return g; } protected creatCountCard(context: d3.Selection<d3.BaseType, {}, HTMLElement, any>, count: number, id: string): void { const countGroup = context.append('g').attr('cursor', 'pointer').attr('id', `${id}-countCard`); const fontWidth = CommonUtil.calculateFontWidth('14', count.toString()); countGroup.append('rect').attr('rx', 3).attr('ry', 3).attr('width', fontWidth + 10).attr('height', 16).attr('x', - fontWidth / 2 - 5).attr('y', 19) .attr('fill-opacity', '1.0').attr('fill', '#cccccc').attr('stroke', '#607d8b'); countGroup.append('text').attr('font-size', '14').attr('x', - fontWidth / 2).attr('y', '32.25') .attr('display', 'inline').style('fill', 'black').text(count); } protected initBoard(): void { this.context = this.svg.html(null).append('g').attr('id', 'context'); this.svg.call(d3.zoom().scaleExtent([1 / 2, 4]).on('zoom', () => { this.context.attr("transform", d3.event.transform.toString()); })); this.width = this.svg.property('clientWidth'); this.height = this.svg.property('clientHeight'); this.svg.append("defs").append("marker").attr("id", 'wg-marker').attr("viewBox", "0 -5 10 10") .attr("refX", 15).attr("refY", -1.5).attr("markerWidth", 6).attr("markerHeight", 6).attr("orient", "auto") .append("svg:path").attr("d", "M0,-5L10,0L0,5").attr('fill', '#00a0f2'); d3.svg('public/icon/icon.svg').then( (date) => { const node = date.firstElementChild; node.setAttribute('width', '20px'); node.setAttribute('height', '20px'); node.setAttribute('fill', '#454646'); node.setAttribute('viewBox', '0 0 512 512'); node.setAttribute('id', 'icon'); this.svg.select('defs').append(() => { return node }); } ); d3.svg('public/icon/goToIcon.svg').then( (data) => { const node = data.firstElementChild; node.setAttribute('width', '16px'); node.setAttribute('height', '16px'); node.setAttribute('viewBox', '0 0 512 512'); node.setAttribute('id', 'gotoIcon'); this.svg.select('defs').append(() => { return node; }); } ); } protected creatNodev2(data: any): void { const g = this.context.append('g').attr('transform', d => { return `translate(100, 300)`; }); g.append('circle').attr('fill-opacity', 1.0).attr('cx', 0).attr('cy', 0).attr('r', 27) .attr('stroke', '#ffffff').attr('fill', '#60acfc').attr('stroke-width', '1.5'); g.on('mouseover', () => { this.creatNodeCardv2(); }); } protected creatNodeCardv2(): void { // if (this.context.select('#nodeCardContext').size()) { // this.context.select('#nodeCardContext').remove(); // } const translate = `translate(100, 300)`; const cardContext = this.context.append('g') .attr('cursor', 'pointer').attr('id', 'nodeCardContext').attr('transform', translate); const cardGroup = cardContext.append('g'); //let font = data.name.length > data.type.length ? data.name : data.type; //const fontWidth = CommonUtil.calculateFontWidth('13px', font); //let width = fontWidth + 80; //if (font.length > 100) { width = 100 } const pathA = `M 0 -54 h 200 v 108 h -200 M 0 29 A 27 27 0 0 0 0 -29`; const pathB = d3.path(); pathB.arc(0, 0, 27, 0, 2 * Math.PI); cardGroup.append('path').attr('d', pathA).attr('fill', '#01a6f3').attr('fill-opacity', 0.5); const card = cardGroup.append('path').attr('d', pathB.toString()).attr('fill', 'rgba(0, 0, 0, 0)').attr('stroke', 'rgba(0, 0, 0, 0)'); //cardGroup.append('text').style('font-size', '13px').attr('x', '35px').attr('y', '-9px').text(data.name); //cardGroup.append('text').style('font-size', '10px').attr('x', '35px').attr('y', '13px').text(data.type); //const gotoTranslate = `translate(100, ${-29})`; //const goto = cardContext.append('g').attr('transform', gotoTranslate); //goto.append('path').attr('d', 'M 0 0 v 51 a 7 7 0 0 1 -7 7 h -25 v -58 z').attr('class', 'dic-s'); //goto.append('g').attr('transform', 'translate(-21 9)').attr('class', 'dic-i').append('use').attr('xlink:href', '#gotoIcon'); cardContext.on('mouseleave ', () => { // this.context.select('#nodeCardContext').remove(); }); } } export default Topology;
ef4a080d133addb3fffda9e394e0d0eed41b767a
[ "JavaScript", "TypeScript", "Markdown" ]
11
TypeScript
wckgo/topology_demo
508c5d31a87b64916e875126a4b147c54c1ac09a
1c462b3af476f1c428b8a4c564f1dadb5618f3c6
refs/heads/main
<file_sep># ms_automation_tutorial Repo for this tutorial: https://egov.atlassian.net/l/c/PdpHzHjD<file_sep>Vagrant.configure("2") do |config| config.vm.box = "dummy" config.vm.provider :managed do |managed, override| managed.server = ENV['MANAGED_IP'] override.vm.box = 'tknerr/managed-server-dummy' override.ssh.username = "ubuntu" override.ssh.private_key_path = "./.ssh/private.key" end config.nfs.functional = false # Override the default sync'd folder, supressing NFS, then allow rsync config.vm.allowed_synced_folder_types = [:rsync] config.vm.synced_folder '.', '/vagrant', type: "rsync", rsync__exclude: [".git/", ".vagrant/"] config.vm.box_check_update = false #################### # SHELL PROVISIONERS #################### # Install Puppet Agent config.vm.provision "shell", preserve_order: true, name: "Download Puppet Installer", inline: "curl -1 -sL https://apt.puppet.com/puppet7-release-bionic.deb > /tmp/puppet7-release-bionic.deb" config.vm.provision "shell", preserve_order: true, name: "Replace Puppet Packages", inline: "sudo dpkg -i '/tmp/puppet7-release-bionic.deb'" config.vm.provision "shell", preserve_order: true, name: "Install Puppet Module", inline: "sudo apt-get update && sudo apt-get install -y puppet-agent" # Install Puppet Modules config.vm.provision "shell", preserve_order: true, name: "Install Archive Module", inline: "puppet module install --force --modulepath=/opt/puppetlabs/puppet/modules puppet-archive --version 5.0.0" config.vm.provision "shell", preserve_order: true, name: "Install SystemD Module", inline: "puppet module install --force --modulepath=/opt/puppetlabs/puppet/modules camptocamp-systemd --version 2.12.0" #################### # PUPPET PROVISIONER #################### config.vm.provision :puppet do |puppet| puppet.environment_path = "./puppet/environments" puppet.environment = 'dev' options = ['--graph'] puppet.facter = { "managed_ip" => ENV['MANAGED_IP'], "installdir" => ENV['INSTALLDIR'] || '/tmp' } end end
adaa8765792330dcfd79cbd47a7dff97b0bf7e35
[ "Markdown", "Ruby" ]
2
Markdown
rdeanmcdonald/ms_automation_tutorial
2547fc4d2bb67bf1e721568c896d31464bdbe6a2
b2d54b3835c2534daf2f6fbfe602100f118c25c7
refs/heads/master
<file_sep># Leibniz-PI This program calculates PI number with the Leibniz formula.<br/> **It may take about 2 minutes to run!** <file_sep>#include <iostream> using namespace std; int main() { double pi = 1; long long frac = 3; for (long long i = 1; i <= 8000000001; i++) { if (i % 2 == 0) pi += (double)1 / frac; else pi -= (double)1 / frac; frac += 2; } cout.precision(11); cout << pi * 4; return 0; }
670a7237fa68ebaae4aa415dbdf73ad6e528295c
[ "Markdown", "C++" ]
2
Markdown
PetrusTryb/Leibniz-PI
662ad3712e807f40a5c1c56f39087064fab73eae
66021fcc519796533e9249a535e2d9fccf85ce50
refs/heads/master
<repo_name>cjolliet/Projet-Awele<file_sep>/projet.c #include "Outil.h" #define N 2 #define M 6 /** *\file *\brief Programme permettant de jouer une partie d'Awélé *\author <NAME> *\date Jeudi 1 Décembre 2016 *\fn void init_Mat(int Mat[N][M]) *\fn void AfficherMat(int Mat[N][M]) *\fn int Choix_case(int Mat[N][M], char typeJ, int joueur) *\fn int Case_Vide(int Mat[N][M], int joueur, int j, int nb, char typeJ) *\fn int Compte_Graine(int Mat[N][M]) *\fn int CapturePoints(int Mat[N][M], int joueur, int j, int nb) *\fn int deplacement_gauche (int Mat[N][M], int j, int joueur, int nb) *\fn int deplacement_droite (int Mat[N][M], int j, int joueur, int nb) *\fn int deplacement(int Mat[N][M], int j, int joueur, int nb) *\fn int JouerTourCapture(int Mat[N][M], int j, int joueur, int nb, int total, char typeJ, int fin) *\fn void JouerTour(int Mat[N][M], int j, int joueur, int nb, char typeJ, int fin) *\fn int ArretJeu(int j1, int j2, char c, int fin, int arret) *\fn int Test(int comptest) *\fn void Partie_Solo(void) *\fn void Partie_A2(void) *\fn int Highscores(FILE * fic, int compt) *\fn int main2(void) *\fn void ModuleAmorceR(void) *\fn int main(void) */ int deplacement_droite (int Mat[N][M], int j, int joueur, int nb); int deplacement_gauche (int Mat[N][M], int j, int joueur, int nb); int Compte_Graine(int Mat[N][M]); int bChaineEgale(char *sTexte1, char *sTexte2); //Toujours utile au cas où (surtout pour des mots de passe); int main2(); /**\brief Initialise les valeurs de l'Awélé à 4*/ void init_Mat(int Mat[N][M]){ //Initialisation de l'Awélé int i, j; for(i = 0 ; i < N ; i++){ for(j = 0 ; j < M ; j++){ Mat[i][j] = 4; } } } /**\brief Affiche les valeurs courantes de l'Awélé*/ void AfficherMat(int Mat[N][M]){ //Affichage de l'Awélé et du reste des graines int i, j, reste; printf("\n 1 2 3 4 5 6\n"); for(i = 0; i < N; i++){ printf("J%i ", i+1); for(j = 0; j < M ; j++){ printf("%i ",Mat[i][j]); } printf("\n"); } reste = Compte_Graine(Mat); printf("\nIl reste %i points à prendre\n", reste); } int Ordi(int Mat[N][M], int joueur){ int jc; int j = 0; int maxO = 0; if(joueur == 0){ printf("Témoin 2\n"); jc = 0; While(8); while( bWhile("Pourquoiça?!(Ordi0())",(jc < 6) || ( (Mat[1][j] == 2) || (Mat[1][j] == 3) ) )){ jc++; } printf("Témoin 3 : jc = %i\n", jc); While(8); while(bWhile("Pourquoiça?!(Choix_case Ordi)",(Mat[joueur][j] <= maxO) && (j < 6) ) ){ if(Mat[joueur][j] > maxO){ maxO = Mat[joueur][j]; } j++; } printf("Témoin 4 : j = %i ; jc + j = %i\n", j, (jc + j)); if( ((j + jc) != maxO) && (maxO < 12)){ j = maxO - 6; } else { while( maxO >= 12 ){ maxO = maxO - 6; } j = maxO; } printf("Témoin 5 : j = %i\n", j); } else if(joueur == 1){ printf("Témoin 2bis\n"); jc = 5; While(8); while( bWhile("Pourquoiça?!(Ordi1())",(jc >= 0) || ( (Mat[0][j] == 2) || (Mat[0][j] == 3) ) )){ jc--; } printf("Témoin 3bis : jc = %i\n", jc); While(8); while( bWhile("Pourquoiça?!(Choix_case Ordi)",(Mat[joueur][j] <= maxO) && (j < 6) )){ if(Mat[joueur][j] > maxO){ maxO = Mat[joueur][j]; } j++; } printf("Témoin 4bis : j = %i ; jc + j = %i\n", j, (jc +j)); if( ((j + jc) != maxO) && (maxO < 12)){ j = maxO - 6; } else { while( maxO >= 12 ){ maxO = maxO - 6; } j = maxO; } printf("Témoin 5bis : j = %i\n", j); } return j; } /**\brief Sélection d'une case de l'Awélé*/ int Choix_case(int Mat[N][M], char typeJ, int joueur){ //Sélection de la case à déplacer selon le type de joueur int j; char c; printf("\nDéplacer quelle case ? \n"); if(typeJ == 'J'){ //Joueur 'réel' scanf("%i",&j); while((j >= 7) || (j < 0)){ //Limites de la matrice prises en compte printf("Hors Limite !\nRecommencez : "); scanf("%i", &j); } if(j == 0){ printf("Voulez-vous terminer le jeu ? (Attention, à 2 joueur vous passez votre tour)\n(y or n)\n"); scanf("%*c%c", &c); if(c == 'n'){ printf("Reprenons alors...\n"); j = Choix_case(Mat, typeJ, joueur); } else if(c == 'y'){ j = 0; } else { printf("Mal écrit, on reprend : \n"); j = Choix_case(Mat, typeJ, joueur); } } } else if (typeJ == 'O'){ //Joueur 'Ordinateur', choisi sa case au hasard printf("Témoin 1\n"); j = Ordi(Mat, joueur); if( j == 0 ){ //Prévision en cas de j nul j = 1; } printf("\nOrdi déplace case %i", j); } else { //On prévoit l'erreur sur 'typeJ' printf("ERREUR, 'typeJ' erronné : %c\nArrêt forcé\n", typeJ); j = -1; } return j; } /**\brief Test de Case vide avec correction imposée*/ int Case_Vide(int Mat[N][M], int joueur, int j, int nb, char typeJ){ //On prend en compte les cases vides et on force le joueur à en changer while(nb == 0){ printf("\nErreur, Case vide\n"); j = Choix_case(Mat, typeJ, joueur); if(j > 0){ j--; } nb = Mat[joueur][j]; printf("\nnb points : %i\n", nb); AfficherMat(Mat); } return j; } /**\brief Compte le total de la somme des valeurs de l'Awélé*/ int Compte_Graine(int Mat[N][M]){ //Pour garder l'oeil sur le nombre de billes/graines restantes, aussi bien durant les tests que durant la partie int i, j; int comptG = 0; for (i = 0 ; i < N ; i++){ for(j = 0 ; j < M ; j++){ comptG = comptG + Mat[i][j]; } } return comptG; } /**\brief Ajoute les points des cases concernées au joueur concerné*/ int CapturePoints(int Mat[N][M], int joueur, int j, int nb){ //Capture des points; on s'assure d'être sur la bonne ligne pour commencer int totalpris = 0; if( ((j - 6) > 0) && (nb < 12)){ j = j - 6; } else if( nb >= 12 ){ while((j - 6) > 0){ j = j - 6; } } if (joueur == 0){ j = 6 - j; } if( (Mat[joueur][j] < 4) && (Mat[joueur][j] > 1) ){ While(10); while(bWhile("pourquoiçafaitça?(CapturePoints)", (j < 6) && (j >= 0)) ){ if((Mat[joueur][j] < 4) && (Mat[joueur][j] > 1)) { totalpris = totalpris + Mat[joueur][j]; Mat[joueur][j] = 0; } if(joueur == 0){ j++; } if(joueur == 1){ j--; } } } return totalpris; } int deplacement_gauche (int Mat[N][M], int j, int joueur, int nb){ //Déplacement vers la gauche ou de 5 à 0 while((nb > 0) && (j >= 0)){ //Ajoute 1 aux valeurs de la Matrice tant que le nombre de billes n'est pas 0 j--; if (j >= 0){ Mat[joueur][j]++; nb--; } } if(nb > 0){ //Lorsqu'on dépasse les limites de la matrice et qu'ils restent des billes à déposer joueur++; deplacement_droite(Mat, j, joueur, nb); } return joueur; } int deplacement_droite (int Mat[N][M], int j, int joueur, int nb){ //Déplacement vers la droite ou de 0 à 5 while((nb > 0) && (j < M)){ //Ajoute 1 aux valeurs de la Matrice tant que le nombre de billes n'est pas 0 j++; if (j < 6){ Mat[joueur][j]++; nb--; } } if(nb > 0){ //Lorsqu'on dépasse les limites de la matrice et qu'ils restent des billes à déposer joueur--; deplacement_gauche(Mat, j, joueur, nb); } return joueur; } /**\brief Gère les déplacements à gauche et à droite de l'Awélé*/ int deplacement(int Mat[N][M], int j, int joueur, int nb){ //Une fonction pour deux déplacements; if(joueur == 0){ joueur = deplacement_gauche(Mat, j, joueur, nb); } else if(joueur == 1){ joueur = deplacement_droite(Mat, j, joueur, nb); } else { printf("\nErreur dans la numérotation des joueurs\n"); } return joueur; } /**\brief Un tour se déroule et on prend des points*/ int JouerTourCapture(int Mat[N][M], int j, int joueur, int nb, int total, char typeJ, int fin){ //joueur joue son tour ; rend le total de point gagnés int nvJoueur; j--; nb = Mat[joueur][j]; j = Case_Vide(Mat, joueur, j, nb, typeJ); nb = Mat[joueur][j]; Mat[joueur][j] = 0; nvJoueur = deplacement(Mat, j, joueur, nb); printf("Joueur = %i\n", nvJoueur); if (nvJoueur != joueur){ total = total + CapturePoints(Mat, nvJoueur, (j + nb), nb); } j++; return total; } /**\brief Un tour se déroule mais on ne prend pas les points*/ void JouerTour(int Mat[N][M], int j, int joueur, int nb, char typeJ, int fin){ //joueur joue son tour; int nvJoueur; j--; nb = j--; nb = Mat[joueur][j]; j = Case_Vide(Mat, joueur, j, nb, typeJ); nb = Mat[joueur][j]; Mat[joueur][j] = 0; nvJoueur = deplacement(Mat, j, joueur, nb); j++; } /**\brief On arrête le jeu lorsqu'on a certaines valeurs*/ int ArretJeu(int j1, int j2, char c, int fin, int arret){ if((j1 == 0) || (j2 == 0)){ while ((c != 'y') && (c != 'n')){ printf("Voulez-vous arrêter le jeu ? (y or n)\n"); scanf("%*c%c", &c); if(c == 'y'){ j1 = fin; j2 = fin; } else if(c == 'n') { j1 = 0; j2 = 0; } else { printf("Erreur caractère\n"); } } } if ((j1 == fin) || (j2 == fin)){ arret = 1; } else { arret = 0; } return arret; } void TestA2() { int Mat[N][M]; int fin = -1; char c, typeJ; int j1, j2, totalj1, totalj2, nb, arret; totalj1 = 0; totalj2 = 0; j1 = 1; j2 = 1; init_Mat(Mat); //Initialisation OBLIGATOIRE ! AfficherMat(Mat); typeJ = 'J'; do{ printf("\n'Testeur 1' as J1\n"); j1 = Choix_case(Mat, typeJ, 0); if((j1 != 0) && (j1 != -1)){ JouerTour(Mat, j1, 0, nb, typeJ, fin); } else if(j1 == -1) { j1 = fin; } AfficherMat(Mat); printf("\n'Testeur 2' as J2\n"); j2 = Choix_case(Mat, typeJ, 1); if((j2 != 0) && (j2 != -1)){ JouerTour(Mat, j2, 1, nb, typeJ, fin); } else if(j2 == -1) { j2 = fin; } AfficherMat(Mat); arret = ArretJeu(j1, j2, c, fin, arret); }while(arret != 1); } void TestOrdi(){// Choix_case a un problème alors trouve-le ! int Mat[N][M]; int fin = -1; int compt; char c, typeJ; int j1, j2, totalj1, totalj2, nb, arret; totalj1 = 0; totalj2 = 0; j1 = 1; j2 = 1; typeJ = 'O'; init_Mat(Mat); //Initialisation OBLIGATOIRE ! AfficherMat(Mat); do{ printf("\nTour 'OrdiTest1' as J1 :\n"); j1 = Choix_case(Mat, typeJ, 0); if((j1 != 0) && (j1 != -1)){ JouerTour(Mat, j1, 0, nb, typeJ, fin); } else if(j1 == -1) { j1 = fin; } AfficherMat(Mat); printf("\nTour 'OrdiTest2' as J2 :\n"); j2 = Choix_case(Mat, typeJ, 1); if((j2 != 0) && (j2 != -1)){ JouerTour(Mat, j2, 1, nb, typeJ, fin); } else if(j2 == -1) { j2 = fin; } AfficherMat(Mat); compt++; }while(compt < 1); printf("\nFait\n"); } /**\brief Test sur le type associé à un joueur (Ordi ou Joueur réel)*/ void TestErrTJoueur() { int Mat[N][M]; int fin = -1; char c, typeJ; int j1, j2, totalj1, totalj2, nb, arret; totalj1 = 0; totalj2 = 0; j1 = 1; j2 = 1; init_Mat(Mat); //Initialisation OBLIGATOIRE ! AfficherMat(Mat); printf("Test : Entrez un type de joueur erronné ('A','B', ...)\n"); scanf("%*c%c", &typeJ); do{ printf("\n'Testeur' as J1\n"); j1 = Choix_case(Mat, typeJ, 0); if((j1 != 0) && (j1 != -1)){ JouerTour(Mat, j1, 0, nb, typeJ, fin); } else if(j1 == -1) { j1 = fin; } AfficherMat(Mat); arret = ArretJeu(j1, j2, c, fin, arret); }while(arret != 1); } /**\brief Test sur le chiffre/nombre associé à un joueur*/ void TestErrNumJoueur() { int Mat[N][M]; int fin = -1; int joueur; char c; int j1, j2, totalj1, totalj2, nb, arret; int typeJ = 'J'; totalj1 = 0; totalj2 = 0; j1 = 1; j2 = 1; init_Mat(Mat); //Initialisation OBLIGATOIRE ! AfficherMat(Mat); printf("Test : Entrez un numéro de joueur erronné (entier > 1 ou < 0 de préférence...)\n"); scanf("%i", &joueur); do{ printf("\n'Testeur' as J1\n"); if((joueur != 0) || (joueur != 1)){ j1 = fin; j2 = fin; printf("\nTest effectué : ERREUR sur 'joueur'\n"); } else { j1 = Choix_case(Mat, typeJ, 0); if((j1 != 0) && (j1 != -1)){ JouerTour(Mat, j1, 0, nb, typeJ, fin); } else if(j1 == -1) { j1 = fin; } AfficherMat(Mat); printf("\nTest effectué : Pas d'ERREUR sur 'joueur'\n"); } arret = ArretJeu(j1, j2, c, fin, arret); }while(arret != 1); } /**\brief Test d'ajout des points gagnés*/ void TestCapture(){ int Mat[N][M]; int fin = -1; char c, typeJ; int j1, j2, totalj1, totalj2, nb, arret; totalj1 = 0; totalj2 = 0; j1 = 1; j2 = 1; init_Mat(Mat); //Initialisation OBLIGATOIRE ! AfficherMat(Mat); typeJ = 'J'; do{ printf("\n'Testeur 1' as J1\n"); j1 = Choix_case(Mat, typeJ, 0); if((j1 != 0) && (j1 != -1)){ totalj1 = JouerTourCapture(Mat, j1, 0, nb, totalj1, typeJ, fin); } else if(j1 == -1) { j1 = fin; } AfficherMat(Mat); printf("\n'Testeur 2' as J2\n"); j2 = Choix_case(Mat, typeJ, 1); if((j2 != 0) && (j2 != -1)){ totalj2 = JouerTourCapture(Mat, j2, 1, nb, totalj2, typeJ, fin); } else if(j2 == -1) { j2 = fin; } AfficherMat(Mat); arret = ArretJeu(j1, j2, c, fin, arret); }while(arret != 1); } /**\brief Gestion de tout les tests : Jeu à 2, en Solo, ajout des points, Erreurs sur le joueur... Utilisable par mot de passe mais il est facile à trouver*/ int Test(int comptest){ int arret, choix; int chance = 5; char passe[1+20] = "Courgette"; char essai[20]; if(comptest < 1){ printf("\nBesoin d'un mot de passe pour les tests :\n"); do{ printf("Essai %i\n", (6-chance)); scanf("%s", essai); if(strcmp(essai, passe)!=0){ chance--; printf("\nRaté ! Encore %i essai(s) !\n", chance); } }while((strcmp(essai, passe)!=0) && (chance > 0)); if(chance == 0){ printf("\nDésolé, plus d'essais possibles, à plus !\nP.S. : Cherchez dans vos Highscores !\n"); comptest = 1; return comptest; } else do{ printf("\nQuel test ?\n"); printf(" 1 - Test A 2\n"); printf(" 2 - Ordi\n"); printf(" 3 - Capture Points\n"); printf(" 4 - Erreur type joueur\n"); printf(" 5 - Erreur numérotation\n"); printf(" 6 - Arrêter\n"); printf("Votre choix : "); scanf("%i", &choix); switch(choix){ case 1: TestA2(); break; case 2: TestOrdi(); break; case 3: TestCapture(); break; case 4: TestErrTJoueur(); break; case 5: TestErrNumJoueur(); break; case 6: arret = -1; break; default: printf("Erreur, le choix ne peut être compris qu'entre 1 et 6, merci !"); //On prévoit pour choix < 1 et choix > 6 } }while( arret != -1 ); } else { printf("\nInutilisable pour l'instant\n"); } } /**\brief Jeu contre l'Ordinateur*/ void Partie_Solo(){ int Mat[N][M]; int fin = -1; int joue; char c, typeJ; int j1, j2, totalj1, totalj2, nb, arret; totalj1 = 0; totalj2 = 0; j1 = 1; j2 = 1; init_Mat(Mat); //Initialisation OBLIGATOIRE ! AfficherMat(Mat); printf("Voulez-vous jouer en '1'er ou en '2'éme ?\n"); scanf("%i", &joue); while((joue <= 0) || (joue > 2)){ //On prévoit l'erreur sur la saisie de l'entier printf("Entrez juste 1 ou 2...\n"); scanf("%i", &joue); } if(joue == 2){ printf("\nJ1 = Ordi ; J2 = Joueur\n"); } else { printf("\nJ1 = Joueur ; J2 = Ordi\n"); } //On précise qui joue à quelle place do{ //Boucle qui fonctionne tant qu'il n'y a pas d'erreur et qu'aucun des joueurs n'a atteint au moins 24 points if(joue == 1){ //On précise que le joueur joue en 1er ou en 2éme printf("\nTour 'Joueur' as J1 :\n"); typeJ = 'J'; //A préciser pour la sélection de la case. j1 = Choix_case(Mat, typeJ, 0); if((j1 != 0) && (j1 != -1)){ JouerTour(Mat, j1, 0, nb, typeJ, fin); } else if(j1 == -1) { j1 = fin; } AfficherMat(Mat); //Pour garder un oeil sur le jeu... printf("\nTour 'Ordinateur' as J2 :\n"); typeJ = 'O'; j2 = Choix_case(Mat, typeJ, 1); if((j1 != -1) && (j1 != 0)){ JouerTour(Mat, j2, 1, nb, typeJ, fin); } else if(j1 == -1) { j2 = fin; } else if(j1 == 0){ j2 = 0; } AfficherMat(Mat); arret = ArretJeu(j1, j2, c, fin, arret); } else if(joue == 2){ printf("\nTour 'Ordinateur' as J1 :\n"); typeJ = 'O'; j1 = Choix_case(Mat, typeJ, 0); if(j2 != 0){ //Passe si l'ordinateur n'a pas rencontré d'erreur ou si le joueur réel souhaite continuer JouerTour(Mat, j1, 0, nb, typeJ, fin); } else if (j2 == 0) { //Prend en compte la volonté d'arrêter du joueur j1 = 0; } AfficherMat(Mat); printf("\nTour 'Joueur' as J2 :\n"); typeJ = 'J'; j2 = Choix_case(Mat, typeJ, 1); if((j2 != 0) && (j2 != -1)){ JouerTour(Mat, j2, 1, nb, typeJ, fin); } else if(j2 == -1) { j2 = fin; } AfficherMat(Mat); arret = ArretJeu(j1, j2, c, fin, arret); } if(joue == 1){ printf("Total Joueur : %i\nTotal Ordi : %i\n", totalj1, totalj2); } else { printf("Total Joueur : %i\nTotal Ordi : %i\n", totalj2, totalj1); } }while( arret != 1 ); } /**\brief Jeu entre 2 joueurs*/ void Partie_A2(){ int Mat[N][M]; int fin = -1; char c; char typeJ = 'J'; int j1, j2, totalj1, totalj2, nb, arret; totalj1 = 0; totalj2 = 0; j1 = 1; j2 = 1; typeJ = 'J'; init_Mat(Mat); //Initialisation OBLIGATOIRE ! AfficherMat(Mat); while( arret != 1 ){ printf("\n'Joueur 1' as J1\n"); j1 = Choix_case(Mat, typeJ, 0); if((j1 != 0) && (j1 != -1)){ totalj1 = JouerTourCapture(Mat, j1, 0, nb, totalj1, typeJ, fin); } else if(j1 == -1) { j1 = fin; } AfficherMat(Mat); printf("total point J1 : %i\n", totalj1); printf("\n'Joueur 2' as J2\n"); j2 = Choix_case(Mat, typeJ, 1); if((j2 != 0) && (j2 != -1)){ totalj2 = JouerTourCapture(Mat, j2, 1, nb, totalj2, typeJ, fin); } else if(j2 == -1) { j2 = fin; } AfficherMat(Mat); printf("total point J2 : %i\n", totalj2); if((totalj1 < 24) && (totalj2 < 24)){ arret = ArretJeu(j1, j2, c, fin, arret); } else if((totalj1 > 24) || (totalj2 > 24)){ arret = 1; } else if((totalj1 == 24) && (totalj2 == 24)){ printf("Match nul\n"); arret = 1; } } printf("\nTotal J1 : %i\nTotal J2 : %i\n", totalj1, totalj2); } /**\brief Affichage des meilleurs scores*/ int Highscores(FILE * fic, int compt){ //Affichage du contenu d'un fichier 'Highscores' int rang, score, n; char c; if(compt < 1){ //On ne souhaite pas l'afficher deux fois d'affilé... printf("\nMeilleurs scores : \n"); While(13); while(bWhile("pourquoiçafaitça?",!feof(fic))){//On affiche toutes les infos du fichier fscanf(fic,"%i %i %c",&rang,&score,&c); n++; if(n <= rang){ //On s'assure que l'on n'affiche pas un doublon printf("Rang : %i - %c Score : %i\n", rang, c, score); } } printf("Fin\n"); compt = 1; return compt; //On précise qu'il a été utilisé } else { printf("\nDéjà utilisé précédemment\n"); } } /**\brief 'Menu' de sélection des modes de jeux et des autres fonctions*/ int main2(){ int choix; int compt = 0; int comptest = 0; FILE * fic; fic = fopen("highscoresA.txt","r"); if(fic == NULL){ //On initialise un fichier Highscores pour les tests fic = fopen("highscoresA.txt","w"); fprintf(fic,"1 24 C\n"); fprintf(fic,"2 24 O\n"); fprintf(fic,"3 24 U\n"); fprintf(fic,"4 24 R\n"); fprintf(fic,"5 24 G\n"); fprintf(fic,"6 24 E\n"); fprintf(fic,"7 24 T\n"); fprintf(fic,"8 24 T\n"); fprintf(fic,"9 24 E\n"); } fclose(fic); do { //Menu de Sélection fic = fopen("highscoresA.txt","r"); printf("\n Bienvenue,\n\nComment voulez jouer à l'Awélé ?\n"); printf(" 1 - Contre l'ordi\n"); printf(" 2 - A deux\n"); printf(" 3 - Afficher highscores\n"); printf(" 4 - Test\n"); printf(" 5 - Quitter le jeu\n"); printf("Votre choix : "); scanf("%i", &choix); switch(choix){ case 1: Partie_Solo(); break; case 2: Partie_A2(); break; case 3: compt = Highscores(fic, compt); break; case 4: comptest = Test(comptest); break; case 5: break; default: printf("Erreur, le choix ne peut être compris qu'entre 1 et 5, merci !"); //On prévoit pour choix < 1 et choix > 5 } if((choix != 3) && (compt > 0) && (choix != 5)){//Car l'afficher une fois suffit pour l'instant compt = 0; printf("\nFonction Highscore réutilisable\n"); } if((choix != 4) && (comptest > 0) && (choix != 5)){//Car l'afficher une fois suffit pour l'instant comptest = 0; printf("\nFonction Test réutilisable\n"); } fclose(fic); //Permet de relire le fichier à partir du début de ce dernier } while(choix!=5); printf("\nA plus !\n"); //Fin return EXIT_SUCCESS; } /**\brief Celle-là j'ai pas compris...*/ void ModuleAmorceR(){ //amorce tous les modules (code à exécuter une fois pour toutes AVANT d'utiliser un quelconque module depuis le main) OutilAMORCER();//NE PAS DECLASSER:doit toujours être appelé en premier //amorcer TOUS les modules autres que Outil mentionnés dans les include de main.c //TasAMORCER(); }//ModuleAmorceR /**\brief Fonction principale appelant les autres*/ int main (int argc, const char * argv[]) { Appel0("");//NE PAS TOUCHER; ce code doit toujours être placé au début du main ModuleAmorceR();//NE PAS TOUCHER; ce code doit toujours suivre immédiatement Appel0("") te("dtxsxsd",54); main2(); Appel1("");//NE PAS TOUCHER; ce code doit toujours être placé à la fin du main, juste avant le return() return 0; } <file_sep>/makefile projet : projet.o Outil.c gcc projet.o Outil.c -o projet -lm Outil.o : Outil.c gcc -c Outil.c projet.o : projet.c Outil.h gcc -c projet.c Outil.h
7988db0d9a377c535478ae5cad7d085dbe4df57b
[ "C", "Makefile" ]
2
C
cjolliet/Projet-Awele
5453089ed6fb113d9fb2426a7e9e84c7ffdb4ab2
4611fb3072aed2e94edd6b757a42f2fb2a087624
refs/heads/master
<repo_name>kraizybone/react-start<file_sep>/src/App.js import React from 'react'; import ReduxToastr from 'react-redux-toastr'; import LoadingBar from 'react-redux-loading-bar'; const App = ({children}) => { return ( <div className="page"> <LoadingBar /> <ReduxToastr timeOut={5000} /> {children} </div> ) }; export default App; <file_sep>/src/constants/FormConstants.js export const CLASS_HAS_ERROR = 'has-error'; <file_sep>/src/utils/PrefetchContainer.js export default (connectedComponent, loadActionWrapper) => { return class PrefetchContainer extends connectedComponent { componentDidMount() { super.componentDidMount(); this.store.dispatch(loadActionWrapper(this.props, this.state)); } componentWillReceiveProps(nextProps) { super.componentWillReceiveProps(nextProps); if (this.props === nextProps) { this.store.dispatch(loadActionWrapper(this.props, this.state)); } } }; }; <file_sep>/src/reducers/AppReducers.js import {combineReducers} from 'redux'; import {reducer as formReducer} from 'redux-form'; import {routerReducer} from 'react-router-redux'; import {loadingBarReducer} from 'react-redux-loading-bar'; import {reducer as toastrReducer} from 'react-redux-toastr'; import securityReducer from '../reducers/SecurityReducer'; /** * Combines reducers for using in app */ export default combineReducers({ routing: routerReducer, form: formReducer, loadingBar: loadingBarReducer, toastr: toastrReducer, security: securityReducer }); <file_sep>/src/components/dashboard/Dashboard.js import React from 'react'; import {toastr} from 'react-redux-toastr'; import {log} from '../../utils/Utils'; /** * Dashboard component */ const Dashboard = () => { const showMessage = () => { log('Toastr message'); toastr.success('success', 'message'); toastr.warning('warning', 'message'); toastr.info('warning', 'message'); toastr.error('error', 'message'); }; return ( <div> <button type="button" onClick={showMessage}>Show</button> This is dashboard </div> ); }; export default Dashboard; <file_sep>/src/components/login/Login.js import React from 'react'; import {connect} from 'react-redux'; import ReduxLoginForm from './LoginForm'; import {login} from '../../actions/LoginAction'; const Login = ({handleSubmit}) => ( <ReduxLoginForm onSubmit={handleSubmit} /> ); const mapDispatchToProps = (dispatch) => { return { handleSubmit: () => dispatch(login()) }; }; export default connect(null, mapDispatchToProps)(Login); <file_sep>/src/constants/AuthConstants.js export const ROLES = { MVS_ADMINISTRATIVNY_PRACOVNIK: 'MVS_ADMINISTRATIVNY_PRACOVNIK' }; export const RIGHTS = { MVS_FILE_SELECT_DEPARTMENT: 'MVS_FILE_SELECT_DEPARTMENT', MVS_FILE_SELECT_INVESTIGATOR: 'MVS_FILE_SELECT_INVESTIGATOR', MVS_FILE_SELECT_DIVISION: 'MVS_FILE_SELECT_DIVISION', MVS_FILE_REPORTER_ADD: 'MVS_FILE_REPORTER_ADD', MVS_ADMIN_USERS: 'MVS_ADMIN_USERS', MVS_ADMIN_USERS_EDIT: 'MVS_ADMIN_USERS_EDIT' }; <file_sep>/src/actions/LoginAction.js // import {log, api} from '../utils/Utils'; import {log} from '../utils/Utils'; // import {Base64} from 'js-base64'; // import {push} from 'react-router-redux'; import {LOGIN} from '../constants/RoutesConstants'; export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; export const LOGIN_ERROR = 'LOGIN_ERROR'; export const LOGOUT = 'LOGOUT'; export const loginRequest = (auth) => { return { type: LOGIN_SUCCESS, payload: { auth } }; }; export const logoutRequest = () => { return { type: LOGOUT }; }; export const loginError = (message) => { return { type: LOGIN_ERROR, payload: { message } }; }; export const login = () => (dispatch, getState) => { log('LOGIN'); // const values = getState().form.formLogin.values; // const options = { // data: JSON.stringify({ // username: values.username, // password: <PASSWORD>(values.password) // }) // }; // let p = new Promise((resolve, reject) => { // log('Action LoginAction/login'); // api(dispatch, getState, ENDPOINTS.AUTH, METHOD.POST, options).then((res) => { // if (res && res.ok) { // dispatch(loginRequest(res.body)); // resolve(); // } else { // // TODO: Treba aj msg wrong username or password? // dispatch(loginError('Error')); // } // }); // }); // return p; }; export const logout = () => (dispatch, getState) => { // if (getState() && getState().security && getState().security.auth.authToken) { // log('LOGOUT'); // let p = new Promise((resolve, reject) => { // log('Action LoginAction/logout'); // api(dispatch, getState, ENDPOINTS.AUTH_LOGOUT, METHOD.POST).then((res) => { // if (res && res.ok) { // dispatch(logoutRequest()); // dispatch(push('/login')); // resolve(); // } // }); // }); // return p; // }; }; export const checkAuth = (store) => (nextState, replace) => { if (store.getState().security && store.getState().security.auth.authToken) { return true; } else { replace(LOGIN); return false; } };<file_sep>/src/constants/ApiRoutesConstants.js export const API_URL = process.env.APP_CONFIG.BE_API_URL; export const ENDPOINTS = {}; <file_sep>/src/utils/Utils.js import request from 'superagent'; import {toastr} from 'react-redux-toastr'; import { showLoading, hideLoading } from 'react-redux-loading-bar'; import { METHOD, HEADER } from '../constants/HttpConstants'; /** * Custom log function. * Works only if APP_DEBUG config parameter is set to true * Otherwise log messages are ommitted * * @param message * @param optionalParams */ export const log = (message, ...optionalParams) => { if (process.env.NODE_ENV === "development") { console.log(message, ...optionalParams); } }; /** * Custom replace function. * * @param message * @param optionalParams */ export const warn = (message, ...optionalParams) => { if (process.env.NODE_ENV === "development") { console.warn(message, ...optionalParams); } }; /** * Makes an REST api call to defined action using defined method (GET, POST, ...) * with defined options (data, headers, queryParams) * * During loading a application wide loader is dispatched. * * @param dispatch - for Loading call * @param route - string for a define endpoint * @param method - string defining HTTP method, see /src/javascript/constants/apiRoutes * @param options - json object defining "data" for POST, PUT, PATCH, DELETE methods, "headers" and, "queryParams" * @returns {Promise.<T>} */ export const api = (dispatch, getState, route, method, options = {}, showToastr = true) => { let data = options.data || {}; let headers; if (getState() && getState().security && getState().security.auth.authToken) { headers = Object.assign({}, options.headers || {}, {[HEADER.AUTH_TOKEN]: getState().security.auth.authToken}); } else { headers = options.headers || {}; } const url = route; dispatch(showLoading()); log('Calling api call: ', url); const noRequestBody = [METHOD.HEAD, METHOD.GET].includes(method); return request[method.toLowerCase()](url) .set('Content-Type', 'application/json') .set('Authorization', 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=') .set(headers) .send(noRequestBody ? undefined : data) .then((res) => { if (!res.ok) { warn('Status not OK: ', res.status); if (showToastr === true) { toastr.error('Error title', 'Error message'); } } dispatch(hideLoading()); return res; }) .catch((err) => { warn('Request failed: ', err); if (showToastr === true) { toastr.error('Error title', 'Error message'); } dispatch(hideLoading()); }); }; /** * Get local field name * @param {String} name * @param {String} component * @return {String} */ // export const getLocalFieldName = (name, component = 'main') => { // if (typeof strings[component] !== 'undefined' && typeof strings[component][name] !== 'undefined') { // return strings[component][name]; // } // return name; // }; /** * Validate against rules * @param {Array} rules * @return {Object} */ export const validateRules = (rules = []) => (values) => { const errors = {}; if (rules.length > 0) { rules.forEach((rule) => { let field = rule.name; if (rule.required === true) { if (!values[field]) { // errors[field] = getLocalFieldName(field) + ' ' + strings.main.isRequired; errors[field] = field + ' is required!'; } } }); } return errors; }; <file_sep>/src/components/common/Main.js import React from 'react'; import {connect} from 'react-redux'; /** * * @param security * @param children * Main content */ const Main = ({security, children}) => { return ( <div id="mainContent"> <div className="main"> {children || 'Nothing'} </div> </div> ); }; const mapStateToProps = (state) => { return { security: state.security }; }; export default connect(mapStateToProps, null)(Main); <file_sep>/src/constants/HttpConstants.js export const STATUS = { CODE_OK: 200, CODE_555: 555, CODE_500: 500, CODE_403: 403 }; export const HEADER = { AUTH_TOKEN: 'X-Auth-Token' }; export const METHOD = { HEAD: 'HEAD', GET: 'GET', POST: 'POST', DELETE: 'DEL', PUT: 'PUT', PATCH: 'PATCH' }; <file_sep>/src/routes.js import React from 'react'; import {Route, IndexRoute} from 'react-router'; import App from './App'; import Main from './components/common/Main'; import Dashboard from './components/dashboard/Dashboard'; import Login from './components/login/Login'; import NotFound from './components/NotFound'; import {LOGIN} from './constants/RoutesConstants'; import {checkAuth} from './actions/LoginAction'; const routes = (store) => ( <Route path="/" component={App}> <Route path={LOGIN} component={Login} /> <Route component={Main} onEnter={checkAuth(store)}> <IndexRoute component={Dashboard} /> <Route path="*" component={NotFound} /> </Route> </Route> ); export default routes;
c64a875d117b5ae759380731d31e37761e32e5f7
[ "JavaScript" ]
13
JavaScript
kraizybone/react-start
c516dbe189d1838d1e6a67b9c7a8470299e53e99
839822d2297dafc9a69f095bc166f208a67b198e
refs/heads/master
<repo_name>ContagionNZ/Angular_Learning<file_sep>/src/app/header/recipe/recipe-list/recipe-list.component.ts import { Component, OnInit, EventEmitter, Output } from '@angular/core'; import { Recipe } from '../recipe.model'; import { TestBed } from '@angular/core/testing'; @Component({ selector: 'app-recipe-list', templateUrl: './recipe-list.component.html', styleUrls: ['./recipe-list.component.css'] }) export class RecipeListComponent implements OnInit { @Output() recipeWasSelceted = new EventEmitter<Recipe>(); recipes: Recipe[] = [ new Recipe('Test', 'This is a Test', 'https://cdn4.iconfinder.com/data/icons/hotel-3-6/48/132-512.png') ]; constructor() { } ngOnInit() { } onRecipeSelected(recipe: Recipe) { this.recipeWasSelceted.emit(recipe); } }
53ee5890614b6d823d42d23549dc3fc925804b45
[ "TypeScript" ]
1
TypeScript
ContagionNZ/Angular_Learning
d687cfb9d03bb625b3037d570c8732824c66ff63
981d5b86b7230320bd5aa6417a331ae62724c1ca
refs/heads/master
<file_sep># API desafio uno Nivel 3 Este proyecto expone un API REST que invoca al servicio GDD y entrega la respuesta en formato JSON con las fechas recibidas y las fechas faltantes. # Detalle de los sistemas Swagger Codegen 2.3.1 (OpenApi 2.0) Java 8 Spring-Boot 1.5.9.RELEASE Maven 3 # Compilar y ejecutar el proyecto Para compilar el proyecto se requiere Java y Maven instalado. Ingresar al directorio *ApiPeriodosF* ejecutar el siguiente comando *maven* ```bash mvn package ``` Luego de compilar el proyecto ingresar al directorio *target* ejecutar el siguiente comando *java* ```bash java -jar .\api-periodos-1.0.0.jar ``` *Nota*: Debe estar disponible el puerto *8084* en el PC donde se ejecute esta API. Adiconalemente debe estar disponible la API GDD bajo el puerto *8080*. # Visualizar Documentación y consumir la API La documentación swagger del API (una vez que se levanta el API) queda disponible en http://1172.16.58.3:8084/periodos/swagger-ui.html#/ Para consumir el servicio se debe invocar la siguiente URL ```bash curl -X GET --header 'Accept: application/json' 'http://127.0.0.1:8084/periodos/api' ``` <file_sep>package com.previred.periodos.metodos; public class Metodos { } <file_sep>package com.previred.periodos.ws; import com.previred.periodos.swagger.codegen.model.Periodo; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class PeriodosService { private static final Logger log = LoggerFactory.getLogger(PeriodosService.class); public Periodo getPeriodosFaltantes() { RestTemplate restTemplate = new RestTemplate(); Periodo periodos = restTemplate.getForObject( "http://127.0.0.1:8080/periodos/api", Periodo.class); LocalDate fechaCreacion = periodos.getFechaCreacion(); LocalDate fechaFin = periodos.getFechaFin(); Set<LocalDate> fechasFaltantes = new HashSet(); for (LocalDate d = fechaCreacion; !d.isAfter(fechaFin); d = d.plusMonths(1)) { if (!periodos.getFechas().contains(d)) { fechasFaltantes.add(d); } } periodos.setFechasFaltantes(fechasFaltantes.stream() .sorted() .collect(Collectors.toList())); return periodos; } }
91396d23a131b40502c7aac29ce250d38e3c9120
[ "Markdown", "Java" ]
3
Markdown
oronozp/Desafio_Uno
4e4ba32f68e37db059f8ac3cc54c45a0104f61bb
e73b89d98701e84ba272a06002353a40abcf1af8
refs/heads/master
<file_sep># server_cinq Back-end server that provide a list of people. ## Tutorial Firstly, You'll need install [NodeJS](https://nodejs.org/en/) and [NPM](https://www.npmjs.com/). After that, clone this repo in your worskpace. With your project already cloned, enter in the folder cd ../server_cinq Now, you need to install every NPM dependency with the command below npm install With every dependency installed, we'll start up the server npm start Done! To get a list of people, go to your prefered browser and access the follow URL: [http:\\localhost:3000/rest/people](http:\\localhost:3000/rest/people) Be Happy. =D<file_sep>var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); router.get('/rest/people', function(req, res, next) { var name = ["Adam", "Abe", "Maria", "Rose", "Mario", "Luigi"]; var surname = ["Lincoln", "Franklin", "Jackson", "Miyazaki", "M'bebe"]; var finalList = []; for(i=0; i<10; i++) { var randomName = Math.floor((Math.random() * name.length) + 1); var randomSurname = Math.floor((Math.random() * surname.length) + 1); var json = {"id" : i, "name" : name[randomName] + " " + surname[randomSurname], "disclosableInfo" : "bla bla bla"}; finalList.push(json); } res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.send(finalList); }); module.exports = router;
65d74ea99cd1c53391600654660cb0b8a95f0f0f
[ "Markdown", "JavaScript" ]
2
Markdown
lazaropj/server_cinq
4082032ef539b9fa2d33ca1932e847c91b89dcd6
f708554b228024aabd43e65d9b8615fc34491acd
refs/heads/main
<repo_name>Reactist215/react-express-invoice-webapplication<file_sep>/src/store/action_types/index.js export { default as alertConstants } from './alert_action_types' export { default as userConstants } from './user_action_types'<file_sep>/src/store/reducers/alert.reducer.js import { alertConstants } from '../action_types' const initialState = { message: '', type: '' } export default function (state = initialState, action) { switch (action.type) { case alertConstants.SUCCESS: console.log(action) return { message: action.message, type: 'SUCCESS' }; case alertConstants.ERROR: console.log(action) return { message: action.message, type: 'ERROR' }; case alertConstants.CLEAR: console.log(action) return initialState; default: return state; } }<file_sep>/src/store/reducers/user.reducer.js import { userConstants } from '../action_types' const initialState = { loading: false, data: null } export default function (state = initialState, action) { switch (action.type) { case userConstants.LOGIN_REQUEST: return { ...state, loading: true }; case userConstants.LOGIN_SUCCESS: return { ...state, loading: false, data: action.user }; case userConstants.LOGIN_FAILURE: return { ...state, ...initialState }; case userConstants.LOGOUT: return { ...state, ...initialState }; case userConstants.SET_USER_DATA: return { ...state, loading: false, data: action.user }; default: return state; } }<file_sep>/src/initialpage/loginpage.jsx /** * Signin Firebase */ import React, { useState, useCallback } from 'react'; import { Helmet } from "react-helmet"; import { shallowEqual, useSelector, useDispatch } from 'react-redux' import { FacebookLoginButton, GoogleLoginButton, MicrosoftLoginButton, TwitterLoginButton } from "react-social-login-buttons"; import { Applogo } from '../Entryfile/imagepath.jsx' import { userActions } from '../store/actions' const Loginpage = () => { const dispatch = useDispatch() // component states const [submitted, setSubmitted] = useState(false) const [state, setState] = useState({ email: '', password: '' }) const { email, password } = state; // form handlers const loginclick = useCallback( () => { // this.props.history.push("/maroon/app/main/dashboard") setSubmitted(true); if (email && password) { dispatch(userActions.login(email, password)); } }, [email, password], ) const handleChange = useCallback( (e) => { const { name, value } = e.target setState(prevState => ({ ...prevState, [name]: value })) }, [], ) // render return ( <div className="main-wrapper"> <Helmet> <title>Login - HRMS Admin Template</title> <meta name="description" content="Login page" /> </Helmet> <div className="account-content"> {/* <a href="/purple/applyjob/joblist" className="btn btn-primary apply-btn">Apply Job</a> */} <div className="container"> {/* Account Logo */} <div className="account-logo"> <a href="/purple/app/main/dashboard"><img src={Applogo} alt="Dreamguy's Technologies" /></a> </div> {/* /Account Logo */} <div className="account-box"> <div className="account-wrapper"> <h3 className="account-title">Login</h3> <p className="account-subtitle">Access to our dashboard</p> {/* Account Form */} <form onSubmit={(e) => e.preventDefault()}> <div className="form-group"> <label>Email Address</label> <input onChange={handleChange} className="form-control" type="text" name="email" /> {submitted && !email && <div className="text-danger">Email is required</div> } </div> <div className="form-group"> <div className="row"> <div className="col"> <label>Password</label> </div> <div className="col-auto"> <a className="text-muted" href="/purple/forgotpassword"> Forgot password? </a> </div> </div> <input onChange={handleChange} className="form-control" type="password" name="password" /> {submitted && !password && <div className="text-danger">Password is required</div> } </div> <div className="form-group text-center"> <a className="btn btn-primary account-btn" onClick={loginclick}> Login</a> <div className="row social-button-wrapper"> <div className="col-lg-6 col-md-12 col-sm-12"> <GoogleLoginButton onClick={() => { alert("Google") }}> <span>Google</span> </GoogleLoginButton> </div> <div className="col-lg-6 col-md-12 col-sm-12"> <TwitterLoginButton onClick={() => alert("Twitter")}> <span>Twitter</span> </TwitterLoginButton> </div> <div className="col-lg-6 col-md-12 col-sm-12"> <MicrosoftLoginButton onClick={() => alert("Microsoft")}> <span>Microsoft</span> </MicrosoftLoginButton> </div> <div className="col-lg-6 col-md-12 col-sm-12"> <FacebookLoginButton onClick={() => alert("Facebook")}> <span>Facebook</span> </FacebookLoginButton> </div> </div> </div> <div className="account-footer"> <p>Don't have an account yet? <a href="/purple/register">Register</a></p> </div> </form> {/* /Account Form */} </div> </div> </div> </div> </div> ); } export default Loginpage; <file_sep>/src/store/actions/user.actions.js import { userConstants } from '../action_types'; import { alertActions } from '../actions'; import { userService } from '../../services'; export default { login, logout, initializeUserData, getAll, }; function login(email, password) { return dispatch => { dispatch(request({ email })); userService.login(email, password) .then( user => { dispatch(success(user)); }, error => { dispatch(success({ email: 'test', role: 'test' })); // dispatch(failure(error)); dispatch(alertActions.error(error)); } ); }; function request(user) { return { type: userConstants.LOGIN_REQUEST, user } } function success(user) { return { type: userConstants.LOGIN_SUCCESS, user } } function failure(error) { return { type: userConstants.LOGIN_FAILURE, error } } } function logout() { userService.logout(); return { type: userConstants.LOGOUT }; } function initializeUserData() { return dispatch => { const token = userService.getToken() userService.getUserDataFromToken(token) .then( user => { dispatch(success(user)); }, error => { dispatch(success({ email: 'test', role: 'test' })); // dispatch(failure(null)); dispatch(alertActions.error(error)); } ); }; function success(user) { return { type: userConstants.SET_USER_DATA, user } } function failure(user) { return { type: userConstants.SET_USER_DATA, user } } } function getAll() { return dispatch => { dispatch(request()); userService.getAll() .then( users => dispatch(success(users)), error => { dispatch(failure(error)); dispatch(alertActions.error(error)) } ); }; function request() { return { type: userConstants.GETALL_REQUEST } } function success(users) { return { type: userConstants.GETALL_SUCCESS, users } } function failure(error) { return { type: userConstants.GETALL_FAILURE, error } } }
10a1f5867cad584f62b234af2a6c55d94114a5d6
[ "JavaScript" ]
5
JavaScript
Reactist215/react-express-invoice-webapplication
38686497816bbd029fa46ad8147afd1af649cdb3
1c2078fca4d6bc8a1bccb3550738c30724e03654
refs/heads/master
<repo_name>greenday99/python_FJUmasterThesis<file_sep>/part_1_FCM_data_process/stock_var.py # -*- coding:utf-8 -*- # copyright: <NAME> # 计算历史模拟法和蒙地卡罗模拟法的VaR值 # 要求:在训练期中,至少要有230天的有效交易日 # 存储于 data/../csv 文件夹中 # 格式:股票代码,历史模拟法VaR,蒙地卡罗模拟法VaR import os import xlrd import csv from myThesis_new.part_1_FCM_data_process import function_hissimulation as simulation_his from myThesis_new.part_1_FCM_data_process import function_monteCarlo as simulation_mont # 获取目标文件夹位置 osPath = os.path.dirname(os.getcwd()) + '/data/' # 待处理文件夹 var_file_path = ['stock_SH_var/', 'stock_SZ_var/'] # 商品初始价格存储文件夹 origin_price_file_name = 'var_original_price/' # 待处理文件名 period = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'] sub_period = ['_0', '_1', '_2', '_3', '_4', '_5'] page = ['_0', '_1'] # 输出文件夹 output_file_path_csv = 'csv/' # 两个后缀名 xls_ext_name = '.xls' csv_ext_name = '.csv' # 有效交易日期的设定 VALIDE_DAYS = 230 # 模拟置信区间 CONFIDENCE_LIMIT = 0.95 # 蒙地卡罗模拟次数 SIMULATE_TIMES = 10000 # 获取所有研究期间的估算期间 sim_days = {} sim_file_path = osPath + 'simulation_days.csv' sim_file = open(sim_file_path, 'r') reader = csv.reader(sim_file) for row in reader: sim_days[row[0]] = int(row[1]) for sub_var_file_path in var_file_path: for period_name in period: # 获取当期的估算期间 now_sim_days = sim_days[period_name] # 获取当期所有商品的初始资产价格 origin_price = {} origin_price_file_path = osPath + sub_var_file_path + origin_price_file_name + period_name + xls_ext_name origin_price_file = xlrd.open_workbook(origin_price_file_path) price_table = origin_price_file.sheets()[0] price_table_rows = price_table.nrows for i in range(1, price_table_rows): row = price_table.row_values(i) origin_price[row[0]] = float(row[1]) # 用来存储当期研究期间的所有股票的var值 period_list = [] period_list.append(['item_id', 'unadjusted_var', 'adjusted_var']) for sub_period_name in sub_period: # 用来存储当前股票的资料 now_item = [] # 用来判断是否到达下一个股票的资料 item_id_now = '' item_id_previous = '' # 输入的文件地址 input_file_path_0 = osPath + sub_var_file_path + period_name + sub_period_name + page[0] + xls_ext_name input_file_path_1 = osPath + sub_var_file_path + period_name + sub_period_name + page[1] + xls_ext_name # 打开相应的文件,若无,则跳出该循环 try: open_input_file_0 = xlrd.open_workbook(input_file_path_0) except: break table_0 = open_input_file_0.sheets()[0] table_rows_0 = table_0.nrows # period为02、03、04的要单独处理 if period_name == '02' or period_name == '03' or period_name == '04': special_item_list = {} # 存储第二个page中的各股票资料 open_input_file_1 = xlrd.open_workbook(input_file_path_1) table_1 = open_input_file_1.sheets()[0] table_rows_1 = table_1.nrows for k in range(1, table_rows_1): row_1 = table_1.row_values(k) if row_1[0] in special_item_list.keys(): if row_1[2] != '': special_item_list[row_1[0]].append(row_1[2]) else: special_item_list[row_1[0]] = [] if row_1[2] != '': special_item_list[row_1[0]].append(row_1[2]) for i in range(1, table_rows_0): row = table_0.row_values(i) item_id_now = str(row[0]) # 第一条记录 if item_id_previous == '': item_id_previous = item_id_now if row[2] != '': now_item.append(float(row[2])) # 同一个商品,并且不是最后一条记录 if item_id_previous == item_id_now and i != table_rows_0 - 1: if row[2] != '': now_item.append(float(row[2])) # 同一个商品,并且是最后一条记录 if item_id_previous == item_id_now and i == table_rows_0 - 1: if row[2] != '': now_item.append(float(row[2])) # period为02、03、04时需要将page2加入 if period_name == '02' or period_name == '03' or period_name == '04': now_item += special_item_list[item_id_now] # 计算商品的有效交易天数是否满足要求 if len(now_item) > VALIDE_DAYS: # 满足,则开始计算VaR值 # 获取这个商品的初始资产价格 item_origin_price = origin_price[item_id_now] unadjuested_var = simulation_his.getVaR(now_item, now_sim_days, item_origin_price, CONFIDENCE_LIMIT) adjuested_var = simulation_mont.getVaR(now_item, now_sim_days, item_origin_price, CONFIDENCE_LIMIT, SIMULATE_TIMES) # 将结果放入period_list中 period_list.append([item_id_now, unadjuested_var, adjuested_var]) # 这个商品全部读取完毕 if item_id_previous != item_id_now: # period为02、03、04时需要将page2加入 if period_name == '02' or period_name == '03' or period_name == '04': now_item += special_item_list[item_id_previous] # 计算商品的有效交易天数是否满足要求 if len(now_item) < VALIDE_DAYS: # 不满足,则这个商品不计算,开始记录下一个商品 item_id_previous = item_id_now now_item = [] if row[2] != '': now_item.append(float(row[2])) else: # 获取这个商品的初始资产价格 item_origin_price = origin_price[item_id_previous] unadjuested_var = simulation_his.getVaR(now_item, now_sim_days, item_origin_price, CONFIDENCE_LIMIT) adjuested_var = simulation_mont.getVaR(now_item, now_sim_days, item_origin_price, CONFIDENCE_LIMIT, SIMULATE_TIMES) # 将结果放入period_list中 period_list.append([item_id_now, unadjuested_var, adjuested_var]) # 开始记录下一个商品 now_item = [] item_id_previous = item_id_now if row[2] != '': now_item.append(float(row[2])) # 当期资料全部计算完毕,存入csv中 output_file_path = osPath + sub_var_file_path + output_file_path_csv + period_name + csv_ext_name output = open(output_file_path, 'w') writer = csv.writer(output) writer.writerows(period_list) print('success: ' + str(output_file_path)) <file_sep>/README.md - data resource: RESSET<file_sep>/part_1_FCM_data_process/stock_beta.py # -*- coding:utf-8 -*- # copyright: GU, MANQING # 剔除建筑业类、金融业类的股票 'E' 'J' # 将本期与下一期的股票代码比较,删去下一期没有的股票代码 -> 保证股票在整个研究期间内都有数据 # 记录股票及其对应的股票门类,放置于 data/../stock_type 文件夹中 # 格式:股票代码,门类代码 # 处理完毕的股票及其beta值,放置于 data/../csv 文件夹中 # 格式:股票代码,股票名称,门类代码,beta import os import xlrd import csv # 获取目标文件夹位置 osPath = os.path.dirname(os.getcwd()) + '/data/' # 待处理文件夹 beta_file_path = ['stock_SH_beta/', 'stock_SZ_beta/'] # 待处理文件名 period = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21'] # 输出文件夹 output_file_path_type = 'stock_type/' output_file_path_csv = 'csv/' # 用来存储不同市场,各研究期间的股票代码文件名称 beta_file_name = ['stock_beta2var_SH', 'stock_beta2var_SZ'] # 两个后缀名 xls_ext_name = '.xls' csv_ext_name = '.csv' for k in range(len(beta_file_path)): sub_beta_file_path = beta_file_path[k] # 将每个研究期间的股票代码存储下来,用于获取var资料 list_id = [] for i in range(len(period) - 1): period_name_now = period[i] # 目前要处理的研究期间名称 period_name_next = period[i + 1] # 需要进行相互比较的研究期间名称 input_file_name_now = osPath + sub_beta_file_path + period_name_now + xls_ext_name input_file_name_next = osPath + sub_beta_file_path + period_name_next + xls_ext_name list_id.append([period_name_now]) # 存储当前的研究期间 # 先处理目前的研究期间,剔除2类股票 open_file_now = xlrd.open_workbook(input_file_name_now) table_now = open_file_now.sheets()[0] table_now_rows = table_now.nrows list_now = [] # 用于存储目前研究期间的数据 for i in range(table_now_rows): row_now = table_now.row_values(i) if i != 0: if row_now[2] == 'E' or row_now[2] == 'J': continue list_now.append([row_now[0], row_now[1], row_now[2], row_now[4]]) # 打开要互相比较的研究期间 open_file_next = xlrd.open_workbook(input_file_name_next) table_next = open_file_next.sheets()[0] table_next_rows = table_next.nrows list_next = [] # 用于存储下一个研究期间的数据 for i in range(table_next_rows): row_next = table_next.row_values(i) list_next.append(row_next) # 两者比较,得出最终结果 final_list = [] final_list.append(list_now[0]) for i in range(1, len(list_now)): for j in range(1, len(list_next)): if list_now[i][0] in list_next[j]: final_list.append(list_now[i]) break # 将最终结果final_list存储 output_file_path = osPath + sub_beta_file_path + output_file_path_csv + period_name_now + csv_ext_name output = open(output_file_path, 'w') writer = csv.writer(output) writer.writerows(final_list) # 提炼出 股票编号,股票门类 并存储 list_type = [] sub_list_id = [] for i in range(len(final_list)): list_type.append([final_list[i][0], final_list[i][2]]) if i != 0: sub_list_id.append(final_list[i][0]) list_id.append(sub_list_id) # 存储当前研究期间的股票代码 # 将最终结果list_type存储 output_file_path = osPath + sub_beta_file_path + output_file_path_type + period_name_now + csv_ext_name output = open(output_file_path, 'w') writer = csv.writer(output) writer.writerows(list_type) print('success:' + str(output_file_path)) # 将list_id 存储 output_file_path = osPath + beta_file_name[k] + csv_ext_name output = open(output_file_path, 'w') writer = csv.writer(output) writer.writerows(list_id) print('ok:' + str(output_file_path)) <file_sep>/tests.py import numpy as np import math a = np.array([1,2,3,4,5]) b = np.array([5,4,3,2,1]) print(a*a) print(np.sum(a*a))<file_sep>/part_1_FCM_data_process/fund_beta.py # -*- coding:utf-8 -*- # copyright: <NAME> # 计算beta值 # 要求:在训练期中,至少要有230天的有效交易日 # 记录基金及其对应的基金种类ETF or LOF,放置于 data/../fund_type 文件夹中 # 格式:基金代码,基金种类(2: LOF; 3: ETF) # 处理完毕的基金及其beta值,放置于 data/../csv 文件夹中 # 格式:基金代码,基金名称,基金种类,beta import os import xlrd import csv import numpy as np import math # 获取目标文件夹位置 osPath = os.path.dirname(os.getcwd()) + '/data/' # 待处理文件夹 beta_file_path = ['fund_SH_beta/', 'fund_SZ_beta/'] # 基金种类名 type_name = ['ETF_', 'LOF_'] # 待处理文件名 period = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'] # 输出文件夹 output_file_path_type = 'fund_type/' output_file_path_csv = 'csv/' # 用来存储不同市场,各研究期间的基金代码文件名称 beta_file_name = ['fund_beta2var_SH', 'fund_beta2var_SZ'] # 两个后缀名 xls_ext_name = '.xls' csv_ext_name = '.csv' # 有效交易日期的设定 VALIDE_DAYS = 230 # beta计算公式 def getBeta(item_rate, hs300_rate): item_rate_array = np.array(item_rate) hs300_rate_array = np.array(hs300_rate) # 样本区间内所含的交易天数 n = len(item_rate) # 沪深300涨跌幅 × 基金净值增长率之和 part_a = np.sum(item_rate_array * hs300_rate_array) # 沪深300指数涨跌幅之和 part_b = np.sum(hs300_rate_array) # 基金净值增长率之和 part_c = np.sum(item_rate_array) # 沪深300指数涨跌幅平方之和 part_d = np.sum(hs300_rate_array * hs300_rate_array) # 基金净值增长率之和的平方 part_e = math.pow(np.sum(hs300_rate_array), 2) # 计算beta result = ((n * part_a) - (part_b * part_c)) / ((n * part_d) - part_e) return result # 开始计算每个文件基金的beta for k in range(len(beta_file_path)): sub_beta_file_path = beta_file_path[k] # 将每个研究期间的股票代码存储下来,用于获取var资料 list_id = [] for period_name in period: # 将当前的基金种类和研究期间存入list_id list_id.append([period_name]) # 用来存储当期研究期间的所有基金的beta值 period_list = [] period_list.append(['item_id', 'item_name', 'item_type', 'beta']) # 用来储存当期研究期间的所有基金的种类 type_list = [] type_list.append(['item_id', 'item_type']) for type in type_name: input_file_path = osPath + sub_beta_file_path + type + period_name + xls_ext_name # 档案读取,如果出错,则代表已没有该文件,需要跳出循环 try: open_input_file = xlrd.open_workbook(input_file_path) except: break table = open_input_file.sheets()[0] table_rows = table.nrows # 用来存储当前基金的日净值增长率 now_item_rate = [] # 用来存储当前日期的沪深300指数涨跌幅 now_hs300_rate = [] # 用来判断是否到达下一个基金的资料 item_id_now = '' item_id_previous = '' for i in range(1, table_rows): row = table.row_values(i) item_id_now = str(row[0]) # 第一条记录 if item_id_previous == '': item_id_previous = item_id_now if row[3] != '': now_item_rate.append(float(row[3])) now_hs300_rate.append(float(row[4])) # 同一个商品,并且不是最后一条记录 if item_id_previous == item_id_now and i != table_rows - 1: if row[3] != '': now_item_rate.append(float(row[3])) now_hs300_rate.append(float(row[4])) # 同一个商品,并且是最后一条记录 if item_id_previous == item_id_now and i == table_rows - 1: if row[3] != '': now_item_rate.append(float(row[3])) now_hs300_rate.append(float(row[4])) # 计算商品的有效交易天数是否满足要求 if len(now_item_rate) > VALIDE_DAYS: # 满足,则开始计算beta值 beta_value = getBeta(now_item_rate, now_hs300_rate) # 确认基金种类 if type == 'ETF_': item_type = 3 if type == 'LOF_': item_type = 2 # 放入period_list中 period_list.append([item_id_previous, row[1], item_type, beta_value]) # 放入type_list中 type_list.append([item_id_previous, item_type]) # 这个商品全部读取完毕 if item_id_previous != item_id_now: # 计算商品的有效交易天数是否满足要求 if len(now_item_rate) > VALIDE_DAYS: # 满足,则开始计算beta值 beta_value = getBeta(now_item_rate, now_hs300_rate) # 确认基金种类 if type == 'ETF_': item_type = 3 if type == 'LOF_': item_type = 2 # 放入period_list中 period_list.append([item_id_previous, table.row_values(i - 1)[1], item_type, beta_value]) # 放入type_list中 type_list.append([item_id_previous, item_type]) # 开始记录下一个商品 now_item_rate = [] now_hs300_rate = [] item_id_previous = item_id_now if row[3] != '': now_item_rate.append(float(row[3])) now_hs300_rate.append(float(row[4])) # 当期资料全部计算完毕,存入csv中 output_file_path_period = osPath + sub_beta_file_path + output_file_path_csv + period_name + csv_ext_name output = open(output_file_path_period, 'w') writer = csv.writer(output) writer.writerows(period_list) output_file_type_path = osPath + sub_beta_file_path + output_file_path_type + period_name + csv_ext_name output = open(output_file_type_path, 'w') writer = csv.writer(output) writer.writerows(type_list) print('success:' + str(output_file_path_period)) # 将该期的id存入list_id中 ids = [] for h in range(1, len(period_list)): ids.append(period_list[h][0]) list_id.append(ids) # 将list_id存储 output_file_path = osPath + beta_file_name[k] + csv_ext_name output = open(output_file_path, 'w') writer = csv.writer(output) writer.writerows(list_id) print('ok: ' + str(output_file_path)) <file_sep>/part_1_FCM_data_process/function_monteCarlo.py # -*- coding:utf-8 -*- # copyright: GU, MANQING # 蒙地卡罗模拟法 import numpy as np import math import random def getVaR(item_list, simulation_days, item_origin_price, CONFIDENCE_LIMIT, SIMULATE_TIMES): # 确定临界损益分布位置,向下取整 select_position = int(SIMULATE_TIMES * (1 - CONFIDENCE_LIMIT)) # 历史期间数 his_days = len(item_list) item_array = np.array(item_list) item_mean = np.mean(item_array) # 平均值 item_std = np.std(item_array) # 标准差 # 存储模拟的数值 sim_list = [] for i in range(SIMULATE_TIMES + 1): value = item_origin_price * math.exp( ((item_mean - (math.pow(item_std, 2) / 2)) * math.exp(random.gauss(0, 1))) + item_std * random.gauss(0,1)) sim_list.append(value) # 计算模拟后的损益分布 sim_rate = [] for i in range(len(sim_list) - 1): sub_rate = (sim_list[i + 1] - sim_list[i]) / sim_list[i] sim_rate.append(sub_rate) # 转换为array,并降序排序 sim_rate_array = np.array(sim_rate) sim_rate_array.sort() # 确定临界损益分布 rate = float(sim_rate_array[select_position]) result = round(math.sqrt(simulation_days) * item_origin_price * rate, 2) return result <file_sep>/database.sql -- MySQL dump 10.13 Distrib 5.7.17, for Linux (x86_64) -- -- Host: localhost Database: myThesisDatabase -- ------------------------------------------------------ -- Server version 5.7.18-0ubuntu0.16.04.1 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `candidates` -- DROP TABLE IF EXISTS `candidates`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `candidates` ( `itemID` varchar(10) NOT NULL, `itemType` int(11) DEFAULT NULL, `openPrice` float DEFAULT NULL, `closePrice` float DEFAULT NULL, `itemPrice` float DEFAULT NULL, `attr_1` float DEFAULT NULL, `attr_2` float DEFAULT NULL, `attr_3` float DEFAULT NULL, `attr_4` float DEFAULT NULL, `attr_5` float DEFAULT NULL, `attr_6` float DEFAULT NULL, `attr_7` float DEFAULT NULL, `attr_8` float DEFAULT NULL, `attr_9` float DEFAULT NULL, `attr_10` float DEFAULT NULL, `attr_11` float DEFAULT NULL, PRIMARY KEY (`itemID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `candidates` -- LOCK TABLES `candidates` WRITE; /*!40000 ALTER TABLE `candidates` DISABLE KEYS */; /*!40000 ALTER TABLE `candidates` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `cluster_four` -- DROP TABLE IF EXISTS `cluster_four`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `cluster_four` ( `itemID` varchar(10) NOT NULL, `itemName` varchar(45) DEFAULT NULL, PRIMARY KEY (`itemID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `cluster_four` -- LOCK TABLES `cluster_four` WRITE; /*!40000 ALTER TABLE `cluster_four` DISABLE KEYS */; /*!40000 ALTER TABLE `cluster_four` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `cluster_one` -- DROP TABLE IF EXISTS `cluster_one`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `cluster_one` ( `itemID` varchar(10) NOT NULL, `itemName` varchar(45) DEFAULT NULL, PRIMARY KEY (`itemID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `cluster_one` -- LOCK TABLES `cluster_one` WRITE; /*!40000 ALTER TABLE `cluster_one` DISABLE KEYS */; /*!40000 ALTER TABLE `cluster_one` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `cluster_three` -- DROP TABLE IF EXISTS `cluster_three`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `cluster_three` ( `itemID` varchar(10) NOT NULL, `itemName` varchar(45) DEFAULT NULL, PRIMARY KEY (`itemID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `cluster_three` -- LOCK TABLES `cluster_three` WRITE; /*!40000 ALTER TABLE `cluster_three` DISABLE KEYS */; /*!40000 ALTER TABLE `cluster_three` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `cluster_two` -- DROP TABLE IF EXISTS `cluster_two`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `cluster_two` ( `itemID` varchar(10) NOT NULL, `itemName` varchar(45) DEFAULT NULL, PRIMARY KEY (`itemID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `cluster_two` -- LOCK TABLES `cluster_two` WRITE; /*!40000 ALTER TABLE `cluster_two` DISABLE KEYS */; /*!40000 ALTER TABLE `cluster_two` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `evaluation_data` -- DROP TABLE IF EXISTS `evaluation_data`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `evaluation_data` ( `itemID` varchar(10) NOT NULL, `itemType` int(11) DEFAULT NULL, `itemPrice` float DEFAULT NULL, `start_info` float DEFAULT NULL, `end_info` varchar(45) DEFAULT NULL, PRIMARY KEY (`itemID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `evaluation_data` -- LOCK TABLES `evaluation_data` WRITE; /*!40000 ALTER TABLE `evaluation_data` DISABLE KEYS */; /*!40000 ALTER TABLE `evaluation_data` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2017-08-22 14:36:04 <file_sep>/part_1_FCM_data_process/function_hissimulation.py # -*- coding:utf-8 -*- # copyright: <NAME> # 历史模拟法 import numpy as np import math def getVaR(item_list, simulation_days, item_origin_price, CONFIDENCE_LIMIT): his_days = len(item_list) # 历史期间 select_position = int(his_days * (1 - CONFIDENCE_LIMIT)) # 确定临界损益分布位置,向下取整 # 转换为array,并降序排序 item_array = np.array(item_list) item_array.sort() # 确定临界损益分布 rate = float(item_array[select_position]) result = round(math.sqrt(simulation_days) * item_origin_price * rate, 2) return result
983f8d959a673f577d71ca378a88998dc5cb237b
[ "Markdown", "SQL", "Python" ]
8
Python
greenday99/python_FJUmasterThesis
835550bd6e7b45f18b403b1664a1a4ccc8635eb1
c9125b4b8cc51eb2788b4f94994d5fbd5fc7bcc0
refs/heads/master
<file_sep>/** * Takes an array of packets and ensures that they are in order. * Puts array of packets in order. * * @author <NAME> * @version 2/5/2018 */ #include <stdio.h> #include <stdlib.h> #include "reorder.h" /** * Checks the order of the array of packets * by comparing the packet num to the loop variable. * * @param len the length of the buffer. * @param pack a buffer containing packet structs. * @return 1 if in order, 0 otherwise. */ int check_order ( int len, struct packet *pack ) { for (int i = 0; i < len; i++) { if (pack[i].p_num != i) { return 0; } } return 1; } /** * Puts the buffer of packets in order. * * @param len the length of the buffer. * @param pack a buffer containing packet structs. * @return 0 once the program is complete. */ int order ( int len, struct packet *pack ) { for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { if ((pack[i].p_num) > (pack[j].p_num)) { struct packet tmp = pack[i]; pack[i] = pack[j]; pack[j] = tmp; } } } return 0; } <file_sep>/** * Takes an array of packets and ensures that they are in order. * Puts array of packets in order. * * @author <NAME> * @version 2/5/2018 */ #pragma pack(1) struct packet { int p_num; char buffer[1024]; }; #pragma pack(0) #ifndef reorder_h #define reorder_h int check_order ( int len, struct packet *pack ); int order ( int len, struct packet *pack ); #endif /* reorder.h */ <file_sep>/** * UDP Server that sends files to a client. * * @author <NAME>, <NAME>, <NAME> * @version 2/5/2018 */ #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <fcntl.h> #include <math.h> #pragma pack(1) struct packet { int p_num; char buffer[1024]; }; #pragma pack(0) int main(int argc, char **argv) { int port_num; char temp[5]; printf("Enter a port number: "); fgets(temp, 5, stdin); port_num = atoi(temp); while(port_num < 1023 || port_num > 49152) { if (port_num < 1023 || port_num > 49152) { printf("Please enter a valid port between 1023 and 49152"); fgets(temp, 5, stdin); port_num = atoi(temp); } } int sockfd = socket(AF_INET, SOCK_DGRAM, 0); struct timeval timeout; timeout.tv_sec = 5; timeout.tv_usec = 0; /* Set socket options. */ setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); struct sockaddr_in serveraddr, clientaddr; serveraddr.sin_family = AF_INET; serveraddr.sin_port = htons(port_num); serveraddr.sin_addr.s_addr = INADDR_ANY; bind(sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)); while (1) { socklen_t clen = sizeof(clientaddr); char fname[32]; long n = recvfrom(sockfd, fname, 32, 0, (struct sockaddr*) &clientaddr, &clen); /* Checks for any recv error, not just timeout. */ if (n == -1) { printf("Timed out while waiting to receive.\n"); } else { printf("File request from client: %s\n", fname); int file_check; if (access(fname, F_OK) != -1) { file_check = 1; sendto(sockfd, &file_check, sizeof(int) + 1, 0, (struct sockaddr*) &clientaddr, sizeof(clientaddr)); FILE *file = fopen(fname, "rb"); struct stat st; int fsize = 0; if(stat(fname, &st) == 0) { fsize = st.st_size; } char tmp_num; int rem = 0; const int window_size = 5; int num_packets = (fsize / 1024); int buff_l = window_size; /* Calculate remainder. */ if (fsize % 1024 != 0) { rem = fsize - (num_packets * 1024); num_packets++; } int packets_left = num_packets; int packet_info [4] = {-1, fsize, num_packets, window_size}; struct packet msg; int x = 0; printf("%s contains %d bytes for %d packets\n\n", fname, fsize, num_packets); while (x != window_size) { sendto(sockfd, packet_info, sizeof(int) * 4 + 1, 0, (struct sockaddr*) &clientaddr, sizeof(clientaddr)); recvfrom(sockfd, &x, sizeof(int), 0, (struct sockaddr*) &clientaddr, &clen); } /* Buffer to hold packets. */ struct packet *send_buf = (struct packet *) malloc (window_size * sizeof(struct packet)); /* Loops until all packets have been acknowledged. Will resend packets if not acknowledged. */ while(packets_left > 0) { if (packets_left > window_size) { for (int i = 0; i < window_size; i++) { msg.p_num = i; fread(msg.buffer, sizeof(char), 1024, file); send_buf[i] = msg; } } /* Last array of packets to send. */ else { buff_l = packets_left; /* Add what is left. */ for (int i = 0; i < buff_l; i++) { if (fsize - i * 1024 > 1024) { msg.p_num = i; fread(msg.buffer, sizeof(char), 1024, file); send_buf[i] = msg; } else { printf("Last packet.\n"); msg.p_num = i; fread(msg.buffer, sizeof(char), rem, file); send_buf[i] = msg; } } } for (int bl = 0; bl < buff_l; bl++) { printf("Sending packet with sequence number: %d\n", bl); sendto(sockfd, &send_buf[bl], sizeof(struct packet) + 1, 0, (struct sockaddr*) &clientaddr, sizeof(clientaddr)); } /* Wait for acknowledgement. */ recvfrom(sockfd, &tmp_num, sizeof(char)*1, 0, (struct sockaddr*) &clientaddr, &clen); printf("Ack: %d\n", tmp_num); int packet_num = abs(tmp_num-48); printf("Packet Number: %d \t Buffer Length: %d\n", packet_num, buff_l); if (packet_num < buff_l) { packets_left-=packet_num; fseek(file, (packet_info[2]-packets_left)*1024, SEEK_SET); printf("Packet dropped.\n"); } else { printf("All packets made it.\n\n\n"); packets_left -= buff_l; } printf("Packets Left: %d\n", packets_left); } fclose(file); free(send_buf); } else { printf("The file '%s' could not be found.\n", fname); file_check = 0; sendto(sockfd, &file_check, sizeof(int) + 1, 0, (struct sockaddr*) &clientaddr, sizeof(clientaddr)); } } } return 0; } <file_sep>/** * Client that sends data to a server and then receives it back. * * @author <NAME>, <NAME>, <NAME> * @version 2/5/2018 */ #include <arpa/inet.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <unistd.h> #include <sys/uio.h> #include "reorder.h" int main(int argc, char **argv) { if (argc != 2) { printf("Please run the program with the new file name as arguments.\n"); exit(0); } int port_num; char temp[5]; char client_ip[16]; printf("Enter an IP address: "); fgets(client_ip, 16, stdin); printf("Enter a port number: "); fgets(temp, 5, stdin); port_num = atoi(temp); while(port_num < 1023 || port_num > 49152) { if (port_num < 1023 || port_num > 49152) { printf("Please enter a valid port between 1023 and 49152"); fgets(temp, 5, stdin); port_num = atoi(temp); } } printf("Enter a file name: "); char fname[32]; /* Flush stdin. */ char tmp[16]; fgets(tmp, 16, stdin); fgets(fname, 32, stdin); /* Remove trailing newline. */ int l = (int)strlen(fname); if (fname[l - 1] == '\n') { fname[l - 1] = '\0'; } int sockfd = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in serveraddr; serveraddr.sin_family = AF_INET; serveraddr.sin_port = htons(port_num); serveraddr.sin_addr.s_addr = inet_addr(client_ip); printf("\nYou requested the file: %s\n", fname); socklen_t len = sizeof(serveraddr); /* Send file name request to server. */ sendto(sockfd, fname, strlen(fname) + 1, 0, (struct sockaddr*) &serveraddr, sizeof(serveraddr)); int file_check; recvfrom(sockfd, &file_check, sizeof(int), 0, (struct sockaddr*) &serveraddr, &len); if (file_check == 0) { printf("File does not exist\n"); exit(1); } int packet_info[4]; struct packet msg; recvfrom(sockfd, packet_info, sizeof(int) * 4 + 1, 0, (struct sockaddr*) &serveraddr, &len); int fsize = packet_info[1]; int num_packets = packet_info[2]; int window = packet_info[3]; int rem = 0; printf("%d packet #, %d bytes, %d total packets, %d window size\n\n", packet_info[0], fsize, num_packets, window); if (window == 5) { sendto(sockfd, &window, sizeof(int) + 1, 0, (struct sockaddr*) &serveraddr, sizeof(serveraddr)); } while (window != 5) { recvfrom(sockfd, packet_info, sizeof(int) * 4 + 1, 0, (struct sockaddr*) &serveraddr, &len); fsize = packet_info[1]; num_packets = packet_info[2]; window = packet_info[3]; rem = 0; if (window == 5) { sendto(sockfd, &window, sizeof(int) + 1, 0, (struct sockaddr*) &serveraddr, sizeof(serveraddr)); } } /* Calculate remainder. */ if (fsize % 1024 != 0) { num_packets--; rem = fsize - (num_packets * 1024); num_packets++; } FILE* file = fopen(argv[1], "wb"); int packets_left = num_packets; struct packet *tmp_buff = (struct packet *) malloc (window * sizeof(struct packet)); int pack_rec; int pack_nums[5]; while (packets_left > 0) { pack_rec = 0; if (packets_left > window) { for (int i = 0; i < window; i++) { /* Break from loop if it takes too long to receive. */ recvfrom(sockfd, &msg, sizeof(struct packet), 0, (struct sockaddr*) &serveraddr, &len); tmp_buff[i] = msg; printf("Packet sequence number received: %d\n", i); } /* Checks if packets are out of order. */ if (!check_order(window, tmp_buff)) { printf("Out of order."); order(window, tmp_buff); } for (int i = 0; i < window; i++) { fwrite(&tmp_buff[i].buffer, sizeof(char), 1024, file); } for (int i = 0; i < window; i++) { if (tmp_buff[i].p_num == i) { pack_rec ++; } pack_nums[i] = tmp_buff[i].p_num; } //packets_left -= pack_rec;; char ack = '5'; printf("Packetss Received: %d\n", pack_rec); if (pack_rec < window) { for (int i = 1; i < window; i++) { if (pack_nums[i-1]+1 != pack_nums[i]) { printf("Lost a packet\n"); ack = 48+pack_nums[i-1]; break; } } packets_left -= pack_rec; } else { printf("All received.\n\n\n"); packets_left -= pack_rec; } sendto(sockfd, &ack, 1, 0, (struct sockaddr*) &serveraddr, sizeof(serveraddr)); } /* Last set of packets to reveive. */ else { pack_rec = 0; printf("Last array to receive.\n"); int buff_l = packets_left; for (int i = 0; i < buff_l; i++) { if (fsize - i * 1024 > 1024) { recvfrom(sockfd, &msg, sizeof(struct packet), 0, (struct sockaddr*) &serveraddr, &len); pack_rec++; pack_nums[msg.p_num] = msg.p_num; tmp_buff[i] = msg; printf("Packet sequence number received: %d\n", msg.p_num); } else { recvfrom(sockfd, &msg, sizeof(struct packet), 0, (struct sockaddr*) &serveraddr, &len); pack_rec++; pack_nums[msg.p_num] = msg.p_num; tmp_buff[i] = msg; printf("Last packet sequence number received: %d\n", msg.p_num); } } /* Checks if packets are out of order. */ if (!check_order(buff_l, tmp_buff)) { order(buff_l, tmp_buff); } for (int i = 0; i < buff_l; i++) { /* Have to change size for last packet. */ if (i != (buff_l - 1)) { fwrite(&tmp_buff[i].buffer, sizeof(char), 1024, file); } else { printf("Writing last packet of size: %d\n", rem); fwrite(&tmp_buff[i].buffer, sizeof(char), rem, file); } } char ack = '5'; if (pack_rec < buff_l) { for (int i = 1; i < window; i++) { if (pack_nums[i - 1] + 1 != pack_nums[i]) { printf("Lost a packet.\n"); ack = 48 + pack_nums[i-1]; //printf("Ack: %d\n", ack); break; } } packets_left -= pack_rec; } else { packets_left -= pack_rec; } printf("Packets Left: %d\n", packets_left); sendto(sockfd, &ack, 1, 0, (struct sockaddr*) &serveraddr, sizeof(serveraddr)); } } fclose(file); free(tmp_buff); close(sockfd); return 0; } <file_sep>import socket import sys import os.path import threading import pickle import json def client(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: ip = input("Enter IP: ") port = input("Enter Port: ") s.connect((ip, int(port))) break except: print("Unable to establish connection to server") print("Connected to server") while True: file = input("Enter filename: ") s.send(file.encode()) fileExist = s.recv(1024).decode() if fileExist == "y": file = open("COPY_" + file, "wb") size = int(s.recv(1024).decode()) s.send("ready".encode()) print("Receiving file...") packet_buffer = {} for i in range(0,5): packet_buffer[i] = {i:""} next_packet_received = 0 count = 0 while count*1024 < size: # size of dict entry + 1024 bytes # Currently have issue with unpickling - order of bytearray is screwy try: dataP = pickle.loads(s.recv(1073)) except: print ("error unpickling") # print(dataP) for i in dataP: packet_buffer[i] = dataP[i] # if there is order in the buffer (1,2,3) print parts to buffer # if there is not order in buffer (1,3) print ordered part to buffer(1) for i in packet_buffer: if i == next_packet_received: count += 1 next_packet_received += 1 file.write(packet_buffer[i]) # if window at end, reset to start of array if next_packet_received == 5: next_packet_received = 0 # Send ack of the lowest packet in array to shift s.send(str(next_packet_received).encode()) file.close() print("Done receiving") else: print("File does not exist! Check file name."); if __name__ == '__main__': client() <file_sep>import socket import sys import os import subprocess from threading import Thread import pickle import time import json from struct import * class multiClient(Thread): def __init__(self, connection, address): Thread.__init__(self) self.connection = connection self.address = address def run(self): client_ip, client_port = str(self.address[0]), str(self.address[1]) print("Client connection from " + client_ip + ":" + client_port) while True: data = self.connection.recv(1024).decode() if data == 'ls': print("Directory listing requested") files = subprocess.check_output("ls", shell=True) self.connection.send(files) elif data == 'exit': print("Closing client connection") self.connection.close() break else: print("File requested: " + data[0:]) # sends y if file exists, n otherwise if os.path.isfile(data[0:]): data = data[0:] self.connection.send("y".encode()) file = open(data, "rb"); print("Sending file...") size = os.path.getsize(data) self.connection.send(str(os.path.getsize(data)).encode()) if self.connection.recv(1024).decode() == 'ready': packet_buffer = ["","","","",""] count = 0 next_packet_send = 0 # position in array for next packet # gives first 5 packets for i in range (0,5): packet_buffer[i] = {i: file.read(1024)} print(packet_buffer[i]) # Error check for files below size of 1024 -> direct send complete full with pickle.dump # Send first 5 before setting up loop for i in range (0,5): # print(sys.getsizeof(pickle.dumps(packet_buffer[i]))) # size of dict in pickle = 1073 dataP = pickle.dumps(packet_buffer[i], protocol=-1) print(dataP) self.connection.send(dataP) while count*1024 < size: # sets the tmp value to the ack from client - # if loss/corruption/out of order resend as needed # otherwise clear packet of the previous value # and set next 1024 bytes tmp = self.connection.recv(1024).decode() #if the ack is the expected value, draw new packet # increment overall packet count # send new packet (if packet 0 is acked, replace it with packet 5 and send if next_packet_send == tmp: packet_buffer[next_packet_send] = {next_packet_send : file.read(1024)} count += 1 dataP = pickle.dumps(packet_buffer[next_packet_send], protocol=-1) self.connection.send(dataP) next_packet_send += 1 if next_packet_send == 5: next_packet_send = 0 #No ack for packet received else: dataP = pickle.dumps(packet_buffer[next_packet_send], protocol=-1) self.connection.send(dataP) file.close() print("Finished sending") else: self.connection.send("n".encode()) def server(): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: port = input("Enter Port: ") try: server.bind(("", int(port))) break except: print("Unable to create server - invalid port") server.listen(10) while True: conn, addr = server.accept() thread1 = multiClient(conn, addr) thread1.start() if __name__ == '__main__': server()<file_sep># CIS-457-UDP
1fba4bb5b0f258c6aff3a0fef19003a678734166
[ "Markdown", "C", "Python" ]
7
C
crumjo/CIS-457-UDP
196a0d611cb98fa9c818e9afde78b050d1827806
64ac94b178a726b386100df83bfb029fd8f26e02
refs/heads/main
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.SceneManagement; public class levelselect : MonoBehaviour { EventSystem eventSystem; // Use this for initialization void Start () { //sys = this.GetComponent<EventSystem>(); eventSystem = this.GetComponent<EventSystem>(); } // Update is called once per frame void Update () { if(Input.GetButtonDown("Submit") && eventSystem.currentSelectedGameObject.name == "level1"){ SceneManager.LoadScene("BlueCity"); } if(Input.GetButtonDown("Submit") && eventSystem.currentSelectedGameObject.name == "level2"){ SceneManager.LoadScene("mels"); } if(Input.GetButtonDown("Submit") && eventSystem.currentSelectedGameObject.name == "level3"){ SceneManager.LoadScene("level_test1"); } if(Input.GetButtonDown("Submit") && eventSystem.currentSelectedGameObject.name == "level4"){ SceneManager.LoadScene("WOW"); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class pie_movement : MonoBehaviour { public float pieMoveSpeed; bool moveLeft = true; float moveVal = 0.0f; public float moveRange = 10.0f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { Debug.Log (moveVal); if (moveLeft) { transform.Translate (-Vector2.right * pieMoveSpeed * Time.deltaTime); moveVal += 0.1f; if (moveVal >= moveRange) { moveVal = 0.0f; moveLeft = false; } } if (!moveLeft) { transform.Translate (Vector2.right * pieMoveSpeed * Time.deltaTime); moveVal -= 0.1f; if (moveVal <= -moveRange) { moveVal = 0.0f; moveLeft = true; } } } } <file_sep>using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; public class player_control : MonoBehaviour { public float jump_force = 500f; public float horizontal_speed = 50f; public float h_speed_multiplier = 0.75f; public float grav_scale_multiplier = 1.25f; public int fat_state = 0; int fat_state_max = 4; bool jump = false; Vector3 scaleoriginal; private bool canBoost = true; private float boostCooldown = 2f; float spriteIncrease = 0.3f; bool[] increase; Rigidbody2D physics; Animator anim; // Call once when the game is initially launched void Start () { physics = this.GetComponent<Rigidbody2D>(); anim = this.GetComponent<Animator>(); increase = new bool[fat_state_max]; for(int i = 0; i < fat_state_max; i++){ increase[i] = true; } increase[0] = false; } // Update is called once per frame void Update () { RaycastHit2D[] hits = new RaycastHit2D[2]; int h = Physics2D.RaycastNonAlloc(transform.position, -Vector2.up, hits); //cast downwards float angle = Mathf.Abs(Mathf.Atan2(hits[1].normal.x, hits[1].normal.y)*Mathf.Rad2Deg); //get angle Debug.Log(angle); if(fat_state >= 4){ //reload level //SceneManager.LoadScene(SceneManager.GetActiveScene().name); StartCoroutine(resetlevel()); //physics.constraints = RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezePositionY; } else{ //flip sprites to face direction moving if((Mathf.Abs(angle) < 10) || (Input.GetAxis("Horizontal") != 0)){ flip(); } } // Get the horizontal movement from the keyboad (A,D,left arrow,right arrow) float horiz = Input.GetAxis("Horizontal") * horizontal_speed; // Should I be playing walking animation? // Animator anim = this.GetComponent<Animator>(); // anim.SetFloat("Horizontal", Mathf.Abs(horiz)); if(increase[fat_state]){ scaleoriginal = this.transform.localScale; scaleoriginal.z = 0; scaleoriginal.x *= spriteIncrease; scaleoriginal.y *= spriteIncrease; transform.localScale += scaleoriginal; increase[fat_state] = false; } // Did the player press the space bar? if (Input.GetButtonDown("Jump") && jump) { Debug.Log ("jumped"); // Give us an upwards velocity physics.AddForce(new Vector2(0, 1.25f * jump_force)); jump = false; anim.SetBool("jump",true); } // Did the player press to dash if (Input.GetButtonDown("Fire1")) { Debug.Log ("dashed"); Vector2 boostSpeed = new Vector2(20,0); if(Input.GetAxis("Horizontal") < 0){ boostSpeed = -boostSpeed; } if(canBoost){ anim.SetBool("jump",false); anim.SetBool("dash", true); StartCoroutine(Boost(0.5f, boostSpeed)); } } //if (Pie.IsTrigger () == true) { //Destroy (Pie); // Use our horizontal movement to move left and right physics.velocity = new Vector2(horiz, physics.velocity.y); } IEnumerator Boost(float boostDur, Vector2 boostSpeed) //Coroutine with a single input of a float called boostDur, which we can feed a number when calling { float time = 0f; //create float to store the time this coroutine is operating canBoost = false; //set canBoost to false so that we can't keep boosting while boosting while(boostDur > time) //we call this loop every frame while our custom boostDuration is a higher value than the "time" variable in this coroutine { time += Time.deltaTime; //Increase our "time" variable by the amount of time that it has been since the last update physics.velocity = boostSpeed; //set our rigidbody velocity to a custom velocity every frame, so that we get a steady boost direction like in Megaman yield return new WaitForSeconds(0); //go to next frame } yield return new WaitForSeconds(boostCooldown); //Cooldown time for being able to boost again, if you'd like. anim.SetBool("dash", false); } IEnumerator resetlevel(){ yield return new WaitForSeconds(1); SceneManager.LoadScene(SceneManager.GetActiveScene().name); } void Dead(){ SceneManager.LoadScene(SceneManager.GetActiveScene().name); } IEnumerator levelselect(){ yield return new WaitForSeconds(1f); SceneManager.LoadScene("levelselect"); } void flip(){ //flip sprites if faced other direction if(Input.GetAxis("Horizontal") < 0){ if(transform.localScale.x >= 0){ Vector3 scale = transform.localScale; scale.x *= -1; transform.localScale = scale; } } else if (Input.GetAxis("Horizontal") > 0){ if (transform.localScale.x < 0){ Vector3 scale = transform.localScale; scale.x *= -1; transform.localScale = scale; } } } float getAngle(){ RaycastHit2D[] hits = new RaycastHit2D[2]; int h = Physics2D.RaycastNonAlloc(transform.position, -Vector2.up, hits); //cast downwards float angle = Mathf.Abs(Mathf.Atan2(hits[1].normal.x, hits[1].normal.y)*Mathf.Rad2Deg); //get angle Debug.Log(angle); return angle; } void OnCollisionEnter2D(Collision2D col) { if (col.gameObject.tag == "Pie") { Destroy (col.gameObject); physics.gravityScale *= grav_scale_multiplier; horizontal_speed *= h_speed_multiplier; //Debug.Log("collided!"); if(fat_state < 4){ fat_state += 1; } anim.SetInteger("fat_state", fat_state); } if (col.gameObject.tag == "Platform" || col.gameObject.tag == "MovingPlatform") { if (jump == false) { jump = true; anim.SetBool("jump", false); canBoost = true; } } if(col.gameObject.tag == "Boundary") { Dead(); } //hit tagged finish object to go to level select if(col.gameObject.tag == "Finish") { StartCoroutine(levelselect()); } if ((col.transform.tag == "MovingPlatform") && Mathf.Abs(getAngle()) < 0.0000001) { transform.parent = col.transform; } } void OnCollisionStay2D(Collision2D col) { if (col.gameObject.tag == "Platform" || col.gameObject.tag == "MovingPlatform") { if(physics.velocity.x != 0){ anim.SetBool("walking", true); } else if(physics.velocity.x <= 0.00f){ anim.SetBool("walking", false); } } } void OnCollisionExit2D(Collision2D col) { if (col.gameObject.tag == "Platform" || col.gameObject.tag == "MovingPlatform") { anim.SetBool("walking", false); } if (col.transform.tag == "MovingPlatform") { transform.parent = null; } } } <file_sep># Piehole NOT WORKING!!! Simple 2DPlat Sidescroller
2c511aa1d51fcbe8f582177596776dc700557609
[ "Markdown", "C#" ]
4
C#
draxlus/Piehole
4cdc253e4a2e5b98ce728e6598269dc43bf5632a
cfc723b7ae5082ccb14236d8b0d11f36fb4d0a6b
refs/heads/master
<file_sep>package cn.test.hibernate; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.junit.Test; public class TesthHibernate { // 向数据库里插入一条记录 @Test public void demo() { // 1.创建配置对象 Configuration config = new Configuration(); // 2.读取配置文件 config.configure(); // 3.创建serviceRegistry对象 ServiceRegistry serviceregistry = new StandardServiceRegistryBuilder().build(); // 4.创建sessionFactory对象 SessionFactory sessionFactory = config.buildSessionFactory(serviceregistry); // 5.获取session对象 Session session = sessionFactory.openSession(); // 6.开启事务 Transaction tx = session.beginTransaction(); // 7.业务逻辑操作 // 向数据库中插入一条记录 Customer customer = new Customer(); customer.setName("测试2"); customer.setAge(25); session.save(customer); // 事务提交 tx.commit(); // 8.释放资源 session.close(); } // 按照id进行查询 @Test public void demo2() { // 1.创建配置对象 Configuration configuration = new Configuration(); // 2.加载核心配置文件hibernate.cfg.xml,其中去获取Customer.hbm.xml(包含对象关系映射) configuration.configure(); // 3.创建serviceRegistry对象 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().build(); // 4.创建sessionFactory对象,构建session工厂 SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); // 5.获取session对象 Session session = sessionFactory.openSession(); // 6.开启事务 Transaction tx = session.beginTransaction(); // 7.业务逻辑操作 // 按照id进行查询 // 使用get查询 Customer customer = (Customer) session.get(Customer.class, 1);// 立即发出SQL语句 System.out.println(customer); // 使用load查询 Customer customer1 = (Customer) session.load(Customer.class, 1);// 没用发送SQL System.out.println(customer1);// 发送SQL // 事务提交 tx.commit(); // 8.释放资源 session.close(); } // 修改记录 @Test public void demo3() { // 1.创建配置对象 Configuration configuration = new Configuration(); // 2.加载核心配置文件 configuration.configure(); // 3.创建serviceRegistry对象 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().build(); // 4.创建sessionFactory对象,构建session工厂 SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); // 5.获取session对象 Session session = sessionFactory.openSession(); // 6.开启事务 Transaction tx = session.beginTransaction(); // 7.业务逻辑操作 // 修改记录的两种方式 // 手动创建对象的方式 /* * Customer customer2 = new Customer(); customer2.setId(6); * customer2.setName("yaya"); session.update(customer2); */ // 先查询再修改的方式 Customer customer2 = (Customer) session.get(Customer.class, 1); customer2.setName("测试1"); session.update(customer2); // 事务提交 tx.commit(); // 8.释放资源 session.close(); } // 删除记录 @Test public void demo4() { // 1.创建配置对象 Configuration configuration = new Configuration(); // 2.加载核心配置文件 configuration.configure(); // 3.创建serviceRegistry对象 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().build(); // 4.创建sessionFactory对象,构建session工厂 SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); // 5.获取session对象 Session session = sessionFactory.openSession(); // 6.开启事务 Transaction tx = session.beginTransaction(); // 7.业务逻辑操作 // 删除记录有两种方式: // 手动创建对象的方式 /* * Customer customer3 = new Customer(); customer3.setId(7); * session.delete(customer3); */ // 5.2先查询在删除的方式 Customer customer3 = (Customer) session.get(Customer.class, 6); session.delete(customer3); // 事务提交 tx.commit(); // 8.释放资源 session.close(); } // 查询所有 @Test public void demo5() { // 1.创建配置对象 Configuration configuration = new Configuration(); // 2.加载核心配置文件 configuration.configure(); // 3.创建serviceRegistry对象 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().build(); // 4.创建sessionFactory对象,构建session工厂 SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); // 5.获取session对象 Session session = sessionFactory.openSession(); // 6.开启事务 Transaction tx = session.beginTransaction(); // 7.业务逻辑操作 // 7.1查询所有的客户 Query query = session.createQuery("from Customer"); List<Customer> list = query.list(); // 7.2按名称查询 /* * Query query = session.createQuery("from Customer where name = ?"); * query.setParameter(0, "测试1"); */ /* * Query query = session.createQuery("from Customer where name = :a"); * query.setParameter("a", "测试1"); List<Customer> list = query.list(); */ for (Customer customer : list) { System.out.println(customer); } // 事务提交 tx.commit(); // 8.释放资源 session.close(); } } <file_sep>package cn.test.hibernate; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test; import cn.test.hibernateutils.HibernateUtils; public class TesthHibernate2 { // 向数据库里插入一条记录 @Test public void demo() { Session session = HibernateUtils.openSession(); Transaction tx = session.beginTransaction(); // 业务逻辑操作 // 向数据库中插入一条记录 Customer customer = new Customer(); customer.setName("测试5"); customer.setAge(26); // 添加对象 session.save(customer); customer.setId(10); customer.setName("测试4"); customer.setAge(25); // 添加并更新对象 session.saveOrUpdate(customer); // 事务提交 tx.commit(); // 释放资源 session.close(); } } <file_sep>hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect hibernate.dialect=org.hibernate.dialect.MySQLMyISAMDialect hibernate.connection.driver_class=com.mysql.jdbc.Driver hibernate.connection.url=jdbc:mysql://localhost:3306/TestHibernate4 hibernate.connection.username=root hibernate.connection.password=<PASSWORD> hibernate.show_sql=true hibernate.format_sql=true hibernate.connection.autocommit=false connection.provider_class=org.hibernate.connection.C3P0ConnectionProvider hibernate.c3p0.max_size=2 hibernate.c3p0.min_size=20 hibernate.c3p0.timeout=120 hibernate.c3p0.max_statements=100 hibernate.c3p0.idle_test_period=3000 hibernate.c3p0.acquire_increment=2 hibernate.c3p0.validate=false
546fbba57b689d3d1adab234412845068ab45ead
[ "Java", "INI" ]
3
Java
XMingcoder/TestHibernate
f29ba4e36da513ae684e94a5ec99b5be0190af64
0d15532d5b72025d5dd3c36ba12d933bec80c9f4
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Post; class PagesController extends Controller { public function index(){ $posts = Post::orderBy('created_at', 'desc')->take(2)->get(); return view('pages.index')->with('posts', $posts); } public function about(){ return view('pages.about'); } public function contact(){ return view('pages.contact'); } public function blog(){ return view('pages.blog'); } public function nhsl(){ return view('pages.nhsl'); } public function nesl(){ return view('pages.nesl'); } public function nmsl(){ return view('pages.nmsl'); } public function ncfsl(){ return view('pages.ncfsl'); } public function nnmcsl(){ return view('pages.nnmcsl'); } public function nsl(){ return view('pages.nsl'); } } <file_sep><?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\PagesController; use App\Http\Controllers\DashboardController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', [PagesController::class, 'index']); Route::get('/about', [PagesController::class, 'about']); Route::get('/contact', [PagesController::class, 'contact']); Route::get('/blog', [PagesController::class, 'blog']); Route::get('/nhsl', [PagesController::class, 'nhsl']); Route::get('/nesl', [PagesController::class, 'nesl']); Route::get('/nmsl', [PagesController::class, 'nmsl']); Route::get('/ncfsl', [PagesController::class, 'ncfsl']); Route::get('/nnmcsl', [PagesController::class, 'nnmcsl']); Route::get('/nsl', [PagesController::class, 'nsl']); Route::resource('posts', 'PostsController'); Auth::routes(); Route::group(['middleware' => ['auth', 'admin']], function () { Route::get('/dashboard', [DashboardController::class, 'index']); });
da21d1a0b1ff5c6f893e55b78f977f16ed6aafd9
[ "PHP" ]
2
PHP
Adebogunabdulroheem/nhl
cb034d9877870f6f9f4d164939246f9a0c7ca5b4
929db044e8cb1c44576a623072061d4cb642bec4
refs/heads/master
<repo_name>w-joy5015/stackathon<file_sep>/server/db/models/device.js const Sequelize = require('sequelize') const db = require('../db') const Device = db.define('device', { name: { type: Sequelize.STRING, unique: true, allowNull: false }, manufacturerUrl: { type: Sequelize.STRING }, imageUrl: { type: Sequelize.STRING, defaultValue: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJigHRateAPTSp8MjH3M6crq5K8_W8os2tuuwYtOninnHFCTPWQg&s' }, info: { type: Sequelize.TEXT } }) module.exports = Device <file_sep>/script/seed.js 'use strict' const db = require('../server/db') const {User, Device, Post} = require('../server/db/models') async function seed() { await db.sync({force: true}) console.log('db synced!') const users = await Promise.all([ User.create({ email: '<EMAIL>', password: '123', patientOrCaregiver: 'patient' }), User.create({ email: '<EMAIL>', password: '123', patientOrCaregiver: 'caregiver' }) ]) const devices = await Promise.all([ Device.create({ name: 'Nexplanon', manufacturerUrl: 'https://www.nexplanon.com/', imageUrl: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQIy822m-VCNACR4wQMjqOIj9o03b-6doz_zFN8vOYbUR0iy4up&s', info: 'Birth control implant inserted under the skin of the upper arm, effective for up to 4 years.' }), Device.create({ name: 'MIC-KEY button', manufacturerUrl: 'https://www.mic-key.com/', imageUrl: 'http://pandaenvos.nl/wp-content/uploads/2019/05/MIC-KEY-button-1000x600.jpg', info: 'Gastrostomy feeding tube used to access the stomach for providing nourishment, fluids, and medications.' }), Device.create({ name: 'Adapta Pacemaker', manufacturerUrl: 'https://www.medtronic.com/us-en/healthcare-professionals/products/cardiac-rhythm/pacemakers/adapta.html', imageUrl: 'https://img.medicalexpo.com/images_me/photo-g/70691-9969954.jpg', info: 'Internal pacemaker for bradycardia (slow heart rate)' }) ]) const posts = await Promise.all([ Post.create({ postType: 'retrospective', sideEffects: ['fatigue'], effectiveness: 'very effective', pain: 2, overallSatisfaction: 8, deviceId: 1, userId: 1 }) ]) console.log( `seeded ${users.length} users, ${posts.length} posts, and ${ devices.length } devices` ) console.log(`seeded successfully`) } // We've separated the `seed` function from the `runSeed` function. // This way we can isolate the error handling and exit trapping. // The `seed` function is concerned only with modifying the database. async function runSeed() { console.log('seeding...') try { await seed() } catch (err) { console.error(err) process.exitCode = 1 } finally { console.log('closing db connection') await db.close() console.log('db connection closed') } } // Execute the `seed` function, IF we ran this module directly (`node seed`). // `Async` functions always return a promise, so we can use `catch` to handle // any errors that might occur inside of `seed`. if (module === require.main) { runSeed() } // we export the seed function for testing purposes (see `./seed.spec.js`) module.exports = seed <file_sep>/client/components/users-new-post.js import React from 'react' import {connect} from 'react-redux' import {postThunkCreator} from '../store/posts' class NewPost extends React.Component { constructor(props) { super(props) this.handleSubmit = this.handleSubmit.bind(this) this.handleChange = this.handleChange.bind(this) this.state = { pain: 0, sideEffects: [], effectiveness: 0, overallSatisfaction: 0, deviceId: 0 } } async handleSubmit(event) { event.preventDefault() await this.props.postThunkCreator( this.props.match.params.userid, this.state ) this.props.history.push('/home') } handleChange(event) { this.setState({[event.target.name]: event.target.value}) } render() { return ( <form className="new-response-container" onSubmit={this.handleSubmit}> <label htmlFor="pain">Select your device</label> <select style={{display: 'inline'}} name="sideEffects" onChange={this.handleChange} required > <option value={1}>Nexplanon</option> <option value={2}>MIC-KEY button</option> <option value={3}>Adapta Pacemaker</option> </select> <label htmlFor="pain">Pain Scale (required)</label> <p> On a scale of 0-10 (10 being the worst pain you have experienced and 0 being no pain) rate your pain level since you've started using your device. </p> <select style={{display: 'inline'}} name="sideEffects" onChange={this.handleChange} required > <option value={0}>0</option> <option value={1}>1</option> <option value={2}>2</option> <option value={3}>3</option> <option value={4}>4</option> <option value={5}>5</option> <option value={6}>6</option> <option value={7}>7</option> <option value={8}>8</option> <option value={9}>9</option> <option value={10}>10</option> </select> <label htmlFor="sideEffects">Side Effects</label> <p> Have you noticed any new symptoms since you've started using your device? Check all that apply: </p> <input name="sideEffects" value={this.state.sideEffects} onChange={this.handleChange} /> <label htmlFor="effectiveness">Effectiveness</label> <p>How effective you would you rate your device?</p> <select style={{display: 'inline'}} name="effectiveness" onChange={this.handleChange} required > <option value="very effective">very effective</option> <optoin value="moderately effective">moderately effective</optoin> <option value="somewhat effective">somewhat effective</option> <option value="not effective at all">not effective at all</option> </select> <label htmlFor="overallSatisfaction">Overall Satisfaction</label> <p>Please rate your overall satisfaction with your device so far:</p> <select name="overallSatisfaction" value={this.state.overallSatisfaction} onChange={this.handleChange} required > <option value={1}>1 - not satisfied at all</option> <option value={2}>2</option> <option value={3}>3 - moderately satisfied</option> <option value={4}>5</option> <option value={5}>5 - very satisfied</option> </select> <label htmlFor="otherComments">Additional comments here:</label> <input name="otherComments" value={this.state.otherComments} onChange={this.handleChange} /> <button type="submit">Save Changes</button> </form> ) } } const mapDispatch = dispatch => ({ postThunkCreator: (arg1, arg2) => dispatch(postThunkCreator(arg1, arg2)) }) export default connect(null, mapDispatch)(NewPost) <file_sep>/server/db/models/post.js const Sequelize = require('sequelize') const db = require('../db') const Post = db.define('post', { postType: { type: Sequelize.STRING, validate: { isIn: [['longitudinal', 'retrospective']] } }, sideEffects: { type: Sequelize.ARRAY(Sequelize.TEXT) }, effectiveness: { type: Sequelize.STRING, validate: { isIn: [ [ 'very effective', 'moderately effective', 'somewhat effective', 'not effective at all' ] ] } }, pain: { type: Sequelize.INTEGER }, overallSatisfaction: { type: Sequelize.INTEGER }, otherComments: { type: Sequelize.TEXT } }) module.exports = Post <file_sep>/client/components/user-responses.js import React from 'react' import {connect} from 'react-redux' import {Link} from 'react-router-dom' import {gotPostsThunk} from '../store/postHx' import SinglePost from './single-post-view' class Responses extends React.Component { componentDidMount() { const userId = this.props.match.params.userId this.props.gotPostsThunk(userId) } render() { const {post} = this.props.post return ( <div> <h2>Your past responses:</h2> <div> {post.map(currentOrder => { return <SinglePost key={currentOrder.id} order={currentOrder} /> })} </div> <Link to={`/new-response/${post.userId}`}>Submit a Response</Link> </div> ) } } const mapState = store => ({ post: store.post }) const mapDispatch = dispatch => ({ gotPostsThunk: arg => dispatch(gotPostsThunk(arg)) }) export default connect(mapState, mapDispatch)(Responses) <file_sep>/client/store/postHx.js import axios from 'axios' /** * ACTION TYPES */ const GET_POSTS = 'GET_POSTS' /** * INITIAL STATE */ const initialState = [] /** * ACTION CREATORS */ const gotPosts = postsArr => ({type: GET_POSTS, postsArr}) /** * THUNK CREATORS */ export const gotPostsThunk = () => async dispatch => { try { const {data} = await axios.get(`/api/posts/`) dispatch(gotPosts(data)) } catch (err) { console.error(err) } } /** * REDUCER */ export default function(state = initialState, action) { switch (action.type) { case GET_POSTS: return action.postsArr default: return state } }
a0b6bd051b4a2ea372c7d1d55d1800386b0145e4
[ "JavaScript" ]
6
JavaScript
w-joy5015/stackathon
c26015928f9b64e6b559d6b871de7e1bed7ab820
5325039b36018e5337197be131ed794853dee6c2
refs/heads/master
<repo_name>Bongkot-Kladklaen/PHP-Basic_Comments<file_sep>/basic_comment.sql CREATE DATABASE db_comment CHARACTER SET utf8 COLLATE utf8_unicode_ci; USE db_comment; CREATE TABLE tbl_comment( id int(11) not null auto_increment PRIMARY KEY, name VARCHAR(50) not null, cimment text not null, comment_itme TIMESTAMP not null default CURRENT_TIMESTAMP on UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT charset=utf8;<file_sep>/index.php <?php include_once 'controller/comment.php'; $com = new Comment(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Comment system oop</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="css/style.css"> </head> <body> <div class="container"> <h3>All comment:</h3> <div class="box"> <ul> <?php if($result = $com->select()){ while ($data=$result->fetch_assoc()) { ?> <li> <b><?php echo $data['name'];?></b> - <?php echo $data['comment'];?> - <?php echo $com->dateFormat($data['comment_time']);?> </li> <?php } } ?> </ul> </div> <br><br> <?php if (isset($_GET['msg'])) { $msg = $_GET['msg']; echo "<span style='color:green; font-size:20px'>".$msg."</span>"; } ?> <form action="post_comment.php" method="post"> <table> <tr> <td>Your name:</td> <td><input type="text" name="name" placeholder="enter name"></td> </tr> <tr> <td>Comment:</td> <td> <textarea name="comment" placeholder="enter comment" cols="30" rows="10"></textarea> </td> </tr> <tr> <td> <input type="submit" name="submit" value="Post"> </td> </tr> </table> </form><br> </div> </body> </html> <file_sep>/controller/comment.php <?php $filepath = realpath(dirname(__FILE__)); include_once $filepath.'../../database/db.php'; class Comment{ private $db; private $name; private $comment; private $table = "tbl_comment"; public function __construct() { $this->db = new DB(); } public function setData($name,$comment) { $this->name = $name; $this->comment = $comment; } public function create() { $query = "INSERT into $this->table(name,comment,comment_time) VALUES('$this->name','$this->comment',now())"; $insert_comment = $this->db->insert($query); return $insert_comment; } public function select() { $query = "SELECT * FROM $this->table ORDER BY id DESC"; $result = $this->db->select($query); return $result; } public function dateFormat($data) { date_default_timezone_set('Asia/Bangkok'); $date = date('M j, h:i:s a',time()); return $date; } } ?>
da5b045e262d003a425d76c0e4736cdd74e764ad
[ "SQL", "PHP" ]
3
SQL
Bongkot-Kladklaen/PHP-Basic_Comments
6681adc7a3fb70e5defe9c28f2ce014e44791a2f
0338e640becc1793c5dfe96d6cc00007d94fe217
refs/heads/master
<repo_name>binlindayu/project1<file_sep>/RunCollatz.cpp #include <iostream> // cin, cout //#include "Collatz.h" // ---------------------------- // projects/collatz/Collatz.c++ // Copyright (C) 2016 // <NAME> // ---------------------------- // -------- // includes // -------- //#include <cassert> // assert using namespace std; #define max_size 10001 long arr[max_size] = { 0 }; // ------------ // collatz_read // ------------ bool collatz_read(istream& r, int& i, int& j) { if (!(r >> i)) return false; r >> j; return true; } // ------------ // collatz_eval // ------------ int circle_length(int i) { int len; if (i < max_size) { if (arr[i] != 0) return arr[i]; } if (i == 1) len = 1; else if (i % 2 == 0) len = circle_length(i >> 1) + 1; else len = circle_length(i * 3 + 1) + 1; if (i < max_size) arr[i] = len; return len; } int collatz_eval(int i, int j) { // <your code> int arr[max_size] = { 0 }; int b1, b2; int count, max; max = 1; if (i <= j) { b1 = i; b2 = j; } else { b1 = i; b2 = j; } for (int n = b1; n <= b2; ++n) { count = circle_length(n); if (max < count) max = count; } return max; } // ------------- // collatz_print // ------------- void collatz_print(ostream& w, int i, int j, int v) { w << i << " " << j << " " << v << endl; } // ------------- // collatz_solve // ------------- void collatz_solve(istream& r, ostream& w) { int i; int j; while (collatz_read(r, i, j)) { const int v = collatz_eval(i, j); collatz_print(w, i, j, v); } } // ---- // main // ---- int main() { using namespace std; collatz_solve(cin, cout); return 0; } /* % g++-4.8 -pedantic -std=c++11 -Wall -fprofile-arcs -ftest-coverage Collatz.c++ RunCollatz.c++ -o RunCollatz % ./RunCollatz < RunCollatz.in > RunCollatz.tmp % diff RunCollatz.tmp RunCollatz.out */
89d1a5e8d182dc3480e0fe966c595c1ffa71c38b
[ "C++" ]
1
C++
binlindayu/project1
7e1e441846854e544207c6c324b9676e3f27c58e
a3f7c9e1f885cbb7a5147871febc8e31c5bee290
refs/heads/master
<file_sep>from recommendations.models import BodyPart, Exercise, Workout from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): """ Serializer for the User model """ class Meta: model = User fields = ['id', 'username', 'email'] class BodyPartSerializer(serializers.ModelSerializer): """ Serializer for the BodyPart model """ class Meta: model = BodyPart fields = ['id', 'name'] class ExerciseSerializer(serializers.ModelSerializer): """ Serializer for the Exercise model """ body_parts = BodyPartSerializer(many=True) class Meta: model = Exercise fields = ['id', 'name', 'body_parts', 'rating'] class WorkoutSerializer(serializers.ModelSerializer): """ Serializer for the Workout model """ user = UserSerializer() exercises = ExerciseSerializer(many=True) class Meta: model = Workout fields = ['id', 'name', 'exercises', 'user', 'day']<file_sep>"""workout_recommendations URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from recommendations.views import BodyPartViewSet, ExerciseRecommendationView, ExerciseViewSet, UserViewSet, CustomAuthToken, WorkoutViewSet from django.contrib import admin from django.urls import path from django.conf.urls import include, url from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'users', UserViewSet) router.register(r'workouts', WorkoutViewSet) router.register(r'exercises', ExerciseViewSet) router.register(r'body-parts', BodyPartViewSet) urlpatterns = [ path('admin/', admin.site.urls), url(r'^user/api-token/$', CustomAuthToken.as_view()), url(r'^workout/(?P<workout_id>[0-9]+)/recommendations/$', ExerciseRecommendationView.as_view()), url(r'^workout/(?P<workout_id>[0-9]+)/$', WorkoutViewSet.as_view({'patch': 'patch'})), url(r'^', include(router.urls)) ] <file_sep># Workout Recommendations ### How to start django This can be started using Docker. First, make sure you have Docker and docker-compose (usually comes with the docker installation for Mac) installed and running. Then run the command ``` docker-compose up ``` This should start the app running on port 8000 on your computer and start neo4j running on port 7474. To stop it running just type Ctrl+C in the terminal you started it in and type ``` docker-compose down ``` To remove all the docker images just type ``` docker rmi $(docker images -a -q) ``` ### Updating the database after creating a new Model or updating one Updates in django are done through things called migrations. These can do bulk updates on data in a database or perform CRUD operations on tables in a database. To update the database, you will have to first execute into the docker container. First do: ``` docker ps ``` This will list all the running docker containers. Copy the container ID of the container with image name some thing like `workout_recommendations_web`. Then run: ``` docker exec -ti <copied container ID> bash ``` This lets you go into the docker container and run commands in it. Now to run the migrations run the following commands: ``` python manage.py makemigrations python manage.py migrate ``` Your database should now be updated. ### Exposing a local port To expose a local port you will need ngrok installed. You can install ngrok using homebrew with the command: ``` brew install --cask ngrok ``` After this you can just expose a port using the command: ``` ngrok http <port to expose> ``` This redirects all requests to a public url (this should be shown on terminal) to your port. <file_sep># Generated by Django 3.2.4 on 2021-06-21 21:48 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='BodyPart', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=100)), ], ), migrations.CreateModel( name='Exercise', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=100)), ('rating', models.DecimalField(decimal_places=2, default=0, max_digits=3)), ('body_parts', models.ManyToManyField(to='recommendations.BodyPart')), ], ), migrations.CreateModel( name='Workout', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=100)), ('day', models.DateField(blank=True, default=django.utils.timezone.now)), ('exercises', models.ManyToManyField(to='recommendations.Exercise')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)), ], ), ] <file_sep>from recommendations.models import BodyPart, Exercise, Workout from recommendations.utils import Neo4jUtils from recommendations.serializers import BodyPartSerializer, ExerciseSerializer, UserSerializer, WorkoutSerializer from django.contrib.auth.models import User from django.db import transaction from rest_framework import viewsets, status from rest_framework.authtoken.models import Token from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView neo4j = Neo4jUtils() class UserViewSet(viewsets.ViewSet): """ Provides create and list actions for the User model """ queryset = User.objects.all() serializer_class = UserSerializer def list(self, request): """ Get all available Users """ return Response( self.serializer_class( self.queryset, context={'request' : request}, many=True).data, status=status.HTTP_200_OK) def create(self, request): """ Creates a new User """ username = request.data.get("username", None) first_name = request.data.get("first_name", "") last_name = request.data.get("last_name", "") password = request.data.get("password", None) email = request.data.get("email", None) if not (username and email and password): return Response({ "message": "Must include username, password and email in request" }, status=status.HTTP_400_BAD_REQUEST) with transaction.atomic(): user = User.objects.create( username=username, email=email, first_name=first_name, last_name = last_name, ) user.set_password(password) user.save() neo4j.run(f"CREATE (u:User{{username:\"{user.username}\", id:{user.id}}})") return Response( self.serializer_class(user, context={'request': request}).data, status=status.HTTP_201_CREATED ) class CustomAuthToken(ObtainAuthToken): """ Custom Token creation view """ def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, _ = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email }) class BodyPartViewSet(viewsets.ViewSet): """ Provides create and list actions for the BodyPart model """ queryset = BodyPart.objects.all() serializer_class = BodyPartSerializer permission_classes = [IsAuthenticated] def list(self, request): """ Get all available BodyParts """ return Response( self.serializer_class( self.queryset, context={'request' : request}, many=True).data, status=status.HTTP_200_OK) def create(self, request): """ Creates a new Exercise """ name = request.data.get("name", None) if not name: return Response({ "message": "Must include name in request" }, status=status.HTTP_400_BAD_REQUEST) body_part = BodyPart.objects.create(name=name) return Response( self.serializer_class(body_part, context={'request': request}).data, status=status.HTTP_201_CREATED ) class ExerciseViewSet(viewsets.ViewSet): """ Provides create and list actions for the Exercise model """ queryset = Exercise.objects.all() serializer_class = ExerciseSerializer permission_classes = [IsAuthenticated] def list(self, request): """ Get all available Exercises """ return Response( self.serializer_class( self.queryset, context={'request' : request}, many=True).data, status=status.HTTP_200_OK) def create(self, request): """ Creates a new Exercise """ name = request.data.get("name", None) body_parts = request.data.get("body_parts", []) rating = request.data.get("rating", 0.0) if not name or len(body_parts) < 1: return Response({ "message": "Must include name and at least 1 body part in request" }, status=status.HTTP_400_BAD_REQUEST) with transaction.atomic(): exercise = Exercise.objects.create(name=name, rating=rating) neo4j.run(f"CREATE (e:Exercise{{id: {exercise.id},name: \"{exercise.name}\", rating: {exercise.rating}}})") existing_body_parts = BodyPart.objects.filter(name__in=body_parts) non_existing_body_parts = set(body_parts).difference(set(existing_body_parts.values_list("name", flat=True))) for name in non_existing_body_parts: BodyPart.objects.create(name=name) exercise.body_parts.add(*BodyPart.objects.filter(name__in=body_parts)) exercise.save() return Response( self.serializer_class(exercise, context={'request': request}).data, status=status.HTTP_201_CREATED ) class WorkoutViewSet(viewsets.ViewSet): """ Provides create, list and patch actions for the Workout model """ queryset = Workout.objects.all() serializer_class = WorkoutSerializer permission_classes = [IsAuthenticated] def list(self, request): """ Get all available Workouts the user has done """ return Response( self.serializer_class( self.queryset.filter(user=request.user), context={'request' : request}, many=True).data, status=status.HTTP_200_OK) def create(self, request): """ Creates a new Workout """ user = request.user name = request.data.get("name", None) if not name: return Response({ "message": "Must include name in request" }, status=status.HTTP_400_BAD_REQUEST) workout = Workout.objects.create(name=name, user=user) return Response( self.serializer_class(workout, context={'request': request}).data, status=status.HTTP_201_CREATED ) def patch(self, request, workout_id): """ Add an Exercises to a workout """ workout = Workout.objects.get(id=workout_id) if workout.user.id != request.user.id: return Response( {"message": "You do not have access to the Workout"}, status=status.HTTP_401_UNAUTHORIZED ) add_exercises = request.data.get("add", {"exercises": []}).get("exercises", []) with transaction.atomic(): with neo4j.session() as session: for exercise in Exercise.objects.filter(name__in=add_exercises).exclude(id__in=workout.exercises.all()): session.run(f""" MATCH (e:Exercise)-[rel:{Exercise.EXERCISE_RELATIONSHIP}]->(:Exercise{{id: {exercise.id}}}) WHERE e.id IN [{','.join(map(lambda i: str(i), workout.exercises.all().values_list('id', flat=True)))}] SET rel.times = rel.times + 1 """) session.run(f""" MATCH (e:Exercise)<-[rel:{Exercise.EXERCISE_RELATIONSHIP}]-(:Exercise{{id: {exercise.id}}}) WHERE e.id IN [{','.join(map(lambda i: str(i), workout.exercises.all().values_list('id', flat=True)))}] SET rel.times = rel.times + 1 """) session.run(f""" MATCH (e1:Exercise) MATCH (e2:Exercise{{id: {exercise.id}}}) WHERE e1.id IN [{','.join(map(lambda i: str(i), workout.exercises.all().values_list('id', flat=True)))}] AND NOT (e1)-[:{Exercise.EXERCISE_RELATIONSHIP}]-(e2) CREATE (e1)-[rel:{Exercise.EXERCISE_RELATIONSHIP}{{times:1}}]->(e2) CREATE (e1)<-[rel2:{Exercise.EXERCISE_RELATIONSHIP}{{times:1}}]-(e2) """) session.run(f""" MATCH (:User)-[rel:{Exercise.USER_RELATIONSHIP}]->(:Exercise{{id: {exercise.id}}}) SET rel.times = rel.times + 1 """) session.run(f""" MATCH (u:User) MATCH (e:Exercise{{id: {exercise.id}}}) WHERE NOT (u)-[:{Exercise.USER_RELATIONSHIP}]-(e) CREATE (u)-[rel:{Exercise.USER_RELATIONSHIP}{{times:1}}]->(e) """) workout.exercises.add(exercise) workout.save() return Response( self.serializer_class(workout, context={'request': request}).data, status=status.HTTP_200_OK ) class ExerciseRecommendationView(APIView): """ View to get exercise recommendations based on an ongoing workout """ permission_classes = [IsAuthenticated] serializer_class = ExerciseSerializer TIMES_WEIGHT = 0.7 RATING_WEIGHT = 0.3 def get(self, request, workout_id): """ Gets recommendations for exercises in a workout """ workout = Workout.objects.get(id=workout_id) if workout.user != request.user: return Response( {"message": "You do not have access to the Workout"}, status=status.HTTP_401_UNAUTHORIZED ) with neo4j.session() as session: result = session.run(f""" MATCH (e:Exercise)-[rel]->(e2:Exercise) WHERE e.id IN [{','.join(map(lambda i: str(i), workout.exercises.all().values_list('id', flat=True)))}] AND NOT e2.id IN [{','.join(map(lambda i: str(i), workout.exercises.all().values_list('id', flat=True)))}] WITH e2, rel, sum(rel.times) as total_relationships ORDER BY (0.7 * rel.times/total_relationships) + (0.3 * e2.rating/5) DESC RETURN collect(DISTINCT e2.id)""") exercises = [Exercise.objects.get(id=i) for i in result.value()[0]] return Response( self.serializer_class(exercises, context={'request': request}, many=True).data, status=status.HTTP_200_OK ) <file_sep>Django>=3.0,<4.0 psycopg2-binary>=2.8 neo4j djangorestframework django-filter bs4<file_sep>from django.conf import settings from django.utils.timezone import now from neo4j import GraphDatabase import urllib.request from bs4 import BeautifulSoup import csv class Neo4jUtils: """ Utils class to interact with neo4j """ def __init__( self, uri=settings.NEO4J_URI, username=settings.NEO4J_USERNAME, password=<PASSWORD>.<PASSWORD> ): self._driver = GraphDatabase.driver(uri, auth=(username, password), encrypted=False) @property def connection(self): return self._driver def close(self): self.connection.close() def session(self): return self.connection.session() def run(self, query): with self.session() as session: return session.run(query) def date_now(): """ Return the Date object of now """ return now().date() # read all exercises from the given webpage content class WorkoutPlan: #default constructor def __init__(self): self.name = "" self.headers = [] self.exercises = [] # reads the workout plan def read_workout_plan(self, html): #read workout plan name key = "<h4>" start_index = html.find(key) if start_index == -1: return None #read workout plan name end_index = html.find("</h4>", start_index) self.name = html[start_index+len(key):end_index] self.name = self.name.strip(" ,\n\r") # read exercises table data now soup = BeautifulSoup(html[end_index+len(key)+1:], 'lxml') table_data = soup.find("table") # headers - "Exercise","Sets","Reps","Name" for i in table_data.find_all('th'): title = i.text.strip() self.headers.append(title) self.headers.append("Name") # exercises - for j in table_data.find_all('tr'): row_data = j.find_all('td') row = [tr.text.strip() for tr in row_data] row.append(self.name) if len(row) == 0 or len(row) == 1: continue else: self.exercises.append(row) return self # read all workout plans from the given webpage url class WorkoutPlanBook: #default constructor def __init__(self): self.plans = [] def read_all_workout_plans(self, url): print("Scraping website: " + url) request = urllib.request.Request(url) request.add_header("User-Agent", "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11") #read the data from the URL and print it page = urllib.request.urlopen(request) html = page.read().decode("utf-8") #read all workout plans while True: #All exercises content start at HTML tag <h4>, <h4 Day>, or <h4 Monday> and #end until the last table HTML tag </table> start_index = html.find("<h4>") if start_index == -1: break end_index = html.find("</table>", start_index) if end_index == -1: break end_index += len("</table>") #get the exercises content - END #create a new workout plan with all exercises workout_plan = WorkoutPlan() exercises_section = html[start_index:end_index] workout_plan.read_workout_plan(exercises_section) self.plans.append(workout_plan) #print(workout_plan.headers) print(workout_plan.exercises) # reset the html page content for the next iteration html = html[end_index:] return self # main program def scrape_workout_plans(): # list of workout URLs to scrape urls = [ "https://www.muscleandstrength.com/workouts/limited-equipment-home-workout", "https://www.muscleandstrength.com/workouts/phul-workout", "https://www.muscleandstrength.com/workouts/6-day-dumbbell-only-workout", "https://www.muscleandstrength.com/workouts/dumbbell-only-upper-lower-workout-routine", "https://www.muscleandstrength.com/workouts/upper-lower-4-day-gym-bodybuilding-workout", "https://www.muscleandstrength.com/workouts/m-f-workout-routine", "https://www.muscleandstrength.com/workouts/4-day-maximum-mass-workout", "https://www.muscleandstrength.com/workouts/4-day-power-muscle-burn-workout-split.html", "https://www.muscleandstrength.com/workouts/6-week-workout-program-to-build-lean-muscle", "https://www.muscleandstrength.com/workouts/muscle-mania-10-week-muscle-growth-workout", "https://www.muscleandstrength.com/workouts/5-day-muscle-and-strength-building-workout-split", "https://www.muscleandstrength.com/workouts/dumbbell-only-home-or-gym-fullbody-workout.html", "https://www.muscleandstrength.com/workouts/michael-b-jordan-workout-program", "https://www.muscleandstrength.com/workouts/thor-ragnarok-chris-hemsworth-inspired-workout", "https://www.muscleandstrength.com/workouts/power-muscle-burn-5-day-powerbuilding-split.html", "https://www.muscleandstrength.com/workouts/10-week-mass-building-program.html", "https://www.muscleandstrength.com/workouts/muscle-and-strength-womens-workout", "https://www.muscleandstrength.com/workouts/muscle-and-strength-womens-fat-loss-workout", "https://www.muscleandstrength.com/workouts/best-full-body-workout-routine-for-women", "https://www.muscleandstrength.com/workouts/12-week-push-pull-legs-for-women", "https://www.muscleandstrength.com/workouts/10-week-upper-lower-workout-for-women", "https://www.muscleandstrength.com/workouts/8-week-full-body-womens-workout-routine", "https://www.muscleandstrength.com/workouts/12-week-womens-bikini-prep-workout", "https://www.muscleandstrength.com/workouts/abs-workout-women-8-weeks-flatter-stomach", "https://www.muscleandstrength.com/workouts/the-super-toning-training-routine.html", "https://www.muscleandstrength.com/workouts/8-week-beginner-workout-for-women", "https://www.muscleandstrength.com/workouts/the-butt-builder.html", "https://www.muscleandstrength.com/workouts/5-day-workout-routine-for-women" ] # create a workout_plans.csv file with the header "Exercise","Sets","Reps","Name" csvfile = open("workout_plans.csv", "w") csvwriter = csv.writer(csvfile) csvwriter.writerow(["Exercise","Sets","Reps", "Name"]) index = 0 while index < len(urls): planBook = WorkoutPlanBook() planBook.read_all_workout_plans(urls[index]) index += 1 # write scraped workout plans to the csv file for plan in planBook.plans: csvwriter.writerows(plan.exercises) print("---END---")<file_sep># Generated by Django 3.2.4 on 2021-06-22 12:00 from django.db import migrations, models import recommendations.utils class Migration(migrations.Migration): dependencies = [ ('recommendations', '0001_initial'), ] operations = [ migrations.AlterField( model_name='workout', name='day', field=models.DateField(blank=True, default=recommendations.utils.date_now), ), ] <file_sep>from django.db import models from django.contrib.auth.models import User from recommendations.utils import date_now class BodyPart(models.Model): """ Represents a human body part """ name = models.CharField(max_length=100, blank=True) class Exercise(models.Model): """ Represents an Exercise """ EXERCISE_RELATIONSHIP = "IS_DONE_WITH" USER_RELATIONSHIP = "HAS_DONE" name = models.CharField(max_length=100, blank=True) body_parts = models.ManyToManyField(BodyPart) rating = models.DecimalField(max_digits=3, decimal_places=2, default=0.0) class Workout(models.Model): """ Represents a Workout that contains multiple Exercises """ name = models.CharField(max_length=100, blank=True) user = models.ForeignKey(User, on_delete=models.DO_NOTHING) exercises = models.ManyToManyField(Exercise) day = models.DateField(default=date_now, blank=True)<file_sep>from django.contrib import admin from .models import Exercise, Workout admin.site.register([Exercise, Workout])
5a9c94c97887fc3332efb75c1b60054200aed32c
[ "Markdown", "Python", "Text" ]
10
Python
joshtummala/workout_recommendations
8edc6d8e5c68dc3986df2c38277d7c8ed76dedf6
7630fd056a9a12e263db60fe9789baf2076052c7
refs/heads/master
<file_sep># IndustryJump Design to HTML, CSS/LESS, Bootstrap4 <file_sep>function postModal() { const modalElm = document.querySelector('.ij-post-modal') const closeBtn = modalElm.querySelector('.ij-post-modal__close') const cancelBtn = modalElm.querySelector('.post-project__btn--cancel') const backBtn = modalElm.querySelector('.post-project__btn--back') const proceedBtn = modalElm.querySelector('.post-project__btn--proceed') const postBtn = modalElm.querySelector('.post-project__btn--post-project') const backdrop = modalElm.querySelector('.ij-post-modal__backdrop') const navItems = modalElm.querySelectorAll('.post-project__nav-item') const postForms = modalElm.querySelectorAll('.post-project__form') const openBtns = document.querySelectorAll('.post-project-btn') function open(event) { event.preventDefault() modalElm.classList.add('is-active') proceedBtn.disabled = false } function close(event) { event.preventDefault() modalElm.classList.remove('is-active') proceedBtn.disabled = true } openBtns.forEach(openBtn => { openBtn.addEventListener('click', (e) => open(e)) }) closeBtn.addEventListener('click', (e) => close(e)) cancelBtn.addEventListener('click', (e) => close(e)) backdrop.addEventListener('click', (e) => close(e)) let formIndex = 0 let isInputEmpty = false function valideForm() { const selectedForm = postForms[formIndex] const inputs = selectedForm.querySelectorAll('.post-project__form-input') const formGroups = selectedForm.querySelectorAll('.post-project__form-group') let h = [] inputs.forEach((input, i) => { if (input.value.length > 0) { h.push(true) } else { h.push(false) const div = document.createElement('div') div.classList.add('post-project__form-erroText') div.innerHTML = 'Please fill out the form above to proceed' formGroups[i].classList.add('post-project__form-group--error') formGroups[i].appendChild(div) proceedBtn.disabled = true input.addEventListener('blur', (e) => { if (e.target.value.length > 0 && formGroups[i].childElementCount > 2) { formGroups[i].classList.remove('post-project__form-group--error') formGroups[i].removeChild(div) proceedBtn.disabled = false isInputEmpty = true } }) creativeTags.forEach(tag => { tag.addEventListener('click', (e) => { if(formGroups[i].childElementCount > 2) formGroups[i].classList.remove('post-project__form-group--error') formGroups[i].removeChild(div) proceedBtn.disabled = false }) }) } }) isInputEmpty = h.every(Boolean) } function nextForm() { valideForm() if (formIndex == (postForms.length - 1) || isInputEmpty == false) return formIndex += 1 formSlide(formIndex) navItems[formIndex].classList.add('is-active') btnCntrols(formIndex) } function prevForm() { if (formIndex == 0) return navItems[formIndex].classList.remove('is-active') formIndex -= 1 formSlide(formIndex) btnCntrols(formIndex) valideForm() proceedBtn.disabled = false } function formSlide(index) { postForms.forEach(postForm => postForm.classList.remove('is-active')) postForms[index].classList.add('is-active') } function btnCntrols(index) { if (index > 0) { cancelBtn.classList.remove('is-active') backBtn.classList.add('is-active') } else { cancelBtn.classList.add('is-active') backBtn.classList.remove('is-active') } if (formIndex == (postForms.length - 1)) { proceedBtn.classList.remove('is-active') postBtn.classList.add('is-active') isInputEmpty = false } else { proceedBtn.classList.add('is-active') postBtn.classList.remove('is-active') } } function emailIsValid(email) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) } const div = document.createElement('div') div.classList.add('post-project__form-erroText') div.innerHTML = 'Please fill out the correct Email' const inputEmail = document.querySelector('.post-project__form-input--email') if(inputEmail) { inputEmail.addEventListener('blur', (e) => { if (!emailIsValid(e.target.value)) { e.target.parentNode.classList.add('post-project__form-group--error') e.target.parentNode.appendChild(div) isInputEmpty = false postBtn.disabled = true } else { isInputEmpty = true postBtn.disabled = false } }) inputEmail.addEventListener('focus', (e) => { if (e.target.parentNode.childNodes.length > 5) { e.target.parentNode.classList.remove('post-project__form-group--error') e.target.parentNode.removeChild(div) } }) } proceedBtn.addEventListener('click', () => nextForm()) backBtn.addEventListener('click', () => prevForm()) postBtn.addEventListener('click', (e) => { valideForm() if (isInputEmpty == false) return close(e) postForms.forEach(postForm => postForm.classList.remove('is-active')) navItems.forEach(postForm => postForm.classList.remove('is-active')) postForms[0].classList.add('is-active') navItems[0].classList.add('is-active') formIndex = 0 cancelBtn.classList.add('is-active') backBtn.classList.remove('is-active') proceedBtn.classList.add('is-active') postBtn.classList.remove('is-active') const inputs = document.querySelectorAll('.post-project__form-input') inputs.forEach(input => input.value = '') }) const creativeInput = document.querySelector('.post-project__form--creative .post-project__form-input') const creativeTags = document.querySelectorAll('.post-project__form--creative .post-project__tag') creativeTags.forEach(tag => { tag.addEventListener('click', () => { creativeInput.value = tag.innerText }) }) } postModal()<file_sep>window.onload = function () { // navbar const pageHeader = document.querySelector(".page-header") const toggler = document.querySelector(".mobile-menu-toggle") const openClassName = "page-header__mobile__open" toggler.addEventListener('click', () => { pageHeader.classList.forEach(cls => { if (cls.indexOf(openClassName) !== -1) { pageHeader.classList.remove(openClassName) } else { pageHeader.classList.add(openClassName) } }) }) // slider const heroSlider = new Swiper('.block-hero__slider', { slidesPerView: 'auto', spaceBetween: 95, wrapperClass: 'block-hero__slider-row', slideClass: 'block-hero__slider-item', slideActiveClass: 'block-hero__slider-item--active', loop: true, loopFillGroupWithBlank: true, pagination: { el: '.block-hero__slider-pagination', clickable: true, }, }) const wantSlider = new Swiper('.block-want-work__slider', { slidesPerView: 1, wrapperClass: 'block-want-work__slider-row', slideClass: 'block-want-work__slider-item', slideActiveClass: 'block-want-work__slider-item--active', centeredSlides: true, direction: 'vertical', loop: true, loopFillGroupWithBlank: true, autoplay: { delay: 2500, disableOnInteraction: false, }, }) // video player const playBtns = document.querySelectorAll('.video-play-btn') const closeBtn = document.querySelector('.video-player-modal__close') const videContainer = document.querySelector('.video-player-modal__container') const videoModalElm = document.querySelector('.video-player-modal') function openVideoModal(src) { const iframe = document.createElement('iframe') iframe.src = src videoModalElm.classList.add('is-active') videContainer.appendChild(iframe) } function closeVideoModal() { videoModalElm.classList.remove('is-active') videContainer.innerHTML = '' } playBtns.forEach(playBtn => { playBtn.addEventListener('click', () => { openVideoModal(playBtn.dataset.src) }) }) closeBtn.addEventListener('click', () => { closeVideoModal() }) // select const selectElms = document.querySelectorAll('.search-matching__select') selectElms.forEach(selectElm => { const openBtn = selectElm.querySelector('.search-matching__select-main') const selectedText = selectElm.querySelector('.search-matching__select-text') const options = selectElm.querySelectorAll('.search-matching__select-option') openBtn.addEventListener('click', () => { selectElm.classList.add('is-active') }) options.forEach(option => { option.addEventListener('click', () => { selectElm.classList.remove('is-active') selectedText.dataset.value = option.dataset.value selectedText.innerHTML = option.innerText }) }) selectElm.addEventListener('mouseleave', () => { selectElm.classList.remove('is-active') }) }) // music items const mItems = document.querySelectorAll('.music-item') mItems.forEach(mItem => { mItem.addEventListener('click', () => { mItems.forEach(r => r.classList.remove('is-active')) mItem.classList.add('is-active') }) }) }
984dedda19fc2440999c06bac61537f94f1e8614
[ "Markdown", "JavaScript" ]
3
Markdown
saddamcrr7/industry-jump
d35d7df33659f77d6b9dae9cafa2bff2c3b62796
abe4b59d0d42ba29839278122138d6d9862aadfe
refs/heads/master
<file_sep>#include <Servo.h> #include <SoftwareSerial.h> #include <Adafruit_NeoPixel.h> #ifdef __AVR__ #include <avr/power.h> #endif #define PIN 12 #define NUMPIXELS 16 Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); int delayval = 500; const int pResistor = A0; int sensorValue; Servo myservo1; Servo myservo2; Servo myservo3; Servo myservo4; Servo myservo5; Servo myservo6; Servo myservo7; Servo myservo8; String commandArray[30]; int count = 0; SoftwareSerial wifiSerial(0, 1); // RX, TX for ESP8266 bool DEBUG = true; //show more logs int responseTime = 10; //communication timeout void getUp(){ myservo1.attach(8); myservo2.attach(9); myservo3.attach(2); myservo4.attach(3); myservo5.attach(4); myservo6.attach(5); myservo7.attach(6); myservo8.attach(7); myservo1.write(10); myservo2.write(170); myservo3.write(170); myservo4.write(10); myservo5.write(45); myservo6.write(45); myservo7.write(135); myservo8.write(45); delay(1000); } void addCommand(String command){ if(count<30){ commandArray[count++] = command; } } String getCommand(){ String cmd = ""; if(count>0){ cmd = commandArray[--count]; } return cmd; } void duck(){ myservo1.write(60); myservo2.write(170); myservo3.write(110); myservo4.write(10); myservo5.write(45); myservo6.write(45); myservo7.write(135); myservo8.write(45); delay(500); } void wave(){ duck(); myservo2.write(10); delay(500); myservo6.write(45); delay(300); myservo6.write(135); delay(300); myservo6.write(45); delay(300); myservo6.write(135); delay(300); myservo6.write(45); delay(300); myservo2.write(170); delay(5000); } void getDown(){ myservo1.write(60); myservo2.write(120); myservo3.write(120); myservo4.write(60); myservo5.write(45); myservo6.write(45); myservo7.write(135); myservo8.write(45); delay(1500); getUp(); } void moveForward(){ delay(1000); liftLeg(8); delay(100); moveLeg(4, "FORWARD"); delay(100); lowerLeg(8); delay(100); liftLeg(9); delay(100); moveLeg(5, "FORWARD"); delay(100); lowerLeg(9); delay(100); liftLeg(3); delay(100); moveLeg(7, "BACK"); delay(100); lowerLeg(3); delay(100); liftLeg(2); delay(100); moveLeg(6, "FORWARD"); delay(100); lowerLeg(2); delay(300); moveLeg(4, "BACK"); moveLeg(7, "FORWARD"); moveLeg(5, "BACK"); moveLeg(6, "BACK"); delay(500); } void moveBackwords(){ delay(1000); liftLeg(8); delay(100); moveLeg(4, "BACK"); delay(100); lowerLeg(8); delay(100); liftLeg(9); delay(100); moveLeg(5, "BACK"); delay(100); lowerLeg(9); delay(100); liftLeg(3); delay(100); moveLeg(7, "FORWARD"); delay(100); lowerLeg(3); delay(100); liftLeg(2); delay(100); moveLeg(6, "BACK"); delay(100); lowerLeg(2); delay(300); moveLeg(4, "FORWARD"); moveLeg(7, "BACK"); moveLeg(5, "FORWARD"); moveLeg(6, "FORWARD"); delay(500); } void moveLeft(){ delay(1000); liftLeg(8); delay(100); moveLeg(4, "FORWARD"); delay(100); lowerLeg(8); delay(100); liftLeg(9); delay(100); moveLeg(5, "FORWARD"); delay(100); lowerLeg(9); delay(100); liftLeg(3); delay(100); moveLeg(7, "FORWARD"); delay(100); lowerLeg(3); delay(100); liftLeg(2); delay(100); moveLeg(6, "BACK"); delay(100); lowerLeg(2); delay(300); moveLeg(4, "BACK"); moveLeg(7, "BACK"); moveLeg(5, "BACK"); moveLeg(6, "FORWARD"); delay(500); } void moveRight(){ delay(1000); liftLeg(8); delay(100); moveLeg(4, "BACK"); delay(100); lowerLeg(8); delay(100); liftLeg(9); delay(100); moveLeg(5, "BACK"); delay(100); lowerLeg(9); delay(100); liftLeg(3); delay(100); moveLeg(7, "BACK"); delay(100); lowerLeg(3); delay(100); liftLeg(2); delay(100); moveLeg(6, "FORWARD"); delay(100); lowerLeg(2); delay(300); moveLeg(4, "FORWARD"); moveLeg(7, "FORWARD"); moveLeg(5, "FORWARD"); moveLeg(6, "BACK"); delay(500); } void liftLeg(int pin){ switch(pin){ case 8: myservo1.write(45); break; case 9: myservo2.write(135); break; case 2: myservo3.write(135); break; case 3: myservo4.write(45); break; } } void lowerLeg(int pin){ if(pin == 8){ myservo1.write(10); }else if(pin == 3) { myservo4.write(10); }else if(pin ==9){ myservo2.write(170); }else if(pin == 2){ myservo3.write(170); } } void moveLeg(int pin, String direction){ if(direction == "FORWARD"){ switch(pin){ case 2: myservo3.write(90);break; case 3: myservo4.write(90);break; case 4: myservo5.write(90);break; case 5: myservo6.write(90);break; case 6: myservo7.write(45);break; case 7: myservo8.write(90);break; case 8: myservo1.write(90);break; case 9: myservo2.write(90);break; } }else if(direction == "BACK"){ if(pin == 6){ myservo7.write(180); } else { switch(pin){ case 2: myservo3.write(0);break; case 3: myservo4.write(45);break; case 4: myservo5.write(0);break; case 5: myservo6.write(0);break; case 7: myservo8.write(0);break; case 8: myservo1.write(45);break; case 9: myservo2.write(45);break; } } } } void returnToStart(){ for (int i = 0; i < sizeof(commandArray); i++){ String command = String(getCommand()); if(command){ if(command.equals("LEFT")){ moveRight(); } else if(command.equals("RIGHT")){ moveLeft(); } else if(command.equals("FORWARD")){ moveBackwords(); } else if(command.equals("BACK")){ moveForward(); } else if(command.equals("WAVE")){ wave(); } else if(command.equals("DUCK")){ duck(); } } } } void ledOn(){ for(int i=0;i<NUMPIXELS;i++){ pixels.setPixelColor(i, pixels.Color(255,255,255)); pixels.show(); delay(delayval); } } void ledOff(){ for(int i=0;i<NUMPIXELS;i++){ pixels.setPixelColor(i, pixels.Color(0,0,0)); pixels.show(); delay(delayval); } } /* * Name: sendData * Description: Function used to send string to tcp client using cipsend * Params: * Returns: void */ void sendData(String str){ String len=""; len+=str.length(); sendToWifi("AT+CIPSEND=0,"+len,responseTime,DEBUG); delay(100); sendToWifi(str,responseTime,DEBUG); delay(100); sendToWifi("AT+CIPCLOSE=5",responseTime,DEBUG); sendToUno(str, responseTime, DEBUG); } /* * Name: find * Description: Function used to match two string * Params: * Returns: true if match else false */ boolean find(String string, String value){ if(string.indexOf(value)>=0) return true; return false; } /* * Name: readSerialMessage * Description: Function used to read data from Arduino Serial. * Params: * Returns: The response from the Arduino (if there is a reponse) */ String readSerialMessage(){ char value[100]; int index_count =0; while(Serial.available()>0){ value[index_count]=Serial.read(); index_count++; value[index_count] = '\0'; // Null terminate the string } String str(value); str.trim(); return str; } /* * Name: readWifiSerialMessage * Description: Function used to read data from ESP8266 Serial. * Params: * Returns: The response from the esp8266 (if there is a reponse) */ String readWifiSerialMessage(){ char value[100]; int index_count =0; while(wifiSerial.available()>0){ value[index_count]=wifiSerial.read(); index_count++; value[index_count] = '\0'; // Null terminate the string } String str(value); str.trim(); return str; } /* * Name: sendToWifi * Description: Function used to send data to ESP8266. * Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no) * Returns: The response from the esp8266 (if there is a reponse) */ String sendToWifi(String command, const int timeout, boolean debug){ String response = ""; wifiSerial.println(command); // send the read character to the esp8266 long int time = millis(); while( (time+timeout) > millis()) { while(wifiSerial.available()) { // The esp has data so display its output to the serial window char c = wifiSerial.read(); // read the next character. response+=c; } } if(debug) { Serial.println(response); } return response; } /* * Name: sendToWifi * Description: Function used to send data to ESP8266. * Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no) * Returns: The response from the esp8266 (if there is a reponse) */ String sendToUno(String command, const int timeout, boolean debug){ String response = ""; Serial.println(command); // send the read character to the esp8266 long int time = millis(); while( (time+timeout) > millis()) { while(Serial.available()) { // The esp has data so display its output to the serial window char c = Serial.read(); // read the next character. response+=c; } } if(debug) { Serial.println(response); } return response; } void setup() { pinMode(pResistor, INPUT); #if defined (__AVR_ATtiny85__) if (F_CPU == 16000000) clock_prescale_set(clock_div_1); #endif pixels.begin(); getUp(); delay(2000); // Open serial communications and wait for port to open esp8266: Serial.begin(115200); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } wifiSerial.begin(115200); while (!wifiSerial) { ; // wait for serial port to connect. Needed for Leonardo only } sendToWifi("AT+CWMODE=2",responseTime,DEBUG); // configure as access point sendToWifi("AT+CIFSR",responseTime,DEBUG); // get ip address sendToWifi("AT+CIPMUX=1",responseTime,DEBUG); // configure for multiple connections sendToWifi("AT+CIPSERVER=1,80",responseTime,DEBUG); // turn on server on port 80 sendToUno("Wifi connection is running!",responseTime,DEBUG); } void loop() { sensorValue = analogRead(pResistor); if (sensorValue > 250){ ledOff(); } else{ ledOn(); } if(Serial.available()>0){ String message = readSerialMessage(); if(find(message,"debugEsp8266:")){ String result = sendToWifi(message.substring(13,message.length()),responseTime,DEBUG); if(find(result,"OK")) sendData("\nOK"); else sendData("\nEr"); } } if(wifiSerial.available()>0){ String message = readWifiSerialMessage(); if(find(message,"esp8266:")){ String result = sendToWifi(message.substring(8,message.length()),responseTime,DEBUG); if(find(result,"OK")) sendData("\n"+result); else sendData("\nErrRead"); //At command ERROR CODE for Failed Executing statement }else if(find(message,"LEFT")){ //receives LEFT from wifi addCommand("LEFT"); moveLeft(); //Robot moves LEFT }else if(find(message,"RIGHT")){ addCommand("RIGHT"); moveRight(); }else if(find(message,"FORWARD")){ addCommand("FORWARD"); moveForward(); }else if(find(message,"BACK")){ addCommand("BACK"); moveBackwords(); }else if(find(message,"WAVE")){ addCommand("WAVE"); wave(); }else if(find(message,"DUCK")){ addCommand("DUCK"); duck(); }else if(find(message,"LEDOFF")){ ledOff(); }else if(find(message,"LEDON")){ ledOn(); }else if(find(message,"6")){ returnToStart(); }else{ sendData("\nErrRead"); //Command ERROR CODE for UNABLE TO READ } } delay(responseTime); }
3d84e61d610700cbd4156f924dbca7ab8d1063de
[ "C++" ]
1
C++
ventsy95/Robot.ino
517affaea28f302c696119305bc095ab8a447599
f29703b47cbcc1f9ebc3aafe1a5ebef93b259bea
refs/heads/master
<file_sep>package com.alibaba.simpleimage.analyze.testbed; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import javax.imageio.ImageIO; import com.alibaba.simpleimage.analyze.harissurf.IntegralImage; import com.alibaba.simpleimage.analyze.harris.Corner; import com.alibaba.simpleimage.analyze.harris.HarrisFast; public class HarrisTest { public static void main(String[] args) throws IOException { BufferedImage img = null; // BufferedImage img_output = null; // FileReader in = null; // FileWriter out = null; HarrisFast hf = null; // String filepath = "D:/aliDrive/test_image/phishing_test/template/"; String filepath = "D:/AliDrive/test_image/phishing_test/target/"; // String filename = "alipay_logo1.png"; String filename = "alipay_2.png"; // String filename = "icbu_logo1.png"; int i, j; img = ImageIO.read(new File(filepath + filename)); int width = img.getWidth(); int height = img.getHeight(); int[][] input = new int[width][height]; for (i = 0; i < width - 1; i++) { for (j = 0; j < height - 1; j++) { input[i][j] = rgb2gray(img.getRGB(i, j)); } } double sigma = 1.2; double k = 0.06; int spacing = 4; IntegralImage mIntegralImage = new IntegralImage(img); hf = new HarrisFast(input, width, height, mIntegralImage); hf.filter(sigma, k, spacing); Graphics2D g2d = img.createGraphics(); g2d.setColor(Color.GREEN); for (Corner corner : hf.corners) { g2d.fill(new Rectangle2D.Float(corner.getX() - 1, corner.getY() - 1, 2, 2)); } g2d.dispose(); FileOutputStream fos; try { fos = new FileOutputStream(filepath + "out_" + filename); ImageIO.write(img, "png", fos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } static int rgb2gray(int srgb) { int r = (srgb >> 16) & 0xFF; int g = (srgb >> 8) & 0xFF; int b = srgb & 0xFF; return (int) (0.299 * r + 0.587 * g + 0.114 * b); } }
53c6cbf64ee9abd2582390beb4c2b8e04363a52d
[ "Java" ]
1
Java
yizhl/simpleimage
08e515238f0b82d88db4dbb7dc41d8a075322035
3e6801801454815f9861caabecddc2df204c4165
refs/heads/main
<repo_name>6RiverSystems/blackboard<file_sep>/test/InMemoryMapBlackboard.spec.ts import {assert} from 'chai'; import {BlackboardRef} from '../lib'; import {InMemoryMapBlackboard} from '../lib/InMemoryMapBlackboard'; describe('InMemoryMapBlackboard', function() { it('create', function() { const uut = new InMemoryMapBlackboard(); const bbRef = new BlackboardRef('someName'); const value = 'someValue'; uut.create(bbRef, value); const [exists, gottenValue] = uut.tryGet(bbRef); assert.isTrue(exists); assert.strictEqual(gottenValue, value); let thrown = false; try { uut.create(bbRef, value); } catch (err) { thrown = true; } assert.isTrue(thrown); }); context('is', function() { let uut = new InMemoryMapBlackboard(); const bbRef = new BlackboardRef('test'); beforeEach(function() { uut = new InMemoryMapBlackboard(); }); const refVals = [{}, [], new Map()]; const valVals = ['', 'test', 3, 0, -1, true, false]; const magicVals = [() => ({}), new Error('test')]; context('same as stored', function() { const testTrue = (value: any) => () => { uut.create(bbRef, value); assert.isTrue(uut.is(bbRef, value)); }; context('reference types', function() { for (const value of refVals) { it(`works with ${value}`, testTrue(value)); } }); context('value types', function() { for (const value of valVals) { it(`works with ${value}`, testTrue(value)); } }); context('magic types', function() { for (const value of magicVals) { it(`works with ${value}`, testTrue(value)); } }); }); context('get-clone', function() { const testFalse = (value: any) => () => { uut.create(bbRef, value); assert.isFalse(uut.is(bbRef, uut.get(bbRef))); }; const testTrue = (value: any) => () => { uut.create(bbRef, value); assert.isTrue(uut.is(bbRef, uut.get(bbRef))); }; context('reference types', function() { for (const value of refVals) { it(`works with ${value}`, testFalse(value)); } }); context('value types', function() { for (const value of valVals) { it(`works with ${value}`, testTrue(value)); } }); context('magic types', function() { for (const value of magicVals) { it(`works with ${value}`, testTrue(value)); } }); }); }); it('get', function() { const uut = new InMemoryMapBlackboard(); const bbRef = new BlackboardRef('someName'); const value = 'someValue'; let thrown = false; try { uut.get(bbRef); } catch (err) { thrown = true; } assert.isTrue(thrown); uut.put(bbRef, value); const gottenValue = uut.get(bbRef); assert.strictEqual(gottenValue, value); }); it('get clone where appropriate', function() { const uut = new InMemoryMapBlackboard(); const bbRefObj = new BlackboardRef<{foo: string}>('obj'); const bbRefFunc = new BlackboardRef<() => boolean>('func'); const bbRefErr = new BlackboardRef<Error>('err'); const valueObj = {foo: 'asdf'}; const valueFunc = () => true; const valueErr = new Error(); uut.put(bbRefObj, valueObj); uut.put(bbRefFunc, valueFunc); uut.put(bbRefErr, valueErr); const gottenValueObj = uut.get(bbRefObj); const gottenValueFunc = uut.get(bbRefFunc); const gottenValueErr = uut.get(bbRefErr); assert.notStrictEqual(gottenValueObj, valueObj); assert.strictEqual(gottenValueFunc, valueFunc); assert.strictEqual(gottenValueErr, valueErr); }); it('tryGet', function() { const uut = new InMemoryMapBlackboard(); const bbRef = new BlackboardRef('someName'); const value = 'someValue'; let [exists, gottenValue] = uut.tryGet(bbRef); assert.isFalse(exists); uut.put(bbRef, value); [exists, gottenValue] = uut.tryGet(bbRef); assert.isTrue(exists); assert.strictEqual(gottenValue, value); }); it('put', function() { const uut = new InMemoryMapBlackboard(); const bbRef = new BlackboardRef('someName'); const value = 'someValue'; uut.put(bbRef, value); let [exists, gottenValue] = uut.tryGet(bbRef); assert.isTrue(exists); assert.strictEqual(gottenValue, value); uut.put(bbRef, value); [exists, gottenValue] = uut.tryGet(bbRef); assert.isTrue(exists); assert.strictEqual(gottenValue, value); }); it('delete', function() { const uut = new InMemoryMapBlackboard(); const bbRef = new BlackboardRef('someName'); const value = 'someValue'; uut.put(bbRef, value); let deleteResult = uut.delete(bbRef); assert.isTrue(deleteResult); deleteResult = uut.delete(bbRef); assert.isFalse(deleteResult); }); it('deleteAll', function() { const uut = new InMemoryMapBlackboard(); const r1 = new BlackboardRef('r1'); const r2 = new BlackboardRef('r2'); const r3 = new BlackboardRef('r3'); uut.put(r1, 1); uut.put(r2, 2); uut.put(r3, 3); assert.lengthOf(Object.entries(uut.stateReadable), 3); let deleted = uut.deleteAll([r1, r2]); assert.deepStrictEqual(deleted, [r1, r2]); assert.lengthOf(Object.entries(uut.stateReadable), 1); deleted = uut.deleteAll([r1, r2]); assert.deepStrictEqual(deleted, []); assert.lengthOf(Object.entries(uut.stateReadable), 1); }); it('stateReadable', function() { const uut = new InMemoryMapBlackboard(); const bbRef1 = new BlackboardRef('someName'); const bbRef2 = new BlackboardRef('someName'); const value1 = 'someValue1'; const value2 = 'someValue2'; assert.deepStrictEqual(uut.stateReadable, {}); uut.put(bbRef1, value1); assert.lengthOf(Object.entries(uut.stateReadable), 1); uut.put(bbRef2, value2); assert.lengthOf(Object.entries(uut.stateReadable), 2); const values = Object.values(uut.stateReadable); assert.include(values, value1 as unknown as object); // WTF TS 3 assert.include(values, value2 as unknown as object); // WTF TS 3 }); }); <file_sep>/test/Accessors/BlackboardConsumer.spec.ts import {assert} from 'chai'; import {InMemoryMapBlackboard} from '../../lib'; import {BlackboardConsumer} from '../../lib/Accessors/'; import {BlackboardRef} from '../../lib/BlackboardRef'; describe('BlackboardConsumer', function() { let bb = new InMemoryMapBlackboard(); const r = new BlackboardRef<number>('test'); const a = new BlackboardConsumer(r); beforeEach(function() { bb = new InMemoryMapBlackboard(); }); it('fails for missing data', function() { let threw = false; try { a.consume(bb); } catch (err) { threw = true; } assert.isTrue(threw); }); it('returns the consumed value', function() { const val = 3; bb.put(r, val); assert.equal(val, a.consume(bb)); }); it('deletes the consumed value', function() { bb.put(r, 3); a.consume(bb); assert.isFalse(bb.tryGet(r)[0]); }); }); <file_sep>/lib/Accessors/index.ts export * from './BlackboardConsumer'; export * from './BlackboardGetter'; export * from './BlackboardProducer'; export * from './BlackboardSetter'; <file_sep>/lib/Accessors/BlackboardProducer.ts import {Blackboard} from '../Blackboard'; import {BlackboardError} from '../BlackboardError'; import {BlackboardRef} from '../BlackboardRef'; export class BlackboardProducer<T> { constructor(private readonly ref: BlackboardRef<T>) {} public produce(blackboard: Blackboard, value: T) { if (blackboard.tryGet(this.ref)[0]) { throw new BlackboardError(this.ref, `Cannot produce with unconsumed data remaining for ${this.ref.name}`); } return blackboard.put(this.ref, value); } } <file_sep>/test/Accessors/BlackboardProducer.spec.ts import {assert} from 'chai'; import {InMemoryMapBlackboard} from '../../lib'; import {BlackboardProducer} from '../../lib/Accessors'; import {BlackboardRef} from '../../lib/BlackboardRef'; describe('BlackboardProducer', function() { let bb = new InMemoryMapBlackboard(); const r = new BlackboardRef<number>('test'); const a = new BlackboardProducer(r); beforeEach(function() { bb = new InMemoryMapBlackboard(); }); it('succeeds with empty slot', function() { a.produce(bb, 3); }); it('fails if slot is occupied', function() { let threw = false; a.produce(bb, 3); try { a.produce(bb, 4); } catch (err) { threw = true; } assert.isTrue(threw); assert.strictEqual(bb.get(r), 3); }); }); <file_sep>/lib/BlackboardError.ts import {BlackboardRef} from './BlackboardRef'; export class BlackboardError extends Error { constructor(public readonly ref: BlackboardRef<any>, message: string) { super(message); } } <file_sep>/lib/Blackboard.ts import {BlackboardRef} from './BlackboardRef'; export interface Blackboard { create<T>(ref: BlackboardRef<T>, value: T): void; is<T>(ref: BlackboardRef<T>, value: T): boolean; get<T>(ref: BlackboardRef<T>): T; tryGet<T>(ref: BlackboardRef<T>): [true, T]|[false, undefined]; put<T>(ref: BlackboardRef<T>, value: T): void; delete(ref: BlackboardRef<any>): boolean; deleteAll(refs: BlackboardRef<any>[]): BlackboardRef<any>[]; } function isFunction(maybeFunction: any): maybeFunction is Function { return maybeFunction !== null && maybeFunction !== undefined && typeof maybeFunction === 'function'; } export const BLACKBOARD_METHODS = Object.freeze(['create', 'get', 'tryGet', 'put', 'delete', 'deleteAll', 'is']); export function isBlackboard(maybeBlackboard: any): maybeBlackboard is Blackboard { return (maybeBlackboard !== null && maybeBlackboard !== undefined) && !BLACKBOARD_METHODS.some((m) => !isFunction(maybeBlackboard[m])); } <file_sep>/lib/Accessors/BlackboardGetter.ts import {Blackboard} from '../Blackboard'; import {BlackboardRef} from '../BlackboardRef'; export class BlackboardGetter<T> { constructor(private readonly ref: BlackboardRef<T>) {} public get(blackboard: Blackboard) { return blackboard.get(this.ref); } public tryGet(blackboard: Blackboard) { return blackboard.tryGet(this.ref); } } <file_sep>/test/Accessors/BlackboardSetter.spec.ts import {assert} from 'chai'; import {InMemoryMapBlackboard} from '../../lib'; import {BlackboardSetter} from '../../lib/Accessors'; import {BlackboardRef} from '../../lib/BlackboardRef'; describe('BlackboardSetter', function() { const bb = new InMemoryMapBlackboard(); const r = new BlackboardRef<number>('test'); const a = new BlackboardSetter(r); it('sets', function() { a.set(bb, 3); assert.strictEqual(bb.get(r), 3); }); }); <file_sep>/lib/index.ts export * from './Accessors'; export * from './Blackboard'; export * from './BlackboardError'; export * from './BlackboardRef'; export * from './InMemoryMapBlackboard'; <file_sep>/lib/Accessors/BlackboardSetter.ts import {Blackboard} from '../Blackboard'; import {BlackboardRef} from '../BlackboardRef'; export class BlackboardSetter<T> { constructor(private readonly ref: BlackboardRef<T>) {} public set(blackboard: Blackboard, value: T) { return blackboard.put(this.ref, value); } } <file_sep>/test/BlackboardRef.spec.ts import {assert} from 'chai'; import {BlackboardRef} from '../lib/BlackboardRef'; describe('BlackboardRef', function() { it('works', function() { const name = 'someName'; const uut = new BlackboardRef(name); assert.isOk(uut.uuid); assert.strictEqual(uut.name, name); }); it('handles hierarchy', function() { const name = 'someName'; const childName = 'childName'; const grandChildName = 'grandChildName'; const uut = new BlackboardRef(name); assert.isOk(uut.uuid); assert.strictEqual(uut.name, name); assert.lengthOf(uut.descendants, 0); const childRef = uut.createChild(childName); assert.isOk(childRef.uuid); assert.isTrue(childRef.name.indexOf(name) >= 0); assert.isTrue(childRef.name.indexOf(childName) >= 0); assert.notEqual(childRef.name, childName); assert.notEqual(childRef.name, name); assert.lengthOf(uut.descendants, 1); assert.deepStrictEqual(uut.descendants, [childRef]); const grandChildRef = childRef.createChild(grandChildName); assert.isOk(grandChildRef.uuid); assert.lengthOf(grandChildRef.descendants, 0); assert.lengthOf(childRef.descendants, 1); assert.lengthOf(uut.descendants, 2); assert.lengthOf(uut.children, 1); assert.lengthOf(childRef.children, 1); assert.lengthOf(grandChildRef.children, 0); }); }); <file_sep>/test/Blackboard.spec.ts import {assert} from 'chai'; import {isBlackboard, BLACKBOARD_METHODS} from '../lib/Blackboard'; function getMockBlackboard() { return BLACKBOARD_METHODS.reduce((obj, meth) => (obj[meth] = () => ({}), obj), {} as any); } describe('Blackboard', function() { context('user-defined type-guard', function() { it('succeeds when all properties are present and functions', function() { assert.isTrue(isBlackboard(getMockBlackboard())); }); context('per-property checks', function() { for (const prop of BLACKBOARD_METHODS) { context(prop, function() { it('fails if prop is missing', function() { const bb: any = getMockBlackboard(); delete bb[prop]; assert.isFalse(isBlackboard(bb)); }); it('fails if prop is wrong', function() { const bb: any = getMockBlackboard(); bb[prop] = 'not a function'; assert.isFalse(isBlackboard(bb)); }); }); } }); }); }); <file_sep>/lib/BlackboardRef.ts import * as uuid from 'uuid'; export class BlackboardRef<T> { private readonly _uuid: string; private readonly _name: string; private readonly _children: BlackboardRef<any>[] = []; // This is unused but prevents assigning, e.g. BlackboardRef<string> to BlackboardRef<number> protected readonly _marker!: T; constructor(name: string, parent?: BlackboardRef<any>) { if (parent) { name = parent.name + '.' + name; } this._uuid = uuid.v4(); this._name = name; } public createChild<U>(name: string): BlackboardRef<U> { const ref = new BlackboardRef<U>(name, this); this._children.push(ref); return ref; } public get children(): ReadonlyArray<BlackboardRef<any>> { return this._children; } public get descendants(): BlackboardRef<any>[] { return this._children.concat(...this._children.map((c) => c.descendants)); } public get uuid(): string { return this._uuid; } public get name(): string { return this._name; } } <file_sep>/lib/InMemoryMapBlackboard.ts import * as _ from 'lodash'; import {Blackboard} from './Blackboard'; import {BlackboardError} from './BlackboardError'; import {BlackboardRef} from './BlackboardRef'; export class InMemoryMapBlackboard implements Blackboard { private readonly state: Map<string, [BlackboardRef<any>, any]> = new Map(); public is<T>(ref: BlackboardRef<T>, value: T) { return this.state.has(ref.uuid) && this.state.get(ref.uuid)![1] === value; } public get<T>(ref: BlackboardRef<T>) { if (this.state.has(ref.uuid)) { return InMemoryMapBlackboard.cloneObject(this.state.get(ref.uuid)![1]); } else { throw new BlackboardError(ref, `could not locate reference for ${ref.name}`); } } public tryGet<T>(ref: BlackboardRef<T>): [true, T]|[false, undefined] { const exists = this.state.has(ref.uuid); if (exists) { return [exists, InMemoryMapBlackboard.cloneObject(this.state.get(ref.uuid)![1])]; } else { return [exists, undefined]; } } public create<T>(ref: BlackboardRef<T>, value: T) { if (this.state.has(ref.uuid)) { throw new BlackboardError(ref, `key already exists for ${ref.name}`); } this.state.set(ref.uuid, [ref, value]); } public put<T>(ref: BlackboardRef<T>, value: T) { this.state.set(ref.uuid, [ref, value]); } public delete(ref: BlackboardRef<any>) { return this.state.delete(ref.uuid); } public deleteAll(refs: BlackboardRef<any>[]) { return refs.filter((r) => this.delete(r)); } // handy method for viewing in the debugger and logging // Q: why is this method public? // A: cfs_models depends on this method. Therefore, changes to this method should be considered breaking // Q: doesn't exposing entire state of the blackboard compromise component isolation? // A: no, because this method is not in the Blackboard interface public get stateReadable(): {[K in string]?: object} { return [...this.state.entries()].reduce((acc, next) => { const uuid = next[0]; const name = next[1][0].name; const value = next[1][1]; if (acc.hasOwnProperty(name)) { return {...acc, [name + '-' + uuid]: value}; } else { return {...acc, [name]: value}; } }, {}); } private static cloneObject<T>(obj: T) { // NOTE: lodash clone is "loosely based on the structured clone algorithm" which doesn't handle certian object // types, so for now just passing them through (otherwise lodash returns an empty object) // see here: https://lodash.com/docs/4.17.11#clone // and here: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) if (obj instanceof Function || obj instanceof Error) { return obj; } return _.cloneDeep(obj); } } <file_sep>/lib/Accessors/BlackboardConsumer.ts import {Blackboard} from '../Blackboard'; import {BlackboardError} from '../BlackboardError'; import {BlackboardRef} from '../BlackboardRef'; export class BlackboardConsumer<T> { constructor(private readonly ref: BlackboardRef<T>) {} public consume(blackboard: Blackboard) { const state = blackboard.tryGet(this.ref); if (!state[0]) { throw new BlackboardError(this.ref, `Cannot consume with no data available for ${this.ref.name}`); } blackboard.delete(this.ref); return state[1]; } } <file_sep>/test/Accessors/BlackboardGetter.spec.ts import {assert} from 'chai'; import {InMemoryMapBlackboard} from '../../lib'; import {BlackboardGetter} from '../../lib/Accessors'; import {BlackboardRef} from '../../lib/BlackboardRef'; describe('BlackboardGetter', function() { let bb = new InMemoryMapBlackboard(); const r = new BlackboardRef<number>('test'); const a = new BlackboardGetter(r); beforeEach(function() { bb = new InMemoryMapBlackboard(); }); context('get', function() { it('fails for lack of data', function() { let threw = false; try { a.get(bb); } catch (err) { threw = true; } assert.isTrue(threw); }); it('succeeds with data', function() { const val = 3; bb.put(r, val); assert.equal(val, a.get(bb)); }); }); context('tryGet', function() { it('returns missing for lack of data', function() { assert.isFalse(a.tryGet(bb)[0]); }); it('returns found + data for data', function() { const val = 3; bb.put(r, val); const result = a.tryGet(bb); assert.isTrue(result[0]); assert.strictEqual(result[1], val); }); }); });
44fce752d3e64fe56cec2415652f6e19cd75617c
[ "TypeScript" ]
17
TypeScript
6RiverSystems/blackboard
368f3596c3fe28da2f161e65ffc78a280b9b1e2d
5d3122c1b697ebdfec6807fd8e955496aeeb6eb3
refs/heads/main
<repo_name>V0vkan/NumeralSystemConverter<file_sep>/Converter.java package converter; public class Converter { public String numbersConverter(int sRadix, String num, int tRadix) { String convertedNumber; String[] parts; if (sRadix == 1) { convertedNumber = Integer.toString(num.length(), tRadix); } else if (tRadix == 1) { convertedNumber = "1".repeat(Integer.parseInt(num)); } else { if (num.contains(".")) { parts = num.split("\\."); int integerPart = Integer.parseInt(parts[0], sRadix); double fractionalPart = 0; for (int i = 0; i < parts[1].length(); i++) { String part = Character.toString(parts[1].charAt(i)); fractionalPart += Integer.parseInt(part, sRadix) / Math.pow(sRadix, i + 1); } convertedNumber = Integer.toString(integerPart, tRadix) + "."; StringBuilder resultFractionalPart = new StringBuilder(); for (int i = 0; i < 5; i++) { fractionalPart *= tRadix; int toAdd = (int) fractionalPart; fractionalPart -= toAdd; resultFractionalPart.append(Integer.toString(toAdd, tRadix)); } convertedNumber += resultFractionalPart.toString(); } else { convertedNumber = Integer.toString(Integer.parseInt(num, sRadix), tRadix); } } return convertedNumber; } } <file_sep>/README.md # NumeralSystemConverter The program converts the number from the specified base to the target base, min base = 1, max base = 36. The program takes three lines: 1. The source radix; 2. The source number; 3. The target radix; Then, it will output converted number to target radix # Example Input: 10 11 2 Output: 1011 # Fractional numbers can also be converted from one base to another. # Examples Exaple 1: Input: 10 0.234 7 Output: 0.14315 Exaple 2: Input: 35 af.xy 17 Output: 148.g88a8
93e61a2f9dbe533edf389b375a4a43a3eb4e2f95
[ "Markdown", "Java" ]
2
Java
V0vkan/NumeralSystemConverter
d9cf75e9a16b777a03ecf224e1066d8fd380be93
4fa8d3a454e79a37c8ba6e0bfb53b54e7073881a
refs/heads/master
<repo_name>willdolbeer/willdolbeer.github.io<file_sep>/src/app/home.component.html <div id="intro" class="row"> <div class="section-content"> <h1 class="display-1"><NAME></h1> <h4>Front End Web Developer</h4> </div> </div> <div id="about" class="row"> <div class="section-content col-md-10 offset-md-1"> <h1 class="display-4">About Me</h1> <img class="about-img" src="assets/headshot.jpg" alt="Headshot" /> <div class="about-text"> <p> I'm a Software Developer based in Durham, North Carolina, and work for boiler manufacturer Miura America Co., Ltd. In addition to my primary focus of front end web development, I also have experience with full stack applications. I have overseen the development of a variety of projects from planning to production, from robust content management systems to data-driven Angular applications. While my strengths are in front end development, I am always looking to grow as a developer and learn new languages and technologies. </p> <p> When I'm not developing, I enjoy spending time with my wife and two daughters, playing adult league soccer, and cycling. </p> </div> </div> </div> <div id="experience" class="row"> <div class="section-content col-md-10 offset-md-1"> <h1 class="display-4">Experience</h1> <h2>Education</h2> <div class="experience-item"> <h3 class="title">Bachelor of Science in Computer Science</h3> <h4 class="sub-title">Mars Hill College</h4> <strong>2003 - 2007</strong> </div> <h2>Professional</h2> <div class="experience-item"> <h3 class="title">Software Developer</h3> <h4 class="sub-title">Miura America Co., Ltd.</h4> <strong>2013 - Present</strong> <p class="description"> Miura is a manufacturer of commercial boilers known for their efficiency, small footprint, and modular design. In this role, I have developed the corporate website, including a complete redesign in 2016, and intranet site using content management systems. I support several of Miura's departments by developing and maintaining web applications for internal use. </p> </div> <h2>What I Use</h2> <div class="card-container"> <div class="card-cell"> <div class="card"> <div class="card-body"> <h3 class="card-title"> <img src="assets/ic_code_white.png" alt="Code icon" /> Angular Applications </h3> <p class="card-text"> Usually combined with Bootstrap and Firebase, Angular has been my primary framework for web development, using versions 1.x and 4/5 with TypeScript. </p> </div> </div> </div> <div class="card-cell"> <div class="card"> <div class="card-body"> <h3 class="card-title"> <img src="assets/ic_web_white.png" alt="Web icon" /> CMS Frameworks </h3> <p class="card-text"> For projects that require quick and easy management, I've developed sites using Drupal, Joomla, and Wordpress, including custom PHP components and plugins. </p> </div> </div> </div> <div class="card-cell"> <div class="card"> <div class="card-body"> <h3 class="card-title"> <img src="assets/ic_devices_white.png" alt="Devices icon" /> Responsive Design </h3> <p class="card-text"> Regardless of the language or framework used, I develop applications that adapt to devices of all sizes and function properly in all browsers. </p> </div> </div> </div> </div> </div> </div> <div id="skills" class="row"> <div class="section-content col-md-10 offset-md-1"> <h1 class="display-4">Skills</h1> <ul class="skills-list"> <li class="skills-item">JavaScript</li> <li class="skills-item">HTML</li> <li class="skills-item">CSS</li> <li class="skills-item">PHP</li> <li class="skills-item">AngularJS</li> <li class="skills-item">Bootstrap</li> <li class="skills-item">jQuery</li> <li class="skills-item">Firebase</li> <li class="skills-item">Joomla</li> <li class="skills-item">Drupal</li> <li class="skills-item">SQL</li> <li class="skills-item">Angular</li> <li class="skills-item">TypeScript</li> <li class="skills-item">Sass</li> <li class="skills-item">Git</li> <li class="skills-item">Wordpress</li> <li class="skills-item">Cordova</li> <li class="skills-item">Java</li> </ul> </div> </div> <div id="contact" class="row"> <div class="section-content"> <div class="contact-links"> <a href="mailto:<EMAIL>" target="blank" class="contact-item" title="Email"> <img src="assets/ic_mail_white.png" alt="Mail icon" /> </a> <a href="https://www.linkedin.com/in/willdolbeer/" target="blank" class="contact-item" title="LinkedIn"> <img src="assets/linkedin.png" alt="LinkedIn icon" /> </a> </div> <div class="copyright">&copy; <NAME> 2018</div> </div> </div> <file_sep>/src/app/app.component.ts import { Component, OnInit, OnDestroy} from '@angular/core'; declare var $: any; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { lastScroll: number; animateScroll = false; constructor() {} scroll(id: string){ this.animateScroll = true; $('html, body').animate({ scrollTop: $('#'+id).offset().top }, 500, () => { this.animateScroll = false; if($(window).width() >= 768 && window.scrollY < ($(window).height()/2)){ $('.navbar').hide(300); } }); if($(window).width() < 768){ $('#navbar').collapse('hide'); } } ngOnInit() { this.lastScroll = window.pageYOffset || document.documentElement.scrollTop; $('.nav-link').click((e) =>{ e.preventDefault(); }); if($(window).width() >= 768){ if(window.scrollY > ($(window).height()/2)){ $('.navbar').show(); }else{ $('.navbar').hide(); } } window.addEventListener('scroll', this.scrolling); window.addEventListener('resize', this.resize); } ngOnDestroy() { window.removeEventListener('scroll', this.scrolling); window.removeEventListener('resize', this.resize); } scrolling = (): void => { if(!this.animateScroll && $(window).width() >= 768){ let st = window.pageYOffset || document.documentElement.scrollTop; if(st <= $(window).height()/2){ this.lastScroll = st; $('.navbar').hide(300); }else{ this.lastScroll = st; $('.navbar').show(300); } } }; resize = (): void => { if($(window).width() < 768){ $('.navbar').show(); }else{ let yc = window.pageYOffset || document.documentElement.scrollTop; if(yc <= $(window).height()/2){ $('.navbar').hide(); }else{ $('.navbar').show(); } } } }
ab1f4a48650907046098c5c874fbd2c6f7fe02ea
[ "TypeScript", "HTML" ]
2
HTML
willdolbeer/willdolbeer.github.io
a4eeb90afad2470b71b4ab0cd6279ad57c76af92
8542d6fc6818b851baf53fb246130edbd7024b84
refs/heads/master
<file_sep>package com.sample.web.controller; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import com.sample.business.entity.Score; import com.sample.business.service.ScoreService; import com.sample.web.form.ScoreForm; @Controller public class ScoreController { @Autowired private ScoreService scoreService; /** * スコアの一覧ページを表示 * @param model * @return */ @GetMapping("/") public String index(Model model){ model.addAttribute("scores", scoreService.findAllWithRank()); model.addAttribute("averagePoint", scoreService.averagePoint()); model.addAttribute("highScore", scoreService.findHighScore()); return "scores/index"; } /** * スコアの新規登録画面を表示 * @param scoreForm * @return */ @GetMapping("/scores/new") public String newScore(ScoreForm scoreForm){ return "scores/new"; } /** * スコアの登録 * @param scoreForm * @param result * @return */ @PostMapping("/scores") public String createScore(@Validated ScoreForm scoreForm, BindingResult result){ if (result.hasErrors()) { return "scores/new"; } Score score = new Score(); BeanUtils.copyProperties(scoreForm, score); scoreService.save(score); return "redirect:/"; } /** * スコアの編集画面を表示 * @param id * @param scoreForm * @return */ @GetMapping("/scores/{id}/edit") public String editScore(@PathVariable Long id, ScoreForm scoreForm){ Score score = scoreService.findOne(id); BeanUtils.copyProperties(score, scoreForm); return "scores/edit"; } /** * スコアの更新 * @param id * @param scoreForm * @param result * @return */ @PostMapping("/scores/{id}") public String updateScore(@PathVariable Long id, @Validated ScoreForm scoreForm, BindingResult result){ if (result.hasErrors()) { return "scores/edit"; } Score score = scoreService.findOne(id); BeanUtils.copyProperties(scoreForm, score); scoreService.save(score); return "redirect:/"; } /** * スコアの削除 * @param id * @return */ @GetMapping("/scores/{id}/delete") public String deleteScore(@PathVariable Long id){ scoreService.delete(id); return "scores/delete"; } } <file_sep>package com.sample.business.repository; import com.sample.business.entity.Score; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; /** * DBから欲しいレコードを取ってこれているかのテスト<br> * <code>@Sql</code>でデータを用意している */ @RunWith(SpringRunner.class) @SpringBootTest @Sql({"/sql/delete-scores.sql", "/sql/insert-data.sql"}) public class ScoreRepositoryTest { @Autowired private ScoreRepository scoreRepository; @Test public void testFindTopByOrderByPointDesc(){ Score highScore = scoreRepository.findTopByOrderByPointDesc(); assertThat(highScore.getName(), is("Luke Skywalker")); assertThat(highScore.getPoint(), is(99)); } } <file_sep>spring.datasource.url=jdbc:mysql://localhost/sample-application spring.datasource.username=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true security.basic.enabled=false<file_sep>INSERT INTO scores (name, point) VALUES ("<NAME>", 21); INSERT INTO scores (name, point) VALUES ("<NAME>", 43); INSERT INTO scores (name, point) VALUES ("Yoda", 62); INSERT INTO scores (name, point) VALUES ("<NAME>", 38); INSERT INTO scores (name, point) VALUES ("<NAME>", 99); <file_sep>spring.datasource.url=${JDBC_DATABASE_URL} spring.datasource.driver-class-name=org.postgresql.Driver security.basic.enabled=true security.user.name=r2d2 security.user.password=<PASSWORD><file_sep>package com.sample.web.controller; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.hamcrest.CoreMatchers.*; /** * コントローラの結合テスト<br> * MockMvcを使う<br> * ScoreController#createScoreのテストはフィクスチャを用意しパラメータ化テストにする */ @RunWith(Theories.class) @SpringBootTest @Transactional public class ScoreControllerTest { @ClassRule public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule(); @Rule public final SpringMethodRule springMethodRule = new SpringMethodRule(); /** * フィクスチャ */ @DataPoints public static Fixture[] fixtures = { new Fixture("", "", 2, "scores/new"), new Fixture("", "50", 1, "scores/new"), new Fixture("jack", "", 1, "scores/new"), new Fixture("jack", "-1", 1, "scores/new"), new Fixture("jack", "0", 0, "redirect:/"), new Fixture("jack", "100", 0, "redirect:/"), new Fixture("jack", "101", 1, "scores/new") }; @Autowired private WebApplicationContext context; private MockMvc mockMvc; /** * Contextを設定し、MockMvcを生成する<br> * <code>MockMvcBuilders.webAppContextSetup(context).build()</code>の場合、結合テストのように行える<br> * <code>MockMvcBuilders.standaloneSetup(new ScoreController()).build()</code>の場合、コントローラの単体テストのように行える<br> */ @Before public void setupMockMvc(){ this.mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); // this.mockMvc = MockMvcBuilders.standaloneSetup(new ScoreController()).build(); } @Test public void testIndex() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name(is("scores/index"))); } @Test public void testNewScore() throws Exception { mockMvc.perform(get("/scores/new")) .andExpect(status().isOk()) .andExpect(view().name(is("scores/new"))); } /** * パラメータ化テスト * @param fixture フィクスチャ * @throws Exception */ @Theory public void testCreateScore(Fixture fixture) throws Exception { mockMvc.perform(post("/scores").param("name", fixture.name).param("point", fixture.point)) .andExpect(model().errorCount(fixture.expectErrorCount)) .andExpect(view().name(is(fixture.expectViewName))); } /** * フィクスチャ用のクラス<br> * スコアを登録するときのパラメータと、そのパラメータの場合の期待値を持つ */ static class Fixture{ /** * パラメータ(name) */ String name; /** * パラメータ(point) */ String point; /** * 期待するエラーの数 */ int expectErrorCount; /** * 期待するレンダリングするビューの名前 */ String expectViewName; Fixture(String name, String point, int expectErrorCount, String expectViewName){ this.name = name; this.point = point; this.expectErrorCount = expectErrorCount; this.expectViewName = expectViewName; } } } <file_sep>package com.sample.business.entity; import javax.persistence.*; @Entity @Table(name = "scores") public class Score { public Score(){ } public Score(String name, Integer point){ this.name = name; this.point = point; } /** * ID */ @Id @GeneratedValue private Long id; /** * 名前 */ @Column(nullable = false) private String name; /** * 得点 */ @Column(nullable = false) private Integer point; /** * スコアのランク<br> * DBには保存しない */ @Transient private String rank; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getPoint() { return point; } public void setPoint(Integer point) { this.point = point; } public String getRank() { return rank; } public void setRank(String rank) { this.rank = rank; } } <file_sep>package com.sample.business.service; import java.util.List; import com.sample.business.entity.Score; public interface ScoreService { /** * スコアの検索 * @param id * @return */ Score findOne(Long id); /** * 得点が最も高いスコアを検索 * @return */ Score findHighScore(); /** * 全スコアの取得 * @return */ List<Score> findAll(); /** * スコアのランクを決定し、全スコアを取得 * @return */ List<Score> findAllWithRank(); /** * スコアの保存 * @param score * @return */ Score save(Score score); /** * スコアの削除 * @param id */ void delete(Long id); /** * 全スコアの平均値 * @return */ int averagePoint(); } <file_sep># spring-test-practice spring-testの練習用プロジェクト ## デモサイト [https://score-manager.herokuapp.com/](https://score-manager.herokuapp.com/) user : r2d2 password : <PASSWORD> <file_sep>DELETE FROM scores;
ecb0d251ed1dff89c537d6575254d6ac1e1f7337
[ "Markdown", "Java", "SQL", "INI" ]
10
Java
FumiyaMori/spring-test-practice
aa16794fb1cc0389031dc02e9939a70457d0b410
c6d2de8077ab0f8fc11150c251d199641cb8a9cc
refs/heads/master
<file_sep>package com.rainsunset.common.bean; import java.io.Serializable; /** * @param <T> the type parameter * @description: API标准返回对象 * @author: ligangwei * @company rainsunset * @date: 2019.04.04 * @version : 1.0 */ public class ResponseResult<T> implements Serializable { /** * 业务成功/失败 */ private boolean success; /** * 业务返回对象 */ private T data; /** * message */ private String message; /** * 错误码 */ private String errorCode; public ResponseResult() {} public ResponseResult(boolean success, T data, String message, String errorCode) { this.success = success; this.data = data; this.message = message; this.errorCode = errorCode; } /** * Is success boolean. * * @return the boolean * @author : ligangwei / 2019-09-24 */ public boolean isSuccess() { return success; } /** * Sets success. * * @param success the success * @author : ligangwei / 2019-09-24 */ public void setSuccess(boolean success) { this.success = success; } /** * Get message string. * * @return the string * @author : ligangwei / 2019-09-24 */ public String getMessage() { return message; } /** * Sets message. * * @param message the message * @author : ligangwei / 2019-09-24 */ public void setMessage(String message) { this.message = message; } /** * Get data t. * * @return the t * @author : ligangwei / 2019-09-24 */ public T getData() { return data; } /** * Sets data. * * @param data the data * @author : ligangwei / 2019-09-24 */ public void setData(T data) { this.data = data; } /** * Get errorcode string. * * @return the string * @author : ligangwei / 2019-09-24 */ public String getErrorCode() { return errorCode; } /** * Sets errorcode. * * @param errorcode the errorcode * @author : ligangwei / 2019-09-24 */ public void setErrorCode(String errorcode) { this.errorCode = errorcode; } } <file_sep>package com.rainsunset.common.util.http; /** * @author: ligangwei * @company rainsunset * @date: 2019.09.24 * @version : 1.0 */ public class HttpConstants { //MIME public final static String MIMETYPE_TEXT_PLAIN = "text/plain;charset=utf-8"; public final static String MIMETYPE_TEXT_XML = "text/xml;charset=utf-8"; public final static String MIMETYPE_APPLICATION_JSON = "application/json;charset=utf-8"; public final static String MIMETYPE_APPLICATION_XML = "application/xml;charset=utf-8"; public final static String MIMETYPE_FORM_DATA = "multipart/form-data;"; public final static String MIMETYPE_FORM_URLENCODED = "application/x-www-form-urlencoded;"; } <file_sep>/** * company * Copyright (C) 2004-2018 All Rights Reserved. */ package com.rainsunset.common.bean; /** * @description: 异常枚举类通用接口 * @author: ligangwei * @company rainsunset * @date: 2019 /4/4 16:53 * @version : 1.0 */ public interface ErrorInfoInterface { /** * Get code string. * * @return the string * @author : ligangwei / 2019-09-24 */ String getCode(); /** * Get message string. * * @return the string * @author : ligangwei / 2019-09-24 */ String getMessage(); } <file_sep>package com.rainsunset.common.util; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @param <T> the type parameter * @description: 分页返回体 * @author: ligangwei * @company rainsunset * @date: 2019.04.16 * @version : 1.0 */ public class PageInfo<T> implements Serializable { /** * serialversionUID */ private static final long serialversionUID = 5689097937777375052L; /** * 总页数 */ private Integer totalPage = 0; /** * 当前页 */ private Integer currentPage = 1; /** * 每页记录条数 */ private Integer pageSize = 0; /** * 数据总长度 */ private Integer totalSize = 0; /** 时间锚点 格式 yyyy-MM-dd HH:mm:ss */ private String markTime; /** * 数据 */ private List<T> rows; /** * Page info. * * @param totalPage the total page * @param currentPage the current page * @param pageSize the page size * @param totalSize the total size * @param rows the rows */ public PageInfo(int totalPage, int currentPage, Integer pageSize, Integer totalSize, String markTime, List<T> rows) { this.totalPage = totalPage; this.currentPage = currentPage; this.pageSize = pageSize; this.totalSize = totalSize; this.markTime = markTime; this.rows = (null == rows) ? new ArrayList<T>() : rows; } /** * Page info. * * @param pageHelper the page helper * @param rows the rows */ public PageInfo(PageHelper pageHelper, List<T> rows) { this.totalPage = pageHelper.getTotalPage(); this.currentPage = pageHelper.getCurrentPage(); this.pageSize = pageHelper.getPageSize(); this.totalSize = pageHelper.getTotalSize(); if (null == rows) { rows = new ArrayList<>(); } this.rows = rows; } /** * Get total page integer. * * @return the integer * @author : ligangwei / 2019-09-24 */ public Integer getTotalPage() { return totalPage; } /** * Sets total page. * * @param totalPage the total page * @author : ligangwei / 2019-09-24 */ public void setTotalPage(int totalPage) { this.totalPage = totalPage; } /** * Get current page integer. * * @return the integer * @author : ligangwei / 2019-09-24 */ public Integer getCurrentPage() { return currentPage; } /** * Sets current page. * * @param currentPage the current page * @author : ligangwei / 2019-09-24 */ public void setCurrentPage(Integer currentPage) { if (null == currentPage || currentPage < 0) { currentPage = 1; } this.currentPage = currentPage; } /** * Get page size integer. * * @return the integer * @author : ligangwei / 2019-09-24 */ public Integer getPageSize() { return pageSize; } /** * Sets page size. * * @param pageSize the page size * @author : ligangwei / 2019-09-24 */ public void setPageSize(Integer pageSize) { if (null == pageSize || pageSize < 0) { this.pageSize = 20; } this.pageSize = (pageSize > 200) ? 200 : pageSize; } /** * Get total size integer. * * @return the integer * @author : ligangwei / 2019-09-24 */ public Integer getTotalSize() { return totalSize; } /** * Sets total size. * * @param totalSize the total size * @author : ligangwei / 2019-09-24 */ public void setTotalSize(Integer totalSize) { this.totalSize = totalSize; } /** * Get rows list. * * @return the list * @author : ligangwei / 2019-09-24 */ public List<T> getRows() { return rows; } /** * Sets rows. * * @param rows the rows * @author : ligangwei / 2019-09-24 */ public void setRows(List<T> rows) { this.rows = rows; } @Override public String toString() { return "PageInfo{" + "totalPage=" + totalPage + ", currentPage=" + currentPage + ", pageSize=" + pageSize + ", totalSize=" + totalSize + '}'; } } <file_sep>package com.rainsunset.common.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import java.lang.reflect.Type; /** * @description: Java Object <==> Gson String * @author: ligangwei * @company rainsunset * @date: 2019.05.29 * @version : 1.0 */ public class GsonUtil { /** * filterNullGson */ private static Gson filterNullGson; /** * nullableGson */ private static Gson nullableGson; static { nullableGson = new GsonBuilder() .enableComplexMapKeySerialization() .serializeNulls() .setDateFormat("yyyy-MM-dd HH:mm:ss:SSS") .create(); filterNullGson = new GsonBuilder() .enableComplexMapKeySerialization() .setDateFormat("yyyy-MM-dd HH:mm:ss:SSS") .create(); } /** * Gson util. */ protected GsonUtil() { } /** * 根据对象返回json 不过滤空值字段 * * @param obj the obj * @return the string * @author : ligangwei / 2019-05-29 */ public static String toJsonWtihNullField(Object obj) { return nullableGson.toJson(obj); } /** * 根据对象返回json 过滤空值字段 * * @param obj the obj * @return the string * @author : ligangwei / 2019-05-29 */ public static String toJsonFilterNullField(Object obj) { return filterNullGson.toJson(obj); } /** * 将json转化为对应的实体对象 * new TypeToken<HashMap<String, Object>>(){}.getType() * * @param <T> the type parameter * @param json the json * @param type the type * @return the t * @author : ligangwei / 2019-05-29 exam : Integer[] intarray = GsonUtil.fromJson(intarraystr,new TypeToken<Integer[]>(){}.getType()); */ public static <T> T fromJson(String json, Type type) { return nullableGson.fromJson(json, type); } /** * 判定是否为JsonObject * * @param jsonElement the json element * @return the boolean * @author : ligangwei / 2019-08-08 */ public static boolean isJsonObject(JsonElement jsonElement) { return ((null != jsonElement) && (!jsonElement.isJsonNull()) && jsonElement.isJsonObject()); } /** * 判定是否为JsonArray * * @param jsonElement the json element * @return the boolean * @author : ligangwei / 2019-08-08 */ public static boolean isJsonArray(JsonElement jsonElement) { return ((null != jsonElement) && (!jsonElement.isJsonNull()) && jsonElement.isJsonArray()); } /** * 判定是否为JsonString * * @param jsonElement the json element * @return the boolean * @author : ligangwei / 2019-08-08 */ public static boolean isJsonString(JsonElement jsonElement) { if ((null == jsonElement) || (jsonElement.isJsonNull())) { return false; } try { jsonElement.getAsString(); return true; } catch (Exception e) { return false; } } /** * jsonElement安全转化为String * * @param jsonElement the json element * @return the string * @author : ligangwei / 2019-11-29 22:07:06 */ public static String getAsString(JsonElement jsonElement) { if ((null == jsonElement) || (jsonElement.isJsonNull())) { return ""; } try { return jsonElement.getAsString(); } catch (Exception e) { return ""; } } } <file_sep>package com.rainsunset.common.bean; import java.io.Serializable; /** * @description: 基础请求参数 * @author: ligangwei * @company rainsunset * @date: 2019.09.24 * @version : 1.0 */ public class BaseRequest implements Serializable { /** * 日志id */ private String traceLogId; /** * Get trace log id string. * * @return the string * @author : ligangwei / 2019-09-24 */ public String getTraceLogId() { return traceLogId; } /** * Sets trace log id. * * @param traceLogId the trace log id * @author : ligangwei / 2019-09-24 */ public void setTraceLogId(String traceLogId) { this.traceLogId = traceLogId; } } <file_sep>package com.rainsunset.common.util; /** * @ClassName PageHelper * @description: 分页参数处理 * @author: ligangwei * @company rainsunset * @date: 2019/4/16 19:43 */ public class PageHelper { /** * 总页数 */ private Integer totalPage = 0; /** * 当前页 */ private Integer currentPage = 1; /** * 每页记录条数 */ private Integer pageSize = 0; /** * Sql查询偏移量 */ private Integer offset = 0; /** * 数据总长度 */ private Integer totalSize = 0; public PageHelper(Integer currentPage, Integer pageSize, Integer totalSize) { this.pageSize = (null == pageSize || 1 > pageSize) ? 20 : ((200 < pageSize) ? 200 : pageSize); if (null == totalSize || 0 > totalSize) { this.totalSize = 0; this.currentPage = 1; this.totalPage = 0; this.offset = 0; } else { this.totalSize = totalSize; this.currentPage = (null == currentPage || 1 > currentPage) ? 1 : currentPage; this.totalPage = (int)Math.ceil((double)this.totalSize / (double)this.pageSize); this.offset = this.pageSize * (this.currentPage - 1); } } public Integer getTotalPage() { return totalPage; } public Integer getCurrentPage() { return currentPage; } public Integer getPageSize() { return pageSize; } public Integer getOffset() { return offset; } public Integer getTotalSize() { return totalSize; } } <file_sep>[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.rainsunset/common/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.rainsunset/common) <file_sep>package com.rainsunset.common.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.UnknownHostException; /** * @description: 网络相关工具类 * @author: ligangwei * @company rainsunset * @date: 2019 /4/9 18:00 * @version : 1.0 * @ClassName NetworkIpUtil */ public class NetworkIpUtil { /** * logger */ private static Logger logger = LoggerFactory.getLogger(NetworkIpUtil.class); /** * 获取当前网络ip * * @param request the request * @return string string * @author : ligangwei / 2019-05-29 */ public static String getIpAddr(HttpServletRequest request) { String ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("HTTP_CLIENT_IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) { // 根据网卡取本机配置的IP InetAddress inet = null; try { inet = InetAddress.getLocalHost(); if (inet != null) { ipAddress = inet.getHostAddress(); } } catch (UnknownHostException e) { logger.error("getIpAddr", e); } } } // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() // = 15 if (ipAddress.indexOf(",") > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); } } return ipAddress; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" 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.github.rainsunset</groupId> <artifactId>common</artifactId> <version>${project.release.version}</version> <name>common</name> <description>rainsunset java project common jar</description> <url>https://github.com/rainsunset/common.git</url> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!--构建信息 (选配)--> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <project.release.version>1.0.0-SNAPSHOT</project.release.version> <!--依赖包版本--> <okhttp.version>4.2.0</okhttp.version> <dom4j.version>1.6</dom4j.version> <slf4j.version>1.7.25</slf4j.version> <apache.poi.version>3.14</apache.poi.version> <gson.version>2.8.5</gson.version> <spring-core.version>5.1.7.RELEASE</spring-core.version> <javax.servlet-api.version>3.1.0</javax.servlet-api.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring-core.version}</version> </dependency> <!--util>okhttp--> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>${okhttp.version}</version> </dependency> <!--util>Dom4j--> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>${dom4j.version}</version> </dependency> <!--log--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>${slf4j.version}</version> </dependency> <!--region Excel --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>${apache.poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>${apache.poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>${apache.poi.version}</version> </dependency> <!-- endregion Excel --> <!-- gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>${gson.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${javax.servlet-api.version}</version> </dependency> </dependencies> <licenses> <license> <name>The Apache Software License, version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> <distribution>repo</distribution> </license> </licenses> <scm> <tag>master</tag> <url>https://github.com/rainsunset/common.git</url> <connection>scm:git:<EMAIL>:rainsunset/common.git</connection> <developerConnection>scm:git:<EMAIL>:rainsunset/common.git</developerConnection> </scm> <developers> <developer> <name>rainsunset</name> <email><EMAIL></email> <organization>sunshine</organization> </developer> </developers> <distributionManagement> <snapshotRepository> <id>sonatype-nexus-snapshots</id> <url>https://oss.sonatype.org/content/repositories/snapshots</url> </snapshotRepository> <repository> <id>sonatype-nexus-staging</id> <url>https://oss.sonatype.org/service/local/staging/deploy/maven2</url> </repository> </distributionManagement> <build> <finalName>${project.artifactId}</finalName> <!--todo:配置打包路径--> <plugins> <!-- 指定编译器版本 --> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> </plugins> </build> <profiles> <profile> <id>common-staging</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <project.release.version>1.0.0</project.release.version> <gpg.executable>gpg</gpg.executable> <gpg.useagent>true</gpg.useagent> <gpg.passphrase>myPassphrase</gpg.passphrase> </properties> <build> <plugins> <!--nexus-staging--> <plugin> <groupId>org.sonatype.plugins</groupId> <artifactId>nexus-staging-maven-plugin</artifactId> <version>1.6.8</version> <extensions>true</extensions> <configuration> <serverId>sonatype-nexus-staging</serverId> <nexusUrl>https://oss.sonatype.org/</nexusUrl> <autoReleaseAfterClose>true</autoReleaseAfterClose> </configuration> </plugin> <!-- Source --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.2.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> <!-- Javadoc --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>3.0.1</version> <configuration> <failOnError>false</failOnError> <quiet>true</quiet> </configuration> <executions> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <!-- GPG 进行验签 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> <version>1.6</version> <executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>common-snapshot</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <project.release.version>1.0.0-SNAPSHOT</project.release.version> <gpg.executable>gpg</gpg.executable> <gpg.useagent>true</gpg.useagent> <gpg.passphrase><PASSWORD></gpg.passphrase> </properties> <build> <plugins> <!--nexus-staging--> <plugin> <groupId>org.sonatype.plugins</groupId> <artifactId>nexus-staging-maven-plugin</artifactId> <version>1.6.8</version> <extensions>true</extensions> <configuration> <serverId>sonatype-nexus-snapshots</serverId> <nexusUrl>https://oss.sonatype.org/</nexusUrl> <autoReleaseAfterClose>true</autoReleaseAfterClose> </configuration> </plugin> <!-- Source --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.2.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> <!-- Javadoc --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>3.0.1</version> <configuration> <failOnError>false</failOnError> <quiet>true</quiet> </configuration> <executions> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <!-- GPG 进行验签 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> <version>1.6</version> <executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project>
0ebd74f9154722a57db7782892e98caa64aac229
[ "Markdown", "Java", "Maven POM" ]
10
Java
rainsunset/common
f40e81c5320bc1278c1f0b9589e9698af3966624
a9ce5e7cdae456837a4dff9e37288033743a4e70
refs/heads/master
<repo_name>Fresh-code/s3-site-uploader<file_sep>/lib/upload-directory.js 'use strict'; const LIMIT_CONCURRENT_FILES = 5; const async = require('async'); const fs = require('fs'); const path = require('path'); const show = require('./output'); const removeModule = require('./remove'); const utils = require('./utils'); const aws = require('./aws'); let s3 = aws.getS3(); let cloudfront = aws.getCloudFront(); const _walkFilesSync = (dir, filelist) => { const files = fs.readdirSync(dir); filelist = filelist || []; const resolveDir = path.resolve(dir); files.forEach((file) => { try { const str = `${dir}/${file}`; if (fs.statSync(str.toString()).isDirectory()) { filelist = _walkFilesSync(`${dir}/${file}`, filelist); } else { filelist.push(`${dir}/${file}`); } } catch (error) { const errorMsg = `Cannot read directory ${resolveDir}/${file} or doesn't exist`; show.error(errorMsg, false); } }); return filelist; }; const _uploadFile = (rootDir) => { return (file, done) => { let fileWithoutLocalPath = file.slice(rootDir.length + 1, file.length); show.progress(`Uploading ${fileWithoutLocalPath}...`); fs.readFile(file, (err, data) => { if (err) { show.error(`[fs] ${err}`, true); } const fileExtension = utils.getFileExtension(file); const metaData = utils.getContentType(fileExtension); const params = { ACL: 'public-read', ContentType: metaData, Body: data, Bucket: process.env.BUCKET_NAME, Key: fileWithoutLocalPath }; if(fileExtension.match(/(css|js|jpg|jpeg|png|gif|svg|ttf)$/i)) { params.CacheControl = 'max-age=2592000000'; } const onUpload = (err, data) => { if (err) { done(err); } else { show.progress(`Uploaded ${fileWithoutLocalPath}...`); } done(null, data.Location); }; s3.upload(params, onUpload); }); } }; const _createInvalidation = () => { let distributionId = process.env.DISTRIBUTION_ID; if(!distributionId){ return; } let params; try { params = { DistributionId: distributionId, InvalidationBatch: { CallerReference: Date.now().toString(), Paths: { Quantity: 1, Items: ['/*'] } } }; show.info(`[cloudfront] Create an invalidation...`); } catch (err) { show.error(err, false); } cloudfront.createInvalidation(params, (err, data) => { if (err) { show.error(err, true); } else { show.info(`[cloudfront] Invalidation was created`); } }); }; module.exports = async(directoryPath) => { show.info(`[fs] Reading directory...`); const directoryPathResolve = path.resolve(directoryPath); show.info(`[config] Directory to upload:\n\t ${directoryPathResolve}`); show.info(`[fs] Reading directory...`); let fileList = _walkFilesSync(directoryPath); show.info(`[fs] Got ${fileList.length} files to upload\n`); await removeModule.clearBucket(s3, process.env.BUCKET_NAME).then(clean => { if (fileList.length && clean) { async.mapLimit(fileList, LIMIT_CONCURRENT_FILES, _uploadFile(directoryPath), (err, filesUploaded) => { if (err) { return show.error(err, true); } show.progress('> All files uploaded successfully!', true); show.info(`\n[result] URLs of uploaded files\n${filesUploaded.join('\n')}`); _createInvalidation(); }); } }); }; <file_sep>/README.md # S3 Site Uploader This library is intended to re-upload directory contents to AWS S3 bucket and invalidates AWS CloudFront cache. ## Install ```bash npm install -g s3-site-uploader ``` ## Configuration s3-site-uploader supports dotenv configuration which either takes AWS authentication info from environment variables: ``` ACCESS_KEY_ID - AWS Access Key SECRET_ACCESS_KEY - AWS Secret Key BUCKET_NAME - Name of S3 bucket to upload site to DISTRIBUTION_ID - ID of CloudFlare distribution to invalidate (optional) ``` or from `.env` properties file. ## Run Call application with a path to upload directory ```bash s3-site-uploader /path/to/directory ```
9a5b3610565563b4639a58f2870996356e430048
[ "JavaScript", "Markdown" ]
2
JavaScript
Fresh-code/s3-site-uploader
4626ea98ff86eb95c6b0da717844761499cf7845
edb72615da800f2227b695ca6c0fc7b275ac8458
refs/heads/master
<repo_name>niranjanbala/olahack<file_sep>/index.js // Include the cluster module var cluster = require('cluster'); // Code to run if we're in the master process if (cluster.isMaster) { // Count the machine's CPUs var cpuCount = require('os').cpus().length; // Create a worker for each CPU for (var i = 0; i < cpuCount; i += 1) { cluster.fork(); } // Listen for dying workers cluster.on('exit', function(worker) { // Replace the dead worker, we're not sentimental console.log('Worker ' + worker.id + ' died :('); cluster.fork(); }); // Code to run if we're in a worker process } else { // Include Express var express = require('express'); var path = require('path'); var compression = require('compression') // Create a new Express application var app = express(); app.use(express.static(path.join(__dirname, 'public'))); app.use(compression({ filter: shouldCompress })) function shouldCompress(req, res) { if (req.headers['x-no-compression']) { // don't compress responses with this request header return false } // fallback to standard filter function return compression.filter(req, res) } app.get('/confirm', function(request, response) { var Parse = require('parse/node'); var query = new Parse.Query(Parse.Installation); Parse.initialize("1PVc9kiXAOabkReQrVOBodTHI3OniukOSpBCRhdD", "<KEY>"); //save in ride var query = new Parse.Query("Ride"); //query.equalTo("rideId", request.query.rideId); query.get(request.query.rideId,{ success: function(ride) { var ids = ride.get("sharedWithOlaUserIds"); ids.push(request.query.sharingOlaUserId) if (ids.length == ride.get("availableSeats")) { ride.set("shareOk", false); } ride.set("sharedWithOlaUserIds", ids); ride.save(null, { success: function(userFilter) { var confirmQuery = new Parse.Query(Parse.Installation); confirmQuery.equalTo("olaUserId", request.query.sharingOlaUserId); Parse.Push.send({ where: confirmQuery, data: { alert: "Gokul has agreed to share the ride with you", action: { "rideId":request.query.rideId } } }, { success: function() { response.jsonp({ success: true }); }, error: function(error) { response.jsonp({ success: false, "message": error.message }); } }); }, error: function(userFilter, error) { response.jsonp({ success: false, "message": error.message }); } }); }, error: function(error) { response.jsonp({ success: false, "message": error.message }); } }); }); app.get('/cancel', function(request, response) { var Parse = require('parse/node'); var query = new Parse.Query(Parse.Installation); query.equalTo("olaUserId", req.query.sharingOlaUserId); Parse.initialize("1<KEY>", "<KEY>"); Parse.Push.send({ where: query, data: { alert: "Gokul has declined to share the ride with you" } }, { success: function() { response.jsonp({ success: true }); }, error: function(error) { response.jsonp({ success: false, "message": error.message }); } }); }); app.get('/share', function(request, response) { var Parse = require('parse/node'); var query = new Parse.Query(Parse.Installation); query.equalTo("olaUserId", request.query.bookingOlaUserId); Parse.initialize("1<KEY>", "<KEY>"); Parse.Push.send({ where: query, data: { alert: "Rajesh has requested to share a ride with you", action: { "rideId": request.query.rideId, "sharingOlaUserId": request.query.sharingOlaUserId, "bookingOlaUserId": request.query.bookingOlaUserId } } }, { success: function() { response.jsonp({ success: true }); }, error: function(error) { response.jsonp({ success: false }); } }); }); app.get('/book', function(request, response) { var pickup_lat = request.query.pickup_lat; var pickup_lng = request.query.pickup_lng; var drop_lat = request.query.drop_lat; var drop_lng = request.query.drop_lng; //X-APP-TOKEN //AUTHORIZATION //var auth = request.headers['X-APP-TOKEN']; //var auth = request.headers['Authorization']; //fire parse query and get rides going to same destinaton & starting point is within 3 kms. var Parse = require('parse/node'); Parse.initialize("<KEY>", "<KEY>"); var query = new Parse.Query("Ride"); // Interested in locations near user. var point = new Parse.GeoPoint({ latitude: Number(pickup_lat), longitude: Number(pickup_lng) }); query.withinKilometers("pickupPoint", point, 3); query.equalTo("shareOk", true); query.equalTo("destinationLat", Number(drop_lat)); query.equalTo("destinationLng", Number(drop_lng)); query.limit(10); query.find({ success: function(rideObjects) { var rideOptions = []; for (var i = 0; i < rideObjects.length; i++) { var rideObject = rideObjects[i]; var rideInfo = rideObject.get("olaRideTrackInfo"); if (rideObject.get("sharedWithOlaUserIds").length < rideObject.get("availableSeats")) rideOptions.push({ "rideId": rideObject.id, "olaUserId": rideObject.get("olaUserId"), "pickup": rideObject.get("pickupPoint"), "desitinationLat": rideObject.get("destinationLat"), "desitinationLng": rideObject.get("destinationLng"), "timeToYourPlace": "10 minute", "driver_name": rideInfo.driver_name, "car_model": rideInfo.car_model, "cab_number": rideInfo.cab_number }); } rideOptions.push({ "id": "sedan", "eta": 2, }); response.jsonp({ "rideOptions": rideOptions, }); } }); }); app.set('port', process.env.PORT || 80); app.listen(app.get('port'), function() { console.log("Node app is running at localhost:" + app.get('port')) }); }
f985d716c05e272d4ade925a2afd1fd166b56db5
[ "JavaScript" ]
1
JavaScript
niranjanbala/olahack
ca2cec30e0b5b0e852e13ce6b3ba176295d0a74f
2e8d526e59c8439f679f040228f0a78a5f3cc54b
refs/heads/master
<file_sep>import json import random from deap import base, creator, tools from deap.algorithms import eaSimple class DataLoader_Mixin(): """ DataLoader_Mixin""" def __init__(self): pass def data_load(self, file_path: str, return_data: bool = False): self.file_path = file_path with open(file_path) as json_read: if isinstance(json_read, type(dict())): return json_read if return_data == True: return json.load(json_read) else: self.data = json.load(json_read) def model_input_load(self, json_file): if isinstance(json_file, type(dict())): dict_temp = json_file else: dict_temp = json.load(json_file) print(dict_temp) self.calories = dict_temp["calories"] self.proteins = dict_temp["proteins"] self.carbohydrates = dict_temp["carbohydrates"] self.fat = dict_temp["fat"] self.meals_per_day = dict_temp["meals_per_day"] def data_sample(self, ind): with open(self.file_path) as json_read: dict_temp = json.load(json_read) instance = [] for i in range(self.meals_per_day): key = random.sample(dict_temp.keys(), 1)[0] instance.append([ key, int(float(dict_temp[key]["calories"])), int(float(dict_temp[key]["proteins"])), int(float(dict_temp[key]["carbohydrates"])), int(float(dict_temp[key]["fat"])) ]) return ind(instance) def data_sample_one(self): with open(self.file_path) as json_read: dict_temp = json.load(json_read) instance = [] for i in range(self.meals_per_day): key = random.sample(dict_temp.keys(), 1)[0] instance.append([ key, int(float(dict_temp[key]["calories"])), int(float(dict_temp[key]["proteins"])), int(float(dict_temp[key]["carbohydrates"])), int(float(dict_temp[key]["fat"])) ]) return instance[0] class GeneticAlgorithm(DataLoader_Mixin): """ Genetic Algorithm class""" def __init__(self, ind_size: int = 10): super().__init__() self.ind_size = ind_size # 0, because ID needs to be stored creator.create("FitnessMulti", base.Fitness, weights=(0, -1, -0.5, -0.5, -0.5)) creator.create("Individual", list, fitness=creator.FitnessMulti) self.toolbox = base.Toolbox() # Register functions self.toolbox.register("attribute", super().data_sample, ind=creator.Individual) self.toolbox.register("individual", tools.initRepeat, creator.Individual, self.toolbox.attribute, n=self.ind_size) self.toolbox.register("population", tools.initRepeat, list, self.toolbox.individual) self.toolbox.register("mate", tools.cxOnePoint) # no need to change self.toolbox.register("mutate", self._mutate, indpb=0.1) self.toolbox.register("select", tools.selTournament, tournsize=3) self.toolbox.register("evaluate", self._evaluate) def run_algorithm(self, file_path: str, json_file) -> dict(): super().data_load(file_path) super().model_input_load(json_file) pop = self.toolbox.population(n=100)[0] CXPB, MUTPB, NGEN = 0.5, 0.5, 5 # Evaluate the entire population fitnesses = list(map(self.toolbox.evaluate, pop)) for ind, fit in zip(pop, fitnesses): ind.fitness.values = fit for g in range(NGEN): # Select the next generation individuals offspring = self.toolbox.select(pop, len(pop)) #print(f"offspring: {offspring}") #print(f"\npop: {pop}") # Clone the selected individuals offspring = list(map(self.toolbox.clone, offspring)) # Apply crossover and mutation on the offspring for child1, child2 in zip(offspring[::2], offspring[1::2]): if random.random() < CXPB: self.toolbox.mate(child1, child2) del child1.fitness.values del child2.fitness.values for mutant in offspring: if random.random() < MUTPB: self.toolbox.mutate(mutant) del mutant.fitness.values # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in offspring if not ind.fitness.valid] fitnesses = map(self.toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit # The population is entirely replaced by the offspring pop[:] = offspring result_arr = [] for day in pop: results_arr_temp = {"calories" : 0, "proteins" : 0, "carbs" : 0, "fat" : 0} for meal in day: results_arr_temp["calories"] += meal[1] results_arr_temp["proteins"] += meal[2] results_arr_temp["carbs"] += meal[3] results_arr_temp["fat"] += meal[4] result_arr.append(results_arr_temp) print(f"result_array: {result_arr}") print(f"Desired intake: {[self.calories, self.proteins, self.carbohydrates, self.fat]}") return pop, self.convert_back_to_dict(pop) def convert_back_to_dict(self, result_arr): day = result_arr[0] ids = [] result_dict = [] for i in range(self.meals_per_day): id = day[i][0] result_dict.append(self.data[id]) return result_dict def run_fake_algorithm(self, file_path: str, json_file) -> dict(): super().data_load(file_path) super().model_input_load(json_file) keys = random.sample(list(self.data), self.meals_per_day) return [self.data[k] for k in keys] def _mutate(self, instance, indpb): indpb = [indpb] if len(indpb) == 1: indpb = list(indpb) * self.meals_per_day if len(indpb) != self.meals_per_day: print("Weird mutation error!") print(indpb) indpb = indpb[:1] * self.meals_per_day print(f"New probs: {indpb}") for i, proba in enumerate(indpb): rand_float = random.uniform(0, 1) if rand_float <= proba: instance_new = super().data_sample_one() instance[i] = instance_new return instance def _select(self, individuals, k, tournsize): pass def _evaluate(self, instance): cals = 0 prots = 0 carbs = 0 fats = 0 # Compute a squared error for i in range(self.meals_per_day): cals += instance[i][1] prots += instance[i][2] carbs += instance[i][3] fats += instance[i][4] cals = (self.calories - cals) ** 2 prots = (self.proteins - prots) ** 2 carbs = (self.carbohydrates - carbs) ** 2 fats = (self.fat - fats) ** 2 return (0, cals, prots, carbs, fats) if __name__ == "__main__": ga = GeneticAlgorithm() data_gen = DataLoader_Mixin() json_file = data_gen.data_load("./sample.json", True) result, _ = ga.run_algorithm("./data.json", json_file) result_arr = [] print(result) test = [] for day in result: results_arr_temp = {"calories" : 0, "proteins" : 0, "carbs" : 0, "fat" : 0} for meal in day: results_arr_temp["calories"] += meal[1] results_arr_temp["proteins"] += meal[2] results_arr_temp["carbs"] += meal[3] results_arr_temp["fat"] += meal[4] test.append(results_arr_temp) print(test) print(f"result_array: {result_arr}") print(f"Desired intake: {[ga.calories, ga.proteins, ga.carbohydrates, ga.fat]}")<file_sep>from flask import Flask, request, jsonify from ml.GeneticAlgorithm import GeneticAlgorithm import os, sys fileDir = os.path.dirname(os.path.abspath(__file__)) app = Flask(__name__) ga = GeneticAlgorithm() @app.route('/') def hello(): return fileDir + r"\ml\data.json" @app.route('/get_recipes', methods=['GET', 'POST']) def recipes_list(): content = request.json["data"] data = [] for i in range(len(content)): _, data_dict = ga.run_algorithm(fileDir + r"\ml\data.json", content[str(i)]) data.append(data_dict) return jsonify(data) if __name__ == '__main__': app.run(debug=True)
1bf434b4300810989d11d943f499196918ffb6e4
[ "Python" ]
2
Python
hacksussex-recipe-planner/team-flask
bace59192830e23d909b4f830e0439c98a7453b1
b9b1d4243f8e83fdb2c6e3d523fcd1f959feac5f
refs/heads/master
<file_sep>#include <stdio.h> #include <stdbool.h> #include <pthread.h> #include <semaphore.h> #include "buffer_circ.h" sem_t buffer_lock, items, huecos; struct Buffer_Circ { // Definir estructura Buffer_Circ int buffer[BUFSIZE]; int bufIN, bufOUT; int contador; }; // Iniciar bufer void initbuffer( struct Buffer_Circ *buff) { int i; sem_init (&buffer_lock,0,1); sem_init(&items,0,0); sem_init(&huecos,0,BUFSIZE); for(i=0; i<BUFSIZE; i++){ (*buff).buffer[i] = -1; } (*buff).bufIN = 0; (*buff).bufOUT = 0; (*buff).contador = 0; } // Get item int get_item(int* x, struct Buffer_Circ *buff) { int nxtOUT = (*buff).bufOUT % BUFSIZE; if( (*buff).contador > 0){ // Si el buffer no esta vacio sem_wait(&items); sem_wait(&buffer_lock); *x = (*buff).buffer[nxtOUT]; // Asignar resultado a x (*buff).bufOUT = (nxtOUT + 1) % BUFSIZE; // Actualizar bufOUT (*buff).contador = (*buff).contador - 1; // Actualizar contador sem_post(&buffer_lock); sem_post(&huecos); return 0; // Devolver 0 -> OK } else { // Si buffer esta lleno return -1; // Devolver -1 -> NOT OK } } // Put item int put_item(int x, struct Buffer_Circ *buff) { int nxtIN = (*buff).bufIN % BUFSIZE; if( (*buff).contador < BUFSIZE ){ // Si el buffer esta vacio sem_wait(&huecos); sem_wait(&buffer_lock); (*buff).buffer[nxtIN] = x; // Insertar x (*buff).bufIN = (nxtIN + 1) % BUFSIZE;// Actualizar bufIN (*buff).contador = (*buff).contador + 1; // Actualizar contador sem_post(&buffer_lock); sem_post(&items); return 0; // Devolver 0 -> OK } else { // Si buffer esta lleno return -1; // Devolver -1 -> NOT OK } } // Consultar si una variable Buffer_Circ está vacía char * bc_vacio(struct Buffer_Circ *buff){ if( (*buff).contador == 0 ) { return "True"; } else { return "False"; } } // Consultar si una variable Buffer_Circ está lleno char * bc_lleno(struct Buffer_Circ *buff){ if( (*buff).contador == BUFSIZE ) { return "True"; } else { return "False"; } } //PRINT void print (struct Buffer_Circ *buff){ // printf("OK? = %d\n", ok ); printf("bufIN = %d\n", (*buff).bufIN ); printf("bufOUT = %d\n", (*buff).bufOUT ); printf("contador = %d\n", (*buff).contador ); int i; for(i=0; i<BUFSIZE; i++){ printf("Posicion %d valor: %d\n", i, (*buff).buffer[i] ); } printf("------------------------------------------------------------\n"); } // Devolver número de elementos int num_elementos (struct Buffer_Circ *buff){ return (*buff).contador; } <file_sep>#include <stdio.h> #include <stdbool.h> #include <pthread.h> #include "buffer_circ.h" struct Buffer_Circ { // Definir estructura Buffer_Circ int buffer[BUFSIZE]; int bufIN, bufOUT; int contador; }; // Iniciar bufer void initbuffer( struct Buffer_Circ *buff) { /*CON MUTEX:*/ //------------------------------- pthread_mutex_lock(&buffer_lock); // Bloquear mutex int i; for(i=0; i<BUFSIZE; i++){ (*buff).buffer[i] = -1; } (*buff).bufIN = 0; (*buff).bufOUT = 0; (*buff).contador = 0; /*CON MUTEX:*/ pthread_mutex_unlock(&buffer_lock); // Desbloquear mutex } // Get item int get_item(int* x, struct Buffer_Circ *buff) { int nxtOUT = (*buff).bufOUT % BUFSIZE; /*CON MUTEX:*/ //------------------------------- pthread_mutex_lock(&buffer_lock); // Bloquear mutex if( (*buff).contador > 0){ // Si el buffer no esta vacio *x = (*buff).buffer[nxtOUT]; // Asignar resultado a x (*buff).bufOUT = (nxtOUT + 1) % BUFSIZE; // Actualizar bufOUT (*buff).contador = (*buff).contador - 1; // Actualizar contador /*CON MUTEX:*/ //------------------------------------ pthread_mutex_unlock(&buffer_lock); // Desbloquear mutex return 0; // Devolver 0 -> OK } else { // Si buffer esta lleno /*CON MUTEX:*/ pthread_mutex_unlock(&buffer_lock); // Desbloquear mutex return -1; // Devolver -1 -> NOT OK } } // Put item int put_item(int x, struct Buffer_Circ *buff) { int nxtIN = (*buff).bufIN % BUFSIZE; /*CON MUTEX:*/ //------------------------------ pthread_mutex_lock(&buffer_lock); // Bloquear mutex if( (*buff).contador < BUFSIZE ){ // Si el buffer esta vacio (*buff).buffer[nxtIN] = x; // Insertar x (*buff).bufIN = (nxtIN + 1) % BUFSIZE; // Actualizar bufIN (*buff).contador = (*buff).contador + 1; // Actualizar contador /*CON MUTEX:*/ //----------------------------- pthread_mutex_unlock(&buffer_lock); // Desbloquear mutex return 0; // Devolver 0 -> OK } else { // Si buffer esta lleno /*CON MUTEX:*/ //---------------------------- pthread_mutex_unlock(&buffer_lock); // Desbloquear mutex return -1; // Devolver -1 -> NOT OK } } // Consultar si una variable Buffer_Circ está vacía bool bc_vacio(struct Buffer_Circ *buff){ /*CON MUTEX:*/ //------------------------------ pthread_mutex_lock(&buffer_lock); // Bloquear mutex if( (*buff).contador == 0 ) { /*CON MUTEX:*/ //---------------------------- pthread_mutex_unlock(&buffer_lock); // Desbloquear mutex return true; } else { /*CON MUTEX:*/ //---------------------------- pthread_mutex_unlock(&buffer_lock); // Desbloquear mutex return false; } } // Consultar si una variable Buffer_Circ está lleno bool bc_lleno(struct Buffer_Circ *buff){ /*CON MUTEX:*/ //------------------------------ pthread_mutex_lock(&buffer_lock); // Bloquear mutex if( (*buff).contador == BUFSIZE ) { /*CON MUTEX:*/ //---------------------------- pthread_mutex_unlock(&buffer_lock); // Desbloquear mutex return true; } else { /*CON MUTEX:*/ //---------------------------- pthread_mutex_unlock(&buffer_lock); // Desbloquear mutex return false; } } //PRINT void print (struct Buffer_Circ *buff){ /*CON MUTEX:*/ //------------------------------ pthread_mutex_lock(&buffer_lock); // Bloquear mutex // printf("OK? = %d\n", ok ); printf("bufIN = %d\n", (*buff).bufIN ); printf("bufOUT = %d\n", (*buff).bufOUT ); printf("contador = %d\n", (*buff).contador ); int i; for(i=0; i<BUFSIZE; i++){ printf("Posicion %d valor: %d\n", i, (*buff).buffer[i] ); } printf("------------------------------------------------------------\n"); /*CON MUTEX:*/ //---------------------------- pthread_mutex_unlock(&buffer_lock); // Desbloquear mutex } // Devolver número de elementos int num_elementos (struct Buffer_Circ *buff){ /*CON MUTEX:*/ //------------------------------ pthread_mutex_lock(&buffer_lock); // Bloquear mutex /*CON MUTEX:*/ //---------------------------- pthread_mutex_unlock(&buffer_lock); // Desbloquear mutex return buff->contador; } <file_sep>/** * Para compilar teclea: gcc x.c -lpthread -o x */ #include <stdio.h> #include <pthread.h> #include <semaphore.h> #include <string.h> #include <unistd.h> #include <stdbool.h> #include "buffer_circ.c" #define INTPROD 20 #define INTCONS 25 #define NTHREADS 50 sem_t mutex, items, huecos; // Definir semaforos int ww; void *Productor( void *arg ) // Funcion productor { struct Buffer_Circ *buffer; // Crear buffer buffer = (struct Buffer_Circ*)arg; // Preparar el buffer int w, ins, err; for(w=0; w < INTPROD; w++){ // Bucle con interacciones de productor ins = ww+100; ww++; sem_wait(&huecos); // Esperar a huecos sem_wait(&mutex); // Esperar mutex err = put_item(ins,buffer); // Llamar a put_item if(err == -1){ // Si put item devuelve error printf("OP: %d. Error al insertar %d\n", w, ins); // Avisar del error printf("CONTADOR: %d\n", num_elementos(buffer)); // Mostrar el contador printf("------------------------------------------------------------\n"); sem_post(&mutex); // Incrementa mutex sem_post(&items); // Incrementa mutex } else { // Si no hay error printf("OP: %d. Se ha INSERTADO el numero: %d\n", w, ins); // print(buffer); printf("CONTADOR: %d\n", num_elementos(buffer)); // printf("Buffer lleno %s", bc_lleno(buffer) ? "true" : "false"); printf(" --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- \n"); sem_post(&mutex); sem_post(&items); } usleep(1000000); // Retraso 1seg } } void *Consumidor( void *arg ) // Funcion consumidor { struct Buffer_Circ *buffer; buffer = (struct Buffer_Circ*)arg; int w, err; int val; for(w=0; w < INTCONS; w++){ sem_wait(&items); sem_wait(&mutex); err = get_item(&val,buffer); if(err == -1){ printf("OP: %d. Error al obtener %d\n", w, val); printf("CONTADOR: %d\n", num_elementos(buffer)); printf("------------------------------------------------------------\n"); sem_post(&mutex); sem_post(&huecos); } else { printf("OP: %d. Se ha EXTRAIDO el numero: %d\n", w, val); //print(buffer); printf("CONTADOR: %d\n", num_elementos(buffer)); // printf("Buffer vacio? %s\n", bc_vacio(buffer) ? "true" : "false"); printf(" --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- \n"); sem_post(&mutex); sem_post(&huecos); } usleep(2000000); // Retraso 2seg } } int main() { int x, i, j; struct Buffer_Circ bc; // Crear puntero buff y buff struct Buffer_Circ *pbc; // Iniciar el semaforo sem_init(&mutex, 0, 1); //---------------------------------- sem_init(&items, 0, 0); sem_init(&huecos, 0, BUFSIZE); pbc = &bc; // Apuntar a buff initbuffer(pbc); // Iniciar buffer pthread_attr_t atrib; //Crear atributo pthread_t t_productor[NTHREADS], t_consumidor[NTHREADS]; // Crear array de threads pthread_attr_init( &atrib ); for(i=0;i<NTHREADS;i++){ pthread_create( &t_productor[i], &atrib, Productor, pbc); pthread_create( &t_consumidor[i], &atrib, Consumidor, pbc); } pthread_join( t_productor[NTHREADS-1], NULL); // Acabar con los threads pthread_join( t_consumidor[NTHREADS-1], NULL); printf("FIN DE LA APLICACIÓN\n"); return 0; }
07863fa2fcbc4d4a46f53725baec1126fe6a4bbc
[ "C" ]
3
C
mintos002/ProSistP4
29ed051c187f9856132fcdfe2495de499ed5b049
7b27dfb9cd33024cfb9801f08db8909ed98bc1fc
refs/heads/master
<file_sep>plugins { id 'com.android.application' id 'com.google.gms.google-services' } android { compileSdkVersion 29 buildToolsVersion "30.0.2" defaultConfig { applicationId "com.tdevelopments.whazzup" minSdkVersion 23 targetSdkVersion 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } buildFeatures { viewBinding true } } apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-android' dependencies { implementation "androidx.core:core-ktx:1.0.1" implementation 'androidx.browser:browser:1.2.0' implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.30" implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'com.google.android.material:material:1.3.0' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' implementation 'com.google.firebase:firebase-auth:20.0.2' implementation 'com.google.firebase:firebase-messaging:21.0.0' implementation 'com.google.android.gms:play-services-auth:19.0.0' implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'com.google.firebase:firebase-database:19.6.0' implementation 'com.google.firebase:firebase-storage:19.2.1' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' implementation 'com.google.android.material:material:1.3.0' implementation 'com.hbb20:ccp:2.4.5' implementation 'com.chaos.view:pinview:1.4.4' implementation 'com.ismaeldivita.chipnavigation:chip-navigation-bar:1.3.4' implementation 'de.hdodenhof:circleimageview:3.1.0' implementation 'com.github.bumptech.glide:glide:4.12.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0' implementation "com.github.pgreze:android-reactions:1.3" implementation 'com.devlomi:circularstatusview:1.0.1' implementation 'com.github.OMARIHAMZA:StoryView:1.0.2-alpha' implementation 'com.camerakit:camerakit:1.0.0-beta3.11' implementation 'com.camerakit:jpegkit:0.1.0' implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.0' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.0' }<file_sep>package com.tdevelopments.whazzup.Activity; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import com.tdevelopments.whazzup.R; public class IntroAct extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intro); ScreenSplash screenSplash = new ScreenSplash(); screenSplash.start(); } private class ScreenSplash extends Thread { @Override public void run() { try { sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } Intent intent = new Intent(IntroAct.this, UserAuth.class); startActivity(intent); finish(); } } }<file_sep>package com.tdevelopments.whazzup.Activity; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.bumptech.glide.Glide; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.tdevelopments.whazzup.R; import com.tdevelopments.whazzup.UserModel.User; import org.w3c.dom.Text; import de.hdodenhof.circleimageview.CircleImageView; public class editprof extends AppCompatActivity { TextView cancelBtn , saveBtn; User user; FirebaseAuth firebaseAuth; FirebaseStorage firebaseStorage; FirebaseDatabase firebaseDatabase; // views CircleImageView imageView; TextInputLayout editusername , edituserbaout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_editprof); // init view cancelBtn = findViewById(R.id.cancelBtn); imageView = findViewById(R.id.editprofimgview); editusername = findViewById(R.id.editprofusername); edituserbaout = findViewById(R.id.editprofuserabout); // firebase firebaseDatabase = FirebaseDatabase.getInstance(); firebaseStorage = FirebaseStorage.getInstance(); firebaseAuth = FirebaseAuth.getInstance(); // getting current user data getTheUserProfileDataToEdit(); cancelBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override public void onBackPressed() { super.onBackPressed(); finish(); } private void getTheUserProfileDataToEdit() { firebaseDatabase.getReference().child("users") .child(firebaseAuth.getUid()) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { user = snapshot.getValue(User.class); if (user != null) { Glide.with(getApplicationContext()).load(user.getProfileUrl()) .placeholder(R.drawable.user) .into(imageView); editusername.getEditText().setText(user.getUserName()); edituserbaout.getEditText().setText(user.getUserAbout()); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } }<file_sep>package com.tdevelopments.whazzup.Activity; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.google.android.material.textfield.TextInputLayout; import com.google.firebase.FirebaseApp; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.hbb20.CountryCodePicker; import com.tdevelopments.whazzup.R; public class UserAuth extends AppCompatActivity { TextInputLayout textInputLayout; Button buttonConfrm; CountryCodePicker countryCodePicker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_auth); // firebase initialize FirebaseApp.initializeApp(this); // layout view textInputLayout = findViewById(R.id.userCred); buttonConfrm = findViewById(R.id.confrm_Btn); countryCodePicker = findViewById(R.id.cpp); // check if user is logged in already userIsLoggedIn(); buttonConfrm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String userCreds = textInputLayout.getEditText().getText().toString().trim(); if (userCreds.isEmpty() ) { textInputLayout.setError("field can't be empty"); } else if (userCreds.length() > 10 || userCreds.length() < 10) { textInputLayout.setError("input should'nt exceed 10 digit"); } else { Intent intent = new Intent(UserAuth.this, SignIn.class); intent.putExtra("phoneNum", "+" + countryCodePicker.getSelectedCountryCode() + userCreds); startActivity(intent); finish(); } } }); } // if user already logged in farword to home private void userIsLoggedIn() { FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); if (firebaseUser != null ) { startActivity(new Intent(getApplicationContext(), MainActivity.class)); finish(); return; } } }<file_sep>package com.tdevelopments.whazzup.Activity; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.TextView; import com.google.android.material.textfield.TextInputLayout; import com.tdevelopments.whazzup.R; public class EncryptionSetup extends AppCompatActivity { RadioButton AESalgo , DESalgo , RSAalgo; TextInputLayout setEncryptionKey; TextView skipEncryption; Button setEncryptionBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_encryption_setup); AESalgo = findViewById(R.id.AESalgo); DESalgo = findViewById(R.id.DESalgo); RSAalgo = findViewById(R.id.RSAalgo); setEncryptionKey = findViewById(R.id.encryptionKeyData); setEncryptionBtn = findViewById(R.id.setEncryption); skipEncryption = findViewById(R.id.skipEncryption); // skip btn skipEncryption.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override public void onBackPressed() { super.onBackPressed(); finish(); } }<file_sep>package com.tdevelopments.whazzup.Activity; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.tdevelopments.whazzup.R; import com.tdevelopments.whazzup.UserModel.User; public class account_setting extends AppCompatActivity { FirebaseDatabase firebaseDatabase; FirebaseStorage firebaseStorage; FirebaseAuth firebaseAuth; TextView usernamecc , ediprofbtn , encryptionSetting ; ImageView userprofile , accbackbtn; Button buttonLogOut ; User user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_account_setting); // init view usernamecc = findViewById(R.id.usernameacc); userprofile = findViewById(R.id.userprofinsetting); buttonLogOut = findViewById(R.id.logoutBtn); accbackbtn = findViewById(R.id.accnackbtn); ediprofbtn = findViewById(R.id.editprofbtn); encryptionSetting = findViewById(R.id.encryptionSettings); // init firebase db , auth , storage firebaseDatabase = FirebaseDatabase.getInstance(); firebaseStorage = FirebaseStorage.getInstance(); firebaseAuth = FirebaseAuth.getInstance(); // encryption setting button encryptionSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(account_setting.this, EncryptionSetup.class); startActivity(intent); } }); ediprofbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(account_setting.this, editprof.class); startActivity(intent); } }); // logout btn buttonLogOut.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FirebaseAuth.getInstance().signOut(); Intent intent = new Intent(account_setting.this, UserAuth.class); startActivity(intent); finish(); } }); // back btn accbackbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(account_setting.this, MainActivity.class); startActivity(intent); finish(); } }); getTheUserProfileData(); } // get username and profile from firebase db private void getTheUserProfileData() { firebaseDatabase.getReference().child("users") .child(FirebaseAuth.getInstance().getUid()) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { user = snapshot.getValue(User.class); if (user != null) { usernamecc.setText(user.getUserName()); Glide.with(getApplicationContext()).load(user.getProfileUrl()) .placeholder(R.drawable.user) .into(userprofile); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } // on back press handling @Override public void onBackPressed() { super.onBackPressed(); Intent intent = new Intent(account_setting.this, MainActivity.class); startActivity(intent); finish(); } }
fd52e7db27dee6a3d40f9582c42f39ece62e7522
[ "Java", "Gradle" ]
6
Gradle
sudhanshuGt/whazzup
3ae2733ce2a793d4a2428d4bd26f535d299c4722
96b869c98a16ce0df8783d2d274c6d33c122e72a
refs/heads/main
<file_sep>const data = {}; const express = require('express'); const app = express(); const cors = require('cors'); app.use(cors()); const path = require('path'); const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({extended:true})); app.use(bodyParser.json()) app.use(express.static('website')); const port = 3000; app.listen(port, ()=>{ console.log(`Running on localhost : ${port}`); }) app.get('/all',recieveInfo) function recieveInfo(req,res){ res.send(data); } app.post('/add',postInfo) function postInfo(req,res){ console.log(req) data['todayDeaths'] = req.body.todayDeaths; data['todayCases'] = req.body.todayCases; data['todayRecovered'] = req.body.todayRecovered; data['critical'] = req.body.critical; data['country'] = req.body.country; data['deaths'] = req.body.deaths; data['cases'] = req.body.cases; data['active'] = req.body.active; data['recovered'] = req.body.recovered; res.send(data); }<file_sep>const api = "https://corona.lmao.ninja/v3/covid-19/countries/" const button = document.getElementById('search'); button.addEventListener('click',function(event){ event.preventDefault(); const country = document.getElementById('name').value; const url = api + country covidCases(url) .then(function(allData){ postInfo('/add',{ country, cases : allData.cases, todayCases: allData.todayCases, deaths: allData.deaths, todayDeaths: allData.todayDeaths, recovered: allData.recovered, todayRecovered : allData.todayRecovered, active: allData.active, critical : allData.critical }) }) .then(function(newData){ updateUI(); }) }); async function covidCases(url){ const data = await fetch(url); try{ const allData = data.json(); console.log(allData) return allData; } catch(error){ alert("error",error); } } async function postInfo(url='',givenData={}){ console.log(givenData) console.log(url); const info = await fetch(url,{ method:'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ country : givenData.country, cases : givenData.cases, todayCases: givenData.todayCases, deaths: givenData.deaths, todayDeaths: givenData.todayDeaths, recovered: givenData.recovered, todayRecovered : givenData.todayRecovered, active: givenData.active, critical : givenData.critical }) }) try{ const newData = info.json(); console.log(newData) return newData; } catch(error){ console.log("error",error) } } async function updateUI(){ const data = await fetch ('/all') try{ const allData = await data.json(); console.log(allData) if(allData.deaths == undefined){ document.getElementById('modal-body').style.display = "none" ; document.getElementById('error').innerHTML = "<strong>Please Enter a valid country</strong>" } else{ document.getElementById('modal-body').style.display = "block"; document.getElementById('error').innerHTML = "" document.getElementById('country').innerHTML = ': ' + allData.country; document.getElementById('cases').innerHTML = ': ' + allData.cases; document.getElementById('todayCases').innerHTML = ': ' + allData.todayCases; document.getElementById('deaths').innerHTML = ': ' + allData.deaths; document.getElementById('todayDeaths').innerHTML = ': ' + allData.todayDeaths; document.getElementById('recovered').innerHTML = ': ' + allData.recovered; document.getElementById('todayRecovered').innerHTML = ': ' + allData.todayRecovered; document.getElementById('active').innerHTML = ': ' + allData.active; document.getElementById('critical').innerHTML = ': ' + allData.critical; } } catch(error){ console.log("error",error); } } $('#search').click(function(){ console.log("hello") $('#bar').modal('toggle'); })<file_sep># Be-Safe-Covid-Tracker-App
382cdea2dc72a53a4e677197eab8287a67cc5b55
[ "JavaScript", "Markdown" ]
3
JavaScript
AbhishekGupta8630/Be-Safe-Covid-Tracker-App
ad38f1d809185a53ca974bb93ae780daf061a659
1d695bdde2bc0357fc2e5064adcab387f8343f98
refs/heads/master
<file_sep>public class OrderedSuperArray extends SuperArray{ public OrderedSuperArray(){ super(); } public OrderedSuperArray(int startingCapacity){ super(startingCapacity); } public OrderedSuperArray(String[] ary){ super(ary.length); for (int i = 0; i < ary.length; i++){ add(ary[i]); } } public void add(int index, String value){ add(value); } public boolean add(String element) { int i = findIndexBinary(element); if (i>=size()){ super.add(element); } else{ super.add(i,element); } return true; } public String set(int index, String element){ throw new UnsupportedOperationException(); } private int findIndex(String val){ for (int i = 0; i < size(); i++){ if (get(i).compareTo(val) > 0 ){ return i; } } return size(); } //CS DOJO HELP DID NOT DO ALONE// private int findIndexBinary(String val){ int start = 0; int end = size(); while (start != end){ if (get((start + end)/2).compareTo(val) > 0){ end = (start + end) / 2; } else { start = (start + end) / 2 + 1; } } return start; } //CS DOJO HELP// public int indexOfBinary(String element){ int start = 0; int end = size(); while (start != end){ if (get((start + end)/2+1).compareTo(element) > 0){ end = (start + end) / 2; } else if (get((start + end)/2 +1).equals(element)){ if (start == 0 || !(get((start + end) / 2 - 1).equals(element))){ return (start + end) / 2; } end = (start + end) / 2; start = (start + end) / 2 - 1; } else { start = (start + end) / 2 + 1; } } if (get(start)!=element){ return -1; } return start; } //CSDOJO HELP // public int lastIndexOfBinary(String element){ int start = indexOfBinary(element); int end = size(); while (start != end){ if (get((start + end)/2+1).compareTo(element) > 0){ end = (start + end) / 2; } else if (get((start + end)/2+1).equals(element)){ if (start == size() - 1 || !(get((start + end) / 2 + 1).equals(element))){ return (start + end) / 2; } end = (start + end) / 2; start = (start + end) / 2 - 1; } else { start = (start + end) / 2 + 1; } } if (get(start)!=element){ return -1; } return start; } } //CS DOJO HELP// <file_sep>import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TemperatureWindow extends JFrame implements ActionListener{ private Container pane; private JButton b,b2; private JCheckBox c; private JTextField t; public void actionPerformed(ActionEvent e){ Double doubleVal = Double.parseDouble(t.getText()); String s = e.getActionCommand(); if(s.equals("Convert")){ //button code here if( c.isSelected() ){ t.setText(Double.toString(FtoC(doubleVal))); }else{ t.setText(Double.toString(CtoF(doubleVal))); } } if(s.equals("Clear")){ //button code here t.setText(""); } } public TemperatureWindow() { this.setTitle("My first GUI"); this.setSize(500,80); this.setLocation(100,100); this.setDefaultCloseOperation(EXIT_ON_CLOSE); pane = this.getContentPane(); pane.setLayout(new FlowLayout()); b = new JButton("Convert"); b2 = new JButton("Clear"); c = new JCheckBox("Farenheit to Celsius? (If C to F, don't check)"); t = new JTextField(15); b.addActionListener(this); b2.addActionListener(this); t.addActionListener(this); c.addActionListener(this); pane.add(t); pane.add(c); pane.add(b); pane.add(b2); } public static void main(String[] args) { TemperatureWindow g = new TemperatureWindow(); g.setVisible(true); } public static Double CtoF(Double t){ return 9 * t / 5 + 32; } public static Double FtoC(Double t){ return 5 * (t - 32) / 9; } } <file_sep>public class CirculatingBook extends LibraryBook{ private String currentHolder; private String dueDate; public CirculatingBook(String _author, String _title, String _ISBN, String _callNumber){ super(_author,_title,_ISBN,_callNumber); currentHolder=null; dueDate=null; } public void checkout(String patron, String _dueDate){ currentHolder=patron; dueDate=_dueDate; } public void returned(){ currentHolder=null; dueDate=null; } public String circulationStatus(){ if (currentHolder != null){ return currentHolder+ " " + dueDate; } return "book available on shelves" ; } public String toString(){ if (currentHolder != null){ return super.toString()+ " " + currentHolder + " " + dueDate; } return super.toString(); } } <file_sep># MKS21X APCS HW Term 1 <file_sep>import java.util.*; import java.io.*; public class WordSearch{ private char[][]data; private Random randgen; private ArrayList<String> wordsToAdd; private ArrayList<String> wordsAdded; private int seed; private char[][] solution; public WordSearch(int rows,int cols,String filename){ this(rows, cols, filename, new Random().nextInt()); } public WordSearch(int rows,int cols,String filename, int seed){ data = new char[rows][cols]; randgen = new Random((long)seed); wordsToAdd = new ArrayList<String>(); wordsAdded = new ArrayList<String>(); solution = new char[rows][cols]; clear(); try{ Scanner in = new Scanner(new File(filename)); while(in.hasNext()){ wordsToAdd.add(in.next()); } } catch (FileNotFoundException e){ System.out.println("File not found: " + filename); } addAllWords(filename); for (int i = 0; i <data.length; i++){ for (int x = 0; x < data[i].length; x++){ solution[i][x] = data[i][x]; } } } public String getSolution(){ String ans = ""; for (int i = 0; i < data.length; i++){ for (int x = 0; x < data[i].length; x++){ ans += solution[i][x] + " "; } ans += "\n"; } return ans; } private void clear(){ for (int x = 0; x < data.length; x++){ for (int y = 0; y < data[x].length; y++){ data[x][y] = '_'; } } } public String toString(){ String ans = ""; for (int i = 0; i < data.length; i++){ for (int x = 0; x < data[i].length; x++){ ans += data[i][x] + " "; } ans += "\n"; } ans += (wordsAdded.toString()).substring(1,(wordsAdded.toString()).length() - 1); return ans; } // some of this gets confusing and people from other periods talked me through it// public boolean addWordHorizontal(String word,int row, int col){ try{ for (int i = 0; i < word.length(); i++){ if ((data[row][col + i] != word.charAt(i)) && (data[row][col + i] != '_')){ return false; } } for (int i = 0; i < word.length(); i++){ data[row][col + i] = word.charAt(i); } return true; } catch (IndexOutOfBoundsException a){ return false; } } public boolean addWordVertical(String word,int row, int col){ try{ for (int i = 0; i < word.length(); i++){ if ((data[row + i][col] != word.charAt(i)) && (data[row + i][col] != '_')){ return false; } } for (int i = 0; i < word.length(); i++){ data[row + i][col] = word.charAt(i); } return true; } catch(IndexOutOfBoundsException a){ return false; } } // this is basically horizontal + vertical combined// public boolean addWordDiagonal(String word,int row, int col){ try{ for (int i = 0; i < word.length(); i++){ if ((data[row + i][col + i] != word.charAt(i)) && (data[row + i][col + i] != '_')){ return false; } } for (int i = 0; i < word.length(); i++){ data[row + i][col + i] = word.charAt(i); } return true; } catch(IndexOutOfBoundsException a){ return false; } } //this was confusing and I needed a lot of help// private boolean addWord(int row, int col, String word, int xcor, int ycor){ word = word.toUpperCase(); if (xcor == 0 && ycor == 0){ return false; } try{ for (int x = 0; x < word.length(); x++){ if ((data[row - x * ycor][col + x * xcor] != word.charAt(x)) && (data[row - x * ycor][col + x * xcor] != '_')){ return false; } } for (int x = 0; x < word.length(); x++){ data[row - x * ycor][col + x * xcor] = word.charAt(x); } wordsAdded.add(word); wordsToAdd.remove(word); return true; } catch(ArrayIndexOutOfBoundsException a){ return false; } } // this was the worst and most confusing and I needed a lot of help// public boolean randomize(){ for (int i = 0; i < data.length; i++){ for (int x = 0; x < data[i].length; x++){ if (data[i][x] == '_'){ int num = (int)(((Math.random()) * 100) / 4 + 65); data[i][x] = (char)(num); } } } return true; } private boolean addAllWords(String filename){ int len = wordsToAdd.size() * 900; for (int i = 0; i < len; i++){ if (wordsToAdd.size() == 0){ return true; } int x = randgen.nextInt(3) - 1, y = randgen.nextInt(3) - 1, num = randgen.nextInt(wordsToAdd.size()), row = randgen.nextInt(data.length), col = randgen.nextInt(data[0].length); String wor = wordsToAdd.get(num); addWord(row, col, wor, x, y); wordsToAdd.remove(wor); } return true; } //Parse is hard to get to work, dojo help// public static void main(String[] args){ try { int row = Integer.parseInt(args[0]), col = Integer.parseInt(args[1]); if (row == 0 || col == 0){ throw new ArrayIndexOutOfBoundsException(); } if (args.length > 3){ int seed = Integer.parseInt(args[3]); WordSearch hey = new WordSearch(row, col, args[2], seed); if (args.length == 5 && args[4].equals("key")){ System.out.println(hey); } else{ hey.randomize(); System.out.println(hey); } } else{ WordSearch hey = new WordSearch(row, col, args[2]); hey.randomize(); System.out.println(hey); } } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Please enter: rows, columns, filename, seed (optional), answer (optional)"); } } } <file_sep>public class SuperArray{ private String[] data; private int size; //Phase 1// //Constructor// public SuperArray(){ data= new String[10]; size=0; } public SuperArray(int _startingcapacity){ data=new String[_startingcapacity]; size=0; } //1.// public void clear(){ data= new String[data.length]; size=0; } //2.// public int size(){ return size; } public boolean isEmpty(){ return size==0; } //3.// public boolean add(String element){ if(size==data.length){ resize(); } data[size]=element; size++; return true; } //4.// public String toString(){ //Needed some help with this kept getting errors// String temp = "["; for (int i=0; i< size;i++){ temp+=data[i]+","; } return temp.substring(0,temp.length()-2) + "]"; } //5.// public String get(int index){ if (index<0||index>=size){ throw new IndexOutOfBoundsException(); } else{ return data[index]; } } //6.// public String set(int index, String element){ String temp; if (index<0||index>=size){ throw new IndexOutOfBoundsException(); } else{ temp=data[index]; data[index]=element; if (index>=size){ size++; } return temp; } } //Phase 2// //7.// private void resize(){ String[] temp = new String[size*2]; for (int i=0;i<size;i++){ temp[i]=data[i]; } data = temp; } //Phase 3// //8.// public boolean contains(String element){ for (int i=0; i<size;i++){ if (data[i].equals(element)){ return true; } } return false; } //9.// public int indexOf(String element){ for (int i=0;i<size;i++){ if (data[i].equals(element)){ return i; } } return -1; } public int lastIndexOf(String element){ for (int i=size-1;i>=0;i--){ if (data[i].equals(element)){ return i; } } return -1; } //10.// public void add(int index, String element){ if (index<0||index>=size){ throw new IndexOutOfBoundsException(); } if(index==size){ add(element); } if (index<size){ resize(); size++; for (int i=size-1;i>index;i--){ data[i]=data[i-1]; } data[index]=element; } } //11.// public String remove(int index){ if (index < 0 || index >= size){ throw new IndexOutOfBoundsException(); } String temp = data[index]; String[] temp2 = new String[size - 1]; for (int i = 0; i < index; i++){ temp2[i] = data[i]; } size--; for (int i = index; i < size; i++){ temp2[i] = data[i+1]; } data=temp2; return temp; } //12.// public boolean remove(String element){ if(contains(element)){ remove(indexOf(element)); return true; } return false; } } //<NAME> from Period 10 helped me with the majority of Phase 3//
26cb568f2b17b96a8001c60f3f79d4831fb5720a
[ "Markdown", "Java" ]
6
Java
cliu5/MKS21X
b1946634d00adcdd62c72f406637a477acb7f251
0c34f9494ae01a45d9191bb4229c5c1580bac378
refs/heads/master
<file_sep>var el = document.getElementById("myTitle"); el.textContent = "5 Day Forecast for Seattle"; window.addEventListener("load", function() { var weather = [ "Friday", "May 13", "High: 82 ", "Low: 55", "Sunny", "Precip: 46%", "Saturday", "May 14", "High: 75", "Low: 52", "Cloudy", "Precip: 54%", "Sunday", "May 15", "High: 69", "Low: 52", "Showers", "Precip: 70%", "Monday", "May 16 ", "High: 69", "Low: 48", "Cloudy", "Precip: 62%", "Tuesday", "May 17", "High: 68", "Low: 48", "Showers", "Precip: 57%" ]; var row = 6, html = "<table><tr>"; for (var i = 0; i < weather.length; i++) { html += "<td>" + weather[i] + "</td>"; var next = i + 1; if (next % row == 0 && next != weather.length) { html += "</tr><tr>"; } } html += "</tr></table>"; document.getElementById("flightsTable").innerHTML = html; });<file_sep>$(document).ready(function () { $('li').css('margin', '10px'); $('li').attr('id', 'uw'); $('#p1 li').click(function () { console.log("$(this):" + $(this)); $(this).fadeOut(2000, function () { console.log("fadeout complete!") }); }); $('#p2 li').click(function () { console.log("$(this):" + $(this)); $(this).fadeOut(2000, function () { console.log("fadeout complete!") }); }); $('#p3 li').click(function () { console.log("$(this):" + $(this)); $(this).fadeOut(2000, function () { console.log("fadeout complete!") }); }); });<file_sep>var companyArray = []; companyArray.push(["Microsoft", 381.7, 86, 22, 128000]); companyArray.push(["Symetra", 2.7, 2.2, 254.2, 1400]); companyArray.push(["Micron", 38, 1.7, 300, 30400]); companyArray.push(["F5", 9.5, 1.6, 311, 3800]); companyArray.push(["Expedia", 10.8, 5.8, 398, 18210]); var el = document.getElementById("dataset"); function hitEvent() { buildTableBody(); } function buildTableBody() { companyArray.forEach(buildRows); } function buildRows(value, index) { if (index == 0) { el.innerHTML = rowBuilder(value); } else { el.innerHTML = el.innerHTML + rowBuilder(value); } } function rowBuilder(x) { console.log(x); var s = "<tr><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td></tr>"; s = s.replace("{1}", x[0]); s = s.replace("{2}", x[1]); s = s.replace("{3}", x[2]); s = s.replace("{4}", x[3]); s = s.replace("{5}", x[4]); return s; }<file_sep>$(document).ready(function () { // --------- jQuery Data Section --------- var book1 = { title: "Upheaval", author: "<NAME>", image: "5ce2ce15021b4c1a82430b93.jpeg" }; var book2 = { title: "Nine Pints", author: "<NAME>", image: "5ce2cef4021b4c6bdb0e4132.jpeg" }; var book3 = { title: "The Future of Capitalism", author: "<NAME>", image: "5ce2cfac021b4c1a305c2336.jpeg" }; var book4 = { title: "Presidents of War", author: "<NAME>", image: "5ce2cf74021b4c5cc800d1ce.jpeg" }; var book5 = { title: "A Gentleman in Moscow", author: "<NAME>", image: "5ce2cf2f021b4c6be22f5f55.jpeg" }; var books = new Array(); books.push(book1); books.push(book2); books.push(book3); books.push(book4); books.push(book5); var img_ref = { url: "https://i.insider.com/5a8de646391d948e008b4795?width=1300&format=jpeg&auto=webp", src: "https://bit.ly/338TQE6", alt: "Bill Gates", height: 150, width: 250 }; var reference = { url: "https://www.businessinsider.com/bill-gates-book-recommendations-summer-2019-5", src: "http://usat.ly/20hirO3", alt: "Gates Books", text: "BG:5 Books for Summer 2019" }; // --------- jQuery Data Section --------- $("a").attr(reference); $("img").attr(img_ref); // --------- jQuery Code Section --------- // apply bootstrap panel classes $('ol').addClass("list-group"); $('li').addClass("list-group-item"); $('li').each(function (i) { this.innerText = i + 1 + ") " + "\"" + books[i].title+ "\"" + " by " + books[i].author; // your code to pull values from the array of objects here }); $('li').each(function (i) { // add your row striping code here if (i % 2 != 0) { $(this).addClass("even"); } else { $(this).addClass("odd"); } }); // --------- jQuery Code Section --------- $(".odd").css("background", "lightgray"); $(".even").css("background", "white"); });<file_sep>function tableToArray(table_id) { myData = document.getElementById(table_id).rows; my_list = []; for (var i = 0; i < myData.length; i++) { el = myData[i].children; my_el = []; for (var j = 0; j < el.length; j++) { my_el.push(el[j].innerText); } my_list.push(my_el); } return my_list; } var theTable = tableToArray(myTable); console.log(theTable);<file_sep>//var todos = document.querySelector("ul"); var lis = document.querySelectorAll("li"); for(var i = 0; i < lis.length; i++){ let e = lis[i] console.log(i, e.id, e.tagName, e.textContent); lis[i].addEventListener("mouseover", function(){ console.log("mouseover"); if (document.getElementById(lis[i]) == "selected"){ document.getElementById(lis[i]).style.backgroundColor= "#4b2e83"; } }); lis[i].addEventListener("mouseout", function(){ console.log("mouseout"); }); lis[i].addEventListener("click", function(){ console.log("clicked"); }); } <file_sep>var myTitle = "Circles"; var el = document.getElementById("myTitle"); el.textContent = "Hello, " + myTitle; function calcCircleGeom(radius){ const pi = Math.PI; var area = pi * radius * radius; var diameter = radius * 2; var circum = 2 * pi * radius; var geometeries = [radius, area, diameter, circum]; return geometeries; } var rad1 = calcCircleGeom(13); var rad2 = calcCircleGeom(3); var rad3 = calcCircleGeom(25); var r1 = document.getElementById("rad1"); r1.textContent = "Circle 1: " + rad1; var r2 = document.getElementById("rad2"); r2.textContent = "Circle 2: " + rad2; var r3 = document.getElementById("rad3"); r3.textContent = "Circle 3: " + rad3;<file_sep>var state = "IDLE"; var cmd = ""; do { cmd = prompt("Enter a command:","run") switch (state){ case "IDLE":{ if (cmd==="run"){ alert("state1!" , state ="S1"); } } break; case "S1": { if (cmd==="next") { alert("state2!" , state ="S2"); } else if (cmd==="skip") { alert("state3!" , state ="S3"); } else if (cmd==="prev") { alert("state4!" , state ="S4"); } } break; } cmd=getUserInput(); } while (cmd !="exit");<file_sep>var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); var h = 600; var w = 600; var m = 20; var x = 100, y = 100, radius = 80, angle = 2 * Math.PI; context.arc(x, y, radius, 0, angle); context.lineWidth = 5; context.stroke(); // ============================== var x2 = 500, y2 = 500; context.moveTo(x2+radius,y2) context.arc(x2, y2, radius, 0, angle); context.lineWidth = 5; context.stroke(); context.moveTo(m, h / 3); context.lineTo(w - m, h / 3); context.lineWidth = 5; context.stroke(); context.moveTo(m, (2 * h) / 3); context.lineTo(w - m, (2 * h) / 3); context.lineWidth = 5; context.stroke(); context.moveTo(w / 3, m); context.lineTo(w / 3, w - m); context.lineWidth = 5; context.stroke(); context.moveTo((2 * w) / 3, m); context.lineTo((2 * w) / 3, w - m); context.lineWidth = 5; context.stroke(); context.moveTo(w / 3 + m, w / 3 + m); context.lineTo(w / 2 + 4 * m, w / 2 + 4 * m); context.lineWidth = 5; context.stroke(); context.moveTo(h / 3 + m, w / 2 + 4 * m); context.lineTo(w / 2 + 4 * m, h / 3 + m); context.lineWidth = 5; context.stroke();<file_sep><html> <head> <title>LINKS</title> </head> <body> <h1 id="top">Link to Specific Part of a Page</h1> <a href="#section1">Link to Section 1</a><br /> <a href="#section2">Link to Section 2</a><br /> <a href="#section3">Link to Section 3</a><br /> <a href="#section4">Link to Section 4</a><br /> <a href="#section5">Link to Section 5</a><br /> <a href="#section6">Link to Section 6</a><br /> <a href="#section7">Link to Section 7</a><br /> <a href="#section8">Link to Section 8</a><br /> <a href="#section9">Link to Section 9</a><br /> <a href="#section10">Link to Section 10</a><br /> <a href="mailto:<EMAIL>">e-mail me! </a> <h2 id="section1">Section 1</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Viverra maecenas accumsan lacus vel. Porttitor leo a diam sollicitudin. Cras fermentum odio eu feugiat pretium nibh ipsum consequat. Sed faucibus turpis in eu mi bibendum neque. Euismod quis viverra nibh cras.</p> <h2 id="section2">Section 2</h2> <p>Elementum facilisis leo vel fringilla est. Consequat interdum varius sit amet mattis vulputate enim nulla aliquet. Integer eget aliquet nibh praesent tristique magna sit. Accumsan in nisl nisi scelerisque. Eu tincidunt tortor aliquam nulla facilisi cras fermentum odio eu. Turpis cursus in hac habitasse. Erat pellentesque adipiscing commodo elit at.</p> <h2 id="section3">Section 3</h2> <p>A diam maecenas sed enim ut. Vel quam elementum pulvinar etiam non quam lacus suspendisse faucibus. Placerat in egestas erat imperdiet sed. Suscipit tellus mauris a diam maecenas sed enim</p> <h2 id="section4">Section 4</h2> <p>Vitae justo eget magna fermentum. Ante metus dictum at tempor. Arcu odio ut sem nulla. Sagittis vitae et leo duis ut diam quam. At lectus urna duis convallis convallis tellus. Nibh ipsum consequat nisl vel pretium lectus.</p> <h2 id="section5">Section 5</h2> <p>Non blandit massa enim nec. Ultricies mi eget mauris pharetra et ultrices neque. In fermentum posuere urna nec. Imperdiet nulla malesuada pellentesque elit eget gravida cum sociis natoque.</p> <h2 id="section6">Section 6</h2> <p>Vitae elementum curabitur vitae nunc sed velit dignissim sodales. Elementum nibh tellus molestie nunc non blandit massa enim. Id porta nibh venenatis cras. Lacus sed viverra tellus in hac habitasse platea dictumst.</p> <h2 id="section7">Section 7</h2> <p>Eget felis eget nunc lobortis mattis aliquam faucibus purus. Sed risus pretium quam vulputate dignissim. Libero volutpat sed cras ornare arcu. Velit euismod in pellentesque massa placerat. </p> <h2 id="section8">Section 8</h2> <p>Facilisis magna etiam tempor orci eu. Malesuada fames ac turpis egestas.</p> <h2 id="section9">Section 9</h2> <p>Ullamcorper eget nulla facilisi etiam. Sagittis vitae et leo duis ut diam quam nulla porttitor. Curabitur gravida arcu ac tortor dignissim convallis aenean.</p> <h2 id="section10">Section 10</h2> <p>Nibh tortor id aliquet lectus proin nibh nisl condimentum. Libero nunc consequat interdum varius sit amet mattis vulputate. </p> <p><a href="#top">Go to Top</a></p> </body> </html><file_sep># BIMD233 Winter 2020 BIMD233 <NAME> - [My website] (http://students.washington.edu/kavyai/) ``` ssh kavyai.virgil.u.washington.edu ``` <file_sep>var myTitle = "Javascript"; var el = document.getElementById("myTitle"); el.textContent = "Hello, " + myTitle +"!"; var username = prompt("Enter Username", "username"); var password = prompt("Enter Password", "<PASSWORD>"); document.getElementById("printUser").innerHTML = "Username: " + username; document.getElementById("printPass").innerHTML = "Password: " + password; console.log("Username: " + username) console.log("Password: " + password) function myUserPass(){ var username = prompt("Username", "username"); var password = prompt("Password", "<PASSWORD>"); document.getElementById("printUser").innerHTML = "Username: " + username; document.getElementById("printPass").innerHTML = "Password: " + <PASSWORD>; }<file_sep>var el = document.getElementById("myTitle"); el.textContent = "Flight Timings"; window.addEventListener("load", function() { var flights = [ "ASA1077", "A319", "Washington Dulles (KIAD)", "San Francisco (KSFO)", "Wed 07:32PM EST", "Wed 10:10PM PST", "ASA1088", "A320", "San Francisco (KSFO)", "Washington Dulles (KIAD)", "Wed 03:58PM PST ", "Wed 11:28PM EST", "ASA1097", "A320", "Washington Dulles (KIAD)", "Los Angeles (KLAX)", "Wed 05:06PM EST", "Wed 07:24PM PST", "ASA11", "B739 ", "Newark Liberty (KEWR)", "Seattle-Tacoma (KSEA)", "Wed 05:00PM EST ", "Wed 07:27PM PST", "ASA1113 ", "A320 ", "<NAME> (KOKC)", "Seattle-Tacoma (KSEA)", "Wed 05:40PM CST ", "Wed 07:11PM PST", ]; var row = 6, html = "<table><tr>"; for (var i = 0; i < flights.length; i++) { html += "<td>" + flights[i] + "</td>"; // Break into next row var next = i + 1; if (next % row == 0 && next != flights.length) { html += "</tr><tr>"; } } html += "</tr></table>"; document.getElementById("flightsTable").innerHTML = html; });
3c6cf237724afdaf81a99d434e014a465e0316dd
[ "JavaScript", "HTML", "Markdown" ]
13
JavaScript
k4vya/BIMD233
b54b2ce576337cc5804dd918706c886743d3b4b0
65293d3aea617b45c8c3355fc6f3ec161a6373fe
refs/heads/master
<repo_name>official71/Modern-as-a-service<file_sep>/hmwk1_aas/catalog/purchase.js listCars = []; listCart = []; function initCars() { listCars.push('{ "id":"01", "manu":"Lamborghini", "pic":"images/lambo-aventador.png", "name":"Aventador LP700-4", "price":"419000.00" }'); listCars.push('{ "id":"02", "manu":"McLaren", "pic":"images/mcl-p1.png", "name":"<NAME>", "price":"866000.00" }'); listCars.push('{ "id":"03", "manu":"Maserati", "pic":"images/mas-turismo.png", "name":"<NAME>", "price":"133000.00" }'); listCars.push('{ "id":"04", "manu":"Ferrari", "pic":"images/fer-laferrari.png", "name":"LaFerrari", "price":"1150000.00" }'); listCars.push('{ "id":"05", "manu":"Ford", "pic":"images/ford-mustang.png", "name":"<NAME>", "price":"34000.00" }'); listCars.push('{ "id":"06", "manu":"Cadillac", "pic":"images/cad-escalade.png", "name":"<NAME>", "price":"76000.00" }'); listCars.push('{ "id":"07", "manu":"Audi", "pic":"images/audi-r8.png", "name":"R8 Coupé V10", "price":"162000.00" }'); /* initialize chart */ for (var i = 0; i < listCars.length; i++) { listCart.push(0); } } function CalcTotal (amount) { var total = 0; for (var i = 0; i < listCart.length; i++) { if (listCart[i] == 0) { continue; } total += parseFloat(JSON.parse(listCars[i]).price) * listCart[i]; } total_str = total.toString(); amount.value = total_str; } function rmCart(id, keyWord, amount) { listCart[id.replace(keyWord, '')]--; /* re-style button */ var btn = document.getElementById(id); btn.className = "btn btn-primary"; btn.value = "Add to Cart"; btn.onclick = function() { addCart(this.id, "add", amount); CalcTotal(amount); }; } function addCart(id, keyWord, amount) { listCart[id.replace(keyWord, '')]++; /* re-style button */ var btn = document.getElementById(id); btn.className = "btn btn-danger"; btn.value = "Remove"; btn.onclick = function() { rmCart(this.id, "add", amount); CalcTotal(amount); }; } function formatPrice(str) { var lst = str.split("."); if (lst.length == 1) { lst.push("00"); } //add ',' var s = lst[0]; var ns = ""; for (var i = 0; i < s.length; i++) { ns += s[i]; if ((s.length - i)%3 == 1 && i != s.length - 1) { ns += ','; } } lst[0] = ns; return lst; } function drawTable() { initCars(); var tbl = document.getElementById('carTbl'); var amount = document.createElement("input"); amount.type="text"; amount.value = "0.00"; for (var i = 0; i < listCars.length+1; i++) { if(i!=listCars.length){ var obj = JSON.parse(listCars[i]); var row = tbl.insertRow(-1); //image var cell0 = row.insertCell(0); cell0.style.width = "30%"; var t0 = document.createElement("img"); t0.src = obj.pic; cell0.appendChild(t0); //description var cell1 = row.insertCell(1); cell1.style.width = "60%"; var t1 = document.createElement("span"); var price = formatPrice(obj.price); t1.innerHTML = "<h4>"+obj.name+"</br>" + "<small>by "+obj.manu+"</small></h4>" + "<h3>$ "+price[0]+"<small>"+price[1]+"</small></h3>"; cell1.appendChild(t1); //action var cell2 = row.insertCell(2); cell2.style.width = "10%"; var t2 = document.createElement("input"); t2.id = "add" + i; t2.type = "button"; t2.className = "btn btn-primary"; t2.value = "Add to Cart"; t2.style.width = "110px"; t2.onclick = function() { addCart(this.id, "add", amount); CalcTotal(amount); }; cell2.appendChild(t2); } else{ var row = tbl.insertRow(-1) var cell0 = row.insertCell(0); var total=document.createElement("span"); total.innerHTML = "<h3> "+"Total: "+"<small></h3>" cell0.appendChild(total) var cell1 = row.insertCell(1); var tmp = document.createElement("span"); cell1.appendChild(tmp); cell2=row.insertCell(2); cell2.append(amount); } } } function commitPurchase() { var total = 0; for (var i = 0; i < listCart.length; i++) { if (listCart[i] == 0) { continue; } total += parseFloat(JSON.parse(listCars[i]).price) * listCart[i]; } console.log("Total amount: "+total); /* // Immediate-Invoke function expression t2.onclick = (function(p){ // console.log(p); return function() { CalcTotal(p, amount); addCart(this.id, "add", p, amount); }; })(obj.price);*/ /* * Now need to save the chart data properly and redirect to payment service. * (Calculating the amount in the .js might not be a good idea) */ }<file_sep>/README.md # Modern-as-a-service
9613d48d735421aa9bc58b0c8a56d3b0d21b6443
[ "JavaScript", "Markdown" ]
2
JavaScript
official71/Modern-as-a-service
cfd68535e30f65b7b7f60a364fd47621c267a3a8
f36d9a38e70fb54a91ea9801f98fc2eac0fb2fa5
refs/heads/master
<file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login Form</title> </head> <body> {% block welcome %} <h1>Welcome to the Log in page</h1> {% endblock welcome %} {% block forms %} <form action="" method="post"> <p> <label for="username">Username</label> <input type="text" name="username"> </p> <p> <label for="pwd">Password</label> <input type="<PASSWORD>" name="pwd"> </p> <p> <input type="submit"> </p> </form> {% endblock %} {% if error %} <p>Error: {{ error }} </p> {% endif %} </body> </html><file_sep>"""<NAME> SDEV300 Lab 8 10/13/2020 This program functions as the back end for a web page which displays dog breed facts upon a user's registration and logging in """ import datetime import logging from flask import Flask, render_template, request, redirect, url_for, session from passlib.handlers.sha2_crypt import sha256_crypt app = Flask(__name__) app.secret_key = 'abc123' def check_pw(entered_pw): """This funciton checks the password for complexity using regex""" # minimum length 8 minfound = False lower_found = False upper_found = False digit_found = False if len(entered_pw) >= 8: minfound = True for i in entered_pw: if i.islower(): lower_found = True elif i.isupper(): upper_found = True elif i.isdigit: digit_found = True return minfound and lower_found and upper_found and digit_found def is_common(pw): """This function checks to see if the password is a commmon password""" content = None with open("C:\\Users\\adben\\Downloads\\CommonPassword.txt") as f: content = f.read().splitlines() print(content) return pw in content def get_current_date(): """This function returns the current date""" x = datetime.datetime.now() return x @app.route('/', methods=['GET', 'POST']) def index(): """This function returns the default registration page""" error = None if request.method == "POST": entered_name = request.form['username'] entered_pw = request.form['pwd'] if check_pw(entered_pw): hashed_pw = sha256_crypt.hash(entered_pw) with open('passfile.txt', "a") as f: f.writelines(hashed_pw + "\n") f.close() with open('usernames.txt', "a") as f: f.writelines(entered_name + "\n") f.close() session['user'] = entered_name return redirect((url_for('welcome'))) error = "You could not be registered" return render_template('register.html', error=error) @app.route('/welcome') def welcome(): """This function returns the Welcome page""" print(session) if 'user' in session: return render_template('welcome.html') else: print("User not logged in") return "Error. You need to log in" @app.route('/changepwd', methods=['post', 'get']) def changepwd(): """This function returns the change password page""" message = '' if request.method == "POST": newpwd = request.form.get('newPassword') oldpwd = request.form.get('password') #Confirm passwords match if newpwd.lower() != oldpwd.lower(): message = "Passwords do not match.. Please try again" print(request.remote_addr) app.logger.error("(" + request.remote_addr + ")" + message) elif is_common(newpwd): message = "password is comonly used. Try again" elif not check_pw(newpwd): message = "Password does not meet complexity standards" else: hashed_pw = sha256_crypt.hash(newpwd) with open('passfile.txt', "a") as f: f.writelines(hashed_pw + "\n") f.close() return render_template('welcome.html') return render_template('changepwd.html', message=message) @app.route('/logout') def logout(): """This function returns the logout page""" session.pop('user', None) return render_template('logout.html') @app.route('/dalmatian') def dalmatian(): """This function returns the dalmatian page""" if 'user' in session: print(session) return render_template('dalmatian.html', get_current_date=get_current_date()) else: print("User not logged in") return "Error. You need to log in" @app.route('/lab') def lab(): """This function returns the labrador page""" if 'user' in session: return render_template('lab.html') else: print("User not logged in") return "Error. You need to log in" @app.route('/dogTable') def dogTable(): """This function returns the dog table page""" if 'user' in session: return render_template('dogTable.html') else: print("User not logged in") return "Error. You need to log in" @app.route('/login', methods=['GET', 'POST']) def login(): """This function returns the login page""" error = None if request.method == "POST": #log usernames and passwords to txt file entered_name = request.form['username'] entered_pw = request.form['pwd'] f = open("usernames.txt", "r") f2 = open("passfile.txt", "r") lines = f.readlines() lines2 = f2.readlines() username_found = False pw_found = False for line in lines: if entered_name == line.strip(): username_found = True for line1 in lines2: if sha256_crypt.verify(entered_pw, line1.strip()): pw_found = True if username_found and pw_found: session['user'] = entered_name return render_template('welcome.html') else: error = "You could not be logged in" return render_template('login.html', error=error) @app.route('/beagle') def beagle(): """This function returns the beagle page""" if 'user' in session: return render_template('beagle.html') else: print("User not logged in") return "Error. You need to log in" if __name__ == "__main__": #configuring logging handler = logging.FileHandler('errors.log') formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setLevel(logging.ERROR) handler.setFormatter(formatter) app.logger.addHandler(handler) app.run()<file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>All About Dalmatians</title> <link rel="stylesheet" href="/static/style.css"> </head> <body> <header> <p>Date: {{ get_current_date }}</p> <h1>Dalmatians</h1> <h2> America's favorite Dog</h2> </header> <section> <ul> <li>Damlmatians are known internationally for their iconic spots</li> <li>One of the more energetic breeds, dalmatians need plenty of exercise</li> <li>While they have historically worked in firehouses, the dalmatian makes a great family pet</li> </ul> <a href="https://www.akc.org/dog-breeds/dalmatian/">Learn More about Dalmatians</a> </section> <section> <a href="/beagle"><p>Learn about beagles</p></a> <a href="/dogTable">Learn more about multiple breeds</a> <a href="/lab">Learn more about labs</a> </section> <aside> <img src="/static/dalmatian1.jpg" alt="Photo of Dalmatian"/> <img src="/static/dalmatian2.jpg" alt="Another Photo of Dalmatian"/> </aside> <footer><a href="/logout">Click here to logout</a></footer> </body> </html>
6a2278391390307aeecb783e968cfa840841703f
[ "Python", "HTML" ]
3
HTML
adamb97/WebFlaskDogProject
004dd884d09b91a01b8d55f8f04f2ca7915cf5fd
f3f17ace69aeed72366922f330c3fa5582e58d40
refs/heads/master
<repo_name>haunt99/Build-Dictionary-from-Spectacular-Literary-Context<file_sep>/README.md # Build a English Dictionary from Spectacular Literary ## Prerequisites + Python3 + PyPDF3 + pikepdf <file_sep>/features.py import os import glob import PyPDF3 as pyPDF import pikepdf #def extractContent(content = ""): #fileNames = [] #numPageBooks = [] #for files in glob.glob("Resource/*.pdf"): # fileNames.append(files) #for i in range(len(fileNames)): # pdfFile = open(fileNames[i], 'rb') # pdfFileReader = PdfFileReader(pdfFile) # if pdfFileReader.isEncrypted: # try: # pdfFileReader.decrypt('') # print('File Decrypted (PyPDF2)') # except: # command = ("copy "+ fileNames[i] + # " Resource/temp.pdf; qpdf --password='' --decrypt Resource/temp.pdf " + fileNames[i] # + "; del Resource/temp.pdf") # os.system(command) # print('File Decrypted (qpdf)') # pdfFile = open(fileNames[i]) # pdfFileReader = PdfFileReader(pdfFile) # else: # print('File Not Encrypted') # numPageBooks.append(pdfFileReader.numPages) #print numPageBooks # pdf = pikepdf.open('Resource/Outlaws of the Marshalso.pdf') # num_pages = len(pdf.pages) # pdf.save("out.pdf") # pdfReader = pyPDF.PdfFileReader("out.pdf") # print(pdfReader.numPages) def extractContent(content = ""): fileNames = [] # numPageBooks = [] pdfFileText = [] pdfFileReader = '' for files in glob.glob("Resource/*.pdf"): fileNames.append(files) for i in range(len(fileNames)): pdfFile = open(fileNames[i], 'rb') pdfFileReader = pyPDF.PdfFileReader(fileNames[i]) if(pdfFileReader.isEncrypted): pdfFile = pikepdf.open(fileNames[i]) #pdfFile.save(fileNames[i]) print("%s decrypted!" %fileNames[i]) pdfFileReader = pyPDF.PdfFileReader(fileNames[i]) #numPageBooks.append(pdfFileReader.numPages) pdfText = pdfFileReader.getPage(100) pdfText = pdfText.extractText() pdfFileText.append(pdfText) print(pdfFileText) extractContent()
2065effb0894043e5748f42d76d3172569cf3a98
[ "Markdown", "Python" ]
2
Markdown
haunt99/Build-Dictionary-from-Spectacular-Literary-Context
7e7c2bf33f39569d0f58929a65516026c480b0ea
c3b20b2d6196e1213d7bddfa7a5dcf559a0ff372
refs/heads/develop
<repo_name>UnbFeelings/unb-feelings-api<file_sep>/api/tests/subject_viewset_test.py # -*- coding: utf-8 -*- from rest_framework.test import APITestCase, APIClient from django.contrib.auth import get_user_model from api.models import Campus, Course, Subject from api.tests.helpers import create_test_user, TestCheckMixin UserModel = get_user_model() class SubjectTestCase(APITestCase, TestCheckMixin): def setUp(self): campus = Campus.objects.get_or_create(name="FGA")[0] self.course = Course.objects.get_or_create( name="ENGENHARIA", campus=campus)[0] Subject.objects.get_or_create(name="Calculo 1", course=self.course) Subject.objects.get_or_create(name="CB", course=self.course) def test_anyone_can_get_list(self): """ Anyone can make get requests to list """ client = APIClient() response = client.get('/api/subjects/') subjects = Subject.objects.all() self.assertEqual(200, response.status_code) self.assertEqual(len(subjects), len(response.data['results'])) def test_anyone_can_get_detail(self): """ Anyone can make get requests to detail """ client = APIClient() subject = Subject.objects.get(name="CB") response = client.get('/api/subjects/{}/'.format(subject.id)) self.assertEqual(200, response.status_code) self.assertEqual(subject.id, response.data['id']) @create_test_user(email="<EMAIL>", password="<PASSWORD>") def test_only_admin_can_create(self): """ Only admin members can create new """ client = APIClient() self._check_admin_only_access( client, lambda: client.post('/api/subjects/', { "name": "A new subject", "course": self.course.id }), "<EMAIL>", "testuser") user = UserModel.objects.get(email="<EMAIL>") user.is_staff = True user.save() token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.post('/api/subjects/', { "name": "A new subject", "course": self.course.id }) self.assertEqual(201, response.status_code) self.assertEqual("A new subject", response.data['name']) @create_test_user(email="<EMAIL>", password="<PASSWORD>") def test_only_admin_can_update(self): """ Only admin members can update """ subject = Subject.objects.get(name="CB") client = APIClient() self._check_admin_only_access( client, lambda: client.patch('/api/subjects/{}/'.format(subject.id), { "name": "other name" }), "<EMAIL>", "testuser") user = UserModel.objects.get(email="<EMAIL>") user.is_staff = True user.save() token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.patch('/api/subjects/{}/'.format(subject.id), {"name": "other name"}) self.assertEqual(200, response.status_code) self.assertEqual("other name", response.data['name']) @create_test_user(email="<EMAIL>", password="<PASSWORD>") def test_only_admin_can_delete(self): """ Only admin members can delete """ subject = Subject.objects.get(name="CB") client = APIClient() self._check_admin_only_access( client, lambda: client.delete('/api/subjects/{}/'.format(subject.id)), "<EMAIL>", "testuser") user = UserModel.objects.get(email="<EMAIL>") user.is_staff = True user.save() token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.delete('/api/subjects/{}/'.format(subject.id)) self.assertEqual(204, response.status_code) self.assertEqual(None, response.data) self.assertEqual(0, len(Subject.objects.all().filter(name="CB"))) <file_sep>/api/tests/__init__.py from .user_registration_view_test import UserRegistrationTestCase # noqa: F401 from .campus_viewset_test import CampusTestCase # noqa: F401 from .course_viewset_test import CourseTestCase # noqa: F401 from .subject_viewset_test import SubjectTestCase # noqa: F401 from .post_viewset_test import PostTestCase # noqa: F401 from .diagnosis_viewset_test import DiagnosisTestCase # noqa: F401 from .block_viewset_test import BlockTestCase from .support_viewset_test import SupportTestCase <file_sep>/api/tests/helpers.py from django.contrib.auth import get_user_model from rest_framework.test import APIClient from api.models import Campus, Course UserModel = get_user_model() def create_test_user(*, email: str, password: str): def my_decorator(target): def wrapper(*args, **kwds): campus = Campus.objects.get_or_create(name="FGA")[0] course = Course.objects.get_or_create( name="ENGENHARIA", campus=campus)[0] user = UserModel.objects.get_or_create( email=email, course=course)[0] user.set_password(password) user.save() return target(*args, **kwds) return wrapper return my_decorator class TestCheckMixin(): """ Mixin class that adds: * a check to logged user only on routes * a check to admin only on routes * a get user token method """ def _get_user_token(self, email, password): client = APIClient() response = client.post("/api/token-auth/", { 'email': email, 'password': <PASSWORD> }) return response.data['token'] def _check_only_logged_user_access(self, client, client_action): response = client_action() self.assertEqual(401, response.status_code) self.assertEqual( "As credenciais de autenticação não foram fornecidas.", response.data['detail']) def _check_admin_only_access(self, client, client_action, user_email, user_password): self._check_only_logged_user_access(client, client_action) token = self._get_user_token(user_email, user_password) client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client_action() self.assertEqual(403, response.status_code) self.assertEqual("Você não tem permissão para executar essa ação.", response.data['detail']) <file_sep>/api/views/support_views.py # from rest_framework.viewsets import ModelViewSet from rest_framework.response import Response from rest_framework.decorators import list_route from rest_framework import viewsets, mixins from rest_framework.generics import CreateAPIView, DestroyAPIView from api.serializers import SupportSerializer from api.models import Support from api.permissions import GetSupportPermission class SupportViewSet(viewsets.GenericViewSet): """Description: SupportViewSet. API endpoint that allows support to be viewed, created, deleted or edited. """ queryset = Support.objects.all() serializer_class = SupportSerializer permission_classes = (GetSupportPermission, ) def destroy(self, request, pk=None): """ API endpoint that allows one support to be deleted by user. """ response = super(SupportViewSet, self).destroy(request, pk) return response @list_route( permission_classes=[GetSupportPermission], methods=['GET'], url_path='to_student' ) def get_support_made_to_student(self,request,id=None): """ API endpoint that allows one student see all supports that have been made to him. --- Response example: ``` { "count": 2, "next": null, "previous": null, "results": [ { "id": 7, "message": "Yes you can", "created_at": "2018-07-04T15:39:25.316130-03:00", "student_from": 8, "student_to": 8 }, { "id": 6, "message": "Teste 1", "created_at": "2018-07-04T15:39:12.854664-03:00", "student_from": 8, "student_to": 8 } ] } ``` """ supports = Support.objects.filter(student_to=request.user).order_by('-created_at') supports_paginated = self.paginate_queryset(supports) if supports_paginated is not None: serializer = SupportSerializer( data=supports_paginated, many=True, context={'request': request}) serializer.is_valid() return self.get_paginated_response(serializer.data) else: data = SupportSerializer( data=supports, many=True, context={'request': request}) data.is_valid() return Response(data.data) @list_route( permission_classes=[GetSupportPermission], methods=['GET'], url_path='from_student' ) def get_support_made_from_student(self,request,id=None): """ API endpoint that allows one student see all supports that he made. --- Response example: ``` { "count": 2, "next": null, "previous": null, "results": [ { "id": 7, "message": "Yes you can", "created_at": "2018-07-04T15:39:25.316130-03:00", "student_from": 8, "student_to": 8 }, { "id": 6, "message": "Teste 1", "created_at": "2018-07-04T15:39:12.854664-03:00", "student_from": 8, "student_to": 8 } ] } ``` """ supports = Support.objects.filter(student_from=request.user).order_by('-created_at') supports_paginated = self.paginate_queryset(supports) if supports_paginated is not None: serializer = SupportSerializer( data=supports_paginated, many=True, context={'request': request}) serializer.is_valid() return self.get_paginated_response(serializer.data) else: data = SupportSerializer( data=supports, many=True, context={'request': request}) data.is_valid() return Response(data.data) class SupportCreate(CreateAPIView, DestroyAPIView): queryset = Support.objects.all() serializer_class = SupportSerializer permission_classes = (GetSupportPermission, )<file_sep>/api/views/post_views.py from django.shortcuts import get_object_or_404 from django.contrib.auth.models import AnonymousUser from django.db.models.query import QuerySet from rest_framework.viewsets import ModelViewSet from rest_framework.decorators import api_view, list_route from rest_framework.response import Response from api.serializers import PostSerializer, SubjectEmotionsCountSerializer from api.models import Post, Student, Subject, SubjectEmotionsCount, Tag from api.permissions import PostPermission class PostViewSet(ModelViewSet): """Description: PostViewSet. API endpoint that allows posts to be viewed, created, deleted or edited. """ queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = (PostPermission, ) def list(self, request): """ API endpoint that allows all posts to be viewed. --- Response example: ``` { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "author": 1, "subject": { "id": 15, "name": "Calculo 1", "course": 1 }, "tag": [ { "id": 1, "description": "TAG1", "quantity": 2 } ], "emotion":"g", "created_at": "2018-05-23T00:20:22.344509Z" } ] } ``` """ if not isinstance(request.user, AnonymousUser): filtered_posts = request.user.filter_blocked_posts(self.queryset) posts_paginated = self.paginate_queryset(filtered_posts) else: posts_paginated = self.paginate_queryset(self.queryset) if posts_paginated is not None: serializer = PostSerializer( data=posts_paginated, many=True, context={'request': request}) serializer.is_valid() return self.get_paginated_response(serializer.data) else: data = PostSerializer( data=filtered_posts, many=True, context={'request': request}) data.is_valid() return Response(data.data) def create(self, request): """ API endpoint that allows posts to be created. --- Body example: ``` { "count": 1, "next": null, "previous": null, "results": [ { "author": <EMAIL>, "subject": 1, "tag": [ { "id": 1, "description": "TAG1", "quantity": 2 } ], "emotion": "b", "created_at": "2018-05-23T00:20:22.344509Z" } ] } ``` Response example: ``` { "count": 1, "next": null, "previous": null, "results": [ { "id": 2, "author": 1, "subject": { "id": 1, "name": "Calculo 1", "course": 1 }, "tag": [ { "id": 1, "description": "TAG1", "quantity": 2 } ], "emotion":"b", "created_at": "2018-05-23T00:20:22.344509Z" } ] } ``` """ response = super(PostViewSet, self).create(request) if not response.data.get('created_at', None): return response post = Post.objects.get(pk=response.data.get('id')) tags = request.data.get('tags', "") response.data['tag'] = [] for tag_text in tags.split('#'): description = tag_text.strip().replace(',', "") if len(tag_text) > 0: tag, created = Tag.objects.get_or_create( description=description) post.tag.add(tag) post.save() response.data['tag'].append(tag.id) return response def destroy(self, request, pk=None): """ API endpoint that allows posts to be deleted. """ response = super(PostViewSet, self).destroy(request, pk) return response def retrieve(self, request, pk=None): """ API endpoint that allows a specific post to be viewed. --- Response example: ``` { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "author": 1, "subject": { "id": 15, "name": "Calculo 1", "course": 1 }, "tag": [ { "id": 1, "description": "TAG1", "quantity": 2 } ], "emotion": "g", "created_at": "2018-05-23T00:20:22.344509Z" } ] } ``` """ if not isinstance(request.user, AnonymousUser): blocked_users = request.user.blocks() user = Post.objects.get(id=pk).author if user in blocked_users: return Response(None) response = super(PostViewSet, self).retrieve(request, pk) return response def partial_update(self, request, pk=None, **kwargs): """ API endpoint that allows a post to be partial edited. --- Body example: ``` { "content": "<NAME>", } ``` Response example: ``` { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "author": 1, "content": "<NAME>", "subject": { "id": 15, "name": "Calculo 1", "course": 1 }, "tag": [ { "id": 1, "description": "TAG1", "quantity": 2 } ], "emotion": "g", "created_at": "2018-05-23T00:20:22.344509Z" } ] } ``` """ response = \ super(PostViewSet, self).partial_update(request, pk, **kwargs) return response def update(self, request, pk=None, **kwargs): """ API endpoint that allows a post to be edited. --- Body example: ``` { "count": 1, "next": null, "previous": null, "results": [ { "author": <EMAIL>, "content": "Pior aula do mundo", "subject": { "id": 15, "name": "Calculo 1", "course": 1 }, "tag": [ { "id": 1, "description": "TAG1", "quantity": 2 } ], "emotion": "b", "created_at": "2018-05-23T00:20:22.344509Z" } ] } ``` Response example: ``` { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "author": <EMAIL>, "content": "Pior aula do mundo", "subject": { "id": 15, "name": "Calculo 1", "course": 1 }, "tag": [ { "id": 1, "description": "TAG1", "quantity": 2 } ], "emotion": "b", "created_at": "2018-05-23T00:20:22.344509Z" } ] } ``` """ response = super(PostViewSet, self).update(request, pk, **kwargs) return response @list_route( permission_classes=[], methods=['GET'], url_path='user/(?P<user_id>\d+)') def user_posts(self, request, user_id=None): """ API endpoint that gets the posts of a given user --- The "content" camp don't show up if you're not the logged user --- Response example: ``` { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "author": <EMAIL>, "content": "Pior aula do mundo", "subject": { "id": 15, "name": "Calculo 1", "course": 1 }, "tag": [ { "id": 1, "description": "TAG1", "quantity": 2 } ], "emotion": "b", "created_at": "2018-05-23T00:20:22.344509Z" } ] } ``` """ user = get_object_or_404(Student, pk=user_id) posts = Post.objects.filter(author=user) posts_paginated = None if not isinstance(request.user, AnonymousUser): blocked_users = request.user.blocks() if user in blocked_users: return Response(None) else: posts_paginated = self.paginate_queryset(posts) if posts_paginated is not None: serializer = PostSerializer( data=posts_paginated, many=True, context={'request': request}) serializer.is_valid() return self.get_paginated_response(serializer.data) else: data = PostSerializer( data=posts, many=True, context={'request': request}) data.is_valid() return Response(data.data) @list_route( permission_classes=[], methods=['GET'], url_path='subject/(?P<subject_id>\d+)') def subject_posts(self, request, subject_id=None): """ API endpoint that getts the posts of a given subject --- Response example: ``` { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "author": hpedro1195<EMAIL>, "subject": { "id": 15, "name": "<NAME>", "course": 1 }, "tag": [ { "id": 1, "description": "TAG1", "quantity": 2 } ], "emotion": "b", "created_at": "2018-05-23T00:20:22.344509Z" } ] } ``` """ subject = get_object_or_404(Subject, pk=subject_id) posts = Post.objects.all().filter(subject=subject) if not isinstance(request.user, AnonymousUser): filtered_posts = request.user.filter_blocked_posts(posts) posts_paginated = self.paginate_queryset(filtered_posts) else: posts_paginated = self.paginate_queryset(posts) if posts_paginated is not None: serializer = PostSerializer( data=posts_paginated, many=True, context={'request': request}) serializer.is_valid() return self.get_paginated_response(serializer.data) else: data = PostSerializer( data=posts, many=True, context={'request': request}) data.is_valid() return Response(data.data) @list_route( permission_classes=[], methods=['GET'], url_path='subjects_posts_count') def subjects_posts(self, request): """ Returns posts's emotion counting for all subjects that have at least one post about it --- Response example: ``` [ { "subject_name": Calculo 1, "good_count": 13, "good_count": 2, } ] ``` """ subjects_emotions_count_list = [] for subject in Subject.objects.all(): emotion_count = get_subject_emotions_count(subject) if not emotion_count.empty(): subjects_emotions_count_list.append(emotion_count) serializer = SubjectEmotionsCountSerializer( subjects_emotions_count_list, many=True) return Response(serializer.data) def get_subject_emotions_count(subject): assert isinstance(subject, Subject) subject_posts = Post.objects.filter(subject=subject) subject_emotions = [post.emotion for post in subject_posts] from collections import Counter count = Counter(subject_emotions) for emotion_choice in Post.EMOTIONS: emotion = emotion_choice[0] if emotion not in count: count[emotion] = 0 subject_emotions_count = SubjectEmotionsCount( subject.name, good_count=count['g'], bad_count=count['b']) return subject_emotions_count <file_sep>/api/tests/post_viewset_test.py # -*- coding: utf-8 -*- from rest_framework.test import APITestCase, APIClient from django.contrib.auth import get_user_model from api.models import Campus, Course, Subject, Post from api.tests.helpers import create_test_user, TestCheckMixin UserModel = get_user_model() class PostTestCase(APITestCase, TestCheckMixin): @create_test_user(email="<EMAIL>", password="<PASSWORD>") def setUp(self): campus = Campus.objects.get_or_create(name="FGA")[0] course = Course.objects.get_or_create( name="ENGENHARIA", campus=campus)[0] self.subject = Subject.objects.get_or_create( name="Calculo 1", course=course)[0] self.ted = Subject.objects.get_or_create( name="Teoria da eletronica digital", course=course)[0] self.ped = Subject.objects.get_or_create( name="Pratica da eletronica digital", course=course)[0] self.user = UserModel.objects.get(email="<EMAIL>") Post.objects.get_or_create( content="<NAME> !", author=self.user, subject=self.subject, emotion="g")[0] Post.objects.get_or_create( content="Good good!", author=self.user, subject=self.ted, emotion="g")[0] Post.objects.get_or_create( content="Bad Bad!", author=self.user, subject=self.ted, emotion="b")[0] def test_anyone_can_get_list(self): """ Anyone can make get requests to list """ client = APIClient() response = client.get('/api/posts/') subjects = Subject.objects.all() self.assertEqual(200, response.status_code) self.assertEqual(len(subjects), len(response.data['results'])) def test_anyone_can_get_detail(self): """ Anyone can make get requests to detail """ client = APIClient() post = Post.objects.get(content="Allahu Akbar !") response = client.get('/api/posts/{}/'.format(post.id)) self.assertEqual(200, response.status_code) self.assertEqual(post.id, response.data['id']) def test_user_create_posts(self): client = APIClient() data = { "content": "FooBarIsALie", "author": self.user.id, "subject": self.subject.id, "emotion": "b", } self._check_only_logged_user_access( client, lambda: client.post('/api/posts/', data)) token = self._get_user_token("<EMAIL>", "test<PASSWORD>") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.post('/api/posts/', data) self.assertEqual(201, response.status_code) self.assertEqual(data["author"], response.data['author']) self.assertEqual(data["subject"], response.data['subject']['id']) self.assertEqual(data["emotion"], response.data['emotion']) def test_user_update_posts(self): client = APIClient() data = { "emotion": "b", } post = Post.objects.get(content="Allahu Akbar !") self._check_only_logged_user_access( client, lambda: client.patch('/api/posts/{}/'.format(post.id), data)) token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.patch('/api/posts/{}/'.format(post.id), data) self.assertEqual(200, response.status_code) self.assertEqual("b", response.data['emotion']) self.assertEqual(post.id, response.data['id']) def test_only_admin_can_delete(self): post = Post.objects.get(content="Allahu Akbar !") client = APIClient() self._check_only_logged_user_access( client, lambda: client.delete('/api/posts/{}/'.format(post.id))) token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.delete('/api/posts/{}/'.format(post.id)) self.assertEqual(204, response.status_code) self.assertEqual(None, response.data) self.assertEqual( 0, len(Post.objects.all().filter(content="Allahu Akbar !"))) def test_user_posts_have_content(self): """ When getting post data, if it is the data from the logged user, content will be avalible """ client = APIClient() token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.get('/api/posts/user/{}/'.format(self.user.id)) self.assertEqual(200, response.status_code) for post in response.data['results']: self.assertEqual(True, 'content' in post) def test_user_posts_dont_have_content(self): """ When getting post data, if it is not the data from the logged user, content will not be avalible """ client = APIClient() response = client.get('/api/posts/user/{}/'.format(self.user.id)) self.assertEqual(200, response.status_code) for post in response.data: self.assertEqual(False, 'content' in post) def test_subjects_emotions_subjects_with_posts(self): """ Only subjects with at least one post about it should be present in the response JSON """ client = APIClient() endpoint = '/api/posts/subjects_posts_count/' response = client.get(endpoint) content = response.json() expected_json = { 'subject_name': 'Teoria da eletronica digital', 'good_count': 1, 'bad_count': 1 } self.assertEqual(200, response.status_code) self.assertIn(expected_json, content) def test_subjects_emotions_subjects_without_posts(self): """ A subject without at least one post about it shouldn't be present in the response JSON """ client = APIClient() endpoint = '/api/posts/subjects_posts_count/' response = client.get(endpoint) content = response.json() subject_name ='Pratica da eletronica digital' self.assertTrue(Subject.objects.filter(name=subject_name)) expected_json = { 'subject_name': subject_name, 'good_count': 0, 'bad_count': 0 } self.assertEqual(200, response.status_code) self.assertNotIn(expected_json, content) <file_sep>/unbfeelings/config/security.py """ secret key to the project. https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ """ import os SECRET_KEY = os.getenv( 'SECRET_KEY', '<KEY> ) <file_sep>/api/management/commands/populatedb.py from django.core.management.base import BaseCommand, CommandError from api.models import Subject, Course, Campus import xml.etree.ElementTree as ET import os class Command(BaseCommand): help = 'Populates the subjects table' def handle(self, *args, **options): dirr = os.path.dirname(__file__) filename = os.path.join(dirr, '../../fixtures/disciplinas.xml') tree = ET.parse(filename) root = tree.getroot() subjects = [] subject = Subject.objects.all() self.create_campuses() self.create_courses() if subject.count() <= 0: for child in root: for v in child: c = Subject(name=v.text, course=Course.objects.get(name=v.tag)) match = [c1.name for c1 in subjects if c1.name == c.name] if match == []: subjects.append(c) if len(subjects): Subject.objects.bulk_create(subjects) self.stdout.write("Subjects added!") else: self.stdout.write("No subjects added. Please remove already inserted subjects from db!") def create_campuses(self): c = Campus.objects.all() if c.count() <= 0: campuses_name = ["FGA" ,"FCE", "DARCY RIBEIRO", "FUP"] campuses = [] for name in campuses_name: campus = Campus(name=name) campuses.append(campus) Campus.objects.bulk_create(campuses) self.stdout.write("Campuses added!") else: self.stdout.write("No campuses added. Please remove already inserted campuses from db!") def create_courses(self): c = Course.objects.all() if c.count() <= 0: courses_name = ["ENGENHARIA" ,"SOFTWARE", "ELETRONICA", "AEROESPACIAL", "ENERGIA", "AUTOMOTIVA"] courses = [] for name in courses_name: course = Course(name=name, campus=Campus.objects.get(pk=1)) # fix logic to add other campuses courses courses.append(course) Course.objects.bulk_create(courses) self.stdout.write("Courses added!") else: self.stdout.write("No courses added. Please remove already inserted courses from db!") <file_sep>/api/views/student_views.py from rest_framework import status from rest_framework.viewsets import ModelViewSet from rest_framework.response import Response from rest_framework.decorators import api_view, list_route from django.shortcuts import get_object_or_404 from api.serializers import StudentSerializer, CourseSerializer from api.models import Student, Course from api.permissions import StudentPermissions, BlockPermissions import json import random class StudentViewSet(ModelViewSet): """Description: StudentViewSet. API endpoint that allows users to be viewed, created, deleted or edited. """ queryset = Student.objects.all() serializer_class = StudentSerializer permission_classes = (StudentPermissions, ) def list(self, request): """ API endpoint that allows all users to be viewed. --- Response example: ``` { "count": 2, "next": null, "previous": null, "results": [ { "id": 1, "email": "<EMAIL>", "course": { "id": 1, "name": "Engenharia de Software", "campus": 1 } }, { "id": 2, "email": "<EMAIL>", "course": { "id": 3, "name": "Engenharia Eletrônica", "campus": 1 } } ] } ``` """ response = super(StudentViewSet, self).list(request) for student in response.data['results']: course = Course.objects.get(id=student['course']) course_serializer = CourseSerializer(course) student['course'] = course_serializer.data return response def create(self, request): """ API endpoint that allows users to be created. --- Body example: ``` { "email": "<EMAIL>", "password": "<PASSWORD>", "course": 1 } ``` Response example: ``` { "id": 1, "email": "<EMAIL>", "course": { "id": 1, "name": "Engenharia de Software", "campus": 1 } } ``` """ response = super(StudentViewSet, self).create(request) course = Course.objects.get(id=response.data['course']) course_serializer = CourseSerializer(course) response.data['course'] = course_serializer.data return response def destroy(self, request, pk=None): """ API endpoint that allows users to be deleted. """ response = super(StudentViewSet, self).destroy(request, pk) return response def retrieve(self, request, pk=None): """ API endpoint that allows a specific user to be viewed. --- Response example: ``` { "id": 1, "email": "<EMAIL>", "course": { "id": 1, "name": "Engenharia de Software", "campus": 1 } } ``` """ response = super(StudentViewSet, self).retrieve(request, pk) course = Course.objects.get(id=response.data['course']) course_serializer = CourseSerializer(course) response.data['course'] = course_serializer.data return response def partial_update(self, request, pk=None, **kwargs): """ API endpoint that allows a user to be partial edited. --- Body example: ``` { "email": "<EMAIL>" } ``` Response example: ``` { "id": 1, "email": "<EMAIL>", "course": { "id": 1, "name": "Engenharia de Software", "campus": 1 } } ``` """ response = \ super(StudentViewSet, self).partial_update(request, pk, **kwargs) return response def update(self, request, pk=None, **kwargs): """ API endpoint that allows a user to be edited. --- Body example: ``` { "email": "<EMAIL>", "password": "<PASSWORD>", "course": 3 } ``` Response example: ``` { "id": 1, "email": "<EMAIL>", "course": { "id": 3, "name": "<NAME>", "campus": 1 } } ``` """ response = super(StudentViewSet, self).update(request, pk, **kwargs) course = Course.objects.get(id=response.data['course']) course_serializer = CourseSerializer(course) response.data['course'] = course_serializer.data return response @list_route( permission_classes=[BlockPermissions], methods=['GET'], url_path='blocks') def user_blocks(self, request, user_id=None): """ API endpoint that gets all users blockeds from a user """ blockeds = self.request.user.list_blocked_users() blockeds_paginated = self.paginate_queryset(blockeds) if blockeds_paginated is not None: serializer = StudentSerializer( data=blockeds_paginated, many=True, context={'request': request}) serializer.is_valid() return self.get_paginated_response(serializer.data) else: data = PostSerializer( data=blockeds, many=True, context={'request': request}) data.is_valid() return Response(data.data) @api_view(['GET']) def anonymous_name(request): """ API endpoint that allows getting an anonymous name to a student. --- Response example: ``` { "anonymous_name": "Rio" } ``` """ # The city names are sorted in alphabetic order CITY_NAMES = json.loads(open("api/fixtures/city_names.json").read()) anonymous_name = {'anonymous_name': random.choice(CITY_NAMES)} return Response(anonymous_name, status=status.HTTP_200_OK) <file_sep>/unbfeelings/config/apps.py """ File responsible for inserting applications within the project. """ APPS_DJANGO = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] EXTERNAL_APPS = [ 'rest_framework', 'corsheaders', 'rest_framework_swagger', ] LOCAL_APPS = ['api'] PRODUCTION_APPS = APPS_DJANGO + EXTERNAL_APPS + LOCAL_APPS DEVELOPMENT_APPS = ['django_extensions'] + PRODUCTION_APPS <file_sep>/api/migrations/0007_merge_20180704_1943.py # Generated by Django 2.0.2 on 2018-07-04 22:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0005_block'), ('api', '0006_support_created_at'), ] operations = [ ] <file_sep>/unbfeelings/urls.py from django.conf.urls import include, url from django.urls import path from rest_framework.routers import DefaultRouter from rest_framework_jwt.views import refresh_jwt_token from rest_framework_swagger.views import get_swagger_view from api.views import (BlockViewSet, CampusViewSet, CourseViewSet, CustomObtainJWTToken, DiagnosisViewSet, PostViewSet, StudentViewSet, SubjectViewSet, TagViewSet, SupportViewSet, SupportCreate) schema_view = get_swagger_view(title='UnB Feelings API') ROUTER = DefaultRouter() ROUTER.register(r'courses', CourseViewSet, base_name='courses') ROUTER.register(r'subjects', SubjectViewSet, base_name='subjects') ROUTER.register(r'users', StudentViewSet) ROUTER.register(r'tags', TagViewSet, base_name='tags') ROUTER.register(r'posts', PostViewSet, base_name='posts') ROUTER.register(r'campus', CampusViewSet, base_name='campus') ROUTER.register(r'block', BlockViewSet, base_name='block') ROUTER.register(r'support', SupportViewSet, base_name='support') urlpatterns = [ url(r'^$', schema_view), url(r'^api/support/(?P<pk>\d+)/', SupportCreate.as_view()), url(r'^api/', include(ROUTER.urls)), url(r'^api/token-auth/', CustomObtainJWTToken.as_view()), url(r'^api/token-refresh/', refresh_jwt_token), url(r'^api/anonymous-name/', StudentViewSet.anonymous_name), url(r'^api/diagnosis/', DiagnosisViewSet.diagnosis), ] <file_sep>/api/views/__init__.py from .campus_views import CampusViewSet # noqa: F401 from .course_views import CourseViewSet # noqa: F401 from .subject_views import SubjectViewSet # noqa: F401 from .student_views import StudentViewSet # noqa: F401 from .tag_views import TagViewSet # noqa: F401 from .post_views import PostViewSet # noqa: F401 from .block_views import BlockViewSet from .diagnosis_views import DiagnosisViewSet # noqa: F401 from .custom_obtain_jwt_token import CustomObtainJWTToken # noqa: F401 from .support_views import SupportViewSet, SupportCreate # noqa: F401<file_sep>/api/tests/block_viewset_test.py from rest_framework.test import APITestCase, APIClient from django.contrib.auth import get_user_model from api.models import Student, Campus, Course, Block from api.tests.helpers import create_test_user, TestCheckMixin UserModel = get_user_model() class BlockTestCase(APITestCase, TestCheckMixin): @create_test_user(email="<EMAIL>", password="<PASSWORD>") def setUp(self): campus = Campus.objects.get_or_create(name="FGA")[0] course = Course.objects.get_or_create( name="ENGENHARIA", campus=campus)[0] self.user = Student.objects.get(email="<EMAIL>") self.user2 = Student.objects.create(email='<EMAIL>',password='1', course=course) self.user3 = Student.objects.create(email='<EMAIL>',password='1', course=course) self.user4 = Student.objects.create(email='<EMAIL>',password='1', course=course) self.block = Block.objects.get_or_create(blocker=self.user, blocked=self.user3) def test_user_block_user(self): client = APIClient() data = { "blocked": self.user2.id, } self._check_only_logged_user_access( client, lambda: client.post('/api/block/', data)) token = self._get_user_token("<EMAIL>", "<PASSWORD>") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.post('/api/block/', data) self.assertEqual(201, response.status_code) self.assertEqual(self.user.id, response.data['blocker']) self.assertEqual(data["blocked"], response.data['blocked']) def test_user_delete_block(self): client = APIClient() blocked_id = self.block[0].blocked.id self._check_only_logged_user_access( client, lambda: client.delete('/api/block/' + str(blocked_id) + '/')) token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.delete('/api/block/' + str(blocked_id) + '/') self.assertEqual(204, response.status_code) self.assertEqual(None, response.data) def test_user_list_block(self): client = APIClient() self._check_only_logged_user_access( client, lambda: client.get('/api/block/')) token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.get('/api/block/') self.assertEqual(200, response.status_code) self.assertEqual(1, response.data["count"]) self.assertEqual(self.block[0].blocker.id,response.data["results"][0]["blocker"]) self.assertEqual(self.block[0].blocked.id,response.data["results"][0]["blocked"]) <file_sep>/unbfeelings/config/password.py """ File responsible by password validation. https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators """ password_validation = 'django.contrib.auth.password_validation' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': '{password}.UserAttributeSimilarityValidator' .format(password=<PASSWORD>), }, { 'NAME': '{password}.MinimumLengthValidator' .format(password=<PASSWORD>), }, { 'NAME': '{password}.CommonPasswordValidator' .format(password=<PASSWORD>), }, { 'NAME': '{password}.NumericPasswordValidator' .format(password=<PASSWORD>), }, ] <file_sep>/api/views/campus_views.py from rest_framework.viewsets import ModelViewSet from api.serializers import CampusSerializer from api.models import Campus from api.permissions import NonAdminCanOnlyGet class CampusViewSet(ModelViewSet): queryset = Campus.objects.all() serializer_class = CampusSerializer permission_classes = (NonAdminCanOnlyGet, ) def list(self, request): return super(CampusViewSet, self).list(request) <file_sep>/unbfeelings/config/rest.py """ Django Rest Framework http://www.django-rest-framework.org/ http://getblimp.github.io/django-rest-framework-jwt/ """ import datetime REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication' ), 'TEST_REQUEST_DEFAULT_FORMAT': 'json', 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100 } JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(minutes=1800), 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(weeks=2), } SWAGGER_SETTINGS = { 'USE_SESSION_AUTH': False } <file_sep>/api/migrations/0001_initial.py # Generated by Django 2.0.2 on 2018-05-15 18:07 from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( name='Student', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('email', models.EmailField(max_length=254, unique=True, verbose_name='email address')), ], options={ 'verbose_name': 'user', 'verbose_name_plural': 'users', 'abstract': False, }, managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.CreateModel( name='Campus', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='Course', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('campus', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='courses', to='api.Campus')), ], ), migrations.CreateModel( name='Emotion', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('emotion_type', models.CharField(choices=[('b', 'Bad'), ('g', 'Good')], max_length=1)), ('name', models.CharField(max_length=100)), ('image_link', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content', models.CharField(max_length=280)), ('author', models.ForeignKey(on_delete=None, to=settings.AUTH_USER_MODEL)), ('emotion', models.ManyToManyField(to='api.Emotion')), ], ), migrations.CreateModel( name='Subject', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Course')), ], ), migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('description', models.CharField(max_length=200, unique=True)), ('_quantity', models.IntegerField(blank=True, default=0, null=True)), ], ), migrations.AddField( model_name='post', name='subject', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='api.Subject'), ), migrations.AddField( model_name='post', name='tag', field=models.ManyToManyField(blank=True, to='api.Tag'), ), migrations.AddField( model_name='student', name='course', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='users', to='api.Course'), ), migrations.AddField( model_name='student', name='groups', field=models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups'), ), migrations.AddField( model_name='student', name='user_permissions', field=models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions'), ), ] <file_sep>/unbfeelings/config/i18n.py """ File responsible for the internationalization of the project. https://docs.djangoproject.com/en/2.0/topics/i18n/ """ LANGUAGE_CODE = 'pt-br' TIME_ZONE = 'America/Sao_Paulo' USE_I18N = True USE_L10N = True USE_TZ = True <file_sep>/api/tests/support_viewset_test.py # -*- coding: utf-8 -*- from rest_framework.test import APITestCase, APIClient from django.contrib.auth import get_user_model from api.models import Campus, Course, Subject, Support from api.tests.helpers import create_test_user, TestCheckMixin UserModel = get_user_model() class SupportTestCase(APITestCase, TestCheckMixin): @create_test_user(email="<EMAIL>", password="<PASSWORD>") @create_test_user(email="<EMAIL>", password="<PASSWORD>") def setUp(self): self.user_sender = UserModel.objects.get(email="<EMAIL>") self.user_receiver = UserModel.objects.get(email="<EMAIL>") def test_user_create_posts(self): client = APIClient() client.login(username='<EMAIL>', password='<PASSWORD>') user_sender_id = self.user_sender.id user_receiver_id = self.user_receiver.id data = { "message": "#VoltaRonyCoins", } token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.post('/api/support/'+str(user_receiver_id)+'/', data) self.assertEqual(201, response.status_code) self.assertEqual(data["message"], response.data['message']) self.assertEqual(user_sender_id, response.data['student_from']) self.assertEqual(user_receiver_id, response.data['student_to']) def test_get_supports_made_by_user(self): client = APIClient() client.login(username='<EMAIL>', password='<PASSWORD>') user_sender_id = self.user_sender.id user_receiver_id = self.user_receiver.id data = { "message": "#VoltaRonyCoins", } token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) client.post('/api/support/'+str(user_receiver_id)+'/', data) response = client.get('/api/support/from_student/', data) self.assertEqual(200, response.status_code) self.assertEqual(data["message"], response.data['results'][0]['message']) self.assertEqual(user_sender_id, response.data['results'][0]['student_from']) self.assertEqual(user_receiver_id, response.data['results'][0]['student_to']) def test__get_supports_made_to_user(self): client = APIClient() client.login(username='<EMAIL>', password='<PASSWORD>') user_sender_id = self.user_sender.id user_receiver_id = self.user_receiver.id data = { "message": "#VoltaRonyCoins", } token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) client.post('/api/support/'+str(user_receiver_id)+'/', data) client.logout() client = APIClient() client.login(username='<EMAIL>', password='<PASSWORD>') token = self._get_user_token("<EMAIL>", "testuser2") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.get('/api/support/to_student/', data) self.assertEqual(200, response.status_code) self.assertEqual(data["message"], response.data['results'][0]['message']) self.assertEqual(user_sender_id, response.data['results'][0]['student_from']) self.assertEqual(user_receiver_id, response.data['results'][0]['student_to']) def test_get_none_supports_made_by_user(self): client = APIClient() client.login(username='<EMAIL>', password='<PASSWORD>') data = { } token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.get('/api/support/from_student/', data) self.assertEqual(200, response.status_code) self.assertEqual(0, response.data['count']) # self.assertEqual(user_sender_id, response.data['results'][0]['student_from']) # self.assertEqual(user_receiver_id, response.data['results'][0]['student_to']) def test_get_none_supports_made_to_user(self): client = APIClient() client.login(username='<EMAIL>', password='<PASSWORD>') data = { } token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.get('/api/support/to_student/', data) self.assertEqual(200, response.status_code) self.assertEqual(0, response.data['count']) def test_post_support_denied_permission(self): client = APIClient() user_receiver_id = self.user_receiver.id data = { } response = client.post('/api/support/'+str(user_receiver_id)+'/', data) self.assertEqual(401, response.status_code) def test_get_support_to_student_denied_permission(self): client = APIClient() data = { } response = client.get('/api/support/to_student/', data) self.assertEqual(401, response.status_code) def test_get_support_from_student_denied_permission(self): client = APIClient() data = { } response = client.get('/api/support/from_student/', data) self.assertEqual(401, response.status_code) <file_sep>/api/tests/course_viewset_test.py # -*- coding: utf-8 -*- from rest_framework.test import APITestCase, APIClient from django.contrib.auth import get_user_model from api.models import Campus, Course from api.tests.helpers import create_test_user, TestCheckMixin UserModel = get_user_model() class CourseTestCase(APITestCase, TestCheckMixin): def setUp(self): self.campus = Campus.objects.get_or_create(name="FGA")[0] Course.objects.get_or_create(name="ENGENHARIA", campus=self.campus) Course.objects.get_or_create(name="ENG.SOFTWARE", campus=self.campus) def test_anyone_can_get_list(self): """ Anyone can make get requests to list """ client = APIClient() response = client.get('/api/courses/') courses = Course.objects.all() self.assertEqual(200, response.status_code) self.assertEqual(len(courses), len(response.data['results'])) def test_anyone_can_get_detail(self): """ Anyone can make get requests to detail """ client = APIClient() course = Course.objects.get(name="ENG.SOFTWARE") response = client.get('/api/courses/{}/'.format(course.id)) self.assertEqual(200, response.status_code) self.assertEqual(course.id, response.data['id']) @create_test_user(email="<EMAIL>", password="<PASSWORD>") def test_only_admin_can_create(self): """ Only admin members can create new """ client = APIClient() self._check_admin_only_access( client, lambda: client.post('/api/courses/', { "name": "A new course", "campus": self.campus.id }), "<EMAIL>", "testuser") user = UserModel.objects.get(email="<EMAIL>") user.is_staff = True user.save() token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.post('/api/courses/', { "name": "A new course", "campus": self.campus.id }) self.assertEqual(201, response.status_code) self.assertEqual("A new course", response.data['name']) @create_test_user(email="<EMAIL>", password="<PASSWORD>") def test_only_admin_can_update(self): """ Only admin members can update """ course = Course.objects.get(name="ENG.SOFTWARE") client = APIClient() self._check_admin_only_access( client, lambda: client.patch('/api/courses/{}/'.format(course.id), { "name": "other name" }), "<EMAIL>", "testuser") user = UserModel.objects.get(email="<EMAIL>") user.is_staff = True user.save() token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.patch('/api/courses/{}/'.format(course.id), {"name": "other name"}) self.assertEqual(200, response.status_code) self.assertEqual("other name", response.data['name']) @create_test_user(email="<EMAIL>", password="<PASSWORD>") def test_only_admin_can_delete(self): """ Only admin members can delete """ course = Course.objects.get(name="ENG.SOFTWARE") client = APIClient() self._check_admin_only_access( client, lambda: client.delete('/api/courses/{}/'.format(course.id)), "<EMAIL>", "testuser") user = UserModel.objects.get(email="<EMAIL>") user.is_staff = True user.save() token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.delete('/api/courses/{}/'.format(course.id)) self.assertEqual(204, response.status_code) self.assertEqual(None, response.data) self.assertEqual( 0, len(Course.objects.all().filter(name="ENG.SOFTWARE"))) <file_sep>/api/views/block_views.py from rest_framework.viewsets import ModelViewSet from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from api.permissions import BlockPermissions from api.serializers import BlockSerializer from api.models import Block class BlockViewSet(ModelViewSet): """Description: BlockViewSet. API endpoint that allows blocks to be listed, created or deleted. """ permission_classes = (BlockPermissions, ) serializer_class = BlockSerializer def get_queryset(self): """ Override of query set method to return only user blocked users """ return Block.objects.filter(blocker=self.request.user) def list(self, request): """ API endpoint that allows user to list all their blocks. """ response = super(BlockViewSet, self).list(request) return response def create(self, request): """ API endpoint that allows user to block other user """ response = super(BlockViewSet, self).create(request) return response def destroy(self, request, pk=None): """ API endpoint that allows blocks to be deleted. """ instance = Block.objects.get(blocked=pk, blocker=self.request.user) self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT) <file_sep>/unbfeelings/config/database.py """ File to insert the development and production database. Para mais informações: https://docs.djangoproject.com/pt-br/2.0/ref/settings/#databases """ import os BASE_DIR = os.path.dirname( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) ) DEVELOPMENT_DB = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } PRODUCTION_DB = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'db', 'PORT': '5432' } } <file_sep>/api/migrations/0004_auto_20180524_2056.py # Generated by Django 2.0.2 on 2018-05-24 23:56 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0003_post_created_at'), ] operations = [ migrations.AlterField( model_name='post', name='author', field=models.ForeignKey(on_delete=None, related_name='posts', to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='post', name='subject', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='posts', to='api.Subject'), ), migrations.AlterField( model_name='post', name='tag', field=models.ManyToManyField(blank=True, related_name='posts', to='api.Tag'), ), migrations.AlterField( model_name='subject', name='course', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='subjects', to='api.Course'), ), ] <file_sep>/api/views/custom_obtain_jwt_token.py from rest_framework_jwt.views import ObtainJSONWebToken from api.models import Student class CustomObtainJWTToken(ObtainJSONWebToken): """Description: StudentViewSet. API endpoint that provides the authentication token. """ def post(self, request, *args, **kwargs): """ API endpoint that provides an authentication token when a user enters the correct credentials. """ response = \ super(CustomObtainJWTToken, self).post(request, *args, **kwargs) user = Student.objects.get(email=request.data['email']) response.data['user'] = user.pk return response <file_sep>/api/fixtures/scripts/load_dev_data.py from api.models import Course, Post, Student, Subject, Tag print("GETTINGS courses") engenharia = Course.objects.get(name="ENGENHARIA") software = Course.objects.get(name="SOFTWARE") eletronica = Course.objects.get(name="ELETRONICA") aeroespacial = Course.objects.get(name="AEROESPACIAL") energia = Course.objects.get(name="ENERGIA") print("\nFGA STUDENTS") fga_courses = [engenharia, software, eletronica, aeroespacial, energia] for i, course in enumerate(fga_courses): username = 'student_' + course.name email = username + '@b.com' print("\tCreating student {}".format(username)) student = Student.objects.create(email=email, course=course) student.set_password("<PASSWORD>") student.save() print("\nTAGs") tags = [ "boladao", "antietico", "cortella", "avestruz", "changemymind", "tanadisney" ] for tag in tags: print("\tCreating tag {}".format(tag)) Tag.objects.create(description=tag) print("\nPOST") contents = [ "Trueborn son of Lannister.", "Tell my lord father", "Jon said.", "He favored Jon with a rueful grin.", "All dwarfs may be bastards", "Whistling a tune.", "Just a moment", "<NAME> stood tall as a king.", "― <NAME>", ] for i, content in enumerate(contents): student = Student.objects.all()[i % Student.objects.count()] subject = Subject.objects.all()[i % Subject.objects.count()] emotion = Post.EMOTIONS[i % 2][0] post = Post.objects.create( content=content, author=student, subject=subject, emotion=emotion) tags = Tag.objects.all()[i:] post.tag.add(*tags) post.save() print("\tCreating post {}".format(post)) <file_sep>/unbfeelings/config/files.py """ Configuration file for static and dynamic files. https://docs.djangoproject.com/en/2.0/howto/static-files/ """ import os BASE_DIR = os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles/') MEDIA_URL = '/media/' <file_sep>/production-deploy.sh #!/bin/bash # # Purpose: Continuous deploy on production enviroment # #Author: <NAME> <<EMAIL>> sudo docker login --username $DOCKER_HUB_USER --password $DOCKER_HUB_PASS sudo docker-compose -f docker-compose.build.production.yml build sudo docker-compose -f docker-compose.build.production.yml push <file_sep>/api/views/tag_views.py from rest_framework import status from rest_framework.viewsets import ModelViewSet from rest_framework.response import Response from api.serializers import TagSerializer from api.models import Tag class TagViewSet(ModelViewSet): """Description: TagViewSet. API endpoint that allows tags to be viewed, created, deleted or edited. """ queryset = Tag.objects.all() serializer_class = TagSerializer def list(self, request): """ API endpoint that allows all tags to be viewed. --- Response example: ``` { "count": 1, "next": null,Tag "previous": null, "results": [ { "id": 1, "description": "TAG1", "quantity": 1 } ] } ``` """ response = super(TagViewSet, self).list(request) return response def create(self, request): """ API endpoint that allows tags to be created. --- Body example: ``` { "description": "educacao" } ``` Response example: ``` { "id": 2, "description": "educacao", "quantity": 0 } ``` """ serializer = TagSerializer(data=request.data) tag_retrieved = -1 try: # trying to find the object on database obj = Tag.objects.get(description=request.data['description']) tag_retrieved = obj except Tag.DoesNotExist: pass if serializer.is_valid(): instance, created = serializer.get_or_create() if not created: serializer.update(instance, serializer.validated_data) tag_data = Tag.objects.get(description=request.data['description']) tag_data = { 'id': tag_data.pk, 'description': tag_data.description, 'quantity': tag_data.quantity } return Response(tag_data, status=status.HTTP_202_ACCEPTED) if tag_retrieved != -1: # if tag exists, we need to pass its id tag_data = { 'id': tag_retrieved.pk, 'description': tag_retrieved.description, 'quantity': tag_retrieved.quantity } return Response(tag_data, status=status.HTTP_202_ACCEPTED) else: # any error from validation will enter here return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) def destroy(self, request, pk=None): """ API endpoint that allows tags to be deleted. """ response = super(TagViewSet, self).destroy(request, pk) return response def retrieve(self, request, pk=None): """ API endpoint that allows a specific tag to be viewed. --- Response example: ``` { "id": 1, "description": "TAG1", "quantity": 1 } ``` """ response = super(TagViewSet, self).retrieve(request, pk) return response def partial_update(self, request, pk=None, **kwargs): """ API endpoint that allows a tag to be partial edited. --- Body example: ``` { "id": 1, "description": "TAG1", "quantity": 1 } ``` Response example: ``` { "id": 1, "description": "TAG1", "quantity": 2 } ``` """ response = \ super(TagViewSet, self).partial_update(request, pk, **kwargs) return response def update(self, request, pk=None, **kwargs): """ API endpoint that allows a tag to be edited. --- Body example: ``` { "description": "TAG2", "quantity": 2 } ``` Response example: ``` { "id": 1, "description": "TAG2", "quantity": 2 } ``` """ response = super(TagViewSet, self).update(request, pk, **kwargs) return response <file_sep>/requirements.txt certifi==2018.4.16 chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 coverage==4.5 Django==2.0.2 django-cors-headers==2.1.0 django-extensions==1.9.9 django-rest-swagger==2.1.2 djangorestframework==3.7.7 djangorestframework-jwt==1.11.0 gunicorn==19.7.1 idna==2.6 itypes==1.1.0 Jinja2==2.10 MarkupSafe==1.0 openapi-codec==1.3.2 psycopg2==2.7.4 psycopg2-binary==2.7.4 PyJWT==1.5.3 pytz==2017.3 requests==2.18.4 simplejson==3.14.0 six==1.11.0 typing==3.6.4 uritemplate==3.0.0 urllib3==1.22 coveralls==1.3.0 PyYAML==3.12 <file_sep>/unbfeelings/config/authentication.py """ File responsible for the project authentication. """ AUTHENTICATION_BACKENDS = [ 'api.backends.EmailBackend' ] AUTH_USER_MODEL = 'api.Student' <file_sep>/api/views/diagnosis_views.py from django.shortcuts import get_object_or_404 from django.utils import timezone from django.http import Http404 from datetime import timedelta from rest_framework.viewsets import ModelViewSet from rest_framework.decorators import api_view from rest_framework.response import Response from api.models import Post, Subject, Student from api.serializers import PostSerializer class DiagnosisViewSet(ModelViewSet): """ Description: DiagnosisViewSet. API endpoint that allows getting a diagnosis of a student, subject or university. """ @api_view(['GET']) def diagnosis(request): """ API endpoint that allows getting a diagnosis of a student, subject or university. By default it will return the unb feelings. But by using query params target and target_id it will return student and subject feelings. * /api/diagnosis/ --> unb feelings * /api/diagnosis/?target=student&target_id=5 --> student feelings * /api/diagnosis/?target=subject&target_id=7 --> subject feelings --- Response example: ``` { "sunday": [], "monday": [], "tuesday": [ { "id": 1, "author_id": 3, "subject": { "id": 15, "name": "Calculo 1", "course": 1 }, "tag": [ { "id": 1, "description": "boladao", "quantity": 1 }, ] "emotion": "g", "created_at": "2018-05-23T00:20:22.344509Z" } ], "wednesday": [], "thursday": [], "friday": [], "saturday": [] } ``` """ target = request.query_params.get("target", None) target_id = request.query_params.get("target_id", None) # only posts from the last week posts = get_posts_by_target(target, target_id) days = ( "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ) diagnosis = dict() for (i, day) in enumerate(days): week_day = i+1 data = posts.filter(created_at__week_day=week_day) serialized = PostSerializer(data=data, many=True) serialized.is_valid() diagnosis[day] = serialized.data return Response(diagnosis) def get_posts_by_target(target=None, target_id=None): """ Given a target and its id, it returns the target posts on the week raises 404 error when target not found or target is invalid. Valid targets: * subject * student * unb """ posts_query = Post.objects.select_related('subject').all() if target is None: # is no target is given, return all unb feelings return posts_query.filter( created_at__gt=timezone.now() - timedelta(days=8)) if target == 'subject': subject = get_object_or_404(Subject, pk=target_id) return posts_query.filter( subject=subject, created_at__gt=timezone.now() - timedelta(days=8)) if target == 'student': student = get_object_or_404(Student, pk=target_id) return posts_query.filter( author=student, created_at__gt=timezone.now() - timedelta(days=8)) # if an invalid target is given return an 404 response raise Http404 <file_sep>/compose/dev/dev.sh #!/bin/sh #echo "Creating migrations and insert into psql database" #python3 manage.py makemigrations #python3 manage.py migrate #echo "Run the server" #python3 manage.py runserver 0.0.0.0:8000<file_sep>/api/tests/test_models.py # -*- coding: utf-8 -*- from rest_framework.test import APITestCase from api.models import SubjectEmotionsCount class SubjectEmotionsCountTestCase(APITestCase): def test_subject_emotions_count_str(self): subject_name = 'Computacao basica' good_count = 3 bad_count = 1 emotions_count = SubjectEmotionsCount(subject_name=subject_name, good_count=good_count, bad_count=bad_count) emotions_count_str = emotions_count.__str__() expected_str = '(Computacao basica, {\'good\': 3, \'bad\': 1})' self.assertEquals(emotions_count_str, expected_str) <file_sep>/compose/dev/Dockerfile # Build an debian image FROM python:3.6 # Install SO dependecies RUN apt-get update && apt-get install -y \ python3-dev \ python3-pip \ libpq-dev \ python3-setuptools \ gettext \ vim \ build-essential # Install pip dependecies RUN pip3 install --upgrade pip # Crate user developer RUN useradd -ms /bin/bash developer # Insert Enviroment variable ENV MODE_ENVIROMENT=development # Create software folder ADD . /home/developer/software WORKDIR /home/developer/software RUN pip3 install -r requirements.txt # Expose port 8000 EXPOSE 8000 # Config user developer RUN chown -R developer: /home/developer/software USER developer # Run the script to create database #RUN chmod +x compose/dev/dev.sh #ENTRYPOINT ["compose/dev/dev.sh"] # Run the server #CMD ["seleep", "infinity"] <file_sep>/api/serializers.py from django.shortcuts import get_object_or_404 from rest_framework import serializers from rest_framework.serializers import ( CurrentUserDefault, PrimaryKeyRelatedField ) from rest_framework.request import Request from .models import ( Campus, Course, Post, Student, Subject, Tag, Block, Support ) class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = [ 'id', 'name', 'campus', ] class CampusSerializer(serializers.ModelSerializer): courses = CourseSerializer(many=True, read_only=True) class Meta: model = Campus fields = [ 'id', 'name', 'courses', ] class SubjectSerializer(serializers.ModelSerializer): class Meta: model = Subject fields = [ 'id', 'name', 'course', ] def to_internal_value(self, data): """ Needed for PostSerializer create posts passing only the Subject id. Otherwise every time a Post is created a new Subject is alse created. """ if isinstance(data, int): return get_object_or_404(Subject.objects.all(), pk=data) elif isinstance(data, dict) and data.get('id'): return get_object_or_404(Subject.objects.all(), pk=data.get('id')) return super(SubjectSerializer, self).to_internal_value(data) class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = [ 'id', 'email', 'password', 'course' ] extra_kwargs = { 'password': { 'write_only': True }, } def create(self, validated_data): user = Student(**validated_data) password = validated_data['password'] user.set_password(password) user.save() return user class TagSerializer(serializers.ModelSerializer): quantity = serializers.IntegerField(read_only=True) class Meta: model = Tag fields = [ 'id', 'description', 'quantity', ] def get_or_create(self): defaults = self.validated_data.copy() identifier = defaults.pop('description') return Tag.objects.get_or_create(description=identifier, defaults=defaults) class PostSerializer(serializers.ModelSerializer): subject = SubjectSerializer() tag = TagSerializer(many=True, read_only=True) class Meta: model = Post fields = [ 'id', 'author', 'content', 'subject', 'tag', 'emotion', 'created_at', ] def __init__(self, *args, **kwargs): super(serializers.ModelSerializer, self).__init__(*args, **kwargs) request = self._get_request_from_kwargs(kwargs) if isinstance(request, Request): user = request.user try: user_id = int(request.parser_context['kwargs'].get('user_id')) except: # noqa: E722 user_id = 0 if user.id == user_id: return # The user can see his Posts content data # For any other user remove the content exclude_fields = {'content', } for field in exclude_fields: self.fields.pop(field) def _get_request_from_kwargs(self, kwargs): context = kwargs.get('context', None) if context is not None: return context.get('request', None) return None class SubjectEmotionsCountSerializer(serializers.Serializer): subject_name = serializers.CharField(max_length=200) good_count = serializers.IntegerField(min_value=0) bad_count = serializers.IntegerField(min_value=0) class BlockSerializer(serializers.ModelSerializer): blocked = PrimaryKeyRelatedField(required=True, queryset=Student.objects.all()) blocker = PrimaryKeyRelatedField(default=CurrentUserDefault(), read_only=True) class Meta: model = Block fields = [ 'blocked', 'blocker', ] def get_or_create(self): defaults = self.validated_data.copy() blocked = defaults.pop('blocked') blocker = defaults.pop('blocker') return Block.objects.get_or_create(blocked=blocked, blocker=blocker) class SupportSerializer(serializers.ModelSerializer): student_from = serializers.PrimaryKeyRelatedField(read_only=True) student_to = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Support fields = [ 'id', 'message', 'created_at', 'student_from', 'student_to' ] def create(self, validated_data): """ API endpoint that allows supports to be made. --- Body example: ``` { "name": "<NAME>", "course": 2 } ``` Response example: ``` { "id": 4, "name": "<NAME>", "course": 2 } ``` """ student_from = self.context['request'].user student_to = self.context['view'].kwargs['pk'] validated_data['student_from'] = student_from validated_data['student_to'] = Student.objects.get(pk=int(student_to)) return Support.objects.create(**validated_data) <file_sep>/api/views/course_views.py from rest_framework.viewsets import ModelViewSet from api.serializers import CourseSerializer from api.models import Course from api.permissions import NonAdminCanOnlyGet class CourseViewSet(ModelViewSet): """Description: CourseViewSet. API endpoint that allows courses to be viewed, created, deleted or edited. """ queryset = Course.objects.all() serializer_class = CourseSerializer permission_classes = (NonAdminCanOnlyGet, ) def list(self, request): """ API endpoint that allows all courses to be viewed. --- Response example: ``` { "count": 6, "next": null, "previous": null, "results": [ { "id": 1, "name": "ENGENHARIA", "campus": 1 }, { "id": 2, "name": "SOFTWARE", "campus": 1 }, { "id": 3, "name": "ELETRONICA", "campus": 1 }, { "id": 4, "name": "AEROESPACIAL", "campus": 1 }, { "id": 5, "name": "ENERGIA", "campus": 1 }, { "id": 6, "name": "AUTOMOTIVA", "campus": 1 } ] } ``` """ return super(CourseViewSet, self).list(request) def create(self, request): """ API endpoint that allows all courses to be created. --- Body example: ``` { "name": "MECATRONICA", } ``` Response example: ``` { "id": 7, "name": "MECATRONICA", "campus": 2 } ``` """ return super(CourseViewSet, self).create(request) def destroy(self, request, pk=None): """ API endpoint that allows courses to be deleted. """ response = super(CourseViewSet, self).destroy(request, pk) return response def retrieve(self, request, pk=None): """ API endpoint that allows a specific course to be viewed. --- Response example: ``` { "id": 7, "name": "MECATRONICA", "campus": 2 } ``` """ response = super(CourseViewSet, self).retrieve(request, pk) return response def partial_update(self, request, pk=None, **kwargs): """ API endpoint that allows a course to be partial edited. --- Body example: ``` { "name": "CIVIL" } ``` Response example: ``` { "id": 7, "name": "CIVIL", "campus": 2 } ``` """ response = \ super(CourseViewSet, self).partial_update(request, pk, **kwargs) return response def update(self, request, pk=None, **kwargs): """ API endpoint that allows a course to be edited. --- Body example: ``` { "name": "CIVIL" } ``` Response example: ``` { "id": 7, "name": "CIVIL", "campus": 2 } ``` """ response = \ super(CourseViewSet, self).update(request, pk, **kwargs) return response <file_sep>/api/tests/user_registration_view_test.py # -*- coding: utf-8 -*- from rest_framework.test import APITestCase, APIRequestFactory, APIClient from django.contrib.auth import get_user_model from api.models import Campus, Course UserModel = get_user_model() class UserRegistrationTestCase(APITestCase): def setUp(self): campus = Campus.objects.get_or_create(name="FGA")[0] self.course = Course.objects.get_or_create( name="ENGENHARIA", campus=campus)[0] def test_valid_user(self): """ Test to verify if given a valid user data. It registers the user """ user_data = { "course": self.course.id, "email": "<EMAIL>", "password": "<PASSWORD>", } client = APIClient() response = client.post('/api/users/', user_data) # 201 == created self.assertEqual(201, response.status_code) self.assertEqual("<EMAIL>", response.data["email"]) def test_cant_create_user_without_email(self): user_data = { "course": self.course.id, "password": "<PASSWORD>", } client = APIClient() response = client.post('/api/users/', user_data) self.assertEqual(400, response.status_code) self.assertEqual("Este campo é obrigatório.", response.data["email"][0]) <file_sep>/api/tests/diagnosis_viewset_test.py # -*- coding: utf-8 -*- from datetime import timedelta from rest_framework.test import APITestCase, APIClient from django.contrib.auth import get_user_model from django.utils import timezone from api.models import Campus, Post, Course, Subject from api.tests.helpers import create_test_user UserModel = get_user_model() TODAY = timezone.now() MONDAY = TODAY - timedelta(days=TODAY.weekday()) TUESDAY = MONDAY + timedelta(days=1) WEDNESDAY = TUESDAY + timedelta(days=1) THURSDAY = WEDNESDAY + timedelta(days=1) FRIDAY = THURSDAY + timedelta(days=1) SATURDAY = FRIDAY + timedelta(days=1) SUNDAY = SATURDAY + timedelta(days=1) WEEK_DAYS = [(MONDAY, 'monday'), (TUESDAY, 'tuesday'), (WEDNESDAY, 'wednesday'), (THURSDAY, 'thursday'), (FRIDAY, 'friday'), (SATURDAY, 'saturday'), (SUNDAY, 'sunday')] class DiagnosisTestCase(APITestCase): @create_test_user(email="<EMAIL>", password="<PASSWORD>") @create_test_user(email="<EMAIL>", password="<PASSWORD>") def setUp(self): campus = Campus.objects.get_or_create(name="FGA")[0] course = Course.objects.get_or_create( name="ENGENHARIA", campus=campus)[0] self.c1 = Subject.objects.get_or_create( name="Calculo 1", course=course)[0] self.f1 = Subject.objects.get_or_create( name="Fisica 1", course=course)[0] self.user_a = UserModel.objects.get(email="<EMAIL>") self.user_b = UserModel.objects.get(email="<EMAIL>") words = ['Allahu', 'Akibar', 'deu ruim', 'ok', 'Vish', 'agora', 'vai'] self.c1_days = [] self.f1_days = [] for i, word in enumerate(words): post = Post.objects.get_or_create( content=word, author=self.user_a if i % 2 == 0 else self.user_b, subject=self.c1 if i % 2 == 0 else self.f1, emotion="g" if i % 2 == 0 else "b")[0] if i % 2 == 0: self.c1_days.append(WEEK_DAYS[i]) else: self.f1_days.append(WEEK_DAYS[i]) post.created_at = WEEK_DAYS[i][0] post.save() def test_get_weekly_feelings_of_unb(self): """ get all weekly feelings of UNB """ client = APIClient() response = client.get("/api/diagnosis/") self.assertEqual(200, response.status_code) for day in WEEK_DAYS: post = Post.objects.filter(created_at=day[0]).first() self.assertEqual(post.id, response.data[day[1]][0]['id']) def test_invalid_target_raises_404_error(self): """ When an invalid target is given an error 404 is returned """ client = APIClient() response = client.get("/api/diagnosis/?target={}".format("invalid")) self.assertEqual(404, response.status_code) def test_get_posts_by_subject(self): client = APIClient() response = client.get("/api/diagnosis/?target={}&target_id={}".format( "subject", self.c1.id)) self.assertEqual(200, response.status_code) for (day_date, day_name) in self.c1_days: post = Post.objects.filter( created_at=day_date, subject=self.c1).first() self.assertEqual(post.id, response.data[day_name][0]['id']) response = client.get("/api/diagnosis/?target={}&target_id={}".format( "subject", self.f1.id)) self.assertEqual(200, response.status_code) for (day_date, day_name) in self.f1_days: post = Post.objects.filter( created_at=day_date, subject=self.f1).first() self.assertEqual(post.id, response.data[day_name][0]['id']) def test_get_posts_by_student(self): client = APIClient() response = client.get("/api/diagnosis/?target={}&target_id={}".format( "student", self.user_a.id)) self.assertEqual(200, response.status_code) posts = self.user_a.posts.all() total_posts = 0 for day in response.data.keys(): total_posts += len(response.data[day]) self.assertEqual(len(posts), total_posts) <file_sep>/compose/prod/prod.sh #!/bin/sh # Esperando o Postgres inicializar postgres_ready() { python3 << END import sys import psycopg2 try: conn = psycopg2.connect(dbname="postgres", user="postgres", password="", host="db") except psycopg2.OperationalError: sys.exit(-1) sys.exit(0) END } until postgres_ready; do >&2 echo "Postgresql is unavailable - Waiting..." sleep 1 done echo "Deleting migrations" find . -path "*/migrations/*.pyc" -delete #find . -path "*/migrations/*.py" -not -name "__init__.py" -delete echo "Deleting staticfiles" find . -path "unbfeelings/static/*" -delete echo "Creating migrations and insert into psql database" #python3 manage.py makemigrations python3 manage.py migrate echo "Collect staticfiles" python3 manage.py collectstatic --noinput echo "Run server" gunicorn --bind 0.0.0.0:8000 unbfeelings.wsgi <file_sep>/unbfeelings/settings.py """ Django settings for unbfeelings project. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ # Not remove the imports. from unbfeelings.config.apps import ( PRODUCTION_APPS, DEVELOPMENT_APPS ) from unbfeelings.config.database import ( DEVELOPMENT_DB, PRODUCTION_DB ) from unbfeelings.config.files import ( STATIC_ROOT, STATIC_URL, MEDIA_ROOT, MEDIA_URL ) from unbfeelings.config.i18n import ( LANGUAGE_CODE, TIME_ZONE, USE_I18N, USE_L10N, USE_TZ ) from unbfeelings.config.rest import ( REST_FRAMEWORK, JWT_AUTH, SWAGGER_SETTINGS ) from unbfeelings.config.authentication import ( AUTHENTICATION_BACKENDS, AUTH_USER_MODEL ) from unbfeelings.config.middleware import MIDDLEWARE from unbfeelings.config.security import SECRET_KEY from unbfeelings.config.templates import TEMPLATES from unbfeelings.config.password import AUTH_PASSWORD_VALIDATORS import os MODE_ENVIROMENT = os.getenv("MODE_ENVIROMENT", "development") ROOT_URLCONF = 'unbfeelings.urls' WSGI_APPLICATION = 'unbfeelings.wsgi.application' CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] if MODE_ENVIROMENT == 'development': DEBUG = True DATABASES = DEVELOPMENT_DB EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' INSTALLED_APPS = DEVELOPMENT_APPS elif MODE_ENVIROMENT == 'production': DEBUG = False DATABASES = PRODUCTION_DB INSTALLED_APPS = PRODUCTION_APPS <file_sep>/api/tests/campus_viewset_test.py # -*- coding: utf-8 -*- from rest_framework.test import APITestCase, APIClient from django.contrib.auth import get_user_model from api.models import Campus from api.tests.helpers import create_test_user, TestCheckMixin UserModel = get_user_model() class CampusTestCase(APITestCase, TestCheckMixin): def setUp(self): Campus.objects.get_or_create(name="FGA") Campus.objects.get_or_create(name="Darcy") def test_anyone_can_get_list(self): """ Anyone can make get requests to list """ client = APIClient() response = client.get('/api/campus/') campi = Campus.objects.all() self.assertEqual(200, response.status_code) self.assertEqual(len(campi), len(response.data['results'])) def test_anyone_can_get_detail(self): """ Anyone can make get requests to detail """ client = APIClient() fga = Campus.objects.get(name="FGA") response = client.get('/api/campus/{}/'.format(fga.id)) self.assertEqual(200, response.status_code) self.assertEqual(fga.id, response.data['id']) @create_test_user(email="<EMAIL>", password="<PASSWORD>") def test_only_admin_can_create(self): """ Only admin members can create new """ client = APIClient() self._check_admin_only_access( client, lambda: client.post('/api/campus/', {"name": "A new campus"}), "<EMAIL>", "testuser") user = UserModel.objects.get(email="<EMAIL>") user.is_staff = True user.save() token = self._get_user_token("<EMAIL>", "testuser") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.post('/api/campus/', {"name": "A new campus"}) self.assertEqual(201, response.status_code) self.assertEqual("A new campus", response.data['name']) @create_test_user(email="<EMAIL>", password="<PASSWORD>") def test_only_admin_can_update(self): """ Only admin members can update """ campus = Campus.objects.get(name="FGA") client = APIClient() self._check_admin_only_access( client, lambda: client.patch('/api/campus/{}/'.format(campus.id), { "name": "other name" }), "<EMAIL>", "testuser") user = UserModel.objects.get(email="<EMAIL>") user.is_staff = True user.save() token = self._get_user_token("<EMAIL>", "test<PASSWORD>") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.patch('/api/campus/{}/'.format(campus.id), {"name": "other name"}) self.assertEqual(200, response.status_code) self.assertEqual("other name", response.data['name']) @create_test_user(email="<EMAIL>", password="<PASSWORD>") def test_only_admin_can_delete(self): """ Only admin members can delete """ campus = Campus.objects.get(name="FGA") client = APIClient() self._check_admin_only_access( client, lambda: client.delete('/api/campus/{}/'.format(campus.id)), "<EMAIL>", "testuser") user = UserModel.objects.get(email="<EMAIL>") user.is_staff = True user.save() token = self._get_user_token("<EMAIL>", "test<PASSWORD>") client.credentials(HTTP_AUTHORIZATION='JWT {}'.format(token)) response = client.delete('/api/campus/{}/'.format(campus.id)) self.assertEqual(204, response.status_code) self.assertEqual(None, response.data) self.assertEqual(0, len(Campus.objects.all().filter(name="FGA"))) <file_sep>/api/migrations/0002_auto_20180520_1617.py # Generated by Django 2.0.2 on 2018-05-20 19:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='post', name='emotion', ), migrations.AddField( model_name='post', name='emotion', field=models.CharField(choices=[('b', 'Bad'), ('g', 'Good')], default='g', max_length=1), preserve_default=False, ), migrations.DeleteModel( name='Emotion', ), ] <file_sep>/compose/test/Dockerfile # Build an debian image FROM python:3.6 # Install SO dependecies RUN apt-get update && apt-get install -y \ python3-dev \ python3-pip \ libpq-dev \ python3-setuptools \ gettext \ build-essential # Install pip dependecies RUN pip3 install --upgrade pip # Insert Enviroment variable #ENV MODE_ENVIROMENT=development # Create software folder RUN mkdir -p /software ADD . /software WORKDIR /software RUN pip3 install -r requirements.txt <file_sep>/README.md # UnbFeelings_api | Verificação | Badge | | ------------------|:-------------:| | Testes Master | [![pipeline status](https://gitlab.com/UnbFeelings/unb-feelings-api/badges/master/pipeline.svg)](https://gitlab.com/UnbFeelings/unb-feelings-api/commits/master) | | Testes Develop | [![pipeline status](https://gitlab.com/UnbFeelings/unb-feelings-api/badges/develop/pipeline.svg)](https://gitlab.com/UnbFeelings/unb-feelings-api/commits/master) | | Cobertura Master | [![Coverage Master Status](https://coveralls.io/repos/github/UnbFeelings/unb-feelings-api/badge.svg?branch=master)](https://coveralls.io/github/UnbFeelings/unb-feelings-api?branch=master) | | Cobertura Develop | [![Coverage Develop Status](https://coveralls.io/repos/github/UnbFeelings/unb-feelings-api/badge.svg?branch=develop)](https://coveralls.io/github/UnbFeelings/unb-feelings-api?branch=develop) | *** Para subir os ambientes do UnB Feelings API, primeiramente é necessário instalar o docker e o docker-compose em seu computador. ## Ambiente de Desenvolvimento * Para clonar o repositório execute o comando: ```bash git clone https://github.com/UnbFeelings/unb-feelings-api.git ``` * Para subir o ambiente basta fazer: ```bash sudo docker-compose build sudo docker-compose run dev python manage.py migrate sudo docker-compose run dev python3 manage.py populatedb sudo docker-compose run dev python manage.py shell < api/fixtures/scripts/load_dev_data.py ``` * Esse primeiro passo só é necessário uma vez. Mas você precisará executar uma nova build(apenas o passo de build) sempre que um novo pacote pip for adicionado aos requirements. E para executar: ```bash sudo docker-compose up ``` * Após executar o ultimo comando, o servidor estará rodando na url 0.0.0.0:8000. Lembrando que sempre que uma model for alterada, será necessário atualizar/criar a sua devida migração. ```bash sudo docker-compose run dev python manage.py makemigrations ``` E realizar essa migração no banco: ```bash sudo docker-compose run dev python manage.py migrate ``` * Para entrar no terminal do container utilize o seguinte comando ``` docker exec -it <nome_do_container> bash ``` * Com isso você estará dentro do terminal do container e poderá criar um super usuário via shell. O ```python manage.py createsuperuser``` não está funcionando devido ao usuário precisar de um curso, então para criar um usuário é necessário entrar via shell pegar(ou criar) um curso e usa-lo na criação do usuário. Mas dentro do "load_dev_data.py"(comando na parte de build) um usuário para curso é criado, ficando: * email: <EMAIL>, password: <PASSWORD> * email: <EMAIL>, password: <PASSWORD> * email: <EMAIL>, password: <PASSWORD> * email: <EMAIL>, password: <PASSWORD> * email: <EMAIL>, password: <PASSWORD> * Com isso você pode modificar os arquivos localmente em sua máquina que ele serão automaticamente modificados dentro do container, possibilitando assim ter um ambiente de desenvolvimento sem a necessidade de muita configuração do ambiente. ## Ambiente de Testes * Para rodar os testes, execute o seguinte comando para subir o ambiente de teste ``` sudo docker-compose run dev python manage.py test ``` Também é possível executar os testes pelo mesmo docker do CI: ```bash sudo docker-compose -f compose/test/docker-compose.test.yml build sudo docker-compose -f compose/test/docker-compose.test.yml run unbfeelings-test python manage.py test ``` Mas nesse caso, é mais fácil simplismente fazer um _push_ para a sua branch no github que logo o CI irá automaticamente executar os testes. Agora caso queira ver a cobertura de testes: ```bash sudo docker-compose run dev coverage run --source='.' manage.py test sudo docker-compose run dev coverage report ``` Caso queira uma analise mais detalhada da cobertura, basta olhar o submit da cobertura pelo CI para o _coveralls_, ou, em vez de ```coverage report``` executar ```coverage html``` e uma pasta de nome __htmlcov__ será criada com a cobertura em HTML. <file_sep>/api/permissions.py from django.core.exceptions import ObjectDoesNotExist from rest_framework import permissions class DefaultPermission(permissions.IsAuthenticated): def has_permission(self, request, view): permission = super().has_permission(request, view) try: if permission and request.user.is_active: permission = True except ObjectDoesNotExist: permission = False return permission class StudentPermissions(permissions.BasePermission): def __init__(self): self.permission = False self.request = None self.user_id = '' self.user_request_id = '' self.authorized_user = False def has_permission(self, request, view): if request.user.is_superuser: return True elif 'users' in request.path: self.request = request self.user_id = str(self.request.user.id) self.user_request_id = \ self.request.path.split('/users/')[1][:-1] if (self.request.method == 'POST' and self.request.user.is_anonymous): self.permission = True if self.user_id == self.user_request_id: self.authorized_user = True if self.request.method != 'DELETE' and self.authorized_user: self.permission = True else: self.permission = True return self.permission class AdminItemPermissions(permissions.BasePermission): def __init__(self): self.permission = False def has_permission(self, request, view): if 'courses' in request.path or 'subjects' in request.path: if request.method == 'GET': self.permission = True elif request.method != 'GET' and request.user.is_superuser: self.permission = True else: self.permission = True return self.permission class NonAdminCanOnlyGet(permissions.BasePermission): """ Non admin members can only use get requests """ def has_permission(self, request, view): return self._base_check(request) def has_object_permission(self, request, view, obj): return self._base_check(request) def _base_check(self, request): if request.method == "GET": return True else: return request.user and request.user.is_staff class PostPermission(permissions.BasePermission): """ Admins and the post owner can do all requests. But others users(even anon users) only do GET requests """ def has_permission(self, request, view): """ Permissions for routes: GET /posts/ POST /posts/ """ if request.method == "GET": return True if not request.user: return False return request.user.is_authenticated def has_object_permission(self, request, view, post): """ Permissions for routes: GET /posts/:id PUT/PATCH /posts/:id DELETE /posts/:id """ if request.method == "GET": return True if not request.user: return False if request.user.is_staff: return True return post.author == request.user class BlockPermissions(permissions.BasePermission): """ Only logged users can access block class view set """ def has_permission(self, request, view): """ Permissions for routes: GET /posts/ POST /posts/ """ if not request.user: return False if request.user.is_anonymous: return False return request.user.is_authenticated def has_object_permission(self, request, view, block): """ Permissions for routes: GET /posts/:id PUT/PATCH /posts/:id DELETE /posts/:id """ if not request.user: return False return block.blocker == request.user class GetSupportPermission(permissions.BasePermission): """ Admins and the post owner can do all requests. But others users(even anon users) only do GET requests """ def has_permission(self, request, view): """ Permissions for routes: GET /posts/ POST /posts/ """ if not request.user: return False if request.user.is_anonymous: return False return True def has_object_permission(self, request, view, support): if request.method == "GET": return True if not request.user: return False if request.user.is_staff: return True return support.student_from == request.user or support.student_to == request.user <file_sep>/compose/prod/Dockerfile # Build an debian image FROM python:3.6 # Install SO dependecies RUN apt-get update && apt-get install -y \ python3-dev \ python3-pip \ libpq-dev \ python3-setuptools \ gettext \ vim \ build-essential # Install pip dependecies RUN pip3 install --upgrade pip # Insert Enviroment variable ENV MODE_ENVIROMENT=production # Create software folder ADD . /software WORKDIR /software RUN pip3 install -r requirements.txt # Expose the port 8000 EXPOSE 8000 # Run the dev script before and after any command RUN chmod +x compose/prod/prod.sh ENTRYPOINT ["compose/prod/prod.sh"] # Run the server CMD ["gunicorn", "--bind 0.0.0.0:8000", "unbfeelings.wsgi"] <file_sep>/api/views/subject_views.py from rest_framework.viewsets import ModelViewSet from api.serializers import SubjectSerializer from api.models import Subject from api.permissions import NonAdminCanOnlyGet class SubjectViewSet(ModelViewSet): """Description: StudentViewSet. API endpoint that allows subjects to be viewed, created, deleted or edited. """ queryset = Subject.objects.all() serializer_class = SubjectSerializer permission_classes = (NonAdminCanOnlyGet, ) def list(self, request): """ API endpoint that allows all subjects to be viewed. --- Response example: ``` { "count": 3, "next": "http://localhost:8000/api/subjects/?limit=100&offset=100", "previous": null, "results": [ { "id": 1, "name": "<NAME> ", "course": 1 }, { "id": 2, "name": "<NAME> ", "course": 1 }, { "id": 3, "name": "<NAME> ", "course": 1 }, } ``` """ response = super(SubjectViewSet, self).list(request) return response def create(self, request): """ API endpoint that allows subjects to be created. --- Body example: ``` { "name": "<NAME>", "course": 2 } ``` Response example: ``` { "id": 4, "name": "<NAME>", "course": 2 } ``` """ response = super(SubjectViewSet, self).create(request) return response def destroy(self, request, pk=None): """ API endpoint that allows subjects to be deleted. """ response = super(SubjectViewSet, self).destroy(request, pk) return response def retrieve(self, request, pk=None): """ API endpoint that allows a specific subject to be viewed. --- Response example: ``` { "id": 1, "name": "<NAME> ", "course": 1 } ``` """ response = super(SubjectViewSet, self).retrieve(request, pk) return response def partial_update(self, request, pk=None, **kwargs): """ API endpoint that allows a subject to be partial edited. --- Body example: ``` { "name": "<NAME>", } ``` Response example: ``` { "id": 1, "name": "<NAME>", "course": 1 } ``` """ response = \ super(SubjectViewSet, self).partial_update(request, pk, **kwargs) return response def update(self, request, pk=None, **kwargs): """ API endpoint that allows a subject to be edited. --- Body example: ``` { "name": "<NAME>", "course": 2 } ``` Response example: ``` { "id": 1, "name": "<NAME>", "course": 2 } ``` """ response = super(SubjectViewSet, self).update(request, pk, **kwargs) return response <file_sep>/api/models.py from django.contrib.auth.models import AbstractUser from django.contrib.auth.validators import UnicodeUsernameValidator from django.db import models from django.utils.translation import gettext_lazy as _ from django.core.exceptions import ValidationError from itertools import chain class Campus(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Course(models.Model): name = models.CharField(max_length=100) campus = models.ForeignKey( Campus, on_delete=models.CASCADE, related_name='courses') def __str__(self): return self.name class Subject(models.Model): name = models.CharField(max_length=200) course = models.ForeignKey( Course, on_delete=models.CASCADE, related_name="subjects") def __str__(self): return self.name class Student(AbstractUser): username_validator = UnicodeUsernameValidator() # Override username to set unique constraint to False username = models.CharField( _('username'), max_length=150, unique=False, help_text=_( 'Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) email = models.EmailField(_('email address'), unique=True) course = models.ForeignKey( Course, on_delete=models.DO_NOTHING, related_name="users", ) EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def list_blocked_users(self): blocks = Block.objects.filter(blocker=self) blocks = blocks.values_list('blocked', flat=True) return Student.objects.filter(pk__in=blocks) def block_user(self, user_id): block = Block() block.blocker = self block.blocked = Student.objects.get(id=user_id) block.save() def blocks(self): """ This method returns all users that this user is not allowed to see their content, because either they blocked him or the other way around """ blocker = Block.objects.filter(blocker=self) blockeds_users = [] for user_block in blocker: blockeds_users.append(user_block.blocked) blocked = Block.objects.filter(blocked=self) for user_block in blocked: blockeds_users.append(user_block.blocker) return blockeds_users def filter_blocked_posts(self, query_posts): """ This method removes all posts that this user is not allowed to see """ blocks = self.blocks() filtered_query_posts = query_posts for block_user in blocks: filtered_query_posts = filtered_query_posts.exclude(author=block_user) return filtered_query_posts class Tag(models.Model): description = models.CharField(max_length=200, unique=True) _quantity = models.IntegerField(default=0, null=True, blank=True) @property def quantity(self): return len(self.posts.all()) def __str__(self): return self.description class Post(models.Model): EMOTIONS = ( ('b', 'Bad'), ('g', 'Good'), ) content = models.CharField(max_length=280) tag = models.ManyToManyField(Tag, blank=True, related_name="posts") author = models.ForeignKey(Student, on_delete=None, related_name="posts") subject = models.ForeignKey( Subject, null=True, blank=True, on_delete=models.CASCADE, related_name="posts") emotion = models.CharField(max_length=1, choices=EMOTIONS, blank=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): tags = ['#' + tag.description for tag in self.tag.all()] tags_str = '(' + ', '.join(tags) + ')' fields = [ self.content, tags_str, self.author.username, self.subject, self.emotion ] out = ', '.join(map(str, fields)) return out class Support(models.Model): student_from = models.ForeignKey( Student, on_delete=models.CASCADE, related_name="supports_given" ) student_to = models.ForeignKey( Student, on_delete=models.CASCADE, related_name="supports_received" ) message = models.CharField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) class SubjectEmotionsCount(): def __init__(self, subject_name, good_count=0, bad_count=0): self.subject_name = subject_name self.good_count = good_count self.bad_count = bad_count def __str__(self): count = {'good': self.good_count, 'bad': self.bad_count} out = '({}, {})'.format(self.subject_name, count) return out def empty(self): return self.bad_count == self.good_count == 0 def validate_post_emotion_choice(sender, instance, **kwargs): valid_emotions = [t[0] for t in sender.EMOTIONS] if instance.emotion not in valid_emotions: raise ValidationError( 'Post Emotion "{}" is not one of the permitted values: {}'.format( instance.emotion, ', '.join(valid_emotions))) models.signals.pre_save.connect(validate_post_emotion_choice, sender=Post) class Block(models.Model): blocker = models.ForeignKey(Student, on_delete=None, related_name="blocker") blocked = models.ForeignKey(Student, on_delete=None, related_name="blocked") <file_sep>/api/migrations/0005_block.py # Generated by Django 2.0.2 on 2018-06-23 16:26 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0004_auto_20180524_2056'), ] operations = [ migrations.CreateModel( name='Block', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('blocked', models.ForeignKey(on_delete=None, related_name='blocked', to=settings.AUTH_USER_MODEL)), ('blocker', models.ForeignKey(on_delete=None, related_name='blocker', to=settings.AUTH_USER_MODEL)), ], ), ]
987e2d302fb08a31555b640ad6f60b2a6b85dd41
[ "Markdown", "Python", "Text", "Dockerfile", "Shell" ]
50
Python
UnbFeelings/unb-feelings-api
73c725113bc89ae4754a68f958eeaae6da85876e
61c141fde594c7365f27beef875520d0684ecb6b
refs/heads/master
<file_sep># OK_CNN Apply Convolutional Neural Network (CNN) to Oklahoma (OK) dataset <file_sep>import pandas as pd from aux import ROOT_DIR def load_catalog(cat_file=None): if not cat_file: cat_file = "Guthrie_catalog.h5" return pd.read_hdf("/".join([ROOT_DIR, "catalog", cat_file]), 'cat') if __name__ == '__main__': import time # Read Catalog into a Pandas dataframe t0 = time.time() cat_file = "/".join([ROOT_DIR, "catalog", "Guthrie.catalog.15MAD.6chan"]) cat = pd.read_csv(cat_file, delim_whitespace=True) print("Loading catalog from original" "file takes {} second".format(time.time() - t0)) # Save catalog in fast access HDF5 format t0 = time.time() cat.to_hdf("/".join([ROOT_DIR, "catalog", "Guthrie_catalog.h5"]), 'cat', format='table', mode='w') print("Saving catalog to HDF5" "file takes {} second".format(time.time() - t0)) # Load catalog in fast HDF5 format t0 = time.time() cat = pd.read_hdf("/".join([ROOT_DIR, "catalog", "Guthrie_catalog.h5"]), 'cat') print("Loading catalog from HDF5" "file takes {} second".format(time.time() - t0)) #----------------------------------------------------------------------# # Count number of events and store in json import json log = {} for i in range(-3, 5): mask = (cat['Magnitude'] > i) & (cat['Magnitude'] < i+1) count = len(cat[mask].index) mag_range = "{:2} ~ {:2}".format(i, i+1) log[mag_range] = count print(log) with open("/".join([ROOT_DIR, "log", "magnitude_distribution.json"]), 'w') as f: json.dump(log, f) #----------------------------------------------------------------------# # Plot event distribution on map import matplotlib.pyplot as plt fig, ax = plt.subplots() for i in range(len(cat.index)): ax.plot(cat.LON[i], cat.LAT[i], 'ko', markerfacecolor='none', markersize=(cat.Magnitude[i]*3)) ax.grid(True) ax.set_xlim(-97.6, -97.3) ax.set_ylim(35.7, 35.9) plt.show() <file_sep>#!/bin/bash # Prepare catalog in the Pandas HDF5 format ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd)" python ${ROOT_DIR}/src/catalog.py
fe408f90c8a7f58cbbf42c909303fb0900263f44
[ "Markdown", "Python", "Shell" ]
3
Markdown
lijunzh/OK_CNN
75885458418501cdb6628490d4ae9ee3e7bd74a7
590515682ad4e17f30be02de425aa2dabb970855
refs/heads/master
<repo_name>ccarr419/Academic-Projects<file_sep>/csc402/assignment2/BankAccount.h /** A bank account has a balance and a mechanism for applying interest or fees at the end of the month. */ #ifndef BANKACCOUNT_H #define BANKACCOUNT_H #include <iostream> using namespace std; class BankAccount { private: int accountNumber; double balance; /** Constructs a bank account with zero balance. */ public: BankAccount(); /** Constructs a bank account with initialized account number and balance. */ BankAccount(int n, float b); /** Set account number. @param account number */ void setAccountNumber(int n); /** Get account number. @return account number */ int getAccountNumber(); /** Makes a deposit into this account. @param amount the amount of the deposit */ void deposit(double amount); /** Makes a withdrawal from this account, or charges a penalty if sufficient funds are not available. @param amount the amount of the withdrawal */ /*this function should be override by subclasses, for checking account, after every withdraw, the number of withdraws should be decreased for saving account, the minBalance should be check before each withdraw. */ virtual void withdraw(double amount); /** Carries out the end of month processing that is appropriate for this account. For checking account, reset the transaction count to 3 For saving account, calculate the interests and accumulate the balance */ virtual void monthEnd() = 0; void setBalance(float amount); /** Gets the current balance of this bank account. @return the current balance */ double getBalance(); /** print the current balance of this bank account. @return the current balance */ void printAccount(ostream &out); }; #endif <file_sep>/csc421/assignment3/src/com/yahtzee/client/Yahtzee.java package com.yahtzee.client; import com.yahtzee.client.YLogic; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.ToggleButton; import com.google.gwt.user.client.ui.HTML; /* * Author: <NAME> * File Name: Yahtzee.java * File Package: com.yahtzee.client * File Version: 1.0 * File Date: 10/05/2017 * Due Date: 11/03/2017 * Assignment: #3 * Professor: Dr. <NAME> * Course #: CSC421 * Course Name: Web-Based Software Design & Development * University: Kutztown University * Major: CSCM Software Development */ /** * The Yahtzee class represents a game of Yahtzee in the form of a GUI. * This is made possible by the use of the GWT. GWT makes it possible for * java code to be run on the web by turning the java byte code into javascript. * This makes is very to easy to transfer a logic-heavy game of Yahtzee * into a GUI for anyone to play. The logic for the game of Yahtzee was * taken from a previous version of the project and adapted for use in a GUI. * Fortunately not much modification was needed as GWT does much of the heavy * lifting. Most if not all of the user/game interaction is handled by a * handful of buttons and widgets that hold said buttons. */ public class Yahtzee implements EntryPoint { Grid gameGrid; //Dice container YLogic gLog; //Yahtzee game logic /** * This function instantiates the GWT module by creating widgets required * for the game to work and placing them inside webpage. Thus creating * the GUI representing a game of Yahtzee. */ public void onModuleLoad() { gLog = new YLogic(); gameGrid = new Grid(1, gLog.dice.NUM_DICE); //Create a button for each die and place it in the game grid for(int col = 0; col < gLog.dice.NUM_DICE; col++) { final int i = col; ToggleButton b = createDiceButton(i); gameGrid.setWidget(0, col, b); } //Create a button to roll the dice Button rollB = createRollButton(gameGrid); //Create a button to take the player to the readme so they can learn //how to play the game or pick up any other useful information Button helpB = new Button("How To Play", new ClickHandler() { public void onClick(ClickEvent event) { Window.open( "http://csitrd.kutztown.edu/~ccarr419/csc421/assignment3/README.txt", "_blank", ""); } }); //Place all the widgets in the RootPanel a.k.a. the webpage rollB.setWidth("150px"); helpB.setWidth("150px"); RootPanel.get("GameContainer").add(gameGrid); RootPanel.get("RollContainer").add(rollB); RootPanel.get("HelpContainer").add(helpB); RootPanel.get("CategoryContainer").add(createCatGrid()); } /** * Creates a grid containg every category in the game and their current * scores. Scores depend on the current dice configuration. Categories * can be picked with a button in the same row. Categories that were picked * will be crossed out and have their buttons disabled. * @return The grid containing the categories, scores and buttons */ public Grid createCatGrid() { Grid categoryGrid = new Grid(gLog.ROUND_LIMIT, 3); int[] scores = gLog.findDiceScores(); int i = 0; //Create a row for every category for(final YLogic.Categories cat : gLog.c.values()) { final int idx = i; final int score = scores[i]; //Replace the underscores in the name with spaces final String str = cat.toString().replaceAll("_", " "); //Create a button that picks that category Button b = new Button("Pick Category", new ClickHandler() { public void onClick(ClickEvent event) { //Make sure that this is what the user wants to do if(!Window.confirm("Pick " + str + " and score " + score + "?")) { return; } //Make sure that the category is picked and cannot be //picked again gLog.setCatPicked(idx, true); gLog.setCatScore(idx, score); Element e = Document.get().getElementById("CatContainer" + idx); e.setInnerText("" + score); resetRound(); //End the round and proceed to the next } }); //If this category was picked already cross it out if(gLog.getCatPicked(idx)) { b.setEnabled(false); HTML h = new HTML("<strong><del>" + str + "</del></strong>"); categoryGrid.setWidget(idx, 0, h); categoryGrid.setText(idx, 1, "x"); } else { //Otherwise display it as normal HTML h = new HTML("<strong>" + str + "</strong>"); categoryGrid.setWidget(idx, 0, h); categoryGrid.setText(idx, 1, "" + score); } //Format each cell to a css class rule categoryGrid.getCellFormatter().setStyleName(idx, 0, "gridCell"); categoryGrid.getCellFormatter().setStyleName(idx, 1, "gridCell"); categoryGrid.getCellFormatter().setStyleName(idx, 2, "gridCell"); //Alternate the background color for readability if(idx % 2 != 0) { categoryGrid.getRowFormatter().setStyleName(idx, "altRow"); } else { categoryGrid.getRowFormatter().setStyleName(idx, "gridRow"); } //Format everything else categoryGrid.setStyleName("gridStyle"); b.setStyleName("gridButton"); categoryGrid.setWidget(idx, 2, b); i++; } return categoryGrid; } /** * Removes the old category grid and replaces it with a new updated grid. * Updated scores and crosses out picked categories. */ public void resetCatGrid() { RootPanel cc = RootPanel.get("CategoryContainer"); cc.remove(cc.getWidget(0)); cc.add(createCatGrid()); } /** * Creates the button to roll the dice. Once pressed, the button will ask * the player if they wish to continue with the roll if they did not pick * dice to keep. If the player has picked dice to keep or they bypassed the * warning all non-kept dice are rolled and replaced with new dice. The roll * button may only be used if the player has not used up all of their rolls for * the round and the game is not over. Otherwise the button will be disabled. * @param g The grid containing the game's dice * @return The roll button created */ public Button createRollButton(final Grid g) { Button rollB = new Button("Roll", new ClickHandler() { public void onClick(ClickEvent event) { //Make sure the user wants to roll if they did not pick any //dice to keep if(!gLog.getPlayerKept()) { if(!Window.confirm("You did not pick dice to keep. Roll anyway?")) { return; } } gLog.playerRoll(); Button tmp = (Button) event.getSource(); //Roll the dice and replace all non-kept dice for(int col = 0; col < gLog.dice.NUM_DICE; col++) { ToggleButton gB = (ToggleButton) g.getWidget(0, col); gB.setText("" + gLog.dice.getDie(col)); } //Update category scores, round and roll information resetCatGrid(); updateRoundAndRoll(tmp); } }); return rollB; } /** * Creates a button that represents a die. The button will contain a * number that is its die-face number. If the player clicks the die it * will act as the player keeping the die. The player can click the die * again to not keep the die; essentially acting as a toggle between keeping * and not keeping the die. * @param num The die to retrieve * @return The dice button created */ public ToggleButton createDiceButton(final int num) { ToggleButton b = new ToggleButton(("" + gLog.dice.getDie(num)), new ClickHandler() { public void onClick(ClickEvent event) { ToggleButton tmp = (ToggleButton) event.getSource(); if(tmp.isDown()) { //While the button is down, keep the die gLog.dice.setKeptDie(num, true); gLog.setPlayerKept(true); } //Otherwise do not keep the die else { gLog.dice.setKeptDie(num, false); } } }); b.setPixelSize(50, 50); return b; } /** * Updates the scores in the player scoresheet. Totals will be calculated * and added. Bonus applicability will be judged and calculated. Also the * yahtzee bonus checkmarks will be added if also applicable. */ public void updateScores() { //Make an array of totals for easy insertion into the scoresheet final int[] totals = { gLog.upperTotal(), gLog.upperTotal() + gLog.upperBonus(), gLog.upperTotal() + gLog.upperBonus(), gLog.lowerTotal() + gLog.lowerBonus(), gLog.grandTotal() }; //Make an array of bonuses for easy insertion into the scoresheet final int[] bonuses = { gLog.upperBonus(), gLog.lowerBonus() }; for(int i = 0; i < totals.length; i++) { //Insert every total final int idx = i; Element e = Document.get().getElementById("TotalContainer" + idx); e.setInnerHTML("<strong>" + totals[idx] + "</strong>"); } for(int i = 0; i < bonuses.length; i++) { //Insert every bonus final int idx = i; Element e = Document.get().getElementById("BonusContainer" + idx); e.setInnerHTML("<strong>" + bonuses[idx] + "</strong>"); } String yStr = ""; //Create the string of checkmarks for every Yahtzee bonus for(int i = 0; i < gLog.getYahtzeeCount()-1; i++) { yStr += "&#10003;"; } //Then add that string to the checksheet Element e = Document.get().getElementById("YahtzeeCountContainer"); e.setInnerHTML("<strong>" + yStr + "</strong>"); } /** * Updates the round and roll numbers. If the player has used all of their * rolls, the roll button will be deactivated. If the player has ran out * of rounds the roll button will be deactivated. * @param b The roll button */ public void updateRoundAndRoll(Button b) { //Get the element that contains the roll and round numbers Element e1 = Document.get().getElementById("RoundNumContainer"); Element e2 = Document.get().getElementById("RollNumContainer"); //Player exceeded round limit? Game is over. if(gLog.getRoundNum() > gLog.ROUND_LIMIT) { e1.setInnerText("Game"); e2.setInnerText("Over"); b.setEnabled(false); //Disable roll button } else { //Otherwise game is still in progress e1.setInnerText("Round #" + gLog.getRoundNum()); e2.setInnerText("Roll #" + gLog.getRollNum()); //If the player ran out of rolls, disable the roll button if(gLog.getRollNum() >= gLog.ROLL_LIMIT) { b.setEnabled(false); } else { b.setEnabled(true); } } } /** * Resets the round by progressing the game to the next round. This function * should be called immediately at the end of a round. This function will * end the round and bring the game to the beginning the next round. Thus * updating scores, dice, and available categories accordingly. */ public void resetRound() { //Increment the Yahtzee count if the dice is a Yahtzee and the //Yahtzee category was filled with a non-zero score. if(gLog.dice.isYahtzee() && gLog.getCatPicked(gLog.c.YAHTZEE.value())) { gLog.incYahtzeeCount(); } //End the round and fill in the score for this round gLog.endRound(); updateScores(); //Reset the roll button and roll the dice for the new round Button b = (Button) RootPanel.get("RollContainer").getWidget(0); Grid g = (Grid) RootPanel.get("GameContainer").getWidget(0); for(int col = 0; col < gLog.dice.NUM_DICE; col++) { ToggleButton tB = createDiceButton(col); g.setWidget(0, col, tB); } //Update scores, round and roll numbers for new round resetCatGrid(); updateRoundAndRoll(b); } } <file_sep>/csc570/DataMineTensorFlow/CSC458DataMineI/water_data.py import pandas as pd import tensorflow as tf TRAIN_FILE = 'csc458water_training49k_e.csv' TEST_FILE = 'csc458water_testing491k_e.csv' CSV_COLUMN_NAMES = [ 'pH', 'TempCelsius', 'Conductance', 'GageHt', 'DischargeRate', 'TimeOfYear', 'TimeOfDay', 'month', 'MinuteOfDay', 'MinuteFromMidnite', 'MinuteOfYear', 'MinuteFromNewYear', 'OxygenMgPerLiter'] CLASSIFICATIONS = 10 LABEL_NAMES = [ "'\'(-inf-2.27]\''","'\'(2.27-4.44]\''","'\'(4.44-6.61]\''", "'\'(6.61-8.78]\''","'\'(8.78-10.95]\''","'\'(10.95-13.12]\''", "'\'(13.12-15.29]\''","'\'(15.29-17.46]\''","'\'(17.46-19.63]\''", "'\'(19.63-inf)\''" ] CSV_COLUMN_DEFAULTS = [[0.0], [0.0], [0.0], [0.0], [0.0], [0], [0], [0], [0], [0], [0], [0], [0]] def load_data(y_name='OxygenMgPerLiter'): """Returns the iris dataset as (train_x, train_y), (test_x, test_y).""" train = pd.read_csv(TRAIN_FILE, names=CSV_COLUMN_NAMES, header=0) train = train.fillna(0) train_x, train_y = train, train.pop(y_name) test = pd.read_csv(TEST_FILE, names=CSV_COLUMN_NAMES, header=0) test = test.fillna(0) test_x, test_y = test, test.pop(y_name) return (train_x, train_y), (test_x, test_y) def train_input_fn(features, labels, batch_size): """An input function for training""" # Convert the inputs to a Dataset. dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels)) # Shuffle, repeat, and batch the examples. dataset = dataset.shuffle(1000).repeat().batch(batch_size) # Return the dataset. return dataset def eval_input_fn(features, labels, batch_size): """An input function for evaluation or prediction""" features = dict(features) if labels is None: # No labels, use only features. inputs = features else: inputs = (features, labels) # Convert the inputs to a Dataset. dataset = tf.data.Dataset.from_tensor_slices(inputs) # Batch the examples assert batch_size is not None, "batch_size must not be None" dataset = dataset.batch(batch_size) # Return the dataset. return dataset # The remainder of this file contains a simple example of a csv parser, # implemented using a the `Dataset` class. # `tf.parse_csv` sets the types of the outputs to match the examples given in # the `record_defaults` argument. def _parse_line(line): # Decode the line into its fields fields = tf.decode_csv(line, record_defaults=CSV_COLUMN_DEFAULTS) # Pack the result into a dictionary features = dict(zip(CSV_COLUMN_NAMES, fields)) # Separate the label from the features label = features.pop('OxygenMgPerLiter') return features, label def csv_input_fn(csv_path, batch_size): # Create a dataset containing the text lines. dataset = tf.data.TextLineDataset(csv_path).skip(1) # Parse each line. dataset = dataset.map(_parse_line) # Shuffle, repeat, and batch the examples. dataset = dataset.shuffle(1000).repeat().batch(batch_size) # Return the dataset. return dataset <file_sep>/csc520/finalproj/src/com/library/protocol/field_list/PAddress.java package com.library.protocol.field_list; import com.library.business_layer.field_list.Address; /** * PAddress serves as a protocol to transfer Table information from the server * to the UI. Only serves as a way to view, print and facilitate information. * PROTOCOL LAYER * @see com.library.business_layer.field_list.Address */ public class PAddress { private String house; private String street; private String county; private String zip; /** * Basic constructor that sets all attributes. * @param h String house number * @param s String street address * @param c String address county * @param z String zip code */ public PAddress(String h, String s, String c, String z) { house = h; street = s; county = c; zip = z; } /** * @return String house number * @see com.library.business_layer.field_list.Address#getHouse() */ public String getHouse() { return house; } /** * @return String street address * @see com.library.business_layer.field_list.Address#getStreet() */ public String getStreet() { return street; } /** * @return String address county * @see com.library.business_layer.field_list.Address#getCounty() */ public String getCounty() { return county; } /** * @return String zip code * @see com.library.business_layer.field_list.Address#getZip() */ public String getZip() { return zip; } /** * Prints the Address in a human understandable summary. */ public String toString() { String out = ""; out += (getHouse() + " " + getStreet() + "\n"); out += (getCounty() + " " + getZip() + "\n"); return out; } } <file_sep>/csc136/testdebugger/debug.cpp // File: debug.cpp // Application for Demo class #include <iostream> #include "demo.h" using namespace std; Demo fun(Demo tmp1, Demo &tmp2); void quick(Demo &d); int main() { Demo d1(1); quick(d1); Demo d2(2, 20.0); d1 = fun(d1,d2); cout << d2.getX(); d1++; return(0); } Demo fun(Demo tmp1, Demo& tmp2) { cout << "*"; tmp2 = tmp1; return tmp2; } void quick(Demo &d) { cout << "R"; Demo quickD(d); } <file_sep>/csc402/inclassprograms/studentStruct.cpp #include <iostream> using namespace std; studentType getOlder(studentType); void getOlder(studentType&); struct studentType { string name; int age; float gpa; }; int main() { studentType s1; s1.name = "Chris"; s1.age = 21; s1.gpa = 3.0; getOlder(s1); cout << s1.age << endl; return 0; } studentType getOlder(studentType s1) { s1.age++; return s1; } void getOlder(studentType &s1) { s1.age++; } <file_sep>/csc237/project2/makefile #Author: <NAME> #Course: CSC 237 #File: makefile #Purpose: Makes possible to link multiple files together CC=/opt/csw/gcc3/bin/g++ DebugFlag=-g app: app.o WordData.o WordDataList.o WordDataDLinkList.o DLinkedList.o $(CC) $(DebugFlag) -o app app.o WordData.o WordDataList.o WordDataDLinkList.o DLinkedList.o testll: testll.o DLinkedList.o WordData.o $(CC) $(DebugFlag) -o testll testll.o DLinkedList.o WordData.o WordData.o: WordData.cpp WordData.h $(CC) $(DebugFlag) -c WordData.cpp WordDataList.o: WordData.h WordDataList.cpp WordDataList.h WordList.h $(CC) $(DebugFlag) -c WordDataList.cpp WordDataDLinkList.o: WordDataDLinkList.cpp WordDataDLinkList.h DLinkedList.h $(CC) $(DebugFlag) -c WordDataDLinkList.cpp DLinkedList.o: DLinkedList.cpp DLinkedList.h types.tpp cp DLinkedList.cpp temp.cpp cat types.tpp >> temp.cpp # Compile temporary file created with instantiations at the end; save as DLinkedList.o $(CC) -c temp.cpp -g -o DLinkedList.o app.o: WordDataList.h WordList.h WordDataDLinkList.h Node.h app.cpp $(CC) $(DebugFlag) -c app.cpp testll.o: testll.cpp DLinkedList.h WordData.h Node.h $(CC) $(DebugFlag) -c testll.cpp clean: \rm -rf *.o testLL <file_sep>/csc402/assignment3/chain.h /* Author: <NAME> File: chain.h About: The chain class is a child of the linearList abstract class. Member functions override linearList's member functions through polymorphism. A chain is made up of chain nodes. */ #include <iostream> #include <assert.h> #include "chainNode.h" #include "linearList.h" using namespace std; template<class T> class chain : public linearList<T> { public: chain(); chain(const chain<T>& theChain); ~chain(); bool empty() const { return listSize == 0; } int size() const { return listSize; } T& get(int theIndex) const; int indexOf(const T& theElement) const; void erase(int theIndex); void insert(int theIndex, const T& theElement); void output(ostream& out) const; protected: void checkIndex(int theIndex) const; chainNode<T>* firstNode; int listSize; }; template<class T> chain<T>::chain() { firstNode = NULL; listSize = 0; } template<class T> chain<T>::chain(const chain<T>& theChain) { if(theChain.empty()) { listSize = theChain.listSize; firstNode = theChain.firstNode; } else { chainNode<T> *p = firstNode; for(chainNode<T> *currentNode = theChain.firstNode; currentNode != NULL; currentNode = currentNode->next) { p = currentNode; p = p->next; listSize++; } } } template<class T> chain<T>::~chain() { while(firstNode != NULL) { chainNode<T> *nextNode = firstNode->next; delete firstNode; firstNode = nextNode; } } template<class T> T& chain<T>::get(int theIndex) const { checkIndex(theIndex); chainNode<T> *currentNode = firstNode; for(int i = 0; i < theIndex; i++) currentNode = currentNode->next; return currentNode->element; } template<class T> int chain<T>::indexOf(const T& theElement) const { chainNode<T> *currentNode = firstNode; int index = 0; while(currentNode != NULL && currentNode->element != theElement) { currentNode = currentNode->next; index++; } if(currentNode == NULL) return -1; else return index; } template<class T> void chain<T>::erase(int theIndex) { checkIndex(theIndex); chainNode<T> *deleteNode; if(theIndex == 0) { deleteNode = firstNode; firstNode = firstNode->next; } else { chainNode<T> *p = firstNode; for(int i = 0; i < theIndex - 1; i++) p = p->next; deleteNode = p->next; p->next = deleteNode->next; } delete deleteNode; listSize--; } template<class T> void chain<T>::insert(int theIndex, const T& theElement) { checkIndex(theIndex); if(theIndex == 0) firstNode = new chainNode<T>(theElement, firstNode); else { chainNode<T> *p = firstNode; for(int i = 0; i < theIndex - 1; i++) p = p->next; p->next = new chainNode<T>(theElement, p->next); } listSize++; } template<class T> void chain<T>::output(ostream& out) const { for(chainNode<T> *currentNode = firstNode; currentNode != NULL; currentNode = currentNode->next) out << currentNode->element << " "; } template<class T> void chain<T>::checkIndex(int theIndex) const { chainNode<T> *p = firstNode; for(int i = 0; i < theIndex; i++) { assert(p); p = p->next; } } //Explicit initializers so template class knows what types it can use template class chain<int>; template class chain<char>; template class chain<bool>; template class chain<float>; template class chain<double>; template class chain<long>; template class chain<string>; <file_sep>/csc330/finalproject/README.txt Author: <NAME> Date: May 2016 Course: CSC 330 Application Development I developed an Android application that would simulate a game of blackjack. The user must first create an account and be entered into the app database. Then they may log in and see their balance (digital currency to use for bets in-game). Every user starts with an initial 1000 chips. From there the user may begin to play by placing a bet and dealing from the deck or reshuffling the deck if deemed necessary. At any time during the game the user can end the game and go back to their profile page. During the game the user's options are: hit (request an additional card), stick (end your turn), fold (forfeit the round), double down (double your bet and agree to take one additional card and end your turn), or split hand (only appears when player is dealt cards of the same number on initial dealing). The point of splitting a hand is to give the user two hands which behave the same as a normal hand. These two hands will give the user double the chance to win. Losing a round means the player relinquishes their bet, winning a round means they will keep their bet and win and equal amount in addition to their original bet. The user can have a negative balance to represent owing the house. <file_sep>/csc136/project3b/term.h /* Author: <NAME> File: term.h Description: Definition of the Term class. The Term class contains a coefficient and exponent which is used and implemented by the Array class. This class also has the ability to multiply, evaluate, input and output a Term as well as check if the exponent is equal to an int and check if two Terms are greater/less than each other. */ #ifndef TERM_H #define TERM_H #include <iostream> using namespace std; class Term { public: ///////////////// //Constructor ///////////////// /* Function: Constructor Member Type: Mutator Description: Sets coefficient and exponent to zero Parameters: None Returns N/A */ Term(float coeff = 0, int expn = 0); ///////// //Sets ///////// /* Function: setTerm Member Type: Mutator Description: Sets the coefficient and exponent in the term Parameters: float - coefficient to put in the term int - exponent to put in the term Returns: true if value is set, false if not */ bool setTerm(float coeff, int expn); /* Function: setCoefficient Member Type: Mutator Description: Sets the coefficient in the term Parameters: float - coefficient to put in the term Returns: true if value is set, false if not */ bool setCoefficient(float coeff); /* Function: setExponent Member Type: Mutator Description: Sets the exponent in the term Parameters: int - exponent to put in the term Returns: true if value is set, false if not */ bool setExponent(int expn); ///////// //Gets ///////// /* Function: getCoefficient Member Type: Inspector Description: Returns the coefficient value of the term Parameters: none Returns: float - coefficient */ float getCoefficient() const; /* Function: getExponent Member Type: Inspector Description: Returns the exponent value of the term Parameters: none Returns: int - exponent */ int getExponent() const; ////////////// //Operators ////////////// /* Function: *= operator Member Type: Mutator Description: Multiplies term coefficient by a factor Parameters: double - factor to multiply by Returns: void */ void operator *=(double); /* Function: () operator Member Type: Facilitator Description: Evaluates the term for the given factor Parameters: double - factor to evaluate the term by Returns: double - the term evaluated */ double operator ()(double) const; /* Function: == operator Member Type: Facilitator Description: Checks if the exponent of a term is equal to the given integer Parameters: int - number to check if equal to Returns: true if the exponent is equal, false if not */ bool operator ==(int) const; /* Function: < operator Member Type: Facilitator Description: Checks if the Term is less than a given Term Parameters: Term& - Term to check if greater than Term Returns: true if the term is less than the other term, false if not */ bool operator <(const Term &) const; private: float coefficient; int exponent; }; //////////////////////// //Associative Operators //////////////////////// /* Function: >> operator Description: Takes input and places it inside the term's coefficient and exponent. Enables cin << Term Parameters: ifstream& - input stream Term& - The Term from user-input Returns: ifstream */ ifstream &operator>>( ifstream &, Term & ); /* Function: << operator Description: Outputs the Term in correct polynomial form Enables cout << Term Parameters: ostream& - the output stream const Term& - the Term to ouput Returns: ostream */ ostream &operator<<( ostream &, const Term & ); #endif <file_sep>/csc402/inclassprograms/handinprograms/wordCount.cpp #include <iostream> #include <fstream> #include <cctype> #include <map> using namespace std; int main() { ifstream inf; inf.open("article.txt"); map<string, int> m; int num; char c; string str = ""; while(inf.get(c)) { if(c >= 65 && c <= 122) { c = tolower(c); str += c; } else { if(str == "") continue; else if(!m.count(str)) m.insert(pair<string, int>(str, 1)); else { map<string, int>::iterator it = m.find(str); it->second++; } str = ""; } } map<string, int>::iterator max = m.begin(); for(map<string, int>::iterator i = m.begin(); i != m.end(); ++i) { if(i->second > max->second) max = i; } cout << "The word that occurs the most is '"; cout << max->first << "' with " << max->second << " occurrences.\n"; } <file_sep>/csc242/Project/searchstart.php <?php session_start(); $loggedin = $_SESSION['loggedin']; /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/searchstart.php Course: CSC 242 - Fall 2013 */ echo "<html xmlns = 'http://www.w3.org/1999/xhtml'> <head> <title> Chris' Book Store </title> <script type = 'text/javascript'> <!-- //Check for empty input and send to search.php //Send ISBN to search by function sISBN() { var isbn = document.getElementById('isbn').value; if(isbn.length < 1) window.alert('Please enter a ISBN to search for'); else document.forms['searchISBN'].submit(); } //Check for empty input and send to search.php //Send keyword to search by function sKeyword() { var keyword = document.getElementById('keyword').value; if(keyword.length < 1) window.alert('Please enter a keyword to search for'); else document.forms['searchKeyword'].submit(); } //--> </script> <!-- My stylesheet for the project --> <link rel = 'stylesheet' type = 'text/css' href = 'projectstyle.css'/> </head> <body> <!-- Links --> <div class = 'header'><h1>Chris' Book Store</h1></div> <div class = 'special'> <h3><p class = 'one'> <a class = 'link' href = 'myproject.php'>Home</a> &nbsp; | &nbsp;"; if($loggedin == true) echo "<a class = 'link' href = 'loggedout.php'>Log Out</a> &nbsp; | &nbsp;"; else echo "<a class = 'link' href = 'login.html'>Log In</a> &nbsp; | &nbsp;"; echo "<a class = 'link' href = 'createaccount.php'>Create Account</a> &nbsp; | &nbsp; <a class = 'link' href = 'contact.php'>Contact Us</a> &nbsp; | &nbsp; <a class = 'link' href = 'categories.php'>Categories</a> &nbsp; | &nbsp; <a class = 'link' href = 'searchstart.php'>Search</a> &nbsp; | &nbsp; <a class = 'link' href = 'orders.php'>View Orders</a> &nbsp; | &nbsp; <a class = 'link' href = 'viewcart.php'>View Cart</a> </p></h3></div> <br/> <!-- Textbox to search by ISBN --> <div class = 'header'> <form id = 'searchISBN' action = 'search.php' method = 'post'> <h3><p><label>Search by ISBN: </label> &nbsp; &nbsp; &nbsp; &nbsp; <input id = 'isbn' name = 'isbn' type = 'text'/> <!-- Click to search by ISBN --> <input type = 'button' value = 'Search' onClick = 'sISBN()'/></p></h3></form> <form id = 'searchKeyword' action = 'search.php' method = 'post'> <!-- Textbox to search by Keyword --> <h3><p><label>Search by Keyword: </label> &nbsp; <input id = 'keyword' name = 'keyword' type = 'text'/> <!-- Button to search by Keyword --> <input type = 'button' value = 'Search' onClick = 'sKeyword()'/></p></h3> </form> </div> </body> </html>"; ?> <file_sep>/csc402/assignment6/arrayBsDemo.cpp /* Author: <NAME> File: treeTest.cpp Date: 10/18/2015 Class: CSC 402 About: Tests the treeGraph by inserting a number of nodes into the tree and then printing the tree in order, pre order and post order. */ #include <iostream> #include "arrayBsTree.h" using namespace std; int main() { bsTree *myTree; myTree = new arrayBsTree; //Insert nodes into tree myTree->insert(22); myTree->insert(3); myTree->insert(75); myTree->insert(10); myTree->insert(7); myTree->insert(1); myTree->insert(2); myTree->insert(34); myTree->insert(57); myTree->insert(100); myTree->insert(81); myTree->insert(0); myTree->insert(14); myTree->insert(28); myTree->insert(105); myTree->insert(79); myTree->erase(22); myTree->erase(100); myTree->erase(3); myTree->erase(75); myTree->erase(0); cout << "In Order: "; myTree->inOrder(cout); cout << endl; cout << "Pre Order: "; myTree->preOrder(cout); cout << endl; cout << "Post Order: "; myTree->postOrder(cout); cout << endl; cout << "Level Order: "; cout << endl; myTree->lvlOrder(cout); if(myTree->find(22)) cout << "Root 22 found\n"; if(myTree->find(0)) cout << "Leaf 0 found\n"; if(myTree->find(10)) cout << "Leaf 10 found\n"; if(myTree->find(79)) cout << "Leaf 79 found\n"; if(myTree->find(105)) cout << "Leaf 105 found\n"; if(!myTree->find(88)) cout << "Leaf 88 not found\n"; return 0; }<file_sep>/sideprojects/coordinateConvert.cpp /***************************************************************************** * Author: <NAME> * File: coordinateConvert.cpp * Created: 11/30/2015 * About: This program converts latitude and longitude coordinates from * an input file to computer notation in an output file. *****************************************************************************/ #include <iostream> #include <fstream> #include <iomanip> using namespace std; //This structure holds an individual longitude or latitude's coordinates struct coordinate { int degrees; double minutes; double seconds; char hemisphere; }; //This structure holds the complete latitude and longitude coordinates struct coordinates { coordinate lat; coordinate lon; }; /***************************************************************************** * Function: convert * Parameters: const coordinate& - input only * Return Value: double - the converted coordinate * About: Converts a coordinate object into a coordinate number *****************************************************************************/ double convert(const coordinate&); int main() { ifstream inf; //input file ofstream ofs; //output file coordinates c; cout << "Converting coordinates... "; inf.open("coordinates.dat"); ofs.open("convertedCoordinates.dat"); while(!inf.eof()) { inf >> c.lat.degrees; if(c.lat.degrees == -1) //-1 designates end of input break; inf >> c.lat.minutes >> c.lat.seconds >> c.lat.hemisphere; inf >> c.lon.degrees >> c.lon.minutes >> c.lon.seconds; inf >> c.lon.hemisphere; ofs << setprecision(8); ofs << convert(c.lat); ofs << setw(4) << "\t"; ofs << convert(c.lon) << endl; } cout << "done\n"; inf.close(); ofs.close(); return 0; } //Takes the coordinates individual values to converts them into //a floating-point number. The new converted number is the return value. double convert(const coordinate& c) { int degree = c.degrees; double minute = c.minutes*60; double second = c.seconds; double coord = degree + ((minute+second)/3600); //Western and Southern hemispheres designate negative numbers if(tolower(c.hemisphere) == 'w' || tolower(c.hemisphere) == 's') coord = -1 * coord; return coord; }<file_sep>/csc510/assignment5/readWriteSTM.cpp /* Author: <NAME> Date: 12/04/17 Due Date: 12/12/17 File: readWriteSTM.cpp Assignment: #5 Course: CSC510 Advanced Operating Systems Professor: Dr. Parson University: Kutztown University of Pennsylvania About: This project's goal is to create a state machine that successfully implements solutions to the Readers/Writers Problem. There are five solutions that this project implements. Weak Reader Preference, Strong Reader Preference, Weak Writer Preference, Strong Writer Preference, and Fair. Each successfully deals with the problem but some are faster and more efficient than others. A problem that occurs with some of the methods (namely the 'strong' preferences) is starvation. The Readers/Writers problem has no remedy for starvation since it is a byproduct of some of its more harsh implementations. Thus starvation must be weighed against the benefits and what the scheduler is trying to achieve. FCFS is added as a control algorithm to show the benefits of alternate solutions which implement concurrency among readers. Implementation of the scheduler functions are to be carried out in their own individual files. As such only functions which set up and tear down the actual STM are implemented here for consitency. The main solution of all the RW alogrithms is the use concurrency among readers i.e. multiple readers are allowed in the critical section. Writers are not allowed to be concurrent and thus each writer must have exclusive access to the critical section always. */ #include <iostream> #include <fstream> //Log Tools #include <sstream> //Log Tools #include <iomanip> //Log Tools #include <deque> //Thread Queueing #include <chrono> //Timing #include <cstdatomic> //Atomic variables #include <pthread.h> //Threads #include "readWriteSTM.h" using namespace std; //Time variable used to get the programs duration static auto timeStart = chrono::high_resolution_clock::now(); /* Function Name: readWriteStm Function Type: constructor Parameters: n/a Returns: n/a About: Constructs the STM object by opening the log and starting off each thread to be create at the init state. */ readWriteSTM::readWriteSTM() { logFile.open("readWriteSTM.log"); } /* Function Name: ~readWriteStm Function Type: destructor Parameters: n/a Returns: n/a About: Terminates the STM by closing the log and destroying all mutexes and condition objects in use. */ readWriteSTM::~readWriteSTM() { logFile.close(); //Close the log file to prevent mishaps //Destroy all mutexes and conditions just to be sure pthread_mutex_destroy(&lMtx); pthread_cond_destroy(&lCon); pthread_mutex_destroy(&csMtx); pthread_cond_destroy(&csCon); pthread_mutex_destroy(&rMtx); pthread_cond_destroy(&rCon); pthread_mutex_destroy(&wMtx); pthread_cond_destroy(&wCon); } /* Function Name: makingThreads Function Type: mutator Parameters: int - the number representing the algorithm to use Returns: n/a About: Represents a processor creating threads and delegating tasks to them. The processor waits a certain amount of time between creating threads to prevent race conditions. Once all threads have been succesfully created, the processor waits until all threads have completed their task before terminating. */ void readWriteSTM::makingThreads(int algor) { int t; //Hold return value from thread creation to check for errors currentSTM = algor; //Set the testing algorithm stringstream sMsg; //Custom log message timeStart = chrono::high_resolution_clock::now(); //Get processor start time logMsg("creating threads", stmProcessor); pthread_t consoleThread; //Thread for console feedback t = pthread_create(&consoleThread, NULL, consoleFeedback, NULL); //If the thread failed to be created, end the simulation if(t) { logMsg("error: failed to create console thread", stmProcessor); return; } //Spawn threads and link them to their tasks. All threads will execute //a single predetermined algorithm for(int i = 0; i < NUM_THREADS; i++) { sMsg << "spawning thread " << i; logMsg(sMsg.str(), stmProcessor); sMsg.str(string()); t = pthread_create(&threads[i].th, NULL, linkThread, (void*)this); //If the thread failed to be created, end the simulation if(t) { logMsg("error: failed to create thread", stmProcessor); return; } usleep(SLEEP_THREAD); //Sleep a small amount between spawning threads to prevent //race conditions and deadlock } logMsg("done spawning threads", stmProcessor); //Wait here until all threads terminate while(threadsToGo) {} //Print how long it took to complete the simulation cout << endl << "real\t" << stmDuration() << endl; logMsg("simulation complete, exiting", stmProcessor); //Wait until the consoleThread terminates and joins pthread_join(consoleThread, NULL); } /* Function Name: startProcess Function Type: mutator Parameters: int - the current thread (i.e. the threads tid) Returns: n/a About: Executes the thread's main purpose. The thread will be assigned a reader or writer role and be directed to the intitial state inside the state machine. The thread will stay in the state machine until it reaches the accept (terminate) state. The thread will repeat the above steps including the assignment of a (possibly different) reader or writer role until the amount of loops are completed. Reader and Writer roles are psuedo-randomly selected although ratios of readers to writers will remain the same. */ void readWriteSTM::startProcess(int thrTid) { threads[thrTid].tid = thrTid; //Assign a tid to the thread for(int lc = 0; lc < NUM_LOOPS; lc++) { currentStates[thrTid] = STATE_INIT; //Start the thread at the initial state threads[thrTid].lpCnt = lc; //Show which loop iteration the thread is on //Get same ratio of R/W but without exact duplicates by using a pseudo- //random number generator using a seed number plus the time. srand((rwSeed++) + time(NULL)); int num = rand() % rwTotal; //Create a percentage split between R/W threads[thrTid].rw = (num < rwSplit) ? READER : WRITER; if(threads[thrTid].rw) logMsg("new writer thread", threads[thrTid], 1); else logMsg("new reader thread", threads[thrTid], 1); scheduleSTM(thrTid); usleep(SLEEP_THREAD); //Sleep between new R/W roles to prevent race conditions } logMsg("<defunct>", threads[thrTid]); threadsToGo--; //Decrement thread count and terminate the thread pthread_exit(NULL); } /* Function Name: scheduleSTM Function Type: mutator Parameters: int - the current thread (i.e. the threads tid) Returns: n/a About: Select what algorithm the threads will execute. The default algorithm used is the fair algorithm if no algorithm is selected */ void readWriteSTM::scheduleSTM(int thrTid) { switch(currentSTM) { case STM_FAIR: //Use the fair algorithm while (fair(threads[thrTid])) {} break; case STM_WRP: //Use weak reader preference while (wrp(threads[thrTid])) {} break; case STM_SRP: //Use strong reader preference while (srp(threads[thrTid])) {} break; case STM_WWP: //Use weak writer preference while (wwp(threads[thrTid])) {} break; case STM_SWP: //Use strong writer preference while (swp(threads[thrTid])) {} break; case STM_FCFS: //Use first come first serve (No concurrency) preference while (fcfs(threads[thrTid])) {} break; default: //Default will be the fair algorithm while (fair(threads[thrTid])) {} } } /* Function Name: *linkThread Function Type: mutator Parameters: void* - Reference to the current STM object Returns: n/a About: Since pthreads can only be passed static functions as a parameter, this function acts as a middle man by accepting the STM as a parameter and linking the thread to its actual task. This function will also assign a tid to every thread by incrementing an atomic thread counter every time a thread is linked to a process. The STM has to be passed as a void* since pthreads will not accept variables of any other type for their function parameter. */ void *readWriteSTM::linkThread(void *stmArg) { readWriteSTM *stm = (readWriteSTM*) stmArg; //cast back to readWriteSTM stm->startProcess(++lastThreadMade); //Give the thread its tid } /* Function Name: *consoleFeedback Function Type: mutator Parameters: void* - dummy parameter since pthreads need a parameter Returns: n/a About: Prints a dot to the screen for every two seconds of real time during the STM's execution. This is simply a courtesy to the user so they are aware the program is still working properly. */ void *readWriteSTM::consoleFeedback(void *d) { //Keep printing dots until all threads have completed and terminated while(threadsToGo) { sleep(2); //Sleep so dots are not printed too fast //Check to make sure the threads have not completed while sleeping if(!threadsToGo) break; cout << '.'; cout.flush(); } pthread_exit(NULL); //Terminate the console thread once simulation is complete } /* Function Name: lockMutex Function Type: mutator Parameters: pthread_mutex_t - the mutex to lock or block pthread_cond_t - the signaling condition to wait for if blocked atomic<bool> - Represents if the mutex is locked or unlocked Returns: n/a About: Attempts to acquire the given mutex. If acquired the atmoic bool will be switch to false and all future attempts to acquire this mutex will block until it is unlocked. */ void readWriteSTM::lockMutex(pthread_mutex_t &m, pthread_cond_t &c, atomic<bool> &b) { pthread_mutex_lock(&m); //Attempt to acquire mutex while(!b) { //Or wait to be signalled that the mutex is open pthread_cond_wait(&c, &m); } b.store(false); //Let others know that the mutex has already been acquired } /* Function Name: unlockMutex Function Type: mutator Parameters: pthread_mutex_t - the mutex to unlock pthread_cond_t - the condition to signal once unlocked atomic<bool> - Represents if the mutex is locked or unlocked Returns: n/a About: Unlocks the given mutex. Assumes the calling thread is the thread that aquired the mutex in the first place. */ void readWriteSTM::unlockMutex(pthread_mutex_t &m, pthread_cond_t &c, atomic<bool> &b) { b.store(true); pthread_cond_signal(&c); //Let other threads know the mutex is unlocked pthread_mutex_unlock(&m); } /* Function Name: logMsg Function Type: inspector Parameters: string - the message to write the the log thread - the current thread calling the log int - the type of msg to write Returns: n/a About: Writes a new line log message in the destination log file. Log files will be created if one does not exist or overriden if if already exists. Log information includes the time the log message was written, the thread writing to the log, the loop iteration if applicable, and the message itself. Log messages are split into two different types. The default type will display 'LOG'. The other type will display 'MSG' and should be reserved for special situations or actions in the STM i.e. not errors, transitions, thread spawning, termination, etc. */ void readWriteSTM::logMsg(string msg, thread th, int type) { //Lock the file resource so only one thread can write to it at a time lockMutex(lMtx, lCon, lOpen); // BEGIN LOG CRITICAL SECTION string time = getTime() + ", "; //Display the time of this log entry string msgType = (type) ? "MSG, " : "LOG, "; //Display the type of message stringstream tORp, lStr; //Display whether the calling thread is a normal thread or the processor if(th.tid >= 0) { tORp << "thread " << th.tid << ", "; //Display thread's tid lStr << "loop " << th.lpCnt << ", "; //Display thread's loop iteration } else { tORp << "processor, "; } logFile << time << msgType << tORp.str() << lStr.str() << msg << endl; // END LOG CRITICAL SECTION unlockMutex(lMtx, lCon, lOpen); //Unlock and let the next log writer in } /* Function Name: getTime Function Type: facilitator Parameters: n/a Returns: string - the current duration of the STM in microseconds About: Will compute and return the duration since the STM began inserted into a string. The time will always be twelve numbers long, padded with leading zeroes if necessary. Units use to measure duration is microseconds as it fits best since milliseconds is not accurate enough and nanoseonds is too granular of a level, even for an average computer. Fun fact: Since the string is twelve characters long, there is a maximum duration of around 11 days, 13 hours, 46 minutes and 40 seconds before the string will have to add another digit. */ string readWriteSTM::getTime() const { using namespace chrono; //So chrono:: does not have to be typed every time stringstream time; //Get the time this function was called and subtract the time the STM //started to find the current duration auto timeEnd = high_resolution_clock::now(); //Cast duration to microseconds for best accuracy auto ticks = duration_cast<microseconds>(timeEnd-timeStart); time << setfill('0') << setw(12) << ticks.count(); //Add leading zeroes return time.str(); } /* Function Name: stmDuration Function Type: facilitator Parameters: n/a Returns: string - the current duration of the STM in microseconds About: Behaves similarly to the function getTime but instead of return duration in microseconds, the duration is split between hours minutes and seconds. Only seconds will act like a floating- point number. Hours and minutes will only be integers. Seconds acts like a floating point number by adding a decimal point and the left over milliseconds to the string. */ string readWriteSTM::stmDuration() const { using namespace chrono; //So chrono:: does not have to be typed every time stringstream time; //Get the time this function was called and subtract the time the STM //started to find the current duration auto timeEnd = high_resolution_clock::now(); auto ticks = duration_cast<microseconds>(timeEnd-timeStart); //Get the duration in hours, minutes and milliseconds. //Microseconds and nanoseconds are too granular for this display //Likewise, duration in days makes no sense as well hours h = duration_cast<hours>(ticks); minutes m = duration_cast<minutes>(ticks); seconds s = duration_cast<seconds>(ticks); milliseconds ms = duration_cast<milliseconds>(ticks); int shortM = (m.count() - (h.count()*60)); //Do not allow over 60 minutes int shortS = (s.count() - (m.count()*60)); //Do not allow over 60 seconds int shortMs = (ms.count() - (s.count()*1000)); //Do not allow over 1000 ms time << h.count() << "h " << shortM << "m " << setfill('0') << setw(2); //Make sure the are 3 digits in ms since there is 1/1000 ms in a second time << shortS << "." << setfill('0') << setw(3) << shortMs << "s"; return time.str(); } <file_sep>/csc310/project3/readme.txt Author: <NAME> Date: 05/01/2015 Class: CSC 310 Project: 3 Semester: Spring 2015 README Notes: * Due to an underestimate of the time required to implement this project and only the week of actual work-time on my behalf it is regrettable that the error checking part of this project was never implemented. I began to write the code and plan everything out on paper for the error checking but time and an unforeseen error (below) has prevented it from being continued and implemented. * With the previous note said, everything works to the best of my awareness besides the error checking Error found while trying to implement error checking: * raised STORAGE_ERROR : stack overflow (or erroneous memory access) Notes on error: * I know this error was related to the error checking because as soon as I erased the procedure calls to the error checking procedure, this error stopped. I have not debugged the error checking part of the project due to the lack of time, which is also regrettable. <file_sep>/csc136/project4/LinkedList.h /* File: LinkedList.h Author: <NAME> Updated by: <NAME> Course: CSC136 Assignment: Project 4 Description: LinkedList class with listItr class. A nearly infinite template object that is a container for whatever it is needed for. Creates the node object which are linked together. The nodes are the containers. */ #ifndef _LinkedList_ #define _LinkedList_ #include <assert.h> #include <iostream> using namespace std; // Need to prototype template classes if they are to be friends template <typename eltType> class LinkedList; template <typename eltType> class listItr; /* // and also the friend...note <> in header declaration of << template <typename eltType> ostream& operator<<(ostream&,LinkedList<eltType>); */ template <typename eltType> class node {private: node(eltType info, node* link = NULL ) : data(info), next(link) {}; eltType data; node* next; friend class LinkedList<eltType>; friend class listItr<eltType>; }; template <typename eltType> class LinkedList { public: // Construct empty LinkedList LinkedList(); // Construct deep copy of another LinkedList LinkedList(const LinkedList&); // destroy LinkedList ~LinkedList(); // Assign another LinkedList to this LinkedList; deep copy LinkedList& operator=(const LinkedList&); // Is the LinkedList empty? bool empty(); bool find(eltType); // Ordered insert/remove bool orderedInsert(eltType); bool remove(eltType); // Quick example of recursion int countNodesInList(); private: // linked list pointer node<eltType>* head; // Get a copy of a (deep) node node<eltType>* copy(node<eltType> *); // Free nodes of a linked list void destroy(node<eltType> *); // Need this to count nodes in LinkedList int countNodes(node<eltType> *); /* // Linked list to ostream friend ostream& operator<< <>(ostream&, LinkedList<eltType>); */ // Needed to use a list iterator friend class listItr<eltType>; }; template <typename eltType> ostream& operator<<(ostream &os,const LinkedList<eltType> &l); // Set up an iterator; // an object that provides a pointer to a linked list (in this case) template <typename eltType> class listItr { public: // Construct a List Iterator listItr(const LinkedList<eltType> &l); // Set curr to point at the first node of itr void start(); // Is curr null? bool more(); // Go to curr->next void next(); // Get the value out of curr's node eltType &value() const; private: const LinkedList<eltType> &itr; node<eltType> *curr; }; #endif <file_sep>/csc237/README.txt CSC 237 - Data Structures Dr. Spiegel Kutztown University Spring 2014 This course is an examination of the basic data structures used to store and manipulate data in memory. The use of classes to represent abstract data types is discussed. Several data structures are implemented and used. The course will involve the evaluation of the data structures and the algorithms associated with them. <file_sep>/csc136/project3b/makefile DebugFlag=-g CC=/opt/csw/gcc3/bin/g++ p3: poly_tst.o poly.o Array.o term.o $(CC) $(DebugFlag) -o p3 poly_tst.o poly.o Array.o term.o Array.o: Array.h Array.cpp term.h $(CC) $(DebugFlag) -c Array.cpp poly_tst.o: poly_tst.cpp poly.h term.h $(CC) $(DebugFlag) -c poly_tst.cpp poly.o: poly.cpp poly.h Array.h term.h $(CC) $(DebugFlag) -c poly.cpp term.o: term.h term.cpp $(CC) $(DebugFlag) -c term.cpp clean: rm -rf *.o p3 <file_sep>/csc402/inclassprograms/depthFirstSearch.cpp #include <iostream> #include <set> using namespace std; void DFS(int startNode, bool flag); int main() { return 0; } void DFS(int startNode, bool flag) { set<int> s; //store all visited nodes s.insert(startNode); for(int i = 0; i < numVertices; i++) { if(matrix[startNode][i] == 1 && s.find(i) == s.end()) { DFS(i, false); } } } <file_sep>/csc520/finalproj/src/com/library/protocol/field_list/PBorrowedBook.java package com.library.protocol.field_list; import com.library.business_layer.field_list.BorrowedBook; import java.text.SimpleDateFormat; import java.util.Date; /** * PBorrowedBook serves as a protocol to transfer Table information from the server * to the UI. Only serves as a way to view, print and facilitate information. * PROTOCOL LAYER * @see com.library.business_layer.field_list.BorrowedBook */ public class PBorrowedBook { private Date startDate; private Date dueDate; /** * Basic constructor that sets all attributes. * @param start Date start date * @param end Date due date */ public PBorrowedBook(Date start, Date end) { startDate = start; dueDate = end; } /** * @return Date borrowed start date * @see com.library.business_layer.field_list.BorrowedBook#getStartDate() */ public Date getStartDate() { return startDate; } /** * @return Date borrowed due date * @see com.library.business_layer.field_list.BorrowedBook#getDueDate() */ public Date getDueDate() { return dueDate; } /** * Prints the BorrowedBook in a human understandable summary. */ public String toString() { String out = ""; Date start = getStartDate(); Date end = getDueDate(); SimpleDateFormat f = new SimpleDateFormat("(MM-dd-yyyy)"); out += ("Start Date: "); out += f.format(getStartDate()); out += (" Due Date: "); out += f.format(getDueDate()); return out; } } <file_sep>/csc242/PracticeFiles/sessTest.php <?php session_start(); $_SESSION['num'] = 10; echo "sessTest, num = " . $_SESSION['num'] . "<br/>"; print "<a href = 'sessFile1.php'>File-1</a> &nbsp; &nbsp;"; print "<a href = 'sessFile2.php'>File-2</a>"; ?><file_sep>/csc237/project3/Micro/clock.cpp /* clock example: countdown */ #include <stdio.h> #include <time.h> void waitFor ( int seconds ) { clock_t endwait; endwait = clock () + seconds * CLOCKS_PER_SEC ; while (clock() < endwait) {} } int main () { printf("There are %d ticks of the system clock per second\n",CLOCKS_PER_SEC); int n; printf ("Starting countdown...\n"); for (n=10; n>0; n--) { printf ("%d\n",n); waitFor (1); } printf ("FIRE!!!\n"); return 0; } <file_sep>/csc136/project4/poly.cpp /* Filename: poly.cpp Author: <NAME> Course: CSC136 Assignment: Project 4 Description: Creates the polynomial object with the constructor and with the help of member functions the user is allowed to update the poly by using Term functions as well as LinkedList functions. */ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cmath> #include "poly.h" #include "LinkedList.h" #include "term.h" using namespace std; //Constructor Polynomial::Polynomial() { } /* Function: setTermList Member Type: Mutator Description: Makes TermList equal to another LinkedList Parameters: const LinkedList<Term> - input - list to be set equal to Returns: bool */ bool Polynomial::setTermList(const LinkedList<Term> &list) { TermList = list; return true; } /* Function: getTermList Member Type: Inspector Description: Returns the LinkedList private member Parameters: none Returns: TermList - LinkedList object */ const LinkedList<Term> Polynomial::getTermList() const { return TermList; } /* Function: operator () Member Type: Facilitator Description: Evaluate the polynomial for variable x Parameters: x - input - variable that is standing for value of x Returns: The polynomial evaluated for x */ double Polynomial::operator()(double x) const { double answer = 0; LinkedList<Term> newList = getTermList(); listItr<Term> lt(newList); while ( lt.more() ) { Term newTerm = lt.value(); //Multiply the coefficient by x^expn and add to total if(newTerm.getExponent() > 1) answer += (pow(x, newTerm.getExponent())*newTerm.getCoefficient()); //Multiply the coefficient by x and add to total else if(newTerm.getExponent() == 1) answer += (x*newTerm.getCoefficient()); //Add the coefficient to total else if(newTerm.getExponent() == 0) answer += newTerm.getCoefficient(); lt.next(); } return answer; } /* Function: multiply Member Type: Facilitator Description: Multiply each coefficient by the scalar arg factor Parameters: fact - input - variable that is multiplying against all the coefficients Returns: void */ void Polynomial::operator*=(float factor) { LinkedList<Term> newList = getTermList(); listItr<Term> lt(newList); while ( lt.more() ) { Term newTerm = lt.value(); float coeff = newTerm.getCoefficient(); coeff *= factor; newTerm.setCoefficient(coeff); lt.value() = newTerm; lt.next(); } setTermList(newList); } /* Function: add Member Type: Mutator Description: Add a term to the polynomial Parameters: coefficient - input - the coefficient of the term being added exponent - input - the exponent of the term being added Returns: true if the term is added, false otherwise */ bool Polynomial::add(float co, int ex) { Term newTerm; newTerm.setCoefficient(co); newTerm.setExponent(ex); return(add(newTerm)); } /* Function: add Member Type: Inspector Description: Add a term to the polynomial Parameters: T - input - the Term being added Returns: true if the term is added, false otherwise */ bool Polynomial::add(Term &T) { TermList.orderedInsert(T); return true; } /* Function: readFile Member Type: Mutator Description: Loads up the terms from a user declared filename Parameters: file& - input/output - stream variable Returns: void */ void Polynomial::readFile(ifstream &file) { Term T; while(file >> T) add(T); file.close(); } /* Function: removeTerm Member Type: Mutator Description: Checks if term is located within the LinkedList and if so removes the term from the LinkedList. Parameters: int - input - term exponent to be removed Returns: bool - true if term is found & removed - false if term is not found */ bool Polynomial::removeTerm(int expn) { Term newTerm; newTerm.setExponent(expn); if(TermList.remove(newTerm)) return true; else return false; } /* Function: operator >> Description: Reads in a Term from a file Parameters: ifstream file - input/output - the input stream Polynomial - output only - Poly to data input Returns: ifstream */ ifstream &operator >>(ifstream &file, const Polynomial&P) { Term newTerm; file >> newTerm; LinkedList<Term> newList = P.getTermList(); newList.orderedInsert(newTerm); return file; } /* Function: operator << Description: Print a Polynomial to the screen Parameters: out - input/output - output stream P - input - The Polynomial to print Returns: void */ ostream &operator <<(ostream &out, const Polynomial &P) { LinkedList<Term> newList = P.getTermList(); listItr<Term> lt(newList); while ( lt.more() ) { out << lt.value(); lt.next(); if(lt.more()) out << " + "; } return out; } <file_sep>/csc520/finalproj/src/com/library/business_layer/field_list/BorrowedBook.java package com.library.business_layer.field_list; import java.io.Serializable; import java.util.Date; /** * The BorrowedBook class represents a scenario where a book has been borrowed. * BorrowedBook contains the unique number for the borrowed book, the date the * book was borrowed, the date the book should be returned as well as its * unique identifier. Identifiers are meant to act similar to a primary key * in a database and as such should be unique. Also implements Serializable so * it can be serialized for later use. * BUSINESS LAYER CLASS */ public class BorrowedBook implements Serializable { private int id; private String number; private Date startDate; private Date dueDate; /** * Contstructs BorrowedBook Object by setting its attributes to a value. * @param i identifier * @param n number * @param s start date * @param e due date */ public BorrowedBook(int i, String n, Date s, Date e) { setId(i); setNumber(n); setStartDate(s); setDueDate(e); } /** * Gets the int identifier value for this Object. * @return id as int */ public int getId() { return id; } /** * Gets the BorrowedBook number as a String. * @return number String */ public String getNumber() { return number; } /** * Gets the borrow start date as a Date Object. * @return start date Date */ public Date getStartDate() { return startDate; } /** * Gets the borrow due date as a Date Object. * @return due date Date */ public Date getDueDate() { return dueDate; } /** * Sets the value for the Object identifier. * @param i int to set id to */ public void setId(int i) { id = i; } /** * Sets the value for the BorrowedBook number. * @param n String to set number to */ public void setNumber(String n) { number = n; } /** * Sets the value for the borrowedBook start date. * @param s Date to set start date to */ public void setStartDate(Date s) { startDate = s; } /** * Sets the value for the borrowedBook due date. * @param e Date to set due date to */ public void setDueDate(Date e) { dueDate = e; } }<file_sep>/sideprojects/derivatives/derivative1.cpp /* Author: <NAME> ** File: derivatve1.cpp ** Purpose: To find the derivative of polynomials */ #include <iostream> using namespace std; /* Function: menu() ** Returns: void ** Parameters: none ** Purpose: displays the menu for the user */ void menu(); /* Function: select() ** Returns: int ** Parameters: none ** Purpose: user selects the option to commence */ int select(); /* Function: singleTerm() ** Returns: void ** Parameters: none ** Purpose: user enters a single term and exponent */ void singleTerm(); /* Function: foX() "f of x" ** Returns: void ** Parameters: float, int ** Purpose: finds the derivative of the given polynomial */ void foX(float, int); //Polynomial containing a term and exponent struct poly { float term; int exp; }; int main() { menu(); int option = select(); while(!option) { cout << "\nThat is not a valid choice\n"; menu(); option = select(); } while(option != -1) { menu(); option = select(); } return 0; } void menu() { cout << "\nPlease select an option\n"; cout << "1. (Single Term)\n"; cout << "2. (Multiple Term) *N/A\n"; cout << "3. (Product Rule) *N/A\n"; cout << "4. (Quotient Rule) *N/A\n"; cout << "5. (Chain Rule) *N/A\n"; cout << "6. (Trig Terms) *N/A\n"; cout << "<-1 to exit>\n"; } int select() { int choice; cout << "\nPlease enter your choice: "; cin >> choice; switch(choice) { case 1: singleTerm(); return 1; case 2: return 2; case 3: return 3; case 4: return 4; case 5: return 5; case 6: return 6; case -1: return -1; default: return 0; } } void singleTerm() { poly singlePoly; cout << "Please enter the term: "; cin >> singlePoly.term; cout << "Please enter the exponent: "; cin >> singlePoly.exp; foX(singlePoly.term, singlePoly.exp); } void foX(float term, int exp) { if(term == 0) { cout << "f(x) = 0\n"; cout << "f'(x) = 0\n"; } else if(exp == 0) { cout << "f(x) = " << term << endl; cout << "f'(x) = 0\n"; } else if(term == 1) { if(exp == 1) { cout << "f(x) = x\n"; cout << "f'(x) = 1\n"; } else { cout << "f(x) = x^" << exp << endl; if(exp == 2) cout << "f'(x) = " << exp << "x\n"; else cout << "f'(x) = " << exp << "x^" << exp-1 << endl; } } else if(term == -1) { if(exp == 1) { cout << "f(x) = -x\n"; cout << "f'(x) = -1\n"; } else { cout << "f(x) = -x^" << exp << endl; if(exp == 2) cout << "f'(x) = " << term*exp << "x\n"; else cout << "f'(x) = " << term*exp << "x^" << exp-1 << endl; } } else { if(exp == 1) { cout << "f(x) = " << term << "x\n"; cout << "f'(x) = " << term << endl; } else { cout << "f(x) = " << term << "x^" << exp << endl; if(exp == 2) cout << "f'(x) = " << term*exp << "x\n"; else cout << "f'(x) = " << term*exp << "x^" << exp-1 << endl; } } } <file_sep>/csc402/assignment2/CheckingAccount.cpp #include <iostream> #include "BankAccount.h" #include "CheckingAccount.h" using namespace std; CheckingAccount::CheckingAccount() : BankAccount() { setAccountNumber(1234567890); setBalance(0.00); setWithdrawals(0); } CheckingAccount::CheckingAccount(int n, float b) : BankAccount(n, b) { setAccountNumber(n); setBalance(b); setWithdrawals(0); } void CheckingAccount::setWithdrawals(int w) { withdrawals = w; } int CheckingAccount::getWithdrawals() { return withdrawals; } void CheckingAccount::withdraw(double amount) { if((getBalance() - amount) < 0) { if(getBalance() <= 0) setBalance(getBalance()-35); //$35 penalty else { if(getWithdrawals() >= 3) { setBalance(0); //withdraw to zero setBalance(getBalance()-35); //minus $35 overdraft fee setBalance(getBalance()-1); //withdraw fee } else { setBalance(0); //withdraw to zero setBalance(getBalance()-35); //minus $35 overdraft fee } } } else { if(getWithdrawals() >= 3) { setBalance(getBalance()-amount); setBalance(getBalance()-1); // withdraw fee } else setBalance(getBalance()-amount); } setWithdrawals(getWithdrawals()+1); } void CheckingAccount::monthEnd() { setWithdrawals(0); } <file_sep>/csc135/medicalExpert_ChristianCarreras.cpp //This program diagnoses the user #include <iostream> using namespace std; int main() { char answer1, answer2, answer3; cout << "Are you coughing? [y/n]: "; cin >> answer1; if (answer1 == 'y') { cout << "Are you short of breath or weezing? [y/n]: "; cin >> answer2; if (answer2 == 'y') cout << "You possibly have pneumonia or an infection of the airways\n"; else if (answer2 == 'n') cout << "You have a possible viral infection\n"; else cout << "Invalid entry\n"; } else if (answer1 == 'n') { cout << "Do you have a headache? [y/n]: "; cin >> answer3; if (answer3 == 'y') cout << "You have a possiblity of meningitis\n"; else if (answer3 == 'n') cout << "You are healthy\n"; else cout << "Invalid entry\n"; } else cout << "Invalid entry\n"; return 0; } <file_sep>/csc242/Project/userlogin.php <?php session_start(); /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/userlogin.php Course: CSC 242 - Fall 2013 */ //Variables taken from login.html or loginfail.html $user = $_POST['user']; $pass = $_POST['pass']; //Correct username and password if(login($user, $pass)) { //Take user to home page $_SESSION['loggedin'] = true; header("Location: myproject.php"); } //Wrong username or password else if(!login($user, $pass)) { //Take user to loginfailed.html header("Location: loginfailed.html"); } //Checks if the username and password the user entered //matches a username and password in the database function login($user, $pass) { //Create PDO object $dsn = 'mysql:host=localhost;dbname=ccarr419_bookstore'; $username = 'ccarr419'; $password = '<PASSWORD>'; //Open database $db = new PDO($dsn, $username, $password); $query = "SELECT * FROM Customers"; $accounts = $db->query($query); //Check database for username and password foreach($accounts as $account) { if($user == $account['Email'] && $pass == $account['Passwd']) { $_SESSION['name'] = $account['FirstName']; $_SESSION['custID'] = $account['CustomerID']; return true; } } return false; } ?><file_sep>/csc135/simpleArray_ChristianCarreras.cpp //This program uses for-loops to process array elements. //Author: <NAME> #include <iostream> using namespace std; int main() { //Declare array and variables int number[10]; int i, highest, lowest, sum, average, counter; sum = 0; counter = 0; //For-loop that asks user for 10 numbers for(i = 0; i < 10; i++) { cout << "Please enter a number: "; cin >> number[i]; } //For-loop that restates the numbers in the entered order cout << "\nYou entered: "; for(i = 0; i < 10; i++) { cout << number[i] << " "; } //For-loop that states the numbers in reverse order cout << "\nReverse order: "; for(i = 9; i >= 0; i--) { cout << number[i] << " "; } cout << endl; //For-loop that finds the highest number highest = number[0]; for(i = 0; i < 10; i++) { if(number[i] > highest) highest = number[i]; } cout << "The highest grade is " << highest << endl; //For-loop that finds the lowest grade lowest = number[0]; for(i = 0; i < 10; i++) { if(number[i] < lowest) lowest = number[i]; } cout << "The lowest grade is " << lowest << endl; //For-loop that finds the average grade for(i = 0; i < 10; i++) { sum+=number[i]; } average = sum/10; cout << "The average grade is " << average << endl; //For-loop that finds how many numbers were above average for(i = 0; i < 10; i++) { if(number[i] > average) counter++; } cout << "There are " << counter << " grades above average\n"; return 0; } <file_sep>/csc402/assignment4/graphDemo.cpp /* Author: <NAME> File: graphDemo.cpp Class: CSC 402 Date: 10/04/2015 */ #include <iostream> #include "adjacencyMatrixGraph.h" #include "adjacencyListGraph.h" using namespace std; int main() { graph *myGraph1, *myGraph2; myGraph1 = new adjacencyMatrixGraph(5); myGraph2 = new adjacencyListGraph(5); cout << "\nADJACENCY MATRIX GRAPH\n\n"; //insertEdge check cout << "Insert edges into matrix graph: \n"; myGraph1->insertEdge(1, 3); myGraph1->insertEdge(0, 4); myGraph1->insertEdge(0, 2); myGraph1->insertEdge(2, 4); myGraph1->output(cout); cout << endl; //degree check for(int i = 0; i < 5; i++) cout << "Vertex " << i << " has a degree of " << myGraph1->degree(i) << endl; cout << endl; //numberOfVertices and numberOfEdges check cout << "There are now " << myGraph1->numberOfVertices() << " vertices in the graph\n"; cout << "The graph has a total of " << myGraph1->numberOfEdges() << " edges\n\n"; //existsEdge check cout << "Does there exist an edge between 1 and 3?\n"; if(myGraph1->existsEdge(1, 3)) cout << "Yes\n"; cout << "Does there exist an edge between 0 and 4?\n"; if(myGraph1->existsEdge(0, 4)) cout << "Yes\n"; cout << "Does there exist an edge between 2 and 4?\n"; if(myGraph1->existsEdge(2, 4)) cout << "Yes\n"; cout << "Does there exist an edge between 0 and 3?\n"; if(myGraph1->existsEdge(0, 3)) cout << "Yes\n\n"; else cout << "No\n\n"; //eraseEdge check cout << "Remove the edges previously inserted: \n"; myGraph1->eraseEdge(1, 3); myGraph1->eraseEdge(0, 4); myGraph1->eraseEdge(0, 2); myGraph1->eraseEdge(2, 4); myGraph1->output(cout); cout << endl; //degree check for(int i = 0; i < 5; i++) cout << "Vertex " << i << " has a degree of " << myGraph1->degree(i) << endl; cout << endl; //numberOfVertices and numberOfEdges check cout << "There are now " << myGraph1->numberOfVertices() << " vertices in the graph\n"; cout << "The graph has a total of " << myGraph1->numberOfEdges() << " edges\n\n"; cout << "ADJACENCY LIST GRAPH\n\n"; //insertEdge check cout << "Insert edges into matrix graph: \n"; myGraph2->insertEdge(1, 3); myGraph2->insertEdge(0, 4); myGraph2->insertEdge(0, 2); myGraph2->insertEdge(2, 4); myGraph2->output(cout); cout << endl; //degree check for(int i = 0; i < 5; i++) cout << "Vertex " << i << " has a degree of " << myGraph2->degree(i) << endl; cout << endl; //numberOfVertices and numberOfEdges check cout << "There are now " << myGraph2->numberOfVertices() << " vertices in the graph\n"; cout << "The graph has a total of " << myGraph2->numberOfEdges() << " edges\n\n"; //existsEdge check cout << "Does there exist an edge between 1 and 3?\n"; if(myGraph2->existsEdge(1, 3)) cout << "Yes\n"; cout << "Does there exist an edge between 0 and 4?\n"; if(myGraph2->existsEdge(0, 4)) cout << "Yes\n"; cout << "Does there exist an edge between 2 and 4?\n"; if(myGraph2->existsEdge(2, 4)) cout << "Yes\n"; cout << "Does there exist an edge between 0 and 3?\n"; if(myGraph2->existsEdge(0, 3)) cout << "Yes\n\n"; else cout << "No\n\n"; //eraseEdge check cout << "Remove the edges previously inserted: \n"; myGraph2->eraseEdge(1, 3); myGraph2->eraseEdge(0, 4); myGraph2->eraseEdge(0, 2); myGraph2->eraseEdge(2, 4); myGraph2->output(cout); cout << endl; //degree check for(int i = 0; i < 5; i++) cout << "Vertex " << i << " has a degree of " << myGraph2->degree(i) << endl; cout << endl; //numberOfVertices and numberOfEdges check cout << "There are now " << myGraph2->numberOfVertices() << " vertices in the graph\n"; cout << "The graph has a total of " << myGraph2->numberOfEdges() << " edges\n\n"; cout << "TEST COMPLETE\n\n"; return 0; } <file_sep>/programmingteam/crc.cpp #include <iostream> #include <fstream> using namespace std; void getChar(ifstream&); int main() { ifstream inf; string fileName; cin >> fileName; inf.open(fileName.c_str()); getChar(inf); inf.close(); return 0; } void getChar(ifstream &inf) { char ch; while(inf.get(ch)) { } }<file_sep>/csc421/assignment5/src/com/yahtzee/client/playerStats.java package com.yahtzee.client; import java.io.Serializable; /* * Author: <NAME> * File Name: playerStats.java * File Package: com.yahtzee.client * File Version: 1.0 * File Date: 12/04/2017 * Due Date: 12/13/2017 * Assignment: #5 * Professor: Dr. <NAME> * Course #: CSC421 * Course Name: Web-Based Software Design & Development * University: Kutztown University * Major: CSCM Software Development */ /** * Class to hold all incoming and outgoing data from the server. The only * necessary data of use to the other player is their score and which categories * they picked. All other data is negligible when used in network play. All data * is serialized so they can be passed back and forth from the server. */ public class playerStats implements Serializable { private static final long serialVersionUID = 1L; public int scores[]; //The player's score public boolean pCats[]; //The categories the player picked public playerStats() {} }<file_sep>/csc135/passFail_ChristianCarreras.cpp //This program tells you if you passed or failed your course. #include <iostream> using namespace std; int main() { int grade; //Ask user grade/user inputs grade. cout << "Please input your grade: "; cin >> grade; //if/else statements. if (grade >= 60) cout << "You passed the course.\n"; else cout << "You failed.\n"; return 0; } <file_sep>/csc237/project3/WordData.cpp /** // Author: <NAME> // Updated By: Dr. Spiegel and <NAME> // Course: CSC 237 // Filename: WordData.cpp // Purpose: Implementations of member functions for // designed to contain a word and its // multiplicity in data */ #include <iostream> #include <iomanip> #include <sstream> #include <string> #include "WordData.h" using namespace std; /** //Constructor */ WordData::WordData(string wrd, int cnt) { setWordData(wrd, cnt); } /** //Sets the given string as the word */ void WordData::setWord(string wrd) { word = wrd; } /** //Sets the given int as the count */ void WordData::setCount(int cnt) { count = cnt; } /** //Sets the WordData object with the given string and int */ void WordData::setWordData(string wrd, int cnt) { setWord(wrd); setCount(cnt); } /** //Returns WordData's word */ string WordData::getWord() const { return(word); } /** //Returns WordData's count */ int WordData::getCount() const { return(count); } /** //Increments WordData's count by one */ void WordData::incCount(int inc) { count+=inc; } /** //Checks if the WordData object is less than another */ bool WordData::operator<(const WordData &w) const { string baseWord = getWord(); string checkWord = w.getWord(); if(baseWord.compare(checkWord) < 0) return true; //First word is less than the other else return false; } /** //Checks if the WordData object is greater than another */ bool WordData::operator>(const WordData &w) const { string baseWord = getWord(); string checkWord = w.getWord(); if(baseWord.compare(checkWord) > 0) return true; //First word is greater than the other else return false; } /** //Checks if the WordData object is equal to another */ bool WordData::operator==(const WordData &w) const { string baseWord = getWord(); string checkWord = w.getWord(); if(baseWord == checkWord) return true; //Words are equal else return false; } /** //Prints the WordData object to the screen */ ostream &operator<<(ostream& output, const WordData &words) { output<<words.getWord()<<"\t\t"<<words.getCount(); return output; } <file_sep>/csc136/README.txt CSC 136 - Computer Science II Dr. <NAME> Kutztown University Fall 2013 This course extends the topics developed in CSC 135. Also covered are concepts of data abstraction and encapsulation as part of the object-oriented paradigm, pointers, recursion, and beginning data structures such as stacks and queues. <file_sep>/csc320/README.txt CSC 320 - Game Development for Computer Scientists I Mr. <NAME> Kutztown University Fall 2016 This course introduces the student to the concepts, process, and algorithms of game design. Topics in this course include an introduction to game design process, game design problems, game algorithms, algorithm implementation and application, data and data structures in game design, and artificial intelligence in game design. The student will create at least two original games using the techniques presented in the course. <file_sep>/csc552/project1/p1.cpp /* Author: <NAME> * File: p1.cpp * Date Made: 02/13/2017 * Due Date: 02/17/2017 * School: Kutztown University * Class Num: CSC 552 * Class Name: Advanced Unix Programming * Semester: SPRING 2017 * Professor: Dr. Spiegel * Purpose: Project 1 simulates a shell by taking command-line arguments * containing the names of two programs to execute and a file to * read. The first program will count the total number of words * contained within that file and return that value. The second * program will print the first n words in the file where n is * value returned by the first program. */ /* * Function Name: beginProcess * Function Type: facilitator * Arguments: char** - input only * Return Value: int - the number of words printed * Purpose: Begins the process of forking and executing the programs * supplied by the command-line. */ int beginProcess(char**); /* * Function Name: makeExec * Function Type: facilitator * Arguments: const char* - input only * Return Value: const char* - the new executable * Purpose: Adds the necessary './' to the given file name to ensure * it executes in a exec command. */ const char* makeExec(const char*); /* * Function Name: toCString * Function Type: facilitator * Arguments: int - input only * Return Value: const char* - new argument suitable for an exec command. * Purpose: Converts an integer to a const char* value for exec use. */ const char* toCString(int); /* * Function Name: waitOnProcess * Function Type: inspector * Arguments: int - input/output * Return Value: int - the number returned by the processing being waited on * Purpose: Makes the parent process wait until its child process has * terminated. Once its child process havs terminated, get the * return value of the child and return it. */ int waitOnProcess(int&); #include <iostream> #include <sstream> #include <sys/wait.h> using namespace std; int main(int argc, char* argv[]) { cout << "Words Printed: " << beginProcess(argv) << endl; return 0; } int beginProcess(char** argv) { int status, wordCount = 0; const char* exec1 = argv[1]; //program#1 const char* exec2 = argv[3]; //program#2 const char* file = argv[2]; //file to count words //Fork a process to count the total words in a file if(fork() == 0) //If child execvp(makeExec(exec1), argv+1); else //If parent { wordCount = waitOnProcess(status); //Fork another process to print n words in a file if(fork() == 0) //If child { /* This next line of code is very perculiar and I have no understanding as to why it is so important. Without it the next program fails to get the correct arguments and will return 0; With it it will function correctly and give appropriate output. I feel as though I am overlooking something dealing with the nature of const char* variables but it is still very odd. It seems that the last argument before NULL in execlp will be "./" if not for the next line of code. I will leave it for now until I can find out why these lines of code react in such a way...*/ cout << makeExec(exec2) << toCString(wordCount) << endl; execlp(makeExec(exec2), exec2, file, toCString(wordCount), NULL); } else //If parent wordCount = waitOnProcess(status); } return wordCount; } //Take the program name and add "./" to make it usable in exec functions. const char* makeExec(const char* exe) { string suf = "./"; string temp = suf + exe; return temp.c_str(); } //Convert an int to a cString to make it usable in exec functions. const char* toCString(int num) { stringstream str; str << num; string temp = str.str(); return temp.c_str(); } //Have a partent process wait until its child has terminated then return //the child's return value. int waitOnProcess(int &status) { wait(&status); return WEXITSTATUS(status); } <file_sep>/csc552/project2/README.txt # Author: <NAME> # File: README.txt # Date: 03/07/2017 # Due Date: 03/11/2017 # Project: #2 # Course Num: CSC552 # Course Title: Advanced Unix Programming # Professor: Dr. Spiegel # School: Kutztown University of Pennsylvania # Semester: SPRING2017 Doxygen Link: http://acad.kutztown.edu/~ccarr419/csc552/project2/html/index.html Design Decisions & Bugs: * In the client, the file descriptor used for the read end of the pipe used has to have it's number increased by one to work. I believe this has to with a bug with my toCString function in p2 since it actually copies the write file descriptor. * In the client, I had to hard code the size for write in the case of "TOTAL" and "EXIT" because my sizeof functions were causing the writes to not work * In the server, any two numbers that are both five digits or more or add up to 10 or more digits gets the wrong answers. I have no clue how this happens because once 1,000,000,000 is hit the numbers get mad. I would like to assume this has to do with the size of float or the size of the message buffer. * In the server, I could not get fread to work when fwrite was used. fputs was used in its place and then fread worked fine. * In the server, if the second number is entered has decimal places, it will almost always be rounded down. Again I this might have to do with the nature of floats but I am not sure. * In the server, substr had to be used to match the entered command to "total" or "exit". This was because there was some garbage hanging around at the end of the entered command that made it not equal to those strings. This one I have no clue about, maybe something with cstrings and pipes? * In the server, the sum will be off by a small amount if decimals are used. Again I believe this has to deal with floats but maybe an error with fputs because the numbers in the file are matching the output from fread. * In the server and client, I had to skip a loop implementation because of time restraints. The user enters one command to the client/server, it fires, and it is done. <file_sep>/csc402/assignment2/AccountDemo.cpp /** This program simulates a bank with checking and savings accounts. */ #include <iostream> #include "BankAccount.h" #include "CheckingAccount.h" #include "SavingsAccount.h" using namespace std; int main() { // Array of BankAccount pointer BankAccount* accountList[2]; accountList[0] = new CheckingAccount(1,1000); accountList[0]->withdraw(100); accountList[0]->withdraw(100); accountList[0]->withdraw(100); accountList[0]->withdraw(100); accountList[0]->monthEnd(); accountList[0]->withdraw(100); accountList[0]->deposit(1000); accountList[0]->printAccount(cout); accountList[1] = new SavingsAccount(2,1000, 5); accountList[1]->withdraw(100); accountList[1]->monthEnd(); accountList[1]->withdraw(100); accountList[1]->printAccount(cout); /* // test your program using the code below. // when you turn in your programming assignment, please comment the code below. // The grading program can not interact with your code, sorry:() // Create accounts SavingsAccount savings = SavingsAccount(); savings.setAccountNumber(1); savings.setInterestRate(5); CheckingAccount checking = CheckingAccount(); checking.setAccountNumber(2); bool done = false; while (!done) { int accountNumber; cout << "Please enter your account number: " ; cin >> accountNumber; cout << "D)eposit W)ithdraw M)onth end Q)uit: " << endl; string input; cin >> input; if (accountNumber == 1 && (input=="D" || input=="W")) // Deposit or withdrawal { cout << "Enter amount: " ; double amount; cin >> amount; if (input=="D") { savings.deposit(amount); } else { savings.withdraw(amount); } savings.printAccount(cout); } else if ( accountNumber == 1 && input=="M") // Month end processing { savings.monthEnd(); savings.printAccount(cout); } else if (accountNumber == 2 && (input=="D" || input=="W")) // Deposit or withdrawal { cout << "Enter amount: " ; double amount; cin >> amount; if (input=="D") { checking.deposit(amount); } else { checking.withdraw(amount); } checking.printAccount(cout); } else if ( accountNumber == 2 && input=="M") // Month end processing { checking.monthEnd(); checking.printAccount(cout); } else if (input == "Q") { done = true; } } */ return 0; } <file_sep>/csc237/project2/WordDataList.h /* // Author: <NAME> // Documented By: <NAME> // Course: CSC 237 // Filename: WordDataList.h // Purpose: */ #ifndef WORDDATALIST_H #define WORDDATALIST_H #include <string> #include "WordList.h" #include "WordData.h" using namespace std; class WordDataList : public WordList { public: /* // Function Name: Constructor // Member Type: Constructor // Parameters: none // Returns: N/A // Purpose: Constructs the WordDataList object */ WordDataList(); /* // Function Name: parseIntoList // Member Type: Mutator // Parameters: ifstream& - import/export // Returns: void // Purpose: Parses file into WordDataList's data member */ void parseIntoList(ifstream &inf); /* // Function Name: printIteratively // Member Type: Facilitator // Parameters: none // Returns: void // Purpose: Prints the object array iteratively with // a for loop */ void printIteratively(); /* // Function Name: printRecursively // Member Type: Facilitator // Parameters: none // Returns: void // Purpose: Prints the object array with recursive calls // uses the printRecursivelyWorker function */ void printRecursively(); /* // Function Name: printPtrRecursively // Member Type: Facilitator // Parameters: none // Returns: void // Purpose: Prints the object array with recursive calls // and pointers */ void printPtrRecursively(); private: WordData TheWords[10]; int numWords; /* // Function Name: incMatch // Member Type: Mutator // Parameters: string - import only // Returns: true if match found // false if not // Purpose: Find if there is already an occurrence // of the word in the object array */ bool incMatch(string temp); /* // Function Name: printRecursivelyWorker // Member Type: Facilitator // Parameters: int - import only // Returns: void // Purpose: Used by the printRecursively function // to do the recursive calls */ void printRecursivelyWorker(int numWords); /* // Function Name: printPtrRecursivelyWorker // Member Type: Facilitator // Parameters: int - import only // Returns: void // Purpose: Used by the pritnPtrRecursively function // to do the recursive calls */ void printPtrRecursivelyWorker(int numWords); }; #endif <file_sep>/csc242/PracticeFiles/testmysql.php <?php $empID = 92; $name = 'Smitty'; $sal = 52000; $dept = 13; echo "<p>Employee ID: $empID </p>"; echo "<p>Employee Name: $name </p>"; echo "<p>Employee Salary: $sal </p>"; echo "<p>Employee Dept#: $dept </p>"; /*$DB_NAME = "ccarr419_bookstore"; $DB_HOST = "localhost"; $DB_USER = "ccarr419"; $DB_PASS = "<PASSWORD>"; global $connection; $connection = mysql_connect($DB_HOST, $DB_USER, $DB_PASS) or die("Cannot connect to $DB_HOST as $DB_USER: " . mysql_error()); mysql_select_db($DB_NAME) or die ("Cannot open $DB_NAME:" . mysql_error()); */ $dsn = 'mysql:host=localhost;dbname=ccarr419_bookstore'; $username = 'ccarr419'; $password = '<PASSWORD>'; $db = new PDO($dsn, $username, $password); $query = "INSERT INTO emp (id, name, sal, dno) VALUES ('$empID', '$name', '$sal', '$dept')"; $insert_count = $db->exec($query); ?><file_sep>/csc342/Site/ManagePhotoAlbum.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PlanetWroxModel; public partial class _ManagePhotoAlbum : BasePage { protected void Page_Load(object sender, EventArgs e) { } protected void EntityDataSource1_Inserting(object sender, EntityDataSourceChangingEventArgs e) { int photoAlbumId = Convert.ToInt32(Request.QueryString.Get("PhotoAlbumId")); Picture myPicture = (Picture)e.Entity; myPicture.PhotoAlbumId = photoAlbumId; } }<file_sep>/csc520/finalproj/src/com/library/business_layer/field_list/CreditCard.java package com.library.business_layer.field_list; import java.io.Serializable; import java.util.Date; /** * The CreditCard class represents a real-life credit or debit card. * A CreditCard Object contains the card type, number, exiration date and a * unique identifier. Identifiers are meant to act similar to a primary key * in a database and as such should be unique. Also implements Serializable * so it can be serialized for later use. * BUSINESS LAYER CLASS */ public class CreditCard implements Serializable { private int id; private String type; private String number; private Date expiration; /** * Contstructs CreditCard Object by setting its attributes to a value. * @param i identifier * @param t type * @param n number * @param e expiration date */ public CreditCard(int i, String t, String n, Date e) { setId(i); setType(t); setNumber(n); setExpiration(e); } /** * Gets the int identifier value for this Object. * @return id as int */ public int getId() { return id; } /** * Gets the type of CreditCard as a String. * @return type String */ public String getType() { return type; } /** * Gets the number on the CreditCard as a String. * @return number String */ public String getNumber() { return number; } /** * Gets the exipriation date on the CreditCard as a Date Object. * @return expiration Date */ public Date getExpiration() { return expiration; } /** * Sets the value for the Object identifier. * @param i int to set id to */ public void setId(int i) { id = i; } /** * Sets the value for CreditCard type. * @param t String to set type to */ public void setType(String t) { type = t; } /** * Sets the value for CreditCard number. * @param n String to set number to */ public void setNumber(String n) { number = n; } /** * Sets the value for CreditCard exipiration date. * @param e Date to set expiration date to */ public void setExpiration(Date e) { expiration = e; } }<file_sep>/csc402/inclassprograms/handinprograms/bankAccount.cpp #include <iostream> #include <iomanip> using namespace std; // Parent class bankAccount class bankAccount { public: bankAccount(float m); void setMoney(float m); float getMoney() const; void deposit(float m); void withdraw(float m); void printMoney(); private: float money; }; // bankAccount member functions bankAccount::bankAccount(float m) { setMoney(m); } void bankAccount::setMoney(float m) { money = m; } float bankAccount::getMoney() const { return money; } void bankAccount::deposit(float m) { money += m; } void bankAccount::withdraw(float m) { money -= m; } void bankAccount::printMoney() { cout << "$" << setprecision(2) << getMoney(); } // Child class savingsAccount class savingsAccount : public bankAccount { public: savingsAccount(float); float getInterest(); void addInterest(); private: float interest; void setInterest(float i); }; // savingsAccount member functions savingsAccount::savingsAccount(float m) : bankAccount(m) { setMoney(m); setInterest(0.01); } void savingsAccount::setInterest(float i) { interest = i; } float savingsAccount::getInterest() { return interest; } void savingsAccount::addInterest() { float total_interest = getMoney() * getInterest(); setMoney(getMoney() + total_interest); } // Child class checkingAccount class checkingAccount : public bankAccount { public: checkingAccount(float m); int getWithdrawals() const; void incWithdrawals(); void resetWithdrawals(); private: int withdrawals; }; // checkingAccount member functions checkingAccount::checkingAccount(float m) : bankAccount(m) { setMoney(m); resetWithdrawals(); } int checkingAccount::getWithdrawals() const { return withdrawals; } void checkingAccount::incWithdrawals() { withdrawals++; } void checkingAccount::resetWithdrawals() { withdrawals = 0; } void menu(); int main() { char choice; while(toupper(choice) != 'Q') { menu(); cout << "Enter your choice: "; cin >> choice; switch(toupper(choice)); { } } return 0; } void menu() { cout << "Choose one of the following:\n"; cout << "D)eposit\n"; cout << "W)ithdraw\n"; cout << "M)onth End\n"; cout << "Q)uit\n"; } <file_sep>/csc570/benchmark_tf.py from __future__ import print_function import matplotlib.pyplot as plt import tensorflow as tf import time import os # -*- coding: utf-8 -*- """ Created on Sun May 6 20:13:25 2018 @author: Chris """ # https://medium.com/@erikhallstrm/hello-world-tensorflow-649b15aed18c """ END OF ORIGINAL DOCUMENTATION """ # Basic TensorFlow benchmark comparing gpu times to cpu times. # Operations used were matrix operations to simulate learning algorithms. # Slight modifications by <NAME>, Kutztown University def get_times(maximum_time): os.environ['TF_CPP_MIN_VLOG_LEVEL'] = '3' os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' tf.logging.set_verbosity(tf.logging.INFO) device_times = { "/gpu:0":[], "/cpu:0":[] } matrix_sizes = range(500,50000,50) for size in matrix_sizes: for device_name in device_times.keys(): print("####### Calculating on the " + device_name + " #######") shape = (size,size) data_type = tf.float16 with tf.device(device_name): r1 = tf.random_uniform(shape=shape, minval=0, maxval=1, dtype=data_type) r2 = tf.random_uniform(shape=shape, minval=0, maxval=1, dtype=data_type) dot_operation = tf.matmul(r2, r1) with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as session: start_time = time.time() result = session.run(dot_operation) time_taken = time.time() - start_time print(result) device_times[device_name].append(time_taken) print(device_times) if time_taken > maximum_time: return device_times, matrix_sizes device_times, matrix_sizes = get_times(1.5) gpu_times = device_times["/gpu:0"] cpu_times = device_times["/cpu:0"] print("TOTAL GPU TIME") total_gpu_time = 0 for time in gpu_times: total_gpu_time += time print(str(round(total_gpu_time, 4)) + ' s') print("TOTAL CPU TIME") total_cpu_time = 0 for time in cpu_times: total_cpu_time += time print(str(round(total_cpu_time, 4)) + ' s') # matplotlib visualization """ plt.plot(matrix_sizes[:len(gpu_times)], gpu_times, 'o-') plt.plot(matrix_sizes[:len(cpu_times)], cpu_times, 'o-') plt.ylabel('Time') plt.xlabel('Matrix size') plt.show() """ <file_sep>/csc237/project3/DLinkedList.h /** // Author: <NAME> // (with thanks to Dr. Spiegel for // the original single linked list) // Course: CSC 237 // Filename: DLinkedList.h // Purpose: The double linked list class uses nodes // with a forward and backward pointer to // make a list easy to iterate through. // Also included is the DLinkedList Iterator. // The iterator is named DListItr and is used // to access data within the list. */ #ifndef DLINKEDLIST_H #define DLINKEDLIST_H #include "Node.h" template <typename eltType> class DLinkedList { public: /** // Function Name: Constructor // Member Type: Constructor // Parameters: none // Returns: N/A // Purpose: Constructs a double linked list */ DLinkedList(); /** // Function Name: Copy Constructor // Member Type: Copy Constructor // Parameters: const DLinkedList& - import only // Returns: N/A // Purpose: Creates a copy of a DLinkedList */ DLinkedList(const DLinkedList&); /** // Function Name: Destructor // Member Type: Destructor // Parameters: none // Returns: N/A // Purpose: Deletes an instantiation of a DLinkedList */ ~DLinkedList(); /** // Function Name: = operator // Member Type: Mutator // Parameters: const DLinkedList& - import only // Returns: DLinkedList& - the object itself // Purpose: Sets a DLinkedList equal to another */ DLinkedList& operator=(const DLinkedList&); /** // Function Name: insert // Member Type: Mutator // Parameters: eltType - import only // Returns: true if inserted, false if not // Purpose: Inserts data into the list in order */ bool insert(eltType); /** // Function Name: remove // Member Type: Mutator // Parameters: eltType - import only // Returns: true if removed, false if not // Purpose: Removes data from the list and // adjusts list appropriately */ bool remove(eltType); private: node<eltType>* head; /** // Function Name: copy // Member Type: Mutator // Parameters: node<eltType>* - import only // Returns: node<eltType>* - first node of copied list // Purpose: copies existing list into new list */ node<eltType>* copy(node<eltType>*); /** // Function Name: destroy // Member Type: Mutator // Parameters: node<eltType>* - import only // Returns: void // Purpose: Destroys a DLinkedList object */ void destroy(node<eltType>*); //Let the DListItr be a friend class template <class T> friend class DListItr; }; template <typename eltType> class DListItr { public: /** // Function Name: Constructor // Member Type: Constructor // Parameters: const DLinkedList<eltType>& - import only // Returns: N/A // Purpose: Constructs an iterator for the given list */ DListItr(const DLinkedList<eltType> &l); /** // Function Name: begin // Member Type: Mutator // Parameters: none // Returns: eltType - the data at the first node // Purpose: Puts the iterator at the first node // and returns the value at that node */ eltType begin(); /** // Function Name: isEmpty // Member Type: Facilitator // Parameters: none // Returns: true if the list is empty // false if not // Purpose: Checks if head == NULL (empty) */ bool isEmpty(); /** // Function Name: isFirstNode // Member Type: Facilitator // Parameters: none // Returns: true if first node // false if not // Purpose: Checks node if it is the first in the list // by checking if prev is NULL */ bool isFirstNode(); /** // Function Name: isLastNode // Member Type: Facilitator // Parameters: none // Returns: true if last node // false if not // Purpose: Checks node if it is the last node in the list // by checking if next is NULL */ bool isLastNode(); /** // Function Name: isNull // Member Type: Facilitator // Parameters: none // Returns: true if current node is NULL // false if not // Purpose: checks if iterator is out of the list */ bool isNull(); /** // Function Name: * operator // Member Type: Inspector // Parameters: none // Returns: eltType - current node's data // Purpose: returns the current node's data the // iterator is pointing at */ eltType operator*() const; /** // Function Name: ++ operator (pre-increment) // Member Type: Mutator // Parameters: none // Returns: DListItr<eltType>& - the iterator itself // Purpose: Moves the iterator to the next node // and returns the iterator to that node */ DListItr<eltType>& operator++(); /** // Function Name: -- operator (pre-decrement) // Member Type: Mutator // Parameters: none // Returns: DListItr<eltType>& - the iterator itself // Purpose: Moves the iterator to the previous node // and returns the iterator to that node */ DListItr<eltType>& operator--(); private: const DLinkedList<eltType> &itr; node<eltType> *curr; //Let the DLinkedList be a friend class template <class T> friend class DLinkedList; }; #endif <file_sep>/csc237/project2/WordDataDLinkList.h /* // Author: <NAME> // Course: CSC 237 // Filename: WordDataDLinkList.h // Purpose: The WordDataDLinkList.h has a single data member DLinkedList. This class parses a file into the list, and prints the list iteratively and recursively */ #ifndef WORDDATADLINKLIST_H #define WORDDATADLINKLIST_H #include "WordList.h" #include "WordData.h" #include "Node.h" #include "DLinkedList.h" using namespace std; class WordDataDLinkList : public WordList { public: /* // Function Name: Constructor // Member Type: Constructor // Parameters: none // Returns: N/A // Purpose: Constructs the WordDataDLinkList object */ WordDataDLinkList(); /* // Function Name: parseIntoList // Member Type: Mutator // Parameters: ifstream & - import/export // Returns: void // Purpose: Inserts data from file into DLinkedList */ void parseIntoList(ifstream &); /* // Function Name: printIteratively // Member Type: Facilitator // Parameters: none // Returns: void // Purpose: Prints list with an iterator // uses polymorphism to use correct function */ void printIteratively(); /* // Function Name: printRecursively // Member Type: Facilitator // Parameters: none // Returns: void // Purpose: Prints list with recursive function calls // uses polymorphism */ void printRecursively(); private: DLinkedList<WordData> DList; /* // Function Name: printRecursivelyWorker // Member Type: Facilitator // Parameters: DListItr<WordData> - import only // Returns: void // Purpose: Uses recursive calls to print list // Used by the printRecursively function */ void printRecursivelyWorker(DListItr<WordData>); /* // Function Name: incMatch // Member Type: Mutator // Parameters: string - import only // Returns: true if match found // false if not // Purpose: Tries to find a match in the list // and increments the count of the word // if a match is found */ bool incMatch(string temp); }; #endif <file_sep>/csc402/assignment2/SavingsAccount.h /** A savings account earns interest on the minimum balance. minBalance = 100; */ #ifndef SAVINGSACCOUNT_H #define SAVINGSACCOUNT_H #include <iostream> #include "BankAccount.h" using namespace std; class SavingsAccount : public BankAccount { private: double interestRate; double minBalance; /** Constructs a savings account with a zero balance and 100 minBalance. */ public: SavingsAccount(); SavingsAccount(int accNum, float thebalance, float theRate); /** Sets the interest rate for this account. @param rate the monthly interest rate in percent */ void setInterestRate(double rate); void withdraw(double amount); void monthEnd(); double getInterestRate(); }; #endif <file_sep>/csc237/project3/Node.h /** // Author: Dr. Spiegel // Updated By: <NAME> // Course: CSC 237 // File: Node.h // Purpose: Doubly-linked list node definition/implementation */ #ifndef NODE_H #define NODE_H #include <cstddef> // Need to prototype template classes if they are to be friends template <class eltType> class node { private: node(eltType info, node* back=NULL, node* link = NULL ) : data(info), prev(back), next(link) {}; eltType data; node *prev, *next; //Let The DLinkedList and DListItr be friend classes template <class T> friend class DLinkedList; template <class T> friend class DListItr; }; #endif <file_sep>/csc402/assignment2/makefile debugFlag=-g AccountDemo: AccountDemo.o BankAccount.o CheckingAccount.o SavingsAccount.o g++ -o AccountDemo AccountDemo.o BankAccount.o CheckingAccount.o SavingsAccount.o $(debugFlag) BankAccount.o: BankAccount.cpp BankAccount.h g++ -c BankAccount.cpp $(debugFlag) CheckingAccount.o: CheckingAccount.cpp CheckingAccount.h BankAccount.h g++ -c CheckingAccount.cpp $(debugFlag) SavingsAccount.o: SavingsAccount.cpp SavingsAccount.h BankAccount.h g++ -c SavingsAccount.cpp $(debugFlag) AccountDemo.o: AccountDemo.cpp BankAccount.h CheckingAccount.h SavingsAccount.h g++ -c AccountDemo.cpp $(debugFlag) clean: \rm -f *.o accountDemo <file_sep>/programmingteam/hyphenRules.cpp #include <iostream> #include <fstream> #include <string> using namespace std; string hypen(string str); void hypenHelper(string &str); void getChar(ifstream &inf); bool checkVowel(char); //bool checkRule3(string); int main(int argc, char *argv[]) { ifstream inf; string fileName; if(argc > 1) { string fileName = argv[1]; inf.open(fileName.c_str()); getChar(inf); } else { cout << "Enter file name: "; cin >> fileName; inf.open(fileName.c_str()); getChar(inf); } return 0; } string hypen(string str) { string tempStr; int pos = 0; int ptr = 0; while(ptr != str.length()) { if(checkVowel(str[ptr])) { if((str[ptr] == 'u' && ptr > 0) && str[ptr-1] == 'q') { ptr++; } else { } } else { ptr++; } } } void hypenHelper(string &str) { } void getChar(ifstream &inf) { char ch; string tempString = ""; while(inf.get(ch)) { if(ch == ' ' || ch == '\n') { tempString = hypen(tempString); cout << tempString << endl; tempString = ""; } else { tempString += ch; } } } bool checkVowel(char ch) { const char vowels[12] = {'a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y'}; for(int i = 0; i < 12; i++) { if(ch == vowels[i]) return true; } return false; } /* bool checkRule3(string str) { const string seq[10] = {"qu", "tr", "br", "str", "st", "sl", "bl", "cr", "ph", "ch"}; for(int i = 0; i < 10; i++) { if(str == seq[i]) return true; } return false; }*/ <file_sep>/sideprojects/fractions/test.cpp #include <iostream> #include <iomanip> #include "fraction.h" using namespace std; int main() { fraction f1(5, 6); fraction f2(7, 9); cout << f1 << endl << f2 << endl; f1+=f2; cout << f1 << endl; // 29/18 f1.printImproper(); // 1u11/18 cout << endl; f2-=f1; // 14/18 - 29/18 cout << f2 << endl; // -15/18 = -5/6 return 0; } <file_sep>/csc548/ProjectFinal/csc548Final_christianCarreras.py import math import operator from mnist import MNIST # https://pypi.python.org/pypi/python-mnist/ from random import shuffle # Find the euclidean distance between the training and testing instances def euclideanDistance(instance1, instance2, length): distance = 0 for x in range(length): distance += pow((instance1[x] - instance2[x]), 2) return math.sqrt(distance) # Find the closest neighbors to the test instance by finding the euclidean # distance of each training instance compared to the current test instance. # Then keep only k of the closest neighbors def getNeighbors(trainingSet, testInstance, k): distances = [] length = len(testInstance)-1 for x in range(len(trainingSet[0])): dist = euclideanDistance(testInstance, trainingSet[0][x], length) distances.append((trainingSet[1][x], dist)) # Print a dot every so often to show progress if x % 10000 == 0: print('. ', end='') print('') distances.sort(key=operator.itemgetter(1)) neighbors = [] for x in range(k): neighbors.append(distances[x][0]) return neighbors # Find the neighbor that appears the most in the group and respond with that def getResponse(neighbors): classVotes = {} for x in range(len(neighbors)): response = neighbors[x] if response in classVotes: classVotes[response] += 1 else: classVotes[response] = 1 sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse=True) return sortedVotes[0][0] # Return the accuracy of the algorithm by the amount of predictions so far def getAccuracy(testSet, predictions): correct = 0 for x in range(len(predictions)): if testSet[x] == predictions[x]: correct += 1 return (correct/float(len(predictions))) * 100.0 def main(): # Prepare data # Dataset location: http://yann.lecun.com/exdb/mnist/ mndata = MNIST('./samples/') trainingSet = mndata.load_training() testSet = mndata.load_testing() # Randomize test set testPictures = list(testSet[0]) testLabels = list(testSet[1]) combined = list(zip(testPictures, testLabels)) shuffle(combined) testPictures[:], testLabels[:] = zip(*combined) # Generate predictions predictions=[] k = 3 for x in range(len(testSet[0])): print(mndata.display(testPictures[x])) print('\nTest #' + repr(len(predictions)+1)) print('Processing ', end='') neighbors = getNeighbors(trainingSet, testPictures[x], k) result = getResponse(neighbors) predictions.append(result) # Print results print('Prediction: ' + repr(result)) print('Actual: ' + repr(testLabels[x])) accuracy = getAccuracy(testLabels, predictions) print('Accuracy: ' + repr(accuracy) + '%') print("Testing Complete") main() <file_sep>/programmingteam/sarumansTower.cpp /* * Author: <NAME> * File: sarumansTower.cpp * Date: 10/23/2015 * About: Calculates the number of levels of Saruman's Tower by the given * day. For each day up to the given day that has a multiple of 3 * for the total of 1's in its binary equivalent, the tower will * raise by one level. Assuming the tower level starts at zero. * http://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&category=579&page=show_problem&problem=4241 */ #include <iostream> #include <cmath> #include <queue> using namespace std; int findLevels(int); void toBinary(queue<int>&, int, int); int count(queue<int>&); int main() { int day[3] = {2, 19, 64}; int lvl[3]; for(int i = 0; i < 3; i++) lvl[i] = findLevels(day[i]); for(int i = 0; i < 3; i++) cout << "Day " << day[i] << ": Level = " << lvl[i] << endl; return 0; } //Counts the number of levels the tower will be at the given day int findLevels(int end_day) { if(end_day < 7) //any day less than 3 will be zero return 0; queue<int> binary; //holds all 1's of a binary equivalent int day = 7, num = 0, lvl = 0; while(day <= end_day) //go from day 3 to given day { toBinary(binary, day, day-1); //get number of 1's num = count(binary); //count number of 1's if(num != 0 && num % 3 == 0) lvl++; //if the count is a multiple of 3, increment lvl day++; //go to next day } return lvl; } //Recursively finds the number of 1's in thebinary equivalent of the given number void toBinary(queue<int>& binary, int num, int k) { if(num == 0 || k < 0) //base case return; if(pow(2, k) <= num) //if 2^k is less than num { binary.push(1); //there will be a one in the binary equivalent toBinary(binary, num - pow(2, k), k-1); } else //keep searching for a power of 2 less than num toBinary(binary, num, k-1); } //Counts the total number of 1's in the queue int count(queue<int>& binary) { int binary_count = 0; while(!(binary.empty()))//go through each entry in the queue { if(binary.front() == 1) //if there is a one, binary_count++; //increment the count binary.pop(); //go to next entry in the queue } return binary_count; }<file_sep>/csc402/assignment4/adjacencyMatrixGraph.cpp /* Author: <NAME> File: adjacencyMatrixGraph.cpp Class: CSC 402 Date: 10/04/2015 */ #include <iostream> #include "adjacencyMatrixGraph.h" using namespace std; adjacencyMatrixGraph::adjacencyMatrixGraph(int n) { numNodes = n; matrix = new int*[numNodes]; for(int i = 0; i < numNodes; i++) matrix[i] = new int[numNodes]; for(int i = 0; i < numNodes; i++) for(int j = 0; j < numNodes; j++) matrix[i][j] = 0; } adjacencyMatrixGraph::~adjacencyMatrixGraph() { delete [] matrix; } int adjacencyMatrixGraph::numberOfVertices() const { int numVertices = 0; for(int i = 0; i < numNodes; i++) { for(int j = 0; j < numNodes; j++) { if(matrix[i][j] == 1) { numVertices++; break; } } } return numVertices; } int adjacencyMatrixGraph::numberOfEdges() const { int numEdges = 0; for(int i = 0; i < numNodes; i++) for(int j = 0; j < numNodes; j++) if(matrix[i][j] == 1) numEdges++; return numEdges; } bool adjacencyMatrixGraph::existsEdge(int from, int to) const { return (matrix[from][to] || matrix[to][from]); } void adjacencyMatrixGraph::insertEdge(int f, int t) { matrix[f][t] = 1; matrix[t][f] = 1; } void adjacencyMatrixGraph::eraseEdge(int f, int t) { matrix[f][t] = 0; matrix[t][f] = 0; } int adjacencyMatrixGraph::degree(int from) const { int degree = 0; for(int i = 0; i < numNodes; i++) if(matrix[from][i] == 1) degree++; return degree; } /* Not a directed graph int adjacencyMatrixGraph::inDegree(int) const { } int adjacencyMatrixGraph::outDegree(int) const { } */ void adjacencyMatrixGraph::output(ostream& out) const { for(int i = 0; i < numNodes; i++) { for(int j = 0; j < numNodes; j++) out << matrix[i][j] << " "; out << "\n"; } } <file_sep>/csc242/Project/search.php <?php session_start(); $loggedin = $_SESSION['loggedin']; /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/search.php Course: CSC 242 - Fall 2013 */ //Create page with same style sheet and links as rest of website echo "<html> <head> <title>Search Results</title> <link rel = 'stylesheet' type = 'text/css' href = 'projectstyle.css'/> </head> <body> <div class = 'header'><h1>Chris' Book Store</h1></div> <div class = 'special'> <h3><p class = 'one'> <a class = 'link' href = 'myproject.php'>Home</a> &nbsp; | &nbsp;"; if($loggedin == true) echo "<a class = 'link' href = 'loggedout.php'>Log Out</a> &nbsp; | &nbsp;"; else echo "<a class = 'link' href = 'login.html'>Log In</a> &nbsp; | &nbsp;"; echo "<a class = 'link' href = 'createaccount.php'>Create Account</a> &nbsp; | &nbsp; <a class = 'link' href = 'contact.php'>Contact Us</a> &nbsp; | &nbsp; <a class = 'link' href = 'categories.php'>Categories</a> &nbsp; | &nbsp; <a class = 'link' href = 'searchstart.php'>Search</a> &nbsp; | &nbsp; <a class = 'link' href = 'orders.php'>View Orders</a> &nbsp; | &nbsp; <a class = 'link' href = 'viewcart.php'>View Cart</a> </p></h3> <h3><div class = 'header'>Search again? <a class = 'link2' href = 'searchstart.php'>Click here</a></div></h3>"; //Variables taken from searchstart.php $isbn = $_POST['isbn']; $keyword = $_POST['keyword']; //Create PDO object & connect to database $dsn = 'mysql:host=localhost;dbname=ccarr419_bookstore'; $username = 'ccarr419'; $password = '<PASSWORD>'; $db = new PDO($dsn, $username, $password); //Get info from the Categories table //If the user searched by ISBN if($isbn != NULL) { $query = "SELECT * FROM Products"; $products = $db->query($query); echo "<h2 class = 'header'>SEARCH RESULTS FOR: $isbn</h2>"; if(!checkEmpty($products, $isbn)) { echo "<h1 class = 'header'><div style = 'color: red'>No Results Found</div></h1>"; } else { $query = "SELECT * FROM Products"; $products = $db->query($query); //Create a table containing the search result echo "<form name = 'orderisbn' action = 'viewcart.php' method = 'post'><table style = 'margin-right: auto; margin-left:auto' border = '1' cellpadding = '5' bgcolor = '#aaaaaa'> <thead> <tr> <th>Title</th> <th>Author</th> <th>Category</th> <th>Product ID</th> <th>Price</th> <th>Quantity</th> </tr></thead>"; $i = 1; foreach($products as $product) { if($product['ProductID'] == $isbn) { echo "<tr><td><div class = 'special'>"; echo $product['Title']; echo "</div></td><td><div class = 'special'>"; echo $product['Author1']; echo "</div></td><td><div class = 'special'>"; $query = "SELECT * FROM Categories"; $categories = $db->query($query); foreach($categories as $category) if($category['CategoryID'] == $product['CategoryID']) echo $category['CategoryName']; echo "</div></td><td><div class = 'special'>"; echo $product['ProductID']; echo "</div></td><td><div class = 'special'>$"; echo round($product['Price'],2); echo "</div></td><td><div class = 'special'><input type = 'text' name = '" . $product['ProductID'] . "' min = '0' max = '"; echo $product['Quantity']; echo "' value = '0' size = '3'/></div></td></tr>"; $i++; } } echo "</table><br/><input type = 'submit' value = 'Add to Cart'/></form></div> </body></html>"; } } //If the user searched by keyword if($keyword != NULL) { $query = "SELECT * FROM Products"; $products = $db->query($query); echo "<h1 class = 'header'>SEARCH RESULTS FOR: $keyword</h1>"; if(!checkEmpty($products, $keyword)) { echo "<h1 class = 'header'><div style = 'color: red'>No Results Found</div></h1>"; } else { $query = "SELECT * FROM Products"; $products = $db->query($query); //Create table containing the search result(s) echo "<form name = 'orderkeyword' action = 'viewcart.php' method = 'post'><table style = 'margin-right: auto; margin-left:auto' border = '1' cellpadding = '5' bgcolor = '#aaaaaa'> <thead> <tr> <th>Title</th> <th>Author</th> <th>Category</th> <th>Product ID</th> <th>Price</th> <th>Quantity</th> </tr></thead>"; foreach($products as $product) { if(strpos($product['Title'], $keyword) !== false) { echo "<tr><td><div class = 'special'>"; echo $product['Title']; echo "</div></td><td><div class = 'special'>"; echo $product['Author1']; echo "</div></td><td><div class = 'special'>"; $query = "SELECT * FROM Categories"; $categories = $db->query($query); foreach($categories as $category) if($category['CategoryID'] == $product['CategoryID']) echo $category['CategoryName']; echo "</div></td><td><div class = 'special'>"; echo $product['ProductID']; echo "</div></td><td><div class = 'special'>$"; echo round($product['Price'],2); echo "</div></td><td><div class = 'special'><input type = 'text' name = '" . $product['ProductID'] . "' min = '0' max = '"; echo $product['Quantity']; echo "' value = '0' size = '3'/></div></td></tr>"; } } echo "</table><br/><input type = 'submit' value = 'Add to Cart'/></form></div> </body></html>"; } } //Checks if result list is empty function checkEmpty($products, $searchItem) { foreach($products as $product) { if(strpos($product['Title'], $searchItem) !== false || $product['ProductID'] == $searchItem) return true; } return false; } ?><file_sep>/csc136/project3a/makefile DebugFlag=-g p3a: Array_tst.o Array.o term.o g++ $(DebugFlag) -o p3a Array_tst.o Array.o term.o Array.o: Array.h Array.cpp term.h g++ $(DebugFlag) -c Array.cpp Array_tst.o: Array_tst.cpp Array.h term.h g++ $(DebugFlag) -c Array_tst.cpp term.o: term.h term.cpp g++ $(DebugFlag) -c term.cpp clean: rm -rf *.o p3a <file_sep>/csc520/finalproj/src/com/library/protocol/field_list/PCatalogQuery.java package com.library.protocol.field_list; import com.library.business_layer.field_list.CatalogQuery; /** * PCatalogQuery serves as a protocol to transfer Table information from the server * to the UI. Only serves as a way to view, print and facilitate information. * PROTOCOL LAYER * @see com.library.business_layer.field_list.CatalogQuery */ public class PCatalogQuery { private int[] publisherIds; private int[] categoryIds; private String[] authors; /** * Basic constructor that sets all attributes. * @param p int[] publisher ids * @param c int[] category ids * @param a String[] author names */ public PCatalogQuery(int p[], int c[], String a[]) { publisherIds = p; categoryIds = c; authors = a; } /** * @return int[] publisher ids * @see com.library.business_layer.field_list.CatalogQuery#getPublisherIds() */ public int[] getPublisherIds() { return publisherIds; } /** * @return int[] category ids * @see com.library.business_layer.field_list.CatalogQuery#getCategoryIds() */ public int[] getCategoryIds() { return categoryIds; } /** * @return String[] author names * @see com.library.business_layer.field_list.CatalogQuery#getAuthors() */ public String[] getAuthors() { return authors; } /** * Prints the CatalogQuery in a human understandable summary. */ public String toString() { String out = ""; out += ("Query: {\n Publishers: ["); for(int i = 0; i < getPublisherIds().length; i++) { out += (Integer.toString(getPublisherIds()[i])); if(i < getPublisherIds().length-1) { out += ", "; } } out += ("];\n Categories: ["); for(int i = 0; i < getCategoryIds().length; i++) { out += (Integer.toString(getCategoryIds()[i])); if(i < getCategoryIds().length-1) { out += ", "; } } out += ("];\n Authors: ["); for(int i = 0; i < getAuthors().length; i++) { out += ("'" + getAuthors()[i] + "'"); if(i < getAuthors().length-1) { out += ", "; } } out += ("];\n}"); return out; } } <file_sep>/csc402/assignment2/SavingsAccount.cpp #include <iostream> #include "BankAccount.h" #include "SavingsAccount.h" using namespace std; SavingsAccount::SavingsAccount() : BankAccount() { setAccountNumber(1234567890); setBalance(0.00); setInterestRate(1); minBalance = 100.00; } SavingsAccount::SavingsAccount(int n, float b, float r) : BankAccount(n, b) { setAccountNumber(n); setBalance(b); setInterestRate(r); minBalance = 100.00; } void SavingsAccount::setInterestRate(double rate) { interestRate = rate*0.01; } void SavingsAccount::withdraw(double amount) { if((getBalance() - amount) < 0) { if(getBalance() <= 0) //(no count towards withdrawal) { setBalance(getBalance()-35); //$35 penalty setBalance(getBalance()-1); //below minBalnce penalty } else { setBalance(0); //withdraw to zero setBalance(getBalance()-35); //minus $35 overdraft fee setBalance(getBalance()-1); //below minBalance penalty } } else { if(getBalance() < minBalance || (getBalance() - amount) < minBalance) { setBalance(getBalance()-amount); setBalance(getBalance()-1); // below minBalance penalty } else setBalance(getBalance()-amount); } } void SavingsAccount::monthEnd() { if(getBalance() >= minBalance) setBalance(getBalance()+(getBalance()*getInterestRate())); } double SavingsAccount::getInterestRate() { return interestRate; } <file_sep>/csc402/inclassprograms/handinprograms/employeeTimeCard.cpp #include <iostream> using namespace std; class employeeTimeCard { public: employeeTimeCard(string fname, string lname, char offloc, char unst, string id, int hrs, float rate, int dep, int ovtm); void setTimeCard(string fname, string lname, char offloc, char unst, string id, int hrs, float rate, int dep, int ovtm); void setFirstName(string); void setLastName(string); void setOfficeLocation(char); void setUnionStanding(char); void setEmployeeId(string); void setHours(int); void setRate(float); void setDependents(int); void setOvertime(int); string getFirstName() const; string getLastName() const; char getOfficeLocation() const; char getUnionStanding() const; string getEmployeeId() const; int getHours() const; float getRate() const; int getDependents() const; int getOvertime() const; void printTimeCard() const; float grossPay() const; float federalTax() const; float socialSecurity() const; float cityTax() const; float unionDues() const; float netPay() const; private: string last_name; string first_name; char office_location; char union_standing; string employee_id; int employee_hours; float employee_rate; int num_dependents; int overtime_hours; }; employeeTimeCard::employeeTimeCard(string fname, string lname, char offloc, char unst, string id, int hrs, float rate, int dep, int ovtm) { setTimeCard(fname, lname, offloc, unst, id, hrs, rate, dep, ovtm); } void employeeTimeCard::setTimeCard(string fname, string lname, char offloc, char unst, string id, int hrs, float rate, int dep, int ovtm) { setFirstName(fname); setLastName(lname); setOfficeLocation(offloc); setUnionStanding(unst); setEmployeeId(id); setHours(hrs); setRate(rate); setDependents(dep); setOvertime(ovtm); } void employeeTimeCard::setFirstName(string fname) { first_name = fname; } void employeeTimeCard::setLastName(string lname) { last_name = lname; } void employeeTimeCard::setOfficeLocation(char offloc) { office_location = offloc; } void employeeTimeCard::setUnionStanding(char unst) { union_standing = unst; } void employeeTimeCard::setEmployeeId(string id) { employee_id = id; } void employeeTimeCard::setHours(int hrs) { employee_hours = hrs; } void employeeTimeCard::setRate(float rate) { employee_rate = rate; } void employeeTimeCard::setDependents(int dep) { num_dependents = dep; } void employeeTimeCard::setOvertime(int ovtm) { overtime_hours = ovtm; } string employeeTimeCard::getFirstName() const { return first_name; } string employeeTimeCard::getLastName() const { return last_name; } char employeeTimeCard::getOfficeLocation() const { return office_location; } char employeeTimeCard::getUnionStanding() const { return union_standing; } string employeeTimeCard::getEmployeeId() const { return employee_id; } int employeeTimeCard::getHours() const { return employee_hours; } float employeeTimeCard::getRate() const { return employee_rate; } int employeeTimeCard::getDependents() const { return num_dependents; } int employeeTimeCard::getOvertime() const { return overtime_hours; } void employeeTimeCard::printTimeCard() const { cout << getLastName() << " " << getFirstName() << " " << getOfficeLocation(); cout << " " << getUnionStanding() << " " << getEmployeeId() << endl; cout << "Gross Pay: $" << grossPay() << endl << endl; cout << "Federal Tax: $" << federalTax() << endl << endl; cout << "Social Security: $" << socialSecurity() << endl << endl; cout << "Net Pay: $" << netPay() << endl; } float employeeTimeCard::grossPay() const { return ( ( getHours() * getRate() ) + ( getOvertime() * 1.5 * getRate() ) ); } float employeeTimeCard::federalTax() const { return ( 0.14 * ( grossPay() - ( 13 * getDependents() ) ) ); } float employeeTimeCard::socialSecurity() const { return ( 0.052 * grossPay() ); } float employeeTimeCard::cityTax() const { if(getOfficeLocation() == 'c') return ( 0.04 * grossPay() ); else return 0.0; } float employeeTimeCard::unionDues() const { if(getUnionStanding() == 'u') return ( 6.75 * grossPay() ); else return 0.0; } float employeeTimeCard::netPay() const { int deductions = (federalTax() + socialSecurity() + cityTax() + unionDues()); return grossPay() - deductions; } int main() { string fname; string lname; char offloc; char unst; string id; int hrs; float rate; int dep; int ovtm; cout << "Enter first name: "; cin >> fname; cout << "Enter last name: "; cin >> lname; cout << "Enter office location: "; cin >> offloc; cout << "Enter union standing: "; cin >> unst; cout << "Enter employee id: "; cin >> id; cout << "Enter regular hours: "; cin >> hrs; cout << "Enter hourly rate: "; cin >> rate; cout << "Enter number of dependents: "; cin >> dep; cout << "Enter amount of overtime hours: "; cin >> ovtm; employeeTimeCard timeCard(fname, lname, offloc, unst, id, hrs, rate, dep, ovtm); cout << endl; timeCard.printTimeCard(); cout << endl; return 0; } <file_sep>/csc136/project2/poly.h // Author: <NAME> // Course: CSC136 // Assignment: Project 2 // Filename: poly.h // Purpose: Definition of the Polynomial Class // This class provides the user the functionality of a polynomial, including // the ability to add terms, evaluate, and multiply the coefficients. // It also provides basic set and get functionality. // A function is provided to read terms from a file, and two associated // non-member, non-friend stream operators are present for reading a Term // and outputting the Polynomial in its entirety. #ifndef POLY_H #define POLY_H #include <iostream> #include <string> using namespace std; struct Term { float coeff; // Coefficient int expn; // Exponent don't use exp, it's a built in function } ; class Polynomial { public: ////// // Constructor ////// /* Function: constructor Member Type: Mutator Description: Sets the number of Terms in the polynomial to 0 Parameters: none Returns: N/A */ //Polynomial(); Polynomial(int s = 0); //Polynomial(const Polynomial &); ////// // Gets and Sets ////// // Sets /* Function: setTerm Member Type: Mutator Description: Sets the term in the variable at a specific index Parameters: int index - input - the index at which the values are stored float co - input - the coefficient int ex - input - the exponent Returns: true if the value is set, false if not */ bool setTerm(int index, float co, int ex); /* Function: setCoeff Member Type: Mutator Description: Sets the coefficient for a term in the variable at a specific index Parameters: int index - input - the index at which the values are stored float co - input - the coefficient for the user Returns: true if the value is set, false if not */ bool setCoeff(int index, float co); /* Function: setExponent Member Type: Mutator Description: Sets the exponent for the term in the variable at a specific index Parameters: int index - input - the index at which the values are stored int ex - input - the exponent for the user Returns: true if the value is set, false if not */ bool setExponent(int index, int ex); // Gets /* Function: getTerm Member Type: Inspector Description: Gives the user the values associated with the terms at the index Parameters: int index - input - the index at which the values are stored Returns: The requested Term Precondition: index is an in use (active) index */ Term getTerm(int index) const; /* Function: getSize Member Type: Inspector Description: Furnishes the number of Terms in the Polynomial Parameters: none Returns: the number of Terms in the Polynomial */ int getSize() const; /* Function: getCoeff Member Type: Inspector Description: Gets the user the coefficient at a certain index Parameters: int index - input - the index at which the values are stored Returns: The requested coefficient Precondition: index is an in use (active) index */ float getCoeff(int index) const; /* Function: getExponent Member Type: Inspector Description: Gets the user the exponent for a certain index Parameters: int index - input - the index at which the values are stored Returns: The requested exponent Precondition: index is an in use (active) index */ int getExponent(int index) const; /* Function: operator () Member Type: Facilitator Description: Evaluate the polynomial for variable x Parameters: x - input - variable that is standing for value of x Returns: The polynomial evaluated for x */ double operator()(double x) const; /* Function: multiply Member Type: Mutator Description: Multiply each coefficient by the scalar arg factor Parameters: fact - input - variable that is multiplying against all the coefficents Returns: void */ void operator *=(float factor); /* Function: add Member Type: Mutator Description: Add a term to the polynomial Parameters: coefficent - input - the coefficent of the term being added exponent - input - the exponent of the term being added Returns: true if the term is added, false otherwise */ bool add(float coefficient, int exponent); /* Function: add Member Type: Mutator Description: Add a term to the polynomial Parameters: T - input - the Term being added Returns: true if the term is added, false otherwise */ bool add(const Term &T); /* Function: readFile Member Type: Mutator Description: Loads up the terms from a user declared filename Parameters: file - input/output - stream variable Returns: void */ void readFile(ifstream &file); private: Term termList[10]; int size; void sort(); // sorts all of the terms in the factor array void swap(Term &x, Term &y); /* Function: setSize Member Type: Mutator Description: Sets the term in the variable at a specific index. Private because the application programmer shouldn't be messing with this; # terms is a function of adding terms. Parameters: int s - input - the index of the last value in the term array Returns: N/A */ void setSize(int s); }; /* Function: operator >> Description: Reads in a Term from a file Parameters: ifstream file - input/output - the input stream Term T - output only - the Term that will hold the data read in Returns: ifstream */ ifstream &operator >>(ifstream &file, Term &T); /* Function: operator << Description: Print a Polynomial to the screen Parameters: out - input/output - output stream P - input - The Polynomial to print Returns: void */ ostream &operator <<(ostream &out,const Polynomial &P); /* Function: operator << Description: Write the Polynomial to a File Parameters: ofstream &out - input/output - The output file stream const Polynomial &P input - Polynomial to save Returns: ofstream - the output file stream */ ofstream &operator <<(ofstream &out,const Polynomial &P); #endif <file_sep>/programmingteam/romannumerals.cpp #include <iostream> #include <string> #include <fstream> using namespace std; string getFileName(); bool openFile(ifstream&, string); void translate(ifstream&); int getNum(char); int main() { string fileName; ifstream inf; fileName = getFileName(); openFile(inf, fileName); translate(inf); return 0; } string getFileName() { string fileName; cout << "Enter file name: "; cin >> fileName; return fileName; } bool openFile(ifstream& inf, string fileName) { bool fileOpen; inf.open(fileName.c_str()); if (inf.fail()) return fileOpen = false; else return fileOpen = true; } void translate(ifstream &inf) { char ch; int num1 = 0; int num2 = 0; int total = 0; string numString = ""; while(inf.get(ch)) { if(ch == ' ' || ch == '\n') { cout << numString << " translated to " << total << endl; num1 = 0; num2 = 0; total = 0; numString = ""; } else { if(num1 == 0) { num1 = getNum(ch); if(num2 < num1) { total += (num1 - num2); total -= num2; } else { total += num1; } } else { num2 = getNum(ch); if(num1 < num2) { total += (num2 - num1); total -= num1; num1 = 0; } else { total += num2; num1 = 0; } } numString += ch; } } } int getNum(char ch) { const char romNum[5] = {'I', 'V', 'X', 'L', 'C'}; ch = toupper(ch); if(ch == romNum[0]) return 1; if(ch == romNum[1]) return 5; if(ch == romNum[2]) return 10; if(ch == romNum[3]) return 50; if(ch == romNum[4]) return 100; return 0; } <file_sep>/csc520/finalproj/src/com/library/server_ui/AuthenticationServerUI.java package com.library.server_ui; import com.library.server_layer.AuthenticationServer; import java.util.Scanner; import java.io.Console; /** * The role of the AuthenticationServerUI is to let the server and user * communicate back and forth. This is done by reading/writing to the console. * The functionality of this server UI includes logging on and off. * SERVER LAYER */ public class AuthenticationServerUI { private AuthenticationServer as; /** * Basic constructor that initializes its corresponding server. */ public AuthenticationServerUI() { as = new AuthenticationServer(); } /** * Lets the user enter their user number and password. Credentials are then * checked for correctness by looking through corresponding Tables. If the * credentials match an existing account, the user will be logged in to * a session id. If there is no match, the user is told. The user may also * choose to steal an existing session if applicable. Session ids are * generated to be unique to each account unless stolen. Accounts that have * their session stolen should be logged out. * @param reader Scanner read user input * @return int the unique or stolen session id, -1 if log in failed */ public int logon(Scanner reader) { as.update(); String num = "", pass = "", steal = ""; Console console = System.console(); boolean s; while(num.equals("")) { //Get user number System.out.print("User Number: "); num = reader.nextLine(); } while(pass.equals("")) { //Get user password System.out.print("Password: "); pass = new String(console.readPassword()); } //Ask if the user wishes to steal an existing session while(!(steal.toLowerCase().equals("y") || steal.toLowerCase().equals("n"))) { System.out.print("Steal an existing session? [y/n]: "); steal = reader.nextLine(); } if(steal.toLowerCase().equals("y")) { s = true; } else { s = false; } int sess = as.logon(num, pass, s); if(sess > 0) { //User got a session id, they are logged in System.out.println("You have successfully logged on\n"); } else { //User log in has failed System.out.println("User number or password was incorrect\n"); } return sess; } /** * Attempts to log off a user with the session id. Only fails if there * is no user with that session id. * @param i int session id */ public void logoff(int i) { as.update(); System.out.println("Logging off..."); if(as.logoff(i)) { System.out.println("You have successfully logged off\n"); } else { System.out.println("An error has occurred when logging off\n"); } } } <file_sep>/csc242/Project/checkout.php <?php session_start(); $loggedin = $_SESSION['loggedin']; $purchases = $_SESSION['order']; /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/checkout.php Course: CSC 242 - Fall 2013 */ //Create page with same style sheet and links as rest of website echo "<html xmlns = 'http://www.w3.org/1999/xhtml'> <head> <title> Chris' Book Store </title> <script type = 'text/javascript'> <!-- function cancelOrder() { var answer = confirm('Are you sure you want to cancel this order?'); if(answer == true) window.location.href = 'myproject.php'; } //--> </script> <!-- My stylesheet for the project --> <link rel = 'stylesheet' type = 'text/css' href = 'projectstyle.css'/> </head> <body> <!-- Links --> <div class = 'header'><h1>Chris' Book Store</h1></div> <div class = 'special'> <h3><p class = 'one'> <a class = 'link' href = 'myproject.php'>Home</a> &nbsp; | &nbsp;"; if($loggedin == true) echo "<a class = 'link' href = 'loggedout.php'>Log Out</a> &nbsp; | &nbsp;"; else echo "<a class = 'link' href = 'login.html'>Log In</a> &nbsp; | &nbsp;"; echo "<a class = 'link' href = 'createaccount.php'>Create Account</a> &nbsp; | &nbsp; <a class = 'link' href = 'contact.php'>Contact Us</a> &nbsp; | &nbsp; <a class = 'link' href = 'categories.php'>Categories</a> &nbsp; | &nbsp; <a class = 'link' href = 'searchstart.php'>Search</a> &nbsp; | &nbsp; <a class = 'link' href = 'orders.php'>View Orders</a> &nbsp; | &nbsp; <a class = 'link' href = 'viewcart.php'>View Cart</a> </p></h3><br/>"; //Open database $dsn = 'mysql:host=localhost;dbname=ccarr419_bookstore'; $username = 'ccarr419'; $password = '<PASSWORD>'; $db = new PDO($dsn, $username, $password); //Create table for the order $query = "SELECT * FROM Products"; $products = $db->query($query); echo "<form name = 'order' action = 'purchasemade.php' method = 'post'><table style = 'margin-right: auto; margin-left:auto' border = '1' cellpadding = '5' bgcolor = '#aaaaaa'> <thead> <tr> <th>Title</th> <th>Product ID</th> <th>Quantity</th> <th>Price</th> <th>S&H</th> <th>Tax</th> <th>Total</th> </tr> </thead>"; //Display, product title, product id, quantity, price, shipping and handling, tax, and total price foreach($purchases as $id => $qty) { foreach($products as $product) { if($id == $product['ProductID']) { echo "<tr><td><div class = 'special'>" . $product['Title'] . "</div></td> <td><div class = 'special'>$id</div></td><input type = 'hidden' name = 'id' value = '$id'/> <td><div class = 'special'><input type 'text' name = 'qty' value = '$qty' size = '3' readOnly/></div></td>"; $price = $qty * $product['Price']; echo "<td><div class = 'special'>$" . $price . "</div></td>"; if($price < 25) $sNh = 4.50; else if($price < 50) $sNh = 7.00; else $sNh = 10.25; echo "<input type = 'hidden' name = 'sNh' value = '$sNh'/><td><div class = 'special'>$" . $sNh . "</div></td>"; $tax = ($price + $sNh) * 0.06; $tax = round($tax, 2); echo "<input type = 'hidden' name = 'tax' value = '$tax'/><td><div class = 'special'>$" . $tax . "</div></td>"; $total = ($price + $sNh + $tax); echo "<input type = 'hidden' name = 'total' value = '$total'/><td><div class = 'special'>$" . $total . "</div></td></tr>"; } } } echo "</table><br/><input type = 'submit' value = 'Comfirm Purchase'/>&nbsp;<input type = 'button' value = 'Cancel Order' onClick = 'cancelOrder()'</form></div></body> </html>"; ?><file_sep>/csc237/project3/WordDataDLinkList.cpp /** // Author: <NAME> // Course: CSC 237 // Filename: WordDataDLinkList.cpp // Purpose: Implements the code for the WordDataDLinkList class // The DLinkedList data member is specifically of the // WordData type and adjusts accordingly. When a duplicate // word is found, only the counter is incremented // no word will be inserted */ #include <iostream> #include "WordDataDLinkList.h" #include "DLinkedList.h" #include "WordData.h" using namespace std; /** //Constructor */ WordDataDLinkList::WordDataDLinkList() {} /** //Checks for matching data within the list */ bool WordDataDLinkList::incMatch(string temp) { for(DListItr<WordData> it(DList); !(it.isNull()); ++it) { WordData checkWord = *it; if (temp == checkWord.getWord()) //If match { DList.remove(checkWord); checkWord.incCount(); DList.insert(checkWord); return true; } } return false; //No match found } /** //Parse from file into DLinkedList */ void WordDataDLinkList::parseIntoList(ifstream &inf) { string temp; //Temporary storage WordData theWord; while (inf >> temp) { if (!incMatch(temp)) //Check if match first { //Insert into list theWord.setWord(temp); theWord.setCount(1); DList.insert(theWord); } } } /** //Print the list with an iterator and for loop */ void WordDataDLinkList::printIteratively() { cout<<"--------------------------"<<endl; cout<<"|D Linked List Iterative|"<<endl; cout<<"|Word Occurences |"<<endl; cout<<"--------------------------"<<endl; for(DListItr<WordData> it(DList); !(it.isNull()); ++it) cout << " " << *it << endl; } /** //Print the list with recursive calls //Calls printRecursivelyWorker */ void WordDataDLinkList::printRecursively() { DListItr<WordData> it(DList); cout<<"--------------------------"<<endl; cout<<"|D Linked List Recursive|"<<endl; cout<<"|Word Occurences |"<<endl; cout<<"--------------------------"<<endl; printRecursivelyWorker(it); } /** //Helps printRecursively with the recursive calls */ void WordDataDLinkList::printRecursivelyWorker(DListItr<WordData> it) { if(it.isLastNode()) //Check if iterator is on last node { cout<<" " << *it << endl; return; //Stop recursion, go back } cout << " " << *it << endl; printRecursivelyWorker(++it); } <file_sep>/csc135/variables_ChristianCarreras.cpp #include <iostream> #include <string> using namespace std; int main() { double number, random; number=23; string name; name= "<NAME>"; char grade; grade= 'A'; cout<< "There are " << number << " in my class." << endl; cout<< "Hello, I am " << name << ". It is nice to meet you." << endl; cout<< "My grade for this class is " << grade << endl; cout<< random << endl; return 0; } <file_sep>/programmingteam/youwin.cpp #include <iostream> #include <vector> #include <string> #include <cmath> using namespace std; int main() { vector<char> alphabet; for(int i = 65; i < 91; i++) { char c = i; alphabet.push_back(c); } vector<char>::iterator active_letter = alphabet.begin(); string name = "YES", s = ""; int count = name.length(); vector<char> input; for(int i = 0; i < name.length(); i++) input.push_back(name[i]); /* while(!input.empty()) { vector<char>::iterator i = input.begin(), lowest = i; for(vector<char>::iterator j = i; j != input.end(); ++j) { if(*j < *lowest) lowest = j; } s += *lowest; input.erase(lowest); }*/ char c = 'A'; while(!input.empty()) { vector<char>::iterator i = input.begin(), lowest = i; int lowest_diff = fabs(*i - c); for(vector<char>::iterator j = i; j != input.end(); ++j) { int diff = fabs(*j - c); if(diff > 13) diff = (26 - diff); if(diff < lowest_diff) { lowest_diff = diff; lowest = j; } } cout << lowest_diff << endl; count += lowest_diff; c = *lowest; s += *lowest; input.erase(lowest); } /* for(int i = 0; i < s.length(); i++) { int num1 = *active_letter, num2 = s[i]; int diff = num1 - num2; while(*active_letter != s[i]) { if(diff > 0) { if(diff > 13) { if(active_letter == alphabet.end()) active_letter = alphabet.begin(); ++active_letter; count++; } else { --active_letter; count++; } } else { if(diff < -13) { if(active_letter == alphabet.begin()) active_letter = alphabet.end(); --active_letter; count++; } else { ++active_letter; count++; } } } }*/ cout << name << endl; cout << s << endl; cout << count << endl; }<file_sep>/csc242/PracticeFiles/display.php <?php $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; echo "$first_name $last_name"; ?> <file_sep>/sideprojects/fractions/makefile #Author: <NAME> cc = /opt/csw/gcc3/bin/g++ test: test.o fraction.o primes.o $(cc) -o test test.o fraction.o primes.o fraction.o: fraction.cpp fraction.h $(cc) -c fraction.cpp test.o: test.cpp fraction.h $(cc) -c test.cpp clean: \rm -rf *.o test <file_sep>/csc552/project2/p2.cpp /// \mainpage /// \author <NAME> /// \date 03/07/2017 (SPRING2017) /// \brief CSC552: Advanced Unix Programming, /// Kutztown University of Pennsylvania /// \details This project aims to replicate a client/server environment /// * by using concurrent processes and IPC mechanisms. /// * The client and server will each have their separate process /// * as well as their own read and write ends from two separate /// * pipes. To start, two pipes are created and then a second /// * process is forked to separate the client and server. The /// * client is the parent process and the server is the child. /// * Each process will close the pipe ends that they will never /// * use. The server will redirect its pipe ends to stdin and /// * stdout and then exec while the client will send the file /// * descriptors for the pipe ends being used as arguments in /// * the exec function. All errors with pipes, forks, and execs /// * are being accounted for with the use of perror (stderr). /* * File: p2.cpp * Due Date: 03/11/2017 * Project: #2 */ #include <iostream> #include <cstdio> #include <sstream> #include <sys/wait.h> using namespace std; /// * Function Name: makeExec /// * Function Type: facilitator /// * Parameters: const char* - import only - executable name /// * Return Value: const char* - ready to be used argument for exec /// * \brief This function takes a single argument of const char* and /// * returns a similar const char* with the exception being './' /// * precedes the argument value. This is necessary for proper /// * execution in a Unix environment. Without this addition to /// * an executable name, every exec function will fail. const char* makeExec(const char*); /// * Function Name: toCString /// * Function Type: facilitator /// * Parameters: int - import only - number to become cstring /// * Return Value: const char* - ready to be used argument for exec /// * \brief This function takes a single argument of int and returns /// * the equivalent in const char*. This is necessary in order /// * to pass the int value as a argument in any exec function. /// * In this project it is used to pass pipe ends to a process /// * so that process can send and receive information through /// * a single or numerous pipes. const char* toCString(int); /// * Function Name: parentProcess /// * Function Type: mutator /// * Parameters: int[] - import/export - pipe 1 /// int[] - import/export - pipe 2 /// * Return Value: void /// * \brief This function will be called by the parent process after /// * the fork. It will close any unused pipe ends in the two /// * given arguments, create any necessary arguments to pass /// * through exec and then finally call exec thus running the /// * client executable. void parentProcess(int[], int[]); /// * Function Name: childProcess /// * Function Type: mutator /// * Parameters: int[] - import/export - pipe 1 /// int[] - import/export - pipe 2 /// * Return Value: void /// * \brief This function will be called by the child process after /// * the fork. It will close any unused pipe ends in the two /// * given arguments, create any necessary arguments to pass /// * through exec and then finally call exec thus running the /// * server executable. void childProcess(int[], int[]); /// \file /// * \brief This project aims to replicate a client/server environment /// * by using concurrent processes and IPC mechanisms. /// * The client and server will each have their separate process /// * as well as their own read and write ends from two separate /// * pipes. To start, two pipes are created and then a second /// * process is forked to separate the client and server. The /// * client is the parent process and the server is the child. /// * Each process will close the pipe ends that they will never /// * use. The server will redirect its pipe ends to stdin and /// * stdout and then exec while the client will send the file /// * descriptors for the pipe ends being used as arguments in /// * the exec function. All errors with pipes, forks, and execs /// * are being accounted for with the use of perror (stderr). int main() { pid_t isParent; //Easily differentiate between child and parent process //File descriptors to use for pipe creation int client2Server_fd[2]; int server2Client_fd[2]; //Variables to hold arguments for exec functions const char *client, *server, *cRead, *cWrite; //Create the client to server pipe //Client will have the write end and the server will have the read end if(pipe(client2Server_fd) == -1) { perror("Pipe Error -- Client to Server pipe could not be created\n"); return 0; } //Create the server to client pipe //Server will have the write end and the client will have the read end if(pipe(server2Client_fd) == -1) { perror("Pipe Error -- Server to Client pipe could not be created\n"); return 0; } //Fork a second process and get the pid of both processes to easily //determine if it is the child or the parent isParent = fork(); if(isParent) { parentProcess(client2Server_fd, server2Client_fd); perror("Parent exec failed\n"); //Should only fire if exec failed } //If the process is the child else if(isParent == 0) { childProcess(client2Server_fd, server2Client_fd); perror("Child exec failed\n"); //Should only fire if exec failed } //If it is not the parent or the child then the fork failed else { perror("Fork Error -- could not fork another process\n"); } return 0; } /// \details /// * makeExec takes a single const char* argument named exec and concatenates /// * with the string value "./" It then returns the cstring equivalent of that /// * concatenation. i.e the result will look like this: "./exe" /// * This function should be used with every exec function to ensure that it /// * works properly in a Unix environment. const char* makeExec(const char* exe) { string suf = "./"; //Unix's way of opening an executable string tempStr = suf + exe; return tempStr.c_str(); } /// \details /// * toCString takes a single int argument which is to be turned into a const /// * char * value. Stringstream will be used to correctly transfer the int value /// * into a cstring. The int value is put into the stringstream using stream /// * insertion. A temporary string will then hold the string equivalent of the /// * string stream. The temporary string is then turned into the cstring /// * equivalent and returned. const char* toCString(int num) { stringstream sstr; sstr << num; string tempStr = sstr.str(); return tempStr.c_str(); } /// \details /// * The parent process will implement the client side of the project. First all /// * unused pipe ends will be closed by using the array parameters given. Then /// * the client executable will be be transformed into the correct format so /// * exec can use it properly. Lastly the pipe ends that will be used will be /// * transformed into const char* so they can be used as arguments in the exec. void parentProcess(int c2s[], int s2c[]) { const char *client, *cRead, *cWrite; //Close unused pipe ends close(c2s[0]); close(s2c[1]); //Create arguments for exec client = makeExec("client"); cRead = toCString(s2c[0]); cWrite = toCString(c2s[1]); //Exec to client process execlp(client, cRead, cWrite, NULL); } /// \details /// * The child process will implement the server side of the project. First all /// * usused pipe ends will be closed by using the array parameters given. Then /// * the pipe ends that will be used will be redirected towards stdin and stdout /// * since the server will only communicate with the client. The redirection is /// * done by the dup2 function. Lastly the server executable will be transformed /// * into the correct format so exec can use it properly. void childProcess(int c2s[], int s2c[]) { const char *server; //Close unused pipe ends close(s2c[0]); close(c2s[1]); dup2(c2s[0], 0); //Redirect to stdin dup2(s2c[1], 1); //Redirect to stdout server = makeExec("server"); //Create argument for exec execlp(server, NULL); } <file_sep>/csc402/assignment3/linearList.h /* Author: <NAME> File: linearList.h About: Abstract linear linked list class with simple, virtual member functions. */ #include <iostream> using namespace std; template<class T> class linearList { public: virtual ~linearList() {}; virtual bool empty() const = 0; virtual int size() const = 0; virtual T& get(int theIndex) const = 0; virtual int indexOf(const T& theElement) const = 0; virtual void erase(int theIndex) = 0; virtual void insert(int theIndex, const T& theElement) = 0; virtual void output(ostream& out) const = 0; }; <file_sep>/csc235/README.txt CSC 235 - Computer Organization and Assembly Language Dr. <NAME> Kutztown University Fall 2014 This course is designed to provide an understanding of the organization of and internal execution of a program by a modern digital computer. <file_sep>/csc136/project4/term.cpp /* File: term.cpp Author: <NAME> Course: CSC136 Assignment: Project 4 Description: Creates term objects that can be used to store inside a polynomial object. The term is self-contained and self-reliant */ #include <iostream> #include <fstream> #include <string> #include <cmath> #include "term.h" using namespace std; ////////////// //Constructor ////////////// /* Function: setCoefficient Member Type: Mutator Description: Sets the coefficient in the term Parameters: float - input - coefficient to put in the term Returns: true if value is set, false if not */ Term::Term(float coeff, int expn) { setTerm(coeff, expn); } /////////// //Sets /////////// /* Function: setExponent Member Type: Mutator Description: Sets the exponent in the term Parameters: int - input - exponent to put in the term Returns: true if value is set, false if not */ bool Term::setTerm(float co, int ex) { coefficient = co; exponent = ex; return true; } /* Function: setCoefficient Member Type: Mutator Description: Sets the coefficient in the term Parameters: float - input - coefficient to put in the term Returns: true if value is set, false if not */ bool Term::setCoefficient(float co) { return(coefficient = co); } /* Function: setExponent Member Type: Mutator Description: Sets the exponent in the term Parameters: int - input - exponent to put in the term Returns: true if value is set, false if not */ bool Term::setExponent(int ex) { return(exponent = ex); } /////////// //Gets /////////// /* Function: getCoefficient Member Type: Inspector Description: Returns the coefficient value of the term Parameters: none Returns: float - coefficient */ float Term::getCoefficient() const { return coefficient; } /* Function: getExponent Member Type: Inspector Description: Returns the exponent value of the term Parameters: none Returns: int - exponent */ int Term::getExponent() const { return exponent; } //////////////////////// //Member Operators //////////////////////// /* Function: *= operator Member Type: Mutator Description: Multiplies term coefficient by a factor Parameters: double - factor to multiply by Returns: void */ void Term::operator*=(double factor) { setCoefficient(getCoefficient()*factor); } /* Function: () operator Member Type: Facilitator Description: Evaluates the term for the given factor Parameters: double - input - factor to evaluate the term by Returns: double - the term evaluated */ double Term::operator()(double x) const { double answer; answer = pow(x, getExponent())*getCoefficient(); return answer; } /* Function: == operator Member Type: Facilitator Description: Checks if the exponent of a term is equal to the given integer Parameters: Term - input - number to check if equal to Returns: true if the exponent is equal, false if not */ bool Term::operator==(Term x) const { if(getExponent() == x.getExponent()) return true; else return false; } /* Function: != operator Member Type: Facilitator Description: Checks if the the exponent of term is not equal to the given integer Parameters: Term - input - number to check not equal to Returns: true if not equal, false if equal */ bool Term::operator!=(Term x) const { if(getExponent() != x.getExponent()) return true; else return false; } /* Function: > operator Member Type: Facilitator Description: Checks if the Term is greater than a given Term Parameters: Term& - input - Term to check if greater than Term Returns: true if the term is greater than the other term, false if not */ bool Term::operator>(const Term &T) const { if(getExponent() > T.getExponent()) return true; else return false; } /* Function: < operator Member Type: Facilitator Description: Checks if the Term is less than a given Term Parameters: Term& - input - Term to check if greater than Term Returns: true if the term is less than the other term, false if not */ bool Term::operator<(const Term &T) const { if(getExponent() < T.getExponent()) return true; else return false; } /* Function: += operator Member Type: Mutator Description: Combines common terms Parameters: Term& - input - Term to add to another term Returns: bool */ bool Term::operator+=(const Term &T) { setCoefficient(getCoefficient()+T.getCoefficient()); return true; } /////////////////////////// //Associated Operators /////////////////////////// /* Function: >> operator Description: Takes input and places it inside the term's coefficient and exponent. Enables cin << Term Parameters: ifstream& - input stream Term& - The Term from user-input Returns: ifstream */ ifstream &operator>>(ifstream &input, Term &T) { float coeff; int expn; input >> coeff >> expn; T.setCoefficient(coeff); T.setExponent(expn); return input; } /* Function: << operator Description: Outputs the Term in correct polynomial form Enables cout << Term Parameters: ostream& - the output stream const Term& - the Term to ouput Returns: ostream */ ostream &operator<<(ostream &out, const Term &T) { //When the coefficient and exponent are greater than 1 if(T.getCoefficient() > 1 && T.getExponent() > 1) out << T.getCoefficient() << "x^" << T.getExponent(); //When the coefficient is equal to 1 but the exponent is greater than 1 else if(T.getCoefficient() == 1 && T.getExponent() > 1) out << "x^" << T.getExponent(); //When the coefficient > 1 and the exponent = 1 else if(T.getCoefficient() > 1 && T.getExponent() == 1) out << T.getCoefficient() << "x"; //When both the coefficient and the exponent are equal to one else if(T.getCoefficient() == 1 && T.getExponent() == 1) out << "x"; //When the the exponent is zero else if(T.getExponent() == 0) out << T.getCoefficient(); //When the coefficient is 0 else if(T.getCoefficient() == 0) out << ""; return out; } <file_sep>/csc570/TensorFlowTutorials/DataRepresentation/KernelMethods/kernel_m.py import time import numpy as np import tensorflow as tf def get_input_fn(dataset_split, batch_size, capacity=10000, min_after_dequeue=3000): def _input_fn(): images_batch, labels_batch = tf.train.shuffle_batch( tensors=[dataset_split.images, dataset_split.labels.astype(np.int32)], batch_size=batch_size, capacity=capacity, min_after_dequeue=min_after_dequeue, enqueue_many=True, num_threads=4) features_map = {'images': images_batch} return features_map, labels_batch return _input_fn data = tf.contrib.learn.datasets.mnist.load_mnist() train_input_fn = get_input_fn(data.train, batch_size=256) eval_input_fn = get_input_fn(data.validation, batch_size=5000) image_column = tf.contrib.layers.real_valued_column('images', dimension=784) # Specify the feature(s) to be used by the estimator. image_column = tf.contrib.layers.real_valued_column('images', dimension=784) optimizer = tf.train.FtrlOptimizer(learning_rate=50.0, l2_regularization_strength=0.001) kernel_mapper = tf.contrib.kernel_methods.RandomFourierFeatureMapper( input_dim=784, output_dim=2000, stddev=5.0, name='rffm') kernel_mappers = {image_column: [kernel_mapper]} estimator = tf.contrib.kernel_methods.KernelLinearClassifier( n_classes=10, optimizer=optimizer, kernel_mappers=kernel_mappers) # Train. start = time.time() estimator.fit(input_fn=train_input_fn, steps=2000) end = time.time() print('Elapsed time: {} seconds'.format(end - start)) # Evaluate and report metrics. eval_metrics = estimator.evaluate(input_fn=eval_input_fn, steps=1) print(eval_metrics) <file_sep>/csc242/Project/loggedout.php <?php session_start(); unset($_SESSION); session_destroy(); //Destroys session and logs the user out /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/loggedout.php Course: CSC 242 - Fall 2013 */ //Create page with same style sheet and links as rest of website echo "<html> <head> <title>Search Results</title> <link rel = 'stylesheet' type = 'text/css' href = 'projectstyle.css'/> </head> <body> <div class = 'header'><h1>Chris' Book Store</h1></div> <div class = 'special'> <h3><p class = 'one'> <a class = 'link' href = 'myproject.php'>Home</a> &nbsp; | &nbsp; <a class = 'link' href = 'login.html'>Log In</a> &nbsp; | &nbsp; <a class = 'link' href = 'createaccount.php'>Create Account</a> &nbsp; | &nbsp; <a class = 'link' href = 'contact.php'>Contact Us</a> &nbsp; | &nbsp; <a class = 'link' href = 'categories.php'>Categories</a> &nbsp; | &nbsp; <a class = 'link' href = 'searchstart.php'>Search</a> &nbsp; | &nbsp; <a class = 'link' href = 'orders.php'>View Orders</a> &nbsp; | &nbsp; <a class = 'link' href = 'viewcart.php'>View Cart</a> </p></h3><br/> <h3><p class = 'one'>You're now logged out! <a href = 'login.html' class = 'link'>Log back in?</a></p></h3> </div></body></html>"; ?><file_sep>/csc402/assignment4/makefile debugFlag=-g graphDemo: graphDemo.o adjacencyMatrixGraph.o adjacencyListGraph.o g++ -o graphDemo graphDemo.o adjacencyMatrixGraph.o adjacencyListGraph.o $(debugFlag) adjacencyMatrixGraph.o: adjacencyMatrixGraph.cpp adjacencyMatrixGraph.h g++ -c adjacencyMatrixGraph.cpp $(debugFlag) adjacencyListGraph.o: adjacencyListGraph.cpp adjacencyListGraph.h g++ -c adjacencyListGraph.cpp $(debugFlag) graphDemo.o: graphDemo.cpp adjacencyMatrixGraph.h adjacencyMatrixGraph.cpp adjacencyListGraph.h adjacencyListGraph.cpp g++ -c graphDemo.cpp clean: \rm -f *.o graphDemo <file_sep>/csc237/project1/WordInfo.h /** // Author: <NAME> // File: WordInfo.h // Purpose: Header file for the WordInfo class. // This file creates the WordInfo class. // The WordInfo class consists of private members // word, which is string and count which is an int but // also counts the # of times the word appears. // The class also has public member functions such // as sets, gets and an overloaded operator. // The class also contains associative operators. */ #ifndef WORDINFO_H #define WORDINFO_H #include <iostream> #include <fstream> #include <string> using namespace std; class WordInfo { public: //Constructor WordInfo(string wrd = "", int cnt = 0); /////// //Sets /////// /** // Function: setWord // Parameters: string - import only // Returns: void // Member Type: Mutator // Purpose: Sets the value for the private member word */ void setWord(string); /** // Function: setCount // Parameters: int - import only // Returns: void // Member Type: Mutator // Purpose: Sets the value for the private member count */ void setCount(int); /////// //Gets /////// /** // Function: getWord // Parameters: none // Returns: string // Member Type: Inspector // Purpose: Returns the value of the private member word */ string getWord() const; /** // Function: getCount // Parameters: none // Returns: int // Purpose: Returns the value of the private member count */ int getCount() const; /** // Function: ++ operator // Parameters: int (post-increment) // Returns: void // Purpose: increments count */ void operator++(int); private: string word; int count; }; //Associate operators /** // Function: >> operator // Parameters: ifstream& - import/export // WordInfo& - import/export // Returns: ifstream // Purpose: Extract data from file directly // into class */ ifstream &operator>>(ifstream &, WordInfo &); /** // Function: << operator // Parameters: ostream& - import/export // WordInfo - import only // Returns: ostream // Purpose: prints the class to screen */ ostream &operator<<(ostream &, const WordInfo &); #endif <file_sep>/csc242/Project/removeOrder.php <?php session_start(); unset($_SESSION['order']); /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/removeOrder.php Course: CSC 242 - Fall 2013 */ //Remove order and return to shopping cart header("Location: viewcart.php"); ?><file_sep>/csc402/inclassprograms/studentGrader.cpp #include <iostream> using namespace std; struct student { string name; int quizzes[]; int exams[]; }; int main() { return 0; } <file_sep>/csc510/assignment5/readWriteSTM.h /* Author: <NAME> Date: 12/04/17 Due Date: 12/12/17 File: readWriteSTM.h Assignment: #5 Course: CSC510 Advanced Operating Systems Professor: Dr. Parson University: Kutztown University of Pennsylvania About: As a header file, numerous functions and constants are declared in order to better depict what the state machine is doing at each step of the way. This file only outlines a general state machine that can have any purpose but was originally intended to solve the Readers Writers Problem. As such, some functions and constants are blueprinted here to help that goal. The Readers Writers Problem is solved by five algorithms in this state machine. To test these algorithms, multithreaded processes are simulated with multiple loops and threads. This is to try and create a similar environment a computer deals with expect on a much higher level. */ #ifndef READWRTIESTM_H #define READWRITESTM_H #define NUM_THREADS 10 //How many threads to run the algorithm #define NUM_LOOPS 100 //How many loops each thread should run #define KEEP_GOING 1 //Keep the current loop going #define STOP_GOING 0 //Terminate the current loop #define READER 0 //Designate the thread as a reader #define WRITER 1 //Designate the thread as a writer #define STATE_INIT 0 //Init state in the STM #define STATE_WAIT 1 //Wait state in the STM #define STATE_CRITSECT 2 //Critical Section state in the STM #define STATE_TERMINATE 3 //Terminate (Accept) state in the STM #define STM_FAIR 0 //Signifies the fair algorithm #define STM_WRP 1 //Signifies the weak reader preference algorithm #define STM_SRP 2 //Signifies the strong reader preference algorithm #define STM_WWP 3 //Signifies the weak writer preference algorithm #define STM_SWP 4 //Signifies the strong writer preference algorithm #define STM_FCFS 5 //Signifies the first come first serve preference algorithm #define SLEEP_THREAD 100 //Amount of time to sleep between spawing threads #define SLEEP_READER 25000 //Amount of time to sleep for a reader in the cs #define SLEEP_WRITER 32500 //Amount of time to sleep for a writer in the cs #include <iostream> #include <fstream> //Write to file #include <queue> //waitingQueue #include <cstdatomic> //Atomic variables #include <pthread.h> //Threads static std::ofstream logFile; //Log file to write to static atomic<bool> lOpen(true); //Log lock open? static atomic<bool> rOpen(true); //Reader lock open? static atomic<bool> wOpen(true); //Writer lock open? static atomic<bool> csOpen(true); //Critical Section lock open? static atomic<bool> free2read(true); //Lets readers know they can concurrently read static atomic<bool> free2write(true); //Lets writers know they can write static atomic<int> readersCount(0); //Number of active readers static atomic<int> readersWaiting(0); //Number of waiting readers static atomic<int> writersCount(0); //Number of active writers static atomic<int> writersWaiting(0); //Number of waiting writers static atomic<int> threadsToGo(NUM_THREADS); //Threads until end of simulation static atomic<int> lastThreadMade(-1); //Tid of the last thread to be made static atomic<int> rwSeed(42); //Starting seed for thread assignment of R/W static pthread_mutex_t lMtx = PTHREAD_MUTEX_INITIALIZER; //Mutex for log static pthread_cond_t lCon = PTHREAD_COND_INITIALIZER; //Condition for log static pthread_mutex_t csMtx = PTHREAD_MUTEX_INITIALIZER; //Mutex for critical section static pthread_cond_t csCon = PTHREAD_COND_INITIALIZER; //Condition for critical section static pthread_mutex_t rMtx = PTHREAD_MUTEX_INITIALIZER; //Mutex for reader count static pthread_cond_t rCon = PTHREAD_COND_INITIALIZER; //Condition for reader count static pthread_mutex_t wMtx = PTHREAD_MUTEX_INITIALIZER; //Mutex for writer count static pthread_cond_t wCon = PTHREAD_COND_INITIALIZER; //Condition for writer count class readWriteSTM { public: /* tid: The thread's ID (-1 default represents the processor) lpCnt: The current loop the thread is on rw: Is the thread a reader or writer? The thread struct keeps all information relevant to a single thread in a single object for easy access of information. */ struct thread { //Tid is -1 by default, must be given a value thread() : tid(-1) {} pthread_t th; //The thread to be used int tid; //Should be: (0 <= tid < NUM_THREADS) int lpCnt; //Should be: (0 <= lpCnt < NUM_LOOPS) int rw; //Should be 1 for Writer, 0 for Reader }; const thread stmProcessor; //Dummy thread to represent the processor (used for log) //The following two variables are used to create the Reader/Writer //distribution amongst the threads. The distribution is as such: //If a number given is between 0 and rwSplit, the result is a reader //If a number given is between rwSplit and rwTotal, the result is a reader //e.g. with a rwTotal of 100 and a rwSplit of 50, there is a 50/50 chance //the thread will be a reader or writer static const int rwTotal = 100; //Should be greater than rwSplit static const int rwSplit = 50; //Should be less than rwTotal std::queue<int> waitingQueue; //Queue that is used in some RWP solutions //Array of threads that are to be all allocated of used for testing thread threads[NUM_THREADS]; readWriteSTM(); ~readWriteSTM(); //Weak Reader Preference: When a reader is in the critical section, a //writer must wait until all readers exit int wrp(thread); //Strong Reader Preference: If a writer is writing and another writer is //waiting, an arriving reader will get in first int srp(thread); //Weak Writer Preference: If a writer is writing, then waiting writers go first int wwp(thread); //Strong Writer Preference: Arriving writers go next int swp(thread); //Fair Preference: Whoever arrives next goes next (default option) int fair(thread); //First Come First Serve: Control algorithm (no concurrency) int fcfs(thread); //Creates NUM_THREAD amount of threads and then sends them to be linked //to the algorithm picked or the default (default is 'fair') void makingThreads(int s=0); //Writes a message to the log file. Uses mutex locks since multiple //threads will be attempting to gain this resource. The third parameter //indicates type and will default to 0 indicating a normal log message void logMsg(std::string, thread, int t=0); private: //The current state of each thread. Is a parallel array to threads[] int currentStates[NUM_THREADS]; int currentSTM; //The current algoithm to test with each thread void scheduleSTM(int); //Sets the current algorithm to test void startProcess(int); //Starts the current threads process/job //Lock the given mutex if unlocked and block if it is locked already void lockMutex(pthread_mutex_t&, pthread_cond_t&, atomic<bool>&); //Unlock the given mutex and signal any waiting threads void unlockMutex(pthread_mutex_t&, pthread_cond_t&, atomic<bool>&); //Necessary function to link the thread to its process to execute. Acts as //a middle man between thread initialization and process function static void *linkThread(void*); //Print dots to the console to show the user the simulation is not stuck static void *consoleFeedback(void*); //Get the current duration time in microseconds at this point in the simulation std::string getTime() const; //Get the current duration in hours, minutes and seconds std::string stmDuration() const; }; #endif <file_sep>/csc570/arffio.py # arffio.py, <NAME>, January 2018, adapted from: # bayescalc.py, <NAME>, Summer 2013 # This module is for reading & writing ARFF # files (attribute Relation File Format) used by Weka. # main is a test driver # small modifications made by <NAME>, March 2018 ''' readARFF and writeARFF are the main library functions of use in this module. The non-private functions (__functions__() are private) are useful as well. The __main__ code is a test driver. ''' import sys import re import copy import math import os.path import datetime # __attr_re__ = re.compile(r'^\s*@attribute\s+(\S+)\s+(\S+)') # __date_re__ parenthesizes name and date-format __date_re__ = re.compile(r'^\s*@attribute\s+(\S+)\s+date\s+(\S+.*)$') # __attr_re__ parenthesizes name and type __attr_re__ = re.compile(r'^\s*@attribute\s+(\S+)\s+(\S+.*)$') # __data_re__ is the @data card __data_re__ = re.compile(r'^\s*@data.*$') def __getAttrIndices__(af): ''' Returns a map from attribute name to (offset, type) pair, where offset is attribute position, starting at 0, and type is described in the readARFF function documentation. Parameter af is the already-open ARFF file handle. Return value is the in-core map "result[aname] = (attrindex, atype)", where aname is the attribute name, attrindex is its index starting at 0, and atype is per the readARFF comments. ''' result = {} attrCount = 0 line = af.readline() while line: sline = line.strip() dm = __date_re__.match(sline) am = __attr_re__.match(sline) if dm: aname = dm.group(1) wformat = dm.group(2).strip() # wformat is Weka format, see # https://www.cs.waikato.ac.nz/ml/weka/arff.html # Appears to be based on Java format in java.text.SimpleDateFormat # https://docs.oracle.com/javase/8/docs/api/index.html # Internal we must use Python's datetime strptime() format: # https://docs.python.org/2/library/time.html#time.strptime # https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior # This section converts Weka's format string wformat to # Python's pformat, and stores the type as a # ('date', wformat, pformat) 3-tuple. pformat = '' wremains = wformat while wremains: if wremains.startswith('yyyy') or wremains.startswith('YYYY'): pformat = pformat + "%Y" wremains = wremains[4:] elif wremains.startswith('yy') or wremains.startswith('YY'): pformat = pformat + "%y" wremains = wremains[2:] elif wremains.startswith('MM'): pformat = pformat + "%m" wremains = wremains[2:] elif wremains.startswith('M'): pformat = pformat + "%m" wremains = wremains[1:] elif wremains.startswith('dd'): pformat = pformat + "%d" wremains = wremains[2:] elif wremains.startswith('HH'): pformat = pformat + "%H" wremains = wremains[2:] elif wremains.startswith('mm'): pformat = pformat + "%M" wremains = wremains[2:] elif wremains.startswith('ss'): pformat = pformat + "%S" wremains = wremains[2:] elif (wremains.startswith('z') or wremains.startswith('Z') or wremains.startswith('X')): pformat = pformat + "%Z" wremains = wremains[1:] else: pformat = pformat + wremains[0] wremains = wremains[1:] result[aname] = (attrCount, ('date', wformat, pformat)) attrCount += 1 # print("DEBUG mapped", aname, "TO", result[aname]) elif am: aname = am.group(1) atype = am.group(2).strip() if atype.startswith('{') and atype.endswith('}'): nlist = atype[1:-1].strip().split(',') for i in range(0,len(nlist)): nlist[i] = nlist[i].strip(); realtype = ('nominal', atype, nlist) else: realtype = atype result[aname] = (attrCount, realtype) attrCount += 1 # print("DEBUG mapped", aname, "TO", result[aname]) elif __data_re__.match(sline): break line = af.readline() return result def __getDataset__(af, amap): # Start helper function __mergeInstanceStrings__. def __mergeInstanceStrings__(instlist): # We have split along ','; fix cases here ',' is in a quoted string. # WHEN A STRING CONTAINS A "," MERGE WITH ITS PARTNER result = [] ix = 0 while ix < len(instlist): field = instlist[ix] if (field.startswith("'") or field.startswith('"')): terminator = field[0] fld = field if fld.endswith(terminator): result.append(fld) ix += 1 else: ix += 1 while ix < len(instlist): f = instlist[ix] # Re-insert the commas as part of the quoted string. if (f.endswith(terminator)): fld = fld + ',' + f ix += 1 break else: fld = fld + ',' + f ix += 1 result.append(fld) else: result.append(field) ix += 1 return result # End helper function __mergeInstanceStrings__. result = [] line = af.readline() while line: sline = line.strip() if sline[0:1] == '%': # Comment line line = af.readline() continue instance = sline.split(',') # WHEN A STRING CONTAINS A "," MERGE WITH ITS PARTNER instance = __mergeInstanceStrings__(instance) for a in amap.keys(): pos, t = amap[a] # print("DEBUG dataset", a, pos, t, instance[pos], instance) if pos >= len(instance): sys.stderr.write("ERROR, attribute " + str(a) + "maps to position, type " + str(pos) + "," + str(t) + ", instance has length " + str(len(instance)) + ":\n\t" + str(instance) + "\n") sys.stderr.flush() if instance[pos] == '?': instance[pos] = None elif t == 'numeric': # sys.stderr.write("DEBUG instance[pos]: " # + str(instance[pos]) + '\n') vf = float(instance[pos]) vi = int(vf) v = vi if (vi == vf and not '.' in instance[pos]) else vf instance[pos] = v elif t == 'string' and instance[pos].startswith("'"): instance[pos] = instance[pos][1:-1] elif isinstance(t, tuple) and len(t) == 3 and t[0] == 'date': # No need to strip anything. instance[pos] = (instance[pos], datetime.datetime.strptime(instance[pos], t[2])) elif isinstance(t, tuple) and len(t) == 3 and t[0] == 'nominal': #instance[pos] = (instance[pos], instance[pos]) instance[pos] = (instance[pos]) result.append(instance) # print("DEBUG instance", instance) line = af.readline() return result def readARFF(fname): ''' Reads ARFF file named fname and returns (attrmap, dataset), where attrmap is the map from attrname -> (offset, type) returns by __getAttrIndices__, and dataset is a 2D list indexed on [row][offset] that holds in actual data instances. This offset is attribute position, starting at 0, and type is one of a date-3-tuple, 'numeric', 'string', a nominal set in {} delimiters, or a ARFF datetime value. A nominal type field is a 3-tuple of ('nominal', {NOMINAL_LIST_IN_STRING_FORM}, PYTHON_LIST_OF_NOMINAL_SYMBOLS), and a datetime (Weka date) is a 3-tuple consisting of ('date', Weka-format-string, Python-datetime-strptime-format-string). A nominal attribute-value in the dataset is a 2-tuple of (STRING_VALUE, NOMINAL_SYMBOL), and a date attribute-value is a 2-tuple (STRING_VALUE, Python datetime.datetime object). ''' af = open(fname, 'r') amap = __getAttrIndices__(af) dataset = __getDataset__(af, amap) af.close() return((amap, dataset)) def writeARFF(fname, attrmap, dataset, isDebugMode=False): ''' Writes ARFF file named fname with data in attrmap and dataset, where attrmap is the map from attrname -> (offset, type) returns by __getAttrIndices__, and dataset is a 2D list indexed on [row][offset] that holds in actual data instances. Set isDebugMode to True (default is False) for debugging output to sys.stderr. ''' def __quoteAttr__(datum): # Fix strings attributes that need to be wrapped in quotes. # print("DEBUG datum 1 ",datum) if (" " in datum) or ("," in datum) or ("'" in datum) or ('"' in datum): # print("DEBUG datum 2 ",datum) if ((datum.startswith("'") and datum.endswith("'")) or (datum.startswith('"') and datum.endswith('"'))): pass # It already is delimited. elif "'" in datum: datum = '"' + datum + '"' else: datum = "'" + datum + "'" return datum fout = open(fname, 'w') relationstring = sys.argv[0] for arg in sys.argv[1:]: relationstring = relationstring + " " + arg # relationstring = relationstring + " @ " + str(datetime.datetime.now()) if "'" in relationstring: relationstring = '"' + relationstring + '"' else: relationstring = "'" + relationstring + "'" # fout.write('@relation tmprelation\n') fout.write('@relation ' + relationstring + '\n') fout.write('% ARFF file generated @ ' + str(datetime.datetime.now()) + '\n') newmap = remapAttributes(attrmap) newkeys = newmap.keys() newkeys.sort() for k in newkeys: fout.write('@attribute ' + newmap[k][0] + ' ' + ('numeric' if (newmap[k][1] == 'float' or newmap[k][1] == 'int') else ('date ' + newmap[k][1][1]) if (isinstance(newmap[k][1],tuple) and newmap[k][1][0] == 'date') else (newmap[k][1][1]) if (isinstance(newmap[k][1],tuple) and newmap[k][1][0] == 'nominal') else newmap[k][1]) + '\n') fout.write('@data\n') for rix in range(0, len(dataset)): # Iterate over rows in relation. row = dataset[rix] datum = row[0] if (isinstance(datum,tuple) and len(datum) == 2): # nominal or date, use the string form datum = datum[0] datum = __quoteAttr__(str(datum) if (not datum is None) else '?') fout.write(datum) for colix in range(1, len(row)): datum = row[colix] if (isinstance(datum,tuple) and len(datum) == 2): # nominal or date, use the string form datum = datum[0] datum = __quoteAttr__(str(datum) if (not datum is None) else '?') fout.write("," + datum) if isDebugMode: # Test whether reading a test arff file's datetime # field into a Python datetime works correctly. if (isinstance(newmap[colix][1],tuple) and len(newmap[colix][1]) == 3 and newmap[colix][1][0] == 'date'): dt = row[colix][1] sys.stderr.write("DEBUG PYTHON DATETIME FIELD " + newmap[colix][0] + ": " + str(dt) + '\n') fout.write('\n') fout.close() def remapAttributes(attrmap): ''' attrmap is a map from "attrname -> (offset, type)", and remapAttributes returns a map "offset -> (attrname, type)" ''' newmap = {} for attrname in attrmap.keys(): newmap[attrmap[attrname][0]] = (attrname, attrmap[attrname][1]) return newmap def mean(valueList): ''' Return the mean of valueList as a float. ''' sum = 0 try: for v in valueList: sum = sum + v floater = sum / float(len(valueList)) return floater except: sys.stderr.write('TYPE ERROR, call to mean for list: ' + str(valueList) + '\n') return None def median(valueList): ''' Return the median of valueList, where median is the center value after sorting a copy of valueList. If there are an even number of elements, median returns the mean of the two central elements. Otherwise, any element type amenable to a sort may be in the valueList. ''' try: vl = copy.copy(valueList) vl.sort() if ((len(vl) & 1) == 1): # odd number of elements return vl[int(len(vl) / 2)] upper = int(len(vl) / 2) if vl[upper-1] == vl[upper]: return vl[upper] sum = vl[upper-1] + vl[upper] floater = sum / 2.0 return floater except: sys.stderr.write('TYPE ERROR, call to median for list: ' + str(valueList) + '\n') return None def stddev(valueList, average=None, issample=False): ''' Return the population standard deviation of valueList. If the caller supplies the average parameter, stddev uses that as the mean in computing the standard deviation. Otherwise, stddev invokes mean() to compute the mean, but returns only the standard deviation. If parameter issample is true, returns the sample standard deviation. ''' try: if average == None: avg = mean(valueList) else: avg = average variance = 0.0 for v in valueList: diff = v - avg variance = variance + (diff * diff) if issample: divisor = len(valueList)-1 else: divisor = len(valueList) result = math.sqrt(variance / float(divisor)) return result except: sys.stderr.write('TYPE ERROR, call to stddev for list: ' + str(valueList) + '\n') return None def minmax(valueList): ''' Return the ordered pair (minimum, maximum) of valueList as an ordered pair. ''' try: min = valueList[0] max = valueList[0] for v in valueList[1:]: if min is None or ((not v is None) and v < min): min = v if max is None or ((not v is None) and v > max): max = v return((min, max)) except: sys.stderr.write('TYPE ERROR, call to minmax for list: ' + str(valueList) + '\n') return ((None, None)) if __name__ == '__main__': if len(sys.argv) != 3: sys.stderr.write("USAGE: python arffio.py INARFFFILE OUTARFFFILE\n") sys.exit(1) infilename = sys.argv[1] outfilename = sys.argv[2] if os.path.exists(outfilename): sys.stderr.write("ERROR, file " + outfilename + " currently exists.\n") sys.exit(2) attrmap, dataset = readARFF(infilename) writeARFF(outfilename, attrmap, dataset, isDebugMode=True) <file_sep>/csc242/PracticeFiles/company.php <?php function db_connect() { $DB_NAME = "emp"; $DB_HOST = "acad.kutztown.edu"; $DB_USER = "ccarr419"; $DB_PASS = "<PASSWORD>"; global $connection; $connection = mysql_connect($DB_HOST, $DB_USER, $DB_PASS) or die("Cannot connect to $DB_HOST as $DB_USER:" . mysql_error()); mysql_select_db($DB_NAME) or die ("Cannot open $DB_NAME:" . mysql_error()); return $connection; } function db_close() { global $connection; mysql_close($connection); } echo "<form action = 'company.php' method = 'post'> <label>Employee's ID: </label> <input type = 'text' name = 'id' id = 'id'/><br/><br/> <label>Emplyee's Name: </label> <input type = 'text' name = 'name' id = 'name'/><br/><br/> <label>Employee's Salary: </label> <input type = 'text' name = 'salary' id = 'salary'/><br/><br/> <label>Employee's Dept#: </label> <input type = 'text' name = 'dept' id = 'dept'/><br/><br/> <input type = 'submit' value = 'Submit'/> <input type = 'reset' value = 'Cancel'/> </form>"; $id = $_POST['id']; $name = $_POST['name']; $salary = $_POST['salary']; $dept = $_POST['dept']; $employee_info = array(); $employee_info['id'] = $id; $employee_info['name'] = $name; $employee_info['salary'] = $salary; $employee_info['dept'] = $dept; db_connect(); $query = "INSERT INTO products (id, name, sal, dno) VALUES ('$id', '$name', '$salary', '$dept')"; $insert_count = $connection->exec($query); /*foreach($employee_info as $info) { echo "<p>$info</p>"; }*/ /*echo "Employee's ID: " . $id . "<br/>"; echo "Employee's Name: " . $name . "<br/>"; echo "Employee's Salary: " . $salary . "<br/>"; echo "Employee's Dept#: " . $dept . "<br/>";*/ ?><file_sep>/csc402/assignment4/adjacencyListGraph.h /* Author: <NAME> File: adjacencyListGraph.h Class: CSC 402 Date: 10/04/2015 */ #ifndef ADJACENCYLISTGRAPH_H #define ADJACENCYLISTGRAPH_H #include <iostream> #include "graph.h" using namespace std; class adjacencyListGraph : public graph { private: int** aList; int numNodes; public: adjacencyListGraph(int n); ~adjacencyListGraph(); int numberOfVertices() const; int numberOfEdges() const; bool existsEdge(int, int) const; void insertEdge(int, int); void eraseEdge(int, int); int degree(int) const; /* Not a directed graph int inDegree(int) const; int outDegree(int) const; */ void output(ostream&) const; }; #endif <file_sep>/csc520/finalproj/src/com/library/server_layer/AuthenticationServer.java package com.library.server_layer; import com.library.business_layer.field_list.Member; import com.library.business_layer.field_list.InternetAccount; import com.library.business_layer.message_list.MemberHome; import com.library.persistence_layer.*; import java.util.ArrayList; /** * The role of the AuthenticationServer is to communicate between the Home * classes and server UI classes. The functionality of this server includes * logging a member on and off. * SERVER LAYER */ public class AuthenticationServer { private MemberHome mh; /** * Basic constructor for this Object that initializes used Home classes. */ public AuthenticationServer() { mh = new MemberHome(); } /** * Logs the member on by checking the given user number and password * to a matching member found within the memberHome. * @param n String user number * @param p String user password * @param s boolean steal session * @return int session id */ public int logon(String n, String p, boolean s) { Member mem = mh.findByMembershipNumber(n); InternetAccount ia = mh.findAccountByMember(mem); long sessionId = -1; //Check if member with the number exists if(mem != null && ia != null) { //Check if password matches member password if(!p.equals(ia.getPassword())) { return (int) sessionId; } Table accTable = mh.getInternetAccounts(); if(s) { //If the member wants to steal a session for(int i = 0; i < accTable.size(); i++) { InternetAccount acc = (InternetAccount) accTable.get(i); if(acc.getSessionId() > 0) { sessionId = acc.getSessionId(); accTable.setForId(acc.getId(), "sessionId", -1); } } } //Otherwise give member a unique session id if(sessionId == -1) { sessionId = (long) Math.floor(Math.pow(mem.getId(),2) / 16) + (1000 + mem.getId()); } accTable.setForId(ia.getId(), "sessionId", sessionId); } return (int) sessionId; } /** * Logs the member off by finding the session and terminating it. * @param i int session id * @return true if the member successfully logged off, false if not */ public boolean logoff(int i) { if(i <= 0) { return false; } InternetAccount ia = mh.findAccountBySessionId(i); if(ia != null) { Table accTable = mh.getInternetAccounts(); accTable.setForId(ia.getId(), "sessionId", -1); return true; } return false; } /** * Force the update of the AuthenticationServer and all its Homes */ public void update() { mh.update(); } } <file_sep>/csc136/project3a/Array_tst.cpp /*************************************************************** Author: <NAME> Course: CSC 136 020 Assignment: #3a Due Date: October 8, 2013 Filename: Array_tst.cpp Purpose: This program reads a file of Terms into an Array and then performs various operations on it, testing the Array and Term classes. You can evaluate, multiply, add, and print the Terms contained in objects of this type ***************************************************************/ #include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <string> #include "Array.h" #include "term.h" using namespace std; bool openFile(ifstream &file, string &filename);//opens a file void mainMenu(Array &TermList); //holds the main menu loop // void getData(ifstream &file, Array &TermList); // loads Terms from the file ifstream &operator>>(ifstream &file, Array &TermList); // Use operator instead void evaluateTerm(Array &TermList); //evaluates a term for a supplied value void multiplyTerm(Array &TermList); //multiplies a term by a supplied value void addTerm(Array &TermList); //adds a term to the term list bool checkQuit(); //checks if the user wants to quit or not int main() { //Declare variables ifstream file; //input file to ingest string filename; //name of the input file char userChoice; //holds the char the user enters to navigate menus Array TermList; //Get file to open from user cout << "\n\nWelcome to the Array of Term testing program!\n\n"; cout << "Enter the file you would like to open:\n"; cin >> filename; //store the filename for the file the user wants to use //Open the file and if (openFile(file,filename) == false) //If false, close the program { cout << "There was an error opening your file!\nQuiting now\n"; return(0); //exit program } //Start to ingest the terms located in the file // getData(file, TermList); file >> TermList; //Enter main menu loop mainMenu(TermList); //Say goodbye and quit cout << "Goodbye!\n"; return(0); //exit program } bool openFile(ifstream &file, string &filename) { /********************************************************************* * Function name: openFile * Description: Opens a file * Parameters: ifstream file - the file stream * string filename - the file name to open * * Return Value: true if file opened correctly false if file opened incorrectly *********************************************************************/ //Attempt to open file file.open(filename.c_str()); return(file); //Check if opened correctly } //void getData(ifstream &file, Array &TermList) ifstream &operator>>(ifstream &file, Array &TermList) { /********************************************************************* * Function name: getData * Description: Takes data from the file into a Term and appends it to TermList * Parameters: ifstream file - holds the file stream * Array TermList - is an Array of Term. * * Return Value: n/a *********************************************************************/ Term aTerm; while (file >> aTerm) TermList.addTerm(aTerm); file.close(); return(file); } void mainMenu(Array &TermList) { /********************************************************************* * Function name: mainMenu * Description: Prints the main menu and executes functions * Parameters: char userChoice - hold the input character for the menu * Term term - holds the Term object and the term data * * Return Value: n/a *********************************************************************/ char userChoice; //enter menu loop while (userChoice != 'X') { //print menu choices cout << "The list of Terms is Presently: " << TermList << endl; cout << "\nChoose from the following:\n\n"; cout << "E - Evaluate a term\nM - Multiply a term\nA - Add a term\n" << "P - Print the List\nQ - Quit the program\n"; cout << "*********************************\n"; cin >> userChoice; //take in users choice userChoice=toupper(userChoice); // and upper case it //give the user what they want switch (userChoice) { case 'E': evaluateTerm(TermList); //evaluates the term break; case 'M': multiplyTerm(TermList); //multiplys the term by a number break; case 'A': addTerm(TermList); //adds a term to the existing TermList break; case 'P': cout << TermList << endl; //prints the TermList break; case 'Q': if (checkQuit()) //sees whether or not the user wants to quit return; break; default: cout << "Invalid menu choice!!\n"; } } } void evaluateTerm(Array &TermList) { /********************************************************************* * Function name: evaluateTerm * Description: Asks for x and and index and evaluates the requested Term * Parameters: Array &TermList - is the list of Terms * * Return Value: n/a *********************************************************************/ // Input x and which Term, and print the result of evaluating that one Term double x; //x= value to evaluate the term with. double termNum = 0; cout << "\nPlease enter a value for x: "; cin >> x; for(int i = 0; i < TermList.getElements(); i++) termNum += TermList[i](x); cout << termNum << endl << endl; } void multiplyTerm(Array &TermList) { /********************************************************************* * Function name: multiplyTerm * Description: Asks for a scalar and index and multiplies the term at the given index by the scalar * Parameters: Array &TermList - is the list of Terms * * Return Value: n/a *********************************************************************/ // Input the factor and which Term, and print the result of multiplying that one Term double factor; //holds the amount the user wants to multiply by double termNum = 0; cout << "\nPlease enter a factor to multiply by: "; cin >> factor; for(int i = 0; i < TermList.getElements(); i++) TermList[i]*=factor; cout << endl; } void addTerm(Array &TermList) { /********************************************************************* * Function name: addTerm * Description: Adds a term to the term * Parameters: Term term - is the poly object being evaluated * * Return Value: n/a *********************************************************************/ //Declare local variables //Term newTerm; double coeff; //holds the desired coefficient to add int expn; //holds the desired exponent to add cout << "\nEnter the coefficient of the term you wish to add:\n"; cin >> coeff; //store the value in coeff cout << "Enter the exponent of the term you wish to add:\n"; cin >> expn; //stores the value in expn cout << endl; TermList.addTerm(coeff, expn); } bool checkQuit() { /********************************************************************* * Function name: checkQuit * Description: Checks if the user wants to actually quit or not * Parameters: char userChoice - holds what the user wants to do in the menu * * Return Value: n/a *********************************************************************/ char userChoice; cout << "Do you really want to quit? (y/n)\n"; //askes if the user really wants to quit cin >> userChoice; //store value in userChoice return (toupper(userChoice)=='Y'); } <file_sep>/csc402/project1/paths.cpp /* * Filename: paths.cpp * Date Created: 09/06/2014 * Author: <NAME> * Class: CSIT 402 (Data Structures II) * Instructor: Dr. Spiegel * Purpose: This file uses the Matrix class to create the ideas of * graphs, paths and cost. The user will read a file into the * Matrix object and will select a starting point and * destination. The program will then find all possible path * ways from the start vertex to destination vertex in the * order of cost. */ #include <iostream> #include <fstream> #include <vector> #include <string> #include <map> #include "Matrix.h" using namespace std; /* * Function Name: startUp * Parameters: ifstream& (import/export) - file to be read * string& (import only) - name of the file * Return Value: void * Purpose: Calls all necessary functions to open the file, display * the menu and let the user take control from there */ void startUp(ifstream&, string&); /* * Function Name: openFile * Parameters: ifstream& (import/export) - file to be read * string& (import only) - name of the file to open * Return Value: true - if file exists and could be opened * false - file could not be found or opened * Purpose: Attempts to open a file from the given file name * string argument and returns true or false based on * the results */ bool openFile(ifstream&, string&); /* * Function Name: readIntoMatrix * Parameters: ifstream& (import/export) - file to read into matrix * Matrix<int>& (import/export) - Matrix object to hold data * Return Value: void * Purpose: Uses the Matrix class' insertion operator (>>) to insert * data from a given file */ void readIntoMatrix(ifstream&, Matrix<int>&); /* * Function Name: getFileName * Parameters: none * Return Value: string - file name entered by the user * Purpose: Gets file name from user to later test if it can be opened */ string getFileName(); /* * Function Name: chooseOption * Parameters: Matrix<int>& (import only) - needed for sub-functions * Return Value: true - keep menu going (user did not quit) * false - user decided to quit (end loop) * Purpose: Provides the switch statement so user can choose his/her * option and be directed towards the correct function * or terminate the program */ bool chooseOption(Matrix<int>&); /* * Function Name: menu * Parameters: none * Return Value: void * Purpose: Displays the menu options for the user */ void menu(); /* * Function Name: findPath * Parameters: * Return Value: * Purpose: */ void findPaths(Matrix<int>&); void findPathsHelper(int, int, int, int, int, int, int, int ,int, int, int, vector<int>, vector<int>, map<int, vector<vector<int> > >&, Matrix<int>&); bool checkDup(vector<int>, int); /* * Function Name: displayMatrix * Parameters: Matrix<int>& (import only) - Matrix to display * Return Value: void * Purpose: Displays the Matrix object to the screen by the use of * the class' (<<) operator */ void displayMatrix(Matrix<int> &mx); /* * Check for command-line arguments or resume normally * Only difference is program asks for file name is it not entered via * command-line argument */ int main(int argc, char *argv[]) { ifstream inf; string fileName; //Name of the file to be used if(argc > 1) //If there was an input on the command-line { fileName = argv[1]; //Use command-line argument as file name startUp(inf, fileName); return 0; } fileName = getFileName(); //Non command-line file name enter startUp(inf, fileName); return 0; } /* * Sets the course of the program no matter if a command-line argument is * entered or not. Calls the functions to open the file and lets the user * select the options he or she wants to use from the menu */ void startUp(ifstream &inf, string &fileName) { Matrix<int> mx; if(openFile(inf, fileName)) { //File exists: transfer data into matrix readIntoMatrix(inf, mx); while(chooseOption(mx)); //Keep menu open until user quits } else //File does not exist or exists and cannot be opened cout << "Could not open file!\n"; } /* * Asks the user for the name of the file to use and returns the string */ string getFileName() { string fileName; cout << "\nPlease enter the file name: "; cin >> fileName; return fileName; } /* * Attempts to open a file from the give file name, if the file does not * exists or exists and fails to open, the function will return false. * Otherwise the function will return true */ bool openFile(ifstream &inf, string &fileName) { inf.open(fileName.c_str()); if (inf.fail()) //If file does not exist. return false; else //If file does exist. return true; } /* * By the use of the overloaded insertion operator (>>) in the Matrix class * the file given is inserted directly into the Matrix object */ void readIntoMatrix(ifstream &inf, Matrix<int> &mx) { inf >> mx; } /* * Displays the Matrix object to the screen by the use of the overloaded * (<<) operator in the Matrix class */ void displayMatrix(Matrix<int> &mx) { cout << mx << endl; } /* * User enters a choice and a switch statement matches the choice up to * its correct sub-function to carry out the task */ bool chooseOption(Matrix<int> &mx) { char choice; menu(); cin >> choice; switch(choice) { case '1': //Find a path between two vertices findPaths(mx); break; case '2': //Display the matrix imported from file displayMatrix(mx); break; case '3': //Quit return false; default: //User entered something other than 1-3 cout << "Sorry, I cannot understand \"" << choice << "\"\n\n"; break; } return true; } /* * Displays the options for the user to choose */ void menu() { cout << "1.)\tFind path\n"; cout << "2.)\tDisplay matrix\n"; cout << "3.)\tQuit\n\n"; cout << "Choose an option: "; } void findPaths(Matrix<int> &mx) { map<int, vector<vector<int> > > path; vector<int> current_path, path_history; int f_idx, l_idx, row, col, current_pos, cost; int row_brkpt, col_brkpt, itr_pos; unsigned start, end; cout << "Enter starting vertex: "; cin >> start; cout << "Enter destination vertex: "; cin >> end; f_idx = 0; l_idx = mx.getColumns()-1; row = start; col = f_idx; current_pos = mx.get(row, col); row_brkpt = start; col_brkpt = f_idx; itr_pos = f_idx; cost = 0; findPathsHelper(row, col, start, end, cost, row_brkpt, col_brkpt, f_idx, l_idx, current_pos, itr_pos, current_path, path_history, path, mx); } void findPathsHelper(int row, int col, int start, int end, int cost, int row_brkpt, int col_brkpt, int f_idx, int l_idx, int current_pos, int itr_pos, vector<int> current_path, vector<int> path_history, map<int, vector<vector<int> > > &path, Matrix<int> &mx) { if((((col == l_idx) && checkDup(current_path, current_pos)) || ((col == l_idx) && (current_pos == 0))) || (((col == f_idx) && checkDup(current_path, current_pos)) || ((col == f_idx) && (current_pos == 0)))) { if(itr_pos == l_idx) return; } if(current_path.empty()) { if(!path_history.empty()) current_path = path_history; else { current_path.push_back(start); path_history.push_back(start); } } current_pos = mx.get(row, col); if(current_pos != 0) { current_path.push_back(current_pos); cost += current_pos; if(col_brkpt == itr_pos) { if(col == end) { path[cost].push_back(current_path); current_path.clear(); cost = 0; if( itr_pos++; row = start; col = itr_pos; findPathsHelper( else { if( } } bool checkDup(vector<int> path_to_check, int current_pos) { for(vector<int>::iterator it = path_to_check.begin(); it != path_to_check.end(); ++it) if(current_pos == *it) return true; return false; } <file_sep>/csc421/assignment5/src/com/yahtzee/client/GreetingService.java package com.yahtzee.client; import com.yahtzee.client.playerStats; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /* * Author: <NAME> * File Name: GreetingService.java * File Package: com.yahtzee.client * File Version: 1.0 * File Date: 12/04/2017 * Due Date: 12/13/2017 * Assignment: #5 * Professor: Dr. <NAME> * Course #: CSC421 * Course Name: Web-Based Software Design & Development * University: Kutztown University * Major: CSCM Software Development */ /** * The client-side stub for the RPC service. */ @RemoteServiceRelativePath("greet") public interface GreetingService extends RemoteService { /** * Checks to see if it is the calling player's turn. * @param i the player who is calling * @return true if it is the player's turn, false if not */ public Boolean getUpdate(int i); /** * Retrieves the stats of the other player for the calling player. * @return the stats of the other player */ public playerStats confirmUpdate(); /** * Sets the server copy of player stats to the calling player's stats. * @param ps the calling player's stats */ public void setStats(playerStats ps); /** * Start the game by only allowing two players at a time. Inform all players * who enter while there are already two players playing that they game * already has players. * @return 1 for player#1, 2 for player#2, 0 for game full */ public Integer start(); /** * Restart the game and reinitialize variables. Allow other users to play. */ public void quit(); } <file_sep>/csc570/README.txt CSC 570 - Independent Study and/or Projects in Computer Science Dr. <NAME> Kutztown Univerity Spring 2018 Topic: Data Analysis/Data Mining with the use of TensorFlow This course involves individual independent study in some area of computer science under the direction of a CS group staff member. This study can be made in any of the areas of analog and hybrid computers, artificial intelligence, automate theory, business information systems, computer-aided design, computer-assisted instructions, computer graphics, computer mechanisms and devices, computer systems, computer telecommunication, computer typesetting, information retrieval, linguistic processing, mechanical languages, numerical analysis, programming theory, or switching systems and logical design, and others. <file_sep>/csc402/inclassprograms/templateClass1.cpp #include <iostream> using namespace std; template<class k, class v> class Pair { public: k firstItem; v secondItem; void print() { cout << firstItem << "\t" << secondItem << endl; } bool operator == (const Pair &aPair) { return (firstItem == aPair.firstItem && secondItem == aPair.secondItem); } }; int main () { Pair<int, string> p1; p1.firstItem = 1; p1.secondItem = "csc"; p1.print(); Pair<string, string> p2; p2.firstItem = "csc"; p2.secondItem = "402"; p2.print(); return 0; } <file_sep>/csc135/multipleOrders_ChristianCarreras.cpp //This program uses a while loop and a nested for loop to //calculate the subtotal of meals for the number of people //at the table. #include <iostream> using namespace std; int main() { float sum, meal, subtotal; int people, num, counter; sum = 0; cout << "\nHow many people are at the table?: "; cin >> people; while(people!=0) { for(counter=0; counter < people; counter++) { cout << "Enter the price of the meal: $"; cin >> meal; sum+=meal; } cout << "\nSubtotal: $" << sum << endl; cout << "\nHow many people are at the table?: "; cin >> people; sum=0; } cout << "Bye!\n"; return 0; } <file_sep>/csc520/finalproj/src/com/library/business_layer/message_list/ReservationStateHome.java package com.library.business_layer.message_list; import com.library.business_layer.field_list.Collectable; import com.library.business_layer.field_list.Concluded; import com.library.business_layer.field_list.Displayable; import com.library.business_layer.field_list.NeedingRenewal; import com.library.business_layer.field_list.Notifiable; import com.library.business_layer.field_list.Reservation; import com.library.business_layer.field_list.Waiting; import com.library.persistence_layer.*; import java.util.ArrayList; import java.sql.Timestamp; import java.util.Date; /** * ReservationStateHome serves as a way to access the all Reservation states * Tables. Thus it also serves as an accessor to the table's element's * attributes. Another purpose of ReservationStateHome is to create and add any * new entries to any of the Reservation states Tables. * BUSINESS LAYER CLASS * @see com.library.business_layer.field_list.Collectable * @see com.library.business_layer.field_list.Concluded * @see com.library.business_layer.field_list.Displayable * @see com.library.business_layer.field_list.NeedingRenewal * @see com.library.business_layer.field_list.Notifiable * @see com.library.business_layer.field_list.Waiting */ public class ReservationStateHome { private Table colTable, conTable, disTable, neeTable, notTable, waiTable; /** * Basic constructor for ReservationStateHome that instantiates home's Tables. */ public ReservationStateHome() { colTable = new DataSchema.CollectableReservationTable(); conTable = new DataSchema.ConcludedReservationTable(); disTable = new DataSchema.DisplayableReservationTable(); neeTable = new DataSchema.NeedingRenewalReservationTable(); notTable = new DataSchema.NotifiableReservationTable(); waiTable = new DataSchema.WaitingReservationTable(); } /** * Gets the CollectableReservationTable as a whole. * @return DataSchema.CollectableReservationTable */ public DataSchema.CollectableReservationTable getCollectables() { return (DataSchema.CollectableReservationTable) colTable; } /** * Gets the ConcludedReservationTable as a whole. * @return DataSchema.ConcludedReservationTable */ public DataSchema.ConcludedReservationTable getConcluded() { return (DataSchema.ConcludedReservationTable) conTable; } /** * Gets the DisplayableReservationTable as a whole. * @return DataSchema.DisplayableReservationTable */ public DataSchema.DisplayableReservationTable getDisplayables() { return (DataSchema.DisplayableReservationTable) disTable; } /** * Gets the NeedingRenewalReservationTable as a whole. * @return DataSchema.NeedingRenewalReservationTable */ public DataSchema.NeedingRenewalReservationTable getNeedingRenewals() { return (DataSchema.NeedingRenewalReservationTable) neeTable; } /** * Gets the NotifiableReservationTable as a whole. * @return DataSchema.NotifiableReservationTable */ public DataSchema.NotifiableReservationTable getNotifiables() { return (DataSchema.NotifiableReservationTable) notTable; } /** * Gets the WaitingReservationTable as a whole. * @return DataSchema.WaitingReservationTable */ public DataSchema.WaitingReservationTable getWaiting() { return (DataSchema.WaitingReservationTable) waiTable; } /** * Creates a new Collectable and appends it to the CollectableReservationTable. * @param d Date date notified * @param resId int reservation id * @return the newly created Collectable */ public Collectable createCollectable(Date d, int resId) { Collectable newCollectable = new Collectable(colTable.nextKey(), d, resId); colTable.append(newCollectable); return newCollectable; } /** * Creates a new Concluded and appends it to the ConcludedReservationTable. * @param reason String reason for conclusion * @param resId int reservation id * @return the newly created Concluded */ public Concluded createConcluded(String reason, int resId) { Concluded newConcluded = new Concluded(conTable.nextKey(), reason, resId); conTable.append(newConcluded); return newConcluded; } /** * Creates a new Displayable and appends it to the DisplayableReservationTable. * @param reason String reason for termination * @param resId int reservation id * @return the newly created Displayable */ public Displayable createDisplayable(String reason, int resId) { Displayable newDisplayable = new Displayable(disTable.nextKey(), reason, resId); disTable.append(newDisplayable); return newDisplayable; } /** * Creates a new NeedingRenewal and appends it to the NeedingRenewalReservationTable. * @param d Date renewal deadline date * @param resId int reservation id * @return the newly created NeedingRenewal */ public NeedingRenewal createNeedingRenewal(Date d, int resId) { NeedingRenewal newNeedingRenewal = new NeedingRenewal(neeTable.nextKey(), d, resId); neeTable.append(newNeedingRenewal); return newNeedingRenewal; } /** * Creates a new Notifiable and appends it to the NotifiableReservationTable. * @param d Date date book put aside * @param resId int reservation id * @return the newly created Notifiable */ public Notifiable createNotifiable(Date d, int resId) { Notifiable newNotifiable = new Notifiable(notTable.nextKey(), d, resId); notTable.append(newNotifiable); return newNotifiable; } /** * Creates a new Waiting and appends it to the WaitingReservationTable. * @param d Date last renewal date * @param resId int reservation id * @return the newly created Waiting */ public Waiting createWaiting(Date d, int resId) { Waiting newWaiting = new Waiting(waiTable.nextKey(), d, resId); waiTable.append(newWaiting); return newWaiting; } /** * Tests whether the Reservation is Collectable or not. * @param r Reservation * @return true if the Reservation is Collectable, false if not */ public boolean isCollectable(Reservation r) { if(colTable.selectWhere("reservationId", r.getId()).isEmpty()) { return false; } else { return true; } } /** * Tests whether the Reservation is Concluded or not. * @param r Reservation * @return true if the Reservation is Concluded, false if not */ public boolean isConcluded(Reservation r) { if(conTable.selectWhere("reservationId", r.getId()).isEmpty()) { return false; } else { return true; } } /** * Tests whether the Reservation is Displayable or not. * @param r Reservation * @return true if the Reservation is Displayable, false if not */ public boolean isDisplayable(Reservation r) { if(disTable.selectWhere("reservationId", r.getId()).isEmpty()) { return false; } else { return true; } } /** * Tests whether the Reservation is NeedingRenewal or not. * @param r Reservation * @return true if the Reservation is NeedingRenewal, false if not */ public boolean isNeedingRenewal(Reservation r) { if(neeTable.selectWhere("reservationId", r.getId()).isEmpty()) { return false; } else { return true; } } /** * Tests whether the Reservation is Notifiable or not. * @param r Reservation * @return true if the Reservation is Notifiable, false if not */ public boolean isNotifiable(Reservation r) { if(notTable.selectWhere("reservationId", r.getId()).isEmpty()) { return false; } else { return true; } } /** * Tests whether the Reservation is Waiting or not. * @param r Reservation * @return true if the Reservation is Waiting, false if not */ public boolean isWaiting(Reservation r) { if(waiTable.selectWhere("reservationId", r.getId()).isEmpty()) { return false; } else { return true; } } /** * Force the update of all ReservationStateHome Tables. */ public void update() { colTable.updateList(); conTable.updateList(); disTable.updateList(); neeTable.updateList(); notTable.updateList(); waiTable.updateList(); } }<file_sep>/csc520/finalproj/src/com/library/business_layer/message_list/CatalogedBookDetailsHome.java package com.library.business_layer.message_list; import com.library.business_layer.field_list.CatalogedBookDetails; import com.library.business_layer.field_list.CatalogedBook; import com.library.persistence_layer.*; import java.util.ArrayList; /** * CatalogedBookDetailsHome serves as a way to access the * CatalogBookDetailsTable. Thus it also serves as an accessor to the table's * element's attributes. Another purpose of CatalogedBookDetailsHome is to * create and add any new entries to the CatalogedBookDetailsTable. * BUSINESS LAYER CLASS * @see com.library.business_layer.field_list.CatalogedBookDetails */ public class CatalogedBookDetailsHome { private Table cbdTable; private Table cbTable; /** * Basic constructor for CatalogedBookDetailsHome that instantiates home's Tables. */ public CatalogedBookDetailsHome() { cbdTable = new DataSchema.CatalogedBookDetailsTable(); cbTable = new DataSchema.CatalogedBookTable(); } /** * Gets the CatalogedBookDetailsTable as a whole. * @return DataSchema.CatalogedBookDetailsTable */ public DataSchema.CatalogedBookDetailsTable getCatalogedBookDetails() { return (DataSchema.CatalogedBookDetailsTable) cbdTable; } /** * Gets a list of all author arrays for every CatalogedBookDetails * @return ArrayList of String arrays containing authors */ public ArrayList<String[]> findAuthors() { ArrayList<String[]> authorList = new ArrayList<>(); for(CatalogedBookDetails cbd : getCatalogedBookDetails().selectAll()) { authorList.add(cbd.getAuthors()); } return authorList; } /** * Finds CatalogedBookDetails by its primary key identifier. * @param id int * @return CatalogedBookDetails */ public CatalogedBookDetails findByPrimaryKey(int id) { return (CatalogedBookDetails) cbdTable.selectId(id); } /** * Creates a new CatalogedBookDetails and appends it to the CatalogedBookDetailsTable. * @param edit String book edition * @param auth String[] book authors * @param desc String book description * @return the newly created CatalogedBookDetails */ public CatalogedBookDetails create(String edit, String auth[], String desc) { CatalogedBookDetails newCatalogedBookDetails = new CatalogedBookDetails(cbdTable.nextKey(), edit, auth, desc); cbdTable.append(newCatalogedBookDetails); return newCatalogedBookDetails; } /** * Finds CatalogedBookDetails for a given CatalogedBook id. * @param id cataloged book to find details for * @return CatalogedBookDetails for CatalogedBook or null if does not exist */ public CatalogedBookDetails findByCatalogedBookId(int id) { ArrayList<CatalogedBook> cb = cbTable.selectWhere("id", id); if(!cb.isEmpty()) { //Make sure a CatalogedBook exists with that id CatalogedBook book = cb.get(0); //ArrayList will only by one entry ArrayList<CatalogedBookDetails> cbd = cbdTable.selectWhere("id", book.getDetailsId()); if(!cbd.isEmpty()) { return cbd.get(0); } //Make sure details exist } return null; //A CatalogedBook with that id does not exist } /** * Force the update of all CatalogedBookDetailsHome Tables. */ public void update() { cbdTable.updateList(); cbTable.updateList(); } }<file_sep>/csc548/Project2/oohs.py ''' Author: <NAME> Project Name: Optimal Overwatch™ Hero Selection (OOHS) File Name: oohs.py File Date: 04/21/2017 Professor: <NAME> Semester: SPRING 2017 Course: CSC 548 Artificial Intelligence II Institution: Kutztown University of Pennsylvania Purpose: The purpose of this project is to create a machine-learning algorithm that is able to successfully predict the success rate of an enemy hero compared to the player's pick. The algorithm will take the enemy's and player's skill into account and compare them with training data. Skills the algoritm will look at are eliminations/min, kill/death ratio, accuracy, damage/min, damage blocked/min, healing/min, and critical hits/min. By using a linear regression method, the algorithm will predict the success rate of new data based on training data and their success rates. Overwatch™ is an online, team-based, first-person shooter that heavily relies on picking the right hero to fill a role or counter an enemy hero. I chose this project as I enjoy playing this game and I was curious if I could create an algorithm that would choose the best hero for me given the circumstances of the current match and players. This file assumes that you are using the Spyder IDE as a python environment and that your working directory is the spyder-py3 folder. If you are not using the Spyder IDE, you must change the code to match your working directory. Alternatively, you can create the spyder-py3 folder in the "C:/Users/%USERNAME%/" directory if you are using Windows. If you are using Linux or Mac, create a spyder-py3 folder in your user directory or change the code to fit your needs. You have full permission to edit the code and upload it anywhere as long as it for academic or self-use only. Just be sure to credit me if you do upload/post it anywhere. Code is as is and has absolutely NO warranty. Future Additions: - Real-life training data made from player v. player. - All heroes will be taken into account - Algorithm will take game-map into account - Algorithm will take game-mode into account - See if other stats not taken into account affect decision Data and averages (besides success rates) were all collected from https://masteroverwatch.com I do not own this data and all data and is for academic/self-use use only. All trademarks referenced herein are the properties of their respective owners. © MasterOverwatch.com 2017. All rights reserved. © 2017 Blizzard Entertainment, Inc. All rights reserved. ''' import pandas # Used for organizing and accessing data import pickle # Used for packaging and un-packaging data import os.path as path # Used for accessing files at a certain location from pandas.tools.plotting import scatter_matrix # Used for scatter-matix import matplotlib.pyplot as plt # Used in showing graphs/visible data from sklearn import model_selection # Used to split dataset into multiple sets from sklearn.linear_model import LinearRegression # Main algorithm for ml from sklearn import preprocessing # Used in label encoding import numpy as np # Used in score calculation from datetime import datetime # Used in random seed generation import random # Used in random seed generation # Path to the data file. If your working directory is different or you are not # using the Spyder IDE change to: # dataPath = ("PATH") where PATH is the file's location dataPath = path.expanduser("~/.spyder-py3/OOHSData.txt") # The headers for each column in the dataset columnNames = ['eHero', 'eElimPerMin', 'eKDRatio', 'eAccuracy', 'eDamPerMin', 'eBlockPerMin', 'eHealPerMin', 'eCritPerMin', 'pHero', 'pElimPerMin', 'pKDRatio', 'pAccuracy', 'pDamPerMin', 'pBlockPerMin','pHealPerMin', 'pCritPerMin', 'SuccessRate'] # The list of heroes currently used in the algorithm and dataset heroList = ["Ana", "Bastion", "Lucio", "McCree", "Mei", "Reaper", "Roadhog", "Soldier:76", "Torbjorn", "Zarya", "Zenyatta"] # This function takes any data as a first parameter and pickles it into a .pkl # file for later use. The name of the new file is given in the second param. def stoDB(db, fn): fn = open(fn+'.pkl','wb') pickle.dump(db,fn) fn.close() # This function tries to find a .pkl file by the name given in the first param. # If there is such a file, the file is unpickled and returned. If there is no # such file, None is returned instead. def getDB(fn): # Check if the file exists in the user's directory # If your working directory is different or you are not # using the Spyder IDE change to: # path.isfile("PATH"+fn+".pkl") where PATH is the file's location if (path.isfile(path.expanduser("~/.spyder-py3/"+ fn + ".pkl"))): dbFile = open(fn+'.pkl','rb') db = pickle.load(dbFile) # Unpickle and load the dataset dbFile.close() return db else: # File does not exist return None # This function loads the dataset to use for the machine-learning algorithm. # If the dataset already has been pickled, retrieve it for use. Otherwise, # generate a new dataset from the data file to use. def initialize(): dataset = getDB("oohs") if (dataset is None): # .pkl does not exist, create one dataset = pandas.read_csv(dataPath, names=columnNames) stoDB(dataset, "oohs") print("Saved dataset to new pkl file.\n") return dataset # This function prints the whole dataset in its entirety instead of printing # a subset of the data (aka the head and tail of the dataset) def print_full(): dataset = initialize() pandas.set_option('display.max_rows', len(dataset)) print(dataset) pandas.reset_option('display.max_rows') #reset to normal # Create a box plot depicting the dataset def boxPlot(): dataset = initialize() dataset.plot(kind='box', subplots=True, layout=(4,4), figsize=(12,12), sharex=False, sharey=False) plt.show() # Create a histogram bar graph depicting the dataset def histogram(): dataset = initialize() dataset.hist(layout=(4,4), figsize=(12,12), xrot=90, xlabelsize=8) plt.show() # Create a scatter plot matrix depicting the dataset def scatterMatrix(): dataset = initialize() scatter_matrix(dataset, figsize=(24,24)) plt.show() # This function turns all non-numerical data in a dataset into integers # All references of a hero name in the dataset will be turned into a # corresponding integer. e.g. Ana will turn to 0, Bastion to 1, etc. def encodeLabels(array): le = preprocessing.LabelEncoder() # LabelEncoder will do all the work le.fit(heroList) # Tell le to change any hero name to its int value array[:,0] = le.transform(array[:,0]) # Transform enemy heroes to ints array[:,8] = le.transform(array[:,8]) # Transform player heroes to ints return le # This function prints the results of a prediction. Print only, no calculation. def printResults(playerHero, enemyHero, pred, y): print("Matchup: " + playerHero + " vs " + enemyHero + "; Prediction: ", end='') print(pred, end='') # Print the actual value of the value being predicted print("%; Actual value: ", end='') print(round(y,4)*100, end='') print("%") # This function prints the mean squared error and variance score of a # prediction compared to it's actual values. Calculation is done inside print. def printStats(regr, X_validation, Y_validation): print("Mean squared error: %.2f" % np.mean((regr.predict(X_validation) - Y_validation) ** 2)) print('Variance score: %.2f' % regr.score(X_validation, Y_validation)) # This function predicts the outcome (aka success rate) of the player hero # against an enemy hero. The method used to elicit a prediction was a linear # regression. First the algorithm will train with a portion of the dataset # then it will try to predict the values of the rest of the dataset. It will # then print the results so the user can easily understand what happened. def makePredictions(X_train, Y_train, X_validation, Y_validation, le): regr = LinearRegression() regr.fit(X_train, Y_train) # Train with a portion of the dataset predictions = regr.predict(X_validation) # Then predict the remaining # Go through all the items in the testing dataset and print the results for k in range(0, X_validation.shape[0]): # Change back to hero names instead of printing ints in results enemyHero = le.inverse_transform(X_validation[k][0]) playerHero = le.inverse_transform(X_validation[k][8]) pred = round(predictions[k],4)*100 # Change from floating to percent printResults(playerHero, enemyHero, pred, Y_validation[k]) print('') printStats(regr, X_validation, Y_validation) # Print algorithm score # This function starts the process of creating needed variables, splitting # the dataset into training and testing data, training, and then making # predictions. All the functionality of this machine-learning algorithm # besides displaying dataset graphs is presented in this function. def start(): # Create pseudo-random seed from current time to ensure no test is the same seed = random.seed(datetime.now()) validation_size = 0.20 # Percent to split from the dataset to testing data dataset = initialize() # Get or create the dataset # Make an array from the dataset so it can be encoded and split array = dataset.values le = encodeLabels(array) # Change string data in the dataset to ints X = array[:,0:16] # Get all rows from columns 0-15 Y = list(array[:,16]) # Get all rows from column 16 # Split the dataset into training and testing data X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split( X, Y, test_size=validation_size, random_state=seed) # Make predictions based on the newly split data after training makePredictions(X_train, Y_train, X_validation, Y_validation, le) <file_sep>/csc421/assignment5/README.txt * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Yahtzee © 2017 Hasbro, Inc. * Version 5.0 * <NAME> BS Computer Science * Kutztown University of Pennsylvania * * Official Rules: * https://www.hasbro.com/common/instruct/Yahtzee.pdf * * JavaDocs Link: * http://csitrd.kutztown.edu/~ccarr419/csc421/assignment5/ * * - - - - - - - - - - MY DESIGN CHOICES - - - - - - - - - - * * For this project I made a GWT application through a * Unix environment with the help of a tomcat server to * unpack my projects' war onto the web. My project * was extended from the previous version by making the * necessary additions specified in the project guidelines. * The main changes between this version and the previous * version is the addition of a server-based two-player * network game support. Minor multimedia additions were * added such as the mute button if the player wants to * turn off all sound. I tried not to make too many visual * changes compared to the previous versions so I could * keep things simple and put more effort into the server. * The only difference with this visually is the addition * of a DialogBox with a single button that is displayed * when it is not the player's turn. The button will check * with the server and see if it is the player's turn. If * it is the player's turn, it will transition to that * player's turn. Otherwise the player will have to keep * waiting until the other player is done with their turn. * Scores are added to the scoresheets after each player's * round and a winner, loser, or tie game is announced * when both players finish their scoresheet. To use * the two-player version simply accept the first prompt * given at page load. To use the one-player version, * cancel the first prompt at page load. To restart the * game just refresh the browser. If there are two players * playing the two player server-based game already, all * incoming players will default to the one player version. * * - - - - - - - - - - - HOW TO PLAY - - - - - - - - - - - - * * On page load, the player or players will be prompted * with the choice of a one-player or two-player game. * If the one-player version is picked, there will be a * singular checksheet. If the two-player version is * checked, there will be two checksheets along with * text that displays which player's turn it is. If there * are two players already playing the two player game * the player will default to a one player game. * * When the game begins, the game starts with an initial * roll. There is no need to manually start the game. The * same rule applies to once a category is picked. Once * a category is picked the game proceeds to the next * round and/or player turn with an initial roll. * * The player can select dice to keep by simply clicking * the dice they want to keep. The player can unkeep the * dice they kept by clicking on the kept dice again. * White dice signify unkept dice. Yellow/cream colored * dice signify kept dice. * * The roll button will roll the dice. There is a maximum * of three rolls per round. With the first roll being * rolled automatically the player will only be able to * roll twice before reaching the roll limit. Once the * roll limit is reached they will no longer be able to * roll until a category is picked. If the player has not * picked any dice to keep before clicking the roll button * the player will be shown a prompt if they wish to * continue with the roll without keeping. * * At any point during a round the player may select a * category to fill for the round. The score depends * on the current dice configuration. To select a score * the player must click the button horizontally across * from the category they wish to fill. The player will * be prompted everytime in the case of misclicks. Once a * category is picked it cannot be unpicked so make * sure to choose wisely. Players will be forced to choose * a category once they use all their rolls. Categories * that were previously picked will be crossed out. * * Scores for the player can be found in the scoresheet * on the left side of the webpage. Scores will be * automatically injected into the scoresheet once a * category is picked with bonuses and totals being * updated automatically as well. If there is more than * one player, individual scoresheets can be selected * by clicking on the specific player's tab. * * The "How To Play" button will bring you to this readme * file that will hold information to help you play. * * There is no game reset button once the game has reached * its natural end. To reset the game from the beginning * please refresh your browser. * * A winner will be announced at the end of the game if * there is more than one player. * * Players will not be able to do anything until it is * their turn, be patient and wait for the other player. * Waiting player's screens will be locked to ensure this. * * - - - - - - - - - - - WORKS CITED - - - - - - - - - - - * * Images: * dice1.jpg, dice2.jpg, dice3.jpg, dice4.jpg, dice5.jpg, dice6.jpg: * http://clipart-library.com/clipart/pT7KbK78c.htm * *Note* Picked versions were made from the set of the images above * Yahtzee.png: * https://en.wikipedia.org/wiki/Yahtzee * soundOn.png: * http://www.iconarchive.com/show/windows-8-icons-by-icons8/Media-Controls-Volume-Up-icon.html * soundOff.png: * http://www.iconarchive.com/show/windows-8-icons-by-icons8/Media-Controls-Mute-icon.html * * Sounds: * diceThrow01.wav: * https://www.mediamusicnow.co.uk/royalty-free-sound-effects/casino/poker-cards-dice/dice-throw-five-dice-on-wood-table-01.aspx * diceThrow02.wav: * https://www.mediamusicnow.co.uk/royalty-free-sound-effects/casino/poker-cards-dice/dice-throw-five-dice-on-wood-table-03.aspx * diceThrow03.wav: * https://www.mediamusicnow.co.uk/royalty-free-sound-effects/casino/poker-cards-dice/dice-throw-five-dice-on-wood-table-04.aspx * pickCategory.wav: * https://www.youtube.com/watch?v=ZNjSEyd4w-w * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <file_sep>/csc136/project2/makefile CC = /opt/csw/gcc4/bin/g++ CFLAGS = -Wall p2: poly_tst.o poly.o $(CC) $(CFLAGS) -o p2 poly_tst.o poly.o poly_tst.o: poly_tst.cpp poly.h $(CC) $(CFLAGS) -c poly_tst.cpp poly.o: poly.cpp poly.h $(CC) $(CFLAGS) -c poly.cpp clean: rm -rf *.o <file_sep>/sideprojects/games/random/makefile cc=/opt/csw/gcc4/bin/g++ random: random.cpp $(cc) -std=gnu++0x random.cpp -o random <file_sep>/csc242/Project/createaccount.php <?php session_start(); $loggedin = $_SESSION['loggedin']; /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/createaccount.php Course: CSC 242 - Fall 2013 */ echo "<html xmlns = 'http://www.w3.org/1999/xhtml'> <head> <title> Create An Account </title> <script type = 'text/javascript'> <!-- //Check if account fields are legitimate function account() { //Variables var fname = document.getElementById('fname').value; //first name var lname = document.getElementById('lname').value; //last name var email = document.getElementById('email').value; //email var pass1 = document.getElementById('pass1').value; //<PASSWORD> var pass2 = document.getElementById('pass2').value; //confirm password var add1 = document.getElementById('add1').value; //address 1 var add2 = document.getElementById('add2').value; //address 2 var city = document.getElementById('city').value; //city var state = document.getElementById('state'); //state var state = state.options[state.selectedIndex].value; var zip = document.getElementById('zip').value; //zip code var phone = document.getElementById('phone').value; //phone number //Check to make sure none of the required fields are empty //Also check that a state is selected if(fname.length < 1 || lname.length < 1 || email.length < 1 || pass1.length < 1 || pass2.length < 1 || add1.length < 1 || city.length < 1 || zip.length < 1 || state == 'none') { window.alert('Please fill out all required fields'); } //Check to make sure that the password and confirm password fields match else if(pass1 != pass2) { window.alert('Your passwords do not match'); } //Make user have a legitimate password that is not too long for the database else if ((pass1.length < 5) || (pass1.length > 15)) { window.alert('Your password must be between 5 and 15 characters long'); } //Check to make sure the email entered is legitimate //Check is @ is present, along with a . and com, net, org etc. else if(email.indexOf('@') == -1 || email.indexOf('.') == -1 || email.length > 50 || (email.indexOf('com') == -1 && email.indexOf('gov') == -1 && email.indexOf('org') == -1 && email.indexOf('edu') == -1 && email.indexOf('net') == -1 && email.indexOf('mil') == -1) || email.length < 7) { window.alert('Please enter a valid email address'); } //Check if name contains a number else if(isNaN(fname) == false || isNaN(lname) == false) { window.alert('Your name cannot contain numbers'); } //Check if first name is too long for database else if(fname.length > 20) { window.alert('Your first name is too long'); } //Check if last name is too long for database else if(lname.length > 25) { window.alert('Your last name is too long'); } //Check if address is too long for database else if(add1.length > 50 || add2.length > 50) { window.alert('That address is too long'); } //Check if city contains a number else if(isNaN(city) == false) { window.alert('City name cannot contain numbers'); } //Check if city name is too long for database else if(city.length > 50) { window.alert('City name is too long'); } //Check to make sure the zip code entered is legitimate else if(isNaN(zip) == true || zip.length != 5) { window.alert('Please enter a valid zip code'); } //Check to make sure if a phone number is entered, it is legitimate else if(phone.length > 0 && (phone.length < 10 || phone.length > 11)) //Standard 555-555-5555 & 1800-555-5555 { window.alert('Please enter a valid phone number with no dashes'); } //Check to make sure if a phone number is entered, it is legitimate else if(phone.length > 0 && (isNaN(phone) == true)) //Make sure letters are not entered { window.alert('Please enter a valid phone number with no dashes'); } //Everything is filled out and correct else { window.alert('Thank you for creating an account! Now please continue to log in!'); document.forms['useraccount'].submit(); } } //--> </script><noscript>Cannot Run JavaScript!</noscript> <link rel = 'stylesheet' type = 'text/css' href = 'projectstyle.css'/> </head> <body> <!-- Links --> <div class = 'header'><h1>Chris' Book Store</h1></div> <div class = 'special'> <h3><p class = 'one'> <a class = 'link' href = 'myproject.php'>Home</a> &nbsp; | &nbsp;"; if($loggedin == true) echo "<a class = 'link' href = 'loggedout.php'>Log Out</a> &nbsp; | &nbsp;"; else echo "<a class = 'link' href = 'login.html'>Log In</a> &nbsp; | &nbsp;"; echo "<a class = 'link' href = 'createaccount.php'>Create Account</a> &nbsp; | &nbsp; <a class = 'link' href = 'contact.php'>Contact Us</a> &nbsp; | &nbsp; <a class = 'link' href = 'categories.php'>Categories</a> &nbsp; | &nbsp; <a class = 'link' href = 'searchstart.php'>Search</a> &nbsp; | &nbsp; <a class = 'link' href = 'orders.php'>View Orders</a> &nbsp; | &nbsp; <a class = 'link' href = 'viewcart.php'>View Cart</a> </p></h3> <br/> <!-- User input fields --> <form id = 'useraccount' action = 'useraccount.php' method = 'post'> <div style = 'text-align: center' class = 'header'> <h3><p><label>*First Name:&nbsp;</label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input id = 'fname' name = 'fname' type = 'text'/></p></h3> <!-- User's first name --> <h3><p><label>*Last Name:</label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input id = 'lname' name = 'lname' type = 'text'/></p></h3> <!-- User's last name --> <h3><p><label>*E-mail Address:&nbsp;</label> &nbsp; &nbsp; <input id = 'email' name = 'email' type = 'text'/></p></h3> <!-- User's desired email address to use --> <h3><p><label>*Password:</label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input id = 'pass1' name = 'pass1' type = 'password'/></p></h3> <!-- User's desired password --> <h3><p><label>*Confirm Password:<label> <input id = 'pass2' name = 'pass2' type = 'password'/></p></h3> <!-- Confirm user's desired password --> <h3><p><label>*Address 1:</label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input id = 'add1' name = 'add1' type = 'text'/></p></h3> <!-- Street address --> <h3><p><label>Address 2:</label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input id = 'add2' name = 'add2' type = 'text'/></p></h3> <!-- Additional address information --> <h3><p><label>*City:</label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input id = 'city' name = 'city' type = 'text'/></p></h3> <!-- City name --> <h3><p><label>*State: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</label> <select id = 'state' name = 'state' > <!-- Drop down list with all 50 states --> <option value = 'none'>--(select a state)--</option> <option value = 'AL'>Alabama</option><option value = 'AK'>Alaska</option><option value = 'AZ'>Arizona</option> <option value = 'AR'>Arkansas</option><option value = 'CA'>California</option><option value = 'CO'>Colorado</option> <option value = 'CT'>Connecticut</option><option value = 'DE'>Delaware</option><option value = 'FL'>Florida</option> <option value = 'GA'>Georgia</option><option value = 'HI'>Hawaii</option><option value = 'ID'>Idaho</option> <option value = 'IL'>Illinois</option><option value = 'IN'>Indiana</option><option value = 'IA'>Iowa</option> <option value = 'KS'>Kansas</option><option value = 'KY'>Kentucky</option><option value = 'LA'>Louisiana</option> <option value = 'ME'>Maine</option><option value = 'MD'>Maryland</option><option value = 'MA'>Massachusetts</option> <option value = 'MI'>Michigan</option><option value = 'MN'>Minnesota</option><option value = 'MS'>Mississippi</option> <option value = 'MO'>Missouri</option><option value = 'MT'>Montana</option><option value = 'NE'>Nebraska</option> <option value = 'NV'>Nevada</option><option value = 'NH'>New Hampshire</option><option value = 'NJ'>New Jersey</option> <option value = 'NM'>New Mexico</option><option value = 'NY'>New York</option><option value = 'NC'>North Carolina</option> <option value = 'ND'>North Dakota</option><option value = 'OH'>Ohio</option><option value = 'OK'>Oklahoma</option> <option value = 'OR'>Oregon</option><option value = 'PA'>Pennsylvania</option><option value = 'RI'>Rhode Island</option> <option value = 'SC'>South Carolina</option><option value = 'SD'>South Dakota</option><option value = 'TN'>Tennessee</option> <option value = 'TX'>Texas</option><option value = 'UT'>Utah</option><option value = 'VT'>Vermont</option> <option value = 'VA'>Virginia</option><option value = 'WA'>Washington</option><option value = 'WV'>West Virginia</option> <option value = 'WI'>Wisconsin</option><option value = 'WY'>Wyoming</option> </select></h3> <h3><p><label>*Zip Code:</label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input id = 'zip' name = 'zip' type = 'text'/></p></h3> <!-- Area zip code --> <h3><p><label>Phone Number:</label> &nbsp; &nbsp; &nbsp; &nbsp; <input id = 'phone' name = 'phone' type = 'text'/></p></h3> <!-- User's phone number --> <input type = 'button' value = 'Create Account' onClick = 'account()'/> <!-- Click to create account --> <input type = 'reset' value = 'Clear'/> <h3><p>* Required Field</p></h3> </div> </form> </body> </html>"; ?> <file_sep>/csc552/project2/client.cpp /* * Author: <NAME> * File: client.cpp * Date: 03/07/2017 * Due Date: 03/11/2017 * Project: #2 * Course Num: CSC552 * Course Title: Advanced Unix Programming * Professor: Dr. Spiegel * School: Kutztown University of Pennsylvania * Semester: SPRING2017 * About: This file acts as client and prompts the user for input. * The prompt will accept either two floating-point numbers * or the words 'total' or 'exit'. All input will be written * to a pipe to be received by the server. The server will * process the information sent and send a message back in * response. The client will then display the message from * the server and start the prompt again until the user * enters 'exit'. All errors dealing with read and write are * being accounted for with the use of perror (stderr). */ #include <iostream> #include <sstream> #include <cstdio> #include <cstdlib> using namespace std; /// * Function Name: isSame /// * Function Type: inspector /// * Parameters: string - import only - string to be modified and compared /// string - import only - string to be compared to /// * Return Value: bool - true if match, false if no match /// * \brief This function takes a two string arguments to compare. /// * It will convert each letter of the first string argument to /// * upper case to ensure case insensitivity. If the string /// * matches the second string then true is returned. If not /// * false is returned. It is assumed that he second argument /// * should be an all caps string and will always return false /// * if it is not. /// * bool isSame(string, string); /// * Function Name: pkgNum /// * Function Type: facilitator /// * Parameters: string - import only - the first number in the package /// string - import only - the second number in the package /// * Return Value: const char* - a cstring containing two numbers /// * \brief This function takes two string arguments and attempts to /// * package them together into a const char* value so it can /// * be written into a pipe. The output format will be: /// * "number1 *SPACE* number2" /// * This function also assumes that the strings are numeric in /// * nature and does not check the strings for correct format. const char* pkgNum(string, string); /// * Function Name: readMessage /// * Function Type: facilitator /// * Parameters: int - import only -the fdes for the read end of the pipe /// * Return Value: bool - true if message sent, false if not /// * \brief This function takes the file descriptor that should be the /// * read end of a pipe and checks to see if the server wrote /// * anything into the pipe. The message will be printed to the /// * screen if it was properly received. If the message failed /// * to be received an error message will be thrown through /// * perror (stderr) and false will be returned. Otherwise true /// * will be returned. This function assumes that the file /// * descriptor is the read end of a pipe. bool readMessage(int); /// * Function Name: writeMessage /// * Function Type: facilitator /// * Parameters: int - import only - the fdes for the write end of the pipe /// const char* - import only - the message to be sent /// size_t - import only - the size of the message to be sent /// * Return Value: bool - true if message sent, false if not /// * \brief This function takes the file descriptor that should be the /// * write end of a pipe and writes the message determined by /// * the 2nd argument to the pipe. The message will be of the /// * size given in the 3rd argument. If the message could not be /// * sent an error message will be thrown through perror /// * (stderr) and false will be returned. Otherwise true will be /// * returned. This function assumes that the file descriptor /// * is the write end of a pipe. bool writeMessage(int, const char*, size_t); /// \file /// * \brief This file acts as client and prompts the user for input. /// * The prompt will accept either two floating-point numbers /// * or the words 'total' or 'exit'. All input will be written /// * to a pipe to be received by the server. The server will /// * process the information sent and send a message back in /// * response. The client will then display the message from /// * the server and start the prompt again until the user /// * enters 'exit'. All errors dealing with read and write are /// * being accounted for with the use of perror (stderr). int main(int argc, char** argv) { string TOTAL = "TOTAL", EXIT = "EXIT"; string n1, n2; //Numbers (or commands) to be entered in prompt int fd[2]; //The pipe the client will be using fd[0] = atoi(argv[0]); //Convert to int to get the read end of pipe fd[1] = atoi(argv[1]); //Convert to int to get the write end of pipe //Display prompt to user once cout << "Enter two floating-point numbers "; cout << "or the words 'TOTAL' or ' EXIT'\n"; cout << "> "; //Get only one input string to test if it's 'TOTAL' or 'EXIT' first cin >> n1; if(isSame(n1, "TOTAL")) //User entered 'TOTAL' - write total to server writeMessage(fd[1], "TOTAL", 32); else if(isSame(n1, "EXIT")) //User entered 'EXIT' - write exit to server writeMessage(fd[1], "EXIT", 32); //If not total or exit then must get another number else { cin >> n2; //Get and package both numbers - write package to server writeMessage(fd[1], pkgNum(n1, n2), BUFSIZ); } sleep(1); //Sleep to prevent race conditions readMessage(fd[0]+1); //Get message from server if any //Close pipe ends since we are done here close(fd[0]+1); close(fd[1]); return 0; } /// \details /// * isSame will take a two strings as arguments. It will iterate through the ///* first string turning every letter to upper case. Once the string has been /// * converted to all upper case then it will be compared to the second string. /// * If the strings match then the function will return true. If not then false /// * will be returned. This function ensures a case-insensitive comparison. /// * This function also assumes that both strings are numeric and the second /// * string is all upper case. bool isSame(string str1, string str2) { //Go to each letter in str1 and make it upper case for(int i = 0; i < str1.length(); i++) str1[i] = toupper(str1[i]); if(str1 == str2) return true; //strings match else return false; //strings do not match } /// \details /// * pkgNum takes two string arguments and places them inside on const char*. /// * A stringstream is used to make the conversion. The first string is stream /// * inserted into the stringstream followed by a space and the second string /// * argument. The string stream is converted into string and placed inside a /// * temporary holding string. The temporary string is then converted into a /// * cstring and returned. const char* pkgNum(string num1, string num2) { stringstream str; str << num1; str << " "; str << num2; string temp = str.str(); return temp.c_str(); } /// \details /// * readMessage takes a single integer argument that represents the file /// * descriptor of the pipe end to read out of. First a message holder of the /// * max size allowed in the system-buffer will be made. Then a message, if one /// * exists will be place inside the message holder. The message will then be /// * printed to the screen. If the message failed to be received then an error /// * message will be printed through perror (stderr) and false will be returned. /// * Otherwise true will be returned. bool readMessage(int fd) { //Create a static message container of the max size the buffer can hold static char message[BUFSIZ]; //Read from pipe and place it in the message container if(read(fd, message, BUFSIZ) != -1) { cout << message; fflush(stdout); //Get everything out of the pipe } else { perror("Message failed to be received\n"); return true; } return false; } /// \details /// * writeMessage will take three arguments. The first argument is the file /// * descriptor which represents the pipe end the client will write to. The /// * second argument is the message to be written to the pipe. The third is the /// * size of the message to be sent. A message of the size buf will then be /// * constructed and sent to the file descriptor pipe end. If the message was /// * not send then an error message will be printed through perror (stderr) and /// * false will be returned. Otherwise true will be returned. bool writeMessage(int fd, const char* message, size_t buf) { //Write into the pipe to communicate with he server if(write(fd, message, buf) != -1) fflush(stdout); //Get everything out of the pipe else { perror("Message failed to be sent\n"); return false; } return true; } <file_sep>/csc510/assignment5/fcfs.cpp /* Author: <NAME> Date: 12/04/17 Due Date: 12/12/17 File: fcfs.cpp Assignment: #5 Course: CSC510 Advanced Operating Systems Professor: Dr. Parson University: Kutztown University of Pennsylvania About: This file serves a control algorithm compared to the other solutions to the readers writers problem. This solution does not allow for concurrency among readers and therefore only one reader or writer is allowed in the critical section at a time. By not having concurrency, this implementation should easily show the benefits of concurrent readers as part of a solution. With more readers than writers this will become even more apparent. It is suggested to run this program along with another solution to see how much time is saved with concurrency implemented. Is similar to the fair solution with the FIFO queue but without effects of concurrency. */ #include <iostream> #include <functional> //ref() function to wrap atomic variable parameters #include "readWriteSTM.h" using namespace std; /* Function Name: fcfs Function Type: mutator Parameters: thread - the calling thread and all its information Returns: int - the status of the state machine About: Evaluates first come first serve solution to the readers writers problem. Each thread must wait their turn to enter the critical section. Only one thread may be in the critical section at a time regardless of reader/writer status. */ int readWriteSTM::fcfs(thread evalThread) { switch (currentStates[evalThread.tid]) { case STATE_INIT: //Initial state where freshly created threads start logMsg("init, ARRIVE", evalThread); currentStates[evalThread.tid] = STATE_WAIT; //Go wait to get in cs logMsg("init, DEPART", evalThread); return(KEEP_GOING); case STATE_WAIT: //Wait here for the critical section to open logMsg("wait, ARRIVE", evalThread); waitingQueue.push(evalThread.tid); //Wait in line for your turn, first in first out while(waitingQueue.front() != evalThread.tid) {} //Mutex lock is first come first serve logMsg("trying lock on mutex", evalThread, 1); lockMutex(csMtx, csCon, ref(csOpen)); //Only admit one R or W logMsg("acquired the mutex", evalThread, 1); waitingQueue.pop(); //Remove yourself from the waiting queue currentStates[evalThread.tid] = STATE_CRITSECT; logMsg("wait, DEPART", evalThread); return(KEEP_GOING); //This control critical section can only hold one reader or writer at a //time i.e. no concurrancy is allowed in this critical section. case STATE_CRITSECT: logMsg("critSec, ARRIVE", evalThread); if(evalThread.rw == READER) { //Readers Only logMsg("reader in critical section, sleeping...", evalThread, 1); usleep(SLEEP_READER); //Sleep to represent doing something } else { //(evalThread.rw == WRITER) Writers Only logMsg("writer in critical section, sleeping...", evalThread, 1); usleep(SLEEP_WRITER); //Sleep to represent doing something } unlockMutex(csMtx, csCon, ref(csOpen)); //Unlock the cs //The task is done go to the terminate state currentStates[evalThread.tid] = STATE_TERMINATE; logMsg("critSec, DEPART", evalThread); return(KEEP_GOING); case STATE_TERMINATE: //End the current task for the thread logMsg("terminate, ARRIVE", evalThread); return(STOP_GOING); //Reached the accept state default: //Should never reach this state but for good measure logMsg("error: illegal state", evalThread); //I do no know how you got here but I am putting a stop to it! return(STOP_GOING); } } //Put other solution function declarations here so readWriteSTM.cpp can know //they exist when it selects which algorithm to use. Otherwise the program //will not compile because these functions will not be defined. int readWriteSTM::fair(thread evalThread) {} int readWriteSTM::wrp(thread evalThread) {} int readWriteSTM::srp(thread evalThread) {} int readWriteSTM::wwp(thread evalThread) {} int readWriteSTM::swp(thread evalThread) {} int main(int argc, char **argv) { readWriteSTM * stm = new readWriteSTM(); cout << "FCFS Preference" << endl; stm->makingThreads(STM_FCFS); //Start the STM with FCFS Preference return 0; } <file_sep>/csc520/finalproj/src/com/library/business_layer/field_list/Notifiable.java package com.library.business_layer.field_list; import java.io.Serializable; import java.util.Date; /** * The Notifiable class represents a reservation that was moved aside for * the person who made the reservation. Notifiable contains the date the * reservation was put aside, the foreign key to reservation id, and a * unique identifier. Identifiers are meant to act similar to a primary key * in a database and as such should be unique. Also implements Serializable * so it can be serialized for later use. * BUSINESS LAYER CLASS * @see com.library.business_layer.field_list.Reservation */ public class Notifiable implements Serializable { private int id; private Date datePutAside; private int reservationId; /** * Contstructs Notifiable Object by setting its attributes to a value. * @param i identifier * @param d date put aside * @param r reservation id */ public Notifiable(int i, Date d, int r) { setId(i); setDatePutAside(d); setReservationId(r); } /** * Gets the int identifier value for this Object. * @return id as int */ public int getId() { return id; } /** * Gets the date the reservation was put aside. * @return date put aside Date */ public Date getDatePutAside() { return datePutAside; } /** * Gets the indentifier for the reservation. * @return reservation id int */ public int getReservationId() { return reservationId; } /** * Sets the value for the Object identifier. * @param i int to set id to */ public void setId(int i) { id = i; } /** * Sets the value for the date the reservation was put aside. * @param dpa Date to set date renewal needed to */ public void setDatePutAside(Date dpa) { datePutAside = dpa; } /** * Sets the value for the reservation id. * @param i int to set reservation id to */ public void setReservationId(int i) { reservationId = i; } }<file_sep>/csc520/finalproj/src/com/library/server_ui/MembershipServerUI.java package com.library.server_ui; import com.library.server_layer.MembershipServer; import com.library.protocol.field_list.PMember; import com.library.protocol.field_list.PCreditCard; import com.library.protocol.field_list.PAddress; import java.util.Arrays; import java.util.Scanner; import java.io.Console; /** * The role of the MembershipServerUI is to let the server and user communicate * back and forth. This is done by reading/writing to the console. The * functionality of this server UI includes printing account information and the * option for a member to change their password. * SERVER LAYER */ public class MembershipServerUI { private MembershipServer ms; /** * Basic constructor that initializes its corresponding server. */ public MembershipServerUI() { ms = new MembershipServer(); } /** * Prints the member with the session id's account information. Only logged * in members can view account details. Fails if a member does not exist * with that session id. * @param sess int session id */ public void member(int sess) { ms.update(); if(sess <= 0) { //Only logged in users can view account info System.out.println("You must be logged in to view account information\n"); return; } PMember pMem = ms.readMember(sess); PCreditCard pCC = ms.readCreditCard(sess); PAddress pADD = ms.readAddress(sess); if(pMem != null && pCC != null && pADD != null) { System.out.println("ACCOUNT INFORMATION"); System.out.println(pMem.toString()); System.out.println("PAYMENT INFORMATION"); System.out.println(pCC.toString()); System.out.println("ADDRESS INFORMATION"); System.out.println(pADD.toString()); } else { System.out.println("An error has occurred\n"); } } /** * Prints the member with the session id's password information. Only logged * in members can view password details. Fails if a member does not exist * with that session id. Actual password is not shown for security reasons. * @param i int session id */ public void password(int i) { if(i <= 0) { //Only logged in users can view password info System.out.println("You must be logged in to view password information\n"); return; } ms.update(); char[] currentPass = new char[ms.readPassword(i).length()]; Arrays.fill(currentPass, '*'); System.out.println("Current Password: " + new String(currentPass) + "\n"); } /** * Allows a member to change their password. Lets the member enter their * old password and a new password. If the old password matches and the new * password is not the same as the old one, the member is taken to the * confirm page. Otherwise the password change fails. A user must be logged * in to change their password. * @param i int session id * @param reader Scanner read user input */ public void changePassword(int i, Scanner reader) { if(i <= 0) { //Only logged in users can change password System.out.println("You must be logged in to change password\n"); return; } ms.update(); String choice = ""; //Confirm with the user if they want to change while(!(choice.toLowerCase().equals("y") || choice.toLowerCase().equals("n"))) { System.out.print("Change your password? [y/n]: "); choice = reader.nextLine(); } if(choice.toLowerCase().equals("n")) { return; } String oldPass = "", newPass = ""; Console console = System.console(); //Get old password for clearance System.out.print("Please enter old password: "); oldPass = new String(console.readPassword()); //Get new password System.out.print("Please enter new password: "); newPass = new String(console.readPassword()); String checkPass = ms.readPassword(i); if(oldPass.equals(newPass)) { //Make sure new password is not the old one System.out.println("New password cannot be the same as old password\n"); } else if(checkPass.equals(oldPass)) { //Make sure the old password matches confirm(i, oldPass, newPass, reader); } else { System.out.println("The old password entered was not correct\n"); } } /** * Confirms if the member wants to change their password. If the member * wishes to continue, the password will attempt to be changed. * @param i int session id * @param o String old password * @param n String new password * @param reader Scanner read user input */ public void confirm(int i, String o, String n, Scanner reader) { if(i <= 0) { System.out.println("You must be logged in to change password\n"); return; } ms.update(); String choice = ""; while(!(choice.toLowerCase().equals("y") || choice.toLowerCase().equals("n"))) { System.out.print("Confirm change? [y/n]: "); choice = reader.nextLine(); } if(choice.toLowerCase().equals("n")) { System.out.println("Aborting new password request\n"); } else { if(ms.changePassword(i, o, n)) { System.out.println("You have successfully changed your password\n"); } else { System.out.println("An error has occured\n"); } } } } <file_sep>/csc402/assignment5/graphDemo.cpp /* Author: <NAME> File: graphDemo.cpp Class: CSC 402 Date: 10/11/2015 */ #include <iostream> #include <vector> #include "adjacencyMatrixGraph.h" #include "adjacencyListGraph.h" using namespace std; int main() { graph *myGraph1, *myGraph2; vector<int> visited_list1, visited_list2; myGraph1 = new adjacencyMatrixGraph(9); myGraph2 = new adjacencyListGraph(11); cout << "\nADJACENCY MATRIX\n"; myGraph1->insertEdge(0, 1); myGraph1->insertEdge(0, 3); myGraph1->insertEdge(1, 2); myGraph1->insertEdge(1, 4); myGraph1->insertEdge(1, 5); myGraph1->insertEdge(2, 4); myGraph1->insertEdge(3, 5); myGraph1->insertEdge(4, 6); myGraph1->insertEdge(4, 8); myGraph1->insertEdge(5, 6); myGraph1->insertEdge(5, 8); myGraph1->insertEdge(7, 8); myGraph1->output(cout); myGraph1->BFS(0, visited_list1); cout << "Breadth First Search Visited List: "; for(int i = 0; i < visited_list1.size(); i++) cout << visited_list1.at(i) << " "; cout << endl; visited_list1.clear(); myGraph1->DFS(0, visited_list1); cout << "Depth First Search Visited List: "; for(int i = 0; i < visited_list1.size(); i++) cout << visited_list1.at(i) << " "; cout << endl; cout << "\nADJACENCY LIST\n"; myGraph2->insertEdge(0, 1); myGraph2->insertEdge(0, 3); myGraph2->insertEdge(1, 4); myGraph2->insertEdge(2, 4); myGraph2->insertEdge(3, 5); myGraph2->insertEdge(4, 6); myGraph2->insertEdge(4, 8); myGraph2->insertEdge(5, 6); myGraph2->insertEdge(6, 10); myGraph2->insertEdge(7, 8); myGraph2->insertEdge(7, 10); myGraph2->insertEdge(10, 9); myGraph2->output(cout); myGraph2->BFS(0, visited_list2); cout << "Breadth First Search Visited List: "; for(int i = 0; i < visited_list2.size(); i++) cout << visited_list2.at(i) << " "; cout << endl; visited_list2.clear(); myGraph2->DFS(0, visited_list2); cout << "Depth First Search Visited List: "; for(int i = 0; i < visited_list2.size(); i++) cout << visited_list2.at(i) << " "; cout << endl << endl; return 0; } <file_sep>/csc135/README.txt CSC 135 - Computer Science I Dr. <NAME> Kutztown University Fall 2012 An introduction to computer components; algorithmic design and the constructs of structured programming; elementary data types and data operations; programming in a high level language; one-and-two dimensional arrays; functions and top-down, modular, step-wise programming; computer solution of several numerical and non-numerical problems. <file_sep>/csc402/inclassprograms/wireRouter.cpp #include <iostream> #include <queue> #include <fstream> #include <stack> using namespace std; struct position { int row; int col; position(int r, int c) { row = r; col = c; } bool equal(position p) { return row == p.row && col == p.col; } position upper() { return position(row-1, col); } position lower() { return position(row+1, col); } position right() { return position(row, col+1); } position left() { return position(row, col-1); } void print() { cout << "(" << row << ", " << col << ")" << endl; } }; void readGrid(int[6][6]); bool findPath(position, position, int[6][6]); void printPath(position, position, int[6][6]); void printGrid(int[6][6]); int main() { int grid[6][6]; readGrid(grid); position startPin(1, 1); position endPin(4, 3); if(findPath(startPin, endPin, grid)) { cout << "Path found!\n"; printGrid(grid); printPath(startPin, endPin, grid); } else cout << "No path found.\n"; return 0; } void readGrid(int grid[6][6]) { ifstream fin; fin.open("grid.dat"); if(fin.fail()) { cout << "Error reading file"; return; } for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) fin >> grid[i][j]; } bool findPath(position startPin, position endPin, int grid[6][6]) { if(startPin.equal(endPin)) return true; queue<position> q; position thePosition = startPin; q.push(startPin); while(!q.empty()) { thePosition = q.front(); q.pop(); int step = grid[thePosition.row][thePosition.col]; if(grid[thePosition.upper().row][thePosition.upper().col] != -1) { q.push(thePosition.upper()); grid[thePosition.upper().row][thePosition.upper().col] = step+1; if(thePosition.upper().equal(endPin)) return true; } if(grid[thePosition.lower().row][thePosition.lower().col] != -1) { q.push(thePosition.lower()); grid[thePosition.lower().row][thePosition.lower().col] = step+1; if(thePosition.lower().equal(endPin)) return true; } if(grid[thePosition.left().row][thePosition.left().col] != -1) { q.push(thePosition.left()); grid[thePosition.left().row][thePosition.left().col] = step+1; if(thePosition.left().equal(endPin)) return true; } if(grid[thePosition.right().row][thePosition.right().col] != -1) { q.push(thePosition.right()); grid[thePosition.right().row][thePosition.right().col] = step+1; if(thePosition.right().equal(endPin)) return true; } } return false; } void printPath(position startPin, position endPin, int grid[6][6]) { int step = grid[endPin.row][endPin.col]; stack<position> s; s.push(endPin); while(step != 1) { position p = s.top(); step = grid[p.row][p.col]; if(grid[p.upper().row][p.upper().col] == step-1) s.push(p.upper()); if(grid[p.lower().row][p.lower().col] == step-1) s.push(p.lower()); if(grid[p.left().row][p.left().col] == step-1) s.push(p.left()); if(grid[p.right().row][p.right().col] == step-1) s.push(p.right()); } while(!s.empty()) { s.top().print(); s.pop(); } } void printGrid(int grid[6][6]) { for(int i = 0; i < 6; i++) { for(int j = 0; j < 6; j++) cout << grid[i][j] << ' '; cout << endl; } } <file_sep>/sideprojects/games/blackjack.cpp #include <iostream> #include <cstdlib> #include <ctime> #include <sstream> using namespace std; string findSuit(int); string findRank(int); string convertInt(int); int getScore(int, int); bool blackJack(int); int main() { srand(time(NULL)); int hand[5], tempCard, score = 0, idx = 0; hand[idx] = (rand() % (52 - 1) + 1); idx++; do { tempCard = (rand() % (52 - 1) + 1); } while(tempCard == hand[0]); hand[idx] = tempCard; idx++; cout << "Card One: " << findRank(hand[0]) << " of " << findSuit(hand[0]) << endl; cout << "Card Two: " << findRank(hand[1]) << " of " << findSuit(hand[1]) << endl; score = getScore(hand[0], score); score += getScore(hand[1], score); cout << "Current Score: " << score << endl; char draw; cout << "Would you like another card? [y: yes | n: no] "; cin >> draw; if(draw == 'y') { do { tempCard = (rand() % (52 - 1) + 1); } while(tempCard == hand[0] || tempCard == hand[1]); hand[idx] = tempCard; idx++; score += getScore(hand[2], score); cout << "Card Drew: " << findRank(hand[2]) << " of " << findSuit(hand[2]) << endl; cout << "Current Score: " << score << endl; if(score > 21) cout << "Busted! You Lose!\n"; else { int dealScore = (rand() % (26 - 11) + 11); cout << "Dealer Score: " << dealScore << endl; if(dealScore > 21) cout << "Dealer Busted! You Win!\n"; else if(dealScore == 21) cout << "Dealer Blackjack! You Lose!\n"; else if(dealScore > score) cout << "Dealer Scored Higher! You Lose!\n"; else if(dealScore == score) cout << "Dealer Scored Same! Dealer Wins By Default!\n"; else if(dealScore < score) cout << "Dealer Scored Lower! You Win!\n"; } } else if(draw == 'n') { int dealScore = (rand() % (26- 11) + 11); cout << "Dealer Score: " << dealScore << endl; if(dealScore > 21) cout << "Dealer Busted! You Win!\n"; else if(dealScore == 21) cout << "Dealer Blackjack! You Lose!\n"; else if(dealScore > score) cout << "Dealer Scored Higher! You Lose!\n"; else if(dealScore == score) cout << "Dealer Scored Same! Dealer Wins By Default!\n"; else if(dealScore < score) cout << "Dealer Scored Lower! You Win!\n"; } if(blackJack(score)) cout << "Black Jack!\n"; return 0; } string findSuit(int card) { if(card / 13 < 1) return "Clubs"; else if(card / 13 < 2) return "Diamonds"; else if(card / 13 < 3) return "Hearts"; else return "Spades"; } string findRank(int card) { if(card % 13 == 0) return "Ace"; else if((card+1) % 13 == 0) return "King"; else if((card+2) % 13 == 0) return "Queen"; else if((card+3) % 13 == 0) return "Jack"; else if(card / 13 < 1) return convertInt(card+1); else if(card / 13 < 2) return convertInt((card-13)+1); else if(card / 13 < 3) return convertInt((card-26)+1); else return convertInt((card-39)+1); } int getScore(int card, int currentScore) { int score; if(card % 13 == 0) if(currentScore > 10) return 1; else return 11; else if((card+1) % 13 == 0) return 10; else if((card+2) % 13 == 0) return 10; else if((card+3) % 13 == 0) return 10; else if(card / 13 < 1) return card+1; else if(card / 13 < 2) return (card-13)+1; else if(card / 13 < 3) return (card-26)+1; else return (card-39)+1; } bool blackJack(int score) { if(score == 21) return true; else return false; } string convertInt(int number) { stringstream ss; ss << number; return ss.str(); } <file_sep>/csc552/project3/README.txt README.txt <NAME> CSC 552 Issues/Bugs/Non-Implementations: * Semapores were not implemented * No signals for shutdown implemented * Inter-machine communication only works one way from my testing. The client not on acad can send messages but not receive. The client on acad can receive but not send. * Shared memory on the client side retains information correctly but it will be displayed incorrectly if users do not log out in FIFO order. This is because I did not implement a inUse boolean system to see what slots/rows in the LOCAL_DIR are being used. I did however use the boolean system for server shared memory. * Minimal documention was added to the server and almost none to the client due to time restraints. I wanted to submit my project on time for the presentation. * During the presentation not all messages sent were received. It was originally thought to be a problem with the ports but this was later debunked. Different Design Decisions: * Client counter is incremented within the child instead of the parent i.e. after successful login and not before the fork(). * Parent server process does not wait for child, only waits on accept. * A client's message is sent to the server first and then redirected towards the intended recipient. This is so the server can tell the user the status of the sent message such as the recipient does not exist, the recipient is the user or the message was sent/failed to send. * The client splits a a message into multiple messages if it goes over the standard message length. <file_sep>/csc242/Project/orders.php <?php session_start(); $loggedin = $_SESSION['loggedin']; $id = $_SESSION['custID']; /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/orders.php Course: CSC 242 - Fall 2013 */ //Create page with same style sheet and links as rest of website echo "<html xmlns = 'http://www.w3.org/1999/xhtml'> <head> <title> Chris' Book Store </title> <!-- My stylesheet for the project --> <link rel = 'stylesheet' type = 'text/css' href = 'projectstyle.css'/> </head> <body> <!-- Links --> <div class = 'header'><h1>Chris' Book Store</h1></div> <div class = 'special'> <h3><p class = 'one'> <a class = 'link' href = 'myproject.php'>Home</a> &nbsp; | &nbsp;"; if($loggedin == true) echo "<a class = 'link' href = 'loggedout.php'>Log Out</a> &nbsp; | &nbsp;"; else echo "<a class = 'link' href = 'login.html'>Log In</a> &nbsp; | &nbsp;"; echo "<a class = 'link' href = 'createaccount.php'>Create Account</a> &nbsp; | &nbsp; <a class = 'link' href = 'contact.php'>Contact Us</a> &nbsp; | &nbsp; <a class = 'link' href = 'categories.php'>Categories</a> &nbsp; | &nbsp; <a class = 'link' href = 'searchstart.php'>Search</a> &nbsp; | &nbsp; <a class = 'link' href = 'orders.php'>View Orders</a> &nbsp; | &nbsp; <a class = 'link' href = 'viewcart.php'>View Cart</a> </p></h3><br/>"; if($loggedin == false) echo "<h3><p class = 'one'>Please log in to view your orders! <a href = 'login.html' class = 'link'>Log in?</a></p></h3>"; else { //Connect to the database $dsn = 'mysql:host=localhost;dbname=ccarr419_bookstore'; $username = 'ccarr419'; $password = '<PASSWORD>'; $db = new PDO($dsn, $username, $password); //Get info from the Orders table $query = "SELECT * FROM Orders"; $orders = $db->query($query); if(!checkEmpty($orders, $id)) { echo "<h1 class = 'header'><div style = 'color: red'>You have not made any orders yet!</div></h1>"; } else { $query = "SELECT * FROM Orders"; $orders = $db->query($query); //Create a table containing orders of the user echo "<table style = 'margin-right: auto; margin-left:auto' border = '1' cellpadding = '5' bgcolor = '#aaaaaa'> <thead><tr> <th>Order ID</th> <th>Customer ID</th> <th>Shipping Cost</th> <th>Tax</th> <th>Total</th> <th>Order Date</th> <th colspan = '1'></th> </tr></thead>"; $i = 1; foreach($orders as $order) { if($order['CustomerID'] == $id) { echo "<tr><td><div class = 'special'>"; echo $order['OrderID']; echo "</div></td><td><div class = 'special'>"; echo $order['CustomerID']; echo "</div></td><td><div class = 'special'>$"; echo round($order['ShippingCost'], 2); echo "</div></td><td><div class = 'special'>$"; echo round($order['Tax'], 2); echo "</div></td><td><div class = 'special'>"; echo $order['Total']; echo "</div></td><td><div class = 'special'>"; echo $order['OrderDate']; echo "</div></td><td><div class = 'special'> <form name = 'order$i' action = 'orderdetails.php' method = 'post'> <input type = 'hidden' id = '" . $order['OrderID'] . "' name = '" . $order['OrderID'] . "' value = '" . $order['OrderID'] . "'/> <input type = 'submit' value = 'Order Details'/></form></div></td></tr>"; $i++; } } } } echo "</table></div></body> </html>"; function checkEmpty($orders, $id) { foreach($orders as $order) { if($order['CustomerID'] == $id) return true; } return false; } ?><file_sep>/csc342/Site/NewPhotoAlbum.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PlanetWroxModel; public partial class _NewPhotoAlbum : BasePage { protected void Page_Load(object sender, EventArgs e) { } protected void EntityDataSource1_Inserted(object sender, EntityDataSourceChangedEventArgs e) { if(e.Entity != null) { PhotoAlbum myPhotoAlbum = (PhotoAlbum)e.Entity; Response.Redirect(string.Format("ManagePhotoAlbum.aspx?PhotoAlbumId={0}", myPhotoAlbum.Id.ToString())); } } }<file_sep>/csc548/README.txt CSC 548 - Artificial Intelligence II Dr. <NAME> Kutztown University Spring 2017 A study of advance topics in artificial intelligence (AI) focusing on those aspects of AI which are most relevant to the design and construction of intelligent agents: control, knowledge acquisition and representation, reasoning with knowledge, planning and carrying out actions. <file_sep>/csc320/Tales of Mortise Game/README.txt 2D side-scroller game created using Unreal Engine 4. <file_sep>/csc242/Project/contact.php <?php session_start(); $loggedin = $_SESSION['loggedin']; /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/contact.php Course: CSC 242 - Fall 2013 */ //Create page with same style sheet and links as rest of website echo "<html xmlns = 'http://www.w3.org/1999/xhtml'> <head> <title> Contact Us </title> <link rel = 'stylesheet' type = 'text/css' href = 'projectstyle.css'/> </head> <body> <!-- Links --> <div class = 'header'><h1>Chris' Book Store</h1></div> <div class = 'special'> <h3><p class = 'one'> <a class = 'link' href = 'myproject.php'>Home</a> &nbsp; | &nbsp;"; if($loggedin == true) echo "<a class = 'link' href = 'loggedout.php'>Log Out</a> &nbsp; | &nbsp;"; else echo "<a class = 'link' href = 'login.html'>Log In</a> &nbsp; | &nbsp;"; echo "<a class = 'link' href = 'createaccount.php'>Create Account</a> &nbsp; | &nbsp; <a class = 'link' href = 'contact.php'>Contact Us</a> &nbsp; | &nbsp; <a class = 'link' href = 'categories.php'>Categories</a> &nbsp; | &nbsp; <a class = 'link' href = 'searchstart.php'>Search</a> &nbsp; | &nbsp; <a class = 'link' href = 'orders.php'>View Orders</a> &nbsp; | &nbsp; <a class = 'link' href = 'viewcart.php'>View Cart</a> </p></h3> <br/> <h3><p class = 'one'> <!-- About Us/Contact Us information --> We here at Chris' Book Store try to give you the best price<br/> and utmost satisfaction or your money back guarantee!<br/><br/> Any questions?<br/><br/> Give us a call at: 1800-555-4795<br/> <!-- Fake phone number --> Send us an email at: <EMAIL><br/><br/> Or send us a letter at:<br/> 15200 Kutztown Rd.<br/> <!-- Fake street address --> Kutztown, Pa 19530<br/><br/> Also check out my official website here: <!-- Link back to home site --> <a href = 'http://unixweb.kutztown.edu/~ccarr419/index.html'>Chris' Official Website</a> </p></h3> </div> </body> </html>"; ?><file_sep>/csc237/project4/BinarySearchTree.h /** * Author: <NAME> * Updated By: <NAME> * File: BinarySearchTree.h * Date: 23/4/2014 * Purpose: Binary Tree ADT using linked structures. * A binary tree is comprised of a root, and subtrees. * Subtrees are called children and can be a parent by * having its own children. If the subtree has no children * it is called a leaf. Entries less than the subtree will go * left, with entries greater than the subtree will go right. * Any entry added that's already in the tree will increment * the counter. This adds multiplicity to the tree. **/ #ifndef TREE_H #define TREE_H template <typename treeEltType> class BinaryTree; /** * Class: TreeNode * Purpose: A template class that holds later to be specified data. * Consists of a pointer to be used to point at a treeNode * with lesser data, a right pointer to point at a treeNode * with greater data, and a counter for multiplicity. **/ template <typename eltType> class TreeNode { private: eltType info; TreeNode<eltType> *left, *right; int count; //Multiplicity counter, initially 1 TreeNode(const eltType &data, TreeNode<eltType> *lChild = NULL, TreeNode *rChild = NULL, int num = 1) { info = data; left = lChild; right = rChild; count = num; //Assign one, or user assigned value to count } friend class BinaryTree<eltType>; }; template <typename treeEltType> class BinaryTree { public: /** * The constructor constructs an instance of a BinaryTree by pointing * the data member root at NULL **/ BinaryTree(); /** * Places an element into the tree by following the rules of a tree. * Returns 1 if inserted (true) **/ int insertToTree(const treeEltType &data); /** * Searches the tree for a specific element. Returns true if the element * resides in the tree, false if not. * Assumes == is defined for treeEltType **/ bool treeSearch(const treeEltType &data); /** * Retrieves an element from the tree while leaving the tree intact * Precondition: The element has to be located in the tree **/ treeEltType &retrieveFromTree(const treeEltType &data); /** * Removes an element from the tree or decrements counter based * on the element's multiplicity. * Precondition: The element has to be located in the tree **/ void deleteFromTree(const treeEltType &data); /** * Changes an element to a new specified data, if the multiplicity of * the element to be changed is greater than one, the element's counter * will be decremented and the new data will be inserted. Otherwise, * the element will be changed/deleted according to the new data **/ void change(const treeEltType &toChange, const treeEltType &data); /** * Checks if the given element has multiple copies (multiplicity g.t. one) * Returns true if multiple copies, false if not * Precondition: At least one copy is in the tree **/ bool hasMultiples(const treeEltType &data); /** * Decrements the count of the given element * Preconditions: Element has to be in the list w/ more than one copy **/ void decCount(const treeEltType &data); /** * Displays the tree in order, least to greatest (Left, Node, Right) **/ void inorder() const; /** * Displays the tree in preorder (Node, Left, Right) **/ void preorder() const; /** * Displays tree in postorder (Left, Right, Node) **/ void postorder() const; /** * Prints the tree according the its actual shape **/ void treePrint() const; private: TreeNode<treeEltType> *root; /** * Recursive helper function to printorder **/ void printInorder(TreeNode<treeEltType> *) const; /** * Recursive helper function to preorder **/ void printPreorder(TreeNode<treeEltType> *) const; /** * Recursive helper function to postorder **/ void printPostorder(TreeNode<treeEltType> *) const; /** * Helper function to treePrint **/ void treePrintHelper(TreeNode<treeEltType> *) const; }; #endif <file_sep>/sideprojects/fractions/primes.h #ifndef PRIMES_H #define PRIMES_H #include <iostream> #include <vector> using namespace std; class primes { public: primes(const int num = 100); void setPrimes(const int); void setPowers(); void resetPrimes(); void resetPowers(); void printPrimes(); int gcd(int, int); int lcm(int, int); private: vector<int> primeNum; vector<int> powers; void gcdMaxHelper(int, int, int); void gcdMinHelper(int, int, int); }; #endif <file_sep>/sideprojects/guitar.cpp #include <iostream> #include <iomanip> #include <string> #include <vector> #include <map> using namespace std; void findNotes(const string[], string[], vector<string>&, int); void printFretboard(map<int, vector<string> >&, int, int, int); int main() { const string sharp[12] = {"A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"}; const string flat[12] = {"A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"}; string tuning[6] = {"E", "A", "D", "G", "B", "E"}; int num_strings = 6; int curr_string = 0; int fret_num = 0; char choice; vector<string> notes; map<int, vector<string> > guitar_string; cout << "Would you like to use sharps (s) or flats (f)? "; cin >> choice; cout << "Enter your tuning: "; cin >> tuning[0] >> tuning[1] >> tuning[2] >> tuning[3] >> tuning[4] >> tuning[5]; cout << endl; if(choice == 's') { for(int i = 0; i < num_strings; i++) { findNotes(sharp, tuning, notes, curr_string); guitar_string[curr_string] = notes; curr_string++; notes.clear(); } } else if(choice == 'f') { for(int i = 0; i < num_strings; i++) { findNotes(flat, tuning, notes, curr_string); guitar_string[curr_string] = notes; curr_string++; notes.clear(); } } curr_string = 0; printFretboard(guitar_string, num_strings, curr_string, fret_num); return 0; } void findNotes(const string notation[], string tuning[], vector<string> &notes, int curr_string) { for(int i = 0; i < 12; i++) { if(notation[i] == tuning[curr_string]) { for(int j = i; j < 12; j++) notes.push_back(notation[j]); for(int j = 0; j <= i; j++) notes.push_back(notation[j]); return; } } } void printFretboard(map<int, vector<string> > &guitar_string, int num_strings, int curr_string, int fret_num) { for(int i = num_strings; i > 0; i--) cout << "\t" << i; cout << "\n\t"; for(int i = 0; i < 42; i++) cout << "-"; cout << "\n"; for(int i = 0; i < guitar_string[curr_string].size(); i++) { for(int j = curr_string; j < num_strings; j++) { if(j == 0) cout << fret_num << "\t" << guitar_string[j].at(i); else cout << "\t" << guitar_string[j].at(i); } cout << "\n"; fret_num++; cout << "\t"; for(int i = 0; i < 42; i++) cout << "-"; cout << "\n"; } } <file_sep>/csc554/README.txt CSC 554 - Project Management Dr. <NAME> Kutztown University Spring 2018 This course discusses the principles of project management which are considered mandatory for the success of business projects. The focus of discussion is project management in general and information systems project management in particular. Though behavioral and organizational aspects of project management are discussed, the emphasis is more on learning tools and techniques which provide quantitative insight during the project management life cycle. These tools and techniques are required to effectively plan, monitor and control the projects. In this course, students also get the opportunity to work on projects simulating real world situations to practice concepts and techniques learnt in this course. <file_sep>/csc510/README.txt CSC 510 - Advanced Operating Systems Dr. <NAME> Kutztown University Fall 2017 This course reviews the basic software components of an operating system, and includes advanced topics, including distributed processing and distributed process management, evaluation of an operating system's performance, networks, operating system security, case studies of particular operating systems. <file_sep>/csc135/restaurant2_ChristianCarreras.cpp /**************************************************************************** Project 4: Loops (Restaurant Bill) This program uses while and for loops as well as nested loops to create an interface for a restaurant which asks the user for how many people were at the table and the price of their meals (assuming 1 meal per person) Then the program will display the subtotal, sales tax, tip and total. The program terminates when the user enters 0 or any value less than 0. Author: <NAME> Course: CSC 135 Due Date: 11/27/2012 ****************************************************************************/ #include <iostream> #include <fstream> #include <iomanip> using namespace std; float getSum(ifstream &fp); int main() { ifstream fp; fp.open("bill.dat"); if(!fp) { cout << "Error opening file\n"; return 0; } const float tax = 0.06; //Pa state tax 6%. //Variables. float tip, salestax, total, people; float sum = getSum(fp); int i; //Calculate tip relative to number of people //at the table. If < 5 then use 18%. //If >= 5 then use 20%. for(i = 0; i < 4; i++) { if(people < 5) { tip = sum * 0.18; } else if(people >= 5) { tip = sum *0.20; } //Calculate sales tax and total. salestax = sum * tax; total = sum + salestax + tip; //Display information (Restaurant Bill cout << setprecision(2) << fixed; //setprecision to 2 decimal places. cout << "\nPeople:\t\t" << people << endl; cout << "Subtotal:\t$" << sum << endl; cout << "Sales Tax:\t$" << salestax << endl; cout << "Tip:\t\t$" << tip << endl; cout << "Total:\t\t$" << total << endl; } return 0; } float getSum(ifstream &fp) { float num, sum = 0; while (fp.eof()==false) { fp>>num; sum+=num; } return sum; } <file_sep>/csc558/assignment5/README.txt Author Name: <NAME> Course Num: CSC 558 Course Name: Data Mining & Analytics II Semester: Spring 2018 Professor: Dr.Parson University: Kutztown University Assignment: Final Date: 05/08/2018 About: Text-mining social media posts for MBTI personality types. DATASET: https://www.kaggle.com/datasnaek/mbti-type BACKGROUND ON MBTI: http://www.myersbriggs.org/my-mbti-personality-type/mbti-basics/home.htm?bhcp=1 HOW TO RUN IN WEKA: Run this on command line java -Xmx1300M -Dfile.encoding=utf-8 -jar "C:\Program Files\Weka-3-8\weka.jar PERMISSIONS: You have my, <NAME>' permission to distribute, publish, present, or use as educational material as long as it is not for monetary gain for any party involved. All I ask is you keep my name and/or credit me where credit is due (: Thanks! <file_sep>/csc520/finalproj/src/com/library/business_layer/field_list/Address.java package com.library.business_layer.field_list; import java.io.Serializable; /** * The Address class represents a real-life address. Address contains a * house number, street name, county and a zip code. Identifiers are meant * to act similar to a primary key in a database and as such should be unique. * Also implements Serializable so it can be serialized for later use. * BUSINESS LAYER CLASS */ public class Address implements Serializable { private int id; private String house; private String street; private String county; private String zip; /** * Contstructs Address Object by setting its attributes to a value. * @param i identifier * @param h house number * @param s street address * @param c county * @param z zip code */ public Address(int i, String h, String s, String c, String z) { setId(i); setHouse(h); setStreet(s); setCounty(c); setZip(z); } /** * Gets the int identifier value for this Object. * @return id as int */ public int getId() { return id; } /** * Gets the address house number as a String. * @return house number String */ public String getHouse() { return house; } /** * Gets the street address as a String. * @return street address String */ public String getStreet() { return street; } /** * Gets the address county name as a String. * @return county name String */ public String getCounty() { return county; } /** * Get the address zip code as a String. * @return zip code String */ public String getZip() { return zip; } /** * Sets the value for the Object identifier. * @param i int to set id to */ public void setId(int i) { id = i; } /** * Sets the value for the address house number. * @param h String to set house number to */ public void setHouse(String h) { house = h; } /** * Sets the value for the street address. * @param s String to set street address to */ public void setStreet(String s) { street = s; } /** * Sets the value for the address county. * @param c String to set county to */ public void setCounty(String c) { county = c; } /** * Sets the value for the address zip code. * @param z String to set zip code to */ public void setZip(String z) { zip = z; } }<file_sep>/csc520/finalproj/src/com/library/business_layer/field_list/Member.java package com.library.business_layer.field_list; import java.io.Serializable; /** * The Member class represents a real-life person who wishes to use the * library's online and in person services. A Member Object contains the * member's name, phone number, amount due, member number, credit card id, * address id, internet account id, whether they are in good standing, and a * unique identifier. Identifiers are meant to act similar to a primary key * in a database and as such should be unique. Also implements Serializable * so it can be serialized for later use. * BUSINESS LAYER CLASS * @see com.library.business_layer.field_list.Address * @see com.library.business_layer.field_list.CreditCard * @see com.library.business_layer.field_list.InternetAccount */ public class Member implements Serializable { private int id; private String name; private String phone; private int amountDue; private boolean inGoodStanding; private String number; private int creditCardId; private int addressId; private int internetAccountId; /** * Contstructs Member Object by setting its attributes to a value. * @param i identifier * @param n name * @param p phone number * @param a amount due * @param igs in good standing * @param num member number * @param ci credit card id * @param ai address id * @param ii internet account id */ public Member(int i, String n, String p, int a, boolean igs, String num, int ci, int ai, int ii) { setId(i); setName(n); setPhone(p); setAmountDue(a); setInGoodStanding(igs); setNumber(num); setCreditCardId(ci); setAddressId(ai); setInternetAccountId(ii); } /** * Gets the int identifier value for this Object. * @return id as int */ public int getId() { return id; } /** * Gets the name of the Member as a String. * @return name String */ public String getName() { return name; } /** * Gets the Member's phone number as a String. * @return phone number String */ public String getPhone() { return phone; } /** * Gets the amount due by the Member as an int. * @return amount due int */ public int getAmountDue() { return amountDue; } /** * Gets the state of the Member's standing as a boolean. * @return in good standing boolean */ public boolean getInGoodStanding() { return inGoodStanding; } /** * Gets the Members user number as a String. * @return number String */ public String getNumber() { return number; } /** * Gets the indentifier for the Member CreditCard. * @return credit card id int */ public int getCreditCardId() { return creditCardId; } /** * Gets the indentifier for the Member Address. * @return address id int */ public int getAddressId() { return addressId; } /** * Gets the indentifier for the Member InternetAccount. * @return internet account id int */ public int getInternetAccountId() { return internetAccountId; } /** * Sets the value for the Object identifier. * @param i int to set id to */ public void setId(int i) { id = i; } /** * Sets the value for Member's name. * @param n String to set name to */ public void setName(String n) { name = n; } /** * Sets the value for Member's phone number. * @param p String to set name to */ public void setPhone(String p) { phone = p; } /** * Sets the value for Member's amount due. * @param a int to set amount due to */ public void setAmountDue(int a) { amountDue = a; } /** * Sets the value for Member's current state. * @param igs boolean to set in good standing to */ public void setInGoodStanding(boolean igs) { inGoodStanding = igs; } /** * Sets the value for Member's number. * @param num String to set number to */ public void setNumber(String num) { number = num; } /** * Sets the value for the CreditCard id. * @param ci int to set credit card id to */ public void setCreditCardId(int ci) { creditCardId = ci; } /** * Sets the value for the Address id. * @param ai int to set address id to */ public void setAddressId(int ai) { addressId = ai; } /** * Sets the value for the InternetAccount id. * @param ii int to set internet account id to */ public void setInternetAccountId(int ii) { internetAccountId = ii; } }<file_sep>/csc520/finalproj/src/com/library/business_layer/message_list/PublisherHome.java package com.library.business_layer.message_list; import com.library.business_layer.field_list.Publisher; import com.library.persistence_layer.*; import java.util.Collections; import java.util.ArrayList; /** * PublisherHome serves as a way to access the PublisherTable. Thus it also * serves as an accessor to the table's element's attributes. Another purpose of * PublisherHome is to create and add any new entries to the PublisherTable. * BUSINESS LAYER CLASS * @see com.library.business_layer.field_list.Publisher */ public class PublisherHome { private Table pubTable; /** * Basic constructor for PublisherHome that instantiates home's Tables. */ public PublisherHome() { pubTable = new DataSchema.PublisherTable(); } /** * Gets the PublisherTable as a whole. * @return DataSchema.PublisherTable */ public DataSchema.PublisherTable getPublishers() { return (DataSchema.PublisherTable) pubTable; } /** * Finds a Publisher by their primary key identifier. * @param id int * @return Publisher */ public Publisher findByPrimaryKey(int id) { return (Publisher) pubTable.selectId(id); } /** * Creates a new Publisher and appends it to the PublisherTable. * @param name String publisher name * @return the newly created Publisher */ public Publisher create(String name) { Publisher newMember = new Publisher(pubTable.nextKey(), name); pubTable.append(newMember); return newMember; } /** * Gets the all the Publishers in PublisherTable sorted by name. * @return sorted ArrayList&lt;Publisher&gt; */ public ArrayList<Publisher> findPublisherNames() { ArrayList<Publisher> p = pubTable.selectAll(); Collections.sort(p); return p; } /** * Force the update of all PublisherHome Tables. */ public void update() { pubTable.updateList(); } }<file_sep>/csc135/parameters_ChristianCarreras.cpp /************************************************** This program uses parameters and pass by values to create functions and display information. Author: <NAME> **************************************************/ #include <iostream> #include <string> using namespace std; void displayNameAge(string , int); //Function with name and age void displaySumDifference(int, int); //Function with sum and difference int main() //Main function { int age, num1, num2, sum, difference; string name; //Ask user for name and age cout << "What is your name? "; getline(cin, name); cout << "How old are you? "; cin >> age; //Ask user for any two integers cout << "Please enter an integer: "; cin >> num1; cout << "Please enter another integer: "; cin >> num2; //Call functions displayNameAge(name, age); displaySumDifference(num1, num2); return 0; } //Name and age function void displayNameAge(string name, int age) { cout << "Hello, " << name << endl; cout << "You are " << age << " years old.\n"; } //Sum and differce function void displaySumDifference(int num1, int num2) { cout << "The sum of the two integers is " << (num1 + num2) << ".\n"; cout << "The difference of the two integers is " << (num1 - num2) << ".\n"; } <file_sep>/csc342/Site/Reviews/All.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PlanetWroxModel; public partial class Reviews_All : BasePage { protected void Page_Load(object sender, EventArgs e) { using (PlanetWroxEntities myEntities = new PlanetWroxEntities()) { var authorizedReviews = from review in myEntities.Reviews where review.Authorized == true orderby review.CreateDateTime descending select review; GridView1.DataSource = authorizedReviews; GridView1.DataBind(); } } }<file_sep>/csc552/project1/README.txt Here is the link to my doxygen documentation: http://acad.kutztown.edu/~ccarr419/csc552/html/index.html <file_sep>/csc242/Project/categories.php <?php session_start(); $loggedin = $_SESSION['loggedin']; /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/categories.php Course: CSC 242 - Fall 2013 */ //Create page with same style sheet and links as rest of website echo "<html xmlns = 'http://www.w3.org/1999/xhtml'> <head> <title> Categories </title> <script type = 'text/javascript'> <!-- function categorySubmit(& category) { document.forms('category').submit(); } //--> </script> <link rel = 'stylesheet' type = 'text/css' href = 'projectstyle.css'/> </head> <body> <div class = 'header'><h1>Chris' Book Store</h1></div> <div class = 'special'> <h3><p class = 'one'> <a class = 'link' href = 'myproject.php'>Home</a> &nbsp; | &nbsp;"; if($loggedin == true) echo "<a class = 'link' href = 'loggedout.php'>Log Out</a> &nbsp; | &nbsp;"; else echo "<a class = 'link' href = 'login.html'>Log In</a> &nbsp; | &nbsp;"; echo "<a class = 'link' href = 'createaccount.php'>Create Account</a> &nbsp; | &nbsp; <a class = 'link' href = 'contact.php'>Contact Us</a> &nbsp; | &nbsp; <a class = 'link' href = 'categories.php'>Categories</a> &nbsp; | &nbsp; <a class = 'link' href = 'searchstart.php'>Search</a> &nbsp; | &nbsp; <a class = 'link' href = 'orders.php'>View Orders</a> &nbsp; | &nbsp; <a class = 'link' href = 'viewcart.php'>View Cart</a> </p></h3></div><br/> "; //Connect to database $dsn = 'mysql:host=localhost;dbname=ccarr419_bookstore'; $username = 'ccarr419'; $password = '<PASSWORD>'; $db = new PDO($dsn, $username, $password); //Get info from Categories table $query = "SELECT * FROM Categories"; $categories = $db->query($query); $i = 1; //Place info into a button foreach($categories as $category) { echo "<form name = 'category$i' action = 'category.php' method = 'post'> <div class = 'header'> <input type = 'hidden' id = '" . $category['CategoryName'] . "' name = '" . $category['CategoryID'] . "' value = '" . $category['CategoryName'] . "'/> <input type = 'submit' value = '" . $category['CategoryName'] . "'/> </div></form> "; $i++; } echo " </body> </html>"; ?><file_sep>/csc520/finalproj/src/com/library/business_layer/message_list/ReservationHome.java package com.library.business_layer.message_list; import com.library.business_layer.field_list.Reservation; import com.library.business_layer.field_list.Concluded; import com.library.business_layer.field_list.Member; import com.library.persistence_layer.*; import java.util.ArrayList; import java.sql.Timestamp; /** * ReservationHome serves as a way to access the ReservationTable. Thus it also * serves as an accessor to the table's element's attributes. Another purpose of * ReservationHome is to create and add any new entries to the ReservationTable. * BUSINESS LAYER CLASS * @see com.library.business_layer.field_list.Reservation */ public class ReservationHome { private Table resTable; private Table conTable; /** * Basic constructor for ReservationHome that instantiates home's Tables. */ public ReservationHome() { resTable = new DataSchema.ReservationTable(); conTable = new DataSchema.ConcludedReservationTable(); } /** * Gets the ReservationTable as a whole. * @return DataSchema.ReservationTable */ public DataSchema.ReservationTable getReservations() { return (DataSchema.ReservationTable) resTable; } /** * Finds a Reservation by its primary key identifier. * @param id int * @return Reservation */ public Reservation findByPrimaryKey(int id) { return (Reservation) resTable.selectId(id); } /** * Creates a new Reservation and appends it to the ReservationTable. * @param num String reservation number * @param t Timestamp timestamp of reservation * @param memId int member id * @param cbId int cataloged book id * @return the newly created Reservation */ public Reservation create(String num, Timestamp t, int memId, int cbId) { Reservation newReservation = new Reservation(resTable.nextKey(), num, t, memId, cbId); resTable.append(newReservation); return newReservation; } /** * Find all Reservations for a member that were not concluded. * @param m Member * @return List of unconcluded Reservations */ public ArrayList<Reservation> findUnconcludedByMember(Member m) { ArrayList<Reservation> res = resTable.selectWhere("memberId", m.getId()); for(Reservation r : res) { ArrayList<Concluded> con = conTable.selectWhere("reservationId", r.getId()); if(!con.isEmpty()) { res.remove(r); } } return res; } /** * Force the update of all ReservationHome Tables. */ public void update() { resTable.updateList(); conTable.updateList(); } }<file_sep>/csc421/assignment1/README.txt * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Yahtzee © 2017 Hasbro, Inc. * Version 1.0 * <NAME> BS Computer Science * Kutztown University of Pennsylvania * * JavaDocs Link: * http://csitrd.kutztown.edu/~ccarr419/csc421/assignment1/ * * - - - - - - - - - - MY DESIGN CHOICES - - - - - - - - - - * * For this project I decided to make a command-based * version of Yahtzee similar to computer console-like * commands. The user is provided with a prompt and can * enter commands freely. The user may start and quit the * game freely at will as well. To represent the dice I * used an integer array and used a pseudo-random number * generator to represent a roll of the dice. In hindsight, * I believe using a class to define the dice object would * have been easier to implement and read but too much * progress was made without implementing a class that * changing it could create complications and break the * majority of the existing code. I am greatly considering * using classes in the future when extending this game. * Command-line arguments are fully set up and were * originally intended for bug-testing but can be used to * start the game with a specific initial roll. To use * the command-line arguments feature, type the code * to run the game followed by five dice digits (1-6), * each separated by a space. The help page (this page), * the categories page, the rules page, and global stats * page are all read from files for easier editing and * displaying purposes (plus it cleans up the code!) * All entered commands are transformed to lower-case for * compatibility and error-handling. All non-commands * are handled gracefully and returns the player prompt. * * - - - - - - - - - - - - HELP PAGE - - - - - - - - - - - - * GAME INPUT COMMANDS * * help - brings up the help page which displays the * complete list of commands that can be used * throughout the game. Can be called at any * point before or during the game. * * start - begin the game with the initial first roll. * Can also be called during a game to restart * the round/game from the beginning. * * stats - shows the current game information including * current roll, current kept dice, the number * of rolls rolled, and the dice rolled for each * roll. Can only be called during an active game. * * gstat - shows the total number of rounds played by any * user on the machine and the average amount * of rolls rolled by each user. Can be called * at any point before or during a game. * * pdice - prints the current rolled dice in both dice * and numeric form. Can only be called * during a game in progress. * * roll - continues the round by rolling the dice again. * A player will only be able to use this * command if a game is in progress i.e. * the game has started and the player has * not exceeded the number of allotted rolls. * Should be preceded by the keep command to * keep dice through the next roll. * * keep - lets the user select which dice they wish to * keep before the next roll. Saved dice will * be carried over future rolls until the user * decides to change which dice are kept. The * user can use the keep command multiple times * before or after a roll if they choose to. * Can only be called during a game. * * cat - shows the complete list of categories that can * be picked by the user regardless if they meet * the prerequisites or not. This command can be * called before or during a game. * * acat - shows the available categories the user can * choose at the moment of this command call. * Can only be called during a game. * * pcat - lets the user pick a category for their round * to fall under. Will only show available * categories similar to the acat command. Can * only be called during an active game. * * quit - lets the user end the game and terminate the * program at any point before or during a * game. Game information will not be logged * if this command is used before round end. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <file_sep>/csc520/assignment1/com/csc520Code/Card.java package com.csc520Code; /* * Author: <NAME> * File Name: Card.java * Creation Date: 01/30/2018 * Due Date: 02/12/2018 * Course: CSC 520 - Advanced Object Oriented Programming * Professor Name: Dr. Schwesinger * Assignment: #1 * Major: MS Software Development * University: Kutztown University of Pennsylvania * JavaDoc Link: http://csitrd.kutztown.edu/~ccarr419/csc520/assignment1/ */ /** * The card class attempts to represent a playing card. Playing cards are * denoted by their rank and suit. Ranks include two through ten, jack, queen, * king, and ace (in order least to highest). Suits include clubs, diamonds, * hearts and spades. Suits each contain their own set of ranks. One suit is * not greater or lesser than another suit and serve the only purpose of * creating another seperate set for the ranks. Ranks and suits are represented * as integers for simplicity, especially when comparing. The class ensures * that only cards found in the range representing a tradional playing card * can be created. All other options will force a run-time exception. Users * cannot modify a card in any way, they can only inspect card information * after the card object has been instantiated. */ public class Card implements Comparable<Card> { private int rank; //Determines greater or less than private int suit; //Determines set of the rank private static final int R_LIMIT = 13; //Number of ranks allowed private static final int S_LIMIT = 4; //Number of suits allowed /** * An enumeration of all the possible ranks for a card. */ private enum Ranks { TWO (0), THREE (1), FOUR (2), FIVE (3), SIX (4), SEVEN (5), EIGHT (6), NINE (7), TEN (8), JACK (9), QUEEN (10), KING (11), ACE (12); private final int value; Ranks(int v) { this.value = v; } public int value() { return value; } } /** * An enumeration of all the possible suits for a card. */ private enum Suits { CLUBS (0), DIAMONDS (1), HEARTS (2), SPADES (3); private final int value; Suits(int v) { this.value = v; } public int value() { return value; } } /** * An exception that is thrown when the user tries to create a card with a * rank outside the accepted range of ranks. */ private class InvalidCardRankException extends Exception { /** Gives error message, prints the stack trace, then terminates. */ public InvalidCardRankException() { System.err.println("Error: Invalid rank for card."); this.printStackTrace(); System.exit(0); } } /** * An exception that is thrown when the user tries to create a card with a * suit outside the accepted range of suits. */ private class InvalidCardSuitException extends Exception { /** Gives error message, prints the stack trace, then terminates. */ public InvalidCardSuitException() { System.err.println("Error: Invalid suit for card."); this.printStackTrace(); System.exit(0); } } /** * A basic constructor that creates a card object with the given rank and * suite. A rank and suit must be given as a blank card serves no purpose. * @param r the rank of the newly created card * @param s the suit of the newly created card */ public Card(int r, int s) { //Call the set functions to make sure rank and suite are acceptable setRank(r); setSuit(s); } /** * Gets the rank of the card in the form of an integer. * @return the int value representing the card's rank */ public int getRank() { return rank; } /** * Gets the suit of the card in the form of an integer. * @return the int value representing the card's suit */ public int getSuit() { return suit; } /** * Turns the integers reprenting the rank and suit into their mnemonic form * and inserts into a string to be returned. * @return the name of the card in a string */ public String toString() { String outStr = ""; //Find the card's rank and append its rank name to string for(Ranks r : Ranks.values()) { if(r.value == rank) { outStr += ("" + r.name() + " of "); break; //No need to look at the others } } //Find the card's suit and append its suit name to string for(Suits s : Suits.values()) { if(s.value == suit) { outStr += ("" + s.name()); break; //No need to look at the others } } return outStr; } /** * Overloaded function from Comparable that allows cards to be sorted. * Cards will be sorted by suit first then by rank. * @param otherCard the card to compare to this card * @return 1 if this card is greater than, -1 if less than, and 0 if equal */ public int compareTo(Card otherCard) { //Order by suit first if(suit > otherCard.getSuit()) { return 1; } else if(suit < otherCard.getSuit()) { return -1; } //Then order by rank else { if(rank > otherCard.getRank()) { return 1; } else if(rank < otherCard.getRank()) { return -1; } else { return 0; } //The cards are equal } } /** * Sets the rank of the card but first checks if the rank is within the * acceptable range of ranks. Throws an exception if necessary. * @param r the rank to set the card to */ private void setRank(int r) { try { //Make sure a negative/out-of-range rank is not given if(r >= R_LIMIT || r < 0) { throw new InvalidCardRankException(); } else { rank = r; } } //If a bad rank was given, throw a run-time exception catch(InvalidCardRankException e) { } } /** * Sets the suit of the card but first checks if the suit is within the * acceptable range of suits. Throws an exception if necessary. * @param s the suit to set the card to */ private void setSuit(int s) { try { //Make sure a negative/out-of-range suit is not given if(s >= S_LIMIT || s < 0) { throw new InvalidCardSuitException(); } else { suit = s; } } //If a bad suit was given, throw a run-time exception catch(InvalidCardSuitException e) { } } }<file_sep>/csc402/assignment4/adjacencyMatrixGraph.h /* Author: <NAME> File: adjacencyMatrixGraph.h Class: CSC 402 Date: 10/04/2015 */ #ifndef ADJACENCYMATRIXGRAPH_H #define ADJACENCYMATRIXGRAPH_H #include <iostream> #include "graph.h" using namespace std; class adjacencyMatrixGraph : public graph { private: int** matrix; int numNodes; public: adjacencyMatrixGraph(int n); ~adjacencyMatrixGraph(); int numberOfVertices() const; int numberOfEdges() const; bool existsEdge(int, int) const; void insertEdge(int, int); void eraseEdge(int, int); int degree(int) const; /* Not a directed graph int inDegree(int) const; int outDegree(int) const; */ void output(ostream&) const; }; #endif <file_sep>/sideprojects/fractions/fraction.cpp /** * Author: <NAME> * File Name: fraction.cpp * Purpose: **/ #include "fraction.h" #include <iostream> #include <assert.h> #include "primes.h" #include <string> #include <cmath> /** * Function Name: Constructor * Member Type: Constructor * Parameter(s): int - import only (numerator) * int - import only (denominator) * Return Value: N/A * Purpose: Constructs fraction object from user given numerator * and denominator, default values for the numerator and * denominator are both one. Checks if fraction can be reduced * after numerator and denominator are set. **/ fraction::fraction(int num, int den) { setFraction(num, den); checkReduce(); } /** * Function Name: setNumerator * Member Type: Mutator * Parameter(s): int - import only * Return Value: void * Purpose: Sets the fraction's numerator value to the given int value **/ void fraction::setNumerator(int num) { numerator = num; } /** * Function Name: setDenominator * Member Type: Mutator * Parameter(s): int - import only * Return Value: void * Purpose: Sets the fraction's denominator value to the given int value * If denominator value is zero, assert will end the program * (This will avoid any divide by zero situation) **/ void fraction::setDenominator(int den) { assert(den != 0); //Avoid dividing by zero if(den < 0) //If the denominator is less than zero { denominator = abs(den); //Will now equal its absolute value setNumerator(-1*getNumerator()); //Numerator will turn negative if positive //and positive if negative } else //If denominator is greater than zero denominator = den; } /** * Function Name: setFraction * Member Type: Mutator * Parameter(s): int - import only (numerator) * int - import only (denominator) * Return Value: void * Purpose: Calls setNumerator and setDenominator to set * the whole fraction at once **/ void fraction::setFraction(int num, int den) { setNumerator(num); setDenominator(den); } /** * Function Name: getNumerator * Member Type: Inspector * Parameter(s): N/A * Return Value: int (numerator) * Purpose: Returns the numerator value of the fraction **/ int fraction::getNumerator() const { return numerator; } /** * Function Name: getDenominator * Member Type: Inspector * Parameter(s): N/A * Return Value: int (denominator) * Purpose: Returns the denomiantor value of the fraction **/ int fraction::getDenominator() const { return denominator; } /** * Function Name: < operator * Member Type: Facilitator * Parameter(s): fraction& - import only * Return Value: true if less than * false if not * Purpose: Checks if current fraction is less than another **/ bool fraction::operator<(fraction &F) const { double dec1 = convertToDecimal(); double dec2 = F.convertToDecimal(); if(dec1 < dec2) return true; return false; } /** * Function Name: < operator * Member Type: Facilitator * Parameter(s): double - import only * Return Value: true if less than * false if not * Purpose: Checks if current fraction is less than the given * double value **/ bool fraction::operator<(double D) const { double dec = convertToDecimal(); if(dec < D) return true; return false; } /** * Function Name: > operator * Member Type: Facilitator * Parameter(s): fraction& - import only * Return Value: true if greater than * false if not * Purpose: Checks if current fraction is greater than another **/ bool fraction::operator>(fraction &F) const { double dec1 = convertToDecimal(); double dec2 = F.convertToDecimal(); if(dec1 > dec2) return true; return false; } /** * Function Name: operator > * Member Type: Facilitator * Parameter(s): double - import only * Return Value: true if greater than * false if not * Purpose: Checks if current fraction is greater than the given * double value **/ bool fraction::operator>(double D) const { double dec = convertToDecimal(); if(dec > D) return true; return false; } /** * Function Name: <= operator * Member Type: Facilitator * Parameter(s): fraction& - import only * Return Value: true if less than or equal to * false if not * Purpose: Checks if current fraction is less than or equal to another **/ bool fraction::operator<=(fraction &F) const { double dec1 = convertToDecimal(); double dec2 = F.convertToDecimal(); if(dec1 <= dec2) return true; return false; } /** * Function Name: <= operator * Member Type: Facilitator * Parameter(s): double - import only * Return Value: true if less than or equal to * false if not * Purpose: Checks if current fraction is less than or equal to the * given double value **/ bool fraction::operator<=(double D) const { double dec = convertToDecimal(); if(dec <= D) return true; return false; } /** * Function Name: >= operator * Member Type: Facilitator * Parameter(s): fraction& - import only * Return Value: true if greater than or equal to * false if not * Purpose: Checks if current fraction is greater than or equal to another **/ bool fraction::operator>=(fraction &F) const { double dec1 = convertToDecimal(); double dec2 = F.convertToDecimal(); if(dec1 >= dec2) return true; return false; } /** * Function Name: >= operator * Member Type: Facilitator * Parameter(s): double - import only * Return Value: true if greater than or equal to * false if not * Purpose: Checks if current fraction is greater than or equal to the * given double value **/ bool fraction::operator>=(double D) const { double dec = convertToDecimal(); if(dec >= D) return true; return false; } /** * Function Name: == operator * Member Type: Facilitator * Parameter(s): fraction& - import only * Return Value: true if equal to * false if not * Purpose: Checks if current fraction is equal to another **/ bool fraction::operator==(fraction &F) const { double dec1 = convertToDecimal(); double dec2 = F.convertToDecimal(); if(dec1 == dec2) return true; return false; } /** * Function Name: == operator * Member Type: Facilitator * Parameter(s): double - import only * Return Value: true if equal to * false if not * Purpose: Checks if current fraction is equal to the given double value **/ bool fraction::operator==(double D) const { double dec = convertToDecimal(); if(dec == D) return true; return false; } /** * Function Name: != operator * Member Type: Facilitator * Parameter(s): fraction& - import only * Return Value: true if not equal to * false if equal to * Purpose: Checks if current fraction is not equal to another **/ bool fraction::operator!=(fraction &F) const { double dec1 = convertToDecimal(); double dec2 = F.convertToDecimal(); if(dec1 != dec2) return true; return false; } /** * Function Name: != operator * Member Type: Facilitator * Parameter(s): double - import only * Return Value: true if not equal to * false if equal to * Purpose: Checks if current fraction is not equal to the given double value **/ bool fraction::operator!=(double D) const { double dec = convertToDecimal(); if(dec != D) return true; return false; } /** * Function Name: = operator * Member Type: Mutator * Parameter(s): fraction& - import only * Return Value: void * Purpose: Sets current fraction equal to another **/ void fraction::operator=(fraction &F) { setNumerator(F.getNumerator()); setDenominator(F.getDenominator()); } /** * Function Name: *= operator * Member Type: Mutator * Parameter(s): fraction& - import only * Return Value: void * Purpose: Multiplies current fraction by another fraction **/ void fraction::operator*=(fraction &F) { //Multiply numerator by numerator setNumerator(getNumerator()*F.getNumerator()); //Multiply denominator by denominator setDenominator(getDenominator()*F.getDenominator()); checkReduce(); } /** * Function Name: /= operator * Member Type: Mutator * Parameter(s): fraction& - import only * Return Value: void * Purpose: Divides current fraction by another fraction **/ void fraction::operator/=(fraction &F) { //Multiply numerator by denominator setNumerator(getNumerator()*F.getDenominator()); //Multiply denominator by numerator setDenominator(getDenominator()*F.getNumerator()); checkReduce(); } /** * Function Name: += operator * Member Type: Mutator * Parameter(s): fraction& - import only * Return Value: void * Purpose: Adds the current fraction and the given fraction together **/ void fraction::operator+=(fraction &F) { //If the denominators are equal, just add the numerators if(getDenominator() == F.getDenominator()) setNumerator(getNumerator()+F.getNumerator()); //If not, multiply the current fraction's numerator and denominator by the //given fraction's denominator and multiply the given fraction's numerator //and denominator by the current fraction's denominator else { fraction f1, f2; //Temporary storage f1.setNumerator(getNumerator() * F.getDenominator()); f1.setDenominator(getDenominator() * F.getDenominator()); f2.setNumerator(F.getNumerator() * getDenominator()); f2.setDenominator(F.getDenominator() * getDenominator()); //Now add the numerators together setNumerator(f1.getNumerator() + f2.getNumerator()); setDenominator(f1.getDenominator()); } //Check if fraction can be reduced checkReduce(); } /** * Function Name: -= operator * Member Type: Mutator * Parameter(s): fraction& - import only * Return Value: void * Purpose: Subtracts the given fraction from the current fraction **/ void fraction::operator-=(fraction &F) { //If the denominators are equal, just subtract the numerators if(getDenominator() == F.getDenominator()) setNumerator(getNumerator()-F.getNumerator()); //If not, multiply the current fraction's numerator and denominator by the //given fraction's denominator and multiply the given fraction's numerator //and denominator by the current fraction's denominator else { fraction f1, f2; //Temporary storage f1.setNumerator(getNumerator() * F.getDenominator()); f1.setDenominator(getDenominator() * F.getDenominator()); f2.setNumerator(F.getNumerator() * getDenominator()); f2.setDenominator(F.getDenominator() * getDenominator()); //Now subtract the numerators setNumerator(f1.getNumerator() - f2.getNumerator()); setDenominator(f1.getDenominator()); } //Check if fraction can be reduced checkReduce(); } /** * Function Name: convertToDecimal * Member Type: Facilitator * Parameter(s): N/A * Return Value: double - converted fraction * Purpose: Divides numerator by denominator to find and return * the fraction's equivalent double value **/ double fraction::convertToDecimal() const { double num = getNumerator(); double den = getDenominator(); double dec = num/den; return dec; } /** * Function Name: checkReduce * Member Type: Mutator * Parameter(s): N/A * Return Value: void * Purpose: Checks if the fraction can be reduced to a smaller fraction * by finding the greatest common multiple (gcm) If the numerator * and denominator are equal the value will be 1/1 or -1/1 **/ void fraction::checkReduce() { if(abs(getNumerator()) == getDenominator()) { setNumerator(getNumerator()/getDenominator()); setDenominator(1); return; } int min = fmin(abs(getNumerator()), getDenominator()); int max = fmax(abs(getNumerator()), getDenominator()); for(int i = min; i > 1; i--) { if(min % i == 0 && max % i == 0) { setNumerator(getNumerator()/i); setDenominator(getDenominator()/i); return; } } } /** * Function Name: printImproper * Member Type: Facilitator * Parameter(s): N/A * Return Value: void * Purpose: Prints the current fraction improperly (if the numerator * is greater than the denominator) if the numerator is not * greater than the denominator, just the fraction will print **/ void fraction::printImproper() const { if(abs(getNumerator()) > getDenominator()) { int wholenum = floor(getNumerator()/getDenominator()); int num = getNumerator()-(wholenum*getDenominator()); cout << wholenum << "u" << num << "/" << getDenominator(); } else cout << *this; } /** * Function Name: << operator * Member Type: N/A * Parameter(s): ostream& - import/export * fraction* - import only * Return Value: ostream& - the fraction printed properly * Purpose: Prints the fraction to screen, if a proper fraction * the value will appear as a fraction ("num/den") **/ ostream &operator<<(ostream &out, const fraction &F) { //If numerator is zero, print zero //If denominator is 1, print numerator if(F.getNumerator() == 0 || F.getDenominator() == 1) out << F.getNumerator(); else { //If numerator and denominator equal, print numerator (1 or -1) if(abs(F.getNumerator()) == F.getDenominator()) out << F.getNumerator(); else //Fraction cannot be reduced to whole number, print fraction out << F.getNumerator() << "/" << F.getDenominator(); } return out; } <file_sep>/csc402/assignment4/adjacencyListGraph.cpp /* Author: <NAME> File: adjacencyListGraph.cpp Class: CSC 402 Date: 10/04/2015 */ #include <iostream> #include "adjacencyListGraph.h" using namespace std; adjacencyListGraph::adjacencyListGraph(int n) { numNodes = n; aList = new int*[numNodes]; for(int i = 0; i < numNodes; i++) aList[i] = new int[numNodes]; for(int i = 0; i < numNodes; i++) for(int j = 0; j < numNodes; j++) aList[i][j] = -1; } adjacencyListGraph::~adjacencyListGraph() { delete [] aList; } int adjacencyListGraph::numberOfVertices() const { int numVertices = 0; for(int i = 0; i < numNodes; i++) { for(int j = 0; j < numNodes; j++) { if(aList[i][j] != -1) { numVertices++; break; } } } return numVertices; } int adjacencyListGraph::numberOfEdges() const { int numEdges = 0; for(int i = 0; i < numNodes; i++) for(int j = 0; j < numNodes; j++) if(aList[i][j] != -1) numEdges++; return numEdges; } bool adjacencyListGraph::existsEdge(int from, int to) const { return (aList[from][to] != -1 && aList[to][from] != -1); } void adjacencyListGraph::insertEdge(int f, int t) { aList[f][t] = t; aList[t][f] = f; } void adjacencyListGraph::eraseEdge(int f, int t) { aList[f][t] = -1; aList[t][f] = -1; } int adjacencyListGraph::degree(int from) const { int degree = 0; for(int i = 0; i < numNodes; i++) if(aList[from][i] != -1) degree++; return degree; } /* Not a directed graph int adjacencyListGraph::inDegree(int) const { } int adjacencyListGraph::outDegree(int) const { } */ void adjacencyListGraph::output(ostream& out) const { for(int i = 0; i < numNodes; i++) { out << "[" << i << "] = ( "; for(int j = 0; j < numNodes; j++) { if(aList[i][j] != -1) out << aList[i][j] << " "; } out << ")\n"; } } <file_sep>/csc136/project3a/term.cpp //File: term.cpp //Author: <NAME> //Description: Term class code and implication // which is to be used by the Array class #include <iostream> #include <fstream> #include <string> #include <cmath> #include "term.h" using namespace std; //Constructor Term::Term(float coeff, int expn) { setTerm(coeff, expn); } /////////// //Sets /////////// bool Term::setTerm(float co, int ex) { coefficient = co; exponent = ex; return true; } bool Term::setCoefficient(float co) { return(coefficient = co); } bool Term::setExponent(int ex) { return(exponent = ex); } /////////// //Gets /////////// float Term::getCoefficient() const { return coefficient; } int Term::getExponent() const { return exponent; } //////////////////////// //Member Operators //////////////////////// //Multiply Term by factor void Term::operator*=(double factor) { setCoefficient(getCoefficient()*factor); } //Evaluate Term for x double Term::operator()(double x) const { double answer; answer = pow(x, getExponent())*getCoefficient(); return answer; } //Checks if Terms matches an int bool Term::operator==(int x) const { if(getExponent() == x) return true; else return false; } //Checks if a Term is less than another Term bool Term::operator<(const Term &T) const { if(getExponent() < T.getExponent()) return true; else return false; } /////////////////////////// //Associated Operators /////////////////////////// //Read input into Term ifstream &operator>>(ifstream &input, Term &T) { float coeff; int expn; input >> coeff >> expn; T.setCoefficient(coeff); T.setExponent(expn); return input; } ostream &operator<<(ostream &out, const Term &T) { //When the coefficient and exponent are greater than 1 if(T.getCoefficient() > 1 && T.getExponent() > 1) out << T.getCoefficient() << "x^" << T.getExponent(); //When the coefficient is equal to 1 but the exponent is greater than 1 else if(T.getCoefficient() == 1 && T.getExponent() > 1) out << "x^" << T.getExponent(); //When the coefficient > 1 and the exponent = 1 else if(T.getCoefficient() > 1 && T.getExponent() == 1) out << T.getCoefficient() << "x"; //When both the coefficient and the exponent are equal to one else if(T.getCoefficient() == 1 && T.getExponent() == 1) out << "x"; //When the the exponent is zero else if(T.getExponent() == 0) out << T.getCoefficient(); //When the coefficient is 0 else if(T.getCoefficient() == 0) out << ""; return out; } <file_sep>/sideprojects/games/random/random.cpp #include <iostream> #include <cstdlib> #include <ctime> using namespace std; bool yahtzee(int[]); bool fourOfaKind(int[]); bool threeOfaKind(int[]); bool aPair(int[]); int keep(int, int[]); void sort(int[]); int main() { srand(time(NULL)); int dice[5]; int rolls = 0; int counter = 0; char choice; do { for(int i = counter; i < 5; i++) dice[i] = rand() % (6 - 1) + 1; rolls++; if(rolls > 1) sort(dice); if(rolls == 3) break; if(yahtzee(dice)) break; cout << "Your roll: "; for(int i = 0; i < 5; i++) cout << dice[i] << " "; cout << endl; cout << "What number would you like to keep? "; cin >> choice; switch (choice) { case '0': break; case '1': counter = keep(1, dice); break; case '2': counter = keep(2, dice); break; case '3': counter = keep(3, dice); break; case '4': counter = keep(4, dice); break; case '5': counter = keep(5, dice); break; case '6': counter = keep(6, dice); break; default: cout << "I cannot understand \"" << choice << "\"\n"; rolls--; break; } } while(1); cout << "Final: "; for(int i = 0; i < 5; i++) cout << dice[i] << " "; cout << endl; if(yahtzee(dice)) cout << "Yahtzee!\n"; else if(fourOfaKind(dice)) cout << "Four of a kind!\n"; else if(threeOfaKind(dice)) cout << "Three of a kind!\n"; else if(aPair(dice)) cout << "A pair!\n"; else cout << "Better luck next time!\n"; return 0; } bool yahtzee(int dice[]) { for(int i = 1; i < 5; i++) { if(dice[i] == dice[i-1]) continue; else return false; } return true; } bool fourOfaKind(int dice[]) { int counter = 1; for(int i = 1; i < 5; i++) { if(dice[i] == dice[i-1]) counter++; else break; } if(counter == 4) return true; else return false; } bool threeOfaKind(int dice[]) { int counter = 1; for(int i = 1; i < 5; i++) { if(dice[i] == dice[i-1]) counter++; else break; } if(counter == 3) return true; else return false; } bool aPair(int dice[]) { int counter = 1; for(int i = 1; i < 5; i++) { if(dice[i] == dice[i-1]) counter++; else break; } if(counter == 2) return true; else return false; } int keep(int num, int dice[]) { int counter = 0; for(int i = 0; i < 5; i++) if(dice[i] == num) counter++; for(int j = 0; j < 5; j++) if(j < counter) dice[j] = num; else dice[j] = 0; return counter; } void sort(int dice[]) { int num = dice[0]; int idx = 0; for(int i = 1; i < 5; i++) { if(dice[i] != num) { if(idx == 0) idx = i; else idx++; } else { int temp = dice[idx]; dice[i] = dice[idx]; dice[idx] = num; } } } <file_sep>/csc402/assignment6/arrayBsTree.cpp /* Author: <NAME> File: treeGraph.cpp Date: 10/18/2015 Class: CSC 402 About: Code file for the treeGraph class. treeGraph is able to instantiate itself through a constructor by first having the root point to null. After construction, the user may insert elements in the binary tree. If the user chooses, he or she may print the tree in the way of three traversals. In Order NRL (Node Right Left) prints the list from least to greatest. Pre Order LNR (Left Node Right) and Post Order LRN (Left Right Node) preserves the tree in list form. */ #include <iostream> #include <queue> #include "arrayBsTree.h" using namespace std; /* Function: Constructor MemberType: Constructor Permission: Public Parameters: N/A ReturnValue: N/A About: Constructs the treeGraph by pointing the root to null */ arrayBsTree::arrayBsTree() { root = NULL; } /* Function: find MemberType: Inspector Permission: Public Parameters: int - import only ReturnValue: true - if found false - if not found About: Traverses the tree looking for a node's data that is equal to the parameter's value */ bool arrayBsTree::find(int info) const { treeNode<int> *currNode = root; while(currNode != NULL) { if(info == currNode->data) return true; else if(info < currNode->data) currNode = currNode->left; else currNode = currNode->right; } return false; } /* Function: insert MemberType: Mutator Permission: Public Parameters: int - import only ReturnValue: void About: Imports a given value into the tree. If the tree is empty, the root will create a new node with the value of the given value. If the tree is not empty, the given value will be compared to the data of each node by going the left child if the given value is less than the current node's data or right if the value is greater. NodeCount is incremented after a proper insertion point is found. */ void arrayBsTree::insert(int info) { if(root == NULL) //if there is an empty tree { root = new treeNode<int>(info); return; } treeNode<int> *currNode = root, *parent; while(currNode != NULL) //while there isn't an empty space { parent = currNode; if(info < currNode->data) //Go left is lesser than currNode = currNode->left; else //Go right if greater than currNode = currNode->right; } if(info < parent->data) parent->left = new treeNode<int>(info); else parent->right = new treeNode<int>(info); nodeCount++; } /* Function: erase MemberType: Mutator Permission: Public Parameters: int - import only ReturnValue: void About: First checks if the node to be erased is in the tree, if the node is in the tree, the node is deleted and if necessary a replacement will fill its spot */ void arrayBsTree::erase(int doomed) { if(!find(doomed)) return; treeNode<int> *nodeWithData, *nodeToDelete, *p = root, *trailP = NULL; while(p->data != doomed) { trailP = p; if(doomed < p->data) p = p->left; else p = p->right; } nodeWithData = p; if(nodeWithData->left == NULL && nodeWithData->right == NULL) { if(nodeWithData == root) root = NULL; else if(trailP->right == nodeWithData) //Parent's right child trailP->right = NULL; else trailP->left = NULL; nodeToDelete = nodeWithData; //free this at the end } else if(nodeWithData->left == NULL) { if(trailP == NULL) { // Node to delete is root and there is no left subtree nodeToDelete = root; root = root->right; } else //Point parent's pointer to this node to this node's right child { if(trailP->right == nodeWithData) trailP->right = nodeWithData->right; else trailP->left = nodeWithData->right; nodeToDelete = nodeWithData; } } else if(nodeWithData->right == NULL) { if (trailP == NULL) { // Node to delete is root and there is no left subtree nodeToDelete = root; root = root->left; } else { // Otherwise, move up the right subtree if(trailP->right == nodeWithData) trailP->right = nodeWithData->left; else trailP->left = nodeWithData->left; nodeToDelete = nodeWithData; } } else { for(trailP = nodeWithData, p = nodeWithData->left; p->right != NULL; trailP = p, p = p->right); nodeWithData->data = p->data; if(trailP == nodeWithData) trailP->left = p->left; else trailP->right = p->left; nodeToDelete = p; } delete nodeToDelete; } /* Function: inOrder MemberType: Inspector Permission: Public Parameters: ostream - export only ReturnValue: void About: Prints the tree in order by giving the helper function the starting point of the root */ void arrayBsTree::inOrder(ostream& out) const { printInOrder(root, out); } /* Function: printInOrder MemberType: Inspector Permission: Private Parameters: treeNode<int>* - import only ostream - export only ReturnValue: void About: Recursively prints the tree by going the left child until a left child cannot be found. Then that node is put in the ostream. Last go right and start the process again. LNR (Left Node Right). */ void arrayBsTree::printInOrder(treeNode<int>* currNode, ostream& out) const { if(currNode == NULL) return; printInOrder(currNode->left, out); out << currNode->data << " "; printInOrder(currNode->right, out); } /* Function: preOrder MemberType: Inspector Permission: Public Parameters: ostream - export only ReturnValue: void About: Prints the tree pre order by giving the helper function the starting point of the root */ void arrayBsTree::preOrder(ostream& out) const { printPreOrder(root, out); } /* Function: printPreOrder MemberType: Inspector Permission: Private Parameters: treeNode<int>* - import only ostream - export only ReturnValue: void About: Recursively prints the tree by putting the current node in the ostream, then going to the left child. If no left child can be found, go to the right child and start the process again. NRL (Node Right Left). */ void arrayBsTree::printPreOrder(treeNode<int>* currNode, ostream& out) const { if(currNode == NULL) return; out << currNode->data << " "; printPreOrder(currNode->left, out); printPreOrder(currNode->right, out); } /* Function: postOrder MemberType: Inspector Permission: Public Parameters: ostream - export only ReturnValue: void About: Prints the tree post order by giving the helper function the starting point of the root */ void arrayBsTree::postOrder(ostream& out) const { printPostOrder(root, out); } /* Function: printPostOrder MemberType: Inspector Permission: Private Parameters: treeNode<int>* - import only ostream - export only ReturnValue: void About: Recursively prints the tree by going the left child until a left child cannot be found. Then go to the right child and start the process again. If no more children can be found, both left and right, put the current node in the ostream. LRN (Left Right Node). */ void arrayBsTree::printPostOrder(treeNode<int>* currNode, ostream& out) const { if(currNode == NULL) return; printPostOrder(currNode->left, out); printPostOrder(currNode->right, out); out << currNode->data << " "; } /* Function: lvlOrder MemberType: Inspector Permission: Public Parameters: ostream - export only ReturnValue: void About: Prints the tree in order by height (level) starting at the root */ void arrayBsTree::lvlOrder(ostream& out) const { printLvlOrder(root, out); } /* Function: printLvlOrder MemberType: Inspector Permission: Private Parameters: treeNode<int>* - import only ostream - export only ReturnValue: void About: Uses a queue to order the tree by level. The root is put in the queue, then the root's left child, then its right child. A dummy node is put in the queue to determine a new level in the tree. The process repeats for each child in the tree */ void arrayBsTree::printLvlOrder(treeNode<int>* root, ostream& out) const { queue<treeNode<int> *> q; treeNode<int> *lvl = new treeNode<int>(-1); if(root != NULL) { out << root->data << endl; q.push(root->left); q.push(root->right); q.push(lvl); } treeNode<int> *currNode = root; while(!q.empty()) { currNode = q.front(); q.pop(); if(currNode == lvl) { if(!q.empty()) { q.push(lvl); out << endl; } } else if(currNode != NULL) { out << currNode->data << " "; q.push(currNode->left); q.push(currNode->right); } } } <file_sep>/csc136/project4/types.tpp /* File: types.tpp Author: <NAME> Updated By: <NAME> Course: CSC136 Assignment: Project 4 Description: Necessary to make the LinkedList object compatible with Term objects. */ // Explicit Initializers. Necessary to be able to be able to place // template class function implementations in a .cpp file #include "term.h" template class node<Term>; template class LinkedList<Term>; template class listItr<Term>; template ostream& operator<<(ostream &os,const LinkedList<Term> &l); <file_sep>/csc136/project4/temp.cpp /* File: LinkedList.cpp Author: <NAME> Updated by: <NAME> Course: CSC136 Assignment: Project 4 Description: Code that implements the LinkedList class. makes it possible that the LinkedList, node and listItr work together to create one object. */ #include <assert.h> #include <iostream> #include "LinkedList.h" // Construct empty LinkedList template <typename eltType> LinkedList<eltType>::LinkedList() : head(NULL) {} // Copy constructor. copy() does the deep copy template <typename eltType> LinkedList<eltType>::LinkedList(const LinkedList<eltType> &cl) {head = copy( cl.head );} // Free all nodes template <typename eltType> LinkedList<eltType>::~LinkedList() {destroy(head);} // Assignment operator: copy() does the deep copy template <typename eltType> LinkedList<eltType> &LinkedList<eltType>::operator =(const LinkedList<eltType>& cl) { if (this != &cl) { destroy(head); head = copy(cl.head); } return *this; } // Place x into the list in order template <typename eltType> bool LinkedList<eltType>::orderedInsert(eltType x) { if (empty() || x > head->data) assert(head=new node<eltType>(x,head)); else // start at 2nd node...already checked first node { node<eltType>* p = head -> next; // head; node<eltType>* trailp = head; // NULL; while (p != NULL && x < p->data) { trailp = p; p = p->next; } //Check if there's a duplicate if(find(x)) { p->data += x; //Add coefficients together return false; } else //If there's no duplicate { assert((trailp->next = new node<eltType>(x,p)) != NULL); return true; } } } // Is this element in the linked list? template <typename eltType> bool LinkedList<eltType>::find(eltType x) { node<eltType> *p = head; while (p != NULL && p->data > x) p = p->next; return (p != NULL && p->data == x); } // Inline: Look into this. template <typename eltType> inline bool LinkedList<eltType>::empty() {return (head == NULL);} // Remove a node in an ordered list // Pre: Node will be found template <typename eltType> bool LinkedList<eltType>::remove(eltType x) { assert( !empty() ); node<eltType>* p = head; node<eltType>* trailp = NULL; while ( p != NULL && p->data > x ) { trailp = p; p = p->next; } if(p->data == x) { if (p == head) head = head->next; // x is first in the LinkedList else trailp->next = p->next; // x is farther down in the LinkedList delete p; return true; } else return false; } // Remove all nodes in the linked list, starting at l template <typename eltType> void LinkedList<eltType>::destroy(node<eltType> *l) { while (l != NULL) { node<eltType> *doomed = l; l = l->next; delete doomed; } } // The deep copy. Copy the source list l, one node at a time template <typename eltType> node<eltType>* LinkedList<eltType>::copy(node<eltType> *l) { node<eltType>* first = NULL; // ptr to beginning of copied LinkedList node<eltType>* last = NULL; // ptr to last item insert in the copy if (l != NULL) { assert((first=last=new node<eltType>(l->data,NULL)) != NULL); for (node<eltType>* source=l->next;source!=NULL; source=source->next,last=last->next) { last->next = new node<eltType>(source->data,NULL); assert(last->next); } } return first; } // Output a linked list, using a list iterator template <typename eltType> ostream& operator<<(ostream &os,const LinkedList<eltType> &l) { listItr<eltType> lt(l); while ( lt.more() ) { os << lt.value(); lt.next(); } return os; } // Count nodes in a linked list, starting at l template <typename eltType> int LinkedList<eltType>::countNodes(node<eltType> *p) {return ((p) ? 1+countNodes(p->next) : 0);} // Return number of nodes in *this' list template <typename eltType> int LinkedList<eltType>::countNodesInList() {return(countNodes(head));} /* **************************************************************** ************** List Iterator Implementations ******************* ****************************************************************/ // Construct a list iterator. It consists of: // a reference to a linked list object // a pointer to the actual list, initially pointing to its head template <typename eltType> listItr<eltType>::listItr(const LinkedList<eltType> &l): itr(l),curr(l.head) {} // Set curr to point at itr's head template <typename eltType> void listItr<eltType>::start(void) {curr = itr.head;} // Is curr at the end of the list? template <typename eltType> bool listItr<eltType>::more(void) {return curr != NULL;} // Move curr to next node template <typename eltType> void listItr<eltType>::next(void) {assert( curr != NULL ); curr = curr->next; } // Return data in curr's node. Regardless of assert(), this // function shouldn't be called until making sure more() returns true template <typename eltType> eltType &listItr<eltType>::value(void) const {assert( curr != NULL ); return curr->data; } /* File: types.tpp Author: Dr. Spiegel Updated By: <NAME> Course: CSC136 Assignment: Project 4 Description: Necessary to make the LinkedList object compatible with Term objects. */ // Explicit Initializers. Necessary to be able to be able to place // template class function implementations in a .cpp file #include "term.h" template class node<Term>; template class LinkedList<Term>; template class listItr<Term>; template ostream& operator<<(ostream &os,const LinkedList<Term> &l); <file_sep>/csc520/finalproj/src/com/library/business_layer/message_list/BorrowedBookHome.java package com.library.business_layer.message_list; import com.library.business_layer.field_list.BorrowedBook; import com.library.business_layer.field_list.BorrowedBookMember; import com.library.business_layer.field_list.Member; import com.library.persistence_layer.*; import java.util.ArrayList; import java.util.Date; /** * BorrowedBookHome serves as a way to access the BorrowedBook and * BorrowedBookMember Tables. Thus it also serves as an accessor to each * table element attributes. Another purpose of BorrowedBook Home is * to create and add any new entries to the BorrowedBook and BorrowedBookMember Tables. * BUSINESS LAYER CLASS * @see com.library.business_layer.field_list.BorrowedBook * @see com.library.business_layer.field_list.BorrowedBookMember */ public class BorrowedBookHome { private Table bbTable; private Table bbmTable; /** * Basic constructor for BorrowedBookHome that instantiates home's Tables. */ public BorrowedBookHome() { bbTable = new DataSchema.BorrowedBookTable(); bbmTable = new DataSchema.BorrowedBookMemberTable(); } /** * Gets the BorrowedBook Table as a whole. * @return DataSchema.BorrowedBookTable */ public DataSchema.BorrowedBookTable getBorrowedBooks() { return (DataSchema.BorrowedBookTable) bbTable; } /** * Gets the BorrowedBookMember Table as a whole. * @return DataSchema.BorrowedBookMemberTable */ public DataSchema.BorrowedBookMemberTable getBorrowedBookMembers() { return (DataSchema.BorrowedBookMemberTable) bbmTable; } /** * Finds a Borrowed by its primary key identifier. * @param id int * @return BorrowedBook */ public BorrowedBook findByPrimaryKey(int id) { return (BorrowedBook) bbTable.selectId(id); } /** * Creates a new BorrowedBook and appends it to the BorrowedBookTable and * BorrowedBookMemberTable. * @param num String borrowed book number * @param startDate Date borrowed book start date * @param dueDate Date borrowed book due date * @param mid int member id * @return the newly created BorrowedBook */ public BorrowedBook create(String num, Date startDate, Date dueDate, int mid) { int key = bbTable.nextKey(); BorrowedBook newBorrowedBook = new BorrowedBook(key, num, startDate, dueDate); BorrowedBookMember newBorrowedBookMember = new BorrowedBookMember(key, mid); bbTable.append(newBorrowedBook); bbmTable.append(newBorrowedBookMember); return newBorrowedBook; } /** * Finds all BorrowedBooks connected to a specific Member. * @param m Member to find borrowed books for * @return ArrayList of the member's borrowed books */ public ArrayList<BorrowedBook> findByMember(Member m) { ArrayList<BorrowedBookMember> tmp = new ArrayList<>(); ArrayList<BorrowedBook> out = new ArrayList<>(); tmp = bbmTable.selectWhere("memberId", m.getId()); //Go through member table to find all connected borrowed books for(BorrowedBookMember mem : tmp) { out.add((BorrowedBook) bbTable.selectId(mem.getBorrowedBookId()) ); } return out; } /** * Force the update of all BorrowedBookHome Tables. */ public void update() { bbTable.updateList(); bbmTable.updateList(); } }<file_sep>/csc136/testdebugger/demo.h // File: Demo.h // Debug exercise to learn how classes and the debugger work #ifndef DEMO_H #define DEMO_H class Demo { public: Demo(int = 10, double = 50.0); // constructor Demo(const Demo&); // copy constructor ~Demo(); // destructor int getX() const; // inspector for x Demo operator=(const Demo &); // overloaded assignment Demo operator++(int); // postincrement private: int x; double y; }; #endif <file_sep>/csc520/finalproj/src/com/library/business_layer/field_list/Displayable.java package com.library.business_layer.field_list; import java.io.Serializable; /** * A Displayable represents a reservation that must be returned to the display * area i.e. member failed to collect. Dispalyable contains the reason the * reservation returned to display area, the foreign key to reservation id, * and a unique identifier. Identifiers are meant to act similar to a primary * key in a database and as such should be unique. Also implements Serializable * so it can be serialized for later use. * BUSINESS LAYER CLASS * @see com.library.business_layer.field_list.Reservation */ public class Displayable implements Serializable { private int id; private String reason; private int reservationId; /** * Contstructs Displayble Object by setting its attributes to a value. * @param i identifier * @param r reason * @param ri reservation id */ public Displayable(int i, String r, int ri) { setId(i); setReason(r); setReservationId(ri); } /** * Gets the int identifier value for this Object. * @return id as int */ public int getId() { return id; } /** * Gets the reason the reservation was terminated. * @return reason String */ public String getReason() { return reason; } /** * Gets the indentifier for the reservation. * @return reservation id int */ public int getReservationId() { return reservationId; } /** * Sets the value for the Object identifier. * @param i int to set id to */ public void setId(int i) { id = i; } /** * Sets the value for the reason the reservation was terminated. * @param r String to set reason to */ public void setReason(String r) { reason = r; } /** * Sets the value for the reservation id. * @param i int to set reservation id to */ public void setReservationId(int i) { reservationId = i; } }<file_sep>/csc135/driverExam_ChristianCarreras.cpp /************************************************** This program opens a file and uses the information within to display if the student passed the test as well as how many they got right/wrong and which numbers on the test the got wrong. Author: <NAME> Due Date: 12/11/2012 **************************************************/ #include <iostream> #include <fstream> //Required to open file using namespace std; //Function prototype char getAnswers(ifstream &fp); int main() { ifstream fp; //Correct answers for the driving test char correct_answers[20]={'B', 'D', 'A', 'A', 'C', 'A', 'B', 'A', 'C', 'D', 'B', 'C', 'D', 'A', 'D', 'C', 'C', 'B', 'D', 'A'}; char student_answer[20]; int student_grade[20]; int counter1 = 0; //Number right int counter2 = 20; //Number wrong //Open file driving.dat fp.open("driving.dat"); if(!fp) { cout << "Error opening file\n"; return 0; } //Header table cout << "Passed\t\tCorrect\t\tWrong\t\tNumbers Wrong\n"; cout << "--------------------------------------------------------------\n"; //Gets information from getAnswers and displays information for(int i = 0; i < 20; i++) { student_answer[i] = getAnswers(fp); if(student_answer[i] == correct_answers[i]) { student_grade[i] = 1; counter1++; counter2--; } else student_grade[i] = 0; } if(counter1 < 15) { cout << "No\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } else { cout << "Yes\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } //Reset cout << endl; counter1 = 0; counter2 = 20; //Same for(int i = 0; i < 20; i++) { student_answer[i] = getAnswers(fp); if(student_answer[i] == correct_answers[i]) { student_grade[i] = 1; counter1++; counter2--; } else student_grade[i] = 0; } if(counter1 < 15) { cout << "No\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } else { cout << "Yes\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } //Reset cout << endl; counter1 = 0; counter2 = 20; //Same for(int i = 0; i < 20; i++) { student_answer[i] = getAnswers(fp); if(student_answer[i] == correct_answers[i]) { student_grade[i] = 1; counter1++; counter2--; } else student_grade[i] = 0; } if(counter1 < 15) { cout << "No\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } else { cout << "Yes\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } //Reset cout << endl; counter1 = 0; counter2 = 20; //Same for(int i = 0; i < 20; i++) { student_answer[i] = getAnswers(fp); if(student_answer[i] == correct_answers[i]) { student_grade[i] = 1; counter1++; counter2--; } else student_grade[i] = 0; } if(counter1 < 15) { cout << "No\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } else { cout << "Yes\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } //Reset cout << endl; counter1 = 0; counter2 = 20; //Same for(int i = 0; i < 20; i++) { student_answer[i] = getAnswers(fp); if(student_answer[i] == correct_answers[i]) { student_grade[i] = 1; counter1++; counter2--; } else student_grade[i] = 0; } if(counter1 < 15) { cout << "No\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } else { cout << "Yes\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } //Reset cout << endl; counter1 = 0; counter2 = 20; //Same for(int i = 0; i < 20; i++) { student_answer[i] = getAnswers(fp); if(student_answer[i] == correct_answers[i]) { student_grade[i] = 1; counter1++; counter2--; } else student_grade[i] = 0; } if(counter1 < 15) { cout << "No\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } else { cout << "Yes\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } //Reset cout << endl; counter1 = 0; counter2 = 20; //Same for(int i = 0; i < 20; i++) { student_answer[i] = getAnswers(fp); if(student_answer[i] == correct_answers[i]) { student_grade[i] = 1; counter1++; counter2--; } else student_grade[i] = 0; } if(counter1 < 15) { cout << "No\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } else { cout << "Yes\t\t" << counter1 << "\t\t" << counter2 << "\t\t"; for(int i = 0; i < 20; i++) { if(student_grade[i] == 0) { cout << i + 1 << " "; } } } cout << endl; return 0; } //This function directs the information from the file to an array char getAnswers(ifstream &fp) { char student_answer[20]; while(fp.eof()==false) { for(int i = 0; i < 20; i++) { fp>>student_answer[i]; return student_answer[i]; } } } <file_sep>/csc520/finalproj/src/com/library/test/LibraryTestData.java package com.library.test; import com.library.business_layer.message_list.*; import java.util.Date; /** * Creates and inserts test data to be used in a client. Will only create if * the data Tables are empty as to not duplicate entries. */ public class LibraryTestData { private static MemberHome mh = new MemberHome(); private static CategoryHome cath = new CategoryHome(); private static PublisherHome pubh = new PublisherHome(); private static ReservationHome resh = new ReservationHome(); private static BorrowedBookHome bbh = new BorrowedBookHome(); private static CatalogedBookHome cbh = new CatalogedBookHome(); private static ReservationStateHome rsth = new ReservationStateHome(); private static CatalogedBookDetailsHome cbdh = new CatalogedBookDetailsHome(); public static void create() { if(!testDataExists()) { //If all tables are empty, create and add data //Create Member mh.create("<NAME>", "555-555-5555", 0, true, "1234", 1, 1, 1); mh.create("Visa", "0000-0000-0000-0001", new Date()); mh.create("111", "Kutztown Ln.", "Berks", "18091"); mh.create("pass", -1); //Borrowed Books for Member bbh.create("0001", new Date(), new Date(2018 - 1900, 5, 11), 1); bbh.create("0002", new Date(), new Date(2018 - 1900, 5, 13), 1); bbh.create("0003", new Date(), new Date(2018 - 1900, 5, 21), 1); bbh.create("0004", new Date(), new Date(2018 - 1900, 5, 30), 1); //CatalogedBooks cbh.create("12as20aef09", "Apples & Oranges", 8, 1, 1); cbh.create("12as20aef08", "Another Slice of Pie", 4, 2, 1); cbh.create("12as20aef07", "<NAME>", 4, 3, 2); cbh.create("12as20aef06", "The Dog in the Hat", 8, 4, 3); cbh.create("12as20aef05", "Something Wild This Way Comes", 9, 5, 4); cbh.create("12as20aef04", "123 ABC", 8, 6, 1); cbh.create("12as20aef03", "Alligator Bop!", 12, 7, 5); cbh.create("12as20aef02", "X-Rays and You. Invisible Helpers!", 3, 8, 3); cbh.create("12as20aef01", "<NAME>", 8, 9, 6); cbh.create("12as20aef00", "Me, Myself and I", 1, 10, 2); cbh.create("12as20aee99", "So How Far Away Is The Moon?", 2, 11, 3); //CatalogedBooksDetails cbdh.create("1", new String[] {"Carreras"}, "Learn the difference between many things in life!"); cbdh.create("2", new String[] {"Pesto"}, "What makes a perfect pizza? Insider secrets they do not want you to know!"); cbdh.create("1", new String[] {"Richardson", "Belcher"}, "Cook the Bob way! It goes great with fries!"); cbdh.create("3", new String[] {"Carreras"}, "What is better than a cat in a hat? Nothing, but a dog in a hat comes close."); cbdh.create("1", new String[] {"Sanchez"}, "Can this brother and sister duo escape the horrors left by their grandfather?"); cbdh.create("1", new String[] {"Smith", "Anderson"}, "A book for a perfectly normal human toddler."); cbdh.create("2", new String[] {"Baggins"}, "How I came to grips with my insecurity at the slopes of Mt. Doom."); cbdh.create("2", new String[] {"Baggins"}, "Absolutely harmless gamma radiation all for the taking!"); cbdh.create("4", new String[] {"Catlady"}, "How many cats are enough? The answer will surprise you."); cbdh.create("1", new String[] {"Hawking", "Descartes", "Strange"}, "Who am I? Do I think therefore I am?"); cbdh.create("3", new String[] {"Skywalker"}, "Is that a moon? That does not seem like a moon."); //Categories cath.create("Fiction"); cath.create("Non-Fiction"); cath.create("Educational"); cath.create("Cooking"); cath.create("Sports"); cath.create("History"); cath.create("Sci-Fi"); cath.create("Kids"); cath.create("Horror"); cath.create("Romance"); cath.create("Classic"); cath.create("Biography"); //Publishers pubh.create("Stoneyfarm Publ."); pubh.create("C&C Inc."); pubh.create("KU Printing"); pubh.create("Allman Sisters"); pubh.create("Sunrise Valley"); pubh.create("SuperDuper Co."); } } /** * Checks to see if all tables are empty. * @return true if all tables are empty, false if not */ private static boolean testDataExists() { int size = bbh.getBorrowedBooks().size() + bbh.getBorrowedBookMembers().size() + cbh.getCatalogedBooks().size() + cbdh.getCatalogedBookDetails().size() + cath.getCategories().size() + mh.getMembers().size() + mh.getInternetAccounts().size() + mh.getCreditCards().size() + mh.getAddresses().size() + pubh.getPublishers().size() + resh.getReservations().size() + rsth.getCollectables().size() + rsth.getConcluded().size() + rsth.getDisplayables().size() + rsth.getNeedingRenewals().size() + rsth.getNotifiables().size() + rsth.getWaiting().size(); if(size <= 0) { return false; } else { return true; } } } <file_sep>/csc242/PracticeFiles/sessFile2.php <?php $_SESSION['num'] = $_SESSION['num'] - 1; echo "sessTest, num = " . $_SESSION['num'] . "<br/>"; echo "<a href = 'sessFile1.php'>File-1</a> &nbsp; <a href = 'sessFile2.php'>File-2</a> &nbsp;"; echo "<a href = 'sessTest.php'>Home</a>"; ?><file_sep>/csc558/README.txt CSC 558 - Data Mining and Predictive Analytics II Dr. <NAME> Kutztown University Spring 2018 This course covers advanced study and practice in data mining and predictive analytics. Topics include understanding, configuring, and applying advanced variants of data association, classification, clustering, and statistical analysis engines, analyzing and applying underlying machine learning algorithms, exploring instance-based, support vector, time-series, ensemble, graphical, and lazy learning algorithms, meta-learning, neural nets, genetic algorithms, and validating results. The course examines topics specific to very large data sets. Data cleaning and formatting require some programming in a modern scripting language. Other course activities include using, extending, and customizing off-the-shelf machine learning software systems to accomplish the tasks of data analysis. <file_sep>/csc136/project3b/poly.h // Author: <NAME> // Updated By: <NAME> // Course: CSC136 // Assignment: Project 2 // Filename: poly.h // Purpose: Definition of the Polynomial Class // This class provides the user the functionality of a polynomial, including // the ability to add terms, evaluate, and multiply the coefficients. // It also provides basic set and get functionality. // A function is provided to read terms from a file, and two associated // non-member, non-friend stream operators are present for reading a Term // and outputting the Polynomial in its entirety. #ifndef POLY_H #define POLY_H #include <iostream> #include <string> #include "Array.h" #include "term.h" using namespace std; class Polynomial { public: ////// // Constructor ////// Polynomial(); ////// // Gets and Sets ////// // Sets /* Function: setTerm Member Type: Mutator Description: Sets the term in the variable at a specific index Parameters: int index - input - the index at which the values are stored float co - input - the coefficient int ex - input - the exponent Returns: true if the value is set, false if not */ bool setTerm(int index, float co, int ex); /* Function: setCoeff Member Type: Mutator Description: Sets the coefficient for a term in the variable at a specific index Parameters: int index - input - the index at which the values are stored float co - input - the coefficient for the user Returns: true if the value is set, false if not */ bool setCoeff(int index, float co); /* Function: setExponent Member Type: Mutator Description: Sets the exponent for the term in the variable at a specific index Parameters: int index - input - the index at which the values are stored int ex - input - the exponent for the user Returns: true if the value is set, false if not */ bool setExponent(int index, int ex); // Gets /* Function: getArray Member Type: Inspector Description: Gives the user the Array object Parameters: none Returns: the Array object */ Array& getArray(); /* Function: getTerm Member Type: Inspector Description: Gives the user the values associated with the terms at the index Parameters: int index - input - the index at which the values are stored Returns: The requested Term Precondition: index is an in use (active) index */ Term getTerm(int index) const; /* Function: getCoeff Member Type: Inspector Description: Gets the user the coefficient at a certain index Parameters: int index - input - the index at which the values are stored Returns: The requested coefficient Precondition: index is an in use (active) index */ float getCoeff(int index) const; /* Function: getExponent Member Type: Inspector Description: Gets the user the exponent for a certain index Parameters: int index - input - the index at which the values are stored Returns: The requested exponent Precondition: index is an in use (active) index */ int getExponent(int index) const; /* Function: operator () Member Type: Facilitator Description: Evaluate the polynomial for variable x Parameters: x - input - variable that is standing for value of x Returns: The polynomial evaluated for x */ double operator()(double x) const; /* Function: multiply Member Type: Mutator Description: Multiply each coefficient by the scalar arg factor Parameters: fact - input - variable that is multiplying against all the coefficents Returns: void */ void operator *=(float factor); /* Function: add Member Type: Mutator Description: Add a term to the polynomial Parameters: coefficent - input - the coefficent of the term being added exponent - input - the exponent of the term being added Returns: true if the term is added, false otherwise */ bool add(float coefficient, int exponent); /* Function: add Member Type: Mutator Description: Add a term to the polynomial Parameters: T - input - the Term being added Returns: true if the term is added, false otherwise */ bool add(Term &T); /* Function: readFile Member Type: Mutator Description: Loads up the terms from a user declared filename Parameters: file - input/output - stream variable Returns: void */ void readFile(ifstream &file); private: Array A; }; /* Function: operator >> Description: Reads in a Term from a file Parameters: ifstream file - input/output - the input stream Polynomial - output only - the Polynomial that will hold the data read in Returns: ifstream */ ifstream &operator >>(ifstream &file, Polynomial&); /* Function: operator << Description: Print a Polynomial to the screen Parameters: out - input/output - output stream P - input - The Polynomial to print Returns: void */ ostream &operator <<(ostream &out, Polynomial &P); #endif <file_sep>/csc402/assignment2/BankAccount.cpp #include <iostream> #include <iomanip> #include "BankAccount.h" using namespace std; BankAccount::BankAccount() { setAccountNumber(1234567890); setBalance(0.00); } BankAccount::BankAccount(int n, float b) { setAccountNumber(n); setBalance(b); } void BankAccount::setAccountNumber(int n) { accountNumber = n; } int BankAccount::getAccountNumber() { return accountNumber; } void BankAccount::deposit(double amount) { setBalance(getBalance()+amount); } void BankAccount::withdraw(double amount) { if((getBalance() - amount) < 0) { if(getBalance() < 0) setBalance(getBalance()-35); //$35 penalty else { setBalance(0); //withdraw to zero setBalance(getBalance()-35); //minus $35 overdraft fee } } else setBalance(getBalance()-amount); } void BankAccount::monthEnd() { } void BankAccount::setBalance(float amount) { balance = amount; } double BankAccount::getBalance() { return balance; } void BankAccount::printAccount(ostream &out) { out << "$" << getBalance() << endl; }<file_sep>/csc520/assignment1/a1Test.java /* * Author: <NAME> * File Name: a1Test.java * Creation Date: 01/30/2018 * Due Date: 02/12/2018 * Course: CSC 520 - Advanced Object Oriented Programming * Professor Name: Dr. Schwesinger * Assignment: #1 * Major: MS Software Development * Institution: Kutztown University of Pennsylvania * Purpose: To implement the code-based equivalent of a UML class * diagram. The UML diagram depicts three seperate classes * that have an aggregated relationship. The three classes are * Card, Deck, and Hand. Deck and Hand are dependent on * Card but are not aware of each other. All attributes and * operations are implemented along with other hidden basics * in order to get everything hooked up and running i.e. * construction, facilitation, and inspection needs. * * JavaDoc Link: http://csitrd.kutztown.edu/~ccarr419/csc520/assignment1/ */ import java.util.List; import java.util.ArrayList; import com.csc520Code.*; /** * This class sole purpose is to fully test the functionality of the Card, Deck, * and Hand classes and show all exceptions. */ public class a1Test { /** * Main method starting the test session. * @param args list of command-line arguments */ public static void main(String[] args) { Deck deck = new Deck(); Hand hand = new Hand(); //Test toString function for Cards testShuffle(deck); //Test drawing cards from deck and adding it to hand testDraw(deck, hand); //Test sorting the hand testHandSort(hand); //Show that there are less cards in deck from drawing cards System.out.println("Current deck:" + deckToString(deck)); //Test contains for Hand testContains(hand); //Test failed addCard for Hand testAddDupHand(hand); //Test removeCard for Hand and addCard for Deck testHand2Deck(deck, hand); //Show the sortHand does not fail on empty hand hand.sortHand(); //Show that the deck is full again System.out.println("\nCurrent deck: " + deckToString(deck) + "\n"); //Show remaining add/remove card to/from deck possibilites testDeckCardFunc(deck); //Show that Card fails to be created upon improper format //THE PROGRAM IS SUPPOSED TO FAIL ON PURPOSE //THIS IS NOT AN ERROR ON MY PART //THIS IS MEANT TO DEMONSTRATE EXCEPTION CATCHING testExcepCard(); } /** * Tests the shuffle function for Deck. Shows before and after. * @param deck the deck to shuffle */ public static void testShuffle(Deck deck) { System.out.println("Current deck:" + deckToString(deck)); System.out.println("Shuffling deck..."); deck.shuffle(); //Test shuffle() for Deck System.out.println("Shuffled deck:" + deckToString(deck)); } /** * Tests drawing cards from the deck and adding them to the hand. * @param deck the deck to draw from * @param hand the hand to add the drawn card */ public static void testDraw(Deck deck, Hand hand) { System.out.println("\nDrawing cards from deck to hand..."); for(int i = 0; i < 5; i++) { Card card = deck.draw(); System.out.println("You drew: " + card.toString()); hand.addCard(card); System.out.println("Current hand: " + handToString(hand)); } } /** * Tests the sortHand function for Hand. Prints the shuffled hand. * @param hand the hand to shuffle */ public static void testHandSort(Hand hand) { System.out.println("\nSorting hand..."); hand.sortHand(); //Test sorting hand System.out.println("Sorted hand: " + handToString(hand)); } /** * Tests the contain function for Hand. Tests one case that can be true or * false (most likely false) and one case where it is always true. * @param hand the hand to check for cards */ public static void testContains(Hand hand) { Card c = new Card(4,2); //Check for a specific card if(hand.contains(c)) { System.out.println("\nThe hand contains " + c.toString()); } else { System.out.println("\nThe hand does not contain " + c.toString()); } //Check for a know card in the hand -- always true for contains List<Card> handList = new ArrayList<Card>(hand.toList()); c = handList.get(0); if(hand.contains(c)) { System.out.println("The hand contains " + c.toString()); } } /** * Tests the addCard function for Hand in an always fail scenario. * @param hand the hand to try and add a card to */ public static void testAddDupHand(Hand hand) { List<Card> handList = new ArrayList<Card>(hand.toList()); Card c = handList.get(0); if(hand.addCard(c) == false) { System.out.println("Cannot add card " + c.toString() + ", card is already within the hand\n"); } } /** * Tests removing all the cards from the hand and placing them in the deck. * @param deck the deck to add cards to * @param hand the hand to remove cards from */ public static void testHand2Deck(Deck deck, Hand hand) { Card c = new Card(4,2); for(int i = 4; i >= 0; i--) { Card tmpCard = removeFirstHand(hand); System.out.println("Removed " + tmpCard.toString() + " from hand " + "and added to deck"); System.out.println("Current hand: " + handToString(hand)); deck.addCard(tmpCard); } //Test failed removeCard for Hand if(!hand.removeCard(c)) { System.out.println("Cannot remove card " + c.toString() + ", card is not within the hand"); } } /** * Tests fail scenarios for removeCard, addCard, and draw, as well as others * for Deck. * @param deck the deck to test exceptions for */ public static void testDeckCardFunc(Deck deck) { Card c = new Card(4,2); //Test failed addCard for Deck if(!deck.addCard(c)) { System.out.println("Cannot add card " + c.toString() + ", card is already within the deck"); } //Test removeCard for Deck if(deck.removeCard(c)) { System.out.println("Card " + c.toString() + " was removed from deck"); } //Test failed draw for Deck System.out.println("Removing all cards from deck..."); removeAllDeck(deck); if(deck.draw() == null) { System.out.println("Cannot draw, no cards left!"); } //Test failed removeCard for Deck if(!deck.removeCard(c)) { System.out.println("Cannot remove card " + c.toString() + ", card is not within the deck"); } //Show empty deck System.out.println("Current deck: " + deckToString(deck)); deck.shuffle(); //Show that shuffle does not fail on empty deck } /** * Tests the exception catching of the Card class when given bad parameters * for its constructor. This will cause the program to crash since it is * deliberately creating and exception. */ public static void testExcepCard() { System.out.println("\nThis next line of code should fail...\n" + "I repeat, the program should now fail ON PURPOSE in order\n" + "to show the exception handling of the Card class.\n"); Card fake = new Card(-1,24); //There is no rank -1 so catch exception } /** * Removes the first card from the given Hand parameter. * @param hand the hand to remove the first card from */ public static Card removeFirstHand(Hand hand) { for(int i = 0; i < 4; i++ ) { for(int j = 0; j < 13; j++) { Card c = new Card(j, i); if(hand.contains(c)) { hand.removeCard(c); return c; } } } return null; } /** * Removes all cards from the given Deck parameter. * @param the deck to remove all the cards from */ public static void removeAllDeck(Deck deck) { for(int i = 0; i < 4; i++ ) { for(int j = 0; j < 13; j++) { Card c = new Card(j, i); deck.removeCard(c); } } } /** * Turns the given Hand into a String. Formated as a list of tuples. * @param hand the hand to turn into a String */ public static String handToString(Hand hand) { String outStr = ""; List<Card> handList = new ArrayList<Card>(hand.toList()); for(int i = 0; i < handList.size(); i++) { if(handList.get(i) != null) { outStr += ("[" + handList.get(i).getRank()); outStr += ("," + handList.get(i).getSuit() + "], "); } } return outStr; } /** * Turns the given deck into a String. Formated as a list of tuples. * @param deck the deck to turn into a String */ public static String deckToString(Deck deck) { String outStr = ""; List<Card> deckList = new ArrayList<Card>(deck.toList()); for(int i = 0; i < deckList.size(); i++) { if(deckList.get(i) != null) { if(i % 10 == 0) { outStr += "\n"; } outStr += ("[" + deckList.get(i).getRank()); outStr += ("," + deckList.get(i).getSuit() + "], "); } } return outStr; } } <file_sep>/csc552/project2/makefile # Author: <NAME> # File: makefile # Date: 03/07/2017 # Due Date: 03/11/2017 # Project: #2 # Course Num: CSC552 # Course Title: Advanced Unix Programming # Professor: Dr. Spiegel # School: Kutztown University of Pennsylvania # Semester: SPRING2017 # About: The purpose of this makefile is to compile each file # necessary in project #2. Each file can be compiled together # by issuing the command 'make' or 'make p2' or they can be # compiled individually by entering 'make client' or # 'make server'. This makefile uses the basic g++ compiler # and adds a debug flag in the case of gdb debugging needs. CC=/usr/bin/g++ DebugFlag=-g #Compile whole project, make sure everything is up to date p2: p2.cpp client.cpp server.cpp $(CC) $(DebugFlag) -o p2 p2.cpp $(CC) $(DebugFlag) -o client client.cpp $(CC) $(DebugFlag) -o server server.cpp #Compile just the client client: client.cpp $(CC) $(DebugFlag) -o client client.cpp #Compile just the server server: server.cpp $(CC) $(DebugFlag) -o server server.cpp <file_sep>/csc237/project2/types.tpp /* // Author: <NAME> // Course: CSC 237 // File: types.tpp // Purpose: Necessary for explicit initialization */ //Explicit Initializers. Necessary to be able to be able to place //template class function implementations in a .cpp file #include "Node.h" #include "WordData.h" template class node<int>; template class node<WordData>; template class DLinkedList<int>; template class DLinkedList<WordData>; template class DListItr<int>; template class DListItr<WordData>; <file_sep>/csc136/testdebugger/makefile CC=/opt/csw/gcc3/bin/g++ DebugFlag=-g debug: debug.o demo.o $(CC) -o debug demo.o debug.o $(DebugFlag) debug.o: debug.cpp demo.h $(CC) -c debug.cpp $(DebugFlag) demo.o: demo.cpp demo.h $(CC) -c demo.cpp $(DebugFlag) clean: \rm -f *.o debug <file_sep>/csc423/README.txt CSC 423 - Game Development for Computer Scientists II Mr. <NAME> Kutztown University Spring 2017 This course is a continuation of the subject matter of CSC 320, Games for Computer Scientists. In CSC 320 we cover the basics of game development from concept to storyboard to low-tech prototype to implementation using a game engine. In this course we will continue our study of game engines and look at some of the more advanced features of this game engine. We will be examining animation techniques, 3D modeling, rigging, gravity, and artificial intelligence. The student will implement at least two original games using these aspects of game development. Link to games: - Abyss: https://github.com/ccarr419/Abyss-Game - PsyBrawl: https://github.com/ccarr419/PsyBrawl-Game <file_sep>/csc242/Project/myproject.php <?php session_start(); $loggedin = $_SESSION['loggedin']; $name = $_SESSION['name']; /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/myproject.php Course: CSC 242 - Fall 2013 */ echo "<html xmlns = 'http://www.w3.org/1999/xhtml'> <head> <title> Chris' Book Store </title> <!-- My stylesheet for the project --> <link rel = 'stylesheet' type = 'text/css' href = 'projectstyle.css'/> </head> <body> <!-- Links --> <div class = 'header'><h1>Chris' Book Store</h1></div> <div class = 'special'> <h3><p class = 'one'> <a class = 'link' href = 'myproject.php'>Home</a> &nbsp; | &nbsp;"; if($loggedin == true) //Checks if the user is logged in echo "<a class = 'link' href = 'loggedout.php'>Log Out</a> &nbsp; | &nbsp;"; else echo "<a class = 'link' href = 'login.html'>Log In</a> &nbsp; | &nbsp;"; echo "<a class = 'link' href = 'createaccount.php'>Create Account</a> &nbsp; | &nbsp; <a class = 'link' href = 'contact.php'>Contact Us</a> &nbsp; | &nbsp; <a class = 'link' href = 'categories.php'>Categories</a> &nbsp; | &nbsp; <a class = 'link' href = 'searchstart.php'>Search</a> &nbsp; | &nbsp; <a class = 'link' href = 'orders.php'>View Orders</a> &nbsp; | &nbsp; <a class = 'link' href = 'viewcart.php'>View Cart</a> </p></h3> <br/> <!-- Opening page & disclaimer --> <h3><p class = 'one'>"; if($loggedin == true) echo "Welcome, " . $name . "!<br/><br/>"; //Displays user's name if logged in else echo "Welcome!<br/><br/>"; echo "This is Chris' Book Store!<br/> The ultimate site for purchasing books!<br/><br/> <div style = 'color: red'>Note: This site is not a legitimate book store and therefore<br/> will not and can not perform any transactions. This is just a class project.</div> </p></h3> </div> </body> </html>"; ?> <file_sep>/csc136/project2/poly.cpp #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cmath> #include "poly.h" using namespace std; //Constructor Polynomial::Polynomial(int s) { setSize(s); } ////////// //SETS ///////// /* Function: setTerm Member Type: Mutator Description: Sets the term in the variable at a specific index Parameters: int index - input - the index at which the values are stored float co - input - the coefficient int ex - input - the exponent Returns: true if the value is set, false if not */ bool Polynomial::setTerm(int index, float co, int ex) { termList[index].coeff = co; termList[index].expn = ex; return true; } /* Function: setCoeff Member Type: Mutator Description: Sets the coefficient for a term in the variable at a specific index Parameters: int index - input - the index at which the values are stored float co - input - the coefficient for the user Returns: true if the value is set, false if not */ bool Polynomial::setCoeff(int index, float co) { return(termList[index].coeff = co); } /* Function: setExponent Member Type: Mutator Description: Sets the exponent for the term in the variable at a specific index Parameters: int index - input - the index at which the values are stored int ex - input - the exponent for the user Returns: true if the value is set, false if not */ bool Polynomial::setExponent(int index, int ex) { return(termList[index].expn = ex); } ////////// //GETS ///////// /* Function: getTerm Member Type: Inspector Description: Gives the user the values associated with the terms at the index Parameters: int index - input - the index at which the values are stored Returns: The requested Term Precondition: index is an in use (active) index */ Term Polynomial::getTerm(int index) const { return termList[index]; } /* Function: getSize Member Type: Inspector Description: Furnishes the number of Terms in the Polynomial Parameters: none Returns: the number of Terms in the Polynomial */ int Polynomial::getSize() const { return size; } /* Function: getCoeff Member Type: Inspector Description: Gets the user the coefficient at a certain index Parameters: int index - input - the index at which the values are stored Returns: The requested coefficient Precondition: index is an in use (active) index */ float Polynomial::getCoeff(int index) const { return termList[index].coeff; } /* Function: getExponent Member Type: Inspector Description: Gets the user the exponent for a certain index Parameters: int index - input - the index at which the values are stored Returns: The requested exponent Precondition: index is an in use (active) index */ int Polynomial::getExponent(int index) const { return termList[index].expn; } /* Function: operator () Member Type: Facilitator Description: Evaluate the polynomial for variable x Parameters: x - input - variable that is standing for value of x Returns: The polynomial evaluated for x */ double Polynomial::operator()(double x) const { double answer; for(int i = 0; i < getSize(); i++) { //Multiply the coefficient by x^expn and add to total if(getExponent(i) > 1) answer = answer+(pow(x, getExponent(i))*getCoeff(i)); //Multiply the coefficient by x and add to total else if(getExponent(i) == 1) answer = answer+(x*getCoeff(i)); //Add the coefficient to total else if(getExponent(i) == 0) answer += getCoeff(i); } return answer; } /* Function: multiply Member Type: Facilitator Description: Multiply each coefficient by the scalar arg factor Parameters: fact - input - variable that is multiplying against all the coefficients Returns: void */ void Polynomial::operator*=(float factor) { for(int i = 0; i < getSize(); i++) setCoeff(i, termList[i].coeff*factor); } /* Function: add Member Type: Mutator Description: Add a term to the polynomial Parameters: coefficient - input - the coefficient of the term being added exponent - input - the exponent of the term being added Returns: true if the term is added, false otherwise */ bool Polynomial::add(float coefficient, int exponent) { //If size > 0, check for duplicate exponents if(getSize() > 0) { for(int i = 0; i < getSize(); i++) { //Add the coefficients together if exponents match if(exponent == getExponent(i)) { setCoeff(i, getCoeff(i)+coefficient); coefficient = 0; } } } //When the coefficient does not equal zero or the polynomial is full if(coefficient != 0 && getSize() < 10) { setCoeff(getSize(), coefficient); setExponent(getSize(), exponent); sort(); // Sort the array every time a new term is added setSize(getSize()+1);} //Increment size return true; } /* Function: add Member Type: Inspector Description: Add a term to the polynomial Parameters: T - input - the Term being added Returns: true if the term is added, false otherwise */ bool Polynomial::add(const Term &T) { return(add(T.coeff,T.expn)); } /* Function: readFile Member Type: Mutator Description: Loads up the terms from a user declared filename Parameters: file& - input/output - stream variable Returns: void */ void Polynomial::readFile(ifstream &file) { Term T; while(file >> T) add(T); file.close(); } /* Function: setSize Member Type: Mutator Description: Sets the term in the variable at a specific index. Private because the application programmer shouldn't be messing with this; # terms is a function of adding terms. Parameters: int s - input - the index of the last value in the term array Returns: N/A */ void Polynomial::setSize(int s) { //Number of terms should be between 0 and 10, if not set size to 10 size = (s >= 0 && s < 11) ? s : 10; } /* Function: sort Member Type: Facilitator Description: Organizes the polynomial from highest exponent to lowest. Parameters: none Returns: N/A */ void Polynomial::sort() { for(int spot = getSize(); spot > 0; spot--) { int idxMax = spot; for(int idx = 0; idx < spot; idx++) if(termList[idxMax].expn > termList[idx].expn) idxMax = idx; if(idxMax != spot) swap(termList[idxMax], termList[spot]); } } /* Function: swap Member Type: Mutator Description: Works with sort() to organize the polynomial from highest exponent to lowest. Parameters: Term &x - input - swap with Term y Term &y - input - swap with Term x Returns: N/A */ void Polynomial::swap(Term &x, Term &y) { Term temp = x; x = y; y = temp; } /* Function: operator >> Description: Reads in a Term from a file Parameters: ifstream file - input/output - the input stream Term T - output only - Term to data input Returns: ifstream */ ifstream &operator >>(ifstream &file, Term &T) { file >> T.coeff >> T.expn; return file; } /* Function: operator << Description: Print a Polynomial to the screen Parameters: out - input/output - output stream P - input - The Polynomial to print Returns: void */ ostream &operator <<(ostream &out, const Polynomial &P) { for(int i = 0; i < P.getSize(); i++) { //When the coefficient and exponent are greater than 1 if(P.getCoeff(i) > 1 && P.getExponent(i) > 1) { //If this is the last element in the polynomial if(i == P.getSize()-1) out << P.getCoeff(i) << "x^" << P.getExponent(i); else out << P.getCoeff(i) << "x^" << P.getExponent(i) << "+"; } //When the coefficient is equal to 1 but the exponent is greater than 1 else if(P.getCoeff(i) == 1 && P.getExponent(i) > 1) { if(i == P.getSize()-1) out << "x^" << P.getExponent(i); else out << "x^" << P.getExponent(i) << "+"; } //When the coefficient > 1 and the exponent = 1 else if(P.getCoeff(i) > 1 && P.getExponent(i) == 1) { if(i == P.getSize()-1) out << P.getCoeff(i) << "x"; else out << P.getCoeff(i) << "x+"; } //When both the coefficient and the exponent are equal to one else if(P.getCoeff(i) == 1 && P.getExponent(i) == 1) { if(i == P.getSize()-1) out << "x"; else out << "x+"; } //When the the exponent is zero else if(P.getExponent(i) == 0) out << P.getCoeff(i); //When the coefficient is 0 else if(P.getCoeff(i) == 0) out << ""; } return out; } /* Function: operator << Description: Write the Polynomial to a File Parameters: ofstream &out - input/output - The output file stream const Polynomial &P input - Polynomial to save Returns: ofstream - the output file stream */ ofstream &operator <<(ofstream &out, const Polynomial &P) { for(int i = 0; i < P.getSize(); i++) out << P.getCoeff(i) << " " << P.getExponent(i) << endl; return out; } <file_sep>/sideprojects/fractions/primes.cpp #include <iostream> #include "primes.h" #include <assert.h> #include <cmath> using namespace std; primes::primes(const int num) { setPrimes(num); setPowers(); } void primes::setPrimes(const int num) { for(int i = 2; i < num; i++) { for(int j = 2; j <= i; j++) { if(i == j) primeNum.push_back(i); else if(i % j == 0) break; } } } void primes::setPowers() { powers.resize(primeNum.size(), 0); } void primes::resetPrimes() { primeNum.clear(); } void primes::resetPowers() { powers.clear(); } void primes::printPrimes() { for(unsigned i = 0; i < primeNum.size(); i++) { cout << primeNum.at(i) << endl; } } int primes::gcd(int a, int b) { if(a == b) return a; else { int max = fmax(a, b); int min = fmin(a, b); assert(max > 0 && min > 0) if(max == 1 || min == 1) return(1); else { gcdMaxHelper(max, 0, 0); } } } void primes::gcdMaxHelper(int min, int prime, int power) { if(min == 1) return; else { do { powers[power] += 1; } while(min % pow(primeNum.at(prime), powers.at(power)) == 0); powers.at(power) -= 1; min = min/pow(primeNum.at(prime), powers.at(power)); gcdMaxHelper(min, prime++, power++); } } <file_sep>/csc552/project2/server.cpp /* * Author: <NAME> * File: server.cpp * Date: 03/07/2017 * Due Date: 03/11/2017 * Project: #2 * Course Num: CSC552 * Course Title: Advanced Unix Programming * Professor: Dr. Spiegel * School: Kutztown University of Pennsylvania * Semester: SPRING2017 * About: This file represents a server and communicates with a * client file wia pipes redirected towards stdin and stdout. * The pipe will receive messages from the client letting * the server know what commands to run. If the client sends * two floating-point numbers then a message consisting of * the sum, difference, product, and quotient of both numbers * is sent. The two numbers are then saved in a binary file * for further use. If the client sends the string 'TOTAL' * then a message holding the sum of every number entered to * to the server will be sent. Last if the client sends the * string 'EXIT' then a message comprised of every pair of * of floating point numbers is sent. */ #include <iostream> #include <sstream> #include <string> #include <cstring> #include <cstdio> #include <cstdlib> #include <iomanip> using namespace std; /// * Function Name: toFloat /// * Function Type: facilitator /// * Parameters: string - string to turn into a float /// * Return Value: float - the string turned into a float /// * \brief This function takes a single string as an integer and /// * converts it into a floating-point number. Stringstreams /// * are used to make this conversion possible. float toFloat(string); /// * Function Name: findFileSize /// * Function Type: facilitator /// * Parameters: FILE* - import only - file to find the size of /// * Return Value: long - the size of the file in bytes /// * \brief This function goes to the end of the file and counts how /// * many bytes are in the file which equally counts how many /// * characters are in the file. Once the size is found, seek /// * back to the beginning of the file so the server can read /// * the whole file if necessary. long findFileSize(FILE*); /// * Function Name: findTotal /// * Function Type: facilitator /// * Parameters: char[] - import only - string carrying the numbers to add /// * Return Value: int - the sum of all the numbers read /// * \brief This function reads through the single string argument and /// * separates each number contained within. Each number is /// * then added to a total sum. Once the end of the file has /// * been reached then the total sum calculated thus far is /// * returned. int findTotal(char[]); /// * Function Name: printAllNumbers /// * Function Type: facilitator /// * Parameters: char[] - import only - string carrying numbers to print /// * Return Value: void /// * \brief This function takes a single string as an argument and /// * separates all the numbers within the string. All the /// * numbers are printed in pairs separated by a space. Each /// * pair is separated by a newline. This is done until the end /// * of the file is reached. void printAllNumbers(char[]); /// * Function Name: printEquations /// * Function Type: facilitator /// * Parameters: string - import only - number 1 in string form /// string - import only - number 2 in string form /// * Return Value: void /// * \brief This function takes two strings as arguments which will /// * be converted into floating-point numbers immediately. /// * Once floating point numbers, the server will send a message /// * through stdout containing the sum, difference, product, /// * and quotient of the two numbers. This will be seen as /// * four columns and two rows. First row containing the header /// * descriptions i.e. sum, diff, etc. and the second containing /// * the actual values of those operations. void printEquations(string, string); /// * Function Name: writeToFile /// * Function Type: mutator /// * Parameters: string - import only - number 1 to write to file /// string - import only - number 2 to write to file /// FILE* - import/export - file to write to /// * Return Value: void /// * \brief This function takes three arguments. The first two /// * arguments are the numbers in string form to write to the /// * file. The third argument is the file to write to. This /// * function will write to the file in the following format: /// * "number *SPACE* number" by using fputs. This function /// * assumes that the file is created and open with write /// * permissions and does not care whether it is appending, /// * truncating or writing to a seeked location. void writeToFile(string, string, FILE*); /// * Function Name: shutDownServer /// * Function Type: mutator /// * Parameters: FILE* - import/export - file to close /// * Return Value: void /// * \brief This function takes one file reference as an argument. It /// * will close the given file, close all open pipes (which will /// * be stdin - 0 and stdout - 1). The buffer will also be /// * flushed as a precautionary. This function should be the /// * last function called before exiting. void shutDownServer(FILE*); /// \file /// * \brief This file represents a server and communicates with a /// * client file wia pipes redirected towards stdin and stdout. /// * The pipe will receive messages from the client letting /// * the server know what commands to run. If the client sends /// * two floating-point numbers then a message consisting of /// * the sum, difference, product, and quotient of both numbers /// * is sent. The two numbers are then saved in a binary file /// * for further use. If the client sends the string 'TOTAL' /// * then a message holding the sum of every number entered to /// * to the server will be sent. Last if the client sends the /// * string 'EXIT' then a message comprised of every pair of /// * of floating point numbers is sent. int main() { long lSize; //Size of the file being opened string num1, num2; //The numbers (or command) being sent by the server //Binary file to hold every number entered to the server ever //The file will be created if it does not exist and will append to the //end if it does. The file is open for both reading and writing if the //permissions exist (if it already exists prior to opening) FILE * nFile = fopen("Numbers.bin", "a+"); lSize = findFileSize(nFile); char buf[lSize]; //holder for reading contents of the file cin >> num1; //get first number or command //If the command entered equals "total" if(num1.substr(0,5) == "TOTAL") { //Get contents of the file and find the sum of all numbers fread(buf, sizeof(char), lSize, nFile); cout << findTotal(buf) << endl; } //If the command entered equals "exit" else if(num1.substr(0,4) == "EXIT") { //Get contents of the file and print it all in number pairs fread(buf, sizeof(char), lSize, nFile); printAllNumbers(buf); } //If not "total" or "exit" get another number else { cin >> num2; //Do basic mathematical operations on the two numbers printEquations(num1, num2); //Place the number pair in a binary file writeToFile(num1, num2, nFile); } //Server is no longer needed, return system resources shutDownServer(nFile); return 0; } /// \details /// * toFloat takes a single string argument to convert into a float. First the /// * string is inserted into a stringstream for holding. Then the stream is /// * extracted into a temporary holding floating-point number. The floating /// * point number is then returned as the functions return value. float toFloat(string str) { float temp; stringstream sstr; sstr << str; sstr >> temp; return temp; } /// \details /// * findFileSize takes a single file reference as a argument. It takes the file /// * reference and fseeks to the end of the file. From there ftell can be called /// * to receive how many bytes are in the file. Since a char is only 1 byte, this /// * number represents how many characters are in the file as well. Once the file /// * size is found, fseek back to the beginning of the file for reading/writing. long findFileSize(FILE* nFile) { fseek(nFile, 0, SEEK_END); //end of file long lSize = ftell(nFile); //returns number of bytes up to current fseek fseek(nFile, 0, SEEK_SET); //beginning of file return lSize; } /// \details /// * findTotal takes a single cstring (char array) as an argument. The argument /// * acts as a message container to search through. With the help of strtok, this /// * function will iterate through every number in the message container with /// * "space" being the delimiter. strtok cycles through each number until the /// * pointer returns is NULL, meaning it has run out of numbers indicating the /// * end of file. Each iteration the number strtok is pointing to in converted /// * into a float and added to sum to be returned. Once every number is added to /// * the sum then the total sum is returned. int findTotal(char buf[]) { int total = 0; //Sum of all numbers float tempNum; //Return tokens in the message container with *space* as a delimiter //delimiter: what will separate each token (number) char * pch = strtok(buf, " "); //pch will be NULL when it has run out of tokens to point to while(pch != NULL) { string str(pch); //Convert char* to string so toFloat can be called tempNum = toFloat(str); //Convert to float so it can be added total += tempNum; //Using NULL as an argument tells strtok to pick up where it left off pch = strtok(NULL, " "); } return total; } /// \details /// * printAllNumbers takes a single cstring (char array) as an argument. The /// * argument acts as a message container to search through. With the help of /// * strtok, this function will iterate through every number in the message /// * container with "space" being the delimiter. strtok cycles through each /// * number until the pointer returns NULL, meaning it has run out of numbers /// * indicating the end of file. Each iteration the number strtok is pointing to /// * is placed in a holding string until both the first number and second number /// * are found. Once the pair are found, they are formatted on a single line and /// * written to stdout. Then on a new line, another pair is written until every /// * pair in the message container has been written. void printAllNumbers(char buf[]) { //iterator to use as a reference for first or second number in a pair int i = 0; //temporary holding variables float tempNum; string tempStr1 = "", tempStr2 = ""; //Return tokens in the message container with *space* as a delimiter //delimiter: what will separate each token (number) char * pch = strtok(buf, " "); //pch will be NULL when it has run out of tokens to point to while(pch != NULL) { string str(pch); //convert char* to string //If the number is the second in the pair if(i % 2 != 0) { tempStr2 = str; //Format and write both numbers to stdout cout.width(15); cout << left << tempStr1; cout.width(15); cout << left << tempStr2; cout << endl; } else //the number is the first of the pair tempStr1 = str; //Using NULL as an argument tells strtok to pick up where it left off pch = strtok(NULL, " "); i++; //increment the iterator to get token number } } /// \details /// * printEquations takes two string arguments. Both string arguments are /// * immediately converted into floats so basic mathematical operations can be /// * performed on them. First the first row is formatted and written to display /// * what operation the number represents. The second is formatted the same as /// * the first but displays the results of the operation above. Everything is /// * formatted and written to stdout independently. Every column will have a set /// * width of 15 characters and be displayed with left justification in the /// * column. Numbers are to be displayed with a precision of 10. void printEquations(string num1, string num2) { //Convert to float for further use in operations float n1 = toFloat(num1); float n2 = toFloat(num2); //Write the operations use to know what the later numbers represent cout.width(15); cout << left << "SUM"; cout.width(15); cout << left << "DIFF"; cout.width(15); cout << left << "PROD"; cout.width(15); cout << left << "QUOT"; cout << endl; //Display the results of the basic mathematical operations: //Sum, Difference, Product, and Quotient cout.width(15); cout << left << setprecision(10) << n1+n2; cout.width(15); cout << left << setprecision(10) << n1-n2; cout.width(15); cout << left << setprecision(10) << n1*n2; cout.width(15); cout << left << setprecision(10) << n1/n2; cout << endl; } /// \details /// * writeToFile takes two string arguments and a single file reference argument. /// * The strings will be numbers to be inserted into the file. The numbers are /// * written to the file individually to avoid packaging. A space character is /// * written between the numbers and after the last number to ensure no number /// * gets combined in the file. void writeToFile(string num1, string num2, FILE* nFile) { string space = " "; fputs(num1.c_str(), nFile); //write num1 fputs(space.c_str(), nFile); //write space fputs(num2.c_str(), nFile); //write num2 fputs(space.c_str(), nFile); //write space } /// \details /// * shutDownServer takes a single file reference argument. The file reference /// * argument is to be closed in order to return system resources. The pipes are /// * flushed of all contents and are closed. Since the server's pipe ends are /// * stdin and stdout, they are closed respectively. void shutDownServer(FILE* nFile) { fclose(nFile); //close file fflush(stdout); //flush pipe of contents //Close pipe ends (stdin and std out) close(0); close(1); } <file_sep>/csc136/testdebugger/demo.cpp // File: Demo.cpp // Implementation of Demo class #include <iostream> #include "demo.h" using namespace std; Demo::Demo(int tx, double ty) { cout << "N"; x = tx; y = ty; } Demo::Demo(const Demo& d) { cout << "CC"; x = d.x; y = d.y; } int Demo::getX() const { return(x); } Demo::~Demo() { cout << "X"; x=0; } Demo Demo::operator=(const Demo &d) { cout << "Q"; x = d.x; y = d.y; return *this; } Demo Demo::operator++(int) { Demo temp=*this; x++; return(temp); } <file_sep>/csc520/finalproj/src/com/library/protocol/field_list/PMember.java package com.library.protocol.field_list; import com.library.business_layer.field_list.Member; /** * PMember serves as a protocol to transfer Table information from the server * to the UI. Only serves as a way to view, print and facilitate information. * PROTOCOL LAYER * @see com.library.business_layer.field_list.Member */ public class PMember { private String name; private String phone; private int amountDue; private boolean inGoodStanding; private String number; /** * Basic constructor that sets all attributes. * @param n String member name * @param p String member phone number * @param a int member amount due * @param igs boolean member in good standing * @param num String member number */ public PMember(String n, String p, int a, boolean igs, String num) { name = n; phone = p; amountDue = a; inGoodStanding = igs; number = num; } /** * @return String member name * @see com.library.business_layer.field_list.Member#getName() */ public String getName() { return name; } /** * @return String member phone number * @see com.library.business_layer.field_list.Member#getPhone() */ public String getPhone() { return phone; } /** * @return int member amount due * @see com.library.business_layer.field_list.Member#getAmountDue() */ public int getAmountDue() { return amountDue; } /** * @return boolean member in good standing * @see com.library.business_layer.field_list.Member#getInGoodStanding() */ public boolean getInGoodStanding() { return inGoodStanding; } /** * @return String member number * @see com.library.business_layer.field_list.Member#getNumber() */ public String getNumber() { return number; } /** * Prints the Member in a human understandable summary. */ public String toString() { String out = ""; out += ("Name: " + getName() + "\nNumber: " + getNumber() + "\n"); out += ("Phone: " + getPhone() + "\n"); out += ("Amount Due: $" + getAmountDue() + "\n"); if(getInGoodStanding()) { out += ("In Good Standing\n"); } else { out += ("Not In Good Standing\n"); } return out; } } <file_sep>/csc421/assignment3/README.txt * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Yahtzee © 2017 Hasbro, Inc. * Version 3.0 * <NAME> BS Computer Science * Kutztown University of Pennsylvania * * Official Rules: * https://www.hasbro.com/common/instruct/Yahtzee.pdf * * JavaDocs Link: * http://csitrd.kutztown.edu/~ccarr419/csc421/assignment3/ * * - - - - - - - - - - MY DESIGN CHOICES - - - - - - - - - - * * For this project I made a GWT application through a * Unix environment with the help of a tomcat server to * unpack my projects' war onto the web. First my project * was created with the GWT command webAppCreator. From * there I modified the html file to create the necessary * divs/tables for my game information. Then I made * modifications to the Yahtzee.java code to create the * game's widgets and inject game information/data. I * made buttons that look like dice the main aspect of * the game. So when a player clicks on the dice it acts * as if they pulled the dice aside to keep. Players * can choose a category at any point during a round. * However players will be forced to pick a category once * they run out of rolls if they wish to continue the * game. Players choose a category by selecting the button * across from the category they wish to pick. They * will be prompted with a pop-up prompt if they want to * pick that category in the case of misclicks. The game * will progress until the player has run out of * categories to fill. At that point the game is over. * To restart the game simply refresh the browser. Lastly * I made changes to the Yahtzee.css file to create the * look and feel of the GUI. * * - - - - - - - - - - - HOW TO PLAY - - - - - - - - - - - - * * When the webpage loads, the game starts with an initial * roll. There is no need to manually start the game. The * same rule applies to once a category is picked. Once * a category is picked the game proceeds to the next * round with an initial roll. * * The player can select dice to keep by simply clicking * the dice they want to keep. The player can unkeep the * dice they kept by clicking on the kept dice again. * White dice signify unkept dice. Yellow/cream colored * dice signify kept dice. * * The roll button will roll the dice. There is a maximum * of three rolls per round. With the first roll being * rolled automatically the player will only be able to * roll twice before reaching the roll limit. Once the * roll limit is reached they will no longer be able to * roll until a category is picked. If the player has not * picked any dice to keep before clicking the roll button * the player will be shown a prompt if they wish to * continue with the roll without keeping. * * At any point during a round the player may select a * category to fill for the round. The score depends * on the current dice configuration. To select a score * the player must click the button horizontally across * from the category they wish to fill. The player will * be prompted everytime in the case of misclicks. Once a * category is picked it cannot be unpicked so make * sure to choose wisely. Players will be forced to choose * a category once they use all their rolls. Categories * that were previously picked will be crossed out. * * Scores for the player can be found in the scoresheet * on the left side of the webpage. Scores will be * automatically injected into the scoresheet once a * category is picked with bonuses and totals being * updated automatically as well. * * The "How To Play" button will bring you to this readme * file that will hold information to help you play. * * There is no game reset button once the game has reached * its natural end. To reset the game from the beginning * please refresh your browser. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <file_sep>/csc242/Project/viewcart.php <?php session_start(); $loggedin = $_SESSION['loggedin']; $purchases = $_SESSION['order']; /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/orders.php Course: CSC 242 - Fall 2013 */ //Create page with same style sheet and links as rest of website echo "<html xmlns = 'http://www.w3.org/1999/xhtml'> <head> <title> Chris' Book Store </title> <script type = 'text/javascript'> <!-- function removeOrder() { var answer = confirm('Are you sure you want to remove this from your shopping cart?'); if(answer == true) window.location.href = 'removeOrder.php'; } //--> </script> <!-- My stylesheet for the project --> <link rel = 'stylesheet' type = 'text/css' href = 'projectstyle.css'/> </head> <body> <!-- Links --> <div class = 'header'><h1>Chris' Book Store</h1></div> <div class = 'special'> <h3><p class = 'one'> <a class = 'link' href = 'myproject.php'>Home</a> &nbsp; | &nbsp;"; if($loggedin == true) echo "<a class = 'link' href = 'loggedout.php'>Log Out</a> &nbsp; | &nbsp;"; else echo "<a class = 'link' href = 'login.html'>Log In</a> &nbsp; | &nbsp;"; echo "<a class = 'link' href = 'createaccount.php'>Create Account</a> &nbsp; | &nbsp; <a class = 'link' href = 'contact.php'>Contact Us</a> &nbsp; | &nbsp; <a class = 'link' href = 'categories.php'>Categories</a> &nbsp; | &nbsp; <a class = 'link' href = 'searchstart.php'>Search</a> &nbsp; | &nbsp; <a class = 'link' href = 'orders.php'>View Orders</a> &nbsp; | &nbsp; <a class = 'link' href = 'viewcart.php'>View Cart</a> </p></h3><br/>"; if($loggedin == false) echo "<h3><p class = 'one'>Please log in to add products to your shopping cart. <a href = 'login.html' class = 'link'>Log in?</a></p></h3>"; else { $orders = array(); $dsn = 'mysql:host=localhost;dbname=ccarr419_bookstore'; $username = 'ccarr419'; $password = '<PASSWORD>'; $db = new PDO($dsn, $username, $password); $query = "SELECT * FROM Products"; $products = $db->query($query); foreach($products as $product) { $orders[$product['ProductID']] = $_POST[$product['ProductID']]; $id[] = $product['ProductID']; if($orders[$product['ProductID']] <= 0) unset($orders[$product['ProductID']]); } if(countArray($purchases) > 0 && countArray($orders) == 0) $orders = $purchases; if(somethingOrdered($orders)) { $_SESSION['order'] = $orders; $query = "SELECT * FROM Products"; $products = $db->query($query); echo "<form name = 'order' action = 'checkout.php' method = 'post'><table style = 'margin-right: auto; margin-left:auto' border = '1' cellpadding = '5' bgcolor = '#aaaaaa'> <thead> <tr> <th>Title</th> <th>Product ID</th> <th>Quantity</th> <th>Price</th> </tr> </thead>"; foreach($orders as $id => $qty) { foreach($products as $product) { if($id == $product['ProductID']) { echo "<tr><td><div class = 'special'>" . $product['Title'] . "</div></td> <td><div class = 'special'>$id</div></td> <td><div class = 'special'><input type 'text' value = '$qty' size = '3' readOnly/></div></td>"; $price = $qty * $product['Price']; echo "<input type = 'hidden' name = '" . $product['ProductID'] . "' value = '" . $product['ProductID'] . "'/> <td><div class = 'special'>$" . $price . "</div></td></tr>"; } } } echo "</table><br/><input type = 'submit' value = 'Check Out'/>&nbsp;<input type = 'button' value = 'Remove Order' onClick = 'removeOrder()'/></form>"; } else { echo "<h1 class = 'special'><div style = 'color: red'>Your Shopping Cart Is Empty!</div></h1>"; } } echo "</div></body> </html>"; function somethingOrdered($orders) { foreach($orders as $order) { if($order > 0 && $order != NULL) return true; } return false; } function countArray($arr) { $i = 0; if($arr == 0 || $arr == NULL) return $i; else { foreach($arr as $a) { $i++; } } return $i; } ?><file_sep>/csc135/reference_ChristianCarreras.cpp /****************************************** This program asks the user to input two integers and using pass by reference will sort the two integers by smallest to largest. Author: <NAME> ******************************************/ #include <iostream> using namespace std; void readInput(int&num1, int&num2);//Asks user for two integers void sort(int&a, int&b);//Sorts the numbers with the smaller first int main() { //Variables int a, b; //Call functions readInput(a, b); sort(a, b); //Prints sorted inputs cout << "The number in sorted order: " << a << " " << b << endl; return 0; } /********************************* This function asks the user for two integers and assigns them by pass by reference to a and b in the main function. *********************************/ void readInput(int&num1, int&num2) { cout << "Please enter an integer: "; cin >> num1; cout << "Please enter another integer: "; cin >> num2; } /********************************* This function sorts the inputs by using if statments to put the smaller integer fisrt. *********************************/ void sort(int&a, int&b) { int num3; if(b < a || a > b) { num3 = a; a = b; b = num3; } } <file_sep>/csc570/TensorFlowTutorials/GettingStarted/tf_benchmark.py import os import time import tensorflow as tf import premade_estimator as pe """ Author: <NAME> Date: 05/08/18 Couse: CSC 570 Independent Study Professor: Dr. Parson University: Kutztown University Purpose: Shows the overhead of the gpu version of TensorFlow when using certain operations. The setting up and tearing down of the gpu device adds up and makes the gpu device perform worse than the cpu. Also not all TensorFlow operations are gpu-supported. """ def main(): for d in ['/cpu:0', '/device:GPU:0']: with tf.device(d): t0 = time.time() print('Starting ' + d + ' calculation') a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b') c = tf.matmul(a, b) with tf.Session() as sess: for _ in range(0,50000): sess.run(c) """ # For showing overhead of the gpu when used on an estimator for _ in range(0,10): pe.main("") """ t1 = time.time() total = t1-t0 print(total) if __name__ == '__main__': os.environ['TF_CPP_MIN_VLOG_LEVEL'] = '3' os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' #tf.logging.set_verbosity(tf.logging.INFO) main() <file_sep>/csc136/project3a/term.h //File: term.h //Author: <NAME> //Description: Term class that contains a coefficient // and exponent which is used by the Array class #ifndef TERM_H #define TERM_H #include <iostream> using namespace std; class Term { public: Term(float coeff = 0, int expn = 0); //Default constructor //Sets bool setTerm(float coeff, int expn); //Set the Term bool setCoefficient(float coeff); //Set the Term's coefficient bool setExponent(int expn); //Set the Term's exponent //Gets float getCoefficient() const; //Return coefficient int getExponent() const; //Return exponent //Operators void operator *=(double); //Multiplies coefficient by factor double operator ()(double) const; //Evaluates Term for x bool operator ==(int) const; //Compares Terms bool operator <(const Term &) const; private: float coefficient; int exponent; }; ifstream &operator>>( ifstream &, Term & ); ostream &operator<<( ostream &, const Term & ); #endif <file_sep>/csc402/assignment6/bsTree.h #ifndef BSTREE_H #define BSTREE_H template <class T> struct treeNode { T data; treeNode<T> *left, *right; treeNode() {}; treeNode(const T& info) { data = info; } }; class bsTree { public: virtual bool find(int) const = 0; virtual void insert(int) = 0; virtual void erase(int) = 0; virtual void inOrder(std::ostream&) const = 0; virtual void preOrder(std::ostream&) const = 0; virtual void postOrder(std::ostream&) const = 0; virtual void lvlOrder(std::ostream&) const = 0; }; #endif <file_sep>/csc135/displayInfo_ChristianCarreras.cpp //This program displays my info. #include <iostream> using namespace std; int main() { cout << "*************************************************" << endl; cout << "*\tName:\t<NAME>\t\t*" << endl; cout << "*\tClass:\tCSC135\t\t\t\t*" << endl; cout << "*\tMajor:\tComputer Science\t\t*" << endl; cout << "*************************************************" << endl; return 0; } <file_sep>/csc570/DataMineTensorFlow/CSC458DataMineI/water_wide_deep.py import argparse import shutil import sys import tensorflow as tf from sklearn import preprocessing # Used in label encoding _CSV_COLUMNS = [ 'pH', 'TempCelsius', 'Conductance', 'GageHt', 'DischargeRate', 'TimeOfYear', 'TimeOfDay', 'month', 'MinuteOfDay', 'MinuteFromMidnite', 'MinuteOfYear', 'MinuteFromNewYear', 'OxygenMgPerLiter' ] LABEL_NAMES = [ "'\'(-inf-2.27]\''","'\'(2.27-4.44]\''","'\'(4.44-6.61]\''", "'\'(6.61-8.78]\''","'\'(8.78-10.95]\''","'\'(10.95-13.12]\''", "'\'(13.12-15.29]\''","'\'(15.29-17.46]\''","'\'(17.46-19.63]\''", "'\'(19.63-inf)\''" ] _CSV_COLUMN_DEFAULTS = [[0.0], [0.0], [0.0], [0.0], [0.0], [0], [0], [0], [0], [0], [0], [0], [0]] parser = argparse.ArgumentParser() parser.add_argument( '--model_dir', type=str, default='/tmp/DataMining_Model', help='Base directory for the model.') parser.add_argument( '--model_type', type=str, default='wide_deep', help="Valid model types: {'wide', 'deep', 'wide_deep'}.") parser.add_argument( '--train_epochs', type=int, default=40, help='Number of training epochs.') parser.add_argument( '--epochs_per_eval', type=int, default=2, help='The number of training epochs to run between evaluations.') parser.add_argument( '--batch_size', type=int, default=40, help='Number of examples per batch.') parser.add_argument( '--train_data', type=str, default='csc458water_training49k_e.csv', help='Path to the training data.') parser.add_argument( '--test_data', type=str, default='csc458water_testing491k_e.csv', help='Path to the test data.') _NUM_EXAMPLES = { 'train': 49189, 'test': 491891, } def build_model_columns(): pH = tf.feature_column.numeric_column('pH') TempCelsius = tf.feature_column.numeric_column('TempCelsius') Conductance = tf.feature_column.numeric_column('Conductance') GageHt = tf.feature_column.numeric_column('GageHt') DischargeRate = tf.feature_column.numeric_column('DischargeRate') TimeOfYear = tf.feature_column.numeric_column('TimeOfYear') TimeOfDay = tf.feature_column.numeric_column('TimeOfDay') month = tf.feature_column.numeric_column('month') MinuteOfDay = tf.feature_column.numeric_column('MinuteOfDay') MinuteFromMidnite = tf.feature_column.numeric_column('MinuteFromMidnite') MinuteOfYear = tf.feature_column.numeric_column('MinuteOfYear') MinuteFromNewYear = tf.feature_column.numeric_column('MinuteFromNewYear') month_buckets = tf.feature_column.bucketized_column( month, boundaries=[3,6,9,12]) base_columns = [ TimeOfYear, TimeOfDay, month_buckets, ] crossed_columns = [ tf.feature_column.crossed_column( ['TimeOfYear', 'TimeOfDay'], hash_bucket_size=1000), tf.feature_column.crossed_column( [month_buckets, 'TimeOfYear', 'TimeOfDay'], hash_bucket_size=1000), ] wide_columns = base_columns + crossed_columns deep_columns = [ pH, TempCelsius, Conductance, GageHt, DischargeRate, month, MinuteOfDay, MinuteFromMidnite, MinuteOfYear, MinuteFromNewYear, TimeOfYear, TimeOfDay, ] return wide_columns, deep_columns def build_estimator(model_dir, model_type): """Build an estimator appropriate for the given model type.""" wide_columns, deep_columns = build_model_columns() hidden_units = [100, 75, 50, 25] # Create a tf.estimator.RunConfig to ensure the model is run on CPU, which # trains faster than GPU for this model. run_config = tf.estimator.RunConfig().replace( session_config=tf.ConfigProto(device_count={'GPU': 0})) if model_type == 'wide': return tf.estimator.LinearClassifier( model_dir=model_dir, feature_columns=wide_columns, n_classes = 10, optimizer=tf.train.FtrlOptimizer( learning_rate=0.1, l1_regularization_strength=1.0, l2_regularization_strength=1.0), config=run_config) elif model_type == 'deep': return tf.estimator.DNNClassifier( model_dir=model_dir, feature_columns=deep_columns, n_classes = 10, hidden_units=hidden_units, config=run_config) else: return tf.estimator.DNNLinearCombinedClassifier( model_dir=model_dir, linear_feature_columns=wide_columns, dnn_feature_columns=deep_columns, n_classes = 10, dnn_hidden_units=hidden_units, config=run_config) def input_fn(data_file, num_epochs, shuffle, batch_size): """Generate an input function for the Estimator.""" assert tf.gfile.Exists(data_file), ('%s not found.' % data_file) def parse_csv(value): print('Parsing', data_file) columns = tf.decode_csv(value, record_defaults=_CSV_COLUMN_DEFAULTS) features = dict(zip(_CSV_COLUMNS, columns)) labels = features.pop('OxygenMgPerLiter') sess = tf.Session() return features, labels # Extract lines from input files using the Dataset API. dataset = tf.data.TextLineDataset(data_file) if shuffle: dataset = dataset.shuffle(buffer_size=_NUM_EXAMPLES['train']) dataset = dataset.map(parse_csv, num_parallel_calls=5) # We call repeat after shuffling, rather than before, to prevent separate # epochs from blending together. dataset = dataset.repeat(num_epochs) dataset = dataset.batch(batch_size) return dataset def main(unused_argv): # Clean up the model directory if present shutil.rmtree(FLAGS.model_dir, ignore_errors=True) model = build_estimator(FLAGS.model_dir, FLAGS.model_type) # Train and evaluate the model every `FLAGS.epochs_per_eval` epochs. for n in range(FLAGS.train_epochs // FLAGS.epochs_per_eval): model.train(input_fn=lambda: input_fn( FLAGS.train_data, FLAGS.epochs_per_eval, True, FLAGS.batch_size)) results = model.evaluate(input_fn=lambda: input_fn( FLAGS.test_data, 1, False, FLAGS.batch_size)) # Display evaluation metrics print('Results at epoch', (n + 1) * FLAGS.epochs_per_eval) print('-' * 60) for key in sorted(results): print('%s: %s' % (key, results[key])) if __name__ == '__main__': tf.logging.set_verbosity(tf.logging.INFO) FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) <file_sep>/csc237/project3/WordList.h /** // Author: <NAME> // Documented By: <NAME> // Course: CSC 237 // Filename: WordList.h // Purpose: Abstract base class for containers of word data // Known subclasses: WordDataList, WordDataDLinkList */ #ifndef WORDLIST_H #define WORDLIST_H #include <fstream> #include <string> using namespace std; class WordList { public: /** // Function Name: parseIntoList // Parameters: ifstream& - import/export // Returns: void // Purpose: Pure virtual funtion to be used by subclasses */ virtual void parseIntoList(ifstream &inf)=0; /** // Function Name: printIteratively // Parameters: none // Returns: void // Purpose: Pure virtual funtion to be used by subclasses */ virtual void printIteratively()=0; /** // Function Name: printRecursively // Parameters: none // Returns: void // Purpose: Pure virtual funtion to be used by subclasses */ virtual void printRecursively()=0; /** // Function Name: printPtrRecursively // Parameters: none // Returns: void // Purpose: Not pure virtual because only used by WordDataList */ virtual void printPtrRecursively() {} }; #endif <file_sep>/csc342/Site/Controls/ContactForm.ascx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Controls_ContactForm : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) { if(!string.IsNullOrEmpty(PhoneHome.Text) || !string.IsNullOrEmpty(PhoneBusiness.Text)) { args.IsValid = true; } else { args.IsValid = false; } } }<file_sep>/csc136/project4/makefile #File: makefile #Author: <NAME> #Used by: <NAME> #Course: CSC136 #Assignment: Project 4 #Description: Makes it possible for the poly.h, poly.cpp, # term.h, term.cpp, LinkedList.h, LinkedList.cpp, # p4.cpp and types.tpp to be used together in one # file by creating .o files. CC=/opt/csw/gcc3/bin/g++ DebugFlag=-g p4: poly.o p4.o LinkedList.o term.o $(CC) $(DebugFlag) -o p4 p4.o poly.o LinkedList.o term.o LinkedList.o: LinkedList.cpp LinkedList.h types.tpp cp LinkedList.cpp temp.cpp cat types.tpp >> temp.cpp # Compile temporary file created with instantiations at the end; save as LinkedList.o $(CC) -c temp.cpp -g -o LinkedList.o # Uncomment the next line before submission # \rm -f temp.cpp p4.o: p4.cpp poly.h term.h $(CC) $(DebugFlag) -c p4.cpp poly.o: poly.cpp poly.h LinkedList.h term.h $(CC) $(DebugFlag) -c poly.cpp term.o: term.h term.cpp $(CC) $(DebugFlag) -c term.cpp clean: \rm -rf *.o p4 <file_sep>/csc520/finalproj/src/com/library/protocol/field_list/PCatalogedBookDetails.java package com.library.protocol.field_list; import com.library.business_layer.field_list.CatalogedBookDetails; /** * PCatalogedBookDetails serves as a protocol to transfer Table information from * the server to the UI. Only serves as a way to view, print and facilitate * information. * PROTOCOL LAYER * @see com.library.business_layer.field_list.BorrowedBook */ public class PCatalogedBookDetails { private String edition; private String authors[]; private String description; /** * Basic constructor that sets all attributes. * @param e String book edition * @param a String[] book authors * @param d String book description */ public PCatalogedBookDetails(String e, String a[], String d) { edition = e; authors = a; description = d; } /** * @return String book edition * @see com.library.business_layer.field_list.CatalogedBookDetails#getEdition() */ public String getEdition() { return edition; } /** * @return String[] book author(s) * @see com.library.business_layer.field_list.CatalogedBookDetails#getAuthors() */ public String[] getAuthors() { return authors; } /** * @return String book description * @see com.library.business_layer.field_list.CatalogedBookDetails#getDescription() */ public String getDescription() { return description; } /** * Prints the CatalogedBookDetails in a human understandable summary. */ public String toString() { String out = ""; out += ("Edition: " + getEdition() + "\nAuthors: "); for(int i = 0; i < getAuthors().length; i++) { out += (getAuthors()[i]); if(i < getAuthors().length-1) { out += ", "; } } out += ("\nDescription: " + getDescription() + "\n"); return out; } }<file_sep>/csc237/project3/WordData.h /** // Author: <NAME> // Updated By: Dr. Spiegel and <NAME> // Course: CSC 237 // Filename: WordData.cpp // Purpose: Container of a word and its multiplicity */ #ifndef WORDDATA_H #define WORDDATA_H #include <iostream> #include <string> using namespace std; class WordData { public: /** // Function Name: Constructor // Member Type: Constructor // Parameters: string - import only // int - import only // Returns: N/A // Purpose: Constructs the WordData object */ WordData(string wrd = "", int cnt = 1); /** // Function Name: setWord // Member Type: Mutator // Parameters: string - import only // Returns: void // Purpose: Sets the word for the WordData object */ void setWord(string wrd); /** // Function Name: setCount // Member Type: Mutator // Parameters: int - import only // Returns: void // Purpose: Sets the count for the WordData object */ void setCount(int cnt); /** // Function Name: setWordData // Member Type: Mutator // Parameters: string - import only // int - import only // Returns: void // Purpose: Sets the word and count for the WordData object */ void setWordData(string,int); /** // Function Name: getWord // Member Type: Inspector // Parameters: none // Returns: string // Purpose: Returns the value of WordData's word */ string getWord() const; /** // Function Name: getCount // Member Type: Inspector // Parameters: none // Returns: int // Purpose: Returns the value of WordData's word */ int getCount() const; /** // Function Name: incCount // Member Type: Mutator // Parameters: int // Returns: void // Purpose: Increments count by one */ void incCount(int inc = 1); /** // Function Name: < operator // Member Type: Facilitator // Parameters: const WordData& - import only // Returns: true if less than // false if not // Purpose: Checks if the WorData is less than another based // on string compare */ bool operator <(const WordData &) const; /** // Function Name: > operator // Member Type: Facilitator // Parameters: const WordData& - import only // Returns: true if greater than // false if not // Purpose: Checks if the WorData is greater than another based // on string compare */ bool operator >(const WordData &) const; /** // Function Name: == operator // Member Type: Facilitator // Parameters: const WordData& - import only // Returns: true if equal to // false if not // Purpose: Checks if the WorData is equal to another based // on string compare */ bool operator ==(const WordData &) const; private: //variables string word; int count; }; /** // Function Name: << operator // Parameters: ostream& - import/export // const WordData& - import only // Returns: ostream // Purpose: Prints a WordData object to the screen */ ostream &operator<<(ostream& output, const WordData &words); #endif <file_sep>/csc237/project2/DLinkedList.cpp /* // Author: <NAME> // (with thanks to Dr. Spiegel for // the original single linked list) // Course: CSC 237 // Filename: DLinkedList.cpp // Purpose: This file implements the code for the data // members of the DLinkedList class. Pointers // to the nodes are used to make everything possible. // This is a templated class, and only uses the data types // specified within types.tpp */ #include <assert.h> #include <iostream> #include "DLinkedList.h" #include "Node.h" using namespace std; /* //DLinkedList constructor, sets head eqaul to NULL */ template <typename eltType> DLinkedList<eltType>::DLinkedList() : head(NULL) {} /* //DLinkedList copy constructor, calls copy private data member */ template <typename eltType> DLinkedList<eltType>::DLinkedList(const DLinkedList<eltType> &cl) {head = copy( cl.head );} /* //DLinkedList destructor, calls destroy data member */ template <typename eltType> DLinkedList<eltType>::~DLinkedList() {destroy(head);} /* //Inserts in order by checking all conditions for insertion: //*Empty list //*Beginning of list //*Middle of list //*End of list */ template <typename eltType> bool DLinkedList<eltType>::insert(eltType x) { if (head == NULL || x < head->data) //Empty list or first in list { if(head == NULL) //Empty list assert(head=new node<eltType>(x, NULL, head)); else //First in the list { node<eltType>* temp = head; assert(head=new node<eltType>(x, NULL, head)); temp->prev = head; } } else //Further down the list { node<eltType>* p = head->next; node<eltType>* trailp = head; while (p != NULL && x > p->data) { trailp = p; p = p->next; } assert((trailp->next = new node<eltType>(x, trailp, p)) != NULL); if(p != NULL) //Middle of list p->prev = trailp->next; } return true; } /* //Removes by checking all conditions for node removal: //*Beginning of list //*End of list //*Middle of list //*Not in list */ template <typename eltType> bool DLinkedList<eltType>::remove(eltType x) { //assert(head != NULL); node<eltType>* p = head; node<eltType>* trailp = NULL; while ( p != NULL && p->data < x ) { trailp = p; p = p->next; } if(p == NULL) //Empty list return false; else if(p->data == x) //Node found { if(p == head) //If node is first node { if(p->next == NULL) //If node is only node in the list head = NULL; else { head = head->next; //Not only node in list head->prev = NULL; } } else if(p->next == NULL) //Last in the list trailp->next = NULL; else { trailp->next = p->next; //x is farther down in the LinkedList p->next->prev = trailp; } delete p; return true; //Removal successful } else //Not in the list return false; } /* //Assignment operator copies the list to be assigned, destroys the old list //and assigns the new list */ template <typename eltType> DLinkedList<eltType> &DLinkedList<eltType>::operator =(const DLinkedList<eltType>& cl) { if (this != &cl) { destroy(head); head = copy(cl.head); } return *this; } /* //Copies one list into a completely new list */ template <typename eltType> node<eltType>* DLinkedList<eltType>::copy(node<eltType> *l) { node<eltType>* first = NULL; // ptr to beginning of copied LinkedList node<eltType>* last = NULL; // ptr to last item insert in the copy if (l != NULL) { assert((first=last=new node<eltType>(l->data,NULL, NULL)) != NULL); for (node<eltType>* source=l->next;source!=NULL; source=source->next,last=last->next) { last->next = new node<eltType>(source->data, last, NULL); assert(last->next); } } return first; } /* //Destroys the whole DLinkedList node by node using recursion */ template <typename eltType> void DLinkedList<eltType>::destroy(node<eltType> *l) { if(l == NULL) //If end of list or empty return; else { destroy(l->next); node<eltType> *doomed = l; delete doomed; //destroy current node } } /* //The constructor of the DListItr. The DLinkedList to be pointed at //is taken as a parameter */ template <typename eltType> DListItr<eltType>::DListItr(const DLinkedList<eltType> &l): itr(l),curr(l.head) {} /* //Places the iterator at the begining of the list and returns that node's data */ template <typename eltType> eltType DListItr<eltType>::begin(void) { curr = itr.head; return curr->data; } /* //Checks if the DLinkedList head is pointing to NULL (empty) */ template <typename eltType> bool DListItr<eltType>::isEmpty(void) { return (itr.head == NULL);} /* //Checks if the current iterator is pointing at the first node in the list */ template <typename eltType> bool DListItr<eltType>::isFirstNode(void) { assert(curr != NULL); return curr->prev == NULL; } /* //Checks if the current iterator is pointing at the last node in the list */ template <typename eltType> bool DListItr<eltType>::isLastNode(void) { assert(curr != NULL); return curr->next == NULL; } /* //Checks whether the current iterator is eqaul to NULL or not */ template <typename eltType> bool DListItr<eltType>::isNull(void) { return curr == NULL;} /* //The * operator returns a pointer the node's data which the current //iterator is pointing at */ template <typename eltType> eltType DListItr<eltType>::operator*(void) const { return curr->data;} /* //The pre-increment operator moves the iterator //forward one node */ template <typename eltType> DListItr<eltType>& DListItr<eltType>::operator++(void) { assert(curr != NULL); curr = curr->next; return *this; //Return the current iterator } /* //The pre-decrement operator moves the iterator //back one node */ template <typename eltType> DListItr<eltType>& DListItr<eltType>::operator--(void) { assert(curr != NULL); curr = curr->prev; return *this; //Return the current iterator } <file_sep>/csc402/assignment5/graph.h /* Author: <NAME> File: graph.h Class: CSC 402 Date: 10/11/2015 */ #ifndef GRAPH_H #define GRAPH_H #include <iostream> #include <vector> #include <queue> #include "edge.h" using namespace std; class graph { public: // ADT methods virtual ~graph() {} virtual int numberOfVertices() const = 0; virtual int numberOfEdges() const = 0; virtual bool existsEdge(int, int) const = 0; virtual void insertEdge(int, int) = 0; virtual void eraseEdge(int, int) = 0; virtual int degree(int) const = 0; /* Not needed for now, not a directed or weighted graph virtual int inDegree(int) const = 0; virtual int outDegree(int) const = 0; virtual bool directed() const = 0; virtual bool weighted() const = 0; */ virtual void output(std::ostream&) const = 0; virtual void BFS(int, vector<int>&) const = 0; virtual void DFS(int, vector<int>&) const = 0; }; #endif <file_sep>/csc520/finalproj/src/com/library/business_layer/field_list/CatalogedBookDetails.java package com.library.business_layer.field_list; import java.io.Serializable; /** * A CatalogedBookDetails represents more fine-grain details of a book. * CatalogedBookDetails contains the book edition, list of authors, * a description, and a unique identifier. Identifiers are meant to * act similar to a primary key in a database and as such should be unique. * Also implements Serializable so it can be serialized for later use. * BUSINESS LAYER CLASS */ public class CatalogedBookDetails implements Serializable { private int id; private String edition; private String authors[]; private String description; /** * Contstructs CatalogedBookDetails Object by setting its attributes to a value. * @param i identifier * @param e edition * @param a authors * @param d description */ public CatalogedBookDetails(int i, String e, String a[], String d) { setId(i); setEdition(e); setAuthors(a); setDescription(d); } /** * Gets the int identifier value for this Object. * @return id as int */ public int getId() { return id; } /** * Gets the edition of the book as a String. * @return edition String */ public String getEdition() { return edition; } /** * Gets the list of authors as a String array. * @return authors String array */ public String[] getAuthors() { return authors; } /** * Gets the description of the book as a String. * @return description String */ public String getDescription() { return description; } /** * Sets the value for the Object identifier. * @param i int to set id to */ public void setId(int i) { id = i; } /** * Sets the value for the book's edition. * @param e String to set edition to */ public void setEdition(String e) { edition = e; } /** * Sets the value for the book's list of authors. * @param a String array to set authors to */ public void setAuthors(String a[]) { authors = a; } /** * Sets the value for the book's description. * @param d String to set description to */ public void setDescription(String d) { description = d; } }<file_sep>/csc330/assignment3/GuitarPlayer/GuitarPlayer/ViewController.swift /* * * * * * * * * * * * * * * * * * * * * * * * * Author: <NAME> * File: ViewController.swift * Project: GuitarPlayer * Course: CSC 330 Mobile Architecture * Date: 03/29/2016 * * * * * * * * * * * * * * * * * * * * * * * */ import UIKit import AVFoundation //For all audio related functions import Darwin //For usleep function class ViewController: UIViewController, UITextFieldDelegate { var startTime: NSTimeInterval! //the time when a note if first pressed (for debugging purposes) var recordStart: NSTimeInterval! //the time when the record button is pressed var time: NSTimeInterval! //the difference in time since startTime (for debugging purposes) var recordTime: NSTimeInterval! //the difference in time since recordStart var Isrecording: Bool! //boolean value to check if the app is recording or not var player: AVAudioPlayer! //audio handler, plays the notes var theRecording: Array<NSTimeInterval>! //array that holds the times of when the notes are pressed var parallelRecording: Array<Int32>! //parallel array to theRecording that holds which notes are pressed var timer: NSTimer! //holds the value of time to wait between playing notes in the recording var recordingName: String! var recordingHolder: Array<Array<NSTimeInterval>>! var recordingHolderParallel: Array<Array<Int32>>! var recordingCount: Int32! var currentRecording: Int32! @IBOutlet weak var recordButton: UIButton! //the button to press to record @IBOutlet weak var stopRecordingButton: UIButton! //the button to press to stop recording @IBOutlet weak var playRecording: UIButton! //the button to press to play the recording @IBOutlet weak var nameRecording: UITextField! @IBOutlet weak var renameRecording: UIButton! @IBOutlet weak var renameRecordingButton: UIButton! @IBOutlet weak var deleteRecordingButton: UIButton! @IBOutlet weak var nameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.startTime = NSDate.timeIntervalSinceReferenceDate() //time since app opened self.Isrecording = false; //make sure recording app is not recording yet self.player = AVAudioPlayer() self.theRecording = [NSTimeInterval]() //set up arrays for recording later self.parallelRecording = [Int32]() self.nameRecording.delegate = self self.recordingHolder = Array<Array<NSTimeInterval>>() self.recordingHolderParallel = Array<Array<Int32>>() self.recordingCount = 0 self.currentRecording = 0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //This function plays the note and handles part of the recording functionality @IBAction func playNoteOn(b:UIButton) { let note = String(b.tag) //hold the tag to get the correct audio file setUpPlayer(note) //get the correct file ready //debugging information self.time = (NSDate.timeIntervalSinceReferenceDate() - startTime) print("silence for \(self.time) seconds") //Do this when recording if(Isrecording == true) { //record start of note press and put it in the array recordTime = (NSDate.timeIntervalSinceReferenceDate() - recordStart) theRecording.append(recordTime) parallelRecording.append(0) //zero indicates that nothing was pressed in that interval of time } self.startTime = NSDate.timeIntervalSinceReferenceDate() //for debugging player.play() //play the note } //This function stops playing the current note beiing played @IBAction func playNoteOff(b:UIButton) { player.stop() //for debugging purposes self.time = (NSDate.timeIntervalSinceReferenceDate() - startTime) print("note \(b.tag) pressed for \(self.time) seconds") //Execute if recording if(Isrecording == true) { //record the time when the note was released recordTime = (NSDate.timeIntervalSinceReferenceDate() - recordStart) theRecording.append(recordTime) parallelRecording.append(Int32(b.tag)) //place the note number in the array } } //This function starts up the recording process when the record button is pressed @IBAction func recordPlaying(sender: AnyObject) { //Clear the last recording theRecording.removeAll() parallelRecording.removeAll() recordingName = "" nameRecording.text = "" nameLabel.text = "" //Hide the recording and play recording button, show the stop recording button, recordButton.hidden = true recordButton.enabled = false stopRecordingButton.enabled = true stopRecordingButton.hidden = false playRecording.hidden = true playRecording.enabled = false renameRecordingButton.hidden = true renameRecordingButton.enabled = false deleteRecordingButton.hidden = true deleteRecordingButton.enabled = false //Switch the app to recording mode Isrecording = true; print("start recording...") self.recordStart = NSDate.timeIntervalSinceReferenceDate() //Denote the time when recording started } //This function wraps up the recording process and returns the app to normal @IBAction func stopRecording(sender: AnyObject) { //Denote the end time of the recording recordTime = (NSDate.timeIntervalSinceReferenceDate() - recordStart) //Hide the stop recording button, show the record and play recording button stopRecordingButton.hidden = true stopRecordingButton.enabled = false recordButton.hidden = false recordButton.enabled = true playRecording.hidden = false playRecording.enabled = true print("recorded for \(self.recordTime) seconds") //display total amount of time spent recording for debugging //Place last elements in arrays theRecording.append(recordTime) parallelRecording.append(0) recordingHolder.append(theRecording) recordingHolderParallel.append(parallelRecording) recordingCount = recordingCount + 1 Isrecording = false //turn off recording nameRecording.hidden = false nameRecording.enabled = true nameRecording.becomeFirstResponder() } //This function plays back what the user recorded @IBAction func playTheRecording(sender: AnyObject) { //Disable buttons so the user cannot mess anything up playRecording.enabled = false recordButton.enabled = false renameRecordingButton.enabled = false deleteRecordingButton.enabled = false print("playing '\(recordingName)'") var i: Int = 0 //index variable if(theRecording.count < 2) { //if the array's count is less than two, the user did not record anything return } while (i < theRecording.count) { if(i == 0) { //the first element in the array will always be silence //get the time of the first silence in microseconds let timer = useconds_t(theRecording[0]*960000) //closer to normal speed for some reason print("waiting...") usleep(timer) //wait until the first note is played (in microseconds) } else { //get the time between when the note was pressed and was stopped in microseconds let timer = useconds_t((theRecording[i]-theRecording[i-1])*960000) //closer to normal speed for some reason //if the note is 0 then just wait if(parallelRecording[i] == 0) { print("waiting...") usleep(timer) } //an acutal note was pressed, prepare to play it else { setUpPlayer(String(parallelRecording[i])) print("playing note: \(parallelRecording[i])") //play note for the set amount of time player.play() usleep(timer) self.player.stop() } } i++ //increment index } print("end") //Return buttons to normal playRecording.enabled = true recordButton.enabled = true renameRecordingButton.enabled = true deleteRecordingButton.enabled = true } @IBAction func renameRecording(sender: AnyObject) { nameRecording.hidden = false nameRecording.enabled = true nameRecording.becomeFirstResponder() nameLabel.text = recordingName } @IBAction func deleteRecording(sender: AnyObject) { theRecording.removeAll() parallelRecording.removeAll() recordingName = "" nameRecording.text = "" nameLabel.text = "" playRecording.hidden = true playRecording.enabled = false renameRecordingButton.hidden = true renameRecordingButton.enabled = false deleteRecordingButton.hidden = true deleteRecordingButton.enabled = false print("recording deleted") } //This function setups up the audio player to play the correct note func setUpPlayer(note: String) { //get the address of the note to play by placing the note number in the string let guitarNote = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Strat P- "+note, ofType: "wav")!) do //do try catch for error checking { //hook up the audio player to the audio file try player = AVAudioPlayer.init(contentsOfURL: guitarNote, fileTypeHint: "wav") } catch //if there was an error locating the file { print("error: file not found") } } func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) recordingName = nameRecording.text nameRecording.enabled = false nameRecording.hidden = true renameRecordingButton.enabled = true renameRecordingButton.hidden = false deleteRecordingButton.enabled = true deleteRecordingButton.hidden = false nameLabel.text = recordingName return false } } <file_sep>/csc136/project1/p1.cpp /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: <NAME> * * * * Course: CSC 136 * * * * Assignment: 1 * * * * Due Date: September 12, 2013 at 11:59 PM * * * * File: p1.cpp * * * * Purpose: This program reads a user specified * * file and lists the number of characters, * * paragraphs, words and how many letters * * are in the words of said file. * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <iostream> #include <string> #include <iomanip> #include <fstream> using namespace std; void getFileName(string&); //Gets file name bool openFile(ifstream&, string&); //Opens file void getChar(ifstream&, int&, int&); //Gets # of characters & paragraphs void getWords(ifstream&, int[], string); //Sorts words by # of letters void Output(string, int&, int&, int[]); //Outputs all data int getTotalWords(int[]); //Gets # of words int main() { ifstream inf; string fileName; //File entered by user bool fileOpen; //Checks if file exists int count[10]; //Sorts words by # of letters int characters = 0; //Total characters in file int paragraphs = 0; //Total paragraphs in file //Sets all elements in the count array to 0. for(int i = 0; i < 10; i++) { count[i] = 0; } //Get file from user. getFileName(fileName); //Attempt to open file. fileOpen = openFile(inf, fileName); //Checks to see if file exists. if(fileOpen == true) { //Find total characters/paragraphs in the file. getChar(inf, paragraphs, characters); //Sort words by # of letters. getWords(inf, count, fileName); //Output the data to screen. Output(fileName, characters, paragraphs, count); } else { //Error message if file does not exist. cout << "ERROR: Failure to open file.\n"; } return 0; } /******************************************* * * * Funtion Name: getFileName * * * * Description: Asks user for file to open * * * * Parameters: string fileName * * * * Return Value: none * * * *******************************************/ void getFileName(string &fileName) { cout << "\nPlease enter the file name: "; cin >> fileName; } /**************************************************** * * * Function Name: openFile * * * * Description: Attempts to open the file specified * * by the user and returns a false * * value if it does not exist * * * * Parameters: ifstream inf * * string fileName * * * * Return Value: bool fileOpen * * * ****************************************************/ bool openFile(ifstream &inf, string &fileName) { bool fileOpen; inf.open(fileName.c_str()); //If file does not exist. if (inf.fail()) return fileOpen = false; //If file does exist. else return fileOpen = true; } /************************************************************** * * * Function Name: getChar * * * * Description: Finds the number of characters and paragraphs * * * * Parameters: ifstream inf * * int paragraphs * * int characters * * * * Return Value: none * * * **************************************************************/ void getChar(ifstream &inf, int &paragraphs, int &characters) { char ch; //Use get fucntion to get all characters in file. while(inf.get(ch)) { //Detect new line character for # of paragraphs. if(ch == '\n') { paragraphs++; characters++; } //Add to charcters if not a white space. else { characters++; } } } /******************************************************************* * * * Function Name: getWords * * * * Description: This function finds the number of letters in the * * words of the user specified file and sorts them * * into the appropriate space in the count array * * with count[0] holding all words with 10+ letters * * * * Parameters: ifstream inf * * int count[10] * * string fileName * * * * Return Value: none * * * *******************************************************************/ void getWords(ifstream &inf, int count[], string fileName) { string word; //Rewind the file. inf.close(); inf.clear(); inf.open(fileName.c_str()); while(inf >> word) { word.size(); //Sorts according to # of letters. if(word.size() < 10) count[word.size()]++; //Sorts all words with 10+ letters to count[0]. else count[0]++; } } /********************************************************************* * * * Function Name: Output * * * * Description: Outputs all data collected from other functions * * * * Parameters: string fileName * * int characters * * int paragraphs * * int count[10] * * * * Return Value: none * * * *********************************************************************/ void Output(string fileName, int &characters, int &paragraphs, int count[]) { int words = 0; //Get the total amount of words in the file. words = getTotalWords(count); cout << "\nFile: " << fileName; cout << "\tCharacters: " << characters; cout << "\t\tWords: " << words; cout << "\tParagraphs: " << paragraphs << endl; cout << "\nAnalysis of Words\n\n"; cout << "Size\t1\t2\t3\t4\t5\t6\t7\t8\t9\t10+\n"; cout << "#Words"; //Display the words sorted by # of letter from 1-10+. for(int i = 1; i < 10; i++) { cout << "\t" << count[i]; } cout << "\t" << count[0] << endl; } /********************************************************* * * * Function Name: getTotalWords * * * * Description: Adds the total number of words * * * * Parameters: int count[10] * * * * Return Value: int words * * * *********************************************************/ int getTotalWords(int count[]) { int words; for(int i = 0; i < 10; i++) { words += count[i]; } return words; } <file_sep>/csc520/finalproj/src/com/library/business_layer/field_list/CatalogQuery.java package com.library.business_layer.field_list; /** * A CatalogQuery is a user search query that is used to search the catalog of * books for a certain book or subset of books. A CatalogQuery can contain * multiple publisher ids, category ids and authors to search for. * BUSINESS LAYER CLASS * @see com.library.business_layer.field_list.Author * @see com.library.business_layer.field_list.Category * @see com.library.business_layer.field_list.Publisher */ public class CatalogQuery { private int[] publisherIds; private int[] categoryIds; private String[] authors; /** * Contstructs CatalogQuery Object by setting its attributes to a value. * @param p publisher ids * @param c category ids * @param a authors */ public CatalogQuery(int p[], int c[], String a[]) { setPublisherIds(p); setCategoryIds(c); setAuthors(a); } /** * Gets the publisher ids in the query as an array. * @return publiser ids int array */ public int[] getPublisherIds() { return publisherIds; } /** * Gets the category ids in the query as an array. * @return edition int array */ public int[] getCategoryIds() { return categoryIds; } /** * Gets the authors in the query as an array. * @return authors String array */ public String[] getAuthors() { return authors; } /** * Sets the publisher id list for the query. * @param p int array to set publisher ids to */ public void setPublisherIds(int p[]) { publisherIds = p; } /** * Sets the category id list for the query. * @param c int array to set category ids to */ public void setCategoryIds(int c[]) { categoryIds = c; } /** * Sets the author list for the query. * @param a String array to set authors to */ public void setAuthors(String a[]) { authors = a; } } <file_sep>/csc342/README.txt CSC 342 - Web Technologies Dr. <NAME> Kutztown University Spring 2015 This course is an introduction to the basic concepts of technologies that are used on the Web. Topics include: Web basics, standards, and infrastructure, client/server architecture on the Web, page presentation using markup languages and style sheets, the Document Object Model (DOM), client-side programming and server-side programming, Web data representation, and Web services. <file_sep>/csc136/project3b/poly.cpp #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cmath> #include "poly.h" #include "Array.h" #include "term.h" using namespace std; //Constructor Polynomial::Polynomial() { } ////////// //SETS ///////// /* Function: setTerm Member Type: Mutator Description: Sets the term in the variable at a specific index Parameters: int index - input - the index at which the values are stored float co - input - the coefficient int ex - input - the exponent Returns: true if the value is set, false if not */ bool Polynomial::setTerm(int index, float co, int ex) { A[index].setCoefficient(co); A[index].setExponent(ex); return true; } /* Function: setCoeff Member Type: Mutator Description: Sets the coefficient for a term in the variable at a specific index Parameters: int index - input - the index at which the values are stored float co - input - the coefficient for the user Returns: true if the value is set, false if not */ bool Polynomial::setCoeff(int index, float co) { return(A[index].setCoefficient(co)); } /* Function: setExponent Member Type: Mutator Description: Sets the exponent for the term in the variable at a specific index Parameters: int index - input - the index at which the values are stored int ex - input - the exponent for the user Returns: true if the value is set, false if not */ bool Polynomial::setExponent(int index, int ex) { return(A[index].setExponent(ex)); } ////////// //GETS ///////// /* Function: getArray Member Type: Inspector Description: Gives the user the Array object Parameters: none Returns: the Array object */ Array& Polynomial::getArray() { return A; } /* Function: getTerm Member Type: Inspector Description: Gives the user the values associated with the terms at the index Parameters: int index - input - the index at which the values are stored Returns: The requested Term Precondition: index is an in use (active) index */ Term Polynomial::getTerm(int index) const { return A[index]; } /* Function: getCoeff Member Type: Inspector Description: Gets the user the coefficient at a certain index Parameters: int index - input - the index at which the values are stored Returns: The requested coefficient Precondition: index is an in use (active) index */ float Polynomial::getCoeff(int index) const { return A[index].getCoefficient(); } /* Function: getExponent Member Type: Inspector Description: Gets the user the exponent for a certain index Parameters: int index - input - the index at which the values are stored Returns: The requested exponent Precondition: index is an in use (active) index */ int Polynomial::getExponent(int index) const { return A[index].getExponent(); } /* Function: operator () Member Type: Facilitator Description: Evaluate the polynomial for variable x Parameters: x - input - variable that is standing for value of x Returns: The polynomial evaluated for x */ double Polynomial::operator()(double x) const { double answer = 0; for(int i = 0; i < A.getElements(); i++) { //Multiply the coefficient by x^expn and add to total if(getExponent(i) > 1) answer += (pow(x, getExponent(i))*getCoeff(i)); //Multiply the coefficient by x and add to total else if(getExponent(i) == 1) answer += (x*getCoeff(i)); //Add the coefficient to total else if(getExponent(i) == 0) answer += getCoeff(i); } return answer; } /* Function: multiply Member Type: Facilitator Description: Multiply each coefficient by the scalar arg factor Parameters: fact - input - variable that is multiplying against all the coefficients Returns: void */ void Polynomial::operator*=(float factor) { for(int i = 0; i < A.getElements(); i++) setCoeff(i, getCoeff(i)*factor); } /* Function: add Member Type: Mutator Description: Add a term to the polynomial Parameters: coefficient - input - the coefficient of the term being added exponent - input - the exponent of the term being added Returns: true if the term is added, false otherwise */ bool Polynomial::add(float co, int ex) { return(A.addTerm(co, ex)); } /* Function: add Member Type: Inspector Description: Add a term to the polynomial Parameters: T - input - the Term being added Returns: true if the term is added, false otherwise */ bool Polynomial::add(Term &T) { return(A.addTerm(T)); } /* Function: readFile Member Type: Mutator Description: Loads up the terms from a user declared filename Parameters: file& - input/output - stream variable Returns: void */ void Polynomial::readFile(ifstream &file) { Term T; while(file >> T) add(T); file.close(); } /* Function: operator >> Description: Reads in a Term from a file Parameters: ifstream file - input/output - the input stream Polynomial - output only - Poly to data input Returns: ifstream */ ifstream &operator >>(ifstream &file, Polynomial&P) { Term newTerm; file >> newTerm; P.add(newTerm); return file; } /* Function: operator << Description: Print a Polynomial to the screen Parameters: out - input/output - output stream P - input - The Polynomial to print Returns: void */ ostream &operator <<(ostream &out, Polynomial &P) { out << P.getArray(); return out; } <file_sep>/csc421/README.txt CSC 421 - Web-Based Software Design and Development Dr. <NAME> Kutztown University Fall 2017 This course introduces the students to web-based software design. Using object-oriented techniques, the students will learn how to develop mainly on the client side of event-based web applications. Projects will build rudimentary knowledge of event-based design, and then expand upon those foundations to create web-based software and to add multimedia enhancements, including audio, video, and animation. The completion of projects using these features is an integral part of the course. <file_sep>/csc135/restaurant_ChristianCarreras.cpp /**************************************************************************** Project 4: Loops (Restaurant Bill) This program uses while and for loops as well as nested loops to create an interface for a restaurant which asks the user for how many people were at the table and the price of their meals (assuming 1 meal per person) Then the program will display the subtotal, sales tax, tip and total. The program terminates when the user enters 0 or any value less than 0. Author: <NAME> Course: CSC 135 Due Date: 11/27/2012 ****************************************************************************/ #include <iostream> #include <iomanip> using namespace std; int main() { const float tax = 0.06; //Pa state tax 6%. //Variables. float sum, meal, salestax, tip, total; int people, num, counter; sum = 0; //Ask user for the number of people at the table. cout << "\nHow many people are at the table?: "; cin >> people; //If the user entered any number greater than or equal to 0. if(people >= 0) { //While loop for when the entered value is not 0. while(people != 0) { //Nested for loop which gathers the price of the meals //relative to the number of people at the table. for(counter = 0; counter < people; counter++) { cout << "Enter the price of the meal: $"; cin >> meal; sum+=meal; //Add up all the meal values. } //Calculate tip relative to number of people //at the table. If < 5 then use 18%. //If >= 5 then use 20%. if(people < 5) tip = sum * 0.18; else if(people >= 5) tip = sum *0.20; //Calculate sales tax and total. salestax = sum * tax; total = sum + salestax + tip; //Display information (Restaurant Bill) cout << setprecision(2) << fixed; //setprecision to 2 decimal places. cout << "\nPeople:\t\t" << people << endl; cout << "Subtotal:\t$" << sum << endl; cout << "Sales Tax:\t$" << salestax << endl; cout << "Tip:\t\t$" << tip << endl; cout << "Total:\t\t$" << total << endl; //Reinterate loop by asking for the number of people at //the table again. cout << "\nHow many people are at the table?: "; cin >> people; sum = 0; //Reset sum to 0. } //When the user enters 0. cout << "Goodbye\n\n"; } //When the user enters any value < 0. else cout << "Invalid Entry!\n\n"; return 0; } <file_sep>/csc421/assignment4/README.txt * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Yahtzee © 2017 Hasbro, Inc. * Version 4.0 * <NAME> BS Computer Science * Kutztown University of Pennsylvania * * Official Rules: * https://www.hasbro.com/common/instruct/Yahtzee.pdf * * JavaDocs Link: * http://csitrd.kutztown.edu/~ccarr419/csc421/assignment4/ * * - - - - - - - - - - MY DESIGN CHOICES - - - - - - - - - - * * For this project I made a GWT application through a * Unix environment with the help of a tomcat server to * unpack my projects' war onto the web. My project * was extended from the previous version by making the * necessary additions specified in the project guidelines. * The main changes between this version and the previous * version is the addition of multimedia and two-player * support. Multimedia additions were images and sound. * The dice buttons were replaced by images of dice for * a more familiar look. Sounds added were a dice rolling * sound that is played everytime a player rolls the dice * and a pencil scribbling sound that plays everytime a * player chooses a category. Two-player support tries not * to make too many visual changes compared to the one * player version. The only difference between the two is * the addition of a TabPanel which can be used to switch * between the two player's scoresheets and text stating * which player's turn it is. Other than that I tried to * keep the same look and feel as to not alienate users * between one-player and two-player versions. To use * the two-player version simply accept the first prompt * given at page load. To use a one-player version, * cancel the first prompt at page load. To restart the * game just refresh the browser. * * - - - - - - - - - - - HOW TO PLAY - - - - - - - - - - - - * * On page load, the player or players will be prompted * with the choice of a one-player or two-player game. * If the one-player version is picked, there will be a * singular checksheet. If the two-player version is * checked, there will be two checksheets along with * text that displays which player's turn it is. * * When the game begins, the game starts with an initial * roll. There is no need to manually start the game. The * same rule applies to once a category is picked. Once * a category is picked the game proceeds to the next * round and/or player turn with an initial roll. * * The player can select dice to keep by simply clicking * the dice they want to keep. The player can unkeep the * dice they kept by clicking on the kept dice again. * White dice signify unkept dice. Yellow/cream colored * dice signify kept dice. * * The roll button will roll the dice. There is a maximum * of three rolls per round. With the first roll being * rolled automatically the player will only be able to * roll twice before reaching the roll limit. Once the * roll limit is reached they will no longer be able to * roll until a category is picked. If the player has not * picked any dice to keep before clicking the roll button * the player will be shown a prompt if they wish to * continue with the roll without keeping. * * At any point during a round the player may select a * category to fill for the round. The score depends * on the current dice configuration. To select a score * the player must click the button horizontally across * from the category they wish to fill. The player will * be prompted everytime in the case of misclicks. Once a * category is picked it cannot be unpicked so make * sure to choose wisely. Players will be forced to choose * a category once they use all their rolls. Categories * that were previously picked will be crossed out. * * Scores for the player can be found in the scoresheet * on the left side of the webpage. Scores will be * automatically injected into the scoresheet once a * category is picked with bonuses and totals being * updated automatically as well. If there is more than * one player, individual scoresheets can be selected * by clicking on the specific player's tab. * * The "How To Play" button will bring you to this readme * file that will hold information to help you play. * * There is no game reset button once the game has reached * its natural end. To reset the game from the beginning * please refresh your browser. * * A winner will be announced at the end of the game if * there is more than one player. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <file_sep>/sideprojects/fractions/fraction.h #ifndef FRACTION_H #define FRACTION_H #include <iostream> using namespace std; class fraction { public: fraction(int num = 1, int den = 1); void setNumerator(int); void setDenominator(int); void setFraction(int, int); int getNumerator() const; int getDenominator() const; bool operator<(fraction&) const; bool operator<(double) const; bool operator>(fraction&) const; bool operator>(double) const; bool operator<=(fraction&) const; bool operator<=(double) const; bool operator>=(fraction&) const; bool operator>=(double) const; bool operator==(fraction&) const; bool operator==(double) const; bool operator!=(fraction&) const; bool operator!=(double) const; void operator=(fraction&); void operator*=(fraction&); void operator/=(fraction&); void operator+=(fraction&); void operator-=(fraction&); double convertToDecimal() const; void checkReduce(); void printImproper() const; private: int numerator; int denominator; }; ostream &operator<<(ostream&, const fraction&); #endif <file_sep>/csc136/project3a/SortSearch.h // FILE: SortSearch.h // A couple of things that are nice to have available // SORTS AN ARRAY (ASCENDING ORDER) USING SELECTION SORT ALGORITHM // USES exchange AND find_index_of_min // EXCHANGES TWO INTEGER VALUES template <class eltType> void exchange(eltType &x,eltType &y) // Arguments: // Both: INOUT: { eltType temp; temp=y; y=x; x=temp; } template <class eltType> void selSort(eltType *list,int items) // Arguments: // list: INOUT - array to be sorted; // items IN: number of items to be sorted (items >= 0) // Sorts the data in array items (list[0] through list[items-1]). // Pre: list is defined and items <= declared size of actual argument array. // Post: The values in list[0] through list[items-1] are in increasing order. { // Local data ... int idxMax; // subscript of each smallest item located by find_index_of_min for (int spot = items-1; spot > 0; spot--) { // Invariant: The elements in list[spot+1] through list[items-1] are in their // proper place and spot > 0. // Find index of largest unsorted element idxMax = spot; for (int idx = 0 ; idx < spot ; idx++) if (list[idx] < list[idxMax]) idxMax = idx; // Exchange items at position idxMax and spot if different if (spot != idxMax) exchange (list[idxMax], list[spot]); } // end for } // end sel_sort // Templated Search function template <class eltType> int orderedSearch(eltType *list,int items,eltType key) { int i; for (i=0;i<items && list[i]<key;i++); if (i==items || list[i]>key) return(-1); return(i); } <file_sep>/csc552/project1/printWords.cpp /* Author: <NAME> * File: printWords.cpp * Date Made: 02/13/2017 * Due Date: 02/17/2017 * School: Kutztown University * Class Num: CSC 552 * Class Name: Advanced Unix Programming * Semester: SPRING 2017 * Professor: Dr. Spiegel * Purpose: This program opens a file given through the command-line and * prints the first occuring number of words specified by the * other command-line argument. */ #include <iostream> #include <fstream> #include <string> #include <cstdlib> /* * Function Name: printWords * Function Type: facilitator * Arguments: char** - input only * Return Value: int - the number of words written * Purpose: Opens the file entered in the command-line and prints the * first n specified words in order. */ int printWords(char**); using namespace std; int main(int argc, char* argv[]) { return printWords(argv); } //Attempts to open the file and print the choosen amount of words. //Close the file once done. int printWords(char** argv) { string tempString; //Temporarily holds the string given by the input stream ifstream inf; //The input file //The number of words to print and number of words printed. int count = 0, numWords = 0; count = atoi(argv[2]); //Convert the argv char* to int inf.open(argv[1]); //Loop while you still have words to print and not end of file while(inf >> tempString && count--) cout << ++numWords << ":\t" << tempString << endl; inf.close(); //Returns the selected number of words in the file. return numWords; } <file_sep>/csc342/Site/Reviews/AllByGenre.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PlanetWroxModel; public partial class Reviews_AllByGenre : BasePage { protected void Page_Load(object sender, EventArgs e) { using(PlanetWroxEntities myEntities = new PlanetWroxEntities()) { var allGenres = from genre in myEntities.Genres.Include("Reviews") orderby genre.Name select new { genre.Name, genre.Reviews }; Repeater1.DataSource = allGenres; Repeater1.DataBind(); } } }<file_sep>/csc520/finalproj/src/com/library/business_layer/field_list/Collectable.java package com.library.business_layer.field_list; import java.io.Serializable; import java.util.Date; /** * A Collectable represents a reservation that can be collected i.e. is ready * to be picked up. Collectable contains the date the user who made the * reservation was notified, the foreign key to reservation id, and a unique * identifier. Identifiers are meant to act similar to a primary key in a * database and as such should be unique. Also implements Serializable so it * can be serialized for later use. * BUSINESS LAYER CLASS * @see com.library.business_layer.field_list.Reservation */ public class Collectable implements Serializable { private int id; private Date dateNotified; private int reservationId; /** * Contstructs Collectable Object by setting its attributes to a value. * @param i identifier * @param d date notified * @param r reservation id */ public Collectable(int i, Date d, int r) { setId(i); setDateNotified(d); setReservationId(r); } /** * Gets the int identifier value for this Object. * @return id as int */ public int getId() { return id; } /** * Gets the Date the user was notified of Collectable. * @return date notified Date */ public Date getDateNotified() { return dateNotified; } /** * Gets the indentifier for the reservation. * @return reservation id int */ public int getReservationId() { return reservationId; } /** * Sets the value for the Object identifier. * @param i int to set id to */ public void setId(int i) { id = i; } /** * Sets the value for the date notified. * @param d Date to set date notified to */ public void setDateNotified(Date d) { dateNotified = d; } /** * Sets the value for the reservation id. * @param i int to set reservation id to */ public void setReservationId(int i) { reservationId = i; } }<file_sep>/csc237/project3/WordDataSTList.cpp /** * Author: <NAME> * File Name: WordDataSTList.cpp * Date Created: 3/30/14 * Class: CSC 237 Spring 2014 * Purpose: This cpp file implements the functions of the header file * WordDataSTList.h. Some functions use polymorphism due to * WordDataSTList being a sub class. WordDataSTList has three * functions that use polymorphism and two helper functions. * Helper functions are used for recursive printing and finding * duplicates within the list. **/ #include <iostream> #include <list> #include "WordDataSTList.h" #include "WordData.h" using namespace std; /** * Function Name: Constructor * Member Type: Constructor * Parameters: None * Return Value: N/A * Purpose: Constructs the WordDataSTList object * Default constructor **/ WordDataSTList::WordDataSTList() {} /** * Function Name: parseIntoList * Member Type: Mutator * Parameters: ifstream - import/export (reads from file) * Return Value: void * Purpose: Implemented through polymorphism by being a subclass * of the WordList class. Reads from the parameter file * into the STL list and calls incMatch to check for * duplicates. **/ void WordDataSTList::parseIntoList(ifstream &inf) { string temp; //Temporary storage WordData theWord; while (inf >> temp) { if (!incMatch(temp)) //Check if match first { //Insert into list theWord.setWord(temp); theWord.setCount(1); STList.push_back(theWord); } } } /** * Function Name: printIteratively * Member Type: Inspector * Parameters: None * Return Value: void * Purpose: Also implemented through polymorphism, this function * with the help of a for loop and list iterator goes * through the list element by element and prints * the WordData info to the screen. **/ void WordDataSTList::printIteratively() { cout<<"--------------------------"<<endl; cout<<"|STL List Iterative|"<<endl; cout<<"|Word Occurences |"<<endl; cout<<"--------------------------"<<endl; for(list<WordData>::iterator it = STList.begin(); it != STList.end(); ++it) cout << " " << *it << endl; } /** * Function Name: printRecursively * Member Type: Inspector * Parameters: None * Return Value: void * Purpose: Another function implemented through polymorphism. * This function calls printRecursivelyWorker to go * through the the list and print the WordData info * recursively until the end of the list is reached. **/ void WordDataSTList::printRecursively() { list<WordData>::iterator it = STList.begin(); cout<<"--------------------------"<<endl; cout<<"|STL List Recursive|"<<endl; cout<<"|Word Occurences |"<<endl; cout<<"--------------------------"<<endl; printRecursivelyWorker(it); } /** * Function Name: printRecursivelyWorker * Member Type: Inspector * Parameters: list<WordData>::iterator - import only * Return Value: void * Purpose: Called by the printRecursively function to make * the recursive calls, iterate through the list * and print the WordList info until the end of the * list is reached. **/ void WordDataSTList::printRecursivelyWorker(list<WordData>::iterator it) { if(it == STList.end()) //Check if iterator is at the end of the list return; //Stop recursion, go back cout << " " << *it << endl; printRecursivelyWorker(++it); } /** * Function Name: incMatch * Member Type: Mutator * Parameters: string - import only (test for match) * Return Value: True if match is found * False if no match found * Purpose: Called by the parseIntoList function. * Iterates through list until a match is found * or the end of the list is reached. If a match is * found then the current data is erased and new data * with the new count is inserted. **/ bool WordDataSTList::incMatch(string temp) { for(list<WordData>::iterator it = STList.begin(); it != STList.end(); ++it) { WordData checkWord = *it; if (temp == checkWord.getWord()) //If match { it = STList.erase(it); checkWord.incCount(); STList.insert(it, checkWord); return true; } } return false; //No match found } <file_sep>/csc237/project3/Micro/makefile cc=/opt/csw/gcc4/bin/g++ micro: Microseconds.cpp $(cc) -std=gnu++0x Microseconds.cpp -o micro <file_sep>/csc402/inclassprograms/maxHeap.h #ifndef MAXHEAP_H #define MAXHEAP_H template<class T> class maxHeap { public: virtual void push(const T& theKey) = 0; virtual T pop() = 0; virtual T top() const = 0; //virtual void heapify(T*); virtual int size() const = 0; virtual bool empty() const = 0; virtual void print() const = 0; }; #endif <file_sep>/csc135/order_ChristianCarreras.cpp //This program uses a for loop to calculate subtotal and total //of user entered values. #include <iostream> #include <iomanip> using namespace std; int main() { float value, sum, tax, salestax, total; int num, counter; tax = 0.08; sum = 0; cout << "How many items are in the order? "; cin >> num; for (counter=1; counter <= num; counter++) { cout << "Enter the price of an item: $"; cin >> value; sum+=value; } salestax = tax*sum; total = salestax + sum; cout << setprecision(2) << fixed << endl; cout << "Subtotal:\t$" << sum << endl; cout << "Sales Tax:\t$" << salestax << endl; cout << "Total:\t\t$" << total << endl; return 0; } <file_sep>/csc242/Project/useraccount.php <?php session_start(); /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/useraccount.php Course: CSC 242 - Fall 2013 */ //Variable taken from creataccount.html $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $pass = $_POST['pass1']; $add1 = $_POST['add1']; $add2 = $_POST['add2']; $city = $_POST['city']; $state = $_POST['state']; $zip = $_POST['zip']; $phone = $_POST['phone']; //Connect to database $dsn = 'mysql:host=localhost;dbname=ccarr419_bookstore'; $username = 'ccarr419'; $password = '<PASSWORD>'; $db = new PDO($dsn, $username, $password); //Insert new customer into database $query = "INSERT INTO Customers (Email, Passwd, FirstName, LastName, Address1, Address2, City, State, ZipCode, PhoneNumber) VALUES ('$email', '$pass', '$fname', '$lname', '$add1', '$add2', '$city', '$state', '$zip', '$phone')"; $insert_count = $db->exec($query); //Change page to home page ; header("Location: login.html"); ?><file_sep>/csc355/README.txt CSC 355 - Software Engineering II Dr. <NAME> Kutztown University Spring 2016 This is the second course in a two semester capstone sequence. This course presents the advanced principles of software engineering. Coverage will include the professional responsibilities of the software engineer, implementation, testing, configuration management, and project management. Students will be introduced to different development and testing approaches. <file_sep>/csc548/Project1/26puzzle_christianCarreras.py # ORIGINAL AUTHOR IS UNKNOWN, THIS IS NOT MY CODE # ALL CODE WAS PROVIDED BY MY PROFESSOR FOR A PROJECT # # Modifications By: <NAME> # File Name: 26puzzle_christianCarreras.py # Date: 02/22/2017 # Course Name: Artificial Intelligence II # Course Number: CSC 548 # Professor: Dr. Rieksts # Term: SPRING 2017 # Institution: Kutztown University # Project: #1 # Due Date: 02/27/2017 # About: This program finds the shortest path between two # configurations of a modified 8-puzzle. The modifications # are simply adding an extra dimension to the 8-puzzle thus # making it a 26-puzzle. To find the shortest path, # data structures such as lists, dictionaries, nodes, # multi-dimensional arrays, etc. are used. The Manhattan # Distance heuristic is used to solve this problem as well. from copy import copy from copy import deepcopy import bisect # The main function # Finds the shortest path from icfg to gcfg # icfg = initial configuration, which is the initial state # gcfg = goal configuration, which is the goal state # Each configurations (state) when it is encountered is given # and identification number (Id) # The function uses 3 lists in parallel = WL< WLfs, WLids # WL = waiting list of nodes to be expanded # WLfs = list of f-values, in parallel with WL # WLids = list of Ids, in parallel with WL # goalId = the Id of the goal state # iNode = the node for the initial state # curNode = the node currently being processed def findPath(icfg,gcfg): print ('icfg',icfg) # Initialize WL< WLfs, WLids WL=[] WLfs=[] WLids=[] # generate the Id of the goal configuration (state) goalId=genCfId(gcfg) # Call makNd to create a node for the initial state iNode = makNd(genCfId(icfg),icfg,0,manh(icfg,gcfg),[]) curNode=iNode # Loop until the current node, the one taken from the head of WL, # has an Id matching the goal Id while curNode['cfid'] != goalId: # Expand current node, returning a list of "newNodes" newNodes=xpdNd(curNode,gcfg) # Apply filtering process keeping only the "good" nodes of newNodes WL,WLfs,WLids=adGoods(newNodes,WL,WLfs,WLids) # Grab the node at the head of WL, making it the current node curNode=WL[0] # Remove it from WL; also remove corresponding values from WLfs, WLids WL.remove(curNode) WLfs.remove(WLfs[0]) WLids.remove(WLids[0]) # Return the path to reach the current node return curNode['path'] # Function to apply filtering process retaining only the "good nodes" # Add these "good" nodes to WL, WLfs, WLids # Filtering function is keepIfBetter # nwNds = list of newly created nodes # wl, wlfs, wlids = current value of WL, WLfs, WLids def adGoods(nwNds,wl,wlfs,wlids): for nd in nwNds: # If we have seen this node before (node's cfid is in waiting list of Ids) # keep only if it is "better" than the one already seen # if not, nd becomes null if nd['cfid'] in wlids: nd=keepIfBetter(nd,wl,wlids) # If nd was kept (did not become null) # insert it into WL, WLfs, WLids if nd: wl,wlfs,wlids=insertKeyed(nd,nd['f'],wl,wlfs,wlids) # Return updated values of WL< WLfs, WLids return wl,wlfs,wlids # The filtering function which is called if the state has been seen before # nd = the node being checked # wl, wlids = current value of WL, Wlids def keepIfBetter(nd,wl,wlids): # Get the index of whcre the Id of this node is found in wlids indx=wlids.index(nd['cfid']) # From WL get the corresponding node oldNode=wl[indx] # If g-value of nd is < that of the "old" node - keep it if nd['g']<oldNode['g']: return nd # Otherwise return the empty list else: return [] # Generate the Id of a configuration (state) # cfg = a puzzle configuration (state) # cfid = the calculated Id of this state # Note to reader - run this function of a few states and it will be # immediately clear how this function works def genCfId(cfg): cfid = 0 for lvl in range(3): for row in range(3): for col in range(3): cfid = cfid*10+cfg[lvl][row][col] return cfid # Function to find in which row and column item is found # item = value being sought in a 3D array # ray3d = a 3 dimensional array # Because the function is generic, it uses range of the number of levels, # rows, and columns to stay within bounds def rcOf(item,ray3d): return [(l,r,c) for l in range(len(ray3d)) for r in range(len(ray3d)) for c in range(len(ray3d[0])) if ray3d[l][r][c]==item][0] # Function to compute the Manhattan distance # cfg1 = a configuration (state) # cfg2 = a second configuration (state) # m = variable holding the value to be returned # l1, r1, c1 = the level, row, column of a particular value of cfg1 # l2, r2, c2 = the level, row, column of a particular value of cfg2 def manh(cfg1,cfg2): m=0 # The values in each configuration run from 1 to 26 # For each such value, we find its level, row, and column for i in range(1,27): l1,r1,c1=rcOf(i,cfg1) l2,r2,c2=rcOf(i,cfg2) # For the values 1 to 26 # add to m the distance that must be travaled to match cfg1 to cg=fg2 m+=abs(l1-l2)+abs(r1-r2)+abs(c1-c2) return m # Generate all possible moves from this state (configuration) # cfg = a particular configuration of the puzzle # mvLsL = the list of possible moves from each position in a level # mvLsR = the list of possible moves from each position in a row # mvLsC = the list of possible moves from each position in a column # le, re, ce = the level, row, column of the empty space (represented by 0) def genMvs(cfg): mvLsL=[['up'],['down','up'],['down']] mvLsR=[['north'],['north','south'],['south']] mvLsC=[['west'],['east','west'],['east']] # Get the level, row, column of the empty space (0) le,re,ce=rcOf(0,cfg) # Based on the level,row,column value, get the list of moves # from mvLsL,mvLsr, mvLsC return mvLsL[le]+mvLsR[re]+mvLsC[ce] # Function to make a new configuration # mv = the move to take, resulting in a new state (configuration) # cfg = the current state (configuration) # le,re,ce = level,row,column of the empty space # lf,rf,cf = level,row,column of the tile to be moved # lmv,rmv,cmv = the amount (1,-1) tile must be moved # from level to level, row to row, from column to column # newCfg = the configuration resulting from that move # findLoc = a dictionary used for lookup # it gives the amount (1,-1) that a tile has to be moved # in order to go to its new location def mkNwCfg(mv,cfg): # Get the level, row, column of the empty space le,re,ce=rcOf(0,cfg) findLoc={'up':(1,0,0),'down':(-1,0,0),'north':(0,1,0),'south':(0,-1,0),'east':(0,0,-1),'west':(0,0,1)} # Use findLoc to calculate the amount by which tile must be moved lmv,rmv,cmv=findLoc[mv] # Calculate the new level, row, column of tile being moved lf,rf,cf=(le+lmv,re+rmv,ce+cmv) # Before making the move, make a "deep" copy of configuration newCfg=deepcopy(cfg) # Place the tile being moved, which is at position lf,rf,cf, # into the empty space, which is at re,ce newCfg[le][re][ce]=newCfg[lf][rf][cf] # Replace the old position of the tile, lf,rf,cf, by 0 newCfg[lf][rf][cf]=0 return newCfg # Function to make the node resulting from a tile being moved # mv = the move that is to be made # node = the current node whose tile is being moved # gcfg = the goal state (configuration) # newCfg = the new configuration resulting from the tile being moved # g = the g-value of the current node # h = the heuristic value calculated by the funciton "manh" # nwNdpath = the path from initial state to this new state def makMvNd(mv,node,gcfg): # Call mkNwCfg to get the state resulting from this move nwCfg=mkNwCfg(mv,node['cfg']) g=node['g'] h=manh(nwCfg,gcfg) # Make a copy of the path to the node from which move is being made # and append to the path the move being made nwNdpath=copy(node['path']) nwNdpath.append(mv) # Build the dictionary of the new node # notice the calculation of the new g-value and the new f-value return {'cfid':genCfId(nwCfg),'cfg':nwCfg,'g':g+1,'h':h,'f':g+1+h,'path':nwNdpath} # Build the dictionary of a node, given all of its component values # cfid,cfg,g,h,path - the component values of the node to be made def makNd(cfid,cfg,g,h,path): return {'cfid':cfid,'cfg':cfg,'g':g,'h':h,'f':g+h,'path':path} # Function to expand a node by finding its neighbors # and calculating the resulting new nodes # Calls genMvs to generate all possible moves # and makMvNd to make the nodes resulting from these moves # Uses a map and lambda combination which will be explained in class # node = node to be expanded # gcfg = goal state (configuration) - needed for calculating heuristic value def xpdNd(node,gcfg): return map(lambda mv:makMvNd(mv,node,gcfg),genMvs(node['cfg'])) #Utilities # separate a list of ordered pairs into two lists - the 1sts and the 2nds # pairs = the pairs to be separated def sepL(pairs): return map(lambda x:x[0],pairs),map(lambda x:x[1],pairs) #Insert item into an already sorted list by key value # Uses bisect to split the sorted lists at the place of insertion # and the slice operation to separate the lists into two parts # node = the node to be inserted into the list # f = the f-value, by which the list is ordered # L = the list into which insertion is to be made # correspons to WL, as seen above # keysL = list of keys of L # corresonds to WLfs, as seen above # idsL = list of configuration Ids # corresponds to WLids, as seen above # place = the place where node is to be inserted into L # Returns what will become the new values of WL, WLfs, WLids def insertKeyed(node,f,L,keysL,idsL): place=bisect.bisect_left(keysL,f) return L[:place]+[node]+L[place:],keysL[:place]+[f]+keysL[place:],idsL[:place]+[node['cfid']]+idsL[place:] # Test data # gcfg = goal state (configuration) gcfg = [[[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,14,15],[16,17,18]],[[19,20,21],[22,23,24],[25,26,0]]] # hcfg = testing one level up hcfg = [[[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,14,15],[16,17,0]],[[19,20,21],[22,23,24],[25,26,18]]] # ocfg = starting the empty space in the middle of the puzzle (simple 3d solving) ocfg = [[[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,0,15],[16,14,17]],[[19,20,21],[22,23,24],[25,26,18]]] # scfg = starting the empty space in the first level (simple 3d solving) scfg = [[[1,2,3],[4,5,6],[7,8,0]],[[10,11,12],[13,14,15],[16,17,9]],[[19,20,21],[22,23,24],[25,26,18]]] # scfg2 = starting the empty space in the first level (simple 3d solving) scfg2 = [[[1,2,3],[4,5,6],[7,8,0]],[[10,11,12],[13,14,18],[16,17,9]],[[19,20,21],[22,23,15],[25,26,24]]] # test = testing with only 2-dimensions in a 3D puzzle test = [[[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,14,15],[16,17,18]],[[22,19,23],[25,21,20],[26,0,24]]] # test2 = moderate 3d solving test2 = [[[2,5,3],[4,0,6],[7,8,9]],[[1,10,12],[13,11,14],[16,17,18]],[[19,20,21],[22,23,15],[25,26,24]]] # test3 = moderate 3d solving test3 = [[[10,5,2],[1,6,9],[8,4,18]],[[13,17,3],[25,0,14],[7,16,15]],[[19,11,12],[23,20,21],[22,26,24]]] nwcfg = [[[0,1,2],[3,4,5],[6,7,8]],[[9,10,11],[12,13,14],[15,16,17]],[[18,19,20],[21,22,23],[24,25,26]]]<file_sep>/csc237/project3/makefile #Author: <NAME> #Course: CSC 237 #File: makefile #Purpose: Links the WordList superclass to it's correct subclasses # and links the subclasses to their correct data member # objects (aka WordData, DLinkedList, Node, etc.) # Creates the executable app to test polymorphism cc=/opt/csw/gcc4/bin/g++ -std=gnu++0x app: app.o WordData.o WordDataList.o WordDataDLinkList.o DLinkedList.o WordDataSTList.o $(cc) -o app app.o WordData.o WordDataList.o WordDataDLinkList.o DLinkedList.o WordDataSTList.o WordData.o: WordData.cpp WordData.h $(cc) -c WordData.cpp WordDataSTList.o: WordData.h WordDataSTList.cpp WordDataSTList.h WordList.h $(cc) -c WordDataSTList.cpp WordDataList.o: WordData.h WordDataList.cpp WordDataList.h WordList.h $(cc) -c WordDataList.cpp WordDataDLinkList.o: WordDataDLinkList.cpp WordDataDLinkList.h DLinkedList.h $(cc) -c WordDataDLinkList.cpp DLinkedList.o: DLinkedList.cpp DLinkedList.h types.tpp cp DLinkedList.cpp temp.cpp cat types.tpp >> temp.cpp # Compile temporary file created with instantiations at the end; save as DLinkedList.o $(cc) -c temp.cpp -g -o DLinkedList.o app.o: WordDataList.h WordList.h WordDataDLinkList.h Node.h app.cpp $(cc) -c app.cpp clean: \rm -rf *.o app <file_sep>/csc242/Project/category.php <?php session_start(); $loggedin = $_SESSION['loggedin']; /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/category.php Course: CSC 242 - Fall 2013 */ echo "<html> <head> <title>Search Results</title> <link rel = 'stylesheet' type = 'text/css' href = 'projectstyle.css'/> </head> <body> <div class = 'header'><h1>Chris' Book Store</h1></div> <div class = 'special'> <h3><p class = 'one'> <a class = 'link' href = 'myproject.php'>Home</a> &nbsp; | &nbsp;"; if($loggedin == true) echo "<a class = 'link' href = 'loggedout.php'>Log Out</a> &nbsp; | &nbsp;"; else echo "<a class = 'link' href = 'login.html'>Log In</a> &nbsp; | &nbsp;"; echo "<a class = 'link' href = 'createaccount.php'>Create Account</a> &nbsp; | &nbsp; <a class = 'link' href = 'contact.php'>Contact Us</a> &nbsp; | &nbsp; <a class = 'link' href = 'categories.php'>Categories</a> &nbsp; | &nbsp; <a class = 'link' href = 'searchstart.php'>Search</a> &nbsp; | &nbsp; <a class = 'link' href = 'orders.php'>View Orders</a> &nbsp; | &nbsp; <a class = 'link' href = 'viewcart.php'>View Cart</a> </p></h3> <h3><div class = 'header'>Choose another category? <a class = 'link2' href = 'categories.php'>Click here</a></div></h3>"; //Open database $dsn = 'mysql:host=localhost;dbname=ccarr419_bookstore'; $username = 'ccarr419'; $password = '<PASSWORD>'; $db = new PDO($dsn, $username, $password); $query = "SELECT * FROM Categories"; $categories = $db->query($query); $j = 1; //get post info from categories.php $selectedCategory = array(); foreach($categories as $category) { $selectedCategory[] = $_POST[$category['CategoryID']]; } //Display products of selected category in a table $categories = $db->query($query); foreach($categories as $category) { foreach($selectedCategory as $i) { if($i == $category['CategoryName']) { echo "<form name = 'order' action = 'viewcart.php' method = 'post'><div class = 'special'><table style = 'margin-right: auto; margin-left:auto' border = '1' cellpadding = '5' bgcolor = '#aaaaaa'> <caption><h1 class = 'header'>" . $category['CategoryName'] . "</h1></caption><thead> <tr> <th><div class = 'special'>Title</div></th> <th><div class = 'special'>Author</div></th> <th><div class = 'special'>Product ID</div></th> <th><div class = 'special'>Price</div></th> <th><div class = 'special'>Quantity</div></th> </tr></thead>"; $query = "SELECT * FROM Products"; $products = $db->query($query); foreach($products as $product) { if($product['CategoryID'] == $category['CategoryID']) { echo "<tr><td><div class = 'special'>"; echo $product['Title']; echo "</div></td><td><div class = 'special'>"; echo $product['Author1']; echo "</div></td><td><div class = 'special'>"; echo $product['ProductID']; echo "</div></td><td><div class = 'special'>$"; echo round($product['Price'],2); echo "</div></td><td><div class = 'special'> <input type = 'text' name = '" . $product['ProductID'] . "' min = '0' max = '"; echo $product['Quantity']; echo "' value = '0' size = '3'/></div></td></tr>"; $j++; } } echo "</table></div><br/><input type = 'submit' value = 'Add to Cart'/></form>"; } } } echo " </body> </html>"; ?><file_sep>/csc520/finalproj/README.txt Author Name: <NAME> Course Name: Advanced OO Programming Course Number: CSC 520 Semester: Spring 2018 Professor: Dr. Schwesinger College: Kutztown University Due Date: 05/07/2018 HOW TO RUN: (1) To build project type 'ant' (2) To run project type 'java -jar dist/com.library.client.jar' HOW TO USE: (1) When ran the program will start on the home page (2) From here you may enter the following: (2.a) 'help' for a list of commands, (2.b) 'logon' to log in with an account *NOTE* Special made account for testing has these credentials: User Number: 1234 Password: <PASSWORD> *ENDNOTE* (2.c) 'nonmem' continue with non-member functionality (2.d) 'quit' to terminate the program (3) Members and Non-Members have access to the following: (3.a) 'index' displays book indexes in the catalog the user may type 'browse' to look up an index from there the user may type 'detail' to view details (3.b) 'search' shows all categories, publishers, and authors the user may type 'query' to query seach the catalog from there the user may type 'detail' to view details (4) Only Members have access to the following: (4.a) 'acc' account information page (4.b) 'res' reservations page/create reservation (4.c) 'bbook' borrowed book page (4.d) 'pass' password page (4.e) 'chpass' change user password (4.f) 'logoff' log off the user (4.g) 'cancel' cancel reservation (5) These commands are available on every page* (5.a) 'refrsh' refresh the page (5.b) 'back' go to the previous page* *(Not available on home or member page) *NOTE* Certain commands can only be used on certain pages. Enter command 'help' in system for a full list of all commands and where they can be used *ENDNOTE* DOCUMENTATION: (1) Documentation is found at http://csitrd.kutztown.edu/~ccarr419/csc520/final/finalproj/ (2) If documentation is not found or link is broken please feel to email me at <EMAIL> or edit the build.xml to your liking -- you have my permission. NOTES: (1) Because of a lack of time, there was no unit testing involved (2) Because of a lack of time, a limited amount of integration testing was done (only to make sure all parts of the client work) (3) At random times (~1-5% of the time) test data may not upload correctly causing logon to fail. Quitting and restarting the client or recompiling the system will most likely fix this. If it does not work the first time, it will certainly fix itself if done multiple times. There may either be a lag with data retrieval/entry somewhere or a hidden bug. <file_sep>/csc402/assignment6/arrayBsTree.h /* Author: <NAME> File: treeGraph.h Date: 10/18/2015 Class: CSC 402 About: Header file for treeGraph. treeGraph is a binary tree that ties together nodes in accordance to their values. This basic binary tree can insert nodes into the tree and print the tree in order, pre order or post order. */ #ifndef ARRAYBSTREE_H #define ARRAYBSTREE_H #include <iostream> #include "bsTree.h" class arrayBsTree : public bsTree { public: arrayBsTree(); bool find(int) const; void insert(int); void erase(int); void inOrder(std::ostream&) const; //NLR void preOrder(std::ostream&) const; //LNR void postOrder(std::ostream&) const; //LRN void lvlOrder(std::ostream&) const; //Print by height private: treeNode<int>* root; int nodeCount; //private helper functions for specific traversals void printInOrder(treeNode<int>*, std::ostream&) const; void printPreOrder(treeNode<int>*, std::ostream&) const; void printPostOrder(treeNode<int>*, std::ostream&) const; void printLvlOrder(treeNode<int>*, std::ostream&) const; }; #endif <file_sep>/csc552/README.txt CSC 552 - Advanced UNIX Programming Dr. <NAME> Kutztown University Spring 2017 This course studies the concepts dealing with UNIX system programming. A lot of emphasis will be placed on working with processes and interprocess communication (IPC). Details of various aspects of IPC will be explored and implemented, including pipes, semaphores, sockets, message queues and shared memory <file_sep>/csc520/finalproj/src/com/library/protocol/message_list/PMemberHome.java package com.library.protocol.message_list; import com.library.protocol.field_list.PMember; import com.library.protocol.field_list.PAddress; import com.library.protocol.field_list.PCreditCard; import java.util.Date; /** * PMemberHome serves a singular purpose of creating protocol variables * that will be used and sent back and forth from server to UI. * PROTOCOL LAYER */ public class PMemberHome { /** * Creates a PMember protocol variable. * @param n String member name * @param p String member phone number * @param a int member amount due * @param igs boolean member in good standing * @param num String member number * @return PMember */ public PMember create(String n, String p, int a, boolean igs, String num) { PMember pMem = new PMember(n, p, a, igs, num); return pMem; } /** * Creates a PCreditCard protocol variable. * @param type String card type * @param num String card number * @param ex Date card expiration date * @return PCreditCard */ public PCreditCard create(String type, String num, Date ex) { PCreditCard newCC = new PCreditCard(type, num, ex); return newCC; } /** * Creates a PAddress protocol variable. * @param house String house number * @param street String street addres * @param county String address county * @param zip String zip code * @return PAddress */ public PAddress create(String house, String street, String county, String zip) { PAddress newAdd = new PAddress(house, street, county, zip); return newAdd; } } <file_sep>/csc237/project1/WordInfo.cpp /** // Author: <NAME> // File: WordInfo.cpp // Purpose: The cpp file for the WordInfo class. // Implements the code to retrieve data // private members with gets and change those // members with sets. Operators are also used // for easier access to private members. */ #include <iostream> #include <string> #include <fstream> #include <iomanip> #include "WordInfo.h" using namespace std; //Constructor WordInfo::WordInfo(string wrd, int cnt) { setWord(wrd); setCount(cnt); } //User can set the value for word void WordInfo::setWord(string wrd) { word = wrd; } //User can set the value for count void WordInfo::setCount(int cnt) { count = cnt; } //User can get the value for word string WordInfo::getWord() const { return word; } //User can get the value for count int WordInfo::getCount() const { return count; } //Increments count by one void WordInfo::operator++(int) { count++; } //Stream extraction operator //Sets word from file and sets count to one ifstream &operator>>(ifstream &file, WordInfo &W) { string word; file >> word; W.setWord(word); W.setCount(1); return file; } //Stream insertion operator //Displays class object to screen ostream &operator<<(ostream &out, const WordInfo &W) { out << left << setw(15) << W.getWord() << W.getCount(); return out; } <file_sep>/csc135/format_ChristianCarreras.cpp //This program uses setw to format information. #include <iostream> #include <string> #include <iomanip> using namespace std; int main() { //User inputed variables. float gross_profit, net_profit; int num_adult_tickets, num_child_tickets; string movie; //Movie name. cout << "What is the name of the movie? "; getline(cin, movie); //Adult/child tickets. cout << "What was the number of adult tickets sold? "; cin >> num_adult_tickets; cout << "What was the number of child tickets sold? "; cin >> num_child_tickets; //User inputs values. cout << "What was the gross profit? $"; cin >> gross_profit; cout << "What was the net profit? $"; cin >> net_profit; cout << "\n"; //Format information. cout << left; cout << setw(30) << "Movie Name:" << movie << endl; cout << setw(30) << "Adult Tickets Sold:" << num_adult_tickets << endl; cout << setw(30) << "Child Tickets Sold:" << num_child_tickets << endl; cout << setw(30) << "Gross Box Office Profit:" << "$" << gross_profit << endl; cout << setw(30) << "Net Box Office Profit:" << "$" << net_profit << endl; return 0; } <file_sep>/csc402/assignment5/adjacencyListGraph.h /* Author: <NAME> File: adjacencyListGraph.h Class: CSC 402 Date: 10/11/2015 */ #include <iostream> #include "graph.h" using namespace std; class adjacencyListGraph : public graph { private: int** aList; int numNodes; vector<int> adjacent(int) const; bool find(vector<int>, int) const; void BFSHelper(queue<int>, vector<int>&) const; public: adjacencyListGraph(int n); ~adjacencyListGraph(); int numberOfVertices() const; int numberOfEdges() const; bool existsEdge(int, int) const; void insertEdge(int, int); void eraseEdge(int, int); int degree(int) const; void BFS(int, vector<int>&) const; void DFS(int, vector<int>&) const; /* Not a directed graph int inDegree(int) const; int outDegree(int) const; */ void output(ostream&) const; }; adjacencyListGraph::adjacencyListGraph(int n) { numNodes = n; aList = new int*[numNodes]; for(int i = 0; i < numNodes; i++) aList[i] = new int[numNodes]; for(int i = 0; i < numNodes; i++) for(int j = 0; j < numNodes; j++) aList[i][j] = -1; } adjacencyListGraph::~adjacencyListGraph() { delete [] aList; } int adjacencyListGraph::numberOfVertices() const { int numVertices = 0; for(int i = 0; i < numNodes; i++) { for(int j = 0; j < numNodes; j++) { if(aList[i][j] != -1) { numVertices++; break; } } } return numVertices; } int adjacencyListGraph::numberOfEdges() const { int numEdges = 0; for(int i = 0; i < numNodes; i++) for(int j = 0; j < numNodes; j++) if(aList[i][j] != -1) numEdges++; return numEdges; } bool adjacencyListGraph::existsEdge(int from, int to) const { return (aList[from][to] != -1 && aList[to][from] != -1); } void adjacencyListGraph::insertEdge(int f, int t) { aList[f][t] = t; aList[t][f] = f; } void adjacencyListGraph::eraseEdge(int f, int t) { aList[f][t] = -1; aList[t][f] = -1; } int adjacencyListGraph::degree(int from) const { int degree = 0; for(int i = 0; i < numNodes; i++) if(aList[from][i] != -1) degree++; return degree; } /* Not a directed graph int adjacencyListGraph::inDegree(int) const { } int adjacencyListGraph::outDegree(int) const { } */ void adjacencyListGraph::output(ostream& out) const { for(int i = 0; i < numNodes; i++) { out << "[" << i << "] = ( "; for(int j = 0; j < numNodes; j++) { if(aList[i][j] != -1) out << aList[i][j] << " "; } out << ")\n"; } } void adjacencyListGraph::BFS(int v, vector<int>& visited_list) const { queue<int> q; q.push(v); visited_list.push_back(v); BFSHelper(q, visited_list); } void adjacencyListGraph::BFSHelper(queue<int> q, vector<int>& visited_list) const { if(q.empty()) return; vector<int> adjacent_vertices = adjacent(q.front()); for(int i = 0; i < adjacent_vertices.size(); i++) { if(!find(visited_list, adjacent_vertices.at(i))) { visited_list.push_back(adjacent_vertices.at(i)); q.push(adjacent_vertices.at(i)); } } q.pop(); BFSHelper(q, visited_list); } void adjacencyListGraph::DFS(int v, vector<int>& visited_list) const { visited_list.push_back(v); vector<int> adjacent_vertices = adjacent(v); for(int i = 0; i < adjacent_vertices.size(); i++) { int w = adjacent_vertices.at(i); if(find(visited_list, w)) continue; else DFS(w, visited_list); } } vector<int> adjacencyListGraph::adjacent(int start) const { vector<int> adjacent_list; for(int i = 0; i < numNodes; i++) if(aList[start][i] != -1) adjacent_list.push_back(i); return adjacent_list; } bool adjacencyListGraph::find(vector<int> list, int v) const { for(int i = 0; i < list.size(); i++) if(list.at(i) == v) return true; return false; } <file_sep>/csc552/project3/server.cpp /* Author: <NAME> Filename: server.cpp Course: CSC 552 About: This project creates a real-time message server where clients are allowed to sign-on and message each other. All information about the clients and the server is location in shared memory and is updated accordingly. */ #include <iostream> #include <stdio.h> #include <string.h> #include <netdb.h> #include <sys/mman.h> using namespace std; /* acad Internet address, defined in /etc/hosts */ // This is the new acad's IP address #define SERV_HOST_ADDR "172.16.17.32" #define BUFF_SIZE 128 //Maximum message buffer size #define MAX_CLI_SIZE 25 //Maximum number of clients allowed on the server #define USRNAME_SIZE 20 //Maximum username length #define TIME_FSIZE 13 //Length of the time format string //Server log flags #define STD_MES 0 //Standard message #define F_CSER 1 //Child server forked #define T_CSER 2 //Child server terminated #define M_SENT 3 //Message sent #define USR_IN 4 //User logged in #define USR_OUT 5 //User logged out #define UNK_OUT 6 //Unknown user terminated #define M_FAIL 7 //Message failed to send //MES is a basic message packet to send between server and clients typedef struct { long mtype; long number; //A number if one needs to be sent char username[USRNAME_SIZE]; //sender's username char recipient[USRNAME_SIZE]; //recipient's username char letter[BUFF_SIZE]; //The message struct sockaddr_in addr; //Address of the sender/recipient } MES; //A struct for the LookUpTable to contain user information typedef struct { int sfd; //initial file descriptor for log out information bool inUse; //tells if the current slot in the table is being used struct sockaddr_in address; //address of the client char name[USRNAME_SIZE]; //username of the client char startTime[TIME_FSIZE]; //time the client logged in char lastLookUp[TIME_FSIZE]; //time the client was last looked up } client_info; //LookUpTable in shared memory which holds information on all active users typedef struct { client_info client[MAX_CLI_SIZE]; int numClients; } sharedMemory; sharedMemory* startShm(struct sockaddr_in); void getTime(char[]); void userExistsPrompt(int); void serverFullPrompt(int); void unkownUserPrompt(int, char[]); void senIsRecpPrompt(int); void messageStsPrompt(int, int); void printAllUsers(int, sharedMemory*); void sLog(int f=0, int n=0, char m[]=NULL, char u[]=NULL, char r[]=NULL); void setSharedMem(int, int, sharedMemory*, sockaddr_in&, char[], char[]); int logInHandler(int, int, int&, sharedMemory*, struct sockaddr_in&); int mesHandler(int, int, int, sharedMemory*); int lookUpServerChild(int, int, sockaddr_in&, sharedMemory*); int startStrmSoc(struct sockaddr_in&, int); int startDgrmSoc(struct sockaddr_in&, int); int logUserIn(int, int, sharedMemory*, char[], sockaddr_in&); int logUserOut(int, sharedMemory*); int testUser(int, sharedMemory*, char[]); int compareCaseIns(string, string); int findUser(char[], sockaddr_in&, sharedMemory*); int sendMessage(int, int, MES&, sharedMemory*); main(int argc,char *argv[]) { struct sockaddr_in cli_addr, serv_addr; int sfd, nfd, clilen, numfork = 0; int SERV_TCP_PORT = 15030; sharedMemory *shm; //Create a stream socket to listen for requests from clients if((sfd = startStrmSoc(serv_addr, SERV_TCP_PORT)) == -1) return 0; //the socket failed to be created shm = startShm(serv_addr); //Create the shared memory space cout << "Please run the program client now.\n"; while(1) { clilen = sizeof(cli_addr); //Wait until a new client tries to connect if((nfd = accept(sfd, (struct sockaddr *) &cli_addr, (socklen_t *) &clilen)) < 0) { cout << "server: accept error\n"; return 0; } //Fork a new child process to handle all the client's needs sLog(F_CSER, ++numfork); bool isParent = fork(); if(!isParent) { if(!lookUpServerChild(nfd, numfork, cli_addr, shm)) { return 0; } //The client terminated/logged off } } } //Creates the shared memory space by using mmap //mmap automatically cleans up when done sharedMemory* startShm(struct sockaddr_in serv_addr) { int size = sizeof(sharedMemory *); //size to allocate in shared memory sharedMemory *shm = (sharedMemory *) mmap(&serv_addr, size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0); //Initilize all rows in shared memory to be not in use for(int i = 0; i < MAX_CLI_SIZE; i++) shm->client[i].inUse = false; shm->numClients = 0; //should be no clients yet return shm; } //Returns the formatted local time (origin of the server "EDT") in a c_str() void getTime(char timestr[]) { time_t rawtime; time(&rawtime); struct tm* currentTime = localtime(&rawtime); //turn into string of hh:mm:ss 'timezone' in 24H format strftime(timestr, TIME_FSIZE, "%H:%M:%S %Z", currentTime); } //Send a message to the client saying the username they picked exists already void userExistsPrompt(int fd) { MES out_mes; out_mes.number = htonl(-1); strncpy(out_mes.letter, "Username exists already.", sizeof(out_mes.letter)); write(fd, &out_mes, sizeof(MES)); } //Send a message to the client saying the server is at capacity void serverFullPrompt(int fd) { MES out_mes; out_mes.number = htonl(-1); strncpy(out_mes.letter, "Server is at capacity. Try again later.", sizeof(out_mes.letter)); write(fd, &out_mes, sizeof(MES)); } //Send a message to the client saying the user they looked up does not exist void unkownUserPrompt(int fd, char user[]) { MES out_mes; strncpy(out_mes.username, "s", sizeof(out_mes.username)); strncpy(out_mes.letter, "The user, \"", sizeof(out_mes.letter)); strcat(out_mes.letter, user); strcat(out_mes.letter, "\" does not exist."); write(fd, &out_mes, sizeof(MES)); } //Send a message to the client saying the user they looked up was themselves void senIsRecpPrompt(int fd) { MES out_mes; strncpy(out_mes.username, "s", sizeof(out_mes.username)); strncpy(out_mes.letter, "Cannot send a message to yourself. Stop.", sizeof(out_mes.letter)); write(fd, &out_mes, sizeof(MES)); } //Send a message to the client stating if their message sent or not void messageStsPrompt(int sts, int fd) { MES out_mes; strncpy(out_mes.username, "s", sizeof(out_mes.username)); if(sts != -1) { strncpy(out_mes.letter, "Message sent", sizeof(out_mes.letter)); write(fd, &out_mes, sizeof(MES)); } else { strncpy(out_mes.letter, "Message failed to send", sizeof(out_mes.letter)); write(fd, &out_mes, sizeof(MES)); sLog(M_FAIL); } } //Make a list of all current users in sharedMemory and send to the client void printAllUsers(int fd, sharedMemory *shm) { MES m_out; sprintf(m_out.letter, "(%d", shm->numClients); strcat(m_out.letter, ") USERS\n"); strcat(m_out.letter, "--------------\n"); for(int i = 0; i < MAX_CLI_SIZE; i++) { if(shm->client[i].inUse) { if(strlen(m_out.letter) >= BUFF_SIZE - USRNAME_SIZE) { write(fd, &m_out, sizeof(MES)); strcpy(m_out.letter, ""); } else { strcat(m_out.letter, shm->client[i].name); strcat(m_out.letter, "\n"); } } } write(fd, &m_out, sizeof(MES)); } //Print log information to the server screen //Use flags to use predetermined log messages void sLog(int flg, int num, char mes[], char usr[], char recp[]) { char tstr[TIME_FSIZE]; getTime(tstr); cout << "(" << tstr << ") "; switch(flg) { case 0: cout << "Server: " << mes << endl; break; case 1: cout << "Forking new lookup server child " << num << ".\n"; break; case 2: cout << "Terminating lookup server child " << num << ".\n"; break; case 3: cout << "Message sent from " << usr << " to " << recp << ": "; cout << mes << endl; break; case 4: cout << usr << " logged in.\n"; break; case 5: cout << usr << " logged out.\n" ; break; case 6: cout << "Unknown user terminated.\n"; break; case 7: cout << "Failed to write message.\n"; break; default: cout << "\n"; } } //Initialize the free space in shared memory to the client's information //Assumes that the space is free (or else information will be overriden) void setSharedMem(int s, int fd, sharedMemory* shm, sockaddr_in &addr, char usr[], char tstr[]) { shm->client[s].sfd = fd; shm->client[s].inUse = true; shm->client[s].address = addr; strncpy(shm->client[s].name, usr, sizeof(shm->client[s].name)); strncpy(shm->client[s].startTime, tstr, sizeof(shm->client[s].startTime)); strncpy(shm->client[s].lastLookUp, tstr, sizeof(shm->client[s].lastLookUp)); } //Attempts to log the client into the server. If the username picked exists //or the server is at capacity, the user will be informed. Otherwise their //information will be put into sharedMemory and they will be allowed to //send messages and see shared memory data int logInHandler(int fd, int num, int &PORT, sharedMemory *mem, struct sockaddr_in &addr) { MES tmp; int slot; //Check if the user logs outs before logging in if(read(fd, &tmp, sizeof(MES)) <= 0) { logUserOut(fd, mem); sLog(T_CSER, num); return 0; } //Check if username exists or server is at capacity slot = testUser(fd, mem, tmp.username); PORT += slot; //Unique port for the client logUserIn(fd, slot, mem, tmp.username, addr); mem->numClients++; return 1; } //Receives a message from the client and determines which course of action to //take. Either sending a message to another client or releasing requested info int mesHandler(int sfd, int dfd, int num, sharedMemory *shm) { MES tmp; //Check if the user logged out if(read(sfd, &tmp, sizeof(MES)) <= 0) { logUserOut(sfd, shm); shm->numClients--; sLog(T_CSER, num); return 0; } //Null-terminate message just in case tmp.letter[strlen(tmp.letter)] = '\0'; string recipient = tmp.recipient; //Check if the client requested to see all active users if(recipient.compare("a") == 0) printAllUsers(sfd, shm); else //Otherwise send a message to the specified user sendMessage(dfd, sfd, tmp, shm); return 1; } //Handles all child lookUpServer duties after the fork int lookUpServerChild(int nfd, int num, sockaddr_in &addr, sharedMemory *shm) { int CLI_TCP_PORT = 15225; //Attempt to log user in. If they logout, terminate if(!logInHandler(nfd, num, CLI_TCP_PORT, shm, addr)) { return 0; } //Set up a datagram for use in client2client messaging int dgrmfd = startDgrmSoc(addr, CLI_TCP_PORT); //Once logged in, wait for messages and respond until the client logs off while(1) { if(!mesHandler(nfd, dgrmfd, num, shm)) { return 0; } } } //Create a stream socket for server2client communication int startStrmSoc(struct sockaddr_in &addr, int PORT) { int sockfd; /* create a socket which is one end of a communication channel */ if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { cout << "server: cannot open stream socket\n"; return -1; } /* initialize server address */ memset(&addr, '\0', sizeof(addr)); addr.sin_family = AF_INET; /* address family: Internet */ addr.sin_addr.s_addr = htonl(INADDR_ANY); /* accept a connection on any Internet interface */ addr.sin_port = htons(PORT); /* specify port number */ /* associate server address with the socket */ if(bind(sockfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) { cout << "server: cannot bind local address\n"; return -1; } /* specify the queue size of the socket to be 5 */ if(listen(sockfd, MAX_CLI_SIZE) < 0) { cout << "server: listen error\n"; return -1; } return sockfd; } //Create a datagram socket for client2client communication int startDgrmSoc(struct sockaddr_in &addr, int PORT) { int sockfd; /* create a socket which is one end of a communication channel */ if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { cout << "server: cannot open dgram socket\n"; return -1; } return sockfd; } //Log the client in and attempt to get their address for use in datagrams //Assumes the client has met all the necessary preconditions to be logged in int logUserIn(int fd, int s, sharedMemory *shm, char usr[], sockaddr_in &addr) { MES out_mes, tmp; char tstr[TIME_FSIZE]; out_mes.number = htonl(s); if(write(fd, &out_mes, sizeof(MES)) == -1) return 0; if(read(fd, &tmp, sizeof(MES)) == -1) return 0; addr = tmp.addr; setSharedMem(s, fd, shm, addr, usr, tstr); sLog(USR_IN, 0, NULL, usr); return 1; } //Logs a user out and resets their space in shared memory to not being in use int logUserOut(int fd, sharedMemory *shm) { char timestr[TIME_FSIZE]; getTime(timestr); for(int i = 0; i < MAX_CLI_SIZE; i++) { if(fd == shm->client[i].sfd) { sLog(USR_OUT, 0, NULL, shm->client[i].name); shm->client[i].inUse = false; return 1; } } sLog(UNK_OUT); return 0; } //Tests if the username given exists in shared memory or if the server is full int testUser(int fd, sharedMemory *shm, char usr[]) { int fslot = -1; string testMESname = usr; for(int i = 0; i < MAX_CLI_SIZE; i++) { string testMMname = shm->client[i].name; if(shm->client[i].inUse) { //Check if the username exists already if(compareCaseIns(testMESname, testMMname)) { userExistsPrompt(fd); return -1; } if(i == MAX_CLI_SIZE-1) { //Check if server is full serverFullPrompt(fd); return -1; } } //Save free slot until it is made sure the username does not exist else { fslot = (fslot == -1 ? i : fslot); } } return fslot; } //Compares two strings without case-sensitivity int compareCaseIns(string str1, string str2) { for(int i = 0; i < str1.length(); i++) { if(isalpha(str1[i])) str1[i] = tolower(str1[i]); } for(int j = 0; j < str2.length(); j++) { if(isalpha(str2[j])) str2[j] = tolower(str2[j]); } if(str1.compare(str2) == 0) return 1; else return 0; } //Find the current slot in shared memory the user resides in //If the user does not exist, return -1 int findUser(char usr[], sockaddr_in &addr, sharedMemory* mem) { string testMESusr = usr; for(int i = 0; i < MAX_CLI_SIZE; i++) { string testMMname = mem->client[i].name; if(mem->client[i].inUse) { if(compareCaseIns(testMESusr, testMMname)) { addr = mem->client[i].address; return i; } } } return -1; } //Send a message from one client to another. If the user exists, check if //the user matches the sender and inform the user if so. Otherwise attempt to //send the message to other client. //If the user does not exist, inform the client. int sendMessage(int dfd, int sfd, MES &m, sharedMemory *shm) { MES m_out; int slot; char timestr[TIME_FSIZE]; struct sockaddr_in recp_addr; string testMESrec = m.recipient; string testMESname = m.username; //Check if the recipient exists if((slot = findUser(m.recipient, recp_addr, shm)) != -1) { //Check if the recipient is the sender if(testMESrec.compare(testMESname) == 0) { senIsRecpPrompt(sfd); } else { sLog(M_SENT, 0, m.letter, m.username, m.recipient); strncpy(m_out.username, "s", sizeof(m_out.username)); strncpy(m_out.recipient, m.recipient, sizeof(m_out.recipient)); //If message failed to send if(sendto(dfd, &m, sizeof(MES), 0, (struct sockaddr *) &shm->client[slot].address, sizeof(shm->client[slot].address)) == -1) { messageStsPrompt(-1, sfd); } else { //Message was successfully sent messageStsPrompt(0, sfd); getTime(timestr); memcpy(shm->client[slot].lastLookUp, timestr, TIME_FSIZE); return 1; } } } //Recipient does not exist else { unkownUserPrompt(sfd, m.recipient); } return 0; } <file_sep>/csc237/project3/WordDataSTList.h /** * Author: <NAME> * File: WordDataSTList.h * Date Created: 3/30/14 * Class: CSC 237 Spring 2014 * Purpose: This is the header file for the WordDataSTList class. * The WordDataSTList is a subclass of the WordList class. * Using pure virtual functions in the WordList class the * subclasses inherits those functions and implements them * through polymorphism. Meaning the function is linked up * to the correct use of that function at run time for there * are multiple uses of that function due to inheritance. * This class uses the Standard Library List (STL) list to * hold data (WordData objects) and uses the inherited functions * to add to the list and print the list iteratively and * recursively with the help of helper functions. **/ #ifndef WORDDATASTLIST_H #define WORDDATASTLIST_H #include "WordList.h" #include "WordData.h" #include <list> using namespace std; class WordDataSTList : public WordList { public: /** * This is the WordSTList constructor. The constructor creates the * WordDataSTList. This is a default constructor meaning that this * is the default C++ constructor for all objects. **/ WordDataSTList(); /** * This function uses polymorphism to link up the pure virtual function * from the superclass to the code for the subclasses' use of that * function. This function reads the parameter file and parses the * strings into the list into using the WordData object data type. * IncMatch is also called to check for duplicates. **/ void parseIntoList(ifstream &); /** * This function also uses polymorphism to link up the pure virtual * function from the superclass. The purpose of this function is to * iterate through the list one by one and print the data to the * screen until the end of the screen is reached. **/ void printIteratively(); /** * This is another function that uses polymorphism from the superclass. * The purpose of this function is iterate through the list with * recursive calls (with the help of the printRecursivelyWorker functon) **/ void printRecursively(); private: list<WordData> STList; /** * This function is a helper function to printRecursively. This function * actually makes the recursive calls by iterating through the list one * by one and printing the data until the end of the list is reached. **/ void printRecursivelyWorker(list<WordData>::iterator); /** * This function is a helper function to parseIntoList. This function * checks for a duplicate occurrence within the list. If a duplicate * is found then the number of occurrences for that word is increased * by one and true is returned. If no duplicate is found then false * is returned and the list is unchanged. **/ bool incMatch(string); }; #endif <file_sep>/csc242/Project/orderdetails.php <?php session_start(); $loggedin = $_SESSION['loggedin']; /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/orderdetails.php Course: CSC 242 - Fall 2013 */ //Create page with same style sheet and links as rest of website echo "<html xmlns = 'http://www.w3.org/1999/xhtml'> <head> <title> Chris' Book Store </title> <!-- My stylesheet for the project --> <link rel = 'stylesheet' type = 'text/css' href = 'projectstyle.css'/> </head> <body> <!-- Links --> <div class = 'header'><h1>Chris' Book Store</h1></div> <div class = 'special'> <h3><p class = 'one'> <a class = 'link' href = 'myproject.php'>Home</a> &nbsp; | &nbsp;"; if($loggedin == true) echo "<a class = 'link' href = 'loggedout.php'>Log Out</a> &nbsp; | &nbsp;"; else echo "<a class = 'link' href = 'login.html'>Log In</a> &nbsp; | &nbsp;"; echo "<a class = 'link' href = 'createaccount.php'>Create Account</a> &nbsp; | &nbsp; <a class = 'link' href = 'contact.php'>Contact Us</a> &nbsp; | &nbsp; <a class = 'link' href = 'categories.php'>Categories</a> &nbsp; | &nbsp; <a class = 'link' href = 'searchstart.php'>Search</a> &nbsp; | &nbsp; <a class = 'link' href = 'orders.php'>View Orders</a> &nbsp; | &nbsp; <a class = 'link' href = 'viewcart.php'>View Cart</a> </p></h3>"; //Connect to the database $dsn = 'mysql:host=localhost;dbname=ccarr419_bookstore'; $username = 'ccarr419'; $password = '<PASSWORD>'; $db = new PDO($dsn, $username, $password); //Get info from the OrderDetails table $query = "SELECT * FROM OrderDetails"; $orders = $db->query($query); $id = array(); foreach($orders as $order) { $id[] = $_POST[$order['OrderID']]; } echo "<h3><div class = 'header'>View another order? <a class = 'link2' href = 'orders.php'>Click here</a></div></h3>"; //Create a table containing order details of specific order echo "<table style = 'margin-right: auto; margin-left:auto' border = '1' cellpadding = '5' bgcolor = '#aaaaaa'> <thead><tr> <th>Order ID</th> <th>Product ID</th> <th>Quantity</th> <th>Line Total</th> </tr></thead>"; $query = "SELECT * FROM OrderDetails"; $orders = $db->query($query); foreach($orders as $order) { foreach($id as $i) { if($i == $order['OrderID']) { echo "<tr><td><div class = 'special'>"; echo $order['OrderID']; echo "</div></td><td><div class = 'special'>"; echo $order['ProductID']; echo "</div></td><td><div class = 'special'>"; echo $order['Quantity']; echo "</div></td><td><div class = 'special'>$"; echo round($order['LineTotal'], 2); echo "</div></td></tr>"; } } } echo "</table></div></body> </html>"; ?><file_sep>/csc135/bmi_ChristianCarreras.cpp //This program calculates the user's bmi #include <iostream> #include <string> using namespace std; int main() { string name; float weight, height, bmi; cout << "What is your name? "; getline(cin, name); cout << "What is your weight in pounds? "; cin >> weight; cout << "What is your height in inches? "; cin >> height; bmi = (703*weight)/(height*height); cout << "Hello, " << name << endl; cout << "Your weight is " << weight << " pounds.\n"; cout << "Your height is " << height << " inches.\n"; cout << "Your body mass index is " << bmi << "." << endl; return 0; } <file_sep>/csc552/project3/client.cpp /* Author: <NAME> Filename: client.cpp Course: CSC 552 About: This project creates a real-time message client that will attempt to connect to a server. Clients will be allowed to message other clients once logged-in. All information about clients on a local machine is held in shared memory. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> #include <iostream> #include <string> #include <fcntl.h> #include <ifaddrs.h> #include <ctype.h> #include <sys/shm.h> using namespace std; /* acad's Internet address, defined in /etc/hosts */ #define SERV_HOST_ADDR "172.16.17.32" #define BUFF_SIZE 128 #define USRNAME_SIZE 20 #define MAX_CLIENTS 25 #define TIME_FSIZE 13 typedef struct { long mtype; long number; char username[USRNAME_SIZE]; char recipient[USRNAME_SIZE]; char letter[BUFF_SIZE]; struct sockaddr_in addr; } MES; typedef struct { char name[USRNAME_SIZE]; char startTime[TIME_FSIZE]; char lastMsgTime[TIME_FSIZE]; int numMsg; pid_t pid; } LOCAL_INFO; typedef struct { LOCAL_INFO localInfo[MAX_CLIENTS]; int numClients; int totalMsgs; } LOCAL_DIR; void getTime(char[]); void logOff(LOCAL_DIR*, int, int); void updateInfo(LOCAL_DIR*, int); void splitMessage(string, MES&, sockaddr_in&, int); void clientAddr2Ser(sockaddr_in&, sockaddr_in&, int, int); bool findBlankSpaces(string); bool checkMessage(char[]); int setLocalInfo(LOCAL_DIR*, string); int compareCaseIns(string, string); int readMessages(int, int); int sendMessage(string, MES&, sockaddr_in&, int); int execExit(); int execAll(int, MES&, sockaddr_in&); int execList(LOCAL_DIR*); int testUsername(string); int registerUser(int, int&, string, sockaddr_in&); int startStrmSock(sockaddr_in&, int); int startDgrmSock(sockaddr_in&); char* parseInput(char[]); struct sockaddr_in getLocalAddrs(); string login(int, int, int&, char*[], sockaddr_in&); main(int argc, char* argv[]) { key_t key = 5678; int sockfd, dgrmfd, shmid, num; int CLI_TCP_PORT = 15225; int SERV_TCP_PORT = 15030; int size = sizeof(LOCAL_DIR); struct sockaddr_in serv_addr, cli_addr; LOCAL_DIR *dir; MES mes_out; string tmpMessage, tmpName; sockfd = startStrmSock(serv_addr, SERV_TCP_PORT); tmpName = login(argc, sockfd, CLI_TCP_PORT, argv, serv_addr); if(tmpName == "") { close(sockfd); return 0; } if ((shmid = shmget(key, size, IPC_CREAT | 0666)) < 0) { cout << "shmget error\n"; close(sockfd); return 0; } if ((dir = (LOCAL_DIR *) shmat(shmid, NULL, 0)) == (LOCAL_DIR *) -1) { cout << "shmat error\n"; close(sockfd); return 0; } num = setLocalInfo(dir, tmpName); clientAddr2Ser(serv_addr, cli_addr, CLI_TCP_PORT, sockfd); dgrmfd = startDgrmSock(cli_addr); strncpy(mes_out.username, tmpName.c_str(), USRNAME_SIZE); cout << "\n<**> "; cout << "Welcome to the chat room, " << mes_out.username << endl; while(1) { cout << "<" << mes_out.username << ">\n"; getline(cin, tmpMessage); char message[tmpMessage.length()+1]; char *recp; strcpy(message, tmpMessage.c_str()); if(tmpMessage == ""); else if(compareCaseIns(tmpMessage, "EXIT")) { if(execExit()) break; } else if(compareCaseIns(tmpMessage, "ALL")) { execAll(sockfd, mes_out, serv_addr); continue; } else if(compareCaseIns(tmpMessage, "LIST")) { execList(dir); continue; } else if((recp = parseInput(message)) != NULL) { tmpMessage.erase(0, strlen(recp)+1); strncpy(mes_out.recipient, recp, USRNAME_SIZE); if(tmpMessage.length() < 1) cout << "<**> " << "No message written. Try again.\n\n"; else if(sendMessage(tmpMessage, mes_out, serv_addr, sockfd)) updateInfo(dir, num); } sleep(1); if(!readMessages(sockfd, dgrmfd)) continue; } logOff(dir, shmid, sockfd); return 0; } void getTime(char timestr[]) { time_t rawtime; time(&rawtime); struct tm* currentTime = localtime(&rawtime); strftime(timestr, TIME_FSIZE, "%H:%M:%S %Z", currentTime); } void logOff(LOCAL_DIR *dir, int shmid, int sockfd) { dir->numClients--; if(dir->numClients == 0) shmctl(shmid, IPC_RMID, (shmid_ds *) NULL); close(sockfd); } void updateInfo(LOCAL_DIR *dir, int num) { char timestr[TIME_FSIZE]; getTime(timestr); dir->totalMsgs++; dir->localInfo[num].numMsg++; strcpy(dir->localInfo[num].lastMsgTime, timestr); } void splitMessage(string tmes, MES &m_out, sockaddr_in &addr, int fd) { MES tmp; int i = 0; size_t mes_size; do { string tmpStr = tmes.substr((i*(BUFF_SIZE-1)), tmes.length()); mes_size = tmpStr.length(); strncpy(m_out.letter, tmpStr.c_str(), BUFF_SIZE-1); if(sendto(fd, &m_out, sizeof(MES),0, (struct sockaddr *) &addr, sizeof(addr)) == -1) { cout << "client: write error\n"; return; } i++; sleep(1); if(read(fd, &tmp, sizeof(MES)) == -1) { return; } cout << "<**> " << tmp.letter << "(" << i << ")\n"; } while(mes_size >= BUFF_SIZE); cout << endl; } void clientAddr2Ser(sockaddr_in &to, sockaddr_in &from, int PORT, int fd) { MES init; from = getLocalAddrs(); from.sin_port = PORT; init.addr = from; sendto(fd, &init, sizeof(MES),0, (struct sockaddr *) &to, sizeof(to)); } bool findBlankSpaces(string tmp) { for(int i = 0; i < tmp.length(); i++) { if(tmp[i] == ' ') return true; } return false; } bool checkMessage(char tmp[]) { if(tmp[0] == ' ') return true; return false; } int setLocalInfo(LOCAL_DIR* dir, string tmpName) { char timestr[TIME_FSIZE]; int num = dir->numClients++; if(!num) dir->totalMsgs = 0; getTime(timestr); strncpy(dir->localInfo[num].name, tmpName.c_str(), USRNAME_SIZE); strcpy(dir->localInfo[num].startTime, timestr); strcpy(dir->localInfo[num].lastMsgTime, timestr); dir->localInfo[num].numMsg = 0; dir->localInfo[num].pid = getpid(); return num; } int readMessages(int sfd, int dfd) { MES tmp; if(read(sfd, &tmp, sizeof(MES)) != -1) cout << "<**> " << tmp.letter << "\n\n"; if(read(dfd, &tmp, sizeof(MES)) != -1) cout << "<" << tmp.username << ">\n" << tmp.letter << "\n\n"; return 1; } int sendMessage(string tmes, MES &m_out, sockaddr_in &addr, int fd) { if(tmes.length() >= BUFF_SIZE) { splitMessage(tmes, m_out, addr, fd); //updateInfo(dir, num); } else { strncpy(m_out.letter, tmes.c_str(), BUFF_SIZE-1); if(sendto(fd, &m_out, sizeof(MES),0, (struct sockaddr *) &addr, sizeof(addr)) == -1) { cout << "client: write error\n"; return 0; } //updateInfo(dir, num); } return 1; } int execExit() { string tmpStr; cout << "\n<**> " << "Are you sure you want to quit? (y or n)\n"; cout << "<**> "; getline(cin, tmpStr); if((tolower(tmpStr[0])) == 'y') { cout << "<**> Goodbye\n\n"; return 1; } else if((tolower(tmpStr[0])) != 'n') cout << "<**> Invalid entry\n"; cout << endl; return 0; } int execAll(int sfd, MES &m, sockaddr_in &addr) { MES tmp; strcpy(m.recipient, "a"); if(sendto(sfd, &m, sizeof(MES),0,(struct sockaddr *) &addr, sizeof(addr)) == -1) { cout << "client: write error\n"; return 0; } sleep(1); if(read(sfd, &tmp, sizeof(MES)) != -1) cout << "\n<**>\n" << tmp.letter; if(read(sfd, &tmp, sizeof(MES)) != -1) cout << tmp.letter; if(read(sfd, &tmp, sizeof(MES)) != -1) cout << tmp.letter; cout << "<**>\n\n"; return 1; } int execList(LOCAL_DIR *ld) { cout << "<**>\n"; for(int i = 0; i < ld->numClients; i++) { cout << ld->localInfo[i].name << "; "; cout << ld->localInfo[i].startTime << "; "; cout << ld->localInfo[i].lastMsgTime << "; "; cout << ld->localInfo[i].numMsg << "; "; cout << ld->localInfo[i].pid << ";\n"; } cout << "<**>\n\n"; } int compareCaseIns(string str1, string str2) { for(int i = 0; i < str1.length(); i++) { if(isalpha(str1[i])) str1[i] = tolower(str1[i]); } for(int j = 0; j < str2.length(); j++) { if(isalpha(str2[j])) str2[j] = tolower(str2[j]); } if(str1.compare(str2) == 0) return 1; else return 0; } int testUsername(string tmpName) { if(findBlankSpaces(tmpName)) cout << "Remove all blank spaces and try again.\n"; else if(tmpName.length() == 0) cout << "Please enter a username.\n"; else if(tmpName.length() >= USRNAME_SIZE) cout << "Username is too long. Try again.\n"; else if(tmpName.length() <= 2) cout << "Username is too short. Try again.\n"; else if(compareCaseIns(tmpName, "EXIT")) cout << "Username cannot be keyword. Try again.\n"; else if(compareCaseIns(tmpName, "ALL")) cout << "Username cannot be keyword. Try again.\n"; else if(compareCaseIns(tmpName, "LIST")) cout << "Username cannot be keyword. Try again.\n"; else return 1; return 0; } int registerUser(int sfd, int &PORT, string tmpName, sockaddr_in &addr) { MES init, tmp; strncpy(init.username, tmpName.c_str(), sizeof(init.username)); if(sendto(sfd, &init, sizeof(MES),0, (struct sockaddr *) &addr, sizeof(addr)) == -1) { cout << "client: write"; return 0; } sleep(1); if(read(sfd, &tmp, sizeof(MES)) == -1); else if(ntohl(tmp.number) != -1) { PORT += ntohl(tmp.number); return 1; } cout << tmp.letter << endl; return 0; } int startStrmSock(sockaddr_in &addr, int PORT) { int sfd, flags; /* create a socket which is one end of a communication channel */ if((sfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { cout << "client: cannot open stream socket"; return -1; } /* specify server address */ memset(&addr, '\0', sizeof(addr)); addr.sin_family = AF_INET; /* address family: Internet */ addr.sin_addr.s_addr = inet_addr(SERV_HOST_ADDR); addr.sin_port = htons(PORT); cout << "Connecting to server...\n"; if(connect(sfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) { cout << "client: cannot connect to server\n"; return -1; } if ((flags = fcntl(sfd, F_GETFL, 0)) < 0) { cout << "client: cannot get socket's flag\n"; return -1; } if (fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) { cout << "client: cannot change socket to non-blocking\n"; return -1; } return sfd; } int startDgrmSock(sockaddr_in &addr) { int dfd, flags; if((dfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { cout << "client: cannot open dgram socket\n"; return -1; } if(bind(dfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) { cout << "client: cannot bind local address\n"; return -1; } if ((flags = fcntl(dfd, F_GETFL, 0)) < 0) { cout << "client: cannot get socket's flag\n"; return -1; } if (fcntl(dfd, F_SETFL, flags | O_NONBLOCK) < 0) { cout << "client: cannot change socket to non-blocking\n"; return -1; } return dfd; } char* parseInput(char str[]) { char* recp; if(checkMessage(str)) { cout << "\n<**> "; cout << "Remove all unnecessary blank spaces and try again.\n\n"; return NULL; } else { recp = strtok(str, " "); if(strlen(recp) <= 2) { cout << "\n<**> " << "Recipient name too short. Try again.\n\n"; return NULL; } else if(strlen(recp) >= 15) { cout << "\n<**> " << "Recipient name too long. Try again.\n\n"; return NULL; } } return recp; } struct sockaddr_in getLocalAddrs() { struct ifaddrs *addrs, *tmpAddrs; struct sockaddr_in *homeAddress; getifaddrs(&addrs); tmpAddrs = addrs; while (tmpAddrs) { if (tmpAddrs->ifa_addr && tmpAddrs->ifa_addr->sa_family == AF_INET) homeAddress = (struct sockaddr_in *) tmpAddrs->ifa_addr; tmpAddrs = tmpAddrs->ifa_next; } freeifaddrs(addrs); return *homeAddress; } string login(int argc, int sfd, int &PORT, char *argv[], sockaddr_in &addr) { string tmpName; if(argc > 1) { tmpName = argv[1]; if(testUsername(tmpName)) { if(!registerUser(sfd, PORT, tmpName, addr)) { return ""; } return tmpName; } else { return ""; } } else { cout << "Please enter your username: "; while(1) { getline(cin, tmpName); if(testUsername(tmpName)) { if(registerUser(sfd, PORT, tmpName, addr)) break; else return ""; } } return tmpName; } } <file_sep>/csc235/project4/readme.txt Author: <NAME> Class: CSC 235 Assignment: #4 File: readme.txt Date Created: December 4, 2014 Problems encountered in Project 4 1.) Segfaults and Bus Errors for multiple entries a.) Ctrl-D did not end data entry b.) Skipped name entry after first employee Notes on 1: I kept to one entry as I didn't have time to fix issues with multiple entries 2.) Half int values do not show up properly Notes on 2: I found that the value depends on values of 2^8 i.e. if value is 256-511, output will be one if value is 512-767, output will be two. etc. 3.) Cannot get smaller fit of data members within frame width a.) Bus Errors for any other location of data members Notes on 3: Only works for the way the data is currently spaced 4.) 4-bit ints did not work for any value of frame a.) Bus Errors Other notes on Project 4 1.) Search not implemented - I could not get multiple entries to work 2.) SearchEmployee not implemented - I could not get multiple entries to work 3.) I did not fully understand the tagged bit so it was left out. a.) In its place I read the char again and tested whether it was h or H 4.) Parameter values and return values were not precise to specifications as I wanted it work first before I had it exact. I could not find out how to do certain means of passing parameters or returning values. 5.) The incompleteness of the project came down to a time issue. <file_sep>/csc237/project4/makefile # Author: <NAME> # Documented By: <NAME> # File: makefile # Date: 25/04/2014 # Purpose: Links the BinarySearch tree .cpp file to its .h file # Then links those files to TreeTest.cpp # Creates the executable named tree debugFlag=-g tree: BinarySearchTree.o Treetest.o g++ -o tree Treetest.o BinarySearchTree.o $(debugFlag) Treetest.o: Treetest.cpp BinarySearchTree.h g++ -c Treetest.cpp $(debugFlag) BinarySearchTree.o: BinarySearchTree.cpp BinarySearchTree.h g++ -c BinarySearchTree.cpp $(debugFlag) clean: \rm -f *.o testdate <file_sep>/csc402/assignment6/makefile # Author: <NAME> # File: makefile # Date: 10/18/2015 # Class: CSC 402 # About: Makefile for compiling instructions of the treeGraph # class and its tester file. arrayBsDemo: arrayBsDemo.o arrayBsTree.o g++ -o arrayBsDemo arrayBsDemo.o arrayBsTree.o arrayBsTree.o: arrayBsTree.cpp arrayBsTree.h bsTree.h g++ -c arrayBsTree.cpp arrayBsDemo.o: arrayBsDemo.cpp arrayBsTree.cpp arrayBsTree.h g++ -c arrayBsDemo.cpp clean: \rm -f *.o arrayBsDemo<file_sep>/sideprojects/replaceAll.cpp #include <iostream> #include <string> using namespace std; string replaceAll(string, string, string); string replaceAllNoReplace(string, string, string); int main(int argc, char** argv) { cout << "Before: " << argv[1] << endl; string myStr = replaceAll(argv[1], argv[2], argv[3]); cout << "After: " << myStr << endl; cout << endl << "NO REPLACE\n\n"; cout << "Before: " << argv[1] << endl; myStr = replaceAllNoReplace(argv[1], argv[2], argv[3]); cout << "After: " << myStr << endl; } string replaceAll(string inStr, string toRep, string repStr) { size_t pos = 0, from = 0; while((pos = inStr.find(toRep, from)) != std::string::npos) { inStr.replace(pos, toRep.length(), repStr, 0, repStr.length()); from = pos+repStr.length(); } return inStr; } string replaceAllNoReplace(string inStr, string toRep, string repStr) { size_t pos = 0, from = 0; while((pos = inStr.find(toRep, from)) != std::string::npos) { inStr.erase(pos, toRep.length()); inStr.insert(pos, repStr); from = pos+repStr.length(); } return inStr; } /* JAVA EQUIVALENT public string replaceAllNoReplace(string inStr, string toRep, string repStr) { int pos = 0, from = 0; while((pos = inStr.indexOf(toRep, from)) != -1) { inStr.erase(pos, toRep.length()); inStr.insert(pos, repStr); from = pos+repStr.length(); } } */ <file_sep>/csc402/inclassprograms/arrayMaxHeap.h #include <iostream> #include "maxHeap.h" using namespace std; template<class T> class arrayMaxHeap : public maxHeap<T> { private: T* root; int heapSize; int arrayLength; void changeArrayLength(int); int getParentIndex(int theIndex) {return theIndex/2;} int getLeftChildIndex(int theIndex) {return theIndex*2;} int getRightChildIndex(int theIndex) {return theIndex*2+1;} public: arrayMaxHeap(); bool empty() const {return heapSize == 0;} int size() const {return heapSize;} void push(const T& theKey); T pop(); T top() const; void heapify(T*); void print() const; }; template<class T> arrayMaxHeap<T>::arrayMaxHeap() { heapSize = 0; arrayLength = 10; root = new T[arrayLength]; } template<class T> void arrayMaxHeap<T>::push(const T& theKey) { if(heapSize-1 == arrayLength) changeArrayLength(2*arrayLength); if(empty()) { root[heapSize+1] = theKey; heapSize++; return; } root[heapSize+1] = theKey; heapSize++; int theIndex = heapSize; while(theIndex > 1) { int parentIndex = getParentIndex(theIndex); if(root[theIndex] < root[parentIndex]) break; else { swap(root[theIndex], root[parentIndex]); theIndex = parentIndex; } } } template<class T> T arrayMaxHeap<T>::pop() { if(size() == 1) { heapSize--; return NULL; } root[1] = root[heapSize]; heapSize--; int theIndex = 1; while(theIndex < heapSize/2+1) { int leftChildIndex = getLeftChildIndex(theIndex); int rightChildIndex = getRightChildIndex(theIndex); if(root[theIndex] < root[leftChildIndex] && root[leftChildIndex] > root[rightChildIndex]) { swap(root[theIndex], root[leftChildIndex]); theIndex = leftChildIndex; } else if(root[theIndex] < root[rightChildIndex] && root[rightChildIndex] > root[leftChildIndex]) { swap(root[theIndex], root[rightChildIndex]); theIndex = rightChildIndex; } else break; } return theIndex; } template<class T> T arrayMaxHeap<T>::top() const { return root[1]; } /*template<class T> void arrayMaxHeap<T>::heapify(T* theKey) { }*/ template<class T> void arrayMaxHeap<T>::changeArrayLength(int newLength) { T* tmp = new T[newLength]; copy(root+1, root+heapSize, tmp); arrayLength = newLength; delete [] root; root = tmp; } template<class T> void arrayMaxHeap<T>::print() const { for(int i = 1; i <= heapSize; i++) cout << root[i] << ' '; cout << endl; } template class arrayMaxHeap<int>; <file_sep>/csc237/project2/WordDataList.cpp /* // Author: <NAME> // Documented By: <NAME> // Course: CSC 237 // Filename: WordDataList.cpp // Purpose: Container of WordData objects // Implementations of member functions // including inherited pure virtual fns. */ #include <sstream> #include <iostream> #include "WordDataList.h" using namespace std; /* //Constructor */ WordDataList::WordDataList() { numWords = 0; } /* //Checks for a match in data witin an object array */ bool WordDataList::incMatch(string temp) { for(int i = 0; i < numWords; i++) { if(temp == TheWords[i].getWord()) { TheWords[i].incCount(); return true; } } return false; } /* //Parses file into an array of objects */ void WordDataList::parseIntoList(ifstream &inf) { string temp; while(inf >> temp) { if(!incMatch(temp) && numWords < 10) { TheWords[numWords].setWord(temp); TheWords[numWords++].setCount(1); } } } /* //Print the data iteratively */ void WordDataList::printIteratively() { cout << "--------------------------" << endl; cout << "|Object Array Iterative|" << endl; cout << "|Word Occurences |" << endl; cout << "--------------------------" << endl; for(int i = 0; i < numWords; i++) cout << " " << TheWords[i] << endl; } /* // Print the data recursively */ void WordDataList::printRecursivelyWorker(int numWords) { if(numWords==1) { cout << "--------------------------" << endl; cout << "|Object Array Recursive|" << endl; cout << "|Word Occurences |" << endl; cout << "--------------------------" << endl; cout << " " << TheWords[numWords-1] << endl; return; } printRecursivelyWorker(numWords-1); cout << " " << TheWords[numWords-1] << endl; } /* //Call worker function to print the data recursively */ void WordDataList::printRecursively() { printRecursivelyWorker(numWords); } /* //Print the data recursively with a pointer */ void WordDataList::printPtrRecursivelyWorker(int numWords) { if(!numWords) { cout << "--------------------------" << endl; cout << "|Object Array Pointer |" << endl; cout << "|Word Occurences |" << endl; cout << "--------------------------" << endl; return; } printPtrRecursivelyWorker(numWords-1); cout << " " << *(TheWords+(numWords-1)) << endl; } /* //Call worker function to print the data recursively */ void WordDataList::printPtrRecursively() { printPtrRecursivelyWorker(numWords); } <file_sep>/README.txt All projects were planned, written and managed from beginning to completion by I, <NAME> with the exception of some files being required for my files to work properly or team projects. All projects were completed at Kutztown University of Pennsylvania for course credit from August 2012 to May 2018. Descriptions of courses and projects will be included where necessary. A higher course number generally represents a more recent and difficult course/project Course numbers < 400 represent undergrad courses, course numbers >= 400 represent grad courses COURSE LIST: ----------------------------------------------------------------- * CSC 135 - Computer Science I * CSC 136 - Computer Science II * CSC 235 - Computer Organization and Assembly Language * CSC 237 - Data Structures * CSC 241 - Advanced Visual Basic Programming * CSC 242 - Web Programming * CSC 310 - Programming Languages * CSC 320 - Game Development for Computer Scientists I * CSC 330 - Introduction to Mobile Architecture and Systems * CSC 342 - Web Technologies * CSC 354 - Software Engineering I * CSC 355 - Software Engineering II ----------------------------------------------------------------- * CSC 402 - Advanced Data Structures * CSC 421 - Web-Based Software Design and Development * CSC 423 - Game Development for Computer Scientists II * CSC 510 - Advanced Operating Systems * CSC 520 - Advanced Object-Oriented Programming * CSC 548 - Artificial Intelligence II * CSC 552 - Advanced UNIX Programming * CSC 554 - Project Management * CSC 558 - Data Mining and Predictive Analytics II * CSC 570 - Independent Study and/or Projects in Computer Science Solutions written for the KU programming team and code written in my spare time at KU are also included <file_sep>/csc342/Site/App_Code/Direction.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; public enum Direction { Horizontal, Vertical }<file_sep>/csc570/TensorFlowTutorials/GettingStarted/benchmark.py import time import tensorflow as tf def main(argv): with tf.device('/cpu:0'): t0 = time.time() """ Do Something """ t1 = time.time() total = t1-t0 print(total) with tf.device('/device:GPU:0'): t0 = time.time() """ Do Something """ t1 = time.time() total = t1-t0 print(total) if __name__ == '__main__': tf.app.run(main) <file_sep>/csc402/inclassprograms/handinprograms/pigLatin.cpp #include <iostream> #include <string> using namespace std; string translate(string); bool isVowel(char); int main() { string inputString, outputString; cout << "Enter your string here: "; cin >> inputString; outputString = translate(inputString); cout << "Translated to pig latin: " << outputString << endl; } string translate(string input) { string temp1, temp2, output; if(input == "") return ""; temp1 = ""; temp2 = ""; for(int i = 0; i < input.length(); i++) { if(i == 0 && isVowel(input[i])) return (input += "-way"); if(isVowel(input[i])) { for(int j = i; j < input.length(); j++) temp2 += input[j]; output = temp2; output += "-"; output += temp1; output += "ay"; return output; } else temp1 += input[i]; } return (input += "-way"); } bool isVowel(char input) { const char vowels[12] = {'a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y'}; for(int i = 0; i < 12; i++) { if(input == vowels[i]) return true; } return false; } <file_sep>/csc136/project4/p4.cpp ///////////////////////////////////////////////////////////// //File: p4.cpp //Author: <NAME> //Course: CSC136 //Assignment: Project 4 //Description: Tests and implements the Polynomial class // with a menu and user interface //////////////////////////////////////////////////////////// #include <iostream> #include <fstream> #include <string> #include <cstdlib> #include "poly.h" //Polynomial header file using namespace std; //////////////////////////////////////////////////// //Function: openFile //Description: Asks the user for a file // and checks if it exists //Parameters: ifstream - to open and read file //Returns: bool /////////////////////////////////////////////////// bool openFile(ifstream&); /////////////////////////////// //Function: menu //Description: Opens menu //Parameters: none //Returns: void ////////////////////////////// void menu(); ////////////////////////////////////////////////////////// //Function: choose //Description: Opens user interface //Parameters: Polynomial - uses the polynomial class //Returns: bool ///////////////////////////////////////////////////////// bool choose(Polynomial&); ////////////////////////////////////////////////////// //Function: evaluate //Description: Evaluates polynomial for input x //Parameters: Polynomial //Returns: void ////////////////////////////////////////////////////// void evaluate(Polynomial&); ///////////////////////////////////////////////////////// //Function: multiply //Description: Multiplies polynomial by a scalar value //Parameters: Polynomial //Returns: void ///////////////////////////////////////////////////////// void multiply(Polynomial&); ////////////////////////////////////////////////////// //Function: print //Description: Prints polynomial to screen //Parameters: Polynomial //Returns: void ////////////////////////////////////////////////////// void print(Polynomial&); ////////////////////////////////////////////////////// //Function: add //Description: Adds a term to the polynomial //Parameters: Polynomial //Returns: void ////////////////////////////////////////////////////// void add(Polynomial&); /////////////////////////////////////// //Function: exit //Description: Closes the program //Parameters: Polynomial //Returns: bool /////////////////////////////////////// bool exit(Polynomial&); /////////////////////////////////////////////////// //Function: remove //Description: removes Term from the LinkedList //Parameters: Polynomial //Returns: void /////////////////////////////////////////////////// void remove(Polynomial&); int main() { Polynomial poly; //Polynomial class ifstream inf; bool fileOpen; //Get file from user and check to see if it exists fileOpen = openFile(inf); //If the file exists if(fileOpen == true) { cout << "\nFile Loaded\n\n"; poly.readFile(inf); //Read the file into the polynomial do //Menu system that will run at least once { menu(); fileOpen = choose(poly); } while(fileOpen == true); } //Error message and terminate program else { cout << "Failed to open file\n\n"; } return 0; } //Asks user for file and checks if it exists bool openFile(ifstream &inf) { string file; cout << "\nPlease enter a file: "; getline(cin, file); inf.open(file.c_str()); //Attempt to open the file if(inf.fail()) //If the file doesn't exist return false; else //If the file exists return true; } //Menu layout for user void menu() { cout << "Chris' Polynomial Program\n"; for(int j = 0; j < 25; j++) { cout << "="; } cout << "\n(E)valuate\n"; cout << "(M)ultiply\n"; cout << "(P)rint\n"; cout << "(A)dd\n"; cout << "E(x)it\n"; cout << "(R)emove\n\n"; //Ask user to enter their choice cout << "Please enter your choice: "; } //User interface bool choose(Polynomial &poly) { bool doNotClose; char choice; cin >> choice; switch(toupper(choice)) { //Evaluate case 'E': //Ask the user for a value of x evaluate(poly); return doNotClose = true; break; //Multiply case 'M': //This will multiply all the coeff by a scalar value multiply(poly); return doNotClose = true; break; //Print case 'P': //Shows the polynomial read in from the file print(poly); return doNotClose = true; break; //Add case 'A': //Asks the for a coeff and expn to added to the polynomial add(poly); return doNotClose = true; break; //Exit case 'X': return doNotClose = exit(poly); break; //Remove case 'R': remove(poly); return doNotClose = true; break; //Error message default: cout << "Invalid entry\n\n"; return doNotClose = true; break; } } //Evaluates polynomial for x which is user defined void evaluate(Polynomial &poly) { double x; //Holds value for 'x' in the Polynomial cout << "\nPlease enter a value for X: "; cin >> x; //Call the overloaded () operator cout << "\nThe polynomial equals: " << poly.operator()(x); cout << " for x = " << x << endl << endl; } //Multiplies the polynomial by the user defined scalar value void multiply(Polynomial &poly) { float factor; cout << "\nPlease enter a value to multiply by: "; cin >> factor; //Call the overloaded *= operator poly.operator*=(factor); cout << "\nThe polynomial equals: " << poly << endl << endl; } //Prints the polynomial to the screen void print(Polynomial &poly) { cout << "\nThe polynomial equals: " << poly << endl << endl; } //Adds a user-defined term to the polynomial void add(Polynomial &poly) { float coeff; int expn; //Ask for the coefficient to be added cout << "\nPlease enter a value for the coefficient: "; cin >> coeff; //Ask for the exponent to be added cout << "Please enter a value for the exponent: "; cin >> expn; //Add to polynomial if it meets the add function's criteria poly.add(coeff, expn); //Display the polynomial cout << "\nThe polynomial equals: " << poly << endl << endl; } //Asks the user if they really want to exit and if they //want to save the polynomial to an external file bool exit(Polynomial &poly) { bool doNotClose; char answer, save; //Is the user sure if they they want to exit? cout << "Are you sure you want to exit? (y or n): "; cin >> answer; if(tolower(answer) == 'y') { cout << "Goodbye\n\n"; return doNotClose = false; } else if(tolower(answer) == 'n') //Return to the menu { cout << "Back to the menu\n\n"; return doNotClose = true; } else { //Will return user to menu interface cout << "Invalid entry\n\n"; return doNotClose = true; } } //Asks the user for the exponent of the Term they wish to remove //Then calls removeTerm to check if the LinkedList contains the Term //If so, it removes the term and gives confirmation //If not, tells the user of failure void remove(Polynomial &poly) { int expn; cout << "Enter the exponent of the term you want to remove: "; cin >> expn; if(poly.removeTerm(expn)) //If term was found and removed cout << "Term was removed successfully!\n\n"; else //If the term wasn't found cout << "Term was not removed!\n\n"; } <file_sep>/csc237/project2/testll.cpp /* // Author: <NAME> // Course: CSC 237 // File: testll.cpp // Purpose: Fully tests the DLinkedList class by letting the user // freely insert/remove integers and use the data members // to print the list, check if the list is empty, and find // the first/node in the list */ #include<iostream> #include "DLinkedList.h" #include "Node.h" using namespace std; /* // Function Name: menu // Parameters: none // Returns: void // Purpose: displays the menu for the user to see */ void menu(); /* // Function Name: options // Parameters: DLinkedList<int>& - import only // Returns: int - user's choice (exit or not) // Purpose: Creates the interface for the user */ int options(DLinkedList<int>&); /* // Function Name: insertIntoList // Parameters: DLinkedList<int>& - import only // Returns: void // Purpose: Asks user for an integer and inserts it into the list */ void insertIntoList(DLinkedList<int>&); /* // Function Name: removeFromList // Parameters: DLinkedList<int>& - import only // Returns: void // Purpose: Asks user for an integer and removes that integer if // it is found in the list. Tells user if successful */ void removeFromList(DLinkedList<int>&); /* // Function Name: checkEmpty // Parameters: DLinkedList<int>& - import only // Returns: void // Purpose: Checks if the current is empty */ void checkEmpty(DLinkedList<int>&); /* // Function Name: findFirst // Parameters: DLinkedList<int>& - import only // Returns: void // Purpose: Finds the first node in the list */ void findFirst(DLinkedList<int>&); /* // Function Name: findLast // Parameters: DLinkedList<int>& - import only // Returns: void // Purpose: Finds the last node in the list */ void findLast(DLinkedList<int>&); /* // Function Name: printListForward // Parameters: DLinkedList<int>& - import only // Returns: void // Purpose: Prints list first-last */ void printListForward(DLinkedList<int>&); /* // Function Name: printListBackward // Parameters: DLinkedList<int>& - import only // Returns: void // Purpose: Prints list last-first */ void printListBackward(DLinkedList<int>&); int main() { DLinkedList<int> theList; char num = '0'; while(num != '8') //Exit selected or not { menu(); num = options(theList); } cout << "\nProgram Session Terminated\n\n"; return 0; } /* //Displays the menu for the user to see */ void menu() { cout << "\nDOUBLE LINKED LIST TEST PROGRAM\n"; cout << "1. Insert Into List\n"; cout << "2. Remove From List\n"; cout << "3. Check If List Is Empty\n"; cout << "4. Find First Node\n"; cout << "5. Find Last Node\n"; cout << "6. Display List Forwards\n"; cout << "7. Display List Backwards\n"; cout << "8. Exit\n"; } /* //Creates the interface for the user to: //*Insert into list //*Remove from list //*Check if list is empty //*Find the first node //*Find the last node //*Print list forwards //*Print list backwards */ int options(DLinkedList<int>&l) { char choice; cout << "\nPlease enter your choice: "; cin >> choice; switch(choice) { case '1': //Insert insertIntoList(l); break; case '2': //Remove removeFromList(l); break; case '3': //Check if list is empty checkEmpty(l); break; case '4': //Find first node findFirst(l); break; case '5': //Find last node findLast(l); break; case '6': //Print first-last printListForward(l); break; case '7': //Print last-first printListBackward(l); break; case '8': //Exit cout << "Goodbye\n"; break; default: //Error-catch cout << "\nNot a valid choice\n"; break; } return choice; } /* //Asks user for an integer to insert into list */ void insertIntoList(DLinkedList<int>&l) { int num; cout << "\nPlease enter an integer to insert: "; cin >> num; if(l.insert(num)) //Display current list printListForward(l); else cout << "Error inserting into list\n"; } /* //Asks user for an integer to remove from the list //Tells user if the number wasn't in the list */ void removeFromList(DLinkedList<int>&l) { int num; cout << "\nPlease enter an integer to remove: "; cin >> num; if(l.remove(num)) //Display current list printListForward(l); else cout << "Number was not found\n"; } /* //Checks if head == NULL (list is empty) */ void checkEmpty(DLinkedList<int>&l) { DListItr<int> it(l); if(it.isEmpty()) cout << "\nThe list is empty\n"; else cout << "\nThe list is not empty\n"; } /* //Find what head is pointing to (first node) and print to screen */ void findFirst(DLinkedList<int>&l) { DListItr<int> it(l); while(!(it.isFirstNode())) ++it; cout << "\nThe first in the list is " << *it << endl; } /* //Find last node in the list and print to screen */ void findLast(DLinkedList<int>&l) { DListItr<int> it(l); while(!(it.isLastNode())) ++it; cout << "\nThe last in the list is " << *it << endl; } /* //Print the current list first node to last node */ void printListForward(DLinkedList<int>&l) { cout << "\nCurrent List: "; for(DListItr<int> it(l); !(it.isNull()); ++it) cout << *it << " "; cout << endl; } /* //Print current list last node to first node */ void printListBackward(DLinkedList<int>&l) { DListItr<int> it(l); cout << "\nCurrent List: "; for( ; !(it.isNull()); ++it) //Go to last node if(it.isLastNode()) break; for( ; !(it.isNull()); --it) //Then print backwards cout << *it << " "; cout << endl; } <file_sep>/csc402/inclassprograms/inheritence.cpp #include <iostream> using namspace std; class base { private: int x; public: base(int n) { cout << "constructing base\n"; setx(n); } ~base() { cout << "deconstructing base\n"; } void setx(int n) { x = n: } void showx() { cout << "x=" << x << endl; } }; class derived : public base { private: int y; public: derived(int n) : base(n) { cout << "constructing derived\n"; sety(n); } void sety(int n) { y = n; } void showy() { cout << "y=" << y << endl; } }; int main() { return 0; } <file_sep>/csc242/Project/purchasemade.php <?php session_start(); $loggedin = $_SESSION['loggedin']; $purchases = $_SESSION['order']; $custID = $_SESSION['custID']; $sNh = $_POST['sNh']; $tax = $_POST['tax']; $qty = $_POST['qty']; $id = $_POST['id']; $total = $_POST['total']; /* Name: <NAME> Project: Designing Web Page Purpose: Book store website URL: http://unixweb.kutztown.edu/~ccarr419/purchasemade.php Course: CSC 242 - Fall 2013 */ //Create page with same style sheet and links as rest of website echo "<html xmlns = 'http://www.w3.org/1999/xhtml'> <head> <title> Chris' Book Store </title> <!-- My stylesheet for the project --> <link rel = 'stylesheet' type = 'text/css' href = 'projectstyle.css'/> </head> <body> <!-- Links --> <div class = 'header'><h1>Chris' Book Store</h1></div> <div class = 'special'> <h3><p class = 'one'> <a class = 'link' href = 'myproject.php'>Home</a> &nbsp; | &nbsp;"; if($loggedin == true) echo "<a class = 'link' href = 'loggedout.php'>Log Out</a> &nbsp; | &nbsp;"; else echo "<a class = 'link' href = 'login.html'>Log In</a> &nbsp; | &nbsp;"; echo "<a class = 'link' href = 'createaccount.php'>Create Account</a> &nbsp; | &nbsp; <a class = 'link' href = 'contact.php'>Contact Us</a> &nbsp; | &nbsp; <a class = 'link' href = 'categories.php'>Categories</a> &nbsp; | &nbsp; <a class = 'link' href = 'searchstart.php'>Search</a> &nbsp; | &nbsp; <a class = 'link' href = 'orders.php'>View Orders</a> &nbsp; | &nbsp; <a class = 'link' href = 'viewcart.php'>View Cart</a> </p></h3><br/>"; //Thank user for order echo "<h1 class = 'header'>Thank you! Your order has been confirmed!</h1></div> </body> </html>"; $dsn = 'mysql:host=localhost;dbname=ccarr419_bookstore'; $username = 'ccarr419'; $password = '<PASSWORD>'; $db = new PDO($dsn, $username, $password); $query = "SELECT * FROM Orders"; $orders = $db->query($query); //Find OrderID for OrderDetails table $higest = 0; foreach($orders as $order) { if($order['OrderID'] > $higest) { $highest = $order['OrderID'] + 1; } } $ordernum = $highest; //Add info into Orders and OrderDetails table insertOrder($custID, $sNh, $tax, $qty); insertDetails($ordernum, $id, $qty, $total); function insertOrder($custID, $sNh, $tax, $qty) { $dsn = 'mysql:host=localhost;dbname=ccarr419_bookstore'; $username = 'ccarr419'; $password = '<PASSWORD>'; $db = new PDO($dsn, $username, $password); $query = "INSERT INTO Orders (CustomerID, ShippingCost, Tax, Total, OrderDate) VALUES ('$custID', '$sNh', '$tax', '$qty', NOW())"; $insert_count = $db->exec($query); } function insertDetails($ordernum, $id, $qty, $total) { $dsn = 'mysql:host=localhost;dbname=ccarr419_bookstore'; $username = 'ccarr419'; $password = '<PASSWORD>'; $db = new PDO($dsn, $username, $password); $query = "INSERT INTO OrderDetails (OrderID, ProductID, Quantity, LineTotal) VALUES ('$ordernum', '$id', '$qty', '$total')"; $insert_count = $db->exec($query); } unset($_SESSION['order']); ?><file_sep>/csc135/temperature_ChristianCarreras.cpp //This program uses if/else to tell the user how cold/warm it is. #include <iostream> using namespace std; int main() { float temperature; //Ask user for temperature. cout << "What is the current temperature? "; cin >> temperature; //If/else statements. if (temperature < 32) cout << "It is freezing today.\n"; else if (temperature < 59) cout << "It is cold today.\n"; else if (temperature < 86) cout << "It is warm today.\n"; else cout << "It is hot today.\n"; return 0; } <file_sep>/csc330/assignment2/TipCalculator/tipCalculator_christianCarreras/ViewController.swift // // ViewController.swift // tipCalculator_christianCarreras // // Created by <NAME> on 2/14/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billAmountLabel: UILabel! @IBOutlet weak var customTipPercentageLabel1: UILabel! @IBOutlet weak var customTipPercentageSlider: UISlider! @IBOutlet weak var tip15Label: UILabel! @IBOutlet weak var total15Label: UILabel! @IBOutlet weak var customTipPercentageLabel2: UILabel! @IBOutlet weak var tipCustomLabel: UILabel! @IBOutlet weak var totalCustomLabel: UILabel! @IBOutlet weak var inputTextField: UITextField! @IBOutlet weak var customPartySizeLabel: UILabel! @IBOutlet weak var customPartySizeSlider: UISlider! @IBOutlet weak var customTipPercentageLabel3: UILabel! @IBOutlet weak var partyPay15Label: UILabel! @IBOutlet weak var partyPayCustomLabel: UILabel! let decimal100 = NSDecimalNumber(string: "100.0") let decimal15Percent = NSDecimalNumber(string: "0.15") override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. inputTextField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func calculateTip(sender: AnyObject) { let inputString = inputTextField.text let sliderValue = NSDecimalNumber(integer: Int(customTipPercentageSlider.value)) let customPercent = sliderValue/decimal100 let partySize = NSDecimalNumber(integer: Int(customPartySizeSlider.value)) if sender is UISlider { customTipPercentageLabel1.text = NSNumberFormatter.localizedStringFromNumber(customPercent, numberStyle: NSNumberFormatterStyle.PercentStyle) customTipPercentageLabel2.text = customTipPercentageLabel1.text customTipPercentageLabel3.text = customTipPercentageLabel1.text customPartySizeLabel.text = NSNumberFormatter.localizedStringFromNumber(partySize, numberStyle: NSNumberFormatterStyle.NoStyle) } if !inputString!.isEmpty { let billAmount = NSDecimalNumber(string: inputString) / decimal100 let fifteenTip = billAmount * decimal15Percent let customTip = billAmount * customPercent if sender is UITextField { billAmountLabel.text = " " + formatAsCurrency(billAmount) tip15Label.text = formatAsCurrency(fifteenTip) total15Label.text = formatAsCurrency(billAmount + fifteenTip) partyPay15Label.text = formatAsCurrency((billAmount + fifteenTip)/partySize) } tipCustomLabel.text = formatAsCurrency(customTip) totalCustomLabel.text = formatAsCurrency(billAmount + customTip) partyPayCustomLabel.text = formatAsCurrency((billAmount + customTip)/partySize) partyPay15Label.text = formatAsCurrency((billAmount + fifteenTip)/partySize) } else { billAmountLabel.text = "" tip15Label.text = "" total15Label.text = "" tipCustomLabel.text = "" totalCustomLabel.text = "" } } } func formatAsCurrency(number: NSNumber) -> String { return NSNumberFormatter.localizedStringFromNumber(number, numberStyle: NSNumberFormatterStyle.CurrencyStyle) } func +(left: NSDecimalNumber, right: NSDecimalNumber) -> NSDecimalNumber { return left.decimalNumberByAdding(right) } func *(left: NSDecimalNumber, right: NSDecimalNumber) -> NSDecimalNumber { return left.decimalNumberByMultiplyingBy(right) } func /(left: NSDecimalNumber, right: NSDecimalNumber) -> NSDecimalNumber { return left.decimalNumberByDividingBy(right) } <file_sep>/csc342/Site/Demos/Email.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net.Mail; public partial class Demos_Email : BasePage { protected void Page_Load(object sender, EventArgs e) { MailMessage myMessage = new MailMessage(); myMessage.Subject = "Test Message"; myMessage.Body = "Hello world, from Planet Wrox"; myMessage.From = new MailAddress("<EMAIL>"); myMessage.To.Add(new MailAddress("<EMAIL>")); SmtpClient mySmtpClient = new SmtpClient(); mySmtpClient.Send(myMessage); } }<file_sep>/csc135/serviceProvider_ChristianCarreras.cpp /***************************************************************** Project 2 This program uses switch and if/else statements to create a menu system which tells the user how much he/she owes for the month Author: <NAME> Class: CSC 135 Date Due: 10/18/2012 ******************************************************************/ #include <iostream> #include <iomanip> using namespace std; int main() { //Declare variables char choice; //User's choice float price_a, price_b, price_c; //Price of the choice cout << endl; cout << "What package did you purchase? [A, B, C]: "; //Menu cin >> choice; switch (choice) //Switch statement { case 'A': //If user enters A int hours1; price_a = 9.95; //Package A cout << "How many hours did you use? "; //Ask user for hours cin >> hours1; cout << endl; if (hours1 > 10) //If the hours entered are greater than 10 { float output; output = price_a + (hours1 - 10) * 2.00; //Calculate cout << setprecision(2) << fixed; // Display results cout << choice << setw(10) << hours1 << setw(10) << "$" << output << endl; } else //If the hours entered are less than 10 cout << choice << setw(10) << hours1 << setw(10) << "$" << price_a << endl; break; case 'B': //If user enters B int hours2; price_b = 14.95; //Package B cout << "How many hours did you use? "; //Ask user for hours cin >> hours2; cout << endl; if (hours2 > 20) //If the hours entered are greater than 20 { float output; output = price_b + (hours2 - 20) * 1.00; //Calculate cout << setprecision(2) << fixed; //Display results cout << choice << setw(10) << hours2 << setw(10) << "$" << output << endl; } else //If the hours entered are less than 20 cout << choice << setw(10) << hours2 << setw(10) << "$" << price_b << endl; break; case 'C': //If user enters C price_c = 19.99; //Package C cout << endl; //Display results cout << choice << setw(20) << "$" << price_c << endl; break; default: //If the user enters anything other than A, B or C cout << choice << setw(33) << "Invalid entry\n"; break; } cout << endl; return 0; } <file_sep>/csc402/project1/Maze.cpp /*There is a maze, use recursive method to get out **print the route each time ** */ #include <time.h> #include <stdlib.h> #include <unistd.h> #include<iostream> using namespace std; void print_array(char maze[12][12],int max_row,int max_col) { //delay(300); system("sleep 1"); system("clear"); //gotoxy(1,1); for(int i=0;i<max_row;i++) { for(int j=0;j<max_col;j++) cout<<maze[i][j]<<' '; cout<<endl; } } void mazeTraverse(char maze[12][12],int start_row,int start_col) { if(start_row>=0&&start_row<12&&start_col>=0&&start_col<12) { if(start_row==4&&start_col==11) cout<<"success"<<endl; if(maze[start_row][start_col]=='.') { maze[start_row][start_col]='x'; print_array(maze,12,12); mazeTraverse(maze,start_row-1,start_col); mazeTraverse(maze,start_row,start_col-1); mazeTraverse(maze,start_row+1,start_col); mazeTraverse(maze,start_row,start_col+1); maze[start_row][start_col]='*'; } } } main() { char array[][12]={{'#','#','#','#','#','#','#','#','#','#','#','#'}, { '#','.','.','.','#','.','.','.','.','.','.','#'}, { '.','.','#','.','#','.','#','#','#','#','.','#'}, { '#','#','#','.','#','.','.','.','.','#','.','#'}, {'#','.','.','.','.','#','#','#','.','#','.','.'}, { '#','#','#','#','.','#','.','#','.','#','.','#'}, {'#','.','.','#','.','#','.','#','.','#','.','#'}, { '#','#','.','#','.','#','.','#','.','#','.','#'}, { '#','.','.','.','.','.','.','.','.','#','.','#'}, {'#','#','#','#','#','#','.','#','#','#','.','#' }, { '#','.','.','.','.','.','.','#','#','#','.','#'}, {'#','#','#','#','#','#','#','#','#','#','#','#'}}; mazeTraverse(array,2,0); } <file_sep>/csc402/assignment6/treeNode.h /* Author: <NAME> File: treeNode.h Date: 10/18/2015 Class: CSC 402 About: Header file for treeNode. treeNodes are the components of the treeGraph/binary tree. A treeNode is comprised of data which is a template for any data type or data structure. A treeNode also has a pointer to its left and right child/leaf. */ #include <iostream> template <class T> struct treeNode { T data; treeNode<T> *left, *right; treeNode() {}; treeNode(const T& info) { data = info; } }; <file_sep>/csc520/finalproj/src/com/library/business_layer/field_list/CatalogedBook.java package com.library.business_layer.field_list; import java.io.Serializable; /** * A CatalogedBook is a representaion of basic book identifying information. * CatalogedBook contains the book ISBN, title, foreign keys to category, * details and publisher, and a unique identifier. Identifiers are meant to * act similar to a primary key in a database and as such should be unique. * Also implements Serializable so it can be serialized for later use. * BUSINESS LAYER CLASS * @see com.library.business_layer.field_list.CatalogedBookDetails * @see com.library.business_layer.field_list.Category * @see com.library.business_layer.field_list.Publisher */ public class CatalogedBook implements Serializable { private int id; private String isbn; private String name; private int categoryId; private int detailsId; private int publisherId; /** * Contstructs CatalogedBook Object by setting its attributes to a value. * @param i identifier * @param is isbn * @param n book name * @param c category id * @param d details id * @param p publisher id */ public CatalogedBook(int i, String is, String n, int c, int d, int p) { setId(i); setIsbn(is); setName(n); setCategoryId(c); setDetailsId(d); setPublisherId(p); } /** * Gets the int identifier value for this Object. * @return id as int */ public int getId() { return id; } /** * Gets the CatalogedBook isbn as a String. * @return isbn String */ public String getIsbn() { return isbn; } /** * Gets the CatalogedBook name as a String. * @return name String */ public String getName() { return name; } /** * Gets the identifier for this CatalogedBook's Category as an int. * @return category id int */ public int getCategoryId() { return categoryId; } /** * Gets the identifier for this CatalogedBook's details as an int. * @return details id int */ public int getDetailsId() { return detailsId; } /** * Gets the identifier for this CatalogedBook's publisher as an int. * @return publisher id int */ public int getPublisherId() { return publisherId; } /** * Sets the value for the Object identifier. * @param i int to set id to */ public void setId(int i) { id = i; } /** * Sets the value for the CatalogedBook's isbn. * @param is String to set isbn to */ public void setIsbn(String is) { isbn = is; } /** * Sets the value for the CatalogedBook's name. * @param n String to set name to */ public void setName(String n) { name = n; } /** * Sets the value for the Category id. * @param c int to set Category id to */ public void setCategoryId(int c) { categoryId = c; } /** * Sets the value for the details id. * @param d int to set details id to */ public void setDetailsId(int d) { detailsId = d; } /** * Sets the value for the publisher id. * @param p int to set publisher id to */ public void setPublisherId(int p) { publisherId = p; } }<file_sep>/csc421/assignment5/src/com/yahtzee/server/GreetingServiceImpl.java package com.yahtzee.server; import com.yahtzee.client.playerStats; import com.yahtzee.client.GreetingService; import com.yahtzee.shared.FieldVerifier; import com.google.gwt.user.server.rpc.RemoteServiceServlet; /* * Author: <NAME> * File Name: GreetingServiceImpl.java * File Package: com.yahtzee.server * File Version: 1.0 * File Date: 12/04/2017 * Due Date: 12/13/2017 * Assignment: #5 * Professor: Dr. <NAME> * Course #: CSC421 * Course Name: Web-Based Software Design & Development * University: Kutztown University * Major: CSCM Software Development */ /** * The server-side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService { private static final long serialVersionUID = 1L; //For serialization private static playerStats stats = new playerStats(); //Last player to update stats private static boolean hasPlayerOne = false; //Game has a player one private static boolean hasPlayerTwo = false; //Game has a player two private static int playerTurn = 1; //Which player turn is it? /** * Checks to see if it is the calling player's turn. * @param player the player who is calling * @return true if it is the player's turn, false if not */ public Boolean getUpdate(int player) { if(player != playerTurn) { return false; } else { return true; } } /** * Retrieves the stats of the other player for the calling player. * @return the stats of the other player */ public playerStats confirmUpdate() { return stats; } /** * Sets the server copy of player stats to the calling player's stats. * @param gLog the calling player's stats */ public void setStats(playerStats gLog) { //Switch to the other player's turn while you are at it if(playerTurn == 1) { playerTurn = 2; } else if(playerTurn == 2) { playerTurn = 1; } stats = gLog; } /** * Start the game by only allowing two players at a time. Inform all players * who enter while there are already two players playing that they game * already has players. * @return 1 for player#1, 2 for player#2, 0 for game full */ public Integer start() { stats = new playerStats(); //Reset game stats Integer result = 0; //The ID of the incoming player //If the game does not have a player one, assign as player one if (!hasPlayerOne) { hasPlayerOne = true; result = 1; } //If the game has a player one but no player two, assign as player two else if(!hasPlayerTwo) { hasPlayerTwo = true; result = 2; } //Else the game is full, return zero return result; } /** * Restart the game and reinitialize variables. Allow other users to play. */ public void quit() { hasPlayerOne = false; hasPlayerTwo = false; playerTurn = 1; } } <file_sep>/csc330/README.txt CSC 330 - Introduction to Mobile Architecture and Systems Dr. <NAME> Kutztown University Spring 2016 This course introduces students to the concepts of technology mobility and the role that new and smaller computing devices play in new systems development. The student will be introduced to the field of mobile systems architecture and apply this knowledge to the creation of architectures using both mobile and traditional computing resources. Following this the student will learn about development using today's popular mobile devices and develop their own architecture and system based on mobile devices. <file_sep>/csc242/README.txt CSC 242 - Web Programming Dr. <NAME> Kutztown University Fall 2013 This course is an introduction to the basic concepts of client/server scripting on the Web. Topics will include: Web architecture, standards, and infrastructure, client/server architecture on the Web, markup languages and style sheets, client-side data validation and form processing, client-side cookie usage, server-side data processing, information storage, and backend databases, and issues involved with Web interface development. <file_sep>/csc421/assignment1/Yahtzee.java /* JavaDoc Link: http://csitrd.kutztown.edu/~ccarr419/csc421/assignment1/ */ import java.util.*; import java.io.*; /** <h1>CSC421 Web-Based Design: Assignment #1</h1> <table> <caption></caption> <tr> <th>Author:</th> <td><NAME></td> </tr> <tr> <th>Major:</th> <td>CSC Masters Software Development</td> </tr> <tr> <th>Creation Date:</th> <td>09/12/2017</td> </tr> <tr> <th>Due Date:</th> <td>09/22/2017</td> </tr> <tr> <th>School:</th> <td>Kutztown University of Pennsylvania</td> </tr> <tr> <th>Course:</th> <td>CSC 421 Web-Based Programming</td> </tr> <tr> <th>Professor Name:</th> <td>Dr. <NAME></td> </tr> <tr> <th>Assignment:</th> <td>#1</td> </tr> <tr> <th>Filename:</th> <td>a1.java</td> </tr> <tr> <th style="vertical-align:top">Purpose:</th> <td>To partially implement a text-based version of the game of Yahtzee. This project<br> will implement a one player version of the game that plays a single round of Yahtzee. </td> </tr> </table> <h1>Help</h1> <p>Commands and project design decisions can be found in the <a href="http://csitrd.kutztown.edu/~ccarr419/csc421/assignment1/README.txt" target="_blank">readme</a>.<br> Categories for Yahtzee can be found <a href="http://csitrd.kutztown.edu/~ccarr419/csc421/assignment1/CATEGORIES.txt" target="_blank">here</a>.<br> Official rules to Yahtzee can be found <a href="https://www.hasbro.com/common/instruct/Yahtzee.pdf" target="_blank"> here</a>.</p> */ public class Yahtzee { /** Number of dice allowed in the game */ public static final int NUMDICE = 5; /** Number of rolls allowed per round */ public static final int NUMROLLS = 3; /** User command to display the help page */ public static final String COMMAND_HELP = "help"; /** User command to start or restart the game */ public static final String COMMAND_START = "start"; /** User command to display current game statistics */ public static final String COMMAND_STATUS = "stats"; /** User command to display global game statistics */ public static final String COMMAND_GLOBST = "gstat"; /** User command to print the current roll */ public static final String COMMAND_PRINTD = "pdice"; /** User command to roll the dice */ public static final String COMMAND_ROLL = "roll"; /** User command select dice to keep from the current roll */ public static final String COMMAND_KEEP = "keep"; /** User command to display all categories in the game */ public static final String COMMAND_CATEGOR = "cat"; /** User command to display all available categories with the current roll */ public static final String COMMAND_AVAILCT = "acat"; /** User command to pick a category currently avaiable to them */ public static final String COMMAND_PICKCAT = "pcat"; /** User command to quit the game */ public static final String COMMAND_QUIT = "quit"; /** File that contains list of commands and design choices * @see <a href= "http://csitrd.kutztown.edu/~ccarr419/csc421/assignment1/README.txt" target="_blank">README.txt</a> */ public static final File helpFile = new File("README.txt"); /** File that contains list all available categories to choose from * @see <a href= "http://csitrd.kutztown.edu/~ccarr419/csc421/assignment1/CATEGORIES.txt" target="_blank">CATEGORIES.txt</a> */ public static final File catFile = new File("CATEGORIES.txt"); /** Data file that stores game information for reading and writing */ public static final File logFile = new File("log.dat"); /** Reads user input from {@code System.in} */ public static Scanner scan = new Scanner(System.in); /** * Main method to the Yahtzee program. Starts the game normally or from the * command-line. * @param args String array of command-line arguments */ public static void main(String[] args) { //Make an array to hold command-line input if present int[] clDice = new int[NUMDICE]; //Check to see if command-line arguments match the required format if((checkClArgs(args, clDice)) == true) { beginGame(clDice); //start game with command-line dice playerPrompt(clDice, true, 1); } //There is no command-line input or incorrect command-line format else { printIntroTag(); //Show welcome tag for basic game information playerPrompt(null, false, 0); } } /** * Checks command-line input for correct format. Correct format dictates * that there must be {@value #NUMDICE} integers separated by a space. * Integers must be in the range of one to six. * @param args The list of command-line arguments if present * @param clDice Int array to return the command-line dice if applicable * @return True if correct command-line format. False if not. * @exception NumberFormatException Non-numeric data */ public static boolean checkClArgs(String[] args, int clDice[]) { //Check if there is no command-line arguments if(args.length == 0) { return false; } //If there is command-line arguments, make sure there are exactly NUMDICE else if(args.length == NUMDICE) { for(int i = 0; i < NUMDICE; i++) { try { //Try to turn command-line arugments into integers clDice[i] = Integer.parseInt(args[i]); //Make sure entered integers are dice face values (1-6) if(clDice[i] < 1 || clDice[i] > 6) { System.out.println("Error: bad command-line arguments."); System.out.println("Initializing normal game start sequence."); return false; } } //The user entered something other than integers catch(NumberFormatException e) { System.out.println("Error: bad command-line arguments."); System.out.println("Initializing normal game start sequence."); return false; } } return true; //Correct command-line input } else { //Too many or too few command-line arguments System.out.println("Error: invalid number of command-line arguments."); System.out.println("Initializing normal game start sequence."); return false; } } /** * Handles all user input commands and links them to their corresponding * fucntions. Prompt will continue until program termination (quit). * @param clDice Command-line entered dice if applicable * @param start Used to signify whether to start the game initially * @param rnd Used to set the initial roll number */ public static void playerPrompt(int[] clDice, boolean start, int rnd) { boolean gameInPrg = start, plKept = false; int rollNum = rnd; int[] dice = clDice; List<int[]> prevRolls = new ArrayList<int[]>(); boolean[] keptDice = new boolean[NUMDICE]; //Check if command-line dice were entered, if so add to previous rolls if(dice != null) { addRoll(dice, prevRolls); } //Loop until user quits while(true) { //Check if the game has reached the end of the round //Set gameInPrg to false if the end of round, true otherwise gameInPrg = chkEndRnd(dice, prevRolls, keptDice, gameInPrg, rollNum); //Set current roll to zero if the game is not in progress rollNum = (gameInPrg) ? rollNum : 0; System.out.print("> "); String command = scan.next(); //Handle user input and link commands to functions switch(command.toLowerCase()) { case COMMAND_HELP: //show help page printList(parseFile(helpFile)); break; case COMMAND_START: //start/restart game dice = beginGame(null); gameInPrg = init(dice, prevRolls, keptDice); rollNum = 1; break; case COMMAND_STATUS: //show current game stats if game in progress if(!prgErr(gameInPrg, "Cannot show game status.")) { } else { playerStats(prevRolls, dice, keptDice, rollNum); } break; case COMMAND_GLOBST: //show game global stats printGlobStats(); break; case COMMAND_PRINTD: //print current dice if game in progress if(!prgErr(gameInPrg, "Cannot print dice.")) { } else { System.out.print(translateToImage(dice)); System.out.println("Current roll: " + printDice(dice)); } break; case COMMAND_ROLL: //roll dice if game in progress if(!prgErr(gameInPrg, "Cannot roll dice.")) { } else { if(playerRoll(dice, keptDice, plKept)) { plKept = nextRoll(dice, prevRolls, keptDice, ++rollNum); } } break; case COMMAND_KEEP: //keep user-specified dice if game in progress if(!prgErr(gameInPrg, "Cannot pick dice to keep.")) { } else { keptDice = keepDice(dice); plKept = true; } break; case COMMAND_CATEGOR: //show all categories in the game printList(parseFile(catFile)); break; case COMMAND_AVAILCT: //show all available categories during a game if(!prgErr(gameInPrg, "Cannot show available categories.")) { } else { printNumberedList(availCategor(dice)); } break; case COMMAND_PICKCAT: //pick an avaiable category during a game if(!prgErr(gameInPrg, "Cannot pick category.")) { } else { if(pickCategory(dice, rollNum)) { gameInPrg = false; } } break; case COMMAND_QUIT: //quit the game and terminate the program System.out.println("Goodbye."); System.exit(0); break; default: //state the the entered String is not a command System.out.println("Error: '" + command + "' is not an internal command."); } } } /** * Sets all necessary data objects to their initial empty state and adds the * current dice roll to the list of previous rolls. * @param dice Integer array that holds the current roll * @param rolls A list of int arrays containing all previous rolls * @param kept Boolean array that that tells which dice are kept * @return Always true to signify start of game */ public static boolean init(int dice[], List<int[]> rolls, boolean kept[]) { for(int i = 0; i < NUMDICE; i++) { kept[i] = false; } rolls.clear(); addRoll(dice, rolls); return true; } /** * Checks if the game has reached the end of the round i.e. the number of * rolls equals {@value #NUMROLLS} or the user picked a category. * @param dice Integer array that holds the current roll * @param rolls A list of int arrays containing all previous rolls * @param kept Boolean array that that tells which dice are kept * @param gPrg Boolean which states whether the game is currently in progress * @param rollNum How many rolls the user has currently rolled * @return True if the game has reached the end of the round. False if not. */ public static boolean chkEndRnd(int dice[], List<int[]> rolls, boolean kept[], boolean gPrg, int rollNum) { if(rollNum >= NUMROLLS || !gPrg) { //Player ran out of rolls if(gPrg) { pickCategory(dice, rollNum); } //Player ran out of rolls or picked a category early if(rollNum > 0) { System.out.println("\nROUND OVER"); playerStats(rolls, dice, kept, rollNum); } System.out.println("\nType 'start' to play.\n"); return false; //Game not in progress } return true; //Game still in progress } /** * Begins the game by printing the global stats compiled from the games * before, rolling the dice and printing said dice to the screen. Checks if * dice is set before rolling the dice. * @param d Int array that will hold the first roll of the dice * @return The freshly rolled dice if d was not set. Returns d if d is set. */ public static int[] beginGame(int d[]) { System.out.println("\nLet's Play!"); printGlobStats(); int[] dice = new int[NUMDICE]; if(d != null) { dice = d; } //Check if d is already set else { dice = rollDice(); } //Otherwise roll the dice System.out.println("\nRoll #1"); System.out.print(translateToImage(dice)); System.out.println("Current roll: " + printDice(dice)); return dice; } /** * If the game is not in progress this will print an error message to screen. * @param gPrg Boolean that tells if the game is in progress or not * @param str String to add to the "Game not in progress." error message * @return gPrg: in order be able to place this function in an if statement */ public static boolean prgErr(boolean gPrg, String str) { if(!gPrg) { System.out.println("Game not in progress. " + str); } return gPrg; } /** * Shows the current statistics of the user's current round. Will show the * number of rolls rolled, current dice rolled, current kept dice if * applicable and all previous rolls including the current roll. * @param rolls A list of int arrays containing all previous rolls * @param dice Integer array that holds the current roll * @param kept Boolean array that that tells which dice are kept * @param round the number of rolls rolled by the user */ public static void playerStats(List<int[]> rolls, int dice[], boolean kept[], int round) { System.out.println("\nNumber of Rolls: " + round); System.out.println("Current Dice: " + printDice(dice)); System.out.print("Current Kept Dice: "); printKeptDice(dice, kept); System.out.println("\nPrevious Rolls:"); for(int i = 0; i < rolls.size(); i++) { System.out.println((i+1) + ".) " + printDice(rolls.get(i))); } } /** * Logs the results of each round of the game to the log file. * Information logged to the file include six integers: five corresponding * to the current dice at round end and the last to represent how many rolls * were rolled. The last bit of information is a String which stores what * category the user picked at round end. * @param dice Integer array that holds the current roll * @param category The category picked by the user * @param roll Number of rolls rolled by the user */ public static void logStats(int dice[], String category, int roll) { try { DataOutputStream out = new DataOutputStream( new FileOutputStream(logFile, true)); //Write the dice integers to file separated by space for(int i = 0; i < NUMDICE; i++) { out.writeInt(dice[i]); out.write(" ".getBytes()); } //Write number of rolls and category picked out.writeInt(roll); out.write(" ".getBytes()); out.write(category.getBytes()); out.write("\n".getBytes()); out.close(); //Be a good samaritan and close the file } //Catch for write errors catch(IOException e) { e.printStackTrace(); } } /** * Prints information from the log file to the screen. Information * printed includes number of rounds played by any user and the average * amount of rolls per round. Checks to see if the log file exists * first. If the file does not exist tell the user they are first to play. */ public static void printGlobStats() { //Check if file exists before reading from it if(logFile.exists()) { System.out.println(""); System.out.println("A total of " + findGlobRounds() + " rounds have been played."); System.out.println("Each round averaged " + findGlobAvg() + " rolls long."); } //If the file does not exist then this user is the first to play else { System.out.println("You are the first to play!"); } } /** * Finds the average number of rolls per round for each round logged into * the data log file. Assumes the log file exists. * @return The average rolls for each round played and logged */ public static float findGlobAvg() { byte[] bArr = getFileBytes(logFile); //File returns bytes int count = 0; float sum = 0, num = 0; //Find all numbers between one an six. That will help locate the number //of rounds in the file because it will always be the sixth integer in //each series of six numbers between one and six. for(int i = 0; i < bArr.length; i++) { if(bArr[i] > 0 && bArr[i] <= 6) { //Important numbers are only 1-6 if(++count == 6) { //Rolls will always be the sixth number count = 0; sum += bArr[i]; num++; } } } return(sum / num); //return the average } /** * Finds the total number of rounds played by any user logged into the * data log file. Assumes the log file exists. * @return The total number of rounds played by any user */ public static int findGlobRounds() { byte[] bArr = getFileBytes(logFile); //File returns bytes String str = new String(bArr); int count = 0; //Look for the new line character, this will equal the number of rounds for(int i = 0; i < str.length(); i++) { if(str.charAt(i) == '\n') { count++; } } return count; } /** * Get all the bytes contained within a file. If the file does not exist, * print the stack trace and terminate the program. * @param file The file to open and get the bytes from * @return The byte array which contains all the bytes from the file */ public static byte[] getFileBytes(File file) { try { //The method read only returns bytes FileInputStream input = new FileInputStream(file); byte[] bArr = new byte[(int)file.length()]; input.read(bArr); input.close(); //Be a good samaritan and close the file return bArr; } //File does not exist or some other related error catch(IOException e) { e.printStackTrace(); } return null; } /** * Compiles a list of categories available to user at the moment of this * method call. Calls helper functions to separate the lower/upper sections. * @param dice Integer array that holds the current roll * @return List of Strings which holds all available categories * @see #catUpperSectHelper * @see #catLowerSectHelper */ public static List<String> availCategor(int dice[]) { List<String> catList = new ArrayList<String>(); catUpperSectHelper(dice, catList); //Check upper section categories catLowerSectHelper(dice, catList); //Check lower section categories catList.add("Chance"); //This catgegory will always show return catList; } /** * Adds to the list of categories by checking if the current dice fufill * the prerequisites of each upper section categories. The upper section * represents categories that only require a minimum of one dice of the * matching number in order to be fulfilled. Helps {@link availCategor}. * @param dice Integer array that holds the current roll * @param catList List of Strings to add categories to */ public static void catUpperSectHelper(int dice[], List<String> catList) { //Add category to list if one dice matches the category and the //category is not in the list already for(int i = 0; i < NUMDICE; i++) { if(dice[i] == 1) { addUnique(catList, "Aces"); } else if(dice[i] == 2) { addUnique(catList, "Twos"); } else if(dice[i] == 3) { addUnique(catList, "Threes"); } else if(dice[i] == 4) { addUnique(catList, "Fours"); } else if(dice[i] == 5) { addUnique(catList, "Fives"); } else { addUnique(catList, "Sixes"); } } } /** * Adds to the list of categories by checking if the current dice fufill * the prerequisites of each lower section categories. The lower section * represents categories that are special configurations of the dice * including three dice the same, four dice the same, all five dice the same, * three dice the same of one number and two the same of another, four * sequential dice and five sequential dice. Helps {@link availCategor}. * @param dice Integer array that holds the current roll * @param catList List of Strings to add categories to */ public static void catLowerSectHelper(int dice[], List<String> catList) { int counter = 0; List<Integer> diceCount = new ArrayList<Integer>(); //Compile a list of integers which signify each dice and their //number of occurances in the roll for(int i = 1; i <= 6; i++) { diceCount.add(countDice(dice, i)); } //Check for multiples of the same dice for "of a kind" categories for(int i = 0; i < diceCount.size(); i++) { if(diceCount.get(i) >= 3) { catList.add("Three of a Kind"); } if(diceCount.get(i) >= 4) { catList.add("Four of a Kind"); } if(diceCount.get(i) == 5) { catList.add("Yahtzee"); } } //Check for two of one dice the same and three of another the same if(diceCount.contains(2) && diceCount.contains(3)) { catList.add("Full House"); } //Count the number of sequential dice by checking how many ones //or twos are next to each other for(Iterator<Integer> i = diceCount.iterator(); i.hasNext();) { int num = i.next(); //Make sure there is only between 1 and 2 dice of that number if(num > 0 && num < 3) { counter++; } //If the counter is less than 2, there's still a chance else if(counter < 2) { counter = 0; } //Else leave as there's no chance for a sequential category //Or have have already met the requirements for one else { break; } } //Sequential dice categories if(counter >= 4) { catList.add("Small Straight"); } if(counter == 5) { catList.add("Large Straight"); } } /** * Allows the user to pick a category from the currently available categories. * Choosing a category will end the round and log the results of the round * to the data file. Player may exit from making a choice by entering zero. * @param dice Integer array that holds the current roll * @param roll Number of rolls rolled by the user * @return True if a category was picked. False if one was not picked. * @exception NumberFormatException User entered non-numeric input */ public static boolean pickCategory(int dice[], int roll) { List<String> categories = availCategor(dice); System.out.println("Select a category by entering the number before " + "it.\nOR enter zero to exit if it is not the last roll."); //Print a numbered list of available categories printNumberedList(categories); do { System.out.print("Enter a number between 1 and " + categories.size() + ": "); String command = scan.next(); try { int choice = Integer.parseInt(command); //Check if the number entered was in range of options if(choice >= 1 && choice <= categories.size()) { System.out.println("You picked: " + categories.get(choice-1)); logStats(dice, categories.get(choice-1), roll); return true; } //Zero represents the exit command, exit back to game if entered else if(choice == 0) { //Make sure it is not the last round, the user must pick a //category if that is the case if(roll >= NUMROLLS) { System.out.println("Cannot exit on last roll."); } else { System.out.println("No category picked. Returning."); return false; } } //Return the prompt to choose a category for out of range numbers else { continue; } } //Return the prompt to choose a category for non-numeric input catch(NumberFormatException e) { continue; } } while(true); //Keep looping until a choice is made } /** * Counts the number of dice that appear in the current roll that match * the given parameter number. * @param dice Integer array that holds the current roll * @param num The number to look for in the current roll * @return The number of dice that exist in the roll with that number */ public static int countDice(int dice[], int num) { int counter = 0; for(int i = 0; i < NUMDICE; i++) { if(dice[i] == num) { counter++; } } return counter; } /** * Checks to see if there is an entry that matches the given String within * the list already. If no such entry exists, add the String to the list. * @param list List to add to and search for duplicate * @param str String to seach for within the list and add if it is unique */ public static void addUnique(List<String> list, String str) { if(list.contains(str)) { return; } else { list.add(str); } } /** * Parses a file and splits it into token Strings by line. The strings are * added to a list of Strings and returned once the whole file is parsed. * @param file The file to parse * @return The list that contains the String tokens */ public static List<String> parseFile(File file) { BufferedReader reader = null; List<String> list = new ArrayList<String>(); //List to split tokens into String text = null; //Temporary String token holder try { //Read the file line by line. Once a line is read, add a new line reader = new BufferedReader(new FileReader(file)); while((text = reader.readLine()) != null) { //While not EoF list.add(text); list.add("\n"); } reader.close(); //Be a good samaritan and close the file } //Catch for read/write errors and if the file does not exist catch(FileNotFoundException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } finally { try { //If file was still left open for any reason close it if(reader != null) { reader.close(); return list; } } catch(IOException e) { } } return null; } /** * Prints a given list of Strings. Used for printing parsed files. * @param list List to print to screen (most likely parsed file) */ public static void printList(List<String> list) { System.out.println(""); for(Iterator<String> i = list.iterator(); i.hasNext();) { String word = i.next(); System.out.print(word); } } /** * Prints a list of strings but numbers them according to their order in the * list. Each entry is separated by a new-line. * @param list List used to print a numbered list */ public static void printNumberedList(List<String> list) { int counter = 1; System.out.println(""); for(Iterator<String> i = list.iterator(); i.hasNext();) { String category = i.next(); System.out.println((counter++) + ".) " + category); } } /** * Method to print a intro tag to welcome the user to the game and inform * them of basic game information or anything else helpful. */ public static void printIntroTag() { System.out.print("\n" + "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" + "* Welcome to Yahtzee!\n*\n" + "* Type 'help' for a list of game commands\n*\n" + "* Programmed by <NAME>\n" + "* Yahtzee © 2017 Hasbro, Inc.\n" + "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n"); } /** * Prints the roll to the screen and adds the roll to the previous rolls list. * @param dice Integer array that holds the current roll * @param rolls List of previous rolls rolled by the user this round * @param kept Boolean list representing what dice the user is keeping * @param rnd The current roll the user is on this round * @return Always false, signifies the user has not updated their kept dice */ public static boolean nextRoll(int dice[], List<int[]> rolls, boolean kept[], int rnd) { System.out.println("\nRoll #" + rnd); System.out.print(translateToImage(dice)); //Print dice image System.out.println("Current roll: " + printDice(dice)); addRoll(dice, rolls); //Add roll to list of previous rolls return false; } /** * Method to roll the dice. First checks if the user has recently picked * dice to keep from the previous rolls. If the user has not kept any dice * a warning will be printed and the user will be asked to continue with the * roll. If the user already picked dice to keep, the roll will continue * without any warning. * @param dice Integer array that holds the current roll * @param kept Boolean list representing what dice the user is keeping * @param pk Boolean to signify whether the user picked dice to keep or not * @return True if the user successfully rolled. False if not. */ public static boolean playerRoll(int dice[], boolean kept[], boolean pk) { if(pk == false) { System.out.println(""); //Ask the user if they wish to continue with the roll if they //did not keep dice from their previous roll if(yesNoPrompt("Are you sure you want to roll " + "w/o keeping dice? [y/n]: ")) { swapDice(dice, kept); //Only roll the not kept dice if any return true; } else { //User decided to go back and pick dice to keep System.out.println("Aborting roll request."); return false; } } //Player already kept so go through with the roll else { swapDice(dice, kept); //Only roll the not kept dice if any return true; } } /** * Rolls the dice and places the dice in a temporary holder. Then the actual * dice object swaps out dice values that were not kept by the user. * @param dice Integer array that holds the current roll * @param kept Boolean list representing what dice the user is keeping */ public static void swapDice(int dice[], boolean kept[]) { int[] temp = rollDice(); //Only swap values that are not kept (false in the kept array) for(int i = 0; i < NUMDICE; i++) { if(!kept[i]) { dice[i] = temp[i]; } } } /** * Adds a new roll to the list of previous rolls. This method is necessary * because lists in java need to add new values. Adding old values already * in the list modifies each one of the values to the newly added value. * @param dice Integer array that holds the current roll * @param rolls List of previous rolls rolled by the user this round */ public static void addRoll(int dice[], List<int[]> rolls) { int[] d = new int[NUMDICE]; d = dice.clone(); rolls.add(d); } /** * Makes a roll of pseudo-random dice and returns that dice array * @return The newly created (rolled) dice array */ public static int[] rollDice() { int[] dice = new int[NUMDICE]; //Generate pseudo-random number for each dice for(int i = 0; i < NUMDICE; i++) { Random ran = new Random(); //Random number generator int num = ran.nextInt(6) + 1; //Generate random number between 1 and 6 dice[i] = num; } return dice; } /** * Method that allows the user decide what dice they would like to keep. The * user will be asked for each dice if they want to keep it or not. After * successfully deciding what dice to keep, the kept dice will be printed. * @param dice Integer array that holds the current roll * @return Boolean array containing which dice are kept and which are not */ public static boolean[] keepDice(int dice[]) { boolean[] keptDice = new boolean[NUMDICE]; //Individually prompt the user to choose if they wish to keep the dice for(int i = 0; i < NUMDICE; i++) { if(yesNoPrompt("Do you want to keep dice #" + (i + 1) + " (" + dice[i] + ")? [y/n]: ")) { keptDice[i] = true; //User decided to keep the dice } else { keptDice[i] = false; } //User decided not to keep } //Print the dice the user decided to keep System.out.print("You kept: "); printKeptDice(dice, keptDice); return keptDice; } /** * Prompts the user with a yes or no question. Changes the input to lower * case for maximum compatibility. * @param str String for the prompt to print (Should be a yes/no question) * @return true if the user entered y (yes). False if the user entered n (no). */ public static boolean yesNoPrompt(String str) { String choice = ""; do { //keep looping until 'y' or 'n' is entered System.out.print(str); choice = scan.next(); } while(!choice.toLowerCase().equals("y") && !choice.toLowerCase().equals("n")); //If 'y' is entered return true, if 'n' is entered return false if(choice.toLowerCase().equals("y")) { return true; } else { return false; } } /** * Prints the dice the user has decided to keep to the screen. * @param dice Integer array that holds the current roll * @param keptDice Boolean list representing what dice the user is keeping */ public static void printKeptDice(int dice[], boolean keptDice[]) { for(int i = 0; i < NUMDICE; i++) { if(keptDice[i] == true) { System.out.print(dice[i] + " "); } } System.out.print("\n"); } /** * Print each dice number separated by a space. * @param dice Integer array that holds the current roll * @return The String that contains the five dice ints separated by a space */ public static String printDice(int dice[]) { String diceStr = ""; for(int i = 0; i < NUMDICE; i++) { diceStr += dice[i]; diceStr += " "; } return diceStr; } /** * Creates a visible image to the likeness of a dice face. Each dice face * will correspond to each number in the roll. Calls a helper function to * figure what section of the dice face to print according to what level * of the print the method is on. Dice faces are printed horizontally. * @param dice Integer array that holds the current roll * @return The string containing the dice face images * @see #imagerHelper */ public static String translateToImage(int dice[]) { //Strings that are used for all combinations of dice faces String dTop = " _________ "; //Dice face top String none = "| |"; //Dice face none String lOne = "| • |"; //Dice face one dot left String cOne = "| • |"; //Dice face one dot center String rOne = "| • |"; //Dice face one dot right String both = "| • • |"; //Dice face two dots (both) String dBot = "|_________|"; //Dice face bottom String out = ""; //Put Strings that change depending on the dice number inside a map //The helper function will help pick the right choice from the map Map<Integer, String> map = new HashMap<Integer, String>(); map.put(0, none); map.put(1, lOne); map.put(2, cOne); map.put(3, rOne); map.put(4, both); //Automatically add the top portion as it is the same for every number for(int i = 0; i < NUMDICE-1; i++) { out += dTop + " "; } out += dTop + "\n"; //Separate the last one because it needs a new line //Automatically add the second top portion as it is the same too for(int i = 0; i < NUMDICE-1; i++) { out += none + " "; } out += none + "\n"; //Separate the last one because it needs a new line //The next three portions change depending on which dice number it is //Call the helper function to get the key of what String to print //located within the map for(int i = 0; i < 3; i++) { //Three sections of dots //Holds the value of the next for loop since it falls out of scope int temp = 0; //Get the correct String to print according to its dice number //and its section number for(int j = 0; j < NUMDICE-1; j++) { out += map.get(imagerHelper(dice[j], i)) + " "; temp = j; //Give temp the value since j will fall out of scope } //Separate the last one because it needs a new line out += map.get(imagerHelper(dice[temp+1], i)) + "\n"; } //Automatically add the last portion as it is the same for every number for(int i = 0; i < NUMDICE-1; i++) { out += dBot + " "; } out += dBot + "\n\n"; return out; } /** * Helps the {@link translateToImage} method by returning a key to get the * correct portion of the dice face to print according to the number given * and the section number. * @param num The dice number * @param pos The section position number * @return The key which is used to access the correct String in a String map */ public static int imagerHelper(int num, int pos) { //Int keys representing what String to print int none = 0, lOne = 1, cOne = 2, rOne = 3, both = 4; switch(pos) { case 0: //Section zero //1 returns none, 2 & 3 returns rOne, everything else returns both if(num == 2 || num == 3) { return rOne; } else if(num > 3) { return both; } else { return none; } case 1: //Section one //1, 3 & 5 return cOne, 6 returns both, the rest return none if(num == 1 || num == 3 || num == 5) { return cOne; } else if(num == 6) { return both; } else { return none; } case 2: //Section two //1 returns none, 2 & 3 returns lOne, everything else returns both if(num == 2 || num == 3) { return lOne; } else if(num > 3) { return both; } else { return none; } default: return -1; //Error on section input } } } <file_sep>/csc402/inclassprograms/clockType.cpp #include <iostream> using namespace std; class clockType { public: clockType(int h = 12, int m = 0, int sec = 0); clockType(const clockType &); void setTime(int, int, int); void setHours(int); void setMinutes(int); void setSeconds(int); int getHours() const; int getMinutes() const; int getSeconds() const; void incrementHours(); void incrementMinutes(); void incrementSeconds(); void decrementHours(); void decrementMinutes(); void decrementSeconds(); void printTime(); private: int hr; int min; int sec; }; clockType::clockType(int h, int m, int s) { setTime(h, m, s); } clockType::clockType(const clockType &clock) { setTime(clock.getHours(), clock.getMinutes(), clock.getSeconds()); } void clockType::setTime(int hr, int min, int sec) { setHours(hr); setMinutes(min); setSeconds(sec); } void clockType::setHours(int hour) { if(hour > 0 && hour <= 12) hr = hour; else hr = 12; } void clockType::setMinutes(int minute) { if(minute >= 0 && minute < 60) min = minute; else min = 0; } void clockType::setSeconds(int second) { if(second >= 0 && second < 60) sec = second; else sec = 0; } int clockType::getHours() const { return hr; } int clockType::getMinutes() const { return min; } int clockType::getSeconds() const { return sec; } void clockType::incrementHours() { setHours(getHours()+1); } void clockType::incrementMinutes() { setMinutes(getMinutes()+1); } void clockType::incrementSeconds() { setSeconds(getSeconds()+1); } void clockType::decrementHours() { setHours(getHours()-1); } void clockType::decrementMinutes() { setMinutes(getMinutes()-1); } void clockType::decrementSeconds() { setSeconds(getSeconds()-1); } void clockType::printTime() { cout << getHours() << ":" << getMinutes() << ":" << getSeconds() << endl; } int main() { clockType clock1(1, 30, 24); cout << "Clock1 is "; clock1.printTime(); cout << "Clock2 is copied from Clock1 "; clockType clock2(clock1); clock1.printTime(); clock2.setTime(10, 55, 8); cout << "Clock2 is changed to "; clock2.printTime(); return 0; } <file_sep>/csc570/DataMineTensorFlow/CSC458DataMineI/water_estimator.py from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import tensorflow as tf import water_data parser = argparse.ArgumentParser() parser.add_argument('--batch_size', default=100, type=int, help='batch size') parser.add_argument('--train_steps', default=1000, type=int, help='number of training steps') def main(argv): args = parser.parse_args(argv[1:]) # Fetch the data (train_x, train_y), (test_x, test_y) = water_data.load_data() # Feature columns describe how to use the input. feature_columns = [] for key in train_x.keys(): feature_columns.append(tf.feature_column.numeric_column(key=key)) # Build 2 hidden layer DNN with 10, 10 units respectively. classifier = tf.estimator.DNNClassifier( feature_columns = feature_columns, # Two hidden layers of 10 nodes each. hidden_units = [10,10], # The model must choose between 10 classes. n_classes = water_data.CLASSIFICATIONS) # Train the Model. classifier.train( input_fn = lambda: water_data.train_input_fn(train_x, train_y, args.batch_size), steps = args.train_steps) # Evaluate the model. eval_result = classifier.evaluate( input_fn = lambda: water_data.eval_input_fn(test_x, test_y, args.batch_size)) print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result)) if __name__ == '__main__': tf.logging.set_verbosity(tf.logging.INFO) tf.app.run(main) <file_sep>/csc402/assignment3/chain.cpp /* Author: <NAME> File: chain.cpp About: Defines the member functions of the chain class. */ #include <iostream> #include <assert.h> #include "chain.h" using namespace std; template<class T> chain<T>::chain() { firstNode = NULL; listSize = 0; } template<class T> chain<T>::chain(const chain<T>& theChain) { if(theChain.empty()) { listSize = theChain.listSize; firstNode = theChain.firstNode; } else { chainNode<T> *p = firstNode; for(chainNode<T> *currentNode = theChain.firstNode; currentNode != NULL; currentNode = currentNode->next) { p = currentNode; p = p->next; listSize++; } } } template<class T> chain<T>::~chain() { while(firstNode != NULL) { chainNode<T> *nextNode = firstNode->next; delete firstNode; firstNode = nextNode; } } template<class T> T& chain<T>::get(int theIndex) const { checkIndex(theIndex); chainNode<T> *currentNode = firstNode; for(int i = 0; i < theIndex; i++) currentNode = currentNode->next; return currentNode->element; } template<class T> int chain<T>::indexOf(const T& theElement) const { chainNode<T> *currentNode = firstNode; int index = 0; while(currentNode != NULL && currentNode->element != theElement) { currentNode = currentNode->next; index++; } if(currentNode == NULL) return -1; else return index; } template<class T> void chain<T>::erase(int theIndex) { checkIndex(theIndex); chainNode<T> *deleteNode; if(theIndex == 0) { deleteNode = firstNode; firstNode = firstNode->next; } else { chainNode<T> *p = firstNode; for(int i = 0; i < theIndex - 1; i++) p = p->next; deleteNode = p->next; p->next = deleteNode->next; } delete deleteNode; listSize--; } template<class T> void chain<T>::insert(int theIndex, const T& theElement) { checkIndex(theIndex); if(theIndex == 0) firstNode = new chainNode<T>(theElement, firstNode); else { chainNode<T> *p = firstNode; for(int i = 0; i < theIndex - 1; i++) p = p->next; p->next = new chainNode<T>(theElement, p->next); } listSize++; } template<class T> void chain<T>::output(ostream& out) const { for(chainNode<T> *currentNode = firstNode; currentNode != NULL; currentNode = currentNode->next) out << currentNode->element << " "; } template<class T> void chain<T>::checkIndex(int theIndex) const { chainNode<T> *p = firstNode; for(int i = 0; i < theIndex; i++) { assert(p != NULL); p = p->next; } } //Explicit initializers so template class knows what types it can use template class chain<int>; template class chain<char>; template class chain<bool>; template class chain<float>; template class chain<double>; template class chain<long>; template class chain<string>;<file_sep>/csc402/inclassprograms/maxHeapDemo.cpp #include <iostream> #include "arrayMaxHeap.h" using namespace std; int main() { maxHeap<int> *myHeap; myHeap = new arrayMaxHeap<int>; cout << "Inserting into the heap...\n"; myHeap->push(5); myHeap->push(1); myHeap->push(8); myHeap->push(7); myHeap->push(13); myHeap->push(22); myHeap->push(3); myHeap->push(15); myHeap->push(-6); myHeap->push(56); myHeap->push(101); if(myHeap->empty()) cout << "The heap is empty\n\n"; else cout << "The heap is not empty\n\n"; while(!myHeap->empty()) { cout << "The top element is: " << myHeap->top() << endl; cout << "The size of the heap is: " << myHeap->size() << endl; myHeap->print(); myHeap->pop(); cout << "Pop!\n\n"; } cout << "The size of the heap is: " << myHeap->size() << endl; if(myHeap->empty()) cout << "The heap is empty\n\n"; else cout << "The heap is not empty\n\n"; return 0; } <file_sep>/csc237/project1/WordData.cpp /*************************************** * File: WordData.cpp * * Prepared by: Dr. Spiegel * * * ***************************************/ #include <iostream> #include <iomanip> #include <sstream> #include <string> #include "WordData.h" using namespace std; WordData::WordData(string wrd, int cnt) { setWordData(word, count); } void WordData::setWord(string wrd) { word = wrd; } void WordData::setCount(int cnt) { count = cnt; } void WordData::setWordData(string wrd, int cnt) { setWord(wrd); setCount(cnt); } string WordData::getWord() const { return(word); } int WordData::getCount() const { return(count); } void WordData::incCount(int amt) { setCount(getCount()+amt); } <file_sep>/csc135/hello100_ChristianCarreras.cpp //This program uses a while loop to repeat a message 100 times. #include <iostream> using namespace std; int main() { int factor; factor = 1; while (factor <= 100) { cout << "Hello World\n"; factor++; } return 0; } <file_sep>/csc520/finalproj/src/com/library/business_layer/field_list/Author.java package com.library.business_layer.field_list; import java.io.Serializable; /** * The Author class represents a real or made up author for a book. Author only * contains the author's name along with an identifier. Identifiers are meant * to act similar to a primary key in a database and as such should be unique. * Also implements Serializable so it can be serialized for later use. * BUSINESS LAYER CLASS */ public class Author implements Serializable { private int id; private String name; /** * Contstructs Author Object by setting its attributes to a value. * @param i identifier * @param n author name */ public Author(int i, String n) { setId(i); setName(n); } /** * Gets the int identifier value for this Object. * @return id as int */ public int getId() { return id; } /** * Gets the Author name as a String. * @return author name String */ public String getName() { return name; } /** * Sets the value for the Object identifier. * @param i int to set id to */ public void setId(int i) { id = i; } /** * Sets the value for the Author name. * @param n String to set name to */ public void setName(String n) { name = n; } }<file_sep>/csc241/README.txt CSC 241 - Advanced Visual Basic Programming Dr. <NAME> Kutztown University Spring 2013 This course is a study of some of the advanced features of Visual Basic. This study would include window design, database access and object oriented features of the language. Under window design such topics as menus, list boxes, common dialog boxes, and multiple form interfaces will be studied. Under database access such topics as creating/opening a database and reading/writing with a database will be studied. Object oriented concepts such as classes and controls will be covered. <file_sep>/csc237/project2/app.cpp /* // Author: <NAME> // (with thanks to Dr. Spiegel & <NAME>) // Course: CSC 237 // Filename: app.cpp // Purpose: This Example inputs a string and demon- // strates how to store it using a subclass // of an abstract base class that incorporates // virtual functions to enable polymorphism // If a file name is input through the command // line all of the options will be done // automatically */ #include <iostream> #include <sstream> #include <vector> #include <fstream> #include <cstdlib> #include "WordList.h" #include "WordDataList.h" #include "WordDataDLinkList.h" #include "DLinkedList.h" using namespace std; /* // Function Name: displayMenu // Parameters: none // Returns: void // Purpose: Displays the menu on the screen */ void displayMenu(); /* // Function Name: printEverything // Parameters: ifstream& - import/export - handle for data file // WordDataList* - export only // Returns: void // Purpose: Takes in a file and sends it through every // parsing and printing function */ void printEverything(ifstream &inf, WordList *TheList, string); /* // Function Name: getFile // Parameters: ifstream& - import/export // string - import only // Returns: true if the file was found and opened // false if the file was not found // or failed to open // Purpose: Tries to open a file and returns whether // it was opened or not */ bool getFile(ifstream &, string); /* // Function Name: chooseOption // Parameters: ifstream& - import/export // WordList* - import only // string - import only // Returns: void // Purpose: Creates an interface for the user to // choose what he/she wants to do */ void chooseOption(ifstream &inf, WordList *TheList, string); int main(int argc,char *argv[]) { ifstream inf; WordList *TheList; if(argc>1) //if there was an input on the command line { inf.open(argv[1]); //try and open the file if (inf.fail()) //if the file does not open { //terminate cout<<"Sorry, the file failed to open."<<endl; return 0; } string file = argv[1]; printEverything(inf ,TheList,file); return 0; } string fileName; cout<<"Please enter a file name: "; getline(cin,fileName); if(getFile(inf, fileName)) //If the file was found chooseOption(inf, TheList, fileName); //Go to the interface else //If the file was not found cout << "File not found.\n"; return 0; } /* // Displays menu to screen */ void displayMenu() { cout<<endl; cout<<"How do you want to print your sentence elements?"<<endl; cout<<"------------------------------------------------"<<endl; cout<<"1. Object Array Iterative"<<endl; cout<<"2. Object Array Recursive"<<endl; cout<<"3. Object Array Pointer Recursive"<<endl; cout<<"4. Double Linked List Iterative"<<endl; cout<<"5. Double Linked List Recursive"<<endl; cout<<"6. Quit"<<endl; } /* // Prints every option if command line is used */ void printEverything(ifstream &inf, WordList *TheList, string file) { TheList = new WordDataList; //Point TheList to a WordDataList TheList->parseIntoList(inf); TheList->printIteratively(); TheList->printRecursively(); TheList->printPtrRecursively(); free(TheList); //Reclaim memory inf.close(); //Reload the file inf.open(file.c_str()); TheList = new WordDataDLinkList;//Point TheList to a WordDataDlinkList TheList->parseIntoList(inf); TheList->printIteratively(); TheList->printRecursively(); free(TheList); //Reclaim memory } /* //Attempt to open file and return a truth value on whether //the file was able to be opened or not */ bool getFile(ifstream &inf, string file) { inf.open(file.c_str()); //Attempt to open the file if(inf.fail()) //If the file doesn't exist return false; else //If the file exists return true; } /* //The interface for the user: //Uses a switch statment to let //the user choose what he/she wants */ void chooseOption(ifstream &inf, WordList *TheList, string file) { char selection; int keepAlive = 1; //Keep interface open while (keepAlive) { displayMenu(); //Open menu cout << "Please enter your choice: "; cin>>selection; switch(selection) { case '1': //Print WordDataList Iteratively TheList = new WordDataList; TheList->parseIntoList(inf); TheList->printIteratively(); break; case '2': //Print WordDataList Recursively TheList = new WordDataList; TheList->parseIntoList(inf); TheList->printRecursively(); break; case '3': //Print WordDataList Ptr Recursively TheList = new WordDataList; TheList->parseIntoList(inf); TheList->printPtrRecursively(); break; case '4': //Print WordDataDLinkList Iteratively TheList = new WordDataDLinkList; TheList->parseIntoList(inf); TheList->printIteratively(); break; case '5': //Print WordDataDLinkList Recursively TheList = new WordDataDLinkList; TheList->parseIntoList(inf); TheList->printRecursively(); break; case '6': //Exit cout << "Goodbye" << endl; keepAlive = 0; break; default: //Error-catch cout << "I cannot understand " << selection; cout << ". Try again." << endl; break; } free(TheList); //Reclaim memory inf.close(); //Reload file getFile(inf, file); } } <file_sep>/csc355/GMOOH Web App/README.txt GMOOH is a web application created by myself and the other members of my senior seminar class at Kutztown University of Pennsylvania. I was team leader of the interface group. My responsibilites were leading my other teammates by dividing tasks, setting deadlines, checking in with other teams, and writing the code for my parts of the project. My team and I used HTML, CSS, JavaScript and PHP to create the look and feel of the website without the use of a framework. Credits Go To... Professor: Dr. Kaplan Team Manager: <NAME> Interface Team Leader: <NAME> Interface Team Member: <NAME> Interface Team Member: <NAME> Business Logic Team Leader: <NAME> Business Logic Team Member: <NAME> Business Logic Team Member: <NAME> + More (Sorry if I forgotten your name, you know who you are) Database Team Leader: <NAME> Database Team Member: <NAME> Database Team Member: <NAME> Also special thanks to Mr. <NAME> our school's IT specialist for setting up our own personal server to use and create our project with. *Seeing as I had to change servers and recreate the database from scratch for this preview some things may not work as intended or preform the same as when it was originally released* <file_sep>/csc135/averageGrade_ChristianCarreras.cpp //This program calculates the average of grades by using a while loop. #include <iostream> using namespace std; int main() { int timesran; float average, sum, grade; timesran = 0; sum = 0; cout << "Enter a grade, enter -1 to end: "; cin >> grade; while (grade != -1) { sum+=grade; cout << "Enter a grade, enter -1 to end: "; cin >> grade; timesran++; } average = sum/timesran; cout << "The class average is " << average << ".\n"; return 0; } <file_sep>/csc510/assignment5/makefile # makefile for assn5, problem 5, CSC 510 Advanced Operating Systems # Dr. <NAME>. Fall 2017 # Modified by <NAME> # do a 'make clean' before every simulation all: needtarget TARGET = csc510fall2017assn5 DEBUG = 1 DPOS := /home/KUTZTOWN/parson/OpSys DPPY := $(DPOS)/state2codeV15 CF = -std=gnu++0x -pthread include ./makelib clean: subclean /bin/rm -f *.o *.log testFair testWRP testSRP testWWP testSWP testFCFS test: needtarget needtarget: @echo "do 'make testAll', 'make testFair', 'make testWRP', 'make testWWP', or 'make testFCFS'" bash -c "exit 1" testAll: testFair testWRP testWWP testFCFS @echo "ALL SIMULATIONS COMPLETE" testFair: fair.o readWriteSTM.o @echo 'COMPILING testFair' /bin/bash -c "g++ $(CF) -o testFair fair.o readWriteSTM.o" @echo "COMPILING COMPLETED" @echo "SIMULATING (TESTING) testFair" /bin/bash -c "./testFair" @echo "COMPLETED (OK) SIMULATING (TESTING) testFair" testWRP: wrp.o readWriteSTM.o @echo 'COMPILING testWRP' /bin/bash -c "g++ $(CF) -o testWRP wrp.o readWriteSTM.o" @echo "COMPILING COMPLETED" @echo "SIMULATING (TESTING) testWRP" /bin/bash -c "./testWRP" @echo "COMPLETED (OK) SIMULATING (TESTING) testWRP" #testSRP: srp.o readWriteSTM.o # @echo 'COMPILING testSRP' # /bin/bash -c "g++ $(CF) -o testSRP srp.o readWriteSTM.o" # @echo "COMPILING COMPLETED" # @echo "SIMULATING (TESTING) testSRP" # /bin/bash -c "./testSRP" # @echo "COMPLETED (OK) SIMULATING (TESTING) testSRP" testWWP: wwp.o readWriteSTM.o @echo 'COMPILING testWWP' /bin/bash -c "g++ $(CF) -o testWWP wwp.o readWriteSTM.o" @echo "COMPILING COMPLETED" @echo "SIMULATING (TESTING) testWWP" /bin/bash -c "./testWWP" @echo "COMPLETED (OK) SIMULATING (TESTING) testWWP" #testSWP: swp.o readWriteSTM.o # @echo 'COMPILING testSWP' # /bin/bash -c "g++ $(CF) -o testSWP swp.o readWriteSTM.o" # @echo "COMPILING COMPLETED" # @echo "SIMULATING (TESTING) testSWP" # /bin/bash -c "./testSWP" # @echo "COMPLETED (OK) SIMULATING (TESTING) testSWP" testFCFS: fcfs.o readWriteSTM.o @echo 'COMPILING testFCFS' /bin/bash -c "g++ $(CF) -o testFCFS fcfs.o readWriteSTM.o" @echo "COMPILING COMPLETED" @echo "SIMULATING (TESTING) testFCFS" /bin/bash -c "./testFCFS" @echo "COMPLETED (OK) SIMULATING (TESTING) testFCFS" fair.o: @echo 'COMPILING fair' /bin/bash -c "g++ $(CF) -c fair.cpp" wrp.o: @echo 'COMPILING wrp' /bin/bash -c "g++ $(CF) -c wrp.cpp" #srp.o: # @echo 'COMPILING srp' # /bin/bash -c "g++ $(CF) -c srp.cpp" wwp.o: @echo 'COMPILING wwp' /bin/bash -c "g++ $(CF) -c wwp.cpp" #swp.o: # @echo 'COMPILING swp' # /bin/bash -c "g++ $(CF) -c swp.cpp" fcfs.o: @echo 'COMPILING fcfs' /bin/bash -c "g++ $(CF) -c fcfs.cpp" readWriteSTM.o: @echo 'COMPILING readWriteSTM' /bin/bash -c "g++ $(CF) -c readWriteSTM.cpp" <file_sep>/csc421/assignment2/README.txt * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Yahtzee © 2017 Hasbro, Inc. * Version 2.0 * <NAME> BS Computer Science * Kutztown University of Pennsylvania * * JavaDocs Link: * http://csitrd.kutztown.edu/~ccarr419/csc421/assignment2/ * * - - - - - - - - - - MY DESIGN CHOICES - - - - - - - - - - * * For this project I decided to make a command-based * version of Yahtzee similar to computer console-like * commands. The user is provided with a prompt and can * enter commands freely. The user may start and quit the * game freely at will as well. To represent the dice I * created a Dice class object that made use of a int array * and used a pseudo-random number generator to represent a * roll of the dice. The Dice class is nested within the * YLogic class which holds the functions that modifies and * facilitates all necessary operations for the logic of * a game of Yahtzee. Within the YLogic class there is also * the nested class called roundData which collects data * from the game as the user plays it. Data from this class * is used for the 'gstat' command documented further down * the page. The YLogic class also creates two enums to * hold game-dependent constants like category indexes and * scores for certain categories and bonuses. To display * the game properly a separate class was created to * represent the interface of the game. This class' sole * purpose is to handle the interactions of the player * and the logic of the game. It will only call the * corresponding functions in the logic class depending * on user-input and game status. Lastly the Yahtzee.java * file is used to only call the functions to start the * interface, it no longer checks for command-line input. * The help page (this page), the categories page, the * and the scoresheet page are all read from files located * in the folder for easier editing and displaying purposes * (plus it cleans up the code!) The exception with the * scoresheet is that it is edited at runtime by inserting * the player scores into their rightful category. All * entered commands are transformed to lower-case for * compatibility and error-handling. All non-commands * are handled gracefully and returns the player prompt. * As a side note: the Yahtzee count variable shown under * the 'gstat' command will always show zero if you choose * the Yahtzee category with a score of zero. Even if you * roll a Yahtzee after the fact. This is completely * intentional as it is necessary in order to calculate * the Lower Section bonus in the scoresheet. * * Psst, hey you. Yes you! Want to hear something cool? * You didn't hear it from me but.. I heard you can pick * your own dice if you wanted to! Just type the magic * phrase 'ccc' and you will be able to set the dice * to your liking. Pretty cool huh? Just don't expect * the data guardians to keep up with your sorcery! * * - - - - - - - - - - - - HELP PAGE - - - - - - - - - - - - * GAME INPUT COMMANDS * * help - brings up the help page which displays the * complete list of commands that can be used * throughout the game. Can be called at any * point before or during the game. * * start - begin the game with the initial first roll. * Can also be called during a game to restart * the game from the beginning. A warning prompt * will be displayed if this command is called * during an active game. * * rstat - shows the current round information including * the current round, current roll, current dice, * current kept dice, and the dice previously * rolled this round. Can only be called during * an active game. * * gstat - shows the current game information including * the total number of rolls, the number of * Yahtzees rolled, total score, the score for * each round, the category picked for every * round, and the dice rolled for each roll in * every round. Can only be called during an * active game. Round information will only * be displayed if the user has completed one * or more rounds. * * score - shows the current player's score sheet. The * score sheet can only be viewed during a game. * The score sheet will be updated after every * round. Categories left blank are categories * not picked yet. Totals and bonuses are * calculated regardless of what categories * are picked or not picked. * * pdice - prints the current rolled dice in both dice * and numeric form. Can only be called * during a game in progress. * * roll - continues the round by rolling the dice again. * A player will only be able to use this * command if a game is in progress i.e. * the game has started and the player has * not exceeded the number of allotted rolls. * Should be preceded by the keep command to * keep dice through the next roll. * * keep - lets the user select which dice they wish to * keep before the next roll. Saved dice will * be carried over future rolls until the user * decides to change which dice are kept. The * user can use the keep command multiple times * before or after a roll if they choose to. * Can only be called during a game. * * cat - shows the complete list of categories that can * be picked by the user regardless if they meet * the prerequisites or not. This command can be * called before or during a game. * * acat - shows the available categories the user can * choose at the moment of this command call i.e. * categories the user has not picked yet. Will * also show what the user will score for each * specific category. Can only be called during * an active game. * * pcat - lets the user pick a category for their round * to fall under. Will only show available * categories similar to the acat command. Any * category not previously picked can be picked * even if the score will be zero. Can only be * called during an active game. * * clear - clears the buffer and aligns the prompt to the * top of the screen. Behaves exactly like the * UNIX 'clear' command or the Windows 'cls' * command. Can be called at any time. Only works * in an ANSI-supported environment. * * quit - lets the user end the game and terminate the * program at any point before or during a * game. The user will be prompted if they are * sure they want to quit. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <file_sep>/csc330/finalproject/src/app/src/main/java/com/example/christiancarreras/blackjack/LoginMain.java /* * Author: <NAME> * File: LoginMain.java * Date: 04/27/2016 * Class: Kutztown University of Pennsylvania, CSC 330 Mobile Development * Purpose: This java file holds the functionality for the log in page. * This is the first page the user will see when opening the app. The app will * prompt the user to enter a username and password to create an account or login. * If an account already exists, the user can log into that account; it will not be * able to be created. Vice versa an uncreated account cannot be logged into. */ package com.example.christiancarreras.blackjack; import android.database.sqlite.SQLiteDatabase; //Tools and methods for SQLite usage import android.database.Cursor; //For creating Cursor objects to search through the database import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; //Allows for communication between the view and back import android.content.Intent; //For creating Intent objects to switch activities import android.widget.EditText; //For creating EditText reference objects import android.widget.Toast; //For created Toast objects to show pop-up messages on screen public class LoginMain extends AppCompatActivity { SQLiteDatabase mydatabase; //Database that holds all users //This string will be sent with the intent so a message can be sent with it. public final static String EXTRA_MESSAGE = "com.example.christiancarreras.blackjack.MESSAGE"; /* * Method Name: onCreate * Method Type: n/a * Parameters: Bundle - (import only) * Return Value: void * Purpose: Creates a database if one does not exist. Then creates a table in that * database with the columns: Username, Password and Balance. If the database * exists then it will just be opened. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_main); //Create the database if it does not exist. Just open it if it does mydatabase = openOrCreateDatabase("blackjackDatabase", MODE_PRIVATE, null); //Create a table for user info in the database if it does not exist already mydatabase.execSQL("CREATE TABLE IF NOT EXISTS BlackjackUsers(Username VARCHAR,Password VARCHAR,Balance INTEGER);"); } /* * Method Name: login * Method Type: facilitator * Parameters: View - (import only) * Return Value: void * Purpose: Will check to make sure a username and password is entered with an * appropriate length. If a password and username of appropriate length is * entered then the user will be authenticated. If the account exists, the * user will be logged on and will be taken to the next page. If not, the * user will remain on the page and will be told the account does not exit. */ public void login(View view) { EditText usernameText = (EditText) findViewById(R.id.usernameText); EditText passwordText = (EditText) findViewById(R.id.passwordText); String username = usernameText.getText().toString(); String password = passwordText.getText().toString(); //Username must be 3 or more characters, password must be 5 or more characters if(username.length() >= 3 && password.length() >= 5) { //Check if the account exists if (authenticate(username, password)) { //The account exists and is authenticated, move to the next page Intent intent = new Intent(this, UserAccountMain.class); //Send the user's username as a message so the balance can be retrieved //and displayed in the next activity (UserAccountMain) intent.putExtra(EXTRA_MESSAGE, username); mydatabase.close(); //Close the database for security purposes startActivity(intent); } else //The account does not exist, inform the user Toast.makeText(getApplicationContext(), "Account Does Not Exist", Toast.LENGTH_LONG).show(); } else //The username/password is not long enough to match Toast.makeText(getApplicationContext(), "Please Enter A Longer Username And/Or Password", Toast.LENGTH_LONG).show(); } /* * Method Name: createAccount * Method Type: mutator * Parameters: View - (import only) * Return Value: void * Purpose: Will first check if the username and password entered are of appropriate * length. Then there will be a check as to whether that account exists * already. If the account does not exist yet, it will be inserted into the * database. If it does, the user will be informed that account already exists. */ public void createAccount(View view) { EditText usernameText = (EditText) findViewById(R.id.usernameText); EditText passwordText = (EditText) findViewById(R.id.passwordText); String username = usernameText.getText().toString(); String password = passwordText.getText().toString(); //Username must be 3 or more characters, password must be 5 or more characters if(username.length() >= 3 && password.length() >= 5) { //Check to see if the account already exists if(!checkEntries(username)) { //The account does not exist yet, create the account for the user mydatabase.execSQL("INSERT INTO BlackjackUsers VALUES('" + username + "','" + password + "','" + 1000 + "');"); Toast.makeText(getApplicationContext(), "Account Created", Toast.LENGTH_LONG).show(); } else //The account already exists, inform the user Toast.makeText(getApplicationContext(), "Account Exists Already", Toast.LENGTH_LONG).show(); } else //The username/password is not of appropriate length Toast.makeText(getApplicationContext(), "Please Enter A Longer Username And/Or Password", Toast.LENGTH_LONG).show(); } /* * Method Name: checkEntries * Method Type: facilitator * Parameters: String - (import only) * Return Value: boolean (true if entry exists, false if not) * Purpose: Checks the database for any rows that have a Username value that * matches the user's username. If there is a row, return true, else * return false. */ private boolean checkEntries(String username) { //Select all the rows from the database where the Username value = the user's username String query = "SELECT * FROM BlackjackUsers WHERE Username = '" + username + "'"; Cursor mycursor = mydatabase.rawQuery(query, null); if(mycursor.getCount() <= 0) //The query returned no results return false; mycursor.close(); return true; } /* * Method Name: authenticate * Method Type: facilitator * Parameters: String - (import only) * String - (import only) * Return Value: boolean - (true if entry exists, false if not) * Purpose: Similar to the checkEntries method except the username and password must * both be validated. */ private boolean authenticate(String username, String password) { //Select all rows from the database where the username and password match String query = "SELECT * FROM BlackjackUsers WHERE Username = '" + username + "' AND Password = '" + <PASSWORD> + "'"; Cursor mycursor = mydatabase.rawQuery(query, null); if(mycursor.getCount() <= 0) //The query returned no results return false; mycursor.close(); return true; } } <file_sep>/csc520/finalproj/src/com/library/protocol/field_list/PPublisher.java package com.library.protocol.field_list; import com.library.business_layer.field_list.Publisher; /** * PPublisher serves as a protocol to transfer Table information from the server * to the UI. Only serves as a way to view, print and facilitate information. * PROTOCOL LAYER * @see com.library.business_layer.field_list.Publisher */ public class PPublisher { private String name; /** * Basic constructor that sets all attributes. * @param n String publisher name */ public PPublisher(String n) { name = n; } /** * @return String publisher name * @see com.library.business_layer.field_list.Publisher#getName() */ public String getName() { return name; } /** * Prints the Publisher in a human understandable summary. */ public String toString() { String out = ""; out += (getName()); return out; } }<file_sep>/csc402/inclassprograms/selectSort.cpp #include <iostream> using namespace std; void printList(int[], int); void selectSort(int[], int); void swap(int&, int&); int main() { int input; int list[100]; int i = 0; int size = 0; cout << "Input your list to sort: (Press -1 to quit)\n"; while(input != -1) { cin >> input; if(input == -1) break; list[i] = input; i++; size++; } cout << "Current list: "; printList(list, size); cout << "Now lets use select sort...\n"; selectSort(list, size); cout << "Ordered list: "; printList(list, size); return 0; } void printList(int list[], int size) { for(int i = 0; i < size; i++) { cout << list[i]; cout << " "; } cout << endl; } void selectSort(int list[], int size) { for(int i = 0; i < size; i++) { int currLow = i; for(int j = i; j < size; j++) { if(list[j] < list[i] && list[j] < list[currLow]) currLow = j; } if(currLow == i) continue; swap(list[i], list[currLow]); printList(list, size); } } void swap(int &i, int &j) { int temp = i; i = j; j = temp; }<file_sep>/csc402/inclassprograms/matrixTrans.cpp #include <iostream> #include <string> #include <fstream> using namespace std; string getFileName(); bool openFile(ifstream&, string); void getMatrix(ifstream&, int[2][3]); void transpose(int[2][3], int[3][2]); void printMatrix(int[3][2]); int main() { ifstream inf; string fileName = getFileName(); int matrix[2][3]; int result[3][2]; if(openFile(inf, fileName)) { getMatrix(inf, matrix); transpose(matrix, result); printMatrix(result); } else cout << "Error: File not found\n"; } string getFileName() { string fileName; cout << "Enter matrix file name: "; cin >> fileName; return fileName; } bool openFile(ifstream &inf, string fileName) { bool fileOpen; inf.open(fileName.c_str()); if (inf.fail()) return fileOpen = false; else return fileOpen = true; } void getMatrix(ifstream &inf, int matrix[2][3]) { char ch; int i = 0; int j = 0; while(inf.get(ch)) { if(i > 1 || j > 2) return; if(ch >= 48 && ch <= 57) { matrix[i][j] = ch; i++; } else if(ch == '\n') { j++; i = 0; } } } void transpose(int orig[2][3], int result[3][2]) { for(int i = 0; i < 2; i++) for(int j = 0; j < 3; j++) result[j][i] = orig[i][j]; } void printMatrix(int matrix[3][2]) { for(int i = 0; i < 2; i++) { for(int j = 0; j < 3; j++) { cout << matrix[i][j]; cout << " "; } cout << endl; } } <file_sep>/csc402/assignment3/chainNode.h /* Author: <NAME> File: chainNode.h About: Node class holds a element that is a template for any given class. Node also has a pointer to another node. */ #include <iostream> using namespace std; template<class T> struct chainNode { T element; chainNode<T> *next; chainNode() {}; chainNode(const T& theElement) { this->element = theElement; } chainNode(const T& theElement, chainNode<T>* theNext) { this->element = theElement; this->next = theNext; } };<file_sep>/csc402/assignment1/arrayList402.cpp #include <iostream> using namespace std; template <class elt> class arrayList{ private: elt *element; // all items are int type int listSize; // number of elements in array int arrayLength; // capacity of the 1D array public: //constructor arrayList(); arrayList(int); // arrayList(arrayList &); ~arrayList(){delete [] element;} int size() const{return listSize;} int length() const {return arrayLength;} bool empty() const {return listSize==0;} void add(const elt&); //add new item at end of the arrayList // insert new item at the specific position void insert(int theIndex, const elt &theElement); // remove the item fro the specific position void erase(int theIndex); // find the index of the element int indexOf(elt &theElement) const; // get the item at the index int get(int theIndex) const; void output(ostream &out) const; private: //change 1D array length void changeArrayLength(int); bool checkIndex(int) const; }; //Constructor arrayList::arrayList<elt>() { element = new elt; listSize = 0; arrayLength = 10; } //Constructor w/ set array length arrayList::arrayList(int length) { element = new elt; listSize = 0; arrayLength = (length > 0 ? length : 10); } //Add an element to the array void arrayList::add(const elt theElement) { if(size() < length()) { element[listSize] = theElement; listSize++; } } //Insert an element into the array at a specific index void arrayList::insert(int theIndex, const elt &theElement) { if(theIndex >= 0 && theIndex < length()) { if(checkIndex(theIndex)) { erase(theIndex); element[theIndex] = theElement; } else { element[theIndex] = theElement; } listSize++; } else return; } //Erase an element from the array according to its index void arrayList::erase(int theIndex) { element[theIndex] = NULL; listSize--; } //Return the index of the given element int arrayList::indexOf(elt &theElement) const { for(int i = 0; i < length(); i++) if(element[i] == theElement) return i; return -1; } //Return the element at the given index int arrayList::get(int theIndex) const { if(checkIndex(theIndex)) return element[theIndex]; else return -1; } //Output the whole array void arrayList::output(ostream &out) const { for(int i = 0; i < length(); i++) { if(checkIndex(i)) { out << get(i); out << " "; } } } //Change the array length void arrayList::changeArrayLength(int newLength) { if(newLength > 0) { if(newLength < length()) { for(int i = newLength-1; i < length()-1; i++) { erase(i); } } arrayLength = newLength; } } //Check to see if there is an element at the given index bool arrayList::checkIndex(int theIndex) const { if(element[theIndex] != NULL) return true; else return false; } int main() { arrayList list(5); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.output(cout); cout << endl; list.insert(4, 9); list.insert(2, 75); list.insert(0, 13); list.output(cout); cout << endl; list.erase(4); list.erase(1); list.output(cout); cout << endl; return 0; } <file_sep>/csc135/simpleFigure_ChristianCarreras.cpp #include <iostream> using namespace std; void drawCircle(); void drawIntersect(); void drawBase(); int main() { drawCircle(); drawIntersect(); drawBase(); drawIntersect(); return 0; } void drawBase() { cout << "-------\n"; } void drawIntersect() { cout << " / \\\n" << " / \\ " << endl; } void drawCircle() { cout << " *\n * *\n * *\n"; } <file_sep>/csc520/finalproj/src/com/library/protocol/message_list/PReservationHome.java package com.library.protocol.message_list; import com.library.protocol.field_list.PReservation; import java.sql.Timestamp; /** * PReservationHome serves a singular purpose of creating protocol variables * that will be used and sent back and forth from server to UI. * PROTOCOL LAYER */ public class PReservationHome { /** * Creates a PReservation protocol variable. * @param n String reservation number * @param t Timestamp * @return PReservation */ public PReservation create(String n, Timestamp t) { PReservation pRes = new PReservation(n, t); return pRes; } } <file_sep>/csc402/assignment5/edge.h /* Author: <NAME> File: edge.h Class: CSC 402 Date: 10/11/2015 */ #include <iostream> using namespace std; struct edge { int from; int to; int weight; edge(int f, int t) { from = t; to = t; } edge(int f, int t, int w) { edge(f, t); weight = w; } }; <file_sep>/csc354/README.txt CSC 354 - Software Engineering I Dr. <NAME> Kutztown University Fall 2015 This is the first course in a two semester capstone sequence. This course introduces the fundamental principles of software engineering. Coverage will include the System Development Lifecycle (SDLC) methodologies, capturing requirements, design modeling, project management, risk management, and quality assurance. Students will learn techniques for requirements elicitation, prioritization, validation, and specification. They will be introduced to various design models that are used to capture requirements. Link to project: https://github.com/ccarr419/GMOOH-Web-App <file_sep>/csc237/project1/makefile #Author: <NAME> #File: makefile #Purpose: Makes it possible to link the WordInfo class # to its code and from there to WordTest.cpp CC = /opt/csw/gcc3/bin/g++ CFLAGS = -Wall p1: WordTest.o WordInfo.o $(CC) $(CFLAGS) -o p1 WordTest.o WordInfo.o WordTest.o: WordTest.cpp WordInfo.h $(CC) $(CFLAGS) -c WordTest.cpp WordInfo.o: WordInfo.cpp WordInfo.h $(CC) $(CFLAGS) -c WordInfo.cpp clean: rm -rf *.o <file_sep>/csc402/assignment3/makefile debugFlag=-g chainDemo: chainDemo.o chain.o g++ -o chainDemo chainDemo.o chain.o $(debugFlag) chain.o: chain.cpp chain.h chainNode.h g++ -c chain.cpp $(debugFlag) chainDemo.o: chainDemo.cpp chain.cpp chain.h g++ -c chainDemo.cpp clean: \rm -f *.o chainDemo <file_sep>/csc402/assignment5/adjacencyMatrixGraph.cpp /* Author: <NAME> File: adjacencyMatrixGraph.cpp Class: CSC 402 Date: 10/11/2015 */ #include <iostream> #include "adjacencyMatrixGraph.h" using namespace std; adjacencyMatrixGraph::adjacencyMatrixGraph(int n) { numNodes = n; matrix = new int*[numNodes]; for(int i = 0; i < numNodes; i++) matrix[i] = new int[numNodes]; for(int i = 0; i < numNodes; i++) for(int j = 0; j < numNodes; j++) matrix[i][j] = 0; } adjacencyMatrixGraph::~adjacencyMatrixGraph() { delete [] matrix; } int adjacencyMatrixGraph::numberOfVertices() const { int numVertices = 0; for(int i = 0; i < numNodes; i++) { for(int j = 0; j < numNodes; j++) { if(matrix[i][j] == 1) { numVertices++; break; } } } return numVertices; } int adjacencyMatrixGraph::numberOfEdges() const { int numEdges = 0; for(int i = 0; i < numNodes; i++) for(int j = 0; j < numNodes; j++) if(matrix[i][j] == 1) numEdges++; return numEdges; } bool adjacencyMatrixGraph::existsEdge(int from, int to) const { return (matrix[from][to] || matrix[to][from]); } void adjacencyMatrixGraph::insertEdge(int f, int t) { matrix[f][t] = 1; matrix[t][f] = 1; } void adjacencyMatrixGraph::eraseEdge(int f, int t) { matrix[f][t] = 0; matrix[t][f] = 0; } int adjacencyMatrixGraph::degree(int from) const { int degree = 0; for(int i = 0; i < numNodes; i++) if(matrix[from][i] == 1) degree++; return degree; } /* Not a directed graph int adjacencyMatrixGraph::inDegree(int) const { } int adjacencyMatrixGraph::outDegree(int) const { } */ void adjacencyMatrixGraph::output(ostream& out) const { for(int i = 0; i < numNodes; i++) { for(int j = 0; j < numNodes; j++) out << matrix[i][j] << " "; out << "\n"; } } void adjacencyMatrixGraph::BFS(int v, vector<int>& visited_list) const { queue<int> q; q.push(v); visited_list.push_back(v); BFSHelper(q, visited_list); } void adjacencyMatrixGraph::BFSHelper(queue<int> q, vector<int>& visited_list) const { if(q.empty()) return; vector<int> adjacent_vertices = adjacent(q.front()); for(int i = 0; i < adjacent_vertices.size(); i++) { if(!find(visited_list, adjacent_vertices.at(i))) { visited_list.push_back(adjacent_vertices.at(i)); q.push(adjacent_vertices.at(i)); } } q.pop(); BFSHelper(q, visited_list); } void adjacencyMatrixGraph::DFS(int v, vector<int>& visited_list) const { visited_list.push_back(v); vector<int> adjacent_vertices = adjacent(v); for(int i = 0; i < adjacent_vertices.size(); i++) { int w = adjacent_vertices.at(i); if(find(visited_list, w)) continue; else DFS(w, visited_list); } } vector<int> adjacencyMatrixGraph::adjacent(int start) const { vector<int> adjacent_list; for(int i = 0; i < numNodes; i++) if(matrix[start][i] == 1) adjacent_list.push_back(i); return adjacent_list; } bool adjacencyMatrixGraph::find(vector<int> list, int v) const { for(int i = 0; i < list.size(); i++) if(list.at(i) == v) return true; return false; } <file_sep>/csc135/returnValue_ChristianCarreras.cpp /********************************************************* This program uses parameters and pass by values to calculate the total tickets sold, total ticket price and total tax. Author: <NAME> *********************************************************/ #include <iostream> using namespace std; //Function prototypes int getNumber(); //No parameters, returns value float calculateTotal(int tickets1); //Returns value float calculateTax(float total1); //Returns value void displayResult(int tickets2, float total2, float tax1); //Returns no value //Main function int main() { //Variables int ticketssold; float total, totaltax; //Call functions with return values ticketssold = getNumber(); total = calculateTotal(ticketssold); totaltax = calculateTax(total); //Call function with void return type displayResult(ticketssold, total, totaltax); return 0; } /***************************************** This fuction asks for the total tickets sold and returns the value back to the main function. *****************************************/ int getNumber() { int tickets; cout << "How many tickets were sold? "; cin >> tickets; cout << endl; return tickets; } /********************************** This function calculates the total of price of every ticket sold and returns it to the main function. **********************************/ float calculateTotal(int tickets1) { float ticketprice; ticketprice = tickets1 * 10.99; return ticketprice; } /********************************* This function calculates the total tax from the total ticket price and returns the value to the main function. *********************************/ float calculateTax(float total1) { float tax; tax = total1 * 0.06; return tax; } /********************************************************* This fuction displays tickets sold, total sales and tax when called in the main function. *********************************************************/ void displayResult(int tickets2, float total2, float tax1) { cout << "Tickets Sold:\t" << tickets2 << endl; cout << "Total Sales:\t$" << total2 << endl; cout << "Tax\t\t$" << tax1 << endl; } <file_sep>/csc136/project3b/Array.h /* Author: Dr. Spiegel Updated By: <NAME> File: Array.h Description: Simple class Array (for Term class) */ #ifndef ARRAY_H #define ARRAY_H #include <iostream> using namespace std; class Term; class Array { public: ////////////// //Constructor ////////////// /* Function: Constructor Description: Constructs an array of Terms Parameters: none Returns: N/A */ Array( int = 10 ); /////////////////// //Copy Constructor /////////////////// /* Function: Copy Constructor Description: Creates copy of the Array object Parameters: const Array& - Array object Returns: N/A */ Array( const Array & ); ////////////// //Destructor ////////////// /* Function: Destructor Description: Removes an Array object from memory Parameters: none Returns: N/A */ ~Array(); ///////// //Sets ///////// /* Function: setCapacity Member Type: Mutator Description: Sets the capacity of the Array object Parameters: int - capacity Returns: void */ void setCapacity(int); ///////// //Gets ///////// /* Function: getCapacity Member Type: Inspector Description: Returns the Array object's capacity Parameters: none Returns: int - capacity */ int getCapacity() const; /* Function: getElements Member Type: Inspector Description: Returns the elementsInUse Parameters: none Returns: int - elementsInUse */ int getElements() const; /* Function: getArrayCount Member Type: Inspector Description: Returns number of Arrays in use Parameters: none Returns: int - arrayCount */ static int getArrayCount(); /////////////////// //Member Functions /////////////////// /* Function: addTerm Member Type: Mutator Description: Calls other addTerm function with smaller data Parameters: Term& - Term object to be added to array Returns: true if Term is added, false if not */ bool addTerm(Term&); /* Function: addTerm Member Type: Mutator Description: Checks if array if full and if the coeff is zero Then calls cDupLoc and += Parameters: float - coefficient int - exponent Returns: true if Term is added, false if not */ bool addTerm(float, int); /* Function: cDupLoc Member Type: Mutator Description: Checks if one element's exponent matches another in the array and if so adds that element's coefficient to the other matching element's coefficient Parameters: float - coefficient int - exponent Returns: true if there is a duplicate location, false if not */ bool cDupLoc(float, int); /* Function: sort Member Type: Mutator Description: Class selSort Parameters: none Returns: void */ void sort(); ////////////// //Operators ////////////// /* Function: = operator Member Type: Mutator Description: Sets one array object equal to another Parameters: const Array& - array object to be set equal to Returns: const Array - the array object itself */ const Array &operator=( const Array & ); /* Function: == operator Member Type: Facilitator Description: Checks if two array objects are equal Parameters: const Array& - array object to be compared to Returns: true if arrays are equal, false if not */ bool operator==( const Array & ) const; // compare equal // Determine if two arrays are not equal and // return true, otherwise return false (uses operator==). bool operator!=( const Array &right ) const { return ! ( *this == right ); } /* Function: [] operator Member Type: Mutator Description: Allows user to potentially change an array element Parameters: int - array index Returns: returns the Term at that Array index */ Term &operator[]( int ); // subscript operator /* Function: [] operator Member Type: Inspector Description: Enables individual array elements to be displayed Parameters: int - array index Returns: returns the Term at that Array index */ const Term &operator[]( int ) const; // subscript operator /* Function: += operator Member Type: Mutator Description: Appends a Term to the end of an Array object Parameters: Term& - the Term to be added Returns: Array& - the Array object itself */ Array& operator+=(Term &); private: int capacity; // size of the array int elementsInUse; // elements of the array used Term *ptr; // pointer to first element of array static int arrayCount; // # of Arrays instantiated /* Function: setElements Member Type: Mutator Description: Sets elementsInUse, private so user can't mess with it Parameters: int - elementsInUse Returns: void */ void setElements(int); }; /* Function: << operator Description: Diplsys the array term by term Parameters: ostream& - output stream const Array& - Array to be place into string Returns: ostream */ ostream &operator<<( ostream &, const Array & ); #endif <file_sep>/csc237/project1/WordTest.cpp /** // Author: <NAME> // File: WordTest.cpp // Purpose: Thoroughly tests multiple data structures including // parallel arrays, classes and vectors. Also this file // tests those data structure by various methods such as // the use of an iterator or recursion. */ #include <iostream> #include <string> #include <fstream> #include <iomanip> #include <vector> #include "WordInfo.h" using namespace std; /** // Function: menu // Parameters: none // Returns: void // Purpose: Displays the menu to the user // after file has been located. */ void menu(); /** // Function: openFile // Parameters: ifstream& - import/export // string& - import only // Returns: true if file was found // false if not // Purpose: Asks user to input a file // and will return a truth value // based on if the file was found or not */ bool getFile(ifstream &, string &); /** // Function: options // Parameters: ifstream& - import only // Returns: only false if the user chooses to exit // Purpose: Selects the appropriate function // according to the user's choice */ bool options(ifstream &); /** // Function: paraIt // Parameters: ifstream& - import only // Returns: void // Purpose: Uses parallel arrays to sort and display // data iteratively */ void paraIt(ifstream &); /** // Function: paraRe // Parameters: ifstream& - import only // Returns: void // Purpose: Uses parallel arrays to sort and // display data recursively */ void paraRe(ifstream &); /** // Function: objectAIt // Parameters: ifstream& - import only // Returns: void // Purpose: Uses the WordInfo class/object to sort // and display data iteratively */ void objectAIt(ifstream &); /** // Function: objectARe // Parameters: ifstream& - import only // Returns: void // Purpose: Uses the WordInfo class/object to sort // and display data recursively */ void objectARe(ifstream &file); /** // Function: objectAPoint // Parameters: ifstream& - import only // Returns: void // Purpose: Uses a pointer to the WordInfo array // to display data recursively with the // help of other functions */ void objectAPoint(ifstream &file); /** // Function: stlVecFL // Parameters: ifstream& - import only // Returns: void // Purpose: Uses a vector of the WordInfo type to sort // and display data using for loops. */ void stlVecFL(ifstream &); /** // Function: stlVecIt // Parameters: ifstream& - import only // Returns: void // Purpose: Uses a vector of the WordInfo type to sort and display data using a vector iterator */ void stlVecIt(ifstream &); /** // Function: openFileArray // Parameters: ifstream& - import only // string[] - import/export // int[] - import/export // string - import only // int& - import/export // Returns: void // Purpose: Stores the data from a file into the array // also calls checkDup to check for any duplicates */ void openFileArray(ifstream &, string[], int[], string, int&); /** // Function: openFileObject // Parameters: ifstream& - import only // WordInfo[] - import/export // string - import only // int& - import/export // Returns: void // Purpose: Stores the data from a file into the array of objects // also calls checkDupObject to check for any duplicates */ void openFileObject(ifstream &, WordInfo[], string, int&); /** // Function: openFileVector // Parameters: ifstream& - import only // vector<WordInfo>& - import/export // WordInfo - import only // Returns: void // Purpose: Stored the data from a file into a vector of WordInfo // also calls checkDupVector to check for any duplicates */ void openFileVector(ifstream &, vector<WordInfo> &, WordInfo); /** // Function: checkDup // Parameters: int[] - export only // string[] - import only // string - import only // int - import only // Returns: true if duplicate location found // false if not // Purpose: Checks for a duplicate location in data // for the functions paraIt and paraRe */ bool checkDup(int[], string[], string, int); /** // Function: checkDupObject // Parameters: WordInfo[] - import/export // string - import only // int - import only // Returns: true if duplicate location found // false if not // Purpose: Checks for a duplicate location in data // for the function objectAIt, objectARe and objectAPoint */ bool checkDupObject(WordInfo[], string, int); /** // Function: checkDupVector // Parameters: vector<WordInfo>& - import/export // WordInfo - import only // Returns: true if duplicate location found // false if not // Purpose: Checks for a duplicate location for a vector // in the function stlVecFL and stlVecIt */ bool checkDupVector(vector<WordInfo> &, WordInfo); /** // Function: displayArray // Parameters: string[] - import only // int[] - import only // int - import only // int - import only // Returns: number of elements in array // Purpose: Displays elements of the parallel // arrays by the use of recursion */ int displayArray(string[], int[], int, int); /** // Function: displayObject // Parameters: WordInfo[] - import only // int - import only // int - import only // Returns: number of elements in array // Purpose: Displays elements of the WordInfo // array by the use of recursion */ int displayObject(WordInfo[], int, int); /** // Function: displayPointObject // Parameters: WordInfo* - import only // int - import only // int - import only // Returns: number of elements in array // Purpose: Displays elements of the WordInfo // array by the use of pointers and recursion */ int displayPointObject(WordInfo*, int, int); int main(int argc, char *argv[]) //Command-line arguments { ifstream inf; if(argc == 2) //Running the program from the command line { string file = argv[1]; if(getFile(inf, file)) //Check for file { paraIt(inf); inf.close(); inf.open(file.c_str()); cout << endl; //Close and reopen the file before every other function paraRe(inf); inf.close(); inf.open(file.c_str()); cout << endl; objectAIt(inf); inf.close(); inf.open(file.c_str()); cout << endl; objectARe(inf); inf.close(); inf.open(file.c_str()); cout << endl; objectAPoint(inf); inf.close(); inf.open(file.c_str()); cout << endl; stlVecFL(inf); inf.close(); inf.open(file.c_str()); cout << endl; stlVecIt(inf); inf.close(); cout << endl; } else //If the argument filename was not found cout << "File not found.\n"; exit(-1); } string file; cout << "\nPlease enter a file: "; getline(cin, file); if(getFile(inf, file)) //If the file was found { menu(); //Open menu bool runAgain = options(inf); //User chooses an option while(runAgain) { inf.close(); inf.open(file.c_str()); menu(); runAgain = options(inf); } } else //If the file was not found cout << "File not found.\n"; return 0; } /** //Displays menu to screen */ void menu() { cout << "\n1: PARALLEL ITERATIVE\n"; cout << "2: PARALLEL RECURSIVE\n"; cout << "3: OBJECT ARRAY ITERATIVE\n"; cout << "4: OBJECT ARRAY RECURSIVE\n"; cout << "5: OBJECT ARRAY POINTER RECURSIVE\n"; cout << "6: STL VECTOR FOR LOOP\n"; cout << "7: STL VECTOR ITERATOR\n"; cout << "8: EXIT\n\n"; } /** //Lets user select one of the //8 options from the menu */ bool getFile(ifstream &inf, string &file) { inf.open(file.c_str()); //Attempt to open the file if(inf.fail()) //If the file doesn't exist return false; else //If the file exists return true; } /** //This function lets the user select an option //and then uses a switch statement to hook up //the code for his/her choice. */ bool options(ifstream &inf) { int answer; cout << "Please enter your choice: "; cin >> answer; switch(answer) { case 1: //Parallel Arrays Iterative paraIt(inf); break; case 2: //Parallel Array Recursive paraRe(inf); break; case 3: //Object Array Iterative objectAIt(inf); break; case 4: //Object Array Recursive objectARe(inf); break; case 5: //Object Array Pointer-Recursive objectAPoint(inf); break; case 6: //STL Vector For Loop stlVecFL(inf); break; case 7: //STL Vector Iterative stlVecIt(inf); break; case 8: //Exit cout << "Goodbye\n"; return false; break; default: //Error Catch cout << "Invalid Choice\n"; break; } return true; } /** //This function uses parallel arrays to hold and display data. //Uses the function CheckDup to assist in duplicate data. */ void paraIt(ifstream &file) { string checkWord; //Temporary storage string word[10]; //Holds the words int count[10] = {0}; //Holds the # of times words appear int counter = 0; openFileArray(file, word, count, checkWord, counter); cout << "Data presented iteratively using parallel arrays:\n"; for(int i = 0; i < counter; i++) //Display data in arrays cout << left << setw(15) << word[i] << count[i] << endl; } /** //This function uses parallel arrays and the //function openFileArray to hold data. //With the help of displayArray is displays the //data recursively. */ void paraRe(ifstream &file) { string out = ""; string checkWord; string word[10]; int count[10] = {0}; int counter = 0; openFileArray(file, word, count, checkWord, counter); //Store data cout << "Data presented recursively using parallel arrays:\n"; displayArray(word, count, counter, 0); //Display data } /** //This function uses the WordInfo class to store information //with the help of loops to access the data iteratively */ void objectAIt(ifstream &file) { WordInfo word[10]; string checkWord; //Terporary storage int counter = 0; openFileObject(file, word, checkWord, counter); cout << "Data presented iteratively using an object array:\n"; for(int i = 0; i < counter; i++) //Display the array of objects cout << word[i] << endl; } /** //This funtion uses a WordInfo array to hold data. //Then calls several functions to insert the data //and to display the data */ void objectARe(ifstream &file) { WordInfo word[10]; string checkWord; //Terporary storage int counter = 0; openFileObject(file, word, checkWord, counter); //Store data cout << "Data presented recursively using an object array:\n"; displayObject(word, counter, 0); //Display data } /** //This function uses a WordInfo array to hold data. //Then calls several functions to insert the data //and to display the data */ void objectAPoint(ifstream &file) { WordInfo word[10]; string checkWord; //Terporary storage int counter = 0; openFileObject(file, word, checkWord, counter); //Store data cout << "Data presented recursively using pointers to an object array:\n"; WordInfo *point = word; displayPointObject(point, counter, 0); //Display data } /** //This function uses a vector to hold data //then calls a function to insert the data. //The data is displayed using a for loop */ void stlVecFL(ifstream &file) { vector<WordInfo> word; //vector of WordInfo type WordInfo checkWord; //Temporary object openFileVector(file, word, checkWord); cout << "Data presented with a for loop using a vector:\n"; for(unsigned i = 0; i < word.size(); i++) //for loop to display data cout << word[i] << endl; } /** //This function uses a vector to hold data //then calls functions to insert and display //the data. */ void stlVecIt(ifstream &file) { vector<WordInfo> word; WordInfo checkWord; openFileVector(file, word, checkWord); cout << "Data presented with an iterator using a vector:\n"; for(vector<WordInfo>::iterator it = word.begin(); it != word.end(); ++it) cout << *it << endl; //Display the data using an iterator } /** //This function is called by paraIt and paraRe //it inserts the data from a file into the parallel //arrays and checks for duplicates by calling //the checkDup function */ void openFileArray(ifstream &file, string word[], int count[], string checkWord, int &counter) { while(file >> checkWord) { if(!checkDup(count, word, checkWord, counter)) { if(counter < 10) //If the array is not full { word[counter] = checkWord; //Put word in array count[counter]++; //Increment count of word counter++; //Increment the counter } } } } /** //This function is called by objectAIt, objectARe and objectAPoint //it inserts data from a file into the WordInfo array and checks //for duplicates by call the checkDupObject function */ void openFileObject(ifstream &file, WordInfo word[], string checkWord, int &counter) { while(file >> checkWord) { if(!checkDupObject(word, checkWord, counter)) { if(counter < 10) //If the array of object is not full { word[counter].setWord(checkWord); word[counter]++; counter++; } } } } /** //This funcion is called by stlVecFL and stlVecIt //it inserts data from a file into the vector //and checks from duplicates by calling the //checkDupVector function */ void openFileVector(ifstream &file, vector<WordInfo> &word, WordInfo checkWord) { while(file >> checkWord) { if(word.size() == 0) //If vector is empty word.push_back(checkWord); else //Check for duplicates if(!checkDupVector(word, checkWord)) word.push_back(checkWord); } } /** //This function checks for duplicate data using a for loop //then returns true or false based on whether a duplicate was found. */ bool checkDup(int count[], string word[], string checkWord, int counter) { for(int i = 0; i < counter; i++) { if(checkWord == word[i]) //If the word from file is already in the array { count[i]++; //Increase count of word return true; } } //No duplicate found return false; } /** //This function checks for duplicate data within the WordInfo //object array, returns true or false based on results */ bool checkDupObject(WordInfo theWord[], string checkWord, int counter) { for(int i = 0; i < counter; i++) { if(checkWord == theWord[i].getWord()) { theWord[i]++; return true; } } //No duplicate found return false; } /** //This function checks for duplicate data within a vector of WordInfo //returns true or false based on the results */ bool checkDupVector(vector<WordInfo> &word, WordInfo checkWord) { for(unsigned i = 0; i < word.size(); i++) { if(checkWord.getWord() == word[i].getWord()) { word[i]++; return true; } } //No duplicate in vector return false; } /** //This function displays the contents of parallels arrays //by the use of recursion */ int displayArray(string word[], int count[], int counter, int i) { if(i == counter) //Display whole array return i; else { cout << left << setw(15) << word[i] << count[i] << endl; return displayArray(word, count, counter, i+1); } } /** //This function displays the contents of a WordInfo //array by the use of recursion */ int displayObject(WordInfo word[], int counter, int i) { if(i == counter) //Display whole object array return i; else { cout << left << setw(15) << word[i].getWord() << word[i].getCount() << endl; return displayObject(word, counter, i+1); } } /** //This function displays the contents of a WordInfo //array by the use of pointers and recursion */ int displayPointObject(WordInfo* word, int counter, int i) { if(i == counter) //Display whole object array with pointer return i; else { cout << left << setw(15) << word[i].getWord() << word[i].getCount() << endl; return displayObject(word, counter, i+1); } } <file_sep>/csc570/DataMineTensorFlow/CSC558DataMineII/noise_data.py import pandas as pd import tensorflow as tf TRAIN_FILE = 'csc558noise_training_e.csv' TEST_FILE = 'csc558noise_testing_e.csv' CSV_COLUMN_NAMES = [ 'tid', 'centroid', 'rms', 'roll25', 'roll50', 'roll75', 'shftfftfund', 'amplscale', 'amplbin1', 'amplbin2', 'amplbin3', 'amplbin4', 'amplbin5', 'amplbin6', 'amplbin7', 'amplbin8', 'amplbin9', 'amplbin10', 'amplbin11', 'amplbin12', 'amplbin13', 'amplbin14', 'amplbin15', 'amplbin16', 'amplbin17', 'amplbin18', 'amplbin19', 'funfreq', 'centrfreq', 'roll25freq', 'roll50freq', 'roll75freq', 'nc', 'n25', 'n50', 'n75', 'normrms', 'tosc'] CLASSIFICATIONS = 5 CSV_COLUMN_DEFAULTS = [ [0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0] ] def load_data(y_name='tosc'): """Returns the iris dataset as (train_x, train_y), (test_x, test_y).""" train = pd.read_csv(TRAIN_FILE, names=CSV_COLUMN_NAMES, header=0) train = train.fillna(0) train_x, train_y = train, train.pop(y_name) test = pd.read_csv(TEST_FILE, names=CSV_COLUMN_NAMES, header=0) test = test.fillna(0) test_x, test_y = test, test.pop(y_name) return (train_x, train_y), (test_x, test_y) def train_input_fn(features, labels, batch_size): """An input function for training""" # Convert the inputs to a Dataset. dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels)) # Shuffle, repeat, and batch the examples. dataset = dataset.shuffle(1000).repeat().batch(batch_size) # Return the dataset. return dataset def eval_input_fn(features, labels, batch_size): """An input function for evaluation or prediction""" features = dict(features) if labels is None: # No labels, use only features. inputs = features else: inputs = (features, labels) # Convert the inputs to a Dataset. dataset = tf.data.Dataset.from_tensor_slices(inputs) # Batch the examples assert batch_size is not None, "batch_size must not be None" dataset = dataset.batch(batch_size) # Return the dataset. return dataset # The remainder of this file contains a simple example of a csv parser, # implemented using a the `Dataset` class. # `tf.parse_csv` sets the types of the outputs to match the examples given in # the `record_defaults` argument. def _parse_line(line): # Decode the line into its fields fields = tf.decode_csv(line, record_defaults=CSV_COLUMN_DEFAULTS) # Pack the result into a dictionary features = dict(zip(CSV_COLUMN_NAMES, fields)) # Separate the label from the features label = features.pop('OxygenMgPerLiter') return features, label def csv_input_fn(csv_path, batch_size): # Create a dataset containing the text lines. dataset = tf.data.TextLineDataset(csv_path).skip(1) # Parse each line. dataset = dataset.map(_parse_line) # Shuffle, repeat, and batch the examples. dataset = dataset.shuffle(1000).repeat().batch(batch_size) # Return the dataset. return dataset <file_sep>/csc402/README.txt CSC 402 - Advanced Data Structures Kutztown University Fall 2015 This course is the second course in data structures. It is designed to present the computer science student with depth of knowledge in the area of data structures. The course is a study in advanced topics of data structures focusing on their structure, efficiency and application. Data structures introduced or expanded include graphs, sets and trees. <file_sep>/csc136/project3a/Array.h // File: array.h // Simple class Array (for Term class) #ifndef ARRAY_H #define ARRAY_H #include <iostream> using namespace std; class Term; class Array { public: Array( int = 10 ); // default constructor Array( const Array & ); // copy constructor ~Array(); // destructor void setCapacity(int); // set the capacity int getCapacity() const; // return capacity int getElements() const; const Array &operator=( const Array & ); // assign arrays bool operator==( const Array & ) const; // compare equal // Determine if two arrays are not equal and // return true, otherwise return false (uses operator==). bool operator!=( const Array &right ) const { return ! ( *this == right ); } Term &operator[]( int ); // subscript operator const Term &operator[]( int ) const; // subscript operator static int getArrayCount(); // Return count of // arrays instantiated. bool addTerm(Term&); bool addTerm(float, int); bool cDupLoc(float, int); void sort(); Array& operator+=(Term &); private: int capacity; // size of the array int elementsInUse; Term *ptr; // pointer to first element of array static int arrayCount; // # of Arrays instantiated void setElements(int); }; ostream &operator<<( ostream &, const Array & ); #endif <file_sep>/csc237/project4/Treetest.cpp /** * Author: <NAME> * Updated By: <NAME> * File: Treetest.cpp * Date: 25/04/2014 * Purpose: Application to thoroughly test the BinarySearchTree by letting * users add and remove integers from the tree, change existing * elements within the tree, and print the tree as it currently is **/ #include <iostream> #include <string> #include "BinarySearchTree.h" using namespace std; typedef BinaryTree<int> BinarySearchTree; /* * Function Name: getChoice * Parameters: string - import only * Return Value: char - users choice * Purpose: returns the first char in the string that the user * entered regardless of other chars in the string * Then converts the char to its uppercase form **/ char getChoice(string ok); int main() { BinarySearchTree Tree; int entry, *result, data; char Choice; do //Print menu to screen { cout << "Select: A)dd R)emove C)hange P)rint"; cout << " T)ree Print Q)uit\n"; Choice=getChoice("ARCPTQ");//User enters choice switch (Choice) { case 'A': //Add integer to tree cout << " Enter an Integer >"; cin >> entry; Tree.insertToTree(entry); break; case 'R': //Remove integer from tree cout << "Value to Delete? >"; cin >> entry; if (!Tree.treeSearch(entry)) //Integer not within tree cout << entry << " Not Found\n"; else //Integer is in tree { if(Tree.hasMultiples(entry))//Check for multiplicity { cout << "Do you want to delete (1) or (a)ll? >"; char choice; cin >> choice; switch(choice) { case '1'://Delete only one Tree.decCount(entry); break; case 'a'://Delete all Tree.deleteFromTree(entry); break; default: //User entered something else cout << "I cannot understand "; cout << choice << endl; break; } } else //Only one copy, delete it Tree.deleteFromTree(entry); } break; case 'C': //Changes one integer to another within the tree cout << "Value to change? >"; cin >> entry; if(!(Tree.treeSearch(entry)))//Integer not in tree cout << entry << " Not Found\n"; else //Integer is in the tree { cout << "Value to change it to? >"; cin >> data; Tree.change(entry, data); } break; case 'P': //Print the tree in order least to greatest cout << "The Tree:" << endl; Tree.inorder(); break; case 'T'://Print the tree to actually look somewhat like a tree cout << "The tree, as it appears (sort of)..\n"; Tree.treePrint(); break; } } while (Choice != 'Q'); //While the user doesn't quit the program } //Get the user's choice for the menu char getChoice(string ok) { char ch=' '; do ch=toupper(cin.get()); while (ok.find(ch)==string::npos); cin.get(); // eat CR return(toupper(ch)); } <file_sep>/csc136/project3b/Array.cpp // File: array.cpp // Member function definitions for class Array #include <iostream> #include <iomanip> #include <stdlib.h> #include <assert.h> #include "Array.h" #include "term.h" #include "SortSearch.h" using namespace std; // Initialize static data member at file scope int Array::arrayCount = 0; // no objects yet // Default constructor for class Array (default size 10) Array::Array( int arraySize ) { setCapacity(( arraySize > 0 ? arraySize : 10 )); ptr = new Term[getCapacity()]; // create space for array assert( ptr != 0 ); // terminate if memory not allocated ++arrayCount; // count one more object setElements(0); for ( int i = 0; i < getCapacity(); i++ ) ptr[ i ] = 0; // initialize array } // Copy constructor for class Array // must receive a reference to prevent infinite recursion Array::Array( const Array &init ) { setCapacity(init.getCapacity()); ptr = new Term[getCapacity()]; // create space for array assert( ptr != 0 ); // terminate if memory not allocated ++arrayCount; // count one more object setElements(getElements()); for ( int i = 0; i < getElements(); i++ ) ptr[ i ] = init.ptr[ i ]; // copy init into object } // Destructor for class Array Array::~Array() { delete [] ptr; // reclaim space for array --arrayCount; // one fewer objects } // Set the Array's size void Array::setCapacity(int elts) { capacity=elts; } // Get the size of the array int Array::getCapacity() const { return capacity; } int Array::getElements() const { return elementsInUse; } // Overloaded assignment operator // const return avoids: ( a1 = a2 ) = a3 const Array &Array::operator=( const Array &right ) { if ( &right != this ) { // check for self-assignment // for arrays of different sizes, deallocate original // left side array, then allocate new left side array. if ( getCapacity() != right.getCapacity() ) { delete [] ptr; // reclaim space setCapacity(right.getCapacity()); // resize this object ptr = new Term[getCapacity()]; // create space for array copy assert( ptr != 0 ); // terminate if not allocated } for ( int i = 0; i < getElements(); i++ ) ptr[ i ] = right[ i ]; // copy array into object } setElements(right.getElements()); return *this; // enables x = y = z; } // Determine if two arrays are equal and // return true, otherwise return false. bool Array::operator==( const Array &right ) const { if ( getElements() != right.getElements() ) return false; // arrays of different sizes for ( int i = 0; i < getElements(); i++ ) if ((ptr[i].getCoefficient() && ptr[i].getExponent()) != (right[i].getCoefficient() && right[i].getExponent())) return false; // arrays are not equal return true; // arrays are equal } // Overloaded subscript operator for non-const Arrays // reference return creates an lvalue Term &Array::operator[]( int subscript ) { // check for subscript out of range error assert( 0 <= subscript && subscript < getElements() ); return ptr[ subscript ]; // reference return } // Overloaded subscript operator for const Arrays // const reference return creates an rvalue const Term &Array::operator[]( int subscript ) const { // check for subscript out of range error assert( 0 <= subscript && subscript < getElements() ); return ptr[ subscript ]; // const reference return } // Return the number of Array objects instantiated // static functions cannot be const int Array::getArrayCount() { return arrayCount; } bool Array::addTerm(Term &T) { return(addTerm(T.getCoefficient(), T.getExponent())); } bool Array::addTerm(float coeff, int expn) { Term T; if(getElements() < getCapacity()) //Check if Array is full { if(coeff != 0) { if(!cDupLoc(coeff, expn))//Check for duplicate location { T.setCoefficient(coeff); T.setExponent(expn); *this+=T; //Add the term to array sort(); //Sort Array return true; } else { setElements(getElements()+1); return true; } } else return false; } else return false; } void Array::sort() { selSort(ptr, getElements()); } //Check to find if exponents match bool Array::cDupLoc(float coeff, int expn) { int idx = getElements(); for(int i = 0; i < getElements(); i++) { if(expn == ptr[i].getExponent())//Duplicate Location { ptr[i].setCoefficient(ptr[i].getCoefficient()+coeff); setElements(getElements()-1); } } if(idx != getElements()) return true; else return false; } //Adds Term to the Array Array& Array::operator+=(Term &T) { ptr[elementsInUse].setCoefficient(T.getCoefficient()); ptr[elementsInUse].setExponent(T.getExponent()); setElements(getElements()+1); } void Array::setElements(int x) { elementsInUse = x; } // Overloaded output operator for class Array ostream &operator<<( ostream &output, const Array &a ) { for(int i = 0; i < a.getElements(); i++) { if(i < a.getElements()-1) output << a[i] << " + "; else output << a[i]; } return output; // enables cout << x << y; } <file_sep>/csc402/inclassprograms/functionOverloading.cpp #include <iostream> using namespace std; /* void exchange(int &n1, int &n2) { int tmp; tmp = n1; n1 = n2; n2 = tmp; } void exchange(float &n1, float &n2) { float tmp; tmp = n1; n1 = n2; n2 = tmp; } void exchange(char &n1, char &n2) { char tmp; tmp = n1; n1 = n2; n2 = tmp; } */ namespace myNameSpace { template<class T> void swap(T &n1, T &n2) { cout << "Using my name space swap\n"; T tmp; tmp = n1; n1 = n2; n2 = tmp; } }; int main() { int a = 1, b = 2; cout << a << "\t" << b << endl; myNameSpace::swap (a, b); cout << a << "\t" << b << endl; float c = 3.5, d = 4.2; cout << c << "\t" << d << endl; myNameSpace::swap (c, d); cout << c << "\t" << d << endl; char e = '#', f = '*'; cout << e << "\t" << f << endl; myNameSpace::swap (e, f); cout << e << "\t" << f << endl; return 0; } <file_sep>/csc402/assignment3/chainDemo.cpp /* Author: <NAME> File: chainDemo.cpp About: Tests every aspect of the chain class. */ #include <iostream> #include "chain.h" using namespace std; int main() { //Constructor checks linearList<int> *myList; myList = new chain<int>; cout << "New chain created.\n"; //empty function check if(myList->empty()) cout << "The chain is empty.\n"; //insert function check myList->insert(0, 5); myList->insert(1, 18); myList->insert(2, 64); myList->insert(3, 12); myList->insert(4, 128); //output function check cout << "Chain now contains: "; myList->output(cout); //size function check cout << "\nChain size: " << myList->size() << endl; //get function check cout << "Element at index 0 is: " << myList->get(0) << endl; cout << "Element at index 1 is: " << myList->get(1) << endl; cout << "Element at index 2 is: " << myList->get(2) << endl; cout << "Element at index 3 is: " << myList->get(3) << endl; cout << "Element at index 4 is: " << myList->get(4) << endl; //indexOf function check cout << "The index of 128 is: " << myList->indexOf(128) << endl; cout << "The index of 12 is: " << myList->indexOf(12) << endl; cout << "The index of 64 is: " << myList->indexOf(64) << endl; cout << "The index of 18 is: " << myList->indexOf(18) << endl; cout << "The index of 5 is: " << myList->indexOf(5) << endl; //insert into list at beginning, end and middle check myList->insert(0, 43); myList->insert(6, 90); myList->insert(2, 27); cout << "Chain now contains: "; myList->output(cout); cout << "\nChain size: " << myList->size() << endl; //erase function check at beginning, end and middle //myList->erase(0); //Seg Fault? myList->erase(7); myList->erase(2); cout << "Chain now contains: "; myList->output(cout); cout << "\nChain size: " << myList->size() << endl; //copy constructor test //correct syntax needed //linearList<int> *copyList; //copyList = new chain<int>(*myList); return 0; //Destructor check upon program end }<file_sep>/csc136/project4/term.h /* File: term.h Author: <NAME> Course: CSC136 Assignment: Project 4 Description: The Term class contains a coefficient and exponent which is used and implemented by the Polynomial class. This class also has the ability to multiply, evaluate, input and output a Term as well as check if Terms are or are not equal, and check if two Terms are greater/less than each other. */ #ifndef TERM_H #define TERM_H #include <iostream> using namespace std; class Term { public: ///////////////// //Constructor ///////////////// /* Function: Constructor Member Type: Mutator Description: Sets coefficient and exponent to zero Parameters: None Returns N/A */ Term(float coeff = 0, int expn = 0); ///////// //Sets ///////// /* Function: setTerm Member Type: Mutator Description: Sets the coefficient and exponent in the term Parameters: float - coefficient to put in the term int - exponent to put in the term Returns: true if value is set, false if not */ bool setTerm(float coeff, int expn); /* Function: setCoefficient Member Type: Mutator Description: Sets the coefficient in the term Parameters: float - input - coefficient to put in the term Returns: true if value is set, false if not */ bool setCoefficient(float coeff); /* Function: setExponent Member Type: Mutator Description: Sets the exponent in the term Parameters: int - input - exponent to put in the term Returns: true if value is set, false if not */ bool setExponent(int expn); ///////// //Gets ///////// /* Function: getCoefficient Member Type: Inspector Description: Returns the coefficient value of the term Parameters: none Returns: float - coefficient */ float getCoefficient() const; /* Function: getExponent Member Type: Inspector Description: Returns the exponent value of the term Parameters: none Returns: int - exponent */ int getExponent() const; ////////////// //Operators ////////////// /* Function: *= operator Member Type: Mutator Description: Multiplies term coefficient by a factor Parameters: double - factor to multiply by Returns: void */ void operator *=(double); /* Function: () operator Member Type: Facilitator Description: Evaluates the term for the given factor Parameters: double - input - factor to evaluate the term by Returns: double - the term evaluated */ double operator ()(double) const; /* Function: == operator Member Type: Facilitator Description: Checks if the exponent of a term is equal to the given integer Parameters: Term - input - number to check if equal to Returns: true if the exponent is equal, false if not */ bool operator ==(Term) const; /* Function: != operator Member Type: Facilitator Description: Checks if the the exponent of term is not equal to the given integer Parameters: Term - input - number to check not equal to Returns: true if not equal, false if equal */ bool operator !=(Term) const; /* Function: > operator Member Type: Facilitator Description: Checks if the Term is greater than a given Term Parameters: Term& - input - Term to check if greater than Term Returns: true if the term is greater than the other term, false if not */ bool operator >(const Term &) const; /* Function: < operator Member Type: Facilitator Description: Checks if the Term is less than a given Term Parameters: Term& - input - Term to check if greater than Term Returns: true if the term is less than the other term, false if not */ bool operator <(const Term &) const; /* Function: += operator Member Type: Mutator Description: Combines common terms Parameters: Term& - input - Term to add to another term Returns: bool */ bool operator +=(const Term &); private: float coefficient; int exponent; }; //////////////////////// //Associative Operators //////////////////////// /* Function: >> operator Description: Takes input and places it inside the term's coefficient and exponent. Enables cin << Term Parameters: ifstream& - input stream Term& - The Term from user-input Returns: ifstream */ ifstream &operator>>( ifstream &, Term & ); /* Function: << operator Description: Outputs the Term in correct polynomial form Enables cout << Term Parameters: ostream& - the output stream const Term& - the Term to ouput Returns: ostream */ ostream &operator<<( ostream &, const Term & ); #endif <file_sep>/csc237/project1/WordData.h /*************************************** * File: WordData.h * * Prepared by: Dr. Spiegel * * * ***************************************/ #ifndef WORDDATA_H #define WORDDATA_H #include <iostream> #include <string> using namespace std; class WordData { public: //Constructor WordData(string wrd = "", int cnt = 0); //Sets void setWord(string wrd); void setCount(int cnt); //Set Whole WordData Object void setWordData(string,int); //Gets string getWord() const; int getCount() const; //Increment void incCount(int amt = 1); private: //variables string word; int count; }; #endif <file_sep>/csc552/project3/makefile #Author: <NAME> #File: client.cpp #Date: 04/12/2017 #Course: CSC 552 Adv Unix Prog #Professor: Dr. Spiegel #School: Kutztown University #Project: #3 #Due Date: 05/11/2017 #About: CC=/usr/bin/g++ #Compile whole project, make sure everything is up to date p3: client.cpp server.cpp $(CC) -o client client.cpp $(CC) -o server server.cpp #Compile just the client client: client.cpp $(CC) -o client client.cpp #Compile just the server server: server.cpp $(CC) -o server server.cpp <file_sep>/csc135/switch_ChristianCarreras.cpp //This program uses a menu and switch statements to do problems #include <iostream> #include <cmath> using namespace std; int main() { //variable for choice int choice; // menu cout << "What do you want to do?\n"; cout << "1. Compute area of a circle\n"; cout << "2. Compute area of a rectangle\n"; cout << "3. Compute area of a triangle\n"; cout << "4. None of them\n"; cin >> choice; switch (choice) //switch statement { case 1: // area of a circle float radius, area_circle; cout << "What is the radius of the circle? "; cin >> radius; area_circle = 3.14*pow(radius, 2); cout << "The answer is " << area_circle << endl; break; case 2: // area of a rectangle float length, width, area_rectangle; cout << "What is the length of the rectangle? "; cin >> length; cout << "What is the width of the rectangle? "; cin >> width; area_rectangle = length*width; cout << "The answer is " << area_rectangle << endl; break; case 3: // area of a triangle float base, height, area_triangle; cout << "What is the base of the triangle? "; cin >> base; cout << "What is the height of the triangle? "; cin >> height; area_triangle = 0.5*base*height; cout << "The answer is " << area_triangle << endl; break; case 4: // end program break; default: // entry other than 1-4 cout << "Invalid entry\n"; break; } return 0; } <file_sep>/programmingteam/easyscript.cpp #include <iostream> #include <string> #include <fstream> using namespace std; string getFileName(); bool openFile(ifstream&, string); void getChar(ifstream&, string&); int main() { string fileName, output; ifstream inf; fileName = getFileName(); if (openFile(inf, fileName)) { cout << "File opened!\n"; getChar(inf, output); cout << output << endl;; } else cout << "Error!\n"; return 0; } string getFileName() { string fileName; cout << "\nPlease enter the file name: "; cin >> fileName; return fileName; } bool openFile(ifstream &inf, string fileName) { bool fileOpen; inf.open(fileName.c_str()); if (inf.fail()) return fileOpen = false; else return fileOpen = true; } void getChar(ifstream &inf, string &out) { char ch, chTemp; int i = 0; string temp = ""; string holder = ""; while(inf.get(ch)) { cout << ch; if(ch != '\n') { if(i % 2 == 0) out += ch; else temp += ch; } else { if(i % 2 == 0) { out += ch; i++; } else { for(int j = 0; j < temp.length(); j++) { chTemp = temp[j]; out += chTemp; /*if(chTemp != ' ') holder += chTemp; else strHolder.push_back(holder);*/ } out += chTemp; out += ch; temp = ""; i++; } } } } <file_sep>/csc520/README.txt CSC 520 - Advanced Object-Oriented Programming Dr. <NAME> Kutztown University Spring 2018 This course introduces the concepts of object-oriented programming languages, object-oriented analysis and design, and design patterns, and demonstrates their use in the development of an object-oriented implementation of a major project. The Unified Modeling Language (UML) is used to develop the project's design and implementation. A current programming language is used throughout the course to illustrate major concepts and implement the project. <file_sep>/csc520/finalproj/src/com/library/server_layer/MembershipServer.java package com.library.server_layer; import com.library.business_layer.field_list.Member; import com.library.business_layer.field_list.CreditCard; import com.library.business_layer.field_list.Address; import com.library.business_layer.field_list.InternetAccount; import com.library.business_layer.message_list.MemberHome; import com.library.protocol.message_list.PMemberHome; import com.library.protocol.field_list.PMember; import com.library.protocol.field_list.PCreditCard; import com.library.protocol.field_list.PAddress; /** * The role of the MembershipServer is to communicate between the Home * classes and server UI classes. The functionality of this server includes * reading Member, CreditCard, Address and Password for a session id and * the ability for a member to change their password. * SERVER LAYER */ public class MembershipServer { private MemberHome mh; private PMemberHome pMH; /** * Basic constructor for this Object that initializes used Home classes. */ public MembershipServer() { mh = new MemberHome(); pMH = new PMemberHome(); } /** * Get Member with the session id. Transforms Member into PMember for * tranferring to server UI. * @param i int session id * @return PMember */ public PMember readMember(int i) { Member mem = mh.findBySessionId(i); if(mem != null) { return pMH.create(mem.getName(), mem.getPhone(), mem.getAmountDue(), mem.getInGoodStanding(), mem.getNumber()); } return null; } /** * Get CreditCard with the session id. Transforms Member into PCreditCard * for tranferring to server UI. * @param i int session id * @return PCreditCard */ public PCreditCard readCreditCard(int i) { CreditCard cc = mh.findCardBySessionId(i); if(cc != null) { return pMH.create(cc.getType(), cc.getNumber(), cc.getExpiration()); } return null; } /** * Get Address with the session id. Transforms Member into PAddress * for tranferring to server UI. * @param i int session id * @return PAddress */ public PAddress readAddress(int i) { Address add = mh.findAddressBySessionId(i); if(add != null) { return pMH.create(add.getHouse(), add.getStreet(), add.getCounty(), add.getZip()); } return null; } /** * Get Member password with the session id. * @param i int session id * @return String password */ public String readPassword(int i) { InternetAccount ia = mh.findAccountBySessionId(i); if(ia != null) { return ia.getPassword(); } return null; } /** * Changes the old password to a new password for the session id Member. * @param i int session id * @param o String old password * @param n String new password * @return true if password was changed, false if not */ public boolean changePassword(int i, String o, String n) { InternetAccount ia = mh.findAccountBySessionId(i); if(ia != null) { if(ia.getPassword().equals(o)) { mh.getInternetAccounts().setForId(ia.getId(), "password", n); return true; } } return false; } /** * Force the update of the MembershipServer and all its Homes */ public void update() { mh.update(); } }<file_sep>/csc520/finalproj/src/com/library/protocol/field_list/PCatalogedBook.java package com.library.protocol.field_list; import com.library.business_layer.field_list.CatalogedBook; /** * PCatalogedBook serves as a protocol to transfer Table information from the server * to the UI. Only serves as a way to view, print and facilitate information. * PROTOCOL LAYER * @see com.library.business_layer.field_list.BorrowedBook */ public class PCatalogedBook { private String isbn; private String name; /** * Basic constructor that sets all attributes. * @param i String ISBN * @param n String book title */ public PCatalogedBook(String i, String n) { isbn = i; name = n; } /** * @return String book ISBN * @see com.library.business_layer.field_list.CatalogedBook#getIsbn() */ public String getIsbn() { return isbn; } /** * @return String book title * @see com.library.business_layer.field_list.CatalogedBook#getName() */ public String getName() { return name; } /** * Prints the CatalogedBook in a human understandable summary. */ public String toString() { String out = ""; out += ("\"" + getName() + "\""); return out; } } <file_sep>/csc237/project4/BinarySearchTree.cpp /** * Author: <NAME> * Updated By: <NAME> * File: BinarySearchTree..cpp * Date: 23/4/2014 * Purpose: Binary Tree ADT using linked structures. * The Binary tree uses treeNode template objects * to hold all data. The Binary Tree consists of one * data member named root which is a pointer to a * treeNode object. As a binary tree works, the left pointer * of a treeNode object will point to a node with data less * than the parent's data. The right pointer will also point * to a treeNode object but will have data greater than the * parent node. The Binary tree class has functions to properly * implement a tree structure by being able to insert, remove, * change and print data held within the tree. **/ #include <iostream> #include <string> #include <queue> #include "BinarySearchTree.h" using namespace std; /** * Function Name: Constructor * Member Type: Constructor * Parameters: None * Return Value: N/A * Purpose: Constructs the BinaryTree by pointing the data member * root at NULL **/ template <typename treeEltType> BinaryTree<treeEltType>::BinaryTree() { root = NULL; } /** * Function Name: insertToTree * Member Type: Mutator * Parameters: const treeEltType& - import only * Return Value: int - (1) true boolean value * Purpose: Finds appropriate place in tree for the parameter, * uses a while loop to navigate through tree until * either it can be placed or the data is already in the * list, where from there, would increase the data's counter **/ template <typename treeEltType> int BinaryTree<treeEltType>:: insertToTree(const treeEltType &data) { if(root == NULL) // Empty Tree { root = new TreeNode<treeEltType>(data); return(1); } // Search for spot to put data; We only stop when we get to the bottom (NULL) TreeNode<treeEltType> *t = root, *parent; while(t != NULL) { if(t->info == data) // data already in Tree { t->count++; //Increment count for multiplicity return(1); } //Set the trail pointer to the ancestor of where we're going parent = t; if(data < t->info) t = t->left; else t = t->right; } // Found the spot; insert node. if(data < parent->info) parent->left = new TreeNode<treeEltType>(data); else parent->right = new TreeNode<treeEltType>(data); return(1); } /** * Function Name: treeSearch * Member Type: Facilitator * Parameters: const treeEltType& - import only * Return Value: Returns Ptr to Elt if Found, NULL otherwise * (true if found, false if not) * Purpose: Used while loop to navigate through tree until * data is found or NULL is hit * Assumes == is defined for treeEltType **/ template <typename treeEltType> bool BinaryTree<treeEltType>:: treeSearch(const treeEltType &key) { TreeNode<treeEltType> *t = root; while(t && t->info != key) if(key < t->info) t = t->left; else t = t->right; return(t); // auto convert int to bool } /** * Function Name: retrieveFromTree * Member Type: Inspector * Parameters: const treeEltType& - import only * Return Value: treeEltType& - the node's info * Purpose: Retrieve Element from Tree (leaving Tree Intact) * Precondition: Item is in Tree **/ template <typename treeEltType> treeEltType &BinaryTree<treeEltType>:: retrieveFromTree(const treeEltType &key) { TreeNode<treeEltType> *t; for(t = root; t->info != key;) if(key < t->info) t = t->left; else t = t->right; return(t->info); } /** * Function Name: deleteFromTree * Member Type: Mutator * Parameters: const treeEltType& - import only * Return Value: void * Purpose: Remove an Element from the tree * Precondition: Element is in the Tree; **/ template <typename treeEltType> void BinaryTree<treeEltType>:: deleteFromTree(const treeEltType &data) { TreeNode<treeEltType> *nodeWithData, *nodeToDelete, *t = root,*trailT = NULL; // Find spot while(t->info != data)//safe because of precondition { trailT = t; if(data < t->info) t = t->left; else t = t->right; } nodeWithData = t; //Hold onto the data Node for later deletion // Case 1: Leaf? if(!(nodeWithData->left) && !(nodeWithData->right)) { // No Subtrees, node is leaf...Wipe it // Is it the root? if(nodeWithData == root) root = NULL; else if(trailT->right == nodeWithData) //Parent's right child trailT->right = NULL; else trailT->left = NULL; nodeToDelete = nodeWithData; //free this at the end } else if(!(nodeWithData->left)) {//If 1st condition false and this one's true, there's a right subtree if(!trailT) { // Node to delete is root and there is no left subtree nodeToDelete = root; root = root->right; } else //Point parent's pointer to this node to this node's right child { if(trailT->right == nodeWithData) trailT->right = nodeWithData->right; else trailT->left = nodeWithData->right; nodeToDelete = nodeWithData; } } else if(!(nodeWithData->right)) // If 1st 2 conditions false and this one's true, there's a left subtree { if (!trailT) { // Node to delete is root and there is no left subtree nodeToDelete = root; root = root->left; } else { // Otherwise, move up the right subtree if(trailT->right == nodeWithData) trailT->right = nodeWithData->left; else trailT->left = nodeWithData->left; nodeToDelete = nodeWithData; } } else { // If you make it here, node has two children //Go to rightmost node in left subtree; we know there's a right child for(trailT = nodeWithData, t = nodeWithData->left; t->right != NULL;trailT = t, t = t->right); // Want to copy data from node with 0 or 1 child to node with data to delete // Place node data in NodeWithData nodeWithData->info = t->info; nodeWithData->count = t->count; // Set the parent of source node to point at source node's left child // (We know it hasn't a right child. Also ok if no left child.) if(trailT == nodeWithData) // Need to point parent correctly. // See if after the we went left there was no right child // If there was no right child, this is rightmost node in left subtree trailT->left = t->left; else // we did go right; after going left, there was a right child // rightmost node has no r. child, so point its parent at its l. child trailT->right = t->left; nodeToDelete = t; } delete nodeToDelete; } /** * Function Name: change * Member Type: Mutator * Parameters: const treeEltType& - import only * const treeEltType& - import only * Return Value: void * Purpose: User enters a value in the tree to change, if the value * is in the tree it will be removed and the new value * will be inserted into the tree **/ template <typename treeEltType> void BinaryTree<treeEltType>:: change(const treeEltType &toChange, const treeEltType &data) { TreeNode<treeEltType> *t = root,*trailT = NULL; if(treeSearch(data))//If data is already in the tree { while(t->info != data) if(data < t->info) t = t->left; else t = t->right; if(hasMultiples(toChange))//Has multiples { decCount(toChange);//Decrease count for node to change t->count++;//Increase count for node being changed to } else { deleteFromTree(toChange);//Delete node t->count++; //Increment multiplicity } } else//Data isn't already in the tree { while(t->info != toChange) //Find node { trailT = t;//Parent if(toChange < t->info) t = t->left; else t = t->right; } if(t == root)//If root { if(!(t->left) && !(t->right))//Root w/ no children { if(t->count > 1) { t->count--; insertToTree(data); } else t->info = data; } else if(t->left && !(t->right)) //Root w/ only left child { if(data > toChange)//Data g.t. root { if(t->count > 1) { t->count--; insertToTree(data); } else t->info = data; } else//Data l.t. root { TreeNode<treeEltType> *n = t->left; while(n->right != NULL)//Go to rightmost child n = n->right; if(data > n->info) {//Data g.t. rightmost leaf if(t->count > 1) { t->count--; insertToTree(data); } else t->info = data; } else//Data l.t. rightmost leaf //Delete root and insert new data { if(t->count > 1) { t->count--; insertToTree(data); } else { deleteFromTree(toChange); insertToTree(data); } } } } else if(!(t->left) && t->right) //Root w/ only right child { if(data < toChange)//Data l.t. root { if(t->count > 1) { t->count--; insertToTree(data); } else t->info = data; } else//Data g.t. root { TreeNode<treeEltType> *n = t->right; while(n->left != NULL)//Go to leftmost child n = n->left; if(data < n->info) //Data l.t. leftmost leaf { if(t->count > 1) { t->count--; insertToTree(data); } else t->info = data; } else//Data g.t leftmost leaf //Delete root and insert new data { if(t->count > 1) { t->count--; insertToTree(data); } else { deleteFromTree(toChange); insertToTree(data); } } } } else//Root has two children { TreeNode<treeEltType> *n1 = t->left; TreeNode<treeEltType> *n2 = t->right; while(n1->right != NULL)//Go to rightmost child n1 = n1->right; while(n2->left != NULL)//Go to lefmost child n2 = n2->left; if(data > n1->info && data < n2->info) {//Data is g.t. rightmost & l.t. leftmost if(t->count > 1) { t->count--; insertToTree(data); } else t->info = data; } else//Data does not fall in previous range { if(t->count > 1) { t->count--; insertToTree(data); } else { deleteFromTree(toChange); insertToTree(data); } } } } else //The node to change is a child of some sort { if(!(t->left) && !(t->right))//Just a leaf { if(t->count > 1) { t->count--; insertToTree(data); } else { deleteFromTree(toChange); insertToTree(data); } } else if(t->left && !(t->right)) //Subtree w/ only left child { if(toChange < trailT->info)//left node of parent { TreeNode<treeEltType> *n = t->left; while(n->right != NULL)//Go to rightmost child n = n->right; if(data > n->info && data < trailT->info) //Data is g.t. left child & l.t. parent { if(t->count > 1) { t->count--; insertToTree(data); } else t->info = data; } else//Data does not fall in previous range { if(t->count > 1) { t->count--; insertToTree(data); } else { deleteFromTree(toChange); insertToTree(data); } } } else//Right node of parent { if(data < toChange && data > t->left->info) //Data is l.t. info but g.t. left child { if(t->count > 1) { t->count--; insertToTree(data); } else t->info = data; } else //Cannot get range { deleteFromTree(toChange); insertToTree(data); } } } else if(!(t->left) && t->right) //Subtree w/ only right child { if(toChange > trailT->info)//right node of parent { TreeNode<treeEltType> *n = t->right; while(n->left != NULL)//Go to leftmost child n = n->left; if(data < n->info && data > trailT->info) //Data is l.t. left child & g.t. parent { if(t->count > 1) { t->count--; insertToTree(data); } else t->info = data; } else//Data does not fall in previous range { if(t->count > 1) { t->count--; insertToTree(data); } else { deleteFromTree(toChange); insertToTree(data); } } } else//Left node of parent { if(data > toChange && data < t->right->info) //Data is g.t. info but l.t. left child { if(t->count > 1) { t->count--; insertToTree(data); } else t->info = data; } else //Cannot get range { deleteFromTree(toChange); insertToTree(data); } } } else//Subtree with two children { TreeNode<treeEltType> *n1 = t->left; TreeNode<treeEltType> *n2 = t->right; while(n1->right != NULL)//Go to rightmost child n1 = n1->right; while(n2->left != NULL)//Go to lefmost child n2 = n2->left; if(data > n1->info && data < n2->info) //Data is g.t. rightmost & l.t. leftmost { if(t->count > 1) { t->count--; insertToTree(data); } else t->info = data; } else//Data does not fall in previous range { if(t->count > 1) { t->count--; insertToTree(data); } else { deleteFromTree(toChange); insertToTree(data); } } } } } } /** * Function Name: hasMultiples * Member Type: Facilitator * Parameters: const treeEltType& - import only * Return Value: true if data has multiplicity * false if not * Purpose: Checks if data has multiple entries within the tree * Precondition: Tree has at least copy of data **/ template <typename treeEltType> bool BinaryTree<treeEltType>:: hasMultiples(const treeEltType &data) { TreeNode<treeEltType> *t = root; while(t->info != data)//Find node if(data < t->info) t = t->left; else t = t->right; if(t->count > 1)//Check for multiplicity return true;//There is multiples else return false;//Ther is no multiples } /** * Function Name: decCount * Member Type: Mutator * Parameters: const treeEltType& - import only * Return Value: void * Purpose: decrements the count of the data in the tree * Preconditions: Tree has more than one copy of data **/ template <typename treeEltType> void BinaryTree<treeEltType>:: decCount(const treeEltType &data) { TreeNode<treeEltType> *t = root; while(t->info != data)//Find node if(data < t->info) t = t->left; else t = t->right; t->count--; //Decrement count } /** * Function Name: printInorder * Member Type: Facilitator * Parameters: TreeNode<treeEltType>* - import only * Return Value: void * Purpose: Recursive helper function that prints the tree in order * from least to greatest while also printing the * multiplicity of the data (if greater than one) **/ template <typename treeEltType> void BinaryTree<treeEltType>:: printInorder(TreeNode<treeEltType> *t) const //void printTheTree(TreeNode *T) { if(t) { printInorder(t->left); cout << t->info; if(t->count > 1) //If there is more than one cout << "(" << t->count << ")"; //Show multiplicity cout << endl; printInorder(t->right); } } /** * Function Name: inorder * Member Type: Facilitator * Parameters: None * Return Value: void * Purpose: Prints tree in order least to greatest with the help * of the recursive helper function printInorder **/ template <typename treeEltType> void BinaryTree<treeEltType>::inorder()const { printInorder(root); } /** * Function Name: printPreorder * Member Type: Facilitator * Parameters: TreeNode<treeEltType>* - import only * Return Value: void * Purpose: Recursive helper function that prints the tree in * preorder (NLR) **/ template <typename treeEltType> void BinaryTree<treeEltType>:: printPreorder(TreeNode<treeEltType> *t) const //void printTheTree(TreeNode *t) { if(t) { cout << t->info << endl; if(t->count > 1) //If there is more than one cout << "(" << t->count << ")"; //Show multiplicity printPreorder(t->left); printPreorder(t->right); } } /** * Function Name: preorder * Member Type: Facilitator * Parameters: None * Return Value: void * Purpose: Prints the tree in preorder (NLR) print node, go left * repeat until those options are used up then go right. * Uses the help of the printPreorder recursive function **/ template <typename treeEltType> void BinaryTree<treeEltType>::preorder()const { printPreorder(root); } /** * Function Name: printPostorder * Member Type: Facilitator * Parameters: TreeNode<treeEltType>* - import only * Return Value: void * Purpose: Recursive helper function that prints the tree in * preorder (LRN) **/ template <typename treeEltType> void BinaryTree<treeEltType>:: printPostorder(TreeNode<treeEltType> *t) const //void printTheTree(TreeNode *t) { if(t) { printPostorder(t->left); printPostorder(t->right); cout << t->info << endl; if(t->count > 1) //If there is more than one cout << "(" << t->count << ")"; //Show multiplicity } } /** * Function Name: postorder * Member Type: Facilitator * Parameters: None * Return Value: void * Purpose: Prints the tree in postorder (LRN) go left, then go right * until both options are used up, then print node. * Uses the help of the printPostorder recursive function **/ template <typename treeEltType> void BinaryTree<treeEltType>::postorder()const { printPostorder(root); } /** * Function Name: treePrint * Member Type: Facilitator * Parameters: None * Return Value: void * Purpose: Prints in the tree shape (sort of) * With the root on top and every subtree/leaf * to its correct row or correct parent. * Calls helper function treePrintHelper **/ template <typename treeEltType> void BinaryTree<treeEltType>::treePrint()const { treePrintHelper(root); } /** * Function Name: treePrintHelper * Member Type: Facilitator * Parameters: None * Return Value: void * Purpose: Prints in the tree shape by using queues. * The output result will resemble a tree structure **/ template <typename treeEltType> void BinaryTree<treeEltType>:: treePrintHelper(TreeNode<treeEltType> *root) const { queue<TreeNode<treeEltType> *> Q; // A dummy node to mark end of level TreeNode<treeEltType> *dummy = new TreeNode<treeEltType>(-1); if(root) { cout << root->info << " " << endl; Q.push(root->left); Q.push(root->right); Q.push(dummy); } TreeNode<treeEltType> *t = root; while(!Q.empty()) { t = Q.front(); Q.pop(); if(t == dummy) { if (!Q.empty()) Q.push(dummy); cout << endl; } else if(t) { cout << t->info << " "; Q.push(t->left); Q.push(t->right); } } } template class BinaryTree<int>; <file_sep>/csc570/DataMineTensorFlow/CSC458DataMineI/encode ''' # Author: <NAME> # File Name: csvEncode.py # Date: 03/20/2018 # Purpose: To take a .csv file and turn all nominal (categorical) column # data into numerical (continous) column data through the use of # label encoding in the sklearn preprocessing module. # One file argument is to be entered and a new file will be # created where all nominal columns are changed to numeric # columns. Original files are unchanged by default. ''' from __future__ import absolute_import from __future__ import print_function import sys import time import argparse import numpy as np import pandas as pd from pathlib import Path from sklearn import preprocessing """Get the default name for the .csv file to create""" """Default name only applies when no csv name argument is given""" def _defaultName(): args = parser.parse_args(sys.argv[1:]) if args.dest_dir == '': return args.file_dir.replace('.csv', '_e.csv') else: return args.dest_dir parser = argparse.ArgumentParser() parser.add_argument('--file_dir', default='', type=str, help="The location and name of the file to encode.") parser.add_argument('--dest_dir', default='', type=str, help="The location and name for the newly created encoded file.") parser.add_argument('--header', default=0, type=int, help="Row number in file_dir to use as column names, use -1 for no headers.") """Checks the input file for correct format (.csv) and that it exists""" def _checkArgs(args): argFile = args.file_dir assert argFile.find('.csv') != -1, ("Only .csv files can be encoded.") file = Path(argFile) assert (file.is_file()), ("File '%s' does not exist." % argFile) return argFile """Read the file with either no header or the position of the file header""" def _input_fn(csv_file, args): if args.header < 0: return pd.read_csv(csv_file, header=None) else: return pd.read_csv(csv_file, header=args.header) """Checks to see if the output file is of correct format and existance""" """If the file exists the user will be prompted to overwrite the file""" def _output_fn(enc_data): dest_file = _defaultName() assert dest_file.find('.csv') != -1, ("Only .csv files can be created.") file = Path(dest_file) if file.is_file(): try: command = input("\nYou are about to overwrite another file! Continue? \ \nPRESS ENTER TO CONTINUE OR CTRL-C (^C) TO QUIT\n") print("Overwritting file " + dest_file) enc_data.to_csv(dest_file, header=False, index=False) except: print("\nQuitting.") sys.exit(0) else: enc_data.to_csv(dest_file, header=False, index=False) """Find the columns in the dataset that contain nominal (categroical) data""" """Return a 2d list containing the unique values for each nominal column""" """Return a list containing the column numbers of each nominal column""" def findNominalColumns(dataset): data = dataset.values uni_col = [] # List of nominal columns and their unique nominal values itr_col = [] # List of nominal columns numbers for i in range(len(data[0])): nom_col = [] if type(data[0][i]) is str: # Only work with nominal(str) data nom_col = data[:,i] # Get all row data for this column nom_col = np.unique(nom_col) # Get rid of all duplicates uni_col.append(list(nom_col)) # Convert nparry to list itr_col.append(i) return uni_col, itr_col """Encode each nominal column with an integer identifier based on their data""" """Return a pandas.DataFrame so that it can easily be written to csv""" def _encodeColumns(dataset, uni_col, itr_col): le = preprocessing.LabelEncoder() data = dataset.values # Get values so that data slices can be worked with for i in range(len(itr_col)): le.fit(uni_col[i]) # Fit the columns nominal values data[:,itr_col[i]] = le.transform(data[:,itr_col[i]]) # Column data->int return pd.DataFrame(data) def main(): start = time.time() # Time the program if conversion times need to be noted args = parser.parse_args(sys.argv[1:]) print("Authenticating file...") csv_file = _checkArgs(args) print("Reading from file " + str(args.file_dir)) dataset = _input_fn(csv_file, args) print("Searching for nominal columns...") uni_col, itr_col = findNominalColumns(dataset) print("Encoding Labels...") enc_data = _encodeColumns(dataset, uni_col, itr_col) print("Writing to file " + _defaultName()) _output_fn(enc_data) end = time.time() # Display that the program finished with this time print("Done at " + "{:.2f}".format(end-start) + " seconds.") if __name__ == '__main__': main() <file_sep>/csc520/assignment1/com/csc520Code/Deck.java package com.csc520Code; import java.util.List; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import com.csc520Code.Card; /* * Author: <NAME> * File Name: Deck.java * Creation Date: 01/30/2018 * Due Date: 02/12/2018 * Course: CSC 520 - Advanced Object Oriented Programming * Professor Name: Dr. Schwesinger * Assignment: #1 * Major: MS Software Development * University: Kutztown University of Pennsylvania * JavaDoc Link: http://csitrd.kutztown.edu/~ccarr419/csc520/assignment1/ */ /** * The deck is an object that holds Card objects. On instantiation, the deck * will hold every possible Card object that can be created and then be * randomly shuffled to ensure that the deck is not received in order. As far * as implementation-wise, the deck works similarly to a queue in that cards * are added to the end of deck and "should" be removed from the front of the * deck. Although a card from anywhere in the deck, it was intended as well * as advised for a card to only be removed from the front. As such, users * cannot see the positions of certain cards within the deck because like in * reality, one cannot see the position of a specific card within a deck. */ public class Deck { private Card[] cards; //Array to hold the deck's cards private int cardCount; //Number of cards in the deck //Number of cards allowed in the deck private static final int D_LIMIT = 52; //(Card.R_LIMIT * Card.S_LIMIT); /** * A constructor that creates every possible combination of cards and * inserts them into the deck Card array. The deck is then shuffled so * the deck will not be in order on instantiation. */ public Deck() { cardCount = 0; //Starting off with no cards in the deck cards = new Card[D_LIMIT]; //Allocate the deck Card array //Create every card by going through each possible suit and rank //Numbers come from Card.S_LIMIT and Card.R_LIMIT for(int i = 0; i < 4; i++) { for(int j = 0; j < 13; j++) { addCard(new Card(j, i)); } } shuffle(); //Assert that the deck will not be in order } /** * Gets the deck Card array index for a given Card parameter. This function * is private since the user should not need to know the position of any * card in the deck. Intended for use in checking if the deck Card array * contains a specific Card. * @param c the Card to find the index for * @return the index of the Card if found, -1 if not found */ private int getIndex(Card c) { for(int i = 0; i < cardCount; i++) { if(cards[i].compareTo(c) == 0) { return i; //Card found at index i } } return -1; //Card is not in the deck } /** * Attempts to add a Card to the deck. If the Card was added successfully * the function will return true. If the deck already contains the card the * function will return false. The cardCount will be incremented on a * successful Card addition to the deck Card array. * @param c the Card to try and add to the deck * @return true if the card was added, false if not */ public boolean addCard(Card c) { if(getIndex(c) == -1) { //If the Card is not found in the deck, add it cards[cardCount] = c; //Append the Card to the end of the deck cardCount++; //Increment the total number of Cards in the deck return true; //Card was added succesfully } else { return false; } //Card exists already and was not added } /** * Attempts to remove a Card from the deck. If the Card was removed * successfully the function will return true. If the deck does not contain * the card the function will return false. The cardCount will be decremented * on a successful Card removal from the deck Card array. * @param c the Card to try and remove from the deck * @return true if the card was removed, false if not */ public boolean removeCard(Card c) { int tmp = getIndex(c); //Try and get the index of the Card if(tmp != -1) { //If the Card was found in the deck //Create a list so the some functions can be called for easier Card //removal and the rest of the deck will adjust accordingly. List<Card> tmpList = new ArrayList<Card>(toList()); tmpList.remove(tmpList.get(tmp)); //Assign the new deck with the removed Card to the deck's Card array cards = tmpList.toArray(cards); cardCount--; //Decrement the total number of Cards in the deck return true; //Card was removed successfully } else { return false; } //The card does not exist in the deck } /** * Shuffles the deck by randomly shifting the Cards positions in the deck * Card array. Uses Collections.shuffle() to do the heavy lifting. */ public void shuffle() { //Turn the Cards array into a List so Collections can shuffle it List<Card> tmpList = new ArrayList<Card>(toList()); Collections.shuffle(tmpList); cards = tmpList.toArray(cards); //Assign the newly shuffled deck } /** * Draws the top Card within the deck (i.e the Card at index zero), returns * it to the user, then removes it from the deck. If there are no cards * within the deck, null is returned instead. * @return the top Card in the deck */ public Card draw() { if(cardCount == 0) { return null; } //No Cards to draw else { Card drawnCard = cards[0]; //Get the top Card removeCard(drawnCard); //Remove the Card from the deck return drawnCard; //Give the Card to the user } } /** * Returns the List equivalent of the deck Card array. Useful for calling * functions that a normal array would not be able to do. * @return the deck Card array in abstract List form */ public List<Card> toList() { return Arrays.asList(cards); } }<file_sep>/csc136/project4/poly.h /* Filename: poly.h Author: <NAME> Updated By: <NAME> Course: CSC136 Assignment: Project 4 Description: Definition of the Polynomial Class This class provides the user the functionality of a polynomial, including the ability to add terms, evaluate, and multiply the coefficients. It also provides basic get and set functionalities. A function is provided to read terms from a file, and two associated non-member, non-friend stream operators are present for reading a Term and outputting the Polynomial in its entirety. */ #ifndef POLY_H #define POLY_H #include <iostream> #include <string> #include "LinkedList.h" #include "term.h" using namespace std; class Polynomial { public: ////// // Constructor ////// Polynomial(); /* Function: setTermList Member Type: Mutator Description: Makes TermList equal to another LinkedList Parameters: const LinkedList<Term> - input - list to be set equal to Returns: bool */ bool setTermList(const LinkedList<Term>&); /* Function: getTermList Member Type: Inspector Description: Returns the LinkedList private member Parameters: none Returns: TermList - LinkedList object */ const LinkedList<Term> getTermList() const; /* Function: operator () Member Type: Facilitator Description: Evaluate the polynomial for variable x Parameters: x - input - variable that is standing for value of x Returns: The polynomial evaluated for x */ double operator()(double x) const; /* Function: multiply Member Type: Mutator Description: Multiply each coefficient by the scalar arg factor Parameters: fact - input - variable that is multiplying against all the coefficents Returns: void */ void operator *=(float factor); /* Function: add Member Type: Mutator Description: Add a term to the polynomial Parameters: coefficent - input - the coefficent of the term being added exponent - input - the exponent of the term being added Returns: true if the term is added, false otherwise */ bool add(float coefficient, int exponent); /* Function: add Member Type: Mutator Description: Add a term to the polynomial Parameters: T - input - the Term being added Returns: true if the term is added, false otherwise */ bool add(Term &T); /* Function: readFile Member Type: Mutator Description: Loads up the terms from a user declared filename Parameters: file - input/output - stream variable Returns: void */ void readFile(ifstream &file); /* Function: removeTerm Member Type: Mutator Description: Checks if term is located within the LinkedList and if so removes the term from the LinkedList. Parameters: int - input - term exponent to be removed Returns: bool - true if term is found & removed - false if term is not found */ bool removeTerm(int); private: LinkedList<Term> TermList; }; /* Function: operator >> Description: Reads in a Term from a file Parameters: ifstream file - input/output - the input stream Polynomial - output only - the Polynomial that will hold the data read in Returns: ifstream */ ifstream &operator >>(ifstream &file, const Polynomial&); /* Function: operator << Description: Print a Polynomial to the screen Parameters: out - input/output - output stream P - input - The Polynomial to print Returns: void */ ostream &operator <<(ostream &out, const Polynomial &P); #endif <file_sep>/csc520/finalproj/src/com/library/business_layer/field_list/InternetAccount.java package com.library.business_layer.field_list; import java.io.Serializable; /** * The InternetAccount class represents a digital construct of a user account. * A InternetAccount Object contains the member's password, current session id * and unique identifier. Identifiers are meant to act similar to a primary key * in a database and as such should be unique. Also implements Serializable * so it can be serialized for later use. * BUSINESS LAYER CLASS */ public class InternetAccount implements Serializable { private int id; private String password; private long sessionid; /** * Contstructs InternetAccount Object by setting its attributes to a value. * @param i identifier * @param p password * @param s session id */ public InternetAccount(int i, String p, long s) { setId(i); setPassword(p); setSessionId(s); } /** * Gets the int identifier value for this Object. * @return id as int */ public int getId() { return id; } /** * Gets the password for the account as a String. * @return password String */ public String getPassword() { return password; } /** * Gets the session id for the account as a long. * @return session id long */ public long getSessionId() { return sessionid; } /** * Sets the value for the Object identifier. * @param i int to set id to */ public void setId(int i) { id = i; } /** * Sets the value for account password. * @param p String to set password to */ public void setPassword(String p) { password = p; } /** * Sets the value for account session id. * @param s long to set session id to */ public void setSessionId(long s) { sessionid = s; } }<file_sep>/csc552/project1/makefile # Author: <NAME> # File: makefile # Date Made: 02/13/2017 # Due Date: 02/17/2017 # School: Kutztown University # Class Num: CSC 552 # Class Name: Advanced Unix Programming # Semester: SPRING 2017 # Professor: Dr. Spiegel # Purpose: This makefile makes executables for every file in program 1. CC=/usr/bin/g++ DebugFlag=-g p1: p1.cpp countWords.cpp printWords.cpp $(CC) $(DebugFlag) -o p1 p1.cpp $(CC) $(DebugFlag) -o countWords countWords.cpp $(CC) $(DebugFlag) -o printWords printWords.cpp countWords: countWords.cpp $(CC) $(DebugFlag) -o countWords countWords.cpp printWords: printWords.cpp $(CC) $(DebugFlag) -o printWords printWords.cpp clean: \rm -rf *.o p1 <file_sep>/csc135/salesTax_ChristianCarreras.cpp /*This program takes the total colleted sales and calculates to find the product sales, county tax sales, state tax sales and total sales tax. Author: <NAME> Due Date: 10/2/2012*/ #include <iostream> #include <string> #include <iomanip> using namespace std; int main() { //Declaring constant values. const float PRODUCT_SALES = 1.06; const float COUNTY_TAX = 0.02; const float STATE_TAX = 0.04; const float TOTAL_TAX = 0.06; //Declaring variables. float total_collected, product_sales, county_sales_tax; float state_sales_tax, total_sales_tax; int year; //Declaring string variable. string month; //Ask user for month. cout << "\nPlease enter the current month: "; cin >> month; //Ask user for year. cout << "Please enter the current year: "; cin >> year; //Ask user for the total amount collected. cout << "Please enter the total amount collected: $"; cin >> total_collected; cout << endl; //Calculate taxes and sales. product_sales = total_collected / PRODUCT_SALES; county_sales_tax = product_sales * COUNTY_TAX; state_sales_tax = product_sales * STATE_TAX; total_sales_tax = product_sales * TOTAL_TAX; //Display information to user. cout.precision(2); //Changes the decimal precision to 2. cout << fixed; //Forces variables to be a fixed number. cout << left; //Changes orientation to left. cout << setw(8) << "Month:" << month << endl; cout << setw(8) << "Year:" << year << endl; cout << "---------------------------------\n"; cout << setw(22) << "Total Collected:" << "$" << total_collected << endl; cout << setw(22) << "Product Sales:" << "$" << product_sales << endl; cout << setw(22) << "County Sales Tax: " << "$" << county_sales_tax << endl; cout << setw(22) << "State Sales Tax:" << "$" << state_sales_tax << endl; cout << setw(22) << "Total Sales Tax:" << "$" << total_sales_tax << endl; cout << endl; return 0; } <file_sep>/csc552/project1/countWords.cpp /* Author: <NAME> * File: countWords.cpp * Date Made: 02/13/2017 * Due Date: 02/17/2017 * School: Kutztown University * Class Num: CSC 552 * Class Name: Advanced Unix Programming * Semester: SPRING 2017 * Professor: Dr. Spiegel * Purpose: This program opens a file given through the command-line and * counts how many words are in the file. It will return the * number of words that were in the file. */ #include <iostream> #include <fstream> #include <string> /* * Function Name: countTotalWords * Function Type: facilitator * Arguments: char** - input only * Return Value: int - the number of words in the file * Purpose: Opens the file entered in the command-line and counts all * the words in the file. */ int countTotalWords(char**); using namespace std; int main(int argc, char* argv[]) { return countTotalWords(argv); } //Attempts to open the file and count all the words. Close the file once done. int countTotalWords(char** argv) { string tempString; //Temporarily holds the string given by the input stream ifstream inf; //The input file int wordCounter = 0; inf.open(argv[1]); //Loop until the end of the file while(inf >> tempString) wordCounter++; inf.close(); //Returns the number of words in the file. return wordCounter; } <file_sep>/csc510/assignment5/fair.cpp /* Author: <NAME> Date: 12/04/17 Due Date: 12/12/17 File: fair.cpp Assignment: #5 Course: CSC510 Advanced Operating Systems Professor: Dr. Parson University: Kutztown University of Pennsylvania About: This file defines the code for the fair solution to the readers writers problem. Once compiled this project will also be able to simulate the fair solution. The fair solution uses a FIFO queue to sort incoming readers and writers along with mutexes to lock the critical section. However, it is more special than a basic FIFO queue in the fact that it allows for (along with most other R/W solutions) concurrent readers in the critical section. Thus, when a reader is in the critical section and a reader is waiting, the waiting reader will be able to enter the critical section along with other readers and so on. This concurrency allows for quite a remarkable speed-up with little worry of starvation. Behaves exactly like weak readers preference but with a queue. */ #include <iostream> #include <functional> //ref() function to wrap atomic variable parameters #include "readWriteSTM.h" using namespace std; /* Function Name: fair Function Type: mutator Parameters: thread - the calling thread and all its information Returns: int - the status of the state machine About: Evaluates the fair preference solution to the readers writers problem. This solution states that whoever arrives next gets to go next. This is the default algorithm. */ int readWriteSTM::fair(thread evalThread) { switch (currentStates[evalThread.tid]) { case STATE_INIT: //Initial state where freshly created threads start logMsg("init, ARRIVE", evalThread); currentStates[evalThread.tid] = STATE_WAIT; //Go wait to get in cs logMsg("init, DEPART", evalThread); return(KEEP_GOING); //All threads will wait their turn to go into the critical section //This state makes writers wait until all readers exit the critical //section and lets the next reader inline enter the critical section if //there is a reader in the critical section already case STATE_WAIT: //Wait here for the critical section to open logMsg("wait, ARRIVE", evalThread); //Be put in a waiting queue and wait your turn waitingQueue.push(evalThread.tid); //Do not go any further unless it is your turn while(waitingQueue.front() != evalThread.tid) {} logMsg("trying lock on mutex", evalThread, 1); if(evalThread.rw == READER) { //Readers Only //Make sure you are the only reader doing this lockMutex(rMtx, rCon, ref(rOpen)); // BEGIN READER COUNT CRITICAL SECTION if(++readersCount == 1) { //Increment the active reader count //Lock or wait for the cs lock if the first reader lockMutex(csMtx, csCon, ref(csOpen)); } // END READER COUNT CRITICAL SECTION unlockMutex(rMtx, rCon, ref(rOpen)); //Let other readers come in logMsg("acquired the mutex", evalThread, 1); waitingQueue.pop(); //Remove yourself from the waiting queue currentStates[evalThread.tid] = STATE_CRITSECT; } //Writers are non-concurrent and must have exclusive access else { //(evalThread.rw == WRITER) Writers Only lockMutex(csMtx, csCon, ref(csOpen)); //Lock or wait for the cs lock logMsg("acquired the mutex", evalThread, 1); //Going to the critical section, remove self from waiting queue waitingQueue.pop(); currentStates[evalThread.tid] = STATE_CRITSECT; } logMsg("wait, DEPART", evalThread); return(KEEP_GOING); //The critical section can concurrently hold multiple readers or //only one writer at a time case STATE_CRITSECT: logMsg("critSec, ARRIVE", evalThread); //If a reader is in the critical section, the critical section will //remained locked until all readers exit if(evalThread.rw == READER) { logMsg("reader in critical section, sleeping...", evalThread, 1); usleep(SLEEP_READER); //Sleep to represent doing something lockMutex(rMtx, rCon, ref(rOpen)); // BEGIN READER COUNT CRITICAL SECTION if(--readersCount == 0) { //Unlock the cs mutex if no more readers unlockMutex(csMtx, csCon, ref(csOpen)); } unlockMutex(rMtx, rCon, ref(rOpen)); //Let other readers in // END READER COUNT CRITICAL SECTION } //Writers are non-concurrent and must have exclusive access else { //(evalThread.rw == WRITER) logMsg("writer in critical section, sleeping...", evalThread, 1); usleep(SLEEP_WRITER); //Sleep to represent doing something unlockMutex(csMtx, csCon, ref(csOpen)); //Unlock the cs } //The task is done go to the terminate state currentStates[evalThread.tid] = STATE_TERMINATE; logMsg("critSec, DEPART", evalThread); return(KEEP_GOING); case STATE_TERMINATE: //End the current task for the thread logMsg("terminate, ARRIVE", evalThread); return(STOP_GOING); //Reached the accept state default: //Should never reach this state but for good measure logMsg("error: illegal state", evalThread); //I do no know how you got here but I am putting a stop to it! return(STOP_GOING); } } //Put other solution function declarations here so readWriteSTM.cpp can know //they exist when it selects which algorithm to use. Otherwise the program //will not compile because these functions will not be defined. int readWriteSTM::wrp(thread evalThread) {} int readWriteSTM::srp(thread evalThread) {} int readWriteSTM::wwp(thread evalThread) {} int readWriteSTM::swp(thread evalThread) {} int readWriteSTM::fcfs(thread evalThread) {} int main(int argc, char **argv) { readWriteSTM * stm = new readWriteSTM(); cout << "Fair Preference" << endl; stm->makingThreads(STM_FAIR); //Start the STM with Fair Preference return 0; } <file_sep>/csc402/assignment2/CheckingAccount.h /** A checking account has a limited number of free withdrawals. const int FREE_WITHDRAWALS = 3; //number of free withdrawals. const int WITHDRAWAL_FEE = 1; // transaction fee after 3 free withdrawals */ #ifndef CHECKINGACCOUNT_H #define CHECKINGACOUNT_H #include <iostream> #include "BankAccount.h" using namespace std; class CheckingAccount : public BankAccount { private: int withdrawals; /** Constructs a checking account with a zero balance. */ public: CheckingAccount(); CheckingAccount(int accNum, float thebalance); void setWithdrawals(int); int getWithdrawals(); void withdraw(double amount); void monthEnd(); }; #endif <file_sep>/csc135/painting_ChristianCarreras.cpp /*********************************************************************** This program uses pass by values and pass by references in seperate functions to create an interface that calculates the total price of the labor and price of paint per gallon involved in painting a space in square feet. The user enters the values of the amount of space to be painted and the price of the paint. Author: <NAME> Class: CSC 135 Due Date: 11/06/2012 **********************************************************************/ #include <iostream> #include <iomanip> using namespace std; //Seperate functions void displayInstructions(); void getSqft(float&sqft1); float getCostPaint(); void calcJob(float sqft2, float&job1); void calcCostPaint(float job2, float costpergallon2, float&paintcost1); void calcCostLabor(float job3, float&labor1); void calcTotalCost(float paintcost2, float labor2, float&totalcost1); //Main function int main() { //Variables float sqft, costpergallon, job, paintcost, labor, totalcost; //Function calls displayInstructions(); getSqft(sqft); costpergallon = getCostPaint(); if(costpergallon < 10) //If the entered amount for paint is less than $10. { cout << "Cost of paint per gallon cannot be less than $10.\n\n"; } else //Everything else { //More function calls calcJob(sqft, job); calcCostPaint(job, costpergallon, paintcost); calcCostLabor(job, labor); calcTotalCost(paintcost, labor, totalcost); //Display information cout << setprecision(2) << fixed; cout << "Square feet:\t" << sqft << endl; cout << "Paint cost:\t$" << paintcost << endl; cout << "Labor cost:\t$" << labor << endl; cout << "Total cost:\t$" << totalcost << endl << endl; } return 0; } /**************************************** This function displays the instructions for the user to follow. ****************************************/ void displayInstructions() { cout << "\n\t========================================\t\n"; cout << "\t\tPainting Cost Calculator\t\t\n"; cout << "\t========================================\t\n"; cout << "This program will calculate the total cost of a space to be\n"; cout << "painted based on the cost of the paint per gallon and the labor\n"; cout << "required to complete the job. The amount of space to be painted\n"; cout << "is to be entered in square feet and the cost per gallon of paint\n"; cout << "cannot be less than $10.\n\n"; } /************************************* This function asks the user for the amount of square feet to be painted. *************************************/ void getSqft(float&sqft1) { cout << "How many square feet of space needs to be painted? "; cin >> sqft1; } /**************************************** This function gets the cost of paint per gallon and returns the value back to the main function. ****************************************/ float getCostPaint() { float costpergallon1; cout << "What is the price of the paint per gallon? $"; cin >> costpergallon1; cout << endl; return costpergallon1; } /**************************************** This function calculates the number for future functions. ****************************************/ void calcJob(float sqft2, float&job1) { job1 = sqft2/115; } /*************************************** This function calculates the number of gallons required for the number of square feet entered. ***************************************/ void calcCostPaint(float job2, float costpergallon2, float&paintcost1) { paintcost1 = job2*costpergallon2; } /*************************************** This function calculates the number of hours required in labor for the amount of square feeet entered. ***************************************/ void calcCostLabor(float job3, float&labor1) { labor1 = job3*(8*18.00); } /**************************************** This program adds the price for gallons of paint used and the price for labor hours for a total price. ****************************************/ void calcTotalCost(float paintcost1, float labor2, float&totalcost1) { totalcost1 = paintcost1 + labor2; } <file_sep>/csc310/README.txt CSC 310 - Programming Languages Dr. <NAME> Kutztown University Spring 2015 This course deals with the main constructs of contemporary programming languages and the tools necessary for the critical evaluation of existing and future programming languages. It provides an in-depth discussion of programming language structures, presents a formal method of describing syntax, and introduces approaches to lexical and syntactic analysis. <file_sep>/csc520/assignment1/com/csc520Code/Hand.java package com.csc520Code; import java.util.List; import java.util.Arrays; import java.util.ArrayList; import com.csc520Code.Card; /* * Author: <NAME> * File Name: Hand.java * Creation Date: 01/30/2018 * Due Date: 02/12/2018 * Course: CSC 520 - Advanced Object Oriented Programming * Professor Name: <NAME> * Assignment: #1 * Major: MS Software Development * University: Kutztown University of Pennsylvania * JavaDoc Link: http://csitrd.kutztown.edu/~ccarr419/csc520/assignment1/ */ /** * The hand object behaves similarly to the deck object with the exception that * that there should be more transparency since users will be interacting * with hands directly. Hands can be sorted at whim by the user if they feel * so inclined. The hand can also be searched by the user for a certain Card. * Hands are initialized as empty and must have Cards added to it. */ public class Hand { private Card[] cards; //Array to hold the hand's Cards private int cardCount; //Number of Cards in the hand private static final int H_LIMIT = 5; //Number of Cards allowed in the hand /** * A basic constructor to initialize the hand's Card array as empty. */ public Hand() { cards = new Card[H_LIMIT]; } /** * Gets the hand Card array index for a given Card parameter. This function * is private since the user should not need to know the position of any * card in the hand. Intended for use in checking if the hand Card array * contains a specific Card. * @param c the Card to find the index for * @return the index of the Card if found, -1 if not found */ private int getIndex(Card c) { for(int i = 0; i < cardCount; i++) { if(cards[i].compareTo(c) == 0) { return i; //Card found at index i } } return -1; //Card is not in the hand } /** * Attempts to add a Card to the hand. If the Card was added successfully * the function will return true. If the hand already contains the card the * function will return false. The cardCount will be incremented on a * successful Card addition to the hand Card array. * @param c the Card to try and add to the hand * @return true if the card was added, false if not */ public boolean addCard(Card c) { if(getIndex(c) == -1) { //If the Card is not found in the hand, add it cards[cardCount] = c; //Append the Card to the end of the hand cardCount++; //Increment the total number of Cards in the hand return true; //Card was added succesfully } else { return false; } //Card exists already and was not added } /** * Attempts to remove a Card from the hand. If the Card was removed * successfully the function will return true. If the hand does not contain * the card the function will return false. The cardCount will be decremented * on a successful Card removal from the hand Card array. * @param c the Card to try and remove from the hand * @return true if the card was removed, false if not */ public boolean removeCard(Card c) { int tmp = getIndex(c); //Try and get the index of the Card if(tmp != -1) { //If the Card was found in the hand //Create a list so the some functions can be called for easier Card //removal and the rest of the hand will adjust accordingly. List<Card> tmpList = new ArrayList<Card>(toList()); tmpList.remove(tmpList.get(tmp)); //Assign the new hand with the removed Card to the hand's Card array cards = tmpList.toArray(cards); cardCount--; //Decrement the total number of Cards in the hand return true; //Card was removed successfully } else { return false; } //The card does not exist in the hand } /** * A user version of getIndex() that returns a boolean instead of a integer. * @param c the Card to check for in the hand * @return true if the Card is in the hand, false if not */ public boolean contains(Card c) { if(getIndex(c) != -1) { return true; } else { return false; } } /** * Sorts the hand by the natural-order of the Card object. Thus the hand * will be sorted by suit first, then rank. Array.sort() does all the work. * If the deck is less than or equal to one, the hand will not be sorted. */ public void sortHand() { if(cardCount <= 1) { return; } else { Arrays.sort(cards); } } /** * Returns the List equivalent of the hand Card array. Useful for calling * functions that a normal array would not be able to do. * @return the hand Card array in abstract List form */ public List<Card> toList() { return Arrays.asList(cards); } }
e16058f3eb62ffe6abaf8595910585028c5873be
[ "Swift", "Makefile", "Java", "Python", "Text", "C#", "PHP", "C++" ]
289
C++
ccarr419/Academic-Projects
71967751b4233f57e858944562db38cf506fc5d3
6b38c7f077cd49c1c86d000b1e47e1c8446ba631
refs/heads/main
<file_sep><?php echo "tes"; ?>
aae5160f3440ecc5637f1ce1cbcbbb951fb307ad
[ "PHP" ]
1
PHP
tesastor25/landing-page
0d7f062d2275c454e594729a1197f82224078f67
4f487c046256cda081921107ec8ecdb225989d2c
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> void showLetterGrade(float); int main() { float score; printf("Enter your score: "); scanf("%f",&score); showLetterGrade(score); return 0; } void showLetterGrade(float score) { if(score >= 90.0) { printf("A"); } else if(score >= 80.0) { printf("B"); } else if(score >= 70.0) { printf("C"); } else if(score >= 60.0) { printf("D"); } else if(score < 60.0) { printf("F"); } }
344fe3042c58ad899949ed23e1885744f82fa6fa
[ "C" ]
1
C
my668618/HW5
abc26728d2921e3c5ab3f850e49cfc610326bf44
a90fd54e6087922a8e115d4ed7d6eadab187a3dd
refs/heads/master
<repo_name>mhndsbgyn/blog-react<file_sep>/src/App.js import React, {useState, useEffect} from 'react'; import './App.css'; import { BrowserRouter as Router, Switch, Route, Link} from "react-router-dom"; import Header from './components/header'; import Details from './pages/details'; import AddBlog from './pages/addBlog'; import Category from './pages/category'; import axios from 'axios' function App() { const[blogs, setBlog]=useState([]) const[error, setError]=useState(null) const[loading,setLoading]=useState(true) useEffect(() => { async function fetchData(){ setLoading(true) try{ const result= await axios.get("http://localhost:1337/blogs") setBlog(result.data) setLoading(false) } catch{ setError(error) setLoading(false) } } fetchData() },[]) return ( <div className="App"> <Router> <Header></Header> <Switch> <Route exact path="/"> { blogs.sort((a,b)=> b.created_at.localeCompare(a.created_at)).map(blog=>{ return( <div style={{width:"60%", margin:"auto", padding:"20px", marginBottom:"15px", border:"1px solid coral", borderRadius:"10px"}} key={blog.id}> <h3> {blog.title} </h3> <h5>{blog.author}</h5> <p>{blog.body.substring(0,70)}...</p> <Link to={`/details/${blog.id}`}> <button>Devamı için Tıklayınız</button> </Link> </div> ) }) } </Route> <Route path="/details/:id"> <Details/> </Route> <Route path="/addblog"> <AddBlog/> </Route> <Route path="/category/:id"> <Category/> </Route> </Switch> </Router> </div> ); } export default App; <file_sep>/src/pages/details.js import React, {useState, useEffect} from 'react' import axios from "axios" import { useParams } from "react-router-dom" function Details() { const {id}=useParams() const[result,setResult]=useState() const[error, setError]=useState(null) const[loading,setLoading]=useState(true) useEffect(() => { async function fetchData(){ setLoading(true) try{ const res= await axios.get(`http://localhost:1337/blogs/${id}`) setResult(res.data) setLoading(false) } catch{ setError(error) setLoading(false) } } fetchData() },[id]) if(loading) return <p>Loading</p> if(error) return <p>Error</p> return ( <div> <div style={{width:"60%", margin:"auto", padding:"20px", marginBottom:"15px", border:"1px solid coral", borderRadius:"10px"}} key={result.id}> <h3> {result.title} </h3> <h5>{result.author}</h5> <p>{result.body}</p> </div> </div> ) } export default Details <file_sep>/README.md Merhaba, Bu projede basit blog tarzı notlarımı anlık yazıp paylaşabileceğim bir react projesi oluşturmayı hedefliyorum. Projenin backend kısmı strapi üzerinden yönetiliyor. Burada strapi kullanmamın temel sebebi ise api kısmında çok fazla işlem yapmayacağım ve çok fazla data toplamayacağım için, yine veritabanımda sadece 2-3 tablo bulunmakta olduğu için strapi bana kolaylık sağlıyor. Kod yapısında Redux, Hook(useState, useEffect), Route(sayfalara url atamak için), Axios(verileri çekmek için) kullanıldı. Bu proje de destek aldığım yer, Udemy platformundaki İsa Acarer eğitmenin React eğitim serisi oldu. Proje basit olarak şunlardan oluşuyor: --Anasayfa da son eklenen blog yazısına göre bloglar listeleniliyor. Blogların devamını okumak için bir detay sayfasına yönlendiriliyor. Bloglar başlık, açıklama, yazar ve yayınladığı tarihten oluşuyor.Bu arada dileyen kullanıcı kategori bazlı arama yapabilir veya blog ekleme kısmından anlık blog ekleyip yayınlayabilir. Projeye Eklemek İstediklerimi Buraya Not Alıyorum Arada Güncellemek için uğrayacağım; 1-)Blogların gösterildiği ksııma search butonu eklemek, burada filtreleme ile arama yapılmasını sağlamak. 2-)Bloglara resim detayı eklemek. 3-)Gece-gündüz modu seçeneği getirmek. 4-)Favorilere ekleme kısmını entegre etmek. 5-)Blog yazılarına yorum yapma, beğenme butonu eklemek. 6-)Bir blog yazısının kaç kere okunduğu bilgisini göstermek. 7-)Facebook, Twitter gibi sosyal mecralar için paylaşım butonu koymak.
aa40784e57ec21ac3d2bce7eb076271704880d22
[ "JavaScript", "Markdown" ]
3
JavaScript
mhndsbgyn/blog-react
8e43c39849ed9e1303ebf782d9f544dbd7d5f645
b9328aac7f434248490954a6fa56c834230d068e
refs/heads/ember-cli
<repo_name>ember-cli/broccoli<file_sep>/test/builder_test.js var test = require('tap').test var broccoli = require('..') var Builder = broccoli.Builder var RSVP = require('rsvp') var heimdall = require('heimdalljs') RSVP.on('error', function(error) { throw error }) function countingTree (readFn, description) { return { read: function (readTree) { this.readCount++ return readFn.call(this, readTree) }, readCount: 0, description: description, cleanup: function () { var self = this return RSVP.resolve() .then(function() { self.cleanupCount++ }) }, cleanupCount: 0 } } test('Builder', function (t) { test('core functionality', function (t) { t.end() test('build', function (t) { test('passes through string tree', function (t) { var builder = new Builder('someDir') builder.build().then(function (hash) { t.equal(hash.directory, 'someDir') t.end() }) }) test('calls read on the given tree object', function (t) { var builder = new Builder({ read: function (readTree) { return 'someDir' } }) builder.build().then(function (hash) { t.equal(hash.directory, 'someDir') t.end() }) }) t.end() }) test('readTree deduplicates', function (t) { var subtree = new countingTree(function (readTree) { return 'foo' }) var builder = new Builder({ read: function (readTree) { return readTree(subtree).then(function (hash) { var dirPromise = readTree(subtree) // read subtree again t.ok(dirPromise.then, 'is promise, not string') return dirPromise }) } }) builder.build().then(function (hash) { t.equal(hash.directory, 'foo') t.equal(subtree.readCount, 1) t.end() }) }) test('cleanup', function (t) { test('is called on all trees called ever', function (t) { var tree = countingTree(function (readTree) { // Interesting edge case: Read subtree1 on the first read, subtree2 on // the second return readTree(this.readCount === 1 ? subtree1 : subtree2) }) var subtree1 = countingTree(function (readTree) { return 'foo' }) var subtree2 = countingTree(function (readTree) { throw new Error('bar') }) var builder = new Builder(tree) builder.build().then(function (hash) { t.equal(hash.directory, 'foo') builder.build().catch(function (err) { t.equal(err.message, 'The Broccoli Plugin: [object Object] failed with:') return builder.cleanup() }) .then(function() { t.equal(tree.cleanupCount, 1) t.equal(subtree1.cleanupCount, 1) t.equal(subtree2.cleanupCount, 1) t.end() }) }) }) t.end() }) }) test('tree graph', function (t) { var parent = countingTree(function (readTree) { return readTree(child).then(function (dir) { return new RSVP.Promise(function (resolve, reject) { setTimeout(function() { resolve('parentTreeDir') }, 30) }) }) }, 'parent') var child = countingTree(function (readTree) { return readTree('srcDir').then(function (dir) { return new RSVP.Promise(function (resolve, reject) { setTimeout(function() { resolve('childTreeDir') }, 20) }) }) }, 'child') var timeEqual = function (a, b) { t.equal(typeof a, 'number') // do not run timing assertions in Travis builds // the actual results of process.hrtime() are not // reliable if (process.env.CI !== 'true') { t.ok(a >= b - 5e7 && a <= b + 5e7, a + ' should be within ' + b + ' +/- 5e7') } } var builder = new Builder(parent) builder.build().then(function (hash) { t.equal(hash.directory, 'parentTreeDir') var parentBroccoliNode = hash.graph t.equal(parentBroccoliNode.directory, 'parentTreeDir') t.equal(parentBroccoliNode.tree, parent) t.equal(parentBroccoliNode.subtrees.length, 1) var childBroccoliNode = parentBroccoliNode.subtrees[0] t.equal(childBroccoliNode.directory, 'childTreeDir') t.equal(childBroccoliNode.tree, child) t.equal(childBroccoliNode.subtrees.length, 1) var leafBroccoliNode = childBroccoliNode.subtrees[0] t.equal(leafBroccoliNode.directory, 'srcDir') t.equal(leafBroccoliNode.tree, 'srcDir') t.equal(leafBroccoliNode.subtrees.length, 0) var json = heimdall.toJSON() t.equal(json.nodes.length, 4) var parentNode = json.nodes[1] timeEqual(parentNode.stats.time.self, 30e6) var childNode = json.nodes[2] timeEqual(childNode.stats.time.self, 20e6) var leafNode = json.nodes[3] timeEqual(leafNode.stats.time.self, 0) for (var i=0; i<json.nodes.length; ++i) { delete json.nodes[i].stats.time.self } t.deepEqual(json, { nodes: [{ _id: 0, id: { name: 'heimdall', }, stats: { own: {}, time: {}, }, children: [1], }, { _id: 1, id: { name: 'parent', broccoliNode: true, }, stats: { own: {}, time: {}, }, children: [2], }, { _id: 2, id: { name: 'child', broccoliNode: true, }, stats: { own: {}, time: {}, }, children: [3], }, { _id: 3, id: { name: 'srcDir', broccoliNode: true, }, stats: { own: {}, time: {}, }, children: [], }], }) t.end() }) }) test('string tree callback', function (t) { var builder = new Builder('fooDir') builder.build(function willReadStringTree (dir) { t.equal(dir, 'fooDir') t.end() }) }) t.end() })
4396311ee7aaf8ff4dac02edb79316e637ba30db
[ "JavaScript" ]
1
JavaScript
ember-cli/broccoli
deab2f08aa7a61f060432c07c7630518ced64eaf
a3c74a02c3a60cf9e3c28697fc5f4ea9fcc695b4
refs/heads/master
<repo_name>Poonam2801/MemorablePlaces<file_sep>/app/src/main/java/com/example/poonamgupta2801/memorableplaces/MainActivity.java package com.example.poonamgupta2801.memorableplaces; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate ( savedInstanceState ); setContentView ( R.layout.activity_main ); ListView listView=(ListView)findViewById ( R.id.memorablePlaces ); final ArrayList<String> placesList= new ArrayList<> ( ); placesList.add ( "Add a new place" ); ArrayAdapter arrayAdapter= new ArrayAdapter ( getApplicationContext (),android.R.layout.simple_list_item_1, placesList ); listView.setAdapter ( arrayAdapter ); listView.setOnItemClickListener ( new AdapterView.OnItemClickListener () { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText ( MainActivity.this, position, Toast.LENGTH_SHORT ).show (); Intent intent = new Intent ( getApplicationContext (), MapsActivity.class ); intent.putExtra("PlaceNumber",position ); startActivity ( intent ); } } ); } }
d58420738a67b9d8fbe2c60bff23ec0d9eabbeea
[ "Java" ]
1
Java
Poonam2801/MemorablePlaces
24dded9f70f4a659bc37f7741a4f95750c60ba5c
7ff86e808617cd02eb13f09330c2d659ca079715
refs/heads/master
<repo_name>Robert-Wildgoose/Py_Goose<file_sep>/README.md # Py_Goose Author - <NAME> # Description Pygoose was a first year university project which as it stands is a custom build python IDE allowing the user to write and execute python code. ## Installation In order to run pygoose you will simply need to have Python 2.5 installed on your computer and then simply run the file. ## Usage TODO: Write usage instructions ## Contributing 1. Fork it! 2. Create your feature branch: `git checkout -b my-new-feature` 3. Commit your changes: `git commit -am 'Add some feature'` 4. Push to the branch: `git push origin my-new-feature` 5. Submit a pull request. <file_sep>/Pygoose.py from tkinter import * #Assignment Submission #N0507072 - <NAME> #Program Name PyGoose from subprocess import Popen, PIPE, call from tkinter.filedialog import * class Application(Frame): def __init__(self,master): super(Application,self).__init__(master) self.grid() self.create_widgets() menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="New",command=self.new_file) filemenu.add_separator() filemenu.add_command(label="Open",command=self.file_open) filemenu.add_command(label="Save As",command=self.file_save) filemenu.add_separator() filemenu.add_command(label="Exit",command=self.do_exit) def do_exit(self): root.destroy() def new_file(self): self.content.delete(0.0,END) self.output.delete(0.0,END) self.error.delete(0.0,END) def file_save(self): fout = asksaveasfile(mode='w', defaultextension=".py") programcode = str(self.content.get(0.0,END)) fout.write(programcode) fout.close() def file_open(self): initial_dir = "C:\Temp" mask = \ [("Text and Python files","*.txt *.py *.pyw"), ("HTML files","*.htm"), ("All files","*.*")] fin = askopenfile(initialdir=initial_dir, filetypes=mask, mode='r') text = fin.read() if text != None: self.content.delete(0.0, END) self.content.insert(END,text) def create_widgets(self): self.contentlabel=Label(self,text="Welcome To PyGoose") self.contentlabel.grid(row=0,column=0) self.content=Text(self,width=40,height=20) self.content.grid(row=1,column=0) self.output=Text(self,width=40,height=6,fg="blue") self.output.grid(row=2,column=0) self.error=Text(self,width=40,height=6,fg="red") self.error.grid(row=3,column=0) self.test=Button(self,text="Test Code",width=40,command=self.test) self.test.grid(row=4,column=0) def test(self): self.output.insert(0.0,"\n>>------END------<<\n") self.error.insert(0.0,"\n>>------END------<<\n") content=self.content.get(0.0,END) filename="default.py" text_file=open(filename,"w") text_file.write(content) text_file.close() pipe = Popen('python default.py', stdout=PIPE,stderr=PIPE) output=pipe.communicate() self.output.insert(0.0,output[0]) self.error.insert(0.0,output[1]) root = Tk() root.configure(background='black') root.title("Pygoose") #root.geometry("515x570") root.resizable(0,0) app=Application(root) #root.wm_iconbitmap('MyIcon.ico') root.mainloop()
57f4a499f3b275b9e0e6bdf515c4485d972b37c8
[ "Markdown", "Python" ]
2
Markdown
Robert-Wildgoose/Py_Goose
d3903e860d9a61bfc97793ae72d1587666c781dc
11b810f85b62bbc00a50f21240cec9c8f05cc3e6
refs/heads/master
<repo_name>nicjo814/docker-sickrage<file_sep>/services/sickrage/run #!/bin/bash umask 0002 exec /sbin/setuser abc python /app/sickrage/SickBeard.py --config=/config/config.ini --datadir=/config/data <file_sep>/README.md # docker-sickrage Sickrage Docker image <file_sep>/init/20_update.sh #!/bin/bash mkdir -p /app chown abc:abc /app if [ ! -d /app/sickrage/.git ]; then /sbin/setuser abc git clone https://github.com/SickRage/SickRage.git /app/sickrage else cd /app/sickrage /sbin/setuser abc git pull fi
865b793ca9b39bd1c63f8146479ceed86b7caeab
[ "Markdown", "Shell" ]
3
Shell
nicjo814/docker-sickrage
6a2165a033b3a7b840c199009db0cbfc03dcd3cf
cbfdf237fe1db03c332db82afa39b66e9a7bc940
refs/heads/master
<file_sep>production-tagger ================= Bash script that automates production tagging process and has a placeholder for executing a deploy command The git tag is in the format *production-yyyymmdd##* where *##* is a two digit number that is incremented for every additional deploy on the same day **Example** The first deploy on May 25th, 2014 would be tagged *production-20140525* then another deploy on the same day would be called *production-2014052501* and then *production-2014052502* after that. <file_sep>#! /bin/bash read -p "Are you sure you want to deploy? " -n 1 -r if [[ $REPLY =~ ^[Yy]$ ]] then # create current days tagname tag="production-`date "+%Y%m%d"`" # find how many other releases occurred today matching_tag_count=`git tag | grep $tag | wc -l` tag_suffix="" # if other releases then create the suffix to mark the current release if [ $matching_tag_count -gt 0 ] then tag_suffix=`printf "%02s" $matching_tag_count` fi tag=$tag$tag_suffix # make sure everyone looks right to the user echo "\nPrevious tag is: `git tag | tail -n 1`" echo "\nNew tag is: $tag" read -p "Is this correct? " -n 1 -r if [[ $REPLY =~ ^[Yy]$ ]] then `git tag $tag` `git push origin $tag` read -p "Push to production environment? " -n 1 -r if [[ $REPLY =~ ^[Yy]$ ]] then # optional deploy code e.g. fab -H $PROD_ENV deploy_code fi fi fi
82eefe10fee80b6815a2c73a74d3bb93363e6063
[ "Markdown", "Shell" ]
2
Markdown
ScottKelly/production-tagger
4da8e44db7c818d0617b1106210c7acbe1dbc445
0b96d1f0d1c2eb612f335d70b1f9a305965be534
refs/heads/main
<file_sep>// Init Weather Class const wea = new weather ; //Init UI Class const ui = new UI ; //On Submit Button const frm= document.getElementById('frm1'); frm.addEventListener('submit', (e) => { e.preventDefault(); const val = document.getElementById('t1').value if(val !== ''){ wea.getCity(val) .then(data => { if(data.city.message === 'city not found'){ //alert ui.showalert(); }else{ //UI Display console.log(data); ui.showcity(data.city.weather); ui.showtemp(data.city.main); ui.showtable_sunrise(data.city.sys, data.city.main, data.city.wind, data.city); // ui.showtable_temp(data.city.main) document.getElementById('t1').value = '' } }); } });<file_sep>class weather { constructor(){ this.appid = '2a343257f8c94d8b908b1995aa9cd2be'; } async getCity(cityname){ const cityResponse = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${cityname}&appid=${this.appid}`) const city = await cityResponse.json(); return { city } } }<file_sep>class UI { constructor(){ this.city = document.getElementById('city') this.txt = document.getElementById('t1') } //Alert Box Funtion showalert(){ const alert = document.getElementById('alert'); alert.className = 'alert' alert.style.display = 'table' setTimeout(()=>{ alert.style.display = 'none'; console.clear(); },3500) alert.classList = 'alert' } //Clear Text box cleartext(){ this.txt.innerHTML = ''; } //Show City Name and Tempture showcity(data){ let op = ''; const cityname = this.txt.value; data.forEach(i => { op += ` <div class="cityname" id="cityname" > <h3>${cityname}</h3> </div> <div class="desc" id="desc"> <h4>${i.description}</h4> </div> <div class="temp" id="temp"></div> <div class="table" id="table"></div> `; }); this.city.className = 'city' this.city.innerHTML = op ; } //Show temprature showtemp(data){ let op =''; op += `<h1 class="temp-head">${Math.round(data.temp - 273)}&degC</h1>`; //converting to celcius document.getElementById('temp').innerHTML = op ; } //Show Table //Show Sunrise and Sunset showtable_sunrise(data, data1, data2, data3){ let op = ''; var dt_sunrise = new Date(data.sunrise * 1000) var hours_sunrise = dt_sunrise.getHours().toString().padStart(2,0) var min_sunrise = dt_sunrise.getMinutes().toString().padStart(2,0) var sec_sunrise = dt_sunrise.getSeconds().toString().padStart(2,0) var dt_sunset = new Date(data.sunset * 1000) var hours_sunset = dt_sunset.getHours().toString().padStart(2,0) var min_sunset = dt_sunset.getMinutes().toString().padStart(2,0) var sec_sunset = dt_sunset.getSeconds().toString().padStart(2,0) op += `<table id="tbl"> <tr><th>Sunrise</th><th>sunset</th></tr> <td>${hours_sunrise}: ${min_sunrise}: ${sec_sunrise}</td> <td>${hours_sunset}: ${min_sunset}: ${sec_sunset}</td> <tr><th>Minimum Tempture</th><th>Maximum Tempture</th></tr> <td>${Math.round(data1.temp_min - 273)}&degC</td> <td>${Math.round(data1.temp_max - 273)}&degC</td> <tr><th>Humidity</th><th>Feels Like</th></tr> <td>${data1.humidity}%</td> <td>${Math.round(data1.feels_like - 273)}&degC</td> <tr><th>Wind</th><th>Visibility</th></tr> <td>${data2.speed * (60*60)/1000}KM/H</td> <td>${data3.visibility}</td> </table>`; document.getElementById('table').innerHTML = op } }
1d9c4b907d5359547d7959691993692e07404755
[ "JavaScript" ]
3
JavaScript
Xfordation/Weather-Application-Using-Vanilla-JS-with-the-Help-of-Open-Weather-Maps-V1.0
b51f8fb50a3ab8d6223a4ac1c1f73a80b93f7371
f606c1457f2581754c61b47bcd3f8e43f5464da6
refs/heads/master
<repo_name>celestialized/next-website<file_sep>/components/faqs/MarketplaceFaqs.js import React from 'react' import Accordion from 'react-bootstrap/Accordion' import Card from "react-bootstrap/Card"; import Link from 'next/link' const MarketplaceFaqs = () => <Accordion defaultActiveKey="0"> <Card> <Accordion.Toggle as={Card.Header} eventKey='0'> <h5 className="faq_head"> Do I have to use Cashfree payment gateway to use Marketplace Settlements? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='0'> <Card.Body> <div className="faq_content"> <p>It is strongly recommended to <Link href="https://docs.cashfree.com/docs/ces/guide/#pg-integration"><a target="_blank">integrate Cashfree payment gateway for collections along with Marketplace Settlements</a></Link>. This ensures payments are assigned to vendors automatically and settled faster. It is also easier to handle refunds. However, vendor settlements can be carried out for transactions captured through any other medium like cash on delivery or an alternate payment provider. </p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='1'> <h5 className="faq_head"> How can I use Marketplace Settlements if I have a webstore on Shopify, Magento, WooCommerce, Martjack, Opencart etc? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='1'> <Card.Body> <div className="faq_content"> <p>All the payments completed via Cashfree payment gateway on your webstore will be available for disbursal via Cashfree's nodal account. These transactions need to be <a href="https://docs.cashfree.com/docs/ces/guide/#add-transaction" target="_blank">assigned to a vendor's ledger</a> - either manually or via the API. As you add transactions on Shopify, Magento or another platform, these will get assigned to your vendors and payment will be settled automatically.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='2'> <h5 className="faq_head"> Do I need a percentage vendor commission structure to split payments? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='2'> <Card.Body> <div className="faq_content"> <p>To split payments you can choose to have a pre-defined percentage for a vendor. It is also possible to specify the vendor commission as a percentage or fixed sum while <a href="https://docs.cashfree.com/docs/ces/guide/#add-transaction" target="_blank"> adding a transaction</a> and assigning it to a vendor.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='3'> <h5 className="faq_head"> Can I adjust refunds before splitting payments to vendor ? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='3'> <Card.Body> <div className="faq_content"> <p>Refunds can be managed by <a href="http://help.cashfree.com/en/articles/1957862-what-are-the-documents-required-at-the-time-of-sign-up" target="_blank"> adjusting the vendor ledger balance</a>. This will ensure the refund amount is adjusted from subsequent vendor settlements.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='4'> <h5 className="faq_head"> Do I need to have a nodal account to use Marketplace Settlements? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='4'> <Card.Body> <div className="faq_content"> <p>No. Marketplace Settlements lets you run a marketplace using a split payment gateway without having to open and operate a nodal account. Marketplace Settlements runs on Cashfree's managed nodal account and doesn't need you to worry about auditing and compliance.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='5'> <h5 className="faq_head"> How is vendor settlement managaged when there are multiple vendors linked to one transaction? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='5'> <Card.Body> <div className="faq_content"> <p>At the time of <a href="https://docs.cashfree.com/docs/ces/guide/#add-transaction" target="_blank"> adding a transaction</a>, you can assign the appropriate percentage of commission or set numeric commission amount. You can also <a href="https://docs.cashfree.com/docs/ces/guide/#attach-vendor" tagret="_blank">add additional vendors to an existing transaction</a> .</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='6'> <h5 className="faq_head"> Can I change the vendor assigned to a transaction? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='6'> <Card.Body> <div className="faq_content"> <p>Yes. Just like vendors can be attached to a transaction, vendors can also be removed from an <a href="https://docs.cashfree.com/docs/ces/guide/#detach-vendor" target="_blank"> existing transaction</a> . It is also possible to transfer the ledger balance of one vendor to another vendor.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='7'> <h5 className="faq_head"> Can I have different payout schedules for different vendors? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='7'> <Card.Body> <div className="faq_content"> <p>Yes, this is possible by modifying your account preferences. By default, pending vendor balances get settled automatically daily as per the regular settlement schedule. It is possible to disable automatic settlements and manaually make a settlement request for a particular vendor by mentioning the unique vendor id against the transfer amount. Cashfree checks for available vendor balance and if it's sufficient, we trigger the transfer to the recipients bank account. This process is synchronous i.e. you will receive the transfer status in the same API call. <a href="https://docs.cashfree.com/docs/ces/guide/#get-vendor-transfers">List of settlements can be retrieved here</a>.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='8'> <h5 className="faq_head"> Do new vendors get added instantly? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='8'> <Card.Body> <div className="faq_content"> <p>Yes, your account preferences can be setup to allow vendors to be added automatically with zero lag time. Please consult your account manager or email us at <EMAIL> to adjust your vendor activation period.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='9'> <h5 className="faq_head"> Where is the money kept for marketplace settlement? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='9'> <Card.Body> <div className="faq_content"> <p>Cashfree maintains centralized nodal accounts with our banking partners, a part of that will be maintained specifically for you. You need not worry about complying with the regulations as Cashfree takes care of it on your behalf.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='10'> <h5 className="faq_head"> What happens if a payment fails? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='10'> <Card.Body> <div className="faq_content"> <p>With our stable Payouts system, and intelligent rerouting algorithms, we ensure high transaction success rates. If in case payment fail due incorrect bank account detail, the money will be reversed to your account automatically and you will be notified. When you share correct bank account details we will trigger the payment again.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='11'> <h5 className="faq_head"> What if payment is made to the wrong vendor? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='11'> <Card.Body> <div className="faq_content"> <p>In such a case, you need to report the issue to us , you can drop a mail at <EMAIL>. Our team will adjust the appropriate amount in the next settlement cycle.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='12'> <h5 className="faq_head"> How do I track the vendor payments? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='12'> <Card.Body> <div className="faq_content"> <p>Using Cashfree advanced dashboard, you will be able to see status of vendor payment for any specific time period, you also get a account statement showing inwards payments through integrated Cashfree split payment gateway and details of outward payments via Cashfree marketplace settlement platform. If the sales are cash on delivery or you are using any other payment collection services , you can upload the transaction details and obtain a consolidated report of inward & outward payments.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='12'> <h5 className="faq_head"> How is the reporting handled? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='12'> <Card.Body> <div className="faq_content"> <p> We give you a daily consolidated report of split payments covering all outward payments at the end of the day.</p> </div> </Card.Body> </Accordion.Collapse> </Card> </Accordion>; export default MarketplaceFaqs; <file_sep>/README.md # cashfreewebsite Cashfree new landing page<file_sep>/pages/_document.js import Document, { Html, Head, Main, NextScript } from 'next/document' class MyDocument extends Document { static async getInitialProps(ctx) { const initialProps = await Document.getInitialProps(ctx) return { ...initialProps } } render() { return ( <Html> <Head> <meta name="theme-color" content="#36d1dc"/> <meta name="msapplication-navbutton-color" content="#36d1dc"/> <meta name="apple-mobile-web-app-status-bar-style" content="#36d1dc"/> <meta name="mobile-web-app-capable" content="yes"/> <meta name="apple-mobile-web-app-capable" content="yes"/> <meta name="google-site-verification" content="<KEY>" /> <link rel="icon" href="/favicon.ico" /> <link rel="apple-touch-icon" href="/favicon.ico" /> <link rel="icon" sizes="192x192" href="/favicon.ico" /> <link rel="icon" sizes="128x128" href="/favicon.ico" /> <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500,600,700,800|Open+Sans:300,400,600,700,800&display=swap" rel="stylesheet"></link> </Head> <body> <Main /> <NextScript /> </body> </Html> ) } } export default MyDocument<file_sep>/components/faqs/AutocollectFaqs.js import React from 'react' import Accordion from 'react-bootstrap/Accordion' import Card from "react-bootstrap/Card"; import Link from 'next/link' const AutoCollectFaq = () => <Accordion defaultActiveKey="0"> <Card> <Accordion.Toggle as={Card.Header} eventKey='0'> <h5 className="faq_head"> Is Autocollect same as cash management services provided by banks? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='0'> <Card.Body> <div className="faq_content"> <p>Cashfree Autocollect helps not only collect incoming bank transfers and UPI payments but also track and automatically reconcile payments. Also Cashfree Autocollect uses Virtual account and Virtual UPI IDs to collect payments, while most banks do not provide this facility.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='1'> <h5 className="faq_head"> What is a Virtual Account? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='1'> <Card.Body> <div className="faq_content"> <p>Virtual Account is a pass through account linked to a real bank account. The account is used to improve inward payments reconciliations. When a business receives payments from multiple sources and over a period of time, it gets difficult to track-who paid and which reason. This is usually reconciled manually by matching reference numbers in the bank statements with screenshots provided by a payer. By creating multiple virtual accounts mapped to the same account, it becomes possible to reconcile different incoming transactions into a bank account. With Cashfree autocollect- cash management services, you can generate any number of virtual accounts or UPI IDs for each payer or invoice and share a/c details while receiving payments. For repeated customers you can use a dedicated virtual account or UPI ID.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='2'> <h5 className="faq_head"> Can I hold money in a Virtual account? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='2'> <Card.Body> <div className="faq_content"> <p>No, it is not possible to hold money in the account. The payment so received eventually passes to the linked real bank account. The virtual account here is used only for payments reconciliation.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='3'> <h5 className="faq_head"> Some banks provide virtual bank account service, does cashfree have any advantage over such accounts? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='3'> <Card.Body> <div className="faq_content"> <p>For most banks, Virtual account payments can be received only using NEFT or RTGS; IMPS payments fail. The payments are not instant and restricted by banking hours. Using Cashfree cash management services solution, funds can be remitted to the virtual account through all bank transfer modes including UPI, IMPS, NEFT, RTGS and even Cheques. Cashfree also helps you create Virtual UPI IDs to accept payments through any UPI app such as WhatsApp or Google Pay. Moreover, for banks, reconciliation of payments happens through files sent over email, which is a once a day reconciliation process. For Cashfree, payment confirmation can be received through an API which is a real-time system update for receipt of funds. Cashfree also supports fully numeric virtual accounts unlike many banks which work on all bank interfaces -- alpha-numeric bank accounts provided by banks do not work on many of the older bank interfaces, especially on mobile.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='4'> <h5 className="faq_head"> Can I use the cash management services for outward payments as well? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='4'> <Card.Body> <div className="faq_content"> <p>No, however for automating outward payments you can use Cashfree Payouts. It is bulk disbursal solution that helps you send money to any UPI-BHIM ID, Paytm wallet, debit card or bank account. With inbuilt bank account verification feature, you can verify the bank account details and ensure that payments hit the right account. Checkout Payouts here.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='5'> <h5 className="faq_head"> Is any KYC required for creating a virtual account? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='5'> <Card.Body> <div className="faq_content"> <p>No there is no KYC required for creating the account. You can create any number of virtual accounts and virtual UPI IDs using cashfree cash management services.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='6'> <h5 className="faq_head"> Can I do payment gateway integration in Android & iOS apps? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='6'> <Card.Body> <div className="faq_content"> <p>Yes, You can use our library to integrate Cashfree Payment Gateway directly into your Android or iOS app using CashfreeSDK. CashfreeSDK has been designed to offload the complexity of handling and integrating payments in your app.</p> <ul> <li>Follow the link to check out CashfreeSDK <a href="https://docs.cashfree.com/docs/android/guide/" target="_blank">integration in Android.</a></li> <li>Follow the link to check out CashfreeSDK <a href="https://docs.cashfree.com/docs/ios/guide/" target="_blank">integration in iOS.</a></li> </ul> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='7'> <h5 className="faq_head"> I want to add Google Pay and other UPI options on the checkout page. How to do that? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='7'> <Card.Body> <div className="faq_content"> <p>At Cashfree, we provide widest range of UPI integrations including Webflow, intent flow, Google Pay integration and UPI SDK integration. You need to just share your requirement and our UPI payment experts will help you analyze the various UPI modes and recommend the best one as per your business requirement.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='8'> <h5 className="faq_head"> Is there any list of banned items for which Cashfree payment gateway services will not be available? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='8'> <Card.Body> <div className="faq_content"> <p>As a payments company we strive to cater to all businesses, however there are some services and goods, for which we donot provide our payment gateway services. Here is the <a href="https://www.cashfree.com/tnc" target="_blank">list of banned items.</a></p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='9'> <h5 className="faq_head"> What is the procedure for Cashfree payment gateway integration? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='9'> <Card.Body> <div className="faq_content"> <p>We do 100% paperless onboarding for merchants on Cashfree Payment Gateway. Following are the steps for integration</p> <ul> <li><a href="https://www.cashfree.com/payment-gateway-india" target="_blank"> Signup on Cashfree</a></li> <li>Update your business profile and upload scanned copies of business documents</li> <li>You can try out the payment gateway yourself. Login and switch to Test Account. <a href="https://docs.cashfree.com/docs/pg.html" target="_blank">Check integration documentation.</a> </li> <li>Our Payment expert will call you in next 24 hours, share your business requirement and we will help you pick the right set of features.</li> <li>Once account is verified, our Product team will help you with the integration.</li> </ul> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='10'> <h5 className="faq_head"> What are the documents required for integration? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='10'> <Card.Body> <div className="faq_content"> <p>Once you sign-up, to activate your Cashfree merchant account you need to share business details along with scanned copies of the following business documents. Here is the list of documents your need to upload. Here is the <a href="http://help.cashfree.com/en/articles/1957862-what-are-the-documents-required-at-the-time-of-sign-up" target="_blank">list of documents required for integration</a> </p> </div> </Card.Body> </Accordion.Collapse> </Card> </Accordion>; export default AutoCollectFaq; <file_sep>/components/faqs/SubsFaqs.js import React from 'react' import Accordion from 'react-bootstrap/Accordion' import Card from "react-bootstrap/Card"; import Link from 'next/link' const SubsFaqs = () => <Accordion defaultActiveKey="0"> <Card> <Accordion.Toggle as={Card.Header} eventKey='0'> <h5 className="faq_head"> What is a subscription? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='0'> <Card.Body> <div className="faq_content"> <p>When you want to bill your customer for continued usage of your product or service, instead of raising a payment request each time, you can provide an option to your user to authorize automatic deduction of billed amount from his bank/Debit/Credit card as the case may be. For this user needs to give authorization to you. This arrangement is called subscription.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='1'> <h5 className="faq_head"> What is subscription management software? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='1'> <Card.Body> <div className="faq_content"> <p>Subscription management starts from creating plans that have one or more people who want to avail the service and pay for the usage on a recurring basis.</p> <p>It involves creating plans, defining pricing model and then adding users and generating billing based on the defined pricing model and actual consumption.</p> <p>Companies of all sizes face the question of whether to build or buy a billing solution. Cashfree Subscription Management Software powers you to enable recurring payment schedule, control the billing cycle and get instant alerts on subscription activity. All you have to do is to link a plan to the customer and Cashfree takes care of the rest.</p> <p>The service is available as a Dashboard feature and as API.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='2'> <h5 className="faq_head"> Can Cashfree subscription work with other payment gateway service providers as well? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='2'> <Card.Body> <div className="faq_content"> <p>No, Cashfree's Subscription Management Software is not configurable with other payment gateways.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='3'> <h5 className="faq_head"> How do recurring payment on Credit Cards work in India? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='3'> <Card.Body> <div className="faq_content"> <p>Credit cards provided by the popular card networks MasterCard and Visa support auto-deduction of recurring payment. For this the card holder needs to authorize the payment to the specified merchant which can be done through a normal Two-Factor Authentication or 3D Secure flow.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='4'> <h5 className="faq_head"> How do recurring payment on Debit Cards work in India? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='4'> <Card.Body> <div className="faq_content"> <p>Currently, not all banks support auto-deduction of payments. Auto-deduction for recurring payment are allowed on Mastercard and Visa network cards issued by following banks:</p> <ul> <li>Kotak Mahindra Bank</li> <li>Citibank</li> <li>Canara Bank</li> <li>Standard Chartered Bank</li> <li>ICICI Bank</li> </ul> <p>Similar to Credit cards, Debit card holders also need to authorize the payment to the specified merchant which can be done through a normal Two-Factor Authentication or 3D Secure flow.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='5'> <h5 className="faq_head"> What is the two-factor authentication (2FA) and how does it work in case of recurring payments? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='5'> <Card.Body> <div className="faq_content"> <p>A card holder when authenticating the merchant to deduct recurring payments, needs to do a one-time transaction which is also the first transaction. To ensure the authenticity of user and account, an extra layer of security is added which involves passing the transaction request following a 2FA process.</p> <p>In case of recurring payments, as the user does the 2FA, the auto-deduction is enabled.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='6'> <h5 className="faq_head"> Which payment instruments can be used for making recurring payments? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='6'> <Card.Body> <div className="faq_content"> <p> Credit card, Debit cards and Nach or E-Mandate are the widely used instruments for recurring payments.</p> <p><b>Credit cards :</b> MasterCard and Visa network cards-issued by any bank in India.</p> <p><b>Debit cards:</b> Mastercard and Visa network cards-issued by ICICI Bank, Kotak Mahindra Bank, Citibank and Canara Bank.</p> <p><b>Nach or E mandate :</b> A paperless authentication feature introduced by NPCI. The registration can be done through netbanking or Debit cards.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='7'> <h5 className="faq_head"> Can I cancel a plan or subscription? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='7'> <Card.Body> <div className="faq_content"> <p>Yes, you can cancel a plan or subscription. However once canceled, it can’t be restored, you need to create a new plan or subscription</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='8'> <h5 className="faq_head"> Can I edit a plan or subscription? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='8'> <Card.Body> <div className="faq_content"> <p>Yes, editing a plan or subscription is possible. You can directly change the plan/subscription details from the Cashfree Subscription Management software dashboard, however the changes that you make happen for future billing and do not take effect from retrospective effect.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='9'> <h5 className="faq_head"> We provide one subscription-multiple users model. Can We use Cashfree Subscriptions for subscription management? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='9'> <Card.Body> <div className="faq_content"> <p>Yes, Using Cashfree you can generate a subscription and through your internal system tag as many users as you wish to the subscription. Given the payment address will be single, cashfree will do the billing for that address.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='10'> <h5 className="faq_head"> Are current accounts supported for Cashfree Subscriptions? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='10'> <Card.Body> <div className="faq_content"> <p>No, Cashfree Subscriptions does not support current accounts.</p> </div> </Card.Body> </Accordion.Collapse> </Card> </Accordion>; export default SubsFaqs; <file_sep>/components/CtaSection.js import React from "react"; import Container from 'react-bootstrap/Container' import Row from 'react-bootstrap/Row' import Col from 'react-bootstrap/Col' const CtaSection = () => <section className="page_section"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h2 className="blue"> Talk to our Payment Experts </h2> <h5 className="p-3">Have a complex payment flow or require payment related advice ?</h5> <a onClick={() => Router.push('/contact-sales')} className="btn-primary"> Get In Touch </a> </div> </Col> </Row> </Container> </section>; export default CtaSection<file_sep>/pages/recurring-payment.js import React from 'react' import Header from '../components/Header' import Router from 'next/router' import Footer from '../components/Footer' import Row from 'react-bootstrap/Row' import Container from 'react-bootstrap/Container' import Col from 'react-bootstrap/Col' import ButtonToolbar from 'react-bootstrap/ButtonToolbar' import Button from 'react-bootstrap/Button' import Image from 'react-bootstrap/Image' import Link from 'next/link' import Tabs from 'react-bootstrap/Tabs'; import Tab from 'react-bootstrap/Tab'; import { NextSeo } from 'next-seo' import '../styles/custom-theme.scss' import SubsFaqs from '../components/faqs/SubsFaqs' const Banner = () => ( <> <section className="hero_section subscription_banner"> <Container> <Row> <Col md={7} xs={12} className="center_content"> <div className="banner_cont"> <h1 className="banner_head white"> Add Recurring Payments to your business. </h1> <p>Automate your recurring payments with Cashfree Subscriptions</p> <p className="text_box"><b className="yellow">Coming Soon</b> UPI recurring payments and Prepaid Payment Instruments (PPIs), including wallets.</p> </div> <a onClick={() => Router.push('/contact-sales')} className="btn-primary"> Get Started </a> </Col> </Row> <Row> <Col md={12} xs={12} className="m-auto"> <div className="new_subs_modes"> <h4>Powering Recurring Payments</h4> <div className="logo_list"> <img src="/images/subscription/credit.png" className="img-responsive" alt=""/> <img src="/images/subscription/debit.png" className="img-responsive" alt=""/> <img src="/images/subscription/nach.png" className="img-responsive" alt=""/> </div> </div> </Col> </Row> </Container> </section> <style> {` .subscription_banner { background-image: url(./images/subscription/subs_banner_bg.svg); background-repeat: no-repeat; background-position: center right; background-size: 400px; } `} </style> </> ) const SubsBlock = () => ( <> <section className="page_section"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h2 className="page_head"> Do More with Cashfree Subscriptions </h2> </div> </Col> </Row> <Row> <Col md={4} sm={4} xs={12}> <div className="main_product subs_icon_block w-100"> <div className="card_img"><Image src="/images/subscription/code.svg" fluid/></div> <h4 className="tile_head">Start without writing code</h4> <p>Use our dashboard to create plans and add users via a link. Share over email, SMS or Whatsapp.</p> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="main_product subs_icon_block w-100"> <div className="card_img"><Image src="/images/subscription/trial.svg" fluid/></div> <h3 className="tile_head">Trial Period</h3> <p>Offer trial period option and link to subscription plan. Charge as per plan at the end of the trial.</p> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="main_product subs_icon_block w-100"> <div className="card_img"><Image src="/images/subscription/upfront.svg" fluid/></div> <h3 className="tile_head">Upfront Charge</h3> <p>Charge your customers a one time fee at start of service along with recurring payment.</p> </div> </Col> </Row> <Row> <Col md={4} sm={4} xs={12}> <div className="main_product subs_icon_block w-100"> <div className="card_img"><Image src="/images/subscription/webhook.svg" fluid/></div> <h4 className="tile_head">Webhook Support</h4> <p>Automatically notify new subscriptions, payments, or cancellations.</p> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="main_product subs_icon_block w-100"> <div className="card_img"><Image src="/images/subscription/analysis.svg" fluid/></div> <h3 className="tile_head">Advanced Analytics</h3> <p>Stay on top of every subscription details-Plans and Users using Dashboard or pull details via API.</p> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="main_product subs_icon_block w-100"> <div className="card_img"><Image src="/images/subscription/support.svg" fluid/></div> <h3 className="tile_head">Multi-user Support</h3> <p>Add your team members for managing subscribers. Define roles & permissions.</p> </div> </Col> </Row> <Row> <Col md={12} sm={12} xs={12}> <div className="cming_soon_box subs_diduknow"> <div className="row"> <div className="col-md-2 col-sm-2 col-xs-12"> <p className="box_head"> Did you know </p> </div> <div className="col-md-6 col-sm-8 col-xs-12"> <p>Cashfree validates if a card supports subscriptions or recurring payments during registration to ensure higher success rate</p> </div> </div> </div> </Col> </Row> </Container> </section> <style> {` .subs_diduknow { background-image: url(./images/subscription/mike.svg); background-size: contain; background-repeat: no-repeat; background-position: center right; } .subs_icon_block .card_img img { max-width: 50px; } `} </style> </> ) const PgFeatures = () => ( <section className="page_section"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h2 className="page_head"> Payment Gateway Enterprise Features<br/> <b className="green">Now Available for All</b> </h2> </div> </Col> </Row> <Row> <Col md={4} sm={4} xs={12}> <div className="product_features w-100"> <div className="card_img"><Image src="/images/pg/customization.png" fluid/></div> <div className="feature_cont"><h3 className="tile_head">Your Website Your Checkout Page</h3> <p>Customize the checkout page to look like your website or application.</p></div> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="product_features w-100"> <div className="card_img"><Image src="/images/pg/savedcards.png" fluid/></div> <div className="feature_cont"><h3 className="tile_head">Saved Cards</h3> <p>Save customers from typing card credentials every time. Only CVV and 3-D secure password will be required during next transaction.</p></div> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="product_features w-100"> <div className="card_img"><Image src="/images/pg/recurring.png" fluid/></div> <div className="feature_cont"><h3 className="tile_head">Recurring Payments</h3> <p>Auto-debit funds for periodic payments via cards, UPI and net banking.</p></div> </div> </Col> </Row> <Row> <Col md={4} sm={4} xs={12}> <div className="product_features w-100"> <div className="card_img"><Image src="/images/pg/preauth.png" fluid/></div> <div className="feature_cont"><h3 className="tile_head">Pre-authorization</h3> <p>Block funds when a customer places an order. If the order is modified or cancelled within a week, process instant refund without paying any charges.</p></div> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="product_features w-100"> <div className="card_img"><Image src="/images/pg/successrate.png" fluid/></div> <div className="feature_cont"><h3 className="tile_head">Higher than Industry Success Rate</h3> <p>With smart dynamic rerouting between multiple bank payment gateways, experience the highest success rate every time.</p></div> </div> </Col> </Row> </Container> </section> ) const Offers = () => ( <section className="page_section"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h2 className="page_head"> Offer Subscription Plans that Suit </h2> </div> </Col> </Row> <Row> <Col md={4} sm={4} xs={12}> <div className="subs_offer w-100"> <div className="feature_cont"><h3 className="tile_head">Flexible Billing</h3> <p>Bill your customers on-demand or automatically on a periodic basis</p></div> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="subs_offer w-100"> <div className="feature_cont"><h3 className="tile_head">Easy Integration</h3> <p>Use dashboard or integrate our REST APIs with your product to automate</p></div> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="subs_offer w-100"> <div className="feature_cont"><h3 className="tile_head">NACH / e-mandate</h3> <p>Accept recurring payments via <a onClick={() => Router.push('/nach-mandate')}>NACH mandate</a> Debit or Credit card</p></div> </div> </Col> </Row> </Container> </section> ) const Integration = () => ( <> <section className="page_section light_bg"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h2 className="page_head"> How to Create Subscription Plans? </h2> </div> </Col> </Row> <Row> <Col md={12} sm={12} xs={12}> <div className="main_product w-100"> <iframe id="cashgram-video" width="100%" height="560px" src="https://www.youtube.com/embed/63-lKFYiJmY?controls=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> </div> </Col> </Row> <Row> <Col md={12} sm={12} xs={12}> <div className="cming_soon_box subs_diduknow for_dev"> <div className="row"> <div className="col-md-2 col-sm-2 col-xs-12"> <p className="box_head"> For <br/> Developers </p> </div> <div className="col-md-7 col-sm-8 col-xs-12"> <p>Checkout our <a href="https://docs.cashfree.com/docs/sbc/guide/" target="_blank" className="white">API documentation</a> and explore how Cashfree Subscription is the building block that lets you create customized subscription logic and pricing models.</p> </div> <div className="col-md-3 col-sm-12 col-xs-12 text-center d-flex align-items-center"> <a onClick={() => Router.push('/contact-sales')} className="btn-white">Contact Sales</a> </div> </div> </div> </Col> </Row> </Container> </section> <style> {` .subs_diduknow.for_dev { background-image: url(./images/subscription/dev.svg); background-size: contain; background-repeat: no-repeat; background-position: center right; } `} </style> </> ) const Faqs = () => <section className="page_section"> <Container> <Row> <Col md={8} xs={12} className="m-auto"> <div className="text-center"> <h2 className="page_head"> FAQs </h2> </div> </Col> </Row> <Row> <Col md={8} xs={12} className="m-auto"> <div className="faqs"> <SubsFaqs/> </div> </Col> </Row> </Container> </section>; const PaymentSolution = () => ( <section className="page_section"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h2 className="page_head"> A comprehensive recurring payments solution </h2> </div> </Col> </Row> <Row> <Col md={12} xs={12}> <div className="solution_tabs"> <Tabs defaultActiveKey="domestic_mode" id="solution_tabs"> <Tab eventKey="domestic_mode" title="Domestic Payment Mode"> <div className="solution_tab_content"> <div className="row"> <div className="col-md-5 col-xs-12"> <h3> Credit Cards </h3> <p>User can add any credit cards on Mastercard and Visa network-any bank in India. Get one-time authentication.</p> <h3> Debit Cards </h3> <p>Works for Debit cards on Mastercard and Visa network issued by ICICI Bank, Kotak Mahindra Bank, Citibank and Canara Bank. Just one-time authentication and automatically deduct charges as per the billing cycle.</p> <h3> Nach Mandate or E-Mandate </h3> <p>Enable automated recurring transactions over a bank account via <a className="bold_text" href="https://blog.cashfree.com/e-mandate/" target="_blank" rel="noopener noreferrer"> e-Mandate registration</a> through Netbanking all banks or Debit Card.</p> </div> <div className="col-md-7 col-xs-12"> <div className="subs_tab_img"> <img src="/images/subscription/domestic.svg" className="img-responsive" alt=""/> </div> </div> </div> </div> </Tab> <Tab eventKey="international" title="International Cards & Currencies"> <div className="solution_tab_content"> <div className="row"> <div class="col-md-5 col-xs-12"> <h3> International Cards </h3> <p>User can add any credit cards on Mastercard and Visa network-any bank in India. Get one-time authentication and automatically deduct charges as per the billing cycle. Support for Amex cards coming soon.</p> <h3> Multi-currency support </h3> <p>Take your offering across the world. Offer secure payments. Go global with support for 50+ currencies</p> </div> <div className="col-md-7 col-xs-12"> <div className="subs_tab_img"> <img src="/images/subscription/international.png" className="img-responsive" alt=""/> </div> </div> </div> </div> </Tab> </Tabs> </div> </Col> </Row> </Container> </section> ) const RecurringPlan = () => ( <section className="page_section light_bg"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h2 className="page_head"> Design Your Custom Recurring Plan </h2> </div> </Col> </Row> <Row> <Col md={4} xs={12}> <div class="plan_content alight_left"> <div class="model"> <h3 class="clockwise">Fixed Recurring Model</h3> <p>For companies that provide a product for a fixed price and charge on a recurring basis</p> </div> <div class="model"> <h3 class="straight">Fixed + Overcharge Model</h3> <p>Simplify billing where amount includes fixed and variable components.</p> </div> </div> </Col> <Col md={4} xs={12}> <div class="plan_content"> <div class="model_img"> <img src="/images/subscription/model.gif" class="img-responsive" alt=""/> </div> </div> </Col> <Col md={4} xs={12}> <div class="plan_content alight_right"> <div class="model"> <h3 class="anticlockwise">Usage Model</h3> <p>Companies that provide a product and who want to enable customers to pay for only what they use.</p> </div> </div> </Col> </Row> <Row> <Col md={12} xs={12} className="text-center"> <a onClick={() => Router.push('/contact-sales')} class="btn-primary mt-5">Accept Recurring Payments</a> </Col> </Row> </Container> </section> ) const SubsProcess = () => ( <section className="page_section voilet_bg"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center mb-5"> <h2 className="page_head white"> How Does Subscription Management Work? </h2> </div> </Col> </Row> <Row> <Col md={4} xs={12}> <div class="subs_box bg_border"> <img src="/images/subscription/create.svg" class="img-responsive" alt=""/> <p className="white"><b>Create a plan</b><br/>Via Dashboard or API</p> </div> </Col> <Col md={4} xs={12}> <div class="subs_box bg_border"> <img src="/images/subscription/add.svg" class="img-responsive" alt=""/> <p className="white"><b>Add subscribers </b> <br/> &amp; notify</p> </div> </Col> <Col md={4} xs={12}> <div class="subs_box"> <img src="/images/subscription/auth.svg" class="img-responsive" alt=""/> <p className="white"><b>Authenticate </b> <br/> &amp; charge</p> </div> </Col> </Row> </Container> </section> ) const Subscription = () => ( <div> <NextSeo title="Recurring Payment | Subscriptions | NACH for India" keywords="payment gateway india,best payment gateway,best payment gateway india,payment gateway integration,payment gateway integration India,international payment gateway" description="[Free Demo] Recurring Payment: Manage subscriptions, recurring payments and billing. Create custom plans & accept subscription payments via Credit cards, Debit cards and e Mandate." /> <Header/> <Banner/> <SubsBlock/> <RecurringPlan/> <PaymentSolution/> <Offers/> <SubsProcess/> <Integration/> <Faqs/> <Footer/> </div> ) export default Subscription <file_sep>/components/faqs/PayoutsFaqs.js import React from 'react' import Accordion from 'react-bootstrap/Accordion' import Card from "react-bootstrap/Card"; import Link from 'next/link' const PayoutsFaqs = () => <Accordion defaultActiveKey="0"> <Card> <Accordion.Toggle as={Card.Header} eventKey='0'> <h5 className="faq_head"> How is Payouts different from using banks for bulk transfers ? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='0'> <Card.Body> <div className="faq_content"> <p>Bulk transfers via bank account happen by uploading a spreadsheet on the banking portal or manually adding every beneficiary before transferring. Cashfree automates bulk transfers fully via APIs AND offers a much simpler alternative to uploading files on a bank portal.</p> <p>Unlike banks, where a single error in a payment file can block all the bulk payments, using Cashfree, even if there are invalid records in a file, valid transfers go through. Reconciliation for failed and invalid transfers is automated so you always know which transfer failed out of hundreds of payments, and why. At Cashfree, new beneficiary addition and activation is instant.</p> <p>Cashfree also allows you to send money to any PayTM account or UPI address in addition to bank accounts, even on holidays.</p> <p>Lastly, all of this can be automated and built into your product or internal systems using our powerful APIs.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='1'> <h5 className="faq_head"> Do I need to be a registered business ? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='1'> <Card.Body> <div className="faq_content"> <p>Yes, we need you to be a business. If you are not yet registered as a business but plan to start soon, it is possible to get access to a test account and explore the API. We can also set up an account with limits on payout volume after understanding your business.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='2'> <h5 className="faq_head"> How can I get started ? What documents are needed ? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='2'> <Card.Body> <div className="faq_content"> <p>We require a cancelled cheque, proof of business registration, PAN card of business and business owners.</p> <p>To get started, you can contact us and request to be called back. We will reach out, understand your business and get you started. You can also Sign Up here and share the required details. Your account manager will contact you. Meanwhile, you can also look at the API doc and try things using test credentials.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='3'> <h5 className="faq_head"> Is it simpler to send mass payments via bulk file uploads or via APIs ? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='3'> <Card.Body> <div className="faq_content"> <p>Using bulk file uploads or manual transfers requires no technical expertise and is the quickest way to get started. Integrating the API can take a day or two depending on the complexity of integration. Many businesses start by using the bulk file upload or manual transfer option, and gradually automate operations by integrating the API.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='4'> <h5 className="faq_head"> How long does it take to transfer funds ? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='4'> <Card.Body> <div className="faq_content"> <p>Transfers to bank accounts happen instantly or within a few minutes, depending on your business requirement. Transfers for amounts in excess of Rs 2,00,000 are restricted by banking hours and can take longer. A payout to UPI-BHIM ID or PayTM wallet is instant.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='5'> <h5 className="faq_head"> Can I transfer funds on Sundays and bank holidays ? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='5'> <Card.Body> <div className="faq_content"> <p>Yes, it is possible to make bulk payments even on Sundays and bank holidays.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='6'> <h5 className="faq_head"> What happens in case the account details are incorrect ? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='6'> <Card.Body> <div className="faq_content"> <p>Transfers to incorrect account details fail instantly. For certain banks, it may take upto 24 hours to receive a confirmation of failure.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='7'> <h5 className="faq_head"> Do you support all banks and bank accounts ? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='7'> <Card.Body> <div className="faq_content"> <p>Yes, you can send money to any active savings or current bank account in India. However, NRE and NRO bank accounts are not supported.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='8'> <h5 className="faq_head"> Do you support payouts to and from other countries ? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='8'> <Card.Body> <div className="faq_content"> <p>It is possible to send a mass payout to India from another country. The purpose of the payment must be known while setting up the account.</p> <p>An Indian business can also send a payout to other countries. However, there are restrictions around the volume of payments and the purpose of payments. Get in touch with us to learn more.</p> </div> </Card.Body> </Accordion.Collapse> </Card> </Accordion>; export default PayoutsFaqs; <file_sep>/components/CaseStudy.js import React from "react"; import Carousel from 'react-bootstrap/Carousel' import Row from 'react-bootstrap/Row' import Col from 'react-bootstrap/Col' import Image from 'react-bootstrap/Image' function cases() { return [ { src:'/images/payouts/grab_testimonial.png',head:"First-of-its kind on-demand wage payout solution", logosrc:'/images/payouts/grab_logo.png', content:"10,000 Grab delivery partners carrying out thousands of deliveries daily, use Cashfree Payouts to withdraw earnings to their bank account, whenever they want, instantly. The delivery partners just need to open their Partner App and request a payout of their daily earnings.Paying wages faster leads to Partner happiness and best in industry Partner retention rate for Grab." }, { src:'/images/payouts/nykaa_testimonial.png',head:"Instant refund processing solution for cash on delivery orders", logosrc:'/images/payouts/nykaa_logo.png', content:"Nykaa uses Payouts to send speedy refunds to customers. Once the customer requests a refund, the operations team creates and sends a Cashgram link. The customer can request a payout by sharing bank account, UPI-BHIM ID or PayTM account.Once approved by the operations team, money is transferred instantly to the customer's preferred account." }, { src:'/images/payouts/rummy_testimonial.png',head:"Real-time player cashouts on gaming websites", logosrc:'/images/payouts/rummycircle_logo.png', content:"With just the click of a 'Withdraw' button, players on RummyCircle are able to receive their winnings in their bank accounts, instantly.By offering API driven Payouts 24x7, RummyCircle is able to offer the best gaming experience to players which greatly enhances engagement and revenue." } ]; } function CaseStudy() { return ( <Carousel className="casestudy_slider testimonial_slider" indicators={false}> {cases().map(slide => ( <Carousel.Item> {/* <Row> <Col md={12} xs={12} className="w-100"> </Col> </Row> */} <Row> <Col md={6} xs={12}> <div className="illus_sec product_img"> <div className="illus_img product_img_bg"> </div> <Image src={slide.src} fluid/> </div> </Col> <Col md={6} xs={12}> <div className="case_head mb-2 pl-3"> <h3 className="m-0">{slide.head}</h3> </div> <div className="content_testi"> <Image src={slide.logosrc} fluid/> <p>{slide.content}</p> </div> </Col> </Row> </Carousel.Item> ))} </Carousel> ); } export default CaseStudy; <file_sep>/pages/resources/preauthorization.js import React from 'react' import Head from 'next/head' import Header from '../../components/Header' import Footer from '../../components/Footer' import Container from 'react-bootstrap/Container'; import '../../styles/custom-theme.scss' const Banner = () => ( <section className="hero_section"> <Container> <div className="career"> <h1 className="banner_head white"> welcome to Cashfree Pricing </h1> </div> </Container> </section> ) const Preauthorization = () => ( <div> <Head> <title>Pricing</title> <link rel="icon" href="/favicon.ico" /> <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500,600,700,800|Open+Sans:300,400,600,700,800&display=swap" rel="stylesheet"></link> </Head> <Header/> <Banner/> <Footer/> </div> ) export default Preauthorization <file_sep>/pages/nodal-account-marketplace-settlements.js import React from 'react' import Head from 'next/head' import Router from 'next/router' import Header from '../components/Header' import Footer from '../components/Footer' import Row from 'react-bootstrap/Row' import Container from 'react-bootstrap/Container' import Col from 'react-bootstrap/Col' import ButtonToolbar from 'react-bootstrap/ButtonToolbar' import Button from 'react-bootstrap/Button' import Image from 'react-bootstrap/Image' import MarketplaceFaqs from '../components/faqs/MarketplaceFaqs' import { NextSeo } from 'next-seo' import '../styles/custom-theme.scss' const Banner = () => ( <section className="hero_section"> <Container> <Row> <Col md={6} xs={12} className="center_content"> <div className="banner_cont"> <h1 className="banner_head white"> Marketplace Payment Gateway </h1> <p>Automatically split payments with your <br /> vendors after every sale.</p> </div> <a onClick={() => Router.push('/contact-sales')} className="btn-primary"> Get Started </a> </Col> </Row> </Container> </section> ) const ContentSection = () => ( <section className="page_section light_bg"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h1 className="cont_head blue"> Split payments without managing a Nodal Account </h1> <h3>Running a marketplace <br /> made supereasy</h3> </div> </Col> </Row> </Container> </section> ) const MplaceCrads = () => ( <section className="page_section"> <Container> <Row> <Col md={4} sm={4} xs={12}> <div className="main_product mp_card w-100"> <div className="card_img"><Image src="/images/marketplace/verified.svg" fluid /></div> <h3 className="tile_head">Vendor Management <br /> <span className="green">Simplified</span></h3> <p>Split payments to vendors correctly: On time and automatically.</p> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="main_product mp_card w-100"> <div className="card_img"><Image src="/images/marketplace/split.svg" fluid /></div> <h3 className="tile_head">Split <br /> <span className="green">Payments</span></h3> <p>Connect with Cashfree split payment gateway to pay your vendors faster from Cashfree’s managed nodal account.</p> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="main_product mp_card w-100"> <div className="card_img"><Image src="/images/marketplace/offline.svg" fluid /></div> <h3 className="tile_head">Offline or cash on <br /> <span className="green">delivery orders</span></h3> <p>Any online or offline transaction can be added and settled using our API.</p> </div> </Col> </Row> </Container> </section> ) const WorkProcess = () => ( <section className="page_section"> <Container> <Row> <Col md={8} xs={12} className="m-auto"> <div className="text-center"> <h2 className="page_head"> How does Marketplace Settlements work? </h2> </div> </Col> </Row> <Row> <Col md={4} sm={4} xs={12}> <div class="process_tile"> <div className="tc"> <img src="/images/marketplace/customer.svg" /> <div className="time_ball"></div> </div> <div className="time-cont"> <h5>Customer Places Order</h5> <h5>Customer places an order for items provided by the seller(s), and you as a marketplace define vendor commission.</h5> </div> </div> </Col> <Col md={4} sm={4} xs={12}> <div class="process_tile"> <div className="tc"> <img src="/images/marketplace/seller.svg" /> <div className="time_ball"></div> </div> <div className="time-cont"> <h5>Sellers are Paid</h5> <h5>Cashfree computes the amount to be paid to the seller(s) and transfers the amount. (T+2 settlement cycle).</h5> </div> </div> </Col> <Col md={4} sm={4} xs={12}> <div class="process_tile"> <div className="tc"> <img src="/images/marketplace/easy.svg" /> <div className="time_ball_l"></div> </div> <div className="time-cont"> <h5>Easy Reconciliation</h5> <h5>A detailed report on orders made to different sellers, transactions carried out and much more.</h5> </div> </div> </Col> </Row> </Container> </section> ) const Features = () => ( <section className="page_section"> <Container> <Row> <Col md={8} xs={12} className="m-auto"> <div className="text-center"> <h2 className="page_head"> Marketplace Settlement Features </h2> </div> </Col> </Row> <Row> <Col md={6} sm={6} xs={12}> <div className="main_product w-100 p-4"> <div className="card_img"><Image src="/images/marketplace/fast.svg" fluid /></div> <h3 className="tile_head">Fast Settlements</h3> <p>Ensures faster settlement to vendors within a T+2 settlement cycle</p> </div> </Col> <Col md={6} sm={6} xs={12}> <div className="main_product w-100 p-4"> <div className="card_img"><Image src="/images/marketplace/easyi.svg" fluid /></div> <h3 className="tile_head">Easy Integration</h3> <p>Integrate with our simple APIs and get running in under 30 minutes</p> </div> </Col> </Row> <Row> <Col md={6} sm={6} xs={12}> <div className="main_product w-100 p-4"> <div className="card_img"><Image src="/images/marketplace/simpler.svg" fluid /></div> <h3 className="tile_head">Simpler business payments</h3> <p>Tax computations are faster and simpler by accessing marketplace earnings per transaction</p> </div> </Col> <Col md={6} sm={6} xs={12}> <div className="main_product w-100 p-4"> <div className="card_img"><Image src="/images/marketplace/global.svg" fluid /></div> <h3 className="tile_head">Go Global</h3> <p>Allow international vendors to sell through your marketplace without any hassle</p> </div> </Col> </Row> </Container> </section> ) const Testimonial = () => <section className="page_section mt-5 mb-5"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h1 className="page_head"> Testimonial </h1> </div> </Col> </Row> <Row> <Col md={6} sm={6} xs={12}> <div className="main_product testimonial_img w-100"> <Image src="/images/marketplace/zaheer.jpg" fluid /> </div> </Col> <Col md={6} sm={6} xs={12} className="center_content"> <div className="cashgram_business w-100"> <Image src="/images/marketplace/ketto.png" fluid /> <h3 className="tile_head mb-3">Everyday we receive 2000+ donations against hundreds of our fundraisers. Previously there was manual work involved in compilations and then the funds were released via corporate net banking. This was error prone and tedious.<br /><br />Marketplace Settlement helped us move away from Excel files and human intervention is now minimal in the payout process. All receipts are automatically tagged to the correct vendor and settlements are completely automated. It is simple to use and the money flow is hassle-free.</h3> <h3 className="tile_head"><NAME> | Co-founder &nbsp; CTO | Ketto</h3> </div> </Col> </Row> <Row> <Col md={12} sm={12} xs={12}> <div className="cming_soon_box subs_diduknow for_dev"> <div className="row"> <div className="col-md-2 col-sm-2 col-xs-12"> <p className="box_head"> For <br /> Developers </p> </div> <div className="col-md-7 col-sm-8 col-xs-12 d-flex align-items-center"> <p>View API documentation to split payments</p> </div> <div className="col-md-3 col-sm-12 col-xs-12 text-center d-flex align-items-center"> <a href="https://docs.cashfree.com/docs/ces/guide/" target="_blank" className="btn-white">View More</a> </div> </div> </div> </Col> </Row> </Container> </section>; const Faqs = () => <section className="page_section"> <Container> <Row> <Col md={8} xs={12} className="m-auto"> <div className="text-center"> <h2 className="page_head"> Payment Gateway Integration FAQs </h2> </div> </Col> </Row> <Row> <Col md={8} xs={12} className="m-auto"> <div className="faqs"> <MarketplaceFaqs /> </div> </Col> </Row> </Container> </section>; const ProductCards = () => ( <section className="page_section light_bg"> <Container> <Row> <Col md={4} sm={4} xs={12}> <div className=" w-100 mt-5"> <h4 className="blue">Link to Cashfree payment gateway and other collections products</h4> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="link_card w-100"> <div className="link-payment-item"> <Image src="/images/productcard1.svg" fluid /> <p><b>Auto Collect</b> - Accept payments directly via NEFT, IMPS, RTGS and UPI and disburse using Payouts</p> </div> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="link_card w-100"> <div className="link-payment-item"> <Image src="/images/productcard2.svg" fluid /> <p><b>Marketplace Settlements</b> - Automatically split commissions with your vendors after every purchase. Run a marketplace with ease.</p> </div> </div> </Col> </Row> </Container> </section> ) const MarketplaceCtaSection = () => <section className="page_section"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h3 className="Mplace_head"> Split Payments Easily </h3> <h5 className="p-3">Run your marketplace without managing a nodal account. <br/> Talk to our payment experts.</h5> <a onClick={() => Router.push('/contact-sales')} className="btn-primary"> Get In Touch </a> </div> </Col> </Row> </Container> </section>; const MarketplaceSettlements = () => ( <div> <NextSeo title="A Nodal Account for Split Payments | Cashfree" keywords="payment gateway india,best payment gateway,best payment gateway india,payment gateway integration,payment gateway integration India,international payment gateway" description="Cashfree's marketplace settlements offers an easy to use nodal account to run your business and split payments with vendors on time" /> <Header /> <Banner /> <ContentSection /> <MplaceCrads /> <WorkProcess /> <Features /> <Testimonial /> <Faqs /> <MarketplaceCtaSection /> <ProductCards /> <Footer /> </div> ) export default MarketplaceSettlements <file_sep>/pages/careers.js import React from 'react' import Head from 'next/head' import Header from '../components/Header' import Footer from '../components/Footer' import Row from 'react-bootstrap/Row' import Container from 'react-bootstrap/Container' import Col from 'react-bootstrap/Col' import ButtonToolbar from 'react-bootstrap/ButtonToolbar' import Button from 'react-bootstrap/Button' import Image from 'react-bootstrap/Image' import Link from 'next/link' import '../styles/custom-theme.scss' const Banner = () => ( <section className="hero_section"> <Container> <Row> <Col md={6} xs={12}> <div className="banner_cont"> <h1 className="banner_head white"> Domestic & International Payment Gateway for India. </h1> <p>Accept domestic and international payments with 100+ payment options. Choose from a range of integrations to give best checkout experience to your customers.</p> </div> <a onClick={() => Router.push('/contact-sales')} className="btn-primary"> Get Started </a> <style jsx>{` p{ font-size: 1.37rem; font-weight: 500; padding: 24px 0; color:white; } `}</style> </Col> <Col md={6} xs={12}> <div className="banner_img"> </div> </Col> </Row> </Container> </section> ) const careers = () => ( <div> <Head> <title>Careers</title> <link rel="icon" href="/favicon.ico" /> <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500,600,700,800|Open+Sans:300,400,600,700,800&display=swap" rel="stylesheet"></link> </Head> <Header/> <Banner/> <Footer/> </div> ) export default careers <file_sep>/components/faqs/PgFaqs.js import React from 'react' import Accordion from 'react-bootstrap/Accordion' import Card from "react-bootstrap/Card"; import Link from 'next/link' const PgFaqs = () => <Accordion defaultActiveKey="0"> <Card> <Accordion.Toggle as={Card.Header} eventKey='0'> <h5 className="faq_head"> Which payments modes do you support? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='0'> <Card.Body> <div className="faq_content"> <p>On Cashfree payment gateway you get the widest range of payment options. We support Credit Card, Debit Card, Net Banking, NEFT, IMPS, Paytm and other wallets, UPI via BHIM UPI , Google Pay, PhonePe etc.</p> <p>We also provide multiple bank EMI and cardless EMI options such as Zest Money. With Cashfree payment gateway you can also give your customers Buy Now Pay Later option by using Ola Money Postpaid, ePayLater etc. Our merchants say that Buy Now Pay Later option has increased checkout success rate by 25-30% for high ticket value transactions. For details, visit the <Link href="/payment-gateway-charges/"><a target="_blank">pricing page</a></Link></p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='1'> <h5 className="faq_head"> I sell products to both Indian and international customers, is Cashfree the right payment gateway for me? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='1'> <Card.Body> <div className="faq_content"> <p>Cashfree's domestic and international payment gateway is built for growing businesses. We support 100+ payment modes both domestic and international to help you go global.</p> <p><b>For domestic payments:</b> We support 70+ netbanking options, Credit Card, Debit Card, NEFT, IMPS, Paytm and other wallets, UPI via BHIM UPI , Google Pay, PhonePe etc. We also provide multiple bank EMI and cardless EMI options such as Zest Money, along with Buy Now Pay Later option (Ola Money Postpaid, ePayLater etc.)</p> <p><b>For international customers:</b> On Cashfree payment gateway, you can show your products in the home currency of your customers. We support 30+international currencies. As payments mode we support international cards, Diners Club International and AMEX. Paypal is trusted payment mode across the global, on Cashfree, you can integrate your existing merchant PayPal account and start accepting international payments from day one.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='2'> <h5 className="faq_head"> What are the payment gateway charges? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='2'> <Card.Body> <div className="faq_content"> <p>Simple and user-friendly: 1.75%. There is Zero Setup fee and we charge no annual maintenance fee. For a detailed breakdown of payment gateway charges by payment mode, visit our <Link href="/payment-gateway-charges/"><a target="_blank">pricing page</a></Link>.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='3'> <h5 className="faq_head"> Can I sign up as an individual? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='3'> <Card.Body> <div className="faq_content"> <p>Yes, you can sign up as an individual for payment gateway. Please share your personal address proof instead of the business registration details. Here is the <a href="http://help.cashfree.com/en/articles/1957862-what-are-the-documents-required-at-the-time-of-sign-up" target="_blank">list of documents</a> required for integration.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='4'> <h5 className="faq_head"> How many days does the integration takes? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='4'> <Card.Body> <div className="faq_content"> <p>Cashfree is the easiest payment gateway solution for any developer. You can do the integration on any website with any stack. We have Simple Payment APIs with detailed documentation and SDKs for all major platforms. With responsive developer support, integrating Cashfree is a smooth experience!</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='5'> <h5 className="faq_head"> In which languages do you have integration kits available? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='5'> <Card.Body> <div className="faq_content"> <p>We have payment gateway integration in PHP, Java, Python, NodeJS, Ruby and.Net.</p> <ul> <li><a href="https://github.com/cashfree/php-pg-integration" target="_blank"> * Reference doc for integration in PHP</a></li> <li><a href="https://github.com/cashfree/pg-integration-kits/tree/master/java" target="_blank"> * Reference doc for integration in Java</a></li> <li><a href="https://github.com/cashfree/pg-integration-kits/tree/master/python" target="_blank"> * Reference doc for integration in Python</a></li> <li><a href="https://github.com/cashfree/pg-integration-kits/tree/master/nodejs/checkout" target="_blank"> * Reference doc for integration in NodeJS</a></li> </ul> <p>With our ready to use integration kits you will be able to integrate payment gateway in no time. Throughout your onboarding process and account activation, you will have a dedicated manager who will assist you at every stage. Our Product experts will also available for any assistance you may need.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='6'> <h5 className="faq_head"> Can I do payment gateway integration in Android & iOS apps? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='6'> <Card.Body> <div className="faq_content"> <p>Yes, You can use our library to integrate Cashfree Payment Gateway directly into your Android or iOS app using CashfreeSDK. CashfreeSDK has been designed to offload the complexity of handling and integrating payments in your app.</p> <ul> <li>Follow the link to check out CashfreeSDK <a href="https://docs.cashfree.com/docs/android/guide/" target="_blank">integration in Android.</a></li> <li>Follow the link to check out CashfreeSDK <a href="https://docs.cashfree.com/docs/ios/guide/" target="_blank">integration in iOS.</a></li> </ul> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='7'> <h5 className="faq_head"> I want to add Google Pay and other UPI options on the checkout page. How to do that? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='7'> <Card.Body> <div className="faq_content"> <p>At Cashfree, we provide widest range of UPI integrations including Webflow, intent flow, Google Pay integration and UPI SDK integration. You need to just share your requirement and our UPI payment experts will help you analyze the various UPI modes and recommend the best one as per your business requirement.</p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='8'> <h5 className="faq_head"> Is there any list of banned items for which Cashfree payment gateway services will not be available? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='8'> <Card.Body> <div className="faq_content"> <p>As a payments company we strive to cater to all businesses, however there are some services and goods, for which we donot provide our payment gateway services. Here is the <a href="https://www.cashfree.com/tnc" target="_blank">list of banned items.</a></p> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='9'> <h5 className="faq_head"> What is the procedure for Cashfree payment gateway integration? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='9'> <Card.Body> <div className="faq_content"> <p>We do 100% paperless onboarding for merchants on Cashfree Payment Gateway. Following are the steps for integration</p> <ul> <li><a href="https://www.cashfree.com/payment-gateway-india" target="_blank"> Signup on Cashfree</a></li> <li>Update your business profile and upload scanned copies of business documents</li> <li>You can try out the payment gateway yourself. Login and switch to Test Account. <a href="https://docs.cashfree.com/docs/pg.html" target="_blank">Check integration documentation.</a> </li> <li>Our Payment expert will call you in next 24 hours, share your business requirement and we will help you pick the right set of features.</li> <li>Once account is verified, our Product team will help you with the integration.</li> </ul> </div> </Card.Body> </Accordion.Collapse> </Card> <Card> <Accordion.Toggle as={Card.Header} eventKey='10'> <h5 className="faq_head"> What are the documents required for integration? </h5> </Accordion.Toggle> <Accordion.Collapse eventKey='10'> <Card.Body> <div className="faq_content"> <p>Once you sign-up, to activate your Cashfree merchant account you need to share business details along with scanned copies of the following business documents. Here is the list of documents your need to upload. Here is the <a href="http://help.cashfree.com/en/articles/1957862-what-are-the-documents-required-at-the-time-of-sign-up" target="_blank">list of documents required for integration</a> </p> </div> </Card.Body> </Accordion.Collapse> </Card> </Accordion>; export default PgFaqs; <file_sep>/components/VideoModal.js import React, { useState } from "react"; import Modal from 'react-bootstrap/Modal' import Button from "react-bootstrap/Button"; function VideoModal(props) { return ( <> <Modal {...props} animation={false} size="lg" aria-labelledby="contained-modal-title-vcenter" centered > <Modal.Body> <div className="video"> <iframe id="cashgram-video" width="100%" height="600px" src={props.src} frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> </div> <div className="close_btn" onClick={props.onHide}>x</div> </Modal.Body> </Modal> </> ); } export default VideoModal; <file_sep>/pages/pricing.js import React from 'react' import Head from 'next/head' import Header from '../components/Header' import Footer from '../components/Footer' import Row from 'react-bootstrap/Row' import Container from 'react-bootstrap/Container' import Col from 'react-bootstrap/Col' import ButtonToolbar from 'react-bootstrap/ButtonToolbar' import Button from 'react-bootstrap/Button' import CtaSection from '../components/CtaSection' import Image from 'react-bootstrap/Image' import PgFaqs from '../components/PgFaqs' import Link from 'next/link' import Tabs from 'react-bootstrap/Tabs'; import Tab from 'react-bootstrap/Tab'; import { NextSeo } from 'next-seo' import '../styles/custom-theme.scss' const Banner = () => ( <section className="hero_section"> <Container> <Row> <Col md={6} xs={12}> <div className="banner_cont"> <h1 className="banner_head white"> Domestic & International Payment Gateway for India. </h1> <p>Accept domestic and international payments with 100+ payment options. Choose from a range of integrations to give best checkout experience to your customers.</p> </div> <a onClick={() => Router.push('/contact-sales')} className="btn-primary"> Get Started </a> </Col> <Col md={6} xs={12}> <div className="banner_img"> <Image src="/images/pg/pgillustration.png" fluid/> </div> </Col> </Row> </Container> </section> ) const Pgcrads = () => ( <section className="page_section"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h1 className="page_head"> Payment Gateway Built for India </h1> </div> </Col> </Row> <Row> <Col md={4} sm={4} xs={12}> <div className="main_product w-100"> <div className="card_img"><Image src="/images/pg/modes.png" fluid/></div> <h3 className="tile_head">100+ Payment Options</h3> <p>Let your customers pay by any card, 70+ Netbanking options, UPI, Paytm & other wallets, EMI and Pay Later options.</p> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="main_product w-100"> <div className="card_img"><Image src="/images/pg/faster.png" fluid/></div> <h3 className="tile_head">Faster Settlements</h3> <p>Get paid next day or as soon as possible.</p> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="main_product w-100"> <div className="card_img"><Image src="/images/pg/global.png" fluid/></div> <h3 className="tile_head">Go Global</h3> <p>Reach customers across the world by unlocking international payment options instantly. Show items in 30+ foreign currencies.</p> </div> </Col> </Row> </Container> </section> ) const PgFeatures = () => ( <section className="page_section"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h1 className="page_head"> Payment Gateway Enterprise Features<br/> <b className="green">Now Available for All</b> </h1> </div> </Col> </Row> <Row> <Col md={4} sm={4} xs={12}> <div className="product_features w-100"> <div className="card_img"><Image src="/images/pg/customization.png" fluid/></div> <div className="feature_cont"><h3 className="tile_head">Your Website Your Checkout Page</h3> <p>Customize the checkout page to look like your website or application.</p></div> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="product_features w-100"> <div className="card_img"><Image src="/images/pg/savedcards.png" fluid/></div> <div className="feature_cont"><h3 className="tile_head">Saved Cards</h3> <p>Save customers from typing card credentials every time. Only CVV and 3-D secure password will be required during next transaction.</p></div> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="product_features w-100"> <div className="card_img"><Image src="/images/pg/recurring.png" fluid/></div> <div className="feature_cont"><h3 className="tile_head">Recurring Payments</h3> <p>Auto-debit funds for periodic payments via cards, UPI and net banking.</p></div> </div> </Col> </Row> <Row> <Col md={4} sm={4} xs={12}> <div className="product_features w-100"> <div className="card_img"><Image src="/images/pg/preauth.png" fluid/></div> <div className="feature_cont"><h3 className="tile_head">Pre-authorization</h3> <p>Block funds when a customer places an order. If the order is modified or cancelled within a week, process instant refund without paying any charges.</p></div> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="product_features w-100"> <div className="card_img"><Image src="/images/pg/successrate.png" fluid/></div> <div className="feature_cont"><h3 className="tile_head">Higher than Industry Success Rate</h3> <p>With smart dynamic rerouting between multiple bank payment gateways, experience the highest success rate every time.</p></div> </div> </Col> </Row> </Container> </section> ) const Integration = () => ( <section className="page_section light_bg"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h1 className="page_head"> Payment Gateway Integration </h1> </div> </Col> </Row> <Row> <Col md={12} sm={12} xs={12}> <div className="main_product w-100"> <iframe id="cashgram-video" width="100%" height="560px" src="https://www.youtube.com/embed/aKi6lJUymiU?controls=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> </div> </Col> </Row> </Container> </section> ) const PaymentLink = () => ( <section className="page_section"> <Container> <Row> <Col md={12} xs={12}> <div className="text-center"> <h1 className="page_head"> Do more with Payment Links </h1> </div> </Col> </Row> <Row> <Col md={4} sm={4} xs={12}> <div className="link_card w-100"> <div className="card_img"><Image src="/images/pg/paymentform.png" fluid/></div> <div className="feature_cont"> <p><b>Payment Form </b>- A fixed link to share with everyone instead of your bank accoun</p></div> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="link_card w-100"> <div className="card_img"><Image src="/images/pg/producthosting.png" fluid/></div> <div className="feature_cont"> <p><b>Product Hosting</b> - Create a webstore in minutes and start selling online.</p></div> </div> </Col> <Col md={4} sm={4} xs={12}> <div className="link_card w-100"> <div className="card_img"><Image src="/images/pg/invoice.png" fluid/></div> <div className="feature_cont"> <p><b>Invoicing</b> - Request payments over email or SMS and track payment status.</p></div> </div> </Col> </Row> </Container> </section> ) const IntegrationTabs = () => ( <section className="page_section light_bg"> <Container fluid> <Row> <Col md={4} xs={12} className="d-flex align-items-center justify-content-center"> <div className="text-center"> <h1 className="page_head"> Easiest integration </h1> </div> </Col> <Col md={8} xs={12}> <div className="intigration_tabs"> <Tabs defaultActiveKey="E-STORE PAYMENTS" id="uncontrolled-tab-example"> <Tab eventKey="E-STORE PAYMENTS" title="E-STORE PAYMENTS"> <div className="icon-holder"> <p className="bounce_button"><a target="_blank" href="https://www.cashfree.com/shopify-payment-gateway-india/"> <img src="/images/pg/shopify.png" alt="Cashfree"/> </a></p> <p className="bounce_button"><a target="_blank" href="https://www.cashfree.com/woocommerce-payment-gateway-india/"> <img src="/images/pg/woocommerce.png" alt="Cashfree"/> </a></p> <p className="bounce_button"><a target="_blank" href="https://www.cashfree.com/magento-payment-gateway-india/"> <img src="/images/pg/magento.png" alt="Cashfree" /> </a></p> <p className="bounce_button"><a target="_blank" href="https://docs.cashfree.com/docs/opencart/guide/"> <img src="/images/pg/opencart.png" alt="Cashfree" /> </a></p> </div> <div className="cashfree-block"> <div className="row cashfree-block-padding"> <div className="col-md-6"> <div className="single"> <h3>Sell in India from anywhere</h3> <p className="cashgram-tab-text"> Being an international payment gateway, you can receive payments in your overseas bank account from Indian customers. Reach Indian buyers without having to set up an office in India. <a href="https://www.cashfree.com/contact-sales"><b>Get in touch for details.</b></a> </p> </div> <div className="single"> <h3>Connect PayPal</h3> <p className="cashgram-tab-text">Offer PayPal as an international payment option on your checkout page. Connect your PayPal account with Cashfree and accept international payments in minutes. Learn more.</p> </div> <div className="single"> <h3>Pay Later and EMI</h3> <p className="cashgram-tab-text">Offer your customers the convenience of Buy Now, Pay Later through Cashfree's platform. Enable multiple Pay Later and cardless credit EMI options with a single integration.</p> </div> </div> <div className="col-md-6"> <div className="single"> <h3>Multi-currency Payments</h3> <p className="cashgram-tab-text">Accept international payments in 30 currencies including USD, GBP, EUR, AED, CAD. Convert currency dynamically from INR during checkout. View list of <a href="https://docs.cashfree.com/docs/resources/#currencies"><b>supported currencies</b></a></p> </div> <div className="single"> <h3>Connect PayTM</h3> <p className="cashgram-tab-text">Offer PayTM as a checkout option along with Cashfree's payment gateway.</p> </div> </div> </div> </div> </Tab> <Tab eventKey="INTEGRATION" title="INTEGRATION"> <div className="icon-holder"> <p className="bounce_button"><a target="_blank" href="https://www.cashfree.com/shopify-payment-gateway-india/"> <img src="/images/pg/php.png" alt="Cashfree" /> </a></p> <p className="bounce_button"><a target="_blank" href="https://www.cashfree.com/woocommerce-payment-gateway-india/"> <img src="/images/pg/java.png" alt="Cashfree" /> </a></p> <p className="bounce_button"><a target="_blank" href="https://www.cashfree.com/magento-payment-gateway-india/"> <img src="/images/pg/python.png" alt="Cashfree" /> </a></p> <p className="bounce_button"><a target="_blank" href="https://docs.cashfree.com/docs/opencart/guide/"> <img src="/images/pg/nodejs.png" alt="Cashfree" /> </a></p> <p className="bounce_button"><a target="_blank" href="https://docs.cashfree.com/docs/opencart/guide/"> <img src="/images/pg/ios.png" alt="Cashfree" /> </a></p> <p className="bounce_button"><a target="_blank" href="https://docs.cashfree.com/docs/opencart/guide/"> <img src="/images/pg/android.png" alt="Cashfree" /> </a></p> </div> <div className="cashfree-block"> <div className="row cashfree-block-padding"> <div className="col-md-6"> <div className="single"> <h3> <a href="https://docs.cashfree.com/docs/web/guide/">Checkout Form</a> </h3> <p className="cashgram-tab-text"> Simple and easy integration, get started in less than an hour. </p> </div> <div className="single"> <h3> <a href="https://docs.cashfree.com/docs/whitelabel/guide/">Seamless Checkout</a> </h3> <p className="cashgram-tab-text">Design your payment form and seamlessly accept payments on your website</p> </div> <div className="single"> <h3> <a href="http://docs.cashfree.com/docs/hosted/guide/">Embedded Checkout</a> </h3> <p className="cashgram-tab-text">Allow customers to pay on your webpage without any redirects.</p> </div> </div> <div className="col-md-6"> <div className="single"> <h3> <a href="https://docs.cashfree.com/docs/android/guide/">Mobile SDKs</a> </h3> <p className="cashgram-tab-text">Latest features optimized for mobile - Saved cards, Auto OTP reader helping faster checkout.</p> </div> </div> </div> </div> </Tab> </Tabs> </div> </Col> </Row> </Container> </section> ) const Faqs = () => <section className="page_section"> <Container> <Row> <Col md={8} xs={12} className="m-auto"> <div className="text-center"> <h2 className="page_head"> Payment Gateway Integration FAQs </h2> </div> </Col> </Row> <Row> <Col md={8} xs={12} className="m-auto"> <div className="faqs"> <PgFaqs/> </div> </Col> </Row> </Container> </section>; const Subscription = () => ( <div> <NextSeo title="International Payment Gateway India [Lowest Pricing]" keywords="payment gateway india,best payment gateway,best payment gateway india,payment gateway integration,payment gateway integration India,international payment gateway" description="Payment Gateway Integration: Are you a business looking for a Payment Gateway in India with Zero Setup Fee, Zero Maintenance fee, Lowest Pricing and a 2 Day Settlement Cycle?" /> <Header/> <Banner/> <Pgcrads/> <PgFeatures/> <IntegrationTabs/> <Integration/> <PaymentLink/> <Faqs/> <CtaSection/> <Footer/> </div> ) export default Subscription
aa67efc29ce8d996f8a87cfdf6190f2ec76c585c
[ "JavaScript", "Markdown" ]
15
JavaScript
celestialized/next-website
0177da0bae1d3ff9db335bbf26e069f4d56324b9
eea6c6affeb7109b865b283641ce5af99420e47a
refs/heads/master
<repo_name>Homely/Homely.AspNetCore.Hosting.CoreApp<file_sep>/CODE_OF_CONDUCT.md # Contributor Covenant Code of Conduct Please refer to the [code of conduct](https://github.com/Homely/Homely/blob/master/CODE_OF_CONDUCT.md) document that applies to all repositories in the (GitHub) Homely organisation. ---<file_sep>/src/Homely.AspNetCore.Hosting.CoreApp/MainOptions.cs namespace Homely.AspNetCore.Hosting.CoreApp { public class MainOptions { /// <summary> /// Command line arguments. /// </summary> public string[] CommandLineArguments { get; set; } /// <summary> /// Optional text which is first displayed when the application starts. /// </summary> /// <remarks>This can be useful to help determine if things have started and are working ok.</remarks> public string FirstLoggingInformationMessage { get; set; } /// <summary> /// Write the assembly name, version and date information to the logger? /// </summary> public bool LogAssemblyInformation { get; set; } = true; /// <summary> /// Optional text which is last displayed when the application stops. /// </summary> /// <remarks>This could be useful to help determine when things are finally stopping.</remarks> public string LastLoggingInformationMessage { get; set; } /// <summary> /// The name of the Environment Variable which contains the 'Environment' value (e.g. Development, Production, etc). This could be different based on the host - for example, ASP.NET uses ASPNETCORE_ENVIRONMENT as it's default key/value while a console app or background host might be different. /// </summary> /// <remarks>Defaults to <code>ASPNETCORE_ENVIRONMENT</code>.</remarks> public string EnvironmentVariableKey { get; set; } = "ASPNETCORE_ENVIRONMENT"; } } <file_sep>/README.md <div> <p align="center"> <img src="https://imgur.com/9E8hN79.png" alt="Homely - ASP.NET Core MVC Helpers" /> </p> </div> # Homely - ASP.NET Core 'Hosting' core application-library. This application-library contains an opinioned `program.cs` class which is to reduce the ceremony for creating ASP.NET Core "Web Hosting" applications. Basically, we (at Homely) use the same `program.cs` code for litterally all of our microservices. So instead of just copying/pasting this code or having [this same code in our Template](https://github.com/Homely/Homely.AspNetCore.WebApi.Template), we've provided this code as a NuGet package so it's easy to update all-or-any microservice if we decide to change something (e.g. we decide to change to a different logging framework). NOTE: This is a `netcoreapp` application and not a `netstandard` library. So it can only be referenced in another `netcoreapp` .NET Core Application. [![Build status](https://ci.appveyor.com/api/projects/status/m97lxr4ytwvmhfqj/branch/master?svg=true)](https://ci.appveyor.com/project/Homely/homely-aspnetcore-hosting-coreapp/branch/master) --- ## Why use this? What's wrong with the default standard program.cs? We're just _extending_ the default `program.cs` content that comes out of the box by: - Wrapping the default code inside `Serilog` error handling. So if _any_ error occurs at any stage of the program (most importantly, at the EARLY starting/initialization stages, `Serilog` will nicely handle this. - Logging some important*** information about the web api: assembly date, version and when this program first started. That's it :) Reducing boilerplate code. *** We (at Homely) thinks this is important! --- ## How to use this library 1. install-package Homely.AspNetCore.Hosting.CoreApp.Program.Main into your ASP.NET Core application. 2. Reference the `Main<T>` method. You can optionally provide some customization ... if you feel like it. ## Simple quickstart ``` public static Task Main(string[] args) { return Homely.AspNetCore.Hosting.CoreApp.Program.Main<Startup>(args); } ``` NOTE: the `Startup` class should be _your_ `Startup.cs` class. ## More customized startup ``` public static Task Main(string[] args) { var options = new MainOptions { CommandLineArguments = args, FirstLoggingInformationMessage = "~~ Accounts Web Api ~~", LogAssemblyInformation = true, LastLoggingInformationMessage = "-- Accounts Web Api has ended/terminated --", EnvironmentVariableKey = "ASPNETCORE_ENVIRONMENT" }; return Homely.AspNetCore.Hosting.CoreApp.Program.Main<Startup>(options); } ``` --- ## Contributing Discussions and pull requests are encouraged :) Please ask all general questions in this repo or pick a specialized repo for specific, targetted issues. We also have a [contributing](https://github.com/Homely/Homely/blob/master/CONTRIBUTING.md) document which goes into detail about how to do this. ## Code of Conduct Yep, we also have a [code of conduct](https://github.com/Homely/Homely/blob/master/CODE_OF_CONDUCT.md) which applies to all repositories in the (GitHub) Homely organisation. ## Feedback Yep, refer to the [contributing page](https://github.com/Homely/Homely/blob/master/CONTRIBUTING.md) about how best to give feedback - either good or needs-improvement :) --- <file_sep>/src/WebApplication1/Program.cs using System.Threading.Tasks; using Homely.AspNetCore.Hosting.CoreApp; namespace WebApplication1 { public class Program { public static Task Main(string[] args) { var options = new MainOptions { CommandLineArguments = args, FirstLoggingInformationMessage = "~~ Test Web Api ~~", LogAssemblyInformation = true, LastLoggingInformationMessage = "-- Test Web Api has ended/terminated --" }; return Homely.AspNetCore.Hosting.CoreApp.Program.Main<Startup>(options); } } } <file_sep>/CONTRIBUTING.md # Contributing Please refer to the [contributing](https://github.com/Homely/Homely/blob/master/CONTRIBUTING.md) document that applies to all repositories in the (GitHub) Homely organisation. ---<file_sep>/src/Homely.AspNetCore.Hosting.CoreApp/Program.cs using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Core; namespace Homely.AspNetCore.Hosting.CoreApp { public static class Program { private static readonly string Explosion = @"" + Environment.NewLine + "" + Environment.NewLine + "" + Environment.NewLine + " ____" + Environment.NewLine + " __,-~~/~ `---." + Environment.NewLine + " _/_,---( , )" + Environment.NewLine + " __ / < / ) \\___" + Environment.NewLine + "- ------===;;;'====------------------===;;;===----- - -" + Environment.NewLine + " \\/ ~\"~\"~\"~\"~\"~\\~\"~)~\"/" + Environment.NewLine + " (_ ( \\ ( > \\)" + Environment.NewLine + " \\_(_<> _>'" + Environment.NewLine + " ~ `-i' ::>|--\"" + Environment.NewLine + " I;|.|.|" + Environment.NewLine + " <|i::|i|`." + Environment.NewLine + " (` ^'\"`-' \")" + Environment.NewLine + "------------------------------------------------------------------" + Environment.NewLine + "[Nuclear Explosion Mushroom by Bill March]" + Environment.NewLine + "" + Environment.NewLine + "------------------------------------------------" + Environment.NewLine + ""; /// <summary> /// The program's main start/entry point. Hold on to your butts .... here we go! /// </summary> /// <typeparam name="T">Startup class type.</typeparam> /// <param name="args">Optional command line arguments.</param> /// <returns>Task of this Main application run.</returns> public static async Task Main<T>(string[] args) where T : class { var options = new MainOptions { CommandLineArguments = args }; await Main<T>(options); } /// <summary> /// The program's main start/entry point. Hold on to your butts .... here we go! /// </summary> /// <typeparam name="T">Startup class type.</typeparam> /// <param name="options">Options to help setup/configure your program.</param> /// <returns>Task of this Main application run.</returns> public static async Task Main<T>(MainOptions options) where T : class { try { if (options is null) { throw new ArgumentNullException(nameof(options)); } // Before we do _ANYTHING_ we need to have a logger so we can start // seeing what is going on ... good or bad. Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(GetConfigurationBuilder(options.EnvironmentVariableKey)) .Enrich.FromLogContext() .CreateLogger(); // Display any (optional) initial banner / opening text to define the start of this application now starting. if (!string.IsNullOrWhiteSpace(options.FirstLoggingInformationMessage)) { Log.Information(options.FirstLoggingInformationMessage); } if (options.LogAssemblyInformation) { var assembly = typeof(T).Assembly; var assemblyDate = string.IsNullOrWhiteSpace(assembly.Location) ? "-- unknown --" : File.GetLastWriteTime(assembly.Location).ToString("u"); var assemblyInfo = $"Name: {assembly.GetName().Name} | Version: {assembly.GetName().Version} | Date: {assemblyDate}"; Log.Information(assemblyInfo); } await CreateHostBuilder<T>(options.CommandLineArguments).Build() .RunAsync(); } catch (Exception exception) { const string errorMessage = "Something seriously unexpected has occurred while preparing the Host. Sadness :~("; // We might NOT have created a logger ... because we might be _trying_ to create the logger but // we have some bad setup-configuration-data and boom!!! No logger successfully setup/created. // So, if we do have a logger created, then use it. if (Log.Logger is Logger) { // TODO: Add metrics (like Application Insights?) to log telemetry failures. Log.Logger.Fatal(exception, errorMessage); } else { // Nope - failed to create a logger and we have a serious error. So lets // just fall back to the Console and _hope_ someone can read/access that. Console.WriteLine(Explosion); Console.WriteLine(errorMessage); Console.WriteLine(); Console.WriteLine(); Console.WriteLine($"Error: {exception.Message}"); Console.WriteLine(); } } finally { var shutdownMessage = string.IsNullOrWhiteSpace(options.LastLoggingInformationMessage) ? "Application has now shutdown." : options.LastLoggingInformationMessage; // Again: did we successfully create a logger? if (Log.Logger is Logger) { Log.Information(shutdownMessage); // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) Log.CloseAndFlush(); } else { Console.WriteLine(shutdownMessage); } } } private static IConfiguration GetConfigurationBuilder(string environmentVariableKey) { return new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true) .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable(environmentVariableKey) ?? "Production"}.json", optional: true) .AddEnvironmentVariables() .Build(); } public static IHostBuilder CreateHostBuilder<T>(string[] args) where T : class => CreateHostBuilder<T>(new MainOptions { CommandLineArguments = args }); public static IHostBuilder CreateHostBuilder<T>(MainOptions options) where T : class => Host.CreateDefaultBuilder(options.CommandLineArguments) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<T>() .UseConfiguration(GetConfigurationBuilder(options.EnvironmentVariableKey)) .UseSerilog(); }); } }
15442ab0d8a250a4147cc3bfbac9f8167a2d5c1c
[ "Markdown", "C#" ]
6
Markdown
Homely/Homely.AspNetCore.Hosting.CoreApp
fe23c41d6391e40322e16dce043b491ca0d30d7c
1f6d29bbdacaaa2bfa8469e6c124a67afa7661df
refs/heads/master
<repo_name>adityanaganath/Factbook-Analyzer<file_sep>/src/MainFrame.java import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.border.Border; import javax.swing.border.TitledBorder; /**GUI - Main frame which extends JFrame * Constructor initializes relevant IVs * Create a scrollable pane and big buttons corresponding to a factoid * User is promped to enter input with error messages displayed for * incorrect input * * @author adityanaganath * */ public class MainFrame extends JFrame { private WebPageAnalyzer analyzer; private JPanel questionAnswers; private JTextPane text; private String questionAnswerList; private JButton firstButton; private JButton secondButton; private JButton thirdButton; private JButton fourthButton; private JButton fifthButton; private JButton sixthButton; private JButton seventhButton; private JButton eigthButton; private JButton ninthButton; private JButton tenthButton; public MainFrame() throws IOException, ClassNotFoundException, NullPointerException, Exception{ analyzer = new WebPageAnalyzer(); questionAnswers = new JPanel(); text = new JTextPane(); questionAnswerList =""; initialize(); setSize(800, 800); setTitle("Totally Cool Analyzer"); setDefaultCloseOperation(EXIT_ON_CLOSE); setBackground(Color.BLACK); setVisible(true); } public void initialize() { JPanel mainPanel = (JPanel) getContentPane(); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, getButtons(), AnswerPanel()); // creates a split panel splitPane.setResizeWeight(0.5); // sets size splitPane.setDividerLocation(600); mainPanel.setLayout(new BorderLayout()); mainPanel.add(splitPane, BorderLayout.CENTER); } private JPanel getButtons() { JPanel panel = new JPanel(); panel.setLayout(new GridLayout(0, 2)); firstButton = new JButton("Question 1:Natural Hazards"); secondButton = new JButton("Question 2: Elevation Points"); thirdButton = new JButton("Question 3: Hemispheres"); fourthButton = new JButton("Question 4: Political Parties"); fifthButton = new JButton("Question 5: Flags"); sixthButton = new JButton("Question 6: Electricity Consumption per capita"); seventhButton = new JButton("Question 7: Landlocked by single countries"); eigthButton = new JButton("Question 8: Most capitals in 10x10 grid"); ninthButton = new JButton("WildCard: Island countries;"); tenthButton = new JButton("WildCard: Dictatorship"); panel.add(firstButton); panel.add(secondButton); panel.add(thirdButton); panel.add(fourthButton); panel.add(fifthButton); panel.add(sixthButton); panel.add(seventhButton); panel.add(eigthButton); panel.add(ninthButton); panel.add(tenthButton); addListeners(); return panel; } private void addListeners() { addLisButton1(); addLisButton2(); addLisButton3(); addLisButton4(); addLisButton5(); addLisButton6(); addLisButton7(); addLisButton8(); addLisButton9(); addLisButton10(); } private void addLisButton10(){ tenthButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if(!(isEmpty(getAnswer10()))){ questionAnswerList += "Answer 10 \n Countries are: \n" + getAnswer10() +"\n \n"; text.setText(questionAnswerList); } else{ JOptionPane.showMessageDialog(null, "ERROR! You entered something wrong!", " ERROR", JOptionPane.ERROR_MESSAGE); } } catch (IOException e) { JOptionPane.showMessageDialog(null, "ERROR! You entered something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } catch (ClassNotFoundException e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } } private String getAnswer10() throws IOException, ClassNotFoundException { return analyzer.Question10(); } }); } private void addLisButton9(){ ninthButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if(!(isEmpty(getAnswer9()))){ questionAnswerList += "Answer 9 \n Countries are: \n" + getAnswer9() +"\n \n"; text.setText(questionAnswerList); } else{ JOptionPane.showMessageDialog(null, "ERROR! You entered something wrong!", " ERROR", JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } } private String getAnswer9() throws Exception { return analyzer.Question9(); } }); } private void addLisButton6() { sixthButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if(!(isEmpty(getAnswer6()))){ questionAnswerList += "Answer 6 \n Countries are: \n" + getAnswer6() +"\n \n"; text.setText(questionAnswerList); } else{ JOptionPane.showMessageDialog(null, "ERROR! You entered something wrong!", " ERROR", JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } } }); } private void addLisButton5() { fifthButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String color = JOptionPane .showInputDialog("Please enter the color"); try { if(!(isEmpty(getAnswer5(color)))){ questionAnswerList += "Answer 5 \n Countries are: \n" + getAnswer5(color) +"\n \n"; text.setText(questionAnswerList); } else{ JOptionPane.showMessageDialog(null, "ERROR! You entered something wrong!", " ERROR", JOptionPane.ERROR_MESSAGE); } } catch (IOException e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } } }); } private void addLisButton4() { fourthButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String continent = JOptionPane .showInputDialog("Please enter the continent"); String number = JOptionPane .showInputDialog("Please enter the number of parties"); try { if(!(isEmpty(getAnswer4(continent, number)))){ questionAnswerList += "Answer 4 \n Countries are: \n" + getAnswer4(continent,number) +"\n \n"; text.setText(questionAnswerList); } else{ JOptionPane.showMessageDialog(null, "ERROR! You entered something wrong!", " ERROR", JOptionPane.ERROR_MESSAGE); } } catch (IOException e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } } }); } private void addLisButton3() { thirdButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String hemisphere = JOptionPane .showInputDialog("Please enter the hemisphere"); try { if(!(isEmpty(getAnswer3(hemisphere)))) {questionAnswerList += "Answer 3 \n Countries are: \n" + getAnswer3(hemisphere) +"\n \n"; text.setText(questionAnswerList);} else{ JOptionPane.showMessageDialog (null, "ERROR! You entered something wrong! Your options are northeast, northwest, southeast,southwest", " ERROR", JOptionPane.ERROR_MESSAGE); } } catch (IOException e) { JOptionPane.showMessageDialog (null, "ERROR! You did something wrong! Your options are northeast, northwest, southeast,southwest", " ERROR", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog (null, "ERROR! You did something wrong! Your options are northeast, northwest, southeast,southwest", " ERROR", JOptionPane.ERROR_MESSAGE); } } }); } private void addLisButton8() { eigthButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String degreesString = JOptionPane .showInputDialog("Please enter the dimension of the grid"); try { double degrees = Double.parseDouble(degreesString); if(!(isEmpty(getAnswer8(degrees)))){ questionAnswerList += "Answer 8 \n Countries are: \n" + getAnswer8(degrees) +"\n \n"; text.setText(questionAnswerList); } else{ JOptionPane.showMessageDialog(null, "ERROR! You entered something wrong!", " ERROR", JOptionPane.ERROR_MESSAGE); } } catch (HeadlessException e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try againd!", " ERROR", JOptionPane.ERROR_MESSAGE); } } }); } private void addLisButton2() { secondButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String continent = JOptionPane .showInputDialog("Please enter the continent"); try { if(!(isEmpty(getAnswer2(continent)))){ questionAnswerList += "Answer 2 \n Countries are: \n" + getAnswer2(continent) +"\n \n"; text.setText(questionAnswerList); } else{ JOptionPane.showMessageDialog(null, "ERROR! You entered something wrong!", " ERROR", JOptionPane.ERROR_MESSAGE); } } catch (HeadlessException e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } } }); } private void addLisButton1() { firstButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String continent = JOptionPane .showInputDialog("Please enter the continent"); String hazard = JOptionPane .showInputDialog("Please enter the hazard"); try { if(!(isEmpty(getAnswer(continent, hazard)))){ questionAnswerList += "Answer 1 \n Countries are: \n" + getAnswer(continent,hazard) +"\n \n"; text.setText(questionAnswerList); } else{ JOptionPane.showMessageDialog(null, "ERROR! You entered something wrong!", " ERROR", JOptionPane.ERROR_MESSAGE); } } catch (IOException e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } catch (ClassNotFoundException e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } catch (HeadlessException e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } } }); } private void addLisButton7() { seventhButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { questionAnswerList += "Answer 7 \n Countries are: \n" + getAnswer7() +"\n \n"; text.setText(questionAnswerList); } catch (IOException e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "ERROR! You did something wrong! Try again!", " ERROR", JOptionPane.ERROR_MESSAGE); } } }); } /** * Calling relevant question answer * @param a * @param b * @return * @throws Exception */ private String getAnswer(String a, String b) throws Exception{ return analyzer.Question1(a,b); } private String getAnswer2(String continent) throws IOException, ClassNotFoundException, Exception{ return analyzer.Question2(continent); } private String getAnswer3(String hemisphere) throws IOException, ClassNotFoundException, Exception{ return analyzer.Question3(hemisphere); } private String getAnswer4(String continent, String number) throws IOException, ClassNotFoundException, Exception{ return analyzer.Question4(continent, number); } private String getAnswer5(String color) throws IOException, ClassNotFoundException, Exception{ return analyzer.Question5(color); } private String getAnswer6() throws IOException, ClassNotFoundException, Exception{ return analyzer.Question6(); } private String getAnswer7() throws IOException, Exception{ return analyzer.question7(); } private String getAnswer8(double degrees) throws IOException, ClassNotFoundException, Exception{ return analyzer.Question8(degrees); } private Boolean isEmpty(String answer){ if(answer.length() == 0){ return true; } else return false; } private JScrollPane AnswerPanel(){ questionAnswers.setLayout(new BorderLayout()); JScrollPane scrollable = new JScrollPane(questionAnswers); // adds title and //border to button //panel Border etchedBorder = BorderFactory.createEtchedBorder(); Border border = BorderFactory.createTitledBorder(etchedBorder, "Answers", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Serif", Font.BOLD, 20), Color.WHITE); questionAnswers.setBorder(border); questionAnswers.setBackground(Color.LIGHT_GRAY); text.setEditable(false); questionAnswers.add(text,BorderLayout.CENTER); return scrollable; } }
0bf2d62bfc4d3430b364712b44328b4768f447f9
[ "Java" ]
1
Java
adityanaganath/Factbook-Analyzer
d564e484be9cc90c4b47c809467b0f3ce0d22834
3dbd1dd3cebff90aa0c85b6f835b339b51ae1089
refs/heads/master
<file_sep>package links; import java.io.IOException; import java.io.StringReader; import java.sql.Timestamp; import java.util.HashSet; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.json.simple.JSONObject; import org.w3c.dom.*; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class SyntheticClientPayload { public JSONObject payload; public SyntheticClientPayload(){ } // public String strinize(JSONObject received){ // // } public JSONObject destrinize(String mqttMsg){ int res = 1; Document doc = loadXMLFromString(mqttMsg); if(doc ==null){ System.out.println("Error: could not parse XML stream"); return null; } doc.getDocumentElement().normalize(); if(doc.getDocumentElement().getNodeName()==null){ res = 0; return null; } payload = new JSONObject(); if(res!=0){ if(doc.getElementsByTagName("timeStamp").getLength()>0){ payload.put("timeStamp",doc.getElementsByTagName("timeStamp").item(0).getTextContent().trim()); } if(doc.getElementsByTagName("element_id").getLength()>0){ payload.put("elementId",doc.getElementsByTagName("element_id").item(0).getTextContent().trim()); } if(doc.getElementsByTagName("source_id").getLength()>0){ payload.put("sourceId",doc.getElementsByTagName("source_id").item(0).getTextContent().trim()); } if(doc.getElementsByTagName("trigger").getLength()>0){ payload.put("trigger",doc.getElementsByTagName("trigger").item(0).getTextContent().trim()); } if(doc.getElementsByTagName("readingType").getLength()>0){ payload.put("readingType",doc.getElementsByTagName("readingType").item(0).getTextContent().trim()); } if(doc.getElementsByTagName("payload").getLength()>0){ payload.put("payload",doc.getElementsByTagName("payload").item(0).getTextContent().trim()); } if(doc.getElementsByTagName("notes").getLength()>0){ payload.put("notes",doc.getElementsByTagName("notes").item(0).getTextContent().trim()); } } return payload; } public Document loadXMLFromString(String xml){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); StringReader lector = new StringReader(xml); InputSource inp = new InputSource(lector); Document doc = builder.parse(inp); return doc; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
ce613cd721caff830faa051f10db6b4c553c573c
[ "Java" ]
1
Java
pepscasanovas/listenerjava
3228d1c2b1e3e97671377e96b733fa04ac0ee639
5b5c145b7381fe48f47dc8bb42c6727ebb9322f5
refs/heads/master
<file_sep>#ifndef functions_H #define functions_H #include <iostream> #include <vector> #include <map> #include <set> #include <string> using std::vector; using std::map; using std::set; using std::cout; using std::cin; using std::endl; using std::string; //Devided function for part 1 (exceptions) double divided(double a, double b) { if (b == 0) throw 0; else return a / b; } //Template part 2 template <typename W> W wordCombine(W a, W b) { return a + " " + b; } //AddWord function for part 3 (STL) void addWord(vector<string>* v) { int number; string newWord; cout << endl; cout << "How many word would you like to add: "; cin >> number; for (int i = 1; i <= number; i++) { cout << "Please enter a preferrable word: "; cin >> newWord; v->push_back(newWord); } cout << endl; } //DeleteWord function for part 3 (STL) void deleteWord(vector<string>* v) { string eraseWord; cout << endl; cout << "What word do you want to delete: "; cin >> eraseWord; vector<string>::iterator newEraseWord = find(v->begin(), v->end(), eraseWord); v->erase(newEraseWord); cout << "Now, you have " << v->size() << " word(s) available" << endl << endl; } //Greatest common divisor part 4 int gcd(int a, int b) { //Making negative number be positive number if (a < 0) a *= -1; if (b < 0) b *= -1; //Base case if (a == 0) return b; if (b == 0) return a; //Recusive case if (a > b) return gcd(a - b, b); else return gcd(a, b - a); } //Fibonacci part 4 int fib(int n) { //Error check if (n < 1) throw "ERROR: Invalid number"; //Base case if (n == 1 || n == 2) return 1; //Recursive case return fib(n - 1) + fib(n - 2); } //Power part 4 int pow(int a, int b) { //Error check if (b < 0) throw "ERROR: Invalid exponent"; //Base case if (b == 0) return 1; //Recursive case return a * pow(a, b - 1); } //Triangular part 4 int tri(int n) { //Error check if (n <= 0) throw "ERROR: Invalid number"; //Base case if (n == 1) return 1; //Recursive case return n + tri(n - 1); } //Greatest common divisor part 5 int gcd_iter(int a, int b) { if (a == b) return a; else { int gcd = 0; while (b != 0) { int temp = a%b; if (temp == 0) gcd = b; a = b; b = temp; } return gcd; } } //Fibonacci part 5 int fib_iter(int n) { //Error check if (n < 1) throw "ERROR: Invalid number"; if (n == 1 || n == 2) return 1; else { int n1 = 1, n2 = 1, fib = 0; for (int i = 3; i <= n; i++) { fib = n1 + n2; n1 = n2; n2 = fib; } return fib; } } //Power part 5 int pow_iter(int a, int b) { //Error check if (b < 0) throw "ERROR: Invalid exponent"; int pow = 1; for (int i = 0; i < b; i++) { pow *= a; } return pow; } //Triangular part 5 int tri_iter(int n) { //Error check if (n <= 0) throw "ERROR: Invalid number"; int tri = 0; for (int i = 1; i <= n; i++) { tri += i; } return tri; } #endif <file_sep>/* ---------------------------------------------------------------------------- * Copyright &copy; 2016 <NAME> <<EMAIL>> * Released under the [MIT License] (http://opensource.org/licenses/MIT) * ------------------------------------------------------------------------- */ /* * A series of programs including exceptions, template, STL (Vector, Set, Map) and recursive/iterative functions */ /* References: http://stackoverflow.com/questions/8777603/what-is-the-simplest-way-to-convert-array-to-vector http://stackoverflow.com/questions/5333113/how-to-pass-a-vector-to-a-function http://www.cplusplus.com/forum/beginner/99524/ http://www.cplusplus.com/forum/beginner/25649/ */ #include <string> #include <random> #include <time.h> #include <array> #include <algorithm> #include "functions.h" int main() { //Declarations bool isYes = true; double a = 0, b = 0; const int SIZE = 5; string word[5]{}; int rand1, rand2; int choice; string yourFruit; string monthInsert; cout << "Assignment 3: <NAME>" << endl; /*------------------------------------------------------------------- Part 1 - Exceptions*/ cout << endl; cout << "------------" << endl; cout << "--Division--" << endl; cout << "------------" << endl; do { cout << "Please enter the first number: "; cin >> a; cout << "Please enter the second number: "; cin >> b; try { cout << "Your answer is " << divided(a, b) << endl; } catch (int b) { cout << "You cannot have 0 as a denominator. Please try again" << endl << endl; continue; } cout << endl << "Do you want to do it again? (1 = yes, 0 = no): "; cin >> isYes; } while (isYes); /*------------------------------------------------------------------- End of part 1 - Exceptions*/ /*------------------------------------------------------------------- Part 2 - Template*/ cout << endl; cout << "------------------" << endl; cout << "--Name Generator--" << endl; cout << "------------------" << endl; for (int i = 0; i < SIZE; i++) { cout << "Please enter a preferrable word #" << i + 1 << " : "; cin >> word[i]; } do { srand(time(0)); rand1 = rand() % 5; rand2 = rand() % 5; cout << endl << "This is the random name from your entered words: "; cout << wordCombine(word[rand1], word[rand2]) << endl; cout << endl << "Do you want to generate again? (1 = yes, 0 = no): "; cin >> isYes; } while (isYes); /*------------------------------------------------------------------- End of Part 2 - Template*/ /*------------------------------------------------------------------- Part 3 - STL (vector)*/ cout << endl; cout << "-------------------------------------" << endl; cout << "--Vector : Word management (vector)--" << endl; cout << "-------------------------------------" << endl; //Copy word[] to vector vector<string> v(std::begin(word), std::end(word)); do { isYes = true; cout << "==Menu==" << endl; cout << "1.) Add more word" << endl; cout << "2.) Delete unpreferrable word" << endl; cout << "3.) Show all words you have" << endl; cout << "4.) Exit" << endl << endl; cout << "Please select your choice: "; cin >> choice; switch (choice) { case 1: addWord(&v); break; case 2: deleteWord(&v); break; case 3: cout << endl << "Your word(s): "; for (string name : v) { cout << name << " "; } cout << endl << endl; break; default: isYes = false; break; } } while (isYes); /*------------------------------------------------------------------- End of Part 3 - STL (vector)*/ /*------------------------------------------------------------------- Part 3 - STL (set)*/ cout << endl; cout << "-----------------------------" << endl; cout << "--Vector : Fruit list (set)--" << endl; cout << "-----------------------------" << endl; isYes = true; std::set<string> fruit{ "banana", "orange", "pineapple", "grape", "cherry" }; do { cout << endl << "We have a list of fruits, please enter any fruit name: "; cin >> yourFruit; auto search = fruit.find(yourFruit); if (search != fruit.end()) { cout << endl; cout << (*search) << " is already in the list! Please try again" << endl; } else { cout << endl; cout << yourFruit << " is not found in the list and I just added "; fruit.insert(yourFruit); cout << yourFruit << " into the list!" << endl << endl; cout << "Would you like to do another? (1 = yes, 0 = no): "; cin >> isYes; } } while (isYes); cout << endl << "Here is all the fruits we have in the list: "; cout << endl; for (string fruitList : fruit) { cout << fruitList << " "; } cout << endl << endl; /*------------------------------------------------------------------- End of Part 3 - STL (set)*/ /*------------------------------------------------------------------- Part 3 - STL (map)*/ cout << endl; cout << "-----------------------------" << endl; cout << "--Vector : Months (map)--" << endl; cout << "-----------------------------" << endl; isYes = true; std::map<string, int> month = { {"january", 31}, {"february", 28}, {"march", 31}, {"april", 30}, {"may", 31}, {"june", 30}, {"july", 31}, {"august", 31}, {"september", 30}, {"october", 31}, {"november", 30}, {"november", 31} }; do { cout << "Please enter a month name: "; cin >> monthInsert; //Convert to all lowercase for (int i = 0; i < monthInsert.length(); i++) { monthInsert[i] = tolower(monthInsert[i]); } auto find = month.find(monthInsert); if (find != month.end()) { cout << find->first << " has " << find->second << " days." << endl << endl; cout << "Would you like to check other month? (1 = yes, 0 = no): "; cin >> isYes; } else { cout << "Please try again." << endl; } } while (isYes); /*------------------------------------------------------------------- End of Part 3 - STL (map)*/ /*------------------------------------------------------------------- Part 4 & 5 - Recursive/Iterative*/ cout << endl; cout << "------------------------------------" << endl; cout << "--Part 4 & 5 : Recursive/Iterative--" << endl; cout << "------------------------------------" << endl; isYes = true; rand1 = rand() % 5 + 1; rand2 = rand() % 5 + 1; cout << endl; do { try { cout << "(Recursive) Greatest Common Divisor for number " << rand1 << " and " << rand2 << " is " << gcd(rand1, rand2) << endl; cout << "(Iterative) Greatest Common Divisor for number " << rand1 << " and " << rand2 << " is " << gcd_iter(rand1, rand2) << endl << endl; cout << "(Recursive) Fibonacci number for index number " << rand1 << " is " << fib(rand1) << endl; cout << "(Iterative) Fibonacci number for index number " << rand1 << " is " << fib_iter(rand1) << endl << endl; cout << "(Recursive) Power for base " << rand1 << " and exponent " << rand2 << " is " << pow(rand1, rand2) << endl; cout << "(Iterative) Power for base " << rand1 << " and exponent " << rand2 << " is " << pow_iter(rand1, rand2) << endl << endl; cout << "(Recursive) Triangular number for number " << rand1 << " is " << tri(rand1) << endl; cout << "(Iterative) Triangular number for number " << rand1 << " is " << tri_iter(rand1) << endl << endl; } catch (char * err) { cout << err; } cout << "Would you like to do one more time? (1 = yes, 0 = no): "; cin >> isYes; } while (isYes); /*------------------------------------------------------------------- End of Part 4 & 5 - Recursive/Iterative*/ system("pause"); return 0; }
7c57c014cb97684fc37b52b9a7ce99e117e0ac78
[ "C++" ]
2
C++
suchartee/assignment-03
008482aa7be3cf40b1f6f1b61289d93c76cef42f
2c43e15473fe5508b61e57989ca963dd92a611f3
refs/heads/master
<file_sep># PensamientoComputacionalPython Scripts en Python desarrollados durante el curso de Introducción al Pensamiento Computacional con Python en Platzi 💚 <file_sep>def list_comprension(my_list): pares = [i for i in my_list if i % 2 == 0] doubles = [i**2 for i in my_list] print(f'Pares: {pares}\n') print(f'Dobles: {doubles}\n') my_list = range(100) list_comprension(my_list) <file_sep>def adjacentElementsProduct(inputArray): mult_res = 0 for i in range(len(inputArray) - 1): mult = inputArray[i] * inputArray[i + 1] if mult > mult_res: mult_res = mult return mult_res inputArray = [3, 6, -2, -5, 7, 3, 9, 12, 100, -5] print(inputArray) result = adjacentElementsProduct(inputArray) print(result) <file_sep>def dictionary_comprehension(size_of_numbers): squares = {num: num**2 for num in range(1,size_of_numbers + 1)} cubes = {num: num**3 for num in range(1,size_of_numbers + 1)} doubles = {num: num*2 for num in range(1,size_of_numbers + 1)} print(squares, cubes, doubles) size_of_numbers = int(input('Escribe hasta qué número calcularas los valores cuadrados, al cubo y dobles: ')) dictionary_comprehension(size_of_numbers) <file_sep>def suma(a, b): total = a + b return total def nombre_completo(nombre, apellido, inverso = False): if inverso: return f'{apellido} {nombre}' else: return f'{nombre} {apellido}' res = suma(2, 3) print(res) name1 = nombre_completo('David', 'Aroesti') print(name1) name2 = nombre_completo('David', 'Aroesti', inverso = True) print(name2) name3 = nombre_completo(apellido = 'Aroesti', nombre = 'David') print(name3)<file_sep>def enumeracion(objetivo): respuesta = 0 while respuesta**2 < objetivo: #Enumera todas las soluciones posibles print(respuesta) respuesta += 1 if respuesta**2 == objetivo: #Evalúa las soluciones de acuerdo a las restricciones del problema return respuesta else: print(f'{objetivo} no tiene raíz cuadrada exacta') def aproximacion(objetivo): epsilon = 0.01 paso = epsilon**2 respuesta = 0.0 while abs(respuesta**2 - objetivo) >= epsilon and respuesta <= objetivo: print(abs(respuesta**2 - objetivo), respuesta) respuesta += paso if abs(respuesta**2 - objetivo) >= epsilon: print(f'No se encontro la raíz cuadrada de {objetivo}') else: return respuesta def busq_binaria(objetivo): epsilon = 0.001 bajo = 0.0 alto = max(1.0, objetivo) respuesta = (alto + bajo) / 2 while abs(respuesta**2 - objetivo) >= epsilon: print(f'bajo = {bajo}, alto = {alto}, respuesta = {respuesta}') if respuesta**2 < objetivo: bajo = respuesta else: alto = respuesta respuesta = (alto + bajo) / 2 return respuesta method = input('''Escoge el método para calcular la raíz cuadrada [E]numeración exhaustiva [A]proximación de soluciones [B]úsqueda binaria ''') objetivo = int(input('Escoge un número entero: ')) if method == 'e' or method == 'E': result = enumeracion(objetivo) # print(f'La raíz cuadrada de {objetivo} es {result}') elif method == 'a' or method == 'A': result = aproximacion(objetivo) # print(f'La raíz cuadrada de {objetivo} es {result}') elif method == 'b' or method == 'B': result = busq_binaria(objetivo) # print(f'La raíz cuadrada de {objetivo} es {result}') else: print('No escogiste un método') if result != None: print(f'La raíz cuadrada de {objetivo} es {result}') <file_sep>name = input('¿Cuál es tu nombre?: ') greeting = f'Bienvenido(a) {name}' print(greeting) print(f'La longitud es: {len(greeting)}') <file_sep>while True: name_1 = input('Escribe el nombre de la primera persona: ') age_1 = int(input('Escribe la edad de la persona: ')) name_2 = input('Escribe el nombre de la segunda persona: ') age_2 = int(input('Escribe la edad de la segunda persona: ')) if age_1 > age_2: print(f'{name_1} es mayor que {name_2}') elif age_1 < age_2: print(f'{name_2} es mayor que {name_1}') else: print(f'{name_1} tiene la misma edad que {name_2}') <file_sep>frutas = ['manzana', 'pera', 'mango'] iterador = iter(frutas) print(next(iterador)) print(next(iterador)) print(next(iterador)) print(next(iterador))<file_sep>my_dict = {'Miguel': 25, 'David': 35, 'Juan': 40,} for llave in my_dict.keys(): print(f'Llave: {llave}') for valor in my_dict.values(): print(f'Valor: {valor}') for llave, valor in my_dict.items(): print(f'Llave: {llave}, Valor: {valor}') print('David' in my_dict) <file_sep>def pares(limit): for i in range(0, limit + 1, 2): print(f'Par: {i}') def nones(limit): for i in range(1, limit, 2): print(f'Non: {i}') limit = int(input('Escribe hasta que número imprimir los números pares y nones: ')) pares(limit) nones(limit) <file_sep>def adjacentElementsProduct(inputArray): mult_res = -1000 for i in range(len(inputArray) - 1): mult = inputArray[i] * inputArray[i + 1] if mult > mult_res: mult_res = mult return mult_res inputArray = [-23, 9, -3, 8, -12] print(inputArray) result = adjacentElementsProduct(inputArray) print(result) <file_sep>sumar = lambda x, y: x + y multiplicar = lambda x, y: x * y print(sumar(2,3)) print(multiplicar(3,2)) <file_sep>objetivo = int(input('Escoge un entero: ')) respuesta = 0 while respuesta**2 < objetivo: #Enumera todas las soluciones posibles print(respuesta) respuesta += 1 if respuesta**2 == objetivo: #Evalúa las soluciones de acuerdo a las restricciones del problema print(f'La raíz cuadrada de {objetivo} es {respuesta}') else: print(f'{objetivo} no tiene raíz cuadrada exacta')
9d0f5ca998982ac6486ee2034efa64463b1eb054
[ "Markdown", "Python" ]
14
Markdown
datormx/PensamientoComputacionalPython
14755a2cad188370df6ba5e988c23a02b88b3f94
63f2c70505bf5a0183983c40925798e96633a3fd
refs/heads/master
<file_sep>#coding=utf-8 "程序启动" from MyBlog import create_app from flask.ext.script import Manager from MyBlog import db from MyBlog.models import Like app=create_app('development') manager=Manager(app) @manager.command def deploy(): db.drop_all() db.create_all() like=Like() db.session.add(like) db.session.commit() if __name__=='__main__': manager.run() <file_sep>#coding=utf-8 from flask.ext.wtf import Form from flask.ext.pagedown.fields import PageDownField from wtforms import StringField,SubmitField from wtforms.validators import Required class PostForm(Form): title=StringField('Title',validators=[Required()]) body=PageDownField("Body",validators=[Required()]) summary=PageDownField("Summary",validators=[Required()]) category=StringField('Category',validators=[Required()]) submit=SubmitField('Submit') class EditForm(Form): title=StringField('Title',validators=[Required()]) body=PageDownField("Body",validators=[Required()]) summary=PageDownField("Summary",validators=[Required()]) submit=SubmitField('Submit')<file_sep> #coding=utf-8 "创建main蓝本" from flask import Blueprint main=Blueprint('main',__name__) from . import views <file_sep> #coding=utf-8 from . import main from forms import PostForm,EditForm from flask import render_template,request,current_app,flash,redirect,url_for,jsonify from ..models import Post,Category,Like from MyBlog import db from flask.ext.login import login_required,current_user from flask import abort @main.route('/') def index(): page=request.args.get('page',1,type=int) #按时间降序,最新的文章将在最上面 pagination=Post.query.order_by(Post.timestamp.desc()).paginate( page,per_page=current_app.config['PER_POSTS_PER_PAGE'],error_out=False ) #另外请求的页数超出范围的话, #True表示返回404错误,然后False返回一个空列表 posts=pagination.items categories=Category.query.order_by(Category.count.desc()) return render_template('index.html',posts=posts,pagination=pagination,categories=categories) @main.route('/about') def about_me(): liked=Like.query.get_or_404(1) return render_template('about.html',liked=liked) @main.route('/post/<int:id>',methods=['GET','POST']) def post(id): post=Post.query.get_or_404(id) #查询出来是一个列表 return render_template('post.html',post=post) @main.route('/write',methods=['GET','POST']) @login_required def write(): if not current_user.is_administration(): abort(403) forms=PostForm() #查询到所有标签 categories=Category.query.order_by(Category.count.desc()) if forms.validate_on_submit(): #如果能查询到标签的话 tag = Category.query.filter_by(tag=forms.category.data).first() if tag is not None: post=Post(title=forms.title.data,body=forms.body.data, summary=forms.summary.data,category=tag) tag.count+=1 db.session.add(post) db.session.commit() else: category=Category(tag=forms.category.data,count=1) post=Post(title=forms.title.data,body=forms.body.data, summary=forms.summary.data,category=category) db.session.add(post) db.session.commit() flash('You have written an article') return redirect(url_for('main.index')) return render_template('write.html',form=forms,categories=categories) @main.route('/edit/<int:id>',methods=['GET','POST']) @login_required def edit(id): if not current_user.is_administration(): abort(403) form=EditForm() post=Post.query.get_or_404(id) if form.validate_on_submit(): post.title=form.title.data post.body= form.body.data post.summary=form.summary.data db.session.add(post) db.session.commit() flash("The article has been updated!") return redirect(url_for('main.post',id=id)) form.title.data=post.title form.body.data=post.body form.summary.data=post.summary return render_template('edit.html',form=form) @main.route('/category/<tag>',methods=['GET','POST']) def category(tag): category=Category.query.filter_by(tag=tag).first() posts=category.posts return render_template("category.html",posts=posts,category=category) @main.app_errorhandler(403) def no_permission_error(e): return render_template('403.html'),403 @main.app_errorhandler(404) def not_found(e): return render_template('404.html'),404 @main.app_errorhandler(500) def internal_error(e): return render_template('500.html'),500 @main.route('/like') def like(): like=Like.query.get_or_404(1) like.count=int(like.count)+1 db.session.add(like) db.session.commit() liked=like.count return jsonify({"liked":liked}) <file_sep>{% extends "base.html" %} {% block title %} Write {% endblock%} {% block scripts%} {{super()}} {{ pagedown.include_pagedown() }} {% endblock%} {% block page_content %} <div class="container"> <div class="row"> <div class="col-md-12"> <div style="box-shadow:5px 5px 20px #CCC;background-color:white;padding:20px 30px;margin-bottom:40px;"> <h2 class="text-center">TO WRITE A BLOG!</h2> <!--利用html标签创建一个表单,创建一个水平表单把标签和控件放在一个带有 class .form-group 的 <div> 中。向标签添加 class .control-label。--> <form class="form-horizontal" method="post" action=""> {{ form.csrf_token }} <!--把标签和控件放在一个带有 class .form-group 的 <div> 中。这是获取最佳间距所必需的。--> <div class="form-group"> <label for="inputEmail3" class="col-sm-1 control-label">{{ form.title.label }}</label> <div class="col-sm-11"> <!--placeholder是那种提示性的文本--> {{ form.title(class="form-control",placeholder="the title") }} </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-1 control-label">{{ form.body.label }}</label> <div class="col-sm-11"> {{ form.body(class="form-control",placeholder="the body",rows="20") }} </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-1 control-label">{{ form.summary.label }}</label> <div class="col-sm-11"> {{ form.summary(class="form-control",placeholder="the summary") }} </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-1 control-label">{{ form.category.label }}</label> <div class="col-sm-11"> {% for category in categories %} <div class="col-md-3"><a class="btn btn-info btn-small btn-block form-btn write-form-btn">{{ category.tag }}</a></div> {% endfor %} <div class="col-md-3"><a class="btn btn-info btn-large btn-block col-md-3 form-add write-form-btn">增加tag <span class="glyphicon glyphicon-plus" aria-hidden="true"></span></a></div> </div> </div> <div class="form-group" id="form_category" style="display:none"> <label for="inputEmail3" class="col-sm-1 control-label">{{ form.category.label }}</label> <div class="col-sm-11"> {{ form.category(class="form-control",placeholder="the category") }} </div> </div> <button type="submit" class="btn btn-large btn-block btn-primary">submit</button> </form> </div> </div> </div> </div> {% endblock %}<file_sep>#coding=utf-8 from flask.ext.wtf import Form from wtforms import StringField,PasswordField,SubmitField,BooleanField,ValidationError from wtforms.validators import Required,Email,Length,EqualTo from ..models import User class RegisterForm(Form): email=StringField('Email',validators=[Required(),Email(),Length(1,64)]) password=PasswordField('Password',validators=[Required(),EqualTo('<PASSWORD>',message='password must match')]) password2=PasswordField('Confirmed password',validators=[Required()]) submit=SubmitField('Register') def validate_email(self,field): "一个单独的验证email的函数" if User.query.filter_by(email=field.data).first(): raise ValidationError('Email already register') class LoginForm(Form): email=StringField('Email',validators=[Required(),Email(),Length(1,64)]) password=<PASSWORD>Field('<PASSWORD>',validators=[Required()]) rememberme=BooleanField('Keep me logged in') submit=SubmitField('Log In')<file_sep>#coding=utf-8 from . import auth from .forms import RegisterForm,LoginForm from MyBlog import db from ..models import User from flask import flash,redirect,render_template,url_for,request from flask.ext.login import login_user,login_required,logout_user @auth.route('/register',methods=['GET','POST']) def register(): form=RegisterForm() if form.validate_on_submit(): user=User(email=form.email.data, password=form.password.data) db.session.add(user) db.session.commit() flash('You have registered!') return redirect(url_for('auth.login')) return render_template('auth/register.html',form=form) @auth.route('/login',methods=['GET','POST']) def login(): form=LoginForm() if form.validate_on_submit(): user=User.query.filter_by(email=form.email.data).first() if user is not None and user.verify_password(form.password.data): login_user(user,form.rememberme.data) return redirect(request.args.get('next') or url_for('main.index')) else: flash('Invalid username or password.') return render_template('auth/login.html',form=form) @auth.route('/logout') @login_required def logout(): logout_user() flash('You have been logged out.') return redirect(url_for('main.index')) <file_sep>#coding=utf-8 from MyBlog import db from werkzeug.security import generate_password_hash,check_password_hash from flask.ext.login import UserMixin from . import login_manager from datetime import datetime from markdown import markdown import bleach class User(db.Model,UserMixin): __tablename__='users' id=db.Column(db.Integer,primary_key=True) email=db.Column(db.String(64),unique=True,index=True) password_hash=db.Column(db.String(128)) is_administrator=db.Column(db.Boolean,default=False,index=True) @property def password(self): "定义一个属性,密码不能被读取" raise AttributeError(u'密码不能被读取') @password.setter def password(self,password): "生成密码哈希值" self.password_hash=generate_password_hash(password) def verify_password(self,password): "验证密码" return check_password_hash(self.password_hash,password) def __init__(self,**kwargs): "创建用户的时候首先执行的方法" super(User,self).__init__(**kwargs) if self.email=='<EMAIL>': self.is_administrator=True def is_administration(self): return self.is_administrator def __repr__(self): return '<User %r>'%self.email @login_manager.user_loader def load_user(user_id): "使用指定标识符加载用户" return User.query.get(int(user_id)) class Post(db.Model): """建立一个博文的数据库模型,与User模型存在多对一的关系,但是该网站中, 发表博客的只有一个管理员,因此可以省略该关系,不过该博客与Category表存在多对一的关系 该表为多,因此在该表内建立外键,在Category表中建立反向关系""" __tablename__='posts' id=db.Column(db.Integer,primary_key=True) title=db.Column(db.String(64),index=True,unique=True) body=db.Column(db.Text) body_html=db.Column(db.Text) timestamp=db.Column(db.DateTime,index=True,default=datetime.utcnow) summary=db.Column(db.Text) summary_html=db.Column(db.Text) Category_id=db.Column(db.Integer,db.ForeignKey('categories.id')) @staticmethod def on_changed_body(target,value,oldvalue,initiator): """这里是在服务器上处理富文本,只提交Markdown原文本,在服务器上使用 Markdown转换程序转为HTML,再使用Bleach清理,确保其中只含有几个允许使用的 标签,转换后的博客文章HTML代码存在POST模型的body_html字段里,模板中可以直接调用 然后原文本还需要存储""" allowed_tags=['a','abbr','acronym','b','blockquote','code', 'em','i','li','ol','pre','strong','ul','h1', 'h2','h3','p'] target.body_html=bleach.linkify(bleach.clean(markdown(value, output_format='html'), tags=allowed_tags,strip=True)) @staticmethod def on_changed_summary(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'code', 'blockquote','em', 'i', 'strong','li','ol','pre','strong','ul','h1','h2','h3','p'] target.summary_html = bleach.linkify(bleach.clean(markdown(value, output_format='html'), tags=allowed_tags, strip=True)) #on_changed_body函数注册在body字段上,是SQLAlchemy set事件的监听程序 db.event.listen(Post.body,'set',Post.on_changed_body) db.event.listen(Post.summary, 'set', Post.on_changed_summary) class Category(db.Model): """建立一个目录表,对博文进行分类""" __tablename__='categories' id=db.Column(db.Integer,primary_key=True) tag=db.Column(db.String(64),unique=True) count=db.Column(db.Integer) #禁止自动排序,category可以过在Post的外键访问posts表 posts=db.relationship("Post",backref="category",lazy='dynamic') def add(self): self.count+=1 class Like(db.Model): __tablename__='liked' id=db.Column(db.Integer,primary_key=True) count=db.Column(db.Integer,index=True) def __init__(self): self.count=1 <file_sep>bleach==1.4.2 dominate==2.1.16 flask==0.10.1 flask-bootstrap==3.3.5.7 flask-login==0.3.2 flask-markdown==0.3 flask-pagedown==0.2.1 flask-psycopg2==1.3 flask-script==2.0.5 flask-sqlalchemy==2.1 flask-wtf==0.12 html5lib==1.0b8 itsdangerous==0.24 jinja2==2.8 markdown==2.6.5 markupsafe==0.23 mongoengine==0.10.5 pymongo==3.2 six==1.10.0 sqlalchemy==1.0.11 visitor==0.1.2 werkzeug==0.11.3 wheel==0.24.0 wtforms==2.1 gunicorn==19.4.5 psycopg2==2.5.1 <file_sep>#coding=utf-8 "延迟创建程序实例,将创建移到工厂函数中" from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config from flask.ext.pagedown import PageDown login_manager=LoginManager() login_manager.session_protection='Strong' login_manager.login_view='auth.login' db=SQLAlchemy() pagedown=PageDown() bootstrap=Bootstrap() def create_app(config_name): """使用了flask-pagedown来讲markdown文本转换成HTML文本,方便显示 Markdown富文本编辑器""" app=Flask(__name__) bootstrap.init_app(app) db.init_app(app) login_manager.init_app(app) pagedown.init_app(app) app.config.from_object(config[config_name]) config[config_name].init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) return app<file_sep> import os basedir=os.path.abspath(os.path.dirname(__file__)) class Config: SQLALCHEMY_COMMIT_ON_TEARDOWN=True SQLALCHEMY_TRACK_MODIFICATIONS=True PER_POSTS_PER_PAGE=10 SECRET_KEY='<PASSWORD> guess <PASSWORD>' @staticmethod def init_app(app): pass class DevelopmentConfig(Config): DEBUG=True SQLALCHEMY_DATABASE_URI=os.environ.get('DATABASE_URL') # or 'sqlite:///'+os.path.join(basedir,'data-dev.sqlite') config={ 'development':DevelopmentConfig } <file_sep># MyBlog_Refer_To_Other-s It's My First Blog and Written By Me Exactly. But Some Refering To Other's Blog Codes!
51d81c216da5cb4771ee5e85d76fded3c632fd80
[ "Markdown", "Python", "Text", "HTML" ]
12
Python
Microndgt/MyBlog_Refer_To_Other-s
3e6d0ec358118686d86de9685cf2e1bd7d0af153
218ff2a3419b29ee53a0ac9c39b6c0d94a7b6b17
refs/heads/master
<file_sep> var socket = io("http://localhost:3000"); var myName = ""; var ready = false; var myX; var myY; var myID; var screenWidth = window.innerWidth; var screenHeight = window.innerHeight; socket.on("info", function(id, x, y){ myID = id; myX = x; myY = y; createDiv(id, x, y); }); socket.on("enemy", function(id, x, y){ createDiv(id, x, y); }); socket.on("playerexit", function(id){ deleteDiv(id); }); socket.on("updatePos", function(id, x, y){ console.log("UPDATE POS"); var translateX = (-1 * (myX - x)); var translateY = (-1 * (myY - y)); document.getElementById(id).style.webkitTransform = "translate(" + translateX + "px," + translateY + "px)"; /*document.getElementById(id).style.left = x.toString() + "px"; document.getElementById(id).style.top = y.toString() + "px";*/ }); /*document.onkeydown = checkKey; function checkKey(e) { e = e || window.event; key = e.keyCode; console.log("<NAME>"); console.log(key); socket.emit("move", myID, key); };*/ window.addEventListener("keydown", keysPressed, false); window.addEventListener("keyup", keysReleased, false); var keys = []; function keysPressed(e) { // store an entry for every key pressed keys[e.keyCode] = true; socket.emit("move", myID, keys); } function keysReleased(e) { // mark keys that were released keys[e.keyCode] = false; socket.emit("move", myID, keys); } function createDiv(id, x, y) { var iDiv = document.createElement('div'); console.log("id: " + id); console.log("x: " + x); console.log("y: " + y); iDiv.id = id; iDiv.style.position = "absolute"; iDiv.style.left = x.toString() + "px"; iDiv.style.top = y.toString() + "px"; if(id === myID){ iDiv.style.backgroundColor = "blue"; } else{ iDiv.style.backgroundColor = "red"; } document.body.appendChild(iDiv); }; function deleteDiv(id){ document.getElementById(id).style.display = "none"; }; /*socket.on("disconnect", function() { setTitle("Disconnected"); }); socket.on("connect", function() { setTitle("Connected to Cyber Chat"); }); socket.on("message", function(message) { printMessage(message); }); socket.on("ready", function(){ ready = true; }); document.forms[1].onsubmit = function () { if(ready){ var input = document.getElementById("message"); printMessage(myName + ": " + input.value); socket.emit("chat", input.value); input.value = ''; } else{ printMessage("MESSAGEM NÃO ENVIADA -> INSERIR NOME"); } }; document.forms[0].onsubmit = function () { var input = document.getElementById("name"); myName = input.value; socket.emit("name", input.value); }; function setTitle(title) { document.querySelector("h1").innerHTML = title; } function printMessage(message) { var p = document.createElement("p"); p.innerText = message; document.querySelector("div.messages").appendChild(p); } */<file_sep>var express = require("express"); var http = require("http"); var app = express(); var server = http.createServer(app).listen(3000); var io = require("socket.io")(server); var numclients = 0; app.use(express.static("./../client")); var id = 0; /*exemplo objecto client var p1 = { name: x:.. y:..}*/ var clients = {}; io.on("connection", function(socket) { numclients++; var x = Math.floor(Math.random() * 100); var y = Math.floor(Math.random() * 100); var p = { id: id, posX: x, posY: y }; for(var c in clients){ socket.emit("enemy", clients[c]["id"], clients[c]["posX"], clients[c]["posY"]); } clients[socket.id] = p; //console.log(clients); //console.log("id: " + id); //console.log("x: " + x); //console.log("y: " + y); socket.emit("info", id, x, y); socket.broadcast.emit("enemy", id, x, y); id++; /*socket.emit("") socket.on("chat", function(message) { var msg = clients[socket.id] + ": " + message; socket.broadcast.emit("message", msg); }); socket.on("name", function(message) { clients[socket.id] = message; socket.emit("ready"); console.log(clients); });*/ socket.on("disconnect", function(){ socket.broadcast.emit("playerexit", clients[socket.id]["id"]); delete clients[socket.id]; }); socket.on("move", function(id, keys){ //W + D if(keys[87] && keys[68]){ console.log("CARREGARAM W + D"); clients[socket.id]["posX"] += 5; clients[socket.id]["posY"] -= 5; socket.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); socket.broadcast.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); } //W + A else if(keys[87] && keys[65]){ console.log("CARREGARAM W + A"); clients[socket.id]["posX"] -= 5; clients[socket.id]["posY"] -= 5; socket.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); socket.broadcast.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); } //S + D else if(keys[83] && keys[68]){ console.log("CARREGARAM S + D"); clients[socket.id]["posX"] += 5; clients[socket.id]["posY"] += 5; socket.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); socket.broadcast.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); } //S + A else if(keys[83] && keys[65]){ console.log("CARREGARAM S + A"); clients[socket.id]["posX"] -= 5; clients[socket.id]["posY"] += 5; socket.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); socket.broadcast.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); } //W else if(keys[87]){ console.log("<NAME>"); clients[socket.id]["posY"] -= 5; socket.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); socket.broadcast.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); } //D else if(keys[68]){ console.log("<NAME>"); clients[socket.id]["posX"] += 5; socket.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); socket.broadcast.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); } //A else if(keys[65]){ console.log("<NAME>"); clients[socket.id]["posX"] -= 5; socket.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); socket.broadcast.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); } //S else if(keys[83]){ console.log("<NAME>"); clients[socket.id]["posY"] += 5; socket.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); socket.broadcast.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); } }); /*socket.on("move", function(id, keys){ if(key === 87){ console.log("<NAME>"); clients[socket.id]["posY"] -= 5; socket.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); socket.broadcast.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); } else if(key === 68){ console.log("<NAME>"); clients[socket.id]["posX"] += 5; socket.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); socket.broadcast.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); } else if(key === 65){ console.log("<NAME>"); clients[socket.id]["posX"] -= 5; socket.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); socket.broadcast.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); } else if(key === 83){ console.log("<NAME>"); clients[socket.id]["posY"] += 5; socket.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); socket.broadcast.emit("updatePos", id, clients[socket.id]["posX"], clients[socket.id]["posY"] ); } });*/ /* socket.emit("message", "Welcome to Cyber Chat");*/ }); console.log("Starting Socket App - http://localhost:3000");
b9dd0692543f4824b66d6b41c662bb9a2534153b
[ "JavaScript" ]
2
JavaScript
fsilvaist/quadrade
3578f75509d11134fb310d266ee1abccb5313249
916950bc8c208e894229b1a71c2f30238313f139
refs/heads/master
<file_sep>export interface StorageConfiguration { readonly ipfsUrl: string readonly dbUrl: string readonly rabbitmqUrl: string } <file_sep>import { injectable, Container } from 'inversify' import { Db, MongoClient } from 'mongodb' import { Messaging } from 'Messaging/Messaging' import { IPFS } from './IPFS' import { IPFSConfiguration } from './IPFSConfiguration' import { Router } from './Router' import { StorageConfiguration } from './StorageConfiguration' import { ClaimController } from './ClaimController' @injectable() export class Storage { private readonly configuration: StorageConfiguration private readonly container = new Container() private dbConnection: Db private router: Router private messaging: Messaging constructor(configuration: StorageConfiguration) { this.configuration = configuration } async start() { console.log('Storage Starting...', this.configuration) this.dbConnection = await MongoClient.connect(this.configuration.dbUrl) this.messaging = new Messaging(this.configuration.rabbitmqUrl) await this.messaging.start() this.initializeContainer() this.router = this.container.get('Router') await this.router.start() console.log('Storage Started') } initializeContainer() { this.container.bind<Db>('DB').toConstantValue(this.dbConnection) this.container.bind<Router>('Router').to(Router) this.container.bind<IPFS>('IPFS').to(IPFS) this.container.bind<IPFSConfiguration>('IPFSConfiguration').toConstantValue({ipfsUrl: this.configuration.ipfsUrl}) this.container.bind<ClaimController>('ClaimController').to(ClaimController) this.container.bind<Messaging>('Messaging').toConstantValue(this.messaging) } }
173b191496871c603c5ebdb2beb0776c24e1409c
[ "TypeScript" ]
2
TypeScript
qiangyuntao2010/node
c8d9e07d8cec85edbeb2256d98b66ad85f74abb9
13df5d518f4955507b3c7b121aea81727ee9ec15