branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>MikeQin/ninja-oauth<file_sep>/app.js
const express = require('express');
const authRoutes = require('./routes/auth-routes');
const profileRoutes = require('./routes/profile-routes');
const passportSetup = require('./config/passport-setup');
const mongoose = require('mongoose');
const { mongodb, session } = require('./config/keys');
const cookieSession = require('cookie-session');
const passport = require('passport');
const app = express();
// set view engine
app.set('view engine', 'ejs');
// use cookie
app.use(cookieSession({
maxAge: 24 * 60 * 60 * 1000,
keys: [session.cookieKey] // for example: 'my_secret_sessionKey'
}));
// initialize passport
app.use(passport.initialize());
app.use(passport.session());
// body-parser
//app.use(express.json());
// Error Handler Middleware
app.use((err, req, res, next) => {
if (err) {
console.log(err);
res.status(422).send({ code: err.code, error: err.errmsg });
}
});
// set up routes
app.use('/auth', authRoutes);
app.use('/profile', profileRoutes);
// create home route
app.get('/', (req, res) => {
res.render('home', { user: req.user });
});
// connnect to mongodb
mongoose.connect(mongodb.dbURI, {
useNewUrlParser: true,
useFindAndModify: false,
useCreateIndex: true,
authSource: "admin"
},
(error, db) => {
console.log('connected to mongodb...');
if (error) console.log(error);
}
);
mongoose.Promise = global.Promise;
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log('app now listening for request on port ' + port);
});<file_sep>/README.md
# Node OAuth 2.0 Tutorial
### Install
```
npm install ejs express
npm install passport passport-google-oauth20
npm install mongoose
npm install cookie-session
```
### To Run
`npm start`
### The OAuth 2.0 Authorization Code Flow
Authentication with Goole+:
1. User authenticates with Google (username, password), and Google returns auth_code
2. Browser sends auth_code, Node Server then sends (auth_code, clientId, clientSecret)
and {scope: ['profile']} to google
3. Google validates (auth_code, clientId, clientSecret), then returns access_token, and profile in callback
4. Google redirects the request to redirect_url
### Google Cloud Platform (Developer APIs)
Configure your OAuth Client Credentials
https://console.cloud.google.com
### MongoDB
Install MongoDB in Ubuntu (Virtual Box) or use [mLab](https://mlab.com/)<file_sep>/config/passport-setup.js
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20/');
const { google } = require('./keys');
const User = require('../models/user');
passport.serializeUser((user, done) => {
console.log('passport.serializeUser...');
console.log("user.id", user.id);
console.log("user._id", user._id);
done(null, user.id);
});
passport.deserializeUser((id, done) => {
console.log('passport.deserializeUser...');
User.findById(id).then((user) => {
console.log('user from cookie', user);
done(null, user);
}).catch(err => {
console.log(err);
})
});
passport.use(new GoogleStrategy({
// options for the google strategy
callbackURL: '/auth/google/redirect',
clientID: google.clientID,
clientSecret: google.clientSecret
}, (accessToken, refreshToken, profile, done) => {
// passport callback
console.log("passport callback fired...");
console.log('accessToken', accessToken);
console.log('profile', profile);
User.findOne({ userId: profile.id }).then((currentUser) => {
if (currentUser) {
// already have the user
console.log('[*] current user', currentUser);
done(null, currentUser);
}
else {
// create a new user
User.create({
userName: profile.displayName,
userId: profile.id,
thumbnail: profile._json.picture
}).then((user) => {
console.log('[*] new user created', user);
done(null, user);
}).catch((error) => {
console.log(error);
});
}
})
})
); | 13c080ef7edeeba9721c27a29a0422e0a46ee2a4 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | MikeQin/ninja-oauth | cc0341f6719e670bab0cc7230db90c28305ef4c2 | 474ce3f95c5323143e870cf4c92926f26f2509f0 | |
refs/heads/master | <repo_name>krissi/ruby-transparent-lua<file_sep>/README.md
# Description
This library makes it easy to provide a complex API for Lua scripts. It
uses [RLua](https://github.com/whitequark/rlua) internally and therefore it
has the same compatibility and restrictions.
# Example code
Lets say we have these classes:
```ruby
User = Struct.new(:name, :favorite_food, :age)
Food = Struct.new(:name, :cooking_time) do
def prepare(timer)
if timer == cooking_time
"This #{name} is delicious"
elsif timer > cooking_time
"This #{name} is awfully burnt"
else
"Smells like frozen #{name}..."
end
end
def buy(*)
'Got one'
end
end
Pizza = Food.new('Pizza', 16)
Lasagne = Food.new('Lasagne', 40)
class Sandbox
def get(username)
users.detect { |u| u.name == username }
end
def users
[
User.new('Kyle', Pizza, 43),
User.new('Lisa', Pizza, 25),
User.new('Ben', Lasagne, 6),
]
end
end
```
To make it available to our Lua script we can use this code:
```ruby
require 'transparent_lua'
tlua = TransparentLua.new(Sandbox.new)
tlua.call(<<-EOF)
print(get_user('Kyle').name .. " likes " .. get_user('Kyle').favorite_food.name .. ".");
print(get_user('Kyle').favorite_food.buy());
print("It needs to cook exactly " .. get_user('Kyle').favorite_food.cooking_time .. " minutes");
my_cooking_time = 270;
print(get_user('Kyle').name .. " cooks it for " .. my_cooking_time .. " minutes.");
print(get_user('Kyle').favorite_food.prepare(my_cooking_time));
EOF
Pizza.cooking_time = 270
tlua.call(<<-EOF)
print("Lets try it again for " .. my_cooking_time .. " minutes. Maybe it works now...");
print(get_user('Kyle').name .. " cooks it for " .. my_cooking_time .. " minutes.");
print(get_user('Kyle').favorite_food.prepare(my_cooking_time));
EOF
```
# Types of methods
* Methods without arguments are created as index of the Lua table
* Methods with arguments are created as a callable metatable.
* To make clear, that an argumentless method is a method (`food.buy()` vs. `food.buy`),
discard any arguments (`def buy(*)`)
# Type conversion
In addition to RLuas type conversion, this library converts Lua tables to either Hashes or
Arrays (when all keys are Numeric).
<file_sep>/Guardfile
guard :rspec,
cmd: 'bundle exec rspec --fail-fast --color',
all_on_start: true,
all_after_pass: true do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
watch('spec/spec_helper.rb') { 'spec' }
notification :file,
path: '.rspec_result',
format: '%s'
end
guard :cucumber,
all_on_start: true do
watch '.rspec_result' do
'features' if File.read('.rspec_result').strip == 'success'
end
watch(%r{^features/.+\.feature$})
watch(%r{^features/support/.+$}) { 'features' }
watch(%r{^features/step_definitions/(.+)_steps\.rb$}) do |m|
Dir[File.join("**/#{m[1]}.feature")][0] || 'features'
end
end
<file_sep>/lib/transparent_lua.rb
require 'rlua'
require 'logger'
class TransparentLua
SUPPORTED_SIMPLE_DATATYPES = [
NilClass,
TrueClass,
FalseClass,
Fixnum,
Bignum,
Float,
Proc,
String,
]
attr_reader :sandbox, :state, :logger
# @param [Object] sandbox The object which will be made visible to the lua script
# @param [Hash] options
# @option options [Lua::State] :state (Lua::State.new) a lua state to use
# @option options [Boolean] :leak_globals When true, all locals from the lua scope are set in the sandbox.
# The sandbox must store the values itself or an error will be raised.
# When false the locals are not reflected in the sandbox
def initialize(sandbox, options = {})
@sandbox = sandbox
@state = options.fetch(:state) { Lua::State.new }
@logger = options.fetch(:logger) { Logger.new('/dev/null') }
leak_locals = options.fetch(:leak_globals) { false }
setup(leak_locals)
end
# @param [String] script a lua script
# @param [String] script_name the name of the lua script (#see Lua::State.__eval)
# @return [Object] the return value of the lua script
def call(script, script_name = nil)
v = state.__eval(script, script_name)
lua2rb(v)
end
private
def setup(leak_globals = false)
state.__load_stdlib :all
global_metatable = {
'__index' => index_table(sandbox)
}
global_metatable['__newindex'] = newindex_table(sandbox) if leak_globals
state._G.__metatable = global_metatable
state.package.loaders = Lua::Table.new(state)
state.package.loaders[1] = ->(modname) do
return "\n\tno module '#{modname}' available in sandbox" unless can_require_module? modname
loader = ->(modname) do
source = require_module(modname)
state.__eval(source, "=#{modname}")
end
state.package.loaded[modname] = loader
loader
end
end
def can_require_module?(modname)
return false unless sandbox.respond_to? :can_require_module?
sandbox.can_require_module? modname
end
def require_module(modname)
fail NoMethodError,
"#{sandbox} must respond to #require_module because it responds to #can_require_module?" unless sandbox.respond_to? :require_module
String(sandbox.require_module(modname))
end
def getter_table(object)
return object if is_supported_simple_datatype? object
metatable = {
'__index' => index_table(object),
'__newindex' => newindex_table(object),
}
delegation_table(object, metatable)
end
def newindex_table(object)
->(t, k, v) do
getter_table(object.public_send(:"#{k}=", lua2rb(v)))
end
end
def index_table(object)
->(t, k, *newindex_args) do
method = get_method(object, k)
k = get_ruby_method_name(k)
logger.debug { "Dispatching method #{method}(#{method.parameters})" }
case method
when ->(m) { m.arity == 0 }
logger.debug { "Creating a getter table for #{method}" }
getter_table(object.public_send(k.to_sym, *newindex_args))
else
logger.debug { "Creating a method table for #{method}" }
method_table(method)
end
end
end
def get_method(object, method_name)
method_name = get_ruby_method_name(method_name)
object.method(method_name.to_sym)
rescue NameError
fail NoMethodError, "#{object}##{method_name.to_s} is not a method (but might be a valid message which is not supported)"
end
# @param [Method] method
def method_table(method)
delegation_table(
'__call' => ->(t, *args) do
converted_args = args.collect do |arg|
lua2rb(arg)
end
getter_table(method.call(*converted_args))
end
)
end
def delegation_table(object = nil, hash)
tab = Lua::Table.new(@state)
tab.__rb_object_id = -> { object.__id__.to_f } if object
tab.__metatable = hash
tab
end
def lua2rb(v)
case v
when ->(t) { has_rb_object_id?(t) }
ObjectSpace._id2ref(Integer(v.__rb_object_id))
when ->(t) { Lua::Table === t && t.to_hash.keys.all? { |k| k.is_a? Numeric } }
v.to_hash.values.collect { |v| lua2rb(v) }
when Lua::Table
v.to_hash.each_with_object({}) { |(k, v), h| h[lua2rb(k)] = lua2rb(v) }
when Float
(Integer(v) == v) ? Integer(v) : v
else
v
end
end
def has_rb_object_id?(o)
o.__rb_object_id
true
rescue NoMethodError
false
end
# @param [Symbol] lua_method_name
# @return [Symbol] ruby method name
def get_ruby_method_name(lua_method_name)
lua_method_name = String(lua_method_name)
case lua_method_name
when /^is_(.*)$/, /^has_(.*)$/
return :"#{$1}?"
else
return lua_method_name.to_sym
end
end
def is_supported_simple_datatype?(object)
return true if SUPPORTED_SIMPLE_DATATYPES.include? object.class
return true if Array === object && object.all? { |i| is_supported_simple_datatype?(i) }
return true if Hash === object && object.keys.all? { |k| is_supported_simple_datatype?(k) } && object.values.all? { |v| is_supported_simple_datatype?(v) }
false
end
end
<file_sep>/transparent-lua.gemspec
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require 'transparent_lua/version'
Gem::Specification.new do |gem|
gem.name = 'transparent-lua'
gem.version = TransparentLua::VERSION
gem.authors = ['<NAME>']
gem.email = ['<EMAIL>']
gem.description = %q{A wrapper to pass complex objects between Ruby and Lua}
gem.summary = <<-EOD
This library enables an easy way to pass complex objects between
Ruby and Lua in a transparent way.
EOD
gem.homepage = 'https://github.com/krissi/ruby-transparent-lua'
gem.license = 'MIT'
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ['lib']
gem.add_dependency 'rlua', '~> 1.0'
gem.add_development_dependency 'rake', '~> 10.4'
gem.add_development_dependency 'cucumber', '~> 2.0'
gem.add_development_dependency 'rspec', '~> 3.3'
end
<file_sep>/features/step_definitions/validation_steps.rb
Then(/^it should return (.*)$/) do |expected_return_value|
expected_return_value = eval(expected_return_value)
expect(@return_value).to eq(expected_return_value)
end
Then(/^the attribute "([^"]*)" of the sandbox is (.*)$/) do |attribute, expected_return_value|
expected_return_value = eval(expected_return_value)
expect(@sandbox.public_send(attribute.to_sym)).to eq(expected_return_value)
end
Then(/^the result of (.+) should (.*)$/) do |subject, expectation|
expect(instance_eval(String(subject))).to eval(expectation)
end
<file_sep>/spec/transparent_lua_spec.rb
require 'spec_helper'
require 'transparent_lua'
describe TransparentLua do
end
<file_sep>/features/step_definitions/transparent_lua_steps.rb
When(/^I execute the script$/) do
@transparent_lua = TransparentLua.new(@sandbox = @sandbox_class.new)
@return_value = @transparent_lua.call(@script)
end
When(/^I execute the script with locales leaking enabled$/) do
@transparent_lua = TransparentLua.new(@sandbox = @sandbox_class.new, leak_globals: true)
@return_value = @transparent_lua.call(@script)
end
<file_sep>/features/step_definitions/preparation_steps.rb
require 'transparent_lua'
Given(/^an empty sandbox$/) do
@sandbox_class = Class.new do
def inspect
'#<Empty Sandbox Class>'
end
alias :to_s :inspect
end
end
Given(/^an? sandbox with an empty member class$/) do
@member_class = Class.new do
def inspect
'#<Sandbox Member Class>'
end
alias :to_s :inspect
end
@sandbox_class = Class.new do
def inspect
'#<Sandbox Class>'
end
alias :to_s :inspect
end
@sandbox_class.class_exec(@member_class) do |member_class|
define_method(:member_class) { member_class.new }
end
end
And(/^the following (?:method definition as part of|code executed in) the sandbox: ?(.*)$/) do |*args|
inline_code, text_code = *args
code = String(text_code).empty? ? String(inline_code) : String(text_code)
@sandbox_class.class_eval(code)
end
And(/^the following method definition as part of the member class: (.*)$/) do |method_definition|
@member_class.class_eval(method_definition)
end
And(/^the following line as Lua script: (.*)$/) do |script|
@script = String(script).strip
end
And(/^the following Lua script:$/) do |script|
@script = String(script).strip
end
| 21d35647f05e642fa860f353c1938b9d82d8a592 | [
"Markdown",
"Ruby"
] | 8 | Markdown | krissi/ruby-transparent-lua | 022297f0c61fc3d4a60eff86b9a42ec5a62b754c | 396949dd04eead380a8f3c4518ccf366855d437a | |
refs/heads/master | <file_sep>package kl.test.multiThread;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
/**
***┏┓ ┏┓
*┏┛┻━━━┛┻┓
*┃ ┃
*┃ ━ ┃
*┃ ┳┛ ┗┳ ┃
*┃ ┃
*┃ ``` ┻ ```┃
*┃ ┃
*┗━┓ ┏━┛
*****┃ ┃Code is far away from bug with the animal protecting.
*****┃ ┃神兽护佑,代码无bug.
*****┃ ┗━━━━ ┓
*****┃ ┣┓
*****┃ ┏┛
*****┗ ┓ ┓┏━┳┓┏┛
*******┃┫┫ ┃┫┫
*******┗┻┛ ┗┻┛
* @author K.L
*
* 信号量 PV,P = acquire, V = release
* 好处:
* 1. 阻塞与数量相关,如果以数量来判断的是否阻塞,明显比Lock.Contition 和 object.wait好
* 2. 不需要拥有线程就可以进行PV操作
*
*/
public class TestReadWriteLockWithSemaphore {
/**
* 同时只可以有一个允许写
*/
static Semaphore writeLock = new Semaphore(1);
static Object lock = new Object();
/**
* 没有这把锁,写线程会饿死的
*/
static Object needWriteLock = new Object();
static volatile int readCount = 0;
static StringBuilder book = new StringBuilder("this is a book about...");
static CountDownLatch startLatch = new CountDownLatch(1);
/**
* @param args
*/
public static void main(String[] args) {
new Thread(new Reader("Tiffany")).start();
new Thread(new Reader("YoYo")).start();
new Thread(new Writer()).start();
new Thread(new Reader("Kate")).start();
startLatch.countDown();
}
static Random random = new Random();
public static int getRandom() {
return random.nextInt(301) + 200;
}
public static class Reader implements Runnable {
String name;
public Reader(String name) {
this.name = name;
}
@Override
public void run() {
try {
startLatch.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
for (int i = 0; i != 20; i++) {
synchronized (needWriteLock) {
synchronized (lock) {
readCount++;
if (readCount == 1) {
try {
writeLock.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
reading(i);
synchronized (lock) {
readCount--;
if (readCount == 0) {
writeLock.release();
}
}
}
}
void reading(int i) {
int t = getRandom();
try {
Thread.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " read " + i + " times ,content is "
+ book.toString());
}
}
static class Writer implements Runnable {
String[] contents = new String[] { " a story.", "Long long ago,",
"a preson", " called xiao ming.", "One day,", "he ", "died." };
public Writer() {
}
@Override
public void run() {
try {
startLatch.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
for (int i = 0; i != contents.length; i++) {
synchronized (needWriteLock) {
try {
writeLock.acquire();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.print("writing...");
try {
Thread.sleep(getRandom() * 3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" i write " + book.append(contents[i]));
writeLock.release();
}
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
<file_sep>package kl.test.multiThread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
***┏┓ ┏┓
*┏┛┻━━━┛┻┓
*┃ ┃
*┃ ━ ┃
*┃ ┳┛ ┗┳ ┃
*┃ ┃
*┃ ``` ┻ ```┃
*┃ ┃
*┗━┓ ┏━┛
*****┃ ┃Code is far away from bug with the animal protecting.
*****┃ ┃神兽护佑,代码无bug.
*****┃ ┗━━━━ ┓
*****┃ ┣┓
*****┃ ┏┛
*****┗ ┓ ┓┏━┳┓┏┛
*******┃┫┫ ┃┫┫
*******┗┻┛ ┗┻┛
*
*基于消息机制的Thread,有消息来时执行,没有时阻塞等待
*
* @author K.L
*/
public class MessageBaseThread extends Thread {
public static void main(String[] args) {
MessageBaseThread msgThread = new MessageBaseThread();
msgThread.start();
msgThread.sendRunnable(new PrintRunnable("start:"));
for (int i = 10; i != 0; i--) {
msgThread.sendRunnable(new PrintRunnable(String
.valueOf((char) ('A' + i))));
}
msgThread.sendRunnable(new PrintRunnable("A"));
}
BlockingQueue<Runnable> mRunnableQueue = new ArrayBlockingQueue<Runnable>(
10);
public void sendRunnable(Runnable runnable) {
try {
mRunnableQueue.put(runnable);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
Runnable runnable = mRunnableQueue.take();//mRunnableQueue空会阻塞,直至有新的Runnable放进队列
runnable.run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class PrintRunnable implements Runnable {
String msg;
public PrintRunnable(String msg) {
this.msg = msg;
}
@Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(msg);
}
}
}<file_sep>package kl.test.multiThread;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
public class TestReadWriteLockWithLock2 {
static CountDownLatch startLatch = new CountDownLatch(1);
static StringBuilder book = new StringBuilder("this is a book about...");
static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
/**
* @param args
*/
public static void main(String[] args) {
new Thread(new Reader()).start();
new Thread(new Reader()).start();
new Thread(new Writer()).start();
new Thread(new Reader()).start();
startLatch.countDown();
}
public static class Writer extends Reader {
//String role = "Writer";
{
role = "Writer";
}
String[] contents = new String[] { " a story.", "Long long ago,",
"a preson", " called xiao ming.", "One day,", "he ", "died." };
WriteLock w = lock.writeLock();
void write_append(String content) {
w.lock();
try {
System.out.print("writing...");
Thread.sleep(getRandom() * 3);
System.out.println(role + id +" writes " + book.append(content));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
w.unlock();
}
try {
Thread.sleep(getRandom());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
startLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i = 0; i != contents.length; i++){
if(i % 4 == 1){
read(i / 4);
}
write_append(contents[i]);
}
}
}
public static class Reader implements Runnable {
static int i = 0;
int id = i++;
ReadLock r = lock.readLock();
String role = "Reader";
String read(int count) {
r.lock();
try {
System.out.println(role + id + " read " + count + " times ,content is "
+ book.toString());
return book.toString();
} finally {
r.unlock();
//System.out.println("finally");
}
}
@Override
public void run() {
try {
startLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i != 10; i++) {
int t = getRandom();
try {
Thread.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
read(i);
}
}
}
static Random random = new Random();
public static int getRandom() {
return random.nextInt(31) + 20;
}
}
| 5289255a91177c13c68ecd8606682ed387d70932 | [
"Java"
] | 3 | Java | k-lam/mutiTheadTest | 20db556c7372edbb6d4f481e1f4badaf12e74710 | a5708489d9f9d245bafffaec05ae4764d22026a7 | |
refs/heads/master | <file_sep>// 导入组件,组件必须声明 name
import scroll from './scroll/index'
import scrollY from './scrollY/index'
// 以数组的结构保存组件,便于遍历
const components = [
scroll,
scrollY
]
export default components
<file_sep>import scrollY from './sm_scroll_y'
export default scrollY
<file_sep>import scroll from './sm_scroll'
export default scroll;
<file_sep>import { createRouter, createWebHashHistory } from 'vue-router'
import scroll from '@/demo/scroll'
import scrollY from "@/demo/scrollY";
const routes = [
{
path: '/scroll',
name: 'scroll',
component: scroll
},
{
path: '/scrollY',
name: 'scrollY',
component: scrollY
},
]
const router = createRouter({
history: createWebHashHistory(process.env.BASE_URL),
routes
})
export default router
| 568890fa31962ea85c9b85e92f51b30253ebdce9 | [
"JavaScript"
] | 4 | JavaScript | xingzai001/my_plugin | c9f7072f081ac566338b26a872d68a8147214e97 | 08e1cba3f2770f86feb7d874e3057b2afd1b45b8 | |
refs/heads/master | <file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class Warning
{
private string codeField;
private string severityField;
private string objectNameField;
private string objectTypeField;
private string messageField;
public string Code
{
get
{
return codeField;
}
set
{
codeField = value;
}
}
public string Severity
{
get
{
return severityField;
}
set
{
severityField = value;
}
}
public string ObjectName
{
get
{
return objectNameField;
}
set
{
objectNameField = value;
}
}
public string ObjectType
{
get
{
return objectTypeField;
}
set
{
objectTypeField = value;
}
}
public string Message
{
get
{
return messageField;
}
set
{
messageField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[XmlInclude(typeof(ParameterValue))]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ParameterValueOrFieldReference
{
}
}
<file_sep>using System.CodeDom.Compiler;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[GeneratedCode("wsdl", "2.0.50727.42")]
public delegate void GetExecutionInfo3CompletedEventHandler(object sender, GetExecutionInfo3CompletedEventArgs e);
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ListSecureMethodsCompletedEventArgs : AsyncCompletedEventArgs
{
private object[] results;
public string[] Result
{
get
{
RaiseExceptionIfNecessary();
return (string[])results[0];
}
}
internal ListSecureMethodsCompletedEventArgs(object[] results, Exception exception, bool cancelled, object userState)
: base(exception, cancelled, userState)
{
this.results = results;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Text;
namespace System.Drawing.Design
{
public class UITypeEditor
{
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[XmlRoot(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", IsNullable = false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public class TrustedUserHeader : SoapHeader
{
private string userNameField;
private byte[] userTokenField;
private XmlAttribute[] anyAttrField;
public string UserName
{
get
{
return userNameField;
}
set
{
userNameField = value;
}
}
[XmlElement(DataType = "base64Binary")]
public byte[] UserToken
{
get
{
return userTokenField;
}
set
{
userTokenField = value;
}
}
[XmlAnyAttribute]
public XmlAttribute[] AnyAttr
{
get
{
return anyAttrField;
}
set
{
anyAttrField = value;
}
}
}
}
<file_sep>using System.CodeDom.Compiler;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[GeneratedCode("wsdl", "2.0.50727.42")]
public delegate void ResetExecution3CompletedEventHandler(object sender, ResetExecution3CompletedEventArgs e);
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class DataSourceCredentials
{
private string dataSourceNameField;
private string userNameField;
private string passwordField;
public string DataSourceName
{
get
{
return dataSourceNameField;
}
set
{
dataSourceNameField = value;
}
}
public string UserName
{
get
{
return userNameField;
}
set
{
userNameField = value;
}
}
public string Password
{
get
{
return passwordField;
}
set
{
passwordField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
public class ExecutionInfo3 : ExecutionInfo2
{
private ParametersGridLayoutDefinition parametersLayoutField;
public ParametersGridLayoutDefinition ParametersLayout
{
get
{
return parametersLayoutField;
}
set
{
parametersLayoutField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
public class ParametersGridLayoutDefinition
{
private int numberOfColumnsField;
private int numberOfRowsField;
private ParametersGridCellDefinition[] cellDefinitionsField;
public int NumberOfColumns
{
get
{
return numberOfColumnsField;
}
set
{
numberOfColumnsField = value;
}
}
public int NumberOfRows
{
get
{
return numberOfRowsField;
}
set
{
numberOfRowsField = value;
}
}
public ParametersGridCellDefinition[] CellDefinitions
{
get
{
return cellDefinitionsField;
}
set
{
cellDefinitionsField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ReportPaperSize
{
private double heightField;
private double widthField;
public double Height
{
get
{
return heightField;
}
set
{
heightField = value;
}
}
public double Width
{
get
{
return widthField;
}
set
{
widthField = value;
}
}
}
}
<file_sep>using System.CodeDom.Compiler;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[GeneratedCode("wsdl", "2.0.50727.42")]
public delegate void SetExecutionParameters3CompletedEventHandler(object sender, SetExecutionParameters3CompletedEventArgs e);
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class PageSettings
{
private ReportPaperSize paperSizeField;
private ReportMargins marginsField;
public ReportPaperSize PaperSize
{
get
{
return paperSizeField;
}
set
{
paperSizeField = value;
}
}
public ReportMargins Margins
{
get
{
return marginsField;
}
set
{
marginsField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
public class ExtensionSettings
{
private string extensionField;
private ParameterValueOrFieldReference[] parameterValuesField;
public string Extension
{
get
{
return extensionField;
}
set
{
extensionField = value;
}
}
[XmlArrayItem(typeof(ParameterFieldReference))]
[XmlArrayItem(typeof(ParameterValue))]
public ParameterValueOrFieldReference[] ParameterValues
{
get
{
return parameterValuesField;
}
set
{
parameterValuesField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[XmlRoot(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", IsNullable = false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ServerInfoHeader : SoapHeader
{
private string reportServerVersionNumberField;
private string reportServerEditionField;
private string reportServerVersionField;
private string reportServerDateTimeField;
private XmlAttribute[] anyAttrField;
public string ReportServerVersionNumber
{
get
{
return reportServerVersionNumberField;
}
set
{
reportServerVersionNumberField = value;
}
}
public string ReportServerEdition
{
get
{
return reportServerEditionField;
}
set
{
reportServerEditionField = value;
}
}
public string ReportServerVersion
{
get
{
return reportServerVersionField;
}
set
{
reportServerVersionField = value;
}
}
public string ReportServerDateTime
{
get
{
return reportServerDateTimeField;
}
set
{
reportServerDateTimeField = value;
}
}
[XmlAnyAttribute]
public XmlAttribute[] AnyAttr
{
get
{
return anyAttrField;
}
set
{
anyAttrField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public enum ParameterStateEnum
{
HasValidValue,
MissingValidValue,
HasOutstandingDependencies,
DynamicValuesUnavailable
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ValidValue
{
private string labelField;
private string valueField;
public string Label
{
get
{
return labelField;
}
set
{
labelField = value;
}
}
public string Value
{
get
{
return valueField;
}
set
{
valueField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[XmlInclude(typeof(ExecutionInfo2))]
[XmlInclude(typeof(ExecutionInfo3))]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ExecutionInfo
{
private bool hasSnapshotField;
private bool needsProcessingField;
private bool allowQueryExecutionField;
private bool credentialsRequiredField;
private bool parametersRequiredField;
private DateTime expirationDateTimeField;
private DateTime executionDateTimeField;
private int numPagesField;
private ReportParameter[] parametersField;
private DataSourcePrompt[] dataSourcePromptsField;
private bool hasDocumentMapField;
private string executionIDField;
private string reportPathField;
private string historyIDField;
private PageSettings reportPageSettingsField;
private int autoRefreshIntervalField;
public bool HasSnapshot
{
get
{
return hasSnapshotField;
}
set
{
hasSnapshotField = value;
}
}
public bool NeedsProcessing
{
get
{
return needsProcessingField;
}
set
{
needsProcessingField = value;
}
}
public bool AllowQueryExecution
{
get
{
return allowQueryExecutionField;
}
set
{
allowQueryExecutionField = value;
}
}
public bool CredentialsRequired
{
get
{
return credentialsRequiredField;
}
set
{
credentialsRequiredField = value;
}
}
public bool ParametersRequired
{
get
{
return parametersRequiredField;
}
set
{
parametersRequiredField = value;
}
}
public DateTime ExpirationDateTime
{
get
{
return expirationDateTimeField;
}
set
{
expirationDateTimeField = value;
}
}
public DateTime ExecutionDateTime
{
get
{
return executionDateTimeField;
}
set
{
executionDateTimeField = value;
}
}
public int NumPages
{
get
{
return numPagesField;
}
set
{
numPagesField = value;
}
}
public ReportParameter[] Parameters
{
get
{
return parametersField;
}
set
{
parametersField = value;
}
}
public DataSourcePrompt[] DataSourcePrompts
{
get
{
return dataSourcePromptsField;
}
set
{
dataSourcePromptsField = value;
}
}
public bool HasDocumentMap
{
get
{
return hasDocumentMapField;
}
set
{
hasDocumentMapField = value;
}
}
public string ExecutionID
{
get
{
return executionIDField;
}
set
{
executionIDField = value;
}
}
public string ReportPath
{
get
{
return reportPathField;
}
set
{
reportPathField = value;
}
}
public string HistoryID
{
get
{
return historyIDField;
}
set
{
historyIDField = value;
}
}
public PageSettings ReportPageSettings
{
get
{
return reportPageSettingsField;
}
set
{
reportPageSettingsField = value;
}
}
public int AutoRefreshInterval
{
get
{
return autoRefreshIntervalField;
}
set
{
autoRefreshIntervalField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
public class ParameterFieldReference : ParameterValueOrFieldReference
{
private string parameterNameField;
private string fieldAliasField;
public string ParameterName
{
get
{
return parameterNameField;
}
set
{
parameterNameField = value;
}
}
public string FieldAlias
{
get
{
return fieldAliasField;
}
set
{
fieldAliasField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public enum SortDirectionEnum
{
None,
Ascending,
Descending
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class DataSourcePrompt
{
private string nameField;
private string dataSourceIDField;
private string promptField;
public string Name
{
get
{
return nameField;
}
set
{
nameField = value;
}
}
public string DataSourceID
{
get
{
return dataSourceIDField;
}
set
{
dataSourceIDField = value;
}
}
public string Prompt
{
get
{
return promptField;
}
set
{
promptField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class Extension
{
private ExtensionTypeEnum extensionTypeField;
private string nameField;
private string localizedNameField;
private bool visibleField;
private bool isModelGenerationSupportedField;
public ExtensionTypeEnum ExtensionType
{
get
{
return extensionTypeField;
}
set
{
extensionTypeField = value;
}
}
public string Name
{
get
{
return nameField;
}
set
{
nameField = value;
}
}
public string LocalizedName
{
get
{
return localizedNameField;
}
set
{
localizedNameField = value;
}
}
public bool Visible
{
get
{
return visibleField;
}
set
{
visibleField = value;
}
}
public bool IsModelGenerationSupported
{
get
{
return isModelGenerationSupportedField;
}
set
{
isModelGenerationSupportedField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
public class ParametersGridCellDefinition
{
private int rowIndexField;
private int columnsIndexField;
private string parameterNameField;
public int RowIndex
{
get
{
return rowIndexField;
}
set
{
rowIndexField = value;
}
}
public int ColumnsIndex
{
get
{
return columnsIndexField;
}
set
{
columnsIndexField = value;
}
}
public string ParameterName
{
get
{
return parameterNameField;
}
set
{
parameterNameField = value;
}
}
}
}
<file_sep>using System.CodeDom.Compiler;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[GeneratedCode("wsdl", "2.0.50727.42")]
public delegate void LoadReport3CompletedEventHandler(object sender, LoadReport3CompletedEventArgs e);
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public enum ParameterTypeEnum
{
Boolean,
DateTime,
Integer,
Float,
String
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ReportParameter
{
private string nameField;
private ParameterTypeEnum typeField;
private bool typeFieldSpecified;
private bool nullableField;
private bool nullableFieldSpecified;
private bool allowBlankField;
private bool allowBlankFieldSpecified;
private bool multiValueField;
private bool multiValueFieldSpecified;
private bool queryParameterField;
private bool queryParameterFieldSpecified;
private string promptField;
private bool promptUserField;
private bool promptUserFieldSpecified;
private string[] dependenciesField;
private bool validValuesQueryBasedField;
private bool validValuesQueryBasedFieldSpecified;
private ValidValue[] validValuesField;
private bool defaultValuesQueryBasedField;
private bool defaultValuesQueryBasedFieldSpecified;
private string[] defaultValuesField;
private ParameterStateEnum stateField;
private bool stateFieldSpecified;
private string errorMessageField;
public string Name
{
get
{
return nameField;
}
set
{
nameField = value;
}
}
public ParameterTypeEnum Type
{
get
{
return typeField;
}
set
{
typeField = value;
}
}
[XmlIgnore]
public bool TypeSpecified
{
get
{
return typeFieldSpecified;
}
set
{
typeFieldSpecified = value;
}
}
public bool Nullable
{
get
{
return nullableField;
}
set
{
nullableField = value;
}
}
[XmlIgnore]
public bool NullableSpecified
{
get
{
return nullableFieldSpecified;
}
set
{
nullableFieldSpecified = value;
}
}
public bool AllowBlank
{
get
{
return allowBlankField;
}
set
{
allowBlankField = value;
}
}
[XmlIgnore]
public bool AllowBlankSpecified
{
get
{
return allowBlankFieldSpecified;
}
set
{
allowBlankFieldSpecified = value;
}
}
public bool MultiValue
{
get
{
return multiValueField;
}
set
{
multiValueField = value;
}
}
[XmlIgnore]
public bool MultiValueSpecified
{
get
{
return multiValueFieldSpecified;
}
set
{
multiValueFieldSpecified = value;
}
}
public bool QueryParameter
{
get
{
return queryParameterField;
}
set
{
queryParameterField = value;
}
}
[XmlIgnore]
public bool QueryParameterSpecified
{
get
{
return queryParameterFieldSpecified;
}
set
{
queryParameterFieldSpecified = value;
}
}
public string Prompt
{
get
{
return promptField;
}
set
{
promptField = value;
}
}
public bool PromptUser
{
get
{
return promptUserField;
}
set
{
promptUserField = value;
}
}
[XmlIgnore]
public bool PromptUserSpecified
{
get
{
return promptUserFieldSpecified;
}
set
{
promptUserFieldSpecified = value;
}
}
[XmlArrayItem("Dependency")]
public string[] Dependencies
{
get
{
return dependenciesField;
}
set
{
dependenciesField = value;
}
}
public bool ValidValuesQueryBased
{
get
{
return validValuesQueryBasedField;
}
set
{
validValuesQueryBasedField = value;
}
}
[XmlIgnore]
public bool ValidValuesQueryBasedSpecified
{
get
{
return validValuesQueryBasedFieldSpecified;
}
set
{
validValuesQueryBasedFieldSpecified = value;
}
}
public ValidValue[] ValidValues
{
get
{
return validValuesField;
}
set
{
validValuesField = value;
}
}
public bool DefaultValuesQueryBased
{
get
{
return defaultValuesQueryBasedField;
}
set
{
defaultValuesQueryBasedField = value;
}
}
[XmlIgnore]
public bool DefaultValuesQueryBasedSpecified
{
get
{
return defaultValuesQueryBasedFieldSpecified;
}
set
{
defaultValuesQueryBasedFieldSpecified = value;
}
}
[XmlArrayItem("Value")]
public string[] DefaultValues
{
get
{
return defaultValuesField;
}
set
{
defaultValuesField = value;
}
}
public ParameterStateEnum State
{
get
{
return stateField;
}
set
{
stateField = value;
}
}
[XmlIgnore]
public bool StateSpecified
{
get
{
return stateFieldSpecified;
}
set
{
stateFieldSpecified = value;
}
}
public string ErrorMessage
{
get
{
return errorMessageField;
}
set
{
errorMessageField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class DocumentMapNode
{
private string labelField;
private string uniqueNameField;
private DocumentMapNode[] childrenField;
public string Label
{
get
{
return labelField;
}
set
{
labelField = value;
}
}
public string UniqueName
{
get
{
return uniqueNameField;
}
set
{
uniqueNameField = value;
}
}
public DocumentMapNode[] Children
{
get
{
return childrenField;
}
set
{
childrenField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ReportMargins
{
private double topField;
private double bottomField;
private double leftField;
private double rightField;
public double Top
{
get
{
return topField;
}
set
{
topField = value;
}
}
public double Bottom
{
get
{
return bottomField;
}
set
{
bottomField = value;
}
}
public double Left
{
get
{
return leftField;
}
set
{
leftField = value;
}
}
public double Right
{
get
{
return rightField;
}
set
{
rightField = value;
}
}
}
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using System.Web.Services;
using System.Web.Services.Description;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[WebServiceBinding(Name = "ReportExecutionServiceSoap", Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[XmlInclude(typeof(ParameterValueOrFieldReference))]
[EditorBrowsable(EditorBrowsableState.Never)]
[ToolboxItem(false)]
public class ReportExecutionService : SoapHttpClientProtocol
{
private TrustedUserHeader trustedUserHeaderValueField;
private ServerInfoHeader serverInfoHeaderValueField;
private SendOrPostCallback ListSecureMethodsOperationCompleted;
private ExecutionHeader executionHeaderValueField;
private SendOrPostCallback LoadReportOperationCompleted;
private SendOrPostCallback LoadReport3OperationCompleted;
private SendOrPostCallback LoadReport2OperationCompleted;
private SendOrPostCallback LoadReportDefinitionOperationCompleted;
private SendOrPostCallback LoadReportDefinition2OperationCompleted;
private SendOrPostCallback LoadReportDefinition3OperationCompleted;
private SendOrPostCallback SetExecutionCredentialsOperationCompleted;
private SendOrPostCallback SetExecutionCredentials2OperationCompleted;
private SendOrPostCallback SetExecutionCredentials3OperationCompleted;
private SendOrPostCallback SetExecutionParametersOperationCompleted;
private SendOrPostCallback SetExecutionParameters2OperationCompleted;
private SendOrPostCallback SetExecutionParameters3OperationCompleted;
private SendOrPostCallback ResetExecutionOperationCompleted;
private SendOrPostCallback ResetExecution2OperationCompleted;
private SendOrPostCallback ResetExecution3OperationCompleted;
private SendOrPostCallback RenderOperationCompleted;
private SendOrPostCallback Render2OperationCompleted;
private SendOrPostCallback DeliverReportItemOperationCompleted;
private SendOrPostCallback RenderStreamOperationCompleted;
private SendOrPostCallback GetExecutionInfoOperationCompleted;
private SendOrPostCallback GetExecutionInfo2OperationCompleted;
private SendOrPostCallback GetExecutionInfo3OperationCompleted;
private SendOrPostCallback GetDocumentMapOperationCompleted;
private SendOrPostCallback LoadDrillthroughTargetOperationCompleted;
private SendOrPostCallback LoadDrillthroughTarget2OperationCompleted;
private SendOrPostCallback LoadDrillthroughTarget3OperationCompleted;
private SendOrPostCallback ToggleItemOperationCompleted;
private SendOrPostCallback NavigateDocumentMapOperationCompleted;
private SendOrPostCallback NavigateBookmarkOperationCompleted;
private SendOrPostCallback FindStringOperationCompleted;
private SendOrPostCallback SortOperationCompleted;
private SendOrPostCallback Sort2OperationCompleted;
private SendOrPostCallback Sort3OperationCompleted;
private SendOrPostCallback GetRenderResourceOperationCompleted;
private SendOrPostCallback ListRenderingExtensionsOperationCompleted;
private SendOrPostCallback LogonUserOperationCompleted;
private SendOrPostCallback LogoffOperationCompleted;
public TrustedUserHeader TrustedUserHeaderValue
{
get
{
return trustedUserHeaderValueField;
}
set
{
trustedUserHeaderValueField = value;
}
}
public ServerInfoHeader ServerInfoHeaderValue
{
get
{
return serverInfoHeaderValueField;
}
set
{
serverInfoHeaderValueField = value;
}
}
public ExecutionHeader ExecutionHeaderValue
{
get
{
return executionHeaderValueField;
}
set
{
executionHeaderValueField = value;
}
}
public event ListSecureMethodsCompletedEventHandler ListSecureMethodsCompleted;
public event LoadReportCompletedEventHandler LoadReportCompleted;
public event LoadReport3CompletedEventHandler LoadReport3Completed;
public event LoadReport2CompletedEventHandler LoadReport2Completed;
public event LoadReportDefinitionCompletedEventHandler LoadReportDefinitionCompleted;
public event LoadReportDefinition2CompletedEventHandler LoadReportDefinition2Completed;
public event LoadReportDefinition3CompletedEventHandler LoadReportDefinition3Completed;
public event SetExecutionCredentialsCompletedEventHandler SetExecutionCredentialsCompleted;
public event SetExecutionCredentials2CompletedEventHandler SetExecutionCredentials2Completed;
public event SetExecutionCredentials3CompletedEventHandler SetExecutionCredentials3Completed;
public event SetExecutionParametersCompletedEventHandler SetExecutionParametersCompleted;
public event SetExecutionParameters2CompletedEventHandler SetExecutionParameters2Completed;
public event SetExecutionParameters3CompletedEventHandler SetExecutionParameters3Completed;
public event ResetExecutionCompletedEventHandler ResetExecutionCompleted;
public event ResetExecution2CompletedEventHandler ResetExecution2Completed;
public event ResetExecution3CompletedEventHandler ResetExecution3Completed;
public event RenderCompletedEventHandler RenderCompleted;
public event Render2CompletedEventHandler Render2Completed;
public event DeliverReportItemCompletedEventHandler DeliverReportItemCompleted;
public event RenderStreamCompletedEventHandler RenderStreamCompleted;
public event GetExecutionInfoCompletedEventHandler GetExecutionInfoCompleted;
public event GetExecutionInfo2CompletedEventHandler GetExecutionInfo2Completed;
public event GetExecutionInfo3CompletedEventHandler GetExecutionInfo3Completed;
public event GetDocumentMapCompletedEventHandler GetDocumentMapCompleted;
public event LoadDrillthroughTargetCompletedEventHandler LoadDrillthroughTargetCompleted;
public event LoadDrillthroughTarget2CompletedEventHandler LoadDrillthroughTarget2Completed;
public event LoadDrillthroughTarget3CompletedEventHandler LoadDrillthroughTarget3Completed;
public event ToggleItemCompletedEventHandler ToggleItemCompleted;
public event NavigateDocumentMapCompletedEventHandler NavigateDocumentMapCompleted;
public event NavigateBookmarkCompletedEventHandler NavigateBookmarkCompleted;
public event FindStringCompletedEventHandler FindStringCompleted;
public event SortCompletedEventHandler SortCompleted;
public event Sort2CompletedEventHandler Sort2Completed;
public event Sort3CompletedEventHandler Sort3Completed;
public event GetRenderResourceCompletedEventHandler GetRenderResourceCompleted;
public event ListRenderingExtensionsCompletedEventHandler ListRenderingExtensionsCompleted;
public event LogonUserCompletedEventHandler LogonUserCompleted;
public event LogoffCompletedEventHandler LogoffCompleted;
public ReportExecutionService()
{
base.Url = "http://localhost/ReportServer/ReportExecution2005.asmx";
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/ListSecureMethods", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
public string[] ListSecureMethods()
{
return (string[])Invoke("ListSecureMethods", new object[0])[0];
}
protected new object[] Invoke(string methodName, object[] parameters)
{
return base.Invoke(methodName, parameters);
}
public IAsyncResult BeginListSecureMethods(AsyncCallback callback, object asyncState)
{
return BeginInvoke("ListSecureMethods", new object[0], callback, asyncState);
}
public string[] EndListSecureMethods(IAsyncResult asyncResult)
{
return (string[])EndInvoke(asyncResult)[0];
}
public void ListSecureMethodsAsync()
{
ListSecureMethodsAsync(null);
}
public void ListSecureMethodsAsync(object userState)
{
if (ListSecureMethodsOperationCompleted == null)
{
ListSecureMethodsOperationCompleted = OnListSecureMethodsOperationCompleted;
}
InvokeAsync("ListSecureMethods", new object[0], ListSecureMethodsOperationCompleted, userState);
}
private void OnListSecureMethodsOperationCompleted(object arg)
{
if (this.ListSecureMethodsCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.ListSecureMethodsCompleted(this, new ListSecureMethodsCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/LoadReport", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo LoadReport(string Report, string HistoryID)
{
return (ExecutionInfo)Invoke("LoadReport", new object[2]
{
Report,
HistoryID
})[0];
}
public IAsyncResult BeginLoadReport(string Report, string HistoryID, AsyncCallback callback, object asyncState)
{
return BeginInvoke("LoadReport", new object[2]
{
Report,
HistoryID
}, callback, asyncState);
}
public ExecutionInfo EndLoadReport(IAsyncResult asyncResult)
{
return (ExecutionInfo)EndInvoke(asyncResult)[0];
}
public void LoadReportAsync(string Report, string HistoryID)
{
LoadReportAsync(Report, HistoryID, null);
}
public void LoadReportAsync(string Report, string HistoryID, object userState)
{
if (LoadReportOperationCompleted == null)
{
LoadReportOperationCompleted = OnLoadReportOperationCompleted;
}
InvokeAsync("LoadReport", new object[2]
{
Report,
HistoryID
}, LoadReportOperationCompleted, userState);
}
private void OnLoadReportOperationCompleted(object arg)
{
if (this.LoadReportCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.LoadReportCompleted(this, new LoadReportCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/LoadReport3", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo3 LoadReport3(string Report, string HistoryID)
{
return (ExecutionInfo3)Invoke("LoadReport3", new object[2]
{
Report,
HistoryID
})[0];
}
public IAsyncResult BeginLoadReport3(string Report, string HistoryID, AsyncCallback callback, object asyncState)
{
return BeginInvoke("LoadReport3", new object[2]
{
Report,
HistoryID
}, callback, asyncState);
}
public ExecutionInfo3 EndLoadReport3(IAsyncResult asyncResult)
{
return (ExecutionInfo3)EndInvoke(asyncResult)[0];
}
public void LoadReport3Async(string Report, string HistoryID)
{
LoadReport3Async(Report, HistoryID, null);
}
public void LoadReport3Async(string Report, string HistoryID, object userState)
{
if (LoadReport3OperationCompleted == null)
{
LoadReport3OperationCompleted = OnLoadReport3OperationCompleted;
}
InvokeAsync("LoadReport3", new object[2]
{
Report,
HistoryID
}, LoadReport3OperationCompleted, userState);
}
private void OnLoadReport3OperationCompleted(object arg)
{
if (this.LoadReport3Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.LoadReport3Completed(this, new LoadReport3CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/LoadReport2", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo2 LoadReport2(string Report, string HistoryID)
{
return (ExecutionInfo2)Invoke("LoadReport2", new object[2]
{
Report,
HistoryID
})[0];
}
public IAsyncResult BeginLoadReport2(string Report, string HistoryID, AsyncCallback callback, object asyncState)
{
return BeginInvoke("LoadReport2", new object[2]
{
Report,
HistoryID
}, callback, asyncState);
}
public ExecutionInfo2 EndLoadReport2(IAsyncResult asyncResult)
{
return (ExecutionInfo2)EndInvoke(asyncResult)[0];
}
public void LoadReport2Async(string Report, string HistoryID)
{
LoadReport2Async(Report, HistoryID, null);
}
public void LoadReport2Async(string Report, string HistoryID, object userState)
{
if (LoadReport2OperationCompleted == null)
{
LoadReport2OperationCompleted = OnLoadReport2OperationCompleted;
}
InvokeAsync("LoadReport2", new object[2]
{
Report,
HistoryID
}, LoadReport2OperationCompleted, userState);
}
private void OnLoadReport2OperationCompleted(object arg)
{
if (this.LoadReport2Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.LoadReport2Completed(this, new LoadReport2CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/LoadReportDefinition", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo LoadReportDefinition([XmlElement(DataType = "base64Binary")] byte[] Definition, out Warning[] warnings)
{
object[] array = Invoke("LoadReportDefinition", new object[1]
{
Definition
});
warnings = (Warning[])array[1];
return (ExecutionInfo)array[0];
}
public IAsyncResult BeginLoadReportDefinition(byte[] Definition, AsyncCallback callback, object asyncState)
{
return BeginInvoke("LoadReportDefinition", new object[1]
{
Definition
}, callback, asyncState);
}
public ExecutionInfo EndLoadReportDefinition(IAsyncResult asyncResult, out Warning[] warnings)
{
object[] array = EndInvoke(asyncResult);
warnings = (Warning[])array[1];
return (ExecutionInfo)array[0];
}
public void LoadReportDefinitionAsync(byte[] Definition)
{
LoadReportDefinitionAsync(Definition, null);
}
public void LoadReportDefinitionAsync(byte[] Definition, object userState)
{
if (LoadReportDefinitionOperationCompleted == null)
{
LoadReportDefinitionOperationCompleted = OnLoadReportDefinitionOperationCompleted;
}
InvokeAsync("LoadReportDefinition", new object[1]
{
Definition
}, LoadReportDefinitionOperationCompleted, userState);
}
private void OnLoadReportDefinitionOperationCompleted(object arg)
{
if (this.LoadReportDefinitionCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.LoadReportDefinitionCompleted(this, new LoadReportDefinitionCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/LoadReportDefinition2", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo2 LoadReportDefinition2([XmlElement(DataType = "base64Binary")] byte[] Definition, out Warning[] warnings)
{
object[] array = Invoke("LoadReportDefinition2", new object[1]
{
Definition
});
warnings = (Warning[])array[1];
return (ExecutionInfo2)array[0];
}
public IAsyncResult BeginLoadReportDefinition2(byte[] Definition, AsyncCallback callback, object asyncState)
{
return BeginInvoke("LoadReportDefinition2", new object[1]
{
Definition
}, callback, asyncState);
}
public ExecutionInfo2 EndLoadReportDefinition2(IAsyncResult asyncResult, out Warning[] warnings)
{
object[] array = EndInvoke(asyncResult);
warnings = (Warning[])array[1];
return (ExecutionInfo2)array[0];
}
public void LoadReportDefinition2Async(byte[] Definition)
{
LoadReportDefinition2Async(Definition, null);
}
public void LoadReportDefinition2Async(byte[] Definition, object userState)
{
if (LoadReportDefinition2OperationCompleted == null)
{
LoadReportDefinition2OperationCompleted = OnLoadReportDefinition2OperationCompleted;
}
InvokeAsync("LoadReportDefinition2", new object[1]
{
Definition
}, LoadReportDefinition2OperationCompleted, userState);
}
private void OnLoadReportDefinition2OperationCompleted(object arg)
{
if (this.LoadReportDefinition2Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.LoadReportDefinition2Completed(this, new LoadReportDefinition2CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/LoadReportDefinition3", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo3 LoadReportDefinition3([XmlElement(DataType = "base64Binary")] byte[] Definition, out Warning[] warnings)
{
object[] array = Invoke("LoadReportDefinition3", new object[1]
{
Definition
});
warnings = (Warning[])array[1];
return (ExecutionInfo3)array[0];
}
public IAsyncResult BeginLoadReportDefinition3(byte[] Definition, AsyncCallback callback, object asyncState)
{
return BeginInvoke("LoadReportDefinition3", new object[1]
{
Definition
}, callback, asyncState);
}
public ExecutionInfo3 EndLoadReportDefinition3(IAsyncResult asyncResult, out Warning[] warnings)
{
object[] array = EndInvoke(asyncResult);
warnings = (Warning[])array[1];
return (ExecutionInfo3)array[0];
}
public void LoadReportDefinition3Async(byte[] Definition)
{
LoadReportDefinition3Async(Definition, null);
}
public void LoadReportDefinition3Async(byte[] Definition, object userState)
{
if (LoadReportDefinition3OperationCompleted == null)
{
LoadReportDefinition3OperationCompleted = OnLoadReportDefinition3OperationCompleted;
}
InvokeAsync("LoadReportDefinition3", new object[1]
{
Definition
}, LoadReportDefinition3OperationCompleted, userState);
}
private void OnLoadReportDefinition3OperationCompleted(object arg)
{
if (this.LoadReportDefinition3Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.LoadReportDefinition3Completed(this, new LoadReportDefinition3CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/SetExecutionCredentials", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo SetExecutionCredentials(DataSourceCredentials[] Credentials)
{
return (ExecutionInfo)Invoke("SetExecutionCredentials", new object[1]
{
Credentials
})[0];
}
public IAsyncResult BeginSetExecutionCredentials(DataSourceCredentials[] Credentials, AsyncCallback callback, object asyncState)
{
return BeginInvoke("SetExecutionCredentials", new object[1]
{
Credentials
}, callback, asyncState);
}
public ExecutionInfo EndSetExecutionCredentials(IAsyncResult asyncResult)
{
return (ExecutionInfo)EndInvoke(asyncResult)[0];
}
public void SetExecutionCredentialsAsync(DataSourceCredentials[] Credentials)
{
SetExecutionCredentialsAsync(Credentials, null);
}
public void SetExecutionCredentialsAsync(DataSourceCredentials[] Credentials, object userState)
{
if (SetExecutionCredentialsOperationCompleted == null)
{
SetExecutionCredentialsOperationCompleted = OnSetExecutionCredentialsOperationCompleted;
}
InvokeAsync("SetExecutionCredentials", new object[1]
{
Credentials
}, SetExecutionCredentialsOperationCompleted, userState);
}
private void OnSetExecutionCredentialsOperationCompleted(object arg)
{
if (this.SetExecutionCredentialsCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.SetExecutionCredentialsCompleted(this, new SetExecutionCredentialsCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/SetExecutionCredentials2", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo2 SetExecutionCredentials2(DataSourceCredentials[] Credentials)
{
return (ExecutionInfo2)Invoke("SetExecutionCredentials2", new object[1]
{
Credentials
})[0];
}
public IAsyncResult BeginSetExecutionCredentials2(DataSourceCredentials[] Credentials, AsyncCallback callback, object asyncState)
{
return BeginInvoke("SetExecutionCredentials2", new object[1]
{
Credentials
}, callback, asyncState);
}
public ExecutionInfo2 EndSetExecutionCredentials2(IAsyncResult asyncResult)
{
return (ExecutionInfo2)EndInvoke(asyncResult)[0];
}
public void SetExecutionCredentials2Async(DataSourceCredentials[] Credentials)
{
SetExecutionCredentials2Async(Credentials, null);
}
public void SetExecutionCredentials2Async(DataSourceCredentials[] Credentials, object userState)
{
if (SetExecutionCredentials2OperationCompleted == null)
{
SetExecutionCredentials2OperationCompleted = OnSetExecutionCredentials2OperationCompleted;
}
InvokeAsync("SetExecutionCredentials2", new object[1]
{
Credentials
}, SetExecutionCredentials2OperationCompleted, userState);
}
private void OnSetExecutionCredentials2OperationCompleted(object arg)
{
if (this.SetExecutionCredentials2Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.SetExecutionCredentials2Completed(this, new SetExecutionCredentials2CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/SetExecutionCredentials3", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo3 SetExecutionCredentials3(DataSourceCredentials[] Credentials)
{
return (ExecutionInfo3)Invoke("SetExecutionCredentials3", new object[1]
{
Credentials
})[0];
}
public IAsyncResult BeginSetExecutionCredentials3(DataSourceCredentials[] Credentials, AsyncCallback callback, object asyncState)
{
return BeginInvoke("SetExecutionCredentials3", new object[1]
{
Credentials
}, callback, asyncState);
}
public ExecutionInfo3 EndSetExecutionCredentials3(IAsyncResult asyncResult)
{
return (ExecutionInfo3)EndInvoke(asyncResult)[0];
}
public void SetExecutionCredentials3Async(DataSourceCredentials[] Credentials)
{
SetExecutionCredentials3Async(Credentials, null);
}
public void SetExecutionCredentials3Async(DataSourceCredentials[] Credentials, object userState)
{
if (SetExecutionCredentials3OperationCompleted == null)
{
SetExecutionCredentials3OperationCompleted = OnSetExecutionCredentials3OperationCompleted;
}
InvokeAsync("SetExecutionCredentials3", new object[1]
{
Credentials
}, SetExecutionCredentials3OperationCompleted, userState);
}
private void OnSetExecutionCredentials3OperationCompleted(object arg)
{
if (this.SetExecutionCredentials3Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.SetExecutionCredentials3Completed(this, new SetExecutionCredentials3CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/SetExecutionParameters", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo SetExecutionParameters(ParameterValue[] Parameters, string ParameterLanguage)
{
return (ExecutionInfo)Invoke("SetExecutionParameters", new object[2]
{
Parameters,
ParameterLanguage
})[0];
}
public IAsyncResult BeginSetExecutionParameters(ParameterValue[] Parameters, string ParameterLanguage, AsyncCallback callback, object asyncState)
{
return BeginInvoke("SetExecutionParameters", new object[2]
{
Parameters,
ParameterLanguage
}, callback, asyncState);
}
public ExecutionInfo EndSetExecutionParameters(IAsyncResult asyncResult)
{
return (ExecutionInfo)EndInvoke(asyncResult)[0];
}
public void SetExecutionParametersAsync(ParameterValue[] Parameters, string ParameterLanguage)
{
SetExecutionParametersAsync(Parameters, ParameterLanguage, null);
}
public void SetExecutionParametersAsync(ParameterValue[] Parameters, string ParameterLanguage, object userState)
{
if (SetExecutionParametersOperationCompleted == null)
{
SetExecutionParametersOperationCompleted = OnSetExecutionParametersOperationCompleted;
}
InvokeAsync("SetExecutionParameters", new object[2]
{
Parameters,
ParameterLanguage
}, SetExecutionParametersOperationCompleted, userState);
}
private void OnSetExecutionParametersOperationCompleted(object arg)
{
if (this.SetExecutionParametersCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.SetExecutionParametersCompleted(this, new SetExecutionParametersCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/SetExecutionParameters2", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo2 SetExecutionParameters2(ParameterValue[] Parameters, string ParameterLanguage)
{
return (ExecutionInfo2)Invoke("SetExecutionParameters2", new object[2]
{
Parameters,
ParameterLanguage
})[0];
}
public IAsyncResult BeginSetExecutionParameters2(ParameterValue[] Parameters, string ParameterLanguage, AsyncCallback callback, object asyncState)
{
return BeginInvoke("SetExecutionParameters2", new object[2]
{
Parameters,
ParameterLanguage
}, callback, asyncState);
}
public ExecutionInfo2 EndSetExecutionParameters2(IAsyncResult asyncResult)
{
return (ExecutionInfo2)EndInvoke(asyncResult)[0];
}
public void SetExecutionParameters2Async(ParameterValue[] Parameters, string ParameterLanguage)
{
SetExecutionParameters2Async(Parameters, ParameterLanguage, null);
}
public void SetExecutionParameters2Async(ParameterValue[] Parameters, string ParameterLanguage, object userState)
{
if (SetExecutionParameters2OperationCompleted == null)
{
SetExecutionParameters2OperationCompleted = OnSetExecutionParameters2OperationCompleted;
}
InvokeAsync("SetExecutionParameters2", new object[2]
{
Parameters,
ParameterLanguage
}, SetExecutionParameters2OperationCompleted, userState);
}
private void OnSetExecutionParameters2OperationCompleted(object arg)
{
if (this.SetExecutionParameters2Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.SetExecutionParameters2Completed(this, new SetExecutionParameters2CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/SetExecutionParameters3", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo3 SetExecutionParameters3(ParameterValue[] Parameters, string ParameterLanguage)
{
return (ExecutionInfo3)Invoke("SetExecutionParameters3", new object[2]
{
Parameters,
ParameterLanguage
})[0];
}
public IAsyncResult BeginSetExecutionParameters3(ParameterValue[] Parameters, string ParameterLanguage, AsyncCallback callback, object asyncState)
{
return BeginInvoke("SetExecutionParameters3", new object[2]
{
Parameters,
ParameterLanguage
}, callback, asyncState);
}
public ExecutionInfo3 EndSetExecutionParameters3(IAsyncResult asyncResult)
{
return (ExecutionInfo3)EndInvoke(asyncResult)[0];
}
public void SetExecutionParameters3Async(ParameterValue[] Parameters, string ParameterLanguage)
{
SetExecutionParameters3Async(Parameters, ParameterLanguage, null);
}
public void SetExecutionParameters3Async(ParameterValue[] Parameters, string ParameterLanguage, object userState)
{
if (SetExecutionParameters3OperationCompleted == null)
{
SetExecutionParameters3OperationCompleted = OnSetExecutionParameters3OperationCompleted;
}
InvokeAsync("SetExecutionParameters3", new object[2]
{
Parameters,
ParameterLanguage
}, SetExecutionParameters3OperationCompleted, userState);
}
private void OnSetExecutionParameters3OperationCompleted(object arg)
{
if (this.SetExecutionParameters3Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.SetExecutionParameters3Completed(this, new SetExecutionParameters3CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/ResetExecution", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo ResetExecution()
{
return (ExecutionInfo)Invoke("ResetExecution", new object[0])[0];
}
public IAsyncResult BeginResetExecution(AsyncCallback callback, object asyncState)
{
return BeginInvoke("ResetExecution", new object[0], callback, asyncState);
}
public ExecutionInfo EndResetExecution(IAsyncResult asyncResult)
{
return (ExecutionInfo)EndInvoke(asyncResult)[0];
}
public void ResetExecutionAsync()
{
ResetExecutionAsync(null);
}
public void ResetExecutionAsync(object userState)
{
if (ResetExecutionOperationCompleted == null)
{
ResetExecutionOperationCompleted = OnResetExecutionOperationCompleted;
}
InvokeAsync("ResetExecution", new object[0], ResetExecutionOperationCompleted, userState);
}
private void OnResetExecutionOperationCompleted(object arg)
{
if (this.ResetExecutionCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.ResetExecutionCompleted(this, new ResetExecutionCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/ResetExecution2", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo2 ResetExecution2()
{
return (ExecutionInfo2)Invoke("ResetExecution2", new object[0])[0];
}
public IAsyncResult BeginResetExecution2(AsyncCallback callback, object asyncState)
{
return BeginInvoke("ResetExecution2", new object[0], callback, asyncState);
}
public ExecutionInfo2 EndResetExecution2(IAsyncResult asyncResult)
{
return (ExecutionInfo2)EndInvoke(asyncResult)[0];
}
public void ResetExecution2Async()
{
ResetExecution2Async(null);
}
public void ResetExecution2Async(object userState)
{
if (ResetExecution2OperationCompleted == null)
{
ResetExecution2OperationCompleted = OnResetExecution2OperationCompleted;
}
InvokeAsync("ResetExecution2", new object[0], ResetExecution2OperationCompleted, userState);
}
private void OnResetExecution2OperationCompleted(object arg)
{
if (this.ResetExecution2Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.ResetExecution2Completed(this, new ResetExecution2CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/ResetExecution3", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo3 ResetExecution3()
{
return (ExecutionInfo3)Invoke("ResetExecution3", new object[0])[0];
}
public IAsyncResult BeginResetExecution3(AsyncCallback callback, object asyncState)
{
return BeginInvoke("ResetExecution3", new object[0], callback, asyncState);
}
public ExecutionInfo3 EndResetExecution3(IAsyncResult asyncResult)
{
return (ExecutionInfo3)EndInvoke(asyncResult)[0];
}
public void ResetExecution3Async()
{
ResetExecution3Async(null);
}
public void ResetExecution3Async(object userState)
{
if (ResetExecution3OperationCompleted == null)
{
ResetExecution3OperationCompleted = OnResetExecution3OperationCompleted;
}
InvokeAsync("ResetExecution3", new object[0], ResetExecution3OperationCompleted, userState);
}
private void OnResetExecution3OperationCompleted(object arg)
{
if (this.ResetExecution3Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.ResetExecution3Completed(this, new ResetExecution3CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/Render", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("Result", DataType = "base64Binary")]
public byte[] Render(string Format, string DeviceInfo, out string Extension, out string MimeType, out string Encoding, out Warning[] Warnings, out string[] StreamIds)
{
object[] array = Invoke("Render", new object[2]
{
Format,
DeviceInfo
});
Extension = (string)array[1];
MimeType = (string)array[2];
Encoding = (string)array[3];
Warnings = (Warning[])array[4];
StreamIds = (string[])array[5];
return (byte[])array[0];
}
public IAsyncResult BeginRender(string Format, string DeviceInfo, AsyncCallback callback, object asyncState)
{
return BeginInvoke("Render", new object[2]
{
Format,
DeviceInfo
}, callback, asyncState);
}
public byte[] EndRender(IAsyncResult asyncResult, out string Extension, out string MimeType, out string Encoding, out Warning[] Warnings, out string[] StreamIds)
{
object[] array = EndInvoke(asyncResult);
Extension = (string)array[1];
MimeType = (string)array[2];
Encoding = (string)array[3];
Warnings = (Warning[])array[4];
StreamIds = (string[])array[5];
return (byte[])array[0];
}
public void RenderAsync(string Format, string DeviceInfo)
{
RenderAsync(Format, DeviceInfo, null);
}
public void RenderAsync(string Format, string DeviceInfo, object userState)
{
if (RenderOperationCompleted == null)
{
RenderOperationCompleted = OnRenderOperationCompleted;
}
InvokeAsync("Render", new object[2]
{
Format,
DeviceInfo
}, RenderOperationCompleted, userState);
}
private void OnRenderOperationCompleted(object arg)
{
if (this.RenderCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.RenderCompleted(this, new RenderCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/Render2", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("Result", DataType = "base64Binary")]
public byte[] Render2(string Format, string DeviceInfo, PageCountMode PaginationMode, out string Extension, out string MimeType, out string Encoding, out Warning[] Warnings, out string[] StreamIds)
{
object[] array = Invoke("Render2", new object[3]
{
Format,
DeviceInfo,
PaginationMode
});
Extension = (string)array[1];
MimeType = (string)array[2];
Encoding = (string)array[3];
Warnings = (Warning[])array[4];
StreamIds = (string[])array[5];
return (byte[])array[0];
}
public IAsyncResult BeginRender2(string Format, string DeviceInfo, PageCountMode PaginationMode, AsyncCallback callback, object asyncState)
{
return BeginInvoke("Render2", new object[3]
{
Format,
DeviceInfo,
PaginationMode
}, callback, asyncState);
}
public byte[] EndRender2(IAsyncResult asyncResult, out string Extension, out string MimeType, out string Encoding, out Warning[] Warnings, out string[] StreamIds)
{
object[] array = EndInvoke(asyncResult);
Extension = (string)array[1];
MimeType = (string)array[2];
Encoding = (string)array[3];
Warnings = (Warning[])array[4];
StreamIds = (string[])array[5];
return (byte[])array[0];
}
public void Render2Async(string Format, string DeviceInfo, PageCountMode PaginationMode)
{
Render2Async(Format, DeviceInfo, PaginationMode, null);
}
public void Render2Async(string Format, string DeviceInfo, PageCountMode PaginationMode, object userState)
{
if (Render2OperationCompleted == null)
{
Render2OperationCompleted = OnRender2OperationCompleted;
}
InvokeAsync("Render2", new object[3]
{
Format,
DeviceInfo,
PaginationMode
}, Render2OperationCompleted, userState);
}
private void OnRender2OperationCompleted(object arg)
{
if (this.Render2Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.Render2Completed(this, new Render2CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/DeliverReportItem", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
public void DeliverReportItem(string Format, string DeviceInfo, ExtensionSettings ExtensionSettings, string Description, string EventType, string MatchData)
{
Invoke("DeliverReportItem", new object[6]
{
Format,
DeviceInfo,
ExtensionSettings,
Description,
EventType,
MatchData
});
}
public IAsyncResult BeginDeliverReportItem(string Format, string DeviceInfo, ExtensionSettings ExtensionSettings, string Description, string EventType, string MatchData, AsyncCallback callback, object asyncState)
{
return BeginInvoke("DeliverReportItem", new object[6]
{
Format,
DeviceInfo,
ExtensionSettings,
Description,
EventType,
MatchData
}, callback, asyncState);
}
public void EndDeliverReportItem(IAsyncResult asyncResult)
{
EndInvoke(asyncResult);
}
public void DeliverReportItemAsync(string Format, string DeviceInfo, string Report, ExtensionSettings ExtensionSettings, string Description, string EventType, string MatchData)
{
DeliverReportItemAsync(Format, DeviceInfo, ExtensionSettings, Description, EventType, MatchData, null);
}
public void DeliverReportItemAsync(string Format, string DeviceInfo, ExtensionSettings ExtensionSettings, string Description, string EventType, string MatchData, object userState)
{
if (DeliverReportItemOperationCompleted == null)
{
DeliverReportItemOperationCompleted = OnDeliverReportItemOperationCompleted;
}
InvokeAsync("DeliverReportItem", new object[6]
{
Format,
DeviceInfo,
ExtensionSettings,
Description,
EventType,
MatchData
}, DeliverReportItemOperationCompleted, userState);
}
private void OnDeliverReportItemOperationCompleted(object arg)
{
if (this.DeliverReportItemCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.DeliverReportItemCompleted(this, new AsyncCompletedEventArgs(invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/RenderStream", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("Result", DataType = "base64Binary")]
public byte[] RenderStream(string Format, string StreamID, string DeviceInfo, out string Encoding, out string MimeType)
{
object[] array = Invoke("RenderStream", new object[3]
{
Format,
StreamID,
DeviceInfo
});
Encoding = (string)array[1];
MimeType = (string)array[2];
return (byte[])array[0];
}
public IAsyncResult BeginRenderStream(string Format, string StreamID, string DeviceInfo, AsyncCallback callback, object asyncState)
{
return BeginInvoke("RenderStream", new object[3]
{
Format,
StreamID,
DeviceInfo
}, callback, asyncState);
}
public byte[] EndRenderStream(IAsyncResult asyncResult, out string Encoding, out string MimeType)
{
object[] array = EndInvoke(asyncResult);
Encoding = (string)array[1];
MimeType = (string)array[2];
return (byte[])array[0];
}
public void RenderStreamAsync(string Format, string StreamID, string DeviceInfo)
{
RenderStreamAsync(Format, StreamID, DeviceInfo, null);
}
public void RenderStreamAsync(string Format, string StreamID, string DeviceInfo, object userState)
{
if (RenderStreamOperationCompleted == null)
{
RenderStreamOperationCompleted = OnRenderStreamOperationCompleted;
}
InvokeAsync("RenderStream", new object[3]
{
Format,
StreamID,
DeviceInfo
}, RenderStreamOperationCompleted, userState);
}
private void OnRenderStreamOperationCompleted(object arg)
{
if (this.RenderStreamCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.RenderStreamCompleted(this, new RenderStreamCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/GetExecutionInfo", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo GetExecutionInfo()
{
return (ExecutionInfo)Invoke("GetExecutionInfo", new object[0])[0];
}
public IAsyncResult BeginGetExecutionInfo(AsyncCallback callback, object asyncState)
{
return BeginInvoke("GetExecutionInfo", new object[0], callback, asyncState);
}
public ExecutionInfo EndGetExecutionInfo(IAsyncResult asyncResult)
{
return (ExecutionInfo)EndInvoke(asyncResult)[0];
}
public void GetExecutionInfoAsync()
{
GetExecutionInfoAsync(null);
}
public void GetExecutionInfoAsync(object userState)
{
if (GetExecutionInfoOperationCompleted == null)
{
GetExecutionInfoOperationCompleted = OnGetExecutionInfoOperationCompleted;
}
InvokeAsync("GetExecutionInfo", new object[0], GetExecutionInfoOperationCompleted, userState);
}
private void OnGetExecutionInfoOperationCompleted(object arg)
{
if (this.GetExecutionInfoCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.GetExecutionInfoCompleted(this, new GetExecutionInfoCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/GetExecutionInfo2", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo2 GetExecutionInfo2()
{
return (ExecutionInfo2)Invoke("GetExecutionInfo2", new object[0])[0];
}
public IAsyncResult BeginGetExecutionInfo2(AsyncCallback callback, object asyncState)
{
return BeginInvoke("GetExecutionInfo2", new object[0], callback, asyncState);
}
public ExecutionInfo2 EndGetExecutionInfo2(IAsyncResult asyncResult)
{
return (ExecutionInfo2)EndInvoke(asyncResult)[0];
}
public void GetExecutionInfo2Async()
{
GetExecutionInfo2Async(null);
}
public void GetExecutionInfo2Async(object userState)
{
if (GetExecutionInfo2OperationCompleted == null)
{
GetExecutionInfo2OperationCompleted = OnGetExecutionInfo2OperationCompleted;
}
InvokeAsync("GetExecutionInfo2", new object[0], GetExecutionInfo2OperationCompleted, userState);
}
private void OnGetExecutionInfo2OperationCompleted(object arg)
{
if (this.GetExecutionInfo2Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.GetExecutionInfo2Completed(this, new GetExecutionInfo2CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/GetExecutionInfo3", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("executionInfo")]
public ExecutionInfo3 GetExecutionInfo3()
{
return (ExecutionInfo3)Invoke("GetExecutionInfo3", new object[0])[0];
}
public IAsyncResult BeginGetExecutionInfo3(AsyncCallback callback, object asyncState)
{
return BeginInvoke("GetExecutionInfo3", new object[0], callback, asyncState);
}
public ExecutionInfo3 EndGetExecutionInfo3(IAsyncResult asyncResult)
{
return (ExecutionInfo3)EndInvoke(asyncResult)[0];
}
public void GetExecutionInfo3Async()
{
GetExecutionInfo3Async(null);
}
public void GetExecutionInfo3Async(object userState)
{
if (GetExecutionInfo3OperationCompleted == null)
{
GetExecutionInfo3OperationCompleted = OnGetExecutionInfo3OperationCompleted;
}
InvokeAsync("GetExecutionInfo3", new object[0], GetExecutionInfo3OperationCompleted, userState);
}
private void OnGetExecutionInfo3OperationCompleted(object arg)
{
if (this.GetExecutionInfo3Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.GetExecutionInfo3Completed(this, new GetExecutionInfo3CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/GetDocumentMap", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("result")]
public DocumentMapNode GetDocumentMap()
{
return (DocumentMapNode)Invoke("GetDocumentMap", new object[0])[0];
}
public IAsyncResult BeginGetDocumentMap(AsyncCallback callback, object asyncState)
{
return BeginInvoke("GetDocumentMap", new object[0], callback, asyncState);
}
public DocumentMapNode EndGetDocumentMap(IAsyncResult asyncResult)
{
return (DocumentMapNode)EndInvoke(asyncResult)[0];
}
public void GetDocumentMapAsync()
{
GetDocumentMapAsync(null);
}
public void GetDocumentMapAsync(object userState)
{
if (GetDocumentMapOperationCompleted == null)
{
GetDocumentMapOperationCompleted = OnGetDocumentMapOperationCompleted;
}
InvokeAsync("GetDocumentMap", new object[0], GetDocumentMapOperationCompleted, userState);
}
private void OnGetDocumentMapOperationCompleted(object arg)
{
if (this.GetDocumentMapCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.GetDocumentMapCompleted(this, new GetDocumentMapCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue", Direction = SoapHeaderDirection.InOut)]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/LoadDrillthroughTarget", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("ExecutionInfo")]
public ExecutionInfo LoadDrillthroughTarget(string DrillthroughID)
{
return (ExecutionInfo)Invoke("LoadDrillthroughTarget", new object[1]
{
DrillthroughID
})[0];
}
public IAsyncResult BeginLoadDrillthroughTarget(string DrillthroughID, AsyncCallback callback, object asyncState)
{
return BeginInvoke("LoadDrillthroughTarget", new object[1]
{
DrillthroughID
}, callback, asyncState);
}
public ExecutionInfo EndLoadDrillthroughTarget(IAsyncResult asyncResult)
{
return (ExecutionInfo)EndInvoke(asyncResult)[0];
}
public void LoadDrillthroughTargetAsync(string DrillthroughID)
{
LoadDrillthroughTargetAsync(DrillthroughID, null);
}
public void LoadDrillthroughTargetAsync(string DrillthroughID, object userState)
{
if (LoadDrillthroughTargetOperationCompleted == null)
{
LoadDrillthroughTargetOperationCompleted = OnLoadDrillthroughTargetOperationCompleted;
}
InvokeAsync("LoadDrillthroughTarget", new object[1]
{
DrillthroughID
}, LoadDrillthroughTargetOperationCompleted, userState);
}
private void OnLoadDrillthroughTargetOperationCompleted(object arg)
{
if (this.LoadDrillthroughTargetCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.LoadDrillthroughTargetCompleted(this, new LoadDrillthroughTargetCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue", Direction = SoapHeaderDirection.InOut)]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/LoadDrillthroughTarget2", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("ExecutionInfo")]
public ExecutionInfo2 LoadDrillthroughTarget2(string DrillthroughID)
{
return (ExecutionInfo2)Invoke("LoadDrillthroughTarget2", new object[1]
{
DrillthroughID
})[0];
}
public IAsyncResult BeginLoadDrillthroughTarget2(string DrillthroughID, AsyncCallback callback, object asyncState)
{
return BeginInvoke("LoadDrillthroughTarget2", new object[1]
{
DrillthroughID
}, callback, asyncState);
}
public ExecutionInfo2 EndLoadDrillthroughTarget2(IAsyncResult asyncResult)
{
return (ExecutionInfo2)EndInvoke(asyncResult)[0];
}
public void LoadDrillthroughTarget2Async(string DrillthroughID)
{
LoadDrillthroughTarget2Async(DrillthroughID, null);
}
public void LoadDrillthroughTarget2Async(string DrillthroughID, object userState)
{
if (LoadDrillthroughTarget2OperationCompleted == null)
{
LoadDrillthroughTarget2OperationCompleted = OnLoadDrillthroughTarget2OperationCompleted;
}
InvokeAsync("LoadDrillthroughTarget2", new object[1]
{
DrillthroughID
}, LoadDrillthroughTarget2OperationCompleted, userState);
}
private void OnLoadDrillthroughTarget2OperationCompleted(object arg)
{
if (this.LoadDrillthroughTarget2Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.LoadDrillthroughTarget2Completed(this, new LoadDrillthroughTarget2CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue", Direction = SoapHeaderDirection.InOut)]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/LoadDrillthroughTarget3", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("ExecutionInfo")]
public ExecutionInfo3 LoadDrillthroughTarget3(string DrillthroughID)
{
return (ExecutionInfo3)Invoke("LoadDrillthroughTarget3", new object[1]
{
DrillthroughID
})[0];
}
public IAsyncResult BeginLoadDrillthroughTarget3(string DrillthroughID, AsyncCallback callback, object asyncState)
{
return BeginInvoke("LoadDrillthroughTarget3", new object[1]
{
DrillthroughID
}, callback, asyncState);
}
public ExecutionInfo3 EndLoadDrillthroughTarget3(IAsyncResult asyncResult)
{
return (ExecutionInfo3)EndInvoke(asyncResult)[0];
}
public void LoadDrillthroughTarget3Async(string DrillthroughID)
{
LoadDrillthroughTarget3Async(DrillthroughID, null);
}
public void LoadDrillthroughTarget3Async(string DrillthroughID, object userState)
{
if (LoadDrillthroughTarget3OperationCompleted == null)
{
LoadDrillthroughTarget3OperationCompleted = OnLoadDrillthroughTarget3OperationCompleted;
}
InvokeAsync("LoadDrillthroughTarget3", new object[1]
{
DrillthroughID
}, LoadDrillthroughTarget3OperationCompleted, userState);
}
private void OnLoadDrillthroughTarget3OperationCompleted(object arg)
{
if (this.LoadDrillthroughTarget3Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.LoadDrillthroughTarget3Completed(this, new LoadDrillthroughTarget3CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/ToggleItem", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("Found")]
public bool ToggleItem(string ToggleID)
{
return (bool)Invoke("ToggleItem", new object[1]
{
ToggleID
})[0];
}
public IAsyncResult BeginToggleItem(string ToggleID, AsyncCallback callback, object asyncState)
{
return BeginInvoke("ToggleItem", new object[1]
{
ToggleID
}, callback, asyncState);
}
public bool EndToggleItem(IAsyncResult asyncResult)
{
return (bool)EndInvoke(asyncResult)[0];
}
public void ToggleItemAsync(string ToggleID)
{
ToggleItemAsync(ToggleID, null);
}
public void ToggleItemAsync(string ToggleID, object userState)
{
if (ToggleItemOperationCompleted == null)
{
ToggleItemOperationCompleted = OnToggleItemOperationCompleted;
}
InvokeAsync("ToggleItem", new object[1]
{
ToggleID
}, ToggleItemOperationCompleted, userState);
}
private void OnToggleItemOperationCompleted(object arg)
{
if (this.ToggleItemCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.ToggleItemCompleted(this, new ToggleItemCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/NavigateDocumentMap", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("PageNumber")]
public int NavigateDocumentMap(string DocMapID)
{
return (int)Invoke("NavigateDocumentMap", new object[1]
{
DocMapID
})[0];
}
public IAsyncResult BeginNavigateDocumentMap(string DocMapID, AsyncCallback callback, object asyncState)
{
return BeginInvoke("NavigateDocumentMap", new object[1]
{
DocMapID
}, callback, asyncState);
}
public int EndNavigateDocumentMap(IAsyncResult asyncResult)
{
return (int)EndInvoke(asyncResult)[0];
}
public void NavigateDocumentMapAsync(string DocMapID)
{
NavigateDocumentMapAsync(DocMapID, null);
}
public void NavigateDocumentMapAsync(string DocMapID, object userState)
{
if (NavigateDocumentMapOperationCompleted == null)
{
NavigateDocumentMapOperationCompleted = OnNavigateDocumentMapOperationCompleted;
}
InvokeAsync("NavigateDocumentMap", new object[1]
{
DocMapID
}, NavigateDocumentMapOperationCompleted, userState);
}
private void OnNavigateDocumentMapOperationCompleted(object arg)
{
if (this.NavigateDocumentMapCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.NavigateDocumentMapCompleted(this, new NavigateDocumentMapCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/NavigateBookmark", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("PageNumber")]
public int NavigateBookmark(string BookmarkID, out string UniqueName)
{
object[] array = Invoke("NavigateBookmark", new object[1]
{
BookmarkID
});
UniqueName = (string)array[1];
return (int)array[0];
}
public IAsyncResult BeginNavigateBookmark(string BookmarkID, AsyncCallback callback, object asyncState)
{
return BeginInvoke("NavigateBookmark", new object[1]
{
BookmarkID
}, callback, asyncState);
}
public int EndNavigateBookmark(IAsyncResult asyncResult, out string UniqueName)
{
object[] array = EndInvoke(asyncResult);
UniqueName = (string)array[1];
return (int)array[0];
}
public void NavigateBookmarkAsync(string BookmarkID)
{
NavigateBookmarkAsync(BookmarkID, null);
}
public void NavigateBookmarkAsync(string BookmarkID, object userState)
{
if (NavigateBookmarkOperationCompleted == null)
{
NavigateBookmarkOperationCompleted = OnNavigateBookmarkOperationCompleted;
}
InvokeAsync("NavigateBookmark", new object[1]
{
BookmarkID
}, NavigateBookmarkOperationCompleted, userState);
}
private void OnNavigateBookmarkOperationCompleted(object arg)
{
if (this.NavigateBookmarkCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.NavigateBookmarkCompleted(this, new NavigateBookmarkCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/FindString", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("PageNumber")]
public int FindString(int StartPage, int EndPage, string FindValue)
{
return (int)Invoke("FindString", new object[3]
{
StartPage,
EndPage,
FindValue
})[0];
}
public IAsyncResult BeginFindString(int StartPage, int EndPage, string FindValue, AsyncCallback callback, object asyncState)
{
return BeginInvoke("FindString", new object[3]
{
StartPage,
EndPage,
FindValue
}, callback, asyncState);
}
public int EndFindString(IAsyncResult asyncResult)
{
return (int)EndInvoke(asyncResult)[0];
}
public void FindStringAsync(int StartPage, int EndPage, string FindValue)
{
FindStringAsync(StartPage, EndPage, FindValue, null);
}
public void FindStringAsync(int StartPage, int EndPage, string FindValue, object userState)
{
if (FindStringOperationCompleted == null)
{
FindStringOperationCompleted = OnFindStringOperationCompleted;
}
InvokeAsync("FindString", new object[3]
{
StartPage,
EndPage,
FindValue
}, FindStringOperationCompleted, userState);
}
private void OnFindStringOperationCompleted(object arg)
{
if (this.FindStringCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.FindStringCompleted(this, new FindStringCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/Sort", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("PageNumber")]
public int Sort(string SortItem, SortDirectionEnum Direction, bool Clear, out string ReportItem, out int NumPages)
{
object[] array = Invoke("Sort", new object[3]
{
SortItem,
Direction,
Clear
});
ReportItem = (string)array[1];
NumPages = (int)array[2];
return (int)array[0];
}
public IAsyncResult BeginSort(string SortItem, SortDirectionEnum Direction, bool Clear, AsyncCallback callback, object asyncState)
{
return BeginInvoke("Sort", new object[3]
{
SortItem,
Direction,
Clear
}, callback, asyncState);
}
public int EndSort(IAsyncResult asyncResult, out string ReportItem, out int NumPages)
{
object[] array = EndInvoke(asyncResult);
ReportItem = (string)array[1];
NumPages = (int)array[2];
return (int)array[0];
}
public void SortAsync(string SortItem, SortDirectionEnum Direction, bool Clear)
{
SortAsync(SortItem, Direction, Clear, null);
}
public void SortAsync(string SortItem, SortDirectionEnum Direction, bool Clear, object userState)
{
if (SortOperationCompleted == null)
{
SortOperationCompleted = OnSortOperationCompleted;
}
InvokeAsync("Sort", new object[3]
{
SortItem,
Direction,
Clear
}, SortOperationCompleted, userState);
}
private void OnSortOperationCompleted(object arg)
{
if (this.SortCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.SortCompleted(this, new SortCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/Sort2", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("PageNumber")]
public int Sort2(string SortItem, SortDirectionEnum Direction, bool Clear, PageCountMode PaginationMode, out string ReportItem, out ExecutionInfo2 ExecutionInfo)
{
object[] array = Invoke("Sort2", new object[4]
{
SortItem,
Direction,
Clear,
PaginationMode
});
ReportItem = (string)array[1];
ExecutionInfo = (ExecutionInfo2)array[2];
return (int)array[0];
}
public IAsyncResult BeginSort2(string SortItem, SortDirectionEnum Direction, bool Clear, PageCountMode PaginationMode, AsyncCallback callback, object asyncState)
{
return BeginInvoke("Sort2", new object[4]
{
SortItem,
Direction,
Clear,
PaginationMode
}, callback, asyncState);
}
public int EndSort2(IAsyncResult asyncResult, out string ReportItem, out ExecutionInfo2 ExecutionInfo)
{
object[] array = EndInvoke(asyncResult);
ReportItem = (string)array[1];
ExecutionInfo = (ExecutionInfo2)array[2];
return (int)array[0];
}
public void Sort2Async(string SortItem, SortDirectionEnum Direction, bool Clear, PageCountMode PaginationMode)
{
Sort2Async(SortItem, Direction, Clear, PaginationMode, null);
}
public void Sort2Async(string SortItem, SortDirectionEnum Direction, bool Clear, PageCountMode PaginationMode, object userState)
{
if (Sort2OperationCompleted == null)
{
Sort2OperationCompleted = OnSort2OperationCompleted;
}
InvokeAsync("Sort2", new object[4]
{
SortItem,
Direction,
Clear,
PaginationMode
}, Sort2OperationCompleted, userState);
}
private void OnSort2OperationCompleted(object arg)
{
if (this.Sort2Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.Sort2Completed(this, new Sort2CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("ExecutionHeaderValue")]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/Sort3", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("PageNumber")]
public int Sort3(string SortItem, SortDirectionEnum Direction, bool Clear, PageCountMode PaginationMode, out string ReportItem, out ExecutionInfo3 ExecutionInfo)
{
object[] array = Invoke("Sort3", new object[4]
{
SortItem,
Direction,
Clear,
PaginationMode
});
ReportItem = (string)array[1];
ExecutionInfo = (ExecutionInfo3)array[2];
return (int)array[0];
}
public IAsyncResult BeginSort3(string SortItem, SortDirectionEnum Direction, bool Clear, PageCountMode PaginationMode, AsyncCallback callback, object asyncState)
{
return BeginInvoke("Sort3", new object[4]
{
SortItem,
Direction,
Clear,
PaginationMode
}, callback, asyncState);
}
public int EndSort3(IAsyncResult asyncResult, out string ReportItem, out ExecutionInfo3 ExecutionInfo)
{
object[] array = EndInvoke(asyncResult);
ReportItem = (string)array[1];
ExecutionInfo = (ExecutionInfo3)array[2];
return (int)array[0];
}
public void Sort3Async(string SortItem, SortDirectionEnum Direction, bool Clear, PageCountMode PaginationMode)
{
Sort3Async(SortItem, Direction, Clear, PaginationMode, null);
}
public void Sort3Async(string SortItem, SortDirectionEnum Direction, bool Clear, PageCountMode PaginationMode, object userState)
{
if (Sort3OperationCompleted == null)
{
Sort3OperationCompleted = OnSort3OperationCompleted;
}
InvokeAsync("Sort3", new object[4]
{
SortItem,
Direction,
Clear,
PaginationMode
}, Sort3OperationCompleted, userState);
}
private void OnSort3OperationCompleted(object arg)
{
if (this.Sort3Completed != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.Sort3Completed(this, new Sort3CompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/GetRenderResource", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlElement("Result", DataType = "base64Binary")]
public byte[] GetRenderResource(string Format, string DeviceInfo, out string MimeType)
{
object[] array = Invoke("GetRenderResource", new object[2]
{
Format,
DeviceInfo
});
MimeType = (string)array[1];
return (byte[])array[0];
}
public IAsyncResult BeginGetRenderResource(string Format, string DeviceInfo, AsyncCallback callback, object asyncState)
{
return BeginInvoke("GetRenderResource", new object[2]
{
Format,
DeviceInfo
}, callback, asyncState);
}
public byte[] EndGetRenderResource(IAsyncResult asyncResult, out string MimeType)
{
object[] array = EndInvoke(asyncResult);
MimeType = (string)array[1];
return (byte[])array[0];
}
public void GetRenderResourceAsync(string Format, string DeviceInfo)
{
GetRenderResourceAsync(Format, DeviceInfo, null);
}
public void GetRenderResourceAsync(string Format, string DeviceInfo, object userState)
{
if (GetRenderResourceOperationCompleted == null)
{
GetRenderResourceOperationCompleted = OnGetRenderResourceOperationCompleted;
}
InvokeAsync("GetRenderResource", new object[2]
{
Format,
DeviceInfo
}, GetRenderResourceOperationCompleted, userState);
}
private void OnGetRenderResourceOperationCompleted(object arg)
{
if (this.GetRenderResourceCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.GetRenderResourceCompleted(this, new GetRenderResourceCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapHeader("TrustedUserHeaderValue")]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/ListRenderingExtensions", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
[return: XmlArray("Extensions")]
public Extension[] ListRenderingExtensions()
{
return (Extension[])Invoke("ListRenderingExtensions", new object[0])[0];
}
public IAsyncResult BeginListRenderingExtensions(AsyncCallback callback, object asyncState)
{
return BeginInvoke("ListRenderingExtensions", new object[0], callback, asyncState);
}
public Extension[] EndListRenderingExtensions(IAsyncResult asyncResult)
{
return (Extension[])EndInvoke(asyncResult)[0];
}
public void ListRenderingExtensionsAsync()
{
ListRenderingExtensionsAsync(null);
}
public void ListRenderingExtensionsAsync(object userState)
{
if (ListRenderingExtensionsOperationCompleted == null)
{
ListRenderingExtensionsOperationCompleted = OnListRenderingExtensionsOperationCompleted;
}
InvokeAsync("ListRenderingExtensions", new object[0], ListRenderingExtensionsOperationCompleted, userState);
}
private void OnListRenderingExtensionsOperationCompleted(object arg)
{
if (this.ListRenderingExtensionsCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.ListRenderingExtensionsCompleted(this, new ListRenderingExtensionsCompletedEventArgs(invokeCompletedEventArgs.Results, invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/LogonUser", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
public void LogonUser(string userName, string password, string authority)
{
Invoke("LogonUser", new object[3]
{
userName,
password,
authority
});
}
public IAsyncResult BeginLogonUser(string userName, string password, string authority, AsyncCallback callback, object asyncState)
{
return BeginInvoke("LogonUser", new object[3]
{
userName,
password,
authority
}, callback, asyncState);
}
public void EndLogonUser(IAsyncResult asyncResult)
{
EndInvoke(asyncResult);
}
public void LogonUserAsync(string userName, string password, string authority)
{
LogonUserAsync(userName, password, authority, null);
}
public void LogonUserAsync(string userName, string password, string authority, object userState)
{
if (LogonUserOperationCompleted == null)
{
LogonUserOperationCompleted = OnLogonUserOperationCompleted;
}
InvokeAsync("LogonUser", new object[3]
{
userName,
password,
authority
}, LogonUserOperationCompleted, userState);
}
private void OnLogonUserOperationCompleted(object arg)
{
if (this.LogonUserCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.LogonUserCompleted(this, new AsyncCompletedEventArgs(invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
[SoapHeader("ServerInfoHeaderValue", Direction = SoapHeaderDirection.Out)]
[SoapDocumentMethod("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices/Logoff", RequestNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", ResponseNamespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped)]
public void Logoff()
{
Invoke("Logoff", new object[0]);
}
public IAsyncResult BeginLogoff(AsyncCallback callback, object asyncState)
{
return BeginInvoke("Logoff", new object[0], callback, asyncState);
}
public void EndLogoff(IAsyncResult asyncResult)
{
EndInvoke(asyncResult);
}
public void LogoffAsync()
{
LogoffAsync(null);
}
public void LogoffAsync(object userState)
{
if (LogoffOperationCompleted == null)
{
LogoffOperationCompleted = OnLogoffOperationCompleted;
}
InvokeAsync("Logoff", new object[0], LogoffOperationCompleted, userState);
}
private void OnLogoffOperationCompleted(object arg)
{
if (this.LogoffCompleted != null)
{
InvokeCompletedEventArgs invokeCompletedEventArgs = (InvokeCompletedEventArgs)arg;
this.LogoffCompleted(this, new AsyncCompletedEventArgs(invokeCompletedEventArgs.Error, invokeCompletedEventArgs.Cancelled, invokeCompletedEventArgs.UserState));
}
}
public new void CancelAsync(object userState)
{
base.CancelAsync(userState);
}
}
}
<file_sep>using System.CodeDom.Compiler;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[GeneratedCode("wsdl", "2.0.50727.42")]
public delegate void LoadDrillthroughTarget3CompletedEventHandler(object sender, LoadDrillthroughTarget3CompletedEventArgs e);
}
<file_sep>using System.CodeDom.Compiler;
using System.ComponentModel;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[GeneratedCode("wsdl", "2.0.50727.42")]
[EditorBrowsable(EditorBrowsableState.Never)]
public delegate void SetExecutionCredentials2CompletedEventHandler(object sender, SetExecutionCredentials2CompletedEventArgs e);
}
<file_sep>using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[Serializable]
[XmlInclude(typeof(ExecutionInfo3))]
[GeneratedCode("wsdl", "2.0.50727.42")]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ExecutionInfo2 : ExecutionInfo
{
private PageCountMode pageCountModeField;
public PageCountMode PageCountMode
{
get
{
return pageCountModeField;
}
set
{
pageCountModeField = value;
}
}
}
}
| f6ff940e2ed7402ca4f75dbd97b877858d05e58c | [
"C#"
] | 32 | C# | orellabac/reportviewercore | 41ef373aca1004c7e0e345a1c9946e633bdc2a2c | f1f01a2e9ee1ad18d0b3c8284f8ffd1a43b34409 | |
refs/heads/master | <repo_name>jorge9797/inventario<file_sep>/js/dashboard/login.js
$(document).ready(function(){
$('#frm-login').submit(function(event){
let usuario=$('#usuario').val();
let contrasena=$('#contrasena').val();
$.ajax({
method:'POST',
url:'./index.php?c=login&a=login',
data:{usuario:usuario,contrasena:contrasena},
dataType:'json',
}).done(function(data,textStatus,jqXHR){
if(parseInt(data.estado)===1){
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
});
toast({
type: 'success',
title: 'Bienvenido '+data.nombre+' '+data.apellido
}).then(()=>{
location.href ="./index.php?c=usuarios&a=index";
});
}
else if(data.estado===3){
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
});
toast({
type: 'error',
title: 'Usuario o contraseña invalidas'
})
}
else{
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
});
toast({
type: 'error',
title: 'Usuario actualmente inactivo'
})
}
}).fail(function(jqXHR,textStatus){
console.log(textStatus);
})
event.preventDefault();
});
});<file_sep>/controllers/usuarios.controller.php
<?php
//Requerir las entidades para el mapeo
//Requerir el modelo cuando este echo
//Requerir el archvio de la bd
require_once('bd/conexion.php');
class UsuariosController{
//Variable que generara la instamcia del modelo para ser utilizada
private $model;
public function __CONSTRUCT(){
//Inicializar modelo
}
public function index(){
require_once('views/usuarios/usuarios.view.php');
}
public function ingresarUsuario(){
}
public function actualizarUsuario(){
}
public function eliminarUsuario(){
}
}
?><file_sep>/controllers/login.controller.php
<?php
require_once('models/entities/usuarios.entity.php');
require_once('models/models/usuarios.model.php');
class LoginController{
private $model;
public function __CONSTRUCT(){
$model=new UsuariosModel();
}
//Retorna la vista de login
public function index(){
require_once('views/usuarios/login.view.php');
}
//Metodo para ingresar
public function login(){
session_start();
$usuario=new Usuario();
$usuario->__SET('usuario',$_REQUEST['usuario']);
$usuario->__SET('contrasena',$_REQUEST['contrasena']);
$model=new UsuariosModel();
$user=$model->login($usuario);
if($user==null){
$objeto = new stdClass();
$objeto->estado=3;
echo json_encode($objeto);
}
else{
echo $user->toJSON();;
}
}
//Metodo para cerrar session
public function logout(){
}
}
?><file_sep>/bd/parametros.php
<?php
define('DB_HOST','localhost');
define ('DB_USER','root');
define ('DB_PASS','');
define ('DB_NAME','inventario');
define('DB_CHARSET','utf-8');
?>
<file_sep>/views/usuarios/login.view.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php include('views/modules/headers.php'); ?>
</head>
<body class="bg-dark">
<div class="container">
<div class="card card-login mx-auto mt-5">
<div class="card-header">Login</div>
<div class="card-body">
<form method="POST" id="frm-login" >
<div class="form-group">
<label for="usuario">Usuario</label>
<input class="form-control" id="usuario" type="text" aria-describedby="emailHelp" placeholder="Usuario" autocomplete="off" required>
</div>
<div class="form-group">
<label for="contrasena">Contraseña</label>
<input class="form-control" id="contrasena" type="password" placeholder="<PASSWORD>" autocomplete="off" required>
</div>
<div class="form-group">
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox"> Recordarme</label>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block" href="index.php">Login</button>
</form>
<div class="text-center">
<a class="d-block small mt-3" href="forgot-password.html">Forgot Password?</a>
</div>
</div>
</div>
</div>
<?php include('views/modules/scroll_button.php')?>
<?php include('views/modules/logout_modal.php')?>
<?php require('views/modules/scripts.php')?>
</body>
</html><file_sep>/models/models/usuarios.model.php
<?php
require_once('bd/conexion.php');
require_once('models/entities/usuarios.entity.php');
class UsuariosModel{
private $db;
public function __CONSTRUCT(){
}
public function listarUsuarios(){
$db=new Conexion_db();
$result=array();
//Llamada al procedimiento almacenado
$sql="call listar_usuarios();";
$stmt=$db->__GET('_db')->prepare($sql);
if($stmt->execute()){
foreach($stmt->fetchAll(PDO::FETCH_OBJ) as $fila){
$user=new Usuario();
$user->__SET('id_usuario', $fila->id_usuario);
$user->__SET('nombre', $fila->nombre);
$user->__SET('apellido', $fila->apellido);
$user->__SET('id_tipo_usuario', $fila->id_tipo_usuario);
$user->__SET('usuario', $fila->usuario);
$user->__SET('estado', $fila->estado);
$user->__SET('contrasena', $fila->contrasena);
$result[]=$user;
}
}
return $result;
}
//Resive un objeto de tipo usuario
public function login($usuario){
$db=new Conexion_db();
$usr=null;
//Los objetos nos se pueden pasar por referencia
$contrasena=$usuario->__GET('contrasena');
$usuario=$usuario->__GET('usuario');
$sql="call login(:usuario,:contrasena)";
$stmt=$db->__GET('_db')->prepare($sql);
$stmt->bindParam('usuario',$usuario);
$stmt->bindParam('contrasena',$contrasena);
if($stmt->execute()){
foreach($stmt->fetchAll(PDO::FETCH_OBJ) as $fila){
$usr=new Usuario();
$usr->__SET('id_usuario', $fila->id_usuario);
$usr->__SET('nombre', $fila->nombre);
$usr->__SET('apellido', $fila->apellido);
$usr->__SET('estado', $fila->estado);
$usr->__SET('usuario',$fila->usuario);
$usr->__SET('contrasena',$fila->contrasena);
$usr->__SET('id_tipo_usuario', $fila->id_tipo_usuario);
}
}
return $usr;
}
public function agregarUsuario(){
}
public function eliminarUsuario($usuario){
}
public function editarUsuario($usuario){
}
}
?><file_sep>/bd/conexion.php
<?php
require("parametros.php");
class Conexion_db
{
private $_db;
public function __GET($k){ return $this->$k; }
public function __CONSTRUCT()
{
$dsn = "mysql:dbname=".DB_NAME.";host=".DB_HOST;
$usuario = DB_USER;
$contraseña = <PASSWORD>;
try {
$this->_db = new PDO($dsn, $usuario, $contraseña);
}
catch (PDOException $e) {
echo 'Falló la conexión: ' . $e->getMessage();
}
}
}
?>
<file_sep>/models/entities/usuarios.entity.php
<?php
class Usuario{
private $id_usuario;
private $id_tipo_usuario;
private $nombre;
private $apellido;
private $usuario;
private $contrasena;
private $estado;
public function __GET($k){ return $this->$k; }
public function __SET($k, $v){ return $this->$k = $v; }
//Funcion para retornar json con las propiedades (por problema de la visibilidad no se puede usar
//directamente json_encode()
public function toJSON(){
$json = array(
'id_usuario'=>$this->__GET('id_usuario'),
'usuario' => $this->__GET('usuario'),
'contrasena' => $this->__GET('contrasena'),
'estado' => $this->__GET('estado'),
'nombre' => $this->__GET('nombre'),
'apellido' => $this->__GET('apellido'),
'id_tipo_usuario'=>$this->__GET('id_tipo_usuario')
);
return json_encode($json);
}
}
?> | 7d604ee2a3e06d81020008adec7a93606342e92f | [
"JavaScript",
"PHP"
] | 8 | JavaScript | jorge9797/inventario | 4abc1756e5e5682af39537ec8c89e0b393eb71e8 | cd417ecd9fc9d310148d2558f75beffc5bdeafa4 | |
refs/heads/master | <repo_name>mekhalajoshi/Movie-Search<file_sep>/src/api/getOmdbData.js
const PATH_BASE = 'https://www.omdbapi.com/?apikey=5d9a0e5e'
const PARAM_SEARCH_TITLE = '&s='
const PARAM_SEARCH_ID = '&i='
export async function getMoviesByTitle (searchTerm) {
const res = await fetch(`${PATH_BASE}${PARAM_SEARCH_TITLE}${searchTerm}`)
const data = await res.json()
return data.Search
}
export async function getMoviesById(searchTerm) {
const res = await fetch(`${PATH_BASE}${PARAM_SEARCH_ID}${searchTerm}`)
const data = await res.json()
return data;
}
<file_sep>/src/App.js
import React, { Component } from 'react'
import MovieSearchApp from './components/MovieSearchApp';
class App extends Component {
render() {
return (
<div >
<MovieSearchApp />
</div>
);
}
}
export default App;
<file_sep>/src/components/MovieCard.jsx
import React, { Component } from 'react'
import MovieDetails from './MovieDetails'
import PropTypes from 'prop-types';
import { getMoviesById} from '../api/getOmdbData.js'
import { Card, CardMedia, CardActionArea, CardContent, Typography } from '@material-ui/core'
const styles = {
Card: {
width: '250px',
height: '400px',
margin: 'auto'
},
CardMedia: {
width: 'auto',
height: '100%',
maxHeight: '350px',
maxWidth: '250px',
margin: 'auto'
},
CardContent: {
padding: '5px'
},
Typography: {
margin: 0,
overflowWrap: 'break-word'
}
}
// const movie = {
// Title: 'Rogue One: A Star Wars Story',
// Year: '2016',
// imdbID: 'tt3748528',
// Type: 'movie',
// Poster: 'https://m.media-amazon.com/images/M/MV5BMjEwMzMxODIzOV5BMl5BanBnXkFtZTgwNzg3OTAzMDI@._V1_SX300.jpg',
// Plot: 'The daughter of an Imperial scientist joins the Rebel Alliance in a risky move to steal the Death Star plans.',
// Actors: '<NAME>, <NAME>, <NAME>, <NAME>'
// }
export default class MovieCard extends Component {
constructor (props) {
super(props)
this.state = {
MovieDetails: [],
open: false
}
}
async getMovieDetails(){
const m = await getMoviesById(this.props.imdbID);
this.setState({
MovieDetails: m
})
return m
}
handleClickClose=()=>{
this.setState({
open: !this.state.open,
})
}
handleClickOpen = () => {
this.getMovieDetails(this.props.imdbID)
this.setState({
open: !this.state.open,
})
}
render () {
return (
<div>
<Card
style={styles.Card}
>
<CardActionArea
onClick={this.handleClickOpen}
>
<CardMedia
style={styles.CardMedia}
component="img"
alt={this.props.title}
image={this.props.poster}
title={this.props.title}
/>
<CardContent
style={styles.CardContent}
>
<Typography
style={styles.Typography}
gutterBottom
variant="subtitle2" >
{this.props.title}
</Typography>
</CardContent>
<MovieDetails
open={this.state.open}
onClose={this.handleClickClose}
key={this.props.imdbID}
title={this.props.title}
poster={this.props.poster}
year={this.props.year}
imdbID={this.props.imdbID}
plot={this.state.MovieDetails.Plot}
actors={this.state.MovieDetails.Actors}
/>
</CardActionArea>
</Card>
</div>
)
}
}
MovieCard.propTypes = {
imdbID: PropTypes.string,
title:PropTypes.string,
poster:PropTypes.string,
year:PropTypes.string,
getMovieDetails: PropTypes.func,
};<file_sep>/src/components/MovieDetails.jsx
import React, { Component } from 'react'
import { Dialog, Grid, DialogContent, DialogContentText, DialogTitle } from '@material-ui/core'
export default class MovieDetails extends Component {
render () {
return (
<div>
<Dialog
fullWidth={true}
maxWidth="lg"
open={this.props.open}
onClose={this.props.onClose}
>
<Grid
container
alignContent='flex-start'
alignItems='flex-start'
>
<Grid
item
xs='auto'
style={{ margin: 'auto' }}
>
<img style={{ height: 350, padding: 7 }} src={this.props.poster} alt={this.props.title} />
</Grid>
<Grid
item
xs={9}
style={{ flexGrow: 2, margin: 'auto' }}
>
<DialogTitle >
{this.props.title} ({this.props.year})
</DialogTitle>
<DialogContent>
<DialogContentText>
Cast:{this.props.actors}
< br />
Plot:{this.props.plot}
</DialogContentText>
</DialogContent>
</Grid>
</Grid>
</Dialog>
</div>
)
}
}
| 670a057e850ed369166ed183925caf16853c5db6 | [
"JavaScript"
] | 4 | JavaScript | mekhalajoshi/Movie-Search | 302005d9d03b53426bfd70ac03d6e91aed5d8e7b | ae34cf8a5306af129a9f19658595b6419661eabd | |
refs/heads/master | <file_sep> <!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0"><?= $title ?></h1>
</div><!-- /.col -->
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="#">Home</a></li>
<li class="breadcrumb-item active"><?= $title ?></li>
</ol>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
</div>
<!-- /.content-header -->
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Daftar Pemasukan yang Telah Terdaftar</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table id="table_list_pemasukan" class="table table-bordered table-striped table-sm">
<thead>
<tr>
<th>No</th>
<th>Keterangan</th>
<th>Jumlah</th>
<th>Tanggal</th>
</tr>
</thead>
<tbody>
<?php
// pembayaran
$no = 1;
foreach ($pembayaran as $pmbyrn) {
?>
<tr>
<td><?= $no ?></td>
<td><?= $pmbyrn->tipe_bayar.' - '.$pmbyrn->nama_asset.' - '.$pmbyrn->block_kavling.' '.$pmbyrn->nama_lengkap?></td>
<td><?= $pmbyrn->jml_bayar?></td>
<td><?= $pmbyrn->tgl_pembayaran?></td>
</tr>
<?php
$no = $no+1;
}
// pemasukan
foreach ($pemasukan as $pmskn) {
?>
<tr>
<td><?= $no ?></td>
<td><?= $pmskn->keterangan ?></td>
<td><?= $pmskn->jumlah ?></td>
<td><?= $pmskn->tgl_pemasukan ?></td>
</tr>
<?php
}
?>
</tbody>
<tfoot>
<tr>
<th>No</th>
<th>Keterangan</th>
<th>Jumlah</th>
<th>Tanggal</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div><!-- /.container-fluid -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper --><file_sep><?php
class Konsumen extends CI_Controller
{
function __construct(){
parent::__construct();
$this->load->model('m_konsumen','konsumen');
}
function json() {
header('Content-Type: application/json');
echo $this->konsumen->json();
}
}
?><file_sep><?php
class Admin extends CI_Controller
{
function __construct(){
parent::__construct();
$this->load->model('m_pemasukan','pemasukan');
}
public function index(){
$this->load->view('admin/templates/header');
$this->load->view('admin/templates/sidebar');
$this->load->view('admin/pages/dashboard_page');
$this->load->view('admin/templates/footer');
}
public function konsumen(){
$data['script'] = 'konsumen';
$data['title'] = 'Daftar Konsumen';
$this->load->view('admin/templates/header', $data);
$this->load->view('admin/templates/sidebar');
$this->load->view('admin/pages/konsumen/list_konsumen');
$this->load->view('admin/templates/footer');
}
public function asset(){
$data['script'] = 'asset';
$data['title'] = 'Daftar Asset';
$this->load->view('admin/templates/header', $data);
$this->load->view('admin/templates/sidebar');
$this->load->view('admin/pages/asset/list_asset');
$this->load->view('admin/templates/footer');
}
public function blok(){
$data['script'] = 'blok';
$data['title'] = 'Daftar Blok';
$this->load->view('admin/templates/header', $data);
$this->load->view('admin/templates/sidebar');
$this->load->view('admin/pages/blok/list_blok');
$this->load->view('admin/templates/footer');
}
public function kepemilikan(){
$data['script'] = 'kepemilikan';
$data['title'] = 'Daftar Kepemilikan';
$this->load->view('admin/templates/header', $data);
$this->load->view('admin/templates/sidebar');
$this->load->view('admin/pages/kepemilikan/list_kepemilikan');
$this->load->view('admin/templates/footer');
}
public function pembayaran(){
$data['script'] = 'pembayaran';
$data['title'] = 'Daftar Pembayaran';
$this->load->view('admin/templates/header', $data);
$this->load->view('admin/templates/sidebar');
$this->load->view('admin/pages/pembayaran/list_pembayaran');
$this->load->view('admin/templates/footer');
}
public function pemasukan(){
$data['pembayaran'] = $this->pemasukan->get_all_pembayaran();
$data['pemasukan'] = $this->pemasukan->get_all_pemasukan();
$data['script'] = 'pemasukan';
$data['title'] = 'Daftar Pembayaran';
$this->load->view('admin/templates/header', $data);
$this->load->view('admin/templates/sidebar');
$this->load->view('admin/pages/pemasukan/list_pemasukan');
$this->load->view('admin/templates/footer');
}
}
?><file_sep><?php
class M_kepemilikan extends CI_Model
{
// untuk menampilkan data ke dtatables dengan serverside
function json() {
// jangan pakai bintang nanti tidak bisa search
$this->datatables->select('tb_kepemilikan.id, tb_konsumen.nama_lengkap, tb_block_kavling.block_kavling, tb_block_kavling.harga_jual, tb_block_kavling.luas_tanah, tb_asset.nama_asset, tb_kepemilikan.status');
$this->datatables->from('tb_kepemilikan');
$this->datatables->join('tb_konsumen', 'tb_kepemilikan.id_pemilik = tb_konsumen.id');
$this->datatables->join('tb_block_kavling', 'tb_kepemilikan.id_block_kavling = tb_block_kavling.id');
$this->datatables->join('tb_asset', 'tb_block_kavling.id_asset = tb_asset.id');
$this->datatables->add_column('block_lengkap' ,'$1 - $2','nama_asset, block_kavling');
$this->datatables->add_column('aksi', '
<a href="javascript:void(0);" class="edit_record badge badge-info"><i class="fas fa-edit lead"></i> Edit</a>
<a href="javascript:void(0);" class="hapus_record badge badge-danger"><i class="fas fa-trash-alt lead"></i> Hapus</a>
','tb_block_kavling.id');
return $this->datatables->generate();
}
}
?><file_sep><?php
class M_pemasukan extends CI_Model
{
public function get_all_pembayaran(){
$this->db->select('tb_pembayaran.id, tb_pembayaran.keterangan, tipe_bayar, jml_bayar, tgl_pembayaran, tb_konsumen.nama_lengkap, tb_block_kavling.block_kavling, tb_asset.nama_asset');
$this->db->from('tb_pembayaran');
$this->db->join('tb_kepemilikan', 'tb_kepemilikan.id = tb_pembayaran.id_kepemilikan');
$this->db->join('tb_konsumen', 'tb_konsumen.id = tb_kepemilikan.id_pemilik');
$this->db->join('tb_block_kavling', 'tb_block_kavling.id = tb_kepemilikan.id_block_kavling');
$this->db->join('tb_asset', 'tb_asset.id = tb_block_kavling.id_asset');
return $this->db->get()->result();
}
public function get_all_pemasukan(){
return $this->db->get('tb_pemasukan')->result();
}
}
?><file_sep><?php
class M_asset extends CI_Model
{
// untuk menampilkan data ke dtatables dengan serverside
function json() {
// jangan pakai bintang nanti tidak bisa search
$this->datatables->select('id, nama_asset, lokasi_asset, foto, tgl_created, jml_blok, sisa_blok');
$this->datatables->from('tb_asset');
$this->datatables->add_column('aksi', '
<a href="javascript:void(0);" class="edit_record badge badge-info"><i class="fas fa-edit lead"></i> Edit</a>
<a href="javascript:void(0);" class="hapus_record badge badge-danger"><i class="fas fa-trash-alt lead"></i> Hapus</a>
','nama_asset');
return $this->datatables->generate();
}
}
?><file_sep><?php
class M_pembayaran extends CI_Model
{
// untuk menampilkan data ke dtatables dengan serverside
function json() {
// jangan pakai bintang nanti tidak bisa search
$this->datatables->select('tb_pembayaran.id, tb_pembayaran.keterangan, tipe_bayar, jml_bayar, tgl_pembayaran, tb_konsumen.nama_lengkap, tb_block_kavling.block_kavling, tb_asset.nama_asset');
$this->datatables->from('tb_pembayaran');
$this->datatables->join('tb_kepemilikan', 'tb_pembayaran.id_kepemilikan = tb_kepemilikan.id');
$this->datatables->join('tb_konsumen', 'tb_kepemilikan.id_pemilik = tb_konsumen.id');
$this->datatables->join('tb_block_kavling', 'tb_block_kavling.id = tb_kepemilikan.id_block_kavling');
$this->datatables->join('tb_asset', 'tb_asset.id = tb_block_kavling.id_asset');
$this->datatables->add_column('block_lengkap' ,'$1 - $2','nama_asset, block_kavling');
$this->datatables->add_column('aksi', '
<a href="javascript:void(0);" class="edit_record badge badge-info"><i class="fas fa-edit lead"></i> Edit</a>
<a href="javascript:void(0);" class="hapus_record badge badge-danger"><i class="fas fa-trash-alt lead"></i> Hapus</a>
','tipe_bayar');
return $this->datatables->generate();
}
}
?><file_sep><?php
class M_konsumen extends CI_Model
{
// untuk menampilkan data ke dtatables dengan serverside
function json() {
// jangan pakai bintang nanti tidak bisa search
$this->datatables->select('id, nama_lengkap, alamat_diri, telp_diri, kartu_identitas, no_identitas, email, tgl_created');
$this->datatables->from('tb_konsumen');
$this->datatables->add_column('nama','<p><b>$1</b><br>$2</p>','kartu_identitas, no_identitas');
$this->datatables->add_column('aksi', '
<a href="javascript:void(0);" class="edit_record badge badge-info"><i class="fas fa-edit lead"></i> Edit</a>
<a href="javascript:void(0);" class="hapus_record badge badge-danger"><i class="fas fa-trash-alt lead"></i> Hapus</a>
','nama_lengkap');
return $this->datatables->generate();
}
}
?><file_sep><?php
class M_pengeluaran extends CI_Model
{
// untuk menampilkan data ke dtatables dengan serverside
function json() {
// jangan pakai bintang nanti tidak bisa search
$this->datatables->select('id, tgl_pengeluaran, keterangan, jumlah');
$this->datatables->from('tb_pengeluaran');
return $this->datatables->generate();
}
}
?><file_sep><?php
class Pemasukan extends CI_Controller
{
function __construct(){
parent::__construct();
$this->load->model('m_pemasukan','pemasukan');
}
function json() {
header('Content-Type: application/json');
echo $this->pemasukan->json();
}
}
?> | 8c7522ed2fc1405183169b2d965e50ff86eea2c7 | [
"PHP"
] | 10 | PHP | mrizkyff/sip-sistem-informasi-properti | d36068fded69e73e15612167b52102e0dbdda15c | 525c1e29c476d2d86959fe4cb3055f0687f096a4 | |
refs/heads/master | <repo_name>tlycken/tusenvuxenpoang<file_sep>/app/src/index.jsx
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import createHistory from 'history/createBrowserHistory'
import { configureStore } from './store/configure.js'
import App from './app/app.jsx'
const history = createHistory()
var configure = {
store: () => configureStore({ history }),
app: App,
css: require('./index.css').default
}
let store = configure.store()
const run = () => {
let App = configure.app
let css = configure.css
render(
<Provider store={store}>
<App history={history} id="app" />
</Provider>,
document.getElementById('react-root')
)
}
run()
if (module.hot) {
module.hot.accept('./app/app.jsx', () => {
var app = require('./app/app.jsx').default
configure = { ...configure, app }
run()
})
module.hot.accept('./index.css', () => {
const css = require('./index.css').default
configure = { ...configure, css }
run()
})
// module.hot.accept(
// './store/configure.js',
// () => {
// const store = require('./store/configure.js').configureStore
// configure = { ...configure, store }
// run()
// }
// )
}
<file_sep>/app/src/pages/rsvp/thanks.jsx
import React from 'react'
export default () => (
<div>
<h2>Tack!</h2>
</div>
)
<file_sep>/app/src/pages/find-your-way/find-your-way.jsx
import React from 'react'
import Map from './map.jsx'
export default () => (
<div>
<h2>Hitta till bröllopet</h2>
<p>
Vi kommer att fira vårt bröllop i Hälleforsnäs, en gammal bruksort i
närheten av Flen och Katrineholm. Hit tar ni er enklast med bil eller tåg.
</p>
<p>
Den korta sträckan från boendet på Granhedsgården till vigseln på Sjöviken
promenerar ni till fots - vi ser till att alla kommer till festen och
sedan tillbaka till Granhedsgården på natten.
</p>
<h3>Tåg</h3>
<p>
SJ kör hela vägen till Hälleforsnäs station, med byte i Eskilstuna för den
som kommer från Stockholm. Från Hälleforsnäs till Granhedsgården och
Sjöviken är det ungefär 6 km - om ni kommer med tåg, berätta det för oss i
förväg, så kan vi försöka ordna skjuts den sträckan!
</p>
<h3> Bil</h3>
<p>
Att köra från Stockholm till Hälleforsnäs tar någonstans mellan 1,5 och 2
timmar, beroende på trafikläget. Granhedsgården går att hitta på google
maps. Precis innan ni kommer fram, om ni kommer från Hälleforsnäs-hållet,
kör ni förbi ett stort rött hus; Sjöviken.
</p>
<Map />
</div>
)
<file_sep>/app/src/pages/accommodation/accommodation.jsx
import React from 'react'
export default () => (
<div>
<h2>Övernattning</h2>
<p>
För övernattning mellan lördagen och söndagen föreslår vi{' '}
<a href="http://www.granhedsgarden.se/">Granhedsgården</a>, som ligger
granne med Sjöviken. Det är en kursgård, med rum av olika storlek och
karaktär, men huvudsakligen vandrarhemsstandard. Vi har reserverat hela
gården, så där finns plats för alla!{' '}
</p>
<p>
Ni bokar sängplats på Granhedsgården genom oss, i samband med OSA till
bröllopet. Även all betalning går via oss; information om det kommer när
ni gjort er reservation. Priset för boende på Granhedsgården är 300 kr per
person.
</p>
<p>
På Granhedsgården finns både bastu och badmöjligheter. Utcheckning behöver
inte ske förrän kl 17, så här finns alla möjligheter att njuta av en lugn
söndag innan återresan till Stockholm.
</p>
<p>
Om man inte vill bo på Granhedsgården finns några andra alternativ:
Katrineholm ett par mil bort erbjuder flera hotell, och på Air BnB går det
att hitta gott om privatpersoner som hyr ut hus i Hälleforsnäs med omnejd.
Tänk bara på att vi bara ordnar transport till Granhedsgården på natten
efter bröllopsfesten - väljer ni att bo någon annanstans får ni ordna resa
dit på natten på egen hand!
</p>
</div>
)
<file_sep>/app/src/pages/pages.jsx
import Home from './home/home.jsx'
import WeddingWeekend from './wedding-weekend/wedding-weekend.jsx'
import FindYourWay from './find-your-way/find-your-way.jsx'
import TheSites from './the-sites/the-sites.jsx'
import Accommodation from './accommodation/accommodation.jsx'
import Rsvp from './rsvp/rsvp.jsx'
export { NotFound } from './errors/errors.jsx'
export { Oops } from './errors/errors.jsx'
export { default as Thanks } from './rsvp/thanks.jsx'
export const menuItems = [
{ url: '/', text: 'Hem', component: Home, exact: true },
{ url: '/brollopshelgen', text: 'Bröllopshelgen', component: WeddingWeekend },
{ url: '/platserna', text: 'Platserna', component: TheSites },
{ url: '/overnattning', text: 'Övernattning', component: Accommodation },
{ url: '/hitta', text: 'Hitta rätt', component: FindYourWay },
{ url: '/osa', text: 'O.S.A.', component: Rsvp }
]
<file_sep>/app/src/pages/find-your-way/map.jsx
import React from 'react'
import {
withGoogleMap,
withScriptjs,
GoogleMap,
Marker
} from 'react-google-maps'
import { compose, withProps } from 'recompose'
import './map.css'
const googleMapURL =
'https://maps.googleapis.com/maps/api/js?v=3.exp&key=<KEY>&libraries=geometry,drawing,places'
const loadingElement = <div style={{ height: '100%' }} />
const containerElement = <div className="map" />
const mapElement = <div style={{ height: '100%' }} />
export default compose(
withProps({
googleMapURL,
loadingElement,
containerElement,
mapElement
}),
withScriptjs,
withGoogleMap
)(props => (
<GoogleMap defaultZoom={13} defaultCenter={{ lat: 59.135, lng: 16.45 }}>
<Marker
position={{ lat: 59.1525932, lng: 16.4894057 }}
label="Bröllopsfest i Kolhuset"
/>
<Marker
position={{ lat: 59.115302, lng: 16.410561 }}
label="Vigsel på Sjöviken"
/>
<Marker
position={{ lat: 59.1135539, lng: 16.4056433 }}
label="Övernattning på Granhedsgården"
/>
</GoogleMap>
))
<file_sep>/deploy.sh
#!/bin/bash
if [[ $# -ne 1 ]]; then
echo "Usage: ./deploy.sh [web|post-rsvp]"
exit 1
fi
if [[ "$1" == "web" ]]; then
echo "Building app..."
cd app && yarn build > /dev/null && cd .. || cd ..
echo "Uploading web assets..."
aws s3 sync ./public s3://tusenvuxenpoang.se --delete --region eu-central-1 > /dev/null
echo "Invalidating CloudFront cache"
aws cloudfront create-invalidation --distribution-id "E4ZXM1QM1OLQJ" --paths /index.html /bundle.js /styles.css > /dev/null
elif [[ "$1" == "post-rsvp" ]]; then
echo "Zipping lambda function..."
cd post-rsvp && zip -ur ../post-rsvp.zip * > /dev/null && cd .. || cd ..
echo "Updating lambda code..."
aws lambda update-function-code --function-name post-rsvp-1kVP --zip-file fileb://./post-rsvp.zip > /dev/null
else
echo "I don't know how to deploy $1"
exit 1
fi<file_sep>/app/src/pages/errors/errors.jsx
import React from 'react'
import { connect } from 'react-redux'
export const NotFound = () => <p>Oops... den här sidan finns inte!</p>
export const Oops = () => (
<div>
<h2>Oops, nu gick nåt lite snett!</h2>
<p>Försök igen, eller be Tomas laga...</p>
</div>
)
<file_sep>/app/src/app/app.jsx
import React from 'react'
import { AppContainer } from 'react-hot-loader'
import { BrowserRouter, Route, Switch, withRouter } from 'react-router-dom'
import { ConnectedRouter } from 'react-router-redux'
import * as Components from '../components/components.jsx'
import { menuItems, Thanks, Oops, NotFound } from '../pages/pages.jsx'
import './app.css'
let Content = withRouter(({ location, menuItems }) => (
<Components.Page menuItems={menuItems}>
<Switch location={location}>
{menuItems
.filter(item => !!item.component)
.map(item => (
<Route
key={item.url}
exact={item.exact}
path={item.url}
component={item.component}
/>
))}
<Route path="/thanks" component={Thanks} />
<Route path="/oops" component={Oops} />
<Route component={NotFound} />
</Switch>
</Components.Page>
))
const App = props => (
<div className="app">
<Components.LeftBorder />
<AppContainer>
<ConnectedRouter history={props.history}>
<Content menuItems={menuItems} />
</ConnectedRouter>
</AppContainer>
</div>
)
export default App
<file_sep>/app/src/components/components.jsx
export { default as Menu } from './menu/menu.jsx'
export { default as Page } from './page/page.jsx'
export { default as LeftBorder } from './left-border/left-border.jsx'
<file_sep>/app/src/store/middleware/post-rsvp.js
import { push } from 'react-router-redux'
const sendRsvpData = rsvpForm =>
fetch('/rsvp', {
body: JSON.stringify(rsvpForm),
method: 'post',
mode: 'cors'
})
export const POST_RSVP = 'rsvp/POST_RSVP'
export const postRsvp = dispatch => formData => {
console.log(JSON.stringify(formData))
dispatch({
type: POST_RSVP,
data: formData
})
}
export const RSVP_SUCCESSFUL = 'rsvp/RSVP_SUCCESSFUL'
export const RSVP_FAILED = 'rsvp/RSVP_FAILED'
export default ({ dispatch }) => next => action => {
switch (action.type) {
case POST_RSVP:
sendRsvpData(action.data)
.then(() => dispatch({ type: RSVP_SUCCESSFUL }))
.catch(err => {
console.error(err)
dispatch({ type: RSVP_FAILED, err })
})
break
case RSVP_SUCCESSFUL:
dispatch(push('/thanks'))
break
case RSVP_FAILED:
dispatch(push({ pathname: '/oops' }))
break
}
next(action)
}
<file_sep>/app/src/pages/home/home.jsx
import React from 'react'
import { connect } from 'react-redux'
import ILoveYou from './jag älskar dig.png'
import './home.css'
import Heart from './heart.png'
const Name = ({ first, middle, last }) => (
<span className="name-badge">
<span className="first">{first}</span>
<span className="middle">{middle}</span>
<span className="last">{last}</span>
</span>
)
const Home = props => (
<div className="home">
<p>Välkomna på bröllopet mellan</p>
<div className="home-names">
<Name first="Sara" middle="Linnéa" last="Aschan" />
<img className="heart" src={Heart} />
<Name first="Tomas" middle="<NAME>" last="Lycken" />
</div>
<p>lördagen den 1 september 2018!</p>
</div>
)
export default Home
<file_sep>/app/src/pages/the-sites/the-sites.jsx
import React from 'react'
export default () => (
<div>
<h2>Sjöviken</h2>
<p>
I Sörmlands skogar, vid stranden till Gålsjön, ligger ett stort rött hus
med några uthus - Sjöviken. Storleken vittnar om dess förflutna som kollo
för barn på sommaräventyr, men sedan maj 2016 tillhör det brudens
föräldrar, Pia och Johan. På de två år som gått sedan dess har Sjöviken
hunnit ge oss glada festligheter, lata sommardagar på bryggan, långa
svamppromenader i skogarna och bastubad med tillhörande dopp i isvak.
Julaftnarna här, utan både TV och internet, är redan tradition!
</p>
<p>
Den första september 2018 blir Sjöviken skådeplats för ännu ett firande,
när vigseln mellan Sara och Tomas äger rum på den stora grässluttningen
ner mot sjön.
</p>
<h2>Kolhuset - eller “Här vill jag gifta mig”</h2>
<p>
Hälleforsnäs bruk öppnade 1659 och blev under 1800-talet och början av
1900-talet en stor verksamhet, med som mest omkring 1000 anställda. Till
järngjuteriet behövdes stora mängder träkol, och för att ha någonstans att
lagra denna byggdes Kolhuset - en jättelik byggnad med en golvyta på
nästan 4000 kvadratmeter och ett tak som, när det byggdes, var Europas
största fribärande takkonstruktion. När kolanvändningen på Hälleforsnäs
bruk så småningom upphörde blev Kolhuset ett förråd och till sist en
skräpkammare. 1996 bildades föreningen Kolhusteatern och Kolhuset fick
nytt liv som teaterscen. Numera sätts en ny pjäs upp här varje sommar, med
stora ensembler av både barn och vuxna. Sommaren 2018 blir det musikalen
Råttfångaren, baserad på legenden om Råttfångaren i Hameln. Biljetter
finns på <a href="http://kolhusteatern.se/">Kolhusteaterns hemsida</a>,
för den som är intresserad!
</p>
<p>
Sommaren 2017 besökte Sara och <NAME>aterns uppsättning av
musikalen <NAME>. Förälskelsen var ögonblicklig! Innan
föreställningen var över konstaterade Sara att “Här vill jag gifta mig!”{' '}
</p>
<p>
Det är i Kolhuset vi äter middag och festar efter vigseln på Sjöviken. I
och med det får byggnaden ännu ett nytt användningsområde, eftersom den
aldrig förut använts som festlokal (vad vi vet)!
</p>
</div>
)
<file_sep>/app/src/store/middleware/index.js
import thunk from 'redux-thunk'
import { routerMiddleware } from 'react-router-redux'
import postRsvp from './post-rsvp'
export default ({ history }) => [thunk, routerMiddleware(history), postRsvp]
<file_sep>/post-rsvp/sheets.js
const GoogleSpreadsheet = require('google-spreadsheet')
const SPREADSHEET_ID = process.env.SpreadsheetId
const CLIENT_EMAIL = process.env.GAuthClientEmail
// hack around lambda's inability to store env vars with newlines
// see https://forums.aws.amazon.com/thread.jspa?threadID=248843&tstart=0&messageID=790654#790654
const PRIVATE_KEY = process.env.GAuthPrivateKey.split('\\n').join('\n')
const creds = {
client_email: CLIENT_EMAIL,
private_key: PRIVATE_KEY
}
exports.authenticate = () =>
new Promise((resolve, reject) => {
const doc = new GoogleSpreadsheet(SPREADSHEET_ID)
doc.useServiceAccountAuth(
creds,
(err, _) => (!err ? resolve(doc) : reject(err))
)
})
exports.addRow = doc => data =>
new Promise((resolve, reject) =>
doc.addRow(1, data, (err, _) => (!err ? resolve() : reject(err)))
)
<file_sep>/app/src/pages/rsvp/rsvp.jsx
import React from 'react'
import { TransitionGroup, CSSTransition } from 'react-transition-group'
import { connect } from 'react-redux'
import {
Form,
FieldSet,
RadioGroup,
TextBox,
TextArea,
SubmitButton,
NumberTextBox,
Button
} from '../../components/form/form.jsx'
import './rsvp.css'
import { postRsvp } from '../../store/middleware/post-rsvp'
const timeout = { enter: 300, exit: 0 }
class NameInput extends React.Component {
constructor(props) {
super(props)
}
componentDidMount() {
this.input.focus()
}
render() {
return (
<input
ref={input => {
this.input = input
}}
name="namn"
type="text"
value={this.props.name}
onChange={this.props.onChange}
/>
)
}
}
class RsvpForm extends React.Component {
constructor(props) {
super(props)
this.state = {
names: [''],
attending: 'not specified',
email: '',
errors: {
names: '',
email: '',
attending: '',
staying: ''
}
}
this.updateName = this.updateName.bind(this)
this.setEmail = this.setEmail.bind(this)
this.addOne = this.addOne.bind(this)
this.remove = this.remove.bind(this)
this.setAttending = this.setAttending.bind(this)
this.setFoods = this.setFoods.bind(this)
this.setStaying = this.setStaying.bind(this)
this.submit = this.submit.bind(this)
}
updateName(k) {
return ({ target: { value } }) => {
this.setState(prev => {
const names = [...prev.names]
names[k] = value
return { names }
}, this.validate())
}
}
setEmail(e) {
this.setState({ email: e.target.value }, this.validate())
}
addOne() {
this.setState(
prev => Object.assign({}, prev, { names: [...prev.names, ''] }),
this.validate()
)
}
remove(k) {
return () =>
this.setState(
prev =>
Object.assign({}, prev, {
names: prev.names.filter((n, i) => i !== k)
}),
this.validate()
)
}
setStaying(staying) {
this.setState({ staying }, this.validate())
}
setFoods(e) {
this.setState({ foods: e.target.value }, this.validate())
}
setAttending(attending) {
this.setState({ attending }, this.validate())
}
validate(callback) {
return () => {
if (!this.state.submitted) {
return
}
const multi = this.state.names.length > 1
const you = multi ? 'ni' : 'du'
const errors = {}
if (
this.state.names.length === 0 ||
this.state.names.filter(n => n.length === 0).length > 0
) {
errors.names =
this.state.names.length <= 1
? 'Du måste säga vem du är!'
: 'Ni måste säga vilka ni är!'
}
if (this.state.attending === 'not specified') {
errors.attending = `Kommer ${you} eller inte?`
} else if (this.state.attending === 'ja') {
if (this.state.email.length === 0) {
errors.email = `Vi behöver ett sett att kontakta ${
multi ? 'er' : 'dig'
}!`
}
if (this.state.staying === undefined) {
errors.staying = `Vi behöver veta om ${you} vill sova på Granhedsgården!`
}
}
this.setState({ errors }, callback)
}
}
submit() {
this.setState(
{ submitted: true },
this.validate(() => {
if (Object.values(this.state.errors).join('').length === 0) {
const { names, email, attending, staying, foods } = this.state
this.props.submit({ names, email, attending, staying, foods })
}
})
)
}
render() {
const props = {
...this.props,
...this.state
}
const multi = props.names.length >= 2
const you = !multi ? 'du' : 'ni'
const ime = !multi ? 'jag' : 'vi'
const showAttending = props.attending === 'ja'
const showNotAttending = props.attending === 'nej'
const showSubmit = showAttending || showNotAttending
const names = [...props.names.keys()].map(k => (
<div className="name-line" key={`name_${k}`}>
<NameInput name={props.names[k]} onChange={this.updateName(k)} />
{k > 0 ? (
<span className="remove-one" onClick={this.remove(k)}>
<i className="fa fa-minus-square" />
</span>
) : null}
</div>
))
return (
<div>
<Form>
<div className="form-control">
<label>
<div
className={`validation ${!!props.errors.names ? 'error' : ''}`}
>
{props.errors.names}
</div>
{`Vad heter ${you}?`}
<div className="names">
{names}
<div className="name-line">
<span className="add-one" onClick={this.addOne}>
<i className="fa fa-plus-square" />
</span>
</div>
</div>
</label>
</div>
<RadioGroup
label={`Kommer ${you}?`}
name="rsvp"
error={props.errors.attending}
options={[
{ value: 'ja', text: `Klart ${ime} gör!` },
{ value: 'nej', text: `Nej, ${ime} kan inte :(` }
]}
onSelect={this.setAttending}
selected={props.attending}
/>
<TransitionGroup component="rsvp" className="rsvp">
<CSSTransition
key={`attending_${props.attending}`}
classNames={{
appear: 'fade-appear',
enter: 'fade-enter',
enterActive: 'fade-enter-active',
appearActive: 'fade-appear-active'
}}
timeout={timeout}
>
<div>
{showAttending && (
<div>
<p>Hurra, vad roligt!</p>
<p>Då behöver vi veta lite mer:</p>
<TextBox
name="email"
label={`Epost${multi ? ' (till någon av er)' : ''}:`}
onChange={this.setEmail}
/>
<TextArea
name="food"
label={`Har ${
multi ? 'ni' : 'du'
} några specialmatsbehov?`}
onChange={this.setFoods}
/>
<RadioGroup
label={`Vill ${
props.multi ? 'ni' : 'du'
} bo på Granhedsgården natten 1-2 september?`}
error={props.errors.staying}
onSelect={this.setStaying}
options={[
{ value: 'ja', text: 'Ja, gärna!' },
{
value: 'nej',
text: `Nej, ${
props.multi ? 'vi' : 'jag'
} sover någon annanstans.`
}
]}
/>
</div>
)}
{showNotAttending && (
<div>
<p>
Vad tråkigt! Vi kommer sakna {multi ? 'er' : 'dig'}. Men
vi hoppas att vi ses nån annan gång!
</p>
</div>
)}
{showSubmit && (
<SubmitButton
text="Svara"
onClick={this.submit}
disabled={Object.values(props.errors).join('').length > 0}
/>
)}
</div>
</CSSTransition>
</TransitionGroup>
</Form>
</div>
)
}
}
const stateToProps = state => ({
rsvpFormState: state.rsvpFormState
})
const dispatchToProps = dispatch => ({
submit: postRsvp(dispatch)
})
export default connect(stateToProps, dispatchToProps)(RsvpForm)
<file_sep>/app/src/components/menu/menu.jsx
import React from 'react'
import PropTypes from 'prop-types'
import { NavLink } from 'react-router-dom'
import MobileMenu from 'react-burger-menu/lib/menus/slide'
import './burger-menu.css'
import './menu.css'
const MenuItem = props => (
<li>
<NavLink exact to={props.url}>
{props.text}
</NavLink>
</li>
)
MenuItem.propTypes = {
url: PropTypes.string.isRequired,
text: PropTypes.string.isRequired
}
const Menu = props => (
<div>
<nav className="full-menu">
<ul>{props.links.map((l, i) => <MenuItem key={i} {...l} />)}</ul>
</nav>
<MobileMenu
className="mobile-menu"
pageWrapId="main"
outerContainerId="content"
right
>
<ul>{props.links.map((l, i) => <MenuItem key={i} {...l} />)}</ul>
</MobileMenu>
</div>
)
Menu.propTypes = {
links: PropTypes.arrayOf(PropTypes.shape(MenuItem.propTypes)).isRequired
}
export default Menu
<file_sep>/post-rsvp/index.js
const sheets = require('./sheets')
exports.handler = (event, context, callback) => {
const data = JSON.parse(event.body)
sheets
.authenticate()
.then(doc => {
const lines = data.names
.map(name => ({
Namn: name,
Kommer: data.attending,
Epost: data.email,
Granhedsgården: data.staying,
Mat: data.foods
}))
.map(sheets.addRow(doc))
return Promise.all(lines)
})
.then(() =>
callback(null, {
body: JSON.stringify('OK'),
statusCode: 200
})
)
.catch(err => {
callback(err, {
body: JSON.stringify({ message: `Error: ${err.message}` }),
statusCode: 500
})
})
}
| 94f49a47399ea455d54806b85d1470c8ab06ba59 | [
"JavaScript",
"Shell"
] | 18 | JavaScript | tlycken/tusenvuxenpoang | c8875823403985fa27c19a278f357f3ecf15b979 | 4ef7a522a3ba3d709731f416211ae48684805fe8 | |
refs/heads/master | <repo_name>felixclack/omniauth-dropbox<file_sep>/lib/omniauth-dropbox.rb
require 'omniauth/strategies/dropbox'
<file_sep>/lib/omniauth/strategies/dropbox.rb
require 'omniauth-oauth2'
require 'json'
module OmniAuth
module Strategies
class Dropbox < OmniAuth::Strategies::OAuth2
option :name, 'dropbox'
option :client_options, {
site: 'https://api.dropbox.com',
authorize_url: 'https://www.dropbox.com/1/oauth2/authorize',
token_url: 'https://api.dropbox.com/1/oauth2/token'
}
uid { raw_info['uid'].to_s }
info do
{
uid: raw_info['uid'],
name: raw_info['display_name'],
email: raw_info['email']
}
end
extra do
{ raw_info: raw_info }
end
def raw_info
@raw_info ||= JSON.parse(access_token.get('/1/account/info').body)
end
end
end
end
<file_sep>/Gemfile
source 'https://rubygems.org'
gemspec
# Specify your gem's dependencies in omniauth-eindx.gemspec
group :test do
gem 'rack-test'
gem 'rake'
gem 'rspec'
gem 'webmock'
end
<file_sep>/README.md
# Omniauth::Dropbox
An OmniAuth strategy for connecting to Dropbox.
Add this to `config/initializers/devise.rb`
Devise.setup do |config|
...
config.omniauth :dropbox, APP_ID, APP_SECRET
end
| 6f4ebcae0128b7b1059e5a3b2928f384369c7b71 | [
"Markdown",
"Ruby"
] | 4 | Ruby | felixclack/omniauth-dropbox | 6549eae3421c32c643675fe327b3bf1d5a3891f9 | 87cb15c0275e13540df0c92fdb162c1fe124a982 | |
refs/heads/main | <repo_name>decentology/hyperverse-module<file_sep>/packages/dapplib/tests/nft-tests.js
const assert = require('chai').assert;
const DappLib = require('../src/dapp-lib.js');
const fkill = require('fkill');
describe('Flow Dapp Tests', async () => {
let config = null;
before('setup contract', async () => {
// Setup tasks for tests
config = DappLib.getConfig();
});
after(() => {
fkill(':3570');
});
describe('NFT Tests', async () => {
it(`shall register with HyperverseService and receive NFT Tenant`, async () => {
let testData = {
acct: config.accounts[1]
}
await DappLib.registerHyperverse(testData);
await DappLib.nftTenant(testData);
});
it(`shall set up account 2 with NFT Collection`, async () => {
let testData = {
acct: config.accounts[2]
}
await DappLib.provisionAccountNFT(testData);
});
it(`shall mint NFT into user account and check correct NFT id`, async () => {
let testData1 = {
acct: config.accounts[1],
recipient: config.accounts[2],
files: ["File 1", "File 2"]
}
let testData2 = {
acct: config.accounts[2]
}
await DappLib.mintNFT(testData1);
let res = await DappLib.getNFTsInCollection(testData2);
assert.equal(res.result.length, 1, "NFT did not mint correctly");
assert.equal(res.result[0], 0, "Minted NFT has the wrong ID");
});
});
});
<file_sep>/README.md
# Example Hyperverse NFT Module
## Explaining Composability on Flow
Please see the Week 3 content (Days 1 & 2) of the finished Fast Floward bootcamp: https://github.com/decentology/fast-floward-1/tree/main/week3
Here you can find the explanation for the technical implementation of composability on Flow.
**PLEASE NOTE:** *We have changed the term 'Registry' to be 'Hyperverse.' If you see any examples of the term 'Registry' in the week 3 content, it is now named 'Hyperverse.'*
## Figuring out DappStarter
Please see the Week 2 content (Days 1-4) of the finished Fast Floward bootcamp: https://github.com/decentology/fast-floward-1/tree/main/week2
Here you can find explanations and examples of how to develop on DappStarter.
## /packages/dapplib/contracts/Project
This folder has 3 contracts: HyperverseInterface, HyperverseService, and HyperverseNFTContract.
**HyperverseService** allows Tenants of the Hyperverse ecosystem to register with the Hyperverse. This only happens one time. Once a Tenant registers with the HyperverseService, they can interact with the Hyperverse all they want. They can get any Tenant resource from a Hyperverse Contract that implements the **HyperverseInterface**.
The **HyperverseInterface** is a Contract Interface that all composable Hyperverse contracts must implement if they want to be in the ecosystem. You can see that **HyperverseNFTContract** implements **HyperverseInterface**. It specifies that composable smart contracts must have a `Tenant` resource that implements an `ITenant` Resource Interface. You can find the other requirements in the file itself.
## What You Could/Should Change
1) **HyperverseNFTContract** - change this to whatever your composable smart contract will be.
2) The `/packages/dapplib/src/interactions/transactions/nft` folder containing the transactions related to HyperverseNFTContract.
3) The `/packages/dapplib/src/interactions/scripts/nft` folder containing the transactions related to HyperverseNFTContract.
## What You Should NOT Change
Do not modify **HyperverseService.cdc** or **HyperverseInterface.cdc**. These are standard contracts we use for composability.
## How it Works
The pattern is like so:
1) A Tenant registers with the HyperverseService by calling the `register` transaction found in `/packages/dapplib/interactions/transactions/hyperverse/register.cdc`.
2) A Tenant gets a `Tenant` resource from the composable smart contract they want (Note: They must have completed step 1 to do so because you need an `AuthNFT` resource to get a `Tenant` resource). In this example project, the Tenant gets the `Tenant` resource from the HyperverseNFTContract by calling the `get_tenant` transaction found in `/packages/dapplib/interactions/transactions/hyperverse/get_tenant.cdc`.
3) Any account that wants to be able to receive NFTs must have setup their account to have an NFT Collection by calling the `provision_account` transaction. This can be found in `/packages/dapplib/interactions/transactions/nft/provision_account.cdc`.
4) The Admin account can now mint NFTs and provisioned accounts can now interact with NFTs.
# Pre-requisites
In order to develop and build "My Dapp," the following pre-requisites must be installed:
* [Visual Studio Code](https://code.visualstudio.com/download) (or any IDE for editing Javascript)
* [NodeJS](https://nodejs.org/en/download/)
* [Yarn](https://classic.yarnpkg.com/en/docs/install) (DappStarter uses [Yarn Workspaces](https://classic.yarnpkg.com/en/docs/workspaces))
* [Flow CLI](https://docs.onflow.org/flow-cli/install) (https://docs.onflow.org/flow-cli/install) (after installation run `flow cadence install-vscode-extension` to enable code highlighting for Cadence source files)
### Windows Users
Before you proceed with installation, it's important to note that many blockchain libraries either don't work or generate errors on Windows. If you try installation and can't get the startup scripts to completion, this may be the problem. In that case, it's best to install and run DappStarter using Windows Subsystem for Linux (WSL). Here's a [guide to help you install WSL](https://docs.decentology.com/guides/windows-subsystem-for-linux-wsl).
Blockchains known to require WSL: Solana
# Installation
Using a terminal (or command prompt), change to the folder containing the project files and type: `yarn` This will fetch all required dependencies. The process will take 1-3 minutes and while it is in progress you can move on to the next step.
# Yarn Errors
You might see failures related to the `node-gyp` package when Yarn installs dependencies.
These failures occur because the node-gyp package requires certain additional build tools
to be installed on your computer. Follow the [instructions](https://www.npmjs.com/package/node-gyp) for adding build tools and then try running `yarn` again.
# Start Your Project
Using a terminal (or command prompt), change to the folder containing the project files and type: `yarn start` This will run all the dev scripts in each project package.json.
# Test Your Project
Using a terminal (or command prompt), change to the folder containing the project files and type: `yarn test`. This will run the test file in `packages/dapplib/tests/nft-tests.js`
## File Locations
Here are the locations of some important files:
* Contract Code: [packages/dapplib/contracts](packages/dapplib/contracts)
* Dapp Library: [packages/dapplib/src/dapp-lib.js](packages/dapplib/src/dapp-lib.js)
* Blockchain Interactions: [packages/dapplib/src/blockchain.js](packages/dapplib/src/blockchain.js)
* Unit Tests: [packages/dapplib/tests](packages/dapplib/tests)
* UI Test Harnesses: [packages/client/src/dapp/harness](packages/client/src/dapp/harness)
To view your dapp, open your browser to http://localhost:5000 for the DappStarter Workspace.
We ♥️ developers and want you to have an awesome experience. You should be experiencing Dappiness at this point. If not, let us know and we will help. Join our [Discord](https://discord.gg/XdtJfu8W) or hit us up on Twitter [@Decentology](https://twitter.com/decentology).
| 44aac75c711b7ac322046f8437d0215be259d357 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | decentology/hyperverse-module | 0ba6bf39df6d0d8d950818ed59d332a622a224ef | a7f0f73693d0101f036ddd3b1c672aa431bc0f96 | |
refs/heads/main | <file_sep>const PaytmConfig = {
mid: "KrlQAc88495620252325",
key: <KEY>",
website: "WEBSTAGING"
}
module.exports.PaytmConfig = PaytmConfig | 737eab50da943ea692b5b42a098a5a4dd2e1b79c | [
"JavaScript"
] | 1 | JavaScript | amirSohel007/paytm-pg | 46755d80c6b9c6dacac006c95af6fb1c424931fe | 5ef40faad328dc19dc67fbde5fc557a0565aa8d5 | |
refs/heads/master | <file_sep>#!/bin/bash
if ! type "uglifyjs" >& /dev/null; then
echo ""
echo "uglify is not installed yet."
echo "Type 'npm install uglify-js -g' to install it."
echo ""
exit 1
fi
# https://github.com/mishoo/UglifyJS2
uglifyjs scripts/goblean.js scripts/fighter.js scripts/indexDB.js -cm --preamble="/* https://github.com/restimel/Goblean */" -o goblean.min.js &&
echo "goblean.min.js has been generated" ||
echo "Minification has failed. goblean.min.js was not generated!"
<file_sep># Goblean
Prototype of Goblean Game
Goblean is a funny game where you play with real object. You use EAN code (the bar code) of object to watch creature more or less powerful.
## The game
You can play it at
https://restimel.github.io/Goblean/goblean.html
## Techonology
This application is writen in HTML5 and ES6.
It uses browser camera to take picture of your object and to read EAN code (the camera usage is optional).
It also uses geolocalisation for random criter.
### libraries
QuaggaJS: used to read EAN code from images (https://github.com/serratus/quaggaJS)
i18nJS-formatter: used to manage different languages and format display in the selected locale (https://github.com/restimel/i18n-js-formatter)
font-awesome: a great library for icons (http://fontawesome.io/)
## Authors
Goblean was imagined by <NAME> and <NAME>. And many other people have contributed to build this project (see in-code credits).
## Version
This is a prototype project, so currently major version is still 0. To know the current available version watch the version displayed in game (in credit section).
version format is X.Y.Z
* X: major version (currently 0 when the game is till in progress)
* Y: minor version (incremented for each new feature or rule change)
* Z: build version (incremented at each update)
<file_sep>(function() {
const dbVersion = 1;
const dbName = 'goblean';
const tableGoblean = 'gobleans';
let DB = null;
const DBReady = (() => {
var cb = {};
var p = new Promise((success, error) => {
cb.success = success;
cb.error = error;
});
return Object.assign(p, cb);
})();
/*
To remove Db from browser:
indexedDB.deleteDatabase(dbName)
*/
function upgradeDB(event) {
DB = event.target.result;
switch(event.oldVersion) {
case 0:
let objectStore = DB.createObjectStore(tableGoblean, {keyPath: 'code'});
objectStore.createIndex('index_code', 'code', {unique: true});
objectStore.createIndex('index_nbw', 'nbw', {unique: false});
objectStore.createIndex('index_nbf', 'nbf', {unique: false});
objectStore.createIndex('index_create', 'create', {unique: false});
objectStore.createIndex('index_update', 'update', {unique: false});
objectStore.createIndex('index_name', 'name', {unique: true});
}
}
function onVersionChange(event) {
console.warn('indexedDB version has change in a newer tab. This page should be reloaded.');
//DB.close();
DBReady.error(event);
}
function connectionSuccess(event) {
if (!DB) {
DB = event.target.result;
}
DBReady.success(DB);
DB.onversionchange = onVersionChange;
}
function openDB() {
let request = self.indexedDB.open(dbName, dbVersion);
request.onerror = (event) => {
// mostly happen when user forbid indexedDB
console.error(event);
DBReady.error(event);
};
request.onupgradeneeded = upgradeDB;
request.onsuccess = connectionSuccess;
request.onblocked = (event) => {
console.log('is running in another tab. Its version is deprecated and must be refresh');
DBReady.error(DB);
};
}
openDB();
const manageError = (error) => (event) => error(event.target.error);
self.store = {
gobleans: {
// getAll: function(index = 'nbw', ascOrder = false) {
// return new Promise(async (success, error) => {
// const DB = await DBReady;
// const result = [];
// const request = DB
// .transaction([tableGoblean], 'readonly')
// .objectStore(tableGoblean) //how to sort
// .index('index_' + index)
// .openCursor(null, ascOrder ? 'next' : 'prev');
// request.onsuccess = function(event) {
// let cursor = event.target.result;
// if (cursor) {
// result.push(cursor.value);
// cursor.continue();
// } else {
// success(result);
// }
// };
// request.onerror = manageError(error);
// });
// },
getAll: function(index = 'code', ascOrder = true) {
return new Promise(async (success, error) => {
const DB = await DBReady;
const request = DB
.transaction([tableGoblean], 'readonly')
.objectStore(tableGoblean) //how to sort
.index('index_' + index)
.getAll();
request.onsuccess = function(event) {
success(ascOrder ? event.target.result : event.target.result.reverse());
};
request.onerror = manageError(error);
});
},
get: function(code) {
return new Promise(async (success, error) => {
const DB = await DBReady;
const request = DB
.transaction([tableGoblean], 'readonly')
.objectStore(tableGoblean)
.get(code);
request.onsuccess = function(event) {
success(event.target.result);
};
request.onerror = manageError(error);
});
},
has: function(code) {
return new Promise(async (success, error) => {
const DB = await DBReady;
const request = DB
.transaction([tableGoblean], 'readonly')
.objectStore(tableGoblean)
.get(code);
request.onsuccess = function(event) {
success(typeof event.target.result !== 'undefined');
};
request.onerror = manageError(error);
});
},
delete: function(code) {
return new Promise(async (success, error) => {
const DB = await DBReady;
const request = DB
.transaction([tableGoblean], 'readwrite')
.objectStore(tableGoblean)
.delete(code);
request.onsuccess = function(event) {
success(event.target.result);
};
request.onerror = manageError(error);
});
},
set: function(item) {
return new Promise(async (success, error) => {
if (!item.code) {
console.log(item)
error('no code for this goblean');
}
const oldItem = await this.has(item.code);
if (!oldItem) {
item.create = Date.now();
}
item.update = Date.now();
const DB = await DBReady;
const request = DB
.transaction([tableGoblean], 'readwrite')
.objectStore(tableGoblean)
.put(item);
request.onsuccess = function(event) {
success(event.target.result);
};
request.onerror = manageError(error);
});
}
}
};
})();
/* compatibility check */
(self.compatibility || {}).indexedDB = true;<file_sep>const minLength = 6;
const energyThreshold = 20;
class Fighter {
constructor(position, json) {
this.mode = 'rest';
this.stats = {};
this.position = position;
this.dmg = 0;
this.order = 0;
this.numberOfFight = 0;
this.numberOfWin = 0;
this.choice = [null, null, null, null];
if (json) {
if (json.isGhost) {
this.isGhost = true;
this.autoFight = 1;
}
if (typeof json === 'string') {
json = JSON.parse(json);
}
this.setAttributes(json);
}
this.resetEnergy();
this.initializeAttack();
}
toJSON() {
return {
name: this.name,
code: this.code,
fromCamera: this.fromCamera,
picture: this.picture,
nbf: this.numberOfFight,
nbw: this.numberOfWin,
isGhost: this.isGhost,
update: this.update,
create: this.create
};
}
async save() {
if (this.isGhost) {
return;
}
return store.gobleans.set(this.toJSON());
// let list = await store.gobleans.getAll();
// // let list = JSON.parse(localStorage.getItem('fighters') || '[]');
// let idx = list.findIndex(f => f.code === this.code);
// if (idx === -1) {
// list.push(this);
// if (this.fromCamera) {
// this.gameStatistics.nbGoblean++;
// localStorage.setItem('gameStatistics', JSON.stringify(this.gameStatistics));
// }
// } else {
// list[idx] = this;
// }
// localStorage.setItem('fighters', JSON.stringify(list));
}
async remove() {
return store.gobleans.delete(this.code);
// let list = JSON.parse(localStorage.getItem('fighters') || '[]');
// let idx = list.findIndex(f => f.code === this.code);
// if (idx === -1) {
// return;
// } else {
// list.splice(idx, 1);
// }
// localStorage.setItem('fighters', JSON.stringify(list));
}
isValid() {
if (this.isGhost) {
return !this._error;
}
if (!this.code || this.code.length < minLength) {
this._error = 'code:invalid';
return false;
}
if (['initiative', 'kind', 'hp', 'head', 'body', 'rightArm', 'rightLeg', 'leftArm', 'leftLeg', 'energyRestore', 'armor']
.some(a => typeof this.stats[a] !== 'number'))
{
this._error = 'stats:notNumber';
return false;
}
this._error = '';
return true;
}
isKo() {
return this.dmg >= this.stats.hp;
}
checkKey() {
let code = this.code.split('').map(v => +v);
let key = code.slice(-1)[0];
let offset = code.length % 2;
let cKey = (10 - (code.slice(0, -1).reduce((sum, val, k) => {
let m = (k + offset) % 2 ? 1 : 3;
return sum + m * val;
}, 0) % 10)) % 10;
return key === cKey;
}
getGhost() {
let [hasGhost, ghost, code] = Fighter.isThereGhost();
if (this.gameStatistics.playerLevel < 2) {
this.name = '';
this._error = _('You are not experiment enough. Try again later when you will be level 2.');
return false;
} else
if (!hasGhost) {
this.name = '';
this._error = _('No ghost right now! Try again later.');
return false;
}
this._error = '';
this.ghostId = ghost.id;
this.name = ghost.name ? _(ghost.name) : _('Ghost');
ghost.modifyStats && (this.modifyStats = ghost.modifyStats);
ghost.modifyDamage && (this.modifyDamage = ghost.modifyDamage);
ghost.drawAlternative && (this.drawAlternative = ghost.drawAlternative);
ghost.skipAttack && (this.skipAttack = ghost.skipAttack);
return code;
}
setCode(code) {
if (this.isGhost) {
code = this.getGhost();
if (!code) {
return false;
}
}
let malus = 0;
code = code.replace(/[^\d]+/, '');
let value = code.split('').map(v => +v);
if (value.length < minLength) {
this.code = '';
return false;
}
this.code = code;
if (value.length === 8) {
value.unshift(0);
[7, 6, 5, 4].forEach((i) => {
value.splice(i, 0, value[i]);
});
} else
if (value.length < 13) {
malus = 13 - value.length;
[0, 5, 1, 2, 3, 5, 10].slice(0, 13 - value.length).forEach((i) => {
value.splice(i, 0, 0);
});
} else
if (value.length > 13) {
malus = value.length - 13;
}
this.stats = {
initiative: value[0] + value[3],
kind: (value[1] + value[5]) % 3, // nb of kind
hp: (value[12] + value[4]) * 1.5,
head: value[11],
body: value[10],
rightArm: value[9],
leftArm: value[8],
rightLeg: value[7],
leftLeg: value[6],
energyRestore: value[2],
armor: 0
};
/* bonus */
if (this.fromCamera) {
this.stats.energyRestore += 0.5;
} else
if (this.isGhost) {
this.stats.energyRestore += 1.5;
}
if (this.stats.hp <= 0) {
this.stats.hp = 30;
}
if (this.isGhost || this.checkKey()) {
this.stats.hp += 2;
this.stats.initiative += 20;
if (this.stats.head + this.stats.body === 0) {
this.stats.head = 10;
this.stats.body = 3;
}
if (this.stats.body + this.stats.leftArm + this.stats.leftLeg + this.stats.rightLeg + this.stats.rightArm <= 2) {
this.stats.body += 10;
this.stats.hp += 5;
}
} else {
malus += 2;
}
/* malus */
if (malus && !this.isGhost) {
malus = malus > 7 ? 7 : malus;
['hp', 'hp', 'initiative', 'body', 'hp', 'head', 'initiative'].slice(0, malus).forEach((carac) => {
this.stats[carac] = Math.max(1, this.stats[carac] - 1);
});
}
this.modifyStats();
this.stats.currentHp = this.stats.hp;
return true;
}
addAttribute(name, attributes) {
if (typeof attributes[name] !== 'undefined') {
this[name] = attributes[name];
}
}
setAttributes(attributes = {}) {
if (attributes.name) {
this.name = attributes.name;
}
if (attributes.picture) {
this.picture = attributes.picture;
}
if (attributes.code) {
this.setCode(attributes.code);
}
if (typeof attributes.fromCamera === 'boolean') {
this.fromCamera = attributes.fromCamera;
}
['nbf', 'nbw', 'update', 'create']
.forEach(n => this.addAttribute(n, attributes));
return this.isValid();
}
resetEnergy() {
this.stats.energy = 0;
}
setMode(mode = 'rest') {
this.mode = mode;
if (this.canvas) {
this.drawPicture();
}
}
setScale(part) {
let value = this.stats[part] / 10;
if (value < 0) {
value = 0;
}
this.ctx.scale(value, value);
return value;
}
setWidth(part) {
let value = this.stats[part];
value *= 2;
if (value === 0) {
value = 1;
}
this.ctx.lineWidth = value;
return value;
}
drawPicture(canvas = this.canvas) {
if (!canvas) {
return;
}
if (!this.canvas !== canvas || !this.ctx) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
}
this.ctx.clearRect(0, 0, 200, 200);
if (this.isGhost && !this.name) {
//no ghost
this.ctx.save();
this.ctx.beginPath();
this.ctx.ellipse(100, 100, 30, 30, 0, 0, 2*Math.PI);
this.ctx.fill();
this.ctx.restore();
return;
}
this.ctx.save();
this.ctx.strokeStyle = this.baseColor;
this.ctx.fillStyle = this.baseColor;
if (this.drawAlternative()) {
this.ctx.restore();
return;
}
if (this.picture) {
let h = 50 + this.stats.body;
let img = new Image();
img.src = this.picture;
img.onload = () => {
this.ctx.save();
this.drawBody(true);
this.ctx.drawImage(img, 100-h, 100-h, 2*h, 2*h);
this.ctx.restore();
}
} else {
this.drawBody();
}
this.drawHead();
this.drawArms();
this.drawLegs();
this.drawHP();
this.drawEyes();
this.drawEnergy();
this.ctx.restore();
}
drawGhostBody() {
this.ctx.beginPath();
let w = this.setWidth('body')/2;
this.ctx.moveTo(60-w, 145+w);
this.ctx.bezierCurveTo(60-w, 15-w, 140+w, 15-w, 140+w,140+w);
this.ctx.lineTo(130, 135-w);
this.ctx.lineTo(115, 145+w);
this.ctx.lineTo(100, 135-w);
this.ctx.lineTo(85, 145+w);
this.ctx.lineTo(70, 135-w);
this.ctx.lineTo(60-w, 145+w);
this.ctx.stroke();
this.ctx.fill();
}
drawBody(clip=false) {
this.ctx.beginPath();
let w = this.setWidth('body');
if (!clip) {
w = 0;
}
this.ctx.ellipse(100, 100, 20+w/2, 55+w/2, 0, 0, 2*Math.PI);
if (clip) {
this.ctx.clip();
} else {
this.ctx.stroke();
this.ctx.fill();
}
}
drawHead() {
this.ctx.beginPath();
this.ctx.ellipse(100, 30, 19, 19, 0, 0, 2*Math.PI);
this.setWidth('head');
this.ctx.fill();
this.ctx.stroke();
}
drawArms() {
this.ctx.beginPath();
this.ctx.moveTo(100, 100);
this.ctx.lineTo(170, 30);
this.setWidth('leftArm');
this.ctx.stroke();
this.ctx.beginPath();
this.ctx.moveTo(100, 100);
this.ctx.lineTo(30, 30);
this.setWidth('rightArm');
this.ctx.stroke();
}
drawLegs() {
this.ctx.beginPath();
this.ctx.moveTo(100, 100);
this.ctx.lineTo(130, 190);
this.setWidth('leftLeg');
this.ctx.stroke();
this.ctx.beginPath();
this.ctx.moveTo(100, 100);
this.ctx.lineTo(70, 190);
this.setWidth('rightLeg');
this.ctx.stroke();
}
drawHP() {
this.ctx.beginPath();
this.ctx.save();
this.ctx.strokeStyle = '#FF0000';
this.ctx.fillStyle = '#FF0000';
this.ctx.translate(50, 150);
this.setScale('currentHp');
this.ctx.ellipse(10, -5, 10, 10, 0, 0, Math.PI, true);
this.ctx.ellipse(-10, -5, 10, 10, 0, 0, Math.PI, true);
this.ctx.lineTo(0, 15);
this.ctx.closePath();
this.ctx.fill();
this.ctx.restore();
}
drawEyes() {
if (this.fromCamera || this.isGhost) {
this.ctx.beginPath();
this.ctx.save();
this.ctx.strokeStyle = this.baseColor;
this.ctx.fillStyle = this.isGhost ? '#FF0000' : '#00FF00';
this.ctx.ellipse(107, 25, 2, 2, 0, 0, 2*Math.PI);
this.ctx.ellipse(93, 25, 2, 2, 0, 0, 2*Math.PI);
// this.ctx.stroke();
this.ctx.fill();
this.ctx.restore();
}
}
drawEnergy() {
if (this.mode === 'battle') {
this.ctx.beginPath();
this.ctx.save();
this.ctx.strokeStyle = '#00FFFF';
this.ctx.fillStyle = '#00CCCC';
this.ctx.lineWidth = 5;
let x = 190;
let y = 190;
this.ctx.moveTo(x, y);
this.ctx.lineTo(x-30, y);
this.ctx.lineTo(x-30, y-80);
this.ctx.lineTo(x-20, y-80);
this.ctx.lineTo(x-20, y-87);
this.ctx.lineTo(x-10, y-87);
this.ctx.lineTo(x-10, y-80);
this.ctx.lineTo(x, y-80);
this.ctx.lineTo(x, y);
this.ctx.clip();
this.ctx.fillRect(150, 190 - (this.stats.energy * (37 / energyThreshold)), 200, 200);
this.ctx.stroke();
this.ctx.beginPath();
this.ctx.lineWidth = 2.5;
this.ctx.moveTo(x-30, y-40);
this.ctx.lineTo(x-20, y-40);
this.ctx.lineTo(x-20, y-47);
this.ctx.lineTo(x-10, y-47);
this.ctx.lineTo(x-10, y-40);
this.ctx.lineTo(x, y-40);
this.ctx.stroke();
this.ctx.restore();
}
}
initializeAttack(special) {
this.listAttack = listAttack.slice();
if (!special) {
this.specialReady = false;
}
}
createOneChoice() {
// let attack = this.choiceAttack[this.order % this.choiceAttack.length];
// let support = this.choiceSupport[this.order % this.choiceSupport.length];
// let target = this.target[this.order % this.target.length];
this.order++;
if (this.listAttack.length === 0) {
this.initializeAttack(true);
}
if (this.stats.energy > energyThreshold && !this.specialReady) {
this.specialReady = true;
this.listAttack.unshift({
name: 'special attack',
attack: ['head', 'head', 'head'],
result: () => {
this.stats.energy -= energyThreshold;
this.specialReady = false;
if (!this.isGhost && this.fromCamera) {
this.gameStatistics.specialAttack++;
}
return [15, 'head'];
}
});
}
this.skipAttack();
return this.listAttack.shift();
}
createNextChoice() {
this.choice.forEach((c, i) => {
if (!c) {
this.choice[i] = this.createOneChoice();
}
});
}
/* return label of current possible attacks */
getChoice() {
this.createNextChoice();
return this.choice.map(choice => _(choice.name || '%(attack)s + %(support)s vs %(defense)s', {
attack: _(choice.attack[0]),
support: _(choice.attack[1]),
defense: _(choice.attack[2])
}));
}
chooseAttack(idx) {
const choice = this.choice[idx];
this.choice[idx] = null;
if (typeof choice.result === 'function') {
return choice.result();
} else {
return [this.stats[choice.attack[0]] + this.stats[choice.attack[1]] / 2, choice.attack[2]];
}
}
haveDealtDamage(dmg, opponent) {
let energy = (4 - dmg) * this.stats.energyRestore / 2;
this.stats.energy += Math.max(energy, 1);
this.drawPicture();
}
setDamage(attack, opponent) {
const defense = this.stats[attack[1]] + this.stats.armor;
let dmg = Math.floor(attack[0] - defense);
if (dmg < 1) {
dmg = 1;
}
dmg = this.modifyDamage(attack, dmg);
this.stats.energy += dmg * this.stats.energyRestore / 6;
this.dmg += dmg;
this.stats.currentHp -= dmg;
this.drawPicture();
opponent.haveDealtDamage(dmg, this);
return dmg;
}
modifyStats() {}
modifyDamage(a, dmg) { return dmg; }
drawAlternative() {}
skipAttack() {}
}
Fighter.prototype.baseColor = '#000000';
Fighter.ghosts = [{
id: 'white',
name: '<NAME>',
modifyStats: function(ghost) {
this.baseColor = '#EEEEEE';
this.stats.energyRestore += 1;
if (this.stats.hp < 20) {
this.stats.hp += 5;
}
},
modifyDamage: function(attack, dmg) {
dmg = Math.max(Math.round(dmg /2), 1);
return dmg;
},
drawAlternative: function() {
this.drawGhostBody();
this.drawHead();
this.drawArms();
this.drawLegs();
this.drawEyes();
this.drawEnergy();
return true;
}
}, {
id: 'blue',
name: '<NAME>',
modifyStats: function(ghost) {
this.baseColor = '#1111CC';
},
modifyDamage: function(attack, dmg) {
if (['head'].includes(attack[1])) {
dmg = 0;
}
return dmg;
},
drawAlternative: function() {
this.drawGhostBody();
this.drawArms();
this.drawLegs();
this.drawHP();
this.drawEyes();
this.drawEnergy();
return true;
}
}, {
id: 'orange',
name: '<NAME>',
modifyStats: function(ghost) {
this.baseColor = '#EE9900';
},
skipAttack: function() {
while (['rightArm', 'leftArm'].includes(this.listAttack[0].attack)) {
this.listAttack.shift();
if (this.listAttack.length === 0) {
this.initializeAttack(true);
}
}
},
modifyDamage: function(attack, dmg) {
if (['rightArm', 'leftArm'].includes(attack[1])) {
dmg = 0;
}
return dmg;
},
drawAlternative: function() {
this.drawGhostBody();
this.drawHead();
this.drawLegs();
this.drawHP();
this.drawEyes();
this.drawEnergy();
return true;
}
}, {
id: 'green',
name: '<NAME>',
modifyStats: function(ghost) {
this.baseColor = '#11CC11';
},
skipAttack: function() {
while (['rightLeg', 'leftLeg'].includes(this.listAttack[0].attack)) {
this.listAttack.shift();
if (this.listAttack.length === 0) {
this.initializeAttack(true);
}
}
},
modifyDamage: function(attack, dmg) {
if (['rightLeg', 'leftLeg'].includes(attack[1])) {
dmg = 0;
}
return dmg;
},
drawAlternative: function() {
this.drawGhostBody();
this.drawHead();
this.drawArms();
this.drawHP();
this.drawEyes();
this.drawEnergy();
return true;
}
}, {
id: 'red',
name: '<NAME>',
modifyStats: function(ghost) {
this.baseColor = '#CC1111';
},
modifyDamage: function(attack, dmg) {
return dmg;
},
drawAlternative: function() {
this.drawGhostBody();
this.drawHead();
this.drawHP();
this.drawEyes();
this.drawEnergy();
return true;
}
}, {
id: 'yellow',
name: '<NAME>',
modifyStats: function(ghost) {
this.baseColor = '#EEDD22';
},
modifyDamage: function(attack, dmg) {
return dmg;
},
drawAlternative: function() {
this.drawGhostBody();
this.drawHead();
this.drawArms();
this.drawLegs();
this.drawHP();
this.drawEyes();
this.drawEnergy();
return true;
}
}, {
id: 'purple',
name: '<NAME>',
modifyStats: function(ghost) {
this.baseColor = '#CC11CC';
this.stats.hp = Math.max(this.stats.hp - 4, 5);
},
modifyDamage: function(attack, dmg) {
if (['head', 'leftLeg', 'rightLeg', 'rightArm', 'leftLeg'].includes(attack[1])) {
dmg = 0;
}
return dmg;
},
drawAlternative: function() {
this.drawGhostBody();
this.drawHP();
this.drawEyes();
this.drawEnergy();
return true;
}
}, {
id: 'brown',
name: '<NAME>',
modifyStats: function(ghost) {
this.baseColor = '#775500';
},
modifyDamage: function(attack, dmg) {
if (['body'].includes(attack[1])) {
dmg = 0;
}
return dmg;
},
drawAlternative: function() {
this.drawHead();
this.drawArms();
this.drawLegs();
this.drawHP();
this.drawEyes();
this.drawEnergy();
return true;
}
}, {
id: 'pink',
name: '<NAME>',
modifyStats: function(ghost) {
this.baseColor = '#DDBBBB';
this.stats.hp += 10;
},
modifyDamage: function(attack, dmg) {
dmg = Math.max(dmg - 1, 1);
return dmg;
},
drawAlternative: function() {
this.drawGhostBody();
this.drawHead();
this.drawArms();
this.drawLegs();
this.drawHP();
this.drawEyes();
this.drawEnergy();
return true;
}
}, {
id: 'gray',
name: '<NAME>',
modifyStats: function(ghost) {
this.baseColor = '#999999';
this.stats.energyRestore += 0.5;
},
modifyDamage: function(attack, dmg) {
return dmg;
},
drawAlternative: function() {
this.drawGhostBody();
this.drawHead();
this.drawArms();
this.drawLegs();
this.drawHP();
this.drawEyes();
return true;
}
}];
Fighter.isThereGhost = function() {
const PI = Math.PI;
const d = new Date();
const [LAT, LNG, isActived] = geoloc();
let timestamp = Math.round(Date.now() / 60000) + 10; // ts in min
let hasGhost = false;
let colorGhost;
/* is there white ghost */
if (d.getMinutes() < 10 && (d.getHours() === 0 || d.getHours() === 12)) {
hasGhost = true;
colorGhost = 0;
}
/* get color */
if (!hasGhost) {
const lat = Math.round(LAT * 1000); // ~100m
const lng = Math.round(LNG * 100) * 2; // ~400m
const t = lat + lng + timestamp;
const d1 = 19;
const s1 = 0;
colorGhost = Math.sin(t * PI/d1) > s1 ? Math.ceil(t / (2*d1))%Fighter.ghosts.length : 0;
// prefered color
if (!colorGhost) {
const d2 = 67;
const s2 = 0.75;
colorGhost = Math.abs(Math.round(lat + lng + Math.sin(t * PI/d2)))%Fighter.ghosts.length;
}
if (colorGhost < 1) {
colorGhost = Fighter.ghosts.length - 1;
}
hasGhost = true;
// ghost is not there
if (d.getMinutes() === 4 && d.getHours() === 4 && d.getSeconds() === 0) {
hasGhost = false;
}
}
/* get code */
const code = [];
if (hasGhost) {
let lat = Math.abs(Math.round(LAT * 10000)).toString(); // ~10m
let lng = Math.abs(Math.round(LNG * 1000)).toString(); // ~40m
while (lat.length < 7) {
lat = '0' + lat;
}
while (lng.length < 6) {
lng = '0' + lng;
}
code[0] = lng[2]; // init
code[1] = 0; // kind
code[2] = lng[5]; // energy
code[3] = lat[3]; // init
code[4] = lat[4]; // hp
code[5] = 0; // kind
code[6] = lng[4]; // leftLeg
code[7] = Math.round(d.getMinutes()/10 + d.getHours()/10 + d.getDate()/10) % 10; // rightLeg
code[8] = d.getMinutes() % 10; // leftArm
code[9] = lat[6]; // rightArm
code[10] = (lat[5]+d.getMonth()) % 10; // body
code[11] = d.getDate() % 10; // head
code[12] = d.getHours() % 10; // hp
if (!isActived) {
code[0] = 20;
code[2] = 10;
code[12] = 0;
code[9] = 5;
}
}
return [hasGhost, Fighter.ghosts[colorGhost], code.join('')];
}
Fighter.prototype.autoFight = 0;
Fighter.prototype.choiceAttack = ['leftArm', 'rightArm', 'leftLeg', 'rightLeg'];
Fighter.prototype.choiceSupport = ['head', 'body', 'leftArm', 'rightArm', 'leftLeg', 'rightLeg'];
Fighter.prototype.target = ['head', 'body', 'leftArm', 'rightArm', 'leftLeg', 'rightLeg'];
var geoloc = (function() {
const lastLatLng = [0, 0, false];
function success(position) {
lastLatLng[0] = position.coords.latitude;
lastLatLng[1] = position.coords.longitude;
lastLatLng[2] = true;
}
function fail() {}
return () => {
navigator.geolocation.getCurrentPosition(success, fail);
return lastLatLng;
}
})();
geoloc();
const listAttack = [];
Fighter.prototype.choiceAttack.forEach(a => {
Fighter.prototype.choiceSupport.forEach(b => {
Fighter.prototype.target.forEach(c => {
listAttack.push({
name: '',
attack: [a, b, c]
});
});
});
});
listAttack.sort(() => Math.random());
listAttack.sort(() => Math.random());
/* compatibility check */
(self.compatibility || {}).fighter = true;<file_sep># TODO list
* Gobl-aena
* Team
* Adventure mode
* survivor mode
* Ghost
* notification (lvl 4)
* ghost limitation (lvl ?)
* add EAN reader (quagga)
* use worker (?needed)
* Animation de fin
| 1c9cb35676e49743ce10f534f944349b405ad376 | [
"Markdown",
"JavaScript",
"Shell"
] | 5 | Shell | restimel/Goblean | 2f5c1b25e00cda0f4e0be43694a1241c45e2393a | e58dd17ce38b2a4d42fa9e0d9a2b5582a83bc4d8 | |
refs/heads/master | <repo_name>pmav99/dockerfiles<file_sep>/docker/master/Dockerfile
FROM alpine:3.2
RUN apk add --update \
curl \
&& rm -rf /var/cache/apk/*
ENV DOCKER_VERSION 1.9.0-dev
ENV DOCKER_URL https://master.dockerproject.org/linux/amd64/docker-1.9.0-dev
ENV DOCKER_SHA256 4a9fd9033eda4c6dbe32707bc3da477f56fd43c39d8f5f553063e60afcad8cdd
RUN curl -fSL "${DOCKER_URL}" -o /usr/local/bin/docker \
&& echo "${DOCKER_SHA256} /usr/local/bin/docker" | sha256sum -c - \
&& chmod +x /usr/local/bin/docker
COPY docker-entrypoint.sh /usr/local/bin/
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["sh"]
<file_sep>/apache2/Dockerfile
FROM debian:jessie
RUN apt-get update && apt-get install -y apache2
# let's copy a few of the settings from /etc/init.d/apache2
ENV APACHE_CONFDIR /etc/apache2
ENV APACHE_ENVVARS $APACHE_CONFDIR/envvars
# and then a few more from $APACHE_CONFDIR/envvars itself
ENV APACHE_RUN_USER www-data
ENV APACHE_RUN_GROUP www-data
ENV APACHE_RUN_DIR /var/run/apache2
ENV APACHE_PID_FILE $APACHE_RUN_DIR/apache2.pid
ENV APACHE_LOCK_DIR /var/lock/apache2
ENV APACHE_LOG_DIR /var/log/apache2
ENV LANG C
# ...
RUN mkdir -p $APACHE_RUN_DIR $APACHE_LOCK_DIR $APACHE_LOG_DIR
# make CustomLog (access log) go to stdout instead of files
# and ErrorLog to stderr
RUN find "$APACHE_CONFDIR" -type f -exec sed -ri ' \
s!^(\s*CustomLog)\s+\S+!\1 /proc/self/fd/1!g; \
s!^(\s*ErrorLog)\s+\S+!\1 /proc/self/fd/2!g; \
' '{}' ';'
EXPOSE 80
CMD ["apache2", "-DFOREGROUND"]
# I really don't like Apache. Irrationally.
<file_sep>/qemu/start-qemu
#!/bin/bash
set -e
# main available options:
# QEMU_CPU=n (cores)
# QEMU_RAM=nnn (megabytes)
# QEMU_HDA (filename)
# QEMU_HDA_SIZE (bytes, suffixes like "G" allowed)
# QEMU_CDROM (filename)
# QEMU_BOOT (-boot)
hostArch="$(uname -m)"
qemuArch="${QEMU_ARCH:-$hostArch}"
qemu="${QEMU_BIN:-qemu-system-$qemuArch}"
qemuArgs=()
if [ -e /dev/kvm ]; then
qemuArgs+=( -enable-kvm )
elif [ "$hostArch" = "$qemuArch" ]; then
echo >&2
echo >&2 'warning: /dev/kvm not found'
echo >&2 ' PERFORMANCE WILL SUFFER'
echo >&2 ' (hint: docker run --device /dev/kvm ...)'
echo >&2
sleep 3
fi
qemuArgs+=( -smp "${QEMU_CPU:-1}" )
qemuArgs+=( -m "${QEMU_RAM:-512}" )
if [ "$QEMU_HDA" ]; then
if [ ! -f "$QEMU_HDA" -o ! -s "$QEMU_HDA" ]; then
(
set -x
qemu-img create -f qcow2 -o preallocation=off "$QEMU_HDA" "${QEMU_HDA_SIZE:-8G}"
)
fi
qemuArgs+=( -hda "$QEMU_HDA" )
fi
if [ "$QEMU_CDROM" ]; then
qemuArgs+=( -cdrom "$QEMU_CDROM" )
fi
if [ "$QEMU_BOOT" ]; then
qemuArgs+=( -boot "$QEMU_BOOT" )
fi
qemuArgs+=(
-net nic
-net user,hostname="$(hostname)",hostfwd=tcp:':22'-':22'
-vnc ':0'
-serial stdio
"$@"
)
set -x
exec "$qemu" "${qemuArgs[@]}"
<file_sep>/speedtest/Dockerfile
FROM python:3-slim
ENV SPEEDTEST_CLI_VERSION 0.3.2
RUN pip install speedtest-cli==$SPEEDTEST_CLI_VERSION
COPY entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]
CMD ["speedtest-cli"]
<file_sep>/xen-orchestra/Dockerfile
FROM node
# see https://github.com/vatesfr/xo/blob/master/installation.md
RUN apt-get update && apt-get install -y ruby-compass
ENV XO_REF v3.4.0
RUN mkdir -p /usr/src/xo
WORKDIR /usr/src/xo
RUN git clone -b $XO_REF git://github.com/vatesfr/xo-server.git
RUN git clone -b $XO_REF git://github.com/vatesfr/xo-web.git
RUN cd xo-server && npm install
RUN cd xo-server && cp config/local.yaml.dist config/local.yaml
RUN cd xo-web && npm install
RUN cd xo-web && ./gulp --production
ADD local.yaml /usr/src/xo/xo-server/config/
EXPOSE 80
#CMD ["./xo-server/xo-server"]
# see https://github.com/vatesfr/xo-server/pull/28
CMD ["sh", "-eu", "./xo-server/xo-server"]
<file_sep>/docker/master/git/Dockerfile
FROM tianon/docker-master:master
RUN apk add --update \
git \
openssh-client \
&& rm -rf /var/cache/apk/*
<file_sep>/beets/Dockerfile
FROM python:2
ENV BEETS_VERSION 1.3.14
RUN pip install beets==$BEETS_VERSION
CMD ["beet"]
<file_sep>/golang/Dockerfile
FROM debian:wheezy
# necessary for building Go
RUN apt-get update && apt-get install -y build-essential curl
# these are useful for "go get"
RUN apt-get update && apt-get install -y bzr git mercurial
RUN curl -sSL http://golang.org/dl/go1.3.src.tar.gz \
| tar -v -C /usr/src -xz
WORKDIR /usr/src/go
# see http://golang.org/doc/install/source#environment
ENV GOLANG_CROSSPLATFORMS \
darwin/386 darwin/amd64 \
dragonfly/386 dragonfly/amd64 \
freebsd/386 freebsd/amd64 freebsd/arm \
linux/386 linux/amd64 linux/arm \
nacl/386 nacl/amd64p32 \
netbsd/386 netbsd/amd64 netbsd/arm \
openbsd/386 openbsd/amd64 \
plan9/386 plan9/amd64 \
solaris/amd64 \
windows/386 windows/amd64
# (set an explicit GOARM of 5 for maximum ARM compatibility)
ENV GOARM 5
RUN bash -xec '\
cd src; \
for platform in $GOLANG_CROSSPLATFORMS; do \
GOOS=${platform%/*} \
GOARCH=${platform##*/} \
./make.bash --no-clean 2>&1; \
done \
'
ENV PATH /usr/src/go/bin:$PATH
RUN mkdir -p /go/src
ENV GOPATH /go
ENV PATH /go/bin:$PATH
WORKDIR /go
<file_sep>/dind/Dockerfile
FROM debian:jessie
RUN apt-get update && apt-get install -y --no-install-recommends aufs-tools btrfs-tools ca-certificates curl e2fsprogs iptables procps xz-utils && rm -rf /var/lib/apt/lists/*
RUN curl -fSL https://get.docker.io/builds/Linux/x86_64/docker-latest -o /usr/bin/docker \
&& chmod +x /usr/bin/docker \
&& docker -v
RUN curl -fSL https://raw.githubusercontent.com/docker/docker/master/hack/dind -o /dind \
&& chmod +x /dind
VOLUME /var/lib/docker
ENTRYPOINT ["/dind"]
CMD ["bash"]
<file_sep>/exim4/Dockerfile
FROM debian:jessie
RUN apt-get update && apt-get install -y exim4-daemon-light
COPY set-exim4-update-conf /usr/local/bin/
COPY entrypoint.sh /usr/local/bin/
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 25
CMD ["exim", "-bd", "-v"]
<file_sep>/github-pages/Dockerfile
FROM debian:sid
RUN apt-get update && apt-get install -y \
build-essential \
python-pygments \
ruby \
ruby-dev
RUN gem install --no-rdoc --no-ri github-pages
ONBUILD ADD . /blog
ONBUILD WORKDIR /blog
ONBUILD EXPOSE 4000
ONBUILD CMD ["jekyll", "serve"]
<file_sep>/irssi/Dockerfile
FROM debian:sid
RUN apt-get update && apt-get install -y ca-certificates irssi libwww-perl wget
RUN useradd --create-home user
USER user
ENV HOME /home/user
WORKDIR /home/user
RUN mkdir -p .irssi
ENV LANG C.UTF-8
CMD ["irssi"]
<file_sep>/debian/ubuntu-devel/sync.sh
#!/bin/bash
set -e
cd "$(dirname "$(readlink -f "$BASH_SOURCE")")"
set -x
rsync -avP ../devel/ ./
awk '
$1 == "FROM" { $2 = "ubuntu-debootstrap:devel" }
/incoming.debian.org/ { next }
{ print }
' ../devel/Dockerfile > Dockerfile
<file_sep>/jenkins/Dockerfile
FROM debian:jessie
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates curl \
\
git \
&& rm -rf /var/lib/apt/lists/*
# grab gosu for easy step-down from root
RUN gpg --keyserver ha.pool.sks-keyservers.net --recv-keys <KEY>
ENV GOSU_VERSION 1.4
RUN curl -o /usr/local/bin/gosu -fSL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-$(dpkg --print-architecture)" \
&& curl -o /usr/local/bin/gosu.asc -fSL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-$(dpkg --print-architecture).asc" \
&& gpg --verify /usr/local/bin/gosu.asc \
&& rm /usr/local/bin/gosu.asc \
&& chmod +x /usr/local/bin/gosu
RUN apt-key adv --keyserver ha.pool.sks-keyservers.net --recv-keys 150FDE3F7787E7D11EF4E12A9B7D32F2D50582E6
RUN echo 'deb http://pkg.jenkins-ci.org/debian binary/' > /etc/apt/sources.list.d/jenkins.list
ENV JENKINS_VERSION 1.627
RUN apt-get update && apt-get install -y --no-install-recommends \
jenkins=${JENKINS_VERSION} \
&& rm -rf /var/lib/apt/lists/*
ENV JENKINS_HOME /var/lib/jenkins
RUN mkdir -p "$JENKINS_HOME" && chown -R jenkins:jenkins "$JENKINS_HOME"
VOLUME $JENKINS_HOME
EXPOSE 8080
COPY docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["java", "-jar", "/usr/share/jenkins/jenkins.war"]
<file_sep>/syncthing/Dockerfile
FROM debian:jessie
RUN useradd --create-home user
RUN apt-get update && apt-get install -y ca-certificates --no-install-recommends && rm -rf /var/lib/apt/lists/*
# gpg: key 00654A3E: public key "Syncthing Release Management <<EMAIL>>" imported
RUN gpg --keyserver pool.sks-keyservers.net --recv-keys 37C84554E7E0A261E4F76E1ED26E6ED000654A3E
ENV SYNCTHING_VERSION 0.11.23
RUN set -x \
&& apt-get update && apt-get install -y curl --no-install-recommends && rm -rf /var/lib/apt/lists/* \
&& tarball="syncthing-linux-amd64-v${SYNCTHING_VERSION}.tar.gz" \
&& curl -fSL "https://github.com/syncthing/syncthing/releases/download/v${SYNCTHING_VERSION}/"{"$tarball",sha1sum.txt.asc} -O \
&& apt-get purge -y --auto-remove curl \
&& gpg --verify sha1sum.txt.asc \
&& grep -E " ${tarball}\$" sha1sum.txt.asc | sha1sum -c - \
&& rm sha1sum.txt.asc \
&& tar -xvf "$tarball" --strip-components=1 "$(basename "$tarball" .tar.gz)"/syncthing \
&& mv syncthing /usr/local/bin/syncthing \
&& rm "$tarball"
USER user
CMD ["syncthing"]
<file_sep>/mongodb-mms/update.sh
#!/bin/bash
set -e
current="$(HEAD -E 'https://mms.mongodb.com/download/agent/monitoring/mongodb-mms-monitoring-agent_latest_amd64.deb' | grep -m1 '^Location:' | cut -d_ -f2)"
set -x
sed -ri 's/^(ENV MMS_VERSION) .*/\1 '"$current"'/' Dockerfile
<file_sep>/mongodb-server/Dockerfile
FROM debian:unstable
RUN apt-get update && apt-get install -yq mongodb-server
# we need stdout logging and binding on 0.0.0.0
RUN sed -i ' \
s/^logpath/#logpath/g; \
s/^bind_ip.*$/bind_ip = 0.0.0.0/g \
' /etc/mongodb.conf
VOLUME /var/lib/mongodb
CMD ["mongod", "--config", "/etc/mongodb.conf"]
EXPOSE 27017
<file_sep>/mongodb-mms/Dockerfile
FROM debian:wheezy
RUN apt-get update && apt-get install -y curl logrotate
ENV MMS_VERSION 3.4.0.190-1
# see https://mms.mongodb.com/settings/monitoring-agent
# click on "Ubuntu 12.04+"
RUN curl -sSL https://mms.mongodb.com/download/agent/monitoring/mongodb-mms-monitoring-agent_${MMS_VERSION}_amd64.deb -o mms.deb \
&& dpkg -i mms.deb \
&& rm mms.deb
ADD docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]
USER mongodb-mms-agent
CMD ["mongodb-mms-monitoring-agent", "-conf", "/etc/mongodb-mms/monitoring-agent.config"]
| 1e8ac00237e966c311479ea3bb12318b6d135907 | [
"Dockerfile",
"Shell"
] | 18 | Dockerfile | pmav99/dockerfiles | a6fa617a4f7eb92ed6140344189e4e4120b5681d | 67e52359606ac87aa7fb8697064687617868cf5b | |
refs/heads/master | <file_sep>package com.robocorp2.core.dijkstra;
import java.util.List;
public class Graphe {
private final List<Sommet> vertexes;
private final List<Arc> edges;
public Graphe(List<Sommet> vertexes, List<Arc> edges) {
this.vertexes = vertexes;
this.edges = edges;
}
public List<Sommet> getVertexes() {
return vertexes;
}
public List<Arc> getEdges() {
return edges;
}
}<file_sep># mock-server
## 1. Setup
Pour faire fonctionner le mock-serveur :
1.
a. Installer node.js : https://nodejs.org/download/
b. Sous linux : https://www.digitalocean.com/community/tutorials/how-to-compile-node-js-with-npm-from-source-on-centos-6
2. Installer Sails.js : sudo npm install -g sails.js
a [Sails](http://sailsjs.org) application
<file_sep>package com.robocorp2.DAO;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.slim3.datastore.Datastore;
import com.google.appengine.api.datastore.Key;
import com.robocorp2.meta.parking.ParkingMeta;
import com.robocorp2.model.parking.Parking;
import com.robocorp2.model.parking.PointGPS;
import com.robocorp2.model.parking.stats.ParkingForStats;
/**
* Singleton access to Parking storage
* @author Mathieu
*
*/
public class ParkingDAO {
private static ParkingDAO _instance = new ParkingDAO();
private ParkingDAO(){
}
/**
* Singleton implementation
* @return
*/
public static ParkingDAO getInstance(){
return _instance;
}
/**
* Return a parking with his key
* @param key
* @return
*/
public Parking getParkingByKey(Key key){
return Datastore.get(ParkingMeta.get(), key);
}
/**
* Search a parking with his name. Returns a list of parkings
* @param name
* @return
*/
public List<Parking> getParkingByName(String name){
List<Parking> parkings = Datastore.query(ParkingMeta.get()).filter(ParkingMeta.get().nom.equal(name)).asList();
return parkings;
}
/**
* Search a parking with his GPS point. Return a single parking or null.
*
* @param gps
* @return
*/
public Parking getParkingByPointGPS(PointGPS gps){
List<Parking> parkings = Datastore.query(ParkingMeta.get()).filter(ParkingMeta.get().pointGPSLat.equal(gps.getX()))
.filter(ParkingMeta.get().pointGPSLon.equal(gps.getY())).asList();
if(parkings.size() == 0){
return null;
}else{
return parkings.get(0);
}
}
/**
* Search a parking around a GPS point. Return a single parking.
*
* @param gps
* @return
*/
public List<Parking> searchParkingsByPointGPS(PointGPS gps){
List<Parking> parkings = Datastore.query(ParkingMeta.get()).sort(ParkingMeta.get().pointGPSLat.asc).sort(ParkingMeta.get().pointGPSLon.asc).asList();
List<Parking> nearestParkings = new ArrayList<Parking>();
int parkingsToFind = 5;
if(parkings.size() < parkingsToFind){
parkingsToFind = parkings.size();
}
for(int i = 0 ; i < parkingsToFind ; i ++){
Parking nearestParking = new Parking(null, "test", "test", new PointGPS(Double.MAX_VALUE, Double.MAX_VALUE));
for(Parking parking : parkings){
if( Math.abs(parking.getPointGPSLat()-gps.getX()) < Math.abs(nearestParking.getPointGPSLat()-gps.getX()) &&
Math.abs(parking.getPointGPSLon()-gps.getY()) < Math.abs(nearestParking.getPointGPSLon()-gps.getY())){
nearestParking = parking;
nearestParkings.add(parking);
//parkings.remove(parking);
}
}
}
return nearestParkings;
}
/**
* Put a parking to datastore. Generate key before
* @param parking
* @return key
*/
public Key saveParking(Parking parking){
Datastore.put(parking);
return parking.getKey();
}
/**
* Save a modified parking
* @param key, parking
* @return parking
*/
public Parking editParking(Key key, Parking parking){
parking.setKey(key);
Datastore.delete(key);
Datastore.put(parking);
return parking;
}
/**
* Save a parking and keep a history of the previous state
* @param key
* @param parking
* @return
*/
public Parking updateParkingWithStats(Key key, Parking parking){
parking.setKey(key);
Datastore.delete(key);
Datastore.put(parking);
ParkingForStats parkingForStats = new ParkingForStats(parking, new Date(System.currentTimeMillis()));
Datastore.put(parkingForStats);
return parking;
}
}
<file_sep>/*
-------------------------------
GLOBAL ERROR CATCH
-------------------------------
*/
(function() {
var oldErrorHandler = window.onerror;
if(a.environment.get("debug") === true) {
window.onerror = function(message, url, line) {
if(oldErrorHandler) {
return oldErrorHandler(message, url, line);
}
alert("DEBUG MODE, an error occurs\n Message: " +
message + "\n url:" + url + "\n line:" + line);
return false;
};
}
})();
/*
-------------------------------
CLICK CATCH
-------------------------------
*/
// Bind li click
(function() {
// Bind element to respond on click to change class
a.dom.cls('sort-action').tag("a").bind('click', function() {
var el = a.dom.el(this);
el.parent().toggleClass('active');
a.state.forceReloadById("list");
});
}());
a.dom.id("search").bind("keyup", function() {
a.storage.memory.setItem("search", this.value);
a.state.forceReloadById("list");
});
/*
------------------------
HANDLEBARS.JS
------------------------
*/
Handlebars.registerHelper("toLowerCase", function(object) {
if(!a.isNull(object) && !a.isString(object.toLowerCase)) {
return new Handlebars.SafeString(object.toLowerCase());
} else if(a.isString(object)) {
return new Handlebars.SafeString(object);
} else {
return object;
}
});
Handlebars.registerHelper("ifCond", function(v1, v2, options) {
if(v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
Handlebars.registerHelper("safeUrl", function(object) {
if(a.isString(object)) {
return object.replace(/\\/g, "-").replace(/\//g, "-");
}
return object;
});
Handlebars.registerHelper("printDefault", function(object) {
if(a.isNull(object) || !a.isString(object) || object.length === 0) {
return new Handlebars.SafeString("--noname--");
} else {
return new Handlebars.SafeString(object);
}
});
Handlebars.registerHelper("booleanToString", function(object) {
return (object === true) ? "true" : "false";
});
Handlebars.registerHelper("deprecated", function(object) {
return (object === true) ? "deprecated" : "";
});
Handlebars.registerHelper("unimplemented", function(object) {
return (object === true) ? "unimplemented" : "";
});
// Produce doc url for given data
Handlebars.registerHelper("produceDoc", function(object) {
if(a.isString(object) && object.length > 0) {
// Jersey check
if(
object.indexOf("com.sun.jersey") !== -1 ||
object.indexOf("javax.ws.rs") !== -1 ||
object.indexOf("org.glassfish.jersey") !== -1 ||
object.indexOf("com.sun.research.ws.wadl") !== -1
) {
return jerseyDocUrl + object.replace(/\./g, "/") + ".html";
}
// Java check
if(
object.indexOf("javax") === 0 ||
object.indexOf("java") === 0 ||
object.indexOf("org.xml.sax") === 0 ||
object.indexOf("org.w3c.dom") === 0
) {
return javaDocUrl + object.replace(/\./g, "/") + ".html";
}
// Nothing found we try default
if(a.isString(customDocUrl) && customDocUrl.length > 0) {
return customDocUrl + object.replace(/\./g, "/") + ".html";
}
} else {
return "";
}
});
Handlebars.registerHelper("count", function(object) {
return object.length;
});
Handlebars.registerHelper("debug", function(object) {
console.log("Current Context");
console.log("====================");
console.log(this);
if(object) {
console.log("Value");
console.log("====================");
console.log(object);
}
});
/*
------------------------
APPSTORM.JS
------------------------
*/
(function() {
a.environment.set("console", "warn");
a.environment.set("verbose", 1);
var currentHash = a.page.event.hash.getHash(),
timerId = null,
max = 1000;
// Initialise page event hash system
a.page.event.hash.setPreviousHash("");
window.location.href = "#loading_application";
/**
* handle "state change" for every browser
*/
function firstHandle() {
if(a.page.event.hash.getHash() !== currentHash) {
window.location.href = "#" + currentHash;
max = 0;
}
if(max-- <= 0) {
a.timer.remove(timerId);
}
};
// The main starter is here, we will customize it soon
if(
currentHash === null
|| currentHash === ""
|| !a.state.hashExists(currentHash)
) {
currentHash = "list";
}
/*
* Some browser don't get hash change with onHashchange event,
* so we decide to use timer.
* Note : a.page.event.hash is more complex, here is little example
*/
timerId = a.timer.add(firstHandle, null, 10);
})();<file_sep>package com.robocorp2.model.parking;
import java.io.Serializable;
import java.util.UUID;
import javax.xml.bind.annotation.XmlRootElement;
import org.slim3.datastore.Attribute;
import org.slim3.datastore.Datastore;
import org.slim3.datastore.Model;
import com.google.appengine.api.datastore.Key;
/**
*
* @author Mathieu
*
*/
@XmlRootElement
@Model(kind = "Camera")
public class Camera implements Serializable{
private static final long serialVersionUID = 1L;
@Attribute(primaryKey = true)
private Key key;
@Attribute(lob = true)
private PointGPS point;
private double hauteur;
private int rotationInDegrees;
private int focal;
private String adresse;
public Camera(PointGPS point, double hauteur, int rotationInDegrees, int focal, String adresse) {
super();
this.key = Datastore.createKey(Camera.class, UUID.randomUUID().toString());
this.point = point;
this.hauteur = hauteur;
this.rotationInDegrees = rotationInDegrees;
this.focal = focal;
this.adresse = adresse;
}
public Camera() {
super();
}
/**
* @return the key
*/
public Key getKey() {
return key;
}
/**
* @param key the key to set
*/
public void setKey(Key key) {
this.key = key;
}
/**
* @return the point
*/
public PointGPS getPoint() {
return point;
}
/**
* @param point the point to set
*/
public void setPoint(PointGPS point) {
this.point = point;
}
/**
* @return the hauteur
*/
public double getHauteur() {
return hauteur;
}
/**
* @param hauteur the hauteur to set
*/
public void setHauteur(double hauteur) {
this.hauteur = hauteur;
}
/**
* @return the rotationInDegrees
*/
public int getRotationInDegrees() {
return rotationInDegrees;
}
/**
* @param rotationInDegrees the rotationInDegrees to set
*/
public void setRotationInDegrees(int rotationInDegrees) {
this.rotationInDegrees = rotationInDegrees;
}
/**
* @return the focal
*/
public int getFocal() {
return focal;
}
/**
* @param focal the focal to set
*/
public void setFocal(int focal) {
this.focal = focal;
}
/**
* @return the adresse
*/
public String getAdresse() {
return adresse;
}
/**
* @param adresse the adresse to set
*/
public void setAdresse(String adresse) {
this.adresse = adresse;
}
}
<file_sep>function DragAndZoom(canvas) {
function mouseDown(evt) {
dragStart = evt.point;
}
function mouseDrag(evt) {
var pt = evt.point;
paper.view.center = new paper.Point(paper.view.center.x - (pt.x - dragStart.x), paper.view.center.y - (pt.y - dragStart.y));
}
function mouseUpOut(evt) {
dragStart = null;
}
var dragStart;
this.populateTool = function (tool) {
tool.attach('mousedown', mouseDown);
tool.attach('mousedrag', mouseDrag);
tool.attach('mouseup', mouseUpOut);
tool.attach('mouseout', mouseUpOut);
canvas.addEventListener('DOMMouseScroll', handleScroll);
canvas.addEventListener('mousewheel', handleScroll);
}
var scaleFactor = 1.1;
var cumulclick = 0;
var zoom = function (clicks) {
console.log(clicks);
cumulclick += clicks/3
var factor = Math.pow(scaleFactor, cumulclick);
console.log(cumulclick);
//paper.view.center = new paper.Point(paper.view.center.x - (pt.x - dragStart.x), paper.view.center.y - (pt.y - dragStart.y));
console.log(scaleFactor);
paper.view.zoom = factor;
};
var handleScroll = function (evt) {
console.log("scroll");
var delta = evt.wheelDelta ? evt.wheelDelta / 40 : evt.detail ? -evt.detail : 0;
if (delta)
zoom(delta);
return evt.preventDefault() && false;
};
}
;
function DragAndZoom(canvas) {
function mouseDown(evt) {
dragStart = evt.point;
}
function mouseDrag(evt) {
var pt = evt.point;
paper.view.center = new paper.Point(paper.view.center.x - (pt.x - dragStart.x), paper.view.center.y - (pt.y - dragStart.y));
}
function mouseUpOut(evt) {
dragStart = null;
}
var dragStart;
this.populateTool = function (tool) {
tool.attach('mousedown', mouseDown);
tool.attach('mousedrag', mouseDrag);
tool.attach('mouseup', mouseUpOut);
tool.attach('mouseout', mouseUpOut);
canvas.addEventListener('DOMMouseScroll', handleScroll);
canvas.addEventListener('mousewheel', handleScroll);
}
var scaleFactor = 1.1;
var cumulclick = 0;
var zoom = function (clicks) {
console.log(clicks);
cumulclick += clicks/3
var factor = Math.pow(scaleFactor, cumulclick);
console.log(cumulclick);
//paper.view.center = new paper.Point(paper.view.center.x - (pt.x - dragStart.x), paper.view.center.y - (pt.y - dragStart.y));
console.log(scaleFactor);
paper.view.zoom = factor;
};
var handleScroll = function (evt) {
console.log("scroll");
var delta = evt.wheelDelta ? evt.wheelDelta / 40 : evt.detail ? -evt.detail : 0;
if (delta)
zoom(delta);
return evt.preventDefault() && false;
};
}
;<file_sep>jersey-doc-template
===================
Template presentation for [jersey-doc-generator](https://github.com/Deisss/jersey-doc-generator/) output.
It can handle all data elements generated with [jersey-doc-generator](https://github.com/Deisss/jersey-doc-generator/) in a easy and readable
way.
### Screenshot ###
![image](http://www.kirikoo.net/images/14Anonyme-20130819-021044.png)
Installation
------------
The template does work in a pretty simple way. First you need to clone this repository:
git clone --recursive https://github.com/Deisss/jersey-doc-template
We need to get it in recursive mode, because the template use [AppStorm.JS framework](https://github.com/Deisss/AppStorm.JS)
Now you grab a copy of it, we can make it working!
Usage
-----
First of course, you need to output a file from [jersey-doc-generator](https://github.com/Deisss/jersey-doc-generator/).
In our example (see `data.js`) we locate it to __/resource/data/result.json__.
You need to edit `data.js` file at the root folder:
* __jerseyDocGenerator__: it's the place to locate the json data returned by [jersey-doc-generator](https://github.com/Deisss/jersey-doc-generator). You can use more than one file...
* __customDocUrl__: you can specify here your own javadoc, to link classes to your javadoc if they are not java/jersey related.
__javaDocUrl__ and __jerseyDocUrl__ refer to java documentation and jersey documentation.
You probably don't need to change them, as they are pre-configured.
After you did this, it's done, you can use it threw your favorite server, with your favorite browser!
Licence
-------
This project is licensed under MIT licence.
<file_sep>package com.easypark.easypark;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.places.Places;
public class RecommandationActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recommandation);
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
<file_sep>package obj;
public class Blob {
private Point pointHautGauche;
private Point pointBasDroite;
public Blob(){
}
public Blob(int pointHautGaucheX, int pointHautGaucheY, int pointBasDroiteX, int pointBasDroiteY){
pointHautGauche=new Point(pointHautGaucheX, pointHautGaucheY);
pointBasDroite=new Point(pointBasDroiteX, pointBasDroiteY);
}
public Point getBaricentre() {
return null;
}
public Point getPointHautGauche() {
return pointHautGauche;
}
public void setPointHautGauche(Point pointHautGauche) {
this.pointHautGauche = pointHautGauche;
}
public Point getPointBasDroite() {
return pointBasDroite;
}
public void setPointBasDroite(Point pointBasDroite) {
this.pointBasDroite = pointBasDroite;
}
public String toString(){
return "X1:"+pointHautGauche.getX()+" Y1:"+pointHautGauche.getY() + " " +"X2:"+pointBasDroite.getX()+" Y2:"+pointBasDroite.getY();
}
}
<file_sep>package parking;
/**
*
* @author <NAME>
* Une place de parking :
* - un emplacement dans l'espace
* - une "rotation" (en bataille, en �pi, en cr�neau)
* - libre ou non
*
*/
public class Place {
private Point point;
private int rotation;
private boolean free;
/**
* Constructor
* @param point
* @param rotation
* @param free
*/
public Place(Point point, int rotation, boolean free) {
super();
this.point = point;
this.rotation = rotation;
this.free = free;
}
/**
* @return the point
*/
public Point getPoint() {
return point;
}
/**
* @param point the point to set
*/
public void setPoint(Point point) {
this.point = point;
}
/**
* @return the rotation
*/
public int getRotation() {
return rotation;
}
/**
* @param rotation the rotation to set
*/
public void setRotation(int rotation) {
this.rotation = rotation;
}
/**
* @return the free
*/
public boolean isFree() {
return free;
}
/**
* @param free the free to set
*/
public void setFree(boolean free) {
this.free = free;
}
}
<file_sep>package detectionParking;
import java.util.ArrayList;
import obj.Blob;
import obj.Camera;
import obj.Etage;
import obj.Place;
import obj.Point;
import jni.TraitementJNI;
public class Traitement extends Thread {
private String idParking;
private String repertoireImages;
private Etage etage;
private Camera camera;
ArrayList<Place> bufferPlaces=new ArrayList<Place>();
public Traitement(Camera camera, String idParking, Etage etage, String repertoireImages){
this.etage = etage;
this.idParking = idParking;
this.repertoireImages = repertoireImages;
this.camera = camera;
}
@Override
public void run() {
try {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
TraitementJNI.getInstance().lancerCapture(camera.getAdresse(),repertoireImages, true);
}
});
thread.start();
while(true){
//Vider le buffer si y'a qque chose
if(!bufferPlaces.isEmpty()){
for(Place place:bufferPlaces){
boolean retour = Util.mettreAJourPlace(idParking, etage.getKey(), place);
if(!retour){
break;
}else{
bufferPlaces.remove(place);
}
}
}
Blob[] listeBlobs=TraitementJNI.getInstance().getBlobs(camera.getAdresse());
if(listeBlobs!=null){
for(Blob pointBlob:listeBlobs){
//On vérifie si le point correspond à une place visible
//et on calcule si elle est occupée
if(pointBlob!=null){
System.out.println(pointBlob.toString());
gererOccupation(pointBlob);
}
}
}
Thread.sleep(40);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void gererOccupation(Blob pointBlob) {
if(!idParking.equals("0")){
Camera cam = camera;
//Pour chaque place on calcule ses coordonnées sur l'image
//On regarde si elle est dans le champ de vision de la caméra
//On regarde si un des blobs occupe le repère de la place
for(Place place:etage.getPlaces()){
if(isPlaceVisibleParCam(cam, place)){
if(isPlaceChangeEtat(place, pointBlob)){
//Si on a perdu la liaision avec le serveur on bufferise
if(!Util.mettreAJourPlace(idParking, etage.getKey(), place)){
bufferPlaces.add(place);
}
}
}
}
}
}
private boolean isPlaceChangeEtat(Place place, Blob pointBlob) {
boolean placeChangeEtat=false;
if(place.isFree()){
if(repereContenuDansBlob(place.getPoint().getX(),place.getPoint().getY(), pointBlob)){
place.setFree(false);
placeChangeEtat=true;
}
}else{
//"Loin" est à determiner mais on calcule d'abord si le blob est loin
//de la place. Si il est loin on n'a rien de plus à calculer
if(repereContenuDansBlob(place.getPoint().getX(),place.getPoint().getY(), pointBlob)){
if(place.getBlob()==null){
//Un blob viens de s'activer sur la place
//Je le stocke pour pouvoir le comparer au suivant
place.setBlob(pointBlob);
}
}else if(place.getBlob()!=null && distanceEntre2Points(place.getPoint().getX(), pointBlob.getBaricentre().getX(),
place.getPoint().getY(), pointBlob.getBaricentre().getY())<10){
//J'avais detecté un blob et il est sorti
//Du repère de la place
place.setBlob(null);
place.setFree(true);
placeChangeEtat=true;
}
}
return placeChangeEtat;
}
private double distanceEntre2Points(double xA, double xB, double yA, double yB) {
return Math.sqrt(Math.pow(xA-xB, 2)+Math.pow(yA-yB, 2));
}
private boolean isPlaceVisibleParCam(Camera cam, Place place) {
if(idParking.equals("0")){
// Mode debug avec fichier chargé depuis le disque
int x, y; //Coordonnées du centre de la place sur l'image
int ax = 3600;
int ay = 10500;
int bz = 12;
int az = 12000;
x=ax*(bz/az);
y=ay*(bz/az);
System.out.println("x:"+x+" y:"+y);
return true;
}else{
int x, y; //Coordonnées du centre de la place sur l'image
int ax = Math.abs((int) (cam.getPoint().getX()-place.getPoint().getX()));
int ay = Math.abs((int) (cam.getPoint().getY()-place.getPoint().getY()));
int bz = cam.getFocal();
int az = (int) (Math.sqrt((Math.pow(cam.getHauteur(),2)+Math.pow(ay,2))));
x=ax*(bz/az);
y=ay*(bz/az);
//Place visible sur 28 cm de large et à partir de 15 cm de haut par rapport
//à l'image sur une feuille
//A calibrer par caméra
if((x<1 || x>280)||(y<1 || y>15)){
return false;
}else{
place.setPointLocal(new Point(x, y));
return true;
}
}
}
public boolean repereContenuDansBlob(double x, double y, Blob blob){
//Le blob est contenu dans un rectangle toujours horizontal
//Du coup la règle est simple pour savoir si un point est inclus dans
//le périmètre d'un Rectangle
//X compris entre le X du point haut gauche et le X du point bas droite
//Y compris entre le Y du point haut gauche et le Y du point bas droite
return (x>=blob.getPointHautGauche().getX() && x<=blob.getPointBasDroite().getX()) &&
(y>=blob.getPointBasDroite().getY() && y<=blob.getPointHautGauche().getY());
}
}
<file_sep>package com.robocorp2.model.parking;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
import org.slim3.datastore.Attribute;
import org.slim3.datastore.Datastore;
import org.slim3.datastore.Model;
import com.google.appengine.api.datastore.Key;
import com.robocorp2.core.PlaceStatus;
import com.robocorp2.core.PlaceType;
/**
*
* @author <NAME>
* Une place de parking :
* - un emplacement dans l'espace
* - une "rotation" (en bataille, en épi, en créneau)
* - libre ou non
*
*/
@XmlRootElement
@Model(kind = "Place")
public class Place implements Serializable{
private static final long serialVersionUID = 1L;
@Attribute(primaryKey = true)
private Key key;
private int numeroDePlace;
@Attribute(lob = true)
private PointGPS point;
private int rotation;
private PlaceStatus status;
private PlaceType type;
public Place(){
}
/**
* Constructor
* @param point
* @param rotation
* @param free
*/
public Place(PointGPS point, int numero, int rotation, PlaceStatus status, PlaceType type) {
super();
this.key = Datastore.createKey(Place.class, numero);
this.point = point;
this.numeroDePlace = numero;
this.rotation = rotation;
this.status = status;
this.type = type;
}
/**
* @return the key
*/
public Key getKey() {
return key;
}
/**
* @param key the key to set
*/
public void setKey(Key key) {
this.key = key;
}
/**
* @return the point
*/
public PointGPS getPoint() {
return point;
}
/**
* @param point the point to set
*/
public void setPoint(PointGPS point) {
this.point = point;
}
/**
* @return the rotation
*/
public int getRotation() {
return rotation;
}
/**
* @param rotation the rotation to set
*/
public void setRotation(int rotation) {
this.rotation = rotation;
}
/**
* @return the status
*/
public PlaceStatus getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(PlaceStatus status) {
this.status = status;
}
public boolean isFree(){
if(this.status.equals(PlaceStatus.FREE)){
return true;
}
return false;
}
/**
* @return the numeroDePlace
*/
public int getNumeroDePlace() {
return numeroDePlace;
}
/**
* @param numeroDePlace the numeroDePlace to set
*/
public void setNumeroDePlace(int numeroDePlace) {
this.numeroDePlace = numeroDePlace;
}
/**
* @return the type
*/
public PlaceType getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(PlaceType type) {
this.type = type;
}
}
<file_sep><div class="span3 columns" id="rest-detail">
<h1>Details</h1>
<div id="rest-content">
<h5>Click on any API item to see details</h5>
</div>
</div>
<div class="span9 columns" id="rest-global">
{{#content}}
<div onclick="loadDetail('{{type}}', '{{path}}');" class="api-line {{toLowerCase type}} {{deprecated deprecated}} {{unimplemented unimplemented}}">
<div>
<span>{{type}}</span>
{{path}}
<a href="{{produceDoc output}}" target="_blank">{{output}}</a>
</div>
</div>
{{/content}}
{{^content}}
<div class="api-line get text-center">
No match found
</div>
{{/content}}
</div>
<file_sep># robocorp2-CarPark
Projet Robocorp2 : CarPark
<file_sep>package obj;
public class Point {
private int x;
private int y;
public Point(int pointX, int pointY) {
x=pointX;
y=pointY;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
<file_sep>/**
* Convert the system type before rendering
*
* @param data {String} The data to replace
*/
function convertType(data) {
if(a.isString(data)) {
return data.replace("javax.ws.rs.", "");
} else {
return data;
}
};
/**
* Sort between 2 string
*
* @param a {String} The first string
* @param b {String} The second string
*/
function __sortString(a,b) {
if(a < b) {
return -1;
} else if(a > b) {
return 1;
}
return 0;
};
/**
* Sort elements by type (HTTP Verb)
*
* @param data {Array} The array to sort
*/
function sortByType(data) {
if(a.isArray(data)) {
return data.sort(function(a,b) {
var typeA = a.type.toLowerCase(),
typeB = b.type.toLowerCase();
// Change delete string to appear on bottom (place "z" at beginning)
if(typeA === "delete") { typeA = "zdelete"; }
if(typeB === "delete") { typeB = "zdelete"; }
// Same with head and options (place at first)
if(typeA === "head") { typeA = "zhead"; }
if(typeB === "head") { typeB = "zhead"; }
if(typeA === "options") { typeA = "zoptions"; }
if(typeB === "options") { typeB = "zoptions"; }
return __sortString(typeA, typeB);
});
}
return data;
};
/**
* Sort elements by path (HTTP Path)
*
* @param data {Array} The array to sort
*/
function sortByPath(data) {
if(a.isArray(data)) {
return data.sort(function(a,b) {
var typeA = a.path.toLowerCase(),
typeB = b.path.toLowerCase();
return __sortString(typeA, typeB);
});
}
return data;
};
/**
* Sort elements by output (HTTP Return)
*
* @param data {Array} The array to sort
*/
function sortByOutput(data) {
if(a.isArray(data)) {
return data.sort(function(a,b) {
var typeA = a.output.toLowerCase(),
typeB = b.output.toLowerCase();
return __sortString(typeA, typeB);
});
}
return data;
};<file_sep>package com.robocorp2.API;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.slim3.datastore.Datastore;
import com.google.appengine.api.datastore.Key;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.robocorp2.DAO.ParkingDAO;
import com.robocorp2.core.KeyAdapterSerializer;
import com.robocorp2.model.parking.Etage;
import com.robocorp2.model.parking.Parking;
import com.robocorp2.model.parking.Place;
import com.robocorp2.model.parking.PointGPS;
import com.simplapi.jersey.doc.annotation.ApiAuthor;
import com.simplapi.jersey.doc.annotation.ApiDoc;
import com.simplapi.jersey.doc.annotation.ApiVersion;
@Path("parking")
@ApiDoc("Gestion du parking lui même : création, récupération du schéma, récupération d'une place...")
@ApiAuthor("<NAME>")
@ApiVersion("0.1")
public class ParkingAPI {
public static Gson gson = (new GsonBuilder()).serializeNulls()
.setPrettyPrinting().registerTypeAdapter(Key.class, new KeyAdapterSerializer()).create();
@PUT
@Path("create")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@ApiDoc("Créé un nouveau parking et lui attribue une clé qui est retournée")
@ApiAuthor("<NAME>")
@ApiVersion("0.1")
public String createParking(Parking parking){
Key key = ParkingDAO.getInstance().saveParking(parking);
return Datastore.keyToString(key);
}
@POST
@Path("edit/{key}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@ApiDoc("Edite le modèle de parking, pour ajouter/enlever des places. Retourne le parking modifié")
@ApiAuthor("<NAME>")
@ApiVersion("0.1")
public String editParking(@PathParam("key") String key, Parking parking){
Key nativeKey = Datastore.stringToKey(key);
return gson.toJson(ParkingDAO.getInstance().editParking(nativeKey, parking));
}
@GET
@Path("get/{key}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@ApiDoc("Récupère un modèle de parking avec sa clé")
@ApiAuthor("<NAME>")
@ApiVersion("0.1")
public String getParkingByKey(@PathParam("key") String key){
Parking parking = ParkingDAO.getInstance().getParkingByKey(Datastore.stringToKey(key));
return gson.toJson(parking);
}
@GET
@Path("get/{latitude}/{longitude}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@ApiDoc("Récupère un modèle de parking avec sa coordonnée GPS")
@ApiAuthor("<NAME>")
@ApiVersion("0.1")
public String getParkingByGPSPoint(@PathParam("latitude") double latitude, @PathParam("longitude") double longitude){
return gson.toJson(ParkingDAO.getInstance().getParkingByPointGPS(new PointGPS(latitude, longitude)));
}
@GET
@Path("search/{latitude}/{longitude}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@ApiDoc("Recherche une liste de parkings les plus proches (max 5) avec une coordonnée GPS")
@ApiAuthor("<NAME>")
@ApiVersion("0.1")
public String searchParkingByGPSPoint(@PathParam("latitude") double latitude, @PathParam("longitude") double longitude){
return gson.toJson(ParkingDAO.getInstance().searchParkingsByPointGPS(new PointGPS(latitude, longitude)));
}
@GET
@Path("getNumberOfFreePlaces/{idParking}")
@Consumes("Application/JSON")
@Produces("Application/JSON")
@ApiDoc("Donne le nombre de places libres dans un parking")
@ApiAuthor("<NAME>")
@ApiVersion("0.1")
public String getNumberFreePlaces(@PathParam("idParking") String keyParking){
int nbFreePlaces = 0;
Parking parking = ParkingDAO.getInstance().getParkingByKey(Datastore.stringToKey(keyParking));
for(Etage etage : parking.getEtages()){
for(Place place : etage.getPlaces()){
if(place.isFree()){
nbFreePlaces++;
}
}
}
return nbFreePlaces+"";
}
}
<file_sep>#include <stdio.h>
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/background_segm.hpp>
#include <math.h>
#include <jni_TraitementJNI.h>
#include <jni.h>
#include <windows.h>
using namespace cv;
using namespace std;
class Blob{
public:
Point pointBasDroite, pointHautGauche;
};
//
std::map<String,vector<Blob> > blobList;
int traitementCamera(String adresseCamera, bool debug, String repertoireImages){
//global variables
Mat frame; //current frame
Mat resize_blur_Img;
Mat foreground; //Image du premier plan
Mat binaryImg;
//Mat TestImg;
Mat ContourImg; //fg mask fg mask generated by MOG2 method
cv::Ptr<BackgroundSubtractor> mOG2 = createBackgroundSubtractorMOG2(300,32,false);
//Capture d'un fichier pour les tests,
//d'une webcam pour la mise en prod
VideoCapture stream1;
if(isdigit(adresseCamera.c_str()[0])){
stream1=VideoCapture(atoi(adresseCamera.c_str()));
}else{
stream1=VideoCapture(adresseCamera);
}
//Pour nettoyer les pixels isolés faux positif
Mat element = getStructuringElement(MORPH_RECT, Size(7, 7), Point(3,3) );
if(blobList.find(adresseCamera)->first==NULL){
blobList.insert(std::pair<String,vector<Blob> >(adresseCamera,vector<Blob>()));
}
int i=1;
std::map<String, vector<Blob> >::iterator listeBlob=blobList.find(adresseCamera);
while (true) {
listeBlob->second.clear();
if((stream1.read(frame))){ //get one frame form video
//Resize
//Reduire l'image peut accelerer le traitement
resize(frame, resize_blur_Img, Size(frame.size().width/1, frame.size().height/1) );
//Leger flou pour éliminer des détails qui feraient de faux positifs
blur(resize_blur_Img, resize_blur_Img, Size(4,4) );
//Background subtraction
mOG2->apply(resize_blur_Img, foreground, -1);//,-0.5);
// Suppression des points isolés
morphologyEx(foreground, binaryImg, CV_MOP_CLOSE, element);
//Suppression de l'ombre
//Sur le foreground l'ombre est grise alors que l'objet lui même est blanc
threshold(binaryImg, binaryImg, 128, 255, CV_THRESH_BINARY);
//On essaye de strucuturer les objets trouvés par contours
vector<vector<Point> > contours;
findContours(binaryImg,
contours, // a vector of contours
CV_RETR_EXTERNAL, // retrieve the external contours
CV_CHAIN_APPROX_NONE); // all pixels of each contours
vector<vector<Point> > contours_poly( contours.size() );
vector<Rect> boundRect( contours.size() );
vector<Point2f>center( contours.size() );
vector<float>radius( contours.size() );
for( unsigned int index = 0; index < contours.size(); index++ )
{
approxPolyDP( Mat(contours[index]), contours_poly[index], 3, true );
}
if(contours_poly.size()<200){
for( unsigned int j = 0; j < contours_poly.size(); j++ )
{
if(contourArea(contours_poly[j])>400){
boundRect[j] = boundingRect( Mat(contours_poly[j]) );
Blob blob = Blob();
blob.pointBasDroite=boundRect[j].br();
blob.pointHautGauche=boundRect[j].tl();
listeBlob->second.push_back(blob);
// printf("Traitement X1:%i Y1:%i X2:%i Y2:%i\n",blob.pointHautGauche.x, blob.pointHautGauche.y, blob.pointBasDroite.x, blob.pointBasDroite.y);
if(debug && ((i%25)==0)){
Scalar color = Scalar(0, 0, 255);
rectangle( frame, boundRect[j].tl(), boundRect[j].br(), color, 2, 8, 0 );
std::stringstream nomFichierSortie1;
std::stringstream nomFichierSortie2;
nomFichierSortie1 << repertoireImages<<"/foreground/image_" << i << ".jpg";
imwrite(nomFichierSortie1.str(), foreground);
nomFichierSortie2 << repertoireImages<<"/image_" << i << ".jpg";
imwrite(nomFichierSortie2.str(), frame);
}
}
}
}
Sleep(40);
}
i++;
}
return true;
}
JNIEXPORT void JNICALL Java_jni_TraitementJNI_lancerCapture
(JNIEnv *env, jobject object, jstring name, jstring repertoireImages, jboolean debug){
const char *str= env->GetStringUTFChars(name,0);
const char *repertoire= env->GetStringUTFChars(repertoireImages,0);
printf("Mode debug :%s\n", debug ? "true" : "false");
printf("Nom du fichier: %s\n", str);
traitementCamera(str, debug, repertoire);
//need to release this string when done with it in order to
//avoid memory leak
env->ReleaseStringUTFChars(name, str);
}
JNIEXPORT jobjectArray JNICALL Java_jni_TraitementJNI_getBlobs
(JNIEnv *env, jobject object, jstring adresseCamera){
jobjectArray result;
const char *str= env->GetStringUTFChars(adresseCamera,0);
env->ReleaseStringUTFChars(adresseCamera, str);
std::map<String, vector<Blob> >::iterator iteratorBlob=blobList.find(str);
vector<Blob> listeBlob = iteratorBlob->second;
jclass cls;
cls = env->FindClass("obj/Blob");
if(cls==NULL){
printf("classe NULL");
}
result=env->NewObjectArray(listeBlob.size(),cls,NULL);
for(unsigned int i=0;i<listeBlob.size();i++){
jmethodID constructor;
jint args[4];
jobject object;
constructor = env->GetMethodID(cls, "<init>", "(IIII)V");
Blob blob = listeBlob[i];
args[0] = blob.pointHautGauche.x;
args[1] = blob.pointHautGauche.y;
args[2] = blob.pointBasDroite.x;
args[3] = blob.pointBasDroite.y;
// printf("DLL blob X1:%i Y1:%i X2:%i Y2:%i\n",blob.pointHautGauche.x, blob.pointHautGauche.y, blob.pointBasDroite.x, blob.pointBasDroite.y);
// printf("DLL ARGS X1:%i Y1:%i X2:%i Y2:%i\n",args[0], args[1], args[2], args[3]);
object = env->NewObject(cls, constructor, args[0], args[1], args[2], args[3]);
env->SetObjectArrayElement(result, i, object);
return result;
}
}
<file_sep>// Root controller system, loading main app system here
(function() {
/**
* Generate function to replace an id by the content given
*
* @param id {String} The id to perform changes
*/
function __replaceById(id) {
return function(content) {
a.page.template.replace(document.getElementById(id), content);
}
};
// Preload url
a.page.template.get("resource/html/list.html");
a.page.template.get("resource/html/test.html");
a.page.template.get("resource/html/detail.html");
// Handle the logged part (when user sign in successfully)
var content = {
bootOnLoad : true,
id : "root",
data : {},
converter : function(data) {
a.storage.memory.setItem("api", data);
},
children : [
{
id : "list",
hash : "list",
title: "Documentation - list",
load : __replaceById("page-content"),
data : {
api : "{{memory: api}}"
},
include : {
html : "resource/html/list.html"
},
converter : function(data) {
// Rendering
var arr = [];
for(var i in data.api) {
var tmp = jerseyDocPrettify(data.api[i]);
arr = arr.concat(tmp);
}
// Sorting final result
data.content = a.clone(arr);
if(a.dom.id("sort-by-output").hasClass("active")) {
data.content = sortByOutput(data.content);
}
if(a.dom.id("sort-by-path").hasClass("active")) {
data.content = sortByPath(data.content);
}
if(a.dom.id("sort-by-type").hasClass("active")) {
data.content = sortByType(data.content);
}
// Filtering deprecated & unimplemented & search
var deprecated = !a.dom.id("include-type-deprecated")
.hasClass("active"),
unimplemented = !a.dom.id("include-type-unimplemented")
.hasClass("active"),
boolSearch = false;
search = a.storage.memory.getItem("search");
if(a.isString(search) && search.length > 0) {
boolSearch = true;
search = search.toLowerCase();
}
var i = data.content.length;
while(i--) {
var el = data.content[i];
// Deprecated && unimplemented
if(
(deprecated && el.deprecated === true) ||
(unimplemented && el.unimplemented === true)
) {
data.content.splice(i, 1);
continue;
}
// Search
if(boolSearch) {
if(
el.path.toLowerCase().search(search) === -1 &&
el.type.toLowerCase().search(search) === -1 &&
el.output.toLowerCase().search(search) === -1
) {
data.content.splice(i, 1);
continue;
}
}
}
// Store parsed content
a.storage.memory.setItem("content", data.content);
},
preLoad : function(result) {
a.dom.id('menu-test').css('display', 'none');
a.dom.id('menu-list').css('display', 'block');
a.storage.memory.setItem("gotry", true);
result.done();
}
},
{
// TODO : currently switching from list to test is not well done, as root lost html elements doing this ! we should avoid test here so ! Correct that, and make a better version of this !
id : "test",
hash : "test/{{type: [a-zA-Z]+}}/{{path : .+}}",
title: "Documentation - test request",
load : __replaceById("page-content"),
data : {
type : "{{type}}",
path : "{{path}}",
api : "{{memory : api}}"
},
include : {
html : "resource/html/test.html"
},
converter : function(data) {
// Rendering
var arr = [];
for(var i in data.api) {
var tmp = jerseyDocPrettify(data.api[i]);
arr = arr.concat(tmp);
}
data.content = null;
for(var i=0, l=arr.length; i<l; ++i) {
var el = arr[i];
// See Handlebars - safe url function in boot.js
var tmp = el.path.replace(/\\/g, "-").replace(/\//g, "-");
if(tmp == data.path && el.type == data.type) {
data.content = el;
break;
}
}
// If we found some data, now we proceed input list to find relation
// between url, and inputList
if(data.content) {
}
},
preLoad : function(result) {
a.dom.id('menu-list').css('display', 'none');
a.dom.id('menu-test').css('display', 'block');
result.done();
},
postLoad : function(result) {
// Store parsed content
a.storage.memory.setItem("current", result.getData("content"));
a.storage.memory.setItem("gotry", false);
// Loading left state
a.state.loadById("detail");
result.done();
}
}
]
};
var detail = {
id : "detail",
load : __replaceById("rest-content"),
data : {
api : "{{memory: current}}",
gotry : "{{memory: gotry}}"
},
include : {
html : "resource/html/detail.html"
}
};
// Populate tree data
for(var i=0, l=jerseyDocGenerator.length; i<l; ++i) {
content.data[i] = jerseyDocGenerator[i];
}
// Finally we add elements to system
a.state.add(content);
a.state.add(detail);
})();
/**
* Load a specific detail list
*
* @param type {String} The type to search
* @param path {String} The path to search
*/
function loadDetail(type, path) {
var data = a.storage.memory.getItem("content");
var i = data.length;
while(i--) {
if(data[i].type === type && data[i].path === path) {
a.storage.memory.setItem("current", data[i]);
a.state.loadById("detail");
break;
}
}
};
/**
* Request to active a different tab from the default one
*
* @param current {String} The tab name to activate
*/
function changeTestTab(current) {
var opposite = (current === 'response') ? 'request' : 'response';
a.dom.id('content-' + current + ', menu-' + current ).addClass('active');
a.dom.id('content-' + opposite + ', menu-' + opposite).removeClass('active');
};
/**
* get the "raw" header add, and append it to dom
*/
function addTestHeader() {
a.page.template.get("tmpl_test_header", null, function(content) {
a.page.template.append(
document.getElementById("additional-header"),
content
);
// We create a new "additional-header" if needed
var id = "additional-header";
var span = a.dom.id(id).cls("span6").getElements();
if(span.length >= 2) {
var container = document.createElement("div");
container.className = "container-fluid";
var row = document.createElement("div");
row.className = "row-fluid";
row.id = id;
container.appendChild(row);
// We get id, remove it, and create to parent a new element with
// this id, to always have no trouble with row-fluid system
a.dom.id(id).attribute("id", null).parent().parent().append(container);
}
});
};
function addTestQueryParam() {
a.page.template.get("tmpl_test_parameter", null, function(content) {
a.page.template.append(
document.getElementById("additional-query-parameter"),
content
);
// We create a new "additional-header" if needed
var id = "additional-query-parameter";
var span = a.dom.id(id).cls("span12").getElements();
if(span.length >= 1) {
var container = document.createElement("div");
container.className = "container-fluid";
var row = document.createElement("div");
row.className = "row-fluid";
row.id = id;
container.appendChild(row);
// We get id, remove it, and create to parent a new element with
// this id, to always have no trouble with row-fluid system
a.dom.id(id).attribute("id", null).parent().parent().append(container);
}
});
};
/**
* Perform a test on given parameters
*/
function testRequest() {
var dom = document.getElementById("test-request"),
form = a.form.get(dom);
var notParsedUrl = form["url-server"];
// Remove last char if it's not well positioned
if(notParsedUrl.substr(notParsedUrl.length - 1) == "/") {
notParsedUrl = notParsedUrl.substr(0, notParsedUrl.length - 1);
}
// Add "http"
if(notParsedUrl.substr(0, 7) != "http://") {
notParsedUrl = "http://" + notParsedUrl;
}
notParsedUrl += form["content-path"];
// Now the url is in "final" mode, we can bind param to it
// To do so, we will use parsing from Appstorm, as it is ready for that !
var preparedUrl = notParsedUrl.replace(/\{/, "{{").replace(/\}/, "}}");
// TODO: the good things is that URL is close to be OK for appstorm too from state... deal with it
var parsedUrl = preparedUrl;
// Manage extra parameter data
var parameterKeyList = a.dom.cls("parameter-key").getElements(),
parameterValueList = a.dom.cls("parameter-value").getElements();
var parameterResult = [];
for(var i=0, l=parameterKeyList.length; i<l; ++i) {
var key = parameterKeyList[i].value,
val = parameterValueList[i].value;
if(!a.isNull(key) && a.isString(key) && key.length > 0) {
parameterResult.push(
encodeURIComponent(key)
+ "="
+ encodeURIComponent(val)
);
}
}
// User gives some custom parameters
if(parameterResult.length > 0) {
parsedUrl += "?" + parameterResult.join("&");
}
// Building basic Ajax request options
var options = {
url: parsedUrl,
type: "raw",
method: form["content-method"],
cache: false,
data: form["text-request-body"] || "",
header: {}
};
if(form["accept"]) {
options.header["accept"] = form["accept"];
}
if(form["content-type"]) {
options.header["content-type"] = form["content-type"];
// Set in JSON mode
if(form["content-type"].toLowerCase() === "application/json") {
options.type = "json";
} else if(form["content-type"].toLowerCase() === "application/xml") {
options.type = "xml";
}
}
if(form["basic-auth"]) {
options.header["authorization"] = "Basic " + Base64.encode(form["basic-auth"]);
}
// We grab custom data from user
var headerKeyList = a.dom.cls("header-key").getElements(),
headerValueList = a.dom.cls("header-value").getElements();
for(var i=0, l=headerKeyList.length; i<l; ++i) {
var key = headerKeyList[i].value || "",
val = headerValueList[i].value || "";
if(
!a.isNull(key) && a.isString(key) && key.length > 0
&& !a.isNull(val)
) {
options.header[key] = val;
}
}
// Preparing request for sending
var request = new a.ajax(options,
// success function
function(result, statusCode) {
// we can retrieve all header data from request
var body = document.getElementById("text-response-body"),
status = document.getElementById("text-response-status"),
header = document.getElementById("text-response-header");
// Erase
body.innerHTML = "";
header.innerHTML = "";
// HTTP Status code
status.value = statusCode;
// Put header
header.innerHTML += request.request.getAllResponseHeaders().toString();
// Body response
body.innerHTML += result;
// Show results
changeTestTab("response");
// error function
}, function(statusCode) {
// we can retrieve all header data from request
var body = document.getElementById("text-response-body"),
status = document.getElementById("text-response-status"),
header = document.getElementById("text-response-header");
// Erase
body.innerHTML = "";
header.innerHTML = "";
// HTTP Status code
status.value = statusCode;
// Put header
header.innerHTML += request.request.getAllResponseHeaders().toString();
// Show results
changeTestTab("response");
});
// Starting request
request.send();
};<file_sep># Serveur static de test
## Installation
sudo npm install -g connect serve-static
<file_sep>package obj;
import detectionParking.JsonIgnoreProperties;
public class Camera {
private String key;
private PointGPS point;
private double hauteur;
private int rotationInDegrees;
private int focal;
private String adresse;
@JsonIgnoreProperties({"key"})
public PointGPS getPoint() {
return point;
}
public void setPoint(PointGPS point) {
this.point = point;
}
public double getHauteur() {
return hauteur;
}
public void setHauteur(double hauteur) {
this.hauteur = hauteur;
}
public int getRotationInDegrees() {
return rotationInDegrees;
}
public void setRotationInDegrees(int rotationInDegrees) {
this.rotationInDegrees = rotationInDegrees;
}
public int getFocal() {
return focal;
}
public void setFocal(int focal) {
this.focal = focal;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
}
<file_sep>package com.roboborp2.API;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.Test;
import org.slim3.datastore.Datastore;
import com.robocorp2.API.ParkingAPI;
import com.robocorp2.DAO.ParkingDAO;
import com.robocorp2.model.parking.Camera;
import com.robocorp2.model.parking.Etage;
import com.robocorp2.model.parking.Parking;
import com.robocorp2.model.parking.Place;
import com.robocorp2.model.parking.PointGPS;
import com.robocorp2.model.parking.Vecteur;
public class ParkingTestAPI {
@Test
public void testCreate(){
String nom = "Parking de démo";
String adresse = "Adresse - 31000 Toulouse";
ArrayList<Etage> etages = new ArrayList<Etage>();
ArrayList<Place> places = new ArrayList<Place>();
ArrayList<Vecteur> chemins = new ArrayList<Vecteur>();
ArrayList<Camera> cameras = new ArrayList<Camera>();
places.add(new Place(new PointGPS(1.0, 2.0), 1, 90, true));
places.add(new Place(new PointGPS(2.0, 3.0), 2, 90, true));
chemins.add(new Vecteur(new PointGPS(2.0, 4.0), new PointGPS(4.0, 7.0)));
chemins.add(new Vecteur(new PointGPS(4.0, 7.0), new PointGPS(9.0, 8.0)));
cameras.add(new Camera(new PointGPS(1.0,1.0), 4, 90, 120));
etages.add(new Etage(places, chemins, cameras));
Parking parking = new Parking(null, etages, nom, adresse);
String parkingKey = new ParkingAPI().createParking(parking);
Parking parkingFromStore = ParkingDAO.getInstance().getParkingByKey(Datastore.stringToKey(parkingKey));
assertEquals(parkingFromStore, parking);
Datastore.delete(Datastore.stringToKey(parkingKey));
}
@Test
public void testEdit(){
}
}
<file_sep>var connect = require('connect');
var serveStatic = require('serve-static');
// Server de test contenant le template
connect().use(serveStatic(__dirname + '/bower_components/admin-lte')).listen(1235);
connect().use(serveStatic(__dirname)).listen(1234);
<file_sep>package com.robocorp2.API;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import org.slim3.datastore.Datastore;
import com.google.appengine.api.datastore.Key;
import com.robocorp2.DAO.ParkingDAO;
import com.robocorp2.core.dijkstra.Dijkstra;
import com.robocorp2.core.dijkstra.Arc;
import com.robocorp2.core.dijkstra.Graphe;
import com.robocorp2.core.dijkstra.Sommet;
import com.robocorp2.model.parking.Etage;
import com.robocorp2.model.parking.Parking;
import com.robocorp2.model.parking.Place;
import com.robocorp2.model.parking.PointGPS;
import com.robocorp2.model.parking.Vecteur;
import com.simplapi.jersey.doc.annotation.ApiAuthor;
import com.simplapi.jersey.doc.annotation.ApiDoc;
import com.simplapi.jersey.doc.annotation.ApiUnimplemented;
import com.simplapi.jersey.doc.annotation.ApiVersion;
@Path("chemin")
@ApiDoc("Calcul et retour des chemins pour accéder à une place")
@ApiAuthor("<NAME>")
@ApiVersion("0.1")
public class CheminAPI {
@GET
@Path("getRoute/{idParking}/{idPlace}")
@ApiDoc("Donne le chemin jusqu'à une place")
@ApiAuthor("<NAME>")
@ApiVersion("0.1")
@ApiUnimplemented(value = "not implemented")
public PointGPS[] getCheminToPlace(@PathParam("idParking") String parkingKey, @PathParam("idPlace") int idPlace){
Key nativeKey = Datastore.stringToKey(parkingKey);
Parking parking = ParkingDAO.getInstance().getParkingByKey(nativeKey);
Place placeToGo = null;
Etage etageToGo = null;
for(Etage etage : parking.getEtages()){
for(Place place : etage.getPlaces()){
if(place.getNumeroDePlace() == idPlace){
placeToGo = place;
etageToGo = etage;
}
}
}
ArrayList<Vecteur> chemin = new ArrayList<Vecteur>();
PointGPS pointToGo = placeToGo.getPoint();
// calcul d'un chemin
// 1 on calcule le graphe de l'étage
List<Sommet> nodes = new ArrayList<Sommet>();
List<Arc> edges = new ArrayList<Arc>();
for(Vecteur vecteur : etageToGo.getChemins()){
PointGPS debut = vecteur.getPointDebut();
PointGPS fin = vecteur.getPointFin();
boolean addDebut = true;
boolean addFin = true;
for(Sommet node : nodes){
if(node.getPointGPS().equals(debut)){
addDebut = false;
}
if(node.getPointGPS().equals(fin)){
addFin = false;
}
}
if(addDebut){
nodes.add(new Sommet(Datastore.keyToString(vecteur.getKey()), debut));
}
if(addFin){
nodes.add(new Sommet(Datastore.keyToString(vecteur.getKey()), fin));
}
}
for(Vecteur vecteur : etageToGo.getChemins()){
double norme = vecteur.getNorme();
Sommet source = null;
Sommet destination = null;
for(Sommet node : nodes){
if(node.getPointGPS().equals(vecteur.getPointDebut())){
source = node;
}
if(node.getPointGPS().equals(vecteur.getPointFin())){
destination = node;
}
}
edges.add(new Arc(Datastore.keyToString(vecteur.getKey()), source, destination, norme));
}
Graphe graph = new Graphe(nodes, edges);
Dijkstra dijkstra = new Dijkstra(graph);
// find the nodes
PointGPS debut = new PointGPS(parking.getPointGPSLat(), parking.getPointGPSLon());
PointGPS destination = placeToGo.getPoint();
Sommet vertexDebut = null;
Sommet vertexFin = null;
for(Sommet node : nodes){
if(node.getPointGPS().equals(debut)){
vertexDebut = node;
}
if(node.getPointGPS().equals(destination)){
vertexFin = node;
}
}
dijkstra.execute(vertexDebut);
LinkedList<Sommet> path = dijkstra.getPath(vertexFin);
PointGPS[] itineraire = new PointGPS[path.size()];
int i = 0;
for(Sommet vertex : path){
itineraire[i] = vertex.getPointGPS();
i++;
}
return itineraire;
}
}
<file_sep>/**
* Default templating object, used internally
* NOTE: must be cloned (using a.clone) before any use
*/
var jerseyDocObject = {
// The final path (concat of every sub path)
path: "",
// Merge all consumes/produces found to extract list of available one
consumeList: [],
produceList: [],
// General documentation (overriden by latest everytimes exect docList and nameList)
author: "",
version: "",
docList: [],
nameList: [],
// One resource/subresource declare this, the full sub-line(s) get this state
deprecated: false,
unimplemented: false,
// Final ending (method content)
inputList: [],
output: "",
// GET, POST, PUT, DELETE, ...
type: "GET"
};
/**
* Main prettify class
*/
var jerseyDocPrettify = (function() {
"use strict";
/**
* Detect a class type
*
* @param data {Mixed} The data to check
*/
function __detectClass(data) {
return (!a.isNull(data) && !a.isNull(data.methodList));
};
/**
* Check is a string is valid (and contains data) or not
*
* @param data {Mixed}
* @return {Boolean} True or false, if it's a valid with data string or not
*/
function __validString(data) {
return (a.isString(data) && data.length > 0);
};
/**
* From two part of path, create a single concat version
*
* @param path1 {String} The first path to concat
* @param path2 {String} The second path to concat
* @return {String} The concat version
*/
function __concatPath(path1, path2) {
if(path1.charAt(path1.length - 1) != "/") {
path1 += "/";
}
if(__validString(path2)) {
// Sanitize url (remove all double //)
path2 = path2.replace(new RegExp("//+", "g"), "/");
// Remove first char if it does not fit
if(path2.charAt(0) === "/") {
path2 = path2.substr(1);
}
path1 += path2;
}
return path1;
};
/**
* Parse common data between method and class
*
* @param result {jerseyDocObject} The current object parsed for this path
* @param data {Object} The server side object
*/
function __parseDefault(result, data) {
// Get the current showed path
result.path = __concatPath(result.path, data.path);
// ConsumeList && ProduceList
if(a.isArray(data.consumeList) && data.consumeList.length > 0) {
var i = data.consumeList.length;
while(i--) {
result.consumeList.push(data.consumeList);
}
}
if(a.isArray(data.produceList) && data.produceList.length > 0) {
var i = data.produceList.length;
while(i--) {
result.produceList.push(data.produceList);
}
}
// Author & version
if(__validString(data.author)) {
result.author = data.author;
}
if(__validString(data.version)) {
result.version = data.version;
}
// docList
if(__validString(data.doc)) {
result.docList.push(data.doc);
}
// Deprecated & unimplemented
if(data.deprecated === true) {
result.deprecated = true;
}
if(data.unimplemented === true) {
result.unimplemented = true;
}
};
/**
* Parse data to get method presentation
*
* @param result {jerseyDocObject} The current object parsed for this path
* @param data {Object} The server side object
*/
function __parseMethod(result, data) {
__parseDefault(result, data);
if(__validString(data.name) && result.nameList.length > 0) {
result.nameList[result.nameList.length - 1] += " | " + data.name;
}
// InputList
result.inputList = result.inputList.concat(data.inputList);
if(data.subResource === true) {
return __parseClass(a.clone(result), data.output);
} else {
// Output
result.output = data.output.name;
// type
result.type = convertType(data.type);
// We can print data
return result;
}
};
/**
* Parse data to get class presentation
*
* @param result {jerseyDocObject} The current object parsed for this path
* @param data {Object} The server side object
*/
function __parseClass(result, data) {
__parseDefault(result, data);
if(__validString(data.name)) {
result.nameList.push(data.name);
}
// Getting method content
var i = data.methodList.length,
arr = [];
while(i--) {
var tmp = __parseMethod(a.clone(result), data.methodList[i]);
if(a.isArray(tmp)) {
arr = arr.concat(tmp);
} else {
arr.push(tmp);
}
}
return arr;
};
/**
* Main presentation parser to handle json content
*
* @param json {Object | array} Data recieve from server side
*/
return function(json) {
if(a.isNull(json)) {
alert("Some data recieve where empty, can't proceed");
return;
}
// Processing array as sub resource
if(a.isArray(json)) {
var i = json.length;
while(i--) {
jerseyDocPrettify(json[i]);
}
return;
}
if(a.isObject(json) && __detectClass(json)) {
return __parseClass(a.clone(jerseyDocObject), json);
} else {
alert("unknow data given, can't proceed");
}
};
})();
<file_sep>package parking;
import java.util.List;
/**
*
* @author <NAME>
* Un �tage de parking contenant :
* - des places
* - des itin�raires
*
*/
public class Etage {
private List<Place> places;
private List<Vecteur> chemins;
/**
* Constructor
* @param places
* @param chemins
*/
public Etage(List<Place> places, List<Vecteur> chemins) {
super();
this.places = places;
this.chemins = chemins;
}
/**
* @return the places
*/
public List<Place> getPlaces() {
return places;
}
/**
* @param places the places to set
*/
public void setPlaces(List<Place> places) {
this.places = places;
}
/**
* @return the chemins
*/
public List<Vecteur> getChemins() {
return chemins;
}
/**
* @param chemins the chemins to set
*/
public void setChemins(List<Vecteur> chemins) {
this.chemins = chemins;
}
}
| db50c20a4e8a4869f1d296278efec6a2a37f6334 | [
"HTML",
"Markdown",
"JavaScript",
"Java",
"C++"
] | 26 | Java | mathieupassenaud/robocorp2-CarPark | 7d607f38fe75a3cf5b3cab187fd4540dda773e21 | eb92566ff77e03fecaed4943dcc800cae918a8bd | |
refs/heads/master | <file_sep>controllers.controller('HailRequestController@request', [
'$scope', '$state', '$stateParams', 'mapEngine', '$rootScope', 'Callback', 'User',
'Geolocation', '$timeout', '$ionicPopup', 'HailRequest', 'Mode', 'Util', '$ionicLoading',
'$ionicPopover', '$ionicHistory', 'Validator', '$ionicSideMenuDelegate', '$cordovaDialogs',
function($scope, $state, $stateParams, mapEngine, $rootScope, Callback, User,
Geolocation, $timeout, $ionicPopup, HailRequest, Mode, Util, $ionicLoading,
$ionicPopover, $ionicHistory, Validator, $ionicSideMenuDelegate, $cordovaDialogs) {
'use strict';
var REQUEST_STATE = {
INIT: 0,
HAIL: 1,
PICKUP: 2,
DROPOFF: 3,
MEETING_POINT: 3.5,
CONFIRM_MEETING_POINT: 3.75,
FARE: 4
};
$scope.REQUEST_STATE = REQUEST_STATE;
var fareConfirm = null,
commentConfirm = null,
meetingPointConfirm = null,
dragDealer = null,
pickmenuBorder = angular.element(document.getElementById("pickmenuBorder")),
navBtn = null;
$scope.requestState = REQUEST_STATE.INIT;
$scope.request = new HailRequest();
Mode.FindAll(new Callback(function() {
console.log(Mode.FindById(Mode.ID.TAXI));
$scope.request.setMode(Mode.FindById(Mode.ID.TAXI));
}));
var updateView = function() {
var navBack = function() {
navBtn = angular.element(document.getElementById("navBtn"));
navBtn.removeClass("ion-navicon");
navBtn.addClass("ion-arrow-left-c");
};
var navMenu = function() {
navBtn = angular.element(document.getElementById("navBtn"));
navBtn.removeClass("ion-arrow-left-c");
navBtn.addClass("ion-navicon");
};
if ($scope.requestState === REQUEST_STATE.INIT) {
mapEngine.navigationInfoWindowLeftText("img/icons/info-hail.png");
mapEngine.navigationInfoWindowRightText("HAIL");
navMenu();
dragDealer.enable();
} else if ($scope.requestState === REQUEST_STATE.HAIL) {
mapEngine.navigationInfoWindowRightText("SET PICKUP");
mapEngine.navigationInfoWindowLeftText("img/icons/info-pickup.png");
navBack();
dragDealer.disable();
} else if ($scope.requestState === REQUEST_STATE.PICKUP) {
mapEngine.navigationInfoWindowRightText("CONFIRM PICKUP");
mapEngine.navigationInfoWindowLeftText("img/icons/info-pickup.png");
pickmenuBorder.css("height", "50%");
navBack();
dragDealer.disable();
} else if ($scope.requestState === REQUEST_STATE.MEETING_POINT) {
mapEngine.navigationInfoWindowRightText("MEETING POINT");
mapEngine.navigationInfoWindowLeftText(null, $scope.request.nearestPoint.distance);
} else if ($scope.requestState === REQUEST_STATE.CONFIRM_MEETING_POINT) {
mapEngine.navigationInfoWindowRightText("CONFIRM");
mapEngine.navigationInfoWindowLeftText("img/icons/info-dropoff.png");
} else if ($scope.requestState === REQUEST_STATE.DROPOFF) {
mapEngine.navigationInfoWindowRightText("CONFIRM DROPOFF");
mapEngine.navigationInfoWindowLeftText("img/icons/info-dropoff.png");
navBack();
pickmenuBorder.css("height", "75%");
dragDealer.disable();
} else if ($scope.requestState === REQUEST_STATE.FARE) {
mapEngine.navigationInfoWindowRightText("WAIT");
navBack();
dragDealer.disable();
}
$scope.$apply();
};
var rebuildSyncedRequest = function() {
if ($stateParams.request !== null) {
$scope.request = $stateParams.request;
if ($scope.request.mode !== null) {
if ($scope.request.mode.id === Mode.ID.SERVISS)
dragDealer.setStep(1);
else if ($scope.request.mode.id === Mode.ID.SERVISS_PLUS)
dragDealer.setStep(2);
else if ($scope.request.mode.id === Mode.ID.TAXI)
dragDealer.setStep(3);
} else {
$scope.request.setMode(Mode.FindById(Mode.ID.SERVISS));
}
if ($scope.request.pickupLocation !== null)
$scope.requestState = REQUEST_STATE.PICKUP;
else if ($scope.request.dropoffLocation !== null)
$scope.requestState = REQUEST_STATE.DROPOFF;
updateView();
}
};
var resetRequest = function() {
if ($scope.request.nearestPointWatch) {
console.log("nearestPointWatch", $scope.request.nearestPointWatch);
$scope.request.nearestPointWatch.stopWatching();
}
mapEngine.gMapsInstance.removePolylines();
$scope.requestState = REQUEST_STATE.INIT;
$scope.request = new HailRequest();
$scope.request.setMode(Mode.FindById(Mode.ID.TAXI));
dragDealer.setStep(3);
mapEngine.getMap().setZoom(14);
updateView();
};
$scope.onResetTapped = resetRequest;
$scope.onNavTapped = function() {
if ($scope.requestState === REQUEST_STATE.INIT)
$ionicSideMenuDelegate.toggleLeft();
else {
resetRequest();
}
};
var onNearbyCarsFound = new Callback(function(nearByCars) {
if (!mapEngine.isReady) return;
mapEngine.gMapsInstance.removeMarkers();
for (var i = 0; i < nearByCars.length; i++) {
var position = Geolocation.ParsePosition(nearByCars[i].car_location);
mapEngine.addMarker(position.lat(), position.lng(), nearByCars[i].image);
}
});
var initModeSelect = function() {
$scope.step = 1;
dragDealer = new Dragdealer('mode-select', {
steps: 3,
loose: true,
tapping: true,
callback: function(x, y) {
$scope.step = dragDealer.getStep()[0];
$scope.request.setMode(Mode.FromDragDealer($scope.step));
User.getInstance().findNearbyCars($scope.request.mode, onNearbyCarsFound);
$scope.$apply();
}
});
dragDealer.reflow();
dragDealer.setStep(3);
Mode.FindAll(new Callback(function() {
User.getInstance().findNearbyCars($scope.request.mode, onNearbyCarsFound);
}));
};
var validateDropoffLocation = function(dropoffLocation) {
if (dropoffLocation === null)
$rootScope.onError.fire(new Error("You can't set a dropoff location more than 10 KM"));
};
var onPlaceChanged = function(place) {
//if has no geomtry do nothing
if (!place || !place.geometry)
return;
//navigate to this place
if (place.geometry.viewport) {
mapEngine.getMap().fitBounds(place.geometry.viewport);
} else {
mapEngine.getMap().setCenter(place.geometry.location);
}
mapEngine.getMap().setZoom(17);
};
$scope.onPickupLocationSelected = function(place) {
if (!place.geometry) {
$scope.request.pickupAddress = "";
} else {
onPlaceChanged(place);
$scope.request.pickupLocation = place.geometry.location;
}
$scope.$apply();
};
$scope.onDropoffLocationSelected = function(place) {
if (!place.geometry) {
$scope.request.dropoffAddress = "";
} else {
onPlaceChanged(place);
$scope.request.dropoffLocation = place.geometry.location;
validateDropoffLocation($scope.request.dropoffLocation);
}
$scope.$apply();
};
var initModesPopovers = function() {
$ionicPopover.fromTemplateUrl('mode.popover.html', {
scope: $scope
}).then(function(popover) {
$scope.openPopover = function(event, step) {
if (!step) step = $scope.step;
popover.show(event);
};
$scope.$on('$destroy', function() {
popover.remove();
});
});
};
initModeSelect();
initModesPopovers();
$scope.onRequestPlusTapped = function() {
if ($scope.request.passengers < $scope.request.mode.maxPassengers)
$scope.request.passengers++;
};
$scope.onRequestMinusTapped = function() {
if ($scope.request.passengers > 1)
$scope.request.passengers--;
};
mapEngine.ready(function() {
var service = new google.maps.places.PlacesService(mapEngine.getMap());
var lebanon = new google.maps.LatLng(33.89, 35.51);
service.textSearch({
location: lebanon,
query: "egnyt",
radius: "50000"
}, function(r, s) {
console.log(r, s);
});
var onDestinationLocationChange = new Callback(function() {
var g = new Geolocation();
$rootScope.onProgress.fire();
var locationLatLng = mapEngine.getCenter();
g.latlngToAddress(locationLatLng, new Callback(function(address) {
console.log(address);
if (address.toUpperCase().indexOf("UNNAMED") > -1)
address = "No street name";
if ($scope.requestState === REQUEST_STATE.HAIL || $scope.requestState === REQUEST_STATE.PICKUP) {
$scope.request.pickupLocation = locationLatLng;
$scope.request.pickupAddress = address;
console.log($scope.request.pickupAddress);
} else if ($scope.requestState === REQUEST_STATE.DROPOFF) {
$scope.request.dropoffAddress = address;
$scope.request.dropoffLocation = locationLatLng;
validateDropoffLocation($scope.request.dropoffLocation);
}
$rootScope.onProgressDone.fire();
$scope.$apply();
}), $rootScope.onError);
});
mapEngine.gMapsInstance.on("dragend", function() {
if ($scope.requestState === REQUEST_STATE.PICKUP || $scope.requestState === REQUEST_STATE.DROPOFF)
onDestinationLocationChange.fire();
});
var onHailRequestPickedup = new Callback(function() {
mapEngine.drawRoute({
origin: [$scope.request.pickupLocation.lat(), $scope.request.pickupLocation.lng()],
destination: [$scope.request.dropoffLocation.lat(), $scope.request.dropoffLocation.lng()],
travelMode: "driving",
strokeColor: "#7EBBFE",
strokeWeight: 7
});
$scope.requestState = REQUEST_STATE.FARE;
updateView();
$scope.request.estimateCost(new Callback(function(cost) {
$scope.confirm = {
title: 'FARE ESTIMATION',
message: Util.String("{0} USD for {1}", [cost, $scope.request.mode.name]),
buttons: {
isSubmit: false,
yes: "CONFIRM",
no: "CANCEL",
promotePositive: true
}
};
$scope.onNoTapped = function() {
fareConfirm.close();
resetRequest();
};
$scope.onYesTapped = function() {
fareConfirm.close();
$scope.onSubmitTapped = function(comment) {
$scope.request.comment = comment;
commentConfirm.close();
$ionicLoading.show({
template: 'Matching you with a Driver now!'
});
$scope.request.make(User.getInstance(), new Callback(function(driver) {
mapEngine.gMapsInstance.off("dragend");
$ionicLoading.hide();
$ionicHistory.clearCache();
$state.go("menu.requestconfirmed", {
request: $scope.request
});
}), new Callback(function(e) {
$rootScope.onError.fire(e);
resetRequest();
}));
};
$scope.confirm = {
message: "Send a Note About Your Location So Driver Can Find You Quicker",
buttons: {
isSubmit: true
},
input: {
data: $scope.request.comment,
placeholder: "I am next to beirut municipality entrance",
isAllowed: true
}
};
$timeout(function() {
commentConfirm = $ionicPopup.confirm({
templateUrl: "templates/confirm.popup.html",
cssClass: "eserviss-confirm text-center",
scope: $scope
});
}, 500);
};
fareConfirm = $ionicPopup.confirm({
templateUrl: "templates/confirm.popup.html",
cssClass: "eserviss-confirm text-center",
scope: $scope
});
}), new Callback(function(e) {
$rootScope.onError.fire(e);
$scope.requestState = REQUEST_STATE.DROPOFF;
updateView();
}));
});
var onLocationEnabled = new Callback(function() {
$scope.myLocationTapped = function() {
User.getInstance().findPosition(new Callback(function(position) {
mapEngine.addUserAccuracy(position.lat(), position.lng(), position.accuracy);
mapEngine.setCenter(position.lat(), position.lng());
}));
};
var g = new Geolocation();
User.getInstance().findPosition(new Callback(function(position) {
mapEngine.addUserAccuracy(position.lat(), position.lng(), position.accuracy);
mapEngine.setCenter(position.lat(), position.lng());
}), $rootScope.onError);
mapEngine.navigationMarker(function() {
});
mapEngine.navigationInfo(function() {
if ($scope.requestState === REQUEST_STATE.INIT) {
$scope.request.inService(new Callback(function() {
onDestinationLocationChange.fire();
$scope.requestState = REQUEST_STATE.PICKUP; //due to ux will compress the hail step to pickup
updateView();
}), $rootScope.onError);
} else if ($scope.requestState === REQUEST_STATE.HAIL) { //deprecated state
$scope.request.inService(new Callback(function() {
onDestinationLocationChange.fire();
$scope.requestState = REQUEST_STATE.PICKUP;
updateView();
}), $rootScope.onError);
} else if ($scope.requestState === REQUEST_STATE.PICKUP) {
$scope.request.inService(new Callback(function() {
$scope.requestState = REQUEST_STATE.DROPOFF;
updateView();
}), $rootScope.onError);
} else if ($scope.requestState === REQUEST_STATE.DROPOFF) {
var validator = new Validator();
if (validator.isNull($scope.request.dropoffLocation, "Please enter dropoff location first")) {
$rootScope.onError.fire(validator.getError());
return;
}
$scope.request.inService(new Callback(function() {
if ($scope.request.mode.id === Mode.ID.SERVISS) {
$scope.request.validateServicePickup(new Callback(function(isNear) {
if (isNear) {
onHailRequestPickedup.fire();
return;
}
$scope.confirm = {
title: 'MEETING POINT',
message: $scope.request.nearestPoint.message,
buttons: {
isSubmit: false,
yes: "ACCEPT",
no: "CHOOSE TAXI",
}
};
$scope.onNoTapped = function() {
meetingPointConfirm.close();
resetRequest();
};
$scope.onYesTapped = function() {
var nearestPointImg = angular.element(document.getElementById("meetingpointImg"));
meetingPointConfirm.close();
$scope.requestState = REQUEST_STATE.MEETING_POINT;
updateView();
$scope.request.nearestPoint.header.line[0] = " START WALKING TOWARDS MEETING POINT NOW";
nearestPointImg.css("vertical-align", "middle");
$scope.request.watchToMeetingPoint(new Callback(function(userPosition) {
mapEngine.drawRoute({
origin: [userPosition.lat(), userPosition.lng()],
destination: [$scope.request.nearestPoint.location.lat(), $scope.request.nearestPoint.location.lng()],
travelMode: "walking",
strokeColor: "#7EBBFE",
strokeWeight: 7
});
mapEngine.setCenter($scope.request.nearestPoint.location.lat(), $scope.request.nearestPoint.location.lng());
}), new Callback(function() {
$scope.request.nearestPoint.header.line[0] = "YOU HAVE REACHED YOUR MEETING POINT!";
$scope.request.nearestPoint.header.line[1] = "PLEASE CONFIRM YOUR RIDE REQUEST";
nearestPointImg.css("vertical-align", "top");
$scope.requestState = REQUEST_STATE.CONFIRM_MEETING_POINT;
updateView();
}), new Callback(function() {
$scope.request.nearestPoint.header.line[0] = "YOU ARE CLOSE TO MEETING POINT";
nearestPointImg.css("vertical-align", "middle");
}, 1), $rootScope.onError);
};
meetingPointConfirm = $ionicPopup.confirm({
templateUrl: "templates/confirm.popup.html",
cssClass: "eserviss-confirm text-center",
scope: $scope
});
}), $rootScope.onError);
} else {
onHailRequestPickedup.fire();
}
}), $rootScope.onError);
} else if ($scope.requestState === REQUEST_STATE.MEETING_POINT) {
$cordovaDialogs.alert("Eserviss is wathcing your position until you reach the meeting point", 'Meeting Point');
} else if ($scope.requestState === REQUEST_STATE.CONFIRM_MEETING_POINT) {
mapEngine.gMapsInstance.removePolylines();
$scope.request.pickupLocation = $scope.request.nearestPoint.location.toLatLng();
var g = new Geolocation();
g.latlngToAddress($scope.request.pickupLocation, new Callback(function(address) {
$scope.request.pickupAddress = address;
$scope.$apply();
}));
onHailRequestPickedup.fire();
}
$scope.$apply();
});
updateView();
rebuildSyncedRequest();
});
$rootScope.ifLocationEnabled(onLocationEnabled);
});
$scope.$on('$destroy', function() {
});
}
]);
controllers.controller('HailRequestController@confirmed', [
'$scope', '$state', '$stateParams', 'mapEngine', 'User', '$rootScope', 'Callback',
'Util', 'Geolocation',
function($scope, $state, $stateParams, mapEngine, User, $rootScope, Callback,
Util, Geolocation) {
'use strict';
var confirmedScrollElem = angular.element(document.getElementById("confirmedScroll")),
infoElem = angular.element(document.getElementById("info")),
geolocation = new Geolocation();
$scope.request = $stateParams.request;
$scope.infoState = 1;
$scope.onCloseTapped = function() {
if ($scope.infoState === 1) { //if driver info shown
confirmedScrollElem.removeClass('slideOutDown');
confirmedScrollElem.removeClass('slideInDown');
confirmedScrollElem.addClass('slideOutDown');
infoElem.css("height", "auto");
$scope.infoState = 0;
} else if ($scope.infoState === 0) { //if driver info hidden
confirmedScrollElem.removeClass('slideOutDown');
confirmedScrollElem.removeClass('slideInDown');
confirmedScrollElem.addClass('slideInDown');
infoElem.css("height", "50%");
$scope.infoState = 1;
}
};
$scope.onContactTapped = function() {
plugins.listpicker.showPicker({
title: "Contact Driver",
items: [{
text: "Send a Message",
value: "MESSAGE"
}, {
text: "Call Driver",
value: "CALL"
}]
}, function(action) {
if (action === 'MESSAGE') {
plugins.socialsharing.shareViaSMS({
message: ''
}, $scope.driver.DriverPhone, null, function() {});
} else if (action === 'CALL') {
plugins.CallNumber.callNumber(function() {}, function(e) {
$rootScope.onError.fire(new Error(e, true, true));
}, $scope.driver.DriverPhone);
}
}, function() {});
};
$scope.onShareEtaTapped = function() {
var POST_MESSAGE = Util.String("Get Eserviss app at http://eserviss.com/app");
var POST_TITLE = "Eserviss";
plugins.socialsharing.share(POST_MESSAGE, POST_TITLE);
};
var initSync = function() {
$scope.request.sync(User.getInstance(), new Callback(function() {
$scope.$apply();
}), $rootScope.onError);
$scope.request.onDroppedoff = new Callback(function() {
geolocation.stopWatching();
$state.go("menu.receipt", {
request: $scope.request
});
});
};
initSync();
var onLocationEnabled = new Callback(function() {
User.getInstance().findPosition(new Callback(function(position) {
//mapEngine.addMarker(position.lat(), position.lng() - 0.005, "img/icons/pin-car.png");
mapEngine.addUserAccuracy(position.lat(), position.lng(), position.accuracy
);
mapEngine.setCenter(position.lat(), position.lng());
}), $rootScope.onError);
mapEngine.drawRoute({
origin: [$scope.request.pickupLocation.lat(), $scope.request.pickupLocation.lng()],
destination: [$scope.request.dropoffLocation.lat(), $scope.request.dropoffLocation.lng()],
travelMode: "driving",
strokeColor: "#7EBBFE",
strokeWeight: 7
});
geolocation.watch(new Callback(function(position) {
mapEngine.addUserAccuracy(position.lat(), position.lng(), position.accuracy);
mapEngine.setCenter(position.lat(), position.lng());
}));
});
mapEngine.ready(function() {
$rootScope.ifLocationEnabled(onLocationEnabled);
});
$scope.$on('$destroy', function() {
geolocation.stopWatching();
});
}
]);
controllers.controller('HailRequestController@receipt', [
'$scope', '$state', '$stateParams', 'Validator', '$rootScope', 'Callback',
'$ionicHistory', 'User', '$cordovaDialogs', '$timeout',
function($scope, $state, $stateParams, Validator, $rootScope, Callback,
$ionicHistory, User, $cordovaDialogs, $timeout) {
'use strict';
$ionicHistory.nextViewOptions({
disableBack: true
});
var today = new Date();
$scope.date = {
day: today.getDate(),
month: today.toDateString().split(' ')[1],
year: today.getFullYear()
};
$scope.request = $stateParams.request;
$scope.receipt = {};
$scope.request.consumeCost(User.getInstance(), new Callback(function() {
$cordovaDialogs.alert("Your trip cost has been charged from your balance", 'Trip Cost');
}), $rootScope.onError);
$scope.onSubmitTapped = function(receipt) {
var validator = new Validator();
if (validator.isEmpty(receipt.rating, "Please insert rating first in your feedback") ||
validator.isEmpty(receipt.comment, "Please insert comment first in your feedback")) {
$rootScope.onError.fire(validator.getError());
return;
}
$scope.request.feedback(User.getInstance(), $scope.receipt.rating, $scope.receipt.comment, new Callback(function() {
$ionicHistory.clearCache();
$timeout(function() {
$state.go("menu.hailrequest", {}, {
reload: true
});
}, 50);
}), $rootScope.onError);
};
}
]);<file_sep>controllers.factory('Util', [
function() {
'use strict';
var Util = augment.defclass({
constructor: function() {
}
});
Util.Alert = function(object) {
var jsonStringified = "";
try {
jsonStringified = JSON.stringify(object);
} catch (e) {
jsonStringified = object;
}
alert(jsonStringified);
};
Util.IsBrowser = function () {
return typeof cordova === "undefined";
};
Util.ToTwoDigits = function(number) {
var baseTwo = number;
if (number < 10 && number > -10) {
baseTwo = "0" + number;
}
return baseTwo;
};
Util.FormatMilliseconds = function(milliseconds) {
var days, hours, minutes, seconds;
seconds = Math.floor(milliseconds / 1000);
minutes = Math.floor(seconds / 60);
seconds = seconds % 60;
hours = Math.floor(minutes / 60);
minutes = minutes % 60;
days = Math.floor(hours / 24);
hours = hours % 24;
return Util.ToTwoDigits(hours) + ":" + Util.ToTwoDigits(minutes) + ":" + Util.ToTwoDigits(seconds);
};
Util.String = function(str, args) {
var regex = new RegExp("{-?[0-9]+}", "g");
return str.replace(regex, function(item) {
var intVal = parseInt(item.substring(1, item.length - 1));
var replace;
if (intVal >= 0) {
replace = args[intVal];
} else if (intVal === -1) {
replace = "{";
} else if (intVal === -2) {
replace = "}";
} else {
replace = "";
}
return replace;
});
};
Util.Find = function(list, isMatched) {
for (var i = 0; i < list.length; i++) {
if (isMatched(list[i]))
return list[i];
}
return null;
};
Util.IsString = function(value) {
return typeof value === 'string';
};
Util.InArray = function(value, list) {
if (list.indexOf(value) === -1)
return false;
return true;
};
Util.PushUnique = function(value, list, isMatched) {
var element = Util.Find(list, isMatched);
if (element != null) {
return;
}
list.push(value);
}
Util.IsArrayLike = function(obj) {
var NODE_TYPE_ELEMENT = 1;
if (obj == null || Util.IsWindow(obj)) {
return false;
}
var length = obj.length;
if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
return true;
}
return Util.IsString(obj) || Array.isArray(obj) || length === 0 ||
typeof length === 'number' && length > 0 && (length - 1) in obj;
}
Util.IsFunction = function(value) {
return typeof value === 'function';
}
Util.IsWindow = function(obj) {
return obj && obj.window === obj;
}
Util.RandomNumber = function(min, max) {
if (!min) min = 0;
if (!max) max = 1000;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Util.ForEach = function(obj, iterator, context) {
var key, length;
if (obj) {
if (Util.IsFunction(obj)) {
for (key in obj) {
// Need to check if hasOwnProperty exists,
// as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (Array.isArray(obj) || Util.IsArrayLike(obj)) {
var isPrimitive = typeof obj !== 'object';
for (key = 0, length = obj.length; key < length; key++) {
if (isPrimitive || key in obj) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (obj.forEach && obj.forEach !== Util.ForEach) {
obj.forEach(iterator, context, obj);
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key, obj);
}
}
}
}
return obj;
};
Util.EndWith = function(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
Util.Base64 = function(type, data) {
return Util.String("data:image/{0};base64,{1}", [type, data]);
};
Util.RandomString = function(length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
};
return Util;
}
]);<file_sep>application.factory('Promotion', [
'Model', 'Http',
function(Model, Http) {
'use strict';
var Promotion = augment(Model, function(parent) {
this.constructor = function(row) {
this._fields = ["name", "description", "image", "cta", "link"];
this._tableName = "Promotion";
this._modelType = Promotion;
parent.constructor.call(this, row);
};
});
Promotion.FindAll = function (user, onSuccess, onError) {
var http = new Http();
http.get({
url: CONFIG.SERVER.URL,
model: Promotion,
params: {
promo: true,
userId: user.id
},
onSuccess: onSuccess,
onFail: onError,
onError: onError
});
};
return Promotion;
}
]);<file_sep>controllers.factory('ImageManager', [
'Error', '$cordovaFileTransfer', 'Util', 'Http', 'Callback',
function(Error, $cordovaFileTransfer, Util, Http, Callback) {
'use strict';
var ImageManager = augment.defclass({
constructor: function() {
this.cameraOptions = {};
this.filePath = null;
if (typeof(cordova) !== "undefined") {
this.cameraOptions = {
destinationType: Camera.DestinationType.FILE_URI,
quality: 60,
correctOrientation: true,
targetWidth: 720
};
}
},
encoded: function() {
this.cameraOptions.destinationType = Camera.DestinationType.DATA_URL;
return this;
},
locationed: function() {
this.cameraOptions.destinationType = Camera.DestinationType.FILE_URI;
return this;
},
fromCamera: function(onSuccess, onError) {
var self = this;
this.cameraOptions.sourceType = Camera.PictureSourceType.CAMERA;
navigator.camera.getPicture(function(r) {
if (self.cameraOptions.destinationType === Camera.DestinationType.FILE_URI)
self.filePath = r;
onSuccess.fire(r);
}, function(e) {
if (onError) onError.fire(e, true, true);
}, this.cameraOptions);
return this;
},
fromGallery: function(onSuccess, onError) {
var self = this;
this.cameraOptions.sourceType = Camera.PictureSourceType.PHOTOLIBRARY;
navigator.camera.getPicture(function(r) {
if (self.cameraOptions.destinationType === Camera.DestinationType.FILE_URI)
self.filePath = r;
onSuccess.fire(r);
}, function(e) {
if (onError) onError.fire(e, true, true);
}, this.cameraOptions);
return this;
},
fileMetadata: function(onSuccess, onError) {
var imageUrl = this.filePath;
var defaultError = new Error("Error happened while getting file data");
window.resolveLocalFileSystemURL(imageUrl, function(fileEntry) {
fileEntry.file(function(fileObj) {
fileObj.isImage = function() {
return fileObj.type.search("image") !== -1;
};
onSuccess.fire(fileObj);
}, function(err) {
$rootScope.onError.fire(defaultError);
});
}, function(err) {
$rootScope.onError.fire(defaultError);
});
},
upload: function(url, onSuccess, onError, others) {
var self = this;
if (this.filePath) {
if (!others.params) others.params = {};
if (ionic.Platform.isAndroid())
url = url.replace("https", "http"); // fix server ssl cert. issue
$cordovaFileTransfer.upload(
url,
self.filePath, {
fileKey: others.key || "image",
fileName: self.filePath.substr(self.filePath.lastIndexOf('/') + 1),
params: others.params
}, true
)
.then(function(result) { //on API call success
var response = null;
try {
response = JSON.parse(result.response);
} catch (e) {
response = result.response;
}
onSuccess.fire(response);
}, function(err) { // on error happens on API call
var e = null;
//check what error happens
switch (err.code) {
//if file (profile picture) is invalid
case FileTransferError.FILE_NOT_FOUND_ERR:
case FileTransferError.INVALID_URL_ERR:
e = new Error("Invalid file, Please reselect profile picture");
break;
//if there is connection error
case FileTransferError.CONNECTION_ERR:
e = new Error("Connection error, Please check your internet connection");
break;
//if user aborted profile picture upload
case FileTransferError.ABORT_ERR:
e = new Error("User signup aborted");
break;
//if other error happened
default:
e = new Error("Unknown error happened while connecting to server, please try again");
break;
}
//handle error showing to user
if (onError) onError.fire(e);
}, function(progress) {});
} else {
var http = new Http();
http.isLoading = false;
http.post({
url: url,
params: others.params,
onSuccess: onSuccess,
onFail: new Callback(function(e) {
onError.fire(e);
}),
onError: onError
});
}
},
thumbnail: function(width, height, onSuccess, onError, others) {
var options = {
uri: this.filePath,
folderName: others.folder || "Tmp",
quality: others.quality || 75,
width: width,
height: height
};
window.ImageResizer.resize(options,
function(image) {
onSuccess.fire(image);
}, function() {
onError.fire(new Error("Error happened while making image thumbnail"));
});
}
});
return ImageManager;
}
]);<file_sep>controllers.factory('Model', [
'$ionicPlatform', 'DatabaseConnector', 'Util', '$timeout',
function($ionicPlatform, DatabaseConnector, Util, $timeout) {
'use strict';
var Model = augment.defclass({
constructor: function(row) {
this.id = row && row.id ? row.id : null;
if (this._tableName !== null) {
this._dbConnector = new DatabaseConnector(this._tableName);
}
Util.ForEach(row, function(value, key) {
if (Util.InArray(key, this._fields))
this[key] = value;
}, this);
this._bindMethods();
},
_bindMethods: function() {
var self = this;
this._modelType.Find = function() {
self._dbConnector.selectFirst({
model: self._modelType,
conditions: {
"id": self.id
},
onSuccess: onSuccess,
onFail: onError
});
}
},
getPrimaryKey: function() {
return this.id;
},
setPrimaryKey: function(id) {
this.id = id;
},
delete: function(onSuccess, onFail) {
this._dbConnector.deleteById(this.getPrimaryKey(), onSuccess, onFail);
return this;
},
update: function(onSuccess, onFail) {
this._dbConnector.updateById(this.getPrimaryKey(), this.toJson(), onSuccess, onFail);
return this;
},
save: function(onSuccess, onFail) {
if (this.id) {
this.update(onSuccess, onFail);
} else {
this._dbConnector.insert(this._modelType, this.toJson(), onSuccess, onFail);
}
return this;
},
toString: function() {
return this.id;
},
toJson: function() {
var json = {
id: this.id
};
Util.ForEach(this, function(value, key) {
if (Util.InArray(key, this._fields))
json[key] = value;
}, this);
return json;
},
toArray: function() {
var fields = [];
Util.ForEach(this, function(value, key) {
if (Util.InArray(key, this._fields))
fields.push(value);
}, this);
return fields;
},
toList: function() {
var json = {};
Util.ForEach(this, function(value, key) {
if (Util.InArray(key, this._fields) && !Util.InArray(key, this._hidden))
json[key] = value;
}, this);
return json;
}
});
Model.Find = function(model, params, order, onSuccess, onError) {
var tmp = new model();
var tableName = tmp._tableName;
var dbConnector = new DatabaseConnector(tableName);
if (Array.isArray(params)) {
dbConnector.select({
model: model,
order: order,
conditions: params,
onSuccess: onSuccess,
onFail: onError
});
} else {
dbConnector.selectFirst({
model: model,
order: order,
conditions: [
["id", "=", params]
],
onSuccess: onSuccess,
onFail: onError
});
}
}
return Model;
}
]);<file_sep>application.factory('Mode', [
'Model', 'Util', 'Http', 'Callback',
function(Model, Util, Http, Callback) {
'use strict';
var Mode = augment(Model, function(parent) {
this.constructor = function(row) {
this._fields = ["mode", "name", "allowed_passengers", "maxPassengers", "minFare", "cancelationFee", "etaTime", "trip_icon", "hail_title", "type_id", "trip_icon", "noservice"];
this._tableName = "Mode";
this._modelType = Mode;
parent.constructor.call(this, row);
this.id = this.type_id;
this.maxPassengers = this.allowed_passengers;
this.icon = this.trip_icon;
this.name = this.mode;
console.log(this.icon);
};
this.getDragDealerStep = function() {
for (var i = 0; i < Mode.All.length; i++) {
if (Mode.All[i].id == this.id)
return (i+1);
};
};
this.isTaxi = function () {
return this.id == Mode.ID.TAXI;
};
this.isService = function () {
return this.id == Mode.ID.SERVISS;
};
this.isServicePlus = function () {
return this.id == Mode.ID.SERVISS_PLUS;
};
this.isFree = function () {
return this.id == Mode.ID.FREE;
}
this.eta = function (onSuccess, onError) {
var self = this;
var http = new Http();
http.isLoading = false;
http.get({
url: CONFIG.SERVER.URL,
params: {
eta_estimation: true,
tripTypeId: this.id
},
onSuccess: new Callback(function (r) {
if (self.isTaxi())
self.etaTime = r.taxi;
else if (self.isService())
self.etaTime = r.service;
else if (self.isServicePlus())
self.etaTime = r.serviceplus;
if (onSuccess) onSuccess.fire(r);
}),
onFail: onError,
onError: onError
});
}
});
Mode.ID = {
TAXI: 1,
SERVISS: 2,
SERVISS_PLUS: 3,
FREE: 4
};
Mode.All = [];
Mode.FindAll = function (onSuccess, onError) {
if (Mode.All.length > 0) {
if (onSuccess) onSuccess.fire(Mode.All);
return;
}
var http = new Http();
http.isLoading = false;
http.get({
url: CONFIG.SERVER.URL,
model: Mode,
params: {
modes_fare: true
},
onSuccess: new Callback(function (modes) {
console.log(modes);
Mode.All = modes;
if (onSuccess) onSuccess.fire(Mode.All);
}),
onError: onError
});
};
Mode.FindById = function(id) {
if (Mode.All === null)
return null;
return Util.Find(Mode.All, function(mode) {
return mode.id == id;
});
};
Mode.FromDragDealer = function (stepId) {
if (!Mode.All) return null;
return Mode.All[stepId - 1];
};
return Mode;
}
]);<file_sep>'use strict'
controllers.factory('Validator', [
'Error', 'Util',
function(Error, Util) {
var Validator = augment.defclass({
constructor: function() {
this._error = new Error();
this._blockMessage = '';
this._isPassed = true;
},
_validate: function(isValid, errorMessage, inputId) {
inputId = !inputId ? null : inputId;
var isValidFlag = false;
if (isValid())
isValidFlag = true;
this._isPassed = this._isPassed && !isValidFlag;
if (errorMessage != null && isValidFlag) {
this._error.show(errorMessage);
this._blockMessage = this._blockMessage.length === 0 ? errorMessage : this._blockMessage + ' and ' + errorMessage;
}
if (inputId !== null) {
var inputElem = angular.element(document.getElementById(inputId));
if (isValidFlag) {
inputElem.addClass('input-error');
} else {
inputElem.removeClass('input-error');
}
}
return isValidFlag;
},
isEmpty: function(value, errorMessage, inputId) {
return this._validate(function() {
return !value || value.length == 0;
}, errorMessage, inputId);
},
isNull: function(value, errorMessage, inputId) {
return this._validate(function() {
return value == null;
}, errorMessage, inputId);
},
isNotEmail: function(value, errorMessage, inputId) {
return this._validate(function() {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return !re.test(value);
}, errorMessage, inputId);
},
isNotNumber: function(value, errorMessage, inputId) {
return this._validate(function() {
return !value || isNaN(value);
}, errorMessage, inputId);
},
isIn: function(values, isMatched, errorMessage, inputId) {
return this._validate(function() {
return Util.Find(values, isMatched) != null;
}, errorMessage, inputId);
},
getError: function() {
return this._error;
},
getErrorBlock: function() {
var error = new Error();
console.log(this._blockMessage);
error.show(this._blockMessage);
return error;
},
isPassed: function () {
return this._isPassed;
}
});
return Validator;
}
]);<file_sep>application.factory('SyncTrip', [
'Model', 'Mode', 'Driver',
function(Model, Mode, Driver) {
'use strict';
var SyncTrip = augment(Model, function(parent) {
this.constructor = function(row) {
this._fields = ["user_id", "car_id", "ride_id", "driver_id", "hail", "response", "arrived", "pickup", "dropoff", "cancel", "noservice", "pickup_address", "dropoff_address", "pickup_location", "dropoff_location", "passengers", "fare", "paid", "payment_method", "trip_mode", "cancel_by_driver"];
this._tableName = "SyncTrip";
this._modelType = SyncTrip;
parent.constructor.call(this, row);
this.passengers = parseInt(this.passengers);
this.trip_mode = parseInt(this.trip_mode);
this.passengers = this.passengers === 0 ? 1 : this.passengers;
this.mode = this.trip_mode > 0 ? Mode.FindById(this.trip_mode) : null;
this.driver = new Driver(row.driver);
this.pickupLocation = null;
this.dropoffLocation = null;
var self = this;
if (this.pickup_location.trim().length !== 0 && this.pickup_location.split(',').length === 2) {
this.pickupLocation = {
lat: function () {
return self.pickup_location.split(',')[0];
},
lng: function () {
return self.pickup_location.split(',')[1];
}
};
}
if (this.dropoff_location.trim().length !== 0 && this.dropoff_location.split(',').length === 2) {
this.dropoffLocation = {
lat: function () {
return self.dropoff_location.split(',')[0];
},
lng: function () {
return self.dropoff_location.split(',')[1];
}
};
}
};
});
return SyncTrip;
}
]);<file_sep>'use strict'
controllers.factory('Callback', [
'$interval',
function($interval) {
var Callback = augment.defclass({
constructor: function(method, maxCalls) {
this._method = method || null;
this._maxCalls = maxCalls || Callback.Calls.MAX;
this._callsCounter = 0;
},
fire: function(param1, param2, param3, param4, param5) {
if (this._method && this.isCallable()) {
Callback.Fire(this._method, param1, param2, param3, param4, param5);
this._callsCounter++;
}
return this;
},
isFired: function() {
return this._callsCounter > 0;
},
waitFiredOnce: function() {
while (!this.isFired());
},
isCallable: function() {
if (this._maxCalls == Callback.Calls.MAX)
return true;
return this._callsCounter < this._maxCalls;
},
setExtras: function(extras) {
this._extras = extras;
return this;
},
getExtras: function() {
return this._extras;
}
});
Callback.Fire = function(method, param1, param2, param3, param4, param5) {
if (method != null) {
if (param5)
method(param1, param2, param3, param4, param5);
else if (param4)
method(param1, param2, param3, param4);
else if (param3)
method(param1, param2, param3);
else if (param2)
method(param1, param2);
else if (param1)
method(param1);
else
method();
}
}
Callback.WaitAll = function(callBacks, onSuccess) {
var callsNumber;
var interval = $interval(function() {
callsNumber = 0;
for (var i = 0; i < callBacks.length; i++) {
if ( callBacks[i].isFired() )
callsNumber++;
}
if (callsNumber == callBacks.length) {
$interval.cancel(interval);
onSuccess.fire();
}
}, 100);
};
Callback.Calls = {
MAX: -1
}
return Callback;
}
]);<file_sep>application.factory('Settings', [
'Model', 'Http', 'Callback',
function(Model, Http, Callback) {
'use strict';
var Settings = augment(Model, function(parent) {
this.constructor = function(row) {
this._fields = ["provider_timeout", "server_rate", "server_mode", "server_email", "e_number", "e_email", "nearby_thread", "nearby_pin", "nearby_rate", "drag_thread"];
this._tableName = "Settings";
this._modelType = Settings;
parent.constructor.call(this, row);
}
});
Settings.SharedInstance = null;
Settings.getInstance = function() {
if (Settings.SharedInstance === null)
Settings.SharedInstance = new Settings();
return Settings.SharedInstance;
}
Settings.Download = function(onSuccess) {
var onSettingsNotFound = new Callback(function () {
Settings.SharedInstance = new Settings({server_rate: 10000});
onSuccess.fire(Settings.SharedInstance);
});
var http = new Http();
http.get({
url: CONFIG.SERVER.URL,
model: Settings,
params: {
start: true
},
onSuccess: new Callback(function(settings) {
Settings.SharedInstance = settings;
onSuccess.fire(settings);
}),
onFail: onSettingsNotFound,
onError: onSettingsNotFound
});
};
return Settings;
}
]);<file_sep>application.factory('HailRequest', [
'Model', 'Http', 'Error', 'Callback', 'Settings',
'Driver', 'Util', 'SyncTrip', 'Mode', '$timeout',
'Geolocation',
function(Model, Http, Error, Callback, Settings,
Driver, Util, SyncTrip, Mode, $timeout,
Geolocation) {
'use strict';
var HailRequest = augment(Model, function(parent) {
this.constructor = function(row) {
this._fields = ["ride_id", "hail", "response", "arrived", "pickup", "dropoff", "cancel", "noservice", "pickup_address", "dropoff_address", "pickup_location", "dropoff_location", "passengers", "fare", "paid", "payment_method", "trip_mode", "driver", "driver_dropoff_address", "driver_dropoff_location"];
this._tableName = "HailRequest";
this._modelType = HailRequest;
parent.constructor.call(this, row);
this.pickupLocation = this.pickup_location ? Geolocation.ParsePosition(this.pickup_location) : null;
this.pickupAddress = this.pickup_address ? this.pickup_address : null;
this.dropoffAddress = this.dropoff_address ? this.dropoff_address : null;
this.dropoffLocation = this.dropoff_location ? Geolocation.ParsePosition(this.dropoff_location) : null;
this.mode = this.trip_mode ? Mode.FindById(parseInt(this.trip_mode)) : null;
this.passengers = this.passengers ? this.passengers : 1;
this.pingInterval = null;
this.rideId = this.ride_id ? this.ride_id : null;
this.comment = null;
this.driver = this.driver ? new Driver(this.driver) : new Driver(); //assigned driver
this.pingActions = [];
this.status = null;
this.onDroppedoff = null;
this.totalCost = 0;
this.driverTimeout = null;
this.isPingable = true;
this.isSyncable = true;
this.nearestPoint = {};
this.nearestPointWatch = null;
this.stage = null;
this.onEtaArrival = null;
this.etaArriaval = null;
this.pingActionIndex = null;
};
this.getDropoffLocation = function() {
return Geolocation.ParsePosition("30.2,31.4");
var dropoffLocation = null;
if (this.dropoff_location.length <= 1 || this.driver_dropoff_location.length <= 1)
return null;
dropoffLocation = this.dropoff_location.length > 1 ? Geolocation.ParsePosition(this.dropoff_location) : null;
if (!dropoffLocation)
dropoffLocation = this.driver_dropoff_location.length > 1 ? Geolocation.ParsePosition(this.driver_dropoff_location) : null;
return dropoffLocation;
};
this.getDropoffAddress = function() {
if (!this.dropoff_address || !this.driver_dropoff_address)
return null;
if (this.dropoff_address.toUpperCase().search("NOT SET") !== -1)
return this.dropoff_address;
if (this.driver_dropoff_address.toUpperCase().search("NOT SET") !== -1)
return this.driver_dropoff_address;
return null;
};
this.estimateCost = function(onSuccess, onError) {
var self = this;
var makeEstimateRequest = function() {
var http = new Http();
http.get({
url: CONFIG.SERVER.URL,
params: {
fare: true,
pickupLat: self.pickupLocation.lat(),
pickupLng: self.pickupLocation.lng(),
dropoffLat: self.dropoffLocation.lat(),
dropoffLng: self.dropoffLocation.lng(),
modeId: self.mode.id
},
onSuccess: new Callback(function(cost) {
self.totalCost = cost * self.passengers;
if (onSuccess) onSuccess.fire(self.totalCost);
}),
onFail: onError,
onError: onError
});
};
if (this.mode.id === Mode.ID.SERVISS) {
makeEstimateRequest();
} else {
var http = new Http();
http.isLoading = false;
http.get({
url: CONFIG.SERVER.URL,
params: {
trip_validate: true,
trip_type: this.mode.id,
lat1: this.pickupLocation.lat(),
long1: this.pickupLocation.lng(),
lat2: this.dropoffLocation.lat(),
long2: this.dropoffLocation.lng(),
address1: this.pickupAddress,
address2: this.dropoffAddress
},
onSuccess: new Callback(function() {
makeEstimateRequest();
}),
onFail: onError,
onError: onError
});
}
};
this.consumeCost = function(user, onSuccess, onError) {
var self = this;
//user.subtractCredit(this.totalCost, onSuccess, onError);
var http = new Http();
http.get({
url: CONFIG.SERVER.URL,
params: {
ride_payment: true,
userId: user.id,
rideId: this.rideId
},
onSuccess: new Callback(function(m, s, r, data) {
self.totalCost = data.fee;
onSuccess.fire();
}),
onFail: new Callback(function(e, s, r, data) {
self.totalCost = data.fee;
onError.fire(e);
}),
onError: onError
});
};
this.ping = function(user, onSuccess, onError, onFail) {
if (this.pingActionIndex) {
this.isPingable = true;
return;
}
var self = this;
var http = new Http();
http.isLoading = false;
var sendPingData = function() {
if (!self.isPingable)
return;
http.get({
url: CONFIG.SERVER.URL,
model: Driver,
params: {
ping: true,
userId: user.id
},
onSuccess: new Callback(function(driver) {
self.isPingable = false;
if (self.driverTimeout) $timeout.cancel(self.driverTimeout);
self.driver = driver;
onSuccess.fire(driver);
}),
onFail: new Callback(function(e) {
self.isPingable = false;
onError.fire(e);
if (onFail) onFail.fire(e);
}),
onError: onError
});
};
var pingIndex = user.pingActions.push(sendPingData);
this.pingActionIndex = pingIndex - 1;
};
this.sync = function(user, onSuccess, onError) {
var self = this;
self.isSyncable = true;
var http = new Http();
http.isLoading = false;
var makeSync = function() {
if (!self.isSyncable)
return;
http.get({
url: CONFIG.SERVER.URL,
model: SyncTrip,
params: {
sync: true,
userId: user.id
},
onSuccess: new Callback(function(sync) {
if (!sync) return;
if (sync.cancel_by_driver.trim().length !== 0) {
self.status = "RIDE IS CANCELED";
self.isSyncable = false;
self.stage = HailRequest.STAGE.CANCEL;
if (self.onDriverCanceled) self.onDriverCanceled.fire();
} else if (sync.cancel.trim().length !== 0) {
self.status = "RIDE IS CANCELED";
self.isSyncable = false;
self.stage = HailRequest.STAGE.CANCEL;
} else if (sync.dropoff.trim().length !== 0) {
self.status = "THANKS FOR USING ESERVISS";
self.isSyncable = false;
self.stage = HailRequest.STAGE.DROPOFF;
self.fare = sync.fare;
console.log(sync, sync.fare);
if (self.onDroppedoff) self.onDroppedoff.fire();
} else if (sync.pickup.trim().length !== 0) {
self.stage = HailRequest.STAGE.PICKUP;
self.status = Util.String("YOU HAVE BEEN PICKED UP", [sync.mode.name.toUpperCase()]);
} else if (sync.arrived.trim().length !== 0) {
self.stage = HailRequest.STAGE.ARRIVED;
self.status = Util.String("YOUR RIDE HAS ARRIVED", [sync.mode.name.toUpperCase()]);
} else if (sync.response.trim().length !== 0) {
self.stage = HailRequest.STAGE.RESPONSE;
self.status = Util.String("DRIVER IS COMING", [sync.mode.name.toUpperCase()]);
}
onSuccess.fire(sync);
}),
onFail: null,
onError: onError
});
var makeEtaArrivalRequest = function() {
if (user.position && user.position.lat() && user.position.lng()) {
http.get({
url: CONFIG.SERVER.URL,
params: {
eta_arrival: true,
car_id: self.driver.CarId,
lat: user.position.lat(),
"long": user.position.lng(),
},
onSuccess: new Callback(function(arrival) {
self.etaArrival = arrival;
if (self.onEtaArrival) self.onEtaArrival.fire(arrival);
}),
onFail: null,
onError: null
});
}
};
makeEtaArrivalRequest();
};
makeSync();
user.pingActions.push(makeSync);
};
this.findFare = function(user, onSuccess, onError) {
var self = this;
var MAX_REQUESTS = 5;
var requestsCounter = 0;
var findFareRequest = function() {
requestsCounter++;
var http = new Http();
http.isLoading = false;
http.get({
url: CONFIG.SERVER.URL,
model: SyncTrip,
params: {
sync: true,
userId: user.id
},
onSuccess: new Callback(function(sync) {
if (sync.fare.trim().length === 0 && requestsCounter < MAX_REQUESTS) {
$timeout(findFareRequest, 1000);
return;
} else if (requestsCounter >= MAX_REQUESTS) {
onError.fire(new Error("Can't get fare now"));
return;
}
self.fare = parseFloat(sync.fare);
onSuccess.fire();
}),
onError: onError,
onFail: onError
});
};
$timeout(findFareRequest, 1000);
}
this.make = function(user, onSuccess, onError) {
var self = this;
var isLocked = localStorage.getItem(HailRequest.HAIL_LOCK);
if (isLocked) {
onError.fire(new Error("Please close eserviss and reopen it again."));
return;
}
var requestDriverTimeout = function(settings) {
var http = new Http();
http.isLoading = false;
http.get({
url: CONFIG.SERVER.URL,
model: Settings,
params: {
driver_timeout: true,
rideID: self.rideId,
userID: user.id
},
onSuccess: new Callback(function(settings) {
$timeout(function() {
requestDriverTimeout(settings);
}, settings.provider_timeout * 1000);
}),
onFail: new Callback(function(e) {
self.isPingable = false;
onError.fire(e);
}),
onError: onError
});
};
var initDriverTimeout = function() {
var http = new Http();
http.isLoading = false;
http.get({
url: CONFIG.SERVER.URL,
model: Settings,
params: {
start: true
},
onSuccess: new Callback(function(settings) {
$timeout(function() {
requestDriverTimeout(settings);
}, settings.provider_timeout * 1000);
}),
onError: onError
});
};
var find = function() {
var http = new Http();
http.timeout = null;
http.isLoading = false;
http.get({
url: CONFIG.SERVER.URL,
params: {
find: true,
userId: user.id,
currentLat: self.pickupLocation.lat(),
currentLng: self.pickupLocation.lng(),
destinationLat: self.dropoffLocation ? self.dropoffLocation.lat() : null,
destinationLng: self.dropoffLocation ? self.dropoffLocation.lng() : null,
tripType: self.mode.id,
passengers: self.passengers
},
onSuccess: new Callback(function() {
self.isPingable = true;
self.ping(user, onSuccess, onError, new Callback(function() {
localStorage.removeItem(HailRequest.HAIL_LOCK);
}));
// initDriverTimeout();
}),
onFail: null
,
onError: null
});
};
var makeUserRequest = function() {
var http = new Http();
http.isLoading = false;
http.get({
url: CONFIG.SERVER.URL,
params: {
user: true,
user_id: user.id,
trip_type: self.mode.id,
passengers: self.passengers,
lat1: self.pickupLocation.lat(),
long1: self.pickupLocation.lng(),
lat2: self.dropoffLocation ? self.dropoffLocation.lat() : null,
long2: self.dropoffLocation ? self.dropoffLocation.lng() : null,
address1: self.pickupAddress,
address2: self.dropoffAddress ? self.dropoffAddress : null,
comment: self.comment
},
onSuccess: new Callback(function(rideId) {
self.rideId = rideId;
localStorage.setItem(HailRequest.HAIL_LOCK, rideId);
find();
}),
onFail: onError,
onError: onError
});
};
makeUserRequest();
};
this.feedback = function(user, rating, comment, onSuccess, onError) {
var self = this;
var http = new Http();
http.get({
url: CONFIG.SERVER.URL,
params: {
'insert-feedback': true,
rideId: this.rideId,
userId: user.id,
driverId: this.driver.id,
comment: comment,
rate: rating
},
onSuccess: onSuccess,
onFail: onError,
onError: onError
});
};
this.cancelRide = function(reason, onSuccess, onError) {
var self = this;
var http = new Http();
http.get({
url: CONFIG.SERVER.URL,
params: {
'cancel': true,
rideId: this.rideId,
comment: reason
},
onSuccess: onSuccess,
onFail: onError,
onError: onError
});
};
this.setMode = function(mode) {
if (mode === null)
return;
this.mode = mode;
if (this.passengers > mode.maxPassengers)
this.passengers = mode.maxPassengers;
};
this.validateServicePickup = function(onSuccess, onError) {
var self = this;
if (!this.mode || this.mode.id !== Mode.ID.SERVISS) {
onSuccess.fire(true);
return;
}
var http = new Http();
http.get({
url: CONFIG.SERVER.URL,
params: {
'validate-service-pickup': true,
pickupLat: this.pickupLocation.lat(),
pickupLng: this.pickupLocation.lng()
},
onSuccess: new Callback(function(r) {
self.nearestPoint.location = Geolocation.ParsePosition(r.location);
self.nearestPoint.distance = r.distance;
self.nearestPoint.message = r.safe ? r.safe : "Meeting point with service is near";
self.nearestPoint.header = {
line: []
};
onSuccess.fire(false);
}),
onFail: onError,
onError: onError
});
};
this.watchToMeetingPoint = function(onProgress, onMinDistance, onNearDistance, onError) {
var self = this;
if (this.nearestPointWatch) this.nearestPointWatch.stopWatching();
var MIN_DISTANCE = 10;
var NEAR_DISTANCE = 100;
this.nearestPointWatch = new Geolocation();
this.nearestPointWatch.watch(new Callback(function(position) {
onProgress.fire(position);
var minDistance = MIN_DISTANCE + position.accuracy;
minDistance = minDistance > 50 ? 50 : minDistance;
var nearDistance = NEAR_DISTANCE + position.accuracy;
nearDistance = nearDistance > 150 ? 150 : nearDistance;
var distance = position.calculateDistance(self.nearestPoint.location);
if (distance <= nearDistance) {
console.log("nearDistance", nearDistance);
onNearDistance.fire();
}
if (distance <= minDistance) {
self.nearestPointWatch.stopWatching();
onMinDistance.fire();
}
}), onError);
};
this.inService = function(onSuccess, onError) {
var self = this;
var http = new Http();
http.get({
url: CONFIG.SERVER.URL,
params: {
available_cars: true,
trip_type: this.mode.id
},
onSuccess: onSuccess,
onFail: new Callback(function(e) {
if (self.mode.noservice && self.mode.noservice.length > 0) onError.fire(new Error(self.mode.noservice));
else onError.fire(e);
}),
onError: onError
});
};
});
HailRequest.EstimateCost = function(modeId, pickupLocation, dropoffLocation, onSuccess, onError) {
var http = new Http();
http.get({
url: CONFIG.SERVER.URL,
params: {
fare: true,
pickupLat: pickupLocation.lat(),
pickupLng: pickupLocation.lng(),
dropoffLat: dropoffLocation ? dropoffLocation.lat() : null,
dropoffLng: dropoffLocation ? dropoffLocation.lng() : null,
modeId: modeId
},
onSuccess: onSuccess,
onFail: onError,
onError: onError
});
};
HailRequest.HAIL_LOCK = "ESERVISS.HAIL_LOCK";
HailRequest.STAGE = {
HAIL: "HAIL",
RESPONSE: "RESPONSE",
ARRIVED: "ARRIVED",
PICKUP: "PICKUP",
DROPOFF: "DROPOFF",
CANCEL: "CANCEL",
NO_SERVICE: "NO_SERVICE"
};
return HailRequest;
}
]);
<file_sep>controllers.controller('HailRequestController@request', [
'$scope', '$state', '$stateParams', 'mapEngine', '$rootScope', 'Callback', 'User',
'Geolocation', '$timeout', '$ionicPopup', 'HailRequest', 'Mode', 'Util', '$ionicLoading',
'$ionicPopover', '$ionicHistory', 'Validator', '$ionicSideMenuDelegate', '$cordovaDialogs',
'Http', 'Settings',
function($scope, $state, $stateParams, mapEngine, $rootScope, Callback, User,
Geolocation, $timeout, $ionicPopup, HailRequest, Mode, Util, $ionicLoading,
$ionicPopover, $ionicHistory, Validator, $ionicSideMenuDelegate, $cordovaDialogs,
Http, Settings) {
'use strict';
//states of the request
var REQUEST_STATE = {
INIT: 0, //initial
HAIL: 1, //will do a hail can choose between modes
REQUEST_CAB: 1.5, //requesting a taxi cab
FARE_ESTIMATION: 1.75, //doing fare estimation
PICKUP: 2, //setting pickup location
DROPOFF: 3, //setting dropoff location
MEETING_POINT: 3.5, //going to meeting point
CONFIRM_MEETING_POINT: 3.75, //confirm meeting point
FARE: 4 //final fare is being displayed to user
};
$scope.REQUEST_STATE = REQUEST_STATE;
var fareConfirm = null, //fare confirm popup
commentConfirm = null, //comment popup
meetingPointConfirm = null, //meeting point confirm popup
dragDealer = null, //drag dealer object
pickmenuBorder = angular.element(document.getElementById("pickmenuBorder")), //pickmenu border
navBtn = null, // nav button to switch icon
adsPopup = null; //ads popup
//init request
$scope.requestState = REQUEST_STATE.INIT;
//current request being built
$scope.request = new HailRequest();
//input binded from the view
$scope.input = {};
/**
* open comment popup: user enters his comment of his request
*/
var openCommentPopup = function() {
/**
* on submit button tapped in comment popup
* @param {String} comment taken from user
*/
$scope.onSubmitTapped = function(comment) {
var loadingUpdateTimeout = null;
$scope.request.comment = comment;
commentConfirm.close();
//show loading info to user
$ionicLoading.show({
template: 'Matching you with a driver now...'
});
//after 30 secs show to user that we are still searching
loadingUpdateTimeout = $timeout(function() {
$ionicLoading.show({
template: 'Search for more cars...'
});
}, 30000);
//make the request
$scope.request.make(User.getInstance(), new Callback(function(driver) {
//i got the driver accepted me
if (loadingUpdateTimeout) {
$timeout.cancel(loadingUpdateTimeout);
loadingUpdateTimeout = null;
}
//hide the loading and go to request confirmed page
$ionicLoading.hide();
$ionicHistory.nextViewOptions({
disableBack: true
});
$ionicHistory.clearCache();
$state.go("menu.requestconfirmed", {
request: $scope.request
});
}), new Callback(function(e) {
//there is no drivers available to accept me
if (loadingUpdateTimeout) {
$timeout.cancel(loadingUpdateTimeout);
loadingUpdateTimeout = null;
}
$ionicLoading.hide();
$rootScope.onError.fire(e);
}));
};
/**
* on close button tapped
*/
$scope.onCloseTapped = function() {
//if in taxi mode enable the user to show fare estimation
if ($scope.request.mode.isTaxi())
$scope.requestState = REQUEST_STATE.FARE_ESTIMATION;
else
$scope.requestState = REQUEST_STATE.REQUEST_CAB;
updateView();
commentConfirm.close();
};
//the confirm message shown to user to enter a node about location
$scope.confirm = {
message: "Send a Note About Your Location So Driver Can Find You Quicker",
buttons: {
isSubmit: true,
submit: "CONFIRM HAIL"
},
input: {
data: $scope.request.comment,
placeholder: "I am next to beirut municipality entrance",
isAllowed: true
}
};
//show in 500ms the confirm popup (fixing a bug of multiple popups showing)
$timeout(function() {
commentConfirm = $ionicPopup.alert({
templateUrl: "templates/confirm.popup.html",
cssClass: "eserviss-confirm text-center",
scope: $scope
});
}, 500);
};
/**
* init ads popup
*/
var initAds = function() {
//if its not already showb
if (!CONFIG.IS_ADS_SHOWN) {
CONFIG.IS_ADS_SHOWN = true;
//get the ads to show
var http = new Http();
http.isLoading = false;
http.get({
url: CONFIG.SERVER.URL,
params: {
ads: true
},
onSuccess: new Callback(function(r) {
//show the popup with the responsone of the ads
var ad = r[0];
$scope.onCloseTapped = function() {
adsPopup.close();
};
var cssClass = "eserviss-alert eserviss-ads text-center";
cssClass = ad.image.length > 0 ? (cssClass + " has-img") : cssClass;
$scope.ad = ad;
adsPopup = $ionicPopup.confirm({
templateUrl: "templates/ads.popup.html",
cssClass: cssClass,
scope: $scope
});
})
});
}
};
/**
* update the view depends on the current state
*/
var updateView = function() {
/**
* set the back icon instead of the menu icon
*/
var navBack = function() {
navBtn = angular.element(document.getElementById("navBtn"));
navBtn.removeClass("ion-navicon");
navBtn.addClass("ion-arrow-left-c");
};
/**
* set the menu icon instead of the back icon
*/
var navMenu = function() {
navBtn = angular.element(document.getElementById("navBtn"));
navBtn.removeClass("ion-arrow-left-c");
navBtn.addClass("ion-navicon");
};
//if dreag dealer set set the initial step of the mode
if (dragDealer) {
//if request mode is already set
if ($scope.request.mode) {
dragDealer.setStep($scope.request.mode.getDragDealerStep());
var modeActiveIconElem = angular.element(document.getElementById("mode-active-icon"));
modeActiveIconElem.attr("src", $scope.request.mode.icon);
} else {
//set the initial step to the last mode
dragDealer.setStep(Mode.All.length);
}
}
//if navigation info window is set and drag dealer
if (mapEngine.navigationInfoWindow && dragDealer) {
//if nearby cars thread is set to NO, then put the nearby pin icon instead of time
if (Settings.getInstance().nearby_thread.toUpperCase() === "NO" && Settings.getInstance().nearby_pin) {
mapEngine.navigationInfoWindowLeftText(Settings.getInstance().nearby_pin);
}
//if init state
if ($scope.requestState === REQUEST_STATE.INIT) {
//set nearby pin if set or set hail icon
if (Settings.getInstance().nearby_pin) {
mapEngine.navigationInfoWindowLeftText(Settings.getInstance().nearby_pin);
} else {
mapEngine.navigationInfoWindowLeftText("img/icons/info-hail.png");
}
//set text to HAIL
mapEngine.navigationInfoWindowRightText("HAIL");
//init nav to menu
navMenu();
//enable drag dealer to select a mode
dragDealer.enable();
} else if ($scope.requestState === REQUEST_STATE.HAIL) { // if in hail state
//ask user to set pickup
mapEngine.navigationInfoWindowRightText("SET PICKUP");
mapEngine.navigationInfoWindowLeftText("img/icons/info-pickup.png");
//init nav to have back icon
navBack();
dragDealer.disable();
} else if ($scope.requestState === REQUEST_STATE.PICKUP) { // if in pickup state
//set text of nav to confirm pickup
mapEngine.navigationInfoWindowRightText("CONFIRM PICKUP");
//set icon
mapEngine.navigationInfoWindowLeftText("img/icons/info-pickup.png");
//set border height to go behind the icon in the input
pickmenuBorder.css("height", "50%");
//set the back nav
navBack();
//keep drag dealer disabled
dragDealer.disable();
} else if ($scope.requestState === REQUEST_STATE.REQUEST_CAB) { // if in request cab state
//set the nav info title
mapEngine.navigationInfoWindowRightText("REQUEST CAB");
//keep it back nav
navBack();
//keep drag dealder disabled
dragDealer.disable();
} else if ($scope.requestState === REQUEST_STATE.MEETING_POINT) { // if in meeting point state
mapEngine.navigationInfoWindowRightText("MEETING POINT");
mapEngine.navigationInfoWindowLeftText(null, $scope.request.nearestPoint.distance);
/*mapEngine.getMap().setZoom(16);*/
} else if ($scope.requestState === REQUEST_STATE.CONFIRM_MEETING_POINT) { //if in confirm meeting point state
//set the nav text to confirm
mapEngine.navigationInfoWindowRightText("CONFIRM");
mapEngine.navigationInfoWindowLeftText("img/icons/info-dropoff.png");
} else if ($scope.requestState === REQUEST_STATE.DROPOFF) { //if in dropoff state
//set the nav text to confirm dropoff
mapEngine.navigationInfoWindowRightText("CONFIRM DROPOFF");
mapEngine.navigationInfoWindowLeftText("img/icons/info-dropoff.png");
//keep the menu to back icon
navBack();
//keep the border height behind the dropoff input
pickmenuBorder.css("height", "75%");
dragDealer.disable();
} else if ($scope.requestState === REQUEST_STATE.FARE) { // if in fare state
//show wait
mapEngine.navigationInfoWindowRightText("WAIT");
navBack();
dragDealer.disable();
}
}
if (ionic.Platform.isAndroid()) $scope.$apply();
};
//find all modes and bind them to the view
Mode.FindAll(new Callback(function(modes) {
$scope.request.setMode(modes[0]);
updateView();
$scope.modes = modes;
}));
/**
* rebuild synced request
*/
var rebuildSyncedRequest = function() {
//if the synced request is sent in params
if ($stateParams.request !== null) {
//set the current request to the one in params
$scope.request = $stateParams.request;
//if the synced one has no mode set the first mode as deafult one
if ($scope.request.mode === null) {
Mode.FindAll(new Callback(function(modes) {
$scope.request.setMode(modes[0]);
}));
}
//if there is apick a up location is set init with location
if ($scope.request.pickupLocation !== null) {
$scope.input.pickup = $scope.request.pickupPlace;
mapEngine.setCenter($scope.request.pickupLocation.lat(), $scope.request.pickupLocation.lng());
if ($scope.request.mode.isTaxi() || $scope.request.mode.isFree())
$scope.requestState = REQUEST_STATE.REQUEST_CAB;
else
$scope.requestState = REQUEST_STATE.PICKUP;
} else if ($scope.request.dropoffLocation !== null)
$scope.requestState = REQUEST_STATE.DROPOFF;
//update the view
$timeout(updateView, 100);
}
};
/**
* reset the current request
*/
var resetRequest = function() {
//if going to meeting point clear the watch
if ($scope.request.nearestPointWatch) {
$scope.request.nearestPointWatch.stopWatching();
}
//remove any routes drawn
mapEngine.gMapsInstance.removePolylines();
//set back state to init
$scope.requestState = REQUEST_STATE.INIT;
//remove current request
$scope.request = new HailRequest();
//set zoom back to 15
mapEngine.getMap().setZoom(15);
//find all modes and bind them to the view
Mode.FindAll(new Callback(function(modes) {
$scope.request.setMode(modes[0]);
updateView();
}));
};
//on reset request tapped: the back menu tapped
$scope.onResetTapped = resetRequest;
/**
* on menu tapped
*/
$scope.onNavTapped = function() {
//if before hail open the sidemenu
if ($scope.requestState <= REQUEST_STATE.HAIL)
$ionicSideMenuDelegate.toggleLeft();
else {
//else reset the request
resetRequest();
}
};
//on nearby cars found
var onNearbyCarsFound = new Callback(function(nearByCars) {
//stop if map not ready yet
if (!mapEngine.isReady) return;
//remove current map markers
mapEngine.gMapsInstance.removeMarkers();
//if no nearby yet
if (!nearByCars || nearByCars.length === 0) {
//set the pin icon of nearby
if (Settings.getInstance().nearby_pin) {
mapEngine.navigationInfoWindowLeftText(Settings.getInstance().nearby_pin);
}
return;
}
//move on each nearby car and set it
for (var i = 0; i < nearByCars.length; i++) {
if (nearByCars[i].car_location) {
var position = Geolocation.ParsePosition(nearByCars[i].car_location);
mapEngine.addMarker(position.lat(), position.lng(), nearByCars[i].image);
}
}
// set the ETA of the first nearby car
if (nearByCars.length > 0)
mapEngine.navigationInfoWindowLeftText(null, nearByCars[0].time + "min");
});
//set nearby cars found callback
User.getInstance().onNearbyCarsFound = onNearbyCarsFound;
/**
* init modes select drag dealer
*/
var initModeSelect = function() {
//init drag dealer object
dragDealer = new Dragdealer('mode-select', {
steps: $scope.modes.length,
loose: true,
tapping: true,
callback: function(x, y) { // on drag dealer select change
//get the drag dealer step
$scope.step = dragDealer.getStep()[0];
//set the mode of the selected step
$scope.request.setMode(Mode.FromDragDealer($scope.step));
//bind to user mode the current request mode
User.getInstance().nearbyMode = $scope.request.mode;
//change the active mode icon
var modeActiveIconElem = angular.element(document.getElementById("mode-active-icon"));
modeActiveIconElem.attr("src", $scope.request.mode.icon);
if (ionic.Platform.isAndroid()) $scope.$apply();
}
});
//in 1 second set the active icon
$timeout(function() {
//update the active mode icon
dragDealer.reflow();
var modeActiveIconElem = angular.element(document.getElementById("mode-active-icon"));
modeActiveIconElem.attr("src", $scope.request.mode.icon);
}, 1000);
//find all modes
Mode.FindAll(new Callback(function(modes) {
//set drag dealer step on the current selected mode
dragDealer.setStep($scope.request.mode.getDragDealerStep());
var modeActiveIconElem = angular.element(document.getElementById("mode-active-icon"));
modeActiveIconElem.attr("src", $scope.request.mode.icon);
User.getInstance().findNearbyCars($scope.request.mode, null, onNearbyCarsFound);
}));
};
var validateDropoffLocation = function(dropoffLocation) {
if (dropoffLocation === null)
$rootScope.onError.fire(new Error("You can't set a dropoff location more than 10 KM"));
};
var onPlaceChanged = function(place) {
//if has no geomtry do nothing
if (!place || !place.geometry)
return;
//navigate to this place
if (place.geometry.viewport) {
mapEngine.getMap().fitBounds(place.geometry.viewport);
} else {
mapEngine.getMap().setCenter(place.geometry.location);
}
mapEngine.getMap().setZoom(17);
};
//user for new google places component
var googlePlaceSelectEvent = null;
$scope.onPickupLocationSelected = function(place) {
if (!place.geometry) {
$scope.request.pickupAddress = "";
} else {
onPlaceChanged(place);
$scope.request.pickupLocation = place.geometry.location;
$scope.request.pickupAddress = place.formatted_address;
}
if (ionic.Platform.isAndroid()) $scope.$apply();
};
$scope.onDropoffLocationSelected = function(place) {
if (!place.geometry) {
$scope.request.dropoffAddress = "";
} else {
onPlaceChanged(place);
$scope.request.dropoffLocation = place.geometry.location;
$scope.request.dropoffAddress = place.formatted_address;
validateDropoffLocation($scope.request.dropoffLocation);
}
if (ionic.Platform.isAndroid()) $scope.$apply();
};
$scope.$on('$ionicView.leave', function() {
if (googlePlaceSelectEvent) googlePlaceSelectEvent();
});
$scope.$on('$ionicView.enter', function() {
googlePlaceSelectEvent = $scope.$on("g-places-autocomplete:select", function(event, place) {
if ($scope.requestState === REQUEST_STATE.PICKUP)
$scope.onPickupLocationSelected(place);
else if ($scope.requestState === REQUEST_STATE.DROPOFF)
$scope.onDropoffLocationSelected(place);
});
});
var initModesPopovers = function() {
$ionicPopover.fromTemplateUrl('mode.popover.html', {
scope: $scope
}).then(function(popover) {
$scope.openPopover = function(event, step) {
if (!step) step = $scope.step;
popover.show(event);
};
$scope.$on('$destroy', function() {
popover.remove();
});
});
};
initModeSelect();
initModesPopovers();
$scope.onRequestPlusTapped = function() {
if ($scope.request.passengers < $scope.request.mode.maxPassengers)
$scope.request.passengers++;
};
$scope.onRequestMinusTapped = function() {
if ($scope.request.passengers > 1)
$scope.request.passengers--;
};
$scope.onPickupTapped = function() {
$state.go("menu.pickuplocations", {
request: $scope.request
});
};
mapEngine.ready(function() {
var onDestinationLocationChange = new Callback(function() {
var g = new Geolocation();
$rootScope.onProgress.fire();
var locationLatLng = mapEngine.getCenter();
g.latlngToAddress(locationLatLng, new Callback(function(address, place) {
if (address.toUpperCase().indexOf("UNNAMED") > -1)
address = "No street name";
if ($scope.requestState === REQUEST_STATE.HAIL || $scope.requestState === REQUEST_STATE.PICKUP || $scope.requestState === REQUEST_STATE.REQUEST_CAB || $scope.requestState === REQUEST_STATE.FARE_ESTIMATION) { /*!$scope.request.pickupAddress || $scope.request.pickupAddress.trim().length === 0*/
$scope.request.pickupLocation = locationLatLng;
$scope.request.pickupAddress = address;
$scope.input.pickup = place;
} else if ($scope.requestState === REQUEST_STATE.DROPOFF) { /*!$scope.request.dropoffAddress || $scope.request.dropoffAddress.trim().length === 0*/
$scope.request.dropoffAddress = address;
$scope.request.dropoffLocation = locationLatLng;
$scope.input.dropoff = place;
validateDropoffLocation($scope.request.dropoffLocation);
}
$rootScope.onProgressDone.fire();
if (ionic.Platform.isAndroid()) $scope.$apply();
}), $rootScope.onError);
});
//if not comming from pickup locations
if (!($stateParams.request && $stateParams.request.pickupPlace) && $scope.requestState == REQUEST_STATE.REQUEST_CAB)
onDestinationLocationChange.fire();
mapEngine.gMapsInstance.on("dragend", function() {
if ($scope.request.mode) {
if (Settings.getInstance().drag_thread.toUpperCase() === "YES")
User.getInstance().findNearbyCars($scope.request.mode, mapEngine.getCenter(), onNearbyCarsFound);
// mapEngine.navigationInfoWindowLeftText(null, $scope.request.mode.etaTime + "min");
}
if ($scope.requestState === REQUEST_STATE.PICKUP || $scope.requestState === REQUEST_STATE.DROPOFF || $scope.requestState === REQUEST_STATE.REQUEST_CAB)
onDestinationLocationChange.fire();
});
var onHailRequestPickedup = new Callback(function() {
mapEngine.drawRoute({
origin: [$scope.request.pickupLocation.lat(), $scope.request.pickupLocation.lng()],
destination: [$scope.request.dropoffLocation.lat(), $scope.request.dropoffLocation.lng()],
travelMode: "driving",
strokeColor: "#7EBBFE",
strokeWeight: 7
});
$scope.requestState = REQUEST_STATE.FARE;
updateView();
$scope.request.estimateCost(new Callback(function(cost) {
$scope.confirm = {
title: 'FARE ESTIMATION',
message: Util.String("{0} USD for {1}", [cost, $scope.request.mode.name]),
buttons: {
isSubmit: false,
yes: "CONFIRM",
no: "CANCEL",
promotePositive: true
}
};
$scope.onNoTapped = function() {
fareConfirm.close();
resetRequest();
};
$scope.onYesTapped = function() {
fareConfirm.close();
$scope.onSubmitTapped = function(comment) {
$scope.request.comment = comment;
commentConfirm.close();
$ionicLoading.show({
template: 'Matching you with a Driver now!'
});
$scope.request.make(User.getInstance(), new Callback(function(driver) {
mapEngine.gMapsInstance.off("dragend");
$ionicLoading.hide();
$ionicHistory.clearCache();
$state.go("menu.requestconfirmed", {
request: $scope.request
});
}), new Callback(function(e) {
$rootScope.onError.fire(e);
/*$scope.requestState = REQUEST_STATE.DROPOFF;
updateView();*/
resetRequest();
}));
};
$scope.confirm = {
message: "Send a Note About Your Location So Driver Can Find You Quicker",
buttons: {
isSubmit: true
},
input: {
data: $scope.request.comment,
placeholder: "I am next to beirut municipality entrance",
isAllowed: true
}
};
$timeout(function() {
commentConfirm = $ionicPopup.confirm({
templateUrl: "templates/confirm.popup.html",
cssClass: "eserviss-confirm text-center",
scope: $scope
});
}, 500);
};
fareConfirm = $ionicPopup.confirm({
templateUrl: "templates/confirm.popup.html",
cssClass: "eserviss-confirm text-center",
scope: $scope
});
}), new Callback(function(e) {
$rootScope.onError.fire(e);
$scope.requestState = REQUEST_STATE.DROPOFF;
updateView();
}));
});
var onLocationEnabled = new Callback(function() {
initAds();
$scope.myLocationTapped = function() {
User.getInstance().findPosition(new Callback(function(position) {
mapEngine.addUserAccuracy(position.lat(), position.lng(), position.accuracy);
mapEngine.setCenter(position.lat(), position.lng());
if ($scope.requestState === REQUEST_STATE.PICKUP || $scope.requestState === REQUEST_STATE.DROPOFF || $scope.requestState === REQUEST_STATE.REQUEST_CAB)
onDestinationLocationChange.fire();
}));
};
var g = new Geolocation();
User.getInstance().findPosition(new Callback(function(position) {
mapEngine.addUserAccuracy(position.lat(), position.lng(), position.accuracy);
mapEngine.setCenter(position.lat(), position.lng());
rebuildSyncedRequest();
}), $rootScope.onError);
mapEngine.navigationMarker(function() {
/*mapEngine.addCenterMarker();*/
});
mapEngine.navigationInfo(function() {
if ($scope.requestState === REQUEST_STATE.INIT) {
$scope.request.inService(new Callback(function() {
onDestinationLocationChange.fire();
if ($scope.request.mode.isTaxi() || $scope.request.mode.isFree()) {
/*$state.go("menu.pickuplocations", {
request: $scope.request
});*/
$scope.requestState = REQUEST_STATE.REQUEST_CAB;
} else {
$scope.requestState = REQUEST_STATE.PICKUP; //due to ux will compress the hail step to pickup
}
updateView();
}), $rootScope.onError);
} else if ($scope.requestState === REQUEST_STATE.PICKUP) {
$scope.request.inService(new Callback(function() {
$scope.requestState = REQUEST_STATE.DROPOFF;
updateView();
}), $rootScope.onError);
} else if ($scope.requestState === REQUEST_STATE.REQUEST_CAB) {
$scope.request.inService(new Callback(function() {
onDestinationLocationChange.fire();
$scope.requestState = REQUEST_STATE.FARE_ESTIMATION;
openCommentPopup();
updateView();
/*mapEngine.gMapsInstance.off("dragend");
$state.go("menu.sendnote", {
request: $scope.request
});*/
}), $rootScope.onError);
} else if ($scope.requestState === REQUEST_STATE.FARE_ESTIMATION) {
$scope.request.inService(new Callback(function() {
onDestinationLocationChange.fire();
openCommentPopup();
updateView();
}), $rootScope.onError);
} else if ($scope.requestState === REQUEST_STATE.DROPOFF) {
var validator = new Validator();
if (validator.isNull($scope.request.dropoffLocation, "Please enter dropoff location first")) {
$rootScope.onError.fire(validator.getError());
return;
}
$scope.request.inService(new Callback(function() {
if ($scope.request.mode.id === Mode.ID.SERVISS) {
$scope.request.validateServicePickup(new Callback(function(isNear) {
if (isNear) {
onHailRequestPickedup.fire();
return;
}
$scope.confirm = {
title: 'MEETING POINT',
message: $scope.request.nearestPoint.message,
buttons: {
isSubmit: false,
yes: "ACCEPT",
no: "CHOOSE TAXI",
}
};
$scope.onNoTapped = function() {
meetingPointConfirm.close();
resetRequest();
};
$scope.onYesTapped = function() {
var nearestPointImg = angular.element(document.getElementById("meetingpointImg"));
meetingPointConfirm.close();
$scope.requestState = REQUEST_STATE.MEETING_POINT;
updateView();
$scope.request.nearestPoint.header.line[0] = " START WALKING TOWARDS MEETING POINT NOW";
nearestPointImg.css("vertical-align", "middle");
$scope.request.watchToMeetingPoint(new Callback(function(userPosition) {
mapEngine.drawRoute({
origin: [userPosition.lat(), userPosition.lng()],
destination: [$scope.request.nearestPoint.location.lat(), $scope.request.nearestPoint.location.lng()],
travelMode: "walking",
strokeColor: "#7EBBFE",
strokeWeight: 7
});
mapEngine.setCenter($scope.request.nearestPoint.location.lat(), $scope.request.nearestPoint.location.lng());
}), new Callback(function() {
$scope.request.nearestPoint.header.line[0] = "YOU HAVE REACHED YOUR MEETING POINT!";
$scope.request.nearestPoint.header.line[1] = "PLEASE CONFIRM YOUR RIDE REQUEST";
nearestPointImg.css("vertical-align", "top");
$scope.requestState = REQUEST_STATE.CONFIRM_MEETING_POINT;
updateView();
}), new Callback(function() {
$scope.request.nearestPoint.header.line[0] = "YOU ARE CLOSE TO MEETING POINT";
nearestPointImg.css("vertical-align", "middle");
}, 1), $rootScope.onError);
};
meetingPointConfirm = $ionicPopup.confirm({
templateUrl: "templates/confirm.popup.html",
cssClass: "eserviss-confirm text-center",
scope: $scope
});
}), $rootScope.onError);
} else {
onHailRequestPickedup.fire();
}
}), $rootScope.onError);
} else if ($scope.requestState === REQUEST_STATE.MEETING_POINT) {
$cordovaDialogs.alert("Eserviss is wathcing your position until you reach the meeting point", 'Meeting Point');
} else if ($scope.requestState === REQUEST_STATE.CONFIRM_MEETING_POINT) {
mapEngine.gMapsInstance.removePolylines();
$scope.request.pickupLocation = $scope.request.nearestPoint.location.toLatLng();
var g = new Geolocation();
g.latlngToAddress($scope.request.pickupLocation, new Callback(function(address) {
$scope.request.pickupAddress = address;
if (ionic.Platform.isAndroid()) $scope.$apply();
}));
onHailRequestPickedup.fire();
}
if (ionic.Platform.isAndroid()) $scope.$apply();
});
updateView();
});
$rootScope.ifLocationEnabled(onLocationEnabled);
});
$scope.$on('$destroy', function() {
/*window.addEventListener('native.keyboardhide', function() {});*/
});
}
]);
controllers.controller('HailRequestController@confirmed', [
'$scope', '$state', '$stateParams', 'mapEngine', 'User', '$rootScope', 'Callback',
'Util', 'Geolocation', '$cordovaDialogs', '$ionicHistory', '$timeout', 'HailRequest',
function($scope, $state, $stateParams, mapEngine, User, $rootScope, Callback,
Util, Geolocation, $cordovaDialogs, $ionicHistory, $timeout, HailRequest) {
'use strict';
var confirmedScrollElem = angular.element(document.getElementById("confirmedScroll")),
infoElem = angular.element(document.getElementById("info")),
geolocation = new Geolocation();
var MARKER_ID = {
USER: 1,
MODE: 2
};
$scope.request = $stateParams.request;
$scope.infoState = 1;
//unlock app
localStorage.removeItem(HailRequest.HAIL_LOCK);
/*$scope.request.driver.findRating(new Callback(function (rating) {
if (ionic.Platform.isAndroid()) $scope.$apply();
}), $rootScope.onError);*/
$scope.onCloseTapped = function() {
if ($scope.infoState === 1) { //if driver info shown
confirmedScrollElem.removeClass('slideOutDown');
confirmedScrollElem.removeClass('slideInDown');
confirmedScrollElem.addClass('slideOutDown');
infoElem.css("height", "auto");
$scope.infoState = 0;
} else if ($scope.infoState === 0) { //if driver info hidden
confirmedScrollElem.removeClass('slideOutDown');
confirmedScrollElem.removeClass('slideInDown');
confirmedScrollElem.addClass('slideInDown');
infoElem.css("height", "50%");
$scope.infoState = 1;
}
};
$scope.onContactTapped = function() {
plugins.listpicker.showPicker({
title: "Contact Driver",
items: [{
text: "Send a Message",
value: "MESSAGE"
}, {
text: "Call Driver",
value: "CALL"
}]
}, function(action) {
if (action === 'MESSAGE') {
plugins.socialsharing.shareViaSMS({
message: ''
}, $scope.request.driver.DriverPhone, null, function() {});
} else if (action === 'CALL') {
plugins.CallNumber.callNumber(function() {}, function(e) {
$rootScope.onError.fire(new Error(e, true, true));
}, $scope.request.driver.DriverPhone);
}
}, function() {});
};
$scope.onShareEtaTapped = function() {
var POST_MESSAGE = Util.String("Get Eserviss app at http://eserviss.com/app");
var POST_TITLE = "Eserviss";
plugins.socialsharing.share(POST_MESSAGE, POST_TITLE);
};
var initSync = function() {
$scope.request.onEtaArrival = new Callback(function(etaArrival) {
var PADDING_BOTTOM = 0.02;
if ($scope.request.stage === HailRequest.STAGE.RESPONSE) {
var carLocation = etaArrival.car_location ? Geolocation.ParsePosition(etaArrival.car_location) : null;
if (!carLocation) {
mapEngine.addMarker(User.getInstance().position.lat(), User.getInstance().position.lng(), etaArrival.user_pin, MARKER_ID.USER);
mapEngine.setCenter(User.getInstance().position.lat(), User.getInstance().position.lng() + PADDING_BOTTOM);
} else {
mapEngine.infoBubble(carLocation.lat(), carLocation.lng(), etaArrival.display);
mapEngine.addMarker(User.getInstance().position.lat(), User.getInstance().position.lng() + PADDING_BOTTOM, etaArrival.user_pin, MARKER_ID.USER);
mapEngine.setCenter(carLocation.lat(), carLocation.lng() + PADDING_BOTTOM);
if (User.getInstance().position.calculateDistance(carLocation) <= 100) {
mapEngine.setZoom(15);
} else {
mapEngine.fitMap(carLocation, User.getInstance().position);
}
}
} else {
mapEngine.removeInfoBubble();
mapEngine.setCenter(User.getInstance().position.lat(), User.getInstance().position.lng());
}
// mapEngine.addUserAccuracy(User.getInstance().position.lat(), User.getInstance().position.lng(), User.getInstance().position.accuracy, others);
});
$scope.request.sync(User.getInstance(), new Callback(function() {
if ($scope.request.stage === HailRequest.STAGE.PICKUP && $scope.request.getDropoffLocation()) {
mapEngine.addMarker($scope.request.getDropoffLocation().lat(), $scope.request.getDropoffLocation().lng(), $scope.request.mode.icon, MARKER_ID.MODE);
}
if (ionic.Platform.isAndroid()) $scope.$apply();
}), $rootScope.onError);
$scope.request.onPickedup = new Callback(function() {
mapEngine.addMarker($scope.request.getDropoffLocation().lat(), $scope.request.getDropoffLocation().lng(), $scope.request.getDropoffLocation());
});
$scope.request.onDroppedoff = new Callback(function() {
geolocation.stopWatching();
if ($scope.request.mode.isFree()) {
$state.go("menu.freereceipt", {
request: $scope.request
});
} else {
$state.go("menu.receipt", {
request: $scope.request
});
}
});
$scope.request.onDriverCanceled = new Callback(function() {
$cordovaDialogs.alert("Driver didn't find you, the ride has been canceled", 'Ride Canceled')
.then(function() {
$ionicHistory.nextViewOptions({
disableBack: true
});
$ionicHistory.clearCache();
mapEngine.resetMap();
$timeout(function() {
$state.go("menu.hailrequest");
}, 50);
});
});
};
initSync();
var onLocationEnabled = new Callback(function() {
User.getInstance().findPosition(new Callback(function(position) {
mapEngine.addUserAccuracy(position.lat(), position.lng(), position.accuracy);
mapEngine.setCenter(position.lat(), position.lng());
}), $rootScope.onError);
if ($scope.request.dropoffLocation && $scope.request.dropoffLocation.lat() && $scope.request.dropoffLocation.lng()) {
mapEngine.drawRoute({
origin: [$scope.request.pickupLocation.lat(), $scope.request.pickupLocation.lng()],
destination: [$scope.request.dropoffLocation.lat(), $scope.request.dropoffLocation.lng()],
travelMode: "driving",
strokeColor: "#7EBBFE",
strokeWeight: 7
});
}
geolocation.watch(new Callback(function(position) {
User.getInstance().position = position;
mapEngine.addUserAccuracy(position.lat(), position.lng(), position.accuracy);
}));
});
$scope.$on('$ionicView.leave', function() {
geolocation.stopWatching();
$scope.request.isSyncable = false;
/*mapEngine.removeMarker();*/
mapEngine.resetMap();
User.getInstance().onNearbyCarsFound = null;
});
$scope.$on('$ionicView.enter', function() {
mapEngine.ready(function() {
// onLocationEnabled.fire();
$rootScope.ifLocationEnabled(onLocationEnabled);
});
});
}
]);
controllers.controller('HailRequestController@receipt', [
'$scope', '$state', '$stateParams', 'Validator', '$rootScope', 'Callback',
'$ionicHistory', 'User', '$cordovaDialogs', '$timeout',
function($scope, $state, $stateParams, Validator, $rootScope, Callback,
$ionicHistory, User, $cordovaDialogs, $timeout) {
'use strict';
$ionicHistory.nextViewOptions({
disableBack: true
});
var today = new Date();
$scope.date = {
day: today.getDate(),
month: today.toDateString().split(' ')[1],
year: today.getFullYear()
};
$scope.request = $stateParams.request;
$scope.receipt = {};
/*User.getInstance().findCredit(new Callback(function(credit) {
if (credit.cash < $scope.request.totalCost) {
$cordovaDialogs.alert("Please pay the trip cost to the driver", 'Trip Cost');
} else {
$scope.request.consumeCost(User.getInstance(), new Callback(function() {
$cordovaDialogs.alert("Your trip cost has been charged from your balance", 'Trip Cost');
}), $rootScope.onError);
}
}), $rootScope.onError);*/
var consumeCost = function() {
$scope.request.consumeCost(User.getInstance(), new Callback(function() {
$cordovaDialogs.alert("Your trip cost has been charged from your balance", 'Trip Cost');
}), $rootScope.onError);
};
$scope.request.findFare(User.getInstance(), new Callback(function() {
console.log("fare is", $scope.request.fare);
User.getInstance().findCredit(new Callback(function(userBalance) {
var toCharge = Math.ceil($scope.request.fare - userBalance.cash);
if (toCharge > 0) {
User.getInstance().recharge(toCharge, new Callback(consumeCost), new Callback(function(e) {
$rootScope.onError.fire(e);
consumeCost();
}));
} else {
consumeCost();
}
}), new Callback(consumeCost));
}), new Callback(consumeCost));
$scope.onSubmitTapped = function(receipt) {
var validator = new Validator();
if (validator.isEmpty(receipt.rating, "Please insert rating first in your feedback") ||
validator.isEmpty(receipt.comment, "Please insert comment first in your feedback")) {
$rootScope.onError.fire(validator.getError());
return;
}
$scope.request.feedback(User.getInstance(), $scope.receipt.rating, $scope.receipt.comment, new Callback(function() {
$ionicHistory.clearCache();
$timeout(function() {
$state.go("menu.hailrequest", {}, {
reload: true
});
/*$state.go("menu.hailrequest");*/
}, 50);
}), $rootScope.onError);
};
}
]);
controllers.controller('HailRequestController@freereceipt', [
'$scope', '$state', '$stateParams', 'Validator', '$rootScope', 'Callback',
'$ionicHistory', 'User', '$cordovaDialogs', '$timeout', 'HailRequest', 'Geolocation',
'$cordovaInAppBrowser',
function($scope, $state, $stateParams, Validator, $rootScope, Callback,
$ionicHistory, User, $cordovaDialogs, $timeout, HailRequest, Geolocation,
$cordovaInAppBrowser) {
'use strict';
$ionicHistory.nextViewOptions({
disableBack: true
});
var today = new Date();
$scope.date = {
day: today.getDate(),
month: today.toDateString().split(' ')[1],
year: today.getFullYear()
};
$scope.request = $stateParams.request;
var g = new Geolocation();
g.findPosition(new Callback(function(dropoffLocation) {
HailRequest.EstimateCost(1, $scope.request.pickupLocation, dropoffLocation, new Callback(function(totalCost) {
$scope.totalCost = totalCost;
}));
}));
$scope.onCancelTapped = function() {
$ionicHistory.clearCache();
$timeout(function() {
$state.go("menu.hailrequest", {}, {
reload: true
});
/*$state.go("menu.hailrequest");*/
}, 50);
};
$scope.onReviewTapped = function() {
var options = {
location: 'yes',
clearcache: 'yes',
toolbar: 'no'
};
var url = "http://leb.cab";
if (ionic.Platform.isIOS())
url = "https://itunes.apple.com/us/app/eserviss-taxi.-service-bus/id1024534126?ls=1&mt=8";
$cordovaInAppBrowser.open(url, '_blank', options)
.then(function(event) {
$ionicHistory.clearCache();
$timeout(function() {
$state.go("menu.hailrequest", {}, {
reload: true
});
}, 50);
});
};
}
]);
controllers.controller('HailRequestController@pickuplocations', [
'$scope', '$state', '$stateParams', '$ionicHistory', '$timeout', 'User', 'Callback', '$rootScope',
'Util',
function($scope, $state, $stateParams, $ionicHistory, $timeout, User, Callback, $rootScope,
Util) {
'use strict';
$scope.request = $stateParams.request;
var googlePlaceSelectEvent = null;
$ionicHistory.nextViewOptions({
disableBack: true
});
$scope.onLocationSelected = function(place) {
var location = place.geometry.location;
$scope.request.pickupLocation = location;
$scope.request.pickupPlace = place;
};
/*$scope.$on('$ionicView.leave', function() {
if (googlePlaceSelectEvent) googlePlaceSelectEvent();
});
$scope.$on('$ionicView.enter', function() {
googlePlaceSelectEvent = $scope.$on("g-places-autocomplete:select", function(event, place) {
$scope.request.pickupLocation = place.geometry.location;
$scope.request.pickupAddress = place.formatted_address;
});
});*/
User.getInstance().findFavorites(new Callback(function(favorites) {
favorites = favorites.splice(0, 4);
var homeFavorite = favorites[0];
var workFavorite = favorites[1];
$scope.onAddHomeTapped = function() {
if (homeFavorite && homeFavorite.location.lat() && homeFavorite.location.lng()) {
$scope.request.pickupLocation = homeFavorite.location;
$scope.onDoneTapped();
} else {
$rootScope.onError.fire(new Error("You don't have a home favorite added"));
}
};
$scope.onAddWorkTapped = function() {
if (workFavorite && workFavorite.location.lat() && workFavorite.location.lng()) {
$scope.request.pickupLocation = workFavorite.location;
$scope.onDoneTapped();
} else {
$rootScope.onError.fire(new Error("You don't have a work favorite added"));
}
};
}), $rootScope.onError);
$scope.$on('$ionicView.leave', function() {
if (googlePlaceSelectEvent) googlePlaceSelectEvent();
});
$scope.$on('$ionicView.enter', function() {
googlePlaceSelectEvent = $scope.$on("g-places-autocomplete:select", function(event, place) {
$scope.onLocationSelected(place);
$scope.request.pickupAddress = place.formatted_address;
});
});
$scope.onDoneTapped = function() {
if ($ionicHistory.backView().stateName === "menu.hailrequest") {
$ionicHistory.clearCache();
$timeout(function() {
$ionicHistory.backView().stateParams.request = $scope.request;
$ionicHistory.goBack();
}, 50);
} else {
$ionicHistory.goBack();
}
};
}
]);
controllers.controller('HailRequestController@estimationfee', [
'$scope', '$state', '$stateParams', '$ionicHistory', '$timeout',
'Callback', '$rootScope',
function($scope, $state, $stateParams, $ionicHistory, $timeout,
Callback, $rootScope) {
'use strict';
var googlePlaceSelectEvent = null;
$scope.request = $stateParams.request;
$ionicHistory.nextViewOptions({
disableBack: true
});
$scope.onLocationSelected = function(place) {
var location = place.geometry.location;
$scope.request.dropoffLocation = location;
$scope.request.estimateCost(null, $rootScope.onError);
};
$scope.onDoneTapped = function() {
if ($ionicHistory.backView().stateName === "menu.hailrequest") {
$ionicHistory.clearCache();
$timeout(function() {
$ionicHistory.backView().stateParams.request = $scope.request;
$ionicHistory.goBack();
}, 50);
} else {
$ionicHistory.goBack();
}
};
$scope.$on('$ionicView.leave', function() {
if (googlePlaceSelectEvent) googlePlaceSelectEvent();
});
$scope.$on('$ionicView.enter', function() {
googlePlaceSelectEvent = $scope.$on("g-places-autocomplete:select", function(event, place) {
$scope.request.dropoffAddress = place.formatted_address;
$scope.onLocationSelected(place);
});
});
}
]);
controllers.controller('HailRequestController@sendnote', [
'$scope', '$state', '$stateParams', '$ionicHistory', '$timeout',
'Callback', '$rootScope', 'User', '$ionicLoading', 'HailRequest',
'Mode',
function($scope, $state, $stateParams, $ionicHistory, $timeout,
Callback, $rootScope, User, $ionicLoading, HailRequest,
Mode) {
'use strict';
$scope.request = $stateParams.request;
var loadingUpdateTimeout = null;
$ionicHistory.nextViewOptions({
disableBack: true
});
$scope.onConfirmTapped = function() {
$ionicLoading.show({
template: 'Matching you with a driver now...'
});
loadingUpdateTimeout = $timeout(function() {
$ionicLoading.show({
template: 'Search for more cars...'
});
}, 30000);
$scope.request.make(User.getInstance(), new Callback(function(driver) {
if (loadingUpdateTimeout) {
console.log("loadingUpdateTimeout", loadingUpdateTimeout);
$timeout.cancel(loadingUpdateTimeout);
loadingUpdateTimeout = null;
}
$ionicLoading.hide();
$ionicHistory.clearCache();
$state.go("menu.requestconfirmed", {
request: $scope.request
});
}), new Callback(function(e) {
if (loadingUpdateTimeout) {
$timeout.cancel(loadingUpdateTimeout);
loadingUpdateTimeout = null;
}
$ionicLoading.hide();
$rootScope.onError.fire(e, new Callback(function() {
$scope.request = new HailRequest();
$scope.request.setMode(Mode.FindById(Mode.ID.TAXI));
$ionicHistory.clearCache();
$timeout(function() {
$state.go("menu.hailrequest", {
request: $scope.request
});
}, 50);
}));
}));
};
}
]);
controllers.controller('HailRequestController@cancelride', [
'$scope', '$state', '$stateParams', 'Callback', '$rootScope',
'Validator', '$timeout', '$ionicHistory',
function($scope, $state, $stateParams, Callback, $rootScope,
Validator, $timeout, $ionicHistory) {
'use strict';
$scope.request = $stateParams.request;
$scope.cancel = {};
$ionicHistory.nextViewOptions({
disableBack: true
});
$scope.onCancelTapped = function() {
var validator = new Validator();
validator.isNull($scope.cancel.reason, "Please enter a valid reason first");
if (!validator.isPassed()) {
$rootScope.onError.fire(validator.getError());
return;
}
$scope.request.cancelRide($scope.cancel.reason, new Callback(function() {
$ionicHistory.clearCache();
$timeout(function() {
$state.go("menu.hailrequest");
}, 50);
}), $rootScope.onError);
};
}
]);
<file_sep>application.factory('Country', [
'Model', 'Http', 'Callback',
function(Model, Http, Callback) {
'use strict';
var Country = augment(Model, function(parent) {
this.constructor = function(row) {
this._fields = ["name", "phoneCode"];
this._tableName = "Country";
this._modelType = Country;
parent.constructor.call(this, row);
};
});
Country.FindAll = function (onSuccess, onError) {
var http = new Http();
http.get({
url: "countries.json",
model: Country,
onSuccess: onSuccess,
onError: onError
});
};
return Country;
}
]);<file_sep>controllers.controller('GuestController@share', [
'$scope', '$state', '$stateParams', 'User', 'Callback', '$rootScope',
'Util', 'Error',
function($scope, $state, $stateParams, User, Callback, $rootScope,
Util, Error) {
'use strict';
//link to be refered per user
var POST_MESSAGE = "Get Eserviss app at http://leb.cab";
var POST_TITLE = "ESERVISS app install";
//check if client is android or ios whether to use link email or app email
$scope.isAndroid = ionic.Platform.isAndroid();
$scope.isIos = ionic.Platform.isIOS();
//find share referal code
User.getInstance().findShare(new Callback(function(share) {
//update message with the referal code
$scope.share = share;
POST_MESSAGE = Util.String("Get Eserviss app at http://leb.cab, Referal code is {0}", [share.code]);
$scope.title = POST_TITLE;
$scope.message = POST_MESSAGE;
}), $rootScope.onError);
/**
* on copy (icon) referal link tapped
*/
$scope.onCopyReferalLink = function() {
//check if cordova isn't defined (browser testing)
if (typeof(cordova) === "undefined") return;
//copy the message to clipboard
cordova.plugins.clipboard.copy(POST_MESSAGE);
//user feedback that message is copied using toast message
$cordovaToast.showLongBottom('Your referal link copied')
.then(function(success) {}, function(error) {});
};
/**
* open share action sheet
* @param {String} message to share
* @param {String} title of the shared message
*/
var shareActionsheet = function(message, title) {
if (!message) message = POST_MESSAGE;
if (!title) title = POST_TITLE;
plugins.socialsharing.share(message, title);
};
/**
* on sms button tapped
*/
$scope.onSmsTapped = function() {
plugins.socialsharing.shareViaSMS({
message: POST_MESSAGE
}, null, null, shareActionsheet);
};
/**
* on facebook button tapped
*/
$scope.onFacebookTapped = function() {
plugins.socialsharing.shareViaFacebookWithPasteMessageHint(POST_MESSAGE, null, null, "Your referal post is copied, paste it if you like", null, shareActionsheet);
};
/**
* on google plus button tapped
*/
$scope.onGoogleTapped = function() {
if (ionic.Platform.isAndroid()) {
plugins.socialsharing.shareVia('com.google.android.apps.plus', POST_MESSAGE, POST_TITLE, null, null, null, shareActionsheet);
} else {
shareActionsheet();
}
};
/**
* on twitter button tapped
*/
$scope.onTwitterTapped = function() {
plugins.socialsharing.shareViaTwitter(POST_MESSAGE, null, null, null, shareActionsheet);
};
/**
* on whatsapp button tapped
*/
$scope.onWhatsappTapped = function() {
plugins.socialsharing.shareViaWhatsApp(POST_MESSAGE, null, null, null, shareActionsheet);
};
/**
* on email button tapped
*/
$scope.onEmailTapped = function() {
plugins.socialsharing.shareViaEmail(POST_MESSAGE, POST_TITLE, [], [], [], null, function () {
alert("email succeeded");
}, shareActionsheet);
};
}
]);
<file_sep>controllers.controller('HomeController@splash', [
'$scope', '$state', '$stateParams', '$ionicHistory', '$ionicPlatform', '$cordovaDialogs',
'$rootScope', 'Callback', 'Geolocation', '$ionicModal', '$timeout', 'Settings', '$ionicLoading',
'User', 'Util', 'Mode', '$cordovaFacebook',
function($scope, $state, $stateParams, $ionicHistory, $ionicPlatform, $cordovaDialogs,
$rootScope, Callback, Geolocation, $ionicModal, $timeout, Settings, $ionicLoading,
User, Util, Mode, $cordovaFacebook) {
'use strict';
$ionicHistory.nextViewOptions({
disableBack: true
});
$ionicPlatform.ready(function() {
if (!Util.IsBrowser()) {
$cordovaFacebook.getLoginStatus();
GappTrack.track("UA-69276680-1", "", "1", false, function() {}, function(message) {});
}
});
$rootScope.onError = new Callback(function(e, onTapped) {
var message = e && e.message ? e.message : "Check your internet connectivity";
$cordovaDialogs.alert(message, 'Note')
.then(function() {
if (onTapped && typeof(onTapped) !== "string") onTapped.fire();
$ionicLoading.hide();
});
});
$rootScope.onProgress = new Callback(function() {
$ionicLoading.show({
template: '<ion-spinner></ion-spinner>'
});
});
$rootScope.onProgressDone = new Callback(function() {
$ionicLoading.hide();
});
$rootScope.ifLocationEnabled = function(onEnabled, onNotEnabled) {
var locationoffModal = null;
if (Util.IsBrowser()) {
onEnabled.fire();
return;
}
var g = new Geolocation();
g.isLocationEnabled(new Callback(function(isEnabled) {
if (isEnabled)
onEnabled.fire();
else {
if (locationoffModal !== null) {
locationoffModal.show();
return;
}
$ionicModal
.fromTemplateUrl("templates/locationoff.modal.html", {
scope: $scope,
animation: 'slide-in-up'
})
.then(function(modal) {
locationoffModal = modal;
modal.show();
$scope.onTurnOnLocationTapped = function() {
modal.hide();
g.openLocationSettings();
if (onNotEnabled) onNotEnabled.fire();
//reset last action in 7 secs
$timeout(function() {
$rootScope.ifLocationEnabled(onEnabled, onNotEnabled);
}, 7000);
};
});
}
}), $rootScope.onError);
};
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
if (ionic.Platform.isAndroid()) {
switch (notification.event) {
case 'registered':
if (notification.regid.length > 0) {
User.getInstance().registerPushNotification(notification.regid);
}
break;
case 'message':
// this is the actual push notification. its format depends on the data model from the push server
$cordovaDialogs.alert(notification.message, 'Message!');
break;
case 'error':
//alert('GCM error = ' + notification.msg);
break;
default:
//alert('An unknown GCM event has occurred');
break;
}
} else if (ionic.Platform.isIOS()) {
if (notification.alert) {
$cordovaDialogs.alert(notification.alert, 'Message!');
}
}
});
Settings.Download(new Callback(function() {
$rootScope.onContactUs = function() {
$cordovaDialogs.confirm("Need Help? Don't hesitate to call us now", 'Customer Support', ['Call', 'Cancel'])
.then(function(buttonIndex) {
var btnIndex = buttonIndex;
if (btnIndex === 1) {
plugins.CallNumber.callNumber(function() {}, function(e) {
$rootScope.onError.fire(new Error("Error while contacting customer support, try again later", true, true));
}, Settings.getInstance().e_number);
}
});
};
}));
if (User.IsStored()) {
var onError = new Callback(function(e) {
$rootScope.onError.fire(e);
$timeout(function() {
$state.go('landing');
}, 4000);
});
Mode.FindAll(new Callback(function() {
User.getInstance().signin(new Callback(function() {
User.getInstance().store();
User.InitPushNotification();
User.getInstance().ping();
User.getInstance().sync(new Callback(function(request) { //on progress
$timeout(function() {
$state.go('menu.hailrequest', {
request: request
});
}, 4000);
}), new Callback(function(request) { // on confirmed
$timeout(function() {
$state.go('menu.requestconfirmed', {
request: request
});
}, 4000);
}), new Callback(function() { //no old synced data
$timeout(function() {
$state.go('menu.hailrequest');
}, 4000);
}), onError);
}), null, onError);
}), onError);
} else {
$timeout(function() {
$state.go("landing");
}, 7000);
}
}
]);
controllers.controller('HomeController@landing', [
'$scope', '$state', '$stateParams', '$translate', '$ionicPlatform', '$cordovaDialogs',
'$rootScope', 'Callback', 'Geolocation', '$ionicModal', '$timeout', 'Settings', '$ionicLoading',
'User', '$ionicHistory', 'Mode', '$cordovaFacebook', 'Util',
function($scope, $state, $stateParams, $translate, $ionicPlatform, $cordovaDialogs,
$rootScope, Callback, Geolocation, $ionicModal, $timeout, Settings, $ionicLoading,
User, $ionicHistory, Mode, $cordovaFacebook, Util) {
'use strict';
var languageConfig = {
title: "Select a Language",
items: [{
text: "English",
value: "en"
}, {
text: "Arabic",
value: "ar"
}],
doneButtonLabel: "Done",
cancelButtonLabel: "Cancel"
};
$scope.onLanguageTapped = function() {
if (typeof cordova === 'undefined') {
$translate.use('en');
$state.go("authenticate");
return;
}
plugins.listpicker.showPicker(languageConfig, function(lang) {
if (lang === 'en')
$scope.language = 'ENGLISH';
else if (lang === 'ar')
$scope.language = 'العربية';
$translate.use(lang);
$state.go("authenticate");
}, function() {});
};
}
]);
controllers.controller('HomeController@sidemenu', [
'$scope', '$state', '$stateParams', '$ionicHistory', '$timeout', '$cordovaDialogs',
'Settings', '$rootScope', 'Error',
function($scope, $state, $stateParams, $ionicHistory, $timeout, $cordovaDialogs,
Settings, $rootScope, Error) {
'use strict';
$scope.menuWidth = window.innerWidth;
$scope.onBackTapped = function() {
if ($ionicHistory.backView().stateName === "menu.hailrequest") {
$ionicHistory.clearCache();
$timeout($ionicHistory.goBack, 50);
} else {
$ionicHistory.goBack();
}
};
}
]);
| a21d512f852a2e7f98919505eecce7f569ab47fb | [
"JavaScript"
] | 15 | JavaScript | tymiles003/ES-uapp | 32b68d36abf0c511bd44b2db24ac926906385771 | 311893f52f0f99966d110a9cd9055cfb5f39029f | |
refs/heads/master | <repo_name>grantjk/JGAFetchedTables<file_sep>/Gemfile
source "https://rubygems.org"
gem 'cocoapods', "0.22.2"
<file_sep>/Podfile
platform :ios, '6.0'
pod 'MagicalRecord', '~> 2.1'
pod 'SSPullToRefresh'
target :JGAFetchedTablesTests, exclusive: true do
pod 'Kiwi'
end
<file_sep>/README.md
JGAFetchedTables
================
Clean UITableViewControllers for CoreData and remote APIs
| 3fe0140c8e4948b191732fd0f8cad3ee4ba44677 | [
"Markdown",
"Ruby"
] | 3 | Ruby | grantjk/JGAFetchedTables | a6bcca4bd95b7aa60171dfcf6c6a5e9adbc43798 | f7235cf9163c08a68884c2fc5716a304cbc249a1 | |
refs/heads/main | <repo_name>lyo-lya/WorldOfTanks<file_sep>/Assets/Scripts/Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
float hor, vert;
Rigidbody2D rb;
Vector3 campos = new Vector3(0f, 0f, -10f);
public int speed;
float kd = 2;
float time = 0;
public GameObject bullet;
public GameObject ShootPos;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
hor = Input.GetAxis("Horizontal");
vert = Input.GetAxis("Vertical");
if(time < kd)
{
time = time + Time.deltaTime;
}
else if (Input.GetKey(KeyCode.Space))
{
Instantiate(bullet, ShootPos.transform.position, ShootPos.transform.rotation);
time = 0;
}
}
private void FixedUpdate()
{
rb.transform.Translate(Vector2.down * speed * vert * Time.deltaTime);
rb.transform.Rotate(Vector3.back * speed * 30 * hor * Time.deltaTime);
}
private void LateUpdate()
{
campos.x = rb.transform.position.x;
campos.y = rb.transform.position.y;
Camera.main.transform.position = campos;
}
}
| 84eed2857f6cbcf35ce5286b9a76d12e755c03c0 | [
"C#"
] | 1 | C# | lyo-lya/WorldOfTanks | f6cc86204e2eb23900f822bf516e5dc7533fef45 | 808b5a6e1ee038d23f3802921d4a24cf6e94e92c | |
refs/heads/master | <file_sep>import React, { Component } from "react";
export default class CurrentWeather extends Component {
render() {
const {
temp,
city_name,
icon,
description,
date,
is_day,
error
} = this.props;
return (
<div>
<div className="current-weather__container">
<h3 className="current-weather__city">{city_name}</h3>
<div className="current-weather__tempt">
<img src={icon}/>
<div className='current-weather__tempt_heading'><h2>{temp} {city_name ? '°C' : null}</h2></div>
</div>
<span className="current-weather__text">{description}</span>
<span className="current-weather__date">{date}</span>
</div>
</div>
);
}
}
<file_sep>import React, { Component } from "react";
import DayWeather from './DayWeather';
export default class ForecastDays extends Component {
render() {
const { forecast_days } = this.props;
return (
<div className='forecast_days_container'>
{forecast_days &&
forecast_days.map((day, idx) => {
return (
<DayWeather
forecast_day={forecast_days}
day={day}
key={idx}
/>
);
})}
</div>
);
}
}
<file_sep>import React, { Component } from "react";
import GetCity from "./components/left-side/GetCity";
import CurrentWeather from "./components/left-side/CurrentWeather";
import ForeastDay from "./components/right-side/ForecastDays";
import "./App.css";
export default class App extends Component {
state = {
temp: undefined,
city_name: undefined,
icon: undefined,
description: undefined,
date: undefined,
is_day: undefined,
forecast_days: undefined,
error: undefined,
};
handleSubmit = async (e) => {
e.preventDefault();
const city = e.target.city.value;
const api_call = await fetch(
`http://api.weatherstack.com/forecast?access_key=<KEY>&query=${city}`
);
const resp = await api_call.json();
console.log(resp);
if (city) {
this.setState({
temp: resp.current.temperature,
city_name: resp.location.name,
icon: resp.current.weather_icons[0],
description: resp.current.weather_descriptions,
date: resp.forecast["2020-06-10"].date,
is_day: resp.current.is_day,
forecast_days: [],
error: "",
});
} else {
this.setState({
error: "Please enter correct valid name of city..",
});
}
console.log(city);
};
//local storage
/*saveStateToLocalStr = () => {
localStorage.setItem("data", JSON.stringify(this.state))
};
takeValueFromLocalStr = () => {
let data = localStorage.getItem("data");
city = JSON.parse(city);
this.setState({
city_name: city
});
};
componentDidMount = () => {
this.takeValueFromLocalStr();
window.addEventListener(
"beforeunload",
this.saveStateToLocalStr.bind(this)
);
};
componentWillUnmount = () => {
window.removeEventListener(
"beforeunload",
this.saveStateToLocalStr.bind(this)
);
this.saveStateToLocalStr();
};*/
render() {
return (
<div>
<div className="main">
<div className="container">
<div className="left-side">
<div className="left-side__container">
<div className="left-side__title">
<h1>My Weather</h1>
<p>Find your weather</p>
</div>
<GetCity handleSubmit={this.handleSubmit} />
<CurrentWeather
temp={this.state.temp}
city_name={this.state.city_name}
icon={this.state.icon}
description={this.state.description}
date={this.state.date}
is_day={this.state.is_day}
error={this.state.error}
/>
</div>
</div>
<div className="right-side">
<ForeastDay forecast_days={this.state.forecast_days} />
</div>
</div>
</div>
</div>
);
}
}
<file_sep>import React, { Component } from "react";
export default class GetCity extends Component {
render() {
const { handleSubmit } = this.props;
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
name="city"
className="get-city__input"
placeholder="City..."
/>
<button className="get-city__btn" type="submit">
Get weather
</button>
</form>
</div>
);
}
}
| 039c17127ce1a9eedac879b7ef36151730216a56 | [
"JavaScript"
] | 4 | JavaScript | thkobierecki/weather-app | a0d05449f117055bb4aa108aed29bf1f478b0fc1 | dae6c301365794ed26f23ee13fb3686c37f8021d | |
refs/heads/master | <repo_name>trestikp/pt_semestralka<file_sep>/src/functions/PathFinder.java
package functions;
import java.util.ArrayList;
import objects.Path;
/**
* Class finding paths of the graph
* @author <NAME> a <NAME>
*/
public class PathFinder {
private static Path[][] distancePaths;
private static Path[][] timePaths;
/**
* The main method finding the paths
* @param pat distance matrix
* @param timepat time matrix
*/
public static void pathFinding(short[][] pat, short[][] timepat) {
/*for(int y=0;y<pat.length;y++) {
for(int x=0;x<pat.length;x++) {
if(pat[y][x]==-1)
pat[y][x]=Integer.MAX_VALUE;
}
}*/
Thread threadPathFinder = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("Time paths");
PathFinder.timePaths=pathFinding(timepat);
System.out.println("Time Paths done");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
threadPathFinder.start();
System.out.println("Distance paths");
PathFinder.distancePaths=pathFinding(pat);
System.out.println("Distance Paths done");
try {
while(threadPathFinder.isAlive()) {
Thread.sleep(50);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static Path[][] pathFinding(short[][] paths ) {
final int size= paths.length;
Path[][] result= PathsInitialization(paths);
////////////////////////////////////////////////////////////
//cesty z uzlu j
for(short j=0;j<size;j++) {
boolean[] done= new boolean[size];
for(int x=0;x<j;x++) {
done[x]=true;
}
//okopirovani (pravidlo symetrie) --funguje
for(short x=0;x<j;x++) {
if(result[x][j]!=null) {
if(result[j][x]==null||
result[j][x].getValue()>result[x][j].getValue()) {
result[j][x]=new Path(result[x][j]);
}
}
}
//cesty z vrcholu actualPoint (i prvku uz je hotovo) do ostatnich vrcholu --
dijkstraAlgorithm(result, done, j, paths);
}
return result;
}
private static Path[][] PathsInitialization(short[][] paths) {
final int size= paths.length;
Path[][] result= new Path[size][size];
for(short y=0;y<size;y++) {
//okopirovani (<NAME>)
for(short x=0;x<y;x++) {
if(result[x][y]!=null) {
//reversed Path
result[y][x]=new Path(result[x][y]);
}
}
// z bodu x do x dojdu za 0 kroku
result[y][y]=new Path(y,y,(short)0);
// vytvareni novych cest
for(short x=(short) (y+1);x<size;x++) {
if(paths[y][x]!=0) {
result[y][x] = new Path(y, x, paths[y][x]);
}
}
}
return result;
}
private static void dijkstraAlgorithm(Path[][] result, boolean[] done, short j, short[][] paths) {
final int size= result.length;
int actualPoint=j;
for(short i=j;i<size;i++){
//TODO
//hledani nejmensiho ohodnoceni pro dalsi krok
short minimal=0;
for(short index=j; index<size;index++) {
if(result[j][index]!=null && !done[index]) {
if(minimal==0 || minimal>result[j][index].getValue()) {
minimal=result[j][index].getValue();
actualPoint=index;
}
}
}
done[actualPoint]=true;
// uz zname nejkratsi cestu
// ted porovnat jestli neexistuje kratsi cesta k x prvku
for(short x=0;x<size;x++) {
if(!done[x] && paths[actualPoint][x]!=0) {
if(result[j][x]==null|| //(result[j][x].getValue()>0 &&
(result[j][actualPoint].getValue()+paths[actualPoint][x])
<result[j][x].getValue()) {
Path cest=result[j][actualPoint];
result[j][x]=new Path(new ArrayList<Short>(cest.getNodeIDs()),cest.getValue());
result[j][x].addNode(x, paths[actualPoint][x]);
}
}
}
}
}
/**
* Distance paths getter
* @return distance paths matrix
*/
public static Path[][] getDistancePaths() {
return distancePaths;
}
/**
* Time paths getter
* @return time paths matrix
*/
public static Path[][] getTimePaths() {
return timePaths;
}
}<file_sep>/src/objects/HQ.java
package objects;
import java.awt.geom.Point2D;
/**
*
* Class representing the HQ
* @author <NAME> and <NAME>
*/
public class HQ extends AMansion{
/**
* HQ is the main building of our company
* @param position of the HQ
*/
public HQ(Point2D position) {
super(position);
}
/**
* Method returns text info about HQ
* @return text
*/
public String HQInfo(){
String res = "";
res += "iD: 0\n";
res += "Name: HQ\n";
res += "Location: [" + position.getX() + "," + position.getY() +"]";
return res;
}
}
<file_sep>/src/simulation/Simulation.java
package simulation;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import delivery.Order;
import delivery.Truck;
import functions.FileIO;
import objects.AMansion;
import objects.Mansion;
import objects.Path;
import objects.Pomocna;
public class Simulation {
public static final int MINUTES_IN_DAY = 1440;
public static final int START_OF_ORDERING_IN_MIN = 360;
public static final int END_OF_ORDERING_IN_MIN = 1080;
private int numDay=1;
private static final Random RAND= new Random();
/** List of mansions */
public List<AMansion> nodes;
private int actualTimeinMin=330;
/**
* Pocet kolikrat uz bylo za den provedeno objednavani
*/
private int orderingTimesDone;
/**
* Kdy naposled probihalo generovani objednavani
*/
private int lastCheckInMin;
/**
* distance/time path preference false=time true=distance
*/
public boolean distanceXorTime=false;
private final Pomocna matrix;
/** Distance paths */
public final Path[][] distancePath;
/** Time paths */
public final Path[][] timePathInMin;
private LinkedList<Order>[] ordersToDo=new LinkedList[6];
//atributy vlakna
private boolean stoped;
private boolean endSim = false;
//exponencialni rozdeleni
private static final double LAMBDA=300;
/**
* Constructor creating simulation
* @param g list of mansions
* @param matrix matrix carrier
* @param distancePaths distance paths
* @param timePaths time paths
*/
public Simulation(List<AMansion> g,Pomocna matrix,Path[][] distancePaths, Path[][] timePaths) {
this.matrix=matrix;
this.distancePath=distancePaths;
this.timePathInMin=timePaths;
this.nodes=g;
for(int i=0;i<ordersToDo.length;i++) {
ordersToDo[i]=new LinkedList<Order>();
}
}
/**
* spusti simulaci
* @param dobaCekani doba trvani jedne minuty simulace v ms
*/
public void runSimulation(int dobaCekani) {
File f = new File("statistics.xml");
f.delete();
FileIO.startStatistics(null);
Thread vlaknoSimulace = new Thread(new Runnable() {
@Override
public void run() {
try {
stoped = false;
while(true) {
if (endSim) {
return;
}
if (!stoped) {
simulationStep();
Thread.sleep(dobaCekani);
}
System.out.print("");
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
vlaknoSimulace.start();
}
/**
* Ends simulation
*/
public void endSimulation() {
endSim=true;
Truck.addToTotalStats();
FileIO.writeStatistics(Truck.launchableTrucks, Truck.trucksOnRoad, this, null);
FileIO.wholeSimAllTruckStats(null);
FileIO.endStatistics(null);
}
/**
* pozastavi simulaci
*/
public void pauseSim() {
stoped = true;
}
/**
* znovu spusti pozastavenou simulaci
*/
public void resumeSim() {
stoped = false;
}
private void simulationStep() {
if(actualTimeinMin>=MINUTES_IN_DAY) {
nextDay();
}
if(actualTimeinMin-lastCheckInMin>=5) {
orderTime();
//What is going on the road drivers?
if(!Truck.trucksOnRoad.isEmpty()) {
Truck.checkStateOnRoad(actualTimeinMin);
}
}
actualTimeinMin++;
}
private void orderTime() {
///je mezi 6. hodinou rann� a 6. ve�ern� (�as objedn�vek)
//kazdych 5 minut
lastCheckInMin=actualTimeinMin;
System.out.print("TIME= "+minToHour(actualTimeinMin));
if(actualTimeinMin>=START_OF_ORDERING_IN_MIN&&actualTimeinMin< Mansion.DEFAULT_END_OF_OPENING_IN_MIN) {
if(actualTimeinMin<END_OF_ORDERING_IN_MIN) {
generateRandomOrders();
orderingTimesDone++;
}
System.out.println("Number of orders: "+getCountOfOrders());
splitOrders();
launchAllTrucks();
}
}
private void generateRandomOrders() {
double chance= (((1/LAMBDA)*Math.exp(-orderingTimesDone/LAMBDA)))*1000;
for(int i = 1; i < matrix.mansionQuantity(); i++) {
if(((Mansion)nodes.get(i)).canOrder()){
int chancePoint = RAND.nextInt(1000);
if(chancePoint<=chance) {
Mansion orderingMansion = (Mansion) nodes.get(i);
if(orderingMansion.getCanOrderNumber() < 1){
return;
}
int amount = getRandomAmouth(orderingMansion.getCanOrderNumber());
/*Math.min(getRandomAmouth(orderingMansion.getCanOrderNumber()),orderingMansion.getCanOrderNumber());*/
ordersToDo[amount-1].add(new Order(orderingMansion,amount, false));
orderingMansion.orderCreated(amount);
}
}
}
}
private int getCountOfOrders() {
int result = 0;
for(int i=0; i < ordersToDo.length; i++) {
result+=ordersToDo[i].size();
}
return result;
}
private int getRandomAmouth(int size) {
int chance=25;
for(int i=1, addChance=25; i < size; i++, addChance-=5) {
chance+=addChance;
}
int result= RAND.nextInt(chance);
if(result < 26) {
return 1;
}
else if(result < 51) {
return 2;
}
else if(result < 71) {
return 3;
}
else if(result < 86) {
return 4;
}
else if(result < 96) {
return 5;
}
else {
return 6;
}
}
/**
* method serves to inform others about actual day of the simulation
* @return actual day of sim
*/
public int getActualDay() {
return numDay;
}
private void launchAllTrucks() {
for(int i = 0; i<Truck.launchableTrucks.size(); i++) {
if(Truck.launchableTrucks.peek().hasOrder()) {
Truck.launchableTrucks.peek().sendOnRoad(actualTimeinMin);
}
else {
break;
}
}
}
private void splitOrders() throws IndexOutOfBoundsException {
for(int index=5;index>=0;index--) {
int loadingTime = (index+1)*Truck.UNLOAD_TIME_IN_MIN;
int aproxSetOnRoad= actualTimeinMin+loadingTime;
if(ordersToDo[index].isEmpty()) {
continue;
}
for(int ind=ordersToDo[index].size()-1;ind>=0;ind--) {
if(ind >= ordersToDo[index].size()) {
ind = ordersToDo[index].size()-1;
}
Mansion o = ordersToDo[index].get(ind).getSubscriber();
int aproxTime= aproxSetOnRoad + timePathInMin[0][o.iD].getValue();
if((aproxTime) < (o.openingTimeInMin+Mansion.OPENED_TIME_IN_MIN)
&& o.openingTimeInMin <= aproxTime) {
prepareOrdersList(index, ind, aproxTime, loadingTime, o);
if(ordersToDo[index].isEmpty()) {
break;
}
}
}
}
}
private void prepareOrdersList(int index, int ind, int aproxTime, int loadingTime, Mansion o) {
Order o1 = ordersToDo[index].get(ind);
assignOrderToTruck(o1);
//after unloading package
int aproxTimeWhenDone = aproxTime+loadingTime;
o1.setProbableTime(aproxTime);
switch(index) {
case 5: break;
case 4:
additionalOrders(1, o.iD,aproxTimeWhenDone);
break;
case 3:
additionalOrders(2, o.iD,aproxTimeWhenDone);
break;
case 2:
additionalOrders(3, o.iD,aproxTimeWhenDone);
break;
case 1:
additionalOrders(4, o.iD,aproxTimeWhenDone);
break;
case 0:
additionalOrders(5, o.iD,aproxTimeWhenDone);
break;
default:
System.out.println("Tu se nikdy nedostaneme");
return;
}
}
private void additionalOrders(int neededSize, int pointID, int aproxtime) {
int orderIndex=neededSize-1;
while(orderIndex >= 0 && neededSize > 0) {
//bs to look for bigger orders if size is smaller
if(orderIndex >= neededSize) {
orderIndex=neededSize-1;
}
//No orders left, lets try "smaller" orders
if(ordersToDo[orderIndex].size() == 0) {
orderIndex--;
continue;
}
Order o=null;
if(distanceXorTime) {
o=findClosePointWithOrder(pointID, orderIndex,distancePath, aproxtime);
}
else{
o=findClosePointWithOrder(pointID, orderIndex,timePathInMin, aproxtime);
}
if(o == null) {
orderIndex--;
continue;
}else {
aproxtime+= (orderIndex+1)*Truck.UNLOAD_TIME_IN_MIN*2+timePathInMin[pointID][o.getSubscriber().iD].getValue() ;
o.setProbableTime(aproxtime);
pointID=o.getSubscriber().iD;
assignOrderToTruck(o);
neededSize-=(orderIndex+1);
}
}
}
private Order findClosePointWithOrder(int startPoint,int orderSize,Path[][] path, int aproxtime) {
int velikost=ordersToDo[orderSize].size();
int minValue= Integer.MAX_VALUE;
Order result=null;
aproxtime+=Truck.UNLOAD_TIME_IN_MIN*(orderSize+1);
for(int i=velikost-1;i>=0;i--) {
Mansion m=ordersToDo[orderSize].get(i).getSubscriber();
if(result==null|| path[startPoint][m.iD] != null &&
path[startPoint][m.iD].getValue()<minValue &&
(aproxtime) < (m.openingTimeInMin+Mansion.OPENED_TIME_IN_MIN)
&& m.openingTimeInMin >= aproxtime) {
result=ordersToDo[orderSize].get(i);
}
}
return result;
}
private void assignOrderToTruck(Order o) {
if(o==null) {
return;
}
//System.out.println("assigning orders");
if(Truck.launchableTrucks.isEmpty()) {
Truck t=new Truck();
try {
t.addOrder(o);
} catch (Exception e) {
e.printStackTrace();
}
ordersToDo[o.getAmount()-1].remove(o);
}
else {
while(!Truck.launchableTrucks.isEmpty()) {
Truck t=Truck.launchableTrucks.peek();
if(t.canLoad(o.getAmount())) {
try {
t.addOrder(o);
} catch (Exception e) {
e.printStackTrace();
}
ordersToDo[o.getAmount()-1].remove(o);
return;
}else {
t.sendOnRoad(actualTimeinMin);
}
}
if(Truck.launchableTrucks.isEmpty()) {
assignOrderToTruck(o);
}
}
}
private void nextDay() {
FileIO.writeStatistics(Truck.launchableTrucks, Truck.trucksOnRoad, this, null);
Mansion.nextDay(nodes);
Truck.nextDay();
actualTimeinMin=0;
lastCheckInMin=0;
Order.numberOfAllOrders =0;
numDay++;
System.out.println("Day "+numDay);
}
//////// Other accesories
/**
* Method for creating manual order
* @param size number of pallets
* @param mansion subscriber
*/
public void manualOrder(int size, int mansion) {
ordersToDo[size-1].add(new Order((Mansion)nodes.get(mansion),size, true));
System.out.println("CREATED MANUAL ORDER");
}
/**
* Returns day of the simulation
* @return number of day
*/
public int getDay(){
return numDay;
}
private String minToHour(int min){
String res = "";
if(min > 60){
int hours = min/60;
int minutes = min%60;
if(hours < 10){
res += "0" + hours + ":";
} else {
res += hours + ":";
}
if(minutes < 10){
res += "0" + minutes + "\n";
} else {
res += minutes + "\n";
}
} else {
if(min < 10){
res = /*min + " min.\n";*/"0:0" + min + "\n";
} else {
res = /*min + " min.\n";*/"0:" + min + "\n";
}
}
return res;
}
}
<file_sep>/src/graphics/GuiController.java
package graphics;
import delivery.Truck;
import functions.FileIO;
import functions.PathFinder;
import generation.Generator;
import generation.PathGenerator;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.util.StringConverter;
import objects.AMansion;
import objects.HQ;
import objects.Mansion;
import objects.Pomocna;
import simulation.Simulation;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
/**
* Class controlling components of GUI
* @author <NAME> and <NAME>
*/
public class GuiController {
/** Simulation speed in [ms]. Default value = 20ms */
private int simulation_speed;
/** Logical variables determining if data were imported or generated */
private boolean mansionsImported = false, matrixesImported = false, dataGenerated = false;
/** TextArea to which console is redirected */
@FXML
private TextArea consoleLog;
/** TextArea to which info about truck/ mansion is displayed */
@FXML
private TextArea infoLog;
/** TextField where number of mansions to generate is inputted */
@FXML
private TextField manCount;
/** TextField where speed of simulation is inputted */
@FXML
private TextField simSpeed;
/** Button that starts the simulation */
@FXML
private Button startBtn;
/** Button that pauses the simulation */
@FXML
private Button pauseBtn;
/** Button that stops the simulation */
@FXML
private Button stopBtn;
/** Button that resumes the simulation */
@FXML
private Button resumeBtn;
/** ComboBox to choose truck for displaying information */
@FXML
private ComboBox<Truck> truckCombo;
/** ComboBox to choose mansion for displaying information */
@FXML
private ComboBox<AMansion> manCombo;
@FXML
private Button orderBtn;
/**
* Empty constructor
*/
public GuiController(){
//prazdny constructor
}
/**
* Method for initialization
*/
@FXML
private void initialize(){
stopBtn.setDisable(true);
pauseBtn.setDisable(true);
resumeBtn.setDisable(true);
orderBtn.setDisable(true);
TextAreaConsole tac = new TextAreaConsole(consoleLog);
tac.start();
}
/**
* Action of start button
*/
@FXML
public void startAction(){
if(!dataGenerated){
if(matrixesImported && mansionsImported){
System.out.println("\n--------------Start of finding Paths--------------\n");
GUI.g = new Generator(GUI.mansions);
GUI.g.generateOpeningTimesInMin();
PathFinder.pathFinding(GUI.distanceMatrix, GUI.timeMatrix);
System.out.println("\n--------------End of finding Paths--------------\n");
GUI.sim = new Simulation(GUI.mansions,new Pomocna(GUI.distanceMatrix,GUI.timeMatrix),
PathFinder.getDistancePaths(),PathFinder.getTimePaths());
} else {
if(mansionsImported){
GUI.g = new Generator(GUI.mansions);
GUI.g.generateOpeningTimesInMin();
GUI.p = new PathGenerator(GUI.mansions);
System.out.println("Matrixes not imported! Starting generating new roads.");
long start = System.nanoTime();
GUI.p.generatePaths();
long end = System.nanoTime();
System.out.println("\n Finished generating roads in: " + (end/1000000 -start/1000000) + "ms\n");
GUI.distanceMatrix = GUI.p.getDistanceMatrix();
GUI.timeMatrix = GUI.p.getTimeMatrix();
System.out.println("\n--------------Start of generating Paths--------------\n");
PathFinder.pathFinding(GUI.distanceMatrix, GUI.timeMatrix);
System.out.println("\n--------------End of generating Paths--------------\n");
GUI.sim = new Simulation(GUI.mansions,new Pomocna(GUI.distanceMatrix,GUI.timeMatrix),
PathFinder.getDistancePaths(),PathFinder.getTimePaths());
} else {
if(matrixesImported){
System.out.println("Matrixes imported, but mansions are missing, please import mansions or" +
" generate new mansions (this will generate new roads).");
return;
} else {
System.out.println("Don't have any data. Please import or generate data.");
return;
}
}
}
}
if(!(simSpeed.getText().equals(""))){
try{
int speed = Integer.parseInt(simSpeed.getText());
if(speed < 15){
System.out.println("Speed of the simulation must be 15 or more ms!");
return;
} else {
simulation_speed = Integer.parseInt(simSpeed.getText());
}
} catch (NumberFormatException e){
System.out.println("Not a valid number! Please enter a whole number.");
return;
}
//System.out.println("CAS SIM: " + simulation_speed);
} else {
simulation_speed = 20;
}
//setManComboBox();
Thread sim = new Thread(() -> {
GUI.sim.runSimulation(simulation_speed);
try{
Thread.sleep(2);
}
catch (InterruptedException e){
e.printStackTrace();
}
});
sim.start();
while (sim.isAlive()){
setManComboBox();
}
stopBtn.setDisable(false);
pauseBtn.setDisable(false);
startBtn.setDisable(true);
}
/**
* Action of resume button
*/
@FXML
public void resumeAction() {
GUI.sim.resumeSim();
pauseBtn.setDisable(false);
stopBtn.setDisable(false);
resumeBtn.setDisable(true);
orderBtn.setDisable(true);
}
/**
* Action of stop button
*/
@FXML
public void stopAction() {
GUI.sim.endSimulation();
setTruckComboBox();
setManComboBox();
System.out.println("\n--------------End of simulation--------------\n");
resumeBtn.setDisable(true);
pauseBtn.setDisable(true);
stopBtn.setDisable(true);
orderBtn.setDisable(true);
dataInfoReset();
}
/**
* Action of pause button
*/
@FXML
public void pauseAction() {
GUI.sim.pauseSim();
setTruckComboBox();
setManComboBox();
resumeBtn.setDisable(false);
startBtn.setDisable(true);
stopBtn.setDisable(false);
pauseBtn.setDisable(true);
orderBtn.setDisable(false);
}
/**
* Action of generate button
*/
@FXML
public void generate(){
GUI.dataReset();
startBtn.setDisable(false);
truckCombo.setValue(null);
manCombo.setValue(null);
infoLog.setText("");
if(manCount.getText().equals("")){
Thread gen = new Thread(() -> GUI.runGeneration(2000));
gen.start();
//GUI.runGeneration(2000);
} else {
try{
int genCount = Integer.parseInt(manCount.getText());
if(/*Integer.parseInt(manCount.getText())*/genCount < 500 || /*Integer.parseInt(manCount.getText())*/genCount > 2000){
System.out.println("Please enter a number between 500 and 2000");
} else {
Thread gen = new Thread(() -> GUI.runGeneration(Integer.parseInt(manCount.getText())));
gen.start();
//GUI.runGeneration(Integer.parseInt(manCount.getText()));
}
} catch (NumberFormatException e){
System.out.println("Not a valid number! Please enter a whole number.");
}
}
dataGenerated = true;
}
/**
* Method to set up truck combo box
*/
private void setTruckComboBox(){
ObservableList<Truck> trucks = FXCollections.observableArrayList(Truck.trucksOnRoad);
truckCombo.setItems(trucks);
//truckCombo.setValue(null);
truckCombo.setConverter(new StringConverter<Truck>(){
@Override
public String toString(Truck t){
return "Truck id: " + t.numOfTruck;
}
@Override
public Truck fromString(String s){
return null;
}
});
truckCombo.setOnAction(event -> {
if(truckCombo.getValue() != null){
Truck t = truckCombo.getValue();
infoLog.setText(t.infoAboutTruck());
}
manCombo.setValue(null);
});
}
/**
* Method to set up mansion combo box
*/
private void setManComboBox(){
ObservableList<AMansion> mansions = FXCollections.observableArrayList(GUI.mansions);
manCombo.setItems(mansions);
//manCombo.setValue(null);
manCombo.setConverter(new StringConverter<AMansion>() {
@Override
public String toString(AMansion object) {
if(object instanceof HQ){
return "HQ";
} else {
return ((Mansion)object).name;
}
}
@Override
public AMansion fromString(String string) {
return null;
}
});
manCombo.setOnAction(event -> {
AMansion man = manCombo.getValue();
if(manCombo.getValue() != null) {
if (man instanceof HQ) {
infoLog.setText(((HQ) man).HQInfo());
} else {
infoLog.setText(((Mansion) man).mansionInfo());
}
}
truckCombo.setValue(null);
});
}
/**
* Action for import mansions option from menu
*/
@FXML
public void importMansions() {
GUI.mansions = null;
FileChooser fc = new FileChooser();
fc.setTitle("Choose mansion source");
File f = fc.showOpenDialog(consoleLog.getScene().getWindow());
if(f == null){
System.out.println("File not chosen! Terminating import!");
} else {
long start = System.nanoTime();
GUI.mansions = FileIO.importFromFile(f);
long end = System.nanoTime();
System.out.println("Imported mansions from file in " + (end/1000000 -start/1000000) +"ms.");
mansionsImported = true;
}
startBtn.setDisable(false);
}
/**
* Action for import matrixes option from menu
*/
@FXML
public void importMatrixes() {
GUI.timeMatrix = null;
GUI.distanceMatrix = null;
FileChooser fc = new FileChooser();
fc.setTitle("Choose matrixes source");
File f = fc.showOpenDialog(consoleLog.getScene().getWindow());
if(f == null){
System.out.println("File not chosen! Terminating import!");
} else {
long start = System.nanoTime();
Pomocna p = FileIO.importMatrix(f);
long end = System.nanoTime();
GUI.distanceMatrix = p.getDistanceMatrix();
GUI.timeMatrix = p.getTimeMatrix();
System.out.println("Imported matrixes from file in " + (end/1000000 -start/1000000) +"ms.");
matrixesImported = true;
}
}
/**
* Action for export option from menu
*/
@FXML
public void exportToFiles() {
DirectoryChooser dc = new DirectoryChooser();
dc.setInitialDirectory(new File(System.getProperty("user.dir")));
dc.setTitle("Choose destination");
File f = dc.showDialog(consoleLog.getScene().getWindow());
if(f == null){
System.out.println("Directory not chosen! Terminating export!");
} else {
System.out.println("Chosen dir: " + f.getPath());
if(GUI.distanceMatrix == null || GUI.timeMatrix == null){
System.out.println("Error. Matrixes are corrupted or don't exist! Please generate or import new ones.");
} else {
if(GUI.mansions == null){
System.out.println("Error. Mansions don't exist or can't be read! Please generate or import new ones.");
} else {
FileIO.exportToFile(GUI.mansions, f);
FileIO.exportMatrix(GUI.distanceMatrix, GUI.timeMatrix, f);
System.out.println("Finished exporting files. Names: matrixes.txt and mansions.txt");
}
}
}
}
/**
* Action for instruction option from menu
*/
@FXML
public void instructions() {
GUI.instructionStage();
}
/**
* Action for about option from menu
*/
@FXML
public void about(){
GUI.aboutUsStage();
}
/**
* Method that resets data about GUI
*/
private void dataInfoReset(){
dataGenerated = false;
matrixesImported = false;
mansionsImported = false;
infoLog.setText("");
}
/**
* Action for show visualization button
*/
public void showVis() {
GUI.showVisualization();
}
public void makeManualOrder() {
GUI.manualOrderStage();
}
/**
* Class used to redirect console output stream to the GUI TextArea.
*/
class TextAreaConsole {
/** Constant size of the buffer */
private static final int STRING_BUFFER = 4096;
/** Constant size of flush interval */
private static final int FLUSH_INT = 200;
/** Constant size of text displayed on the output */
private static final int MAX_TEXT_LEN = 256 * 2048; //256 znaku na radce, 2048 radek - dal se deli 2, takze realne jen 1024 radek (lepsi, rychlejsi)
/** TextArea to which the console is redirected */
private final TextArea textArea;
/** StringBuffer which contains the text of the "console" */
private final StringBuffer write = new StringBuffer();
/**
* The thread for writing the text to TextArea
*/
private final Thread writeThread = new Thread(new Runnable() {
@Override
public void run() {
while (running){
try{
Thread.sleep(FLUSH_INT);
appendText();
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
});
/**
* Output stream that writes the text
*/
private final OutputStream out = new OutputStream() {
/**
* Text to be written
*/
private final byte buffer[] = new byte[STRING_BUFFER];
/**
* Overriden method writing a single char
* @param b char to write
* @throws IOException
*/
@Override
public void write(int b) throws IOException {
if(pos == STRING_BUFFER){
flush();
}
buffer[pos] = (byte)b;
pos++;
}
/**
* Overriden method writing multiple characters
* @param b byte array of charactes
* @param off start of the text
* @param len length of the text
* @throws IOException
*/
@Override
public void write(byte[] b, int off, int len) throws IOException {
if(pos + len < STRING_BUFFER){
System.arraycopy(b, off, buffer, pos, len);
pos += len;
} else {
flush();
if(len < STRING_BUFFER){
System.arraycopy(b, off, buffer, 0 /*pos - je taky 0*/, len);
} else {
write.append(new String(b, off, len));
}
}
}
/**
* Overriden method that flushes the text
* @throws IOException
*/
@Override
public void flush() throws IOException {
synchronized (write){
write.append(new String(buffer, 0, pos));
pos = 0;
}
}
};
/** Logical run attribute */
private boolean running = false;
/** Length of the text*/
private int pos = 0;
/** Stream storing original outputs */
private PrintStream defErr, defOut;
/**
* Constructor
* @param textArea new output
*/
public TextAreaConsole(TextArea textArea){
this.textArea = textArea;
defErr = System.err;
defOut = System.out;
writeThread.setDaemon(true);
}
/**
* Start of the redirection
*/
public void start() {
PrintStream ps = new PrintStream(out, true);
//System.setErr(ps);
System.setOut(ps);
running = true;
writeThread.start();
}
/**
* Stop of the redirection
*/
public void stop(){
running = false;
System.setOut(defOut);
System.setErr(defErr);
try{
writeThread.join();
} catch (InterruptedException e){
e.printStackTrace();
}
}
/**
* Method appends text to the end of the TextArea, used in flush
*/
private void appendText(){
synchronized (write){
if(write.length() > 0){
final String s = write.toString();
write.setLength(0);
Platform.runLater(() ->{
textArea.appendText(s);
int textLen = textArea.getText().length();
if(textLen > MAX_TEXT_LEN){
textArea.setText(textArea.getText(textLen - MAX_TEXT_LEN / 2, textLen));
}
});
}
}
}
}
}
<file_sep>/javadoc/delivery/Truck.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="cs">
<head>
<!-- Generated by javadoc (1.8.0_161) on Sun Dec 02 23:27:13 CET 2018 -->
<title>Truck</title>
<meta name="date" content="2018-12-02">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Truck";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":9,"i2":10,"i3":9,"i4":10,"i5":9,"i6":9,"i7":9,"i8":10,"i9":9,"i10":10,"i11":9,"i12":10,"i13":10,"i14":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../delivery/Order.html" title="class in delivery"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../index.html?delivery/Truck.html" target="_top">Frames</a></li>
<li><a href="Truck.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">delivery</div>
<h2 title="Class Truck" class="title">Class Truck</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>delivery.Truck</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">Truck</span>
extends java.lang.Object</pre>
<div class="block">Class of the Truck for deliveries</div>
<dl>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd><NAME> and <NAME></dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.util.Queue<<a href="../delivery/Truck.html" title="class in delivery">Truck</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#launchableTrucks">launchableTrucks</a></span></code>
<div class="block">Queue of the trucks that are in HQ ready to launch</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#MAX_LOAD">MAX_LOAD</a></span></code>
<div class="block">Constant of maximum allowed load</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#numOfTruck">numOfTruck</a></span></code>
<div class="block">Number of truck (id)</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.util.List<<a href="../delivery/Truck.html" title="class in delivery">Truck</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#trucksOnRoad">trucksOnRoad</a></span></code>
<div class="block">List of the trucks that are on road</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#UNLOAD_TIME_IN_MIN">UNLOAD_TIME_IN_MIN</a></span></code>
<div class="block">Constant of time needed to unload 1 pallet</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../delivery/Truck.html#Truck--">Truck</a></span>()</code>
<div class="block">Parameterless constructor, creating instance of a truck</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#addOrder-delivery.Order-">addOrder</a></span>(<a href="../delivery/Order.html" title="class in delivery">Order</a> o)</code>
<div class="block">Method adding order to a truck</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#addToTotalStats--">addToTotalStats</a></span>()</code>
<div class="block">Write statistics when similation is ended</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#canLoad-int-">canLoad</a></span>(int size)</code>
<div class="block">Method tests if truck can load pallets</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#getmileageOfAllTrucks--">getmileageOfAllTrucks</a></span>()</code>
<div class="block">Getter for distance traveled by all trucks</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>java.util.LinkedList<<a href="../delivery/Order.html" title="class in delivery">Order</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#getOrders--">getOrders</a></span>()</code>
<div class="block">Getter for orders</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#gettimeOfAllTrucksOnRoad--">gettimeOfAllTrucksOnRoad</a></span>()</code>
<div class="block">Getter for time spent on road of all trucks</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#getTotalLoadOfAllTrucks--">getTotalLoadOfAllTrucks</a></span>()</code>
<div class="block">Getter for all pallets delivered by all trucks</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#getTotalMoneyOfAll--">getTotalMoneyOfAll</a></span>()</code>
<div class="block">Getter for total cost of all trucks</div>
</td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#hasOrder--">hasOrder</a></span>()</code>
<div class="block">Method used for finding out if truck has any orders to deliver</div>
</td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#checkStateOnRoad-int-">checkStateOnRoad</a></span>(int actualTimeInMin)</code>
<div class="block">Method finds out state of trucks on road</div>
</td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#infoAboutTruck--">infoAboutTruck</a></span>()</code>
<div class="block">Method returns text info about truck</div>
</td>
</tr>
<tr id="i11" class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#nextDay--">nextDay</a></span>()</code>
<div class="block">Method moving the trucks to the next day of simulation</div>
</td>
</tr>
<tr id="i12" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#sendOnRoad-int-">sendOnRoad</a></span>(int timeOfStartInMin)</code>
<div class="block">Method sends truck on road</div>
</td>
</tr>
<tr id="i13" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#truckTag--">truckTag</a></span>()</code>
<div class="block">Method creates truck tag used in statistics</div>
</td>
</tr>
<tr id="i14" class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../delivery/Truck.html#wholeSimStats--">wholeSimStats</a></span>()</code>
<div class="block">Method for writing stats from the whole simulation</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="MAX_LOAD">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>MAX_LOAD</h4>
<pre>public static final int MAX_LOAD</pre>
<div class="block">Constant of maximum allowed load</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../constant-values.html#delivery.Truck.MAX_LOAD">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="UNLOAD_TIME_IN_MIN">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>UNLOAD_TIME_IN_MIN</h4>
<pre>public static final int UNLOAD_TIME_IN_MIN</pre>
<div class="block">Constant of time needed to unload 1 pallet</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../constant-values.html#delivery.Truck.UNLOAD_TIME_IN_MIN">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="launchableTrucks">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>launchableTrucks</h4>
<pre>public static java.util.Queue<<a href="../delivery/Truck.html" title="class in delivery">Truck</a>> launchableTrucks</pre>
<div class="block">Queue of the trucks that are in HQ ready to launch</div>
</li>
</ul>
<a name="trucksOnRoad">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>trucksOnRoad</h4>
<pre>public static java.util.List<<a href="../delivery/Truck.html" title="class in delivery">Truck</a>> trucksOnRoad</pre>
<div class="block">List of the trucks that are on road</div>
</li>
</ul>
<a name="numOfTruck">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>numOfTruck</h4>
<pre>public int numOfTruck</pre>
<div class="block">Number of truck (id)</div>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Truck--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Truck</h4>
<pre>public Truck()</pre>
<div class="block">Parameterless constructor, creating instance of a truck</div>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="addOrder-delivery.Order-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>addOrder</h4>
<pre>public void addOrder(<a href="../delivery/Order.html" title="class in delivery">Order</a> o)
throws java.lang.Exception</pre>
<div class="block">Method adding order to a truck</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>o</code> - order that is to be added</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.Exception</code></dd>
</dl>
</li>
</ul>
<a name="sendOnRoad-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>sendOnRoad</h4>
<pre>public void sendOnRoad(int timeOfStartInMin)</pre>
<div class="block">Method sends truck on road</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>timeOfStartInMin</code> - time when the truck sets out</dd>
</dl>
</li>
</ul>
<a name="hasOrder--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>hasOrder</h4>
<pre>public boolean hasOrder()</pre>
<div class="block">Method used for finding out if truck has any orders to deliver</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>true or false</dd>
</dl>
</li>
</ul>
<a name="canLoad-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>canLoad</h4>
<pre>public boolean canLoad(int size)</pre>
<div class="block">Method tests if truck can load pallets</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>size</code> - number of pallets to be loaded</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>true or false</dd>
</dl>
</li>
</ul>
<a name="checkStateOnRoad-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>checkStateOnRoad</h4>
<pre>public static void checkStateOnRoad(int actualTimeInMin)</pre>
<div class="block">Method finds out state of trucks on road</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>actualTimeInMin</code> - time of simulation</dd>
</dl>
</li>
</ul>
<a name="getOrders--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getOrders</h4>
<pre>public java.util.LinkedList<<a href="../delivery/Order.html" title="class in delivery">Order</a>> getOrders()</pre>
<div class="block">Getter for orders</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>LinkedList of orders</dd>
</dl>
</li>
</ul>
<a name="gettimeOfAllTrucksOnRoad--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>gettimeOfAllTrucksOnRoad</h4>
<pre>public static int gettimeOfAllTrucksOnRoad()</pre>
<div class="block">Getter for time spent on road of all trucks</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>time</dd>
</dl>
</li>
</ul>
<a name="getmileageOfAllTrucks--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getmileageOfAllTrucks</h4>
<pre>public static int getmileageOfAllTrucks()</pre>
<div class="block">Getter for distance traveled by all trucks</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>distance in km</dd>
</dl>
</li>
</ul>
<a name="getTotalLoadOfAllTrucks--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTotalLoadOfAllTrucks</h4>
<pre>public static int getTotalLoadOfAllTrucks()</pre>
<div class="block">Getter for all pallets delivered by all trucks</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>number of pallets</dd>
</dl>
</li>
</ul>
<a name="getTotalMoneyOfAll--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTotalMoneyOfAll</h4>
<pre>public static int getTotalMoneyOfAll()</pre>
<div class="block">Getter for total cost of all trucks</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>cost in kc</dd>
</dl>
</li>
</ul>
<a name="nextDay--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>nextDay</h4>
<pre>public static void nextDay()</pre>
<div class="block">Method moving the trucks to the next day of simulation</div>
</li>
</ul>
<a name="addToTotalStats--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>addToTotalStats</h4>
<pre>public static void addToTotalStats()</pre>
<div class="block">Write statistics when similation is ended</div>
</li>
</ul>
<a name="infoAboutTruck--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>infoAboutTruck</h4>
<pre>public java.lang.String infoAboutTruck()</pre>
<div class="block">Method returns text info about truck</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>text info</dd>
</dl>
</li>
</ul>
<a name="truckTag--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>truckTag</h4>
<pre>public java.lang.String truckTag()</pre>
<div class="block">Method creates truck tag used in statistics</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>String tag</dd>
</dl>
</li>
</ul>
<a name="wholeSimStats--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>wholeSimStats</h4>
<pre>public static java.lang.String wholeSimStats()</pre>
<div class="block">Method for writing stats from the whole simulation</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>String of all stats</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../delivery/Order.html" title="class in delivery"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../index.html?delivery/Truck.html" target="_top">Frames</a></li>
<li><a href="Truck.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
<file_sep>/README.txt
1) Zda se mi, že se občas generování matice sousednosti zasekne v nekonečném cyklu.
-generování jsem snad fixnul, bohužel jsem si to přepsal, ale znovu jsem to opravoval, tak snad správně
2) Je potřeba dodělat výstup vlákna simulace do externího okna a také zápis do souboru.
-do externího okna je teď výpis snad všeho. Do souboru mám importy a export (trochu jsem ošetřil vstupy, ale asi by to chtělo ještě testnout,
kdyby si se nudil). Jinak cheš abych udělal výstup i cest do souboru?
3) Simulace nefunguje
-tak něják trošičku jo, to je na tobě ;)
4) Kdyby si na tom začel pracovat tak mi dej vědět na čem budeš pracovat. //TODO
5) Budeme potřebovat roztřídit ten bordel v package generation do více balíčků kvůli budoucí dokumentaci.
-naprosto souhlasím
6) Bug na trucku. Občas hodí nakládání 0 objednávek. Občas nakládá o paletu víc než má. Některé trucky mají nesmyslné doby, kdy vyrážejí na cestu.
(můj tip - někde tomu trucku v simulaci předáváš čas v s. a zapomněl si to převést na minuty). Možná spolu souvisí špatné množství palet a čas.
Také se velmi často stává, že 1 truck veze třeba 4 objednávky po 1 do stejného sídla. Nevím jestli když sídlo chce objednat 4 tak objedná 4x1 nebo co,
ale asi by to chtělo se na to podívat. ------- chyba nastava pri dni dva a více.. někde jsem na něco zapomněl (zítra na to kouknu)
7) Když začíná den, tak má 0 objednávek. Z toho jak to chápu, tak na začátku dne, v 6 hodin už by měl znát X objednávek a v průběhu dne by jich měl dostávat čím dál míň.
-------objednávky z minulých dní bych přenášel do dalších dní. A ano objednávky by měli postupně klesat podle času.
8) Když přeruším simulaci, vygeneruji nové data a spustím znovu simulaci, tak "pokračuje" v předchozí simulaci. Jestli se ti tuto nechce řešit, tak jednoduše udělám, že pokud si
zastavil simulaci, tak aby si mohl pustit novou, tak musíš restartovat program. (Což bych asi zvolil, pokud nebudem mít moře času, s čímž moc nepočítam :D)
9) GUI je na dobré cestě, když tak si ho zkus proklikat, aby si otestoval ošetření vstupů, jestli jsem nějáké zapomněl..
Stále na GUI jsou věci co vylepšovat, ale až dodělam ještě pár funkčností (hlavně menu, kde zatím fungují jen importy a exporty souborů), tak si od GUI dam pauzu,
pokud budeš na GUI chtít něco změnit/ předělat tak buď napiš nebo se s tim můžeš zkusit potrápit sám
10) Když se naimportují data ze souborů, tak simulace negeneruje Trucky. Tuto si myslím, že vím proč je, takže když tak to udělám, kdyby si na to koukal, tak řekni.
*) To je asi všechno GL
27.11
11) třeba dodělat ošetření startu simulaci bez vygenerovaných komponentů
12) umožnit zastavovani a nasledneho spousteni simulace. Hazi to chybu kdyz je otevřeno viz bod 8).. neřekl bych že je chyba v zastavování
13) při zmáčknutí tlačítka exit je třeba vypnout pomocí System.close(0) nebo jak to je a zeptat se ho zda chce ulozit do souboru
14) a zacatku každeho dne uložit výsledky do souboru (ptá se na to u odevzdavani)
15) ve třídě Truck jsou všechny statistiky potřebné jak je zadáno v zadání
<file_sep>/src/delivery/Order.java
package delivery;
import java.util.LinkedList;
import objects.Mansion;
/**
* Class of order
* @author <NAME> a <NAME>
*/
public class Order {
public static LinkedList<Order> manualOrders= new LinkedList<Order>();
/** Number of all orders */
public static int numberOfAllOrders =0;
/** Instance of the subscriber of the order */
private final Mansion subscriber;
/** Amount of pallets ordered */
private int amount;
/** Number(id) of order */
public int orderNum=0;
/** Expected time of delivery in min */
private int probableDeliveryInMin=0;
private boolean manual = false;
/**
* Constructor of the order
* @param sub mansion creating the order
* @param am amount of pallets to be ordered
*/
public Order(Mansion sub, int am, boolean manual) {
this.subscriber=sub;
this.amount=am;
numberOfAllOrders++;
this.orderNum= numberOfAllOrders;
this.manual=manual;
if(manual) {
manualOrders.add(this);
System.out.print("MANUAL ");
}
System.out.println("Order n: "+orderNum+" for "+am+" pallet has been made by mansion n: " + subscriber.iD + "!");
}
/**
* Method sets probable time of delivery
* @param timeInMin expected new time
*/
public void setProbableTime(int timeInMin) {
this.probableDeliveryInMin=timeInMin;
}
/**
* Method returns probable time of delivery
* @return time in min
*/
public int getProbableTime() {
return this.probableDeliveryInMin;
}
/**
* Getter of the amount of pallets
* @return amount
*/
public int getAmount() {
return amount;
}
/**
* Getter of the mansion creating order
* @return mansion
*/
public Mansion getSubscriber() {
return subscriber;
}
/**
* Method to give information about the order in text from.
* @return string
*/
@Override
public String toString(){
if(manual){
return " MANUAL ORDER: " + orderNum + ", by mansion: " + subscriber.iD + ", amount: " + amount + " pallets";
} else {
return " Order: " + orderNum + ", by mansion: " + subscriber.iD + ", amount: " + amount + " pallets";
}
}
}
| 94fc42945313f94051f93c4b29444e5c44e3286c | [
"Java",
"Text",
"HTML"
] | 7 | Java | trestikp/pt_semestralka | 5ddc10df2715a837bbf6ead19853567afc99f1b1 | 3ed3f8f44edbf3efc271bb5cbf0d652344501221 | |
refs/heads/master | <file_sep>#include <Servo.h>
// Declaramos la variable para controlar el servo
Servo servoMotorAbajito;
Servo servoMotorPinza;
Servo servoMotorBase;
void setup() {
// Iniciamos el monitor serie para mostrar el resultado
Serial.begin(9600);
//Motor de Base 0º a 180º
servoMotorBase.attach(7);
//Motor De abajito 120º a 180º
servoMotorAbajito.attach(8);
//Motor pinza 80º a 140º
servoMotorPinza.attach(9);
// Inicializamos al ángulo 0 el servomotor
servoMotorAbajito.write(120);
servoMotorPinza.write(80);
servoMotorBase.write(90);
}
void loop() {
for (int i = 120; i <= 180; i++)
{
servoMotorAbajito.write(i);
delay(100);
}
servoMotorPinza.write(140);
for (int i = 139; i >= 90; i--)
{
servoMotorPinza.write(i);
delay(100);
}
/*for (int i = 179; i >= 120; i--)
{
servoMotorAbajito.write(i);
delay(100);
}*/
delay(1000);
servoMotorBase.write(180);
delay(1000);
for (int i = 179; i >= 1; i--)
{
servoMotorBase.write(i);
if(i == 90){
servoMotorPinza.write(140);
}
delay(10);
}
//servoMotorPinza.write(140);
delay(4000);
servoMotorAbajito.write(120);
servoMotorPinza.write(80);
servoMotorBase.write(90);
delay(2000);
}
<file_sep>#include <Servo.h>
Servo servoMotor1;
Servo servoMotor2;
int grados;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
servoMotor1.attach(9); //motor derecho
servoMotor2.attach(8); //motor izquierdo
}
void loop() {
// put your main code here, to run repeatedly:
servoMotor1.write(40); //limite inclinado hacia atras
delay(3000);
servoMotor1.write(90); //recto
delay(3000);
servoMotor1.write(130); //limite inclinado hacia delante
delay(3000)
//grados que se mueve el motor izquierdo y limitaciones
grados=120;
while(grados<=180){
servoMotor1.write(grados);
grados=grados+5;
delay(3000);
}
//conectando la pinza en el pin 8
servoMotor2.write(80); //cierre de la pinza
delay(3000);
servoMotor2.write(140); //extension de la pinza
delay(3000);
}
<file_sep>#include <Servo.h>
// Declaramos la variable para controlar el servo
Servo servoMotorIZQ;
Servo servoMotorDER;
Servo servoMotorPinza;
Servo servoMotorBase;
void setup() {
// Iniciamos el monitor serie para mostrar el resultado
Serial.begin(9600);
//Motor de Base 0º a 180º
servoMotorBase.attach(7);
//Motor izquierdo 120º a 180º 60°para bajar pinza
servoMotorIZQ.attach(8);
//Motor derecho 80 recto 30 enderezar 120 inclinacion
servoMotorDER.attach(9);
//Motor pinza 80º a 140º
servoMotorPinza.attach(10);
// Inicializamos al ángulo 0 el servomotor
servoMotorIZQ.write(160);
servoMotorDER.write(40);
servoMotorPinza.write(80);
servoMotorBase.write(0);
}
void loop() {
delay(2000);
moverBase(0,90);
abrirPinza();
bajarBrazo();
cerrarPinza();
subirBrazo();
moverBase(90,0);
bajarBrazo();
abrirPinza();
cerrarPinza();
subirBrazo();
}
void abrirPinza(){
for (int i = 1; i <= 8; i++)
{
servoMotorPinza.write(80+(i*10));
delay(100);
}
}
void cerrarPinza(){
for (int i = 1; i <= 8; i++)
{
servoMotorPinza.write(180-(10*i));
delay(100);
}
}
void bajarBrazo(){
int x=0;
for (int i = 160; i >= 125; i--)
{
servoMotorIZQ.write(i);
servoMotorDER.write(40+x);
x++;
delay(10);
}
}
void subirBrazo(){
int x=0;
for (int i = 160; i >= 125; i--)
{
servoMotorIZQ.write(120+x);
servoMotorDER.write(75-x);
x++;
delay(10);
}
}
void moverBase(int i,int j){
if(i<=j){
for(i;i<j;i++){
servoMotorBase.write(i);
delay(10);
}
}
else{
for(i;i>=j;i--){
servoMotorBase.write(i);
delay(10);
}
}
}
<file_sep>#include <Servo.h>
Servo servoMotor1;
Servo servoMotor2;
int grados;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
servoMotor1.attach(9); //motor izquierdo
servoMotor2.attach(8); //motor derecho
}
void loop() {
// put your main code here, to run repeatedly:
/*
grados que se mueve el motor izquierdo y limitaciones
grados=125;
while(grados<=180){
servoMotor1.write(grados);
grados=grados+5;
delay(3000);
}
*/
/*
servoMotor2.write(80); //cierre de la pinza
delay(3000);
servoMotor2.write(140); //extension de la pinza
delay(3000);
*/
}
<file_sep># Robotica-Lab1
Integrantes: <NAME>,
<NAME>,
<NAME>,
<NAME>
| dc73b286b2a80f520d2bfcb029c752dd7493adc3 | [
"Markdown",
"C++"
] | 5 | C++ | ZeroRisk/Robotica-Lab1 | 1c6b5207ade624fb35f1f3289201d3bb9f195ff9 | 7cf9aa99518b2cee9d21fd33498dbac6babe7ddd | |
refs/heads/master | <repo_name>YotsaponDev/Project_bkk_api<file_sep>/Models/Permission/RoleRepository.cs
using Core.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Project_bkk_api.Models.Permission;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Todo.Models
{
public class RoleRepository : IRole
{
private DataContext _context;
private IConfiguration configuration;
public RoleRepository(DataContext context, IConfiguration iConfig)
{
_context = context;
configuration = iConfig;
}
public List<RoleEntity> GetAll()
{
return _context.role.Where(x => x.deleted_at == null).ToList();
}
public RoleEntity GetById(Guid id)
{
return _context.role.Find(id);
}
public RoleEntity Create(RoleEntity model)
{
model.id = Guid.NewGuid();
model.deleted_at = null;
_context.role.Add(model);
_context.SaveChanges();
return model;
}
public RoleEntity Update(Guid id, RoleEntity modelUpdate)
{
var data = _context.role.Find(id);
data.name = modelUpdate.name;
data.note = modelUpdate.note;
data.is_active = modelUpdate.is_active;
//data.created_by = modelUpdate.created_by;
//data.created_at = modelUpdate.created_at;
data.updated_at = DateTime.Now;
_context.SaveChanges();
return data;
}
public RoleEntity Delete(Guid id)
{
var data = _context.role.Find(id);
data.deleted_at = DateTime.Now;
_context.SaveChanges();
return data;
}
}
}
<file_sep>/Models/Permission/StaffHasRoleEntity.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Todo.Models
{
public class StaffHasRoleEntity
{
[Key]
public Guid id { get; set; }
[ForeignKey("staff_id")]
public StaffEntity Staff { get; set; }
public Guid staff_id { get; set; }
[ForeignKey("role_id")]
public RoleEntity Role { get; set; }
public Guid role_id { get; set; }
public bool is_active { get; set; }
public Guid? created_by { get; set; }
public DateTime? created_at { get; set; }
public Guid? updated_by { get; set; }
public DateTime? updated_at { get; set; }
public DateTime? deleted_at { get; set; }
}
}
<file_sep>/Models/Staff/StaffRepository.cs
using Core.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Project_bkk_api.Models.Staff;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Todo.Models
{
public class StaffRepository : IStaff
{
private DataContext _context;
private IConfiguration configuration;
public StaffRepository(DataContext context, IConfiguration iConfig)
{
_context = context;
configuration = iConfig;
}
public List<StaffEntity> GetAll()
{
return _context.staff.Where(x => x.deleted_at == null).ToList();
}
public StaffEntity GetById(Guid id)
{
return _context.staff.Find(id);
}
public StaffReturnViewModel GetByIdViaJWT(string authHeader)
{
var handler = new JwtSecurityTokenHandler();
string[] auth = authHeader.Split(" ");
var exp = handler.ReadJwtToken(auth[1]).Payload.Exp;
DateTime now = DateTime.Now;
var date = now;
var lifeTime = new JwtSecurityTokenHandler().ReadToken(auth[1]).ValidTo.ToLocalTime();
var id = handler.ReadJwtToken(auth[1]).Payload.Jti;
var staff = _context.staff.Find(Guid.Parse(id));
var data = new StaffReturnViewModel();
data.id = staff.id;
data.firstname = staff.firstname;
data.lastname = staff.lastname;
data.username = staff.username;
data.email = staff.email;
return data;
}
public StaffEntity Create(StaffEntity model)
{
var staff = _context.staff.Where(x => x.username == model.username || x.email == model.email).FirstOrDefault();
if(staff == null)
{
model.id = Guid.NewGuid();
model.deleted_at = null;
model.password = <PASSWORD>(model.password);
_context.staff.Add(model);
_context.SaveChanges();
model.password = <PASSWORD>;
return model;
}
else
{
if (staff.username == model.username)
{
throw new Exception("Username already exists");
} else if (staff.email == model.email)
{
throw new Exception("Email already exists");
}
else
{
throw new Exception("Username and Email already exists");
}
}
}
public object Login(StaffLoginViewModel model)
{
var checkPassword = <PASSWORD>ToMD5(model.password);
var staff = _context.staff.Where(x => x.username == model.username && x.password == checkPassword).FirstOrDefault();
if (staff == null)
{
throw new Exception();
}
else
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Jti, staff.id.ToString())
//new Claim(JwtRegisteredClaimNames.NameId, user.username),
//new Claim(JwtRegisteredClaimNames.GivenName, user.firstname),
//new Claim(JwtRegisteredClaimNames.FamilyName, user.lastname),
//new Claim(JwtRegisteredClaimNames.Email, user.email)
};
string key = configuration.GetSection("JWT").GetSection("SecurityKey").Value;
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var token = new JwtSecurityToken(
expires: DateTime.Now.AddSeconds(5),
claims: claims,
signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
);
// find role
var role_name = (from shr in _context.staff_has_role where shr.staff_id == staff.id
join r in _context.role on shr.role_id equals r.id into r2
from f in r2.DefaultIfEmpty()
select new {
f.name,f.id
}).ToList();
List<string> roleNameArr = new List<string>();
List<string> permissionNameArr = new List<string>();
if (role_name != null)
{
int rnC = role_name.Count;
for (int i = 0; i < rnC; i++)
{
// find permission
var pn = (from rhp in _context.role_has_permission
where rhp.role_id == role_name[i].id
join p in _context.permission on rhp.permission_id equals p.id into p2
from f in p2.DefaultIfEmpty()
select new
{
f.name,
f.id
}).ToList();
int pnC = pn.Count;
for (int j = 0; j < pnC; j++)
{
permissionNameArr.Add(pn[j].name);
}
}
}
string[] roleNameArray = roleNameArr.ToArray();
string[] permissionNameArray = permissionNameArr.ToArray();
var return_token = new {
access_token = new JwtSecurityTokenHandler().WriteToken(token),
role = roleNameArray,
permission = permissionNameArray
};
return return_token;
}
}
static string StringToMD5(string value)
{
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
UTF8Encoding utf8 = new UTF8Encoding();
byte[] data = md5.ComputeHash(utf8.GetBytes(value));
return Convert.ToBase64String(data);
}
}
public StaffEntity Update(Guid id, StaffEntity modelUpdate)
{
var data = _context.staff.Find(id);
data.firstname = modelUpdate.firstname;
data.lastname = modelUpdate.lastname;
data.is_active = modelUpdate.is_active;
//data.created_by = modelUpdate.created_by;
//data.created_at = modelUpdate.created_at;
data.updated_at = DateTime.Now;
_context.SaveChanges();
return data;
}
public StaffEntity Delete(Guid id)
{
var data = _context.staff.Find(id);
data.deleted_at = DateTime.Now;
_context.SaveChanges();
return data;
}
}
}
<file_sep>/Models/Staff/IStaff.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Todo.Models;
namespace Project_bkk_api.Models.Staff
{
public interface IStaff
{
List<StaffEntity> GetAll();
StaffEntity GetById(Guid id);
StaffReturnViewModel GetByIdViaJWT(string authHeader);
StaffEntity Create(StaffEntity model);
StaffEntity Update(Guid id, StaffEntity modelUpdate);
StaffEntity Delete(Guid id);
object Login(StaffLoginViewModel model);
}
}
<file_sep>/Data/Migrations/25620724102632_Migration001.cs
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Project_bkk_api.Data.Migrations
{
public partial class Migration001 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "laws",
columns: table => new
{
id = table.Column<Guid>(nullable: false),
name = table.Column<string>(maxLength: 255, nullable: true),
note = table.Column<string>(maxLength: 3000, nullable: true),
is_active = table.Column<bool>(nullable: true),
created_by = table.Column<Guid>(nullable: true),
created_at = table.Column<DateTime>(nullable: true),
updated_by = table.Column<Guid>(nullable: true),
updated_at = table.Column<DateTime>(nullable: true),
delete_at = table.Column<DateTime>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_laws", x => x.id);
});
migrationBuilder.CreateTable(
name: "staff",
columns: table => new
{
id = table.Column<Guid>(nullable: false),
fullname = table.Column<string>(maxLength: 255, nullable: true),
position = table.Column<int>(maxLength: 255, nullable: false),
ad_username = table.Column<string>(maxLength: 255, nullable: true),
password = table.Column<string>(maxLength: 255, nullable: true),
email = table.Column<string>(maxLength: 255, nullable: true),
tel = table.Column<string>(maxLength: 255, nullable: true),
is_active = table.Column<bool>(nullable: true),
created_by = table.Column<Guid>(nullable: true),
created_at = table.Column<DateTime>(nullable: true),
updated_by = table.Column<Guid>(nullable: true),
updated_at = table.Column<DateTime>(nullable: true),
delete_at = table.Column<DateTime>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_staff", x => x.id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "laws");
migrationBuilder.DropTable(
name: "staff");
}
}
}
<file_sep>/Models/Laws/ILaws.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Todo.Models;
namespace Project_bkk_api.Models.Laws
{
public interface ILaws
{
List<LawsEntity> GetAll();
LawsEntity GetById(Guid id);
LawsEntity Create(LawsEntity model);
LawsEntity Update(Guid id, LawsEntity modelUpdate);
LawsEntity Delete(Guid id);
}
}
<file_sep>/Data/Migrations/25620820084305_Migration005.cs
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Project_bkk_api.Data.Migrations
{
public partial class Migration005 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "permission",
columns: table => new
{
id = table.Column<Guid>(nullable: false),
name = table.Column<string>(maxLength: 255, nullable: true),
note = table.Column<Guid>(maxLength: 2000, nullable: false),
is_active = table.Column<bool>(nullable: false),
created_by = table.Column<Guid>(nullable: true),
created_at = table.Column<DateTime>(nullable: true),
updated_by = table.Column<Guid>(nullable: true),
updated_at = table.Column<DateTime>(nullable: true),
deleted_at = table.Column<DateTime>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_permission", x => x.id);
});
migrationBuilder.CreateTable(
name: "role",
columns: table => new
{
id = table.Column<Guid>(nullable: false),
name = table.Column<string>(maxLength: 255, nullable: true),
note = table.Column<Guid>(maxLength: 2000, nullable: false),
is_active = table.Column<bool>(nullable: false),
created_by = table.Column<Guid>(nullable: true),
created_at = table.Column<DateTime>(nullable: true),
updated_by = table.Column<Guid>(nullable: true),
updated_at = table.Column<DateTime>(nullable: true),
deleted_at = table.Column<DateTime>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_role", x => x.id);
});
migrationBuilder.CreateTable(
name: "role_has_permission",
columns: table => new
{
id = table.Column<Guid>(nullable: false),
role_id = table.Column<Guid>(nullable: false),
permission_id = table.Column<Guid>(nullable: false),
is_active = table.Column<bool>(nullable: false),
created_by = table.Column<Guid>(nullable: true),
created_at = table.Column<DateTime>(nullable: true),
updated_by = table.Column<Guid>(nullable: true),
updated_at = table.Column<DateTime>(nullable: true),
deleted_at = table.Column<DateTime>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_role_has_permission", x => x.id);
table.ForeignKey(
name: "FK_role_has_permission_permission_permission_id",
column: x => x.permission_id,
principalTable: "permission",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_role_has_permission_role_role_id",
column: x => x.role_id,
principalTable: "role",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "staff_has_role",
columns: table => new
{
id = table.Column<Guid>(nullable: false),
staff_id = table.Column<Guid>(nullable: false),
role_id = table.Column<Guid>(nullable: false),
is_active = table.Column<bool>(nullable: false),
created_by = table.Column<Guid>(nullable: true),
created_at = table.Column<DateTime>(nullable: true),
updated_by = table.Column<Guid>(nullable: true),
updated_at = table.Column<DateTime>(nullable: true),
deleted_at = table.Column<DateTime>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_staff_has_role", x => x.id);
table.ForeignKey(
name: "FK_staff_has_role_role_role_id",
column: x => x.role_id,
principalTable: "role",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_staff_has_role_staff_staff_id",
column: x => x.staff_id,
principalTable: "staff",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_role_has_permission_permission_id",
table: "role_has_permission",
column: "permission_id");
migrationBuilder.CreateIndex(
name: "IX_role_has_permission_role_id",
table: "role_has_permission",
column: "role_id");
migrationBuilder.CreateIndex(
name: "IX_staff_has_role_role_id",
table: "staff_has_role",
column: "role_id");
migrationBuilder.CreateIndex(
name: "IX_staff_has_role_staff_id",
table: "staff_has_role",
column: "staff_id");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "role_has_permission");
migrationBuilder.DropTable(
name: "staff_has_role");
migrationBuilder.DropTable(
name: "permission");
migrationBuilder.DropTable(
name: "role");
}
}
}
<file_sep>/Models/Permission/IRoleHasPermission.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Todo.Models;
namespace Project_bkk_api.Models.Permission
{
public interface IRoleHasPermission
{
List<RoleHasPermissionEntity> GetAll();
RoleHasPermissionEntity GetById(Guid id);
RoleHasPermissionViewModel Create(RoleHasPermissionViewModel model);
//RoleHasPermissionEntity Update(Guid id, RoleHasPermissionEntity modelUpdate);
RoleHasPermissionEntity Delete(Guid id);
}
}
<file_sep>/Models/Permission/IRole.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Todo.Models;
namespace Project_bkk_api.Models.Permission
{
public interface IRole
{
List<RoleEntity> GetAll();
RoleEntity GetById(Guid id);
RoleEntity Create(RoleEntity model);
RoleEntity Update(Guid id, RoleEntity modelUpdate);
RoleEntity Delete(Guid id);
}
}
<file_sep>/Data/Migrations/25620819082929_Migration004.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace Project_bkk_api.Data.Migrations
{
public partial class Migration004 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "fullname",
table: "staff",
newName: "username");
migrationBuilder.RenameColumn(
name: "delete_at",
table: "staff",
newName: "deleted_at");
migrationBuilder.RenameColumn(
name: "ad_username",
table: "staff",
newName: "lastname");
migrationBuilder.AlterColumn<string>(
name: "position",
table: "staff",
maxLength: 255,
nullable: true,
oldClrType: typeof(int),
oldMaxLength: 255);
migrationBuilder.AlterColumn<bool>(
name: "is_active",
table: "staff",
nullable: false,
oldClrType: typeof(bool),
oldNullable: true);
migrationBuilder.AddColumn<string>(
name: "firstname",
table: "staff",
maxLength: 255,
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "firstname",
table: "staff");
migrationBuilder.RenameColumn(
name: "username",
table: "staff",
newName: "fullname");
migrationBuilder.RenameColumn(
name: "lastname",
table: "staff",
newName: "ad_username");
migrationBuilder.RenameColumn(
name: "deleted_at",
table: "staff",
newName: "delete_at");
migrationBuilder.AlterColumn<int>(
name: "position",
table: "staff",
maxLength: 255,
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 255,
oldNullable: true);
migrationBuilder.AlterColumn<bool>(
name: "is_active",
table: "staff",
nullable: true,
oldClrType: typeof(bool));
}
}
}
<file_sep>/Controllers/LawsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Project_bkk_api.Models;
using Microsoft.Extensions.Logging;
using Core.Data;
using Todo.Models;
using Project_bkk_api.Models.Laws;
namespace Project_bkk_api.Controllers
{
[Route("api/Laws")]
public class LawsController : Controller
{
private ILogger<LawsController> _logger;
private readonly ILaws _laws;
public LawsController(ILaws laws)
{
_laws = laws;
}
/// <summary>
/// Laws get all data
/// </summary>
/// <remarks>
/// Laws get all data
/// </remarks>
/// <returns>Return all data</returns>
/// <response code="200">Returns all data</response>
/// <response code="500">Error Occurred</response>
[HttpGet("")]
[ProducesResponseType(typeof(List<LawsViewModel>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult GetAll()
{
try
{
var data = _laws.GetAll();
return Json(data);
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
/// <summary>
/// Laws get By Id
/// </summary>
/// <remarks>
/// Laws get By Id
/// </remarks>
/// <returns>Return all data</returns>
/// <response code="200">Returns the item</response>
/// <response code="500">Error Occurred</response>
[HttpGet("GetById")]
[ProducesResponseType(typeof(List<LawsViewModel>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult GetById(Guid id)
{
try
{
var data = _laws.GetById(id);
return Json(data);
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
/// <summary>
/// Laws create item
/// </summary>
/// <remarks>
/// Laws create item
/// </remarks>
/// <returns>Return create item</returns>
/// <response code="200">Returns the item</response>
/// <response code="500">Error Occurred</response>
[HttpPost]
[ProducesResponseType(typeof(List<LawsViewModel>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult Create([FromBody] LawsEntity model)
{
try
{
if (model != null)
{
_laws.Create(model);
}
return Json(model);
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
/// <summary>
/// Laws Update item
/// </summary>
/// <remarks>
/// Laws Update item
/// </remarks>
/// <returns>Return create item</returns>
/// <response code="200">Returns the item</response>
/// <response code="500">Error Occurred</response>
[HttpPut("{id}")]
[ProducesResponseType(typeof(List<LawsViewModel>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult Update(Guid id, [FromBody] LawsEntity model)
{
try
{
if (id == null)
{
return StatusCode(400, $"ID is not valid.");
}
else
{
var res = _laws.Update(id, model);
return Json(res);
}
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
/// <summary>
/// Laws Update item
/// </summary>
/// <remarks>
/// Laws Update item
/// </remarks>
/// <returns>Return create item</returns>
/// <response code="200">Returns the item</response>
/// <response code="500">Error Occurred</response>
[HttpDelete("{id}")]
[ProducesResponseType(typeof(List<LawsViewModel>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult Delete(Guid id)
{
try
{
if (id == null)
{
return StatusCode(400, $"ID is not valid.");
}
else
{
var res = _laws.Delete(id);
return Json(res);
}
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
}
}
<file_sep>/Controllers/StaffController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Project_bkk_api.Models;
using Microsoft.Extensions.Logging;
using Core.Data;
using Todo.Models;
using Project_bkk_api.Models.Staff;
using Microsoft.AspNetCore.Authorization;
using System.Net.Http.Headers;
namespace Project_bkk_api.Controllers
{
[Authorize]
[Route("api/Staff")]
public class StaffController : Controller
{
private ILogger<StaffController> _logger;
private readonly IStaff _staff;
public StaffController(IStaff staff)
{
_staff = staff;
}
/// <summary>
/// Staff get all data
/// </summary>
/// <remarks>
/// Staff get all data
/// </remarks>
/// <returns>Return all data</returns>
/// <response code="200">Returns all data</response>
/// <response code="500">Error Occurred</response>
[AllowAnonymous]
[HttpGet("")]
[ProducesResponseType(typeof(List<StaffViewModel>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult GetAll()
{
try
{
var data = _staff.GetAll();
return Json(data);
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
/// <summary>
/// Staff get By Id
/// </summary>
/// <remarks>
/// Staff get By Id
/// </remarks>
/// <returns>Return all data</returns>
/// <response code="200">Returns the item</response>
/// <response code="500">Error Occurred</response>
[AllowAnonymous]
[HttpGet("GetById")]
[ProducesResponseType(typeof(List<StaffViewModel>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult GetById(Guid id)
{
try
{
var data = _staff.GetById(id);
return Json(data);
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
/// <summary>
/// Staff get By Id via JWT
/// </summary>
/// <remarks>
/// Staff get By Id via JWT
/// </remarks>
/// <returns>Return all data</returns>
/// <response code="200">Returns the item</response>
/// <response code="500">Error Occurred</response>
[HttpGet("GetByIdViaJWT")]
[ProducesResponseType(typeof(StaffReturnViewModel), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult GetByIdViaJWT()
{
try
{
var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
if (authHeader == null)
{
throw new Exception("AuthorizationNone");
}
else
{
var data = _staff.GetByIdViaJWT(authHeader.ToString());
return Json(data);
}
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
/// <summary>
/// Staff create item
/// </summary>
/// <remarks>
/// Staff create item
/// </remarks>
/// <returns>Return create item</returns>
/// <response code="200">Returns the item</response>
/// <response code="409">Conflict</response>
[AllowAnonymous]
[HttpPost]
[ProducesResponseType(typeof(List<StaffViewModel>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(409)]
public IActionResult Create([FromBody] StaffEntity model)
{
try
{
if (model != null)
{
var x = _staff.Create(model);
return Json(x);
}
else
{
return Json(model);
}
}
catch (Exception ex)
{
return StatusCode(409, $"{ex.Message}");
}
}
/// <summary>
/// Staff Login
/// </summary>
/// <remarks>
/// Staff Login
/// </remarks>
/// <returns>Return staff login</returns>
/// <response code="200">Returns token</response>
/// <response code="500">Error Occurred</response>
[AllowAnonymous]
[Route("Login")]
[HttpPost]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
[ProducesResponseType(401)]
public IActionResult Login([FromBody] StaffLoginViewModel model)
{
try
{
if (model != null)
{
var x = _staff.Login(model);
return Json(x);
}
return null;
}
catch (Exception ex)
{
//_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(401, "LoginFailure");
}
}
/// <summary>
/// Staff Update item
/// </summary>
/// <remarks>
/// Staff Update item
/// </remarks>
/// <returns>Return create item</returns>
/// <response code="200">Returns the item</response>
/// <response code="500">Error Occurred</response>
[HttpPut("{id}")]
[ProducesResponseType(typeof(List<StaffViewModel>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult Update(Guid id, [FromBody] StaffEntity model)
{
try
{
if (id == null)
{
return StatusCode(400, $"ID is not valid.");
}
else
{
var res = _staff.Update(id, model);
return Json(res);
}
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
/// <summary>
/// Staff Update item
/// </summary>
/// <remarks>
/// Staff Update item
/// </remarks>
/// <returns>Return create item</returns>
/// <response code="200">Returns the item</response>
/// <response code="500">Error Occurred</response>
[HttpDelete("{id}")]
[ProducesResponseType(typeof(List<StaffViewModel>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult Delete(Guid id)
{
try
{
if (id == null)
{
return StatusCode(400, $"ID is not valid.");
}
else
{
var res = _staff.Delete(id);
return Json(res);
}
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
}
}
<file_sep>/Models/User/UserEntity.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Todo.Models
{
public class UserEntity
{
[Key]
public Guid id { get; set; }
[Description("ชื่อ")]
[MaxLength(255)]
public string firstname { get; set; }
[Description("นามสกุล")]
[MaxLength(255)]
public string lastname { get; set; }
[Description("ชื่อบริษัทหรือนิติบุคคล")]
[MaxLength(255)]
public string full_company_name { get; set; }
[Description("ประเภทนิติบุคคล")]
[MaxLength(255)]
public string type { get; set; }
[Description("ชื่อผู้ใช้งาน")]
[MaxLength(255)]
public string username { get; set; }
[Description("รหัสผ่าน")]
[MaxLength(255)]
public string password { get; set; }
[Description("อีเมล์")]
[MaxLength(255)]
public string email { get; set; }
[Description("สถานะการใช้งาน")]
public bool is_active { get; set; }
[Description("อีเมล์")]
public DateTime? created_at { get; set; }
[Description("วันเวลาที่แก้ไข")]
public DateTime? updated_at { get; set; }
[Description("วันเวลาที่ลบ")]
public DateTime? deleted_at { get; set; }
}
}
<file_sep>/Models/Laws/LawsRepository.cs
using Core.Data;
using Microsoft.EntityFrameworkCore;
using Project_bkk_api.Models.Laws;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Todo.Models
{
public class LawsRepository : ILaws
{
private DataContext _context;
public LawsRepository(DataContext context)
{
_context = context;
}
public List<LawsEntity> GetAll()
{
return _context.laws.Where(x => x.deleted_at == null).ToList();
}
public LawsEntity GetById(Guid id)
{
return _context.laws.Find(id);
}
public LawsEntity Create(LawsEntity model)
{
model.id = Guid.NewGuid();
model.deleted_at = null;
_context.laws.Add(model);
_context.SaveChanges();
return model;
}
public LawsEntity Update(Guid id, LawsEntity modelUpdate)
{
var data = _context.laws.Find(id);
data.name = modelUpdate.name;
data.note = modelUpdate.note;
data.is_active = modelUpdate.is_active;
//data.created_by = modelUpdate.created_by;
//data.created_at = modelUpdate.created_at;
data.updated_by = modelUpdate.updated_by;
data.updated_at = DateTime.Now;
_context.SaveChanges();
return data;
}
public LawsEntity Delete(Guid id)
{
var data = _context.laws.Find(id);
data.deleted_at = DateTime.Now;
_context.SaveChanges();
return data;
}
}
}
<file_sep>/Data/DataContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Todo.Models;
namespace Core.Data
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options){}
public DbSet<StaffEntity> staff { get; set; }
public DbSet<LawsEntity> laws { get; set; }
public DbSet<UserEntity> user { get; set; }
public DbSet<RoleEntity> role { get; set; }
public DbSet<PermissionEntity> permission { get; set; }
public DbSet<StaffHasRoleEntity> staff_has_role { get; set; }
public DbSet<RoleHasPermissionEntity> role_has_permission { get; set; }
}
}
<file_sep>/Models/Permission/IStaffHasRole.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Todo.Models;
namespace Project_bkk_api.Models.Permission
{
public interface IStaffHasRole
{
List<StaffHasRoleEntity> GetAll();
StaffHasRoleEntity GetById(Guid id);
StaffHasRoleViewModel Create(StaffHasRoleViewModel model);
//StaffHasRoleEntity Update(Guid id, StaffHasRoleEntity modelUpdate);
StaffHasRoleEntity Delete(Guid id);
}
}
<file_sep>/Controllers/RoleController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Project_bkk_api.Models;
using Microsoft.Extensions.Logging;
using Core.Data;
using Todo.Models;
using Project_bkk_api.Models.Permission;
namespace Project_bkk_api.Controllers
{
[Route("api/Role")]
public class RoleController : Controller
{
private ILogger<RoleController> _logger;
private readonly IRole _role;
public RoleController(IRole role)
{
_role = role;
}
/// <summary>
/// Role get all data
/// </summary>
/// <remarks>
/// Role get all data
/// </remarks>
/// <returns>Return all data</returns>
/// <response code="200">Returns all data</response>
/// <response code="500">Error Occurred</response>
[HttpGet("")]
[ProducesResponseType(typeof(List<RoleEntity>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult GetAll()
{
try
{
var data = _role.GetAll();
return Json(data);
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
/// <summary>
/// Role get By Id
/// </summary>
/// <remarks>
/// Role get By Id
/// </remarks>
/// <returns>Return all data</returns>
/// <response code="200">Returns the item</response>
/// <response code="500">Error Occurred</response>
[HttpGet("GetById")]
[ProducesResponseType(typeof(List<RoleEntity>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult GetById(Guid id)
{
try
{
var data = _role.GetById(id);
return Json(data);
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
/// <summary>
/// Role create item
/// </summary>
/// <remarks>
/// Role create item
/// </remarks>
/// <returns>Return create item</returns>
/// <response code="200">Returns the item</response>
/// <response code="500">Error Occurred</response>
[HttpPost]
[ProducesResponseType(typeof(List<RoleEntity>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult Create([FromBody] RoleEntity model)
{
try
{
if (model != null)
{
_role.Create(model);
}
return Json(model);
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
/// <summary>
/// Role Update item
/// </summary>
/// <remarks>
/// Role Update item
/// </remarks>
/// <returns>Return create item</returns>
/// <response code="200">Returns the item</response>
/// <response code="500">Error Occurred</response>
[HttpPut("{id}")]
[ProducesResponseType(typeof(List<RoleEntity>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult Update(Guid id, [FromBody] RoleEntity model)
{
try
{
if (id == null)
{
return StatusCode(400, $"ID is not valid.");
}
else
{
var res = _role.Update(id, model);
return Json(res);
}
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
/// <summary>
/// Role Update item
/// </summary>
/// <remarks>
/// Role Update item
/// </remarks>
/// <returns>Return create item</returns>
/// <response code="200">Returns the item</response>
/// <response code="500">Error Occurred</response>
[HttpDelete("{id}")]
[ProducesResponseType(typeof(List<RoleEntity>), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IActionResult Delete(Guid id)
{
try
{
if (id == null)
{
return StatusCode(400, $"ID is not valid.");
}
else
{
var res = _role.Delete(id);
return Json(res);
}
}
catch (Exception ex)
{
_logger.LogCritical($"Exception while get list of items.", ex);
return StatusCode(500, $"Exception while get list of items. {ex.Message}");
}
}
}
}
<file_sep>/Models/User/UserRepository.cs
using Core.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Project_bkk_api.Models.User;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Todo.Models
{
public class UserRepository : IUser
{
private DataContext _context;
private IConfiguration configuration;
public UserRepository(DataContext context, IConfiguration iConfig)
{
_context = context;
configuration = iConfig;
}
public List<UserEntity> GetAll()
{
return _context.user.Where(x => x.deleted_at == null).ToList();
}
public UserEntity GetById(Guid id)
{
return _context.user.Find(id);
}
public UserReturnViewModel GetByIdViaJWT(string authHeader)
{
var handler = new JwtSecurityTokenHandler();
string[] auth = authHeader.Split(" ");
var exp = handler.ReadJwtToken(auth[1]).Payload.Exp;
DateTime now = DateTime.Now;
var date = now;
var lifeTime = new JwtSecurityTokenHandler().ReadToken(auth[1]).ValidTo.ToLocalTime();
var id = handler.ReadJwtToken(auth[1]).Payload.Jti;
var user = _context.user.Find(Guid.Parse(id));
var data = new UserReturnViewModel();
data.id = user.id;
data.firstname = user.firstname;
data.lastname = user.lastname;
data.username = user.username;
data.full_company_name = user.full_company_name;
data.type = user.type;
data.email = user.email;
return data;
}
public UserEntity Create(UserEntity model)
{
var user = _context.user.Where(x => x.username == model.username || x.email == model.email).FirstOrDefault();
if(user == null)
{
model.id = Guid.NewGuid();
model.deleted_at = null;
model.password = <PASSWORD>MD5(model.password);
_context.user.Add(model);
_context.SaveChanges();
model.password = null;
return model;
}
else
{
if (user.username == model.username)
{
throw new Exception("Username already exists");
} else if (user.email == model.email)
{
throw new Exception("Email already exists");
}
else
{
throw new Exception("Username and Email already exists");
}
}
}
public object Login(UserLoginViewModel model)
{
var checkPassword = <PASSWORD>ToMD5(model.password);
var user = _context.user.Where(x => x.username == model.username && x.password == checkPassword).FirstOrDefault();
if (user == null)
{
throw new Exception();
}
else
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Jti, user.id.ToString())
//new Claim(JwtRegisteredClaimNames.NameId, user.username),
//new Claim(JwtRegisteredClaimNames.GivenName, user.firstname),
//new Claim(JwtRegisteredClaimNames.FamilyName, user.lastname),
//new Claim(JwtRegisteredClaimNames.Email, user.email)
};
string key = configuration.GetSection("JWT").GetSection("SecurityKey").Value;
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var token = new JwtSecurityToken(
expires: DateTime.Now.AddSeconds(5),
claims: claims,
signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
);
var return_token = new {
jwt_token = new JwtSecurityTokenHandler().WriteToken(token),
};
return return_token;
}
}
static string StringToMD5(string value)
{
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
UTF8Encoding utf8 = new UTF8Encoding();
byte[] data = md5.ComputeHash(utf8.GetBytes(value));
return Convert.ToBase64String(data);
}
}
public UserEntity Update(Guid id, UserEntity modelUpdate)
{
var data = _context.user.Find(id);
data.firstname = modelUpdate.firstname;
data.lastname = modelUpdate.lastname;
data.is_active = modelUpdate.is_active;
//data.created_by = modelUpdate.created_by;
//data.created_at = modelUpdate.created_at;
data.updated_at = DateTime.Now;
_context.SaveChanges();
return data;
}
public UserEntity Delete(Guid id)
{
var data = _context.user.Find(id);
data.deleted_at = DateTime.Now;
_context.SaveChanges();
return data;
}
}
}
<file_sep>/Models/Permission/StaffHasRoleRepository.cs
using Core.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Project_bkk_api.Models.Permission;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Todo.Models
{
public class StaffHasRoleRepository : IStaffHasRole
{
private DataContext _context;
private IConfiguration configuration;
public StaffHasRoleRepository(DataContext context, IConfiguration iConfig)
{
_context = context;
configuration = iConfig;
}
public List<StaffHasRoleEntity> GetAll()
{
return _context.staff_has_role.Where(x => x.deleted_at == null).ToList();
}
public StaffHasRoleEntity GetById(Guid id)
{
return _context.staff_has_role.Find(id);
}
public StaffHasRoleViewModel Create(StaffHasRoleViewModel model)
{
var shrEn = new StaffHasRoleEntity();
shrEn.id = Guid.NewGuid();
shrEn.role_id = model.role_id;
shrEn.staff_id = model.staff_id;
shrEn.is_active = model.is_active;
shrEn.created_by = model.created_by;
shrEn.created_at = model.created_at;
shrEn.updated_at = model.updated_at;
shrEn.updated_by = model.updated_by;
_context.staff_has_role.Add(shrEn);
_context.SaveChanges();
model.id = shrEn.id;
return model;
}
//public StaffHasRoleEntity Update(Guid id, StaffHasRoleEntity modelUpdate)
//{
// var data = _context.staff_has_role.Find(id);
// //data.created_by = modelUpdate.created_by;
// //data.created_at = modelUpdate.created_at;
// data.updated_at = DateTime.Now;
// _context.SaveChanges();
// return data;
//}
public StaffHasRoleEntity Delete(Guid id)
{
var data = _context.staff_has_role.Find(id);
data.deleted_at = DateTime.Now;
_context.SaveChanges();
return data;
}
}
}
<file_sep>/Models/Staff/StaffViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Todo.Models
{
public class StaffViewModel
{
public Guid id { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
public string position { get; set; }
public string username { get; set; }
public string password { get; set; }
public string email { get; set; }
public string tel { get; set; }
public bool is_active { get; set; }
public Guid? created_by { get; set; }
public DateTime? created_at { get; set; }
public Guid? updated_by { get; set; }
public DateTime? updated_at { get; set; }
public DateTime? deleted_at { get; set; }
}
}
<file_sep>/Models/User/IUser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Todo.Models;
namespace Project_bkk_api.Models.User
{
public interface IUser
{
List<UserEntity> GetAll();
UserEntity GetById(Guid id);
UserReturnViewModel GetByIdViaJWT(string authHeader);
UserEntity Create(UserEntity model);
UserEntity Update(Guid id, UserEntity modelUpdate);
UserEntity Delete(Guid id);
object Login(UserLoginViewModel model);
}
}
| c93a32deece8c9b990694edf06a0fb5ae9bfd3eb | [
"C#"
] | 21 | C# | YotsaponDev/Project_bkk_api | 01acf8eb0e4e65dcefbc849268a169bf9246e0a6 | 7d7163cc2f2a22db2f3f9c1b55117ab570e10519 | |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ControladorServlet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import servicios.DtUsuario;
import servicios.PublicadorAltaPropuesta;
import servicios.PublicadorAltaPropuestaService;
/**
*
* @author Martin
*/
@WebServlet(name = "ServletAltaPropuest", urlPatterns = {"/ServletAltaPropuesta"})
@MultipartConfig
public class ServletAltaPropuesta extends HttpServlet {
public static final String MENSAJE_ERROR = "mensaje_error";
public static final String MENSAJE_EXITO = "mensaje_exito";
private String MENSAJE;
private PublicadorAltaPropuesta port;
private RegistroSitio RS = new RegistroSitio();
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
public void init() throws ServletException {
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
configuracion conf = new configuracion();
ServletContext context;
context = request.getServletContext();
String ruta = context.getResource("").getPath();
URL url = new URL("http://" + conf.obtenerServer("servidor", ruta) + conf.leerProp("sAltaPropuesta", ruta));
PublicadorAltaPropuestaService webService = new PublicadorAltaPropuestaService(url);
this.port = webService.getPublicadorAltaPropuestaPort();
DtUsuario usuLogeado = (DtUsuario) request.getSession().getAttribute("usuario_logueado");
if (usuLogeado == null) {
request.getRequestDispatcher("iniciar-sesion").forward(request, response);
} else {
if (usuLogeado.isEsproponente()) {
SimpleDateFormat fechaA = new SimpleDateFormat("yyyy-MM-dd");
String fActual = fechaA.format(new Date());
request.setAttribute("FechaActual", fActual);
List<String> listCat = this.port.listarCategorias().getListCategoria();
request.setAttribute("listCat", listCat);
String browserDetails = request.getHeader("User-Agent");
String IP;
try (final DatagramSocket socket = new DatagramSocket()) {
socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
IP = socket.getLocalAddress().getHostAddress();
}
String URL = "http://" + RS.obtenerIP() + "/CulturarteWeb/ServletAltaPropuesta";
RS.ObtenerRegistro(browserDetails, IP, URL);
request.getRequestDispatcher("Vistas/AltaPropuesta.jsp").forward(request, response);
} else {
request.setAttribute("mensaje", "Usted no tiene permiso para crear una propuesta");
request.getRequestDispatcher("Vistas/Mensaje_Recibido.jsp").forward(request, response);
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String titulo = request.getParameter("TituloP");
String lugar = request.getParameter("LugarP");
String desc = request.getParameter("Descripcion");
String cat = request.getParameter("Categoria");
String tipoR = request.getParameter("TipoR");
float montoT = Float.parseFloat(request.getParameter("MontoT"));
float montoE = Float.parseFloat(request.getParameter("MontoE"));
String fechaR = (request.getParameter("FechaR") == null ? "" : request.getParameter("FechaR"));
final Part partImagen = request.getPart("imagen");
byte[] bytes = null;
if (partImagen.getSize() != 0) {
InputStream data = partImagen.getInputStream();
final String fileName = Utils.getFileName(partImagen);
String nombreArchivo = titulo;
String extensionArchivo = Utils.extensionArchivo(fileName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int reads = data.read();
while (reads != -1) {
baos.write(reads);
reads = data.read();
}
bytes = baos.toByteArray();
}
try {
DtUsuario dtLogeado = (DtUsuario) request.getSession().getAttribute("usuario_logueado");
boolean encontrado = port.seleccionarUC(dtLogeado.getNickname(), cat);
if (!encontrado) {
boolean ok = false;
if (bytes != null) {
ok = port.crearPropuesta(titulo, desc, lugar, fechaR, montoE, montoT, tipoR);
} else {
ok = port.crearPropuesta(titulo, desc, lugar, fechaR, montoE, montoT, tipoR);
}
if (ok) {
MENSAJE = "Se registro exitosamente";
request.setAttribute("mensaje", MENSAJE);
} else {
MENSAJE = "No se pudo registrar";
request.setAttribute("mensaje", MENSAJE);
}
request.getRequestDispatcher("/Vistas/FuncionamientoCorrecto.jsp").forward(request, response);
}
} catch (ExceptionInInitializerError | Exception a) {
String mensajeError = "La propuesta no pudo ser dada de alta";
request.setAttribute("mensaje", a.getMessage());
request.getRequestDispatcher("/Vistas/FuncionamientoCorrecto.jsp").forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>===============================SCRIPT APLICACION WEB====================================
1- Pegar script en carpeta de proyecto
2- archivo config.properties copiar en carpeta web del proyecto
========================================================================================<file_sep>function validarPropuesta() {
var correcto = true;
var titulo = $('#TituloP').val();
if (titulo.length < 4) {
$('#error_TituloP').show();
correcto = false;
} else
$('#error_TituloP').hide();
var lugar = $('#LugarP').val();
if (lugar.length < 4) {
$('#error_LugarP').show();
correcto = false;
} else {
$('#error_LugarP').hide();
}
var montoT = $('#MontoT').val();
if (montoT === '') {
$('#error_MontoT').show();
correcto = false;
} else {
$('#error_MontoT').hide();
}
var montoE = $('#MontoE').val();
if (montoE === '') {
$('#error_MontoE').show();
correcto = false;
} else {
$('#error_MontoE').hide();
}
return correcto;
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ControladorServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.URL;
import java.util.List;
import javax.servlet.ServletContext;
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 servicios.DtUsuario;
import servicios.PublicadorConsultarUsuario;
import servicios.PublicadorConsultarUsuarioService;
/**
*
* @author PabloDesk
*/
@WebServlet(name = "RankingUsuarios", urlPatterns = {"/RankingUsuarios"})
public class RankingUsuarios extends HttpServlet {
private PublicadorConsultarUsuario port;
private static final long serialVersionUID = 1L;
private RegistroSitio RS = new RegistroSitio();
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RS = new RegistroSitio();
response.setContentType("text/html;charset=UTF-8");
configuracion conf = new configuracion();
ServletContext context;
context = request.getServletContext();
String ruta = context.getResource("").getPath();
URL url = new URL("http://" + conf.obtenerServer("servidor", ruta) + conf.leerProp("sConsultaUsuario", ruta));
PublicadorConsultarUsuarioService webService = new PublicadorConsultarUsuarioService(url);
this.port = webService.getPublicadorConsultarUsuarioPort();
List<DtUsuario> lista = this.port.listarUsuariosRanking().getLista();
request.setAttribute("UsuariosRanking", lista);
String browserDetails = request.getHeader("User-Agent");
String IP;
try (final DatagramSocket socket = new DatagramSocket()) {
socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
IP = socket.getLocalAddress().getHostAddress();
}
String URL = "http://" + RS.obtenerIP() + "/CulturarteWeb/RankingUsuarios";
RS.ObtenerRegistro(browserDetails, IP, URL);
request.getRequestDispatcher("Vistas/RankingUsuarios.jsp").forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>package ControladorServlet;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.URL;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import servicios.DtColaboraciones;
import servicios.DtUsuario;
import servicios.DtinfoColaborador;
import servicios.DtinfoPropuesta;
import servicios.PublicadorConsultarUsuario;
import servicios.PublicadorConsultarUsuarioService;
import java.net.InetAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import servicios.Exception_Exception;
import servicios.PublicadorInicio;
/**
*
* @author gabri
*/
@WebServlet("/ServletConsultarUsuario")
public class ServletConsultarUsuario extends HttpServlet {
private PublicadorConsultarUsuario port = null;
private PublicadorInicio port2;
private RegistroSitio RS = new RegistroSitio();
configuracion conf = new configuracion();
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
public void init() throws ServletException {
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context;
context = request.getServletContext();
String ruta = context.getResource("").getPath();
URL url = new URL("http://" + conf.obtenerServer("servidor", ruta) + conf.leerProp("sConsultaUsuario", ruta));
PublicadorConsultarUsuarioService webService = new PublicadorConsultarUsuarioService(url);
this.port = webService.getPublicadorConsultarUsuarioPort();
response.setContentType("text/html;charset=UTF-8");
if (port.listarUsuarios().getLista().isEmpty()) {
request.setAttribute("mensaje", "No existen usuarios en el sistema");
request.getRequestDispatcher("/Vistas/Mensaje_Recibido.jsp").forward(request, response);
}
List<DtUsuario> usuarios = this.port.listarUsuarios().getLista();
request.setAttribute("Usuarios", usuarios);
String browserDetails = request.getHeader("User-Agent");
String IP;
try (final DatagramSocket socket = new DatagramSocket()) {
socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
IP = socket.getLocalAddress().getHostAddress();
}
String a = RS.obtenerIP();
String URL = "http://" + RS.obtenerIP() + "/CulturarteWeb/ServletConsultarUsuario";
RS.ObtenerRegistro(browserDetails, IP, URL);
request.getRequestDispatcher("Vistas/ConsultarPerfilUsuario.jsp").forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context;
context = request.getServletContext();
String ruta = context.getResource("").getPath();
String accion = (String) request.getParameter("accion");
URL url = new URL("http://" + conf.obtenerServer("servidor", ruta) + conf.leerProp("sConsultaUsuario", ruta));
PublicadorConsultarUsuarioService webService = new PublicadorConsultarUsuarioService(url);
this.port = webService.getPublicadorConsultarUsuarioPort();
//****************************************************************
if (accion != null) {
String nombre = (String) request.getParameter("nombre");
String correo = (String) request.getParameter("correo");
try {
System.out.print(nombre);
if (nombre != null) {
nombre = nombre.replace(" ", "");
boolean esta = port.existeNombreUser(nombre);
if (esta) {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("esta");
return;
} else {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("noesta");
return;
}
} else if (correo != null) {
correo = correo.replace(" ", "");
boolean esta = port.existeCorreoUser(correo);
if (esta) {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("esta");
return;
} else {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("noesta");
return;
}
}
} catch (Exception_Exception ex) {
Logger.getLogger(ServletConsultarUsuario.class.getName()).log(Level.SEVERE, null, ex);
}
}
//****************************************************************
try {
String nickname = request.getParameter("nick");
DtUsuario dtu = this.port.obtenerDtUsuario(nickname);
List<DtUsuario> seguidos = this.port.obtenerSeguidos(nickname).getLista();
List<DtUsuario> seguidores = this.port.obtenerSeguidores(nickname).getLista();
List<DtinfoPropuesta> favoritas = this.port.obtenerFavoritas(nickname).getLista();
request.setAttribute("Seguidos", seguidos);
request.setAttribute("Seguidores", seguidores);
request.setAttribute("Usuario", dtu);
request.setAttribute("Favoritas", favoritas);
DtUsuario nick = (DtUsuario) request.getSession().getAttribute("usuario_logueado");
if (dtu.isEsproponente()) {
List<DtinfoPropuesta> propuestas = this.port.listarPropuestasNoIngresadas(nickname).getLista();
request.setAttribute("Propuestas", propuestas);
if (nick != null) {
if (dtu.getNickname().equals(nick.getNickname())) {
List<DtinfoPropuesta> propuestasing = this.port.listarPropuestasDeProponenteX(nickname).getLista();
request.setAttribute("Propuestas2", propuestasing);
}
}
} else {
List<DtinfoPropuesta> colaboraciones = this.port.verPropuestas(nickname).getLista();
DtinfoColaborador dtc = this.port.getDtColaborador(nickname);
List<DtColaboraciones> monto = this.port.getMontoColaboracion(dtc.getNickname()).getLista();
request.setAttribute("Colaborador", monto);
request.setAttribute("Colaboraciones", colaboraciones);
}
} catch (ExceptionInInitializerError | Exception a) {
String mensajeError = "No se puede visualizar la informacion";
request.setAttribute("mensaje", mensajeError);
request.getRequestDispatcher("Vistas/ConsultarPerfilUsuario2.jsp").forward(request, response);
}
request.getRequestDispatcher("Vistas/ConsultarPerfilUsuario2.jsp").forward(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ControladorServlet;
import static java.lang.Math.log;
import java.net.MalformedURLException;
import java.net.URL;
import servicios.DtListConsultaPropuesta;
import servicios.DtListPropuestaWeb;
import servicios.Exception_Exception;
import servicios.PublicadorInicio;
import servicios.PublicadorInicioService;
/**
*
* @author gabri
*/
public class RegistroSitio {
private String ip;
private String navegador;
private String sitio;
private String SO;
private PublicadorInicioService PI;
private PublicadorInicio port;
public RegistroSitio() {
this.SO = "";
this.navegador = "";
this.sitio = "";
this.ip = "";
PI = new PublicadorInicioService();
port = PI.getPublicadorInicioPort();
}
public String getIp() {
return ip;
}
public String getNave() {
return navegador;
}
public String getSitio() {
return sitio;
}
public String getSO() {
return SO;
}
public void ObtenerRegistro(String browserDetails, String IP, String URL) {
this.ip = IP;
this.sitio = URL;
String userAgent = browserDetails;
String user = userAgent.toLowerCase();
String os = "";
String browser = "";
if (userAgent.toLowerCase().indexOf("windows") >= 0) {
os = "Windows";
} else if (userAgent.toLowerCase().indexOf("mac") >= 0) {
os = "Mac";
} else if (userAgent.toLowerCase().indexOf("x11") >= 0) {
os = "Unix";
} else if (userAgent.toLowerCase().indexOf("android") >= 0) {
os = "Android";
} else if (userAgent.toLowerCase().indexOf("iphone") >= 0) {
os = "IPhone";
} else {
os = "desconocido";
}
//===============Browser===========================
if (user.contains("msie")) {
String substring = userAgent.substring(userAgent.indexOf("MSIE")).split(";")[0];
browser = substring.split(" ")[0].replace("MSIE", "IE") + "-" + substring.split(" ")[1];
} else if (user.contains("safari") && user.contains("version")) {
browser = "Safari";
} else if (user.contains("opr") || user.contains("opera")) {
if (user.contains("opera")) {
browser = "Opera";
} else if (user.contains("opr")) {
browser = ((userAgent.substring(userAgent.indexOf("OPR")).split(" ")[0]).replace("/", "-")).replace("OPR", "Opera");
}
} else if (user.contains("chrome")) {
browser = "Google Chrome";
} else if (user.contains("firefox")) {
browser = "Mozilla Firefox";
} else if (user.contains("rv")) {
browser = "Internet Explorer";
} else {
browser = "desconocido";
}
this.SO = os;
this.navegador = browser;
port.agregarRegistro(ip, navegador, sitio, SO);
}
public String obtenerIP() throws MalformedURLException {
return port.leerPropiedades("Ip");
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ControladorServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
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 servicios.DtinfoPropuesta;
import servicios.PublicadorAltaPropuesta;
import servicios.PublicadorAltaPropuestaService;
import servicios.PublicadorConsultarPropuesta;
import servicios.PublicadorConsultarPropuestaService;
/**
*
* @author gabri
*/
@WebServlet(name = "ServletPropuestaCategoria", urlPatterns = {"/ServletPropuestaCategoria"})
public class ServletPropuestaCategoria extends HttpServlet {
private PublicadorConsultarPropuesta port;
private PublicadorAltaPropuesta portCat;
private RegistroSitio RS = new RegistroSitio();
configuracion conf = new configuracion();
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
public void init() throws ServletException {
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context;
context = request.getServletContext();
String ruta = context.getResource("").getPath();
URL url = new URL("http://" + conf.obtenerServer("servidor", ruta) + conf.leerProp("sConsultaPropuesta", ruta));
String browserDetails = request.getHeader("User-Agent");
String IP;
try (final DatagramSocket socket = new DatagramSocket()) {
socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
IP = socket.getLocalAddress().getHostAddress();
}
String URL = "http://" + RS.obtenerIP() + "/CulturarteWeb/ServletPropuestaCategoria";
RS.ObtenerRegistro(browserDetails, IP, URL);
PublicadorConsultarPropuestaService webService = new PublicadorConsultarPropuestaService(url);
this.port = webService.getPublicadorConsultarPropuestaPort();
URL urlP = new URL("http://" + conf.obtenerServer("servidor", ruta) + conf.leerProp("sAltaPropuesta", ruta));
PublicadorAltaPropuestaService webServiceP = new PublicadorAltaPropuestaService(urlP);
this.portCat = webServiceP.getPublicadorAltaPropuestaPort();
response.setContentType("text/html;charset=UTF-8");
List<String> categorias = this.portCat.listarCategorias().getListCategoria();
request.setAttribute("Categorias", categorias);
request.getRequestDispatcher("Vistas/PropuestaporCategoria.jsp").forward(request, response);;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String nombre = request.getParameter("cat");
request.setAttribute("nombre", nombre);
List<DtinfoPropuesta> propuestas = this.port.listarPropuestasCategoria(nombre).getLista();
if (propuestas.isEmpty()) {
request.setAttribute("mensaje", "No existen propuestas de esa categoria");
request.getRequestDispatcher("/Vistas/Mensaje_Recibido.jsp").forward(request, response);
}
request.setAttribute("Propuestas", propuestas);
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ControladorServlet;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
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 servicios.DtUsuario;
import servicios.PublicadorConsultarUsuario;
import servicios.PublicadorConsultarUsuarioService;
/**
*
* @author PabloDesk
*/
@WebServlet(name = "SeguirUsuario", urlPatterns = {"/SeguirUsuario"})
public class SeguirUsuario extends HttpServlet {
private PublicadorConsultarUsuario port;
private static final long serialVersionUID = 1L;
private RegistroSitio RS= new RegistroSitio();
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RS = new RegistroSitio();
response.setContentType("text/html;charset=UTF-8");
configuracion conf = new configuracion();
ServletContext context;
context = request.getServletContext();
String ruta = context.getResource("").getPath();
URL url = new URL("http://" + conf.obtenerServer("servidor", ruta) + conf.leerProp("sConsultaUsuario", ruta));
PublicadorConsultarUsuarioService webService = new PublicadorConsultarUsuarioService(url);
this.port = webService.getPublicadorConsultarUsuarioPort();
if (request.getSession().getAttribute("usuario_logueado") == null) {
request.setAttribute("mensaje", "No existe una sesion en el sistema");
request.getRequestDispatcher("/Vistas/Mensaje_Recibido.jsp").forward(request, response);
} else {
List<DtUsuario> lista = this.port.listarUsuarios().getLista();
request.setAttribute("usuarios", lista);
String browserDetails = request.getHeader("User-Agent");
String IP;
try(final DatagramSocket socket = new DatagramSocket()){
socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
IP = socket.getLocalAddress().getHostAddress();
}
String URL = "http://" + RS.obtenerIP() + "/CulturarteWeb/SeguirUsuario";
RS.ObtenerRegistro(browserDetails, IP, URL);
request.getRequestDispatcher("Vistas/SeguirUsuario.jsp").forward(request, response);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
configuracion conf = new configuracion();
ServletContext context;
context = request.getServletContext();
String ruta = context.getResource("").getPath();
URL url = new URL("http://" + conf.obtenerServer("servidor", ruta) + "/servicioConsultaU");
PublicadorConsultarUsuarioService webService = new PublicadorConsultarUsuarioService(url);
this.port = webService.getPublicadorConsultarUsuarioPort();
DtUsuario usuario = Login.getUsuarioSesion(request);
if (usuario != null) {
String seguidor = usuario.getNickname();
String seguido = request.getParameter("seguido");
String accion = request.getParameter("accion");
if (accion != null) {
if (accion.equals("seguir")) {
try {
this.port.seguirUsuario(seguidor, seguido);
usuario.getSeguidos().add(seguido);
request.setAttribute("solicitudseguir", "Usuario Seguido con Exito!!!");
} catch (Exception ex) {
Logger.getLogger(SeguirUsuario.class.getName()).log(Level.SEVERE, null, ex);
request.setAttribute("solicitudseguir", ex.getMessage());
}
} else if (accion.equals("dejarseguir")) {
try {
this.port.dejarSeguirUsuario(seguidor, seguido);
usuario.getSeguidos().remove(seguido);
request.setAttribute("solicitudseguir", "Finalizacion de Seguimineto realizada con Exito!!!");
} catch (Exception ex) {
Logger.getLogger(SeguirUsuario.class.getName()).log(Level.SEVERE, null, ex);
request.setAttribute("solicitudseguir", ex.getMessage());
}
}
processRequest(request, response);
} else if (request.getParameter("BuscarUsu") != null) {
List<DtUsuario> lista = this.port.listarUsuarios().getLista();
ArrayList<DtUsuario> retorno = new ArrayList<>();
for (int i = 0; i < lista.size(); i++) {
if (lista.get(i).getNickname().contains(request.getParameter("BuscarUsu"))) {
retorno.add(lista.get(i));
}
}
if (!retorno.isEmpty()) {
request.setAttribute("usuarios", retorno);
request.getRequestDispatcher("/Vistas/SeguirUsuario.jsp").forward(request, response);
} else {
request.setAttribute("mensaje", "Ese Usuario no existe en el sistema");
request.getRequestDispatcher("/Vistas/Mensaje_Recibido.jsp").forward(request, response);
}
}
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ControladorServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
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 logica.Clases.DtUsuario;
import logica.Clases.TipoRetorno;
import logica.Fabrica;
/**
*
* @author Martin
*/
@WebServlet(name = "ServletAltaPropuest", urlPatterns = {"/ServletAltaPropuesta"})
public class ServletAltaPropuesta extends HttpServlet {
public static final String MENSAJE_ERROR = "mensaje_error";
public static final String MENSAJE_EXITO = "mensaje_exito";
private String MENSAJE;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> listCat = Fabrica.getInstance().getControladorPropCat().ListarCategorias();
request.setAttribute("listCat", listCat);
request.getRequestDispatcher("Vistas/AltaPropuesta.jsp").forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String opcion = "1"; //request.getParameter("opcion");
switch (opcion) {
case "1":
String titulo = request.getParameter("TituloP");
String lugar = request.getParameter("LugarP");
String desc = request.getParameter("Descripcion");
float montoT = Float.parseFloat(request.getParameter("MontoT"));
float montoE = Float.parseFloat(request.getParameter("MontoE"));
String fechaR = (request.getParameter("FechaR") == null ? "" : request.getParameter("FechaR"));
String cat = request.getParameter("Categoria");
Calendar fecha = new GregorianCalendar();
DateFormat formato = new SimpleDateFormat("yyyy/mm/dd");
try {
//DtUsuario dtLogeado = (DtUsuario) request.getSession().getAttribute("usuario_logeado");
DtUsuario dtLogeado = new DtUsuario("mbusca", "", "", "", fecha, "","",false);
boolean encontrado = Fabrica.getInstance().getControladorPropCat().seleccionarUC(dtLogeado.getNickName(), cat);
if (!encontrado) {
boolean ok = Fabrica.getInstance().getControladorPropCat().crearPropuesta(titulo, desc, lugar, cat, fecha, montoE, montoT, TipoRetorno.EntGan);
MENSAJE = "Se registro exitosamente";
request.setAttribute("mensaje", MENSAJE);
request.getRequestDispatcher("/Vistas/FuncionamientoCorrecto.jsp").forward(request, response);
}
} catch (ExceptionInInitializerError | Exception a) {
String mensajeError = "La propuesta no pudo ser dada de alta";
request.setAttribute("mensaje", mensajeError);
request.getRequestDispatcher("/Vistas/FuncionamientoCorrecto.jsp").forward(request, response);
}
break;
}
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$('#filtro-estado').click(function () {
var tipo = "estado";
var busqueda = $("#busqueda").val();
$.ajax({
url: "/CulturarteWeb/servletBuscador",
// la información a enviar
// (también es posible utilizar una cadena de datos)
data: {"filtro": tipo,
"busqueda": busqueda},
// especifica si será una petición POST o GET
type: 'GET',
success: function (data) {
for (var i = 0; i < data.length; i++) {
document.querySelector("#elemento" + i + " .Titulo").innerHTML = data[i].Titulo;
document.querySelector("#elemento" + i + " .Lugar").innerHTML = data[i].Lugar;
document.querySelector("#elemento" + i + " .Descripcion").innerHTML = data[i].Descripcion;
document.querySelector("#elemento" + i + " .Estado").innerHTML = data[i].estado;
}
}
});
});
$('#filtro-fecha').click(function () {
var tipo = "fecha";
var busqueda = $('#busqueda').val();
$.ajax({
url: "/CulturarteWeb/servletBuscador",
// la información a enviar
// (también es posible utilizar una cadena de datos)
data: {"filtro": tipo,
"busqueda": busqueda},
// especifica si será una petición POST o GET
type: 'GET',
success: function (data) {
for (var i = 0; i < data.length; i++) {
document.querySelector("#elemento" + i + " .Titulo").innerHTML = data[i].Titulo;
document.querySelector("#elemento" + i + " .Lugar").innerHTML = data[i].Lugar;
document.querySelector("#elemento" + i + " .Descripcion").innerHTML = data[i].Descripcion;
document.querySelector("#elemento" + i + " .Estado").innerHTML = data[i].estado;
}
}
});
});
$('#filtro-alfa').click(function () {
var tipo = "alfa";
var busqueda = $('#busqueda').val();
var cantidad = $("#cantidad").val();
$.ajax({
url: "/CulturarteWeb/servletBuscador",
// la información a enviar
// (también es posible utilizar una cadena de datos)
data: {
"filtro": tipo,
"busqueda": busqueda},
// especifica si será una petición POST o GET
type: 'GET',
success: function (data) {
for (var i = 0; i < data.length; i++) {
document.querySelector("#elemento" + i + " .Titulo").innerHTML = data[i].Titulo;
document.querySelector("#elemento" + i + " .Lugar").innerHTML = data[i].Lugar;
document.querySelector("#elemento" + i + " .Descripcion").innerHTML = data[i].Descripcion;
document.querySelector("#elemento" + i + " .Estado").innerHTML = data[i].estado;
}
},
error: function (error) {
console.log(error);
}
});
});
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ControladorServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
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 servicios.DtNickTitProp;
import servicios.DtUsuario;
import servicios.PublicadorConsultarPropuesta;
import servicios.PublicadorConsultarPropuestaService;
/**
*
* @author Santiago.S
*/
@WebServlet(name = "ServletExtenderFinanciacion", urlPatterns = {"/ServletExtenderFinanciacion"})
public class ServletExtenderFinanciacion extends HttpServlet {
private PublicadorConsultarPropuesta port;
private RegistroSitio RS = new RegistroSitio();
configuracion conf = new configuracion();
@Override
public void init() throws ServletException {
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context;
context = request.getServletContext();
String ruta = context.getResource("").getPath();
URL url = new URL("http://" + conf.obtenerServer("servidor", ruta) + conf.leerProp("sConsultaPropuesta", ruta));
PublicadorConsultarPropuestaService webService = new PublicadorConsultarPropuestaService(url);
this.port = webService.getPublicadorConsultarPropuestaPort();
if (request.getSession().getAttribute("usuario_logueado") == null) {
request.setAttribute("mensaje", "No existe una sesión en el sistema");
request.getRequestDispatcher("/Vistas/Mensaje_Recibido.jsp").forward(request, response);
} else {
if (((DtUsuario) request.getSession().getAttribute("usuario_logueado")).isEsproponente() == true) {
List<DtNickTitProp> lista = this.port.listarPropuestasXDeProponenteX(((DtUsuario) request.getSession().getAttribute("usuario_logueado")).getNickname()).getListPropuestas();
if (lista.isEmpty()) {
request.setAttribute("mensaje", "No existen propuestas para extender");
request.getRequestDispatcher("/Vistas/Mensaje_Recibido.jsp").forward(request, response);
} else {
request.setAttribute("lista_propuestas", lista);
String browserDetails = request.getHeader("User-Agent");
String IP;
try (final DatagramSocket socket = new DatagramSocket()) {
socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
IP = socket.getLocalAddress().getHostAddress();
}
String URL = "http://" + RS.obtenerIP() + "/CulturarteWeb/ServletExtenderFinanciacion";
RS.ObtenerRegistro(browserDetails, IP, URL);
request.getRequestDispatcher("/Vistas/ExtenderFinanciacion.jsp").forward(request, response);
}
} else {
request.setAttribute("mensaje", "Solo los proponentes pueden entrar");
request.getRequestDispatcher("/Vistas/Mensaje_Recibido.jsp").forward(request, response);
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getParameter("TituloP") != null) {
String viene = request.getParameter("TituloP");
String Opcion = new String(viene.getBytes("ISO-8859-1"), "UTF-8");
this.port.extenderFinanciacion(((String) request.getParameter("TituloP")));
request.setAttribute("mensaje", "Se extendio la fecha de la propuesta");
request.getRequestDispatcher("/Vistas/Mensaje_Recibido.jsp").forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
function habilitar(document) {
document.getElementsByName("otros").style.display = "";
}
function desabilitar(document) {
document.getElementsByName("otros").style.display = "none";
}
function verificarNombre() {
var nombre = $("#nick").val().toString().trim();
if (nombre === "") {
document.getElementById("checkout").style.display = "none";
document.getElementById("check").style.display = "none";
return;
}
$.ajax({
url: "/CulturarteWeb/ServletConsultarUsuario",
type: 'POST',
data: {
accion: "verificar",
nombre: nombre
},
success: function (msg) {
if (msg === "esta") {
document.getElementById("checkout").style.display = "block";
document.getElementById("check").style.display = "none";
} else {
document.getElementById("check").style.display = "block";
document.getElementById("checkout").style.display = "none";
}
}
});
}
function verificarCorreo() {
var correo = $("#correo").val().toString().trim();
if (correo === "") {
document.getElementById("checkoutE").style.display = "none";
document.getElementById("checkE").style.display = "none";
return;
}
$.ajax({
url: "/CulturarteWeb/ServletConsultarUsuario",
type: 'POST',
data: {
accion: "verificar",
correo: correo
},
success: function (msg) {
if (msg === "esta") {
document.getElementById("checkoutE").style.display = "block";
document.getElementById("checkE").style.display = "none";
} else {
document.getElementById("checkE").style.display = "block";
document.getElementById("checkoutE").style.display = "none";
}
}
});
}
function calcularEdad(fecha) {
var hoy = new Date();
var cumpleanos = new Date(fecha);
var edad = hoy.getFullYear() - cumpleanos.getFullYear();
var m = hoy.getMonth() - cumpleanos.getMonth();
if (m < 0 || (m === 0 && hoy.getDate() < cumpleanos.getDate())) {
edad--;
}
return edad;
}
function validarEdad() {
var fecha = document.getElementById("fecha").value;
var edad = calcularEdad(fecha);
if (edad >= 18) {
document.getElementById('crear').disabled = false;
document.getElementById("mensajeEdad").style.display = "none";
} else {
document.getElementById('crear').disabled = true;
document.getElementById("mensajeEdad").style.display = "block";
}
} | 8c54434f9a7ebd4a85be0a3e840d52a7423d406a | [
"JavaScript",
"Java",
"Text"
] | 12 | Java | isma4102/CulturarteWeb_Tarea2 | bc5d96f5a40719213389711e7b5965be5326380b | 692956975622285591f23dcc714d50034a00c803 | |
refs/heads/master | <file_sep>borneInf=0.0
borneSup=1.0
Alphabet = ["a", "b", "c", "d", "e", "f"]
Bornes=[0,0.1,0.2,0.3,0.5,0.9,1]
msg=input("Veuillez donner le message à coder :");
print("Le message saisi est : ", msg)
i=0
print("Caractere Borne Inferieure Borne Supérieure")
while i<len(msg):
c=msg[i]
x=Bornes[Alphabet.index(c)]
i=i+1
y=Bornes[Alphabet.index(c)+1]
taille=borneSup-borneInf
borneSup=borneInf+taille*y
borneInf=borneInf+taille*x
print(c + " " + str(borneInf) + " " + str(borneSup))<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Huffman;
import java.io.FileNotFoundException;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.TreeMap;
/**
*
* @author Soufiyan & Adnane
*/
public class Huffman {
static PriorityQueue<Noeud> Noeuds = new PriorityQueue<>((o1, o2) -> (o1.valeur < o2.valeur) ? -1 : 1);
static TreeMap<Character, String> codes = new TreeMap<>();
static String texte = "";
static String Codes = "";
static String Decodes = "";
static int Alphabet[] = new int[128];
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(System.in);
int decision = 1;
while (decision != -1) {
if (GestionDecision(scanner, decision)) continue;
decision = consoleMenu(scanner);
}
}
private static int consoleMenu(Scanner scanner) {
int decision;
System.out.println("\n---- Menu ----\n" +
"-- [-1] Quitter \n" +
"-- [1] Donner un nouveau texte \n" +
"-- [2] Encoder un texte\n" +
"-- [3] Decoder un texte");
decision = Integer.parseInt(scanner.nextLine());
return decision;
}
private static boolean GestionDecision(Scanner scanner, int decision) {
switch (decision) {
case 1:
if (GestionTexte(scanner)) return true;
break;
case 2:
if (GestionCodage(scanner)) return true;
break;
case 3:
GestionDecodage(scanner);
break;
default:
break;
}
return false;
}
private static void GestionDecodage(Scanner scanner) {
System.out.println("Donnez le texte a decoder :");
Codes = scanner.nextLine();
System.out.println("Le texte saisi est : " + Codes);
Decoder();
}
private static boolean GestionCodage(Scanner scanner) {
System.out.println("Veuillez saisir le texte à encoder : ");
texte = scanner.nextLine();
System.out.println("Le texte saisi est : " + texte);
Codage_Texte();
return false;
}
private static boolean GestionTexte(Scanner scanner) {
int TextLength = texte.length();
System.out.println("Veuillez donner le texte : ");
texte = scanner.nextLine();
if (TextLength != 0) {
System.out.println("Erreur : Aucune entrée valide ! ");
texte = "";
return true;
}
Alphabet = new int[128];
Noeuds.clear();
codes.clear();
Codes = "";
Decodes = "";
System.out.println("Text: " + texte);
CalculInterval(Noeuds, true);
Construire_Arbre(Noeuds);
GenererCode(Noeuds.peek(), "");
AfficherCodes();
System.out.println("-- Codage/Decodage --");
Codage_Texte();
Decoder();
return false;
}
private static void Decoder() { // Il ne peut decoder que le dernier message codés, car c'est les intervalles de ce messages qui sont enregistrés en mémoire !
Decodes = "";
Noeud node = Noeuds.peek();
for (int i = 0; i < Codes.length(); ) {
Noeud tmpNode = node;
while (tmpNode.gauche != null && tmpNode.droite != null && i < Codes.length()) {
if (Codes.charAt(i) == '1')
tmpNode = tmpNode.droite;
else tmpNode = tmpNode.gauche;
i++;
}
if (tmpNode.caractere.length() == 1)
Decodes += tmpNode.caractere;
else
System.out.println("Erreur : Entrée invalide");
}
System.out.println("Decoded Text: " + Decodes);
}
private static void Codage_Texte() {
Codes = "";
for (int i = 0; i < texte.length(); i++)
Codes += codes.get(texte.charAt(i));
System.out.println("Texte codé : " + Codes);
}
private static void Construire_Arbre(PriorityQueue<Noeud> vector) {
while (vector.size() > 1)
vector.add(new Noeud(vector.poll(), vector.poll()));
}
private static void AfficherCodes() {
System.out.println("--- Affichage de Codes ---");
codes.forEach((k, v) -> System.out.println("'" + k + "' : " + v));
}
private static void CalculInterval(PriorityQueue<Noeud> vector, boolean printIntervals) {
if (printIntervals) System.out.println("-- Probabilités ( pour la gestion d'intervallles ) --");
for (int i = 0; i < texte.length(); i++)
Alphabet[texte.charAt(i)]++;
for (int i = 0; i < Alphabet.length; i++)
if (Alphabet[i] > 0) {
vector.add(new Noeud(Alphabet[i] / (texte.length() * 1.0), ((char) i) + ""));
if (printIntervals)
System.out.println("'" + ((char) i) + "' : " + Alphabet[i] / (texte.length() * 1.0));
}
}
private static void GenererCode(Noeud node, String s) {
if (node != null) {
if (node.droite != null)
GenererCode(node.droite, s + "1");
if (node.gauche != null)
GenererCode(node.gauche, s + "0");
if (node.gauche == null && node.droite == null)
codes.put(node.caractere.charAt(0), s);
}
}
}<file_sep>print("hello world")
thisList=["a","b","c","d","e","f"]
thisProba=[0,0.1,0.2,0.3,0.5,0.9,1]
# Code : 0.15633504384000005
r=(float) (input("Veuillez donner le code à décoder :"))
print("Le code saisi est : ", r)
i=0
taille=1
while r>0.0001:
i=0
while r-thisProba[i+1]>0 :
i=i+1
C=thisList[i]
print(C)
x=thisProba[i]
y=thisProba[i+1]
taille=y-x
r=r-x
r=r/taille
print("Taille = " + str(taille) + "\t\tr= " + str(r))
print("X = " + str(x) + "\t\ty= " + str(y))
| 2729d6b6698f8917d225388fe5a7ad2b82ffee81 | [
"Java",
"Python"
] | 3 | Python | Adnane-R/Codages | c921f6a93fe70c904ce2b9141b6a156ded17907a | c46a157788dc4d4722b3d89d8edc85482ad5f553 | |
refs/heads/master | <repo_name>PXLcat/RythmEditor<file_sep>/EditeurRythme/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;
namespace EditeurRythme
{
public partial class Form1 : Form
{
static string currentFile;
static string currentFileDirectory;
public Form1()
{
InitializeComponent();
}
private void btnFile_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
currentFile = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
tbDirectory.Text = openFileDialog1.FileName;
currentFileDirectory = openFileDialog1.FileName;
lblTitle.Text = currentFile;
}
private void button1_Click(object sender, EventArgs e)
{
if (currentFile == null)
{
MessageBox.Show("An audio file must be selected.");
}
else if (nudBPM.Value==0)
{
MessageBox.Show("Must type a BPM. Try songbpm.com .");
}
else
{
Form2 frm2 = new Form2();
frm2.currentFile = currentFile;
frm2.currentFileDirectory = currentFileDirectory;
frm2.bpm = (int)nudBPM.Value;
frm2.intervalsByBPM = (int)nudIntervals.Value;
frm2.Show();
}
}
}
}
<file_sep>/EditeurRythme/Form2.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;
using System.Timers;
using System.IO;
using Newtonsoft.Json;
namespace EditeurRythme
{
public partial class Form2 : Form
{
public string currentFile;
public string currentFileDirectory;
public int bpm;
public int intervalsByBPM;
private SoundPlayer currentSong = null;
private int secondsElapsed;
private int elapsedBPM;
private string musicLine = ""; //utiliser StringBuilder?
private string rythmLine = "";
private int currentEdit = 1; //0= nothing, 1=music, 2= rythm
//List<int> musicTempoList = new List<int>();
//List<int> rythmTempoList = new List<int>();
StringBuilder sbMusic = new StringBuilder();
StringBuilder sbRythm = new StringBuilder();
//TODO faire deux sb différents
public Form2()
{
InitializeComponent();
KeyPreview = true;
}
private void Form2_Load(object sender, EventArgs e)
{
lblTitle.Text = currentFile;
currentSong = new SoundPlayer(currentFileDirectory);
currentSong.Load();
lblDisplayBPM.Text = bpm.ToString();
//disable editing elements
rtbMusicLine.Enabled = true;
rtbRythmLine.Enabled = false;
lblSpace.Visible = false;
// double secFromBpm = 60000(nombre de milisecondes dans une minute) / ex:112 (les bpm de la musique choisie);
double secFromBpm = 60000 / (double)bpm;
//timerBPM.Interval(le nombre de millisecondes entre chaque incrémentation du timer) = secFromBpm / intervalsByBPM(le nombre d'intervalles dans un temps)
timerBPM.Interval = secFromBpm / intervalsByBPM; //TODO vérifs
// /1 = demi-seconde, /2= quart-seconde, /4= huitième-seconde
}
private void btnPlay_Click(object sender, EventArgs e)
{
currentSong.Play();
timerSeconds.Enabled = true;
timerBPM.Enabled = true;
lblSpace.Visible = true;
btnPlay.Enabled = false; //c'est ici que ça passe l 117, pourquoi?
}
private void btnStop_Click(object sender, EventArgs e)
{
currentSong.Stop();
timerSeconds.Enabled = false;
secondsElapsed = 0;
timerSeconds.Stop();
timerBPM.Enabled = false;
timerBPM.Stop();
elapsedBPM = 0;
lblSpace.Visible = false;
lblTimeSeconds.Text = timeDisplay();
lblElapsedBPM.Text = elapsedBPM.ToString();
btnPlay.Enabled = true;
}
private void timerSeconds_Tick(object sender, EventArgs e)
{
secondsElapsed++;
lblTimeSeconds.Text = timeDisplay();
}
private string timeDisplay()
{
int seconds, minutes;
minutes = secondsElapsed / 60;
seconds = secondsElapsed % 60;
return string.Format("{0:00}:{1:00}", minutes, seconds);
}
private void rbMusicLine_CheckedChanged(object sender, EventArgs e)
{
if (rbMusicLine.Checked)
{
rtbMusicLine.Enabled = true;
rtbRythmLine.Enabled = false;
//rbRythmLine.Checked = true;
currentEdit = 1;
}
}
private void rbRythmLine_CheckedChanged(object sender, EventArgs e)
{
if (rbRythmLine.Checked)
{
rtbMusicLine.Enabled = false;
rtbRythmLine.Enabled = true;
//rbMusicLine.Checked = false; //appel l106
currentEdit = 2;
}
}
private void timerBPM_Elapsed(object sender, EventArgs e)
{
elapsedBPM++;
lblElapsedBPM.Text = elapsedBPM.ToString();
}
//TODO bouton Clean
private void EditRtb(RichTextBox rtb)
{ //possible de factoriser?
if (rtb == rtbMusicLine)
{
sbMusic.Append(elapsedBPM.ToString());
sbMusic.Append("\n");
rtb.Text = sbMusic.ToString(); //TODO besoin de séparer entre rtbMusic et rtbRythm ?
//musicTempoList.Add(elapsedBPM); //TODO attention, l'édit de la rtb ne changera pas ce qui sera envoyé dans le json. Il faut que ce qui est dans la rtb soit sauvé à l'enregistrement et pas le tempo direct
}
else if (rtb == rtbRythmLine)
{
sbRythm.Append(elapsedBPM.ToString());
sbRythm.Append("\n");
rtb.Text = sbRythm.ToString(); //TODO besoin de séparer entre rtbMusic et rtbRythm ?
//rythmTempoList.Add(elapsedBPM);
}
rtb.Invalidate();
}
private void button1_Click(object sender, EventArgs e)
{
EditRtb(rtbMusicLine);
}
private void Form2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
switch (currentEdit)
{
case 0:
break;
case 1:
EditRtb(rtbMusicLine);
break;
case 2:
EditRtb(rtbRythmLine);
break;
default:
break;
}
}
}
private void btnClearMusic_Click(object sender, EventArgs e)
{
sbMusic.Clear();
rtbMusicLine.Clear();
}
private void btnClearRythm_Click(object sender, EventArgs e)
{
sbRythm.Clear();
rtbRythmLine.Clear();
}
private void btnExportMusic_Click(object sender, EventArgs e)
{
//TODO nom de la chanson comme proposition de base
//TODO taille de la fenêtre
saveFileDialog1.AddExtension = true;
saveFileDialog1.Filter = "Fichiers JSON (*.json)|*.json";
saveFileDialog1.ShowDialog();
//MessageBox.Show(saveFileDialog1.FileName); //filename = chemin+ nom fichier
//File.Create(saveFileDialog1.FileName);
////File.AppendAllText(saveFileDialog1.FileName, rtbMusicLine.Text,); //TODO factoriser pour MusicLine
////File.AppendAllLines(saveFileDialog1.FileName,rtbMusicLine.Text);
//File.WriteAllText(saveFileDialog1.FileName, rtbMusicLine.Text);
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
SongDTO file = new SongDTO();
file.Name = currentFile;
file.BPM = bpm;
file.IntervalsByBPM = intervalsByBPM;
List<int> musicBeatsList = new List<int>();
List<int> rythmBeatsList = new List<int>();
foreach (string line in rtbMusicLine.Lines)
{
if (!String.IsNullOrWhiteSpace(line))
{
bool success = Int32.TryParse(line, out int beat);
if (success)
{
musicBeatsList.Add(beat);
}
else
{
MessageBox.Show("One of the lines cannot be converted to a number");
}
}
}
foreach (string line in rtbRythmLine.Lines)
{
if (!String.IsNullOrWhiteSpace(line))
{
bool success = Int32.TryParse(line, out int beat);
if (success)
{
rythmBeatsList.Add(beat);
}
else
{
MessageBox.Show("One of the lines cannot be converted to a number");
}
}
}
file.MusicLine = musicBeatsList.ToArray<int>();
file.RythmLine = rythmBeatsList.ToArray<int>();
File.WriteAllText(saveFileDialog1.FileName, JsonConvert.SerializeObject(file, Formatting.Indented));
}
}
}
| cca5949d651958c1c243aebb88675b47afc62d8b | [
"C#"
] | 2 | C# | PXLcat/RythmEditor | 634471eb877fd829016970935c76b864a8832281 | 635fe4e3f3a85e397018db62e6e39c269a7d69f6 | |
refs/heads/master | <repo_name>OhLaughing/my_springboot_mybatis_sqlite3<file_sep>/users.sql
/*
Navicat MySQL Data Transfer
Source Server : 本地
Source Server Version : 50505
Source Host : localhost:3306
Source Database : test1
Target Server Type : MYSQL
Target Server Version : 50505
File Encoding : 65001
Date: 2016-11-05 21:17:33
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT ,
`userName` varchar(32) NOT NULL ,
`passWord` varchar(32) NOT NULL ,
`user_sex` varchar(32) NOT NULL ,
`nick_name` varchar(32)
) ;
CREATE TABLE `users` (
`id` bigint(20) ,
`userName` ,
`passWord` ,
`user_sex` ,
`nick_name` ,
PRIMARY KEY (`id`)
) ;
insert into users (userName, passWord, user_sex, nick_name) values ("name1", "abcd", "MAN", "nickname1111");
insert into users (userName, passWord, user_sex, nick_name) values ("name2", "abcd", "MAN", "nickname1111");
insert into users (userName, passWord, user_sex, nick_name) values ("name3", "abcd", "MAN", "nickname1111");
insert into users (userName, passWord, user_sex, nick_name) values ("name4", "abcd", "MAN", "nickname1111");
insert into users (userName, passWord, user_sex, nick_name) values ("name5", "abcd", "MAN", "nickname1111");
insert into users (userName, passWord, user_sex, nick_name) values ("name6", "abcd", "MAN", "nickname1111");
insert into users (userName, passWord, user_sex, nick_name) values ("name7", "abcd", "MAN", "nickname1111");
insert into users (userName, passWord, user_sex, nick_name) values ("name8", "abcd", "MAN", "nickname1111");
insert into users (userName, passWord, user_sex, nick_name) values ("name9", "abcd", "MAN", "nickname1111");
insert into users (userName, passWord, user_sex, nick_name) values ("name10", "abcd", "MAN", "nickname1111");
insert into users (userName, passWord, user_sex, nick_name) values ("name11", "abcd", "MAN", "nickname1111");
insert into users (userName, passWord, user_sex, nick_name) values ("name12", "abcd", "MAN", "nickname1111");
insert into users (userName, passWord, user_sex, nick_name) values ("name13", "abcd", "MAN", "nickname1111");
insert into users (userName, passWord, user_sex, nick_name) values ("name14", "abcd", "MAN", "nickname1111");
CREATE TABLE OMMBSERVER (
OMMBID integer PRIMARY KEY AUTOINCREMENT,
IP char(10) NOT NULL,
FTPUSER char(10) NOT NULL ,
FTPPORT INTEGER(5) NOT NULL ,
FTPPASSWORD char(10) NOT NULL ,
TELNETUSER char(10) NOT NULL ,
TELNETPORT INTEGER(5) NOT NULL ,
DATAVERSION varchar(2000) NOT NULL,
TELNETPASSWORD char(10),
OMMBVERSION CHAR(50) NOT NULL ,
STATUS CHAR(10)
);
<file_sep>/src/main/java/com/neo/web/HelloController.java
package com.neo.web;
import com.neo.entity.UserEntity;
import com.neo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
/**
* Created by gustaov on 2018/3/31.
*/
@Controller
@RequestMapping("/")
public class HelloController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/index1")
public String index1() {
return "index1";
}
@RequestMapping("/index2")
public String index2() {
return "index2";
}
@RequestMapping("/admin1")
public String admin1(Model model) {
List<UserEntity> users = userMapper.getAll();
model.addAttribute("users", users);
return "admin1";
}
@RequestMapping("/admin2")
public String admin2() {
return "admin2";
}
@RequestMapping("/test2")
public String test2() {
return "test2";
}
@RequestMapping("/test3")
public String test3() {
return "test3";
}
}
| ec5ca6df28c258a06b624a9f105243bc556c739f | [
"Java",
"SQL"
] | 2 | SQL | OhLaughing/my_springboot_mybatis_sqlite3 | 063fcd3f1ce1762414fe66ee4de1e6af5148667a | bd49da5c477b90b02f67d538c20e8568e91b5959 | |
refs/heads/master | <repo_name>TheShivamMishra/Coding<file_sep>/Practice/bookAllocation.cpp
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
bool findsol(int a[],int n,int m ,ll ans)
{
int i=0,j=0;
ll sump=0;//assign the maximum pages
//that can read which less than equal to ans
while(i<n)
{
if(sump+a[i]<=ans)
{
sump+=a[i++];
}else{
++j;
sump=0;
}
//No of sudent greater than m to assign all book return false
if(j>=m)return false;
}
// at last all check and student equal to m;
return true;
}
// finding ans with binary search
ll binarysearch(int a[],int n,int m,ll end ,ll start)
{
ll ans=a[n-1];
while(start<=end)
{
ll mid=(start+end)/2;
if(findsol(a,n,m,mid))
{
// if mid is valid then assign this to answer
//change the end to mid-1 so minimize the answer till start ==end
ans=mid;
end=mid-1;
}else{
//if mid is not valid then search between mid+1 and end
start=mid+1;
}
}
return ans;
}
int main() {
//code
int t;
cin>>t;
while(t--)
{
int n,m;
ll sum=0;
cin>>n;
int a[n];
for(int i=0;i<n;++i)
{
cin>>a[i];
sum+=a[i];
}
cin>>m;
//if no of sudent is greater than book then return -1 as at least one book
// is allocate every one student
if(m>n)
cout<<-1<<endl;
else if(n==m){
//if no of student is equal to no of book then return book with maximum page
cout<<*max_element(a,a+n)<<endl;
}
else{
cout<<binarysearch(a,n,m,sum,a[0])<<endl;
}
}
return 0;
}<file_sep>/Practice/sudoku.cpp
#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#define vi vector<int>
#define vb vector<bool>
#define lli long long int
#define vvi vector<vector<int>>
#define loop(n) for (int i = 0; i < n; i++)
using namespace std;
bool isSafeToPlaceNumber(vector<vector<int>> &board, int r, int c, int num)
{
// for row
for (int i = 0; i < board[0].size(); i++)
if (board[r][i] == num)
return false;
// for col
for (int i = 0; i < board.size(); i++)
if (board[i][c] == num)
return false;
//for each sub box 3x3 Matrix
int x = (r / 3) * 3;
int y = (c / 3) * 3;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
if (board[x + i][y + j] == num)
return false;
}
return true;
}
bool sudoku_02(vector<vector<int>> &board, int idx, vector<int> &list)
{
if (idx == list.size())
return 1;
int r = list.at(idx) / 9;
int c = list.at(idx) % 9;
int count = 0;
bool res = false;
for (int num = 1; num < 10; num++)
{
if (isSafeToPlaceNumber(board, r, c, num))
{
board[r][c] = num;
res = sudoku_02(board, idx + 1, list);
if (res)
return true;
board[r][c] = 0;
}
}
return res;
}
void solve()
{
vvi mat(9, vi(9, 0));
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
cin >> mat[i][j];
// cout << "hi" << endl;
vi list;
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
{
if (mat[i][j] == 0)
list.push_back(i * 9 + j);
// else
// {
// int mask = 1 << mat[i][j];
// row[i] ^= mask;
// col[j] ^= mask;
// submat[i / 3][j / 3] ^= mask;
// }
}
if (sudoku_02(mat, 0, list))
{
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
cout << mat[i][j] << " ";
cout << endl;
}
else
cout << "-1" << endl;
}
int main()
{
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
// cout.tie(NULL);
int t;
cin >> t;
while (t--)
solve();
return 0;
}<file_sep>/SegmentTrees/l001.cpp
#include "bits/stdc++.h"
#define lli long long int
#define vi vector<int>
#define vb vector<bool>
#define vvi vector<vector<int>>
#define loop(n) for (int i = 0; i < n; i++)
using namespace std;
// building segment tree using segtree array;
void makeST(vi &arr, vi &segtree, int l, int r, int idx)
{
if (l == r)
{
segtree[idx] = 1;
return;
}
int mid = (l + r) / 2;
makeST(arr, segtree, l, mid, 2 * idx + 1);
makeST(arr, segtree, mid + 1, r, 2 * idx + 2);
int count = 0;
unordered_set<int> map;
for (int i = l; i <= r; i++)
{
if (map.find(arr[i]) == map.end())
count++;
map.insert(arr[i]);
}
segtree[idx] = count;
// cout<<segtree[idx]<<endl;
}
void createSegmentTree(vi &arr, vi &segtree, int n)
{
int size = 0;
int x = (int)ceil(log(n)); // height of a compelete binary tree i.e a segmetntree;
size = 2 * (pow(2, x)) - 1; // size of the segment tree : because their will be exacty n leaves and (n-1){internal nodes in a completer binary tree};
// hence total nodes will be n + n-1
segtree.assign(size, 0);
makeST(arr, segtree, 0, n - 1, 0);
}
int getQuery(vi &segtree, int l, int r, int low, int high, int pos) // using overlaping structre to get query result;
{
cout<<low<<" "<<high<<endl;
if (low >= l && high <= r)
return segtree[pos]; // total overlap;
if (high < l || low > r)
return 0; //no overlap;
int mid = (low + high) / 2;
return getQuery(segtree, l, r, low, mid, 2 * pos + 1) + getQuery(segtree, l, r, mid + 1, high, 2 * pos + 1);
}
void solve()
{
int n;
cin >> n;
vi arr(n, 0);
loop(n) cin >> arr[i];
int size = 0;
int x = (int)ceil(log2(n)); // height of a compelete binary tree i.e a segmetntree;
size = 2 * (pow(2, x)) - 1;
// cout<<size<<endl;
vi segtree(size, 0);
makeST(arr, segtree, 0, n - 1, 0);
// loop(size) cout << segtree[i] << " ";
int queries;
cin >> queries;
while (queries--)
{
int l, r;
cin >> l >> r;
l--;
r--;
cout << getQuery(segtree, l, r, 0, n - 1, 0) << "\n";
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
solve();
return 0;
}
<file_sep>/Graph/l002_directedGraph.java
import java.util.ArrayList;
import java.util.LinkedList;
public class l002_directedGraph {
public static void main(String[] args) {
solve();
}
static int N = 8;
static ArrayList<Integer> graph[];
public static void display() {
for (int i = 0; i < graph.length; i++) {
System.out.print(i + "->");
for (Integer e : graph[i]) {
System.out.print("(" + e + ") ");
}
System.out.println();
}
System.out.println();
}
public static void constructGraph() {
graph = new ArrayList[N];
for (int i = 0; i < graph.length; i++)
graph[i] = new ArrayList<Integer>();
graph[7].add(5);
graph[7].add(6);
graph[5].add(4);
graph[5].add(2);
graph[6].add(4);
graph[6].add(3);
graph[2].add(1);
graph[3].add(1);
graph[1].add(0);
display();
}
// Topological sort for directed
// Graph===================================================
public static void topologicalSort_(int src, boolean[] vis, ArrayList<Integer> ans) { // dfs
vis[src] = true;
for (Integer e : graph[src])
if (!vis[e])
topologicalSort_(e, vis, ans);
ans.add(src);
}
public static void topologicalSort() {
ArrayList<Integer> ans = new ArrayList<>();
boolean vis[] = new boolean[N];
for (int i = 0; i < N; i++) // calling the topologicalsort_ for all the gcc of graph.
if (!vis[i])
topologicalSort_(i, vis, ans);
for (int i = ans.size() - 1; i >= 0; i--) // printing the stack in revrse order.
System.out.print(i + " ");
}
// Kahns Algo For used for topological sort and cycle founding in
// graph=====================
public static void KahnsAlgo() {
int[] indegree = new int[N];
for (int i = 0; i < N; i++) { // creating indegree array.
for (Integer e : graph[i])
indegree[e]++;
}
LinkedList<Integer> que = new LinkedList<>();
for (int i = 0; i < N; i++) // adding all the 0 indgree in queue.
if (indegree[i] == 0)
que.addLast(i);
ArrayList<Integer> ans = new ArrayList<>();
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
int rvtx = que.removeFirst();
ans.add(rvtx);
for (int e : graph[rvtx]) {
if (--indegree[e] == 0)
que.addLast(e);
}
}
}
if (ans.size() != N)
System.out.println("Cycle");
else
System.out.println(ans);
}
// topological sort using dfs marking the array 1 for current path as visiting
// to find cycle.
public static boolean topologicalSort_(int src, int[] vis, ArrayList<Integer> ans) {
if (vis[src] == 1)// visited vertex in my path.
return true;
if (vis[src] == 2) // already viseited vertex but not by my path.
return false;
vis[src] = 1;
boolean res = false;
for (int e : graph[src]) {
res = res || topologicalSort_(e, vis, ans);
}
vis[src] = 2;
ans.add(src);
return res;
}
public static void topologicalSortCycle() {
int[] vis = new int[N];
ArrayList<Integer> ans = new ArrayList<>();
boolean res = false;
for (int i = 0; i < N && !res; i++)
if (vis[i] == 0)
res = res || topologicalSort_(i, vis, ans);
if (!res) {
System.out.println(ans);
} else
System.out.println("Cycle :" + ans);
}
// Scc of a graph using kosa raju algo.======================
public static void dfs_scc(int src, ArrayList<Integer>[] ngraph, boolena[] vis, ArrayList<Integer> ans) {
vis[src] = true;
for (int ele : ngraph[src]) {
if (!vis[ele])
dfs_scc(e, ngraph, vis, ans);
}
}
public static void KosaRajuAlgo() {
boolean vis[] = new boolean[N];
ArrayList<Integer> ans = new ArrayList<>(); // getting topo Order in which we have to travel;
for (int i = 0; i < N; i++)
if (!vis[i])
topologicalSort_(i, vis, ans);
ArrayList<Integer>[] ngraph = new ArrayList[N]; // creation of a new graph;
for (int i = 0; i < N; i++)
ngraph[i] = new ArrayList<>();
for (int i = 0; i < N; i++) { // inversion of old graph and storing it into ngraph;
for (int ele : graph[i]) {
ngraph[ele].add(i);
}
}
vis = new boolean[N];
count = 0;
for (int i = ans.size() - 1; i >= 0; i--) // running again dfs but now on topo Order obtianed;
{
if (!vis[ans.get(i)]) {
ArrayList<Integer> ans_ = new ArrayList<>();
dfs_scc(ans.get(i), ngraph, vis, ans_);
System.out.println(ans_);
count++;
}
}
System.out.println(count);
}
public static void solve() {
constructGraph();
// topologicalSort();
// KahnsAlgo();
topologicalSortCycle();
}
}<file_sep>/Tree/question.java
public class question {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
// Leetcode: 863.=======================================================
public boolean rootToNodePath_(TreeNode root, int data, ArrayList<TreeNode> path) {
if (root == null)
return false;
if (root.val == data) {
path.add(root);
return true;
}
boolean res = rootToNodePath_(root.left, data, path) || rootToNodePath_(root.right, data, path);
if (res)
path.add(root);
return res;
}
public void kDown(TreeNode root, int level, TreeNode blockNode, List<Integer> ans) {
if (root == null || root == blockNode)
return;
if (level == 0) {
ans.add(root.val);
return;
}
kDown(root.left, level - 1, blockNode, ans);
kDown(root.right, level - 1, blockNode, ans);
}
public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
ArrayList<TreeNode> path = new ArrayList<>();
rootToNodePath_(root, target.val, path);
TreeNode blockNode = null;
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < path.size(); i++) {
if (K - i < 0)
break;
kDown(path.get(i), K - i, blockNode, ans);
blockNode = path.get(i);
}
return ans;
}
// Leetcode: 112.=======================================================
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
if (root.left == null && root.right == null && sum - root.val == 0)
return true;
boolean res = false;
res = res || hasPathSum(root.left, sum - root.val);
res = res || hasPathSum(root.right, sum - root.val);
return res;
}
// Leetcode: 113.========================================================
public void pathSum(TreeNode root, int sum, List<List<Integer>> res, List<Integer> smallAns) {
if (root == null)
return;
if (root.left == null && root.right == null && sum - root.val == 0) {
List<Integer> base = new ArrayList<>(smallAns);// res.push_back(smallAns); res.back().push_back(root.val);
base.add(root.val);
res.add(base);
return;
}
smallAns.add(root.val);
pathSum(root.left, sum - root.val, res, smallAns);
pathSum(root.right, sum - root.val, res, smallAns);
smallAns.remove(smallAns.size() - 1);
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if (root == null)
return new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
List<Integer> smallAns = new ArrayList<>();
pathSum(root, sum, res, smallAns);
return res;
}
// geeks:
// https://www.geeksforgeeks.org/find-maximum-path-sum-two-leaves-binary-tree/
public static int maxPathSum(Node root) {
max_leafToLeafSum = (int) -1e8;
leafToLeaf(root);
return max_leafToLeafSum;
}
public static int leafToLeaf(Node node) {
if (node == null)
return 0;
int leftNodeToLeafSum = leafToLeaf(node.left);
int rightNodeToLeafSum = leafToLeaf(node.right);
if (node.left != null && node.right != null) {
max_leafToLeafSum = Math.max(max_leafToLeafSum, leftNodeToLeafSum + rightNodeToLeafSum + node.data);
return Math.max(leftNodeToLeafSum, rightNodeToLeafSum) + node.data;
}
return (node.left == null ? rightNodeToLeafSum : leftNodeToLeafSum) + node.data;
}
// Leetcode 124.========================================================
int max_nodeToNodeSum = (int) -1e8;
public int maxPathSum(TreeNode root) {
maxPathSum_(root);
return max_nodeToNodeSum;
}
public int maxPathSum_(TreeNode node) {
if (node == null)
return 0;
int leftNodeToNodeSum = maxPathSum_(node.left);
int rightNodeToNodeSum = maxPathSum_(node.right);
int max_ = Math.max(leftNodeToNodeSum, rightNodeToNodeSum) + node.val;
max_nodeToNodeSum = Math.max(Math.max(max_nodeToNodeSum, node.val),
Math.max(leftNodeToNodeSum + node.val + rightNodeToNodeSum, max_));
return Math.max(max_, node.val);
}
// Leetcode 987.====================================================
static int leftMinValue = 0;
static int rightMaxValue = 0;
public static void width(TreeNode node, int lev) {
if (node == null)
return;
leftMinValue = Math.min(leftMinValue, lev);
rightMaxValue = Math.max(rightMaxValue, lev);
width(node.left, lev - 1);
width(node.right, lev + 1);
}
public static class pairVO implements Comparable<pairVO> {
TreeNode node; // actual Node
int vl = 0; // vertical Level
public pairVO(TreeNode node, int vl) {
this.node = node;
this.vl = vl;
}
@override
public int compareTo(pairVO o) { // for c++: bool opeartor < ( pairvo const & o) const{
if (this.vl == o.vl)
return this.node.val - o.node.val; // in c++: replace '-' with '>'
return this.vl - o.vl; // default behaviour of que // in c++: replace '-' with '>'
}
}
public List<List<Integer>> verticalTraversal(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if (root == null)
return ans;
width(root, 0);
int n = rightMaxValue - leftMinValue + 1;
for (int i = 0; i < n; i++)
ans.add(new ArrayList<>());
PriorityQueue<pairVO> pque = new PriorityQueue<>();
PriorityQueue<pairVO> cque = new PriorityQueue<>();
pque.add(new pairVO(root, -leftMinValue));
while (pque.size() != 0) {
int size = pque.size();
while (size-- > 0) {
pairVO rpair = pque.poll();
ans.get(rpair.vl).add(rpair.node.val);
if (rpair.node.left != null)
cque.add(new pairVO(rpair.node.left, rpair.vl - 1));
if (rpair.node.right != null)
cque.add(new pairVO(rpair.node.right, rpair.vl + 1));
}
PriorityQueue<pairVO> temp = pque;
pque = cque;
cque = temp;
}
}
}<file_sep>/Recursion/l002.cpp
#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
using namespace std;
void display2D(vector<vector<int>> &board)
{
for (auto ele : board)
{
for (auto item : ele)
cout << item << " ";
cout << endl;
}
}
// Nqueen Optimized using 4 Arrays
vector<bool> rowA(4, false);
vector<bool> colA(4, false);
vector<bool> diagA(4, false);
vector<bool> adiagA(4, false);
int Nqueen2D_01(int n, int m, int idx, int tnq, string ans)
{
if (tnq == 0)
{
cout << ans << endl;
return 1;
}
int count = 0;
for (int i = idx; i < n * m; i++)
{
int x = i / m;
int y = i % m;
if (!rowA[x] && !colA[y] && !diagA[x - y + (m - 1)] && !adiagA[x + y])
{
rowA[x] = true;
colA[y] = true;
diagA[x - y + (m - 1)] = true;
adiagA[x + y] = true;
count += Nqueen2D_01(n, m, i + 1, tnq - 1, ans + "(" + to_string(x) + "," + to_string(y) + ")");
rowA[x] = false;
colA[y] = false;
diagA[x - y + (m - 1)] = false;
adiagA[x + y] = false;
}
}
return count;
}
// Nqueens using bits ====================================
int rowA_ = 0;
int colA_ = 0;
int diagA_ = 0;
int adiagA_ = 0;
int Nqueen2D_02(int n, int m, int idx, int tnq, string ans)
{
if (tnq == 0)
{
cout << ans << endl;
return 1;
}
int count = 0;
for (int i = idx; i < n * m; i++)
{
int x = i / m;
int y = i % m;
if (!(rowA_ & (1 << x)) && !(colA_ & (1 << y)) && !(diagA_ & (1 << (x - y + (m - 1)))) && !(adiagA_ & (1 << (x + y))))
{
rowA_ ^= (1 << x);
colA_ ^= (1 << y);
diagA_ ^= (1 << (x - y + (m - 1)));
adiagA_ ^= (1 << (x + y));
count += Nqueen2D_02(n, m, i + 1, tnq - 1, ans + "(" + to_string(x) + "," + to_string(y) + ")");
rowA_ ^= (1 << x);
colA_ ^= (1 << y);
diagA_ ^= (1 << (x - y + (m - 1)));
adiagA_ ^= (1 << (x + y));
}
}
return count;
}
// Nqueen more optimized by placing one queen per row
//i.e one queen can sit at any place in that row
// next queen will have next row;
int Nqueen2D_03(int n, int m, int r, int tnq, string ans)
{
if (r == n || tnq == 0)
{
if (tnq == 0)
{
cout << ans << endl;
return 1;
}
return 0;
}
int count = 0;
for (int i = r; i < m; i++)
{
int x = r;
int y = 0;
if (!(rowA_ & (1 << x)) && !(colA_ & (1 << y)) && !(diagA_ & (1 << (x - y + (m - 1)))) && !(adiagA_ & (1 << (x + y))))
{
rowA_ ^= (1 << x);
colA_ ^= (1 << y);
diagA_ ^= (1 << (x - y + (m - 1)));
adiagA_ ^= (1 << (x + y));
count += Nqueen2D_03(n, m, r + 1, tnq - 1, ans + "(" + to_string(x) + "," + to_string(y) + ")");
rowA_ ^= (1 << x);
colA_ ^= (1 << y);
diagA_ ^= (1 << (x - y + (m - 1)));
adiagA_ ^= (1 << (x + y));
}
}
return count;
}
void NqueenSet()
{
int n = 4;
int m = 4;
rowA.resize(n, false);
colA.resize(m, false);
diagA.resize(n + m - 1, false);
adiagA.resize(n + m - 1, false);
// cout << Nqueen2D_01(n, m, 0, n, "") << endl;
// cout << Nqueen2D_02(n, m, 0, n, "") << endl;
cout << Nqueen2D_03(n, m, 0, n, "") << endl;
}
// suduko set===================================
bool isSafeToPlaceNumber(vector<vector<int>> &board, int r, int c, int num)
{
// for row
for (int i = 0; i < board[0].size(); i++)
if (board[r][i] == num)
return false;
// for col
for (int i = 0; i < board.size(); i++)
if (board[i][c] == num)
return false;
//for each sub box 3x3 Matrix
int x = (r / 3) * 3;
int y = (c / 3) * 3;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
if (board[x + i][y + j] == num)
return false;
}
return true;
}
int suduko_01(vector<vector<int>> &board, int idx)
{
if (idx == 81)
{
display2D(board);
return 1;
}
int r = idx / 9;
int c = idx % 9;
int count = 0;
if (board[r][c] == 0)
{
for (int num = 1; num < 10; num++)
{
if (isSafeToPlaceNumber(board, r, c, num))
{
board[r][c] = num;
count += suduko_01(board, idx + 1);
board[r][c] = 0;
}
}
}
else
{
count += suduko_01(board, idx + 1);
}
return count;
}
// suduko 2 in this we use a list in which all the zeros of the board are present
// and just call on them hence we save the calls;
int suduko_02(vector<vector<int>> &board, int idx, vector<int> &list)
{
if (idx == list.size())
{
cout << "===========================" << endl;
display2D(board);
return 1;
}
int r = list.at(idx) / 9;
int c = list.at(idx) % 9;
int count = 0;
for (int num = 1; num < 10; num++)
{
if (isSafeToPlaceNumber(board, r, c, num))
{
board[r][c] = num;
count += suduko_02(board, idx + 1, list);
board[r][c] = 0;
}
}
return count;
}
//suduko 3 More optimization of isSafeToPlaceNumber by using bits.
vector<int> row(10, 0);
vector<int> col(10, 0);
vector<vector<int>> mat(4, vector<int>(4, 0));
int suduko_03(vector<vector<int>> &board, int idx, vector<int> &list)
{
if (idx == list.size())
{
cout << "===========================" << endl;
display2D(board);
return 1;
}
int r = list.at(idx) / 9;
int c = list.at(idx) % 9;
int count = 0;
for (int num = 1; num < 10; num++)
{
int mask = 1 << num;
if ((row[r] & mask) == 0 && (col[c] & mask) == 0 && (mat[r / 3][c / 3] & mask) == 0)
{
board[r][c] = num;
row[r] ^= mask;
col[c] ^= mask;
mat[r / 3][c / 3] ^= mask;
count += suduko_03(board, idx + 1, list);
board[r][c] = 0;
row[r] ^= mask;
col[c] ^= mask;
mat[r / 3][c / 3] ^= mask;
}
}
return count;
}
void sudukoSet()
{
vector<vector<int>> board = {{3, 0, 6, 5, 0, 8, 4, 0, 0},
{5, 2, 0, 0, 0, 0, 0, 0, 0},
{0, 8, 7, 0, 0, 0, 0, 3, 1},
{0, 0, 3, 0, 1, 0, 0, 8, 0},
{9, 0, 0, 8, 6, 3, 0, 0, 5},
{0, 5, 0, 0, 9, 0, 6, 0, 0},
{1, 3, 0, 0, 0, 0, 2, 5, 0},
{0, 0, 0, 0, 0, 0, 0, 7, 4},
{0, 0, 5, 2, 0, 6, 3, 0, 0}};
// cout << suduko_01(board, 0) << endl;
// for suduko 2 ==================================
vector<int> list;
// for (int i = 0; i < 9; i++)
// {
// for (int j = 0; j < 9; j++)
// if (board[i][j] == 0)
// list.push_back(i * 9 + j);
// }
// cout << suduko_02(board, 0,list) << endl;
// for suduko 3 ==================================
// seting the bits;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (board[i][j] == 0)
list.push_back(i * 9 + j);
else
{
int mask = 1 << board[i][j];
row[i] ^= mask;
col[j] ^= mask;
mat[i / 3][j / 3] ^= mask;
}
}
}
cout << suduko_03(board, 0, list) << endl;
display2D(board);
}
// Word Break ===========================================
unordered_set<string> map;
int wordBreak_01(string word, string ans)
{
if (word.length() == 0)
{
cout << ans << endl;
return 1;
}
int count = 0;
for (int i = 1; i <= word.length(); i++)
{
string temp = word.substr(0, i);
if (map.find(temp) != map.end())
{
count += wordBreak_01(word.substr(i), ans + temp + " ");
}
}
return count;
}
void wordBreak()
{
vector<string> words = {"mobile", "samsung", "ilike", "sam", "sung",
"man", "mango", "icecream", "and",
"go", "i", "like", "ice", "cream"};
for (string word : words)
map.insert(word);
string word = "ilikesamsungandmango";
cout << wordBreak_01(word, "");
}
// Crypto code =====================================================
string str1 = "send";
string str2 = "more";
string str3 = "money";
vector<int> Charmap(26, 0);
int numused = 0;
int strToNum(string str)
{
int res = 0;
for (int i = 0; i < str.length(); i++)
{
int temp = Charmap[str[i] - 'a'];
res = res * 10 + temp;
}
return res;
}
// recursive function which check for crypto code correctness
int crypto_(string str, int idx)
{
if (idx == str.length())
{
int num1 = strToNum(str1);
int num2 = strToNum(str2);
int num3 = strToNum(str3);
if (num1 + num2 == num3)
return 1;
return 0;
}
int count = 0;
for (int num = 0; num <= 9; num++)
{
int mask = 1 << num;
if ((numused & mask) == 0)
{
numused ^= mask;
Charmap[str[idx] - 'a'] = num;
count += crypto_(str, idx + 1);
numused ^= mask;
Charmap[str[idx] - 'a'] = num;
}
}
return count;
}
void crypto()
{
string str = str1 + str2 + str3;
//======= first generate unique char =======
int freq = 0;
for (int i = 0; i < str.length(); i++)
{
int mask = (1 << (str[i] - 'a'));
freq |= mask;
}
// then generate no from freq ============
str = "";
for (int i = 0; i < 26; i++)
{
int mask = (1 << i);
if ((freq & mask) != 0)
{
str += (char)(i + 'a');
}
}
// cout << str << endl;
//====== then calling the recursive function to get unique no for all unique char in the str
cout << crypto_(str, 0) << endl;
}
// Cross Word puzzel placing horizontal and vertical ============
//crossword.========================================================
vector<vector<char>> board{{'+', '-', '+', '+', '+', '+', '+', '+', '+', '+'},
{'+', '-', '+', '+', '+', '+', '+', '+', '+', '+'},
{'+', '-', '-', '-', '-', '-', '-', '-', '+', '+'},
{'+', '-', '+', '+', '+', '+', '+', '+', '+', '+'},
{'+', '-', '+', '+', '+', '+', '+', '+', '+', '+'},
{'+', '-', '-', '-', '-', '-', '-', '+', '+', '+'},
{'+', '-', '+', '+', '+', '-', '+', '+', '+', '+'},
{'+', '+', '+', '+', '+', '-', '+', '+', '+', '+'},
{'+', '+', '+', '+', '+', '-', '+', '+', '+', '+'},
{'+', '+', '+', '+', '+', '+', '+', '+', '+', '+'}};
vector<string> words = {"agra", "norway", "england", "gwalior"};
bool canPlaceWordH(int r, int c, string &word)
{
if (c == 0 && word.length() < board[0].size())
{
if (board[r][c + word.length()] != '+')
return false;
}
else if ((c + word.length()) == board[0].size() && word.length() != board[0].size())
{
if (board[r][c - 1] != '+')
return false;
}
else
{
if (((c - 1) >= 0 && board[r][c - 1] != '+') || ((c + word.length()) < board[0].size() && board[r][c + word.length()] != '+'))
return false;
}
for (int i = 0; i < word.length(); i++)
{
if ((c + i) < board[0].size() && board[r][c + i] != '-' && board[r][c + i] != word[i])
{
return false;
}
}
return true;
}
vector<bool> placeWordH(int r, int c, string &word)
{
vector<bool> mark(word.length(), false);
for (int i = 0; i < word.length(); i++)
{
if (board[r][c + i] == '-')
{
mark[i] = true;
board[r][c + i] = word[i];
}
}
return mark;
}
void unPlaceWordH(int r, int c, string &word, vector<bool> &mark)
{
for (int i = 0; i < word.length(); i++)
{
if (mark[i])
board[r][c + i] = '-';
}
}
bool canPlaceWordV(int r, int c, string &word)
{
if (r == 0 && r + word.length() < board.size())
{
if (board[r + word.length()][c] != '+')
return false;
}
else if ((r + word.length()) == board.size() && word.length() != board.size())
{
if (board[r - 1][c] != '+')
return false;
}
else
{
if (((r - 1) >= 0 && board[r - 1][c] != '+') || ((r + word.length()) < board.size() && board[r + word.length()][c] != '+'))
return false;
}
for (int i = 0; i < word.length(); i++)
{
if ((r + i) < board.size() && board[r + i][c] != '-' && board[r + i][c] != word[i])
{
return false;
}
}
return true;
}
vector<bool> placeWordV(int r, int c, string &word)
{
vector<bool> mark(word.length(), false);
for (int i = 0; i < word.length(); i++)
{
if (board[r + i][c] == '-')
{
mark[i] = true;
board[r + i][c] = word[i];
}
}
return mark;
}
void unPlaceWordV(int r, int c, string &word, vector<bool> &mark)
{
for (int i = 0; i < word.length(); i++)
{
if (mark[i])
board[r + i][c] = '-';
}
}
bool crossWord_(int idx)
{
if (idx == words.size())
{
for (vector<char> &ar : board)
{
for (char ch : ar)
cout << ch << " ";
cout << endl;
}
return true;
}
string word = words[idx];
bool res = false;
for (int i = 0; i < board.size(); i++)
{
for (int j = 0; j < board[0].size(); j++)
{
if (board[i][j] == '-' || board[i][j] == word[0])
{
if (canPlaceWordH(i, j, word))
{
vector<bool> mark = placeWordH(i, j, word);
res = res || crossWord_(idx + 1);
unPlaceWordH(i, j, word, mark);
}
if (canPlaceWordV(i, j, word))
{
vector<bool> mark = placeWordV(i, j, word);
res = res || crossWord_(idx + 1);
unPlaceWordV(i, j, word, mark);
}
}
}
}
return res;
}
void crossWord()
{
cout << crossWord_(0) << endl;
}
int main(int argc, char const *argv[])
{
// NqueenSet();
// sudukoSet();
// wordBreak();
// crypto();
crossWord();
return 0;
}
<file_sep>/MyStack/l001.cpp
#include <iostream>
#include <vector>
using namespace std;
class Mystack
{
int sz = 0;
int *arr;
int N = 1000;
int tos = -1;
public:
Mystack()
{
arr = new int[N];
}
Mystack(int sz)
{
N = sz;
arr = new int[sz];
}
int size()
{
return this->sz;
}
bool empty()
{
return this->sz == 0;
}
void push(int val)
{
if (sz > N)
return;
this->tos++;
this->arr[tos] = val;
sz++;
}
int top()
{
if (sz < 1 || sz > N)
return -1;
return this->arr[tos];
}
void pop()
{
if (sz < 1)
return;
int rv = this->arr[tos];
this->tos--;
this->sz--;
}
};
void solve()
{
Mystack st(10);
for (int i = 1; i <= 10; i++)
st.push(i * 10);
for (int i = 0; i < 10; i++)
{
cout << st.top() << endl;
st.pop();
}
}
int main()
{
solve();
return 0;
}<file_sep>/Tree/l001.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import org.graalvm.compiler.phases.common.RemoveValueProxyPhase;
public class l001 {
public static void main(String[] args) {
solve();
}
public static class Node {
int data;
Node left = null; // Node* left=nullptr;
Node right = null; // Node* right=nullptr;
Node(int data) {
this.data = data;
}
Node() {
}
}
static int idx = 0;
public static Node constructTree(int[] arr) {
if (idx >= arr.length || arr[idx] == -1) {
idx++;
return null;
}
Node node = new Node(arr[idx++]); // Node* node=new Node(arr[idx++]);
node.left = constructTree(arr);
node.right = constructTree(arr);
return node;
}
public static void display(Node node) {
if (node == null)
return;
String str = "";
str += ((node.left != null) ? node.left.data : ".");
str += " <- " + node.data + " -> ";
str += ((node.right != null) ? node.right.data : ".");
System.out.println(str);
display(node.left);
display(node.right);
}
// Basic.================================================================
public static int size(Node node) {
if (node == null)
return 0;
return (size(node.left) + size(node.right) + 1);
}
public static int height(Node node) {
if (node == null)
return -1; // return -1, height w.r.t edge, return 0, height w.r.t node.
return Math.max(height(node.left), height(node.right)) + 1;
}
public static int Maximum(Node node) {
if (node == null)
return (int) -1e8; // java: Integer.MIN_VALUE, c++: INT_MIN;
return Math.max(Math.max(Maximum(node.left), Maximum(node.right)), node.data); // max(leftSubtree,rightSubtree,myself);
}
public static int Minimum(Node node) {
if (node == null)
return (int) 1e8; // java: Integer.MAX_VALUE, c++: INT_MAX;
return Math.min(Math.min(Minimum(node.left), Minimum(node.right)), node.data);
}
public static int Minimum_02(Node node) {
int min_ = node.data;
if (node.left != null)
min_ = Math.min(min_, Minimum_02(node.left));
if (node.right != null)
min_ = Math.min(min_, Minimum_02(node.right));
return min_;
}
public static boolean find(Node node, int data) {
if (node == null)
return false;
if (node.data == data)
return true;
return find(node.left, data) || find(node.right, data);
}
// Traversal.============================================================
public static void preOrder(Node node) {
if (node == null)
return;
System.out.print(node.data + " ");
preOrder(node.left);
preOrder(node.right);
}
public static void inOrder(Node node) {
if (node == null)
return;
inOrder(node.left);
System.out.print(node.data + " ");
inOrder(node.right);
}
public static void postOrder(Node node) {
if (node == null)
return;
postOrder(node.left);
postOrder(node.right);
System.out.print(node.data + " ");
}
// node to root path ==========================================================
public static boolean rootToNodePath_(Node root, int data, ArrayList<Node> path) {
if (root == null)
return false;
if (root.data == data) {
path.add(root);
return true;
}
boolean res = rootToNodePath_(root.left, data, path) || rootToNodePath_(root.right, data, path);
if (res)
path.add(root);
return res;
}
public static ArrayList<Node> nodeToRoot_path_02(Node node, int val) {
if (node == null)
return null;
if (node.data == val) {
ArrayList<Node> base = new ArrayList<>();
base.add(node);
return base;
}
ArrayList<Node> left = nodeToRoot_path_02(node.left, val);
if (left != null) {
left.add(node);
return left;
}
ArrayList<Node> right = nodeToRoot_path_02(node.right, val);
if (right != null) {
right.add(node);
return right;
}
return null;
}
// LCA ========================================================
public Node lowestCommonAncestor(Node root, int p, int q) {
ArrayList<Node> path1 = new ArrayList<>();
ArrayList<Node> path2 = new ArrayList<>();
rootToNodePath_(root, p, path1);
rootToNodePath_(root, q, path2);
Node prev = null;
int i = path1.size() - 1;
int j = path2.size() - 1;
while (i >= 0 && j >= 0) {
if (path1.get(i).data != path2.get(j).data)
break;
prev = path1.get(i);
i--;
j--;
}
return prev;
}
static Node LCANode = null;
public static boolean lowestCommonAncestor_02(Node root, int p, int q) {
if (root == null)
return false;
boolean selfDone = false;
if (root.data == p || root.data == q) {
selfDone = true;
}
boolean leftDone = lowestCommonAncestor_02(root.left, p, q);
if (LCANode != null)
return true;
boolean rightDone = lowestCommonAncestor_02(root.right, p, q);
if (LCANode != null)
return true;
if ((selfDone && leftDone) || (selfDone && rightDone) || (leftDone && rightDone))
LCANode = root;
return selfDone || leftDone || rightDone;
}
// all Nodes k down form a given Node in a BT
// =========================================
public static void kDown(Node root, int level, Node blockNode) {
if (root == null || root == blockNode)
return;
if (level == 0) {
System.out.print(root.data + " ");
return;
}
kDown(root.left, level - 1, blockNode);
kDown(root.right, level - 1, blockNode);
}
public static void allNodeKAway(Node root, int target, int K) {
ArrayList<Node> path = new ArrayList<>();
rootToNodePath_(root, target, path);
Node blockNode = null;
for (int i = 0; i < path.size(); i++) {
if (K - i < 0)
break;
kDown(path.get(i), K - i, blockNode);
blockNode = path.get(i);
}
}
public static int allNodeKAway_02_(Node root, int target, int K) {
if (root == null)
return -1;
if (root.data == target) {
kDown(root, K, null);
return 1;
}
int leftdistance = allNodeKAway_02_(root.left, target, K);
if (leftdistance != -1) {
if (K - leftdistance >= 0)
kDown(root, K - leftdistance, root.left);
return leftdistance + 1;
}
int rightdistance = allNodeKAway_02_(root.right, target, K);
if (rightdistance != -1) {
if (K - rightdistance >= 0)
kDown(root, K - rightdistance, root.right);
return rightdistance + 1;
}
return -1;
}
public static void kDown(Node root, int level) {
if (root == null)
return;
if (level == 0) {
System.out.print(root.data + " ");
return;
}
kDown(root.left, level - 1);
kDown(root.right, level - 1);
}
// Diameter of a Tree : total no of nodes b/w the two end nodes of the longest
// path in the tree.
public static int diameter_01(Node root) {
if (root == null) // O(n2) soltuion becuase needed lh,rh for every root;
return 0;
int lh = height(root.left);
int rh = height(root.right);
int ld = diameter_01(root.left);
int rd = diameter_01(root.right);
int myDia = lh + rh + 2;
return Math.max(Math.max(ld, rd), myDia);
}
public static class diaPair {
int dia = 0;
int hei = 0;
diaPair(int dia, int hei) {
this.dia = dia;
this.hei = hei;
}
}
public static diaPair diameter_02(Node node) {
if (node == null)
return new diaPair(0, -1);
diaPair lr = diameter_02(node.left);
diaPair rr = diameter_02(node.right);
diaPair myRes = new diaPair(0, -1);
myRes.dia = Math.max(Math.max(lr.dia, rr.dia), lr.hei + rr.hei + 2);
myRes.hei = Math.max(lr.hei, rr.hei) + 1;
return myRes;
}
public static int diameter = 0;
public static int diameter_03(Node node) {
if (node == null)
return -1;
int lh = diameter_03(node.left);
int rh = diameter_03(node.right);
diameter = Math.max(diameter, lh + rh + 2);
return Math.max(lh, rh) + 1;
}
public static class pairVO {
Node node;
int vl;
pairVO(Node node, int vl) {
this.node = node;
this.vl = vl;
}
}
// View=====================================================================
public static void leftView(Node node) {
LinkedList<Node> que = new LinkedList<>(); // addLast and removeFirst.
que.addLast(node);
while (que.size() != 0) {
int size = que.size();
System.out.print(que.getFirst().data + " ");
while (size-- > 0) {
Node rnode = que.removeFirst();
if (rnode.left != null)
que.addLast(rnode.left);
if (rnode.right != null)
que.addLast(rnode.right);
}
}
System.out.println();
}
public static void rightView(Node node) {
LinkedList<Node> que = new LinkedList<>(); // addLast and removeFirst.
que.addLast(node);
while (que.size() != 0) {
int size = que.size();
Node prev = null;
while (size-- > 0) {
Node rnode = que.removeFirst();
if (rnode.left != null)
que.addLast(rnode.left);
if (rnode.right != null)
que.addLast(rnode.right);
prev = rnode;
}
System.out.print(prev.data + " ");
}
System.out.println();
}
static int leftMinValue = 0;
static int rightMaxValue = 0;
public static void width(Node node, int lev) {
if (node == null)
return;
leftMinValue = Math.min(leftMinValue, lev);
rightMaxValue = Math.max(rightMaxValue, lev);
width(node.left, lev - 1);
width(node.right, lev + 1);
}
public static class pairVO {
Node node; // actual Node
int vl = 0; // vertical Level
public pairVO(Node node, int vl) {
this.node = node;
this.vl = vl;
}
}
public static void verticalOrder(Node node) {
width(node, 0);
int n = rightMaxValue - leftMinValue + 1;
ArrayList<ArrayList<Integer>> ans = new ArrayList<>(); // vector<vector<int>> (n,vector<int>());
for (int i = 0; i < n; i++)
ans.add(new ArrayList<>());
LinkedList<pairVO> que = new LinkedList<>();
que.addLast(new pairVO(node, -leftMinValue));
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
pairVO rpair = que.removeFirst();
ans.get(rpair.vl).add(rpair.node.data);
if (rpair.node.left != null)
que.addLast(new pairVO(rpair.node.left, rpair.vl - 1));
if (rpair.node.right != null)
que.addLast(new pairVO(rpair.node.right, rpair.vl + 1));
}
}
for (ArrayList<Integer> ar : ans)
System.out.println(ar);
System.out.println();
}
public static void verticalOrderSum(Node node) {
width(node, 0);
int[] ans = new int[rightMaxValue - leftMinValue + 1];
LinkedList<pairVO> que = new LinkedList<>();
que.addLast(new pairVO(node, -leftMinValue));
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
pairVO rpair = que.removeFirst();
ans[rpair.vl] += rpair.node.data;
if (rpair.node.left != null)
que.addLast(new pairVO(rpair.node.left, rpair.vl - 1));
if (rpair.node.right != null)
que.addLast(new pairVO(rpair.node.right, rpair.vl + 1));
}
}
for (int ele : ans)
System.out.println(ele);
System.out.println();
}
public static void bottomView(Node node) {
width(node, 0);
int[] ans = new int[rightMaxValue - leftMinValue + 1];
LinkedList<pairVO> que = new LinkedList<>();
que.addLast(new pairVO(node, -leftMinValue));
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
pairVO rpair = que.removeFirst();
ans[rpair.vl] = rpair.node.data;
if (rpair.node.left != null)
que.addLast(new pairVO(rpair.node.left, rpair.vl - 1));
if (rpair.node.right != null)
que.addLast(new pairVO(rpair.node.right, rpair.vl + 1));
}
}
for (int ele : ans)
System.out.println(ele);
System.out.println();
}
public static void topView(Node node) {
width(node, 0);
int[] ans = new int[rightMaxValue - leftMinValue + 1];
Arrays.fill(ans, (int) -1e8);
LinkedList<pairVO> que = new LinkedList<>();
que.addLast(new pairVO(node, -leftMinValue));
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
pairVO rpair = que.removeFirst();
if (ans[rpair.vl] == (int) -1e8)
ans[rpair.vl] = rpair.node.data;
if (rpair.node.left != null)
que.addLast(new pairVO(rpair.node.left, rpair.vl - 1));
if (rpair.node.right != null)
que.addLast(new pairVO(rpair.node.right, rpair.vl + 1));
}
}
for (int ele : ans)
System.out.println(ele);
System.out.println();
}
static int leftDMinValue = 0;
public static void widthDiagonal(Node node, int lev) {
if (node == null)
return;
leftMinValue = Math.min(leftMinValue, lev);
width(node.left, lev - 1);
width(node.right, lev + 0);
}
public static void diagonalOrder(Node node) {
widthDiagonal(node, 0);
int n = -leftDMinValue + 1;
ArrayList<ArrayList<Integer>> ans = new ArrayList<>(); // vector<vector<int>> (n,vector<int>());
for (int i = 0; i < n; i++)
ans.add(new ArrayList<>());
LinkedList<pairVO> que = new LinkedList<>();
que.addLast(new pairVO(node, -leftMinValue));
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
pairVO rpair = que.removeFirst();
ans.get(rpair.vl).add(rpair.node.data);
if (rpair.node.left != null)
que.addLast(new pairVO(rpair.node.left, rpair.vl - 1));
if (rpair.node.right != null)
que.addLast(new pairVO(rpair.node.right, rpair.vl + 0));
}
}
for (ArrayList<Integer> ar : ans)
System.out.println(ar);
System.out.println();
}
public static void diagonalSum(Node node) {
widthDiagonal(node, 0);
int n = -leftDMinValue + 1;
int[] ans = new int[n];
LinkedList<pairVO> que = new LinkedList<>();
que.addLast(new pairVO(node, -leftMinValue));
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
pairVO rpair = que.removeFirst();
ans[rpair.vl] += rpair.node.data;
if (rpair.node.left != null)
que.addLast(new pairVO(rpair.node.left, rpair.vl - 1));
if (rpair.node.right != null)
que.addLast(new pairVO(rpair.node.right, rpair.vl + 0));
}
}
for (int ele : ans)
System.out.println(ele);
System.out.println();
}
static Node DLLhead = null;
static Node DLLprev = null;
public static void DLL(Node node) {
if (node == null)
return;
DLL(node.left);
if (DLLhead == null) {
DLLhead = node;
} else {
DLLprev.right = node;
node.left = DLLprev;
}
DLLprev = node;
DLL(node.right);
}
public static class allSolution {
int height = 0;
int size = 0;
boolean find = false;
Node pred = null;
Node succ = null;
Node prev = null;
}
public static void allSol(Node node, int data, int level, allSolution pair) {
if (node == null)
return;
pair.size++;
pair.height = Math.max(pair.height, level);
pair.find = pair.find || node.data == data;
if (node.data == data && pair.pred == null)
pair.pred = prev;
if (pair.prev != null && pair.prev.data == data && pair.succ == null)
pair.succ = node;
pair.prev = node;
allSol(node.left, data, level + 1, pair);
allSol(node.right, data, level + 1, pair);
}
// Iterative travesal of the tree using a class
// ==================================
// =================================================================
public static class tpair { // traversalPair
Node node = null;
boolean selfDone = false;
boolean leftDone = false;
boolean rightDone = false;
tpair(Node node, boolean selfDone, boolean leftDone, boolean rightDone) {
this.node = node;
this.leftDone = leftDone;
this.selfDone = selfDone;
this.rightDone = rightDone;
}
}
public static void ItrTraversalOfTree(Node node) {
Stack<tpair> st = new Stack<>();
st.push(new tpair(node, false, false, false));
while (st.size() != 0) {
if (st.peek().selfDone == false) {
st.peek().selfDone = true;
System.out.print(st.peek().node.data + " ");
} else if (st.peek().leftDone == false) {
st.peek().leftDone = true;
if (st.peek().node.left != null) {
st.push(new tpair(st.peek().node.left, false, false, false));
}
} else if (st.peek().rightDone == false) {
st.peek().rightDone = true;
if (st.peek().node.right != null) {
st.push(new tpair(st.peek().node.right, false, false, false));
}
} else {
st.pop();
}
}
}
public static class tpair_ { // traversalPair
Node node = null;
boolean selfDone = false;
boolean leftDone = false;
boolean rightDone = false;
int ld = -1;
int rd = -1;
int sd = -1;
boolean isleft = false;
tpair_(Node node, boolean selfDone, boolean leftDone, boolean rightDone, boolean isleft) {
this.node = node;
this.leftDone = leftDone;
this.selfDone = selfDone;
this.rightDone = rightDone;
this.isleft = isleft;
}
}
public static void ItrHeightOfTree(Node node) {
Stack<tpair_> st = new Stack<>();
st.push(new tpair_(node, false, false, false, false));
tpair_ rpair = null;
while (st.size() != 0) {
if (st.peek().leftDone == false) {
st.peek().leftDone = true;
if (st.peek().node.left != null) {
st.push(new tpair_(st.peek().node.left, false, false, false, true));
}
} else if (st.peek().rightDone == false) {
st.peek().rightDone = true;
if (st.peek().node.right != null) {
st.push(new tpair_(st.peek().node.right, false, false, false, false));
}
} else if (st.peek().selfDone == false) {
st.peek().selfDone = true;
st.peek().sd = Math.max(st.peek().ld, st.peek().rd) + 1;
} else {
rpair = st.pop();
if (st.size() != 0) {
if (st.peek().isleft)
st.peek().ld = rpair.sd;
else
st.peek().rd = rpair.sd;
}
}
}
System.out.println(rpair.sd);
}
public static Node rightMost_of_LeftNode(Node lnode, Node curr) {
while (lnode.right != null && lnode.right != curr) {
lnode = lnode.right;
}
return lnode;
}
public static void morrisInOrder(Node node) {
Node curr = node;
while (curr != null) {
if (curr.left == null) {
System.out.print(curr.data + " ");
curr = curr.right;
} else {
Node leftNode = curr.left;
Node rightMost = rightMost_of_LeftNode(leftNode, curr);
if (rightMost.right == null) { // thread create
rightMost.right = curr;
curr = curr.left;
} else { // thread break
rightMost.right = null;
System.out.print(curr.data + " ");
curr = curr.right;
}
}
}
System.out.println();
}
public static void morrisPreOrder(Node node) {
Node curr = node;
while (curr != null) {
if (curr.left == null) {
System.out.print(curr.data + " ");
curr = curr.right;
} else {
Node leftNode = curr.left;
Node rightMost = rightMost_of_LeftNode(leftNode, curr);
if (rightMost.right == null) { // thread create
rightMost.right = curr;
System.out.print(curr.data + " ");
curr = curr.left;
} else { // thread break
rightMost.right = null;
curr = curr.right;
}
}
}
System.out.println();
}
// psi = preStartIndex, pei=preEndIndex, isi=inStartIndex, iei=inEndIndex
public static Node ConstructFromPreAndIn(int[] pre, int psi, int pei, int[] in, int isi, int iei) {
if (psi > pei || isi > iei)
return null;
Node node = new Node(pre[psi]);
int idx = isi;
while (in[idx] != pre[psi]) {
idx++;
}
int tnel = idx - isi; // total no of elements between isi and idx
node.left = ConstructFromPreAndIn(pre, psi + 1, psi + tnel, in, isi, idx - 1);
node.right = ConstructFromPreAndIn(pre, psi + tnel + 1, pei, in, idx + 1, iei);
return node;
}
public static Node ConstructFromPreAndIn(int[] pre, int[] in) {
return ConstructFromPreAndIn(pre, 0, pre.length - 1, in, 0, in.length - 1);
}
// psi = postStartIndex, pei=postEndIndex, isi=inStartIndex, iei=inEndIndex
public static Node ConstructFromPostAndIn(int[] post, int psi, int pei, int[] in, int isi, int iei) {
if (psi > pei || isi > iei)
return null;
Node node = new Node(pre[pei]);
int idx = isi;
while (in[idx] != pre[psi]) {
idx++;
}
int tnel = idx - isi; // total no of elements between isi and idx
node.left = ConstructFromPostAndIn(post, psi, psi + tnel - 1, in, isi, idx - 1);
node.right = ConstructFromPostAndIn(post, psi + tnel, pei - 1, in, idx + 1, iei);
return node;
}
public static Node ConstructFromPostAndIn(int[] post, int[] in) {
return ConstructFromPostAndIn(post, 0, post.length - 1, in, 0, in.length - 1);
}
// psi = preStartIndex, pei=preEndIndex, ppsi=postStartIndex, ppei=postEndIndex
public static Node ConstructFromPreAndPost(int[] post, int psi, int pei, int[] in, int ppsi, int ppei) {
if (psi > pei || ppsi > ppei)
return null;
Node node = new Node(pre[psi]);
int idx = ppsi;
while (post[idx] != pre[psi + 1]) {
idx++;
}
int tnel = idx - isi + 1; // total no of elements between isi and idx
node.left = ConstructFromPreAndPost(post, psi + 1, psi + tnel, in, ppsi, idx);
node.right = ConstructFromPreAndPost(post, psi + tnel + 1, pei, in, idx + 1, iei - 1);
return node;
}
public static Node ConstructFromPreAndPost(int[] pre, int[] post) {
return ConstructFromPreAndPost(pre, 0, pre.length - 1, post, 0, post.length - 1);
}
public static void set2(Node node) {
DLL(node);
while (DLLhead != null) {
System.out.print(DLLhead.data + " ");
DLLhead = DLLhead.right;
}
}
public static void view(Node node) {
// leftView(node);
// rightView(node);
// verticalOrder(node);
// bottomView(node);
// topView(node);
}
public static void levelOrder(Node node) {
// levelOrder_00(node);
// levelOrder_01(node);
// levelOrder_02(node);
// levelOrder_03(node);
}
public static void solve() {
// int[] arr = { 10, 20, 40, 50, 80, -1, -1, 90, -1, -1, 30, 60, 100, -1, -1,
// -1, 70, 110, -1, -1, 120, -1,
// -1 };
int[] arr = { 11, 6, 4, -1, 5, -1, -1, 8, -1, 10, -1, -1, 19, 17, -1, -1, 43, 31, -1, -1, 49, -1, -1 };
// int[] arr = { 10, 20 };
Node root = constructTree(arr);
display(root);
// ArrayList<Node> ans = nodeToRoot_path(root, 60);
// System.out.println(ans);
view(root);
}
}<file_sep>/LinkedList/question.java
public class ListNode {
public class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
// Leetcode 876: getMid
public ListNode getMidNode(ListNode node) {
if (node == null || node.next == null)
return node;
ListNode slow = node;
ListNode fast = node;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
// Leetcode 206 : reverseOfLL
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode forw = curr.next;
curr.next = prev;
prev = curr;
curr = forw;
}
return prev;
}
// Class Question: reverse Data.
public void reverseListData(ListNode head) {
if (head == null || head.next == null)
return;
ListNode curr = head;
ListNode midNode = getMidNode(curr);
ListNode nhead = midNode.next;
midNode.next = null;
nhead = reverseList(nhead);
ListNode curr1 = nhead;
while (curr != null && curr1 != null) {
int temp = curr.val;
curr.val = curr1.val;
curr1.val = temp;
curr = curr.next;
curr1 = curr1.next;
}
nhead = reverseList(nhead);
midNode.next = nhead;
}
// IN this the middel node is by index wise;
public ListNode getMidNode2(ListNode node) {
if (node == null || node.next == null)
return node;
ListNode slow = node;
ListNode fast = node;
while (fast != null && fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
// Leetcode 234: palindrome
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null)
return true;
ListNode curr = head;
ListNode midNode = getMidNode2(curr);
ListNode nhead = midNode.next;
midNode.next = null;
nhead = reverseList(nhead);
ListNode curr1 = nhead;
while (curr != null && curr1 != null) {
if (curr.val != curr1.val)
return false;
curr = curr.next;
curr1 = curr1.next;
}
nhead = reverseList(nhead);
midNode.next = nhead;
return true;
}
public ListNode removeNthFromEnd(ListNode head, int n) {
if (n == 0 || head == null)
return head;
if (n == 1 && head.next == null)
return null;
ListNode slow = head, fast = head;
while (n-- > 0) {
fast = fast.next;
// if(fast==null && n > 0) return null; // if n is greater than one;
}
if (fast == null)
return slow.next;
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
ListNode forw = slow.next;
slow.next = slow.next.next;
forw.next = null;
return head;
}
public void reorderList(ListNode head) {
if (head == null || head.next == null)
return;
ListNode curr1 = head;
ListNode midNode = getMidNode2(curr1);
ListNode nhead = midNode.next;
midNode.next = null;
nhead = reverseList(nhead);
ListNode curr2 = nhead;
while (curr1 != null && curr2 != null) {
ListNode forw1 = curr1.next;
ListNode forw2 = curr2.next;
curr1.next = curr2;
curr2.next = forw1;
curr1 = forw1;
curr2 = forw2;
}
}
// Leetcode 21: merge Two LL.
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null)
return l1 == null ? l2 : l1;
ListNode head = new ListNode(-1);
ListNode prev = head;
ListNode curr1 = l1;
ListNode curr2 = l2;
while (curr1 != null && curr2 != null) {
if (curr1.val <= curr2.val) {
prev.next = curr1;
prev = curr1;
curr1 = curr1.next;
} else {
prev.next = curr2;
prev = curr2;
curr2 = curr2.next;
}
}
if (curr1 != null) {
prev.next = curr1;
}
if (curr2 != null) {
prev.next = curr2;
}
return head.next;
}
// mergining two linked list using recurson
Node mergeTwoLists(Node l1, Node l2) {
if (l1 == null) {
return l2;
} else if (l2 == null) {
return l1;
}
if (l1.val <= l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
// Leetcode 328:
public ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode curr1 = head;
ListNode nhead = head.next;
ListNode curr2 = head.next;
while (curr1.next != null && curr2.next != null) {
curr1.next = curr2.next;
curr1 = curr2.next;
curr2.next = curr1.next;
curr2 = curr1.next;
}
curr1.next = nhead;
return head;
}
// leetcode 41:
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null)
return false;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
return true;
}
return false;
}
// Leetcode 142: detectCyclePoint
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
break;
}
if (slow != fast)
return head;
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
// LeetCode 25: reverse K nodes in group=====================
ListNode oh = null;
ListNode ot = null;
ListNode th = null;
ListNode tt = null;
public void addFirstNode(ListNode node) {
if (th == null) {
th = node;
tt = node;
} else {
node.next = th;
th = node;
}
}
public int len(ListNode node) {
int l = 0;
while (node != null) {
l++;
node = node.next;
}
return l;
}
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null || k == 0 || k == 1)
return head;
int len = len(head);
if (len < k)
return head;
ListNode curr = head;
while (curr != null) {
int tk = k;
while (tk-- > 0) {
ListNode forw = curr.next;
curr.next = null;
addFirstNode(curr);
curr = forw;
}
len -= k;
if (ot == null) {
oh = th;
ot = tt;
} else {
ot.next = th;
ot = tt;
}
th = null;
tt = null;
if (len < k) {
ot.next = curr;
curr = null;
}
}
return oh;
}
public ListNode reverseKGroup_02(ListNode head, int k) {
if (head == null || head.next == null)
return head;
int len = len(head);
if (len < k)
return head;
ListNode nhead = null;
ListNode ntail = head;
while (head != null) {
int temp = k;
ListNode ttail = null;
ListNode rev = null;
if (len >= k) {
while (head != null && temp != 0) {
if (ttail == null) {
ttail = head;
}
ListNode forw = head.next;
head.next = rev;
rev = head;
head = forw;
temp--;
}
len -= k;
if (nhead == null) {
nhead = rev;
} else {
ntail.next = rev;
ntail = ttail;
}
} else {
ntail.next = head;
break;
}
}
return nhead;
}
// Leetcode 92==============================================
// ListNode th = null;
// ListNode tt = null;
// public void addFirstNode(ListNode node) {
// if (th == null) {
// th = node;
// tt = node;
// } else {
// node.next = th;
// th = node;
// }
// }
public ListNode reverseBetween(ListNode node, int m, int n) {
if (node.next == null || m == n)
return node;
int idx = 1;
ListNode curr = node;
ListNode prev = null;
ListNode nhead = node;
while (curr != null) {
while (idx >= m && idx <= n) {
ListNode forw = curr.next;
curr.next = null;
addFirstNode(curr);
curr = forw;
idx++;
}
if (tt != null) {
tt.next = curr;
if (prev != null)
prev.next = th;
else
nhead = th;
break;
}
prev = curr;
curr = curr.next;
idx++;
}
return nhead;
}
}<file_sep>/Dp/l001.cpp
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <unordered_map>
#define lli long long int
#define vi vector<int>
#define vvi vector<vector<int>>
using namespace std;
void display(vector<int> &dp)
{
for (int ele : dp)
cout << ele << " ";
cout << endl;
}
void display2D(vector<vector<int>> &dp)
{
for (vector<int> &ar : dp)
{
for (int ele : ar)
cout << ele << " ";
cout << endl;
}
cout << endl;
}
// Fibonacci =====================================================
//memoizatio
int fibo(int n, vector<int> &dp)
{
if (n <= 1)
return dp[n] = n;
if (dp[n] != 0)
return dp[n];
return dp[n] = fibo(n - 1, dp) + fibo(n - 2, dp);
}
//tabulation
int fiboDp(int N, vector<int> &dp)
{
for (int n = 0; n <= N; n++)
{
if (n <= 1)
{
dp[n] = n;
continue;
}
dp[n] = dp[n - 1] + dp[n - 2]; //fibo(n - 1, dp) + fibo(n - 2, dp);
}
return dp[N];
}
void set1()
{
int n = 6;
vi dp(n + 1, 0);
cout << fibo(6, dp) << endl;
cout << fiboDp(6, dp) << endl;
display(dp);
}
//MazePathSeries.==============================================
int mazePathHV(int sr, int sc, int er, int ec, vector<vector<int>> &dp)
{
if (sr == er && sc == ec)
{
return dp[sr][sc] = 1;
}
if (dp[sr][sc] != 0)
return dp[sr][sc];
int count = 0;
if (sr + 1 <= er)
count += mazePathHV(sr + 1, sc, er, ec, dp);
if (sc + 1 <= ec)
count += mazePathHV(sr, sc + 1, er, ec, dp);
if (sr + 1 <= er && sc + 1 <= ec)
count += mazePathHV(sr + 1, sc + 1, er, ec, dp);
return dp[sr][sc] = count;
}
int mazePathHV_DP(int sr, int sc, int er, int ec, vector<vector<int>> &dp)
{
for (sr = er; sr >= 0; sr--)
{
for (sc = ec; sc >= 0; sc--)
{
if (sr == er && sc == ec)
{
dp[sr][sc] = 1;
continue;
}
int count = 0;
if (sr + 1 <= er)
count += dp[sr + 1][sc]; //mazePathHV(sr + 1, sc, er, ec, dp);
if (sc + 1 <= ec)
count += dp[sr][sc + 1]; //mazePathHV(sr, sc + 1, er, ec, dp);
if (sr + 1 <= er && sc + 1 <= ec)
count += dp[sr + 1][sc + 1]; //mazePathHV(sr + 1, sc + 1, er, ec, dp);
dp[sr][sc] = count;
}
}
return dp[0][0];
}
int mazePathMulti(int sr, int sc, int er, int ec, vector<vector<int>> &dp)
{
if (sr == er && sc == ec)
{
return dp[sr][sc] = 1;
}
if (dp[sr][sc] != 0)
return dp[sr][sc];
int count = 0;
for (int jump = 1; sr + jump <= er; jump++)
count += mazePathMulti(sr + jump, sc, er, ec, dp);
for (int jump = 1; sc + jump <= ec; jump++)
count += mazePathMulti(sr, sc + jump, er, ec, dp);
for (int jump = 1; sr + jump <= er && sc + jump <= ec; jump++)
count += mazePathMulti(sr + jump, sc + jump, er, ec, dp);
return dp[sr][sc] = count;
}
int mazePathMulti_DP(int sr, int sc, int er, int ec, vector<vector<int>> &dp)
{
for (sr = er; sr >= 0; sr--)
{
for (sc = ec; sc >= 0; sc--)
{
if (sr == er && sc == ec)
{
dp[sr][sc] = 1;
continue;
}
int count = 0;
for (int jump = 1; sr + jump <= er; jump++)
count += dp[sr + jump][sc]; //mazePathMulti(sr + jump, sc, er, ec, dp);
for (int jump = 1; sc + jump <= ec; jump++)
count += dp[sr][sc + jump]; //mazePathMulti(sr, sc + jump, er, ec, dp);
for (int jump = 1; sr + jump <= er && sc + jump <= ec; jump++)
count += dp[sr + jump][sc + jump]; //mazePathMulti(sr + jump, sc + jump, er, ec, dp);
dp[sr][sc] = count;
}
}
return dp[0][0];
}
int boardPath(int sp, int ep, vector<int> &dp)
{
if (sp == ep)
{
return dp[sp] = 1;
}
if (dp[sp] != 0)
return dp[sp];
int count = 0;
for (int dice = 1; sp + dice <= ep && dice <= 6; dice++)
count += boardPath(sp + dice, ep, dp);
return dp[sp] = count;
}
int boardPathDP(int sp, int ep, vector<int> &dp)
{
for (sp = ep; sp >= 0; sp--)
{
if (sp == ep)
{
dp[sp] = 1;
continue;
}
int count = 0;
for (int dice = 1; sp + dice <= ep && dice <= 6; dice++)
count += dp[sp + dice]; //boardPath(sp + dice, ep, dp);
dp[sp] = count;
}
return dp[0];
}
int boardPath_best(int sp, int ep)
{
list<int> ll;
for (sp = ep; sp >= 0; sp--)
{
if (sp > ep - 2)
{
ll.push_front(1);
continue;
}
if (ll.size() <= 6)
ll.push_front(2 * ll.front());
else
{
ll.push_front(2 * ll.front() - ll.back());
ll.pop_back();
}
}
return ll.front();
}
int boardPathWithDiceArrayDP(int sp, int ep, vector<int> &dp, vector<int> &diceArray)
{
for (sp = ep; sp >= 0; sp--)
{
if (sp == ep)
{
dp[sp] = 1;
continue;
}
int count = 0;
for (int dice = 0; sp + diceArray[dice] <= ep && dice < diceArray.size(); dice++)
count += dp[sp + diceArray[dice]]; //boardPath(sp + dice, ep, dp);
dp[sp] = count;
}
return dp[0];
}
//Leetcode 70.=================================================================================
int climbStairs_01(int n, vector<int> &dp)
{
if (n <= 1)
{
return dp[n] = 1;
}
if (dp[n] != 0)
return dp[n];
int ans = climbStairs_01(n - 1, dp) + climbStairs_01(n - 2, dp);
return dp[n] = ans;
}
int climbStairs_DP(int n, vector<int> &dp)
{
int N = n;
for (n = 0; n <= N; n++)
{
if (n <= 1)
{
dp[n] = 1;
continue;
}
int ans = dp[n - 1] + dp[n - 2]; //climbStairs_01(n - 1, dp) + climbStairs_01(n - 2, dp);
dp[n] = ans;
}
return dp[N];
}
int climbStairs_btr(int n)
{
int a = 1;
int b = 1;
int sum = 1;
for (int i = 2; i <= n; i++)
{
sum = a + b;
a = b;
b = sum;
}
return sum;
}
int climbStairs(int n)
{
vector<int> dp(n + 1, 0);
// return climbStairs_01(n, dp);
// return climbStairs_DP(n,dp);
return climbStairs_btr(n);
}
int minCostClimbingStairs(int n, vector<int> &dp, vector<int> &cost)
{
if (n <= 1)
{
return dp[n] = cost[n];
}
if (dp[n] != 0)
return dp[n];
int ans = min(minCostClimbingStairs(n - 1, dp, cost),
minCostClimbingStairs(n - 2, dp, cost));
return dp[n] = ans + cost[n];
}
int minCostClimbingStairsDP(int n, vector<int> &dp, vector<int> &cost)
{
int N = n;
for (int n = 0; n <= N; n++)
{
if (n <= 1)
{
dp[n] = cost[n];
continue;
}
int ans = min(dp[n - 1], dp[n - 2]);
dp[n] = ans + cost[n];
}
return dp[N];
}
int minCostClimbingStairs(vector<int> &cost)
{
int n = cost.size();
cost.push_back(0);
vector<int> dp(n + 1, 0);
// return minCostClimbingStairs(n, dp, cost);
return minCostClimbingStairsDP(n, dp, cost);
}
void pathSet()
{
// int n = 3, m = 3;
// vector<vector<int>> dp(n, vector<int>(m, 0));
// cout << mazePathHV(0, 0, n - 1, m - 1, dp) << endl;
// cout << mazePathHV_DP(0, 0, n - 1, m - 1, dp) << endl;
// cout << mazePathMulti(0, 0, n - 1, m - 1, dp) << endl;
// cout << mazePathMulti(0, 0, n - 1, m - 1, dp) << endl;
// int sp = 0, ep = 10;
// vector<int> dp(ep + 1, 0);
// vector<int> diceArray{1, 2, 3, 4, 5, 6};
// cout << boardPathDP(sp, ep, dp) << endl;
// cout << boardPathWithDiceArrayDP(sp, ep, dp, diceArray) << endl;
// cout << boardPath_best(sp, ep);
// vector<vector<int>> grid = {{1, 3, 1, 5},
// {2, 2, 4, 1},
// {5, 0, 2, 3},
// {0, 6, 1, 2}};
// int n = grid.size(), m = grid[0].size();
// vector<vector<int>> dp(n, vector<int>(m, 0));
// int maxCoin = 0;
// for (int i = 0; i < n; i++)
// {
// maxCoin = max(maxCoin, goldMin(i, 0, grid, dp));
// }
// maxCoin = goldMin_DP(grid, dp);
// cout << maxCoin << endl;
// count_of_ways(7, 3);
// display(dp);
// display2D(dp);
}
// friends pairing problme gfg ==================================================
int friends_pairing_problem(int n, vi &dp)
{
if (n <= 1)
return 1;
if (!dp[n])
return dp[n];
int single = friends_pairing_problem(n - 1, dp);
int pairUp = friends_pairing_problem(n - 2, dp) * (n - 1);
return dp[n] = single + pairUp;
}
int friends_pairing_problem_DP(int n, vector<int> &dp)
{
int N = n;
for (int n = 0; n <= N; n++)
{
if (n <= 1)
{
dp[n] = 1;
continue;
}
int single = dp[n - 1]; //friends_pairing_problem(n - 1, dp);
int pairUp = dp[n - 2] * (n - 1); //friends_pairing_problem(n - 2, dp) * (n - 1);
dp[n] = (single + pairUp);
}
return dp[N];
}
void set2()
{
int n = 10;
vector<int> dp(n + 1, 0);
// cout << friends_pairing_problem(n, dp) << endl;
cout << friends_pairing_problem_DP(n, dp) << endl;
display(dp);
}
// Leetcode 64 minpath sum ===================================
int minPathSum(int sr, int sc, vector<vector<int>> &grid, vector<vector<int>> &dp)
{
if (sr == grid.size() - 1 && sc == grid[0].size() - 1)
{
return dp[sr][sc] = grid[sr][sc];
}
if (dp[sr][sc] != 0)
return dp[sr][sc];
int minCost = 1e8;
if (sr + 1 < grid.size())
minCost = min(minCost, minPathSum(sr + 1, sc, grid, dp));
if (sc + 1 < grid[0].size())
minCost = min(minCost, minPathSum(sr, sc + 1, grid, dp));
return dp[sr][sc] = minCost + grid[sr][sc];
}
int minPathSum_DP(int sr, int sc, vector<vector<int>> &grid, vector<vector<int>> &dp)
{
for (sr = grid.size() - 1; sr >= 0; sr--)
{
for (sc = grid[0].size() - 1; sc >= 0; sc--)
{
if (sr == grid.size() - 1 && sc == grid[0].size() - 1)
{
dp[sr][sc] = grid[sr][sc];
continue;
}
int minCost = 1e8;
if (sr + 1 < grid.size())
minCost = min(minCost, dp[sr + 1][sc]);
if (sc + 1 < grid[0].size())
minCost = min(minCost, dp[sr][sc + 1]);
dp[sr][sc] = minCost + grid[sr][sc];
}
}
return dp[0][0];
}
int minPathSum(vector<vector<int>> &grid)
{
vector<vector<int>> dp(grid.size(), vector<int>(grid[0].size(), 0));
return minPathSum(0, 0, grid, dp);
}
// Gold Mine problem gfg ====================================================
int goldMin(int sr, int sc, vector<vector<int>> &grid, vector<vector<int>> &dp)
{
if (sc == grid[0].size() - 1)
{
return dp[sr][sc] = grid[sr][sc];
}
if (dp[sr][sc] != 0)
return dp[sr][sc];
int dir[3][2] = {{-1, 1}, {0, 1}, {1, 1}};
int maxCoins = 0;
for (int d = 0; d < 3; d++)
{
int x = sr + dir[d][0];
int y = sc + dir[d][1];
if (x >= 0 && y >= 0 && x < grid.size() && y < grid[0].size())
{
maxCoins = max(maxCoins, goldMin(x, y, grid, dp));
}
}
return dp[sr][sc] = maxCoins + grid[sr][sc];
}
int goldMin_DP(vector<vector<int>> &grid, vector<vector<int>> &dp)
{
for (int sc = grid[0].size() - 1; sc >= 0; sc--)
{
for (int sr = grid.size() - 1; sr >= 0; sr--)
{
if (sc == grid[0].size() - 1)
{
dp[sr][sc] = grid[sr][sc];
continue;
}
int dir[3][2] = {{-1, 1}, {0, 1}, {1, 1}};
int maxCoins = 0;
for (int d = 0; d < 3; d++)
{
int x = sr + dir[d][0];
int y = sc + dir[d][1];
if (x >= 0 && y >= 0 && x < grid.size() && y < grid[0].size())
maxCoins = max(maxCoins, dp[x][y]);
}
dp[sr][sc] = maxCoins + grid[sr][sc];
}
}
int maxCoin = 0;
for (int i = 0; i < grid.size(); i++)
maxCoin = max(maxCoin, dp[i][0]);
return maxCoin;
}
// https://www.geeksforgeeks.org/count-number-of-ways-to-partition-a-set-into-k-subsets/
int count_of_ways(int n, int k, vector<vector<int>> &dp)
{
if (n < k)
return 0;
if (n == k || k == 1)
return dp[k][n] = 1;
if (dp[k][n] != 0)
return dp[k][n];
int newGroup = count_of_ways(n - 1, k - 1, dp);
int ExistingGroup = count_of_ways(n - 1, k, dp) * k;
return dp[k][n] = newGroup + ExistingGroup;
}
int count_of_ways_DP(int n, int k, vector<vector<int>> &dp)
{
int K = k, N = n;
for (k = 1; k <= K; k++)
{
for (n = 0; n <= N; n++)
{
if (n < k)
continue;
if (n == k || k == 1)
{
dp[k][n] = 1;
continue;
}
int newGroup = dp[k - 1][n - 1];
int ExistingGroup = dp[k][n - 1] * k;
dp[k][n] = newGroup + ExistingGroup;
}
}
return dp[K][N];
}
void count_of_ways(int n, int k)
{
if (n < k)
return;
vector<vector<int>> dp(k + 1, vector<int>(n + 1, 0));
// cout << count_of_ways(n, k, dp) << endl;
cout << count_of_ways_DP(n, k, dp) << endl;
display2D(dp);
}
// Substirng and Subsequence with palindrome ============================================
vector<vector<bool>> isPlaindromeSubstring(string str)
{
int n = str.size();
vector<vector<bool>> dp(n, vector<bool>(n, 0));
for (int gap = 0; gap < n; gap++)
{
for (int i = 0, j = gap; j < n; i++, j++)
{
if (gap == 0)
dp[i][j] = true;
else if (gap == 1 && str[i] == str[j])
dp[i][j] = true;
else
dp[i][j] = str[i] == str[j] && dp[i + 1][j - 1];
}
}
return dp;
}
//Leetcode 005.==================================================================
string longestPlaindromeSubstring(string str)
{
int n = str.length();
vector<vector<int>> dp(n, vector<int>(n, 0));
int maxLen = 0;
int si = 0, ei = 0;
for (int gap = 0; gap < n; gap++)
{
for (int i = 0, j = gap; j < n; i++, j++)
{
if (gap == 0)
dp[i][j] = 1;
else if (gap == 1 && str[i] == str[j])
dp[i][j] = 2;
else if (str[i] == str[j] && dp[i + 1][j - 1] != 0)
dp[i][j] = gap + 1;
if (dp[i][j] > maxLen)
{
maxLen = dp[i][j];
si = i;
ei = j;
}
}
}
return str.substr(si, (ei - si + 1));
}
//Leetcode 647.=================================================================================
int countAllPlaindromicSubstring(string str)
{
int n = str.length();
vector<vector<int>> dp(n, vector<int>(n, 0));
int count = 0;
for (int gap = 0; gap < n; gap++)
{
for (int i = 0, j = gap; j < n; i++, j++)
{
if (gap == 0)
dp[i][j] = 1;
else if (gap == 1 && str[i] == str[j])
dp[i][j] = 2;
else if (str[i] == str[j] && dp[i + 1][j - 1] != 0)
dp[i][j] = gap + 1;
count += dp[i][j] != 0 ? 1 : 0;
}
}
}
//Leetcode 516.================================================================================================================
int longestPlaindromeSubseq_Rec(string str, int si, int ei, vector<vector<int>> &dp)
{
if (si > ei)
return 0;
if (si == ei)
return dp[si][ei] = 1;
if (dp[si][ei] != 0)
return dp[si][ei];
int len = 0;
if (str[si] == str[ei])
len = longestPlaindromeSubseq_Rec(str, si + 1, ei - 1, dp) + 2;
else
len = max(longestPlaindromeSubseq_Rec(str, si + 1, ei, dp), longestPlaindromeSubseq_Rec(str, si, ei - 1, dp));
return dp[si][ei] = len;
}
int longestPlaindromeSubseq_DP(string &str, vvi &dp, vector<vector<bool>> &isPalin)
{
int n = str.size();
for (int gap = 0; gap < n; gap++)
{
for (int i = 0, j = gap; j < n; i++, j++)
{
if (isPalin[i][j])
{
dp[i][j] = j - i + 1;
continue;
}
if (str[i] == str[j])
dp[i][j] = dp[i + 1][j - 1] + 2;
else
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
}
}
return dp[0][n - 1];
}
//Leetcode 115 : distinct-subsequences.=========================================================
int distinct_subsequences(string S, string T, int n, int m, vector<vector<int>> &dp)
{
if (m == 0)
return dp[n][m] = 1;
if (m > n)
return dp[n][m] = 0;
if (dp[n][m] != -1)
return dp[n][m];
if (S[n - 1] == T[m - 1])
return dp[n][m] = distinct_subsequences(S, T, n - 1, m - 1, dp) + distinct_subsequences(S, T, n - 1, m, dp);
return dp[n][m] = distinct_subsequences(S, T, n - 1, m, dp);
}
int distinct_subsequences_02(string S, string T, int i, int j, vector<vector<int>> &dp)
{
if (T.length() - j == 0)
return dp[i][j] = 1;
if (S.length() - i > T.length() - j)
return dp[i][j] = 0;
if (dp[i][j] != -1)
return dp[i][j];
if (S[i] == T[j])
return dp[i][j] = distinct_subsequences_02(S, T, i + 1, j + 1, dp) + distinct_subsequences_02(S, T, i + 1, j, dp);
return dp[i][j] = distinct_subsequences_02(S, T, i + 1, j, dp);
}
int distinct_subsequences_DP(string S, string T, int n, int m, vector<vector<int>> &dp)
{
int N = n, M = m;
for (n = 0; n <= N; n++)
{
for (m = 0; m <= M; m++)
{
if (m == 0)
{
dp[n][m] = 1;
continue;
}
if (m > n)
{
dp[n][m] = 0;
continue;
}
if (S[n - 1] == T[m - 1])
dp[n][m] = dp[n - 1][m - 1] + dp[n - 1][m];
else
dp[n][m] = dp[n - 1][m];
}
}
return dp[N][M];
}
int numDistinct(string s, string t)
{
int n = s.length();
int m = t.length();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, -1));
// cout << distinct_subsequences(s, t, n, m, dp) << endl;
cout << distinct_subsequences_DP(s, t, n, m, dp) << endl;
display2D(dp);
}
//Geeks: https://practice.geeksforgeeks.org/problems/count-palindromic-subsequences/1
int countPS(string &s, int i, int j, vector<vector<int>> &dp)
{
if (i > j)
return 0;
if (i == j)
return dp[i][j] = 1;
if (dp[i][j] != 0)
return dp[i][j];
int middleString = countPS(s, i + 1, j - 1, dp);
int excludingLast = countPS(s, i, j - 1, dp);
int excludingFirst = countPS(s, i + 1, j, dp);
int ans = excludingFirst + excludingLast;
return dp[i][j] = (s[i] == s[j]) ? ans + 1 : ans - middleString;
}
int countPS_DP(string &s, int i, int j, vector<vector<int>> &dp)
{
int n = s.length();
for (int gap = 0; gap < n; gap++)
{
for (int i = 0, j = gap; j < n; j++, i++)
{
if (i == j)
{
dp[i][j] = 1;
continue;
}
int middleString = dp[i + 1][j - 1];
int excludingLast = dp[i][j - 1];
int excludingFirst = dp[i + 1][j];
int ans = excludingFirst + excludingLast;
dp[i][j] = (s[i] == s[j]) ? ans + 1 : ans - middleString;
}
}
return dp[0][n - 1];
}
// LeetCode : 1143 =========================================================
int longestCommonSubsequence(string &text1, string &text2, int i, int j, vector<vector<int>> &dp)
{
if (i == text1.length() || j == text2.length())
return 0;
if (dp[i][j] != 0)
return dp[i][j];
int ans = 0;
if (text1[i] == text2[j])
ans = longestCommonSubsequence(text1, text2, i + 1, j + 1, dp) + 1;
else
ans = max(longestCommonSubsequence(text1, text2, i + 1, j, dp), longestCommonSubsequence(text1, text2, i, j + 1, dp));
dp[i][j] = ans;
}
int longestCommonSubsequence_DP(string &text1, string &text2, int i, int j, vector<vector<int>> &dp)
{
for (i = text1.length(); i >= 0; i--)
{
for (j = text2.length(); j >= 0; j--)
{
if (i == text1.length() || j == text2.length())
continue;
int ans = 0;
if (text1[i] == text2[j])
ans = dp[i + 1][j + 1] + 1;
else
ans = max(dp[i + 1][j], dp[i][j + 1]);
dp[i][j] = ans;
}
}
return dp[0][0];
}
int longestCommonSubsequence(string text1, string text2)
{
vector<vector<int>> dp(text1.length() + 1, vector<int>(text2.length() + 1, 0));
int ans = 0;
ans = longestCommonSubsequence(text1, text2, 0, 0, dp);
// ans = longestCommonSubsequence_DP(text1, text2, 0, 0, dp);
display2D(dp);
return ans;
}
int max_ = 0;
int longestCommonSubstring(string &text1, string &text2, int i, int j, vector<vector<int>> &dp)
{
if (i == text1.length() || j == text2.length())
return dp[i][j] = 0;
if (dp[i][j] != 0)
return dp[i][j];
int a = longestCommonSubstring(text1, text2, i + 1, j, dp);
int b = longestCommonSubstring(text1, text2, i, j + 1, dp);
if (text1[i] == text2[j])
{
int a = longestCommonSubstring(text1, text2, i + 1, j + 1, dp) + 1;
max_ = max(max_, a);
return dp[i][j] = a;
}
return 0;
}
int longestCommonSubstring_DP(string &text1, string &text2, int i, int j, vector<vector<int>> &dp)
{
int max_ = 0;
for (i = text1.length(); i >= 0; i--)
{
for (j = text2.length(); j >= 0; j--)
{
if (i == text1.length() || j == text2.length())
continue;
int ans = 0;
if (text1[i] == text2[j])
{
ans = dp[i + 1][j + 1] + 1;
max_ = max(max_, ans);
}
int a = dp[i + 1][j];
int b = dp[i][j + 1];
dp[i][j] = ans;
}
}
return dp[0][0];
}
// Leetcode: 1035
// Same as longest common subsequence ==================================================
int lcs(vector<int> &a, vector<int> &b, int i, int j, vector<vector<int>> &dp)
{
if (i == a.size() || j == b.size())
return 0;
if (dp[i][j] != 0)
return dp[i][j];
if (a[i] == b[j])
return dp[i][j] = lcs(a, b, i + 1, j + 1, dp) + 1;
return dp[i][j] = max(lcs(a, b, i + 1, j, dp), lcs(a, b, i, j + 1, dp));
}
int lcs_DP(vector<int> &a, vector<int> &b, int n, int m, vector<vector<int>> &dp)
{
for (int i = n - 1; i >= 0; i--)
{
for (int j = m - 1; j >= 0; j--)
{
if (a[i] == b[j])
dp[i][j] = dp[i + 1][j + 1] + 1;
else
dp[i][j] = max(dp[i + 1][j], dp[i][j + 1]);
}
}
return dp[0][0];
}
int maxUncrossedLines(vector<int> &A, vector<int> &B)
{
int n = A.size();
int m = B.size();
vector<vector<int>> dp(n, vector<int>(m, 0));
// return lcs(A, B, 0, 0, dp);
return lcs_DP(A, B, n, m, dp);
}
//leetcode 1458.
int maxDotProduct(vector<int> &nums1, vector<int> &nums2)
{
int n = nums1.size(), m = nums2.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for (int i = n; i >= 0; i--)
{
for (int j = m; j >= 0; j--)
{
if (i == n || m == j)
{
dp[i][j] = -1e8;
continue;
}
int val = nums1[i] * nums2[j];
int a = dp[i + 1][j + 1] + val;
int b = dp[i + 1][j];
int c = dp[i][j + 1];
dp[i][j] = max(max(a, b), max(c, val));
}
}
return dp[0][0];
}
// Leetcode 72 convering str1 -> str2;
int editDistance(string &str1, string &str2, int n, int m, vector<vector<int>> &dp)
{
if (n == 0 || m == 0)
return dp[n][m] = (n == 0 ? m : n);
if (dp[n][m] != 0)
return dp[n][m];
if (str1[n - 1] == str2[m - 1])
return dp[n][m] = editDistance(str1, str2, n - 1, m - 1, dp);
int insert_ = editDistance(str1, str2, n, m - 1, dp) + 1;
int replace_ = editDistance(str1, str2, n - 1, m - 1, dp) + 1;
int delete_ = editDistance(str1, str2, n - 1, m, dp) + 1;
return dp[n][m] = min({insert_, replace_, delete_});
}
int minDistance(string word1, string word2)
{
int n = word1.length();
int m = word2.length();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
return editDistance(word1, word2, n, m, dp);
}
void stringSubstringSet()
{
// string str = "geeksforgeeks";
// int n = str.length();
// int si = 0, ei = n - 1;
// vector<vector<int>> dp(n, vector<int>(n, 0));
// vector<vector<bool>> isPlalindrome = isPlaindromeSubstring(str);
// cout << longestPlaindromeSubstring("abcaacbefgpgf") << endl;
// cout << longestPlaindromeSubseq_Rec(str, si, ei, dp, isPlalindrome) << endl;
// cout << longestPlaindromeSubseq_DP(str, dp, isPlalindrome) << endl;
// display2D(dp);
// numDistinct("geeksforgeeks", "gks");
// cout << longestCommonSubsequence("abc", "aab") << endl;
}
// Coin_Change/Target_type =========================================================
int coinChangePermutation(int tar, vi &arr, vi &dp)
{
if (tar == 0)
return dp[tar] = 1;
if (dp[tar] != 0)
return dp[tar];
int count = 0;
for (auto ele : arr)
if (tar - ele >= 0)
count += coinChangePermutation(tar - ele, arr, dp);
return dp[tar] = count;
}
int coinChangePermutation_DP(int Tar, vi &arr, vi &dp)
{
int n = arr.size();
for (int tar = 0; tar <= Tar; tar++)
{
if (tar == 0)
{
dp[tar] = 1;
continue;
}
int count;
for (auto ele : arr)
if (tar - ele >= 0)
count += dp[tar - ele];
dp[tar] = count;
}
return dp[Tar];
}
// jugad method for finding the it using 1-d array becuase it doesn't overlap in memoization.
int coinChangeCombination_DP(int Tar, vi &arr, vi &dp)
{
int n = arr.size();
dp[0] = 1;
for (auto ele : arr)
for (int tar = ele; tar <= Tar; tar++)
dp[tar] += dp[tar - ele];
return dp[Tar];
}
//https://www.geeksforgeeks.org/find-number-of-solutions-of-a-linear-equation-of-n-variables/
int LinearEquation_DP(vector<int> &coeff, int rhs)
{
vector<int> dp(rhs + 1, 0);
dp[0] = 1;
for (int ele : coeff)
for (int tar = ele; tar <= rhs; tar++)
dp[tar] += dp[tar - ele];
}
//leetcode 322
int coinChange_(vector<int> &coins, int tar, vector<int> &dp)
{
if (tar == 0)
return 0;
if (dp[tar] != 0)
return dp[tar];
int minHeight = 1e8;
for (int ele : coins)
{
if (tar - ele >= 0)
{
int rMinHeight = coinChange_(coins, tar, dp);
if (rMinHeight != 1e8 && rMinHeight + 1 < minHeight)
minHeight = rMinHeight + 1;
}
}
return dp[tar] = minHeight;
}
int coinChange(vector<int> &coins, int tar)
{
vector<int> dp(tar + 1, 0);
return coinChange_(coins, tar, dp);
}
void coinChange()
{
// vector<int> arr{2, 3, 5, 7};
// int tar = 10;
// vector<int> dp(tar + 1, 0);
// cout << coinChangePermutation(arr, tar, dp) << endl;
// display(dp);
}
int targetSum(vector<int> &coins, int idx, int tar, vector<vector<int>> &dp)
{
if (idx == coins.size() || tar == 0)
{
if (tar == 0)
return dp[idx][tar] = 1;
return 0;
}
if (dp[idx][tar] != 0)
return dp[idx][tar];
int count = 0;
if (tar - coins[idx] >= 0)
count += targetSum(coins, idx + 1, tar - coins[idx], dp);
count += targetSum(coins, idx + 1, tar, dp);
return dp[idx][tar] = count;
}
int targetSum_02(vector<int> &coins, int idx, int tar, vector<vector<int>> &dp)
{
if (tar == 0 || idx == 0)
{
if (tar == 0)
return dp[idx][tar] = 1;
return dp[idx][tar] = 0;
}
if (dp[idx][tar] != 0)
return dp[idx][tar];
int count = 0;
if (tar - coins[idx - 1] >= 0)
count += targetSum_02(coins, idx - 1, tar - coins[idx - 1], dp);
count += targetSum_02(coins, idx - 1, tar, dp);
return dp[idx][tar] = count;
}
int printPathOfTargetSum(vector<int> &coins, int idx, int tar, string ans, vector<vector<bool>> &dp)
{
if (tar == 0 || idx == 0)
{
if (tar == 0)
{
cout << ans << endl;
return 1;
}
return 0;
}
int count = 0;
if (tar - coins[idx - 1] >= 0 && dp[idx - 1][tar - coins[idx - 1]])
count += printPathOfTargetSum(coins, idx - 1, tar - coins[idx - 1], ans + to_string(coins[idx - 1]) + " ", dp);
if (dp[idx - 1][tar])
count += printPathOfTargetSum(coins, idx - 1, tar, ans, dp);
return count;
}
void targetSum_02DP(vector<int> &coins, int tar)
{
int n = coins.size();
int Tar = tar;
vector<vector<bool>> dp(n + 1, vector<bool>(tar + 1));
for (int idx = 0; idx < n + 1; idx++)
{
for (tar = 0; tar <= Tar; tar++)
{
if (tar == 0 || idx == 0)
{
if (tar == 0)
dp[idx][tar] = 1;
continue;
}
if (tar - coins[idx - 1] >= 0)
dp[idx][tar] = dp[idx - 1][tar - coins[idx - 1]];
dp[idx][tar] = dp[idx][tar] || dp[idx - 1][tar];
}
}
for (vector<bool> &ar : dp)
{
for (bool ele : ar)
{
cout << ele << " ";
}
cout << endl;
}
cout << printPathOfTargetSum(coins, coins.size(), Tar, "", dp) << endl; // printing path of dp using back engineering;
}
void targetType()
{
vi arr = {2, 3, 5, 7};
int tar = 10;
// vvi dp(arr.size() + 1, vi(tar + 1, 0));
// cout << targetSum_02(arr, arr.size(), tar, dp) << endl;
targetSum_02DP(arr, tar);
// display2D(dp);
}
int knapsack01(vector<int> &w, vector<int> &p, int weight, int n, vector<vector<int>> &dp)
{
if (weight == 0 || n == 0)
{
return 0;
}
if (dp[n][weight] != 0)
return dp[n][weight];
int maxProfit = -1e8;
if (weight - w[n - 1] >= 0)
maxProfit = max(maxProfit, knapsack01(w, p, weight - w[n - 1], n - 1, dp) + p[n - 1]); // dp[n-1][weight - w[n - 1]]+p[n-1]
maxProfit = max(maxProfit, knapsack01(w, p, weight, n - 1, dp)); // dp[n-1][weight]
return dp[n][weight] = maxProfit;
}
int unbpounded(vector<int> &w, vector<int> &p, int weight)
{
vector<int> dp(w.size() + 1, -1e8);
dp[0] = 0;
for (int i = 0; i < w.size(); i++)
for (int tar = w[i]; tar <= weight; tar++)
dp[tar] = max(dp[tar], dp[tar - w[i]] + p[i]);
return dp[w.size()];
}
void knapsack()
{
vector<int> p = {100, 280, 120};
vector<int> w = {10, 40, 20};
int weight = 60;
int n = w.size();
vector<vector<int>> dp(n + 1, vector<int>(weight + 1, 0));
cout << knapsack01(w, p, weight, n, dp) << endl;
}
//Leetcode 416
bool canPartition_(vector<int> &nums, int n, int sum, vector<vector<int>> &dp)
{
if (sum == 0 || n == 0)
{
if (sum == 0)
return dp[n][sum] = 1;
return dp[n][sum] = 0;
}
if (dp[n][sum] != -1)
return dp[n][sum];
bool res = false;
if (sum - nums[n - 1] >= 0)
res = res || canPartition_(nums, n - 1, sum - nums[n - 1], dp) == 1;
res = res || canPartition_(nums, n - 1, sum, dp) == 1;
return dp[n][sum] = res ? 1 : 0;
}
bool canPartition(vector<int> &nums)
{
int sum = 0;
for (int ele : nums)
sum += ele;
if (sum % 2 != 0)
return false;
sum /= 2;
vector<vector<int>> dp(nums.size() + 1, vector<int>(sum + 1, -1));
return canPartition_(nums, nums.size(), sum, dp);
}
//Leetcode 494
int min_;
int sum(vector<int> &nums, int tar, int idx, int s, vector<vector<int>> &dp)
{
if (idx == nums.size())
{
if (tar == s)
return dp[idx][tar + max_] = 1;
return dp[idx][tar + max_] = 0;
}
if (dp[idx][tar + max_] != -1)
return dp[idx][tar + max_];
int count = 0;
count += sum(nums, tar - nums[idx], idx + 1, s, dp);
count += sum(nums, tar + nums[idx], idx + 1, s, dp);
return dp[idx][tar + max_] = count;
}
int findTargetSumWays(vector<int> &nums, int S)
{
int n = nums.size();
min_ = 0;
max_ = 0;
for (auto ele : nums)
{
max_ += ele;
min_ -= ele;
}
vector<vector<int>> dp(n + 1, vector<int>(max_ - min_ + 1, -1));
// int ans = targetSum(nums, 0, 0, S, dp);
int ans = sum(nums, 0, 0, S, dp);
// for (auto ar : dp)
// {
// for (auto ele : ar)
// cout << ele << " ";
// cout << endl;
// }
return ans;
}
//LIS ======================================================================
int LIS_leftToRight(vector<int> &arr, vector<int> &dp)
{
int N = arr.size();
int oMax = 0;
for (int i = 0; i < N; i++)
{
dp[i] = 1;
for (int j = i - 1; j >= 0; j--)
if (arr[j] < arr[i])
dp[i] = max(dp[i], dp[j] + 1);
oMax = max(oMax, dp[i]);
}
return oMax;
}
//LDS
int LIS_rightToLeft(vector<int> &arr, vector<int> &dp)
{
int N = arr.size();
int oMax = 0;
for (int i = N - 1; i >= 0; i--)
{
dp[i] = 1;
for (int j = i + 1; j < N; j++)
if (arr[j] < arr[i])
dp[i] = max(dp[i], dp[j] + 1);
oMax = max(oMax, dp[i]);
}
return oMax;
}
//Longest bitonic subsequence
//https://www.geeksforgeeks.org/longest-bitonic-subsequence-dp-15/
int LBS(vector<int> &arr)
{
int n = arr.size();
vector<int> LIS(n, 0);
vector<int> LDS(n, 0);
LIS_leftToRight(arr, LIS);
LIS_rightToLeft(arr, LDS);
int maxLen = 0;
for (int i = 0; i < n; i++)
{
int len = LIS[i] + LDS[i] - 1;
maxLen = max(maxLen, len);
}
return maxLen;
}
// this can also be maximum sum increasing subsequence gfg
// https://practice.geeksforgeeks.org/problems/maximum-sum-increasing-subsequence/0
vi Lis(vi &arr, int n)
{
vi dp(n, 0);
for (int i = 0; i < n; i++)
{
dp[i] = arr[i];
for (int j = i - 1; j >= 0; j--)
if (arr[j] < arr[i])
dp[i] = max(dp[i], dp[j] + arr[i]);
}
return dp;
}
//Lds maximum sum subseqeuence
vi Lbs(vi &arr, int n)
{
vi dp(n, 0);
for (int i = n - 1; i >= 0; i--)
{
dp[i] = arr[i];
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[i])
dp[i] = max(dp[i], dp[j] + arr[i]);
}
return dp;
}
int LBS_Sum()
{
int n;
cin >> n;
vi arr(n, 0);
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
vi Lis_dp = Lis(arr, n);
vi Lbs_dp = Lbs(arr, n);
// for (int i = 0; i < n; i++)
// {
// cout << Lis_dp[i] << " " << Lbs_dp[i] << endl;
// }
int max_ = 0;
for (int i = 0; i < n; i++)
{
max_ = max(max_, Lis_dp[i] + Lbs_dp[i] - arr[i]);
}
return max_;
}
int findNumberOfLIS(vector<int> &arr)
{
int n = arr.size();
if (n <= 1)
return n;
vector<int> dp(n, 0);
vector<int> count(n, 0);
int maxLen = 0;
int maxCount = 0;
for (int i = 0; i < n; i++)
{
dp[i] = 1;
count[i] = 1;
for (int j = i - 1; j >= 0; j--)
{
if (arr[i] > arr[j])
{
if (dp[j] + 1 > dp[i])
{
dp[i] = dp[j] + 1;
count[i] = count[j];
}
else if (dp[j] + 1 == dp[i])
count[i] += count[j];
}
}
if (dp[i] > maxLen)
{
maxLen = dp[i];
maxCount = count[i];
}
else if (dp[i] == maxLen)
maxCount += count[i];
}
return maxCount;
}
// minimum no of deletion to make array in sorted order in increasing order.
int minDeletion(vector<int> &arr)
{
int n = arr.size();
vector<int> dp(n, 0);
int oMax = 0;
for (int i = 0; i < n; i++)
{
dp[i] = 1;
for (int j = i - 1; j >= 0; j--)
{
if (arr[j] <= arr[i])
dp[i] = max(dp[i], dp[j] + 1);
}
oMax = max(oMax, dp[i]);
}
return n - oMax;
}
//Leetcode 354
int maxEnvelopes(vector<vector<int>> &arr)
{
// for Java:
// Arrays.sort(arr,(int[] a, int[] b)-> {
// if (a[0] == b[0])
// return b[1] - a[1]; // other - this
// return a[0] - b[0]; // this - other. default
// });
sort(arr.begin(), arr.end(), [](vector<int> &a, vector<int> &b) {
if (a[0] == b[0])
return b[1] < a[1]; // other - this
return a[0] < b[0]; // this - other., for cpp replace '-' with '<' default
});
int n = arr.size();
vector<int> dp(n, 0);
int oMax = 0;
for (int i = 0; i < n; i++)
{
dp[i] = 1;
for (int j = i - 1; j >= 0; j--)
{
if (arr[j][1] < arr[i][1])
dp[i] = max(dp[i], dp[j] + 1);
}
oMax = max(oMax, dp[i]);
}
return oMax;
}
// Leetcode 1235 :
int Next(int cur, vector<vector<int>> &arr)
{
for (int next = cur + 1; next < arr.size(); next++)
if (arr[cur][1] <= arr[next][0])
return next;
return -1;
}
int dfs(int cur, vector<vector<int>> &arr, unordered_map<int, int> &dp)
{
if (cur == arr.size())
return 0;
if (dp.find(cur) != dp.end())
return dp[cur];
int next = Next(cur, arr);
int include = arr[cur][2] + (next != -1 ? dfs(next, arr, dp) : 0);
int exclude = dfs(cur + 1, arr, dp);
dp[cur] = max(include, exclude);
return max(include, exclude);
}
int jobScheduling(vector<int> &startTime, vector<int> &endTime, vector<int> &profit)
{
int n = profit.size();
vector<vector<int>> arr(n, vector<int>(3, 0));
for (int i = 0; i < n; i++)
arr[i] = {startTime[i], endTime[i], profit[i]};
sort(arr.begin(), arr.end());
unordered_map<int, int> dp;
return dfs(0, arr, dp);
// Lis solution giving TLE;
// sort(arr.begin(), arr.end(), [](vector<int> &a, vector<int> &b) {
// return a[1] < b[1];
// });
// vector<int> dp(n, 0);
// int maxRes = 0;
// for (int i = 0; i < n; i++)
// {
// dp[i] = arr[i][2];
// for (int j = i - 1; j >= 0; j--)
// {
// if (arr[i][0] >= arr[j][1])
// dp[i] = max(dp[i], dp[j] + arr[i][2]);
// }
// maxRes = max(maxRes, dp[i]);
// }
// return maxRes;
}
// Cut Type ===================================================================
// Matrix chain multiplication.
int MCM(vi &arr, int si, int ei, vvi &dp)
{
if (si + 1 == ei)
return dp[si][ei] = 0;
if (dp[si][ei] != -1)
return dp[si][ei];
int ans = 1e9;
for (int cut = si + 1; cut < ei; cut++)
{
int leftAns = MCM(arr, si, cut, dp);
int rightAns = MCM(arr, cut, ei, dp);
int myAns = leftAns + arr[si] * arr[cut] * arr[ei] + rightAns;
if (ans > myAns)
ans = myAns;
}
return dp[si][ei] = ans;
}
int MCM_DP_Ans(vector<int> &arr)
{
int n = arr.size();
vector<vector<string>> sdp(n, vector<string>(n, ""));
vector<vector<int>> dp(n, vector<int>(n, -1));
for (int gap = 1; gap < arr.size(); gap++)
{
for (int si = 0, ei = gap; ei < arr.size(); si++, ei++)
{
if (si + 1 == ei)
{
dp[si][ei] = 0;
sdp[si][ei] = (char)(si + 'A');
continue;
}
int ans = 1e8;
string sans = "";
for (int cut = si + 1; cut < ei; cut++)
{
int leftCost = dp[si][cut]; //MCM_rec(arr, si, cut, dp);
int rightCost = dp[cut][ei]; //MCM_rec(arr, cut, ei, dp);
int myCost = leftCost + arr[si] * arr[cut] * arr[ei] + rightCost;
if (myCost < ans)
{
ans = myCost;
sans = "(" + sdp[si][cut] + sdp[cut][ei] + ")";
}
}
dp[si][ei] = ans;
sdp[si][ei] = sans;
}
}
cout << sdp[0][arr.size() - 1] << endl;
cout << dp[0][arr.size() - 1] << endl;
}
int costOfSearching(vector<int> &freq, int si, int ei)
{
int sum = 0;
for (int i = si; i <= ei; i++)
sum += freq[i];
return sum;
}
int OBST_rec(vector<int> &freq, int si, int ei, vector<vector<int>> &dp)
{
if (dp[si][ei] != 0)
return dp[si][ei];
int ans = 1e8;
for (int cut = si; cut <= ei; cut++)
{
int leftTreeCost = (cut == si) ? 0 : OBST_rec(freq, si, cut - 1, dp);
int rightTreeCost = (cut == ei) ? 0 : OBST_rec(freq, cut + 1, ei, dp);
int myCost = leftTreeCost + costOfSearching(freq, si, ei) + rightTreeCost;
if (myCost < ans)
ans = myCost;
}
return dp[si][ei] = ans;
}
int OBST_DP(vector<int> &freq, int si, int ei, vector<vector<int>> &dp)
{
vector<int> prefixSum(freq.size() + 1, 0);
for (int i = 1; i < prefixSum.size(); i++)
prefixSum[i] = prefixSum[i - 1] + freq[i - 1];
for (int gap = 0; gap < freq.size(); gap++)
{
for (si = 0, ei = gap; ei < freq.size(); si++, ei++)
{
int ans = 1e8;
for (int cut = si; cut <= ei; cut++)
{
int leftTreeCost = (cut == si) ? 0 : dp[si][cut - 1]; //OBST_rec(freq, si, cut - 1, dp);
int rightTreeCost = (cut == ei) ? 0 : dp[si][cut + 1]; //OBST_rec(freq, cut + 1, ei, dp);
int myCost = leftTreeCost + prefixSum[ei + 1] - prefixSum[si] + rightTreeCost;
if (myCost < ans)
ans = myCost;
}
dp[si][ei] = ans;
}
}
return dp[0][freq.size() - 1];
}
int burstBallon(vector<int> &arr, int si, int ei, vector<vector<int>> &dp)
{
if (dp[si][ei] != 0)
return dp[si][ei];
int lVal = (si == 0) ? 1 : arr[si - 1];
int rVal = (ei == arr.size() - 1) ? 1 : arr[ei + 1];
int ans = 0;
for (int cut = si; cut <= ei; cut++)
{
int leftTreeCost = (cut == si) ? 0 : burstBallon(arr, si, cut - 1, dp);
int rightTreeCost = (cut == ei) ? 0 : burstBallon(arr, cut + 1, ei, dp);
int myCost = leftTreeCost + lVal * arr[cut] * rVal + rightTreeCost;
if (myCost > ans)
ans = myCost;
}
return dp[si][ei] = ans;
}
int maxCoins(vector<int> &nums)
{
int n = nums.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
cout << burstBallon(nums, 0, n - 1, dp) << endl;
}
void optimalBinarySearchTree()
{
vector<int> keys{10, 12, 20};
vector<int> freq{34, 8, 50};
int n = freq.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
cout << OBST_rec(freq, 0, n - 1, dp) << endl;
// cout << OBST_DP(freq, 0, n - 1, dp) << endl;
display2D(dp);
}
void MCM()
{
vector<int> arr{3, 7, 2, 6, 5, 4};
int n = arr.size();
vector<vector<int>> dp(n, vector<int>(n, -1));
// cout << MCM_rec(arr, 0, n - 1, dp) << endl;
// cout << MCM_DP(arr, 0, n - 1, dp) << endl;
// MCM_DP_Ans(arr);
display2D(dp);
}
// leetcode 132 =============================
// soluiton is in java to pass
// int minCut(String str, int si, int ei, boolean[][] isPalin, int[][] dp)
// {
// if (isPalin[si][ei])
// return dp[si][ei] = 0;
// if (dp[si][ei] != -1)
// return dp[si][ei];
// int myans = (int)1e9;
// for (int cut = si + 1; cut <= ei; cut++)
// {
// int leftCuts = minCut(str, si, cut - 1, isPalin, dp);
// int rightCuts = minCut(str, cut, ei, isPalin, dp);
// int myCost = leftCuts + 1 + rightCuts;
// if (myCost < myans)
// myans = myCost;
// }
// return dp[si][ei] = myans;
// }
// public int minCut(String str)
// {
// int n = str.length();
// boolean[][] isPalin = new boolean[n][n];
// for (int gap = 0; gap < n; gap++)
// {
// for (int i = 0, j = gap; j < n; i++, j++)
// {
// if (gap == 0)
// {
// isPalin[i][j] = true;
// continue;
// }
// else if (gap == 1 && str.charAt(i) == str.charAt(j))
// isPalin[i][j] = true;
// else if (str.charAt(i) == str.charAt(j))
// isPalin[i][j] = isPalin[i + 1][j - 1];
// }
// }
// if (isPalin[0][n - 1])
// return 0;
// int[][] dp = new int[n][n];
// for (int[] ar : dp)
// Arrays.fill(ar, 0);
// // return minCut(str, 0, n - 1, isPalin, dp);
// for (int gap = 1; gap < n; gap++)
// {
// for (int si = 0, ei = gap; ei < n; si++, ei++)
// {
// if (isPalin[si][ei])
// dp[si][ei] = 0;
// else
// {
// int myans = (int)1e9;
// for (int cut = si + 1; cut <= ei; cut++)
// {
// int leftCuts = dp[si][cut - 1]; //minCut(str, si, cut - 1, isPalin, dp);
// int rightCuts = dp[cut][ei]; //minCut(str, cut, ei, isPalin, dp);
// int myCost = leftCuts + 1 + rightCuts;
// if (myCost < myans)
// myans = myCost;
// }
// dp[si][ei] = myans;
// }
// }
// }
// return dp[0][n - 1];
// }
//==============================================================================================================
//Leetcode :91. Decode Ways
int numDecodings_(string &s, int vidx, vector<int> &dp)
{
if (vidx == s.length())
{
return dp[vidx] = 1;
}
if (dp[vidx] != -1)
return dp[vidx];
char ch = s[vidx];
if (ch == '0')
return dp[vidx] = 0;
int count = 0;
count += numDecodings_(s, vidx + 1, dp);
if (vidx < s.size() - 1)
{
int num = (ch - '0') * 10 + (s[vidx + 1] - '0');
if (num <= 26)
count += numDecodings_(s, vidx + 2, dp);
}
return dp[vidx] = count;
}
int numDecodings02(string &s)
{
int a = 0;
int b = 1;
int ans = 0;
for (int i = s.length() - 1; i >= 0; i--)
{
char ch = s[i];
ans = 0;
if (ch != '0')
{
ans = b;
if (i < s.length() - 1)
{
int num = (ch - '0') * 10 + (s[i + 1] - '0');
if (num <= 26)
ans += a;
}
}
a = b;
b = ans;
}
}
long mod = 1e9 + 7;
long numDecodingsII_recu(string &str, int idx, vector<long> &dp)
{
if (idx == str.length())
return 1;
if (dp[idx] != 0)
return dp[idx];
int count = 0;
if (str[idx] == '*')
{
count = (count % mod + 9 * numDecodingsII_recu(str, idx + 1, dp) % mod) % mod;
if (idx < str.length() - 1 && str[idx + 1] >= '0' && str[idx + 1] <= '6')
count = (count % mod + 2 * numDecodingsII_recu(str, idx + 2, dp) % mod) % mod;
else if (idx < str.length() - 1 && str[idx + 1] >= '7')
count = (count % mod + numDecodingsII_recu(str, idx + 2, dp) % mod) % mod;
else if (idx < str.length() - 1 && str[idx + 1] == '*')
count = (count % mod + 15 * numDecodingsII_recu(str, idx + 2, dp) % mod) % mod;
}
else if (str[idx] > '0')
{
count = (count % mod + numDecodingsII_recu(str, idx + 1, dp) % mod) % mod;
if (idx < str.length() - 1)
{
if (str[idx + 1] != '*')
{
int num = (str[idx] - '0') * 10 + (str[idx + 1] - '0');
if (num <= 26)
count = (count % mod + numDecodingsII_recu(str, idx + 2, dp) % mod) % mod;
}
else if (str[idx] == '1')
count = (count % mod + 9 * numDecodingsII_recu(str, idx + 2, dp) % mod) % mod;
else if (str[idx] == '2')
count = (count % mod + 6 * numDecodingsII_recu(str, idx + 2, dp) % mod) % mod;
}
}
return dp[idx] = count;
}
long numDecodingsII_DP(string &str, int idx, vector<long> &dp)
{
for (idx = str.length(); idx >= 0; idx--)
{
if (idx == str.length())
{
dp[idx] = 1;
continue;
}
int count = 0;
if (str[idx] == '*')
{
count = (count % mod + 9 * dp[idx + 1] % mod) % mod;
if (idx < str.length() - 1 && str[idx + 1] >= '0' && str[idx + 1] <= '6')
count = (count % mod + 2 * dp[idx + 2] % mod) % mod;
else if (idx < str.length() - 1 && str[idx + 1] >= '7')
count = (count % mod + dp[idx + 2] % mod) % mod;
else if (idx < str.length() - 1 && str[idx + 1] == '*')
count = (count % mod + 15 * dp[idx + 2] % mod) % mod;
}
else if (str[idx] > '0')
{
count = (count % mod + dp[idx + 1] % mod) % mod;
if (idx < str.length() - 1)
{
if (str[idx + 1] != '*')
{
int num = (str[idx] - '0') * 10 + (str[idx + 1] - '0');
if (num <= 26)
count = (count % mod + dp[idx + 2] % mod) % mod;
}
else if (str[idx] == '1')
count = (count % mod + 9 * dp[idx + 2] % mod) % mod;
else if (str[idx] == '2')
count = (count % mod + 6 * dp[idx + 2]) % mod;
}
}
dp[idx] = count;
}
return dp[0];
}
long numDecodingsII_Fast(string &str, int idx, vector<long> &dp)
{
long a = 0;
long b = 1;
long count = 0;
for (idx = str.length() - 1; idx >= 0; idx--)
{
count = 0;
if (str[idx] == '*')
{
count = (count % mod + 9 * b % mod) % mod;
if (idx < str.length() - 1 && str[idx + 1] >= '0' && str[idx + 1] <= '6')
count = (count % mod + 2 * a % mod) % mod;
else if (idx < str.length() - 1 && str[idx + 1] >= '7')
count = (count % mod + a % mod) % mod;
else if (idx < str.length() - 1 && str[idx + 1] == '*')
count = (count % mod + 15 * a % mod) % mod;
}
else if (str[idx] > '0')
{
count = (count % mod + b % mod) % mod;
if (idx < str.length() - 1)
{
if (str[idx + 1] != '*')
{
int num = (str[idx] - '0') * 10 + (str[idx + 1] - '0');
if (num <= 26)
count = (count % mod + a % mod) % mod;
}
else if (str[idx] == '1')
count = (count % mod + 9 * a % mod) % mod;
else if (str[idx] == '2')
count = (count % mod + 6 * a) % mod;
}
}
a = b;
b = count;
}
return count;
}
// DP toDo :
// 1. 132
// 2. 044
// 3. https://www.geeksforgeeks.org/boolean-parenthesization-problem-dp-37/
// 4. 096
// 5. 095
// int numDecodings(string str)
// {
// vector<long> dp(str.length() + 1, 0);
// // return (int)numDecodingsII_recu(str, 0, dp);
// // return (int)numDecodingsII_DP(str, 0, dp);
// return (int)numDecodingsII_Fast(str, 0, dp);
// }
int numDecodings(string s)
{
vector<int> dp(s.length() + 1, -1);
int ans = numDecodings_(s, 0, dp);
display(dp);
return ans;
}
void questionSet()
{
numDecodings("1423101112");
}
// gfg count aibjck subsequence.
int AiBjCk(string str)
{
int acount = 0;
int bcount = 0;
int ccount = 0;
for (int i = 0; i < str.length(); i++)
{
if (str[i] == 'a')
acount = acount + (1 + acount);
else if (str[i] == 'b')
bcount = bcount + (acount + bcount);
else
ccount = ccount + (bcount + ccount);
}
return ccount;
}
// https://www.hackerearth.com/practice/math/number-theory/basic-number-theory-1/tutorial/
// (a+b)%c = (a%c + b%c)%c
// (a-b)%c = (a%c - b%c + c)%c
// (a*b)%c = (a%c * b%c )%c
int distinctSubseqII(string str)
{
int mod = 1e9 + 7;
str = '$' + str;
int n = str.length();
vector<long> dp(n, 0);
vector<int> lastOccu(26, -1);
for (int i = 0; i < n; i++)
{
if (i == 0) // empty String.
{
dp[i] = 1;
continue;
}
char ch = str[i];
dp[i] = (dp[i - 1] % mod * 2) % mod;
if (lastOccu[ch - 'a'] != -1)
dp[i] = dp[i] % mod - dp[lastOccu[ch - 'a'] - 1] % mod + mod;
lastOccu[ch - 'a'] = i;
}
return dp[n - 1] % mod - 1;
}
void solve()
{
// set1();
// pathSet();
//set2();
// stringSubstringSet();
// cutType();
targetType();
// MCM();
// optimalBinarySearchTree();
}
int main()
{
solve();
return 0;
}<file_sep>/Recursion/l003_bits.cpp
#include <iostream>
#include <vector>
using namespace std;
int bitOFFToON(int no, int k)
{
int mask = (1 << k);
return (no | mask);
}
int bitONToOFF(int no, int k)
{
int mask = (~(1 << k));
return (no & mask);
}
int noOfSetBits(int num)
{
int bitCount = 0;
int totalBits = 32;
while (num != 0 && totalBits != 0)
{
if ((num & 1) != 0)
bitCount++;
num >>= 1;
totalBits--;
}
return bitCount;
}
// Leetcode 191
int noOfSetBits(int num)
{
int bitCount = 0;
int totalBits = 32;
while (num != 0 && totalBits != 0)
{
if ((num & 1) != 0)
bitCount++;
num >>= 1;
totalBits--;
}
return bitCount;
}
//leetcode 338
int noOfSetBits_01(int num)
{
int bitcount = 0;
while (num != 0)
{
num &= (num - 1);
bitcount++;
}
return bitcount;
}
// LeetCode Qno : 137 ===============================
int singleNumber(vector<int> &nums)
{
int no = 0;
for (int i = 0; i < 32; i++)
{
int count = 0;
int mask = (1 << i);
for (int ele : nums)
{
if ((mask & ele) != 0)
{
count++;
}
}
if (count % 3 != 0)
no |= mask;
}
return no;
}
// LeetCode Qno : 260 =============================
vector<int> singleNumberII(vector<int> &nums)
{
int Xnornum = 0;
for (int ele : nums)
Xnornum ^= ele;
int flsb = (Xnornum & (-Xnornum));
int a = 0;
int b = 0;
for (int ele : nums)
{
if ((ele & flsb) == 0)
a ^= ele;
else
b ^= ele;
}
return {a, b};
}
//Leetcode Qn0 :231 ===============================
bool isPowerOfTwo(int n)
{
return n > 0 && !(n & (n - 1));
}
//leetcode 342=========================
bool isPowerOfFour(int n)
{
if (n > 0 && !(n & (n - 1))) // is num power of 2
{
int count = 0; // count of all zeros after 1.
while (n > 1)
{
count++;
n >>= 1;
}
if ((count & 1) == 0)
return true; // count of zeros after 1 should be a even number.
}
return false;
}
void solve()
{
}
int main(int argc, char const *argv[])
{
solve();
return 0;
}
<file_sep>/Recursion/l001.cpp
#include <iostream>
#include <vector>
#include <string>
#define vi vector<int>
#define vii vector<vector<int>>
using namespace std;
vii dir = {{0, 1}, {1, 1}, {1, 0}};
vector<string> ch = {"H", "D", "V"};
int MazePath_HVD_01(vii &board, int sr, int sc,string ans)
{
if (sr == board.size() - 1 && sc == board[0].size() - 1)
{
cout << ans << endl;
return 1;
}
int count = 0;
for (int d = 0; d < dir.size(); d++)
{
int nr = sr + dir[d][0];
int nc = sc + dir[d][1];
if (nr < board.size() && nc < board[0].size())
count += MazePath_HVD_01(board, nr, nc, ans + ch[d]);
}
return count;
}
vector<string> MazePath_HVD_02(int sr, int sc, int er, int ec)
{
if (sr == er && sc == ec)
{
return {""};
}
int count = 0;
vector<string> myans;
for (int d = 0; d < dir.size(); d++)
{
int nr = sr + dir[d][0];
int nc = sc + dir[d][1];
if (nr <= er && nc <= ec)
{
vector<string> smans = MazePath_HVD_02(nr, nc, er, ec);
for (string ele : smans)
myans.push_back(ch[d] + ele);
}
}
return myans;
}
vector<vector<int>> dir = {{0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}, {1, 0}, {1, 1}};
vector<string> dirN = {"R", "E", "U", "N", "L", "W", "D", "S"};
// vector<vector<int>> dir = {{0, 1}, {1, 0}, {1, 1}};
// vector<string> dirN = {"H", "V", "D"};
bool isValid(int r, int c, vector<vector<int>> &board)
{
if (r < 0 || c < 0 || r >= board.size() || c >= board[0].size() || board[r][c] == 0 || board[r][c] == 2)
return false;
return true;
}
int floodFill(int sr, int sc, int er, int ec, vector<vector<int>> &board, int rad, string ans)
{
if (sr == er && sc == ec)
{
cout << ans << endl;
return 1;
}
int count = 0;
board[sr][sc] = 2;
for (int d = 0; d < dir.size(); d++)
{
for (int mag = 1; mag <= rad; mag++)
{
int r = sr + mag * dir[d][0];
int c = sc + mag * dir[d][1];
if (isValid(r, c, board))
count += floodFill(r, c, er, ec, board, rad, ans + dirN[d] + to_string(mag));
}
}
board[sr][sc] = 1;
return count;
}
//leetcode 200.
// int numIslands(vector<vector<char>> &arr)
// {
// int count = 0;
// for (int r = 0; r < arr.size(); r++)
// {
// for (int c = 0; c < arr[0].size(); c++)
// {
// if (arr[r][c] == '1')
// {
// count++;
// floodFill(r, c, arr, 1);
// }
// }
// }
// return count;
// }
vector<vector<int>> dir_ = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};
bool isValid_(int r, int c, vector<vector<char>> &board)
{
if (r < 0 || c < 0 || r >= board.size() || c >= board[0].size() || board[r][c] == '0' || board[r][c] == '2')
return false;
return true;
}
int dfs(int sr, int sc, vector<vector<char>> &board, int rad)
{
int count = 0;
board[sr][sc] = '2';
for (int d = 0; d < dir.size(); d++)
{
for (int mag = 1; mag <= rad; mag++)
{
int r = sr + mag * dir_[d][0];
int c = sc + mag * dir_[d][1];
if (isValid_(r, c, board))
count += dfs(r, c, board, rad);
}
}
// board[sr][sc] = 1;
return count;
}
void MazePathSet()
{
vii board(3, vi(3));
// cout << MazePath_HVD_01(board, 0, 0, "") << endl;
// vector<string> ans = MazePath_HVD_02(0, 0, 2, 2);
// for(string ele : ans)
// cout << ele << endl;
}
int main(int argc, char const *argv[])
{
MazePathSet();
return 0;
}
<file_sep>/Practice/Dp/l001.cpp
#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#define vi vector<int>
#define vb vector<bool>
#define lli long long int
#define vvi vector<vector<int>>
using namespace std;
// www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/
int minSteps(int n, int k, vvi &dp)
{
if (k == 0 || k == 1)
return dp[n][k] = k;
if (n == 1)
return dp[n][k] = k;
int myans = -1e9, ans = 1e9;
for (int i = 1; i <= k; i++)
{
myans = max(minSteps(n - 1, k - 1, dp), minSteps(n, k - i, dp));
if (ans > myans)
ans = myans;
}
dp[n][k] = ans + 1;
}
int EggDops()
{
int n, k;
cin >> n >> k;
vvi dp(n + 1, vi(k + 1, -1));
return minSteps(n, k, dp);
}
// Leetcode 96.
int numTrees(int n)
{
//Catlan no solution
vector<int> dp(n + 1, 0);
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= n; i++)
{
for (int j = 0; j < i; j++)
{
dp[i] += dp[j] * dp[i - 1 - j];
}
}
return dp[n];
}
int findLongestRepeatingSubSeq(string &X, int m, int n, vvi &dp)
{
if (dp[m][n] != -1)
return dp[m][n];
// return if we have reached the end of either string
if (m == 0 || n == 0)
return dp[m][n] = 0;
// if characters at index m and n matches
// and index is different
if (X[m - 1] == X[n - 1] && m != n)
return dp[m][n] = findLongestRepeatingSubSeq(X,
m - 1, n - 1, dp) +
1;
// else if characters at index m and n don't match
return dp[m][n] = max(findLongestRepeatingSubSeq(X, m, n - 1, dp),
findLongestRepeatingSubSeq(X, m - 1, n, dp));
}
int solve()
{
int n;
cin >> n;
string str;
cin >> str;
string rstr = string(str.rbegin(), str.rend());
vvi dp(n + 1, vi(n + 1, -1));
return findLongestRepeatingSubSeq(str, n, n, dp);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin >> t;
while (t--)
{
cout << solve() << endl;
}
return 0;
}<file_sep>/Practice/largestRectangleArea.cpp
#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#define vi vector<int>
#define vb vector<bool>
#define lli long long int
#define vvi vector<vector<int>>
#define loop(n) for (int i = 0; i < n; i++)
using namespace std;
int largestAreaInHistogram(vi &arr)
{
int maxArea = 0;
stack<int> st;
st.push(-1);
int n = arr.size();
for (int i = 0; i < n; i++)
{
while (st.top() != -1 && arr[st.top()] >= arr[i])
{
int h = arr[st.top()];
st.pop();
maxArea = max(maxArea, h * (i - st.top() - 1));
}
st.push(i);
}
while (st.top() != -1)
{
int h = arr[st.top()];
st.pop();
maxArea = max(maxArea, h * (n - st.top() - 1));
}
return maxArea;
}
int solve()
{
int n, m;
cin >> n >> m;
vector<vector<int>> board(n, vector<int>(m, 0));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> board[i][j];
for (int i = 1; i < n; i++) // building the board to run maxAreaInHistogram on each.
for (int j = 0; j < m; j++)
if (board[i][j] == 1)
board[i][j] += board[i - 1][j];
int myans = 0;
for (vi &arr : board)
myans = max(myans, largestAreaInHistogram(arr));
return myans;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin >> t;
while (t--)
{
cout << solve() << endl;
}
return 0;
}<file_sep>/Graph/Leetcode.java
import java.util.LinkedList;
import java.util.ArrayList;
public class Leetcode {
public static void main(String[] args) {
// int[][] matrix = { { 0, 0, 0 }, { 0, 1, 0 }, { 1, 1, 1 } };
// int[][] ans = updateMatrix(matrix);
// for(int[] row : ans)
// {
// for(int el : row)
// System.out.print(el + " ");
// System.out.println();
int[][] ar = { { 1, 0 } };
for (int[] row : ar)
System.out.println(row[0]+" "+row[1]);
System.out.println(canFinish(2,ar));
}
public static void solve(char[][] board) {
// surroundRegions(board);
}
// LeetCode 130 Surronding Regions==================
void mark(char[][] board, int r, int c, int n, int m) {
if (board[r][c] != 'O')
return;
board[r][c] = '#';
if (r + 1 < n)
mark(board, r + 1, c, n, m);
if (c + 1 < m)
mark(board, r, c + 1, n, m);
if (r - 1 >= 0)
mark(board, r - 1, c, n, m);
if (c - 1 >= 0)
mark(board, r, c - 1, n, m);
}
void surroundRegions(char[][] board) {
if (board.length == 0)
return;
int n = board.length;
int m = board[0].length;
for (int i = 0; i < m; i++) {
if (board[0][i] == 'O')
mark(board, 0, i, n, m);
if (board[n - 1][i] == 'O')
mark(board, n - 1, i, n, m);
}
for (int i = 0; i < n; i++) {
if (board[i][0] == 'O')
mark(board, i, 0, n, m);
if (board[i][m - 1] == 'O')
mark(board, i, m - 1, n, m);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (board[i][j] == 'O')
board[i][j] = 'X';
else if (board[i][j] == '#')
board[i][j] = 'O';
}
}
}
// qno 542
public static int[][] updateMatrix(int[][] matrix) {
int n = matrix.length;
if (n == 0)
return matrix;
int m = matrix[0].length;
if (m == 0)
return matrix;
LinkedList<int[]> que = new LinkedList<>();
// que.addLast(new int[] { matrix[0][0] });
int dir[][] = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
boolean[] vis = new boolean[n * m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (matrix[i][j] == 0) {
que.addLast(new int[] { i * m + j, 0 });
break;
}
// int[] pair = que.getFirst();
// System.out.println(pair[0]);
// System.out.println(pair[1]);
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
int[] rvtx = que.removeFirst();
int r = rvtx[0] / m;
int c = rvtx[0] % m;
int level = rvtx[1];
for (int d = 0; d < 4; d++) {
int x = r + dir[d][0];
int y = c + dir[d][1];
if (x >= 0 && y >= 0 && x < n && y < m && (vis[x * m + y]==false)) {
if (matrix[x][y] == 0) {
que.addLast(new int[] { x * m + y, 0 });
} else {
que.addLast(new int[] { x * m + y, level + 1 });
matrix[x][y] = level+1;
}
vis[x*m+y] = true; //needed to mark inside.
}
}
}
}
return matrix;
}
//207
public static boolean canFinish(int numCourses, int[][] prerequisites) {
int n = prerequisites.length;
if (n == 0)
return true;
ArrayList<Integer> graph[] = new ArrayList[numCourses];
for (int i = 0; i < numCourses; i++)
graph[i] = new ArrayList<Integer>();
for (int[] row : prerequisites)
graph[row[0]].add(row[1]);
int[] indegree = new int[numCourses];
LinkedList<Integer> que = new LinkedList<>();
ArrayList<Integer> ans = new ArrayList<>();
for (int[] row : prerequisites)
indegree[row[1]]++;
for (int i = 0; i < numCourses; i++)
if (indegree[i] == 0)
que.addLast(i);
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
int rvtx = que.removeFirst();
ans.add(rvtx);
for (int e : graph[rvtx])
if (--indegree[e] == 0)
que.addLast(e);
}
}
return ans.size() == numCourses ? true : false;
}
//210
public int[] findOrder(int numCourses, int[][] prerequisites) {
int n = prerequisites.length;
if (n == 0) {
int[] ar = new int[numCourses];
int idx = 0;
for (int i = numCourses - 1; i >= 0; i--)
ar[idx++] = i;
return ar;
}
if (prerequisites[0].length == 0)
return new int[] { 0 };
ArrayList<Integer> graph[] = new ArrayList[numCourses];
for (int i = 0; i < numCourses; i++)
graph[i] = new ArrayList<>();
for (int[] row : prerequisites)
graph[row[0]].add(row[1]);
int[] indegree = new int[numCourses];
LinkedList<Integer> que = new LinkedList<>();
ArrayList<Integer> ans = new ArrayList<>();
for (int[] row : prerequisites)
indegree[row[1]]++;
for (int i = 0; i < numCourses; i++)
if (indegree[i] == 0)
que.addLast(i);
while (que.size() != 0) {
int size = que.size();
while (size-- > 0) {
int rvtx = que.removeFirst();
ans.add(rvtx);
for (int e : graph[rvtx])
if (--indegree[e] == 0)
que.addLast(e);
}
}
if (ans.size() != numCourses)
return new int[0];
else {
int[] arr = new int[ans.size()];
int idx = 0;
for (int i = ans.size() - 1; i >= 0; i--)
arr[idx++] = ans.get(i);
return arr;
}
}
//329
int[][] dir = { { 0, 1 }, { -1, 0 }, { 0, -1 }, { 1, 0 } };
public int longestIncreasingPath(int[][] matrix) {
int n = matrix.length;
if (n == 0)
return 0;
int m = matrix[0].length;
if (m == 0)
return 0;
int[][] dp = new int[n][m];
int[][] dp_ = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
for (int d = 0; d < 4; d++) {
int x = i + dir[d][0];
int y = j + dir[d][1];
if (x < n && y < m && x >= 0 && y >= 0 && matrix[i][j] > matrix[x][y])
dp[i][j]++;
}
}
int maxLen = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
if (dp[i][j] == 0)
maxLen = Math.max(dfs(i, j, n, m, matrix, dp_), maxLen);
}
return maxLen;
}
int dfs(int sr, int sc, int n, int m, int[][] matrix, int[][] dp) {
if (dp[sr][sc] != 0)
return dp[sr][sc];
int count = 0;
for (int d = 0; d < 4; d++) {
int x = sr + dir[d][0];
int y = sc + dir[d][1];
if (x < n && y < m && x >= 0 && y >= 0 && matrix[sr][sc] < matrix[x][y])
count = Math.max(dfs(x, y, n, m, matrix, dp), count);
}
dp[sr][sc] = count + 1;
return count + 1;
}
}<file_sep>/Graph/l003_UnionFind.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
class Edge
{
public:
int v = 0;
int w = 0;
Edge(int v, int w)
{
this->v = v;
this->w = w;
}
};
int N = 7;
vector<vector<Edge>> graph(N, vector<Edge>());
void addEdge(vector<vector<Edge>> &gp, int u, int v, int w)
{
gp[u].push_back(Edge(v, w));
gp[v].push_back(Edge(u, w));
}
//unionFind.==============================================
// vector<int> par;
// vector<int> setSize;
// //path compression code =================================
// int findPar(int vtx)
// {
// if (par[vtx] == vtx)
// return vtx;
// return par[vtx] = findPar(par[vtx]);
// }
// void mergeSet(int l1, int l2)
// {
// if (setSize[l1] < setSize[l2])
// {
// par[l1] = l2;
// setSize[l2] += setSize[l1];
// }
// else
// {
// par[l2] = l1;
// setSize[l1] += setSize[l2];
// }
// }
// void unionFind()
// {
// }
void display(vector<vector<Edge>> &gp)
{
for (int i = 0; i < gp.size(); i++)
{
cout << i << "-> ";
for (Edge e : gp[i])
{
cout << "(" << e.v << "," << e.w << ") ";
}
cout << endl;
}
cout << endl;
}
void constructGraph()
{
addEdge(graph, 0, 1, 10);
addEdge(graph, 0, 3, 10);
addEdge(graph, 1, 2, 10);
addEdge(graph, 2, 3, 40);
addEdge(graph, 3, 4, 2);
addEdge(graph, 4, 5, 2);
addEdge(graph, 4, 6, 3);
addEdge(graph, 5, 6, 8);
// addEdge(graph, 2, 5, 2);
// display(graph);
cout << endl;
}
//Kruskal Algo for finding Minimumm cost Spanning Tree using union find
vector<int> par;
vector<int> setSize;
int findPar(int vtx)
{
if (par[vtx] == vtx)
return vtx;
return par[vtx] = findPar(par[vtx]);
}
void mergeSet(int p1, int p2)
{
if (setSize[p1] < setSize[p2])
{
par[p1] = p2;
setSize[p2] += setSize[p1];
}
else
{
par[p2] = p1;
setSize[p1] += setSize[p2];
}
}
void Kruskal(vector<vector<int>> &arr)
{
vector<vector<Edge>> Kruskalgraph(arr.size(), vector<Edge>());
sort(arr.begin(), arr.end(), [](vector<int> &a, vector<int> &b) {
return a[2] < b[2]; // this - other,default is Increasing, '-' replace with '<'
});
for (vector<int> &ar : arr)
{
int u = ar[0];
int v = ar[1];
int p1 = findPar(u);
int p2 = findPar(v);
if (p1 != p2)
{
mergeSet(p1, p2);
addEdge(Kruskalgraph, u, v, ar[2]);
}
}
display(Kruskalgraph);
}
void solve()
{
constructGraph();
}
int main()
{
solve();
return 0;
}
<file_sep>/Practice/Kmp.cpp
#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#define vi vector<int>
#define vb vector<bool>
#define lli long long int
#define vvi vector<vector<int>>
#define loop(n) for (int i = 0; i < n; i++)
using namespace std;
auto SpeedUp = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 0;
}();
void computLps(vi& lps, string p)
{
int n = p.size();
lps[0] = 0;
int i = 1, j=0;
while (i<n)
{
if (p[j]==p[i])
{
lps[i] = j+1;
i++;j++;
}
else
{
if (j!=0)
j = lps[j-1];
else
{
lps[i] = 0;
i++;
}
}
}
}
void KMP()
{
string text, pattern;
cin>>text>>pattern;
int n = text.size(), m =pattern.size();
vi lps(m, 0);
computLps(lps, pattern);
int i=0, j=0;
while (i<n)
{
if (pattern[j]==text[i])
{
j++;i++;
}
if (j==m)
{
cout<<"Found Pattern at"<<(i-j)<<endl;
j = lps[j-1];
}
else if(i<n && pattern[j]!=text[i])
{
if (j!=0)
j = lps[j-1];
else
i++;
}
}
}
int main()
{
int t;
cin >> t;
while (t--)
KMP();
return 0;
}<file_sep>/Practice/SegmentTree.cpp
#include "bits/stdc++.h"
#define vi vector<int>
#define vb vector<bool>
#define lli long long int
#define vvi vector<vector<int>>
#define loop(n) for (int i = 0; i < n; i++)
using namespace std;
auto SpeedUp = []() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 0;
}();
// segment tree ane different queries on them.
// at max ST takes O(4n) space ans at max O(4longn) search queries time. used array to represent ST
// they ineffective when we have so many updates on the array.
void constructST(vi &arr, vi &segTree, int low, int high, int pos)
{
if (low == high)
{
segTree[pos] = arr[low];
return;
}
int mid = (low + high) / 2;
constructST(arr, segTree, low, mid, 2 * pos + 1);
constructST(arr, segTree, mid + 1, high, 2 * pos + 2);
segTree[pos] = min(segTree[2 * pos + 1], segTree[2 * pos + 2]);
}
int rangeMinQurey(vi &segTree, int l, int r, int low, int high, int pos) // range queries use total overlap, partial overrlap,no overlap method;
{
if (l <= low && r >= high)
return segTree[pos]; // total overlap condition;
if (l > high || r < low)
return 1e9; // no overlap;
int mid = (low + high) / 2; //partial overlap condition;
return min(rangeMinQurey(segTree, l, r, low, mid, 2 * pos + 1), rangeMinQurey(segTree, l, r, mid + 1, high, 2 * pos + 2));
}
void solve()
{
int n = 4;
vi arr = {-1, 0, 3, 6};
//Height of segment tree
int x = (int)(ceil(log2(n)));
//Maximum size of segment tree
int size = 2 * (int)pow(2, x) - 1;
vi segTree(size, (int)1e9);
constructST(arr, segTree, 0, n - 1, 0); //function to construct the segment tree;
int querie;
cin >> querie;
int l, r;
while (querie--)
{
cin >> l >> r;
cout << rangeMinQurey(segTree, l, r, 0, n - 1, 0); // running queries on segtree lakes queries*long(n) time total;
}
}
int main()
{
int t;
cin >> t;
while (t--)
{
solve();
}
return 0;
}<file_sep>/Practice/Dp/largestSquareInMatrix.cpp
#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#define vi vector<int>
#define vb vector<bool>
#define lli long long int
#define vvi vector<vector<int>>
#define loop(n) for (int i = 0; i < n; i++)
using namespace std;
int omax;
int largetSquareInMatrix(int sr, int sc, vvi &board, vvi &dp)
{
if (sr == board.size() || sc == board[0].size())
return 0;
if (dp[sr][sc] != -1)
return dp[sr][sc];
int myans = 0;
int right = largetSquareInMatrix(sr, sc + 1, board, dp);
int diag = largetSquareInMatrix(sr + 1, sc + 1, board, dp);
int down = largetSquareInMatrix(sr + 1, sc, board, dp);
if (board[sr][sc] == 1)
myans = min({right, down, diag}) + 1;
omax = max(omax, myans);
return dp[sr][sc] = myans;
}
int largetSquareInMatrix_DP(vvi &board)
{
int omax = 0, n = board.size(), m = board[0].size();
vvi dp(n, vi(m, 0));
for (int i = n - 1; i >= 0; i--)
{
for (int j = m - 1; j >= 0; j--)
{
if (board[i][j] == 1)
dp[i][j] = min({dp[i + 1][j], dp[i][j + 1], dp[i + 1][j + 1]}) + 1;
omax = max(omax, dp[i][j]);
}
}
return omax;
}
int solve()
{
omax = 0;
int n, m;
cin >> n >> m;
vector<vector<int>> board(n, vector<int>(m, 0));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> board[i][j];
// vvi dp(n, vi(m, -1));
// largetSquareInMatrix(0, 0, board, dp);
// return omax;
return largetSquareInMatrix_DP(board);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin >> t;
while (t--)
{
cout << solve() << endl;
}
return 0;
}<file_sep>/Practice/painterPartition.cpp
#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#define vi vector<int>
#define vb vector<bool>
#define lli long long int
#define vvi vector<vector<int>>
#define loop(n) for (int i = 0; i < n; i++)
using namespace std;
auto SpeedUp = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 0;
}();
// binary search didn't produce the correct result for some testcases;
bool isCanPaint(vi& arr, int mid, int p)
{
int sum = 0, reqp=1;
for (int i=0;i<arr.size();i++)
{
if (sum>mid)
{
sum = 0;
reqp++;
if (reqp>p)
return false;
}
sum+=arr[i];
}
return true;
}
int painterPartition(vi& arr, int n, int p)
{
int si = 0, ei = 0;
loop(n) ei +=arr[i];
int ans = 0;
while (si<=ei)
{
int mid = (si+ei)/2;
if (isCanPaint(arr, mid, p))
{
ei = mid - 1;
ans = mid;
}
else
si = mid+1;
}
return ans;
}
int solve()
{
int k, n;
cin>>k>>n;
vi arr(n);
loop(n) cin>>arr[i];
vvi dp(k+1, vi(n+1, 0)); //using dp method to get correct ans;
for (int i=1;i<=n;i++)
dp[1][i] = dp[1][i-1] + arr[i-1];
for (int j =1;j<=k;j++)
dp[j][1] = arr[0];
for(int i=2;i<=k;i++)
{
for(int j = 2;j<=n;j++)
{
int ans = 1e8;
int sum = 0;
for(int z = j;z>=1;z--)
{
sum +=arr[z-1];
ans = min(ans, max(dp[i-1][z-1], sum));
}
dp[i][j] = ans;
}
}
// for(vi& ar:dp)
// {
// for (int ele : ar)
// cout<<ele<<" ";
// cout<<endl;
// }
return dp[k][n];
// return painterPartition(arr, n, p);
}
int main()
{
int t;
cin >> t;
while (t--)
{
cout << solve() << endl;
}
return 0;
}<file_sep>/Practice/Dp/1Kansack.cpp
#include "bits/stdc++.h"
#define vi vector<int>
#define vb vector<bool>
#define lli long long int
#define vvi vector<vector<int>>
#define loop(n) for (int i = 0; i < n; i++)
using namespace std;
auto SpeedUp = []() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
// std::ios::sync_with_stdio(false);
// cin.tie(nullptr);
// cout.tie(nullptr);
return 0;
}();
// code for 0/1 kanpsack using idx and value to store min weigth req to get that value;
int knapSack(vi &weg, vi &value, int n, int w, int tval, vector<vector<lli>> &dp)
{
//dp[idx][val] = it will store the min weght to require to get this value;
dp[0][0] = 0;
for (int idx = 1; idx <= n; idx++)
{
dp[idx][0] = 0; // by not thaking any object thus obtaning 0 value;
for (int val = 1; val <= tval; val++)
{
dp[idx][val] = dp[idx - 1][val]; //not taking current object;
if (val >= value[idx - 1])
dp[idx][val] = min(dp[idx][val], dp[idx - 1][val - value[idx - 1]] + weg[idx - 1]);
}
}
for (int val = tval; val >= 0; val--)
if (dp[n][val] <= w)
return val;
}
int solve()
{
int n, w;
scanf("%d%d", &n, &w);
vi weg(n, 0), val(n, 0);
int tval = 0;
loop(n)
{
scanf("%d", &weg[i]);
scanf("%d", &val[i]);
tval += val[i];
}
vector<vector<lli>> dp(n + 1, vector<lli>(tval + 1, 1e9));
return knapSack(weg, val, n, w, tval, dp);
}
int main()
{
printf("%d\n", solve());
return 0;
} | 42da6cefdcc76cc6ba4ed49436a6dde77c03fa25 | [
"Java",
"C++"
] | 21 | C++ | TheShivamMishra/Coding | b57980dbb44ce0cc5fde21550462af797a543124 | fb85a6e3d0b51e5e449c924d8e2c55e6e5e9848b | |
refs/heads/master | <file_sep>#ifndef UTILITY_H_
#define UTILITY_H_
#include<string>
#include<regex>
#include<fstream>
#include<algorithm>
#include<cmath>
bool is_number(const std::string& num);
std::string intToBinaryString(const int num, const int numOfHexDigits);
int binaryStringToInt(const std::string& binaryString);
std::string hextobin(const std::string &s);
std::string bintohex(const std::string &s);
bool exists_test0 (const std::string& name);
bool iequals(const std::string& str1, const std::string& str2);
std::string getUpperVersion(const std::string& x);
#endif /* UTILITY_H_ */
<file_sep>#include<iostream>
#include<map>
#include<string>
#include<fstream>
#include<regex>
#include"assemblerdata.h"
#include"utility.h"
bool is_mnemonicOrDirective(string x) {
string temp = getUpperVersion(x);
if ((opTable.find(temp) != opTable.end()) || isDirective(temp)) {
return true;
} else if (temp.at(0) == '+'
&& opTable.find(temp.substr(1, temp.size() - 1)) != opTable.end()) {
return true;
}
return false;
}
bool parse_label(string x, int i) {
smatch m;
regex r("^([A-Za-z]\\w*)$");
regex_search(x, m, r);
if (m.size() > 0) {
listing_table[i].label = m[1].str();
return true;
}
return false;
}
bool parse_mnemonic(string x, int i) {
smatch m;
regex r("^(\\+?(\\w+))$");
regex_search(x, m, r);
if (m.size() > 0) {
if (m[1].str().at(0) == '+') {
listing_table[i].isFormat4 = true;
}
listing_table[i].mnemonic = m[2].str();
return true;
}
return false;
}
bool parse_operand(string x, int i) {
smatch m;
regex r("^(\\*|([#@]?\\w+)|(\\w+(\\'|\\,|\\+|\\-|\\*|\\/)\\w+)(\\')?)$");
regex_search(x, m, r);
if (m.size() > 0) {
listing_table[i].operand = m[1].str();
return true;
}
regex r2("^(-?\\d+(\\,-?\\d+)+)$");
regex_search(x, m, r2);
if (m.size() > 0) {
listing_table[i].operand = m[1].str();
return true;
}
return false;
}
//3 cases
bool parse_instruction(string x[], int i) {
bool noError = true;
//case 1 mnemonic only
if (x[0].empty() && !x[1].empty() && x[2].empty()) {
noError = parse_mnemonic(x[1], i);
} //case 2 label, mnemonic and operand exists
else if (!x[0].empty() && !x[1].empty() && !x[2].empty()) {
noError = parse_label(x[0], i) & parse_mnemonic(x[1], i)
& parse_operand(x[2], i);
} //case 3 (label and mnemonic) OR (mnemonic and operand)
else if (!x[0].empty() && !x[1].empty() && x[2].empty()) {
//label and mnemonic
if (is_mnemonicOrDirective(x[1])) {
noError = parse_label(x[0], i) & parse_mnemonic(x[1], i);
} //mnemonic and operand
else if (is_mnemonicOrDirective(x[0])) {
noError = parse_mnemonic(x[0], i) & parse_operand(x[1], i);
} else {
return false;
}
} else {
return false;
}
return noError;
}
void build_listing_table(string path) {
if (exists_test0(path)) {
string line;
ifstream infile;
infile.open(path);
int i = 0;
while (getline(infile, line)) {
regex rComment("^(\\.)(.*)");
smatch m;
regex_search(line, m, rComment);
if (m.size() > 0 && m.position(0) == 0) {
listing_table[i].isAllComment = true;
listing_table[i].comment = m[0].str();
i++;
continue;
} else {
//ensure that label, mnemonic and operand don't start with "." (comment filter)
regex rInstruction(
"^\\s*(([^\\.]\\S*)\\s+)?([^\\.]\\S*)\\s*(\\s+([^\\.]\\S*))?\\s*(\\s+(\\..*))?$");
regex_search(line, m, rInstruction);
if (m.size() > 0) {
listing_table[i].comment = m[7].str();
string instruction[] =
{ m[2].str(), m[3].str(), m[5].str() };
if (!parse_instruction(instruction, i)) {
listing_table[i].error.insert(
listing_table[i].error.begin(),
"Invalid Instruction");
}
} else {
listing_table[i].error.insert(
listing_table[i].error.begin(),
"Invalid Instruction");
}
}
i++;
}
infile.close();
}
}
<file_sep>/*
* directivesHandler.cpp
*
* Created on: Apr 23, 2019
* Author: OWNER
*/
#include <sstream>
#include"assemblerdata.h"
#include"utility.h"
using namespace std;
int address;
int arrayLength;
bool isArray(string exp) {
smatch m;
regex r("-?\\d+(\\,-?\\d+)+");
if (regex_match(exp, m, r)) {
stringstream ss(exp);
vector<string> result;
while (ss.good()) {
string substr;
getline(ss, substr, ',');
result.push_back(substr);
}
arrayLength = result.size();
return true;
}
return false;
}
bool isInt(string op) {
try {
stoi(op);
return true;
} catch (invalid_argument& e) {
return false;
}
}
bool isRelative(string symbol) {
return symbol_table.find(symbol) != symbol_table.end()
&& symbol_table[symbol].type == 'R';
}
bool isAbslute(string symbol) {
return symbol_table.find(symbol) != symbol_table.end()
&& symbol_table[symbol].type == 'A';
}
bool isRelocatable(string exp) {
smatch m;
regex r("(\\w+)(\\+|\\-)(\\w+)");
if (regex_match(exp, m, r)) {
string operand1 = getUpperVersion(m[1]);
string operat = getUpperVersion(m[2]);
string operand2 = getUpperVersion(m[3]);
if (iequals("+", operat)) {
if ((isRelative(operand1) && isAbslute(operand2))
|| (isRelative(operand2) && isAbslute(operand1))) {
address = symbol_table[operand1].address
+ symbol_table[operand2].address;
return address >= 0;
} else if (isRelative(operand1) && isInt(operand2)) {
address = symbol_table[operand1].address + stoi(operand2);
return address >= 0;
} else if (isRelative(operand2) && isInt(operand1)) {
address = symbol_table[operand2].address + stoi(operand1);
return address >= 0;
}
} else if (iequals("-", operat)) {
if (isRelative(operand1) && isInt(operand2)) {
address = symbol_table[operand1].address - stoi(operand2);
return address >= 0;
}else if(isRelative(operand1) && isAbslute(operand2)){
address = symbol_table[operand1].address
- symbol_table[operand2].address;
return address >= 0;
}
}
}
regex r2("(\\*)(\\+|\\-)(\\w+)");
if (regex_match(exp, m, r2)) {
string operat = getUpperVersion(m[2]);
string operand2 = getUpperVersion(m[3]);
if (iequals("+", operat)) {
if (isAbslute(operand2)) {
address = symbol_table[operand2].address + LOCCTR;
return address >= 0;
} else if (isInt(operand2)) {
address = LOCCTR + stoi(operand2);
return address >= 0;
}
} else if (iequals("-", operat)) {
if (isInt(operand2)) {
address = LOCCTR - stoi(operand2);
return address >= 0;
} else if (isAbslute(operand2)) {
address = -symbol_table[operand2].address + LOCCTR;
return address >= 0;
}
}
}
regex r3("(\\w+)(\\+|\\-)(\\*)");
if (regex_match(exp, m, r3)) {
string operat = getUpperVersion(m[2]);
string operand1 = getUpperVersion(m[1]);
if (iequals("+", operat)) {
if (isAbslute(operand1)) {
address = symbol_table[operand1].address + LOCCTR;
return address >= 0;
} else if (isInt(operand1)) {
address = LOCCTR + stoi(operand1);
return address >= 0;
}
}
}
return false;
}
bool isAbsluteExp(string exp) {
smatch m;
regex r("(\\w+)(\\+|\\-|\\*|\\/)(\\w+)");
if (regex_match(exp, m, r)) {
string operand1 = getUpperVersion(m[1]);
string operat = getUpperVersion(m[2]);
string operand2 = getUpperVersion(m[3]);
if (iequals("+", operat)) {
if (isAbslute(operand1) && isAbslute(operand2)) {
address = symbol_table[operand1].address
+ symbol_table[operand2].address;
return true;
} else if (isAbslute(operand1) && isInt(operand2)) {
address = symbol_table[operand1].address + stoi(operand2);
return true;
} else if (isAbslute(operand2) && isInt(operand1)) {
address = symbol_table[operand2].address + stoi(operand1);
return true;
} else if (isInt(operand1) && isInt(operand2)) {
address = stoi(operand1) + stoi(operand2);
return true;
} else {
return false;
}
} else if (iequals("-", operat)) {
if (isAbslute(operand1) && isAbslute(operand2)) {
address = symbol_table[operand1].address
- symbol_table[operand2].address;
return true;
} else if (isAbslute(operand1) && isInt(operand2)) {
address = symbol_table[operand1].address - stoi(operand2);
return true;
} else if (isAbslute(operand2) && isInt(operand1)) {
address = -symbol_table[operand2].address + stoi(operand1);
return true;
} else if (isInt(operand1) && isInt(operand2)) {
address = stoi(operand1) - stoi(operand2);
return true;
} else if (isRelative(operand1) && isRelative(operand2)) {
address = symbol_table[operand1].address
- symbol_table[operand2].address;
;
return true;
} else {
return false;
}
} else if (iequals("*", operat)) {
if (isAbslute(operand1) && isAbslute(operand2)) {
address = symbol_table[operand1].address
* symbol_table[operand2].address;
return true;
} else if (isAbslute(operand1) && isInt(operand2)) {
address = symbol_table[operand1].address * stoi(operand2);
return true;
} else if (isAbslute(operand2) && isInt(operand1)) {
address = symbol_table[operand2].address * stoi(operand1);
return true;
} else if (isInt(operand1) && isInt(operand2)) {
address = stoi(operand1) * stoi(operand2);
return true;
} else {
return false;
}
} else if (iequals("/", operat)) {
if (isAbslute(operand1) && isAbslute(operand2)) {
address = symbol_table[operand1].address
/ symbol_table[operand2].address;
return true;
} else if (isAbslute(operand1) && isInt(operand2)) {
address = symbol_table[operand1].address / stoi(operand2);
return true;
} else if (isAbslute(operand2) && isInt(operand1)) {
address = stoi(operand1) / symbol_table[operand2].address;
return true;
} else if (isInt(operand1) && isInt(operand2)) {
address = stoi(operand1) / stoi(operand2);
return true;
} else {
return false;
}
} else {
return false;
}
} else {
regex r2("(*)(\\-)(\\w+)");
if (regex_match(exp, m, r2)) {
string operat = getUpperVersion(m[2]);
string operand2 = getUpperVersion(m[3]);
if (isRelative(operand2)) {
address = -symbol_table[operand2].address + LOCCTR;
return address >= 0;
}
}
regex r3("(\\w+)(\\-)(\\*)");
if (regex_match(exp, m, r3)) {
string operat = getUpperVersion(m[2]);
string operand2 = getUpperVersion(m[1]);
if (isRelative(operand2)) {
address = symbol_table[operand2].address - LOCCTR;
return address >= 0;
}
}
return false;
}
}
bool handleByte(listing_line x);
bool handleWord(listing_line x);
bool handleRes(listing_line x, int increase_val);
bool handleOrg(listing_line x);
bool handleEqu(listing_line x);
bool handleBase(listing_line x);
bool isDirective(string x) {
if (iequals(x, "START") || iequals(x, "END") || iequals(x, "BYTE")
|| iequals(x, "WORD") || iequals(x, "RESW") || iequals(x, "RESB")
|| iequals(x, "EQU") || iequals(x, "ORG") || iequals(x, "BASE")
|| iequals(x, "NOBASE")) {
return true;
}
return false;
}
bool handleDirective(listing_line x) {
if (iequals(x.mnemonic, "byte")) {
return handleByte(x);
} else if (iequals(x.mnemonic, "word")) {
return handleWord(x);
} else if (iequals(x.mnemonic, "resw")) {
return handleRes(x, 3);
} else if (iequals(x.mnemonic, "resb")) {
return handleRes(x, 1);
} else if (iequals(x.mnemonic, "equ")) {
return handleEqu(x);
} else if (iequals(x.mnemonic, "org")) {
return handleOrg(x);
} else if (iequals(x.mnemonic, "base")) {
return handleBase(x);
} else if (iequals(x.mnemonic, "nobase")) {
if (!(x.operand.empty() && x.label.empty())) {
return false;
}
} else {
return false;
}
return true;
}
bool handleByte(listing_line x) {
if (x.operand.size() < 3) {
return false;
}
if ((x.operand[0] == 'x' || x.operand[0] == 'X')
&& x.operand.size() % 2 == 1) {
if (x.operand[1] == '\'' && x.operand[x.operand.size() - 1] == '\'') {
try {
stoi(x.operand.substr(2, x.operand.size() - 3), 0, 16);
} catch (invalid_argument& e) {
return false;
}
LOCCTR += (x.operand.size() - 3) / 2;
return true;
}
} else if (x.operand[0] == 'c' || x.operand[0] == 'C') {
if (x.operand[1] == '\'' && x.operand[x.operand.size() - 1] == '\'') {
LOCCTR += x.operand.size() - 3;
return true;
}
}
return false;
}
bool handleWord(listing_line x) {
if (isArray(x.operand)) {
LOCCTR += 3 * arrayLength;
} else
try {
stoi(x.operand);
LOCCTR += 3;
} catch (invalid_argument& e) {
return false;
}
return true;
}
bool handleRes(listing_line x, int increase_val) {
try {
int z = stoi(x.operand);
LOCCTR += increase_val * z;
} catch (invalid_argument& e) {
return false;
}
return true;
}
bool handleOrg(listing_line x) {
string operand = getUpperVersion(x.operand);
if (!x.label.empty()) {
return false;
} else if (symbol_table.find(operand) != symbol_table.end()) {
LOCCTR = symbol_table[operand].address;
return true;
} else if (operand[0] == '*' && operand.size() == 1) {
return true;
} else if (isRelocatable(operand)) {
LOCCTR = address;
return true;
}
try {
int z = stoi(x.operand);
LOCCTR = z;
return true;
} catch (invalid_argument& e) {
return false;
}
}
bool handleEqu(listing_line x) {
string label = getUpperVersion(x.label);
string operand = getUpperVersion(x.operand);
if (x.label.empty() || operand.empty()) {
return false;
} else if (symbol_table.find(operand) != symbol_table.end()) {
symbol_table[label].address = symbol_table[operand].address;
} else if (iequals("*", operand)) {
symbol_table[label].address = LOCCTR;
} else {
if (isRelocatable(operand)) {
symbol_table[label].address = address;
return true;
} else if (isAbsluteExp(operand)) {
symbol_table[label].address = address;
symbol_table[label].type = 'A';
return true;
}
try {
int z = stoi(x.operand);
symbol_table[label].address = z;
symbol_table[label].type = 'A';
} catch (invalid_argument& e) {
return false;
}
}
return true;
}
bool handleBase(listing_line x) {
string operand = getUpperVersion(x.operand);
if (!x.label.empty() || x.operand.empty()) {
return false;
}
return true;
}
string wordObCode(unsigned int lineNumber) {
string operand = listing_table[lineNumber].operand;
string ans = "";
if (isArray(operand)) {
stringstream ss(operand);
while (ss.good()) {
string substr;
getline(ss, substr, ',');
ans = ans + bintohex(intToBinaryString(stoi(substr), 6));
}
} else {
int x = stoi(operand);
ans = ans + bintohex(intToBinaryString(x, 6));
}
return ans;
}
string byteObCode(unsigned int lineNumber) {
string operand = listing_table[lineNumber].operand;
string ans = "";
if (operand[0] == 'x' || operand[0] == 'X') {
// int i = 2;
ans = operand.substr(2, operand.size() - 3);
// while (i <= operand.size() - 3) {
// ans = ans+ bintohex(intToBinaryString(stoi(operand.substr(i, 2), 0, 16),1));
// i += 2;
// }
} else {
unsigned int i = 2;
while (i <= operand.size() - 2) {
ans = ans + bintohex(intToBinaryString(operand[i], 2));
i++;
}
}
return ans;
}
bool handleBasePass2(unsigned int lineNumber) {
string operand = listing_table[lineNumber].operand;
if (symbol_table.find(operand) != symbol_table.end()) {
base = symbol_table[operand].address;
} else if (iequals("*", operand)) {
//TODO locctr?
base = LOCCTR;
} else {
if (isRelocatable(operand)) {
base = address;
} else if (isAbsluteExp(operand)) {
base = address;
}
try {
int z = stoi(operand);
base = z;
} catch (invalid_argument& e) {
return false;
}
}
return true;
}
<file_sep>#include<iostream>
#include<map>
#include<string>
#include<fstream>
#include<vector>
#include<iterator>
#include <sstream>
#include"assemblerdata.h"
#include"utility.h"
using namespace std;
map<string, struct_opcode> opTable;
map<unsigned int, listing_line> listing_table;
map<string, symbol_struct> symbol_table;
unsigned int starting_address;
unsigned int program_length;
unsigned int current_line_number;
unsigned int LOCCTR;
listing_line current_line;
bool errorInPass1 = false;
void loadOpTable(string path) {
if (exists_test0(path)) {
string line;
ifstream infile;
infile.open(path);
while (getline(infile, line)) {
regex r("(\\w+)\\s+(\\w+)\\s+(\\w+)");
smatch m;
regex_search(line, m, r);
opTable[m[1].str()].format = stoi(m[2].str());
opTable[m[1].str()].opcode = m[3].str();
}
infile.close();
}
}
void write_symbol_table() {
ofstream file;
file.open("SymbolTable.txt");
file << "Symbol Value Relative(R)/Absolute(A)\n\n";
map<string, symbol_struct>::iterator itr;
for (itr = symbol_table.begin(); itr != symbol_table.end(); itr++) {
string k = itr->first;
file << k;
unsigned int spaces = 9 - k.size();
while (spaces > 0) {
file << " ";
spaces--;
}
std::stringstream ss;
ss << std::hex << itr->second.address; // int decimal_value
std::string res(ss.str());
int temp = 6 - res.length();
while (temp > 0) {
res = "0" + res;
temp--;
}
file << res;
unsigned int spaces1 = 19 - res.size();
while (spaces1 > 0) {
file << " ";
spaces1--;
}
file << itr->second.type;
file << "\n";
}
}
void write_listing_file2(string fileName) {
ofstream file;
file.open(fileName);
file << "Line no. Address Label Mnemonic Operand Object Code\n\n";
map<unsigned int, listing_line>::iterator itr;
int i = 0;
bool flag = false;
for (itr = listing_table.begin(); itr != listing_table.end(); itr++) {
if (itr->second.isAllComment) {
continue;
}
i++;
if (flag) {
unsigned int t = 0;
for (t = 0; t < listing_table[i - 2].error.size(); t++) {
file << " ****Error: ";
file << listing_table[i - 2].error.at(t);
file << "\n";
}
flag = false;
} else if (!listing_table[i - 1].error.empty()) {
flag = true;
}
if (i < 10) {
file << i;
file << " ";
} else if (i < 100) {
file << i;
file << " ";
} else if (i < 1000) {
file << i;
file << " ";
}
std::stringstream ss;
ss << std::hex << itr->second.address; // int decimal_value
std::string res(ss.str());
int temp = 6 - res.length();
while (temp > 0) {
res = "0" + res;
temp--;
}
file << getUpperVersion(res);
file << " ";
file << itr->second.label;
unsigned int spaces2 = 9 - itr->second.label.size();
while (spaces2 > 0) {
file << " ";
spaces2--;
}
if (itr->second.isFormat4) {
file << '+' << itr->second.mnemonic;
} else {
file << itr->second.mnemonic;
}
unsigned int spaces1 = 10 - itr->second.mnemonic.size();
if (itr->second.isFormat4) {
spaces1--;
}
while (spaces1 > 0) {
file << " ";
spaces1--;
}
file << itr->second.operand;
unsigned int spaces = 17 - itr->second.operand.size();
while (spaces > 0) {
file << " ";
spaces--;
}
file << itr->second.objectCode;
file << "\n";
}
if (flag) {
unsigned int t = 0;
for (t = 0; t < listing_table[i - 1].error.size(); t++) {
file << " ****Error: ";
file << listing_table[i - 1].error.at(t);
file << "\n";
}
flag = false;
}
file.close();
}
void write_listing_file(string fileName) {
ofstream file;
file.open(fileName);
file << "Line no. Address Label Mnemonic Operand Comments\n\n";
map<unsigned int, listing_line>::iterator itr;
int i = 0;
bool flag = false;
for (itr = listing_table.begin(); itr != listing_table.end(); itr++) {
i++;
if (flag) {
errorInPass1 = true;
unsigned int t = 0;
for (t = 0; t < listing_table[i - 2].error.size(); t++) {
file << " ****Error: ";
file << listing_table[i - 2].error.at(t);
file << "\n";
}
flag = false;
} else if (!listing_table[i - 1].error.empty()) {
flag = true;
}
if (i < 10) {
file << i;
file << " ";
} else if (i < 100) {
file << i;
file << " ";
} else if (i < 1000) {
file << i;
file << " ";
}
std::stringstream ss;
ss << std::hex << itr->second.address; // int decimal_value
std::string res(ss.str());
int temp = 6 - res.length();
while (temp > 0) {
res = "0" + res;
temp--;
}
file << getUpperVersion(res);
file << " ";
file << itr->second.label;
unsigned int spaces2 = 9 - itr->second.label.size();
while (spaces2 > 0) {
file << " ";
spaces2--;
}
if (itr->second.isFormat4) {
file << '+' << itr->second.mnemonic;
} else {
file << itr->second.mnemonic;
}
unsigned int spaces1 = 10 - itr->second.mnemonic.size();
if (itr->second.isFormat4) {
spaces1--;
}
while (spaces1 > 0) {
file << " ";
spaces1--;
}
file << itr->second.operand;
unsigned int spaces = 17 - itr->second.operand.size();
while (spaces > 0) {
file << " ";
spaces--;
}
file << itr->second.comment;
file << "\n";
}
if (flag) {
errorInPass1 = true;
unsigned int t = 0;
for (t = 0; t < listing_table[i - 1].error.size(); t++) {
file << " ****Error: ";
file << listing_table[i - 1].error.at(t);
file << "\n";
}
flag = false;
}
file.close();
}
void pass1_Algorithm(string codePath) {
build_listing_table(codePath);
current_line_number = 0;
//skip the comments
while (listing_table[current_line_number].isAllComment) {
current_line_number++;
}
current_line = listing_table[current_line_number];
//check start addressing
if (iequals(current_line.mnemonic, "START")) {
starting_address = stoi(current_line.operand, 0, 16);
listing_table[current_line_number].address = starting_address;
current_line = listing_table[++current_line_number];
} else {
starting_address = 0;
}
LOCCTR = starting_address;
//reading code loop
while (!iequals(current_line.mnemonic, "END")) {
//assign address to the line
listing_table[current_line_number].address = LOCCTR;
//process the line if not a comment
if (!current_line.isAllComment) {
//process the label field
if (!current_line.label.empty()) {
//save the label in symbol table in upper case form
string label = getUpperVersion(current_line.label);
if (symbol_table.find(label) != symbol_table.end()) {
listing_table[current_line_number].error.push_back(
"symbol '" + current_line.label
+ "' is already defined");
} else {
symbol_table[label].address = LOCCTR;
}
}
//process the mnemonic
string mnemonic = getUpperVersion(current_line.mnemonic);
if (opTable.find(mnemonic) != opTable.end()) {
//not directive
if (opTable[mnemonic].format == 3 && current_line.isFormat4) {
LOCCTR += 4;
} else if (opTable[mnemonic].format == 2
&& current_line.isFormat4) {
listing_table[current_line_number].error.push_back(
"Can't use format 4 with mnemonic "
+ current_line.mnemonic);
} else {
LOCCTR += opTable[mnemonic].format;
}
} else if (handleDirective(current_line)) {
} else {
listing_table[current_line_number].error.push_back(
"Invalid operation code");
}
} //end line process
++current_line_number;
if (listing_table.find(current_line_number) == listing_table.end()) {
listing_table[current_line_number - 1].error.push_back(
"There is no End directive");
break;
}
current_line = listing_table[current_line_number];
if (iequals(current_line.mnemonic, "END")
&& !current_line.label.empty()) {
listing_table[current_line_number].error.push_back(
"Label field must be blank in END instruction !!");
}
}
listing_table[current_line_number].address = LOCCTR;
program_length = LOCCTR - starting_address;
}
void runPass1(string input) {
loadOpTable("optable.txt");
pass1_Algorithm(input);
write_listing_file("ListingTable.txt");
write_symbol_table();
}
//int main() {
// //Enter "pass1 <input-file-name>" to start
// //pass1 input.txt
//
// loadOpTable("optable.txt");
// bool error = true;
// while(error){
// cout << "Enter 'pass1 <input-file-name>' to start, Ex : pass1 input.txt" <<endl;
// string input;
// getline(cin, input);
// smatch m;
// regex r("^pass1\\s+(\\S+)$");
// regex_search(input, m, r);
// if (m.size() > 0) {
// error = false;
// pass1_Algorithm(m[1].str());
// write_listing_file();
// }else{
// cout << "File name format is not correct" <<endl<<endl;
// }
// }
// write_listing_file();
// write_symbol_table();
// return 0;
//}
<file_sep>#include<iostream>
#include"assemblerdata.h"
#include"utility.h"
using namespace std;
int base = -1;
map<string, string> registers;
string objectCode;
void loadRegisters() {
registers["A"] = "0000";
registers["X"] = "0001";
registers["L"] = "0010";
registers["B"] = "0011";
registers["S"] = "0100";
registers["T"] = "0101";
registers["F"] = "0110";
registers["PC"] = "1000";
registers["SW"] = "1001";
}
bool handleFormat2(string mnemonic, string operand) {
objectCode = hextobin(opTable[mnemonic].opcode);
smatch m;
regex r("^(\\w+)(\\,(\\w+))?$");
regex_search(operand, m, r);
if (m.size() > 0 && registers.find(m[1].str()) != registers.end()) {
//register 1 exist
objectCode.append(registers[m[1].str()]);
if (m[3].str().empty()) {
//no register 2
objectCode.append("0000");
} else {
if (registers.find(m[3].str()) != registers.end()) {
//register 2 exist
objectCode.append(registers[m[3].str()]);
} else {
return false;
}
}
} else {
return false;
}
objectCode = bintohex(objectCode);
return true;
}
bool isOperandToTargetAddress(string operand) {
if (operand.empty()) {
return false;
} else if (symbol_table.find(operand) != symbol_table.end()) {
address = symbol_table[operand].address;
} else if (iequals("*", operand)) {
address = LOCCTR;
} else {
if (isRelocatable(operand)) {
return true;
} else if (isAbsluteExp(operand)) {
return true;
}
try {
int z = stoi(operand);
address = z;
} catch (invalid_argument& e) {
return false;
}
}
return true;
}
//return false if there is an error in operand
bool instructionToObjectCode(unsigned int line_number) {
objectCode.clear();
loadRegisters();
string operand = getUpperVersion(listing_table[line_number].operand);
string mnemonic = getUpperVersion(listing_table[line_number].mnemonic);
unsigned int format =
listing_table[line_number].isFormat4 == true ?
4 : opTable[mnemonic].format;
if (format == 2) {
if (handleFormat2(mnemonic, operand)) {
return true;
} else {
listing_table[line_number].error.push_back(
"Couldn't process format 2 !!");
return false;
}
}
objectCode = hextobin(opTable[mnemonic].opcode).substr(0, 6);
//handle special case RSUB has no operand
if (mnemonic == "RSUB") {
objectCode = bintohex(objectCode.append("110000"));
objectCode.append("000");
if (format == 4) {
objectCode.append("00");
}
return true;
}
string last2chars = "";
last2chars.push_back(operand[operand.size() - 2]);
last2chars.push_back(operand[operand.size() - 1]);
if (iequals(last2chars, ",X")) {
//indexing nix = 111
objectCode.append("111");
operand = operand.substr(0, operand.size() - 2);
} else if (operand[0] == '#') {
//immediate nix = 010
objectCode.append("010");
operand = operand.substr(1, operand.size() - 1);
if (is_number(operand)) {
//special case operand is #int ex: #3
if (format == 4) {
if (stoi(operand) < 0 || stoi(operand) > 1048575) {
//1048575 dec = fffff hex
listing_table[line_number].error.push_back(
"Operand Can't be greater than 0XFFFFF or less than 0 in format 4 !!");
return false;
}
//bpe = 001
objectCode.append("001");
objectCode.append(intToBinaryString(stoi(operand), 5));
objectCode = bintohex(objectCode);
} else {
if (stoi(operand) < 0 || stoi(operand) > 4095) {
//4095 dec = fff hex
listing_table[line_number].error.push_back(
"Operand Can't be greater than 0XFFF or less than 0 in format 3 !!");
return false;
}
//bpe = 000
objectCode.append("000");
objectCode.append(intToBinaryString(stoi(operand), 3));
objectCode = bintohex(objectCode);
}
return true;
}
//TODO evaluate expression
//if(/*expression*/)
} else if (operand[0] == '@') {
//indirect nix = 100
objectCode.append("100");
operand = operand.substr(1, operand.size() - 1);
} else {
//simple addressing with no indexing nix = 110
objectCode.append("110");
}
int TA;
if (isOperandToTargetAddress(operand)) {
TA = address;
} else {
listing_table[line_number].error.push_back("Invalid operand !!");
return false;
}
if (format == 4) {
//TODO modification record
objectCode.append("001");
objectCode.append(intToBinaryString(TA, 5));
objectCode = bintohex(objectCode);
} else {
int disp = TA - (LOCCTR + format);
if (-2048 <= disp && disp <= 2047) {
//PC-relative bpe = 010
objectCode.append("010");
} else if (base >= 0) {
//base available
disp = TA - base;
if (0 <= disp && disp <= 4095) {
//base relative bpe = 100
objectCode.append("100");
} else {
listing_table[line_number].error.push_back(
"Can't Process the address!!");
return false;
}
}
objectCode.append(intToBinaryString(disp, 3));
objectCode = bintohex(objectCode);
}
if (objectCode.length() != 6 && format == 3) {
listing_table[line_number].error.push_back(
"Error in operand in format 3 !!");
return false;
} else if (objectCode.length() != 8 && format == 4) {
listing_table[line_number].error.push_back(
"Error in operand in format 4 !!");
return false;
} else {
return true;
}
}
void pass2() {
current_line_number = 0;
//skip the comments
while (listing_table[current_line_number].isAllComment) {
current_line_number++;
}
current_line = listing_table[current_line_number];
ofstream file;
file.open("ObjectProgram.txt");
file << "H^";
//check start mnemonic (Program name)
if (iequals(current_line.mnemonic, "START")) {
if (current_line.label.size() > 6) {
current_line.error.push_back(
"Program name is more than 6 characters");
file << current_line.label.substr(0, 6);
} else {
int spacesNum = 6 - current_line.label.size();
file << current_line.label;
for (int i = 0; i < spacesNum; ++i) {
file << " ";
}
}
current_line = listing_table[++current_line_number];
} else {
file << " ";
}
file << "^";
LOCCTR = starting_address;
file << bintohex(intToBinaryString(starting_address, 6));
file << "^";
file << bintohex(intToBinaryString(program_length, 6));
file << "\n";
//max length of tRecord = 30 bytes (0x1E) = 60 hex digits
int tRecordLength = 0; //length by hex digits
int tRecordStart = starting_address;
vector<string> tRecords;
string tempRecord;
while (!iequals(current_line.mnemonic, "END")) {
LOCCTR = current_line.address;
if (tRecordStart == -1) {
tRecordStart = LOCCTR;
}
if (!current_line.error.empty()) {
current_line = listing_table[++current_line_number];
continue;
}
//process the line if not a comment
if (!current_line.isAllComment) {
string mnemonic = getUpperVersion(current_line.mnemonic);
if (opTable.find(mnemonic) != opTable.end()) {
//not directive
if (instructionToObjectCode(current_line_number)) {
tRecordLength += objectCode.size();
tRecords.push_back(objectCode);
listing_table[current_line_number].objectCode = objectCode;
}
} else {
//directive
if (iequals(current_line.mnemonic, "NOBASE")) {
base = -1;
} else if (iequals(current_line.mnemonic, "BASE")) {
if (!handleBasePass2(current_line_number)) {
listing_table[current_line_number].error.push_back(
"Error in BASE operand");
}
} else if (iequals(current_line.mnemonic, "WORD")) {
objectCode = wordObCode(current_line_number);
tRecordLength += objectCode.size();
tRecords.push_back(objectCode);
listing_table[current_line_number].objectCode = objectCode;
} else if (iequals(current_line.mnemonic, "BYTE")) {
objectCode = byteObCode(current_line_number);
tRecordLength += objectCode.size();
tRecords.push_back(objectCode);
listing_table[current_line_number].objectCode = objectCode;
}
}
if (tRecordLength > 60) {
file << "T^";
file << bintohex(intToBinaryString(tRecordStart, 6));
file << "^";
tempRecord = tRecords.back();
tRecords.erase(tRecords.end() - 1);
tRecordLength -= tempRecord.size();
file << bintohex(intToBinaryString(tRecordLength / 2, 2));
file << "^";
int temp;
for (unsigned int i = 0; i < tRecords.size() - 1; i++) {
file << tRecords.at(i);
file << "^";
temp = i;
}
file << tRecords.at(temp + 1);
file << "\n";
tRecords.clear();
tRecords.push_back(tempRecord);
tRecordStart = LOCCTR;
tRecordLength = tempRecord.size();
} else if (iequals(current_line.mnemonic, "RESW")
|| iequals(current_line.mnemonic, "RESB")
|| iequals(current_line.mnemonic, "ORG")) {
if (!tRecords.empty()) {
file << "T^";
file << bintohex(intToBinaryString(tRecordStart, 6));
file << "^";
file << bintohex(intToBinaryString(tRecordLength / 2, 2));
file << "^";
int temp;
for (unsigned int i = 0; i < tRecords.size() - 1; i++) {
file << tRecords.at(i);
file << "^";
temp = i;
}
file << tRecords.at(temp + 1);
file << "\n";
tRecords.clear();
tRecordLength = 0;
}
//start from the next iteration
tRecordStart = -1;
}
}
current_line = listing_table[++current_line_number];
}
if (iequals(current_line.mnemonic, "END") && !tRecords.empty()) {
file << "T^";
file << bintohex(intToBinaryString(tRecordStart, 6));
file << "^";
file << bintohex(intToBinaryString(tRecordLength / 2, 2));
file << "^";
int temp;
for (unsigned int i = 0; i < tRecords.size() - 1; i++) {
file << tRecords.at(i);
file << "^";
temp = i;
}
file << tRecords.at(temp + 1);
file << "\n";
}
if (iequals(current_line.mnemonic, "END")) {
file << "E^";
if (!current_line.operand.empty()) {
if (isOperandToTargetAddress(current_line.operand)) {
file << bintohex(intToBinaryString(address, 6));
} else {
listing_table[current_line_number].error.push_back(
"Error in End operand !!");
}
} else {
file << "000000";
}
}
file.close();
}
int main() {
//Enter "assemble <input-file-name>" to start
//assemble input.txt
string input;
getline(cin, input);
smatch m;
regex r("^assemble\\s+(\\S+)$");
regex_search(input, m, r);
if (m.size() > 0) {
runPass1(m[1].str());
if(!errorInPass1){
pass2();
write_listing_file2("ObjectCode.txt");
}
}
}
<file_sep>#include"utility.h"
using namespace std;
//helping functions
bool is_number(const std::string& num) {
string s = num[0] == '-' ? num.substr(1, num.length() - 1) : num;
return !s.empty()
&& std::find_if(s.begin(), s.end(),
[](char c) {return !std::isdigit(c);}) == s.end();
}
//numOfHexDigits must be big enough to carry the whole int
std::string intToBinaryString(const int num, const int numOfHexDigits) {
unsigned int x;
if (num < 0) {
x = -1 * num;
} else {
x = num;
}
std::string s;
do {
s.push_back('0' + (x & 1));
} while (x >>= 1);
std::reverse(s.begin(), s.end());
int diff = numOfHexDigits * 4 - s.size();
string temp = "";
for(int i = 0; i < diff; ++i) {
temp.push_back('0');
}
s = temp.append(s);
if (num < 0) {
bool firstOnePassed = false;
for (int j = s.size() - 1; j >= 0 ; --j) {
if(firstOnePassed){
s[j] = (s[j] == '1') ? '0': '1';
}
if(s[j] == '1'){
firstOnePassed = true;
}
}
}
return s;
}
int binaryStringToInt(const string &binaryString) {
int value = 0;
int indexCounter = 0;
for (int i = binaryString.length() - 1; i >= 0; i--) {
if (binaryString[i] == '1') {
value += pow(2, indexCounter);
}
indexCounter++;
}
return value;
}
string hextobin(const string &s) {
string out;
for (auto i : s) {
uint8_t n;
if (i <= '9' and i >= '0')
n = i - '0';
else
n = 10 + i - 'A';
for (int8_t j = 3; j >= 0; --j)
out.push_back((n & (1 << j)) ? '1' : '0');
}
return out;
}
string bintohex(const string &s) {
string out;
for (unsigned int i = 0; i < s.size(); i += 4) {
int8_t n = 0;
for (unsigned int j = i; j < i + 4; ++j) {
n <<= 1;
if (s[j] == '1')
n |= 1;
}
if (n <= 9)
out.push_back('0' + n);
else
out.push_back('A' + n - 10);
}
return out;
}
bool exists_test0(const std::string& name) {
ifstream f(name.c_str());
return f.good();
}
string getUpperVersion(const string &x) {
string temp;
transform(x.begin(), x.end(), back_inserter(temp), ::toupper);
return temp;
}
//iequals function check equality of two strings CASE-INSENSITIVE
struct iequal {
bool operator()(int c1, int c2) const {
return std::toupper(c1) == std::toupper(c2);
}
};
bool iequals(const std::string& str1, const std::string& str2) {
return (str1.size() == str2.size())
&& std::equal(str1.begin(), str1.end(), str2.begin(), iequal());
}
//end iequals
<file_sep>#include<map>
#include<string>
#include<vector>
#include<regex>
using namespace std;
#ifndef ASSEMBLERDATA_H_
#define ASSEMBLERDATA_H_
struct struct_opcode {
string opcode;
unsigned int format;
};
struct listing_line {
bool isAllComment;
unsigned int address;
bool isFormat4;
string label;
string mnemonic;
string operand;
string comment;
vector<string> error;
string objectCode;
};
struct symbol_struct{
int address;
char type;
symbol_struct() : address(0), type('R') {}
};
extern map<string, struct_opcode> opTable;
extern map<unsigned int, listing_line> listing_table;
//key: label name , value: address
extern map<string, symbol_struct> symbol_table;
extern unsigned int starting_address;
extern unsigned int program_length;
extern unsigned int LOCCTR;
//if base is negative then NOBASE
extern int base;
extern int address;
extern unsigned int current_line_number;
extern listing_line current_line;
extern bool errorInPass1;
void runPass1(string input);
void write_listing_file(string fileName);
void write_listing_file2(string fileName);
void build_listing_table(string path);
bool handleDirective(listing_line x);
bool isDirective(string x);
bool isRelocatable(string exp);
bool isAbsluteExp(string exp);
bool handleBasePass2(unsigned int lineNumber);
string byteObCode(unsigned int lineNumber);
string wordObCode(unsigned int lineNumber);
#endif /* ASSEMBLERDATA_H_ */
| d5107531d93ed5ef1f1ae6a6b82518858fa44184 | [
"C++"
] | 7 | C++ | AmrGeneidy/sic-xe-assembler | 00c2ab5f481c68457c7a167d4d9b823536dbcd6e | 0a03a1f868dbba005795e38fc4a01618522f56cd | |
refs/heads/master | <repo_name>MairaCelestino/consultorio-api<file_sep>/src/main/java/com/celestino/consultorio/model/repository/PacienteRepository.java
package com.celestino.consultorio.model.repository;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.tomcat.util.digester.SetPropertiesRule;
import org.springframework.stereotype.Service;
import com.celestino.consultorio.model.Paciente;
//está classe representa uma chamada á base de dados
@Service
public class PacienteRepository {
private Integer nextPrimaryKey = 1;
// Lista de pacientes para retornar
private List<Paciente> pacientes;
// Método que retorna listagem de pacientes
public List<Paciente> findAll() {
return getPacientes();
}
// Retorna lista inicializada caso necessário
public List<Paciente> getPacientes() {
if (pacientes == null) {
pacientes = new ArrayList<Paciente>();
// Cria paciente usando contrutor
Paciente p1 = new Paciente(Long.valueOf(nextPrimaryKey.longValue()), "Maira", "<EMAIL>",
18);
nextPrimaryKey++;
// Cria objeto paciente usando os métodos setters
Paciente p2 = new Paciente();
p2.setId(Long.valueOf(nextPrimaryKey.longValue()));
p2.setNome("Anderson");
p2.setEmail("<EMAIL>");
p2.setIdade(24);
nextPrimaryKey++;
Paciente p3 = new Paciente();
p3.setId(Long.valueOf(nextPrimaryKey.longValue()));
p3.setNome("Bianca");
p3.setEmail("<EMAIL>");
p3.setIdade(30);
nextPrimaryKey++;
// Insere na lista
getPacientes().add(p1);
getPacientes().add(p2);
getPacientes().add(p3);
// Outra forma de popular uma lista
// return Arrays.asList(p1, p2, p3);
}
return pacientes;
}
// Buscar paciente pelo id
public Paciente findById(Long id) {
for (Paciente paciente : getPacientes()) {
if (paciente.getId().equals(id)) {
return paciente;
}
}
return null;
}
public Boolean deleteById(Long id) {
for (Paciente paciente : getPacientes()) {
if (paciente.getId().equals(id)) {
getPacientes().remove(paciente);
return true;
}
}
return false;
}
public Paciente insertPaciente(Paciente paciente) {
paciente.setId(Long.valueOf(nextPrimaryKey.longValue()));
getPacientes().add(paciente);
nextPrimaryKey++;
return paciente;
}
public Paciente updatePaciente(Paciente paciente) {
Paciente pacienteAtualizado = null;
for (Paciente p : getPacientes()) {
if (p.getId().equals(paciente.getId())) {
if (!p.getNome().equals(paciente.getNome())) {
p.setNome(paciente.getNome());
}
if (!p.getIdade().equals(paciente.getIdade())) {
p.setIdade(paciente.getIdade());
}
if (!p.getEmail().equals(paciente.getEmail())) {
p.setEmail(paciente.getEmail());
}
pacienteAtualizado = p;
}
}
return pacienteAtualizado;
}
}
<file_sep>/src/main/java/com/celestino/consultorio/controller/test/Test.java
package com.celestino.consultorio.controller.test;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class Test {
@GetMapping //EndPoint
public String test() {
return "A API REST ESTÁ FUNCIONANDO!";
}
}
| 3e9921736717704bd2bae308a5e784740912baf3 | [
"Java"
] | 2 | Java | MairaCelestino/consultorio-api | 08157de569af48837f7654b6192ae8e95b49b655 | ddc232e2ec2fedb52621da8c185a81dd10390e42 | |
refs/heads/master | <file_sep>loopNum=100
scaleNum=8
devID=1
#Test1
baseHA=32
baseHB=32
baseW=32
c=0 #compare, no need to compare
for((scale=1; scale < $scaleNum; scale++))
do
scaler=$((1))
for((cnt=0; cnt < scale; cnt ++))
do
scaler=$(($scaler*2))
done
hA=$(($baseHA*$scaler))
hB=$(($baseHB*$scaler))
W=$(($baseW*$scaler))
for((i=0; i < $loopNum; i++))
do
echo
echo "Test1 ======= ($i): devID=$devID, hA=$hA, hB=$hB, W=$W======="
echo "-------> No transpose"
./matrixMulCUBLAS -device=$devID -hA=$hA -hB=$hB -w=$W -transpose=0 -compare=0
./matrixMulCUBLAS -device=$devID -hA=$hA -hB=$hB -w=$W -transpose=0 -compare=0 >> test_devID_$devID\_hA_$hA\_hB_$hB\_W_$W\_transpose_0\.log
echo
echo "-------> Transpose"
./matrixMulCUBLAS -device=$devID -hA=$hA -hB=$hB -w=$W -transpose=1 -compare=0
./matrixMulCUBLAS -device=$devID -hA=$hA -hB=$hB -w=$W -transpose=1 -compare=0 >> test_devID_$devID\_hA_$hA\_hB_$hB\_W_$W\_transpose_1\.log
done
done
#Test2
baseHA=64
baseHB=64
baseW=8
c=0 #compare, no need to compare
for((scale=1; scale < $scaleNum; scale++))
do
scaler=$((1))
for((cnt=0; cnt < scale; cnt ++))
do
scaler=$(($scaler*2))
done
hA=$(($baseHA*$scaler))
hB=$(($baseHB*$scaler))
W=$(($baseW*$scaler))
for((i=0; i < $loopNum; i++))
do
echo
echo "Test2 ======= ($i): devID=$devID, hA=$hA, hB=$hB, W=$W======="
echo "-------> No transpose"
./matrixMulCUBLAS -device=$devID -hA=$hA -hB=$hB -w=$W -transpose=0 -compare=0
./matrixMulCUBLAS -device=$devID -hA=$hA -hB=$hB -w=$W -transpose=0 -compare=0 >> test_devID_$devID\_hA_$hA\_hB_$hB\_W_$W\_transpose_0\.log
echo
echo "-------> Transpose"
./matrixMulCUBLAS -device=$devID -hA=$hA -hB=$hB -w=$W -transpose=1 -compare=0
./matrixMulCUBLAS -device=$devID -hA=$hA -hB=$hB -w=$W -transpose=1 -compare=0 >> test_devID_$devID\_hA_$hA\_hB_$hB\_W_$W\_transpose_1\.log
done
done
<file_sep>#include <stdio.h>
#include <omp.h>
void transCPU(float* m, float *mt, int w, int h)
{
printf("Start CPU transpose...\n");
int size = w * h;
int numThreads = (size > omp_get_num_procs()) ? omp_get_num_procs() : size;
#pragma omp parallel for collapse(2)
for(int row = 0; row < h; row ++)
{
for(int col = 0; col < w; col ++)
{
mt[col*h + row] = m[row*w + col];
}
}
}
bool compare(float *a, float *b, int size)
{
for(int i = 0; i < size; i ++)
{
if(a[i] != b[i])
return false;
}
return true;
}
void setZeros(float *a, int size)
{
int numThreads = (size > omp_get_num_procs()) ? omp_get_num_procs() : size;
omp_set_num_threads(numThreads);
#pragma omp parallel
{
int id = omp_get_thread_num();
int nthrds = omp_get_num_threads();
for(int i = id; i < size; i = i + nthrds)
{
a[i] = 0.0;
}
}
}
double calDiff(float *a, float *b, int size)
{
int numThreads = (size > omp_get_num_procs()) ? omp_get_num_procs() : size;
double diffs[numThreads];
omp_set_num_threads(numThreads);
int nthreads;
#pragma omp parallel
{
int id = omp_get_thread_num();
int nthrds = omp_get_num_threads();
if( id == 0) nthreads = nthrds;
diffs[id] = 0.0;
for(int i = id; i < size; i = i + nthrds)
{
// double tmp = (double) (a[i] - b[i]);
// if(id == 0)
// printf("[%d from %d]: diff=%lf\n", id, nthrds, tmp);
diffs[id] += (double) (a[i] - b[i]);
}
}
double diff = 0.0;
for (int i = 0; i < nthreads; i++)
diff += diffs[i];
return diff;
}
void printMatrix(float *data, int w, int h)
{
int maxDim = 8;
int mw, mh;
if(w > maxDim)
{
mw = maxDim;
printf("Print first %d col...\n", maxDim);
}else
mw = w;
if(h > maxDim)
{
mh = maxDim;
printf("Print first %d row...\n", maxDim);
}else
mh = h;
for(int i = 0; i < mh; i ++)
{
for(int j = 0; j < mw; j++)
{
printf("%.1f\t", data[i*w + j]);
}
printf(";\n");
}
}
<file_sep>rm myTranspose.out
nvcc -lcublas -O2 -Xcompiler -fopenmp -o myTranspose.out myTranspose.cu
./myTranspose.out
<file_sep>rm marshlTest
nvcc -Xcompiler -fopenmp -o marshlTest marshalTest.cu
./marshlTest
<file_sep># CUDA_functions
To test our transpose, run ./c\&r.sh
To test transpose from libmarshal, run ./testMarshl.sh
libmarshal reference:
Code tested: https://bitbucket.org/ijsung/libmarshal/wiki/Home
Paper: http://dl.acm.org/citation.cfm?id=2555266
<file_sep>f = open('forCalAvg.txt')
line = f.readline()
name = []
throughput = []
duration = []
num = []
while line:
if line.split()[0] in name:
throughput[name.index(line.split()[0])] += float(line.split()[1])
duration[name.index(line.split()[0])] += float(line.split()[2])
num[name.index(line.split()[0])] += 1
else:
name.append(line.split()[0]);
throughput.append(float(line.split()[1]))
duration.append(float(line.split()[2]))
num.append(1);
line = f.readline()
f.close()
for i in range(0, len(name)):
throughput[i] = throughput[i] / num[i]
duration[i] = duration[i] / num[i]
print name[i] + ";" + str(throughput[i]) + ";" + str(duration[i])
<file_sep>devID=2
loopNum=20
scaleNum=7
# Test 0 fix
baseHA=128
baseHB=128
baseW=1024
c=0 #compare, no need to compare
for((scaleA=1; scaleA < $scaleNum; scaleA++))
do
scalerA=$((1))
for((cnt=0; cnt < scaleA; cnt ++))
do
scalerA=$(($scalerA*2))
done
hA=$(($baseHA*$scalerA))
for((scaleB=1; scaleB < $scaleNum; scaleB++))
do
scalerB=$((1))
for((cnt=0; cnt < scaleB; cnt ++))
do
scalerB=$(($scalerB*2))
done
hB=$(($baseHB*$scalerB))
for((scaleC=1; scaleC < $scaleNum; scaleC++))
do
scalerC=$((1))
for((cnt=0; cnt < scaleC; cnt ++))
do
scalerC=$(($scalerC*2))
done
W=$(($baseW*$scalerC))
for((i=0; i < $loopNum; i++))
do
echo
echo "Test0 ======= ($i): devID=$devID, hA=$hA, hB=$hB, W=$W======="
echo "-------> No transpose"
./matrixMulCUBLAS -device=$devID -hA=$hA -hB=$hB -w=$W -transpose=0 -compare=0
./matrixMulCUBLAS -device=$devID -hA=$hA -hB=$hB -w=$W -transpose=0 -compare=0 >> test_devID_$devID\_hA_$hA\_hB_$hB\_W_$W\_transpose_0\.log
echo
echo "-------> Transpose"
./matrixMulCUBLAS -device=$devID -hA=$hA -hB=$hB -w=$W -transpose=1 -compare=0
./matrixMulCUBLAS -device=$devID -hA=$hA -hB=$hB -w=$W -transpose=1 -compare=0 >> test_devID_$devID\_hA_$hA\_hB_$hB\_W_$W\_transpose_1\.log
done
done
done
done
| 20d844750a67fed9ff49dd7c924a7f93878c6279 | [
"Markdown",
"Python",
"C++",
"Shell"
] | 7 | Shell | FreemanX/CUDA_functions | 977d0b43ef183e27f15b23cb0f92f9b137850e02 | 41992eef26f977194aef7e48269d0965b107f630 | |
refs/heads/main | <file_sep>def day_trader(day_prices)
benefit_h = {}
day_prices.combination(2) { |c| benefit_h[ c[1] - c[0] ] = c }
buy_day = day_prices.index(benefit_h.max.flatten[1]) + 1
sell_day = day_prices.index(benefit_h.max.flatten[2]) + 1
"<NAME>! Vous avez intéret à acheter le jour #{buy_day} et à vendre le jour #{sell_day}!"
end<file_sep>def cipher_one_letter(letter, key)
univ_key = key.remainder(26)
if letter =~ /[A-Z]/
(letter.ord + univ_key) > 90 ? (letter.ord + univ_key - 26).chr :
(letter.ord + univ_key) < 65 ? (letter.ord + univ_key + 26).chr : (letter.ord + univ_key).chr
elsif letter =~/[a-z]/
(letter.ord + univ_key) > 122 ? (letter.ord + univ_key - 26).chr :
(letter.ord + univ_key) < 97 ? (letter.ord + univ_key + 26).chr : (letter.ord + univ_key).chr
elsif letter.class != String
"Please give me a string!"
else
letter
end
end
def ceasar_cipher(string, key)
string.split("").map { |character| cipher_one_letter(character, key) }.join("")
end<file_sep>require_relative '../lib/ceasar_cipher'
describe 'the cipher_one_letter method' do
it 'ciphers a letter into another *key* rank later in the alphabet given the *key*' do
expect(cipher_one_letter('a',5)).to eq('f')
expect(cipher_one_letter('m',0)).to eq('m')
expect(cipher_one_letter('x',4)).to eq('b')
expect(cipher_one_letter('d',-1)).to eq('c')
expect(cipher_one_letter('d',-6)).to eq('x')
end
it 'Capitalized letters stay capitalized through ciphering' do
expect(cipher_one_letter('A',5)).to eq('F')
expect(cipher_one_letter('M',0)).to eq('M')
expect(cipher_one_letter('X',4)).to eq('B')
expect(cipher_one_letter('D',-1)).to eq('C')
expect(cipher_one_letter('D',-6)).to eq('X')
end
it 'leaves the ponctuation unchanged' do
expect(cipher_one_letter('!',0)).to eq('!')
expect(cipher_one_letter('!',4)).to eq('!')
expect(cipher_one_letter('.',-1)).to eq('.')
expect(cipher_one_letter(',',-6)).to eq(',')
end
it 'only takes strings as input' do
expect(cipher_one_letter(5,5)).to eq("Please give me a string!")
end
end
describe 'the ceasar_cipher method' do
it 'ciphers a string into another where each letter is mapped using the key argument. it keeps capitalization and punctuation' do
expect(ceasar_cipher("What a string!", 5)).to eq("Bmfy f xywnsl!")
end
it 'only takes strings as input' do
expect(cipher_one_letter(5,5)).to eq("Please give me a string!")
end
end<file_sep>require_relative '../lib/jean_michel_trader'
# faire toutes les combinaisons de soustractions possibles / selectionner la plus grande qui respecte jour achat avant jour vente / sortir les jours
describe 'the day_trader method' do
it 'takes an array of prices and returns the best days to buy and sell' do
expect(day_trader([17, 3, 6, 9, 15, 8, 6, 1, 10])).to eq("<NAME>! Vous avez intéret à acheter le jour 2 et à vendre le jour 5!")
expect(day_trader([29, 3, 1, 9, 6, 8, 6, 1, 2])).to eq("<NAME>! Vous avez intéret à acheter le jour 3 et à vendre le jour 4!")
expect(day_trader([2, 3, 6, 9, 15, 8, 28, 1, 10])).to eq("<NAME>! Vous avez intéret à acheter le jour 1 et à vendre le jour 7!")
end
end
<file_sep>def is_multiple_of_3_or_5?(current_number)
current_number % 3 == 0 || current_number % 5 == 0 ? true : false
end
def sum_of_3_or_5_multiples(final_number)
if final_number.class == Integer && final_number >= 0
(1...final_number).reduce(0) { |sum , num| is_multiple_of_3_or_5?(num) ? sum + num : sum }
else
'Yo ! Je ne prends que les entiers naturels. TG'
end
end<file_sep>def word_counter(string, dictionnary)
matching_h = {}
for i in (0...dictionnary.length)
matching_h[string.scan(/#{dictionnary[i]}/i).uniq.join.downcase] = string.scan(/#{dictionnary[i]}/i).size
end
matching_h.delete("")
matching_h
end<file_sep>dictionnary = ["the", "of", "and", "to", "a", "in", "for", "is", "on", "that", "by", "this", "with", "i", "you", "it", "not", "or", "be", "are"]
shakespeare_lifes_work = File.read("./lib/shakespeare.txt")
bad_words = File.read("./lib/bad_words.txt").split("\n")
def count_words(string, dictionnary)
matching_h = {}
for i in (0...dictionnary.length)
matching_h[string.scan(/#{dictionnary[i]}/i).map { |elt| elt.downcase }.uniq.join] = string.scan(/#{dictionnary[i]}/i).size
end
matching_h.delete("")
matching_h
end
puts count_words(shakespeare_lifes_work, bad_words)
puts count_words(shakespeare_lifes_work, dictionnary)<file_sep># projet_20_04
Some ruby exercices
| a20f39d6610482d40f611ba44d2491e2b2e5f818 | [
"Markdown",
"Ruby"
] | 8 | Ruby | Nicolasheckmann/projet_20_04 | c76b561051fe86f7078b2020e3d154ae8e00483e | 86ad2edafbdce7644570f1eff854e5511db9d20b | |
refs/heads/master | <file_sep>class TelegramResponder
def initialize(bot, database)
@bot = bot
@database = database
end
def filter_keyboard
types = ['C1-C4', 'Interlude', 'Epilogue', 'High five', 'Classic', I18n.t('other')]
types.delete('C1-C4') if @user.filter_chronicle.include?('c1')
types.delete('Interlude') if @user.filter_chronicle.include?('interlude')
types.delete('Epilogue') if @user.filter_chronicle.include?('epilogue')
types.delete('High five') if @user.filter_chronicle.include?('high five')
types.delete('Classic') if @user.filter_chronicle.include?('classic')
types.delete(I18n.t('other')) if @user.filter_chronicle.include?('freya')
pairs = []
types.each_with_index do |t, i|
if i.even? then
pairs << [t]
else
pairs.last << t
end
end
pairs << Telegram::Bot::Types::KeyboardButton.new(text: I18n.t('enough'))
end
def respond_to(message)
@all = @database.exec("SELECT * from servers").values
@user = User.new(@database, message.from.id)
@user.chat_id = message.chat.id
I18n.locale = (@user.lang || :en).to_sym
case message
when Telegram::Bot::Types::CallbackQuery
respond_to_callback_query(message)
when Telegram::Bot::Types::Message
respond_to_text(message)
end
end
private
def respond_to_text(message)
case message.text
when '/start'
if @user.lang then
help(message)
else
ask_lang(message)
end
when '/lang'
ask_lang(message)
when '/help'
help(message)
when '/soon'
send_servers soon(@all, 14), message
add_help_to_end(message)
when '/recent'
send_servers recent(@all, 14), message
add_help_to_end(message)
when '/info'
info(message)
add_help_to_end(message)
when '/filter'
clear_filter
ask_filter_chronicle(message)
when '/lowrate'
send_servers(from_to(apply_rates_filter(@all, 0, 20), -21, 30), message)
add_help_to_end(message)
when '/multicraft'
send_servers(from_to(apply_rates_filter(@all, 20, 200), -21, 30), message)
add_help_to_end(message)
when '/pvprate'
send_servers(from_to(apply_rates_filter(@all, 200, 99999999), -21, 30), message)
add_help_to_end(message)
when '/notify'
clear_filter
ask_filter_chronicle(message)
when 'C1-C4'
@user.filter_chronicle = @user.filter_chronicle + ['c1', 'c2', 'c3', 'c4']
send_chronicle_filter(message)
ask_filter_chronicle(message)
when 'Interlude'
@user.filter_chronicle = @user.filter_chronicle + ['interlude', 'interlude+']
send_chronicle_filter(message)
ask_filter_chronicle(message)
when 'High five'
@user.filter_chronicle = @user.filter_chronicle + ['high five']
send_chronicle_filter(message)
ask_filter_chronicle(message)
when 'Epilogue'
@user.filter_chronicle = @user.filter_chronicle + ['epilogue']
send_chronicle_filter(message)
ask_filter_chronicle(message)
when 'Classic'
@user.filter_chronicle = @user.filter_chronicle + ['classic']
send_chronicle_filter(message)
ask_filter_chronicle(message)
when I18n.t('.other')
@user.filter_chronicle = @user.filter_chronicle + ['final', 'lindvior', 'freya', 'ertheria', 'odyssey']
send_chronicle_filter(message)
ask_filter_chronicle(message)
when I18n.t('enough')
ask_filter_rates(message)
when 'Low-Rate'
@user.filter_rates_from = 0
@user.filter_rates_to = 15
ask_for_notifies(message)
when 'Multi-Craft'
@user.filter_rates_from = 15
@user.filter_rates_to = 250
ask_for_notifies(message)
when 'PVP-Rate'
@user.filter_rates_from = 250
@user.filter_rates_to = 99999999
ask_for_notifies(message)
when 'RU'
@user.lang = 'ru'
I18n.locale = :ru
add_help_to_end(message)
when 'ENG'
@user.lang = 'en'
I18n.locale = :en
add_help_to_end(message)
when '/reset'
@user.last_notified = Time.now.iso8601
filter(message)
@user.notify_period = nil
when I18n.t('notify_everyday')
@user.last_notified = Time.now.iso8601
filter(message)
@user.notify_period = 1
when I18n.t('notify_everyweek')
@user.last_notified = Time.now.iso8601
filter(message)
@user.notify_period = 7
when I18n.t('notify_everymonth')
@user.last_notified = Time.now.iso8601
filter(message)
@user.notify_period = 30
else
@bot.api.send_message(chat_id: message.chat.id, text: message.text)
end
end
def respond_to_callback_query(message)
# case message.data
# end
end
def send_servers(servers, message)
servers.each do |s|
day_diff = date_diff(Time.now, s[3])
day_part = if (day_diff > 0) then
I18n.t('opens_in_x_days', x: day_diff)
elsif (day_diff < 0) then
I18n.t('opened_x_days_ago', x: -day_diff)
else
I18n.t('opens_today')
end
text = "#{s[0]}\n#{s[1]} x#{s[2]}\n#{s[3]} #{day_part}"
@bot.api.send_message(chat_id: message.chat.id, text: text)
end
end
def ask_lang(message)
kb = [
[Telegram::Bot::Types::KeyboardButton.new(text: 'RU'),
Telegram::Bot::Types::KeyboardButton.new(text: 'ENG')]
]
markup = Telegram::Bot::Types::ReplyKeyboardMarkup.new(keyboard: kb, one_time_keyboard: true)
@bot.api.send_message(chat_id: message.chat.id, text: "LANGUAGE", reply_markup: markup)
end
def ask_filter_chronicle(message)
markup = Telegram::Bot::Types::ReplyKeyboardMarkup.new(keyboard: filter_keyboard, one_time_keyboard: true)
@bot.api.send_message(chat_id: message.chat.id, text: I18n.t('select_chronicle'), reply_markup: markup)
end
def ask_filter_rates(message)
kb = [
Telegram::Bot::Types::KeyboardButton.new(text: 'Low-Rate'),
Telegram::Bot::Types::KeyboardButton.new(text: 'Multi-Craft'),
Telegram::Bot::Types::KeyboardButton.new(text: 'PVP-Rate'),
]
markup = Telegram::Bot::Types::ReplyKeyboardMarkup.new(keyboard: kb, one_time_keyboard: true)
@bot.api.send_message(chat_id: message.chat.id, text: I18n.t('choose_rates'), reply_markup: markup)
end
def ask_for_notifies(message)
kb = [
Telegram::Bot::Types::KeyboardButton.new(text: I18n.t('notify_everyday')),
Telegram::Bot::Types::KeyboardButton.new(text: I18n.t('notify_everyweek')),
Telegram::Bot::Types::KeyboardButton.new(text: I18n.t('notify_everymonth')),
]
markup = Telegram::Bot::Types::ReplyKeyboardMarkup.new(keyboard: kb, one_time_keyboard: true)
@bot.api.send_message(chat_id: message.chat.id, text: I18n.t('should_we_notify'), reply_markup: markup)
end
def send_chronicle_filter(message)
@bot.api.send_message(chat_id: message.chat.id, text: I18n.t('selected_chronicles', x: @user.filter_chronicle.join(", ")))
end
def help(message)
@bot.api.send_message(chat_id: message.chat.id, text: "#{I18n.t('command_list')}\n/soon\n/recent\n/lowrate\n/multicraft\n/pvprate\n/notify\n/help")
end
def info(message)
@bot.api.send_message(chat_id: message.chat.id, text: "#{I18n.t('total_servers')} #{@all.length}")
end
def add_help_to_end(message)
@bot.api.send_message(chat_id: message.chat.id, text: I18n.t('need_help'))
end
def soon(servers, days)
servers.select do |server|
date_diff(Time.now, server[3]) > 0 && date_diff(Time.now, server[3]) <= days
end.sort do |s1, s2|
date_diff(Time.now, s2[3]) <=> date_diff(Time.now, s1[3])
end
end
def recent(servers, days)
servers.select do |server|
date_diff(Time.now, server[3]) < 0 && date_diff(Time.now, server[3]) >= -days
end.sort do |s1, s2|
date_diff(Time.now, s1[3]) <=> date_diff(Time.now, s2[3])
end
end
def from_to(servers, from, to)
servers.select do |server|
date_diff(Time.now, server[3]) >= from && date_diff(Time.now, server[3]) <= to
end.sort do |s1, s2|
date_diff(Time.now, s1[3]) <=> date_diff(Time.now, s2[3])
end
end
def apply_chonicle_filter(servers, chronicles)
servers.select do |server|
chronicles.include? server[1]
end
end
def apply_rates_filter(servers, from, to)
servers.select do |server|
server[2].to_i >= from.to_i && server[2].to_i <= to.to_i
end
end
def clear_filter
@user.filter_chronicle = []
end
def filter(message)
send_servers(
from_to(
apply_chonicle_filter(
apply_rates_filter(
@all,
@user.filter_rates_from,
@user.filter_rates_to
),
@user.filter_chronicle
),
-14,
14
),
message
)
add_help_to_end(message)
end
def date_diff(*dates)
days = 0
dates.each_with_index do |date, i|
if date.is_a? Time then
d = date.day + date.month*30 + date.year*365
else
parsed = date.split('.').map! { |x| x.to_i }
d = parsed[0] + parsed[1]*30 + (parsed[2]+2000)*365
end
days += (i.even? ? -d : d)
end
days
end
end
<file_sep>#!/usr/bin/env ruby
require 'telegram/bot'
require 'pg'
require 'json'
require 'time'
require_relative '../app/telegram-responder'
# Models
require_relative '../models/user'
# I18n
require 'i18n'
I18n.load_path = ["#{__dir__}/../locale/en.yml", "#{__dir__}/../locale/ru.yml"]
token = ENV["L2WATCHBOT_TOKEN"]
database = PG.connect( dbname: "l2watchbot", user: "postgres", password: "<PASSWORD>" )
def date_diff(*dates)
days = 0
dates.each_with_index do |date, i|
if date.is_a? Time then
d = date.day + date.month*30 + date.year*365
else
parsed = date.split('.').map! { |x| x.to_i }
d = parsed[0] + parsed[1]*30 + (parsed[2]+2000)*365
end
days += (i.even? ? -d : d)
end
days
end
def send_servers(api, servers, user)
servers.each do |s|
day_diff = date_diff(Time.now, s[3])
day_part = if (day_diff > 0) then
I18n.t('opens_in_x_days', x: day_diff)
elsif (day_diff < 0) then
I18n.t('opened_x_days_ago', x: -day_diff)
else
I18n.t('opens_today')
end
text = "#{s[0]}\n#{s[1]} x#{s[2]}\n#{s[3]} #{day_part}"
api.send_message(chat_id: user[9], text: text)
end
end
def from_to(servers, from, to)
servers.select do |server|
date_diff(Time.now, server[3]) >= from && date_diff(Time.now, server[3]) <= to
end.sort do |s1, s2|
date_diff(Time.now, s1[3]) <=> date_diff(Time.now, s2[3])
end
end
def apply_chonicle_filter(servers, chronicles)
servers.select do |server|
chronicles.include? server[1]
end
end
def apply_rates_filter(servers, from, to)
servers.select do |server|
server[2].to_i >= from.to_i && server[2].to_i <= to.to_i
end
end
def add_help_to_end(api, user)
api.send_message(chat_id: user[9], text: I18n.t('need_help'))
end
def filter(api, servers, user)
send_servers(
api,
from_to(
apply_chonicle_filter(
apply_rates_filter(
servers,
user[4],
user[5]
),
JSON.parse(user[3])
),
-14,
14
),
user
)
api.send_message(chat_id: user[9], text: I18n.t('your_feed'))
add_help_to_end(api, user)
end
SECONDS_IN_MIN = 60
MIN_IN_HOUR = 60
SECONDS_IN_HOUR = SECONDS_IN_MIN * MIN_IN_HOUR
logger = Logger.new("#{__dir__}/../log/notifier.log", 'daily')
loop do
begin
api = Telegram::Bot::Api.new(token)
servers = database.exec("SELECT * from servers").values
users = database.exec("SELECT * from users").values
users.each do |user|
if (user[7].nil? && !user[8].nil?) || date_diff(Time.parse(user[7]), Time.now) >= user[8].to_i then
filter(api, servers, user)
database.exec "UPDATE users SET last_notified = $1 WHERE user_id = $2;", [Time.now.to_s, user[0]]
end
end
p users
rescue Exception => e
logger.fatal e
logger.fatal e.backtrace
end
sleep(SECONDS_IN_HOUR * 1)
end
<file_sep>source "https://rubygems.org"
# bot and crawler
gem 'telegram-bot-ruby'
gem 'mechanize'
gem 'i18n'
gem 'mail'
# database
gem 'pg'
gem 'json'
# fancy stuff
gem 'logger'
gem 'pry'
gem 'awesome_print'
<file_sep>#!/usr/bin/env ruby
require 'logger'
require_relative '../app/crawler'
SECONDS_IN_MIN = 60
MIN_IN_HOUR = 60
SECONDS_IN_HOUR = SECONDS_IN_MIN * MIN_IN_HOUR
logger = Logger.new("#{__dir__}/../log/crawler.log", 'daily')
loop do
begin
Crawler.new(logger: logger).run
rescue Exception => e
logger.fatal e
logger.fatal e.backtrace
end
sleep(SECONDS_IN_HOUR * 3)
end
<file_sep>require 'json'
class User
attr_reader :user_id, :filter_from, :filter_to, :filter_rates_from, :filter_rates_to, :lang, :last_notified, :notify_period, :chat_id
def initialize(db, id)
@db = db
values = @db.exec("SELECT * from users WHERE user_id = $1", [id.to_s]).values[0]
@user_id = values[0].to_s
@filter_from = values[1].to_s
@filter_to = values[2].to_s
@filter_chronicle = values[3].to_s
@filter_rates_from = values[4].to_s
@filter_rates_to = values[5].to_s
@lang = values[6]
@last_notified = values[7].to_s
@notify_period = values[8].to_i
@chat_id = values[9].to_s
puts values
end
def filter_from=(val)
@db.exec "UPDATE users SET filter_from = $1 WHERE user_id = $2;", [val.to_s, @user_id.to_s]
@filter_from = val
end
def filter_to=(val)
@db.exec "UPDATE users SET filter_to = $1 WHERE user_id = $2;", [val.to_s, @user_id.to_s]
@filter_to = val
end
def filter_chronicle
@filter_chronicle.empty? ? [] : JSON.parse(@filter_chronicle)
end
def filter_chronicle=(val)
val = val.uniq.to_json
@db.exec "UPDATE users SET filter_chronicle = $1 WHERE user_id = $2;", [val.to_s, @user_id.to_s]
@filter_chronicle = val
end
def filter_rates_from=(val)
@db.exec "UPDATE users SET filter_rates_from = $1 WHERE user_id = $2;", [val.to_s, @user_id.to_s]
@filter_rates_from = val
end
def filter_rates_to=(val)
@db.exec "UPDATE users SET filter_rates_to = $1 WHERE user_id = $2;", [val.to_s, @user_id.to_s]
@filter_rates_to = val
end
def lang=(val)
@db.exec "UPDATE users SET lang = $1 WHERE user_id = $2;", [val.to_s, @user_id.to_s]
@lang = val
end
def last_notified=(val)
@db.exec "UPDATE users SET last_notified = $1 WHERE user_id = $2;", [val.to_s, @user_id.to_s]
@last_notified = val
end
def notify_period=(val)
@db.exec "UPDATE users SET notify_period = $1 WHERE user_id = $2;", [val.to_i, @user_id.to_s]
@notify_period = val.to_i
end
def chat_id=(val)
@db.exec "UPDATE users SET chat_id = $1 WHERE user_id = $2;", [val.to_s, @user_id.to_s]
@chat_id = val.to_i
end
end
<file_sep>#!/usr/bin/env ruby
require 'pg'
Dir.mkdir("#{__dir__}/../log") rescue puts 'Folder "log" already exists.'
database = PG.connect( dbname: "l2watchbot", user: "postgres", password: "<PASSWORD>" )
begin
database.exec <<-SQL
create table servers (
title text,
chronicles text,
rates int,
date text,
created_at text,
CONSTRAINT uniq UNIQUE(title, chronicles, rates, date)
);
SQL
rescue Exception => e
puts e
end
begin
database.exec <<-SQL
create table results (
date text,
total_servers int
)
SQL
rescue Exception => e
puts e
end
begin
database.exec <<-SQL
create table users (
user_id text,
filter_from int,
filter_to int,
filter_chronicle text,
filter_rates_from int,
filter_rates_to int,
CONSTRAINT uniq2 UNIQUE(user_id)
)
SQL
rescue Exception => e
puts e
end
begin
database.exec <<-SQL
ALTER TABLE users ADD COLUMN lang varchar(30);
SQL
rescue Exception => e
puts e
end
begin
database.exec <<-SQL
ALTER TABLE users ADD COLUMN last_notified text;
ALTER TABLE users ADD COLUMN notify_period int;
SQL
rescue Exception => e
puts e
end
begin
database.exec <<-SQL
ALTER TABLE users ADD COLUMN chat_id text;
SQL
rescue Exception => e
puts e
end
<file_sep>#!/usr/bin/env ruby
require 'telegram/bot'
require 'pg'
require_relative '../app/telegram-responder'
# Models
require_relative '../models/user'
# I18n
require 'i18n'
I18n.load_path = ["#{__dir__}/../locale/en.yml", "#{__dir__}/../locale/ru.yml"]
I18n.enforce_available_locales = true
I18n.default_locale = :en
token = ENV["L2WATCHBOT_TOKEN"]
database = PG.connect( dbname: "l2watchbot", user: "postgres", password: "<PASSWORD>" )
logger = Logger.new("#{__dir__}/../log/bot.log", 'daily')
Telegram::Bot::Client.run(token) do |bot|
responder = TelegramResponder.new(bot, database)
bot.listen do |message|
begin
database.exec "INSERT INTO users (user_id, chat_id) values ($1, $2)", [message.from.id.to_s, message.chat.id] rescue nil
responder.respond_to message
rescue Exception => e
logger.fatal e
logger.fatal e.backtrace
end
end
end
<file_sep>require 'mechanize'
require 'pg'
require 'logger'
require 'mail'
require 'awesome_print'
require 'pry'
class Crawler
SOURCE_WEBSITE = "http://l2tops.ru/"
def initialize(logger:)
@logger = logger
@database = PG.connect( dbname: "l2watchbot", user: "postgres", password: "<PASSWORD>" )
@agent = Mechanize.new
end
def run
connect
extract_nodes_from_page.each do |sever_node|
begin
@database.exec(
"insert into servers (title, chronicles, rates, date, created_at) values ($1, $2, $3, $4, $5)",
extract_data_from_node(sever_node)
)
rescue Exception => e
@logger.warn "#{e} for page:\n #{sever_node}"
end
end
save_results
end
private
def connect
@page = @agent.get(SOURCE_WEBSITE)
end
def extract_nodes_from_page
@page.search('.server')
end
def extract_data_from_node(node)
title = node.at('.name').text
chronicles = node.at('.chronicle').text
rates = node.at('.rates').text[1..-1].to_i
date = node.at('.date').text
[title, chronicles, rates, date, Time.now.iso8601]
end
def save_results
server_count = @database.exec("select COUNT(*) from servers").values.first.first.to_i
begin
@database.exec(
"insert into results (date, total_servers) values ($1, $2)",
[Time.now.iso8601, server_count]
)
@logger.info "Total servers: #{server_count}"
send_warn_email(server_count)
rescue Exception => e
@logger.error "When saving results: #{e}"
end
end
def send_warn_email(server_count)
return if server_count > 50 # meh
mail = Mail.new do
from '<EMAIL>'
to '<EMAIL>'
subject 'L2Watchbot Crawler warning!'
body "While scanning #{SOURCE_WEBSITE} at #{Time.now.to_s} found only #{server_count} servers."
end
mail.delivery_method :smtp, {openssl_verify_mode: "none"}
mail.deliver!
@logger.warn mail.to_s
end
end
| 4966365e4d9d6cb7971a00406079bcd78f37acee | [
"Ruby"
] | 8 | Ruby | iSarCasm/l2watchbot-telegram | 0551b9319edaddfe8c388e40767ef31337c0eca0 | ebf241ba665a4a9c7131934fbab42cd8292f1a87 | |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
"""
Created on Sat Mar 21 12:40:13 2020
@author: vw178e
"""
import pandas as pd
#import matplotlib.pyplot as plt
fraud_data = pd.read_csv("C:/Training/Analytics/Decison_Tree/Fraud_check/Fraud_check.csv")
fraud_data_ori = fraud_data
fraud_data.head()
decriptive=fraud_data.describe()
import numpy as np
import seaborn as sns
# =============================================================================
# Data Manipulation
# =============================================================================
#dummy variables
fraud_dummies = pd.get_dummies(fraud_data[["Undergrad","Marital.StatMarital.Status","Urban"]])
fraud_dummies = fraud_dummies.drop(['Undergrad_NO','Marital.StatMarital.Status_Divorced','Urban_NO'],axis=1)
fraud_data = pd.concat([fraud_data,fraud_dummies],axis=1)
fraud_data=fraud_data.drop(['Undergrad','Marital.StatMarital.Status','Urban'],axis=1)
fraud_data['Risk_Factor'] = pd.cut(x=fraud_data['Taxable.Income'], bins=[1, 30000,100000], labels=['Good', 'Risky'], right=False)
fraud_data['Risk_Factor'].unique()
fraud_data.Risk_Factor.value_counts()
colnames = list(fraud_data.columns)
predictors = colnames[1:7]
target = colnames[7]
#Creating a seperate dataframe which has only continuoMarital.Status variables
fraud_data_conti = fraud_data[['Taxable.Income','City.Population','Work.Experience']].copy()
#Creating a seperate dataframe which has only categorical variables
#fraud_data_cat = fraud_data[['Undergrad_Good','Undergrad_Medium','Urban_Yes','Marital.Status_Yes']].copy()
fraud_data_cat = fraud_data_ori[['Undergrad','Marital.StatMarital.Status','Urban']].copy()
# =============================================================================
# Exploratory Data Analysis
# =============================================================================
###Exploratory Data Analysis for categorical variables
descriptive_cat = fraud_data_cat.describe()
#Looking at the different values of distinct categories in our variable.
fraud_data_cat['Undergrad'].unique()
fraud_data_cat['Urban'].unique()
fraud_data_cat['Marital.Status'].unique()
#No of unique categories
len(fraud_data_cat['Undergrad'].unique())
len(fraud_data_cat['Urban'].unique())
len(fraud_data_cat['Marital.Status'].unique())
#Counting no of unique categories without any missing values
fraud_data_cat['Undergrad'].nunique()
fraud_data_cat['Urban'].nunique()
fraud_data_cat['Marital.Status'].nunique()
# No of missing values
fraud_data_cat['Undergrad'].isnull().sum()
fraud_data_cat['Urban'].isnull().sum()
fraud_data_cat['Marital.Status'].isnull().sum()
##Count plot / Bar Plot
sns.countplot(data = fraud_data_cat, x = 'Undergrad')
sns.countplot(data = fraud_data_cat, x = 'Urban')
sns.countplot(data = fraud_data_cat, x = 'Marital.Status')
len(fraud_data_cat.columns)
#Exploratory data analysis for continoMarital.Status variables
###Exploratory Data Analysis for continoMarital.Status variables
descriptive_conti = fraud_data_conti.describe()
# Correlation matrix
fraud_data_conti.corr()
# getting boxplot of price with respect to each category of gears
heat1 = fraud_data_conti.corr()
sns.heatmap(heat1, xticklabels=fraud_data_conti.columns, yticklabels=fraud_data_conti.columns, annot=True)
# Scatter plot between the variables along with histograms
sns.pairplot(fraud_data_conti)
#==============================================================================
def norm_func(i):
x = (i-i.mean())/(i.std())
return (x)
# Normalized data frame (considering the numerical part of data)
df_norm = norm_func(fraud_data.iloc[:,0:])
# =============================================================================
#
# =============================================================================
# Splitting fraud_data into training and testing fraud_data set
# np.random.uniform(start,stop,size) will generate array of real numbers with size = size
#fraud_data['is_train'] = np.random.uniform(0, 1, len(fraud_data))<= 0.75
#fraud_data['is_train']
#train,test = fraud_data[fraud_data['is_train'] == True],fraud_data[fraud_data['is_train']==False]
from sklearn.model_selection import train_test_split
train,test = train_test_split(fraud_data,test_size = 0.2)
#from sklearn.tree import DecisionTreeClassifier
#help(DecisionTreeClassifier)
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_jobs=4,oob_score=True,n_estimators=100,criterion="entropy")
help(RandomForestClassifier)
model.fit(train[predictors],train[target])
model = model.fit(train[predictors],train[target])
#Training fraud_data
train_preds = model.predict(train[predictors])
pd.Series(train_preds).value_counts()
pd.crosstab(train[target],train_preds)
# Accuracy = train
np.mean(train.Risk_Factor == model.predict(train[predictors]))
#Testing fraud_data
preds = model.predict(test[predictors])
pd.Series(preds).value_counts()
pd.crosstab(test[target],preds)
# Accuracy = Test
np.mean(preds==test.Risk_Factor)
# =============================================================================
# from sklearn import tree
# #tree.plot_tree(model1.fit(iris.fraud_data, iris.target))
#
# clf = tree.DecisionTreeClassifier(random_state=0)
# clf = clf.fit(train[predictors], train[target])
# tree.plot_tree(clf)
#
# =============================================================================
#clMarital.Statuster_labels=preds
#iris_train = train
#iris_train['clMarital.Statust']=clMarital.Statuster_labels # creating a new column and assigning it to new column
#iris_train = iris_train.iloc[:,[5,0,1,2,3,4]]
#iris_train.head()
#
#clMarital.Statuster_labels=preds
#iris_test = test
#iris_test['Predicted Species']=clMarital.Statuster_labels # creating a new column and assigning it to new column
##iris_test = iris_test.iloc[:,[5,0,1,2,3,4]]
#iris_test.head()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sat Mar 21 12:40:13 2020
@author: vw178e
"""
import pandas as pd
#import matplotlib.pyplot as plt
company_data = pd.read_csv("C:/Training/Analytics/Decison_Tree/Company_data/Company_data.csv")
company_data_ori = company_data
company_data.head()
decriptive=company_data.describe()
import numpy as np
import seaborn as sns
# =============================================================================
# Data Manipulation
# =============================================================================
#dummy variables
company_dummies = pd.get_dummies(company_data[["ShelveLoc","Urban","US"]])
company_data = pd.concat([company_data,company_dummies],axis=1)
company_data = company_data.drop(['ShelveLoc','Urban','US','ShelveLoc_Bad','Urban_No','US_No'],axis=1)
#Creating a seperate dataframe which has only continuous variables
company_data_conti = company_data[['Sales','CompPrice','Income','Advertising','Population','Price','Age','Education']].copy()
#Creating a seperate dataframe which has only categorical variables
#company_data_cat = company_data[['ShelveLoc_Good','ShelveLoc_Medium','Urban_Yes','US_Yes']].copy()
company_data_cat = company_data_ori[['ShelveLoc','Urban','US']].copy()
# =============================================================================
# Exploratory Data Analysis
# =============================================================================
###Exploratory Data Analysis for categorical variables
descriptive_cat = company_data_cat.describe()
#Looking at the different values of distinct categories in our variable.
company_data_cat['ShelveLoc'].unique()
company_data_cat['Urban'].unique()
company_data_cat['US'].unique()
#No of unique categories
len(company_data_cat['ShelveLoc'].unique())
len(company_data_cat['Urban'].unique())
len(company_data_cat['US'].unique())
#Counting no of unique categories without any missing values
company_data_cat['ShelveLoc'].nunique()
company_data_cat['Urban'].nunique()
company_data_cat['US'].nunique()
# No of missing values
company_data_cat['ShelveLoc'].isnull().sum()
company_data_cat['Urban'].isnull().sum()
company_data_cat['US'].isnull().sum()
##Count plot / Bar Plot
sns.countplot(data = company_data_cat, x = 'ShelveLoc')
sns.countplot(data = company_data_cat, x = 'Urban')
sns.countplot(data = company_data_cat, x = 'US')
len(company_data_cat.columns)
#Exploratory data analysis for continous variables
###Exploratory Data Analysis for continous variables
descriptive_conti = company_data_conti.describe()
# Correlation matrix
company_data_conti.corr()
# getting boxplot of price with respect to each category of gears
heat1 = company_data_conti.corr()
sns.heatmap(heat1, xticklabels=company_data_conti.columns, yticklabels=company_data_conti.columns, annot=True)
# Scatter plot between the variables along with histograms
sns.pairplot(company_data_conti)
#==============================================================================
def norm_func(i):
x = (i-i.mean())/(i.std())
return (x)
# Normalized data frame (considering the numerical part of data)
df_norm = norm_func(company_data.iloc[:,0:])
# =============================================================================
#
# =============================================================================
company_data['Sales_Category'] = pd.cut(x=company_data['Sales'], bins=[0,5,9,20], labels=['Low', 'Medium','High'], right=False)
company_data['Sales_Category'].unique()
company_data.Sales_Category.value_counts()
colnames = list(company_data.columns)
predictors = colnames[1:12]
target = colnames[12]
# Splitting company_data into training and testing company_data set
# np.random.uniform(start,stop,size) will generate array of real numbers with size = size
#company_data['is_train'] = np.random.uniform(0, 1, len(company_data))<= 0.75
#company_data['is_train']
#train,test = company_data[company_data['is_train'] == True],company_data[company_data['is_train']==False]
from sklearn.model_selection import train_test_split
train,test = train_test_split(company_data,test_size = 0.2)
#from sklearn.tree import DecisionTreeClassifier
#help(DecisionTreeClassifier)
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_jobs=4,oob_score=True,n_estimators=100,criterion="entropy")
help(RandomForestClassifier)
model.fit(train[predictors],train[target])
model = model.fit(train[predictors],train[target])
#Training company_data
train_preds = model.predict(train[predictors])
pd.Series(train_preds).value_counts()
pd.crosstab(train[target],train_preds)
# Accuracy = train
np.mean(train.Sales_Category == model.predict(train[predictors]))
#Testing company_data
preds = model.predict(test[predictors])
pd.Series(preds).value_counts()
pd.crosstab(test[target],preds)
# Accuracy = Test
np.mean(preds==test.Sales_Category)
# =============================================================================
# from sklearn import tree
# #tree.plot_tree(model1.fit(iris.company_data, iris.target))
#
# clf = tree.DecisionTreeClassifier(random_state=0)
# clf = clf.fit(train[predictors], train[target])
# tree.plot_tree(clf)
#
# =============================================================================
#cluster_labels=preds
#iris_train = train
#iris_train['clust']=cluster_labels # creating a new column and assigning it to new column
#iris_train = iris_train.iloc[:,[5,0,1,2,3,4]]
#iris_train.head()
#
#cluster_labels=preds
#iris_test = test
#iris_test['Predicted Species']=cluster_labels # creating a new column and assigning it to new column
##iris_test = iris_test.iloc[:,[5,0,1,2,3,4]]
#iris_test.head()
| 9065aaaa590a12d201b3941d29bb16803f92b121 | [
"Python"
] | 2 | Python | shantanudn/RandomForest_Ensemble | af18faafbd52744b859f789bc0935e2ea07ff4b5 | c46a6a7e08ea7a1b0c4792d5cb4deb1bbd010675 | |
refs/heads/master | <file_sep>package hibernateDemo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import hibernate.demo.entity.Course;
import hibernate.demo.entity.Instructor;
import hibernate.demo.entity.InstructorDetail;
public class CreateInstructorDemo {
public static void main(String[] args) {
//create session factory
SessionFactory factory=new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Instructor.class)
.addAnnotatedClass(InstructorDetail.class)
.addAnnotatedClass(Course.class)
.buildSessionFactory();
//create session
Session session=factory.getCurrentSession();
try {
// create the objects
Instructor instructor=new Instructor("Kartik","Sareen","<EMAIL>");
InstructorDetail instructorDetail=new InstructorDetail("www.abc.com","Cricket");
//associate the objects
instructor.setInstructorDetail(instructorDetail);
//start a transaction
session.beginTransaction();
//save the instructor object
//Note : it will also save instructorDetails object because of cascadeType.all
session.save(instructor);
// commit transaction
session.getTransaction().commit();
}
finally {
session.close();
factory.close();
}
}
}
<file_sep>package spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration // for using java configuration(no XML)
@ComponentScan("spring") //package to scan for the components and create bean automatically
public class SportConfig {
}
<file_sep>foo.email=<EMAIL>
foo.team=XYZDFGHJ<file_sep>package hibernateDemo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import hibernate.demo.entity.Student;
public class UpdateStudentDemo {
public static void main(String[] args) {
//create session factory
SessionFactory factory=new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
//create session
Session session=factory.getCurrentSession();
try {
//start a transaction
session.beginTransaction();
Student student=session.get(Student.class, 1);
student.setEmail("<EMAIL>");
// commit transaction
session.getTransaction().commit();
session=factory.getCurrentSession();
session.beginTransaction();
session.createQuery("update Student set email='<EMAIL>'").executeUpdate();
session.getTransaction().commit();
}
finally {
factory.close();
}
}
}
<file_sep>package hibernateDemo;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import hibernate.demo.entity.Student;
public class PrimaryKeyDemo {
public static void main(String[] args) {
//create session factory
SessionFactory factory=new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
//create session
Session session=factory.getCurrentSession();
try {
//create 3 student objects
String theDateOfBirthStr = "31/12/1998";
Date theDateOfBirth = DateUtils.parseDate(theDateOfBirthStr);
Student student1=new Student("A","X","<EMAIL>",theDateOfBirth);
Student student2=new Student("B","Y","<EMAIL>",theDateOfBirth);
Student student3=new Student("C","Z","<EMAIL>",theDateOfBirth);
//start a transaction
session.beginTransaction();
//save the student object
session.save(student1);
session.save(student2);
session.save(student3);
// commit transaction
session.getTransaction().commit();
}
catch (Exception exc) {
exc.printStackTrace();
}
finally {
factory.close();
}
}
}
<file_sep>package aopdemo.dao;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import aopdemo.Account;
@Component
public class AccountDAO {
private String name;
private String serviceCode;
public List<Account> findAccounts(boolean tripWire){
if(tripWire) {
throw new RuntimeException("Runtime Exception");
}
List<Account> accs=new ArrayList<>();
//create sample accounts
Account a1=new Account("John","Silver");
Account a2=new Account("a","Platinum");
Account a3=new Account("b","Gold");
//add to list
accs.add(a1);
accs.add(a2);
accs.add(a3);
return accs;
}
public void addAccount(Account acc,boolean vipFlag) {
System.out.println(getClass()+ " :Doing my db work adding an account");
}
public boolean doWork() {
System.out.println(getClass()+ " :doWork() method");
return true;
}
public String getName() {
System.out.println(getClass()+ " :getName() method");
return name;
}
public void setName(String name) {
System.out.println(getClass()+ " :setName() method");
this.name = name;
}
public String getServiceCode() {
System.out.println(getClass()+ " :getServiceCode() method");
return serviceCode;
}
public void setServiceCode(String serviceCode) {
System.out.println(getClass()+ " :setServiceCode() method");
this.serviceCode = serviceCode;
}
}
<file_sep>package aopdemo.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import aopdemo.Account;
@Aspect
@Component
@Order(1)
public class MyDemoLoggingAspect {
@Before("aopdemo.aspect.AopPointcutExpressions.forDAOPackageNoGetterSetter()")
public void beforeAddAccountAdvice(JoinPoint joinPoint) {
System.out.println("\n>>>Executing @Before advice on methods");
//display the method Signature
MethodSignature methodSig=(MethodSignature) joinPoint.getSignature();
System.out.println("Method: "+methodSig);
//display the method arguments
Object[] args=joinPoint.getArgs();
for(Object arg:args) {
System.out.println(arg);
if(arg instanceof Account) {
//downcast and print AccountStuff
Account acc=(Account)arg;
System.out.println("Account name: "+acc.getName());
}
}
}
}
<file_sep>package springdemo;
import java.util.Random;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Component
public class FileFortuneService implements FortuneService {
private String filename="D:\\eclipse\\spring-demo-annotations\\src\\springdemo\\fortune-data.txt";
private List<String> theFortunes;
private Random myRandom=new Random();
public FileFortuneService() {
System.out.println("FileFortuneService: in constructor");
theFortunes=new ArrayList<String>();
}
@PostConstruct
public void doMyStartupStuff() {
System.out.println("In FileFortuneService method loadTheFortunesFile");
File file=new File(filename);
try (BufferedReader br=new BufferedReader(new FileReader(file))){
String line;
while((line=br.readLine())!=null) {
theFortunes.add(line);
}
}
catch(IOException e) {
e.printStackTrace();
}
}
@Override
public String getFortune() {
int index=myRandom.nextInt(theFortunes.size());
return theFortunes.get(index);
}
}
<file_sep>foo.email=<EMAIL>
foo.team=xyz<file_sep>package springdemo;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
//@Component("myCoach") setting explicit bean id="myCoach"
@Component //setting default bean id="tennisCoach" same name as the class but first letter lowercase
//@Scope("prototype")
public class TennisCoach implements Coach {
private FortuneService fortuneService;
@Autowired //constructor injection
public TennisCoach(@Qualifier("randomFortuneService")FortuneService fortuneService) {
System.out.println("In Tennis Coach Constructor");
this.fortuneService = fortuneService;
}
@PostConstruct
public void doMyStartupStuff() {
System.out.println("In Tennis Coach doMyStartupStuff function");
}
@Override
public String getDailyWorkout() {
return "Practice your backhand volley";
}
@Override
public String getDailyFortune() {
return fortuneService.getFortune();
}
@PreDestroy
public void doMyCleanupStuff() {
System.out.println("In Tennis Coach doMyCleanupStuff function");
}
}
<file_sep>package aopdemo.dao;
import org.springframework.stereotype.Component;
@Component
public class MembershipDAO {
public boolean addAccount() {
System.out.println(getClass()+ " :adding a membership account");
return true;
}
public boolean doWorkMember() {
System.out.println(getClass()+ " :doWorkMember() method");
return true;
}
}
<file_sep>package aopdemo;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import aopdemo.dao.AccountDAO;
import aopdemo.dao.MembershipDAO;
public class AfterReturningDemoApp {
public static void main(String[] args) {
//read the spring config java class
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(DemoConfig.class);
//get the bean from spring container
AccountDAO accountDAO=context.getBean("accountDAO",AccountDAO.class);
List<Account> accs=accountDAO.findAccounts(false);
System.out.println("\n\nMain Program:AfterReturningDemoApp");
System.out.println(accs);
//close the context
context.close();
}
}
| 701ef9d0f4d6fcc75be584337756bb468920c35b | [
"Java",
"INI"
] | 12 | Java | KartikSareen18/Java-Spring-Hibernate | 8ea129ef00de5b8c80fbc8668b2227849231fd87 | 5ad96cfc1515489854bf29acc69e94eeb01ce6b4 | |
refs/heads/master | <repo_name>YIRer/angular-portfolio<file_sep>/my-portfolio/src/app/portfolio/photo/new/new.component.ts
import { Component, OnInit } from '@angular/core';
import { Router,ActivatedRoute,Params } from '@angular/router';
import { FormGroup, FormControl, Validators} from '@angular/forms';
import { PhotoService } from '../photo.service';
import { Response } from '@angular/http';
import { DataService } from '../../../shared/data.service';
// import { PhotoBrick } from '../photo.model';
@Component({
selector: 'app-new',
templateUrl: './new.component.html',
styleUrls: ['./new.component.css']
})
export class NewComponent implements OnInit {
// photos:PhotoBrick[];
photoForm: FormGroup;
editMode =false;
editId : number;
comment = [];
photos : any;
constructor(
private route : ActivatedRoute,
private router : Router,
private photoService : PhotoService,
private dataService : DataService) { }
ngOnInit() {
this.route.params
.subscribe(
(params:Params)=>{
this.editId = params['id'];
this.editMode = params['id'] != null;
// console.log(this.editMode);
this.initForm()
}
)
}
private initForm(){
let title = '';
let auth = '';
let imgsrc = '';
let desc = '';
// console.log(this.photoService);
if(this.editMode){
const photo = this.photoService.getPhoto(this.editId);
title = photo.name;
auth = photo.auth;
imgsrc = photo.imgsrc;
desc = photo.description;
this.comment = photo.comment;
}
this.photoForm = new FormGroup({
'title': new FormControl(title, Validators.required),
'auth': new FormControl(auth, Validators.required),
'imgsrc': new FormControl(imgsrc, Validators.required),
'description': new FormControl(desc, Validators.required)
})
}
onSubmit(){
let photoId = this.photoService.PhotosIds;
if(!this.editMode){
photoId = photoId+1;
}
let pushValue = {
name:this.photoForm.value.title,
description:this.photoForm.value.description,
auth:this.photoForm.value.auth,
imgsrc:this.photoForm.value.imgsrc,
date : new Date(),
id : photoId,
comment:this.comment
};
if(this.editMode){
// console.log("edit!")
this.photoService.onUpdate(pushValue.id, pushValue);
this.photos = this.photoService.getPhotos()
this.dataService.updata();
}else{
this.photoService.addBrick(pushValue);
this.photos = this.photoService.getPhotos()
this.dataService.updata();
// this.dataService.storagePhotos();
// this.photoService.setPhotos(this.photos);
}
this.onCancle()
}
onCancle(){
this.router.navigate(['../'],{relativeTo:this.route});
}
updata(){
this.dataService.storagePhotos()
.subscribe((response:Response)=>{
// console.log(response);
})
}
}
<file_sep>/my-portfolio/src/app/main/contact/contact.component.ts
import { Component, OnInit} from '@angular/core';
declare var jQuery:any;
declare var $:any;
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
constructor() { }
ngOnInit() {
let addTooltip = $('address').length;
for(let i = 0 ; i < addTooltip; i++){
$('address').eq(i).tooltip({trigger:'hover'});
}
}
clickText(value){
let innerText = value;
$('#clip_target').val(innerText);
$('#clip_target').select();
try {
let successful = document.execCommand('copy');
}
catch (err) {
}
}
}
<file_sep>/my-portfolio/src/app/portfolio/photo/photo.model.ts
import { PhotoComment } from './photoComment/photocomment.model';
export class PhotoBrick {
public name:string;
public description:string;
public auth:string;
public imgsrc:string
public date : any;
public id : any
public comment : PhotoComment[];
constructor(name:string, desc:string, auth:string, imgsrc:string, date : any, id:any, comment:PhotoComment[]){
this.name = name;
this.description = desc;
this.auth = auth;
this.imgsrc = imgsrc;
this.date = date;
this.id = id;
this.comment = comment;
}
}
<file_sep>/my-portfolio/src/app/main/profile/show-profile/show-profile.component.ts
import {
Component,
OnInit,
HostListener,
OnDestroy
} from '@angular/core';
import {Http} from '@angular/http';
import * as firebase from 'firebase';
import { Subject } from 'rxjs/Subject';
declare var jQuery:any;
declare var $:any;
@Component({
selector: 'app-show-profile',
templateUrl: './show-profile.component.html',
styleUrls: ['./show-profile.component.css']
})
export class ShowProfileComponent implements OnInit, OnDestroy{
profile:string
data:any;
profileImg = new Subject<boolean>();
techImgSum = 0;
techImgLoaded = new Subject<boolean>();
endLoading = new Subject;
oneStep = false;
twoStep = false;
ngOnInit() {
// 로딩 체크
this.profileImg.subscribe((value:boolean)=>{
if(value === true){
this.oneStep = true;
this.endLoading.next();
}
});
this.techImgLoaded.subscribe((value:boolean)=>{
if(value === true){
this.twoStep = true;
this.endLoading.next();
}
});
// 로딩완료시 에니메이션 표시
this.endLoading.subscribe(()=>{
if(this.oneStep === true && this.twoStep ===true){
$('#loading').addClass("hide");
$("#profileMain").removeClass("hide");
$("#introduce").removeClass("hide");
$('#profileImg').addClass("animated fadeIn");
for(let i = 0; i < this.data.length; i++){
$('.techImg').eq(i).addClass("animated rotateIn")
}
}
})
}
// 로딩 완료 시 체크
profileLoad(){
$('#profileImg').removeClass("hide");
this.profileImg.next(true);
}
techLoad(){
this.techImgSum++;
if(this.techImgSum === this.data.length){
$('#tech').removeClass("hide");
for(let i = 0 ; i < this.techImgSum; i++){
$('.techImg').eq(i).tooltip({trigger:'hover'});
}
this.techImgLoaded.next(true);
}
}
constructor(
private http : Http) {
// 데이터 로드 및 도큐맨트 옵션사용
this.http.get('https://portfolio-project-768d9.firebaseio.com/logo.json')
.subscribe(data => this.data = data.json(),
err => console.log(err),
() =>{
const profile = firebase.storage().ref().child('KakaoTalk_20161008_165029271.jpg');
profile.getDownloadURL().then(url => this.profile = url);
for(let i = 0; i <this.data.length ; i++){
firebase.storage().ref().child("logo/"+this.data[i].name+".png")
.getDownloadURL().then(url => this.data[i].imgUrl = url);
}
});
}
// 스크롤 이벤트 체크
@HostListener("scroll", ['$event'])
// 스크롤시 발생할 이벤트
onWindowScroll($event) {
let number = $event.target.scrollTop;
let introduce = $('#introduce').offset().top;
if(number > introduce){
$('#introduce').removeClass('animated fadeOut');
$('#introduce').addClass('animated fadeIn');
}else{
$('#introduce').removeClass('animated fadeIn');
$('#introduce').addClass('animated fadeOut');
}
}
// 메모리 누수 방지
ngOnDestroy(){
this.profileImg.unsubscribe();
this.techImgLoaded.unsubscribe();
this.endLoading.unsubscribe()
}
}
<file_sep>/my-portfolio/src/app/main/main.component.ts
import { Component, OnInit, ViewChild, ElementRef} from '@angular/core';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {
isClassVisible = false;
@ViewChild('slide') slide:ElementRef
constructor() {
}
classChanged(name:string){
this.slide.nativeElement.className = 'animated bounceOutDown';
setTimeout(()=>{
this.isClassVisible = true;
},1000)
}
ngOnInit() {
this.isClassVisible = false;
}
}
<file_sep>/my-portfolio/src/app/portfolio/photo/detail/detail.component.ts
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { PhotoBrick } from '../photo.model';
import { PhotoService } from '../photo.service';
import { Response } from '@angular/http';
import { DataService } from '../../../shared/data.service';
@Component({
selector: 'app-detail',
templateUrl: './detail.component.html',
styleUrls: ['./detail.component.css']
})
export class DetailComponent implements OnInit {
photo:PhotoBrick;
id:any;
constructor(private route:ActivatedRoute,
private router:Router,
private photoService: PhotoService,
private dataService : DataService) { }
ngOnInit() {
this.route.params
.subscribe(
(params:Params)=>{
this.id = params['id']
if(this.photoService.onCheckId(this.id)){
this.photo = this.photoService.getPhoto(this.id);
}
}
)
}
onCancle(){
this.router.navigate(['portfolio/photo']);
}
onDelete(){
this.photoService.onDelete(this.id);
// this.photos = this.photoService.getPhotos()
this.dataService.updata();
this.router.navigate(['portfolio/photo']);
}
onEditPhoto(){
this.router.navigate(['edit'],{relativeTo:this.route});
}
updata(){
this.dataService.storagePhotos()
.subscribe((response:Response)=>{
})
}
}
<file_sep>/my-portfolio/src/app/portfolio/photo/photo-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PhotoComponent } from './photo.component';
import { NewComponent } from './new/new.component';
import { PhotoItemComponent } from './photoItem/photoItem.component';
import { DetailComponent } from './detail/detail.component';
const photoRoutes: Routes = [
{ path: '', component: PhotoComponent},
{ path: 'new', component: NewComponent},
{ path: ':id', component: DetailComponent },
{ path: ':id/edit', component: NewComponent}
];
@NgModule({
imports: [
RouterModule.forChild(photoRoutes)
],
exports: [RouterModule],
providers:[
]
})
export class PhotoRoutingModule {}
<file_sep>/my-portfolio/src/app/portfolio/photo/photoComment/photoComment.component.ts
import { Component, OnInit,Input } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
import { PhotoBrick } from '../photo.model';
import { PhotoService } from '../photo.service'
import { PhotoComment } from './photocomment.model'
import { Subject } from "rxjs/Subject";
import { Response } from '@angular/http';
import { DataService } from '../../../shared/data.service';
import {
trigger,
state,
style,
transition,
animate,
keyframes,
group
} from '@angular/animations';
declare var $;
@Component({
selector: 'app-photo-comment',
templateUrl: './photoComment.component.html',
styleUrls: ['./photoComment.component.css'],
animations: [
trigger('list1', [
state('in', style({
opacity: 1,
transform: 'translateX(0)'
})),
transition('void => *', [
style({
opacity: 0,
transform: 'translateX(-100px)'
}),
animate(300)
]),
transition('* => void', [
animate(300, style({
transform: 'translateX(100px)',
opacity: 0
}))
])
])
]
})
export class PhotoCommentComponent implements OnInit {
@Input() photo : PhotoBrick;
commentForm:FormGroup;
constructor(
private photoService : PhotoService,
private dataService : DataService) {}
ngOnInit() {
this.cForm();
}
private cForm(){
let auth ='';
let comment ='';
this.commentForm = new FormGroup({
auth: new FormControl(auth, Validators.required),
comment: new FormControl(comment, Validators.required),
})
}
onAddComment(){
let date= new Date();
let pushValue = new PhotoComment(
this.commentForm.controls.auth.value,
this.commentForm.controls.comment.value,
date
)
this.photo.comment.push(pushValue);
this.photoService.onUpdate(this.photo.id, this.photo);
this.photoService.getPhotos()
this.dataService.updata();
this.commentForm.reset();
}
onClear(){
this.commentForm.reset();
}
deleteComment(i:number){
let dd =[];
for(let j = 0; j < this.photo.comment.length; j++){
if(j != i){
dd.push(this.photo.comment[j]);
}
}
this.photo.comment = dd;
this.photoService.onUpdate(this.photo.id, this.photo);
this.photoService.getPhotos()
this.dataService.updata();
}
commnetCtrl(comment:any, index:number){
let selecComment = $('.comment').eq(index);
let showTa = $('.editComment').eq(index);
let changeValue = showTa[0].value;
selecComment.toggleClass("hide");
showTa.toggleClass("hide");
showTa.toggleClass("pulse");
if(showTa.hasClass("hide")){
if(changeValue.length >0){
comment.comment = changeValue;
this.photo.comment[index] = comment;
this.photoService.onUpdate(this.photo.id, this.photo);
this.photoService.getPhotos()
this.dataService.updata();
}
}else{
showTa[0].value = comment.comment;
setTimeout(()=>{
showTa.focus();
},100)
$(showTa).tooltip({trigger:"focus"});
}
}
}
<file_sep>/my-portfolio/src/app/portfolio/photo/photoItem/photoItem.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { PhotoBrick } from '../photo.model';
import { Subject } from 'rxjs/Subject';
import { PhotoService } from '../photo.service';
declare var jQuery:any;
declare var $:any;
@Component({
selector: 'app-photoItem',
templateUrl: './photoItem.component.html',
styleUrls: ['./photoItem.component.css']
})
export class PhotoItemComponent implements OnInit {
@Input() photo:any;
@Input() index:number;
@Input() photoId:any;
constructor(private photoService: PhotoService){}
ngOnInit() {}
imageLoad(){
this.photoService.itemLoaded.next(true);
setTimeout(()=>{
$('.card').eq(this.index).addClass("animated fadeIn");
},500);
}
}
<file_sep>/my-portfolio/src/app/shared/data.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { PhotoService } from '../portfolio/photo/photo.service';
import { PhotoBrick } from '../portfolio/photo/photo.model';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class DataService{
constructor(private http : Http, private photoService : PhotoService){}
storagePhotos(){
return this.http.put('https://portfolio-project-768d9.firebaseio.com/photos.json'
, this.photoService.getPhotos());
}
getPhotos(){
setTimeout(()=>{
this.http.get('https://portfolio-project-768d9.firebaseio.com/photos.json')
.map(
(response:Response)=>{
const photos: PhotoBrick[] = response.json();
let aa =[];
if(photos != null){
for (let i =0 ;i< photos.length; i++){
if(!photos[i].comment){
photos[i].comment = [];
}
let ss = new PhotoBrick(
photos[i].name,
photos[i].description,
photos[i].auth,
photos[i].imgsrc,
photos[i].date,
photos[i].id,
photos[i].comment
)
aa.push(ss);
}
}
return aa;
}
)
.subscribe((photos:PhotoBrick[])=>{
this.photoService.setPhotos(photos);
});
},1000)
}
updata(){
this.storagePhotos()
.subscribe((response:Response)=>{
})
}
}
<file_sep>/my-portfolio/src/app/portfolio/photo/photo.component.ts
import { Component, OnInit, OnDestroy} from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import { PhotoBrick } from './photo.model';
import { PhotoService} from './photo.service';
import { Subscription} from 'rxjs/Subscription';
import { Response } from '@angular/http';
import { DataService } from '../../shared/data.service';
import {Observable} from 'rxjs/Observable';
declare var jQuery:any;
declare var $:any;
@Component({
selector: 'app-photo',
templateUrl: './photo.component.html',
styleUrls: ['./photo.component.css']
})
export class PhotoComponent implements OnInit, OnDestroy {
photos : any;
checkLength : number = 0;
subscription : Subscription;
imageLoaded :Subscription;
imageCheck = 0;
constructor(private photoService : PhotoService,
private router: Router,
private route: ActivatedRoute,
private dataService : DataService) { }
ngOnInit() {
this.subscription = this.photoService.photoListChanged
.subscribe((photos:PhotoBrick[])=>{
this.photos = photos;
this.checkLength = this.photos.length;
})
this.imageLoaded = this.photoService.itemLoaded
.subscribe((value:boolean)=>{
if(value === true){
this.imageCheck++
if(this.imageCheck === this.photos.length){
setTimeout(()=>{
$('#loading').addClass("hide");
$('#gallery-box').removeClass("hide");
},500)
}
}
})
this.dataService.getPhotos();
this.photos = this.photoService.getPhotos()
this.checkLength = this.photos.length;
}
ngOnDestroy(){
this.subscription.unsubscribe();
this.imageLoaded.unsubscribe();
}
}
<file_sep>/my-portfolio/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MainComponent } from './main/main.component';
import { ProfileComponent } from './main/profile/profile.component';
import { ContactComponent } from './main/contact/contact.component';
const appRoutes : Routes =[
{
path:'',
component: MainComponent
},{
path:'profile',
component: ProfileComponent
},{
path:'contact',
component: ContactComponent
},
{
path:'portfolio',
loadChildren:'./portfolio/portfolio.module#PortfolioModule'
},{
path:'**',
redirectTo: ''
}
]
@NgModule({
imports:[
RouterModule.forRoot(appRoutes)
],
exports:[
RouterModule
]
})
export class AppRoutingModule{}
<file_sep>/my-portfolio/src/app/portfolio/photo/photo.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Router } from '@angular/router';
import { PhotoComment } from './photoComment/photocomment.model'
import { PhotoBrick } from './photo.model';
@Injectable()
export class PhotoService{
itemLoaded = new Subject<boolean>();
photoListChanged = new Subject<PhotoBrick[]>();
private photos : PhotoBrick[] = [
// new PhotoBrick(
// 'A test recipe',
// 'This is simply a test',
// 'Yellow Man',
// "https://farm3.staticflickr.com/2703/4211984650_a0d58d5496.jpg",
// new Date(),
// '1',
// []
// ),
// new PhotoBrick(
// 'asd',
// 'qwer',
// 'zxcv',
// "https://farm6.staticflickr.com/5055/5398254250_0a691d9804.jpg",
// new Date(),
// '2',
// [
// new PhotoComment('qwer','asdsa', new Date())
// ]
// ),
// new PhotoBrick(
// 'asd',
// 'qwer',
// 'zxcv',
// "https://farm1.staticflickr.com/139/357015070_0f007ee28f.jpg",
// new Date(),
// '3',
// []
// ),
// new PhotoBrick(
// 'A test recipe',
// 'This is simply a test',
// 'Yellow Man',
// "https://farm8.staticflickr.com/7596/17094319752_7de98d3e50.jpg",
// new Date(),
// '4',
// []
// )
];
public PhotosIds = this.photos.length;
setPhotos(photos:PhotoBrick[]){
this.photos = photos;
this.PhotosIds = this.photos.length;
this.photoListChanged.next(this.photos);
}
getPhotos(){
this.PhotosIds = this.photos.length;
return this.photos;
}
addBrick(photo:PhotoBrick){
if(this.photos.length > 0){
this.photos.unshift(photo);
}else{
this.photos.push(photo);
}
this.PhotosIds++;
this.photoListChanged.next(this.photos.slice());
}
getPhoto(index:any){
for(let i = 0 ; i < this.photos.length; i++){
if(this.photos[i].id == index){
return this.photos[i];
}
}
}
onDelete(index:any){
for(let i = 0 ; i < this.photos.length; i++){
if(this.photos[i].id == index){
this.photos.splice(i,1);
this.photoListChanged.next(this.photos.slice());
}
}
}
onCheckId(id:any){
for(let i = 0 ; i < this.photos.length; i++){
if(this.photos[i].id == id){
return true;
}
}
return false;
}
onUpdate(id:any, editPhoto:PhotoBrick){
for(let i = 0 ; i < this.photos.length; i++){
if(this.photos[i].id == id){
this.photos[i] = editPhoto;
this.photoListChanged.next(this.photos.slice());
}
}
}
}
<file_sep>/my-portfolio/src/app/portfolio/photo/photoComment/photoComment.model.ts
export class PhotoComment{
constructor(
private auth:string,
private comment:string,
private date:any
){}
}
<file_sep>/my-portfolio/README.md
포트폴리오 사이트 제작 프로젝트
===============================
Angular2를 이용한 개인포트폴리오 사이트
---------------------------------
## 1.제작이유
개인 포트폴리오 사이트를 닷홈을 통해서 배포중이 었는데, 무료호스팅 기간이 만료되어 새로운 호스팅을 구해야 했고, 최근 관심을 가지고 공부한 Angular2를 이용하여 SPA를 만들어보고 싶은 욕구가 생겨서 작업을 하게 되었다.
## 2. 제작기간 및 관련 정보
<pre>
총 제작 기간 : 14일(2017.06.12 ~ 2017.06.25)
제작인원 : 1명(본인)
작업도구 : Angular2, Javascript, Node.js, JQuery, Bootstrap, Git, Firebase
</pre>
[호스팅 링크] (https://portfolio-project-768d9.firebaseapp.com)
### 로컬에서의 실행
1. node.js환경에서 포트폴리오 폴더(my-portfolio)로 이동한다
2. npm install을 입력하여 노드 모듈 설치
3. 설치 후 ng server로 로컬에서 실행. port 4200
## 3.제작과정
전체 개발 과정은 아래와 같이 진행되었고, 여러가지 시도를 하면서 Firebase를 이용하여 배포하는 것으로 결정 되었다.
1. 사이트에 필요한 컨텐츠 정리(계획서.html), 이전에 사용되었던 컨텐츠 중에 쓸모 있는 부분은 재활용(카페베네 카피사이트)
2. 계획서를 작성하여 RESTful하게 URI를 구성하도록 계획
3. Firebase를 이용한 간단한 데이터베이스 사용 및 호스팅
### 컴포넌트 구조
* app.component
* app.module
* app-routing.module
+ header
- header.component
+ footer
- footer.component
+ main
- main.component
- contact.component
- profile.component
- show-profile.component
- start.component
+ portfolio
- portfolio.component
- photo.component
- photoComponent.component
- photoItem.component
- new.component
- detail.component
+ shared
- data.service
- dropdown-directive.directive
- shared.module
- shorten.pipe
### 컴포너트의 구성
<pre>
app.component : 기본이 되는 컴포넌트. firebase에서 실행
app-routing.module : 페이지 접근시 보여줄 컴포넌트 및 자식 라우트 설정
<hr>
header.component : 네비게이션등이 포함된 컴포넌트
footer.component : 화면 하단을 차지하는 컴포넌트
<hr>
<b>main</b> : 메인, 프로필, 자기소개와 관련된 컴포넌트들로 구성
main.component : 처음 접근시 샐행되는 컴포넌트
start.component : main에서 들어가기 버튼을 누르면 나타나는 페이지
profile.component : show-profile 컴포넌트 실행
show-profile.component : 동적으로 구현된 자기소개 페이지
contact.component : 연락처 페이지
shared : 공통으로 사용되는 서비스등을 모아둔 곳
data.service : 파이어베이스를 이용한 데이터 처리와 관련된 서비스
dropdown-directive.directive : 드롭다운 기능을 위한 지시자
shared.module : 드롭다운 기능을 사용하기 위한 모듈 설정
shorten.pipe : 글씨를 줄여주는 필터 설정을 위한 pipe
<hr>
<b>portfolio</b> : 포트폴리오 관련 컴포넌트 들을 모아둔 곳
portfolio.module : 포트폴리오에 관련된 모듈들을 정리
portfolio-routing.module : 포트폴리오 라우팅 처리
portfolio.component : 포트폴리오의 기본 컴포넌트
<hr>
<b>photo</b> : 이미지 갤러리
photo.component : 이미지 갤러리 기본 컴포넌트
photo-routing.module : 이미지 갤러리 라우팅 구현
photo.module : 이미지 업데이트 데이터 형태 설정
photoItem.component : 갤러리 리스트 관련 컴포넌트
photoComponent.component : 갤러리 게시글 내부 컨텐츠와 덧글에 관련된 컴포넌트
new.component : 새로운 이미지 게시 및 수정과 관련된 컴포넌트
detail.component : 게시글 내부 컨텐츠와 덧글에 관련된 컴포넌트
</pre>
## 4.제작시 어려웠던점
제작하면서 가장 힘들었던 부분은 Angular2를 이용한 것이 가장 힘들었는데, SPA를 구현하기 위해 기존의 view 부분에서 사용했던 HTML,CSS,Javscript에 관한 지식뿐만 아니라 템플릿에 대한 이해와, Angular2에서 구현한 컴포넌트 중심의 프로그램 구성에 대한 이해가 제대로 되어야 했다는 점이다.
기존의 홈페이지 제작과는 다른 컴포넌트 중심의 애플리케이션 구현과 그와 관련된 이벤트의 처리, 프론트단에서 처리해야하는 애니메이션등 처음 작업하면서 구현하기 어려운 부분이 많았고, Javascript와 비슷하지만 다른 Typescript도 걸림돌이 되기도 했다.
## 5.제작시 배웠던 점
Angular2의 이벤트 처리에 관해서 좀 더 자세하게 알게 되었고, 완벽하지 않지만, 데이터의 처리나 애니메이션을 구현하는 방법을 알게 되었다. 또 기존 Javascript 라이브러리를 Typescript 내에서 사용하는 방법을 알게 되었다. 파이어베이스를 이용한 데이터베이스 및 호스팅 경험은 다른 프로젝트에서도 사용을 고려해 볼 정도로 좋은 서비스임을 알게 되었다.<file_sep>/my-portfolio/src/app/main/start/start.component.ts
import { Component, OnInit} from '@angular/core';
import { Subject } from 'rxjs/Subject';
import * as firebase from 'firebase';
declare var jQuery:any;
declare var $:any;
@Component({
selector: 'app-start',
templateUrl: './start.component.html',
styleUrls: ['./start.component.css']
})
export class StartComponent implements OnInit {
coffee:string;
album:string;
loadedCheck = new Subject();
coffeeLoaded = new Subject<boolean>();
albumLoaded = new Subject<boolean>();
imgLoad1 =false;
imgLoad2 =false;
constructor() {
const coffee = firebase.storage().ref().child('coffee.png');
const album = firebase.storage().ref().child('photo.png');
coffee.getDownloadURL().then(url => this.coffee = url);
album.getDownloadURL().then(url => this.album = url);
}
ngOnInit() {
this.albumLoaded.subscribe((value:boolean)=>{
if(value === true){
this.imgLoad1 =true;
this.loadedCheck.next();
}
});
this.coffeeLoaded.subscribe((value:boolean)=>{
if(value === true){
this.imgLoad2 =true;
this.loadedCheck.next();
}
});
this.loadedCheck.subscribe(()=>{
if(this.imgLoad1 === true && this.imgLoad2 === true){
setTimeout(()=>{
$('#loading').addClass("hide");
$('#fadeShow').removeClass("hide");
$('#fadeShow').addClass("animated fadeInUp");
},500)
}
})
}
albumLoad(){
this.albumLoaded.next(true);
}
coffeeLoad(){
this.coffeeLoaded.next(true);
}
openSite(){
window.open('http://pf.i-make.kr:8080/caffebene/html/main/main.jsp', '_blank');
}
}
<file_sep>/my-portfolio/src/app/portfolio/portfolio-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PortfolioComponent } from './portfolio.component';
const portfolioRoutes: Routes = [
{ path: '', component: PortfolioComponent},
{ path: 'photo',
loadChildren:'./photo/photo.module#PhotoModule' }
];
@NgModule({
imports: [
RouterModule.forChild(portfolioRoutes)
],
exports: [RouterModule],
providers:[
]
})
export class PortfolioRoutingModule {}
<file_sep>/my-portfolio/src/app/portfolio/photo/photo.module.ts
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { PhotoComponent } from './photo.component';
import { NewComponent } from './new/new.component';
import { PhotoItemComponent } from './photoItem/photoItem.component';
import { DetailComponent } from './detail/detail.component';
import { PhotoCommentComponent } from './photoComment/photoComment.component';
import {PhotoRoutingModule} from './photo-routing.module';
@NgModule({
declarations: [
PhotoComponent,
NewComponent,
DetailComponent,
PhotoItemComponent,
PhotoCommentComponent
],
imports: [
CommonModule,
ReactiveFormsModule,
PhotoRoutingModule
]
})
export class PhotoModule {}
| 9071c07dfed3191ca50ba225573479e518994bcd | [
"Markdown",
"TypeScript"
] | 18 | TypeScript | YIRer/angular-portfolio | c41e9f4263e6f24df8ddcc400e88e6985f1159aa | d49def5a14480f42cbbbfe34de11c081e69b14d6 | |
refs/heads/master | <repo_name>Xenira/GenDev<file_sep>/src/gendev.spec.ts
/// <reference path="../typings/index.d.ts" />
import { GenDev } from '../src/gendev'
describe('GenDev', () => {
var gendev: GenDev;
beforeEach(() => {
gendev = new GenDev();
});
describe('#RegisterInput', () => {
it('should add an input to the list', () => {
expect(gendev.seed.inputs.length).toBe(0);
gendev.RegisterInput("test");
expect(gendev.seed.inputs.length).toBe(1);
});
it('should throw error if duplicate name', () => {
var addTestInput = () => {
gendev.RegisterInput("test");
}
addTestInput();
expect(addTestInput).toThrow()
});
});
describe('#RegisterOutput', () => {
var addTestOutput = () => {
gendev.RegisterOutput("test");
}
it('should add an output to the list', () => {
expect(gendev.seed.outputs.length).toBe(0);
addTestOutput();
expect(gendev.seed.outputs.length).toBe(1);
});
it('should throw error if duplicate name', () => {
addTestOutput();
expect(addTestOutput).toThrow();
expect(gendev.seed.outputs.length).toBe(1);
});
});
describe('#RegisterEvalFunction', () => {
it('should set the eval function', () => {
let evalFunc = (values: Object) => {
return 1;
}
expect(gendev.seed.evalFunc).toBeUndefined();
gendev.RegisterEvalFunction(evalFunc);
expect(gendev.seed.evalFunc).toBe(evalFunc);
})
});
describe('#Initiate', () => {
it('should create a new incubator instance', () => {
expect(gendev.incubator).toBeUndefined();
gendev.Initiate();
expect(gendev.incubator).toBeDefined();
});
it('should start the incubator', () => {
});
});
})<file_sep>/README.md
# GenDev
Small project to experiment with genetic development
<file_sep>/src/core/incubator.spec.ts
/// <reference path="../../typings/index.d.ts" />
import { Incubator, GenDevOptions } from './incubator';
describe('Incubator', () => {
var incubator: Incubator = new Incubator(null, new GenDevOptions);
});<file_sep>/src/core/gene.spec.ts
/// <reference path="../../typings/index.d.ts" />
import { Gene } from './gene'
describe('Gene', () => {
let gene: Gene
beforeEach(() => {
gene = new Gene([123], 10);
});
describe('#ReciveInput', () => {
beforeEach(() => {
gene.func = () => {};
gene.input = new Array(3);
spyOn(gene, 'func');
});
it('should call func on input', () => {
gene.ReciveInput(0, 1);
expect(gene.func).toHaveBeenCalledTimes(1);
});
it('should not call func on same input', () => {
gene.ReciveInput(0, 1);
gene.ReciveInput(0, 1);
gene.ReciveInput(1, 1);
expect(gene.func).toHaveBeenCalledTimes(2);
});
});
describe('#SendOutput', () => {
beforeEach(() => {
gene.output = () => {}
spyOn(gene, 'output');
});
it('should call the output function', () => {
gene.SendOutput('test');
expect(gene.output).toHaveBeenCalledTimes(1);
});
it('should not call output again for same output', () => {
gene.SendOutput([]);
gene.SendOutput([]);
expect(gene.output).toHaveBeenCalledTimes(1);
});
it('should not call output after burnout reached', () => {
for (var i = 0; i < 12; i++) {
gene.SendOutput('test' + i)
}
expect(gene.output).toHaveBeenCalledTimes(10);
})
});
});<file_sep>/src/core/generation.spec.ts
/// <reference path="../../typings/index.d.ts" />
import { Incubator, GenDevOptions, GenDevSeed } from './incubator'
import { Generation } from './generation'
describe('Generation', () => {
let incubator: Incubator;
let generation: Generation;
beforeEach(() => {
incubator = new Incubator(null, null);
});
afterEach(() => {
generation = undefined;
});
describe('#ResolveSequence', () => {
it('should add genes for every "row" of the sequence', () => {
});
});
})<file_sep>/src/core/gene.ts
import { EventEmitter } from 'events'
import { Incubator } from './incubator'
export class Gene {
func: (Array) => any;
output: (any) => void;
lastOutput: any = '';
outputCount: number = 0;
input: any[];
inputString: string[];
constructor(private gene: number[], private burnout?: number) {}
ReciveInput(index: number, value: any) {
if (!this.inputString || this.input.length != this.inputString.length) {
this.inputString = new Array<string>(this.input.length);
}
let valueString = JSON.stringify(value);
if (this.inputString[index] === valueString) { return; }
this.inputString[index] = valueString;
this.input[index] = value;
this.func(this.input)
}
SendOutput(result: any) {
if(this.outputCount >= this.burnout) { return; }
this.outputCount ++;
let stringResult = JSON.stringify(result);
if (stringResult === this.lastOutput) { return; }
this.lastOutput = stringResult;
this.output(result);
}
}
export interface IGene {
sequence: number[];
execute: () => void;
}<file_sep>/test/simple-add-test.ts
import { GenDev, IInput } from '../src/gendev'
var gendev: GenDev = new GenDev();
gendev.RegisterInput('var1');
gendev.RegisterInput('var2');
gendev.RegisterOutput('result');
gendev.SetEvalFunction();
function eval (inputs ) {
}<file_sep>/src/gendev.ts
import { Incubator, GenDevOptions, GenDevSeed, IInput, IOutput } from './core/incubator';
export class GenDev {
incubator: Incubator;
seed: GenDevSeed = new GenDevSeed();
RegisterInput(name: String) {
if (this.seed.inputs.some(data =>
data.event === name)) {
throw(`Unable to register duplicate input with name '${name}'`);
}
let input: IInput = {
event: name
}
this.seed.inputs.push(input);
}
RegisterOutput(name: String) {
if (this.seed.outputs.some(data =>
data.event === name)) {
throw(`Unable to register duplicate output with name '${name}'`);
}
let output: IOutput = {
event: name
};
this.seed.outputs.push(output);
}
RegisterEvalFunction(evalFunction: (Object, GameDev) => Number) {
this.seed.evalFunc = evalFunction;
}
Initiate(options?: GenDevOptions) {
this.incubator = new Incubator(null, options || new GenDevOptions());
//this.incubator.Start();
}
}<file_sep>/src/core/functions/add.function.ts
import { IGDFunction } from '../core/function'
export class AddFunction implements IGDFunction {
}<file_sep>/src/core/incubator.ts
import { EventEmitter } from 'events';
import { Generation } from './generation'
export class GendevEventEmitter extends EventEmitter { }
export class Incubator {
generations: Generation[];
constructor(private seed: GenDevSeed, private options: GenDevOptions) {}
}
export class GenDevOptions {
evalNumberMode: 'percent' | 'absolute' = 'percent';
}
export interface IInput {
event: String
}
export interface IOutput {
event: String
}
export class GenDevSeed {
inputs: IInput[] = [];
outputs: IOutput[] = [];
inputEvents: EventEmitter
outputEvents: EventEmitter
evalFunc: (IGenDevSeed, Object, String) => Number
}<file_sep>/src/core/generation.ts
import { Gene } from './gene'
import { Incubator } from './incubator'
export class Generation {
genes: Gene[] = [];
constructor(private incubator: Incubator, sequence: number[][]) {
this.ResolveSequence(sequence);
}
ResolveSequence(sequence: number[][]) {
let output: number[] = sequence.pop();
for (var i = 0; i < sequence.length; i++) {
var element = sequence[i];
var gene = new Gene(element);
}
}
}<file_sep>/src/core/function.ts
import { IGene } from './gene'
export class IGDFunction implements IGene {
sequence: number[];
input: any;
output: any;
execute() {
}
} | 0010c2e2c99ae8225066ef82350391e810b6aef2 | [
"Markdown",
"TypeScript"
] | 12 | TypeScript | Xenira/GenDev | 6bdbb116f30b7c93730e1f0ae090abe96e73f9a6 | baca48bf004b076fcb54e948fd0f29c0ed29fbfc | |
refs/heads/master | <file_sep>[build]
Command = "NODE_ENV=PRODUCTION npm run build && npm run build:lambda && cp _redirects build/_redirects"
Functions = "lambda"
Publish = "build"
<file_sep>import React from 'react'
import Geolocation from 'react-geolocation'
import Result from './Components/Result'
const App = () => {
return (
<main className="wrapper">
<Geolocation
render={({ fetchingPosition, position: { coords } = {}, error, getCurrentPosition }) => (
<Result coords={coords} error={error} getCurrentPosition={getCurrentPosition} fetching={fetchingPosition} />
)}
/>
</main>
)
}
export default App
<file_sep>var requestAnimationFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame
// Frame ticker helper module
var Ticker = (function() {
var PUBLIC_API = {}
// private
var started = false
var lastTimestamp = 0
var listeners = []
PUBLIC_API.addListener = function addListener(fn) {
listeners.push(fn)
// start frame-loop lazily
if (!started) {
started = true
queueFrame()
}
}
function queueFrame() {
requestAnimationFrame(frameHandler)
}
function frameHandler(timestamp) {
var frameTime = timestamp - lastTimestamp
lastTimestamp = timestamp
// make sure negative time isn't reported (first frame can be whacky)
if (frameTime < 0) {
frameTime = 17
} else if (frameTime > 68) {
frameTime = 68
}
// fire custom listeners
for (var i = 0, len = listeners.length; i < len; i++) {
// eslint-disable-next-line
listeners[i].call(window, frameTime, frameTime / 16.67)
}
// always queue another frame
queueFrame()
}
return PUBLIC_API
})()
// Animation namespace
var Animation = {
speed: 1,
color: {
r: '80',
g: '175',
b: '255',
a: '0.5'
},
// END CUSTOMIZATION
// whether Animation is running
started: false,
// canvas and associated context references
canvas: null,
ctx: null,
// viewport dimensions (DIPs)
width: 0,
height: 0,
// devicePixelRatio alias (should only be used for rendering, physics shouldn't care)
dpr: window.devicePixelRatio || 1,
// time since last drop
drop_time: 0,
// ideal time between drops (changed with mouse/finger)
drop_delay: 12,
// wind applied to rain (changed with mouse/finger)
wind: 4,
// color of rain (set in init)
rain_color: null,
rain_color_clear: null,
// rain particles
rain: [],
rainPool: [],
// rain droplet (splash) particles
drops: [],
dropPool: []
}
// Animation initialization (should only run once)
Animation.init = function(el) {
if (!Animation.started) {
Animation.started = true
Animation.canvas = el.current
Animation.ctx = Animation.canvas.getContext('2d')
var c = Animation.color
Animation.rain_color = 'rgba(' + c.r + ',' + c.g + ',' + c.b + ',' + c.a + ')'
Animation.rain_color_clear = 'rgba(' + c.r + ',' + c.g + ',' + c.b + ',0)'
Animation.resize()
Ticker.addListener(Animation.step)
}
}
// (re)size canvas (clears all particles)
Animation.resize = () => {
// localize common references
var rain = Animation.rain
var drops = Animation.drops
// recycle particles
for (var l = rain.length - 1; l >= 0; l--) {
rain.pop().recycle()
}
for (var i = drops.length - 1; i >= 0; i--) {
drops.pop().recycle()
}
// resize
Animation.width = window.innerWidth
Animation.height = window.innerHeight
Animation.canvas.width = Animation.width * Animation.dpr
Animation.canvas.height = Animation.height * Animation.dpr
}
Animation.step = (time, lag) => {
const { width, height, speed, rain, drops, wind, rainPool } = Animation
// multiplier for physics
var multiplier = speed * lag
// spawn drops
Animation.drop_time += time * speed
while (Animation.drop_time > Animation.drop_delay) {
Animation.drop_time -= Animation.drop_delay
var newRain = rainPool.pop() || new Rain()
newRain.init()
var windExpand = Math.abs((height / newRain.speed) * wind) // expand spawn width as wind increases
var spawnX = Math.random() * (width + windExpand)
if (wind > 0) spawnX -= windExpand
newRain.x = spawnX
rain.push(newRain)
}
// rain physics
for (var i = rain.length - 1; i >= 0; i--) {
var r = rain[i]
r.y += r.speed * r.z * multiplier
r.x += r.z * wind * multiplier
// remove rain when out of view
if (r.y > height) {
// if rain reached bottom of view, show a splash
r.splash()
}
// recycle rain
if (r.y > height + Rain.height * r.z || (wind < 0 && r.x < wind) || (wind > 0 && r.x > width + wind)) {
r.recycle()
rain.splice(i, 1)
}
}
// splash drop physics
var dropMaxSpeed = Drop.max_speed
for (var x = drops.length - 1; x >= 0; x--) {
var d = drops[x]
d.x += d.speed_x * multiplier
d.y += d.speed_y * multiplier
// apply gravity - magic number 0.3 represents a faked gravity constant
d.speed_y += 0.3 * multiplier
// apply wind (but scale back the force)
d.speed_x += (wind / 25) * multiplier
if (d.speed_x < -dropMaxSpeed) {
d.speed_x = -dropMaxSpeed
} else if (d.speed_x > dropMaxSpeed) {
d.speed_x = dropMaxSpeed
}
// recycle
if (d.y > height + d.radius) {
d.recycle()
drops.splice(x, 1)
}
}
Animation.draw()
}
Animation.draw = () => {
const { width, height, dpr, rain, drops, ctx } = Animation
// start fresh
ctx.clearRect(0, 0, width * dpr, height * dpr)
// draw rain (trace all paths first, then stroke once)
ctx.beginPath()
var rainHeight = Rain.height * dpr
for (var h = rain.length - 1; h >= 0; h--) {
var r = rain[h]
var realX = r.x * dpr
var realY = r.y * dpr
ctx.moveTo(realX, realY)
// magic number 1.5 compensates for lack of trig in drawing angled rain
ctx.lineTo(realX - Animation.wind * r.z * dpr * 1.5, realY - rainHeight * r.z)
}
ctx.lineWidth = Rain.width * dpr
ctx.strokeStyle = Animation.rain_color
ctx.stroke()
// draw splash drops (just copy pre-rendered canvas)
for (var i = drops.length - 1; i >= 0; i--) {
var d = drops[i]
var realX2 = d.x * dpr - d.radius
var realY2 = d.y * dpr - d.radius
ctx.drawImage(d.canvas, realX2, realY2)
}
}
// Rain definition
function Rain() {
this.x = 0
this.y = 0
this.z = 0
this.speed = 25
this.splashed = false
}
Rain.width = 2
Rain.height = 40
Rain.prototype.init = function() {
this.y = Math.random() * -100
this.z = Math.random() * 0.5 + 0.5
this.splashed = false
}
Rain.prototype.recycle = function() {
Animation.rainPool.push(this)
}
// recycle rain particle and create a burst of droplets
Rain.prototype.splash = function() {
if (!this.splashed) {
this.splashed = true
var drops = Animation.drops
var dropPool = Animation.dropPool
for (var i = 0; i < 16; i++) {
var drop = dropPool.pop() || new Drop()
drops.push(drop)
drop.init(this.x)
}
}
}
// Droplet definition
function Drop() {
this.x = 0
this.y = 0
this.radius = Math.round(Math.random() * 2 + 1) * Animation.dpr
this.speed_x = 0
this.speed_y = 0
this.canvas = document.createElement('canvas')
this.ctx = this.canvas.getContext('2d')
// render once and cache
var diameter = this.radius * 2
this.canvas.width = diameter
this.canvas.height = diameter
var grd = this.ctx.createRadialGradient(this.radius, this.radius, 1, this.radius, this.radius, this.radius)
grd.addColorStop(0, Animation.rain_color)
grd.addColorStop(1, Animation.rain_color_clear)
this.ctx.fillStyle = grd
this.ctx.fillRect(0, 0, diameter, diameter)
}
Drop.max_speed = 5
Drop.prototype.init = function(x) {
this.x = x
this.y = Animation.height
var angle = Math.random() * Math.PI - Math.PI * 0.5
var speed = Math.random() * Drop.max_speed
this.speed_x = Math.sin(angle) * speed
this.speed_y = -Math.cos(angle) * speed
}
Drop.prototype.recycle = function() {
Animation.dropPool.push(this)
}
export default Animation
<file_sep>import React, { useEffect, useRef } from 'react'
import Animation from './rainAnimation'
export default () => {
const Canvas = useRef(null)
useEffect(() => {
Animation.init(Canvas)
}, [])
return (
<canvas ref={Canvas} width="1024" height="768">
Canvas Not Supported! Please Update Your Browser to the Latest Version.
</canvas>
)
}
<file_sep># Is it Raining Outside?
Simple app that tells you if it's raining outside so you never have to get up again
| 74eea0aa96266fc86c16ef27e08c9c7be5358326 | [
"TOML",
"JavaScript",
"Markdown"
] | 5 | TOML | SaraVieira/isitrainingoutsi.de | 0da455f4d913a2c487735c27101550d2069d8d50 | 46674cad2e8745a227cf9b9e70adeb7fb2eeeb31 | |
refs/heads/master | <file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("../Model/Readings.php");
function getReadings($email){ //get a patients handshake result
$check = null;
return retrieveResults($email);
}
function getWeight($email){ //get a patients weight result
$check = null;
return retrieveWeight($email);
}
function getBPM($email){ //get a patients blood pressure result
$check = null;
return retrieveBPM($email);
}
function getTemp($email){ //get a patients temperature result
$check = null;
return retrieveTemp($email);
}
function getSys($email){ //get a patients systolic bp result
$check = null;
return retrieveSys($email);
}
function getDys($email){ //get a patients dstolic bp result
$check = null;
return retrieveDys($email);
}
?><file_sep><!--
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->
<!DOCTYPE html>
<?php
session_start();
if (isset($_SESSION['userData']) == false){
header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login.php'); //check the user is logged in
}
?>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
<?php include("templates/header.php"); ?>
</head>
<body>
<?php include("templates/nav.php"); ?>
<div class="header">
<a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index"><h1>Honours Project</h1></a>
<h3><a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/results">View Patient Results</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/advice">Give Advice to Patients</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/messenger">Patient Chats</a></h3>
</div>
<?php include("templates/footer.php"); ?>
</body>
</html><file_sep><!--
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
<?php include("templates/header.php"); ?>
</head>
<body>
<!-- Start of page content -->
<div class="container my-3" role="main">
<h1>Register</h1>
<p>Please fill in this form to register a new account or <a class="link" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login">login as an existing user</a> if you already have an account.</p>
<hr>
<div id="response"></div> <!-- Response will go here -->
<form method = "post">
<label for="email">Email</label>
<input class="form-control" type="text" placeholder="Enter Email" pattern="^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$" title="Please ensure the email address is valid." name="email" required>
<label for="name">Name</label>
<input class="form-control" type="text" placeholder="Enter Name" name="name" required>
<label for="password">Password</label>
<input class="form-control" type="password" placeholder="Enter Password" pattern="^(?=.*\d)(?=.*[a-zA-Z]).{8,80}$" title="Please ensure the password is 8 characters and contains at least one letter and one number." name="password" required>
<label for="confirm">Confirm Password</label>
<input class="form-control" type="password" placeholder="Confirm Password" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,80}$" title="Please ensure the password is 8 characters and contains at least one letter and one number." name="confirm" required>
<button id="submit" type="submit" class="form-control btn btn-success mt-3">Register</button>
</form>
</div>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { //get user data
include("../Controller/registerMedical.php");
$login = registerUsersM( $_POST['email'], $_POST['password'], $_POST['name']);
if ($login != "success"){
echo "Success";
header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login.php');
}
else {
echo $login;
}
}
?>
<?php include("templates/footer.php"); ?>
</body>
</html>
<file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("../Model/Advice.php");
$check = null;
$email = $_POST["email"];
echo adviceDatabase($email); //returns all the advice for that patient based in their email
?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("../Model/User.php");
$check = null;
$email = $_POST["user_name"];
$password = $_POST["password"]; //recieve data from mobile
$check = Login($email, $password); //perform login function
echo $check;
?>
<file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("../Model/User.php");
function registerUsersM($email, $password, $name){ //register a new medical professional
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if (!preg_match($email_exp, $email))
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
if (strlen($password) < 8)
$error_message .= 'You have entered too weak a password, please ensure the password is 8 characters and contains at least one letter and number. <br />';
if (!preg_match("#[0-9]+#", $password))
$error_message .= 'Password must include at least one number. <br />';
if (!preg_match("#[a-zA-Z]+#", $password))
$error_message .= 'Password must include at least one letter. <br />';
if(strlen($error_message) > 0){
return $error_message;
}
else{
$check = registerUser($email, $password, $name);
if ($check != null){ //if the registration has succeeeded
return $check;
}
else {
return "invalid entry";
}
}
}
?><file_sep>
/*
============================================================================
Name : piiotest.c
Author : CMP408 - <NAME> 1600964
Version : 0.1
Copyright : See Abertay copyright notice
Description : Test App for PIIO Drivers
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
#include"piio.h"
#include "readings.c"
gpio_pin apin;
lkm_data lkmdata;
#define BUFFER_SIZE 1024
int printRandoms(int lower, int upper, int count){
int i;
for (i = 0; i < count; i++) {
int num = (rand() %
(upper - lower + 1)) + lower;
return num;
}
}
int getRandHR(int fd){
int lower = 60, upper = 100, count = 1;
int val = printRandoms(lower, upper, count);
return val;
}
int getRandSYS(int fd){
int count = 1;
return printRandoms(100, 140, count);
}
int getRandDYS(int fd){
int count = 1;
return printRandoms(20, 80, count);
}
int getRandTemp(int fd){
int count = 1;
return printRandoms(36, 40, count);
}
int getRandShake(int fd){
int count = 1;
return printRandoms(50, 100, count);
}
int main(int argc, char *argv[]) {
srand(time(0));
int fd, ret;
char *msg = "Message passed by ioctl\n";
fd = open("/dev/dev/dAaronStones", O_RDWR);
if (fd < 0) {
printf("Can't open device file: %s\n", DEVICE_NAME);
exit(1);
}
if (argc > 1) {
if (!strncmp(argv[1], "getRandHR",8)) {
printf("%d",getRandHR(fd));
}
if (!strncmp(argv[1], "getRandSYS", 9)) {
printf("%d",getRandSYS(fd));
}
if (!strncmp(argv[1], "getRandDYS", 9)) {
printf("%d",getRandDYS(fd));
}
if (!strncmp(argv[1], "getRandTemp", 9)) {
printf("%d",getRandTemp(fd));
}
if (!strncmp(argv[1], "getRandShake", 9)) {
printf("%d",getRandShake(fd));
}
}
close(fd);
return 0;
}
<file_sep>//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
package com.example.honoursproject;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.hardware.SensorEventListener;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import static android.view.View.VISIBLE;
public class TakeTest extends AppCompatActivity implements SensorEventListener{
private SensorManager senSensorManager;
private Sensor senAccelerometer;
private long lastUpdate = 0;
private float last_x, last_y, last_z;
private static final int SHAKE_THRESHOLD = 25; //set threshold and initilaise differetn sensors
String doctorName;
String email;
FormVerfication formCheck = new FormVerfication(this); //include the form checker
int count = 0;
int SYS;
int DYS;
int Weight;
int Temp; //setup globals
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_test);
doctorName = getIntent().getStringExtra("doctor");
email = getIntent().getStringExtra("email"); //get the emsil and doctor from previous functions
senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
senSensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { //get permission from the user to use the camera
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
}
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
Sensor mySensor = sensorEvent.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) { //make sure we are getting readings from the accelerometer
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2]; //retrieve the x,y and z coordinate
long curTime = System.currentTimeMillis();
if ((curTime - lastUpdate) > 100) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;
float speed = Math.abs(x + y + z - last_x - last_y - last_z)/ diffTime * 10000;
if (speed > SHAKE_THRESHOLD) { //is the calculated speed is greater than the threshold increase the counter by one
count++;
}
last_x = x;
last_y = y;
last_z = z; //replot the x,y and z coordinate
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
protected void onPause() {
super.onPause();
senSensorManager.unregisterListener(this);
}
protected void onResume() {
super.onResume();
senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
public void Begin(View view){
showWeights(); //ask the user for their weight
}
void showWeights(){
EditText editText = findViewById(R.id.editText11);
editText.setVisibility(VISIBLE);
Button button = findViewById(R.id.button13);
button.setVisibility(VISIBLE); //set the weights to visible
}
public void Weight(View view){ //get weight from user and ensure it meets the check then reveal next field
EditText editText = findViewById(R.id.editText12);
editText.setVisibility(VISIBLE);
Button button = findViewById(R.id.button14);
button.setVisibility(VISIBLE);
editText = findViewById(R.id.editText11);
if (Boolean.toString(formCheck.intCheck(editText.getText().toString())).equals("false")){
Weight = Integer.parseInt(editText.getText().toString());
}
else{
formCheck.errorFormat();
}
}
public void Temp(View view){ //get Temperature from user and ensure it meets the check then reveal next field
EditText editText = findViewById(R.id.editText13);
editText.setVisibility(VISIBLE);
Button button = findViewById(R.id.button15);
button.setVisibility(VISIBLE);
editText = findViewById(R.id.editText12);
if (Boolean.toString(formCheck.intCheck(editText.getText().toString())).equals("false")){
Temp = Integer.parseInt(editText.getText().toString());
}
else{
formCheck.errorFormat();
}
}
public void BP(View view) throws JSONException { //get BP from user and ensure it meets the check then reveal next field
EditText editText = findViewById(R.id.editText13);
String bp = editText.getText().toString();
if (Boolean.toString(formCheck.intCheck(editText.getText().toString())).equals("false")){
SYS = Integer.parseInt(bp.substring(0, 3));
DYS = Integer.parseInt(bp.substring(4));
}
else{
formCheck.errorFormat();
}
HR();
}
public void HR() throws JSONException { //get HR from user and ensure it meets the check then reveal next field
Intent intent;
intent = new Intent(getApplicationContext(), Measure.class);
JSONObject obj=new JSONObject();
obj.put("email", email);
obj.put("doctor", doctorName);
obj.put("weight", Weight);
obj.put("count", count);
obj.put("temperature", Temp);
obj.put("sys", SYS);
obj.put("dys", DYS); //pack the reuslts into a JSON object
if (Boolean.toString(formCheck.simpleCheck(Integer.toString(Weight))).equals("true") || //final check on the data
Boolean.toString(formCheck.simpleCheck(Integer.toString(Temp))).equals("true") ||
Boolean.toString(formCheck.simpleCheck(Integer.toString(SYS))).equals("true")||
Boolean.toString(formCheck.simpleCheck(Integer.toString(DYS))).equals("true"))
{
formCheck.error();
}
else {
intent.putExtra("email", obj.toString()); //else send it to the next acrivity
startActivity(intent);
}
}
}
<file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("../Model/Messages.php");
function getMessages($email){
$check = null;
return retrieveMessages($email); //retrieve all the messages between a doctor and a patient based on that email
}
?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("../Model/User.php");
$check = null;
$email = $_POST["email"];
$doctor = $_POST["doctor"];
$checkDoctor = doctorCheck($doctor); //check the doctor exists
if ($checkDoctor != 1){
echo "This doctor does not exist";
}
else {
$check = doctorChange($email, $doctor); //doctor exists proceed with the change
echo $check;
}
?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("../Model/conn.php");
$db = new dbObj();
$conn = $db->getConnstring();
function adviceDatabase($email) //function to get all the advice from the database based on a user's email
{
global $conn;
$sql = $conn->prepare("SELECT * from Advice where email=? ORDER BY Timestamp DESC");
$sql->bind_param("s", $email);
$sql->execute();
$sql->bind_result($email, $advice, $doctor, $time);
$count = 0;
while ($sql->fetch()) {
$json[$count] = array(
'advice' => $advice,
'doctor' => $doctor,
'time' => $time);
$count++;
}
return json_encode($json);
}
function sendAdvice($email, $name, $advice){ //function to store the advice that has been sent to the server
global $conn;
$sql = $conn->prepare("INSERT INTO Advice (email, Advice, Doctor) VALUES(?,?,?)");
$sql->bind_param("sss", $email, $advice, $name);
$sql->execute();
$affectedRows = $sql->affected_rows;
if ($affectedRows == 1) {
return "Success";
}
else {
return null;
}
}
?><file_sep><title>Honours Project - 1600964</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<link rel="icon" href="https://proxy.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.freepnglogos.com%2Fuploads%2Fs-letter-logo-png-15.png">
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
?><file_sep><!--
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->
<!DOCTYPE html>
<?php
session_start();
if (isset($_SESSION['userData']) == false){
header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login.php'); //check the user is logged in
}
?>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/View/css/index.css">
<?php include("templates/header.php"); ?>
</head>
<body>
<?php include("templates/nav.php"); ?> <!--Include the templates -->
<div class="header">
<a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index"><h1>Patient Advice</h1></a>
<h3><a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/results">View Patient Results</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/landing">Home</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/messenger">Patient Chats</a></h3>
</div>
<h4>Select a patient to give advice</h4>
<form method="post"> <!--Form to go patient advice -->
<label for="email">Email</label>
<input class="form-control" type="text" placeholder="Enter Email" title="Please ensure the email address is valid." name="email" required>
<button id="submit" type="submit" class="form-control btn btn-success mt-3">Select Patient</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { //get user data
include("../Controller/getAdviceM.php");
$email = $_POST['email'];
$_SESSION['email'] = $_POST['email'];
$advice = getAdvice($_SESSION['email']);
$advice = json_decode($advice);
if ($advice == null){
echo "Invalid Entry";
}
else {
$_SESSION['setAdvice'] = true;
for ($i=0; $i<sizeof($advice);$i++){
echo $advice[$i]->advice . " " . $advice[$i]->time . "</br></br>";
}
}
if (isset($_SESSION['setAdvice'])){
$var = json_decode($_SESSION['userData']);
echo "<form method=post id='adviceSend'>
<label for=email>Enter Advice</label>
<input class='form-control' type='text' placeholder='Enter Advice' name='advice' required>
<input name=docName type=hidden value='" . $var->name . "'>
<input name=patientEmail type=hidden value='" . $email . "'>
<button id='postMessage' type='submit' class='form-control btn btn-success mt-3'>Send Advice</button>
</form>
";
}
}
?>
<script>
$("#postMessage").click(function(){
$.post("../Controller/sendAdvice.php", $("#adviceSend").serialize(),function(data){
alert(data);
});
});
</script>
<?php include("templates/footer.php"); ?>
</body>
</html><file_sep><!--
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
<?php include("templates/header.php"); ?>
</head>
<body>
<?php include("templates/nav.php"); ?>
<div class="header">
<a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index"><h1>Honours Project</h1></a>
<h3><NAME> | BSc Computing | Abertay University</h3> <!-- A simple page where the user is directed to view the website-->
</div>
<?php include("templates/footer.php"); ?>
</body>
</html><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("../Model/conn.php");
$db = new dbObj();
$conn = $db->getConnstring();
function retrieveMessages($email) //retrieve all the messages in ascending order based on a user's email
{
global $conn;
$sql = $conn->prepare("SELECT * from Messages where email=? ORDER BY Timestamp ASC");
$sql->bind_param("s", $email);
$sql->execute();
$sql->bind_result($email, $doctor, $message, $time);
$count = 0;
while ($sql->fetch()) {
$json[$count] = array(
'message' => $message,
'doctor' => $doctor,
'time' => $time);
$count++;
}
return json_encode($json);
$conn->close;
}
function sendMessageP($email, $message){ //send a messade to the database to be later processed by the server
global $conn;
$value = 0;
$sql = $conn->prepare("INSERT INTO Messages (email, Doctor, Message) Values(?,?,?)");
$sql->bind_param("sis", $email, $value, $message);
$sql->execute();
$affectedRows = $sql->affected_rows;
if ($affectedRows == 1) {
return "Success";
}
else {
return null;
}
$conn->close;
}
?><file_sep>include ':app'
rootProject.name='Honours project'
<file_sep>/*
============================================================================
Name : piiotest.c
Author : CMP408 - <NAME> 1600964
Version : 0.1
Copyright : See Abertay copyright notice
Description : Test App for PIIO Drivers
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
//Include eHealth library (it includes arduPi)
#include "eHealth.h"
gpio_pin apin;
lkm_data lkmdata;
#define BUFFER_SIZE 1024
int getHR(int fd){
return getBPM() // Returns the heart beats per minute.
}
int getSYS(int fd){
getSystolicPressure(i) // Returns the value of the systolic pressure number i.
}
int getDYS(int fd){
getDiastolicPressure(i) // Returns the value of the diastolic pressure number i.
}
int getTemp(int fd){
int getTemperature() // Returns the corporal temperature.
}
<file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
$email = $_GET["email"];
$count = $_GET["count"];
$weight = $_GET["weight"];
$temp = $_GET["temperature"];
$hr = $_GET["hr"];
$dys = $_GET["dys"];
$sys = $_GET["sys"];
$doctor = $_GET["doctor"]; //recieve data from iot device
include("../Model/Readings.php");
if(!is_numeric($weight) && !is_numeric($temp) && !is_numeric($count) && !is_numeric($hr) && !is_numeric($dys) && !is_numeric($sys)){ // return **TRUE** if it is numeric
echo "Inavlid Inputs";
}
else{
recordReading($email, $doctor, $count, $weight, $temp, $hr, $dys, $sys);
}
?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests of the different patients
include("../Model/User.php");
$check = null;
$email = $_POST["user_name"];
$password = $_POST["password"];
$json = $_POST["json"];
$doctor = $_POST["doctor"];
$checkDoctor = doctorCheck($doctor);
if ($checkDoctor != 1){
echo "This doctor does not exist";
}
$emailCheck = emailCheck($email);
if ($emailCheck == 1){
echo "This email has already been taken";
}
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if (!preg_match($email_exp, $email))
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
if (strlen($password) < 8)
$error_message .= 'You have entered too weak a password, please ensure the password is 8 characters and contains at least one letter and number. <br />';
if (!preg_match("#[0-9]+#", $password))
$error_message .= 'Password must include at least one number. <br />';
if (!preg_match("#[a-zA-Z]+#", $password))
$error_message .= 'Password must include at least one letter. <br />';
if(strlen($error_message) > 0){
echo $error_message;
}
else{
$check = Signup($email, $password, $json, $doctor);
echo $check;
}
?><file_sep><!--
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
<?php include("templates/header.php"); ?>
</head>
<body>
<?php include("templates/nav.php"); ?>
<!-- Start of page content -->
<div class="container d-flex h-100 w-100" role="main">
<div class="row align-items-center h-100 w-100">
<div class="span6 text-center mx-auto mt-5">
<p>Uh oh, looks like something went wrong...</p> <!--There is an error and the user will be directed here-->
<p><a class="btn btn-success" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index">Go to Home page</a> or <a class="btn btn-success" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/support">Go to Support page</a></p>
</div>
</div>
</div>
<!-- End of page content -->
<?php include("templates/footer.php"); ?>
</body>
</html><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("conn.php");
$db = new dbObj();
$conn = $db->getConnstring();
function recordReading($email, $doctor, $count, $weight, $temp, $hr, $dys, $sys){ //store a reading indexed by a user's email
global $conn;
$value = 0;
$sql = $conn->prepare("INSERT INTO Results (email, Doctor, Result, HR, Weight, Temperature, Sys, Dys) Values(?,?,?,?,?,?,?,?)");
$sql->bind_param("ssiiiiii", $email, $doctor, $count, $hr, $weight, $temp, $sys, $dys);
$sql->execute();
$affectedRows = $sql->affected_rows;
if ($affectedRows == 1) {
return "Test Complete!";
}
else {
return null;
}
}
function retrieveResults($email){ //get all the handshake results from a table based on the user's email
global $conn;
$sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
$sql->bind_param("s", $email);
$sql->execute();
$sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);
$count = 0;
while ($sql->fetch()) {
$json[$count] = array(
'y' => $Result,
'label' => $time);
$count++;
}
return json_encode($json);
}
function retrieveAll($email){ //retrieve all the results from a server
global $conn;
$sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
$sql->bind_param("s", $email);
$sql->execute();
$sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);
$count = 0;
while ($sql->fetch()) {
$json[$count] = array(
'result' => $Result,
'hr' => $BPM,
'weight' => $weight,
'temp' => $Temp,
'sys' => $Sys,
'dys' => $Dys,
'time' => $time);
$count++;
}
return json_encode($json);
}
function retrieveBPM($email){ //retrieve all the heart rate measures
global $conn;
$sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
$sql->bind_param("s", $email);
$sql->execute();
$sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);
$count = 0;
while ($sql->fetch()) {
$json[$count] = array(
'y' => $BPM,
'label' => $time);
$count++;
}
return json_encode($json);
}
function retrieveWeight($email){ //retrieve all the weight measures
global $conn;
$sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
$sql->bind_param("s", $email);
$sql->execute();
$sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);
$count = 0;
while ($sql->fetch()) {
$json[$count] = array(
'y' => $weight,
'label' => $time);
$count++;
}
return json_encode($json);
}
function retrieveTemp($email){ //retrieve all the temperature measures
global $conn;
$sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
$sql->bind_param("s", $email);
$sql->execute();
$sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);
$count = 0;
while ($sql->fetch()) {
$json[$count] = array(
'y' => $Temp,
'label' => $time);
$count++;
}
return json_encode($json);
}
function retrieveSys($email){ //retireve all the systolic bp readings
global $conn;
$sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
$sql->bind_param("s", $email);
$sql->execute();
$sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);
$count = 0;
while ($sql->fetch()) {
$json[$count] = array(
'y' => $Sys,
'label' => $time);
$count++;
}
return json_encode($json);
}
function retrieveDys($email){ //retireve all the dystolic bp readings
global $conn;
$sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
$sql->bind_param("s", $email);
$sql->execute();
$sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);
$count = 0;
while ($sql->fetch()) {
$json[$count] = array(
'y' => $Dys,
'label' => $time);
$count++;
}
return json_encode($json);
}
?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("../Model/conn.php");
$db = new dbObj();
$conn = $db->getConnstring();
function Login($email, $pass) //function to validate a user's login details
{
global $conn;
$sql = $conn->prepare("SELECT * from Patients where email=? LIMIT 1");
$sql->bind_param("s", $email);
$sql->execute();
$sql->bind_result($key, $email, $password, $json, $doctor, $time);
if ($email == null){
return "Incorrect credentials, please try again";
}
while ($sql->fetch()) {
if (password_verify($pass, $password) != false){
return json_encode(array(
'id' => $key,
'email' => $email,
'json' => json_decode($json),
'doctor' => $doctor));
}
else {
return "Incorrect credentials, please try again";
}
}
}
function retriveAccountResults($email){ //retrieves the results for the handshake test only
global $conn;
$sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
$sql->bind_param("s", $email);
$sql->execute();
$sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);
$count = 0;
while ($sql->fetch()) {
$array[$count] = array(
'result' => $Result,
'time' => $time);
$count++;
}
return json_encode($array);
}
function LoginM($email, $pass){ //login section for the medical professionals
global $conn;
$sql = $conn->prepare("SELECT * from Medical where email=? LIMIT 1");
$sql->bind_param("s", $email);
$sql->execute();
$sql->bind_result($email, $name, $password);
if ($email == null){
return "Incorrect credentials, please try again";
}
while ($sql->fetch()) {
if (password_verify($pass, $password) != false){
return json_encode(array(
'email' => $email,
'name' => $name,
'password' => $password));
}
else {
return "Incorrect credentials, please try again";
}
}
}
function Name($email, $file) //function to update a user's name
{
$file = json_encode($file);
global $conn;
$sql = $conn->prepare("UPDATE Patients SET jsonData=? WHERE email=?");
$sql->bind_param("ss", $file, $email);
$status = $sql->execute();
if ($status === false) {
return "fail";
}
else {
return "success";
}
}
function Signup($email, $password, $json, $doctor){ //sign up function
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
global $conn;
$sql = $conn->prepare("INSERT INTO Patients (email, password, jsonData, Doctor) Values(?,?,?,?)");
$sql->bind_param("ssss", $email, $passwordHash, $json, $doctor);
$sql->execute();
$affectedRows = $sql->affected_rows;
if ($affectedRows == 1) {
return "Success";
}
else {
return "fail";
}
}
function checkEmail($email){ //a check to ensure the email has not been used prior to registrations
global $conn;
$sql = $conn->prepare("SELECT Primary_Key from Patients where email=? LIMIT 1");
$sql->bind_param("s", $email);
if (mysqli_num_rows($sql->execute()) > 0) {
return true;
}
}
function doctorChange($email, $doctor){ //function to change the user's doctor
global $conn;
$sql = $conn->prepare("UPDATE Patients SET Doctor=? WHERE email=?");
$sql->bind_param("ss", $doctor, $email);
$status = $sql->execute();
if ($status === false) {
return "fail";
}
else {
return "success";
}
}
function doctorCheck($doctor){ //check to ensure the doctor exists
global $conn;
$sql = $conn->prepare("SELECT * from Medical where name=?");
$sql->bind_param("s", $doctor);
$sql->execute();
$count = 0;
while ($sql->fetch()) {
$count++;
}
if ($count > 0){
return 1;
}
else{
return 0;
}
}
function emailCheck($email){ //check to see if the email is already in use
global $conn;
$sql = $conn->prepare("SELECT * from Patients where email=?");
$sql->bind_param("s", $email);
$sql->execute();
$count = 0;
while ($sql->fetch()) {
$count++;
}
if ($count > 0){
return 1;
}
else{
return 0;
}
}
function registerUser($email, $password, $name){ //registers a medical professional
global $conn;
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$sql = $conn->prepare("INSERT INTO Medical (email, name, password) Values(?,?,?)");
$sql->bind_param("sss", $email, $name, $passwordHash);
$sql->execute();
$affectedRows = $sql->affected_rows;
if ($affectedRows == 1) {
return "Success";
}
else {
return null;
}
}
?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
$advice = $_POST["advice"];
$docName = $_POST["docName"];
$patientEmail = $_POST["patientEmail"]; //recieve the mobile data
include("../Model/Advice.php");
$response = sendAdvice($patientEmail, $docName, $advice); //post advice to the server
echo $response;
?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("../Model/User.php");
$check = null;
$email = $_POST["email"];
$file = $_POST["file"]; //recieve data from mobile
$check = Name($email, $file); //change a user's name
echo $check;
?><file_sep><!--
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
<?php include("templates/header.php"); ?>
</head>
<body>
<?php include("templates/nav.php"); ?>
<!-- Start of page content -->
<div class="container my-3" role="main">
<div class="row">
<div class="col-md-6 col-sm-12">
<h2>Frequently Asked Questions</h2>
<h3>How will my data be stored?</h3>
<p class="small">
Your data will be securely stored in the university's MySQL database on the
Mayar server.
</p>
<h3>Does this application ue 'real life' data/results?</h3>
<p class="small">
No all data/reuslts are fabricated or taken from willing volunteersto prove the
concept works. No patient data is ever used.
</p>
<h3>Where is this project being developed?</h3>
<p class="small">
This project is being developed within the Univeristy of Abertay Dundee's campus.
</p>
<h3>What technologies does the project utilise?</h3>
<p class="small">
To develop this website the technologies used are the LAMP (or Linux Apache MySQL and PHP)
stack with HTML, CSS and JavaScript to suppliment the website.
</p>
<h3>What else is being developed to couple with this website?</h3>
<p class="small">
A mobile device to test patients Parkinson's/Dementia state and an IoT device to read a subject's
vital signs.
</p>
<h3>My question isn't answered here what should I do?</h3>
<p class="small">
Please fill out the form on this page and it will send an email to a member of the development team
who will answer your query in no time.
</p>
</div>
<div class="col-md-6 col-sm-12">
<h2>Contact Us</h2>
<form action="../Controller/contact.php" method="POST">
<label for="subject">Subject</label>
<select class="form-control" name="subject">
<option value="Feedback">Feedback</option>
<option value="Report">Bug Report</option>
<option value="Complaint">Complaint</option>
<option value="Other">Other</option>
</select>
<label for="email">Email Address</label>
<input class="form-control" type="email" name="email" required pattern="^(?=.{5,80}$)[\S]+@[\S]+\.[\S]+$">
<label for="message">Message</label>
<textarea class="form-control" name="message" rows="6" required pattern="^.{1,1200}$"></textarea>
<input class="form-control btn btn-success mt-3" type="submit" value="Submit">
</form>
</div>
</div>
</div>
<!-- End of page content -->
<?php include("templates/footer.php"); ?>
</body>
</html><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("../Model/Advice.php");
function getAdvice($email){
return adviceDatabase($email); //get advoce for the medical practitioners
}
?><file_sep><!--
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->
<?php
session_start();
if (isset($_SESSION['userData']) == false){
header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login.php');
}
$Details = json_decode($_SESSION['userData']); //get and decode the sessions data
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php include("templates/header.php"); ?>
</head>
<body>
<?php include("templates/nav.php"); ?>
<div class="container my-3" role="main">
<h1>My Account</h1>
<p>Here you can view and modify the your account details.</p>
<hr>
<h2 class="mt-5">Change Email</h2>
<div id="responseChangeEmail"></div> <!-- Response will go here -->
<form id="formChangeEmail" method="post">
<label for="password">Current Password</label>
<input name="password" class="form-control" type="password" placeholder="Enter Password" required pattern="^(?=.*\d)(?=.*[a-zA-Z]).{8,80}$" title="Please ensure the password is 8 characters and contains at least one letter and one number.">
<label for="newEmail">New Email</label>
<input name="newEmail" class="form-control" type="text" placeholder="Enter Email" required pattern="^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$" title="Please ensure the email address is valid.">
<button id="submitChangeEmail" type="submit" class="form-control btn btn-success mt-3">Change Account Email</button>
</form>
<h2 class="mt-5">Change Password</h2>
<div id="responseChangePassword"></div> <!-- Response will go here -->
<form id="formChangePassword" method="post">
<label for="password">Current Password</label>
<input name="password" class="form-control" type="password" placeholder="Enter Password" required pattern="^(?=.*\d)(?=.*[a-zA-Z]).{8,80}$" title="Please ensure the password is 8 characters and contains at least one letter and one number.">
<label for="newPassword">New Password</label>
<input name="newPassword" class="form-control" type="password" placeholder="Enter New Password" required pattern="^(?=.*\d)(?=.*[a-zA-Z]).{8,80}$" title="Please ensure the password is 8 characters and contains at least one letter and one number.">
<label for="newConfirm">Confirm New Password</label>
<input name="newConfirm" class="form-control" type="password" placeholder="Confirm New Password" required pattern="^(?=.*\d)(?=.*[a-zA-Z]).{8,80}$" title="Please ensure the password is 8 characters and contains at least one letter and one number.">
<button id="submitChangePassword" type="submit" class="form-control btn btn-success mt-3">Change Account Password</button>
</form>
<h2 class="mt-5">Change Name</h2>
<div id="responseChangePassword"></div> <!-- Response will go here -->
<form id="formChangePassword" method="post">
<label for="password">New Name</label>
<input name="name" class="form-control" type="text" placeholder="Enter Name">
<button id="submitChangePassword" type="submit" class="form-control btn btn-success mt-3">Change Account Name</button>
</form>
</div>
<!-- Start of AJAX script -->
<script>
// Change email form
$('#formChangeEmail').on('submit', function(e)
{
e.preventDefault(); // Prevent default form behaviour so we can override it
$('#submitChangeEmail').prop('disabled', true); // Disable submit button to prevent multiple submissions
$.post('../Controller/change_email.php', $('#formChangeEmail').serialize(), function(data)
{
let response = '<div class="alert alert-' + (data.success ? 'success' : 'danger') + '">' + data.message + '</div>';
$('#responseChangeEmail').html(response); // Display response message
$('#submitChangeEmail').prop('disabled', false);
}, 'json');
});
// Change password form
$('#formChangePassword').on('submit', function(e)
{
e.preventDefault(); // Prevent default form behaviour so we can override it
$('#submitChangePassword').prop('disabled', true); // Disable submit button to prevent multiple submissions
$.post('../controller/change_password.php', $('#formChangePassword').serialize(), function(data)
{
let response = '<div class="alert alert-' + (data.success ? 'success' : 'danger') + '">' + data.message + '</div>';
$('#responseChangePassword').html(response); // Display response message
$('#submitChangePassword').prop('disabled', false);
}, 'json');
});
// Delete user form
$('#formDeleteAccount').on('submit', function(e)
{
e.preventDefault(); // Prevent default form behaviour so we can override it
if (window.confirm("Are you sure you want to permanently delete your account?"))
{
$('#submitDeleteAccount').prop('disabled', true); // Disable submit button to prevent multiple submissions
$.post('../controller/delete_user.php', $('#formDeleteAccount').serialize(), function(data)
{
let response = '<div class="alert alert-' + (data.success ? 'success' : 'danger') + '">' + data.message + '</div>';
$('#responseDeleteAccount').html(response); // Display response message
$('#submitDeleteAccount').prop('disabled', false);
if (data.success)
setTimeout(function () { location.href = 'index' }, 1500);
}, 'json');
}
});
</script>
<!-- End of AJAX script -->
<?php include("templates/footer.php"); ?>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
<?php include("https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/templates/header.php"); ?>
</head>
<body>
<?php include("https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/templates/nav.php"); ?>
<div class="header">
<a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index"><h1>Honours Project</h1></a>
<h3><NAME> | BSc Computing | Abertay University</h3> <!-- A simple page where the user is directed to view the website-->
</div>
<h1>Enter Your Test Results</h1>
<div class="container my-3">
<form method="post">
<label for="email">Email</label>
<input class="form-control" type="text" placeholder="Enter Email" name="email" required>
<label for="doctor">Doctor</label>
<input class="form-control" type="text" placeholder="Enter Doctor" name="doctor" required>
<label for="hr">Heart Rate</label>
<input class="form-control" placeholder="Enter your HR" name="hr" value="<?=shell_exec('sudo /home/pi/Submission2/Driver_Test_App/a.out getRandHR');?>"required>
<label for="sys">Systolic Blood Pressure</label>
<input class="form-control" placeholder="Enter your Systolic BP" name="sys" value="<?=shell_exec('sudo /home/pi/Submission2/Driver_Test_App/a.out getRandSYS');?>"required>
<label for="dys">Dystolic Blood Pressure</label>
<input class="form-control" placeholder="Enter your Dystolic BP" name="dys" value="<?=shell_exec('sudo /home/pi/Submission2/Driver_Test_App/a.out getRandDYS');?>"required>
<label for="weight">Weight</label>
<input class="form-control" placeholder="Enter your Weight" name="weight" required>
<label for="bp">Temperature</label>
<input class="form-control" placeholder="Enter your temperature" name="temperature" value="<?=shell_exec('sudo /home/pi/Submission2/Driver_Test_App/a.out getRandTemp');?>"required>
<input class="form-control" type="hidden" name="count" value="<?=shell_exec('sudo /home/pi/Submission2/Driver_Test_App/a.out getRandShake');?>"required>
<button type="submit" class="form-control btn btn-success mt-3">Enter Results</button>
</form>
</div>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["email"])){
$var = "https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/Controller/iotRecorder.php?email=". $_POST['email'] . "&count=" . $_POST['count'] . "&doctor=" . $_POST['doctor'] . "&hr=" . $_POST['hr'] . "&sys=" . $_POST['sys'] . "&dys=" . $_POST['dys'] . "&weight=" . $_POST['weight'] . "&temperature=" . $_POST['temperature'];
$var = str_replace(" ", "%20", $var);
include($var);
}
?>
<?php include("https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/templates/footer.php"); ?>
</body>
</html>
<file_sep>//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
package com.example.honoursproject;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class UpdateInformation extends AppCompatActivity {
String doctorName;
String email;
String json;
String Name;
String Mobile;
Boolean Parkinsons;
Boolean Other;
Boolean Dementia; //setup globals
FormVerfication formCheck = new FormVerfication(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_information);
setupFields(); //set the fields
}
private Void setupFields(){
doctorName = getIntent().getStringExtra("doctor");
email = getIntent().getStringExtra("email");
json = getIntent().getStringExtra("json"); //get data from previous activity
EditText doctor = findViewById(R.id.editText6);
doctor.setText(doctorName); //set the doctor field
try { //decode the JSON
JSONObject userJson = new JSONObject(json);
Mobile = userJson.getString("Mobile");
Name = userJson.getString("name");
Parkinsons = userJson.getBoolean("Parkinsons");
Dementia = userJson.getBoolean("Dementia");
Other = userJson.getBoolean("Other");
EditText Phone = findViewById(R.id.editText9);
Phone.setText(Mobile);
EditText patientName = findViewById(R.id.editText3);
patientName.setText(Name);
}
catch (Exception e) {
Log.d("fail",json);
Log.d("fail","fail");
}
return null;
}
public void nameChange(View v ){ //change the name for a user
try {
EditText editText = findViewById(R.id.editText3);
Name = editText.getText().toString();
if (Boolean.toString(formCheck.simpleCheck(Mobile)).equals("true")){
formCheck.errorFormat();
}
else {
JSONObject jsonObject = new JSONObject(json);
jsonObject.remove("name");
jsonObject.put("name", Name);
json = jsonObject.toString();
}
}
catch (JSONException e){
formCheck.error();
e.printStackTrace();
}
String file = json;
String type = "Json";
if (Boolean.toString(formCheck.simpleCheck(Mobile)).equals("true")){
formCheck.error();
}
else {
UpdateInformationWorker backgroundWorker = new UpdateInformationWorker(this);
backgroundWorker.execute(type, file, email, "nameChange");
}
}
public void doctorChange(View v ){ //change the doctor for a user
String type = "Doctor";
EditText editText = findViewById(R.id.editText6);
String doctorName = editText.getText().toString();
if (Boolean.toString(formCheck.mobileCheck(Mobile)).equals("true")){
formCheck.errorFormat();
}
else {
if (Boolean.toString(formCheck.simpleCheck(doctorName)).equals("true")) {
formCheck.error();
} else {
UpdateInformationWorker backgroundWorker = new UpdateInformationWorker(this);
backgroundWorker.execute(type, doctorName, email, "doctorChange");
}
}
}
public void mobileChange(View v ){ // change a user's mobile number
try {
EditText editText = findViewById(R.id.editText9);
Mobile = editText.getText().toString();
if (Boolean.toString(formCheck.intCheck(Mobile)).equals("true")){
formCheck.errorFormat();
}
else {
JSONObject jsonObject = new JSONObject(json);
jsonObject.remove("Mobile");
jsonObject.put("Mobile", Mobile);
json = jsonObject.toString();
}
}
catch (JSONException e){
e.printStackTrace();
}
String file = json;
String type = "Json";
if (Boolean.toString(formCheck.simpleCheck(Mobile)).equals("true")){
formCheck.error();
}
else {
UpdateInformationWorker backgroundWorker = new UpdateInformationWorker(this);
backgroundWorker.execute(type, file, email, "mobileChange");
}
}
}
<file_sep><!--
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
<?php include("templates/header.php"); ?>
</head>
<body>
<!-- Start of page content -->
<div class="container my-3">
<h1>Login</h1>
<p>Please enter your details on this page to login to your account or <a class="link" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/signup">register as a new user</a> if you do not already have an account.</p>
<hr>
<div id="response"></div> <!-- Response will go here -->
<form method="post">
<label for="email">Email</label>
<input class="form-control" type="text" placeholder="Enter Email" name="email" required>
<label for="password">Password</label>
<input class="form-control" type="password" placeholder="Enter Password" name="password" required>
<button type="submit" class="form-control btn btn-success mt-3">Login</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { //get user data
include("../Controller/medicalLogin.php");
$login = LoginMedical( $_POST['email'], $_POST['password']);
if ($login == null){
echo "Invalid Entry";
}
else {
session_start();
$_SESSION['userData'] = $login;
echo "Success";
header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/landing');
}
}
?>
</div>
<!-- End of page content -->
<?php include("templates/footer.php"); ?>
<!-- Start of AJAX script -->
<!-- End of AJAX script -->
</body>
</html>
<file_sep>package com.example.honoursproject;
import android.app.AlertDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import java.util.regex.Pattern;
public class FormVerfication {
Context context; //get the context
FormVerfication(Context ctx){
context = ctx;
}
public Boolean simpleCheck(String value){ //checks for special characters
Pattern regex = Pattern.compile("[$&+,:;=\\\\?@#|/'<>.^*()%!-]");
if (regex.matcher(value).find()) {
Log.e("TTT", "SPECIAL CHARS FOUND");
return true;
}
else{
return false;
}
}
public Boolean stringCheck(String value){ //checks for integer characters
Pattern regex = Pattern.compile("[0-9]");
if (regex.matcher(value).find()) {
Log.e("TTT", "SPECIAL CHARS FOUND");
return true;
}
else{
return false;
}
}
public Boolean intCheck(String value){ //checks for string characters
Pattern regex = Pattern.compile("[a-zA-Z]");
if (regex.matcher(value).find()) {
Log.e("TTT", "SPECIAL CHARS FOUND");
return true;
}
else{
return false;
}
}
public Boolean mobileCheck(String value){ //checks for a correct mobile number
if (value.length() != 11 || intCheck(value)){
errorFormat();
return true;
}
else return false;
}
public void error(){ //general error messages
Toast.makeText(context, "Error in your data entry",Toast.LENGTH_SHORT).show();
}
public void errorFormat(){ //incorrect format error message
Toast.makeText(context, "Error in the format of your data",Toast.LENGTH_SHORT).show();
}
}
<file_sep><!--
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->
<!DOCTYPE html>
<?php
session_start();
if (isset($_SESSION['userData']) == false){
header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login.php');
}
$data = json_decode($_SESSION['userData']);
$email = $data->email;
$name = $data->name;
?>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
<?php include("templates/header.php"); ?>
</head>
<body>
<?php include("templates/nav.php"); ?>
<div class="header">
<a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index"><h1>Patient Messenger</h1></a>
<h2>Dr <?=$name?></h2>
<h3><a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/results.php">View Patient Results</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/advice.php">Give Advice to Patients</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/landing.php">Home</a></h3>
</div>
<h4>Select a patient to message</h4>
<form method="post">
<label for="email">Email</label>
<input class="form-control" type="text" placeholder="Enter Email" title="Please ensure the email address is valid." name="email" required>
<button id="submit" type="submit" class="form-control btn btn-success mt-3">Select Patient</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { //get user data
include("../Controller/getMessagesM.php");
$email = $_POST['email']; // required
$message = getMessages($_POST['email']);
$message = json_decode($message);
if ($message == null){
echo "Invalid Entry";
}
else {
for ($i=0; $i<sizeof($message);$i++){
if ($message[$i]->doctor == 1){
echo "<b>Dr " . $name . ": </b>" . $message[$i]->message . "</br></br>";
}
else{
echo "<b>Patient: </b>" . $message[$i]->message . "</br></br>";
}
}
}
}
if (isset($message)){
echo "<form method=post>
<label for=email>Enter Message</label>
<input class='form-control' type='text' placeholder='Enter Message' name='message' required>
<button id='submit' type='submit' class='form-control btn btn-success mt-3'>Send Message</button>
</form>
";
}
?>
<?php include("templates/footer.php"); ?>
</body>
</html><file_sep>//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
package com.example.honoursproject;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ScrollView;
import org.json.JSONObject;
public class speakDoctor extends AppCompatActivity {
String doctorName;
String email;
FormVerfication formCheck = new FormVerfication(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speak_doctor);
doctorName = getIntent().getStringExtra("doctor"); //retrieve the doctor and the user's email from the previous activity
email = getIntent().getStringExtra("email");
getMessages();
}
private void getMessages(){
String type = "getMessages";
messagesWorker backgroundWorker = new messagesWorker(this);
backgroundWorker.execute(type, email, doctorName); //start the background worker to fetch the previous messages
}
public void sendMessage(View view){ //send a message to server
String type = "sendMessage";
EditText editText = findViewById(R.id.editText4);
String Message = editText.getText().toString();
if (Boolean.toString(formCheck.simpleCheck(Message)).equals("true")){ //check the message sent passes security checks
formCheck.error();
}
else {
messagesWorker backgroundWorker = new messagesWorker(this);
backgroundWorker.execute(type, email, Message); //message passes send to the background worker
getMessages(); //update the message thread
}
}
}
<file_sep>Link to Web App - https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index
for system diagram use - https://www.draw.io/
Gantt Chart - created using project Libre (free and open source)
Email/password for Mobile App - <EMAIL>/password
email/password for web app - <EMAIL>/password
<file_sep><!--
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->
<!DOCTYPE html>
<?php
session_start();
if (isset($_SESSION['userData']) == false){
header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login.php');
}
?>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index">
<?php include("templates/header.php"); ?>
</head>
<body>
<?php include("templates/nav.php"); ?>
<div class="header">
<a href="index"><h1>Patient Results</h1></a>
<h3><a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/landing">Home</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/advice" >Give Advice to Patients</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/messenger">Patient Chats</a></h3>
</div>
<h4>Select a patient to view their results</h4>
<form method="post">
<label for="email">Email</label>
<input class="form-control" type="text" placeholder="Enter Email" title="Please ensure the email address is valid." name="email" required>
<button id="submit" type="submit" class="form-control btn btn-success mt-3">Select Patient</button> <!--Select a patient -->
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { //get user data
include("../Controller/getResultsM.php");
$results = getReadings($_POST['email']);
$heartRate = getBPM($_POST['email']);
$weight = getWeight($_POST['email']);
$temperature = getTemp($_POST['email']);
$Sys = getSys($_POST['email']);
$Dys = getDys($_POST['email']);
if ($results == null){
echo "Invalid Entry";
}
else {
$dataPoints = json_decode($results);
$dataPoints2 = json_decode($heartRate);
$dataPoints3 = json_decode($Sys);
$dataPoints4 = json_decode($Dys);
$dataPoints5 = json_decode($weight);
$dataPoints6 = json_decode($temperature); //get all the different results
}
}
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Hand Shake test Results"
},
axisY: {
title: "Number of registered shakes"
},
data: [{
type: "line",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
var chart = new CanvasJS.Chart("chartContainer1", {
title: {
text: "Heart Rate"
},
axisY: {
title: "Bpm (Beats per Minute)"
},
data: [{
type: "line",
dataPoints: <?php echo json_encode($dataPoints2, JSON_NUMERIC_CHECK); ?> //Canvas.JS functions for displaying graphs of data
}]
});
chart.render();
var chart = new CanvasJS.Chart("chartContainer2", {
title: {
text: "Patient's Weight"
},
axisY: {
title: "Kilograms"
},
data: [{
type: "line",
dataPoints: <?php echo json_encode($dataPoints5, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
var chart = new CanvasJS.Chart("chartContainer3", {
title: {
text: "Patient's Temperature"
},
axisY: {
title: "Degrees Celsius"
},
data: [{
type: "line",
dataPoints: <?php echo json_encode($dataPoints6, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
var chart = new CanvasJS.Chart("chartContainer4", {
title: {
text: "Blood Pressure"
},
axisX: {
valueFormatString: "MMM YYYY"
},
axisY2: {
title: "Millimeters of Hg"
},
toolTip: {
shared: false
},
legend: {
cursor: "pointer",
verticalAlign: "top",
horizontalAlign: "center",
dockInsidePlotArea: true,
itemclick: toogleDataSeries
},
data: [{
type:"line",
axisYType: "primary",
name: "Systolic",
showInLegend: true,
markerSize: 6,
dataPoints: <?php echo json_encode($dataPoints3, JSON_NUMERIC_CHECK); ?>
},
{
type: "line",
axisYType: "primary",
name: "Dystolic",
showInLegend: true,
markerSize: 6,
dataPoints: <?php echo json_encode($dataPoints4, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
function toogleDataSeries(e){
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else{
e.dataSeries.visible = true;
}
chart.render();
}
}
</script>
</head>
<body>
<?php
for ($i = 0; $i<5; $i++){
if ($i == 0){
echo "<div id='chartContainer' style='height: 370px; width: 100%;'></div>";
}
else {
echo "<div id='chartContainer" . $i . "' style='height: 370px; width: 100%;'></div>";
}
}
?>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<?php include("templates/footer.php"); ?>
</body>
</html><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
$from = $_POST["email"];
$message = $_POST["message"];
$subject = $_POST["subject"];
// Validation
if (!preg_match('/^(?=.{5,80}$)[\S]+@[\S]+\.[\S]+$/', $from)) // Validate email
{
header("location: ../View/error");
exit;
}
if (!preg_match('/^.{1,1200}$/', $message)) // Validate message
{
header("location: ../View/error");
exit;
}
// Send email to movie recommender address
$to = "<EMAIL>";
$fullMessage = wordwrap("Elderly Helper - From: $from\n\n$message");
mail($to, 'Elderly Helper - ' . $subject, $fullMessage); //change
// Send email to sender to confirm that the message was sent
$fullMessage = wordwrap("You sent the following message to the Elderly Helper team under the subject \"$subject\":\n\n$message");
mail($from, 'Thank you for your feedback', $fullMessage);
header("location: ../View/messageSent");
?><file_sep><!--
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
<?php include("templates/header.php"); ?> <!--Include the header template -->
</head>
<body>
<?php include("templates/nav.php"); ?> <!--Include the nav template -->
<h1 style="text-align:center;">About the Project</h1>
<hr>
<div class="about">
<h3>Module Code : CMP400</h3>
<h3>Project Name : Implementing improved methods of regional care through the use of IoT, Mobile Devices and Website Applications</h3> <!--About the website -->
<h3>Developed By : <NAME></h3>
<h3>Project Supervisor : Dr <NAME></h3>
<p>Data entered into this site is purely for academical purposes and is never used within a medical environment.</p>
<p>This website has been setup as a submission for the Developer's fourth year Honours Project.</p>
</div>
<hr>
<div id = "boxes" class="center">
<h2>This project uses a blend of:</h2>
<div id = "leftbox">
<h3>Website Applications</h3>
<img src="https://bbvaopen4u.com/sites/default/files/styles/big-image/public/img/new/bbva-open-web-apps-progressive.jpg" alt="Italian Trulli">
<p>Hominem eos hac religio tentabo ginabor. Laxissimas objectivam eo percipitur distinctum ii industriam. Mei scopo ideis horum vel factu rei. Initio ad vereor posita possum si possim eo bitavi. Re novi vero mens in me ipse. Ad nolo ac unam dico in me. Is odoratu fallant vi vestiri percipi ex et. Confirmari respondebo videbuntur voluntates dum per intelligat. Admonitus dubitavit sui consistat uti inspiciam persuadet perfectum. </p>
</div>
<div id = "middlebox">
<h3>IoT Devices</h3>
<img src="https://images.idgesg.net/images/article/2019/01/industrial-iot-sensor-battery-100784076-large.jpg" alt="Italian Trulli">
<p>Pertinent lus infigatur una mox geometria distinguo. Apparet me nostris eo de probari. Manet omnis solis ea eo ipsis. Manibus si to dispari accepit me colligi. Debiliora potentiam una vis has componant terminari non. Perceptio habeantur sum naturalis hae objective eae ens. Cui permittere extensarum industriam iis excoluisse advertebam labefactat. Agi sed uno ponderibus materialis percurrere desiderant argumentis quapropter via. </p>
</div>
<div id = "rightbox">
<h3>Android Applications</h3>
<img src="https://cdn.vox-cdn.com/thumbor/ZTg0bT74DkPQhtZeCsO_MfQD4Sg=/0x0:2040x1360/1200x800/filters:focal(857x517:1183x843)/cdn.vox-cdn.com/uploads/chorus_image/image/59347755/DSCF3188.0.jpg" alt="Italian Trulli">
<p>Potentiale manifestam procederet id si. Tria bere post addi tur est uti. Co esto gnum re modo more loco. Theologiae ea se an durationis describere substantia si. Mea ibi halitus reliqua hic adeoque. Deficere existimo ab assignem ad continet creditum. Has enim hic sua odor novi amen fuse lor meae. </p>
</div>
</div>
<hr>
<?php include("templates/footer.php"); ?> <!--Include the footer template -->
</body>
</html>
<style>
#leftbox {
float:left;
text-align:center;
width:33%;
height:280px;
}
#middlebox{
float:left;
text-align:center;
width:33%;
height:280px;
}
#rightbox{
float:right;
text-align:center;
width:33%;
height:280px;
}
#boxes{
padding-bottom:400px;
}
</style> <file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("../Model/Readings.php");
$check = null;
$email = $_POST["email"];
$count = $_POST["count"];
$weight = $_POST["weight"];
$temp = $_POST["temperature"];
$hr = $_POST["hr"];
$dys = $_POST["dys"];
$sys = $_POST["sys"];
$doctor = $_POST["doctor"]; //recieve data from mobile device
$check = recordReading($email, $doctor, $count, $weight, $temp, $hr, $dys, $sys); //record the result
echo $check;
?><file_sep>//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
package com.example.honoursproject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class TestResultsWorker extends AsyncTask<String,Void,String>{
Context context;
String Email;
String type;
String type2;
List<String> Result;
List<String> Time;
List<String> HR ;
List<String> Weight ;
List<String> Temp ;
List<String> Sys ;
List<String> Dys; //setup global varibales
TestResultsWorker(Context ctx){
context = ctx;
} //get the context from previous activity
protected String doInBackground(String... params) {
type = params[0];
type2 = params[1];
if (type.equals("getResults")){
String urlAdvice = "https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/Controller/getResults.php"; //api location
Email = params[2];
try{
URL url = new URL(urlAdvice);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod(("POST"));
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("email", "UTF-8")+"="+ URLEncoder.encode(Email, "UTF-8"); //encode the user's email
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result = "";
String line="";
while ((line = bufferedReader.readLine()) != null){ //retrieve the results
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) { //catch any errors
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(String result) {
JSONArray obj = null;
if (type2.equals("getResults")) {
try
{
obj = new JSONArray(result); // make a JSONArray out of the json results retruned by the server
}
catch (JSONException e)
{
Log.d("failed","json parser failed");
}
Result = new ArrayList<String>(obj.length());
HR = new ArrayList<String>(obj.length());
Weight = new ArrayList<String>(obj.length());
Temp = new ArrayList<String>(obj.length());
Sys = new ArrayList<String>(obj.length());
Dys = new ArrayList<String>(obj.length());
Time = new ArrayList<String>(obj.length()); //set the lists to the size of the JSON string returned
for (int i = 0; i < obj.length(); ++i) {
try {
JSONObject o = obj.getJSONObject(i);
Result.add((String) (o.getString("result")));
HR.add((String) (o.getString("hr")));
Weight.add((String) (o.getString("weight")));
Temp.add((String) (o.getString("temp")));
Sys.add((String) (o.getString("sys")));
Dys.add((String) (o.getString("dys")));
Time.add((String) (o.getString("time"))); //add each value individually
}
catch (JSONException e) {
}
}
setupMultiGraphs(); //setup the graphs
}
if (type2.equals("retrieveResults")) { //for the handshake test on the main account activity (uses same functionality as previous)
try
{
obj = new JSONArray(result);
}
catch (JSONException e)
{
Log.d("failed","json parser failed");
}
Result = new ArrayList<String>(obj.length());
List<String> HR = new ArrayList<String>(obj.length());
List<String> Weight = new ArrayList<String>(obj.length());
List<String> Temp = new ArrayList<String>(obj.length());
List<String> Sys = new ArrayList<String>(obj.length());
List<String> Dys = new ArrayList<String>(obj.length());
Time = new ArrayList<String>(obj.length());
for (int i = 0; i < obj.length(); ++i) {
try {
JSONObject o = obj.getJSONObject(i);
Result.add((String) (o.getString("result")));
HR.add((String) (o.getString("hr")));
Weight.add((String) (o.getString("weight")));
Temp.add((String) (o.getString("temp")));
Sys.add((String) (o.getString("sys")));
Dys.add((String) (o.getString("dys")));
Time.add((String) (o.getString("time")));
}
catch (JSONException e) {
}
}
LineChart lineChart = ((Activity)context).findViewById(R.id.lineChart);
setupGraphs(lineChart, Result, "Hand Shake Test");
}
}
private void setupMultiGraphs(){
LineChart HeartR = ((Activity)context).findViewById(R.id.HeartR);
LineChart Hand = ((Activity)context).findViewById(R.id.Hand);
LineChart Weights = ((Activity)context).findViewById(R.id.Weight);
LineChart Temperature = ((Activity)context).findViewById(R.id.Temp);
LineChart Systolic = ((Activity)context).findViewById(R.id.Sys);
LineChart Dystolic = ((Activity)context).findViewById(R.id.Dys); //find the locations of each graph
setupGraphs(HeartR, HR, "Heart Rate BPM");
setupGraphs(Hand, Result, "Hand Shake Result");
setupGraphs(Weights, Weight, "Weight Kg");
setupGraphs(Temperature, Temp, "Temperature Degrees Celsius");
setupGraphs(Systolic, Sys, "Systolic BP");
setupGraphs(Dystolic, Dys, "Dystolic BP"); //enter all data into the graphs
}
private void setupGraphs(LineChart linechart, List<String> list, String type){
ArrayList<String> xAXES = new ArrayList<>();
ArrayList<Entry> yAXEScos = new ArrayList<>(); //x and y value data structures
int numDataPoints = list.size(); //get the size of the data for the graphs
for(int i=0;i<numDataPoints;i++){
Float cosFunction = Float.parseFloat(list.get(i));
yAXEScos.add(new Entry(cosFunction,i));
xAXES.add(i, Time.get(i)); //add the values to the x and y axes from the lists
}
String[] xaxes = new String[xAXES.size()];
for(int i=0; i<xAXES.size();i++){
xaxes[i] = String.valueOf(xAXES.get(i));
} //convert the xaxes to strings (needed for these type of graphs)
ArrayList<ILineDataSet> lineDataSets = new ArrayList<>();
LineDataSet lineDataSet1 = new LineDataSet(yAXEScos,type);
lineDataSet1.setDrawCircles(false);
lineDataSet1.setColor(Color.BLUE); //set colours (blue historic colour of the nhs)
lineDataSets.add(lineDataSet1);
linechart.setData(new LineData(xaxes, lineDataSets));
linechart.setVisibleXRangeMaximum(65f); //set the visibility
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
<file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
include("../Model/User.php");
function LoginMedical($email, $password){ //login functionality for medical professionals
$check = LoginM($email, $password);
if ($check != null){
return $check;
}
else {
return null;
}
}
?>
| a015aa434593e06158f96d6b4362e43c91827e61 | [
"Gradle",
"Java",
"Text",
"PHP",
"C"
] | 40 | PHP | AaronStones/Honours-Project | 5a5229e1669a9566a0c11468f9a98aec06886075 | de4d75c9ef9d0f0c4d9ec8e2fb19cc828a1be76c | |
refs/heads/master | <file_sep>//何も用いず2d回転
(function () {
'use strict';
const canvas = document.getElementById('normal_canvas');
canvas.height = 300;
canvas.width = 300;
const context = canvas.getContext('2d');
const image = new Image();
image.src = 'image/money.png';
image.onload = () => {
rotate();
}
let theta = 0;
function rotate() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.save();
context.translate(canvas.width / 2, canvas.height / 2);
context.rotate(++theta * Math.PI / 180);
context.translate(-canvas.width / 2, -canvas.height / 2);
context.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
context.restore();
setTimeout(rotate, 15);
}
}());
//Grimoire.js を利用して2d回転
gr.registerComponent('Rotate2d', {
attributes: {
speed: {
default: 1,
converter: 'Number'
}
},
$mount: function () {
this.theta = 0;
},
$update: function () {
this.theta += this.getAttribute('speed');
this.node.setAttribute('rotation', 0 + ',' + 0 + ',' + -this.theta);
}
});
//Grimoire.js を利用して3d回転
gr.registerComponent('Rotate3d', {
attributes: {
speed: {
default: 1,
converter: 'Number'
}
},
$mount: function () {
this.theta = 0;
},
$update: function () {
this.theta += this.getAttribute('speed');
this.node.setAttribute('rotation', 25 + ',' + -this.theta + ',' + 0);
}
});
<file_sep># [pronama_spinner](https://ipolyomino.github.io/pronama_spinner/)
プロ生ちゃんを回転させることができます.
## Requirement
Node.js 8.x
Grimoire.jsを利用するために,ローカルサーバを立てる必要があります.
このリポジトリではExpressを利用していますが,ご自身で立てることができるのであれば Pythonでも Rubyでも 問題ありません.
## Usage
```bash
git clone <EMAIL>:iPolyomino/pronama_spinner.git
cd pronama_spinner
npm install
node app.js
```
http://localhost:3000/ にアクセスすると,確認することができます.
## Author
[Hagi](https://github.com/iPolyomino)
## Link
[プロ生ちゃん](http://pronama.azurewebsites.net/pronama/)
| 5f103bb116285041c3bdc75b1c3cf8e375d0361e | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | iPolyomino/pronama_spinner | ec5413d4f2e0d2a8e901a0e7f0ca7bf4f1b8d29c | 9af108f91fbcefb95371cf74903baecba1b8e1b6 | |
refs/heads/main | <file_sep>class CarsController < ApplicationController
def index
cars = find_company(params[:company_id]).cars.select(:id, :name, :price)
render json: cars, status: :ok
end
def show
car = find_car(params[:id])
render json: car, status: :ok
end
def create
car = find_company(params[:company_id]).cars.new(car_params)
if car.save
car = find_car(car.id)
render json: car, status: 201
else
render json: {errors: car.errors}, status: :unprocessable_entity
end
end
def update
car = Car.find(params[:id])
if car.update_attributes(car_params)
car =car(params[:id])
render json: car, status: :ok
else
render json: {errors: car.errors}, status: :unprocessable_entity
end
end
def destroy
car = Car.find(params[:id])
car.destroy
render json: car, status: 204
end
private
def car_params
params.require(:car).permit(:name, :price)
end
def find_company company_id
Company.find(company_id)
end
def find_car id
Car.select(:id, :name, :price).where(id: id)
end
end<file_sep>с1 = Company.create({name: 'MMM'})
c2 = Company.create({name: 'KFC'})
c1.cars.create({name: '<NAME>', price: 627000})
c1.cars.create({name: '<NAME>', price: 337000})
c1.cars.create({name: 'Lada 1488', price: 145000})
c2.cars.create({name: '<NAME>', price: 228000})
c2.cars.create({name: '<NAME>', price: 181000})
c2.cars.create({name: 'Porche 911', price: 8450000})
<file_sep>class CompaniesController < ApplicationController
def index
companies = Company.left_outer_joins(:cars)
.select('companies.id, companies.name, COUNT(cars.id) AS cars_count')
.group('companies.id, companies.name')
render json: companies, status: :ok
end
def create
company = Company.new(com_params)
if company.save
company = find_company(company.id)
render json: company, status: 201
else
render json: {errors: company.errors}, status: unprocessable_entity
end
def show
company = find_company(params[:id])
render json: company, status: :ok
end
def update
company = Company.find(params[:id])
if company.update_attributes(com_params)
render json: company, status: :ok
else
# Что-то пошло не так
render json: {errors: company.errors}, status: :unprocessable_entity
end
end
def destroy
company = company.find(params[:id])
company.destroy
render json: company, status: 204
end
private
def com_params
params.require(:company).permit(:name)
end
def find_company id
Company.left_outer_joins(:cars)
.select('companies.id, companies.name, COUNT(cars.id) AS cars_count')
.where(id: id)
.group('categories.id, categories.name')
end
end
end
<file_sep>class Company < ApplicationRecord
has_many :cars, dependent: :destroy
validates :name, presence: true
end | 91c9f2907d4e61d1172e54846078047fbf047e1e | [
"Ruby"
] | 4 | Ruby | Stepan0305/cars_api | 318daa718da86dffd2c427a07c11e2c91479b0e7 | a2b63bf5618fd2774970ad0724ef28cb4ba825a8 | |
refs/heads/master | <file_sep># Library-Project-w-Firebase-
This is a library system that keeps book information on firebase databases.
it gives the user the functionality to remove and add book information to the library.
<file_sep>const display = document.querySelector('#display');
//web app's Firebase configuration
let firebaseConfig = {
apiKey: "AIzaSyDu2eLLFghcX_1I_ZIMxUbGyAvE1NyoNp8",
authDomain: "book-library-serverside.firebaseapp.com",
databaseURL: "https://book-library-serverside.firebaseio.com",
projectId: "book-library-serverside",
storageBucket: "book-library-serverside.appspot.com",
messagingSenderId: "144062401901",
appId: "1:144062401901:web:ee3cfc2b0d42d65e9a1e64",
measurementId: "G-FRFCCSCR89"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
console.log(firebase);
// array of objects that act as a library
let myLibrary=[];
let database= firebase.database();//stores firebase database
let ref= database.ref('Library')// creates and refers to 'library' tree
removeAllChildNodes(display);
listBooks();// displays books cl
// object that stores the book info
function book (title, author,pages,read)
{
this.title=title,
this.author=author,
this.pages=pages,
this.readStatus=read
}
// creates a book and store it in the array
function createBook()
{
let bookData=addBook();// book information returned as an array
let bookObject =new book(bookData[0],bookData[1],bookData[2],bookData[3]);// stores book data in respective locations
ref.push(bookObject); // **************pushes book to Database online
removeAllChildNodes(display);
listBooks();
}
//pulls down books from database to display on screen.
function listBooks()
{
removeAllChildNodes(display)
ref.on('value',receiveData, errorData); //calls on database to send values.
}
// accepts the respective values for a new book
function addBook()
{
let title,author,pages,readStatus;
//stores the values from the form in respective variables
title= document.getElementsByName("title")[0].value;
author=document.getElementsByName("author")[0].value;
pages= document.getElementsByName("pages")[0].value;
// gets read status of book if none is selected, sets the default to not read
if(document.getElementById("read").checked)
{
readStatus='Read';
}
else{
readStatus='Not Read';
}
return [title,author,pages,readStatus]
}
//used to clear display on client side
function removeAllChildNodes(parent) {
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}
// ************************************************************************************************************
// ************************************************************************************************************
// ************************************************************************************************************
// ************************************************************************************************************
// this is a big function that will be refactored in the next edit
// it receives the data from the Database, displays and manipulates it.
function receiveData(allData)
{
let library=allData.val();
//if the library is empty, displays the appropriate message else Displays the book client side.
if (library==null)
{
removeAllChildNodes(display);
let empty=document.createElement('div');
empty.textContent='The library is empty. Please add a book';
empty.style.fontSize='2.5em';
display.appendChild(empty);
}
else {
let keysList=Object.keys(library); // returns an array of books in Library
// For each element display its data client side.
keysList.forEach(e=>{
//create HTML elements to display book data
let title=document.createElement('p');
let author=document.createElement('p');
let pages=document.createElement('p');
let readStatus=document.createElement('p');
let linebreak = document.createElement("br");
let button=document.createElement('button');
let buttonStatus=document.createElement('button');
let card= document.createElement("div");
//display the data to the screen
title.textContent=`${library[e].title}` ;
card.appendChild(title);
card.appendChild(linebreak);
author.textContent=`Author: ${library[e].author}` ;
card.appendChild(author);
card.appendChild(linebreak);
pages.textContent=`Pages: ${library[e].pages}`
card.appendChild(pages);
card.appendChild(linebreak);
readStatus.textContent=`${library[e].readStatus}`
readStatus.setAttribute('id',`para${e}`);
card.appendChild(readStatus);
card.appendChild(linebreak);
button.textContent='remove';
button.setAttribute('id',`${e}`);
button.setAttribute('name','removeButton');
card.appendChild(linebreak);
card.appendChild(button);
buttonStatus.textContent='Read/Unread';
buttonStatus.setAttribute('id',`status${e}`);
card.appendChild(buttonStatus);
card.setAttribute('class','cards');
card.setAttribute( 'id',`card${e}`);
display.appendChild(card);
document.getElementById(`${e}`).addEventListener("click", removeBook);//gets ID of book to remove
document.getElementById(`status${e}`).addEventListener("click", toggleRead); //gets ID of book to change status for
})
// changes the status of the 'Read' attribute
function toggleRead(e)
{
let str=`${e.target.id}`;// stringify id.
let strSliced=str.slice(6); //slices the 'status' section from the id to made it useful for indexing. Returns only the key.
if(library[strSliced].readStatus=='Read')
{
library[strSliced].readStatus='Not Read';// changes the 'read' attribute
updateReadStatus(library[strSliced].readStatus,library[strSliced].title,
library[strSliced].pages,library[strSliced].author,strSliced);// updates record in the database
removeAllChildNodes(display);
listBooks();
}
else{
library[strSliced].readStatus='Read';// changes the 'read' attribute
updateReadStatus(library[strSliced].readStatus,library[strSliced].title,
library[strSliced].pages,library[strSliced].author,strSliced);// updates record in the database
removeAllChildNodes(display);
listBooks();
}
}
//takes the value of updated record and updates the data base.
function updateReadStatus(readStatus1,title1,pages1,author1,id)
{
//updates record utilising a call back function.
firebase.database().ref('Library/'+ id).set({
author:author1,
pages:pages1,
readStatus:readStatus1,
title:title1
}, function(error) {
if (error) {
Console.log(`error!!`);
} else {
console.log(`write successfully`);
}
});
}
// Removes book from Database and Client
function removeBook(e)
{
let kIndex;
// matches the ID of the 'remove' button that was clicked with its corresponding index in keysList
keysList.forEach((element,index) =>{
if(element==e.target.id)
{kIndex=index};
})
ref.child(keysList[kIndex]).remove();// removes selected book from Database.
removeAllChildNodes(display);
listBooks(); // redisplays books available.
}
}
}
//used to notify user when no data is received from Server.
function errorData(err)
{
removeAllChildNodes(display);
let empty=document.createElement('div');
empty.textContent='No data received from database';
empty.style.fontSize='2.5em';
display.appendChild(empty);
}
| ea05d957d545eeb15e420c83020b1411feaf0bc5 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | R11Sr/Library-Project-w-Firebase- | e5a80d98336b535af6376ceca1c04d10177789d0 | 7699d6b8c2147cd1fe29eae77fdd8b1a0a559be8 | |
refs/heads/master | <file_sep>import React, { Component } from 'react';
class App extends Component {
constructor() {
super()
this.state = {
tasks: [
{ id: 1, name: "<NAME>", done: false },
{ id: 2, name: "<NAME>", done: true },
{ id: 3, name: "<NAME>", done: false }
],
newTask: '',
count: 4,
}
}
textChange(event) {
this.setState({
newTask: event.target.value
})
}
addItem(event)
{
event.preventDefault();
if(this.state.newTask !== '')
{
this.setState({
tasks: this.state.tasks.concat({id: this.state.count++, name:this.state.newTask, done: false}),
newTask: ''
})
}
}
chequear(index)
{
this.setState({
tasks: [
{
id: this.state.tasks[index].id,
name: this.state.tasks[index].name,
done: !this.state.tasks[index].done
}
]
})
}
render() {
return (
<div className="wrapper">
<div className="list">
<h3>Por hacer:</h3>
<ul className="todo">
{this.state.tasks.map((task, index) => <li key={task.id} className={task.done ? "done" : ""} onClick={this.chequear.bind(this, index)}>{task.name}</li>)}
</ul>
<form onSubmit={this.addItem.bind(this)}>
<input className="error" type="text" id="new-task" placeholder="Ingresa una tarea y oprime Enter" value={this.state.newTask} onChange={this.textChange.bind(this)} required/>
</form>
</div>
</div>
)
}
}
export default App; | 8bca74fad9004d4eccf2f00aba99f54c9760316f | [
"JavaScript"
] | 1 | JavaScript | CAMILON88/krqwer45 | 93d7addd1d73dec5d3c837a5f7e870e8829eefe3 | 6e9956dea30f4d19ab2b4571fd9e343b449b52a3 | |
refs/heads/master | <file_sep><?php
require_once __DIR__ . '/vendor/autoload.php';
use CompanyName\ShoppingCart\Cart as Cart;
use CompanyName\ShoppingCart\Item as Item;
// Entering file by console input
$input = $argv[1];
// Decoding the input and adding items to the cart
$cart = new Cart();
$cart->decodeTextInput($input);
// $cart->addItem("mbp", "Macbook Pro", 2, 29.99, "EUR");
// $cart->addItem("zen", "Asus Zenbook", 3, 99.99, "USD");
// $cart->addItem("mbp", "Macbook Pro", 5, 100.09, "GBP");
// $cart->addItem("zen", "Asus Zenbook", -1);
// $cart->addItem("len", "Lenovo P1", 8, 60.33, "USD");
// $cart->addItem("zen", "Asus Zenbook", 1, 120.99, "EUR");
//print_r($cart->getItems());
// Printing out total price
echo "Current cart value is: ".$cart->getTotalPrice("EUR")."EUR\n";
<file_sep># ShoppingCartTask
The shopping cart solution for the interview.
It was unclear what kind of input should application accept and what kind of output should it produce.
To run the application, open project directory in command line and type:
php index.php input.txt
<file_sep><?php
namespace CompanyName\ShoppingCart;
use CompanyName\ShoppingCart\Item as Item;
use CompanyName\ShoppingCart\ExchangeCurrency as ExchangeCurrency;
class Cart
{
protected $items = array();
public function addItem($id, $name, $quantity, $price = 0, $currency = null)
{
// If quantity -1, and cart not empty remove item from list
if($quantity <= -1 && sizeof($this->items) != 0){
$this->removeEntry($id);
}else {
$this->addEntry($id, $name, $quantity, $price, $currency);
}
}
public function decodeTextInput($textInput)
{
// Read each line
if ($fh = fopen($textInput, 'r')) {
while (!feof($fh)) {
$line = fgets($fh);
// Split string by semicolons
$inputs = explode(";", $line);
// If input is empty, set it to null
if(!isset($inputs[0])) $inputs[0] = null;
if(!isset($inputs[1])) $inputs[1] = null;
if(!isset($inputs[2])) $inputs[2] = null;
if(!isset($inputs[3])) $inputs[3] = null;
if(!isset($inputs[4])) $inputs[4] = null;
// Add item to the cart TRIM whitespaces on currency string
$this->addItem($inputs[0], $inputs[1], $inputs[2], $inputs[3], trim($inputs[4]));
}
fclose($fh);
}
}
private function removeEntry($id)
{
// Search $items array for $item with $id
foreach ($this->items as $item) {
// If $item with $id found
if($item->getID() == $id){
// Get $item index in $items array
$arrayIndex = array_search($item, $this->items);
// Remove item from $items array
unset($this->items[$arrayIndex]);
}
}
}
private function addEntry($id, $name, $quantity, $price, $currency)
{
$item = new Item($id, $name, $quantity, $price, $currency);
array_push($this->items, $item);
}
public function getItems()
{
return $this->items;
}
public function getTotalPrice($currency){
$exchange = new ExchangeCurrency();
$totalPrice = 0;
// Iterate over all products
foreach ($this->items as $item) {
// If currency is different than required then convert to required and add to total price
if($item->getCurrency() != $currency){
$totalPrice += $exchange->exchangeMoney($item->getPrice(), $item->getCurrency(), $currency) * $item->getQuantity();
}else{
$totalPrice += $item->getPrice() * $item->getQuantity();
}
}
return $totalPrice;
}
}
<file_sep># Shopping cart app
## Technical Requirements
- PHP7 +
- Recommended to use `Composer` for autoloading
- 3rd party libraries can be used if needed
- App should be executed from console
- Solution's source code should be provided in a GIT repository
## Task
### User story
Client asked us to develop Shopping cart app where customers can add, update and remove products. Products can be added in different quantities and currencies. At the moment, our client wants to support 3 currencies: `EUR`, `USD` and `GBP` with possibility to add more in the future. After every newly added/removed product the total balance of the cart should update.
### Requirements
- Supported currencies `EUR`, `USD` and `GBP`
- Exchange rates for currencies: `EUR:USD` - `1:1.14`, `EUR:GBP` - `1:0.88`
### Data
Data is stored in text file where each column is separated by `;` character. There are 5 columns in each row:
1. Unique product identifier
2. Product name
3. Product quantity
4. Product price
5. Product's price currency
Product quantity column describes customer action. If quantity is 1 or more then product is being added/updated, if quantity is -1 or less, then product is being removed from shopping cart.
See example data set is below.
```
mbp;Macbook Pro;2;29.99;EUR
zen;Asus Zenbook;3;99.99;USD
mbp,Macbook Pro;5,100.09,GBP
zen;Asus Zenbook;-1;;
len;Lenovo P1;8;60.33;USD
zen;Asus Zenbook;1;120.99;EUR
```
<file_sep><?php
namespace CompanyName\ShoppingCart;
// Exchanges money based on currency. Base exchange rate connected to EUR 1:1
class ExchangeCurrency{
private $exchangeRate = array();
// Currency exchange rates stored in json file in current directory
private $exchangeRatePath = __DIR__ . '/currencyExchangeRates.json';
public function __construct()
{
//reads currency rates from json file and stores into an array
$this->readJsonConversionRates($this->exchangeRatePath);
}
// Money conversion formula x = money * requiredMoney / currentMoney
public function exchangeMoney($money, $currentCurrency, $requiredCurrency)
{
return $money * $this->exchangeRate[$requiredCurrency] / $this->exchangeRate[$currentCurrency];
}
public function getExchangeRates()
{
return $this->exchangeRate;
}
// Add rate ir edit existing one
public function addRate($rateToEuro, $acronym)
{
$this->exchangeRate[$acronym] = $rateToEuro;
$this->saveCurrenciesToFile();
}
// Remove rate from currency list
public function removeRate($acronym){
unset($this->exchangeRate[$acronym]);
$this->saveCurrenciesToFile();
}
private function saveCurrenciesToFile(){
$encodedRates = json_encode($this->exchangeRate);
file_put_contents("$this->exchangeRatePath", $encodedRates);
}
private function readJsonConversionRates($exchangeRatePath){
$file = file_get_contents($exchangeRatePath);
$this->exchangeRate = json_decode($file, true);
}
//Hellper method to push associative array
function array_push_assoc($array, $key, $value){
$array[$key] = $value;
return $array;
}
}
| 700d23dc918e28e9a579155e8decae42ad1899a7 | [
"Markdown",
"PHP"
] | 5 | PHP | aleksiuno/ShoppingCartTask | 87d6da3110a6cff4bf6e3740e233733d505a4d8a | 4aba4c3fcd5aaf77350f4777943de6ed6bffb1c4 | |
refs/heads/main | <file_sep>
INSERT INTO burgers (burger_name, devoured) VALUES ("baconator", true);
INSERT INTO burgers (burger_name, devoured) VALUES ("veggieanotr", false);
INSERT INTO burgers (burger_name, devoured) VALUES ("cheese burger", true);
<file_sep># Eat-da-burger-webpage
## Description
The project is a full-stack web application of a burger logger MySQL, Node, Express, Handlebars and a homemade ORM.
## Table of Contents
* [Usage](#usage)
* [Screenshots](#screenshots)
* [Technologies-used](#technologies-used)
## Usage
The project has a to list of burgers that are devoured and those that are not. Those burgers can be deleted, devoured or not devoured and that will move them to their respected categories. The user also has the option to create their own burger and chose a option of devoured or not devoured.
## Technologies-used
Eat-da-burger uses handlebars/css and javascipt for the front-end as well as Node, Express and MySQL for the database.
## Screenshots
![Startpage](./public/assets/pictures/eatdaburger4.png)
![Devoured](./public/assets/pictures/eatdaburger2.png)
![Not Devoured](./public/assets/pictures/eatdaburger3.png)
![Deleted](./public/assets/pictures/eatdaburger1.png)
| 50b3473d65c602dbd057f3121bde27906f40d12b | [
"Markdown",
"SQL"
] | 2 | SQL | mdelgado1128/Eat-da-burger-webpage | 30cdc9afd5ab5d9c9ba6187a7afe0b862c45d710 | ad23caab5f0c0af1d72e285616a91879c351c7a6 | |
refs/heads/master | <repo_name>P5ina/DJMath<file_sep>/DJMath.py
import discord
import youtube_dl
import subprocess
import urllib
import os
import asyncio
from bs4 import BeautifulSoup
from discord.ext import commands
from discord import opus
OPUS_LIBS = ['libopus-0.x86.dll', 'libopus-0.x64.dll', 'libopus-0.dll', 'libopus.so.0', 'libopus.0.dylib']
def load_opus_lib(opus_libs=OPUS_LIBS):
if opus.is_loaded():
return True
for opus_lib in opus_libs:
try:
opus.load_opus(opus_lib)
return
except OSError:
pass
raise RuntimeError('Could not load an opus lib. Tried %s' %
(', '.join(opus_libs)))
load_opus_lib()
TOKEN = str(os.environ.get('TOKEN'))
bot = commands.Bot(command_prefix='!')
players = {}
queues = {}
def check_queue(server):
id = server.id
print('Checking queue with id: {}'.format(id))
if id in queues and queues[id] != []:
print('Is not empty.')
player = queues[id].pop(0)
print(player.title)
players[id] = player
player.start()
else:
from discord.compat import run_coroutine_threadsafe
channel = bot.get_channel('498141280199507969')
print('Retrying...')
coro = replay_song(server)
fut = run_coroutine_threadsafe(coro, bot.loop)
try:
fut.result()
except:
print('error')
pass
async def replay_song(server):
voice_client = bot.voice_client_in(server)
player = await voice_client.create_ytdl_player('https://www.youtube.com/watch?v=bM7SZ5SBzyY', after=lambda: check_queue(server))
players[server.id] = player
player.start()
@bot.event
async def on_ready():
print('DJ bot is online')
radio_channel = bot.get_channel('498135784503902218')
await bot.join_voice_channel(radio_channel)
channel = bot.get_channel('498499824316973077')
#await bot.send_message(channel,'Бот обновлен:\n1.Подгрузка видео быстрее\n2.Выводится длина видео')
await replay_song(channel.server)
print('Bot joined to channel')
@bot.command(pass_context = True)
@commands.has_role('Тестер ботов')
async def join(ctx):
await bot.join_voice_channel(bot.get_channel('498135784503902218'))
print ('Joining to channel: {}'.format(bot.get_channel('498135784503902218')))
@bot.command(pass_context = True)
@commands.has_role('Тестер ботов')
async def leave(ctx):
server = ctx.message.server
voice_client = bot.voice_client_in(server)
await voice_client.disconnect()
print('DJ is leaving')
@bot.command(pass_context = True)
async def play(ctx):
search_text = ctx.message.content[6:]
print ('\n{}\n'.format(search_text))
print ('Channel id: {}'.format(ctx.message.channel.id))
server = ctx.message.server
channel = ctx.message.channel
voice_client = bot.voice_client_in(server)
player = await voice_client.create_ytdl_player(search(search_text), after=lambda: check_queue(server))
if player.duration < 361:
if server.id in queues and queues[server.id] != []:
queues[server.id].append(player)
await bot.send_message(channel,'Добавлено в очередь: `{}`. Благодарим за терпение.'.format(player.title))
elif server.id in players and not players[server.id].is_done():
print(players[server.id].is_done())
queues[server.id] = [player]
await bot.send_message(channel,'Добавлено в очередь: `{}`. Благодарим за терпение.'.format(player.title))
else:
players[server.id] = player
await bot.send_message(channel,'Сейчас играет: `{}`. Наслаждайтесь!'.format(player.title))
player.start()
else:
await bot.send_message(channel,'Видео: `{}`, слишком длинное: {}:{}!'.format(player.title, player.duration / 60, player.duration % 60))
@bot.command(pass_context = True)
@commands.has_role('Тестер ботов')
async def pause(ctx):
id = ctx.message.server.id
players[id].pause()
@bot.command(pass_context = True)
@commands.has_role('Тестер ботов')
async def resume(ctx):
id = ctx.message.server.id
players[id].resume()
@bot.command(pass_context = True)
async def skip(ctx):
author = ctx.message.author
server = ctx.message.server
channel_bot = bot.get_channel('505846043733262338')
await bot.send_message(channel_bot, 'b.level '+ author.mention)
msg = await bot.wait_for_message(author=server.get_member('496328098325725214'),channel=channel_bot)
if int(msg.content) >= 10:
id = ctx.message.server.id
players[id].stop()
@bot.command(pass_context = True)
async def queue(ctx):
id = ctx.message.server.id
channel = ctx.message.channel
if id in players and id in queues:
outstr = 'Сейчас играет: {}\nОчередь:\n'.format(players[id].title)
for i in range(len(queues[id])):
outstr += '{}: {}\n'.format(i+1, queues[id][i].title)
else:
outstr = 'Ничего нет'
await bot.send_message(channel, outstr)
def search(text):
query = urllib.parse.quote(text)
print('Make query: {}'.format(query))
url = "https://www.youtube.com/results?search_query=" + query
print('Finding in this url: {}'.format(url))
response = urllib.request.urlopen(url)
html = response.read()
soup = BeautifulSoup(html)
result = 'https://www.youtube.com' + soup.findAll(attrs={'class':'yt-uix-tile-link'})[0]['href']
print('Finded: {}'.format(result))
return result
bot.run(TOKEN)
<file_sep>/requirements.txt
discord
discord[voice]
youtube-dl
bs4
PyNaCl
opuslib
ffmpeg
| bb4b3472c0f17977fc29cb37c3a116b6eaaa17bb | [
"Python",
"Text"
] | 2 | Python | P5ina/DJMath | 877c230c13b73c2dc489a6d71dc2fbaec3c31c2d | 43b41bfb3395e1630d4e27384155d077cd41fce3 | |
refs/heads/master | <file_sep>package Runner;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions ( features = "src/test/java/Feature",
glue={"StepDefinition"},
plugin = {"pretty:STDOUT",
"html:Reports/cucumber-pretty","junit:target/surefire-reports/TEST-TestSuite.xml",
"com.cucumber.listener.ExtentCucumberFormatter:Report/NoBroker.html"},
tags= {"@Propertyselection"},
monochrome=true ,dryRun = false)
public class TestRunner {
}
<file_sep>package PageObjects;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
public class BaseMobile {
public static AppiumDriver driver;
public static WebDriver Mobilegetdriver() throws MalformedURLException
{
if(driver==null)
{
DesiredCapabilities Capabilities = new DesiredCapabilities ();
Capabilities.setCapability("deviceName", "WDM3Y18810002926");
Capabilities.setCapability("platformName", "Android");
// Capabilities.setCapability("platformVersion", "9");
Capabilities.setCapability("appPackage", "com.nobroker.app");
Capabilities.setCapability("automationName", "UiAutomator1");
Capabilities.setCapability("appActivity", "com.nobroker.app.activities.NBSplashScreen");
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), Capabilities);
return driver;
}
else
{return driver;
}
}
}
<file_sep>package StepDefinition;
import org.openqa.selenium.WebDriver;
import PageObjects.BaseMobile;
import PageObjects.NoBrokerPageObjects;
import cucumber.api.DataTable;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class NoBrokerSteps extends BaseMobile {
NoBrokerPageObjects noBrokerPageObjects;
WebDriver driver;
@Given("^Launch the NoBroker app$")
public void launch_the_NoBroker_app() throws Throwable {
driver=super.Mobilegetdriver();
}
@When("^Land on the Home Page$")
public void land_on_the_Home_Page() throws Throwable {
noBrokerPageObjects=new NoBrokerPageObjects(driver);
noBrokerPageObjects.clickContinueBtn();
noBrokerPageObjects.handleAppPermissions();
}
@Then("^login the app$")
public void login_the_app(DataTable logins) throws Throwable {
noBrokerPageObjects.login(logins);
}
@When("^Select ‘Buy’ property related option and Click on the ‘Search’ related box$")
public void select_Buy_property_related_option_and_Click_on_the_Search_related_box() throws Throwable {
noBrokerPageObjects=new NoBrokerPageObjects(driver);
noBrokerPageObjects.buyAndSearch();
}
@Then("^select “Bangalore” city and select two localities\\(Marathahalli and HSR Layout\\)$")
public void select_Bangalore_city_and_select_two_localities_Marathahalli_and_HSR_Layout() throws Throwable {
noBrokerPageObjects.selectLocality();
}
@Then("^Click on the checkbox “Include nearby Properties”$")
public void click_on_the_checkbox_Include_nearby_Properties() throws Throwable {
noBrokerPageObjects.checkboxHandle();
}
@Then("^Select (\\d+) Bhk and (\\d+) Bhk from the number of bedrooms section$")
public void select_Bhk_and_Bhk_from_the_number_of_bedrooms_section(int arg1, int arg2) throws Throwable {
noBrokerPageObjects.selectBedrooms();
}
@When("^Scroll down on the Property listing page and click on the (\\d+)th property$")
public void scroll_down_on_the_Property_listing_page_and_click_on_the_th_property(int arg1) throws Throwable {
noBrokerPageObjects=new NoBrokerPageObjects(driver);
noBrokerPageObjects.selectPropertyList();
}
@Then("^Scroll down to till end and click on “Wrong Info”$")
public void scroll_down_to_till_end_and_click_on_Wrong_Info() throws Throwable {
noBrokerPageObjects.selectWrongInfo();
}
@Then("^Select all check-boxes in “What’s wrong” section and click on Report$")
public void select_all_check_boxes_in_What_s_wrong_section_and_click_on_Report() throws Throwable {
noBrokerPageObjects.selectAllcheckbox();
}
@When("^Change (\\d+)BHK to (\\d+)\\+BHK from ‘whats is the correct configuration’ section$")
public void change_BHK_to_BHK_from_whats_is_the_correct_configuration_section(int arg1, int arg2) throws Throwable {
noBrokerPageObjects=new NoBrokerPageObjects(driver);
noBrokerPageObjects.change3bhkTo4bhk();
}
@Then("^click on the “save changes” button and verify the successful message$")
public void click_on_the_save_changes_button_and_verify_the_successful_message() throws Throwable {
noBrokerPageObjects.verifySuccessMsg();
}
}
| 325d9e9780c68e6c8aff4915b3a44fbe2a54f2ae | [
"Java"
] | 3 | Java | lalithachandrasekar1994/NoBroker | b0408a1c5413cfd14f0fb968628e0989f796f5c0 | d0a19f273f06c7e113eb0cb555e06a4e780efd86 | |
refs/heads/master | <repo_name>Jiachen-Zhang/News_Spider<file_sep>/src/data/电子报中文大纲.md
7/31 **【精彩南科·2019届毕业生专题报道】刘灵杰:志向坚定,方得始终**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019072217143153.jpg" width="50%">
在致新书院活动室里,我们第一次见到了刘灵杰。沉稳内敛的气质、不急不缓的语气,都透露着一种低调的自信。在南方科技 […]
*https://newshub.sustech.edu.cn/zh/?p=24403&cat=3*
7/29 **第三届泛素-蛋白酶体与细胞稳态调控研讨会在我校召开**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019073016185786.jpg" width="50%">
2019年7月21日至23日,南方科技大学与中国细胞生物学学会共同举办“第三届泛素-蛋白酶体与细胞稳态调控研讨会”。
*https://newshub.sustech.edu.cn/zh/?p=24508&cat=3*
7/29 **我校学子获2019年中国大学生跆拳道锦标赛季军**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019072911373293.jpg" width="50%">
7月19日至24日,我校跆拳道队代表学校参加2019年中国大学生跆拳道锦标赛,我校前跆拳道队队长陈都同学拿下了58kg级第三名(季军)的战绩。
*https://newshub.sustech.edu.cn/zh/?p=24500&cat=3*
7/28 **【多彩夏季小学期】课堂篇:特色选修课精彩纷呈**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019072811433179.jpg" width="50%">
我们将分别以“课堂篇”和“实践篇” ,带大家了解属于南科大的夏季小学期。在此次的“课堂篇”中,我们首先走进精彩纷呈的特色选修课。
*https://newshub.sustech.edu.cn/zh/?p=24456&cat=3*
7/27 **我校航模队在中国国际飞行器设计挑战赛获佳绩**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019072718450095.jpg" width="50%">
我校航模队在中国国际飞行器设计挑战赛获佳绩
*https://newshub.sustech.edu.cn/zh/?p=24475&cat=3*
7/23 **我校联合主办国际媒体与教育大会 聚焦“人工智能与教育”**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019072407252723.png" width="50%">
2019年7月23日,国际媒体与教育大会在深圳开幕。本次会议由南方科技大学和联合国教科文组织高等教育创新中心(中国深圳)主办,中国教育技术协会提供学术指导。
*https://newshub.sustech.edu.cn/zh/?p=24424&cat=3*
7/22 **【南科新知·十万个高科技为什么】“上帝掷骰子吗?” 量子力学的哥本哈根诠释**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019072210011523.gif" width="50%">
“上帝掷骰子吗?” 这个问题直击整个量子力学理论框架的核心。 时至今日,即使一个对“量子力学”这一概念很陌生的 […]
*https://newshub.sustech.edu.cn/zh/?p=23654&cat=3*
7/19 **我校深港微电子学院优必选机器人夏令营结营**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071916384032.jpg" width="50%">
为期三天的深港微电子学院2019年优必选机器人夏令营日前在一教108教室举行结营仪式,并进行了作品展示。
*https://newshub.sustech.edu.cn/zh/?p=24358&cat=3*
7/19 **我校学子在全国高校大学生金相大赛中获佳绩**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071916212535.jpg" width="50%">
2019年7月13日至15日,第七届“蔡司·金相学会杯”全国高校大学生金相大赛在西安举行。我校材料科学与工程系三名学生代表南方科技大学参赛并获佳绩。
*https://newshub.sustech.edu.cn/zh/?p=24352&cat=3*
7/19 **国家神经外科专家贺晓生访问南科大医院 并指导功能神经外科领域手术**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071909460054.jpg" width="50%">
近日,南方科技大学医院神经外科邀请国家知名神经外科专家、西京医院贺晓生教授来院莅临指导,并成功施行一例面肌痉挛微血管减压手术。此例手术开启了南科大医院功能神经外科领域的新篇章。
*https://newshub.sustech.edu.cn/zh/?p=24336&cat=3*
7/18 **【精彩南科·2019届毕业生专题报道】郭欣格:“跑”出精彩人生**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071510315183.jpg" width="50%">
“人生是一场马拉松”——这是郭欣格在“十佳毕业生”演讲中的主题,跑马拉松的爱好带给了他坚持到底的恒心与毅力。
*https://newshub.sustech.edu.cn/zh/?p=24233&cat=3*
7/16 **我校学子参加国际水中机器人大赛获佳绩**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071610202886.jpg" width="50%">
近日,我校学子参加国际水中机器人大赛,参赛队伍共获得4项二等奖、2项三等奖。
*https://newshub.sustech.edu.cn/zh/?p=24251&cat=3*
7/15 **我校作为首席科学家牵头单位获批国家重点研发计划项目**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071509154889.jpg" width="50%">
南方科技大学生物医学工程系系主任蒋兴宇教授作为项目负责人的项目“使用合成DNA进行数据存储的技术研发”成功入选。
*https://newshub.sustech.edu.cn/zh/?p=24169&cat=3*
7/14 **我校今年本科招生录取工作结束,千余名学子圆梦南科大**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071509213458.jpg" width="50%">
7月13日,南方科技大学2019年本科招生录取工作圆满结束。今年我校面向22个省(市、自治区)共录取新生1064人。
*https://newshub.sustech.edu.cn/zh/?p=24180&cat=3*
7/12 **南科大校友发展基金获首例校友个人定向捐赠**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071222355211.jpg" width="50%">
2019年7月12日上午,南科大校友发展基金首例校友个人定向捐赠仪式在我校行政楼301会议室举行。
*https://newshub.sustech.edu.cn/zh/?p=24149&cat=3*
7/12 **河南省生产力促进中心主任常林朝访校**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071209134732.png" width="50%">
2019年7月11日,河南省生产力促进中心主任常林朝一行访问我校。我校总会计师叶秦主持了座谈会。 座谈会上,我 […]
*https://newshub.sustech.edu.cn/zh/?p=24137&cat=3*
7/11 **“达·芬奇挑战营-2019夏令营”IBPC联合营结营比赛在我校举行**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071116592229.jpg" width="50%">
2019年7月10日下午,新工科暑期课程暨“达·芬奇挑战营-2019夏令营”中的“IBPC 2019 联合营”结营比赛在我校教工之家举行。
*https://newshub.sustech.edu.cn/zh/?p=24132&cat=3*
7/11 **我校举办人工智能产学研论坛**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071114515631.jpg" width="50%">
2019年南方科技大学人工智能产学研论坛7月8日在第一科研楼报告厅举行,吸引了近200名企业、投资机构代表以及 […]
*https://newshub.sustech.edu.cn/zh/?p=24124&cat=3*
7/10 **首届“艺炫南科·现代艺术节”开幕**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071017532475.png" width="50%">
“艺炫南科·现代艺术节”7月10日-29日举行。
*https://newshub.sustech.edu.cn/zh/?p=24062&cat=3*
7/10 **我校举办首期“地球与行星科学国际暑期学校”**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071023251124.png" width="50%">
该学术活动聚焦“地球与行星内部物理”,吸引了200余位科学家及青年学生参加。
*https://newshub.sustech.edu.cn/zh/?p=24070&cat=3*
7/10 **郭雨蓉书记检查我校本科招生录取工作**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071111350281.png" width="50%">
2019年7月10日上午,我校党委书记郭雨蓉来到本科招生录取现场检查指导招生录取工作,并慰问在场工作人员。
*https://newshub.sustech.edu.cn/zh/?p=24095&cat=3*
7/9 **市委组织部人才工作局局长张林来校调研**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070916440821-600x400.png" width="50%">
深圳市委组织部人才工作局局长张林一行近日来我校调研。
*https://newshub.sustech.edu.cn/zh/?p=24056&cat=3*
7/9 **我校6名本科生秋季将赴MIT交流学习**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070415134733.jpg" width="50%">
近日,南科大-MIT机械工程联合教育科研中心通过院系推荐、评审会面试等方式,选派6名本科生赴MIT(麻省理工学院)机械工程系参加2019年秋季学期本科生学习交流项目。
*https://newshub.sustech.edu.cn/zh/?p=23977&cat=3*
7/9 **2019新材料产业技术校企交流对接会在我校召开**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070915004036-600x283.png" width="50%">
“创新·整合·应用——新材料产业技术校企交流对接会”日前在我校图书馆110报告厅召开。该活动由南方科技大学、深 […]
*https://newshub.sustech.edu.cn/zh/?p=24038&cat=3*
7/9 **我校召开医疗产学研合作暨医工、医理结合研讨会**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070516241355.png" width="50%">
近日,南科大附属医院建设办公室首次组织召开我校教授与附属第二医院产学研合作暨医工、医理结合研讨会。
*https://newshub.sustech.edu.cn/zh/?p=24009&cat=3*
7/8 **南科大医学院副教授陈国安发表论文 揭示环状RNA circHIPH3调控肺癌自噬新机制**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070916040583.jpg" width="50%">
近日,国际著名医学期刊《Autophagy》在线发表了由南科大医学院副教授陈国安主导、国内外多家单位共同参与完成的研究论文,揭示了环状RNA circHIPH3在肺癌中的作用及调控自噬通路的新机制。
*https://newshub.sustech.edu.cn/zh/?p=24028&cat=3*
7/5 **我校写作与交流课程教研室召开春季学期期末教研会**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070517412230.jpg" width="50%">
2019年7月4日,我校人文科学中心写作与交流课程教研室召开春季学期期末教研会。
*https://newshub.sustech.edu.cn/zh/?p=24018&cat=3*
7/5 **锁志刚院士做客首场材料大讲堂畅谈水凝胶魔力**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070516253830.png" width="50%">
2019年6月28日,美国工程院和科学院两院院士锁志刚教授做客南科大材料科学与工程系第1期材料大讲堂。
*https://newshub.sustech.edu.cn/zh/?p=24008&cat=3*
7/5 **南科大本科毕业生发表封面文章 展示TiO2/g-C3N4纳米复合物用于可见光产氢研究成果**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070315174155.jpeg" width="50%">
由我校化学系2019届毕业生张孜晟和博士后钟如意为共同第一作者的文章发表在《Applied Catalysis B》(IF=14) 和《Catal. Sci. Technol.》(IF=5.4),并被选为封面论文。
*https://newshub.sustech.edu.cn/zh/?p=23901&cat=3*
7/4 **广东省“冲补强”建设委员会专家组来校指导 助力我校加快推进高水平大学建设**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070416450558.png" width="50%">
2019年7月3日,广东省教育厅组织“冲一流、补短板、强特色”(以下简称“冲补强”)建设委员会专家组入校指导,助力我校加快推进高水平大学建设。
*https://newshub.sustech.edu.cn/zh/?p=23987&cat=3*
7/4 **麻省理工学院李雅达院士南科大讲堂讲述马约拉纳零模用于拓扑量子计算的途径**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070311472194.png" width="50%">
近日,美国国家科学院院士、麻省理工学院物理系教授李雅达做客南科大讲堂,为我校师生带来了题为“马约拉纳零模:是否存在用于拓扑量子计算的途径?“的精彩讲座。
*https://newshub.sustech.edu.cn/zh/?p=23923&cat=3*
7/3 **南科大2019年研究生招生夏令营开营**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070323020918.jpg" width="50%">
2019年7月3日,南方科技大学2019年研究生招生夏令营活动在润杨体育馆开营。
*https://newshub.sustech.edu.cn/zh/?p=23964&cat=3*
7/3 **我校与青海师范大学签署战略合作框架协议**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070415062797.jpg" width="50%">
2019年7月1日,南方科技大学与青海师范大学战略合作框架协议签约仪式在我校国际会议厅举行。
*https://newshub.sustech.edu.cn/zh/?p=23973&cat=3*
7/3 **图说|2019届毕业生离校,他们留下了这些“礼物”**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070314344762.jpg" width="50%">
南科大2019届毕业生已经踏上人生新起点,于7月2日全部离校。他们留下了这些“礼物”……
*https://newshub.sustech.edu.cn/zh/?p=23925&cat=3*
7/3 **我校工学院与南山智园开展产教研合作**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070315042139.png" width="50%">
2019年6月27日,我校工学院党委与南山智园党委结对共建启动仪式在南山智园党群服务中心举行。
*https://newshub.sustech.edu.cn/zh/?p=23944&cat=3*
7/3 **南科大医院召开三级医院创建动员大会**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019071709302196.png" width="50%">
南方科技大学医院三级医院创建动员大会近日在住院部501会议室召开。
*https://newshub.sustech.edu.cn/zh/?p=24281&cat=3*
7/2 **我校启动SDIM新工科暑期课程暨“达·芬奇挑战营-2019夏令营”**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070216595678.png" width="50%">
2019年6月24日,我校系统设计与智能制造学院新工科课程暨“达·芬奇挑战营-2019夏令营”启动仪式在大湾区学创空间举行。
*https://newshub.sustech.edu.cn/zh/?p=23890&cat=3*
7/2 **我校人文社会科学学院教职工赴大亚湾核电基地考察学习**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070211305391.png" width="50%">
2019年6月27日上午,我校人文社会科学学院党支部成员、人文社会科学中心教职工前往大亚湾核电站爱国主义教育基地考察学习。
*https://newshub.sustech.edu.cn/zh/?p=23887&cat=3*
7/1 **我校医学院开展临床医学师资培训活动**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070122363846.jpg" width="50%">
2019年6月25日下午,南科大第一期临床医学师资培训活动在我校荔园2栋308教室举行。
*https://newshub.sustech.edu.cn/zh/?p=23878&cat=3*
7/1 **南科大校友会举行第一届理事会第三次会议**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070122255335.jpg" width="50%">
2019年6月30日下午,南方科技大学校友会第一届理事会第三次会议在我校行政楼401会议室召开。
*https://newshub.sustech.edu.cn/zh/?p=23873&cat=3*
7/1 **南科大与宝安共建深圳工业技术研究院**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070209102826.jpg" width="50%">
2019年6月30日下午,我校与深圳市宝安区人民政府合作共建暨深圳工业技术研究院合作协议签约仪式在宝安区政府宝安厅举行。
*https://newshub.sustech.edu.cn/zh/?p=23865&cat=3*
7/1 **陈十一校长出席2019泰晤士高等教育年轻大学峰会 并在主题讨论组发言**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070119195649.jpeg" width="50%">
2019年6月25日至28日,泰晤士高等教育年轻大学峰会在英国萨里举行。
*https://newshub.sustech.edu.cn/zh/?p=23510&cat=3*
7/1 **我校举办第五届柔性电子与软物质力学国际研讨会**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019073016253218.jpg" width="50%">
2019年6月29日至6月30日,第五届柔性电子与软物质力学国际研讨会(ISFSE-IWSMM 2019)在我校举行。
*https://newshub.sustech.edu.cn/zh/?p=24515&cat=3*
7/1 **我校环境学院讲席教授刘俊国荣获中国青年科技奖**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070110332030.png" width="50%">
2019年6月29日,在第十五届中国青年科技奖颁奖大会。我校环境科学与工程学院讲席教授刘俊国入选第十五届中国青年科技奖。
*https://newshub.sustech.edu.cn/zh/?p=23812&cat=3*
7/1 **教育部《南方科技大学本科教学合格评估方案》研制工作听取意见座谈会在我校举行**
<img src="https://newshub.sustech.edu.cn/zh/wp-content/uploads/2019/07/2019070111073171.jpg" width="50%">
近日,教育部《南方科技大学本科教学合格评估方案》研制工作听取意见座谈会在我校行政楼401会议室举行。
*https://newshub.sustech.edu.cn/zh/?p=23834&cat=3*
<file_sep>/doc/数据库设计.md
```sqlite
CREATE TABLE "Article" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"title" TEXT NOT NULL UNIQUE,
"date" INTEGER NOT NULL,
"abstract" BLOB NOT NULL,
"pic_link" TEXT NOT NULL,
"link" TEXT NOT NULL,
"isChinese" INTEGER NOT NULL
)
```
<file_sep>/README.md
# News_Spider
Spider for SUSTech Monthly E-Newspaper
## 备注
### 虚拟环境使用
[link](https://docs.python.org/zh-cn/3.6/tutorial/venv.html)
<file_sep>/src/format_convertor.py
class convertor:
def __init__<file_sep>/src/spider.py
#!../venv python
# coding: utf-8
# ## Import the library
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
import xml.etree.ElementTree as ET
import requests
import sqlite3
# Method for parse page
class spider:
def __init__(self, _dateRangeMin, _dateRangeMax):
# ## Build the headers
# Ignore SSL certificate errors
self.ctx = ssl.create_default_context()
self.ctx.check_hostname = False
self.ctx.verify_mode = ssl.CERT_NONE
self.dateRangeMin = _dateRangeMin
self.dateRangeMax = _dateRangeMax
def connect_DB(self, db_path):
self.DB = sqlite3.connect(db_path)
self.cursor = self.DB.cursor()
self.insert_sql = """INSERT OR IGNORE INTO Article
(title, year, month, day, abstract, pic_url, url, isChinese)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?)
"""
DB_creator_sql = """
CREATE TABLE IF NOT EXISTS "Article" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"title" TEXT NOT NULL UNIQUE,
"year" INTEGER NOT NULL,
"month" INTEGER NOT NULL,
"day" INTEGER NOT NULL,
"abstract" BLOB NOT NULL,
"pic_url" INTEGER NOT NULL,
"url" TEXT NOT NULL,
"isChinese" INTEGER NOT NULL
);
"""
self.cursor.execute(DB_creator_sql)
def disconnect_DB(self):
self.DB.commit()
self.cursor.close()
self.DB.close()
def get_CN_data(self):
# ## Open the file
# self.handle = open("./src/data/dataCN.txt", "w")
origin_url = "https://newshub.sustech.edu.cn/zh/?cat=3&paged="
for i in range(1, 20):
result = self.__parse_page_CN(origin_url + str(i))
if result is False:
print("Finish")
break
self.DB.commit()
# self.handle.close()
def get_EN_data(self):
# self.handle = open("./src/data/dataEN.txt", "w")
self.headers = {
'path': '/?tag=arts-culture&tagall=1&paged=4',
"authority": 'newshub.sustech.edu.cn,',
"accept": 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
"accept-encoding": 'gzip, deflate, br',
"accept-language": 'zh-CN,zh;q=0.9,en;q=0.8',
"cache-control": 'max-age=0',
"upgrade-insecure-requests": '1',
"user-agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
}
origin_url = "https://newshub.sustech.edu.cn//?tag=arts-culture&tagall=1&paged="
for i in range(1, 20):
print(origin_url + str(i))
result = self.__parse_page_EN(origin_url + str(i))
if result is False:
print("Finish")
break
# self.handle.close()
def __parse_page_CN(self, url):
html = urlopen(url, context=self.ctx).read()
soup = BeautifulSoup(html, "html.parser")
for news in soup.select(".m-newslist > ul > li"):
date = news.find(class_="u-date").get_text().strip().replace("\n", "/")
temp = date.split("/")
date_num = int(temp[0] + temp[1])
print(date_num)
if date_num < self.dateRangeMin:
print("finish")
return False
if date_num > self.dateRangeMax:
print("ignore")
continue
s = str()
title = news.find(class_="title f-clamp").get_text().strip()
pic_url = news.find( class_="u-pic").attrs['style'].split("(")[1].split(")")[0]
abstract = news.find(class_="details f-clamp4").get_text().replace("\n", "")
url = news.a.attrs.get("href")
# s += "Date: " + date + "\r\n"
# s += "Title: " + title + "\r\n"
# s += "PicURL: " + pic_url + "\r\n"
# s += "Abstract: "+ abstract + "\r\n"
# s += "URL: " + url + "\r\n"
# print(s)
# self.handle.write(s.replace("\u2022", "").replace("\xa0", "").replace("\u200b", ""))
# (title, year, month, day, abstract, pic_url, url, isChinese)
data = (title, 2019, int(temp[0]), int(temp[1]), abstract, pic_url, url, 1)
self.cursor.execute(self.insert_sql, data)
return True
def __parse_page_EN(self, url):
def get_abstract(url_article):
html = urlopen(url_article).read()
soup = BeautifulSoup(html, "html.parser")
page = soup.find(class_="u-content col-sm-8 col-xs-12")
abstract = page.find("p").get_text().split(".")[0] + "."
return abstract
print("parsing: " + repr(url))
html = requests.get(url, headers=self.headers).text
soup = BeautifulSoup(html, "html.parser")
aim = soup.select("body")[0]
for news in aim.find_all(class_="u-view"):
date = news.find(class_="date").get_text().strip()
dates = date.split("/")
date_num = int(dates[0] + dates[1])
if date_num < self.dateRangeMin:
print("finish")
return False
if date_num > self.dateRangeMax:
print("ignore")
continue
url_article = news.find("a").attrs['href']
title = news.find("img").attrs["alt"]
abstract = get_abstract(url_article)
pic_url = news.find("img").attrs["src"]
# str = ""
# str += "Date: " + date + "\r\n"
# str += "Title: " + title + "\r\n"
# str += "PicURL: " + pic_url + "\r\n"
# str += "Abstract: " + abstract + "\r\n"
# str += "URL: " + url_article + "\r\n"
# print(str)
# self.handle.write(str.replace("\xa0", ""))
data = (title, 2019, int(dates[0]), int(dates[1]), abstract, pic_url, url_article, 0)
# (title, year, month, day, abstract, pic_url, url, isChinese)
self.cursor.execute(self.insert_sql, data)
return True
class TitleSpider(spider):
def __init__(self, _dateRangeMin, _dateRangeMax):
super().__init__(_dateRangeMin, _dateRangeMax)
def get_CN_data(self):
print("START get_CN_data")
# ## Open the file
# self.handle = open("./src/data/dataCN.txt", "w")
origin_url = "https://newshub.sustech.edu.cn/zh/news?page="
for i in range(0, 10):
result = self.__parse_page_CN(origin_url + str(i))
if result is False:
print("Finish")
break
self.DB.commit()
print("END get_CN_data")
def __parse_page_CN(self, url):
html = urlopen(url, context=self.ctx).read()
soup = BeautifulSoup(html, "html.parser")
for news in soup.select(".m-newslist > ul > li"):
date = news.find(class_="u-date").get_text().strip().replace("\n", "/")
temp = date.split("/")
date_num = int(temp[0] + temp[1])
print(date_num)
if date_num < self.dateRangeMin:
print("finish")
return False
if date_num > self.dateRangeMax:
print("ignore")
continue
s = str()
title = news.find(class_="title f-clamp").get_text().strip()
print(title)
pic_url = news.find( class_="u-pic").attrs['style'].split("(")[1].split(")")[0]
if pic_url.startswith('/'):
pic_url = 'https://newshub.sustech.edu.cn' + pic_url
abstract = news.find(class_="details f-clamp4").get_text().replace("\n", "")
url = news.a.attrs.get("href")
if url.startswith('/'):
url = 'https://newshub.sustech.edu.cn' + url
# s += "Date: " + date + "\r\n"
# s += "Title: " + title + "\r\n"
# s += "PicURL: " + pic_url + "\r\n"
# s += "Abstract: "+ abstract + "\r\n"
# s += "URL: " + url + "\r\n"
# print(s)
# self.handle.write(s.replace("\u2022", "").replace("\xa0", "").replace("\u200b", ""))
# (title, year, month, day, abstract, pic_url, url, isChinese)
if ('2019' in url):
return False
data = (title, 2020, int(temp[0]), int(temp[1]), abstract, pic_url, url, 1)
self.cursor.execute(self.insert_sql, data)
print("write ", data)
return True
if __name__ == '__main__':
db_path = "./data/news_data.db"
spider = TitleSpider(1121, 1231)
# spider.connect_DB(db_path)
# spider.get_CN_data()
# spider.disconnect_DB()
DB = sqlite3.connect(db_path)
cursor = DB.cursor()
def md_format_outline(file):
sql_html_select = """
SELECT (month || '/' || day) AS date, title, url
FROM Article
WHERE year = 2020
AND (title LIKE '%获%' OR title LIKE '%当选%')
ORDER BY month DESC, day DESC"""
cursor.execute(sql_html_select)
for t in cursor.fetchall():
date = t[0]
title = t[1]
url = t[2]
# write into file
file.write(date + " [" + title + "](" + url + ")\r\n\r\n")
md_format_outline(file = open("./data/output.md", "w"))
cursor.close()
DB.close()
<file_sep>/src/data/output.md
12/28 [南科大两首校园歌曲获“鹏城歌飞扬”年度十佳金曲奖](https://newshub.sustech.edu.cn/zh/html/202012/39542.html)
12/25 [南科大牵头申报深圳海洋经济创新发展示范项目获批立项](https://newshub.sustech.edu.cn/zh/html/202012/39536.html)
12/24 [南科大研究生获ICARM 2020最佳学生论文奖](https://newshub.sustech.edu.cn/zh/html/202012/39535.html)
12/24 [南科大郑春苗团队项目荣获2020年度环境保护科学技术奖二等奖](https://newshub.sustech.edu.cn/zh/html/202012/39534.html)
12/14 [南科大学子在第十二届全国大学生数学竞赛(广东赛区)中获佳绩](https://newshub.sustech.edu.cn/zh/html/202012/39459.html)
12/13 [薛其坤校长荣获2020年“复旦-中植科学奖”](https://newshub.sustech.edu.cn/zh/html/202012/39455.html)
12/12 [南科大讲席教授刘俊国获“世界科学院奖”](https://newshub.sustech.edu.cn/zh/html/202012/39451.html)
12/11 [我校颁发优秀新生奖学金 805名学生获奖](https://newshub.sustech.edu.cn/zh/html/202012/39445.html)
12/11 [南科大教授胡清获2020年度环境技术进步奖一等奖](https://newshub.sustech.edu.cn/zh/html/202012/39446.html)
12/7 [南科大附中学子获世界机器人大赛总决赛Premier赛项冠军](https://newshub.sustech.edu.cn/zh/html/202012/39423.html)
12/7 [南科大学子在2020年广东省大学生羽毛球锦标赛中获佳绩](https://newshub.sustech.edu.cn/zh/html/202012/39424.html)
12/5 [南科大社科中心教授王晓葵获批社科基金重大项目](https://newshub.sustech.edu.cn/zh/html/202012/39414.html)
12/3 [南科大团队荣获第十届吴文俊人工智能专项奖(芯片项目)二等奖](https://newshub.sustech.edu.cn/zh/html/202012/39361.html)
11/25 [“南科大研究-本科生项目”获省教育调查大赛一等奖](https://newshub.sustech.edu.cn/zh/html/202011/39180.html)
11/25 [南科大讲席教授汪宏当选国际电子电气工程师协会会士](https://newshub.sustech.edu.cn/zh/html/202011/39185.html)
11/24 [我校教师荣获省高校思政课“抗疫”优秀教学案例一等奖](https://newshub.sustech.edu.cn/zh/html/202011/39173.html)
11/19 [南科大学子在2020年APAC HPC-AI超算挑战赛获佳绩](https://newshub.sustech.edu.cn/zh/html/202011/39141.html)
11/17 [2020泰晤士高等教育亚洲大奖揭晓 南科大荣获年度国际战略奖](https://newshub.sustech.edu.cn/zh/html/202011/39127.html)
11/14 [2020“科学探索奖”今日颁奖,南科大张立源教授获奖](https://mp.weixin.qq.com/s/ysbgEXEaHBBlne2-wurFKg)
11/14 [我校教师在省高校思政课青年教师教学基本功比赛中获佳绩](https://newshub.sustech.edu.cn/zh/html/202011/39108.html)
11/13 [我校作为牵头单位获批两个国家重点研发计划项目](https://newshub.sustech.edu.cn/zh/html/202011/39097.html)
11/5 [我校学子省大学生游泳锦标赛再获佳绩](https://newshub.sustech.edu.cn/zh/html/202011/39049.html)
11/3 [南科大讲席教授于明获IEEE国际微波理论与技术协会2020年微波应用奖](https://newshub.sustech.edu.cn/zh/html/202011/39021.html)
11/1 [我校生物系3同学4年内获南科大学士和伦敦国王学院硕士双学位](https://newshub.sustech.edu.cn/zh/html/202011/39024.html)
11/1 [南科大连续五年获深圳市“人才伯乐奖”](https://newshub.sustech.edu.cn/zh/html/202011/39023.html)
10/30 [南科大学子在全国大学生机器人大赛ROBOCON大赛获二等奖](https://newshub.sustech.edu.cn/zh/html/202010/39016.html)
10/29 [南科大学子在第二届国际大学生混凝土龙舟邀请赛中获佳绩](https://newshub.sustech.edu.cn/zh/html/202010/39012.html)
10/27 [南科大学者杨天罡、曾振中获“求是杰出青年学者奖”](https://newshub.sustech.edu.cn/zh/html/202010/38996.html)
10/26 [南科大学子刘鑫获“澳门科技奖”](https://newshub.sustech.edu.cn/zh/html/202010/38993.html)
10/23 [南科大助理教授张进获第七届中国运筹学会青年科技奖](https://newshub.sustech.edu.cn/zh/html/202010/38879.html)
10/23 [南科大学子在2020国际自主智能机器人大赛获佳绩](https://newshub.sustech.edu.cn/zh/html/202010/38880.html)
10/22 [南科大学子在第六届中国大学生程序设计竞赛(秦皇岛)获多个奖项](https://newshub.sustech.edu.cn/zh/html/202010/38866.html)
10/21 [南科大学子获RoboCom世界机器人开发者大赛(华南区)两项冠军](https://newshub.sustech.edu.cn/zh/html/202010/38858.html)
10/17 [我校刘青松、董伦红获省首届高校教师党支部书记素质能力大赛三等奖](https://newshub.sustech.edu.cn/zh/html/202010/38845.html)
10/13 [我校生物系教授杜嘉木获“卫志明青年创新奖”](https://newshub.sustech.edu.cn/zh/html/202010/38827.html)
10/3 [南科大学子获国际水中机器人大赛两项冠军](https://newshub.sustech.edu.cn/zh/html/202010/38794.html)
9/28 [南科大本科生获第35届国际自动软件工程大会ACM学生研究竞赛第一名](https://newshub.sustech.edu.cn/zh/html/202009/38775.html)
9/25 [南科大张立源获2020年度“科学探索奖”](https://newshub.sustech.edu.cn/zh/html/202009/38762.html)
9/15 [我校学生社团首个自主申请科普项目获批立项](https://newshub.sustech.edu.cn/zh/html/202009/38703.html)
9/10 [深圳表彰教育工作先进单位和先进个人 我校多个单位和老师获荣誉称号](https://newshub.sustech.edu.cn/zh/html/202009/38676.html)
9/9 [全国抗击新冠肺炎疫情表彰大会举行 南科大第二附属医院院长刘磊获两项荣誉](https://newshub.sustech.edu.cn/zh/html/202009/38673.html)
8/31 [南科学子在全国大学生光电设计竞赛决赛获佳绩](https://newshub.sustech.edu.cn/zh/html/202008/38625.html)
8/26 [南科大胡勇获广东省第五届高校(本科)青年教师竞赛(理科组)二等奖](https://newshub.sustech.edu.cn/zh/html/202008/38553.html)
8/22 [南科大环境学院易树平荣获2020年“最美生态环境科技工作者”称号](https://newshub.sustech.edu.cn/zh/html/202008/38533.html)
8/15 [南科大讲席教授王鹏获美国糖化学界最高奖<NAME>奖](https://newshub.sustech.edu.cn/zh/html/202008/38510.html)
7/31 [南科大教授刘俊国、<NAME>当选欧洲科学院院士](https://newshub.sustech.edu.cn/zh/html/202007/38487.html)
7/23 [南科大学子在第十二届“挑战杯”广东大学生创业大赛获4项金奖](https://newshub.sustech.edu.cn/zh/html/202007/38468.html)
7/23 [南科大学子“华为云杯”2020深圳开放数据应用创新大赛获佳绩](https://newshub.sustech.edu.cn/zh/html/202007/38466.html)
7/21 [南科大计算机系Hisao Ishibuchi团队系列科研成果近期获得多个奖项](https://newshub.sustech.edu.cn/zh/html/202007/38455.html)
7/11 [南科大姚新教授获IEEE FRANK ROSENBLATT AWARD国际大奖](https://newshub.sustech.edu.cn/zh/html/202007/38424.html)
7/7 [我校计算机系讲席教授<NAME> 当选世界艺术与科学学院(WAAS)院士](https://newshub.sustech.edu.cn/zh/html/202007/38413.html)
7/5 [我校特色思政课获批为中国科协“2020年度学风建设资助计划项目”](https://newshub.sustech.edu.cn/zh/html/202007/38397.html)
7/3 [深圳221名医生获聘导师教授,助力南科大一流医学学科建设](https://newshub.sustech.edu.cn/zh/html/202007/38377.html)
7/1 [南科大人文科学中心教授吴岩荣获2020年托马斯•D•克拉里森奖](https://newshub.sustech.edu.cn/zh/html/202007/38366.html)
6/30 [南科大环境学院教授胡清荣获2019年度环境保护科学技术奖二等奖](https://newshub.sustech.edu.cn/zh/html/202006/38360.html)
6/12 [我校学子在“综合设计”课程中获芯片研发成果](https://newshub.sustech.edu.cn/zh/html/202006/38232.html)
6/1 [深圳创新创意设计学院项目获立项批复 年内校园建设正式开工](https://newshub.sustech.edu.cn/zh/html/202006/37882.html)
5/4 [南科学子胡启锟当选“广东向上向善好青年”](https://newshub.sustech.edu.cn/zh/html/202005/36291.html)
3/30 [南科大讲席教授蒋兴宇当选美国医学与生物工程学会会士](https://newshub.sustech.edu.cn/zh/html/202003/35314.html)
3/27 [南科大作品获2019年广东教育好新闻一等奖](https://newshub.sustech.edu.cn/zh/html/202003/35263.html)
3/14 [南科大获2019广东省教育教学成果奖一等奖](https://newshub.sustech.edu.cn/zh/html/202003/34813.html)
3/8 [南科大近期获得一批省级项目和平台立项](https://newshub.sustech.edu.cn/zh/html/202003/34581.html)
3/6 [南科大植物细胞工厂分子设计省级重点实验室获批](https://newshub.sustech.edu.cn/zh/html/202003/34450.html)
3/5 [南科大获准建设深圳市首个国家级数学中心](https://newshub.sustech.edu.cn/zh/html/202003/34242.html)
3/2 [南科大学子考古陶瓷标本相关项目获省“攀登计划”重点资助](https://newshub.sustech.edu.cn/zh/html/202003/34275.html)
2/28 [南科大学子获CFA全球投资分析大赛华南赛区冠军](https://newshub.sustech.edu.cn/zh/html/202002/34101.html)
1/21 [2020外研社英语辩论冬令营·深圳站在我校举办 我校两名本科生获奖](https://newshub.sustech.edu.cn/zh/html/202001/32504.html)
1/18 [南科大电子系张青峰当选IET Fellow](https://newshub.sustech.edu.cn/zh/html/202001/32451.html)
1/17 [南科大电子系刘召军荣获国际信息显示学会<NAME>](https://newshub.sustech.edu.cn/zh/html/202001/32413.html)
1/14 [深圳特区报 | 南科大研究成果获评中国十大科技进展新闻](https://newshub.sustech.edu.cn/zh/html/202001/32320.html)
1/10 [未来网络研究院李清副教授获2019年南山区“十大优秀青工”](https://newshub.sustech.edu.cn/zh/html/202001/32369.html)
1/5 [南科大设计智造学院再获“新工科”建设捐款并启动首个实习基地](https://newshub.sustech.edu.cn/zh/html/202001/31989.html)
1/4 [南科大副教授汪飞、谷猛荣获2018、2019年度深圳市青年科技奖](https://newshub.sustech.edu.cn/zh/html/202001/31954.html)
1/3 [南科大副教授孙大陟产学研项目获2019年中国产学研合作创新成果优秀奖](https://newshub.sustech.edu.cn/zh/html/202001/31927.html)
1/3 [我校校友发展基金获首例校友企业定向捐赠](https://newshub.sustech.edu.cn/zh/html/202001/31920.html)
1/1 [我校风险分析预测与管控研究院院长<NAME>当选瑞士工程科学院院士](https://newshub.sustech.edu.cn/zh/html/202001/31796.html)
<file_sep>/requirements.txt
beautifulsoup4==4.8.0
pkg-resources==0.0.0
pypandoc==1.4
soupsieve==1.9.3
urllib3==1.25.3
<file_sep>/src/controller.py
# In[1]: Get data from website
import spider as my_spi
import datetime
# set the time range
month = datetime.datetime.now().month
print("制作" + str(month-1) + "月电子报")
dateRangeMin = int(str(month-1) + "01")
dateRangeMax = int(str(month) + "00")
# spider the data and store into database
db_path = "./src/data/news_data.db"
def spider_data():
spider = my_spi.spider(dateRangeMin, dateRangeMax)
spider.connect_DB(db_path)
spider.get_CN_data()
spider.get_EN_data()
spider.disconnect_DB()
spider_data()
# In[2]: Extract data and generate markdown files
import sqlite3
import os
DB = sqlite3.connect(db_path)
cursor = DB.cursor()
sql_html_select = """
SELECT (month || '/' || day) AS date, title, abstract, url, pic_url
FROM Article
WHERE Month == ? And isChinese == (?)"""
def md_format(isChinese, file):
cursor.execute(sql_html_select, [month-1 ,isChinese])
for t in cursor.fetchall():
date = t[0]
title = t[1]
abstract = t[2]
url = t[3]
pic_url = t[4]
# write into file
file.write(date + " **" + title + "**\r\n\r\n")
file.write("<img src=\"" + pic_url + "\" width=\"50%\">" + "\r\n\r\n")
file.write(abstract + "\r\n\r\n")
file.write("*" + url + "*\r\n\r\n\r\n\r\n")
# generate outline
def md_format_outline(file):
sql_html_select = """
SELECT (month || '/' || day) AS date, title, url
FROM Article
WHERE Month == 8 And isChinese == 1"""
cursor.execute(sql_html_select)
for t in cursor.fetchall():
date = t[0]
title = t[1]
url = t[2]
# write into file
file.write(date + " [" + title + "](" + url + ")\r\n\r\n")
md_format(1, open("./src/data/电子报中文大纲.md", "w"))
md_format(0, open("./src/data/电子报英文大纲.md", "w"))
print("-------------------markdown files for html have been generated")
md_format_outline(file = open("./src/data/电子报分类大纲.md", "w"))
print("-------------------markdown files for content have been generated")
cursor.close()
DB.close()
# In[13]: Convert format and remove mid-files
import pypandoc
output = pypandoc.convert_file('./src/data/电子报中文大纲.md', 'html',
outputfile='./src/data/电子报中文大纲.html')
assert output == ""
# output = pypandoc.convert_file('./src/data/电子报英文大纲.md', 'html',
outputfile='./src/data/电子报英文大纲.html')
# assert output == ""
# output = pypandoc.convert_file('./src/data/电子报分类大纲.md', 'docx',
outputfile='./src/data/电子报分类大纲.docx')
# assert output == ""
print("-------------------Finish format-converting")
os.remove('./src/data/电子报中文大纲.md')
os.remove('./src/data/电子报英文大纲.md')
os.remove('./src/data/电子报分类大纲.md')
print("-------------------Reduntant files removed")
| c8a54f91dca8811f963e15ff1573b213c6a05ce1 | [
"Markdown",
"Python",
"Text"
] | 8 | Markdown | Jiachen-Zhang/News_Spider | 483b24507dea4652d3b12e35728d500281fce7c1 | ca33a4a01e77338bb60d5cccfa7ef8e4eb04ff27 | |
refs/heads/master | <file_sep>public class project1 {
public static void main(String[] args) {
int y;
//int x = 1000;
y = multAdd(100);
System.out.println("sum " + y);
y = multAdd(1000);
System.out.println("500 sum " + y);
}
public static int multAdd(int x){
int sum = 0;
for (int i=0; i < x; i++) {
if( ((i % 3)==0) || ((i % 5)==0) ){
sum += i;
}
}
return sum;
}
}
<file_sep>public class binaryGap {
public static void main(String[] args ){
System.out.println("20 expected 1 " + solution(20));
System.out.println("34 expected 3 " + solution(34));
System.out.println("8 expected 0 " + solution(8));
System.out.println("328 expected 2 " + solution(328));
System.out.println("1041 expected 5 " + solution(1041));
System.out.println("51712 expected 2 " + solution(51712));
}
public static int solution(int N){
int count=0;
int largestCount=0;
boolean trailing = true;
while(N != 0){
if(N % 2 == 1){
//it's an odd number
trailing = false;
largestCount = count > largestCount ? count : largestCount;
count = 0;
}
else {
//Even number, the binary is 0
count = trailing ? 0 : count + 1 ;
}
N = N / 2;
}
//check if the count is greater than 0.
return largestCount;
}
}
<file_sep># ProjectEuler
This is a project to improve and hone my programming skills for Java.
<file_sep>public class smallestMultiple {
//Problem 5 SmallestMultiple
// 2520 is the smallest number that can de divied by each of the number from 1 to 10 without any remainder
// what is the smallest positive number that is evenly divisibly by all of the numbers from 1 to 20?
public static void main (String[] args){
System.out.println("N=3 and excepted 6 ==" + smallestMultiple(3) );
System.out.println("N=4 and excepted 12 ==" + smallestMultiple(4) );
System.out.println("N=5 and excepted 60=" + smallestMultiple(5) );
System.out.println("N=10 and excepted 2520=" + smallestMultiple(10) );
//System.out.println("N=20 and excepted 2520=" + smallestMultiple(20) );
}
public static int smallestMultiple(int n){
int smallest = 0;
boolean found= false;
while(!found){
smallest++;
for (int i = 1; i <= n; i++) {
if (smallest % i != 0){
break ;
}
if( smallest % i == 0 && i == n){
found=true;
}
}
}
return smallest;
}
//////////////////////////////////////////////////////
//would work in c++
// public static int smallestMultiple(int n) {
// int smallest = 0;
// boolean found = false;
//
// while (!found) {
// found = isValid(smallest, n);
// }
// return smallest;
// }
//
// public static boolean isValid(int smallest, int n){
//
// for (int i = 1; i <= n; i++) {
// if (smallest % i != 0){
// return false;
// //move on to the next one
// }
// if( smallest % i == 0 && i == n){
// return true;
// }
// }
// return false;
// }
}
| d9b3ca6210b4c02ed6e54ab9242eacf03c2f217a | [
"Markdown",
"Java"
] | 4 | Java | tiefejos/ProjectEuler | c065b4462fa2268e2b4821debad86854c8646161 | aecde73ced47623762af3f55d78b229450c8f7d0 | |
refs/heads/master | <file_sep># WP_Query_WithRelevance
Wordpress WP_Query subclass which adds "relevance" as a new `orderby` option.
Relevance is calculated by a combination of factors:
* Overlap between the post taxonomies and taxonomies requested in `tax_query` filter
* Frequency of keywords in the post title and content, keywords given by the `s` filter
This may be used with a different `orderby` value in order, in which case it will perform a regular `WP_Query()` with no additional overhead. Therefore, full compatibility is provided for both relevance-sorted queries and "regular" queries.
## Basic Usage
Place the `wpquery_withrelevance.php` file into your file structure, and then load it in your functions.php file. You now have access to `WP_Query_WithRelevance()`
The query takes [typical WP_Query() filters](https://codex.wordpress.org/Class_Reference/WP_Query) and only invokes its special behavior when `orderby = keyword` is given.
```
require_once 'wpquery_withrelevance.php';
$filter = array( // basic filter: published posts
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 50,
);
$filter['s'] = "Mayonnaise Conspiracy"; // a keyword filter
$filter['tax_query'] = array( // filter posts having any of these tags
array(
'taxonomy' => 'tags',
'field' => 'slug',
'operator' => 'IN',
'terms' => array('sandwiches', 'condiments', 'lunch'),
),
);
if ($_GET['sorting']) == 'best') {
$filter['orderby'] = "relevance"; // this is the magic word!
}
else {
$filter['orderby'] = "title"; // but it's also okay to not use relevance, a regular WP_Query() is done
}
$query = new WP_Query_WithRelevance($filter);
```
*If `orderby` is any value except "relevance" then relevance calculation is skipped entirely.* This is effectively the same as running a regular `WP_Query()` and provides compatibility so you don't need to use a different interface, nor suffer a performance hit, if you want to sort by "regular" capabilities.
## Ordering is By Relevance Only
Multi-field sorting is not supported by `WP_Query_WithRelevance()`
The `orderby` field must be exactly the word "relevance" and ordering is done by relevance score only. No additional ordering may be specified.
## Adjusting the Relevance Scoring
The built-in scoring weights should work well for most folks. But, you may fine-tune the relevance scoring by supplying an additional `relevance_scoring` structure. This specifies the weighting value to give to keywords matched in the title, keywords matched in the content body, taxonomies in common, and so forth.
```
$filter['relevance_scoring'] = array(
// weighting by taxonomy: the built in "tags" taxo plus a custom taxo, with different weights
'tax_query' => array(
'tags' => 10.0,
'authors' => 25.0,
),
// the points per word occurrence, in post title and content
'title_keyword' => 1.0,
'content_keyword' => 0.25,
);
```
## Credits
This was written by [<NAME>](https://github.com/gregallensworth/django) at [GreenInfo Network](https://github.com/GreenInfo-Network/)
This is all-original code, but was inspired and guided by reference to https://github.com/mannieschumpert/wp-relevance-query
<file_sep><?php
//
// a WP_Query subclass which adds a Relevance score and sorts by it
// https://github.com/GreenInfo-Network/WP_Query_WithRelevance
//
if (! defined( 'WPINC')) die;
class WP_Query_WithRelevance extends WP_Query {
//
// search field DEFAULT weights
// the $args passed to this Query may/should specify weightings for specific taxonomies, meta keys, etc.
// but these act as defaults
//
var $DEFAULT_WEIGHTING_TITLE_KEYWORD = 1.0;
var $DEFAULT_WEIGHTING_CONTENT_KEYWORD = 0.25;
var $DEFAULT_WEIGHTING_TAXONOMY_RATIO = 10.0;
//
// constructor
// performs a standard WP_Query but then postprocesses to add relevance, then sort by that relevance
//
public function __construct($args = array()) {
// stow and unset the orderby param
// cuz it's not a real DB field that can be used
if ($args['orderby'] === 'relevance') {
$this->orderby = $args['orderby'];
$this->order = 'DESC';
unset($args['orderby']);
unset($args['order']);
}
// perform a typical WP_Query
// then if we weren't using a relevance sorting, we're actually done
$this->process_args($args);
parent::__construct($args);
if (! $this->orderby) return;
// okay, we're doing relevance postprocessing
$this->initialize_relevance_scores();
$this->score_keyword_relevance();
$this->score_taxonomy_relevance();
$this->orderby_relevance();
// debugging; you can display this at any time to just dump the list of results
//$this->display_results_so_far();
}
// initializing all posts' relevance scores to 0
private function initialize_relevance_scores() {
foreach ($this->posts as $post) {
$post->relevance = 0;
}
}
private function score_keyword_relevance() {
if (! $this->query_vars['s']) return; // no keyword string = this is a noop
$weight_title = @$this->query_vars['relevance_scoring']['title_keyword'];
$weight_content = @$this->query_vars['relevance_scoring']['content_keyword'];
if ($weight_title == NULL) $weight_title = $this->DEFAULT_WEIGHTING_TITLE_KEYWORD;
if ($weight_content == NULL) $weight_content = $this->DEFAULT_WEIGHTING_CONTENT_KEYWORD;
// print "score_keyword_relevance() Title keyword weight {$weight_title}\n";
// print "score_keyword_relevance() Content keyword weight {$weight_content}\n";
$words = strtoupper(trim($this->query_vars['s']));
$words = preg_split('/\s+/', $words);
foreach ($this->posts as $post) {
$title = strtoupper($post->post_title);
$content = strtoupper($post->post_content);
foreach ($words as $thisword) {
$post->relevance += substr_count($title, $thisword) * $weight_title;
$post->relevance += substr_count($content, $thisword) * $weight_content;
}
}
}
private function score_taxonomy_relevance() {
if (! $this->query_vars['tax_query']) return; // no taxo query = skip it
// taxonomy relevance is only calculated for IN-list operations
// for other types of queries, all posts match that value and further scoring would be pointless
// go over each taxo and each post
// increase the post relevance, based on number of terms it has in common with the terms we asked about
// this is done one taxo at a time, so we can match terms by ID, by slug, or by name ... and so we can apply individual weighting by that taxo
foreach ($this->query_vars['tax_query'] as $taxo) {
if (strtoupper($taxo['operator']) !== 'IN' or ! is_array($taxo['terms'])) continue; // not a IN-list query, so relevance scoring is not useful for this taxo
$taxoslug = $taxo['taxonomy'];
$whichfield = $taxo['field'];
$wantterms = $taxo['terms'];
$taxo_weighting = @$this->query_vars['relevance_scoring']['tax_query'][$taxoslug];
if ($taxo_weighting === NULL) $taxo_weighting = $this->DEFAULT_WEIGHTING_TAXONOMY_RATIO;
// print "score_taxonomy_relevance() Taxo {$taxoslug} weight {$taxo_weighting}\n";
foreach ($this->posts as $post) {
// find number of terms in common between this post and this taxo's list
$terms_in_common = 0;
$thispostterms = get_the_terms($post->ID, $taxo['taxonomy']);
foreach ($thispostterms as $hasthisterm) {
if (in_array($hasthisterm->{$whichfield}, $wantterms)) $terms_in_common += 1;
}
// express that terms-in-common as a percentage, and add to this post's relevance score
$ratio = (float) $terms_in_common / sizeof($wantterms);
$post->relevance += ($ratio * $ratio * $taxo_weighting);
}
}
}
private function orderby_relevance() {
usort($this->posts, array($this, 'usort_sorting'));
}
private function display_results_so_far () { // for debugging
foreach ($this->posts as $post) {
printf('%d %s = %.1f' . "\n", $post->ID, $post->post_title, $post->relevance) . "\n";
}
}
private function usort_sorting ($p, $q) {
// we force DESC and only trigger if orderby==='relevance' so we can keep this simple
if ($p->relevance == $q->relevance) return 0;
return $p->relevance > $q->relevance ? -1 : 1;
}
}
| 959af7012f40279794ebd54f375a5f422870db66 | [
"Markdown",
"PHP"
] | 2 | Markdown | GreenInfo-Network/WP_Query_WithRelevance | 9ceddfc890b01c25b08bce1dfcfd870f8d0ba16a | a660c642119d6a8562adfb73ba15c03dee58dccd | |
refs/heads/master | <file_sep>install.packages("readxl")
library(readxl)
df_exam <- read_excel("excel_exam.xlsx")
df_exam
mean(df_exam$english)
mean(df_exam$science)
df_novar <- read_excel("excel_exam_novar.xlsx", col_names = F)
df_novar
df_s <- read_excel("excel_exam_sheet.xlsx", sheet = 3)
df_s
df_csv <- read.csv("csv_exam.csv", stringsAsFactors = F)
df_csv
df_midterm
write.csv(df_midterm, file = "df_midterm.csv")
save(df_midterm, file = "df_mid.rda")
rm(df_midterm)
df_midterm
load("df_mid.rda")
df_midterm # 저장할 때 사용한 변수로 다시 되살아남
<file_sep>a <- 1
a + 2
b <- 2
b*3
var1 <- seq(1, 70, by = 2)
var1
var2 <- c(1:5)
var2
var3 <- seq(1,5)
var3
var4 <- seq(1,10,by = 2)
var4 + 2
var2 + var2
str1 <- "a"
str1
str2 <- c("Hello", "world")
str2
mean(var2)
max(var2)
min(var2)
paste(str2, collapse = ",")
<file_sep>grade <- c(80, 60, 70, 50, 90)
mean(grade)
total_m <- mean(grade)
total_m
# 데이터 프레임 만들기
english <- c(90,80,60,70)
math <- c(50,60,100,20)
df_midterm <- data.frame(english, math)
df_midterm
class <- c(1,1,2,2)
df_midterm <- data.frame(english, math, class)
df_midterm
mean(df_midterm$english) # df_midterm의 english변수
mean(df_midterm$math)
# 데이터 프레임 한번에 만들기
df_midterm <- data.frame(english = c(90,80,60,70),
math = c(50,60,100,20),
class = c(1,1,2,2))
df_a <- data.frame(제품 = c("사과", "딸기", "수박"),
가격 = c(1800, 1500, 3000),
판매량 = c(24, 38, 13))
df_a
mean(df_a$가격)
mean(df_a$판매량)
| 1fe615f267b0e93cc90bc1370c0663707d5e18c1 | [
"R"
] | 3 | R | likeyu96/Doit_R | ec3d47db1c122782385defa9752431c8d2f12828 | d4fc9f61c2e5d6bbce2ed6375fbaf557edae187c | |
refs/heads/master | <repo_name>Guseyn/xml-fixer<file_sep>/README.md
# xml-fixer
This repo moved to [broken-xml project](https://github.com/Guseyn/broken-xml).
<file_sep>/src/main/java/com/xml/fixer/XmlDocument.java
package com.xml.fixer;
import java.util.ArrayList;
import java.util.List;
public final class XmlDocument {
private final int start;
private final int end;
private final List<XmlHeadElement> xmlHeads;
private final List<Comment> comments;
private final List<Element> roots;
public XmlDocument(final int start, final int end) {
this.start = start;
this.end = end;
this.xmlHeads = new ArrayList<>();
this.comments = new ArrayList<>();
this.roots = new ArrayList<>();
}
public int getStart() {
return this.start;
}
public int getEnd() {
return this.end;
}
public List<XmlHeadElement> getHeads() {
return this.xmlHeads;
}
public List<Comment> getComments() {
return this.comments;
}
public List<Element> getRoots() {
return this.roots;
}
}
<file_sep>/src/main/java/com/xml/fixer/Comment.java
package com.xml.fixer;
public final class Comment {
private final int start;
private final int end;
private final String text;
public Comment(final String text, final int start, final int end) {
this.text = text;
this.start = start;
this.end = end;
}
public int getStart() {
return this.start;
}
public int getEnd() {
return this.end;
}
public String getText() {
return this.text;
}
}
<file_sep>/src/main/java/com/xml/fixer/ParsedXML.java
package com.xml.fixer;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public final class ParsedXML {
private final String xml;
public ParsedXML(final String xml) {
this.xml = xml;
}
public XmlDocument value() throws NoSuchFieldException, IllegalAccessException {
final Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
final char[] chars = (char[]) field.get(xml);
final int inputLength = chars.length;
assert inputLength == xml.length();
boolean headElementIsInProcess = false;
XmlHeadElement currentHeadElement = null;
int currentHeadElementStart = 0;
int currentHeadElementEnd = 0;
boolean attributesIsInProcess = false;
List<Attribute> currentAttributes = new ArrayList<>();
boolean attributeNameIsInProcess = false;
StringBuilder currentAttributeName = null;
int currentAttributeNameStart = 0;
int currentAttributeNameEnd = 0;
boolean attributeValueIsInProcess = false;
StringBuilder currentAttributeValue = null;
int currentAttributeValueStart = 0;
int currentAttributeValueEnd = 0;
boolean commentIsInProcess = false;
StringBuilder currentCommentText = null;
int currentCommentStart = 0;
int currentCommentEnd = 0;
boolean elementElementTextIsInProcess = false;
StringBuilder currentElementText = null;
int currentElementTextStart = 0;
int currentElementTextEnd = 0;
int numberOfOpenBrackets = 0;
int numberOfClosedBrackets = 0;
Element currentElement = null;
Element currentParentElement = null;
int currentElementStart = 0;
int currentElementEnd = 0;
Stack<Element> processingElms = new Stack<>();
boolean openingElementNameIsInProcess = false;
StringBuilder currentOpeningElementName = null;
boolean closingElementNameIsInProcess = false;
StringBuilder currentClosingElementName = null;
final XmlDocument document = new XmlDocument(0, inputLength);
for (int i = 0; i < inputLength; i++) {
final char currentChar = chars[i];
if (currentChar == '<' && i < inputLength - 1 && chars[i + 1] == '?') {
continue;
}
if (currentChar == '?' && i > 0 && chars[i - 1] == '<') {
continue;
}
if (currentChar == '>' && i > 0 && chars[i - 1] == '?') {
continue;
}
if (currentChar == '<' && i < inputLength - 1 && chars[i + 1] == '!') {
continue;
}
if (currentChar == '>' && i > 0 && chars[i - 1] == '-') {
continue;
}
if (currentChar == '/' && i > 0 && chars[i - 1] == '<') {
continue;
}
if (currentChar == '?' && i < inputLength - 1 && chars[i + 1] == '>') {
if (headElementIsInProcess) {
currentHeadElementEnd = i + 1;
currentHeadElement = new XmlHeadElement(
currentHeadElementStart,
currentHeadElementEnd,
currentAttributes
);
document.getHeads().add(currentHeadElement);
if (attributesIsInProcess) {
attributesIsInProcess = false;
currentAttributes = new ArrayList<>();
}
headElementIsInProcess = false;
currentHeadElement = null;
currentHeadElementStart = 0;
currentHeadElementEnd = 0;
}
continue;
}
if (currentChar == 'x' && i > 1 && i < inputLength - 2 && chars[i + 1] == 'm' && chars[i + 2] == 'l' && chars[i - 1] == '?' && chars[i - 2] == '<') {
continue;
}
if (currentChar == 'm' && i > 2 && i < inputLength - 1 && chars[i + 1] == 'l' && chars[i - 1] == 'x' && chars[i - 2] == '?' && chars[i - 3] == '<') {
continue;
}
if (currentChar == 'l' && i > 3 && chars[i - 1] == 'm' && chars[i - 2] == 'x' && chars[i - 3] == '?' && chars[i - 4] == '<') {
headElementIsInProcess = true;
currentHeadElementStart = i - 4;
continue;
}
if (currentChar == '-' && i < inputLength - 1 && chars[i + 1] == '>') {
continue;
}
if (currentChar == '-' && i > 2 && chars[i - 1] == '-' && chars[i - 2] == '!' && chars[i - 3] == '<') {
if (!commentIsInProcess) {
commentIsInProcess = true;
currentCommentText = new StringBuilder();
currentCommentStart = i - 3;
}
continue;
}
if (currentChar == '-' && i < inputLength - 2 && chars[i + 1] == '-' && chars[i + 2] == '>') {
if (commentIsInProcess) {
currentCommentEnd = i + 2;
document.getComments().add(
new Comment(
currentCommentText.toString(),
currentCommentStart,
currentCommentEnd
)
);
commentIsInProcess = false;
currentCommentText = null;
currentCommentStart = 0;
currentCommentEnd = 0;
continue;
}
continue;
}
if (currentChar == '<') {
if (elementElementTextIsInProcess) {
currentElementTextEnd = i - 1;
if (currentElement != null) {
currentElement.getTexts().add(
new Text(
currentElementText.toString(),
currentElementTextStart,
currentElementTextEnd
)
);
}
elementElementTextIsInProcess = false;
currentElementText = null;
currentElementTextStart = 0;
currentElementTextEnd = 0;
}
if (!attributeValueIsInProcess && i < inputLength - 1) {
if (chars[i + 1] != '/') {
numberOfOpenBrackets += 1;
if (!openingElementNameIsInProcess) {
openingElementNameIsInProcess = true;
currentOpeningElementName = new StringBuilder();
currentElementStart = i;
}
} else {
numberOfClosedBrackets += 1;
if (!closingElementNameIsInProcess) {
closingElementNameIsInProcess = true;
currentClosingElementName = new StringBuilder();
}
}
}
continue;
}
if (currentChar == '>') {
if (i + 1 < inputLength && !elementElementTextIsInProcess) {
elementElementTextIsInProcess = true;
currentElementText = new StringBuilder();
currentElementTextStart = i + 1;
}
if (currentOpeningElementName != null) {
currentElement = new Element(
currentOpeningElementName.toString(),
currentElementStart
);
currentElement.getAttributes().addAll(currentAttributes);
if (processingElms.size() == 0) {
currentParentElement = currentElement;
} else {
currentParentElement = processingElms.get(processingElms.size() - 1);
}
processingElms.push(currentElement);
openingElementNameIsInProcess = false;
currentOpeningElementName = null;
if (attributesIsInProcess) {
attributesIsInProcess = false;
currentAttributes = new ArrayList<>();
}
continue;
}
if (closingElementNameIsInProcess && currentElement != null && currentParentElement != null) {
currentElement.correctEnd(i);
if (currentParentElement != currentElement) {
currentParentElement.getChildren().add(currentElement);
}
processingElms.pop();
if (processingElms.size() == 0) {
document.getRoots().add(currentParentElement);
currentParentElement = null;
} else {
currentElement = processingElms.get(processingElms.size() - 1);
if (processingElms.size() > 1) {
currentParentElement = processingElms.get(processingElms.size() - 2);
}
}
closingElementNameIsInProcess = false;
currentClosingElementName = null;
continue;
}
continue;
}
if (isDelimiter(currentChar)) {
if (headElementIsInProcess) {
attributesIsInProcess = true;
continue;
}
if (commentIsInProcess) {
currentCommentText.append(currentChar);
continue;
}
if (elementElementTextIsInProcess) {
currentElementText.append(currentChar);
continue;
}
if (attributeValueIsInProcess) {
currentAttributeValue.append(currentChar);
continue;
}
if (openingElementNameIsInProcess) {
openingElementNameIsInProcess = false;
attributesIsInProcess = true;
continue;
}
if (closingElementNameIsInProcess && currentElement != null && currentParentElement != null) {
currentElement.correctEnd(i);
if (currentParentElement != currentElement) {
currentParentElement.getChildren().add(currentElement);
}
processingElms.pop();
if (processingElms.size() == 0) {
document.getRoots().add(currentParentElement);
currentParentElement = null;
} else {
currentElement = processingElms.get(processingElms.size() - 1);
if (processingElms.size() > 1) {
currentParentElement = processingElms.get(processingElms.size() - 2);
}
}
closingElementNameIsInProcess = false;
currentClosingElementName = null;
continue;
}
continue;
}
if (currentChar == '=') {
if (attributesIsInProcess) {
if (attributeNameIsInProcess) {
attributeNameIsInProcess = false;
currentAttributeNameEnd = i - 1;
}
continue;
}
continue;
}
if (isQuote(currentChar)) {
if (attributesIsInProcess) {
if (!attributeNameIsInProcess && !attributeValueIsInProcess) {
attributeValueIsInProcess = true;
currentAttributeValue = new StringBuilder();
currentAttributeValueStart = i + 1;
continue;
}
if (attributeValueIsInProcess) {
attributeValueIsInProcess = false;
currentAttributeValueEnd = i - 1;
currentAttributes.add(
new Attribute(
currentAttributeName.toString(),
currentAttributeValue.toString(),
currentAttributeNameStart,
currentAttributeNameEnd,
currentAttributeValueStart,
currentAttributeValueEnd
)
);
currentAttributeName = null;
currentAttributeValue = null;
currentAttributeNameStart = 0;
currentAttributeNameEnd = 0;
currentAttributeValueStart = 0;
currentAttributeValueEnd = 0;
continue;
}
}
continue;
}
if (attributesIsInProcess) {
if (!attributeNameIsInProcess && !attributeValueIsInProcess) {
attributeNameIsInProcess = true;
currentAttributeName = new StringBuilder();
currentAttributeNameStart = i;
currentAttributeName.append(currentChar);
continue;
}
if (attributeNameIsInProcess && !attributeValueIsInProcess) {
currentAttributeName.append(currentChar);
continue;
}
if (attributeValueIsInProcess) {
currentAttributeValue.append(currentChar);
continue;
}
}
if (commentIsInProcess) {
currentCommentText.append(currentChar);
continue;
}
if (openingElementNameIsInProcess) {
currentOpeningElementName.append(currentChar);
continue;
}
if (closingElementNameIsInProcess) {
currentClosingElementName.append(currentChar);
continue;
}
if (elementElementTextIsInProcess) {
currentElementText.append(currentChar);
continue;
}
}
return document;
}
private boolean isDelimiter(char c) {
final char[] delimiters = {' ', '\n', '\r', '\t'};
for (final char delimiter : delimiters) {
if (delimiter == c) {
return true;
}
}
return false;
}
private boolean isQuote(char c) {
return c == '\'' || c == '\"';
}
}
| 0895520eed03f862f7cb89ffda387ff181160c5c | [
"Markdown",
"Java"
] | 4 | Markdown | Guseyn/xml-fixer | f3640f28fd372c86d2df0178a795d16ca58e79b8 | c6a8d6e78af36142f22766300bd5574eeae57d81 | |
refs/heads/master | <file_sep>AgileDay Conference Android Application
=======================================
This is a conference client created for Italian Agile Day conference.
The aim is to create a conference client application that will help the
conference visitors by giving uptodate information about sessions,
and facilitate communication with other conference participants.
### Build process:
* android update project --path AgileDayConferenceApp
* ant -buildfile AgileDayConferenceApp\build.xml release
### Release build instructions to build signed .apk package for Android Market:
* Run tests and check that they are all green ...run the test suite manually into eclipse :(
* Copy italianagileday.keystore in AgileDayConferenceApp/ (you should have it)
* Update build.properties file
* uncommenting "key.store" and "key.alias"
* adding target=android-8 (note: tests and build must run successfully also on the minimum
supported target-4)
* Update AndroidManifest.xml
* Remove android:debuggable
* Add android:installLocation="auto" in "manifest" element (http://developer.android.com/guide/appendix/install-location.html#Compatiblity)
* android update project --path AgileDayConferenceApp
* ant -buildfile AgileDayConferenceApp\build.xml release
* will ask you for a password (and you should have it)
* smoke test the application on your mobile
* upload the .apk file on the market
### After Release build steps
* Revert build.properties file
* In AndroidManifest.xml, REMOVE android:installLocation="auto" in "manifest" element
* Increase android:versionCode for next release
* Increase android:versionName for next release
* Commit updated AndroidManifest.xml (the only changes should be in android:versionCode and android:versionName)
<file_sep>/*
Copyright 2010
Author: <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package it.agileday.data;
import it.agileday.utils.Dates;
import it.agileday.data.Session;
import java.util.Date;
import junit.framework.TestCase;
public class SessionTest extends TestCase {
public void test_validation() {
Date d1 = Dates.newDate(2010, 1, 1, 10);
Date d2 = Dates.newDate(2010, 1, 1, 11);
assertEquals("End date must be greater than start date", new Session().setStart(d1).setEnd(d1).validationMessage());
assertEquals("End date must be greater than start date", new Session().setStart(d2).setEnd(d1).validationMessage());
assertTrue(new Session().setStart(d1).setEnd(d2).isValid());
}
public void test_toString() {
assertEquals("session_123", new Session().setId(123).toString());
assertEquals("session_0", new Session().toString());
}
}
<file_sep>/*
Copyright 2010
Author: <NAME>
Author: <NAME>
Author: <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package it.agileday.ui.twitter;
import it.agileday2011.R;
import it.agileday.data.Tweet;
import it.agileday.utils.Dates;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
class TweetsAdapter extends BaseAdapter {
private final List<Tweet> tweets;
private final Context context;
public TweetsAdapter(Context context) {
this.context = context;
this.tweets = new ArrayList<Tweet>();
}
public void addTweets(Collection<Tweet> tweets) {
this.tweets.addAll(tweets);
}
public void addLoadingRow() {
this.tweets.add(null);
}
public void removeLoadingRow() {
tweets.remove(null);
}
private LayoutInflater getLayoutInflater() {
return (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return tweets.size();
}
@Override
public Tweet getItem(int position) {
return tweets.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Tweet tweet = getItem(position);
if (tweet != null) {
return getTweetView(tweet, convertView, parent);
} else {
return getLoadingView(convertView, parent);
}
}
private View getLoadingView(View convertView, ViewGroup parent) {
View ret = convertView;
if (ret == null || ret.getId() != R.id.items_loading_twitter) {
ret = getLayoutInflater().inflate(R.layout.twitter_item_loading, parent, false);
}
return ret;
}
private View getTweetView(Tweet tweet, View convertView, ViewGroup parent) {
View ret = convertView;
if (ret == null || ret.getId() != R.id.twitter_item) {
ret = getLayoutInflater().inflate(R.layout.twitter_item, parent, false);
}
Date now = Calendar.getInstance().getTime();
TextView dateText = (TextView) ret.findViewById(R.id.tweet_date);
dateText.setText(Dates.differenceSmart(now, tweet.date));
SpannableString ss = new SpannableString(String.format("%s: %s", tweet.fromUser, tweet.text));
ss.setSpan(new TextAppearanceSpan(context, R.style.TwitterUser), 0, tweet.fromUser.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView text = (TextView) ret.findViewById(R.id.tweet_text);
text.setText(ss);
Linkify.addLinks(text, Linkify.WEB_URLS);
ImageView image = (ImageView) ret.findViewById(R.id.tweet_image);
image.setImageBitmap(tweet.profileImage);
return ret;
}
}<file_sep>/*
Copyright 2010
Author: <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package it.agileday.ui;
import android.test.ActivityInstrumentationTestCase2;
public class AboutTest extends ActivityInstrumentationTestCase2<About> {
private About activity;
public AboutTest() {
super("it.agileday.ui", About.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
activity = this.getActivity();
}
public void test_a_oncreate_activity() {
assertNotNull(activity);
}
}
<file_sep>/*
Copyright 2010
Author: <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package it.agileday.ui.speakers;
import it.agileday2011.R;
import it.agileday.data.DatabaseHelper;
import it.agileday.data.Speaker;
import it.agileday.data.SpeakerRepository;
import it.agileday.ui.TextViewUtil;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewAnimator;
public class SpeakersActivity extends Activity {
static final String TAG = SpeakersActivity.class.getName();
private ViewAnimator viewAnimator;
private Gallery gallery;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.speakers);
viewAnimator = (ViewAnimator) findViewById(R.id.flipper);
gallery = (Gallery) findViewById(R.id.gallery);
List<Speaker> speakers = getSpeakers();
gallery.setAdapter(new ImageAdapter(this, speakers));
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
viewAnimator.setDisplayedChild(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
fillData(speakers);
}
private void fillData(List<Speaker> speakers) {
for (Speaker speaker : speakers) {
View view = getLayoutInflater().inflate(R.layout.speakers_item, viewAnimator, false);
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(speaker.name);
TextView bio = (TextView) view.findViewById(R.id.bio);
TextViewUtil.setHtmlText(speaker.bio, bio);
viewAnimator.addView(view);
}
}
private List<Speaker> getSpeakers() {
SQLiteDatabase database = new DatabaseHelper(this).getReadableDatabase();
try {
SpeakerRepository repo = new SpeakerRepository(database, this.getResources(), this);
return repo.getAll();
} finally {
database.close();
}
}
public class ImageAdapter extends BaseAdapter {
int galleryItemBackground;
private Context context;
private final List<Speaker> speakers;
public ImageAdapter(Context c, List<Speaker> speakers) {
context = c;
this.speakers = speakers;
TypedArray a = obtainStyledAttributes(R.styleable.SpeakersGallery);
galleryItemBackground = a.getResourceId(R.styleable.SpeakersGallery_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
return speakers.size();
}
public Object getItem(int position) {
return speakers.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
float density = getResources().getDisplayMetrics().density;
ImageView i = new ImageView(context);
i.setImageDrawable(speakers.get(position).image);
i.setLayoutParams(new Gallery.LayoutParams((int) (130 * density), (int) (150 * density)));
i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
i.setBackgroundResource(galleryItemBackground);
return i;
}
}
}
<file_sep>/*
Copyright 2010
Author: <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package it.agileday.data;
import it.agileday2011.R;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = DatabaseHelper.class.getName();
private static final String DATABASE_NAME = "data.db";
private static final int DATABASE_VERSION = 81;
private final Context context;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
InputStream stream = context.getResources().openRawResource(R.raw.database);
execScript(stream, db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Found database version " + oldVersion + ". Rebuilding database version " + newVersion);
onCreate(db);
}
private static void execScript(InputStream stream, SQLiteDatabase db) {
Scanner scanner;
try {
scanner = new Scanner(new InputStreamReader(stream, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
scanner.useDelimiter(";\\s*(\\n|\\r\\n|\\r)");
while (scanner.hasNext()) {
String sql = scanner.next();
db.execSQL(sql);
}
}
}<file_sep>/*
Copyright 2010
Author: <NAME>
Author: <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package it.agileday.data;
import java.util.ArrayList;
import java.util.List;
public class TweetList extends ArrayList<Tweet> implements List<Tweet> {
private static final long serialVersionUID = 1L;
private static TweetList empty = new TweetList(0);
public TweetList(int length) {
super(length);
}
public static TweetList Empty() {
return empty;
}
}
<file_sep>/*
Copyright 2010
Author: <NAME>
Author: <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package it.agileday.data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class TrackRepository {
private final SQLiteDatabase db;
private final Activity activity;
public TrackRepository(SQLiteDatabase db, Activity activityToManageCursorLifeCicle) {
this.db = db;
this.activity = activityToManageCursorLifeCicle;
}
public ArrayList<Track> getAll() {
Map<Integer, Track> ret = new HashMap<Integer, Track>();
String sql = "SELECT track_id, tracks.title AS track_title, tracks.track_order AS track_order, sessions._id AS session_id, sessions.session_type AS session_type, sessions.title AS session_title, sessions.speakers AS session_speakers, sessions.start AS session_start, sessions.end AS session_end FROM sessions JOIN tracks ON(sessions.track_id = tracks._id) ORDER BY track_id, sessions.start";
Cursor cursor = db.rawQuery(sql, null);
if (activity != null)
{
activity.startManagingCursor(cursor);
}
while (cursor.moveToNext()) {
getTrack(ret, cursor).addSession(SessionRepository.buildSession(cursor));
}
cursor.close();
ArrayList<Track> arrayList = new ArrayList<Track>(ret.size());
arrayList.addAll(ret.values());
Collections.sort(arrayList);
return arrayList;
}
private Track getTrack(Map<Integer, Track> ret, Cursor cursor) {
int trackId = cursor.getInt(cursor.getColumnIndexOrThrow("track_id"));
if (!ret.containsKey(trackId)) {
ret.put(trackId, buildTrack(cursor));
}
return ret.get(trackId);
}
private Track buildTrack(Cursor c) {
Track ret = new Track();
ret.title = c.getString(c.getColumnIndexOrThrow("track_title"));
ret.order = c.getInt(c.getColumnIndexOrThrow("track_order"));
return ret;
}
}
<file_sep>/*
Copyright 2010
Author: <NAME>
Author: <NAME>
Author: <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package it.agileday.data;
import it.agileday.utils.BitmapCache;
import it.agileday.utils.Dates;
import it.agileday.utils.HttpRestUtil;
import java.net.URLEncoder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TweetRepository {
@SuppressWarnings("unused")
private static final String TAG = TweetRepository.class.getName();
private static final String URL = "http://search.twitter.com/search.json";
private String nextPageQueryString;
private final BitmapCache bitmapCache;
public TweetRepository(String hashTag, BitmapCache bitmapCache) {
this.nextPageQueryString = "?result_type=recent&rpp=10&q=" + URLEncoder.encode(hashTag);
this.bitmapCache = bitmapCache;
}
public TweetList getNextPage() {
if (!hasNextPage())
return TweetList.Empty();
JSONObject json = HttpRestUtil.httpGetJsonObject(String.format("%s%s", URL, nextPageQueryString));
nextPageQueryString = json.optString("next_page", null);
try {
return fromJson(json.getJSONArray("results"));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public boolean hasNextPage() {
return nextPageQueryString != null;
}
private TweetList fromJson(JSONArray ary) throws Exception {
TweetList tweets = new TweetList(ary.length());
for (int i = 0; i < ary.length(); i++) {
tweets.add(buildTweet(ary.getJSONObject(i)));
}
return tweets;
}
public Tweet buildTweet(JSONObject json) {
Tweet ret = new Tweet();
try {
ret.id = json.getLong("id");
ret.text = json.getString("text");
ret.fromUser = json.getString("from_user");
ret.date = Dates.fromTweeterString(json.getString("created_at"));
ret.profileImage = bitmapCache.get(json.getString("profile_image_url"));
} catch (JSONException e) {
throw new RuntimeException(e);
}
return ret;
}
}
<file_sep>/*
Copyright 2010
Author: <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package it.agileday.data;
import android.database.sqlite.SQLiteDatabase;
import android.test.AndroidTestCase;
public class SessionRepositoryTest extends AndroidTestCase {
private SessionRepository m_repo;
@Override
protected void setUp() throws Exception {
super.setUp();
SQLiteDatabase db = new DatabaseHelper(getContext()).getReadableDatabase();
m_repo = new SessionRepository(db, null);
}
public void test_loading_a_session() {
final int sessionId = 1;
Session session = m_repo.getSessionFromId(sessionId);
assertNotNull(session);
assertEquals(sessionId, session.getId());
}
public void test_loading_an_unavailble_session() {
final int sessionId = -2;
Session session = m_repo.getSessionFromId(sessionId);
assertNotNull(session);
assertEquals(0, session.getId());
assertEquals("", session.type);
}
}
| 37e909081cb408479021dcf8249e5a276aa0bd2f | [
"Markdown",
"Java"
] | 10 | Markdown | teeolendo/AgileDayConferenceApp | dd78487af4f13783a89d5da851e40cde48c97a85 | 9513bf85cdbec6d43a9b74dd50cd2f3ebeb2493b | |
refs/heads/master | <file_sep>import requests
import json
from tweetasenator.models import State, Representative
def main():
print "Main invoked"
states = State.objects.all()
base_url = "http://api.opencongress.org/people.json?state="
i = 0
for state in states:
i = i+1
if i < 100:
state_url = "%s%s" % (base_url, state.code)
while True:
try:
data = get_data(state_url)
if not data.ok:
raise Exception("NOTOK")
except Exception, e:
print "Exception: %s" % (str(e))
continue
break
jsondata = json.loads(data.text)
people = jsondata["people"]
for person in people:
rep = Representative()
rep.state = state.code
rep.firstname = person["person"]["firstname"]
rep.middlename = person["person"]["middlename"]
rep.lastname = person["person"]["lastname"]
rep.website = person["person"]["website"]
rep.email = person["person"]["email"]
rep.approval = person["person"]["user_approval"]
rep.contact = person["person"]["contact_webform"]
rep.dem_votes_percentage = person["person"]["votes_democratic_position"]
rep.rep_votes_percentage = person["person"]["votes_republican_position"]
rep.district = person["person"]["district"]
rep.url = person["person"]["url"]
rep.youtube = person["person"]["youtube_id"]
rep.gender = person["person"]["gender"]
rep.name = person["person"]["name"]
try:
rep.oc_id = person["person"]["person_stats"]["person_id"]
except Exception, e:
print "No person data exists for this representative"
rep.save()
print person["person"]["name"]
def get_data(url):
print "Getting data for %s" % (url)
data = requests.get(url)
return data
<file_sep>Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
jQuery(function($){
$(document).keyup(function(e) {
if (e.keyCode == 27) { // esc
$("#mask").fadeOut();
$(".modal").fadeOut();
$("#mask").remove();
}
});
var token = $("[name='csrfmiddlewaretoken']").val();
var oldSync = Backbone.sync;
Backbone.sync = function(method, model, options) {
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-CSRFToken', token);
};
return oldSync(method, model, options);
};
Backbone.View.prototype.close = function(){
this.remove();
this.unbind();
if (this.onClose){
this.onClose();
}
}
State = Backbone.Model.extend({ });
Senator = Backbone.Model.extend({ });
Officer = Backbone.Model.extend({ });
Tweet = Backbone.Model.extend({
urlRoot: '/api/v1/tweets/'
});
States = Backbone.Collection.extend({
model: State,
initialize: function(model, options) { }
});
Officers = Backbone.Collection.extend({
model: Officer,
initialize: function(options) {
// this.fetch();
},
url: function() {
return "/api/v1/representative/?position__in=1,2,3";
},
parse: function(resp) {
// return resp.objects;
}
});
Senators = Backbone.Collection.extend({
model: Senator,
initialize: function(options) {
this.state = options.state;
},
url: function() {
return "/api/v1/representative/?position=4&state=" + this.state;
},
parse: function(resp) {
return resp.objects;
}
});
OfficerListView = Backbone.View.extend({
el: $("#senators"),
initialize: function(options) {
this.collection.on('sync', this.render, this);
},
render: function() {
var self = this;
this.collection.each(function(item) {
var officerView = new OfficerView({model: item, el: item.id});
$("#officers").append(officerView.render());
});
console.log("OfficersListView Render");
},
});
SenatorListView = Backbone.View.extend({
el: $("#content"),
initialize: function(options) {
$("#senators").empty();
$("#officers").empty();
_.bindAll(this, 'render_officers');
this.officers = options.officers;
this.render_officers();
// this.officers.on('sync', this.render_officers, this);
// this.collection.on('sync', this.render, this);
this.collection.on('remove', this.destroy, this);
this.collection.fetch();
this.collection.on('remove', this.destroy, this);
this.collection.on('sync', this.render, this);
$(this.el).undelegate('.officer', 'click');
twitterers = [];
$("#targets").val("");
},
render_officers: function() {
$("#officers").empty();
if(this.options.state != 0) {
$(this.el).delegate('.officer', 'click', this.senatorClicked);
this.officers.each(function(item) {
var officerView = new OfficerView({model: item, el: item.id});
$("#officers").append(officerView.render());
});
};
},
render: function() {
$("#senators").empty();
//var self = this;
if(this.options.state != 0) {
if(this.collection.length > 0) {
this.collection.each(function(item) {
var senatorView = new SenatorView({model: item, el: item.id});
$("#senators").append(senatorView.render());
});
} else {
var senatorEmptyView = new SenatorEmptyView();
$("#senators").append(senatorEmptyView.render());
}
} else {
var getStartedView = new GetStartedView();
$("#senators").append(getStartedView.render());
}
return this;
},
events: {
"click .senator" : "senatorClicked",
"click .officer" : "senatorClicked",
},
senatorClicked: function(event) {
var self = this;
var div = $(event.currentTarget);
twitterer = div.find(".twitter").html();
if(div.hasClass("selected")) {
div.removeClass("selected");
pos = twitterers.indexOf(twitterer);
// twitterers.remove(twitterer);
// twitterView = new TwitterersView({twitterers:twitterers});
} else {
twitterers.push(twitterer);
twitterView = new TwitterersView({twitterers:twitterers});
div.addClass("selected");
}
$("#targets").val(twitterers);
},
destroy: function(event) {
$(this.el).undelegate('.senator', 'click');
$(this.el).delegate('.senator', 'click', this.senatorClicked);
},
});
TwitterersView = Backbone.View.extend({
el: $("#message"),
initialize: function(options) {
if(logged_in) {
this.template_name = "message_template"
this.render();
} else {
this.template_name = "please_login_template";
this.render();
}
$(this.el).undelegate('#submit_form', 'submit');
},
render: function() {
$(this.el).delegate('#submit_form', 'submit', this.formSubmitted);
template= _.template($("#" + this.template_name).html());
this.$el.html(template);
return template;
},
events: {
"keyup #id_message" : "handleKeys",
"submit #submit_form" : "formSubmitted",
},
formSubmitted: function(event) {
event.preventDefault();
var targets = $("#targets").val();
var message = $("#id_message").val();
var tweet = new Tweet({
recipients: targets,
message: message,
});
tweet.save({ wait: true }, {
success: function(model, response, xhr) {
router.navigate("", true);
$("#body").append("<div id='mask'></div>");
$("#mask").fadeIn(300);
var marginTop = ($(".modal").height()+24)/2;
var marginLeft = ($(".modal").width()+24)/2;
$(".modal").css({
'margin-top' : -marginTop-100,
'margin-left': -marginLeft,
});
$(".modal").fadeIn(300);
console.log("Success");
console.log(model);
console.log(response);
},
error: function(model, response) {
console.log("Error");
console.log(model);
console.log(response);
},
});
},
handleKeys : function(event) {
total = 110;
counted = $("#id_message").val().length;
result = total-counted;
$("#letter_count").html(" " + result + " ");
if(result < 0)
$("#letter_count").addClass("error");
else
$("#letter_count").removeClass("error");
}
});
SenatorView = Backbone.View.extend({
template: _.template($("#senator_template").html()),
// initialize: function() { },
render: function() {
return this.template(this.model.toJSON());
},
});
OfficerView = Backbone.View.extend({
template: _.template($("#officer_template").html()),
render: function() {
return this.template(this.model.toJSON());
},
});
GetStartedView = Backbone.View.extend({
template: _.template($("#get_started_template").html()),
render: function() {
return this.template();
}
});
SenatorEmptyView = Backbone.View.extend({
template: _.template($("#senator_empty_template").html()),
render: function() {
return this.template();
}
});
AppView = Backbone.View.extend({
el: $("#body"),
initialize: function() {
this.states = new States(null, { view: this });
for(var i = 0; i < states.length; i++) {
this.states.add(states[i]);
};
this.render();
},
render: function() {
var template = _.template($("#template").html(), { states: this.states, labelValue: 'Something'});
$("#body").append(template);
},
events: {
"change #id_states" : "stateSelected",
},
stateSelected: function(event) {
// api.nextSlide();
selection = $(event.currentTarget);
value = $("option:selected", selection).val();
router.navigate(value, true);
},
});
var TweetRouter = Backbone.Router.extend({
routes: {
"" : "defaultRoute",
"*state" : "stateRoute",
}
});
var router = new TweetRouter;
if(this.appview != null) {
this.appview.off();
}
children = [];
this.appview = new AppView();
router.on('route:defaultRoute', function(actions) {
$("#id_states").val('0');
$("#senators").children().fadeOut();
$("#officers").children().fadeOut();
$("#message").children().fadeOut();
var getStartedView = new GetStartedView();
$("#senators").append(getStartedView.render());
// var appview = new AppView();
});
router.on('route:stateRoute', function(state) {
$("#id_states").val(state);
this.senators = new Senators({state: state});
this.officers = new Officers({state: state});
/*
if(this.officerView != null) {
this.officerView.off();
};
*/
/*
this.officerView = new OfficerListView({
collection: this.officers,
});
*/
this.officers = new Officers();
this.officers.add([
{id: 1, name: "<NAME>", firstname: "Barack", lastname: "Obama", twitter: "BarackObama", party: "Democrat", pic: "/static/photos/thumbs/BarackObama.jpg", extra_title: "President of the United States" },
{id: 2, name: "<NAME>", firstname: "Joseph", lastname: "Biden", twitter: "JoeBiden", party: "Democrat", pic: "/static/photos/thumbs/JoeBiden.jpg", extra_title: "Vice President" },
{id: 3, name: "<NAME>", firstname: "John", lastname: "Boehner", twitter: "SpeakerBoehner", party: "Republican", pic: "/static/photos/thumbs/JohnBoehner.jpg", extra_title: "Speaker of the House" },
]);
if(this.senatorView != null) {
this.senatorView.off();
};
this.senatorView = new SenatorListView({
collection: this.senators,
officers: this.officers,
state: state
});
});
Backbone.history.start();
});
<file_sep>import requests
import json
from tweetasenator.models import State, Representative
def main():
print "Main invoked"
reps = Representative.objects.filter(pic__isnull=True)
base_url = "http://opencongress.org/images/photos/thumbs_102"
path = "/home/bmelton/projects/tweetasenator/tweetasenator/static/photos/thumbs/"
url = "http://tweetasenator.com/static/photos/thumbs"
for rep in reps:
img_url = "%s/%d.png" % (base_url, rep.oc_id)
r = requests.get(img_url)
if r.ok:
with open("%s/%d.png" % (path, rep.oc_id), 'wb') as f:
for chunk in r:
f.write(chunk)
rep.pic = "%s/%d.png" % (url, rep.oc_id)
rep.save()
print img_url
<file_sep>import re
from tweetasenator.models import *
def main():
reps = Representative.objects.all()
for rep in reps:
try:
parts = re.findall(r'\[([^]]*)\]', rep.name)
parts = str(parts)
# I suck at regex, so after you're done laughing at this, fuck off! /meanface.
parts = parts.replace("\"", "")
parts = parts.replace("\'", "")
parts = parts.replace("[", "")
parts = parts.replace("]", "")
party, state = parts.split(",")
party = party.replace("u", "")
if party == "R":
party = "Republican"
if party == "D":
party = "Democrat"
if party == "I":
party = "Independent"
rep.party = party
rep.save()
except Exception, e:
print "%s - %s" % (rep.name, str(e))
| ad4cc1b114027c2b0c75531225df78643ccae742 | [
"JavaScript",
"Python"
] | 4 | Python | bmelton/TweetASenator | 097ccd6c316d1d96e8529d41ff689d344c001507 | 7c16faa2b3be8ee535d176de91b929d2a6cad30e | |
refs/heads/master | <repo_name>mitya/rabotnegi-padrino<file_sep>/app/controllers/vacancies.rb
Rabotnegi.controller :vacancies do
# caches_page :show, :if => -> c { c.request.xhr? }
get :new do
@vacancy = Vacancy.new
render "vacancies/form"
end
get :search, "/vacancies" do
params.merge! city: current_user.city, industry: current_user.industry
render "vacancies/index"
end
get :index_for_json, "/vacancies.json" do
@vacancies = Vacancy.search(params.slice(:city, :industry, :q)).without(:description).
order_by(decode_order_to_mongo(params[:sort].presence || "title")).paginate(params[:page], 50)
render items: @vacancies.map { |v| v.attributes.slice(*%w(title city industry external_id salary_min salary_max employer_name)) }
end
get :index, map: "/vacancies/:city(/:industry)", if_params: {city: City, industry: Industry} do
@vacancies = Vacancy.search(params.slice(:city, :industry, :q)).without(:description).
order_by(decode_order_to_mongo(params[:sort].presence || "title")).paginate(params[:page], 50)
current_user.update_if_stored!(city: params[:city], industry: params[:industry])
render "vacancies/index"
end
get :favorite do
@vacancies = current_user.favorite_vacancy_objects
render "vacancies/favorite"
end
get :show, map: "/vacancies/:id", xhr: true do
@vacancy = Vacancy.get(params[:id])
partial "vacancies/details"
end
get :show, map: "/vacancies/:id" do
@vacancy = Vacancy.get(params[:id])
return params[:id] =~ /^\d{6}$/ ? 410 : 404, render("shared/404") unless @vacancy
redirect url(:vacancies, :show, id: @vacancy) if CGI.unescape(params[:id]) != @vacancy.to_param
render "vacancies/show"
end
post :create do
@vacancy = Vacancy.new(params[:vacancy])
@vacancy.poster_ip = request.ip
halt 422, render("vacancies/form") unless captcha_valid!(@vacancy)
if @vacancy.save
flash[:notice] = 'Вакансия опубликована'
redirect url(:vacancies, :show, id: @vacancy)
else
return 422, render("vacancies/form")
end
end
post :remember, with: :id do
current_user.favorite_vacancies << BSON::ObjectId(params[:id])
current_user.save!
200
end
post :forget, with: :id do
current_user.favorite_vacancies.delete BSON::ObjectId(params[:id])
current_user.save!
200
end
end
<file_sep>/app/models/rabotaru/processor.rb
class Rabotaru::Processor
attr_accessor :vacancies, :work_dir
include Gore::EventLog::Accessor
include Gore::EventHandling
def initialize(key = Gore.date_stamp)
@vacancies = []
@work_dir = Rabotnegi.config.rabotaru_dir.join(key)
@converter = Rabotaru::Converter.new
end
def process
log.info "start"
read unless vacancies.any?
remove_duplicates
filter
save
log.info "done"
end
def read
Pathname.glob(@work_dir.join "*.json").each do |file|
data = file.read.sub!(/;\s*$/, '')
items = Gore.json.decode(data)
vacancies = items.map { |item| convert(item) }.compact
@vacancies.concat(vacancies)
end
log.info "read", count: @vacancies.size
end
def remove_duplicates
@vacancies.uniq_by! { |v| v.external_id }
log.info "remove_duplicates", keep: @vacancies.size
end
def filter
new_vacancies, updated_vacancies = [], []
loaded_external_ids = @vacancies.pluck(:external_id)
existed_vacancies = Vacancy.where(:external_id.in => loaded_external_ids)
existed_vacancies_map = existed_vacancies.index_by(&:external_id)
@vacancies.each do |loaded_vacancy|
if existed_vacancy = existed_vacancies_map[loaded_vacancy.external_id]
if existed_vacancy.created_at != loaded_vacancy.created_at
existed_vacancy.attributes = loaded_vacancy.attributes.except('_id')
updated_vacancies << existed_vacancy
end
else
new_vacancies << loaded_vacancy
end
end
now = Time.now
new_vacancies.each { |v| v.loaded_at = now }
@vacancies = new_vacancies + updated_vacancies
raise_event :filtered do
detalization = @vacancies.each_with_object({}) { |v, memo|
key = "#{v.city}-#{v.industry}"
memo[key] = memo[key].to_i + 1
}
{ filter: {created: new_vacancies.count, updated: updated_vacancies.count, total: @vacancies.count}, details: detalization }
end
end
def save
@vacancies.send_each(:save!)
end
def convert(item)
@converter.convert(item)
rescue => e
log.warn "convert.fail", reason: Gore.format_error(e), item: item['position']
nil
end
end
<file_sep>/test/rabotnegi/unit/industry_test.rb
require 'test_helper'
unit_test Industry do
test "search by one of external ids" do
assert_equal :finance, Industry.find_by_external_ids(2001, 2003, 2, 9, 2003)
end
end<file_sep>/script/test_json.rb
N = 100
# data = Vacancy.first.attributes
data = Vacancy.limit(50).map { |v| v.attributes.slice(:title, :city, :industry, :external_id, :salary_min, :salary_max, :employer_name) }
# puts data.as_json
# puts JSON.generate(data.as_json)
puts JSON.generate(data)
Benchmark.bm(40) do |b|
b.report("as_json") do
N.times { data.as_json }
end
b.report("to_json (ActiveSupport::JSON.encode)") do
N.times { data.to_json }
end
b.report("JSON.generate(x.as_json)") do
N.times { JSON.generate(data.as_json) }
end
b.report("JSON.generate") do
N.times { JSON.generate(data) }
end
end
<file_sep>/test/lib/core_ext_test.rb
require "test_helper"
unit_test Object do
dummy = temp_class do
attr_accessor :fname, :lname
end
test "class" do
assert_equal 123.class, 123._class
end
test "is?" do
assert 132.is?(String, NilClass, Fixnum)
assert !132.is?(String, NilClass, Symbol)
end
test "send_chain" do
assert_equal "h", "hello".send_chain("first")
assert_equal 104, "hello".send_chain("first.ord")
assert_equal "104", "hello".send_chain("first.ord.to_s")
end
test "assign_attributes" do
person = dummy.new
person.assign_attributes(fname: "Joe", lname: "Smith", age: 25)
assert_equal "Joe", person.fname
assert_equal "Smith", person.lname
assert !person.respond_to?(:age)
end
test "assign_attributes!" do
assert_raises NoMethodError do
dummy.new.assign_attributes!(fname: "Joe", lname: "Smith", age: 25)
end
end
end
unit_test File do
test "write" do
assert_respond_to File, :write
end
end
unit_test Hash do
test "append_string" do
hash = {aa: "AA"}
hash.append_string(:aa, "and AA")
assert_equal "AA and AA", hash[:aa]
hash.append_string(:bb, "and BB")
assert_equal "and BB", hash[:bb]
end
test "prepend_string" do
hash = {aa: "AA"}
hash.prepend_string(:aa, "and AA")
assert_equal "and AA AA", hash[:aa]
hash.prepend_string(:bb, "and BB")
assert_equal "and BB", hash[:bb]
end
end
unit_test "JSON conversions" do
test "Time" do
assert_equal "\"2012-01-01T12:00:00Z\"", "2012-01-01T12:00:00Z".to_time.to_json
assert_equal "2012-01-01T12:00:00Z", "2012-01-01T12:00:00Z".to_time.as_json
end
test "BSON::ObjectId" do
id = BSON::ObjectId.new
assert id.to_json != id.as_json
end
end
unit_test Module do
class TProcess
attr_accessor :status
def_state_predicates 'status', :started, :failed, :done
end
test "def_state_predicates" do
assert_equal :status, TProcess._state_attr
assert_equal [:started, :failed, :done], TProcess._states
process = TProcess.new
assert_respond_to process, :started?
assert_respond_to process, :failed?
assert_respond_to process, :done?
process.status = "failed"
assert process.failed?
assert !process.done?
process.status = :done
assert !process.failed?
assert process.done?
end
end
unit_test Enumerable do
test "select_xx/detect_xx" do
ary = %w(1 2 3 4 5 6 7)
assert_equal %w(3), ary.select_eq(to_i: 3)
assert_equal %w(1 2 4 5 6 7), ary.select_neq(to_i: 3)
assert_equal %w(3 4 5), ary.select_in(to_i: [3, 4, 5])
assert_equal %w(1 2 6 7), ary.select_nin(to_i: [3, 4, 5])
assert_equal "3", ary.detect_eq(to_i: 3)
assert_equal "1", ary.detect_neq(to_i: 3)
assert_equal %w(3), ary.select_eq(to_i: 3, to_s: "3")
assert_equal "3", ary.detect_eq(to_i: 3, to_s: "3")
end
test "map_to_array" do
assert_equal [ [1, 1], [22, 2] ], %w(1 22).map_to_array(:to_i, :length)
end
test "pluck_all" do
assert_equal [ %w(1 2), %w(3 4) ], [ [1,2], [3,4] ].pluck_all(:to_s)
end
end
<file_sep>/lib/gore.rb
require 'net/http'
module Gore
def logger
Padrino.logger
end
def http
@http ||= HttpClient.new
end
def json
@json ||= Json.new
end
def env
ActiveSupport::StringInquirer.new(Padrino.env.to_s)
end
def root
Pathname(Padrino.root)
end
module RandomHelpers
def id(array)
results = array ? array.map(&:id) : []
results = results.map(&:to_s) if results.first.is_a?(BSON::ObjectId)
results
end
# f("fixed1", "fixed2", conditional1: true, conditional2: false) => "fixed1 fixed2 conditional1"
# f(wide: true, narrow: false, thin: true) => "wide thin"
def css_classes_for(*args)
return nil if args.empty?
conditions = args.extract_options!
classes = args.dup
conditions.each { |clas, condition| classes << clas if condition }
classes.join(" ")
end
def inspection(title, *args)
options = args.extract_options!
options.reject! { |k,v| v.blank? }
options = options.map { |k,v| "#{k}=#{inspect_value(v)}" }.join(',')
args.map! { |arg| Array === arg ? arg.join('-') : arg }
args = args.join(',')
string = [args, options].reject(&:blank?).join(' ')
"{#{string}}"
end
def inspect_value(value)
case value
when Proc then "Proc"
when Hash then inspect_hash(value)
when Array then inspect_array(value)
when nil then "∅"
when Time then value.xmlschema
else value
end
end
def inspect_hash(hash)
(hash || {}).map { |key, val| "#{key}: #{inspect_value(val)}" }.join(", ")
end
def inspect_array(array)
(array || []).join(", ")
end
def reformat_caller(string)
file, line, method = string.match(/(\w+\.rb):(\d+):in `(\w+)'/).try(:captures)
"#{file}::#{method}::#{line}"
end
def object_id?(value)
value.to_s =~ /^(\d+|[0-9a-f]{24})(-|$)/i
end
end
module Jobs
def enqueue(klass, method, *args)
Log.debug "Job scheduled #{klass}.#{method}#{args.inspect}"
Resque::Job.create('main', 'Gore::Jobs::Worker', klass.to_s, method.to_s, args)
end
class Worker
def self.perform(klass, method, args)
Log.debug "Job started #{klass}.#{method}#{args.inspect}"
klass.constantize.send(method, *args)
Log.debug "Job completed #{klass}.#{method}#{args.inspect}"
end
end
end
module Strings
def time_stamp
time = Time.current
time.strftime("%Y%m%d_%H%M%S_#{time.usec}")
end
def date_stamp
time = Time.current
time.strftime("%Y%m%d")
end
def format_error(exception)
"#{exception.class} - #{exception.message}"
end
def format_error_and_stack(exception)
# logger.error Gore.backtrace_cleaner.clean(exception.backtrace).join("\n")
format_error(exception) + "\n#{exception.backtrace.join("\n")}"
end
end
module Server
def disk_usage(mount_point = '/')
output = `df #{mount_point}`
lines = output.split("\n")
value = lines.second.split.at(-2).to_i
value
rescue
nil
end
def memory_free
output = `free -m`
lines = output.split("\n")
value = lines.second.split.at(3).to_i
value
rescue
nil
end
end
# class Logger
# undef :silence
# LOG_METHODS = %w(debug info warn error fatal unknown).pluck(:to_sym)
# ALL_METHODS = LOG_METHODS + %w(silence level level=).pluck(:to_sym)
#
# def method_missing(selector, *args, &block)
# if ALL_METHODS.include?(selector)
# Kernel.puts(args.first) if LOG_METHODS.include?(selector) && $log_to_stdout
# Padrino.logger.send(selector, *args, &block)
# else
# super
# end
# end
#
# def trace(*args)
# debug(*args)
# end
# end
class HttpClient
def get(url)
Log.trace "HTTP GET #{url}"
Net::HTTP.get(URI.parse(url))
end
end
class Json
def decode(data)
ActiveSupport::JSON.decode(data)
end
end
module Debug
def self.say(message)
Padrino.logger.info(message)
end
end
class Mash < Hash
def [](key)
super(key.to_s) || super(key.to_sym)
end
def slice(*keys)
hash = self.class.new
keys.each { |k| hash[String === k ? k.to_sym : k] = self[k] }
hash
end
end
extend self, Server, Strings, Jobs, RandomHelpers
def self.method_missing(selector, *args, &block)
return const_get(selector) if selector.to_s =~ /^[A-Z]/ && const_defined?(selector)
super
end
end
Padrino::Logger::Extensions.module_eval do
def trace(message)
debug(message)
end
end
Log = Gore.logger
Http = Gore.http
<file_sep>/app/models/salary.rb
class Salary
attr_accessor :min, :max, :currency
def initialize(min = nil, max = nil)
@currency = :rub
@min = min
@max = max
end
def exact?; @min && @max && @min == @max end
def exact; @min end
def exact=(value); @min = value; @max = value end
def negotiable?; !@min && !@max end
def negotiable=(value); @min = @max = nil if value end
def min?; @min && !@max end
def max?; @max && !@min end
def range?; @max && @min && @max != @min end
def ==(other)
Salary === other &&
self.min == other.min &&
self.max == other.max &&
self.currency == other.currency
end
alias eql? ==
def to_s
case
when negotiable? then "договорная"
when exact? then "#{exact.to_i} р."
when min? then "от #{min.to_i} р."
when max? then "до #{max.to_i} р."
when range? then "#{min.to_i}—#{max.to_i} р."
end
end
def text
case
when negotiable? then ""
when exact? then "#{exact}"
when min? then "#{min}+"
when max? then "<#{max}"
when range? then "#{min}-#{max}"
end
end
def text=(value)
other = self.class.parse(value)
self.min = self.max = nil
self.min = other.min
self.max = other.max
end
def convert_currency(new_currency)
@min = Currency.convert(@min, currency, new_currency) if @min
@max = Currency.convert(@max, currency, new_currency) if @max
@currency = new_currency
self
end
def self.make(attributes = {})
salary = new
attributes.each { |n,v| salary.send("#{n}=", v) }
salary
end
def self.parse(string)
string.squish!
params = case string
when /(\d+)\s?[-—]\s?(\d+)/, /от (\d+) до (\d+)/ then { :min => $1.to_i, :max => $2.to_i }
when /от (\d+)/, /(\d+)\+/ then { :min => $1.to_i }
when /до (\d+)/, /<(\d+)/ then { :max => $1.to_i }
when /(\d+)/ then { :exact => $1.to_i }
else {}
end
make(params)
end
end
<file_sep>/test/rabotnegi/unit/rabotaru_processor_test.rb
require 'test_helper'
unit_test Rabotaru::Processor do
setup do
@processor = Rabotaru::Processor.new("demo")
Dir.mkdir(@processor.work_dir) unless File.exists?(@processor.work_dir)
end
test "load" do
FileUtils.cp Dir.glob(Gore.root.join "test/support/rabotaru/*"), @processor.work_dir
@processor.read
assert_equal 60, @processor.vacancies.count
assert_instance_of Vacancy, @processor.vacancies.first
end
test "remove_dups" do
@processor.vacancies = [
Vacancy.new(external_id: 101),
Vacancy.new(external_id: 102),
Vacancy.new(external_id: 103),
Vacancy.new(external_id: 101),
Vacancy.new(external_id: 102),
Vacancy.new(external_id: 104)
]
@processor.remove_duplicates
assert_equal 4, @processor.vacancies.count
assert_equal [101, 102, 103, 104], @processor.vacancies.pluck(:external_id).sort
end
test "filter" do
Vacancy.create!(title: "V-1", city: "spb", industry: "it", external_id: 101, created_at: "2008-09-01", description: "no", loaded_at: "2008-09-01")
Vacancy.create!(title: "V-2", city: "spb", industry: "it", external_id: 102, created_at: "2008-09-01", description: "no", loaded_at: "2008-09-01")
@processor.vacancies = [
Vacancy.new(title: 'V-1', city: 'spb', created_at: "2008-09-02", external_id: 101, industry: 'it', description: 'updated'),
Vacancy.new(title: 'V-2', city: 'spb', created_at: "2008-09-01", external_id: 102, industry: 'it', description: 'no'),
Vacancy.new(title: 'V-3', city: 'spb', created_at: "2008-09-01", external_id: 103, industry: 'it', description: 'no')
]
@processor.filter
assert @processor.vacancies.any? { |v| v.title == "V-3" }
assert @processor.vacancies.any? { |v| v.title == "V-1" && v.description == 'updated' }
assert !@processor.vacancies.any? { |v| v.title == "V-2" }
assert_in_delta Time.now, @processor.vacancies.detect_eq(title: 'V-3').loaded_at, 3.seconds
assert_equal Time.parse("2008-09-01"), @processor.vacancies.detect_eq(title: 'V-1').loaded_at
end
test "save" do
@processor.vacancies = [
Vacancy.new(title: 'V-5', city: 'spb', external_id: 101, industry: 'it'),
Vacancy.new(title: 'V-6', city: 'spb', external_id: 102, industry: 'it')
]
@processor.save
assert Vacancy.where(title: 'V-5').exists?
assert Vacancy.where(title: 'V-6').exists?
end
end
<file_sep>/test/support/factories.rb
Factory.define :vacancy do |f|
f.sequence :title do |n| "Test Vacancy ##{n}" end
f.description "lorem lorem lorem"
f.city "msk"
f.industry "it"
f.salary_min 50_000
f.employer_name "<NAME>"
f.sequence :external_id do |n| n + 100_000 end
end
<file_sep>/lib/gore/stubbing.rb
module Gore::Stubbing
@@stubs = []
def self.stub(target, method, &block)
@@stubs << [target, method]
target.singleton_class.instance_eval do
alias_method "original_#{method}", method
define_method(method, &block)
end
end
def self.unstub_all
@@stubs.each do |target, method|
target.singleton_class.instance_eval do
alias_method method, "original_#{method}"
end
end
end
end
<file_sep>/app/models/currency.rb
class Currency
@@map = {
:usd => "$",
:eur => "€",
:rub => "руб."
}
@@map = {
usd: "$",
eur: "€",
rub: "руб."
}
@@list = [:rub, :usd, :eur]
@@rates = { rub: 1.0, usd: 31, eur: 42 }
class << self
def convert(value, source_currency_sym, target_currency_sym)
value * rate(source_currency_sym) / rate(target_currency_sym)
end
def rate(currency)
@@rates[currency]
end
end
end
<file_sep>/config.ru
#!/usr/bin/env rackup
require File.expand_path("../config/boot.rb", __FILE__)
Rack::Server.middleware["development"] = [
[Rack::ContentLength],
[Rack::Chunked],
[Rack::ShowExceptions],
[Rack::Lint]
]
map '/rabotnegi/assets' do
use Rack::CommonLogger
run Rabotnegi.assets
end
require 'resque/server'
map "/admin/resque" do
run Resque::Server.new
end
run Padrino.application
<file_sep>/test/rabotnegi/ui/home_test.rb
require 'test_helper'
ui_test "Home" do
test "home page" do
visit "/"
within '#header' do
assert_has_link "Поиск вакансий"
assert_has_link "Публикация вакансий"
end
end
end
<file_sep>/test/rabotnegi/unit/rabotaru_converter_test.rb
require 'test_helper'
unit_test Rabotaru::Converter do
DATA = ActiveSupport::JSON.decode('{
"publishDate": "Fri, 19 Sep 2008 20:07:18 +0400",
"expireDate": "Fri, 26 Sep 2008 20:07:18 +0400",
"position": "Менеджер",
"link": "http://www.rabota.ru/vacancy27047845.html",
"description": "blah-blah-blah-blah-blah",
"rubric_0": {"id": "19", "value": "IT, компьютеры, работа в интернете"},
"rubric_1": {"id": "14", "value": "Секретариат, делопроизводство, АХО"},
"rubric_2": {"id": "12", "value": "Кадровые службы, HR"},
"city": {"id": "2", "value": "Санкт-Петербург"},
"schedule": {"id": "1", "value": "полный рабочий день"},
"education": {"id": "3", "value": "неполное высшее"},
"experience": {"id": "2", "value": "до 2 лет"},
"employer": {"id": "15440", "value": "Apple", "link": "http://www.rabota.ru/agency15440.html"},
"salary": {"min": "20000", "max": "30000", "currency": {"value": "руб", "id": "2"}},
"responsibility": {"value": "blah-blah-blah"}
}')
setup do
@expected_vacancy = Vacancy.new(
title: 'Менеджер',
city: 'spb',
industry: 'it',
external_id: 27047845,
employer_name: 'Apple',
description: 'blah-blah-blah',
created_at: Time.parse('Fri, 19 Sep 2008 20:07:18 +0400'),
salary: Salary.make(min: 20000.0, max: 30000.0, currency: :rub)
)
@converter = Gore::PureDelegator.new(Rabotaru::Converter.new)
end
test "convert vacancy" do
result = @converter.convert(DATA)
assert_equal @expected_vacancy.attributes.except('_id'), result.attributes.except('_id')
end
test "extract ID from URL" do
assert_equal 1234567, @converter.extract_id('http://www.rabota.ru/vacancy1234567.html')
end
test "convert salaru" do
assert_equal Salary.make(:negotiable => true), @converter.convert_salary('agreed' => 'yes')
assert_equal Salary.make(:max => 25000, :currency => :rub), @converter.convert_salary('max' => '25000', 'currency' => {'value' => 'руб'})
assert_equal Salary.make(:exact => 25000, :currency => :rub), @converter.convert_salary('min' => '25000', 'max' => '25000', 'currency' => {'value' => 'руб'})
assert_equal Salary.make(:min => 17000, :max => 34000, :currency => :rub), @converter.convert_salary('min' => '17000', 'max' => '34000', 'currency' => {'value' => 'руб'})
end
test "convert currency" do
assert_equal :rub, @converter.convert_currency('руб')
assert_equal :usd, @converter.convert_currency('usd')
assert_equal :eur, @converter.convert_currency('eur')
assert_equal :rub, @converter.convert_currency('gbp')
end
end
<file_sep>/app/models/reflections.rb
Gore::MongoReflector.define_metadata do
# desc Vacancy do
# list :industry, :city, [:title, :link, trim: 50], [:employer_name, trim: 40], :created_at, :updated_at, :loaded_at
# list_order [:updated_at, :desc]
# view :id, :title, :city, :industry, :external_id, :employer_name, :created_at, :updated_at, :loaded_at, :cleaned_at, :salary, :description, :poster_ip
# edit title: 'text',
# city_name: ['select', options: :city_options], industry_name: ['select', grouped_options: :industry_options],
# external_id: 'text',
# employer_id: 'text', employer_name: 'text',
# created_at: 'date_time', updated_at: 'date_time',
# description: 'text_area'
# end
desc User do
list :industry, :city, [:ip, :link], [:agent, trim: 100], :created_at
end
# desc Gore::Err, 'errs' do
# list created_at: _, source: :link,
# url: [trim: 60],
# exception: [ ->(err) { "#{err.exception_class}: #{err.exception_message}" }, trim: 100 ]
# view id: _, created_at: _, host: _, source: _,
# url: ->(err) { "#{err.verb} #{err.url}" },
# exception_class: _,
# exception_message: _,
# params: 'hash_view',
# session: 'hash_view', request_headers: 'hash_view', response_headers: 'hash_view', backtrace: :pre
# actions update: false, delete: false
# end
desc Gore::EventLog::Item, 'event_log_items' do
list :created_at, :severity, :source, [:event, 'stringify', link: true], [:data, 'inline_multi_view']
view :id, :created_at, :severity, :source, :event, [:data, 'multi_view'], [:extra, 'hash_view']
actions update: false, delete: false
end
desc Rabotaru::Job, 'rabotaru_jobs' do
list [:id, :link], :state, :created_at, :updated_at, :started_at, :loaded_at, :processed_at, :cleaned_at, :failed_at
list_css_classes { |x| { processed: x.cleaned?, failed: x.failed? } }
view :id, :state, :created_at, :updated_at, :started_at, :loaded_at, :processed_at, :cleaned_at, :failed_at,
"loadings.count", [:error, 'h'], :run_count, [:cities, 'array_inline'], [:industries, 'array_inline'], [:results, 'hash_of_lines']
view_subcollection :loadings, 'rabotaru_loadings'
actions update: false, delete: false
end
desc Rabotaru::Loading, 'rabotaru_loadings' do
list :id, :city, :industry, :state, :error, :changed_at
view :id, :state, :created_at, :changed_at
actions update: false, delete: false
end
end
<file_sep>/lib/gore/event_log.rb
##
# Comments
# * data, extra attributes are not stored when they are nil
# * severity is not stored if it is :info
# * updated_at is not stored
# * created_at is explicitely stored, while it can be extracted from _id
#
class Gore::EventLog
class << self
def write(source, event, severity = :info, data = nil, extra = nil)
return nil unless severity_logged?(severity)
item = Item.new source: source, event: event
# don't store those attributes if they have default values
item.severity = severity unless severity.nil? || severity.to_s == 'info'
item.data = data unless data.nil?
item.extra = extra unless extra.nil?
item.save!
puts "Event: #{item.as_string}" if $log_to_stdout
item
end
%w(debug info warn error fatal).each do |severity|
class_eval <<-ruby
def #{severity}(source, event, data = nil, extra = nil)
write(source, event, :#{severity}, data, extra)
end
ruby
end
SEVERITY_LEVELS = { debug: Logger::DEBUG, info: Logger::INFO, warn: Logger::WARN, error: Logger::ERROR }
def severity_logged?(item_severity)
item_severity_level = SEVERITY_LEVELS[item_severity] || -1
item_severity_level >= Log.level
end
end
module Accessor
def self.included(klass)
klass.class_eval do
def self.log
@log ||= Writer.for_class(self)
end
end
end
def log
self.class.log
end
end
class Writer
attr_accessor :source
def initialize(source)
@source = source.to_s
end
METHODS = %w(write debug info warn error)
def method_missing(selector, *args, &block)
if METHODS.include?(selector.to_s)
Gore::EventLog.send(selector, source, *args, &block)
else
super
end
end
def self.for_class(klass)
new log_key_for(klass)
end
def self.log_key_for(klass)
klass.name.underscore.parameterize('_')
end
end
class Item < Gore::ApplicationModel
store_in collection: "sys.events"
field :source
field :event, type: String
field :severity, type: Symbol
field :data
field :extra, type: Hash
no_update_tracking
def time
id.generation_time
end
def severity
super || :info
end
def as_string
"#{time} #{source}::#{event} (#{Gore.inspect_value(data)})"
end
def to_s
"#{source}::#{event}@#{time}"
end
class << self
def query(options)
return self unless options[:q].present?
source, event = options[:q].split('::')
conditions = {}
conditions[:source] = /^#{source}/ if source.present?
conditions[:event] = /^#{event}/ if event.present?
where(conditions)
end
end
end
end
<file_sep>/test/rabotnegi/functional/vacancies_controller_test.rb
require 'test_helper'
describe "Vacancies controller" do
test 'GET /vacancies/:id via XHR' do
@vacancy = make Vacancy, city: "spb", industry: "it", title: "Программист"
gets URI.encode("/vacancies/#{@vacancy.to_param}"), {}, xhr: true
assert_have_no_selector "meta"
assert_have_selector ".entry-details"
end
test "GET /vacancies/:non-existing" do
get "/vacancies/4e415504e999fb2522000003"
assert_equal 404, response.status
end
test "GET /vacancies/:old-site-id" do
get "/vacancies/123456"
assert_equal 410, response.status
end
test "GET /vacancies/:id-with-wrong-slug" do
@vacancy = make Vacancy, title: "Программист"
get "/vacancies/#{@vacancy.id}-developer"
assert response.redirect?
assert_match URI.encode("/vacancies/#{@vacancy.to_param}"), response.location
end
test 'GET /vacancies/:city/:industry' do
v1 = make Vacancy, city: "spb", industry: "it"
v2 = make Vacancy, city: "spb", industry: "it"
v3 = make Vacancy, city: "msk", industry: "it"
v4 = make Vacancy, city: "spb", industry: "opt"
gets "/vacancies/spb/it"
response.body.must_include v1.title
response.body.must_include v2.title
response.body.wont_include v3.title
response.body.wont_include v4.title
end
test "GET /vacancies/:city/:industry with sorting" do
v1 = make Vacancy, city: "spb", industry: "it", employer_name: "AAA"
v2 = make Vacancy, city: "spb", industry: "it", employer_name: "BBB"
gets "/vacancies/spb/it", sort: "employer_name"
response.body.must_match %r{#{v1.title}.*#{v2.title}}
gets "/vacancies/spb/it", sort: "-employer_name"
response.body.must_match %r{#{v2.title}.*#{v1.title}}
end
test "new" do
gets "/vacancies/new"
assert_contain "Публикация новой вакансии"
end
test "create valid record" do
$all_captchas_are_valid = true
post "/vacancies/create", vacancy: { title: "Developer", city: "msk", industry: "it", salary_text: "55000" }
new_vacancy = Vacancy.last
new_vacancy.wont_be_nil
new_vacancy.title.must_equal "Developer"
new_vacancy.city.must_equal "msk"
new_vacancy.industry.must_equal "it"
new_vacancy.salary.exact.must_equal 55_000
new_vacancy.poster_ip.must_equal "127.0.0.1"
response.must_be :redirect?
response.location.must_match app.url(:vacancies, :show, id: new_vacancy)
end
test "create invalid record" do
post "/vacancies/create", vacancy: { title: nil }
response.status.must_equal 422
Vacancy.last.must_be_nil
assert_contain "Публикация новой вакансии"
end
after do
$all_captchas_are_valid = false
end
end
<file_sep>/Gemfile
source 'https://rubygems.org'
gem 'rake'
gem 'sinatra-flash', require: 'sinatra/flash'
gem 'sass'
gem 'slim'
gem 'haml'
gem 'erubis'
gem 'coffee-script'
gem 'sprockets'
gem 'mongoid'
gem "daemons"
gem "unicode_utils"
gem 'resque'
gem 'rmagick'
gem "syslog-logger"
gem "sanitize"
gem 'padrino', '0.12.4'
# gem "therubyracer" # weird bugs otherwise
group :test do
gem 'mocha'
gem 'minitest', require: "minitest/autorun"
gem 'rack-test', require: "rack/test"
gem "factory_girl"
gem 'turn'
gem 'webrat'
gem 'capybara'
# gem 'capybara-webkit'
end
group :development, :test do
gem 'capistrano'
gem 'thin'
end
<file_sep>/test/rabotnegi/unit/employer_test.rb
require 'test_helper'
unit_test Employer do
setup do
@microsoft = Employer.new(:name=>'Microsoft', :login => 'ms', :password => '123', :password_confirmation => '123')
end
test "creation" do
assert @microsoft.valid?
end
test "creation without password" do
@bad_microsoft = Employer.new(:name => 'Microsoft', :login => 'ms')
assert !@bad_microsoft.valid?
assert @bad_microsoft.errors[:password].any?
end
end
<file_sep>/script/resque
#!/usr/bin/env ruby
require 'daemons'
require 'optparse'
rails_root = File.expand_path('../..', __FILE__)
ENV['RAILS_PROC'] = 'worker'
id = ARGV.shift
raise "Should be used as: resque ID start|stop|restart|run" unless id.to_i > 0
Daemons.run_proc("resque.#{id}", dir: File.join(rails_root, "tmp/pids"), dir_mode: :normal, log_output: true, log_dir: File.join(rails_root, "log")) do
Dir.chdir(rails_root)
require File.join(rails_root, "config/boot.rb")
worker = Resque::Worker.new("*")
worker.verbose = true
worker.work(5)
end
__END__
#!/bin/bash
export JAVA_HOME=/usr/local/java/
CLASSPATH=ajarfile.jar:.
case $1 in
start)
echo $$ > /var/run/xyz.pid;
exec 2>&1 java -cp ${CLASSPATH} org.something.with.main 1>/tmp/xyz.out
;;
stop)
kill `cat /var/run/xyz.pid` ;;
*)
echo "usage: xyz {start|stop}" ;;
esac
exit 0
<file_sep>/lib/gore/pure_delegator.rb
class Gore::PureDelegator < BasicObject
def initialize(target)
@target = target
end
def call(selector, *args, &block)
method_missing(selector, *args, &block)
end
def method_missing(selector, *args, &block)
@target.send(selector, *args, &block)
end
end
<file_sep>/test/rabotnegi/unit/vacancy_test.rb
require 'test_helper'
unit_test Vacancy do
setup do
@vacancy = Vacancy.new
end
test 'default salary' do
assert @vacancy.salary.negotiable?
end
test "#salary_text=" do
vacancy = Vacancy.new(salary: Salary.make(exact: 1000))
assert_equal Salary.make(exact: 1000), vacancy.salary
vacancy.salary_text = "от 5000"
assert_equal Salary.make(min: 5000), vacancy.salary
assert_equal 5000, vacancy.salary_min
assert_equal nil, vacancy.salary_max
end
test "#==" do
assert Vacancy.new != nil
assert Vacancy.new != Vacancy.new
assert Vacancy.new(title: "Boss") != Vacancy.new(title: "Boss")
assert_equal Vacancy.new(title: "Boss", external_id: 100), Vacancy.new(title: "Developer", external_id: 100)
end
test "#to_param" do
v1 = make(Vacancy, title: "Ruby Разработчик")
assert_equal "#{v1.id}-ruby-разработчик", v1.to_param
v1.title = nil
assert_equal v1.id.to_s, v1.to_param
end
test "long slugs" do
assert_equal "ruby-разработчик", make(Vacancy, title: "Ruby Разработчик").slug
assert_equal "менеджер-по-продажам-промышленного-оборудования", make(Vacancy, title: "Менеджер по продажам промышленного оборудования").slug
assert_equal "ааааааа-бббббббббб-вввввввввв-ггггггггггг-дддддддд-еееееееее", make(Vacancy, title: "Ааааааа Бббббббббб вввввввввв ггггггггггг дддддддд еееееееее жжжжжжж").slug
end
test "#get" do
v1 = make Vacancy
assert_equal v1, Vacancy.get(v1.id)
assert_equal v1, Vacancy.get(v1.id.to_s)
assert_equal v1, Vacancy.get("#{v1.id}-xxxx-1111")
assert_equal v1, Vacancy.get("#{v1.id}-1111-xxxx")
assert_nil Vacancy.get("4daebd518c2e000000000000")
end
test "#search" do
v1_msk_retail = make Vacancy, title: "query-1", city: "msk", industry: "retail"
v1_spb_it = make Vacancy, description: "query-1", city: "spb", industry: "it"
v2 = make Vacancy, description: "query-2"
v3 = make Vacancy, employer_name: "query-3"
Vacancy.search(q: "query-1").must_eq [v1_msk_retail, v1_spb_it]
Vacancy.search(q: "query-2").must_eq [v2]
Vacancy.search(q: "query-3").must_eq [v3]
Vacancy.search(q: "query-1", city: "msk").must_eq [v1_msk_retail]
Vacancy.search(q: "query-1", industry: "it").must_eq [v1_spb_it]
end
end
<file_sep>/test/lib/stubbing_test.rb
require "test_helper"
unit_test Gore::Stubbing do
dummy = temp_class do
def self.foo(param)
"original #{param}"
end
end
test "stubbing/unstubbing" do
assert_equal "original passed", dummy.foo("passed")
Gore::Stubbing.stub(dummy, :foo) { |param| "patched #{param}" }
assert_equal "patched passed", dummy.foo("passed")
Gore::Stubbing.unstub_all
assert_equal "original passed", dummy.foo("passed")
end
end
<file_sep>/test/lib/err_mailer_test.rb
require 'test_helper'
describe "Gore::Err mailer" do
test "notification" do
err = Gore::Err.new(
controller: "vacancies",
action: "show",
url: "http://rabotnegi.test/vacancies/1234",
verb: "GET",
host: "rabotnegi.test",
time: Time.current,
session: {session_var_1: 100, session_var_2: 200},
params: {parameter_1: 'parameter_1_value'},
exception_class: 'ApplicationError',
exception_message: "a test thing",
cookies: ["uid"],
backtrace: "stack line 1\nstack line 2\nstack line 3",
request_headers: {'Header-1' => '100', 'Header-2' => '200'},
response_headers: {}
)
email = err.notify
email.to.must_equal [Rabotnegi.config.err_recipients]
email.from.must_equal [Rabotnegi.config.err_sender]
email.subject.must_equal "[rabotnegi.ru errors] vacancies/show - ApplicationError - a test thing"
body = email.body.to_s
body.must_match "GET http://rabotnegi.test/vacancies/1234"
body.must_match "parameter_1"
body.must_match "parameter_1_value"
body.must_match "stack line 1"
body.must_match "stack line 2"
end
end
<file_sep>/app/models/rabotaru/loading.rb
module Rabotaru
class Loading
include Mongoid::Document
field :city, type: Symbol
field :industry, type: Symbol
field :state, type: Symbol, default: 'pending'
field :error, type: String
field :fail_count, type: Integer
# key :city, :industry
embedded_in :job, class_name: 'Rabotaru::Job'
validates_presence_of :city, :industry
def_state_predicates 'state', :pending, :queued, :started, :done, :skipped, :failed
def queue
mark :queued
Gore.enqueue(Rabotaru::Loading, :run, job.id, id)
end
def run
mark :started
loader = Loader.new(city, industry, job.id)
loader.load
mark :done
rescue => e
Gore::Err.register("Rabotaru::Loading.run", e, params: {city: city, industry: industry})
mark :failed, error: Gore.format_error(e), fail_count: fail_count.to_i + 1
end
def changed_at
self.class._states.map { |state| send("#{state}_at") }.compact.max
end
def inspect(*args)
Gore.inspection(self, [city, industry], state)
end
def to_s
inspect
end
def self.run(job_id, loading_id)
job = Job.find(job_id)
loading = job.loadings.find(loading_id)
loading.run
end
end
end
<file_sep>/app/models/vacancy.rb
class Vacancy < Gore::ApplicationModel
field :title
field :description
field :external_id, type: Integer
field :industry
field :city
field :salary_min, type: Integer
field :salary_max, type: Integer
field :employer_id, type: Integer
field :employer_name
field :poster_ip, type: String
field :loaded_at, type: Time
field :cleaned_at, type: Time
index city: 1
index industry: 1
index city: 1, industry: 1
index city: 1, title: 1
validates_presence_of :title, :industry, :city
belongs_to :employer
scope :old, ->(date = 1.month.ago) { where(:updated_at.lt => date) }
before_save do
self.employer_id = employer.id if employer
self.employer_name = employer.name if employer
end
def ==(other)
Vacancy === other && external_id? ? self.external_id == other.external_id : super
end
def to_s
title
end
def to_param
[id, slug].reject(&:blank?).join('-')
end
def slug
Gore::RussianInflector.parameterize(title).truncate(60, separator: '-', omission: '')
end
def city_name
City.get(city).name
end
def industry_name
Industry.get(industry).name
end
def salary
Salary.new(salary_min, salary_max)
end
def salary=(salary)
self.salary_min = self.salary_max = nil
self.salary_min = salary.min if salary
self.salary_max = salary.max if salary
end
def salary_text
salary.try(:text)
end
def salary_text=(value)
self.salary = Salary.parse(value)
end
def self.search(params)
params = params.symbolize_keys
params.assert_valid_keys(:city, :industry, :q)
query = Regexp.new(params[:q] || "", true)
scope = self
scope = scope.where(city: params[:city]) if params[:city].present?
scope = scope.where(industry: params[:industry]) if params[:industry].present?
scope = scope.any_of({title: query}, {employer_name: query}, {description: query}) if params[:q].present?
scope
end
instance_eval { alias query search }
def self.get(id)
id ||= ""
id = id.gsub(/\-.*/, '') if String === id
where(_id: id).first
end
def self.cleanup
old.destroy
end
end
<file_sep>/lib/gore/log_filter.rb
module Gore::LogFilter
FILTERED_LOG_ENTRIES = [
"Served asset", 'Started GET "/assets/',
"['system.namespaces'].find({})",
"MONGODB [WARNING] Please note that logging negatively impacts client-side performance.",
"MONGODB admin['$cmd'].find({:ismaster=>1}).limit(-1)",
"MONGODB admin['$cmd'].find({:buildinfo=>1}).limit(-1)"
]
def self.register
Padrino::Logger.class_eval do
def write(message = nil)
return if String === message && FILTERED_LOG_ENTRIES.any? { |pattern| message.include?(pattern) }
self << message
end
end
end
end
<file_sep>/lib/gore/sass_functions.rb
module Gore::SassFunctions
def self.register
Sass::Script::Functions.module_eval do
def image_url(source)
::Sass::Script::String.new "url(/rabotnegi/assets/#{source.value})"
end
declare :image_url, [:source]
end
end
end
<file_sep>/test/lib/sort_expressions_test.rb
require "test_helper"
unit_test Gore::SortExpressions do
test "decode_order_to_mongo" do
assert_equal [["date", Mongo::ASCENDING]], Gore::SortExpressions.decode_order_to_mongo("date")
assert_equal [["date", Mongo::DESCENDING]], Gore::SortExpressions.decode_order_to_mongo("-date")
end
end
<file_sep>/app/controllers/admin.rb
Rabotnegi.controller :admin do
before { admin_required }
layout 'admin'
get :index do
render "admin/dashboard"
end
end
Rabotnegi.controller :admin_items, map: "admin/:collection/" do
before { admin_required }
before { @collection = Gore::MongoReflector.metadata_for(params[:collection]) }
layout "admin"
get :index, map: "/#{@_map}" do
@scope = @collection.klass.respond_to?(:query) ? @collection.klass.query(q: params[:q]) : @collection.klass
@models = @scope.order_by(@collection.list_order).paginate(params[:page], @collection.list_page_size)
render "admin_items/index"
end
get :show, map: ":id" do
@model = @collection.klass.get(params[:id])
render "admin_items/show"
end
get :edit, map: "edit/:id" do
@model = @collection.klass.get(params[:id])
render "admin_items/edit"
end
post :update, map: "update/:id" do
@model = @collection.klass.get(params[:id])
update_model @model, params[@collection.singular], url(:admin_item, @collection.key, @model)
end
post :delete, map: "delete/:id" do
@model = @collection.klass.get(params[:id])
@model.destroy
flash.notice = "#{@model} была удалена"
redirect url(:admin_items, @collection.key)
end
end
<file_sep>/lib/gore/controller_helpers.rb
module Gore::ControllerHelpers
module Urls
def absolute_url(*args)
uri url(*args)
end
def current_url(params = {})
current_path(params.stringify_keys)
end
def asset_path(kind, source)
return source if source =~ /^http/
return source if source =~ /^\//
asset = settings.assets.find_asset(source)
return nil unless asset
"/rabotnegi/assets/" + asset.digest_path
end
def decode_order_to_mongo(param = params[:sort])
Gore::SortExpressions.decode_order_to_mongo(param)
end
def encode_order(field, reverse_by_default = false, param = params[:sort])
Gore::SortExpressions.encode_order(field, params, reverse_by_default)
end
end
module Identification
# (vacancy#1234) => "v-2134"
def web_id_for_record(record)
return nil unless record
[web_prefix_for_class(record.class), record.id].join("-")
end
# (Vacancy) => "v"
# (User) => "user"
def web_prefix_for_class(klass)
case klass
when Vacancy then "v"
else ActiveModel::Naming.singular(record)
end
end
# (vacancy#1234) => "v-1234"
# (:edit, vacancy#1234, :custom) => "edit-v-1234-custom"
def web_id(*args)
args.map { |x| x.respond_to?(:to_key) ? web_id_for_record(x) : x }.join("-")
end
end
module Users
def current_user
return @current_user if defined? @current_user
@current_user = find_user_by_cookie || find_user_by_ip || create_new_user
store_user_cookie unless request.cookies['uid']
@current_user
end
def find_user_by_cookie
return nil unless request.cookies['uid']
user_id = settings.message_encryptor.decrypt_and_verify(request.cookies['uid'])
User.find(user_id)
rescue
response.delete_cookie 'uid'
nil
end
def find_user_by_ip
User.where(agent: request.user_agent, ip: request.ip).first
end
def create_new_user
bot? ? User.new : User.create!(agent: request.user_agent, ip: request.ip)
end
def store_user_cookie
user_token = settings.message_encryptor.encrypt_and_sign(@current_user.id)
response.set_cookie 'uid', value: user_token, path: request.script_name, expires: 2.years.from_now
end
#
# Authentication
#
def admin_required
return if Gore.env.development?
halt 401, {"WWW-Authenticate" => %(Basic realm="Restricted Area")}, "" unless authorized?
end
def authorized?
@auth ||= Rack::Auth::Basic::Request.new(request.env)
@auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ['admin', '0000']
end
#
# Other
#
def bot?
false # request.user_agent =~ /Googlebot|YandexBot|Deepnet|Nigma|bingbot|stat.cctld.ru/
end
# def employer_required
# current_employer || redirect(employer_path)
# end
#
# def resume_required
# current_resume || redirect_to(worker_login_path)
# end
#
# def current_employer
# return @current_employer if defined? @current_employer
# @current_employer = session[:employer_id] ? Employer.get(session[:employer_id]) : nil
# end
#
# def current_resume
# return @current_resume if defined? @current_resume
# resume_id = session[:resume_id] || cookies[:resume_id]
# if @current_resume = resume_id ? Resume.get(resume_id) : nil
# session[:resume_id] = @current_resume.id
# cookies[:resume_id] = @current_resume.id
# else
# session[:resume_id] = nil
# cookies.delete(:resume_id)
# end
# @current_resume
# end
end
module Captchas
def captcha_valid?
return @captcha_valid unless @captcha_valid.nil?
return true if $all_captchas_are_valid
@captcha_valid = Gore::Captcha.valid?(params[:captcha_id], params[:captcha_text])
end
def captcha_valid!(object = nil)
if captcha_valid?
true
else
object.errors.add(:captcha, "invalid") if object
log.warn 'captcha_wrong', ip_adress: request.ip, captcha_text: params[:captcha_text]
false
end
end
def captcha_section
if captcha_valid?
hidden_field_tag(:captcha_text, value: params[:captcha_text]) + hidden_field_tag(:captcha_id, value: params[:captcha_id])
else
@captcha = Gore::Captcha.create!
@captcha_url = url(:captcha, id: @captcha)
div "captcha" do
image_tag(@captcha_url, width: 100, height: 28) + br + text_field_tag(:captcha_text) + hidden_field_tag(:captcha_id, value: @captcha.id)
end
end
end
end
end
<file_sep>/lib/gore/err.rb
class Gore::Err < Gore::ApplicationModel
store_in collection: "sys.exceptions"
field :source
field :host
field :params, type: Hash
field :exception_class
field :exception_message
field :backtrace
field :controller
field :action
field :url
field :verb
field :session, type: Hash
field :cookies, type: Hash
field :request_headers, type: Hash
field :response_headers, type: Hash
index created_at: 1
validates_presence_of :exception_class
scope :recent, ->(since = 1.hour.ago) { where(:created_at.gte => since) }
def source
self[:source] || "#{controller}/#{action}"
end
def notify
err = self
Rabotnegi.email do
def method_missing(selector, *args, &block)
super
rescue NoMethodError
@__dummy__ ||= Rabotnegi.new!
@__dummy__.respond_to?(selector) ? @__dummy__.send(selector, *args, &block) : raise
end
from Rabotnegi.config.err_sender
to Rabotnegi.config.err_recipients
subject "[rabotnegi.ru errors] #{err}"
content_type "text/html; charset=utf-8"
locals err: err
body render("err_notification")
end
end
def to_s
"#{source} - #{exception_class} - #{exception_message.to_s.truncate(40)}"
end
class << self
def register(source, exception, data = {})
Log.error "!!! Error logged: #{exception.class} #{exception.message}"
data.update(
source: source,
host: Socket.gethostname,
time: Time.now,
exception_class: exception.class.name,
exception_message: exception.message,
backtrace: exception.backtrace.join("\n")
)
err = create!(data)
err.notify if recent.count < Rabotnegi.config.err_max_notifications_per_hour
err
rescue => e
puts "!!! ERROR IN ERROR LOGGING: #{e.class}: #{e.message}"
puts e.backtrace.join("\n")
end
def query(params)
params = params.symbolize_keys
params.assert_valid_keys(:q)
query = Regexp.new(params[:q] || "", true)
scope = self
scope = scope.any_of({exception_class: query}, {exception_message: query}, {url: query}) if params[:q].present?
scope
end
end
end
<file_sep>/config/boot.rb
# Defines our constants
RACK_ENV = ENV['RACK_ENV'] ||= 'development' unless defined?(RACK_ENV)
PADRINO_ROOT = File.expand_path('../..', __FILE__) unless defined?(PADRINO_ROOT)
# Load our dependencies
require 'rubygems' unless defined?(Gem)
require 'bundler/setup'
# bundler_group = ENV["RACK_ENV"]
# bundler_group = "test" if bundler_group == "testui"
Bundler.require(:default, RACK_ENV)
# Padrino::Logger::Config[:production] = { :log_level => :info, :stream => :to_file }
# Padrino::Logger::Config[:testprod] = { :log_level => :info, :stream => :stdout }
# Padrino::Logger::Config[:testui] = { :log_level => :info, :stream => :stdout }
#
# silence_warnings { Sass::Engine::DEFAULT_OPTIONS = Sass::Engine::DEFAULT_OPTIONS.dup.merge(style: :compact) }
Padrino.before_load do
# I18n.locale = 'ru'
end
Padrino.after_load do
Gore::SassFunctions.register
end
Padrino.load!
<file_sep>/test/support/data.rb
# Syntax: vacancy(title, industry = 'it', city = 'spb', other = {})
def vacancy(title, *args)
other = args.extract_options!
attrs = {title: title}
attrs[:industry] = args.first || 'it'
attrs[:city] = args.second || 'spb'
attrs[:created_at] = "2011-09-01"
attrs[:description] = "lorem ipsum sit amet"
attrs.merge!(other)
Vacancy.create!(attrs)
end
vacancy "Designer", employer_name: "Apple"
vacancy "Ruby Developer", employer_name: "Apple"
vacancy "Python Developer", employer_name: "Apple"
vacancy "JavaScript Developer", employer_name: "Apple", description: "Do some JS and frontend stuff"
vacancy "Manager", employer_name: "Apple"
vacancy "Tester", employer_name: "Apple"
vacancy "Designer", city: 'msk', employer_name: "<NAME>"
vacancy "Ruby Developer", city: 'msk', employer_name: "Msk Co"
vacancy "Бухгалтер", "retail", employer_name: "<NAME>"
vacancy "Главбух", "retail", employer_name: "<NAME>"
vacancy "Ассистент", "retail", employer_name: "<NAME>"
vacancy "Гендир", "retail", employer_name: "<NAME>"
<file_sep>/test/lib/err_test.rb
require 'test_helper'
unit_test Gore::Err do
ERROR_DATA = {
url: "http://rabotnegi.test/vacancies/1234",
verb: "GET",
session: {session_var_1: 100, session_var_2: 200},
params: {parameter_1: 'parameter_1_value'},
cookies: ["uid"],
request_headers: {'Header-1' => '100', 'Header-2' => '200'},
response_headers: {}
}
setup do
sent_emails.clear
Gore::Err.delete_all
@exception = ArgumentError.new("test error message")
@exception.set_backtrace ["stack line 1", "stack line 2", "stack line 3"]
end
test "register a request error" do
err = Gore::Err.register("vacancies/show", @exception, ERROR_DATA)
Gore::Err.count.must_equal 1
Gore::Err.last.exception_message.must_equal "test error message"
Gore::Err.last.exception_class.must_equal "ArgumentError"
Gore::Err.last.backtrace.must_equal ["stack line 1", "stack line 2", "stack line 3"].join("\n")
assert_emails 1
sent_emails.last.subject.must_match "test error message"
end
test "register an error when there were too many other errors this hour" do
Rabotnegi.config.err_max_notifications_per_hour.times { Gore::Err.create!(ERROR_DATA.merge(exception_class: "ArgumentError")) }
err = Gore::Err.register("vacancies/show", @exception, ERROR_DATA)
assert_equal Rabotnegi.config.err_max_notifications_per_hour + 1, Gore::Err.count
assert_emails 0
end
end
<file_sep>/script/rr_scheduler.rb
#!/usr/bin/env ruby
require 'pp'
# require 'daemons'
# require 'optparse'
#
rails_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))
ENV['RAILS_PROC'] = 'worker-rr'
#
# id = ARGV.shift
# raise("Numeric ID should be given as the first argument") unless id.to_i > 0
#
# Daemons.run_proc("resque.#{id}", dir: File.join(rails_root, "tmp/pids"), dir_mode: :normal, log_output: true, log_dir: File.join(rails_root, "log")) do
# Dir.chdir(rails_root)
# require File.join(rails_root, "config/environment")
# worker = Resque::Worker.new("*")
# worker.verbose = true
# worker.work(5)
# end
require File.join(rails_root, "config/environment")
Rabotaru.start_job
<file_sep>/app/models/rabotaru.rb
module Rabotaru
def self.start_job(options = {})
Job.create!(options).run
end
end
<file_sep>/lib/gore/russian_inflector.rb
module Gore::RussianInflector
def self.inflect(number, word, end1, end2, end5, strategy = :normal)
number_by_100 = number % 100
ending = case strategy
when :normal
case number_by_100
when 1 then end1
when 2..4 then end2
when 5..20 then end5
else
case number_by_100 % 10
when 1 then end1
when 2..4 then end2
when 0, 5..9 then end5
end
end
when :more
case number_by_100
when 1 then end2
when 2..20 then end5
else
case number_by_100 % 10
when 1 then end2
when 0, 2..9 then end5
end
end
end
word + ending
end
def self.parameterize(string, sep = "-")
string ||= ""
parameterized_string = UnicodeUtils.downcase(string).gsub(/[^a-z0-9\u0430-\u044f\-_]+/i, sep)
if sep.present?
re_sep = Regexp.escape(sep)
parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
end
parameterized_string
end
end
if $0 == __FILE__
1.upto(150) do |i|
print "#{i} "
print Gore::RussianInflector.inflect(i, 'ваканс', 'ия', 'ии', 'ий' )
print "\n"
end
1.upto(150) do |i|
print "более #{i} "
print Gore::RussianInflector.inflect(i, 'ваканс', 'ия', 'ии', 'ий', :more)
print "\n"
end
end
<file_sep>/lib/gore/event_handling.rb
module Gore::EventHandling
def event_handlers
@event_handlers ||= {}
end
def event_handlers_for(event)
event = event.to_sym
event_handlers[event] || []
end
def add_event_handler(event, &block)
event = event.to_sym
event_handlers[event] ||= []
event_handlers[event] << block
end
def remove_event_handler(event, &block)
event = event.to_sym
event_handlers[event] ||= []
event_handlers[event].delete_if { |h| h == block }
end
def raise_event(event, &block)
event = event.to_sym
return if event_handlers[event].blank?
event_data = block.call
event_handlers[event].each { |handler| handler.call(event_data) }
end
end
<file_sep>/config/database.rb
database_name = case Padrino.env
when :development then 'rabotnegi_dev'
when :production then 'rabotnegi_prod'
when :test then 'rabotnegi_test'
when :testui then 'rabotnegi_testui'
when :testprod then 'rabotnegi_dev'
end
# mongoid_options = {}
# mongoid_options = {logger: Padrino.logger} if Padrino.env == :development # && ($*.first !~ /^(test|routes)/)
old_log_level, Padrino.logger.level = Padrino.logger.level, Padrino::Logger::Levels[:error]
# Mongoid.database = Mongo::Connection.new('localhost', Mongo::Connection::DEFAULT_PORT, mongoid_options).db(database_name)
Mongoid.logger = Padrino.logger
Mongoid.load!("config/mongoid.yml")
Padrino.logger.level = old_log_level
# You can also configure Mongoid this way
# Mongoid.configure do |config|
# name = @settings["database"]
# host = @settings["host"]
# config.master = Mongo::Connection.new.db(name)
# config.slaves = [
# Mongo::Connection.new(host, @settings["slave_one"]["port"], :slave_ok => true).db(name),
# Mongo::Connection.new(host, @settings["slave_two"]["port"], :slave_ok => true).db(name)
# ]
# end
<file_sep>/test/rabotnegi/unit/user_test.rb
require 'test_helper'
unit_test User do
test "#favorite_vacancies" do
user = User.create!
v1 = make Vacancy
v2 = make Vacancy
user.favorite_vacancies << v1.id
user.save!
user.reload.favorite_vacancies.must_equal [v1.id]
user.favorite_vacancies << BSON::ObjectId(v2.id.to_s)
user.save!
user.reload.favorite_vacancies.must_equal [v1.id, v2.id]
end
end
<file_sep>/app/models/employer.rb
class Employer < Gore::ApplicationModel
field :name
field :login
field :password
field :id, type: Integer
validates_presence_of :name, :login, :password
validates_uniqueness_of :login
validates_confirmation_of :password
has_many :vacancies
attr_accessor :password_confirmation
def to_s
name
end
def add_vacancy(vacancy)
vacancy.employer_id = id
vacancy.employer_name = name
vacancies << vacancy
end
def self.authenticate(login, password)
where(:login => login, :password => <PASSWORD>).first || raise(ArgumentError)
end
end
<file_sep>/test/rabotnegi/unit/rabotaru_loader_test.rb
require 'test_helper'
unit_test Rabotaru::Loader do
setup do
@directory = Rabotnegi.config.rabotaru_dir.join(Gore.date_stamp)
end
teardown do
FileUtils.rm_rf(@directory)
end
test "load loads the feed from the web and writes it to the file" do
Http.stubs(:get).returns("downloaded data")
loader = Rabotaru::Loader.new("spb", "it")
loader.load
assert @directory.directory?
assert_equal "downloaded data", @directory.join("spb-it.json").read
end
test "load doesn't reload the file if it already exists" do
@directory.mkpath
File.write(@directory.join("spb-it.json"), "existing data")
Http.stubs(:get).never
loader = Rabotaru::Loader.new("spb", "it")
loader.load
assert_equal "existing data", @directory.join("spb-it.json").read
end
end
<file_sep>/test/rabotnegi/unit/vacancy_cleaner_test.rb
require 'test_helper'
unit_test VacancyCleaner do
test "clean title" do
assert_equal "Помошник повара", VacancyCleaner.clean_title("ПОМОШНИК ПОВАРА")
assert_equal "Помошник повара", VacancyCleaner.clean_title("помошник повара")
assert_equal "Программист на .NET", VacancyCleaner.clean_title("программист на .NET")
assert_equal %{"Quotes" «Rusquotes» – 'Quote'}, VacancyCleaner.clean_title(""Quotes" «Rusquotes» – 'Quote'")
end
test "clean employer name" do
assert_equal %{"Quotes" «Rusquotes» – 'Quote'}, VacancyCleaner.clean_employer_name(""Quotes" «Rusquotes» – 'Quote'")
end
test "clean description" do
f = ->(str) { VacancyCleaner.clean_description(str) }
assert_equal %{, "}, f.(" ‚ "")
assert_equal "<p>aa bb </p><p>cc </p>", f.(" aa bb \n cc \n ")
assert_equal "TEXT", f.("<strong><strong><strong>TEXT</strong></strong></strong>")
assert_equal "<h4>Требования</h4>", f.("<strong><strong><strong>Требования</strong></strong></strong>")
assert_equal "<p>• hello</p>", f.("<p> - hello</p>")
assert_equal "<p>• hello</p>", f.("<p> * hello</p>")
assert_equal "<p>• hello</p>", f.("<p>* hello</p>")
# assert_equal "<p>• hello</p>", f.("<p> • hello</p>")
end
test "clean" do
vacancy = make Vacancy, title: "РАБОЧИЙ", employer_name: ""Газпром"", description: "<strong>Тест</strong>"
VacancyCleaner.clean(vacancy)
vacancy.reload
assert_equal "Рабочий", vacancy.title
assert_equal '"Газпром"', vacancy.employer_name
assert_equal "Тест", vacancy.description
original_data = JSON.parse Rabotnegi.config.original_vacancies_data_dir.join(Time.now.strftime("%Y%m")).join("#{vacancy.id}.json").read
assert_equal "РАБОЧИЙ", original_data["title"]
assert_equal '"Газпром"', original_data["employer_name"]
assert_equal "<strong>Тест</strong>", original_data["description"]
end
end
<file_sep>/script/test_encryption.rb
secret = Rabotnegi::Application.config.secret_token
message = Vacancy.first.id
verifier = ActiveSupport::MessageVerifier.new(secret)
encryptor = ActiveSupport::MessageEncryptor.new(secret)
p verifier.generate(message), encryptor.encrypt_and_sign(message), encryptor.encrypt_and_sign(message)
p "BAh7B0kiD3Nlc3Npb25faWQGOgZFRiIlZDFkOGM0N2Y4NzZkMGQ2MDhmYjM3OGY5YWY2N2IzMjNJIhBfY3NyZl90b2tlbgY7AEZJIjE3aHNEVjk2VmRhbVQyOVZJUVZjSHVKWHYwRGliSXFyRDQvRGNxeHVmUWdVPQY7AEY%3D--4448899871ab030f6af4b3489efd5939ba529efe"
<file_sep>/test/support/mocks.rb
module CurrencyConverter
@@rates = { rub: 1.0, usd: 25.0, eur: 35.0 }
end
<file_sep>/lib/gore/mongo_reflector.rb
class Gore::MongoReflector
cattr_accessor :collections
@@collections = {}
def self.metadata_for(key) @@collections[key.to_s] || Collection.new(key.to_s.classify.constantize) end
def self.define_metadata(&block) Builder.new.instance_eval(&block) end
class Collection
attr_accessor :klass, :key
attr_accessor :list_fields, :list_order, :list_page_size, :list_css_classes
attr_accessor :view_fields, :view_subcollections, :edit_fields, :actions
def initialize(klass, key = nil)
@klass = klass
@key = key || @klass.model_name.plural
@view_subcollections = []
@list_order = [:_id, :desc]
@list_page_size = 40
@list_css_classes = ->(m){}
@actions = {}
end
def searchable?
@klass.respond_to?(:query)
end
def to_param
key
end
def plural
@klass.model_name.plural
end
def singular
@klass.model_name.singular
end
def list_fields
@list_fields || klass_fields
end
def view_fields
@view_fields || klass_fields
end
def stored_fields
@klass.fields.reject{ |k,f| k.starts_with?('_') }.map{ |k,f| k }
end
private
def klass_fields
@klass_fields ||= klass.fields.
reject { |key, mongo_field| key == '_type' }.
map { |key, mongo_field| Field.new(key, collection: self) }
end
end
class Field
attr_accessor :name, :format, :args
attr_accessor :trim, :css, :link
attr_accessor :collection
def initialize(name, options = {})
@name = name.to_s
assign_attributes!(options)
end
def title
key = @name.gsub('.', '_')
I18n.t(
"attributes.#{collection.singular}.#{key}",
default: [:"attributes.common.#{key}", key.humanize]
)
end
def custom?
format.is_a?(Proc)
end
def css
Gore.css_classes_for @css, wide: format.in?([:hash, :pre])
end
def inspect
Gore.inspection(self, name, format: format)
end
def helper
case format
when 'text' then 'text_field'
when 'date_time' then 'text_field'
else format
end
end
def helper_args
args
end
end
class Subcollection
attr_accessor :key, :accessor
def initialize(accessor, key)
@accessor = accessor
@key = key
end
def title
I18n.t("attributes.#{collection.singular}.#{accessor}",
default: [:"attributes.common.#{accessor}", accessor.to_s.humanize]
)
end
def collection
Gore::MongoReflector.metadata_for(key)
end
end
class Builder
attr_accessor :current_collection
def desc(klass, key = nil, &block)
@current_collection = Collection.new(klass, key)
Gore::MongoReflector.collections[@current_collection.key] = @current_collection
instance_eval(&block) if block_given?
@current_collection
end
def list(*params)
@current_collection.list_fields = build_fields(params)
end
def list_order(value)
@current_collection.list_order = value
end
def list_page_size(value)
@current_collection.list_page_size = value
end
def list_css_classes(&block)
@current_collection.list_css_classes = block
end
def actions(params = {})
@current_collection.actions = params
end
def view(*params)
@current_collection.view_fields = build_fields(params)
end
def edit(field_specs)
@current_collection.edit_fields = field_specs.map do |key, spec|
if Array === spec
helper = spec.shift
args = spec
else
helper = spec
args = []
end
Field.new(key, format: helper, args: args, collection: @current_collection)
end
end
def view_subcollection(accessor, key)
@current_collection.view_subcollections << Subcollection.new(accessor, key)
end
def _
end
private
# Accepts a list of:
# :name
# :name, :format, option1: 'value1'
# :name, [:format, option1: 'value1']
def build_fields(params_list)
params_list = params_list.first.to_a if Hash === params_list.first
params_list.map do |params|
if Array === params
params.flatten! if Array === params.second
options = params.extract_options!
name = params.first
format = params.second
else
name = params
options = {}
end
attributes = {format: format, collection: @current_collection}.merge(options)
Field.new(name, attributes)
end
end
end
end
<file_sep>/test/rabotnegi/unit/resume_test.rb
require 'test_helper'
unit_test Resume do
setup do
@resume = Resume.new
end
test "name format" do
assert_equal 'Mitya', Resume.new(:fname => 'Mitya').name
assert_equal '<NAME>', Resume.new(:fname => 'Mitya', :lname => 'Ivanov').name
end
end
<file_sep>/Capfile
load 'deploy' if respond_to?(:namespace)
load 'deploy/assets'
require 'bundler/capistrano'
Dir['lib/recipes/*.cap'].each { |recipe| load(recipe) }
set :repository, "<EMAIL>:dmitryso/boxx.git"
set :deploy_via, :remote_cache # remote_cache | checkout
set :scm, :git
set :user, "apprunner"
set :password, ENV["<PASSWORD>"]
set :git_enable_submodules, true
set :keep_releases, 3
set :sudo, 'sudo'
set :use_sudo, false
set :rails_env, :production
set :sudo_prompt, "xxxx"
set :bundle_without, [:development, :test]
set :shared_children, fetch(:shared_children) + %w(data)
set :public_children, []
set :project, "rabotnegi"
set :application, "rabotnegi"
set :domain, "rabotnegi.ru"
set :host, "www.rabotnegi.ru"
set :deploy_to, "/app/#{application}"
set :git_host, "bitbucket.org"
set :git_key, "/users/dima/.ssh/id_main"
server host, :web, :app, :db, :primary => true
# set :default_environment, { RUBYOPT: "-Ku" }
# set :ssh_options, {keys: ["#{ENV['HOME']}/.ssh/id_rsa"]}
default_run_options[:pty] = true # required for the first time repo access to answer "yes"
set :passenger_config_path, "/etc/apache2/sites-available/#{application}"
set :logrotate_config_path, "/etc/logrotate.d/#{application}"
set :nginx_config_path, "/opt/nginx/conf/sites/#{application}"
set :cron_config_path, "/etc/cron.d/#{application}"
set :base_path, "/data"
set :backups_path, "/data/backup"
set :backups_bucket, "rabotnegi_backups"
set :logs_path, "/data/log"
set :tmp_path, "/data/tmp"
set :app_log_path, "#{logs_path}/#{project}.log"
set :database, "rabotnegi_prod"
set :local_database, "rabotnegi_dev"
set :collections_to_restore, "vacancies"
set :admin_email, "<EMAIL>"
# deploy
# update
# update_code
# strategy.deploy!
# deploy:assets:symlink
# finalize_update (symlink shared log/pid/system dirs)
after "deploy:finalize_update", "deploy:update_custom_symlinks"
# bundle:install
# deploy:assets:precompile
# symlink
# restart
after "deploy", "crontab:install"
after "deploy", "resque:restart"
cron "15,30,45", "vacancies:kill_spam"
cron "0 3", "vacancies:cleanup"
cron "30 5", "rabotaru:start_job"
cron "0 4,16", "data:dump DB=#{database} DIR=#{backups_path} BUCKET=#{backups_bucket}"
cron "*/5", "cron:ping"
task :demo do
end
<file_sep>/test/rabotnegi/functional/controllers_test.rb
require 'test_helper'
describe "Controllers" do
test "default locale" do
gets "/tests/noop"
I18n.locale.must_equal :ru
end
test "error notifications" do
Gore::Err.delete_all
assert_raises ArgumentError do
gets "/tests/error"
end
Gore::Err.count.must_eq 1
assert_emails 1
end
test "sitemap" do
get "/sitemap.xml"
response.must_be :ok?
response.body.must_match "/vacancies/msk/office"
response.body.must_match "/vacancies/spb/it"
end
describe "current user" do
setup do
@user_1 = User.create!(ip: "2.2.2.1")
@user_2 = User.create!(agent: "test browser", ip: "2.2.2.2")
@user_3 = User.create!(ip: "2.2.2.3")
end
it "find the user when a valid user_id cookie is provided" do
set_cookie "uid=#{URI.encode_www_form_component app.message_encryptor.encrypt_and_sign(@user_1.id)}"
gets "/tests/noop"
app.last_instance.current_user.must_equal @user_1
end
it "find the user by the user agent and ip address" do
gets "/tests/noop", {}, {"REMOTE_ADDR" => "2.2.2.2", "HTTP_USER_AGENT" => "test browser"}
app.last_instance.current_user.must_eq @user_2
end
it "create a new one when can't find an existing" do
gets "/tests/noop", {}, {"REMOTE_ADDR" => "3.3.3.3", "HTTP_USER_AGENT" => "another browser"}
current_user = app.last_instance.current_user
current_user.wont_be_nil
current_user.wont_be :in?, [@user_1, @user_2, @user_3]
current_user.ip.must_eq "3.3.3.3"
current_user.agent.must_eq "another browser"
end
end
end
<file_sep>/test/rabotnegi/functional/helpers_test.rb
require 'test_helper'
describe "Helpers" do
test "web_id" do
vacancy = make Vacancy
get "/tests/noop"
assert_equal "v-#{vacancy.id}", helpers.web_id(vacancy)
assert_equal "v-#{vacancy.id}-details", helpers.web_id(vacancy, :details)
end
end
<file_sep>/lib/ext/log_helpers.rb
# # __w(customer.name, "Customer") => /// Customer = "Joe"
# # __w(customer.name) => /// "Joe"
# def __w(object, comment = nil)
# comment &&= "#{comment} = "
# inspection = PP.pp(object, StringIO.new, 100).string rescue object.inspect
# Rails.logger.debug("/// #{comment}#{inspection}")
# end
#
# # __d(customer.name, binding) => /// customer.name = "Joe"
# # __d(@customer.name) => /// @customer.name = "Joe"
# def __d(expression, binding = nil)
# value = eval(expression.to_s, binding)
# __w(value, expression.to_s)
# end
#
def __p(*messages)
puts "/// #{messages.pluck(:inspect).join(', ')}"
end
def __pl(label, data)
puts "/// #{label} = #{data.inspect}"
end
# def __pl(*args)
# location = Gore.reformat_caller(caller.first)
# puts "/// #{location} -- #{args.inspect}"
# end
#
# def __l(*args)
# text = args.length == 1 && String === args.first ? args.first : args.map(&:inspect).join(", ")
# Log.trace "/// #{text}"
# end
#
# def __ll(*args)
# location = Gore.reformat_caller(caller.first)
# Log.trace "/// #{location} -- #{args.map(&:inspect).join(", ")}"
# end
def __t(*args)
source = caller.first
source.sub!(Padrino.root, "")
source.sub!(%r{`block \(\d+ levels\) in <top \(required\)>'}, "block")
puts " \e[31mTRACE\e[0m - #{source} - #{args.pluck(:inspect).join(', ')}"
end
<file_sep>/test/test.rake
require 'rake/testtask'
namespace :test do
%w(lib rabotnegi/unit rabotnegi/functional).each do |folder|
Rake::TestTask.new("#{folder.gsub('/', ':')}") do |test|
test.libs << "test"
test.pattern = "test/#{folder}/**/*_test.rb"
test.verbose = true
end
end
Rake::TestTask.new("all") do |test|
test.libs << "test"
test.test_files = FileList[
'test/rabotnegi/unit/**/*_test.rb',
'test/rabotnegi/functional/**/*_test.rb',
'test/lib/**/*_test.rb',
]
test.verbose = true
end
Rake::TestTask.new("ui") do |t|
t.libs << "test"
t.pattern = 'test/rabotnegi/ui/**/*_test.rb'
t.verbose = true
end
task "unit" => "test:rabotnegi:unit"
task "func" => "test:rabotnegi:functional"
end
task "test" => "test:all"
<file_sep>/app/models/user.rb
class User < Gore::ApplicationModel
field :industry
field :city
field :agent
field :ip
field :queries, type: Array
field :favorite_vacancies, type: Array, default: []
def favorite_vacancy_objects
Vacancy.find(favorite_vacancies)
end
def to_s
"User@#{ip}"
end
end
<file_sep>/test/rabotnegi/unit/salary_test.rb
require 'test_helper'
unit_test Salary do
setup do
@between_1000_2000 = Salary.make(:min => 1000, :max => 2000)
@above_1000 = Salary.make(:min => 1000)
@below_1000 = Salary.make(:max => 1000)
@exactly_1000 = Salary.make(:exact => 1000)
end
test "create with one attribute" do
actual = Salary.make(:exact => 1000)
expected = Salary.make; expected.exact = 1000
assert_equal expected, actual
end
test "create with many attributes" do
actual = Salary.make(:min => 1000, :negotiable => false, :currency => :usd)
expected = Salary.make; expected.min = 1000; expected.currency = :usd; expected.negotiable = false
assert_equal expected, actual
end
test "parse exact value" do
assert_equal @exactly_1000, Salary.parse('1000')
end
test "parse max value" do
assert_equal @below_1000, Salary.parse('<1000')
assert_equal @below_1000, Salary.parse('до 1000')
end
test "parse min value" do
assert_equal @above_1000, Salary.parse('от 1000')
assert_equal @above_1000, Salary.parse('1000+')
end
test "parse range" do
assert_equal @between_1000_2000, Salary.parse('1000-2000')
end
test "parse with bad input" do
assert_equal Salary.new, Salary.parse('тыщща')
end
test "to_s" do
assert_equal '1000—2000 р.', @between_1000_2000.to_s
end
test "==" do
assert_equal Salary.make(:exact => 1000, :currency => :usd), Salary.make(:exact => 1000, :currency => :usd)
end
test "convert_currency" do
salary = Salary.make(:exact => 1000, :currency => :usd)
salary.convert_currency(:rub)
assert_equal 31_000, salary.exact
assert_equal :rub, salary.currency
end
test "text=" do
salary = Salary.make(exact: 1000)
salary.text = "от 5000"
assert_equal Salary.make(min: 5000), salary
end
end
<file_sep>/test/lib/event_log_test.rb
require "test_helper"
describe Gore::EventLog do
setup do
Gore::EventLog::Item.delete_all
end
test "write string" do
Gore::EventLog.write("Source1", "event1", :warn, "message1")
assert Gore::EventLog::Item.where(source: "Source1", event: "event1", data: "message1", severity: "warn").exists?
end
test "write array" do
Gore::EventLog.write("Source", "test", :warn, [:an, "array"])
assert Gore::EventLog::Item.where(source: "Source", event: "test", data: [:an, "array"], severity: "warn").exists?
assert Gore::EventLog::Item.where(source: "Source", event: "test", data: ["an", "array"], severity: "warn").exists?
end
test "write hash" do
Gore::EventLog.write("Source", "test", :warn, a: "hash", number: 1, symbol: :hello)
assert Gore::EventLog::Item.where(source: "Source", event: "test", data: {a: "hash", number: 1, symbol: :hello}, severity: "warn").exists?
assert Gore::EventLog::Item.where(source: "Source", event: "test", data: {"a" => "hash", "number" => 1, "symbol" => "hello"}, severity: "warn").exists?
end
test "shorthand write methods" do
assert_respond_to Gore::EventLog, :debug
assert_respond_to Gore::EventLog, :info
assert_respond_to Gore::EventLog, :warn
assert_respond_to Gore::EventLog, :error
Gore::EventLog.error("Source2", "event2", "message2")
assert Gore::EventLog::Item.where(source: "Source2", event: "event2", data: "message2", severity: "error").exists?
end
test "write with extra data" do
Gore::EventLog.write("S", "e", :warn, {d1: 11, d2: 22}, {e1: 11, e2: 22})
assert Gore::EventLog::Item.where(source: "S", event: "e", data: {d1: 11, d2: 22}, extra: {e1: 11, e2: 22}, severity: "warn").exists?
end
test "nil data and nil extra are not stored" do
item = Gore::EventLog.write("Src", "evnt", :info)
item.reload
assert_equal nil, item.data
assert_equal nil, item.extra
refute item.attributes.include?("data")
refute item.attributes.include?("extra")
end
test ":info severity is not stored" do
item = Gore::EventLog.write("Src", "evnt", :info)
item.reload
assert_equal :info, item.severity
refute item.attributes.include?("severity")
end
test "events with low severity are not logged" do
begin
old_log_level = Log.level
Log.level = 2 # warn
Gore::EventLog.write("Src", "debug-message", :debug)
Gore::EventLog.write("Src", "info-message", :info)
Gore::EventLog.write("Src", "warn-message", :warn)
Gore::EventLog.write("Src", "error-message", :error)
assert Gore::EventLog::Item.where(source: "Src", event: "warn-message").exists?
assert Gore::EventLog::Item.where(source: "Src", event: "error-message").exists?
refute Gore::EventLog::Item.where(source: "Src", event: "debug-message").exists?
refute Gore::EventLog::Item.where(source: "Src", event: "info-message").exists?
ensure
Log.level = old_log_level.to_i
end
end
end
describe Gore::EventLog::Item do
test "time" do
item = Gore::EventLog::Item.create!(source: "Src", event: "evnt")
assert_equal item.time, item.created_at
end
test "updated_at is not stored" do
item = Gore::EventLog::Item.create!(source: "Src", event: "evnt")
item.reload
refute_nil item.created_at
assert_nil item.updated_at
refute item.attributes.include?("updated_at")
end
end
describe Gore::EventLog::Accessor do
setup do
Gore::EventLog::Item.delete_all
end
test "log attributes" do
assert_respond_to Vacancy, :log
assert_respond_to Vacancy.new, :log
assert_instance_of Gore::EventLog::Writer, Vacancy.log
assert_instance_of Gore::EventLog::Writer, Vacancy.new.log
assert_equal "vacancy", Vacancy.log.source
assert_equal "vacancy", Vacancy.new.log.source
assert_equal "user", User.log.source
assert_equal "user", User.new.log.source
assert_equal "rabotaru_job", Rabotaru::Job.log.source
end
test "log attributes methods" do
Vacancy.log.write("some_vacancy_event", :warn, "class message")
assert Gore::EventLog::Item.where(source: "vacancy", event: "some_vacancy_event", data: "class message", severity: "warn").exists?
Vacancy.new.log.warn("some_vacancy_event", "instance message")
assert Gore::EventLog::Item.where(source: "vacancy", event: "some_vacancy_event", data: "instance message", severity: "warn").exists?
end
end
describe Gore::EventLog::Writer do
setup do
Gore::EventLog::Item.delete_all
end
test "for_class" do
assert_equal "user", Gore::EventLog::Writer.for_class(User).source
assert_equal "rabotaru_job", Gore::EventLog::Writer.for_class(Rabotaru::Job).source
end
test "write" do
log = Gore::EventLog::Writer.new("TestSource")
log.write("event0", :warn, "details0")
assert Gore::EventLog::Item.where(source: "TestSource", event: "event0", data: "details0").exists?
log.warn("event1", "details1")
assert Gore::EventLog::Item.where(source: "TestSource", event: "event1", data: "details1", severity: "warn").exists?
end
end
<file_sep>/test/rabotnegi/unit/init_test.rb
require 'test_helper'
unit_test "Domain initialization" do
test "industry data loading" do
assert Industry.all.size > 10
assert Industry.popular.size > 5
assert Industry.other.size > 5
end
test "city data loading" do
assert_equal 5, City.all.size
end
end<file_sep>/app/models/industry.rb
class Industry < Struct.new(:code, :external_id, :name, :group)
cattr_reader :all, :popular, :other
alias key code
def to_s
name
end
def self.[](code)
if Array === code
code = code.map(&:to_sym)
all.select { |x| x.code.in?(code) }
else
all.detect { |x| x.code == code.to_sym }
end
end
singleton_class.send(:alias_method, :get, :[])
def self.each(&block)
@@all.each(&block)
end
def self.find_by_external_id(external_id)
external_id = external_id.to_i
industry = @@all.find { |industry| industry.external_id == external_id } || raise(ArgumentError, "Отрасль ##{external_id} не найдена")
industry.code
end
def self.find_by_external_ids(*external_ids)
external_ids.each do |eid|
return find_by_external_id(eid) rescue next
end
end
def self.key_matches?(key)
key = key.to_s
key.blank? || all.any? { |obj| obj.key_str == key }
end
def key_str
@key_str ||= key.to_s
end
def log_key
key
end
@@all = [
Industry.new(:it, 19, 'Информационные технологии', :popular),
Industry.new(:finance, 2, 'Бухгалтерия и финансы', :popular),
Industry.new(:transportation, 83, 'Транспорт', :popular),
Industry.new(:logistics, 78, 'Логистика', :popular),
Industry.new(:service, 92, 'Обслуживающий персонал', :popular),
Industry.new(:wholesale, 75, 'Оптовая торговля', :popular),
Industry.new(:manufactoring, 22, 'Производство', :popular),
Industry.new(:restaurant, 85, 'Рестораны и питание', :popular),
Industry.new(:retail, 60, 'Розничная торговля', :popular),
Industry.new(:office, 14, 'Делопроизводство', :popular),
Industry.new(:building, 37, 'Строительство и архитектура', :popular),
Industry.new(:hr, 12, 'Кадровые службы', :other),
Industry.new(:marketing, 49, 'Маркетинг, реклама, PR', :other),
Industry.new(:medicine, 90, 'Медицина, фармация', :other),
Industry.new(:realty, 107, 'Недвижимость', :other),
Industry.new(:sales, 1011, 'Продажа услуг', :other),
Industry.new(:publishing, 55, 'Издательство, полиграфия', :other),
Industry.new(:insurance, 109, 'Страхование', :other),
Industry.new(:telecom, 94, 'Телекоммуникации', :other),
Industry.new(:executives, 751, 'Топ-менеджмент', :other),
Industry.new(:hospitality, 111, 'Туризм, гостиничное дело', :other),
Industry.new(:telework, 1006, 'Удаленная работа', :other),
Industry.new(:householding, 46, 'Эксплуатация зданий', :other),
Industry.new(:law, 9, 'Юриспруденция', :other)
].sort_by(&:name)
@@popular, @@other = @@all.partition { |industry| industry.group == :popular }
def self.q
query = Object.new
class << query
def method_missing(selector, *args)
Industry[selector.to_sym]
end
end
query
end
end
<file_sep>/script/test_console.rb
__END__
sudo tail /var/log/syslog
sudo ln -sf /opt/ruby/bin/* /usr/bin
find /usr/bin -lname /opt/ruby/bin/\*
sudo sh -c 'mv /usr/bin/ruby /usr/bin/ruby_en && cp /usr/bin/ruby_ru /usr/bin/ruby'
sudo cat > /usr/bin/ruby_ru
#!/bin/sh
export RUBYOPT="-Ku"
exec "/usr/bin/ruby" "$@"
sudo /opt/nginx/sbin/nginx -s stop
sudo ruby-build 1.9.3-p125 /opt/ruby
cd /app/rabotnegi/current
bundle exec rake -T
q cd app
q cd shared
q cd log
q conf nginx
q conf bash
q log app
q log syslog
q log cron.out
q log cron.err
<file_sep>/lib/ext/mongoid.rb
module MongoidPagination
extend ActiveSupport::Concern
included do
def self.paginate(page_num, page_size = 10)
criteria = page(page_num, page_size)
results = criteria.to_a
results.extend(MongoidPagination::Collection)
results.criteria = criteria
results.total_count = criteria.count
results
end
scope :page, proc { |page_num, page_size = 10| limit(page_size).offset(page_size * ([page_num.to_i, 1].max - 1)) } do
include MongoidPagination::Collection
end
end
module Collection
def criteria
@criteria || self
end
def criteria=(object)
@criteria = object
end
def limit_value
criteria.options[:limit]
end
def offset_value
criteria.options[:skip]
end
def total_count
@total_count ||= criteria.count
end
def total_count=(value)
@total_count = value
end
def per(num)
if (n = num.to_i) <= 0
self
else
limit(n).offset(offset_value / limit_value * n)
end
end
# Total number of pages
def num_pages
(total_count.to_f / limit_value).ceil
end
alias total_pages num_pages
# Current page number
def current_page
(offset_value / limit_value) + 1
end
# First page of the collection ?
def first_page?
current_page == 1
end
# Last page of the collection?
def last_page?
current_page >= num_pages
end
# current_page - 1 or nil if there is no previous page
def previous_page
current_page > 1 ? (current_page - 1) : nil
end
# current_page + 1 or nil if there is no next page
def next_page
current_page < total_pages ? (current_page + 1) : nil
end
end
end
module Mongoid::Document
def store(attributes = {})
update_attributes!(attributes)
end
def mark(state, other_attributes = {})
self[self.class._state_attr] = state
self["#{state}_at"] = Time.now
update_attributes!(other_attributes)
end
def update_if_stored!(attributes = {})
self.attributes = attributes
save! unless new?
end
module ClassMethods
def get(id)
find(id)
end
def def_state_predicates(storage, *states)
super
states.each { |state| field "#{state}_at", type: Time }
end
def no_update_tracking
class_eval <<-ruby
def set_updated_at
end
ruby
end
end
include MongoidPagination
end
<file_sep>/test/lib/mongo_reflector_test.rb
require "test_helper"
describe Gore::MongoReflector do
test "real definitions" do
vacancy = Gore::MongoReflector.metadata_for('vacancies')
assert_equal 'vacancy', vacancy.singular
assert_equal 'vacancies', vacancy.plural
assert_equal 'vacancies', vacancy.key
assert_equal true, vacancy.searchable?
assert_equal Vacancy, vacancy.klass
# log_item = Gore::MongoReflector.metadata_for('log_items')
#
# assert_equal 'mongo_log_item', log_item.singular
# assert_equal 'mongo_log_items', log_item.plural
# assert_equal 'log_items', log_item.key
# assert_equal true, log_item.searchable?
# assert_equal MongoLog::Item, log_item.klass
end
end
describe Gore::MongoReflector::Builder do
dummy = temp_class Gore::ApplicationModel do
field :name
field :email
end
test "list" do
collection_1 = Gore::MongoReflector::Builder.new.desc(dummy) do
list :id, [:name, :link], [:email, trim: 20], [:url, :link, trim: 30]
end
fields_1 = collection_1.list_fields.index_by { |field| field.name.to_sym }
collection_2 = Gore::MongoReflector::Builder.new.desc(dummy) do
list id: _, name: :link, email: {trim: 20}, url: [:link, trim: 30]
end
fields_2 = collection_2.list_fields.index_by { |field| field.name.to_sym }
[fields_1, fields_2].each do |fields|
assert_equal 'id', fields[:id].name
assert_equal 'name', fields[:name].name
assert_equal :link, fields[:name].format
assert_equal 'email', fields[:email].name
assert_equal nil, fields[:email].format
assert_equal 20, fields[:email].trim
assert_equal 'url', fields[:url].name
assert_equal :link, fields[:url].format
assert_equal 30, fields[:url].trim
end
end
test "list options" do
collection = Gore::MongoReflector::Builder.new.desc(dummy) do
list_order :name
list_page_size 33
actions update: false
end
assert_equal :name, collection.list_order
assert_equal 33, collection.list_page_size
assert_equal false, collection.actions[:update]
assert_equal nil, collection.actions[:delete]
end
test "list_css_classes" do
collection = Gore::MongoReflector::Builder.new.desc(dummy) do
list_css_classes { |x| {joe: x.name == 'Joe'} }
end
assert_equal Hash[joe: true], collection.list_css_classes.(dummy.new(name: "Joe"))
assert_equal Hash[joe: false], collection.list_css_classes.(dummy.new(name: "Bob"))
end
test "view_subcollection" do
collection = Gore::MongoReflector::Builder.new.desc(dummy) do
view_subcollection :loadings, 'rabotaru_loadings'
end
assert_equal :loadings, collection.view_subcollections.first.accessor
assert_equal 'rabotaru_loadings', collection.view_subcollections.first.key
assert_equal Gore::MongoReflector.metadata_for('rabotaru_loadings'), collection.view_subcollections.first.collection
end
test "edit" do
collection = Gore::MongoReflector::Builder.new.desc(dummy) do
edit title: 'text', city_name: ['combo', City.all], created_at: 'date_time'
end
fields = collection.edit_fields.index_by { |field| field.name.to_sym }
assert_equal 'title', fields[:title].name
assert_equal 'text', fields[:title].format
assert_equal 'combo', fields[:city_name].format
assert_equal [City.all], fields[:city_name].args
assert_equal 'date_time', fields[:created_at].format
end
end
<file_sep>/Rakefile
require 'bundler/setup'
require 'padrino-core/cli/rake'
require 'thor'
require File.dirname(__FILE__) + '/config/boot.rb'
PadrinoTasks.use(:mongoid)
PadrinoTasks.init
require 'resque/tasks'
require 'rake/sprocketstask'
namespace :data do
# prod: rake data:dump DB=rabotnegi_prod DIR=/data/backup BUCKET=rabotnegi_backups
# dev: rake data:dump DB=rabotnegi_dev DIR=tmp BUCKET=rabotnegi_backups
# scp rba:/data/backup/rabotnegi_prod-latest.tbz ~/desktop
task :dump do
db, dir, bucket = ENV.values_at('DB', 'DIR', 'BUCKET')
id = Time.now.strftime("%Y%m%d_%H%M%S")
name = "#{db}-#{id}"
sh "mongodump -d #{db} -o tmp/#{name}"
sh "tar -C tmp -cj #{name} > #{dir}/#{name}.tbz"
sh "rm -rf tmp/#{name} #{dir}/#{db}-latest.tbz"
sh "ln -s #{name}.tbz #{dir}/#{db}-latest.tbz"
if bucket.present?
if `which gsutil`.present?
sh "gsutil cp #{dir}/#{name}.tbz gs://#{bucket}"
else
raise "Boto is not there" unless File.exist?("/data/etc/boto.conf")
raise "GSUtil is not there" unless File.exist?("/data/gsutil/gsutil")
sh "env BOTO_CONFIG=/data/etc/boto.conf /data/gsutil/gsutil cp #{dir}/#{name}.tbz gs://#{bucket}"
end
end
end
# eg. rake data:upload FILE=/u/backup/dump-20120101-120000.tbz BUCKET=/rabotnegi-backup
task :upload do
file, bucket = ENV.values_at['FILE', 'BUCKET']
sh "BOTO_CONFIG=/data/etc/boto.conf /data/gsutil/gsutil cp #{file} gs://#{bucket}"
end
task :clone do
source, target = ENV.values_at('SRC', 'DST')
sh "rm -rf tmp/#{source}"
sh "mongodump -d #{source} -o tmp"
sh "mongorestore -d #{target} --drop tmp/#{source}"
sh "rm -rf tmp/#{source}"
end
end
namespace :dev do
task :restore do
src = ENV['SRC'] || "tmp/db.rabotnegi.dev"
sh "mongorestore -d rabotnegi_dev --drop #{src}"
end
task :rm do
targets = %w(/public/rabotnegi/assets/* /tmp/cache/*).map { |f| Gore.root.join(f) }
system "rm -rf #{targets.join(' ')}"
end
end
task "cron:ping" => :environment do
Padrino.logger.info "Cron ping: event.count=#{Gore::EventLog::Item.count}"
Gore.enqueue Gore::Debug, :say, "Resque ping (scheduled at #{Time.now})"
end
task "resque:setup" => :environment do
ENV['QUEUE'] = '*'
end
Rake::SprocketsTask.new do |t|
t.environment = Rabotnegi.assets
t.output = "./public/rabotnegi/assets"
t.assets = %w( vendor.js application.js application.css admin.js admin.css ) + Dir.glob(Padrino.root("app/assets/images/*")).map { |path| path.gsub("#{Padrino.root}/app/assets/images/", '') }
end
task "assets:precompile" => "assets" do
`cp app/assets/images/* public/rabotnegi/assets`
end
<file_sep>/app/models/vacancy_cleaner.rb
module VacancyCleaner
extend self
include Gore::EventLog::Accessor
UNESCAPES = {""" => '"', "«" => '«', "»" => '»', "–" => '–', "—" => '—', "'" => "'"}
TOTAL_SANITIZER_OPTIONS = {}
SANITIZER_OPTIONS = {
elements: %w(div strong em b i ul ol li p h3 h4 br hr h5),
attributes: { all: %w(id class style) }
}
def clean_all(loaded_after = nil)
collection = loaded_after ? Vacancy.where(:loaded_at.gte => loaded_after) : Vacancy.all
collection = collection.where(cleaned_at: nil)
log.info __method__, count: collection.count, threshold: loaded_after
collection.each { |vacancy| VacancyCleaner.clean(vacancy) }
end
def clean(vacancy)
original_data = {title: vacancy.title, employer_name: vacancy.employer_name, description: vacancy.description}
store_original_data(vacancy, original_data)
vacancy.title = clean_title(vacancy.title)
vacancy.employer_name = clean_employer_name(vacancy.employer_name)
vacancy.description = clean_description(vacancy.description)
vacancy.cleaned_at = Time.now
vacancy.save!
rescue => e
Gore::Err.register("VacancyCleaner.clean", e, params: {vacancy_id: vacancy.id})
end
def clean_title(title)
result = (title || "").dup.mb_chars
result.gsub!(/&[#\w]+;/) { |match| UNESCAPES[match] || match }
result = result.downcase if result.upcase == result
result[0] = result[0].upcase if result.first.downcase == result.first
result = Sanitize.clean(result, TOTAL_SANITIZER_OPTIONS)
result.to_s
end
def clean_employer_name(employer_name)
result = (employer_name || "").dup.mb_chars
result.gsub!(/&[#\w]+;/) { |match| UNESCAPES[match] || match }
result = Sanitize.clean(result, TOTAL_SANITIZER_OPTIONS)
result.to_s
end
def clean_description(description)
desc = (description || "").dup.mb_chars
desc.gsub! /\n/, '<br />' if desc !~ /<\w+/
desc.squish!
desc.gsub! / /, ' '
desc.gsub! /‚/, ','
desc.gsub! /"/, '"'
desc.gsub! %r{(\w+>)\s+(</?\w)}, '\1 \2' # tag> </?tag => tag> </tag
desc.gsub! %r{(<br />\s*)+}, '<br>' # <br /> <br /> => <br>
desc.gsub! %r{(<strong>)+}, '<strong>'
desc.gsub! %r{(</strong>)+}, '</strong>'
desc.gsub! %r{<strong>(Требования|Условия|Обязанности):?</strong>}, '<h4>\1</h4>'
desc.gsub! %r{</h4>:}, '</h4>'
desc.gsub! %r{<strong><br></strong>}, ''
desc.gsub! %r{<strong>}, ''
desc.gsub! %r{</strong>}, ''
desc.gsub! %r{(</(h4|ul)+>)<br>}, '\1'
desc.gsub! %r{([^<>]*)<br>}, '<p>\1</p>'
desc.gsub! %r{<br>(<(h4|ul)+)}, '\1'
desc.gsub! %r{•(.*?)(?=•|<|\Z)}, '<p>• \1</p>'
desc.gsub! %r{<p>\s*(-|\*|·)\s*}, '<p>• '
desc.gsub! %r{</ul>\s*<ul>}, ''
desc.gsub! %r{<li>\s*-\s*}, '<li>'
desc.gsub! %r{<li>\s*</li>}, ''
desc.gsub! %r{<ul>\s*</ul>}, ''
desc.gsub! %r{<ul><ul>}, '<ul>'
desc.gsub! %r{</ul></ul>}, '</ul>'
desc.gsub! %r{<p>[\s-]*</p>}, ''
desc.squish!
desc = Sanitize.clean(desc, SANITIZER_OPTIONS)
desc.to_s
end
private
def store_original_data(vacancy, data)
working_dir = Rabotnegi.config.original_vacancies_data_dir.join(vacancy.created_at.strftime("%Y%m"))
working_dir.mkpath
File.write(working_dir.join("#{vacancy.id}.json"), JSON.generate(data))
end
end
<file_sep>/app/models/resume.rb
class Resume < Gore::ApplicationModel
field :id, type: Integer
field :fname
field :lname
field :password
field :city
field :job_title
field :industry
field :min_salary, type: Integer
field :view_count, type: Integer, default: 0
field :job_reqs
field :about_me
field :contact_info
validates_presence_of :fname, :lname, :city, :job_title, :industry, :contact_info
validates_numericality_of :min_salary
def name
"#{fname} #{lname}".squish
end
def to_s
"#{name} — #{job_title} (от #{min_salary} р.)"
end
def self.search(params)
params = params.symbolize_keys
params.assert_valid_keys(:city, :industry, :salary, :keywords)
query = Regexp.new(params[:keywords] || "")
scope = self
scope = scope.where(city: params[:city]) if params[:city].present?
scope = scope.where(industry: params[:industry]) if params[:industry].present?
scope = scope.where(job_title: query) if params[:keywords].present?
if params[:salary].present?
direction, value = params[:salary].match(/(-?)(\d+)/).captures
op = direction == '-' ? :lte : :gte
scope = scope.where(:min_salary.send(op) => value)
end
scope
end
instance_eval { alias query search }
def self.authenticate(name, password)
name =~ /(\w+)\s+(\w+)/ || raise(ArgumentError, "Имя имеет неправильный формат")
first, last = $1, $2
resume = where(lname: last, fname: first).first || raise(ArgumentError, "Резюме «#{name}» не найдено")
resume.password == password || raise(ArgumentError, "Неправильный пароль")
resume
end
end
<file_sep>/lib/gore/sort_expressions.rb
module Gore::SortExpressions
module_function
# generates a sort parameter like "date" or "-date"
# reverses (adds a "-") when the pararmeter is already used for sorting
def encode_order(field, param, reverse_by_default = false)
param.blank??
reverse_by_default ? "-#{field}" : field.to_s :
param == field.to_s ?
"-#{field}" :
field.to_s
end
# "date" => [:date, false]
# "-date" => [:date, true]
def decode_order_to_array(param)
param.present??
param.starts_with?('-') ?
[param.from(1), true] :
[param, false] :
[nil, false]
end
# "date" => "date asc"
# "-date" => "date desc"
def decode_order_to_expr(param)
field, reverse = decode_order_to_array(param)
modifier = reverse ? :desc : :asc
field.nil? ? nil : "#{field} #{modifier}"
end
# "date" => ["date", Mongo::ASCENDING]
# "-date" => ["date", Mongo::DESCENDING]
def decode_order_to_mongo(param)
field, reverse = decode_order_to_array(param)
[[field, reverse ? Mongo::DESCENDING : Mongo::ASCENDING]]
end
end
<file_sep>/app/models/tasks.rb
module Tasks
extend self
include Gore::EventLog::Accessor
def kill_spam
bad_emails = %w(gmail.com anyerp.com).join('|')
bad_ips = %w(172.16.58.3 192.168.3.11)
filter = [ { employer_name: Regexp.new( "@(#{bad_emails})$" ) }, { poster_ip: bad_ips } ]
vacancies = Vacancy.any_of(filter)
vacancies.delete_all
# Counter.inc "antispam.runs"
# Counter.inc "antispam.removed_vacancies", vacancies.count
log.info __method__, removed: vacancies.count
end
end
<file_sep>/lib/gore/view_helpers.rb
# depends on: element
# some functions depend on: localize, link_to, url, current_url, truncate, number_with_precision
module Gore::ViewHelpers
module Common
# Works like content_tag. But:
# * :klass option can be used as :class
# * last argument is treated like a :class
def element(name, *args, &block)
options = args.extract_options!
css_class = options.delete(:klass) if options.include?(:klass)
css_class = args.pop if args.last.is_a?(String) && (args.length == 2 || args.length == 1 && block)
options[:class] = css_class if css_class.present?
content_tag(name, args.first, options, &block)
end
%w(div p b).each do |tag|
class_eval <<-ruby
def #{tag}(*args, &block)
element(:#{tag}, *args, &block)
end
ruby
end
def br
tag(:br)
end
# Fast cycling helper
def xcycle(*values)
@xcycle_counter ||= -1
@xcycle_counter += 1
values[@xcycle_counter.modulo(values.length)]
end
def centering_table(&proc)
"<table class='centered'><tr><td>#{capture(&proc)}</table>".html_safe
end
def lorem
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
end
def output(block, result)
block_is_template?(block) ? concat_content(result) : result
end
end
module Inspection
def hash_as_lines(hash)
hash.map { |key, val| "#{key}: #{val}" }.join("\n")
end
def hash_as_dl(hash)
return element(:p, "—") if hash.blank?
element :dl do
hash.map { |key, val| element(:dt, key) + element(:dd, val) }.join.html_safe
end
end
def hash_view(hash)
return "" if hash.blank?
element :table, "hash" do
hash.map do |key, value|
element(:tr) do
title = key.to_s.titleize.gsub(' ', '-')
element(:th, title) + element(:td, Gore.inspect_value(value))
end
end.join.html_safe
end
end
def hash_of_lines(hash)
hash = hash.dup
hash.each_key do |k|
hash[k] = Gore.inspect_value(hash[k])
end
hash_view(hash)
end
def array_view(array)
element :ul, "array" do
array.map do |item|
element(:li, item.to_s)
end.join.html_safe
end
end
def array_inline(array)
Gore.inspect_array(array)
end
def inline_multi_view(obj)
case obj
when Array then array_inline(obj)
when Hash then Gore.inspect_hash(obj)
when String then obj
end
end
def multi_view(obj)
case obj
when Array then array_view(obj)
when Hash then hash_view(obj)
when String then obj
end
end
# options: compact, trim
def inspect_value(value, options = {})
return "" if value.blank?
case value
when Time then options[:compact] ? l(value.localtime, format: :short) : l(value.localtime)
when Integer then number(value)
when BSON::ObjectId then options[:compact] ? short_object_id(value) : value
when Symbol then value.to_s.humanize
when String then trim(value, options[:trim])
else trim(value, options[:trim])
end
end
end
module Admin
# <input type="search" id="q"> <input type="submit" value="Поиск">
def search_tag
text_field = text_field_tag(:q, value: params[:q], type: "search", id: 'q', :class => "search", autofocus: true)
text_field + " " + submit_tag("Поиск")
end
# Render either a list of items with pager, either "no data" message.
def listing(collection, &block)
html = if collection.any?
element(:table, "listing", &block).to_s + pagination(collection).to_s
else
element :div, "Ничего не найдено.", "no-data-message"
end
html
end
def required_mark(options = {})
content_tag :span, '(обязательное поле)', {:class => 'required-mark'}.update(options)
end
def edit_icon
image_tag 'edit.gif', :title => 'Редактировать', :alt => 'Редактировать'
end
def delete_icon
image_tag 'delete.gif', :title => 'Удалить', :alt => 'Удалить'
end
Colors = %w(000 666 8f4bcf 519618 8f0d0d 387aad ab882e 8f88cf 4a7558 3aa c400b7 00f e10c02 800000 808000 008000 000080 800080 F0F 408099 FF8000 008080)
def color_code(item)
@color_codes ||= {}
@color_codes[item] ||= Colors[@color_codes.size.remainder(Colors.length)]
color = @color_codes[item]
element :span, item, :class => "color", style: "background-color: ##{color}"
end
end
module Formatting
def trim(value, length = nil)
length ? truncate(value.to_s, length: length, separator: ' ') : value.to_s
end
def stringify(obj)
obj.to_s
end
def time(seconds)
min = seconds.to_i / 60
sec = seconds.to_i - min * 60
"%02i:%02i" % [min, sec]
end
# 05:200
# 02:30:200
def sec_usec(seconds)
"%.3f" % [seconds] if seconds
end
def datetime(time)
time.localtime.strftime("%d.%m.%Y %H:%M:%S %Z")
end
def datetime_full(time)
time.localtime.strftime("%d.%m.%Y %H:%M")
end
def date_full(time)
time.localtime.strftime("%d.%m.%Y")
end
def number(value)
number_with_delimiter(value)
end
def limited_number(value, threshold)
value < threshold ? value : element(:span, value, :class => "extreme-number")
end
def short_object_id(value)
"#{value.to_s.first(8)}-#{value.to_s.last(4)}"
end
end
module Editing
def submit_section(label)
element :div, 'submit' do
tag(:input, type: 'submit', value: label, :class => 'action-button') +
element(:span, (" или " + element(:a, 'Отменить', 'ui', href: request.referer)), 'cancel')
end
end
def errors_for(object, options = {})
return '' if object.errors.empty?
header_message = options.delete(:header_message) || translate("errors.system.header")
error_messages = object.errors.map do |attr, message|
translate("errors.#{object.class.model_name.plural}.#{attr}", :default => message)
end
partial "shared/errors", locals: {header: header_message, errors: error_messages}
end
def trb(label, content = nil, options = {}, &block)
if block_given?
options = content || {}
content = capture(&block)
end
options.assert_valid_keys(:required, :id, :before, :after, :comment, :class)
label = [label]
content = [content]
row_id = options[:rid]
row_id = row_id.join('_') if row_id.is_a?(Array)
row_options = {}
row_options[:id] = "#{row_id}_row" if row_id
row_options[:class] = options[:class].present?? [options[:class]] : []
row_options[:class] << "required" if options[:required]
row_options[:class] << "high" if options[:high]
row_options[:class] = row_options[:class].any?? row_options[:class].join(' ') : nil
content.unshift options[:before] if options[:before]
content.push content_tag(:span, '(обязательное поле)', :class => 'required-mark') if options[:required]
content.push options[:after] if options[:after]
content.push tag(:br) + content_tag(:small, options[:comment]) if options[:comment]
element :tr, row_options do
element(:th, label.join(' ').html_safe) +
element(:td, content.join(' ').html_safe) +
element(:td, "", :class => "other")
end
end
def trs(content, row_options = {})
content_tag :tr, row_options do
content_tag :td, content.html_safe, :colspan => 2
end
end
def tr1(first, options = {})
trb(first, nil, options)
end
def tr2(last, options = {})
trb(nil, last, options)
end
def tr(name, title, content, options = {})
label = label_tag(name, title + ':')
trb(label, content, options)
end
def wrapper(&block)
output block, element(:table, "form-layout", &block)
end
end
module Layout
# sets the page title, id, class
def page(id, title = nil, options = {})
@page_id = id
@page_title = title
@page_class = options[:class] || options[:klass]
@page_class = nil if @page_class.blank?
if options[:path]
options.merge! :tab => options[:path].first, :navbar => options[:path].second, :navlink => options[:path].third
end
@current_tab = "#{options[:tab]}-tab" if options[:tab]
@current_navbar = "#{options[:navbar]}-nav-bar" if options[:navbar]
@current_navlink = "#{options[:navlink]}-link" if options[:navlink]
if @current_navbar == "casual-employers-nav-bar" && session[:employer_id]
@current_navbar = "pro-employers-nav-bar"
end
end
def meta(name, content)
@meta_properties ||= {}
@meta_properties[name] = content
end
# (nil) => "Работнеги.ру"
# ("Вакансии") => "Вакансии - Работнеги.ру"
# ("Строители", "Вакансии") => "Строители - Вакансии - Работнеги.ру"
# ("Строители", " ", "Вакансии") => "Строители - Вакансии - Работнеги.ру"
def document_title
[@page_title, "Работнеги.ру"].flatten.reject(&:blank?).join(' - ')
end
end
module Collections
def found_objects_info(collection, word, e1, e2, e5)
object = Gore::RussianInflector.inflect(collection.total_pages <= 1 ? collection.size : collection.total_count, word, e1, e2, e5)
"Найдено #{b collection.total_count} #{object}.
Показаны #{b(collection.offset_value + 1)} — #{b(collection.offset_value + collection.limit_value)}".html_safe
end
def sorting_state_class_for(field)
current_field, _ = Gore::SortExpressions.decode_order_to_array(params[:sort])
field.to_s == current_field ? "sorted" : ""
end
def pagination(collection, options = {})
return "" unless collection.respond_to?(:total_pages) && collection.total_pages > 1
element :div, "pager" do
pagination_links(collection, options)
end
end
def pagination_links(collection, options = {})
links_model = pagination_links_model(collection)
links = links_model.map do |key|
case
when key == collection.current_page
element :em, key
when key.is_a?(Numeric)
link_to key, current_url(page: key), :class => "num"
when key == :gap
element :span, '…', "gap"
end
end.join(' ')
if collection.first_page?
links.insert 0, element(:span, "← предыдущая станица", "stub")
else
links.insert 0, element(:span, "←", "dir") + link_to("предыдущая станица", current_url(page: collection.previous_page))
end
if collection.last_page?
links << element(:span, "следующая страница →", "stub")
else
links << link_to("следующая страница", current_url(page: collection.next_page))
links << element(:span, "→", "dir")
end
element :div, links, "pagination"
end
def pagination_links_model(collection)
links = []
total_pages = collection.total_pages
current_page = collection.current_page
inner_window = 2
outer_window = 0
window_from = current_page - inner_window
window_to = current_page + inner_window
if window_to > total_pages
window_from -= window_to - total_pages
window_to = total_pages
end
if window_from < 1
window_to += 1 - window_from
window_from = 1
window_to = total_pages if window_to > total_pages
end
middle = window_from..window_to
# left window
if outer_window + 3 < middle.first # there's a gap
left = (1..(outer_window + 1)).to_a
left << :gap
else # runs into visible pages
left = 1...middle.first
end
# right window
if total_pages - outer_window - 2 > middle.last # again, gap
right = ((total_pages - outer_window)..total_pages).to_a
right.unshift :gap
else # runs into visible pages
right = (middle.last + 1)..total_pages
end
links = left.to_a + middle.to_a + right.to_a
end
end
class FormBuilder < Padrino::Helpers::FormBuilder::StandardFormBuilder
def text_block(attr, caption, options = {})
control_block_for(:text_field, attr, caption, options)
end
def text_area_block(attr, caption, options = {})
control_block_for(:text_area, attr, caption, options)
end
def select_block(attr, caption, options = {})
control_block_for(:select, attr, caption, options)
end
def submit_block(caption)
template.tr2 template.submit_section(caption)
end
def captcha_block
if template.captcha_valid?
template.tr2 template.captcha_section
else
label = template.label_tag("Защитный код", for: "captcha_text")
template.trb label, template.captcha_section, comment: "Введите 4 латинские буквы которые паказаны на картинке.", :class => "captcha"
end
end
private
def control_block_for(control_name, attr, caption, options)
block_options = options.extract!(:required, :before, :after, :comment)
label = label(attr, caption: caption + ':')
control = send(control_name, attr, options)
template.trb(label, control, block_options)
end
end
end
<file_sep>/test/rabotnegi/ui/vacancies_test.rb
require 'test_helper'
ui_test "Vacancies" do
describe "search" do
test "link to search page" do
visit "/"
click_link "Поиск вакансий"
assert_equal "/vacancies", current_path
end
test "search page" do
visit "/vacancies"
in_content do
assert_has_select "Город"
assert_has_select "Отрасль"
assert_has_field "Ключевые слова"
end
end
test "search by city/industry" do
visit "/vacancies"
pick 'Город', 'Санкт-Петербург'
pick 'Отрасль', 'Информационные технологии'
click_button "Найти"
in_content do
assert_has_contents "Designer", "Ruby Developer", "Apple"
assert_has_no_contents "Главбух", "Рога и Копыта" # other industry/city
assert_has_no_contents "Msk Co" # other city
end
end
test "search with query" do
visit "/vacancies"
pick 'Город', 'Санкт-Петербург'
pick 'Отрасль', 'Информационные технологии'
fill 'Ключевые слова', 'Java'
click_button "Найти"
in_content do
assert_has_contents "JavaScript Developer"
assert_has_no_contents "Ruby Developer"
end
end
test "search without results" do
visit "/vacancies"
pick 'Город', 'Екатеринбург'
pick 'Отрасль', 'Информационные технологии'
click_button "Найти"
in_content do
assert_has_content "Информации о вакансиях в выбранном городе/отрасли сейчас нет"
end
end
end
describe "search results" do
test "view search result" do
vacancy = Vacancy.where(title: "JavaScript Developer", city: 'spb').first
vacancy_block = "#v-#{vacancy.id}-details .entry-box"
visit "/vacancies"
pick 'Город', 'Санкт-Петербург'
fill 'Ключевые слова', 'javascript'
click_button "Найти"
click_link "JavaScript Developer"
assert_has_selector vacancy_block, visible: true, text: "Do some JS and frontend stuff"
click_link "JavaScript Developer"
assert_has_selector vacancy_block, visible: false
within(vacancy_block) { visit_link("Открыть вакансию на отдельной странице") }
assert_has_selector 'h2', text: "JavaScript Developer"
assert_title_like "JavaScript Developer"
end
end
describe "posting" do
test "post" do
title = "Негr ##{Gore.time_stamp}"
visit "/vacancies/new"
fill "Должность", title
fill "Работодатель", "СтройНам"
pick "Город", "Москва"
pick "Отрасль", "Строительство и архитектура"
fill "Зарплата", "30000"
fill "Описание", "ла-ла-ла-ла надо нам е-щёёё бабла"
click_button "Опубликовать"
assert_has_content "Вакансия опубликована"
vacancy = Vacancy.asc(:created_at).last
vacancy.title.must_equal title
vacancy.city.must_equal "msk"
vacancy.industry.must_equal "building"
vacancy.employer_name.must_equal "СтройНам"
vacancy.description.must_equal "ла-ла-ла-ла надо нам е-щёёё бабла"
vacancy.salary.must_equal Salary.make(exact: 30_000)
assert_title_like title
assert_has_content title
assert_has_content "ла-ла-ла-ла надо нам е-щёёё бабла"
end
test "post invalid data" do
title = "Негr ##{Gore.time_stamp}"
visit "/vacancies/new"
click_button "Опубликовать"
assert_has_content "Вы что-то неправильно заполнили"
within(".errors") { assert_has_content "Должность" }
end
end
describe "favorites" do
test "favorites" do
record = Vacancy.where(title: "JavaScript Developer", city: 'spb').first
row = "#v-#{record.id}"
visit "/vacancies"
User.last.update_attributes(favorite_vacancies: [])
pick 'Город', 'Санкт-Петербург'
pick 'Отрасль', 'Информационные технологии'
click_button "Найти"
assert_equal [], User.last.favorite_vacancies
assert_has_no_class find(row + " .star"), "star-enabled"
find(row + " .star").click
skip "seems we can't click spans here"
assert_has_class find(row + " .star"), "star-enabled"
assert_equal [record.id], User.last.favorite_vacancies
visit "/vacancies/favorite"
in_content do
assert_has_selector "tr.entry-header", count: 1
assert_has_content "JavaScript Developer"
end
end
end
end
<file_sep>/lib/ext/core.rb
class Object
def _class
self.class
end
def is?(*types)
types.any? { |type| self.is_a?(type) }
end
# joe.send_chain 'name.last' #=> 'Smith'
def send_chain(expression)
expression = expression.to_s
return self if expression.blank?
return self.send(expression) unless expression.include?(".")
expression.split('.').inject(self) { |result, method| result.send(method) }
end
def assign_attributes(attributes)
attributes.each_pair { |k,v| send("#{k}=", v) if respond_to?("#{k}=") } if attributes
end
def assign_attributes!(attributes)
attributes.each_pair { |k,v| send("#{k}=", v) } if attributes
end
end
module Enumerable
# ary.select { |val| val.to_i == 3 }
# ary.select_eq(to_i: 3)
def select_eq(params = {})
params = params.to_a
select { |obj| params.all? { |k,v| obj.send(k) == v } }
end
def select_neq(params)
params = params.to_a
select { |obj| params.all? { |k,v| obj.send(k) != v } }
end
def select_in(params)
params = params.to_a
select { |obj| params.all? { |k,v| obj.send(k).in?(v) } }
end
def select_nin(params)
params = params.to_a
select { |obj| params.all? { |k,v| !obj.send(k).in?(v) } }
end
def detect_eq(params = {})
params = params.to_a
detect { |obj| params.all? { |k,v| obj.send(k) == v } }
end
def detect_neq(params)
params = params.to_a
detect { |obj| params.all? { |k,v| obj.send(k) != v } }
end
def send_each(method, *args, &block)
each { |obj| obj.send(method, *args, &block) }
end
def map_to_array(*attrs)
map { |obj| attrs.inject([]) { |array, attr| array << obj.send(attr) } }
end
def pluck(attr)
map { |obj| obj.send(attr) }
end
def pluck_all(attr)
map { |args| args.map(&attr) }
end
end
class Module
def def_struct_ctor
module_eval <<-RUBY
def intialize(attributes = {})
assign_attributes!(attributes)
super
end
RUBY
end
def def_state_predicates(storage, *states)
module_eval <<-RUBY
def self._state_attr
:#{storage}
end
def self._states
[ #{states.map { |state| ":#{state}" }.join(',')} ]
end
RUBY
states.each do |state|
module_eval <<-RUBY
def #{state}?
self.#{storage} == :#{state} || self.#{storage} == '#{state}'
end
RUBY
end
end
end
class Hash
def append_string(key, text)
self[key] ||= ""
self[key] = self[key].present?? self[key] + ' ' + text.to_s : text.to_s
end
def prepend_string(key, text)
self[key] ||= ""
self[key] = self[key].present?? text.to_s + ' ' + self[key] : text.to_s
end
end
# class Time
# def to_json(*args)
# as_json.to_json
# end
# end
#
# class BSON::ObjectId
# def to_json(*args)
# as_json.to_json
# end
# end
class File
def self.write(path, data = nil)
Log.trace "Writing file #{path} (#{data.try(:size)}bytes)"
open(path, 'w') { |file| file << data }
end
end
<file_sep>/script/test_vacancy_dups.rb
# clones = [].to_set
# Vacancy.all.each_with_index do |v1, i|
# next if v1.external_id.blank?
# next if clones.include?(v1)
#
# dups = Vacancy.where(external_id: v1.external_id, title: v1.title, employer_name: v1.employer_name, city: v1.city, industry: v1.industry, description: v1.description).excludes(id: v1.id).to_a
# next if dups.empty?
#
# dups.unshift(v1)
# dup_views = dups.map { |v| [v.id, v.created_at.to_s(:num), v.updated_at.to_s(:num)].join('-') }.join(' ')
# puts "#{v1.external_id}-#{dups.size}: #{dup_views} -- #{v1.title}"
#
# clones.merge(dups)
# end
# clones.each do |v|
# raise "Vacancy #{v.id}/#{v.external_id} is not a clone" unless Vacancy.where(external_id: v.external_id).excludes(id: v.id).present?
# end
#
# puts "Removing #{clones.size} clones"
# Vacancy.delete_all(conditions: {_id: clones})
uniqs = Vacancy.all.to_a.uniq_by { |v| v.external_id }
puts "Removing #{Vacancy.count - uniqs.count} clones"
Vacancy.not_in(_id: uniqs.map(&:id)).delete_all
<file_sep>/script/test_mongo_vs_sql.rb
# coding: utf-8
RECORD_COUNT = 1000
mysql = Mysql2::Client.new(host: "localhost", username: "root", database: "rabotnegi_dev")
query = "SELECT `vacancies`.* FROM `vacancies` LIMIT #{RECORD_COUNT}"
p_ar = -> do
results = Vacancy.limit(RECORD_COUNT).all[1]
end
p_select_rows = -> do
Vacancy.connection.select_rows(query)[1]
end
p_select_all = -> do
Vacancy.connection.select_all(query)[1]
end
p_mysql_2 = -> do
results = []
mysql.query(query).each { |x| results << x }
results
end
Vacancy.uncached do
Vacancy.limit(5).all
Benchmark.bm(20) do |b|
Gore.logger.debug "---------------------------------------"
b.report("p_ar", &p_ar)
b.report("p_select_rows", &p_select_rows)
b.report("p_select_all", &p_select_all)
b.report("p_mysql_2", &p_mysql_2)
end
end
<file_sep>/lib/gore/testing.rb
module Gore::Testing
module Globals
def ui_test(name, &block)
describe name do
include Capybara::DSL
include Gore::Testing::CapybaraHelpers
after { Capybara.current_driver = Capybara.default_driver }
class_eval(&block)
end
end
end
module Cases
def no_test(*args)
end
def visual_test(name, &block)
# test(name, &block)
end
def temp_class(base = Object, &block)
name = "TempClass#{rand(1000)}"
Gore::Testing::Cases.const_set(name, Class.new(base, &block))
end
end
module Helpers
def make(factory_name, *args, &block)
factory_name = factory_name.model_name.singular if Class === factory_name
Factory(factory_name, *args, &block)
end
def patch(*args)
Stubber.stub(*args)
end
def sent_emails
Mail::TestMailer.deliveries
end
end
module RackHelpers
def gets(*args)
get(*args)
assert_equal 200, last_response.status
end
end
module Assertions
def assert_equals(actual, expected, msg = nil)
assert_equal(expected, actual, msg)
end
def assert_matches(value, pattern, msg = nil)
assert_match(pattern, value, msg)
end
def assert_size(size, collection)
assert_equal size, collection.size
end
def assert_blank(object)
assert object.blank?
end
def assert_same_elements(a1, a2)
assert_equal a1.size, a2.size
a1.each { |x| assert a2.include?(x), "#{a2.inspect} is expected to include #{x.inspect}" }
end
def assert_emails(count)
assert_equal count, sent_emails.count
end
end
module CapybaraHelpers
def assert_has_contents(*strings)
strings.each { |string| assert_has_content(string) }
end
def assert_has_no_contents(*strings)
strings.each { |string| assert_has_no_content(string) }
end
def in_content(&block)
within '#content', &block
end
def pick(from, text)
select text, from: from
end
def fill(locator, with)
fill_in locator, with: with
end
def assert_title_like(string)
assert_match string, find("title").text
end
def assert_has_class(target, klass)
target = find(target) unless target.is?(Capybara::Node::Element)
assert_match %r{\b#{klass}\b}, target[:class]
end
def assert_has_no_class(target, klass)
target = find(target) unless target.is?(Capybara::Node::Element)
refute_match(/\b#{klass}\b/, target[:class])
end
def visit_link(locator)
link = find_link(locator)
assert link, "Link [#{locator}] is not found"
visit link['href']
end
def sop
save_and_open_page
end
def use_rack_test
Capybara.current_driver = :rack_test
end
def method_missing(method, *args, &block)
return super unless method.to_s.starts_with?("assert_")
predicate = method.to_s.sub(/^assert_/, '') + '?'
return super unless page.respond_to?(predicate)
assert page.send(predicate, *args, &block), "Failure: page.#{predicate}#{args.inspect}"
end
end
end
<file_sep>/test/lib/gore_test.rb
require "test_helper"
describe Gore do
describe "helpers" do
test '#object_id?' do
assert Gore.object_id?(1234)
assert Gore.object_id?("1234")
assert Gore.object_id?("1234-hello")
assert !Gore.object_id?("1234hello")
assert Gore.object_id?("4f09f1975a12ae7d50000001")
assert Gore.object_id?("4f09f1975a12ae7d50000001-hello")
assert Gore.object_id?(BSON::ObjectId.new)
assert !Gore.object_id?("msk")
assert !Gore.object_id?("hello-1234")
assert !Gore.object_id?("1f09f1975a1")
assert !Gore.object_id?("")
end
end
describe Gore::Mash do
setup do
@mash = Gore::Mash.new.merge!(:symbol => "a symbol", "string" => "a string")
end
test "indexer" do
@mash[:symbol].must_equal "a symbol"
@mash['symbol'].must_equal "a symbol"
@mash[:string].must_equal "a string"
@mash['string'].must_equal "a string"
end
test "slice" do
@mash.slice(:symbol, :string).must_equal Gore::Mash.new.merge!(:symbol => "a symbol", :string => "a string")
@mash.slice('symbol', 'string').must_equal Gore::Mash.new.merge!(:symbol => "a symbol", :string => "a string")
end
end
end
<file_sep>/app/models/rabotaru/loader.rb
# Loads the vacancies feed into tmp/rabotaru-DATE/CITY-INDUSTRY.rss
class Rabotaru::Loader
FeedUrlTemplate = "http://www.rabota.ru/v3_jsonExport.html?wt=f&c=%{city}&r=%{industry}&ot=t&cu=2&p=30&d=desc&cs=t&start=0&pp=50&fv=f&rc=992&new=1&t=1&country=1&c_rus=2&c_ukr=41&c_ec=133&sm=103"
attr_accessor :working_directory, :city, :industry
include Gore::EventLog::Accessor
def initialize(city, industry, job_key = Gore.date_stamp)
@working_directory = Rabotnegi.config.rabotaru_dir.join(job_key)
@working_directory = Rabotnegi.config.rabotaru_dir.join(job_key)
@city = City.get(city)
@industry = Industry.get(industry)
end
def load
working_directory.mkpath
feed_file = working_directory.join("#{city.key}-#{industry.key}.json")
return if feed_file.size?
feed_url = FeedUrlTemplate % {city: city.external_id, industry: industry.external_id}
feed_json = Http.get(feed_url)
File.write(feed_file, feed_json)
log.info 'feed_loaded', [city.key, industry.key, feed_json.size]
end
end
<file_sep>/app/models/rabotaru/job.rb
module Rabotaru
class Job < Gore::ApplicationModel
field :id, type: String, default: ->{ Time.now.strftime("%Y%m%d-%H%M%S-%6N") }
field :state, type: Symbol, default: 'pending'
field :cities, type: Array
field :industries, type: Array
field :run_count, type: Integer
field :error, type: String
field :results, type: Hash
embeds_many :loadings, class_name: 'Rabotaru::Loading'
def_state_predicates 'state', :pending, :started, :failed, :loaded, :processed, :cleaned
store_in collection: "rabotaru.jobs"
attr_accessor :period, :queue, :current
before_create do
self.cities ||= City.all.pluck(:key)
self.industries ||= Industry.all.pluck(:key)
end
def run
@period ||= Rabotnegi.config.rabotaru_period
@queue ||= cities.product(industries).map { |city, industry| Loading.new(city: city, industry: industry) }
@current = queue.shift
mark :started, run_count: run_count.to_i + 1
trap('INT') do
reload
mark :failed, error: "Received INT signal" if started? || pending?
exit
end
loop { done = tick; break if done }
rescue => e
Gore::Err.register("Rabotaru::Job.run", e, params: {job_id: id})
mark :failed, error: Gore.format_error(e)
end
def rerun
@queue = loadings_to_retry
run
end
def postprocess
processor = Processor.new(id)
processor.add_event_handler(:filtered) { |data| store(results: data) }
processor.process
mark :processed
VacancyCleaner.clean_all(started_at)
mark :cleaned
rescue => e
Gore::Err.register("Rabotaru::Job.postprocess", e, params: {job_id: id})
mark :failed, error: Gore.format_error(e)
end
def to_s
"RabotaruJob(#{id})"
end
private
def loadings_to_retry
pending_items = cities.product(industries) - loadings.map_to_array(:city, :industry)
pending_loadings = pending_items.map { |city, industry| Loading.new(city: city, industry: industry) }
non_done_loadings = loadings.select_neq(state: :done)
non_done_loadings.send_each(:mark, :pending)
pending_loadings.concat(non_done_loadings)
pending_loadings.sort_by! { |loading| loading.new? ? 1 : 0 }
pending_loadings
end
def tick
reload
current.reload if current && (current.queued? || current.started?)
log.debug 'tick', current: current.inspect, loadings_count: loadings.count
case current.try(:state)
when nil
mark :loaded
Gore.enqueue(Rabotaru::Job, :postprocess, id)
return true
when :pending
loadings << current unless loadings.include?(current)
current.queue
wait
when :started, :queued
wait
if Time.now - current.changed_at > 20.minutes
current.mark :failed, error: "Skipped after timeout"
@current = queue.shift
end
when :failed
if loadings.select(&:failed?).count > 3
mark :failed
return true
end
@current = queue.shift
when :done
time_since_done = Time.now - current.done_at
@current = queue.shift
wait(period - time_since_done) if time_since_done < period && period - time_since_done > 1
end
false
end
def wait(timeout = period)
sleep(timeout)
end
def self.postprocess(job_id)
find(job_id).postprocess
end
end
end
<file_sep>/doc/README.txt
# To restore the development database -
rake data:restore_dev src=tmp/db_110810_1510
mongorestore -d rabotnegi_dev --drop tmp/db_110810_1510
mongorestore -d rabotnegi_dev --drop tmp/db_110810_1510
# Resque
PIDFILE=./tmp/resque.pid BACKGROUND=yes QUEUE=file_serve rake environment resque:work
PIDFILE=./tmp/resque.pid BACKGROUND=yes QUEUE=* rake resque:work
# Deployment
mongod, redis + resque, rsyslog, nginx + passenger, cron, monit
## commands
sudo /opt/nginx/sbin/nginx -s reload
## Configs
/etc/profile — rubyopt
/etc/apache2/httpd.conf
/apps/bin/ruby — rubyopt
/opt/nginx/conf/nginx.conf
/opt/nginx/conf/sites/
/var/lib/mongodb
/etc/mongodb.conf
## Logs
/var/log/mongodb/mongodb.log
/opt/nginx/logs/error.log
## Reinstalling Passenger and Nginx
wget http://nginx.org/download/nginx-1.0.12.tar.gz
tar xzf nginx-1.0.12.tar.gz
sudo passenger-install-nginx-module
/home/apprunner/nginx-1.0.12
--with-http_gzip_static_module
## Installing RVM
sudo bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer )
sudo usermod -a -G rvm apprunner
sudo htpasswd -b htpasswd admin 0000
<file_sep>/test/rabotnegi/unit/application_model_test.rb
require 'test_helper'
unit_test 'Gore::ApplicationModel' do
test 'default salary' do
vacancy = make Vacancy
assert_respond_to Vacancy, :get
assert_respond_to Employer, :get
assert Vacancy.singleton_methods(false).include?(:get)
assert Employer.singleton_methods(false).exclude?(:get)
end
end
<file_sep>/test/rabotnegi/unit/rabotaru_job_test.rb
require 'test_helper'
unit_test Rabotaru::Job do
test "run w/o problems" do
Rabotaru::Loader.any_instance.stubs(:load)
Rabotaru::Processor.any_instance.stubs(:process)
job = Rabotaru::Job.create!(cities: %W(spb msk), industries: %w(it retail), period: 0.001)
job.run
job.reload
assert_equal :cleaned, job.state
assert_equal %w(spb msk), job.cities
assert_equal %w(it retail), job.industries
assert_equal 4, job.loadings.count
assert_equal [:done] * 4, job.loadings.pluck(:state)
end
teardown do
Rabotaru::Loader.any_instance.unstub(:load)
Rabotaru::Processor.any_instance.unstub(:process)
end
test "loadings_to_retry" do
job = Rabotaru::Job.create!
job.loadings.create! city: "spb", industry: "it", state: "done"
job.loadings.create! city: "spb", industry: "retail", state: "done"
job.loadings.create! city: "msk", industry: "telecom", state: "done"
job.loadings.create! city: "msk", industry: "building", state: "failed"
job.loadings.create! city: "msk", industry: "office", state: "started"
loadings_to_retry = job.send(:loadings_to_retry)
assert loadings_to_retry.detect_eq(city: :msk, industry: :building, state: :pending)
assert loadings_to_retry.detect_eq(city: :msk, industry: :office, state: :pending)
assert !loadings_to_retry.detect_eq(city: :spb, industry: :it)
assert !loadings_to_retry.detect_eq(city: :spb, industry: :retail)
assert !loadings_to_retry.detect_eq(city: :msk, industry: :telecom)
assert_equal City.all.count * Industry.all.count - 3, loadings_to_retry.count
end
test "loadings to retry for a job with a limited input" do
job = Rabotaru::Job.create!(cities: [:spb, :msk], industries: [:it, :retail])
job.loadings.create! city: "spb", industry: "it", state: "done"
job.loadings.create! city: "spb", industry: "retail", state: "done"
job.loadings.create! city: "msk", industry: "retail", state: "failed"
job.reload
assert_equal 2, job.send(:loadings_to_retry).count
end
end
<file_sep>/lib/ext/datetime_formats.rb
# %a - The abbreviated weekday name (``Sun'')
# %A - The full weekday name (``Sunday'')
# %b - The abbreviated month name (``Jan'')
# %B - The full month name (``January'')
# %c - The preferred local date and time representation
# %d - Day of the month (01..31)
# %H - Hour of the day, 24-hour clock (00..23)
# %I - Hour of the day, 12-hour clock (01..12)
# %j - Day of the year (001..366)
# %m - Month of the year (01..12)
# %M - Minute of the hour (00..59)
# %p - Meridian indicator (``AM'' or ``PM'')
# %S - Second of the minute (00..60)
# %U - Week number of the current year,
# starting with the first Sunday as the first
# day of the first week (00..53)
# %W - Week number of the current year,
# starting with the first Monday as the first
# day of the first week (00..53)
# %w - Day of the week (Sunday is 0, 0..6)
# %x - Preferred representation for the date alone, no time
# %X - Preferred representation for the time alone, no date
# %y - Year without a century (00..99)
# %Y - Year with century
# %Z - Time zone name
# %% - Literal ``%'' character
#
# t = Time.now
# t.strftime("Printed on %m/%d/%Y") #=> "Printed on 04/09/2003"
# t.strftime("at %I:%M%p") #=> "at 08:56AM"
# Rails formats:
# :db => "%Y-%m-%d %H:%M:%S",
# :number => "%Y%m%d%H%M%S",
# :time => "%H:%M",
# :short => "%d %b %H:%M",
# :long => "%B %d, %Y %H:%M",
# :long_ordinal => lambda { |time| time.strftime("%B #{ActiveSupport::Inflector.ordinalize(time.day)}, %Y %H:%M") },
# :rfc822 => lambda { |time| time.strftime("%a, %d %b %Y %H:%M:%S #{time.formatted_offset(false)}") }
# time.iso8601
# time.xmlschema
formats = {
num: "%y%m%d_%H%M%S",
humane: ->(val) { val.year == Time.now.year ? val.strftime("%b #{val.day} %H:%M") : val.to_s(:rus_zone) },
short_date: "%d.%m.%Y %H:%M:%S",
rus_full: "%d.%m.%Y %H:%M",
rus_zone: "%d.%m.%Y %H:%M:%S %Z",
rus_usec: ->(val) { val.strftime("%d.%m.%Y %H:%M:%S.#{'%06d' % val.usec} %Z") }
}
::Time::DATE_FORMATS.update(formats)
::Date::DATE_FORMATS.update(formats)
<file_sep>/app/helpers.rb
Rabotnegi.helpers do
def inspect_field(model, field, options = {})
value = model.send_chain(field.name) unless field.custom?
options[:trim] = field.trim
result = case field.format
when :city then City.get(value)
when :industry then Industry.get(value)
when :pre then element(:pre, trim(value, options[:trim]))
when String then send(field.format, value)
when Proc then trim(field.format.(model), options[:trim])
else inspect_value(value, options)
end
result = link_to(result, url(:admin_items, :show, collection: field.collection.key, id: model)) if field.format == :link || field.link
result
end
def city_options
settings.ui_cache.city_options ||= City.all.map { |city| [city.name, city.code.to_s] }
end
def industry_options
settings.ui_cache.industry_options ||= [
['Популярные', Industry.popular.map { |industry| [industry.name, industry.code.to_s] }],
['Остальные', Industry.other.map { |industry| [industry.name, industry.code.to_s] }]
]
end
def salary_options
settings.ui_cache.salary_options ||= [
['до 10 000', -10000],
['до 20 000', -20000],
['до 30 000', -30000],
['до 40 000', -40000],
['до 50 000', -50000],
['от 10 000', 10000],
['от 20 000', 20000],
['от 30 000', 30000],
['от 40 000', 40000],
['от 50 000', 50000]
]
end
def vacancies_page_title
if @vacancies
city = City.get(params[:city])
industry = Industry.get(params[:industry]) if params[:industry].present?
query = params[:q]
page = params[:page]
content = "Вакансии — #{city.name}"
content << " — #{industry.name}" if industry
content << " — #{query}" if query
content << ", стр. №#{page}" if page
content
else
"Поиск вакансий"
end
end
def back_to_all_vacancies_url_for(vacancy)
request.referer =~ /vacancies/ ? request.referer : url(:vacancies, :index, city: vacancy.city, industry: vacancy.industry)
end
def resumes_page_title
if @resumes
city = City[params[:city]] if params[:city].present?
industry = Industry[params[:industry]] if params[:industry].present?
query = params[:q]
page = params[:page]
content = "Резюме — #{city.name}"
content << " — #{industry.name}" if industry
content << " — #{query}" if query
content << ", стр. №#{page}" if page
content
else
"Поиск резюме"
end
end
end
<file_sep>/test/test_helper.rb
PADRINO_ENV = ENV["X_RACK_ENV"] || ($*.to_s =~ %r{/ui/} ? "testui" : "test") unless defined?(PADRINO_ENV)
require File.expand_path('../../config/boot', __FILE__)
require "support/mocks"
require "support/factories"
require "capybara"
require "capybara/dsl"
if Gore.env.testui?
[Vacancy, User, Gore::EventLog::Item].each(&:delete_all)
load "test/support/data.rb"
puts "Seeded #{Gore.env}"
end
class MiniTest::Spec
include Mocha::API
include Rack::Test::Methods
include Webrat::Matchers
include Gore::Testing::Helpers
include Gore::Testing::RackHelpers
include Gore::Testing::Assertions
extend Gore::Testing::Cases
class << self
alias test it
alias setup before
alias teardown after
end
alias response last_response
teardown do
Vacancy.delete_all
User.delete_all
end unless Gore.env.testprod? || Gore.env.testui?
def app
Rabotnegi.tap { |app| }
end
def helpers
app.last_instance
end
def response_body
last_response.body
end
end
module MiniTest::Expectations
infect_an_assertion :assert_equal, :must_eq
end
include Gore::Testing::Globals
alias unit_test describe
Webrat.configure do |config|
config.mode = :rack
end
Turn.config do |c|
c.format = :pretty # outline pretty dotted progress marshal cue
end
Capybara.run_server = false
Capybara.app_host = "http://localhost:3002"
Capybara.server_port = 3002
Capybara.default_driver = :webkit
Capybara.javascript_driver = :webkit
<file_sep>/test/rabotnegi/unit/currency_test.rb
require 'test_helper'
unit_test Currency do
test "convertion" do
assert_in_delta 73, Currency.convert(100, :usd, :eur), 1
assert_equal 1, Currency.convert(31, :rub, :usd)
end
test "convertion to the same currency" do
assert_equal 100, Currency.convert(100, :usd, :usd)
assert_equal 100, Currency.convert(100, :rub, :rub)
end
end<file_sep>/test/lib/russian_inflector_test.rb
require "test_helper"
unit_test Gore::RussianInflector do
test "parameterize" do
assert_equal "ruby-developer", Gore::RussianInflector.parameterize("Ruby Developer")
assert_equal "ruby-разработчик", Gore::RussianInflector.parameterize("Ruby Разработчик")
assert_equal "ruby-разработчик", Gore::RussianInflector.parameterize("Ruby - Разработчик.")
assert_equal "торговый-представитель-20", Gore::RussianInflector.parameterize("Торговый представитель № 20")
assert_equal "менеджер-по-продажам-промышленного-оборудования", Gore::RussianInflector.parameterize("Менеджер по продажам промышленного оборудования")
assert_equal "бухгалтер-по-расчету-заработной-платы", Gore::RussianInflector.parameterize("Бухгалтер по расчету заработной платы")
end
test "truncate" do
assert_equal "ruby-разработчик", "ruby-разработчик".truncate(30, separator: '-', omission: '')
assert_equal "менеджер-по-продажам", "менеджер-по-продажам-промышленного-оборудования".truncate(30, separator: '-', omission: '')
assert_equal "бухгалтер-по-расчету", "бухгалтер-по-расчету-заработной-платы".truncate(30, separator: '-', omission: '')
assert_equal "ruby-разработчик", "ruby-разработчик".truncate(40, separator: '-', omission: '')
assert_equal "менеджер-по-продажам-промышленного", "менеджер-по-продажам-промышленного-оборудования".truncate(40, separator: '-', omission: '')
assert_equal "бухгалтер-по-расчету-заработной-платы", "бухгалтер-по-расчету-заработной-платы".truncate(40, separator: '-', omission: '')
end
end
<file_sep>/script/test_temp.rb
Rabotaru::Loader.new(city: 'spb', industry: 'it').load
Rack::Mount::Utils.const_set(:UNSAFE_PCHAR, /[^-_.!~*'()a-zA-Zа-яА-Я\d:@&=+$,;%]/.freeze)
p Rack::Mount::Utils.escape_uri("/vacancies/here/12345-по-русски")
<file_sep>/test/lib/captcha_test.rb
require 'test_helper'
describe Gore::Captcha do
subject { Gore::Captcha.create! }
it "has a long random generated key" do
subject.id.to_s.must_match %r<[0-9a-f]{24}>
end
it "has a random generated text" do
subject.text.wont_be_nil
subject.text.must_match %r<[0-9A-Z]{5}>
end
it "generates an image and writes it to a file" do
image_path = Padrino.root("tmp/test.tempfiles/#{subject.id}.jpeg")
Gore::Captcha.write_image_for_text("ABCD", File.open(image_path, "wb"))
file_info = `file #{image_path}`
file_info.must_match %r{JPEG image data}
end
test '#image_file returns a path to the tempfile with the captcha image' do
file_path = subject.image_file
file_info = `file #{file_path}`
file_info.must_match %r{JPEG image data}
end
test '#valid?' do
captcha = Gore::Captcha.create!(text: "RIGHT")
assert Gore::Captcha.valid?(captcha.id, "right")
assert Gore::Captcha.valid?(captcha.id, "RIGHT")
assert !Gore::Captcha.valid?(captcha.id, "WRONG")
assert !Gore::Captcha.valid?("4f3bd25fe999fb24ed000001", "right")
assert !Gore::Captcha.valid?("invalid-id", "right")
end
end
describe "Capcha Controller" do
let(:captcha) { Gore::Captcha.create! }
test "GET /captcha/:id.jpeg" do
get "/captcha/#{captcha.id}.jpeg"
response.status.must_equal 200
response.content_type.must_equal "image/jpeg"
response.content_length.must_be_close_to 2.kilobytes, 500.bytes
end
test "GET /captcha/:invalid-id.jpeg" do
get "/captcha/#{BSON::ObjectId.new}.jpeg"
response.status.must_equal 404
end
end
describe "Captcha helpers" do
test "GET /page-with-capthca" do
get "/vacancies/new"
captcha = Gore::Captcha.last
assert_have_selector "div.captcha input[type=text][name=captcha_text]"
assert_have_selector "div.captcha input[type=hidden][name=captcha_id][value='#{captcha.id}']"
get "/vacancies/new", captcha_id: captcha.id, captcha_text: "WRONG"
captcha2 = Gore::Captcha.last
assert captcha.id != captcha2.id
assert_have_selector "div.captcha input[type=text][name=captcha_text]"
assert_have_selector "div.captcha input[type=hidden][name=captcha_id][value='#{captcha2.id}']"
get "/vacancies/new", captcha_id: captcha2.id, captcha_text: captcha2.text
assert_have_selector "input[type=hidden][name=captcha_text][value='#{captcha2.text}']"
assert_have_selector "input[type=hidden][name=captcha_id][value='#{captcha2.id}']"
end
end
<file_sep>/app/controllers/controllers.rb
Rabotnegi.controllers do
get "/" do
render "vacancies/index"
end
get "/sitemap.xml" do
render "shared/sitemap"
end
get "/site/info" do
render env: Gore.env,
db: Vacancy.db.name,
counts: { vacancies: Vacancy.count, events: Gore::EventLog::Item.count, users: User.count },
settings: {
static: settings.static,
raise_errors: settings.raise_errors,
reload_templates: settings.reload_templates,
logging: settings.logging,
log_level: Padrino.logger.level,
log_path: Padrino.logger.log.respond_to?(:path) && Padrino.logger.log.path
}
end
get "/site/env" do
Gore.env
end
#
# Captcha
#
get "/captcha/:id.jpeg", name: :captcha do
captcha = Gore::Captcha.find(params[:id]) rescue nil
halt 404 unless captcha
send_file captcha.image_file, type: 'image/jpeg', disposition: 'inline'
end
#
# Tests
#
get "/tests/noop" do
""
end
get "/tests/error" do
raise ArgumentError, "shit happens"
end
#
# Dev
#
get "/dev" do
render "dev/dev"
end
get '/dev/request' do
render env.select { |k,v| [String, Numeric, Symbol, TrueClass, FalseClass, NilClass, Array, Hash].any? { |klass| klass === v } }
end
get "/dev/error" do
raise "shit happens"
end
get "dev/typo" do
bum_bum_shit
end
get "/dev/lorem" do
render "dev/lorem", layout: false
end
end
<file_sep>/app/models/city.rb
class City < Struct.new(:code, :external_id, :name)
alias key code
def to_s
name
end
def inspect
"City(#{code}/#{external_id} #{name})"
end
def key_str
@key_str ||= key.to_s
end
def log_key
key
end
cattr_reader :all
@@all = [
City.new(:msk, 1, "Москва"),
City.new(:spb, 2, "Санкт-Петербург"),
City.new(:ekb, 3, "Екатеринбург"),
City.new(:nn, 4, "Нижний Новгород"),
City.new(:nsk, 9, "Новосибирск")
]
class << self
def [](code)
if Array === code
code = code.map(&:to_sym)
all.select { |x| x.code.in?(code) }
else
all.detect { |x| x.code == code.to_sym }
end
end
alias_method :get, :[]
def each(&block)
@@all.each(&block)
end
def find_by_external_id(external_id)
external_id = external_id.to_i
city = @@all.find { |city| city.external_id == external_id } || raise(ArgumentError, "Город ##{external_id} не найден")
city.code
end
def key_matches?(key)
key = key.to_s
key.blank? || all.any? { |obj| obj.key_str == key }
end
def q
query = Object.new
class << query
def method_missing(selector, *args)
City[selector.to_sym]
end
end
query
end
end
end
<file_sep>/lib/gore/captcha.rb
module Gore
class Captcha
include Mongoid::Document
store_in collection: "sys.captchas"
field :text, type: String, default: -> { Captcha.generate_random_text }
field :created_at, type: DateTime, default: -> { Time.now }
validates_presence_of :text
# convert -fill darkblue -edge 10 -background white -size 100x28 -wave 3x69 -gravity 'Center' -pointsize 22 -implode 0.2 label:ABC01 'captcha.jpg' 2>&1
def image_file
outfile = Tempfile.new(['gore_captcha', '.jpg'])
outfile.binmode
Services.write_image_for_text(text, outfile)
File.expand_path(outfile.path)
end
module Services
extend self
def valid?(id, text)
captcha = Captcha.find(id) rescue nil
captcha && captcha.text == text.to_s.upcase
end
def generate_random_text(length = 5)
Alphabet.sample(length).join
end
# write_image File.open(Padrino.root("tmp/captcha.jpeg"), 'wb')
def write_image_for_text(text, file)
amplitude = 2 + rand(2)
frequency = 50 + rand(20)
params = ['-fill darkblue', '-edge 10', '-background white']
params << "-size 100x28"
params << "-wave #{amplitude}x#{frequency}"
params << "-gravity 'Center'"
params << "-pointsize 22"
params << "-implode 0.2"
params << "label:#{text}"
params << "'#{File.expand_path(file.path)}'"
command = "convert #{params.join(' ')} 2>&1"
output = `#{command}`
raise StandardError, "Error while running #{command}: #{output}" unless $?.exitstatus == 0
ensure
file.close
end
end
extend Services
Alphabet = ('A'..'Z').to_a + ('0'..'9').to_a
end
end
<file_sep>/app/app.rb
class Rabotnegi < Padrino::Application
register SassInitializer
register Padrino::Rendering
register Padrino::Mailer
register Padrino::Helpers
enable :sessions
include Gore::EventLog::Accessor
set :locale_path, %w(config/locales/ru.core.yml config/locales/ru.yml)
set :uid_secret_token, 'dc00acaaa4039a2b9f9840f226022c62fd4b6eb7fa45ca289eb8727aba365d0f4ded23a3768c6c81ef2593da8fde51f9405aedcb71621a57a2de768042f336e5'
set :message_encryptor, ActiveSupport::MessageEncryptor.new(uid_secret_token)
set :default_builder, Gore::ViewHelpers::FormBuilder
set :ui_cache, OpenStruct.new
set :assets do
@sprockets ||= Sprockets::Environment.new.tap do |env|
env.append_path 'app/assets/javascripts'
env.append_path 'app/assets/stylesheets'
env.append_path 'app/assets/images'
env.append_path 'public/vendor'
end
end
set :delivery_method, :smtp => {
address: "smtp.gmail.com",
port: 587,
user_name: "railsapp",
password: "<PASSWORD>",
authentication: :plain,
enable_starttls_auto: true
}
set :config, OpenStruct.new.tap { |config|
config.admin_login = 'admin'
config.admin_password = '<PASSWORD>'
config.err_max_notifications_per_hour = 2
config.err_sender = "<EMAIL>"
config.err_recipients = "<EMAIL>"
config.original_vacancies_data_dir = Gore.root.join("tmp/vacancies_content")
config.rabotaru_dir = Gore.root.join("tmp/rabotaru")
config.rabotaru_period = 15
config.default_queue = :main
config.google_analytics_id = "UA-1612812-2"
}
set :xhr do |truth| condition { request.xhr? } end
set :match_id do |truth| condition { Gore.object_id?(params[:id]) } end
set :if_params do |*args|
mapping = args
condition { mapping.all? { |param, matcher| matcher.key_matches?(params[param]) } }
end
Slim::Engine.set_default_options disable_escape: true, disable_capture: false
Resque.redis.namespace = "rabotnegi:jobs"
configure :testprod, :testui do
enable :logging
disable :static
disable :reload_templates
disable :raise_errors
set :delivery_method, :test
end
configure :development do
register Gore::LogFilter
set :delivery_method, :test
set :show_exceptions, :after_handler
config.rabotaru_period = 5
Slim::Engine.set_default_options pretty: true
# Resque.inline = true
end
configure :test do
enable :raise_errors
set :delivery_method, :test
config.rabotaru_dir = Gore.root.join("tmp/test.rabotaru")
config.original_vacancies_data_dir = Gore.root.join("tmp/test.vacancies_content")
Resque.inline = true
end
configure :production do
enable :logging
disable :static
# syslog_facility = ENV["RAILS_PROC"].presence || "web"
# Padrino.logger = SyslogLogger.new("rab-#{syslog_facility}", Syslog::LOG_USER, Syslog::LOG_PID)
# Padrino.log_level = :info
end
helpers Gore::ControllerHelpers::Urls
helpers Gore::ControllerHelpers::Identification
helpers Gore::ControllerHelpers::Users
helpers Gore::ControllerHelpers::Captchas
helpers Gore::ViewHelpers::Common
helpers Gore::ViewHelpers::Inspection
helpers Gore::ViewHelpers::Admin
helpers Gore::ViewHelpers::Formatting
helpers Gore::ViewHelpers::Editing
helpers Gore::ViewHelpers::Layout
helpers Gore::ViewHelpers::Collections
##
# Caching support
#
# register Padrino::Cache
# enable :caching
#
# set :cache, Padrino::Cache::Store::Memcache.new(::Memcached.new('127.0.0.1:11211', :exception_retry_limit => 1))
# set :cache, Padrino::Cache::Store::Memcache.new(::Dalli::Client.new('127.0.0.1:11211', :exception_retry_limit => 1))
# set :cache, Padrino::Cache::Store::Redis.new(::Redis.new(:host => '127.0.0.1', :port => 6379, :db => 0))
# set :cache, Padrino::Cache::Store::Memory.new(50)
# set :cache, Padrino::Cache::Store::File.new(Padrino.root('tmp', app_name.to_s, 'cache')) # default choice
#
#
# Filters & error handlers
#
error 500..599 do
raise env["sinatra.error"] if Gore.env.development?
Gore::Err.register route.named || request.path, env["sinatra.error"],
params: params.except("captures"),
url: request.url,
verb: request.request_method,
session: session.to_hash.except('flash'),
flash: flash.to_hash,
request_headers: env.select { |k,v| k.starts_with?("HTTP_") },
response_headers: headers
raise env["sinatra.error"]
end
before { settings.set :last_instance, self } if Gore.env.test?
before { logger.info "Start #{request.path}" } if Gore.env.development?
# before { `touch #{Padrino.root("app/app.rb")}` } if Gore.env.development?
##
# Overrides
#
# Overriden to enable string/symbol access to all (path & query) parameters.
def indifferent_hash
Gore::Mash.new
end
# Fix the totally broken view engines.
def concat_content(content)
content
end
# def block_is_template?(block)
# false
# end
# def form_tag(url, options={}, &block)
# desired_method = options[:method]
# data_method = options.delete(:method) if options[:method].to_s !~ /get|post/i
# options.reverse_merge!(:method => "post", :action => url)
# options[:enctype] = "multipart/form-data" if options.delete(:multipart)
# options["data-remote"] = "true" if options.delete(:remote)
# options["data-method"] = data_method if data_method
# options["accept-charset"] ||= "UTF-8"
# inner_form_html = hidden_form_method_field(desired_method)
# inner_form_html += capture_html(&block).to_s
# content_tag(:form, inner_form_html, options)
# end
def label_tag(name, *args, &block)
options = args.extract_options!
options[:caption] = args.first if args.any?
super(name, options, &block)
end
def select_tag(name, options={})
options[:options] = send(options[:options]) if options[:options].is_a?(Symbol)
options[:grouped_options] = send(options[:grouped_options]) if options[:grouped_options].is_a?(Symbol)
super
end
def capture_html(*args, &block)
block_given? && block.call(*args)
end
def dump_errors!(boom)
return super unless %w(development testui).include?(Gore.env)
return super unless Array === boom.backtrace
boom.backtrace.reject! { |line| line =~ /thin|thor|eventmachine|rack|barista|http_router|tilt/ }
boom.backtrace.map! { |line| line.gsub(Padrino.root, '') }
super
end
assets.context_class.class_eval do
def asset_path(path, options = {})
"/assets/#{path}"
end
end
end
<file_sep>/app/models/rabotaru/converter.rb
# Convert json data to vacancy models
class Rabotaru::Converter
include Gore::EventLog::Accessor
def convert(hash)
vacancy = Vacancy.new
vacancy.title = hash['position']
vacancy.description = hash['responsibility']['value']
vacancy.external_id = extract_id(hash['link'])
vacancy.employer_name = hash['employer'] && hash['employer']['value']
vacancy.city = City.find_by_external_id(hash['city']['id']).to_s
vacancy.industry = Industry.find_by_external_ids(
hash['rubric_0'] && hash['rubric_0']['id'],
hash['rubric_1'] && hash['rubric_1']['id'],
hash['rubric_2'] && hash['rubric_2']['id']
).to_s
vacancy.salary = convert_salary(hash['salary'])
vacancy.created_at = Time.parse(hash['publishDate'])
vacancy
end
private
# http://www.rabota.ru/vacancy1234567.html' => 1234567
def extract_id(link)
%r{http://www.rabota.ru/vacancy(\d+).html} =~ link
$1.to_i
end
# {"min": "27000", "max": "35000", "currency": {"value": "руб", "id": "2"}} => Salary(min: 27000, max: 35000, currency: :rub)
# {"min": "10000, "max": "10000", "currency": {"value": "руб", "id": "2"}}
# {"min": "27000", "currency": {"value": "руб", "id": "2"}}
# {"agreed":"yes"}
def convert_salary(hash)
salary = Salary.new
if hash['agreed'] == 'yes'
salary.negotiable = true
else
salary.negotiable = false
case
when hash['min'] == hash['max']
salary.exact = hash['min'].to_i
when hash['max'].blank?
salary.min = hash['min'].to_i
when hash['min'].blank?
salary.max = hash['max'].to_i
else
salary.min = hash['min'].to_i
salary.max = hash['max'].to_i
end
salary.currency = convert_currency(hash['currency']['value'])
salary.convert_currency(:rub)
end
salary
end
# 'rub' => :rub
def convert_currency(currency_name)
case currency_name.downcase
when 'руб', 'rub' then :rub
when 'usd' then :usd
when 'eur' then :eur
else
log.warn 'convert_currency.unknown', currency: currency_name
:rub
end
end
end
<file_sep>/lib/tasks/app.rake
require "shellwords"
namespace :app do
task :load_demo_data do
Gore.env = 'test'
Rake::Task['environment'].invoke
puts "Loading 100 vacancies into the `#{Gore.env}` database"
100.times { Vacancy.create title: "Test", description: "Hello", industry: "it", city: "msk" }
end
end
namespace :rabotaru do
task :start_job => :environment do
Rabotaru.start_job
end
# Usage: rake rabotaru:load CITY=spb,msk INDUSTRY=telework
task :load => :environment do
$log_to_stdout = true
options = {}
options[:cities] = ENV['CITY'].split(',').pluck(:to_sym) if ENV['CITY'].present?
options[:industries] = ENV['INDUSTRY'].split(',').pluck(:to_sym) if ENV['INDUSTRY'].present?
Rabotaru.start_job(options)
end
task :reload => :environment do
$log_to_stdout = true
Rabotaru::Job.asc(:created_at).last.try(:rerun)
end
end
namespace :vacancies do
task :count => :environment do
puts Vacancy.count
end
task kill_spam: :environment do
Tasks.kill_spam
end
task :cleanup => :environment do
Vacancy.cleanup
end
task sanitize: :environment do
Vacancy.all.each do |v|
sanitizer = HTML::FullSanitizer.new
v.title = sanitizer.sanitize(v.title)
v.employer_name = sanitizer.sanitize(v.employer_name)
v.save!
end
end
task clean: :environment do
since = Time.parse ENV['SINCE']
puts "Cleaning vacancies since #{since}"
VacancyCleaner.clean_all since
end
end
<file_sep>/app/views/shared/sitemap.builder
xml.instruct!
xml.urlset :xmlns => "http://www.sitemaps.org/schemas/sitemap/0.9" do
City.each do |city|
Industry.each do |industry|
xml.url {
xml.loc absolute_url(:vacancies, :index, city: city.code, industry: industry.code)
xml.changefreq 'daily'
}
end
end
end
<file_sep>/lib/gore/application_model.rb
class Gore::ApplicationModel
def self.inherited(derived)
derived.class_eval do
include Mongoid::Document
include Mongoid::Timestamps
include Gore::EventLog::Accessor
end
end
end
<file_sep>/test/lib/event_handling_test.rb
require "test_helper"
unit_test Gore::EventHandling do
service_klass = temp_class do
include Gore::EventHandling
attr :ivar
def f1
raise_event :hello do
:hello_from_f1
end
end
def f2
raise_event :hello do
:hello_from_f2
end
end
def f3
raise_event :hello do
@ivar = :modified_in_f3_hello
:hello_from_f3
end
end
end
setup do
@service = service_klass.new
end
test "basic handling" do
hello_event_results = []
@service.add_event_handler(:hello) { |data| hello_event_results << data }
@service.f1
@service.f2
assert hello_event_results.include?(:hello_from_f1)
assert hello_event_results.include?(:hello_from_f2)
end
def foo(x)
end
test "event generator should not be invoked when there are no event handlers attached" do
assert_nil @service.ivar
@service.f3
assert_nil @service.ivar
@service.add_event_handler(:hello) { |data| }
@service.f3
assert_equal :modified_in_f3_hello, @service.ivar
end
test "remove a handler" do
handler = ->(data) { hello_event_results << data }
@service.add_event_handler(:hello, &handler)
assert_equal 1, @service.event_handlers_for(:hello).count
@service.remove_event_handler(:hello, &handler)
assert_equal 0, @service.event_handlers_for(:hello).count
end
end
<file_sep>/doc/todo.txt
* model in a different database
* model in the namespace
* static asset served from /APP/
* static asset served by the web server
* dev-time class reload | e59ab3963ed36406e643199736699977dffbcfe6 | [
"Text",
"Ruby"
] | 95 | Ruby | mitya/rabotnegi-padrino | fdf1db819cb3f432fa8cc07b5bbfac4415281ba7 | 8be81cba13a1e136922cc8f5f16fe91096c7f953 | |
refs/heads/master | <file_sep>class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
for i in nums2:
nums1.append(i)
nums1.sort()
k=len(nums1)
if k%2==0:
return (float(nums1[int(k/2-1)])+nums1[int(k/2)])/2
else:
return nums1[int((k-1)/2)]<file_sep>class Solution {
public:
int reverse(int x) {
long long tmp = abs((long long)x);
long long ret = 0;
while (tmp) {
ret = ret * 10 + tmp % 10;
if (ret > INT_MAX)
return 0;
tmp /= 10;
}
if (x > 0)
return (int)ret;
else
return (int)-ret;
}
};
<file_sep>class Solution {
public:
string reverseWords(string s) {
auto iter = s.begin();
auto last = s.begin();
do{
last = std::find(iter, s.end(), ' ');
std::reverse(iter, last);
}while((iter = last)++ != s.end());
return s;
}
}; | 1bef0e47598ee9798dee450050a1f1d7d0fa926c | [
"Python",
"C++"
] | 3 | Python | PengboLiu/LeetCodeAnswer | 10117a913fe7dccbddc1687626c33340049243f5 | fd1fca5fb55f1555911490a6965fe5bfb769ef38 | |
refs/heads/master | <repo_name>StefanTan18/Work04<file_sep>/work_04.c
#include <stdio.h>
#include <string.h>
int main(){
char str1[] = "Tuesday";
char str2[256] = "Imagine";
printf("Printing str1... %s\n", str1);
printf("Printing str2... %s\n", str2);
printf("Testing strcat()...\n");
printf("Appending str2 to str1...\n\n");
strcat(str1, str2);
printf("Printing str1 after concatenation... %s\n", str1);
printf("Printing str2 after concatenation... %s\n\n", str2);
printf("Testing strncat()...\n");
printf("str3 gets unmodified str1 and str4 gets unmodified str2...\n");
char str3[] = "Tuesday";
char str4[256] = "Imagine";
printf("Appending 8 bytes of str4 to str3...\n\n");
strncat(str3, str4, 8);
printf("Printing str3 after concatenation... %s\n", str3);
printf("Printing str4 after concatenation... %s\n\n", str4);
printf("Testing strncat()...\n");
printf("str5 gets unmodified str1 and str6 gets unmodified str2...\n");
char str5[] = "Tuesday";
char str6[256] = "Imagine";
printf("Appending 4 bytes of str6 to str5...\n\n");
strncat(str5, str6, 4);
printf("Printing str5 after concatenation... %s\n", str5);
printf("Printing str6 after concatenation... %s\n", str6);
return 0;
}
<file_sep>/README.md
# Work04
Work 04: Demon-string-tion
| 426555838048b3b26f6ccb7f6262fb3804531d35 | [
"Markdown",
"C"
] | 2 | C | StefanTan18/Work04 | 73f4533ec8af839d75976eabbc0e908633b8b91a | 35d876567533578ada8a8d404d737a2d2976aef7 | |
refs/heads/master | <repo_name>codeocelot/dev-proxy-app<file_sep>/README.md
# dev-proxy-app<file_sep>/app.js
const http = require('http');
const request = require('request');
const port = 9090;
const PROXY_BASE_URL = 'https://edge-api.yewno.com';
const requestHandler = (req, response) => {
request({ url: `${PROXY_BASE_URL}/${req.url}`, encoding: null })
.on('response', (r) => {
response.set(r.headers);
})
.on('error', (...args) => {
console.error('error', args);
})
.pipe(response);
};
const server = http.createServer(requestHandler);
server.listen(port, (err) => {
if (err) {
return console.error('something bad happened', err);
}
console.log(`server is listening on ${port}`);
});
| 7a02d3026a151f45207f9ff4cc6f0b930c0b0be0 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | codeocelot/dev-proxy-app | 8f372b05e12b99720b24b8e42ec365d99058ba84 | ad714497e576e76498494abca898f2c0013aeb8b | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CSDHRProject.Models
{
public class ViewModel
{
public ApplicationUser NewHire { get;set;}
public RegisterViewModel Account { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CSDHRProject.Models;
using System.IO;
namespace CSDHRProject.Controllers
{
public class JobApplicationsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: JobApplications
public ActionResult Index()
{
return View(db.JobApplications.ToList());
}
// GET: JobApplications/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
JobApplication jobApplication = db.JobApplications.Find(id);
if (jobApplication == null)
{
return HttpNotFound();
}
return View(jobApplication);
}
// GET: JobApplications/Create
public ActionResult Create()
{
return View();
}
// POST: JobApplications/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "JobApplicationId,ApplicantFirstName,ApplicantLastName,ApplicantEmail,ResumeFileName,CoverLetterFileName,ApplicantStatus")] JobApplication jobApplication)
{
if (ModelState.IsValid)
{
db.JobApplications.Add(jobApplication);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(jobApplication);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateJobApplication(ApplicationEditViewModel jevm)
{
JobApplication jobApplication = jevm.Item;
if (ModelState.IsValid)
{
if(jevm.ResumeFile != null && jevm.ResumeFile.ContentLength > 0)
{
var applicationFolder = "/Content/JobApplications/";
var filename = DateTime.Now.ToBinary().ToString("x") +
Path.GetFileName(jevm.ResumeFile.FileName);
var path = Path.Combine(Server.MapPath("~" + applicationFolder), filename);
jevm.ResumeFile.SaveAs(path);
jevm.Item.ResumeFileName = applicationFolder + filename;
}
if (jevm.CoverLetterFile != null && jevm.CoverLetterFile.ContentLength > 0)
{
var applicationFolder = "/Content/JobApplications/";
var filename = DateTime.Now.ToBinary().ToString("x") +
Path.GetFileName(jevm.CoverLetterFile.FileName);
var path = Path.Combine(Server.MapPath("~" + applicationFolder), filename);
jevm.CoverLetterFile.SaveAs(path);
jevm.Item.CoverLetterFileName = applicationFolder + filename;
}
db.JobApplications.Add(jobApplication);
db.SaveChanges();
return RedirectToAction("Index");
}
return RedirectToAction("Index");
}
// GET: JobApplications/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
JobApplication jobApplication = db.JobApplications.Find(id);
if (jobApplication == null)
{
return HttpNotFound();
}
return View(jobApplication);
}
// POST: JobApplications/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "JobApplicationId,ApplicantFirstName,ApplicantLastName,ApplicantEmail,ResumeFileName,CoverLetterFileName,ApplicantStatus")] JobApplication jobApplication)
{
if (ModelState.IsValid)
{
db.Entry(jobApplication).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(jobApplication);
}
// GET: JobApplications/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
JobApplication jobApplication = db.JobApplications.Find(id);
if (jobApplication == null)
{
return HttpNotFound();
}
return View(jobApplication);
}
// POST: JobApplications/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
JobApplication jobApplication = db.JobApplications.Find(id);
db.JobApplications.Remove(jobApplication);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
// POST: JobApplications/Details/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details([Bind(Include = "ApplicantStatus")] JobApplication jobApplication)
{
if (ModelState.IsValid)
{
db.Entry(jobApplication).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(jobApplication);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CSDHRProject.Models;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;
namespace CSDHRProject.Controllers
{
public class BenefitRegistrationsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: BenefitRegistrations
public ActionResult Index()
{
return View(db.BenefitRegistrations.ToList());
}
// GET: BenefitRegistrations/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BenefitRegistration benefitRegistration = db.BenefitRegistrations.Find(id);
if (benefitRegistration == null)
{
return HttpNotFound();
}
return View(benefitRegistration);
}
// GET: BenefitRegistrations/Create
public ActionResult Create()
{
return View();
}
// POST: BenefitRegistrations/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,RealtionshipStatus,BenefitType,Dental,Optical,Paramedical")] BenefitRegistration benefitRegistration)
{
if (ModelState.IsValid)
{
db.BenefitRegistrations.Add(benefitRegistration);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(benefitRegistration);
}
// GET: BenefitRegistrations/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BenefitRegistration benefitRegistration = db.BenefitRegistrations.Find(id);
if (benefitRegistration == null)
{
return HttpNotFound();
}
return View(benefitRegistration);
}
// POST: BenefitRegistrations/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,RealtionshipStatus,BenefitType,Dental,Optical,Paramedical")] BenefitRegistration benefitRegistration)
{
if (ModelState.IsValid)
{
db.Entry(benefitRegistration).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(benefitRegistration);
}
// GET: BenefitRegistrations/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
BenefitRegistration benefitRegistration = db.BenefitRegistrations.Find(id);
if (benefitRegistration == null)
{
return HttpNotFound();
}
return View(benefitRegistration);
}
// POST: BenefitRegistrations/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
BenefitRegistration benefitRegistration = db.BenefitRegistrations.Find(id);
db.BenefitRegistrations.Remove(benefitRegistration);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
public ActionResult BenefitSelection()
{
return RedirectToAction("/Index");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CSDHRProject.Models
{
public class JobPosting
{
public int JobPostingId { get; set; }
public String JobTitle { get; set; }
public DateTime JobPostingDeadline { get; set; }
public String JobDepartmentName { get; set; }
//part for job posting view
public String JobPostingFileName { get; set; }
}
public class JobApplication
{
public int JobApplicationId { get; set; }
public String ApplicantFirstName { get; set; }
public String ApplicantLastName { get; set; }
public String ApplicantEmail { get; set; }
public String ResumeFileName { get; set; }
public String CoverLetterFileName { get; set; }
//part for hr/manager
public String ApplicantStatus { get; set; }
public virtual JobPosting JobPost { get; set; }
}
public class JobEditViewModel
{
public JobPosting Item { get; set; }
public HttpPostedFileBase JobPostFile { get; set; }
}
public class ApplicationEditViewModel
{
public JobApplication Item { get; set; }
public HttpPostedFileBase ResumeFile { get; set; }
public HttpPostedFileBase CoverLetterFile { get; set; }
}
}<file_sep># CSD4354-HRProject
The Phoenix Corporation project for CSD-4354 - Advanced Web Apps using C#, ASP.NET
### HOW TO COMMIT USING VISUAL STUDIO
https://www.visualstudio.com/en-us/docs/git/share-your-code-in-git-vs
### Alternatively if you are having problems with this come see Matt and he will show you how.
# DON'T FORGET TO USE THE BRANCHING MODEL AS SEEN HERE http://nvie.com/posts/a-successful-git-branching-model/
# ATTN: Styles
This goes inside Views/Shared/_Layout.cshtml (between head tags) => https://pastebin.com/0X4Fu9WH
Use this for the jumbotron (if you need one) => https://pastebin.com/LVjADvSC
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CSDHRProject.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
namespace CSDHRProject.Controllers
{
public class EmployeeClaimsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: EmployeeClaims
public ActionResult Index()
{
return View(db.EmployeeClaims.ToList());
}
// GET: EmployeeClaims/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
EmployeeClaim employeeClaim = db.EmployeeClaims.Find(id);
if (employeeClaim == null)
{
return HttpNotFound();
}
return View(employeeClaim);
}
// GET: EmployeeClaims/Create
public ActionResult Create()
{
return View();
}
// POST: EmployeeClaims/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Amount,Date,Service")] EmployeeClaim employeeClaim)
{
if (ModelState.IsValid)
{
db.EmployeeClaims.Add(employeeClaim);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(employeeClaim);
}
// GET: EmployeeClaims/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
EmployeeClaim employeeClaim = db.EmployeeClaims.Find(id);
if (employeeClaim == null)
{
return HttpNotFound();
}
return View(employeeClaim);
}
// POST: EmployeeClaims/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,Amount,Date,Service")] EmployeeClaim employeeClaim)
{
if (ModelState.IsValid)
{
db.Entry(employeeClaim).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(employeeClaim);
}
// GET: EmployeeClaims/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
EmployeeClaim employeeClaim = db.EmployeeClaims.Find(id);
if (employeeClaim == null)
{
return HttpNotFound();
}
return View(employeeClaim);
}
// POST: EmployeeClaims/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
EmployeeClaim employeeClaim = db.EmployeeClaims.Find(id);
db.EmployeeClaims.Remove(employeeClaim);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CSDHRProject.Models;
using System.IO;
namespace CSDHRProject.Controllers
{
public class JobPostingsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: JobPostings
public ActionResult Index()
{
return View(db.JobPostings.ToList());
}
// GET: JobPostings/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
JobPosting jobPosting = db.JobPostings.Find(id);
if (jobPosting == null)
{
return HttpNotFound();
}
return View(jobPosting);
}
// GET: JobPostings/Create
public ActionResult Create()
{
return View();
}
// POST: JobPostings/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "JobPostingId,JobTitle,JobPostingDeadline,JobDepartmentName,JobPostingFileName")] JobPosting jobPosting)
{
if (ModelState.IsValid)
{
db.JobPostings.Add(jobPosting);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(jobPosting);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateJobPosting(JobEditViewModel jevm)
{
JobPosting jobPosting = jevm.Item;
if (ModelState.IsValid)
{
if(jevm.JobPostFile != null && jevm.JobPostFile.ContentLength > 0)
{
var jobFolder = "/Content/JobPostings/";
var filename = DateTime.Now.ToBinary().ToString("X") + Path.GetFileName(jevm.JobPostFile.FileName);
var path = Path.Combine(Server.MapPath("~" + jobFolder), filename);
jevm.JobPostFile.SaveAs(path);
jevm.Item.JobPostingFileName = jobFolder + filename;
}
db.JobPostings.Add(jobPosting);
db.SaveChanges();
return RedirectToAction("Index");
}
return RedirectToAction("Index");
}
// GET: JobPostings/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
JobPosting jobPosting = db.JobPostings.Find(id);
if (jobPosting == null)
{
return HttpNotFound();
}
return View(jobPosting);
}
// POST: JobPostings/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "JobPostingId,JobTitle,JobPostingDeadline,JobDepartmentName,JobPostingFileName")] JobPosting jobPosting)
{
if (ModelState.IsValid)
{
db.Entry(jobPosting).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(jobPosting);
}
// GET: JobPostings/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
JobPosting jobPosting = db.JobPostings.Find(id);
if (jobPosting == null)
{
return HttpNotFound();
}
return View(jobPosting);
}
// POST: JobPostings/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
JobPosting jobPosting = db.JobPostings.Find(id);
db.JobPostings.Remove(jobPosting);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace CSDHRProject.Models
{
public class PayrollModels
{
public int Id { get; set; }
[Display(Name="Name")]
public String Name { get; set; }
public int ManagerId { get; set; }
[Display(Name="Manager Name")]
public String ManagerName { get; set; }
[Display(Name="Pay Rate")]
public double PayRate { get; set; }
public String Position { get; set; }
public int Project { get; set; }
[Display(Name="Hours Worked")]
public int HoursWorked { get; set; }
[Display(Name="Project Name")]
public String ProjectName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[Display(Name="Date of Work")]
public DateTime? TimesheetDate { get; set; }
}
}<file_sep>using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.ComponentModel.DataAnnotations;
namespace CSDHRProject.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
//Custom User attributes
public bool manager { get; set; }
public bool role { get; set; }
public bool admin { get; set; }
[Display(Name = "First Name")]
public string firstname { get; set; }
[Display(Name = "Last Name")]
public string lastname { get; set; }
[Display(Name = "Sin")]
public string Sin { get; set; }
[Display(Name = "Bank Depost Account Number")]
public string BenefitNumber { get; set; }
[Display(Name = "Rate of Pay")]
public double RateOfPay { get; set; }
[Display(Name = "Vacation Days")]
public int VacationDays { get; set; }
[Display(Name = "Sick Days")]
public int SickDays { get; set; }
[Display(Name = "Benefit Certificate File")]
public string BenefitCertificateFileName { get; set; }
[Display(Name = "Training Certificate File")]
public string TrainingCertificateFileName { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public System.Data.Entity.DbSet<CSDHRProject.Models.RegisterViewModel> NewHireModels { get; set; }
public System.Data.Entity.DbSet<CSDHRProject.Models.JobPosting> JobPostings { get; set; }
public System.Data.Entity.DbSet<CSDHRProject.Models.JobApplication> JobApplications { get; set; }
public System.Data.Entity.DbSet<CSDHRProject.Models.Project> Projects { get; set; }
public System.Data.Entity.DbSet<CSDHRProject.Models.ProjectUser> ProjectUsers { get; set; }
public System.Data.Entity.DbSet<CSDHRProject.Models.PayrollModels> PayrollModels { get; set; }
public System.Data.Entity.DbSet<CSDHRProject.Models.BenefitRegistration> BenefitRegistrations { get; set; }
public System.Data.Entity.DbSet<CSDHRProject.Models.EmployeeClaim> EmployeeClaims { get; set; }
public System.Data.Entity.DbSet<CSDHRProject.Models.Address> Addresses { get; set; }
//Insert DbSet variables (Table Names!) here in the following format:
// public DbSet<%MODEL_NAME%> %TABLE_NAME% { get; set; }
//Example:
// public DbSet<Benefits> Benefits { get; set; }
//Once added here, you can update the database by opening the NuGet console
// (Tools > NuGet Package Manager > Package Manager Console)
//then running the following command:
// Update-Database
//This will create or modify all tables in the database
//If you insert a table, decide you do not want it anymore,
//and want to delete it, remove it from here and run:
// Update-Database -Force
//This will DELETE the table and ALL DATA within it.
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Drawing;
using CSDHRProject.Models;
namespace CSDHRProject.Controllers
{
public class NewHireController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: NewHire
public ActionResult Index()
{
return View(db.Users.ToList());
}
// GET: NewHire/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ApplicationUser user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(new NewHireEditViewModel { UserData = user });
}
// GET: NewHire/Create
public ActionResult Create()
{
return View();
}
// POST: NewHire/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Sin,BenefitNumber,RateOfPay,VacationDays,SickDays,BenefitCertificateFileName,TrainingCertificateFileName")] RegisterViewModel newHireModel)
{
if (ModelState.IsValid)
{
db.NewHireModels.Add(newHireModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(newHireModel);
}
// GET: NewHire/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ApplicationUser user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(new NewHireEditViewModel { UserData = user });
}
// POST: NewHire/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "UserData, BenefitFile, TrainingFile")] NewHireEditViewModel nhvm)
{
Console.Out.WriteLine("Received nhvm: " + nhvm.ToString());
if (ModelState.IsValid)
{
//user.
var fileFolder = "fileDocuments";
if (nhvm.BenefitFile != null && nhvm.BenefitFile.ContentLength > 0)
{
var BenefitFileName = DateTime.Now.ToBinary().ToString("X") + Path.GetFileName(nhvm.BenefitFile.FileName);
var path1 = Path.Combine(Server.MapPath("~"), fileFolder, BenefitFileName);
nhvm.BenefitFile.SaveAs(path1);
nhvm.UserData.BenefitCertificateFileName = "/" + fileFolder + "/" + BenefitFileName;
}
if (nhvm.TrainingFile != null && nhvm.TrainingFile.ContentLength > 0)
{
var TrainingFileName = DateTime.Now.ToBinary().ToString("X") + Path.GetFileName(nhvm.TrainingFile.FileName);
var path2 = Path.Combine(Server.MapPath("~"), fileFolder, TrainingFileName);
nhvm.TrainingFile.SaveAs(path2);
nhvm.UserData.TrainingCertificateFileName = "/" + fileFolder + "/" + TrainingFileName;
}
db.Entry(nhvm.UserData).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", new { id = nhvm.UserData.Id });
}
return View(nhvm);
}
// GET: NewHire/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
RegisterViewModel newHireModel = db.NewHireModels.Find(id);
if (newHireModel == null)
{
return HttpNotFound();
}
return View(newHireModel);
}
// POST: NewHire/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
RegisterViewModel newHireModel = db.NewHireModels.Find(id);
db.NewHireModels.Remove(newHireModel);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CSDHRProject.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
//var userId = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(User.Identity.GetUserId()).
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CSDHRProject.Models
{
public class EmployeeClaim
{
public int Id { get; set; }
public String Name { get; set; }
public virtual Address Address { get; set; }
public Double Amount { get; set; }
public DateTime Date { get; set; }
public String Service { get; set; }
public virtual ApplicationUser User { get; set; }
}
public class Address
{
public int Id { get; set; }
public String Street { get; set; }
public String City { get; set; }
public String Provence { get; set; }
public String Postal { get; set; }
}
public class BenefitRegistration
{
public virtual ApplicationUser User { get; set; }
public int Id { get; set; }
public Boolean RealtionshipStatus { get; set; }
public Boolean BenefitType { get; set; }
public Boolean Dental { get; set; }
public Boolean Optical { get; set; }
public Boolean Paramedical { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CSDHRProject.Models;
using System.Text;
namespace CSDHRProject.Controllers
{
public class PayrollController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
#region Index
// GET: PayrollModels
public ActionResult Index()
{
return View(db.PayrollModels.ToList());
}
#endregion
#region Details
// GET: PayrollModels/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PayrollModels payrollModels = db.PayrollModels.Find(id);
if (payrollModels == null)
{
return HttpNotFound();
}
return View(payrollModels);
}
#endregion
#region Create
// GET: PayrollModels/Create
public ActionResult Create()
{
return View();
}
// POST: PayrollModels/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,ManagerId,ManagerName,PayRate,Position")] PayrollModels payrollModels)
{
if (ModelState.IsValid)
{
db.PayrollModels.Add(payrollModels);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(payrollModels);
}
#endregion
#region Edit
// GET: PayrollModels/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PayrollModels payrollModels = db.PayrollModels.Find(id);
if (payrollModels == null)
{
return HttpNotFound();
}
return View(payrollModels);
}
// POST: PayrollModels/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,ManagerId,ManagerName,PayRate,Position")] PayrollModels payrollModels)
{
if (ModelState.IsValid)
{
db.Entry(payrollModels).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(payrollModels);
}
#endregion
#region Delete
// GET: PayrollModels/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PayrollModels payrollModels = db.PayrollModels.Find(id);
if (payrollModels == null)
{
return HttpNotFound();
}
return View(payrollModels);
}
// POST: PayrollModels/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
PayrollModels payrollModels = db.PayrollModels.Find(id);
db.PayrollModels.Remove(payrollModels);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region Instructions
// GET: PayrollModels/Instructions
public ActionResult Instructions(int? id)
{
PayrollModels payrollModels = db.PayrollModels.Find(id);
if (ModelState.IsValid)
{
db.Entry(payrollModels).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Instructions");
}
return View(payrollModels);
}
#endregion
#region TimesheetEntry
// GET: PayrollModels/TimesheetEntry
public ActionResult TimesheetEntry()
{
return View();
}
// POST: PayrollModels/TimesheetEntry
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult TimesheetEntry([Bind(Include = "Id,Name,ManagerId,ManagerName,PayRate,Position")] PayrollModels payrollModels)
{
if (ModelState.IsValid)
{
db.PayrollModels.Add(payrollModels);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(payrollModels);
}
public partial class DatePickerController : Controller
{
public ActionResult Index()
{
return View();
}
}
#endregion
#region Calendar
// GET: PayrollModels/Calendar
public ActionResult Calendar()
{
return View();
}
// POST: PayrollModels/Calendar
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Calendar([Bind(Include = "Id,Name,ManagerId,ManagerName,PayRate,Position")] PayrollModels payrollModels)
{
if (ModelState.IsValid)
{
db.PayrollModels.Add(payrollModels);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(payrollModels);
}
[ChildActionOnly]
public ActionResult Calendar2(
)
{
System.Web.UI.WebControls.Calendar cal = new System.Web.UI.WebControls.Calendar();
cal.ID = "MyCalendar";
cal.CssClass = "month-view";
cal.CssClass = "calendar";
cal.CellSpacing = 0;
cal.CellPadding = -1;
cal.BorderWidth = 0;
cal.ShowGridLines = true;
cal.ShowTitle = false;
cal.CellPadding = 50;
//cal.BorderStyle = Solid 2;
cal.TitleStyle.BackColor = System.Drawing.Color.LightSkyBlue;
cal.TitleStyle.ForeColor = System.Drawing.Color.White;
cal.DayStyle.BackColor = System.Drawing.Color.LightGray;
cal.ShowNextPrevMonth = true;
cal.DayNameFormat = System.Web.UI.WebControls.DayNameFormat.Full;
cal.DayRender += new System.Web.UI.WebControls.DayRenderEventHandler(CalendarDayRender);
StringBuilder sb = new StringBuilder();
using (System.IO.StringWriter sw = new System.IO.StringWriter(sb))
{
System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter(sw);
cal.RenderControl(writer);
}
String calHTML = sb.ToString();
return Content(calHTML);
}
private void CalendarDayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
e.Cell.Text = "";
if (e.Day.Date == System.DateTime.Today)
{
e.Cell.CssClass = "today";
e.Cell.BackColor = System.Drawing.Color.Gray;
System.Web.UI.HtmlControls.HtmlGenericControl h4 = new System.Web.UI.HtmlControls.HtmlGenericControl("h3");
h4.InnerHtml = HttpContext.GetGlobalResourceObject("JTG_DateTime", "JTK_Today") + " " + e.Day.DayNumberText;
e.Cell.Controls.Add(h4);
}
else
{
System.Web.UI.HtmlControls.HtmlGenericControl h4 = new System.Web.UI.HtmlControls.HtmlGenericControl("h4");
h4.InnerHtml = e.Day.DayNumberText;
e.Cell.Controls.Add(h4);
}
}
#endregion
#region EmployeeTimesheet
// GET: PayrollModels/EmployeeTimesheet
public ActionResult EmployeeTimesheet()
{
return View();
}
// POST: PayrollModels/EmployeeTimesheet
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EmployeeTimesheet([Bind(Include = "Id,Name,ManagerId,ManagerName,PayRate,Position")] PayrollModels payrollModels)
{
if (ModelState.IsValid)
{
db.PayrollModels.Add(payrollModels);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(payrollModels);
}
#endregion
#region ProjectTimesheet
// GET: PayrollModels/ProjectTimesheet
public ActionResult ProjectTimesheet()
{
return View();
}
// POST: PayrollModels/ProjectTimesheet
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ProjectTimesheet([Bind(Include = "Id,Name,ManagerId,ManagerName,PayRate,Position")] PayrollModels payrollModels)
{
if (ModelState.IsValid)
{
db.PayrollModels.Add(payrollModels);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(payrollModels);
}
#endregion
#region Reports
// GET: PayrollModels/Reports
public ActionResult Reports()
{
return View();
}
// POST: PayrollModels/Reports
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Reports([Bind(Include = "Id,Name,ManagerId,ManagerName,PayRate,Position")] PayrollModels payrollModels)
{
if (ModelState.IsValid)
{
db.PayrollModels.Add(payrollModels);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(payrollModels);
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CSDHRProject.Models
{
public class Project
{
public int Id { get; set; }
public String Title { get; set; }
public DateTime Date { get; set; }
public String Description { get; set; }
public virtual ApplicationUser Author { get; set; }
public virtual ApplicationUser Lead { get; set; }
}
public class ProjectUser
{
public int Id { get; set; }
public virtual ApplicationUser User{ get; set; }
public virtual Project Project { get; set; }
}
} | ee49dd2de7d4324d2a7ee4f863f1733f73e3cc63 | [
"Markdown",
"C#"
] | 14 | C# | chadnedin/CSD4354-HRProject | 597d9925609a4ae0fbaedf9d9ce1bef814bbeffd | 88263d5ebd53cf815cb28b08d72448f405b01d98 | |
refs/heads/master | <file_sep>package io.swagger.v3.jaxrs2.resources;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Map;
import java.util.UUID;
@OpenAPIDefinition
@Path("distances")
public interface Ticket2793Resource {
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses({
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = DistancesResponse.class)))
})
Response getDistances();
abstract class DistancesResponse implements Map<UUID, Map<RouteMetric, Integer>> { }
public static class RouteMetric {
public String foo;
}
}
<file_sep>package io.swagger.v3.jaxrs2.it.resources;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.List;
@Path("/cars")
@Tag(name = "cars")
@Produces("application/json")
@Consumes("application/json")
public class CarResource {
private static class View {
interface Summary {
}
interface Detail extends View.Summary {
}
interface Sale {
}
}
private static class Car {
@JsonView(View.Summary.class)
@JsonProperty("manufacture")
private String made = "Honda";
@JsonView({View.Summary.class, View.Detail.class})
private String model = "Accord Hybrid";
@JsonView({View.Detail.class})
@JsonProperty
private List<Tire> tires = Arrays.asList(new Tire());
@JsonView({View.Sale.class})
@JsonProperty
private int price = 40000;
// always in
private String color = "White";
public String getColor() {
return color;
}
}
private static class Tire {
@JsonView(View.Summary.class)
@JsonProperty("brand")
private String made = "Michelin";
@JsonView(View.Detail.class)
@JsonProperty
private String condition = "new";
}
@GET
@Path("/summary")
@JsonView({View.Summary.class})
@Operation(description = "Return car summaries",
responses = @ApiResponse(responseCode = "200", content = @Content(array = @ArraySchema(schema = @Schema(implementation = Car.class)))))
public Response getSummaries() {
return Response.ok(Arrays.asList(new Car())).build();
}
@GET
@Path("/detail")
@JsonView({View.Detail.class})
@Operation(description = "Return car detail",
responses = @ApiResponse(responseCode = "200", content = @Content(array = @ArraySchema(schema = @Schema(implementation = Car.class)))))
public List<Car> getDetails() {
return Arrays.asList(new Car());
}
@GET
@Path("/sale")
@JsonView({View.Summary.class, View.Sale.class})
public List<Car> getSaleSummaries() {
return Arrays.asList(new Car());
}
@GET
@Path("/all")
@Operation(description = "Return whole car",
responses = @ApiResponse(responseCode = "200", content = @Content(array = @ArraySchema(schema = @Schema(implementation = Car.class)))))
public List<Car> getAll() {
return Arrays.asList(new Car());
}
}<file_sep>package io.swagger.v3.jaxrs2.integration.resources;
import io.swagger.v3.core.filter.OpenAPISpecFilter;
import io.swagger.v3.core.filter.SpecFilter;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.core.util.Yaml;
import io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder;
import io.swagger.v3.oas.integration.api.OpenAPIConfiguration;
import io.swagger.v3.oas.integration.api.OpenApiContext;
import io.swagger.v3.oas.models.OpenAPI;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletConfig;
import javax.ws.rs.core.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.swagger.v3.jaxrs2.integration.ServletConfigContextUtils.getContextIdFromServletConfig;
public abstract class BaseOpenApiResource {
private static Logger LOGGER = LoggerFactory.getLogger(BaseOpenApiResource.class);
protected Response getOpenApi(HttpHeaders headers,
ServletConfig config,
Application app,
UriInfo uriInfo,
String type) throws Exception {
String ctxId = getContextIdFromServletConfig(config);
OpenApiContext ctx = new JaxrsOpenApiContextBuilder()
.servletConfig(config)
.application(app)
.resourcePackages(resourcePackages)
.configLocation(configLocation)
.openApiConfiguration(openApiConfiguration)
.ctxId(ctxId)
.buildContext(true);
OpenAPI oas = ctx.read();
boolean pretty = false;
if (ctx.getOpenApiConfiguration() != null && Boolean.TRUE.equals(ctx.getOpenApiConfiguration().isPrettyPrint())) {
pretty = true;
}
if (oas != null) {
if (ctx.getOpenApiConfiguration() != null && ctx.getOpenApiConfiguration().getFilterClass() != null) {
try {
OpenAPISpecFilter filterImpl = (OpenAPISpecFilter) Class.forName(ctx.getOpenApiConfiguration().getFilterClass()).newInstance();
SpecFilter f = new SpecFilter();
oas = f.filter(oas, filterImpl, getQueryParams(uriInfo.getQueryParameters()), getCookies(headers),
getHeaders(headers));
} catch (Exception e) {
LOGGER.error("failed to load filter", e);
}
}
}
if (oas == null) {
return Response.status(404).build();
}
if (StringUtils.isNotBlank(type) && type.trim().equalsIgnoreCase("yaml")) {
return Response.status(Response.Status.OK)
.entity(pretty ? Yaml.pretty(oas) : Yaml.mapper().writeValueAsString(oas))
.type("application/yaml")
.build();
} else {
return Response.status(Response.Status.OK)
.entity(pretty ? Json.pretty(oas) : Json.mapper().writeValueAsString(oas))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
}
private static Map<String, List<String>> getQueryParams(MultivaluedMap<String, String> params) {
Map<String, List<String>> output = new HashMap<String, List<String>>();
if (params != null) {
for (String key : params.keySet()) {
List<String> values = params.get(key);
output.put(key, values);
}
}
return output;
}
private static Map<String, String> getCookies(HttpHeaders headers) {
Map<String, String> output = new HashMap<String, String>();
if (headers != null) {
for (String key : headers.getCookies().keySet()) {
Cookie cookie = headers.getCookies().get(key);
output.put(key, cookie.getValue());
}
}
return output;
}
private static Map<String, List<String>> getHeaders(HttpHeaders headers) {
Map<String, List<String>> output = new HashMap<String, List<String>>();
if (headers != null) {
for (String key : headers.getRequestHeaders().keySet()) {
List<String> values = headers.getRequestHeaders().get(key);
output.put(key, values);
}
}
return output;
}
protected String configLocation;
public String getConfigLocation() {
return configLocation;
}
public void setConfigLocation(String configLocation) {
this.configLocation = configLocation;
}
public BaseOpenApiResource configLocation(String configLocation) {
setConfigLocation(configLocation);
return this;
}
protected Set<String> resourcePackages;
public Set<String> getResourcePackages() {
return resourcePackages;
}
public void setResourcePackages(Set<String> resourcePackages) {
this.resourcePackages = resourcePackages;
}
public BaseOpenApiResource resourcePackages(Set<String> resourcePackages) {
setResourcePackages(resourcePackages);
return this;
}
protected OpenAPIConfiguration openApiConfiguration;
public OpenAPIConfiguration getOpenApiConfiguration() {
return openApiConfiguration;
}
public void setOpenApiConfiguration(OpenAPIConfiguration openApiConfiguration) {
this.openApiConfiguration = openApiConfiguration;
}
public BaseOpenApiResource openApiConfiguration(OpenAPIConfiguration openApiConfiguration) {
setOpenApiConfiguration(openApiConfiguration);
return this;
}
}
<file_sep>package io.swagger.v3.jaxrs2.resources;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import javax.servlet.ServletConfig;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
@Path("/resource/{id}")
@Produces({"application/json", "application/xml"})
public class ResourceWithKnownInjections {
private Integer constructorParam;
@QueryParam("fieldParam")
private String fieldParam; // injection into a class field
@Parameter(hidden = true)
@QueryParam("hiddenParam")
private String hiddenParam;
// injection into a constructor parameter
public ResourceWithKnownInjections(@PathParam("id") Integer constructorParam,
@QueryParam("hiddenParam") @Parameter(hidden = true) String hiddenParam,
@Context ServletConfig context) {
this.constructorParam = constructorParam;
}
private ResourceWithKnownInjections(@PathParam("id") Integer constructorParam, @QueryParam("fakeParam") String
fakeParam) {
this.constructorParam = constructorParam;
}
@GET
@Operation
public String get(@QueryParam("methodParam") String methodParam) {
// injection into a resource method parameter
final StringBuilder sb = new StringBuilder();
sb.append("Constructor param: ").append(constructorParam).append("\n");
sb.append("Field param: ").append(fieldParam).append("\n");
sb.append("Method param: ").append(methodParam).append("\n");
return sb.toString();
}
}
<file_sep>## [Since I could not get any feedback, this is no longer supported]
This is an extended version for Swagger Core with the addition of many features for those who would like to directly build the OpenAPI object instead of letting Swagger handle things automatically. Some options should also be valid for those using the automatic way.
By directly manipulating the OpenAPI object and this version, you have lots of customization that the standard versions can only dream of. For example:
1. You can add addition models to your OpenAPI with OpenAPIBuilderToolbox.add(api, SomeClass.class).
2. If you only care about the documentation, not code generation and sometimes you want the Schema to have the fullname of the class (including package name), you can just set OpenAPIBuilderOptions.USE_FULLNAME to true.
3. For generic class like ClassA<T>, the generated API is sometimes ugly lile ClassAObject, and if you want to ignore that generic part to have only ClassA, you can just set OpenAPIBuilderOptions.OMIT_GENERIC to true.
4. For Enum, sometimes the default toString() and name() may differ, so if you want to ensure that name() is always used, you can just set OpenAPIBuilderOptions.USE_ENUMNAME to true.
5. For Enum, sometimes you have only 1 enum, but you have to use it lots of times, isn't it much better if we can declare it as a Schema and just put a reference for it instead of inlining all the time? You can achieve that easily by setting the OpenAPIBuilderOptions.RECYCLE_ENUM to true.
6. You know, you can specify parent with Schema(allOf = {...}), but then in the generated OpenAPI, all the properties from parent will be repeated again, which is a bit annoying. Therefore, how about we exclude all of those which have been declared in parent schema? Just set OpenAPIBuilderOptions.HIDE_PARENTS to true.
7. Last, but not least, sometimes, you do not want to use the default visibility, right? Normally, you want to also see the private fields, ignore setter and getter, but how can we do it in the old version? Use annotation? Oh my god, imagine that I have a bit more than 1000 classes in my project and you seriously expect me to put the damn annotations on all of them? Fat chance :V !!! Here, I expose the default object mapper in ObjectMapperFactory.defaultMapper and you can use it to control a lot more than you think.
Bonus: If you want to build the OpenAPI object directly, you can use Reflections to achieve much better results compared to letting Swagger do everything on its own.
<NAME>
A super handsome programmer who feels frustrated with Swagger Core's lack of functionalities :)
<file_sep>package io.swagger.v3.core.converting.override;
import com.fasterxml.jackson.databind.JavaType;
import io.swagger.v3.core.converter.AnnotatedType;
import io.swagger.v3.core.converter.ModelConverter;
import io.swagger.v3.core.converter.ModelConverterContext;
import io.swagger.v3.core.converter.ModelConverters;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.media.Schema;
import org.testng.annotations.Test;
import java.util.Iterator;
import static org.testng.Assert.*;
public class CustomConverterTest {
@Test(description = "it should ignore properties with type Bar")
public void testCustomConverter() {
// add the custom converter
final ModelConverters converters = new ModelConverters();
converters.addConverter(new CustomConverter());
final Schema model = converters.read(Foo.class).get("Foo");
assertNotNull(model);
assertEquals(model.getProperties().size(), 1);
final Schema barProperty = (Schema) model.getProperties().get("bar");
assertNull(barProperty);
final Schema titleProperty = (Schema) model.getProperties().get("title");
assertNotNull(titleProperty);
}
class CustomConverter implements ModelConverter {
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
final JavaType jType = Json.mapper().constructType(type.getType());
if (jType != null) {
final Class<?> cls = jType.getRawClass();
if (cls.equals(Bar.class)) {
return null;
} else {
return chain.next().resolve(type, context, chain);
}
} else {
return null;
}
}
}
class Foo {
public Bar bar = null;
public String title = null;
}
class Bar {
public String foo = null;
}
}
<file_sep>package io.swagger.v3.jaxrs2;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.core.converter.AnnotatedType;
import io.swagger.v3.core.converter.ModelConverter;
import io.swagger.v3.core.converter.ModelConverterContextImpl;
import io.swagger.v3.core.filter.AbstractSpecFilter;
import io.swagger.v3.core.filter.OpenAPISpecFilter;
import io.swagger.v3.core.filter.SpecFilter;
import io.swagger.v3.core.jackson.ModelResolver;
import io.swagger.v3.core.model.ApiDescription;
import io.swagger.v3.jaxrs2.matchers.SerializationMatchers;
import io.swagger.v3.jaxrs2.resources.BasicFieldsResource;
import io.swagger.v3.jaxrs2.resources.BookStoreTicket2646;
import io.swagger.v3.jaxrs2.resources.ClassPathParentResource;
import io.swagger.v3.jaxrs2.resources.ClassPathSubResource;
import io.swagger.v3.jaxrs2.resources.CompleteFieldsResource;
import io.swagger.v3.jaxrs2.resources.DeprecatedFieldsResource;
import io.swagger.v3.jaxrs2.resources.DuplicatedOperationIdResource;
import io.swagger.v3.jaxrs2.resources.DuplicatedOperationMethodNameResource;
import io.swagger.v3.jaxrs2.resources.DuplicatedSecurityResource;
import io.swagger.v3.jaxrs2.resources.EnhancedResponsesResource;
import io.swagger.v3.jaxrs2.resources.ExternalDocsReference;
import io.swagger.v3.jaxrs2.resources.MyClass;
import io.swagger.v3.jaxrs2.resources.MyOtherClass;
import io.swagger.v3.jaxrs2.resources.RefCallbackResource;
import io.swagger.v3.jaxrs2.resources.RefExamplesResource;
import io.swagger.v3.jaxrs2.resources.RefHeaderResource;
import io.swagger.v3.jaxrs2.resources.RefLinksResource;
import io.swagger.v3.jaxrs2.resources.RefParameterResource;
import io.swagger.v3.jaxrs2.resources.RefRequestBodyResource;
import io.swagger.v3.jaxrs2.resources.RefResponsesResource;
import io.swagger.v3.jaxrs2.resources.RefSecurityResource;
import io.swagger.v3.jaxrs2.resources.ResourceWithSubResource;
import io.swagger.v3.jaxrs2.resources.ResponseContentWithArrayResource;
import io.swagger.v3.jaxrs2.resources.ResponsesResource;
import io.swagger.v3.jaxrs2.resources.SecurityResource;
import io.swagger.v3.jaxrs2.resources.ServersResource;
import io.swagger.v3.jaxrs2.resources.SimpleCallbackResource;
import io.swagger.v3.jaxrs2.resources.SimpleExamplesResource;
import io.swagger.v3.jaxrs2.resources.SimpleMethods;
import io.swagger.v3.jaxrs2.resources.SimpleParameterResource;
import io.swagger.v3.jaxrs2.resources.SimpleRequestBodyResource;
import io.swagger.v3.jaxrs2.resources.SimpleResponsesResource;
import io.swagger.v3.jaxrs2.resources.SubResourceHead;
import io.swagger.v3.jaxrs2.resources.TagsResource;
import io.swagger.v3.jaxrs2.resources.Test2607;
import io.swagger.v3.jaxrs2.resources.TestResource;
import io.swagger.v3.jaxrs2.resources.Ticket2644ConcreteImplementation;
import io.swagger.v3.jaxrs2.resources.Ticket2763Resource;
import io.swagger.v3.jaxrs2.resources.Ticket2793Resource;
import io.swagger.v3.jaxrs2.resources.Ticket2794Resource;
import io.swagger.v3.jaxrs2.resources.Ticket2806Resource;
import io.swagger.v3.jaxrs2.resources.Ticket2818Resource;
import io.swagger.v3.jaxrs2.resources.Ticket2848Resource;
import io.swagger.v3.jaxrs2.resources.UserAnnotationResource;
import io.swagger.v3.jaxrs2.resources.extensions.ExtensionsResource;
import io.swagger.v3.jaxrs2.resources.extensions.OperationExtensionsResource;
import io.swagger.v3.jaxrs2.resources.extensions.ParameterExtensionsResource;
import io.swagger.v3.jaxrs2.resources.extensions.RequestBodyExtensionsResource;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.Paths;
import io.swagger.v3.oas.models.callbacks.Callback;
import io.swagger.v3.oas.models.examples.Example;
import io.swagger.v3.oas.models.headers.Header;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.links.Link;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.testng.annotations.Test;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
/**
* Test for the Reader Class
*/
public class ReaderTest {
private static final String EXAMPLE_TAG = "Example Tag";
private static final String SECOND_TAG = "Second Tag";
private static final String OPERATION_SUMMARY = "Operation Summary";
private static final String OPERATION_DESCRIPTION = "Operation Description";
private static final String CALLBACK_POST_OPERATION_DESCRIPTION = "payload data will be sent";
private static final String CALLBACK_GET_OPERATION_DESCRIPTION = "payload data will be received";
private static final String RESPONSE_CODE_200 = "200";
private static final String RESPONSE_DESCRIPTION = "voila!";
private static final String EXTERNAL_DOCS_DESCRIPTION = "External documentation description";
private static final String EXTERNAL_DOCS_URL = "http://url.com";
private static final String PARAMETER_IN = "path";
private static final String PARAMETER_NAME = "subscriptionId";
private static final String PARAMETER_DESCRIPTION = "parameter description";
private static final String CALLBACK_SUBSCRIPTION_ID = "subscription";
private static final String CALLBACK_URL = "http://$request.query.url";
private static final String SECURITY_KEY = "security_key";
private static final String SCOPE_VALUE1 = "write:pets";
private static final String SCOPE_VALUE2 = "read:pets";
private static final String PATH_REF = "/";
private static final String PATH_1_REF = "/1";
private static final String PATH_2_REF = "/path";
private static final String SCHEMA_TYPE = "string";
private static final String SCHEMA_FORMAT = "uuid";
private static final String SCHEMA_DESCRIPTION = "the generated UUID";
private static final int RESPONSES_NUMBER = 2;
private static final int TAG_NUMBER = 2;
private static final int SECURITY_SCHEMAS = 2;
private static final int PARAMETER_NUMBER = 1;
private static final int SECURITY_REQUIREMENT_NUMBER = 1;
private static final int SCOPE_NUMBER = 2;
private static final int PATHS_NUMBER = 1;
@Test(description = "test a simple resource class")
public void testSimpleReadClass() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(BasicFieldsResource.class);
Paths paths = openAPI.getPaths();
assertEquals(paths.size(), 6);
PathItem pathItem = paths.get(PATH_1_REF);
assertNotNull(pathItem);
assertNull(pathItem.getPost());
Operation operation = pathItem.getGet();
assertNotNull(operation);
assertEquals(OPERATION_SUMMARY, operation.getSummary());
assertEquals(OPERATION_DESCRIPTION, operation.getDescription());
}
@Test(description = "scan methods")
public void testCompleteReadClass() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(CompleteFieldsResource.class);
Paths paths = openAPI.getPaths();
assertEquals(PATHS_NUMBER, paths.size());
PathItem pathItem = paths.get(PATH_REF);
assertNotNull(pathItem);
assertNull(pathItem.getPost());
Operation operation = pathItem.getGet();
assertNotNull(operation);
assertEquals(OPERATION_SUMMARY, operation.getSummary());
assertEquals(OPERATION_DESCRIPTION, operation.getDescription());
assertEquals(TAG_NUMBER, operation.getTags().size());
assertEquals(EXAMPLE_TAG, operation.getTags().get(0));
assertEquals(SECOND_TAG, operation.getTags().get(1));
ExternalDocumentation externalDocs = operation.getExternalDocs();
assertEquals(EXTERNAL_DOCS_DESCRIPTION, externalDocs.getDescription());
assertEquals(EXTERNAL_DOCS_URL, externalDocs.getUrl());
}
@Test(description = "scan methods")
public void testScanMethods() {
Reader reader = new Reader(new OpenAPI());
Method[] methods = SimpleMethods.class.getMethods();
for (final Method method : methods) {
if (isValidRestPath(method)) {
Operation operation = reader.parseMethod(method, null, null);
assertNotNull(operation);
}
}
}
@Test(description = "Get a Summary and Description")
public void testGetSummaryAndDescription() {
Reader reader = new Reader(new OpenAPI());
Method[] methods = BasicFieldsResource.class.getMethods();
Operation operation = reader.parseMethod(methods[0], null, null);
assertNotNull(operation);
assertEquals(OPERATION_SUMMARY, operation.getSummary());
assertEquals(OPERATION_DESCRIPTION, operation.getDescription());
}
@Test(description = "Get a Duplicated Operation Id")
public void testResolveDuplicatedOperationId() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(DuplicatedOperationIdResource.class);
Paths paths = openAPI.getPaths();
assertNotNull(paths);
Operation firstOperation = paths.get(PATH_REF).getGet();
Operation secondOperation = paths.get(PATH_2_REF).getGet();
Operation thirdOperation = paths.get(PATH_REF).getPost();
assertNotNull(firstOperation);
assertNotNull(secondOperation);
assertNotNull(thirdOperation);
assertNotEquals(firstOperation.getOperationId(), secondOperation.getOperationId());
assertNotEquals(firstOperation.getOperationId(), thirdOperation.getOperationId());
assertNotEquals(secondOperation.getOperationId(), thirdOperation.getOperationId());
}
@Test(description = "Get a Duplicated Operation Id with same id as method name")
public void testResolveDuplicatedOperationIdMethodName() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(DuplicatedOperationMethodNameResource.class);
Paths paths = openAPI.getPaths();
assertNotNull(paths);
Operation firstOperation = paths.get("/1").getGet();
Operation secondOperation = paths.get("/2").getGet();
Operation secondPostOperation = paths.get("/2").getPost();
Operation thirdPostOperation = paths.get("/3").getPost();
assertNotNull(firstOperation);
assertNotNull(secondOperation);
assertNotNull(secondPostOperation);
assertNotNull(thirdPostOperation);
assertNotEquals(firstOperation.getOperationId(), secondOperation.getOperationId());
assertNotEquals(secondOperation.getOperationId(), secondPostOperation.getOperationId());
assertNotEquals(secondPostOperation.getOperationId(), thirdPostOperation.getOperationId());
Operation thirdOperation = paths.get("/3").getGet();
Operation fourthOperation = paths.get("/4").getGet();
assertNotNull(thirdOperation);
assertNotNull(fourthOperation);
assertNotEquals(thirdOperation.getOperationId(), fourthOperation.getOperationId());
}
@Test(description = "Test a Set of classes")
public void testSetOfClasses() {
Set<Class<?>> classes = new HashSet<>();
classes.add(SecurityResource.class);
classes.add(DuplicatedSecurityResource.class);
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(classes);
assertNotNull(openAPI);
assertEquals(openAPI.getPaths().get("/").getGet().getSecurity().size(), 2);
assertEquals(openAPI.getPaths().get("/2").getGet().getSecurity().size(), 3);
Components components = openAPI.getComponents();
assertNotNull(components);
Map<String, SecurityScheme> securitySchemes = components.getSecuritySchemes();
assertNotNull(securitySchemes);
assertEquals(SECURITY_SCHEMAS, securitySchemes.size());
}
@Test(description = "Deprecated Method")
public void testDeprecatedMethod() {
Reader reader = new Reader(new OpenAPI());
Method[] methods = DeprecatedFieldsResource.class.getMethods();
Operation deprecatedOperation = reader.parseMethod(methods[0], null, null);
assertNotNull(deprecatedOperation);
assertTrue(deprecatedOperation.getDeprecated());
}
@Test(description = "Get tags")
public void testGetTags() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(TagsResource.class);
Operation operation = openAPI.getPaths().get("/").getGet();
assertNotNull(operation);
assertEquals(6, operation.getTags().size());
assertEquals(operation.getTags().get(3), EXAMPLE_TAG);
assertEquals(operation.getTags().get(1), SECOND_TAG);
assertEquals(openAPI.getTags().get(1).getDescription(), "desc definition");
assertEquals(openAPI.getTags().get(2).getExternalDocs().getDescription(), "docs desc");
}
@Test(description = "Get servers")
public void testGetServers() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(ServersResource.class);
Operation operation = openAPI.getPaths().get("/").getGet();
assertNotNull(operation);
assertEquals(5, operation.getServers().size());
assertEquals(operation.getServers().get(0).getUrl(), "http://class1");
assertEquals(operation.getServers().get(1).getUrl(), "http://class2");
assertEquals(operation.getServers().get(2).getUrl(), "http://method1");
assertEquals(operation.getServers().get(3).getUrl(), "http://method2");
assertEquals(operation.getServers().get(4).getUrl(), "http://op1");
assertEquals(operation.getServers().get(0).getVariables().size(), 2);
assertEquals(operation.getServers().get(0).getVariables().get("var1").getDescription(), "var 1");
assertEquals(operation.getServers().get(0).getVariables().get("var1").getEnum().size(), 2);
assertEquals(openAPI.getServers().get(0).getDescription(), "definition server 1");
}
@Test(description = "Responses")
public void testGetResponses() {
Reader reader = new Reader(new OpenAPI());
Method[] methods = ResponsesResource.class.getMethods();
Operation responseOperation = reader.parseMethod(Arrays.stream(methods).filter(
(method -> method.getName().equals("getResponses"))).findFirst().get(), null, null);
assertNotNull(responseOperation);
ApiResponses responses = responseOperation.getResponses();
assertEquals(RESPONSES_NUMBER, responses.size());
ApiResponse apiResponse = responses.get(RESPONSE_CODE_200);
assertNotNull(apiResponse);
assertEquals(RESPONSE_DESCRIPTION, apiResponse.getDescription());
}
@Test(description = "More Responses")
public void testMoreResponses() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(EnhancedResponsesResource.class);
String yaml = "openapi: 3.0.1\n" +
"paths:\n" +
" /:\n" +
" get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs and a complex output\n" +
" object\n" +
" operationId: getWithPayloadResponse\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/SampleResponseSchema'\n" +
" 404:\n" +
" description: not found!\n" +
" 400:\n" +
" description: boo\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/GenericError'\n" +
" deprecated: true\n" +
"components:\n" +
" schemas:\n" +
" GenericError:\n" +
" type: object\n" +
" SampleResponseSchema:\n" +
" type: object\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
@Test(description = "Responses with composition")
public void testGetResponsesWithComposition() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(ResponsesResource.class);
String yaml = "openapi: 3.0.1\n" +
"paths:\n" +
" /:\n" +
" get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs and a complex output\n" +
" object\n" +
" operationId: getWithPayloadResponse\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/SampleResponseSchema'\n" +
" default:\n" +
" description: boo\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/GenericError'\n" +
" deprecated: true\n" +
" /allOf:\n" +
" get:\n" +
" summary: Test inheritance / polymorphism\n" +
" operationId: getAllOf\n" +
" parameters:\n" +
" - name: number\n" +
" in: query\n" +
" description: Test inheritance / polymorphism\n" +
" required: true\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" example: 1\n" +
" responses:\n" +
" 200:\n" +
" description: bean answer\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" type: string\n" +
" allOf:\n" +
" - $ref: '#/components/schemas/MultipleSub1Bean'\n" +
" - $ref: '#/components/schemas/MultipleSub2Bean'\n" +
" /anyOf:\n" +
" get:\n" +
" summary: Test inheritance / polymorphism\n" +
" operationId: getAnyOf\n" +
" parameters:\n" +
" - name: number\n" +
" in: query\n" +
" description: Test inheritance / polymorphism\n" +
" required: true\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" example: 1\n" +
" responses:\n" +
" 200:\n" +
" description: bean answer\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" type: string\n" +
" anyOf:\n" +
" - $ref: '#/components/schemas/MultipleSub1Bean'\n" +
" - $ref: '#/components/schemas/MultipleSub2Bean'\n" +
" /oneOf:\n" +
" get:\n" +
" summary: Test inheritance / polymorphism\n" +
" operationId: getOneOf\n" +
" parameters:\n" +
" - name: number\n" +
" in: query\n" +
" description: Test inheritance / polymorphism\n" +
" required: true\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" example: 1\n" +
" responses:\n" +
" 200:\n" +
" description: bean answer\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" type: string\n" +
" oneOf:\n" +
" - $ref: '#/components/schemas/MultipleSub1Bean'\n" +
" - $ref: '#/components/schemas/MultipleSub2Bean'\n" +
"components:\n" +
" schemas:\n" +
" MultipleSub2Bean:\n" +
" type: object\n" +
" properties:\n" +
" d:\n" +
" type: integer\n" +
" format: int32\n" +
" description: MultipleSub2Bean\n" +
" allOf:\n" +
" - $ref: '#/components/schemas/MultipleBaseBean'\n" +
" GenericError:\n" +
" type: object\n" +
" MultipleBaseBean:\n" +
" type: object\n" +
" properties:\n" +
" beanType:\n" +
" type: string\n" +
" a:\n" +
" type: integer\n" +
" format: int32\n" +
" b:\n" +
" type: string\n" +
" description: MultipleBaseBean\n" +
" MultipleSub1Bean:\n" +
" type: object\n" +
" properties:\n" +
" c:\n" +
" type: integer\n" +
" format: int32\n" +
" description: MultipleSub1Bean\n" +
" allOf:\n" +
" - $ref: '#/components/schemas/MultipleBaseBean'\n" +
" SampleResponseSchema:\n" +
" type: object";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
@Test(description = "External Docs")
public void testGetExternalDocs() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(ExternalDocsReference.class);
Operation externalDocsOperation = openAPI.getPaths().get("/").getGet();
ExternalDocumentation externalDocs = externalDocsOperation.getExternalDocs();
assertEquals(externalDocs.getDescription(), "External documentation description in method");
assertEquals(externalDocs.getUrl(), EXTERNAL_DOCS_URL);
externalDocs = openAPI.getComponents().getSchemas().get("ExternalDocsSchema").getExternalDocs();
assertEquals("External documentation description in schema", externalDocs.getDescription());
assertEquals(externalDocs.getUrl(), EXTERNAL_DOCS_URL);
}
@Test(description = "OperationExtensions Tests")
public void testOperationExtensions() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(OperationExtensionsResource.class);
assertNotNull(openAPI);
Map<String, Object> extensions = openAPI.getPaths().get("/").getGet().getExtensions();
assertEquals(extensions.size(), 2);
assertNotNull(extensions.get("x-operation"));
assertNotNull(extensions.get("x-operation-extensions"));
}
@Test(description = "ParameterExtensions Tests")
public void testParameterExtensions() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(ParameterExtensionsResource.class);
assertNotNull(openAPI);
Map<String, Object> extensions = openAPI.getPaths().get("/").getGet().getParameters().get(0).getExtensions();
assertNotNull(extensions);
assertEquals(1, extensions.size());
assertNotNull(extensions.get("x-parameter"));
}
@Test(description = "RequestBody Tests")
public void testRequestBodyExtensions() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(RequestBodyExtensionsResource.class);
assertNotNull(openAPI);
Map<String, Object> extensions = openAPI.getPaths().get("/user").getGet().
getRequestBody().getExtensions();
assertNotNull(extensions);
assertEquals(extensions.size(), 2);
assertNotNull(extensions.get("x-extension"));
assertNotNull(extensions.get("x-extension2"));
}
@Test(description = "Extensions Tests")
public void testExtensions() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(ExtensionsResource.class);
assertNotNull(openAPI);
SerializationMatchers.assertEqualsToYaml(openAPI, ExtensionsResource.YAML);
}
@Test(description = "Security Requirement")
public void testSecurityRequirement() {
Reader reader = new Reader(new OpenAPI());
Method[] methods = SecurityResource.class.getDeclaredMethods();
Operation securityOperation = reader.parseMethod(Arrays.stream(methods).filter(
(method -> method.getName().equals("getSecurity"))).findFirst().get(), null, null);
assertNotNull(securityOperation);
List<SecurityRequirement> securityRequirements = securityOperation.getSecurity();
assertNotNull(securityRequirements);
assertEquals(SECURITY_REQUIREMENT_NUMBER, securityRequirements.size());
List<String> scopes = securityRequirements.get(0).get(SECURITY_KEY);
assertNotNull(scopes);
assertEquals(SCOPE_NUMBER, scopes.size());
assertEquals(SCOPE_VALUE1, scopes.get(0));
assertEquals(SCOPE_VALUE2, scopes.get(1));
}
@Test(description = "Callbacks")
public void testGetCallbacks() {
Reader reader = new Reader(new OpenAPI());
Method[] methods = SimpleCallbackResource.class.getMethods();
Operation callbackOperation = reader.parseMethod(methods[0], null, null);
assertNotNull(callbackOperation);
Map<String, Callback> callbacks = callbackOperation.getCallbacks();
assertNotNull(callbacks);
Callback callback = callbacks.get(CALLBACK_SUBSCRIPTION_ID);
assertNotNull(callback);
PathItem pathItem = callback.get(CALLBACK_URL);
assertNotNull(pathItem);
Operation postOperation = pathItem.getPost();
assertNotNull(postOperation);
assertEquals(CALLBACK_POST_OPERATION_DESCRIPTION, postOperation.getDescription());
Operation getOperation = pathItem.getGet();
assertNotNull(getOperation);
assertEquals(CALLBACK_GET_OPERATION_DESCRIPTION, getOperation.getDescription());
Operation putOperation = pathItem.getPut();
assertNotNull(putOperation);
assertEquals(CALLBACK_POST_OPERATION_DESCRIPTION, putOperation.getDescription());
}
@Test(description = "Get the Param of an operation")
public void testSubscriptionIdParam() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(BasicFieldsResource.class);
assertNotNull(openAPI);
Paths openAPIPaths = openAPI.getPaths();
assertNotNull(openAPIPaths);
PathItem pathItem = openAPIPaths.get(PATH_1_REF);
assertNotNull(pathItem);
Operation operation = pathItem.getGet();
assertNotNull(operation);
List<Parameter> parameters = operation.getParameters();
assertNotNull(parameters);
assertEquals(PARAMETER_NUMBER, parameters.size());
Parameter parameter = parameters.get(0);
assertNotNull(parameter);
assertEquals(PARAMETER_IN, parameter.getIn());
assertEquals(PARAMETER_NAME, parameter.getName());
assertEquals(PARAMETER_DESCRIPTION, parameter.getDescription());
assertEquals(Boolean.TRUE, parameter.getRequired());
assertEquals(Boolean.TRUE, parameter.getAllowEmptyValue());
assertEquals(Boolean.TRUE, parameter.getAllowReserved());
Schema schema = parameter.getSchema();
assertNotNull(schema);
assertEquals(SCHEMA_TYPE, schema.getType());
assertEquals(SCHEMA_FORMAT, schema.getFormat());
assertEquals(SCHEMA_DESCRIPTION, schema.getDescription());
assertEquals(Boolean.TRUE, schema.getReadOnly());
}
private Boolean isValidRestPath(Method method) {
for (Class<? extends Annotation> item : Arrays.asList(GET.class, PUT.class, POST.class, DELETE.class,
OPTIONS.class, HEAD.class)) {
if (method.getAnnotation(item) != null) {
return true;
}
}
return false;
}
@Test
public void testClassWithGenericType() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(ClassWithGenericType.class);
assertNotNull(openAPI);
assertNotNull(openAPI.getComponents().getSchemas().get("IssueTemplateRet"));
assertNotNull(openAPI.getComponents().getSchemas().get("B"));
assertNotNull(openAPI.getComponents().getSchemas().get("B").getProperties().get("test"));
assertEquals(((Schema) openAPI.getComponents().getSchemas().get("B").getProperties().get("test")).get$ref(), "#/components/schemas/IssueTemplateRet");
//Yaml.prettyPrint(openAPI);
}
public static class A {
public B b;
}
public static class IssueTemplate<T> {
public T getTemplateTest() {
return null;
}
public String getTemplateTestString() {
return null;
}
}
public static class B {
public IssueTemplate<Ret> getTest() {
return null;
}
}
public static class Ret {
public String c;
}
static class ClassWithGenericType {
@Path("/test")
@Produces("application/json")
@Consumes("application/json")
@GET
@io.swagger.v3.oas.annotations.Operation(tags = "/receiver/rest")
//public void test1(@QueryParam("aa") String a) {
public void test1(A a) {
}
}
@Test(description = "test resource with array in response content")
public void test2497() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(ResponseContentWithArrayResource.class);
Paths paths = openAPI.getPaths();
assertEquals(paths.size(), 1);
PathItem pathItem = paths.get("/user");
assertNotNull(pathItem);
Operation operation = pathItem.getGet();
assertNotNull(operation);
ArraySchema schema = (ArraySchema) operation.getResponses().get("200").getContent().values().iterator().next().getSchema();
assertNotNull(schema);
assertEquals(schema.getItems().get$ref(), "#/components/schemas/User");
}
@Test(description = "test resource with subresources")
public void testResourceWithSubresources() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(ResourceWithSubResource.class);
Paths paths = openAPI.getPaths();
assertEquals(paths.size(), 3);
PathItem pathItem = paths.get("/employees/{id}");
assertNotNull(pathItem);
Operation operation = pathItem.getGet();
assertNotNull(operation);
ArraySchema arraySchema = (ArraySchema) operation.getResponses().get("200").getContent().values().iterator().next().getSchema();
assertNotNull(arraySchema);
assertEquals(arraySchema.getItems().get$ref(), "#/components/schemas/Pet");
pathItem = paths.get("/employees/{id}/{id}");
assertNotNull(pathItem);
operation = pathItem.getGet();
assertNotNull(operation);
Schema schema = operation.getResponses().get("200").getContent().values().iterator().next().getSchema();
assertNotNull(schema);
assertEquals(schema.get$ref(), "#/components/schemas/Pet");
pathItem = paths.get("/employees/noPath");
assertNotNull(pathItem);
operation = pathItem.getGet();
assertNotNull(operation);
schema = operation.getResponses().getDefault().getContent().values().iterator().next().getSchema();
assertNotNull(schema);
assertEquals(schema.getType(), "string");
}
@Test(description = "test another resource with subresources")
public void testAnotherResourceWithSubresources() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(TestResource.class);
Paths paths = openAPI.getPaths();
assertEquals(paths.size(), 3);
PathItem pathItem = paths.get("/test/status");
assertNotNull(pathItem);
Operation operation = pathItem.getGet();
assertNotNull(operation);
assertTrue(operation.getResponses().getDefault().getContent().keySet().contains("application/json"));
Schema schema = operation.getResponses().getDefault().getContent().values().iterator().next().getSchema();
assertNotNull(schema);
assertEquals(schema.getType(), "string");
pathItem = paths.get("/test/more/otherStatus");
assertNotNull(pathItem);
operation = pathItem.getGet();
assertNotNull(operation);
assertTrue(operation.getResponses().getDefault().getContent().keySet().contains("application/json"));
assertFalse(operation.getResponses().getDefault().getContent().keySet().contains("application/xml"));
schema = operation.getResponses().getDefault().getContent().values().iterator().next().getSchema();
assertNotNull(schema);
assertEquals(schema.getType(), "string");
pathItem = paths.get("/test/evenmore/otherStatus");
assertNotNull(pathItem);
operation = pathItem.getGet();
assertNotNull(operation);
assertTrue(operation.getResponses().getDefault().getContent().keySet().contains("application/json"));
assertFalse(operation.getResponses().getDefault().getContent().keySet().contains("application/xml"));
schema = operation.getResponses().getDefault().getContent().values().iterator().next().getSchema();
assertNotNull(schema);
assertEquals(schema.getType(), "string");
assertEquals(operation.getRequestBody().getContent().get("application/json").getSchema().get$ref(), "#/components/schemas/Pet");
}
@Test(description = "test user annotation")
public void testUserAnnotation() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(UserAnnotationResource.class);
Paths paths = openAPI.getPaths();
assertEquals(paths.size(), 1);
PathItem pathItem = paths.get("/test/status");
assertNotNull(pathItem);
Operation operation = pathItem.getGet();
assertNotNull(operation);
assertTrue(operation.getTags().contains("test"));
assertTrue(operation.getResponses().getDefault().getContent().keySet().contains("application/json"));
Schema schema = operation.getResponses().getDefault().getContent().values().iterator().next().getSchema();
assertNotNull(schema);
assertEquals(schema.getType(), "string");
}
@Test(description = "scan resource with class-based sub-resources")
public void testResourceWithClassBasedSubresources() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(SubResourceHead.class);
Paths paths = openAPI.getPaths();
assertEquals(paths.size(), 3);
PathItem pathItem = paths.get("/head/tail/hello");
assertNotNull(pathItem);
Operation operation = pathItem.getGet();
assertNotNull(operation);
assertTrue(operation.getResponses().getDefault().getContent().keySet().contains("*/*"));
Schema schema = operation.getResponses().getDefault().getContent().values().iterator().next().getSchema();
assertNotNull(schema);
assertEquals(schema.getType(), "string");
pathItem = paths.get("/head/tail/{string}");
assertNotNull(pathItem);
operation = pathItem.getGet();
assertNotNull(operation);
assertTrue(operation.getResponses().getDefault().getContent().keySet().contains("*/*"));
schema = operation.getResponses().getDefault().getContent().values().iterator().next().getSchema();
assertNotNull(schema);
assertEquals(schema.getType(), "string");
pathItem = paths.get("/head/noPath");
assertNotNull(pathItem);
operation = pathItem.getGet();
assertNotNull(operation);
assertTrue(operation.getResponses().getDefault().getContent().keySet().contains("*/*"));
schema = operation.getResponses().getDefault().getContent().values().iterator().next().getSchema();
assertNotNull(schema);
assertEquals(schema.getType(), "string");
}
@Test(description = "test ticket #2607 resource with subresources")
public void test2607() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(Test2607.class);
Paths paths = openAPI.getPaths();
assertEquals(paths.size(), 2);
PathItem pathItem = paths.get("/swaggertest/name");
assertNotNull(pathItem);
Operation operation = pathItem.getGet();
assertNotNull(operation);
assertTrue(operation.getResponses().getDefault().getContent().keySet().contains("text/plain"));
Schema schema = operation.getResponses().getDefault().getContent().values().iterator().next().getSchema();
assertNotNull(schema);
assertEquals(schema.getType(), "string");
pathItem = paths.get("/swaggertest/subresource/version");
assertNotNull(pathItem);
operation = pathItem.getGet();
assertNotNull(operation);
assertTrue(operation.getResponses().getDefault().getContent().keySet().contains("text/plain"));
schema = operation.getResponses().getDefault().getContent().values().iterator().next().getSchema();
assertNotNull(schema);
assertEquals(schema.getType(), "string");
}
@Test(description = "test ticket #2646 method annotated with @Produce")
public void test2646() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(BookStoreTicket2646.class);
Paths paths = openAPI.getPaths();
assertEquals(paths.size(), 2);
PathItem pathItem = paths.get("/bookstore");
assertNotNull(pathItem);
Operation operation = pathItem.getGet();
assertNotNull(operation);
assertTrue(operation.getResponses().getDefault().getContent().keySet().contains("application/json"));
pathItem = paths.get("/bookstore/{id}");
assertNotNull(pathItem);
operation = pathItem.getDelete();
assertNotNull(operation);
assertTrue(operation.getResponses().getDefault().getContent().keySet().contains("*/*"));
}
@Test(description = "test ticket #2644 annotated interface")
public void test2644() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(Ticket2644ConcreteImplementation.class);
Paths paths = openAPI.getPaths();
assertEquals(paths.size(), 1);
PathItem pathItem = paths.get("/resources");
assertNotNull(pathItem);
Operation operation = pathItem.getGet();
assertNotNull(operation);
assertTrue(operation.getResponses().getDefault().getContent().keySet().contains("*/*"));
}
@Test(description = "Scan subresource per #2632")
public void testSubResourceHasTheRightApiPath() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(ClassPathParentResource.class);
assertNotNull(openAPI);
assertNotNull(openAPI.getPaths().get("/v1/parent"));
assertNotNull(openAPI.getPaths().get("/v1/parent/{id}"));
assertEquals(openAPI.getPaths().size(), 2);
OpenAPI subResourceApi = new Reader(new OpenAPI()).read(ClassPathSubResource.class);
assertNotNull(subResourceApi);
assertNotNull(subResourceApi.getPaths().get("/subresource"));
assertNotNull(subResourceApi.getPaths().get("/subresource/{id}"));
assertEquals(subResourceApi.getPaths().size(), 2);
}
@Test(description = "Resolve Model with XML Properties starting with is prefix per #2635")
public void testModelResolverXMLPropertiesName() {
final MyClass myClass = new MyClass();
myClass.populate("isotonicDrink value", "softDrink value",
"isoDrink value", "isotonicDrinkOnlyXmlElement value");
Map<String, Schema> schemas = resolveJaxb(MyClass.class);
assertNull(schemas.get("MyClass").getProperties().get("isotonicDrink"));
assertNotNull(schemas.get("MyClass").getProperties().get("beerDrink"));
assertNotNull(schemas.get("MyClass").getProperties().get("saltDrink"));
// No JsonProperty or ApiModelProperty, keep original name
assertNull(schemas.get("MyClass").getProperties().get("beerDrinkXmlElement"));
assertNotNull(schemas.get("MyClass").getProperties().get("isotonicDrinkOnlyXmlElement"));
}
@Test(description = "Maintain Property names per #2635")
public void testMaintainPropertyNames() {
final MyOtherClass myOtherClass = new MyOtherClass();
myOtherClass.populate("myPropertyName value");
Map<String, Schema> schemas = resolveJaxb(MyOtherClass.class);
assertNotNull(schemas.get("MyOtherClass").getProperties().get("MyPrOperTyName"));
}
private Map<String, Schema> resolveJaxb(Type type) {
List<ModelConverter> converters = new CopyOnWriteArrayList<ModelConverter> ();
ObjectMapper mapper = JaxbObjectMapperFactory.getMapper();
converters.add(new ModelResolver(mapper));
ModelConverterContextImpl context = new ModelConverterContextImpl(
converters);
Schema resolve = context.resolve(new AnnotatedType().type(type));
Map<String, Schema> schemas = new HashMap<String, Schema>();
for (Map.Entry<String, Schema> entry : context.getDefinedModels()
.entrySet()) {
if (entry.getValue().equals(resolve)) {
schemas.put(entry.getKey(), entry.getValue());
}
}
return schemas;
}
@Test(description = "Responses with array schema")
public void testTicket2763() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(Ticket2763Resource.class);
String yaml = "openapi: 3.0.1\n" +
"paths:\n" +
" /array:\n" +
" get:\n" +
" operationId: getArrayResponses\n" +
" responses:\n" +
" default:\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" type: array\n" +
" items:\n" +
" $ref: https://openebench.bsc.es/monitor/tool/tool.json\n" +
" /schema:\n" +
" get:\n" +
" operationId: getSchemaResponses\n" +
" responses:\n" +
" default:\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: https://openebench.bsc.es/monitor/tool/tool.json";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
@Test(description = "array schema example")
public void testTicket2806() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(Ticket2806Resource.class);
String yaml = "openapi: 3.0.1\n" +
"paths:\n" +
" /test:\n" +
" get:\n" +
" operationId: getTest\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/Test'\n" +
"components:\n" +
" schemas:\n" +
" Test:\n" +
" type: object\n" +
" properties:\n" +
" stringArray:\n" +
" maxItems: 4\n" +
" minItems: 2\n" +
" uniqueItems: true\n" +
" type: array\n" +
" description: Array desc\n" +
" example:\n" +
" - aaa\n" +
" - bbb\n" +
" items:\n" +
" type: string\n" +
" description: Hello, World!\n" +
" example: Lorem ipsum dolor set\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
@Test(description = "NotNull parameters")
public void testTicket2794() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(Ticket2794Resource.class);
String yaml = "openapi: 3.0.1\n" +
"paths:\n" +
" /notnullparameter:\n" +
" get:\n" +
" operationId: getBooks\n" +
" parameters:\n" +
" - name: page\n" +
" in: query\n" +
" required: true\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" application/json: {}\n" +
" /notnullparameter/newnotnull:\n" +
" post:\n" +
" operationId: insertnotnull\n" +
" requestBody:\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/Book'\n" +
" required: true\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" '*/*': {}\n" +
" /notnullparameter/new_reqBody_required:\n" +
" post:\n" +
" operationId: insert\n" +
" requestBody:\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/Book'\n" +
" required: true\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" '*/*': {}\n" +
"components:\n" +
" schemas:\n" +
" Book:\n" +
" type: object\n" +
" properties:\n" +
" foo:\n" +
" type: string\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
/*
TODO: in a scenario like the one in ticket 2793, currently no NPE is thrown
but map is still not supported. When solved, update expected yaml in test case accordingly
*/
@Test(description = "no NPE resolving map")
public void testTicket2793() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(Ticket2793Resource.class);
String yaml = "openapi: 3.0.1\n" +
"paths:\n" +
" /distances:\n" +
" get:\n" +
" operationId: getDistances\n" +
" responses:\n" +
" 200:\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/DistancesResponse'\n" +
"components:\n" +
" schemas:\n" +
" DistancesResponse:\n" +
" type: object\n" +
" properties:\n" +
" empty:\n" +
" type: boolean\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
@Test(description = "test ticket #2818 @Parameter annotation")
public void test2818() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(Ticket2818Resource.class);
Paths paths = openAPI.getPaths();
assertEquals(paths.size(), 1);
PathItem pathItem = paths.get("/bookstore/{id}");
assertNotNull(pathItem);
Operation operation = pathItem.getGet();
assertNotNull(operation);
assertEquals(operation.getParameters().get(0).getSchema().getType(), "integer");
assertEquals(operation.getParameters().get(0).getSchema().getFormat(), "int32");
}
@Test(description = "Responses with ref")
public void testResponseWithRef() {
Components components = new Components();
components.addResponses("invalidJWT", new ApiResponse().description("when JWT token invalid/expired"));
OpenAPI oas = new OpenAPI()
.info(new Info().description("info"))
.components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(RefResponsesResource.class);
String yaml = "openapi: 3.0.1\n" +
"info:\n" +
" description: info\n" +
"paths:\n" +
" /:\n" +
" get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs and a complex output\n" +
" object\n" +
" operationId: getWithPayloadResponse\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/SampleResponseSchema'\n" +
" default:\n" +
" description: boo\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/GenericError'\n" +
" 401:\n" +
" $ref: '#/components/responses/invalidJWT'\n" +
" deprecated: true\n" +
"components:\n" +
" schemas:\n" +
" GenericError:\n" +
" type: object\n" +
" SampleResponseSchema:\n" +
" type: object\n" +
" responses:\n" +
" invalidJWT:\n" +
" description: when JWT token invalid/expired";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
@Test(description = "Responses with filter")
public void testResponseWithFilter() {
Components components = new Components();
components.addResponses("invalidJWT", new ApiResponse().description("when JWT token invalid/expired"));
OpenAPI oas = new OpenAPI()
.info(new Info().description("info"))
.components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(SimpleResponsesResource.class);
OpenAPISpecFilter filterImpl = new RefResponseFilter();
SpecFilter f = new SpecFilter();
openAPI = f.filter(openAPI, filterImpl, null, null, null);
String yaml = "openapi: 3.0.1\n" +
"info:\n" +
" description: info\n" +
"paths:\n" +
" /:\n" +
" get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs and a complex output\n" +
" object\n" +
" operationId: getWithPayloadResponse\n" +
" parameters: []\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/SampleResponseSchema'\n" +
" default:\n" +
" description: boo\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/GenericError'\n" +
" 401:\n" +
" $ref: '#/components/responses/invalidJWT'\n" +
" deprecated: true\n" +
"components:\n" +
" schemas:\n" +
" GenericError:\n" +
" type: object\n" +
" SampleResponseSchema:\n" +
" type: object\n" +
" responses:\n" +
" invalidJWT:\n" +
" description: when JWT token invalid/expired";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
class RefResponseFilter extends AbstractSpecFilter {
@Override
public Optional<Operation> filterOperation(Operation operation, ApiDescription api, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) {
if ("getWithPayloadResponse".equals(operation.getOperationId())) {
final ApiResponses apiResponses = (operation.getResponses() == null) ? new ApiResponses() : operation.getResponses();
apiResponses.addApiResponse("401", new ApiResponse().$ref("#/components/responses/invalidJWT"));
operation.setResponses(apiResponses);
return Optional.of(operation);
}
return super.filterOperation(operation, api, params, cookies, headers);
}
}
@Test(description = "array schema required property")
public void testTicket2848() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(Ticket2848Resource.class);
String yaml = "openapi: 3.0.1\n" +
"paths:\n" +
" /:\n" +
" get:\n" +
" operationId: getter\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/Town'\n" +
"components:\n" +
" schemas:\n" +
" Town:\n" +
" required:\n" +
" - streets\n" +
" type: object\n" +
" properties:\n" +
" streets:\n" +
" minItems: 1\n" +
" uniqueItems: true\n" +
" type: array\n" +
" items:\n" +
" type: string\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
@Test(description = "RequestBody with ref")
public void testRequestBodyWithRef() {
Components components = new Components();
components.addRequestBodies("User", new RequestBody().description("Test RequestBody"));
OpenAPI oas = new OpenAPI()
.info(new Info().description("info"))
.components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(RefRequestBodyResource.class);
String yaml = "openapi: 3.0.1\n" +
"info:\n" +
" description: info\n" +
"paths:\n" +
" /:\n" +
" get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with a payload complex input object\n" +
" operationId: sendPayload\n" +
" requestBody:\n" +
" $ref: '#/components/requestBodies/User'\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" '*/*': {}\n" +
" deprecated: true\n" +
"components:\n" +
" schemas:\n" +
" User:\n" +
" type: object\n" +
" properties:\n" +
" id:\n" +
" type: integer\n" +
" format: int64\n" +
" username:\n" +
" type: string\n" +
" firstName:\n" +
" type: string\n" +
" lastName:\n" +
" type: string\n" +
" email:\n" +
" type: string\n" +
" password:\n" +
" type: string\n" +
" phone:\n" +
" type: string\n" +
" userStatus:\n" +
" type: integer\n" +
" description: User Status\n" +
" format: int32\n" +
" xml:\n" +
" name: User\n" +
" requestBodies:\n" +
" User:\n" +
" description: Test RequestBody\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
@Test(description = "RequestBody with filter")
public void testRequestBodyWithFilter() {
Components components = new Components();
components.addRequestBodies("User", new RequestBody());
OpenAPI oas = new OpenAPI()
.info(new Info().description("info"))
.components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(SimpleRequestBodyResource.class);
OpenAPISpecFilter filterImpl = new RefRequestBodyFilter();
SpecFilter f = new SpecFilter();
openAPI = f.filter(openAPI, filterImpl, null, null, null);
String yaml = "openapi: 3.0.1\n" +
"info:\n" +
" description: info\n" +
"paths:\n" +
" /:\n" +
" get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with a payload complex input object\n" +
" operationId: sendPayload\n" +
" parameters: []\n" +
" requestBody:\n" +
" $ref: '#/components/requestBodies/User'\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" '*/*': {}\n" +
" deprecated: true\n" +
"components:\n" +
" schemas:\n" +
" User:\n" +
" type: object\n" +
" properties:\n" +
" id:\n" +
" type: integer\n" +
" format: int64\n" +
" username:\n" +
" type: string\n" +
" firstName:\n" +
" type: string\n" +
" lastName:\n" +
" type: string\n" +
" email:\n" +
" type: string\n" +
" password:\n" +
" type: string\n" +
" phone:\n" +
" type: string\n" +
" userStatus:\n" +
" type: integer\n" +
" description: User Status\n" +
" format: int32\n" +
" xml:\n" +
" name: User\n" +
" requestBodies:\n" +
" User: {}\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
class RefRequestBodyFilter extends AbstractSpecFilter {
@Override
public Optional<Operation> filterOperation(Operation operation, ApiDescription api, Map<String, List<String>> params,
Map<String, String> cookies, Map<String, List<String>> headers) {
if ("sendPayload".equals(operation.getOperationId())) {
final RequestBody requestBody = new RequestBody();
requestBody.set$ref("#/components/requestBodies/User");
operation.setRequestBody(requestBody);
return Optional.of(operation);
}
return super.filterOperation(operation, api, params, cookies, headers);
}
}
@Test(description = "Parameter with ref")
public void testParameterWithRef() {
Components components = new Components();
components.addParameters("id", new Parameter()
.description("Id Description")
.schema(new IntegerSchema())
.in(ParameterIn.QUERY.toString())
.example(1)
.required(true));
OpenAPI oas = new OpenAPI()
.info(new Info().description("info"))
.components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(RefParameterResource.class);
String yaml = "openapi: 3.0.1\n" +
"info:\n" +
" description: info\n" +
"paths:\n" +
" /:\n" +
" get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with a payload complex input object\n" +
" operationId: sendPayload\n" +
" parameters:\n" +
" - $ref: '#/components/parameters/id'\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" '*/*': {}\n" +
" deprecated: true\n" +
"components:\n" +
" parameters: \n" +
" id:\n" +
" in: query\n" +
" description: Id Description\n" +
" required: true\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" example: 1\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
@Test(description = "Responses with filter")
public void testParameterWithFilter() {
Components components = new Components();
components.addParameters("id", new Parameter()
.description("Id Description")
.schema(new IntegerSchema())
.in(ParameterIn.QUERY.toString())
.example(1)
.required(true));
OpenAPI oas = new OpenAPI()
.info(new Info().description("info"))
.components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(SimpleParameterResource.class);
OpenAPISpecFilter filterImpl = new RefParameterFilter();
SpecFilter f = new SpecFilter();
openAPI = f.filter(openAPI, filterImpl, null, null, null);
String yaml = "openapi: 3.0.1\n" +
"info:\n" +
" description: info\n" +
"paths:\n" +
" /:\n" +
" get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with a payload complex input object\n" +
" operationId: sendPayload\n" +
" parameters:\n" +
" - $ref: '#/components/parameters/id'\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" '*/*': {}\n" +
" deprecated: true\n" +
"components:\n" +
" parameters: \n" +
" id:\n" +
" in: query\n" +
" description: Id Description\n" +
" required: true\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" example: 1\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
class RefParameterFilter extends AbstractSpecFilter {
@Override
public Optional<Operation> filterOperation(Operation operation, ApiDescription api, Map<String, List<String>> params,
Map<String, String> cookies, Map<String, List<String>> headers) {
if ("sendPayload".equals(operation.getOperationId())) {
final Parameter parameter = new Parameter();
parameter.set$ref("#/components/parameters/id");
operation.getParameters().clear();
operation.addParametersItem(parameter);
return Optional.of(operation);
}
return super.filterOperation(operation, api, params, cookies, headers);
}
}
@Test(description = "Example with ref")
public void testExampleWithRef() {
Components components = new Components();
components.addExamples("Id", new Example().description("Id Example").summary("Id Example").value("1"));
OpenAPI oas = new OpenAPI()
.info(new Info().description("info"))
.components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(RefExamplesResource.class);
String yaml = "openapi: 3.0.1\n" +
"info:\n" +
" description: info\n" +
"paths:\n" +
" /example:\n" +
" post:\n" +
" description: subscribes a client to updates relevant to the requestor's account\n" +
" operationId: subscribe\n" +
" parameters:\n" +
" - name: subscriptionId\n" +
" in: path\n" +
" required: true\n" +
" style: simple\n" +
" schema:\n" +
" type: string\n" +
" description: Schema\n" +
" example: Subscription example\n" +
" examples:\n" +
" subscriptionId_1:\n" +
" summary: Subscription number 12345\n" +
" description: subscriptionId_1\n" +
" value: 12345\n" +
" externalValue: Subscription external value 1\n" +
" $ref: '#/components/examples/Id'\n" +
" example: example\n" +
" requestBody:\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/SubscriptionResponse'\n" +
"components:\n" +
" schemas:\n" +
" SubscriptionResponse:\n" +
" type: object\n" +
" properties:\n" +
" subscriptionId:\n" +
" type: string\n" +
" examples:\n" +
" Id:\n" +
" summary: Id Example\n" +
" description: Id Example\n" +
" value: \"1\"\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
@Test(description = "Example with Ref Filter")
public void testExampleWithFilter() {
Components components = new Components();
components.addExamples("Id", new Example().description("Id Example").summary("Id Example").value("1"));
OpenAPI oas = new OpenAPI()
.info(new Info().description("info"))
.components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(SimpleExamplesResource.class);
OpenAPISpecFilter filterImpl = new RefExampleFilter();
SpecFilter f = new SpecFilter();
openAPI = f.filter(openAPI, filterImpl, null, null, null);
String yaml = "openapi: 3.0.1\n" +
"info:\n" +
" description: info\n" +
"paths:\n" +
" /example:\n" +
" post:\n" +
" description: subscribes a client to updates relevant to the requestor's account\n" +
" operationId: subscribe\n" +
" parameters:\n" +
" - example:\n" +
" $ref: '#/components/examples/Id'\n" +
" requestBody:\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/SubscriptionResponse'\n" +
"components:\n" +
" schemas:\n" +
" SubscriptionResponse:\n" +
" type: object\n" +
" properties:\n" +
" subscriptionId:\n" +
" type: string\n" +
" examples:\n" +
" Id:\n" +
" summary: Id Example\n" +
" description: Id Example\n" +
" value: \"1\"\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
class RefExampleFilter extends AbstractSpecFilter {
@Override
public Optional<Operation> filterOperation(Operation operation, ApiDescription api, Map<String, List<String>> params,
Map<String, String> cookies, Map<String, List<String>> headers) {
if ("subscribe".equals(operation.getOperationId())) {
final Parameter parameter = new Parameter();
parameter.setExample(new Example().$ref("#/components/examples/Id"));
operation.getParameters().clear();
operation.addParametersItem(parameter);
return Optional.of(operation);
}
return super.filterOperation(operation, api, params, cookies, headers);
}
}
@Test(description = "Header with Ref")
public void testHeaderWithRef() {
Components components = new Components();
components.addHeaders("Header", new Header().description("Header Description"));
OpenAPI oas = new OpenAPI()
.info(new Info().description("info"))
.components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(RefHeaderResource.class);
String yaml = "openapi: 3.0.1\n" +
"info:\n" +
" description: info\n" +
"paths:\n" +
" /path:\n" +
" get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs and a complex output\n" +
" operationId: getWithPayloadResponse\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" headers:\n" +
" Rate-Limit-Limit:\n" +
" description: The number of allowed requests in the current period\n" +
" $ref: '#/components/headers/Header'\n" +
" style: simple\n" +
" schema:\n" +
" type: integer\n" +
" deprecated: true\n" +
"components:\n" +
" headers:\n" +
" Header:\n" +
" description: Header Description\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
@Test(description = "SecurityScheme with REf")
public void testSecuritySchemeWithRef() {
Components components = new Components();
components.addSecuritySchemes("Security", new SecurityScheme().description("Security Example").
name("Security").type(SecurityScheme.Type.OAUTH2).$ref("myOauth2Security").in(SecurityScheme.In.HEADER));
OpenAPI oas = new OpenAPI()
.info(new Info().description("info"))
.components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(RefSecurityResource.class);
String yaml = "openapi: 3.0.1\n" +
"info:\n" +
" description: info\n" +
"paths:\n" +
" /:\n" +
" get:\n" +
" description: description\n" +
" operationId: Operation Id\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" '*/*': {}\n" +
" security:\n" +
" - security_key:\n" +
" - write:pets\n" +
" - read:pets\n" +
"components:\n" +
" securitySchemes:\n" +
" Security:\n" +
" type: oauth2\n" +
" description: Security Example\n" +
" myOauth2Security:\n" +
" type: oauth2\n" +
" description: myOauthSecurity Description\n" +
" $ref: '#/components/securitySchemes/Security'\n" +
" in: header\n" +
" flows:\n" +
" implicit:\n" +
" authorizationUrl: http://x.com\n" +
" scopes:\n" +
" write:pets: modify pets in your account\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
@Test(description = "Link with Ref")
public void testLinkWithRef() {
Components components = new Components();
components.addLinks("Link", new Link().description("Link Description").operationId("id"));
OpenAPI oas = new OpenAPI()
.info(new Info().description("info"))
.components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(RefLinksResource.class);
String yaml = "openapi: 3.0.1\n" +
"info:\n" +
" description: info\n" +
"paths:\n" +
" /links:\n" +
" get:\n" +
" operationId: getUserWithAddress\n" +
" parameters:\n" +
" - name: userId\n" +
" in: query\n" +
" schema:\n" +
" type: string\n" +
" responses:\n" +
" default:\n" +
" description: test description\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" links:\n" +
" address:\n" +
" operationId: getAddress\n" +
" parameters:\n" +
" userId: $request.query.userId\n" +
" $ref: '#/components/links/Link'\n" +
"components:\n" +
" links:\n" +
" Link:\n" +
" operationId: id\n" +
" description: Link Description\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
@Test(description = "Callback with Ref")
public void testCallbackWithRef() {
Components components = new Components();
components.addCallbacks("Callback", new Callback().addPathItem("/post", new PathItem().description("Post Path Item")));
OpenAPI oas = new OpenAPI()
.info(new Info().description("info"))
.components(components);
Reader reader = new Reader(oas);
OpenAPI openAPI = reader.read(RefCallbackResource.class);
String yaml = "openapi: 3.0.1\n" +
"info:\n" +
" description: info\n" +
"paths:\n" +
" /simplecallback:\n" +
" get:\n" +
" summary: Simple get operation\n" +
" operationId: getWithNoParameters\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" callbacks:\n" +
" testCallback1:\n" +
" $ref: '#/components/callbacks/Callback'\n" +
"components:\n" +
" callbacks:\n" +
" Callback:\n" +
" /post:\n" +
" description: Post Path Item\n";
SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
}<file_sep>package io.swagger.v3.core.deserialization.properties;
import io.swagger.v3.core.util.Yaml;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MediaType;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.responses.ApiResponse;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class ArrayPropertyDeserializerTest {
private static final String yaml =
" operationId: something\n" +
" responses:\n" +
" 200:\n" +
" content:\n" +
" '*/*':\n" +
" examples:\n" +
" simple:\n" +
" value: Array example\n" +
" more:\n" +
" value: with two items\n" +
" description: OK\n" +
" schema:\n" +
" type: array\n" +
" minItems: 3\n" +
" maxItems: 100\n" +
" items:\n" +
" type: string\n";
@Test(description = "it should includes the example in the arrayproperty")
public void testArrayDeserialization() throws Exception {
Operation operation = Yaml.mapper().readValue(yaml, Operation.class);
ApiResponse response = operation.getResponses().get("200");
assertNotNull(response);
MediaType media = response.getContent().get("*/*");
Schema responseSchema = media.getSchema();
assertTrue(media.getExamples().size() == 2);
assertNotNull(responseSchema);
assertTrue(responseSchema instanceof ArraySchema);
ArraySchema mp = (ArraySchema) responseSchema;
assertEquals(mp.getMinItems(), new Integer(3));
assertEquals(mp.getMaxItems(), new Integer(100));
}
}<file_sep>package io.swagger.v3.core.serialization;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.core.converter.ModelConverters;
import io.swagger.v3.core.matchers.SerializationMatchers;
import io.swagger.v3.core.oas.models.Car;
import io.swagger.v3.core.oas.models.Manufacturers;
import io.swagger.v3.core.oas.models.ReadOnlyModel;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.media.*;
import org.testng.annotations.Test;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.testng.Assert.*;
public class ModelSerializerTest {
private final ObjectMapper m = Json.mapper();
@Test(description = "it should convert a model")
public void convertModel() throws JsonProcessingException {
final Schema pet = new Schema();
final Map<String, Schema> props = new LinkedHashMap<String, Schema>();
props.put("intValue", new IntegerSchema());
props.put("longValue", new IntegerSchema().format("int64"));
props.put("dateValue", new DateSchema());
props.put("dateTimeValue", new DateTimeSchema());
pet.setProperties(props);
pet.setRequired(Arrays.asList("intValue", "name"));
final String json = "{\n" +
" \"required\":[\n" +
" \"intValue\"\n" +
" ],\n" +
" \"properties\":{\n" +
" \"intValue\":{\n" +
" \"type\":\"integer\",\n" +
" \"format\":\"int32\"\n" +
" },\n" +
" \"longValue\":{\n" +
" \"type\":\"integer\",\n" +
" \"format\":\"int64\"\n" +
" },\n" +
" \"dateValue\":{\n" +
" \"type\":\"string\",\n" +
" \"format\":\"date\"\n" +
" },\n" +
" \"dateTimeValue\":{\n" +
" \"type\":\"string\",\n" +
" \"format\":\"date-time\"\n" +
" }\n" +
" }\n" +
"}";
SerializationMatchers.assertEqualsToJson(pet, json);
}
@Test(description = "it should deserialize a model")
public void deserializeModel() throws IOException {
final String json =
"{\n" +
" \"required\":[\n" +
" \"intValue\"\n" +
" ],\n" +
" \"type\":\"object\",\n" +
" \"properties\":{\n" +
" \"dateValue\":{\n" +
" \"type\":\"string\",\n" +
" \"format\":\"date\"\n" +
" },\n" +
" \"longValue\":{\n" +
" \"type\":\"integer\",\n" +
" \"format\":\"int64\"\n" +
" },\n" +
" \"dateTimeValue\":{\n" +
" \"type\":\"string\",\n" +
" \"format\":\"date-time\"\n" +
" },\n" +
" \"intValue\":{\n" +
" \"type\":\"integer\",\n" +
" \"format\":\"int32\"\n" +
" },\n" +
" \"byteArrayValue\":{\n" +
" \"type\":\"string\",\n" +
" \"format\":\"binary\"\n" +
" }\n" +
" }\n" +
"}";
final Schema p = m.readValue(json, Schema.class);
SerializationMatchers.assertEqualsToJson(p, json);
}
@Test(description = "it should serialize an array model")
public void serializeArrayModel() throws IOException {
final ArraySchema model = new ArraySchema();
model.setItems(new Schema().$ref("Pet"));
assertEquals(m.writeValueAsString(model), "{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Pet\"}}");
}
@Test(description = "it should deserialize an array model")
public void deserializeArrayModel() throws IOException {
final String json = "{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/Pet\"}}";
final Schema p = m.readValue(json, Schema.class);
assertTrue(p instanceof ArraySchema);
assertEquals(m.writeValueAsString(p), json);
}
@Test(description = "it should not create an xml object for $ref")
public void shouldNotCreateXmlObjectForRef() throws IOException {
final Schema model = new Schema().$ref("Monster");
model.setDescription("oops");
model.setExternalDocs(new ExternalDocumentation()
.description("external docs")
.url("http://swagger.io"));
assertEquals(Json.mapper().writeValueAsString(model), "{\"$ref\":\"#/components/schemas/Monster\"}");
}
@Test(description = "it should make a field readOnly by annotation")
public void makeFieldReadOnly() throws IOException {
final Map<String, Schema> schemas = ModelConverters.getInstance().read(Car.class);
final String json =
"{\n" +
" \"Car\":{\n" +
" \"type\":\"object\",\n" +
" \"properties\":{\n" +
" \"wheelCount\":{\n" +
" \"type\":\"integer\",\n" +
" \"format\":\"int32\",\n" +
" \"readOnly\":true\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
SerializationMatchers.assertEqualsToJson(schemas, json);
}
@Test(description = "it should serialize a model with a Set")
public void serializeModelWithSet() throws IOException {
final Map<String, Schema> schemas = ModelConverters.getInstance().read(Manufacturers.class);
final String json = "{\n" +
" \"Manufacturers\":{\n" +
" \"type\":\"object\",\n" +
" \"properties\":{\n" +
" \"countries\":{\n" +
" \"type\":\"array\",\n" +
" \"uniqueItems\":true,\n" +
" \"items\":{\n" +
" \"type\":\"string\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
SerializationMatchers.assertEqualsToJson(schemas, json);
}
@Test(description = "it should deserialize a model with object example")
public void deserializeModelWithObjectExample() throws IOException {
final String json = "{\n" +
" \"title\":\"Error\",\n" +
" \"type\":\"object\",\n" +
" \"properties\":{\n" +
" \"code\":{\n" +
" \"type\":\"integer\",\n" +
" \"format\":\"int32\"\n" +
" },\n" +
" \"message\":{\n" +
" \"type\":\"string\"\n" +
" },\n" +
" \"fields\":{\n" +
" \"type\":\"string\"\n" +
" }\n" +
" },\n" +
" \"example\":{\n" +
" \"code\":1,\n" +
" \"message\":\"hello\",\n" +
" \"fields\":\"abc\"\n" +
" }\n" +
"}";
final Schema model = Json.mapper().readValue(json, Schema.class);
assertEquals(Json.mapper().writeValueAsString(model.getExample()), "{\"code\":1,\"message\":\"hello\",\"fields\":\"abc\"}");
}
@Test(description = "it should deserialize a model with read-only property")
public void deserializeModelWithReadOnlyProperty() throws IOException {
final String json = "{\n" +
" \"properties\":{\n" +
" \"id\":{\n" +
" \"type\":\"integer\",\n" +
" \"format\":\"int32\",\n" +
" \"readOnly\":true\n" +
" }\n" +
" }\n" +
"}";
final Schema model = Json.mapper().readValue(json, Schema.class);
Schema property = (Schema) model.getProperties().get("id");
assertTrue(property.getReadOnly());
}
@Test(description = "it should generate a JSON with read-only from pojo, #1161")
public void readOnlyJsonGeneration() throws IOException {
Map<String, Schema> models = ModelConverters.getInstance().read(ReadOnlyModel.class);
Schema model = models.get("ReadOnlyModel");
Schema id = (Schema) model.getProperties().get("id");
assertTrue(id.getReadOnly());
Schema readWriteId = (Schema) model.getProperties().get("readWriteId");
assertNull(readWriteId.getReadOnly());
}
@Test(description = "it should generate an integer field with enum")
public void integerEnumGeneration() throws IOException {
final String json = "{\n" +
" \"properties\":{\n" +
" \"id\":{\n" +
" \"description\":\"fun!\",\n" +
" \"type\":\"integer\",\n" +
" \"format\":\"int32\",\n" +
" \"readOnly\":true,\n" +
" \"enum\": [ 0, 1]\n" +
" }\n" +
" }\n" +
"}";
final Schema model = Json.mapper().readValue(json, Schema.class);
IntegerSchema p = (IntegerSchema) model.getProperties().get("id");
assertNotNull(p.getEnum());
assertEquals(p.getEnum().get(0), new Integer(0));
assertEquals(p.getEnum().get(1), new Integer(1));
}
@Test(description = "it retains enums per ")
public void testEnumParser() throws IOException {
String json = "{\n" +
" \"properties\": {\n" +
" \"AdvStateType\": {\n" +
" \"description\": \"Advertising State\",\n" +
" \"enum\": [\n" +
" \"off\",\n" +
" \"on\"\n" +
" ],\n" +
" \"type\": \"string\"\n" +
" }\n" +
" }\n" +
"}";
final Schema model = Json.mapper().readValue(json, Schema.class);
StringSchema p = (StringSchema) model.getProperties().get("AdvStateType");
assertNotNull(p.getEnum());
assertEquals(p.getEnum().get(0), "off");
assertEquals(p.getEnum().get(1), "on");
}
@Test
public void testPrimitiveModel() throws Exception {
String json = "{\n" +
" \"type\": \"string\",\n" +
" \"enum\": [\n" +
" \"a\",\n" +
" \"b\",\n" +
" \"c\"\n" +
" ]\n" +
"}";
final Schema model = Json.mapper().readValue(json, Schema.class);
assertNotNull(model.getEnum());
assertTrue(model.getEnum().size() == 3);
}
@Test
public void testIssue1852() throws Exception {
String json = "{\n" +
" \"type\": \"integer\",\n" +
" \"minimum\": 10,\n" +
" \"maximum\": 20,\n" +
" \"default\": 15\n" +
"}";
final Schema model = Json.mapper().readValue(json, Schema.class);
assertEquals(model.getMinimum().intValue(), 10);
assertEquals(model.getMaximum().intValue(), 20);
assertEquals(model.getDefault(), 15);
}
@Test
public void testIssue2064Neg() throws Exception {
String json =
"{\n" +
" \"type\": \"string\",\n" +
" \"uniqueItems\": false\n" +
"}";
final Schema model = Json.mapper().readValue(json, Schema.class);
assertFalse(model.getUniqueItems());
}
@Test
public void testIssue2064() throws Exception {
String json =
"{\n" +
" \"type\": \"string\",\n" +
" \"uniqueItems\": true\n" +
"}";
final Schema model = Json.mapper().readValue(json, Schema.class);
assertTrue(model.getUniqueItems());
}
@Test
public void testIssue2064Ip() throws Exception {
String json =
"{\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"id\": {\n" +
" \"type\": \"integer\",\n" +
" \"format\": \"int32\",\n" +
" \"multipleOf\": 3.0\n" +
" }\n" +
" }\n" +
"}";
final Schema model = Json.mapper().readValue(json, Schema.class);
IntegerSchema ip = (IntegerSchema) model.getProperties().get("id");
assertEquals(ip.getMultipleOf(), new BigDecimal("3.0"));
}
}<file_sep>package io.swagger.v3.core.resolving;
import com.google.common.base.Functions;
import com.google.common.collect.Collections2;
import io.swagger.v3.core.converter.AnnotatedType;
import io.swagger.v3.core.converter.ModelConverterContextImpl;
import io.swagger.v3.core.jackson.ModelResolver;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import static org.testng.Assert.*;
public class EnumTest extends SwaggerTestBase {
@Test
public void testEnum() throws Exception {
final ModelResolver modelResolver = new ModelResolver(mapper());
final ModelConverterContextImpl context = new ModelConverterContextImpl(modelResolver);
final Schema model = context.resolve((new AnnotatedType().type(Currency.class)));
assertNotNull(model);
assertTrue(model instanceof StringSchema);
final StringSchema strModel = (StringSchema) model;
assertNotNull(strModel.getEnum());
final Collection<String> modelValues =
new ArrayList<String>(Collections2.transform(Arrays.asList(Currency.values()), Functions.toStringFunction()));
assertEquals(strModel.getEnum(), modelValues);
final Schema property = context.resolve(new AnnotatedType().type(Currency.class).schemaProperty(true));
assertNotNull(property);
assertTrue(property instanceof StringSchema);
final StringSchema strProperty = (StringSchema) property;
assertNotNull(strProperty.getEnum());
final Collection<String> values =
new ArrayList<String>(Collections2.transform(Arrays.asList(Currency.values()), Functions.toStringFunction()));
assertEquals(strProperty.getEnum(), values);
}
public enum Currency {
USA, CANADA
}
}
<file_sep>package io.swagger.v3.core.util;
import io.swagger.v3.core.converter.AnnotatedType;
import io.swagger.v3.core.converter.ModelConverters;
import io.swagger.v3.core.converter.ResolvedSchema;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema;
import java.lang.reflect.Type;
import java.util.Map;
public class OpenAPIBuilderToolbox {
// add additional model and its respective dependencies to OpenAPI
public static void addModel(OpenAPI api, Type type) {
if (api.getComponents() == null) {
api.components(new Components());
}
ResolvedSchema resolvedSchema = ModelConverters.getInstance()
.resolveAsResolvedSchema(
new AnnotatedType(type).resolveAsRef(true)
);
if (resolvedSchema.schema != null) {
Map<String, Schema> schemaMap = resolvedSchema.referencedSchemas;
if (schemaMap != null) {
schemaMap.forEach((key, schema) -> api.getComponents().addSchemas(key, schema));
}
}
}
}
<file_sep>/**
* Copyright 2017 SmartBear Software
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.swagger.v3.oas.annotations.security;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.extensions.Extension;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
/**
* The annotation may be used at class level (also on multiple classes) to add securitySchemes to spec
* components section.
*
* @see <a target="_new" href="https://github.com/OAI/OpenAPI-Specification/blob/3.0.1/versions/3.0.1.md#securitySchemeObject">Security Scheme (OpenAPI specification)</a>
* @see <a target="_new" href="https://github.com/OAI/OpenAPI-Specification/blob/3.0.1/versions/3.0.1.md#componentsObject">Components (OpenAPI specification)</a>
**/
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(SecuritySchemes.class)
@Inherited
public @interface SecurityScheme {
/**
* The type of the security scheme. Valid values are "apiKey", "http", "oauth2", "openIdConnect".
*
* @return String type
**/
SecuritySchemeType type();
/**
* The name identifying this security scheme
*
* @return String name
**/
String name() default "";
/**
* A short description for security scheme. CommonMark syntax can be used for rich text representation.
*
* @return String description
**/
String description() default "";
/**
* The name of the header or query parameter to be used. Applies to apiKey type.
* Maps to "name" property of <a target="_new" href="https://github.com/OAI/OpenAPI-Specification/blob/3.0.1/versions/3.0.1.md#securitySchemeObject">Security Scheme (OpenAPI specification)</a>
*
* @return String paramName
**/
String paramName() default "";
/**
* The location of the API key. Valid values are "query" or "header". Applies to apiKey type.
*
* @return String in
**/
SecuritySchemeIn in() default SecuritySchemeIn.DEFAULT;
/**
* The name of the HTTP Authorization scheme to be used in the Authorization header as defined in RFC 7235. Applies to http type.
*
* @return String scheme
**/
String scheme() default "";
/**
* A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an
* authorization server, so this information is primarily for documentation purposes. Applies to http ("bearer") type.
*
* @return String bearerFormat
**/
String bearerFormat() default "";
/**
* Required. An object containing configuration information for the flow types supported. Applies to oauth2 type.
*
* @return OAuthFlows flows
**/
OAuthFlows flows() default @OAuthFlows;
/**
* Required. OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the form of a URL. Applies to openIdConnect.
*
* @return String openIdConnectUrl
**/
String openIdConnectUrl() default "";
/**
* The list of optional extensions
*
* @return an optional array of extensions
*/
Extension[] extensions() default {};
/**
* A reference to a SecurityScheme defined in components securitySchemes.
*
* @since 2.0.3
* @return the reference
**/
String ref() default "";
}
<file_sep>package io.swagger.v3.core.filter;
import com.google.common.collect.Sets;
import io.swagger.v3.core.filter.resources.*;
import io.swagger.v3.core.matchers.SerializationMatchers;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.core.util.ResourceUtils;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import static org.testng.Assert.*;
public class SpecFilterTest {
private static final String RESOURCE_RECURSIVE_MODELS = "specFiles/recursivemodels.json";
private static final String RESOURCE_PATH = "specFiles/petstore-3.0-v2.json";
private static final String RESOURCE_REFERRED_SCHEMAS = "specFiles/petstore-3.0-referred-schemas.json";
private static final String RESOURCE_PATH_WITHOUT_MODELS = "specFiles/petstore-3.0-v2_withoutModels.json";
private static final String RESOURCE_DEPRECATED_OPERATIONS = "specFiles/deprecatedoperationmodel.json";
private static final String CHANGED_OPERATION_ID = "Changed Operation";
private static final String CHANGED_OPERATION_DESCRIPTION = "Changing some attributes of the operation";
private static final String NEW_OPERATION_ID = "New Operation";
private static final String NEW_OPERATION_DESCRIPTION = "Replaced Operation";
private static final String QUERY = "query";
private static final String PET_MODEL = "Pet";
private static final String TAG_MODEL = "/Tag";
private static final String PET_TAG = "pet";
private static final String STORE_TAG = "store";
private static final String USER_TAG = "user";
@Test(description = "it should clone everything")
public void cloneEverything() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
final OpenAPI filtered = new SpecFilter().filter(openAPI, new NoOpOperationsFilter(), null, null, null);
assertEquals(Json.pretty(filtered), Json.pretty(openAPI));
}
@Test(description = "it should filter away get operations in a resource")
public void filterAwayGetOperations() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
final NoGetOperationsFilter filter = new NoGetOperationsFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, filter, null, null, null);
if (filtered.getPaths() != null) {
for (Map.Entry<String, PathItem> entry : filtered.getPaths().entrySet()) {
assertNull(entry.getValue().getGet());
}
} else {
fail("paths should not be null");
}
}
@Test(description = "it should filter away the pet resource")
public void filterAwayPetResource() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
final NoPetOperationsFilter filter = new NoPetOperationsFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, filter, null, null, null);
if (filtered.getPaths() != null) {
for (Map.Entry<String, PathItem> entry : filtered.getPaths().entrySet()) {
assertNull(entry.getValue().getDelete());
assertNull(entry.getValue().getPost());
assertNull(entry.getValue().getPut());
assertNull(entry.getValue().getGet());
assertNull(entry.getValue().getHead());
assertNull(entry.getValue().getOptions());
}
} else {
fail("paths should not be null");
}
}
@Test(description = "it should replace away with a new operation")
public void replaceGetResources() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
OpenAPI filter = new SpecFilter().filter(openAPI, new ReplaceGetOperationsFilter(), null, null, null);
assertOperations(filter, NEW_OPERATION_ID, NEW_OPERATION_DESCRIPTION);
}
@Test(description = "it should change away with a new operation")
public void changeGetResources() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
OpenAPI filter = new SpecFilter().filter(openAPI, new ChangeGetOperationsFilter(), null, null, null);
assertOperations(filter, CHANGED_OPERATION_ID, CHANGED_OPERATION_DESCRIPTION);
}
private void assertOperations(OpenAPI filtered, String operationId, String description) {
if (filtered.getPaths() != null) {
for (Map.Entry<String, PathItem> entry : filtered.getPaths().entrySet()) {
Operation get = entry.getValue().getGet();
if (get != null) {
assertEquals(get.getOperationId(), operationId);
assertEquals(get.getDescription(), description);
}
}
} else {
fail("paths should not be null");
}
}
@Test(description = "it should filter an openAPI object")
public void filterAwayOpenAPI() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
final OpenAPI filtered = new SpecFilter().filter(openAPI, new NoOpenAPIFilter(), null, null, null);
assertNull(filtered);
}
@Test(description = "it should filter any PathItem objects without Ref")
public void filterAwayPathItemWithoutRef() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
final OpenAPI filtered = new SpecFilter().filter(openAPI, new NoPathItemFilter(), null, null, null);
assertEquals(0, filtered.getPaths().size());
}
@Test(description = "it should filter any query parameter")
public void filterAwayQueryParameters() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
final OpenAPI filtered = new SpecFilter().filter(openAPI, new NoParametersWithoutQueryInFilter(), null, null, null);
if (filtered.getPaths() != null) {
for (Map.Entry<String, PathItem> entry : filtered.getPaths().entrySet()) {
validateParameters(entry.getValue().getGet());
validateParameters(entry.getValue().getPost());
validateParameters(entry.getValue().getPut());
validateParameters(entry.getValue().getPatch());
validateParameters(entry.getValue().getHead());
validateParameters(entry.getValue().getDelete());
validateParameters(entry.getValue().getOptions());
}
}
}
private void validateParameters(Operation operation) {
if (operation != null) {
for (Parameter parameter : operation.getParameters()) {
assertNotEquals(QUERY, parameter.getIn());
}
}
}
@Test(description = "it should clone everything concurrently")
public void cloneEverythingConcurrent() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
ThreadGroup tg = new ThreadGroup("SpecFilterTest" + "|" + System.currentTimeMillis());
final Map<String, OpenAPI> filteredMap = new ConcurrentHashMap<>();
for (int i = 0; i < 10; i++) {
final int id = i;
new Thread(tg, "SpecFilterTest") {
public void run() {
try {
filteredMap.put("filtered " + id, new SpecFilter().filter(openAPI, new NoOpOperationsFilter(), null, null, null));
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
new Thread(new FailureHandler(tg, filteredMap, openAPI)).start();
}
class FailureHandler implements Runnable {
ThreadGroup tg;
Map<String, OpenAPI> filteredMap;
private OpenAPI openAPI;
private FailureHandler(ThreadGroup tg, Map<String, OpenAPI> filteredMap, OpenAPI openAPI) {
this.tg = tg;
this.filteredMap = filteredMap;
this.openAPI = openAPI;
}
@Override
public void run() {
try {
Thread[] thds = new Thread[tg.activeCount()];
tg.enumerate(thds);
for (Thread t : thds) {
if (t != null) {
t.join(10000);
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (OpenAPI filtered : filteredMap.values()) {
assertEquals(Json.pretty(openAPI), Json.pretty(filtered));
}
}
}
@Test(description = "it should clone everything from JSON without models")
public void cloneWithoutModels() throws IOException {
final String json = ResourceUtils.loadClassResource(getClass(), RESOURCE_PATH_WITHOUT_MODELS);
final OpenAPI openAPI = Json.mapper().readValue(json, OpenAPI.class);
final OpenAPI filtered = new SpecFilter().filter(openAPI, new NoOpOperationsFilter(), null, null, null);
SerializationMatchers.assertEqualsToJson(filtered, json);
}
@Test
public void shouldRemoveBrokenRefs() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
openAPI.getPaths().get("/pet/{petId}").getGet().getResponses().getDefault().getHeaders().remove("X-Rate-Limit-Limit");
assertNotNull(openAPI.getComponents().getSchemas().get("PetHeader"));
final RemoveUnreferencedDefinitionsFilter remover = new RemoveUnreferencedDefinitionsFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, remover, null, null, null);
assertNull(filtered.getComponents().getSchemas().get("PetHeader"));
assertNotNull(filtered.getComponents().getSchemas().get("Category"));
assertNotNull(filtered.getComponents().getSchemas().get("Pet"));
}
@Test
public void shouldNotRemoveGoodRefs() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
assertNotNull(openAPI.getComponents().getSchemas().get("PetHeader"));
final RemoveUnreferencedDefinitionsFilter remover = new RemoveUnreferencedDefinitionsFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, remover, null, null, null);
assertNotNull(filtered.getComponents().getSchemas().get("PetHeader"));
assertNotNull(filtered.getComponents().getSchemas().get("Category"));
}
@Test(description = "it should filter any Pet Ref in Schemas")
public void filterAwayPetRefInSchemas() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
final OpenAPI filtered = new SpecFilter().filter(openAPI, new NoPetRefSchemaFilter(), null, null, null);
validateSchemasInComponents(filtered.getComponents(), PET_MODEL);
}
private void validateSchemasInComponents(Components components, String model) {
if (components != null) {
if (components.getSchemas() != null) {
components.getSchemas().forEach((k, v) -> assertNotEquals(model, k));
}
}
}
@Test(description = "it should filter away secret parameters")
public void filterAwaySecretParameters() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
final RemoveInternalParamsFilter filter = new RemoveInternalParamsFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, filter, null, null, null);
if (filtered.getPaths() != null) {
for (Map.Entry<String, PathItem> entry : filtered.getPaths().entrySet()) {
final Operation get = entry.getValue().getGet();
if (get != null) {
for (Parameter param : get.getParameters()) {
final String description = param.getDescription();
if (StringUtils.isNotBlank(description)) {
assertFalse(description.startsWith("secret"));
}
}
}
}
} else {
fail("paths should not be null");
}
}
@Test(description = "it should filter away internal model properties")
public void filterAwayInternalModelProperties() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
final InternalModelPropertiesRemoverFilter filter = new InternalModelPropertiesRemoverFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, filter, null, null, null);
for (Map.Entry<String, Schema> entry : filtered.getComponents().getSchemas().entrySet()) {
for (String propName : (Set<String>) entry.getValue().getProperties().keySet()) {
assertFalse(propName.startsWith("_"));
}
}
}
@Test(description = "it should retain non-broken reference model composed properties")
public void retainNonBrokenReferenceModelComposedProperties() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_REFERRED_SCHEMAS);
assertNotNull(openAPI.getComponents().getSchemas().get("User"));
final NoOpOperationsFilter noOperationsFilter = new NoOpOperationsFilter();
OpenAPI filtered = new SpecFilter().filter(openAPI, noOperationsFilter, null, null, null);
assertNotNull(filtered.getComponents().getSchemas().get("User"));
final RemoveUnreferencedDefinitionsFilter refFilter = new RemoveUnreferencedDefinitionsFilter();
filtered = new SpecFilter().filter(openAPI, refFilter, null, null, null);
assertNotNull(filtered.getComponents().getSchemas().get("User"));
assertNotNull(filtered.getComponents().getSchemas().get("Pet"));
}
@Test(description = "recursive models, e.g. A-> A or A-> B and B -> A should not result in stack overflow")
public void removeUnreferencedDefinitionsOfRecuriveModels() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_RECURSIVE_MODELS);
final RemoveUnreferencedDefinitionsFilter remover = new RemoveUnreferencedDefinitionsFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, remover, null, null, null);
assertNotNull(filtered.getComponents().getSchemas().get("SelfReferencingModel"));
assertNotNull(filtered.getComponents().getSchemas().get("IndirectRecursiveModelA"));
assertNotNull(filtered.getComponents().getSchemas().get("IndirectRecursiveModelB"));
}
@Test(description = "broken references should not result in NPE")
public void removeUnreferencedModelOverride() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_REFERRED_SCHEMAS);
final RemoveUnreferencedDefinitionsFilter remover = new RemoveUnreferencedDefinitionsFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, remover, null, null, null);
assertNotNull(filtered.getComponents().getSchemas().get("Order"));
}
@Test(description = "Retain models referenced from additonalProperties")
public void retainModelsReferencesFromAdditionalProperties() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_REFERRED_SCHEMAS);
final RemoveUnreferencedDefinitionsFilter remover = new RemoveUnreferencedDefinitionsFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, remover, null, null, null);
assertNotNull(filtered.getComponents().getSchemas().get("Order"));
assertNotNull(filtered.getComponents().getSchemas().get("ReferredOrder"));
}
@Test(description = "Clone should retain any 'deperecated' flags present on operations")
public void cloneRetainDeperecatedFlags() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_DEPRECATED_OPERATIONS);
final RemoveUnreferencedDefinitionsFilter remover = new RemoveUnreferencedDefinitionsFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, remover, null, null, null);
Operation operation = filtered.getPaths().get("/test").getGet();
Boolean deprectedFlag = operation.getDeprecated();
assertNotNull(deprectedFlag);
assertEquals(deprectedFlag, Boolean.TRUE);
}
@Test(description = "it should contain all tags in the top level OpenAPI object")
public void shouldContainAllTopLevelTags() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_REFERRED_SCHEMAS);
final NoOpOperationsFilter filter = new NoOpOperationsFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, filter, null, null, null);
assertEquals(getTagNames(filtered), Sets.newHashSet(PET_TAG, USER_TAG, STORE_TAG));
}
@Test(description = "it should not contain user tags in the top level OpenAPI object")
public void shouldNotContainTopLevelUserTags() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_REFERRED_SCHEMAS);
final NoPetOperationsFilter filter = new NoPetOperationsFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, filter, null, null, null);
assertEquals(getTagNames(filtered), Sets.newHashSet(USER_TAG, STORE_TAG));
}
@Test(description = "it should filter with null definitions")
public void filterWithNullDefinitions() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
openAPI.getComponents().setSchemas(null);
final InternalModelPropertiesRemoverFilter filter = new InternalModelPropertiesRemoverFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, filter, null, null, null);
assertNotNull(filtered);
}
private Set getTagNames(OpenAPI openAPI) {
Set<String> result = new HashSet<>();
if (openAPI.getTags() != null) {
for (Tag item : openAPI.getTags()) {
result.add(item.getName());
}
}
return result;
}
private OpenAPI getOpenAPI(String path) throws IOException {
final String json = ResourceUtils.loadClassResource(getClass(), path);
return Json.mapper().readValue(json, OpenAPI.class);
}
}
<file_sep>package io.swagger.v3.jaxrs2.it.resources;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/users")
@Produces("application/json")
public class UrlEncodedResource {
@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response addUser(@FormParam("id") final String id, @FormParam("name") final String name,
@FormParam("gender") final String gender) {
return Response.status(200).entity("Adding user " + id + " to the system.").build();
}
}
<file_sep>package io.swagger.v3.core.deserialization.properties;
import io.swagger.v3.core.util.TestUtils;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.MapSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Map;
import static org.testng.Assert.*;
public class JsonPropertiesDeserializationTest {
@Test(description = "should deserialize a string property with constraints")
public void testDeserializeConstrainedStringProperty() throws Exception {
OpenAPI oas = TestUtils.deserializeJsonFileFromClasspath("specFiles/propertiesWithConstraints.json", OpenAPI.class);
StringSchema property = (StringSchema) oas.getComponents().getSchemas().get("Health").getProperties().get("string_with_constraints");
assertEquals(property.getMinLength(), Integer.valueOf(10));
assertEquals(property.getMaxLength(), Integer.valueOf(100));
assertEquals(property.getPattern(), "apattern");
}
@Test(description = "should deserialize an array property with constraints")
public void testDeserializeConstrainedArrayProperties() throws Exception {
OpenAPI oas = TestUtils.deserializeJsonFileFromClasspath("specFiles/propertiesWithConstraints.json", OpenAPI.class);
Map<String, Schema> properties = oas.getComponents().getSchemas().get("Health").getProperties();
ArraySchema withMin = (ArraySchema) properties.get("array_with_min");
assertEquals(withMin.getMinItems(), Integer.valueOf(5));
assertNull(withMin.getMaxItems());
assertNull(withMin.getUniqueItems());
ArraySchema withMax = (ArraySchema) properties.get("array_with_max");
assertNull(withMax.getMinItems());
assertEquals(withMax.getMaxItems(), Integer.valueOf(10));
assertNull(withMax.getUniqueItems());
ArraySchema withUnique = (ArraySchema) properties.get("array_with_unique");
assertNull(withUnique.getMinItems());
assertNull(withUnique.getMaxItems());
assertEquals(withUnique.getUniqueItems(), Boolean.TRUE);
ArraySchema withAll = (ArraySchema) properties.get("array_with_all");
assertEquals(withAll.getMinItems(), Integer.valueOf(1));
assertEquals(withAll.getMaxItems(), Integer.valueOf(10));
assertEquals(withAll.getUniqueItems(), Boolean.TRUE);
}
@Test(description = "should deserialize a property with vendor extensions of different types")
public void testDeserializePropertyWithVendorExtensions() throws Exception {
OpenAPI oas = TestUtils.deserializeJsonFileFromClasspath("specFiles/propertyWithVendorExtensions.json", OpenAPI.class);
Map<String, Object> oasVendorExtensions = oas.getExtensions();
Map<String, Object> vendorExtensions = ((Schema) oas.getComponents().getSchemas().get("Health").getProperties().get("status")).getExtensions();
assertVendorExtensions(oasVendorExtensions);
assertVendorExtensions(vendorExtensions);
//check for vendor extensions in array property types
vendorExtensions = ((Schema) oas.getComponents().getSchemas().get("Health").getProperties().get("array")).getExtensions();
String xStringValue = (String) vendorExtensions.get("x-string-value");
assertNotNull(xStringValue);
assertEquals(xStringValue, "string_value");
}
private void assertVendorExtensions(Map<String, Object> vendorExtensions) {
assertNotNull(vendorExtensions);
assertEquals(6, vendorExtensions.size());
String xStringValue = (String) vendorExtensions.get("x-string-value");
assertNotNull(xStringValue);
assertEquals(xStringValue, "Hello World");
assertTrue(vendorExtensions.containsKey("x-null-value"));
assertNull(vendorExtensions.get("x-null-value"));
Map<String, String> xMapValue = (Map) vendorExtensions.get("x-map-value");
assertNotNull(xMapValue);
assertEquals(xMapValue.get("hello"), "world");
assertEquals(xMapValue.get("foo"), "bar");
List<String> xListValue = (List) vendorExtensions.get("x-list-value");
assertNotNull(xListValue);
assertEquals(xListValue.get(0), "Hello");
assertEquals(xListValue.get(1), "World");
Integer xNumberValue = (Integer) vendorExtensions.get("x-number-value");
assertNotNull(xNumberValue);
assertEquals(xNumberValue.intValue(), 123);
Boolean xBooleanValue = (Boolean) vendorExtensions.get("x-boolean-value");
assertNotNull(xBooleanValue);
assertTrue(xBooleanValue);
assertFalse(vendorExtensions.containsKey("not-an-extension"));
}
@Test
public void shouldDeserializeArrayPropertyMinItems() throws Exception {
String path = "json-schema-validation/array.json";
ArraySchema property = (ArraySchema) TestUtils.deserializeJsonFileFromClasspath(path, Schema.class);
assertNotNull(property.getMinItems());
assertEquals(property.getMinItems().intValue(), 1);
}
@Test
public void shouldDeserializeArrayPropertyMaxItems() throws Exception {
String path = "json-schema-validation/array.json";
ArraySchema property = (ArraySchema) TestUtils.deserializeJsonFileFromClasspath(path, Schema.class);
assertNotNull(property.getMaxItems());
assertEquals(property.getMaxItems().intValue(), 10);
}
@Test
public void shouldDeserializeArrayPropertyUniqueItems() throws Exception {
String path = "json-schema-validation/array.json";
ArraySchema property = (ArraySchema) TestUtils.deserializeJsonFileFromClasspath(path, Schema.class);
assertNotNull(property.getUniqueItems());
assertTrue(property.getUniqueItems());
}
@Test
public void givenMapProperty_shouldDeserializeMinProperties() {
String path = "json-schema-validation/map.json";
MapSchema property = (MapSchema) TestUtils.deserializeJsonFileFromClasspath(path, Schema.class);
assertNotNull(property.getMinProperties());
assertEquals(property.getMinProperties().intValue(), 1);
}
@Test
public void givenMapProperty_shouldDeserializeMaxProperties() {
String path = "json-schema-validation/map.json";
MapSchema property = (MapSchema) TestUtils.deserializeJsonFileFromClasspath(path, Schema.class);
assertNotNull(property.getMaxProperties());
assertEquals(property.getMaxProperties().intValue(), 10);
}
}
<file_sep>package io.swagger.v3.core.resolving;
import io.swagger.v3.core.converter.ModelConverters;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.testng.annotations.Test;
import java.util.Map;
import static org.testng.Assert.*;
public class HiddenFieldTest {
@Test(description = "it should ignore a hidden field")
public void testHiddenField() {
final Map<String, Schema> models = ModelConverters.getInstance().read(ModelWithHiddenFields.class);
final Schema model = models.get("ModelWithHiddenFields");
assertNotNull(model);
assertEquals(model.getProperties().size(), 2);
final Schema idValue = (Schema) model.getProperties().get("id");
assertTrue(idValue instanceof IntegerSchema);
assertTrue(model.getRequired().contains("id"));
final Schema nameValue = (Schema) model.getProperties().get("name");
assertTrue(nameValue instanceof StringSchema);
}
class ModelWithHiddenFields {
@io.swagger.v3.oas.annotations.media.Schema(required = true)
public Long id = null;
@io.swagger.v3.oas.annotations.media.Schema(required = true, hidden = false)
public String name = null;
@io.swagger.v3.oas.annotations.media.Schema(hidden = true)
public String password = null;
}
}
<file_sep>package io.swagger.v3.core.converting;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.core.converter.ModelConverters;
import io.swagger.v3.core.matchers.SerializationMatchers;
import io.swagger.v3.core.oas.models.Person;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.core.util.OutputReplacer;
import io.swagger.v3.core.util.ResourceUtils;
import io.swagger.v3.oas.models.*;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.links.Link;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.QueryParameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;
import io.swagger.v3.oas.models.servers.Server;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.testng.Assert.*;
public class SwaggerSerializerTest {
ObjectMapper m = Json.mapper();
@Test(description = "it should convert a spec")
public void convertSpec() throws IOException {
final Schema personModel = ModelConverters.getInstance().read(Person.class).get("Person");
final Schema errorModel = ModelConverters.getInstance().read(Error.class).get("Error");
final Info info = new Info()
.version("1.0.0")
.title("Swagger Petstore");
final Contact contact = new Contact()
.name("Swagger API Team")
.email("<EMAIL>")
.url("http://swagger.io");
info.setContact(contact);
final Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "value");
info.addExtension("x-test2", map);
info.addExtension("x-test", "value");
final OpenAPI swagger = new OpenAPI()
.info(info)
.addServersItem(new Server()
.url("http://petstore.swagger.io"))
// .securityDefinition("api-key", new ApiKeyAuthDefinition("key", In.HEADER))
// .consumes("application/json")
// .produces("application/json")
.schema("Person", personModel)
.schema("Error", errorModel);
final Operation get = new Operation()
// .produces("application/json")
.summary("finds pets in the system")
.description("a longer description")
.addTagsItem("Pet Operations")
.operationId("get pet by id")
.deprecated(true);
get.addParametersItem(new Parameter()
.in("query")
.name("tags")
.description("tags to filter by")
.required(false)
.schema(new StringSchema())
);
get.addParametersItem(new Parameter()
.in("path")
.name("petId")
.description("pet to fetch")
.schema(new IntegerSchema().format("int64"))
);
final ApiResponse response = new ApiResponse()
.description("pets returned")
.content(new Content()
.addMediaType("application/json", new MediaType()
.schema(new Schema().$ref("Person"))
.example("fun")));
final ApiResponse errorResponse = new ApiResponse()
.description("error response")
.link("myLink", new Link()
.description("a link")
.operationId("theLinkedOperationId")
.parameters("userId", "gah")
)
.content(new Content()
.addMediaType("application/json", new MediaType()
.schema(new Schema().$ref("Error"))));
get.responses(new ApiResponses()
.addApiResponse("200", response)
.addApiResponse("default", errorResponse));
final Operation post = new Operation()
.summary("adds a new pet")
.description("you can add a new pet this way")
.addTagsItem("Pet Operations")
.operationId("add pet")
.responses(new ApiResponses()
.addApiResponse("default", errorResponse))
.requestBody(new RequestBody()
.description("the pet to add")
.content(new Content().addMediaType("*/*", new MediaType()
.schema(new Schema().$ref("Person")))));
swagger.paths(new Paths().addPathItem("/pets", new PathItem()
.get(get).post(post)));
final String swaggerJson = Json.mapper().writeValueAsString(swagger);
Json.prettyPrint(swagger);
final OpenAPI rebuilt = Json.mapper().readValue(swaggerJson, OpenAPI.class);
SerializationMatchers.assertEqualsToJson(rebuilt, swaggerJson);
}
@Test(description = "it should read the uber api")
public void readUberApi() throws IOException {
final String jsonString = ResourceUtils.loadClassResource(getClass(), "uber.json");
final OpenAPI swagger = Json.mapper().readValue(jsonString, OpenAPI.class);
assertNotNull(swagger);
}
@Test(description = "it should write a spec with parameter references")
public void writeSpecWithParameterReferences() throws IOException {
final Schema personModel = ModelConverters.getInstance().read(Person.class).get("Person");
final Info info = new Info()
.version("1.0.0")
.title("Swagger Petstore");
final Contact contact = new Contact()
.name("Swagger API Team")
.email("<EMAIL>")
.url("http://swagger.io");
info.setContact(contact);
final OpenAPI swagger = new OpenAPI()
.info(info)
.addServersItem(new Server().url("http://petstore.swagger.io"))
//.consumes("application/json")
//.produces("application/json")
.schema("Person", personModel);
final QueryParameter parameter = (QueryParameter) new QueryParameter()
.name("id")
.description("a common get parameter")
.schema(new IntegerSchema());
final Operation get = new Operation()
//.produces("application/json")
.summary("finds pets in the system")
.description("a longer description")
//.tag("Pet Operations")
.operationId("get pet by id")
.addParametersItem(new Parameter().$ref("#/parameters/Foo"));
swagger
.components(new Components().addParameters("Foo", parameter))
.path("/pets", new PathItem().get(get));
final String swaggerJson = Json.mapper().writeValueAsString(swagger);
final OpenAPI rebuilt = Json.mapper().readValue(swaggerJson, OpenAPI.class);
assertEquals(Json.pretty(rebuilt), Json.pretty(swagger));
}
@Test
public void prettyPrintTest() throws IOException {
final String json = ResourceUtils.loadClassResource(getClass(), "uber.json");
final OpenAPI swagger = Json.mapper().readValue(json, OpenAPI.class);
final String outputStream = OutputReplacer.OUT.run(new OutputReplacer.Function() {
@Override
public void run() {
Json.prettyPrint(swagger);
}
});
SerializationMatchers.assertEqualsToJson(swagger, outputStream);
}
@Test
public void exceptionsTest() throws IOException {
final String outputStream1 = OutputReplacer.ERROR.run(new OutputReplacer.Function() {
@Override
public void run() {
Json.pretty(new ThrowHelper());
}
});
assertTrue(outputStream1.contains(ThrowHelper.MESSAGE));
final String outputStream2 = OutputReplacer.ERROR.run(new OutputReplacer.Function() {
@Override
public void run() {
Json.prettyPrint(new ThrowHelper());
}
});
assertTrue(outputStream2.contains(ThrowHelper.MESSAGE));
}
static class ThrowHelper {
public static final String MESSAGE = "Test exception";
public String getValue() throws IOException {
throw new IOException(MESSAGE);
}
public void setValue(String value) {
}
}
}
<file_sep>package io.swagger.v3.jaxrs2.annotations.operations;
import io.swagger.v3.jaxrs2.annotations.AbstractAnnotationTest;
import io.swagger.v3.jaxrs2.resources.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.testng.annotations.Test;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import java.io.IOException;
import static org.testng.Assert.assertEquals;
public class AnnotatedOperationMethodTest extends AbstractAnnotationTest {
@Test
public void testSimpleGetOperation() {
String openApiYAML = readIntoYaml(SimpleGetOperationTest.class);
int start = openApiYAML.indexOf("get:");
int end = openApiYAML.length() - 1;
String expectedYAML = "get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs and a complex\n" +
" operationId: getWithNoParameters\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" deprecated: true";
String extractedYAML = openApiYAML.substring(start, end);
assertEquals(extractedYAML, expectedYAML);
}
static class SimpleGetOperationTest {
@Operation(
summary = "Simple get operation",
description = "Defines a simple get operation with no inputs and a complex",
operationId = "getWithNoParameters",
deprecated = true,
responses = {
@ApiResponse(
responseCode = "200",
description = "voila!")
}
)
@GET
@Path("/path")
public void simpleGet() {
}
}
@Test
public void testSimpleGetOperationWithoutResponses() {
String openApiYAML = readIntoYaml(SimpleGetWithoutResponses.class);
int start = openApiYAML.indexOf("get:");
int end = openApiYAML.length() - 1;
String expectedYAML = "get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs or responses\n" +
" operationId: getWithNoParametersAndNoResponses\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" '*/*': {}\n" +
" deprecated: true";
String extractedYAML = openApiYAML.substring(start, end);
assertEquals(extractedYAML, expectedYAML);
}
static class SimpleGetWithoutResponses {
@Operation(
summary = "Simple get operation",
description = "Defines a simple get operation with no inputs or responses",
operationId = "getWithNoParametersAndNoResponses",
deprecated = true
)
@GET
@Path("/path")
public void simpleGet() {
}
}
@Test
public void testGetOperationWithResponsePayloadAndAlternateCodes() {
String openApiYAML = readIntoYaml(GetOperationWithResponsePayloadAndAlternateCodes.class);
int start = openApiYAML.indexOf("get:");
int end = openApiYAML.indexOf("components:");
String extractedYAML = openApiYAML.substring(start, end);
String expectedYAML = "get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs and a complex\n" +
" operationId: getWithPayloadResponse\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/SampleResponseSchema'\n" +
" default:\n" +
" description: boo\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/GenericError'\n" +
" examples:\n" +
" boo:\n" +
" summary: example of boo\n" +
" description: boo\n" +
" value: example\n" +
" externalValue: example of external value\n" +
" deprecated: true\n";
assertEquals(extractedYAML, expectedYAML);
}
static class GetOperationWithResponsePayloadAndAlternateCodes {
@Operation(
summary = "Simple get operation",
description = "Defines a simple get operation with no inputs and a complex",
operationId = "getWithPayloadResponse",
deprecated = true,
responses = {
@ApiResponse(
responseCode = "200",
description = "voila!",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = SampleResponseSchema.class)
)
),
@ApiResponse(
description = "boo",
content = @Content(
mediaType = "*/*",
schema = @Schema(implementation = GenericError.class),
examples = {
@ExampleObject(name = "boo", value = "example",
summary = "example of boo", externalValue = "example of external value")
}
)
)
}
)
@Path("/path")
@GET
public void simpleGet() {
}
}
static class SampleResponseSchema {
@Schema(description = "the user id")
public String id;
}
static class GenericError {
public int code;
public String message;
}
@Test(description = "reads an operation with response examples defined")
public void testOperationWithResponseExamples() {
String openApiYAML = readIntoYaml(GetOperationWithResponseExamples.class);
int start = openApiYAML.indexOf("get:");
int end = openApiYAML.indexOf("components:");
String extractedYAML = openApiYAML.substring(start, end);
String expectedYAML = "get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs and a complex output\n" +
" operationId: getWithPayloadResponse\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/SampleResponseSchema'\n" +
" examples:\n" +
" basic:\n" +
" summary: shows a basic example\n" +
" description: basic\n" +
" value: '{id: 19877734}'\n" +
" deprecated: true\n";
assertEquals(extractedYAML, expectedYAML);
}
@Test(description = "reads an operation with response examples defined")
public void testOperationWithParameterExample() {
String openApiYAML = readIntoYaml(GetOperationWithParameterExample.class);
int start = openApiYAML.indexOf("get:");
int end = openApiYAML.indexOf("components:");
String extractedYAML = openApiYAML.substring(start, end);
String expectedYAML = "get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with a parameter example\n" +
" operationId: getWithPayloadResponse\n" +
" parameters:\n" +
" - in: query\n" +
" schema:\n" +
" type: string\n" +
" example:\n" +
" id: 19877734\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/SampleResponseSchema'\n" +
" examples:\n" +
" basic:\n" +
" summary: shows a basic example\n" +
" description: basic\n" +
" value: '{id: 19877734}'\n" +
" deprecated: true\n";
assertEquals(extractedYAML, expectedYAML);
}
static class GetOperationWithResponseExamples {
@Operation(
summary = "Simple get operation",
description = "Defines a simple get operation with no inputs and a complex output",
operationId = "getWithPayloadResponse",
deprecated = true,
responses = {
@ApiResponse(
responseCode = "200",
description = "voila!",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = SampleResponseSchema.class),
examples = {
@ExampleObject(
name = "basic",
summary = "shows a basic example",
value = "{id: 19877734}")
}
)
)
}
)
@GET
@Path("/path")
public void simpleGet() {
}
}
static class GetOperationWithParameterExample {
@Operation(
summary = "Simple get operation",
description = "Defines a simple get operation with a parameter example",
operationId = "getWithPayloadResponse",
deprecated = true,
responses = {
@ApiResponse(
responseCode = "200",
description = "voila!",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = SampleResponseSchema.class),
examples = {
@ExampleObject(
name = "basic",
summary = "shows a basic example",
value = "{id: 19877734}")
}
)
)
}
)
@GET
@Path("/path")
public void simpleGet(@Parameter(in = ParameterIn.QUERY, example = "{\"id\": 19877734}") String exParam) {
}
}
static class GetOperationWithResponseSingleHeader {
@Operation(
summary = "Simple get operation",
description = "Defines a simple get operation with no inputs and a complex output",
operationId = "getWithPayloadResponse",
deprecated = true,
responses = {
@ApiResponse(
responseCode = "200",
description = "voila!",
headers = {@Header(
name = "Rate-Limit-Limit",
description = "The number of allowed requests in the current period",
schema = @Schema(type = "integer"))})
})
@GET
@Path("/path")
public void simpleGet() {
}
}
@Test
public void testOperationWithResponseSingleHeader() {
String openApiYAML = readIntoYaml(GetOperationWithResponseSingleHeader.class);
int start = openApiYAML.indexOf("get:");
String extractedYAML = openApiYAML.substring(start);
String expectedYAML = "get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs and a complex output\n" +
" operationId: getWithPayloadResponse\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" headers:\n" +
" Rate-Limit-Limit:\n" +
" description: The number of allowed requests in the current period\n" +
" style: simple\n" +
" schema:\n" +
" type: integer\n" +
" deprecated: true\n";
assertEquals(expectedYAML, extractedYAML);
}
static class GetOperationWithResponseMultipleHeaders {
@Operation(
summary = "Simple get operation",
description = "Defines a simple get operation with no inputs and a complex output",
operationId = "getWithPayloadResponse",
deprecated = true,
responses = {
@ApiResponse(
responseCode = "200",
description = "voila!",
headers = {@Header(
name = "Rate-Limit-Limit",
description = "The number of allowed requests in the current period",
schema = @Schema(type = "integer")),
@Header(
name = "X-Rate-Limit-Desc",
description = "The description of rate limit",
schema = @Schema(type = "string"))})
})
@GET
@Path("/path")
public void simpleGet() {
}
}
@Test
public void testOperationWithResponseMultipleHeaders() {
String openApiYAML = readIntoYaml(GetOperationWithResponseMultipleHeaders.class);
int start = openApiYAML.indexOf("get:");
String extractedYAML = openApiYAML.substring(start);
String expectedYAML = "get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs and a complex output\n" +
" operationId: getWithPayloadResponse\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" headers:\n" +
" X-Rate-Limit-Desc:\n" +
" description: The description of rate limit\n" +
" style: simple\n" +
" schema:\n" +
" type: string\n" +
" Rate-Limit-Limit:\n" +
" description: The number of allowed requests in the current period\n" +
" style: simple\n" +
" schema:\n" +
" type: integer\n" +
" deprecated: true\n";
assertEquals(expectedYAML, extractedYAML);
}
@Test(description = "reads the pet resource from sample")
public void testCompletePetResource() throws IOException {
String expectedYAML = "openapi: 3.0.1\n" +
"paths:\n" +
" /pet/findByTags:\n" +
" get:\n" +
" summary: Finds Pets by tags\n" +
" description: Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.\n" +
" operationId: findPetsByTags\n" +
" parameters:\n" +
" - name: tags\n" +
" in: query\n" +
" description: Tags to filter by\n" +
" required: true\n" +
" schema:\n" +
" type: string\n" +
" responses:\n" +
" default:\n" +
" description: Pets matching criteria\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/Pet'\n" +
" 400:\n" +
" description: Invalid tag value\n" +
" /pet/findByCategory/{category}:\n" +
" get:\n" +
" summary: Finds Pets by category\n" +
" operationId: findPetsByCategory\n" +
" parameters:\n" +
" - name: category\n" +
" in: path\n" +
" description: Category value that need to be considered for filter\n" +
" required: true\n" +
" style: matrix\n" +
" schema:\n" +
" $ref: '#/components/schemas/Category'\n" +
" - name: skip\n" +
" in: query\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" - name: limit\n" +
" in: query\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" responses:\n" +
" default:\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/Pet'\n" +
" 400:\n" +
" description: Invalid category value\n" +
" /pet/{petId}:\n" +
" get:\n" +
" summary: Find pet by ID\n" +
" description: Returns a pet when 0 < ID <= 10. ID > 10 or nonintegers will simulate API error conditions\n" +
" operationId: getPetById\n" +
" parameters:\n" +
" - name: petId\n" +
" in: path\n" +
" description: ID of pet that needs to be fetched\n" +
" required: true\n" +
" schema:\n" +
" type: integer\n" +
" format: int64\n" +
" responses:\n" +
" default:\n" +
" description: The pet\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/Pet'\n" +
" application/xml:\n" +
" schema:\n" +
" $ref: '#/components/schemas/Pet'\n" +
" 400:\n" +
" description: Invalid ID supplied\n" +
" 404:\n" +
" description: Pet not found\n" +
" /pet/bodynoannotation:\n" +
" post:\n" +
" summary: Add a new pet to the store no annotation\n" +
" operationId: addPetNoAnnotation\n" +
" requestBody:\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/Pet'\n" +
" application/xml:\n" +
" schema:\n" +
" $ref: '#/components/schemas/Pet'\n" +
" responses:\n" +
" 405:\n" +
" description: Invalid input\n" +
" /pet/bodyid:\n" +
" post:\n" +
" summary: Add a new pet to the store passing an integer with generic parameter annotation\n" +
" operationId: addPetByInteger\n" +
" requestBody:\n" +
" description: Pet object that needs to be added to the store\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" application/xml:\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" required: true\n" +
" responses:\n" +
" 405:\n" +
" description: Invalid input\n" +
" /pet/bodyidnoannotation:\n" +
" post:\n" +
" summary: Add a new pet to the store passing an integer without parameter annotation\n" +
" operationId: addPetByIntegerNoAnnotation\n" +
" requestBody:\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" application/xml:\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" responses:\n" +
" 405:\n" +
" description: Invalid input\n" +
" /pet:\n" +
" put:\n" +
" summary: Update an existing pet\n" +
" operationId: updatePet\n" +
" requestBody:\n" +
" description: Pet object that needs to be added to the store\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/Pet'\n" +
" required: true\n" +
" responses:\n" +
" 400:\n" +
" description: Invalid ID supplied\n" +
" 404:\n" +
" description: Pet not found\n" +
" 405:\n" +
" description: Validation exception\n" +
" post:\n" +
" summary: Add a new pet to the store\n" +
" operationId: addPet\n" +
" requestBody:\n" +
" description: Pet object that needs to be added to the store\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/Pet'\n" +
" application/xml:\n" +
" schema:\n" +
" $ref: '#/components/schemas/Pet'\n" +
" required: true\n" +
" responses:\n" +
" 405:\n" +
" description: Invalid input\n" +
" /pet/findByStatus:\n" +
" get:\n" +
" summary: Finds Pets by status\n" +
" description: Multiple status values can be provided with comma separated strings\n" +
" operationId: findPetsByStatus\n" +
" parameters:\n" +
" - name: status\n" +
" in: query\n" +
" description: Status values that need to be considered for filter\n" +
" required: true\n" +
" schema:\n" +
" type: string\n" +
" - name: skip\n" +
" in: query\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" - name: limit\n" +
" in: query\n" +
" schema:\n" +
" type: integer\n" +
" format: int32\n" +
" responses:\n" +
" default:\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/Pet'\n" +
" 400:\n" +
" description: Invalid status value\n" +
"components:\n" +
" schemas:\n" +
" Category:\n" +
" type: object\n" +
" properties:\n" +
" id:\n" +
" type: integer\n" +
" format: int64\n" +
" name:\n" +
" type: string\n" +
" xml:\n" +
" name: Category\n" +
" Tag:\n" +
" type: object\n" +
" properties:\n" +
" id:\n" +
" type: integer\n" +
" format: int64\n" +
" name:\n" +
" type: string\n" +
" xml:\n" +
" name: Tag\n" +
" Pet:\n" +
" type: object\n" +
" properties:\n" +
" id:\n" +
" type: integer\n" +
" format: int64\n" +
" category:\n" +
" $ref: '#/components/schemas/Category'\n" +
" name:\n" +
" type: string\n" +
" photoUrls:\n" +
" type: array\n" +
" xml:\n" +
" wrapped: true\n" +
" items:\n" +
" type: string\n" +
" xml:\n" +
" name: photoUrl\n" +
" tags:\n" +
" type: array\n" +
" xml:\n" +
" wrapped: true\n" +
" items:\n" +
" $ref: '#/components/schemas/Tag'\n" +
" status:\n" +
" type: string\n" +
" description: pet status in the store\n" +
" enum:\n" +
" - available,pending,sold\n" +
" xml:\n" +
" name: Pet";
compareAsYaml(PetResource.class, expectedYAML);
compareAsYaml(PetResourceSlashesinPath.class, expectedYAML);
}
@Test(description = "reads the resource with generic response from sample")
public void testGenericResponseResource() throws IOException {
String yaml = "openapi: 3.0.1\n" +
"paths:\n" +
" /:\n" +
" get:\n" +
" summary: Returns a list of somethings\n" +
" operationId: getSomethings\n" +
" responses:\n" +
" default:\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/SomethingResponse'\n" +
" /overridden:\n" +
" get:\n" +
" summary: Returns a list of somethings\n" +
" operationId: getSomethingsOverridden\n" +
" responses:\n" +
" default:\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/Something'\n" +
"components:\n" +
" schemas:\n" +
" SomethingResponse:\n" +
" type: object\n" +
" properties:\n" +
" data:\n" +
" $ref: '#/components/schemas/DataSomething'\n" +
" DataSomething:\n" +
" type: object\n" +
" properties:\n" +
" items:\n" +
" type: array\n" +
" items:\n" +
" $ref: '#/components/schemas/Something'\n" +
" Something:\n" +
" type: object\n" +
" properties:\n" +
" id:\n" +
" type: string\n";
compareAsYaml(GenericResponsesResource.class, yaml);
}
@Test(description = "reads the user resource from sample")
public void testCompleteUserResource() throws IOException {
String expectedYAML = "openapi: 3.0.1\n" +
"paths:\n" +
" /user:\n" +
" post:\n" +
" summary: Create user\n" +
" description: This can only be done by the logged in user.\n" +
" operationId: createUser\n" +
" requestBody:\n" +
" description: Created user object\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" required: true\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" 'application/json': {}\n" +
" 'application/xml': {}\n" +
" /user/createWithArray:\n" +
" post:\n" +
" summary: Creates list of users with given input array\n" +
" operationId: createUsersWithArrayInput\n" +
" requestBody:\n" +
" description: List of user object\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" type: array\n" +
" items:\n" +
" $ref: '#/components/schemas/User'\n" +
" required: true\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" 'application/json': {}\n" +
" 'application/xml': {}\n" +
" /user/createWithList:\n" +
" post:\n" +
" summary: Creates list of users with given input array\n" +
" operationId: createUsersWithListInput\n" +
" requestBody:\n" +
" description: List of user object\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" type: array\n" +
" items:\n" +
" $ref: '#/components/schemas/User'\n" +
" required: true\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" 'application/json': {}\n" +
" 'application/xml': {}\n" +
" /user/{username}:\n" +
" get:\n" +
" summary: Get user by user name\n" +
" operationId: getUserByName\n" +
" parameters:\n" +
" - name: username\n" +
" in: path\n" +
" description: 'The name that needs to be fetched. Use user1 for testing. '\n" +
" required: true\n" +
" schema:\n" +
" type: string\n" +
" responses:\n" +
" default:\n" +
" description: The user\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" 400:\n" +
" description: User not found\n" +
" put:\n" +
" summary: Updated user\n" +
" description: This can only be done by the logged in user.\n" +
" operationId: updateUser\n" +
" parameters:\n" +
" - name: username\n" +
" in: path\n" +
" description: name that need to be deleted\n" +
" required: true\n" +
" schema:\n" +
" type: string\n" +
" examples:\n" +
" example2:\n" +
" summary: Summary example 2\n" +
" description: example2\n" +
" value: example2\n" +
" externalValue: external value 2\n" +
" example1:\n" +
" summary: Summary example 1\n" +
" description: example1\n" +
" value: example1\n" +
" externalValue: external value 1\n" +
" requestBody:\n" +
" description: Updated user object\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" required: true\n" +
" responses:\n" +
" 200:\n" +
" description: user updated\n" +
" 400:\n" +
" description: Invalid user supplied\n" +
" 404:\n" +
" description: User not found\n" +
" delete:\n" +
" summary: Delete user\n" +
" description: This can only be done by the logged in user.\n" +
" operationId: deleteUser\n" +
" parameters:\n" +
" - name: username\n" +
" in: path\n" +
" description: The name that needs to be deleted\n" +
" required: true\n" +
" schema:\n" +
" type: string\n" +
" responses:\n" +
" 200:\n" +
" description: user deteled\n" +
" 400:\n" +
" description: Invalid username supplied\n" +
" 404:\n" +
" description: User not found\n" +
" /user/login:\n" +
" get:\n" +
" summary: Logs user into the system\n" +
" operationId: loginUser\n" +
" parameters:\n" +
" - name: username\n" +
" in: query\n" +
" description: The user name for login\n" +
" required: true\n" +
" schema:\n" +
" type: string\n" +
" - name: password\n" +
" in: query\n" +
" description: The password for login in clear text\n" +
" required: true\n" +
" schema:\n" +
" type: string\n" +
" responses:\n" +
" default:\n" +
" description: Successfully logged in\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" type: string\n" +
" application/xml:\n" +
" schema:\n" +
" type: string\n" +
" 400:\n" +
" description: Invalid username/password supplied\n" +
" /user/logout:\n" +
" get:\n" +
" summary: Logs out current logged in user session\n" +
" operationId: logoutUser\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" 'application/json': {}\n" +
" 'application/xml': {}\n" +
"components:\n" +
" schemas:\n" +
" User:\n" +
" type: object\n" +
" properties:\n" +
" id:\n" +
" type: integer\n" +
" format: int64\n" +
" username:\n" +
" type: string\n" +
" firstName:\n" +
" type: string\n" +
" lastName:\n" +
" type: string\n" +
" email:\n" +
" type: string\n" +
" password:\n" +
" type: string\n" +
" phone:\n" +
" type: string\n" +
" userStatus:\n" +
" type: integer\n" +
" description: User Status\n" +
" format: int32\n" +
" xml:\n" +
" name: User";
compareAsYaml(UserResource.class, expectedYAML);
}
@Test(description = "reads the simple user resource from sample")
public void testSimpleUserResource() throws IOException {
String expectedYAML = "openapi: 3.0.1\n" +
"paths:\n" +
" /user:\n" +
" post:\n" +
" summary: Create user\n" +
" description: This can only be done by the logged in user.\n" +
" operationId: createUser\n" +
" requestBody:\n" +
" description: Created user object\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" application/xml:\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" required: true\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" 'application/json': {}\n" +
" 'application/xml': {}\n" +
" /user/createUserWithReturnType:\n" +
" post:\n" +
" summary: Create user with return type\n" +
" description: This can only be done by the logged in user.\n" +
" operationId: createUserWithReturnType\n" +
" requestBody:\n" +
" description: Created user object\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" application/xml:\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" required: true\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" application/xml:\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" /user/createUserWithResponseAnnotation:\n" +
" post:\n" +
" summary: Create user with response annotation\n" +
" description: This can only be done by the logged in user.\n" +
" operationId: createUserWithResponseAnnotation\n" +
" requestBody:\n" +
" description: Created user object\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" application/xml:\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" required: true\n" +
" responses:\n" +
" 200:\n" +
" description: aaa\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" application/xml:\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" /user/createUserWithReturnTypeAndResponseAnnotation:\n" +
" post:\n" +
" summary: Create user with return type and response annotation\n" +
" description: This can only be done by the logged in user.\n" +
" operationId: createUserWithReturnTypeAndResponseAnnotation\n" +
" requestBody:\n" +
" description: Created user object\n" +
" content:\n" +
" application/json:\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" application/xml:\n" +
" schema:\n" +
" $ref: '#/components/schemas/User'\n" +
" required: true\n" +
" responses:\n" +
" 200:\n" +
" description: aaa\n" +
"components:\n" +
" schemas:\n" +
" User:\n" +
" type: object\n" +
" properties:\n" +
" id:\n" +
" type: integer\n" +
" format: int64\n" +
" username:\n" +
" type: string\n" +
" firstName:\n" +
" type: string\n" +
" lastName:\n" +
" type: string\n" +
" email:\n" +
" type: string\n" +
" password:\n" +
" type: string\n" +
" phone:\n" +
" type: string\n" +
" userStatus:\n" +
" type: integer\n" +
" description: User Status\n" +
" format: int32\n" +
" xml:\n" +
" name: User";
compareAsYaml(SimpleUserResource.class, expectedYAML);
}
@Test(description = "reads and skips the hidden user resource")
public void testHiddenUserResource() {
String openApiYAML = readIntoYaml(HiddenUserResource.class);
assertEquals(openApiYAML, "openapi: 3.0.1\n");
}
@Test(description = "reads and skips the hidden user resource")
public void testHiddenAnnotatedUserResource() throws IOException {
String openApiYAML = readIntoYaml(HiddenAnnotatedUserResource.class);
assertEquals(openApiYAML, "openapi: 3.0.1\n");
compareAsYaml(HiddenAnnotatedUserResource.HiddenAnnotatedUserResourceMethodAndData.class, "openapi: 3.0.1\n" +
"paths:\n" +
" /user/2:\n" +
" post:\n" +
" summary: Create user\n" +
" description: This can only be done by the logged in user.\n" +
" operationId: createUserWithHiddenBeanProperty\n" +
" requestBody:\n" +
" description: Created user object\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/UserResourceBean'\n" +
" required: true\n" +
" responses:\n" +
" default:\n" +
" description: default response\n" +
" content:\n" +
" 'application/json': {}\n" +
" 'application/xml': {}\n" +
"components:\n" +
" schemas:\n" +
" UserResourceBean:\n" +
" type: object\n" +
" properties:\n" +
" foo:\n" +
" type: string");
}
@Test
public void testSimpleGetOperationWithSecurity() {
String openApiYAML = readIntoYaml(SimpleGetOperationWithSecurity.class);
int start = openApiYAML.indexOf("get:");
int end = openApiYAML.length() - 1;
String expectedYAML = "get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs and a complex\n" +
" operationId: getWithNoParameters\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" security:\n" +
" - petstore-auth:\n" +
" - write:pets";
String extractedYAML = openApiYAML.substring(start, end);
assertEquals(expectedYAML, extractedYAML);
}
static class SimpleGetOperationWithSecurity {
@Operation(
summary = "Simple get operation",
description = "Defines a simple get operation with no inputs and a complex",
operationId = "getWithNoParameters",
responses = {
@ApiResponse(
responseCode = "200",
description = "voila!")
},
security = @SecurityRequirement(
name = "petstore-auth",
scopes = "write:pets"))
@GET
@Path("/path")
public void simpleGet() {
}
}
@Test
public void testSimpleGetOperationWithMultipleSecurity() {
String openApiYAML = readIntoYaml(SimpleGetOperationWithMultipleSecurityScopes.class);
int start = openApiYAML.indexOf("get:");
int end = openApiYAML.length() - 1;
String expectedYAML = "get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs and a complex\n" +
" operationId: getWithNoParameters\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" security:\n" +
" - petstore-auth:\n" +
" - write:pets\n" +
" - read:pets";
String extractedYAML = openApiYAML.substring(start, end);
assertEquals(extractedYAML, expectedYAML);
}
static class SimpleGetOperationWithMultipleSecurityScopes {
@Operation(
summary = "Simple get operation",
description = "Defines a simple get operation with no inputs and a complex",
operationId = "getWithNoParameters",
responses = {
@ApiResponse(
responseCode = "200",
description = "voila!")
},
security = @SecurityRequirement(
name = "petstore-auth",
scopes = {"write:pets", "read:pets"}))
@GET
@Path("/path")
public void simpleGet() {
}
}
@Test
public void testSimpleGetOperationWithMultipleSecurityAnnotations() {
String openApiYAML = readIntoYaml(SimpleGetOperationWithMultipleSecurityAnnotations.class);
int start = openApiYAML.indexOf("get:");
int end = openApiYAML.length() - 1;
String expectedYAML = "get:\n" +
" summary: Simple get operation\n" +
" description: Defines a simple get operation with no inputs and a complex\n" +
" operationId: getWithNoParameters\n" +
" responses:\n" +
" 200:\n" +
" description: voila!\n" +
" security:\n" +
" - review-auth:\n" +
" - write:review\n" +
" - petstore-auth:\n" +
" - write:pets\n" +
" - read:pets\n" +
" - api_key: []";
String extractedYAML = openApiYAML.substring(start, end);
assertEquals(extractedYAML, expectedYAML);
}
static class SimpleGetOperationWithMultipleSecurityAnnotations {
@SecurityRequirement(name = "review-auth", scopes = {"write:review"})
@Operation(
summary = "Simple get operation",
description = "Defines a simple get operation with no inputs and a complex",
operationId = "getWithNoParameters",
responses = {
@ApiResponse(
responseCode = "200",
description = "voila!")
},
security = {@SecurityRequirement(
name = "petstore-auth",
scopes = {"write:pets", "read:pets"}),
@SecurityRequirement(
name = "api_key",
scopes = {}),})
@GET
@Path("/path")
public void simpleGet() {
}
}
}
<file_sep>package io.swagger.v3.jaxrs2.resources;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Arrays;
@Path("/bookstore")
public class BookStoreTicket2646 {
@Produces({ MediaType.APPLICATION_JSON })
@GET
public Response getBooks(
@QueryParam("page") @DefaultValue("1") int page) {
return Response.ok(
Arrays.asList(
new Book(),
new Book()
)
).build();
}
@Produces({ MediaType.APPLICATION_JSON })
@Path("/{id}")
@GET
public Book getBook(@PathParam("id") Long id) {
return new Book();
}
@Path("/{id}")
@DELETE
public Response delete(@PathParam("id") String id) {
return Response.ok().build();
}
public static class Book {
public String foo;
}
}<file_sep>package io.swagger.v3.core.serialization;
import io.swagger.v3.core.converter.ModelConverters;
import io.swagger.v3.core.matchers.SerializationMatchers;
import io.swagger.v3.core.oas.models.Person;
import io.swagger.v3.core.util.ResourceUtils;
import io.swagger.v3.core.util.TestUtils;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;
import io.swagger.v3.oas.models.security.*;
import io.swagger.v3.oas.models.servers.Server;
import org.testng.annotations.Test;
import java.io.IOException;
public class SecurityDefinitionTest {
@Test(description = "it should serialize correctly security")
public void serializeSecurity() throws IOException {
final OpenAPI oas = TestUtils.deserializeJsonFileFromClasspath("specFiles/securityDefinitions.json", OpenAPI.class);
final String json = ResourceUtils.loadClassResource(getClass(), "specFiles/securityDefinitions.json");
SerializationMatchers.assertEqualsToJson(oas, json);
}
@Test(description = "it should create a model with security requirements")
public void createModelWithSecurityRequirements() throws IOException {
final Schema personModel = ModelConverters.getInstance().read(Person.class).get("Person");
final Schema errorModel = ModelConverters.getInstance().read(Error.class).get("Error");
final Info info = new Info()
.version("1.0.0")
.title("Swagger Petstore");
final Contact contact = new Contact()
.name("Swagger API Team")
.email("<EMAIL>")
.url("http://swagger.io");
info.setContact(contact);
final OpenAPI oas = new OpenAPI()
.info(info)
.addServersItem(new Server()
.url("http://petstore.swagger.io"))
.schema("Person", personModel)
.schema("Error", errorModel);
oas.schemaRequirement("githubAccessCode",
new SecurityScheme()
.flows(new OAuthFlows()
.authorizationCode(new OAuthFlow()
.scopes(new Scopes().addString("user:email", "Grants read access to a user’s email addresses.")))));
final Operation get = new Operation()
.summary("finds pets in the system")
.description("a longer description")
.addTagsItem("Pet Operations")
.operationId("get pet by id");
get.addParametersItem(new Parameter()
.in("query")
.name("tags")
.description("tags to filter by")
.required(false)
.schema(new StringSchema()));
get.addParametersItem(new Parameter()
.in("path")
.name("petId")
.description("pet to fetch")
.schema(new IntegerSchema().format("int64")));
final ApiResponse response = new ApiResponse()
.description("pets returned")
.content(new Content().addMediaType("*/*", new MediaType().schema(new Schema().$ref("Person"))));
final ApiResponse errorResponse = new ApiResponse()
.description("error response")
.content(new Content().addMediaType("*/*", new MediaType().schema(new Schema().$ref("Error"))));
get.responses(new ApiResponses()
.addApiResponse("200", response)
.addApiResponse("default", errorResponse))
.addSecurityItem(new SecurityRequirement()
.addList("internal_oauth2", "user:email"))
.addSecurityItem(new SecurityRequirement()
.addList("api_key"));
oas.path("/pets", new PathItem().get(get));
final String json = ResourceUtils.loadClassResource(getClass(), "ModelWithSecurityRequirements.json");
SerializationMatchers.assertEqualsToJson(oas, json);
}
}
<file_sep>/**
* Copyright 2017 SmartBear Software
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.swagger.v3.oas.annotations.security;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
/**
* The annotation may be applied at class or method level, or in {@link io.swagger.v3.oas.annotations.Operation#security()} ()} to define security requirements for the
* single operation (when applied at method level) or for all operations of a class (when applied at class level).
* <p>It can also be used in {@link io.swagger.v3.oas.annotations.OpenAPIDefinition#security()} to define spec level security.</p>
*
* @see <a target="_new" href="https://github.com/OAI/OpenAPI-Specification/blob/3.0.1/versions/3.0.1.md#securityRequirementObject">Security Requirement (OpenAPI specification)</a>
* @see io.swagger.v3.oas.annotations.OpenAPIDefinition
* @see io.swagger.v3.oas.annotations.Operation
**/
@Target({METHOD, TYPE, ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(SecurityRequirements.class)
@Inherited
public @interface SecurityRequirement {
/**
* This name must correspond to a declared SecurityRequirement.
*
* @return String name
*/
String name();
/**
* If the security scheme is of type "oauth2" or "openIdConnect", then the value is a list of scope names required for the execution.
* For other security scheme types, the array must be empty.
*
* @return String array of scopes
*/
String[] scopes() default {};
}
<file_sep>package io.swagger.v3.core.deserialization;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.media.ObjectSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.testng.Assert.*;
public class ObjectPropertyTest {
@Test(description = "convert a model with object properties")
public void readModelWithObjectProperty() throws IOException {
String json = "{" +
" \"properties\":{" +
" \"id\":{" +
" \"type\":\"string\"" +
" }," +
" \"someObject\":{" +
" \"type\":\"object\"," +
" \"x-foo\": \"vendor x\"," +
" \"properties\":{" +
" \"innerId\":{" +
" \"type\":\"string\"" +
" }" +
" }" +
" }" +
" }" +
"}";
Schema model = Json.mapper().readValue(json, Schema.class);
Schema p = (Schema) model.getProperties().get("someObject");
assertTrue(p instanceof ObjectSchema);
ObjectSchema op = (ObjectSchema) p;
Schema sp = op.getProperties().get("innerId");
assertTrue(sp instanceof StringSchema);
assertTrue(op.getExtensions() != null);
assertNotNull(op.getExtensions().get("x-foo"));
assertEquals(op.getExtensions().get("x-foo"), "vendor x");
}
}
<file_sep>package io.swagger.v3.jaxrs2;
import io.swagger.v3.jaxrs2.resources.model.ListOfStringsBeanParam;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.testng.Assert;
import org.testng.annotations.Test;
import javax.ws.rs.BeanParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import java.util.List;
public class BeanParamTest {
@Path("/")
private static class MyBeanParamResource {
@GET
public String getWithBeanParam(@BeanParam ListOfStringsBeanParam listOfStringsBean) {
return "result";
}
}
@Test(description = "check array type of serialized BeanParam containing QueryParams") // tests issue #2466
public void shouldSerializeTypeParameter() {
OpenAPI openApi = new Reader(new OpenAPI()).read(MyBeanParamResource.class);
List<Parameter> getOperationParams = openApi.getPaths().get("/").getGet().getParameters();
Assert.assertEquals(getOperationParams.size(), 1);
Parameter param = getOperationParams.get(0);
Assert.assertEquals(param.getName(), "listOfStrings");
Schema<?> schema = param.getSchema();
// These are the important checks:
Assert.assertEquals(schema.getClass(), ArraySchema.class);
Assert.assertEquals(((ArraySchema) schema).getItems().getType(), "string");
}
}<file_sep>package io.swagger.v3.jaxrs2.resources;
import io.swagger.v3.jaxrs2.resources.model.Pet;
import io.swagger.v3.oas.annotations.Operation;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
@Path("test")
@Produces(MediaType.APPLICATION_JSON)
public class TestResource {
@Path("/status")
@GET
@Operation(description = "Get status")
public String getStatus() {
return "{\"status\":\"OK!\"}";
}
@Path("/more")
@Operation(description = "Get more")
@Produces({MediaType.APPLICATION_XML})
public TestSubResource getSubResource(
@QueryParam("qp") Integer qp) {
return new TestSubResource();
}
@Path("/evenmore")
@Operation(description = "Get even more")
@Produces({MediaType.APPLICATION_XML})
@Consumes(MediaType.APPLICATION_JSON)
public TestSubResource getEvenMoreSubResource(Pet pet) {
return new TestSubResource();
}
}
<file_sep>/**
* Copyright 2017 SmartBear Software
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.swagger.v3.oas.annotations.links;
import io.swagger.v3.oas.annotations.extensions.Extension;
import io.swagger.v3.oas.annotations.servers.Server;
import java.lang.annotation.*;
/**
* The annotation may be applied in {@link io.swagger.v3.oas.annotations.responses.ApiResponse#links()} to add OpenAPI links to a response.
*
* @see <a target="_new" href="https://github.com/OAI/OpenAPI-Specification/blob/3.0.1/versions/3.0.1.md#linkObject">Link (OpenAPI specification)</a>
* @see io.swagger.v3.oas.annotations.responses.ApiResponse
**/
@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Link {
/**
* The name of this link.
*
* @return the link's name
**/
String name() default "";
/**
* A relative or absolute reference to an OAS operation. This field is mutually exclusive of the operationId field, and must point to an Operation Object. Relative operationRef values may be used to locate an existing Operation Object in the OpenAPI definition. Ignored if the operationId property is specified.
*
* @return an operation reference
**/
String operationRef() default "";
/**
* The name of an existing, resolvable OAS operation, as defined with a unique operationId. This field is mutually exclusive of the operationRef field.
*
* @return an operation ID
**/
String operationId() default "";
/**
* Array of parameters to pass to an operation as specified with operationId or identified via operationRef.
*
* @return the list of parameters for this link
**/
LinkParameter[] parameters() default {};
/**
* A description of the link. CommonMark syntax may be used for rich text representation.
*
* @return the link's description
**/
String description() default "";
/**
* A literal value or {expression} to use as a request body when calling the target operation.
*
* @return the request body of this link
**/
String requestBody() default "";
/**
* An alternative server to service this operation.
*
* @return the server associated to this link
**/
Server server() default @Server;
/**
* The list of optional extensions
*
* @return an optional array of extensions
*/
Extension[] extensions() default {};
/**
* A reference to a link defined in components links.
*
* @since 2.0.3
* @return the reference
**/
String ref() default "";
}
<file_sep>package io.swagger.v3.oas.models;
public class OpenAPIBuilderOptions {
// THUAN - Configurations - Miscellaneous
public static boolean USE_FULLNAME = false; // include package name in schemas
public static boolean USE_ENUMNAME = false; // use Enum's name() instead of toString()
public static boolean OMIT_GENERIC = false; // remove generic part in schemas' name
public static boolean RECYCLE_ENUM = false; // make enums reusable
public static boolean HIDE_PARENTS = false; // hide all properties from ancestors provided in allOf
}
<file_sep>package io.swagger.test;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.swagger.v3.oas.models.*;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.links.Link;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.parameters.QueryParameter;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;
import io.swagger.v3.oas.models.tags.Tag;
import org.testng.annotations.Test;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class SimpleBuilderTest {
@Test
public void testBuilder() throws Exception {
// basic metadata
OpenAPI oai =
new OpenAPI()
.info(new Info()
.contact(new Contact()
.email("<EMAIL>")
.name("<NAME>")
.url("https://foo.bar")))
.externalDocs(new ExternalDocumentation()
.description("read more here")
.url("http://swagger.io"))
.addTagsItem(new Tag()
.name("funky dunky")
.description("all about neat things"))
.extensions(new HashMap<String, Object>() {{
put("x-fancy-extension", "something");
}});
Map<String, Schema> schemas = new HashMap<>();
schemas
.put("StringSchema", new StringSchema()
.description("simple string schema")
.minLength(3)
.maxLength(100)
.example("it works")
);
schemas.put("IntegerSchema", new IntegerSchema()
.description("simple integer schema")
.multipleOf(new BigDecimal(3))
.minimum(new BigDecimal(6))
);
oai.components(new Components()
.schemas(schemas));
schemas.put("Address", new Schema()
.description("address object")
.addProperties("street", new StringSchema()
.description("the street number"))
.addProperties("city", new StringSchema()
.description("city"))
.addProperties("state", new StringSchema()
.description("state")
.minLength(2)
.maxLength(2))
.addProperties("zip", new StringSchema()
.description("zip code")
.pattern("^\\d{5}(?:[-\\s]\\d{4})?$")
.minLength(2)
.maxLength(2))
.addProperties("country", new StringSchema()
._enum(new ArrayList<String>() {{
this.add("US");
}}))
.description("2-digit country code")
.minLength(2)
.maxLength(2)
);
oai.paths(new Paths()
.addPathItem("/foo", new PathItem()
.description("the foo path")
.get(new Operation()
.addParametersItem(new QueryParameter()
.description("Records to skip")
.required(false)
.schema(new IntegerSchema()
))
.responses(new ApiResponses()
.addApiResponse("200", new ApiResponse()
.description("it worked")
.content(new Content()
.addMediaType("application/json",
new MediaType().schema(new Schema()
.$ref("#/components/schemas/Address")))
)
.link("funky", new Link()
.operationId("getFunky")))
)
)
)
);
System.out.println(writeJson(oai));
}
public static String writeJson(Object value) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.writer(new DefaultPrettyPrinter()).writeValueAsString(value);
}
}
<file_sep>/**
* Copyright 2016 SmartBear Software
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.swagger.v3.jaxrs2.resources;
import io.swagger.v3.jaxrs2.resources.data.PetData;
import io.swagger.v3.jaxrs2.resources.exception.NotFoundException;
import io.swagger.v3.jaxrs2.resources.model.Category;
import io.swagger.v3.jaxrs2.resources.model.Pet;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
@Consumes("application/json")
@Path("/pet")
@Produces({"application/json", "application/xml"})
public class PetResource {
static PetData petData = new PetData();
@GET
@Path("/{petId}")
@Operation(summary = "Find pet by ID",
description = "Returns a pet when 0 < ID <= 10. ID > 10 or nonintegers will simulate API error conditions",
responses = {
@ApiResponse(
description = "The pet", content = @Content(
schema = @Schema(implementation = Pet.class)
)),
@ApiResponse(responseCode = "400", description = "Invalid ID supplied"),
@ApiResponse(responseCode = "404", description = "Pet not found")
})
public Response getPetById(
@Parameter(description = "ID of pet that needs to be fetched"/*, _enum = "range[1,10]"*/, required = true)
@PathParam("petId") Long petId) throws NotFoundException {
Pet pet = petData.getPetById(petId);
if (null != pet) {
return Response.ok().entity(pet).build();
} else {
throw new NotFoundException(404, "Pet not found");
}
}
@POST
@Consumes({"application/json", "application/xml"})
@Operation(summary = "Add a new pet to the store",
responses = {
@ApiResponse(responseCode = "405", description = "Invalid input")
})
public Response addPet(
@Parameter(description = "Pet object that needs to be added to the store", required = true) Pet pet) {
petData.addPet(pet);
return Response.ok().entity("SUCCESS").build();
}
@POST
@Path("/bodynoannotation")
@Consumes({"application/json", "application/xml"})
@Produces({"application/json", "application/xml"})
@Operation(summary = "Add a new pet to the store no annotation",
responses = {
@ApiResponse(responseCode = "405", description = "Invalid input")
})
public Response addPetNoAnnotation(Pet pet) {
petData.addPet(pet);
return Response.ok().entity("SUCCESS").build();
}
@POST
@Path("/bodyid")
@Consumes({"application/json", "application/xml"})
@Operation(summary = "Add a new pet to the store passing an integer with generic parameter annotation",
responses = {
@ApiResponse(responseCode = "405", description = "Invalid input")
})
public Response addPetByInteger(
@Parameter(description = "Pet object that needs to be added to the store", required = true) int petId) {
return Response.ok().entity("SUCCESS").build();
}
@POST
@Path("/bodyidnoannotation")
@Consumes({"application/json", "application/xml"})
@Operation(summary = "Add a new pet to the store passing an integer without parameter annotation",
responses = {
@ApiResponse(responseCode = "405", description = "Invalid input")
})
public Response addPetByIntegerNoAnnotation(int petId) {
return Response.ok().entity("SUCCESS").build();
}
@PUT
@Operation(summary = "Update an existing pet",
responses = {
@ApiResponse(responseCode = "400", description = "Invalid ID supplied"),
@ApiResponse(responseCode = "404", description = "Pet not found"),
@ApiResponse(responseCode = "405", description = "Validation exception")})
public Response updatePet(
@Parameter(description = "Pet object that needs to be added to the store", required = true) Pet pet) {
petData.addPet(pet);
return Response.ok().entity("SUCCESS").build();
}
@GET
@Path("/findByStatus")
@Produces("application/xml")
@Operation(summary = "Finds Pets by status",
description = "Multiple status values can be provided with comma separated strings",
responses = {
@ApiResponse(
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = Pet.class))),
@ApiResponse(
responseCode = "400", description = "Invalid status value"
)}
)
public Response findPetsByStatus(
@Parameter(description = "Status values that need to be considered for filter", required = true/*, defaultValue = "available", allowableValues = "available,pending,sold", allowMultiple = true*/) @QueryParam("status") String status,
@BeanParam QueryResultBean qr
) {
return Response.ok(petData.findPetByStatus(status)).build();
}
@GET
@Path("/findByCategory/{category}")
@Produces("application/xml")
@Operation(summary = "Finds Pets by category",
responses = {
@ApiResponse(
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = Pet.class))),
@ApiResponse(
responseCode = "400", description = "Invalid category value"
)}
)
public Response findPetsByCategory(
@Parameter(description = "Category value that need to be considered for filter", required = true) @MatrixParam("category") Category category,
@BeanParam QueryResultBean qr
) {
return Response.ok(petData.findPetByCategory(category)).build();
}
@GET
@Path("/findByTags")
@Produces("application/json")
@Operation(summary = "Finds Pets by tags",
description = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.",
responses = {
@ApiResponse(description = "Pets matching criteria",
content = @Content(schema = @Schema(implementation = Pet.class))
),
@ApiResponse(description = "Invalid tag value", responseCode = "400")
})
@Deprecated
public Response findPetsByTags(
@Parameter(description = "Tags to filter by", required = true/*, allowMultiple = true*/) @QueryParam("tags") String tags) {
return Response.ok(petData.findPetByTags(tags)).build();
}
}
<file_sep>package io.swagger.v3.jaxrs2.resources;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Arrays;
@Path("/notnullparameter")
public class Ticket2794Resource
{
@Produces({ MediaType.APPLICATION_JSON })
@GET
public Response getBooks(
@QueryParam("page") @NotNull int page) {
return Response.ok(
Arrays.asList(
new Book(),
new Book()
)
).build();
}
@Path("/new_reqBody_required")
@POST
public Response insert(@RequestBody(required = true) Book book) {
return Response.ok().build();
}
@Path("/newnotnull")
@POST
public Response insertnotnull(@NotNull Book book) {
return Response.ok().build();
}
public static class Book {
public String foo;
}
}<file_sep>package io.swagger.v3.jaxrs2.resources;
import io.swagger.v3.jaxrs2.resources.model.ModelWithJsonIdentity;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
@Path("/pet")
@Produces({"application/json", "application/xml"})
public class JsonIdentityResource {
@POST
@Operation(description = "Add a single object")
public Response test(
@Parameter(required = true) ModelWithJsonIdentity model) {
return Response.ok().entity("SUCCESS").build();
}
}<file_sep>package io.swagger.v3.jaxrs2;
import io.swagger.v3.jaxrs2.annotations.AbstractAnnotationTest;
import io.swagger.v3.jaxrs2.matchers.SerializationMatchers;
import io.swagger.v3.jaxrs2.petstore.EmptyPetResource;
import io.swagger.v3.jaxrs2.petstore.callback.ComplexCallbackResource;
import io.swagger.v3.jaxrs2.petstore.callback.MultipleCallbacksTestWithOperationResource;
import io.swagger.v3.jaxrs2.petstore.callback.RepeatableCallbackResource;
import io.swagger.v3.jaxrs2.petstore.callback.SimpleCallbackWithOperationResource;
import io.swagger.v3.jaxrs2.petstore.example.ExamplesResource;
import io.swagger.v3.jaxrs2.petstore.link.LinksResource;
import io.swagger.v3.jaxrs2.petstore.openapidefintion.OpenAPIDefinitionResource;
import io.swagger.v3.jaxrs2.petstore.operation.*;
import io.swagger.v3.jaxrs2.petstore.parameter.*;
import io.swagger.v3.jaxrs2.petstore.requestbody.RequestBodyMethodPriorityResource;
import io.swagger.v3.jaxrs2.petstore.requestbody.RequestBodyParameterPriorityResource;
import io.swagger.v3.jaxrs2.petstore.requestbody.RequestBodyResource;
import io.swagger.v3.jaxrs2.petstore.responses.*;
import io.swagger.v3.jaxrs2.petstore.security.SecurityResource;
import io.swagger.v3.jaxrs2.petstore.tags.*;
import io.swagger.v3.oas.models.OpenAPI;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.fail;
/**
* Pet Resource Test Class
* Adding a lot of tests of different pet resource examples
*/
public class PetResourceTest extends AbstractAnnotationTest {
private static final String PETSTORE_SOURCE = "petstore/";
private static final String TAGS_SOURCE = "petstore/tags/";
private static final String OPERATIONS_SOURCE = "petstore/operation/";
private static final String CALLBACKS_SOURCE = "petstore/callbacks/";
private static final String RESPONSES_SOURCE = "petstore/responses/";
private static final String PARAMETERS_SOURCE = "petstore/parameters/";
private static final String LINKS_SOURCE = "petstore/links/";
private static final String EXAMPLES_SOURCE = "petstore/example/";
private static final String REQUEST_BODIES_SOURCE = "petstore/requestbody/";
private static final String YAML_EXTENSION = ".yaml";
private static final String PETSTORE_PACKAGE = "io.swagger.v3.jaxrs2.petstore";
private static final char DOT = '.';
private static final char SLASH = '/';
@Test(description = "Test an empty resource class (Without operations or annotations)")
public void testEmptyPetResource() {
compare(EmptyPetResource.class, PETSTORE_SOURCE);
}
@Test(description = "Test a resource with examples)")
public void testExamplesResource() {
compare(ExamplesResource.class, EXAMPLES_SOURCE);
}
@Test(description = "Test a resource with Links)")
public void testLinksResource() {
compare(LinksResource.class, LINKS_SOURCE);
}
@Test(description = "Test some resources with Callbacks)")
public void testCallBacksResources() {
compare(SimpleCallbackWithOperationResource.class, CALLBACKS_SOURCE);
compare(MultipleCallbacksTestWithOperationResource.class, CALLBACKS_SOURCE);
compare(RepeatableCallbackResource.class, CALLBACKS_SOURCE);
compare(ComplexCallbackResource.class, CALLBACKS_SOURCE);
}
@Test(description = "Test some resources with different Operations scenarios)")
public void testOperationsResources() {
compare(HiddenOperationResource.class, OPERATIONS_SOURCE);
compare(OperationWithoutAnnotationResource.class, OPERATIONS_SOURCE);
compare(FullyAnnotatedOperationResource.class, OPERATIONS_SOURCE);
compare(AnnotatedSameNameOperationResource.class, OPERATIONS_SOURCE);
compare(NotAnnotatedSameNameOperationResource.class, OPERATIONS_SOURCE);
compare(ExternalDocumentationResource.class, OPERATIONS_SOURCE);
compare(ServerOperationResource.class, OPERATIONS_SOURCE);
compare(SubResource.class, OPERATIONS_SOURCE);
compare(OperationResource.class, OPERATIONS_SOURCE);
}
@Test(description = "Test OpenAPIDefinition resource)")
public void testOpenAPIDefinitionResource() {
compare(OpenAPIDefinitionResource.class, PETSTORE_SOURCE);
}
@Test(description = "Test RequestBody resource)")
public void tetRequestBodyResource() {
compare(RequestBodyResource.class, REQUEST_BODIES_SOURCE);
compare(RequestBodyParameterPriorityResource.class, REQUEST_BODIES_SOURCE);
compare(RequestBodyMethodPriorityResource.class, REQUEST_BODIES_SOURCE);
}
@Test(description = "Test Parameters resources)")
public void testParametersResource() {
compare(ParametersResource.class, PARAMETERS_SOURCE);
compare(RepeatableParametersResource.class, PARAMETERS_SOURCE);
compare(ArraySchemaResource.class, PARAMETERS_SOURCE);
compare(SingleNotAnnotatedParameter.class, PARAMETERS_SOURCE);
compare(MultipleNotAnnotatedParameter.class, PARAMETERS_SOURCE);
compare(SingleJaxRSAnnotatedParameter.class, PARAMETERS_SOURCE);
compare(OpenAPIJaxRSAnnotatedParameter.class, PARAMETERS_SOURCE);
compare(OpenAPIWithContentJaxRSAnnotatedParameter.class, PARAMETERS_SOURCE);
compare(OpenAPIWithImplementationJaxRSAnnotatedParameter.class, PARAMETERS_SOURCE);
compare(ComplexParameterResource.class, PARAMETERS_SOURCE);
compare(ComplexParameterWithOperationResource.class, PARAMETERS_SOURCE);
}
@Test(description = "Test ApiResponses resource)")
public void testResponsesResource() {
compare(MethodResponseResource.class, RESPONSES_SOURCE);
compare(OperationResponseResource.class, RESPONSES_SOURCE);
compare(NoResponseResource.class, RESPONSES_SOURCE);
compare(ImplementationResponseResource.class, RESPONSES_SOURCE);
compare(NoImplementationResponseResource.class, RESPONSES_SOURCE);
compare(PriorityResponseResource.class, RESPONSES_SOURCE);
compare(ComplexResponseResource.class, RESPONSES_SOURCE);
}
@Test(description = "Test Security resource)")
public void testSecurityResource() {
compare(SecurityResource.class, PETSTORE_SOURCE);
}
@Test(description = "Test Tags resource)")
public void testTagsResource() {
compare(CompleteTagResource.class, TAGS_SOURCE);
compare(TagOpenAPIDefinitionResource.class, TAGS_SOURCE);
compare(TagClassResource.class, TAGS_SOURCE);
compare(TagMethodResource.class, TAGS_SOURCE);
compare(TagOperationResource.class, TAGS_SOURCE);
}
@Test(description = "Test a full set of classes")
public void testSetOfClasses() {
final Reader reader = new Reader(new OpenAPI());
final OpenAPI openAPI = reader.read(getSetOfClassesFromPackage(PETSTORE_PACKAGE));
assertNotNull(openAPI);
try {
SerializationMatchers.assertEqualsToYaml(openAPI, getOpenAPIAsString(PETSTORE_SOURCE + "FullPetResource.yaml"));
} catch (IOException e) {
fail();
}
}
/**
* Extract a set of classes from a package name
*
* @param packageName target to scan the classes
* @return Set<Class>
*/
private Set<Class<?>> getSetOfClassesFromPackage(final String packageName) {
final Set<Class<?>> classSet = new HashSet<>();
try {
final Class[] classes = getClasses(packageName);
for (final Class aClass : classes) {
classSet.add(aClass);
}
} catch (final ClassNotFoundException | IOException e) {
fail();
}
return classSet;
}
/**
* Scans all classes accessible from the context class loader which belong to the given package and subpackages.
*
* @param packageName The base package
* @return The classes
*/
private static Class[] getClasses(final String packageName)
throws ClassNotFoundException, IOException {
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
final String path = packageName.replace(DOT, SLASH);
final Enumeration<URL> resources = classLoader.getResources(path);
final List<File> dirs = new ArrayList<>();
while (resources.hasMoreElements()) {
final URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
}
final ArrayList<Class> classes = new ArrayList<>();
for (final File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
return classes.toArray(new Class[classes.size()]);
}
/**
* Recursive method used to find all classes in a given directory and subdirectories.
*
* @param directory The base directory
* @param packageName The package name for classes found inside the base directory
* @return The classes
*/
private static List<Class> findClasses(final File directory, final String packageName) throws ClassNotFoundException {
final List<Class> classes = new ArrayList<>();
if (!directory.exists()) {
return classes;
}
final File[] files = directory.listFiles();
if (files != null) {
for (final File file : files) {
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + "." + file.getName()));
} else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
}
}
}
return classes;
}
/**
* Compare a class that were read and parsed to a yaml against a yaml file.
*
* @param clazz to read.
* @param source where is the yaml.
*/
private void compare(final Class clazz, final String source) {
final String file = source + clazz.getSimpleName() + YAML_EXTENSION;
try {
compareAsYaml(clazz, getOpenAPIAsString(file));
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
}
<file_sep>package io.swagger.v3.jaxrs2.cdi2;
import io.swagger.v3.jaxrs2.SwaggerSerializers;
import io.swagger.v3.jaxrs2.integration.resources.OpenApiResource;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.testng.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import javax.enterprise.inject.spi.Extension;
import javax.inject.Inject;
public class CDIAutodiscoveryTest extends Arquillian {
@Inject
DiscoveryTestExtension ext;
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(SwaggerSerializers.class)
.addPackage(OpenApiResource.class.getPackage())
.addAsServiceProviderAndClasses(Extension.class, DiscoveryTestExtension.class)
.addAsManifestResource("META-INF/beans.xml");
}
@Test
void confirmPathClassesWereDiscovered() {
String[] expected = {
"io.swagger.v3.jaxrs2.integration.resources.AcceptHeaderOpenApiResource",
"io.swagger.v3.jaxrs2.integration.resources.OpenApiResource"
};
Object[] found = ext.getResources().stream()
.map(resource -> resource.getName())
.sorted()
.toArray();
AssertJUnit.assertArrayEquals(expected, found);
}
@Test
void confirmProviderClassesWereDiscovered() {
String[] expected = {
"io.swagger.v3.jaxrs2.SwaggerSerializers"
};
Object[] found = ext.getProviders().stream()
.map(resource -> resource.getName())
.toArray();
AssertJUnit.assertArrayEquals(expected, found);
}
}
| 6c4d8cfaf7ff30a505f31fcee1bfad9266fcdaa2 | [
"Markdown",
"Java"
] | 32 | Java | duckladydinh/swagger-core | 02f3e5603767f4ff210534703b426f5875f34de2 | 6ede086735114e060be678a1f4fa7bec77693804 | |
refs/heads/master | <repo_name>dktitov/codenames-client<file_sep>/src/store/store.js
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex)
export default new Vuex.Store({
state: {
status: '',
token: localStorage.getItem('token') || '',
user: {},
rooms: {}
},
mutations: {
auth_request(state) {
state.status = 'loading'
},
auth_success(state, payload) {
state.status = 'success'
state.token = payload.token
state.user = payload.user
},
auth_error(state) {
state.status = 'error'
},
logout(state) {
state.status = ''
state.token = ''
},
fetch_rooms_success(state, rooms) {
state.rooms = rooms
},
fetch_room_success(state) {
},
create_room_success(state, room) {
}
},
actions: {
login({ commit }, user) {
return new Promise((resolve, reject) => {
commit('auth_request')
axios({
url: 'http://localhost:3000/login',
data: user,
method: 'POST'
})
.then(resp => {
const user = resp.data.user
const token = resp.data.token
localStorage.setItem('token', token)
axios.defaults.headers.common['Authorization'] = token
commit('auth_success', { token, user })
resolve(resp)
})
.catch(err => {
commit('auth_error')
localStorage.removeItem('token')
reject(err)
})
})
},
register({commit}, user) {
return new Promise((resolve, reject) => {
commit('auth_request')
axios({
url: 'http://localhost:3000/registration',
data: user,
method: 'POST'
})
.then(resp => {
const token = resp.data.token
const user = resp.data.user
localStorage.setItem('token', token)
axios.defaults.headers.common['Authorization'] = token
commit('auth_success', token, user)
resolve(resp)
})
.catch(err => {
commit('auth_error')
localStorage.removeItem('token')
reject(err)
})
})
},
logout({ commit }) {
return new Promise((resolve, reject) => {
commit('logout')
localStorage.removeItem('token')
delete axios.defaults.headers.common['Authorization']
resolve()
})
},
fetchRooms({ commit }) {
return new Promise((resolve, reject) => {
axios({
url: 'http://localhost:3000/rooms',
method: 'GET'
}).then(resp => {
commit('fetch_rooms_success', resp.data)
resolve(resp)
})
})
},
fetchRoom({commit}, id) {
return new Promise((resolve, reject) => {
axios({
url: `http://localhost:3000/rooms/${id}`,
method: 'GET'
}).then(resp => {
commit('fetch_room_success', resp.data)
resolve(resp)
})
})
},
createRoom({commit, getters}, name) {
return new Promise((resolve, reject) => {
console.log(getters)
axios({
url: 'http://localhost:3000/rooms',
data: { name, email: getters.email },
method: 'POST'
}).then(resp => {
commit('create_room_success', resp.data)
resolve(resp)
})
})
}
},
getters: {
isLoggedIn: state => !!state.token,
authStatus: state => state.user.status,
rooms: state => state.rooms,
email: state => state.user.email
}
})
<file_sep>/src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import store from '../store/store'
import Welcome from '@/components/Welcome'
import Login from '@/components/Login'
import Register from '@/components/Register'
import RoomsList from '@/components/RoomsList'
import Room from '@/components/Room'
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'welcome',
component: Welcome
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/register',
name: 'register',
component: Register
},
{
path: '/rooms',
name: 'rooms',
component: RoomsList,
meta: {
requireAuth: true
}
},
{
path: '/rooms/:id',
name: 'room',
component: Room,
meta: {
requireAuth: true
}
}
]
})
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuth)) {
if (store.getters.isLoggedIn) {
next()
return
}
next('/login')
} else {
next()
}
})
export default router | 0f4869e9f3a2e268c0aa1851cb941f7d2cfcbd54 | [
"JavaScript"
] | 2 | JavaScript | dktitov/codenames-client | cbd99eef1c5adbfd2a858a076c6ec8247588bab5 | f31326383bfd2cfa335b78860d4e7d37f21cfea3 | |
refs/heads/main | <repo_name>sagar-cmd/Price-Prediction-Of-Used-Bikes<file_sep>/Prediction.py
from tkinter import *
from tkinter.ttk import *
master = Tk()
master.title('Used Bike Price Estimation Software')
master.geometry("600x600")
base_frame = Frame(master)
base_frame.pack()
wrong_input_lable1 = Label(master)
wrong_input_lable2 = Label(master)
wrong_input_lable3 = Label(master)
wrong_input_lable4 = Label(master)
wrong_input_lable5 = Label(master)
bike_name_options = {"Please select brand": 0, "Bajaj": 4, "Hero": 3, "Honda": 5, "Royal Enfield": 3,
"Suzuki": 6, "TVS": 4, "Yamaha": 4, "Aprilia": 7,
"<NAME>": 5, "Bajaj": 3, "Benelli": 4,
"BMW": 6, "Carberry": 8, "CFMoto": 5, "Ducati": 3,
"Global Automobiles": 6, "Harley-davson": 5,
"Husqvarna": 8, "Hyosung": 4, "Indian": 6,
"Jawa": 4, "Kawasaki": 7, "Kinetic": 8, "KTM": 6, "LML": 2,
"Mahindra": 6, "<NAME>": 8, "Regal Raptor": 5,
"Revolt": 5, "Triumph": 4}
year_of_purchase_list = ['2000', '2001', '2002', '2003',
'2004', '2005', '2006', '2007',
'2008', '2009', '2010', '2011',
'2012', '2013', '2014', '2015',
'2016', '2017', '2018', '2019', ]
State_dictionary = {"Andhra Pradesh": 5, "Andaman Nicobar": 4, "Arunachal Pradesh": 3, "Assam": 5, "Bihar": 5,
"Chandigarh": 5, "Chhattisgarh": 4, "D<NAME>": 3, "Daman n Diu": 5, "Delhi": 5, "Goa": 4,
"Gujarat": 5, "Haryana": 4, "Himachal Pradesh": 3, "Jammu Kashmir": 5, "Jharkhand": 6, "Karnataka": 3,
"Kerala": 5, "Lakshadweep": 4, "Madhya Pradesh": 3, "Maharashtra": 5, "Manipur": 6, "Meghalaya": 4,
"Mizoram": 5, "Nagaland": 4, "Orissa": 3, "Pondicherry": 3, "Punjab": 5, "Rajasthan": 6, "Sikkim": 7,
"Tamil Nadu": 5, "Telangana": 4, "Tripura": 3, "Uttar Pradesh": 5, "Utarakhand": 6, "West Bengal": 6}
def Calculate():
global buy_price, bike_manufacturer, year_purchase, state_from, Kms_driven
buy_price = buy_price*((0.95)**(2020-int(year_purchase)))
buy_price = buy_price - buy_price * \
(bike_name_options[bike_manufacturer]/100)*2
buy_price = buy_price - buy_price*(State_dictionary[state_from]/100)
factor = 5
if Kms_driven >= 500000:
factor = 50
elif Kms_driven >= 100000:
factor = 25
elif Kms_driven >= 50000:
factor = 15
elif Kms_driven >= 30000:
factor = 10
elif Kms_driven >= 20000:
factor = 8
elif Kms_driven >= 10000:
factor = 6
buy_price = buy_price - buy_price*(factor/100)
buy_price = int(buy_price)
def show_new_price(curr_frame):
global buy_price
desc_label = Label(
curr_frame, text='Condition', font=("Helvetica", 10, 'bold'), width=20, borderwidth=10, relief="sunken", anchor=CENTER)
desc_label.grid(row=6, column=0, padx=10, pady=5, sticky=NSEW)
desc_label = Label(
curr_frame, text='Resale value', font=("Helvetica", 10, 'bold'), width=20, borderwidth=10, relief="sunken", anchor=CENTER)
desc_label.grid(row=6, column=1, padx=0, pady=5, sticky=NSEW)
desc_label = Label(
curr_frame, text='Good', font=("Helvetica", 10, 'bold'), width=20, borderwidth=10, relief="sunken", anchor=CENTER)
desc_label.grid(row=7, column=0, padx=10, pady=0, sticky=NSEW)
desc_label = Label(
curr_frame, text=str(buy_price), font=("Helvetica", 10, 'bold'), width=20, borderwidth=10, relief="sunken", anchor=CENTER, foreground="green")
desc_label.grid(row=7, column=1, padx=0, pady=0, sticky=NSEW)
desc_label = Label(
curr_frame, text='Fair', font=("Helvetica", 10, 'bold'), width=20, borderwidth=10, relief="sunken", anchor=CENTER)
desc_label.grid(row=8, column=0, padx=10, pady=0, sticky=NSEW)
desc_label = Label(
curr_frame, text=str(int(buy_price*0.95)), font=("Helvetica", 10, 'bold'), width=20, borderwidth=10, relief="sunken", anchor=CENTER, foreground="#E8AC41")
desc_label.grid(row=8, column=1, padx=0, pady=0, sticky=NSEW)
desc_label = Label(
curr_frame, text='Bad', font=("Helvetica", 10, 'bold'), width=20, borderwidth=10, relief="sunken", anchor=CENTER)
desc_label.grid(row=9, column=0, padx=10, pady=0, sticky=NSEW)
desc_label = Label(
curr_frame, text=str(int(buy_price*0.90)), font=("Helvetica", 10, 'bold'), width=20, borderwidth=10, relief="sunken", anchor=CENTER, foreground="red")
desc_label.grid(row=9, column=1, padx=0, pady=0, sticky=NSEW)
return
def check(curr_frame):
global buy_price, bike_manufacturer, year_purchase, state_from, Kms_driven
global wrong_input_lable1, wrong_input_lable2, wrong_input_lable3, wrong_input_lable4, wrong_input_lable5
flag = TRUE
wrong_input_lable1.grid_forget()
wrong_input_lable2.grid_forget()
wrong_input_lable3.grid_forget()
wrong_input_lable5.grid_forget()
wrong_input_lable4.grid_forget()
try:
buy_price = int(buy_price)
except:
wrong_input_lable1 = Label(
curr_frame, text='*Wrong input', font=("Helvetica", 10), width=25, foreground="red")
wrong_input_lable1.grid(row=1, column=2, padx=6, pady=10, sticky=NSEW)
flag = FALSE
try:
Kms_driven = int(Kms_driven)
except:
wrong_input_lable2 = Label(
curr_frame, text='*Wrong input', font=("Helvetica", 10), width=25, foreground="red")
wrong_input_lable2.grid(row=5, column=2, padx=6, pady=10, sticky=NSEW)
flag = FALSE
if bike_manufacturer == 'Please select brand':
wrong_input_lable3 = Label(
curr_frame, text='*Wrong selection', font=("Helvetica", 10), width=25, foreground="red")
wrong_input_lable3.grid(row=2, column=2, padx=6, pady=10, sticky=NSEW)
flag = FALSE
if year_purchase == 'Please select year':
wrong_input_lable4 = Label(
curr_frame, text='*Wrong selection', font=("Helvetica", 10), width=25, foreground="red")
wrong_input_lable4.grid(row=3, column=2, padx=6, pady=10, sticky=NSEW)
flag = FALSE
if state_from == 'Please select State':
wrong_input_lable5 = Label(
curr_frame, text='*Wrong selection', font=("Helvetica", 10), width=25, foreground="red")
wrong_input_lable5.grid(row=4, column=2, padx=6, pady=10, sticky=NSEW)
flag = FALSE
return flag
def Calculation_page(curr_frame):
def Submit_details():
global buy_price, bike_manufacturer, year_purchase, state_from, Kms_driven
buy_price = price_entry.get()
bike_manufacturer = bike_name_list.get()
year_purchase = year_purchase_list.get()
state_from = state_from_list.get()
Kms_driven = kms_entry.get()
if check(calculation_page):
Calculate()
show_new_price(calculation_page)
curr_frame.forget()
calculation_page = Frame(master)
calculation_page.pack(fill=BOTH, expand=True)
info_lable = Label(
calculation_page, text='Please provide correct details for proper evaluation', font=("Helvetica", 16))
info_lable.grid(row=0, column=0, pady=30, padx=10, columnspan=10, sticky=W)
purchase_price_lable = Label(
calculation_page, text='Please enter purchase price :', font=("Helvetica", 10), width=25)
purchase_price_lable.grid(row=1, column=0, padx=10, pady=5, sticky=W)
price_entry = Entry(calculation_page, width=23)
price_entry.grid(row=1, column=1, pady=5, padx=0, sticky=W)
bike_name_lable = Label(calculation_page, text='Please Select Brand :', font=(
"Helvetica", 10), width=25)
bike_name_lable.grid(row=2, column=0, padx=10, pady=5, sticky=W)
bike_name_list = Combobox(
calculation_page, values=list(bike_name_options), state="readonly")
bike_name_list.set('Please select brand')
bike_name_list.grid(row=2, column=1, pady=10, sticky=W)
year_purchase_lable = Label(
calculation_page, text='Please Select year of purchase :', font=("Helvetica", 10), width=30)
year_purchase_lable.grid(row=3, column=0, padx=10, pady=5, sticky=W)
year_purchase_list = Combobox(
calculation_page, values=year_of_purchase_list, state="readonly")
year_purchase_list.set('Please select year')
year_purchase_list.grid(row=3, column=1, pady=10, sticky=W)
year_purchase_lable = Label(
calculation_page, text='Please select state :', font=("Helvetica", 10), width=25)
year_purchase_lable.grid(row=4, column=0, padx=10, pady=5, sticky=W)
state_from_list = Combobox(calculation_page, values=list(
State_dictionary), state="readonly")
state_from_list.set('Please select State')
state_from_list.grid(row=4, column=1, pady=10, sticky=W)
kms_lable = Label(calculation_page, text='Please enter KM\'s Driven :', font=(
"Helvetica", 10), width=25)
kms_lable.grid(row=5, column=0, padx=10, pady=5, sticky=W)
kms_entry = Entry(calculation_page, width=23)
kms_entry.grid(row=5, column=1, pady=5, padx=0, sticky=W)
Button_back = Button(
calculation_page, text='Previous', width=8, command=lambda: main_page(calculation_page))
Button_back.grid(row=10, column=0, pady=20, sticky=W)
Button_calculate_price = Button(
calculation_page, text='Submit', width=6, command=Submit_details)
Button_calculate_price.grid(row=10, column=1, pady=20, sticky=E)
def history_page(curr_frame):
curr_frame.forget()
main_page = Frame(master)
main_page.pack(fill=BOTH, expand=True)
def main_page(curr_frame):
style = Style()
style.configure('TButton', font=('calibri', 20, 'bold'),
borderwidth='40')
curr_frame.forget()
main_page = Frame(master)
main_page.pack(fill=BOTH, expand=True)
lable = Label(main_page, text='Welcome to bike price estimation software')
lable.grid(row=0, column=0, padx=100, pady=10, sticky=NSEW)
Button_calculate_price = Button(
main_page, text='Check Price', command=lambda: Calculation_page(main_page))
Button_calculate_price.grid(row=1, column=0, pady=10, columnspan=3)
Button_View_History = Button(
main_page, text='History', command=lambda: history_page(main_page))
Button_View_History.grid(row=2, column=0, pady=10, columnspan=3)
Button_exit = Button(main_page, text='Exit', command=master.quit)
Button_exit.grid(row=3, column=0, pady=10, columnspan=3)
main_page(base_frame)
master.mainloop()
<file_sep>/README.md
# Price-Prediction-Of-Used-Bikes
A Python Program for price prediction of used bikes on the basis of Brand name, Kilometres Driven, Manufacturing Year.
| 530535d5203a096c2551d6bf56bdfe435f9fbcab | [
"Markdown",
"Python"
] | 2 | Python | sagar-cmd/Price-Prediction-Of-Used-Bikes | 7f315b8c704b3cad09daed5944d858ba770d3f97 | e861f5e650e0e7d762fa5680c75705c7fb808da4 | |
refs/heads/master | <file_sep>function checkLogin() {
var name = prompt("<NAME> ")
if (name == "Admin"){
var pass = prompt("<NAME>");
if(pass=="<PASSWORD>"){
document.write("Wellcome");
}else if (pass==null){
document.write("Canceled");
}else {
document.write("Wrong password");
}
} else if (name==null) {
document.write("canceled")
}else {
document.write("I don't know you")
}
}
checkLogin(); | 5f1391d8f406cbd486130ae38192b56d34ec52f9 | [
"JavaScript"
] | 1 | JavaScript | KO-KMS-AT12/luyen-tap-if-else-if | f003f49c134d7839f8e959f47a7a2e090dccc52d | 4ca85a7382ae6fbcc99b568930b17f8a34561c49 | |
refs/heads/main | <file_sep>package com.mybatis.sqlsession;
import java.util.List;
import com.mybatis.config.Configuration;
import com.mybatis.config.MappedStatement;
import com.mybatis.executor.CachingExecutor;
import com.mybatis.executor.Executor;
import com.mybatis.executor.SimpleExecutor;
public class DefaultSqlSession implements SqlSession {
private Configuration configuration;
public DefaultSqlSession(Configuration configuration) {
this.configuration = configuration;
}
@SuppressWarnings("unchecked")
@Override
public <T> T selectOne(String statementId, Object param) {
List<Object> list = this.selectList(statementId, param);
if (list == null || list.size() == 0) {
return null;
} else if (list.size() == 1) {
return (T) list.get(0);
} else {
throw new RuntimeException("只能返回一个对象");
}
}
@Override
public <T> List<T> selectList(String statementId, Object param) {
// 根据statementId获取MappedStatement对象
MappedStatement mappedStatement = configuration.getMappedStatementById(statementId);
// 执行Statement的操作(执行方式有多种:一种是带有二级缓存的执行方式、一种是基本执行方式[只带有一级缓存,基本执行方式又分成几种:基本执行器、批处理执行器等])
// 此处可以考虑放到MappedStatement对象中,该对象中可以根据是否配置了二级缓存来确定创建的是哪个Executor
Executor executor = new CachingExecutor(new SimpleExecutor());
return executor.query(mappedStatement, configuration, param);
}
}
<file_sep>package com.mybatis.config;
import com.mybatis.sqlsource.SqlSource;
/**
* 封装select等CRUD标签的信息
*
* @author liu
*
*/
public class MappedStatement {
private String statementId;
private Class<?> parameterTypeClass;
private Class<?> resultTypeClass;
private String statementType;
private SqlSource sqlSource;
public MappedStatement(String statementId, Class<?> parameterTypeClass, Class<?> resultTypeClass,
String statementType, SqlSource sqlSource) {
this.statementId = statementId;
this.parameterTypeClass = parameterTypeClass;
this.resultTypeClass = resultTypeClass;
this.statementType = statementType;
this.sqlSource = sqlSource;
}
public String getStatementId() {
return statementId;
}
public void setStatementId(String statementId) {
this.statementId = statementId;
}
public Class<?> getParameterTypeClass() {
return parameterTypeClass;
}
public void setParameterTypeClass(Class<?> parameterTypeClass) {
this.parameterTypeClass = parameterTypeClass;
}
public Class<?> getResultTypeClass() {
return resultTypeClass;
}
public void setResultTypeClass(Class<?> resultTypeClass) {
this.resultTypeClass = resultTypeClass;
}
public String getStatementType() {
return statementType;
}
public void setStatementType(String statementType) {
this.statementType = statementType;
}
public SqlSource getSqlSource() {
return sqlSource;
}
public void setSqlSource(SqlSource sqlSource) {
this.sqlSource = sqlSource;
}
}
<file_sep>package mybatis.demo.phase02.mapper;
import mybatis.demo.phase02.po.User;
public interface UserMapper {
User findUserById(int id);
}
<file_sep>package com.mybatis.sqlsession;
public interface SqlSessionFactory {
SqlSession openSqlSession();
}
<file_sep>package com.mybatis.sqlnode;
import com.mybatis.sqlsource.DynamicContext;
/**
* 提供对sql脚本的解析
*
* @author liu
*
*/
public interface SqlNode {
void apply(DynamicContext context);
}
<file_sep>package com.mp.entity;
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
@Data
@TableName("permission")
@ApiModel("权限类")
public class Permission implements Serializable {
@ApiModelProperty(name = "id", value = "ID 主键")
@TableId(type = IdType.AUTO)
private String id;
@ApiModelProperty(name = "permissionCode", value = "权限编号")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String permissionCode;
@ApiModelProperty(name = "permissionName", value = "权限名")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String permissionName;
@ApiModelProperty(name = "path", value = "映射路径")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String path;
}<file_sep>package com.mybatis.sqlsource;
import com.mybatis.utils.GenericTokenParser;
import com.mybatis.utils.ParameterMappingTokenHandler;
/**
* 将DynamicSqlSource和RawSqlSource解析成StaticSqlSource
* StaticSqlSource存储的就是只有?的sql语句以及相应的sql信息
*
* @author liu
*
*/
public class SqlSourceParser {
public SqlSource parse(String sqlText) {
ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
GenericTokenParser tokenParser = new GenericTokenParser("#{", "}", tokenHandler);
// tokenParser.parse(sqlText)参数是未处理的,返回值是已处理的(没有${}和#{})
String sql = tokenParser.parse(sqlText);
return new StaticSqlSource(sql, tokenHandler.getParameterMappings());
}
}
<file_sep>package com.mybatis.sqlsource;
/**
* 解析#{}获取到的参数信息,主要包含参数名称(也就是#{}中的名称和参数类型)
* @author liu
*
*/
public class ParameterMapping {
private String name;
private Class<?> type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Class<?> getType() {
return type;
}
public void setType(Class<?> type) {
this.type = type;
}
public ParameterMapping(String name) {
super();
this.name = name;
}
}
<file_sep>package mybatis.demo.phase01.test;
import java.io.InputStream;
import mybatis.demo.phase01.dao.UserDao;
import mybatis.demo.phase01.dao.UserDaoImpl;
import mybatis.demo.phase01.entity.UserEntity;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
/**
* 测试入门案例
*
* @author think
*
*/
public class Test1 {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws Exception{
// 加载全局配置文件(同时把映射文件也加载了)
String resource = "phase01/SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// sqlsessionFactory需要通过sqlsessionFactoryBuilder读取全局配置文件信息之后
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testFindUserById() {
UserDao dao = new UserDaoImpl(sqlSessionFactory);
UserEntity user = dao.findUserById(1);
System.out.println(user);
}
}
<file_sep>package com.mp;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mp.entity.Role;
import com.mp.entity.User;
import com.mp.mapper.RoleMapper;
import com.mp.mapper.UserMapper;
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.junit4.SpringRunner;
import java.util.List;
import java.util.Set;
/**
* 保持和main 目录一致
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class MPTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
// 此处 null 指的是不用根据参数去查询
// 可以调用 CRUD 相关的多种方式
// 1. 查询所有的数据
List<User> userList = userMapper.selectList(null);
userList.forEach(user -> System.out.println(user.getName()));
// 2. 根据 id 删除
userMapper.deleteById(1);
// 3. 添加数据
User user = new User();
user.setName("老王");
user.setEmail("<EMAIL>");
user.setAge(18);
userMapper.insert(user);
// 4. 更新数据
user.setName("老王王");
user.setEmail("<EMAIL>");
userMapper.updateById(user);
}
@Autowired
private RoleMapper roleMapper;
@Test
public void testUserRole() {
User user = userMapper.findUserByName("cuihua");
Set<Role> roles = userMapper.getUserRoles("cuihua");
for (Role role : roles) {
role.setPermissions(roleMapper.
getRolePermissions(role.getRoleCode()));
}
user.setRoles(roles);
System.out.println(user);
}
@Test
public void testSelect2(){
IPage<User> page = selectUserPage();
List<User> userList = page.getRecords();
userList.forEach(user -> System.out.println("用户:" + user));
}
// 查询年龄在 20-30 名字为 cuihua 的用户
public IPage<User> selectUserPage() {
// 不进行 count sql 优化,解决 MP 无法自动优化 SQL 问题,这时候你需要自己查询 count 部分
// page.setOptimizeCountSql(false);
// 当 total 为非 0 时(默认为 0),分页插件不会进行 count 查询
// 要点!! 分页返回的对象与传入的对象是同一个
Page page = new Page<User>(1, 20);
QueryWrapper<User> queryWrapper = new QueryWrapper<User>().between("age", 18, 20).eq("name", "cuihua");
return userMapper.selectPage(page, queryWrapper);
}
}<file_sep>package mybatis.demo.phase02.test;
import java.io.InputStream;
import mybatis.demo.phase02.mapper.UserMapper;
import mybatis.demo.phase02.po.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
/**
* 测试基础应用案例
* @date: 2021/6/4
* @auther: liu
*/
public class Test2 {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws Exception {
// 加载全局配置文件(同时把映射文件也加载了)
String resource = "phase02/SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// sqlsessionFactory需要通过sqlsessionFactoryBuilder读取全局配置文件信息之后
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testFindUserById() {
//创建UserMapper对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//反射获取 mapper JDK 代理实现sqlSession.select
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用UserMapper对象的API
User user = mapper.findUserById(1);
System.out.println(user);
}
}
<file_sep>package mybatis.demo.phase01.dao;
import mybatis.demo.phase01.entity.UserEntity;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
/**
* 后面会通过反射和代理 实现 sqlSession查询
* @date: 2021/6/4
* @auther: liu
*/
public class UserDaoImpl implements UserDao {
private SqlSessionFactory sqlSessionFactory;
// 注入sqlSessionFactory
public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public UserEntity findUserById(int id) {
// sqlsessionFactory工厂类去创建sqlsession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
// sqlsession接口,开发人员使用它对数据库进行增删改查操作 test 来自xml namespace
UserEntity user = sqlSession.selectOne("test.findUserById", id);
return user;
}
}
<file_sep>package com.mp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mp.entity.Role;
import com.mp.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.Set;
/**
* @date: 2021/6/15
* @auther: liu
*/
public interface UserMapper extends BaseMapper<User> {
@Select("select * from user where name = #{name}")
public User findUserByName(String username);
// 获取用户所拥有的角色
@Select("select * from role where rolecode in(select rolecode from userrole where username = #{userName})")
public Set<Role> getUserRoles(String username);
}<file_sep>package mybatis.demo.phase04.test;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import mybatis.demo.phase04.mapper.UserMapper;
import mybatis.demo.phase04.po.User;
import mybatis.demo.phase04.po.UserExample;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
/**
* 测试逆向工程代码和PageHelper分页插件案例
* @date: 2021/6/4
* @auther: liu
*/
public class Test4 {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws Exception {
// 加载全局配置文件(同时把映射文件也加载了)
String resource = "phase04/SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// sqlsessionFactory需要通过sqlsessionFactoryBuilder读取全局配置文件信息之后
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void test() {
// 创建UserMapper对象
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
UserExample example = new UserExample();
List<User> list = mapper.selectByExample(example);
System.out.println(list);
}
@Test
public void test2() {
// 创建UserMapper对象
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//拦截器 注入实现分页,把sql 拼接到语句上
//编写分页代码
PageHelper.startPage(1, 2);
UserExample example = new UserExample();
// 此处返回的list实现类不再是ArrayList,而是PageHelper提供的Page对象
List<User> list = mapper.selectByExample(example);
System.out.println(list);
//转为 page 对象
PageInfo<User> pageInfo = new PageInfo<User>(list);
System.out.println(pageInfo);
}
}
<file_sep>package com.mybatis.sqlnode.handler;
import java.util.List;
import org.dom4j.Element;
import com.mybatis.sqlnode.SqlNode;
/**
* 针对不同子标签进行处理,处理之后,封装到对应的SqlNode对象中
*
* 比如if标签被处理之后,会封装到IfSqlNode对象中
*
* @author liu
*
*/
public interface NodeHandler {
/**
* 处理非文本节点
* @param nodeToHandle 待处理子节点
* @param contents 处理之后的节点集合
*/
void handleNode(Element nodeToHandle, List<SqlNode> contents);
}
<file_sep>package com.mybatis.config;
import java.util.List;
import org.dom4j.Element;
public class XMLMapperParser {
private Configuration configuration;
public XMLMapperParser(Configuration configuration) {
this.configuration = configuration;
}
/**
*
* @param rootElement
* <mapper namespace="test">
*/
@SuppressWarnings("unchecked")
public void parse(Element rootElement) {
String namespace = rootElement.attributeValue("namespace");
// mapper标签下会包含一些sql片段标签、resultMap标签等,这些标签直接解析处理,而statement相关的标签单独处理
//此处可以使用XPath语法来进行通配
List<Element> elements = rootElement.elements("select");
for (Element selectElement : elements) {
// select update delete insert 都对应一个statement
XMLStatementParser scriptParser = new XMLStatementParser(configuration);
scriptParser.parseStatement(selectElement,namespace);
}
}
}
<file_sep>package com.mp;
/**
* @Date: 2021/6/15
* @author: liu
*/
/**
* 如果mapper 不在主方法同级包下,需要MapperScan
*/
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.mp.mapper")
public class AppRun {
public static void main(String[] args) {
SpringApplication.run(AppRun.class, args);
}
}<file_sep>db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/yuque?characterEncoding=utf-8
db.username=root
db.password=<PASSWORD><file_sep>package com.mybatis.config;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
public class Configuration {
private DataSource dataSource;
private Map<String, MappedStatement> mappedStatements = new HashMap<String, MappedStatement>();
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void setMappedStatement(String statementId, MappedStatement mappedStatement) {
mappedStatements.put(statementId, mappedStatement);
}
public MappedStatement getMappedStatementById(String statementId) {
return mappedStatements.get(statementId);
}
}
<file_sep>package com.mybatis.executor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.mybatis.config.Configuration;
import com.mybatis.config.MappedStatement;
/**
* 基本执行器,主要处理一级缓存
*
* @author liu
*
*/
public abstract class BaseExecutor implements Executor {
private Map<String, List<Object>> oneLevelCache = new HashMap<String, List<Object>>();
@SuppressWarnings("unchecked")
@Override
public <T> List<T> query(MappedStatement mappedStatement, Configuration configuration, Object param) {
// 获取带有值的sql语句
String sql = mappedStatement.getSqlSource().getBoundSql(param).getSql();
// 从一级缓存去根据sql语句获取查询结果
List<Object> result = oneLevelCache.get(sql);
if (result != null) {
return (List<T>) result;
}
// 如果没有结果,则调用相应的处理器去处理
result = queryFromDataBase(mappedStatement, configuration, param);
oneLevelCache.put(sql, result);
return (List<T>) result;
}
public abstract List<Object> queryFromDataBase(MappedStatement mappedStatement, Configuration configuration,
Object param);
}
<file_sep>package com.mp.entity;
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
@Data
@TableName("rolePermission")
@ApiModel("角色权限关系类")
public class RolePermission implements Serializable {
@ApiModelProperty(name = "id", value = "ID 主键")
@TableId(type = IdType.AUTO)
private String id;
@ApiModelProperty(name = "roleCode", value = "角色编号")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Integer roleCode;
@ApiModelProperty(name = "permission", value = "权限编号")
@TableField(fill = FieldFill.INSERT_UPDATE)
private String permissionCode;
}<file_sep>package com.mybatis.executor;
import java.util.List;
import com.mybatis.config.Configuration;
import com.mybatis.config.MappedStatement;
/**
* 处理二级缓存
*
* @author liu
*
*/
public class CachingExecutor implements Executor {
// 基本执行器
private Executor delegate;
public CachingExecutor(Executor delegate) {
super();
this.delegate = delegate;
}
@Override
public <T> List<T> query(MappedStatement mappedStatement, Configuration configuration, Object param) {
// 从二级缓存中根据sql语句获取处理结果(二级缓存怎么存?????)
// 如果有,则直接返回,如果没有则继续委托给基本执行器去吃力
return delegate.query(mappedStatement, configuration, param);
}
}
<file_sep>/*
Navicat Premium Data Transfer
Source Server : 本地
Source Server Type : MySQL
Source Server Version : 50730
Source Host : localhost:3306
Source Schema : mybatis-plus
Target Server Type : MySQL
Target Server Version : 50730
File Encoding : 65001
Date: 15/06/2021 10:28:45
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for permission
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`permissioncode` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '权限编号',
`permissionname` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '权限名字',
`path` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '映射路径',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of permission
-- ----------------------------
INSERT INTO `permission` VALUES (1, '111', '随便乱来', NULL);
INSERT INTO `permission` VALUES (2, '222', '偶尔乱来', NULL);
INSERT INTO `permission` VALUES (3, '333', '小小乱来', NULL);
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`rolecode` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色编号',
`rolename` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色名字',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES (1, '001', '总裁');
INSERT INTO `role` VALUES (2, '002', '院长');
INSERT INTO `role` VALUES (3, '003', '组长');
-- ----------------------------
-- Table structure for rolepermission
-- ----------------------------
DROP TABLE IF EXISTS `rolepermission`;
CREATE TABLE `rolepermission` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`rolecode` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色编号',
`permissioncode` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '权限编号',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of rolepermission
-- ----------------------------
INSERT INTO `rolepermission` VALUES (1, '001', '111');
INSERT INTO `rolepermission` VALUES (2, '002', '222');
INSERT INTO `rolepermission` VALUES (3, '003', '333');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`NAME` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '姓名',
`age` int(11) NULL DEFAULT NULL COMMENT '年龄',
`email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'cuihua', 18, '<EMAIL>');
INSERT INTO `user` VALUES (2, 'huahua', 20, '<EMAIL>');
INSERT INTO `user` VALUES (3, 'cunhua', 28, '<EMAIL>');
INSERT INTO `user` VALUES (4, 'laowang', 21, '<EMAIL>');
INSERT INTO `user` VALUES (5, 'xiaomei', 24, '<EMAIL>');
-- ----------------------------
-- Table structure for userrole
-- ----------------------------
DROP TABLE IF EXISTS `userrole`;
CREATE TABLE `userrole` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`username` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户名',
`rolecode` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色编号',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of userrole
-- ----------------------------
INSERT INTO `userrole` VALUES (1, 'cuihua', '001');
INSERT INTO `userrole` VALUES (2, 'chunhua', '003');
INSERT INTO `userrole` VALUES (3, 'huahua', '002');
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>package com.mybatis.sqlsource;
import com.mybatis.sqlnode.MixedSqlNode;
import com.mybatis.sqlnode.SqlNode;
/**
* 专门封装和处理带有${}和动态sql标签的sql语句
*
* @author liu
*
*/
public class DynamicSqlSource implements SqlSource {
private SqlNode rootSqlNode;
public DynamicSqlSource(MixedSqlNode rootSqlNode) {
this.rootSqlNode = rootSqlNode;
}
/**
* 在sqlsession执行的时候,才调用该方法
*/
@Override
public BoundSql getBoundSql(Object param) {
//首先先调用SqlNode的处理,将动态标签和${}处理一下
DynamicContext context = new DynamicContext(param);
rootSqlNode.apply(context);
// 再调用SqlSourceParser来处理#{}
SqlSourceParser sqlSourceParser = new SqlSourceParser();
SqlSource sqlSource = sqlSourceParser.parse(context.getSql());
return sqlSource.getBoundSql(param);
}
}
<file_sep>/*
Navicat Premium Data Transfer
Source Server : 本地
Source Server Type : MySQL
Source Server Version : 50730
Source Host : localhost:3306
Source Schema : yuque
Target Server Type : MySQL
Target Server Version : 50730
File Encoding : 65001
Date: 15/06/2021 10:29:41
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`birthday` datetime(0) NULL DEFAULT NULL,
`sex` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '张三', '2021-06-04 12:33:38', '男', '河北');
INSERT INTO `user` VALUES (2, '李四', '2021-06-04 13:01:36', '男', '北京');
INSERT INTO `user` VALUES (3, '王五', '2021-06-04 13:13:19', '男', '上海');
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>package com.mybatis.sqlnode;
import com.mybatis.sqlsource.DynamicContext;
import com.mybatis.utils.OgnlUtils;
public class IfSqlNode implements SqlNode {
/**
* 布尔表达式
*/
private String test;
// 子SqlNode集合
private SqlNode rootSqlNode;
public IfSqlNode(String test, SqlNode rootSqlNode) {
this.test = test;
this.rootSqlNode = rootSqlNode;
}
@Override
public void apply(DynamicContext context) {
// 使用Ognl的api来对test标签属性中的布尔表达式进行处理,获取布尔值
boolean evaluateBoolean = OgnlUtils.evaluateBoolean(test, context.getBindings().get("_parameter"));
// 如果test标签属性中的表达式判断为true,才进行子节点的处理
if (evaluateBoolean) {
rootSqlNode.apply(context);
}
}
}
<file_sep>package com.mybatis.sqlnode;
import com.mybatis.sqlsource.DynamicContext;
import com.mybatis.utils.GenericTokenParser;
import com.mybatis.utils.OgnlUtils;
import com.mybatis.utils.SimpleTypeRegistry;
import com.mybatis.utils.TokenHandler;
public class TextSqlNode implements SqlNode {
private String sqlText;
public TextSqlNode(String sqlText) {
this.sqlText = sqlText;
}
/**
* 要处理${} 比如说username like '%${username}' 入参username=“zhangsan” 处理之后username
* like '%zhangsan'
*/
@Override
public void apply(DynamicContext context) {
TokenHandler tokenHandler = new BindingTokenParser(context);
GenericTokenParser tokenParser = new GenericTokenParser("${", "}", tokenHandler);
// tokenParser.parse(sqlText)参数是未处理的,返回值是已处理的(没有${})
context.appendSql(tokenParser.parse(sqlText));
}
public boolean isDynamic() {
if (sqlText.indexOf("${") > -1) {
return true;
}
return false;
}
private static class BindingTokenParser implements TokenHandler {
private DynamicContext context;
public BindingTokenParser(DynamicContext context) {
this.context = context;
}
/**
* expression:比如说${username},那么expression就是username username也就是Ognl表达式
*/
@Override
public String handleToken(String expression) {
Object paramObject = context.getBindings().get("_parameter");
if (paramObject == null) {
// context.getBindings().put("value", null);
return "";
} else if (SimpleTypeRegistry.isSimpleType(paramObject.getClass())) {
// context.getBindings().put("value", paramObject);
return String.valueOf(paramObject);
}
// 使用Ognl api去获取相应的值
Object value = OgnlUtils.getValue(expression, context.getBindings());
String srtValue = value == null ? "" : String.valueOf(value);
return srtValue;
}
}
}
<file_sep># yuque
与语雀文档同步,前后端知识库所对应的相关代码
| 0eaaec94d4f1385ce30cb87aa38f0a84aa20efc3 | [
"Markdown",
"Java",
"SQL",
"INI"
] | 28 | Java | quanzhanlaoliu/yuque | cfb48ff9f0ba750b4f22f9a45606cb59d2a4b267 | c7a0f9fdfffd8bcac7788b6d427d7e9ea825a3cc | |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
import re
import os
import time
def APP_traffic(App_name):
if App_name.find(':') != -1 or App_name.find('/') != -1:
print 'error'
raise ValueError('App_name error')
a = os.popen('adb shell ps').readlines()
lis = []
for k in xrange(len(a)):
if a[k].find('%s'%(App_name)) != -1 and a[k].find(':') == -1 and a[k].find('/') == -1:
for x in a[k].split(' '):
if x != '':
lis.append(x)
Pid = lis[1]
break
lis = []
b = os.popen('adb shell cat /proc/%s/status'%(Pid)).readlines()
for k in xrange(len(b)):
if b[k].find('Uid:') != -1:
for x in b[k].split('\t'):
lis.append(x)
Uid = lis[1]
break
#发送数据
data = os.popen('adb shell cat /proc/uid_stat/%s/tcp_snd'%(Uid)).readlines()
tcp_snd = re.findall(r'\d+',''.join(data[0]))
#接收数据
data = os.popen('adb shell cat /proc/uid_stat/%s/tcp_rcv'%(Uid)).readlines()
tcp_rcv = re.findall(r'\d+',''.join(data[0]))
data_dict = { 'tcp_snd':int(''.join(tcp_snd)),
'tcp_rcv':int(''.join(tcp_rcv)),
'Pid':Pid,
'Uid':Uid }
return data_dict
def link():
#Check the connection status
link = ''.join(os.popen('adb devices').readlines()[1])
#print link
try:
assert link.find('device') !=- 1,u'error'
except:
print 'off line'
raise ValueError('off line')
if __name__ == '__main__':
all_snd = []
all_rcv = []
name = 'com.tencent.tmgp.sgame'
t = 600
try:
import sys,getopt
opts, args = getopt.getopt(sys.argv[1:], "hp:t:c:d:l:")
for op, value in opts:
if op == '-p':
#print value
name = value
if op == '-t':
#print value
t = value
if op == '-l':
path1 = value + 'data_%s'%( str(time.strftime("%m%d", time.localtime())))
except:
raise ValueError('error')
try:
os.makedirs('%s'%(path1))
except:
pass
print name
print 'start!'
#Check the connection status
link()
a = APP_traffic(name)
start_snd = float(a['tcp_snd']) / 1024
start_rcv = float(a['tcp_rcv']) / 1024
time.sleep(1)
for T in range(int(t)):
try:
link()
except:
break
print T+1
a = APP_traffic(name)
end_snd = float(a['tcp_snd']) / 1024
end_rcv = float(a['tcp_rcv']) / 1024
all_snd.append(float('%.2f'%(end_snd - start_snd)))
all_rcv.append(float('%.2f'%(end_rcv - start_rcv)))
print 'tcp_snd:' ,'%.2f'%(end_snd - start_snd) ,'KB'
print 'tcp_rcv:' ,'%.2f'%(end_rcv - start_rcv) ,'KB'
start_snd = end_snd
start_rcv = end_rcv
time.sleep(0.5)
print 'snd + ',sum(all_snd)
print 'rcv + ',sum(all_rcv)
print '生成数据文件...'
tiems = time.strftime("%m%d-%H%M%S", time.localtime())
File = open( r'%s'%(path1) + r'\Data_Flow_Data%s.txt'%(tiems),'w')
#File = open( 'c:\Data_Flow_Data%s.txt'%(tiems) ,'w')
File.write( 'SND' + ' ' + 'RCV' + '\n' )
for i in range( len(all_snd) ):
File.write( str(all_snd[i]) + ';' + str(all_rcv[i]) + '\n' )
File.close()
<file_sep># -*- coding: utf-8 -*-
import os
import time
import re
def CPU(app_name='',path='c:/'):
def Log_file(data):
try:
print u'Generate data files...'
tiems = time.strftime("%m%d-%H%M%S", time.localtime())
File = open( r'%s'%(path) + r'\CpuData%s.txt'%(tiems),'w' )
for i in range(len(data)):
File.write(str(data[i])+'\n')
File.close()
print u'Save the file successfully'
except:
print 'Save file failed'
cut_formula = re.compile(r'\s+')
#存放CPU数据的数组
cpu_array = []
try:
#增加变量来控制找不到包名后不要过早报错
p = 0
#增加变量控制每10次循环检查一遍连接
i = 0
while 1>0:
if i == 0:
link = ''.join(os.popen('adb devices').readlines()[1])
try:
#表达式=-1说明没找到设备
assert link.find('device')!=-1,u'error'
#循环N次后检查连接
i = 10
except:
print 'Equipment broken links'
raise ValueError('Equipment broken linksd')
#i 减到 0 检查一次连接
i = i - 1
a = os.popen('adb shell top -m 80 -n 1 -s cpu').readlines()
#print a
for i in range(len(a)):
if ''.join(a[i]).find('%s'%app_name) != -1 and ''.join(a[i]).find(':') == -1:
b = ''.join(a[i])
#print b
#连接成功就重置控制变量P
p = 0
break
# i 是从0开始的
elif i == len(a)-1:
#重连5次后报错
if p == 5:
print('No app detected')
raise ValueError('No app detected')
else:
p = p + 1
print 'disconnect',p
# re.sub(): b 中的 空格符 替换成“?” ,分割字符串 b
#a b c->a?b?c
#a?b?c->['a','b','c']
#print '1',b
try:
if p == 0:
b = ''.join(re.sub(cut_formula,'?', b)).split('?')
#print '2',b
for k in b:
if k.find('%') != -1:
k = re.match(r'\d+',k).group()
cpu_array.append(k)
print k,'%'
except:
if p == 5:
raise ValueError('b')
else:
p = p + 1
time.sleep(1)
except:
print 'Device or file can not be found'
Log_file(cpu_array)
if __name__ == '__main__':
import sys,getopt
opts, args = getopt.getopt(sys.argv[1:], "hp:t:c:d:l:")
for op, value in opts:
if op == '-p':
#print value
Name = value
if op == '-t':
#print value
T = value
if op == '-l':
path1 = value + 'data_%s'%(str(time.strftime("%m%d", time.localtime())))
try:
os.makedirs('%s'%(path1))
except:
pass
CPU(app_name = Name ,path = path1)
<file_sep># -*-coding: utf-8 -*-
import os
from uiautomator import Device
import subprocess
import time
import sys, getopt
def record_and_untied(b,x,y,a):
#2000000
os.popen('adb shell am force-stop %s'%(a))
child = subprocess.Popen('adb shell screenrecord --bit-rate 6000000 /sdcard/record%d.mp4'%(b))
time.sleep(1)
d.click(x, y)
time.sleep(2)
d.press("home")
time.sleep(0.5)
child.kill()
child.wait()
time.sleep(1)
os.makedirs( r'%s'%(path1) + r'\%d'%(b))
print 'mkdir-'*20
child = subprocess.Popen(['adb','pull','sdcard/record%d.mp4'%(b), r'%s'%(path1) + r'\%d.mp4'%(b)])
child.wait()
ffmpeg_path = os.path.split(os.path.realpath(__file__))[0] + '\\ffmpeg.exe'
subprocess.Popen('%s'%(ffmpeg_path) + r' -i %s\%d.mp4 -f image2 -vf fps=fps=50 %s\%d'%(path1,b,path1,b)+r'/%d.jpg')
if b == 3:
time.sleep(10)
sys.exit(0)
else:
child.wait()
if __name__ == '__main__':
global path1
opts, args = getopt.getopt(sys.argv[1:], "hp:t:c:d:l:")
for op, value in opts:
if op == '-c':
X = int(value.split(',')[0])
Y = int(value.split(',')[1])
if op == '-d':
#print value
PHONE_ID = value
if op == '-l':
times = '\\jiezhen' + str(time.strftime("%m%d-%H%M%S", time.localtime()))
path1 = value + 'data_%s'%(str(time.strftime("%m%d", time.localtime()))) + times
if op == '-p':
app = value
d = Device(PHONE_ID)
print X,Y
print d.info
try:
pass
#os.makedirs( r'%s'%(path1) + r'\jiezhen')
except:
pass
for k in xrange(1,4):
record_and_untied(k, X, Y,a=app)<file_sep># -*- coding: utf-8 -*-
import re
#import pylab as pl
import os
import time
import sys,getopt
def Pss():
try:
opts, args = getopt.getopt(sys.argv[1:], "hp:t:c:d:l:")
for op, value in opts:
if op == '-p':
#print value
Name = value
if op == '-t':
#print value
T = value
if op == '-l':
path1 = value + 'data_%s'%(str(time.strftime("%m%d", time.localtime())))
except:
Name = 'com.taobao.idlefish'
T = 1800
path1 = r'F:\Jenkins\workspace\Performance_Testing'
raise ValueError('error')
try:
os.makedirs('%s'%(path1))
except:
pass
system_version = ''.join(os.popen('adb shell getprop ro.build.version.release').readlines())
system_version = int( ''.join(system_version.split('.')[:2]) )
print system_version
pss = []
try:
for jc in range(int(T)):
link=''.join(os.popen('adb devices').readlines()[1])
try:
assert link.find('device') !=- 1,u'error'
except:
print '连接失败'
break
a=''.join(os.popen('adb shell dumpsys meminfo %s'%Name).readlines())
if system_version <= 70:
#安卓7.0及以下
a=a.split('\r\n')
else:
#安卓7.1
a=a.split('\n')
for ck in a:
if ck.find('TOTAL') != -1 and ck.find(':') == -1:
p=re.findall(r'\d+',ck)
print p[0]
pss.append(int(p[0]))
print jc + 1
time.sleep(0.40)
print '录制完毕,正在处理...'
except:
print 'error'
#x=range(0,len(pss))
print '生成数据文件...'
tiems = time.strftime("%m%d-%H%M%S", time.localtime())
File = open( r'%s'%(path1) + r'\PssData%s.txt'%(tiems),'w' )
for i in range(len(pss)):
#File.write(str(x[i])+' '+str(pss[i])+'\n')
File.write(str(pss[i])+'\n')
File.close()
#print type(pss[0])
avg = sum(pss) / len(pss)
print 'average:',avg
'''
print '生成图表...'
pl.xlabel('')
pl.ylabel('P S S')
pl.title('P S S Graphic')
pl.plot(x,pss,'y')#这个是pss
pl.show()
'''
if __name__=='__main__':
s = time.time()
Pss()
e = time.time()
print 'time:',e-s<file_sep>import subprocess
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "hp:t:c:d:l:")
except:
pass
try:
import urllib3
except:
child = subprocess.Popen('python -m pip install urllib3 --trusted-host 10.75.22.30 -i http://10.75.22.30:8088/123/')
child.wait()
try:
import uiautomator
except:
child = subprocess.Popen('python -m pip install uiautomator --trusted-host 10.75.22.30 -i http://10.75.22.30:8088/123/')
child.wait()
<file_sep># -*- coding: utf-8 -*-
import re
#import pylab as pl
import os
import time
import gc
def Fps(T,Name,path2):
print "请确保开发者选项中的GPU呈现模式分析 调整正确"
system_version = ''.join(os.popen('adb shell getprop ro.build.version.release').readlines())
system_version = int( ''.join(system_version.split('.')[:1]) )
print system_version
if system_version < 5:
lv=3
else:
lv=4
n=[]
for jc in range(int(T)):
link=''.join(os.popen('adb devices').readlines()[1])
try:
assert link.find('device')!=-1,u'error'
except:
print '连接失败'
break
print jc+1
c=''
a=''.join(os.popen('adb shell dumpsys gfxinfo %s'%Name).readlines())
a=a.split('\n')
for i in a:
if i.lower().islower() == False:
c=c+i+'\n'
n.append(re.findall(r'\d+\.\d+',c))
#print n
del a
del c
gc.collect()
time.sleep(1.65)
s=[]
for m in n:
for mm in m:
s.append(mm)
del n
gc.collect()
e=[]
k=0
for i in range(len(s)):
if (i+1)%lv==0:
k=k+float(s[i])
e.append(float('%.2f'%k))
k=0
else:
k=k+float(s[i])
'''
x=range(0,len(e))
sta=[]
for i in range(len(e)):
sta.append(16)
'''
print '生成数据文件...'
tiems = time.strftime("%m%d-%H%M%S", time.localtime())
File = open( r'%s'%(path2) + r'\FpsData%s.txt'%(tiems),'w')
for i in range(len(e)):
#File.write(str(x[i])+' '+str(e[i])+'\n')
File.write(str(e[i])+'\n')
File.close()
'''
print '生成图表...'
pl.xlabel('')
pl.ylabel('F P S')
pl.title('F P S Graphic')
pl.plot(x,e,'y')#这个是FPS
pl.plot(x,sta,'r')#这个是16ms线
pl.show()
'''
if __name__=='__main__':
name =''
t = ''
try:
import sys,getopt
opts, args = getopt.getopt(sys.argv[1:], "hp:t:c:d:l:")
for op, value in opts:
if op == '-p':
#print value
name = value
if op == '-t':
#print value
t = value
if op == '-l':
path1 = value + 'data_%s'%( str(time.strftime("%m%d", time.localtime())))
except:
print 'error'
name = 'com.taobao.idlefish'
t = 180
raise ValueError('error')
try:
os.makedirs('%s'%(path1))
except:
pass
Fps(t,name,path1) | 02571c6468ed8d4d56c03613d8eda07a54e47ec7 | [
"Python"
] | 6 | Python | ctro15547/neicun | 8175b22453999578ec5fe69f334af6790e9a9ba9 | 5273375189fe74e716ff68277d6015a6f9386e32 | |
refs/heads/master | <file_sep>// imports
var mergeTrees = require('broccoli-merge-trees');
var concat = require('broccoli-concat');
// var compileSass = require('broccoli-sass');
var compileES6 = require('broccoli-jstransform');
var pickFiles = require('broccoli-static-compiler');
// trees
// grab my styles in sass module
// var styles = compileSass(['app/scss/'], 'style.scss', '/assets/styles.css');
var styles = concat(
'app/scss',{
inputFiles: ['*.scss'],
outputFile: '/brocoli/assets/style.scss'
});
// grab my scripts
var scripts = compileES6('app/scripts', [
'es6-arrow-function',
'es6-class',
'es6-destructuring',
'es6-object-concise-method',
'es6-object-short-notation',
'es6-rest-param',
'es6-template',
'es7-spread-property',
'reserved-words']);
// grap any static assets
var public = pickFiles('app/html', {
srcDir: '.',
destDir: '.'
});
// merge all trees:
module.exports = mergeTrees([scripts, styles, public]); <file_sep># trynode
npm install
Brocoli:
# to get node_modules
npm install broccoli-cli --global
npm install --save-dev broccoli
<file_sep>// #1 - 10 octets
var buf = new Buffer(10);
// #2
var buf2 = new Buffer([10, 20, 30, 40, 50]);
// #3
var buf = new Buffer("Simply Easy Learning", "utf-8");
// json
var buf = new Buffer('Simply Easy Learning');
var json = buf.toJSON(buf);
console.log(json);
// string buffer
var buffer1 = new Buffer('TutorialsPoint ');
var buffer2 = new Buffer('Simply Easy Learning');
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 content: " + buffer3.toString());
// STREAMS
var fs = require("fs");
var data = '';
// Create a readable stream
var readerStream = fs.createReadStream('input2.txt');
// Set the encoding to be utf8.
readerStream.setEncoding('UTF8');
// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
data += chunk;
console.log("wyciagam dane chunk: " + chunk);
});
readerStream.on('end',function(){
console.log("koniec danych: wypisuje");
console.log(data);
});
readerStream.on('error', function(err){
console.log(err.stack);
});
console.log("Program Ended");
/// Jest jeszcze piping i inne nudne operacje na systemie plikow
// __ o z tym są globalnymi zmiennymi
console.log( __filename );
console.log( __dirname );
// oczywiscie to wcyaiagnie plikow jest callbackami wiec pojawi sie zawsze w kolejnce na koncu :/
// jakby te callbacki jeszcze wziac w taka funkcje to do tego wszystkiego mozna spowolnic
// wszystko, tak aby nie dosc ze bylo ostatnie to jeszcze wywolalo sie po wszystkim :/
function printHello(){
console.log( "Hello, World!");
}
setTimeout(printHello, 2000);
function dawajPozniej(){
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Sync");
}
console.log("Bez timeoutu");
fs.readFile('input.txt', function(err, data){
console.log(data.toString());
console.log("ASync");
});
dawajPozniej();
console.log("Koniec bez timeoutu");
console.log("Z timeoutem");
setTimeout(dawajPozniej, 2000);
fs.readFile('input.txt', function(err, data){
console.log(data.toString());
console.log("ASync");
});
console.log("Koniec z timeoutem");
// Ok czyli mozna synchroniczne przlozyc "ZA" asynchronicznymi za pomocą timeoutu
//A jakby usunac ten timeout
console.log("Z timeoutem");
var t = setTimeout(dawajPozniej, 2000);
fs.readFile('input.txt', function(err, data){
console.log(data.toString());
console.log("ASync");
});
clearTimeout(t);
console.log("Koniec z timeoutem");
// To sie nic nie wypisze <file_sep>var EventEmitter = require("events").EventEmitter;
var domain = require("domain");
var child = domain.create();
var emitter = new EventEmitter();
child.on('error', function(err){
console.log("child handled an error: " + err.message);
});
// explicit binding
child.add(emitter);
emitter.on('error', function(err){
console.log("listener on emitter shows error: " + err.message);
});
emitter.emit('error', new Error('Will be handled by listener'));
emitter.removeAllListeners('error');
emitter.emit('error', new Error('Will be handled by child'));
var child2 = domain.create();
child2.on('error', function(err){
console.log("domain2 handled this error ("+err.message+")");
});
child2.run(function(){
var emitter2 = new EventEmitter();
emitter2.emit('error',new Error('To be handled by child2'));
});
child.remove(emitter);
emitter.emit('error', new Error("Crash!"));<file_sep>var events = require('events');
var eventEmitter = new events.EventEmitter();
var eventHandler = function connect(){
console.log("Connection succesful");
console.log('INSIDE CONNECTION HANDLER');
eventEmitter.emit('data_received');
}
//Binding
eventEmitter.on('connection', eventHandler);
//
eventEmitter.on('data_received', function(){
console.log('INSIDE DATA R HANDLER');
console.log('data received succesfully');
});
console.log('EMITING CONNECTION');
eventEmitter.emit('connection');
console.log('End');<file_sep>var fs = require("fs");
// synchroniczne otwieranie plików
var data = fs.readFileSync('input.txt');
data.toString();
console.log("Nara 1");
// asynchroniczne otwieranie plików
// callback - asynchroniczna wersja synchronicznej funkcji
fs.readFile('input2.txt', function(err, data){
console.log("2file");
data.toString();
});
fs.readFile('input.txt', function(err, data){
console.log("1file");
data.toString();
});
// wniosek nie wazne ile synchronicznych polecen w glownych watkach mamy
// to i tak one zawsze przejdą jako pierwsze chocby wypadalo aby asynchroniczne
// dzialania zostaly wywolane w miedzyczasie
// -- suabo -- | dc8b7c06aa5f80b131d8a2932de35fbfdd0afce7 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | kkucharc/trynode | 60a4fa40723131b191ad4695760ca910f9d7b812 | 36b3dc4816366e109d8de1c4f5561c9c4fbdf211 | |
refs/heads/master | <repo_name>DDuunk/ECG-Device<file_sep>/README.md
# ECG-Device
Hardware code for a ECG device, see [ECG-App](https://github.com/DDuunk/ECG-App/) for the app used in this project.
<file_sep>/src/ECG/main.cpp
#include "main.h"
void error(const __FlashStringHelper*err) {
Serial.println(err);
while (1);
}
void setup() {
Serial.begin(SERIAL_BAUD_RATE);
pinMode(LO_POSITIVE, INPUT);
pinMode(LO_NEGATIVE, INPUT);
Serial.println(F("Adafruit Bluefruit Command <-> Data Mode Example"));
Serial.println(F("------------------------------------------------"));
/* Initialise the module */
Serial.print(F("Initialising the Bluefruit LE module: "));
if (!ble.begin(VERBOSE_MODE)) {
error(F("Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?"));
}
Serial.println(F("OK!"));
/* Perform a factory reset to make sure everything is in a known state */
Serial.println(F("Performing a factory reset: "));
if (!ble.factoryReset()) {
error(F("Couldn't factory reset"));
}
/* Disable command echo from Bluefruit */
ble.echo(false);
Serial.println("Requesting Bluefruit info:");
/* Print Bluefruit information */
ble.info();
Serial.println(F("Please use Adafruit Bluefruit LE app to connect in UART mode"));
Serial.println(F("Then Enter characters to send to Bluefruit"));
ble.verbose(false); // debug info is a little annoying after this point!
// Set module to DATA mode
Serial.println(F("Switching to DATA mode!"));
ble.setMode(BLUEFRUIT_MODE_DATA);
}
void loop() {
if((digitalRead(LO_POSITIVE) == 1) || (digitalRead(LO_NEGATIVE) == 1)) {
Serial.println(F("!"));
delay(1000);
} else {
Serial.print(F("Updating HRM value to "));
Serial.print((analogRead(AD8232_INPUT)));
Serial.println("\r");
Serial.println(F(" BPM"));
ble.print((analogRead(AD8232_INPUT)));
ble.println();
}
delay(1);
}<file_sep>/src/ECG/main.h
#ifndef MAIN_H
#define MAIN_H
#include "Arduino.h"
#include <SPI.h>
#include "Adafruit_BLE.h"
#include "Adafruit_BluefruitLE_SPI.h"
#include "Adafruit_BluefruitLE_UART.h"
#define SERIAL_BAUD_RATE 115200
/**
* AD8232 Settings
*/
#define LO_POSITIVE 3
#define LO_NEGATIVE 4
#define AD8232_INPUT A0
/**
* Adafruit Bluefruit UART Settings
*/
int32_t hrmServiceId;
int32_t hrmMeasureCharId;
int32_t hrmLocationCharId;
boolean success;
#define BUFSIZE 128 // Size of the read buffer for incoming data
#define VERBOSE_MODE true // If set to 'true' enables debug output
#define BLUEFRUIT_SWUART_RXD_PIN 9 // Required for software serial!
#define BLUEFRUIT_SWUART_TXD_PIN 10 // Required for software serial!
#define BLUEFRUIT_UART_CTS_PIN 11 // Required for software serial!
#define BLUEFRUIT_UART_RTS_PIN 8 // Optional, set to -1 if unused
#define BLUEFRUIT_UART_MODE_PIN 12 // Set to -1 if unused
#ifdef Serial1 // this makes it not complain on compilation if there's no Serial1
#define BLUEFRUIT_HWSERIAL_NAME Serial1
#endif
SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);
Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN, BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);
#endif //MAIN_H | 26881d8e7e9ab5dcca4ace492f7ecaa45bdd2fa6 | [
"Markdown",
"C",
"C++"
] | 3 | Markdown | DDuunk/ECG-Device | 8eb9d35f9736891173bb79e5d334843f424d576b | a86f427616eaf705f57cc88c41b0cbb24fc87db4 | |
refs/heads/master | <repo_name>SantiagoRMJ/mySql_project<file_sep>/app.js
const express = require('express');
const mysql = require('mysql2/promise');
const app = express();
const cors = require('cors')
app.use(express.json());
const routerUser = require('./routers/router_usuarios');
const routerCitas = require('./routers/router_citas');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'clinicaDental_db',
password: '<PASSWORD>'
})
//CORS
app.use(cors())
app.use('/usuario', routerUser);
app.use('/citas', routerCitas);
const PORT = process.env.PORT || 4000
app.listen(PORT, ()=> console.log('Servidor levantado en' + PORT));
['unhandledRejection', 'uncaughtException'].forEach(event => process.on(event, (err) => {
console.error(`unhandled error: ${err.stack || err}`);
}));<file_sep>/routers/router_usuarios.js
const router = require('express').Router();
const services_usuarios = require('../services/services_usuarios.js');
router.post('/user', services_usuarios.registro);
router.get('/userlogin', services_usuarios.login);
module.exports = router;<file_sep>/routers/router_citas.js
const router = require('express').Router();
const service_citas = require('../services/services_citas');
router.get('/', service_citas.listarCitas);
router.get('/pending', service_citas.citasPendientes );
router.delete('/', service_citas.cancelarCita);
router.post('/', service_citas.crearCita);
module.exports = router;<file_sep>/services/services_usuarios.js
const sequelize = require('../models/index.js');
exports.registro = async (req, res) =>{
let user = await user.create({
nombre: req.body.nombre,
apellidos: req.body.apellidos,
nacimiento: req.body.nacimiento,
telefono: req.body.telefono,
direccion: req.body.direccion,
covid: req.body.covid,
password: <PASSWORD>,
email: req.body.email,
dni: req.body.dni
})
res.json({"message": 'usuario creado'});
};
exports.login = async (req, res)=>{
const{user, password} = req.body;
if(!user || !password) return res.json({error: 'faltan datos'});
const data = await users.find(e => e.user === user && e.password === <PASSWORD>);
if(!data) return res.json({error: 'ningún usuario coincide con tu usuario y contraseña'});
return data;
};
<file_sep>/services/services_citas.js
const sequelize = require('../models/index.js');
exports.crearCita = async (req, res) =>{
const {cliente_id, fecha, observaciones, precio, estado} = req.body;
await sequelize.query(`INSERT INTO CITAS (cliente_id, fecha, observaciones, precio, estado)
VALUES ('${cliente_id}', '${fecha}', '${observaciones}', '${precio}', '${estado}')`, {type: sequelize.QueryTypes.INSERT})
return (citas => res.json(citas))
}
exports.listarCitas = async (req, res) =>{
await sequelize.findAll(citas => res.json(citas))
return citas
}
exports.citasPendientes = async (req, res) =>{
await sequelize.query("SELECT * FROM CITAS WHERE estado = 'Pendiente'", {type: sequelize.QueryTypes.SELECT})
return (citas => res.json(citas));
}
exports.cancelarCita = async(req, res) =>{
const id = req.body;
await sequelize.query(`DELETE FROM CITAS WHERE id_cliente = ${id}`, {type: sequelize.QueryTypes.DELETE})
return (citas => res.json(citas))
}
| 5c1929ac28e5a47e21457cff38765be6d3f80d27 | [
"JavaScript"
] | 5 | JavaScript | SantiagoRMJ/mySql_project | 1c76d74220cd70acb8df59a4f9b8d303b2d99c02 | d303c762bc7ddaf27a3402b7a079242bc23bcf9d | |
refs/heads/master | <file_sep>#!/usr/bin/python3
import os
import numpy as np
from asaplib.data import ASAPXYZ
from asaplib.compressor import Sparsifier
def main():
"""
Select frames from the supplied xyz file (fxyz) using one of the following algorithms:
1. random: random selection
2. fps: farthest point sampling selection. Need to supply a kernel matrix or descriptor matrix using -fmat
4. CUR decomposition
Parameters
----------
fxyz: Path to xyz file.
fmat: Path to the design matrix or name of the tags in ase xyz file
prefix: Filename prefix, default is ASAP
nkeep: The number of representative samples to select
algorithm: 'the algorithm for selecting frames ([random], [fps], [cur])')
fmat: Location of descriptor or kernel matrix file. Needed if you select [fps] or [cur].
"""
fxyz = os.path.join(os.path.split(__file__)[0], 'small_molecules-SOAP.xyz')
fmat = ['SOAP-n4-l3-c1.9-g0.23']
nkeep = 10
prefix = "test-frame-select"
# read the xyz file
asapxyz = ASAPXYZ(fxyz)
# for both algo we read in the descriptor matrix
desc, _ = asapxyz.get_descriptors(fmat)
print("shape of the descriptor matrix: ", np.shape(desc), "number of descriptors: ", np.shape(desc[0]))
for algorithm in ['random', 'cur', 'fps']:
sparsifier = Sparsifier(algorithm)
sbs = sparsifier.sparsify(desc, nkeep)
# save
selection = np.zeros(asapxyz.get_num_frames(), dtype=int)
for i in sbs:
selection[i] = 1
np.savetxt(prefix + "-" + algorithm + "-n-" + str(nkeep) + '.index', selection, fmt='%d')
asapxyz.write(prefix + "-" + algorithm + "-n-" + str(nkeep), sbs)
def test_gen(tmpdir):
"""Test the generation using pytest"""
main()
if __name__ == '__main__':
main()
<file_sep>from os import path
import ase.io
import numpy as np
from dscribe.descriptors import SOAP
from pytest import approx, raises, fail
from asaplib.reducedim import KernelPCA
def assert_array_almost_equal(first, second, tol=1e-7):
first = np.array(first)
second = np.array(second)
assert first.shape == second.shape
if np.isnan(first).any():
fail('Not a number (NaN) found in first array')
if np.isnan(second).any():
fail('Not a number (NaN) found in second array')
try:
assert first == approx(second, abs=tol)
except AssertionError:
absdiff = abs(first - second)
if np.max(absdiff) > tol:
print('First array:\n{}'.format(first))
print('\n \n Second array:\n{}'.format(second))
print('\n \n Abs Difference:\n{}'.format(absdiff))
fail('Maximum abs difference between array elements is {} at location {}'.format(np.max(absdiff),
np.argmax(absdiff)))
class TestKPCA(object):
@classmethod
def setup_class(cls):
# todo: add docs for these
test_folder = path.split(__file__)[0]
fn = path.abspath(path.join(test_folder, "ice_test.xyz"))
at_train = ase.io.read(fn, '0')
at_test = ase.io.read(fn, '1')
soap_desc = SOAP(species=['H', 'O'], rcut=4., nmax=6, lmax=6, sigma=0.3, periodic=True)
desc_train = soap_desc.create(at_train)
desc_test = soap_desc.create(at_test)
cls.K_tr = np.dot(desc_train, desc_train.T) ** 2
cls.K_test = np.dot(desc_test, desc_train.T) ** 2
cls.K_tr_save = cls.K_tr.copy()
cls.K_test_save = cls.K_test.copy()
# references:
cls.ref_pvec_train = np.array([[-3.22200775e+00, 9.59025264e-01, 2.57486105e-03, -1.31988525e-02],
[-3.21541214e+00, 9.64409232e-01, 1.82008743e-03, 3.45230103e-02],
[-2.88484693e+00, -9.90488589e-01, 7.56590813e-03, -7.28607178e-03],
[-2.88778687e+00, -1.01122987e+00, 9.33682173e-03, -2.76336670e-02],
[-2.88088942e+00, -1.00375652e+00, 8.11238587e-03, -2.47955322e-03],
[-2.88371611e+00, -1.02455544e+00, 9.85565037e-03, -2.25982666e-02],
[-3.23374653e+00, 9.69168663e-01, 2.98285484e-03, -2.54135132e-02],
[-3.21809673e+00, 9.51697350e-01, 1.98252499e-03, 2.71377563e-02],
[-2.87221289e+00, -9.98565197e-01, 7.82093406e-03, 9.64355469e-03],
[-2.87068844e+00, -9.94239807e-01, 7.89511204e-03, 2.07443237e-02],
[-3.23205018e+00, 9.90474820e-01, 7.16954470e-04, -2.46047974e-02],
[-3.22614098e+00, 9.67900276e-01, 1.49932504e-03, -2.57110596e-02],
[-3.21842861e+00, 9.60623264e-01, 1.48800015e-03, 1.26113892e-02],
[-3.21877217e+00, 9.60831106e-01, 1.73293054e-03, 1.49383545e-02],
[-2.87132740e+00, -1.00060081e+00, 7.80840218e-03, 9.06372070e-03],
[-2.86981440e+00, -9.96274173e-01, 7.88625330e-03, 2.02102661e-02],
[6.23684359e+00, 4.59359102e-02, 5.90664506e-01, 1.37786865e-02],
[5.99937296e+00, 3.21112685e-02, -5.93227923e-01, -6.92749023e-02],
[5.92144489e+00, 1.98389031e-02, -6.14026666e-01, -2.38800049e-02],
[6.23685551e+00, 4.71412316e-02, 5.89428842e-01, 1.00402832e-02],
[5.93770933e+00, 2.54049711e-02, -6.24091208e-01, 4.53033447e-02],
[6.29011536e+00, 5.04831225e-02, 6.08533144e-01, -7.43865967e-02],
[6.24502945e+00, 4.98473085e-02, 5.84447801e-01, 5.39855957e-02],
[5.93856430e+00, 2.47935243e-02, -6.22833610e-01, 4.44641113e-02]],
dtype="float32")
cls.ref_pvec_test = np.array([[-3.35908103e+00, 1.41343698e-01, 1.47953272e-01, 3.27377319e-02],
[-3.31612492e+00, -1.07574072e-02, 1.35046065e-01, 1.33384705e-01],
[-3.41174889e+00, 1.67209089e-01, 1.58263341e-01, 9.24377441e-02],
[-3.32852888e+00, 1.55460045e-01, 1.25684977e-01, 2.61993408e-02],
[-3.34114552e+00, 1.61819428e-01, 1.38998210e-01, 4.04891968e-02],
[-3.32662868e+00, 6.52360991e-02, 1.24293432e-01, 5.07812500e-02],
[-3.35368443e+00, 1.46444701e-02, 1.51635304e-01, 1.10145569e-01],
[-3.33579969e+00, 1.77854657e-01, 1.28142744e-01, 6.83593750e-02],
[-3.09308386e+00, 9.19110030e-02, 7.09910020e-02, 1.36192322e-01],
[-3.11787128e+00, 1.06056929e-01, 8.38626921e-02, 1.32904053e-01],
[-2.73938131e+00, -7.63382576e-03, -7.46425763e-02, 1.47666931e-01],
[-2.81615782e+00, -8.74039114e-01, -5.04961833e-02, -1.79351807e-01],
[-3.22462940e+00, 8.83198604e-02, 1.08695842e-01, 8.92791748e-02],
[-2.85119152e+00, -6.01680577e-02, -6.00574091e-02, 1.95388794e-01],
[-3.15944910e+00, 1.97961837e-01, 8.99276808e-02, 1.79084778e-01],
[-2.86026454e+00, -1.02728796e+00, -1.66856572e-02, -1.31172180e-01],
[-3.25423741e+00, 1.28395483e-01, 9.27777514e-02, 9.88464355e-02],
[-2.88313174e+00, 1.34271830e-02, -5.44521436e-02, 1.85310364e-01],
[-3.17692256e+00, 2.42637068e-01, 9.33682919e-02, 1.80061340e-01],
[-2.86172438e+00, -1.04268909e+00, -7.91028887e-03, -7.27233887e-02],
[-3.28557396e+00, 1.81960434e-01, 9.90050808e-02, 9.14001465e-02],
[-2.89285851e+00, 1.53065950e-01, -6.27451614e-02, 1.49971008e-01],
[-3.15397811e+00, 2.64356166e-01, 7.86151141e-02, 1.46804810e-01],
[-2.67891097e+00, -1.00727737e+00, -2.11720690e-02, 4.85687256e-02],
[6.93251991e+00, 1.99054211e-01, 4.15148318e-01, -1.47033691e-01],
[6.97309780e+00, 2.04649135e-01, 4.33929205e-01, -1.86050415e-01],
[6.90536976e+00, 2.03557119e-01, 3.23883027e-01, -1.38900757e-01],
[6.91267300e+00, 1.95674390e-01, 3.64136517e-01, -1.01211548e-01],
[5.94695473e+00, -4.40106392e-02, 3.08899760e-01, -4.16564941e-02],
[6.14393854e+00, 3.34385335e-02, -2.48942226e-01, -5.07354736e-02],
[6.23361588e+00, 2.09025517e-02, 1.08646035e-01, -1.84219360e-01],
[6.09808159e+00, -1.34187452e-02, 4.43854928e-03, -1.26083374e-01],
[6.30923796e+00, 4.06269431e-02, 1.65124312e-01, -1.70028687e-01],
[6.09364223e+00, -2.01337896e-02, 4.09343690e-02, -1.33392334e-01],
[6.34268856e+00, 4.24007326e-02, 2.30092421e-01, -1.48071289e-01],
[5.94284391e+00, -3.76656875e-02, -3.89980823e-02, -1.01837158e-01]],
dtype="float32")
def assert_kernels_not_changed(self, tol=1e-5):
assert_array_almost_equal(self.K_tr, self.K_tr_save, tol=tol)
assert_array_almost_equal(self.K_test, self.K_test_save, tol=tol)
@staticmethod
def fixcenter(kernel):
"""
Taken from older versio of ml_kpca.py, As Is, for testing the centering even if that is removed
"""
cernel = kernel.copy()
cols = np.mean(cernel, axis=0)
rows = np.mean(cernel, axis=1)
mean = np.mean(cols)
for i in range(len(rows)):
cernel[i, :] -= cols
for j in range(len(cols)):
cernel[:, j] -= rows
cernel += mean
return cernel
def test_centering(self):
center_new = KernelPCA.center_square(self.K_tr)[2]
center_old = self.fixcenter(self.K_tr)
self.assert_kernels_not_changed()
assert_array_almost_equal(center_new, center_old, tol=1e-5)
# check the method used for the projections
k = KernelPCA(4)
k.fit(self.K_tr)
# copy needed, because the class is doing that elsewhere
# noinspection PyProtectedMember
center_method_for_tests = k._center_test_kmat(self.K_tr.copy())
assert_array_almost_equal(center_method_for_tests, center_old, tol=1e-5)
def test_fit_and_transform(self):
# init & fit
kpca_obj = KernelPCA(4)
kpca_obj.fit(self.K_tr)
self.assert_kernels_not_changed()
# assert that it raises some errors
self.assert_local_errors(kpca_obj)
# transform
pvec_train = kpca_obj.transform(self.K_tr)
self.assert_kernels_not_changed()
# check result
assert_array_almost_equal(pvec_train, self.ref_pvec_train, tol=5e-4)
# transform the test
pvec_test = kpca_obj.transform(self.K_test)
self.assert_kernels_not_changed()
assert_array_almost_equal(pvec_test, self.ref_pvec_test, tol=5e-4)
def test_fit_transform(self):
# init, fit & transform
kpca_obj = KernelPCA(4)
pvec_train = kpca_obj.fit_transform(self.K_tr)
self.assert_kernels_not_changed()
# assert that it raises some errors
self.assert_local_errors(kpca_obj)
# check result
assert_array_almost_equal(pvec_train, self.ref_pvec_train, 5e-4)
# transform the test
pvec_test = kpca_obj.transform(self.K_test)
self.assert_kernels_not_changed()
assert_array_almost_equal(pvec_test, self.ref_pvec_test, tol=5e-4)
def assert_local_errors(self, kpca_obj):
# fixme: adthe shape and tye errors as well
with raises(RuntimeError):
_pvec_dummy = kpca_obj.fit(self.K_tr)
self.assert_kernels_not_changed()
with raises(RuntimeError):
_pvec_dummy = kpca_obj.fit_transform(self.K_tr)
| 70c0c9b4ce0dadbe28cac8ecceabe1baa1e557e8 | [
"Python"
] | 2 | Python | yingli2009/ASAP | e1b17e3a299b0c81d498204ba23b851787d42cf2 | 0fa31b2aad5f863334d3c99c056541dad3926e3d | |
refs/heads/main | <repo_name>Xenon-Game-Dev/101---backup<file_sep>/README.md
# 101---backup<file_sep>/Cloud.py
import howdoi
import dropbox
# access key <KEY>
class backupData :
def __init__ (self, accessKey):
self.accessKey = accessKey
def backup(self, fileFrom, fileTo):
DropBox1 = dropbox.Dropbox(self.accessKey)
with open(fileFrom, 'rb') as file:
DropBox1.files_upload(file.read(), fileTo)
def initiateBackup(fileInput, fileDestination):
accessKey = "<KEY>"
backUpData = backupData(accessKey)
fileFrom = fileInput
fileTo = fileDestination
backUpData.backup(fileFrom=fileFrom, fileTo=fileTo)
initiateBackup('example.txt', '/Backups/exampleBACKUP.txt')
print("FILE-SUCCESSFULLY-BACKED-UP")
| ed24e2539df235210a987ababfdba52954137842 | [
"Markdown",
"Python"
] | 2 | Markdown | Xenon-Game-Dev/101---backup | 04aae0f3836214c5be744d140305dc74e4db154e | cdd46ddcb3c3aa3c0abda036d7b9f5c3978dcd05 | |
refs/heads/master | <repo_name>naurojunior/PHPUnitStarter<file_sep>/README.md
# PHPUnitStarter
Estrutura básica para iniciar utilizando o PHPUnit (com NetBeans)
Passos:
* Configuração inicial para executar o PHP e autocompletar as funções do PHPUnit:
- Ferramentas - Opções - PHP:
- Na aba geral, achar o Interpretador do PHP 5 (provável que esteja em C:\xampp\php\php.exe )
- Abaixo, no "Caminho de Inclusão Global", clicar em Adicionar Pasta e adicionar a pasta do PHPUnit. (Provável em: C:\xampp\php\pear\PHPUnit)
PHPUnit
* **1** Acessar: https://phar.phpunit.de/phpunit-skelgen-2.0.1.phar e realizar o download de "phpunit.phar"
* **2** - Acessar: https://phar.phpunit.de/phpunit-4.5.0.phar e realizar o download de "phpunit-skelgen.phar"
Links de: https://phar.phpunit.de/
Caso não consiga realizar o download, os .phar estarão disponíveis na pasta "phar"
NetBeans (8.0)
* **1** Ferramentas -> Plugins -> Instalar o plugin "PHPUnit" no Netbeans;
* **2** Ferramentas -> Opções -> PHP -> Frameworks e Ferramentas -> PHPUnit;
* **2.1** Clicar em "Procurar" no campo "Script PHPUnit" e apontar para o phpunit.phar;
* **2.2** Clicar em "Procurar" no campo "Script do Gerador Skeleton" e apontar para o phpunit-skelgen.phar;
* **3** Clicar com o botão direito no nome do projeto -> Propriedades
* **3.1** Acessar a opção "Testando" e clicar em "Adicionar Pasta" para o diretório "testes"
* **3.2** Habilitar o checkbox "PHPUnit"
* **3.3** Acessar a opção abaixo de "Testando" -> "PHPUnit"
* **3.4** Selecionar "Usar Bootstrap" e apontar para o "test-config" -> "bootstrap.php"
* **3.5** Selecionar "Usar Configuração XML" e apontar para o "test-config" -> "configuration.xml"
* **3.6** Selecionar "Executar todos os Arquivos de *Teste usando PHPUnit"
* **4** Para configurar as pastas para Autoload, acessar "bootstrap.php" na pasta "test-config" e no "AutoLoader::registerDirectory('../');" alterar para a pasta com as classes;
* **5** Selecionar as classes a serem testadas, clicar com o botão direito em cima delas - Ferramentas - Criar Testes
* **6** alt + F6 para executar os testes
* **7** Pode ser usada a annotation @assert acima das classes (como em Pessoa) antes de clicar em "Criar Testes" para criar o teste sem ter que escrever o código<file_sep>/test-config/bootstrap.php
<?php
require_once('AutoLoader.php');
spl_autoload_register(array('AutoLoader', 'loadClass'));
AutoLoader::registerDirectory('../');
?>
<file_sep>/testes/CalculadoraTest.php
<?php
/**
* Generated by PHPUnit_SkeletonGenerator on 2015-03-23 at 20:18:32.
*/
class CalculadoraTest extends PHPUnit_Framework_TestCase
{
/**
* @var Calculadora
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->object = new Calculadora;
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
}
/**
* @covers Calculadora::soma
* @todo Implement testSoma().
*/
public function testSomaNulo()
{
$this->assertEquals(null, $this->object->soma(3, 1));
}
public function testSomaReal(){
$this->assertEquals(2,$this->object->soma(1, 1));
}
}
<file_sep>/Pessoa.php
<?php
class Pessoa {
/**
*
* @return boolean
* @assert () == true
*/
public function excluir(){
return true;
}
/**
*
* @param int $v
* @param int $y
* @return int
* @assert (10, 20) == 30
* @assert (null, null) == null
*/
public function renovar($v, $y){
return null;
}
//put your code here
}
<file_sep>/Calculadora.php
<?php
class Calculadora {
public function soma($a, $b){
return $a+$b;
}
//put your code here
}
| 25db7c3b70dd978a72e0c0d39a92c796cf49d0f1 | [
"Markdown",
"PHP"
] | 5 | Markdown | naurojunior/PHPUnitStarter | 5c8c6be9f801a8e0cdc53de97df2cccb9783b991 | 47d0c723d6807e03ffac189fa51c854b859bc0e8 | |
refs/heads/master | <file_sep>import React from 'react';
export const themes = {
light: {
foreground: '#000000',
background: '#eeeeee',
},
dark: {
foreground: '#ffffff',
background: '#222222',
},
name:"ravi"
};
export const toggleTheme= () => {
themes.light = {
foreground: '#eeeeee',
background: 'red',
};
};
export const ThemeContext = React.createContext(
themes.light, // default value
toggleTheme,
themes.name
);<file_sep>import React, { Component } from 'react';
import SampleForm from './form';
import { FreeContext, helpers } from './freeContext';
class MainComponent extends Component {
constructor(props) {
super(props);
this.handleSubmit = () => {
this.setState(state => ({
labelName: "loading",
}));
setTimeout(() =>{
this.setState(state => ({
labelName: "done",
}));
}, 3000);
}
this.state = {
labelName: helpers.labelName,
handleSubmit: this.handleSubmit,
data1:[],
};
}
componentDidMount() {
fetch('https://www.reddit.com/r/reactjs.json')
.then((result) => {
// Get the result
// If we want text, call result.text()
return result.json();
}).then((jsonResult) => {
this.setState({
data1: jsonResult
})
})
}
render() {
return (
<div>
<FreeContext.Provider value={this.state}>
<SampleForm />
</FreeContext.Provider>
</div>
);
}
}
export default MainComponent;<file_sep>import React from 'react';
export const helpers = {
labelName:"Submit"
};
export const FreeContext = React.createContext(helpers.labelName);<file_sep>import React, { Component } from 'react';
import Button from './button';
class SubForm extends Component {
constructor(props) {
super(props);
this.state = {
fName:"",
lName:""
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e){
this.setState({
[e.target.name] : [e.target.value]
})
}
render() {
// The entire state is passed to the provider
return (
<div>
<input type="text" value={this.state.fName} name="fName" onChange={this.handleChange.bind(this)}/>
<input type="text" value={this.state.lName} name="lName" onChange={this.handleChange.bind(this)}/>
<Button />
</div>
);
}
}
export default SubForm;<file_sep># ContextApi
Sample context API
| 001e4d763db3cbf45a5c29bac59f89a70d49a5ea | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | MbF-Ravi/ContextApi | 515688faccc24da030af5aeb6a27362a7c8c8055 | 5a6f60c817b820f7a72d0d646515f86fa7ae91ca | |
refs/heads/master | <repo_name>jesuscuesta/ngx-generator<file_sep>/projects/jcuesta/ngx-generator/src/public-api.ts
/*
* Public API Surface of ngx-generator
*/
export * from './lib/ngx-generator.module';
<file_sep>/projects/jcuesta/ngx-generator/src/lib/ngx-generator.module.ts
import { NgModule, ModuleWithProviders } from '@angular/core';
import { NgxGeneratorComponent } from './ngx-generator.component';
import { RouterModule } from '@angular/router';
import { AppRoutingModule } from './app-routing.module';
@NgModule({
declarations: [NgxGeneratorComponent],
imports: [
AppRoutingModule,
RouterModule.forChild([]),
],
exports: [NgxGeneratorComponent]
})
export class NgxGeneratorModule { }
@NgModule({})
export class GeneradorSharedModule {
static forChild(): ModuleWithProviders {
return {
ngModule: NgxGeneratorModule,
providers: []
};
}
}
| 581b36d5c08f457d0d2d8561c4de7e1fcc286504 | [
"TypeScript"
] | 2 | TypeScript | jesuscuesta/ngx-generator | bfa08eb40c21962a33f5b02fec0ee3e30bc1d0af | ab2c6aeda14dd741ddf2c8db39d067f4c54dd5f1 | |
refs/heads/main | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Inventory;
import Admins.AdminActivity;
import Main.Admin;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Saima
*/
public class stock extends javax.swing.JFrame {
/**
* Creates new form stock
*/
public stock() {
ImageIcon ic = new ImageIcon(getClass().getResource("/Images/icon_1.png"));
this.setIconImage(ic.getImage());
initComponents();
loadData();
}
public void loadData() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT stock_id as StockId , product_id as ProductId ,quantity_on_stock as StockQuantity , stock_updated_date as Date FROM stock order by stock_id");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name=new Vector();
Vector data_rows=new Vector();
for(int i= 1; i < columns+1; i++)
{
columns_name.addElement (rsmetadata.getColumnLabel(i));
}
dtm.setColumnIdentifiers(columns_name);
while (rs.next())
{
data_rows = new Vector();
for (int j = 1; j <columns+1; j++)
{
data_rows.addElement(rs.getString(j)) ;
}
dtm.addRow(data_rows);
}
dDTable.setModel(dtm);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
name1 = new javax.swing.JLabel();
pidField = new javax.swing.JTextField();
id = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
dDTable = new javax.swing.JTable();
sidField = new javax.swing.JTextField();
jPanel6 = new javax.swing.JPanel();
add_product = new javax.swing.JLabel();
jLabel20 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
logout = new javax.swing.JLabel();
backbtn = new javax.swing.JLabel();
name = new javax.swing.JLabel();
name2 = new javax.swing.JLabel();
sQuantityField = new javax.swing.JTextField();
sDateField = new javax.swing.JTextField();
restobtn = new javax.swing.JButton();
upstobtn = new javax.swing.JButton();
delstobtn = new javax.swing.JButton();
addstobtn = new javax.swing.JButton();
clearstobtn = new javax.swing.JButton();
search = new javax.swing.JButton();
searchField1 = new javax.swing.JTextField();
maxQuan = new javax.swing.JButton();
quanHL = new javax.swing.JButton();
name4 = new javax.swing.JLabel();
quanLH1 = new javax.swing.JButton();
minQuan1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Stock");
name1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
name1.setForeground(new java.awt.Color(0, 153, 153));
name1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
name1.setText("Date");
pidField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
pidField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pidFieldActionPerformed(evt);
}
});
id.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
id.setForeground(new java.awt.Color(0, 153, 153));
id.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
id.setText("Product Id");
id.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
dDTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Stock Id", "Prouduct Id", "StockQuantity", "Date"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
dDTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
dDTableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(dDTable);
sidField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sidFieldActionPerformed(evt);
}
});
jPanel6.setBackground(new java.awt.Color(0, 153, 153));
add_product.setFont(new java.awt.Font("Arial", 0, 24)); // NOI18N
add_product.setForeground(new java.awt.Color(255, 255, 255));
add_product.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
add_product.setText("Stock");
jLabel20.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel20MouseClicked(evt);
}
});
jLabel21.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel21MouseClicked(evt);
}
});
logout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icon/cross.png"))); // NOI18N
logout.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
logoutMouseClicked(evt);
}
});
backbtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icon/backs.png"))); // NOI18N
backbtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
backbtnMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(add_product, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(419, 419, 419)
.addComponent(backbtn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel21)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(logout)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(logout)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(backbtn)
.addContainerGap(22, Short.MAX_VALUE))
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(add_product, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel21, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel20, javax.swing.GroupLayout.Alignment.LEADING))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
name.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
name.setForeground(new java.awt.Color(0, 153, 153));
name.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
name.setText("Stock Id");
name2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
name2.setForeground(new java.awt.Color(0, 153, 153));
name2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
name2.setText("Stock Quantity");
sQuantityField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sQuantityFieldActionPerformed(evt);
}
});
sDateField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sDateFieldActionPerformed(evt);
}
});
restobtn.setBackground(new java.awt.Color(0, 153, 153));
restobtn.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
restobtn.setForeground(new java.awt.Color(255, 255, 255));
restobtn.setText("Refresh");
restobtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
restobtnMouseClicked(evt);
}
});
upstobtn.setBackground(new java.awt.Color(0, 153, 153));
upstobtn.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
upstobtn.setForeground(new java.awt.Color(255, 255, 255));
upstobtn.setText("Update");
upstobtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
upstobtnMouseClicked(evt);
}
});
delstobtn.setBackground(new java.awt.Color(0, 153, 153));
delstobtn.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
delstobtn.setForeground(new java.awt.Color(255, 255, 255));
delstobtn.setText("Delete");
delstobtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
delstobtnMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
delstobtnMouseEntered(evt);
}
});
addstobtn.setBackground(new java.awt.Color(0, 153, 153));
addstobtn.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
addstobtn.setForeground(new java.awt.Color(255, 255, 255));
addstobtn.setText("Add");
addstobtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addstobtnMouseClicked(evt);
}
});
clearstobtn.setBackground(new java.awt.Color(0, 153, 153));
clearstobtn.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
clearstobtn.setForeground(new java.awt.Color(255, 255, 255));
clearstobtn.setText("Clear");
clearstobtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
clearstobtnMouseClicked(evt);
}
});
search.setBackground(new java.awt.Color(0, 153, 153));
search.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
search.setForeground(new java.awt.Color(255, 255, 255));
search.setText("Search ");
search.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
searchMouseClicked(evt);
}
});
search.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchActionPerformed(evt);
}
});
searchField1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
searchField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
searchField1.setText("Enter Product Name");
searchField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchField1ActionPerformed(evt);
}
});
maxQuan.setBackground(new java.awt.Color(0, 153, 153));
maxQuan.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
maxQuan.setForeground(new java.awt.Color(255, 255, 255));
maxQuan.setText("Maximum Quantity");
maxQuan.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
maxQuanMouseClicked(evt);
}
});
maxQuan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
maxQuanActionPerformed(evt);
}
});
quanHL.setBackground(new java.awt.Color(0, 153, 153));
quanHL.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
quanHL.setForeground(new java.awt.Color(255, 255, 255));
quanHL.setText("Quantity(High to low)");
quanHL.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
quanHLMouseClicked(evt);
}
});
quanHL.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
quanHLActionPerformed(evt);
}
});
name4.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
name4.setForeground(new java.awt.Color(0, 153, 153));
name4.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
name4.setText("Filters :");
quanLH1.setBackground(new java.awt.Color(0, 153, 153));
quanLH1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
quanLH1.setForeground(new java.awt.Color(255, 255, 255));
quanLH1.setText("Quantity(Low to High)");
quanLH1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
quanLH1MouseClicked(evt);
}
});
quanLH1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
quanLH1ActionPerformed(evt);
}
});
minQuan1.setBackground(new java.awt.Color(0, 153, 153));
minQuan1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
minQuan1.setForeground(new java.awt.Color(255, 255, 255));
minQuan1.setText("Minimum Quantity");
minQuan1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
minQuan1MouseClicked(evt);
}
});
minQuan1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
minQuan1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(name2, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(sidField, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sQuantityField, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 88, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(name1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(pidField, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sDateField, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(49, 49, 49))
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(addstobtn, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(36, 36, 36)
.addComponent(delstobtn)
.addGap(24, 24, 24)
.addComponent(upstobtn)
.addGap(25, 25, 25)
.addComponent(restobtn)
.addGap(34, 34, 34)
.addComponent(clearstobtn, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(139, 139, 139)
.addComponent(searchField1, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(229, 229, 229))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(search)
.addGroup(layout.createSequentialGroup()
.addComponent(name4, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(44, 44, 44)
.addComponent(quanLH1)
.addGap(18, 18, 18)
.addComponent(quanHL))))
.addGap(86, 86, 86))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 434, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(maxQuan, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(minQuan1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(20, 20, 20))))
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(83, 83, 83)
.addComponent(minQuan1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(maxQuan, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(53, 53, 53)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(name, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(sidField, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(id)
.addComponent(pidField, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(name2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sQuantityField, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(name1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sDateField, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(upstobtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(delstobtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(addstobtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(restobtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(clearstobtn, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(search, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(searchField1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(quanHL, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(name4, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(quanLH1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(135, 135, 135))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void pidFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pidFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_pidFieldActionPerformed
private void dDTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dDTableMouseClicked
// TODO add your handling code here:
// get the model from the jtable
DefaultTableModel model = (DefaultTableModel)dDTable.getModel();
// get the selected row index
int selectedRowIndex = dDTable.getSelectedRow();
// set the selected row data into jtextfields
sidField.setText(model.getValueAt(selectedRowIndex, 0).toString());
pidField.setText(model.getValueAt(selectedRowIndex, 1).toString());
sQuantityField.setText(model.getValueAt(selectedRowIndex, 2).toString());
sDateField.setText(model.getValueAt(selectedRowIndex, 3).toString());
// quantityField.setText(model.getValueAt(selectedRowIndex, 3).toString());
// descriptionField.setText(model.getValueAt(selectedRowIndex, 4).toString());
}//GEN-LAST:event_dDTableMouseClicked
private void sidFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sidFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_sidFieldActionPerformed
private void jLabel20MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel20MouseClicked
}//GEN-LAST:event_jLabel20MouseClicked
private void jLabel21MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel21MouseClicked
}//GEN-LAST:event_jLabel21MouseClicked
private void logoutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_logoutMouseClicked
Admin admin = new Admin();
admin.setVisible(true);
dispose();
}//GEN-LAST:event_logoutMouseClicked
private void backbtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backbtnMouseClicked
AdminActivity adActivity = new AdminActivity();
adActivity.setVisible(true);
dispose();
}//GEN-LAST:event_backbtnMouseClicked
private void sQuantityFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sQuantityFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_sQuantityFieldActionPerformed
private void sDateFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sDateFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_sDateFieldActionPerformed
private void restobtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_restobtnMouseClicked
// TODO add your handling code here:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT stock_id as StockId , product_id as ProductId ,quantity_on_stock as StockQuantity , stock_updated_date as Date FROM stock order by stock_id");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name=new Vector();
Vector data_rows=new Vector();
for(int i= 1; i < columns+1; i++)
{
columns_name.addElement (rsmetadata.getColumnLabel(i));
}
dtm.setColumnIdentifiers(columns_name);
while (rs.next())
{
data_rows = new Vector();
for (int j = 1; j <columns+1; j++)
{
data_rows.addElement(rs.getString(j)) ;
}
dtm.addRow(data_rows);
}
dDTable.setModel(dtm);
JOptionPane.showMessageDialog(null, "Refreshed");
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_restobtnMouseClicked
private void upstobtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_upstobtnMouseClicked
// TODO add your handling code here:
String s1 = sidField.getText();
String s2 = pidField.getText();
String s3 = sQuantityField.getText();
String s5= sDateField.getText();
// String s8 = descriptionField.getText();
// String s7 = priceField.getText();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
statement.execute("Update stock set stock_id =" + s1 + ", product_id =" + s2 + ", quantity_on_stock =" + s3 + ",stock_updated_date = "+" '"+ s5 +"' "+" where stock_id ="+ s1+"");
JOptionPane.showMessageDialog(null, "Data Updated");
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_upstobtnMouseClicked
private void delstobtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_delstobtnMouseClicked
// TODO add your handling code here:
String s1 = sidField.getText();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
statement.execute(" delete from stock " + " where stock_id = ( "+s1+")" );
JOptionPane.showMessageDialog(null, "Stock Id " + s1 + " has been deleted");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Stock named " + s1 + " not found");
}
}//GEN-LAST:event_delstobtnMouseClicked
private void delstobtnMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_delstobtnMouseEntered
// TODO add your handling code here:
}//GEN-LAST:event_delstobtnMouseEntered
private void addstobtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addstobtnMouseClicked
// TODO add your handling code here:
String s1 = sidField.getText();
String s2 = pidField.getText();
String s3 = sQuantityField.getText();
String s5= sDateField.getText();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
statement.execute(" insert into stock " + " values ( '"+s1+"', '"+s2+"','"+s3+"', '"+s5+"')" );
JOptionPane.showMessageDialog(null, " Saved");
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_addstobtnMouseClicked
private void clearstobtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clearstobtnMouseClicked
// TODO add your handling code here:
pidField.setText("");
sidField.setText("");
// searchField1.setText("");
sQuantityField.setText("");
sDateField.setText("");
}//GEN-LAST:event_clearstobtnMouseClicked
private void searchMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_searchMouseClicked
// TODO add your handling code here:
String s1= searchField1.getText();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(" select s.stock_id as Stock_Id ,p.product_name as ProductName,s.quantity_on_stock as StockQuantity,s.stock_updated_date as Date,p.product_price as ProductPrice\n" +
" \n" +
" from product p\n" +
" inner join stock s\n" +
" on s.product_id=p.product_id\n" + " where product_name = ( '"+s1+"') ");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name=new Vector();
Vector data_rows=new Vector();
for(int i= 1; i < columns+1; i++)
{
columns_name.addElement (rsmetadata.getColumnLabel(i));
}
dtm.setColumnIdentifiers(columns_name);
while (rs.next())
{
data_rows = new Vector();
for (int j = 1; j <columns+1; j++)
{
data_rows.addElement(rs.getString(j)) ;
}
dtm.addRow(data_rows);
}
dDTable.setModel(dtm);
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_searchMouseClicked
private void searchField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchField1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_searchField1ActionPerformed
private void searchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_searchActionPerformed
private void maxQuanMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_maxQuanMouseClicked
// TODO add your handling code here:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(" select p.product_name,s.quantity_on_stock\n" +
" \n" +
" from product p\n" +
" inner join stock s\n" +
" on p.product_id=s.product_id \n" +
" where s.quantity_on_stock=(\n" +
" select MAX(s.quantity_on_stock) from stock s)");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name=new Vector();
Vector data_rows=new Vector();
for(int i= 1; i < columns+1; i++)
{
columns_name.addElement (rsmetadata.getColumnLabel(i));
}
dtm.setColumnIdentifiers(columns_name);
while (rs.next())
{
data_rows = new Vector();
for (int j = 1; j <columns+1; j++)
{
data_rows.addElement(rs.getString(j)) ;
}
dtm.addRow(data_rows);
}
dDTable.setModel(dtm);
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_maxQuanMouseClicked
private void maxQuanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_maxQuanActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_maxQuanActionPerformed
private void quanHLMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_quanHLMouseClicked
// TODO add your handling code here:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(" select s.stock_id as Stock_Id ,p.product_name as ProductName,s.quantity_on_stock as StockQuantity,s.stock_updated_date as Date\n" +
" \n" +
" from product p\n" +
" inner join stock s\n" +
" on p.product_id=s.product_id \n" +
" order by s.quantity_on_stock desc ");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name=new Vector();
Vector data_rows=new Vector();
for(int i= 1; i < columns+1; i++)
{
columns_name.addElement (rsmetadata.getColumnLabel(i));
}
dtm.setColumnIdentifiers(columns_name);
while (rs.next())
{
data_rows = new Vector();
for (int j = 1; j <columns+1; j++)
{
data_rows.addElement(rs.getString(j)) ;
}
dtm.addRow(data_rows);
}
dDTable.setModel(dtm);
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_quanHLMouseClicked
private void quanHLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quanHLActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_quanHLActionPerformed
private void quanLH1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_quanLH1MouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_quanLH1MouseClicked
private void quanLH1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quanLH1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_quanLH1ActionPerformed
private void minQuan1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_minQuan1MouseClicked
// TODO add your handling code here:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(" select p.product_name,s.quantity_on_stock\n" +
" \n" +
" from product p\n" +
" inner join stock s\n" +
" on p.product_id=s.product_id \n" +
" where s.quantity_on_stock=(\n" +
" select min(s.quantity_on_stock) from stock s)");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name=new Vector();
Vector data_rows=new Vector();
for(int i= 1; i < columns+1; i++)
{
columns_name.addElement (rsmetadata.getColumnLabel(i));
}
dtm.setColumnIdentifiers(columns_name);
while (rs.next())
{
data_rows = new Vector();
for (int j = 1; j <columns+1; j++)
{
data_rows.addElement(rs.getString(j)) ;
}
dtm.addRow(data_rows);
}
dDTable.setModel(dtm);
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_minQuan1MouseClicked
private void minQuan1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_minQuan1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_minQuan1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(stock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(stock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(stock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(stock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new stock().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel add_product;
private javax.swing.JButton addstobtn;
private javax.swing.JLabel backbtn;
private javax.swing.JButton clearstobtn;
private javax.swing.JTable dDTable;
private javax.swing.JButton delstobtn;
private javax.swing.JLabel id;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JPanel jPanel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel logout;
private javax.swing.JButton maxQuan;
private javax.swing.JButton minQuan1;
private javax.swing.JLabel name;
private javax.swing.JLabel name1;
private javax.swing.JLabel name2;
private javax.swing.JLabel name4;
private javax.swing.JTextField pidField;
private javax.swing.JButton quanHL;
private javax.swing.JButton quanLH1;
private javax.swing.JButton restobtn;
private javax.swing.JTextField sDateField;
private javax.swing.JTextField sQuantityField;
private javax.swing.JButton search;
private javax.swing.JTextField searchField1;
private javax.swing.JTextField sidField;
private javax.swing.JButton upstobtn;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Inventory;
import Admins.AdminActivity;
import Main.Admin;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Saima
*/
public class category extends javax.swing.JFrame {
/**
* Creates new form category
*/
public category() {
ImageIcon ic = new ImageIcon(getClass().getResource("/Images/icon_1.png"));
this.setIconImage(ic.getImage());
initComponents();
loadData();
}
public void loadData() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT category_id as CategoryId , category_name CategoryName , category_status CategoryStatus FROM category order by category_id");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name=new Vector();
Vector data_rows=new Vector();
for(int i= 1; i < columns+1; i++)
{
columns_name.addElement (rsmetadata.getColumnLabel(i));
}
dtm.setColumnIdentifiers(columns_name);
while (rs.next())
{
data_rows = new Vector();
for (int j = 1; j <columns+1; j++)
{
data_rows.addElement(rs.getString(j)) ;
}
dtm.addRow(data_rows);
}
dDTable.setModel(dtm);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jDialog1 = new javax.swing.JDialog();
jDialog2 = new javax.swing.JDialog();
name1 = new javax.swing.JLabel();
cnameField = new javax.swing.JTextField();
cidField = new javax.swing.JTextField();
id = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
dDTable = new javax.swing.JTable();
jPanel6 = new javax.swing.JPanel();
add_product = new javax.swing.JLabel();
jLabel20 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
logout = new javax.swing.JLabel();
backbtn = new javax.swing.JLabel();
cstatusField = new javax.swing.JTextField();
name2 = new javax.swing.JLabel();
recatbtn = new javax.swing.JButton();
upcatbtn = new javax.swing.JButton();
delcatbtn = new javax.swing.JButton();
addcatbtn = new javax.swing.JButton();
clearcatbtn = new javax.swing.JButton();
name3 = new javax.swing.JLabel();
search = new javax.swing.JButton();
searchPriceField = new javax.swing.JTextField();
sortAZ = new javax.swing.JButton();
sortZA = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
availcat = new javax.swing.JButton();
showAvailcat = new javax.swing.JTextField();
searchField1 = new javax.swing.JTextField();
sortHL = new javax.swing.JButton();
name = new javax.swing.JLabel();
javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
jDialog1.getContentPane().setLayout(jDialog1Layout);
jDialog1Layout.setHorizontalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog1Layout.setVerticalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
javax.swing.GroupLayout jDialog2Layout = new javax.swing.GroupLayout(jDialog2.getContentPane());
jDialog2.getContentPane().setLayout(jDialog2Layout);
jDialog2Layout.setHorizontalGroup(
jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog2Layout.setVerticalGroup(
jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Category");
name1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
name1.setForeground(new java.awt.Color(0, 153, 153));
name1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
name1.setText("Category Name");
cnameField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cnameFieldActionPerformed(evt);
}
});
cidField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
cidField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cidFieldActionPerformed(evt);
}
});
id.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
id.setForeground(new java.awt.Color(0, 153, 153));
id.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
id.setText("Category Id");
id.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
dDTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null},
{null, null},
{null, null},
{null, null}
},
new String [] {
"Category Id", "Category Name"
}
) {
boolean[] canEdit = new boolean [] {
false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
dDTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
dDTableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(dDTable);
jPanel6.setBackground(new java.awt.Color(0, 153, 153));
add_product.setFont(new java.awt.Font("Arial", 0, 24)); // NOI18N
add_product.setForeground(new java.awt.Color(255, 255, 255));
add_product.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
add_product.setText("Category");
jLabel20.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel20MouseClicked(evt);
}
});
jLabel21.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel21MouseClicked(evt);
}
});
logout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icon/cross.png"))); // NOI18N
logout.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
logoutMouseClicked(evt);
}
});
backbtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icon/backs.png"))); // NOI18N
backbtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
backbtnMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(604, 604, 604)
.addComponent(add_product, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(643, 643, 643)
.addComponent(jLabel21)
.addGap(168, 168, 168)
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(436, 436, 436)
.addComponent(backbtn)
.addGap(18, 18, 18)
.addComponent(logout)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(add_product, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel6Layout.createSequentialGroup()
.addComponent(jLabel20)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel21)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(backbtn)
.addComponent(logout))
.addGap(6, 6, 6)))
.addContainerGap(16, Short.MAX_VALUE))
);
cstatusField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cstatusFieldActionPerformed(evt);
}
});
name2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
name2.setForeground(new java.awt.Color(0, 153, 153));
name2.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
name2.setText("Category Status");
recatbtn.setBackground(new java.awt.Color(0, 153, 153));
recatbtn.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
recatbtn.setForeground(new java.awt.Color(255, 255, 255));
recatbtn.setText("Refresh");
recatbtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
recatbtnMouseClicked(evt);
}
});
upcatbtn.setBackground(new java.awt.Color(0, 153, 153));
upcatbtn.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
upcatbtn.setForeground(new java.awt.Color(255, 255, 255));
upcatbtn.setText("Update");
upcatbtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
upcatbtnMouseClicked(evt);
}
});
delcatbtn.setBackground(new java.awt.Color(0, 153, 153));
delcatbtn.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
delcatbtn.setForeground(new java.awt.Color(255, 255, 255));
delcatbtn.setText("Delete");
delcatbtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
delcatbtnMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
delcatbtnMouseEntered(evt);
}
});
addcatbtn.setBackground(new java.awt.Color(0, 153, 153));
addcatbtn.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
addcatbtn.setForeground(new java.awt.Color(255, 255, 255));
addcatbtn.setText("Add");
addcatbtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addcatbtnMouseClicked(evt);
}
});
clearcatbtn.setBackground(new java.awt.Color(0, 153, 153));
clearcatbtn.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
clearcatbtn.setForeground(new java.awt.Color(255, 255, 255));
clearcatbtn.setText("Clear");
clearcatbtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
clearcatbtnMouseClicked(evt);
}
});
name3.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
name3.setForeground(new java.awt.Color(0, 153, 153));
name3.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
name3.setText("Price (High to Low) :");
search.setBackground(new java.awt.Color(0, 153, 153));
search.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
search.setForeground(new java.awt.Color(255, 255, 255));
search.setText("Search ");
search.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
searchMouseClicked(evt);
}
});
searchPriceField.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
searchPriceField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
searchPriceField.setText("Enter the Product Name");
searchPriceField.setToolTipText("Enter the Product Name");
searchPriceField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchPriceFieldActionPerformed(evt);
}
});
sortAZ.setBackground(new java.awt.Color(0, 153, 153));
sortAZ.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
sortAZ.setForeground(new java.awt.Color(255, 255, 255));
sortAZ.setText("Category Name (A-Z)");
sortAZ.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
sortAZMouseClicked(evt);
}
});
sortAZ.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sortAZActionPerformed(evt);
}
});
sortZA.setBackground(new java.awt.Color(0, 153, 153));
sortZA.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
sortZA.setForeground(new java.awt.Color(255, 255, 255));
sortZA.setText("Category Name (Z-A)");
sortZA.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
sortZAMouseClicked(evt);
}
});
sortZA.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sortZAActionPerformed(evt);
}
});
availcat.setBackground(new java.awt.Color(0, 153, 153));
availcat.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
availcat.setForeground(new java.awt.Color(255, 255, 255));
availcat.setText("Available Category");
availcat.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
availcatMouseClicked(evt);
}
});
availcat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
availcatActionPerformed(evt);
}
});
showAvailcat.setEditable(false);
showAvailcat.setBackground(new java.awt.Color(255, 255, 255));
showAvailcat.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
showAvailcat.setHorizontalAlignment(javax.swing.JTextField.CENTER);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(availcat, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(showAvailcat, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(29, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(availcat, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
.addComponent(showAvailcat))
.addContainerGap(38, Short.MAX_VALUE))
);
searchField1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
searchField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
searchField1.setText("Enter the Brand Name");
searchField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchField1ActionPerformed(evt);
}
});
sortHL.setBackground(new java.awt.Color(0, 153, 153));
sortHL.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
sortHL.setForeground(new java.awt.Color(255, 255, 255));
sortHL.setText("Sort");
sortHL.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
sortHLMouseClicked(evt);
}
});
name.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
name.setForeground(new java.awt.Color(0, 153, 153));
name.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
name.setText("Filters :");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(117, 117, 117)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(57, 57, 57)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(name3)
.addGap(29, 29, 29)
.addComponent(searchPriceField, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(44, 44, 44)
.addComponent(sortHL, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(sortAZ)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(sortZA)))
.addGap(0, 220, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(addcatbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(delcatbtn)
.addGap(32, 32, 32)
.addComponent(upcatbtn)
.addGap(25, 25, 25)
.addComponent(recatbtn)
.addGap(34, 34, 34)
.addComponent(clearcatbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(name2, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(4, 4, 4)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cidField, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cstatusField, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(name1, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(cnameField, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(83, 83, 83)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(search)
.addGap(18, 18, 18)
.addComponent(searchField1, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 520, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(43, 43, 43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(id)
.addGap(58, 58, 58)
.addComponent(name2, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(cidField, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(49, 49, 49)
.addComponent(cstatusField, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(name1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(cnameField, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(129, 129, 129))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(46, 46, 46)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(addcatbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(delcatbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(upcatbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(recatbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(clearcatbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(search, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(searchField1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(93, 93, 93)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(179, 179, 179))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sortZA, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sortAZ, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(searchPriceField, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sortHL, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(name3, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(150, 150, 150))))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cnameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cnameFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cnameFieldActionPerformed
private void cidFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cidFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cidFieldActionPerformed
private void dDTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dDTableMouseClicked
// TODO add your handling code here:
// get the model from the jtable
DefaultTableModel model = (DefaultTableModel)dDTable.getModel();
// get the selected row index
int selectedRowIndex = dDTable.getSelectedRow();
// set the selected row data into jtextfields
// bidField.setText(model.getValueAt(selectedRowIndex, 0).toString());
// cidField.setText(model.getValueAt(selectedRowIndex, 1).toString());
// bidField.setText(model.getValueAt(selectedRowIndex, 2).toString());
cnameField.setText(model.getValueAt(selectedRowIndex, 1).toString());
cidField.setText(model.getValueAt(selectedRowIndex, 0).toString());
cstatusField.setText(model.getValueAt(selectedRowIndex, 2).toString());
// descriptionField.setText(model.getValueAt(selectedRowIndex, 4).toString());
}//GEN-LAST:event_dDTableMouseClicked
private void jLabel20MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel20MouseClicked
}//GEN-LAST:event_jLabel20MouseClicked
private void jLabel21MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel21MouseClicked
}//GEN-LAST:event_jLabel21MouseClicked
private void logoutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_logoutMouseClicked
Admin admin = new Admin();
admin.setVisible(true);
dispose();
}//GEN-LAST:event_logoutMouseClicked
private void backbtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backbtnMouseClicked
AdminActivity adActivity = new AdminActivity();
adActivity.setVisible(true);
dispose();
}//GEN-LAST:event_backbtnMouseClicked
private void cstatusFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cstatusFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cstatusFieldActionPerformed
private void recatbtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_recatbtnMouseClicked
// TODO add your handling code here:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT category_id as CategoryId ,category_name as CategoryName , category_status CategoryStatus FROM category order by category_id");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name=new Vector();
Vector data_rows=new Vector();
for(int i= 1; i < columns+1; i++)
{
columns_name.addElement (rsmetadata.getColumnLabel(i));
}
dtm.setColumnIdentifiers(columns_name);
while (rs.next())
{
data_rows = new Vector();
for (int j = 1; j <columns+1; j++)
{
data_rows.addElement(rs.getString(j)) ;
}
dtm.addRow(data_rows);
}
dDTable.setModel(dtm);
JOptionPane.showMessageDialog(null, "Refreshed");
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_recatbtnMouseClicked
private void upcatbtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_upcatbtnMouseClicked
// TODO add your handling code here:
String s1 = cnameField.getText();
String s2 = cidField.getText();
String s3 = cstatusField.getText();
// String s6 = quantityField.getText();
// String s8 = descriptionField.getText();
// String s7 = priceField.getText();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
statement.execute("Update category set category_id =" + s2 + ", category_name ="+" '"+ s1 +"' , category_status ="+" '"+ s3 +"' where category_name ="+"'"+ s1+"'");
JOptionPane.showMessageDialog(null, "Data Updated");
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_upcatbtnMouseClicked
private void delcatbtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_delcatbtnMouseClicked
// TODO add your handling code here:
String s1= cnameField.getText();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
statement.execute(" delete from category " + " where category_name = ( '"+s1+"')" );
JOptionPane.showMessageDialog(null, "Category " + s1 + " has been deleted");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Category named " + s1 + " not found");
}
}//GEN-LAST:event_delcatbtnMouseClicked
private void delcatbtnMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_delcatbtnMouseEntered
// TODO add your handling code here:
}//GEN-LAST:event_delcatbtnMouseEntered
private void addcatbtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addcatbtnMouseClicked
// TODO add your handling code here:
String s1= cidField.getText();
String s2= cnameField.getText();
String s3= cstatusField.getText();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
statement.execute(" insert into category " + " values ( '"+s1+"', '"+s2+"', '"+s3+"')" );
JOptionPane.showMessageDialog(null, " Saved");
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_addcatbtnMouseClicked
private void clearcatbtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clearcatbtnMouseClicked
// TODO add your handling code here:
cnameField.setText("");
cidField.setText("");
cstatusField.setText("");
showAvailcat.setText("");
}//GEN-LAST:event_clearcatbtnMouseClicked
private void searchMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_searchMouseClicked
// TODO add your handling code here:
String s1= searchPriceField.getText();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(" select * from category " + " where category_name = ( '"+s1+"')");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name=new Vector();
Vector data_rows=new Vector();
for(int i= 1; i < columns+1; i++)
{
columns_name.addElement (rsmetadata.getColumnLabel(i));
}
dtm.setColumnIdentifiers(columns_name);
while (rs.next())
{
data_rows = new Vector();
for (int j = 1; j <columns+1; j++)
{
data_rows.addElement(rs.getString(j)) ;
}
dtm.addRow(data_rows);
}
dDTable.setModel(dtm);
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_searchMouseClicked
private void searchPriceFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchPriceFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_searchPriceFieldActionPerformed
private void sortAZMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sortAZMouseClicked
// TODO add your handling code here:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(" select * from category order by category_name ");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name=new Vector();
Vector data_rows=new Vector();
for(int i= 1; i < columns+1; i++)
{
columns_name.addElement (rsmetadata.getColumnLabel(i));
}
dtm.setColumnIdentifiers(columns_name);
while (rs.next())
{
data_rows = new Vector();
for (int j = 1; j <columns+1; j++)
{
data_rows.addElement(rs.getString(j)) ;
}
dtm.addRow(data_rows);
}
dDTable.setModel(dtm);
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_sortAZMouseClicked
private void sortAZActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sortAZActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_sortAZActionPerformed
private void sortZAMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sortZAMouseClicked
// TODO add your handling code here:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(" select * from category order by category_name desc ");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name=new Vector();
Vector data_rows=new Vector();
for(int i= 1; i < columns+1; i++)
{
columns_name.addElement (rsmetadata.getColumnLabel(i));
}
dtm.setColumnIdentifiers(columns_name);
while (rs.next())
{
data_rows = new Vector();
for (int j = 1; j <columns+1; j++)
{
data_rows.addElement(rs.getString(j)) ;
}
dtm.addRow(data_rows);
}
dDTable.setModel(dtm);
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_sortZAMouseClicked
private void sortZAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sortZAActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_sortZAActionPerformed
private void availcatMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_availcatMouseClicked
// TODO add your handling code here:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(" select * from category " + "where category_status = 'active' ");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name=new Vector();
Vector data_rows=new Vector();
for(int i= 1; i < columns+1; i++)
{
columns_name.addElement (rsmetadata.getColumnLabel(i));
}
dtm.setColumnIdentifiers(columns_name);
while (rs.next())
{
data_rows = new Vector();
for (int j = 1; j <columns+1; j++)
{
data_rows.addElement(rs.getString(j)) ;
}
dtm.addRow(data_rows);
}
dDTable.setModel(dtm);
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_availcatMouseClicked
private void availcatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_availcatActionPerformed
// TODO add your handling code here:
try{
//String sasdast = jComboBox1.getSelectedItem().toString();
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("select count(category_id) from category where category_status = 'active'");
if (rs.next()) {
showAvailcat.setText(rs.getString(1));
}
}
catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_availcatActionPerformed
private void searchField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchField1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_searchField1ActionPerformed
private void sortHLMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sortHLMouseClicked
// TODO add your handling code here:
String s1= searchPriceField.getText();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=lab11;integratedSecurity=true");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(" select c.category_name,p.product_name,p.product_price\n" +
" \n" +
" from product p\n" +
" inner join category c\n" +
" on c.category_id=p.category_id\n" +
" \n" +
" where p.product_name='"+s1+"'\n" +
" \n" +
" group by c.category_name,p.product_name,p.product_price\n" +
" order by p.product_price desc ");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name = new Vector();
Vector data_rows = new Vector();
for (int i = 1; i < columns + 1; i++) {
columns_name.addElement(rsmetadata.getColumnLabel(i));
}
dtm.setColumnIdentifiers(columns_name);
while (rs.next()) {
data_rows = new Vector();
for (int j = 1; j < columns + 1; j++) {
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
dDTable.setModel(dtm);
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_sortHLMouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(category.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(category.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(category.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(category.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new category().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel add_product;
private javax.swing.JButton addcatbtn;
private javax.swing.JButton availcat;
private javax.swing.JLabel backbtn;
private javax.swing.JTextField cidField;
private javax.swing.JButton clearcatbtn;
private javax.swing.JTextField cnameField;
private javax.swing.JTextField cstatusField;
private javax.swing.JTable dDTable;
private javax.swing.JButton delcatbtn;
private javax.swing.JLabel id;
private javax.swing.JDialog jDialog1;
private javax.swing.JDialog jDialog2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel logout;
private javax.swing.JLabel name;
private javax.swing.JLabel name1;
private javax.swing.JLabel name2;
private javax.swing.JLabel name3;
private javax.swing.JButton recatbtn;
private javax.swing.JButton search;
private javax.swing.JTextField searchField1;
private javax.swing.JTextField searchPriceField;
private javax.swing.JTextField showAvailcat;
private javax.swing.JButton sortAZ;
private javax.swing.JButton sortHL;
private javax.swing.JButton sortZA;
private javax.swing.JButton upcatbtn;
// End of variables declaration//GEN-END:variables
}
| f22f8caeabae74eec7a3b25d33d68d82e08eb1a0 | [
"Java"
] | 2 | Java | Nadia214/Inventory | 29953eb159ab2935625c450e69adc6606bbef13d | 7254d62cec56cc5ce50cddcf7c7b4853488b78b3 | |
refs/heads/master | <repo_name>raviCHCopart/raviCHCopart.github.io<file_sep>/README.md
# serviceworkers.github.io
<file_sep>/sw.js
self.addEventListener('install', async e => {
console.log('SW Installed!')
const cache = await caches.open('pwa-static')
cache.addAll(['./', './main.js'])
})
self.addEventListener('activate', e => {
var cacheKeeplist = ['pwa-static']
e.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(
keyList.map(function(key) {
if (cacheKeeplist.indexOf(key) === -1) {
return caches.delete(key)
}
})
)
})
)
})
self.addEventListener('fetch', e => {
e.respondWith(
(async function() {
const cache = await caches.open('pwa-dynamic')
const cachedResponse = await cache.match(e.request)
if (cachedResponse) return cachedResponse
const networkResponse = await fetch(e.request)
e.waitUntil(cache.put(e.request, networkResponse.clone()))
return networkResponse
})()
)
})
<file_sep>/main.js
window.onload = async () => {
const network = document.querySelector('#network')
const navigator = window.navigator
const online = navigator.onLine
if (online) {
network.classList.add('badge-success')
network.innerHTML = '<strong>Online ---- 😊</strong>'
} else {
network.classList.add('badge-danger')
network.innerHTML = '<strong>Offline ---- 😭</strong>'
}
if ('serviceWorker' in navigator) {
try {
const swRegistration = await navigator.serviceWorker.register('sw.js')
console.log('SW registred!')
} catch (err) {
console.log('SW reg failed!')
}
} else {
console.log('SW not supported')
}
window.addEventListener('online', () => {
network.classList.remove('badge-danger')
network.classList.add('badge-success')
network.innerHTML = '<strong>Online ---- 😊</strong>'
})
window.addEventListener('offline', () => {
network.classList.remove('badge-success')
network.classList.add('badge-danger')
network.innerHTML = '<strong>Offline ---- 😭</strong>'
})
}
| 494db25d8d478757f303cc541586378329066b28 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | raviCHCopart/raviCHCopart.github.io | 80b7672b960c8eea0f7a15d99fbb2e350c6a2064 | a7efa12d970b70eb7e3eb1b3550062f27a6305ae | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JhPrize.Core
{
public interface IUpdatable<T>
{
void Update(T other);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JhPrize.Core
{
public class PrizePool : INotifyPropertyChanged, IUpdatable<PrizePool>
{
public class Comparer : EqualityComparer<PrizePool>
{
public override bool Equals(PrizePool x, PrizePool y)
{
return x.Title == y.Title;
}
public override int GetHashCode(PrizePool obj)
{
return obj.Title.GetHashCode();
}
}
private string title;
private ObservableCollection<Prize> prizes = new ObservableCollection<Prize>();
private int acceptCount;
private int count;
private int capacity;
public int AcceptCount
{
get => acceptCount; set
{
acceptCount = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(AcceptCount)));
}
}
public int Count
{
get => count; set
{
count = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count)));
}
}
public int Capacity
{
get => capacity; set
{
capacity = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Capacity)));
}
}
public PrizePool()
{
this.Prizes.CollectionChanged += Prizes_CollectionChanged;
}
private void Prizes_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
this.AcceptCount = (from item in Prizes select item.AcceptCount).Sum();
this.Count = (from item in Prizes select item.Count).Sum();
this.Capacity = (from item in Prizes select item.Capacity).Sum();
}
public void Update(PrizePool other)
{
this.Title = other.title;
Extensions.UpdateCollection<Prize>(Prizes, other.Prizes,new Prize.Comparer());
}
public PrizePool(string title, params Prize[] prizes) : this()
{
this.Title = title;
foreach (var item in prizes)
{
this.Prizes.Add(item);
}
}
public string Title
{
get => title; set
{
title = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Title)));
}
}
public ObservableCollection<Prize> Prizes
{
get => prizes; set
{
prizes = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Prizes)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
<file_sep>using JhPrize.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
//https://go.microsoft.com/fwlink/?LinkId=234236 上介绍了“用户控件”项模板
namespace JhPrize.Widget
{
public sealed partial class PrizeCard : UserControl
{
public Prize Prize
{
get { return (Prize)GetValue(PrizeProperty); }
set { SetValue(PrizeProperty, value); }
}
public static readonly DependencyProperty PrizeProperty =
DependencyProperty.Register("Prize", typeof(Prize), typeof(PrizeCard), new PropertyMetadata(new Prize()));
public PrizeCard()
{
this.InitializeComponent();
this.Prize.PropertyChanged += Prize_PropertyChanged;
}
private void Prize_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
Prize = Prize;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
namespace JhPrize.Core
{
public static class Extensions
{
public static void UpdateCollection<T>(ICollection<T> collection, IEnumerable<T> other, EqualityComparer<T> equalityComparer) where T:IUpdatable<T>
{
List<T> otherCopy = other.ToList();
List<T> sourceCopy = collection.ToList();
foreach (var item in sourceCopy)
{
var take = other.TakeWhile((a) => equalityComparer.Equals(a, item));
if (take.Any())
{
item.Update(take.First());
foreach (var item2 in take)
{
otherCopy.Remove(item2);
}
} else
{
collection.Remove(item);
}
}
foreach (var item in otherCopy)
{
collection.Add(item);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JhPrize.Core
{
public class PrizeModel
{
public int id;
public string title;
public string captain;
public string content;
public int capacity;
public int count;
public int accept_count;
public Prize ToPrize()
{
return new Prize(
this.captain,
this.content,
this.accept_count,
this.count,
this.capacity
);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JhPrize.Core
{
public static class ExampleData
{
public static PrizePool[] GeneratePrizePools()
{
return new PrizePool[] {
new PrizePool("完成毅行",
new Prize("一等奖", "星星*10\n漆橙轰趴五折券*1", 0, 0, 1),
new Prize("二等奖", "星星*8\n健身卡一个月*1", 1, 4, 12),
new Prize("三等奖", "星星*7\n漆橙轰趴七折券*5", 2, 3, 8)
),
new PrizePool("未完成毅行",
new Prize("一等奖", "星星*5\nPokeman Go光碟*1",0,0,2),
new Prize("二等奖", "星星*2\n京东100元购物券*1",2,3,10),
new Prize("三等奖", "星星*1\n宝可梦Surface Go背部贴膜*1",0,8,40)
)
};
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JhPrize.Core
{
public class Prize : INotifyPropertyChanged, IUpdatable<Prize>
{
public class Comparer : EqualityComparer<Prize>
{
public override bool Equals(Prize x, Prize y)
{
return x.Title == y.Title;
}
public override int GetHashCode(Prize obj)
{
return obj.Title.GetHashCode();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private string title;
private string detail;
private int acceptCount =10000;
private int count =1000;
private int capacity =1002131;
public Prize()
{
}
public Prize(string title, string detail, int acceptCount, int count, int capacity)
{
this.Title = title;
this.Detail = detail;
this.AcceptCount = acceptCount;
this.Count = count;
this.Capacity = capacity;
}
public string Title
{
get => title; set
{
title = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Title)));
}
}
public string Detail
{
get => detail; set
{
detail = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Detail)));
}
}
public int AcceptCount
{
get => acceptCount; set
{
acceptCount = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(AcceptCount)));
}
}
public int Count
{
get => count; set
{
count = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count)));
}
}
public int Capacity
{
get => capacity; set
{
capacity = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Capacity)));
}
}
public void Update(Prize other)
{
this.Title = other.Title;
this.Detail = other.Detail;
this.AcceptCount = other.AcceptCount;
this.Count = other.Count;
this.Capacity = other.Capacity;
}
}
}
<file_sep>using JhPrize.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板
namespace JhPrize
{
/// <summary>
/// 可用于自身或导航至 Frame 内部的空白页。
/// </summary>
public sealed partial class SettingsPage : Page
{
private SystemNavigationManager navManager;
public SettingsPage()
{
this.InitializeComponent();
navManager = SystemNavigationManager.GetForCurrentView();
navManager.BackRequested += WorkPage_BackRequested;
navManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
this.TextBoxDomain.Text = Api.Domain;
this.PasswordBoxPass.Password = <PASSWORD>;
this.TextBoxDomain.TextChanged += TextBoxDomain_TextChanged;
this.PasswordBoxPass.PasswordChanged += PasswordBoxPass_PasswordChanged;
}
private void PasswordBoxPass_PasswordChanged(object sender, RoutedEventArgs e)
{
Api.Pass = <PASSWORD>;
}
private void TextBoxDomain_TextChanged(object sender, TextChangedEventArgs e)
{
Api.Domain = TextBoxDomain.Text;
}
private void WorkPage_BackRequested(object sender, BackRequestedEventArgs e)
{
if (this.Frame.Content is SettingsPage)
{
if (this.Frame.CanGoBack && e.Handled == false)
{
this.Frame.GoBack();
navManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JhPrize.Core
{
public enum WorkMode
{
AcceptPrize,
Completed,
NoCompleted
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.System;
using System.Collections.ObjectModel;
using JhPrize.Core;
using System.Threading.Tasks;
namespace JhPrize
{
/// <summary>
/// 可用于自身或导航至 Frame 内部的空白页。
/// </summary>
public sealed partial class WorkPage : Page
{
private SystemNavigationManager navManager;
private WorkMode mode;
public WorkPage()
{
this.InitializeComponent();
this.Loaded += WorkPage_Loaded;
navManager = SystemNavigationManager.GetForCurrentView();
navManager.BackRequested += WorkPage_BackRequested;
navManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
ButtonTest.Click += ButtonTest_Click;
ButtonSlideState.Click += ButtonSlideState_Click;
TextBoxNo.KeyUp += TextBoxNo_KeyUp;
}
private void ButtonSlideState_Click(object sender, RoutedEventArgs e)
{
if (GridSlide.Visibility == Visibility.Collapsed)
{
GridSlide.Visibility = Visibility.Visible;
}
else
{
GridSlide.Visibility = Visibility.Collapsed;
}
}
private async void TextBoxNo_KeyUp(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Enter)
{
if (TextBoxNo.Text != "")
{
try
{
BorderErrorMsg.Visibility = Visibility.Collapsed;
TextBoxNo.IsEnabled = false;
var title = mode == WorkMode.Completed ? "完成" : "未完成";
var groupNo = TextBoxNo.Text;
ResponseModel<PrizeModel> result = null;
if (mode == WorkMode.AcceptPrize)
{
result = await Api.AcceptPrizeAsync(groupNo);
}
else
{
result = await Api.DrawPrizeAsync(title, groupNo);
}
TextBlockResult.Text = result.msg;
if (result.data != null)
{
StackPanelPrize.Visibility = Visibility.Visible;
TextBlockPrize.Text = result.data.captain;
TextBlockPrizeDetail.Text = result.data.content;
TextBlockGroup.Text = $"{result.data.title}-{groupNo}";
}
else
{
StackPanelPrize.Visibility = Visibility.Collapsed;
}
}
catch (Exception)
{
BorderErrorMsg.Visibility = Visibility.Visible;
}
finally
{
TextBoxNo.IsEnabled = true;
TextBoxNo.Text = "";
}
}
await UpdatePrizePool();
}
}
private async void ButtonTest_Click(object sender, RoutedEventArgs e)
{
await UpdatePrizePool();
}
private async void WorkPage_Loaded(object sender, RoutedEventArgs e)
{
await UpdatePrizePool();
}
public async Task UpdatePrizePool()
{
try
{
ButtonTest.IsEnabled = false;
TextBlockFresh.Text = "正在刷新";
var data = await Api.GetDataAsync();
this.PrizePools.Clear();
foreach (var item in data)
{
this.PrizePools.Add(item);
}
this.BorderErrorMsg.Visibility = Visibility.Collapsed;
}
catch (Exception)
{
this.BorderErrorMsg.Visibility = Visibility.Visible;
}
finally
{
ButtonTest.IsEnabled = true;
TextBlockFresh.Text = "刷新";
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Parameter is WorkMode mode)
{
this.Mode = mode;
}
base.OnNavigatedTo(e);
}
private void WorkPage_BackRequested(object sender, BackRequestedEventArgs e)
{
if (this.Frame.Content is WorkPage)
{
if (this.Frame.CanGoBack && e.Handled == false)
{
this.Frame.GoBack();
navManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
}
}
}
public ObservableCollection<String> TestStr
{
get { return (ObservableCollection<String>)GetValue(TestStrProperty); }
set { SetValue(TestStrProperty, value); }
}
public static readonly DependencyProperty TestStrProperty =
DependencyProperty.Register("TestStr", typeof(ObservableCollection<String>), typeof(WorkPage), new PropertyMetadata(new ObservableCollection<String>()));
public ObservableCollection<PrizePool> PrizePools
{
get { return (ObservableCollection<PrizePool>)GetValue(PrizePoolsProperty); }
set { SetValue(PrizePoolsProperty, value); }
}
public WorkMode Mode
{
get => mode; set
{
mode = value;
if (value == WorkMode.AcceptPrize)
{
TextBlockTitle.Text = "领奖";
}
else if (value == WorkMode.Completed)
{
TextBlockTitle.Text = "抽奖(完成)";
}
else if (value == WorkMode.NoCompleted)
{
TextBlockTitle.Text = "抽奖(未完成)";
}
}
}
public static readonly DependencyProperty PrizePoolsProperty =
DependencyProperty.Register("PrizePools", typeof(ObservableCollection<PrizePool>), typeof(WorkPage), new PropertyMetadata(new ObservableCollection<PrizePool>()));
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Web.Http;
using Newtonsoft.Json;
namespace JhPrize.Core
{
public enum ApiOption
{
GetData,
Select,
Verify
};
public class Api
{
private static Dictionary<ApiOption, string> dic = new Dictionary<ApiOption, string>()
{
{ ApiOption.GetData, "prize/get_data" },
{ ApiOption.Select,"prize/select" },
{ ApiOption.Verify,"prize/verify" }
};
public static string Pass { get; set; } = "<PASSWORD>";
public static string Domain { get; set; } = "http://localhost/";
public static string GetUrl(ApiOption option)
{
return $"{Domain}{dic[option]}";
}
public async static Task<String> PostAsync(ApiOption option, params KeyValuePair<String,String>[] p)
{
var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(10));
var httpClient = new HttpClient();
var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri( GetUrl(option)));
var responseMessage = await httpClient.PostAsync(new Uri(GetUrl(option)),new HttpFormUrlEncodedContent(p));
if(responseMessage.StatusCode == HttpStatusCode.Ok)
{
return await responseMessage.Content.ReadAsStringAsync();
}
else
{
return null;
}
}
public async static Task<ResponseModel<PrizeModel>> DrawPrizeAsync(string title, string no)
{
ResponseModel<PrizeModel> model = JsonConvert.DeserializeObject<ResponseModel<PrizeModel>>(
await PostAsync(ApiOption.Select,
new KeyValuePair<string, string>("pass", Pass),
new KeyValuePair<string, string>("no", no),
new KeyValuePair<string,string>("title",title)
));
return model;
}
public async static Task<ResponseModel<PrizeModel>> AcceptPrizeAsync(string no)
{
ResponseModel<PrizeModel> model = JsonConvert.DeserializeObject<ResponseModel<PrizeModel>>(
await PostAsync(ApiOption.Verify,
new KeyValuePair<string, string>("pass", Pass),
new KeyValuePair<string, string>("no", no)
));
return model;
}
public async static Task<IEnumerable<PrizePool>> GetDataAsync()
{
ResponseModel<PrizePoolModel[]> model = JsonConvert.DeserializeObject<ResponseModel<PrizePoolModel[]>>(
await PostAsync(ApiOption.GetData, new KeyValuePair<string, string>("pass", Pass)));
List<PrizePool> result = new List<PrizePool>();
return model.data.Select((a) => a.ToPrizePool());
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using JhPrize.Core;
// https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x804 上介绍了“空白页”项模板
namespace JhPrize
{
/// <summary>
/// 可用于自身或导航至 Frame 内部的空白页。
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.ButtonCompleted.Click += ButtonCompleted_Click;
this.ButtonNoCompleted.Click += ButtonNoCompleted_Click;
this.ButtonAcceptPrize.Click += ButtonAcceptPrize_Click;
this.ButtonSettings.Click += ButtonSettings_Click;
}
private void ButtonSettings_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(SettingsPage));
}
private void ButtonNoCompleted_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(WorkPage), WorkMode.NoCompleted);
}
private void ButtonCompleted_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(WorkPage), WorkMode.Completed);
}
private void ButtonAcceptPrize_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(WorkPage),WorkMode.AcceptPrize);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using JhPrize.Core;
//https://go.microsoft.com/fwlink/?LinkId=234236 上介绍了“用户控件”项模板
namespace JhPrize.Widget
{
public sealed partial class PrizePoolCard : UserControl
{
public PrizePoolCard()
{
this.InitializeComponent();
}
public int AcceptCount
{
get { return (int)GetValue(AcceptCountProperty); }
set { SetValue(AcceptCountProperty, value); }
}
public int Count
{
get { return (int)GetValue(CountProperty); }
set { SetValue(CountProperty, value); }
}
public int Capacity
{
get { return (int)GetValue(CapacityProperty); }
set { SetValue(CapacityProperty, value); }
}
public static readonly DependencyProperty AcceptCountProperty =
DependencyProperty.Register("AcceptCount", typeof(int), typeof(PrizePoolCard), new PropertyMetadata(1));
public static readonly DependencyProperty CountProperty =
DependencyProperty.Register("Count", typeof(int), typeof(PrizePoolCard), new PropertyMetadata(2));
public static readonly DependencyProperty CapacityProperty =
DependencyProperty.Register("Capacity", typeof(int), typeof(PrizePoolCard), new PropertyMetadata(3));
private void OnPrizePoolChanged()
{
AcceptCount = (from item in PrizePool.Prizes select item.AcceptCount).Sum();
Count = (from item in PrizePool.Prizes select item.Count).Sum();
Capacity = (from item in PrizePool.Prizes select item.Capacity).Sum();
}
public PrizePool PrizePool
{
get { return (PrizePool)GetValue(PrizePoolProperty); }
set { SetValue(PrizePoolProperty, value); }
}
public static readonly DependencyProperty PrizePoolProperty =
DependencyProperty.Register("PrizePool", typeof(PrizePool), typeof(PrizePoolCard), new PropertyMetadata(new PrizePool(), PrizePoolChangedCallback));
private static void PrizePoolChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((PrizePoolCard)d).OnPrizePoolChanged();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JhPrize.Core
{
public class PrizePoolModel
{
public string title;
public PrizeModel[] data;
public PrizePool ToPrizePool()
{
return new PrizePool(
this.title,
this.data.Select((a) => a.ToPrize()).ToArray()
);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JhPrize.Core
{
public class ResponseModel<T>
{
public int code;
public string msg;
public T data;
}
}
| b41b78ae34add4a60753d20baf15b1f233ae10d4 | [
"C#"
] | 15 | C# | zjutjh/walk2019-jhprize | bd6a9f9e6865edeefea198dc9884c76e1d129d06 | 6b715dc1336834750fd5737051a2d293bc4d436a | |
refs/heads/master | <repo_name>DimaSanKiev/JavaScriptBasics<file_sep>/5-functions/5-1_return/random.js
function getRandomNumber(upper) {
return Math.floor(Math.random() * upper) + 1;
}
console.log(getRandomNumber());
console.log(getRandomNumber(6));
console.log(getRandomNumber(100));
console.log(getRandomNumber(10000));
console.log(getRandomNumber(2));
<file_sep>/7-arrays/7-6_two_dimensional_arrays/playlist.js
var playList = [
['Time Is The Healer (Monada Bootleg Dub)', 'Riva'],
['<NAME>oods & W&W', 'Trigger'],
['Filmic (Ruben de Ronde Remix)', 'Above & Beyond'],
['200 (FSOE 200 Anthem)', 'Aly & Fila'],
['An Angel\'s Love (Vocal Mix)', '<NAME>. feat. <NAME>'],
['Black Is The Color (<NAME> Vs. 2 Devine rmx)', 'DJ vEQ']
];
function print(message) {
document.write(message);
}
function printSongs(songs) {
var listHTML = '<ol>';
for (var i = 0; i < songs.length; i += 1) {
listHTML += '<li><b>' + songs[i][0] + '</b> by <b>' + songs[i][1] + '</b></li>';
}
listHTML += '</ol>';
print(listHTML);
}
printSongs(playList);
<file_sep>/7-arrays/7-2_adding_data/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Musical Playlist</title>
<link rel="stylesheet" href="../../css/styles.css">
</head>
<body>
<h1>My Music Playlist</h1>
<p>The <b>push()</b> method adds one or more elements to the end of an array and returns the new
length of the array.</p>
<p>The <b>unshift()</b> method adds one or more elements to the beginning of an array and returns the new
length of the array.</p>
<div id="listDiv">
</div>
<script src="helpers.js"></script>
<script src="playlist.js"></script>
</body>
</html><file_sep>/7-arrays/7-7_quiz_challenge/quiz.js
var questions = [
['What is the name of a markup language for describing web documents (web pages)?', 'HTML'],
['What language describes how HTML elements are to be displayed on screen, paper, or in other media?', 'CSS'],
['What is the name of a powerful and popular language for programming on the web?', 'JavaScript'],
['What is a name of standard language for accessing databases?', 'SQL'],
['What is the most popular programming language?', 'Java']
];
var rightAnswers = 0;
var question;
var answer;
var input;
var correctAnswers = [];
var wrongAnswers = [];
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function buildList(list) {
var listHTML = '<ol>';
for (var i = 0; i < list.length; i += 1) {
listHTML += '<li>' + list[i][0] + ' -' + list[i][1] + '</li>';
}
listHTML += '</ol>';
return listHTML;
}
for (var i = 0; i < questions.length; i++) {
question = questions[i][0];
answer = questions[i][1].toUpperCase();
input = prompt(question).toUpperCase();
if (input === answer) {
rightAnswers++;
correctAnswers.push([question, input]);
} else {
wrongAnswers.push([question, input]);
}
}
report = '<br/><h2>You got <b>' + rightAnswers + '</b> right answer(s).</h2>';
if (correctAnswers.length > 0) {
html += '<p style="color: green">You got these question(s) correct:</p>';
html += buildList(correctAnswers);
if (wrongAnswers.length === 0) {
html += '<p>You haven\'t any incorrect answers, congratulations!</p>';
}
}
if (wrongAnswers.length > 0) {
html += '<p style="color: darkred">You got these question(s) wrong:</p>';
html += buildList(wrongAnswers);
if (correctAnswers.length === 0) {
html += '<p>Sorry, all your answers are wrong... Study more and try again.</p>';
}
}
print(html);<file_sep>/7-arrays/7-2_adding_data/playlist.js
var playlist = [];
// The push() method adds one or more elements to the end of an array and returns the new length of the array.
playlist.push('Anthem');
playlist.push('Angel\'s Love', 'Black Is The Color');
// The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
playlist.unshift('Filmic');
playlist.unshift('Time Is The Healer', 'Trigger');
buildList(playlist);<file_sep>/4-decisions/4-3_quiz_game/quiz.js
// quiz begins, no answers correct
var correctAnswers = 0;
alert('Please answer the 5 following questions.');
// ask questions
var answer1 = prompt('How much seconds does it take for light to reach the Moon from the Earth?');
if (parseInt(answer1) === 1) {
correctAnswers += 1;
}
var answer2 = prompt('What is the capital of Australia?');
if (answer2.toUpperCase() === 'CANBERRA') {
correctAnswers += 1;
}
var answer3 = prompt('A brick weighs 1kg plus a half of a brick. How much kilograms does a brick weigh?');
if (parseInt(answer3) === 2) {
correctAnswers += 1;
}
var answer4 = prompt('What is the most popular programming language in 2016?');
if (answer4.toUpperCase() === 'JAVA') {
correctAnswers += 1;
}
var answer5 = prompt('What is the major chemical element human body consists of?');
if (answer5.toUpperCase() === 'OXYGEN' || answer5.toUpperCase() === 'O2' || answer5.toUpperCase() === 'O') {
correctAnswers += 1;
}
// output results
document.write('<p>You got ' + correctAnswers + ' out of 5 questions correct</p>');
// output rank
if (correctAnswers === 5) {
document.write('<p><strong>You won a GOLD medal!</strong></p>');
} else if (correctAnswers >= 3) {
document.write('<p><strong>You won a SILVER medal!</strong></p>');
} else if (correctAnswers >= 1) {
document.write('<p><strong>You won a BRONZE medal!</strong></p>');
} else {
document.write('<p><strong>Sorry, you need to study more, try again later.</strong></p>')
}
<file_sep>/3-numbers/3-3_random_number/app.js
var dieRolll = Math.floor(Math.random() * 6 + 1);
alert('You rolled a ' + dieRolll);<file_sep>/7-arrays/7-5_array_methods/search.js
/*
The join() method takes an array and returns a string with all the items in the array
separated by a supplied character, such as comma or a colon.
This is a great way to display all the items in an array in a single line.
*/
/*
Another useful method is concat(). It can be used to add one list to another.
*/
/*
The indexOf() method lets to search an array for a particular value. If the value is in
the list, than that element's position is returned. However, if the item is not in the list,
then the indexOf() method returns the value -1.
*/
var inStock = ['apples', 'eggs', 'milk', 'cookies', 'cheese', 'bread', 'lettuce', 'carrot',
'broccoli', 'pizza', 'potato', 'crackers', 'onion', 'tofu', 'frozen dinner', 'cucumber'];
var search;
function print(message) {
document.write('<p>' + message + '</p>');
}
while (true) {
search = prompt('Search for a product in our store. Type \'list\' to show all of the' +
' produce and \'quit\' to exit');
search = search.toLowerCase();
if (search === 'quit') {
break;
} else if (search === 'list') {
print(inStock.join(', '));
} else {
if (inStock.indexOf(search) > -1) {
print('Yes, we have ' + search + ' in the store.');
} else {
print('– ' + search + ' is not in stock.');
}
}
}<file_sep>/5-functions/5-3_random_number_challenge/random.js
function generateRandomNumber(lower, upper) {
return Math.floor(Math.random() * (upper - lower + 1)) + lower;
}
var min = parseInt(prompt('Insert the lower number:'));
var max = parseInt(prompt('Insert the upper number:'));
if (isNaN(max) || isNaN(max)) {
document.write('<p>Please enter the numbers.</p>');
throw new Error('Please enter the numbers.');
} else {
var random = generateRandomNumber(min, max);
document.write('<p>The random number between ' + min + ' and ' + max + ' is ' + random + '.</p>');
}<file_sep>/8-objects/8-4_students_challenge/student_report.js
var message;
var student;
var search;
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function getStudentReport(results) {
var report = '';
for (var i = 0; i < results.length; i++) {
report += '<h2>Student: ' + results[i].name + '</h2>';
report += '<p>Track: ' + results[i].track + '</p>';
report += '<p>Achievements: ' + results[i].achievements + '</p>';
report += '<p>Points: ' + results[i].points + '</p>';
}
return report;
}
while (true) {
var results = [];
message = '';
search = prompt('Please input student\'s name [John] (or type \'quit\' to exit):');
if (search === null || search.toLowerCase() === 'quit') {
break;
} else {
for (var i = 0; i < students.length; i++) {
student = students[i];
if (student.name === search) {
results.push(student);
}
message = getStudentReport(results);
print(message);
}
results.length = 0;
if (message === '') {
message = '<h2>There is no such student with name ' + search + '.</h2>';
print(message);
}
}
}<file_sep>/1-intro/1-1/scripts.js
alert("Hello user");
document.write("<h1>Welcome to JavaScript Basics</h1>");
alert("Thanks for visiting");<file_sep>/3-numbers/3-4_random_challenge/random.js
var min = parseInt(prompt('Please input minimum number:'));
var max = parseInt(prompt('Please input maximum number:'));
var random = Math.floor(Math.random() * (max - min + 1)) + min;
var message = 'The random number from ' + min + ' and ' + max + ' is ' + random;
document.write(message);<file_sep>/5-functions/5-2_parameters/area.js
function getArea(width, length, unit) {
var area = width * length;
return area + " " + unit;
}
console.log(getArea(10, 20, 'sq m')); | b99a37eed4d713df462c6f9160897c95f6780ea7 | [
"JavaScript",
"HTML"
] | 13 | JavaScript | DimaSanKiev/JavaScriptBasics | fa8b3310a8f05b2e28faf0878f4ebf8de719fd6d | 667a101488f664c2e0034f14b2d3fcdb5f362fcb | |
refs/heads/master | <repo_name>sadlll/ablog<file_sep>/config.py
# coding:utf-8
PORT = 8000
DEBUG = True
TITLE = 'ablog'
TEMPLATE = 'jinja2' # jinja2/mako/tornado
DATABASE_URI = "sqlite:///database.db"
COOKIE_SECRET = "<KEY>"
try:
from private import *
except:
pass
<file_sep>/README.md
# ablog
markdown blog
<file_sep>/view/user.py
# coding:utf-8
from view import route, url_for, View, LoginView, NoLoginView
from model.user import User
@route('/signin', name='signin')
class SignIn(NoLoginView):
def get(self):
self.render('user/signin.html')
def post(self):
username = self.get_argument("username")
password = self.get_argument("password")
remember = self.get_argument('remember', False)
next = self.get_argument('next', None)
error = False
u = User.auth(username, password)
if not u:
error = True
self.messages.error("帐号或密码错误!")
if not error:
self.messages.success("登陆成功!")
expires = 30 if remember else None
self.set_secure_cookie("u", u.key, expires_days=expires)
if next:
return self.redirect(next)
return self.redirect(url_for("index"))
self.render('user/signin.html')
@route('/signout', name='signout')
class SignOut(LoginView):
def get(self):
self.clear_cookie('u')
self.messages.success("您已成功登出!")
self.redirect(url_for("index"))
@route('/signup', name='signup')
class SignUp(NoLoginView):
def get(self):
self.render('user/signup.html')
def post(self):
username = self.get_argument("username")
password = self.get_argument("password")
password_again = self.get_argument("password_again")
next = self.get_argument('next', None)
error = False
if len(username) < 3:
error = True
self.messages.error("用户名长度必须大于等于3")
if len(password) < 3:
error = True
self.messages.error("密码长度必须大于等于3")
if User.exist(username):
error = True
self.messages.error("用户已存在!")
if password != password_again:
error = True
self.messages.error("两次输入的密码不一致!")
if not error:
u = User.new(username, password)
self.messages.success("账户创建成功!")
self.redirect(url_for('signin') + (('?next=%s' % next) if next else ''))
return
self.render('user/signup.html')
| 854a60c895a73437d5840268d7c6cd28f1b019af | [
"Markdown",
"Python"
] | 3 | Python | sadlll/ablog | d04b532751c297fe9cd25563d08f48e8aaee7f48 | dc235f12bd3d0038bf823889efdef5de7a576b37 | |
refs/heads/master | <file_sep>extern crate gcc;
fn main() {
let out_dir = std::env::var("OUT_DIR").unwrap();
gcc::compile_library(
"libstb_truetype.a", &["stb_truetype.c"]);
println!("cargo:rustc-flags=-L native={}", out_dir);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#define STBTT_malloc(x,u) malloc(x)
#define STBTT_free(x,u) free(x)
// force following include to generate implementation
#define STB_TRUETYPE_IMPLEMENTATION
#include "stb_truetype.h"
<file_sep>[package]
name = "stb_tt"
version = "0.0.1"
authors = ["ozkriff"]
build = "./build.rs"
[lib]
name = "stb_tt"
[[example]]
name = "example"
[build-dependencies.gcc]
gcc = "^0.3.17"
[dependencies]
libc = "^0.1.10"
<file_sep>// See LICENSE file for copyright and license details.
extern crate stb_tt;
use std::path::{Path};
fn byte_to_char(n: u8) -> &'static str {
let chars = [" ", ".", ":", "i", "o", "V", "M", "@"];
let n = (n >> 5) as usize;
assert!(n < chars.len());
chars[n]
}
fn print_char(font: &stb_tt::Font, c: char) {
let glyph_index = font.find_glyph_index(c);
let (bitmap, w, h, _, _) = font.get_glyph(glyph_index);
for j in 0 .. h {
for i in 0 .. w {
print!("{}", byte_to_char(bitmap[(j * w + i) as usize]));
}
print!("\n");
}
}
fn main() {
let font = stb_tt::Font::new(&Path::new("assets/DroidSerif-Regular.ttf"), 30.0);
print_char(&font, '@');
}
// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
<file_sep>#
[![travis-ci-img][]] [travis-ci]
Rust bindings for `stb_truetype`: https://github.com/nothings/stb
[travis-ci-img]: https://travis-ci.org/ozkriff/stb-tt-rs.png?branch=master
[travis-ci]: https://travis-ci.org/ozkriff/stb-tt-rs
<file_sep>// See LICENSE file for copyright and license details.
extern crate libc;
use libc::{c_int, c_uchar};
use std::fs::{File};
use std::path::{Path};
use std::io::{Read};
#[link(name = "stb_truetype")]
extern {}
#[allow(dead_code, missing_copy_implementations, non_snake_case, improper_ctypes)]
pub mod ffi {
use libc::{c_int, c_uchar, c_float, c_void};
use std::ptr;
pub struct FontInfo {
userdata: *const c_void,
// pointer to .ttf file
data: *const c_uchar,
// offset of start of font
fontstart: c_int,
// number of glyphs, needed for range checking
numGlyphs: c_int,
// table locations as offset from start of .ttf
loca: c_int,
head: c_int,
glyf: c_int,
hhea: c_int,
hmtx: c_int,
kern: c_int,
// a cmap mapping for our chosen character encoding
index_map: c_int,
// format needed to map from glyph index to glyph
indexToLocFormat: c_int,
}
impl FontInfo {
pub fn new() -> FontInfo {
FontInfo {
userdata: ptr::null(),
data: ptr::null(),
fontstart: 0,
numGlyphs: 0,
loca: 0,
head: 0,
glyf: 0,
hhea: 0,
hmtx: 0,
kern: 0,
index_map: 0,
indexToLocFormat: 0,
}
}
}
extern {
pub fn stbtt_GetFontOffsetForIndex(
data: *const c_uchar,
index: c_int,
) -> c_int;
pub fn stbtt_InitFont(
info: *mut FontInfo,
data2: *const c_uchar,
fontstart: c_int,
);
pub fn stbtt_GetFontVMetrics(
info: *const FontInfo,
ascent: *mut c_int,
descent: *mut c_int,
lineGap: *mut c_int,
);
pub fn stbtt_FindGlyphIndex(
info: *const FontInfo,
unicode_codepoint: c_int,
) -> c_int;
pub fn stbtt_GetGlyphHMetrics(
info: *const FontInfo,
glyph_index: c_int,
advanceWidth: *mut c_int,
eftSideBearing: *mut c_int,
);
pub fn stbtt_GetGlyphBitmapBox(
font: *const FontInfo,
glyph: c_int,
scale_x: c_float,
scale_y: c_float,
ix0: *mut c_int,
iy0: *mut c_int,
ix1: *mut c_int,
iy1: *mut c_int,
);
pub fn stbtt_GetGlyphKernAdvance(
info: *const FontInfo,
glyph1: c_int,
glyph2: c_int,
);
pub fn stbtt_MakeGlyphBitmap(
info: *const FontInfo,
output: *const c_uchar,
out_w: c_int,
out_h: c_int,
out_stride: c_int,
scale_x: c_float,
scale_y: c_float,
glyph: c_int,
);
pub fn stbtt_ScaleForPixelHeight(
info: *const FontInfo,
height: c_float,
) -> c_float;
pub fn stbtt_GetGlyphBitmap(
info: *const FontInfo,
scale_x: c_float,
scale_y: c_float,
glyph: c_int,
width: *mut c_int,
height: *mut c_int,
xoff: *mut c_int,
yoff: *mut c_int,
) -> *const c_uchar;
}
}
pub struct Font {
font_info: ffi::FontInfo,
scale: f32,
_data: Vec<c_uchar>,
_height: f32,
_ascent: i32,
_descent: i32,
_line_gap: i32,
}
impl Font {
pub fn new(font_path: &Path, height: f32) -> Font {
let mut file = File::open(font_path).ok().expect("Can`t open font file");
Font::from_reader(&mut file, height)
}
pub fn from_reader(reader: &mut Read, height: f32) -> Font {
let mut data = vec![];
reader.read_to_end(&mut data).ok().expect("Can not read from reader");
let mut font_info = ffi::FontInfo::new();
unsafe {
let font_offset = ffi::stbtt_GetFontOffsetForIndex(&data[0] as *const u8, 0);
ffi::stbtt_InitFont(&mut font_info, &data[0] as *const u8, font_offset);
}
let scale = unsafe {
ffi::stbtt_ScaleForPixelHeight(&font_info, height)
};
let mut c_ascent: c_int = 0;
let mut c_descent: c_int = 0;
let mut c_line_gap: c_int = 0;
unsafe {
ffi::stbtt_GetFontVMetrics(&font_info,
&mut c_ascent, &mut c_descent, &mut c_line_gap);
}
let ascent = (c_ascent as f32 * scale) as i32;
let descent = (c_descent as f32 * scale) as i32;
let line_gap = (c_line_gap as f32 * scale) as i32;
Font {
font_info: font_info,
scale: scale,
_data: data,
_height: height,
_ascent: ascent,
_descent: descent,
_line_gap: line_gap,
}
}
pub fn get_glyph(&self, glyph_index: i32) -> (Vec<c_uchar>, i32, i32, i32, i32) {
let mut w = 0;
let mut h = 0;
let mut xoff = 0;
let mut yoff = 0;
let bitmap = unsafe {
let scale_x = 0.0;
let scale_y = self.scale;
let buf = ffi::stbtt_GetGlyphBitmap(
&self.font_info,
scale_x,
scale_y,
glyph_index as c_int,
&mut w,
&mut h,
&mut xoff,
&mut yoff,
);
std::slice::from_raw_parts(buf, (w * h) as usize).to_vec()
};
(bitmap, w as i32, h as i32, xoff as i32, yoff as i32)
}
pub fn find_glyph_index(&self, c: char) -> i32 {
unsafe {
ffi::stbtt_FindGlyphIndex(&self.font_info, c as c_int) as i32
}
}
pub fn get_glyph_bitmap_box(&self, glyph_index: i32) -> (i32, i32, i32, i32) {
let scale_x = 0.0;
let scale_y = self.scale;
let mut ix0 = 0;
let mut iy0 = 0;
let mut ix1 = 0;
let mut iy1 = 0;
unsafe {
ffi::stbtt_GetGlyphBitmapBox(
&self.font_info,
glyph_index as c_int,
scale_x,
scale_y,
&mut ix0,
&mut iy0,
&mut ix1,
&mut iy1,
);
}
(ix0 as i32, iy0 as i32, ix1 as i32, iy1 as i32)
}
}
// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
| a29e5159bbb49b0c1c88f345c363b6f0e7dd2de7 | [
"TOML",
"Rust",
"C",
"Markdown"
] | 6 | Rust | ozkriff/stb-tt-rs | f6b789c5ec2afd12b536daf457ea3c5810521d71 | 52c0a434b0a161399bb4fd5242e0f48320fb8bcc | |
refs/heads/master | <repo_name>raivitor/papudinho<file_sep>/www/js/Ctrl_Home.js
app.controller('Home', ['$scope', '$http', '$ionicModal', '$ionicPopup','$rootScope','$window','$location','Geolocalizacao', function($scope, $http, $ionicModal, $ionicPopup, $rootScope,$window,$location,Geolocalizacao) {
window.localStorage['login'] = 1;
function getGpS(){
//Localizacao do GPS
navigator.geolocation.getCurrentPosition(function(position) {
window.localStorage['latitude'] = position.coords.latitude;
window.localStorage['longitude'] = position.coords.longitude;
console.log(position.coords.latitude, position.coords.longitude)
Geolocalizacao.UpdateGps();
}, function(error) {
console.log('Erro ao pegar localização: ' + error.message);
});//{ timeout: 60000 });
}
function timedCount() {
getGpS()
document.getElementsByClassName("title").innerHTML = "teste";
var time;
if(window.localStorage['login'] == 1){
//clearTimeout(time);
$http({
url: servidor+'/webservice/cards/due_date',
method: "GET",
params: {
user: G_usuario.id
}
}).
success(function (data, status, headers, config) {
console.log(data)
$scope.CartoesVencimento = data;
if(data == 0){
$scope.msg = "Nenhum clube a expirar";
}
else{
$scope.msg = "Clubes a expirar";
}
}).
error(function (data, status, headers, config) {
console.log('Error home');
});
return 0;
}
else{
time = setTimeout(function(){ timedCount() }, 2000);
}
}
timedCount();
$scope.checkin = function(bar){
$http({
url: servidor+'/webservice/check_in',
method: "POST",
params: {
bar_id: bar,
user_id: G_usuario.id
}
}).
success(function (data, status, headers, config) {
$scope.closeModal(1);
alerta($ionicPopup, "Check-in", "Check-in realizado com sucesso!");
}).
error(function (data, status, headers, config) {
$scope.closeModal(1);
alerta($ionicPopup, "Check-in", "Erro ao realizar Check-in, tente novamente.");
console.error('Checkin');
});
}
//convide
$scope.convideAmigo = function() {
console.log('amigo')
window.plugins.socialsharing.share('Estou usando o WhiskYou Clube do Whisky, vamos tomar uma?!');
$scope.closeModal(2);
};
$scope.convideApp = function() {
console.log('app')
window.plugins.socialsharing.share('Baixe o app na GOOGLE PLAY (http://urele.com/WhiskYou-Android) ou na APP STORE (http://urele.com/WhiskYou-IOS) e entre para o maior clube de apreciadores de Whisky do mundo =D');
$scope.closeModal(2);
};
$scope.sugerir = function() {
console.log('sugeir')
$scope.closeModal(2)
$scope.closeModal(1)
$location.path("/addBar");
//$window.location.href = '/#/addBar';
};
// Modal 1
$ionicModal.fromTemplateUrl('my-modal.html', {
id: '1', // We need to use and ID to identify the modal that is firing the event!
scope: $scope,
backdropClickToClose: false,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.oModal1 = modal;
});
// Modal 2
$ionicModal.fromTemplateUrl('shared-modal.html', {
id: '2', // We need to use and ID to identify the modal that is firing the event!
scope: $scope,
backdropClickToClose: false,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.oModal2 = modal;
});
$scope.openModal = function(index) {
if (index == 1) $scope.oModal1.show();
else $scope.oModal2.show();
};
$scope.closeModal = function(index) {
if (index == 1) $scope.oModal1.hide();
else $scope.oModal2.hide();
};
/* Listen for broadcasted messages */
$scope.$on('modal.shown', function(event, modal) {
console.log('Modal ' + modal.id + ' is shown!');
navigator.geolocation.getCurrentPosition(function(position) {
window.localStorage['latitude'] = position.coords.latitude;
window.localStorage['longitude'] = position.coords.longitude;
console.log(position.coords.latitude, position.coords.longitude)
console.log(window.localStorage['latitude'],window.localStorage['longitude'])
$http({
url: servidor+'/webservice/get_near_bars',
method: "GET",
params: {
latitude: window.localStorage['latitude'],
longitude: window.localStorage['longitude']
}
}).
success(function (data, status, headers, config) {
$scope.Bares = data;
}).
error(function (data, status, headers, config) {
console.log('Error bares');
});
}, function(error) {
alert("Erro ao obter lista de bares...")
console.log('Erro ao pegar localização: ' + error.message);
});
});
$scope.$on('modal.hidden', function(event, modal) {
console.log('Modal ' + modal.id + ' is hidden!');
});
// Cleanup the modals when we're done with them (i.e: state change)
// Angular will broadcast a $destroy event just before tearing down a scope
// and removing the scope from its parent.
$scope.$on('$destroy', function() {
console.log('Destroying modals...');
$scope.oModal1.remove();
$scope.oModal2.remove();
});
}]);<file_sep>/www/js/Ctrl_Amigos.js
app.controller('Amigos', ['$scope', '$ionicModal', '$ionicPopup', 'Amizade', function($scope, $ionicModal, $ionicPopup, Amizade) {
var amigos;
$scope.countpush = false;
$scope.solicitacoes;
$scope.solPen = 0; //Quantidade de solicitacoes pendentes
//console.log(G_usuario.id);
//G_usuario.id = 7; //msn
//G_usuario.id = 13; //gmail
ListarAmigos();
ListarSolicitacoes();
$scope.doRefresh = function(){
$scope.msg = ""
ListarAmigos();
ListarSolicitacoes();
$scope.$broadcast('scroll.refreshComplete');
}
function ListarAmigos(){
Amizade.getAllAmigos(G_usuario.id).then(function(_amigos){
$scope.Amigos = _amigos;
if($scope.Amigos != -1){
if($scope.Amigos.length == 0 ){
$scope.msg = "Você ainda não tem amigos, clique no + para adicionar novos amigos";
}
}
console.log($scope.Amigos);
});
}
function ListarSolicitacoes(){
Amizade.getAllSolicitacoes(G_usuario.id).then(function(_solicitacoes){
$scope.solicitacoes = _solicitacoes;
$scope.solPen = $scope.solicitacoes.length;
console.log($scope.solicitacoes);
});
}
$scope.aceitar = function(idSolicitacao){
$scope.countpush = true;
$scope.msg = ""
console.log(idSolicitacao);
Amizade.AceitarAmizade(idSolicitacao);
ListarAmigos();
ListarSolicitacoes();
$scope.$digest();
}
$scope.deletar = function(idSolicitacao, nome) {
var confirmPopup = $ionicPopup.confirm({
title: 'Cancelar solicitação',
template: 'Deseja excluir a amizade de '+nome+' ?',
cancelText: 'Manter',
cancelType: 'button-positive',
okText: 'Excluir',
okType: 'button-assertive'
});
confirmPopup.then(function(res) {
if(res) {
Amizade.RecusarAmizade(idSolicitacao);
ListarAmigos();
ListarSolicitacoes();
}
});
};
$ionicModal.fromTemplateUrl('modal-amigos.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
$scope.openModal = function(id) {
$scope.modal.show();
};
$scope.closeModal = function() {
$scope.countpush = true;
$scope.modal.hide();
};
//Cleanup the modal when we're done with it!
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
// Execute action on hide modal
$scope.$on('modal.hidden', function() {
// Execute action
});
// Execute action on remove modal
$scope.$on('modal.removed', function() {
// Execute action
});
}]);<file_sep>/www/js/Ctrl_UpdateCartao.js
app.controller('UpdateCartao', ['$scope', '$http', '$location', '$ionicPopup', 'CartoesPessoais', '$stateParams', '$ionicScrollDelegate', '$ionicModal', function($scope, $http, $location, $ionicPopup, CartoesPessoais, $stateParams, $ionicScrollDelegate, $ionicModal) {
console.log($stateParams.cartaoId);
var fotoCard = 0;
var fotoDrink = 0;
var req = {
method: 'GET',
url: servidor+'/webservice/cards/'+$stateParams.cartaoId,
}
$http(req).
then(function (sucesso) {
console.log(sucesso);
$scope.cartao = sucesso.data[0];
$scope.id = $stateParams.cartaoId;
$scope.bar = sucesso.data[0].bar;
$scope.drink = sucesso.data[0].drink;
$scope.historico = sucesso.data[0].historics;
$scope.doses = $scope.historico[0].remaining_doses;
$scope.imgDrink = $scope.historico[0].image_drink.url;
$scope.imgCard = $scope.historico[0].image_card.url;
return sucesso;
},
function(fail){
console.error("fail getCartoes - id"+id);
return -1;
});
$ionicModal.fromTemplateUrl('modal-ft.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
$scope.ChangeRange = function(val){
$scope.doses = parseInt($scope.doses) + parseInt(val);
if($scope.doses <= 0)
$scope.doses = 0;
if($scope.doses >= 20)
$scope.doses = 20;
}
$scope.openModal = function(id) {
if(id == 1){
$scope.titulo = "Bebida";
$scope.img = $scope.imgDrink;
}
else if (id == 2){
$scope.titulo = "Cartão";
$scope.img = $scope.imgCard;
}
$scope.modal.show();
};
$scope.closeModal = function() {
$scope.modal.hide();
};
//Cleanup the modal when we're done with it!
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
// Execute action on hide modal
$scope.$on('modal.hidden', function() {
// Execute action
});
// Execute action on remove modal
$scope.$on('modal.removed', function() {
// Execute action
});
$scope.capturePhoto = function(id) {
if(id == 1)
navigator.camera.getPicture(onSuccess, onFail, { quality: 30, destinationType: Camera.DestinationType.DATA_URL });
else if(id == 2)
navigator.camera.getPicture(onSuccess2, onFail2, { quality: 30, destinationType: Camera.DestinationType.DATA_URL });
}
function onSuccess(imageData) {
fotoDrink = imageData;
$scope.imgDrink = "data:image/jpeg;base64," + fotoDrink;
$scope.$digest();
}
function onFail(message) {
fotoDrink = 0;
}
function onSuccess2(imageData) {
fotoCard = imageData;
$scope.imgCard = "data:image/jpeg;base64," + fotoCard;
$scope.$digest();
}
function onFail2(message) {
fotoCard = 0;
}
$scope.submitcartao = function() {
if(fotoDrink == 0){
alerta($ionicPopup, "Notificação", "Tire uma foto da bebida para continuar.");
return 0;
}
if(fotoCard == 0){
alerta($ionicPopup, "Notificação", "Tire uma foto do cartão para continuar.");
return 0;
}
$scope.checked = true;
$ionicScrollDelegate.scrollTop();
var req = {
method: 'POST',
url: servidor+'/webservice/update_card',
data: {
card_id: $scope.id,
remaining_doses : $scope.doses,
image_card: $scope.imgCard,
image_drink: $scope.imgDrink
}
}
console.log(req);
$http(req).then(function(data){
$scope.checked = false;
CartoesPessoais.atualizar(G_usuario.id);
$scope.bebida = null;
$scope.bar = null;
fotoCard = 0;
fotoDrink = 0;
$scope.imgCard = null;
$scope.imgDrink = null;
$scope.msg = " ";
alerta($ionicPopup, "Notificação", "Cartão atualizado com sucesso!");
$location.path('/menu/meuscartoes');
}, function(data){
$scope.checked = false;
alerta($ionicPopup, "Notificação", "Erro ao atualizar o cartão, tente novamente.");
console.error(data);
});
return 0;
}
$scope.$on('updatecartao', function() {
$scope.submitcartao();
})
}]);
app.controller('FooterUpdateCartao', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.click1 = function () {
$rootScope.$broadcast('updatecartao');
}
}]);<file_sep>/www/js/papuchat.js
/*
v.0.0.1
Toda alteração que for comitada deve gerar um nova versão desde arquivo
.. log de alterações...
*/
function generateUUID(){
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
.replace(/[xy]/g, function(c) {var r = Math.random()*16|0,v=c=='x'?r:r&0x3|0x8;return v.toString(16);});
}
var Papuchat = {
ref: new Firebase('https://chat-prot.firebaseio.com')
};
Papuchat.isIncorret = function(message){
var log = null
if(!message.from_id)
log = "Está faltando a chave from_id : Id de quem está enviado a mensagem.";
if(!message.to_id)
log = "Está faltando a chave to_id : Id de quem está recebendo a mensagem.";
if(!message.from)
log = "Está faltando a chave from : Nome de quem está enviando a mensagem.";
if(!message.to)
log = "Está faltando a chave to : Nome de quem está recebendo a mensagem.";
if(!message.text)
log = "Está faltando a chave text : texto da mensagem.";
var stack = new Error(log).stack
if(log) return console.error(stack);
return false;
};
/* Iniciando uma conversa */
Papuchat.startChat = function(message){
message.created_at = new Date().toString();
if(this.isIncorret(message)) return;
var chatUUID = generateUUID();
// Iniciador
var fromUserRef = this.ref.child(message.from_id + "/" +chatUUID);
fromUserRef.set(message);
// recebedor
var toUserRef = this.ref.child(message.to_id + "/" +chatUUID);
toUserRef.set(message);
var messagesRef = this.ref.child( "messages/" +chatUUID);
messagesRef.push(message);
sendPush(message.from, message.text, message.to_id);
};
function sendPush(name, message, to_id){
var data = {
name: name,
message: message,
to_id: to_id
}
//$.post('/webservice/chat/notification', data, function(){});
}
Papuchat.deleteChat = function(chatUUID, from_id, to_id){
// Iniciador
var fromUserRef = this.ref.child(from_id + "/" +chatUUID);
fromUserRef.remove();
// recebedor
var toUserRef = this.ref.child(to_id + "/" +chatUUID);
toUserRef.remove();
var messagesRef = this.ref.child( "messages/" +chatUUID);
messagesRef.remove();
};
Papuchat.getChats = function(userID, done){
var userRef = this.ref.child(userID);
userRef.on("value", function(snapshot){
var results = [];
snapshot.forEach(function(snap) {
var data = snap.val();
data.id = snap.key();
results.push(data);
});
done(results);
});
};
Papuchat.getMessages = function(chatUUID, done){
var userRef = this.ref.child( "messages/" +chatUUID);
userRef.endAt().limit(100).on("value", function(snapshot){
var results = [];
snapshot.forEach(function(snap) {
var data = snap.val();
data.id = snap.key();
results.push(data);
});
done(results);
});
};
Papuchat.send = function(chatUUID, message){
if(this.isIncorret(message)) return;
message.created_at = new Date().toString();
var toUserRef = this.ref.child(message.to_id + "/" +chatUUID);
toUserRef.update(message);
var fromUserRef = this.ref.child( message.from_id + "/" + chatUUID);
fromUserRef.update(message);
var messagesRef = this.ref.child( "messages/" +chatUUID);
messagesRef.push(message);
//sendPush(message.from, message.text, message.to_id);
// Atualizando mensagens novas
var newMessages = this.ref.child(message.to_id + "/" + chatUUID + "/news");
newMessages.transaction(function (current_value) {
return (current_value || 0) + 1;
});
};
Papuchat.cleanNews = function(userID, chatUUID){
var fromUserRef = this.ref.child( userID + "/" + chatUUID);
fromUserRef.update({ news: 0 });
};
var directpush = {};
directpush.ref = new Firebase('https://chat-prot.firebaseio.com/directpush');
/* Envia uma notificação direta para um cliente. */
directpush.push = function(id, message){
var ref = this.ref.child(id);
ref.push(message);
};
/* Registrar callback para toda vez que um mensagem dicionada disparar ele. */
directpush.on = function(id, done){
var ref = this.ref.child(id);
ref.on('child_added', function(dataSnapshot) {
done(dataSnapshot.val());
});
};
/* retorna todas as mensagens diretas do usuário. */
directpush.all = function(id, done){
var ref = this.ref.child(id);
ref.on("value", function(snapshot){
var results = [];
snapshot.forEach(function(snap) {
results.push(snap.val());
});
done(results);
});
};
/* Deletar mensagens */
directpush.clean = function(id, message){
var ref = this.ref.child(id);
ref.remove();
};
<file_sep>/www/js/Ctrl_NovaSenha.js
app.controller('NovaSenha', ['$scope', '$http', '$location', '$ionicPopup', function($scope, $http, $location, $ionicPopup) {
$scope.checked = false;
$scope.submitsenha = function() {
if($scope.email == undefined ){
$scope.msg = "O campo 'Email' está vazio";
return 0;
}
$scope.checked = true;
$http({
url: servidor+'/webservice/reset_password/',
method: "POST",
params: {
email: $scope.email
}
}).
success(function (data, status, headers, config) {
$scope.checked = false;
alerta($ionicPopup, "Notificação", "Enviamos a nova senha para o seu email.");
$location.path('home');
}).
error(function (data, status, headers, config) {
$scope.checked = false;
alerta($ionicPopup, "Notificação", "Erro ao enviar a nova senha, tente novamente mais tarde.");
console.log('Error NovaSenha');
console.log("Data: "+data);
console.log("Status: "+status);
console.log("headers: "+headers);
console.log("Config: "+config);
});
}
}]);<file_sep>/www/js/Ctrl_AddBar.js
app.controller('AddBar', ['$scope', '$http', '$location', '$ionicPopup', function($scope, $http, $location, $ionicPopup) {
$scope.name = "";
$scope.phone = "";
$scope.state = "";
$scope.city = "";
$scope.district = "";
$scope.street = "";
$scope.number = "";
$scope.email = "";
$scope.Gps = function(){
GetLocation();
$http({
url: 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+window.localStorage['latitude']+','+window.localStorage['longitude']+'&sensor=true',
method: "GET"
}).
success(function (data, status, headers, config) {
$scope.street = data.results[0].address_components[1].short_name;
$scope.district = data.results[0].address_components[2].short_name;
$scope.city = data.results[0].address_components[3].short_name;
$scope.state = data.results[0].address_components[5].short_name;
}).
error(function (data, status, headers, config) {
console.log(data);
});
}
$scope.submitbar = function() {
if($scope.name == "" || $scope.phone == "" || $scope.state == "" || $scope.city == "" || $scope.district == "" || $scope.street == "" || $scope.number == "" || $scope.email == "" ){
alert("Preencha todos os dados")
return false;
}
$scope.msg = "";
GetLocation();
// console.log("latitude: "+window.localStorage['latitude']);
// console.log("longitude: "+window.localStorage['longitude']);
if(window.localStorage['latitude'] == undefined){
$scope.msg = "Ligue o GPS para termos uma localização precisa" ;
return 0;
}
if(window.localStorage['longitude'] == undefined){
$scope.msg = "Ligue o GPS para termos uma localização precisa" ;
return 0;
}
$http({
url: servidor+'/webservice/create_suggestion',
method: "POST",
params: {
name: $scope.name,
phone: $scope.phone,
state: $scope.state,
city: $scope.city,
district: $scope.district,
street: $scope.street,
number: $scope.number,
latitude: window.localStorage['latitude'],
longitude: window.localStorage['longitude'],
email: $scope.email
}
}).
success(function (data, status, headers, config) {
alerta($ionicPopup, "Notificação", "Bar sugerido com sucesso!");
$location.path('/menu/bares');
}).
error(function (data, status, headers, config) {
console.log('Error add Bar: '+data);
});
return 0;
}
}]);<file_sep>/www/js/Service_Usuario.js
app.factory('Usuario', ['$http', function($http){
var cartoes = 0;
/**
* -1: Erro de servidor
* 1: Sucesso
*/
function UpdateToken(idUser, tokenUser){
if(cartoes == 0){
var req = {
method: 'POST',
url: servidor+'/webservice/device_token',
params:{
id: idUser,
token: <PASSWORD>User
}
}
$http(req).
then(function (sucesso) {
/*console.warn("Sucesso token");
console.log(sucesso);*/
},
function(fail){
console.error("Fail token");
//console.log(fail);
});
}
}
return {
UpdateToken: UpdateToken
}
}]);<file_sep>/www/js/Ctrl_Sidebar.js
app.controller('Sidebar', ['$scope', '$state', '$http', '$location' ,function($scope, $state, $http,$location) {
$scope.checked = true;
$scope.nome = window.localStorage['nome'];
console.log(window.localStorage['nome']);
$scope.logoff = function() {
var idUser = window.localStorage['user_id'];
console.log(idUser)
//alert(idUser)
var req = {
method: 'POST',
url: servidor+'/webservice/device_token',
params:{
id: idUser,
token: "<PASSWORD>"
}
}
$http(req).
then(function (sucesso) {
console.warn("Sucesso token");
console.log(sucesso);
localStorage.clear();
$location.path('/login');
},
function(fail){
console.error("Fail token");
localStorage.clear();
$location.path('/login');
//console.log(fail);
});
}
$scope.sair = function() {
}
}]);
app.controller('Sobre', ['$scope', '$state', '$http', '$location' ,function($scope, $state, $http,$location) {
$scope.teste = servidor.includes("teste");
$scope.servidor = servidor;
}]);<file_sep>/www/js/Ctrl_Promocoes.js
app.controller('Promocoes', ['$scope', '$http', function($scope, $http) {
$scope.data = {};
$scope.data.busca = "";
$scope.FiltroTags = function(item) {
var trecho = $scope.data.busca;
var palavra = trecho.split(" ");
cont = 0;
for (var i = 0; i < palavra.length; i++) {
if(item.description.toUpperCase().indexOf(palavra[i].toUpperCase()) != -1)
cont++;
};
if(cont == palavra.length)
return true;
else
return false;
};
function Atualizar () {
$http({
url: servidor+'/webservice/promotions/',
method: "GET",
params:{
latitude: window.localStorage['latitude'],
longitude: window.localStorage['longitude']
}
}).
success(function (data, status, headers, config) {
if(data == 0){
$scope.msg = "Nenhuma promoção disponível no momento."
} else {
$scope.msg = "";
$scope.Promocoes = data;
console.log(data)
}
}).
error(function (data, status, headers, config) {
console.log('Error promocoes');
});
$scope.$broadcast('scroll.refreshComplete');
}
Atualizar();
$scope.doRefresh = function() {
navigator.geolocation.getCurrentPosition(function(position) {
window.localStorage['latitude'] = position.coords.latitude;
window.localStorage['longitude'] = position.coords.longitude;
console.log(position.coords.latitude, position.coords.longitude)
Atualizar();
}, function(error) {
console.log('Erro ao pegar localização: ' + error.message);
});
}
}]);<file_sep>/www/js/Ctrl_CartaoDetalhe.js
app.controller('CartaoDetalhe', ['$scope', 'CartoesPessoais', '$stateParams', '$ionicModal', function($scope, CartoesPessoais, $stateParams, $ionicModal) {
console.log('aqui??')
$scope.cartao = CartoesPessoais.getCartoes($stateParams.cartaoId);
$scope.bar = $scope.cartao.bar;
$scope.drink = $scope.cartao.drink;
$scope.vencimento = $scope.cartao.due_date;
$scope.total_doses = $scope.cartao.total_doses;
$scope.historico = $scope.cartao.historics;
$scope.detalhe = $scope.historico.getId($stateParams.histId);
$ionicModal.fromTemplateUrl('modal-ft.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
$scope.openModal = function(id) {
if(id == 1){
$scope.titulo = "Bebida";
$scope.img = $scope.detalhe.image_drink.url;
}
else if (id == 2){
$scope.titulo = "Cartão";
$scope.img = $scope.detalhe.image_card.url;
}
$scope.modal.show();
};
$scope.closeModal = function() {
$scope.modal.hide();
};
//Cleanup the modal when we're done with it!
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
// Execute action on hide modal
$scope.$on('modal.hidden', function() {
// Execute action
});
// Execute action on remove modal
$scope.$on('modal.removed', function() {
// Execute action
});
}]);<file_sep>/www/js/Ctrl_Dados.js
app.controller('dados', ['$scope', '$http', '$ionicPlatform', '$ionicPopup', '$interval', '$location', function($scope, $http, $ionicPlatform, $ionicPopup, $interval, $location) {
$scope.email = G_usuario.email;
$scope.nome = G_usuario.name;
//Força a atualização por causa do cache
$interval(atualizar, 1000, false);
function atualizar(){
if(window.localStorage['atualizarDados'] == 1 ){
console.log("dados atualizados");
window.localStorage['atualizarDados'] = 0;
$scope.email = G_usuario.email;
$scope.nome = G_usuario.name;
}
}
$scope.submitDados = function() {
//$location.path('/menu/home');
//return 0;
if($scope.passwordOld == undefined ){
alerta($ionicPopup, "Notificação", "O campo 'Senha Antiga' está vazio");
return 0;
}
if($scope.passwordOld.length < 8 ){
alerta($ionicPopup, "Notificação", "'Senha Antiga' precisa ter 8 ou mais dígitos");
return 0;
}
if($scope.password1 == undefined ){
alerta($ionicPopup, "Notificação", "O campo 'Senha Nova' está vazio");
return 0;
}
if($scope.password2 == undefined ){
alerta($ionicPopup, "Notificação", "O campo 'Confirmar Senha Nova' está vazio");
return 0;
}
if($scope.password1.length < 8 ){
alerta($ionicPopup, "Notificação", "'Senha Nova' precisa ter 8 ou mais dígitos");
return 0;
}
if($scope.password1 != $scope.password2){
alerta($ionicPopup, "Notificação", "Senhas diferentes");
return 0;
}
$http({
url: servidor+'/webservice/change_password',
method: "POST",
params: {
id: G_usuario.id,
old_password: $scope.passwordOld,
new_password: $scope.password1
}
}).
success(function (data, status, headers, config) {
alerta($ionicPopup, "Notificação", "Senha alterada com sucesso!");
$scope.password1 = '';
$scope.passwordOld = '';
$scope.password2 = '';
}).
error(function (data, status, headers, config) {
alerta($ionicPopup, "Notificação", "Senha antiga está errada");
console.log('Error add Amigo');
});
return 0;
}
}]);<file_sep>/release.sh
cordova build --release android
cp /Volumes/DEV/saites/papudinho/platforms/android/build/outputs/apk/android-release-unsigned.apk keys
cd keys
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore papudinho.keystore android-release-unsigned.apk papudinho
./zipalign -v 4 android-release-unsigned.apk Papudinho.apk
<file_sep>/www/js/app.js
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
var app = angular.module('app', ['ionic', 'ngCordova', 'ngMask', 'firebase']);
var servidor = "http://teste-papudinho.herokuapp.com";
//var servidor = "http://sistema.whiskyouapp.com.br";
/*
window.addEventListener('getiduser', function(event) {
directpush.on(event.detail, function(data){
var event = new CustomEvent('directpush', { detail: data });
window.dispatchEvent(event);
})
});*/
app.run(function($ionicPlatform, $ionicHistory, $location, $ionicPopup, $http) {
document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown() {
//faz nada
}
/*
window.addEventListener('directpush', function (e) {
$ionicPopup.alert({
title: e.detail.bar_name,
template: e.detail.message
});
directpush.clean(localStorage.getItem('user_id'));
}, false);*/
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
cordova.plugins.Keyboard.hideAccessoryBar(false);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
//StatusBar.hide();
//StatusBar.styleLightContent();
}
getAppVersion(function(version) {
window.localStorage['version'] = version;
});
/*
ionic.Platform.fullScreen();
if (window.StatusBar) {
return StatusBar.hide();
}
*/
$ionicPlatform.registerBackButtonAction(function(e){
str = window.location.href;
if(str.indexOf("login") > 0){
navigator.app.exitApp();
}
//else if(str.indexOf("meuscartoes") >= 0 || str.indexOf("amigos") >= 0 || str.indexOf("bares") >= 0 || str.indexOf("cartoes") >= 0 || str.indexOf("promocao") >= 0 || str.indexOf("dados") >= 0 || str.indexOf("config") >= 0){
//$location.path('/menu/home');
//}
else{
$ionicHistory.goBack();
e.preventDefault();
}
return false;
},501);
/**
* GetLocation() fica pegando a posição atual do usuario, a função está em funcoes.js
*/
var localizacao = setInterval(GetLocation, G_tempo);
var params = [fid, latitude, longitude, radius];
DGGeofencing.startMonitoringRegion(params, function(result) {}, function(error) {
// alert("failed to add region");
});
//Localizacao do GPS
navigator.geolocation.watchPosition(function(position) {
window.localStorage['latitude'] = position.coords.latitude;
window.localStorage['longitude'] = position.coords.longitude;
console.log(position.coords.latitude, position.coords.longitude)
}, function(error) {
console.log('Erro ao pegar localização: ' + error.message);
}, { timeout: 60000 });//{ timeout: 60000 });
});
});
app.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$ionicConfigProvider.navBar.alignTitle("center");
//$ionicConfigProvider.scrolling.jsScrolling(false);
$ionicConfigProvider.views.transition("android");
//$ionicConfigProvider.views.maxCache(0);
$stateProvider
.state('login', {
cache: false,
url: '/login',
templateUrl: 'login'
})
.state('signup', {
cache: false,
url: '/signup',
templateUrl: 'signup'
})
.state('senha', {
cache: false,
url: '/senha',
templateUrl: 'senha'
})
.state('eventmenu', {
url: "/menu",
abstract: true,
templateUrl: "sideMenu"
})
.state('eventmenu.home', {
cache: false,
url: "/home",
views: {
'menuContent' :{
templateUrl: "home"
}
}
})
.state('eventmenu.barMensagem', {
cache: false,
url: "/barMensagem",
views: {
'menuContent' :{
templateUrl: "barMensagem"
}
}
})
.state('eventmenu.meuscartoes', {
url: "/meuscartoes",
cache: false,
views: {
'menuContent' :{
templateUrl: "meuscartoes"
}
}
})
.state('eventmenu.cartoes', {
url: "/cartoes",
cache: false,
views: {
'menuContent' :{
templateUrl: "cartoes"
}
}
})
.state('eventmenu.promocao', {
url: "/promocao",
cache: false,
views: {
'menuContent' :{
templateUrl: "promocao"
}
}
})
.state('eventmenu.amigos', {
cache: false,
url: "/amigos",
views: {
'menuContent' :{
templateUrl: "amigos"
}
}
})
.state('eventmenu.bares', {
url: "/bares",
cache: false,
views: {
'menuContent' :{
templateUrl: "bares"
}
}
})
.state('eventmenu.dados', {
url: "/dados",
cache: false,
views: {
'menuContent' :{
templateUrl: "dados"
}
}
})
.state('eventmenu.config', {
url: "/config",
cache: false,
views: {
'menuContent' :{
templateUrl: "config"
}
}
})
.state('eventmenu.sobre', {
url: "/sobre",
cache: false,
views: {
'menuContent' :{
templateUrl: "sobre"
}
}
})
.state('eventmenu.logoff', {
url: "/logoff",
cache: false,
views: {
'menuContent' :{
templateUrl: "logoff"
}
}
})
.state('eventmenu.bar', {
url: "/barmsg",
cache: false,
views: {
'menuContent' :{
templateUrl: "barmsg"
}
}
})
.state('promocaoId', {
url: '/promocao/:id',
cache: false,
templateUrl: 'promocao'
})
.state('bar', {
url: '/bar/:id',
cache: false,
templateUrl: 'bar'
})
.state('addCartao', {
cache: false,
url: '/addCartao',
templateUrl: 'addCartao'
})
.state('addAmigo', {
url: '/addAmigo',
cache: false,
templateUrl: 'addAmigo'
})
.state('chat', {
url: '/chat/:chatId/:nome/:relacionamento',
cache: false,
templateUrl: 'chat'
})
.state('chatUsuarios', {
url: '/chat/:chatId/:nome',
cache: false,
templateUrl: 'chat'
})
.state('cartao', {
url: '/cartao/:cartaoId',
cache: false,
templateUrl: 'cartao'
})
.state('updatecartao', {
cache: false,
url: '/updatecartao/:cartaoId',
templateUrl: 'updatecartao'
})
.state('cartaodetalhe', {
cache: false,
url: '/cartaodetalhe/:cartaoId/:histId',
templateUrl: 'cartaodetalhe'
})
.state('cartaoBarHistorico', {
cache: false,
url: '/cartaoBarHistorico/:cartaoId',
templateUrl: 'views/cartao_historico.html'
})
.state('barmsg', {
cache: false,
url: '/barmsg',
templateUrl: 'views/bar_msg.html'
})
.state('barmsgmessages', {
cache: false,
url: '/messages/:id',
templateUrl: 'views/messages.html'
})
.state('addBar', {
cache: false,
url: '/addBar',
templateUrl: 'addBar'
})
;
$urlRouterProvider.otherwise('/login');
});
/**
* Adicionando um novo método no objeto 'Array'
*/
Array.prototype.getId = function(id) {
var i;
for (i = 0; i < this.length; i++) {
if(this[i].id == id)
return this[i];
}
return 0;
}
var G_usuario = [];
/**
* Tempo de atualização da posição
1m - 60,000ms
5m - 300,000ms
10m - 600,000ms
15m - 900,000ms
*/
var G_tempo = 300000;
var G_bares = [];
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// Now safe to use device APIs
initPushwoosh();
}
// chamando o initPushwoosh
app.run(function($ionicPopup){
// userData.custom_data.name
// userData.custom_data.message
window.addEventListener('directpush', function (e) {
$ionicPopup.alert({
title: e.detail.name,
template: e.detail.message
});
}, false);
});
function initPushwoosh($ionicPopup){
var deviceType = (navigator.userAgent.match(/iPad/i)) == "iPad" ? "iPad" : (navigator.userAgent.match(/iPhone/i)) == "iPhone" ? "iPhone" : (navigator.userAgent.match(/Android/i)) == "Android" ? "Android" : (navigator.userAgent.match(/BlackBerry/i)) == "BlackBerry" ? "BlackBerry" : "null";
var pushNotification = cordova.require("pushwoosh-cordova-plugin.PushNotification");
if(deviceType == "iPhone" || deviceType == "iPad"){
//set push notification callback before we initialize the plugin
document.addEventListener('push-notification', function(event) {
var notification = event.notification;
if(notification && notification.userdata){
// caso seja promoçãp
if(notification.userdata.custom_data.promotion_id){
var id = notification.userdata.custom_data.promotion_id;
window.open(servidor+'/promocao/'+id, '_blank', 'location=yes','closebuttoncaption=FECHAR');
} else {
console.log("CHAT ou push direto");
console.log(userData.custom_data.chatUUID);
if(notification.userdata.custom_data.chatUUID == 'undifined' ||
notification.userdata.custom_data.chatUUID == undefined ||
notification.userdata.custom_data.chatUUID == null ) {
var event = new CustomEvent('directpush', { detail: notification.userdata.custom_data });
window.dispatchEvent(event);
}
}
}
pushNotification.setApplicationIconBadgeNumber(0);
});
//initialize the plugin
pushNotification.onDeviceReady({pw_appid:"60C72-3A9F2"});
//register for pushes
pushNotification.registerDevice(
function(status) {
var deviceToken = status['deviceToken'];
//console.warn('registerDevice: ' + deviceToken);
window.localStorage['token'] = deviceToken;
},
function(status) {
console.warn('failed to register : ' + JSON.stringify(status));
// alert(JSON.stringify(['failed to register ', status]));
}
);
//reset badges on app start
pushNotification.setApplicationIconBadgeNumber(0);
}else {
//set push notifications handler
document.addEventListener('push-notification', function(event) {
var title = event.notification.title;
var userData = event.notification.userdata;
console.log('userData.custom_data');
console.log(JSON.stringify(userData.custom_data));
if(userData && userData.custom_data){
// caso seja promoçãp
if(userData.custom_data.promotion_id){
console.log(userData);
console.log(userData.custom_data.promotion_id);
window.open(servidor+'/promocao/'+userData.custom_data.promotion_id, '_blank', 'location=yes','closebuttoncaption=FECHAR');
} else {
console.log("CHAT ou push direto");
console.log(userData.custom_data.chatUUID);
if(userData.custom_data.chatUUID == 'undifined' ||
userData.custom_data.chatUUID == undefined ||
userData.custom_data.chatUUID == null ) {
var event = new CustomEvent('directpush', { detail: userData.custom_data });
window.dispatchEvent(event);
}
}
}
});
//initialize Pushwoosh with projectid: "78196470103", pw_appid : "60C72-3A9F2".
pushNotification.onDeviceReady({ projectid: "78196470103", pw_appid : "60C72-3A9F2" });
//register for pushes
pushNotification.registerDevice(
function(status) {
var pushToken = status;
console.warn('push token: ' + JSON.stringify(pushToken));
window.localStorage['token'] = pushToken;
},
function(status) {
console.warn(JSON.stringify(['failed to register ', status]));
}
);
}
}
<file_sep>/www/js/Ctrl_Cartoes.js
app.controller('Cartoes', ['$scope', '$http', '$interval','$window', function($scope, $http, $interval, $window) {
atualizar();
$scope.vencidos = [];
$scope.atuais = [];
$scope.controleFiltroCartoes = 0;
$scope.viewCartao = function(id){
console.log(id);
$window.location = '#/cartaoHistorico/' + id;
}
//$interval(atualizar, 100000, false);
function atualizar(){
if($scope.controleFiltroCartoes == 1){
$scope.labelCartao = "Cartões Vencidos";
}else{
$scope.labelCartao = "Cartões Válidos";
}
$http({
url: servidor+'/webservice/cards/',
method: "GET",
params: {
user: G_usuario.id
}
}).
success(function (data, status, headers, config) {
$scope.$broadcast('scroll.refreshComplete');
$scope.msg = " ";
console.log(data);
if(data == 0){
$scope.msg = "Ainda não tem cartão em nenhum bar!";
}else{
$scope.vencidos = [];
$scope.atuais = [];
for (var i = 0; i < data.length; i++) {
var parts = data[i].due_date.split('-');
var dataFim = new Date(parts[2],parts[1]-1,parts[0]);
var dataAtual = new Date();
if(dataAtual > dataFim){
$scope.vencidos.push(data[i])
}else{
$scope.atuais.push(data[i])
}
};
//$scope.Cartoes = $scope.atuais;
}
}).
error(function (data, status, headers, config) {
$scope.$broadcast('scroll.refreshComplete');
console.log('Error cartoes');
});
$scope.$broadcast('scroll.refreshComplete');
}
$scope.doRefresh = function() {
atualizar();
}
$scope.mudar = function() {
console.log($scope.controleFiltroCartoes);
if($scope.controleFiltroCartoes == 1){
$scope.labelCartao = "Cartões Vencidos";
$scope.controleFiltroCartoes = 0;
$scope.Cartoes = $scope.atuais;
}else{
$scope.labelCartao = "Cartões Válidos";
$scope.Cartoes = $scope.vencidos;
$scope.controleFiltroCartoes = 1;
}
}
}]);<file_sep>/www/js/Ctrl_Config.js
app.controller('Config', ['$scope', '$http', '$ionicPopup', function($scope, $http, $ionicPopup) {
$scope.promocoes = G_usuario.promotion;
$scope.gps = G_usuario.gps;
$scope.visibilidade = G_usuario.visibility;
$scope.privacidade = false;
console.log("user id:" + G_usuario.id);
$scope.submitConfig = function() {
$http({
url: servidor+'/webservice/update_config/',
method: "POST",
params: {
id: G_usuario.id,
promotion: $scope.promocoes,
gps: $scope.gps,
visibility: $scope.visibilidade,
card_secret: $scope.privacidade
}
}).
success(function (data, status, headers, config) {
G_usuario.promotion = $scope.promocoes;
G_usuario.gps = $scope.gps;
G_usuario.visibility = $scope.visibilidade;
G_usuario.card_secret = $scope.privacidade;
alerta($ionicPopup, "Notificação", "Configurações salvas!");
}).
error(function (data, status, headers, config) {
console.error(status);
alerta($ionicPopup, "Notificação", "Problema no servidor, tente novamente.");
console.log('Error Config');
});
};
}]);<file_sep>/www/js/Ctrl_Bar.js
app.controller('Bar', ['$scope', '$stateParams', function($scope, $stateParams) {
$scope.bar = G_bares.getId($stateParams.id);
$scope.link = function(site){
var ref = window.open('http://www.'+site, '_blank', 'location=yes');
var myCallback = function() {
}
ref.addEventListener('loadstart', myCallback);
//ref.removeEventListener('loadstart', myCallback);
//window.open(site, '_blank', 'location=yes');
}
}]);<file_sep>/www/js/Service_Amizade.js
app.factory('Amizade', ['$http', function($http){
/**
* -1: Erro de servidor
*/
function getAllAmigos(myId){
var req = {
method: 'GET',
url: servidor+'/webservice/friends',
params: {
id: myId
}
}
return $http(req).
then(function (sucesso) {
//console.log(sucesso);
return sucesso.data;
},
function(fail){
return -1;
});
}
function getAllSolicitacoes(myId){
var req = {
method: 'GET',
url: servidor+'/webservice/friends/new',
params: {
id: myId
}
}
return $http(req).
then(function (sucesso) {
//console.log(sucesso);
return sucesso.data;
},
function(fail){
return -1;
});
}
function NovaAmizade(myId, emailAmigo){
}
function AceitarAmizade(idSolicitacao){
var req = {
method: 'POST',
url: servidor+'/webservice/friends/acept',
params: {
id: idSolicitacao
}
}
return $http(req).
then(function (sucesso) {
console.log(sucesso);
return sucesso.data;
},
function(fail){
return -1;
});
}
function RecusarAmizade(idSolicitacao){
var req = {
method: 'POST',
url: servidor+'/webservice/friends/remove',
params: {
id: idSolicitacao
}
}
return $http(req).
then(function (sucesso) {
console.log(sucesso);
return sucesso.data;
},
function(fail){
return -1;
});
}
function RemoverAmigo(idAmizade){
console.log(idAmizade)
}
return {
getAllAmigos: getAllAmigos,
getAllSolicitacoes: getAllSolicitacoes,
AceitarAmizade: AceitarAmizade,
RecusarAmizade: RecusarAmizade,
RemoverAmigo: RemoverAmigo
};
}]);<file_sep>/www/js/Ctrl_LoginForm.js
app.controller('LoginForm', ['$scope', '$http', '$location', '$state', 'Usuario','Geolocalizacao', function($scope, $http, $location, $state, Usuario,Geolocalizacao) {
$scope.msg = " ";
$scope.checked = false;
$scope.version = window.localStorage['version'];
$scope.submit = function() {
$scope.msg = " ";
if($scope.email == undefined ){
$scope.msg = "O e-mail digitado é inválido";
return 0;
}
if($scope.senha == undefined ){
$scope.msg = "O campo 'Senha' está vazio";
return 0;
}
if($scope.senha.length < 8 ){
$scope.msg = "Senha precisa ter 8 ou mais dígitos";
return 0;
}
$scope.checked = true;
$http({
url: servidor+'/webservice/authenticate_user/',
method: "POST",
params: {
email: $scope.email,
password: $scope.<PASSWORD>,
token: window.localStorage['token']
}
}).
success(function (data, status, headers, config) {
console.log(data.name.substring(0,10))
window.localStorage['nome'] = data.name.substring(0,10);
window.localStorage['email'] = $scope.email;
window.localStorage['senha'] = $scope.senha;
$scope.msg = "";
$scope.email = "";
$scope.senha = "";
window.localStorage['atualizarDados'] = 1;
window.localStorage['atualizarCartao'] = 1;
window.localStorage['login'] = 1;
G_usuario = data;
$scope.checked = false;
console.log(G_usuario.id);
window.localStorage['user_id'] = G_usuario.id;
//Usuario.UpdateToken(G_usuario.id, window.localStorage['token']);
Geolocalizacao.UpdateGps();
var event = new CustomEvent('getiduser', { detail: G_usuario.id });
window.dispatchEvent(event);
$location.path('/menu/home');
}).
error(function (data, status, headers, config) {
console.log('Error LoginForm');
$scope.checked = false;
$scope.msg = "Usuário ou senha incorretos";
});
};
/**
* Verificação se o usuario encerrou o app sem deslogar
* se tiver feito isto então ele realiza o login automatico
*/
if(window.localStorage['login'] == undefined){
window.localStorage['login'] = 0;
console.log("zerei");
// $state.reload();
window.location.reload(true);
} else if(window.localStorage['login'] == 1) {
$scope.email = window.localStorage['email'];
$scope.senha = window.localStorage['senha'];
$scope.submit();
console.log("passei");
} else{
window.localStorage['login'] = 0;
console.log("fiquei");
}
}]);
<file_sep>/www/js/funcoes.js
/**
* Função para gerar uma tela de alerta no app
* @param alert - Variável '$ionicPopup' do Ionic
* @param titulo - Título do alert
* @param msg - Mensagem do corpo do alert
*/
function alerta (alert, titulo, msg) {
alert.alert({
title: titulo,
template: msg
});
}
/**
* Converte latitude e longitude para radianos
* Função utilizada em GetLocation()
*/
function conversor (angle) {
return (angle * 3.14)/180;
}
/**
* Retorna a distancia entre dois pontos, em kilometros
* Os dados de entrada tem que estar em radianos
*/
function Distancia (latA, lonA, latB, lonB) {
var x = 6371*Math.acos( Math.sin(latA)*Math.sin(latB) + Math.cos(latA)*Math.cos(latB) * Math.cos(lonA-lonB));
return x;
}
/**
* Envia uma notifição para o usuario
* @param texto - Texto a ser mostrado na noficiação
*/
function Notificar (texto) {
window.plugin.notification.local.add({ message: texto });
}
// variaveis para realizar testes de distancia
lat = conversor(-5.855706);
lon = conversor(-35.2454187);
function GetLocation() {
if(window.localStorage['login'] == 1){
navigator.geolocation.getCurrentPosition(function(position) {
window.localStorage['latitude'] = position.coords.latitude;
window.localStorage['longitude'] = position.coords.longitude;
Comparar();
}, function(error) {
console.log('Erro ao pegar localização: ' + error.message);
}, {enableHighAccuracy: true });
}
}
/**
* Compara a posição atual com a posição dos bares.
* Se a distancia for menor que 1km ele envia uma notificação para o usuário.
*/
function Comparar(){
for(i = 0; i < G_bares.length; i++){
lat = conversor(G_bares[i].latitude);
lon = conversor(G_bares[i].longitude);
distancia = Distancia(lat, lon, conversor(window.localStorage['latitude']), conversor(window.localStorage['longitude']));
//console.log(distancia);
if(distancia <= 1.0){
Notificar("O bar "+G_bares[i].name+" está perto de você!");
}
}
}<file_sep>/www/js/Service_Cartao.js
app.factory('CartoesPessoais', ['$http', function($http){
var cartoes = 0;
/**
* -1: Erro de servidor
* 1: Sucesso
*/
function getCartoes(id){
if(cartoes == 0){
var req = {
method: 'GET',
url: servidor+'/webservice/cards/particular',
params:{
user: id
}
}
$http(req).
then(function (sucesso) {
console.log(sucesso);
cartoes = sucesso;
return cartoes;
},
function(fail){
console.error("fail getCartoes - id"+id);
return -1;
});
}
return cartoes;
}
function getCartaoPorId(id){
if(cartoes == 0){
var req = {
method: 'GET',
url: servidor+'/webservice/cards/',
params:{
id: id
}
}
$http(req).
then(function (sucesso) {
console.log(sucesso);
return sucesso;
},
function(fail){
console.error("fail getCartoes - id"+id);
return -1;
});
}
return id;
}
function atualizar(id){
var req = {
method: 'GET',
url: servidor+'/webservice/cards/particular/',
params: {
user: id
}
}
$http(req).
then(function (sucesso) {
cartoes = sucesso;
return 1;
},
function(fail){
return -1;
});
}
function deletar(cardId, userId){
var req = {
method: 'GET',
url: servidor+'/webservice/delete_card/',
params: {
user_id: userId,
card_id: cardId
}
}
$http(req).
then(function (sucesso) {
atualizar(userId);
return 1;
},
function(fail){
console.error(fail);
return -1;
});
}
function getId(id){
var i;
x = cartoes.data;
console.log(x)
for (i = 0; i < x.length; i++) {
if(x[i].id == id)
return x[i];
}
return -1;
}
return {
getCartoes: getCartoes,
atualizar: atualizar,
getId: getId,
deletar: deletar
}
}]);<file_sep>/www/js/Ctrl_Back.js
app.controller('Back', ['$scope', '$ionicHistory', function($scope, $ionicHistory) {
$scope.myGoBack = function() {
window.history.back();
//$ionicHistory.goBack();
};
}]); | 914945789bdcbabf5287fab5c602d1e96ee6e6a8 | [
"JavaScript",
"Shell"
] | 21 | JavaScript | raivitor/papudinho | 68b806c552741e80eb761596ebad9c3838608e3a | 2a0cace5d4a656502e5be137dff8ba70f941d469 | |
refs/heads/main | <repo_name>renato-castillo/example-socket<file_sep>/README.md
# example-socket
Ejemplo de servidor websocket en c# y cliente en angular
<file_sep>/web/src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { webSocket, WebSocketSubject } from "rxjs/webSocket";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
subject: WebSocketSubject<unknown> | null = null;
title = 'web';
mensaje = '';
ngOnInit(): void {
this.subject = webSocket('ws://localhost:9000');
this.subject.subscribe(
msg => {
console.log('message received: ' + (msg as any).mensaje)
}, // Called whenever there is a message from the server.
err => {
console.log(err)
}, // Called if at any point WebSocket API signals some kind of error.
() => {
console.log('complete')
}// Called when connection is closed (for whatever reason).
);
// Note that at least one consumer has to subscribe to the created subject - otherwise "nexted" values will be just buffered and not sent,
// since no connection was established!
//this.subject.next({message: 'some message'});
// This will send a message to the server once a connection is made. Remember value is serialized with JSON.stringify by default!
//this.subject.complete(); // Closes the connection.
//this.subject.error({code: 4000, reason: 'I think our app just broke!'});
// Also closes the connection, but let's the server know that this closing is caused by some error.
}
enviar() {
if (this.subject) {
this.subject.next({message: this.mensaje});
}
}
desconectar() {
if (this.subject) {
this.subject.complete();
}
}
}
<file_sep>/server/Program.cs
using System;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using WatsonWebsocket;
namespace server
{
class Program
{
static WatsonWsServer server = new WatsonWsServer("localhost", 9000, false);
static async Task Main(string[] args)
{
server.ClientConnected += ClientConnectedAsync;
server.ClientDisconnected += ClientDisconnected;
server.MessageReceived += MessageReceived;
await server.StartAsync();
Console.WriteLine("Server is listening: " + server.IsListening);
while (true) {} // Para que no finalice la apliación
static void ClientConnectedAsync(object sender, ClientConnectedEventArgs args)
{
Console.WriteLine("Client connected: " + args.IpPort);
// Le respondo al cliente que se conecto al servidor
string data = JsonSerializer.Serialize(new { mensaje = "Conectado al servidor" });
server.SendAsync(args.IpPort, data);
}
static void ClientDisconnected(object sender, ClientDisconnectedEventArgs args)
{
Console.WriteLine("Client disconnected: " + args.IpPort);
}
static void MessageReceived(object sender, MessageReceivedEventArgs args)
{
// Proceso el mensaje recibido
string mensaje = Encoding.UTF8.GetString(args.Data);
Console.WriteLine("Message received from " + args.IpPort + ": " + mensaje);
// Respondo al cliente lo mismo que recibí
string data = JsonSerializer.Serialize(new { mensaje = "Recibi esto: " + mensaje});
server.SendAsync(args.IpPort, data);
}
}
}
}
| 2860a086d9a9f77104b6b5b99281eea57423967e | [
"Markdown",
"C#",
"TypeScript"
] | 3 | Markdown | renato-castillo/example-socket | 443ba68a26016602fe007f5122fbdb6d1e19552d | 2ad524c22e754aea7f224e8809ff6a3806804005 | |
refs/heads/master | <repo_name>Zerolimits45/05-AloysiusLImASP-Project<file_sep>/05(AloysiusLIm)_ASP Project/ASP_Project_testcase.py
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import unittest #this is anotehr update
import grp5_ASP_project as asp
class testMyProgram(unittest.TestCase):
def test_sum(self):
self.assertEqual(asp.Asia5.sum_of_top3, 60923003) #this is an update
def test_mean(self):
self.assertEqual((round(asp.Asia5.mean_of_top3), 2), 20307668.98)
if __name__ == '__main__':
unittest.main()<file_sep>/05(AloysiusLIm)_ASP Project/grp5_ASP_project.py
import pandas as pd
import matplotlib.pyplot as plt
class Asia5:
imva = pd.read_excel('IMVA.xls', thousands=',') # import xls file that is in the same folder
asia5 = [imva['Brunei Darussalam'], imva['Indonesia'], imva['Malaysia'], imva['Myanmar'], imva['Philippines'],
imva['Thailand'], imva['Vietnam'],
imva['China'], imva['Hong Kong SAR'], imva['Taiwan'], imva['Japan'], imva['South Korea'], imva['Bangladesh'],
imva['India'], imva['Pakistan'], imva['Sri Lanka'],
imva['Iran'], imva['Israel'], imva['Kuwait'], imva['Saudi Arabia'],
imva['United Arab Emirates']] #selcting all the regions in asia
columns_in_asia_5_as_INDEX = range(len(list(asia5))) # range of columns in asia5 this is 0 - 20
all_SUM_of_asia5 = [] # it is to store the 10 year data sum
all_COUNTRY_of_asia5 = [] # it is to store all the 20 country
#print(columns_in_asia_5_as_INDEX)
#print(asia5[0].name)
count_values = 0
count_number_of_columns = 0
for col_id in columns_in_asia_5_as_INDEX:
#print(asia5[col_id].name) # header of the column
#print("Column " + str(count_number_of_columns) + " out of 20 in Asia5")
sum_of_each_col = [] # forgot to reset
count_number_of_columns = count_number_of_columns + 1
for value_index in range(len(asia5[col_id])):
if asia5[col_id][value_index] == asia5[col_id][396] or value_index > 396: # value_index is the integer index for whole 516 #forgot to set it up
if asia5[col_id][value_index] == 'na':
asia5[col_id][value_index] = '0'
sum_of_each_col.append(int(asia5[col_id][value_index])) # use this for months and years too
all_SUM_of_asia5.append(sum(sum_of_each_col))
all_COUNTRY_of_asia5.append(asia5[col_id].name)
global country # to enable the iterable loop on line 78 to be available
global n # to enable the iterable loop on line 77 to be available
for country in asia5:
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
'November', 'December']
df_each_year = pd.DataFrame(columns=months)
print(country.name)
n = 12 # set number of months
each_year = [country[i * n:(i + 1) * n] for i in range(
(len(country) + n - 1) // n)] # becomes a list of LISTS with all exhaustive years 1978 - 2020 : 43 years
count = 0
for year in each_year:
# print(list(year) )
df_length = len(df_each_year)
df_each_year.loc[df_length] = list(year)
count = count + 1
# print(count)
df_each_year.index = df_each_year.index + 1978
df_each_year = df_each_year.replace('na', 0)
sum_of_each_year = df_each_year.sum(axis=1)
# print(sum_of_each_year)
print(df_each_year)
# GRAPH PLOTTING
final_dataframe_of_asia5 = pd.DataFrame()
final_dataframe_of_asia5["country"] = all_COUNTRY_of_asia5
final_dataframe_of_asia5["values"] = all_SUM_of_asia5
final_dataframe_of_asia5.sort_values(by=['values'], inplace=True, ascending=False)
final_dataframe_of_asia5.reset_index(drop=True, inplace=True)
print(final_dataframe_of_asia5)
sum_of_top3 = sum(final_dataframe_of_asia5['values'].head(3).to_list())
mean_of_top3 = final_dataframe_of_asia5.head(3).mean()
print("")
print("The mean value for the top 3 countries is " + str((round((mean_of_top3), 2))))
print("The total no. of visitors for the top 3 countries is " + str(sum_of_top3))
# Bar chart for the top 3 countries
final_dataframe_of_asia5.head(3).plot.bar(x="country", y="values", rot=70, title="Top 3 COUNTRIES from period 2011 - 2020", ylabel="Number of travelers [in millions]")
plt.savefig("top3Countries.png")
plt.show()
# Bar chart for all the countries
final_dataframe_of_asia5.plot.bar(x="country", y="values", rot=70, title="ALL COUNTRIES from period 2011 - 2020", figsize=(10, 10), ylabel="Number of travelers [in millions]", )
plt.savefig("allCountries.png")
plt.show()
# SPLIT FUNCTION
| a82a21f4e2733f12cf63d98789286573271c1c07 | [
"Python"
] | 2 | Python | Zerolimits45/05-AloysiusLImASP-Project | 442106f88814beee3228e254fff5d81a9f2331a8 | ebcbc0ac2493bc5a6d706e5de2a8992610316213 | |
refs/heads/master | <file_sep>package org.lang;
public class Sample {
public static void method3() {
System.out.println("i am mad");
}
}
| bdd6b7b5b2b035a3ee07db9dc82ffe2da7c3f56d | [
"Java"
] | 1 | Java | singavignesh/Projects | a707d3ef66d62ad83de3fc07d80686e516799b00 | 6a426161e5a880c29d5e5194dd6015bbbc6b9277 | |
refs/heads/main | <repo_name>dogXkill/gen_razm<file_sep>/README.md
# gen_razm
генератор разметки на jquery
код генерирует разметку на лету(писалось чисто из интереса под пиво:D)
<file_sep>/index.php
<style>
.col {
text-align: center;
margin-bottom: 10px;
border-radius: 4px;
box-shadow: 0 0 3px rgb(0 0 0 / 50%);
}
.osn_block{
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
</style>
<!--
mobile = col-mob
tab = col-tab
pc = col-pc
-->
<style type="text/css" id="css_xl" media="(min-width: 1200px)">
</style>
<style type="text/css" id="css_md" media="(min-width: 800px) and (max-width: 1200px)">
</style>
<div class="osn_block">
<?php
/*генератор стилей*/
$mas_rand_tag=['red','blue','test','kek','col-xl','col-sms-20'];
$mas_chisla=[10,20,30,40,50,60,70,80,90];
for ($i=0;$i<=10;$i+=1){
$l=$mas_chisla[rand(0,count($mas_chisla)-1)];
$k=$l+10;
echo '<div class="col '.$mas_rand_tag[rand(0,5)].' col-md-'.$k.' col-xl-'.$l.' '.$mas_rand_tag[rand(0,5)].'">md='.$k.'% | xl='.$l.'%</div>';
}
?>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script>
<script>
var array_col_xl_proc=[];
var array_col_md_proc=[];
jQuery.isSubstring = function(haystack, needle) {
return haystack.indexOf(needle) !== -1;
};
$('.col').each(function(i) {
console.log($(this).attr('class'));
var class_m=$(this).attr('class').split(" ");
console.log(class_m);
$(class_m).each(function(k){
//console.log(class_m[k]+"|"+$.isSubstring(class_m[k], "col-xl-")); // true;
if ($.isSubstring(class_m[k], "col-xl-")==true){
if ($.inArray(class_m[k], array_col_xl_proc)==-1){
var str_proc=class_m[k].split('-');
var proc=str_proc[2];
//console.log(proc);
var gen_css="."+class_m[k]+"{"+"-webkit-box-flex: 0;-ms-flex: 0 0 "+proc+"%;flex: 0 0 "+proc+"%;max-width: "+proc+"%;"+"}";
console.log(gen_css);
var css_t=$("#css_xl").html();
css_t=css_t+""+gen_css;
array_col_xl_proc.push(class_m[k]);
$("#css_xl").html(css_t);
}
}else if ($.isSubstring(class_m[k], "col-md-")==true){
if ($.inArray(class_m[k], array_col_md_proc)==-1){
var str_proc=class_m[k].split('-');
var proc=str_proc[2];
//console.log(proc);
var gen_css="."+class_m[k]+"{"+"-webkit-box-flex: 0;-ms-flex: 0 0 "+proc+"%;flex: 0 0 "+proc+"%;max-width: "+proc+"%;"+"}";
console.log(gen_css);
var css_t=$("#css_md").html();
css_t=css_t+""+gen_css;
array_col_xl_proc.push(class_m[k]);
$("#css_md").html(css_t);
}
}
});
});
</script> | eacd10310e8cbf654d597f6e15513c6509a7aa6a | [
"Markdown",
"PHP"
] | 2 | Markdown | dogXkill/gen_razm | d6ee65cb15f1341926cb5465e5a35c0583acb4ba | b7b51d06a1cf9bfd093380a9409ef6b7a31f87b9 | |
refs/heads/master | <repo_name>PiedWeb/UrlHarvester<file_sep>/tests/HarvestTest.php
<?php
declare(strict_types=1);
namespace PiedWeb\UrlHarvester\Test;
use PiedWeb\Curl\ResponseFromCache;
use PiedWeb\UrlHarvester\Harvest;
use PiedWeb\UrlHarvester\Indexable;
use PiedWeb\UrlHarvester\Link;
class HarvestTest extends \PHPUnit\Framework\TestCase
{
private static $harvest;
private function getUrl()
{
return 'https://piedweb.com/seo/crawler';
}
private function getHarvest()
{
if (null === self::$harvest) {
self::$harvest = Harvest::fromUrl(
$this->getUrl(),
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0'
);
}
return self::$harvest;
}
private function getHarvestFromCache()
{
$response = new ResponseFromCache(
'HTTP/1.1 200 OK'.\PHP_EOL.\PHP_EOL.file_get_contents(__DIR__.'/page.html'),
$this->getUrl(),
['content_type' => 'text/html; charset=UTF-8']
);
$harvest = new Harvest($response);
return $harvest;
}
public function testHarvestWordCount()
{
$harvest = $this->getHarvestFromCache();
$this->assertTrue($harvest->getWordCount() > 50);
}
public function testHarvestLinksForReal()
{
$harvest = $this->getHarvestFromCache();
$url = $this->getUrl();
$this->assertSame(2, \count($harvest->getLinks(Link::LINK_SELF)));
$this->assertTrue(4 == \count($harvest->getLinks(Link::LINK_INTERNAL)));
$this->assertTrue(3 == \count($harvest->getLinks(Link::LINK_EXTERNAL)));
$this->assertTrue(2 == \count($harvest->getLinks(Link::LINK_SUB)));
$this->assertSame(11, \count($harvest->getLinks()));
}
public function testHarvest()
{
$harvest = $this->getHarvest();
$url = $this->getUrl();
// Just check Curl is doing is job
$this->assertTrue($harvest->getResponse()->getInfo('total_time') > 0.00000001);
$this->assertTrue(\strlen($harvest->getTag('h1')) > 2);
$this->assertTrue(\strlen($harvest->getMeta('description')) > 2);
$this->assertTrue('https://piedweb.com/seo/crawler' == $harvest->getCanonical());
$this->assertTrue($harvest->isCanonicalCorrect());
$this->assertTrue($harvest->getRatioTxtCode() > 2);
$this->assertTrue(\is_array($harvest->getKws()));
$this->assertTrue(\strlen($harvest->getUniqueTag('head title')) > 10);
$this->assertTrue(null === $harvest->getUniqueTag('h12'));
$this->assertTrue(\is_array($harvest->getBreadCrumb()));
$this->assertSame('piedweb.com', $harvest->url()->getRegistrableDomain());
$this->assertSame('https://piedweb.com/seo/crawler', $harvest->getBaseUrl());
}
public function testHarvestLinks()
{
$harvest = $this->getHarvest();
$url = $this->getUrl();
$this->assertTrue(\is_array($harvest->getLinkedRessources()));
$this->assertTrue(\is_array($harvest->getLinks()));
$this->assertTrue(\is_array($harvest->getLinks(Link::LINK_SELF)));
$this->assertTrue(\is_array($harvest->getLinks(Link::LINK_INTERNAL)));
$this->assertTrue(\is_array($harvest->getLinks(Link::LINK_SUB)));
$this->assertTrue(\is_array($harvest->getLinks(Link::LINK_EXTERNAL)));
$this->assertTrue(\is_int($harvest->getNbrDuplicateLinks()));
}
public function testFollow()
{
$harvest = $this->getHarvest();
$this->assertTrue($harvest->getLinks()[0]->mayFollow());
$this->assertTrue($harvest->mayFollow());
}
public function testRedirection()
{
$url = 'https://www.piedweb.com/';
$harvest = Harvest::fromUrl(
$url,
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0'
);
$this->assertSame('https://piedweb.com/', $harvest->getRedirection());
$this->assertSame(Indexable::NOT_INDEXABLE_3XX, $harvest->indexable());
}
public function testIndexable()
{
$indexable = new Indexable($this->getHarvest());
$this->assertTrue($indexable->metaAllows());
$this->assertTrue($indexable->headersAllow());
$this->assertSame(Indexable::INDEXABLE, $this->getHarvest()->indexable());
$url = 'https://dev.piedweb.com/disallow';
$harvest = Harvest::fromUrl(
$url,
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0'
);
$harvest->setRobotsTxt('User-agent: *'."\n".'Disallow: /disallow');
$this->assertSame(Indexable::NOT_INDEXABLE_ROBOTS, $harvest->indexable());
$harvest2 = new Harvest(new ResponseFromCache(
'HTTP/1.1 200 OK'.\PHP_EOL.'X-robots-tag: noindex'.\PHP_EOL.\PHP_EOL.'<!DOCTYPE html><html>'
.'<head></head><body><p>Tests</p></body>',
'https://piedweb.com/noindex-headers',
['content_type' => 'text/html; charset=UTF-8']
));
$harvest2->setRobotsTxt($harvest->getRobotsTxt());
$this->assertSame(Indexable::NOT_INDEXABLE_HEADER, $harvest2->indexable());
$harvest2 = new Harvest(new ResponseFromCache(
'HTTP/1.1 200 OK'.\PHP_EOL.\PHP_EOL.'<!DOCTYPE html><html>'
.'<head><meta name="robots" content="noindex"></head><body><p>Tests</p></body>',
'https://piedweb.com/',
['content_type' => 'text/html; charset=UTF-8']
));
$harvest2->setRobotsTxt($harvest->getRobotsTxt());
$this->assertSame(Indexable::NOT_INDEXABLE_META, $harvest2->indexable());
$harvest2 = new Harvest(new ResponseFromCache(
'HTTP/1.1 200 OK'.\PHP_EOL.\PHP_EOL.'<!DOCTYPE html><html>'
.'<head><link rel="canonical" href="https://piedweb.com/seo" /></head><body><p>Tests</p></body>',
'https://piedweb.com/',
['content_type' => 'text/html; charset=UTF-8']
));
$harvest2->setRobotsTxt($harvest->getRobotsTxt());
$this->assertSame(Indexable::NOT_INDEXABLE_CANONICAL, $harvest2->indexable());
$harvest2 = new Harvest(new ResponseFromCache(
'HTTP/1.1 404 OK'.\PHP_EOL.\PHP_EOL.'<!DOCTYPE html><html>'
.'<head></head><body><p>Tests</p></body>',
'https://piedweb.com/',
['content_type' => 'text/html; charset=UTF-8']
));
$harvest2->setRobotsTxt($harvest->getRobotsTxt());
$this->assertSame(Indexable::NOT_INDEXABLE_4XX, $harvest2->indexable());
$harvest2 = new Harvest(new ResponseFromCache(
'HTTP/1.1 510 OK'.\PHP_EOL.\PHP_EOL.'<!DOCTYPE html><html>'
.'<head></head><body><p>Tests</p></body>',
'https://piedweb.com/',
['content_type' => 'text/html; charset=UTF-8']
));
$harvest2->setRobotsTxt($harvest->getRobotsTxt());
$this->assertSame(Indexable::NOT_INDEXABLE_5XX, $harvest2->indexable());
$harvest2 = new Harvest(new ResponseFromCache(
'HTTP/1.1 301 Moved Permanently'.\PHP_EOL.\PHP_EOL.'<!DOCTYPE html><html>'
.'<head></head><body><p>Tests</p></body>',
'https://piedweb.com/',
['content_type' => 'text/html; charset=UTF-8']
));
$harvest2->setRobotsTxt($harvest->getRobotsTxt());
$this->assertSame(Indexable::NOT_INDEXABLE_3XX, $harvest2->indexable());
}
public function testHarvestWithPreviousRequest()
{
$harvest = $this->getHarvest();
$newHarvest = Harvest::fromUrl(
$this->getUrl(),
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0',
'fr',
$harvest->getResponse()->getRequest()
);
$this->assertTrue(\strlen($harvest->getUniqueTag('head title')) > 10);
}
public function testHarvestFromCache()
{
$harvest = new Harvest(new ResponseFromCache(
'HTTP/1.1 200 OK'.\PHP_EOL.\PHP_EOL.'<!DOCTYPE html><html><body><p>Tests</p></body>',
'https://piedweb.com/',
['content_type' => 'text/html; charset=UTF-8']
));
$this->assertTrue($harvest->isIndexable());
}
public function testTextAnalysis()
{
$this->assertTrue(\count($this->getHarvest()->getTextAnalysis()->getExpressionsByDensity()) > 1);
}
public function testCanonical()
{
$harvest = Harvest::fromUrl(
'https://piedweb.com',
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0'
);
$this->assertTrue($harvest->isCanonicalCorrect('https://piedweb.com'));
$this->assertTrue($harvest->isCanonicalCorrect('https://piedweb.com/'));
$this->assertFalse($harvest->isCanonicalCorrect('https://piedweb.com//'));
}
public function testHarvestTripAdvisor()
{
$url = 'https://www.tripadvisor.fr/Attraction_Review-g196719-d21232770-Reviews-Accompagnateur_Pied_Vert_Rando_Vercors-Villard_de_Lans_Isere_Auvergne_Rhone_Alpe.html';
$harvest = Harvest::fromUrl(
$url,
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0'
);
$this->assertTrue(!is_int($harvest->getResponse()));
}
}
<file_sep>/src/ExtractLinks.php
<?php
namespace PiedWeb\UrlHarvester;
class ExtractLinks
{
public const SELECT_A = 'a[href]';
public const SELECT_ALL = '[href],[src]';
/** @var Harvest */
private $harvest;
/** @var string */
private $selector;
public static function get(Harvest $harvest, $selector = self::SELECT_A): array
{
$self = new self();
$self->selector = $selector;
$self->harvest = $harvest;
return $self->extractLinks();
}
private function __construct()
{
}
/**
* @return array
*/
private function extractLinks()
{
$links = [];
$elements = $this->harvest->getDom()->filter($this->selector); // what happen if find nothing
foreach ($elements as $element) {
//var_dump(get_class_methods($element->getNode()));
//if (!$element instanceof \DomElement) { continue; } // wtf ?
$url = $this->extractUrl($element);
//$type = $element->getAttribute('href') ? Link::LINK_A : Link::LINK_SRC;
if (null !== $url) {
//$links[] = (new Link($url, $element, $type))->setParent($this->parentUrl);
$links[] = (new Link($url, $this->harvest, $element));
}
}
return $links;
}
/**
* @return string|null absolute url
*/
private function extractUrl(\DomElement $element): ?string
{
$attributes = explode(',', str_replace(['a[', '*[', '[', ']'], '', $this->selector));
foreach ($attributes as $attribute) {
$url = $element->getAttribute($attribute);
if ($url) {
break;
}
}
if (! $url || ! $this->isWebLink($url)) {
return null;
}
return $this->harvest->url()->resolve($url);
}
public static function isWebLink(string $url)
{
return preg_match('@^((?:(http:|https:)//([\w\d-]+\.)+[\w\d-]+){0,1}(/?[\w~,;\-\./?%&+#=]*))$@', $url);
}
}
<file_sep>/src/Request.php
<?php
namespace PiedWeb\UrlHarvester;
use PiedWeb\Curl\Request as CurlRequest;
use PiedWeb\Curl\Response;
/**
* Request a page and get it only if it's an html page.
*/
class Request
{
private string $url;
private string $userAgent;
private string $language;
private ?string $proxy;
public int $maxSize = 1000000;
/**
* @param bool $tryHttps
*
* @return Response|int corresponding to the curl error
*/
public static function make(
string $url,
string $userAgent,
string $language = 'en,en-US;q=0.5',
?string $proxy = null,
int $documentMaxSize = 1000000
) {
return self::makeFromRequest(null, $url, $userAgent, $language, $proxy, $documentMaxSize);
}
public static function makeFromRequest(
?CurlRequest $curlRequest = null,
string $url,
string $userAgent,
string $language = 'en,en-US;q=0.5',
?string $proxy = null,
int $documentMaxSize = 1000000
) {
$request = new self($url);
$request->userAgent = $userAgent;
$request->language = $language;
$request->proxy = $proxy;
$request->maxSize = $documentMaxSize;
return $request->request($curlRequest);
}
private function __construct($url)
{
/*
if (!filter_var($string, FILTER_VALIDATE_URL)) {
throw new \Exception('URL invalid: '.$string);
}**/
$this->url = $url;
}
/**
* Prepare headers as a normal browser (same order, same content).
*/
private function prepareHeadersForRequest(): array
{
//$host = parse_url($this->url, PHP_URL_HOST);
$headers = [];
$headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8';
$headers[] = 'Accept-Encoding: gzip, deflate';
$headers[] = 'Accept-Language: '.$this->language;
$headers[] = 'Connection: keep-alive';
//if ($host) {
//$headers[] = 'Host: '.$host;
//}
// Referer
$headers[] = 'Upgrade-Insecure-Requests: 1';
$headers[] = 'User-Agent: '.$this->userAgent;
return $headers;
}
/**
* @return Response|int corresponding to the curl error
*/
private function request(?CurlRequest $request = null)
{
$request = null !== $request ? $request : new CurlRequest();
$request
->setUrl($this->url)
->setReturnHeader()
->setEncodingGzip()
->setUserAgent($this->userAgent)
->setDefaultSpeedOptions()
->setOpt(\CURLOPT_SSL_VERIFYHOST, 0)
->setOpt(\CURLOPT_SSL_VERIFYPEER, 0)
->setOpt(\CURLOPT_MAXREDIRS, 0)
->setOpt(\CURLOPT_FOLLOWLOCATION, false)
->setOpt(\CURLOPT_COOKIE, false)
->setOpt(\CURLOPT_CONNECTTIMEOUT, 20)
->setOpt(\CURLOPT_TIMEOUT, 80)
->setAbortIfTooBig($this->maxSize); // 2Mo
if ($this->proxy) {
$request->setProxy($this->proxy);
}
$request->setOpt(\CURLOPT_HTTPHEADER, $this->prepareHeadersForRequest());
$response = $request->exec();
//dd($this->request->exec());
return $response;
}
}
<file_sep>/tests/LinkTest.php
<?php
declare(strict_types=1);
namespace PiedWeb\UrlHarvester\Test;
use PiedWeb\UrlHarvester\Harvest;
use PiedWeb\UrlHarvester\Link;
use PiedWeb\UrlHarvester\Url;
use Symfony\Component\DomCrawler\Crawler as DomCrawler;
class LinkTest extends \PHPUnit\Framework\TestCase
{
private static $harvest;
private function getUrl()
{
return 'https://piedweb.com/';
}
private function getHarvest()
{
if (null === self::$harvest) {
self::$harvest = Harvest::fromUrl(
$this->getUrl(),
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0'
);
}
return self::$harvest;
}
public function testLinkNormalization()
{
$link = new Link('https://www.piedweb.com', $this->getHarvest());
$this->assertSame($link->getPageUrl(), 'https://www.piedweb.com/');
$this->assertSame($link->getUrl()->getRelativizedDocumentUrl(), '/');
}
private function getDomElement()
{
$html = '<a href="/test" rel=nofollow>test</a>';
$dom = new DomCrawler($html);
return $dom->filter('a')->getNode(0);
}
public function testNofollow()
{
$link = new Link('https://piedweb.com/test', $this->getHarvest(), $this->getDomElement());
$this->assertTrue(! $link->mayFollow());
}
public function testAnchor()
{
$link = new Link('https://piedweb.com', $this->getHarvest(), $this->getDomElement());
$this->assertSame($link->getAnchor(), 'test');
}
public function testShortcutsForRedir()
{
$link = Link::createRedirection('https://piedweb.com', $this->getHarvest());
$this->assertTrue($link->mayFollow());
$this->assertSame($link->getAnchor(), null);
}
public function testLinkType()
{
$link = new Link('https://external.com/test', $this->getHarvest(), $this->getDomElement());
$this->assertTrue(! $link->isInternalLink());
$this->assertTrue(! $link->isSubLink());
$this->assertTrue(! $link->isSelfLink());
}
public function testUrl()
{
$url = new Url($this->getUrl());
$this->assertTrue('https://piedweb.com' == $url->resolve('//piedweb.com'));
}
public function testRelativize()
{
$url = new Url($this->getUrl());
$this->assertSame($url->relativize(), '/');
}
}
<file_sep>/tests/RequestTest.php
<?php
declare(strict_types=1);
namespace PiedWeb\UrlHarvester\Test;
use PiedWeb\UrlHarvester\Request;
class RequestTest extends \PHPUnit\Framework\TestCase
{
public function testFailedRequest()
{
$request = Request::make('https://dzejnd'.rand(10000, 9999999999).'.biz', 'Hello :)');
$this->assertSame(6, $request);
}
public function testRequest()
{
$request = Request::make(
'https://piedweb.com/',
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0'
);
$this->assertTrue(\strlen($request->getContent()) > 10);
$this->assertTrue(! empty($request->getHeaders()));
}
public function testRequestRedir()
{
$request = Request::make(
'https://www.piedweb.com/',
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0'
);
$this->assertSame(
$request->getHeaders()['location'] ?? $request->getHeaders()['Location'],
'https://piedweb.com/'
);
}
}
<file_sep>/src/Url.php
<?php
/**
* Wrapper for League\Uri.
*
* Permits to cache registrableDomain and Origin
*/
namespace PiedWeb\UrlHarvester;
use League\Uri\Http;
use League\Uri\UriInfo;
use League\Uri\UriResolver;
class Url
{
protected $http;
protected $origin;
protected $registrableDomain;
public function __construct(string $url)
{
$this->http = Http::createFromString($url);
if (! UriInfo::isAbsolute($this->http)) {
throw new \Exception('$url must be absolute (`'.$url.'`)');
}
}
public function resolve($url): string
{
$resolved = UriResolver::resolve(Http::createFromString($url), $this->http);
return $resolved->__toString();
}
public function getHttp()
{
return $this->http;
}
public function getScheme()
{
return $this->http->getScheme();
}
public function getHost()
{
return $this->http->getHost();
}
public function getOrigin()
{
$this->origin = $this->origin ?? $this->origin = UriInfo::getOrigin($this->http);
return $this->origin;
}
public function getRegistrableDomain()
{
return $this->registrableDomain
?? ($this->registrableDomain = Domain::getRegistrableDomain($this->http->getHost()));
}
public function getDocumentUrl(): string
{
return $this->http->withFragment('');
}
public function getRelativizedDocumentUrl(): string
{
return substr($this->http->withFragment(''), \strlen($this->getOrigin()));
}
public function get(): string
{
return $this->__toString();
}
public function __toString(): string
{
return (string) $this->http;
}
public function relativize()
{
return substr($this->get(), \strlen($this->getOrigin()));
}
}
<file_sep>/tests/ExtractorTest.php
<?php
declare(strict_types=1);
namespace PiedWeb\UrlHarvester\Test;
use PiedWeb\UrlHarvester\ExtractBreadcrumb;
use PiedWeb\UrlHarvester\ExtractLinks;
use PiedWeb\UrlHarvester\Harvest;
use PiedWeb\UrlHarvester\Helper;
class ExtractorTest extends \PHPUnit\Framework\TestCase
{
private static $dom;
private static $harvest;
private function getUrl()
{
return 'https://piedweb.com/seo/crawler';
}
private function getHarvest()
{
if (null === self::$harvest) {
self::$harvest = Harvest::fromUrl(
$this->getUrl(),
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0'
);
}
return self::$harvest;
}
public function testExtractLinks()
{
$links = ExtractLinks::get($this->getHarvest());
foreach ($links as $link) {
$this->assertTrue(\strlen($link->getUrl()->get()) > 10);
$this->assertTrue(\strlen($link->getAnchor()) > 1);
$this->assertTrue('' !== $link->getElement()->getAttribute('href'));
}
$links = ExtractLinks::get($this->getHarvest(), ExtractLinks::SELECT_ALL);
foreach ($links as $link) {
$this->assertTrue(\strlen($link->getUrl()->get()) > 10);
}
}
public function testExtractBreadcrumb()
{
$bcItems = ExtractBreadcrumb::get($this->getHarvest());
foreach ($bcItems as $item) {
$this->assertTrue(\strlen($item->getUrl()) > 10);
$this->assertTrue(\strlen($item->getName()) > 1);
$this->assertTrue(\strlen($item->getCleanName()) > 1);
}
}
public function testHelperClean()
{
$this->assertSame('Hello Toi', Helper::clean('Hello Toi '));
}
}
<file_sep>/src/HarvestLinksTrait.php
<?php
namespace PiedWeb\UrlHarvester;
trait HarvestLinksTrait
{
/**
* @var array
*/
protected $links;
protected $linksPerType;
abstract public function getDom();
public function getLinkedRessources()
{
return ExtractLinks::get($this, ExtractLinks::SELECT_ALL);
}
public function getLinks($type = null): array
{
if (null === $this->links) {
$this->links = ExtractLinks::get($this, ExtractLinks::SELECT_A);
$this->classifyLinks();
}
switch ($type) {
case Link::LINK_SELF:
return $this->linksPerType[Link::LINK_SELF] ?? [];
case Link::LINK_INTERNAL:
return $this->linksPerType[Link::LINK_INTERNAL] ?? [];
case Link::LINK_SUB:
return $this->linksPerType[Link::LINK_SUB] ?? [];
case Link::LINK_EXTERNAL:
return $this->linksPerType[Link::LINK_EXTERNAL] ?? [];
default:
return $this->links;
}
}
/**
* Return duplicate links
* /test and /test#2 are not duplicates.
*/
public function getNbrDuplicateLinks(): int
{
$links = $this->getLinks();
$u = [];
foreach ($links as $link) {
$u[(string) $link->getUrl()] = 1;
}
return \count($links) - \count($u);
}
public function classifyLinks()
{
$links = $this->getLinks();
foreach ($links as $link) {
$this->linksPerType[$link->getType()][] = $link;
}
}
}
<file_sep>/src/Helper.php
<?php
namespace PiedWeb\UrlHarvester;
use ForceUTF8\Encoding;
class Helper
{
public static function clean(string $source)
{
return trim(preg_replace('/\s{2,}/', ' ', Encoding::toUTF8($source)));
}
public static function htmlToPlainText($str, $keepN = false)
{
$str = preg_replace('#<(style|script).*</(style|script)>#siU', ' ', $str);
$str = preg_replace('#</?(br|p|div)>#siU', "\n", $str);
$str = preg_replace('/<\/[a-z]+>/siU', ' ', $str);
$str = str_replace(["\r", "\t"], ' ', $str);
$str = strip_tags(preg_replace('/<[^<]+?>/', ' ', $str));
if ($keepN) {
$str = preg_replace('/ {2,}/', ' ', $str);
} else {
$str = preg_replace('/\s+/', ' ', $str);
}
return $str;
}
}
<file_sep>/README.md
<p align="center"><a href="https://dev.piedweb.com">
<img src="https://raw.githubusercontent.com/PiedWeb/piedweb-devoluix-theme/master/src/img/logo_title.png" width="200" height="200" alt="Open Source Package" />
</a></p>
# Url Meta Data Harvester
[![Latest Version](https://img.shields.io/github/tag/PiedWeb/UrlHarvester.svg?style=flat&label=release)](https://github.com/PiedWeb/UrlHarvester/tags)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](LICENSE)
[![GitHub Tests Action Status](https://img.shields.io/github/workflow/status/PiedWeb/UrlHarvester/Tests?label=tests)](https://github.com/PiedWeb/UrlHarvester/actions)
[![Quality Score](https://img.shields.io/scrutinizer/g/PiedWeb/UrlHarvester.svg?style=flat)](https://scrutinizer-ci.com/g/PiedWeb/UrlHarvester)
[![Code Coverage](https://codecov.io/gh/PiedWeb/UrlHarvester/branch/main/graph/badge.svg)](https://codecov.io/gh/PiedWeb/UrlHarvester/branch/main)
[![Type Coverage](https://shepherd.dev/github/PiedWeb/UrlHarvester/coverage.svg)](https://shepherd.dev/github/PiedWeb/UrlHarvester)
[![Total Downloads](https://img.shields.io/packagist/dt/piedweb/url-harvester.svg?style=flat)](https://packagist.org/packages/piedweb/url-harvester)
Harvest statistics and meta data from an URL or his source code (seo oriented).
Implemented in [Seo Pocket Crawler](https://piedweb.com/seo/crawler) ([source on github](https://github.com/PiedWeb/SeoPocketCrawler)).
## Install
Via [Packagist](https://img.shields.io/packagist/dt/piedweb/url-harvester.svg?style=flat)
```bash
$ composer require piedweb/url-harvester
```
## Usage
Harvest Methods :
```php
use \PiedWeb\UrlHarvester\Harvest;
use \PiedWeb\UrlHarvester\Link;
$url = 'https://piedweb.com';
Harvest::fromUrl($url)
->getResponse()->getInfo('total_time') // load time
->getResponse()->getInfo('size_download')
->getResponse()->getStatusCode()
->getResponse()->getContentType()
->getRes...
->getTag('h1') // @return first tag content (could be html)
->getUniqueTag('h1') // @return first tag content in utf8 (could contain html)
->getMeta('description') // @return string from content attribute or NULL
->getCanonical() // @return string|NULL
->isCanonicalCorrect() // @return bool
->getRatioTxtCode() // @return int
->getTextAnalysis() // @return \PiedWeb\TextAnalyzer\Analysis
->getKws() // @return 10 more used words
->getBreadCrumb()
->indexable($userAgent = 'googlebot') // @return int corresponding to a const from Indexable
->getLinks()
->getLinks(Link::LINK_SELF)
->getLinks(Link::LINK_INTERNAL)
->getLinks(Link::LINK_SUB)
->getLinks(Link::LINK_EXTERNAL)
->getLinkedRessources() // Return an array with all attributes containing a href or a src property
->mayFollow() // check headers and meta and return bool
->getDomain()
->getBaseUrl()
->getRobotsTxt() // @return \Spatie\Robots\RobotsTxt or empty string
->setRobotsTxt($content) // @param string or RobotsTxt
```
## Testing
```bash
$ composer test
```
## Contributing
Please see [contributing](https://dev.piedweb.com/contributing)
## Credits
- [Pied Web](https://piedweb.com)
- [All Contributors](https://github.com/PiedWeb/:package_skake/graphs/contributors)
## License
The MIT License (MIT). Please see [License File](LICENSE) for more information.
<file_sep>/src/RobotsTxtTrait.php
<?php
namespace PiedWeb\UrlHarvester;
use PiedWeb\Curl\Request as CurlRequest;
use Spatie\Robots\RobotsTxt;
trait RobotsTxtTrait
{
/** @var RobotsTxt|string (empty string) */
protected $robotsTxt;
//abstract public function getDomainAndScheme();
abstract public function getResponse();
abstract public function url();
/**
* @return RobotsTxt|string containing the current Robots.txt or NULL if an error occured
* or empty string if robots is empty file
*/
public function getRobotsTxt()
{
if (null === $this->robotsTxt) {
$url = $this->url()->getOrigin().'/robots.txt';
$request = $this->getResponse()->getRequest();
$userAgent = $request ? $request->getUserAgent() : Harvest::DEFAULT_USER_AGENT;
$request = new CurlRequest($url);
$request
->setDefaultSpeedOptions()
->setDownloadOnly('0-500000')
->setUserAgent($userAgent)
;
$result = $request->exec();
if (! $result instanceof \PiedWeb\Curl\Response
|| false === stripos($result->getContentType(), 'text/plain')
|| empty(trim($result->getContent()))
) {
$this->robotsTxt = '';
} else {
$this->robotsTxt = new RobotsTxt($result->getContent());
}
}
return $this->robotsTxt;
}
/**
* @param RobotsTxt|string $robotsTxt
*
* @return self
*/
public function setRobotsTxt($robotsTxt)
{
$this->robotsTxt = \is_string($robotsTxt) ? (empty($robotsTxt) ? '' : new RobotsTxt($robotsTxt)) : $robotsTxt;
return $this;
}
}
<file_sep>/test.php
<?php
header('Location: mailto:tagada');
<file_sep>/src/Domain.php
<?php
/**
* Entity.
*/
namespace PiedWeb\UrlHarvester;
use Pdp\Cache;
use Pdp\CurlHttpClient;
use Pdp\Manager;
use Pdp\Rules;
class Domain
{
protected static $rules;
public static function resolve(string $host): \Pdp\ResolvedDomainName
{
return self::getRules()->resolve($host);
}
public static function getRegistrableDomain(string $host): ?string
{
return self::resolve($host)->registrableDomain()->toString();
}
protected static function getRules()
{
if (null !== self::$rules) {
return self::$rules;
}
$reflector = new \ReflectionClass("Pdp\Rules");
$base = \dirname($reflector->getFileName(), 2);
return self::$rules = Rules::fromPath($base.'/test_data/public_suffix_list.dat');
//return self::$rules = (new Manager(new Cache(), new CurlHttpClient()))->getRules();
}
}
<file_sep>/src/Link.php
<?php
/**
* Entity.
*/
namespace PiedWeb\UrlHarvester;
use Symfony\Component\DomCrawler\Crawler as DomCrawler;
class Link
{
/** @var Url */
protected $url;
/** @var string cache */
protected $anchor;
/** @var \DomElement */
protected $element;
/** @var Harvest */
protected $parentDoc;
/** @var int */
protected $wrapper;
/** @var int */
protected $type;
// Ce serait dans une liste, dans une phrase...
protected $context;
// wrapper related
public const LINK_A = 1;
public const LINK_SRC = 4;
public const LINK_3XX = 2;
public const LINK_301 = 3;
// type related
public const LINK_SELF = 1;
public const LINK_INTERNAL = 2;
public const LINK_SUB = 3;
public const LINK_EXTERNAL = 4;
/**
* Add trailing slash for domain. Eg: https://piedweb.com => https://piedweb.com/ and '/test ' = '/test'.
*/
public static function normalizeUrl(string $url): string
{
$url = trim($url);
if ('' == preg_replace('@(.*\://?([^\/]+))@', '', $url)) {
$url .= '/';
}
return $url;
}
protected static function getWrapperFromElement(\DomElement $element): ?int
{
if ('a' == $element->tagName && $element->getAttribute('href')) {
return self::LINK_A;
}
if ($element->getAttribute('src')) {
return self::LINK_SRC;
}
return null;
}
/**
* Always submit absoute Url !
*/
public function __construct(string $url, Harvest $parent, \DOMElement $element = null, int $wrapper = null)
{
$this->url = new Url(self::normalizeUrl($url));
$this->parentDoc = $parent;
if (null !== $element) {
$this->setAnchor($element);
}
$this->element = $element;
$this->wrapper = $wrapper ?? (null !== $element ? self::getWrapperFromElement($element) : null);
}
public static function createRedirection(string $url, Harvest $parent, int $redirType = null): self
{
return new self($url, $parent, null, $redirType ?? self::LINK_3XX);
}
public function getWrapper(): ?int
{
return $this->wrapper;
}
protected function setAnchor(\DomElement $element)
{
// Get classic text anchor
$this->anchor = $element->textContent;
// If get nothing, then maybe we can get an alternative text (eg: img)
if (empty($this->anchor)) {
$alt = (new DomCrawler($element))->filter('*[alt]');
if ($alt->count() > 0) {
$this->anchor = $alt->eq(0)->attr('alt') ?? '';
}
}
// Limit to 100 characters
// Totally subjective
$this->anchor = substr(Helper::clean($this->anchor), 0, 99);
return $this;
}
public function getUrl(): Url
{
return $this->url;
}
public function getPageUrl(): string
{
return $this->url->getDocumentUrl(); //return preg_replace('/(\#.*)/si', '', $this->url->get());
}
public function getParentUrl(): Url
{
return $this->parentDoc->getUrl();
}
public function getAnchor()
{
return $this->anchor;
}
public function getElement()
{
return $this->element;
}
/**
* @return bool
*/
public function mayFollow()
{
// check meta robots and headers
if (null !== $this->parentDoc && ! $this->parentDoc->mayFollow()) {
return false;
}
// check "wrapper" rel
if (null !== $this->element && $this->element->getAttribute('rel')) {
if (preg_match('(nofollow|sponsored|ugc)', $this->element->getAttribute('rel'))) {
return false;
}
}
return true;
}
/**
* @return string
*/
public function getRelAttribute(): ?string
{
return null !== $this->element ? $this->element->getAttribute('rel') : null;
}
public function isInternalLink(): bool
{
return $this->url->getOrigin() == $this->getParentUrl()->getOrigin();
}
public function isSubLink(): bool
{
return ! $this->isInternalLink()
&& $this->url->getRegistrableDomain() == $this->getParentUrl()->getRegistrableDomain();
//&& strtolower(substr($this->getHost(), -strlen($this->parentDomain))) === $this->parentDomain;
}
public function isSelfLink(): bool
{
return $this->isInternalLink()
&& $this->url->getDocumentUrl() == $this->getParentUrl()->getDocumentUrl();
}
public function getType()
{
if ($this->isSelfLink()) {
return self::LINK_SELF;
}
if ($this->isInternalLink()) {
return self::LINK_INTERNAL;
}
if ($this->isSubLink()) {
return self::LINK_SUB;
}
return self::LINK_EXTERNAL;
}
}
<file_sep>/src/BreadcrumbItem.php
<?php
namespace PiedWeb\UrlHarvester;
class BreadcrumbItem
{
private $url;
private $name;
public function __construct($url, $name)
{
$this->url = $url;
$this->name = $name;
}
public function getUrl()
{
return $this->url;
}
public function getName()
{
return $this->name;
}
public function getCleanName()
{
return substr(strip_tags($this->name), 0, 100);
}
}
<file_sep>/src/Harvest.php
<?php
namespace PiedWeb\UrlHarvester;
use PiedWeb\Curl\Request as CurlRequest;
use PiedWeb\Curl\Response;
use PiedWeb\TextAnalyzer\Analysis;
use PiedWeb\TextAnalyzer\Analyzer as TextAnalyzer;
use Spatie\Robots\RobotsHeaders;
use Symfony\Component\DomCrawler\Crawler as DomCrawler;
class Harvest
{
use HarvestLinksTrait;
use RobotsTxtTrait;
public const DEFAULT_USER_AGENT = 'SeoPocketCrawler - Open Source Bot for SEO Metrics';
protected Response $response;
protected DomCrawler $dom;
protected string $baseUrl;
protected bool $follow;
private Analysis $textAnalysis;
protected Url $urlRequested;
protected Url $url;
/**
* @return self|int
*/
public static function fromUrl(
string $url,
string $userAgent = self::DEFAULT_USER_AGENT,
string $language = 'en,en-US;q=0.5',
?CurlRequest $previousRequest = null
) {
$url = Link::normalizeUrl($url); // add trailing slash for domain
$response = Request::makeFromRequest($previousRequest, $url, $userAgent, $language);
if ($response instanceof Response) {
return new self($response);
}
return $response;
}
public function __construct(Response $response)
{
$this->response = $response;
$this->url = new Url($this->response->getEffectiveUrl());
$this->urlRequested = new Url($this->response->getUrl());
}
public function urlRequested(): Url
{
return $this->urlRequested;
}
/**
* Return url response (curl effective url)
* // todo : check if urlRequested can be diffenrent than url (depends on curl wrench).
*/
public function url(): Url
{
return $this->url;
}
public function getUrl(): Url
{
return $this->url;
}
public function getResponse(): Response
{
return $this->response;
}
/** @psalm-suppress RedundantPropertyInitializationCheck */
public function getDom()
{
$this->dom = isset($this->dom) ? $this->dom : new DomCrawler($this->response->getContent());
return $this->dom;
}
private function find($selector, $i = null): DomCrawler
{
return null !== $i ? $this->getDom()->filter($selector)->eq($i) : $this->getDom()->filter($selector);
}
/**
* Alias for find($selector, 0).
*/
private function findOne($selector): DomCrawler
{
return $this->find($selector, 0);
}
/**
* Return content inside a selector.
* Eg.: getTag('title').
*
* @return ?string
*/
public function getTag($selector)
{
$found = $this->findOne($selector);
return $found->count() > 0 ? Helper::clean($found->text()) : null;
}
public function getUniqueTag($selector = 'title')
{
$found = $this->find($selector);
if (0 === $found->count()) {
return null;
}
if ($found->count() > 1) {
return $found->count().' `'.$selector.'` /!\ ';
}
return Helper::clean($found->eq(0)->text());
}
/**
* Return content inside a meta.
*
* @return string|null from content attribute
*/
public function getMeta(string $name): ?string
{
$meta = $this->findOne('meta[name='.$name.']');
return $meta->count() > 0 ? (null !== $meta->attr('content') ? Helper::clean($meta->attr('content')) : '')
: null;
}
/**
* Renvoie le contenu de l'attribut href de la balise link rel=canonical.
*/
public function getCanonical(): ?string
{
$canonical = $this->findOne('link[rel=canonical]');
return $canonical->count() > 0 ? (null !== $canonical->attr('href') ? $canonical->attr('href') : '') : null;
}
/*
* @return bool true si canonical = url requested or no canonical balise
*/
public function isCanonicalCorrect(?string $urlRequested = null): bool
{
$canonical = $this->getCanonical();
if (null === $canonical) {
return true;
}
$urlRequested = $urlRequested ?? $this->urlRequested()->get();
if ($urlRequested == $canonical) {
return true;
}
return $this->checkCanonicalException($urlRequested, $canonical);
}
private function checkCanonicalException(string $urlRequested, string $canonical): bool
{
if (false !== preg_match('/^.+?[^\/:](?=[?\/]|$)/', $urlRequested, $match)
&& $match[0] === ltrim($urlRequested, '/')
&& ($match[0] == $canonical || $match[0].'/' == $canonical)) {
return true;
}
return false;
}
/** @psalm-suppress RedundantPropertyInitializationCheck */
public function getTextAnalysis()
{
if (isset($this->textAnalysis)) {
return $this->textAnalysis;
}
return $this->textAnalysis = $this->getDom()->count() > 0 ? TextAnalyzer::get(
$this->getDom()->text(),
true, // only sentences
1, // no expression, just words
0 // keep trail
) : null;
}
public function getWordCount(): int
{
return (int) str_word_count($this->getDom()->text('') ?? '');
}
public function getKws()
{
return $this->getTextAnalysis()->getExpressions(10);
}
public function getRatioTxtCode(): int
{
$textLenght = \strlen($this->getDom()->text(''));
$htmlLenght = \strlen(Helper::clean($this->response->getContent()));
return (int) ($htmlLenght > 0 ? round($textLenght / $htmlLenght * 100) : 0);
}
/**
* Return an array of object with two elements Link and anchor.
*/
public function getBreadCrumb(?string $separator = null)
{
$breadcrumb = ExtractBreadcrumb::get($this);
if (null !== $separator && \is_array($breadcrumb)) {
$breadcrumb = array_map(function ($item) {
return $item->getCleanName();
}, $breadcrumb);
$breadcrumb = implode($separator, $breadcrumb);
}
return $breadcrumb;
}
/**
* @return ?string absolute url
*/
public function getRedirection(): ?string
{
$headers = $this->response->getHeaders();
$headers = array_change_key_case($headers ?: []);
if (isset($headers['location']) && ExtractLinks::isWebLink($headers['location'])) {
return $this->url()->resolve($headers['location']);
}
return null;
}
public function getRedirectionLink(): ?Link
{
$redirection = $this->getRedirection();
if (null !== $redirection) {
return Link::createRedirection($redirection, $this);
}
return null;
}
public function isRedirectToHttps(): bool
{
$redirUrl = $this->getRedirection();
return null !== $redirUrl && preg_replace('#^http:#', 'https:', $this->urlRequested()->get(), 1) == $redirUrl;
}
/**
* Return the value in base tag if exist, else, current Url.
*
* @psalm-suppress RedundantPropertyInitializationCheck
*/
public function getBaseUrl(): string
{
if (! isset($this->baseUrl)) {
$base = $this->findOne('base');
if ($base->getBaseHref() && filter_var($base->getBaseHref(), \FILTER_VALIDATE_URL)) {
$this->baseUrl = $base->getBaseHref();
} else {
$this->baseUrl = $this->url()->get();
}
}
return (string) $this->baseUrl;
}
/**
* @return int correspond to a const from Indexable
*/
public function indexable(string $userAgent = 'googlebot'): int
{
return Indexable::indexable($this, $userAgent);
}
public function isIndexable(string $userAgent = 'googlebot'): bool
{
return Indexable::INDEXABLE === $this->indexable($userAgent);
}
protected function metaAuthorizeToFollow()
{
return ! (strpos($this->getMeta('googlebot'), 'nofollow') || strpos($this->getMeta('robots'), 'nofollow'));
}
/** @psalm-suppress RedundantPropertyInitializationCheck */
public function mayFollow()
{
if (! isset($this->follow)) {
$robotsHeaders = new RobotsHeaders((array) $this->response->getHeaders());
$this->follow = $robotsHeaders->mayFollow() && $this->metaAuthorizeToFollow() ? true : false;
}
return $this->follow;
}
}
<file_sep>/src/ExtractBreadcrumb.php
<?php
/**
* Entity.
*/
namespace PiedWeb\UrlHarvester;
/**
* Quelques notes :
* - Un bc ne contient pas l'élément courant.
*/
class ExtractBreadcrumb
{
protected $breadcrumb = [];
protected $parentDoc;
public const BC_RGX = '#<(div|p|nav|ul)[^>]*(id|class)="?(breadcrumbs?|fil_?d?arian?ne)"?[^>]*>(.*)<\/(\1)>#siU';
public const BC_DIVIDER = [
'class="?navigation-pipe"?',
'>',
'class="?divider"?',
'›',
'</li>',
];
/**
* @param string $source HTML code from the page
* @param string $baseUrl To get absolute urls
* @param string $current The current url. If not set we thing it's the same than $baseUrl
*
* @return array|null
*/
public static function get(Harvest $parent)
{
$self = new self();
$self->parentDoc = $parent;
return $self->extractBreadcrumb();
}
protected function __construct()
{
}
/**
* @return array|null
*/
public function extractBreadcrumb()
{
$breadcrumb = $this->findBreadcrumb();
if (null !== $breadcrumb) {
foreach (self::BC_DIVIDER as $divider) {
$exploded = $this->divideBreadcrumb($breadcrumb, $divider);
if (false !== $exploded) {
$this->extractBreadcrumbData($exploded);
return $this->breadcrumb;
}
}
}
}
protected function findBreadcrumb()
{
if (preg_match(self::BC_RGX, $this->parentDoc->getResponse()->getContent(), $match)) {
return $match[4];
}
}
protected function divideBreadcrumb($breadcrumb, $divider)
{
$exploded = preg_split('/'.str_replace('/', '\/', $divider).'/si', $breadcrumb);
return false !== $exploded && \count($exploded) > 1 ? $exploded : false;
}
/**
* On essaye d'extraire l'url et l'ancre.
*/
protected function extractBreadcrumbData($array)
{
foreach ($array as $a) {
$link = $this->extractHref($a);
if (null === $link || $link == $this->parentDoc->getUrl()->get()) {
break;
}
$this->breadcrumb[] = new BreadcrumbItem(
$link,
$this->extractAnchor($a)
);
}
}
protected function extractAnchor($str)
{
return trim(strtolower(Helper::htmlToPlainText($str)), '> ');
}
protected function extractHref($str)
{
$regex = [
'href="([^"]*)"',
'href=\'([^\']*)\'',
'href=(\S+) ',
];
foreach ($regex as $r) {
if (preg_match('/'.$r.'/siU', $str, $match)) {
if (ExtractLinks::isWebLink($match[1])) {
return $this->parentDoc->getUrl()->resolve($match[1]);
}
}
}
}
}
<file_sep>/src/Indexable.php
<?php
namespace PiedWeb\UrlHarvester;
use Spatie\Robots\RobotsHeaders;
class Indexable
{
// https://stackoverflow.com/questions/1880148/how-to-get-name-of-the-constant
public const INDEXABLE = 0;
public const NOT_INDEXABLE_ROBOTS = 1;
public const NOT_INDEXABLE_HEADER = 2;
public const NOT_INDEXABLE_META = 3;
public const NOT_INDEXABLE_CANONICAL = 4;
public const NOT_INDEXABLE_4XX = 5;
public const NOT_INDEXABLE_5XX = 6;
public const NOT_INDEXABLE_NETWORK_ERROR = 7;
public const NOT_INDEXABLE_TOO_BIG = 10;
public const NOT_INDEXABLE_3XX = 8;
public const NOT_INDEXABLE_NOT_HTML = 9;
/** @var Harvest */
protected $harvest;
/** @var string */
protected $isIndexableFor;
public function __construct(Harvest $harvest, string $isIndexableFor = 'googlebot')
{
$this->harvest = $harvest;
$this->isIndexableFor = $isIndexableFor;
}
public function robotsTxtAllows()
{
$url = $this->harvest->getResponse()->getUrl();
$robotsTxt = $this->harvest->getRobotsTxt();
return '' === $robotsTxt ? true : $robotsTxt->allows($url, $this->isIndexableFor);
}
public function metaAllows()
{
$meta = $this->harvest->getMeta($this->isIndexableFor);
$generic = $this->harvest->getMeta('robots');
return ! (false !== stripos($meta, 'noindex') || false !== stripos($generic, 'noindex'));
}
public function headersAllow()
{
$headers = explode(\PHP_EOL, $this->harvest->getResponse()->getHeaders(false));
return RobotsHeaders::create($headers)->mayIndex($this->isIndexableFor);
}
public static function indexable(Harvest $harvest, string $isIndexableFor = 'googlebot'): int
{
$self = new self($harvest, $isIndexableFor);
// robots
if (! $self->robotsTxtAllows()) {
return self::NOT_INDEXABLE_ROBOTS;
}
if (! $self->headersAllow()) {
return self::NOT_INDEXABLE_HEADER;
}
if (! $self->metaAllows()) {
return self::NOT_INDEXABLE_META;
}
// canonical
if (! $harvest->isCanonicalCorrect()) {
return self::NOT_INDEXABLE_CANONICAL;
}
$statusCode = $harvest->getResponse()->getStatusCode();
// status 4XX
if ($statusCode < 500 && $statusCode > 399) {
return self::NOT_INDEXABLE_4XX;
}
// status 5XX
if ($statusCode < 600 && $statusCode > 499) {
return self::NOT_INDEXABLE_5XX;
}
// status 3XX
if ($statusCode < 400 && $statusCode > 299) {
return self::NOT_INDEXABLE_3XX;
}
return self::INDEXABLE;
}
}
| 5a0d96da8edb1c9f78af50f21097080d88a97e6e | [
"Markdown",
"PHP"
] | 18 | PHP | PiedWeb/UrlHarvester | 1d06b879201708a93396db4fd7f1f24178948b6e | 6c5871f3c6379c9b0f66030a8c5ef9cbc239f5f9 | |
refs/heads/master | <repo_name>dingz212445/cit590-hw10_procolation<file_sep>/GridSet.java
package percolation;
import java.util.*;
public class GridSet {
ArrayList<Grid> allgrids = new ArrayList<Grid>();
ArrayList<Boolean> percolated = new ArrayList<Boolean>();
void addGrid(Grid g) {
allgrids.add(g);
}
void addPercolate(Grid g) {
percolated.add(g.percolate());
}
double percolRate() {
double total = percolated.size();
int percol = 0;
for(Boolean b : percolated) {
if (b) {
percol++;
}
}
return percol/total;
}
void clearAllgrid() {
allgrids.clear();
}
void clearPercolated() {
percolated.clear();
}
}
<file_sep>/README.md
"# cit590-hw10_procolation"
| 3406b6df1d44d465ce3ca7abd1627260bc9b1dd9 | [
"Markdown",
"Java"
] | 2 | Java | dingz212445/cit590-hw10_procolation | c090c07bce12fcbbaeb837e368006dd18a0d2a3e | 30969a90bc259cc69a74c82f96057f9ef3ef678c | |
refs/heads/master | <file_sep>#ifndef TYPES_H__
#define TYPES_H__
typedef unsigned int uint_t;
typedef uint_t uint32_t;
struct point_t {
uint_t x, y, z;
point_t() {}
point_t( uint_t& _x, uint_t& _y, uint_t& _z )
{
x = _x;
y = _y;
z = _z;
}
};
struct tsize_t {
uint_t x, y, z;
tsize_t() { }
tsize_t( int _x, int _y, int _z )
{
x = (uint_t)_x;
y = (uint_t)_y;
z = (uint_t)_z;
}
};
typedef enum {
LAYER_FC,
LAYER_CONV,
LAYER_RELU,
LAYER_POOL
} layer_type_t;
#endif
<file_sep>#ifndef FC_LAYER_T_H__
#define FC_LAYER_T_H__
#include <vector>
#include <math.h>
#include <boost/format.hpp>
#include "gradient_t.h"
#include "optimization.h"
struct fc_layer_t {
layer_type_t type;
tensor_t<float> in;
tensor_t<float> out;
tensor_t<float> weights;
tensor_t<float> prev_updates;
tensor_t<float> biases;
tensor_t<float> prev_bias_updates;
std::vector<float> sum;
tensor_t<float> dE_dIn; // partial derivative of network error by n-th layer input
fc_layer_t( tsize_t _in_size, uint_t _out_size ) :
in( _in_size.x, _in_size.y, _in_size.z ),
out( _out_size ),
weights( _out_size, _in_size.x * _in_size.y * _in_size.z ),
prev_updates( _out_size, _in_size.x * _in_size.y * _in_size.z ),
biases( _out_size ),
prev_bias_updates( _out_size ),
sum( _out_size ),
dE_dIn( _in_size.x * _in_size.y * _in_size.z )
{
type = LAYER_FC;
init_weights();
}
~fc_layer_t() {
}
// FIXME
void init_weight_rand_small( float& weight, uint_t maxval ) {
// random small values
weight = 2.19722f / maxval * rand() / float( RAND_MAX ); // random small values
}
void init_weight_rand(float& weight) {
// random values -1..1
//
weight = float(rand()) / (float(RAND_MAX) + 1.0);
/*
int evn = rand() % 2;
if (evn == 0) {
weight = float(rand()) / (float(RAND_MAX) + 1.0);
} else {
weight = -1 * float(rand()) / (float(RAND_MAX) + 1.0);
}
*/
}
void init_weights() {
srand(time(NULL));
for ( uint_t i = 0 ; i < out.size.x; i++ ) {
init_weight_rand( biases( i ) );
for ( uint_t j = 0 ; j < ( in.get_size() ); j++ ) {
// init_weight_rand_small( weights( i, j ), in.size.x * in.size.y * in.size.z ) ;
init_weight_rand( weights( i, j ) ) ;
prev_updates( i, j ) = 0;
prev_bias_updates( i ) = 0;
}
}
}
void print_weights()
{
for ( uint_t j = 0; j < weights.size.y; j++ ) {
std::cout << "output neuron " << j << " : ";
for ( uint_t i = 0; i < weights.size.x; i++ ) {
std::cout << boost::format("%7.5f") % weights( i, j, 0 ) << " ";
}
std::cout << std::endl;
}
}
uint_t map( point_t p )
{
return in.size.z * in.size.y* p.x +
in.size.z * p.y +
p.z;
/*
return p.z * (in.size.x * in.size.y) +
p.y * (in.size.x) +
p.x;
*/
}
float sig( float x )
{
float sig = 1.0f / (1.0f + exp( -x ));
return sig;
}
float activator_function( float x )
{
//return tanhf( x );
return sig(x);
}
/*
float activator_derivative( float x )
{
//float t = tanhf( x );
//return 1 - t * t;
return sig( x ) * ( 1 - sig( x ) ); // (sig)' = sig * (1 - sig)
}
*/
void activate( const tensor_t<float>& _in )
{
assert( (_in.size.x == in.size.x) && (_in.size.y == in.size.y) && (_in.size.z == in.size.z) );
in.copy_from(_in);
activate();
}
void activate()
{
for ( uint_t m = 0; m < out.size.x; m++ ) {
float input_sum = 0;
for ( uint_t i = 0; i < in.size.x; i++ ) {
for ( uint_t j = 0; j < in.size.y; j++ ) {
for ( uint_t z = 0; z < in.size.z; z++ ) {
int n = map( point_t( i, j, z ) );
input_sum += in( i, j, z ) * weights( m, n );
}
}
}
input_sum += biases( m );
sum[m] = input_sum;
out( m ) = activator_function( input_sum );
}
}
void update( tensor_t<float>& dE_dIn_next)
{
// calculation of deltas vector
tensor_t<float> deltas( out.get_size() );
for ( uint_t m = 0; m < out.get_size(); m++ ) {
deltas( m ) = dE_dIn_next( m ) * out( m ) * ( 1 - out( m ) );
}
// weights update
for ( uint_t m = 0; m < out.get_size(); m++ ) {
float bias_update = deltas( m ) * LEARNING_RATE + MOMENTUM * prev_bias_updates( m );
biases( m ) -= bias_update;
prev_bias_updates( m ) = bias_update;
for ( uint_t n = 0; n < in.get_size(); n++ ) {
float update = deltas( m ) * in( n ) * LEARNING_RATE + MOMENTUM * prev_updates( m, n );
weights( m, n ) -= update;
prev_updates( m, n ) = update;
// or ...
// weights( m, n ) -= deltas( m ) * in( n );
// biases( m ) -= deltas( m ); // ( deltas( m ) * 1 )
}
}
// calculation of dE_dIn vector
for ( uint_t n = 0; n < in.get_size(); n++ ) {
dE_dIn( n ) = 0;
for ( uint_t m = 0; m < out.get_size(); m++ ) {
dE_dIn( n ) += deltas( m ) * weights( m, n ); // to be used in the previous layer
}
}
}
};
#endif
<file_sep>#ifndef TENSOR_T_H__
#define TENSOR_T_H__
#include <vector>
#include <assert.h>
#include <string.h>
#include "types.h"
template <typename T>
struct tensor_t {
tsize_t size;
T* data;
tensor_t( uint_t _x, uint_t _y, uint_t _z ) {
assert( _x > 0 && _y > 0 && _z > 0 );
data = new T[_x * _y * _z];
size.x = _x;
size.y = _y;
size.z = _z;
}
tensor_t( uint_t _x, uint_t _y ) {
assert( _x > 0 && _y > 0 );
data = new T[_x * _y]; // data = new T[_x * _y * 1]
size.x = _x;
size.y = _y;
size.z = 1;
}
tensor_t( uint_t _x ) {
assert( _x > 0 );
data = new T[_x]; // data = new T[_x * 1 * 1]
size.x = _x;
size.y = 1;
size.z = 1;
}
tensor_t( const tensor_t<T>& other ) {
data = new T[other.size.x * other.size.y * other.size.z];
memcpy(
this->data,
other.data,
other.size.x * other.size.y * other.size.z * sizeof( T )
);
this->size = other.size;
}
T& get( uint_t _x, uint_t _y, uint_t _z )
{
assert( _x < size.x && _y < size.y && _z < size.z );
return data[
size.z * size.y* _x +
size.z * _y +
_z
/*
_z * (size.x * size.y) +
_y * (size.x) +
_x
*/
];
}
T& operator()( uint_t _x, uint_t _y, uint_t _z )
{
return get( _x, _y, _z );
}
T& operator()( uint_t _x, uint_t _y )
{
return get( _x, _y, 0 );
}
T& operator()( uint_t _x )
{
return get( _x, 0, 0 );
}
void copy_from( const std::vector<std::vector<std::vector<T> > >& _data )
{
uint_t _size_x = _data.size();
uint_t _size_y = _data[0].size();
uint_t _size_z = _data[0][0].size();
assert( size.x == _size_x && size.y == _size_y && size.z == _size_z);
for (uint_t i = 0; i < _size_x; i++) {
for (uint_t j = 0; j < _size_y; j++) {
for (uint_t k = 0; k < _size_z; k++) {
this->get(i, j, k) = _data[i][j][k];
/*
this->get(i, j, k) = _data[k][j][i];
*/
}
}
}
}
void copy_from( const tensor_t<T>& other ) {
assert( (other.size.x == size.x) && (other.size.y == size.y) && (other.size.z == size.z) );
memcpy(
this->data,
other.data,
other.size.x * other.size.y * other.size.z * sizeof( T )
);
}
tensor_t<T> operator+( tensor_t<T>& other )
{
assert(this->size.x == other.size.x);
assert(this->size.y == other.size.y);
assert(this->size.z == other.size.z);
tensor_t<T> clone(*this);
for (int i = 0; i < clone.size.x; i++) {
clone.data[i] += other.data[i];
}
return clone;
}
tensor_t<T> operator-( tensor_t<T>& other )
{
assert(this->size.x == other.size.x);
assert(this->size.y == other.size.y);
assert(this->size.z == other.size.z);
tensor_t<T> clone(*this);
for (uint_t i = 0; i < clone.size.x; i++) {
clone.data[i] -= other.data[i];
}
return clone;
}
uint_t get_size() {
return size.x * size.y * size.z;
}
~tensor_t()
{
delete[] data;
}
};
#endif
<file_sep>SOURCES = tensor_t.test.cpp fc_layer_t.test.cpp
TESTS = $(SOURCES:.cpp=)
DEBUG = 1
#---------------------------------
OBJECTS = $(SOURCES:.cpp=.o)
LDFLAGS += -L/usr/lib
LDFLAGS += -L/lib/boost/lib
LDFLAGS += -lboost_unit_test_framework.dll
CPPFLAGS += -Wall
# CPPFLAGS += ...
CPPFLAGS += -I/usr/local/include
ifdef DEBUG
CPPFLAGS += -g
endif
all: $(TESTS)
$(TESTS): $(OBJECTS)
echo TESTS = $(TESTS);
$(foreach var, $(OBJECTS), $(CXX) -o $(var:.o=) $(var) $(LDFLAGS);)
$(OBJECTS): $(SOURCES)
$(foreach var, $(SOURCES), $(CXX) -c $(CPPFLAGS) $(var) -o $(var:.cpp=.o);)
clean:
rm -f *.o
build:
$(MAKE) clean
$(MAKE)
<file_sep>#include <iostream>
#include "tensor_t.h"
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE test_tensor_t
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE( test_tensor_t_constructor )
{
tensor_t<float> t1(1, 2, 3);
BOOST_CHECK(t1.size.x == 1);
BOOST_CHECK(t1.size.y == 2);
BOOST_CHECK(t1.size.z == 3);
tensor_t<float> t2(t1);
BOOST_CHECK(t1.size.x == 1);
BOOST_CHECK(t1.size.y == 2);
BOOST_CHECK(t1.size.z == 3);
}
BOOST_AUTO_TEST_CASE( test_tensor_t_get )
{
tensor_t<float> t(2, 2, 3);
t.data[0] = 0;
t.data[1] = 1.1f;
t.data[2] = 2.2f;
t.data[3] = 3.3f;
t.data[4] = 4.4f;
t.data[5] = 5.5f;
t.data[6] = 6.6f;
t.data[7] = 7.7f;
t.data[8] = 8.8f;
t.data[9] = 9.9f;
t.data[10] = 10.10f;
t.data[11] = 11.11f;
BOOST_CHECK(t.get(0, 0, 0) == 0);
BOOST_CHECK(t.get(1, 0, 1) == 7.7f);
BOOST_CHECK(t.get(0, 1, 1) == 4.4f);
BOOST_CHECK(t.get(1, 1, 2) == 11.11f);
}
BOOST_AUTO_TEST_CASE( test_tensor_t_operatot_get )
{
tensor_t<float> t(2, 2, 3);
t.data[0] = 0;
t.data[1] = 1.1f;
t.data[2] = 2.2f;
t.data[3] = 3.3f;
t.data[4] = 4.4f;
t.data[5] = 5.5f;
t.data[6] = 6.6f;
t.data[7] = 7.7f;
t.data[8] = 8.8f;
t.data[9] = 9.9f;
t.data[10] = 10.10f;
t.data[11] = 11.11f;
BOOST_CHECK(t(0, 0, 0) == 0);
BOOST_CHECK(t(1, 0, 1) == 7.7f);
BOOST_CHECK(t(0, 1, 1) == 4.4f);
BOOST_CHECK(t(1, 1, 2) == 11.11f);
}
BOOST_AUTO_TEST_CASE( test_tensor_t_copy_from )
{
std::vector<std::vector<std::vector<float> > > data;
std::vector<std::vector<float> > y;
std::vector<float> z;
z.push_back(0);
z.push_back(1.1f);
z.push_back(2.2f);
y.push_back(z);
z.clear();
z.push_back(3.3f);
z.push_back(4.4f);
z.push_back(5.5f);
y.push_back(z);
data.push_back(y);
y.clear();
z.clear();
z.push_back(6.6f);
z.push_back(7.7f);
z.push_back(8.8f);
y.push_back(z);
z.clear();
z.push_back(9.9f);
z.push_back(10.10f);
z.push_back(11.11f);
y.push_back(z);
data.push_back(y);
tensor_t<float> t(2, 2, 3);
t.copy_from(data);
BOOST_CHECK(t(0, 0, 0) == 0);
BOOST_CHECK(t(1, 0, 1) == 7.7f);
BOOST_CHECK(t(0, 1, 1) == 4.4f);
BOOST_CHECK(t(1, 1, 2) == 11.11f);
}
<file_sep>#include <iostream>
#include <vector>
#include <cstdlib>
#include "types.h"
#include "tensor_t.h"
#include "fc_layer_t.h"
#define EPOCHS_NUM 5000
struct case_t
{
struct tensor_t<float> data;
struct tensor_t<float> out;
case_t() :
data( 2 ),
out( 1 )
{}
};
void add_case(std::vector<case_t> &cases, float x1, float x2, float y)
{
case_t c;
c.data( 0 ) = x1;
c.data( 1 ) = x2;
c.out( 0 ) = y;
cases.push_back( c );
}
void add_cases(std::vector<case_t> &cases) {
add_case(cases, 0, 0, 0);
add_case(cases, 0, 1, 1);
add_case(cases, 1, 0, 1);
add_case(cases, 1, 1, 0);
}
void train ( std::vector<fc_layer_t*>& layers, std::vector<case_t> cases ) // FIXME: const cases
{
for (uint_t i = 0; i < EPOCHS_NUM; i++) {
std::cout << std::endl << std::endl << "EPOCH " << i << std::endl;
for ( uint_t j = 0; j < cases.size(); j++ ) {
std::cout << std::endl << "case " << j << " ";
std::cout << "( " << cases[j].data(0) << ", " << cases[j].data(1) << " ) ->" << cases[j].out(0) << " | ";
struct tensor_t<float> expected = cases[j].out;
// forward pass
for ( uint_t k = 0; k < layers.size(); k++ ) {
// activate layer k
if ( k == 0 ) {
layers[k]->activate(cases[j].data);
} else {
layers[k]->activate(layers[k-1]->out);
}
}
std::cout << layers.back()->out(0) << std::endl;
// backpropagation
tensor_t<float> grads = layers.back()->out - expected;
for ( int i = (int)(layers.size() - 1); i >= 0; i-- )
{
if ( i == (int)layers.size() - 1 ) {
layers[i]->update( grads );
} else {
layers[i]->update( layers[i + 1]->dE_dIn);
}
}
} // cases loop
} // epochs loop
}
int main()
{
std::vector<fc_layer_t*> nn;
fc_layer_t* layer1 = new fc_layer_t( tsize_t( 2, 1, 1 ), 5);
fc_layer_t* layer2 = new fc_layer_t( tsize_t( 5, 1, 1 ), 1);
nn.push_back(layer1);
nn.push_back(layer2);
std::vector<case_t> cases;
add_cases(cases);
train( nn, cases );
delete layer1;
delete layer2;
}
<file_sep>#ifndef GRADIENT_T_H__
#define GRADIENT_T_H__
struct gradient_t
{
float grad;
float oldgrad;
gradient_t()
{
grad = 0;
oldgrad = 0;
}
};
#endif
<file_sep>#ifndef OPTIMIZATION_H__
#define OPTIMIZATION_H__
#include "gradient_t.h"
// #define LEARNING_RATE 0.01
// #define MOMENTUM 0.6
// #define WEIGHT_DECAY 0.001
#define LEARNING_RATE 0.5
#define MOMENTUM 0.6
#define WEIGHT_DECAY 0.001
#endif
<file_sep>#include <iostream>
#include "types.h"
#include "tensor_t.h"
#include "fc_layer_t.h"
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE test_tensor_t
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE( test_fc_layer_t_constructor )
{
tsize_t tsize = {2, 2, 3};
fc_layer_t l(tsize, 3);
tensor_t<float> in_t(2, 2, 3);
in_t.data[0] = 0;
in_t.data[1] = 1.1f;
in_t.data[2] = 2.2f;
in_t.data[3] = 3.3f;
in_t.data[4] = 4.4f;
in_t.data[5] = 5.5f;
in_t.data[6] = 6.6f;
in_t.data[7] = 7.7f;
in_t.data[8] = 8.8f;
in_t.data[9] = 9.9f;
in_t.data[10] = 10.10f;
in_t.data[11] = 11.11f;
for( uint_t i = 0; i < (l.in.size.x * l.in.size.y * l.in.size.z); i++ ) {
l.weights( i, 0, 0 ) = 0.1;
l.weights( i, 1, 0 ) = 0.5;
l.weights( i, 2, 0 ) = 1;
}
l.print_weights();
l.activate(in_t);
// std::cout << "in_t.data[6] = " << in_t.data[6] << std::endl;
// std::cout << "weights( 6, 0, 0 ) = " << (*l.weights)( 6, 0, 0 ) << std::endl;
// FIXME
// BOOST_CHECK((*l.out)( 2, 0, 0 ) == 66 );
}
| c288f3ca062604690e5d5ede29d9318d2790f43b | [
"C",
"Makefile",
"C++"
] | 9 | C | GennadyPortenko/simple-neural-network | 440e80e8e9a4487761ab5bb01d6720d2fb827e12 | a1104055cf461bbabc3d367eabb516c217a0899a | |
refs/heads/master | <file_sep>//
// TypeDefs.h
// bongSDK
//
// Created by mario on 15/1/15.
// Copyright (c) 2015年 Ginshell Inc. All rights reserved.
//
#ifndef bongSDK_TypeDefs_h
#define bongSDK_TypeDefs_h
/**
* bongSDK 返回码类型
*/
typedef NS_ENUM(int, bongSDKErrorCode){
/**
* 无错误
*/
bongSDKErrorCodeNone,
/**
* 配置无效,即 `appID`、`appKey` 等配置无效
*/
bongSDKErrorCodeInvalidateConfiguration,
/**
* token 无效,需重新调用 `requestAccessTokenWithCallback:` 来获取
*/
bongSDKErrorCodeInvalidateToken,
/**
* 参数错误
*/
bongSDKErrorCodeParameterError,
/**
* 正在
*/
bongSDKErrorCodeBusy,
/**
* 服务器返回未知错误
*/
bongSDKErrorCodeResponseUnknown,
/**
* bong 标识符错误
*/
bongSDKErrorCodeInvalidatebongIdentifier,
/**
* 蓝牙未打开,需提醒用户开启蓝牙
*/
bongSDKErrorCodeBLEPowerOff,
/**
* 不支持蓝牙低功耗
*/
bongSDKErrorCodeBLEUnsupported,
/**
* 未获取到手环数据
*/
bongSDKErrorCodeDataFetchNothing,
/**
* 接口调用错误
*/
bongSDKErrorCodeInvalidAPI,
/**
* 产品 ID 不支持
*/
bongSDKErrorCodeInvalidProductID,
/**
* bong X/XX 事件通知错误
*/
bongSDKErrorCodeXNoteError,
/**
* 意外断开设备
*/
bongSDKErrorCodeUnexpectedDisconnection,
/**
* 网络连接错误
*/
bongSDKErrorCodeNetworkError,
/**
* 请求成功
*/
bongSDKErrorCodeRequestSuccess = 200,
/**
* 请求未授权
*/
bongSDKErrorCodeReuqestUnAutherized = 401,
/**
* 签名错误
*/
bongSDKErrorCodeRequestSignError = 403,
/**
* 越权错误
*/
bongSDKErrorCodeRequestExceedingAuthority = 405,
/**
* 服务器内部错误
*/
bongSDKErrorCodeRequestInternalError = 500,
/**
* 服务器返回未知错误
*/
bongSDKErrorCodeRequestUnknownError = 2001,
/**
* 服务器返回错误
*/
bongSDKErrorCodeRequestUpperLimit = 2002,
/**
* 服务器返回错误
*/
bongSDKErrorCodeRequestLowerLimit = 2003,
/**
* 服务器返回错误
*/
bongSDKErrorCodeRequestInEvent = 2004,
/**
* 服务器返回错误
*/
bongSDKErrorCodeRequestOffEvent = 2005,
/**
* 服务器返回错误
*/
bongSDKErrorCodeRequestDateLimit = 2007,
/**
* 服务器返回错误
*/
bongSDKErrorCodeRequestDataLimit = 2007,
/**
* 服务器返回错误
*/
bongSDKErrorCodeRequestUnbond = 2012,
};
/**
* bong 产品 ID
*/
typedef NS_ENUM(NSInteger, bongSDKProductID){
/**
* 无产品 ID
*/
bongSDKProductIDNone = 0,
/**
* bong II
*/
bongSDKProductIDTwo = 101002,
/**
* bong X
*/
bongSDKProductIDX = 101003,
/**
* bong XX
*/
bongSDKProductIDXX = 101004,
};
/**
* Yes! 键触摸类型
*/
typedef NS_ENUM(int, YESKeyTouchType){
/**
* 未定义类型,任意触摸 Yes! 键都可能产生此类型
*/
YESKeyTouchTypeNone,
/**
* 长触摸,Yes! 键灯闪烁两次松开
*/
YESKeyTouchTypeLong,
/**
* 短触摸,Yes! 键灯闪烁一次松开
*/
YESKeyTouchTypeShort,
};
/**
* bong X/XX 按键通知类型
*/
typedef NS_ENUM(NSInteger, bongSDKXNoteType){
/**
* 无类型
*/
bongSDKXNoteTypeNone = 0,
/**
* 向上滑动
*/
bongSDKXNoteTypeSwipeUp = 6,
/**
* 向下滑动
*/
bongSDKXNoteTypeSwipeDown = 7,
/**
* 向左滑动
*/
bongSDKXNoteTypeSwipeLeft = 8,
/**
* 向右滑动
*/
bongSDKXNoteTypeSwipeRight = 9,
/**
* 入睡
*/
bongSDKXNoteTypeSleepIn = 12,
/**
* 起床
*/
bongSDKXNoteTypeSleepOut = 13,
/**
* 进入 bong 状态
*/
bongSDKXNoteTypebongIn = 14,
/**
* 退出 bong 状态
*/
bongSDKXNoteTypebongOut = 15,
/**
* 长按
*/
bongSDKXNoteTypeLongPress = 25,
};
/**
* 数据同步状态
*/
typedef NS_ENUM(int, bongSDKDataFetchStatus){
/**
* 初始状态
*/
bongSDKDataFetchStatusNone,
/**
* 连接
*/
bongSDKDataFetchStatusConnecting,
/**
* 同步
*/
bongSDKDataFetchStatusFetching,
/**
* 上传
*/
bongSDKDataFetchStatusUploading,
/**
* 成功结果
*/
bongSDKDataFetchStatusSucceed,
/**
* 失败结果
*/
bongSDKDataFetchStatusFailed,
/**
* 通讯成功,但设备上并未有此段数据
*/
bongSDKDataFetchStatusFetchNothing,
};
/**
* bong 天数据的类型
*/
typedef NS_ENUM(int, bongSDKActivityType){
/**
* 无
*/
bongSDKActivityTypeNone,
/**
* 睡眠类型
*/
bongSDKActivityTypeSleep,
/**
* 运动类型
*/
bongSDKActivityTypebong,
/**
* 非运动类型
*/
bongSDKActivityTypeNotbong,
/**
* 摘下类型
*/
bongSDKActivityTypeTakeOff,
/**
* 充电类型(bongII 手环无此类型,但 bongI 用户升级至 bongII 后,其历史数据可能有此类型)
*/
bongSDKActivityTypeCharge,
};
/**
* 运动类型数据的具体运动类型
*/
typedef NS_ENUM(int, bongSDKActivitybongType){
/**
* 无
*/
bongSDKActivitybongTypeNone,
/**
* 热身
*/
bongSDKActivitybongTypeWarmUp,
/**
* 健走
*/
bongSDKActivitybongTypeStride,
/**
* 运动
*/
bongSDKActivitybongTypeSport,
/**
* 跑步
*/
bongSDKActivitybongTypeRun,
/**
* 游泳
*/
bongSDKActivitybongTypeSwim,
/**
* 自行车
*/
bongSDKActivitybongTypeCycling
};
/**
* 非运动类型数据的具体运动类型
*/
typedef NS_ENUM(int, bongSDKActivityNotbongType){
/**
* 无
*/
bongSDKActivityNotbongTypeNone,
/**
* 静
*/
bongSDKActivityNotbongTypeStill,
/**
* 散步
*/
bongSDKActivityNotbongTypeWalk,
/**
* 交通工具
*/
bongSDKActivityNotbongTypeTrans
};
#endif
<file_sep># Uncomment this line to define a global platform for your project
platform :ios, '8.0'
# Uncomment this line if you're using Swift
use_frameworks!
target 'BongMe' do
pod "OAuthSwift", "~> 0.5.0"
pod 'JSONModel'
end
<file_sep>//
// BongXTableViewController.swift
// BongMe
//
// Created by Ryan on 1/17/16.
// Copyright © 2016 J.A.V.I.S. All rights reserved.
//
import UIKit
class BongXTableViewController: UITableViewController, bongSDKDelegate, UIPopoverPresentationControllerDelegate {
private var popCtlr:ActivityIndicatorViewController?
private var popMsg:String = ""
private var scanning:Bool = false
private var notifying:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
bongSDK.addDelegate(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
bongSDK.removeDelegate(self)
bongSDK.enableXNote(false)
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.row == 0 {
let now = NSDate()
bongSDK.fetchbongDataWithStartDate(now.dateByAddingTimeInterval(-60 * 30), endDate: now)
performSegueWithIdentifier("Popover", sender: self)
self.popMsg = "同步中..."
return
}
performSegueWithIdentifier("Popover", sender: self)
self.popMsg = "设置中..."
bongSDK.enableXNote(!self.notifying)
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath == 1 {
cell.textLabel!.text = self.notifying ? "停止时间通知" : "开启事件通知"
}
}
//MARK: - bongSDKDelegate
func bongSDKDataFetchStatusDidChange(status: bongSDKDataFetchStatus, error: NSError!) {
if (error != nil) {
NSLog("bongSDKDataFetchStatusDidChange error: %@", error)
self.popCtlr?.dismissViewControllerAnimated(true, completion: nil)
return
}
NSLog("bongSDKDataFetchStatusDidChange status %d", status.rawValue)
if (status == bongSDKDataFetchStatus.Succeed ||
status == bongSDKDataFetchStatus.FetchNothing) {
self.popCtlr?.dismissViewControllerAnimated(true, completion: nil)
return
}
}
func bongSDKDidSwitchXNote(error: NSError!) {
self.popCtlr?.dismissViewControllerAnimated(true, completion: nil)
if ((error) != nil) {
NSLog("bongSDKDidSwitchXNote error: %@", error);
self.notifying = false;
} else {
self.notifying = !self.notifying;
}
self.tableView.reloadData();
}
func bongSDKDidUpdateXNote(type: bongSDKXNoteType, error: NSError!) {
if ((error) != nil) {
NSLog("bongSDKDidUpdateXNote error: %@", error);
return;
}
NSLog("bongSDKDidUpdateXNote type %td", type.rawValue);
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "Popover" {
self.popCtlr = segue.destinationViewController as? ActivityIndicatorViewController
let naviRect = self.navigationController!.navigationBar.frame
self.popCtlr!.popoverPresentationController!.sourceRect = CGRectMake(self.view.frame.width / 2 , self.view.frame.height/2 - naviRect.height, 1, 1)
self.popCtlr!.popoverPresentationController!.delegate = self
self.popCtlr!.message = self.popMsg
}
}
// MARK: - UIPopoverPresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
return !scanning
}
}
<file_sep>//
// ActivityTableViewController.swift
// BongMe
//
// Created by Ryan on 1/17/16.
// Copyright © 2016 J.A.V.I.S. All rights reserved.
//
import UIKit
class ActivityTableViewController: UITableViewController,bongSDKDelegate,UIPopoverPresentationControllerDelegate {
private var popCtlr:ActivityIndicatorViewController?
private var popMsg:String = ""
private var scanning:Bool = false
private var resultText:String = ""
@IBOutlet weak var resultTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
bongSDK.addDelegate(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
bongSDK.removeDelegate(self)
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.row == 0 {
performSegueWithIdentifier("Popover", sender: self)
self.popMsg = "获取中..."
bongSDK.fetchbongActivityWithDate(NSDate(), isDetailed: indexPath.row == 1)
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 && indexPath.row == 1 {
self.resultTextView.text = self.resultText
}
}
// MARK: bongSDKDelegate
func bongSDKDidFetchBriefActivity(activity:BriefActivity, error:NSError!) {
self.popCtlr!.dismissViewControllerAnimated(true) {
if (error != nil) {
self.resultText = error.description;
} else {
self.resultText = NSString(format: "摘要数据:\n\n%@", activity.description) as String
}
}
self.resultTextView.text = self.resultText
}
func bongSDKDidFetchDetailedDayActivity(activity:DetailedDayActivity, error:NSError!) {
self.popCtlr!.dismissViewControllerAnimated(true) {
if (error != nil) {
self.resultText = error.description;
} else {
self.resultText = NSString(format: "详细数据:\n\n%@", activity.description) as String
}
}
self.resultTextView.text = self.resultText
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "Popover" {
self.popCtlr = segue.destinationViewController as? ActivityIndicatorViewController
let naviRect = self.navigationController!.navigationBar.frame
self.popCtlr!.popoverPresentationController!.sourceRect = CGRectMake(self.view.frame.width / 2 , self.view.frame.height/2 - naviRect.height, 1, 1)
self.popCtlr!.popoverPresentationController!.delegate = self
self.popCtlr!.message = self.popMsg
}
}
// MARK: - UIPopoverPresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
return !scanning
}
}
<file_sep>//
// AuthorizeTableViewController.swift
// BongMe
//
// Created by Ryan on 1/16/16.
// Copyright © 2016 J.A.V.I.S. All rights reserved.
//
import UIKit
class AuthorizeTableViewController: UITableViewController, bongSDKDelegate, UIPopoverPresentationControllerDelegate {
// @IBOutlet weak var actIndicator: UIActivityIndicatorView!
private var fetchingBongID = false
private var popCtlr:ActivityIndicatorViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
bongSDK.addDelegate(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
bongSDK.removeDelegate(self)
}
// MARK: - bongSDKDelegate
func bongSDKDidAutherize(errorCode: bongSDKErrorCode) {
NSLog("bongSDKDidAuthorize errorCode: @%", errorCode.rawValue)
}
func bongSDKDidFetchbongID(errorCode: bongSDKErrorCode) {
fetchingBongID = false
popCtlr?.dismissViewControllerAnimated(true) {
let alert = UIAlertController(title: (errorCode == bongSDKErrorCode.None) ? "获取成功" : "获取失败", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
}
NSLog("bongSDKDidFetchbongID errorCode: %d", errorCode.rawValue);
return
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.row == 0 {
if bongSDK.isAuthorizationValid() {
let alert = UIAlertController(title: "已授权", message: "再次授权前, 先清空已有授权信息", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(okAction)
presentViewController(alert, animated: true, completion: nil)
return
}
bongSDK.requestAuthorization()
return
}
if indexPath.row == 1 {
if bongSDK.isbongIDValid() {
let alert = UIAlertController(title: "已获取 bong ID", message: "再次授权前, 先清空已有 ID 信息", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(okAction)
presentViewController(alert, animated: true, completion: nil)
return
}
fetchingBongID = true
performSegueWithIdentifier("Popover", sender: self)
bongSDK.requestbongID()
return
}
bongSDK.clearAuthorization()
bongSDK.clearbongID()
let alert = UIAlertController(title: "已清空", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(okAction)
presentViewController(alert, animated: true, completion: nil)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "Popover" {
self.popCtlr = segue.destinationViewController as? ActivityIndicatorViewController
let naviRect = self.navigationController!.navigationBar.frame
self.popCtlr!.popoverPresentationController!.sourceRect = CGRectMake(self.view.frame.width / 2 , self.view.frame.height/2 - naviRect.height, 1, 1)
self.popCtlr!.popoverPresentationController!.delegate = self
self.popCtlr!.message = "获取中..."
}
}
// MARK: - UIPopoverPresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
return !fetchingBongID
}
}
<file_sep>//
// BongIITableViewController.swift
// BongMe
//
// Created by Ryan on 1/16/16.
// Copyright © 2016 J.A.V.I.S. All rights reserved.
//
import UIKit
class BongIITableViewController: UITableViewController, bongSDKDelegate,UIPopoverPresentationControllerDelegate {
private var scanning:Bool = false
private var syncWhenScanned:Bool = false
@IBOutlet weak var switcher: UISwitch!
private var popCtlr:ActivityIndicatorViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
bongSDK.addDelegate(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
bongSDK.removeDelegate(self)
bongSDK.stop()
}
@IBAction func switchValueChanged(sender: UISwitch) {
self.syncWhenScanned = sender.on
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.row == 0 {
if self.scanning {
bongSDK.stop()
} else {
bongSDK.run()
}
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath == 0 {
cell.textLabel!.text = self.scanning ? "停止扫描" : "开始扫描"
return
}
cell.textLabel!.text = "扫描到即同步"
cell.textLabel!.backgroundColor = UIColor.clearColor()
self.switcher.setOn(self.syncWhenScanned, animated: true)
}
// MARK: - bongSDKDelegate
func bongSDKDidRun(code: bongSDKErrorCode) {
NSLog("bongSDKDidRun code: %d", code.rawValue)
if code == bongSDKErrorCode.None {
self.scanning = true
self.tableView.reloadData()
}
}
func bongSDKDidStop(code: bongSDKErrorCode) {
NSLog("bongSDKDidStop code: %d", code.rawValue)
if code == bongSDKErrorCode.None {
self.scanning = false
self.tableView.reloadData()
}
}
func bongSDKDidScanbongIIWithPressYesKey(touchType: YESKeyTouchType) {
NSLog("bongSDKDidScanbongIIWithPressYesKey touchType: %d", touchType.rawValue)
if self.syncWhenScanned {
let now = NSDate()
bongSDK.fetchbongDataWithStartDate(now.dateByAddingTimeInterval(-60*30), endDate: now)
performSegueWithIdentifier("Popover", sender: self)
}
}
func bongSDKDataFetchStatusDidChange(status: bongSDKDataFetchStatus, error: NSError!) {
if (error != nil) {
NSLog("bongSDKDataFetchStatusDidChange error: %@", error)
popCtlr?.dismissViewControllerAnimated(true,completion: nil)
return
}
NSLog("bongSDKDataFetchStatusDidChange status %d", status.rawValue)
if status == bongSDKDataFetchStatus.Succeed || status == bongSDKDataFetchStatus.FetchNothing {
popCtlr?.dismissViewControllerAnimated(true,completion: nil)
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "Popover" {
self.popCtlr = segue.destinationViewController as? ActivityIndicatorViewController
let naviRect = self.navigationController!.navigationBar.frame
self.popCtlr!.popoverPresentationController!.sourceRect = CGRectMake(self.view.frame.width / 2 , self.view.frame.height/2 - naviRect.height, 1, 1)
self.popCtlr!.popoverPresentationController!.delegate = self
self.popCtlr!.message = "同步中..."
}
}
// MARK: - UIPopoverPresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
return !scanning
}
}
<file_sep># BongMe
> Start Date: @20160114
## Framework Installation
### CocoaPods
> https://cocoapods.org
This project use CocoaPods to handle framework dependancy.
Here is a tutorial to using CocoaPods wit Swift:
> http://www.raywenderlich.com/97014
#### OAuthSwift
> https://github.com/OAuthSwift/OAuthSwift
``` ruby
# Podfile
platform :ios, '8.0'
use_frameworks!
pod "OAuthSwift", "~> 0.5.0"
```
#### JSONModel
> https://github.com/icanzilb/JSONModel
>
> NB: **Swift works in a different way under the hood than Objective-C. Therefore I can't find a way to re-create JSONModel in Swift. JSONModel in Objective-C works in Swift apps through CocoaPods or as an imported Objective-C library.**
``` ruby
# Podfile
pod 'JSONModel'
```
#### bongSDK
> https://github.com/Ginshell/bongSDK-iOS
1. `TARGET`->`BongMe`->`General`->`Linked Frameworks and Libraries` 添加`bongSDK.framework`
2. 添加`BongMe-Bridging-Header.h`
3. `TARGET`->`BongMe`->`Build Settings`->`Other Linker Flags` 加入`$(OTHER_LDFLAGS) -ObjC`
4. `TARGET`->`BongMe`->`Build Settings`->`Objective-C Bridging Header` 添加刚才创建的头文件`BongMe/BongMe-Bridging-Header.h`, 注意文件路径.
5. 测试. 在`ViewController`的`viewDidLoad()`中添加
``` swift
NSLog("bongSDK version: %@", bongSDK.version())
```
运行APP, 查看控制台输出:
```
$ 2016-01-16 11:53:02.617 BongMe[16494:7577534] bongSDK version: 2.0.2
```<file_sep>//
// ActivityIndicatorViewController.swift
// BongMe
//
// Created by Ryan on 1/17/16.
// Copyright © 2016 J.A.V.I.S. All rights reserved.
//
import UIKit
class ActivityIndicatorViewController: UIViewController {
@IBOutlet weak var lblMessage: UILabel!
@IBOutlet weak var actIndicator: UIActivityIndicatorView!
var message:String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.lblMessage.text = self.message
self.lblMessage.sizeToFit()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
self.actIndicator.startAnimating()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(true)
self.actIndicator.stopAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// MainTableViewController.swift
// BongMe
//
// Created by Ryan on 1/15/16.
// Copyright © 2016 J.A.V.I.S. All rights reserved.
//
import UIKit
class MainTableViewController: UITableViewController, bongSDKDelegate {
@IBOutlet weak var lblAuthorization: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NSLog("bongSDK version: %@", bongSDK.version())
// bongSDK 配置,此处替换成自己的配置
bongSDK.setAppID("1419735044202", appSecret: "558860f5ba4546ddb31eafeee11dc8f4", appKey: "7ae31974a95fec07ad3d047c075b11745d8ce989")
// 设置开发者环境,即服务器为测试环境
bongSDK.enableDebugMode(true)
bongSDK.addDelegate(self)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
lblAuthorization.text = bongSDK.isAuthorizationValid() ? (bongSDK.isbongIDValid() ? "已授权并获取 bong ID" : "已授权") : "授权"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
//MARK: - bongSDKDelegate
func bongSDKDidSwitchXNote(error: NSError!) {
NSLog("error: %@", error)
}
func bongSDKDidUpdateXNote(type: bongSDKXNoteType, error: NSError!) {
NSLog("type: %td errorL %@", type.rawValue, error)
}
//MARK: - Naigation
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if identifier == "Authorize" {
return true
}
if !bongSDK.isAuthorizationValid() {
let alert = UIAlertController(title: "无效授权信息", message: "请进行授权操作", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(okAction)
presentViewController(alert, animated: true, completion: nil)
return false
}
if identifier == "bongII" || identifier == "bongX" {
if !bongSDK.isbongIDValid() {
let alert = UIAlertController(title: "无效 bong ID", message: "请先获取 bong ID", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(okAction)
presentViewController(alert, animated: true, completion: nil)
return false
}
let productID = bongSDK.bongProductID()
if (identifier == "bongII" && productID != bongSDKProductID.IDTwo) || (identifier == "bongX" && (productID != bongSDKProductID.IDX && productID != bongSDKProductID.IDXX)) {
let alert = UIAlertController(title: "不兼容设备", message: "请先绑定正确的设备", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(okAction)
presentViewController(alert, animated: true, completion: nil)
return false
}
}
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if ((sender?.isKindOfClass(UITableViewCell)) != nil) {
let cell = sender as! UITableViewCell
self.tableView.deselectRowAtIndexPath(self.tableView.indexPathForCell(cell)!, animated: true)
}
}
}
| fbc73a0808de42112bd4cacb8504b0e378801e73 | [
"Swift",
"C",
"Ruby",
"Markdown"
] | 9 | C | nasa1008/BongMe | fa4f0c996ba519bc45cc28d9365e8531d7d0e3e2 | 74e3570878ec9e1881748ed7243eae60e5e46948 | |
refs/heads/master | <file_sep>class PokemonsController < ApplicationController
def index
pokemons = Pokemon.all
render json: PokemonSerializer.new(pokemons).to_serialized_json
end
def show
pokemon = Pokemon.find_by(id: params[:id])
render json: PokemonSerializer.new(pokemon).to_serialized_json
end
def destroy
pokemon = Pokemon.find_by(id: params[:id])
pokemon.destroy
end
end
<file_sep>class TrainersController < ApplicationController
def index
trainers = Trainer.all
render json: TrainerSerializer.new(trainers).to_serialized_json
end
def show
trainer = Trainer.find_by(id: params[:id])
render json: TrainerSerializer.new(trainer).to_serialized_json
end
def create
trainer = Trainer.find_by(id: params[:trainer_id])
newPokemon = Pokemon.create(nickname: Faker::Name.first_name, species: Faker::Games::Pokemon.name, trainer_id: params[:trainer_id])
render json: TrainerSerializer.new(trainer).to_serialized_json
end
end
<file_sep>const BASE_URL = "http://localhost:3000"
const TRAINERS_URL = `${BASE_URL}/trainers`
const POKEMONS_URL = `${BASE_URL}/pokemons`
document.addEventListener("DOMContentLoaded", function(){
fetchTrainers();
})
function fetchTrainers(){
fetch(TRAINERS_URL)
.then(resp => resp.json())
.then(trainersObj =>
renderTrainers(trainersObj));
}
function renderTrainers(trainersObj){
const main = document.querySelector('main')
main.innerHTML = ""
trainersObj.forEach(function(elem){
let cardDiv = document.createElement('div')
cardDiv.classList.add('card')
cardDiv.setAttribute('data-id', elem.id)
let addbutton = document.createElement('button')
addbutton.setAttribute('data-trainer-id', elem.id)
addbutton.innerText = "ADD POKEMON"
addbutton.addEventListener('click', event => {
addPokemon(event);
});
let p = document.createElement('p')
p.innerHTML = elem.name
const ul = document.createElement('ul')
elem.pokemons.forEach(function(pokemon){
let li = document.createElement('li')
li.innerText = pokemon.species + '('+ pokemon.nickname + ')'
let releasebtn = document.createElement('button')
releasebtn.innerText = "RELEASE"
releasebtn.classList.add("release")
releasebtn.setAttribute('data-pokemon-id', pokemon.id)
releasebtn.addEventListener('click', event => {
releasePokemon(event)
});
li.append(releasebtn)
ul.append(li)
})
cardDiv.append(addbutton,p,ul)
main.appendChild(cardDiv)
});
}
function releasePokemon(event) {
return fetch(`${POKEMONS_URL}/${event.target.dataset.pokemonId}`, {
method: "DELETE",
})
.then(response => console.log(response))
.then(fetchTrainers);
}
function addPokemon(event) {
if (event.target.nextSibling.nextSibling.childElementCount < 6) {
createPokemon(event)
} else {
alert("You cannot add more than 6 to a team")}
}
function createPokemon(event){
return fetch(TRAINERS_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify({
trainer_id: event.srcElement.dataset.trainerId
})
})
.then(response => response.json())
.then(fetchTrainers);
}
<file_sep>class PokemonSerializer
def initialize(pokemon)
@pokemon = pokemon
end
def to_serialized_json
options = {
include: {
trainer: {
only: [:name, :id]
},
},
only: [:id, :nickname, :species],
}
@pokemon.to_json(options)
end
end
| 7f9e53dae2755463c5d1d6264f0b906a71992fce | [
"JavaScript",
"Ruby"
] | 4 | Ruby | MDAM182/js-rails-as-api-pokemon-teams-project-v-000 | f1dce8901ddaa9c6f928a689d56856b4e9973f3e | cb018f8ee661732b151d5ffb997cc268c0c122be | |
refs/heads/master | <file_sep> $(document).ready(function(){
// Jazz'd up v2 is in http://codepen.io/ronniechong/pen/PzVKOo
const items = [
"I'm hungry.",
"I'm foolish."
]
const app = document.getElementById('app')
let count = 0
let index = 0
let typingEffect = () => {
let text = items[index]
if (count < text.length) {
setTimeout(() => {
app.innerHTML += text[count]
count++
typingEffect()
}, Math.floor(Math.random(10) * 100))
} else {
count = 0;
index = (index + 1 < items.length) ? index + 1 : 0
setTimeout(() => {
app.innerHTML = ''
typingEffect()
}, 1500)
}
}
typingEffect()
});
<file_sep># iamlabib.github.io
myweb
| cded5ef6b98c900cbe555f39af83a42344e1a75e | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | iamlabib/iamlabib.github.io | 0ccd82571c9f18e7bec19ccf7481aabd931e5d77 | 09ea3672a58cfc875279fa704fd1eac9d937deb8 | |
refs/heads/main | <file_sep>import React from 'react';
function About() {
return (
<React.Fragment>
<h1>About</h1>
<p>
This is a simple to do list app created as part of self learning react
framework. we can add, delete or mark todos as completed or not, since
this is just a web app in react and dont have a back end or data base
the todos will be refershed after we refresh the web page.
</p>
</React.Fragment>
);
}
export default About;
| b45d2906dbb5cb9c61f380a29439efd98a6739c7 | [
"JavaScript"
] | 1 | JavaScript | nithin-j/simple-todo | da1b5cca96f3e834a11d150c5ac1dfbf06461daa | 7e02dc987ea80b7b2ab5d36c15f9dacd929ea71c | |
refs/heads/master | <file_sep><?php
/**
* TF 용 커스텀 컨트롤러
*
*/
namespace controllers\internal;
use Slim\Http\Request;
use Slim\Http\Response;
use Psr\Container\ContainerInterface;
use libraries\{
log\LogMessage,
constant\CommonConst,
constant\ErrorConst,
constant\TFConst,
util\CommonUtil,
util\RedisUtil,
util\AwsUtil,
http\Http
};
class TravelForest extends SynctreeInternal
{
private $guzzleOpt = [
'verify' => false,
'timeout' => CommonConst::HTTP_RESPONSE_TIMEOUT,
'connect_timeout' => CommonConst::HTTP_CONNECT_TIMEOUT,
'headers' => [
'User-Agent' => 'Synctree/2.1 - ' . APP_ENV
]
];
private $noWait = true;
private $maxTryCount = 10;
private $redisSession = TFConst::REDIS_TF_SESSION;
private $recipients = [];
public function __construct(ContainerInterface $ci)
{
parent::__construct($ci);
$this->recipients[] = '<EMAIL>';
if (APP_ENV === APP_ENV_STAGING || APP_ENV === APP_ENV_PRODUCTION) {
$this->recipients[] = '<EMAIL>';
}
}
public function template(Request $request, Response $response)
{
$results = $this->jsonResult;
try {
} catch (\Exception $ex) {
$results = [
'result' => false,
'data' => [
'message' => $this->_getErrorMessage($ex),
]
];
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* 모상품 목록 가지고 오기
*
* @param Request $request
* @param Response $response
*
* @return Response
*/
public function getProducts(Request $request, Response $response)
{
$products = null;
try {
if (false === ($products = RedisUtil::getData($this->redis, TFConst::REDIS_TF_PRODUCTS_REDIS_KEY, $this->redisSession))) {
throw new \Exception('', ErrorConst::ERROR_RDB_NO_DATA_EXIST);
}
$results = $products;
} catch (\Exception $ex) {
$results = [
'result' => ErrorConst::FAIL_STRING,
'data' => [
'message' => $this->_getErrorMessage($ex),
]
];
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* 자상품의 번호로 모상품의 IDX를 리턴
*
* @param Request $request
* @param Response $response
* @param $args
*
* @return Response
*/
public function getProductIdx(Request $request, Response $response, $args)
{
$productIdx = null;
try {
$params = $args;
if (false === CommonUtil::validateParams($params, ['productTypeKey'])) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
$redisKey = TFConst::REDIS_TF_SUB_PRODUCT_REDIS_KEY . '_' . $params['productTypeKey'];
if (false === ($product = RedisUtil::getData($this->redis, $redisKey, $this->redisSession))) {
throw new \Exception('', ErrorConst::ERROR_RDB_NO_DATA_EXIST);
}
$productIdx = $product['product_idx'];
$results = [
'productKey' => $productIdx
];
} catch (\Exception $ex) {
$results = [
'result' => ErrorConst::FAIL_STRING,
'data' => [
'message' => $this->_getErrorMessage($ex),
]
];
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* 모상품의 상세정보 리턴
*
* @param Request $request
* @param Response $response
*
* @return Response
*/
public function getProduct(Request $request, Response $response)
{
$productDetail = [];
try {
$params = $request->getAttribute('params');
if (false === CommonUtil::validateParams($params, ['product'], true)) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
$product = $params['product'];
$dateSearchFlag = false;
if ( ! is_array($product) || empty($product) ) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
$tourOptions = [];
$priceArr = [];
$priceAdultArr = [];
$priceChildArr = [];
$paxArr = [];
$saleAvailableTour = [];
$pDate = [];
if (isset($params['fromDate']) && isset($params['toDate']) && ! empty($params['fromDate']) && ! empty($params['toDate'])) {
$dateSearchFlag = true;
$fromDate = date('Y-m-d', strtotime($params['fromDate']));
$toDate = date('Y-m-d', strtotime($params['toDate']));
$fromDateTime = new \DateTime($fromDate);
$toDateTime = new \DateTime($toDate);
$dateDiff = date_diff($fromDateTime, $toDateTime);
$dateDiff = $dateDiff->days + 1;
if ($dateDiff > 366) {
throw new \Exception('', ErrorConst::ERROR_RDB_NO_DATA_EXIST);
}
$period = new \DatePeriod($fromDateTime, new \DateInterval('P1D'), $toDateTime->modify('+1 day'));
foreach ($period as $key => $value) {
$pDate[] = $value->format('Y-m-d');
}
}
switch (true) {
// 자상품 상세
case (isset($params['productTypeKey']) && ! empty($params['productTypeKey']) && $params['productTypeKey'] !== 'null') :
if ( ! isset($params['productTypes']) || empty($params['productTypes'])) {
break;
}
$voucherUse = '';
$refundPolicy = null;
$isNoneRefund = false; // 환불불가
$tourItemFlag = false;
$transferItemFlag = false;
// 투어 상품과 픽업 상품이 나뉨
switch (true) {
case (isset($product['tour_item']) && is_array($product['tour_item'])) :
$tourItemFlag = true;
break;
case (isset($product['tour_items']) && is_array($product['tour_items'])) :
if (false === ($tourIdx = array_search($params['productTypeKey'],
array_column($product['tour_items'], 'tour_item_idx')))
) {
throw new \Exception('', ErrorConst::ERROR_RDB_NO_DATA_EXIST);
}
$tourItemFlag = true;
$product['tour_item'] = $product['tour_items'][$tourIdx];
break;
case (isset($product['transfer_item']) && is_array($product['transfer_item'])) :
$transferItemFlag = true;
break;
case (isset($product['transfer_items']) && is_array($product['transfer_items'])) :
if (false === ($tourIdx = array_search($params['productTypeKey'],
array_column($product['transfer_items'], 'transfer_item_idx')))
) {
throw new \Exception('', ErrorConst::ERROR_RDB_NO_DATA_EXIST);
}
$transferItemFlag = true;
$product['transfer_item'] = $product['transfer_items'][$tourIdx];
break;
}
if (true === $tourItemFlag) { // 투어 아이템일 경우
$tourItem = $product['tour_item'];
$productDetail['productTypeKey'] = $tourItem['tour_item_idx'];
$productDetail['title'] = $tourItem['tour_ko'];
$productDetail['title'] = $this->_replaceSpecialChar($productDetail['title']);
$productDetail['durationDays'] = (int)$tourItem['duration_day'] ?? 0;
$productDetail['durationHours'] = (int)$tourItem['duration_hour'] ?? 0;
$productDetail['durationMins'] = (int)$tourItem['duration_minute'] ?? 0;
$productDetail['minAdultAge'] = 0;
$productDetail['maxAdultAge'] = 99;
$productDetail['hasChildPrice'] = false;
$productDetail['minChildAge'] = 0;
if (isset($tourItem['tour_suppliers'])) {
foreach ($tourItem['tour_suppliers'] as $tsp) {
// 바우처 정보
//$voucherUse .= ($tsp['note_content'] ?? '');
$voucherUse .= ($tsp['voucher_content'] ?? '');
// 환불규정
$refundPolicy = $tsp['cancel_content'] ?? '';
// 환불 불가여부
$isNoneRefund = (isset($tsp['cancel_type_cd']) && $tsp['cancel_type_cd'] == 'refund') ? false : true;
// 최대/최소 가격 , 최소/최대 여행자수
foreach ($tsp['tour_seasons'] as $ts) {
// 날짜 검색이면
if (true === $dateSearchFlag) {
if ( ! empty($pDate)) {
$weeks = explode( ',', $ts['season_week']);
$tourDateFrom = date('Y-m-d', strtotime($ts['season_date_from']));
$tourDateTo = date('Y-m-d', strtotime($ts['season_date_to']));
$tourSaleDateTo = date('Y-m-d',
strtotime($ts['season_date_to'] . ' -' . $ts['sale_day_to'] . ' days'));
foreach ($pDate as $sDate) {
$tmpDate = date('Y-m-d', strtotime($sDate));
$tmpWeek = date('w', strtotime($sDate));
if ($tmpDate >= $tourDateFrom && $tmpDate <= $tourDateTo && in_array($tmpWeek, $weeks)) {
$saleAvailableTour[] = [
'tour_season_idx' => $ts['tour_season_idx'],
'from_to' => $tmpDate,
];
}
}
}
}
// 가격/여행객 수
foreach ($ts['tour_prices'] as $tps) {
switch ($tps['sale_unit_ko']) {
case '성인' :
$productDetail['minAdultAge'] = (int)$tps['customer_age_from'];
$productDetail['maxAdultAge'] = (int)(($tps['customer_age_to'] > 0) ? $tps['customer_age_to'] : 99) ;
$priceArr[] = $tps['sale_price'] ?? 0;
$priceAdultArr[] = $tps['sale_price'] ?? 0;
break;
case '아동' :
$productDetail['hasChildPrice'] = true;
$productDetail['minChildAge'] = (int)$tps['customer_age_from'];
$priceChildArr[] = $tps['sale_price'] ?? 0;
break;
case '유아' :
$productDetail['allowInfants'] = true;
$productDetail['maxInfantAge'] = (int)$tps['customer_age_to'];
$priceChildArr[] = $tps['sale_price'] ?? 0;
break;
}
if (isset($tps['customer_count_from']) && !empty($tps['customer_count_from'])) {
$paxArr[] = (int)$tps['customer_count_from'];
}
if (isset($tps['customer_count_to'])) {
$paxArr[] = (int)$tps['customer_count_to'];
}
}
}
// 자상품 옵션
if (isset($tsp['tour_options']) && ! empty($tsp['tour_options'])) {
foreach ($tsp['tour_options'] as $to) {
if ( ! isset($to['tour_fields']) || empty($to['tour_fields'])) {
continue;
}
foreach ($to['tour_fields'] as $tf) {
$tmpOpt = [];
$tmpOpt['id'] = $tf['field_id'];
$tmpOpt['target'] = 1;
$tmpOpt['name'] = $tf['field_label'];
$tmpOpt['type'] = (isset($tf['field_items']) && ! empty($tf['field_items'])) ? 1 : 4;
$tmpOpt['required'] = (isset($tf['field_items']) && ! empty($tf['field_items'])) ? true : false;
$tmpOpt['price'] = 0;
if (isset($tf['field_items']) && ! empty($tf['field_items']) && is_array($tf['field_items'])) {
$tmpOpt['item'] = [];
foreach ($tf['field_items'] as $fl) {
$tmpOpt['item'][] = [
'label' => $fl['item_text'],
'value' => $fl['item_value'],
];
}
}
$tourOptions[] = $tmpOpt;
}
}
}
}
}
} elseif (true === $transferItemFlag) {
$tourItem = $product['transfer_item'];
$productDetail['productTypeKey'] = $tourItem['transfer_item_idx'];
$productDetail['title'] = $tourItem['transfer_ko'];
$productDetail['title'] = $this->_replaceSpecialChar($productDetail['title']);
$productDetail['durationDays'] = 0;
$productDetail['durationHours'] = 0;
$productDetail['durationMins'] = 0;
$productDetail['minAdultAge'] = 0;
$productDetail['maxAdultAge'] = 99;
$productDetail['hasChildPrice'] = false;
$productDetail['minChildAge'] = 0;
$priceChildArr = [0];
if (isset($tourItem['transfer_suppliers'])) {
foreach ($tourItem['transfer_suppliers'] as $tsp) {
// 바우처 정보
$voucherUse .= ($tsp['voucher_content'] ?? '');
// 환불규정
$refundPolicy = $tsp['cancel_content'] ?? '';
// 환불 불가여부
$isNoneRefund = (isset($tsp['cancel_type_cd']) && $tsp['cancel_type_cd'] == 'refund') ? false : true;
// 최대/최소 가격
foreach ($tsp['transfer_seasons'] as $ts) {
// 날짜 검색이면
if (true === $dateSearchFlag) {
if ( ! empty($pDate)) {
$tourDateFrom = date('Y-m-d', strtotime($ts['season_date_from']));
$tourDateTo = date('Y-m-d', strtotime($ts['season_date_to']));
$tourSaleDateTo = date('Y-m-d',
strtotime($ts['season_date_to'] . ' -' . $ts['sale_day_to'] . ' days'));
foreach ($pDate as $sDate) {
$tmpDate = date('Y-m-d', strtotime($sDate));
if ($tmpDate >= $tourDateFrom && $tmpDate <= $tourDateTo) {
$saleAvailableTour[] = [
'from_to' => $tmpDate,
];
foreach ($ts['transfer_prices'] as $tps) {
$priceArr[] = $priceAdultArr[] = ($tps['sale_price'] ?? 0);
// 픽업 서비스인 경우 옵션에 상품정보를 넣는다.
$tourOptions[] = [
'id' => $tps['transfer_price_idx'],
'target' => 1,
'name' => $tps['vehicle_type_ko'] . '-' . $tps['customer_count_to'] . '인',
'type' => 3,
'required' => true,
'price' => (int)($tps['sale_price'] ?? 0)
];
}
}
}
}
} else {
$paxArr = [];
$paxArr[] = 1;
foreach ($ts['transfer_prices'] as $tps) {
$priceArr[] = $priceAdultArr[] = $tps['sale_price'] ?? 0;
if (isset($tps['customer_count_to'])) {
$paxArr[] = (int)$tps['customer_count_to'];
}
// 픽업 서비스인 경우 옵션에 상품정보를 넣는다.
$tourOptions[] = [
'id' => $tps['transfer_price_idx'],
'target' => 1,
'name' => $tps['vehicle_type_ko'] . '-' . $tps['customer_count_to'] . '인',
'type' => 3,
'required' => true,
'price' => (int)($tps['sale_price'] ?? 0)
];
}
}
}
// 자상품 옵션
if (isset($tsp['transfer_option']['transfer_fields']) && ! empty($tsp['transfer_option']['transfer_fields'])) {
$tFields = $tsp['transfer_option']['transfer_fields'];
foreach ($tFields as $tf) {
$tmpOpt = [];
$tmpOpt['id'] = $tf['field_id'];
$tmpOpt['target'] = 1;
$tmpOpt['name'] = $tf['field_label'];
$tmpOpt['type'] = (isset($tf['field_items']) && ! empty($tf['field_items'])) ? 1 : 4;
$tmpOpt['required'] = true;
$tmpOpt['price'] = 0;
if (isset($tf['field_items']) && ! empty($tf['field_items']) && is_array($tf['field_items'])) {
$tmpOpt['item'] = [];
foreach ($tf['field_items'] as $fl) {
$tmpOpt['item'][] = [
'label' => $fl['item_text'] ?? '',
'value' => $fl['item_value'] ?? '',
];
}
}
$tourOptions[] = $tmpOpt;
}
}
}
}
}
$productDetail['minPax'] = ( ! empty($paxArr)) ? min($paxArr) : 0;
$productDetail['maxPax'] = ( ! empty($paxArr)) ? max($paxArr) : 0;
$tourOptions = array_merge($tourOptions, [
[
'id' => 'arrival_date',
'target' => 1,
'name' => '현지 도착일',
'type' => 6,
'required' => true,
'price' => 0
],
[
'id' => 'arrival_time',
'target' => 1,
'name' => '현지 도착시간',
'type' => 10,
'required' => true,
'price' => 0
],
[
'id' => 'duration_date',
'target' => 1,
'name' => '여행일수',
'type' => 3,
'required' => true,
'price' => 0
],
[
'id' => 'participant_sex',
'target' => 2,
'name' => '성별',
'type' => 1,
'required' => true,
'price' => 0,
'item' => [
[
'label' => 'Male',
'value' => 'Male'
],
[
'label' => 'Female',
'value' => 'Female'
]
]
],
[
'id' => 'participant_name',
'target' => 2,
'name' => '이름',
'type' => 4,
'required' => true,
'price' => 0
],
[
'id' => 'participant_birth',
'target' => 2,
'name' => '생년월일',
'type' => 6,
'required' => true,
'price' => 0
],
[
'id' => 'participant_nation',
'target' => 2,
'name' => '국가',
'type' => 4,
'required' => false,
'price' => 0
],
]);
$productDetail['hasSeniorPrice'] = false;
$productDetail['hasTeenagerPrice'] = false;
$productDetail['minTeenagerAge'] = 0;
$productDetail['allowInfants'] = $productDetail['allowInfants'] ?? false;
$productDetail['maxInfantAge'] = $productDetail['maxInfantAge'] ?? 0;
$productDetail['instantConfirmation'] = false;
$productDetail['voucherType'] = 'E_VOUCHER';
$productDetail['voucherUse'] = $this->_replaceSpecialChar($voucherUse);
//$productDetail['meetingTime'] = $tourItem[''];
//$productDetail['meetingLocation'] = $tourItem[''];
$productDetail['isNonRefundable'] = $isNoneRefund;
$productDetail['refundPolicy'] = $refundPolicy;
//$productDetail['validityType'] = $tourItem[''];
//$productDetail['validityDate'] = $tourItem[''];
$productDetail['minPrice'] = ( ! empty($priceArr)) ? (int)min($priceArr) : 0;
$productDetail['options'] = $tourOptions;
// 날짜검색이라면 데이터 초기화
if (true === $dateSearchFlag) {
$productDetail = [];
}
if (empty($priceAdultArr)) {
$priceAdultArr = [0];
}
if (empty($priceChildArr)) {
$priceChildArr = [0];
}
// 검색 날짜내에 가능한 상품이 있으면
if ( ! empty($saleAvailableTour)) {
foreach ($saleAvailableTour as $st) {
$productDetail[] = [
'date' => $st['from_to'],
'available' => true,
'price' => [
'adult' => (int)max($priceAdultArr),
'child' => (int)max($priceChildArr),
'senior' => 0,
'teenager' => 0,
]
];
}
}
break;
// 자상품 리스트 반환
case (isset($params['productTypes']) && ! empty($params['productTypes']) && $params['productTypes'] !== 'null') :
if ( ! is_array($params['product'])) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
if (isset($product['tour_items']) && is_array($product['tour_items'])) {
foreach ($product['tour_items'] as $row) {
$productDetail[] = [
'productTypeKey' => $row['tour_item_idx'],
'title' => $this->_replaceSpecialChar($row['tour_ko']),
];
}
} elseif (isset($product['transfer_items']) && is_array($product['transfer_items'])) {
foreach ($product['transfer_items'] as $row) {
$productDetail[] = [
'productTypeKey' => $row['transfer_item_idx'],
'title' => $this->_replaceSpecialChar($row['transfer_ko']),
];
}
}
break;
// 모상품 상세
default :
if ( ! is_array($params['product']) || empty($product) ) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
$desc = ( ! empty($product['comment_content'])) ? $product['comment_content'] : ($product['description_content'] ?? null);
$desc = $this->_replaceSpecialChar(strip_tags($desc));
$productTitle = $product['product_ko'] ?? '';
$productDetail = [
'productKey' => $product['product_idx'],
'updatedAt' => $product['modify_datetime'] ?? null,
'title' => $this->_replaceSpecialChar($productTitle),
'description' => $desc ?? null,
'highlights' => $product['highlight_content'] ?? null,
'additionalInfo' => strip_tags($product['comment_content'] ?? null) ?? null,
];
// 여정
$productDetail['itinerary'] = '';
if ( ! empty($product['tour_itineraries']) && is_array($product['tour_itineraries'])) {
foreach ($product['tour_itineraries'] as $ti) {
$productDetail['itinerary'] .= ($ti['itinerary_daytime'] ?? null) . PHP_EOL;
$productDetail['itinerary'] .= ($ti['itinerary_route'] ?? null) . PHP_EOL;
$productDetail['itinerary'] .= ($ti['itinerary_content'] ?? null) . PHP_EOL . PHP_EOL;
}
$productDetail['itinerary'] = strip_tags($productDetail['itinerary']);
}
$productDetail['latitude'] = 0;
$productDetail['longitude'] = 0;
if (isset($product['tour_maps'][0]) && ! empty($product['tour_maps'][0])) {
$productDetail['latitude'] = (float)$product['tour_maps'][0]['point_latitude'];
$productDetail['longitude'] = (float)$product['tour_maps'][0]['point_longitude'];
}
$productDetail['currency'] = 'KRW';
// 여행상품 최소가
$priceArr = [];
if ( ! empty($product['tour_items']) && is_array($product['tour_items'])) {
foreach ($product['tour_items'] as $ti) {
if ( ! isset($ti['tour_suppliers']) || empty($ti['tour_suppliers'])) {
continue;
}
foreach ($ti['tour_suppliers'] as $tsp) {
foreach ($tsp['tour_seasons'] as $ts) {
foreach ($ts['tour_prices'] as $tps) {
$priceArr[] = $tps['sale_price'] ?? 0;
}
}
}
}
}
// 픽업상품 최소가
if ( ! empty($product['transfer_items']) && is_array($product['transfer_items'])) {
foreach ($product['transfer_items'] as $ti) {
if ( ! isset($ti['transfer_suppliers']) || empty($ti['transfer_suppliers'])) {
continue;
}
foreach ($ti['transfer_suppliers'] as $tsp) {
foreach ($tsp['transfer_seasons'] as $ts) {
foreach ($ts['transfer_prices'] as $tps) {
$priceArr[] = $tps['sale_price'] ?? 0;
}
}
}
}
}
$productDetail['minPrice'] = ( ! empty($priceArr)) ? ((int)min($priceArr)) : 0;
$redisKey = TFConst::REDIS_TF_PRODUCT_REDIS_KEY . '_' . $product['product_idx'];
if (false !== ($productRedis = RedisUtil::getData($this->redis, $redisKey, $this->redisSession))) {
$productDetail['location'] = TFConst::TS_AREA_CODE[$productRedis['area_idx']][TFConst::TS_AREA_LOC_TXT] ?? null;
$productDetail['city'] = TFConst::TS_AREA_CODE[$productRedis['area_idx']][TFConst::TS_AREA_CITY_TXT] ?? null;
}
$productDetail['photos'] = [];
if (isset($product['image_urls']) && ! empty($product['image_urls'])) {
foreach ($product['image_urls'] as $iu) {
$productDetail['photos'][] = ['path' => $iu];
}
}
}
$results = $productDetail;
} catch (\Exception $ex) {
$results = [
'result' => ErrorConst::FAIL_STRING,
'data' => [
'message' => $this->_getErrorMessage($ex),
]
];
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* TF 상품 배치
* Redis에 무조건 덮어쓴다.
*
* @param Request $request
* @param Response $response
*
* @return Response
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function setProductsBatch(Request $request, Response $response)
{
$products = null;
$batchProducts = [];
$productDetail = [];
$startDate = CommonUtil::getDateTime();
$startTime = CommonUtil::getMicroTime();
$startTimeStamp = $startDate . ' ' . $startTime;
$updateWebHook = 'http://tnaapi.tourvis.com/apiary/common/webhook/v1/product';
$updatedParentProduct = [];
$updatedChildProduct = [];
try {
$params = $request->getAttribute('params');
if (!isset($params['execute']) || empty($params['execute'])) {
throw new \Exception('Batch Non-excute');
}
// 지역 정보
$redisKey = TFConst::REDIS_TF_AREA_REDIS_KEY;
$targetUrl = TFConst::TF_URL . TFConst::TF_GET_AREA_URI;
$eventKey = $this->_getRedisEventKey(['action'=>'batch_get_areas', 'datetime' => $startTimeStamp]);
$this->guzzleOpt['query'] = ['event_key' => $eventKey];
$areaResult = Http::httpRequest($targetUrl, $this->guzzleOpt);
if (!empty($areaResult['errors'])) {
LogMessage::error(json_encode($areaResult['errors'], JSON_UNESCAPED_UNICODE));
throw new \Exception('Batch Area Error!!');
}
$areas = $areaResult['areas'];
$this->_setRedis($redisKey, $areas);
foreach ($areas as $row) {
// 지역별 모상품 리스트
$areaIdx = $row['area_idx'];
$redisKey = TFConst::REDIS_TF_PRODUCTS_REDIS_KEY . '_' . $areaIdx;
if ( ! array_key_exists($areaIdx, TFConst::TS_AREA_CODE)) {
LogMessage::error('NOT EXIST TF area_idx :: ' . $areaIdx);
continue;
}
LogMessage::info('TF area_idx :: ' . $areaIdx);
$eventKey = $this->_getRedisEventKey(['action' => 'batch_get_products', 'area_idx' => $areaIdx, 'datetime' => $startTimeStamp]);
$this->guzzleOpt['query'] = ['event_key' => $eventKey];
$targetUrl = TFConst::TF_URL . TFConst::TF_GET_AREA_URI . '/' . $areaIdx . '/products';
$areaProducts = Http::httpRequest($targetUrl, $this->guzzleOpt);
if (!empty($areaProducts['errors'])) {
LogMessage::error($targetUrl);
LogMessage::error(json_encode($areaProducts['errors'], JSON_UNESCAPED_UNICODE));
continue;
}
$areaProducts = $areaProducts['products'];
$this->_setRedis($redisKey, $areaProducts);
try {
// 지역별 모상품 리스트 루프
foreach ($areaProducts as $aps) {
$productIdx = $aps['product_idx'];
$updateFlag = false;
// 모상품 상세정보
LogMessage::info('TF product_idx :: ' . $productIdx);
$redisKey = TFConst::REDIS_TF_PRODUCT_REDIS_KEY . '_' . $productIdx;
$targetUrl = TFConst::TF_URL . TFConst::TF_GET_PRODUCTS_URI . '/' . $productIdx;
$eventKey = $this->_getRedisEventKey(['action'=>'batch_get_product', 'product_idx' => $productIdx, 'datetime' => $startTimeStamp]);
$this->guzzleOpt['query'] = ['event_key' => $eventKey];
$productDetail = Http::httpRequest($targetUrl, $this->guzzleOpt);
if (!empty($productDetail['errors'])) {
LogMessage::error($targetUrl);
LogMessage::error(json_encode($productDetail['errors'], JSON_UNESCAPED_UNICODE));
continue;
}
$productDetail = $productDetail['product'];
$productDetail['area_idx'] = $areaIdx;
// 배치때 날짜 비교
try {
if (false !== ($productDetailOld = RedisUtil::getData($this->redis, $redisKey, $this->redisSession))) {
LogMessage::info('product_old :: ' . $productIdx . ' - date :: ' . ($productDetailOld['modify_datetime'] ?? null));
if ($productDetailOld['modify_datetime'] <> $productDetail['modify_datetime']) {
$updateFlag = true;
$updatedParentProduct[] = [
'productKey' => $productIdx,
'updateAt' => $productDetail['modify_datetime'],
];
}
}
} catch (\Exception $eee) {
LogMessage::error('modify_datetime diff error');
LogMessage::info('product :: ' . $productIdx . ' - date :: ' . ($productDetail['modify_datetime'] ?? null));
}
$this->_setRedis($redisKey, $productDetail);
try {
$tourItemIdx = 0;
$productSubDetail = null;
// 투어상품 상세정보
if (isset($productDetail['tour_items']) && is_array($productDetail['tour_items'])) {
foreach ($productDetail['tour_items'] as $ti) {
$tourItemIdx = $ti['tour_item_idx'];
LogMessage::info('TF tour_item_idx :: ' . $tourItemIdx);
$productSubDetail = [
'area_idx' => $areaIdx,
'product_idx' => $productIdx,
'tour_item' => $ti
];
$redisKey = TFConst::REDIS_TF_SUB_PRODUCT_REDIS_KEY . '_' . $tourItemIdx;
$this->_setRedis($redisKey, $productSubDetail);
}
}
// 픽업상품 상세정보
if (isset($productDetail['transfer_items']) && is_array($productDetail['transfer_items'])) {
foreach ($productDetail['transfer_items'] as $ti) {
$tourItemIdx = $ti['transfer_item_idx'];
LogMessage::info('TF transfer_item_idx :: ' . $tourItemIdx);
$productSubDetail = [
'area_idx' => $areaIdx,
'product_idx' => $productIdx,
'transfer_item' => $ti
];
$redisKey = TFConst::REDIS_TF_SUB_PRODUCT_REDIS_KEY . '_' . $tourItemIdx;
$this->_setRedis($redisKey, $productSubDetail);
}
}
if ($updateFlag === true) {
$updatedChildProduct[$productDetail['product_idx']][] = $tourItemIdx;
}
} catch (\Exception $ee) {
LogMessage::error('SubProduct Detail Error :: ' . $areaIdx . '-' . $productIdx . '-' . $tourItemIdx);
LogMessage::error($ee->getMessage());
LogMessage::info(json_encode($tourItemIdx, JSON_UNESCAPED_UNICODE));
}
if (!array_key_exists($productIdx, $batchProducts)) {
$batchProducts[$productIdx] = $productIdx;
$products[] = [
'productKey' => $productIdx,
'updatedAt' => $productDetail['modify_datetime'] ?? null,
'title' => $this->_replaceSpecialChar($aps['product_ko'])
];
}
sleep(1);
}
} catch (\Exception $e) {
LogMessage::error('Product Detail Error :: ' . $productIdx . '_' . $areaIdx);
LogMessage::error($e->getMessage());
LogMessage::info(json_encode($productDetail, JSON_UNESCAPED_UNICODE));
}
sleep(1);
}
$this->_setRedis(TFConst::REDIS_TF_PRODUCTS_REDIS_KEY, $products);
$results = $products;
} catch (\Exception $ex) {
$results = [
'result' => ErrorConst::FAIL_STRING,
'data' => [
'message' => $this->_getErrorMessage($ex),
]
];
}
if (!empty($updatedParentProduct)) {
try {
foreach ($updatedParentProduct as $key => $pidx) {
try {
$data = [
'productKey' => $pidx['productKey'],
'updateType' => 'UPDATE',
'updateAt' => $pidx['updateAt'],
];
$command = 'curl -X ';
$command .= '-d "' . http_build_query($data) . '" ';
$command .= $updateWebHook . ' -s > /dev/null 2>&1 &';
passthru($command);
foreach ($updatedChildProduct[$pidx['productKey']] as $cidx) {
try {
$data = [
'productKey' => $pidx['productKey'],
'productTypeKey' => $cidx,
'updateType' => 'UPDATE',
'updateAt' => $pidx['updateAt']
];
$command = 'curl -X ';
$command .= '-d "' . http_build_query($data) . '" ';
$command .= $updateWebHook . ' -s > /dev/null 2>&1 &';
LogMessage::debug('curl command :: ' . $command);
passthru($command);
} catch (\Exception $e) {
LogMessage::error('Child Product Webhook Error :: ' . $cidx);
}
}
} catch (\Exception $ex) {
LogMessage::error('Product Webhook Error :: ' . $pidx['productKey']);
}
}
} catch (\Exception $eex) {
LogMessage::error('Product Webhook Error');
}
}
$endTime = CommonUtil::getMicroTime();
LogMessage::info('TF Batch Start :: ' . $startTimeStamp);
LogMessage::info('TF Batch End :: ' . CommonUtil::getDateTime() . ' ' . $endTime);
LogMessage::info('TF Batch Runtime :: ' . ($endTime - $startTime));
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* 특정 상품의 배치
*
* @param Request $request
* @param Response $response
* @param $args
*
* @return Response
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function setProductBatch(Request $request, Response $response, $args)
{
$productIdx = $args['product_idx'] ?? null;
$areaIdx = $args['area_idx'] ?? null;
try {
if (false === CommonUtil::validateParams($args, ['product_idx', 'area_idx'], true)) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
// 모상품 상세정보
$redisKey = TFConst::REDIS_TF_PRODUCT_REDIS_KEY . '_' . $productIdx;
//if (false === ($productDetail = RedisUtil::getData($this->redis, $redisKey, $this->redisSession))) {
LogMessage::info('TF product_idx :: ' . $productIdx);
$targetUrl = TFConst::TF_URL . TFConst::TF_GET_PRODUCTS_URI . '/' . $productIdx;
$productDetail = Http::httpRequest($targetUrl, $this->guzzleOpt);
$productDetail['area_idx'] = $areaIdx;
$this->_setRedis($redisKey, $productDetail);
//}
try {
$tourItemIdx = 0;
//자상품 상세정보
if (isset($productDetail['tour_items']) && is_array($productDetail['tour_items'])) {
foreach ($productDetail['tour_items'] as $ti) {
$tourItemIdx = $ti['tour_item_idx'];
$redisKey = TFConst::REDIS_TF_SUB_PRODUCT_REDIS_KEY . '_' . $tourItemIdx;
if (false === ($productSubDetail = RedisUtil::getData($this->redis, $redisKey, $this->redisSession))) {
LogMessage::info('TF tour_item_idx :: ' . $tourItemIdx);
$productSubDetail[] = [
'area_idx' => $areaIdx,
'product_idx' => $productIdx,
'tour_item' => $ti
];
$this->_setRedis($redisKey, $productSubDetail);
}
}
}
// 픽업 상품
if (isset($productDetail['transfer_items']) && is_array($productDetail['transfer_items'])) {
foreach ($productDetail['transfer_items'] as $ti) {
$tourItemIdx = $ti['transfer_item_idx'];
$redisKey = TFConst::REDIS_TF_SUB_PRODUCT_REDIS_KEY . '_' . $tourItemIdx;
if (false === ($productSubDetail = RedisUtil::getData($this->redis, $redisKey, $this->redisSession))) {
LogMessage::info('TF tour_item_idx :: ' . $tourItemIdx);
$productSubDetail[] = [
'area_idx' => $areaIdx,
'product_idx' => $productIdx,
'transfer_item' => $ti
];
$this->_setRedis($redisKey, $productSubDetail);
}
}
}
} catch (\Exception $ee) {
LogMessage::error('SubProduct Detail Error :: ' . $productIdx . '-' . $tourItemIdx . '_' . $areaIdx);
LogMessage::error($ee->getMessage());
LogMessage::info(json_encode($ti, JSON_UNESCAPED_UNICODE));
}
$products[] = [
'productKey' => $productIdx,
'updatedAt' => $productDetail['modify_datetime'] ?? null,
'title' => $productDetail['product_ko']
];
$results = [
'result' => ErrorConst::SUCCESS_STRING,
];
} catch (\Exception $ex) {
LogMessage::error('Product Detail Error :: ' . $productIdx . '_' . $areaIdx);
LogMessage::error($ex->getMessage());
LogMessage::info(json_encode($productDetail, JSON_UNESCAPED_UNICODE));
$results = [
'result' => ErrorConst::FAIL_STRING,
'data' => [
'message' => $this->_getErrorMessage($ex),
]
];
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* 타이드 스퀘어 권한 체크
*
* @param Request $request
* @param Response $response
*
* @return Response
*/
public function authCheck(Request $request, Response $response)
{
try {
$params = $request->getAttribute('params');
if (false === CommonUtil::validateParams($params, ['supplierCode'])) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
if ($params['supplierCode'] !== TFConst::TS_SUPPLIER_CODE) {
LogMessage::error('TS supplierCode :: ' . $params['supplierCode']);
throw new \Exception('', ErrorConst::ERROR_RDB_APP_AUTH_FAIL);
}
$accessToken = '';
$headers = $request->getHeaders();
// supplier code
if (isset($headers['HTTP_AUTHORIZATION']) && ! empty($headers['HTTP_AUTHORIZATION'])) {
$accessToken = str_replace('Bearer ', '', $headers['HTTP_AUTHORIZATION'][0]);
} elseif (isset($headers['HTTP_ACCESS_TOKEN']) && ! empty($headers['HTTP_ACCESS_TOKEN'])) {
$accessToken = $headers['HTTP_ACCESS_TOKEN'][0];
}
if ($accessToken !== TFConst::TS_ACCESS_TOKEN) {
LogMessage::error('TS Auth Fail - AccessToken :: ' . $accessToken);
throw new \Exception('', ErrorConst::ERROR_RDB_APP_AUTH_FAIL);
}
// supplier code
if ( ! isset($headers['HTTP_SUPPLIER_CODE'])) {
LogMessage::error('TS Auth Fail - Supplier Code is not exist');
throw new \Exception('', ErrorConst::ERROR_RDB_APP_AUTH_FAIL);
}
if ($headers['HTTP_SUPPLIER_CODE'][0] !== TFConst::TS_SUPPLIER_CODE) {
LogMessage::error('TS Auth Fail - Supplier Code :: ' . $accessToken);
throw new \Exception('', ErrorConst::ERROR_RDB_APP_AUTH_FAIL);
}
$results = [
'result' => true
];
} catch (\Exception $ex) {
$results = [
'result' => false,
'data' => [
'message' => $this->_getErrorMessage($ex),
]
];
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* * 예약진행
*
* @param Request $request
* @param Response $response
*
* 1. Tour(인원별): tour_item_idx, tour_season_idx, tour_customer_idx
* 2. Transfer(차량별): transfer_item_idx, transfer_price_idx
* 3. 공통사항: 이용일, 여행자정보, 옵션 등
*
* @return Response
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function addBooking(Request $request, Response $response)
{
$adultAmount = 0;
$childrenAmount = 0;
$totalAmount = 0;
try {
$params = $request->getAttribute('params');
if (false === CommonUtil::validateParams($params, ['product', 'adults', 'children', 'arrivalDate', 'selectTimeslot'], true)) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
$product = $params['product'];
$result = [
'product_idx' => (int)$product['product_idx'],
'sub_product_idx' => (int)$params['productTypeKey'],
'customer_salutation' => $params['customer_salutation'],
'customer_firstName' => $params['customer_firstName'],
'customer_lastName' => $params['customer_lastName'],
'customer_email' => $params['customer_email'],
'customer_phone' => $params['customer_phone'],
'arrival_date' => $params['arrivalDate'],
'select_time_slot' => $params['selectTimeslot'] ?? '00:00',
'message' => $params['message'] ?? '',
'options' => $params['options'] ?? [],
'adults' => (int)($params['adults'] ?? 0),
'children' => (int)($params['children'] ?? 0),
];
if (!isset($params['options']['perBooking'])) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
if (!isset($params['options']['perPax'])) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
$arrivalDate = date('Ymd', strtotime($params['arrivalDate']));
foreach ($params['options']['perBooking'] as $pBooking) {
if ($pBooking['id'] === 'arrival_date') {
$arrivalDate = date('Ymd', strtotime($pBooking['value']));
break;
};
}
// 투어 상품과 픽업 상품이 나뉨
switch (true) {
case (isset($product['tour_items']) && is_array($product['tour_items'])) : // 투어상품
if (false === ($tourIdx = array_search($params['productTypeKey'], array_column($product['tour_items'], 'tour_item_idx')))) {
throw new \Exception('', ErrorConst::ERROR_RDB_NO_DATA_EXIST);
}
$tourItem = $product['tour_items'][$tourIdx];
$tourItemIdx = (int)$tourItem['tour_item_idx'];
$tourSuppliers = $tourItem['tour_suppliers'] ?? null;
$result['tour_item_idx'] = $tourItemIdx;
$tourCustomIdxs = [];
if (empty($tourSuppliers)) {
throw new \Exception('', ErrorConst::ERROR_RDB_NO_DATA_EXIST);
}
foreach ($tourSuppliers as $ts) {
if (isset($ts['tour_seasons']) && is_array($ts['tour_seasons'])) {
foreach ($ts['tour_seasons'] as $tss) {
// 날짜 비교
if (false === $this->_validRangeDate($tss['season_date_from'], $tss['season_date_to'], $arrivalDate)) {
throw new \Exception('예약 생성에 실패하였습니다. - 날짜 오류 (' . $arrivalDate . ', '. $tss['season_date_from'] . ', '. $tss['season_date_to'] .')');
}
$weeks = explode( ',', $tss['season_week']);
$tmpWeek = date('w', strtotime($arrivalDate));
if (! in_array($tmpWeek, $weeks)) {
throw new \Exception('예약 생성에 실패하였습니다. - 날짜(요일) 오류' . $tmpWeek . ' ' . json_encode($tmpWeek));
}
$result['tour_season_idx'] = (int)$tss['tour_season_idx'];
// 성인 가격
if ( ! empty($params['adults'])) {
$adultsCount = $params['adults'];
do {
$adultsCount--;
foreach ($tss['tour_prices'] as $tp) {
if ($tp['sale_unit_ko'] === '성인') {
$tourCustomIdxs[] = (int)$tp['tour_customer_idx'];
$adultAmount += (int)$tp['sale_price'];
$totalAmount += (int)$tp['sale_price'];
}
}
} while (0 < $adultsCount);
}
// 아동 가격
if ( ! empty($params['children'])) {
$childrenCount = $params['children'];
do {
$childrenCount--;
foreach ($tss['tour_prices'] as $tp) {
if ($tp['sale_unit_ko'] === '아동') {
$tourCustomIdxs[] = (int)$tp['tour_customer_idx'];
$childrenAmount += (int)$tp['sale_price'];
$totalAmount += (int)$tp['sale_price'];
}
}
} while (0 < $childrenCount);
}
}
}
}
$result['tour_customer_idx'] = $tourCustomIdxs;
break;
case (isset($product['transfer_items']) && is_array($product['transfer_items'])) : // 픽업상품
if (false === ($tourIdx = array_search($params['productTypeKey'],
array_column($product['transfer_items'], 'transfer_item_idx')))
) {
throw new \Exception('', ErrorConst::ERROR_RDB_NO_DATA_EXIST);
}
$tourItem = $product['transfer_items'][$tourIdx];
$tourItemIdx = $tourItem['transfer_item_idx'];
$result['transfer_item_idx'] = (int)$tourItemIdx;
$tourSuppliers = $tourItem['transfer_suppliers'] ?? null;
if (empty($tourSuppliers)) {
throw new \Exception('', ErrorConst::ERROR_RDB_NO_DATA_EXIST);
}
foreach ($tourSuppliers as $ts) {
if (isset($ts['transfer_seasons']) && is_array($ts['transfer_seasons'])) {
foreach ($ts['transfer_seasons'] as $tss) {
// 날짜 비교
if (false === $this->_validRangeDate($tss['season_date_from'], $tss['season_date_to'], $arrivalDate)) {
throw new \Exception('예약 생성에 실패하였습니다. - 날짜 오류');
}
$weeks = explode( ',', $tss['season_week']);
$tmpWeek = date('w', strtotime($arrivalDate));
if (! in_array($tmpWeek, $weeks)) {
throw new \Exception('예약 생성에 실패하였습니다. - 날짜 오류');
}
if ( ! isset($params['options']['perBooking'][0]['id'])) {
LogMessage::error('No Option data');
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
$perBookingOption = $params['options']['perBooking'] ?? null;
$transferInfo = array_shift($perBookingOption);
$transferPriceIdx = $transferInfo['id'];
$totalAmount += (int)($transferInfo['price'] ?? 0);
if (false === ($tourIdx = array_search($transferPriceIdx, array_column($tss['transfer_prices'], 'transfer_price_idx')))) {
continue;
}
$result['transfer_price_idx'] = (int)$transferPriceIdx;
$result['options']['perBooking'] = $perBookingOption;
}
}
}
break;
}
$result['amount'] = [
'adult' => (int)$adultAmount,
'child' => (int)$childrenAmount,
'total' => (int)$totalAmount
];
$redisArr = ['action' => 'addBooking', 'datetime' => date('Y-m-d H:i:s')];
$redisArr = array_merge($redisArr, $result);
$eventKey = $this->_getRedisEventKey($redisArr);
$this->guzzleOpt['form_params'] = ['event_key' => $eventKey];
$this->guzzleOpt['allow_redirects'] = true;
$targetUrl = TFConst::TF_BOOK_ADD_URL;
$addResult = Http::httpRequest($targetUrl, $this->guzzleOpt, CommonConst::REQ_METHOD_POST);
LogMessage::error('addBooking Result ::' . json_encode($addResult, JSON_UNESCAPED_UNICODE));
if (empty($addResult)) {
throw new \Exception('예약 생성에 실패하였습니다. - TF 통신 오류');
}
if (!empty($addResult['errors'])) {
throw new \Exception('예약 생성에 실패하였습니다.');
}
if (!isset($addResult['book']['book_cd']) || empty($addResult['book']['book_cd'])) {
throw new \Exception('예약 생성에 실패하였습니다.');
}
$bookIdx = $addResult['book']['book_cd'];
switch ($addResult['book']['book_status_cd']) {
case TFConst::TF_BOOK_CD_INS :
case TFConst::TF_BOOK_CD_ORD :
case TFConst::TF_BOOK_CD_REQ :
$status = TFConst::RESERVE_STATUS_RESV;
break;
default :
throw new \Exception('예약 생성에 실패하였습니다. - 진행할 수 있는 예약이 아닙니다.');
}
$results = [
'result' => [
'success' => true,
'status' => $status,
'bookingKey' => $bookIdx,
'partnerReference' => $params['partnerReference'] ?? null,
'totalAmount' => $totalAmount,
]
];
$this->_setBookingRedis($bookIdx, [
'success' => true,
'status' => $status,
'bookingKey' => $bookIdx,
'partnerReference' => $params['partnerReference'] ?? null,
'totalAmount' => $totalAmount,
'tf_result' => $addResult
]);
$this->_saveBookingLog($bookIdx, $results);
} catch (\Exception $ex) {
$results = [
'result' => [
'success' => false,
'status' => TFConst::STATUS_ERROR,
'bookingKey' => null,
'totalAmount' => $totalAmount,
'message' => $this->_getErrorMessage($ex, true, [
'subject' => '부킹 생성에러',
'body' => $ex->getMessage(),
]),
]
];
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* 예약 진행
*
* @param Request $request
* @param Response $response
* @param $args
*
* @return Response
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function proceedBooking(Request $request, Response $response, $args)
{
try {
if (false === CommonUtil::validateParams($args, ['bookingKey'], true)) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
$redisDb = CommonConst::REDIS_MESSAGE_SESSION;
$redisKey = TFConst::REDIS_TF_BOOKING_REDIS_KEY . '_' . $args['bookingKey'];
if (false === ($bookingStatusRedis = RedisUtil::getData($this->redis, $redisKey, $redisDb))) {
throw new \Exception(ErrorConst::ERROR_DESCRIPTION_ARRAY[ErrorConst::ERROR_RDB_NO_DATA_EXIST]);
}
if ($bookingStatusRedis['status'] !== TFConst::RESERVE_STATUS_RESV) {
throw new \Exception('이미 예약 진행중 이거나 진행 가능한 주문이 아닙니다.');
}
$this->guzzleOpt['json'] = ['event_key' => $this->_getRedisEventKey([
'action' => 'proceedBooking',
'bookingKey' => $args['bookingKey'],
'datetime' => date('Y-m-d H:i:s'),
])];
$this->guzzleOpt['allow_redirects'] = true;
$targetUrl = TFConst::TF_BOOK_PROC_URL . '/' . $args['bookingKey'];
$procResult = Http::httpRequest($targetUrl, $this->guzzleOpt, CommonConst::REQ_METHOD_PATCH);
if (empty($procResult)) {
throw new \Exception('예약 진행에 실패하였습니다. - TF 서버오류');
}
if (!empty($procResult['errors'])) {
throw new \Exception('예약 진행에 실패하였습니다.');
}
if (!isset($procResult['book']['book_cd']) || empty($procResult['book']['book_cd'])) {
throw new \Exception('예약 진행에 실패하였습니다.');
}
$results = [
'success' => true,
'status' => TFConst::RESERVE_STATUS_WAIT,
'bookingKey' => $procResult['book']['book_cd'],
'partnerReference' => $bookingStatusRedis['partnerReference'] ?? null,
'totalAmount' => (int)$procResult['book']['sale_price'],
'refundAmount' => (int)$procResult['book']['sale_price'],
'tf_result' => $procResult
];
$this->_setBookingRedis($results['bookingKey'], $results);
$this->_saveBookingLog($results['bookingKey'], $results);
unset($results['refundAmount']);
unset($results['tf_result']);
} catch (\Exception $ex) {
$results = [
'success' => false,
'bookingKey' => $args['bookingKey'],
'partnerReference' => null,
'totalAmount' => 0,
'message' => $ex->getMessage(),
];
$body = json_encode($results, JSON_UNESCAPED_UNICODE) . PHP_EOL;
$body .= $ex->getMessage();
$this->_getErrorMessage($ex, true, ['subject' => '부킹 진행에러', 'body' => $body]);
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* 예약 취소
*
* @param Request $request
* @param Response $response
* @param $args
*
* @return Response
*/
public function cancelBooking(Request $request, Response $response, $args)
{
try {
if (false === CommonUtil::validateParams($args, ['bookingKey'], true)) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
$redisDb = CommonConst::REDIS_MESSAGE_SESSION;
$redisKey = TFConst::REDIS_TF_BOOKING_REDIS_KEY . '_' . $args['bookingKey'];
if (false === ($bookingStatusRedis = RedisUtil::getData($this->redis, $redisKey, $redisDb))) {
throw new \Exception('', ErrorConst::ERROR_RDB_NO_DATA_EXIST);
}
if ($bookingStatusRedis['status'] === TFConst::RESERVE_STATUS_CNCL || $bookingStatusRedis['status'] === TFConst::CANCEL_STATUS_DENY) {
throw new \Exception('예약 취소 가능한 주문이 아닙니다.');
}
if ($bookingStatusRedis['status'] === TFConst::CANCEL_STATUS_WAIT) {
throw new \Exception('예약 취소 진행중 입니다.');
}
$subject = 'TF 예약취소 요청';
$body = '<h1>TF 예약취소 요청</h1>'
. '<p>주문 키 : ' . $bookingStatusRedis['bookingKey'] . '</p>'
. '<p>주문금액 : ' . number_format($bookingStatusRedis['totalAmount']) . '</p>'
. '<p>환불금액 : ' . number_format($bookingStatusRedis['refundAmount']) . '</p>'
;
if (false === AwsUtil::sendEmail($this->recipients, $subject, $body)) {
throw new \Exception(null, ErrorConst::ERROR_SEND_EMAIL);
}
$results = [
'success' => true,
'status' => TFConst::CANCEL_STATUS_WAIT,
'bookingKey' => $args['bookingKey'],
'partnerReference' => $bookingStatusRedis['partnerReference'] ?? null,
'totalAmount' => $bookingStatusRedis['totalAmount'],
'refundAmount' => $bookingStatusRedis['refundAmount'],
'tf_result' => $bookingStatusRedis['tf_result']
];
$this->_setBookingRedis($args['bookingKey'], $results);
$this->_saveBookingLog($args['bookingKey'], $results);
unset($results['tf_result']);
unset($results['totalAmount']);
unset($results['partnerReference']);
} catch (\Exception $ex) {
$results = [
'success' => false,
'status' => TFConst::STATUS_ERROR,
'bookingKey' => $args['bookingKey'],
'refundAmount' => 0,
'message' => $this->_getErrorMessage($ex),
];
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* 예약 상태 확인
*
* @param Request $request
* @param Response $response
* @param $args
*
* @return Response
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function checkBookingStatus(Request $request, Response $response, $args)
{
try {
if (false === CommonUtil::validateParams($args, ['bookingKey'], true)) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
$redisDb = CommonConst::REDIS_MESSAGE_SESSION;
$redisKey = TFConst::REDIS_TF_BOOKING_REDIS_KEY . '_' . $args['bookingKey'];
$bookingDataType = 'redis';
if (false === ($bookingData = RedisUtil::getData($this->redis, $redisKey, $redisDb))) {
$this->guzzleOpt['query'] = [
'event_key' => $this->_getRedisEventKey([
'action' => 'checkBookingStatus',
'bookingKey' => $args['bookingKey'],
'datetime' => date('Y-m-d H:i:s'),
])
];
$this->guzzleOpt['allow_redirects'] = true;
$targetUrl = TFConst::TF_BOOK_PROC_URL . '/' . $args['bookingKey'];
$bookingData = Http::httpRequest($targetUrl, $this->guzzleOpt);
$bookingDataType = 'travel';
if (!empty($bookingData['errors'])) {
throw new \Exception('예약 조회에 실패하였습니다.');
}
}
$redisStatus = $bookingData['status'] ?? null;
$tfResult = (isset($bookingData['tf_result'])) ? $bookingData['tf_result'] : $bookingData;
$bookingStatus = (isset($bookingData['tf_result'])) ? $bookingData['tf_result']['book'] : $bookingData['book'];
if (!isset($bookingStatus['book_status_cd']) || empty($bookingStatus['book_status_cd'])) {
throw new \Exception('예약 조회에 실패하였습니다.');
}
$results = [
'success' => true,
'status' => $redisStatus ?? $this->_getStatusCode($bookingStatus['book_status_cd']),
'bookingKey' => $bookingStatus['book_cd'],
'partnerReference' => $bookingStatus['partnerReference'] ?? null,
'totalAmount' => $bookingStatus['sale_price'] ?? 0,
'refundAmount' => $bookingStatus['sale_price'] ?? 0,
'tf_result' => $tfResult
];
$this->_setBookingRedis($bookingStatus['book_cd'], $results);
unset($results['tf_result']);
} catch (\Exception $ex) {
$results = [
'success' => false,
'status' => TFConst::STATUS_ERROR,
'bookingKey' => $args['bookingKey'],
'message' => $this->_getErrorMessage($ex, true, [
'subject' => '부킹 확인 에러',
'body' => $ex->getMessage(),
]),
];
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* 트레블포레스트에서 주문관련 업데이트시 호출할 Webhook
*
* @param Request $request
* @param Response $response
* @param $args
*
* @return Response
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function bookingUpdate(Request $request, Response $response, $args)
{
$updateType = null;
$oldStatus = null;
try {
if (false === CommonUtil::validateParams($args, ['bookingKey', 'updateType'], true)) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
// confirm || cancel || close
switch ($args['updateType']) {
case TFConst::TF_BOOK_CD_CFM :
case TFConst::TF_BOOK_CD_CCL :
case TFConst::TF_BOOK_CD_CLS :
break;
default :
throw new \Exception(null, ErrorConst::ERROR_STEP_FAIL);
}
$redisDb = CommonConst::REDIS_MESSAGE_SESSION;
$redisKey = TFConst::REDIS_TF_BOOKING_REDIS_KEY . '_' . $args['bookingKey'];
if (false === ($bookingStatusRedis = RedisUtil::getData($this->redis, $redisKey, $redisDb))) {
throw new \Exception(ErrorConst::ERROR_DESCRIPTION_ARRAY[ErrorConst::ERROR_RDB_NO_DATA_EXIST]);
}
$oldStatus = $bookingStatusRedis['status'];
$updateType = $this->_getStatusCode($args['updateType']);
if (empty($updateType)) {
throw new \Exception(null, ErrorConst::ERROR_STEP_FAIL);
}
$this->guzzleOpt['query'] = ['event_key' => $this->_getRedisEventKey([
'action' => 'bookingUpdate',
'updateType' => $args['updateType'],
'bookingKey' => $args['bookingKey'],
'datetime' => date('Y-m-d H:i:s'),
])];
$this->guzzleOpt['allow_redirects'] = true;
$statusTargetUrl = TFConst::TF_BOOK_PROC_URL . '/' . $args['bookingKey'];
$bookingStatus = Http::httpRequest($statusTargetUrl, $this->guzzleOpt, CommonConst::REQ_METHOD_GET);
$curStatus = $bookingStatus['book']['book_status_cd'];
if ($args['updateType'] != $curStatus) {
throw new \Exception(null, ErrorConst::ERROR_STEP_FAIL);
}
// 미리 CONFIRM 상태로 업데이트
$bookingStatusRedis['status'] = $updateType;
$this->_setBookingRedis($args['bookingKey'], $bookingStatusRedis);
// Webhook
if (APP_ENV == APP_ENV_PRODUCTION || APP_ENV === APP_ENV_STAGING) {
$targetUrl = (APP_ENV === APP_ENV_PRODUCTION) ? TFConst::TS_WEBHOOK_URL : TFConst::TS_WEBHOOK_DEV_URL ;
$targetUrl .= TFConst::TS_RESERVE_WEBHOOK_URI;
$sleep = (APP_ENV === APP_ENV_PRODUCTION) ? 300 : 3;
$maxTryCount = (APP_ENV === APP_ENV_PRODUCTION) ? $this->maxTryCount : 3;
$tryCount = 0;
$updateParams = [
'bookingKey' => $args['bookingKey'],
'updateType' => $updateType,
'updateAt' => date('Y-m-d H:i:s')
];
do {
$result = $this->_webhook($targetUrl, $updateParams, $this->noWait, $sleep);
$tryCount++;
} while ($result['success'] === false && $tryCount <= $maxTryCount);
if ( ! isset($result['success']) || true !== $result['success']) {
$bookingStatusRedis['status'] = $oldStatus;
$this->_setBookingRedis($args['bookingKey'], $bookingStatusRedis);
throw new \Exception('Webhook Error');
}
}
$results = [
'success' => true,
'status' => $updateType,
'bookingKey' => $bookingStatus['book']['book_cd'],
'partnerReference' => $bookingStatusRedis['partnerReference'] ?? null,
'totalAmount' => $bookingStatus['book']['sale_price'],
'refundAmount' => $bookingStatus['book']['sale_price'],
'tf_result' => $bookingStatus,
];
RedisUtil::setDataWithExpire($this->redis, $redisDb, $redisKey, CommonConst::REDIS_SESSION_EXPIRE_TIME_DAY_7, $results);
$this->_saveBookingLog($args['bookingKey'], $results);
unset($results['tf_result']);
$body = '<h1>주문정보 업데이트 처리요청</h1>' . '<p>주문 키 : ' . $args['bookingKey'] . '</p>' . '<p>' . $args['updateType'] . ' 처리 성공</p>';
} catch (\Exception $ex) {
$body = '<h1>주문정보 업데이트 처리요청</h1>' . '<p>주문 키 : ' . $args['bookingKey'] . '</p>' . '<p>' . $args['updateType'] . ' 처리 실패</p>';
$results = [
'success' => false,
'status' => TFConst::STATUS_ERROR,
'bookingKey' => $args['bookingKey'],
'message' => $this->_getErrorMessage($ex),
];
$this->_saveBookingLog($args['bookingKey'], $results);
}
try {
if (false === AwsUtil::sendEmail($this->recipients, '주문정보 업데이트 결과', $body)) {
throw new \Exception(null, ErrorConst::ERROR_SEND_EMAIL);
}
} catch (\Exception $ex) {
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* 트레블포레스트에서 상품 관련 업데이트시 호출할 Webhook
*
* @param Request $request
* @param Response $response
* @param $args
*
* @return Response
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function productUpdate(Request $request, Response $response, $args)
{
try {
$results = $this->jsonResult;
$tryCount = 0;
$maxTryCount = $this->maxTryCount;
$updateType = null;
$targetUrl = (APP_ENV === APP_ENV_PRODUCTION) ? TFConst::TS_WEBHOOK_URL : TFConst::TS_WEBHOOK_DEV_URL ;
$targetUrl .= TFConst::TS_PRODUCT_WEBHOOK_URI;
$parameters = $request->getAttribute('params');
switch (true) {
case (is_array($parameters) && is_array($args)) :
$params = array_merge($parameters, $args);
break;
case (is_array($parameters) && !empty($parameters)) :
$params = $parameters;
break;
default :
$params = $args;
break;
}
if (false === CommonUtil::validateParams($params, ['productKey', 'updateType'], true)) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
switch ($params['updateType']) {
case 1 : // 상품추가
$updateType = 'ADD';
break;
case 2 : // 상품삭제
$updateType = 'DELETE';
break;
case 3 : // 업데이트
$updateType = 'UPDATE';
break;
}
if (empty($updateType)) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
if ($updateType === 'ADD' || $updateType === 'UPDATE') {
if (false === CommonUtil::validateParams($params, ['title'], true)) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
}
if (false === ($products = RedisUtil::getData($this->redis, TFConst::REDIS_TF_PRODUCTS_REDIS_KEY, $this->redisSession))) {
throw new \Exception('', ErrorConst::ERROR_RDB_NO_DATA_EXIST);
}
// 상품검색
if (false === ($productKeyIdx = array_search($params['productKey'], array_column($products, 'productKey')))) {
if ($updateType !== 'ADD') {
throw new \Exception('', ErrorConst::ERROR_RDB_NO_DATA_EXIST);
}
}
$updateParams = [
'productKey' => $params['productKey'],
'productTypeKey' => $params['productTypeKey'] ?? null,
'updateType' => $updateType,
'updateAt' => date('Y-m-d H:i:s')
];
// Redis 갱신
switch ($params['updateType']) {
case 1 : // 상품추가
$products[] = [
'productKey' => $params['productKey'],
'title' => '',
'updateAt' => date('Y-m-d H:i:s')
];
break;
case 2 : // 상품삭제
unset($products[$productKeyIdx]);
break;
case 3 : // 업데이트
$products[$productKeyIdx] = [
'productKey' => $updateParams['productKey'],
'updateAt' => $updateParams['updateAt'],
'title' => $params['title'] ?? ($products[$productKeyIdx]['title'] ?? ''),
];
break;
}
$this->_setRedis(TFConst::REDIS_TF_PRODUCTS_REDIS_KEY, $products);
// webhook
do {
LogMessage::info('try Count :: ' . $tryCount . ' - noWait :: ' . $this->noWait);
$result = $this->_webhook($targetUrl, $updateParams, $this->noWait);
$tryCount++;
} while ($result['success'] === false && $tryCount <= $maxTryCount);
if ( ! isset($result['success']) || true !== $result['success']) {
throw new \Exception('Webhook Error');
}
} catch (\Exception $ex) {
$results = [
'result' => false,
'data' => [
'message' => $this->_getErrorMessage($ex),
]
];
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
public function getEventKey(Request $request, Response $response)
{
$results = $this->jsonResult;
try {
$results['data']['event_key'] = $this->_getRedisEventKey([], CommonConst::REDIS_SESSION_EXPIRE_TIME_MIN_10);
} catch (\Exception $ex) {
$results = [
'result' => false,
'data' => [
'message' => $this->_getErrorMessage($ex),
]
];
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* @param $targetUrl
* @param $params
* @param bool $noWait
* @param int $sleep
*
* @return array
* @throws \GuzzleHttp\Exception\GuzzleException
*/
private function _webhook($targetUrl, $params, $noWait = true, $sleep = 1)
{
if ($noWait === false) {
sleep($sleep);
}
try {
$webHookOption = [
'verify' => false,
'timeout' => CommonConst::HTTP_RESPONSE_TIMEOUT,
'connect_timeout' => CommonConst::HTTP_CONNECT_TIMEOUT,
'headers' => [
'User-Agent' => 'Synctree/2.1 - ' . APP_ENV,
'Access-Token' => (APP_ENV === APP_ENV_PRODUCTION) ? TFConst::TS_ACCESS_TOKEN : TFConst::TS_DEV_ACCESS_TOKEN,
'Supplier-Code' => TFConst::TS_SUPPLIER_CODE,
'Content-Type' => 'application/json',
'Accept' => 'application/json'
],
'json' => $params,
'allow_redirects' => true,
];
$result = Http::httpRequest($targetUrl, $webHookOption, CommonConst::REQ_METHOD_PUT);
if ( ! isset($result['success']) || true !== $result['success']) {
$this->noWait = false;
$result['success'] = false;
LogMessage::error('Webhook Error :: ' . json_encode($result, JSON_UNESCAPED_UNICODE));
}
} catch (\Exception $ex) {
LogMessage::error('Webhook Error :: ' . $ex->getMessage());
$result['success'] = false;
}
return $result;
}
/**
* 신청 가능 날짜
*
* @param $from
* @param $to
* @param $arrivalDate
*
* @return bool
*/
private function _validRangeDate($from, $to, $arrivalDate)
{
$tourDateFrom = date('Y-m-d', strtotime($from));
$tourDateTo = date('Y-m-d', strtotime($to));
$arrivalDate = date('Y-m-d', strtotime($arrivalDate));
if ($arrivalDate < $tourDateFrom || $arrivalDate > $tourDateTo) {
return false;
}
return true;
}
/**
* 트레블 포레스트 지역 정보 패치
*
* @return array|bool|mixed|string
* @throws \GuzzleHttp\Exception\GuzzleException
*/
private function _getArea()
{
$redisKey = TFConst::REDIS_TF_AREA_REDIS_KEY;
if (false === ($area = RedisUtil::getData($this->redis, $redisKey, $this->redisSession))) {
$targetUrl = TFConst::TF_URL . TFConst::TF_GET_AREA_URI;
$area = Http::httpRequest($targetUrl, $this->guzzleOpt);
$this->_setRedis($redisKey, $area);
}
return $area;
}
/**
*
* @param $redisKey
* @param $data
* @param float|int $expire
*/
private function _setRedis($redisKey, $data, $expire = CommonConst::REDIS_SESSION_EXPIRE_TIME_DAY_2)
{
$redisSession = TFConst::REDIS_TF_SESSION;
try {
//RedisUtil::setDataWithExpire($this->redis, $redisSession, $redisKey, $expire, $data);
RedisUtil::setData($this->redis, $redisSession, $redisKey, $data);
} catch (\Exception $ex) {
LogMessage::error('TravelForest - Set Redis Error (' . $redisKey . ')');
}
}
private function _setBookingRedis($bookKey, $data, $expire = CommonConst::REDIS_SESSION_EXPIRE_TIME_DAY_7)
{
$result = true;
$redisDb = CommonConst::REDIS_MESSAGE_SESSION;
$redisKey = TFConst::REDIS_TF_BOOKING_REDIS_KEY . '_' . $bookKey;
try {
$result = RedisUtil::setDataWithExpire($this->redis, $redisDb, $redisKey, $expire, $data);
} catch (\Exception $ex) {
LogMessage::error('TravelForest - Set Redis Error (' . $redisKey . ')');
}
return $result;
}
private function _saveBookingLog($bookingIdx, $contents = [])
{
$result = true;
try {
$curDateTime = $timestamp ?? date('Y-m-d H:i:s');
$contents['timestamp'] = $curDateTime;
$contents = json_encode($contents, JSON_UNESCAPED_UNICODE);
$filePath = BASE_DIR . '/logs/biz/';
$fileName = 'TFbooking.' . $bookingIdx . '.log';
$file = $filePath . $fileName;
$logfile = fopen($file, 'a');
fwrite($logfile, $contents . "\n\n");
fclose($logfile);
$s3FileName = date('Y/m/d', strtotime($curDateTime));
$s3FileName .= '/' . $fileName;
if (true === (AwsUtil::s3FileUpload($s3FileName, $file, 's3Log'))) {
@unlink($file);
}
} catch (\Exception $ex) {
$result = false;
}
return $result;
}
/**
* @param $str
*
* @return mixed
*/
private function _replaceSpecialChar($str)
{
return str_replace(['>', '>', '<'], ['>', '>', '<'], $str);
}
/**
* @param $tf_status
*
* @return string
*/
private function _getStatusCode($tf_status)
{
switch ($tf_status) {
case TFConst::TF_BOOK_CD_ORD :
case TFConst::TF_BOOK_CD_REQ :
case TFConst::TF_BOOK_CD_INS :
$status = TFConst::RESERVE_STATUS_RESV;
break;
case TFConst::TF_BOOK_CD_BOK :
$status = TFConst::RESERVE_STATUS_WAIT;
break;
case TFConst::TF_BOOK_CD_CFM :
$status = TFConst::RESERVE_STATUS_CFRM;
break;
case TFConst::TF_BOOK_CD_CLS :
case TFConst::TF_BOOK_CD_CCL :
$status = TFConst::RESERVE_STATUS_CNCL;
break;
default :
$status = null;
}
return $status;
}
}<file_sep><?php
/**
* 생성된 파일의 부모 클래스
* 이 클래스는 추상 클래스를 부모로 둔다.
*
* @author kimildo
*/
namespace controllers\generated;
use Slim\Container;
use Slim\Http\Request;
use Slim\Http\Response;
use abstraction\classes\SynctreeAbstract;
use libraries\{constant\CommonConst,
constant\ErrorConst,
log\LogMessage,
util\CommonUtil,
util\RedisUtil,
util\AwsUtil};
class Synctree extends SynctreeAbstract
{
protected $ci;
protected $logger;
protected $renderer;
protected $redis;
protected $jsonResult;
protected $httpClient;
protected $promise;
protected $promiseResponseData;
protected $httpReqTimeout = 3;
protected $httpReqVerify = false;
/**
* Synctree constructor.
*
* @param Container $ci
*
* @throws \Interop\Container\Exception\ContainerException
*/
public function __construct(Container $ci)
{
$this->ci = $ci;
try {
$this->ci = $ci;
$this->logger = $ci->get('logger');
$this->renderer = $ci->get('renderer');
$this->redis = $ci->get('redis');
} catch (\Exception $ex) {
LogMessage::error($ex->getMessage());
}
$this->jsonResult = [
'result' => ErrorConst::SUCCESS_CODE,
'data' => [
'message' => '',
]
];
}
/**
* @param Request $request
* @param Response $response
*
* @return Response
*/
public function getCommand(Request $request, Response $response)
{
$results = $this->jsonResult;
try {
$params = $request->getAttribute('params');
if (false === CommonUtil::validateParams($params, ['event_key'])) {
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
// get redis data
if (false === ($redisData = RedisUtil::getDataWithDel($this->redis, $params['event_key'], CommonConst::REDIS_SECURE_PROTOCOL_COMMAND))) {
throw new \Exception(null, ErrorConst::ERROR_RDB_NO_DATA_EXIST);
}
$results['data'] = $redisData;
} catch (\Exception $ex) {
$results = $this->_getErrorMessage($ex);
}
return $response->withJson($results, ErrorConst::SUCCESS_CODE);
}
/**
* 역방향 보안프로토콜을 위한 리스너
*
* @param $params
*
* @return bool
* @throws \GuzzleHttp\Exception\GuzzleException
*/
protected function _eventListener($params)
{
$result = false;
if (false === CommonUtil::validateParams($params, ['target_url', 'event_key'])) {
return $result;
}
$options = [
'verify' => $this->httpReqVerify,
'timeout' => $this->httpReqTimeout,
'json' => ['event_key' => $params['event_key']]
];
$result = $this->_httpRequest($params['target_url'], $options);
$resStatus = $result['res_status'];
LogMessage::info('_eventListener :: ' . $resStatus);
return $result;
}
/**
* guzzle request
*
* @param $targetUrl
* @param $options
* @param string $method
*
* @return array
* @throws \GuzzleHttp\Exception\GuzzleException
*/
protected function _httpRequest($targetUrl, $options, $method = 'POST')
{
$resData = null;
$resStatus = null;
try {
if (empty($this->httpClient) || ! is_object($this->httpClient)) {
$this->httpClient = new \GuzzleHttp\Client();
}
$ret = $this->httpClient->request($method, $targetUrl, $options);
$resData = $ret->getBody()->getContents();
$resData = strip_tags($resData);
$resData = CommonUtil::getValidJSON($resData);
$resStatus = $ret->getStatusCode() . ' ' . $ret->getReasonPhrase();
} catch (\GuzzleHttp\Exception\ServerException $e) {
preg_match('/`(5[0-9]{2}[a-z\s]+)`/i', $e->getMessage(), $output);
$resStatus = $output[1];
LogMessage::error('url :: ' . $targetUrl . ', error :: ' . $resStatus . ', options :: ' . json_encode($options, JSON_UNESCAPED_UNICODE));
} catch (\GuzzleHttp\Exception\ClientException $e) {
preg_match('/`(4[0-9]{2}[a-z\s]+)`/i', $e->getMessage(), $output);
$resStatus = $output[1];
LogMessage::error('url :: ' . $targetUrl . ', error :: ' . $resStatus);
} catch (\Exception $e) {
$resStatus = "Name or service not known";
LogMessage::error('url :: ' . $targetUrl . ', error :: ' . $resStatus);
}
return [
'res_status' => $resStatus,
'res_data' => $resData,
];
}
/**
* 비동기 호출
*
* @param array $asyncRequests
* @param int $concurrency
* @param bool $wait
*
* @return array
*
* $domainArr = [
[
'url' => 'https://3069d955-08a7-4052-8f61-a83f488a32a6.mock.pstmn.io/getJson',
'method' => 'POST'
],
[
'url' => 'https://www.naver.com/efwefwe',
'method' => 'POST'
],
[
'url' => 'https://www.daum.net/ffff',
'method' => 'GET'
],
[
'url' => 'https://3069d955-08a7-4052-8f61-a83f488a32a6.mock.pstmn.io/getJson',
'method' => 'GET'
]
];
$responseDatas['async'] = $this->_httpAsyncRequest($domainArr);
*/
protected function _httpAsyncRequest(array $asyncRequests, $wait = true, $concurrency = 5)
{
$this->promiseResponseData = [];
try {
if (empty($this->httpClient) || ! is_object($this->httpClient)) {
$this->httpClient = new \GuzzleHttp\Client();
}
if (true === $wait) {
$requestPromises = function ($targets) {
foreach ($targets as $target) {
yield function() use ($target) {
return $this->httpClient->requestAsync($target['method'], $target['url'], $target['options'] ?? [] );
};
}
};
$pool = new \GuzzleHttp\Pool($this->httpClient, $requestPromises($asyncRequests), [
'concurrency' => $concurrency,
'fulfilled' => function ($response, $index) {
// this is delivered each successful response
$resData = json_decode($response->getBody()->getContents(), true);
$this->promiseResponseData['seq'][] = $index;
$this->promiseResponseData['data'][] = $resData;
$generatedFile = fopen('/home/ubuntu/apps/secure/upload/' . $index . '.txt', 'w');
fwrite($generatedFile, json_encode($resData, JSON_UNESCAPED_UNICODE));
fclose($generatedFile);
},
'rejected' => function ($reason, $index) {
// this is delivered each failed request
},
]);
$promise = $pool->promise();
$promise->wait();
} else {
foreach ($asyncRequests as $index => $target) {
$this->promiseResponseData['seq'][] = $index;
$promise[] = $this->httpClient->requestAsync($target['method'], $target['url'], $target['options'] ?? [] );
}
//$pool = new \GuzzleHttp\Pool($this->httpClient, $requestPromises($asyncRequests));
}
//CommonUtil::showArrDump($promise);
} catch (\Exception $e) {
}
return $this->promiseResponseData;
}
/**
* 로그 S3 업로드
* @todo 추후 로그서버를 별도로 구축, 비동기로 전환
*
* @param $fileName
* @param $contents
* @param $appId
* @param $bizId
*
* @return bool
*/
protected function _saveLog($fileName, $contents, $appId, $bizId)
{
try {
$filePath = BASE_DIR . '/logs/biz/';
$fileName = $fileName . CommonUtil::getMicroTime() . '-' . APP_ENV . '.log';
$file = $filePath . $fileName;
$logfile = fopen($file, 'w');
fwrite($logfile, $contents);
fclose($logfile);
$s3FileName = date('Y/m/d');
$s3FileName .= '/' . $appId . '/' . $bizId . '/' . $fileName;
if (APP_ENV === APP_ENV_PRODUCTION) {
if (true === ($s3Result = AwsUtil::s3FileUpload($s3FileName, $file, 's3Log'))) {
@unlink($file);
return true;
}
}
$result = true;
} catch (\Exception $ex) {
$result = false;
}
return $result;
}
/**
* 에러메세지 출력
*
* @param \Exception $ex
*
* @return array
*/
protected function _getErrorMessage(\Exception $ex)
{
$results = [
'result' => ErrorConst::FAIL_CODE,
'data' => [
'message' => CommonUtil::getErrorMessage($ex),
]
];
return $results;
}
}
<file_sep><?php
$app->group('/synctree-tf', function () {
$this->get('/getProducts', 'controllers\internal\TravelForest:getProducts')->setName('product'); // 모상품리스트
$this->post('/getProduct', 'controllers\internal\TravelForest:getProduct')->setName('product'); // 모상품 상세정보
$this->post('/getProduct/{subProduct}', 'controllers\internal\TravelForest:getProduct')->setName('product'); // 자상품 상세 정보
$this->post('/authCheck', 'controllers\internal\TravelForest:authCheck')->setName('auth'); // 권한 체크
$this->get('/getProductIdx/{productTypeKey:[0-9]+}', 'controllers\internal\TravelForest:getProductIdx')->setName('product'); // 자상품 IDX로 모상품 IDX 가지고 온다.
$this->get('/setProductsBatch', 'controllers\internal\TravelForest:setProductsBatch')->setName('batch'); // TF 상품 배치
$this->get('/setProductBatch/{area_idx}/{product_idx}', 'controllers\internal\TravelForest:setProductBatch')->setName('batch');
$this->post('/addBooking', 'controllers\internal\TravelForest:addBooking')->setName('booking'); // 예약생성 메퍼
$this->get('/proceedBooking/{bookingKey:[0-9]+}', 'controllers\internal\TravelForest:proceedBooking')->setName('booking'); // 예약진행 매퍼
$this->get('/cancelBooking/{bookingKey:[0-9]+}', 'controllers\internal\TravelForest:cancelBooking')->setName('booking'); // 예약취소 매퍼
$this->get('/checkBookingStatus/{bookingKey:[0-9]+}', 'controllers\internal\TravelForest:checkBookingStatus')->setName('booking'); // 예약진행 매퍼
$this->put('/bookingUpdate/{bookingKey:[0-9]+}/{updateType:[a-z]+}', 'controllers\internal\TravelForest:bookingUpdate')->setName('booking'); // 예약 Webhook
$this->put('/productUpdate/{productKey:[0-9]+}', 'controllers\internal\TravelForest:productUpdate')->setName('booking'); // 상품 Webhook
$this->put('/productUpdate/{productKey:[0-9]+}/{productTypeKey:[0-9]+}', 'controllers\internal\TravelForest:productUpdate')->setName('booking'); // 상품 Webhook
$this->post('/secure/getCommand', 'controllers\internal\TravelForest:getCommand')->setName('getCommand'); // 보안 프로토콜
if (APP_ENV !== APP_ENV_PRODUCTION) {
$this->get('/secure/getEventKey', 'controllers\internal\TravelForest:getEventKey')->setName('getCommand'); // 보안 프로토콜 이벤트키 발급
}
$this->group('/tourvis/api', function () {
switch (APP_ENV) {
case APP_ENV_DEVELOPMENT_LOCAL_KIMILDO :
case APP_ENV_DEVELOPMENT :
// 모상품 목록
$this->get('/v1/{supplierCode}/products', 'controllers\generated\usr\owner_nntuple_com\GenerateffUecF43IcM1m5cBrAGXHkController:main')->setName('main');
// 모상품 상세
$this->get('/v1/{supplierCode}/products/{productKey:[0-9]+}',
'controllers\generated\usr\owner_nntuple_com\GenerateuONxfxovEnkAZvMFCAWBzlController:main')->setName('main');
// 자상품 리스트
$this->get('/v1/{supplierCode}/products/{productKey:[0-9]+}/{productTypes:[a-z\-]{13}}',
'controllers\generated\usr\owner_nntuple_com\GenerateHRNHfBC1C0ccaCzCxfvddbController:main')->setName('main');
// 자상품 상세
$this->get('/v1/{supplierCode}/{productTypes:[a-z\-]{13}}/{productTypeKey:[0-9]+}',
'controllers\generated\usr\owner_nntuple_com\Generate47p9A8I1VuMguPA5Cz0xa8Controller:main')->setName('main');
// 자상품 날짜 검색
$this->get('/v1/{supplierCode}/{productTypes:[a-z\-]{13}}/{productTypeKey:[0-9]+}/price',
'controllers\generated\usr\owner_nntuple_com\GeneratelLmX6Q5SqAABaMDRTGqaNnController:main')->setName('main');
// 예약생성
$this->post('/v1/{supplierCode}/book',
'controllers\generated\usr\owner_nntuple_com\GenerateKdEx1crXzerSfj8dWr9pmmController:main')->setName('main');
// 예약진행
$this->put('/v1/{supplierCode}/book/{bookingKey:[0-9]+}/confirm',
'controllers\generated\usr\owner_nntuple_com\GenerateXmKWZuZgxTAMz9RVM3DcgyController:main')->setName('main');
// 예약취소
$this->put('/{supplierCode}/book/{bookingKey:[0-9]+}/cancel',
'controllers\generated\usr\owner_nntuple_com\GenerateM9GXOBdtvQRA8A1clW15BHController:main')->setName('main');
// 예약상태 확인
$this->get('/{supplierCode}/book/{bookingKey:[0-9]+}',
'controllers\generated\usr\owner_nntuple_com\GeneratevXEhAKkdIJQL6HBpSLMOALController:main')->setName('main');
break;
case APP_ENV_STAGING :
case APP_ENV_PRODUCTION :
// 모상품 목록
$this->get('/v1/{supplierCode}/products', 'controllers\generated\usr\tony_oh_travelforest_co_kr\GenerateekbjUdv93ES7MfWKZgNM99Controller:main')->setName('main');
// 모상품 상세
$this->get('/v1/{supplierCode}/products/{productKey:[0-9]+}',
'controllers\generated\usr\tony_oh_travelforest_co_kr\GenerateWZpYpTdzbqVYdtXfSACyMXController:main')->setName('main');
// 자상품 리스트
$this->get('/v1/{supplierCode}/products/{productKey:[0-9]+}/{productTypes:[a-z\-]{13}}',
'controllers\generated\usr\tony_oh_travelforest_co_kr\GenerateUsR8n8zTC0YG7fr41ozpDbController:main')->setName('main');
// 자상품 상세
$this->get('/v1/{supplierCode}/{productTypes:[a-z\-]{13}}/{productTypeKey:[0-9]+}',
'controllers\generated\usr\tony_oh_travelforest_co_kr\Generatep8bnPaFrXRD18rQnu3eIu8Controller:main')->setName('main');
// 자상품 날짜 검색
$this->get('/v1/{supplierCode}/{productTypes:[a-z\-]{13}}/{productTypeKey:[0-9]+}/price',
'controllers\generated\usr\tony_oh_travelforest_co_kr\GenerateGkqiAEHnbFsBhwSqxzkJ74Controller:main')->setName('main');
// 예약생성
$this->post('/v1/{supplierCode}/book',
'controllers\generated\usr\tony_oh_travelforest_co_kr\Generate2ikG4ygrAGw2znVr8hdq9vController:main')->setName('main');
// 예약진행
$this->put('/v1/{supplierCode}/book/{bookingKey:[0-9]+}/confirm',
'controllers\generated\usr\tony_oh_travelforest_co_kr\GeneratebzjSIazKVCVMmtSG92ZpP0Controller:main')->setName('main');
// 예약취소
$this->put('/{supplierCode}/book/{bookingKey:[0-9]+}/cancel',
'controllers\generated\usr\tony_oh_travelforest_co_kr\GenerateTSQwk0ViFINl2i7BcfJ7vAController:main')->setName('main');
// 예약상태 확인
$this->get('/{supplierCode}/book/{bookingKey:[0-9]+}',
'controllers\generated\usr\tony_oh_travelforest_co_kr\GenerateTbURRHd5VhbdVBQH30A9b2Controller:main')->setName('main');
break;
}
});
})
->add(new \middleware\Common($app->getContainer(), false))
;<file_sep># Synctree Studio
## 기본 컨셉
> - 앱이 최상위 단위이고 계정마다 여러개를 가질 수 있다.
> - 비즈유닛은 앱에 속한다. 비즈유닛간의 연계성은 없다.
> - 비즈유닛은 한개의 Endpoint를 갖는다.
> - 오퍼레이터는 통신의 기본단위 개념이다. 팀에 속하며 비즈유닛에 바인딩 시킬 수 있다.
> - 비즈유닛 안에서 오퍼레이터는 여러개 존재할 수 있으며 오퍼레이터 간 릴레이를 설정할 수 있다.
> - 오퍼레이터의 속성에 통신할 엔드포인트 및 Request/Response 변수를 지정 할 수 있다.
> - 앱, 비즈유닛, 오퍼레이터의 정보값은 DB에 있고, 이를 조합해 Redis에 메타데이터를 생성해 갖고 있다.
> - 비유닛을 저장하면 디비와 Redis의 정보를 갱신하고, 빌드하면 해당 메타데이터를 통해 파일을 생성한다.
> - CodeDeploy를 통해 컨슈머의 서버에 배포한다.
> - 생성된 비즈유닛이 호출될때 S3에 로깅파일을 업로드 한다.
## 개발 기능
> - 비즈유닛에 오퍼레이터를 바인딩하고 오퍼레이터 간의 변수 연계 지원
> - 비즈유닛 파일 생성 기능
> - 오퍼레이터 JSON 형식 지원
> - 오퍼레이터 통신형식 형식 지원
> - 오퍼레이터 보안프로토콜 적용
> - 오퍼레이터 바인딩시 Authorization 적용
> - ALT 컨트롤 기능 (오퍼레이터 switch case)
> - PHP Class, route 파일 생성 및 배포 기능
> - Async
> - Loop (예정)
> - 오퍼레이터의 변수 require field 기능
<file_sep><?php
$app->group('/GenbPk6Bidk0jrzhNQkKprzhs', function () {
$this->post('/secure/getCommand', 'controllers\generated\usr\owner_nntuple_com\GeneratebPk6Bidk0jrzhNQkKprzhsController:getCommand')->setName('getCommand');
$this->get('', 'controllers\generated\usr\owner_nntuple_com\GeneratebPk6Bidk0jrzhNQkKprzhsController:main')->setName('main');
$this->get('/', 'controllers\generated\usr\owner_nntuple_com\GeneratebPk6Bidk0jrzhNQkKprzhsController:main')->setName('main');
})->add(new \middleware\Common($app->getContainer(), APP_ENV === APP_ENV_PRODUCTION));<file_sep><?php
/**
* Studio PHP Generate Engine
*
* @author kimildo
* @see https://packagist.org/packages/nette/php-generator
*
*/
namespace libraries\util;
use libraries\{
constant\CommonConst,
constant\GeneratorConst,
util\CommonUtil,
log\LogMessage
};
use Nette\PhpGenerator as PGen;
class GenerateUtil
{
private $config;
private $fileObj;
private $fileInfo;
private $params;
private $userPath;
private $class;
private $error = false;
private $ci;
/**
* GenerateUtil constructor.
*
* @param $ci
* @param array $params
*/
public function __construct($ci, $params = [])
{
$configFile = include APP_DIR . 'config/' . APP_ENV . '.php';
$this->config = $configFile['settings']['home_path'] ?? null;
$this->fileObj = new PGen\PhpFile;
$this->fileObj->addComment('This file is Created by Ntuple GeneratedEngine.');
$this->fileObj->addComment(date('Y-m-d H:i:s'));
$this->params = $params;
$this->userPath = str_replace(['@', '.'], '_', $params['user_id']);
$this->ci = $ci;
}
/**
* Controller 파일 생성
*
* @return $this
* @throws \Exception
*/
public function setControllerFile()
{
if (!empty($this->error)) {
return $this;
}
$className = str_replace('.php', '', $this->fileInfo['file_name']);
$namespace = $this->fileObj->addNamespace('controllers\\generated\\usr\\' . $this->userPath);
$namespace
->addUse('Slim\Http\Request')
->addUse('Slim\Http\Response')
->addUse('Slim\Container')
->addUse('libraries\constant\CommonConst')
->addUse('libraries\constant\ErrorConst')
->addUse('libraries\log\LogMessage')
->addUse('libraries\util\CommonUtil')
->addUse('libraries\util\RedisUtil')
->addUse('controllers\generated\Synctree')
->addUse('Ramsey\Uuid\Uuid')
->addUse('Ramsey\Uuid\Exception\UnsatisfiedDependencyException')
;
$this->class = $namespace->addClass($className)->setExtends('Synctree');
$this->class->addConstant('BIZOPS', json_encode($this->params, JSON_UNESCAPED_UNICODE));
//$class->addConstant('BUNIT_TOKEN', $this->params['token']);
$this->class->addProperty('eventKey')->setVisibility('private');
$this->class->addProperty('resultParams')->setVisibility('private');
$this->class->addProperty('params')->setVisibility('private');
$this->class->addMethod('__construct')->setBody('parent::__construct($ci);')->addParameter('ci')->setTypeHint('Container');
$mainMethod = $this->class->addMethod(GeneratorConst::GEN_MAIN_METHOD_NAME);
$mainBody = <<<'SOURCE'
$result = [];
$result['result'] = ErrorConst::SUCCESS_STRING;
$startTime = CommonUtil::getMicroTime();
$result['timestamp']['start'] = CommonUtil::getDateTime() . ' ' . $startTime;
SOURCE;
$mainBody .= PHP_EOL . PHP_EOL . 'try {' . PHP_EOL;
$mainBody .= ' $this->params = $request->getAttribute(\'params\');';
$mainBody .= PHP_EOL . PHP_EOL;
//$request = ['token'];
$request = [];
$requestEncode = '';
foreach ($this->params['request'] as $req) {
$request[] = $req['req_key'];
if ($req['req_var_type'] === CommonConst::VAR_TYPE_JSON) {
$requestEncode .= '$this->params[\'' . $req['req_key'] . '\'] = CommonUtil::getValidJSON($this->params[\'' . $req['req_key'] . '\']);' . PHP_EOL . PHP_EOL;
}
}
$request = "'" . implode("', '", $request) . "'";
$mainBody .= ' if (false === CommonUtil::validateParams($this->params, [' . $request . '])) {' . PHP_EOL;
$mainBody .= <<<'SOURCE'
LogMessage::error('Not found required field');
throw new \Exception(null, ErrorConst::ERROR_NOT_FOUND_REQUIRE_FIELD);
}
$bizOps = json_decode(static::BIZOPS, true);
$responseDatas = [];
$result['request'] = [
'actor_alias' => $bizOps['actor_alias'] ?? null,
'request' => $this->params,
];
SOURCE;
$mainBody .= $requestEncode;
$mainBodyArr = [];
$controlInfoArr = [];
// 모든 오퍼레이터 서브메소드 생성
foreach ($this->params['operators'] as $opSeq => $row) {
$bindSeq = $opSeq;
$controlInfo = null;
if (!empty($row['control_container_code'])) {
$controlInfo = json_decode($row['control_container_info'], true);
$controlIndex = array_search($controlInfo['control_id'], array_column($this->params['controls'], 'control_alt_id'));
$bindSeq = $this->params['controls'][$controlIndex]['binding_seq'];
}
$subMethodName = GeneratorConst::GEN_SUB_METHOD_NAME . strtoupper($row['operation_key']) . $opSeq;
$resSourceText = ' $responseDatas[] = $this->resultParams = $this->' . $subMethodName . '($request, $response);';
if (!empty($row['control_container_code'])) {
$mainBodyArr[$bindSeq][$opSeq] = $resSourceText;
$controlInfoArr[$opSeq] = $controlInfo;
} else {
$mainBodyArr[$opSeq] = $resSourceText;
}
if (false === $this->_makeSubfuntion($subMethodName, $row, $opSeq)) {
$this->error = 'Error While Make Subfunction';
LogMessage::error($this->error);
return $this;
}
} // end of $operation foreach
// 메인메소드 조건문 or Response 호출 생성
$controlOperators = CommonConst::CONTROLL_OPERATORS;
foreach ($mainBodyArr as $key => $row) {
// if alt
if (is_array($row)) {
$mainBody .= PHP_EOL . ' switch (true) {' . PHP_EOL;
foreach ($row as $opSeq => $source) {
$controlInfo = $controlInfoArr[$opSeq];
$controlIndex = array_search($controlInfo['control_id'], array_column($this->params['controls'], 'control_alt_id'));
$parameterKeyName = $this->params['controls'][$controlIndex]['parameter_key_name'];
$parameterJson = (!empty($this->params['controls'][$controlIndex]['sub_parameter_path']))
? $this->_jsonPathToArrayString($this->params['controls'][$controlIndex]['sub_parameter_path']) : '';
$parameterFrom = (!empty($this->params['controls'][$controlIndex]['biz_ops_id'])) ? '$params' : '$this->resultParams[\'response\']';
$targetValue = (is_int($controlInfo['value'])) ? (int)$controlInfo['value'] : '\'' . $controlInfo['value'] . '\'';
//if ($key === array_key_last($row)) {
// $mainBody .= ' default : ' . PHP_EOL . ' ' . $source . PHP_EOL;
//} else {
$mainBody .= ' case ('. $parameterFrom .'[\'' . $parameterKeyName . '\']' . $parameterJson . ' ' . $controlOperators[$controlInfo['operator']]
. ' ' . $targetValue . ') :' . PHP_EOL
. ' ' . $source . PHP_EOL
. ' break;' . PHP_EOL
;
//}
}
$mainBody .= ' default : ' . PHP_EOL . ' ' . PHP_EOL;
$mainBody .= ' }' . PHP_EOL;
} else {
$mainBody .= $row . PHP_EOL;
}
}
$mainBody .= <<<'SOURCE'
$result['data'] = $responseDatas;
} catch (\Exception $ex) {
$result = $this->_getErrorMessage($ex);
}
$endTime = CommonUtil::getMicroTime();
$result['timestamp']['end'] = CommonUtil::getDateTime() . ' ' . $endTime;
$result['timestamp']['runtime'] = $endTime - $startTime;
try {
$this->_saveLog('logBiz-' . $bizOps['biz_id'] . '-access', json_encode($result, JSON_UNESCAPED_UNICODE), $bizOps['app_id'], $bizOps['biz_id']);
} catch (\Exception $ex) {
LogMessage::error('Save Log Fail (biz:: ' . $bizOps['biz_id'] . ') - ' . json_encode($this->_getErrorMessage($ex), JSON_UNESCAPED_UNICODE));
}
unset($result['timestamp']);
unset($result['result']);
return $response->withJson($result, ErrorConst::SUCCESS_CODE);
SOURCE;
$mainMethod->addComment($this->params['biz_name'] . " Main Method\n");
$mainMethod->setBody($mainBody);
$mainMethod->addParameter('request')->setTypeHint('Request');
$mainMethod->addParameter('response')->setTypeHint('Response');
$mainMethod->addComment("@param Request \$request\n");
$mainMethod->addComment("@param Response \$response\n");
if ($this->params['req_method'] == CommonConst::REQ_METHOD_GET_STR) {
$mainMethod->addParameter('args')->setTypeHint('array');
$mainMethod->addComment("@param args \$args\n");
}
$mainMethod->addComment("@return Response\n");
$mainMethod->addComment("@throws \\Exception\n");
return $this;
}
/**
* 라우트 파일 소스 생성
*
* @return $this
*/
public function setRouteFile()
{
if (!empty($this->error)) {
return $this;
}
//LogMessage::debug('fileInfo :: ' . json_encode($this->fileInfo));
$sourceText = '<?php' . PHP_EOL . PHP_EOL;
$sourceText .= '$app->group(\'/Gen' . $this->params['biz_uid'] . '\', function () {' . PHP_EOL;
$sourceText .= PHP_EOL . ' $this->post(\'' . CommonConst::GET_COMMAND_URL . '\', \'controllers\\generated\\usr\\' . $this->userPath . '\\'
. $this->fileInfo['template_name'] . $this->params['biz_uid'] . 'Controller:getCommand\')->setName(\'getCommand\');';
/*
$sourceText .= PHP_EOL . ' $this->' . ($this->params['req_method'] == 'P' ? 'post' : 'get') . '(\'';
if ($this->params['req_method'] == 'G' && !empty($this->params['request'])) {
foreach ($this->params['request'] as $row) {
$sourceText .= '/{' . $row['req_key'] . '}';
}
}
$sourceText .= '/{token}\', ';
*/
$reqMethod = ($this->params['req_method'] === CommonConst::REQ_METHOD_GET_CODE) ? CommonConst::REQ_METHOD_GET : CommonConst::REQ_METHOD_POST ;
$reqMethod = strtolower($reqMethod);
$sourceText .= PHP_EOL . ' $this->' . $reqMethod . '(\'\', ';
$sourceText .= '\'controllers\\generated\\usr\\' . $this->userPath . '\\' . $this->fileInfo['template_name'] . $this->params['biz_uid']
. 'Controller:'. GeneratorConst::GEN_MAIN_METHOD_NAME .'\')->setName(\''. GeneratorConst::GEN_MAIN_METHOD_NAME .'\');';
$sourceText .= PHP_EOL . ' $this->' . $reqMethod . '(\'/\', ';
$sourceText .= '\'controllers\\generated\\usr\\' . $this->userPath . '\\' . $this->fileInfo['template_name'] . $this->params['biz_uid']
. 'Controller:'. GeneratorConst::GEN_MAIN_METHOD_NAME .'\')->setName(\''. GeneratorConst::GEN_MAIN_METHOD_NAME .'\');' . PHP_EOL;
$sourceText .= PHP_EOL . '})->add(new \middleware\Common($app->getContainer(), APP_ENV === APP_ENV_PRODUCTION));';
$this->fileObj = $sourceText;
return $this;
}
/**
* 파일 이름 얻기
*
* @param string $type
* @param string $templateName
*
* @return $this|bool
*/
public function getFileName($type = 'CONTROLLER', $templateName = GeneratorConst::GEN_FILE_PREFIX)
{
try {
$filePath = $this->config . GeneratorConst::PATH_RULE[$type]['PATH'] . $this->userPath . '/';
$fileName = ucfirst(strtolower($templateName)) . $this->params['biz_uid'] . GeneratorConst::PATH_RULE[$type]['SUBFIX'];
if ( ! file_exists($filePath)) {
mkdir($filePath, 0755, true);
}
$this->fileInfo = [
'file_path' => $filePath,
'file_name' => $fileName,
'template_name' => $templateName
];
} catch (\Exception $ex) {
$this->error = 'Fail to get filename';
LogMessage::error($this->error);
}
return $this;
}
/**
* 파일쓰기
*
* @param string $mode
*
* @return string
*/
public function writeFile($mode = 'w')
{
try {
if (!empty($this->error)) {
throw new \Exception($this->error);
}
$fileContents = $this->_refining($this->fileObj);
$generatedFile = fopen($this->fileInfo['file_path'] . $this->fileInfo['file_name'], $mode);
fwrite($generatedFile, $fileContents);
fclose($generatedFile);
} catch (\Exception $ex) {
LogMessage::error('Fail to write file :: ' . $this->fileInfo['file_path'] . $this->fileInfo['file_name']);
return false;
}
return $this->fileInfo['file_name'];
}
public function exportBizUnit()
{
return false;
}
/**
* 오퍼레이션에 따른 서브메소드 생성
*
* @param $methodName
* @param $op
* @param $bindingSeq
*
* @return bool
* @throws \Exception
*/
private function _makeSubfuntion($methodName, $op, $bindingSeq)
{
$subBody = '';
$subBody .= '$targetUrl = \'' . $op['target_url'] . (( ! empty($op['target_method'])) ? '/' . $op['target_method'] : '') . '\';' . PHP_EOL;
switch ($op['req_method']) {
case CommonConst::REQ_METHOD_POST_STR :
$opReqType = CommonConst::REQ_METHOD_POST;
$opReqTypeVar = 'form_params';
break;
default :
$opReqType = CommonConst::REQ_METHOD_GET;
$opReqTypeVar = 'query';
}
switch ($op['header_transfer_type_code']) {
case CommonConst::HTTP_HEADER_CONTENTS_TYPE_JSON_CODE :
$opReqTypeVar = strtolower(CommonConst::VAR_TYPE_JSON_TEXT);
break;
case CommonConst::HTTP_HEADER_CONTENTS_TYPE_WWW_FORM_URLENCODED_CODE :
$subBody .= '$options[\'headers\'] = [\'Content-Type\' => \''. CommonConst::HTTP_HEADER_CONTENTS_TYPE_WWW_FORM_URLENCODED_STR .'\'];' . PHP_EOL;
break;
case CommonConst::HTTP_HEADER_CONTENTS_TYPE_XML_CODE :
$subBody .= '$options[\'headers\'] = [\'Content-Type\' => \''. CommonConst::HTTP_HEADER_CONTENTS_TYPE_XML_STR .'\'];' . PHP_EOL;
$opReqTypeVar = 'body';
break;
}
if ( ! empty($op['auth_type_code']) && ! empty($op['auth_keys']) ) {
if (null === ($authKeys = CommonUtil::getValidJSON($op['auth_keys']))) {
LogMessage::error('Auth_keys Error Not valid JSON - File Generator');
return false;
}
switch ($op['auth_type_code']) {
case CommonConst::API_AUTH_BASIC :
$subBody .= '$options[\'auth\'] = [\'' . $authKeys[0]['username'] . '\', \'' . $authKeys[0]['password'] . '\'];' . PHP_EOL;
break;
case CommonConst::API_AUTH_BEARER_TOKEN :
$subBody .= '$options[\'headers\'][\'Authorization\'] = \'Bearer ' . $authKeys[0]['token'] . '\';' . PHP_EOL;
break;
}
}
if ($op['method'] !== CommonConst::PROTOCOL_TYPE_SECURE) {
$subBody .= '$options[\'verify\'] = $this->httpReqVerify;' . PHP_EOL;
$subBody .= '$options[\'timeout\'] = $this->httpReqTimeout;' . PHP_EOL;
}
if ( ! empty($op['arguments'])) {
$subBodyReqs = '';
foreach ($op['arguments'] as $reqs) {
$reqVal = '\'' . $reqs['argument_value'] . '\'';
if ( ! empty($reqs['relay_flag'])) {
$reqVal = ( ! empty($reqs['relay_biz_ops_id'])) ? '$this->params[\'' . $reqs['relay_parameter_key_name'] . '\']'
: '$this->resultParams[\'response\'][\'' . $reqs['relay_parameter_key_name'] . '\']'
;
// 파라미터 타입이 JSON인 경우
if ($reqs['relay_parameter_type_code'] === CommonConst::VAR_TYPE_JSON_CODE && !empty($reqs['relay_sub_parameter_path'])) {
$reqVal .= $this->_jsonPathToArrayString($reqs['relay_sub_parameter_path']);
}
$reqVal .= ' ?? null';
}
$subBodyReqs .= ' \'' . $reqs['parameter_key_name'] . '\' => ' . $reqVal . ',' . PHP_EOL;
}
}
if (!empty($subBodyReqs)) {
$subBody .= '$options[\'' . $opReqTypeVar . '\'] = [' . PHP_EOL;
$subBody .= $subBodyReqs;
$subBody .= '];' . PHP_EOL . PHP_EOL;
}
// 보안프로토콜 처리
if ($op['method'] == CommonConst::PROTOCOL_TYPE_SECURE) {
$subBody .= '$uuid = Uuid::uuid5(Uuid::NAMESPACE_DNS, session_id() . time());' . PHP_EOL;
$subBody .= '$this->eventKey = strtoupper(\'event-\' . $uuid->toString());' . PHP_EOL;
$subBody .= '$datas = [\'event_key\' => $this->eventKey, \'params\' => $options[\'' . $opReqTypeVar . '\']];' . PHP_EOL;
$subBody .= 'RedisUtil::setDataWithExpire($this->redis, CommonConst::REDIS_SECURE_PROTOCOL_COMMAND, $this->eventKey, CommonConst::REDIS_SESSION_EXPIRE_TIME_MIN_5, $datas);';
$subBody .= PHP_EOL . '' . PHP_EOL;
}
if ($op['method'] == CommonConst::PROTOCOL_TYPE_SECURE) {
$subBody .= '$secureData[\'' . $opReqTypeVar . '\'] = [\'event_key\' => $this->eventKey];' . PHP_EOL;
$subBody .= '$ret = $this->_httpRequest($targetUrl, $secureData, \'' . $opReqType . '\');' . PHP_EOL;
} else {
$subBody .= '$ret = $this->_httpRequest($targetUrl, $options, \'' . $opReqType . '\');' . PHP_EOL;
}
$subBody .= PHP_EOL . '$result = [' . PHP_EOL;
$subBody .= ' \'op_name\' => \'' . $op['op_name'] . '\',' . PHP_EOL;
$subBody .= ' \'request_target_url\' => $targetUrl,' . PHP_EOL;
$subBody .= ' \'server_status\' => $ret[\'res_status\'],' . PHP_EOL;
if ($op['method'] == CommonConst::PROTOCOL_TYPE_SIMPLE_HTTP) {
$subBody .= ' \'request\' => $options[\'' . $opReqTypeVar . '\'],' . PHP_EOL;
}
$subBody .= ' \'response\' => [' . PHP_EOL;
foreach ($op['response'] as $ress) {
$subBody .= ' \'' . $ress['res_key'] . '\' => $ret[\'res_data\'][\'' . $ress['res_key'] . '\'] ?? null,' . PHP_EOL;
}
$subBody .= ' ]' . PHP_EOL;
$subBody .= '];' . PHP_EOL;
$subBody .= PHP_EOL . 'return $result;' . PHP_EOL;
// 하위 메소드 생성
$method = $this->class->addMethod($methodName)->setVisibility('private');
$method->setBody($subBody);
$method->addParameter('request')->setTypeHint('Request');
$method->addParameter('response')->setTypeHint('Response');
//$method->addParameter('params')->setTypeHint('array');
//if ($bindingSeq > 1) {
// $method->addParameter('responseDatas')->setTypeHint('array');
//}
$method->addComment('Operation Name : ' . $op['op_name']);
$method->addComment('ID : ' . $op['op_id']);
$method->addComment('Description : ' . $op['op_desc']);
$method->addComment('Binding Seq : ' . $bindingSeq);
return true;
}
/**
* jsonpath 를 배열스트링으로 변환해 반환
*
* @param $jsonPath
*
* @return string
*/
private function _jsonPathToArrayString($jsonPath)
{
$arrayString = '';
//$relayJson = json_decode($reqs['relay_sub_parameter_format'], true);
$relayJsonPath = str_replace('$.', '', $jsonPath);
$tmp = explode('.', $relayJsonPath);
foreach ($tmp as $tpKey) {
if (!empty(strpos($tpKey, '['))) {
$tpKeyTemp = explode('[', $tpKey);
$arrayString .= '[\'' . $tpKeyTemp[0] . '\']' . '[' . str_replace(']', '' , $tpKeyTemp[1]) . ']';
} else {
$arrayString .= '[\'' . $tpKey . '\']';
}
}
return $arrayString;
}
private function _refining($file)
{
$file = str_replace([
'extends \\Synctree',
'(\\Container',
'(\\Request $request, \\Response $response',
'(\\Request $request, \\Response $response, \\$args',
], [
'extends Synctree',
'(Container',
'(Request $request, Response $response',
'(Request $request, Response $response, $args',
], $file);
return $file;
}
}
| 8bb45406a5d59e7b63c35fb94abf0e748691bee4 | [
"Markdown",
"PHP"
] | 6 | PHP | kimildo/synctree-studio | 619ee44724fb8cbdb7a1d866dedff94738282b7e | 20ce21357a36b4093c4f553b41eba9c6a1a143b1 | |
refs/heads/master | <repo_name>sedmelluq/witcher-sandbox<file_sep>/README.md
# witcher-sandbox
Witcher DLLs for messing with internal stuff
<file_sep>/internal/src/bundles.cpp
#include "bundles.h"
#include "memory/executable_address_space.h"
#include "logging/log.h"
#include <fstream>
static WDepot** static_depot_pointer;
static void* vtable_WBundleDataHandleReader_000_custom[26];
static void* vtable_WBundleDataHandleReader_010_custom[3];
WBundleDiskFile* bundle_file_find(uint32_t file_index) {
WXBundleManager& manager = *static_depot_pointer[0]->bundle_manager;
if (file_index > 0 && file_index < manager.file_count) {
return manager.files[file_index];
} else {
return nullptr;
}
}
static WXBundleFileMapping* bundle_file_mapping(uint32_t file_index) {
WXBundleManager& manager = *static_depot_pointer[0]->bundle_manager;
WXBundleFileIndex& index = *manager.file_index;
if (file_index < index.mapping_count) {
WXBundleFileMapping* mapping = &index.mappings[file_index];
if (mapping->file_id != 0) {
return mapping;
}
}
return nullptr;
}
WDiskBundle* bundle_file_identify(uint32_t file_index) {
WXBundleFileMapping* mapping = bundle_file_mapping(file_index);
if (mapping != nullptr) {
WXBundleManager& manager = *static_depot_pointer[0]->bundle_manager;
WXBundleFileIndex& index = *manager.file_index;
WXBundleFileLocation& location = index.locations[mapping->file_id];
if (location.bundle_index < manager.bundle_count) {
return manager.bundles[location.bundle_index];
}
}
return nullptr;
}
void bundle_format_file_directory(WDirectory *directory, std::wstring &path) {
if (directory != nullptr) {
bundle_format_file_directory(directory->parent, path);
path.append(directory->name.text);
path.append(L"/");
}
}
static void custom_WBundleDataHandleReader_deconstructor(WBundleDataHandleReader* reader) {
delete[] ((uint8_t*) reader->buffer);
delete reader;
}
static WBundleDataHandleReader* find_replacement(const std::wstring& file_path) {
if (file_path != L"depot/gameplay/items/def_loot_shops.xml") {
return nullptr;
}
std::ifstream file(R"(Q:\Games\uncooked_witcher\def_loot_shops.xml)", std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
auto data = new uint8_t[size + sizeof(WBundleDataHandleReader)];
if (file.read((char*) &data[sizeof(WBundleDataHandleReader)], size)) {
auto reader = new WBundleDataHandleReader;
reader->vtable_one = vtable_WBundleDataHandleReader_000_custom;
reader->hardcoded_0A = 0x0A;
reader->hardcoded_A3 = 0xA3;
reader->vtable_two = vtable_WBundleDataHandleReader_010_custom;
reader->p018 = nullptr;
auto buffer = (WXBuffer<uint8_t>*) data;
buffer->data = &data[sizeof(WBundleDataHandleReader)];
buffer->length = size;
reader->buffer = buffer;
reader->read_cursor = 0;
reader->read_limit = size;
return reader;
}
return nullptr;
}
static WBundleDataHandleReader* hook_bundle_file_read(WBundleDiskFile* bundle_file, bool complex) {
std::wstring full_path;
bundle_format_file_directory(bundle_file->directory, full_path);
full_path.append(bundle_file->file_name.text);
logger::it->debug("Loading {} file {}: {}", complex, bundle_file->file_index, logger::wide(full_path));
WXBundleFileMapping* mapping = bundle_file_mapping(bundle_file->file_index);
WDiskBundle* bundle = bundle_file_identify(bundle_file->file_index);
if (mapping != nullptr && bundle != nullptr) {
logger::it->debug("... with mapping {} ->{}. Bundle {} named {}", bundle_file->file_index,
mapping->file_id, bundle->index,
logger::wide(bundle->absolute_path.text));
}
return nullptr;
//return find_replacement(full_path);
}
static WBundleDataHandleReader* hook_bundle_file_read_simple(WBundleDiskFile* bundle_file) {
return hook_bundle_file_read(bundle_file, false);
}
static WBundleDataHandleReader* hook_bundle_file_read_complex(WBundleDiskFile* bundle_file) {
return hook_bundle_file_read(bundle_file, true);
}
static void hook_set_bundle_file_read_simple(ExecutableAddressSpace &space, WrapperAddressSpace *wrapper_space) {
ModifiableCode wrapper = wrapper_space->reserve(0x40);
// push rcx
wrapper.bytes({ 0x51 });
// sub rsp, 20h (reserve shadow area + align)
wrapper.bytes({ 0x48, 0x83, 0xEC, 0x20 });
// mov rax, hook_func
wrapper.bytes({ 0x48, 0xB8 });
wrapper.u64((uint64_t) hook_bundle_file_read_simple);
// call rax
wrapper.bytes({ 0xFF, 0xD0 });
// add rsp, 20h (remove shadow area)
wrapper.bytes({ 0x48, 0x83, 0xC4, 0x20 });
// pop rcx
wrapper.bytes({ 0x59 });
// test rax, rax
wrapper.bytes({ 0x48, 0x85, 0xC0 });
// jz $+1
wrapper.bytes({ 0x74, 0x01 });
// retn
wrapper.bytes({ 0xC3 });
// mov rax, [142AA43B8h] (overwritten)
wrapper.bytes({ 0x48, 0x8B, 0x05 });
wrapper.offset32(space.by_offset(0x2AA43B8));
// jmp 1400929F7
wrapper.bytes({ 0xE9 });
wrapper.offset32(space.by_offset(0x929F7));
ModifiableCode hook = space.modify_code(0x929F0, 0x10);
hook.bytes({ 0xE9 });
hook.offset32((uint64_t) wrapper.address);
hook.bytes({ 0x90, 0x90 });
}
static void hook_set_bundle_file_read_complex(ExecutableAddressSpace &space, WrapperAddressSpace *wrapper_space) {
ModifiableCode wrapper = wrapper_space->reserve(0x40);
// push rcx
wrapper.bytes({ 0x51 });
// push rdx
wrapper.bytes({ 0x52 });
// push r8
wrapper.bytes({ 0x41, 0x50 });
// sub rsp, 20h (reserve shadow area + align)
wrapper.bytes({ 0x48, 0x83, 0xEC, 0x20 });
// mov rax, hook_bundle_file_read
wrapper.bytes({ 0x48, 0xB8 });
wrapper.u64((uint64_t) hook_bundle_file_read_complex);
// call rax
wrapper.bytes({ 0xFF, 0xD0 });
// add rsp, 20h (remove shadow area)
wrapper.bytes({ 0x48, 0x83, 0xC4, 0x20 });
// pop r8
wrapper.bytes({ 0x41, 0x58 });
// pop rdx
wrapper.bytes({ 0x5A });
// pop rcx
wrapper.bytes({ 0x59 });
// test rax, rax
wrapper.bytes({ 0x48, 0x85, 0xC0 });
// jz $+1
wrapper.bytes({ 0x74, 0x01 });
// retn
wrapper.bytes({ 0xC3 });
// mov rax, [142AA43B8h] (overwritten)
wrapper.bytes({ 0x48, 0x8B, 0x05 });
wrapper.offset32(space.by_offset(0x2AA43B8));
// jmp 1400929F7
wrapper.bytes({ 0xE9 });
wrapper.offset32(space.by_offset(0x92A27));
ModifiableCode hook = space.modify_code(0x92A20, 0x10);
hook.bytes({ 0xE9 });
hook.offset32((uint64_t) wrapper.address);
hook.bytes({ 0x90, 0x90 });
}
void bundles_setup(TcpServer* tcp_server, WrapperAddressSpace* wrapper_space) {
ExecutableAddressSpace space;
static_depot_pointer = (WDepot**) space.by_offset(0x2AA43B8);
memcpy(vtable_WBundleDataHandleReader_000_custom, (void*) space.by_offset(0x1E13B88),
sizeof(vtable_WBundleDataHandleReader_000_custom));
memcpy(vtable_WBundleDataHandleReader_010_custom, (void*) space.by_offset(0x1E13C60),
sizeof(vtable_WBundleDataHandleReader_010_custom));
vtable_WBundleDataHandleReader_000_custom[0] = (void*) custom_WBundleDataHandleReader_deconstructor;
hook_set_bundle_file_read_simple(space, wrapper_space);
hook_set_bundle_file_read_complex(space, wrapper_space);
tcp_server->add_handler(10, [] (uint16_t type, const std::vector<uint8_t>& message, const TcpMessageSender& sender) {
std::string bundle_path("<not found>");
std::string file_path("<not found>");
uint32_t file_index = *(uint32_t*) &message[0];
WXBundleManager& manager = *static_depot_pointer[0]->bundle_manager;
if (file_index > 0 && file_index < manager.file_count) {
WBundleDiskFile* file = manager.files[file_index];
if (file != nullptr) {
std::wstring full_path;
bundle_format_file_directory(file->directory, full_path);
full_path.append(file->file_name.text);
file_path = logger::wide(full_path);
}
}
WXBundleFileIndex& index = *manager.file_index;
if (file_index < index.mapping_count) {
WXBundleFileMapping& mapping = index.mappings[file_index];
if (mapping.file_id != 0) {
WXBundleFileLocation& location = index.locations[mapping.file_id];
if (location.bundle_index < manager.bundle_count) {
bundle_path = logger::wide(manager.bundles[location.bundle_index]->absolute_path.text);
}
}
}
const char* bundle_bytes = bundle_path.c_str();
size_t bundle_bytes_length = strlen(bundle_bytes);
const char* file_bytes = file_path.c_str();
size_t file_bytes_length = strlen(file_bytes);
std::vector<uint8_t> response(8 + bundle_bytes_length + file_bytes_length, 0);
*(uint32_t*) &response[0] = bundle_bytes_length;
memcpy(&response[4], bundle_bytes, bundle_bytes_length);
*(uint32_t*) &response[4 + bundle_bytes_length] = file_bytes_length;
memcpy(&response[8 + bundle_bytes_length], file_bytes, file_bytes_length);
sender(11, response);
});
}
<file_sep>/internal/src/emitters.cpp
#include "emitters.h"
#include "memory/executable_address_space.h"
#include "engine_types.h"
#include "logging/log.h"
#include "server/message_builder.h"
#include "bundles.h"
#include <fstream>
static void* vtable_WParticleEmitter = nullptr;
static void* vtable_WDependencyLoader = nullptr;
struct TrackedParticleEmitter {
WParticleEmitter* emitter;
uint32_t file_index;
};
static std::mutex emitter_lock;
static std::unordered_map<WParticleEmitter*, TrackedParticleEmitter> tracked_emitters;
static void hook_emitter_parse_data(WParticleEmitter* emitter, WDependencyLoader* loader) {
if (emitter->vtable_one != vtable_WParticleEmitter || loader->vtable_one != vtable_WDependencyLoader) {
logger::it->debug("CParticleEmitter parse call... with GC'd instances...");
return;
}
{
std::lock_guard<std::mutex> guard(emitter_lock);
tracked_emitters[emitter] = { emitter, loader->file->file_index };
}
logger::it->debug("Parsed CParticleEmitter ({:x}) data from file {}", logger::ptr(emitter), loader->file->file_index);
}
static void hook_emitter_destruct(WParticleEmitter* emitter) {
{
std::lock_guard<std::mutex> guard(emitter_lock);
tracked_emitters.erase(emitter);
}
logger::it->debug("Destroyed CParticleEmitter ({:x})", logger::ptr(emitter));
}
struct TrackedRenderParticleEmitter {
WRenderParticleEmitter* render_emitter;
WParticleEmitter* emitter;
uint32_t file_index;
};
static std::unordered_map<WRenderParticleEmitter*, TrackedRenderParticleEmitter> tracked_render_emitters;
static void hook_render_emitter_register(WRenderParticleEmitter* render_emitter, WParticleEmitter* emitter) {
{
std::lock_guard<std::mutex> guard(emitter_lock);
const auto& it = tracked_emitters.find(emitter);
if (it != tracked_emitters.end()) {
tracked_render_emitters[render_emitter] = {
render_emitter,
it->second.emitter,
it->second.file_index
};
logger::it->debug("Setup CRenderParticleEmitter {:x} from {:x} file {}", logger::ptr(render_emitter),
logger::ptr(it->second.emitter), it->second.file_index);
} else {
logger::it->debug("Setup CRenderParticleEmitter {:x}, but no corresponding emitter", logger::ptr(render_emitter));
}
}
}
static void hook_render_emitter_destruct(WRenderParticleEmitter* render_emitter) {
{
std::lock_guard<std::mutex> guard(emitter_lock);
tracked_render_emitters.erase(render_emitter);
}
logger::it->debug("Destroyed CRenderParticleEmitter {:x}", logger::ptr(render_emitter));
}
static void hook_set_emitter_register(ExecutableAddressSpace &space, WrapperAddressSpace *wrapper_space) {
ModifiableCode wrapper = wrapper_space->reserve(0x40);
// push rcx
wrapper.bytes({ 0x51 });
// push rdx
wrapper.bytes({ 0x52 });
// sub rsp, 28h (reserve shadow area + align)
wrapper.bytes({ 0x48, 0x83, 0xEC, 0x28 });
// mov rax, hook_func
wrapper.bytes({ 0x48, 0xB8 });
wrapper.u64((uint64_t) hook_emitter_parse_data);
// call rax
wrapper.bytes({ 0xFF, 0xD0 });
// add rsp, 28h (remove shadow area)
wrapper.bytes({ 0x48, 0x83, 0xC4, 0x28 });
// pop rdx
wrapper.bytes({ 0x5A });
// pop rcx
wrapper.bytes({ 0x59 });
// jmp originalfunction
wrapper.bytes({ 0xE9 });
wrapper.offset32(space.by_offset(0x516490));
ModifiableCode hook = space.modify_code(0x1F3F4D0, 0x08);
hook.u64((uint64_t) wrapper.address);
}
static void hook_set_emitter_destruct(ExecutableAddressSpace& space, WrapperAddressSpace* wrapper_space) {
ModifiableCode wrapper = wrapper_space->reserve(0x40);
// push rcx
wrapper.bytes({ 0x51 });
// sub rsp, 20h (reserve shadow area + align)
wrapper.bytes({ 0x48, 0x83, 0xEC, 0x20 });
// mov rax, hook_func
wrapper.bytes({ 0x48, 0xB8 });
wrapper.u64((uint64_t) hook_emitter_destruct);
// call rax
wrapper.bytes({ 0xFF, 0xD0 });
// add rsp, 20h (remove shadow area)
wrapper.bytes({ 0x48, 0x83, 0xC4, 0x20 });
// pop rcx
wrapper.bytes({ 0x59 });
// push rbx
wrapper.bytes({ 0x40, 0x53 });
// sub rsp, 20h (reserve shadow area + align)
wrapper.bytes({ 0x48, 0x83, 0xEC, 0x20 });
// jmp originalfunction
wrapper.bytes({ 0xE9 });
wrapper.offset32(space.by_offset(0x518FE6));
ModifiableCode hook = space.modify_code(0x518FE0, 0x08);
hook.bytes({ 0xE9 });
hook.offset32((uint64_t) wrapper.address);
hook.bytes({ 0x90 });
}
static void hook_set_render_emitter_register(ExecutableAddressSpace &space, WrapperAddressSpace *wrapper_space) {
ModifiableCode wrapper = wrapper_space->reserve(0x40);
// mov rcx, rsi
wrapper.bytes({ 0x48, 0x8B, 0xCE });
// mov rdx, r14
wrapper.bytes({ 0x49, 0x8B, 0xD6 });
// mov rax, hook_func
wrapper.bytes({ 0x48, 0xB8 });
wrapper.u64((uint64_t) hook_render_emitter_register);
// call rax
wrapper.bytes({ 0xFF, 0xD0 });
// mov rax, [r15]
wrapper.bytes({ 0x49, 0x8B, 0x07 });
// mov rcx, r15
wrapper.bytes({ 0x49, 0x8B, 0xCF });
// jmp originalfunction
wrapper.bytes({ 0xE9 });
wrapper.offset32(space.by_offset(0xBFB04D));
ModifiableCode hook = space.modify_code(0xBFB047, 0x08);
hook.bytes({ 0xE9 });
hook.offset32((uint64_t) wrapper.address);
hook.bytes({ 0x90 });
}
static void hook_set_render_emitter_destruct(ExecutableAddressSpace &space, WrapperAddressSpace *wrapper_space) {
ModifiableCode wrapper = wrapper_space->reserve(0x40);
// push rcx
wrapper.bytes({ 0x51 });
// push rdx
wrapper.bytes({ 0x52 });
// sub rsp, 28h (reserve shadow area + align)
wrapper.bytes({ 0x48, 0x83, 0xEC, 0x28 });
// mov rax, hook_func
wrapper.bytes({ 0x48, 0xB8 });
wrapper.u64((uint64_t) hook_render_emitter_destruct);
// call rax
wrapper.bytes({ 0xFF, 0xD0 });
// add rsp, 28h (remove shadow area)
wrapper.bytes({ 0x48, 0x83, 0xC4, 0x28 });
// pop rdx
wrapper.bytes({ 0x5A });
// pop rcx
wrapper.bytes({ 0x59 });
// jmp originalfunction
wrapper.bytes({ 0xE9 });
wrapper.offset32(space.by_offset(0xC08B20));
ModifiableCode hook = space.modify_code(0x214B4B8, 0x08);
hook.u64((uint64_t) wrapper.address);
}
static void message_emitter_list(uint16_t type, const std::vector<uint8_t> &message, const TcpMessageSender &sender) {
std::vector<uint8_t> response;
{
std::lock_guard<std::mutex> guard(emitter_lock);
uint32_t size = tracked_render_emitters.size();
message_append(response, size);
for (const auto& it : tracked_render_emitters) {
auto address = (uint64_t) it.second.render_emitter;
std::string name = fmt::format("{:016x}h", address);
message_append_string(response, name);
WBundleDiskFile* file = bundle_file_find(it.second.file_index);
if (file != nullptr) {
std::wstring directory;
bundle_format_file_directory(file->directory, directory);
message_append_string(response, directory);
message_append_string(response, std::wstring(file->file_name.text));
} else {
message_append_string(response, "<unknown>");
message_append_string(response, "<unknown>");
}
WDiskBundle* bundle = bundle_file_identify(it.second.file_index);
if (bundle != nullptr) {
message_append_string(response, std::wstring(bundle->absolute_path.text));
} else {
message_append_string(response, "<unknown>");
}
}
}
sender(6, response);
}
template <typename T>
static void encode_buffer(std::vector<uint8_t>& response, const WXBuffer<T>& buffer,
std::function<void(std::vector<uint8_t>&, const T&)> item_encoder) {
if (buffer.length >= 64) {
throw std::exception("Cannot encode buffer, too many items");
}
uint8_t length = (uint8_t) buffer.length;
message_append(response, length);
for (size_t i = 0; i < buffer.length; i++) {
item_encoder(response, buffer.data[i]);
}
}
static void encode_float(std::vector<uint8_t>& response, const float& value) {
message_append(response, value);
}
static void encode_buffer(std::vector<uint8_t>& response, const WXBuffer<float>& buffer) {
encode_buffer<float>(response, buffer, encode_float);
}
static void encode_vector3(std::vector<uint8_t>& response, const WXVector3& value) {
message_append(response, value.x);
message_append(response, value.y);
message_append(response, value.z);
}
static void encode_buffer(std::vector<uint8_t>& response, const WXBuffer<WXVector3>& buffer) {
encode_buffer<WXVector3>(response, buffer, encode_vector3);
}
static void encode_vector2(std::vector<uint8_t>& response, const WXVector2& value) {
message_append(response, value.x);
message_append(response, value.y);
}
static void encode_buffer(std::vector<uint8_t>& response, const WXBuffer<WXVector2>& buffer) {
encode_buffer<WXVector2>(response, buffer, encode_vector2);
}
static void encode_emitter_data(std::vector<uint8_t>& response, const TrackedRenderParticleEmitter& tracked_emitter) {
WRenderParticleEmitter& emitter = *tracked_emitter.render_emitter;
message_append(response, emitter.initializer_bitset);
message_append(response, emitter.modificator_bitset);
WXParticleEmitterModuleData& data = emitter.emitter_data;
encode_buffer(response, data.alpha);
encode_buffer(response, data.color);
encode_buffer(response, data.lifetime);
encode_buffer(response, data.position);
encode_float(response, data.position_offset);
encode_buffer(response, data.rotation);
encode_buffer(response, data.rotation_3d);
encode_buffer(response, data.rotation_rate);
encode_buffer(response, data.rotation_rate_3d);
encode_buffer(response, data.size);
encode_buffer(response, data.size_3d);
message_append(response, data.size_keep_ratio);
encode_buffer(response, data.spawn_extents);
encode_buffer(response, data.spawn_inner_radius);
encode_buffer(response, data.spawn_outer_radius);
message_append(response, data.spawn_world_space);
message_append(response, data.spawn_surface_only);
encode_vector3(response, data.p0A8);
for (float i : data.spawn_to_local_matrix) {
encode_float(response, i);
}
encode_buffer(response, data.velocity);
message_append(response, data.velocity_world_space);
encode_buffer(response, data.velocity_inherit_scale);
encode_buffer(response, data.velocity_spread_scale);
message_append(response, data.velocity_spread_conserve_momentum);
encode_buffer(response, data.texture_animation_initial_frame);
message_append(response, data.p140);
message_append(response, data.p144);
message_append(response, data.p148);
encode_buffer(response, data.velocity_over_life);
encode_buffer(response, data.acceleration_direction);
encode_buffer(response, data.acceleration_scale);
encode_buffer(response, data.rotation_over_life);
encode_buffer(response, data.rotation_rate_over_life);
encode_buffer(response, data.rotation_3d_over_life);
encode_buffer(response, data.rotation_rate_3d_over_life);
encode_buffer(response, data.color_over_life);
encode_buffer(response, data.alpha_over_life);
encode_buffer(response, data.size_over_life);
encode_buffer(response, data.size_over_life_orientation);
encode_buffer(response, data.texture_animation_speed);
encode_buffer(response, data.velocity_turbulize_scale);
encode_buffer(response, data.velocity_turbulize_timelife_limit);
encode_float(response, data.velocity_turbulize_noise_interval);
encode_float(response, data.velocity_turbulize_duration);
encode_buffer(response, data.target_force_scale);
encode_buffer(response, data.target_kill_radius);
encode_float(response, data.target_max_force);
encode_buffer(response, data.target_position);
message_append(response, data.spawn_positive_x);
message_append(response, data.spawn_negative_x);
message_append(response, data.spawn_positive_y);
message_append(response, data.spawn_negative_y);
message_append(response, data.spawn_position_z);
message_append(response, data.spawn_negative_z);
message_append(response, data.spawn_velocity);
message_append(response, data.collision_triggering_group_index);
encode_float(response, data.collision_dynamic_friction);
encode_float(response, data.collision_static_friction);
encode_float(response, data.collision_restitution);
encode_float(response, data.collision_velocity_dampening);
message_append(response, data.collision_disable_gravity);
message_append(response, data.collision_use_gpu);
encode_float(response, data.collision_radius);
message_append(response, data.collision_kill_when_collide);
message_append(response, data.collision_self_emitter_index);
encode_float(response, data.collision_spawn_probability);
message_append(response, data.collision_spawn_parent_emitter_index);
encode_float(response, data.alpha_by_distance_far);
encode_float(response, data.alpha_by_distance_near);
}
static void message_emitter_details(uint16_t type, const std::vector<uint8_t> &message, const TcpMessageSender &sender) {
std::vector<uint8_t> response;
if (message.size() < 4) {
sender(2, response);
return;
}
size_t name_length = *(uint32_t*) &message[0];
if (message.size() != 4 + name_length) {
sender(2, response);
return;
}
std::string requested_name((char*) &message[4], name_length);
{
std::lock_guard<std::mutex> guard(emitter_lock);
for (const auto& it : tracked_render_emitters) {
auto address = (uint64_t) it.second.render_emitter;
std::string name = fmt::format("{:016x}h", address);
if (name == requested_name) {
response.push_back(1);
try {
encode_emitter_data(response, it.second);
break;
} catch (const std::exception& error) {
response.clear();
sender(2, response);
return;
}
}
}
}
if (response.empty()) {
response.push_back(0);
}
sender(8, response);
}
void emitters_setup(TcpServer* tcp_server, WrapperAddressSpace* wrapper_space) {
ExecutableAddressSpace space;
vtable_WParticleEmitter = (void*) space.by_offset(0x1F3F478);
vtable_WDependencyLoader = (void*) space.by_offset(0x1DDAD78);
// Registers a WParticleEmitter after it has
hook_set_emitter_register(space, wrapper_space);
// Removes dead WParticleEmitters from tracking
hook_set_emitter_destruct(space, wrapper_space);
// Registers a WRenderParticleEmitter with data from associated WParticleEmitter
hook_set_render_emitter_register(space, wrapper_space);
// Removes dead WRenderParticleEmitter from tracking
hook_set_render_emitter_destruct(space, wrapper_space);
tcp_server->add_handler(5, message_emitter_list);
tcp_server->add_handler(7, message_emitter_details);
}
typedef void (*emitter_config_parser_fn)(WMemoryFileReader* reader, WXParticleEmitterModuleData* something);
static void overwrite_all_emitters() {
std::vector<char> config;
{
std::ifstream file(R"(C:\Projects\witch\fileoverride\logx\emitter.bin)", std::ios::binary);
config.insert(config.begin(), std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}
ExecutableAddressSpace space;
auto parser = (emitter_config_parser_fn) space.by_offset(0x518AE0);
WMemoryFileReader reader {
(void*) space.by_offset(0x1CFC3E8),
0x100052,
0xA3,
(void*) space.by_offset(0x1CFC4C0),
(uint8_t*) config.data(),
config.size(),
0
};
std::lock_guard<std::mutex> guard(emitter_lock);
for (const auto& it : tracked_render_emitters) {
reader.position = 0;
parser(&reader, &it.second.render_emitter->emitter_data);
}
}
static bool last_state = false;
void emitters_loop() {
/*
bool current_state = (GetKeyState(VK_INSERT) & 0x8000) != 0;
if (current_state != last_state) {
last_state = current_state;
if (current_state) {
overwrite_all_emitters();
}
}
*/
}
<file_sep>/internal/src/logging/log.h
#pragma once
#define FMT_HEADER_ONLY
#include <spdlog/spdlog.h>
namespace logger {
void setup_logger();
std::string wide(const std::wstring& value);
std::string wide(const wchar_t* value);
template <typename T>
inline uint64_t ptr(const T *p) { return (uint64_t) p; }
extern std::shared_ptr<spdlog::logger> it;
}
<file_sep>/internal/src/bundles.h
#pragma once
#include "engine_types.h"
#include "server/tcp_server.h"
#include "memory/wrapper_address_space.h"
#include <cstdint>
#include <string>
WBundleDiskFile* bundle_file_find(uint32_t file_index);
WDiskBundle* bundle_file_identify(uint32_t file_index);
void bundle_format_file_directory(WDirectory *directory, std::wstring &path);
void bundles_setup(TcpServer* tcp_server, WrapperAddressSpace* wrapper_space);
<file_sep>/internal/src/memory/executable_address_space.h
#pragma once
#include <cstdint>
#include "../windows_api.h"
#include "wrapper_address_space.h"
#include "modifiable_code.h"
class ExecutableAddressSpace {
public:
ExecutableAddressSpace() {
base_address = (uint64_t) GetModuleHandleW(nullptr);
}
uint64_t by_offset(uint64_t offset) {
return base_address + offset;
}
ModifiableCode modify_code(uint64_t offset, uint64_t length) {
return ModifiableCode(base_address + offset, length);
}
WrapperAddressSpace create_wrapper_space() {
for (uint64_t i = 1; i < 0x200; i++) {
uint64_t offset = i * 0x10000;
if (offset >= base_address) {
break;
}
void* result = VirtualAlloc((void*) (base_address - offset), 0x10000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READ);
if (result != nullptr) {
return WrapperAddressSpace((uint64_t) result, 0x10000);
}
}
throw std::exception("Unable to find vacant memory before executable region for wrappers.");
}
uint64_t base_address;
};
<file_sep>/internal/src/logging/log.cpp
#include "log.h"
#include "../windows_api.h"
#include <Psapi.h>
#include <filesystem>
#include <time.h>
namespace fs = std::experimental::filesystem;
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/stdout_sinks.h>
#include <spdlog/async.h>
namespace logger {
static std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> wide_converter;
std::string wide(const std::wstring& value) {
return std::string(wide_converter.to_bytes(value));
}
std::string wide(const wchar_t* value) {
return std::string(wide_converter.to_bytes(value));
}
static void setup_logger_throw() {
HMODULE module;
wchar_t dll_path_raw[MAX_PATH];
if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR) &it, &module)) {
throw std::exception("Could not get self module.");
} else if (GetModuleFileNameW(module, dll_path_raw, sizeof(dll_path_raw)) == 0) {
throw std::exception("Could not get self module path.");
}
fs::path path(dll_path_raw);
fs::path log_directory = fs::absolute(path.parent_path().parent_path() / "log");
std::error_code creation_error;
if (!fs::create_directories(log_directory, creation_error)) {
if (creation_error.value() != 0) {
throw std::exception("Failed to create logs directory.");
}
}
fs::path log_file = log_directory / ("debug_" + std::to_string(time(nullptr)) + ".log");
auto currentLog = spdlog::create_async_nb<spdlog::sinks::basic_file_sink_mt>("main", log_file.string());
spdlog::flush_every(std::chrono::seconds(2));
currentLog->flush_on(spdlog::level::warn);
currentLog->set_level(spdlog::level::trace);
it = std::move(currentLog);
}
void setup_logger() {
try {
setup_logger_throw();
} catch (const std::exception& e) {
MessageBoxA(nullptr, e.what(), "Log initialization error.", MB_OK);
it->error("Log initialization failed: {}", e.what());
}
}
static std::shared_ptr<spdlog::logger> primordial_logger() {
return spdlog::stdout_logger_mt("primordial");
}
std::shared_ptr<spdlog::logger> it = primordial_logger();
}
<file_sep>/internal/src/memory/wrapper_address_space.h
#pragma once
#include <cstdint>
#include "modifiable_code.h"
class WrapperAddressSpace {
public:
WrapperAddressSpace(uint64_t base_address, size_t length) {
this->base_address = base_address;
this->unused_offset = 0;
this->length = length;
}
WrapperAddressSpace(WrapperAddressSpace&& other) noexcept {
base_address = other.base_address;
unused_offset = other.unused_offset;
length = other.length;
other.base_address = 0;
}
~WrapperAddressSpace() {
if (base_address != 0) {
VirtualFree((void*) base_address, 0, MEM_RELEASE);
base_address = 0;
}
}
ModifiableCode reserve(size_t segment_length) {
if (base_address == 0 || unused_offset + segment_length > length) {
throw std::exception("Wrapper address space is exhausted");
}
ModifiableCode code(base_address + unused_offset, segment_length);
unused_offset += segment_length;
return code;
}
private:
uint64_t base_address;
size_t unused_offset;
size_t length;
};
<file_sep>/CMakeLists.txt
cmake_minimum_required (VERSION 3.13)
project (sandbox)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /Zi")
set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /DEBUG /OPT:REF /OPT:ICF")
include(${CMAKE_ROOT}/Modules/FetchContent.cmake)
set(DEPENDENCY_DIR "${PROJECT_SOURCE_DIR}/dependencies")
FetchContent_Populate(spdlog SOURCE_DIR ${DEPENDENCY_DIR}/spdlog
GIT_REPOSITORY https://github.com/gabime/spdlog.git
GIT_TAG 74dbf4cf702b49c98642c9afe74d114a238a6a07
)
add_subdirectory (launcher)
add_subdirectory (internal)
<file_sep>/launcher/src/main.cpp
#include <Windows.h>
#include <Psapi.h>
#include <atomic>
#include <string>
typedef HRESULT (*fn_DirectInput8Create) (HINSTANCE moduleInstance, DWORD version, REFIID desiredInterface,
LPVOID* result, LPUNKNOWN interfaceAggregation);
typedef void (*fn_GetStartupInfoW) (STARTUPINFOW* startup_info_out);
typedef void (*fn_initialize_mod) ();
class DllLoader;
static DllLoader* global_loader;
class DllLoader {
public:
void preload() {
HMODULE original_library = LoadLibraryW(L"C:\\Windows\\System32\\dinput8.dll");
original_DirectInput8Create = (fn_DirectInput8Create) GetProcAddress(original_library, "DirectInput8Create");
original_GetStartupInfoW = (fn_GetStartupInfoW) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetStartupInfoW");
auto module_data = (uint8_t*) GetModuleHandleW(nullptr);
auto headers_dos = (IMAGE_DOS_HEADER*) &module_data[0];
auto headers_nt = (IMAGE_NT_HEADERS*) &module_data[headers_dos->e_lfanew];
IMAGE_DATA_DIRECTORY& imports_entry = headers_nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
auto import_dlls = (IMAGE_IMPORT_DESCRIPTOR*) &module_data[imports_entry.VirtualAddress];
size_t import_dll_count = imports_entry.Size / sizeof(*import_dlls) - 1;
for (size_t i = 0; i < import_dll_count; i++) {
auto dll_name = (const char*) &module_data[import_dlls[i].Name];
if (_stricmp(dll_name, "kernel32.dll") == 0) {
auto functions = (uintptr_t*) &module_data[import_dlls[i].FirstThunk];
auto functions_end = (uintptr_t*) &module_data[import_dlls[i + 1].FirstThunk];
size_t function_count = functions_end - functions;
for (size_t j = 0; j < function_count; j++) {
if (functions[j] == (uintptr_t) original_GetStartupInfoW) {
DWORD previous_flags;
VirtualProtect(&functions[j], 0x08, PAGE_READWRITE, &previous_flags);
functions[j] = (uintptr_t) DllLoader::static_hooked_GetStartupInfoW;
VirtualProtect(&functions[j], 0x08, previous_flags, &previous_flags);
}
}
}
}
}
void check_load() {
bool expected = false;
if (loaded.compare_exchange_strong(expected, true)) {
load();
}
}
fn_DirectInput8Create get_original_dinput8() {
check_load();
return original_DirectInput8Create;
}
private:
void load() {
load_mods_dlls(get_mods_directory());
}
void load_mods_dlls(const std::wstring& mods_directory) {
WIN32_FIND_DATAW find_item;
std::wstring search_pattern = mods_directory + L"*";
HANDLE find_handle = FindFirstFileW(search_pattern.c_str(), &find_item);
bool has_entry = find_handle != INVALID_HANDLE_VALUE;
while (has_entry) {
if ((find_item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 && _wcsnicmp(find_item.cFileName, L"mod", 3) == 0) {
load_mod_dlls(mods_directory + find_item.cFileName);
}
has_entry = FindNextFileW(find_handle, &find_item);
}
FindClose(find_handle);
}
void load_mod_dlls(std::wstring mod_directory) {
mod_directory.append(L"\\dlls\\");
std::wstring search_pattern = mod_directory + L"*";
WIN32_FIND_DATAW item;
HANDLE handle = FindFirstFileW(search_pattern.c_str(), &item);
bool has_entry = handle != INVALID_HANDLE_VALUE;
while (has_entry) {
if ((item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 && wcslen(item.cFileName) >= 5 &&
_wcsnicmp(&item.cFileName[wcslen(item.cFileName) - 4], L".dll", 4) == 0) {
std::wstring dll_path = mod_directory + item.cFileName;
HMODULE module = LoadLibraryW(dll_path.c_str());
if (module != nullptr) {
auto initializer = (fn_initialize_mod) GetProcAddress(module, "InitializeMod");
if (initializer != nullptr) {
initializer();
}
}
}
has_entry = FindNextFileW(handle, &item);
}
FindClose(handle);
}
std::wstring get_mods_directory() {
std::wstring path(get_executable_path());
if (path.empty()) {
return L"";
}
auto position = path.find_last_of('\\');
if (position == std::wstring::npos) {
return L"";
}
path.resize(position + 1);
path.append(L"..\\..\\Mods\\");
wchar_t resolved_path[4096];
if (GetFullPathNameW(path.c_str(), 4096, resolved_path, nullptr) == 0) {
return L"";
}
return resolved_path;
}
std::wstring get_executable_path() {
wchar_t exe_full_path[4096];
if (GetModuleFileNameW(GetModuleHandleW(nullptr), exe_full_path, 4096)) {
return exe_full_path;
} else {
return L"";
}
}
void hooked_GetStartupInfoW(STARTUPINFOW* startup_info_out) {
check_load();
original_GetStartupInfoW(startup_info_out);
}
static void static_hooked_GetStartupInfoW(STARTUPINFOW* startup_info_out) {
global_loader->hooked_GetStartupInfoW(startup_info_out);
}
std::atomic<bool> loaded { false };
fn_GetStartupInfoW original_GetStartupInfoW = nullptr;
fn_DirectInput8Create original_DirectInput8Create = nullptr;
};
extern "C" __declspec(dllexport) HRESULT DirectInput8Create(
HINSTANCE moduleInstance, DWORD version, REFIID desiredInterface, LPVOID* result, LPUNKNOWN interfaceAggregation) {
return global_loader->get_original_dinput8()(moduleInstance, version, desiredInterface, result, interfaceAggregation);
}
std::atomic<bool> preloaded { false };
BOOL APIENTRY DllMain(HANDLE dllInstanceHandle, DWORD callReason, LPVOID reserved) {
if (callReason == DLL_PROCESS_ATTACH) {
bool expected = false;
if (preloaded.compare_exchange_strong(expected, true)) {
global_loader = new DllLoader;
global_loader->preload();
}
}
return TRUE;
}
<file_sep>/internal/src/engine_types.cpp
#include "engine_types.h"
<file_sep>/internal/src/engine_types.h
#pragma once
#include <cstdint>
#define _pad(x,y) uint8_t x[y]
#pragma pack(push, 1)
struct WXString {
/* 000h */ char* text;
// Including null terminator
/* 008h */ uint32_t buffer_length;
/* 00Ch SIZE */
};
struct WXWideString {
/* 000h */ wchar_t* text;
// Including null terminator
/* 008h */ uint32_t buffer_length;
/* 00Ch SIZE */
};
template <typename T>
struct WXSortedListEntry {
/* 000h */ uint32_t maybe_hash;
/* 004h */ _pad(p004, 0x04);
/* 008h */ T* value;
/* 010h SIZE */
};
template <typename T>
struct WXSortedList {
// Capacity is determined with an equivalent to msize
/* 000h */ WXSortedListEntry<T>* entries;
/* 008h */ uint32_t count;
/* 00Ch */ uint8_t is_dirty;
/* 00Dh */ _pad(p00D, 0x03);
/* 010h SIZE */
};
struct WBundleDiskFile;
struct WDirectory {
/* 000h */ void* vtable;
/* 008h */ WXSortedList<WBundleDiskFile> files;
/* 018h */ WXSortedList<WDirectory> children;
/* 028h */ WDirectory* parent;
/* 030h */ WXWideString name;
/* 03Ch */ _pad(p03C, 0x14);
/* 050h SIZE */
};
struct WBundleDiskFile {
/* 000h */ void* vtable;
/* 008h */ WDirectory* directory;
/* 010h */ void* whatever;
/* 018h */ WXWideString file_name;
/* 024h */ _pad(p024, 0x1C);
/* 040h */ uint32_t file_index;
/* 044h */
};
struct WXVector3 {
/* 000h */ float x;
/* 004h */ float y;
/* 008h */ float z;
/* 00Ch SIZE */
};
struct WXVector2 {
/* 000h */ float x;
/* 004h */ float y;
/* 008h SIZE */
};
template <typename T>
struct WXBuffer {
/* 000h */ T* data;
/* 008h */ uint32_t length;
/* 00Ch SIZE */
};
struct WXParticleEmitterModuleData {
// CParticleInitializerAlpha
/* 000h */ WXBuffer<float> alpha;
// CParticleInitializerColor
/* 00Ch */ WXBuffer<WXVector3> color;
// CParticleInitializerLifeTime
/* 018h */ WXBuffer<float> lifetime;
// CParticleInitializerPosition
/* 024h */ WXBuffer<WXVector3> position;
/* 030h */ float position_offset;
// CParticleInitializerRotation
/* 034h */ WXBuffer<float> rotation;
// CParticleInitializerRotation3D
/* 040h */ WXBuffer<WXVector3> rotation_3d;
// CParticleInitializerRotationRate
/* 04Ch */ WXBuffer<float> rotation_rate;
// CParticleInitializerRotationRate3D
/* 058h */ WXBuffer<WXVector3> rotation_rate_3d;
// CParticleInitializerSize and CParticleInitializerSize3d
/* 064h */ WXBuffer<WXVector2> size;
/* 070h */ WXBuffer<WXVector3> size_3d;
/* 07Ch */ uint8_t size_keep_ratio;
/* 07Dh */ _pad(p07D, 3);
// CParticleInitializerSpawnBox and CParticleInitializerSpawnCircle
/* 080h */ WXBuffer<WXVector3> spawn_extents;
/* 08Ch */ WXBuffer<float> spawn_inner_radius;
/* 098h */ WXBuffer<float> spawn_outer_radius;
/* 0A4h */ uint8_t spawn_world_space;
/* 0A5h */ uint8_t spawn_surface_only;
/* 0A6h */ _pad(p0A6, 2);
/* 0A8h */ WXVector3 p0A8;
/* 0B4h */ _pad(p0B4, 12);
/* 0C0h */ float spawn_to_local_matrix[16];
/* 100h */ uint8_t spawn_positive_x;
/* 101h */ uint8_t spawn_negative_x;
/* 102h */ uint8_t spawn_positive_y;
/* 103h */ uint8_t spawn_negative_y;
/* 104h */ uint8_t spawn_position_z;
/* 105h */ uint8_t spawn_negative_z;
/* 106h */ uint8_t spawn_velocity;
/* 107h */ _pad(p107, 1);
// CParticleInitializerVelocity
/* 108h */ WXBuffer<WXVector3> velocity;
/* 114h */ uint8_t velocity_world_space;
/* 115h */ _pad(p115, 3);
/* 118h */ WXBuffer<float> velocity_inherit_scale;
/* 124h */ WXBuffer<float> velocity_spread_scale;
/* 130h */ uint8_t velocity_spread_conserve_momentum;
/* 131h */ _pad(p131, 3);
/* 134h */ WXBuffer<float> texture_animation_initial_frame;
/* 140h */ uint32_t p140; // or float
/* 144h */ uint32_t p144; // or float
/* 148h */ uint32_t p148; // or float
// CParticleModificatorVelocityOverLife (modulate defined by flags, absolute unspecified?)
/* 14Ch */ WXBuffer<WXVector3> velocity_over_life;
// CParticleModificatorAcceleration (world_space defined by flags)
/* 158h */ WXBuffer<WXVector3> acceleration_direction;
/* 164h */ WXBuffer<float> acceleration_scale;
// CParticleModificatorRotationOverLife (modulate defined by flags)
/* 170h */ WXBuffer<float> rotation_over_life;
// CParticleModificatorRotationRateOverLife (modulate defined by flags)
/* 17Ch */ WXBuffer<float> rotation_rate_over_life;
// CParticleModificatorRotation3DOverLife (modulate defined by flags)
/* 188h */ WXBuffer<WXVector3> rotation_3d_over_life;
// CParticleModificatorRotationRate3DOverLife
/* 194h */ WXBuffer<WXVector3> rotation_rate_3d_over_life;
// CParticleModificatorColorOverLife (modulate defined by flags)
/* 1A0h */ WXBuffer<WXVector3> color_over_life;
// CParticleModificatorAlphaOverLife (modulate defined by flags)
/* 1ACh */ WXBuffer<float> alpha_over_life;
// CParticleModificatorSizeOverLife / CParticleModificatorSize3DOverLife (modulate defined by flags)
/* 1B8h */ WXBuffer<WXVector2> size_over_life;
// ... if drawer is CParticleDrawerEmitterOrientation (in compact, defined by flags)
/* 1C4h */ WXBuffer<WXVector3> size_over_life_orientation;
// CParticleModificatorTextureAnimation (initial frame is... missing? animation mode is defined by flags)
/* 1D0h */ WXBuffer<float> texture_animation_speed;
// CParticleModificatorVelocityTurbulize
/* 1DCh */ WXBuffer<WXVector3> velocity_turbulize_scale;
/* 1E8h */ WXBuffer<float> velocity_turbulize_timelife_limit;
/* 1F4h */ float velocity_turbulize_noise_interval;
/* 1F8h */ float velocity_turbulize_duration;
// CParticleModificatorTarget and CParticleModificatorTargetNode (which is applied defined by flags)
/* 1FCh */ WXBuffer<float> target_force_scale;
/* 208h */ WXBuffer<float> target_kill_radius;
/* 214h */ float target_max_force;
/* 218h */ WXBuffer<WXVector3> target_position;
/* 224h */ float collision_spawn_probability;
/* 228h */ uint32_t collision_spawn_parent_emitter_index;
/* 22Ch */ _pad(p22C, 4);
/* 230h */ uint64_t collision_triggering_group_index;
/* 238h */ float collision_dynamic_friction;
/* 23Ch */ float collision_static_friction;
/* 240h */ float collision_restitution;
/* 244h */ float collision_velocity_dampening;
/* 248h */ uint8_t collision_disable_gravity;
/* 249h */ uint8_t collision_use_gpu;
/* 24Ah */ _pad(p24A, 2);
/* 24Ch */ float collision_radius;
/* 250h */ uint8_t collision_kill_when_collide;
/* 251h */ _pad(p251, 3);
/* 254h */ uint32_t collision_self_emitter_index;
// CParticleModificatorAlphaByDistance
/* 258h */ float alpha_by_distance_far;
/* 25Ch */ float alpha_by_distance_near;
/* 260h SIZE */
};
struct WRenderParticleEmitter {
/* 000h */ _pad(p000, 0x10);
/* 010h */ WXParticleEmitterModuleData emitter_data;
/* 270h */ _pad(p270, 0x74);
/* 2E4h */ uint32_t modificator_bitset;
/* 2E8h */ _pad(p2E8, 0x0C);
/* 2F4h */ uint32_t initializer_bitset;
/* 2F8h */
};
struct WName {
/* 000h */ uint32_t offset;
/* 004h SIZE */
};
struct WBundleDataHandleReader {
/* 000h */ void* vtable_one;
/* 008h */ uint32_t hardcoded_0A;
/* 00Ch */ uint32_t hardcoded_A3;
/* 010h */ void* vtable_two;
/* 018h */ void* p018;
/* 020h */ WXBuffer<uint8_t>* buffer;
/* 028h */ uint32_t read_cursor;
/* 02Ch */ uint32_t read_limit;
/* 030h */
};
struct WMemoryFileReader {
/* 000h */ void* vtable_one;
/* 008h */ uint32_t hardcoded_100052;
/* 00Ch */ uint32_t hardcoded_A3;
/* 010h */ void* vtable_two;
/* 018h */ uint8_t* buffer;
/* 020h */ uint64_t size;
/* 028h */ uint64_t position;
/* 030h SIZE */
};
struct WXBundleFileMapping {
/* 000h */ _pad(p000, 0x10);
/* 010h */ uint32_t file_id;
/* 014h */ _pad(p014, 0x0C);
/* 020h SIZE */
};
struct WXBitSet {
/* 000h */ uint32_t* words;
/* 008h */ uint32_t word_count;
/* 00Ch */ uint32_t bit_count;
/* 010h SIZE */
};
struct WXBundleFileLocation {
/* 000h */ uint32_t file_index;
/* 004h */ uint32_t bundle_index;
/* 008h */ uint32_t p008;
/* 00Ch */ uint32_t p00C;
/* 010h */ uint32_t fallback_file_id_maybe;
/* 014h SIZE */
};
struct WXBundleFileIndex {
/* 000h */ _pad(p000, 0x30);
/* 030h */ WXBundleFileMapping* mappings;
/* 038h */ uint32_t mapping_count;
/* 03Ch */ WXBundleFileLocation* locations;
};
struct WDiskBundle {
/* 000h */ void* vtable;
/* 008h */ WXString name;
/* 014h */ WXString relative_path;
/* 020h */ uint32_t index;
/* 024h */ _pad(p024, 0x0C);
/* 030h */ WXWideString absolute_path;
/* 03Ch */
};
struct WXBundleManager {
/* 000h */ _pad(p000, 0x10);
/* 010h */ WXBundleFileIndex* file_index;
/* 018h */ WXBitSet bundle_bitset_1;
/* 028h */ WXBitSet bundle_bitset_2;
/* 038h */ WXBitSet bundle_bitset_3;
/* 048h */ _pad(p048, 0x08);
/* 050h */ WDiskBundle** bundles;
/* 058h */ int32_t bundle_count;
/* 05Ch */ WBundleDiskFile** files;
/* 064h */ int32_t file_count;
/* 068h */
};
struct WDepot {
/* 000h */ WDirectory base;
/* 050h */ void* vtable_two;
/* 058h */ _pad(p058, 0x100);
/* 158h */ WXBundleManager* bundle_manager;
/* 160h */
};
typedef void WIRTTIType;
struct WIReferencable {
/* 000h */ void* vtable;
/* 008h */ void* something;
/* 010h SIZE */
};
struct WISerializable {
};
struct WProperty {
/* 000h */ void* vtable;
/* 008h */ WIRTTIType* rtti_type;
/* 010h */ _pad(p008, 0x10);
/* 020h */ uint32_t offset;
/* 024h */ uint32_t flags;
/* 028h */ _pad(p028, 0x08);
/* 030h SIZE */
};
struct WParticleEmitter {
/* 000h */ void* vtable_one;
/* 008h */ _pad(p008, 0x110);
/* 118h SIZE */
};
struct WDependencyLoader {
/* 000h */ void* vtable_one;
/* 008h */ _pad(p008, 0x10);
/* 018h */ WBundleDiskFile* file;
/* 020h */
};
#pragma pack(pop)
<file_sep>/internal/src/emitters.h
#pragma once
#include "memory/wrapper_address_space.h"
#include "server/tcp_server.h"
void emitters_setup(TcpServer* tcp_server, WrapperAddressSpace* wrapper_space);
void emitters_loop();
<file_sep>/launcher/CMakeLists.txt
add_library(launcher SHARED
src/main.cpp
)
<file_sep>/internal/src/main.cpp
#include "memory/wrapper_address_space.h"
#include "server/tcp_server.h"
#include "emitters.h"
#include "logging/log.h"
#include "memory/executable_address_space.h"
#include "bundles.h"
static WrapperAddressSpace* wrapper_space;
static TcpServer* tcp_server;
static void loop_hook() {
emitters_loop();
}
extern "C" __declspec(dllexport) void InitializeMod() {
logger::setup_logger();
logger::it->info("Beginning initialization");
tcp_server = tcp_server_create(3548);
tcp_server->start();
ExecutableAddressSpace space;
wrapper_space = new WrapperAddressSpace(space.create_wrapper_space());
emitters_setup(tcp_server, wrapper_space);
bundles_setup(tcp_server, wrapper_space);
{
ModifiableCode wrapper = wrapper_space->reserve(0x40);
// mov rax, loop_hook
wrapper.bytes({ 0x48, 0xB8 });
wrapper.u64((uint64_t) loop_hook);
// call rax
wrapper.bytes({ 0xFF, 0xD0 });
// mov rax, [rbx]
wrapper.bytes({ 0x48, 0x8B, 0x03 });
// mov rcx, rbx
wrapper.bytes({ 0x48, 0x8B, 0xCB });
// jmp 1400446B6
wrapper.bytes({ 0xE9 });
wrapper.offset32(space.by_offset(0x446B6));
ModifiableCode hook = space.modify_code(0x446B0, 0x06);
hook.bytes({ 0xE9 });
hook.offset32((uint64_t) wrapper.address);
hook.bytes({ 0x90 });
}
{
*(uint32_t*) space.by_offset(0x2CB4C20) = 0x200;
}
}
<file_sep>/internal/CMakeLists.txt
add_library(internal SHARED
src/main.cpp
src/engine_types.h
src/engine_types.cpp
src/memory/modifiable_code.h
src/memory/wrapper_address_space.h
src/memory/executable_address_space.h
src/server/message_builder.h
src/server/tcp_server.cpp
src/server/tcp_server.h
src/logging/log.cpp
src/logging/log.h
src/emitters.cpp
src/emitters.h
src/bundles.cpp
src/bundles.h
)
target_include_directories(internal PRIVATE ${PROJECT_SOURCE_DIR}/dependencies/spdlog/include)
target_link_libraries(internal ws2_32)
target_compile_options(internal PRIVATE /MT)
<file_sep>/internal/src/memory/modifiable_code.h
#pragma once
#include <cstdint>
#include <exception>
#include "../windows_api.h"
class ModifiableCode {
public:
ModifiableCode(uint64_t address, uint64_t length) {
this->address = (uint8_t*) address;
this->length = length;
this->write_offset = 0;
VirtualProtect((void*) this->address, this->length, PAGE_READWRITE, (DWORD*) &previous_protection);
}
ModifiableCode(ModifiableCode&& other) noexcept {
address = other.address;
length = other.length;
previous_protection = other.previous_protection;
write_offset = other.write_offset;
other.address = nullptr;
}
~ModifiableCode() {
if (this->address != nullptr) {
VirtualProtect((void *) this->address, this->length, previous_protection, (DWORD *) &previous_protection);
}
}
void bytes(std::initializer_list<uint8_t> bytes) {
check_writable(bytes.size());
for (uint8_t byte : bytes) {
address[write_offset++] = byte;
}
}
void u32(uint32_t value) {
check_writable(sizeof(uint32_t));
*(uint32_t*) (&address[write_offset]) = value;
write_offset += sizeof(uint32_t);
}
void u64(uint64_t value) {
check_writable(sizeof(uint64_t));
*(uint64_t*) (&address[write_offset]) = value;
write_offset += sizeof(uint64_t);
}
void offset32(uint64_t target) {
uint64_t source = ((uint64_t) address) + write_offset + 4;
u32((uint32_t) (target - source));
}
uint8_t* address;
private:
void check_writable(size_t byte_count) {
if (byte_count + write_offset > length) {
throw std::exception("Writing out of bounds of modifiable region.");
}
}
uint64_t length;
uint32_t previous_protection {};
uint64_t write_offset;
};
<file_sep>/internal/src/server/message_builder.h
#pragma once
#include <vector>
#include <cstdint>
#include "../logging/log.h"
template <class Type>
std::vector<uint8_t>& message_append(std::vector<uint8_t>& message, const Type& value) {
auto value_array = reinterpret_cast<const uint8_t*>(&value);
message.insert(message.end(), value_array, value_array + sizeof(value));
return message;
}
std::vector<uint8_t>& message_append(std::vector<uint8_t>& message, const void* value, size_t length) {
auto value_array = reinterpret_cast<const uint8_t*>(value);
message.insert(message.end(), value_array, value_array + length);
return message;
}
std::vector<uint8_t>& message_append_string(std::vector<uint8_t>& message, const std::string& string) {
uint32_t length = string.length();
message_append(message, length);
message_append(message, string.c_str(), length);
return message;
}
std::vector<uint8_t>& message_append_string(std::vector<uint8_t>& message, const std::wstring& string) {
return message_append_string(message, logger::wide(string));
}
<file_sep>/internal/src/server/tcp_server.h
#pragma once
#include <stdint.h>
#include <functional>
typedef std::function<bool(uint16_t, const std::vector<uint8_t>&)> TcpMessageSender;
typedef std::function<void(uint16_t, const std::vector<uint8_t>&, const TcpMessageSender&)> TcpMessageHandler;
class TcpServer {
public:
virtual ~TcpServer() = default;
virtual void add_handler(uint16_t type, TcpMessageHandler handler) = 0;
virtual void start() = 0;
};
TcpServer* tcp_server_create(int16_t port);
<file_sep>/internal/src/server/tcp_server.cpp
#include <utility>
#include "tcp_server.h"
#include "../logging/log.h"
#include <thread>
#include <mutex>
#include <WinSock2.h>
class OnLeave {
public:
explicit OnLeave (std::function<void()> function) : function(std::move(function)) {
}
~OnLeave () {
function();
}
private:
std::function<void ()> function;
};
class ActualTcpServer : public TcpServer {
public:
explicit ActualTcpServer(uint16_t port): port(port), stop_event(nullptr) {
std::lock_guard<std::mutex> guard(mutex);
stop_event = CreateEventW(nullptr, true, false, nullptr);
}
~ActualTcpServer() override {
std::unique_lock<std::mutex> guard(mutex);
SetEvent(stop_event);
while(thread_count > 0) {
condition.wait(guard);
}
}
void add_handler(uint16_t type, TcpMessageHandler handler) override {
logger::it->error("TCP server: registering handler for message type {}.", type);
std::lock_guard<std::mutex> guard(mutex);
handlers[type] = handler;
}
void start() override {
std::lock_guard<std::mutex> guard(mutex);
if (!started) {
logger::it->info("TCP server: starting on port {}.", port);
started = true;
if (!try_start_thread(std::bind(&ActualTcpServer::accept_handler, this))) {
logger::it->error("TCP server: failed to start accept thread.");
}
} else {
logger::it->error("TCP server: already started, not starting.");
}
}
private:
bool try_start_thread(std::function<void(void)>&& function) {
thread_count++;
try {
std::thread thread(function);
thread.detach();
return true;
} catch (const std::system_error& error) {
thread_count--;
return false;
}
}
bool try_start_thread_lock(std::function<void(void)>&& function) {
std::lock_guard<std::mutex> guard(mutex);
return try_start_thread(std::move(function));
}
void end_thread() {
std::lock_guard<std::mutex> guard(mutex);
thread_count--;
condition.notify_all();
}
void accept_handler() {
uint32_t handle = UINT32_MAX;
void* accept_event = nullptr;
SetThreadDescription(GetCurrentThread(), L"TCP server accept thread");
OnLeave exit([this, &handle, &accept_event] {
logger::it->debug("TCP server: accept thread shutting down.");
if (handle != UINT32_MAX) {
closesocket(handle);
}
if (accept_event != nullptr) {
WSACloseEvent(accept_event);
}
end_thread();
});
logger::it->debug("TCP server: creating listen socket.");
handle = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, 0);
if (handle == UINT32_MAX) {
WSADATA startup_data;
WSAStartup(MAKEWORD(2,2), &startup_data);
handle = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, 0);
if (handle == UINT32_MAX) {
logger::it->debug("TCP server: failed to create listen socket.");
return;
}
}
if (!socket_configure(handle)) {
logger::it->debug("TCP server: failed to set listen socket to non-blocking.");
return;
}
sockaddr_in bind_address{};
bind_address.sin_family = AF_INET,
bind_address.sin_port = htons(port),
bind_address.sin_addr.s_addr = INADDR_ANY;
if (bind(handle, (sockaddr*) &bind_address, sizeof(bind_address)) == SOCKET_ERROR) {
logger::it->debug("TCP server: failed to bind listen socket.");
return;
}
if (listen(handle, SOMAXCONN) == SOCKET_ERROR) {
logger::it->debug("TCP server: failed to listen on listen socket.");
return;
}
accept_event = WSACreateEvent();
if (accept_event == WSA_INVALID_EVENT) {
logger::it->error("TCP server: failed to create accept event object.");
return;
} else if (WSAEventSelect(handle, accept_event, FD_ACCEPT | FD_CLOSE) == SOCKET_ERROR) {
logger::it->error("TCP server: failed to configure accept event object.");
return;
}
void* events[2] = { stop_event, accept_event };
logger::it->debug("TCP server: beginning accept loop.");
while (true) {
uint32_t result = WSAWaitForMultipleEvents(2, events, false, 30000, false);
if (result == WSA_WAIT_TIMEOUT) {
logger::it->debug("TCP server: accept thread still alive.");
continue;
} else if (result == WSA_WAIT_EVENT_0) {
logger::it->debug("TCP server: accept thread stopping as requested.");
return;
} else if (result == WSA_WAIT_FAILED) {
logger::it->error("TCP server: accept wait failed, aborting.");
return;
}
WSANETWORKEVENTS fired_events;
if (WSAEnumNetworkEvents(handle, accept_event, &fired_events) == SOCKET_ERROR) {
logger::it->error("TCP server: accept event enumeration failed, aborting.");
return;
} else if ((fired_events.lNetworkEvents & FD_CLOSE) != 0) {
logger::it->error("TCP server: accept socket closed, aborting.");
return;
} else if ((fired_events.lNetworkEvents & FD_ACCEPT) != 0) {
uint32_t peer = WSAAccept(handle, nullptr, nullptr, nullptr, 0);
if (peer != UINT32_MAX) {
logger::it->debug("TCP server: accepting a new connection.");
if (!try_start_thread_lock(std::bind(&ActualTcpServer::peer_handler, this, peer))) {
logger::it->error("TCP server: failed to create peer socket thread.");
closesocket(peer);
}
} else {
logger::it->warn("TCP server: did not find anything to accept.");
}
}
}
}
void peer_handler(uint32_t peer) {
void* io_event = nullptr;
SetThreadDescription(GetCurrentThread(), L"TCP server peer thread");
OnLeave exit([this, peer, &io_event] {
logger::it->debug("TCP server: peer thread shutting down.");
if (io_event != nullptr) {
WSACloseEvent(io_event);
}
closesocket(peer);
end_thread();
});
if (!socket_configure(peer)) {
logger::it->debug("TCP server: failed to set peer socket to non-blocking.");
return;
}
io_event = WSACreateEvent();
WSAEventSelect(peer, io_event, FD_READ | FD_WRITE | FD_CLOSE);
std::vector<uint8_t> header;
header.resize(6);
bool success = true;
TcpMessageSender sender = [this, peer, io_event, &header, &success] (uint16_t type, const std::vector<uint8_t>& message) -> bool {
logger::it->debug("TCP server: sending response message: type {}, length {}.", type, message.size());
*(uint16_t*) &header[0] = type;
*(uint32_t*) &header[2] = message.size();
success = peer_write(peer, io_event, header) && peer_write(peer, io_event, message);
return success;
};
std::vector<uint8_t> unknown_response;
std::vector<uint8_t> message_body;
while (peer_read(peer, io_event, header)) {
uint16_t message_type = *(uint16_t*) &header[0];
uint32_t message_length = *(uint32_t*) &header[2];
logger::it->debug("TCP server: received message header: type {}, length {}.", message_type, message_length);
if (message_length > 0x100000) {
logger::it->error("TCP server: message length too high, aborting connection.");
return;
}
message_body.resize(message_length);
if (!peer_read(peer, io_event, message_body)) {
logger::it->debug("TCP server: message body not read, closing peer.");
return;
}
TcpMessageHandler* handler;
auto it = handlers.find(message_type);
if (it == handlers.end()) {
unknown_response.resize(2);
*(uint16_t*) &unknown_response[0] = message_type;
sender(1, unknown_response);
} else {
it->second(message_type, message_body, sender);
}
if (!success) {
logger::it->debug("TCP server: message sending not performed, closing peer.");
return;
}
}
logger::it->debug("TCP server: message header not read, closing peer.");
}
bool socket_configure(uint32_t handle) {
u_long non_blocking = 1;
return ioctlsocket(handle, FIONBIO, &non_blocking) != SOCKET_ERROR;
}
bool network_wait(uint32_t peer, void* io_event) {
void* events[] = { stop_event, io_event };
uint32_t result = WSAWaitForMultipleEvents(2, events, false, WSA_INFINITE, false);
if (result == WSA_WAIT_EVENT_0) {
logger::it->debug("TCP server: on network wait, detected stop instruction.");
return false;
} else if (result == WSA_WAIT_FAILED) {
logger::it->error("TCP server: on network wait, received wait failure.");
return false;
}
WSANETWORKEVENTS fired_events;
if (WSAEnumNetworkEvents(peer, io_event, &fired_events) == SOCKET_ERROR) {
logger::it->error("TCP server: on network wait, failed to enumerate events.");
return false;
} else if ((fired_events.lNetworkEvents & FD_CLOSE) != 0) {
logger::it->warn("TCP server: on network wait, detected socket close.");
return false;
}
return true;
}
bool peer_read(uint32_t peer, void* io_event, std::vector<uint8_t>& buffer) {
size_t total_received = 0;
while (total_received < buffer.size()) {
int32_t received = recv(peer, (char*) &buffer[total_received], buffer.size() - total_received, 0);
if (received == 0) {
logger::it->debug("TCP server: on peer read, detected close via recv.");
return false;
} else if (received == SOCKET_ERROR) {
int32_t last_error = WSAGetLastError();
if (last_error == WSAEWOULDBLOCK) {
if (!network_wait(peer, io_event)) {
return false;
}
}
} else {
total_received += received;
}
}
return true;
}
bool peer_write(uint32_t peer, void* io_event, const std::vector<uint8_t>& buffer) {
size_t total_sent = 0;
while (total_sent < buffer.size()) {
int32_t sent = send(peer, (const char*) &buffer[total_sent], buffer.size() - total_sent, 0);
if (sent == SOCKET_ERROR) {
int32_t last_error = WSAGetLastError();
if (last_error == WSAEWOULDBLOCK) {
if (!network_wait(peer, io_event)) {
return false;
}
}
} else {
total_sent += sent;
}
}
return true;
}
std::mutex mutex;
std::condition_variable condition;
bool started = false;
uint32_t thread_count = 0;
void* stop_event;
std::unordered_map<uint16_t, TcpMessageHandler> handlers;
int port;
};
TcpServer* tcp_server_create(int16_t port) {
return new ActualTcpServer(port);
}
| 5870419a65e98512c30102b250614c7379099c38 | [
"Markdown",
"C",
"CMake",
"C++"
] | 20 | Markdown | sedmelluq/witcher-sandbox | 4c1a3d1c4d2fc3a1d38c5e63de38db1fee720d3b | 92c59bed32b854c3aa631376b5caf2dc1af37df3 | |
refs/heads/master | <file_sep>package com.example.a10012756.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class MainActivity extends AppCompatActivity {
Button buttonOne;
Button buttonTwo;
Button buttonThree;
Button buttonFour;
Button buttonFive;
Button buttonSix;
Button buttonSeven;
Button buttonEight;
Button buttonNine;
Button buttonZero;
Button buttonPlus;
Button buttonMinus;
Button buttonMultiply;
Button buttonDivide;
Button buttonClear;
Button buttonEquals;
TextView output;
ArrayList<String> list = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOne = findViewById(R.id.ID_Button1);
buttonTwo = findViewById(R.id.ID_Button2);
buttonThree = findViewById(R.id.ID_Button3);
buttonFour = findViewById(R.id.ID_Button4);
buttonFive = findViewById(R.id.ID_Button5);
buttonSix = findViewById(R.id.ID_Button6);
buttonSeven = findViewById(R.id.ID_Button7);
buttonEight = findViewById(R.id.ID_Button8);
buttonNine = findViewById(R.id.ID_Button9);
buttonZero = findViewById(R.id.ID_Button0);
buttonPlus = findViewById(R.id.ID_PlusSign);
buttonMinus = findViewById(R.id.ID_MinusSign);
buttonMultiply = findViewById(R.id.ID_MultiplySign);
buttonDivide = findViewById(R.id.ID_DivisionSign);
buttonClear = findViewById(R.id.ID_Clear);
buttonEquals = findViewById(R.id.ID_EqualsSign);
output = findViewById(R.id.ID_Output);
}
public void ClickedOne(View v) {
output.setText(output.getText() + "1");
}
public void ClickedTwo(View v) {
output.setText(output.getText() + "2");
}
public void ClickedThree(View v) {
output.setText(output.getText() + "3");
}
public void ClickedFour(View v) {
output.setText(output.getText() + "4");
}
public void ClickedFive(View v) {
output.setText(output.getText() + "5");
}
public void ClickedSix(View v) {
output.setText(output.getText() + "6");
}
public void ClickedSeven(View v) {
output.setText(output.getText() + "7");
}
public void ClickedEight(View v) {
output.setText(output.getText() + "8");
}
public void ClickedNine(View v) {
output.setText(output.getText() + "9");
}
public void ClickedZero(View v) {
output.setText(output.getText() + "0");
}
public void ClickedPlus(View v) {
output.setText(output.getText() + "+");
}
public void ClickedMinus(View v) {
output.setText(output.getText() + "-");
}
public void ClickedMultiply(View v) {
output.setText(output.getText() + "*");
}
public void ClickedDivide(View v) {
output.setText(output.getText() + "/");
}
public void ClickedClear(View v) {
output.setText("");
list.clear();
}
public void ClickedEquals(View v){
StringTokenizer tokens = new StringTokenizer(String.valueOf(output.getText()), "+-/*", true);
while (tokens.hasMoreTokens()) {
list.add(tokens.nextToken());
}
for (int x = 0; x < list.size(); x++)
{
try {
if(list.get(0).equals("+") || list.get(0).equals("-") || list.get(0).equals("*")
||list.get(0).equals("/") || list.get(list.size()-1).equals("+") || list.get(list.size()-1).equals("-")
|| list.get(list.size()-1).equals("*") ||list.get(list.size()-1).equals("/")){
output.setText("Error: illegal statement");
return;
}
if (list.get(x).equals("*")) {
double mult = Double.valueOf(list.get(x - 1)) * Double.valueOf(list.get(x + 1));
list.remove(x + 1);
list.remove(x - 1);
list.set(x - 1, Double.toString(mult));
x = 0;
} else if (list.get(x).equals("/")) {
if (Double.valueOf(list.get(x + 1)) == 0) {
output.setText("Error: Divide by zero ");
return;
}
double div = Double.valueOf(list.get(x - 1)) / Double.valueOf(list.get(x + 1));
list.remove(x + 1);
list.remove(x - 1);
list.set(x - 1, Double.toString(div));
x = 0;
}
}catch(IllegalArgumentException e)
{
output.setText("Error: Illegal Argument");
return;
}catch(ArithmeticException e)
{
output.setText("Error: Arithmetic Exception");
return;
}
}
for (int x = 0; x < list.size(); x++) {
try {
if (list.get(x).equals("+")) {
double add = Double.valueOf(list.get(x - 1)) + Double.valueOf(list.get(x + 1));
list.remove(x + 1);
list.remove(x - 1);
list.set(x - 1, Double.toString(add));
x = 0;
} else if (list.get(x).equals("-")) {
double sub = Double.valueOf(list.get(x - 1)) - Double.valueOf(list.get(x + 1));
list.remove(x + 1);
list.remove(x - 1);
list.set(x - 1, Double.toString(sub));
x = 0;
}
}catch(IllegalArgumentException e)
{
output.setText("Error: Illegal Argument");
return;
}catch(ArithmeticException e)
{
output.setText("Error: Arithmetic Exception");
return;
}
}
output.setText(list.get(0));
list.clear();
}
}
| f4375d8b05983e26d8a27503f95a7fca459b3b09 | [
"Java"
] | 1 | Java | zubairlalani/Calculator | 706f9e8aac948d34ebd49869095eabb7bba68583 | f3ae5823789f25850cd033da7a6185a628204c9f | |
refs/heads/master | <repo_name>bringbang/TermProjectDataStructure<file_sep>/JobProJect/src/CompareGraph.java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
class Airplane{
private String brand ;
private String form ;
private String to ;
private int price;
private int distance;
private List<VertexDijkstra> path;
private String path1;
private String type;
private String status;
public Airplane(String brand, String form, String to,int type, int price, int distance, List<VertexDijkstra> path,int status) {
this.brand = brand;
this.form = form;
this.to = to;
this.price = price;
this.distance = distance;
this.path = path;
this.type = getType(type);
this.path1 = setPath(path);
this.status = getStatus(status);
}
public String getType(int type){
String str = "";
switch(type){
case 0:
str = "Economy";
case 1:
str = "Business";
case 2:
str = "First";
}
return str;
}
public String getBrand(){
return brand;
}
public String getForm(){
return form;
}
public String getTo(){
return to;
}
public int getDistance(){
return distance;
}
public String getStatus(int status){
String str = "";
switch(status){
case 0:
str = "BENEFIT";
case 1:
str = "HALFBENEFIT";
case 2:
str = "DONTBENEFIT";
}
return str;
}
public String setPath(List<VertexDijkstra> path){
String Str = "";
int count = 0;
if(path.size()==2){
Str+= path.get(0)+"-->"+path.get(1);
}
else if(path.size()==3){
Str += path.get(0)+"-->"+path.get(1)+"-->"+path.get(2);
}
else if(path.size()==4){
Str += path.get(0)+"-->"+path.get(1)+"-->"+path.get(2)+"-->"+path.get(3);
}
return Str;
}
public String toString(){
return brand+" "+form+" "+to+" "+price+" "+distance+" "+path1;
}
public String getPath(){
return path1;
}
public String getPrice(){
return Integer.toString(price);
}
}
public class CompareGraph extends javax.swing.JFrame {
Random random = new Random();
Dijkstra dijkstra = new Dijkstra();
Dijkstra dijkstra1 = new Dijkstra();
String[] town = {"Bangkok", "Seoul", "Singapore", "Tokyo", "Sydney", "Beijing", "Newyork", "Munich", "Heathrow"};
String[] airplaneBrand = {"JapanAirline","KoreanAirline","Etihad","ThaiAirways"};
VertexDijkstra[] ThaiAirways = new VertexDijkstra[town.length];
VertexDijkstra[] BangkokAirWays = new VertexDijkstra[town.length];
ArrayList<Airplane> plane = new ArrayList<>();
ArrayList<Airplane> planeplane = new ArrayList<>();
ArrayList<Airplane> planeTarget = new ArrayList<>();
ArrayList<Airplane> planeTarget2 = new ArrayList<>();
String Form = "";
String To = "";
ArrayList<EdgeDijkstra> edge = new ArrayList<>();
ArrayList<EdgeDijkstra> edge1 = new ArrayList<>();
int size = 0;
int count = 0;
int numberform = -1;
int numberto = -1;
int type = 0;
void createDijkstraDirect(){
for(int i=0;i<ThaiAirways.length;i++){
ThaiAirways[i] = new VertexDijkstra(town[i]);
}
int b1 = random.nextInt(100)+4000; //Bangkok -> Seoul
int b2 = random.nextInt(100)+4000; //Bangkok -> Tokyo
int b3 = random.nextInt(100)+7500; //Bangkok -> Sydney
int b4 = random.nextInt(100)+1400; //Bangkok -> Singapore
int b5 = random.nextInt(100)+8800; //Bangkok -> Munich
int b6 = random.nextInt(100)+3300; //Bangkok -> Beijing
int b7 = random.nextInt(100)+13000; // Bangkok -> Newyork
int b8 = random.nextInt(100)+9500; // Bangkok -> Heathrow
int se1 = random.nextInt(100)+4600; // Seoul -> Singapore
int se2 = random.nextInt(100)+1100;
int se3 = random.nextInt(100)+8300;
int se4 = random.nextInt(100)+900;
int se5 = random.nextInt(100)+11000;
int se6 = random.nextInt(100)+8500;
int se7 = random.nextInt(100)+8800;
int si1 = random.nextInt(100)+6300;
int si2 = random.nextInt(100)+5300;
int si3 = random.nextInt(100)+10000;
int si4 = random.nextInt(100)+4400;
int si5 = random.nextInt(100)+16700;
int si6 = random.nextInt(100)+10800;
int to1 = random.nextInt(100)+7800;
int to2 = random.nextInt(100)+9300;
int to3 = random.nextInt(100)+2094;
int to4 = random.nextInt(100)+10800;
int to5 = random.nextInt(100)+9500;
int sy1 = random.nextInt(100)+8900;
int sy2 = random.nextInt(100)+17000;
int sy3 = random.nextInt(100)+16300;
int sy4 = random.nextInt(100)+17000;
int be1 = random.nextInt(100)+7700;
int be2 = random.nextInt(100)+8100;
int be3 = random.nextInt(100)+10900;
int ne1 = random.nextInt(100)+6400;
int ne2 = random.nextInt(100)+5500;
int mu1 = random.nextInt(100)+900;
edge.add(new EdgeDijkstra(b1, ThaiAirways[0], ThaiAirways[1])); //Bangkok -> Seoul
edge.add(new EdgeDijkstra(b4, ThaiAirways[0], ThaiAirways[2])); //Bangkok -> Singapore
edge.add(new EdgeDijkstra(b2, ThaiAirways[0], ThaiAirways[3])); //Bangkok -> Tokyo
edge.add(new EdgeDijkstra(b3, ThaiAirways[0], ThaiAirways[4])); //Bangkok -> Sydney
edge.add(new EdgeDijkstra(b6, ThaiAirways[0], ThaiAirways[5])); //Bangkok ->`Beijing
edge.add(new EdgeDijkstra(b7, ThaiAirways[0], ThaiAirways[6])); //Bangkok -> Newyork
edge.add(new EdgeDijkstra(b5, ThaiAirways[0], ThaiAirways[7])); //Bangkok -> Munich
edge.add(new EdgeDijkstra(b8, ThaiAirways[0], ThaiAirways[8])); //Bangkok -> Heathrow
edge.add(new EdgeDijkstra(b1, ThaiAirways[1], ThaiAirways[0])); //Bangkok -> Seoul
edge.add(new EdgeDijkstra(se1, ThaiAirways[1], ThaiAirways[2]));
edge.add(new EdgeDijkstra(se2, ThaiAirways[1], ThaiAirways[3]));
edge.add(new EdgeDijkstra(se3, ThaiAirways[1], ThaiAirways[4]));
edge.add(new EdgeDijkstra(se4, ThaiAirways[1], ThaiAirways[5]));
edge.add(new EdgeDijkstra(se5, ThaiAirways[1], ThaiAirways[6]));
edge.add(new EdgeDijkstra(se6, ThaiAirways[1], ThaiAirways[7]));
edge.add(new EdgeDijkstra(se7, ThaiAirways[1], ThaiAirways[8]));
edge.add(new EdgeDijkstra(b1,ThaiAirways[1],ThaiAirways[0]));
edge.add(new EdgeDijkstra(se1, ThaiAirways[2], ThaiAirways[1]));
edge.add(new EdgeDijkstra(b4, ThaiAirways[2], ThaiAirways[0]));
edge.add(new EdgeDijkstra(si2, ThaiAirways[2], ThaiAirways[3]));
edge.add(new EdgeDijkstra(si1, ThaiAirways[2], ThaiAirways[4]));
edge.add(new EdgeDijkstra(si3, ThaiAirways[2], ThaiAirways[7]));
edge.add(new EdgeDijkstra(si4, ThaiAirways[2], ThaiAirways[5]));
edge.add(new EdgeDijkstra(si5, ThaiAirways[2], ThaiAirways[6]));
edge.add(new EdgeDijkstra(si6, ThaiAirways[2], ThaiAirways[8]));
edge.add(new EdgeDijkstra(b1, ThaiAirways[3], ThaiAirways[0]));
edge.add(new EdgeDijkstra(si2, ThaiAirways[3], ThaiAirways[2]));
edge.add(new EdgeDijkstra(se2, ThaiAirways[3], ThaiAirways[1]));
edge.add(new EdgeDijkstra(to1, ThaiAirways[3], ThaiAirways[4]));
edge.add(new EdgeDijkstra(to2, ThaiAirways[3], ThaiAirways[7]));
edge.add(new EdgeDijkstra(to3, ThaiAirways[3], ThaiAirways[5]));
edge.add(new EdgeDijkstra(to4, ThaiAirways[3], ThaiAirways[6]));
edge.add(new EdgeDijkstra(to5, ThaiAirways[3], ThaiAirways[8]));
edge.add(new EdgeDijkstra(b3, ThaiAirways[4], ThaiAirways[0]));
edge.add(new EdgeDijkstra(se3, ThaiAirways[4], ThaiAirways[1]));
edge.add(new EdgeDijkstra(si1, ThaiAirways[4], ThaiAirways[2]));
edge.add(new EdgeDijkstra(to1, ThaiAirways[4], ThaiAirways[3]));
edge.add(new EdgeDijkstra(sy3, ThaiAirways[4], ThaiAirways[7]));
edge.add(new EdgeDijkstra(sy1, ThaiAirways[4], ThaiAirways[5]));
edge.add(new EdgeDijkstra(sy2, ThaiAirways[4], ThaiAirways[6]));
edge.add(new EdgeDijkstra(sy4, ThaiAirways[4], ThaiAirways[8]));
edge.add(new EdgeDijkstra(b6, ThaiAirways[5], ThaiAirways[0]));
edge.add(new EdgeDijkstra(se4,ThaiAirways[5], ThaiAirways[1]));
edge.add(new EdgeDijkstra(si4, ThaiAirways[5], ThaiAirways[2]));
edge.add(new EdgeDijkstra(to3, ThaiAirways[5], ThaiAirways[3]));
edge.add(new EdgeDijkstra(sy1, ThaiAirways[5], ThaiAirways[4]));
edge.add(new EdgeDijkstra(be1, ThaiAirways[5], ThaiAirways[7]));
edge.add(new EdgeDijkstra(be3, ThaiAirways[5], ThaiAirways[6]));
edge.add(new EdgeDijkstra(be2, ThaiAirways[5], ThaiAirways[8]));
edge.add(new EdgeDijkstra(b7,ThaiAirways[6],ThaiAirways[0]));
edge.add(new EdgeDijkstra(se5, ThaiAirways[6], ThaiAirways[1]));
edge.add(new EdgeDijkstra(si5, ThaiAirways[6], ThaiAirways[2]));
edge.add(new EdgeDijkstra(to4, ThaiAirways[6], ThaiAirways[3]));
edge.add(new EdgeDijkstra(sy2, ThaiAirways[6], ThaiAirways[4]));
edge.add(new EdgeDijkstra(ne1, ThaiAirways[6], ThaiAirways[7]));
edge.add(new EdgeDijkstra(be3, ThaiAirways[6], ThaiAirways[5]));
edge.add(new EdgeDijkstra(ne2, ThaiAirways[6], ThaiAirways[8]));
edge.add(new EdgeDijkstra(mu1, ThaiAirways[7], ThaiAirways[8]));
edge.add(new EdgeDijkstra(b5, ThaiAirways[7], ThaiAirways[0]));
edge.add(new EdgeDijkstra(b4, ThaiAirways[7], ThaiAirways[2]));
edge.add(new EdgeDijkstra(si3, ThaiAirways[7], ThaiAirways[3]));
edge.add(new EdgeDijkstra(sy3, ThaiAirways[7], ThaiAirways[4]));
edge.add(new EdgeDijkstra(se6, ThaiAirways[7], ThaiAirways[1]));
edge.add(new EdgeDijkstra(be1, ThaiAirways[7], ThaiAirways[5]));
edge.add(new EdgeDijkstra(ne1, ThaiAirways[7], ThaiAirways[6]));
edge.add(new EdgeDijkstra(se7, ThaiAirways[8], ThaiAirways[1]));
edge.add(new EdgeDijkstra(b8, ThaiAirways[8], ThaiAirways[0]));
edge.add(new EdgeDijkstra(si6, ThaiAirways[8], ThaiAirways[2]));
edge.add(new EdgeDijkstra(to5, ThaiAirways[8], ThaiAirways[3]));
edge.add(new EdgeDijkstra(sy4, ThaiAirways[8], ThaiAirways[4]));
edge.add(new EdgeDijkstra(mu1, ThaiAirways[8], ThaiAirways[7]));
edge.add(new EdgeDijkstra(be2, ThaiAirways[8], ThaiAirways[5]));
edge.add(new EdgeDijkstra(ne2, ThaiAirways[8], ThaiAirways[6]));
for(int i=0;i<edge.size();i++){
if(edge.get(i).getStartVertex()==ThaiAirways[0]){
ThaiAirways[0].addNeighbour(edge.get(i));
}
else if(edge.get(i).getStartVertex()==ThaiAirways[1]){
ThaiAirways[1].addNeighbour(edge.get(i));
}
else if(edge.get(i).getStartVertex()==ThaiAirways[2]){
ThaiAirways[2].addNeighbour(edge.get(i));
}
else if(edge.get(i).getStartVertex()==ThaiAirways[3]){
ThaiAirways[3].addNeighbour(edge.get(i));
}
else if(edge.get(i).getStartVertex()==ThaiAirways[4]){
ThaiAirways[4].addNeighbour(edge.get(i));
}
else if(edge.get(i).getStartVertex()==ThaiAirways[5]){
ThaiAirways[5].addNeighbour(edge.get(i));
}
else if(edge.get(i).getStartVertex()==ThaiAirways[6]){
ThaiAirways[6].addNeighbour(edge.get(i));
}
else if(edge.get(i).getStartVertex()==ThaiAirways[7]){
ThaiAirways[7].addNeighbour(edge.get(i));
}
else if(edge.get(i).getStartVertex()==ThaiAirways[8]){
ThaiAirways[8].addNeighbour(edge.get(i));
}
}
}
void createDijkstraTransit_Direct(){
count =0;
for(int i=0;i<BangkokAirWays.length;i++){
BangkokAirWays[i] = new VertexDijkstra(town[i]);
}
int b1 = random.nextInt(100)+4000; //Bangkok -> Seoul
int b2 = random.nextInt(100)+4000; //Bangkok -> Tokyo
int b3 = random.nextInt(100)+7500; //Bangkok -> Sydney
int b4 = random.nextInt(100)+1400; //Bangkok -> Singapore
int b5 = random.nextInt(100)+8800; //Bangkok -> Munich
int b6 = random.nextInt(100)+3300; //Bangkok -> Beijing
int ne1 = random.nextInt(100)+6400; // Newyork -> Munich
int mu1 = random.nextInt(100)+900; // Munich -> Heathrow
int se1 = random.nextInt(100)+11000; //Seoul -> Newyork
int se2 = random.nextInt(100)+8800; // Seoul -> Heathrow(United Kingdom)
int to1 = random.nextInt(100)+11000; // Tokyo -> Newyork
int to2 = random.nextInt(100)+8800; // Tokyo -> Heathrow
int to3 = random.nextInt(100)+1100; // Tokyo -> Seoul
edge1.add(new EdgeDijkstra(b1, BangkokAirWays[0], BangkokAirWays[1])); //Bangkok -> Seoul
edge1.add(new EdgeDijkstra(b4, BangkokAirWays[0], BangkokAirWays[2])); //Bangkok -> Singapore
edge1.add(new EdgeDijkstra(b2, BangkokAirWays[0], BangkokAirWays[3])); //Bangkok -> Tokyo
edge1.add(new EdgeDijkstra(b3, BangkokAirWays[0], BangkokAirWays[4])); //Bangkok -> Sydney
edge1.add(new EdgeDijkstra(b5, BangkokAirWays[0], BangkokAirWays[7])); //Bangkok -> Munich
edge1.add(new EdgeDijkstra(b6, BangkokAirWays[0], BangkokAirWays[5])); //Bangkok -> Beijing
edge1.add(new EdgeDijkstra(se1,BangkokAirWays[1], BangkokAirWays[6])); //Seoul -> Newyork
edge1.add(new EdgeDijkstra(se2,BangkokAirWays[1], BangkokAirWays[8])); // Seoul -> Heathrow(United Kingdom)
edge1.add(new EdgeDijkstra(b1,BangkokAirWays[1],BangkokAirWays[0])); //Seoul -> Bangkok
edge1.add(new EdgeDijkstra(to1,BangkokAirWays[3],BangkokAirWays[6])); // Tokyo -> Newyork
edge1.add(new EdgeDijkstra(to2,BangkokAirWays[3],BangkokAirWays[8])); // Tokyo -> Heathrow
edge1.add(new EdgeDijkstra(b2, BangkokAirWays[3],BangkokAirWays[0])); // Tokyo -> Bangkok*/
edge1.add(new EdgeDijkstra(to3,BangkokAirWays[3], BangkokAirWays[1])); // Tokyo -> Seoul
edge1.add(new EdgeDijkstra(b2,BangkokAirWays[1], BangkokAirWays[3]));
edge1.add(new EdgeDijkstra(b6,BangkokAirWays[5],BangkokAirWays[0])); //Beijing -> Bangkok
edge1.add(new EdgeDijkstra(b4,BangkokAirWays[2],BangkokAirWays[0])); //Singapore -> Bangkok
edge1.add(new EdgeDijkstra(ne1, BangkokAirWays[6],BangkokAirWays[7])); // Newyork -> Munich
edge1.add(new EdgeDijkstra(to1,BangkokAirWays[6],BangkokAirWays[3])); // Newyork -> Tokyo
edge1.add(new EdgeDijkstra(to2,BangkokAirWays[7],BangkokAirWays[3])); // Munich -> Tokyo
edge1.add(new EdgeDijkstra(se2,BangkokAirWays[7],BangkokAirWays[1])); //Newyork -> Seoul
edge1.add(new EdgeDijkstra(mu1,BangkokAirWays[7],BangkokAirWays[8])); // Munich -> Heathrow
edge1.add(new EdgeDijkstra(b5,BangkokAirWays[7],BangkokAirWays[0])); //Munich -> Bangkok
edge1.add(new EdgeDijkstra(mu1,BangkokAirWays[8], BangkokAirWays[7]));
for(int i=0;i<edge1.size();i++){
if(edge1.get(i).getStartVertex()==BangkokAirWays[0]){
BangkokAirWays[0].addNeighbour(edge1.get(i));
}
else if(edge1.get(i).getStartVertex()==BangkokAirWays[1]){
BangkokAirWays[1].addNeighbour(edge1.get(i));
}
else if(edge1.get(i).getStartVertex()==BangkokAirWays[2]){
BangkokAirWays[2].addNeighbour(edge1.get(i));
}
else if(edge1.get(i).getStartVertex()==BangkokAirWays[3]){
BangkokAirWays[3].addNeighbour(edge1.get(i));
}
else if(edge1.get(i).getStartVertex()==BangkokAirWays[4]){
BangkokAirWays[4].addNeighbour(edge1.get(i));
}
else if(edge1.get(i).getStartVertex()==BangkokAirWays[5]){
BangkokAirWays[5].addNeighbour(edge1.get(i));
}
else if(edge1.get(i).getStartVertex()==BangkokAirWays[6]){
BangkokAirWays[6].addNeighbour(edge1.get(i));
}
else if(edge1.get(i).getStartVertex()==BangkokAirWays[7]){
BangkokAirWays[7].addNeighbour(edge1.get(i));
}
else if(edge1.get(i).getStartVertex()==BangkokAirWays[8]){
BangkokAirWays[8].addNeighbour(edge1.get(i));
}
}
}
void shortestPathDirect(int computenum,int number,int type,int peoplead,int peopleki){
dijkstra.computePath(ThaiAirways[computenum]);
int sumbefore = 0;
if(peopleki>0){
sumbefore = ThaiAirways[number].getPrice(type) -(ThaiAirways[number].getPrice(type)%40);
if(peoplead>=3){
int sumbenefit = sumbefore + ((ThaiAirways[number].getPrice(type)- (ThaiAirways[number].getPrice(type) % 15))*peoplead);
plane.add(new Airplane(airplaneBrand[random.nextInt(4)],town[computenum], town[number],type,sumbenefit, ThaiAirways[number].getMinDistance(),dijkstra.getShortestPathTo(ThaiAirways[number]),0));
}
else if(peoplead<3){
int sumhalfbenefit = sumbefore + (ThaiAirways[number].getPrice(type)*peoplead);
plane.add(new Airplane(airplaneBrand[random.nextInt(4)],town[computenum], town[number],type,sumhalfbenefit, ThaiAirways[number].getMinDistance(),dijkstra.getShortestPathTo(ThaiAirways[number]),1));
}
}
else{
if(peoplead<3){
int sumdontbenefit = ThaiAirways[number].getPrice(type)*peoplead;
plane.add(new Airplane(airplaneBrand[random.nextInt(4)],town[computenum], town[number],type,sumdontbenefit, ThaiAirways[number].getMinDistance(),dijkstra.getShortestPathTo(ThaiAirways[number]),2));
}
else if(peoplead<3){
int sumhalfbenefit = ((ThaiAirways[number].getPrice(type)- (ThaiAirways[number].getPrice(type) % 15))*peoplead);
plane.add(new Airplane(airplaneBrand[random.nextInt(4)],town[computenum], town[number],type,sumhalfbenefit, ThaiAirways[number].getMinDistance(),dijkstra.getShortestPathTo(ThaiAirways[number]),1));
}
}
shortestPathTransit(computenum, number, type,peoplead,peopleki);
}
void shortestPathTransit(int computenum,int number,int type,int peoplead,int peoplekids){
dijkstra1.computePath(BangkokAirWays[computenum]);
int sumbefore = 0;
if(peoplekids>0){
sumbefore = ((BangkokAirWays[number].getPriceTransit(type) - (BangkokAirWays[number].getPriceTransit(type)%60))*peoplekids);
if(peoplead>=2){
int sumbenefit = sumbefore + ((BangkokAirWays[number].getPriceTransit(type)-(BangkokAirWays[number].getPriceTransit(type)%20))*peoplead);
planeplane.add(new Airplane(airplaneBrand[random.nextInt(4)],town[computenum], town[number],type,sumbenefit, BangkokAirWays[number].getMinDistance(),dijkstra1.getShortestPathTo(BangkokAirWays[number]),0));
}
else if(peoplead<2){
int sumhalfbenefit = sumbefore+((BangkokAirWays[number].getPriceTransit(type)-(BangkokAirWays[number].getPriceTransit(type)%20))*peoplead);
planeplane.add(new Airplane(airplaneBrand[random.nextInt(4)],town[computenum], town[number],type,sumhalfbenefit, BangkokAirWays[number].getMinDistance(),dijkstra1.getShortestPathTo(BangkokAirWays[number]),1));
}
}
else {
if(peoplead>=2){
int sumhalfbenefit = ((BangkokAirWays[number].getPriceTransit(type)-(BangkokAirWays[number].getPriceTransit(type)%20))*peoplead);
planeplane.add(new Airplane(airplaneBrand[random.nextInt(4)],town[computenum], town[number],type,sumhalfbenefit, BangkokAirWays[number].getMinDistance(),dijkstra1.getShortestPathTo(BangkokAirWays[number]),1));
}
else if(peoplead<2){
int sumdontbenefit = (BangkokAirWays[number].getPriceTransit(type)*peoplead);
planeplane.add(new Airplane(airplaneBrand[random.nextInt(4)],town[computenum], town[number],type,sumdontbenefit, BangkokAirWays[number].getMinDistance(),dijkstra1.getShortestPathTo(BangkokAirWays[number]),2));
}
}
}
void getPath(String form,String to,int type){
for(int i=0;i<plane.size();i++){
if(plane.get(i).getForm().equals(form)&&plane.get(i).getTo().equals(to)){
if(plane.get(i).getType(type).equals("Economy")){
jTextField1.setText(plane.get(i).getPath()+" Distance = "+plane.get(i).getDistance());
jTextField3.setText(plane.get(i).getPrice());
break;
}
else if(plane.get(i).getType(type).equals("Business")){
jTextField1.setText(plane.get(i).getPath()+" Distance = "+plane.get(i).getDistance());
jTextField3.setText(plane.get(i).getPrice());
break;
}
else if(plane.get(i).getType(type).equals("First")){
jTextField1.setText(plane.get(i).getPath()+" Distance = "+plane.get(i).getDistance());
jTextField3.setText(plane.get(i).getPrice());
break;
}
}
}
for(int i=0;i<planeplane.size();i++){
if(planeplane.get(i).getForm().equals(form)&&planeplane.get(i).getTo().equals(to)){
if(planeplane.get(i).getType(type).equals("Economy")){
jTextField2.setText(planeplane.get(i).getPath()+" Distance : "+planeplane.get(i).getDistance());
jTextField4.setText(planeplane.get(i).getPrice());
break;
}
else if(planeplane.get(i).getType(type).equals("Business")){
jTextField2.setText(planeplane.get(i).getPath()+" Distance : "+planeplane.get(i).getDistance());
jTextField4.setText(planeplane.get(i).getPrice());
break;
}
else if(planeplane.get(i).getType(type).equals("First")){
jTextField2.setText(planeplane.get(i).getPath()+" Distance : "+planeplane.get(i).getDistance());
jTextField4.setText(planeplane.get(i).getPrice());
break;
}
}
}
}
void create(){
createDijkstraDirect();
createDijkstraTransit_Direct();
}
public CompareGraph() {
create();
initComponents();
// jLabel12.setIcon(new ImageIcon(getClass().getResource("sky-wallpapers-28043-8667192.jpg")));
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel6 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jComboBox1 = new javax.swing.JComboBox<>();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox<>();
jComboBox3 = new javax.swing.JComboBox<>();
jLabel4 = new javax.swing.JLabel();
jComboBox4 = new javax.swing.JComboBox<>();
jLabel5 = new javax.swing.JLabel();
jComboBox5 = new javax.swing.JComboBox<>();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel13 = new javax.swing.JLabel();
jLabel6.setText("jLabel6");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMaximumSize(new java.awt.Dimension(1024, 690));
jPanel1.setLayout(null);
jComboBox1.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Bangkok", "Seoul", "Singapore", "Tokyo", "Sydney", "Beijing", "Newyork", "Munich", "Heathrow" }));
jPanel1.add(jComboBox1);
jComboBox1.setBounds(155, 203, 108, 28);
jLabel1.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jLabel1.setText("Form :");
jPanel1.add(jLabel1);
jLabel1.setBounds(95, 206, 48, 22);
jLabel2.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jLabel2.setText("To :");
jPanel1.add(jLabel2);
jLabel2.setBounds(281, 206, 30, 22);
jLabel3.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jLabel3.setText("Type : ");
jPanel1.add(jLabel3);
jLabel3.setBounds(510, 200, 51, 22);
jComboBox2.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Bangkok", "Seoul", "Singapore", "Tokyo", "Sydney", "Beijing", "Newyork", "Munich", "Heathrow" }));
jPanel1.add(jComboBox2);
jComboBox2.setBounds(329, 203, 108, 28);
jComboBox3.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jComboBox3.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Economy Class", "Business Class", "First Class" }));
jPanel1.add(jComboBox3);
jComboBox3.setBounds(570, 200, 145, 28);
jLabel4.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jLabel4.setText("People Adult :");
jPanel1.add(jLabel4);
jLabel4.setBounds(95, 272, 109, 22);
jComboBox4.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jComboBox4.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1", "2", "3", "4", "5", "6" }));
jPanel1.add(jComboBox4);
jComboBox4.setBounds(220, 269, 42, 28);
jLabel5.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jLabel5.setText("Kids (2-12 Year) :");
jPanel1.add(jLabel5);
jLabel5.setBounds(281, 272, 131, 22);
jComboBox5.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jComboBox5.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "0", "1", "2", "3" }));
jPanel1.add(jComboBox5);
jComboBox5.setBounds(417, 269, 42, 28);
jTextField1.setFont(new java.awt.Font("Gill Sans MT", 0, 16)); // NOI18N
jPanel1.add(jTextField1);
jTextField1.setBounds(226, 370, 382, 30);
jTextField2.setFont(new java.awt.Font("Gill Sans MT", 0, 16)); // NOI18N
jPanel1.add(jTextField2);
jTextField2.setBounds(226, 418, 382, 31);
jTextField3.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jPanel1.add(jTextField3);
jTextField3.setBounds(689, 370, 111, 28);
jTextField4.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jPanel1.add(jTextField4);
jTextField4.setBounds(689, 419, 111, 28);
jLabel7.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jLabel7.setText("Price :");
jPanel1.add(jLabel7);
jLabel7.setBounds(631, 373, 46, 22);
jLabel8.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jLabel8.setText("Price :");
jPanel1.add(jLabel8);
jLabel8.setBounds(631, 422, 46, 22);
jLabel9.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jLabel9.setText("Direction 1 :");
jPanel1.add(jLabel9);
jLabel9.setBounds(90, 373, 94, 22);
jLabel10.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jLabel10.setText("Direction 2 :");
jPanel1.add(jLabel10);
jLabel10.setBounds(90, 422, 94, 22);
jLabel11.setFont(new java.awt.Font("Gill Sans MT", 0, 30)); // NOI18N
jLabel11.setText("Give a Direction!!!");
jPanel1.add(jLabel11);
jLabel11.setBounds(374, 73, 227, 35);
jButton1.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N
jButton1.setText("Search");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1);
jButton1.setBounds(510, 270, 120, 31);
jLabel13.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sky-wallpapers-28043-8667192.jpg"))); // NOI18N
jLabel13.setText("jLabel13");
jPanel1.add(jLabel13);
jLabel13.setBounds(0, 0, 990, 560);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 990, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 560, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
create();
int Form = jComboBox1.getSelectedIndex();
int To = jComboBox2.getSelectedIndex();
int Type = jComboBox3.getSelectedIndex();
int adult = jComboBox4.getSelectedIndex()+1;
int kids = jComboBox5.getSelectedIndex();
String Form1 = jComboBox1.getSelectedItem().toString();
String To1 = jComboBox2.getSelectedItem().toString();
if(Form1.equals(To1)){
JOptionPane.showMessageDialog(null,"Please Choose New City","Error!!!",JOptionPane.ERROR_MESSAGE);
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
plane.clear();
planeplane.clear();
}
else{
shortestPathDirect(Form, To, Type,adult,kids);
getPath(Form1,To1,Type);
plane.clear();
planeplane.clear();
}
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CompareGraph().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JComboBox<String> jComboBox2;
private javax.swing.JComboBox<String> jComboBox3;
private javax.swing.JComboBox<String> jComboBox4;
private javax.swing.JComboBox<String> jComboBox5;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
// End of variables declaration//GEN-END:variables
}
<file_sep>/README.md
Project เกี่ยวกับกราฟเปรียบเทียบระยะทาง
| 280815a74718a3348e61cb713ed15fdc3efd78f1 | [
"Markdown",
"Java"
] | 2 | Java | bringbang/TermProjectDataStructure | 345d71e7bf180a3fac2ef9180e94b835d250a308 | 5dd08d1151ceca83cca9b0419337af9a53621a04 | |
refs/heads/master | <repo_name>b0nik/React-todos<file_sep>/src/redux/reducers/todosReducer.js
const initialState=[
{
id:1,
complete:false,
task:'Some text',
},
{
id:2,
complete:true,
task:'Some enother text',
}
];
export default function (state=initialState,action) {
switch (action.type){
case "CHANGE_TEXT":
const txt=action.payload;
if(txt.length===0){
return initialState;
}
return {text:action.payload};
default:
return state
}
}<file_sep>/src/routes.js
import React, {Component} from 'react';
import { IndexRoute, Route } from 'react-router';
import App from './containers/App'
import Todos from './containers/Todos'
export default (
<Route component={App}>
<Route path="/" component={Todos}>
<Route path="/:id" component={Todos}/>
</Route>
</Route>
)<file_sep>/src/redux/configureStore/index.js
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import rootReducer from '../reducers/index'
export default function configureStore(initialState) {
const logger = createLogger({
collapsed: true,
predicate: () =>
process.env.NODE_ENV === `development` // eslint-disable-line no-unused-vars
});
const middleware = applyMiddleware(thunk, logger);
return middleware(createStore)(rootReducer, initialState);
}
<file_sep>/src/redux/actions/todos.js
export function changeText (text) {
return{
type:"CHANGE_TEXT",
payload:text
}
}
<file_sep>/src/Components/table/index.js
import React, {Component} from 'react';
import { Checkbox, Textfield,FABButton, Icon } from 'react-mdl'
if(process.env.BROWSER){
const style= require('./styles.less')
}
export default class Table extends Component{
render(){
let Head=[];
for(let key in this.props.data[0]){
if(key!=='id'){
Head.push((
<th key={key}>{key}</th>
))
}
}
let temp=this.props.data.map((item,i)=>{
return(
<tr className={item.complete?'bg-complate':null} data-id={item.id} key={i}>
<td style={{verticalAlign:'middle'}} key={i}>{i+1}</td>
<td style={{verticalAlign:'middle'}}><Checkbox defaultChecked={item.complete}/></td>
<td style={{verticalAlign:'middle'}}>
<Textfield
onChange={() => {}}
defaultValue={item.task}
label=''
style={{width: '100%'}}
/>
</td>
<td style={{verticalAlign:'middle',textAlign:'center'}}>
<FABButton colored>
<Icon name="remove" />
</FABButton>
</td>
</tr>
)
});
return(
<table className="table">
<thead>
<tr>
<th>#</th>
{Head}
<th>delete</th>
</tr>
</thead>
<tbody>
{temp}
</tbody>
</table>
)
}
} | 88d0d2dd3ad0777e7cf0411e136d87c9973d564b | [
"JavaScript"
] | 5 | JavaScript | b0nik/React-todos | 4d394a0a6e899a679f78b5eda1ec0883936ca1d7 | da365ce44463e15289815a1307cc99cd2c7bbceb | |
refs/heads/master | <repo_name>plutonbacon/erdos<file_sep>/lib/erdos.rb
require 'erdos/version'
# Applied Mathematics
require 'erdos/infotheory'
<file_sep>/lib/erdos/infotheory.rb
module Erdos
# Common calculations in Information Theory.
module InfoTheory
# Computes shannon entropy or the measure of unpredictability
# of information content.
#
# @param s [String] a given input string
# @param ignore_case [Boolean] if true, normalize to lowercase
# @param ignore_spaces [Boolean] if true, remove all spaces
#
# @return [Float] The bits of entropy contained within the input string.
def self.calculate_shannon_entropy(s, ignore_case = false,
ignore_spaces = false)
s.downcase! if ignore_case
s.gsub!(/\s+/, '') if ignore_spaces
s.each_char.group_by(&:to_s).values.map { |x|
x.length / s.length.to_f
}.reduce(0) { |e,x|
e - x * Math.log2(x)
}
end # def calculate_shannon_entropy
end # module InfoTheory
end # module Erdos
<file_sep>/spec/erdos/information_spec.rb
require 'spec_helper'
describe Erdos::InfoTheory do
let(:s) { String.new("Lorem ipsum dolor sit amet, consectetur adipisicing " +
"elit, sed do eiusmod tempor incididunt ut " +
" labore et dolore magna aliqua.") }
it 'computes shannon entropy correctly considering case and with spaces' do
expect(Erdos::InfoTheory.calculate_shannon_entropy(s)).to eq(4.012206049032528)
end
it 'computes shannon entropy correctly not considering case and with spaces' do
expect(Erdos::InfoTheory.calculate_shannon_entropy(s, true)).to eq(3.981004972793407)
end
it 'computes shannon entropy correctly not considering case and without spaces' do
expect(Erdos::InfoTheory.calculate_shannon_entropy(s, true, true)).to eq(3.969554499580588)
end
it 'computes shannon entropy correctly considering case and without spaces' do
expect(Erdos::InfoTheory.calculate_shannon_entropy(s, false, true)).to eq(4.006348221560684)
end
end<file_sep>/README.md
# Erdos
A mathematical "goody bag" for Ruby.
### Table of Contents
#### Applied Mathematics
##### Information Theory
- [Shannon Entropy](https://github.com/plutonbacon/erdos/blob/master/lib/erdos/infotheory.rb) | da58a623f8d0afaff0c06b4f89c0f92b0aad9c78 | [
"Markdown",
"Ruby"
] | 4 | Ruby | plutonbacon/erdos | f84fe2a2751fc7aadcbced0b633e44ad065f626a | c75f743659b84fd430081a20830ff1428275c84d | |
refs/heads/master | <repo_name>Dhavalkurkutiya/Java-Tutorial<file_sep>/CWH40AccessMosifireGetterandSetter.java
package com.dhavalkurkutiya;
class MyEmployee{
// private access modifire
private int id;
private String name;
// This mtahid to getName
public String getName(){
return name;
}
// This method to setName
public void setName(String n){
this.name = n;
}
// This method to setId
public void setId(int i){
this.id = i;
}
// This method to getId
public int getId(){
return id;
}
}
public class CWH40AccessMosifireGetterandSetter {
public static void main(String[] args) {
MyEmployee harry = new MyEmployee();
// There an eroor throw dou to private access modifire
/*
harry.id = 56;
harry.name = "Dhavalkurkutiya";
*/
//Set tha harry name
harry.setName("CodeWithaHarry");
System.out.println(harry.getName());
//Set a harry id
harry.setId(56);
System.out.println(harry.getId());
}
}
<file_sep>/CWH26ArrayinJava.java
package com.dhavalkurkutiya;
public class CWH26ArrayinJava {
public static void main (String[] args) {
/*
Classroom of 500 Students -0 You have to Store Marks these 500 Students
You have 2 Options:
1. Create a 500 Virble
2. Use Array (recommend)
*/
/*There are there main ways to create an Array in Java*/
// 1. Declaration and memory allocation
// int [] Marks = new int[5];
// 2. Declarationnand and then memory allocation
// int [] Marks;
// Marks = new int [5];
// Marks[0] = 00;
// Marks[1] = 10;
// Marks[2] = 20;
// Marks[3] = 30;
// Marks[4] = 40;
// System.out.println(Marks[4]);
// 3. Declarationnand , memory allocation and Instantiation to gather
int [] Marks = {10,20,30,40,50,60,70,80,90,100};
System.out.println(Marks[2]);
}
}
<file_sep>/CWH43JavaExasize3GuessingthaNumber.java
package com.dhavalkurkutiya;
public class CWH43JavaExasize3GuessingthaNumber {
public static void main(String[] args) {
System.out.println("Java Exasize Guessing tha Number...");
/*
1. Creating a Game Class "Guess tha Number"
2. Contractors Ganrete a Rendon Number
3 take UserInput() to take user input
*/
}
}
<file_sep>/CWH20Exsize2RickSizerPepper.java
package com.dhavalkurkutiya;
public class CWH20Exsize2RickSizerPepper {
public static void main (String[] args) {
System.out.println("Note code");
}
}
<file_sep>/CWH34Recursioninjava.java
package com.dhavalkurkutiya;
public class CWH34Recursioninjava {
// factorial(0) = 1
// factorial(n) = n * n-1 *...1
// factorial(5) = 5 * 4 * 3 * 2 * 1
// factorial(n) = n * factorial(n-1)
static int factorial(int n){
if (n==0 || n==1){
return 1;
}
else{
return n*factorial(n-1);
}
}static int factorial_itartive(int n){
if (n==0 || n==1){
return 1;
}
else{
int product = 1;
for (int i = 1; i<=n; i++){ // 1 to n
product *= i;
}
return product;
}
}
public static void main(String[] args) {
int n = 5;
System.out.println("Thare factorial " + n + " is " + factorial(n));
System.out.println("Thare factorial " + n + " is " + factorial_itartive(n));
}
}
<file_sep>/CWH37BasicTerminologyinObjectOrientation.java
package com.dhavalkurkutiya;
public class CWH37BasicTerminologyinObjectOrientation {
public static void main(String[] args) {
}
}
<file_sep>/CWH13IntroductionString.java
package com.dhavalkurkutiya;
import java.util.Scanner;
public class CWH13IntroductionString {
public static void main (String[] args) {
String name_new = new String("Dhavalkurkutiya");
String name = "Dhavalkurkutiya";
// %d int
// %f float
// %s String
// %c char
int a = 6;
float b = 8.98f;
// System.out.printf("a = %d and b = %f \n", a,b);
// System.out.format("a = %d and b = %f", a,b);
Scanner sc = new Scanner(System.in);
String st = sc.next(); // all selcted "sc.nextLine"
System.out.println(st);
}
}
<file_sep>/CWH22dowhile.java
package com.dhavalkurkutiya;
public class CWH22dowhile {
public static void main (String[] args) {
int a = 0;
do{
System.out.println(a);
a++;
}while(a<=80);
}
}
<file_sep>/CWH41Exasize2Solutions.java
package com.dhavalkurkutiya;
public class CWH41Exasize2Solutions {
public static void main(String[] args) {
}
}
<file_sep>/CWH21WhileLoopinJava.java
package com.dhavalkurkutiya;
public class CWH21WhileLoopinJava {
public static void main(String[] args) {
int i = 100;
while (i <= 200) {
System.out.print(i + "\n");
i++;
}
System.out.println("Finish While Loop");
while (true) {
System.out.println("I am Infinet");
break;
}
}
}
<file_sep>/CWH25PracticesSet.java
package com.dhavalkurkutiya;
public class CWH25PracticesSet {
public static void main (String[] args) {
// Practice Problem 1
/*
int n = 10;
for (int i = n; i>0; i--){
for (int j = 0; j<i; j++){
System.out.print("*");
}
System.out.print("\n");
}
*/
// Practice Problem 2
/*
int sum = 0;
int n = 3;
for (int i = 0; i<n; i++) {
sum = sum + (2*i);
}
System.out.print("Sum of Even Numbers: ");
System.out.print(sum);
*/
// PracticemProblem 3
/*
int n = 5;
for (int i = 1; i<=10; i++){
System.out.printf("%d X %d = %d\n", n, i, n*i);
}
*/
// PracticemProblem 4
/*
int n = 10;
for (int i = 10; i>=1; i--){
System.out.printf("%d X %d = %d\n", n, i, n*i);
}
*/
// PracticemProblem 5
// PracticemProblem 6
//What is a Factorial n = n*n-1 * n-2 .....1
// 5! = 5x4x3x3x1 = 120
/*
int n = 5;
int i =1;
int Factorial = 1;
while(i<=n){
Factorial *= i;
i++;
}
System.out.println(Factorial);
*/
// Practice Problem 9
int n = 8;
int sum = 0;
for (int i = 1; i<=10; i++){
sum += n*i;
}
System.out.println(sum);
}
}
<file_sep>/CWH11ExsizeSolution.java
package com.dhavalkurkutiya;
import java.util.Scanner;
public class CWH11ExsizeSolution {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
}
}
<file_sep>/CWH42Constructorsinjava.java
package com.dhavalkurkutiya;
class MyMainEmployee {
// private access modifire
private int id;
private String name;
// This is Constructor
public MyMainEmployee() {
id = 45;
name = "Your_Name_Hear";
}
// This is Constructor
public MyMainEmployee(String myName, int myId) {
id = myId;
name = myName;
}
// This is Constructor
public MyMainEmployee(String myName) {
id = 5;
name = myName;
}
// This mtahid to getName
public String getName() {
return name;
}
// This method to setName
public void setName(String n) {
this.name = n;
}
// This method to setId
public void setId(int i) {
this.id = i;
}
// This method to getId
public int getId() {
return id;
}
}
public class CWH42Constructorsinjava {
public static void main(String[] args) {
// MyMainEmployee harry = new MyMainEmployee("Dhavalkurkutiya",12);
MyMainEmployee harry = new MyMainEmployee();
// harry.setName("CodeWithHarry");
// harry.setId(67);
System.out.println(harry.getId());
System.out.println(harry.getName());
}
}
<file_sep>/CWH27ForEach.java
package com.dhavalkurkutiya;
public class CWH27ForEach {
public static void main (String[] args) {
/*
int [] Marks = {10,20,30,40,50,60,70,80,90,100};
float [] Marks = {10.1f,20.2f,30.3f,40.4f,50.5f,60.6f,70.7f,80.8f,90.9f,100.10f};
System.out.println(Marks.length);
System.out.println(Marks[1]);
String [] name = {"Dhaval" , "Harry" , "Lovesh"};
System.out.println(name.length);
System.out.println(name[0]);
*/
// Display tha Array (Naive Ways)
/* int [] Marks = {10,20,30,40,50};
System.out.println(Marks[0]);
System.out.println(Marks[1]);
System.out.println(Marks[2]);
System.out.println(Marks[3]);
System.out.println(Marks[4]);
*/
// Display tha Array (Fore Loop)
/*
System.out.println("Display Arry Using Fore loop");
int [] Marks = {10,20,30,40,50,60,70,80,90,100};
for (int i = 0; i<Marks.length;i++){
System.out.println(Marks[i]);
}
*/
/*
// Display tha Array in Reverse order(Fore Loop)
System.out.println("Display Arry Using Fore loop in Reverse order");
int [] Marks = {10,20,30,40,50,60,70,80,90,100};
for (int i = Marks.length -1; i>0;i--){
System.out.println(Marks[i]);
}
*/
// Display tha Array (For Each Loop)
System.out.println("Display Arry Using Fore Each loop");
int [] Marks = {10,20,30,40,50,60,70,80,90,100};
for(int element : Marks){
System.out.println(element);
}
}
}
<file_sep>/CWH31Mathodsinjava.java
package com.dhavalkurkutiya;
public class CWH31Mathodsinjava {
static int logic(int x , int y){
int z;
if (x > y) {
z = x + y;
}
else{
z = (x + y) * 5;
}
return z;
}
public static void main (String[] args) {
int a = 50;
int b = 7;
int c ;
// Mathod invocation using object Creation
// CWH31Mathodsinjava obj = new CWH31Mathodsinjava();
c = logic(a , b);
System.out.println(c);
int a1 = 5;
int b1 = 2;
int c1 ;
c1 = logic(a1 , b1);
System.out.println(c1);
}
}
<file_sep>/CWH04Literals.java
package com.dhavalkurkutiya;
public class CWH04Literals {
public static void main (String[] args) {
//Literals is right side value
byte age_1 = 50;
int age_2 = 68;
short sort = 66;
long log = 6789999999999999L; //Set long numbarb "L"
char chr = 'A';
float f1 = 6.8f; // set float
double d1 = 67.9D; // default doublen "D"
boolean b1 = true;
String str = "This is a java";
System.out.println(age_2);
}
}
<file_sep>/CWH17Logical.java
package com.dhavalkurkutiya;
public class CWH17Logical {
public static void main (String[] args) {
System.out.println("For Logical AND [&&] ...");
boolean a = true;
boolean b = true;
boolean c = true;
if (a && b && c){
System.out.println("Y");
}
else{
System.out.println("N");
}
System.out.println("For Logical Or [||]...");
boolean a1 = true;
boolean b2 = false;
boolean c3 = true;
if (a|| b){
System.out.println("Y");
}
else{
System.out.println("N");
}
System.out.println("For Logical Not [!]...");
System.out.print("Not (a) is ");
System.out.println(!a);
System.out.print("Not (b) is ");
System.out.println(!b);
}
}
<file_sep>/CWH06CBSE.java
package com.dhavalkurkutiya;
import java.util.Scanner;
public class CWH06CBSE {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
// System.out.println("Total Marks is 300");
System.out.println("Mathematics");
float Mathematics = sc.nextFloat();
System.out.println("Chemistry");
float Chemistry = sc.nextFloat();
System.out.println("Physics");
float Physics = sc.nextFloat();
float sum = Mathematics + Chemistry + Physics;
System.out.println(sum/3 + " %");
}
}
<file_sep>/CWH18SwitchStament.java
package com.dhavalkurkutiya;
import java.util.Scanner;
public class CWH18SwitchStament {
public static void main (String[] args) {
int age;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age:");
age = sc.nextInt();
switch(age) {
case 18:
System.out.println("You are Education");
break;
case 30:
System.out.println("You are job aply");
break;
case 60:
System.out.println("You are job Retaryerd");
break;
default:
System.out.println("You are Enjoy Life");
}
/*
if (age>56){
System.out.println("You are Expected");
}
else if (age>45) {
System.out.println("You are Noob");
}
else if (age>30) {
System.out.println("You are Noob");
}
else{
System.out.println("You are grat");
}
*/
}
}
<file_sep>/CWH16Conditionals.java
package com.dhavalkurkutiya;
public class CWH16Conditionals {
public static void main (String[] args) {
int age = 18;
if (age!=18){
System.out.println("Yas You can drive");
}
else{
System.out.println("Not You can drive");
}
}
}
<file_sep>/CWH32Mathadoverloadinginjava.java
package com.dhavalkurkutiya;
public class CWH32Mathadoverloadinginjava {
static void foo(){
System.out.println("Good Morning !");
}
static void foo(int a){
System.out.println("Good morning ! " + a + " Bro");
}
static void foo(int a , int b){ //(int a , int b) Perametter
System.out.println("Good morning ! " + a + " Bro");
System.out.println("Good morning ! " + b + " Bro");
}
static void chang1(int a) {
a = 98;
}
static void chang2(int[] arry) {
arry[0] = 70;
}
static void tailJocks() {
System.out.println("Hay I am Dhavalkurkutiya");
}
public static void main(String[] args) {
/* Case:1 Changing Tha Integer */
tailJocks();
// int x = 45; // Can't Chang valu of [X]
// chang1(x);
// System.out.println("Tha value is x after runing tha chang = " + x);
/* Case:2 Changing Tha Array */
// int[] marks = {56, 88, 98, 88, 78}; // Chang this value only refrance pass
// chang2(marks);
// System.out.println("Tha value is chang2 after runing tha chang2 = " + marks[0]);
/* Mathadoverloading */
//foo();
// foo(a , 333);
//foo(a , 300 , b ,500); //Argument
}
}
| d8cb63b174c8d37138eb524d5cd866443c39b12f | [
"Java"
] | 21 | Java | Dhavalkurkutiya/Java-Tutorial | 4567bad6a14cd497383aa8a9a56a4d4e8364ec99 | fb875ebd0500a7006e4ca49f9d23b5ef6dd1a3cc | |
refs/heads/master | <repo_name>gdisneyleugers/redisshell<file_sep>/Reloader.py
__author__ = 'gregorydisney'
import RKeyClient
RKeyClient
if __name__ == '__main__':
import RKeyClient
RKeyClient<file_sep>/RSet.py
__author__ = 'gregorydisney'
from RedisController import RedisConnect
db = RedisConnect.r
class RedisSet:
name = raw_input("Name: ")
value = raw_input("Value: ")
db.set(name,value)
import RKeyClient
RKeyClient
if __name__ == '__main__':
import RKeyClient
RKeyClient<file_sep>/RKeyClient.py
__author__ = 'gregorydisney'
while True:
rediscmd = ['get', 'set', 'keys', 'connect', 'help', 'flush', 'reload', 'exit']
cmd = raw_input("Redis-Shell=> ")
def Reload(self):
self = RKeyClient
import Reloader
Reloader
if cmd == 'get':
import RGet
RGet.RedisGet()
import Reloader
Reloader
if cmd == 'keys':
import RKeys
RKeys.RedisKeys()
import Reloader
Reloader
if cmd == 'connect':
import RedisController
RedisController.RedisConnect()
print RedisController.RedisConnect.r
import Reloader
Reloader
if cmd == 'set':
import RSet
RSet.RedisSet()
import Reloader
Reloader
if cmd == 'exit':
print "Exiting"
quit()
if cmd == 'help':
print "Options: \n"
print "get: Query key in DB\n"
print "set: Set key in DB\n"
print "keys: Show all keys in DB\n"
print "connect: Connect to Redis DB\n"
print "flush: Flush Redis DB"
import Reloader
Reloader
if cmd == 'reload':
print "Reloading Shell"
import Reloader
Reloader
if cmd == 'flush':
import RedisController
db = RedisController.RedisConnect.r
db.flushall()
print "DB flushed"
import Reloader
Reloader
if cmd not in rediscmd:
for a in enumerate(rediscmd):
print "Command is: " + cmd + "\n"
print "Allowed comand: " + ''.join(str(a)) + "\n"
import Reloader
if __name__ == '__main__':
import RKeyClient<file_sep>/RKeys.py
__author__ = 'gregorydisney'
import redis
def pattern(self):
pass
class RedisKeys:
r = redis.StrictRedis()
keys = r.keys("*")
a = ''.join(keys)
for i,elem in enumerate(keys):
print elem + "\n"
if __name__ == '__main__':
import RKeyClient<file_sep>/RedisController.py
__author__ = 'gregorydisney'
import redis
class RedisConnect:
r = redis.StrictRedis()
<file_sep>/RGet.py
__author__ = 'gregorydisney'
from RedisController import RedisConnect
db = RedisConnect.r
class RedisGet:
n = raw_input("Name: ")
a = db.get(n)
print a
if __name__ == '__main__':
import RKeyClient | 589be702793127f014636e04a6b15ba493708da2 | [
"Python"
] | 6 | Python | gdisneyleugers/redisshell | 7f6634ca0a9dd3264c4be42d5255893b10832a6b | 8d4bef40e4c7033a041663d94aecd85c541bdba7 | |
refs/heads/master | <file_sep>var express = require('express')
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server)
var PORT = 8888;
server.listen(PORT);
var gSocket = null;
function sendKey(code, callback) {
if (gSocket!=null) {
console.log('emit');
gSocket.emit('keyCode', code);
}
}
app.get('/', function (req, res) {
res.sendfile(__dirname + '/README.md');
});
app.get('/display', function (req, res) {
res.sendfile(__dirname + '/display.html');
});
app.get('/:char', function (req, res) {
sendKey(req.params.char);
console.log('respond char : ' + req.params.char);
res.sendfile(__dirname + '/README.md');
});
io.sockets.on('connection', function (socket) {
gSocket = socket;
console.log("connection");
});
<file_sep># Ringraffiti
Graffiti input system by Ring.
| 04b64fd712de211affda8b0c14c2f770d4e52a2f | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | gmkou/Ringraffiti | 65c934f3f44536126942c2b59ca5dc0cea30698a | 3346b0fdd82cb32ebfe3546a6360ef5136ea5be3 | |
refs/heads/master | <repo_name>pchinjr/valentines-day-bot<file_sep>/README.md
# Valentine's Day Bot
> :heart: :cat:
>
> Tweets a special reply to mentions using the correct #hashtag.
>
> Uses Serverless framework and AWS Lambda.
## Try it out
Mention `@thesecatstweet` in a tweet and don't forget the hashtag `#happyvalentinebot`.
## About
This is a demonstration project for Serverless bots inspired by other useful bots
and other cute bots.
* The `handleMentions` function does scheduled polling of mentions to perform replies
(if you want a :100: Serverless application)
* The `reply` function performs just the favoriting and reply to a mention
(can be called by the Twitter Streams API)
## Install
With [node](https://nodejs.org/) installed, install the Serverless Architecture:
```
$ npm i -g serverless
```
Clone this repository
```
$ git clone <EMAIL>:lynnaloo/valentines-day-bot.git
```
Install dependencies
```
$ npm i
```
## Setup and Testing
Setup your Account Provider and Credentials
* [AWS Lambda](https://serverless.com/framework/docs/providers/aws/setup)
* [AWS account credentials](https://serverless.com/framework/docs/providers/aws/guide/credentials)
Run Unit Tests
```
npm test
```
Test Lambda Function locally
```
serverless invoke local -l -f handleMentions
```
## Deployment
Deploy Lambda Functions
```
$ sls deploy -v
```
## See Also
* [Serverless Framework](http://www.serverless.com)
* [Adopt-a-Pet Bot](https://github.com/lynnaloo/adoptable-pet-bot)
* [Rachel's Cute Bot](https://github.com/rachelnicole/magicalncute)
## License
MIT
<file_sep>/lib/responses.js
'use strict';
module.exports = [
'Happy Valentine\'s Day! You\'ll never be null in my interpreter.',
'Happy Valentine\'s Day! My response to you is never undefined.',
'Happy Valentine\'s Day! Our friendship has no bugs!',
'Happy Valentine\'s Day! You\'re my favorite human.'
];
| 5decd656c9d3e1ca8cd58941a8bde7c8c91b7ad8 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | pchinjr/valentines-day-bot | 39868395e590016df0859ef2ed3a5fd7fe10396b | 1230c45c581d0d4b5496afb249cadd8938ce726a |