branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/main
|
<repo_name>Deepesh368/TODO_web_app<file_sep>/app.js
const path = require('path');
const express = require('express');
const app = express();
const port = 5000;
app.use(express.static('public'));
app.set('views', './views');
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html');
});
app.listen(port, () => console.info(`App listening on port ${port}`));
|
b63bbfddbb3f95e9cc84a350029ba70afc146909
|
[
"JavaScript"
] | 1 |
JavaScript
|
Deepesh368/TODO_web_app
|
6cbaaf37fab68410a8616fe20d3a36e49403445b
|
6ca66d060bbfdbf4f3344e4ee5180bb13fd25889
|
refs/heads/master
|
<file_sep>from sqlalchemy import create_engine # начните работу с этой библиотеки
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import mapper, sessionmaker
from User import User
db_conn_string = 'postgresql://postgres:123456@localhost/postgres'
engine = create_engine(db_conn_string, echo=False)
metadata = MetaData()
users_table = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(50)),
Column('fullname', String(50)),
Column('password', String(50))
)
# metadata.create_all(engine)
mapper(User, users_table)
# user = User('Вася', 'Василий', '<PASSWORD>')
# print(user)
# print(user.id)
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
# session.add(user)
ourUser = session.query(User).filter_by(name="Вася").first()
ourUser.password = '<PASSWORD>'
print(ourUser, ourUser.id)
<file_sep>class User(object):
def __init__(self, name, fullname, password):
self.name = name
self.fullname = fullname
self.password = <PASSWORD>
def __repr__(self):
return "<User(%r, %r, %r)>" % (self.name, self.fullname, self.password)
|
a9c45237caceaec5b5c355d3931e976b0348844e
|
[
"Python"
] | 2 |
Python
|
konstantinov90/postgre_python_test
|
506356b4084bad05fdcb33e620f557a92bee2949
|
8d756631ea001ed5dc5c7fb8e3317364b59257e1
|
refs/heads/master
|
<repo_name>tjstankus/proper<file_sep>/lib/proper.rb
require "proper/version"
module Proper
# Your code goes here...
end
|
e1b38bf45c1f97f6da4ca5f1c0a33ead19ebabb2
|
[
"Ruby"
] | 1 |
Ruby
|
tjstankus/proper
|
666082a061b0daef85ade6251a034ad64088ba20
|
25d81917b026955892c1bac6dea4e64fc4008543
|
refs/heads/main
|
<file_sep>import friends from '../data/friends.json';
import statisticalData from '../data/statistical-data.json';
import user from '../data/user.json';
import transaction from '../data/transactions.json';
const data = { friends, statisticalData, user, transaction };
export default data;
|
eb393d549a6d12daa7866687382d9e2b49cec046
|
[
"JavaScript"
] | 1 |
JavaScript
|
OleksandrPenskyi/goit-react-hw-01-components
|
8e190a5519e0881fd7548e4f1efa6c4cfa9a1439
|
a21b41003e87ce0094593c2012415f8cc1d57357
|
refs/heads/master
|
<file_sep>import numpy as np
import matplotlib.pyplot as plt
mymatrix = np.loadtxt('f237',delimiter=',',skiprows=2)
# mymatrix[:,0] = (mymatrix[:,0] - 5361.)
mymatrix[:,0] = (mymatrix[:,0])
s = mymatrix[:,0]
print(s)
t = np.linspace(0,.005,np.shape(s)[0])
# plt.ylabel("Amplitude")
# plt.xlabel("Time [s]")
# plt.plot(t, s)
# plt.show()
t = np.linspace(0, 0.05, 500)
s = np.sin(40 * 2 * np.pi * t)
plt.ylabel("Amplitude")
plt.xlabel("Time [s]")
plt.plot(t, s)
plt.show()
fft = np.fft.fft(s)
T = t[1] - t[0] # sampling interval
N = s.size
# 1/T = frequency
f = np.linspace(0, 1 / T, N)
print(f)
print("hello")
print(fft*1/N)
plt.ylabel("Amplitude")
plt.xlabel("Frequency [Hz]")
plt.bar(f[:N // 2], np.abs(fft)[:N // 2] * 1 / N, width=1.5) # 1 / N is a normalization factor
plt.show()<file_sep>import numpy as np
import matplotlib.pyplot as plt
time_data_collect = 49928.
number_data_points = 1700
Y0=np.loadtxt('one_thousand_position_readings')
# Y0=position_data[:]
Y1=np.loadtxt('one_thousand_velocity_readings')
# Y1=velocity_data[:]
X = np.linspace(0.,time_data_collect,number_data_points)
# X = t[:]
plt.figure(0)
plt.plot(X,Y0,':ro')
# plt.ylim((0,55000))
# plt.show() #or
plt.savefig('positions.png')
plt.figure(1)
plt.plot(X,Y1,':go')
plt.savefig('velocities.png')
plt.show()<file_sep>"""
===========================
Furuta Pendulum Simulation
===========================
This animation illustrates the Furuta Pendulum problem.
"""
# Code modified from Double Pendulum animation example code found here:
# https://matplotlib.org/examples/animation/double_pendulum_animated.html
# Dynamics and State Space Representation found from paper:
# "Nonlinear stabilization control of Furuta pendulum only
# using angle position measurements"
# Authors: <NAME>, <NAME>, <NAME>, <NAME>
import time
t0 = time.time()
from numpy import sin, cos
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animation
# import cv2
# import math
G = 9.8 # acceleration due to gravity, in m/s^2
# Motor
M1 = .0695 # mass of pendulum 1 in kg
L1 = .035 # length of pendulum 1 in m
l1 = 0.025 # radius of center of mass
J1 = 0.00015625
B1 = 0.0
# Pendulum
M2 = .025 # mass of pendulum 2 in kg
L2 = 0.06 # length of pendulum 2 in m
l2 = 0.03 # radius
J2 = 0.00003
B2 = 0.0
# FRIC1 = .3 # friction coefficient (* by velocity)
# FRIC2 = .3 # friction coefficient (* by velocity)
# A1 = J1 + M1 * R1 * R1
# A2 = M1 * R1 * L2
# A3 = J2 + M2 * R2 * R2 + M1 * L2 * L2
# A4 = M1 * G * R1
A0 = J1 + M1 * l1 * l1 + M2 * L1 * L1
A2 = J2 + M2 * l2 * l2
peak_torque_output = 0.0 # track maximum torque output from motor
time_to_45degree_error = np.inf # track time to get nearly upright
def derivs(state, t):
dydx = np.zeros_like(state)
global peak_torque_output
global time_to_45degree_error
# if (t<20.0):
# if (state[2] > 2.96706) or (state[2] < -2.96706):
# if ((np.pi - abs(state[2])) * np.sign(state[2]) * .05) > 0:
# tau1 = .05
# elif ((np.pi - abs(state[2])) * np.sign(state[2]) * .05) < 0:
# tau1 = -.05
# tau1 = (np.pi - abs(state[2])) * np.sign(state[2]) * .18 - 0.004 * state[3]
# tau1 = (np.pi - abs(state[2])) * np.sign(state[2]) * .18
tau1 = 0.0
# tau1 = 0.0
# else:
# tau1 = -state[3] * 0.001 # motor torque
# if t < time_to_45degree_error:
if (abs(tau1) > abs(peak_torque_output)):
peak_torque_output = tau1
if (state[2] > 2.35619) or (state[2] < -2.35619):
time_to_45degree_error = t
# tau1 = 0.0
# else:
# tau1 = 0.0
# tau2 = 0.0 # disturbance torque (system not actuated here)!
tau2 = -.00001 * state[3] # apply friction
mytwos = 2 * state[2]
dydx[0] = state[1]
dydx[1] = (2 * A2 * tau1 - 2 * A2 * B1 * state[1] - 2 * L1 * l2 * M2 * tau2 * cos(state[2]) \
+ 2 * B2 * L1 * l2 * M2 * state[3] * cos(state[2]) \
+ 2 * A2 * L1 * l2 * M2 * state[3] * state[3] * sin(state[2]) \
+ 2 * G * L1 * l2 * l2 * M2 * M2 * cos(state[2]) * sin(state[2]) \
- 2 * A2 * A2 * state[1] * state[3] * sin( mytwos ) \
- A2 * L1 * l2 * M2 * state[1] * state[1] * cos(state[2]) * sin(mytwos)) \
/ ( 2 * ( A0 * A2 - L1 * L1 * l2 * l2 * M2 * M2 * cos(state[2]) * cos(state[2]) + A2 * A2 * sin(state[2]) * sin(state[2]) ) )
dydx[2] = state[3]
dydx[3] = (2 * A0 * tau2 \
- 2 * A0 * B2 * state[2] \
- 2 * L1 * l2 * M2 * tau1 * cos(state[2]) \
+ 2 * B1 * L1 * l2 * M2 * state[1] * cos(state[2]) \
- 2 * A0 * G * l2 * M2 * sin(state[2]) \
- 2 * L1 * L1 * l2 * l2 * M2 * M2 * state[3] * state[3] * cos(state[2]) * sin(state[2]) \
+ 2 * A2 * tau2 * sin(state[2]) * sin(state[2]) \
- 2 * A2 * B2 * state[3] * sin(state[2]) * sin(state[2]) \
- 2 * A2 * B2 * state[3] * sin(state[2]) * sin(state[2]) \
- 2 * A2 * G * l2 * M2 * sin(state[2]) * sin(state[2]) * sin(state[2])
+ A0 * A2 * state[1] * state[1] * sin(mytwos) \
+ 2 * A2 * L1 * l2 * M2 * state[1] * state[3] * cos(state[2]) * sin(mytwos) \
+ A2 * A2 * state[1] * state[1] * sin(state[2]) * sin(state[2]) * sin(mytwos) ) \
/ ( 2 * (A0 * A2 - L1 * L1 * l2 * l2 * M2 * M2 * cos(state[2]) * cos(state[2]) + A2 * A2 * sin(state[2]) * sin(state[2]) ) )
return dydx
# create a time array from 0..100 sampled at 0.01 second steps
# dt = 0.03125
dt = 0.01428571428
t = np.arange(0.0, 15.0, dt)
myfps = int(1/dt)
myinterval = int(dt*1000)
# Initial conditions
q1 = 180.0 # angle of motor
q1d = 0.0 # initial angular speed of motor
q2 = 177.0 # angle of pendulum
q2d = 0.0 # initial angular speed of pendulum
# X1, X2, X3, X4 are the state space representation
# X1 = q1
# X2 = A1 * q1d - A2 * cos(math.radians(q1) * math.radians(q2d))
# X3 = q2
# X4 = q2d
# initial state
state = np.radians([q1, q1d, q2, q2d])
# integrate your ODE using scipy.integrate.
y = integrate.odeint(derivs, state, t)
x1 = -L1*sin(y[:, 0])
y1 = L1*cos(y[:, 0])
x2 = L2*sin(y[:, 2])
y2 = -L2*cos(y[:, 2])
fig = plt.figure()
ax = fig.add_subplot(111, autoscale_on=False, xlim=(-0.1, 0.1), ylim=(-0.1, 0.1))
fig.gca().set_aspect('equal',adjustable='box')
ax.grid()
line, = ax.plot([], [], 'o-', lw=2)
line2, = ax.plot([], [], 'o-', lw=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
def init():
line.set_data([], [])
time_text.set_text('')
return line, time_text
def animate(i):
thisx = [0, x1[i]]
thisy = [0, y1[i]]
thisx2 = [0, x2[i]]
thisy2 = [0, y2[i]]
line.set_data(thisx, thisy)
line2.set_data(thisx2,thisy2)
time_text.set_text(time_template % (i*dt))
return line, line2, time_text
ani = animation.FuncAnimation(fig, animate, np.arange(1, len(y)),
interval=0, blit=False, init_func=init)
# Set up formatting for the movie files
# Writer = animation.writers['ffmpeg']
# writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
ani.save('f3.mp4', fps=myfps, dpi=60, writer='ffmpeg')
# plt.show()
print("peak torque used was ", peak_torque_output, " Nm.")
print("time to reach less than 45 degree error: ", time_to_45degree_error)
t1 = time.time()
print(t1-t0)
<file_sep>import time
t0 = time.time()
import odrive
from odrive.enums import *
print("finding an odrive...")
my_drive = odrive.find_any()
# Calibrate motor and wait for it to finish
print("starting calibration...")
my_drive.axis0.requested_state = AXIS_STATE_FULL_CALIBRATION_SEQUENCE
while my_drive.axis0.current_state != AXIS_STATE_IDLE:
time.sleep(0.1)
time.sleep(1)
# To read a value, simply read the property
print("Bus voltage is " + str(my_drive.vbus_voltage) + "V")
my_drive.axis0.controller.config.vel_limit = 70000
print("Velocity limit is ", str(my_drive.axis0.controller.config.vel_limit))
# my_drive.axis0.motor.config.current_lim = 30
my_drive.axis0.controller.config.control_mode = CTRL_MODE_CURRENT_CONTROL
print("Ctrl mode is ", str(my_drive.axis0.controller.config.control_mode))
my_drive.axis0.controller.current_setpoint = 0.3
print("Current setpoint is ", str(my_drive.axis0.controller.current_setpoint))
my_drive.axis0.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL
print("State: ", str(my_drive.axis0.current_state))
while my_drive.axis0.current_state != AXIS_STATE_IDLE:
print(my_drive.vbus_voltage)
print(my_drive.axis0.motor.current_control.Iq_measured)
time.sleep(0.1)
# time.sleep(40)
#
# while my_drive.axis0.requested_state == AXIS_STATE_CLOSED_LOOP_CONTROL:
# print(my_drive.vbus_voltage)
# time.sleep(0.1)
# print(hex(mot/error)
my_drive.axis0.requested_state = AXIS_STATE_IDLE
t1 = time.time()
print("code run time: ",t1-t0)<file_sep>import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import sepfir2d
# TO TRY: SUBTRACT THE DERIVATIVE OF THE PROPORTIONAL ERROR, ADD
# mymatrix = np.loadtxt('f255',delimiter=',',skiprows=2)
# mymatrix = np.loadtxt('a412',delimiter=',',skiprows=2)
# mymatrix = np.loadtxt('pgain00285dc015left',delimiter=',',skiprows=2)
myfilename = 'g0632'
lookup = ','
# lookup2 = 'STARTING'
with open(myfilename) as myFile:
for num, line in enumerate(myFile, 1):
if lookup in line: print('found comma at line:', num); break
# if lookup2 in line: print('found at line:', num); break
mymatrix = np.loadtxt(myfilename,delimiter=',',skiprows=num-1)
print(mymatrix)
mymatrix[:,0] = (mymatrix[:,0] - 5440.)/200
# mymatrix[:,0] = sepfir2d(mymatrix[:,0], 2, 0)
a = np.fft.fft(mymatrix[:,0])
# mymatrix[:,2] = mymatrix[:,2]/0.0003834951969714103074295218974/0.15/1000
# mymatrix[:,2] = mymatrix[:,2]
# a = mymatrix[:,2]
# b = np.reshape(a,(np.shape(a)[0],1))
#
# # mymatrix[:,:-1] = np.transpose(mymatrix[:,2])
# print(np.transpose(mymatrix[:,2]))
# print(np.shape(a))
# print(np.shape(np.transpose(a)))
# print(np.shape(b))
# newmatrix = np.append(mymatrix,b,axis=1)
# print(newmatrix)
# print(newmatrix)
plt.axhline(y=0, color='r', linestyle='-')
# plt.legend("ah")
plt.plot(mymatrix[:,0], '.',label='position')
plt.plot(mymatrix[:,1], label='current')
plt.plot(mymatrix[:,2], label='Proportional')
plt.plot(mymatrix[:,3], label='Derivative')
plt.legend(loc='upper left')
plt.savefig(myfilename + '.png')
# plt.savefig(myfilename + '.svg')
plt.show()
<file_sep># furuta-pendulum
This is a python simulation of a [Furuta Pendulum](https://en.wikipedia.org/wiki/Furuta_pendulum), (though the final simulation was moved over to MATLAB).
Hardware Video: https://www.youtube.com/watch?v=xowrt6ShdCw
Video of simulated [Swing-up](https://drive.google.com/file/d/1S6-EbsayWW5-o18eGSLLA2UU1cRS-E2y/view?usp=sharing)
Video of simulated [balancing (PD Control)](https://drive.google.com/file/d/1gIvbGe5FHMjtKigN6REe39BbWgFBypCI/view?usp=sharing)
|
c64597722919e3929f883218a13b57171fba3978
|
[
"Markdown",
"Python"
] | 6 |
Python
|
tangmack/furuta-pendulum
|
4cee88e92270acfcdf33c41710392ff5a7372d2c
|
eb1fdba725cdf9a04a7e14a0dc1f917ea6ae83b7
|
refs/heads/master
|
<file_sep>from django.shortcuts import render, redirect
from . forms import movieForm
from . models import movies
from django.contrib.auth.decorators import login_required, permission_required
# Create your views here.
@login_required
def index(request):
movie = movies.objects.all()
return render(request, "index.html", {
'movie': movie
})
@login_required
def create(request):
form = movieForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
return redirect("index")
return render(request, "create.html", {
'form': form
})
@login_required
@permission_required("netflix.view_movie")
def show(request, id):
movie = movies.objects.get(pk=id)
return render(request, "show.html", {
'movie': movie
})
@login_required
def update(request, id):
movie = movies.objects.get(pk=id)
form = movieForm(request.POST or None, request.FILES or None, instance=movie)
if form.is_valid():
form.save()
return redirect("index")
return render(request, "update.html", {
'form': form,
'movie': movie
})
@login_required
def delete(request, id):
movie = movies.objects.get(pk=id)
movie.delete()
return redirect("index")<file_sep>from django import forms
from django.core.exceptions import ValidationError
from . models import Category, movies
not_allowed_name = ["admin"]
class customForm(forms.Form):
name = forms.CharField(max_length=233)
password = forms.CharField(widget=forms.PasswordInput)
def clean(self):
name = self.cleaned_data.get("name")
if name in not_allowed_name:
return ValidationError("name is not allowed")
class movieForm(forms.ModelForm):
class Meta:
model = movies
fields = "__all__"
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = "__all__"
<file_sep># lab-django
<file_sep>from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=100, null=True)
def __str__(self):
return self.name
class movies(models.Model):
title = models.CharField(max_length=255)
overview = models.TextField()
year = models.DateField()
poster = models.ImageField(upload_to="movie/posters")
video = models.FileField(upload_to="movie/video")
categories = models.ManyToManyField(Category)<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name = 'index'),
path('create', views.create, name = 'create'),
path('show/<int:id>', views.show, name = 'show'),
path('update/<int:id>', views.update, name = 'update'),
path('delete/<int:id>', views.delete, name = 'delete'),
]
|
400ccb184222222e8e4553be08887557f44eecf7
|
[
"Markdown",
"Python"
] | 5 |
Python
|
ayahmed2050/lab-django
|
375e000a8b0ea315b9f3abc82b490dbe3248c8d0
|
4f8e10b4cd458d15ae5d6e2f564775e8449ea236
|
refs/heads/master
|
<file_sep>(function(){
'use strict';
angular.module('angularSandboxApp')
.controller('projectEditorController', ['projectsService', '$stateParams', '$state', projectEditorController]);
function projectEditorController(projectsService, $stateParams, $state) {
var vm = this;
var id = $stateParams.id;
if (id === 'new'){
// create a new project
}
if (parseInt(id) != id){
$state.go('projects');
}
vm.instruments = projectsService.getInstrumentTypes();
vm.project = projectsService.getProjectById(parseInt(id));
vm.formlyFields = [
{
key: 'id',
type: 'input',
templateOptions: {
label: 'Project ID'
}
},
{
key: 'name',
type: 'input',
templateOptions: {
label: 'Project Name',
placeHolder: 'Enter Project Name'
}
},
{
key: 'description',
type: 'textarea',
templateOptions: {
label: 'Description',
rows: 5
}
}
];
}
}());<file_sep>/**
* Created by pwaivers on 2/26/15.
*/
(function(){
'use strict';
angular.module('angularSandboxApp')
.controller('loginController', function(){
var that = this;
that.userName = '';
that.password = '';
});
}());<file_sep>(function(){
'use strict';
angular.module('angularSandboxApp')
.factory('projectsService', ['lodash', projectsService]);
function projectsService(lodash){
var _ = lodash;
var projects = {};
projects.getAll = getAll;
projects.getProjectById = getProjectById;
projects.getInstrumentTypes = getInstrumentTypes;
var dummyData =
[
{
id: 1,
name: 'Mad World',
userName: 'chubs3000',
instrument: 'guitar',
description: 'This is a cover of the Gary Jules song (which is cover of an older song)'
},
{
id: 27,
name: '<NAME>irl by <NAME>',
userName: 'chubs300',
instrument: 'piano'
}
];
function getAll(){
return dummyData;
}
function getProjectById(id){
var project = _.findWhere(dummyData, {'id': id});
return project;
}
function getInstrumentTypes() {
return ['guitar', 'piano', 'ukulele', 'drums', 'vocal', 'bass', 'other'];
}
return projects;
}
}());<file_sep>'use strict';
angular
.module('angularSandboxApp', ['ui.router', 'ngLodash', 'ngMessages'])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home/home.html'
})
.state('about', {
url: '/about',
templateUrl: 'about/about.html'
})
.state('projects', {
url: '/projects',
templateUrl: 'projects/projects.html',
controller: 'projectsController as projectsCtrl'
})
.state('projects.editor', {
url: '/{id}',
templateUrl: 'projects/project.editor.html',
controller: 'projectEditorController as vm'
})
.state('account', {
url: 'account',
templateUrl: 'account/account.html'
})
.state('account.login', {
url: '/login',
templateUrl: 'account/login/login.html',
controller: 'loginController as loginCtrl'
})
.state('account.register', {
url: '/register',
templateUrl: 'account/register/register.html',
controller: 'registerController as registerCtrl'
});
});
<file_sep>'use strict';
angular.module('angularSandboxApp')
.factory('cache', function () {
// Public API here
var CacheService = function(){
var that = this;
that.getCache = function () {
};
that.pushToCache = function () {
};
that.pullFromCache = function () {
};
};
return new CacheService();
});
<file_sep># AngularSandbox
AngularJS Sandbox and Seed Application
## Setup
You should already have `node` and `bower` installed.
First, install the node packages
```
> npm install
```
Then, install the bower packages
```
> bower install
```
Lastly, run `grunt`
```
> grunt
```
## What is included in this project
* AngularJS
* Bootstrap
* Grunt
* Forms and validation
* UI-Routing with sub-routes
## To Be Added
* Unit Testing - Karma and Jasmine stack
<file_sep>(function() {
'use strict';
angular.module('angularSandboxApp')
.controller('projectsController', ['projectsService', projectsController]);
function projectsController(projectService){
var vm = this;
vm.title = 'Projects Page';
vm.projects = projectService.getAll();
}
}());<file_sep>/**
* Created with JetBrains WebStorm.
* User: admin
* Date: 2/26/15
* Time: 6:28 PM
* To change this template use File | Settings | File Templates.
*/
(function(){
'use strict';
angular.module('angularSandboxApp')
.controller('registerController', registerController);
function registerController(){
var that = this;
}
}());
|
1f7155d1a2071043f0fa16b91e2fd67889c79321
|
[
"JavaScript",
"Markdown"
] | 8 |
JavaScript
|
pwaivers/AngularSandbox
|
a5ceec2d57bc4d94fb8e7c86e134762b3651db81
|
bf20c6c340aae516de4151d3e2d99f532a2838a4
|
refs/heads/master
|
<file_sep>#FROM node:6
# Create code directory
#RUN mkdir -p /code
# Bundle app source
#WORKDIR /code/
# Set permissions for node and set timezone
#RUN chown -h $USER /code
# Set code as workdir
#WORKDIR /code
# Set user to node
#USER node
#CMD [ "npm", "start" ]
FROM node:6
#RUN git clone https://github.com/preboot/angular2-webpack.git
WORKDIR current-website
RUN sed -i.bak 's/--port 8080/--host 0.0.0.0 --port 8080/' package.json
RUN npm i
EXPOSE 8080
CMD [ "npm", "run", "start" ]
<file_sep>import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'my-nav-component',
template: require('./navigation.component.html'),
styles: [require('./navigation.component.scss')],
encapsulation: ViewEncapsulation.None,
})
export class MyNavComponent {
constructor() {
}
}
<file_sep>import {Component} from '@angular/core';
import {NgClass} from '@angular/common';
@Component({
selector: "[navTrigger]",
template: '<button (click)="onClick()">Click me</button>',
directives: [NgClass],
})
export class NavigationDirective {
isOn = false;
constructor(){
}
onClick() {
this.isOn = !this.isOn;
}
}
<file_sep>import {
it,
inject,
describe,
beforeEachProviders,
} from '@angular/core/testing';
// Load the implementations that should be tested
import { NavComponent } from './navigation.component';
describe('Nav', () => {
// provide our implementations or mocks to the dependency injector
beforeEachProviders(() => [
NavComponent
]);
it('should log ngOnInit', inject([NavComponent], (nav) => {
expect(nav).toBeDefined();
}));
});
<file_sep># troonhouse
# troonhouse
<file_sep>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MyNavComponent } from '../navigation/navigation.component';
const DECLARATIONS = [ MyNavComponent ];
@NgModule( {
declarations : DECLARATIONS ,
exports : DECLARATIONS
} )
export class NavModule {
}
<file_sep>import { TestBed } from '@angular/core/testing';
import { MyNavComponent } from './navigation.component';
describe('NavComponent Component', () => {
beforeEach(() => {
TestBed.configureTestingModule({declarations: [MyNavComponent]});
});
it('should ...', () => {
const fixture = TestBed.createComponent(MyNavComponent);
fixture.detectChanges();
//console.log(fixture.nativeElement.children[0].textContent);
expect(fixture.nativeElement.children[0]).toBeDefined();
});
});
|
82886e6f57da0256fbaa38a00e90c08ae1dd33d3
|
[
"Markdown",
"TypeScript",
"Dockerfile"
] | 7 |
Dockerfile
|
seanrkerr/troonhouse
|
df48b0b80a2089ad900fbd53359ae62614af9c0b
|
36827ebe278e23ad255a8d8ab738b1f6629d31b5
|
refs/heads/master
|
<file_sep>
// ImageProcToolView.h : CImageProcToolView 类的接口
//
#pragma once
#include "resource.h"
class CImageProcToolView : public CFormView
{
protected: // 仅从序列化创建
CImageProcToolView();
DECLARE_DYNCREATE(CImageProcToolView)
public:
enum{ IDD = IDD_VISIONPLATFORM_FORM };
// 特性
public:
CImageProcToolDoc* GetDocument() const;
// 操作
public:
// 重写
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
virtual void OnInitialUpdate(); // 构造后第一次调用
// 实现
public:
virtual ~CImageProcToolView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// 生成的消息映射函数
protected:
afx_msg void OnFilePrintPreview();
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // ImageProcToolView.cpp 中的调试版本
inline CImageProcToolDoc* CImageProcToolView::GetDocument() const
{ return reinterpret_cast<CImageProcToolDoc*>(m_pDocument); }
#endif
<file_sep>// 001View.h : interface of the C001View class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_001VIEW_H__E59FEFE7_63B5_4F0D_9D5D_03FB71D31430__INCLUDED_)
#define AFX_001VIEW_H__E59FEFE7_63B5_4F0D_9D5D_03FB71D31430__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "ImageProcToolDoc.h"
class C001View : public CEditView
{
protected: // create from serialization only
C001View();
DECLARE_DYNCREATE(C001View)
// Attributes
public:
CImageProcToolDoc * GetDocument();
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(C001View)
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~C001View();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(C001View)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in 001View.cpp
inline CSpltDoc* C001View::GetDocument()
{ return (CSpltDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_001VIEW_H__E59FEFE7_63B5_4F0D_9D5D_03FB71D31430__INCLUDED_)
<file_sep>#if !defined(AFX_002VIEW_H__8C0B9C04_831E_43E0_9952_BD9B843AB074__INCLUDED_)
#define AFX_002VIEW_H__8C0B9C04_831E_43E0_9952_BD9B843AB074__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// 002View.h : header file
//
#include "ImageProcToolDoc.h"
#include <afxcview.h>
/////////////////////////////////////////////////////////////////////////////
// C002View view
class C002View : public CListView
{
protected:
C002View(); // protected constructor used by dynamic creation
DECLARE_DYNCREATE(C002View)
// Attributes
public:
CImageProcToolDoc* GetDocument();
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(C002View)
public:
virtual void OnInitialUpdate();
protected:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
// Implementation
protected:
virtual ~C002View();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
protected:
//{{AFX_MSG(C002View)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in 001View.cpp
inline ImageProcToolDoc* C002View::GetDocument()
{ return (ImageProcToolDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_002VIEW_H__8C0B9C04_831E_43E0_9952_BD9B843AB074__INCLUDED_)
<file_sep>
// ChildFrm.cpp : CChildFrame 类的实现
//
#include "stdafx.h"
#include "ImageProcTool.h"
#include "ChildFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CChildFrame
IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWndEx)
BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWndEx)
END_MESSAGE_MAP()
// CChildFrame 构造/析构
CChildFrame::CChildFrame()
{
// TODO: 在此添加成员初始化代码
}
CChildFrame::~CChildFrame()
{
}
//BOOL CChildFrame::OnCreateClient(LPCREATESTRUCT /*lpcs*/, CCreateContext* pContext)
//{
// return m_wndSplitter.Create(this,
// 2, 2, // TODO: 调整行数和列数
// CSize(10, 10), // TODO: 调整最小窗格大小
// pContext);
//}
BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: 在此处通过修改 CREATESTRUCT cs 来修改窗口类或样式
if( !CMDIChildWndEx::PreCreateWindow(cs) )
return FALSE;
return TRUE;
}
// CChildFrame 诊断
#ifdef _DEBUG
void CChildFrame::AssertValid() const
{
CMDIChildWndEx::AssertValid();
}
void CChildFrame::Dump(CDumpContext& dc) const
{
CMDIChildWndEx::Dump(dc);
}
#endif //_DEBUG
// CChildFrame 消息处理程序
BOOL CChildFrame::OnCreateClient(LPCREATESTRUCT /*lpcs*/,
CCreateContext* pContext)
{
//BOOL ret=m_wndSplitter.CreateStatic(this,3,2);
BOOL ret=m_wndSplitter.CreateStatic(this,2,2);
if(!ret)
{
TRACE("SplitCreate Failed...\n");
return ret;
}
//计算窗口尺寸
CRect rt;
GetClientRect(&rt);
//CSize czPane(rt.Width()/2, rt.Height()/3);
CSize czPane(rt.Width()/2, rt.Height()/2);
// ------------- 1 ----------------
//创建接收数据显示窗口
pContext->m_pCurrentFrame=this;
ret=m_wndSplitter.CreateView(
0,0,
RUNTIME_CLASS(C004View),
czPane,
pContext);
if(!ret)
{
TRACE("SplitCreateView Failed(1)...\n");
return ret;
}
// ------------- 2 ----------------
//创建发送数据显示窗口
pContext->m_pCurrentFrame=this;
ret=m_wndSplitter.CreateView(
0,1,
RUNTIME_CLASS(C006View),
czPane,
pContext);
if(!ret)
{
TRACE("Split CreateView Failed(2)...\n");
return ret;
}
// ------------- 3 ----------------
//创建调试数据显示窗口
pContext->m_pCurrentFrame=this;
ret=m_wndSplitter.CreateView(
1,0,
RUNTIME_CLASS(C001View),
czPane,
pContext);
// ------------- 4 ----------------
pContext->m_pCurrentFrame=this;
ret=m_wndSplitter.CreateView(
1,1,
RUNTIME_CLASS(C002View),
czPane,
pContext);
////
//// ------------- 5 ----------------
//pContext->m_pCurrentFrame=this;
//ret=m_wndSplitter.CreateView(
// 2,0,
// RUNTIME_CLASS(C005View),
// czPane,
// pContext);
////
//// ------------- 6 ----------------
//pContext->m_pCurrentFrame=this;
//ret=m_wndSplitter.CreateView(
// 2,1,
// RUNTIME_CLASS(C006View),
// //RUNTIME_CLASS(C007View),
// czPane,
// pContext);
//if(!ret)
//{
// TRACE("Split CreateView Failed(3)...\n");
// return ret;
//}
//初始化窗口
m_wndSplitter.RecalcLayout();
m_wndSplitter.SetActivePane(1,0);
return ret;
}
<file_sep>// C004View.cpp : 实现文件
//
#include "stdafx.h"
#include "ImageProcTool.h"
#include "004View.h"
// C004View
IMPLEMENT_DYNCREATE(C004View, CFormView)
C004View::C004View()
: CFormView(C004View::IDD)
{
}
C004View::~C004View()
{
}
void C004View::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(C004View, CFormView)
END_MESSAGE_MAP()
// C004View 诊断
#ifdef _DEBUG
void C004View::AssertValid() const
{
CFormView::AssertValid();
}
#ifndef _WIN32_WCE
void C004View::Dump(CDumpContext& dc) const
{
CFormView::Dump(dc);
}
#endif
#endif //_DEBUG
// C004View 消息处理程序
<file_sep>#include "StdAfx.h"
#include "StudyGA.h"
StudyGA::StudyGA(void)
{
}
StudyGA::~StudyGA(void)
{
}
/*
说明:
(1)这里是求函数的最小值,函数值越小的个体适应度越大,所以这里采用倒数变换,
即把适应度函数F(x)定义为1/f(x)(f(x)为目标函数值),这样就保证了适应度函数F(x)越大,个体是越优的。
(当然我们已经保证了f(x)始终是一个正数)
(2) 选择操作采用的是经典的轮盘赌法,即每个个体被选为父代的概率与其适应度是成正比的,适应度越高,
被选中的概率越大,设pi为第i个个体被选中的概率,则
pi=Fi/(∑Fi),Fi为第i个个体的适应度函数。
(3)交叉操作:由于个体采用实数编码,所以交叉操作也采用实数交叉法,
第k个染色体ak和第l个染色体al在第j位的交叉操作方法为:
akj=aij(1-b)+aijb; alj=alj(1-b)+akjb,其中b是[0,1]之间的随机数。k,l,j都是随机产生的,
即随机选取两个父代,再随机选取一个基因,按照公式完成交叉操作。
(4)变异操作:第i个个体的第j个基因进行变异的操作方法是:
r>=0.5时,aij=aij+(amax-aij)*f(g)
r<0.5时,aij=aij+(amin-aij)*f(g)
其中amax是基因aij的上界,amin是aij的下界,f(g)=r2*(1-g/Gmax)2,r2是一个[0,1]之间的随机数,
g是当前迭代次数,Gmax是进化最大次数,r是[0,1]之间的随机数。
可以看出,当r>=0.5时,aij是在aij到amax之间变化的;r<0.5时,aij是在amin到aij之间变化的。
这样的函数其实可以构造不止一种,来完成变异的操作。只要符合随机性,以及保证基因在有效的变化范围内即可。
我在ubuntu16.04下,使用gcc编译器运行得到的结果如下:
从结果上来看,种群数目为50,进化代数为500时,得到的最优解为2.014102已经非常接近实际的最优解2了,
当然,如果把种群数目再变大比如500,进化代数变多比如1000代,那么得到的结果将会更精确,种群数目为500,
进化代数为1000时的最优解如下:
可以看出,增加种群数目以及增加进化代数之后,最优值从2.014102变为2.000189,比原来的精度提高了两位,
但是相应地,程序的运行时间也显著增加了(从0.08秒左右增加到2秒左右)。
所以在具体求解复杂问题的时候(比如有的时候会碰到函数参数有几十个之多),
我们就必须综合考虑最优解的精度以及运算复杂度(运算时间)这两个方面,权衡之后,取合适的参数进行问题的求解。
当然,这里只是以求解多元非线性函数的极值问题为例来说明遗传算法的具体实现步骤,
遗传算法的实际运用非常广泛,不仅仅可以求解复杂函数极值,而且在运筹学等众多领域有着非常广泛的应用,
也经常会和其他的智能算法或者优化算法结合来求解问题。这个后面我还会再较为详细地论述。
*/
double chrom[sizepop][lenchrom]; // 种群数组
double fitness[sizepop]; //种群每个个体的适应度
double fitness_prob[sizepop]; // 每个个体被选中的概率(使用轮盘赌法确定)
double bestfitness[maxgen]; // 每一代最优值
double gbest_pos[lenchrom]; // 取最优值的位置
double average_best[maxgen+1]; // 每一代平均最优值
double gbest; // 所有进化中的最优值
int gbest_index; // 取得最优值的迭代次数序号
// 目标函数
double fit_func(double * arr)
{
double x1 = *arr;
double x2 = *(arr+1);
double x3 = *(arr+2);
double x4 = *(arr+3);
double x5 = *(arr+4);
double func_result = -5*sin(x1)*sin(x2)*sin(x3)*sin(x4)*sin(x5) - sin(5*x1)*sin(5*x2)*sin(5*x3)*sin(5*x4)*sin(5*x5) + 8;
return func_result;
}
// 求和函数
double sum(double * fitness)
{
double sum_fit = 0;
for(int i=0;i<sizepop;i++)
sum_fit += *(fitness+i);
return sum_fit;
}
double * min_local(double * fitness)
{
double min_fit = *fitness;
double min_index = 0;
static double arr[2];
for(int i=1;i<sizepop;i++)
{
if(*(fitness+i) < min_fit)
{
min_fit = *(fitness+i);
min_index = i;
}
}
arr[0] = min_index;
arr[1] = min_fit;
return arr;
}
// 种群初始化
void init_chrom()
{
for(int i=0;i<sizepop;i++)
{
for(int j=0;j<lenchrom;j++)
{
chrom[i][j] = bound_up*(((double)rand())/RAND_MAX);
}
fitness[i] = fit_func(chrom[i]); // 初始化适应度
}
}
// 选择操作
void Select(double chrom[sizepop][lenchrom])
{
//cout<< "\t Select(double chrom[sizepop][lenchrom]): "<< endl;
int index[sizepop];
for(int i=0;i<sizepop;i++)
{
double * arr = chrom[i];
fitness[i] = 1/(fit_func(arr)); // 本例是求最小值,适应度为目标函数的倒数,即函数值越小,适应度越大
}
double sum_fitness = 0;
for(int i=0;i<sizepop;i++)
{
sum_fitness += fitness[i]; // 适应度求和
}
for(int i=0;i<sizepop;i++)
{
fitness_prob[i] = fitness[i]/sum_fitness;
}
for(int i=0;i<sizepop;i++)
{
fitness[i] = 1/fitness[i]; // 恢复函数值
}
for(int i=0;i<sizepop;i++) // sizepop 次轮盘赌
{
double pick = ((double)rand())/RAND_MAX;
int idExit = 0 ;
while(pick < 0.0001)
{
pick = ((double)rand())/RAND_MAX;
idExit ++ ;
if( idExit>numsExit )
{
cout<< "force break. "<< endl ;
break;
}
}
for(int j=0;j<sizepop;j++)
{
pick = pick - fitness_prob[j];
if(pick<=0)
{
index[i] = j;
break;
}
}
}
for(int i=0;i<sizepop;i++)
{
for(int j=0;j<lenchrom;j++)
{
chrom[i][j] = chrom[index[i]][j];
}
fitness[i] = fitness[index[i]];
}
}
// 交叉操作
void Cross(double chrom[sizepop][lenchrom])
{
for(int i=0;i<sizepop;i++)
{
//cout<< "\t Cross(double chrom[sizepop][lenchrom]): i = "<< i << endl;
// 随机选择两个染色体进行交叉
double pick1 = ((double)rand())/RAND_MAX;
double pick2 = ((double)rand())/RAND_MAX;
int choice1 = (int)(pick1*sizepop);// 第一个随机选取的染色体序号
int choice2 = (int)(pick2*sizepop);// 第二个染色体序号
int idExit = 0 ;
while(choice1 > sizepop-1)
{
pick1 = ((double)rand())/RAND_MAX;
choice1 = (int)(pick1*sizepop); //防止选取位置过界
idExit ++ ;
if( idExit>numsExit )
{
cout<< "force break. "<< endl ;
break;
}
}
idExit = 0 ;
while(choice2 > sizepop-1)
{
pick2 = ((double)rand())/RAND_MAX;
choice2 = (int)(pick2*sizepop);
idExit ++ ;
if( idExit>numsExit )
{
cout<< "force break. "<< endl ;
break;
}
}
double pick = ((double)rand())/RAND_MAX;// 用于判断是否进行交叉操作
if(pick>pcross)
{
continue;
}
int flag = 0; // 判断交叉是否有效的标记
while(flag == 0)
{
double pick = ((double)rand())/RAND_MAX;
int pos = (int)(pick*lenchrom);
int idExit = 0 ;
while(pos > lenchrom-1)
{
double pick = ((double)rand())/RAND_MAX;
int pos = (int)(pick*lenchrom); // 处理越界
idExit ++ ;
if( idExit>numsExit )
{
cout<< "force break. "<< endl ;
break;
}
}
// 交叉开始
double r = ((double)rand())/RAND_MAX;
double v1 = chrom[choice1][pos];
double v2 = chrom[choice2][pos];
chrom[choice1][pos] = r*v2 + (1-r)*v1;
chrom[choice2][pos] = r*v1 + (1-r)*v2; // 交叉结束
if(chrom[choice1][pos] >=bound_down && chrom[choice1][pos]<=bound_up && chrom[choice2][pos] >=bound_down && chrom[choice2][pos]<=bound_up)
flag = 1; // 交叉有效,退出交叉,否则继续下一次交叉
}
}
}
// 变异操作
void Mutation(double chrom[sizepop][lenchrom])
{
int idExit ;
for(int i=0;i<sizepop;i++)
{
//cout<< "\t Mutation(double chrom[sizepop][lenchrom]): i = "<< i << endl;
double pick = ((double)rand())/RAND_MAX; // 随机选择一个染色体进行变异
int choice = (int)(pick*sizepop);
idExit = 0;
while(choice > sizepop-1)
{
pick = ((double)rand())/RAND_MAX;
int choice = (int)(pick*sizepop); // 处理下标越界
idExit ++ ;
if( idExit>numsExit )
{
cout<< "force break. "<< endl ;
break;
}
}
pick = ((double)rand())/RAND_MAX; // 用于决定该轮是否进行变异
if(pick>pmutation)
{
continue;
}
pick = ((double)rand())/RAND_MAX;
int pos = (int)(pick*lenchrom);
while(pos > lenchrom-1)
{
pick = ((double)rand())/RAND_MAX;
pos = (int)(pick*lenchrom);
idExit ++ ;
if( idExit>numsExit )
{
cout<< "force break. "<< endl ;
break;
}
}
double v = chrom[i][pos];
double v1 = v - bound_up;
double v2 = bound_down - v;
double r = ((double)rand())/RAND_MAX;
double r1 = ((double)rand())/RAND_MAX;
if(r >= 0.5)
chrom[i][pos] = v - v1*r1*(1-((double)i)/maxgen)*(1-((double)i)/maxgen);
else
chrom[i][pos] = v + v2*r1*(1-((double)i)/maxgen)*(1-((double)i)/maxgen);
// 注意这里写法是不会越界的,所以只用一次变异就可以了
}
}
// 主函数
int mainGA(void )
{
time_t start, finish;
start = clock(); // 程序开始计时
srand( ( unsigned ) time(NULL) ); // 初始化随机数种子
init_chrom(); // 初始化种群
double * best_fit_index = min_local(fitness);
int best_index =(int)(*best_fit_index);
gbest = *(best_fit_index+1); // 最优值
gbest_index = 0;
average_best[0] = sum(fitness)/sizepop; //初始平均最优值
for(int i=0;i<lenchrom;i++)
{
gbest_pos[i] = chrom[best_index][i];
}
// 进化开始
for(int i=0;i<maxgen;i++)
{
try
{
Select(chrom); // 选择
Cross(chrom); //交叉
Mutation(chrom); //变异
for(int j=0;j<sizepop;j++)
{
fitness[j] = fit_func(chrom[j]);
}
double sum_fit = sum(fitness);
average_best[i+1] = sum_fit/sizepop; // 平均最优值
double * arr = min_local(fitness);
double new_best = *(arr+1);
int new_best_index = (int)(*arr); // 新最优值序号
if(new_best < gbest)
{
gbest = new_best;
for(int j=0;j<lenchrom;j++)
{
gbest_pos[j] = chrom[new_best_index][j];
}
gbest_index = i+1;
}
cout<< "gen = "<< i ;
cout<< " , ( new_best, gbest ) = "<< new_best<< " , "<< gbest<< endl;
}
catch (CMemoryException* e)
{
cout<< " some CMemoryException occur. "<< endl ;
continue;
}
catch (CFileException* e)
{
cout<< " some CFileException occur. "<< endl ;
continue;
}
catch (CException* e)
{
cout<< " some CException occur. "<< endl ;
continue;
}
}
finish = clock(); // 程序计算结束
double duration = ((double)(finish-start))/CLOCKS_PER_SEC;
printf("程序计算耗时:%lf秒\n.",duration);
printf("遗传算法进化了%d次,最优值为:%lf,最优值在第%d代取得,此代的平均最优值为%lf.\n",
maxgen,gbest,gbest_index,average_best[gbest_index]);
printf("取得最优值的地方为(%lf,%lf,%lf,%lf,%lf).\n",
gbest_pos[0],gbest_pos[1],gbest_pos[2],gbest_pos[3],gbest_pos[4]);
cout<< endl;
cv::Mat imgShow= cv::Mat( 200,200, CV_8UC3,Scalar(0,0,0 ));
imshow( "imgShow", imgShow );
waitKey(0);
return 0;
}
<file_sep>#pragma once
//代码引用出处
// https://www.cnblogs.com/lyrichu/p/6152897.html#undefined
/*
* 遗传算法求解函数的最优值问题
* 参考自《MATLAB智能算法30个案例分析》
* 本例的寻优函数为:f = -5*sin(x1)*sin(x2)*sin(x3)*sin(x4)*sin(x5) - sin(5*x1)*sin(5*x2)*sin(5*x3)*sin(5*x4)*sin(5*x5) + 8
* 其中x1,x2,x3,x4,x5是0~0.9*PI之间的实数。该函数的最小值为2,当x1,x2,x3,x4,x5都取PI/2时得到。
* update in 16/12/3
* author:Lyrichu
* email:<EMAIL>
*/
#include<iostream>
using namespace std;
#include<opencv2/opencv.hpp>
using namespace cv;
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define PI 3.1415926 //圆周率
#define sizepop 50 // 种群数目
#define maxgen 500 // 进化代数
#define pcross 0.6 // 交叉概率
#define pmutation 0.1 // 变异概率
#define lenchrom 5 // 染色体长度
#define bound_down 0 // 变量下界,这里因为都相同,所以就用单个值去代替了,如果每个变量上下界不同,也许需要用数组定义
#define bound_up (0.9*3.1415926) // 上界
const int numsExit = 400; // 值更新循环次数上限
class StudyGA
{
public:
StudyGA(void);
~StudyGA(void);
};
int mainGA(void);
double * min_local( double * fitness);
<file_sep>
// ChildFrm.h : CChildFrame 类的接口
//
#pragma once
#include "001view.h"
#include "002view.h"
#include "003view.h"
#include "006view.h"
#include "005view.h"
#include "007view.h"
#include "004View.h"
//#include "ImageProcTool.h"
class CChildFrame : public CMDIChildWndEx
{
DECLARE_DYNCREATE(CChildFrame)
public:
CChildFrame();
// 特性
protected:
CSplitterWndEx m_wndSplitter;
public:
// 操作
public:
// 重写
public:
virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext);
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
// 实现
public:
virtual ~CChildFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// 生成的消息映射函数
protected:
DECLARE_MESSAGE_MAP()
//public:
// CSplitterWnd m_wndSplitter;
//
};
<file_sep>
// ImageProcToolView.cpp : CImageProcToolView 类的实现
//
#include "stdafx.h"
// SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的
// ATL 项目中进行定义,并允许与该项目共享文档代码。
#ifndef SHARED_HANDLERS
#include "ImageProcTool.h"
#endif
#include "ImageProcToolDoc.h"
#include "ImageProcToolView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CImageProcToolView
IMPLEMENT_DYNCREATE(CImageProcToolView, CFormView)
BEGIN_MESSAGE_MAP(CImageProcToolView, CFormView)
ON_WM_CONTEXTMENU()
ON_WM_RBUTTONUP()
END_MESSAGE_MAP()
// CImageProcToolView 构造/析构
CImageProcToolView::CImageProcToolView()
: CFormView(CImageProcToolView::IDD)
{
// TODO: 在此处添加构造代码
}
CImageProcToolView::~CImageProcToolView()
{
}
void CImageProcToolView::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
}
BOOL CImageProcToolView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return CFormView::PreCreateWindow(cs);
}
void CImageProcToolView::OnInitialUpdate()
{
CFormView::OnInitialUpdate();
ResizeParentToFit();
}
void CImageProcToolView::OnRButtonUp(UINT /* nFlags */, CPoint point)
{
ClientToScreen(&point);
OnContextMenu(this, point);
}
void CImageProcToolView::OnContextMenu(CWnd* /* pWnd */, CPoint point)
{
#ifndef SHARED_HANDLERS
theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, TRUE);
#endif
}
// CImageProcToolView 诊断
#ifdef _DEBUG
void CImageProcToolView::AssertValid() const
{
CFormView::AssertValid();
}
void CImageProcToolView::Dump(CDumpContext& dc) const
{
CFormView::Dump(dc);
}
CImageProcToolDoc* CImageProcToolView::GetDocument() const // 非调试版本是内联的
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CImageProcToolDoc)));
return (CImageProcToolDoc*)m_pDocument;
}
#endif //_DEBUG
// CImageProcToolView 消息处理程序
<file_sep>// 001View.cpp : implementation of the C001View class
//
#include "stdafx.h"
#include "ImageProcTool.h"
#include "ImageProcToolDoc.h"
#include "001View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// C001View
IMPLEMENT_DYNCREATE(C001View, CEditView)
BEGIN_MESSAGE_MAP(C001View, CEditView)
//{{AFX_MSG_MAP(C001View)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CEditView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CEditView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CEditView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// C001View construction/destruction
C001View::C001View()
{
// TODO: add construction code here
}
C001View::~C001View()
{
}
BOOL C001View::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CEditView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// C001View drawing
void C001View::OnDraw(CDC* pDC)
{
CImageProcToolDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
}
/////////////////////////////////////////////////////////////////////////////
// C001View printing
BOOL C001View::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void C001View::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void C001View::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// C001View diagnostics
#ifdef _DEBUG
void C001View::AssertValid() const
{
CEditView::AssertValid();
}
void C001View::Dump(CDumpContext& dc) const
{
CEditView::Dump(dc);
}
CImageProcToolDoc* C001View::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CImageProcToolDoc)));
return (CImageProcToolDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// C001View message handlers
<file_sep>// 002View.cpp : implementation file
//
#include "stdafx.h"
#include "ImageProcTool.h"
#include "002View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// C002View
IMPLEMENT_DYNCREATE(C002View, CListView)
C002View::C002View()
{
}
C002View::~C002View()
{
}
BEGIN_MESSAGE_MAP(C002View, CListView)
//{{AFX_MSG_MAP(C002View)
ON_WM_CREATE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// C002View drawing
void C002View::OnDraw(CDC* pDC)
{
CDocument* pDoc = GetDocument();
// TODO: add draw code here
}
/////////////////////////////////////////////////////////////////////////////
// C002View diagnostics
#ifdef _DEBUG
void C002View::AssertValid() const
{
CListView::AssertValid();
}
void C002View::Dump(CDumpContext& dc) const
{
CListView::Dump(dc);
}
CImageProcToolDoc* C002View::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CImageProcToolDoc)));
return (CImageProcToolDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// C002View message handlers
BOOL C002View::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Add your specialized code here and/or call the base class
cs.style |= LVS_REPORT |
LVS_SHOWSELALWAYS |
LVS_SINGLESEL;
return CListView::PreCreateWindow(cs);
}
void C002View::OnInitialUpdate()
{
CListView::OnInitialUpdate();
CListCtrl* pctlList=&GetListCtrl();
LVCOLUMN lvc={0};
char buf[128]={0};
lvc.pszText= LPWSTR ( (char*)buf );
lvc.mask=LVCF_FMT|LVCF_TEXT|LVCF_SUBITEM|LVCF_WIDTH;
lvc.fmt=LVCFMT_LEFT;
lvc.iSubItem=0;
lvc.cx=50;
lstrcpyn( LPWSTR (buf), CString("left") ,sizeof(buf));
pctlList->InsertColumn(lvc.iSubItem,&lvc);
lvc.fmt=LVCFMT_CENTER;
lvc.iSubItem++;
lvc.cx=100;
lstrcpyn( LPWSTR (buf), CString("center"),sizeof(buf));
pctlList->InsertColumn(lvc.iSubItem,&lvc);
lvc.fmt=LVCFMT_RIGHT;
lvc.iSubItem++;
lvc.cx=150;
lstrcpyn( LPWSTR (buf), CString("right"),sizeof(buf));
pctlList->InsertColumn(lvc.iSubItem,&lvc);
LVITEM lvi={0};
lvi.mask=LVIF_TEXT;
lvi.pszText= LPWSTR( (char*)buf );
lvi.iItem=0;
lvi.iSubItem=0;
lstrcpyn( LPWSTR (buf), CString("left-1"),sizeof(buf));
pctlList->InsertItem(&lvi);
lvi.iSubItem++;
lstrcpyn( LPWSTR (buf) ,CString("center-1" ),sizeof(buf));
pctlList->SetItem(&lvi);
lvi.iSubItem++;
lstrcpyn( LPWSTR (buf) ,CString("right-1"),sizeof(buf));
pctlList->SetItem(&lvi);
lvi.iItem++;
lvi.iSubItem=0;
lstrcpyn( LPWSTR (buf) , CString("left-2" ),sizeof(buf));
pctlList->InsertItem(&lvi);
lvi.iSubItem++;
lstrcpyn( LPWSTR (buf) ,CString("center-2"),sizeof(buf));
pctlList->SetItem(&lvi);
lvi.iSubItem++;
lstrcpyn( LPWSTR (buf), CString("right-2"),sizeof(buf));
pctlList->SetItem(&lvi);
}
int C002View::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CListView::OnCreate(lpCreateStruct) == -1)
return -1;
DWORD dwStyle = SendMessage(LVM_GETEXTENDEDLISTVIEWSTYLE);
dwStyle |= LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_HEADERDRAGDROP;
SendMessage(LVM_SETEXTENDEDLISTVIEWSTYLE, 0, (LPARAM)dwStyle);
return 0;
}
<file_sep>// 005View.cpp : implementation file
//
#include "stdafx.h"
#include "ImageProcTool.h"
#include "005View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// C005View
IMPLEMENT_DYNCREATE(C005View, CEditView)
C005View::C005View()
{
}
C005View::~C005View()
{
}
BEGIN_MESSAGE_MAP(C005View, CEditView)
//{{AFX_MSG_MAP(C005View)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// C005View drawing
void C005View::OnDraw(CDC* pDC)
{
CDocument* pDoc = GetDocument();
// TODO: add draw code here
}
/////////////////////////////////////////////////////////////////////////////
// C005View diagnostics
#ifdef _DEBUG
void C005View::AssertValid() const
{
CEditView::AssertValid();
}
void C005View::Dump(CDumpContext& dc) const
{
CEditView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// C005View message handlers
<file_sep>// 007View.cpp : implementation file
//
#include "stdafx.h"
#include "ImageProcTool.h"
#include "007View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// C007View
IMPLEMENT_DYNCREATE(C007View, CListView)
C007View::C007View()
{
}
C007View::~C007View()
{
}
BEGIN_MESSAGE_MAP(C007View, CListView)
//{{AFX_MSG_MAP(C007View)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// C007View drawing
void C007View::OnDraw(CDC* pDC)
{
CDocument* pDoc = GetDocument();
// TODO: add draw code here
}
/////////////////////////////////////////////////////////////////////////////
// C007View diagnostics
#ifdef _DEBUG
void C007View::AssertValid() const
{
CListView::AssertValid();
}
void C007View::Dump(CDumpContext& dc) const
{
CListView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// C007View message handlers
<file_sep>#pragma once
#include "opencv2/opencv.hpp"
using namespace cv;
// ImageProcPlatDlg 对话框
class ImageProcPlatDlg : public CDialogEx
{
DECLARE_DYNAMIC(ImageProcPlatDlg)
public:
ImageProcPlatDlg(CWnd* pParent = NULL); // 标准构造函数
virtual ~ImageProcPlatDlg();
// 对话框数据
enum { IDD = IDD_DIALOG1_ImageProcPlat };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
// 数据到bmp的长度转换
int cal_WIDTHBYTES( int bits ,int channels )
{
if( 3 == channels )
{
//下面的这个式子是对的,但应该理解清楚.
// 这个适用于bgr图像的。
return ((( bits)+ 31 )/32*4 ) ;
}
else if( 1 == channels )
{
// 这里应该是多少呢?好好算算吧.下面的式子是不对的。
return ((( bits)+ 7 )/8 ) ;
}
}
void procImageShowAccordingToWH( int w,int h, cv::Mat & Image )
{
double rateW = double(w)/Image.cols;
double rateH = double(h)/Image.rows;
double rateF = rateW>rateH? rateH:rateW;
cv::Mat imgSc;
resize( Image,imgSc, Size( Image.cols* rateF, Image.rows*rateF ));
Image = imgSc;
}
void DrawIplImage2MFC( Mat src , unsigned int id)
{
if( 3> src.channels() )
{
//appendTextToTextEdit( IDC_EDIT1, CString("<info:图像显示:>单通道图像显示部分还没完成。") );
//appendTextToTextEdit( IDC_EDIT1, CString("<info:图像显示:>所以对于非彩色图像,暂时转换为三通道图像来显示... ... ") );
// 改为三通道图像
Mat srcBGR;
cvtColor( src, srcBGR, CV_GRAY2BGR );
srcBGR.copyTo( src );
}
// src -- iamgecontrl-- bmp
BYTE *g_pBits;
HDC g_hMemDC;
HBITMAP g_hBmp, g_hOldBmp;
CDC *pDC;
CStatic *pic;
int width, height;
CRect rect;
// 控件的信息
pDC = GetDlgItem(id)->GetDC();
pic = (CStatic*)GetDlgItem(id);
pic->GetClientRect(&rect);
width = rect.Width();
height = rect.Height();
if( 1 )
{
if( 0 )
{
Mat srcR;
resize( src, srcR, Size( width, height ) );
srcR.copyTo( src );
}
procImageShowAccordingToWH( width,height, src );
}
if( src.cols %4!= 0 || src.rows %4 != 0 )
{
Mat tmp;
resize(src, tmp , Size( ((int)src.cols/4+1 )*4, ((int)src.rows/4+1 )*4 ) );
tmp.copyTo( src );
}
// bmp图片的信息
IplImage *img = & IplImage( src );
g_hMemDC =::CreateCompatibleDC(pDC->m_hDC);
BYTE bmibuf[sizeof(BITMAPINFO)+256 * sizeof(RGBQUAD)];
memset(bmibuf, 0, sizeof(bmibuf));
BITMAPINFO *pbmi = (BITMAPINFO*)bmibuf;
pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pbmi->bmiHeader.biWidth = img->width;
pbmi->bmiHeader.biHeight = img->height;
pbmi->bmiHeader.biPlanes = 1;
pbmi->bmiHeader.biBitCount = 24;
pbmi->bmiHeader.biCompression= BI_RGB; //BI_RLE8
g_hBmp =::CreateDIBSection(g_hMemDC, pbmi, DIB_RGB_COLORS, (void**)&g_pBits, 0, 0);
g_hOldBmp = (HBITMAP)::SelectObject(g_hMemDC, g_hBmp);
BitBlt(g_hMemDC, 0, 0, width, height, pDC->m_hDC, 0, 0, SRCCOPY);
if( 1 )
{
//int l_width = WIDTHBYTES( img->width* pbmi->bmiHeader.biBitCount );
int l_width = cal_WIDTHBYTES( img->width* pbmi->bmiHeader.biBitCount , src.channels() );
for (int row = 0; row < img->height;row++)
memcpy( &g_pBits[row*l_width], &img->imageData[ (img->height - row - 1)*l_width], l_width );
TransparentBlt(pDC->m_hDC, 0, 0, width, height, g_hMemDC, 0, 0,
img->width, img->height, RGB(0, 0, 0));
SelectObject(g_hMemDC, g_hOldBmp);
}
//另一种显示方式
if( 1 )
{
//id = IDC_STATIC2;
CBitmap bm;
bm.Attach( g_hBmp );
CStatic *p = (CStatic* )(GetDlgItem( id ) );
p->ModifyStyle( 0xf,SS_BITMAP |SS_CENTERIMAGE | SS_REALSIZEIMAGE );
p->SetBitmap( bm );
}
//release
DeleteDC(g_hMemDC);
DeleteObject(pic);
DeleteObject(g_hBmp);
DeleteObject(g_hOldBmp);
}
// mfc画图
void DrawIplImage2MFC_loadBmp( Mat src , unsigned int id)
{
CStatic *p = (CStatic* )(GetDlgItem( id ) );
CRect rect;
p->GetClientRect(&rect);
int width = rect.Width();
int height = rect.Height();
//resize
Mat srcR;
resize( src, srcR, Size( width, height ) );
srcR.copyTo( src );
const char* nameWindow = "tmp.bmp" ;
imwrite( nameWindow, src );
HBITMAP bm = ( HBITMAP)::LoadImageW(NULL, _T( "tmp.bmp" ),IMAGE_BITMAP,
0, 0, LR_CREATEDIBSECTION| LR_DEFAULTSIZE |LR_LOADFROMFILE ) ;
//CBitMap bm; bm.LoadBitmapW( IDB_BITMAP1 ); ( 这个是另外的一种加载bmp的方式)
p->ModifyStyle( 0xf,SS_BITMAP |SS_CENTERIMAGE | SS_REALSIZEIMAGE );
p->SetBitmap( bm );
}
void fetchFileName(string & nameOut)
{
CString picPath; //定义图片路径变量
CFileDialog dlg(TRUE, NULL, NULL,
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_ALLOWMULTISELECT,
NULL, this); //选择文件对话框
//const char *nameOfDlg = "open image file";
//CFileDialog dlg(TRUE, NULL , nameOfDlg,
// OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_ALLOWMULTISELECT,
// NULL, this); //选择文件对话框
if (dlg.DoModal() == IDOK)
{
picPath = dlg.GetPathName(); //获取图片路径
}
else
{
return;
}
if (picPath.IsEmpty())
return;
////CString to string 使用这个方法记得字符集选用“使用多字节字符”,不然会报错
//string picpath = picPath.GetBuffer(0);
//从这里开始进行转化,这是一个宏定义
USES_CONVERSION;
//进行转换
char* keyChar = T2A(picPath.GetBuffer(0));
picPath.ReleaseBuffer();
//Mat testMat= imread( keyChar ) ;
//if( !testMat.data )
// keyChar = NULL;
string picpath(keyChar);
nameOut = picpath;
}
afx_msg void On32773_openImageFile();
afx_msg void On32774_toGray();
afx_msg void On32775_toColor();
afx_msg void On32776_saveImageToFile();
afx_msg void On32777_onExit();
string nameOfImageFile;
cv::Mat src_const ;
cv::Mat image_current;
string nameOfImageFileSave;
afx_msg void OnUpdate32774_OnUpdate__On32774_toGray(CCmdUI *pCmdUI);
};
<file_sep>================================================================================
MICROSOFT 基础类库: ImageProcTool 项目概述
===============================================================================
应用程序向导已为您创建了这个 ImageProcTool 应用程序。此应用程序不仅演示 Microsoft 基础类的基本使用方法,还可作为您编写应用程序的起点。
本文件概要介绍组成 ImageProcTool 应用程序的每个文件的内容。
ImageProcTool.vcxproj
这是使用应用程序向导生成的 VC++ 项目的主项目文件。
它包含生成该文件的 Visual C++ 的版本信息,以及有关使用应用程序向导选择的平台、配置和项目功能的信息。
ImageProcTool.vcxproj.filters
这是使用“应用程序向导”生成的 VC++ 项目筛选器文件。
它包含有关项目文件与筛选器之间的关联信息。在 IDE 中,通过这种关联,在特定节点下以分组形式显示具有相似扩展名的文件。例如,“.cpp”文件与“源文件”筛选器关联。
ImageProcTool.h
这是应用程序的主要头文件。它包括其他项目特定的头文件(包括 Resource.h),并声明 CImageProcToolApp 应用程序类。
ImageProcTool.cpp
这是包含应用程序类 CImageProcToolApp 的主要应用程序源文件。
ImageProcTool.rc
这是程序使用的所有 Microsoft Windows 资源的列表。它包括 RES 子目录中存储的图标、位图和光标。此文件可以直接在 Microsoft Visual C++ 中进行编辑。项目资源位于 2052 中。
res\ImageProcTool.ico
这是用作应用程序图标的图标文件。此图标包括在主要资源文件 ImageProcTool.rc 中。
res\ImageProcTool.rc2
此文件包含不在 Microsoft Visual C++ 中进行编辑的资源。您应该将不可由资源编辑器编辑的所有资源放在此文件中。
/////////////////////////////////////////////////////////////////////////////
对于主框架窗口:
项目包含标准 MFC 界面。
MainFrm.h, MainFrm.cpp
这些文件包含框架类 CMainFrame,该类派生自
CMDIFrameWnd 并控制所有 MDI 框架功能。
/////////////////////////////////////////////////////////////////////////////
对于子框架窗口:
ChildFrm.h,ChildFrm.cpp
这些文件定义并实现 CChildFrame 类,该类支持 MDI 应用程序中的子窗口。
/////////////////////////////////////////////////////////////////////////////
应用程序向导创建一个文档类型和一个视图:
ImageProcToolDoc.h,ImageProcToolDoc.cpp - 文档
这些文件包含 CImageProcToolDoc 类。编辑这些文件可以添加特殊文档数据并可实现文件保存和加载(通过 CImageProcToolDoc::Serialize)。
ImageProcToolView.h,ImageProcToolView.cpp - 文档的视图
这些文件包含 CImageProcToolView 类。
CImageProcToolView 对象用于查看 CImageProcToolDoc 对象。
res\ImageProcToolDoc.ico
这是图标文件,它用作 CImageProcToolDoc 类的 MDI 子窗口的图标。此图标包括在主要资源文件 ImageProcTool.rc 中。
/////////////////////////////////////////////////////////////////////////////
其他功能:
ActiveX 控件
应用程序包括对使用 ActiveX 控件的支持。
拆分窗口
应用程序向导已为应用程序文档添加了拆分窗口支持。
/////////////////////////////////////////////////////////////////////////////
其他标准文件:
StdAfx.h,StdAfx.cpp
这些文件用于生成名为 ImageProcTool.pch 的预编译头 (PCH) 文件和名为 StdAfx.obj 的预编译类型文件。
Resource.h
这是标准头文件,它定义新的资源 ID。
Microsoft Visual C++ 读取并更新此文件。
ImageProcTool.manifest
应用程序清单文件供 Windows XP 用来描述应用程序
对特定版本并行程序集的依赖性。加载程序使用此
信息从程序集缓存加载适当的程序集或
从应用程序加载私有信息。应用程序清单可能为了重新分发而作为
与应用程序可执行文件安装在相同文件夹中的外部 .manifest 文件包括,
也可能以资源的形式包括在该可执行文件中。
/////////////////////////////////////////////////////////////////////////////
其他注释:
应用程序向导使用“TODO:”指示应添加或自定义的源代码部分。
如果应用程序在共享的 DLL 中使用 MFC,则需要重新发布这些 MFC DLL;如果应用程序所用的语言与操作系统的当前区域设置不同,则还需要重新发布对应的本地化资源 MFC100XXX.DLL。有关这两个主题的更多信息,请参见 MSDN 文档中有关 Redistributing Visual C++ applications (重新发布 Visual C++ 应用程序)的章节。
/////////////////////////////////////////////////////////////////////////////
<file_sep>#if !defined(AFX_004VIEW_H__05FC321D_4A64_4C3D_B80B_224A6E01EEF4__INCLUDED_)
#define AFX_004VIEW_H__05FC321D_4A64_4C3D_B80B_224A6E01EEF4__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// 004View.h : header file
//
#include "ImageProcToolDoc.h"
/////////////////////////////////////////////////////////////////////////////
// C006View form view
#ifndef __AFXEXT_H__
#include <afxext.h>
#endif
class C006View : public CFormView
{
protected:
C006View(); // protected constructor used by dynamic creation
DECLARE_DYNCREATE(C006View)
// Form Data
public:
//{{AFX_DATA(C006View)
enum { IDD = IDD_DIALOG1_forView6 };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// Attributes
public:
CImageProcToolDoc* GetDocument();
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(C006View)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
virtual ~C006View();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
//{{AFX_MSG(C006View)
afx_msg void OnButton1();
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in 001View.cpp
inline ImageProcToolDoc* C006View::GetDocument()
{ return (ImageProcToolDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_004VIEW_H__05FC321D_4A64_4C3D_B80B_224A6E01EEF4__INCLUDED_)
<file_sep>// ImageProcPlatDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "ImageProcTool.h"
#include "ImageProcPlatDlg.h"
#include "afxdialogex.h"
// ImageProcPlatDlg 对话框
IMPLEMENT_DYNAMIC(ImageProcPlatDlg, CDialogEx)
ImageProcPlatDlg::ImageProcPlatDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(ImageProcPlatDlg::IDD, pParent)
{
}
ImageProcPlatDlg::~ImageProcPlatDlg()
{
}
void ImageProcPlatDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(ImageProcPlatDlg, CDialogEx)
ON_COMMAND(ID_32773, &ImageProcPlatDlg::On32773_openImageFile)
ON_COMMAND(ID_32774, &ImageProcPlatDlg::On32774_toGray)
ON_UPDATE_COMMAND_UI(ID_32774, &ImageProcPlatDlg::OnUpdate32774_OnUpdate__On32774_toGray)
ON_COMMAND(ID_32775, &ImageProcPlatDlg::On32775_toColor)
ON_COMMAND(ID_32776, &ImageProcPlatDlg::On32776_saveImageToFile)
ON_COMMAND(ID_32777, &ImageProcPlatDlg::On32777_onExit)
END_MESSAGE_MAP()
// ImageProcPlatDlg 消息处理程序
#include "string"
void ImageProcPlatDlg::On32773_openImageFile()
{
// TODO: 在此添加命令处理程序代码
fetchFileName( this->nameOfImageFile );
src_const = imread( nameOfImageFile );
if( src_const.data )
{
image_current = src_const.clone();
DrawIplImage2MFC( image_current, IDC_STATIC ) ;
}
}
void ImageProcPlatDlg::On32774_toGray()
{
// TODO: 在此添加命令处理程序代码
if(! (this-> image_current.data ) )
{
AfxMessageBox( _T( "没有当前图像数据."));
return ;
}
cv::Mat res;
if( image_current.channels() == 3 )
{
cvtColor( image_current, res, CV_BGR2GRAY );
}
else
{
res = image_current.clone();
}
this->image_current = res;
if( this->image_current.data )
{
DrawIplImage2MFC( this->image_current, IDC_STATIC ) ;
}
}
void ImageProcPlatDlg::On32775_toColor()
{
// TODO: 在此添加命令处理程序代码
cv::Mat res;
if( this->image_current.channels() == 1 )
{
cvtColor( this->image_current, res, CV_GRAY2BGR );
}
else
{
res = src_const.clone();
}
this->image_current = res;
if( this->image_current.data )
{
DrawIplImage2MFC( this->image_current, IDC_STATIC ) ;
}
}
void ImageProcPlatDlg::On32776_saveImageToFile()
{
// TODO: 在此添加命令处理程序代码
fetchFileName( this->nameOfImageFileSave );
if( image_current.data && !(this->nameOfImageFileSave.empty()) )
{
try
{
imwrite( ( this->nameOfImageFileSave+".record.jpg").c_str(), image_current );
}
catch (CMemoryException* e)
{
}
catch (CFileException* e)
{
}
catch (CException* e)
{
}
}
}
void ImageProcPlatDlg::On32777_onExit()
{
// TODO: 在此添加命令处理程序代码
CDialogEx::OnCancel();
}
//void CMainFrame::OnUpdate__On32774_toGray(CCmdUI* pCmdUI) //grays the menu item, as only one DialogWindow is allowed
//{
// // TODO: Code f黵 die Befehlsbehandlungsroutine zum Aktualisieren der Benutzeroberfl鋍he hier einf黦en
// if(CDialogWindow::IsCreated())
// pCmdUI->Enable(FALSE);
// else
// pCmdUI->Enable(TRUE);
//}
void ImageProcPlatDlg::OnUpdate32774_OnUpdate__On32774_toGray(CCmdUI *pCmdUI)
{
// TODO: 在此添加命令更新用户界面处理程序代码
if( !( this->image_current.data ) )
pCmdUI->Enable(FALSE);
else
pCmdUI->Enable(TRUE);
}
<file_sep>// 004View.cpp : implementation file
//
#include "stdafx.h"
#include "ImageProcTool.h"
#include "006View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// C006View
IMPLEMENT_DYNCREATE(C006View, CFormView)
C006View::C006View()
: CFormView(C006View::IDD)
{
//{{AFX_DATA_INIT(C006View)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
C006View::~C006View()
{
}
void C006View::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
//{{AFX_DATA_MAP(C006View)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(C006View, CFormView)
//{{AFX_MSG_MAP(C006View)
ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
ON_WM_LBUTTONUP()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// C006View diagnostics
#ifdef _DEBUG
void C006View::AssertValid() const
{
CFormView::AssertValid();
}
void C006View::Dump(CDumpContext& dc) const
{
CFormView::Dump(dc);
}
CImageProcToolDoc * C006View::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CImageProcToolDoc)));
return (CImageProcToolDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// C006View message handlers
void C006View::OnButton1()
{
// TODO: Add your control notification handler code here
}
void C006View::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CFormView::OnLButtonUp(nFlags, point);
}
<file_sep>// 003View.cpp : implementation file
//
#include "stdafx.h"
#include "ImageProcTool.h"
#include "003View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// C003View
IMPLEMENT_DYNCREATE(C003View, CTreeView)
C003View::C003View()
{
}
C003View::~C003View()
{
}
BEGIN_MESSAGE_MAP(C003View, CTreeView)
//{{AFX_MSG_MAP(C003View)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// C003View drawing
void C003View::OnDraw(CDC* pDC)
{
CDocument* pDoc = GetDocument();
// TODO: add draw code here
}
/////////////////////////////////////////////////////////////////////////////
// C003View diagnostics
#ifdef _DEBUG
void C003View::AssertValid() const
{
CTreeView::AssertValid();
}
void C003View::Dump(CDumpContext& dc) const
{
CTreeView::Dump(dc);
}
CImageProcToolDoc* C003View::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CImageProcToolDoc)));
return (CImageProcToolDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// C003View message handlers
BOOL C003View::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Add your specialized code here and/or call the base class
cs.style |= TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT;
return CTreeView::PreCreateWindow(cs);
}
void C003View::OnInitialUpdate()
{
CTreeView::OnInitialUpdate();
CTreeCtrl* pctlTree=&GetTreeCtrl();
HTREEITEM hRoot=NULL,
hCurr=NULL,
hChild=NULL;
#define XXX
#ifdef XXX
hRoot=pctlTree->InsertItem( CString("root1" ) );
hCurr=pctlTree->InsertItem( CString("111111" ) ,hRoot);
hChild=pctlTree->InsertItem(CString("111111-1" ) ,hCurr);
hChild=pctlTree->InsertItem(CString("111111-2" ) ,hCurr);
hChild=pctlTree->InsertItem(CString("111111-3" ) ,hCurr);
hCurr=pctlTree->InsertItem(CString("222222" ) ,hRoot);
hChild=pctlTree->InsertItem(CString("222222-1" ) ,hCurr);
hChild=pctlTree->InsertItem(CString("222222-2" ) ,hCurr);
hChild=pctlTree->InsertItem(CString("222222-3" ) ,hCurr);
#endif
}
|
fe07b05aef4e29f2bfc1c0e372037bad6cf3212e
|
[
"Text",
"C++"
] | 19 |
C++
|
leoking01/ImageProcTool
|
2c8c092c1d8aa38a9b275a895f3eec6bb688b248
|
923a6f9e3710ca70860a621e5e1c8073d5737fcf
|
refs/heads/master
|
<file_sep>require 'erb'
class Navbar
attr_accessor :parent
attr_writer :html_template_path
def initialize( name = nil, path = nil )
@name, @path = name, path
@children = []
end
def html_template_path
@html_template_path || parent.html_template_path
end
def add_child(child)
@children << child
child.parent = self
end
def html_output
template = ERB.new(File.read(html_template_path))
template.result(self.send :binding)
end
def xml_output
output = ""
output << unless @name
"<navbar>"
else
%{<item href="#{@path}" name="#{@name}"#{@children.empty? ? "/" : ""}>}
end
@children.each do |child|
output << child.xml_output
end
output << unless @name
"</navbar>"
else
@children.empty? ? "" : "</item>"
end
end
end
<file_sep>require 'test/unit'
require File.expand_path("../lib/navbar.rb", File.dirname(__FILE__))
class NavbarTest < Test::Unit::TestCase
def setup
@navbar = Navbar.new
user = Navbar.new("User","/user")
@navbar.add_child(user)
user_show = Navbar.new("Show","/user")
user.add_child(user_show)
user_edit = Navbar.new("Edit","/user/edit")
user.add_child(user_edit)
end
def test_html_output
assert_equal_ignore_space(<<EOS, @navbar.html_output
<ul>
<li><a href="/user">User</a>
<ul>
<li><a href="/user">Show</a></li>
<li><a href="/user/edit">Edit</a></li>
</ul>
</li>
</ul>
EOS
)
end
def test_xml_output
assert_equal_ignore_space(<<EOS, @navbar.xml_output
<navbar>
<item href="/user" name="User">
<item href="/user" name="Show"/>
<item href="/user/edit" name="Edit"/>
</item>
</navbar>
EOS
)
end
def assert_equal_ignore_space(expected, current)
assert_equal(expected.gsub(/\s/, ""), current.gsub(/\s/, ""))
end
end
|
bb70faf62830fc04f3818196c567cafbc1104d6e
|
[
"Ruby"
] | 2 |
Ruby
|
autumncollection/MyMenu
|
43e9c7ef4cd00f79c9be2cc7f6ef400db4f39194
|
d1b8431cc0d2ce8048c37e30769660976068b64e
|
refs/heads/master
|
<repo_name>HoanNguyen18795/AT_Mobile<file_sep>/app/src/main/java/com/testing/hoan/at_mobile/SessionManager.java
package com.testing.hoan.at_mobile;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
/**
* Created by Hoan on 9/11/2016.
*/
public class SessionManager {
private static String TAG=SessionManager.class.getSimpleName();
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE=0;
private static final String PREF_NAME="HNK";
private static final String KEY_IS_LOGGED_IN="isLoggedIN";
public SessionManager(Context context){
_context=context;
pref=_context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
editor=pref.edit();
}
public void setLogin(boolean isLoggedin){
editor.putBoolean(KEY_IS_LOGGED_IN,isLoggedin);
editor.commit();
Log.d(TAG,"user login modified");
}
public boolean isLoggedin(){
return pref.getBoolean(KEY_IS_LOGGED_IN,false);
}
}
<file_sep>/app/src/main/java/com/testing/hoan/at_mobile/RecyclerViewFrag.java
package com.testing.hoan.at_mobile;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Hoan on 11/21/2016.
*/
public class RecyclerViewFrag extends Fragment implements RecyclerView.OnScrollChangeListener{
private RecyclerViewListener mRecyclerViewListener;
private static final String TAG="RecyclerView Fragment";
private RequestQueue requestQueue;
private ArrayList<Events> eventsList;
private ProgressBar mProgressBar;
private RecyclerViewAdapter mRecyclerViewAdapter;
private RecyclerView.LayoutManager mLayout;
private RecyclerView mRecyclerView;
private int counter=1;
private int code=-1;
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//if(isLastItem(mRecyclerView)){
// getData();
//}
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState!=null){
getData();
}
getData();
Log.i(TAG,"recycler fragment onActivityCreated");
}
public interface RecyclerViewListener{
public void onItemSelected(int position,ArrayList<Events> events);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try{
Activity activity;
if(context instanceof Activity){
activity=(Activity) context;
mRecyclerViewListener=(RecyclerViewListener) activity;
}
}catch(ClassCastException e){
throw new ClassCastException(context.toString()
+ " must implement RecyclerViewListener");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get data first here
requestQueue= Volley.newRequestQueue(getActivity());
getData();
Log.i(TAG,"fragment oncreate");
}
// check that the recycler view has reached the last item
public boolean isLastItem(RecyclerView mrecyclerView){
if(mrecyclerView.getAdapter().getItemCount()!=0){
int lastVisibleItemPosition=((LinearLayoutManager)mrecyclerView.getLayoutManager()).findLastVisibleItemPosition();
if(lastVisibleItemPosition !=RecyclerView.NO_POSITION&& lastVisibleItemPosition==mrecyclerView.getAdapter().getItemCount()-1){
return true;
}
}
return false;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.recyclerview_fragment,container,false);
rootview.setTag("RecyclerViewFragment on create view inflated rootview");
mProgressBar =(ProgressBar) rootview.findViewById(R.id.progressbar);
mProgressBar.setIndeterminate(true);
mProgressBar.setVisibility(View.VISIBLE);
// initialize recyclerview
mRecyclerView=(RecyclerView) rootview.findViewById(R.id.recyclerview);
//setting up the recyclerview
mRecyclerView.setHasFixedSize(true);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
mRecyclerViewListener.onItemSelected( position,eventsList);
}
}));
// initialize a layout reference
mLayout=new LinearLayoutManager(getActivity());
// this layout will define how the recyclerview items are displayed
mRecyclerView.setLayoutManager(mLayout);
// initialize custom adapter
eventsList=new ArrayList<Events>();
mRecyclerViewAdapter=new RecyclerViewAdapter(eventsList,getActivity());
mRecyclerView.setAdapter(mRecyclerViewAdapter);
return rootview;
}
private JsonObjectRequest getDataFromServer() {
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, AppConfig.EVENTS_URL, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
parseData(response);
} catch (JSONException e) {
e.printStackTrace();
}
mProgressBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
error.printStackTrace();
mProgressBar.setVisibility(View.GONE);
Log.i(TAG,"Failed to get response");
}
});
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(50000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return jsObjRequest;
}
private void getData(){
// adding the request to the request que
//ApplicationControl.getInstance(this).addToRequestQueue(getDataFromServer(counter));
requestQueue.add(getDataFromServer());
//counter++;
}
private void parseData(JSONObject obj) throws JSONException {
JSONArray array=obj.getJSONArray("data");
Log.i(TAG,"data array size: "+array.length());
for(int i=0;i<array.length();i++){
Events event= new Events();
JSONObject json=null;
try{
json=array.getJSONObject(i);
event.setId(json.getString("_id"));
event.setBody(json.getString("body"));
try {
Log.i(TAG, json.getString("body"));
}catch(JSONException e){
e.printStackTrace();
}
// if(json.getString("image")!=null) {
// event.setImageUrl(json.getString("image"));
// }
// else{
event.setImageUrl("http://cucgach.mobi/wp-content/uploads/2016/04/icon-android-150x150.png");
// }
if(json.getString("title")!=null) {
event.setTitle(json.getString("title"));
}
else{
event.setTitle("Untitled");
}
}catch(Exception ex){
ex.printStackTrace();
Log.i(TAG,"could not parse json");
}
eventsList.add(event);
}
// notifying the adapter that data has been changed
mRecyclerViewAdapter.notifyDataSetChanged();
}
public ArrayList getEventList(){
return eventsList;
}
}
<file_sep>/app/src/main/java/com/testing/hoan/at_mobile/Events.java
package com.testing.hoan.at_mobile;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Hoan on 10/28/2016.
*/
public class Events implements Parcelable {
private String id;
private String title;
private String imageUrl;
private String body;
public Events(){
}
protected Events(Parcel in) {
id = in.readString();
title = in.readString();
imageUrl = in.readString();
body=in.readString();
}
public static final Creator<Events> CREATOR = new Creator<Events>() {
@Override
public Events createFromParcel(Parcel in) {
return new Events(in);
}
@Override
public Events[] newArray(int size) {
return new Events[size];
}
};
private boolean isValid(String params){
if(params==null){
return false;
}
return true;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public void setBody(String newBody){
body=newBody;
}
public String getBody(){
return body;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(title);
dest.writeString(imageUrl);
dest.writeString(body);
}
}
|
3e5d351197e4eb7264900e883832b7f1fd21dc46
|
[
"Java"
] | 3 |
Java
|
HoanNguyen18795/AT_Mobile
|
a4c2e60122bb138b8d2d532de02cf42d9188b6bc
|
689065d343ee42069cbc0edbeeb36c04edef89df
|
refs/heads/master
|
<repo_name>AndreasHorwath/http-api-demo-clients<file_sep>/Nevaris.Build.ClientApi/Models.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Nevaris.Build.ClientApi
{
/// <summary>
/// Basisklasse aller Model-Klassen.
/// </summary>
public class BaseObject
{
/// <summary>
/// Dictionary, in dem beim Deserialisieren Feld-Werte abgespeichert werden, für die es keine entspechende
/// Property im Model gibt. Ermöglicht ein versionierungstolerantes Serialisieren und Deserialisieren
/// von Model-Objekten ohne Informationsverlust.
/// </summary>
[JsonExtensionData]
public Dictionary<string, object> AdditionalProperties { get; set; }
}
public class VersionInfo : BaseObject
{
/// <summary>
/// Die NEVARIS Build-Programmversion.
/// </summary>
public string ProgramVersion { get; set; }
/// <summary>
/// Die Versionsnummer der HTTP API. Diese folgt den Regeln der sematischen Versionierung.
/// </summary>
public string ApiVersion { get; set; }
}
public enum AdressArt
{
Organisation,
Person
}
public enum GesperrtArt
{
Nein = 0,
Ja,
Bereich,
Hinweis
}
public class GeoCoordinate
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
public class NewAdresseInfo
{
public AdressArt AdressArt { get; set; }
}
public class Adresse
{
public string Code { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)]
public AdressArt AdressArt { get; set; }
public string Name { get; set; }
public string Vorname { get; set; }
public string Nachname { get; set; }
public string Kürzel { get; set; }
public string LandCode { get; set; }
public bool IstPostfachInVerwendung { get; set; }
public string Titel { get; set; }
public string UstId { get; set; }
public string Telefon { get; set; }
public string Fax { get; set; }
public string EMail { get; set; }
public string Name2 { get; set; }
public string Name3 { get; set; }
public string Name4 { get; set; }
public string Ort { get; set; }
public string Straße { get; set; }
public string Plz { get; set; }
public string Postfach { get; set; }
public string PostfachPlz { get; set; }
public string PostfachOrt { get; set; }
public string MobilFirma { get; set; }
public string MobilPrivat { get; set; }
public string Internet { get; set; }
public bool IstBauleistender { get; set; }
public string Skype { get; set; }
public string LoginName { get; set; }
public string Suchbegriff { get; set; }
public string Briefanschrift { get; set; }
public string SozialesNetzwerk1 { get; set; }
public string SozialesNetzwerk1Name { get; set; }
public string SozialesNetzwerk2 { get; set; }
public string SozialesNetzwerk2Name { get; set; }
public string Adresszusatz { get; set; }
public string BundeslandCode { get; set; }
public string LandkreisCode { get; set; }
public string AnredeCode { get; set; }
public string KonzernCode { get; set; }
public string ZentraleCode { get; set; }
public string SperrhinweisCode { get; set; }
public string SpracheCode { get; set; }
public string AdressQuelleCode { get; set; }
public string VerweisAufAdresseCode { get; set; }
public bool IstDebitorVorhanden { get; set; }
public bool IstKreditorVorhanden { get; set; }
public string Handelsregister { get; set; }
public string UnsereKundenNummerDort { get; set; }
public string SteuernummerGesellschaft { get; set; }
public string UrsprungsCode { get; set; }
public bool IstEigeneAdresse { get; set; }
public string TitelImAnschreiben { get; set; }
public DateTime? Geburtsdatum { get; set; }
public GesperrtArt GesperrtArt { get; set; }
public DateTime? GültigAb { get; set; }
public DateTime? GültigBis { get; set; }
public bool IstDuplikat { get; set; }
public int? VollständigkeitInProzent { get; set; }
public decimal? Saldo { get; set; }
public string ExternerCode { get; set; }
public string Auslandsvorwahl { get; set; }
public string DurchwahlFax { get; set; }
public string DurchwahlZentrale { get; set; }
public Guid? Guid { get; set; }
public string Hauptanschlussnummer { get; set; }
public bool? IsReadOnlyNumber { get; set; }
public string Ortskennzahl { get; set; }
public string OutlookEntryId { get; set; }
public int? Ähnlichkeit { get; set; }
public GeoCoordinate GeoPosition { get; set; }
public string Notiz { get; set; }
public string Beschreibung { get; set; }
public List<Adressat> Adressaten { get; set; }
public List<Bankverbindung> Bankverbindungen { get; set; }
public List<AdressBranche> Branchen { get; set; }
public List<AdressGewerk> Gewerke { get; set; }
}
public class Adressat
{
public string Code { get; set; }
public string AnredeCode { get; set; }
public string PrivatadresseCode { get; set; }
public string Titel { get; set; }
public string TitelImAnschreiben { get; set; }
public string Vorname { get; set; }
public string Nachname { get; set; }
public string Telefon { get; set; }
public string Fax { get; set; }
public string Mobil { get; set; }
public string EMail { get; set; }
public string EMailAbteilung { get; set; }
public string Url { get; set; }
public string Skype { get; set; }
public string AbteilungCode { get; set; }
public string FunktionCode { get; set; }
public bool IstInaktiv { get; set; }
public DateTime? Austrittsdatum { get; set; }
public string Raum { get; set; }
public string Info { get; set; }
public string Beschreibung { get; set; }
public string Notiz { get; set; }
public string SpracheCode { get; set; }
public string Briefanschrift { get; set; }
public string Durchwahl { get; set; }
public string DurchwahlFax { get; set; }
public Guid? Guid { get; internal set; }
}
public class Bankverbindung
{
public string Iban { get; set; }
public string Bic { get; set; }
public string Bankname { get; set; }
}
public class AdressBranche
{
public string BrancheCode { get; set; }
public string Bezeichnung { get; set; }
public string Beschreibung { get; set; }
}
public class AdressGewerk
{
public string GewerkCode { get; set; }
public string Bezeichnung { get; set; }
public string Beschreibung { get; set; }
}
/// <summary>
/// Ein Speicherort (Ordner oder Datenbank).
/// </summary>
public class Speicherort : BaseObject
{
public Guid Id { get; set; }
public string Bezeichnung { get; set; }
/// <summary>
/// Falls der Speicherort ein Ordner ist, enthält dieses Objekt die passenden Informationen.
/// </summary>
public OrdnerInfo OrdnerInfo { get; set; }
/// <summary>
/// Falls der Speicherort eine Datenbank ist, enthält dieses Objekt die passenden Informationen.
/// </summary>
public DatenbankInfo DatenbankInfo { get; set; }
/// <summary>
/// (Detailinfo) Liste von Projekten an diesem Speicherort.
/// </summary>
public List<ProjektInfo> ProjektInfos { get; set; }
}
public class OrdnerInfo : BaseObject
{
public string Pfad { get; set; }
public string Arbeitsgruppenserver { get; set; }
}
public class DatenbankInfo : BaseObject
{
public string Server { get; set; }
public string Datenbank { get; set; }
public string Benutzername { get; set; }
public string Passwort { get; set; }
public bool IntegratedSecurity { get; set; }
}
/// <summary>
/// Beschreibt ein Projekt. Im Gegensatz zu <see cref="Projekt"/> enthält dieser Typ nur ID,
/// Nummer und Bezeichnung des Projekts und sonst keine Projektinhalte.
/// </summary>
public class ProjektInfo : BaseObject
{
public string Id { get; set; }
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
}
/// <summary>
/// Ein Projekt.
/// </summary>
public class Projekt : BaseObject
{
public string Id { get; set; }
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
public DateTime? Baubeginn { get; set; }
public DateTime? Bauende { get; set; }
public string Ampel { get; set; }
public string Art { get; set; }
public string Auschreibungsart { get; set; }
public string Status { get; set; }
public string Sparte { get; set; }
public string Typ { get; set; }
/// <summary>
/// Liste von Leistungsverzeichnissen, die in diesem Projekt enthalten sind.
/// </summary>
public List<Leistungsverzeichnis> Leistungsverzeichnisse { get; set; }
}
public class NewProjektInfo : BaseObject
{
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
}
/// <summary>
/// Ein Betriebsmittelstamm (auch Betriebsmittelkatalog genannt).
/// </summary>
public class BetriebsmittelStamm : BaseObject
{
public Guid Id { get; set; }
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
public string Beschreibung { get; set; }
public BetriebsmittelStammArt? Art { get; set; }
public int? RechengenauigkeitMengen { get; set; } // = NachkommastellenAnsatz
public int? RechengenauigkeitBeträge { get; set; } // = NachkommastellenKostenPreise
public int? DarstellungsgenauigkeitMengen { get; set; } // = NachkommastellenAnsatzUI
public int? DarstellungsgenauigkeitBeträge { get; set; } // = NachkommastellenKostenPreiseUI
public Guid LohnRootGruppeId { get; set; }
public Guid MaterialRootGruppeId { get; set; }
public Guid GerätRootGruppeId { get; set; }
public Guid SonstigeKostenRootGruppeId { get; set; }
public Guid NachunternehmerRootGruppeId { get; set; }
public Guid BausteinRootGruppeId { get; set; }
/// <summary>
/// (Detailinfo) Enthält Kostenanteilbezeichnungen.
/// </summary>
public BetriebsmittelStammBezeichnungen Bezeichnungen { get; set; }
/// <summary>
/// (Detailinfo) Liste von Kostenkatalogen.
/// </summary>
public List<Kostenkatalog> Kostenkataloge { get; set; }
/// <summary>
/// (Detailinfo) Liste von Zuschlagskatalogen.
/// </summary>
public List<Zuschlagskatalog> Zuschlagskataloge { get; set; }
/// <summary>
/// (Detailinfo) Liste von Zuschlagsgruppen. Legt fest, welche Zuschläge zur Verfügung stehen.
/// </summary>
public List<Zuschlagsgruppe> Zuschlagsgruppen { get; set; }
/// <summary>
/// (Detailinfo) Liste von Zuschlagsarten (entspricht dem Reiter "Zuschläge" in Build).
/// Über dieses Feld wird bestimmt, wie viele Zuschlagsspalten in den Kosten- und Zuschlagskatalogen angeboten werden und wie diese heißen.
/// </summary>
public List<Zuschlagsart> Zuschlagsarten { get; set; }
/// <summary>
/// (Detailinfo) Liste von Gerätefaktoren.
/// </summary>
public List<Gerätefaktor> Gerätefaktoren { get; set; }
/// <summary>
/// (Detailinfo) Liste von globalen Variablen.
/// </summary>
public List<GlobaleVariable> GlobaleVariablen { get; set; }
/// <summary>
/// (Detailinfo) Liste von Warengruppen.
/// </summary>
public List<Warengruppe> Warengruppen { get; set; }
/// <summary>
/// (Detailinfo) Liste von DbBetriebsmittelGruppen.
/// </summary>
public List<DbBetriebsmittelGruppe> DbBetriebsmittelGruppen { get; set; }
/// <summary>
/// (Detailinfo) Die Einträge im Grid "Zuschlagsberechnung" (nur GAEB-Stämme).
/// </summary>
public List<ZuschlagsartGruppe> ZuschlagsartGruppen { get; set; }
}
public enum BetriebsmittelStammArt
{
FreieForm,
Aut,
Ger
}
/// <summary>
/// Enthält die Kostenanteilbezeichnungen.
/// </summary>
public class BetriebsmittelStammBezeichnungen : BaseObject
{
public string LohnKostenanteil1 { get; set; }
public string LohnKostenanteil2 { get; set; }
public string ListenpreisGeraetKostenanteil1 { get; set; }
public string ListenpreisGeraetKostenanteil2 { get; set; }
public string SonstigeKostenKostenanteil1 { get; set; }
public string SonstigeKostenKostenanteil2 { get; set; }
public string SonstigeKostenKostenanteil3 { get; set; }
public string SonstigeKostenKostenanteil4 { get; set; }
public string SonstigeKostenKostenanteil5 { get; set; }
public string SonstigeKostenKostenanteil6 { get; set; }
public string NachunternehmerKostenanteil1 { get; set; }
public string NachunternehmerKostenanteil2 { get; set; }
public string NachunternehmerKostenanteil3 { get; set; }
public string NachunternehmerKostenanteil4 { get; set; }
public string NachunternehmerKostenanteil5 { get; set; }
public string NachunternehmerKostenanteil6 { get; set; }
}
/// <summary>
/// Informationen zu einem neu zu erzeugenden Betriebsmittelstamm.
/// </summary>
public class NewBetriebsmittelStammInfo : BaseObject
{
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
public BetriebsmittelStammArt? Art { get; set; }
}
/// <summary>
/// Eine Kostenart. Kann auch eine Kostenartengruppe sein.
/// </summary>
public class Kostenart : BaseObject
{
/// <summary>
/// Die Bezeichung der Kostenart.
/// </summary>
public string Bezeichnung { get; set; }
/// <summary>
/// Die Nummer der Kostenart innerhalb der enthaltenden Gruppe (z.B. "2").
/// </summary>
public string NummerLokal { get; set; }
/// <summary>
/// Die vollständige Nummer (z.B. "3.1.2").
/// </summary>
public string Nummer { get; set; }
/// <summary>
/// Falls true, ist dies eine Kostenartenguppe.
/// </summary>
public bool IstGruppe { get; set; }
/// <summary>
/// Befüllt im Fall IstGruppe == true. Enthält die Child-Kostenarten.
/// </summary>
public List<Kostenart> Kostenarten { get; set; }
}
/// <summary>
/// Informationen zu einer neu zu erzeugenden Kostenart.
/// </summary>
public class NewKostenartInfo
{
public string Bezeichnung { get; set; }
public string Nummer { get; set; }
public bool IstGruppe { get; set; }
}
public enum GeräteArt
{
Vorhaltegerät,
Leistungsgerät,
Investitionsgerät,
Listenpreisgerät
}
public class Gerätefaktor : BaseObject
{
public string Nummer { get; set; }
public GeräteArt? Art { get; set; }
public string Bezeichnung { get; set; }
public decimal? AbminderungsfaktorAV { get; set; }
public decimal? AbminderungsfaktorRepLohn { get; set; }
public decimal? AbminderungsfaktorRepMaterial { get; set; }
public decimal? StundenProMonat { get; set; }
}
public class GlobaleVariable : BaseObject
{
public string Variable { get; set; }
public bool? IstKalkulationsVariable { get; set; }
public string Ansatz { get; set; }
}
public class Warengruppe : BaseObject
{
public int Nummer { get; set; }
public string Bezeichnung { get; set; }
}
public class NewKostenkatalogInfo : BaseObject
{
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
}
public class NewZuschlagskatalogInfo : BaseObject
{
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
}
public class NewZuschlagsartInfo : BaseObject
{
public int Index { get; set; }
public string Bezeichnung { get; set; }
public ZuschlagsTyp? Zuschlagstyp { get; set; }
}
public class DbBetriebsmittelGruppe
{
public string Bezeichnung { get; set; }
public BetriebsmittelArt? Art { get; set; }
}
public class ZuschlagsartGruppe : BaseObject
{
public ZuschlagsTyp? Art { get; set; }
public ZuschlagsBasis? Berechnung { get; set; }
public bool HatZwischensumme { get; set; }
}
public enum ZuschlagsBasis
{
AufHundert,
ImHundert,
}
/// <summary>
/// Beschreibt einen Zuschläg, der in einem Betriebsmittelstamm zur Verfügung steht. Der Wert des Zuschlags
/// wird per Zuschlagskatalog.ZuschlagsgruppenWerte festgelegt.
/// </summary>
public class Zuschlagsgruppe : BaseObject
{
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
public int? Stufe { get; set; }
}
/// <summary>
/// Der Wert einer Zuschlagsgruppe innerhalb eines Zuschlagskatalogs.
/// </summary>
public class ZuschlagsgruppenWert : BaseObject
{
/// <summary>
/// Verweist auf eine Zuschlagsgruppe.
/// </summary>
public string ZuschlagsgruppenNummer { get; set; }
public decimal? Wert { get; set; }
}
/// <summary>
/// Eine Zuschlagsart. Beschreibt eine Zuschlagsspalte in den Kosten- und Zuschlagskatalogen.
/// </summary>
public class Zuschlagsart : BaseObject
{
public int Index { get; set; }
public string Bezeichnung { get; set; }
public ZuschlagsTyp? Typ { get; set; }
}
public enum ZuschlagsTyp
{
Agk, Bgk, Gewinn, Wagnis
}
public class Kostenkatalog : BaseObject
{
public Guid Id { get; set; }
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
public string Beschreibung { get; set; }
public bool IstStandard { get; set; }
public Guid? ParentKostenkatalogId { get; set; }
}
public class Zuschlagskatalog : BaseObject
{
public Guid Id { get; set; }
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
public string Beschreibung { get; set; }
public bool IstStandard { get; set; }
public List<ZuschlagsgruppenWert> ZuschlagsgruppenWerte { get; set; }
}
public enum BetriebsmittelArt
{
Lohn,
Material,
Gerät,
SonstigeKosten,
Nachunternehmer,
Baustein,
LohnGruppe,
MaterialGruppe,
GerätGruppe,
SonstigeKostenGruppe,
NachunternehmerGruppe,
BausteinGruppe
}
/// <summary>
/// Informationen zu einem neu zu erzeugenden Betriebsmittel.
/// </summary>
public class NewBetriebsmittelInfo : BaseObject
{
/// <summary>
/// Die ID der Betriebsmittelgruppe, unter dem das neue Betriebsmittel angelegt wird.
/// Falls nicht befüllt, wird das neue Betriebsmittel unter der Root-Gruppe angelegt.
/// </summary>
public Guid? ParentGruppeId { get; set; }
/// <summary>
/// Die Art des zu erzeugenden Betriebsmittels. Kann eine Gruppe sein.
/// </summary>
public BetriebsmittelArt Art { get; set; }
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
}
/// <summary>
/// Ein Betriebsmittel (kann auch eine Betriebsmittelgruppe sein).
/// </summary>
public class Betriebsmittel : BaseObject
{
public Guid Id { get; set; }
public BetriebsmittelArt Art { get; set; }
public string Nummer { get; set; }
public string NummerKomplett { get; set; }
public string Bezeichnung { get; set; }
public bool? Leistungsfähig { get; set; }
public string Einheit { get; set; }
public string Kostenart { get; set; }
/// <summary>
/// Liste von Kosten (eine pro Kostenebene, auf der die Kosten für dieses Betriebsmittel definiert sind).
/// Ist normalerweise eine Detailinfo, das heißt, dieses Feld ist nur im Fall von Einzelabfragen befüllt.
/// Allerdings erlaubt der Aufruf /build/global/betriebsmittelstaemme/{betriebsmittelStammId}/betriebsmittel
/// über den "mitKosten"-Parameter das Auslesen meherer Betriebsmittel einschließlich Kosten.
/// </summary>
public List<BetriebsmittelKosten> Kosten { get; set; }
/// <summary>
/// Enthält berechnete Kosten und Preise. Diese sind abhängig von der gewählten Kosten- und Zuschlagsebene.
/// Ist normalerweise eine Detailinfo, das heißt, dieses Feld ist nur im Fall von Einzelabfragen befüllt.
/// Allerdings erlaubt der Aufruf /build/global/betriebsmittelstaemme/{betriebsmittelStammId}/betriebsmittel
/// über den "mitKosten"-Parameter das Auslesen meherer Betriebsmittel einschließlich berechneter Kosten und Preise.
/// </summary>
public BetriebsmittelKostenDetails KostenDetails { get; set; }
/// <summary>
/// (Detailinfo) Liste mit weiteren Kosten.
/// </summary>
public List<KalkulationsZeile> WeitereKosten { get; set; }
/// <summary>
/// (Detailinfo) Die Zuschläge, die auf diesem Betriebsmittel definiert sind.
/// </summary>
public List<BetriebsmittelZuschlag> Zuschläge { get; set; }
/// <summary>
/// (Detailinfo) Spezielle Eigenschaften, die nur bei Einzelabfragen geladen werden.
/// </summary>
public BetriebsmittelDetails Details { get; set; }
/// <summary>
/// Falls das Betriebsmittel eine Gruppe ist, enthält dieses Objekt die passenden Eigenschaften.
/// </summary>
public BetriebsmittelGruppeDetails GruppeDetails { get; set; }
/// <summary>
/// Falls das Betriebsmittel ein Lohn ist, enthält dieses Objekt die passenden Eigenschaften.
/// </summary>
public BetriebsmittelLohnDetails LohnDetails { get; set; }
/// <summary>
/// Falls das Betriebsmittel ein Material ist, enthält dieses Objekt die passenden Eigenschaften.
/// </summary>
public BetriebsmittelMaterialDetails MaterialDetails { get; set; }
/// <summary>
/// Falls das Betriebsmittel eine Gerät ist, enthält dieses Objekt die passenden Eigenschaften.
/// </summary>
public BetriebsmittelGerätDetails GerätDetails { get; set; }
/// <summary>
/// Falls das Betriebsmittel ein Sonstige-Kosten-Objekt ist, enthält dieses Objekt die passenden Eigenschaften.
/// </summary>
public BetriebsmittelSonstigeKostenDetails SonstigeKostenDetails { get; set; }
/// <summary>
/// Falls das Betriebsmittel ein Nachunternehmer ist, enthält dieses Objekt die passenden Eigenschaften.
/// </summary>
public BetriebsmittelNachunternehmerDetails NachunternehmerDetails { get; set; }
/// <summary>
/// Falls das Betriebsmittel ein Baustein ist, enthält dieses Objekt die passenden Eigenschaften.
/// </summary>
public BetriebsmittelBausteinDetails BausteinDetails { get; set; }
}
public class BetriebsmittelDetails : BaseObject
{
/// <summary>
/// Die Beschreibung als Text (ohne Formatierungen).
/// </summary>
public string Beschreibung { get; set; }
public string Stichwörter { get; set; }
public string Markierungskennzeichen { get; set; }
public string StandardAnsatz { get; set; }
public string DbBetriebsmittelGruppeBezeichnung; // = DBBetriebsmittelgruppe
public string KostenartNummer { get; set; }
}
/// <summary>
/// Ein Zuschlag , der auf einem Betriebsmittel definiert ist.
/// </summary>
public class BetriebsmittelZuschlag : BaseObject
{
/// <summary>
/// Verweist auf eine ZuschlagsartGruppe.
/// </summary>
public string ZuschlagsgruppenNummer { get; set; }
/// <summary>
/// Verweist auf eine Zuschlagsart.
/// </summary>
public int ArtIndex { get; set; }
/// <summary>
/// Die ID des Kosten- oder Zuschlagskatalogs.
/// </summary>
public Guid ZuschlagsebeneId { get; set; }
}
public class BetriebsmittelGruppeDetails : BaseObject
{
/// <summary>
/// Die in dieser Gruppe enthaltenen Child-Betriebsmittel.
/// </summary>
public List<Betriebsmittel> BetriebsmittelList { get; set; }
}
public class BetriebsmittelLohnDetails : BaseObject
{
public bool? IstProduktiv { get; set; }
public decimal? EinheitenFaktor { get; set; } // = Umrechnung auf Stunden(1/x)
public string BasNummer { get; set; } // Nummer des Bauarbeitsschlüssels
}
public class BetriebsmittelMaterialDetails : BaseObject
{
public decimal? Ladezeit { get; set; }
}
public class BetriebsmittelGerätDetails : BaseObject
{
public BglArt? BasisBgl { get; set; } // = BGLArt
public string GerätefaktorNummer { get; set; }
public string KostenartAV { get; set; }
public string KostenartRepLohn { get; set; }
public string KostenartRepMaterial { get; set; }
/// <summary>
/// (Detailinfo) Enthält zusätzliche Geräte-Eigenschaften.
/// </summary>
public BetriebsmittelGerätDetailsSonstiges Sonstiges { get; set; }
}
public enum Antriebsart
{
Elektro,
Diesel,
Gas,
Benzin
}
public class BetriebsmittelGerätDetailsSonstiges : BaseObject
{
public string BglNummer { get; set; } // = BGLNummer
public string EdvKurztext { get; set; } // = BGLBezeichnung
// Sonstiges
public decimal? Vorhaltemenge { get; set; }
public decimal? Vorhaltedauer { get; set; }
public Antriebsart? Antriebsart1 { get; set; } // = AntriebsArt
public Antriebsart? Antriebsart2 { get; set; }
public decimal? Gewicht { get; set; }
public decimal? TransportVolumen { get; set; }
public decimal? Leistung1 { get; set; } // = GeraeteLeistung
public decimal? Leistung2 { get; set; } // = GeraeteLeistung2
// Bahnspezifische Angaben
public string Fabrikat { get; set; }
public int? Mindestradius { get; set; }
public int? BeherrschbareSteigung { get; set; }
public string Schallemissionspegel { get; set; }
public int? Arbeitsgeschwindigkeit { get; set; }
public int? GegenseitigeUeberhoehung { get; set; }
}
public class BetriebsmittelSonstigeKostenDetails : BaseObject
{
public string Kostenart1 { get; set; }
public string Kostenart2 { get; set; }
public string Kostenart3 { get; set; }
public string Kostenart4 { get; set; }
public string Kostenart5 { get; set; }
public string Kostenart6 { get; set; }
}
public class BetriebsmittelNachunternehmerDetails : BaseObject
{
public string Kostenart1 { get; set; }
public string Kostenart2 { get; set; }
public string Kostenart3 { get; set; }
public string Kostenart4 { get; set; }
public string Kostenart5 { get; set; }
public string Kostenart6 { get; set; }
}
public class BetriebsmittelBausteinDetails : BaseObject
{
}
/// <summary>
/// Enthält berechnete Betriebsmittelkosten.
/// </summary>
public class BetriebsmittelKostenDetails : BaseObject
{
/// <summary>
/// Die Betriebsmittelkosten (ohne Berücksichtigung der weiteren Kosten).
/// </summary>
public Money Kosten { get; set; }
/// <summary>
/// Der Betriebsmittelpreis (ohne Berücksichtigung der weiteren Kosten).
/// </summary>
public Money Preis { get; set; }
/// <summary>
/// Die Gesamtbetrag der weiteren Kosten.
/// </summary>
public Money WeitereKosten { get; set; }
/// <summary>
/// Die Gesamtkosten.
/// </summary>
public Money KostenGesamt { get; set; }
/// <summary>
/// Der Gesamtpreis.
/// </summary>
public Money PreisGesamt { get; set; }
}
/// <summary>
/// Enthält die Kostenebenen-spezifischen Kosten eines Betriebsmittels.
/// </summary>
public class BetriebsmittelKosten : BaseObject
{
/// <summary>
/// Die ID der Kostenebene, auf der die Kosten für das Betriebsmittel definiert sind (z.B. des Kostenkatalog).
/// </summary>
public Guid KostenebeneId { get; set; }
/// <summary>
/// Der Typ der Kostenebene (muss bei PUT-Operationen nicht angegeben werden).
/// </summary>
public KostenebeneTyp? KostenebeneTyp { get; set; }
/// <summary>
/// Befüllt, wenn das Betriebsmittel ein Lohn ist.
/// </summary>
public BetriebsmittelKostenLohnDetails LohnDetails { get; set; }
/// <summary>
/// Befüllt, wenn das Betriebsmittel ein Material ist.
/// </summary>
public BetriebsmittelKostenMaterialDetails MaterialDetails { get; set; }
/// <summary>
/// Befüllt, wenn das Betriebsmittel ein Gerät ist.
/// </summary>
public BetriebsmittelKostenGerätDetails GerätDetails { get; set; }
/// <summary>
/// Befüllt, wenn das Betriebsmittel ein Sonstige-Kosten-Objekt ist.
/// </summary>
public BetriebsmittelKostenSonstigeKostenDetails SonstigeKostenDetails { get; set; }
/// <summary>
/// Befüllt, wenn das Betriebsmittel ein Nachunternehmer ist.
/// </summary>
public BetriebsmittelKostenNachunternehmerDetails NachunternehmerDetails { get; set; }
}
public enum KostenebeneTyp
{
Kostenkatalog,
Zuschlagskatalog,
Kalkulation,
Lv,
Umlagegruppe,
Projekt,
Unterprojekt,
BetriebsmittelKalkulationsZeile
}
public class BetriebsmittelKostenLohnDetails : BaseObject
{
public Money Kostenanteil1 { get; set; }
public Money Kostenanteil2 { get; set; }
public int? WarengruppeNummer { get; set; }
}
public class BetriebsmittelKostenMaterialDetails : BaseObject
{
public Money Listenpreis { get; set; }
public decimal? Rabatt { get; set; }
public decimal? Verlust { get; set; }
public Money Manipulation { get; set; }
public Money Transportkosten { get; set; }
public int? WarengruppeNummer { get; set; }
}
public class BetriebsmittelKostenGerätDetails : BaseObject
{
public Money Neuwert { get; set; } // = Mittlerer Neuwert
public Money Kostenanteil1 { get; set; }
public Money Kostenanteil2 { get; set; }
public decimal? AbschreibungVerzinsung { get; set; } // = A + V
public decimal? Reparaturkosten { get; set; }
}
public class BetriebsmittelKostenSonstigeKostenDetails : BaseObject
{
public Money Kostenanteil1 { get; set; }
public Money Kostenanteil2 { get; set; }
public Money Kostenanteil3 { get; set; }
public Money Kostenanteil4 { get; set; }
public Money Kostenanteil5 { get; set; }
public Money Kostenanteil6 { get; set; }
public int? Warengruppe0Nummer { get; set; }
public int? Warengruppe1Nummer { get; set; }
public int? Warengruppe2Nummer { get; set; }
public int? Warengruppe3Nummer { get; set; }
public int? Warengruppe4Nummer { get; set; }
public int? Warengruppe5Nummer { get; set; }
}
public class BetriebsmittelKostenNachunternehmerDetails : BaseObject
{
public Money Kostenanteil1 { get; set; }
public Money Kostenanteil2 { get; set; }
public Money Kostenanteil3 { get; set; }
public Money Kostenanteil4 { get; set; }
public Money Kostenanteil5 { get; set; }
public Money Kostenanteil6 { get; set; }
public int? Warengruppe0Nummer { get; set; }
public int? Warengruppe1Nummer { get; set; }
public int? Warengruppe2Nummer { get; set; }
public int? Warengruppe3Nummer { get; set; }
public int? Warengruppe4Nummer { get; set; }
public int? Warengruppe5Nummer { get; set; }
}
public class KalkulationsZeileDetails : BaseObject
{
public decimal? Ergebnis { get; set; }
public decimal? MengeGesamt { get; set; }
public decimal? LeistungsMenge { get; set; }
public Money KostenProEinheit { get; set; }
public Money Kosten { get; set; }
public Money Preis { get; set; }
public decimal? StundenProduktiv { get; set; }
public Money ZuschlagGesamt { get; set; }
}
/// <summary>
/// Eine Zeile in den weiteren Kosten oder in einem Kalkulationsblatt der Detailkalkulation.
/// </summary>
public class KalkulationsZeile : BaseObject
{
/// <summary>
/// Die ID ist bei GET-Zugriffen immer befüllt. Für PUT-Operationen, d.h. für
/// PUT /build/{projektId}/kalkulationen/{kalkulationId}/kalkulationsBlaetter/{positionId} und
/// PUT /build/global/betriebsmittel/{betriebsmittelId}
/// kann sie fehlen. In diesem Fall wird die Zeile neu angelegt.
/// </summary>
public Guid? Id { get; set; }
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
public string Kommentar { get; set; }
public string Einheit { get; set; }
public bool IstInaktiv { get; set; }
/// <summary>
/// (Detailinfo) Enthält weitere Eigenschaften der Kalkulationszeile, insbesondere berechnete Werte.
/// </summary>
public KalkulationsZeileDetails Details { get; set; }
/// <summary>
/// Befüllt, wenn die Zeile einen Verweis auf ein Betriebsmittel enthält.
/// </summary>
public KalkulationsZeileBetriebsmittelDetails BetriebsmittelDetails { get; set; }
/// <summary>
/// Befüllt, wenn die Zeile einen Variablenansatz enthält.
/// </summary>
public KalkulationsZeileVariablenDetails VariablenDetails { get; set; }
/// <summary>
/// Befüllt, wenn es sich um eine Kommentarzeile handelt.
/// </summary>
public KalkulationsZeileKommentarDetails KommentarDetails { get; set; }
/// <summary>
/// Befüllt, wenn es sich um eine Unterposition handelt. Diese kann mehrere Unterzeilen enthalten.
/// </summary>
public KalkulationsZeileUnterpositionDetails UnterpositionDetails { get; set; }
/// <summary>
/// Befüllt, wenn es sich um einen Rückgriff handelt.
/// </summary>
public RückgriffZeileDetails RückgriffDetails { get; set; }
/// <summary>
/// Befüllt, wenn es sich um eine Summenzeile handelt.
/// </summary>
public SummenKalkulationsZeileDetails SummenDetails { get; set; }
}
public class KalkulationsZeileBetriebsmittelDetails : BaseObject
{
public Guid BetriebsmittelId { get; set; }
public BetriebsmittelArt? BetriebsmittelArt { get; set; } // aus Performancegründen speichern wir hier auch (optional) die Betriebsmittelart ab
public string Ansatz { get; set; }
public string BasNummer { get; set; }
}
public class KalkulationsZeileVariablenDetails : BaseObject
{
public string Variable { get; set; }
public string Ansatz { get; set; }
}
public class KalkulationsZeileKommentarDetails : BaseObject
{
}
public class RückgriffZeileDetails : BaseObject
{
public Guid PositionId { get; set; }
public Guid? UnterpositionsZeileId { get; set; }
public string Ansatz { get; set; }
}
public enum SummenKalkulationsZeileArt
{
Relativ = 0,
Absolut = 1,
}
public class SummenKalkulationsZeileDetails : BaseObject
{
public SummenKalkulationsZeileArt? Art { get; set; }
public string Modifikator { get; set; }
public Money Kosten { get; set; }
public Money Preis { get; set; }
public decimal? StundenProduktiv { get; set; }
}
public class KalkulationsZeileUnterpositionDetails : BaseObject
{
public string Ansatz { get; set; }
public string BasNummer { get; set; }
/// <summary>
/// Zeilen, die in dieser Zeile enthalten sind.
/// </summary>
public List<KalkulationsZeile> Zeilen { get; set; }
}
public enum BglArt
{
Keine,
Oebgl,
Dbgl
}
public enum Norm
{
Oenorm,
Gaeb
}
public enum LvArt
{
Ausschreibung,
FreieAusschreibung,
Vergabe,
Auftrag,
FreierAuftragEingehend,
FreierAuftragAusgehend,
Kostenschaetzung,
Anfrage,
Angebot,
FreiesAngebot,
AuftragAusfuehrend,
Subvergabe,
SubVergabeAusfuehren
}
public enum KalkulationsArt
{
NullKalkulation,
AbgestimmteNullKalkulation,
OptimierteKalkulation,
AngebotsKalkulation,
AuftragsKalkulation,
Arbeitskalkulation
}
public class NewKalkulationInfo
{
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
public KalkulationsArt? KalkulationsArt { get; set; }
public Guid BetriebsmittelStammId { get; set; }
public Guid? KostenkatalogId { get; set; }
public Guid? ZuschlagskatalogId { get; set; }
}
/// <summary>
/// Eine zu einem Leistungsverzeichnis gehörende Kalkulation.
/// </summary>
public class Kalkulation : BaseObject
{
public Guid Id { get; set; }
public Guid LvId { get; set; }
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
public KalkulationsArt? Art { get; set; }
/// <summary>
/// Liste von untergeordneten Kalkulationen. Ist nur befüllt, wenn die Kalkulationen
/// als Teil eines Leistungsverzeichnisses, d.h. per /build/{projektId}/leistungsverzeichnisse/{lvId} geladen wurden.
/// </summary>
public List<Kalkulation> Kalkulationen { get; set; }
/// <summary>
/// Enthält Informationen über die Zahl der Nachkommastellen verschiedener Feldtypen.
/// </summary>
public KalkulationNachkommastellen Nachkommastellen { get; set; }
}
public class KalkulationNachkommastellen : BaseObject
{
public int? Ansatz { get; set; }
public int? AnsatzUI { get; set; }
public int? KostenPreise { get; set; }
public int? KostenPreiseUI { get; set; }
}
/// <summary>
/// Ein Kalkulationsblatt. Dieses enthält die Kalkulationszeilen zu einer Position.
/// Als Id fungiert das Tupel (KalkulationId, PositionId).
/// </summary>
public class KalkulationsBlatt : BaseObject
{
public Guid KalkulationId { get; set; }
public Guid PositionId { get; set; }
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
/// <summary>
/// (Detailinfo) Objekt mit weiteren Eigenschaften, insbesondere berechnete Werte (z.B. Einheitspreis).
/// </summary>
public KalkulationsBlattDetails Details { get; set; }
/// <summary>
/// (Detailinfo) Liste von Kalkulationszeilen (hierarchisch aufgebaut).
/// </summary>
public List<KalkulationsZeile> Zeilen { get; set; }
}
public class NewKalkulationsBlattInfo
{
public Guid PositionId { get; set; }
}
/// <summary>
/// Detailinformationen (insbesondere berechnete Werte) eines Kalkulationsblattes
/// </summary>
public class KalkulationsBlattDetails : BaseObject
{
public string PositionsNummerKomplett { get; set; }
public decimal? Menge { get; set; }
public decimal? StundenProduktiv { get; set; }
public decimal? StundenProduktivGesamt { get; set; }
public Money Kosten { get; set; }
public Money KostenGesamt { get; set; }
public Money Preis { get; set; }
public Money PreisGesamt { get; set; }
public Money Einheitspreis { get; set; }
public Money EinheitspreisGesamt { get; set; }
public Dictionary<string, Money> Preisanteile { get; set; }
}
public class PreisanteilInfo : BaseObject
{
public string Code { get; set; }
public string Bezeichnung { get; set; }
}
/// <summary>
/// Ein Leistungsverzeichnis (GAEB oder ÖNORM).
/// </summary>
public class Leistungsverzeichnis : BaseObject
{
public Guid Id { get; set; } // ist die ID der Box
public string Nummer { get; set; }
public string Bezeichnung { get; set; }
public Norm? Norm { get; set; }
public LvArt? Art { get; set; }
public string Waehrung { get; set; }
public List<PreisanteilInfo> PreisanteilInfos { get; set; }
/// <summary>
/// (Detailinfo) Der Wurzelknoten einschließlich untergeordneter Knoten und Positionen.
/// </summary>
public LvKnoten RootKnoten { get; set; }
/// <summary>
/// (Detailinfo) Die Wurzelkalkulationen einschließlich untergeordneter Kalkulationen.
/// </summary>
public List<Kalkulation> RootKalkulationen { get; set; }
}
public enum Herkunftskennzeichen
{
/// <summary>
/// Position aus einem Leistungsbuch (LB).
/// </summary>
LB,
/// <summary>
/// + ... Position aus einem Ergänzungs-LB
/// </summary>
ErgLB,
/// <summary>
/// Z ... Frei formulierte Position (Z-Position)
/// </summary>
Z
}
public class LvItemBase : BaseObject
{
public Guid Id { get; set; }
public string Typ { get; set; }
public string Nummer { get; set; }
public string NummerKomplett { get; set; }
public string Kurztext { get; set; }
public string Langtext { get; set; }
public string Teilleistungsnummer { get; set; }
public Money Betrag { get; set; }
public Herkunftskennzeichen? Herkunftskennzeichen { get; set; }
}
/// <summary>
/// Ein LV-Knoten (z.B. Titel oder Leistungsgruppe).
/// </summary>
public class LvKnoten : LvItemBase
{
public List<LvKnoten> Knoten { get; set; }
public List<LvPosition> Positionen { get; set; }
}
/// <summary>
/// Eine LV-Position.
/// </summary>
public class LvPosition : LvItemBase
{
public string Einheit { get; set; }
public string Art { get; set; }
public decimal? LvMenge { get; set; }
// TODO Prognosemengen
public Dictionary<string, Money> Preisanteile { get; set; }
public Money Einheitspeis { get; set; }
public bool IstFixpreis { get; set; }
public bool IstIntern { get; set; }
}
/// <summary>
/// Ein einfacher Geldbetrag (inklusive Währung).
/// </summary>
public class SimpleMoney
{
public SimpleMoney(string currency, decimal? value)
{
Currency = currency;
Value = value;
}
[JsonProperty("cur")]
public string Currency { get; private set; }
[JsonProperty("val")]
public decimal? Value { get; private set; }
public override string ToString()
{
return Currency + " " + Value;
}
}
/// <summary>
/// Ein mehrfacher Geldbetrag (für unterschiedliche Währungen).
/// </summary>
public class Money : Collection<SimpleMoney>
{
public Money()
{
}
public static Money FromValues(IEnumerable<(string Currency, decimal? Value)> values)
{
if (values == null)
{
return null;
}
Money result = null;
foreach (var betrag in values)
{
if (result == null)
{
result = new Money();
}
result.Add(betrag.Currency, betrag.Value);
}
return result;
}
public void Add(string currency, decimal? value)
{
Add(new SimpleMoney(currency, value));
}
public decimal? FirstValue
{
get => this.FirstOrDefault()?.Value;
set => this[0] = new SimpleMoney(this[0].Currency, value);
}
public override string ToString()
{
return string.Join("; ", this);
}
}
}
<file_sep>/README.md
# http-api-demo-clients
Diese Visual Studio-Solution enthält Projekt, die den Zugriff auf NEVARIS Build 2019 über die HTTP-API demonstrieren:
* *BetriebsmittelStammApp:* WPF-Applikation, die Betriebsmittelstämme von einem System in ein anderes kopiert.
* *AdressConsoleApp:* Konsolenapplikation, die den Zugriff auf globale Adressen demonstriert. Die notwendigen Einstellungen (unter anderem die Basis-URL des Zielsystems) werden aus der Datei _Settings.json_ ausgelesen.
<file_sep>/Nevaris.Build.ClientApi/IProjektApi.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Refit;
namespace Nevaris.Build.ClientApi
{
/// <summary>
/// Interface zum Zugriff auf projektspezifische Operationen über die NEVARIS Build API.
/// </summary>
public interface IProjektApi
{
[Get("/build/projekte/{projektId}")]
Task<Projekt> GetProjekt(string projektId);
[Delete("/build/projekte/{projektId}")]
Task DeleteProjekt(string projektId);
[Get("/build/projekte/{projektId}/leistungsverzeichnisse")]
Task<List<Leistungsverzeichnis>> GetLeistungsverzeichnisse(string projektId);
[Get("/build/projekte/{projektId}/leistungsverzeichnisse/{lvId}?mitKnoten={mitKnoten}&mitKalkulationen={mitKalkulationen}")]
Task<Leistungsverzeichnis> GetLeistungsverzeichnis(string projektId, Guid lvId, bool mitKnoten = true, bool mitKalkulationen = true);
[Post("/build/projekte/{projektId}/leistungsverzeichnisse/{lvId}")]
Task<Kalkulation> CreateKalkulation(string projektId, Guid lvId, [Body] NewKalkulationInfo newKalkulationInfo);
[Get("/build/projekte/{projektId}/kalkulationen/{kalkulationId}")]
Task<Kalkulation> GetKalkulation(string projektId, Guid kalkulationId);
[Post("/build/projekte/{projektId}/kalkulationen/{parentKalkulationId}/kalkulationen")]
Task<Kalkulation> CreateUntergeordneteKalkulation(string projektId, Guid parentKalkulationId);
[Put("/build/projekte/{projektId}/kalkulationen/{kalkulationId}")]
Task UpdateKalkulation(string projektId, Guid kalkulationId, [Body] Kalkulation kalkulation);
[Delete("/build/projekte/{projektId}/kalkulationen/{kalkulationId}")]
Task DeleteKalkulation(string projektId, Guid kalkulationId);
[Get("/build/projekte/{projektId}/kalkulationen/{kalkulationId}/kalkulationsBlaetter?mitZeilen={mitZeilen}")]
Task<List<KalkulationsBlatt>> GetKalkulationsBlätter(string projektId, Guid kalkulationId, bool mitZeilen = false);
[Get("/build/projekte/{projektId}/kalkulationen/{kalkulationId}/kalkulationsBlaetter/{positionId}?createNewIfNecessary={createNewIfNecessary}&includeParentKalkulationen={includeParentKalkulationen}")]
Task<KalkulationsBlatt> GetKalkulationsBlatt(string projektId, Guid kalkulationId, Guid positionId, bool createNewIfNecessary = false, bool includeParentKalkulationen = false);
[Put("/build/projekte/{projektId}/kalkulationen/{kalkulationId}/kalkulationsBlaetter/{positionId}")]
Task UpdateKalkulationsBlatt(string projektId, Guid kalkulationId, Guid positionId, [Body] KalkulationsBlatt kalkulationsBlatt);
[Delete("/build/projekte/{projektId}/kalkulationen/{kalkulationId}/kalkulationsBlaetter/{positionId}")]
Task DeleteKalkulationsBlatt(string projektId, Guid kalkulationId, Guid positionId);
[Get("/build/projekte/{projektId}/betriebsmittel?art={art}&mitGruppen={mitGruppen}&mitKosten={mitKosten}&mitWeiterenKosten={mitWeiterenKosten}&mitZuschlaegen={mitZuschlaegen}&mitDetails={mitDetails}&kostenebeneId={kostenebeneId}&zuschlagsebeneId={zuschlagsebeneId}")]
Task<List<Betriebsmittel>> GetAllBetriebsmittel(
string projektId,
BetriebsmittelArt? art,
bool mitGruppen = true,
bool mitKosten = false,
bool mitWeiterenKosten = false,
bool mitZuschlaegen = false,
bool mitDetails = false,
Guid? kostenebeneId = null,
Guid? zuschlagsebeneId = null);
[Get("/build/projekte/{projektId}/betriebsmittel/{betriebsmittelId}?art={art}&kostenebeneId={kostenebeneId}&zuschlagsebeneId={zuschlagsebeneId}")]
Task<Betriebsmittel> GetBetriebsmittel(
string projektId,
Guid betriebsmittelId,
BetriebsmittelArt? art = null,
Guid? kostenebeneId = null,
Guid? zuschlagsebeneId = null);
[Post("/build/projekte/{projektId}/betriebsmittel")]
Task<Betriebsmittel> CreateBetriebsmittel(string projektId, [Body] NewBetriebsmittelInfo newBetriebsmittelInfo);
[Put("/build/projekte/{projektId}/betriebsmittel/{betriebsmittelId}")]
Task UpdateBetriebsmittel(string projektId, Guid betriebsmittelId, [Body] Betriebsmittel betriebsmittel);
[Delete("/build/projekte/{projektId}/betriebsmittel/{betriebsmittelId}")]
Task DeleteBetriebsmittel(string projektId, Guid betriebsmittelId);
}
}
<file_sep>/Nevaris.Build.ClientApi/IStammApi.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Refit;
namespace Nevaris.Build.ClientApi
{
/// <summary>
/// Interface zum Zugriff auf Stammdaten-Operationen über die NEVARIS Build API.
/// </summary>
public interface IStammApi
{
[Get("/build/global/version")]
Task<VersionInfo> GetVersion();
[Get("/build/global/adressen")]
Task<List<Adresse>> GetAdressen();
[Get("/build/global/adressen/{code}")]
Task<Adresse> GetAdresse(string code);
[Post("/build/global/adressen")]
Task<Adresse> CreateAdresse([Body] NewAdresseInfo newAdresseInfo);
[Put("/build/global/adressen/{code}")]
Task UpdateAdresse(string code, [Body] Adresse adresse);
[Delete("/build/global/adressen/{code}")]
Task DeleteAdresse(string code);
[Get("/build/global/speicherorte")]
Task<List<Speicherort>> GetSpeicherorte();
[Get("/build/global/speicherorte/{id}")]
Task<Speicherort> GetSpeicherort(Guid id);
[Post("/build/global/speicherorte/{speicherortId}/projekte")]
Task<Projekt> CreateProjekt(Guid speicherortId, [Body] NewProjektInfo newProjekt);
[Get("/build/global/betriebsmittelstaemme")]
Task<List<BetriebsmittelStamm>> GetBetriebsmittelStämme();
[Get("/build/global/betriebsmittelstaemme/{betriebsmittelStammId}")]
Task<BetriebsmittelStamm> GetBetriebsmittelStamm(Guid betriebsmittelStammId);
[Post("/build/global/betriebsmittelstaemme")]
Task<BetriebsmittelStamm> CreateBetriebsmittelStamm([Body] NewBetriebsmittelStammInfo newBetriebsmittelstammInfo);
[Put("/build/global/betriebsmittelstaemme/{betriebsmittelStammId}")]
Task UpdateBetriebsmittelStamm(Guid betriebsmittelStammId, [Body] BetriebsmittelStamm betriebsmittelstamm);
[Delete("/build/global/betriebsmittelstaemme/{betriebsmittelStammId}")]
Task DeleteBetriebsmittelStamm(Guid betriebsmittelStammId);
[Get("/build/global/betriebsmittelstaemme/{betriebsmittelStammId}/betriebsmittel?art={art}&mitGruppen={mitGruppen}&mitKosten={mitKosten}&mitWeiterenKosten={mitWeiterenKosten}&mitZuschlaegen={mitZuschlaegen}&mitDetails={mitDetails}&kostenebeneId={kostenebeneId}&zuschlagsebeneId={zuschlagsebeneId}")]
Task<List<Betriebsmittel>> GetAllBetriebsmittel(
Guid betriebsmittelStammId,
BetriebsmittelArt? art,
bool mitGruppen = true,
bool mitKosten = false,
bool mitWeiterenKosten = false,
bool mitZuschlaegen = false,
bool mitDetails = false,
Guid? kostenebeneId = null,
Guid? zuschlagsebeneId = null);
[Get("/build/global/betriebsmittel/{betriebsmittelId}?art={art}&kostenebeneId={kostenebeneId}&zuschlagsebeneId={zuschlagsebeneId}")]
Task<Betriebsmittel> GetBetriebsmittel(
Guid betriebsmittelId,
BetriebsmittelArt? art = null,
Guid? kostenebeneId = null,
Guid? zuschlagsebeneId = null);
[Post("/build/global/betriebsmittelstaemme/{betriebsmittelStammId}/betriebsmittel")]
Task<Betriebsmittel> CreateBetriebsmittel(Guid betriebsmittelStammId, [Body] NewBetriebsmittelInfo newBetriebsmittelInfo);
[Put("/build/global/betriebsmittel/{betriebsmittelId}")]
Task UpdateBetriebsmittel(Guid betriebsmittelId, [Body] Betriebsmittel betriebsmittel);
[Delete("/build/global/betriebsmittel/{betriebsmittelId}")]
Task DeleteBetriebsmittel(Guid betriebsmittelId);
}
}
<file_sep>/Nevaris.Build.ClientApi/NevarisBuildClient.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Refit;
namespace Nevaris.Build.ClientApi
{
/// <summary>
/// Ermöglicht die Steuerung von NEVARIS Build (Stammdaten und Projekte) über die NEVARIS Build API.
/// Voraussetzung ist, dass der NEVARIS Build Businessdienst auf einem erreichbaren Server läuft und
/// so konfiguriert ist, dass die HTTP API bereitgestellt wird. Dazu muss auf dem Server in der
/// %PROGRAMDATA%/Nemetschek/Nevaris/Nevaris.config ein entsprechender SystemSetting-Eintrag
/// (<HttpApiBaseAddress>http://*:8500</HttpApiBaseAddress>) vorhanden sein. Zur Kontrolle,
/// ob die HTTP API verfügbar ist, kann vom Client aus in einem Browser über die URL [BASIS-URL]/api-docs
/// die API-Doku abgerufen werden (z.B. http://localhost:8500/api-docs für den Fall, dass der
/// Businessdienst auf dem lokalen Rechner läuft).
/// </summary>
public class NevarisBuildClient
{
/// <summary>
/// Konstruktor.
/// </summary>
/// <param name="hostUrl">Die Basis-URL, auf der die API bereitgestellt wird, z.B. "http://localhost:8500".</param>
public NevarisBuildClient(string hostUrl)
{
HostUrl = hostUrl;
ProjektApi = RestService.For<IProjektApi>(hostUrl, _refitSettings);
StammApi = RestService.For<IStammApi>(hostUrl, _refitSettings);
}
/// <summary>
/// Liefert die im Konstruktor übergebene Basis-URL.
/// </summary>
public string HostUrl { get; }
/// <summary>
/// Zugriff auf projektspezifische Operationen.
/// </summary>
public IStammApi StammApi { get; }
/// <summary>
/// Zugriff auf Stammdaten-Operationen.
/// </summary>
public IProjektApi ProjektApi { get; }
static RefitSettings _refitSettings = new RefitSettings
{
JsonSerializerSettings = _jsonSerializerSettings
};
static JsonSerializerSettings _jsonSerializerSettings = new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = { new StringEnumConverter { CamelCaseText = true } },
NullValueHandling = NullValueHandling.Ignore
};
}
}
|
b19a723e97789bd6cdee7b3c458b1ec8a6d4df84
|
[
"Markdown",
"C#"
] | 5 |
C#
|
AndreasHorwath/http-api-demo-clients
|
853ac48c8470b29c9bc24a6c77d2d21aec1c7926
|
cf061c2cb951d5dd778f531b4197db0579fd1b16
|
refs/heads/master
|
<repo_name>santanarscs/fenrir<file_sep>/resources/assets/spa/js/mixins/class_information.mixin.js
import store from '../store/store';
export default {
computed: {
classTeaching() {
return store.state.teacher.classTeaching.classTeaching;
},
classInformation() {
return !this.classTeaching ? null : this.classTeaching.class_information;
},
classInformationName() {
if (this.classInformation) {
let classInformationAlias = this.$options.filters.classInformationAlias(this.classInformation);
return `${classInformationAlias} - ${this.classTeaching.subject.name}`;
}
return null;
},
}
}
|
e19bad09a997d8d64d13003af26693fc47eef597
|
[
"JavaScript"
] | 1 |
JavaScript
|
santanarscs/fenrir
|
b23fad9edbfe0f3ef18e79a369867f60c2c0684b
|
8f459b67c8f8eccaddfc61510e60f40011d528c9
|
refs/heads/master
|
<repo_name>asifrc/rnr2<file_sep>/src/main/java/com/thoughtworks/rnr/factory/JSONObjectFactory.java
package com.thoughtworks.rnr.factory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.IOException;
import java.io.InputStreamReader;
public class JSONObjectFactory {
public JSONObject httpResponseToJSONObject(HttpResponse response) throws IOException, JSONException {
HttpEntity entity = response.getEntity();
return new JSONObject(
new JSONTokener(new InputStreamReader(
entity.getContent()))
);
}
}
<file_sep>/src/test/java/com/thoughtworks/rnr/saml/IPRangeTest.java
package com.thoughtworks.rnr.saml;
import com.thoughtworks.rnr.saml.util.IPRange;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class IPRangeTest {
@Test
public void testInvalidAddress_NonNumeric() {
try {
new IPRange("1.2.3.a", "1.2.3.4");
fail("Exception expected");
} catch (NumberFormatException ex) {
//expected
} catch (Exception ex) {
fail("Expected NumberFormatException");
}
}
@Test
public void testInvalidAddress_RangeTooLow() {
try {
new IPRange("1.2.3.-1", "1.2.3.4");
fail("Exception expected");
} catch (NumberFormatException ex) {
//expected
} catch (Exception ex) {
fail("Expected NumberFormatException");
}
}
@Test
public void testInvalidAddress_RangeTooHigh() {
try {
new IPRange("1.2.3.266", "1.2.3.4");
fail("Exception expected");
} catch (NumberFormatException ex) {
//expected
} catch (Exception ex) {
fail("Expected NumberFormatException");
}
}
@Test
public void testIPWildcard() {
IPRange ipRange = new IPRange("1.2.3.*", null);
assertTrue(ipRange.isAddressInRange("1.2.3.10"));
assertTrue(ipRange.isAddressInRange("1.2.3.0"));
assertTrue(ipRange.isAddressInRange("1.2.3.255"));
}
@Test
public void testIPInMatch() {
IPRange ipRange = new IPRange("1.2.3.4", null);
assertTrue(ipRange.isAddressInRange("1.2.3.4"));
}
@Test
public void testIPNotMatch() {
IPRange ipRange = new IPRange("1.2.3.5", null);
assertFalse(ipRange.isAddressInRange("1.2.3.4"));
}
@Test
public void testIPInRange() {
IPRange ipRange = new IPRange("1.2.3.4", "5.6.7.8");
assertTrue(ipRange.isAddressInRange("1.2.3.4"));
assertTrue(ipRange.isAddressInRange("4.4.4.4"));
assertTrue(ipRange.isAddressInRange("5.5.5.5"));
assertTrue(ipRange.isAddressInRange("5.6.7.8"));
assertTrue(ipRange.isAddressInRange("1.6.7.8"));
}
@Test
public void testIPInRangeFirstWildcard() {
IPRange ipRange = new IPRange("1.2.3.4", "*.6.7.8");
assertTrue(ipRange.isAddressInRange("255.4.5.6"));
}
@Test
public void testIPInRangeSecondWildcard() {
IPRange ipRange = new IPRange("1.2.3.4", "5.*.7.8");
assertTrue(ipRange.isAddressInRange("5.255.5.6"));
}
@Test
public void testIPInRangeThirdWildcard() {
IPRange ipRange = new IPRange("1.2.3.4", "5.6.*.8");
assertTrue(ipRange.isAddressInRange("192.168.3.11"));
}
@Test
public void testIPInRangeFourthWildcard() {
IPRange ipRange = new IPRange("1.2.3.4", "5.6.7.*");
assertTrue(ipRange.isAddressInRange("4.5.6.255"));
}
@Test public void testIPOutOfRange() {
IPRange ipRange = new IPRange("1.2.3.4", "5.6.7.8");
assertFalse(ipRange.isAddressInRange("6.0.4.5"));
assertFalse(ipRange.isAddressInRange("2.7.0.5"));
assertFalse(ipRange.isAddressInRange("2.3.8.0"));
assertFalse(ipRange.isAddressInRange("192.168.127.12"));
}
}
<file_sep>/src/main/webapp/prod.properties
host=http://rnr.thoughtworks.com:80/manager/text
redirectUrl=https://thoughtworks.oktapreview.com/app/template_saml_2_0/k21tpw64VPAMDOMKRXBS/sso/saml
timeProvider=com.thoughtworks.rnr.saml.util.SimpleClock<file_sep>/README.md
# RnR Readme
Thanks for your interest in contributing to the ThoughtWorks RnR project!
To get started, you will want to clone and set this project up locally, helpful tips are included below.
To start contributing to this project, you will need to contact the Chicago Beach for access to the Trello board,
where information project setup and current iteration is stored.
~~~~~~~~~
**Trello Etiquette**
We are using Trello (https://trello.com/) as our story tracker as well as for iteration planning and tracking purposes. Information about project contributors,
accessing the production server and ci pipeline, etc, can be found on the InfoBoard. Stories can be found on the currentIterationStoryBoard.
If you would like to work on a story, please use Trello to Assign yourself to the story and put it in "Doing".
If for any reason you ned to stop working on that story, please add an update on what you have accomplished in the comments, unassign yourself,
and move the story back to "Ready for Development".
This process should be used for stories being development as well as stories in QA.
Since it is not always possible for everyone on this project to attend a stand-up, it is important that you keep the Trello board up to date with
as much detail as possible.
~~~~~~~~~~~~~
**Things you might want to install**
IntelliJ Ultimate Edition Version 13.0.3, bld: 133.1122 **See note below
HomeBrew (http://brew.sh/ -- makes installation easy)
Using Homebrew:
Git
Gradle
Jetty
### In terminal:
cd to project directory
```gradle build```
To run application:
```gradle -q -Dorg.gradle.project.environment=dev jettyRun```
To run unit tests:
```gradle test```
To run functional tests:
```gradle -Dorg.gradle.project.environment=test testFunctional```
This version has a known bug that is incompatible with Gradle:
IntelliJ IDEA 13.1.2
Build #IU-135.690, built on April 17, 2014
Import using build.gradle file.
Run tasks using gradle toolbuttons.
~~~
**Troubleshooting**
FEEL FREE TO ADD ANY TIPS OR PROBLEMS YOU ENCOUNTER TO THIS LIST
If code shows errors due to missing libraries:
import libraries: junit-4.1.0 and spring-framework-web if it's not there
If 'catalina start' in the terminal does not work:
Install Tomcat 7.0.42
have port 8080 open
If there is no artifact:
Project Structure - Artifacts tab
Plus sign, added Web App Exploded, selected main folder
Make sure to add all the libraries to the artifact
If Intellij is throwing errors after these steps:
Delete the project
Check out from VCS on the home IntelliJ page using GIT
Then open the project from the home IntelliJ page
Repeat all above steps as necessary
If you seem to be missing an inordinate number of libraries and the artifact cannot be deployed
Check your version of Java.
Less than 1.7 will cause really funky errors
Cheers!
<file_sep>/src/main/java/com/thoughtworks/rnr/controller/SAMLController.java
package com.thoughtworks.rnr.controller;
import com.thoughtworks.rnr.service.SAMLService;
import com.thoughtworks.rnr.service.SalesForceService;
import org.opensaml.ws.security.SecurityPolicyException;
import org.opensaml.xml.io.UnmarshallingException;
import org.opensaml.xml.validation.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.xml.sax.SAXException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.security.cert.CertificateException;
@Controller
public class SAMLController {
private SAMLService samlService;
private SalesForceService salesForceService;
@Autowired
public SAMLController(SAMLService samlService, SalesForceService salesForceService) {
this.samlService = samlService;
this.salesForceService = salesForceService;
}
@RequestMapping(value = "/auth/saml/callback", method = RequestMethod.POST)
public String handleOKTACallback(HttpServletRequest request, HttpServletResponse response) {
try {
String samlResponse = request.getParameter("SAMLResponse");
samlService.setSessionWhenSAMLResponseIsValid(request, samlResponse);
// salesForceService.authenticateWithSalesForce(request, response); // comment this line for functional test run and ignore corresponding controller test.
// return null; // for real life, since this line of code never gets reached.
return "redirect:/home"; // for functional test run, since we need to comment out above call to salesforceservice.
}
catch (IOException | UnmarshallingException | ValidationException | ParserConfigurationException | SAXException | SecurityPolicyException | CertificateException e) {
return "sorry";
}
}
}<file_sep>/src/test/java/com/thoughtworks/rnr/controller/HomeControllerTest.java
package com.thoughtworks.rnr.controller;
import com.thoughtworks.rnr.model.AccrualRateCalculator;
import com.thoughtworks.rnr.model.Constants;
import com.thoughtworks.rnr.model.Employee;
import com.thoughtworks.rnr.model.PersonalDaysCalculator;
import com.thoughtworks.rnr.service.*;
import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.mockito.internal.verification.VerificationModeFactory.times;
public class HomeControllerTest {
private HomeController homeController;
@Mock
SalesForceParserService mockSalesForceParserService;
@Mock
EmployeeService mockEmployeeService;
@Mock
VacationCalculatorService mockVacationCalculatorService;
@Mock
AccrualRateCalculator mockAccrualRateCalculator;
@Mock
DateParserService mockDateParserService;
@Mock
PersonalDaysCalculator mockPersonalDaysCalculator;
@Mock
SAMLService mockSAMLService;
private String startDate;
private String rolloverDays;
private String accrualRate;
private String salesForceText;
private String endDate;
private final String samlRequestURL = "redirect:http://rain.okta1.com:1802/app/template_saml_2_0/k8lqGUUCIFIJHKUOGQKG/sso/saml?";
@Before
public void setUp() throws Exception {
initMocks(this);
homeController = new HomeController(mockEmployeeService, mockSalesForceParserService, mockVacationCalculatorService, mockAccrualRateCalculator, mockDateParserService, mockPersonalDaysCalculator, mockSAMLService);
startDate = "10/22/2012";
rolloverDays = "1";
accrualRate = "10";
salesForceText = "Test";
endDate = "11/22/2013";
}
@Test
public void post_shouldReturnHomeView() throws IOException, ParseException {
assertThat(homeController.postDate(startDate, rolloverDays, accrualRate, salesForceText, endDate).getViewName(), is("home"));
}
@Test
public void get_shouldReturnHomeView() {
HttpServletRequest mockRequest = mock(HttpServletRequest.class);
HttpSession mockSession = mock(HttpSession.class);
when(mockRequest.getSession()).thenReturn(mockSession);
when(mockSession.getAttribute("startDate")).thenReturn("03/03/2014");
ModelAndView mav = homeController.displayHome(mockRequest, new ModelMap());
assertThat(mav.getViewName(), is("home"));
}
@Test
public void shouldInteractWithSalesForceParserServiceAndEmployeeService() throws Exception {
when(mockVacationCalculatorService.getVacationDays(any(Employee.class), any(AccrualRateCalculator.class), any(LocalDate.class))).thenReturn(20d);
when(mockPersonalDaysCalculator.calculatePersonalDays(any(Employee.class), any(LocalDate.class), any(LocalDate.class))).thenReturn(0d);
assertThat(homeController.postDate(startDate, rolloverDays, accrualRate, salesForceText, endDate).getViewName(), is("home"));
verify(mockSalesForceParserService).extractDatesAndHoursFromSalesForceText(salesForceText, Constants.PERSONAL_DAY_CODES);
verify(mockSalesForceParserService).extractDatesAndHoursFromSalesForceText(salesForceText, Constants.VACATION_DAY_CODES);
verify(mockEmployeeService, times(1)).createEmployee(null, rolloverDays, new HashMap<LocalDate, Double>(), new HashMap<LocalDate, Double>(), accrualRate);
verify(mockDateParserService, times(2)).parse(anyString());
}
}
/*
In SP initiated the flow is:
User goes to the target SP first. They do not have a session established with the SP
SP redirects the user to the configured Login URL (Okta’s generated app instance url) sending the SAMLRequest.
Okta is sent SAMLRequest (assumption is that the user has an existing Okta session)
Okta sends a SAMLResponse to the configured SP
SP receives the SAMLResponse and verifies that it is correct. A session is established on the SP side.
User is authenticated
In both cases, there is additional configuration required in the target app (SP) you are configuring SAML with. Okta provides this information in our SAML 2.0 app instructions (accessible from the Sign on tab in the app wizard). This is typically the following: External key, certificate, and login url (normally only needed in the SP initiated flow mentioned above.
*/<file_sep>/src/test/java/com/thoughtworks/rnr/controller/SAMLControllerTest.java
package com.thoughtworks.rnr.controller;
import com.thoughtworks.rnr.service.SAMLService;
import com.thoughtworks.rnr.service.SalesForceService;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mock;
import org.opensaml.ws.security.SecurityPolicyException;
import org.opensaml.xml.io.UnmarshallingException;
import org.opensaml.xml.validation.ValidationException;
import org.xml.sax.SAXException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.security.cert.CertificateException;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
public class SAMLControllerTest {
@Mock HttpServletRequest mockRequest;
@Mock HttpServletResponse mockResponse;
@Mock SAMLService mockSamlService;
@Mock SalesForceService mockSalesForceService;
private SAMLController samlController;
@Before
public void setUp() throws Exception {
initMocks(this);
samlController = new SAMLController(mockSamlService, mockSalesForceService);
}
@Test
public void shouldGetSAMLResponseStringFromHTTPRequest() throws SAXException, ParserConfigurationException, IOException, ValidationException, CertificateException, UnmarshallingException, SecurityPolicyException {
samlController.handleOKTACallback(mockRequest, mockResponse);
verify(mockRequest).getParameter("SAMLResponse");
}
@Test
public void shouldSetSession() throws SAXException, ParserConfigurationException, IOException, ValidationException, CertificateException, UnmarshallingException, SecurityPolicyException {
when(mockRequest.getParameter("SAMLResponse")).thenReturn("some response");
samlController.handleOKTACallback(mockRequest, mockResponse);
verify(mockSamlService).setSessionWhenSAMLResponseIsValid(mockRequest, "some response");
}
@Ignore("Need to ignore due to commenting line out in SAMLController for Functional test run")
@Test
public void shouldAuthenticateWithSalesForce() throws IOException {
samlController.handleOKTACallback(mockRequest, mockResponse);
verify(mockSalesForceService).authenticateWithSalesForce(mockRequest, mockResponse);
}
@Test
public void shouldReturnSorryViewWhenExceptionIsThrown() throws CertificateException, UnmarshallingException, IOException, ValidationException, SAXException, ParserConfigurationException, SecurityPolicyException {
when(mockRequest.getParameter("SAMLResponse")).thenReturn("some response");
doThrow(new SecurityPolicyException()).when(mockSamlService).setSessionWhenSAMLResponseIsValid(mockRequest, "some response");
String actual = samlController.handleOKTACallback(mockRequest,mockResponse);
assertThat(actual, is("sorry"));
}
}<file_sep>/src/main/webapp/dev.properties
host=http://localhost:8080/manager/text
redirectUrl=https://thoughtworks.oktapreview.com/app/template_saml_2_0/k21tpw64VPAMDOMKRXBS/sso/saml
timeProvider=com.thoughtworks.rnr.saml.util.SimpleClock<file_sep>/src/test/java/com/thoughtworks/rnr/saml/SPUsersAndGroupsConfigTest.java
package com.thoughtworks.rnr.saml;
import org.opensaml.DefaultBootstrap;
import org.opensaml.ws.security.SecurityPolicyException;
import org.opensaml.xml.ConfigurationException;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Arrays;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public class SPUsersAndGroupsConfigTest {
private TestsHelper helper;
private Configuration configuration;
@BeforeTest
public void setup() throws IOException, CertificateException, XPathExpressionException,
SecurityPolicyException, ConfigurationException {
DefaultBootstrap.bootstrap(); // initialize openSAML library
helper = new TestsHelper();
configuration = helper.loadConfig("/valid-config-with-sp-users.xml");
}
@Test
public void testUsersInSPRange() {
assertFalse(configuration.isUsernameAllowedForOkta("<EMAIL>"));
assertTrue(configuration.isUsernameAllowedForOkta("no-such-user-in-confluence-list"));
}
@Test
public void testGroupsInSPRange() {
assertFalse(configuration.isInSPGroups(Arrays.asList("no-such-group")));
assertTrue(configuration.isInSPGroups(Arrays.asList("jira-grp")));
assertTrue(configuration.isInSPGroups(Arrays.asList("confluence-grp")));
}
}
<file_sep>/src/main/java/com/thoughtworks/rnr/controller/StubOKTAController.java
package com.thoughtworks.rnr.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class StubOKTAController {
@RequestMapping(value = "/stubOKTA", method = RequestMethod.GET)
public String stubOKTA() {
return "stubOKTA";
}
}<file_sep>/src/test/java/com/thoughtworks/rnr/saml/TestsHelper.java
package com.thoughtworks.rnr.saml;
import org.opensaml.ws.security.SecurityPolicyException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CertificateException;
public class TestsHelper {
public String convertStreamToString(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is, "UTF-8").useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
public Configuration loadConfig(String path) throws IOException, CertificateException, XPathExpressionException, SecurityPolicyException {
InputStream stream = getClass().getResourceAsStream(path);
String file;
try {
file = convertStreamToString(stream);
} finally {
stream.close();
}
return new Configuration(file);
}
}
<file_sep>/build.gradle
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'jetty'
group = 'com.springapp'
version = '1.0-SNAPSHOT'
sourceCompatibility = 1.7
targetCompatibility = 1.7
repositories {
mavenCentral()
}
configurations {
providedCompile
}
sourceSets {
selenium
main {
java {
srcDir 'src/main/java'
if (environment != 'test') {
exclude '**/StubOKTAController.java'
}
}
output.classesDir = 'build/classes/production'
}
test {
java {
srcDir 'src/test/java'
}
output.resourcesDir = 'build/classes/test'
}
}
dependencies {
def seleniumVersion = "2.40.0"
providedCompile "javax.servlet:servlet-api:2.5"
compile group: 'org.springframework', name: 'spring-core', version: '4.0.1.RELEASE'
compile group: 'org.springframework', name: 'spring-web', version: '4.0.1.RELEASE'
compile group: 'javax.servlet', name: 'servlet-api', version: '2.5'
compile group: 'javax.servlet', name: 'jstl', version: '1.2'
compile group: 'joda-time', name: 'joda-time', version: '2.3'
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.0.1.RELEASE'
compile group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.3.2'
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.3.3'
compile group: 'org.json', name: 'json', version: '20080701'
compile group: 'org.eclipse.jetty.orbit', name: 'javax.servlet', version: '3.0.0.v201112011016'
testCompile group: 'org.springframework', name: 'spring-test', version: '4.0.1.RELEASE'
compile group: 'org.opensaml', name: 'openws', version: '1.4.4'
compile group: 'org.opensaml', name: 'opensaml', version: '2.5.3'
compile group: 'commons-codec', name: 'commons-codec', version: ' 1.4'
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.6'
compile group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.6.3'
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.3.2'
testCompile group: 'junit', name: 'junit', version: '4.8.2'
testCompile group: 'org.testng', name: 'testng', version: '6.8.8'
testCompile group: 'org.jbehave', name: 'jbehave-core', version: '3.8'
testCompile group: 'de.codecentric', name: 'jbehave-junit-runner', version: '1.0.1'
testCompile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '2.40.0'
testCompile "com.github.detro.ghostdriver:phantomjsdriver:1.0.1"
testRuntime "org.seleniumhq.selenium:selenium-support:$seleniumVersion"
seleniumCompile 'junit:junit:4.11'
seleniumCompile 'org.seleniumhq.selenium:selenium-java:2.30.0'
}
sourceSets.main.compileClasspath += configurations.providedCompile
sourceSets.test.compileClasspath += configurations.providedCompile
sourceSets.test.runtimeClasspath += configurations.providedCompile
task wrapper(type: Wrapper) {
gradleVersion = '1.12'
}
task jettyDaemon(type: org.gradle.api.plugins.jetty.JettyRun) {
daemon = true
}
[jettyRun, jettyRunWar, jettyStop]*.stopPort = 8081
[jettyRun, jettyRunWar, jettyStop]*.stopKey = 'stopKey'
test() {
exclude '**/functional/*.*'
}
task copyStubOkta(type: org.gradle.api.tasks.Copy) {
from('src/test/pages')
into('src/main/webapp/WEB-INF/pages')
}
task deleteStubOKTA(type: Delete) {
delete 'src/main/webapp/WEB-INF/pages/stubOKTA.jsp'
}
task testFunctional(type: Test, dependsOn: test) {
doFirst {
copyStubOkta.execute()
println 'Starting the embedded jetty server'
jettyRun.daemon = true
jettyRun.execute()
}
doLast {
println 'Stopping the embedded jetty server'
jettyStop.execute()
deleteStubOKTA.execute()
}
}<file_sep>/src/main/java/com/thoughtworks/rnr/saml/util/NineFiftyFiveAMClock.java
package com.thoughtworks.rnr.saml.util;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.springframework.stereotype.Component;
/**
* An implementation of Clock for testing purposes
*/
@Component
public class NineFiftyFiveAMClock implements Clock {
private String instant = "2014-05-20T09:56:00.000-05:00";
/**
* @return the instant set by setInstant()
*/
@Override
public String instant() {
return instant;
}
/**
* @return the instant set by setInstant() as a DateTime object
*/
@Override
public DateTime dateTimeNow() {
return ISODateTimeFormat.dateTime().parseDateTime(instant);
}
}
<file_sep>/src/test/java/com/thoughtworks/rnr/saml/MockIdentifier.java
package com.thoughtworks.rnr.saml;
import com.thoughtworks.rnr.saml.util.Identifier;
/**
* Implementation for Identifier used for testing
*/
public class MockIdentifier implements Identifier {
private String id;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
<file_sep>/src/main/java/com/thoughtworks/rnr/controller/SalesForceController.java
package com.thoughtworks.rnr.controller;
import com.thoughtworks.rnr.service.SalesForceService;
import org.apache.commons.httpclient.HttpClient;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
@Controller
public class SalesForceController {
private static final Logger LOGGER = LoggerFactory.getLogger(SalesForceController.class);
private SalesForceService salesForceService;
@Autowired
public SalesForceController(SalesForceService salesForceService) {
this.salesForceService = salesForceService;
}
@RequestMapping(value = "/oauth/_callback", method = RequestMethod.GET)
public String handleSalesForceCallback(HttpServletRequest request, HttpClient client) throws JSONException {
try {
setStartDateInSession(request, client);
} catch (IOException | URISyntaxException e) {
LOGGER.debug("Inside callback GET request from SalesForce: /oauth/_callback");
}
return "redirect:/home";
}
private void setStartDateInSession(HttpServletRequest request, HttpClient client) throws IOException, JSONException, URISyntaxException {
String startDate = salesForceService.fetchStartDate(request, client);
request.getSession().setAttribute("startDate", startDate);
}
}<file_sep>/src/main/java/com/thoughtworks/rnr/controller/HomeController.java
package com.thoughtworks.rnr.controller;
import com.thoughtworks.rnr.model.AccrualRateCalculator;
import com.thoughtworks.rnr.model.Constants;
import com.thoughtworks.rnr.model.Employee;
import com.thoughtworks.rnr.model.PersonalDaysCalculator;
import com.thoughtworks.rnr.service.*;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.util.Map;
@Controller
@RequestMapping("/")
public class HomeController {
private final EmployeeService employeeService;
private final SalesForceParserService salesForceParserService;
private final VacationCalculatorService vacationCalculatorService;
private final AccrualRateCalculator accrualRateCalculator;
private final DateParserService dateParserService;
private final PersonalDaysCalculator personalDaysCalculator;
private SAMLService samlService;
@Autowired
public HomeController(EmployeeService employeeService, SalesForceParserService salesForceParserService,
VacationCalculatorService vacationCalculatorService, AccrualRateCalculator accrualRateCalculator,
DateParserService dateParserService, PersonalDaysCalculator personalDaysCalculator, SAMLService samlService) {
this.employeeService = employeeService;
this.salesForceParserService = salesForceParserService;
this.vacationCalculatorService = vacationCalculatorService;
this.accrualRateCalculator = accrualRateCalculator;
this.dateParserService = dateParserService;
this.personalDaysCalculator = personalDaysCalculator;
this.samlService = samlService;
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public String doesNothing() {
return "home";
}
@RequestMapping(value = "/home", method = RequestMethod.GET)
public ModelAndView displayHome(HttpServletRequest request, ModelMap model) {
HttpSession session = request.getSession();
String startDate = (String) session.getAttribute("startDate");
model.addAttribute("startDate", startDate);
return new ModelAndView("home", "startDateModel", model);
}
@RequestMapping(value = "/", params = {"startDate", "rolloverdays", "accrualRate", "salesForceText", "endDate"}, method = RequestMethod.POST)
public ModelAndView postDate(@RequestParam("startDate") String startDate,
@RequestParam("rolloverdays") String rollover,
@RequestParam("accrualRate") String accrualRate,
@RequestParam("salesForceText") String salesForceText,
@RequestParam("endDate") String endDate) throws IOException, ParseException {
LocalDate convertedStartDate = dateParserService.parse(startDate);
LocalDate convertedEndDate = dateParserService.parse(endDate);
Map<LocalDate, Double> parsedVacationDays = salesForceParserService.extractDatesAndHoursFromSalesForceText(salesForceText, Constants.VACATION_DAY_CODES);
Map<LocalDate, Double> parsedPersonalDays = salesForceParserService.extractDatesAndHoursFromSalesForceText(salesForceText, Constants.PERSONAL_DAY_CODES);
Employee employee = employeeService.createEmployee(convertedStartDate, rollover, parsedVacationDays, parsedPersonalDays, accrualRate);
double vacationDays = vacationCalculatorService.getVacationDays(employee, accrualRateCalculator, convertedEndDate);
double personalDays = personalDaysCalculator.calculatePersonalDays(employee, convertedStartDate, convertedEndDate);
String capReachedMessage = vacationCalculatorService.getVacationCapNotice(employee, accrualRateCalculator, convertedEndDate);
return showVacationDays(vacationDays, personalDays, rollover, accrualRate, salesForceText, startDate, endDate, capReachedMessage);
}
private ModelAndView showVacationDays(Double vacationDays, Double personalDays, String rollover,
String accrualRate, String salesForceText, String startDate,
String endDate, String capReachedMessage) {
ModelMap model = new ModelMap();
model.put("vacationDays", roundToNearestHundredth(vacationDays));
model.put("personalDays", roundToNearestHundredth(personalDays));
model.put("startDate", startDate);
model.put("endDate", endDate);
model.put("rollover", rollover);
model.put("accrualRate", accrualRate);
model.put("salesForceText", salesForceText);
model.put("capReachedMessage", capReachedMessage);
return new ModelAndView("home", "postedValues", model);
}
private Double roundToNearestHundredth(Double number) {
return (double) Math.round(number * 100) / 100;
}
}
<file_sep>/src/main/webapp/test.properties
host=http://localhost:8080/manager/text
redirectUrl=/stubOKTA
timeProvider=com.thoughtworks.rnr.saml.util.NineFiftyFiveAMClock<file_sep>/src/main/java/com/thoughtworks/rnr/saml/Configuration.java
package com.thoughtworks.rnr.saml;
import com.thoughtworks.rnr.saml.util.IPRange;
import com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl;
import org.apache.commons.lang.StringUtils;
import org.opensaml.ws.security.SecurityPolicyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.xml.xpath.*;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.util.*;
/**
* This class is derived from a xml configuration file;
* it is used to provide an application required to generate a SAMLRequest,
* and to validate SAMLResponse.
*/
public class Configuration {
private Map<String, Application> applications;
private String defaultEntityID = null;
private boolean suppressErrors;
private String loginUri;
static XPath XPATH;
private static XPathExpression CONFIGURATION_ROOT_XPATH;
private static XPathExpression APPLICATIONS_XPATH;
private static XPathExpression ENTITY_ID_XPATH;
private static XPathExpression DEFAULT_APP_XPATH;
private static XPathExpression ADDRESSES_XPATH;
private static XPathExpression SP_USERNAMES_XPATH;
private static XPathExpression SP_GROUPS_XPATH;
private static XPathExpression SUPPRESS_ERRORS_XPATH;
private static XPathExpression LOGIN_URI_XPATH;
private IPRange oktaUsersIps;
private IPRange spUsersIps;
private List<String> spUsernames;
private List<String> spGroupnames;
public static final String SAML_RESPONSE_FORM_NAME = "SAMLResponse";
public static final String CONFIGURATION_KEY = "thoughtworks.rnr.config.xml";
public static final String DEFAULT_ENTITY_ID = "thoughtworks.rnr.config.default_entity_id";
public static final String REDIR_PARAM = "os_destination";
public static final String RELAY_STATE_PARAM = "RelayState";
private static final Logger logger = LoggerFactory.getLogger(Configuration.class);
static {
try {
XPathFactory xPathFactory = new XPathFactoryImpl();
XPATH = xPathFactory.newXPath();
XPATH.setNamespaceContext(new MetadataNamespaceContext());
CONFIGURATION_ROOT_XPATH = XPATH.compile("configuration");
APPLICATIONS_XPATH = XPATH.compile("applications/application");
ADDRESSES_XPATH = XPATH.compile("allowedAddresses");
SP_USERNAMES_XPATH = XPATH.compile("spUsers/username");
SP_GROUPS_XPATH = XPATH.compile("spGroups/groupname");
ENTITY_ID_XPATH = XPATH.compile("md:EntityDescriptor/@entityID");
DEFAULT_APP_XPATH = XPATH.compile("default");
SUPPRESS_ERRORS_XPATH = XPATH.compile("suppressErrors");
LOGIN_URI_XPATH = XPATH.compile("loginUri");
} catch (XPathExpressionException e) {
logger.error("Failed to create XPathFactory instance", e);
}
}
public Configuration(String configuration) throws XPathExpressionException, CertificateException, UnsupportedEncodingException, SecurityPolicyException {
InputSource source = new InputSource(new StringReader(configuration));
Node root = (Node) CONFIGURATION_ROOT_XPATH.evaluate(source, XPathConstants.NODE);
NodeList applicationNodes = (NodeList) APPLICATIONS_XPATH.evaluate(root, XPathConstants.NODESET);
// the xpathconstants defines the return type you want to get
defaultEntityID = DEFAULT_APP_XPATH.evaluate(root);
applications = new HashMap<String, Application>();
spUsernames = new ArrayList<String>();
spGroupnames = new ArrayList<String>();
for (int i = 0; i < applicationNodes.getLength(); i++) {
Element applicationNode = (Element) applicationNodes.item(i);
String entityID = ENTITY_ID_XPATH.evaluate(applicationNode);
Application application = new Application(applicationNode);
applications.put(entityID, application);
}
Element allowedAddresses = (Element) ADDRESSES_XPATH.evaluate(root, XPathConstants.NODE);
if (allowedAddresses != null) {
String oktaFrom = (String) XPATH.compile("oktaUsers/ipFrom").evaluate(allowedAddresses, XPathConstants.STRING);
String oktaTo = (String) XPATH.compile("oktaUsers/ipTo").evaluate(allowedAddresses, XPathConstants.STRING);
String spFrom = (String) XPATH.compile("spUsers/ipFrom").evaluate(allowedAddresses, XPathConstants.STRING);
String spTo = (String) XPATH.compile("spUsers/ipTo").evaluate(allowedAddresses, XPathConstants.STRING);
// if (oktaFrom != null) {
// try {
// oktaUsersIps = new IPRange(oktaFrom, oktaTo);
// } catch (NumberFormatException e) {
// logger.error("Invalid IP specified for Okta users addresses: " + e.getMessage());
// }
// }
//
// if (spFrom != null) {
// try {
// spUsersIps = new IPRange(spFrom, spTo);
// } catch (NumberFormatException e) {
// logger.error("Invalid IP specified for Service Provider users addresses: " + e.getMessage());
// }
// }
}
String suppress = SUPPRESS_ERRORS_XPATH.evaluate(root);
if (suppress != null) {
suppress = suppress.trim();
}
suppressErrors = (!StringUtils.isBlank(suppress)) ? Boolean.parseBoolean(suppress) : true;
loginUri = LOGIN_URI_XPATH.evaluate(root);
if (loginUri != null) {
loginUri = loginUri.trim();
}
NodeList spUnames = (NodeList) SP_USERNAMES_XPATH.evaluate(root, XPathConstants.NODESET);
if (spUnames != null) {
for (int i = 0; i < spUnames.getLength(); i++) {
Element usernameNode = (Element) spUnames.item(i);
if (!StringUtils.isBlank(usernameNode.getTextContent())) {
spUsernames.add(usernameNode.getTextContent().trim());
}
}
}
NodeList spGnames = (NodeList) SP_GROUPS_XPATH.evaluate(root, XPathConstants.NODESET);
if (spGnames != null) {
for (int i = 0; i < spGnames.getLength(); i++) {
Element groupnameNode = (Element) spGnames.item(i);
if (!StringUtils.isBlank(groupnameNode.getTextContent())) {
spGroupnames.add(groupnameNode.getTextContent().trim());
}
}
}
}
/**
* @return the map of all the applications listed in the config file,
* where the entityID of the application's EntityDescriptor is the key
* and its representation in Application object is the value
*/
public Map<String, Application> getApplications() {
return applications;
}
/**
* @param entityID an identifier for an EntityDescriptor
* @return an Application whose EntityDescriptor entityID matches the given entityID
*/
public Application getApplication(String entityID) {
return applications.get(entityID);
}
/**
* @return the Application whose EntityDescriptor entityID matches the default entityID
*/
public Application getDefaultApplication() {
if (StringUtils.isBlank(defaultEntityID)) {
return null;
}
return applications.get(defaultEntityID);
}
/**
* @return the default entityID from the configuration, which in configured under default
*/
public String getDefaultEntityID() {
return defaultEntityID;
}
/**
* Is ip allowed for identity provider users (Okta)
*/
public boolean isIpAllowedForOkta(String ip) {
try {
boolean isRejectedForOkta = oktaUsersIps != null && !oktaUsersIps.isAddressInRange(ip);
boolean isRejectedForSP = spUsersIps != null && !spUsersIps.isAddressInRange(ip);
//making it more explicit
if ((isRejectedForOkta && isRejectedForSP) ||
(!isRejectedForOkta && !isRejectedForSP) ||
(oktaUsersIps == null && isRejectedForSP) ||
(spUsersIps == null && oktaUsersIps == null)) {
return true;
}
if ((oktaUsersIps == null && !isRejectedForSP) ||
(isRejectedForOkta && !isRejectedForSP)) {
return false;
}
} catch (Exception e) {
logger.error(e.getClass().getSimpleName() + ": " + e.getMessage());
//something is wrong with configuration, logging this and falling back to default behaviour
return true;
}
return true;
}
/**
* Is username allowed for identity provider users (Okta)
*/
public boolean isUsernameAllowedForOkta(String username) {
if (StringUtils.isBlank(username)) {
return true;
}
return !spUsernames.contains(username);
}
public boolean isInSPGroups(Collection<String> userGroups) {
if (userGroups == null || userGroups.isEmpty() || spGroupnames.isEmpty()) {
return false;
}
for (String atlGroup: spGroupnames) {
for (String userGroup : userGroups) {
if (userGroup.trim().equalsIgnoreCase(atlGroup.trim())) {
return true;
}
}
}
return false;
}
public boolean isSPUsernamesUsed() {
return !spUsernames.isEmpty();
}
public boolean isSPGroupnamesUsed() {
return !spGroupnames.isEmpty();
}
/**
* Is ip allowed for service provider users
*/
public boolean isIpAllowedForSP(String ip) {
return !isIpAllowedForOkta(ip);
}
public boolean suppressingErrors() {
return suppressErrors;
}
public String getLoginUri() {
return loginUri;
}
}<file_sep>/src/test/java/com/thoughtworks/rnr/factory/JSONObjectFactoryTest.java
package com.thoughtworks.rnr.factory;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import java.io.InputStream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class JSONObjectFactoryTest {
private JSONObjectFactory jsonObjectFactory;
@Mock
HttpResponse mockHttpResponse;
@Mock
HttpEntity mockHttpEntity;
@Before
public void setUp() throws Exception {
jsonObjectFactory = new JSONObjectFactory();
initMocks(this);
}
@Test
public void httpResponseToJSONObject_shouldReturnJSONObject() throws Exception {
InputStream stubInputStream = IOUtils.toInputStream("{data: some test data for my input stream}");
when(mockHttpResponse.getEntity()).thenReturn(mockHttpEntity);
when(mockHttpEntity.getContent()).thenReturn((stubInputStream));
JSONObject object = jsonObjectFactory.httpResponseToJSONObject(mockHttpResponse);
assertThat(object, instanceOf(JSONObject.class));
}
}
|
4d98d7c72ebb436512ab76a43eb9162923da9019
|
[
"Markdown",
"Java",
"INI",
"Gradle"
] | 19 |
Java
|
asifrc/rnr2
|
5387225020e66fcb52bf69fec6c0111635ce4b0b
|
f52c509872efaba450b135f3076b6d799a5813dd
|
refs/heads/master
|
<repo_name>LuisaFerCo/TestingBDD<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/questions/Prices.java
package co.com.webapps.screenplay.questions;
import co.com.webapps.screenplay.userinterfaces.ShoppingCartPage;
import co.com.webapps.screenplay.utils.StringManager;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Question;
import net.serenitybdd.screenplay.questions.Text;
import java.util.List;
import java.util.stream.Collectors;
public class Prices implements Question<List<Integer>> {
@Override
public List<Integer> answeredBy(Actor actor) {
return Text.of(ShoppingCartPage.PRICE_ITEMS_SHOPPING_LIST).viewedBy(actor).resolveAll()
.stream().map(StringManager::priceToInteger).collect(Collectors.toList());
}
public static Prices ofArticles(){
return new Prices();
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/exceptions/DriverFailException.java
package co.com.webapps.screenplay.exceptions;
import net.serenitybdd.core.exceptions.CausesCompromisedTestFailure;
import net.serenitybdd.core.exceptions.SerenityManagedException;
public class DriverFailException extends SerenityManagedException implements CausesCompromisedTestFailure {
public static final String FAILED_CONNECTION_DRIVER = "Failed the driver's connection";
public DriverFailException(String message, Throwable cause) {
super(message, cause);
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/exceptions/IncorrectPriceException.java
package co.com.webapps.screenplay.exceptions;
public class IncorrectPriceException extends AssertionError {
public IncorrectPriceException(String detailMessage) {
super(detailMessage);
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/tasks/smart/GotoOnline.java
package co.com.webapps.screenplay.tasks.smart;
import co.com.webapps.screenplay.userinterfaces.smart.SmartPage;
import net.serenitybdd.core.steps.Instrumented;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
import net.serenitybdd.screenplay.matchers.WebElementStateMatchers;
import net.serenitybdd.screenplay.waits.WaitUntil;
public class GotoOnline implements Task {
@Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(Click.on(SmartPage.ONLINE_STORE_OPTION)
, WaitUntil.the(SmartPage.GO_TO_CART, WebElementStateMatchers.isClickable())
,Click.on(SmartPage.GO_TO_CART));
}
public static GotoOnline storeToCart(){
return Instrumented.instanceOf(GotoOnline.class).newInstance();
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/interactions/sums/PriceOfSmartPlan.java
package co.com.webapps.screenplay.interactions.sums;
import co.com.webapps.screenplay.integration.TextPlainFile;
import co.com.webapps.screenplay.utils.PathManager;
import net.serenitybdd.markers.IsSilent;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Interaction;
import static co.com.webapps.screenplay.utils.StringManager.priceToInteger;
public class PriceOfSmartPlan implements Interaction, IsSilent {
@Override
public <T extends Actor> void performAs(T actor) {
String price ="0";
try{
price = actor.recall("subtotal");
}catch (Exception e){
price = "0";
}
TextPlainFile.getInstance(PathManager.FILE_PRICE_SHOPPING_SMART)
.writeFile(String.valueOf(priceToInteger(price)));
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/userinterfaces/smart/SmartPage.java
package co.com.webapps.screenplay.userinterfaces.smart;
import net.serenitybdd.screenplay.targets.Target;
public class SmartPage {
public static final Target ONLINE_STORE_OPTION = Target.the("Enter to online store")
.locatedBy("//nav//li[contains(@id,'menu-item-94510')]/a[contains(text(),'Tienda Virtual')]");
public static final Target GO_TO_CART = Target.the("Go to shopping cart")
.locatedBy("//nav//li[contains(@id,'menu-item-94510')]//ul[@class='sub-menu']//span[contains(text(),'Carrito de Compras')]");
public static final Target TITLE_PLANS = Target.the("Plans to add to cart")
.locatedBy("//h1[contains(text(),'Programas presenciales en nuestras sedes')]");
public static final Target SELECT_PLAN = Target.the("Select plan ")
.locatedBy("//h2[contains(text(),'{0}')]");
public static final Target ADD_TO_CART_BUTTON = Target.the("Add to cart")
.locatedBy("//button[@name='add-to-cart']");
public SmartPage() {
super();
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/utils/enums/app/CategoryAppStore.java
package co.com.webapps.screenplay.utils.enums.app;
public enum CategoryAppStore {
MOBILE_CATEGORY("Celulares");
private String category;
CategoryAppStore(String category) {
this.category = category;
}
public String getType() {
return category;
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/questions/TextOf.java
package co.com.webapps.screenplay.questions;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Question;
import net.serenitybdd.screenplay.questions.Text;
import net.serenitybdd.screenplay.targets.Target;
public class TextOf implements Question<String> {
private final Target target;
public TextOf(Target target) {
this.target = target;
}
@Override
public String answeredBy(Actor actor) {
return Text.of(target).viewedBy(actor).resolve();
}
public static TextOf target(Target tr){
return new TextOf(tr);
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/interactions/builders/GoTo.java
package co.com.webapps.screenplay.interactions.builders;
import co.com.webapps.screenplay.interactions.Cart;
import co.com.webapps.screenplay.interactions.NavigatePage;
import co.com.webapps.screenplay.utils.enums.PagesEnum;
import net.serenitybdd.core.steps.Instrumented;
public class GoTo {
public static NavigatePage Page(PagesEnum page){
return Instrumented.instanceOf(NavigatePage.class).withProperties(page);
}
public static Cart shoppingCart(){
return Instrumented.instanceOf(Cart.class).newInstance();
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/tasks/Add.java
package co.com.webapps.screenplay.tasks;
import co.com.webapps.screenplay.interactions.AddToCart;
import co.com.webapps.screenplay.interactions.ScrollBy;
import co.com.webapps.screenplay.userinterfaces.DetailsArticlePage;
import co.com.webapps.screenplay.userinterfaces.InitPage;
import net.serenitybdd.core.steps.Instrumented;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.RememberThat;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
import net.serenitybdd.screenplay.conditions.Check;
import net.serenitybdd.screenplay.questions.Text;
import net.serenitybdd.screenplay.waits.WaitUntil;
import net.thucydides.core.annotations.Step;
import static co.com.webapps.screenplay.utils.StringManager.*;
import static net.serenitybdd.screenplay.matchers.WebElementStateMatchers.isEnabled;
public class Add implements Task {
private String articleName;
private String quantity;
public Add(String articleName) {
this.articleName = articleName;
this.quantity = "1";
}
@Override
@Step("{0} select #articleName then select #quantity articles and finally add to cart")
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(ScrollBy.aBit(),
RememberThat.theValueOf(ARTICLE_FOUND).is(NO));
while(actor.recall(ARTICLE_FOUND).equals(false)) {
actor.attemptsTo(ScrollBy.aBit()
,Check.whether(!Text.of(InitPage.ARTICLE.of(articleName)).viewedBy(actor).resolveAll().isEmpty())
.andIfSo(Click.on(InitPage.ARTICLE.of(articleName))
,WaitUntil.the(DetailsArticlePage.LIST_DROPDOWN_PRODUCT_QUANTITY, isEnabled())
.forNoMoreThan(5).seconds()
,AddToCart.quantity(quantity)
,RememberThat.theValueOf(ARTICLE_FOUND).is(YES))
.otherwise(ScrollBy.aBit(),ScrollBy.aBit()));
}
/* actor.attemptsTo(ScrollBy.aBit(), ScrollBy.aBit()
//Scroll.to(InitPage.LIST_GROUP_FILTER_SEARCH).andAlignToTop()
, WaitUntil.the(InitPage.ARTICLE.of(articleName), WebElementStateMatchers.isEnabled())
.forNoMoreThan(8).seconds()
, Scroll.to(InitPage.ARTICLE.of(articleName)).andAlignToBottom()
, Click.on(InitPage.ARTICLE.of(articleName))
, WaitUntil.the(DetailsArticlePage.LIST_DROPDOWN_PRODUCT_QUANTITY, WebElementStateMatchers.isEnabled())
.forNoMoreThan(5).seconds()
, AddToCart.quantity(quantity)
);
*/
}
public static Add article(String name){
return Instrumented.instanceOf(Add.class).withProperties(name);
}
public Add withProductQuantity(String quantity){
this.quantity = quantity;
return this;
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/questions/SubTotal.java
package co.com.webapps.screenplay.questions;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Question;
import java.util.Collection;
import java.util.List;
import java.util.stream.IntStream;
public class SubTotal implements Question<Integer> {
private final Question<? extends Collection<Integer>> listQuestion;
public SubTotal(Question<? extends Collection<Integer>> listQuestion) {
this.listQuestion = listQuestion;
}
@Override
public Integer answeredBy(Actor actor) {
List<Integer> pricesList= (List<Integer>) listQuestion.answeredBy(actor);
List<Integer> quantityList = actor.asksFor(Quantities.ofEachArticles());
return IntStream.range(0,Math.min(pricesList.size(), 1))
.map(i-> pricesList.get(i)*quantityList.get(i))
.sum();
}
public static SubTotal ofShopping(Question<? extends Collection<Integer>> listQuestion){
return new SubTotal(listQuestion);
}
}
<file_sep>/WebScreenplay/settings.gradle
rootProject.name = 'WebScreenplay'
<file_sep>/WebScreenplay/src/test/java/co/com/webapps/screenplay/stepdefinitions/linio/AddToCartStepDefinition.java
package co.com.webapps.screenplay.stepdefinitions.linio;
import co.com.webapps.screenplay.interactions.AddToCart;
import co.com.webapps.screenplay.interactions.OpenCategories;
import co.com.webapps.screenplay.interactions.ScrollBy;
import co.com.webapps.screenplay.interactions.builders.GoTo;
import co.com.webapps.screenplay.interactions.sums.Save;
import co.com.webapps.screenplay.models.Article;
import co.com.webapps.screenplay.questions.ListOfProducts;
import co.com.webapps.screenplay.questions.Prices;
import co.com.webapps.screenplay.questions.SubTotal;
import co.com.webapps.screenplay.questions.TextOf;
import co.com.webapps.screenplay.tasks.Add;
import co.com.webapps.screenplay.tasks.Adds;
import co.com.webapps.screenplay.tasks.Clean;
import co.com.webapps.screenplay.tasks.filters.builder.Filters;
import co.com.webapps.screenplay.userinterfaces.DetailsArticlePage;
import co.com.webapps.screenplay.userinterfaces.InitPage;
import co.com.webapps.screenplay.userinterfaces.ShoppingCartPage;
import co.com.webapps.screenplay.utils.enums.CategoriesEnum;
import co.com.webapps.screenplay.utils.enums.SectionsEnum;
import co.com.webapps.screenplay.utils.smart.DataDriven;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import net.serenitybdd.screenplay.RememberThat;
import net.serenitybdd.screenplay.actions.Click;
import net.serenitybdd.screenplay.actors.OnStage;
import net.serenitybdd.screenplay.actors.OnlineCast;
import net.serenitybdd.screenplay.questions.targets.TheTarget;
import org.hamcrest.Matchers;
import java.util.List;
import java.util.Map;
import static co.com.webapps.screenplay.utils.StringManager.FIRST;
import static co.com.webapps.screenplay.utils.StringManager.priceToInteger;
import static co.com.webapps.screenplay.utils.enums.CategoriesEnum.CONSOLES_AND_VIDEO_GAMES;
import static co.com.webapps.screenplay.utils.enums.PagesEnum.LINIO_PAGE;
import static co.com.webapps.screenplay.utils.enums.TypeSort.LOWER_PRICE;
import static net.serenitybdd.screenplay.GivenWhenThen.seeThat;
import static net.serenitybdd.screenplay.actors.OnStage.theActorInTheSpotlight;
import static org.hamcrest.Matchers.*;
public class AddToCartStepDefinition {
@Before
public void setTheStage() {
OnStage.setTheStage(new OnlineCast());
}
@Given("(.*) enters to at the Linio web store")
public void tinaEntersToAtTheLinioWebStore(String name) {
OnStage.theActor(name).attemptsTo(GoTo.Page(LINIO_PAGE));
}
@When("she add products from consoles and video games category")
public void sheSearchProductFromConsolesAndVideoGamesCategory() {
theActorInTheSpotlight().attemptsTo(Adds.articles(DataDriven.getListArticles())
.fromCategory(CONSOLES_AND_VIDEO_GAMES)
,GoTo.shoppingCart());
}
@Then("she should see all products on shopping cart")
public void sheShouldSeeAllProductsOnShoppingCart() {
List<String> selectedProductsList = theActorInTheSpotlight().recall("listOfProducts");
selectedProductsList.forEach(product-> theActorInTheSpotlight().should(seeThat(ListOfProducts.inShoppingCart(),
(hasItem(containsString(product))))));
}
@When("she adds the products from sport category into Motorsports section")
public void sheLooksForTheTulaMotoImpermeableDryBagFromSportCategoryIntoMotorsportsSection(List<Article> listArticles) {
theActorInTheSpotlight().attemptsTo(
OpenCategories.onCategory(CategoriesEnum.SPORTS).andSection(SectionsEnum.MOTORSPORTS)
, Add.article(listArticles.get(0).getName()).withProductQuantity(listArticles.get(0).getQuantity())
, Click.on(DetailsArticlePage.GO_TO_CART)
, RememberThat.theValueOf("subtotal").isAnsweredBy(TextOf.target(ShoppingCartPage.SUBTOTAL_PRICE)));
}
@Then("she should see total price of the 5 articles on the shopping cart")
public void sheShouldSeeTotalPriceOfTheArticlesOnTheShoppingCart() {
theActorInTheSpotlight().should(seeThat(SubTotal.ofShopping(Prices.ofArticles()),
equalTo(priceToInteger(theActorInTheSpotlight().recall("subtotal")))));
theActorInTheSpotlight().attemptsTo(Save.priceLinioShopping());
}
@When("she search products from Fashion section")
public void sheSearchProductsFromFashionSection() {
theActorInTheSpotlight().attemptsTo(OpenCategories.onCategory(CategoriesEnum.FASHION));
}
@When("she search by following propertie")
public void sheSearchByFollowingProperties(List<Map<String, String>> properties) {
theActorInTheSpotlight().attemptsTo(Filters.byBrand(properties.get(0).get("brand"))
,Filters.byColor(properties.get(0).get("color"))
,Filters.byPriceFrom(properties.get(0).get("priceRangeFrom"))
.to(properties.get(0).get("priceRangeTo"))
,Filters.byShipment(properties.get(0).get("shipment")));
}
@When("she searches (.*) brand")
public void sheSearchesAdidasBrand(String brand) {
theActorInTheSpotlight().attemptsTo(Filters.byBrand(brand));
}
@When("she searches by (.*) color")
public void sheSearchesByWhiteColor(String color) {
theActorInTheSpotlight().attemptsTo(Filters.byColor(color));
}
@When("she reduces price range from (.*) to (.*)")
public void sheReducesPriceRangeFromTo(String minPrice, String maxPrice) {
theActorInTheSpotlight().attemptsTo(Filters
.byPriceFrom(minPrice)
.to(maxPrice));
}
@When("she chooses the shipment as (.*)")
public void sheChoosesTheShipmentAsNacional(String shipment) {
theActorInTheSpotlight().attemptsTo(Filters.byShipment(shipment));
}
@When("she sorts for lower price")
public void sheSortsForLowerPrice() {
theActorInTheSpotlight().attemptsTo(Filters.sortBy(LOWER_PRICE));
}
@When("Tina adds to shopping cart the first product found")
public void tinaAddsToShoppingCartTheFirstProductOfTheSearching() {
theActorInTheSpotlight().attemptsTo(ScrollBy.aBit()
,Click.on(InitPage.CATALOG_ROW_PRODUCT.of(FIRST))
,AddToCart.quantity(FIRST)
,Click.on(DetailsArticlePage.GO_TO_CART));
}
@Then("she should see the product to shopping cart")
public void sheShouldSeeTheProductToShoppingCart() {
theActorInTheSpotlight().should(seeThat(ListOfProducts.inShoppingCart(), Matchers.hasSize(1)));
}
@Given("Tina add several products to shopping cart")
public void tinaAddSeveralProductsToShoppingCart(List<Article> listArticles) {
theActorInTheSpotlight().attemptsTo(Adds.articles(listArticles).fromCategory(CONSOLES_AND_VIDEO_GAMES)
,GoTo.shoppingCart());
}
@Given("she decides remove all products of the shopping cart")
public void sheDecidesRemoveAllProductsOfTheShoppingCart() {
theActorInTheSpotlight().attemptsTo(Clean.allShoppingCart());
}
@Then("she should not see any products in to list")
public void sheShouldNotSeeAnyProductsInToList() {
theActorInTheSpotlight().should(seeThat(TheTarget.textOf(ShoppingCartPage.EMPTY_CART_SHOPPING_MESSAGE),
Matchers.equalToIgnoringCase("NO TIENES PRODUCTOS EN TU CARRITO")));
}
@After()
public void tearDown() {
OnStage.drawTheCurtain();
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/userinterfaces/calculator/CalculatorPage.java
package co.com.webapps.screenplay.userinterfaces.calculator;
import net.serenitybdd.screenplay.targets.Target;
public class CalculatorPage {
public static final Target NUMBER_BUTTON = Target.the("button {0}")
.locatedBy("//*[@AutomationId='num{0}Button']");
public static final Target ADD_BUTTON = Target.the("add button")
.locatedBy("//*[@AutomationId='plusButton']");
public static final Target TOTAL_BUTTON = Target.the("equal button")
.locatedBy("//*[@AutomationId='equalButton']");
public static final Target RESULT = Target.the("result")
.locatedBy("//*[@AutomationId='CalculatorResults']");
public CalculatorPage() {
super();
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/tasks/filters/Sort.java
package co.com.webapps.screenplay.tasks.filters;
import co.com.webapps.screenplay.userinterfaces.FilterSectionPage;
import co.com.webapps.screenplay.utils.enums.TypeSort;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
import net.serenitybdd.screenplay.matchers.WebElementStateMatchers;
import net.serenitybdd.screenplay.waits.WaitUntil;
public class Sort implements Task {
private TypeSort typeSort;
public Sort(TypeSort typeSort) {
this.typeSort = typeSort;
}
@Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(
WaitUntil.the(FilterSectionPage.SORT_FILTER, WebElementStateMatchers.isClickable()),
Click.on(FilterSectionPage.SORT_FILTER)
,Click.on(FilterSectionPage.SORT_TYPE.of(typeSort.getType())));
}
}
<file_sep>/WebScreenplay/serenity.properties
webdriver.driver=chrome
webdriver.ie.driver=src/test/resources/webdriver/IEDriverServer.exe
webdriver.chrome.driver =src/test/resources/webdriver/chromedriver.exe
serenity.use.unique.browser = false
serenity.restart.browser.for.each = NEVER
serenity.dry.run=false
serenity.logging = VERBOSE
serenity.project.name = WebScreenplay
serenity.take.screenshots = FOR_FAILURES
serenity.reports.show.step.details = true
serenity.timeout = 10000
webdriver.wait.for.timeout = 16000
webdriver.timeouts.implicitlywait = 16000
story.timeout.in.secs = 3000
chrome.switches = --lang=es,--start-maximized,
appium.browserName = chrome<file_sep>/WebScreenplay/src/test/java/co/com/webapps/screenplay/runners/restservice/RestGetDataTypeCode.java
package co.com.webapps.screenplay.runners.restservice;
import cucumber.api.CucumberOptions;
import cucumber.api.SnippetType;
import net.serenitybdd.cucumber.CucumberWithSerenity;
import org.junit.runner.RunWith;
@RunWith(CucumberWithSerenity.class)
@CucumberOptions(features = "src/test/resources/features/restservice/rest_get_data_typecode.feature"
, glue = "co.com.webapps.screenplay.stepdefinitions"
, snippets = SnippetType.CAMELCASE
)
public class RestGetDataTypeCode {
}
<file_sep>/WebScreenplay/mobile/configmobile.properties
serenity.timeout = 50000
serenity.restart.browser.for.each = NEVER
webdriver.driver = appium
appium.hub = https://api.kobiton.com/wd/hub
appium.username = jaryauto
appium.accessKey = 7b06c438-aed2-4b29-a4ca-e2f07f4142d7
appium.sessionName = Automation test session
appium.deviceOrientation = portrait
appium.captureScreenshots = true
appium.deviceGroup = KOBITON
appium.noReset = true
appium.newCommandTimeout = 1000
appium.autoGrantPermissions = true
appium.platformName = ANDROID
appium.platformVersion = 6.0.1
appium.deviceName = Galaxy C5
appium.app=kobiton-store:22926
appium.appPackage = com.todo1.bc.proyecto7
appium.appActivity = com.todo1.mobile.ui.contenido.splash
appium.automationName=uiautomator2
appium.browserName = chrome<file_sep>/README.md
# Introduction
Testing project using Screenplay pattern is executing using WebDriver Chrome, IE explorer, and it has also some api and desktop test
# Requerements
+ Java JDK 1.8 y Gradle using version 4.7.
It will be specifying the requirements for each testing types:
## Web
The pages that are using there are Linio Shopping Online and Smart Academy. The drivers they are set on path
´resources/webdriver´
The feature files was creating they have test scenarios.
Linio are executing using Chrome Driver. Setting by default from serenit.properties file
Smart are executing using IE Explorer, Setting throw @driver tag to run it with IExplorer driver
## Rest
The rest Services Users and Countries are exposed to <https://jsonplaceholder.typicode.com/users > and <https://restcountries.eu/rest/v2/name/united>
## Desktop
Calculator App using WinAppDriver that must have run it from local computer
# Run
To compile
```
gradle clean build -x test
```
# Contribute
TODO: <NAME>
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/questions/Quantities.java
package co.com.webapps.screenplay.questions;
import co.com.webapps.screenplay.userinterfaces.ShoppingCartPage;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Question;
import net.serenitybdd.screenplay.questions.Text;
import java.util.List;
import java.util.stream.Collectors;
public class Quantities implements Question<List<Integer>> {
@Override
public List<Integer> answeredBy(Actor actor) {
return Text.of(ShoppingCartPage.QUANTITY_ITEMS_SHOPPING_LIST).viewedBy(actor).resolveAll()
.stream().map(Integer::parseInt).collect(Collectors.toList());
}
public static Quantities ofEachArticles(){
return new Quantities();
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/questions/smart/SeePay.java
package co.com.webapps.screenplay.questions.smart;
import co.com.webapps.screenplay.questions.TextOf;
import co.com.webapps.screenplay.userinterfaces.smart.PayProccessPage;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Question;
import net.serenitybdd.screenplay.abilities.BrowseTheWeb;
import net.serenitybdd.screenplay.matchers.WebElementStateMatchers;
import net.serenitybdd.screenplay.waits.WaitUntil;
import org.hamcrest.Matchers;
import static net.serenitybdd.screenplay.EventualConsequence.eventually;
import static net.serenitybdd.screenplay.GivenWhenThen.seeThat;
public class SeePay implements Question<String> {
@Override
public String answeredBy(Actor actor) {
actor.attemptsTo(WaitUntil.the(PayProccessPage.TITLE_SUMMARY_PAY, WebElementStateMatchers.isPresent()));
actor.should(eventually(seeThat(TextOf.target(PayProccessPage.TITLE_SUMMARY_PAY)
,Matchers.containsString("Resumen de la compra")).because("Espera que la plataforma lo lleve al proceso de pago")));
return BrowseTheWeb.as(actor).getTitle();
}
public static SeePay UPlatform(){
return new SeePay();
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/utils/smart/DataDriven.java
package co.com.webapps.screenplay.utils.smart;
import co.com.webapps.screenplay.integration.CsvFiles;
import co.com.webapps.screenplay.models.Article;
import co.com.webapps.screenplay.models.ArticleBuilder;
import co.com.webapps.screenplay.models.smart.DataBilling;
import co.com.webapps.screenplay.models.smart.DataBillingBuilder;
import co.com.webapps.screenplay.utils.PathManager;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class DataDriven {
public static DataBilling getDataBilling(){
return DataBillingBuilder.getInstance(CsvFiles.inPath(PathManager.FILE_DATA_BILLING_SMART).getData()
.get(0)).build();
}
public static List<Article> getListArticles(){
List<Map<String,String>> list = CsvFiles.inPath(PathManager.FILE_DATA_LIST_ARTICLES).getData();
return list.stream().map(element->ArticleBuilder.getInstance(element).build())
.collect(Collectors.toList());
}
public DataDriven() {
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/utils/PathManager.java
package co.com.webapps.screenplay.utils;
public class PathManager {
public static final String FILE_DATA_BILLING_SMART = "src/test/resources/datadriven/smart/data.csv";
public static final String FILE_DATA_LIST_ARTICLES = "src/test/resources/datadriven/linio/list_articles.csv";
public static final String FILE_RESPONSE_DATA_REST = "src/test/resources/datadriven/restservice/response_users.txt";
public static final String FILE_RESPONSE_COUNTRIES = "src/test/resources/datadriven/restservice/response_countries.xlsx";
public static final String FILE_PRICE_SHOPPING = "src/test/resources/datadriven/sums/shopping_linio.txt";
public static final String FILE_PRICE_SHOPPING_SMART = "src/test/resources/datadriven/sums/shopping_smart.txt";
public PathManager() {
super();
}}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/utils/restservice/UsersServiceFile.java
package co.com.webapps.screenplay.utils.restservice;
import co.com.webapps.screenplay.exceptions.NotFoundFileException;
import co.com.webapps.screenplay.models.restservice.users.DataUser;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.List;
public class UsersServiceFile {
private List<DataUser> dataUserList;
private String path;
public UsersServiceFile(String path) {
this.path = path;
}
public UsersServiceFile theData(List<DataUser> dataUserList){
this.dataUserList = dataUserList;
writeFile();
return this;
}
public void writeFile() {
try {
FileWriter fileWriter = new FileWriter(path);
PrintWriter printWriter = new PrintWriter(fileWriter);
for (DataUser dataUser : dataUserList) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(dataUser.getId()+";");
stringBuilder.append(dataUser.getUsername()+";");
stringBuilder.append(dataUser.getEmail()+";");
stringBuilder.append(dataUser.getAddress().getCity());
printWriter.printf(stringBuilder.toString());
printWriter.println();
}
printWriter.close();
} catch (IOException e) {
throw new NotFoundFileException("No s encontro el archivo "+path, e);
}
}
private String headers(){
Method[] methods = DataUser.class.getDeclaredMethods();
String headers = "";
StringBuilder stringBuilder = null;
for(Method method: methods){
Parameter[] parameters = method.getParameters();
for (Parameter p:parameters){
if(p.isNamePresent()){
stringBuilder = new StringBuilder();
stringBuilder.append(p.getName()+";");
}
headers = stringBuilder.toString();
}
}
return headers;
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/utils/enums/TypeSort.java
package co.com.webapps.screenplay.utils.enums;
public enum TypeSort {
LOWER_PRICE("Menor precio");
private String type;
TypeSort(String type) {
this.type = type;
}
public String getType() {
return type;
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/tasks/smart/AddPlan.java
package co.com.webapps.screenplay.tasks.smart;
import co.com.webapps.screenplay.userinterfaces.smart.SmartPage;
import co.com.webapps.screenplay.utils.enums.smart.PlansEnum;
import net.serenitybdd.core.steps.Instrumented;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
public class AddPlan implements Task {
public PlansEnum plansEnum;
public AddPlan(PlansEnum plansEnum) {
this.plansEnum = plansEnum;
}
@Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(ChooseAPlan.named(plansEnum)
, Click.on(SmartPage.ADD_TO_CART_BUTTON));
}
public static AddPlan toCart(PlansEnum plansEnum){
return Instrumented.instanceOf(AddPlan.class).withProperties(plansEnum);
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/tasks/filters/Color.java
package co.com.webapps.screenplay.tasks.filters;
import co.com.webapps.screenplay.userinterfaces.FilterSectionPage;
import co.com.webapps.screenplay.userinterfaces.InitPage;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
import net.serenitybdd.screenplay.actions.Scroll;
import net.thucydides.core.annotations.Step;
public class Color implements Task {
private String colorName;
public Color(String colorName) {
this.colorName = colorName;
}
@Override
@Step("{0} filter by color #colorName")
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(Scroll.to(InitPage.TITLE_CATEGORY).andAlignToTop()
,Click.on(FilterSectionPage.FILTER_COLOR)
,Scroll.to(InitPage.TITLE_CATEGORY).andAlignToTop()
);
actor.attemptsTo(Click.on(FilterSectionPage.OPTION_COLOR.of(colorName)));
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/tasks/calculator/Sum.java
package co.com.webapps.screenplay.tasks.calculator;
import co.com.webapps.screenplay.userinterfaces.calculator.CalculatorPage;
import net.serenitybdd.core.steps.Instrumented;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Sum implements Task {
private List<String> listNumbers;
public Sum(List<String> listNumbers) {
this.listNumbers = listNumbers;
}
@Override
public <T extends Actor> void performAs(T actor) {
Iterator<String> numbers = listNumbers.iterator();
while (numbers.hasNext()){
String price = numbers.next();
for(char digit:price.toCharArray()){
actor.attemptsTo( Click.on(CalculatorPage.NUMBER_BUTTON.of(String.valueOf(digit))));
}
if(numbers.hasNext()){
actor.attemptsTo( Click.on(CalculatorPage.ADD_BUTTON));
}
}
actor.attemptsTo( Click.on(CalculatorPage.TOTAL_BUTTON));
}
public static Sum ofPrices(String... prices){
return Instrumented.instanceOf(Sum.class).withProperties(Arrays.asList(prices));
}
public static Sum ofPrices(List<String> prices){
return Instrumented.instanceOf(Sum.class).withProperties(prices);
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/questions/restservice/Responses.java
package co.com.webapps.screenplay.questions.restservice;
public class Responses {
public static DataUsers serviceOfDataUsers(){
return new DataUsers();
}
public static TheCountries ofServiceDataCountries(){
return new TheCountries();
}
public Responses() {
super();
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/tasks/SearchBy.java
package co.com.webapps.screenplay.tasks;
public class SearchBy {
}
<file_sep>/WebScreenplay/build.gradle
tasks.withType(JavaCompile) {
options.encoding = "ISO-8859-1"
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'net.serenity-bdd.aggregator'
compileJava.options.encoding = 'ISO-8859-1'
group 'co.com.webapps'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
buildscript {
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath("net.serenity-bdd:serenity-gradle-plugin:2.0.82")
}
}
ext {
serenityVersion = '2.1.8'
serenityCucumberVersion = '1.9.48'
}
dependencies {
compile "net.serenity-bdd:serenity-core:$rootProject.ext.serenityVersion"
compile "net.serenity-bdd:serenity-junit:$rootProject.ext.serenityVersion"
compile "net.serenity-bdd:serenity-cucumber:$rootProject.ext.serenityCucumberVersion"
compile "net.serenity-bdd:serenity-screenplay:$rootProject.ext.serenityVersion"
implementation "net.serenity-bdd:serenity-screenplay-rest:$rootProject.ext.serenityVersion"
implementation "io.appium:java-client:6.0.0"
implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
implementation group: 'org.apache.poi', name: 'poi', version: '4.1.2'
implementation group: 'org.apache.poi', name: 'poi-ooxml', version: '4.1.2'
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.10.5'
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.6.1'
compile group: 'org.apache.maven.plugins', name: 'maven-dependency-plugin', version: '3.1.2'
compileOnly 'org.projectlombok:lombok:1.18.20'
annotationProcessor 'org.projectlombok:lombok:1.18.20'
testCompileOnly 'org.projectlombok:lombok:1.18.20'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.20'
testImplementation 'junit:junit:4.13'
testImplementation 'org.assertj:assertj-core:3.9.1'
testImplementation 'org.slf4j:slf4j-simple:1.7.7'
}
gradle.startParameter.continueOnFailure = true<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/tasks/filters/Price.java
package co.com.webapps.screenplay.tasks.filters;
import co.com.webapps.screenplay.userinterfaces.FilterSectionPage;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
import net.serenitybdd.screenplay.actions.Enter;
public class Price implements Task {
private String min;
private String max;
public Price(String min) {
this.min = min;
}
@Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(Click.on(FilterSectionPage.FILTER_PRICE)
, Enter.theValue(min).into(FilterSectionPage.PRICE_MIN)
, Enter.theValue(max).into(FilterSectionPage.PRICE_MAX)
,Click.on(FilterSectionPage.ESTABLISH_PRICES)
);
}
public Price to(String max){
this.max = max;
return this;
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/models/smart/DataBilling.java
package co.com.webapps.screenplay.models.smart;
public class DataBilling {
private String firstName;
private String lastName;
private String id;
private String email;
private String city;
private String address;
public DataBilling(DataBillingBuilder dataBillingBuilder) {
this.firstName = dataBillingBuilder.getFirsName();
this.lastName = dataBillingBuilder.getLastName();
this.id = dataBillingBuilder.getId();
this.email = dataBillingBuilder.getEmail();
this.city = dataBillingBuilder.getCity();
this.address = dataBillingBuilder.getAddress();
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getId() {
return id;
}
public String getEmail() {
return email;
}
public String getCity() {
return city;
}
public String getAddress() {
return address;
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/models/restservice/users/DataUser.java
package co.com.webapps.screenplay.models.restservice.users;
public class DataUser {
private String id;
private String username;
private String email;
private Address address;
private String phone;
private String website;
public DataUser(String id, String username, String email, Address address, String phone, String website) {
this.id = id;
this.username = username;
this.email = email;
this.address = address;
this.phone = phone;
this.website = website;
}
public String getId() {
return id;
}
public String getUsername() {
return username;
}
public String getEmail() {
return email;
}
public Address getAddress() {
return address;
}
public String getPhone() {
return phone;
}
public String getWebsite() {
return website;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DataUser {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" address: ").append(toIndentedString(address)).append("\n");
sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" website: ").append(toIndentedString(website)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/userinterfaces/InitPage.java
package co.com.webapps.screenplay.userinterfaces;
import net.serenitybdd.screenplay.targets.Target;
public class InitPage {
public static final Target CATEGORY_MENU = Target.the("Left menu categories")
.locatedBy("//div[contains(text(),'Categor�as')]");
public static final Target SHOPPING_CART = Target.the("Shopping Cart icon")
.locatedBy("//a[@href='/cart']/span[@class='icon icon-padding']");
public static final Target CATEGORY_OPTION = Target.the("the Category to select of list")
.locatedBy("//a[@title='{0}']");
public static final Target SECTION_CATEGORY = Target.the("")
.locatedBy("//span[@class='category-name' and contains(text(),'{0}')]");
public static final Target ARTICLE = Target.the("Article of list products ")
.locatedBy("//span[@class='title-section' and contains(text(),'{0}')]");
public static final Target LIST_GROUP_FILTER_SEARCH = Target.the("list group filter search group")
.locatedBy("//dl[@class='list-group filter-search-group']");
public static final Target TITLE_CATEGORY = Target.the("Title of Category")
.locatedBy("//h1[@class='catalogue-title section-title']");
public static final Target CATALOG_ROW_PRODUCT = Target.the("Catalog row product")
.locatedBy("(//div[@class='catalogue-product row '])[{0}]");
private InitPage() {
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/models/restservice/countries/DataCountryBuilder.java
package co.com.webapps.screenplay.models.restservice.countries;
import co.com.webapps.screenplay.models.Builder;
public class DataCountryBuilder implements Builder<DataCountries> {
private String name;
private String capital;
private String region;
public DataCountryBuilder(DataCountries dataCountries){
this.name = dataCountries.getName();
this.capital = dataCountries.getCapital();
this.region = dataCountries.getRegion();
}
public static DataCountryBuilder reduce(DataCountries dataCountries){
return new DataCountryBuilder(dataCountries);
}
@Override
public DataCountries build() {
return new DataCountries(this);
}
public String getName() {
return name;
}
public String getCapital() {
return capital;
}
public String getRegion() {
return region;
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/exceptions/NotFoundDataException.java
package co.com.webapps.screenplay.exceptions;
public class NotFoundDataException extends NullPointerException {
public static final String NOT_FOUND_OBJECT_CONSULT = "No se encontró el objeto en el archivo";
public NotFoundDataException(String s) {
super(s);
}
}
<file_sep>/WebScreenplay/src/main/java/co/com/webapps/screenplay/interactions/EnterAndHide.java
package co.com.webapps.screenplay.interactions;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Interaction;
import net.serenitybdd.screenplay.targets.Target;
import net.thucydides.core.annotations.Step;
import static net.serenitybdd.screenplay.Tasks.instrumented;
public class EnterAndHide implements Interaction {
private Target target;
private String value;
public EnterAndHide(String theText) {
this.value = theText;
}
@Step("{0} enters ****** into #target")
@Override
public <T extends Actor> void performAs(T actor) {
target.resolveFor(actor).sendKeys(value);
}
public static EnterAndHide theValue(String theText){
return instrumented(EnterAndHide.class,theText);
}
public EnterAndHide into(Target target){
this.target=target;
return this;
}
}
|
4dc7a0140dba080e10b0edced1b41afb847fb93c
|
[
"Markdown",
"Java",
"INI",
"Gradle"
] | 38 |
Java
|
LuisaFerCo/TestingBDD
|
eb3be98c3c33f9fac2ddee723f4bfe789d34328f
|
502c9477f1d9f3653e22fb578f4cd99b19fc5f0f
|
refs/heads/master
|
<file_sep>var WS_Manager =
function() {
this.input =
{
address: "",
onopen : function() {},
onmessage : function(msg) {},
onclosed : function() {}
}
this.id = "ws_manager"
this.wsSocket = null
this.hangOutCheck = null
this.pong = JSON.stringify({
"pong" : true
})
}
WS_Manager.prototype = {
init : function() {
console.log("indirizzo "+this.input.address)
try {
this.wsSocket =
window['MozWebSocket'] ?
new MozWebSocket(this.input.address) :
new WebSocket(this.input.address)
;
var me = this;
var dummy_socket = this.wsSocket;
this.wsSocket.onopen =
function() {
console.log("Connection opened ...");
me.hangOutCheck = setTimeout(function(){dummy_socket.close()},1000)
me.input.onopen.call();
};
this.wsSocket.onmessage =
function (event) {
if (event.data.error) {
console.log("ws data error")
this.close()
return
}
var msg = jQuery.parseJSON(event.data);
if (msg.ping != undefined) {
if ($("#__placeholder_"+me.id).length > 0) {
try {
clearTimeout(me.hangOutCheck);
} catch(err) {}
me.hangOutCheck =
setTimeout(function(){
console.log("Connection lost");
dummy_socket.close()},1000)
this.send(me.pong);
}
else {
this.close();
}
} else {
me.input.onmessage.call(me,msg);
}
};
this.wsSocket.onclose =
function() {
console.log("Connection is closed...");
me.input.onclose.call();
if ($("#__placeholder_"+me.id).length > 0)
setTimeout(function(){me.init()},500);
};
} catch (err) {
console.log(err);
console.log("cannot connect to ws");
}
},
send: function(msg) {
this.wsSocket.send(JSON.stringify(msg));
}
}
|
60838ee554b1b949b4bb31a20cca0504e25cda34
|
[
"JavaScript"
] | 1 |
JavaScript
|
Acciaio/play_web_socket_example
|
00689e56f29f12612e1a27af96081254908a8c5b
|
b8f3923c23f710af5abfdbc039017e4e233ec68f
|
refs/heads/master
|
<file_sep>source 'http://rubygems.org'
gem 'rails', '3.0.5'
gem 'activerecord-sqlserver-adapter', '3.0.10'
gem 'tiny_tds', '0.3.2'
gem 'jquery-rails', '0.2.7'
gem 'compass', '0.10.6'
|
b013f57c681afeb425dab734df11e720d4846260
|
[
"Ruby"
] | 1 |
Ruby
|
rezlam/clogs
|
35684b13f70147a5efe5b553c5d43e138a54b205
|
407159b00e6f5e6c67438931be0e36b2ea52cc85
|
refs/heads/master
|
<repo_name>lntusl/ua-parser2<file_sep>/js/test/load/load.mocha.js
"use strict";
/* global describe, it */
// Note: These tests here cannot be executed together with the other tests as mocha does not have a defined execution order
var
assert = require('assert'),
path = require('path'),
fs = require('fs'),
uaParser = require('../../index')(),
testcasesM = require('./testcases')/*.testcases*/;
var
file = __dirname + '/../../../regexes.yaml',
testfile = __dirname + '/load-regexes.yaml',
testfileWatch = __dirname + '/watch-regexes.yaml',
testfileNotExists = __dirname + '/does-not-exist.yaml';
function run(testcases) {
testcases = testcases || testcasesM.testcases;
testcases.forEach(function(tc){
it('- ' + tc.string, function(){
var uaParsed = uaParser.parse(tc.string);
assert.deepEqual(uaParsed, tc);
//~ console.log(JSON.stringify(uaParsed));
});
});
}
function copySync(src, dest) {
var content = fs.readFileSync(src, 'utf-8');
fs.writeFileSync(dest, content, 'utf-8');
}
describe("load regexes", function(){
it('- load custom regexes file', function(){
var error = uaParser.loadSync({ file: file, backwardsCompatible: false });
assert.equal(error, null);
run();
});
it("- not existing", function(){
var error = uaParser.loadSync(testfileNotExists);
assert.ok(/ENOENT/.test(error.message));
});
it("- async load not existing", function(done){
uaParser.load(testfileNotExists, function(error){
assert.ok(/ENOENT/.test(error.message));
done();
});
});
it("- async load existing", function(done){
uaParser.load(testfile , function(error){
assert.equal(error, null);
run();
done();
});
});
});
describe ("watch tests", function(){
it("- async watch existing", function(done){
this.timeout(10000);
copySync(file, testfileWatch);
run(testcasesM.testcasesRegexes);
uaParser.watch(testfileWatch , function(error){
fs.unwatchFile(testfileWatch);
assert.equal(error, null);
run();
done();
});
setTimeout(function(){
copySync(testfile, testfileWatch);
}, 10);
});
});
<file_sep>/CHANGELOG.md
# Changelog
**2017-03-11** v0.2.0
- engine:
- correct "Chrome" to "Blink" engine
- move family type to "type", e.g. "Webkit::Apple" => family: "Webkit", type: "Apple"
- add new matchers
- device: New Oneplus, RCA
**2017-02-03** v0.1.40
- ua: New SohoNews app
- device: New Google Pixel C
- ua: fix Facebook app without version
- ua: New PRTG Network Monitor bot
- ua: New Waterfox
- os: New iOS 10 CFNetwork
- os: New Chromecast
- ua: New Opera Neon
- ua: New PingdomTMS bot
- os: Fix os for chrome on mac os
**2016-12-27** v0.1.39
- ua, os: Detection of Outlook-iOS-Android
- ua: Fix detection of 008 bot
- os: Fix iOS detection
- ua: Fix doubled Minimo
- ua: Fix Fennec browser
- ua: Fix baidubrowser
- device: adding device types
- device: Huawei Honor
- device: fix generic_android containing Build twice
- ua: update mediaplayer, feedreader
- os: Linux, Red Hat
- ua: headless browsers
- ua: Pinterest app, bot
**2016-12-02** v0.1.38
- ua: distinguish Lightning from Thunderbird
- ua: app Kurio, BacaBerita, Deezer
- ua: MxBrowser is Maxthon
- device: better detect iP devices
- os: detect iPd UCWEB browser
- os: better iOS detection
**2016-11-12** v0.1.37
- regexes:
- Detect Postbox mail client
- Detect Kodi, XMBC, spmc media players
- adding changed ua scheme for Iron
- adding Enseo room entertainment system
- adding Kurio devices
- adding GoogleImageProxy
- fixing webOS
- performance improvements
- adding Slackbot
- fix for iPad,iPod,iPhone family
- adding device type bot to spiders
- adding BingPreview as bot
- fixing iPhone,iPad family
- fixing iPad,iPhone
- type headless for Phantom Browser
- adding Slack and Office365/Outlook services
- fix UC Browser detection
**2016-09-28** v0.1.36
- regexes:
- user_agent_parsers
- Detect Chrome Mobile based browsers, MobileIron, Crosswalks
- Detect mail programs
- Fix UC Browser
- LG Browser
- engine
- Chrome::QtWebEngine
- os_parsers
- RemixOS
- macOS Sierra, Mac OSX El Capitan
- WebOS
- device
- correcting iPod touch
- snom
**2016-05-14** v0.1.35
- regexes:
- user_agent_parsers
- Adding NerdyBot
- iOS has two types of webviews UI/WKWebView which cannot be distinguished
- Add TwitterBot
- Detection of Apple Mail
- CaptiveNetworkSupport <https://discussions.apple.com/thread/3688992>
- Improve Version detection on Bots
- PayPal Instant Payment Notification Bot
- adbeat.com Bot
- Comodo SSL Checker
- Digg Feed Fetcher
- Electron
- SamsungBrowser
- Dragon
- ScoutJet Bot
- DeuSu Bot
- MailBar
- 360 speed/ speed browser
- engine_parsers
- Adding Chrome::WebView <https://developer.chrome.com/multidevice/user-agent>
- Fixing Chrome::Samsung (SamsungBrowser)
- os_parsers
- Raspbian
- device_parsers
- Nexus 5X, Nexus 6P
- XiaoMi MI PAD, Mi 4i
- Fix device detection for Nokia rv:11 Windows Phone
**2016-02-03** v0.1.34
- regexes:
- Correcting/Extending Mail User-Agents, Thunderbird, Shredder, Spicebird, Outlook, Windows Live Mail
**2016-02-03** v0.1.33
- regexes:
- Adding support for Brave Browser https://brave.com
**2016-01-11** v0.1.32
- regexes:
- fix YAMLException with duplicated mapping keys
**2015-11-24** v0.1.31
- regexes
- user_agent_parsers
- better detection of Opera Mini
- better detection of Chrome Mobile
- os_parsers
- adding tvOS
**2015-10-18** v0.1.30
- regexes
- device
- More XiaoMi Devices
**2015-10-12** v0.1.29
- regexes
- user_agent_parsers
- fix wrong mobile safari version
- Adding support for Otter and QupZilla
- Adding Version to BB10
- Adding support for Edge Mobile
**2015-10-11** v0.1.28
- regexes
- user_agent_parsers
- Adding support for qutebrowser
- Better detection of Facebook
- Mobile Safari UIWebView
**2015-10-01** v0.1.27
- regexes
- device_parsers
- Mac OS X-Devices
- Fix generic Android devices
- More Wiko, Sony, Brondi, Kyocera devices
- user_agent_parsers
- social networks: Pinterest, Facebook
- os_parsers
- Mac OS X Version
**2015-09-21** v0.1.26
- regexes
- os_parsers
- CFNetwork Mac OS X 10.11 El Capitan
- CFNetwork iOS 9.0
**2015-09-19** v0.1.25
- regexes
- user_agent_parsers
- SiteCon Bot
- Firefox Browser for Android Tablets
- Spotify Desktop App
**2015-09-13** v0.1.24
- replacing yamlparser with js-yaml
**2015-09-13** v0.1.23
- regexes
- user_agent_parsers
- Firefox on iOS
- os_parsers
- Firefox OS Versions
**2015-06-26** v0.1.22
- benchmark comparison
- reducing regexes with neg lookahead
- regexes
- user_agent_parsers
- Edge detected as Edge instead of IE
**2015-05-17** v0.1.21
- regexes
- device_parsers
- Karbonn, EverCoss, Toshiba, Blu, Alcatel, Gionee, Sharp, Aoc, Asus, Hisense, Lenovo, LG, ZTE, Amazon devices
- new brand ADVAN, TWM, Yezz, Symphony, Vonino, NYX, Bangho
**2015-05-14** v0.1.20
- regexes
- os_parsers
- Mac OS X 10.10 Yosemite
- detect "Mac OS X/" with slash
- iOS 8.1 - 8.3
- Apple TV
- device_parsers
- Apple TV with Hardware Version
**2015-05-08** v0.1.19
- fix failing Mac OS X test
**2015-05-01** v0.1.18
- regexes
- user_agent_parsers
- MacAppStore
- bot: websitepulse checker
- os_parsers
- "MacOS X" and "Mac OS X Mach-0"
- iTunes User-Agents
**2015-05-01** v0.1.17
- regexes
- user_agent_parsers
- Vivaldi (http://vivaldi.com/)
**2015-04-15** v0.1.16
- regexes
- os_parsers:
- Windows 10
- device_parsers:
- Karbonn: A10, A12, A15 ... are not Micromax
- QMobile: improved regex
- Allview AX4Nano
- HbbTV Thomson
**2015-03-11** v0.1.15
- regexes
- user_agent_parsers
- Firefox: Better version detection using rv:
- fix Phoenix: Fly Phoenix 2
- os_parsers
- Android: Better version detection
- X11, Macintosh: Detection
- fix Android Donut to version 1.6
- device_parsers
- ionik: TU-1201A, TU-1489A, TU-7851A
- Jaytech: TPC_PX753, TPC-PA10.1M
- Denver: PO#xxxx
- MyPhone: Better detection
- Medion: 4001, 4004
- Ramos: New brand
- Runbo: New brand
- xiaomi: New devices mipad
- mysaga: New brand
- Leagoo: New brand
- fix SonyEricsson X\d{2,3} devices (move to Generic_Android)
- fix SonyEricsson E\d{4} devices
- Brondi: New brand
- NGM: New brand
- Odys: NERON
- ZTE: OpenC
- Xtouch: New brand
- Xianghe: improved regex
- Windows Phones: improved parsers
- update to contributing
**2015-02-14** v0.1.14
- parser
- fix problem with node v0.12
- regexes
- device_parsers
- Huawei: Honor, H60-L*, OrangeLuno, OrangeYumo
- Samsung: GT-Xperia S
- Acer: A1-000FHD, A3-A00FHD, B1-000FHD, b1-000, E39, E320, E380, E400, S55, S56, S500, S510, S520, Z140, Z150, Z160, Z200, Z410, Z500
- Alcatel: 4032X, 5038D, 5050X, 5050Y, 6016D, 6016X, 6036Y, 6037Y, 6043D, 6050Y, Vodafone_Smart_II, Orange Infinity 8008X, Orange Hiro, Orange Yomi, Telenor Smart, Telenor Smart, Telenor_One_Touch_S, move 2, BS471, I213, Mobile Sosh, MTC975, smart_a17
- Asus: K007, K010, K011, K013, K014, K015, K016, K017, K018, K019, TX201LA
- Avus: New brand
- Blackview: New brand
- bq: Aquaris
- CAT: B15, B15Q
- Coolpad: Improvement
- Cubot: GT89, GT90, GT91, P6, P7, P9, P10, S108, S168, S200, S208, S222, S308, s350, T9, X6, X9
- Doogee: New brand
- Doro: New brand
- Elephone: New brand
- Enot: Fix regexes
- Fairphone: New brand
- Gionee: E7
- GoClever: ARIES
- Haier: HW-W718, HW-W910, W867
- Hannspree: HSG1279, HSG1281, HSG1291, HSG1297
- HTC: A320a, Z520m, HTL22, 801a, Nexus 9, PJ83100, ADR6410
- InFocus: New brand
- Jaytech: TPC-PA10.1M, TPC-PA1070, TPC-PA762, TPC-PA777, TPC-PA7815, TPC-PA9702, TPC-PX753, TPC-81203G
- Kazam: New brand
- Kiano: New brand
- Landvo: New brand
- Lenovo: YOGA pad
- Mobiwire: New brand
- Motorola: Refactor Xoom, RAZR HD, Nexus 6
- Neken: New brand
- Newman: New brand
- Nook: BNTV250A
- Oneplus: New Brand
- Odys: ARIA, AVIATOR, CONNECT7PRO, CONNECT8PLUS, GATE, INTELLITAB7, JUNIORTAB, MIRON, Motion, PRO_Q8, SKYPLUS3G, UNO_X10, VISIO, XelioPT2Pro
- Phicomm: i600, i813w
- Prestigio: PSP, PMT
- Trekstor: VT10416, Surftab, breeze, xiron
- Smartbook: New brand
- SonyEricsson: R800a
- Sony: S39h
- Switel: New brand
- Thl: W200S, T100S
- Umi: New brand
- Wiko: BIRDY, GETAWAY, GOA, HIGHWAY SIGNS, IGGY, JIMMY, KITE, LENNY, RIDGE, RIDGE FAB, SLIDE, SUNSET
- Xiaomi: HM devices
- Xoro: New devices
- Amazon: 4th Gen Devices
**2014-12-17
- regexes
- ua: Opera Coast and Opera Mini
- ua: escaped ' in bot regex solved
- parser
- simplification with regex gen
**2014-12-16**
- tests
- Change to [streamss](http://github.com/commenthol/streamss) for all test cases.
- Tests now also run on Node v0.8.x
**2014-11-13**
- regexes
- Better detection of ThL, Cubot, HTC One M*
- New: Gigaset
- New: IE Tech-Preview on Windows10
**2014-11-05**
- regexes
- type bot::healthcheck introduced for Monitors/Loadbalancers
**2014-10-30**
- regexes
- Puffin Browser added
- Amazon Silk hidden by Chrome
- Better detection of bots
**2014-10-08**
- regexes
- Xenu and other Bots added
- Fix: Version detection of Bots
- Motorola now contains brand name in device replacement
**2014-09-25**
- regexes
- Zopo Devices
- Asus Transformer, PadFone
**2014-09-24**
- regexes
- Oppo Find 7a added
- ZTE OpenC
- Fix for Archos/ Arnova Tablets
**2014-09-11**
- regexes
- Riddler bot, Sony Xperia Z3 added
**2014-09-02**
- regexes
- Sony Playstation, os + device
- CFNetwork, os
- Better detection of bots
- Fix in ua bot detection - major version not recognized as hidden by "google(^tv)"
**2014-08-14**
- regexes
- Sony Android Rule updated for D6603
- engine_parsers:
- Webkit::Nokia renamed for webkit based NokiaBrowser
- Webkit:LG and Webkit::Samsung for tv sets
- device_parsers: type=tv added
**2014-08-10**
- regexes
- Windows OS refactored, Cygwin added
- New OS's added: YunOS, AmigaOS, Tizen, Sailfish, Haiku, BeOS, Nintendo, OS/2, PalmOS, Various Linux Distros, RISC OS, Solaris, HopenOS, Gogi
- UA: Better catch of Browsers using Chrome Engine, CocoonJS
- Device: types for camera, car added
- Device: Nokia, Palm, Blackberry refactored
- Device: garmin-asus Nuvifone added
- Device: Nook, CnM, Versus, Danew, Lenovo, Acer, Micromax, Alcatel, Amoi, Avvio, Bmobile improved
**2014-08-09**
- parser
- Replacements use either `$10` or `${1}0`
- Specification update -> Version 1.1 Final
- Travis Build added
- Quick tests (quick-tests.json) for npm package added.
The big test file gets excluded.
- parserdevice.js simplified in parser.js
<file_sep>/js/lib/device.js
'use strict';
function Device(family, brand, model, type, debug) {
this.family = family || 'Other';
this.brand = brand || null;
this.model = model || null;
if (typeof type !== 'undefined') { this.type = type || null; }
if (typeof debug !== 'undefined') { this.debug = debug || null; }
}
Device.prototype.toString = function() {
var output = '';
if (this.brand !== null) {
output += this.brand;
if (this.model !== null) {
output += ' ' + this.model;
}
}
else if (this.family) {
output = this.family;
}
return output;
};
module.exports = Device;
<file_sep>/js/lib/helpers.js
'use strict';
var DIGITS = /^\d/;
exports.startsWithDigit = startsWithDigit;
function startsWithDigit(str) {
return DIGITS.test(str);
}
<file_sep>/js/test/libhelper.js
'use strict';
/* global describe, it */
var
assert = require('assert'),
helper = require('./lib/helper');
describe('#compact', function(){
var
org = {"ua":{"family":"NCSA Mosaic","major":null,"minor":null,"patch":null},"engine":{"family":"Other","major":null,"minor":null,"patch":null},"os":{"family":"Other","major":null,"minor":null,"patch":null, "patchMinor": null},"device":{"family":"Other","brand":null,"model":null},"string":"Mozilla/1.0 (compatible; NCSA Mosaic; Atari 800-ST)"},
com = {"ua":{"family":"NCSA Mosaic"},"string":"Mozilla/1.0 (compatible; NCSA Mosaic; Atari 800-ST)"};
it('strip', function(){
var
clone = helper.merge(org),
res = helper.compact.strip(clone);
assert.deepEqual(res, com);
});
it('unstrip', function(){
var
res = helper.compact.unstrip(com);
assert.deepEqual(res, org);
});
});
|
18c0b96cb530358d0433de4b0e9b3ae3fa16caec
|
[
"JavaScript",
"Markdown"
] | 5 |
JavaScript
|
lntusl/ua-parser2
|
11cb4a947b7e239092ed4b1cd3504d32438684cd
|
8e3bc42289b02cfb0e6c8dd3875285794b0027e9
|
refs/heads/master
|
<file_sep>require 'spec_helper'
describe UserSessoinsController do
end
<file_sep># This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'spec_helper'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
end
describe Restaurant do
before do
@restaurant = Restaurant.new(name: "Momofuku")
end
subject { @restaurant }
it { should respond_to(:name) }
it { should be_valid }
describe "when name is not present" do
before { @restaurant.name = " " }
it { should_not be_valid }
end
describe "when name is already taken" do
before do
restaurant_with_same_name = @restaurant.dup
restaurant_with_same_name.name = @restaurant.name.upcase
restaurant_with_same_name.save
end
it { should_not be_valid }
end
end
|
610f77a7daa25d73cba5ad60cb717338b8df4945
|
[
"Ruby"
] | 2 |
Ruby
|
softcomet/restauranteur
|
567f1945d5099fa3c8e242fe643885cd379406af
|
95bd1aa4364939d43bb5683b6d04d87ed7b53f91
|
refs/heads/master
|
<repo_name>qwtfps/haha<file_sep>/myoohoohoo2.go
// Copyright 2011 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package myoohoohoo2
import (
"appengine"
//"appengine/blobstore"
"appengine/datastore"
"encoding/json"
"fmt"
//"io"
"net/http"
//"os"
. "github.com/qiniu/api/conf"
//"github.com/qiniu/api/io"
"github.com/qiniu/api/rs"
"strconv"
"time"
)
type UserStruct struct {
Uid int
UserName string
Password string `json:"-"`
Sex string
Date time.Time
TokenTime time.Time `json:"-"`
}
type AudioStruct struct {
Aid int
Uid int
UserName string
AudioKey string
AudioTitle string
IsValid bool `json:"-"`
Favorite int
Date time.Time
Size int
}
type AudioSlice struct {
Audios []AudioStruct
}
type CollectionAudio struct {
Uid int
Aid int
}
//func main() {
// mux := http.NewServeMux()
// r := mux.NewRouter()
// r.HandleFunc("/", root)
// r.HandleFunc("/register", register)
// r.HandleFunc("/login", login)
// r.HandleFunc("/generate", generate) //get toekn
// r.HandleFunc("/checkvalid", checkvalid)
// r.HandleFunc("/query", query)
// r.HandleFunc("/delaudio", delaudio) //delete audio=set IsValid = false
// r.HandleFunc("/recqiniu", recqiniu) //get sth from qiniu
//}
//建表记录设备型号,用户来源国家地区,系统
func init() {
ACCESS_KEY = "<KEY>"
SECRET_KEY = "<KEY>"
http.HandleFunc("/", root)
http.HandleFunc("/register", register)
http.HandleFunc("/login", login)
http.HandleFunc("/generate", generate) //get toekn
http.HandleFunc("/checkvalid", checkvalid)
http.HandleFunc("/query", query)
http.HandleFunc("/delaudio", delaudio) //delete audio=set IsValid = false
http.HandleFunc("/recqiniu", recqiniu) //get sth from qiniu
http.HandleFunc("/addcollect", addcollect)
http.HandleFunc("/delcollect", delcollect)
//http.HandleFunc("/getinfo", getinfo)//for myself to check users audios count,need xxx=yyy?
}
func linkJson(status string, subKey string, val string) string {
return "{\"status\":" + status + "," + "\"" + subKey + "\"" + ":" + val + "}"
}
func root(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "root!")
//var s AudioSlice
//s.Audios = append(s.Audios, AudioStruct{Aid: 10001, Uid: 111001, AudioKey: "aehjaewb", Favorite: 1, Date: time.Now(), Size: 123456})
//s.Audios = append(s.Audios, AudioStruct{Aid: 121312, Uid: 21312, AudioKey: "feewdwED", Favorite: 1, Date: time.Now(), Size: 123456})
//b, err := json.Marshal(s)
//if err != nil {
// fmt.Fprintln(w, linkJson("0", "msg", "no audio"))
//}
//fmt.Fprint(w, "{\"status\":\"1\""+","+string(b)+"}")
//fmt.Fprintln(w, linkJson("1", nil, string(b)))
}
func uptoken(bucketName string, uid string) string {
//body := "x:uid=" + uid + "&key=$(etag)&size=$(fsize)" // + "&gentime=" + string(time.Now().Unix())
body := "uid=$(x:uid)&username=$(x:username)&audiotitle=$(x:audiotitle)&key=$(etag)&size=$(fsize)" + "&gentime=" + string(time.Now().Unix())
putPolicy := rs.PutPolicy{
Scope: bucketName,
CallbackUrl: "http://www.oohoohoo.com/recqiniu?", //http://<your domain>/recqiniu
CallbackBody: body, //gae body eg:test=$(x:test)&key=$(etag)&size=$(fsize)&uid=$(endUser)
//ReturnUrl: returnUrl,
//ReturnBody: returnBody,
//AsyncOps: asyncOps,
EndUser: uid, //uid
Expires: 3600 * 24 * 7, // 1week?
}
return putPolicy.Token(nil)
}
func generate(w http.ResponseWriter, r *http.Request) {
//get uid
if "POST" == r.Method {
//uid := r.FormValue("uid")
uid, _ := strconv.Atoi(r.FormValue("uid"))
c := appengine.NewContext(r)
q1 := datastore.NewQuery("UserStruct").Filter("Uid =", uid)
existUser := make([]UserStruct, 0, 1)
if _, err := q1.GetAll(c, &existUser); err != nil {
fmt.Fprint(w, "{\"status\":\"0\"}")
return
}
if len(existUser) > 0 {
token := uptoken("qtestbucket", r.FormValue("uid"))
//update user tokentime
thisUser := existUser[0]
thisUser = UserStruct{
Uid: thisUser.Uid,
UserName: thisUser.UserName,
Password: thisUser.Password,
Sex: thisUser.Sex,
Date: thisUser.Date,
TokenTime: time.Now(),
}
//kkk, err1 := datastore.Put(c, datastore.NewIncompleteKey(c, "UserStruct", nil), &thisUser)
//fmt.Fprintln(w, thisUser)
key_str := "UserStruct" + r.FormValue("uid")
key := datastore.NewKey(c, "UserStruct", key_str, 0, nil)
_, err1 := datastore.Put(c, key, &thisUser)
if err1 != nil {
fmt.Fprintln(w, linkJson("0", "uploadToken", "\"\""))
} else {
fmt.Fprintln(w, linkJson("1", "uploadToken", "\""+token+"\""))
//fmt.Fprintln(w, "success")
}
} else {
fmt.Fprintln(w, linkJson("0", "uploadToken", "\"\"")) //not find this uid
}
}
}
func checkvalid(w http.ResponseWriter, r *http.Request) {
if "POST" == r.Method {
uid, _ := strconv.Atoi(r.FormValue("uid"))
c := appengine.NewContext(r)
q1 := datastore.NewQuery("UserStruct").Filter("Uid =", uid)
existUser := make([]UserStruct, 0, 1)
if _, err := q1.GetAll(c, &existUser); err != nil {
fmt.Fprint(w, "{\"status\":\"0\"}")
return
}
if len(existUser) > 0 {
thisUser := existUser[0]
result := isvalid(thisUser.TokenTime)
if result {
fmt.Fprintln(w, linkJson("1", "msg", "\"success\""))
} else {
fmt.Fprintln(w, linkJson("0", "msg", "\"fail\"")) //need re generate token
}
} else {
fmt.Fprintln(w, linkJson("0", "uploadToken", "")) //not find this uid
}
}
}
func isvalid(gentime time.Time) bool {
//now is before valid time is right
if time.Now().Before(gentime.Add(1000 * 1000 * 1000 * 3600 * 24 * 7)) {
return true
} else {
return false
}
return false
}
//http://requestb.in/ 测试七牛返回数据
func recqiniu(w http.ResponseWriter, r *http.Request) {
if "POST" == r.Method {
uid := r.FormValue("uid")
username := r.FormValue("username")
audiokey := r.FormValue("key")
audiotitle := r.FormValue("audiotitle")
size := r.FormValue("size")
fmt.Fprintln(w, linkJson("1", "audiotitle", "\""+audiotitle+"\""))
c := appengine.NewContext(r)
q := datastore.NewQuery("AudioStruct") //query count
audios := make([]AudioStruct, 0, 10) //10need max or auto add
if _, err := q.GetAll(c, &audios); err != nil {
return
}
count := len(audios)
//uid_str := strconv.Itoa(count + 1)
uid_int, _ := strconv.Atoi(uid)
aid_int := count + 1
size_int, _ := strconv.Atoi(size)
audio := AudioStruct{
Aid: aid_int,
Uid: uid_int,
UserName: username,
AudioKey: audiokey,
AudioTitle: audiotitle,
IsValid: true,
Favorite: 0,
Date: time.Now(),
Size: size_int,
}
//_, err1 := datastore.Put(c, datastore.NewIncompleteKey(c, "AudioStruct", nil), &audio)
aid_str := strconv.Itoa(aid_int)
key_str := "AudioStruct" + aid_str //应该从七牛返回的来存,这个key,或者从手机传出去的时候就规则好key
key := datastore.NewKey(c, "AudioStruct", key_str, 0, nil)
_, err1 := datastore.Put(c, key, &audio)
if err1 != nil {
fmt.Fprintln(w, linkJson("0", "msg", "\"fail\""))
return
} else {
fmt.Fprintln(w, linkJson("1", "msg", "\"success\""))
}
}
}
//http://localhost:8080/register?username=aaa&password=<PASSWORD>&sex=1
func register(w http.ResponseWriter, r *http.Request) {
if "POST" == r.Method {
c := appengine.NewContext(r)
q := datastore.NewQuery("UserStruct") //query count
users := make([]UserStruct, 0, 10) //need max or auto add
if _, err := q.GetAll(c, &users); err != nil {
fmt.Fprint(w, "{\"status\":\"0\"}")
return
}
q1 := datastore.NewQuery("UserStruct").Filter("UserName =", r.FormValue("username"))
existUser := make([]UserStruct, 0, 1)
if _, err := q1.GetAll(c, &existUser); err != nil {
fmt.Fprint(w, "{\"status\":\"0\"}")
return
}
if len(existUser) > 0 {
//msg,用户名已存在
fmt.Fprint(w, "{\"status\":\"0\",\"msg\":\"1\"}")
return
}
count := len(users)
//uid_str := strconv.Itoa(count + 1)
//uid_int, _ := strconv.Atoi(uid_str)
uid_int := 100000 + count + 1
//uid_str := strconv.Itoa(uid_int)
u := UserStruct{
Uid: uid_int,
UserName: r.FormValue("username"),
Password: r.FormValue("<PASSWORD>"),
Sex: r.FormValue("sex"),
Date: time.Now(),
//TokenTime: nil,
}
uid_str := strconv.Itoa(uid_int)
key_str := "UserStruct" + uid_str
key := datastore.NewKey(c, "UserStruct", key_str, 0, nil)
_, err := datastore.Put(c, key, &u)
//_, err := datastore.Put(c, datastore.NewIncompleteKey(c, "UserStruct", nil), &u)
if err != nil {
fmt.Fprint(w, "{\"status\":\"0\"}")
return
} else {
var s = make(map[string]interface{})
s["Uid"] = u.Uid
s["UserName"] = u.UserName
s["Sex"] = u.Sex
s["Date"] = u.Date.Format("2006-01-02 15:04:05")
b, err := json.Marshal(s)
if err != nil {
fmt.Println(err)
return
}
fmt.Fprintln(w, linkJson("1", "userinfo", string(b)))
//注册成功后,记录原来输入的,客户端执行登录
}
} else {
fmt.Fprintln(w, "get")
}
}
func login(w http.ResponseWriter, r *http.Request) {
if "POST" == r.Method {
c := appengine.NewContext(r)
q := datastore.NewQuery("UserStruct").Filter("UserName =", r.FormValue("username"))
users := make([]UserStruct, 0, 1)
if _, err := q.GetAll(c, &users); err != nil {
return
}
if len(users) > 0 {
realPwd := users[0].Password
if r.FormValue("password") == realPwd {
//返回相应信息
//response := fmt.Sprintf("%v", users[0].Password)
var s = make(map[string]interface{})
s["Uid"] = users[0].Uid
s["UserName"] = users[0].UserName
s["Sex"] = users[0].Sex
s["Date"] = users[0].Date.Format("2006-01-02 15:04:05")
//response := "userinfo:" + s
b, err := json.Marshal(s)
if err != nil {
fmt.Println(err)
return
}
fmt.Fprintln(w, linkJson("1", "userinfo", string(b)))
//fmt.Fprint(w, "{\"status\":\"1\"}")
}
} else {
fmt.Fprint(w, "{\"status\":\"0\"}")
}
} else {
fmt.Fprintln(w, "login get")
}
}
type Sizer interface {
Size() int64
}
func query(w http.ResponseWriter, r *http.Request) {
if "POST" == r.Method {
c := appengine.NewContext(r)
//q := datastore.NewQuery("AudioStruct").Filter("UserName =", r.FormValue("username"))
//type order audio
page, _ := strconv.Atoi(r.FormValue("page"))
countbegin := (page - 1) * 20 //page * 20
q := datastore.NewQuery("AudioStruct").Filter("IsValid =", true).Order("-Date").Limit(20).Offset(countbegin)
audios := make([]AudioStruct, 0, 10) //need max or auto add
if _, err := q.GetAll(c, &audios); err != nil {
fmt.Fprintln(w, linkJson("0", "msg", "\"db error\""))
return
}
if len(audios) > 0 {
//fmt.Fprint(w, "has audio")
//getAudio := audios[0].AudioKey
var s AudioSlice
for _, value := range audios {
s.Audios = append(s.Audios, AudioStruct{Aid: value.Aid, Uid: value.Uid, UserName: value.UserName, AudioKey: value.AudioKey, AudioTitle: value.AudioTitle, Favorite: value.Favorite, Date: value.Date, Size: value.Size})
}
b, err := json.Marshal(s)
if err != nil {
fmt.Fprintln(w, linkJson("0", "msg", "\"json error\""))
return
}
//fmt.Fprint(w, "{\"status\":\"1\""+","+string(b)+"}")
//fmt.Fprintln(w, linkJson("1", "msg", string(b)))
fmt.Fprintln(w, linkJson("1", "audios", string(b)))
} else {
fmt.Fprintln(w, linkJson("0", "msg", "\"no audio\""))
}
}
}
func delaudio(w http.ResponseWriter, r *http.Request) {
if "POST" == r.Method {
c := appengine.NewContext(r)
aid, _ := strconv.Atoi(r.FormValue("aid"))
q := datastore.NewQuery("AudioStruct").Filter("Aid =", aid)
audios := make([]AudioStruct, 0, 1)
if _, err := q.GetAll(c, &audios); err != nil {
return
}
if len(audios) > 0 {
thisAudio := audios[0]
thisAudio = AudioStruct{
Aid: thisAudio.Aid,
Uid: thisAudio.Uid,
UserName: thisAudio.UserName,
AudioKey: thisAudio.AudioKey,
AudioTitle: thisAudio.AudioTitle,
IsValid: false,
Favorite: thisAudio.Favorite,
Date: thisAudio.Date,
Size: thisAudio.Size,
}
key_str := "AudioStruct" + r.FormValue("aid")
key := datastore.NewKey(c, "AudioStruct", key_str, 0, nil)
_, err1 := datastore.Put(c, key, &thisAudio)
if err1 != nil {
fmt.Fprintln(w, linkJson("0", "msg", "\"delete failed\""))
} else {
fmt.Fprintln(w, linkJson("1", "msg", "\"delete succeed\""))
}
}
}
}
func addcollect(w http.ResponseWriter, r *http.Request) {
if "POST" == r.Method {
c := appengine.NewContext(r)
uid, _ := strconv.Atoi(r.FormValue("uid"))
aid, _ := strconv.Atoi(r.FormValue("aid"))
q := datastore.NewQuery("CollectionAudio").Filter("Uid =", uid).Filter("Aid =", aid)
existC := make([]CollectionAudio, 0, 1) //this uid collected this aid before
if _, err := q.GetAll(c, &existC); err != nil {
fmt.Fprint(w, "{\"status\":\"0\"}")
return
}
if len(existC) > 0 {
//msg,this uid collected this aid before
fmt.Fprint(w, "{\"status\":\"0\",\"msg\":\"1\"}")
return
}
collect := CollectionAudio{
Uid: uid,
Aid: aid,
}
key_str := "CollectionAudio" + r.FormValue("uid") + r.FormValue("aid")
key := datastore.NewKey(c, "CollectionAudio", key_str, 0, nil)
_, err := datastore.Put(c, key, &collect)
if err != nil {
fmt.Fprint(w, "{\"status\":\"0\"}")
return
} else {
fmt.Fprintln(w, "{\"status\":\"1\"}") //collect success
}
}
}
func delcollect(w http.ResponseWriter, r *http.Request) {
if "POST" == r.Method {
c := appengine.NewContext(r)
uid, _ := strconv.Atoi(r.FormValue("uid"))
aid, _ := strconv.Atoi(r.FormValue("aid"))
q := datastore.NewQuery("CollectionAudio").Filter("Uid =", uid).Filter("Aid =", aid)
existC := make([]CollectionAudio, 0, 1) //this uid collected this aid before
if _, err := q.GetAll(c, &existC); err != nil {
fmt.Fprint(w, "{\"status\":\"0\"}")
return
}
if len(existC) > 0 {
//delete record
key_str := "CollectionAudio" + r.FormValue("uid") + r.FormValue("aid")
key := datastore.NewKey(c, "CollectionAudio", key_str, 0, nil)
err := datastore.Delete(c, key)
if err != nil {
fmt.Fprint(w, "{\"status\":\"0\"}") //delete fail
return
} else {
fmt.Fprint(w, "{\"status\":\"1\"}") //delete success
return
}
} else {
fmt.Fprint(w, "{\"status\":\"0\"}")
}
}
}
//c := appengine.NewContext(r)
//uid, _ := strconv.Atoi(r.FormValue("uid"))
//q := datastore.NewQuery("UserStruct").Filter("Uid =", uid)
//q := datastore.NewQuery("UserStruct").Order("-Date")
//q = q.Filter("Sex =", "1")
//users := make([]UserStruct, 0, 10)
//if _, err := q.GetAll(c, &users); err != nil {
// return
//}
//if len(users) > 0 {
// fmt.Fprint(w, "has user")
// //getUser := users[0].TokenTime
// name := users[0].UserName
// fmt.Fprint(w, name)
// fmt.Fprint(w, strconv.Itoa(len(users)))
//} else {
// fmt.Fprint(w, "no user")
//}
//return
//type Server struct {
// ServerName string
// ServerIP string
//}
//type Serverslice struct {
// Servers []Server
//}
//func main() {
// var s Serverslice
// s.Servers = append(s.Servers, Server{ServerName: "Shanghai_VPN", ServerIP: "127.0.0.1"})
// s.Servers = append(s.Servers, Server{ServerName: "Beijing_VPN", ServerIP: "127.0.0.2"})
// b, err := json.Marshal(s)
// if err != nil {
// fmt.Println("json err:", err)
// }
// fmt.Println(string(b))
//}
//http://hi.baidu.com/liuhelishuang/item/035bc33f23c389c21b9696a7
//http://golang.usr.cc/thread-52517-1-1.html//可能有用,上传file的defer后正确的
//https://github.com/jimmykuu/gopher/blob/master/src/gopher/account.go
//c := appengine.NewContext(r)
// audio := AudioStruct{
// Aid: 2,
// Uid: 2,
// UserName: "yjmiyf",
// AudioKey: " hmjg ",
// AudioTitle: "hjmhgj",
// IsValid: true,
// Favorite: 0,
// Date: time.Now(),
// Size: 1233,
// }
// //_, err1 := datastore.Put(c, datastore.NewIncompleteKey(c, "AudioStruct", nil), &audio)
// aid_str := strconv.Itoa(2)
// key_str := "AudioStruct" + aid_str //应该从七牛返回的来存,这个key,或者从手机传出去的时候就规则好key
// key := datastore.NewKey(c, "AudioStruct", key_str, 0, nil)
// _, err1 := datastore.Put(c, key, &audio)
// if err1 != nil {
// fmt.Fprintln(w, linkJson("0", "msg", "\"fail\""))
// return
// } else {
// fmt.Fprintln(w, linkJson("1", "msg", "\"success\""))
// }
|
1da432af18552eae5f0e85a25cc1f1ea6e771fb8
|
[
"Go"
] | 1 |
Go
|
qwtfps/haha
|
eb5173633b4673252c21bc6fa4224fec65c4990f
|
f49f32556108f42fba5f48545517e0efc687a908
|
refs/heads/master
|
<file_sep>from django.db import models
class Order(models.Model):
order_id = models.CharField(max_length=20)
customer = models.CharField(max_length=20)
item = models.CharField(max_length=20)
def __str__(self):
return self.order_id
<file_sep>from django.conf.urls import patterns, url
from django.contrib import admin
from order.views import get_order, get_order_detail, ajax
admin.autodiscover()
urlpatterns = [
url(r'^$', 'demo.views.index', name='index'),
url(r'^attrs/$', 'demo.views.attrs', name='attrs'),
url(r'^metadata/$', 'demo.views.metadata', name='metadata'),
# url(r'^accounts/', include('users.urls', namespace='users')),
url(r'^search$', get_order, name='get_order'),
url(r'^order/(?P<order_id>\w+)/$', get_order_detail, name='get_order_detail'),
url(r'^ajax$', ajax, name='ajax'),
url(r'^admin/', admin.site.urls),
]<file_sep>from django.http import HttpResponse
from django.shortcuts import render
from .models import Order
def get_order(request):
if request.method == 'POST':
search_text = request.POST.get('search_text')
order_list = Order.objects.filter(customer=search_text).order_by('order_id').values('order_id', 'customer').distinct()
return render(request, 'first_page.html', {
'order_list': order_list,
})
else:
return render(request, 'first_page.html')
def get_order_detail(request, order_id):
item_list = Order.objects.filter(order_id=order_id)
customer = item_list[0].customer
return render(request, 'second_page.html', {
'item_list': item_list,
'order_id': order_id,
'customer': customer,
})
def ajax(request):
search_text = request.GET.get('search_text')
order_list = Order.objects.filter(
customer=search_text
).order_by('order_id').values_list('order_id', flat=True).distinct()
html = ""
if len(order_list) == 0:
html = "<tr><td colspan='2'>No Orders</td></tr>"
else:
for order in order_list:
html = html + "<tr><td><a href='/order/{0}/'>{0}</a></td><td>{1}</td></tr>".format(order, search_text)
return HttpResponse(html)
<file_sep>from django.contrib import admin
from .models import Order
class OrderAdmin(admin.ModelAdmin):
list_display = ('order_id', 'customer', 'item')
# Register your models here.
admin.site.register(Order)
|
42318b5f694d63b90e72955276c730ec0acbcb37
|
[
"Python"
] | 4 |
Python
|
yaohappy/hw4_sso
|
f4dea9e3735b8cd3960d10908d21b8c9f6fd85c5
|
9e61ac92deb12a988b8154fd39b12be4f26ba4b9
|
refs/heads/master
|
<repo_name>MAhsanmirza/kc_house_price-prediction<file_sep>/project = MOD-02-FIS.py
#!/usr/bin/env python
# coding: utf-8
# # Introduction: Pricing of Homes in King County, WA
# 
#
# Welcome to my kernel
#
# In this dataset we have to predict the sales price of houses in King County, Seattle. It includes homes sold between May 2014 and May 2015. Before doing anything we should first know about the dataset what it contains what are its features and what is the structure of data.
#
# The dataset cantains 21 house features plus the price, along with 21597 observations.
#
# The description for the 21 features is given below:
#
# 1. id :- It is the unique numeric number assigned to each house being sold.
# 2. date :- It is the date on which the house was sold out.
# 3. price:- It is the price of house which we have to predict so this is our target variable and aprat from it are our features.
# 4. bedrooms :- It determines number of bedrooms in a house.
# 5. bathrooms :- It determines number of bathrooms in a bedroom of a house.
# 6. sqft_living :- It is the measurement variable which determines the measurement of house in square foot.
# 7. sqft_lot : It is also the measurement variable which determines square foot of the lot.
# 8. floors: It determines total floors means levels of house.
# 9. waterfront : This feature determines whether a house has a view to waterfront 0 means no 1 means yes.
# 10. view : This feature determines whether a house has been viewed or not 0 means no 1 means yes.
# 11. condition : It determines the overall condition of a house on a scale of 1 to 5.
# 12. grade : It determines the overall grade given to the housing unit, based on King County grading system on a scale of 1 to 11.
# 13. sqft_above : It determines square footage of house apart from basement.
# 14. sqft_basement : It determines square footage of the basement of the house.
# 15. yr_built : It detrmines the date of building of the house.
# 16. yr_renovated : It detrmines year of renovation of house.
# 17. zipcode : It determines the zipcode of the location of the house.
# 18. lat : It determines the latitude of the location of the house.
# 19. long : It determines the longitude of the location of the house.
# 20. sqft_living15 : Living room area in 2015(implies-- some renovations)
# 21. sqft_lot15 : lotSize area in 2015(implies-- some renovations)
#
# Now, we know about the overall structure of a dataset . So let's apply some of the steps that we should generally do while applying OLS stats model.
#
# # STEP 1: IMPORTING LIBRARIES
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import seaborn as sns
from matplotlib import style
import matplotlib.cm as cm
from matplotlib import *
from scipy.stats import pearsonr
get_ipython().run_line_magic('matplotlib', 'inline')
# ### Exploring the whole dataset
#
# To get a sense for what is in the King County Housing dataset, first I will do some basic exploration of the entire dataset. After cleaning, another round of exploration will help clarify trends in the data specific to midrange housing.
# In[2]:
# Import needed packages and read in the data
data = pd.read_csv('kc_house_data.csv')
# In[3]:
# View first few rows of the dataset
data.head()
# # STEP 2: DATA CLEANING AND PREPROCESSING
#
# In this step we check whether data contain null or missing values. What is the size of the data. What is the datatype of each column. What are unique values of categorical variables etc.
# In[4]:
# View counts and data types by column
data.info()
# In[5]:
# Check for missing values by column
data.isna().sum()
# In[6]:
# Check for duplicate records
print('Number of duplicate records: ', sum(data.duplicated()))
# In[7]:
# Check for duplicate IDs
display(data['id'].value_counts().head())
# Count non-unique IDs
id_value_counts = data['id'].value_counts()
num_repeat_ids = len(id_value_counts[id_value_counts > 1])*2 + 1
print('Number of non-unique IDs: ', num_repeat_ids)
# In[8]:
# Inspect a few of the records with duplicate IDs
display(data[data['id'] == 795000620])
display(data[data['id'] == 1825069031])
display(data[data['id'] == 2019200220])
display(data[data['id'] == 7129304540])
display(data[data['id'] == 1781500435])
# In[9]:
data.describe()
# In[10]:
# Check the number of unique values in each column
unique_vals_list = []
for col in data.columns:
unique_vals_list.append({'column': col, 'unique values': len(data[col].unique())})
pd.DataFrame(unique_vals_list)
# In[11]:
# Define a function to create histograms
def hist_it(data):
"""Creates histograms of all numeric columns in a DataFrame"""
data.hist(figsize=(16,14))
# In[12]:
# Create histograms for numerical variables
data_for_hist = data.drop(['id'], axis=1)
hist_it(data_for_hist)
# # STEP 3 : FINDING CORRELATION
#
#
# In this step we check by finding correlation of all the features wrt target variable i.e., price to see whether they are positively correlated or negatively correlated to find if they help in prediction process in model building process or not. But this is also one of the most important step as it also involves domain knowledge of the field of the data means you cannot simply remove the feature from your prediction process just because it is negatively correlated because it may contribute in future prediction for this you should take help of some domain knowledge personnel.
# ### correlation using Heatmap
# In[13]:
sns.set(font_scale=2.2)
str_list = [] # empty list to contain columns with strings (words)
for colname, colvalue in data.iteritems():
if type(colvalue[1]) == str:
str_list.append(colname)
# Get to the numeric columns by inversion
num_list = data.columns.difference(str_list)
# Create Dataframe containing only numerical features
house_num = data[num_list]
f, ax = plt.subplots(figsize=(35, 30))
plt.title('Correlation of features')
# Draw the heatmap using seaborn
#sns.heatmap(house_num.astype(float).corr(),linewidths=0.25,vmax=1.0, square=True, cmap="PuBuGn", linecolor='k', annot=True)
sns.heatmap(house_num.astype(float).corr(),linewidths=2.0,vmax=1.0, square=True, cmap="YlGnBu", linecolor='k', annot=True)
plt.show()
# ### Initial cleaning
# In[14]:
(data['bedrooms']> 5).value_counts().to_frame()
# In[15]:
(data['price']< 1000000).value_counts().to_frame()
# ### Filter to focus on homes price under 1 Million?
# In[16]:
# Filter the dataset
midrange_homes = data[(data['price'] < 1000000)
& (data['bedrooms'].isin(range(2, 6)))]
# View the first few rows
midrange_homes.head()
# In[17]:
midrange_homes.shape
# In[18]:
midrange_homes.describe()
# In[19]:
# Check for missing values by column
midrange_homes.isna().sum()
# ### Resolve missing values
# In[20]:
# View value counts for 'waterfront'
midrange_homes['waterfront'].value_counts()
# In[21]:
# Print medians of homes with and without 'waterfront'
print(midrange_homes[midrange_homes['waterfront'] == 1]['price'].median())
print(midrange_homes[midrange_homes['waterfront'] == 0]['price'].median())
# In[22]:
# Fill NaNs with 0.0 because it is the mode
midrange_homes['waterfront'] = midrange_homes['waterfront'].fillna(0.0)
midrange_homes['waterfront'] = midrange_homes['waterfront'].astype('int64')
midrange_homes.info()
# ### view
# In[23]:
# Create a histogram of 'view' values
plt.figure(figsize=(10,6))
midrange_homes['view'].hist()
plt.title('Histogram of \'view\' values')
plt.xlabel('\'view\' values')
plt.ylabel('Count')
plt.show();
# In[24]:
# Fill NaNs with 0.0 and check that missing `view` values are now resolved
midrange_homes['view'] = midrange_homes['view'].fillna(0.0).astype('int64')
midrange_homes.info()
# ### yr_renovated
# In[25]:
# Create a histogram of 'yr_renovated' values
plt.figure(figsize=(10,6))
midrange_homes['yr_renovated'].hist()
plt.title('Histogram of \'yr_renovated\' values')
plt.xlabel('\'yr_renovated\' values')
plt.ylabel('Count')
plt.show();
# In[26]:
midrange_homes['yr_renovated'].value_counts().to_frame()
# Here we can see in yr_renovated columns alot of years data are misiing it is better to delete coulumn.
# ### Drop unneeded columns
# In[27]:
# Drop unneeded columns
midrange_homes.drop(['id', 'date', 'sqft_above', 'yr_renovated','sqft_basement'],
axis=1, inplace=True)
# Review the remaining columns
midrange_homes.info()
# ### After cleaning again checking correlation between features.
# In[28]:
# Create the correlation heatmap
data_for_scatter_matrix = midrange_homes.drop(['price'], axis=1)
plt.figure(figsize=(16,10))
sns.heatmap(data_for_scatter_matrix.corr(), center=0)
plt.title('Heatmap showing correlations between independent variables',
fontsize=18)
plt.show();
# In[29]:
# Check any number of columns with NaN or missing values
print(midrange_homes.isnull().any().sum(), ' / ', len(midrange_homes.columns))
# Check any number of data points with NaN
print(midrange_homes.isnull().any(axis=1).sum(), ' / ', len(midrange_homes))
# In[30]:
midrange_homes.isna().sum()
# In[31]:
midrange_homes.head()
# In[32]:
from scipy.stats import pearsonr
# In[33]:
features = midrange_homes.iloc[:,1:].columns.tolist()
target = midrange_homes.iloc[:,0].name
features
# In[34]:
type(target)
# In[35]:
(features)
# In[36]:
# Finding Correlation of price woth other variables to see how many variables are strongly correlated with price
correlations = {}
for f in features:
data_temp = midrange_homes[[f,target]]
x1 = data_temp[f].values
x2 = data_temp[target].values
key = f + ' vs ' + target
correlations[key] = pearsonr(x1,x2)[0]
# In[37]:
# Printing all the correlated features value with respect to price which is target variable
data_correlations = pd.DataFrame(correlations, index=['Value']).T
data_correlations.loc[data_correlations['Value'].abs().sort_values(ascending=False).index]
# # STEP 4 : EDA or DATA VISUALIZATION
#
# This is also a very important step in your prediction process as it help you to get aware you about existing patterns in the data how it is relating to your target variables etc.
# ### (1)What is the relationship between grade and price?
# In[38]:
# Create boxplots to compare 'grade' and 'price'
plt.figure(figsize=(10,8))
sns.boxplot(midrange_homes['grade'], midrange_homes['price'], color='skyblue')
plt.title('Distributions of prices for each grade', fontsize=18)
plt.xlabel('Grade')
plt.ylabel('Price (USD)')
plt.yticks([0, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000],
['0', '100k', '200k', '300k', '400k', '500k', '600k', '700k', '800k', '900k', '1M'])
plt.show();
# It looks like there could be substantial differences in price based on the grade of a house. For instance, only the outliers of grade-5 houses fall within the price range of grade-11 houses.
#
# Let's make a direct comparison between the median prices of grade-7 and grade-10 homes:
# In[39]:
grade_7_med = midrange_homes[midrange_homes['grade'] == 7]['price'].median()
grade_10_med = midrange_homes[midrange_homes['grade'] == 10]['price'].median()
grade_10_med - grade_7_med
# There is a huge difference (almost $420500.0) between the median prices of grade-7 and grade-10 homes. Improving the grade of a home by that much is probably outside the reach of most homeowners. What if a homeowner could improve the grade of their home from 7 to 8?
# In[40]:
grade_8_med = midrange_homes[midrange_homes['grade'] == 8]['price'].median()
grade_8_med - grade_7_med
# Based on the boxplots above, we can see that the jump in median price from grade 7 to grade 8 is a big one, but if a homeowner could manage it, it could pay off. The median price of a grade-8 home is $125500.0 higher than the median price of a grade-7 home. Again, this is without considering any other factors, like the size or condition of these homes.
# ### What is the relationship between bedrooms and price?
# In[41]:
# Create boxplots for 'bedrooms' v. 'price'
plt.figure(figsize=(10,8))
sns.boxplot(midrange_homes['bedrooms'], midrange_homes['price'], color='skyblue')
plt.title('Distributions of prices for each number of bedrooms', fontsize=18)
plt.xlabel('Number of bedrooms')
plt.ylabel('Price (USD)')
plt.yticks([0, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000],
['0', '100k', '200k', '300k', '400k', '500k', '600k', '700k', '800k', '900k', '1M'])
plt.show();
# In[42]:
# Calculate percent differences in median prices
medians = []
for n in range(2,6):
medians.append(midrange_homes[midrange_homes['bedrooms'] == n]['price'].median())
percent_differences = []
for m in range(0,len(medians)-1):
percent_differences.append(round(((medians[m+1] - medians[m]) / medians[m]),2))
percent_differences
# The biggest difference in median price is between four and three bedrooms, where there is an increase of 22%
# ### What is the relationship between floors and price?
# In[43]:
var = 'floors'
data = pd.concat([ midrange_homes['price'], midrange_homes[var]], axis=1)
f, ax = plt.subplots(figsize=(20, 20))
fig = sns.boxplot(x=var, y="price", data=data)
fig.axis(ymin=0, ymax=1000000);
# In[44]:
# # Create boxplots for 'floors' v. 'price'
# plt.figure(figsize=(10,8))
# sns.boxplot(midrange_homes['floors'], midrange_homes['price'], color='skyblue')
# plt.title('Distributions of prices for each number of floors', fontsize=18)
# plt.xlabel('Number of floors')
# plt.ylabel('Price (USD)')
# plt.yticks([0, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000],
# ['0', '100k', '200k', '300k', '400k', '500k', '600k', '700k', '800k', '900k', '1M'])
# plt.show();
# What is the relationship between bathrooms and price?
# In[45]:
var = 'bathrooms'
data = pd.concat([midrange_homes['price'], midrange_homes[var]], axis=1)
f, ax = plt.subplots(figsize=(20, 20))
fig = sns.boxplot(x=var, y="price", data=data)
fig.axis(ymin=0, ymax=1000000);
# # Where are the midrange homes in King County?
# In[46]:
# Define a function to create map-like scatter plots with color code
def locate_it(data, latitude, longitude, feature):
"""Create a scatterplot from lat/long data with color code.
Parameters:
data: a DataFrame
latitude: the name of the column in your DataFrame that contains
the latitude values. Pass this as a string.
longitude: the name of the column in your DataFrame that contains
the longitude values. Pass this as a string.
feature: the name of the column whose values you want to use as
the values for your color code. Pass this as a string.
Dependencies: matplotlib
Returns: scatterplot"""
plt.figure(figsize=(16,12))
cmap = plt.cm.get_cmap('RdYlBu')
sc = plt.scatter(data[longitude], data[latitude],
c=data[feature], vmin=min(data[feature]),
vmax=max(data[feature]), alpha=0.5, s=5, cmap=cmap)
plt.colorbar(sc)
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.title('House {} by location'.format(feature), fontsize=18)
plt.show();
# In[47]:
# Call locate_it for price by location
locate_it(midrange_homes, 'lat', 'long', 'price')
# In[48]:
# Call locate_it for sqft_living by location
locate_it(midrange_homes, 'lat', 'long', 'sqft_living')
# In[49]:
# Customize the plot for sqft_living by location
plt.figure(figsize=(16,12))
cmap = plt.cm.get_cmap('RdYlBu')
sc = plt.scatter(midrange_homes['long'], midrange_homes['lat'],
c=midrange_homes['sqft_living'],
vmin=min(midrange_homes['sqft_living']),
vmax=np.percentile(midrange_homes['sqft_living'], 90),
alpha=0.5, s=5, cmap=cmap)
plt.colorbar(sc)
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.title('House square footage by location\n(Darkest blue = 90th percentile of size)', fontsize=14)
plt.show();
# In[50]:
# Call locate_it for grade by location
locate_it(midrange_homes, 'lat', 'long', 'grade')
# In[51]:
locate_it(midrange_homes, 'lat', 'long', 'condition')
# In[52]:
list(features)
# In[53]:
target
# In[54]:
feature_matrix = midrange_homes[features]
#feature_matrix = preprocessing.scale(feature_matrix)
feature_matrix_unscaled = midrange_homes[features]
lable_vector = midrange_homes['price']
feature_matrix_unscaled.head()
#feature_matrix[0::1000]
# In[55]:
style.use('fivethirtyeight')
cm = plt.cm.get_cmap('RdYlBu')
xy = range(19648)
z = xy
for feature in feature_matrix_unscaled:
sc = plt.scatter(midrange_homes[feature], midrange_homes['price'], label = feature, c = z, marker = 'o', s = 30, cmap = cm)
plt.colorbar(sc)
plt.xlabel(''+feature)
plt.ylabel('price')
plt.yticks([0, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000],
['0', '100k', '200k', '300k', '400k', '500k', '600k', '700k', '800k', '900k', '1M'])
plt.legend()
plt.show()
# # Final preprocessing
# In[56]:
# Generate dummy variables
zip_dummies = pd.get_dummies(midrange_homes['zipcode'], prefix='zip')
# In[57]:
# Drop the original 'zipcode' column
mh_no_zips = midrange_homes.drop('zipcode', axis=1)
# Concatenate the dummies to the copy of 'midrange_homes'
mh_zips_encoded = pd.concat([mh_no_zips, zip_dummies], axis=1)
# Preview the new DataFrame
mh_zips_encoded.head()
# In[58]:
# Drop one of the dummy variables
mh_zips_encoded.drop('zip_98168', axis=1, inplace=True)
# Check the head again
mh_zips_encoded.head()
# # Creating the model
# In[59]:
# Import statsmodels
import statsmodels.api as sm
from statsmodels.formula.api import ols
# In[60]:
# Split the cleaned data into features and target
mh_features = midrange_homes.drop(['price'], axis=1)
mh_target = midrange_homes['price']
# In[61]:
# Define a function to run OLS and return model summary
def model_it(data, features):
"""Fit an OLS model and return model summary
data: a DataFrame containing both features and target
features: identical to 'data', but with the target dropped"""
features_sum = '+'.join(features.columns)
formula = 'price' + '~' + features_sum
model = ols(formula=formula, data=data).fit()
return model.summary()
# In[62]:
# Fit the model and return summary
model_it(midrange_homes, mh_features)
# # Second model
# In[63]:
# Drop unwanted features and rerun the modeling function
mh_features_fewer = mh_features.drop(['long', 'sqft_lot15'], axis=1)
model_it(midrange_homes, mh_features_fewer)
# # Third model
# In[64]:
# Split the data into features and target
mh_zips_encoded_features = mh_zips_encoded.drop(['price'], axis=1)
mh_zips_encoded_target = mh_zips_encoded['price']
# In[65]:
model_it(mh_zips_encoded, mh_zips_encoded_features)
# In[66]:
mh_zips_encoded_features.head()
# In[67]:
final_data = mh_zips_encoded_features.drop(['long','sqft_lot15','zip_98001','zip_98002','zip_98003','zip_98019','zip_98022','zip_98030'], axis =1)
# In[68]:
f_data =final_data.drop(['zip_98031','zip_98042','zip_98055','zip_98058','zip_98092','zip_98178','zip_98188','zip_98198'], axis = 1)
# In[69]:
f_data.head()
# In[70]:
X = f_data
y = mh_zips_encoded['price']
Xconst = sm.add_constant(X)
model = sm.OLS(y, Xconst, hasconst= True)
fitted_model = model.fit()
fitted_model.summary()
# In[71]:
X = f_data
y = mh_zips_encoded['price']
# Xconst = sm.add_constant(X)
model = sm.OLS(y, X)
fitted_model = model.fit()
fitted_model.summary()
#
# Conclusion
#
# So, we have seen that accuracy of OLS is around 82.9%.
<file_sep>/README.md
# KC_House_Price

|
6da666308d2d70b45a7c01cc93e44d2a574bdf33
|
[
"Markdown",
"Python"
] | 2 |
Python
|
MAhsanmirza/kc_house_price-prediction
|
0a0abaca0aceeaf54afc9ad61add18ef818af46d
|
5c036b91586ed7d4d696ef9c58094aacb74be29b
|
refs/heads/master
|
<file_sep># Financy
a dashboard which shows stockprices, commodities, cryptocurrencies and exchangerates
currently frankensteinlike app from a js newbie going the TDD route
# Uses
CasperJS
Jasmine<file_sep>describe("Finance", function() {
var finance;
beforeEach(function() {
finance = new Finance();
});
describe("when looking for the Sector of the Yahoo stock", function() {
it("should be 'Technology'", function() {
stockObj = finance.getStockInfos("YHOO");
expect(stockObj.Sector).toEqual("Technology");
});
});
describe("when looking for the trade price of the Yahoo stock", function() {
it("should contain the name of the company", function() {
quoteObj = finance.getQuoteInfos("YHOO");
expect(quoteObj.Name).toEqual("Yahoo Inc.");
});
});
describe("when looking for the trade price of the Yahoo" +
" stock in a timeframe", function() {
it("should contain the Date and ClosingPrices of these days",
function() {
DatePrices = finance.getHistoricalInfos("YHOO", "2012-01-03",
"2012-01-07");
Price = DatePrices[1];
expect(Price[0]).toEqual(16.29);
expect(Price[1]).toEqual(15.78);
expect(Price[2]).toEqual(15.64);
expect(Price[3]).toEqual(15.52);
Dates = DatePrices[0];
expect(Dates[0]).toEqual("2012-01-03");
expect(Dates[1]).toEqual("2012-01-04");
expect(Dates[2]).toEqual("2012-01-05");
expect(Dates[3]).toEqual("2012-01-06");
});
});
});
<file_sep>casper.test.begin('Stockform can be submitted', 1, function(test) {
casper.start('file:///home/xorrr/devel/financy/index.html', function() {
this.fill('form#addstock', {'symbol':'yhoo', 'startDate':'2012-01-03',
'endDate':'2012-01-07'}, true);
});
casper.then(function() {
canvas = this.evaluate(function() {
return __utils__.findOne('#stock1');
});
test.assertEquals(canvas.className, 'drawn', "stockchart was drawn");
});
casper.run(function() {
test.done();
});
});
<file_sep>function Finance() {
this.baseUri = "http://query.yahooapis.com/v1/public/yql?q=";
this.suffix = "&format=json&env=store://datatables.org/alltableswithkeys";
}
Finance.prototype.getStockInfos = function(symbol) {
var fullUri = this.buildUrl(this.encodeQuery(buildStockQuery(symbol)));
var responseText = requestInfos(fullUri);
return getStockObject(responseText);
};
Finance.prototype.getQuoteInfos = function(symbol) {
var fullUri = this.buildUrl(this.encodeQuery(buildQuoteQuery(symbol)));
var responseText = requestInfos(fullUri);
return getQuoteObject(responseText);
};
Finance.prototype.getHistoricalInfos = function(symbol, startDate, endDate) {
fullUri = this.buildUrl(this.encodeQuery(buildHistoricalQuery(symbol,
startDate
, endDate
)));
var responseText = requestInfos(fullUri);
return getHistoricalPrices(responseText);
};
Finance.prototype.encodeQuery = function(query) {
return encodeURIComponent(query);
};
function buildStockQuery(symbol) {
return 'select * from yahoo.finance.stocks where symbol="'
+ symbol + '"';
};
function buildQuoteQuery(symbol) {
return 'select * from yahoo.finance.quote where symbol="'
+ symbol + '"';
};
function buildHistoricalQuery(symbol, startDate, endDate) {
return 'select * from yahoo.finance.historicaldata where symbol = "'
+ symbol + '" and startDate = "' + startDate + '" and endDate = "'
+ endDate + '"';
};
Finance.prototype.buildUrl = function(encodedQuery) {
return this.baseUri + encodedQuery + this.suffix;
};
function requestInfos(uri) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", uri, false);
xmlHttp.send(null);
return xmlHttp.responseText;
};
function getStockObject(responseText) {
var parsedStock = JSON.parse(responseText);
return parsedStock.query.results.stock;
};
function getQuoteObject(responseText) {
var parsedQuote = JSON.parse(responseText);
return parsedQuote.query.results.quote;
};
function getHistoricalQuoteArray(responseText) {
var parsedResponse = JSON.parse(responseText);
return parsedResponse.query.results.quote;
};
function addClosingPricesToPrices(obj, key) {
if (key === "Close") {
Prices.push(parseFloat(obj[key]));
}
};
function addDateToDates(obj, key) {
if (key === "Date") {
Dates.push(obj[key]);
}
};
function iterateTheKeysInQuote(obj) {
for (var key in obj) {
addClosingPricesToPrices(obj, key);
addDateToDates(obj, key);
}
}
function iterateTheQuoteArray(parsedHistoricalQuoteArray) {
for (var i=parsedHistoricalQuoteArray.length; i>0;i--) {
var obj = parsedHistoricalQuoteArray[i-1];
iterateTheKeysInQuote(obj);
}
}
function getHistoricalPrices(responseText) {
var Prices = new Array();
var Dates = new Array();
var parsedHistoricalQuoteArray = getHistoricalQuoteArray(responseText);
iterateTheQuoteArray(parsedHistoricalQuoteArray);
var DatePrices = new Array();
DatePrices.push(Dates);
DatePrices.push(Prices);
return DatePrices;
};
|
6a4b12a065849e89f34f17b2fe255da72ef4352f
|
[
"Markdown",
"JavaScript"
] | 4 |
Markdown
|
xorrr/financy
|
01488d7803f14f1e65495d8443dc577c2ad9dea9
|
2ff6b2e498cf594d40ba6e1ac956e03dce730c9a
|
refs/heads/master
|
<repo_name>nadeemshahzad/python-port-scanner<file_sep>/README.md
Python Port Scanner
Usage:
python network_scan.py
Script will ask for input of target machine to scan for exposed ports
Enter hostname: xyz.com
Enter initial port value: 80
Enter final port range: 896
<file_sep>/port_scanner.py
import socket
import threading
class PortScanner(object):
def __init__(self,hostname,s_port,f_port):
self.hostname=hostname
self.s_port=s_port
self.f_port=f_port
self.ip=socket.gethostbyname(self.hostname)
''' This method use python socket to connect with remote host
on specified port. Sockettimeout is set to 1 second this
count port close if socket not respond within this time '''
def port_scan(self,port):
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.settimeout(1)
try:
result=s.connect_ex((self.ip,port))
except Exception as e:
print e
if result==0:
print "[+] port is open %d"%port
s.close()
''' Thread is spawned for each socket connection given port
range should be in limit defined for user in operating
system running the script.This can be checked with `ulimit -a`'''
def start_scan(self):
for port in xrange(self.s_port,self.f_port):
t=threading.Thread(target=self.port_scan,args=(port,))
t.start()
host_name=raw_input("Hostname to scan: ")
s_port=input("Initial Port:")
f_port=input("Final Port:")
p_s=PortScanner(host_name,s_port,f_port)
p_s.start_scan()
|
849d74d1830878793b4a64540d665776328aaf5b
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
nadeemshahzad/python-port-scanner
|
53570e3ff8922a73115cbfc27f036bf9dbfbc26a
|
adce9791d699803e8a0d3ce693724cdd04a6eb36
|
refs/heads/main
|
<repo_name>MaxSomewhere/LKtests<file_sep>/cypress/pageobject/loginForm.js
let inputSelectAuth = '.select-styled';
let inputContractLogin = 'input[id="userid"]';
let inputContractPassword = 'input[name="userpassword"]';
let buttonSubmit = 'button[class="btn shadow login-btn"]';
let inputEmailLogin = 'input[name="useremail"]';
let inputEmailPassword = 'input[name="emailpassword"]';
export class AuthLoginform {
//Выбор способа авторизации
selectAuthInput (selectInput) {
cy.get(inputSelectAuth).click()
cy.get(selectInput).click({ force: true })
}
//Авторизация при помощи номера договора
userAuthContract(login, password) {
cy.get(inputContractLogin).clear().type(login)
cy.get(inputContractPassword).clear().type(password)
cy.get(buttonSubmit).click()
}
//Авторизация при помощи логина
userAuthLogin(login, password) {
cy.get(inputLogin).clear().type(login)
cy.get(inputPassword).clear().type(password)
cy.get(buttonSubmit).click()
}
//Авторизация при помощи Email
userAuthEmail(login, password) {
cy.get(inputEmailLogin).clear().type(login)
cy.get(inputEmailPassword).clear().type(password)
cy.get(buttonSubmit).click()
}
}
export const loginForm = new AuthLoginform()<file_sep>/cypress/integration/Auth.spec.js
const { loginForm } = require("../pageobject/loginForm")
describe ("Log in", () => {
beforeEach(() => {
cy.viewport(1920, 1080)
})
let selectAuthContract = '[rel="user"]';
let selectAuthEmail = '[rel="email"]';
it ("Валидация полей при авторизации с № Договора (негативное тестирование)",() => {
cy.fixture('lktests').then(lk => {
cy.visit(lk.baseUrl)
//Выбор метода авторизации "№ Договора + пароль"
loginForm.selectAuthInput(selectAuthContract)
//Авторизация с невалидным № Договора
loginForm.userAuthContract(lk.invalidAkkNum , lk.correctAkkPass)
cy.url().should('eq', lk.baseUrl)
//Авторизация с некорректным № Договора
loginForm.userAuthContract(lk.incorrectAkkNum , lk.correctAkkPass)
cy.url().should('eq', lk.baseUrl)
//Авторизация с корректным № Договора и некорректным паролем
loginForm.userAuthContract(lk.correctAkkNum , lk.incorrectAkkPass)
cy.url().should('eq', lk.baseUrl)
})
})
it ("Валидация полей при авторизации с № Договора(позитивное тестирование)",() => {
cy.fixture('lktests').then(lk => {
cy.visit(lk.baseUrl)
//Выбор метода авторизации "№ Договора + пароль"
loginForm.selectAuthInput(selectAuthContract)
//Авторизация с корректным № Договора и корректным паролем
loginForm.userAuthContract(lk.correctAkkNum , lk.correctAkkPass)
cy.url().should('eq', 'https://stat.briz.ua/')
})
})
it ("Валидация полей при авторизации с Email(негативное тестирование)",() => {
cy.fixture('lktests').then(lk => {
cy.visit(lk.baseUrl)
//Выбор метода авторизации "Email + пароль"
loginForm.selectAuthInput(selectAuthEmail)
//Авторизация с невалидным Email
loginForm.userAuthEmail(lk.invalidEmail , lk.correctAkkPass)
cy.url().should('eq', lk.baseUrl)
//Авторизация с некорректным Email
loginForm.userAuthEmail(lk.incorrectEmail , lk.correctAkkPass)
cy.url().should('eq', lk.baseUrl)
//Авторизация с корректным Email и некорректным паролем
loginForm.userAuthEmail(lk.correctEmail , lk.incorrectAkkPass)
cy.url().should('eq' , lk.baseUrl)
})
})
it ("Валидация полей при авторизации с Email(позитивное тестирование)",() => {
cy.fixture('lktests').then(lk => {
cy.visit(lk.baseUrl)
//Выбор метода авторизации "Email + пароль"
loginForm.selectAuthInput(selectAuthEmail)
//Авторизация с корректным Email и корректным паролем
loginForm.userAuthEmail(lk.correctEmail, lk.correctAkkPass)
cy.url().should('eq', 'https://stat.briz.ua/')
})
})
})
|
eaa370052f44e27e0936603d24bc7e47ec2d74bc
|
[
"JavaScript"
] | 2 |
JavaScript
|
MaxSomewhere/LKtests
|
e75aad97bce18bb07b70b1c8e8684573acd1a673
|
a03e614f707ff13b17d7049fc0cf97d16b7db4af
|
refs/heads/master
|
<file_sep>package com.umeng.soexample;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* Created by W on 2019/1/17 9:06.
*/
public class DdCountView extends RelativeLayout {
private int mnumber = 0;
private TextView send_count_minus;
private TextView send_count_number;
private TextView send_count_plus;
public DdCountView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.add_remove_view, this);
initView();
}
private void initView() {
send_count_minus = findViewById(R.id.delete_dt);
send_count_number = findViewById(R.id.product_number_tv);
send_count_plus = findViewById(R.id.add_dt);
}
public void setNumber(int number) {
mnumber = number;
send_count_number.setText(mnumber + "");
}
}
<file_sep>package com.umeng.soexample.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.umeng.soexample.R;
import com.umeng.soexample.bean.Address;
import com.umeng.soexample.bean.Quanzi;
import java.util.List;
/**
* Created by W on 2019/1/11 19:09.
*/
public class AddressAdapter extends RecyclerView.Adapter<AddressAdapter.ViewHolder> {
private List<Address.ResultBean> list;
private Context context;
public AddressAdapter(List<Address.ResultBean> list, Context context) {
this.list = list;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
ViewHolder holder = null;
View view = LayoutInflater.from(context).inflate(R.layout.address_item,parent,false);
holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
holder.address_preson_name.setText(list.get(position).getRealName());
holder.address_preson_phone.setText(list.get(position).getPhone());
holder.address_preson_dizhi.setText(list.get(position).getAddress());
holder.address_check.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (listener!=null){
listener.onItemClick(view,position,list.get(position).getId());
}
}
});
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView address_preson_name;
private TextView address_preson_phone;
private TextView address_preson_dizhi;
private TextView address_check;
private TextView address_update;
private TextView address_delete;
public ViewHolder(View itemView) {
super(itemView);
address_preson_name = itemView.findViewById(R.id.address_preson_name);
address_preson_phone = itemView.findViewById(R.id.address_preson_phone);
address_preson_dizhi = itemView.findViewById(R.id.address_preson_dizhi);
address_check = itemView.findViewById(R.id.address_check);
address_update = itemView.findViewById(R.id.address_update);
address_delete = itemView.findViewById(R.id.address_delete);
}
}
public RexiaoAdapter.OnItemClickListener listener;
public interface OnItemClickListener{
void onItemClick(View v,int positon ,int id);
}
public void setClick(RexiaoAdapter.OnItemClickListener listener){
this.listener = listener;
}
}
<file_sep>package com.umeng.soexample;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.umeng.soexample.adapter.SubmitAdaptr;
import com.umeng.soexample.bean.OrderBean;
import com.umeng.soexample.bean.Submit;
import com.umeng.soexample.presenter.PresenterImpl;
import com.umeng.soexample.presenter.ShouPresenterImpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class TijiaoActivity<T> extends AppCompatActivity implements IView<T>, View.OnClickListener {
private RecyclerView mCreatePostRecycle;
private TextView mCreatePayment;
private TextView mCreateSubmission;
private SubmitAdaptr submitAdaptr;
private ArrayList<Submit> submit;
private ShouPresenterImpl presenter;
private int userId;
private String sessionId;
private int allGoodsPrice;
private TextView mTextAddress;
private RecyclerView mRecyAddress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tijiao);
initView();
}
private void initView() {
presenter = new ShouPresenterImpl(this);
Intent intent = getIntent();
submit = intent.getParcelableArrayListExtra("submit");
Log.e("submit", submit.toString());
mCreatePostRecycle = (RecyclerView) findViewById(R.id.create_post_recycle);
mCreatePayment = (TextView) findViewById(R.id.create_payment);
mCreateSubmission = (TextView) findViewById(R.id.create_Submission);
mCreateSubmission.setOnClickListener(this);
LinearLayoutManager manager = new LinearLayoutManager(this);
mCreatePostRecycle.setLayoutManager(manager);
submitAdaptr = new SubmitAdaptr(submit,this);
mCreatePostRecycle.setAdapter(submitAdaptr);
submitAdaptr.notifyDataSetChanged();
flushBottomLayout();
mCreatePostRecycle.addItemDecoration(new SpaceItemDecoration(20));
}
private void flushBottomLayout() {
int allGoodsNumber = submitAdaptr.getCount();
allGoodsPrice = submitAdaptr.getSumPrice();
mCreatePayment.setText("共" + allGoodsNumber + "件商品需付款" + allGoodsPrice + "元");
}
@Override
public void success(Object data) {
if (data instanceof OrderBean) {
Toast.makeText(this, ((OrderBean) data).getMessage(), Toast.LENGTH_SHORT).show();
if(((OrderBean) data).getStatus().equals("0000"))
{
finish();
}
}
}
@Override
public void error(Object error) {
if (error instanceof OrderBean) {
Toast.makeText(this, error.toString(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.create_Submission:
SharedPreferences shopping = getSharedPreferences("ischeck", Context.MODE_PRIVATE);
userId = shopping.getInt("userId", 0);
sessionId = shopping.getString("sessionId", null);
Map<String, String> body = new HashMap<>();
Map<String, String> head = new HashMap<>();
head.put("userId", userId+"");
head.put("sessionId", sessionId);
body.put("orderInfo", submit.toString());
body.put("totalPrice", allGoodsPrice+"");
body.put("addressId", 650+"");
presenter.post(Contacts.DINGDAN, body, head, OrderBean.class);
break;
}
}
class SpaceItemDecoration extends RecyclerView.ItemDecoration {
int mSpace;
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
outRect.left = mSpace;
outRect.right = mSpace;
outRect.bottom = mSpace;
if (parent.getChildAdapterPosition(view) == 0) {
outRect.top = mSpace;
}
}
public SpaceItemDecoration(int space) {
this.mSpace = space;
}
}
}
<file_sep>package com.umeng.soexample;
import android.webkit.WebView;
import com.umeng.soexample.presenter.ShouPresenter;
/**
* 用来存放所有接口
*/
public class Contacts {
//总接口前缀
//public static final String BASE_URL = "http://mobile.bwstudent.com/small/";
public static final String BASE_URL = "http://172.17.8.100/small/";
public static final String USER_UPDATENAME = "user/verify/v1/modifyUserNick";
public static final String USER_UPDATPWD = "user/verify/v1/modifyUserPwd";
public static final String SHOU_SHOP = "commodity/v1/commodityList";
public static final String SHOU_SHOP_SOUSUO = "commodity/v1/findCommodityByKeyword";
public static final String QUAN_QUERY = "circle/v1/findCircleList";
public static final String SHOU_XIANGQING = "commodity/v1/findCommodityDetailsById";
public static final String SHOU_PINLIN = "commodity/v1/CommodityCommentList";
//查询购物车
public static final String GWC_QUERY = "order/verify/v1/findShoppingCart";
//同步购物车
public static final String GWC_ADD = "order/verify/v1/syncShoppingC" +
"art";
//地址列表
public static final String ADDRESS_LIST = "user/verify/v1/receiveAddressList";
public static final String ADDRESS_ADD = "user/verify/v1/addReceiveAddress";
public static final String DINGDAN = "order/verify/v1/createOrder";
public static final String DINGDAN_QUE = "order/verify/v1/findOrderListByStatus";
}
<file_sep>package com.umeng.soexample.fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import com.umeng.soexample.Contacts;
import com.umeng.soexample.IView;
import com.umeng.soexample.R;
import com.umeng.soexample.TijiaoActivity;
import com.umeng.soexample.adapter.GwcAdapter;
import com.umeng.soexample.bean.Querygwc;
import com.umeng.soexample.bean.Submit;
import com.umeng.soexample.presenter.ShouPresenterImpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
/**
* A simple {@link Fragment} subclass.
*/
public class GouFragment<T> extends Fragment implements IView<T>, View.OnClickListener {
@BindView(R.id.query_gwc)
RecyclerView queryGwc;
@BindView(R.id.check)
CheckBox check;
@BindView(R.id.gou_heji)
TextView gouHeji;
@BindView(R.id.js)
TextView js;
Unbinder unbinder;
private ShouPresenterImpl presenter;
private GwcAdapter adapter;
private SharedPreferences sp;
private List<Querygwc.ResultBean> mList = new ArrayList<>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_gou, container, false);
unbinder = ButterKnife.bind(this, view);
sp = getActivity().getSharedPreferences("ischeck", Context.MODE_PRIVATE);
presenter = new ShouPresenterImpl(this);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
queryGwc.setLayoutManager(layoutManager);
Map<String,String> headmap = new HashMap<>();
int userId = sp.getInt("userId",0);
String sessionId = sp.getString("sessionId",null);
headmap.put("userId",userId+"");
headmap.put("sessionId",sessionId);
adapter = new GwcAdapter(mList,getActivity());
queryGwc.setAdapter(adapter);
Map<String,Object> map = new HashMap<>();
presenter.startShoushop(Contacts.GWC_QUERY,null,headmap,Querygwc.class);
js.setOnClickListener(this);
adapter.setOnItemClick(new GwcAdapter.OnItemClick() {
@Override
public void onClick(View view, int position) {
boolean status = adapter.thisCheckStatus(position);
adapter.setCheckStatus(position, !status);
adapter.notifyDataSetChanged();
FlushFooter();
}
@Override
public void onDelete(View view, int position) {
mList.remove(position);
adapter.notifyDataSetChanged();
FlushFooter();
}
@Override
public void onNumber(int position, int number) {
adapter.setShopCount(position, number);
adapter.notifyDataSetChanged();
FlushFooter();
}
});
check.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean status = adapter.allCheckStatus();
adapter.setAllCheckStatus(!status);
check.setChecked(!status);
adapter.notifyDataSetChanged();
FlushFooter();
}
});
return view;
}
private void FlushFooter() {
boolean status = adapter.allCheckStatus();
check.setChecked(status);
double allPrice = adapter.getAllPrice();
gouHeji.setText("¥" + allPrice);
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@Override
public void success(T data) {
Querygwc querygwc = (Querygwc) data;
mList.clear();
mList.addAll(querygwc.getResult());
adapter.notifyDataSetChanged();
}
@Override
public void error(T error) {
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.js:
Intent intent = new Intent(getActivity(), TijiaoActivity.class);
List<Submit> list = new ArrayList<>();
for (int i = 0; i < mList.size(); i++) {
if (mList.get(i).isChildCheck() == true) {
Submit bean = new Submit(mList.get(i).getCommodityId(), mList.get(i).getCount(), mList.get(i)
.getCommodityName(), mList.get(i).getCount(), mList.get(i).getPic(), mList.get(i).getPrice());
list.add(bean);
}
}
intent.putParcelableArrayListExtra("submit", (ArrayList<? extends Parcelable>) list);
startActivity(intent);
break;
}
}
}
<file_sep>package com.umeng.soexample.utils;
import java.util.concurrent.TimeUnit;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* Created by W on 2018/12/28.
*/
public class OKHttpUtils {
private OkHttpClient okHttpClient;
private OKHttpUtils() {
//日志拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.callTimeout(20, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
.build();
}
public static OKHttpUtils getInstance() {
return OkHolder.okUtils;
}
static class OkHolder {
private static final OKHttpUtils okUtils = new OKHttpUtils();
}
//get
public void getAsync(String url, Callback callback) {
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(callback);
}
//post
public void postAsync(String url, Callback callback) {
RequestBody body = new FormBody.Builder().add("key", "value").build();
Request request = new Request.Builder().url(url).post(body).build();
okHttpClient.newCall(request).enqueue(callback);
}
}
<file_sep>package com.umeng.soexample;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.umeng.soexample.adapter.AddressAdapter;
import com.umeng.soexample.bean.Address;
import com.umeng.soexample.presenter.ShouPresenterImpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
public class AddressActivity<T> extends AppCompatActivity implements IView<T>, View.OnClickListener {
@BindView(R.id.shouhuodizhi)
TextView shouhuodizhi;
@BindView(R.id.address_finsh)
TextView addressFinsh;
@BindView(R.id.add_address)
Button addAddress;
@BindView(R.id.recy_address)
RecyclerView recyAddress;
private ShouPresenterImpl presenter;
private AddressAdapter addressAdapter;
private List<Address.ResultBean> mList = new ArrayList<>();
private SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_address);
ButterKnife.bind(this);
presenter = new ShouPresenterImpl(this);
addressAdapter = new AddressAdapter(mList,this);
recyAddress.setAdapter(addressAdapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyAddress.setLayoutManager(layoutManager);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
}
@Override
protected void onStart() {
super.onStart();
sp = this.getSharedPreferences("ischeck", MODE_PRIVATE);
String sessionId = sp.getString("sessionId", null);
int userId = sp.getInt("userId", 0);
Map<String,String> head = new HashMap<>();
head.put("userId",userId+"");
head.put("sessionId",sessionId);
presenter.startShoushop(Contacts.ADDRESS_LIST,null,head,Address.class);
addAddress.setOnClickListener(this);
}
@Override
public void success(Object data) {
Address address = (Address) data;
mList.clear();
mList.addAll(address.getResult());
addressAdapter.notifyDataSetChanged();
}
@Override
public void error(Object error) {
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.add_address:
Intent intent = new Intent(this,AddActivity.class);
startActivity(intent);
break;
}
}
}
<file_sep>package com.umeng.soexample;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.umeng.soexample.bean.Update;
import com.umeng.soexample.presenter.ShouPresenterImpl;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ZiliaoActivity<T> extends AppCompatActivity implements IView<T> {
@BindView(R.id.my_ziliao_tx)
ImageView myZiliaoTx;
@BindView(R.id.my_ziliao_name)
EditText myZiliaoName;
@BindView(R.id.my_ziliao_pwd)
EditText myZiliaoPwd;
@BindView(R.id.info)
LinearLayout info;
private SharedPreferences sp;
private InputMethodManager imm;
private ShouPresenterImpl presenter;
private String nickName_update;
private String sessionId;
private int userId;
private String pwd_update;
private String headPic;
private String nickName;
private String pwd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ziliao);
ButterKnife.bind(this);
sp = this.getSharedPreferences("ischeck", MODE_PRIVATE);
headPic = sp.getString("headPic", null);
nickName = sp.getString("nickName", null);
pwd = sp.getString("pwd", null);
sessionId = sp.getString("sessionId", null);
userId = sp.getInt("userId", 0);
presenter = new ShouPresenterImpl(this);
Glide.with(this).load(headPic).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(myZiliaoTx);
myZiliaoName.setText(nickName);
myZiliaoPwd.setText(pwd);
}
@OnClick(R.id.info)
public void onViewClicked() {
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
}
@Override
protected void onPause() {
super.onPause();
nickName_update = myZiliaoName.getText().toString().trim();
sp.edit().putString("nickName", nickName_update).commit();
pwd_update = myZiliaoPwd.getText().toString().trim();
sp.edit().putString("pwd", pwd_update).commit();
}
@Override
protected void onDestroy() {
super.onDestroy();
HashMap<String, Object> map = new HashMap<>();
map.put("nickName", nickName_update);
Map<String, String> mapHeader = new HashMap<>();
mapHeader.put("userId", userId+"");
mapHeader.put("sessionId", sessionId);
HashMap<String, Object> mapPwd = new HashMap<>();
mapPwd.put("oldPwd", pwd);
mapPwd.put("newPwd", pwd_update);
if (!nickName_update.equals(nickName)) {
Log.e("修改昵称", nickName_update);
presenter.startRequest(Contacts.USER_UPDATENAME, map, mapHeader, Update.class);
}
if (!pwd_update.equals(pwd)) {
Log.e("修改密码", pwd_update);
presenter.startRequest(Contacts.USER_UPDATPWD, mapPwd, mapHeader, Update.class);
}
}
@Override
public void success(T data) {
if (data instanceof Update) {
Toast.makeText(this, ((Update) data).getMessage(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void error(T error) {
}
}
<file_sep>package com.umeng.soexample.model;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.google.gson.Gson;
import com.umeng.soexample.bean.Login;
import com.umeng.soexample.bean.Register;
import com.umeng.soexample.callback.MyCallBack;
import com.umeng.soexample.utils.HttpUtils;
/**
* Created by W on 2018/12/29.
*/
public class ModelImpl implements Model {
private MyCallBack callBack;
private int type;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (type){
case 1:
String jsonStr = (String) msg.obj;
Gson gson = new Gson();
Login login = gson.fromJson(jsonStr,Login.class);
callBack.setSuccess(login);
break;
case 2:
String jsonStr1 = (String) msg.obj;
Gson gson1 = new Gson();
Register register = gson1.fromJson(jsonStr1,Register.class);
callBack.setSuccess(register);
break;
}
}
};
@Override
public void getData(final String url, final String name, final String password, int type, final MyCallBack callBack) {
this.callBack = callBack;
this.type = type;
new Thread(new Runnable() {
@Override
public void run() {
try {
String jsonStr = HttpUtils.post(url, name, password);
handler.sendMessage(handler.obtainMessage(0, jsonStr));
} catch (Exception e) {
Looper.prepare();
callBack.setError("异常");
Looper.loop();
}
}
}).start();
}
}
<file_sep>package com.umeng.soexample.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.umeng.soexample.R;
import com.umeng.soexample.bean.AllDingdan;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by W on 2019/1/16 10:18.
*/
public class AllddAdapter extends RecyclerView.Adapter<AllddAdapter.ViewHolder> {
private List<AllDingdan.OrderListBean> list;
private Context context;
public AllddAdapter(List<AllDingdan.OrderListBean> list, Context context) {
this.list = list;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
ViewHolder holder = null;
View view = LayoutInflater.from(context).inflate(R.layout.dingdan_item,parent,false);
holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
holder.orderPendingPaymentNumber.setText(list.get(position).getOrderId());
holder.orderPendingPaymentSize.setText(list.get(position).getDetailList().size() + "");
holder.orderPendingPaymentPrice.setText(list.get(position).getPayAmount() + "");
holder.orderPendingPaymentRecycle.setLayoutManager(new LinearLayoutManager(context));
DingpageAdapter adapter = new DingpageAdapter((ArrayList<AllDingdan.OrderListBean.DetailListBean>) list.get(position).getDetailList(),context);
holder.orderPendingPaymentRecycle.setAdapter(adapter);
holder.orderPendingPaymentCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (itemClick != null) {
itemClick.cancel(v, position);
}
}
});
holder.orderPendingPaymentPayment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (itemClick != null) {
itemClick.pay(v, position);
}
}
});
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.order_PendingPayment_ddh)
TextView orderPendingPaymentDdh;
@BindView(R.id.order_PendingPayment_number)
TextView orderPendingPaymentNumber;
@BindView(R.id.order_PendingPayment_time)
TextView orderPendingPaymentTime;
@BindView(R.id.order_PendingPayment_recycle)
RecyclerView orderPendingPaymentRecycle;
@BindView(R.id.order_PendingPayment_size)
TextView orderPendingPaymentSize;
@BindView(R.id.order_PendingPayment_price)
TextView orderPendingPaymentPrice;
@BindView(R.id.order_PendingPayment_lin)
LinearLayout orderPendingPaymentLin;
@BindView(R.id.order_PendingPayment_cancel)
Button orderPendingPaymentCancel;
@BindView(R.id.order_PendingPayment_payment)
Button orderPendingPaymentPayment;
public ViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
public interface itemClick {
void pay(View v, int position);
void cancel(View v, int position);
void queren(View v, int position);
}
private itemClick itemClick;
public void setItemClick(itemClick itemClick) {
this.itemClick = itemClick;
}
}
<file_sep>package com.umeng.soexample.base;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by W on 2018/12/26.
*/
public abstract class BaseActivity extends AppCompatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
previewAction();
setContentView(getContentView());
initView();
initData();
setListener();
setMoreAction();
}
protected void previewAction() {
}
protected abstract int getContentView();
protected abstract void initView();
protected void initData() {
}
protected void setListener() {
}
protected void setMoreAction() {
}
}
<file_sep>package com.umeng.soexample.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.umeng.soexample.CountView;
import com.umeng.soexample.DdCountView;
import com.umeng.soexample.R;
import com.umeng.soexample.bean.AllDingdan;
import java.util.ArrayList;
import java.util.List;
/**
* Created by W on 2019/1/16 14:32.
*/
public class DingpageAdapter extends RecyclerView.Adapter<DingpageAdapter.ViewHolder> {
private List<AllDingdan.OrderListBean.DetailListBean> list;
private Context context;
public DingpageAdapter(List<AllDingdan.OrderListBean.DetailListBean> list, Context context) {
this.list = list;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
ViewHolder holder = null;
View view = LayoutInflater.from(context).inflate(R.layout.ding_page_item,parent,false);
holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.name.setText(list.get(position).getCommodityName());
holder.price.setText(list.get(position).getCommodityPrice()+"");
holder.item_count.setNumber(list.get(position).getCommodityCount());
holder.item_count.setFocusable(false);
String image = list.get(position).getCommodityPic();
String[] split = image.split("\\,");
Glide.with(context).load(split[0]).into(holder.img);
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView img;
private TextView name;
private TextView price;
DdCountView item_count;
public ViewHolder(View itemView) {
super(itemView);
img = itemView.findViewById(R.id.page_item_img);
name = itemView.findViewById(R.id.page_item_name);
price = itemView.findViewById(R.id.page_item_price);
item_count = itemView.findViewById(R.id.page_item_countt);
}
}
}
|
67d7b5c47f55a43f9ee9e9440a9f40b9e04eedbd
|
[
"Java"
] | 12 |
Java
|
WeiShuaiG/xiangmu
|
1afb99d439daf4954f8b14a1fd30b08358dd4e75
|
b61cb3c3becbbd83ca0f81da1e1d3224cd7d950e
|
refs/heads/main
|
<file_sep>//
// AqiCN.swift
// Air Quality Monitor
//
// Created by <NAME> on 9/18/21.
//
import Foundation
struct AqiCNMeasurements: Codable {
let status: String?
let data: AqiData?
var tomorrowForecast: Int {
data?.forecast?.daily?.tomorrowForecast ?? -1
}
}
struct AqiData: Codable {
// commented out available from API but not used in app
let aqi: Int?
//let idx: Int?
let attributions: [AqiAttribution]?
let city: AqiCity?
//let dominentpol: String?
//let iaqi: Aqiiaqi?
let forecast: AqiForecast?
}
struct AqiForecast: Codable {
let daily: AqiDailyForecast?
}
struct AqiDailyForecast: Codable {
let o3: [AqiForecastData?]
let pm25: [AqiForecastData?]
let pm10: [AqiForecastData?]
let uvi: [AqiForecastData?]
var tomorrowForecast: Int {
guard let maxVal = [tomorrowO3Aqi,tomorrowPm10Aqi,tomorrowPm25Aqi].sorted(by: { $0.value > $1.value }).first else { return -1 }
return maxVal.value
}
var todayUviAqi: (name: String, value: Int) { getTodayAqi(for: "uvi")}
var todayPm10Aqi: (name: String, value: Int) { getTodayAqi(for: "pm10")}
var todayPm25Aqi: (name: String, value: Int) { getTodayAqi(for: "pm25")}
var todayO3Aqi: (name: String, value: Int) { getTodayAqi(for: "o3")}
var tomorrowUviAqi: (name: String, value: Int) { getTomorrowAqi(for: "uvi")}
var tomorrowPm10Aqi: (name: String, value: Int) { getTomorrowAqi(for: "pm10")}
var tomorrowPm25Aqi: (name: String, value: Int) { getTomorrowAqi(for: "pm25")}
var tomorrowO3Aqi: (name: String, value: Int) { getTomorrowAqi(for: "o3")}
private func getTodayAqi(for pollutant: String) -> (name: String, value: Int) {
let pollutantData: Dictionary<String,[AqiForecastData?]> = [
"o3":o3,
"pm25":pm25,
"pm10":pm10,
"uvi":uvi
]
guard let forecastData = pollutantData[pollutant] else { return (name: pollutant, value: -1) }
guard let tomorrowData = forecastData.compactMap({ value -> AqiForecastData? in
if let date = value?.date {
return Calendar(identifier: .gregorian).isDateInToday(date) ? value : nil
}
return nil
}).first else { return (name: pollutant, value: -1) }
guard let min = tomorrowData.min, let max = tomorrowData.max, let avg = tomorrowData.avg else { return (name: pollutant, value: -1) }
return EPAData.getAqi(for: pollutant, min: .ppb(min), max: .ppb(max), avg: .ppb(avg))
}
private func getTomorrowAqi(for pollutant: String) -> (name: String, value: Int) {
let pollutantData: Dictionary<String,[AqiForecastData?]> = [
"o3":o3,
"pm25":pm25,
"pm10":pm10,
"uvi":uvi
]
guard let forecastData = pollutantData[pollutant] else { return (name: pollutant, value: -1) }
guard let tomorrowData = forecastData.compactMap({ value -> AqiForecastData? in
if let date = value?.date {
return Calendar(identifier: .gregorian).isDateInTomorrow(date) ? value : nil
}
return nil
}).first else { return (name: pollutant, value: -1) }
guard let min = tomorrowData.min, let max = tomorrowData.max, let avg = tomorrowData.avg else { return (name: pollutant, value: -1) }
//return EPAData.getAqi(for: pollutant, min: min, max: max, avg: avg, convertPPBtoPPM: true)
return EPAData.getAqi(for: pollutant, min: .ppb(min), max: .ppb(max), avg: .ppb(avg))
}
}
struct AqiForecastData: Codable {
let avg: Int?
let day: String?
let max: Int?
let min: Int?
var date: Date? {
guard let dateString = day else { return nil }
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd"
dateFormatter.locale = .current
return dateFormatter.date(from: dateString)
}
}
struct Aqiiaqi: Codable {
let co: AqiValue?
let h: AqiValue?
let no2: AqiValue?
let o3: AqiValue?
let p: AqiValue?
let pm10: AqiValue?
let pm25: AqiValue?
let so2: AqiValue?
let t: AqiValue?
let w: AqiValue?
}
struct AqiValue: Codable {
let v: Double?
}
struct AqiAttribution: Codable {
let url: String?
let name: String?
}
struct AqiCity: Codable {
let geo: [Double]?
let name: String?
let url: String?
}
/*
schema:
{
"status": "ok",
"data": {
"aqi": 42,
"idx": 1451,
"attributions": [
{
"url": "http://www.bjmemc.com.cn/",
"name": "Beijing Environmental Protection Monitoring Center (北京市环境保护监测中心)"
},
{
"url": "https://waqi.info/",
"name": "World Air Quality Index Project"
}
],
"city": {
"geo": [
39.954592,
116.468117
],
"name": "Beijing (北京)",
"url": "https://aqicn.org/city/beijing"
},
"dominentpol": "pm25",
"iaqi": {
"co": {
"v": 4.6
},
"h": {
"v": 88
},
"no2": {
"v": 5.5
},
"o3": {
"v": 26.4
},
"p": {
"v": 1016
},
"pm10": {
"v": 10
},
"pm25": {
"v": 42
},
"so2": {
"v": 1.6
},
"t": {
"v": 19
},
"w": {
"v": 2.5
}
},
"time": {
"s": "2021-09-19 08:00:00",
"tz": "+08:00",
"v": 1632038400,
"iso": "2021-09-19T08:00:00+08:00"
},
"forecast": {
"daily": {
"o3": [
{
"avg": 1,
"day": "2021-09-17",
"max": 18,
"min": 1
},
{
"avg": 1,
"day": "2021-09-18",
"max": 7,
"min": 1
},
{
"avg": 1,
"day": "2021-09-19",
"max": 6,
"min": 1
},
{
"avg": 5,
"day": "2021-09-20",
"max": 14,
"min": 1
},
{
"avg": 2,
"day": "2021-09-21",
"max": 17,
"min": 1
},
{
"avg": 1,
"day": "2021-09-22",
"max": 14,
"min": 1
},
{
"avg": 1,
"day": "2021-09-23",
"max": 8,
"min": 1
},
{
"avg": 1,
"day": "2021-09-24",
"max": 1,
"min": 1
}
],
"pm10": [
{
"avg": 60,
"day": "2021-09-18",
"max": 72,
"min": 28
},
{
"avg": 73,
"day": "2021-09-19",
"max": 119,
"min": 63
},
{
"avg": 29,
"day": "2021-09-20",
"max": 58,
"min": 21
},
{
"avg": 23,
"day": "2021-09-21",
"max": 32,
"min": 19
},
{
"avg": 49,
"day": "2021-09-22",
"max": 57,
"min": 34
},
{
"avg": 58,
"day": "2021-09-23",
"max": 67,
"min": 46
},
{
"avg": 53,
"day": "2021-09-24",
"max": 58,
"min": 46
},
{
"avg": 49,
"day": "2021-09-25",
"max": 58,
"min": 45
}
],
"pm25": [
{
"avg": 155,
"day": "2021-09-18",
"max": 164,
"min": 88
},
{
"avg": 172,
"day": "2021-09-19",
"max": 243,
"min": 158
},
{
"avg": 87,
"day": "2021-09-20",
"max": 154,
"min": 68
},
{
"avg": 71,
"day": "2021-09-21",
"max": 91,
"min": 59
},
{
"avg": 123,
"day": "2021-09-22",
"max": 154,
"min": 89
},
{
"avg": 147,
"day": "2021-09-23",
"max": 158,
"min": 134
},
{
"avg": 148,
"day": "2021-09-24",
"max": 159,
"min": 138
},
{
"avg": 124,
"day": "2021-09-25",
"max": 151,
"min": 89
}
],
"uvi": [
{
"avg": 0,
"day": "2021-09-18",
"max": 0,
"min": 0
},
{
"avg": 0,
"day": "2021-09-19",
"max": 2,
"min": 0
},
{
"avg": 0,
"day": "2021-09-20",
"max": 2,
"min": 0
},
{
"avg": 1,
"day": "2021-09-21",
"max": 5,
"min": 0
},
{
"avg": 1,
"day": "2021-09-22",
"max": 5,
"min": 0
},
{
"avg": 0,
"day": "2021-09-23",
"max": 2,
"min": 0
}
]
}
},
"debug": {
"sync": "2021-09-19T09:53:39+09:00"
}
}
}
*/
<file_sep>//
// Air_Quality_MonitorApp.swift
// Air Quality Monitor
//
// Created by <NAME> on 9/17/21.
//
import SwiftUI
@main
struct Air_Quality_MonitorApp: App {
var body: some Scene {
WindowGroup {
AirQualityView(airQualityModelView: AirQualityModelView())
}
}
}
<file_sep>//
// AirQualityModelView.swift
// Air Quality Monitor
//
// Created by <NAME> on 9/18/21.
//
import Foundation
import CoreLocation
import SwiftUI
class AirQualityModelView: NSObject, ObservableObject {
enum AirQualityError: Error {
case searchDataNotValid
var localizedDescription: String {
switch self {
case .searchDataNotValid:
return "Must enter valid country and city names"
}
}
}
private let indicatorColors: Dictionary<ClosedRange<Int>,Color> = [
(0...50) : .green,
(51...100) : .yellow,
(101...150) : .orange,
(151...200) : .red,
(201...300) : .purple,
(301...400) : .purple
]
@Published var modelViewError: Error?
@Published var cityName: String?
@Published var stationName: String?
@Published var coordinates: CLLocationCoordinate2D?
@Published var todayAqi: Int? {
willSet {
indicatorColors.forEach { if $0.key.contains(newValue ?? -1) { self.indicatorColor = $0.value }}
}
}
@Published var yesterdayAqi: Int?
@Published var tomorrowAqi: Int?
@Published var indicatorColor: Color
@Published var searchCountry: String = ""
@Published var searchCity: String = ""
lazy private var locationManager: CLLocationManager = {
let locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
locationManager.delegate = self
return locationManager
}()
override init() {
indicatorColor = .green
}
public func fetchLocalData() {
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
}
public func geocoderSearch() {
guard !searchCity.isEmpty, !searchCountry.isEmpty else {
self.modelViewError = AirQualityError.searchDataNotValid
return
}
CLGeocoder().geocodeAddressString("\(searchCity) \(searchCountry)") { [weak self] clPlacemark, error in
if let error = error {
self?.modelViewError = error
return
}
if let location = clPlacemark?.first?.location?.coordinate {
self?.fetchAPIData(location: location)
}
}
}
func fetchAPIData(location: CLLocationCoordinate2D) {
// fetch today's value from openAQ
NetworkManager.fetchOpenAQMeasurements(location: location, searchRadiusInMeters: 10000, daysIntoThePast: 0) { [weak self] in
switch $0 {
case .failure(let error):
self?.modelViewError = error
case .success(let value):
print("today value recieved: \(value.aqi.value)")
DispatchQueue.main.async {
self?.todayAqi = value.aqi.value
self?.cityName = value.city
self?.coordinates = location
}
}
self?.fetchYesterdayAqi(location: location)
}
}
private func fetchYesterdayAqi(location: CLLocationCoordinate2D) {
// fetch yesterday's value from openAQ. sequential to not overload shared urlsession
NetworkManager.fetchOpenAQMeasurements(location: location, searchRadiusInMeters: 10000, daysIntoThePast: 1) { [weak self] in
switch $0 {
case .failure(let error):
self?.modelViewError = error
case .success(let value):
print("yesterday value received: \(value.aqi.value)")
DispatchQueue.main.async {
self?.yesterdayAqi = value.aqi.value
}
}
self?.fetchTomorrowAqi(location: location)
}
}
private func fetchTomorrowAqi(location: CLLocationCoordinate2D) {
// fetch tomorrow's value from AqiCN. sequential to not overload shared urlsession
NetworkManager.fetchAqiCNMeasurements(location: location) { [weak self] in
switch $0 {
case .failure(let error):
self?.modelViewError = error
case .success(let value):
print("tomorrow value received: \(value.tomorrowForecast)")
DispatchQueue.main.async {
self?.tomorrowAqi = value.tomorrowForecast
self?.stationName = value.data?.city?.name ?? "No station data"
}
}
}
}
}
extension AirQualityModelView: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("locationManager receive: \(locations)")
guard let location = locations.first else { return }
fetchAPIData(location: location.coordinate)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("locationManager error: \(error.localizedDescription)")
DispatchQueue.main.async { [weak self] in
self?.modelViewError = error
}
}
}
<file_sep>//
// NetworkManager.swift
// Air Quality Monitor
//
// Created by <NAME> on 9/17/21.
//
import Foundation
import Combine
import CoreLocation
struct NetworkManager {
enum NetworkError: Error {
case BadURL
case NilData
case SearchAreaOutOfRange
}
private static var cancellable: AnyCancellable?
public static func fetchAqiCNMeasurements(location: CLLocationCoordinate2D, completion: @escaping (Result<AqiCNMeasurements,Error>) -> Void) {
//example url: https://api.waqi.info/feed/geo:37.787;-122.4/?token=<PASSWORD>
let route = "feed/geo:\(location.latitude);\(location.longitude)/"
guard var urlComponents = URLComponents(string: aqiCNServer+route) else {
completion(.failure(NetworkError.BadURL))
return
}
urlComponents.queryItems = [URLQueryItem(name: "token", value: aqicnToken)] // token in gitignored file.
guard urlComponents.url != nil else { completion(.failure(NetworkError.BadURL)); return }
var urlRequest = URLRequest(url: urlComponents.url!)
urlRequest.httpMethod = "GET"
cancellable = URLSession.shared.dataTaskPublisher(for: urlRequest)
.map { $0.data }
.decode(type: AqiCNMeasurements.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { receiveCompletion in
switch receiveCompletion {
case .failure(let error):
completion(.failure(error))
break
case .finished:
break
}
}, receiveValue: { receiveValue in
completion(.success(receiveValue))
})
}
public static func fetchOpenAQMeasurements(location: CLLocationCoordinate2D, searchRadiusInMeters: Int, daysIntoThePast: Int, completion: @escaping (Result<OpenAQMeasurements,Error>) -> Void) {
guard (0...100000).contains(searchRadiusInMeters) else {
completion(.failure(NetworkError.SearchAreaOutOfRange))
return
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd"
let nearestDate = Date(timeIntervalSinceNow: -24*60*60*Double(daysIntoThePast))
let furthestDate = Date(timeIntervalSinceNow: -24*60*60*Double(daysIntoThePast+1))
let parameters: Dictionary<String, String> = [
"page":"1",
"offset":"0",
"sort":"desc",
"date_from":dateFormatter.string(from: furthestDate),
"date_to":dateFormatter.string(from: nearestDate),
"coordinates":"\(String(format: "%.3f",location.latitude)),\(String(format: "%.3f",location.longitude))",
"radius":"\(searchRadiusInMeters)",
"sensorType":"reference grade",
"limit":"100",
"order_by":"datetime"
]
let route = "v2/measurements"
guard var urlComponents = URLComponents(string: openAQServer+route) else {
completion(.failure(NetworkError.BadURL))
return
}
urlComponents.queryItems = parameters.map { URLQueryItem(name: $0.key, value: $0.value) }
guard urlComponents.url != nil else {
completion(.failure(NetworkError.BadURL))
return
}
var urlRequest = URLRequest(url: urlComponents.url!)
urlRequest.httpMethod = "GET"
cancellable = URLSession.shared.dataTaskPublisher(for: urlRequest)
.map { $0.data }
.decode(type: OpenAQMeasurements.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { receiveCompletion in
switch receiveCompletion {
case .failure(let error):
print("receive error")
completion(.failure(error))
default:
break
}
}, receiveValue: { receiveValue in
completion(.success(receiveValue))
})
}
}
<file_sep># Air-Quality-Monitor
An app for acquiring air quality index information for a given location.

## Description
This project is a general use information app that displays air quality data for a region based on user's GPS or specificied search results. This app employs unlimited free use APIs from [OpenAQ](https://openaq.org/) and [AqiCN](https://aqicn.org/).
## Technologies
Project is created with:
* XCode 13
* Swift 5
* SwiftUI
<file_sep>//
// WaitSpinner.swift
// Air Quality Monitor
//
// Created by <NAME> on 9/19/21.
//
import SwiftUI
struct WaitSpinner: View {
@State var colorToggler: Bool = false
@State var startAngle: CGFloat = 0.0
@State var endAngle: CGFloat = 0.0
private var color = Color(.sRGB, red: 0.2, green: 0.3, blue: 0.7, opacity: 1.0)
var body: some View {
GeometryReader { geometry in
let localSize = min(geometry.size.height, geometry.size.width)
ZStack {
Circle()
.stroke(colorToggler ? Color.gray : color, style: StrokeStyle(lineWidth: localSize * 0.3))
Circle()
.trim(from: startAngle, to: endAngle)
.stroke(colorToggler ? color : Color.gray, style: StrokeStyle(lineWidth: localSize * 0.3, lineCap: .round))
}
.animation(Animation.spring(response: 1.0, dampingFraction: 1.0, blendDuration: 0.1).repeatForever(autoreverses: false))
.onAppear() {
endAngle = 1.0
colorToggler.toggle()
}
}
}
}
struct WaitSpinner_Previews: PreviewProvider {
static var previews: some View {
WaitSpinner().frame(width: 100, height: 100, alignment: .center)
}
}
<file_sep>//
// EPAData.swift
// Air Quality Monitor
//
// Created by <NAME> on 9/19/21.
//
import Foundation
struct EPAData {
enum PollutantValue {
case ppm(Double)
case ppb(Int)
}
static let uom: Dictionary<String,String> = [
"pm10":"ug/m3",
"pm25":"ug/m3",
"o3":"ppm",
"no2":"ppm",
"co":"ppm"
]
// all data provided by EPA. source: https://en.wikipedia.org/wiki/Air_quality_index
static let pollutantRanges: Dictionary<String,Dictionary<ClosedRange<Double>, ClosedRange<Int>>> = [
"pm10": [
(0.0...54.9):(0...50),
(55.0...154.9):(51...100),
(155.0...254.9):(101...150),
(255.0...354.9):(151...200),
(355.0...424.9):(201...300),
(425.0...504.9):(301...400),
(505.0...604.0):(401...500)
],
"pm25": [
(0.0...12.0):(0...50),
(12.1...35.4):(51...100),
(35.5...55.4):(101...150),
(55.5...150.4):(151...200),
(150.5...250.4):(201...300),
(250.5...350.4):(301...400),
(350.5...500.4):(401...500)
],
"o3": [
(0.000...0.054):(0...50),
(0.055...0.070):(51...100),
(0.071...0.085):(101...150),
(0.086...0.105):(151...200),
(0.106...0.200):(201...300),
(0.201...0.400):(301...400),
(0.401...0.600):(401...500)
],
"no2": [
(0.000...0.053):(0...50),
(0.054...0.100):(51...100),
(0.101...0.360):(101...150),
(0.361...0.649):(151...200),
(0.650...1.249):(201...300),
(1.250...1.649):(301...400),
(1.650...2.049):(401...500)
],
"co": [
(0.0...4.4):(0...50),
(4.5...9.4):(51...100),
(9.5...12.4):(101...150),
(12.5...15.4):(151...200),
(15.5...30.4):(201...300),
(30.5...40.4):(301...400),
(40.5...50.4):(401...500)
]
]
static func getAqi(for pollutant: String, min: PollutantValue, max: PollutantValue, avg: PollutantValue) -> (name: String, value: Int) {
var localMax = 0.0
var localMin = 0.0
var localAverage = 0.0
// convert PPB to PPM all values.
switch max {
case .ppm(let value):
localMax = value
case .ppb(let value):
localMax = Double(value)/1000.0
}
switch min {
case .ppm(let value):
localMin = value
case .ppb(let value):
localMin = Double(value)/1000.0
}
switch avg {
case .ppm(let value):
localAverage = value
case .ppb(let value):
localAverage = Double(value)/1000.0
}
guard let range = EPAData.pollutantRanges[pollutant] else { return (name: pollutant, value: -1) }
guard let aqiRange = range.compactMap({ ranges -> ClosedRange<Int>? in
ranges.key.contains(localAverage) ? ranges.value : nil
}).first else { return (name: pollutant, value: -1)}
//HACK: - Error handling when all values same over time. Equation below tries to divide by zero.
if(localMax-localMin) == 0 {
let scalarRange = range.filter({ $0.key.contains(localAverage)}).first!
let scaler = (scalarRange.key.upperBound - scalarRange.key.lowerBound) / (localAverage - scalarRange.key.lowerBound)
let scale = (Double(scalarRange.value.upperBound - scalarRange.value.lowerBound) * scaler) + Double(scalarRange.value.lowerBound)
return (name: pollutant, value: Int(scale))
}
// equation provided by EPA. source: https://en.wikipedia.org/wiki/Air_quality_index
let equationStepOne = Double(aqiRange.max()! - aqiRange.min()!) / (localMax - localMin)
let equationStepTwo = equationStepOne * (localAverage - localMin)
return (name: pollutant, value: Int(equationStepTwo) + aqiRange.min()!)
}
static func getAqi(for pollutant: String, min: Int, max: Int, avg: Int, convertPPBtoPPM: Bool) -> (name: String, value: Int) {
EPAData.getAqi(for: pollutant, min: Double(min), max: Double(max), avg: Double(avg), convertPPBtoPPM: convertPPBtoPPM)
}
static func getAqi(for pollutant: String, min: Double, max: Double, avg: Double, convertPPBtoPPM: Bool) -> (name: String, value: Int) {
let localMax = convertPPBtoPPM ? max/1000.0 : max
let localMin = convertPPBtoPPM ? min/1000.0 : min
let localAvg = convertPPBtoPPM ? avg/1000.0 : avg
guard let range = EPAData.pollutantRanges[pollutant] else { return (name: pollutant, value: -1) }
guard let aqiRange = range.compactMap({ ranges -> ClosedRange<Int>? in
ranges.key.contains(localAvg) ? ranges.value : nil
}).first else { return (name: pollutant, value: -1)}
// equation provided by EPA. source: https://en.wikipedia.org/wiki/Air_quality_index
let equationStepOne = Double(aqiRange.max()! - aqiRange.min()!) / (localMax - localMin)
let equationStepTwo = equationStepOne * (localAvg - localMin)
return (name: pollutant, value: Int(equationStepTwo) + aqiRange.min()!)
}
}
<file_sep>//
// ContentView.swift
// Air Quality Monitor
//
// Created by <NAME> on 9/17/21.
//
import SwiftUI
import Combine
struct AirQualityView: View {
@ObservedObject var airQualityModelView: AirQualityModelView
var body: some View {
Group {
if airQualityModelView.modelViewError != nil {
ErrorView(airQualityModelView: airQualityModelView)
}
if airQualityModelView.todayAqi == nil {
LoadingView()
} else {
ZStack {
//BackgroundView(airQualityModelView: airQualityModelView)
LinearGradient(gradient: Gradient(colors: [Color(.sRGB, white: 0.9, opacity: 0.9), Color(hue: 0.6, saturation: 0.6, brightness: 0.7)]), startPoint: .top, endPoint: .bottom)
.ignoresSafeArea()
VStack {
VStack {
Text("Air Quality Index:")
.font(.title)
Text("\(airQualityModelView.todayAqi ?? 0)")
.font(.largeTitle)
.background(airQualityModelView.indicatorColor)
.clipShape(RoundedRectangle(cornerRadius: 10.0))
.frame(width: 50, height: 50, alignment: .center)
Text("\(airQualityModelView.cityName ?? "")")
.font(.title3)
Text("\(airQualityModelView.stationName ?? "")")
.font(.body)
Text("""
\(String(format: "%.5f", airQualityModelView.coordinates?.latitude ?? 0)), \(String(format: "%.5f", airQualityModelView.coordinates?.longitude ?? 0))
""")
.font(.body)
}
.foregroundColor(.black)
.padding(EdgeInsets(top: 65.0, leading: 5.0, bottom: 30.0, trailing: 5.0))
HStack {
VStack {
Text("Yesterday's AQI:")
.font(.title3)
Text("\(airQualityModelView.yesterdayAqi ?? 0)")
.font(.largeTitle)
}
.padding(10)
VStack {
Text("Tomorrow's AQI:")
.font(.title3)
Text("\(airQualityModelView.tomorrowAqi ?? 0)")
.font(.largeTitle)
}
.padding(10)
}
.foregroundColor(.black)
.padding(EdgeInsets(top: 5.0, leading: 5.0, bottom: 55.0, trailing: 5.0))
VStack {
Text("Search another city")
.font(.title3)
Text("City")
.font(.caption)
TextField("City", text: $airQualityModelView.searchCity)
.frame(width: 300, height: 35, alignment: .center)
.background(Color.white)
.foregroundColor(.gray)
Text("Country")
.font(.caption)
TextField("Country", text: $airQualityModelView.searchCountry)
.frame(width: 300, height: 35, alignment: .center)
.background(Color.white)
.foregroundColor(.gray)
Button("Search") {
airQualityModelView.geocoderSearch()
}
.frame(width: 200, height: 35, alignment: .center)
.background(Color(.sRGB, white: 0.8, opacity: 0.8))
.clipShape(RoundedRectangle(cornerRadius: 8.0))
.padding(3)
HStack {
Button(action: {
airQualityModelView.fetchLocalData()
}, label: {
Image(systemName: "location.fill")
.frame(width: 35, height: 35, alignment: .center)
})
.foregroundColor(Color(.sRGB, red: 0.2, green: 0.3, blue: 0.7, opacity: 1.0))
Text("Get local data")
.font(.title3)
}
.padding(EdgeInsets(top: 45.0, leading: 25.0, bottom: 5.0, trailing: 25.0))
}
.foregroundColor(.black)
.padding(EdgeInsets(top: 5.0, leading: 5.0, bottom: 100.0, trailing: 5.0))
}
}
}
}
.onAppear() {
airQualityModelView.fetchLocalData()
}
}
}
struct LoadingView: View {
var body: some View {
ZStack {
LinearGradient(gradient: Gradient(colors: [Color(.sRGB, white: 0.9, opacity: 0.9), Color(hue: 0.6, saturation: 0.6, brightness: 0.7)]), startPoint: .top, endPoint: .bottom)
.ignoresSafeArea()
.ignoresSafeArea()
VStack {
Text("Air Quality Monitor")
.font(.largeTitle)
.foregroundColor(Color(.sRGB, red: 0.2, green: 0.3, blue: 0.7, opacity: 1.0))
.shadow(radius: 2)
WaitSpinner()
.frame(width: 100, height: 100, alignment: .center)
.padding(EdgeInsets(top: 50.0, leading: 0.0, bottom: 350.0, trailing: 0.0))
}
}
}
}
struct ErrorView: View {
@ObservedObject var airQualityModelView: AirQualityModelView
var body: some View {
VStack {
Text(airQualityModelView.modelViewError?.localizedDescription ?? "Error")
Button("Dismiss") {
airQualityModelView.modelViewError = nil
}
}
.frame(width: 300, height: 300, alignment: .center)
}
}
struct LoadingView_Previews: PreviewProvider {
static var previews: some View {
LoadingView()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
AirQualityView(airQualityModelView: AirQualityModelView())
}
}
<file_sep>//
// IntegrationTests.swift
// Air Quality MonitorTests
//
// Created by <NAME> on 9/19/21.
//
import XCTest
@testable import Air_Quality_Monitor
class IntegrationTests: XCTestCase {
let sut = AirQualityModelView()
override func setUpWithError() throws {
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testAPICalls() {
let exp = expectation(description: #function)
sut.fetchLocalData()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 4) { [weak self] in
guard self?.sut.todayAqi != nil,self?.sut.tomorrowAqi != nil,self?.sut.yesterdayAqi != nil else { return }
exp.fulfill()
}
wait(for: [exp], timeout: 5)
XCTAssert(true)
}
func testNYC() {
let exp = expectation(description: #function)
sut.searchCity = "New York City"
sut.searchCountry = "USA"
sut.geocoderSearch()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 4) { [weak self] in
guard self?.sut.todayAqi != nil,self?.sut.tomorrowAqi != nil,self?.sut.yesterdayAqi != nil else { return }
exp.fulfill()
}
wait(for: [exp], timeout: 5)
XCTAssert(true)
}
}
<file_sep>//
// Air_Quality_MonitorTests.swift
// Air Quality MonitorTests
//
// Created by <NAME> on 9/17/21.
//
import XCTest
import CoreLocation
@testable import Air_Quality_Monitor
class Air_Quality_MonitorTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testAqiCN() {
let exp = expectation(description: #function)
let coordinate = CLLocationCoordinate2D(latitude: 37.376, longitude: -121.803)
NetworkManager.fetchAqiCNMeasurements(location: coordinate) {
switch $0 {
case .failure(let error):
print(error as Any)
case .success(let value):
print("~~~~~~~~~~~~~~TODAY~~~~~~~~~~~~`")
print("Calculated aqi from pm25: \(value.data?.forecast?.daily?.todayPm25Aqi as Any)")
print("Calculated aqi from o3: \(value.data?.forecast?.daily?.todayO3Aqi as Any)")
print("Calculated aqi from pm10: \(value.data?.forecast?.daily?.todayPm10Aqi as Any)")
print("Calculated aqi from uvi: \(value.data?.forecast?.daily?.todayUviAqi as Any)")
print("~~~~~~~~~~~~~~TOMORROW~~~~~~~~~~~~`")
print("tomorrow o3: \(value.data?.forecast?.daily?.tomorrowO3Aqi as Any)")
print("tomorrow pm25: \(value.data?.forecast?.daily?.tomorrowPm25Aqi as Any)")
print("tomorrow pm10: \(value.data?.forecast?.daily?.tomorrowPm10Aqi as Any)")
print("tomorrow uvi: \(value.data?.forecast?.daily?.tomorrowUviAqi as Any)")
print(value as Any)
exp.fulfill()
}
}
wait(for: [exp], timeout: 2)
XCTAssert(true)
}
func testOpenAQApi() {
let exp = expectation(description: #function)
//37.376052, -121.803207
let coordinate = CLLocationCoordinate2D(latitude: 37.376, longitude: -121.803)
NetworkManager.fetchOpenAQMeasurements(location: coordinate, searchRadiusInMeters: 10000, daysIntoThePast: 0) {
switch $0 {
case .failure(let error):
print(error as Any)
case .success(let value):
print("city: \(value.city)")
print("gps: \(value.coordinates)")
print(value.aqi)
print("Calculated aqi from pm25: \(value.pm25Aqi)")
print("Calculated aqi from o3: \(value.o3Aqi)")
print("Calculated aqi from no2: \(value.no2Aqi)")
print("Calculated aqi from co: \(value.coAqi)")
//print(value.results)
exp.fulfill()
}
}
wait(for: [exp], timeout: 2)
XCTAssert(true)
}
}
<file_sep>//
// Tokens.swift
// Air Quality Monitor
//
// Created by <NAME> on 9/18/21.
//
import Foundation
let aqicnToken = "<KEY>"
let openAQServer = "https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/"
let aqiCNServer = "https://api.waqi.info/"
<file_sep>//
// OpenAQ.swift
// Air Quality Monitor
//
// Created by <NAME> on 9/17/21.
//
import Foundation
struct OpenAQMeasurements: Codable {
private static let uom: Dictionary<String,String> = [
"pm25":"ug/m3",
"o3":"ppm",
"no2":"ppm",
"co":"ppm"
]
//let meta: OpenAQMeta // uneeded.
private let results: [OpenAQResult]
var city: String {
var cities = Dictionary<String, Int>()
results.forEach {
if let city = $0.city {
cities[city, default: 0] += 1
}
}
let maxCity = cities.max { $0.value < $1.value }?.key ?? ""
return maxCity
}
var coordinates: String {
var coordinates = Dictionary<String, Int>()
results.forEach {
if let coordinate = $0.coordinates {
if let lat = coordinate.latitude, let long = coordinate.longitude {
coordinates["\(lat),\(long)", default: 0] += 1
}
}
}
let maxCoordinate = coordinates.max { $0.value < $1.value }?.key ?? ""
return maxCoordinate
}
var aqi: (majorPollutant: String, value: Int) {
let maxPollutant = [pm25Aqi, o3Aqi, no2Aqi, coAqi].sorted { $0.value > $1.value }.first!
return (majorPollutant: maxPollutant.name, value: maxPollutant.value)
}
var pm25Aqi: (name: String, value: Int) { getAqi(for: "pm25") }
var o3Aqi: (name: String, value: Int) { getAqi(for: "o3") }
var no2Aqi: (name: String, value: Int) { getAqi(for: "no2") }
var coAqi: (name: String, value: Int) { getAqi(for: "co") }
private var pm25History: [(name: String, value: Double, date: Date, uom: String)] { getHistory(for: "pm25") }
private var o3History: [(name: String, value: Double, date: Date, uom: String)] { getHistory(for: "o3") }
private var no2History: [(name: String, value: Double, date: Date, uom: String)] { getHistory(for: "no2") }
private var coHistory: [(name: String, value: Double, date: Date, uom: String)] { getHistory(for: "co") }
private func getHistory(for pollutant: String) -> [(name: String, value: Double, date: Date, uom: String)] {
let pollutantHistory = results.filter { $0.parameter == pollutant }
return pollutantHistory.compactMap { pollutantName -> (name: String, value: Double, date: Date, uom: String)? in
guard let date = pollutantName.date?.localDate else { return nil }
guard let value = pollutantName.value else { return nil }
return (name: pollutantName.parameter!, value: value, date: date, uom: OpenAQMeasurements.uom[pollutant]!)
}.sorted { $0.date > $1.date }
}
private func getAqi(for pollutant: String) -> (name: String, value: Int) {
let sourceDictionary: Dictionary<String, [(name: String, value: Double, date: Date, uom: String)]> = [
"pm25":pm25History,
"co":coHistory,
"no2":no2History,
"o3":o3History
]
guard let source = sourceDictionary[pollutant] else { return (name: pollutant, value: -1) }
let values = source.map { $0.value }
let average = values.reduce(0) { $0 + $1 } / Double(source.count)
guard let max = values.max() else { return (name: pollutant, value: -1) }
guard let min = values.min() else { return (name: pollutant, value: -1) }
return EPAData.getAqi(for: pollutant, min: .ppm(min), max: .ppm(max), avg: .ppm(average))
}
}
/*
Meta data available from API but unused.
struct OpenAQMeta: Codable {
let name: String?
let license: String?
let website: String?
let page: Int?
let limit: Int?
let found: Int?
}
*/
/*
Schema
"meta": {
"name": "openaq-api",
"license": "CC BY 4.0d",
"website": "https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/",
"page": 1,
"limit": 100,
"found": 632374
},
*/
struct OpenAQResult: Codable {
// commented out are available from API, but unused.
//let locationId: Int?
//let location: String?
let parameter: String?
let value: Double?
let date: OpenAQDate?
let unit: String? // unit of measure for pollutant
let coordinates: Coordinate?
let country: String?
let city: String?
//let isMobile: Bool?
//let isAnalysis: Bool?
//let entity: String?
//let sensorType: String?
}
struct OpenAQDate: Codable {
static let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ssZZZZ"
dateFormatter.locale = .current
return dateFormatter
}()
let utc: String?
let local: String?
var localDate: Date? {
guard let localDate = local else { return nil }
return OpenAQDate.dateFormatter.date(from: localDate.replacingOccurrences(of: "T", with: " "))
}
var utcDate: Date? {
guard let utcDate = utc else { return nil }
return OpenAQDate.dateFormatter.date(from: utcDate.replacingOccurrences(of: "T", with: " "))
}
}
struct Coordinate: Codable {
let latitude: Double?
let longitude: Double?
}
/*
Schema
"results": [
{
"locationId": 2007,
"location": "San Jose - Knox Ave",
"parameter": "no2",
"value": 0.011,
"date": {
"utc": "2021-09-18T00:00:00+00:00",
"local": "2021-09-17T17:00:00-07:00"
},
"unit": "ppm",
"coordinates": {
"latitude": 37.338202,
"longitude": -121.849892
},
"country": "US",
"city": "San Jose-Sunnyvale-Santa Clara",
"isMobile": false,
"isAnalysis": false,
"entity": "government",
"sensorType": "reference grade"
}
*/
|
2521c662b86e3d22f8cadc562a7b73aacdde25ac
|
[
"Swift",
"Markdown"
] | 12 |
Swift
|
jeffreydthompson/Air-Quality-Monitor
|
d9c81da03a8d8f3e982479d6a30dc026822df3a0
|
15f605b94456002524fb1a37a2b30e352474bf6a
|
refs/heads/main
|
<file_sep>import speech_recognition as sr #To convert speech into text
import pyttsx3 #To convert text into speech
import datetime #To get the date and time
import wikipedia #To get information from wikipedia
import webbrowser #To open websites
import os #To open files
import time #To calculate time
import subprocess #To open files
from tkinter import * #For the graphics
import pyjokes #For some really bad jokes
from playsound import playsound #To playsound
import keyboard #To get keyboard
name_file = open("Assistant_name", "r")
name_assistant = name_file.read()
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def speak(text):
engine.say(text)
print(name_assistant + " : " + text)
engine.runAndWait()
def wishMe():
hour=datetime.datetime.now().hour
if hour >= 0 and hour < 12:
speak("Hello,Good Morning")
elif hour >= 12 and hour < 18:
speak("Hello,Good Afternoon")
else:
speak("Hello,Good Evening")
def get_audio():
r = sr.Recognizer()
audio = ''
with sr.Microphone() as source:
print("Listening")
playsound("assistant_on.wav")
audio = r.listen(source, phrase_time_limit = 3)
playsound("assistant_off.wav")
print("Stop.")
try:
text = r.recognize_google(audio, language ='en-US')
print('You: ' + ': ' + text)
return text
except:
return "None"
def note(text):
date = datetime.datetime.now()
file_name = str(date).replace(":", "-") + "-note.txt"
with open(file_name, "w") as f:
f.write(text)
subprocess.Popen(["notepad.exe", file_name])
def date():
now = datetime.datetime.now()
month_name = now.month
day_name = now.day
month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
ordinalnames = [ '1st', '2nd', '3rd', ' 4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd','24rd', '25th', '26th', '27th', '28th', '29th', '30th', '31st']
speak("Today is "+ month_names[month_name-1] +" " + ordinalnames[day_name-1] + '.')
wishMe()
def Process_audio():
run = 1
if __name__=='__main__':
while run==1:
app_string = ["open word", "open powerpoint", "open excel", "open zoom","open notepad", "open chrome"]
app_link = [r'\Microsoft Office Word 2007.lnk',r'\Microsoft Office PowerPoint 2007.lnk', r'\Microsoft Office Excel 2007.lnk', r'\Zoom.lnk', r'\Notepad.lnk', r'\Google Chrome.lnk' ]
app_dest = r'C:\Users\shriraksha\AppData\Roaming\Microsoft\Windows\Start Menu\Programs'
statement = get_audio().lower()
results = ''
run +=1
if "hello" in statement or "hi" in statement:
wishMe()
if "good bye" in statement or "ok bye" in statement or "stop" in statement:
speak('Your personal assistant ' + name_assistant +' is shutting down, Good bye')
screen.destroy()
break
if 'wikipedia' in statement:
try:
speak('Searching Wikipedia...')
statement = statement.replace("wikipedia", "")
results = wikipedia.summary(statement, sentences = 3)
speak("According to Wikipedia")
wikipedia_screen(results)
except:
speak("Error")
if 'joke' in statement:
speak(pyjokes.get_joke())
if 'open youtube' in statement:
webbrowser.open_new_tab("https://www.youtube.com")
speak("youtube is open now")
time.sleep(5)
if 'open google' in statement:
webbrowser.open_new_tab("https://www.google.com")
speak("Google chrome is open now")
time.sleep(5)
if 'open gmail' in statement:
webbrowser.open_new_tab("mail.google.com")
speak("Google Mail open now")
time.sleep(5)
if 'open netflix' in statement:
webbrowser.open_new_tab("netflix.com/browse")
speak("Netflix open now")
if 'open prime video' in statement:
webbrowser.open_new_tab("primevideo.com")
speak("Amazon Prime Video open now")
time.sleep(5)
if app_string[0] in statement:
os.startfile(app_dest + app_link[0])
speak("Microsoft office Word is opening now")
if app_string[1] in statement:
os.startfile(app_dest + app_link[1])
speak("Microsoft office PowerPoint is opening now")
if app_string[2] in statement:
os.startfile(app_dest + app_link[2])
speak("Microsoft office Excel is opening now")
if app_string[3] in statement:
os.startfile(app_dest + app_link[3])
speak("Zoom is opening now")
if app_string[4] in statement:
os.startfile(app_dest + app_link[4])
speak("Notepad is opening now")
if app_string[5] in statement:
os.startfile(app_dest + app_link[5])
speak("Google chrome is opening now")
if 'news' in statement:
news = webbrowser.open_new_tab("https://timesofindia.indiatimes.com/city/mangalore")
speak('Here are some headlines from the Times of India, Happy reading')
time.sleep(6)
if 'cricket' in statement:
news = webbrowser.open_new_tab("cricbuzz.com")
speak('This is live news from cricbuzz')
time.sleep(6)
if 'corona' in statement:
news = webbrowser.open_new_tab("https://www.worldometers.info/coronavirus/")
speak('Here are the latest covid-19 numbers')
time.sleep(6)
if 'time' in statement:
strTime=datetime.datetime.now().strftime("%H:%M:%S")
speak(f"the time is {strTime}")
if 'date' in statement:
date()
if 'who are you' in statement or 'what can you do' in statement:
speak('I am '+name_assistant+' your personal assistant. I am programmed to minor tasks like opening youtube, google chrome, gmail and search wikipedia etcetra')
if "who made you" in statement or "who created you" in statement or "who discovered you" in statement:
speak("I was built by Abhhi Sannayya")
if 'make a note' in statement:
statement = statement.replace("make a note", "")
note(statement)
if 'note this' in statement:
statement = statement.replace("note this", "")
note(statement)
speak(results)
def change_name():
name_info = name.get()
file=open("Assistant_name", "w")
file.write(name_info)
file.close()
settings_screen.destroy()
screen.destroy()
def change_name_window():
global settings_screen
global name
settings_screen = Toplevel(screen)
settings_screen.title("Settings")
settings_screen.geometry("300x300")
settings_screen.iconbitmap('app_icon.ico')
name = StringVar()
current_label = Label(settings_screen, text = "Current name: "+ name_assistant)
current_label.pack()
enter_label = Label(settings_screen, text = "Please enter your Virtual Assistant's name below")
enter_label.pack(pady=10)
Name_label = Label(settings_screen, text = "Name")
Name_label.pack(pady=10)
name_entry = Entry(settings_screen, textvariable = name)
name_entry.pack()
change_name_button = Button(settings_screen, text = "Ok", width = 10, height = 1, command = change_name)
change_name_button.pack(pady=10)
def info():
info_screen = Toplevel(screen)
info_screen.title("Info")
info_screen.iconbitmap('app_icon.ico')
creator_label = Label(info_screen,text = "Created by <NAME>")
creator_label.pack()
Age_label = Label(info_screen, text= " at the age of 12")
Age_label.pack()
for_label = Label(info_screen, text = "For Makerspace")
for_label.pack()
keyboard.add_hotkey("F4", Process_audio)
def wikipedia_screen(text):
wikipedia_screen = Toplevel(screen)
wikipedia_screen.title(text)
wikipedia_screen.iconbitmap('app_icon.ico')
message = Message(wikipedia_screen, text= text)
message.pack()
def main_screen():
global screen
screen = Tk()
screen.title(name_assistant)
screen.geometry("100x250")
screen.iconbitmap('app_icon.ico')
name_label = Label(text = name_assistant,width = 300, bg = "black", fg="white", font = ("Calibri", 13))
name_label.pack()
microphone_photo = PhotoImage(file = "assistant_logo.png")
microphone_button = Button(image=microphone_photo, command = Process_audio)
microphone_button.pack(pady=10)
settings_photo = PhotoImage(file = "settings.png")
settings_button = Button(image=settings_photo, command = change_name_window)
settings_button.pack(pady=10)
info_button = Button(text ="Info", command = info)
info_button.pack(pady=10)
screen.mainloop()
main_screen()
<file_sep># A-GUI-Virtual-Assistant-with-python
Hello, I am Abhhi a beginner programmer. This is a program I made almost completely bymyself. If you find any way to improve it please tell me.
|
eb0e872d946008a00754a99505028916ff0333d7
|
[
"Markdown",
"Python"
] | 2 |
Python
|
Ascool7776/A-GUI-Virtual-Assistant-with-python
|
bf6195c4d5112f095bc161b810469c1815b9bc37
|
012595c4518c3ed3d1fa2c67fc2fc81ad04d6ecc
|
refs/heads/master
|
<repo_name>Capeo/WebInt-Project<file_sep>/result.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Result</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body onresize="resize_canvas()">
<canvas id="myCanvas" width="810" height="340">
</canvas>
<pre id="desc"></pre>
<table id="myTable" style="width:100%">
<tr>
<td>Very negative</td>
<td>A little negative</td>
<td>A little positive</td>
<td>Very positive</td>
</tr>
<tr id="newsTable">
<td><pre id="vNeg"></pre></td>
<td><pre id="lNeg"></pre></td>
<td><pre id="lPos"></pre></td>
<td><pre id="vPos"></pre></td>
</tr>
</table>
</body>
<script>
var result = [ <?php
//For testing only
/*
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
*/
//Define API key
$api_key = "b24b21443654829ad3a9598b26e64d7ed66b10b2";
//Retrieve keywords from through POST method
$keywords = $_POST['keywords'];
$terms = explode(" ", $keywords);
//Add all keywords to query using conjunction
$query = "A[";
foreach($terms as $t){
$query = $query . $t . "^";
}
$query = rtrim($query, "^");
$query = $query . "]";
//Generate correct url for query
$url = "https://gateway-a.watsonplatform.net/calls/data/GetNews?&apikey=" . $api_key . "&outputMode=json&rank=high&dedup=1&start=now-1d&end=now&count=10&q.enriched.url.text=" . $query . "&return=enriched.url.url,enriched.url.docSentiment.score";
//Retrieve JSON using cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close($ch);
$obj = json_decode($json);
$results = $obj->result->docs;
//For each result retrieved find source name and document sentiment. Store in associative array with source name as key
$sources = array();
foreach($results as $doc){
$docRes = $doc->source->enriched->url;
$sentiment = $docRes->docSentiment->score;
$docUrl = $docRes->url;
//Parse source name
if(strpos($docUrl, "http://") !== false){
$source = ltrim($docUrl, "http://");
if (strpos($source, "/") !== false) {
$source = substr($source, 0, strpos($source, "/"));
}
}
elseif(strpos($docUrl, "https://") !== false){
$source = ltrim($docUrl, "https://");
if (strpos($source, "/") !== false) {
$source = substr($source, 0, strpos($source, "/"));
}
}
else{
$source = "Unknown";
}
if(array_key_exists($source, $sources)){
$sources[$source][0] += $sentiment;
$sources[$source][1] += 1;
}
else{
$sources[$source] = array($sentiment, 1);
}
}
//Calculate average sentiment of each source and store in associative array. Also calculate 'global' average accross all retrieved articles
$global_total = 0;
$global_num = 0;
$sentiments = array();
foreach($sources as $source => $value){
$sentiments[$source] = $value[0] / $value[1];
$global_total += $value[0];
$global_num += $value[1];
}
$global_avg = $global_total / $global_num;
$sentiments["Global"] = $global_avg;
//Return JSON of associative array
echo json_encode($sentiments);
?> ];
var i = result[0]["Global"];
var search = "<?php echo $_POST['keywords']; ?>";
var pElement = document.getElementById("desc");
pElement.innerHTML="Search term: " + search + "\t\t\t" + "Average score: "+ i;
var col1 = document.getElementById("vNeg");
var col2 = document.getElementById("lNeg");
var col3 = document.getElementById("lPos");
var col4 = document.getElementById("vPos");
//col1.innerHTML="New york times: -0.89" + "\n" + "BBC: -0.77";
for (var key in result[0]) {
var attrName = key;
var attrValue = result[0][key];
if(key=="Global"){
}
else if(attrValue<-0.5){
col1.innerHTML+="\n"+attrName+": "+attrValue;
}
else if(attrValue<0){
col2.innerHTML+="\n"+attrName+": "+attrValue;
}
else if(attrValue<0.5){
col3.innerHTML+="\n"+attrName+": "+attrValue;
}
else{
col4.innerHTML+="\n"+attrName+": "+attrValue;
}
}
function resize_canvas(){
var canvas = document.getElementById("myCanvas");
if (canvas.width < window.innerWidth)
{
canvas.width = window.innerWidth;
}
if (canvas.height < window.innerHeight)
{
canvas.height = window.innerHeight;
}
var ctx=canvas.getContext("2d");
var x = window.innerWidth;
var y = window.innerHeight/3;
var m = x/2;
ctx.canvas.width = x;
ctx.canvas.height = y;
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,x/4,y);
var ctx2=canvas.getContext("2d");
ctx2.fillStyle="#FF9933";
ctx2.fillRect(x/4,0,x/2,y);
var ctx3=canvas.getContext("2d");
ctx3.fillStyle="#FFFF00";
ctx3.fillRect(x/2,0,(3*x)/4,y);
var ctx4=canvas.getContext("2d");
ctx4.fillStyle="#00FF00";
ctx4.fillRect((3*x)/4,0,x,y);
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(m+m*i, y);
context.lineTo(m+m*i, 0);
context.lineWidth = 5;
// set line color
context.strokeStyle = '#000000';
context.stroke();
}
window.onload = function() {
resize_canvas();
};
</script>
</html><file_sep>/README.md
# WebInt-Project
Sentiment analysis project for WebInt.<file_sep>/query.php
<?php
//For testing only
/*
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
*/
//Define API key
$api_key = "b24b21443654829ad3a9598b26e64d7ed66b10b2";
//Retrieve keywords from through POST method
$keywords = $_POST['keywords'];
$terms = explode(" ", $keywords);
//Add all keywords to query using conjunction
$query = "A[";
foreach($terms as $t){
$query = $query . $t . "^";
}
$query = rtrim($query, "^");
$query = $query . "]";
//Generate correct url for query
$url = "https://gateway-a.watsonplatform.net/calls/data/GetNews?&apikey=" . $api_key . "&outputMode=json&rank=high&dedup=1&start=now-1d&end=now&count=10&q.enriched.url.text=" . $query . "&return=enriched.url.url,enriched.url.docSentiment.score";
//Retrieve JSON using cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close($ch);
$obj = json_decode($json);
$results = $obj->result->docs;
//For each result retrieved find source name and document sentiment. Store in associative array with source name as key
$sources = array();
foreach($results as $doc){
$docRes = $doc->source->enriched->url;
$sentiment = $docRes->docSentiment->score;
$docUrl = $docRes->url;
//Parse source name
if(strpos($docUrl, "http://") !== false){
$source = ltrim($docUrl, "http://");
if (strpos($source, "/") !== false) {
$source = substr($source, 0, strpos($source, "/"));
}
}
elseif(strpos($docUrl, "https://") !== false){
$source = ltrim($docUrl, "https://");
if (strpos($source, "/") !== false) {
$source = substr($source, 0, strpos($source, "/"));
}
}
else{
$source = "Unknown";
}
if(array_key_exists($source, $sources)){
$sources[$source][0] += $sentiment;
$sources[$source][1] += 1;
}
else{
$sources[$source] = array($sentiment, 1);
}
}
//Calculate average sentiment of each source and store in associative array. Also calculate 'global' average accross all retrieved articles
$global_total = 0;
$global_num = 0;
$sentiments = array();
foreach($sources as $source => $value){
$sentiments[$source] = $value[0] / $value[1];
$global_total += $value[0];
$global_num += $value[1];
}
$global_avg = $global_total / $global_num;
$sentiments["Global"] = $global_avg;
//Return JSON of associative array
echo json_encode($sentiments);
?>
|
1887a5dca7f0c3f4332d826d9706c605c31e8071
|
[
"Markdown",
"PHP"
] | 3 |
PHP
|
Capeo/WebInt-Project
|
e61ec6e21117b4e54c9f91255c9c384f5790fb87
|
323362e04d4c463a001dd790cc1ee73b4082c7f1
|
refs/heads/master
|
<file_sep>
## This function creates a matrix object that can cache its inverse.
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
save <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
savecache <- function(matrix) m <<- matrix
getcache <- function() m
list(save = save, get = get,
savecache = savecache,
getcache = getcache)
}
##This function computes the inverse of the matrix returned by makeCacheMatrix above. If the inverse has already been calculated (and the matrix has not changed), then the cachesolve should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x'
m <- x$getcache()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- solve(data, ...)
x$savecache(m)
m
}
|
822e42240debe95312bb8fe573d3526220b30308
|
[
"R"
] | 1 |
R
|
JaHaRa/ProgrammingAssignment2
|
f39e698d66f35489e227178e3fda08ddd5cdfacd
|
34315e5729f4d210cb7795cb4979e36b60b4cdc8
|
refs/heads/master
|
<file_sep>import React from 'react';
import { Mutation } from 'react-apollo';
import { authToken, VOTE_MUTATION } from '../constants';
import { timeDifferenceForDate } from '../utils';
const Link = ({
link: {
description,
url,
votes,
postedBy,
createdAt,
id
},
index,
updateStoreAfterVote
}) =>
<div className="flex mt2 items-start">
<div className="flex items-center">
<span className="gray">{ index + 1 }</span>
{
authToken &&
<Mutation
mutation={ VOTE_MUTATION }
variables={{ linkId: id }}
update={ (store, { data: { vote } }) => updateStoreAfterVote(store, vote, id) }
>
{
voteMutation =>
<div className="ml1 gray f11" onClick={ voteMutation }>
▲
</div>
}
</Mutation>
}
</div>
<div className="ml1">
<div>
{ description } ({ url })
</div>
<div className="f6 lh-copy gray">
{ votes.length } votes | by{ ' ' }
{ postedBy ? postedBy.name : 'Unknown' }{ ' ' }
{ timeDifferenceForDate(createdAt) }
</div>
</div>
</div>
export default Link;
<file_sep>import React, { useState } from 'react';
import { withApollo } from 'react-apollo';
import { FEED_SEARCH_QUERY } from '../constants';
import Link from './Link';
const Search = ({ client }) => {
const [searchInfo, setSearchInfo] = useState({
links: [],
filter: ''
});
const { links, filter } = searchInfo;
const executeSearch = async () => {
const result = await client.query({
query: FEED_SEARCH_QUERY,
variables: { filter }
});
const links = result.data.feed.links;
setSearchInfo({ ...searchInfo, links });
}
return (
<div>
<div>
Search
<input
type="text"
onChange={ e => setSearchInfo({ ...searchInfo, filter: e.target.value }) }
/>
<button onClick={ executeSearch }>OK</button>
</div>
{
links.map((link, index) =>
<Link key={ link.id } link={ link } index={ index } />
)
}
</div>
)
}
export default withApollo(Search);
<file_sep>import React from 'react';
import { Query } from 'react-apollo';
import { FEED_QUERY, NEW_LINKS_SUBSCRIPTION, NEW_VOTES_SUBSCRIPTION, LINKS_PER_PAGE } from '../constants';
import Link from './Link';
const subscribeToNewLinks = subscribeToMore => {
subscribeToMore({
document: NEW_LINKS_SUBSCRIPTION,
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData.data) return prev;
const newLink = subscriptionData.data.newLink;
const exists = prev.feed.links.find(({ id }) => id === newLink.id);
if (exists) return prev;
return Object.assign({}, prev, {
feed: {
links: [newLink, ...prev.feed.links],
count: prev.feed.links.length + 1,
__typename: prev.feed.__typename
}
})
}
})
}
const subscribeToNewVotes = subscribeToMore => {
subscribeToMore({
document: NEW_VOTES_SUBSCRIPTION
})
}
const LinkList = ({ history, location: { pathname }, match: { params: { page } } }) => {
const isNewPage = pathname.includes('new');
const currentPage = parseInt(page, 10);
const skip = isNewPage ? (currentPage - 1) * LINKS_PER_PAGE : 0;
const first = isNewPage ? LINKS_PER_PAGE : 100;
const orderBy = isNewPage ? 'createdAt_DESC' : null;
const updateCacheAfterVote = (store, createVote, linkId) => {
const data = store.readQuery({
query: FEED_QUERY,
variables: { first, skip, orderBy }
});
const votedLink = data.feed.links.find(link => link.id === linkId);
votedLink.votes = createVote.link.votes;
store.writeQuery({ query: FEED_QUERY, data });
}
const getQueryVariables = () => ({ first, skip, orderBy })
const getLinksToRender = ({ feed: { links } }) => {
if (isNewPage) return links;
const rankedList = links.slice();
rankedList.sort((link1, link2) => link2.votes.length - link1.votes.length);
return rankedList;
}
const goToNextPage = ({ feed: { count } }) => {
if (page <= count / LINKS_PER_PAGE) {
const nextPage = currentPage + 1;
history.push(`/new/${nextPage}`);
}
}
const goToPreviousPage = () => {
if (page > 1) {
const previousPage = page - 1;
history.push(`/new/${previousPage}`);
}
}
return (
<Query query={ FEED_QUERY } variables={ getQueryVariables() }>
{
({ loading, error, data, subscribeToMore }) => {
if (loading) return <div>Fetching...</div>
if (error) return <div>Error!</div>
subscribeToNewLinks(subscribeToMore);
subscribeToNewVotes(subscribeToMore);
const linksToRender = getLinksToRender(data);
const pageIndex = page ? (page - 1) * LINKS_PER_PAGE : 0;
return (
<>
{
linksToRender.map((link, index) =>
<Link
key={ link.id }
link={ link }
index={ index + pageIndex }
updateStoreAfterVote={ updateCacheAfterVote }
/>
)
}
{
isNewPage &&
<div className="flex ml4 mv3 gray">
<div className="pointer mr2" onClick={ goToPreviousPage }>Previous</div>
<div className="pointer" onClick={ () => goToNextPage(data) }>Next</div>
</div>
}
</>
)
}
}
</Query>
)
}
export default LinkList;
<file_sep>import React, { useState } from 'react';
import { Mutation } from 'react-apollo';
import { AUTH_TOKEN, LOGIN_MUTATION, SIGNUP_MUTATION } from '../constants';
const initialState = {
login: true,
email: '',
password: '',
name: ''
}
const saveUserData = token => {
localStorage.setItem(AUTH_TOKEN, token)
}
const Login = ({ history }) => {
const [ userInfo, setUserInfo ] = useState(initialState);
const { login, email, password, name } = userInfo;
const confirm = async data => {
const { token } = login ? data.login : data.signup;
saveUserData(token);
history.push('/');
}
return (
<div>
<h4 className="mv3">{ login ? 'Login' : 'Sign Up' }</h4>
<div className="flex flex-column">
{
!login &&
<input
type="text"
placeholder="Your name"
value={ name }
onChange={ e => setUserInfo({ ...userInfo, name: e.target.value }) }
/>
}
<input
type="text"
placeholder="Your email address"
value={ email }
onChange={ e => setUserInfo({ ...userInfo, email: e.target.value }) }
/>
<input
type="password"
placeholder="Choose a safe password"
value={ password }
onChange={ e => setUserInfo({ ...userInfo, password: e.target.value }) }
/>
</div>
<div className="flex mt3">
<Mutation
mutation={ login ? LOGIN_MUTATION : SIGNUP_MUTATION }
variables={{ email, password, name }}
onCompleted={ data => confirm(data) }
>
{
mutation =>
<div className="pointer mr2 button" onClick={ mutation }>
{ login ? 'login' : 'create account' }
</div>
}
</Mutation>
<div className="pointer button" onClick={ () => setUserInfo({ ...userInfo, login: !login }) }>
{ login ? 'need to create an account?' : 'already have an account?' }
</div>
</div>
</div>
)
}
export default Login;
|
10a4a5b7c794ccbc4f6aadfb02d4a740b7332e4b
|
[
"JavaScript"
] | 4 |
JavaScript
|
aloeugene/hacker-news-clone
|
0f4c7278c0550175a3beb81e24864fd29aee3ac9
|
e0e6f45e5bb99623c191d814fbcf404aa890435a
|
refs/heads/master
|
<repo_name>ThomasSquall/PHPMagicAnnotations<file_sep>/tests/MyTestClass.php
<?php
/**
* @MyTest(name = "Thomas", surname = "{$surname}")
*/
class MyTestClass
{
const TEST_CONSTANT = "TEST";
/**
* @var int $age
*/
var $age = 27;
var $surname = "Cocchiara";
public function callTest() {}
/**
* @OneArg(arg = ["ciao", "due"])
* @NoConstructor
*/
public function callTest2() {}
}<file_sep>/tests/NoConstructorAnnotation.php
<?php
use PHPAnnotations\Annotations\Annotation;
class NoConstructorAnnotation extends Annotation
{
}<file_sep>/src/Reflection/Reflector.php
<?php
namespace PHPAnnotations\Reflection;
use \ReflectionProperty as RP;
use \ReflectionMethod as RM;
use \ReflectionClass as RC;
use \stdClass as stdClass;
use \Exception as Exception;
/**
* Extended class for reflection.
* Class Reflector.
*/
class Reflector
{
/**
* Used to get all the properties.
*/
const ALL_PROPERTIES = RP::IS_PUBLIC | RP::IS_PROTECTED | RP::IS_PRIVATE;
/**
* Used to get all the methods.
*/
const ALL_METHODS = RM::IS_PUBLIC | RM::IS_PROTECTED | RM::IS_PRIVATE;
/**
* The object to reflect.
* @var stdClass $object
*/
private $object = null;
/**
* The reflected object.
* @var RC $reflected
*/
private $reflected;
/**
* Array of object annotations.
* @var ReflectionBase[] $annotations
*/
private $annotations;
/**
* Reflector constructor.
* @param mixed $object
* @throws Exception
*/
public function __construct($object)
{
if (is_null($object))
throw new Exception("Cannot evaluate null!");
if (!is_object($object))
throw new Exception("Works with objects only!");
$this->object = $object;
$this->reflected = new RC($object);
$this->prepareAnnotations();
}
/**
* Returns the reflected class.
* @return ReflectionClass
*/
public function getClass()
{
return $this->annotations['class'];
}
/**
* Returns the object constants.
* @return array
*/
public function getConstants()
{
return $this->reflected->getConstants();
}
/**
* Returns the reflected properties.
* @return array[ReflectionProperty[]]
*/
public function getProperties()
{
return $this->annotations['properties'];
}
/**
* Returns the reflected parameter.
* @param string $name
* @return ReflectionProperty
*/
public function getProperty($name)
{
if ($this->reflected->hasProperty($name))
return $this->annotations['properties'][$name];
return null;
}
/**
* Returns the reflected methods.
* @return array[ReflectionMethod[]]
*/
public function getMethods()
{
return $this->annotations['methods'];
}
/**
* Returns the reflected method.
* @param string $name
* @return ReflectionMethod
*/
public function getMethod($name)
{
if ($this->reflected->hasMethod($name))
return $this->annotations['methods'][$name];
return null;
}
private function prepareAnnotations()
{
$docs =
[
'class' => [],
'properties' => [],
'methods' => []
];
$class = new ReflectionClass($this->reflected->name);
$this->calculateAnnotations($class, $this->reflected->getDocComment());
$docs['class'] = $class;
$properties = $this->reflected->getProperties(self::ALL_PROPERTIES);
foreach ($properties as $p)
{
$property = new ReflectionProperty();
$this->calculateAnnotations($property, $p->getDocComment());
$docs['properties'][$p->getName()] = $property;
}
$methods = $this->reflected->getMethods(self::ALL_METHODS);
foreach ($methods as $m)
{
$method = new ReflectionMethod();
$this->calculateAnnotations($method, $m->getDocComment());
$docs['methods'][$m->getName()] = $method;
}
$this->annotations = $docs;
}
private function calculateAnnotations(ReflectionBase &$obj, $docs)
{
$docs = str_replace("\r", "", $docs);
$tmp = strings_between($docs, '@', "\n");
foreach ($tmp as $annotation)
{
if (string_contains($annotation, '('))
$this->calculateAnnotationsWithArgs($obj, $annotation);
else
$this->calculateAnnotationsWithoutArgs($obj, $annotation);
}
}
private function calculateAnnotationsWithArgs(&$obj, $annotation)
{
$args = string_between($annotation, '(', ')');
if ($this->stringContainsExcludingBetween($args, ',', "\"", "\"") &&
$this->stringContainsExcludingBetween($args, ',', "[", "]"))
$args = $this->calculateMultipleArgs($args);
else
$args = $this->calculateSingleArg($args);
foreach ($args as $k => $v)
$args[$k] = $this->parseArg($v);
$aClass = $this->stringBefore($annotation, '(');
$this->getAnnotationsClass($aClass);
$instance = null;
if (is_null($aClass))
return;
if (method_exists($aClass, '__construct'))
$instance = $this->instanceFromConstructor($aClass, $args);
else
$instance = new $aClass();
if ($instance != null)
{
if (count($args) > 0)
{
foreach ($args as $key => $value)
{
if (!property_exists($instance, $key)) continue;
$instance->$key = $value;
}
}
$instance = $this->fillInstance($instance);
$obj->annotations[$aClass] = $instance;
}
}
private function calculateAnnotationsWithoutArgs(&$obj, $annotation)
{
$aClass = $annotation;
$this->getAnnotationsClass($aClass);
if (is_null($aClass))
return;
$instance = $this->fillInstance(new $aClass());
$obj->annotations[$aClass] = $instance;
}
private function calculateMultipleArgs($args)
{
$args = $this->replaceTokens($args, [', ' => ',']);
$args = explode(',', $args);
$namedArgs = [];
foreach ($args as $arg)
{
if (!string_contains($arg, '=')) continue;
$tokens = $this->replaceTokens($arg, [' = ' => '=', ' =' => '=', '= ' => '=']);
$tokens = explode('=', $tokens);
$namedArgs[$tokens[0]] = $tokens[1];
}
return $namedArgs;
}
private function calculateSingleArg($args)
{
if (string_contains($args, '='))
{
$args = $this->replaceTokens($args, [' =' => '=', '= ', '=', ' = ', '=']);
$args = explode('=', $args);
$args = [$args[0] => $args[1]];
}
elseif ($args !== "") $args = [$args];
return $args;
}
private function fillInstance($instance)
{
$instance->obj = $this->object;
return $instance;
}
private function parseArg($value)
{
$v = trim($value);
if (string_starts_with($v, "'") && string_ends_with($v, "'"))
$result = string_between($v, "'", "'");
elseif (string_starts_with($v, '"') && string_ends_with($v, '"'))
$result = string_between($v, '"', '"');
elseif (string_starts_with($v, '[') && string_ends_with($v, ']'))
$result = explode(',', string_between($v, '[', ']'));
elseif (strtolower($v) === 'true')
$result= true;
elseif (strtolower($v) === 'false')
$result = false;
else
{
if (string_contains($v, '.')) $result = floatval($v);
else $result = intval($v);
}
return $result;
}
private function instanceFromConstructor($aClass, &$args)
{
$refMethod = new RM($aClass, '__construct');
$params = $refMethod->getParameters();
$reArgs = [];
foreach ($params as $key => $param)
{
$name = $param->getName();
if (isset($args[$name])) $key = $name;
if (!isset($args[$key]))
{
$reArgs[$key] =
$param->isDefaultValueAvailable() ?
$param->getDefaultValue() :
null;
continue;
}
if ($param->isPassedByReference()) $reArgs[$key] = &$args[$key];
else $reArgs[$key] = $args[$key];
unset($args[$key]);
}
$refClass = new RC($aClass);
return $refClass->newInstanceArgs((array)$reArgs);
}
private function stringBefore($string, $before)
{
$result = false;
if (string_contains($string, $before))
{
$tmp = explode($before, $string);
$result = $tmp[0];
}
return $result;
}
private function stringContainsExcludingBetween($where, $find, $start, $end)
{
$between = string_between($where, $start, $end);
$where = $this->replaceTokens($where, [$start . $between . $end => ""]);
return string_contains($where, $find);
}
private function replaceTokens($text, array $replace)
{
foreach ($replace as $token => $value)
{
$text = str_replace($token, $value, $text);
}
return $text;
}
private function getAnnotationsClass(&$aClass)
{
if (!string_ends_with($aClass, 'Annotation'))
$aClass .= 'Annotation';
$possibleAnnotations = [];
if (!string_contains($aClass, "\\"))
{
foreach (get_declared_classes() as $class)
if (string_ends_with($class, $aClass))
$possibleAnnotations[] = $class;
$count = count($possibleAnnotations);
if ($count > 1)
{
$message = "";
$foundSame = false;
foreach ($possibleAnnotations as $index => $annotation)
{
if ($annotation === $aClass)
{
$possibleAnnotations[0] = $annotation;
$foundSame = true;
break;
}
switch ($index)
{
case $count - 2;
$message .= "$annotation and ";
break;
case $count - 1;
$message .= "$annotation ";
break;
default:
$message .= "$annotation , ";
break;
}
}
if (!$foundSame)
{
$message .= "all satisfy the $aClass. Please use a full namespace instead.";
throw new Exception($message);
}
}
if ($count != 0)
$aClass = $possibleAnnotations[0];
else
$aClass = null;
}
if (!is_subclass_of($aClass, 'PHPAnnotations\Annotations\Annotation'))
$aClass = null;
}
}<file_sep>/src/Reflection/ReflectionMethod.php
<?php
namespace PHPAnnotations\Reflection;
class ReflectionMethod extends ReflectionBase
{
}<file_sep>/src/Reflection/ReflectionClass.php
<?php
namespace PHPAnnotations\Reflection;
class ReflectionClass extends ReflectionBase
{
}<file_sep>/tests/src/Reflection/ReflectionBaseTest.php
<?php
include_once dirname(__FILE__) . '/../../MyTestAnnotation.php';
include_once dirname(__FILE__) . '/../../MyTestClass.php';
use \PHPAnnotations\Reflection\Reflector;
class ReflectionBaseTest extends PHPUnit_Framework_TestCase
{
public function testHasAnnotationTrue()
{
$myClass = new MyTestClass();
$reflector = new Reflector($myClass);
$this->assertTrue($reflector->getClass()->hasAnnotation("MyTest"));
}
public function testHasAnnotationFalse()
{
$myClass = new MyTestClass();
$reflector = new Reflector($myClass);
$this->assertFalse($reflector->getClass()->hasAnnotation("NotMyTest"));
}
public function testGetAnnotation()
{
$expected = "<NAME>";
$myClass = new MyTestClass();
$reflector = new Reflector($myClass);
$this->assertEquals($expected,
$reflector->getClass()->getAnnotation("MyTest")->GetFullName());
$this->assertInstanceOf('MyTestClass',
$reflector->getClass()->getAnnotation("MyTest")->GetObject());
}
public function testGetAnnotationNull()
{
$myClass = new MyTestClass();
$reflector = new Reflector($myClass);
$this->assertNull($reflector->getClass()->getAnnotation("NotMyTest"));
}
}<file_sep>/src/Reflection/ReflectionBase.php
<?php
namespace PHPAnnotations\Reflection;
use PHPAnnotations\Annotations\Annotation;
abstract class ReflectionBase
{
/**
* The array containing our annotations.
* @var Annotation[] $annotations
*/
public $annotations = [];
/**
* Tells if the reflection object has the given annotation or not.
* @param string $name
* @return bool
*/
public function hasAnnotation($name)
{
$result = false;
if (!string_ends_with($name, 'Annotation')) $name .= 'Annotation';
foreach ($this->annotations as $annotation)
{
$class = get_class($annotation);
if (string_starts_with($class, "\\") && !string_starts_with($name, "\\"))
$name = "\\" . $name;
elseif (!string_starts_with($class, "\\") && string_starts_with($name, "\\"))
$name = substr($name, 1);
if (string_ends_with($class, $name))
{
$result = true;
break;
}
}
return $result;
}
private function hasAnnotationAndReturn(&$name)
{
$result = false;
if (!string_ends_with($name, 'Annotation')) $name .= 'Annotation';
foreach ($this->annotations as $annotation)
{
$class = get_class($annotation);
if (string_starts_with($class, "\\") && !string_starts_with($name, "\\"))
$name = "\\" . $name;
elseif (!string_starts_with($class, "\\") && string_starts_with($name, "\\"))
$name = substr($name, 1);
if (string_ends_with($class, $name))
{
$name = $class;
$result = true;
break;
}
}
return $result;
}
/**
* Returns the requested annotation.
* @param string $name
* @return Annotation|null
*/
public function getAnnotation($name)
{
$result = null;
if ($this->hasAnnotationAndReturn($name))
{
if (!string_ends_with($name, 'Annotation')) $name .= 'Annotation';
$result = isset($this->annotations[$name]) ? $this->annotations[$name] : null;
if ($result == null)
{
if (string_starts_with($name, '\\'))
$name = substr($name, 1, strlen($name) - 1);
else
$name = '\\' . $name;
$result = isset($this->annotations[$name]) ? $this->annotations[$name] : null;
}
$result = $this->evaluateAnnotation($result);
}
return $result;
}
private function evaluateAnnotation(Annotation $annotation)
{
$reflected = new \ReflectionClass($annotation);
$properties = $reflected->getProperties(
\ReflectionProperty::IS_PUBLIC |
\ReflectionProperty::IS_PROTECTED
);
foreach ($properties as $p)
{
$key = $p->name;
$value = $annotation->$key;
if (is_string($value) && string_contains($value, '{$'))
{
$fields = strings_between($value, '{$', '}');
$tokens = [];
foreach ($fields as $field)
{
$v = property_exists($annotation->obj, $field) ? $annotation->obj->$field : "";
$tokens['{$' . $field . '}'] = $v;
}
$value = $this->replaceTokens($value, $tokens);
$annotation->$key = $value;
}
}
return $annotation;
}
private function replaceTokens($text, array $replace)
{
foreach ($replace as $token => $value)
{
$text = str_replace($token, $value, $text);
}
return $text;
}
}<file_sep>/tests/src/Reflection/ReflectorTest.php
<?php
include_once dirname(__FILE__) . '/../../MyTestAnnotation.php';
include_once dirname(__FILE__) . '/../../OneArgAnnotation.php';
include_once dirname(__FILE__) . '/../../NoConstructorAnnotation.php';
include_once dirname(__FILE__) . '/../../MyTestClass.php';
use \PHPAnnotations\Reflection\Reflector;
class ReflectorTest extends PHPUnit_Framework_TestCase
{
public function testConstructorWithNullObject()
{
$result = false;
try { new Reflector(null); }
catch(Exception $ex) { $result = true; }
$this->assertTrue($result);
}
public function testConstructorWithNonObject()
{
$result = false;
try { new Reflector(10); }
catch(Exception $ex) { $result = true; }
$this->assertTrue($result);
}
public function testConstructorWithObject()
{
$result = true;
$myClass = new MyTestClass();
try { new Reflector($myClass); }
catch(Exception $ex) { $result = false; }
$this->assertTrue($result);
}
public function testGetConstants()
{
$myClass = new MyTestClass();
$reflector = new Reflector($myClass);
$this->assertCount(1, $reflector->getConstants());
}
public function testGetProperties()
{
$myClass = new MyTestClass();
$reflector = new Reflector($myClass);
$this->assertCount(2, $reflector->getProperties());
}
public function testGetExistingProperty()
{
$myClass = new MyTestClass();
$reflector = new Reflector($myClass);
$this->assertNotNull($reflector->getProperty('age'));
}
public function testGetNonExistingProperty()
{
$myClass = new MyTestClass();
$reflector = new Reflector($myClass);
$this->assertNull($reflector->getProperty('fsd'));
}
public function testGetMethods()
{
$myClass = new MyTestClass();
$reflector = new Reflector($myClass);
$this->assertCount(2, $reflector->getMethods());
}
public function testGetExistingMethod()
{
$myClass = new MyTestClass();
$reflector = new Reflector($myClass);
$this->assertNotNull($reflector->getMethod('callTest'));
}
public function testGetNonExistingMethod()
{
$myClass = new MyTestClass();
$reflector = new Reflector($myClass);
$this->assertNull($reflector->getMethod('fwe'));
}
public function testAnnotationWithNoConstructor()
{
$myClass = new MyTestClass();
$reflector = new Reflector($myClass);
$this->assertTrue($reflector->getMethod('callTest2')->hasAnnotation('NoConstructor'));
}
public function testAnnotationWithOneArg()
{
$myClass = new MyTestClass();
$reflector = new Reflector($myClass);
$this->assertTrue($reflector->getMethod('callTest2')->hasAnnotation('OneArg'));
}
}<file_sep>/tests/MyTestAnnotation.php
<?php
namespace tests;
use PHPAnnotations\Annotations\Annotation;
class MyTestAnnotation extends Annotation
{
protected $name;
protected $surname;
public function __construct($name, $surname)
{
$this->name = $name;
$this->surname = $surname;
}
public function GetFullName()
{
return "$this->name $this->surname";
}
public function GetObject()
{
return $this->obj;
}
}<file_sep>/src/Annotations/Annotation.php
<?php
namespace PHPAnnotations\Annotations;
class Annotation
{
protected $obj;
public function __set($key, $value)
{
if (!property_exists($this, $key))
throw new \Exception("Param $key does not exist in " . get_class($this) . " annotation!");
$trace = debug_backtrace();
$class = $trace[1]['class'];
if ('\PHPAnnotations\Reflection\Reflector' === $class ||
'PHPAnnotations\Reflection\Reflector' === $class ||
is_a($class, '\PHPAnnotations\Reflection\ReflectionBase', true) ||
is_a($class, 'PHPAnnotations\Reflection\ReflectionBase', true))
{
$this->$key = $value;
}
}
/**
* __get magic method used to retrieve the name.
* @param string $param
* @return null
*/
public function __get($param)
{
$result = null;
if (property_exists($this, $param)) $result = $this->$param;
return $result;
}
}<file_sep>/src/Reflection/ReflectionProperty.php
<?php
namespace PHPAnnotations\Reflection;
class ReflectionProperty extends ReflectionBase
{
}<file_sep>/src/Utils.php
<?php
function class_has_annotation($object, $annotation)
{
$reflector = get_class_reflector($object);
if (!is_string($annotation))
throw new Exception("Second argument of class_has_annotation should be a string, " .
gettype($object) . " given instead.");
return $reflector->getClass()->hasAnnotation($annotation);
}
function method_has_annotation($object, $method, $annotation)
{
$reflector = get_class_reflector($object);
if (!is_string($method))
throw new Exception("Second argument of method_has_annotation should be a string, " .
gettype($method) . " given instead.");
if (!is_string($annotation))
throw new Exception("Third argument of method_has_annotation should be a string, " .
gettype($annotation) . " given instead.");
$reflectedMethod = $reflector->getMethod($method);
if (is_null($reflectedMethod))
throw new Exception("Method $method does not exist in " . gettype($object) . " class.");
/** @var \PHPAnnotations\Reflection\ReflectionMethod $reflectedMethod */
return $reflectedMethod->hasAnnotation($annotation);
}
function property_has_annotation($object, $property, $annotation)
{
$reflector = get_class_reflector($object);
if (!is_string($property))
throw new Exception("Second argument of property_has_annotation should be a string, " .
gettype($property) . " given instead.");
if (!is_string($annotation))
throw new Exception("Third argument of property_has_annotation should be a string, " .
gettype($annotation) . " given instead.");
$reflectedProperty = $reflector->getProperty($property);
if (is_null($reflectedProperty))
throw new Exception("Property $property does not exist in " . gettype($object) . " class.");
/** @var \PHPAnnotations\Reflection\ReflectionMethod $reflectedProperty */
return $reflectedProperty->hasAnnotation($annotation);
}
function get_class_annotation($object, $annotation)
{
if (class_has_annotation($object, $annotation))
return get_class_reflector($object)->getClass()->getAnnotation($annotation);
return null;
}
function get_method_annotation($object, $method, $annotation)
{
if (method_has_annotation($object, $method, $annotation))
return get_class_reflector($object)->getMethod($method)->getAnnotation($annotation);
return null;
}
function get_property_annotation($object, $property, $annotation)
{
if (property_has_annotation($object, $property, $annotation))
return get_class_reflector($object)->getProperty($property)->getAnnotation($annotation);
return null;
}
function get_class_methods_annotations($object)
{
return get_class_reflector($object)->getMethods();
}
function get_class_properties_annotations($object)
{
return get_class_reflector($object)->getProperties();
}
function get_class_reflector($object)
{
/** @var [\PHPAnnotations\Reflection\Reflector] $reflectors */
static $reflectors = [];
if (is_object($object))
$class = get_class($object);
else
throw new Exception("First argument should be an object, " .
gettype($object) . " given instead.");
if (!array_key_exists($class, $reflectors))
$reflectors[$class] = new \PHPAnnotations\Reflection\Reflector($object);
return $reflectors[$class];
}<file_sep>/tests/OneArgAnnotation.php
<?php
use PHPAnnotations\Annotations\Annotation;
class OneArgAnnotation extends Annotation
{
protected $myArg;
public function __construct($arg)
{
$this->myArg = $arg;
}
}<file_sep>/README.md
## Annotations for PHP
[](https://packagist.org/packages/thomas-squall/php-magic-annotations)
[](https://travis-ci.org/ThomasSquall/PHPMagicAnnotations)
[](https://coveralls.io/github/ThomasSquall/PHPMagicAnnotations?branch=master)
[](https://codecov.io/gh/ThomasSquall/PHPMagicAnnotations)
[](https://packagist.org/thomas-squall/php-magic-annotationsr)
[](https://packagist.org/packages/thomas-squall/php-magic-annotations)
PHP does not have any kind of native annotation (AKA attributes from .NET world) so if you'd like to implement your own annotation framework think of using this first and save some time.
### Installation
Using composer is quite simple, just run the following command:
```
$ composer require thomas-squall/php-magic-annotations
```
### Usage
#### Create a new Annotation
First you have to create a new class. In this example the class will be called **MyCustomAnnotation**
``` php
class MyCustomAnnotation
{
}
```
Then you'll have to extend the **Annotation** class from the library
``` php
use PHPAnnotations\Annotations\Annotation;
class MyCustomAnnotation extends Annotation
{
}
```
Add some logic to it
``` php
use PHPAnnotations\Annotations\Annotation;
class MyCustomAnnotation extends Annotation
{
private $name;
private $surname;
public function __constructor($name, $surname)
{
$this->name = $name;
$this->surname = $surname;
}
public function GetFullName()
{
return "$this->name $this->surname";
}
}
```
Now our beautiful annotation is ready to go!
#### Use the annotation
Create a class to used to test the annotation
``` php
class MyTestClass
{
}
```
And add the annotation through the docs
``` php
/**
* @MyCustom(name = "Thomas", surname = "Cocchiara")
**/
class MyTestClass
{
}
```
Now we're ready to test it out!
``` php
use use PHPAnnotations\Reflection\Reflector;
$myObject = new MyTestClass();
$reflector = new Reflector($myObject);
echo $reflector->getClass()->getAnnotation("MyCustom")->GetFullName();
```
Hope you guys find this library useful.
Please share it and give me a feedback :)
Thomas
|
5cf40b781ffafc350f5d41c15a928b522789e13b
|
[
"Markdown",
"PHP"
] | 14 |
PHP
|
ThomasSquall/PHPMagicAnnotations
|
d07b1318486c3f942cfc0163f995f2dd6c916378
|
e3446f76857ae0608754eb88756a57d1cca65c87
|
refs/heads/master
|
<file_sep># Hazelcast Open Binary Client Protocol
**Hazelcast Open Binary Client Protocol** definitions and code generator for multiple programming languages.
## Hazelcast Open Binary Client Protocol Definitions
The protocol is defined in `protocol-definitions/*.yaml` yaml files where each yaml file represents a service like Map, List, Set etc.
## Service definition
A service is defined by a separate YAML file, containing all its method definitions.
```yaml
id: Service Id (1-255)
name: Service Name
methods:
- id: METHOD-ID-1 (1-255)
name: METHOD-NAME-1
...
- id: METHOD-ID-2 (1-255)
name: METHOD-NAME-2
...
```
A method(aka Remote method call) is defined by a request-response pair. If the method definition
A basic method structure example:
```yaml
- id: METHOD-ID-1 (1-255)
name: METHOD-NAME-1
since: 2.0
doc: |
Documentation of the method call
request:
retryable: false
acquiresResource: false
partitionIdentifier: None
params:
- name: parameter1
type: String
nullable: false
since: 2.0
doc: |
Documentation of the parameter 1
- name: parameter1
type: Data
nullable: false
since: 2.0
doc: |
Documentation of the parameter 2
response:
params:
- name: response parameter 1
type: Data
nullable: true
since: 2.0
doc: |
the response parameter 1
#Optional events section
events:
- name: Event-1
params:
- name: event-param-1
type: Data
nullable: true
since: 2.0
doc: |
Documentation of the event parameter 1
- name: value
type: Data
nullable: true
since: 2.0
doc: |
Documentation of the event parameter 2
```
Please refer to [schema](schema/protocol-schema.json) for details of a service definition.
## Code Generator
The new protocol generator, generates the related language codecs into the configured folder. It does not depend on hazelcast repo.
### Setup
You need to have python3 configured on your `PATH`. After cloning the repository, install the python library dependencies:
```bash
pip3 install -r requirements.txt
```
### Code Generation
You can generate codecs for your favorite language by calling,
```bash
./generator.py [--root-dir ROOT_DIRECTORY] [--lang LANGUAGE]
```
where
* `ROOT_DIRECTORY` is the root folder. If left empty, default value is `./output/[LANGUAGE]`.
* `LANGUAGE` is one of
* `JAVA` : Java
* `CPP` : C++
* `CS` : C#
* `PY` : Python
* `TS` : Typescript
* `GO` : Go
`JAVA` will be the default value if left empty.
If you want to generate java codecs into your development repo, and let's assume your local hazelcast git repo is at
`~/git/hazelcast/` then you can call,
```bash
./generator.py --root-dir ~/git/hazelcast/
```
### Schema Validation
The protocol definitions should validate against the [schema](schema/protocol-schema.json). You can configure your favorite IDE to
use this schema to validate and provide autocompletion.
The generator also uses this schema during code generation. It will report any schema problem on the console.
<file_sep>FixedLengthTypes = [
"boolean",
"byte",
"int",
"long",
"UUID"
]
VarLengthTypes = [
'byteArray',
'longArray',
'String',
'Data'
]
FixedMapTypes = [
'Map_Integer_UUID',
'Map_String_Long',
'Map_Integer_Long'
]
FixedListTypes = [
'List_Integer',
'List_Long',
'List_UUID'
]
CustomTypes = [
'Address',
'CacheEventData',
'DistributedObjectInfo',
'Member',
'QueryCacheEventData',
'RaftGroupId',
'ScheduledTaskHandler',
'SimpleEntryView',
'WanReplicationRef',
'Xid'
]
CustomConfigTypes = [
'CacheSimpleEntryListenerConfig',
'EventJournalConfig',
'EvictionConfigHolder',
'HotRestartConfig',
'ListenerConfigHolder',
'MapAttributeConfig',
'MapIndexConfig',
'MapStoreConfigHolder',
'MerkleTreeConfig',
'NearCacheConfigHolder',
'NearCachePreloaderConfig',
'PredicateConfigHolder',
'QueryCacheConfigHolder',
'QueueStoreConfigHolder',
'RingbufferStoreConfigHolder',
'TimedExpiryPolicyFactoryConfig'
]
VarLengthMapTypes = [
'Map_String_String',
'Map_String_byteArray',
'Map_String_Long',
'Map_String_Map_Integer_Long',
'Map_Address_List_Integer',
'Map_Data_Data',
'Map_Member_List_ScheduledTaskHandler'
]
VarLengthListTypes = [
'List_Address',
'List_byteArray',
'List_CacheEventData',
'List_CacheSimpleEntryListenerConfig',
'List_Data',
'List_DistributedObjectInfo',
'List_ListenerConfigHolder',
'List_MapAttributeConfig',
'List_MapIndexConfig',
'List_Member',
'List_QueryCacheConfigHolder',
'List_QueryCacheEventData',
'List_ScheduledTaskHandler',
'List_String',
'List_Xid',
]
AllTypes = FixedLengthTypes + VarLengthTypes + FixedMapTypes + FixedListTypes + CustomTypes + CustomConfigTypes \
+ VarLengthMapTypes + VarLengthListTypes
<file_sep>#!/usr/bin/env python3
import time
import argparse
from util import *
start = time.time()
parser = argparse.ArgumentParser(description='Hazelcast Code Generator generates code of client protocol '
'across languages.')
parser.add_argument('-r', '--root-dir',
dest='root_dir', action='store',
metavar='ROOT_DIRECTORY', default=None,
type=str, help='Root directory for the generated codecs (default is ./output/[LANGUAGE])')
parser.add_argument('-l', '--lang',
dest='lang', action='store',
metavar='LANGUAGE', default='java',
choices=[lang.value for lang in SupportedLanguages],
type=str, help='Language to generate codecs for (default is java)')
args = parser.parse_args()
lang_str = args.lang
root_dir_arg = args.root_dir
lang = SupportedLanguages[lang_str.upper()]
root_dir = root_dir_arg if root_dir_arg is not None else './output/' + lang_str
output_dir = root_dir + output_directories[lang]
# PWD
dir_path = os.path.dirname(os.path.realpath(__file__))
protocol_defs_path = dir_path + '/protocol-definitions/'
schema_path = dir_path + '/schema/protocol-schema.json'
services = load_services(protocol_defs_path)
if not validate_services(services, schema_path):
exit(-1)
env = create_environment(lang)
codec_template = env.get_template("codec-template.%s.j2" % lang_str)
generate_codecs(services, codec_template, output_dir, file_extensions[lang])
end = time.time()
print("Generator took: %d secs" % (end - start))
print('Generated codecs are at \'%s\'' % os.path.abspath(output_dir))
|
72004de88df43356b1c711d42d1ccfbe5f6b1666
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
petrpleshachkov/hazelcast-client-protocol
|
c0096cdea701442d2c9caddc0076c674adef4ff8
|
84fb05e63febc8bf92c2444692bbf688a01655b8
|
refs/heads/main
|
<repo_name>alemprogramer/react-filtering<file_sep>/src/pages/homePage/desclaimer/Desclaim.jsx
import React from 'react';
import "./desclaim.css";
const Desclaim=()=> {
return (
<div className='position-fixed containerPart' >
<div className="contentArea">
</div>
</div>
)
}
export default Desclaim
<file_sep>/src/components/headings/CommonHead.jsx
import React, {Component} from 'react'
export class CommonHead extends Component {
render() {
const { title, slogan, icon}=this.props;
return (
<div className="row">
<div className="col-md-12 col-sm-12">
<div className="cmn_heading text-capitalize text-center">
<h3>
{title}
</h3>
{slogan ? <h6>{slogan} {icon ? <span>
<i className={`fas ${icon}`}></i>
</span>:''} </h6>:""}
</div>
</div>
</div>
)
}
}
export default CommonHead
<file_sep>/README.md
Dependancies Used :
React-Slick
React-Bootstrap
React-Router
React-Wow
Trying to use Hooks and Functional Components instead of Class-Based Components
The Footer and the carousel takes more time than expected, Last thing to do is add lazy and suspense on all sliders and Footer
On development : I've target to develop this app with Laravel and then make it a progressive app. This message is for my Laravel Developer.
You've to use Passport ( Laravel Package of Oauth2), Spatie, Stripe, Cashier (for stripe), Excel Sheet, Easypost, Multiple Mailing API, ReCaptcha and maybe more .<file_sep>/src/components/banner/index.jsx
import { useState,useEffect } from "react";
import Desk from "./desk";
import Mobile from "./mobile";
import mediaObserver from "../breakPoints/breakpoint";
function Banner(props) {
const { blogger,title, miniTitle, text, price, img, url, urlIcon, urlText, buttonText}=props;
// { title, miniTitle, text, price, link, image, linkText, buttonText }
const [media, setMedia] = useState();
useEffect(() => {
mediaObserver(setMedia);
}, [media]);
return (
<>
{media === 'mobile' ? <Mobile title={title} miniTitle={miniTitle} text={text} price={price} link={url} image={img} linkText={urlText} buttonText={buttonText}/> : <Desk title={title} miniTitle={miniTitle} blog={blogger} text={text} price={price} image={img} link={url} linkIcon={urlIcon} linkText={urlText} buttonText={buttonText} />}
</>
)
}
export default Banner
<file_sep>/src/components/navbar/LargeNavbar.jsx
import React, {Suspense, lazy, useState, useEffect, useContext} from 'react'
import {Link} from "react-router-dom";
import Loaders from '../contexts';
import { Logo, NavItem } from '../loader/navbarLoader';
const MegaMenu = lazy(() => import ("./MegaMenu"));
const LargeNavbar = ({data}) => {
const {loader}= useContext(Loaders);
const [services,
setServices] = useState([]);
useEffect(() => {
setServices(data);
return () => {
};
// eslint-disable-next-line
}, [services]);
useEffect(() => {
console.log(loader);
setTimeout(() => {
}, 2000);
return () => {
setServices([]);
};
// eslint-disable-next-line
}, []);
console.log(loader);
return (
<section
className="page-head">
<div className="rd-navbar-wrap">
<div
className="header-bar-area rd-navbar rd-navbar-corporate-light rd-navbar-original rd-navbar-static rd-navbar--is-stuck">
<div className="container">
<div className="row">
<div className="col-lg-2 col-xl-2 col-sm-2 col-md-2 d-flex align-items-center">
<div className="logo-area overflow-hidden">
{loader === true ? <Logo/> :<Link to='/'>Virtual Decor</Link>}
</div>
</div>
<div className="col-lg-10 col-md-10 col-sm-10 col-xl-10 text-right">
<div className="main-menu">
<ul>
{loader === true ? [1, 2, 3, 4, 5, 6].map(d => <li className="overflow-hidden" key={d}>
<NavItem/>
</li>):<>
<li>
<Link to='/service' className="nav-link">Services</Link>
<div className="mega-menu">
<Suspense fallback={< p > Please wait ...</p>}>
{services
.map(t =>< MegaMenu key = {
t.mainTitle
}
title = {
t.mainTitle
}
data = {
t.datas
} />)}
</Suspense>
</div>
</li>
<li>
<Link to='/portfolio' className="nav-link">Portfolio</Link>
</li>
<li>
<Link to='/blog' className="nav-link">Blog</Link>
</li>
<li>
<Link to='/faq' className="nav-link">Help</Link>
</li>
<li>
<Link to='/contact' className="nav-link">Contact</Link>
</li>
<li>
<Link to=''>Sign in</Link>
</li>
<li>
<Link to='' className="btn">Place Order</Link>
</li>
</>
}
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
)
}
export default LargeNavbar
<file_sep>/src/components/Js/index.js
const url = process.env.PUBLIC_URL;
const imgUrl = `${url}/vendor/images`;
const array = [
{ // take
setA: {
title: 'Vacant Photos',
img: `${imgUrl}/vacant.png`,
text: `We specialize in transforming photos of vacant properties into beautiful, virtually staged homes that sells faster and for top dollar.`,
importance: 2
},
setB: {
title: 'Floor Plans',
img: `${imgUrl}/vacant.png`,
text: `We specialize in transforming photos of vacant properties into beautiful, virtually staged homes that sells faster and for top dollar.`,
importance: 2
},
setC: {
title: 'Dimensions',
img: `${imgUrl}/vacant.png`,
text: `We specialize in transforming photos of vacant properties into beautiful, virtually staged homes that sells faster and for top dollar.`,
importance: 1
}
}, { //give
setA: {
title: 'Digitally Staged Photos',
text: `We specialize in transforming photos of vacant properties into beautiful, virtually staged homes that sells faster and for top dollar.`,
img: `${imgUrl}/vacant.png`
},
setB: {
title: 'Same Size',
text: `We specialize in transforming photos of vacant properties into beautiful, virtually staged homes that sells faster and for top dollar.`,
img: `${imgUrl}/vacant.png`
},
setC: {
title: 'Top Notch Support',
text: `We specialize in transforming photos of vacant properties into beautiful, virtually staged homes that sells faster and for top dollar.`,
img: `${imgUrl}/vacant.png`
}
}, { //faq
setA: {
head: `What are the pricing packages for the virtual staging service?`,
text: `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras consequat, lectus quis efficitur consectetur, turpis erat porta magna, quis tincidunt mi sem in enim. Integer cursus eu metus non eleifend. Maecenas vel euismod enim. Morbi dignissim dolor justo, eu dignissim mauris pellentesque nec. Quisque leo nulla, suscipit sed sem in, pulvinar tristique enim. In non placerat neque. Duis pharetra velit in sapien feugiat, vitae viverra ligula condimentum. Proin eget mauris leo.`
},
setB: {
head: `What happens if I upload a photo that is a small size or low resolution or may not work with your service?`,
text: `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras consequat, lectus quis efficitur consectetur, turpis erat porta magna, quis tincidunt mi sem in enim. Integer cursus eu metus non eleifend. Maecenas vel euismod enim. Morbi dignissim dolor justo, eu dignissim mauris pellentesque nec. Quisque leo nulla, suscipit sed sem in, pulvinar tristique enim. In non placerat neque. Duis pharetra velit in sapien feugiat, vitae viverra ligula condimentum. Proin eget mauris leo.`
},
setC: {
head: `How long does it take to process my order and get my staged photos back?`,
text: `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras consequat, lectus quis efficitur consectetur, turpis erat porta magna, quis tincidunt mi sem in enim. Integer cursus eu metus non eleifend. Maecenas vel euismod enim. Morbi dignissim dolor justo, eu dignissim mauris pellentesque nec. Quisque leo nulla, suscipit sed sem in, pulvinar tristique enim. In non placerat neque. Duis pharetra velit in sapien feugiat, vitae viverra ligula condimentum. Proin eget mauris leo.`
},
setD: {
head: `How long can I use the virtually staged photos?`,
text: `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras consequat, lectus quis efficitur consectetur, turpis erat porta magna, quis tincidunt mi sem in enim. Integer cursus eu metus non eleifend. Maecenas vel euismod enim. Morbi dignissim dolor justo, eu dignissim mauris pellentesque nec. Quisque leo nulla, suscipit sed sem in, pulvinar tristique enim. In non placerat neque. Duis pharetra velit in sapien feugiat, vitae viverra ligula condimentum. Proin eget mauris leo.`
},
setE: {
head: `Does VSP alter the photographs by changing the wall colors, adding appliances and removing fixtures, etc?`,
text: `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras consequat, lectus quis efficitur consectetur, turpis erat porta magna, quis tincidunt mi sem in enim. Integer cursus eu metus non eleifend. Maecenas vel euismod enim. Morbi dignissim dolor justo, eu dignissim mauris pellentesque nec. Quisque leo nulla, suscipit sed sem in, pulvinar tristique enim. In non placerat neque. Duis pharetra velit in sapien feugiat, vitae viverra ligula condimentum. Proin eget mauris leo.`
},
setF: {
head: `Can I provide suggestions with respect to the staging of the photos?`,
text: `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras consequat, lectus quis efficitur consectetur, turpis erat porta magna, quis tincidunt mi sem in enim. Integer cursus eu metus non eleifend. Maecenas vel euismod enim. Morbi dignissim dolor justo, eu dignissim mauris pellentesque nec. Quisque leo nulla, suscipit sed sem in, pulvinar tristique enim. In non placerat neque. Duis pharetra velit in sapien feugiat, vitae viverra ligula condimentum. Proin eget mauris leo.`
}
}, { //differ
a: {
icon: `${imgUrl}/user.png`,
title: 'Professional Home Stagers',
text: 'We specialize in transfcascasorming photos of vacant properties into beautiful, ' +
'virtually staged homes that sells faster and for top dollar.'
},
b: {
icon: `${imgUrl}/user.png`,
title: 'Professasascional Home Stagers',
text: 'We specialize in trascascansforming photos of vacant properties into beautiful, ' +
'virtually staged homes that sells faster and for top dollar.'
},
c: {
icon: `${imgUrl}/user.png`,
title: 'Professional Hocasme Stagers',
text: 'We specialize in transforming photos of vacant properties into beautiful, virtua' +
'lly staged homes that sells faster and for top dollar.'
},
d: {
icon: `${imgUrl}/user.png`,
title: 'Professional Home Staascgers',
text: 'We specialize in transforming photos of vacant properties into beautiful, virtua' +
'lly staged homes that sells faster and for top dollar.'
},
e: {
icon: `${imgUrl}/user.png`,
title: 'Professional Home Stagers',
text: 'We specialize in transforming photos of vacant properties into beautiful, virtua' +
'lly staged homescbf that sells faster and for top dollar.'
},
f: {
icon: `${imgUrl}/user.png`,
title: 'Profesgfdsional Home Stagers',
text: 'We specialnfgnfgize in transforming photos of vacant properties into beautiful, ' +
'virtually staged homes that sells faster and for top dollar.'
}
}, { //howIt
setA: {
head: `Virtual Home Staging`,
text: `Upload photos ( please use professional high resolution photos, not the ones you can take on your phone)`,
image: `${imgUrl}/how.jpg`
},
setB: {
head: `Interior Design and Support`,
text: `Upload photos (not the ones you can take on your phone)`,
image: `${imgUrl}/how_2.jpg`
},
setC: {
head: `Virtual Home Staging`,
text: `Upload photos ( please use professional high resolution photos, not the ones you can take on your phone)`,
image: `${imgUrl}/how_3.jpg`
},
setD: {
head: `Interior Design`,
text: `Upload photos (not the ones you can take on your phone)`,
image: `${imgUrl}/how_4.jpg`
}
},
];export default array
|
0a1c039eabf68dd49cf1f0f9e0f13165fdc5074e
|
[
"JavaScript",
"Markdown"
] | 6 |
JavaScript
|
alemprogramer/react-filtering
|
7bf13e9f9e6c80cb5d0eeca7bab6651fbe664174
|
2bebde16d472481651ea74cc068214920a28b806
|
refs/heads/master
|
<repo_name>bhurlow/textual<file_sep>/server.js
var ecstatic = require('ecstatic')
var http = require('http')
var fs = require('fs')
http.createServer(ecstatic({ root: __dirname + '/public' })).listen(3000)
<file_sep>/make.sh
browserify main.js > public/bundle.js
<file_sep>/main.js
/*
* <NAME> 2014
*/
var through = require('through2')
var ready = require('domready')
var domstream = require('./lib/domstream')
// db config
var levelup = require('levelup')
var leveljs = require('level-js')
var sublevel = require('level-sublevel')
var search = require('level-inverted-index')
var db = levelup('textual', { db: leveljs })
var db = window.db = sublevel(db)
// text search index
var index = search(db, 'search')
// cache of top keys
window.topkeys = []
var hooks = require('level-hooks')(window.db)
var ACTIVE = null
//db.hooks.post(function(change, add) {
//console.log('hy')
//console.log(change)
//console.log(add)
//})
// fill the index
//db.createReadStream().pipe(through.obj(fill))
//function fill(chunk, enc, cb) {
//cb()
//}
ready(function() {
window.input = document.querySelector('input[type=search]')
window.stubs = document.querySelector('.stubs')
window.area = document.querySelector('textarea')
window.renderstream = domstream(window.stubs)
// render all on first load
db.createReadStream().pipe(renderstream)
document.addEventListener('keypress', function(e) {
var isNumberKey = isNumberKeyCode(e.keyCode)
if (isNumberKey) {
handleNumber(e.keyCode)
e.preventDefault()
}
})
input.addEventListener('input', function(e) {
var val = this.value
if (e.keyCode === 13) return submit.call(this, val)
console.log(val)
query(val)
})
window.area.addEventListener('keypress', function() {
// would consider throttling this
return updateActive(this.value)
})
})
function query(q) {
console.log(q)
index.createQueryStream(q.split(' ')).on('data', function(chunk) {
console.log(chunk)
})
}
function show(key) {
console.log(key)
db.get(key, function(err, value) {
if (err) throw err
console.log(value)
})
}
function submit(value) {
db.put(value, ' ', function(err) {
if (err) throw err
window.area.focus()
ACTIVE = value
})
}
function updateActive(value) {
value = value || ' '
db.put(ACTIVE, value, function(err) {
if (err) throw err
})
}
var keyMap = function() {
var o = {}
var y = 1
var x = 49
while (x <= 57) {
o[x] = y
y++
x++
}
return o
}()
function isNumberKeyCode(code) {
console.log(code)
return (code >= 49 && code <= 57)
}
function handleNumber(code) {
var key = keyMap[code]
show(window.topkeys[key - 1])
}
function createNewEntry() {
}
<file_sep>/lib/domstream.js
var through = require('through2');
module.exports = function domStream(el) {
var tr = through.obj(write)
tr.readable = false
var stack = []
var counter = 0
return tr
function write(chunk, enc, cb) {
console.log(counter)
window.topkeys[counter] = chunk.key
var innerEl = document.createElement('span')
innerEl.className += 'block'
innerEl.innerHTML = (counter + 1) + ' ' + chunk.key + ' – ' + truncate(chunk.value)
el.appendChild(innerEl)
counter++
return cb()
}
}
function truncate(string) {
return string.slice(0, 20) + '...'
}
<file_sep>/watch.sh
#!/bin/sh
watchify main.js -o public/bundle.js
|
5a0d31f4b0d297b532d0f5ef2efdd04a6b604348
|
[
"JavaScript",
"Shell"
] | 5 |
JavaScript
|
bhurlow/textual
|
e5301e96009cc37c716d5e2abedd8677837f3ccf
|
836f1f2fee82d69e8247b840e3f337c04a78f369
|
refs/heads/master
|
<file_sep>using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Tasklist.Domain.Contracts.Repositories;
using Tasklist.Domain.Entities;
namespace Tasklist.DAL.SQL.Repositories
{
public class ProjectRepository : BaseRepository<DataContext, Project>, IProjectRepository
{
public ProjectRepository(DataContext dbContext) : base(dbContext)
{
}
public override Task<Project> GetByIdAsync(object id)
{
return DbSet.Include(p => p.Tasks).FirstOrDefaultAsync(p => p.Id.Equals((long)id));
}
protected override IQueryable<Project> AllQuery()
{
return base.AllQuery().Include(p => p.Tasks);
}
public Task<List<Project>> GetProjectsByNameAsync(string nameSubstring)
{
return AllQuery().Where(p => p.Name.Contains(nameSubstring)).ToListAsync();
}
}
}
<file_sep>using System.Collections.Generic;
using System.Threading.Tasks;
using Tasklist.Domain.Entities;
using Task = System.Threading.Tasks.Task;
namespace Tasklist.Domain.Contracts.Services
{
public interface IProjectService
{
Task<Project> GetProjectByIdAsync(long id);
Task<List<Project>> GetAllProjectsAsync();
Task AddProjectAsync(Project project);
Task DeleteProjectAsync(long id);
Task UpdateProjectAsync(Project project);
}
}
<file_sep>using Tasklist.Domain.Contracts.Repositories;
using Task = Tasklist.Domain.Entities.Task;
namespace Tasklist.DAL.SQL.Repositories
{
public class TaskRepository:BaseRepository<DataContext,Task>, ITaskRepository
{
public TaskRepository(DataContext dbContext) : base(dbContext)
{
}
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using Tasklist.Domain.Entities;
using Tasklist.Web.Models;
namespace Tasklist.Web.Mapping
{
public static class ProjectMapper
{
public static ProjectModel Map(Project project)
{
if (project == null)
{
return null;
}
return new ProjectModel
{
Id = project.Id,
Name = project.Name,
Description = project.Description,
DueDate = project.DueDate,
Tasks = project.Tasks?.Select(TaskMapper.Map).ToList() ?? new List<TaskModel>(),
};
}
}
}<file_sep>using System.Data.Entity;
using Tasklist.DAL.SQL.Maps;
using Tasklist.Domain.Entities;
namespace Tasklist.DAL.SQL
{
public class DataContext : DbContext
{
public DataContext()
: base("Name=DataContext")
{
Configuration.LazyLoadingEnabled = false;
Configuration.AutoDetectChangesEnabled = false;
}
public DbSet<Project> Projects { get; set; }
public DbSet<Task> Tasks{ get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ProjectMap());
modelBuilder.Configurations.Add(new TaskMap());
}
}
}
<file_sep>(function () {
'use strict';
var app = angular.module('app', [
'ngAnimate',
'ngRoute',
'ngSanitize',
'ui.bootstrap',
'mwl.confirm',
'common'
]);
app.run(['$route', function ($route) {
}]);
})();<file_sep>using System.Collections.Generic;
using System.Threading.Tasks;
namespace Tasklist.Domain.Contracts.Repositories
{
public interface IBaseRepository<T> where T : class
{
Task<List<T>> GetAllAsync();
Task<T> GetByIdAsync(object id);
void Add(T obj);
void Update(T obj);
void Delete(T entity);
}
}
<file_sep>(function () {
'use strict';
var controllerId = 'projectsController';
angular
.module('app')
.controller(controllerId, projectsController);
projectsController.$inject = ['$location', 'common', 'repository'];
function projectsController($location, common, repository) {
var vm = this;
var log = common.logger.getLogFn(controllerId);
vm.projects = [];
vm.edit = function(id) {
$location.path('/editProject/' + id);
};
activate();
function activate() {
common.activateController([getProjects(), controllerId]);
}
function getProjects() {
return repository.getAllProjects().then(function (response) {
return vm.projects = response.data;
});
}
}
})();
<file_sep>using System.Threading.Tasks;
using Tasklist.DAL.SQL.Repositories;
using Tasklist.Domain.Contracts;
using Tasklist.Domain.Contracts.Repositories;
namespace Tasklist.DAL.SQL
{
public class UnitOfWork : IUnitOfWork
{
private readonly DataContext _dataContext;
public Task SaveChangesAsync()
{
return _dataContext.SaveChangesAsync();
}
public UnitOfWork(DataContext dataContext)
{
_dataContext = dataContext;
}
private IProjectRepository _projectRepository;
public IProjectRepository ProjectRepository
{
get
{
_projectRepository = _projectRepository ?? new ProjectRepository(_dataContext);
return _projectRepository;
}
}
private ITaskRepository _taskRepository;
public ITaskRepository TaskRepository
{
get
{
_taskRepository = _taskRepository ?? new TaskRepository(_dataContext);
return _taskRepository;
}
}
}
}
<file_sep>using Tasklist.DAL.SQL;
using Tasklist.Domain.Contracts;
namespace TaskList.Tests.DAL.SQL
{
internal static class UnitOfWorkFabric
{
public static IUnitOfWork CreateUnitOfWork()
{
return new UnitOfWork(new DataContext());
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(Tasklist.Web.Startup))]
namespace Tasklist.Web
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
UnityConfig.RegisterComponents(config);
WebApiConfig.Register(config);
app.UseWebApi(config);
}
}
}
<file_sep>using Tasklist.Domain.Contracts;
namespace Tasklist.BLL.Servcies
{
public class BaseService
{
protected readonly IUnitOfWork UnitOfWork;
public BaseService(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
}
}
<file_sep>using System.Collections.Generic;
using System.Threading.Tasks;
using Tasklist.Domain.Entities;
namespace Tasklist.Domain.Contracts.Repositories
{
public interface IProjectRepository : IBaseRepository<Project>
{
Task<List<Project>> GetProjectsByNameAsync(string nameSubstring);
}
}
<file_sep>using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using Tasklist.Domain.Entities;
namespace Tasklist.DAL.SQL.Maps
{
internal class TaskMap : EntityTypeConfiguration<Task>
{
public TaskMap()
{
HasKey(t => t.Id);
Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasRequired(t => t.Project).WithMany(p => p.Tasks);
Property(t => t.Name).HasMaxLength(255);
}
}
}
<file_sep>using System.Threading.Tasks;
namespace Tasklist.Domain.Contracts.Services
{
public interface ITaskService
{
Task AddTaskAsync(Entities.Task task);
Task DeleteTaskAsync(long id);
Task UpdateTaskAsync(Entities.Task task);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Optimization;
namespace Tasklist.Web
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/common").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/bootstrap.js",
"~/Scripts/bootstrap-confirmation.min.js",
"~/Scripts/respond.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
"~/Scripts/knockout-{version}.js",
"~/Scripts/knockout.validation.js"));
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/angular1").Include(
"~/Scripts/angular.js",
"~/Scripts/angular-animate.js",
"~/Scripts/angular-route.js",
"~/Scripts/angular-sanitize.js",
"~/Scripts/angular-ui/ui-bootstrap.js",
"~/Scripts/angular-bootstrap-confirm.js",
"~/Scripts/toastr.js",
"~/Scripts/spin.js",
"~/Angular1SPA/app.js",
"~/Angular1SPA/config.js",
"~/Angular1SPA/config.exceptionHandler.js",
"~/Angular1SPA/config.routes.js",
"~/Angular1SPA/common/common.js",
"~/Angular1SPA/common/logger.js",
"~/Angular1SPA/common/spinner.js",
"~/Angular1SPA/services/repository.js",
"~/Angular1SPA/layout/layoutController.js",
"~/Angular1SPA/projects/projectsController.js",
"~/Angular1SPA/projects/addProjectController.js",
"~/Angular1SPA/projects/editProjectController.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.min.css",
"~/Content/bootstrap.theme.min.css",
"~/Content/Site.css"));
bundles.Add(new StyleBundle("~/Content/angular1css").Include(
"~/Content/toastr.css"));
}
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
using Tasklist.Domain.Contracts.Services;
using Tasklist.Domain.Entities;
using Tasklist.Web.Mapping;
using Tasklist.Web.Models;
using WebGrease.Css.Extensions;
using Task = Tasklist.Domain.Entities.Task;
namespace Tasklist.Web.Controllers
{
public class MvcController : Controller
{
private readonly IProjectService _projectService;
public MvcController(IProjectService projectService)
{
_projectService = projectService;
}
public async Task<ActionResult> Index()
{
var projects = await _projectService.GetAllProjectsAsync();
var model = new ProjectListVM
{
Projects = projects.Select(ProjectMapper.Map).ToList()
};
return View(model);
}
public ActionResult Add()
{
return View(new ProjectModel());
}
[HttpPost]
public async Task<ActionResult> Add(ProjectModel project)
{
if (!ModelState.IsValid)
{
return View(project);
}
var newProject = new Project {
Name = project.Name,
Description = project.Description,
};
await _projectService.AddProjectAsync(newProject);
return RedirectToAction("Edit", new { id = newProject.Id });
}
public async Task<ActionResult> Edit(long id)
{
var project = await _projectService.GetProjectByIdAsync(id);
var model = ProjectMapper.Map(project);
return View(model);
}
[HttpPost]
public async Task<ActionResult> Edit(ProjectModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var project = await _projectService.GetProjectByIdAsync(model.Id);
if (project != null)
{
project.Name = model.Name;
project.Description = model.Description;
var tasks = project.Tasks?.ToList() ?? new List<Task>();
tasks.AddRange(model.Tasks.Select(TaskMapper.Map).ToList());
project.Tasks = tasks;
await _projectService.UpdateProjectAsync(project);
}
return RedirectToAction("Index");
}
[HttpDelete]
public async Task<ActionResult> Delete(long id)
{
await _projectService.DeleteProjectAsync(id);
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Threading.Tasks;
using Tasklist.Domain.Contracts.Repositories;
namespace Tasklist.DAL.SQL.Repositories
{
public class BaseRepository<TContext, TEntity> : IBaseRepository<TEntity>
where TEntity : class
where TContext : DbContext
{
protected TContext DbContext { get; }
protected DbSet<TEntity> DbSet { get; set; }
public BaseRepository(TContext dbContext)
{
if (dbContext == null)
{
throw new ArgumentNullException(nameof(dbContext));
}
DbContext = dbContext;
DbSet = DbContext.Set<TEntity>();
}
protected virtual IQueryable<TEntity> AllQuery()
{
return DbSet.AsQueryable();
}
public virtual Task<List<TEntity>> GetAllAsync()
{
return AllQuery().ToListAsync();
}
public virtual Task<TEntity> GetByIdAsync(object id)
{
return DbSet.FindAsync(id);
}
public virtual void Add(TEntity obj)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(obj);
if (dbEntityEntry.State != EntityState.Detached)
{
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(obj);
}
}
public virtual void Update(TEntity obj)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(obj);
if (dbEntityEntry.State == EntityState.Detached)
{
DbSet.Attach(obj);
}
dbEntityEntry.State = EntityState.Modified;
}
public async Task Delete(object id)
{
var obj = await GetByIdAsync(id);
if (obj != null)
{
Delete(obj);
}
}
public void Delete(TEntity entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Deleted)
{
dbEntityEntry.State = EntityState.Deleted;
}
else
{
DbSet.Attach(entity);
DbSet.Remove(entity);
}
}
}
}
<file_sep>namespace Tasklist.Web.Models
{
public class TaskModel
{
public string Name { get; set; }
public bool IsDone { get; set; }
}
}<file_sep>using System.Web.Http;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Tasklist.BLL.Servcies;
using Tasklist.DAL.SQL;
using Tasklist.Domain.Contracts;
using Tasklist.Domain.Contracts.Services;
using Unity.Mvc5;
namespace Tasklist.Web
{
public static class UnityConfig
{
public static void RegisterComponents(HttpConfiguration config)
{
var container = GetConfiguratedContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
config.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
}
private static UnityContainer GetConfiguratedContainer()
{
var container = new UnityContainer();
container.RegisterType<IUnitOfWork, UnitOfWork>();
container.RegisterType<IProjectService, ProjectService>();
return container;
}
}
}<file_sep>using Tasklist.Domain.Entities;
using Tasklist.Web.Models;
namespace Tasklist.Web.Mapping
{
public static class TaskMapper
{
public static TaskModel Map(Task task)
{
if (task == null)
{
return null;
}
return new TaskModel
{
Name = task.Name,
IsDone = task.IsDone,
};
}
public static Task Map(TaskModel task)
{
if (task == null)
{
return null;
}
return new Task
{
Name = task.Name,
IsDone = task.IsDone,
};
}
}
}<file_sep>using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using Tasklist.Domain.Entities;
namespace Tasklist.DAL.SQL.Maps
{
internal class ProjectMap: EntityTypeConfiguration<Project>
{
public ProjectMap()
{
HasKey(p => p.Id);
Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(p => p.Name).HasMaxLength(255);
}
}
}
<file_sep>(function () {
'use strict';
var controllerId = 'addProjectController';
angular
.module('app')
.controller(controllerId, addProjectController);
addProjectController.$inject = ['$location', 'common', 'repository'];
function addProjectController($location, common, repository) {
var vm = this;
var log = common.logger.getLogFn(controllerId);
vm.name = '';
vm.description = '';
vm.addProject = function () {
repository.addProject(vm.name, vm.description).then(function (response) {
$location.path('/editProject/' + response.data);
});
}
activate();
function activate() {
common.activateController([controllerId]);
}
}
})();
<file_sep>using System;
using System.Linq;
using NUnit.Framework;
using Tasklist.Domain.Entities;
namespace TaskList.Tests.DAL.SQL
{
[TestFixture]
public class ProjectRepositoryTests
{
[Test]
public async System.Threading.Tasks.Task AddProjectTest()
{
var uow = UnitOfWorkFabric.CreateUnitOfWork();
var project = new Project
{
Name = "<NAME>",
Description = "test desc",
DueDate = new DateTime(2000, 1, 1),
};
uow.ProjectRepository.Add(project);
await uow.SaveChangesAsync();
Assert.IsTrue(project.Id != 0);
var addedProject = await uow.ProjectRepository.GetByIdAsync(project.Id);
Assert.IsNotNull(addedProject);
Assert.AreEqual("Test name", addedProject.Name);
Assert.AreEqual("test desc", addedProject.Description);
Assert.AreEqual(new DateTime(2000, 1, 1), addedProject.DueDate);
}
[Test]
public async System.Threading.Tasks.Task AddProjectWithTaskTest()
{
var uow = UnitOfWorkFabric.CreateUnitOfWork();
var project = new Project
{
Name = "<NAME>",
Description = "test desc",
DueDate = new DateTime(2000, 1, 1),
};
uow.ProjectRepository.Add(project);
await uow.SaveChangesAsync();
Assert.IsTrue(project.Id != 0);
var task = new Task { IsDone = true, Name = "test task", ProjectId = project.Id };
uow.TaskRepository.Add(task);
await uow.SaveChangesAsync();
var addedProject = await uow.ProjectRepository.GetByIdAsync(project.Id);
Assert.IsNotNull(addedProject);
Assert.AreEqual(1, addedProject.Tasks.Count);
Assert.AreEqual("test task", addedProject.Tasks.Single().Name);
Assert.IsTrue(addedProject.Tasks.Single().IsDone);
}
[Test]
public async System.Threading.Tasks.Task EditProjectTest()
{
var uow = UnitOfWorkFabric.CreateUnitOfWork();
var project = new Project
{
Name = "<NAME>",
Description = "test desc",
DueDate = new DateTime(2000, 1, 1),
};
uow.ProjectRepository.Add(project);
await uow.SaveChangesAsync();
var addedProject = await uow.ProjectRepository.GetByIdAsync(project.Id);
Assert.IsNotNull(addedProject);
addedProject.Name = "edited name";
addedProject.Description = "edited desc";
addedProject.DueDate = new DateTime(2001, 1, 1);
uow.ProjectRepository.Update(addedProject);
await uow.SaveChangesAsync();
var editedProject = await uow.ProjectRepository.GetByIdAsync(project.Id);
Assert.IsNotNull(editedProject);
Assert.AreEqual("edited name", addedProject.Name);
Assert.AreEqual("edited desc", addedProject.Description);
Assert.AreEqual(new DateTime(2001, 1, 1), addedProject.DueDate);
}
[Test]
public async System.Threading.Tasks.Task DeleteProjectTest()
{
var uow = UnitOfWorkFabric.CreateUnitOfWork();
var project = new Project
{
Name = "<NAME>",
DueDate = new DateTime(1999, 9, 9),
};
uow.ProjectRepository.Add(project);
await uow.SaveChangesAsync();
var addedProject = await uow.ProjectRepository.GetByIdAsync(project.Id);
Assert.IsNotNull(addedProject);
uow.ProjectRepository.Delete(addedProject);
await uow.SaveChangesAsync();
var deletedProject = await uow.ProjectRepository.GetByIdAsync(project.Id);
Assert.IsNull(deletedProject);
}
[Test]
public async System.Threading.Tasks.Task FindBySubstringTest()
{
var uow = UnitOfWorkFabric.CreateUnitOfWork();
uow.ProjectRepository.Add(new Project
{
Name = "yellow blue",
DueDate = new DateTime(1999, 9, 9),
});
uow.ProjectRepository.Add(new Project
{
Name = "blue red",
DueDate = new DateTime(1999, 9, 19),
});
uow.ProjectRepository.Add(new Project
{
Name = "light green",
DueDate = new DateTime(1999, 9, 5),
});
await uow.SaveChangesAsync();
var projects = await uow.ProjectRepository.GetProjectsByNameAsync("blue");
Assert.IsNotNull(projects);
Assert.AreEqual(2, projects.Count);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using Tasklist.Domain.Contracts.Services;
using Tasklist.Domain.Entities;
using Tasklist.Web.Mapping;
using Tasklist.Web.Models;
namespace Tasklist.Web.Controllers
{
public class ProjectController : ApiController
{
private readonly IProjectService _projectService;
public ProjectController(IProjectService projectService)
{
_projectService = projectService;
}
public async Task<List<ProjectModel>> Get()
{
var projects = await _projectService.GetAllProjectsAsync();
return projects.Select(ProjectMapper.Map).ToList();
}
public async Task<ProjectModel> Get(long id)
{
var project = await _projectService.GetProjectByIdAsync(id);
return ProjectMapper.Map(project);
}
public async Task<long> Post(ProjectModel project)
{
var newProject = new Project
{
Name = project.Name,
Description = project.Description,
};
await _projectService.AddProjectAsync(newProject);
return newProject.Id;
}
public async System.Threading.Tasks.Task Put(ProjectModel project)
{
var existingProject = await _projectService.GetProjectByIdAsync(project.Id);
if (existingProject != null)
{
existingProject.Name = project.Name;
existingProject.Description = project.Description;
var tasks = existingProject.Tasks?.ToList() ?? new List<Domain.Entities.Task>();
tasks.AddRange(project.Tasks.Select(TaskMapper.Map).ToList());
existingProject.Tasks = tasks;
await _projectService.UpdateProjectAsync(existingProject);
}
}
public async System.Threading.Tasks.Task Delete(long id)
{
await _projectService.DeleteProjectAsync(id);
}
}
}
<file_sep>namespace Tasklist.Domain.Contracts.Repositories
{
public interface ITaskRepository: IBaseRepository<Entities.Task>
{
}
}
<file_sep># sample-tasklist
A simple task list app
Currently the same functionality is implemented with
* ASP.NET MVC + jQuery and knockout.js (multi page app)
* ASP.NET Web Api + Angular1 (single page app)
Backend technologies used:
* Microsoft SQL Server
* Entity Framework Code first (with migrations)
* Unity as IoC container
Integration tests:
* NUnit
<file_sep>using System.Threading.Tasks;
using Tasklist.Domain.Contracts.Repositories;
namespace Tasklist.Domain.Contracts
{
public interface IUnitOfWork
{
Task SaveChangesAsync();
IProjectRepository ProjectRepository { get; }
ITaskRepository TaskRepository { get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Tasklist.Domain.Contracts;
using Tasklist.Domain.Contracts.Services;
using Tasklist.Domain.Entities;
using Task = System.Threading.Tasks.Task;
namespace Tasklist.BLL.Servcies
{
public class ProjectService: BaseService, IProjectService
{
public ProjectService(IUnitOfWork unitOfWork) : base(unitOfWork)
{
}
public Task<Project> GetProjectByIdAsync(long id)
{
return UnitOfWork.ProjectRepository.GetByIdAsync(id);
}
public Task<List<Project>> GetAllProjectsAsync()
{
return UnitOfWork.ProjectRepository.GetAllAsync();
}
public Task AddProjectAsync(Project project)
{
if (project.DueDate < DateTime.Today)
{
project.DueDate = DateTime.Today.AddDays(7);
}
UnitOfWork.ProjectRepository.Add(project);
return UnitOfWork.SaveChangesAsync();
}
public async Task DeleteProjectAsync(long id)
{
var project = await GetProjectByIdAsync(id);
foreach (var task in project.Tasks.ToList())
{
UnitOfWork.TaskRepository.Delete(task);
}
UnitOfWork.ProjectRepository.Delete(project);
await UnitOfWork.SaveChangesAsync();
}
public Task UpdateProjectAsync(Project project)
{
foreach (var task in project.Tasks.Where(t => t.Id != 0).ToList())
{
project.Tasks.Remove(task);
UnitOfWork.TaskRepository.Delete(task);
}
foreach (var task in project.Tasks.Where(t => !string.IsNullOrWhiteSpace(t.Name)))
{
task.ProjectId = project.Id;
UnitOfWork.TaskRepository.Add(task);
}
UnitOfWork.ProjectRepository.Update(project);
return UnitOfWork.SaveChangesAsync();
}
}
}
<file_sep>using System.Collections.Generic;
namespace Tasklist.Web.Models
{
public class ProjectListVM
{
public List<ProjectModel> Projects { get; set; }
}
}<file_sep>using System;
using System.Data.Entity;
using NUnit.Framework;
using Tasklist.DAL.SQL;
namespace TaskList.Tests.DAL.SQL //must be in root namespace for SetUpFixture to be called by NUnit
{
[SetUpFixture]
public class TestRunner
{
[SetUp]
public static void SetUp()
{
AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory());
Database.SetInitializer(new DropCreateDatabaseAlways<DataContext>());
}
}
}
<file_sep>namespace Tasklist.Domain.Entities
{
public class Task
{
public long Id { get; set; }
public long ProjectId { get; set; }
public string Name { get; set; }
public bool IsDone { get; set; }
public virtual Project Project { get; set; }
}
}
|
79de3552a11aa0fea67b8fcb2c5222a9088a1c15
|
[
"JavaScript",
"C#",
"Markdown"
] | 32 |
C#
|
andreydil/sample-tasklist
|
3867bf8baa3447c81e234751e21cfc39b30c2b5c
|
fb1ec85d2e60bb6da1e4f35a98cd58e99534eafe
|
refs/heads/master
|
<file_sep>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.IO;
namespace Test
{
public partial class Form1 : Form
{
DAG DP = new DAG();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
string fileName = ofd.FileName;
textBox1.Text = String.Empty;
Result_box.Text = String.Empty;
try
{
{
textBox1.Text = File.ReadAllText(fileName);
DP.Process(fileName);
}
}
catch
{
MessageBox.Show("The file could not be read");
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void BFS_button_Click(object sender, EventArgs e)
{
Result_box.Text = String.Empty;
if (DP.N == 0)
{
Result_box.Text = "Empty Matrix";
}
else
{
DP.sortBFS(DP.N);
int semester = 0;
foreach (List<string> list in DP.resultBFS1)
{
semester++;
Result_box.AppendText("Semester " + semester + "\t: ");
foreach (string item in list)
{
Result_box.AppendText(item + " ");
}
Result_box.AppendText(Environment.NewLine);
}
}
}
private void DFS_button_Click(object sender, EventArgs e)
{
Result_box.Text = String.Empty;
DP.GetDFS();
for (int j = 0; j < DP.N; j++)
{
if (DP.IsZeroCol(j))
{
DP.arrFirst.Add(j);
}
}
int a = 0;
while (a < DP.arrFirst.Count)
{
DP.ProcessDFS(DP.arrFirst[a]);
int sem = 0;
for (int i = 0; i < DP.N; i++)
{
sem++;
Result_box.AppendText("Semester " + sem + "\t: ");
Result_box.AppendText(DP.Value[DP.arrDFS[i]] + " ");
Result_box.AppendText(Environment.NewLine);
}
DP.allResult.Add(DP.arrDFS);
DP.arrDFS.Clear();
a++;
}
}
private void Result_box_TextChanged(object sender, EventArgs e)
{
}
}
class DAG
{
public int N { get; private set; }
public string[] Value { get; private set; }
public List<List<string>> resultBFS1 = new List<List<string>>();
public int[,] Adjmat { get; private set; }
private int adj, end; //idx = row; adj = col
private int counttime;
public int[,] Adjmatcopy;
public string[] Valuecopy;
public bool[] ValueVisit;
public List<int> arrFirst;
public List<List<int>> allResult;
public List<int> arrP;
public List<int> arrQ;
public List<int> arrDFS;
public List<int> tempQ;
public Stack<int> st;
internal void IntoMatrix(string[] lines)
{
Adjmat = new int[N, N];
Value = new string[N];
string[] Deliminators = { ", ", "." };
int i = 0;
foreach (string line in lines)
{
string[] Adjs = line.Split(Deliminators, StringSplitOptions.RemoveEmptyEntries);
foreach (string adj in Adjs)
{
int idx = Array.IndexOf(Value, adj);
if (idx == -1)
{
Value[i] = adj;
idx = i;
i++;
}
if (adj != Adjs[0])
{
Adjmat[idx, Array.IndexOf(Value, Adjs[0])] = 1; //Adjs[0] ditunjuk idx
}
}
}
}
/* --------------------------------------- START OF BFS PROCEDURES ---------------------------------------- */
internal void delArrElmt(int idx)
{
// Set nama mata kuliah menjadi "Cx"
Value[idx] = "Cx";
}
internal void delPreRequisite(int idx, int N)
{
// Menghapus prasyarat mata kuliah karena telah diambil
for (int i = 0; i < N; i++)
{
Adjmat[idx, i] = 0;
}
}
public List<int> noPreRequisite(int N)
{
// Mengembalikan list berisi indeks elemen array yang prasyaratnya sudah terpenuhi
List<int> temp = new List<int>();
int i = 0;
int j, countZero;
while (i < N)
{
if (Value[i] != "Cx")
{
j = 0;
countZero = 0;
while (j < N)
{
if (Adjmat[j, i] == 0)
countZero++;
else
break;
j++;
}
if (countZero == N)
{
temp.Add(i);
}
}
i++;
}
return temp;
}
internal int nbNotUsed(int N)
{
// Mengembalikan jumlah mata kuliah yang belum diambil
int count = 0;
for (int i = 0; i < N; i++)
{
if (Value[i] != "Cx")
count++;
}
return count;
}
internal void sortBFS(int N)
{
// Fungsi implementasi BFS (Pada matriks mata kuliah)
List<int> temp = new List<int>();
List<string> str = new List<string>();
if (nbNotUsed(N) > 1)
{
temp = noPreRequisite(N);
foreach (int item in temp)
{
str.Add(Value[item]);
delArrElmt(item);
delPreRequisite(item, N);
}
resultBFS1.Add(str);
sortBFS(N);
}
else if (nbNotUsed(N) == 1)
{
for (int i = 0; i < N; i++)
{
if (Value[i] != "Cx")
{
str.Add(Value[i]);
delArrElmt(i);
delPreRequisite(i, N);
break;
}
}
resultBFS1.Add(str);
}
}
/* --------------------------------------- END OF BFS PROCEDURES ---------------------------------------- */
/* --------------------------------------- START OF DFS PROCEDURES ---------------------------------------- */
internal void GetDFS()
{
counttime = 0;
end = 0;
Adjmatcopy = new int[N, N];
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
Adjmatcopy[i, j] = Adjmat[i, j];
}
}
Valuecopy = new string[N];
for (int i = 0; i < N; i++)
{
Valuecopy[i] = Value[i];
}
ValueVisit = new bool[N];
for (int i = 0; i < N; i++)
{
ValueVisit[i] = false;
}
arrP = new List<int>();
for (int i = 0; i < N; i++)
{
arrP.Add(0);
}
arrQ = new List<int>();
for (int i = 0; i < N; i++)
{
arrQ.Add(0);
}
arrDFS = new List<int>();
arrFirst = new List<int>();
allResult = new List<List<int>>();
tempQ = new List<int>();
st = new Stack<int>();
}
internal bool IsZeroCol(int col)
{
bool zerocol = false;
int count = 0;
int i = 0;
while ((i < N) && (zerocol == false))
{
if (Adjmat[i, col] == 0)
{
count++;
}
i++;
if (count == N)
{
zerocol = true;
}
}
return zerocol;
}
internal int FindAdj(int row)
{
bool found = false;
int col = 999;
int j = 0;
while ((j < N) && (found == false))
{
if (Adjmatcopy[row, j] == 1)
{
found = true;
col = j;
}
else
{
j++;
}
}
return col;
}
internal int FindPointed(int col)
{
bool found = false;
int row = 999;
int i = 0;
while ((i < N) && (found == false))
{
if (Adjmatcopy[i, col] == 1)
{
found = true;
row = i;
}
else
{
i++;
}
}
return row;
}
internal bool isVisited(int idx)
{
if (ValueVisit[idx] == true)
{
return true;
}
else
{
return false;
}
}
internal void MakeZero(int row, int col)
{ //MakeZero(idx, findadj)
Adjmatcopy[row, col] = 0;
}
internal void PushAndSetStart(int idx)
{
if (!isVisited(idx))
{
st.Push(idx);
counttime++;
arrP.RemoveAt(idx);
arrP.Insert(idx, counttime);
ValueVisit[idx] = true;
}
}
internal void PopAndSetEnd()
{
string pop = st.Pop().ToString();
end = Convert.ToInt32(pop);
counttime++;
arrQ.RemoveAt(end);
arrQ.Insert(end, counttime);
}
internal int FindIdx(int x, List<int> Arr)
{
int i = 0;
int res = 999;
while ((i < Arr.Count) && (res == 999))
{
if (Arr[i] == x)
{
res = i;
}
else
{
i++;
}
}
return res;
}
internal void ProcessDFS(int idx)
{
//int top;
PushAndSetStart(idx);
while (st.Count != 0)
{
adj = FindAdj(idx);
if (adj != 999)
{
if (!isVisited(adj))
{
MakeZero(idx, adj);
PushAndSetStart(adj);
//arrDFS.Add(adj);
idx = adj;
}
else
{
MakeZero(idx, adj);
}
}
else
{
if (FindAdj(Convert.ToInt32(st.Peek().ToString())) != 999)
{
idx = Convert.ToInt32(st.Peek().ToString());
}
else
{
idx = Convert.ToInt32(st.Peek().ToString());
PopAndSetEnd();
}
}
}
for (int i = 0; i < arrQ.Count; i++)
{
tempQ.Add(arrQ[i]);
}
tempQ.Sort();
tempQ.Reverse();
for (int i = 0; i < N; i++)
{
int a = FindIdx(tempQ[i], arrQ);
arrDFS.Add(a);
}
}
/* --------------------------------------- END OF DFS PROCEDURES ---------------------------------------- */
internal void Process(string fileName)
{
string[] lines = File.ReadAllLines(fileName);
N = lines.Length;
IntoMatrix(lines);
}
}
}
|
69f30bb8fd412f9d3bdf64b78b0a3ce6963d14dd
|
[
"C#"
] | 1 |
C#
|
NiraRamadhani/BFS_DFS-AlgorithmStrategy
|
3979f95630e01753b16a45e0ccf856d08c1d87d9
|
4d449ab76db5a2ce0f5d3fe97e12ae5d38afa095
|
refs/heads/main
|
<repo_name>davidkern/batmonbrd<file_sep>/main.py
# import board
# import busio
# import digitalio
# import time
# import struct
# i2c = busio.I2C(board.SCL, board.SDA, frequency=100000)
# i2c.try_lock()
# def reg_read_int16(dev_addr, reg_addr):
# """Reads register `reg_addr` on device `dev_addr`"""
# result = bytearray(2)
# i2c.writeto_then_readfrom(
# dev_addr,
# bytes([reg_addr]),
# result)
# return struct.unpack(">h", result)[0]
# def reg_write(dev_addr, reg_addr, value):
# """Write `value` to register `reg_addr` on device `dev_addr`"""
# buf = bytearray([reg_addr, value // 256, value % 256])
# i2c.writeto(dev_addr, buf)
# def led_set(dev_addr, value):
# """Toggle LED by manipulating bus-undervoltage alert bit"""
# if value:
# reg_write(dev_addr, 0x06, 0x0000)
# else:
# reg_write(dev_addr, 0x06, 0x1000)
# def shunt_read(dev_addr):
# """Shunt reading in amperes, positive charge, negative discharge"""
# # LSB is 2.5uV
# # Shunts are 75mV per 100A
# return - reg_read_int16(dev_addr, 0x01) * 3.33e-3
# def bus_read(dev_addr):
# """Bus reading in volts"""
# # LSB is 1.25mV
# return reg_read_int16(dev_addr, 0x02) * 1.25e-3
# led = False
# # Accumulated energy in watt-hours (starts counting from charged)
# alpha_accum = 1280
# beta_accum = 1280
# gamma_accum = 1280
# # set alert limit to max possible bus-voltage so toggling
# # the bus-voltage undervoltage alert bit toggles the LED
# try:
# reg_write(0x40, 0x07, 0x7fff)
# except:
# pass
# try:
# reg_write(0x41, 0x07, 0x7fff)
# except:
# pass
# try:
# reg_write(0x42, 0x07, 0x7fff)
# except:
# pass
# last_time = time.monotonic()
# # below is sloppy math for a sanity check - will refactor to properly average and integrate
# while True:
# current_time = time.monotonic()
# delta_time = current_time - last_time
# try:
# alpha_shunt = shunt_read(0x40)
# alpha_bus = bus_read(0x40)
# except:
# alpha_shunt = None
# alpha_bus = None
# if alpha_shunt is not None and alpha_bus is not None:
# alpha_accum += alpha_shunt * alpha_bus * delta_time / 3600.0
# try:
# beta_shunt = shunt_read(0x41)
# beta_bus = bus_read(0x41)
# except:
# beta_shunt = None
# beta_bus = None
# if beta_shunt is not None and beta_bus is not None:
# beta_accum += beta_shunt * beta_bus * delta_time / 3600.0
# try:
# gamma_shunt = shunt_read(0x42)
# gamma_bus = bus_read(0x42)
# except:
# gamma_shunt = None
# gamma_bus = None
# if gamma_shunt is not None and gamma_bus is not None:
# gamma_accum += gamma_shunt * gamma_bus * delta_time / 3600.0
# last_time = current_time
# led = not led
# try:
# led_set(0x40, led)
# except:
# pass
# try:
# led_set(0x41, led)
# except:
# pass
# try:
# led_set(0x42, led)
# except:
# pass
# print("{:.2f},{:.2f},{:.2f},{:.2f},{:.2f},{:.2f},{:.2f},{:.2f},{:.2f},{:.2f}".format(
# alpha_bus, alpha_shunt, alpha_accum,
# beta_bus, beta_shunt, beta_accum,
# gamma_bus, gamma_shunt, gamma_accum,
# alpha_accum + beta_accum + gamma_accum))
# time.sleep(0.1)
import time
OUTPUT_PERIOD = 1.0
def main():
from i2cbus import I2CBus
from ina226 import INA226Client
i2c = I2CBus()
devices = [
INA226Client(i2c, 0x40),
INA226Client(i2c, 0x41),
INA226Client(i2c, 0x42)
]
last_output_time = time.monotonic()
while True:
measurements = [device.measurement().to_json() for device in devices]
output_time = time.monotonic()
if output_time < last_output_time or last_output_time + OUTPUT_PERIOD < output_time:
last_output_time = output_time
print(f"[{','.join(measurements)}]")
if __name__ == "__main__":
main()
<file_sep>/README.md
# batmonbrd - Battery Monitor Board
This code file is for a Serpente (https://www.tindie.com/products/arturo182/serpente-a-tiny-circuitpython-prototyping-board/) CircuitPython board
which monitors INA226 (https://www.ti.com/product/INA226) for the LiFePO4 batteries
in the Hab.
Bus and shunt voltages are read continuously for each of the three batteries.
An accumulated bus * shunt value is kept for each battery, which when multiplied
by a constant gives the total energy stored.
The alert pin of the INA226 is used as a GPIO to flash an LED. This will be
used to indicate state of charge of the battery.
This was hacked together to be "good enough". Future work will clean this up to
be consistent with other Hab devices.
# License
Either MIT or Apache license, at your option.
# Requirements
1. The INA226 chips are read over an I2C bus with a 100kHz clock (de-rated from 400kHz)
to account for the additional bus capacitance due to the longer leads.
2. Chips are used in their boot configuration, which are continuous reads at approximately
1ms each with no on-chip scaling.
3. An LED on each sensor is connected to the ALERT pin. The LED can be enabled by setting
bit 13, Bus Voltage Over-Voltage, in the Mask/Enable register.
4. State-of-charge (SOC) for each battery is stored in Watt-hours, at device reset SOC is
set to fully-charged, which is 1280 Whr.
5. The LED is flashed at 1-10Hz, in proportion to the corresponding battery's charge. At
full charge, the LED flashes at 10Hz. At 10% state of charge or lower, the LED flashes
at 1Hz.
6. Once per second a JSON-encoded list of battery state is sent to the host. The battery
state is encoded as:
```
{
"voltage": 13.50
"current": 1.23
"soc": 1280.00
}
```
7. Values are reported to the nearest 1/100th.
8. The host may send a JSON-encoded list, one element per battery, to set the state of
charge.
9. If the battery voltage reaches 14.15 volts, then SOC is reset to fully charged and
remains fully charged until battery voltage drops below 13.45 volts.
<file_sep>/ina226.py
import time
SOC_MAX = 1280 # Fully charged is 1280 Whr
LED_FREQUENCY_MAX = 10 # Frequency in Hz
class Measurement:
"""A moment-in-time measurement from the INA226"""
def __init__(self, timestamp=0, voltage=0, current=0, soc=SOC_MAX):
"""
Creates a measurement record.
"""
self.timestamp = timestamp
self.voltage = voltage
self.current = current
self.soc = soc
def to_json(self):
"""
Convert to json using string interpolation to work-around lack
of (u)json module on serpente's CircuitPython
"""
return f'{{"ts": {self.timestamp:f}, "voltage": {self.voltage:.3f}, "current": {self.current:.3f}, "soc": {self.soc:.3f}}}'
class INA226Client:
"""INA226 device on the I2C bus"""
def __init__(self, i2c, address):
"""
Initializes INA226 device object.
Args:
i2c: The i2c bus object
address: The address of the INA226 on the bus
"""
self.i2c = i2c
self.address = address
self.led_frequency = 0
self.last_measurement = Measurement()
def read_shunt(self):
"""Shunt reading in amperes, positive charge, negative discharge"""
# LSB is 2.5uV
# Shunts are 75mV per 100A
return - self.i2c.reg_read_int16(self.address, 1) * 3.33e-3
def read_bus(self):
"""Bus reading in volts"""
# LSB is 1.25mV
return self.i2c.reg_read_int16(self.address, 2) * 1.25e-3
def measurement(self, timestamp=None):
"""Take a measurement"""
if timestamp is None:
timestamp = time.monotonic()
measurement = Measurement(
timestamp,
self.read_bus(),
self.read_shunt())
# calculate new state of charge
if self.last_measurement.timestamp != 0:
delta = timestamp - self.last_measurement.timestamp
if delta >= 0:
# integrate using mean of the interval endpoints
mean_voltage = (self.last_measurement.voltage + measurement.voltage) / 2.0
mean_current = (self.last_measurement.current + measurement.current) / 2.0
mean_power = mean_voltage * mean_current
measurement.soc = self.last_measurement.soc + mean_power * delta / 3600.0
else:
# wrapped around, use last soc calculation
measurement.soc = self.last_measurement.soc
self.last_measurement = measurement
return measurement
@property
def soc(self):
return self.last_measurement.soc
@property
def voltage(self):
return self.last_measurement.voltage
@property
def current(self):
return self.last_measurement.current
<file_sep>/test.py
import unittest
import main
import collections
import ina226
class FakeINA226:
"""Implements a faked INA226 for testing"""
REG_CONFIGURATION = 0
REG_SHUNT_VOLTAGE = 1
REG_BUS_VOLTAGE = 2
REG_POWER = 3
REG_CURRENT = 4
REG_CALIBRATION = 5
REG_MASK_ENABLE = 6
REG_ALERT_LIMIT = 7
REG_MANUFACTURER_ID = 8
REG_DIE_ID = 9
def __init__(self):
"""Initial conditions from datasheet"""
self.registers = [
0x4127, # Configuration
0x0000, # Shunt Voltage
0x0000, # Bus Voltage
0x0000, # Power
0x0000, # Current
0x0000, # Calibration
0x0000, # Mask/Enable
0x0000, # Alert Limit
0x5449, # Manufacturer ID
0x2260 # Die ID
]
def read_int16(self, address):
return self.registers[address]
def write_int16(self, address, value):
self.registers[address] = value
class FakeI2CBus:
"""Implements a faked I2C bus for testing"""
def __init__(self):
self.devices = {}
def attach_device(self, address, device):
"""Attaches a faked device to the faked bus"""
self.devices[address] = device
def reg_read_int16(self, dev_addr, reg_addr):
"""Reads register `reg_addr` on device `dev_addr`"""
return self.devices[dev_addr].read_int16(reg_addr)
def reg_write_int16(self, dev_addr, reg_addr, value):
"""Write `value` to register `reg_addr` on device `dev_addr`"""
return self.devices[dev_addr].write_int16(reg_addr, value)
class TestINA226(unittest.TestCase):
def setUp(self):
self.i2c = FakeI2CBus()
self.i2c.attach_device(0x40, FakeINA226())
self.dut = ina226.INA226Client(self.i2c, 0x40)
def test_initial_conditions(self):
"""Test that state of charge is initially fully charged"""
self.assertEqual(1280, self.dut.soc)
def test_first_measurement_skips_integration(self):
"""Tests that first measurement does not integrate"""
# set expectations
# -1.23A shunt current and 12.8V bus voltage
self.i2c.reg_write_int16(0x40, FakeINA226.REG_SHUNT_VOLTAGE, 369)
self.i2c.reg_write_int16(0x40, FakeINA226.REG_BUS_VOLTAGE, 10240)
measurement = self.dut.measurement(1000)
self.assertEqual(1000, measurement.timestamp)
self.assertTrue(abs(-1.23 - measurement.current) <= 0.01)
self.assertEqual(12.8, measurement.voltage)
self.assertEqual(1280, measurement.soc)
if __name__ == "__main__":
unittest.main()
<file_sep>/i2cbus.py
import busio
import board
import struct
class I2CBus:
"""Implement I2C read/write functionality"""
def __init__(self):
"""Initialize I2C device"""
self.i2c = busio.I2C(board.SCL, board.SDA, frequency=100000)
self.i2c.try_lock()
def reg_read_int16(self, dev_addr, reg_addr):
"""Reads register `reg_addr` on device `dev_addr`"""
result = bytearray(2)
self.i2c.writeto_then_readfrom(
dev_addr,
bytes([reg_addr]),
result)
return struct.unpack(">h", result)[0]
def reg_write_int16(self, dev_addr, reg_addr, value):
"""Write `value` to register `reg_addr` on device `dev_addr`"""
buf = bytearray([reg_addr, value // 256, value % 256])
self.i2c.writeto(dev_addr, buf)
|
64ad79c19cb7e5cf1b17dbfc792479d295a95fe7
|
[
"Markdown",
"Python"
] | 5 |
Python
|
davidkern/batmonbrd
|
bf775e0a807f4fc176d5f8c6f9e26047d01393fd
|
6a4d0b4a09ccd3ccfc4bb62a0747b015273f58a6
|
refs/heads/master
|
<file_sep>require_relative 'node'
class PSD::Node
# Represents the root node of a Photoshop document
class Root < PSD::Node
include PSD::HasChildren
include PSD::Node::ParseLayers
attr_accessor :children
# Stores a reference to the parsed PSD and builds the
# tree hierarchy.
def initialize(psd)
@psd = psd
build_hierarchy
end
# Recursively exports the hierarchy to a Hash
def to_hash
{
children: children.map(&:to_hash),
document: {
width: document_width,
height: document_height
}
}
end
# Returns the width and height of the entire PSD document.
def document_dimensions
[document_width, document_height]
end
# The width of the full PSD document as defined in the header.
def document_width
@psd.header.width.to_i
end
alias_method :width, :document_width
# The height of the full PSD document as defined in the header.
def document_height
@psd.header.height.to_i
end
alias_method :height, :document_height
# The root node has no name since it's not an actual layer or group.
def name
nil
end
# The depth of the root node is always 0.
def depth
0
end
[:top, :right, :bottom, :left].each do |meth|
define_method(meth) { 0 }
end
def opacity; 255; end
def fill_opacity; 255; end
def psd; @psd; end
private
def build_hierarchy
@children = []
result = { layers: [] }
parseStack = []
# First we build the hierarchy
@psd.layers.each do |layer|
if layer.folder?
parseStack << result
result = { name: layer.name, layer: layer, layers: [] }
elsif layer.folder_end?
temp = result
result = parseStack.pop
result[:layers] << temp
else
result[:layers] << layer
end
end
parse_layers(result[:layers])
end
end
end<file_sep>require_relative 'nodes/ancestry'
require_relative 'nodes/search'
# Internal structure to help us build trees of a Photoshop documents.
# A lot of method names borrowed from the Ruby ancestry gem.
class PSD
class Node
include Ancestry
include Search
include BuildPreview
# Default properties that all nodes contain
PROPERTIES = [:name, :left, :right, :top, :bottom, :height, :width]
attr_accessor :parent, :children, :layer, :force_visible
def initialize(layers=[])
@children = []
layers.each do |layer|
layer.parent = self
@children << layer
end
@force_visible = nil
end
def hidden?
!visible?
end
def visible?
force_visible.nil? ? @layer.visible? : force_visible
end
def psd
parent.psd
end
def layer?
is_a?(PSD::Node::Layer)
end
def group?
is_a?(PSD::Node::Group) || is_a?(PSD::Node::Root)
end
def debug_name
root? ? ":root:" : name
end
def to_hash
hash = {
type: nil,
visible: visible?,
opacity: @layer.opacity / 255.0,
blending_mode: @layer.blending_mode
}
PROPERTIES.each do |p|
hash[p] = self.send(p)
end
hash
end
def document_dimensions
@parent.document_dimensions
end
end
end<file_sep>require 'benchmark'
require 'pp'
require 'psd'
file = ARGV[0] || 'examples/example.psd'
results = Benchmark.measure "Image exporting" do
psd = PSD.new(file, parse_layer_images: true)
psd.parse!
psd.layer_comps.each do |comp|
puts "Saving #{comp[:name]} - #{comp[:id]}"
psd.tree
.filter_by_comp(comp[:id])
.save_as_png("./#{comp[:name]}.png")
end
end
puts Benchmark::CAPTION
puts results.to_s<file_sep>class PSD
class Node
module Search
# Searches the tree structure for a node at the given path. The path is
# defined by the layer/folder names. Because the PSD format does not
# require unique layer/folder names, we always return an array of all
# found nodes.
def children_at_path(path, opts={})
path = path.split('/').delete_if { |p| p == "" } unless path.is_a?(Array)
query = path.shift
matches = children.select do |c|
if opts[:case_sensitive]
c.name == query
else
c.name.downcase == query.downcase
end
end
if path.length == 0
return matches
else
return matches.map { |m| m.children_at_path(path, opts) }.flatten
end
end
alias :children_with_path :children_at_path
# Given a layer comp ID, name, or :last for last document state, create a new
# tree with layer/group visibility altered based on the layer comp.
def filter_by_comp(id)
if id.is_a?(String)
comp = psd.layer_comps.select { |c| c[:name] == id }.first
raise "Layer comp not found" if comp.nil?
id = comp[:id]
elsif id == :last
id = 0
end
root = PSD::Node::Root.new(psd)
filter_for_comp!(id, root)
return root
end
private
def filter_for_comp!(id, node)
# Force layers to be visible if they are enabled for the comp
node.children.each do |c|
enabled = c.visible?
c
.metadata
.data[:layer_comp]['layerSettings'].each do |l|
enabled = l['enab'] if l.has_key?('enab')
break if l['compList'].include?(id)
end
c.force_visible = enabled
filter_for_comp!(id, c) if c.group?
end
end
end
end
end<file_sep>require_relative 'node'
class PSD::Node
# Represents a group, or folder, in the PSD document. It can have
# zero or more children nodes.
class Group < PSD::Node
include PSD::HasChildren
include PSD::Node::ParseLayers
include PSD::Node::LockToOrigin
attr_reader :name, :top, :left, :bottom, :right
# Parses the descendant tree structure and figures out the bounds
# of the layers within this folder.
def initialize(folder)
@name = folder[:name]
@layer = folder[:layer]
parse_layers(folder[:layers])
get_dimensions
end
# Calculated height of this folder.
def rows
@bottom - @top
end
alias :height :rows
# Calculated width of this folder.
def cols
@right - @left
end
alias :width :cols
# Attempt to translate this folder and all of the descendants.
def translate(x=0, y=0)
@children.each{ |c| c.translate(x,y) }
end
# Attempt to hide all children of this layer.
def hide!
@children.each{ |c| c.hide! }
end
# Attempt to show all children of this layer.
def show!
@children.each{ |c| c.show! }
end
def passthru_blending?
blending_mode == 'passthru'
end
def empty?
@children.each do |child|
return false unless child.empty?
end
return true
end
# Export this layer and it's children to a hash recursively.
def to_hash
super.merge({
type: :group,
visible: visible?,
children: children.map(&:to_hash)
})
end
# If the method is missing, we blindly send it to the layer.
# The layer handles the case in which the method doesn't exist.
def method_missing(method, *args, &block)
@layer.send(method, *args, &block)
end
private
def get_dimensions
children = @children.reject(&:empty?)
@left = children.map(&:left).min || 0
@top = children.map(&:top).min || 0
@bottom = children.map(&:bottom).max || 0
@right = children.map(&:right).max || 0
end
end
end
<file_sep>require_relative 'node'
class PSD::Node
class Layer < PSD::Node
include PSD::Node::LockToOrigin
attr_reader :layer
# Stores a reference to the PSD::Layer
def initialize(layer)
super([])
@layer = layer
layer.node = self
end
# Delegates some methods to the PSD::Layer
(PROPERTIES + [:text, :ref_x, :ref_y]).each do |meth|
define_method meth do
@layer.send(meth)
end
define_method "#{meth}=" do |val|
@layer.send("#{meth}=", val)
end
end
# Attempt to translate the layer.
def translate(x=0, y=0)
@layer.translate x, y
end
# Attempt to scale the path components of the layer.
def scale_path_components(xr, yr)
@layer.scale_path_components(xr, yr)
end
# Tries to hide the layer by moving it way off canvas.
def hide!
# TODO actually mess with the blend modes instead of
# just putting things way off canvas
return if @hidden_by_kelly
translate(100000, 10000)
@hidden_by_kelly = true
end
# Tries to re-show the canvas by moving it back to it's original position.
def show!
if @hidden_by_kelly
translate(-100000, -10000)
@hidden_by_kelly = false
end
end
def empty?
width == 0 || height == 0
end
# Exports this layer to a Hash.
def to_hash
super.merge({
type: :layer,
text: @layer.text,
ref_x: @layer.reference_point.x,
ref_y: @layer.reference_point.y,
mask: @layer.mask.to_hash,
image: {
width: @layer.image.width,
height: @layer.image.height,
channels: @layer.channels_info
}
})
end
# If the method is missing, we blindly send it to the layer.
# The layer handles the case in which the method doesn't exist.
def method_missing(method, *args, &block)
@layer.send(method, *args, &block)
end
end
end
|
877862cc44c9def70202bee2b9606ff95171bf08
|
[
"Ruby"
] | 6 |
Ruby
|
pinnamur/psd.rb
|
3a95f2a6de1e5e396f6cd678eb2d4d7929797fea
|
edcc7c8d2fe9963cb3fec0a6be96c0436d8ba777
|
refs/heads/master
|
<repo_name>farrelreginaldo/captcha<file_sep>/README.md
# captcha
Anggota :
1. <NAME>. (13)
2. <NAME>. (23)
3. <NAME> (33)
<file_sep>/captcha/gambarcaptcha.php
<?php
//ini kode untuk membaut gambar
session_start();
//ini untuk membuat session dulu di PHP, harus diletakkan diatas.
header("content-type: image/png");
$_SESSION["nomorCaptcha"]="";
//mementukan ukuran width/lebar, dan tinggi/height
$gbr = imagecreate(180, 40);
//menentukan warna background.
imagecolorallocate($gbr, 167, 218, 239);
$grey = imagecolorallocate($gbr, 128, 128, 128);
$black = imagecolorallocate($gbr, 0 ,0, 0);
// mendefinisikan font yang akan digunakan
//untuk menuliskan angka acak dan menempelkannya ke gambar
$font = 'arial.TTF';
for($i=0;$i<=5;$i++) {
//menentukan jumlah karakter yang akan ditampilkan.
//kalau mau mengerti, tinggal ganti variabel $i
//generate nomor acak dulu
$nomor=rand(0, 9);
$_SESSION["nomorCaptcha"].=$nomor;
$sudut=rand(-25, 25);
imagettftext($gbr, 20, $sudut, 8+15*$i, 25, $black, $font, $nomor);
//menambahkan shadow ke
imagettftext($gbr, 20, $sudut, 9+15*$i, 26, $grey, $font, $nomor);
}
//untuk create gambar
imagepng($gbr);
imagedestroy($gbr);
?><file_sep>/captcha/cekhasil.php
<head>
<title> Penilaian captcha </title>
</head>
<body>
<p align="center"> Hasil Login <br/>
<?php
session_start();
if($_SESSION["nomorCaptcha"] !=$_POST["nilaiCaptcha"])
{
echo "username anda " .$_POST["username"];
echo "<br/>";
echo "password anda " .$_POST["password"];
echo "<br/>";
echo "kode captcha anda salah";
}
else
{
echo "username anda " .$_POST["username"];
echo "<br/>";
echo "password anda " .$_POST["password"];
echo "<br/>";
echo "kode captcha anda benar";
}
?>
</body>
|
64cfcb999a64e236e9dad4119dd41a77128da75e
|
[
"Markdown",
"PHP"
] | 3 |
Markdown
|
farrelreginaldo/captcha
|
f9afa96cd538128affff0306a98b0b8128610e3a
|
ab4e5443f4fc3d79ef18f494ad1d70c895c1ef0e
|
refs/heads/master
|
<file_sep>from keras.datasets import mnist, cifar10
from collections import Counter, defaultdict
import math
def sorted_batches(X_train, y_train, batch_size=64):
indexDict = defaultdict(list)
for i, y in enumerate(y_train):
indexDict[y].append(i)
N = y_train.shape[0]
n_batches = int(math.floor(N / batch_size))
idx = []
nb_classes = 10
indices = [0] * nb_classes
for i in range(n_batches):
j = i % nb_classes
start = indices[j]
end = indices[j] + batch_size
if end > len(indexDict[j]):
indices[j] = 0
items = indexDict[j][start:end]
idx.extend(items)
indices[j] += batch_size
return X_train[idx], y_train[idx]
if __name__ == "__main__":
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
img_color, img_rows, img_cols = 3, 32, 32
nb_classes = 10
y_train = y_train[:, 0]
y_test = y_test[:, 0]
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, img_color)
X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, img_color)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
X_train, y_train = sorted_batches(X_train, y_train, 64)
|
81a114756a980e39b6f209144362ae2ed85a9dc1
|
[
"Python"
] | 1 |
Python
|
fredericgo/mlds2017final
|
8bbf4bde54ab18df1467a313c43343df3df24bff
|
653a6124591e2259efee712e8874bcfd7f79e0bf
|
refs/heads/master
|
<file_sep># PianKe
片刻
<file_sep>//
// PKURL.h
// iOSPianKe
//
// Created by ma c on 16/1/17.
// Copyright © 2016年 赵金鹏. All rights reserved.
//
#ifndef PKURL_h
#define PKURL_h
#define LOGIN_URL @"http://api2.pianke.me/user/login"
#endif /* PKURL_h */
<file_sep>//
// Header.h
// iOSPianKe
//
// Created by ma c on 16/1/17.
// Copyright © 2016年 赵金鹏. All rights reserved.
//
#ifndef Header_h
#define Header_h
#endif /* Header_h */
|
e7d06c8c1fee0c4e8c03164375c22c2d55732be3
|
[
"Markdown",
"C"
] | 3 |
Markdown
|
q1662737134/PianKe
|
cad0db4f838fd4eae40cde5dc64ce4228beae5a7
|
0995e60b8ecf7cf93c5de32739e2f2a883e750e7
|
refs/heads/master
|
<repo_name>GianMoran/Rails-Practice-Code-Challenge-Travelatr-houston-web-012720<file_sep>/app/models/blogger.rb
class Blogger < ApplicationRecord
has_many :posts
has_many :destinations, through: :posts
validates :name , uniqueness: true, on: :create
validates :age, numericality: { greater_than: 0 }
def likes
self.posts.inject(0){|sum, post| sum+= post.likes}
end
def featured_post
self.posts.max_by {|post| post.likes}
end
def top_5
self.destinations.sort { |d1, d2|
d2.post_count(self) <=> d1.post_count(self)
}.first(5)
end
end
<file_sep>/app/controllers/destinations_controller.rb
class DestinationsController < ApplicationController
before_action :current_destination, only: [:show,:update,:edit,:destroy]
def index
@destinations = Destination.all
end
def show
end
def new
@destination = Destination.new
end
def edit
end
def create
@destination = Destination.create(strong_params)
redirect_to destination_path(@destination)
end
def update
@destination.update(strong_params)
redirect_to destination_path(@destination)
end
def destroy
@destination.destroy
redirect_to destinations_path
end
private
def current_destination
@destination = Destination.find(params[:id])
end
def strong_params
params.require(:destination).permit(:name,:country)
end
end
<file_sep>/app/models/destination.rb
class Destination < ApplicationRecord
has_many :posts
has_many :bloggers, through: :posts
def average_age
if self.bloggers.exists?
self.bloggers.inject(0){|sum, blogger| sum += blogger.age}/self.bloggers.count
else
return 0
end
end
def most_featured
self.posts.order(:created_at).first
end
def post_count(user)
counter = 0
self.posts.each do |post|
if post.blogger == user
counter += 1
end
end
counter
end
end
<file_sep>/app/controllers/posts_controller.rb
class PostsController < ApplicationController
before_action :current_post, only: [:show,:update,:edit,:destroy,:like]
def index
@posts = Post.all
end
def like
@post.likes +=1
@post.save
redirect_to post_path(@post)
end
def show
end
def new
@post = Post.new
@bloggers = Blogger.all
@destinations = Destination.all
end
def edit
@bloggers = Blogger.all
@destinations = Destination.all
end
def create
@post = Post.new(strong_params)
if @post.valid?
@post.likes = 0
@post.save
redirect_to post_path(@post)
else
flash[:errors] = @post.errors.full_messages
redirect_to new_post_path
end
end
def update
@post.update(strong_params)
redirect_to post_path(@post)
end
def destroy
@post.destroy
redirect_to posts_path
end
private
def current_post
@post = Post.find(params[:id])
end
def strong_params
params.require(:post).permit(:title,:content, :blogger_id, :destination_id)
end
end
<file_sep>/app/controllers/bloggers_controller.rb
class BloggersController < ApplicationController
before_action :current_blogger, only: [:update,:show,:edit, :destroy]
def index
@bloggers =Blogger.all
end
def new
@blogger = Blogger.new
end
def create
@blogger = Blogger.new(strong_params)
if @blogger.valid?
@blogger.save
redirect_to blogger_path(@blogger)
else
flash[:errors] = @blogger.errors.full_messages
redirect_to new_blogger_path
end
end
def show
end
def edit
end
def update
@blogger.update(strong_params)
redirect_to blogger_path(@blogger)
end
def destroy
@blogger.destroy
redirect_to bloggers_path
end
private
def current_blogger
@blogger = Blogger.find(params[:id])
end
def strong_params
params.require(:blogger).permit(:name, :bio, :age)
end
end
|
69487fe631ce049fb6c005215b993dda8236a357
|
[
"Ruby"
] | 5 |
Ruby
|
GianMoran/Rails-Practice-Code-Challenge-Travelatr-houston-web-012720
|
7bb2ed278828fe53dfaab15c18364767f4bf85f1
|
e459229555562db6e836b968c1a05a4b50a264c2
|
refs/heads/master
|
<repo_name>xiaonanln/PyHAAS<file_sep>/index.py
import haas
import struct
print('int size', struct.calcsize('I'))
haas.hello()
<file_sep>/haas/Service.py
# -*- coding: utf8 -*-
import abc
import asyncio
from .errors import ServiceError
class Service(abc.ABC):
"""Base class for services"""
def __init__(self):
self.task = None
def start(self):
if self.task is not None:
raise ServiceError('service is already started')
self.task = asyncio.get_event_loop().create_task(self.run())
@abc.abstractmethod
async def run(self):
pass
def stop(self):
self.task.cancel()
class MethodService(Service):
"""Base class for method services"""
def __init__(self):
super(MethodService, self).__init__()
self.callQueue = asyncio.Queue()
async def run(self):
while True:
call = await self.callQueue.get()
<file_sep>/haas/__init__.py
def hello():
print('hello', 'haas')
from .haas import Register, Run, SetEtcdAddress
from .Service import Service
__all__ = ['Service', 'Register', 'Run', 'SetEtcdAddress']<file_sep>/sample/etcd_test.py
import haas
from haas import asyncetcd
from haas import logging
import asyncio
class EtcdTestService(haas.Service):
async def run(self):
while True:
try:
setRes = await asyncetcd.Set( '/test_key', 'test_val' )
logging.info('set etcd ok: %s', setRes)
except asyncio.CancelledError as ex:
logging.error('set error: %s', ex)
except Exception as ex:
logging.error('set error: %s', ex)
try:
getRes = await asyncetcd.Get('/test_key')
logging.info('get etcd ok: %s', getRes)
except asyncio.CancelledError as ex:
logging.error('get error: %s', ex)
except Exception as ex:
logging.error('get error: %s', ex)
await asyncio.sleep(1.0)<file_sep>/haas/haas.py
import sys
import asyncio
import os
from . import asyncetcd
from .errors import RegisterError
from . import logging
from . import globals
if os.name == 'posix':
try:
import uvloop
except ImportError:
print('uvloop is not used', file=sys.stderr)
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
# elif os.name == 'nt':
# print('Using', asyncio.ProactorEventLoop.__doc__, file=sys.stderr)
# asyncio.set_event_loop(asyncio.ProactorEventLoop())
globals.loop = loop = asyncio.get_event_loop()
registeredServices = {}
runningServices = {}
def Run():
loop.call_later(1.0, checkServices)
logging.info('PyHAAS start running ...')
loop.run_forever()
def Register(serviceClass):
if serviceClass.__name__ in registeredServices:
raise RegisterError(serviceClass.__name__)
registeredServices[serviceClass.__name__] = serviceClass
runningServices[serviceClass.__name__] = set()
def checkServices():
try:
checkServicesImpl()
finally:
loop.call_later(1.0, checkServices)
def checkServicesImpl():
for className, serviceClass in registeredServices.items():
# print('registered service %s: %s' % (className, serviceClass), file=sys.stderr)
runningSet = runningServices[className]
if len(runningSet) < 1:
logging.info("Starting new service instance for %s ...", className)
s = serviceClass()
runningSet.add( s )
s.start()
def SetEtcdAddress(host, port):
asyncetcd.SetEtcdAddress(host, port)<file_sep>/haas/asyncetcd/__init__.py
from .asyncetcd import SetEtcdAddress, Set, Get<file_sep>/sample/app.py
import haas
import fib
import dummy
import web
import etcd_test
def main():
# haas.Register(fib.FibService)
haas.Register(dummy.DummyService1)
haas.Register(dummy.DummyService2)
haas.Register(web.WebService)
haas.Register(etcd_test.EtcdTestService)
haas.SetEtcdAddress( '127.0.0.1', 2379 )
haas.Run()
if __name__ == '__main__':
main()
<file_sep>/requirements.txt
dnspython==1.15.0
psutil==5.4.5
python-etcd==0.4.5
tornado==5.0.2
urllib3==1.22
<file_sep>/sample/web.py
import tornado.ioloop
import tornado.web
import haas
from haas import logging
service = None
class MainHandler(tornado.web.RequestHandler):
async def get(self):
n = int(self.get_argument('n', '1'))
res = await service.call( 'FibService', 'fib', n )
self.write(str(res))
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
class WebService(haas.Service):
async def run(self):
global service
service = self
app = make_app()
app.listen(25000)
logging.info('Listening on localhost:25000 ...')
<file_sep>/sample/dummy.py
import asyncio
import haas
class DummyService1(haas.Service):
async def run(self):
while True:
await asyncio.sleep(1.0)
print('i am dummy 1 ...')
class DummyService2(haas.Service):
async def run(self):
while True:
await asyncio.sleep(1.0)
print('i am dummy 2 ...')
<file_sep>/haas/logging.py
import logging
logging.basicConfig(level=logging.DEBUG,
format='levelname:%(levelname)s filename: %(filename)s '
'outputNumber: [%(lineno)d] thread: %(threadName)s output msg: %(message)s'
' - %(asctime)s', datefmt='[%d/%b/%Y %H:%M:%S]')
debug = logging.debug
info = logging.info
error = logging.error
warning = logging.warning
<file_sep>/haas/errors.py
class RegisterError(RuntimeError):
def __init__(self, className):
RuntimeError.__init__(self, 'Service %s is registered multiple times' % className)
class ServiceError(RuntimeError):
pass
<file_sep>/README.md
# PyHAAS
Highly Available Auto-Scaling Services in Python
**Design Goals:**
* Work with Kubernetes for autoscaling
* Automatic service discovery
* Reliable messaging
* Fault tolerant & recovery
<file_sep>/haas/globals.py
loop = None
<file_sep>/haas/asyncetcd/asyncetcd.py
import sys
import time
import etcd
import threading
import queue
import asyncio
import traceback
from .. import globals
etcdManThread = None
OP_GET = 1
OP_SET = 2
class EtcdManThread(threading.Thread):
def __init__(self, host, port):
threading.Thread.__init__(self)
self.host = host
self.port = port
self.client = etcd.Client(host=self.host, port=self.port)
self.requestQueue = queue.Queue()
def addRequest(self, req):
self.requestQueue.put( req )
def run(self):
loop = globals.loop
while True:
try:
self.loop_once(loop)
except Exception as ex:
traceback.print_exc()
time.sleep(1)
def loop_once(self, loop):
f, op, *args = self.requestQueue.get()
try:
if op == OP_GET:
res = self.client.get( args[0] )
elif op == OP_SET:
key, val = args
res = self.client.set(key, val)
else:
raise RuntimeError("unknown etcd operation: %s", op)
except Exception as ex:
loop.call_soon_threadsafe(f.set_exception, ex)
else:
loop.call_soon_threadsafe(f.set_result, res)
def assureConnected(self):
if self.client is None:
print('connected etcd: %s ...' % self.client, file=sys.stderr)
def SetEtcdAddress(host, port):
global etcdManThread
etcdManThread = EtcdManThread( host, port )
etcdManThread.setDaemon(True)
etcdManThread.start()
async def Set( key, val ):
f = asyncio.Future()
etcdManThread.addRequest( (f, OP_SET, key, val) )
res = await f
return res
async def Get(key):
f = asyncio.Future()
etcdManThread.addRequest( (f, OP_GET, key) )
res = await f
return res
|
20a0415d3ebd9b4cc0c4e9bae594f0a5e347b47e
|
[
"Markdown",
"Python",
"Text"
] | 15 |
Python
|
xiaonanln/PyHAAS
|
d549418c579aedf2450fdd8bb38c323bc9342457
|
0da62fcb4021cca0d54182f5efdda718f3b68be4
|
refs/heads/main
|
<repo_name>lamnguyenthanh2510/ASM_EAD<file_sep>/hello-lam/src/main/java/com/example/hello/service/UserService.java
package com.example.hello.service;
import com.example.hello.entity.UserEntity;
import java.util.List;
public interface UserService {
UserEntity createUser(UserEntity userEntity);
List<UserEntity> getAll();
void delete(UserEntity emp);
UserEntity findOne (int id);
void save(UserEntity emp);
}
<file_sep>/hello-lam/src/main/java/com/example/hello/repository/UserRepo.java
package com.example.hello.repository;
import com.example.hello.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepo extends JpaRepository<UserEntity, Integer> {
}
|
81c416dfcd64899b25cc9fda8780cb3c0eb4e5d3
|
[
"Java"
] | 2 |
Java
|
lamnguyenthanh2510/ASM_EAD
|
58424a1fccdb6dc997b7ffa1ef3c407de6f33829
|
ffe7a31b7bf132f9d186cbfd159776fa1ba6ee29
|
refs/heads/master
|
<file_sep>#!/bin/bash
set -euo pipefail
# This script is run every time an instance of our app - aka grain - starts up.
# This is the entry point for your application both when a grain is first launched
# and when a grain resumes after being previously shut down.
cd /opt/app
./sandpass \
-db=/var/keepass.kdb \
-listen='[::]:8000' \
-static_dir=/opt/app \
-templates_dir=/opt/app/templates
<file_sep>#!/bin/bash
# When you change this file, you must take manual action. Read this doc:
# - https://docs.sandstorm.io/en/latest/vagrant-spk/customizing/#setupsh
set -euo pipefail
GOVERSION='go1.6.3'
if ! [[ -f /usr/local/go/VERSION && "$(cat /usr/local/go/VERSION)" == "$GOVERSION" ]]; then
echo "Downloading $GOVERSION"
rm -rf /usr/local/go
curl -sSL "https://storage.googleapis.com/golang/${GOVERSION}.linux-amd64.tar.gz" | \
tar -C /usr/local -xzf -
fi
if [[ ! -d /gopath ]]; then
mkdir /gopath
chown vagrant:vagrant /gopath
fi
<file_sep>// Copyright 2016 The Sandpass Authors
//
// 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 main
import (
"crypto/rand"
"encoding/base64"
"flag"
"net/http"
"time"
"zombiezen.com/go/sandpass/pkg/kdbcrypt"
"zombiezen.com/go/sandpass/pkg/keepass"
)
// Session flags.
var (
sessionExpiry = flag.Duration("session_expiry", 30*time.Minute, "length of time that a session token is valid")
tokenSize = flag.Int("token_size", 33, "size of the session tokens sent to the client (in bytes)")
)
// sessionCookie is the name of browser cookie containing the session token.
const sessionCookie = "sandpass_session"
type sessionStorage struct {
s map[string]*session
}
// new creates a new session and token.
func (ss *sessionStorage) new(w http.ResponseWriter, data sessionData) *session {
buf := make([]byte, *tokenSize)
_, err := rand.Read(buf)
if err != nil {
// TODO(light): return error?
panic(err)
}
tok := base64.StdEncoding.EncodeToString(buf)
s := &session{
token: tok,
expires: time.Now().Add(*sessionExpiry),
sessionData: data,
}
if ss.s == nil {
ss.s = make(map[string]*session)
}
ss.s[tok] = s
http.SetCookie(w, &http.Cookie{
Name: sessionCookie,
Value: s.token,
Path: "/",
})
return s
}
func (ss *sessionStorage) dbFromRequest(w http.ResponseWriter, r *http.Request) (*keepass.Database, error) {
s := ss.fromRequest(r)
if !s.isValid() {
// Attempt to decrypt with no credentials, since that shouldn't require the
// user to enter credentials.
if db, err := openDatabase(nil); err == nil {
ss.new(w, sessionData{key: db.ComputedKey()})
return db, nil
}
return nil, errInvalidSession
}
return openDatabase(&keepass.Options{
ComputedKey: s.key,
})
}
func (ss *sessionStorage) fromRequest(r *http.Request) *session {
if ss.s == nil {
return nil
}
c, err := r.Cookie(sessionCookie)
if err != nil {
return nil
}
return ss.s[c.Value]
}
func (ss *sessionStorage) clear() {
for id, s := range ss.s {
s.clear()
delete(ss.s, id)
}
}
func (ss *sessionStorage) clearInvalid() int {
n := 0
for id, s := range ss.s {
if !s.isValid() {
s.clear()
delete(ss.s, id)
n++
}
}
return n
}
type sessionData struct {
key kdbcrypt.ComputedKey
}
// clear zeroes out the session's data as a weak defense against RAM compromise.
func (data *sessionData) clear() {
for i := range data.key {
data.key[i] = 0
}
}
type session struct {
sessionData
token string
expires time.Time
}
func (s *session) isValid() bool {
return s != nil && time.Now().Before(s.expires)
}
<file_sep># v1.0.0
* New new icons (thanks again, @neynah. You rock.)
* Search
* Multi-word searches match individual words instead of literal phrases
* Searches happen over entry notes, not just titles
* Show entry's group in results page
* Security Precautions
* Pages are marked as uncacheable to avoid the user agent potentially storing
credentials in clear text
* Disabled autocomplete on entry form fields for similar reasons.
* Added basic XSRF protection. Defense in depth here, as Sandstorm protects
against XSRF attacks anyway.
* Minor visual tweaks
# v1.0.0-rc1
* Features
* Search (#3)
* Password generation (#11)
* Deletion of entries (#5)
* Deletion of entire database (#8)
* Moving entities and groups between groups (#15)
* Creating, editing, and deleting groups (#4)
* Separate out management role (#18)
* Bug Fixes
* Preserve attachments in existing KeePass databases (#12)
* Clear sessions from memory shortly after expiring (#14)
# v0.2.2
* New icon (thanks @neynah)
* Store derived key in sessions instead of password/keyfile (improves request
performance)
* Security: generate random IV for every write
# v0.2.1
* Basic styling
* Actually bump version number
# v0.2.0
* Allow toggling password visibility
* Direct copy of passwords
* Bypass credentials page if database is not encrypted
* Add breadcrumb navigation
* Update Sandstorm shell paths and titles on page navigation
# v0.1.0
Initial public release.
<file_sep># Sandpass
Sandpass is a web-based password manager based on the [KeePass][keepass]
database format that runs on [Sandstorm][sandstorm].
Sandpass has not undergone a formal security review: use at your own risk.
[keepass]: http://keepass.info/
[sandstorm]: https://sandstorm.io/
## Installing
Install Sandpass from [the Sandstorm App Market][sandpass-app-market],
or grab the SPK from the [releases][releases] page.
[sandpass-app-market]: https://apps.sandstorm.io/app/rq41p170hcs5rzg66axggv8r90fjcssdky8891kq5s7jcpm1813h
[releases]: https://github.com/zombiezen/sandpass/releases
## Developing
Prerequisite: [Go 1.6](https://golang.org/dl/)
```
go get zombiezen.com/go/sandpass
cd $GOPATH/zombiezen.com/go/sandpass
```
Running as a normal HTTP server:
```
sandpass -db=foo.db -listen=localhost:8080 -permissions=false
```
Running as a Sandstorm app (requires [vagrant-spk][vagrant-spk-install]):
```
vagrant-spk dev
```
[vagrant-spk-install]: https://docs.sandstorm.io/en/latest/vagrant-spk/installation/
## License
Apache 2.0. See the LICENSE file for details. Vendored libraries are released
under their respective licenses.
<file_sep>#!/bin/bash
set -euo pipefail
# This script is run in the VM each time you run `vagrant-spk dev`. This is
# the ideal place to invoke anything which is normally part of your app's build
# process - transforming the code in your repository into the collection of files
# which can actually run the service in production
cd /opt/app
export GOPATH=/gopath
if [[ ! -h "$GOPATH/src/zombiezen.com/go/sandpass" ]]; then
mkdir -p "$GOPATH/src/zombiezen.com/go/"
ln -s /opt/app "$GOPATH/src/zombiezen.com/go/sandpass"
fi
/usr/local/go/bin/go install zombiezen.com/go/sandpass
cp --archive "$GOPATH/bin/sandpass" sandpass
exit 0
|
e283c93f601a891878e762b9201ab71656a06f65
|
[
"Markdown",
"Go",
"Shell"
] | 6 |
Shell
|
haiderny/sandpass
|
fac8ba01e3bc4288e6b9a6712ea635970dea4882
|
28f1fc8026719f5a846f70b55fcf69fb50884a01
|
refs/heads/main
|
<repo_name>hasnatosman/bmi_calculation<file_sep>/README.md
calculate your BMI.
<file_sep>/bmi_calculator.py
print('BMI calculator to check Body Mass Index.!')
# how to find bmi......................
def BMI(weight, height):
bmi = weight / (height ** 2)
return bmi
# driver code..........................
weight = int(input('Input your weight in kg :'))
height = float(input('Input your height in metre :'))
# calling the BMI function.............
bmi = BMI(weight, height)
print('The BMI is', format(bmi), ', So it looks you are ', end=' ')
if bmi < 18.5:
print('underweight.')
elif 18.5 < bmi < 24.9:
print('healthy.')
elif 24.9 < bmi < 30:
print('overweight.')
elif bmi > 30:
print('suffering from the obesity.')
|
e7e64fad2a61cca2d310ea3c3d9a495f5e6809b4
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
hasnatosman/bmi_calculation
|
2362c33f8f99c2bfe04b776b84ebabefd138966b
|
f3cc6263abf91f401d03bdb6df3c84ec2d383177
|
refs/heads/master
|
<repo_name>censore/EX-2<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('reset_password/{token}', ['as' => 'password.reset', function($token)
{
// implement your reset password route here!
}]);
/*
Route::group(['prefix'=>'auth', 'middleware'=>'web'], function(){
#Route::get('/', 'Auth\LoginController@login');
Route::get('/login', 'Auth\LoginController@login');
});*/
Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'adminRole', 'RoleAndLang']], function (){
CRUD::resource('user', 'Admin\UserCrudController');
Route::post('/user/gift/{user_id}/{gift_id}', 'Admin\UserCrudController@gift');
Route::post('/user/bonus/{user_id}','Admin\UserCrudController@bonus');
Route::post('/user/bonus/{user_id}/{type}','Admin\UserCrudController@bonus');
CRUD::resource('categories', 'Admin\CategoriesCrudController');
CRUD::resource('restaurants', 'Admin\RestaurantsCrudController');
CRUD::resource('posterminals', 'Admin\PosTerminalsCrudController');
CRUD::resource('menu', 'Admin\MenuCrudController');
CRUD::resource('menucitycosts', 'Admin\MenuCityCostsCrudController');
CRUD::resource('popular', 'Admin\PopularCrudController');
CRUD::resource('percentgroups', 'Admin\PercentGroupsCrudController');
CRUD::resource('nomenklatura', 'Admin\NomenklaturaCrudController');
CRUD::resource('bonusgroups', 'Admin\BonusGroupsCrudController');
CRUD::resource('messages', 'Admin\PushNotificationMessagesCrudController');
CRUD::resource('templates', 'Admin\PushNotificationTemplatesCrudController');
CRUD::resource('schedule', 'Admin\PushNotificationScheduleCrudController');
CRUD::resource('logs', 'Admin\PushNotificationLogsCrudController');
CRUD::resource('smsmessages', 'Admin\SmsMessagesCrudController');
CRUD::resource('smsschedules', 'Admin\SmsScheduleCrudController');
CRUD::resource('smslogs', 'Admin\SmsLogsCrudController');
CRUD::resource('article', 'Admin\ArticleCrudController');
CRUD::resource('category', 'Admin\CategoryCrudController');
CRUD::resource('tag', 'Admin\TagCrudController');
CRUD::resource('koefbonusschedule', 'Admin\KoefBonusScheduleCrudController');
CRUD::resource('menubonusschedule', 'Admin\MenuBonusScheduleCrudController');
Route::get('settings','Admin\SettingsController@index');
Route::post('settings','Admin\SettingsController@update');
CRUD::resource('aromagifts', 'Admin\AromaGiftsCrudController');
Route::get('executeschedule/{scheduleName}', 'Admin\AdminController@executeschedule');
Route::get('geocity', 'Admin\GeoCitiesController@index');
Route::get('geocity/{id}', 'Admin\GeoCitiesController@show');
Route::get('menus', 'Admin\MenuController@index');
Route::get('menus/{id}', 'Admin\MenuController@show');
Route::get('restaurant', 'Admin\RestaurantController@index');
Route::get('restaurant/{id}', 'Admin\RestaurantController@show');
Route::get('users', 'Admin\UserController@index');
Route::get('users/{id}', 'Admin\UserController@show');
Route::group(['prefix' => '/reports', 'middleware' => ['admin']], function () {
Route::get('/', 'Admin\ReportController@reports'); // show user reports forms
Route::get('/rate', 'Admin\ReportController@rate'); // show user reports forms
Route::get('/bonus', 'Admin\ReportController@mistakes'); // show user reports forms
Route::get('/gifts', 'Admin\ReportController@usersGifts');
Route::get('/bonusReport', 'Admin\ReportController@bonusReport');
Route::match(array('GET', 'POST'), '/user', 'Admin\ReportController@user');
Route::get('/user/detail/{user_id}/purchases', 'Admin\ReportController@transactions');
Route::get('/user/detail/{user_id}/comments', 'Admin\ReportController@userComments');
Route::get('/user/detail/{user_id}/gifts', 'Admin\ReportController@userGifts');
});
Route::get('/user_export', 'Admin\UploadUsersController@index');
Route::get('/user_export/{id}/download', 'Admin\UploadUsersController@download')->where(['id'=>'^[0-9]+$']);
Route::post('/user_export', 'Admin\UploadUsersController@index');
CRUD::resource('/ratecomments', 'Admin\RatecommentsCrudController');
CRUD::resource('role', 'Admin\RoleCrudController');
});
Route::get('/', 'Admin\AdminController@home');<file_sep>/database/migrations/2017_12_07_130052_alter_geo.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterGeo extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('geo_cities', function ($table) {
$sql = 'TRUNCATE TABLE `geo_cities`';
DB::connection()->getPdo()->exec($sql);
$sql = 'TRUNCATE TABLE `geo_areas`';
DB::connection()->getPdo()->exec($sql);
$sql = 'TRUNCATE TABLE `geo_regions`';
DB::connection()->getPdo()->exec($sql);
$sql = 'TRUNCATE TABLE `geo_types`';
DB::connection()->getPdo()->exec($sql);
$table->dropColumn('area');
$table->dropColumn('region');
$table->dropColumn('type');
$table->dropColumn('title_en');
$table->dropColumn('title_ru');
$table->dropColumn('title_ua');
$table->dropColumn('latitude');
$table->dropColumn('longitude');
$table->decimal('lat', 10, 8);
$table->decimal('lng', 11, 8);
$table->bigInteger('koatuu')->change();
$table->boolean('center')->change();
$table->json('title');
$table->integer('geo_area_id')->after('id');
$table->integer('geo_region_id')->after('geo_area_id');
$table->integer('geo_type_id')->after('geo_region_id');
});
Schema::table('geo_areas', function ($table) {
$table->dropColumn('ref');
$table->dropColumn('group');
$table->dropColumn('title_en');
$table->dropColumn('title_ru');
$table->dropColumn('title_ua');
$table->json('title');
});
Schema::table('geo_regions', function ($table) {
$table->dropColumn('ref');
$table->dropColumn('title_en');
$table->dropColumn('title_ru');
$table->dropColumn('title_ua');
$table->integer('geo_area_id')->after('id');
$table->json('title');
});
Schema::table('geo_types', function ($table) {
$table->dropColumn('ref');
$table->dropColumn('title_en');
$table->dropColumn('title_ru');
$table->dropColumn('title_ua');
$table->json('title');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/database/migrations/2017_12_15_154225_add_opertaion_to_user_history.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddOpertaionToUserHistory extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$sql = 'ALTER TABLE `user_history` CHANGE `operation` `operation` ENUM(\'bonus\',\'birthdate\',\'status\',\'phone\',\'percent_group_id\') NOT NULL;';
DB::connection()->getPdo()->exec($sql);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/database/migrations/2017_12_07_122042_alter_restaurants.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterRestaurants extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('restaurants', function ($table) {
$sql = 'TRUNCATE TABLE `restaurants`';
DB::connection()->getPdo()->exec($sql);
$sql = 'TRUNCATE TABLE `pos_terminals`';
DB::connection()->getPdo()->exec($sql);
$sql = 'TRUNCATE TABLE `restaurants_images`';
DB::connection()->getPdo()->exec($sql);
$sql = 'TRUNCATE TABLE `restaurant_tags`';
DB::connection()->getPdo()->exec($sql);
$sql = 'DROP TABLE `pos_terminals_group`';
DB::connection()->getPdo()->exec($sql);
$table->dropColumn('address');
});
Schema::table('restaurants', function (Blueprint $table){
$table->dropColumn('description');
$table->dropColumn('ceramic_dish');
$table->dropColumn('kruasan');
$table->dropColumn('latlng');
$table->dropColumn('server_name');
$table->dropColumn('invalid');
$table->json('address');
$table->json('keywords');
$table->boolean('wc')->default(0)->change();
$table->boolean('cookies')->default(0)->change();
$table->boolean('soup')->default(0)->change();
$table->boolean('seat')->default(0)->change();
$table->boolean('dessert')->default(0)->change();
$table->boolean('buggy')->default(0)->change();
$table->decimal('lat', 10, 8)->change();
$table->decimal('lng', 11, 8)->change();
$table->renameColumn('superviser', 'supervisor');
$table->renameColumn('superviser_email', 'supervisor_email');
});
Schema::table('pos_terminals', function (Blueprint $table){
$table->dropColumn('server_name');
$table->integer('restaurant_id')->after('id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/features/bootstrap/FeatureContext.php
<?php
use Behat\Behat\Tester\Exception\PendingException;
use Behat\Behat\Context\Context;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;
use PHPUnit_Framework_Assert as PHPUnit;
use Behat\MinkExtension\Context\MinkContext;
use GuzzleHttp\Client;
/**
* Defines application features from the specific context.
*/
class FeatureContext extends MinkContext implements Context, \Behat\Behat\Context\SnippetAcceptingContext
{
protected $client;
protected $response;
/**
* Initializes context.
*
* Every scenario gets its own context instance.
* You can also pass arbitrary arguments to the
* context constructor through behat.yml.
*/
public function __construct()
{
$this->client = new Client([
'base_url'=>Request::root()
]);
}
/**
* @When /^I send a ([A-Z]+) request to "([^"]*)"$/
*/
public function iSendAPostRequest($method, $uri)
{
$request = $this->client->createRequest($method, $uri);
$this->response = $this->client->send($request);
}
/**
* @Then /^the response code should be (\d+)$/
*/
public function theResponseCodeShouldBe($response_code)
{
assertEquals($response_code, $this->response->getStatusCode());
}
/**
* @Then the JSON response should have a :arg1 containing :arg2
*/
public function theJsonResponseShouldHaveAContaining($arg1, $arg2)
{
throw new PendingException();
}
}
<file_sep>/database/migrations/2017_12_06_154952_articles_translate.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ArticlesTranslate extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('articles', function ($table) {
$table->dropColumn('title');
$table->dropColumn('content');
});
Schema::table('articles', function ($table) {
$table->json('title')->after('category_id');
$table->json('content')->after('category_id');
});
Schema::table('articles', function ($table) {
// init JSON fields
$sql = 'UPDATE `articles` SET `title`="{}",`content`="{}"';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('articles', function ($table) {
$table->string('title')->change();
$table->text('content')->change();
});
}
}
<file_sep>/database/migrations/2017_12_07_190358_alter_menu.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterMenu extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('menu', function ($table) {
$sql = 'TRUNCATE TABLE `menu`';
DB::connection()->getPdo()->exec($sql);
$sql = 'TRUNCATE TABLE `nomenklatura`';
DB::connection()->getPdo()->exec($sql);
$table->dropColumn('title');
$table->dropColumn('title_ukr');
$table->dropColumn('title_en');
$table->dropColumn('bonus');
$table->dropColumn('color');
$table->dropColumn('city');
$table->dropColumn('restaurant_id');
$table->dropColumn('sale');
$table->dropColumn('weight');
$table->dropColumn('description');
$table->dropColumn('medium');
$table->dropColumn('cost');
$table->dropColumn('large');
});
Schema::table('menu', function ($table) {
$table->json('unit');
$table->json('title');
$table->json('description');
});
Schema::table('nomenklatura', function ($table) {
$table->renameColumn('nomen_cost', 'nomen_small');
});
Schema::create('menu_city_costs', function (Blueprint $table) {
$table->integer('menu_id');
$table->integer('geo_city_id');
$table->decimal('cost_small', 8, 2);
$table->decimal('cost_medium', 8, 2);
$table->decimal('cost_large', 8, 2);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/resources/lang/vendor/backpack/ru/base.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Backpack\Base Language Lines
|--------------------------------------------------------------------------
*/
'bonus_groups_title'=>'Группы подарков',
'bonus_groups'=>'Группы',
'bonus_gifts'=>'Подарки',
'map_title'=>'Локации кофеен',
'other'=>'Другое',
'crud' => 'Создать / Изменить',
'statistics'=>'Статистика',
'bonus_program'=>'Бонусная программа',
'bonus_settings'=>'Настройки бонусов',
'Sale'=>'Акция',
'sale'=>'Акция',
'cities'=>'Города',
'popular'=>'Предложение недели',
'categories'=>'Категории',
'restaurants'=>'Кофейни',
'menu'=>'Меню',
'users'=>'Пользователи',
'registration_closed' => 'Регистрация закрыта',
'first_page_you_see' => '',
'login_status' => 'Статус логина',
'logged_in' => 'Вы вошли!',
'toggle_navigation' => 'Переключить навигацию',
'administration' => 'АДМИНИСТРИРОВАНИЕ',
'user' => 'ПОЛЬЗОВАТЕЛЬ',
'logout' => 'Выход',
'login' => 'Вход',
'register' => 'Регистрация',
'name' => 'Имя',
'email_address' => 'E-Mail',
'password' => '<PASSWORD>',
'confirm_password' => '<PASSWORD>',
'remember_me' => 'Запомнить меня',
'forgot_your_password' => '<PASSWORD>?',
'reset_password' => '<PASSWORD>',
'send_reset_link' => 'Отправить ссылку для сброса пароля',
'click_here_to_reset' => 'Нажмите здесь для сброса пароля',
'unauthorized' => 'Неавторизован',
'dashboard' => 'Панель управления',
'handcrafted_by' => 'Сделано в',
'powered_by' => 'Powered by',
'push_notifications' => 'Push-уведомления',
'push_notification_templates' => 'Шаблоны уведомлений',
'push_notification_messages' => 'Уведомления',
'push_notification_schedule' => 'Рассылки',
'push_notification_logs' => 'История',
'sms' => 'SMS',
'sms_messages' => 'Сообщения',
'sms_schedules' => 'Рассылки',
'sms_logs' => 'История',
'user_settings' => 'Настройки пользователей',
'groups' => 'Группы',
'roles' => 'Разрешения',
'news' => 'Новости',
'articles' => 'Статьи',
'tags' => 'Теги',
'settings' => 'Настройки',
'costs' => 'Цены и наличие',
'pos' => 'POS-терминалы',
'percentgroups' => 'Группы скидок',
'menubonusschedule' => 'Бонусы на блюда',
'koefbonusschedule' => 'Умножение бонусов',
'nomenklatura' => 'Номенклатура 1С',
'access_denied' => 'Доступ запрещен',
'aroma_gifts_title' => 'Подарки от Аромы'
];
<file_sep>/database/migrations/2017_12_12_142218_add_bonus_types.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddBonusTypes extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('gifts', function ($table) {
$table->dropColumn(['used']);
$table->enum('type', ['gift', 'aroma'])->after('menu_id');
$table->integer('bonus_group_id')->after('menu_id');
});
Schema::table('bonus_history', function ($table) {
$table->enum('type', ['food', 'drink'])->after('transaction_id')->nullable();
$table->integer('menu_id')->after('transaction_id');
$table->integer('bonus_group_id')->after('transaction_id');
});
Schema::table('bonus_groups', function ($table) {
$table->enum('type', ['food', 'drink', 'gift', 'aroma'])->after('id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/resources/lang/uk/json.php
<?php
/**
* Created by PhpStorm.
* User: dev
* Date: 09-Nov-17
* Time: 11:17 AM
*/
return [
'City_not_found' => 'Місто не знайдено',
'already_voted' => 'Ви вже оцінили цю кофейню',
'no_voting_transactions' => 'Ви не можете оцінити цю кофейню',
'User_not_found' => 'Користувача не знайдено',
'Incorrect_reset_link' => 'Невірний токен для скидання пароля',
'Access_denied' => 'Доступ заборонено',
'Something_went_wrong' => 'Щось з авторизацією пішло не так, спробуйте повторити пізніше',
'Password_changed' => '<PASSWORD>',
'Token_invalid' => '<PASSWORD>',
'Sms_code_invalid' => 'Невірний код SMS',
'User_already_exists' => 'Користувач вже існує',
'User_register_error' => 'Помилка створення користувача, перевірте правильність введених даних',
'Categories not found' => 'Категорія не знайдена',
'Favorite_Restaurants_not_found' => 'Кав\'ярню не знайдено в обраному',
'Favorites_not_found' => 'У вас відсутні обрані товари',
'Menu_not_found' => 'Товари відсутні',
'Menu_deleted_successfully' => 'Товар видалено',
'Can_t_store_image' => 'Невдалось зберегти аватар',
'User_deleted_successfully' => 'Користувача видалено',
'User_retrieved_successfully' => 'Користувач успішно переданий',
'User_saved_successfully' => 'Дані користувача збережені',
'Favorite_Restaurants_saved_successfully' => 'Кав\'ярня успішно додана в обране',
'Phone_number_already_registered_in_our_system' => 'Введений телефон вже зареєстрований в системі',
'Operator_not_allowed' => 'Невірний оператор',
'user_is_not_activated' => 'Користувач не активований',
'user_is_blocked' => 'Користувач заблокований. Зверніться за адресою <EMAIL>',
'Entered_sms_code_invalid' => 'Невірний код SMS',
'error_adding_to_favorites' => 'Помилка додавання в обране',
'Popular_not_found' => 'Пропозиції тижня не знайдені',
'Restaurant_not_found' => 'Кав\'ярню не знайдено',
'Restaurants_not_found' => 'Кав\'ярні не знайдені',
'Favirite_ID_didn\'t_found' => 'Обрані кав\'ярні не знайдені',
'Old_password_incorrect' => '<PASSWORD> вказано <PASSWORD>',
'Token_expired' => 'Закінчився термін дії токена',
'cant_change_bonus_type' => 'Бонусну програму можна змінювати не частіше разу на день',
'sms_code_limit' => 'Ви можете запитувати SMS на відновлення пароля не частіше 3-х разів на годину',
'authorization_code' => 'Ваш код авторизації: :code',
'email_is_taken' => 'Такий e-mail вже зайнятий',
'wrong_credentials' => 'Пароль вказано невірно',
'too_many_login_requests' => 'Кількість спроб введення паролю вичерпано. Відновіть пароль через SMS'
];<file_sep>/database/migrations/2017_11_24_142524_create_push_notification_schedule_push_notification_groups_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePushNotificationSchedulePushNotificationGroupsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('push_notification_schedule_push_notification_groups', function (Blueprint $table) {
$table->unsignedBigInteger('push_notification_schedule_id');
$table->unsignedBigInteger('push_notification_group_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('push_notification_schedule_push_notification_groups');
}
}
<file_sep>/README.md
Example 2
Example with Laravel 5.2"# EX-2"
<file_sep>/database/migrations/2017_09_14_082958_create_table_restaurants.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableRestaurants extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (Schema::hasTable('restaurants')) return;
Schema::create('restaurants', function (Blueprint $table) {
$table->increments('id');
$table->string('title', 100);
$table->text('description')->nullable();
$table->string('latlng', 8, 2)->nullable();
$table->string('address')->nullable();
$table->integer('status')->default(1);
$table->integer('city_id')->nullable();
$table->string('open')->nullable();
$table->string('close')->nullable();
$table->string('server_name', 100)->nullable();
$table->integer('point_type');
$table->string('wc',4);
$table->string('invalid',4);
$table->string('cookies',4);
$table->string('soup',4);
$table->string('seat',4);
$table->string('kruasan', 3)->default('да');
$table->string('dessert',4);
$table->string('ceramic_dish',4);
$table->string('superviser', 100);
$table->string('superviser_email', 100);
$table->integer('places')->default(0);
$table->timestamps();
});
}
public function down()
{
//
}
}
<file_sep>/database/seeds/fill_point_types.php
<?php
use Illuminate\Database\Seeder;
use \App\Models\PointTypes;
class fill_point_types extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$data = [
'Большая',
'Киоск со входом',
'Киоск',
'Островок',
'Фудкорт',
'Киоск (летняя точка на колесах)',
'Маф',
];
foreach($data as $item){
$model = new PointTypes();
$model->title = $item;
$model->save();
}
}
}
<file_sep>/config/com.php
<?php
/**
* Created by PhpStorm.
* User: dev
* Date: 18-Oct-17
* Time: 9:27 AM
*/
return json_decode( json_encode([
'api'=>'remote',
'dll'=>[
'object'=>'DSCom.DSComObj'
],
'remote'=>[
'ip'=>'192.168.3.11',
'port'=>'80',
'hash'=>'98aqerugm-qe9r8gu-e98qgue98gru-qe',
]
]));
<file_sep>/resources/lang/ru/errors.php
<?php
/**
* Created by PhpStorm.
* User: dev
* Date: 09-Nov-17
* Time: 11:17 AM
*/
return [];<file_sep>/database/migrations/2017_09_14_080458_create_table_menu.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableMenu extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (Schema::hasTable('menu')) return;
Schema::create('menu', function (Blueprint $table) {
$table->increments('id');
$table->string('title', 100);
$table->text('description')->nullable();
$table->decimal('cost', 8, 2);
$table->decimal('sale');
$table->integer('category_id');
$table->integer('restaurant_id');
$table->float('bonus', 200)->default('0.00');
$table->string('image')->default('no_product.jpg');
$table->float('weight')->default('0.01');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('menu');
}
}
<file_sep>/database/migrations/2017_11_22_131604_alter_table_transactions_add_more_fields.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterTableTransactionsAddMoreFields extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (!Schema::hasTable('transactions')) return;
Schema::table('transactions', function(Blueprint $table) {
$table->float('discount', '3','2');
$table->float('count', '3','2');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/database/migrations/2017_12_18_130259_drop_unused_tables.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class DropUnusedTables extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (Schema::hasTable('allowed_phones')) Schema::drop('allowed_phones');
if (Schema::hasTable('dds_repositories')) Schema::drop('dds_repositories');
if (Schema::hasTable('bonuses')) Schema::drop('bonuses');
if (Schema::hasTable('cities')) Schema::drop('cities');
if (Schema::hasTable('favorite_categories')) Schema::drop('favorite_categories');
if (Schema::hasTable('restaurant_tags')) Schema::drop('restaurant_tags');
if (Schema::hasTable('social_login_profiles')) Schema::drop('social_login_profiles');
if (Schema::hasTable('tags_list')) Schema::drop('tags_list');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/database/migrations/2017_12_06_140511_menu_categories_translate.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class MenuCategoriesTranslate extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('menu_categories', function ($table) {
// add JSON field
$table->json('tmp_title')->after('title');
});
Schema::table('menu_categories', function ($table) {
// init JSON field
$sql = 'UPDATE `menu_categories` SET `tmp_title`="{}"';
DB::connection()->getPdo()->exec($sql);
// copy data to JSON field
$sql = 'UPDATE `menu_categories` SET `tmp_title`=JSON_SET(`tmp_title`, "$.ru", `title`);';
DB::connection()->getPdo()->exec($sql);
// drop old text field
$table->dropColumn('title');
// rename new JSON field
$table->renameColumn('tmp_title', 'title');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('menu_categories', function ($table) {
$table->string('title', 50)->change();
});
}
}
<file_sep>/database/migrations/2017_11_24_095453_create_push_notification_logs_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePushNotificationLogsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('push_notification_logs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id')->comment('Initiator ID');
$table->string('action', 100)->nullable();
$table->string('status', 20)->nullable();
$table->text('text')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('push_notification_logs');
}
}
<file_sep>/routes/api.php
<?php
use Dingo\Api\Routing\Router;
/** @var Router $api */
$api = app(Router::class);
$api->version('v1', function (Router $api) {
$api->group(['prefix' => 'scanner'], function(Router $api){
$api->post('card', 'App\Api\V1\Controllers\ScannerController@card');
});
$api->group(['prefix' => 'itcafe'], function(Router $api){
$api->post('order', 'App\Api\V1\Controllers\ItcafeController@order');
});
$api->group(['prefix' => 'auth', 'middleware'=>['RoleAndLang'],], function(Router $api) {
$api->post('signup', 'App\Api\V1\Controllers\SignUpController@signUp');
$api->post('login', 'App\Api\V1\Controllers\LoginController@login');
$api->post('facebook', 'App\Api\V1\Controllers\LoginController@loginFacebook');
$api->post('google', 'App\Api\V1\Controllers\LoginController@loginGoogle');
$api->post('recovery', 'App\Api\V1\\Controllers\ForgotPasswordController@sendResetSms');
$api->post('reset', 'App\Api\V1\Controllers\ResetPasswordController@resetPassword');
$api->post('activate', 'App\Api\V1\Controllers\SignUpController@activateUser');
$api->post('resend', 'App\Api\V1\Controllers\SignUpController@resend');
$api->post('phone/change', 'App\Api\V1\Controllers\SignUpController@activate_phone');
//$api->post('social', 'App\Http\Controllers\Api\LoginController@social');
});
$api->group(['prefix'=>'bonus', 'middleware'=>['jwt.auth','RoleAndLang','uniqueToken']], function (Router $api){
$api->get('/history', 'App\Http\Controllers\Api\BonusHistoryAPIController@index');
});
$api->group(['prefix'=>'restaurants','middleware'=>['jwt.auth','RoleAndLang','uniqueToken',]], function (Router $api){
$api->get('/favorites', 'App\Http\Controllers\Api\FavoriteRestaurantsAPIController@index');
$api->get('/', 'App\Http\Controllers\Api\RestaurantsAPIController@index');
$api->post('/search', 'App\Http\Controllers\Api\RestaurantsAPIController@textSearch');
$api->post('/', 'App\Http\Controllers\Api\RestaurantsAPIController@nearest');
$api->post('/{id}/vote', 'App\Http\Controllers\Api\RatecommentsAPIController@store')->where(['id'=>'^[0-9]+$']);
$api->delete('/{id}/vote', 'App\Http\Controllers\Api\RatecommentsAPIController@decline')->where(['id'=>'^[0-9]+$']);
$api->get('/{id}', 'App\Http\Controllers\Api\RestaurantsAPIController@show')->where(['id'=>'^[0-9]+$']);
$api->get('/{id}/products', 'App\Http\Controllers\Api\MenuAPIController@showMenu')->where(['id'=>'^[0-9]+$']);
$api->get('/{restaurant_id}/categories/{id}/', 'App\Http\Controllers\Api\CategoriesAPIController@show')->where([
'id'=>'^[0-9]+$'
]);
$api->get('/{restaurant_id}/categories/{id}/products', 'App\Http\Controllers\Api\MenuAPIController@showByCategory')->where([
'restaurant_id'=>'^[0-9]+$',
'id'=>'^[0-9]+$',
]);
$api->post('/{restaurant_id}', 'App\Http\Controllers\Api\RestaurantsAPIController@addToFavorites');
$api->delete('/{restaurant_id}', 'App\Http\Controllers\Api\RestaurantsAPIController@deleteFromFavorites');
$api->get('/{id}/categories', 'App\Http\Controllers\Api\CategoriesAPIController@showCategory')->where(['id'=>'^[0-9]+$']);
$api->post('/{restaurant_id}/rate', 'App\Http\Controllers\Api\RestaurantsAPIController@rate');
});
$api->group(['prefix'=>'menu','middleware'=>['jwt.auth','RoleAndLang','uniqueToken',]], function (Router $api){
$api->get('/', 'App\Http\Controllers\Api\MenuAPIController@index');
$api->get('/{id}', 'App\Http\Controllers\Api\MenuAPIController@show')->where(['id'=>'^[0-9]+$']);
});
$api->group(['prefix'=>'popular','middleware'=>['jwt.auth','RoleAndLang','uniqueToken',]], function (Router $api){
$api->get('/', 'App\Http\Controllers\Api\PopularAPIController@index'); // get all popular ITEMS
$api->get('/{id}', 'App\Http\Controllers\Api\MenuAPIController@show')->where(['id'=>'^[0-9]+$']);
});
$api->group(['prefix'=>'favorites','middleware'=>['jwt.auth','RoleAndLang','uniqueToken',]], function (Router $api){
$api->get('/', 'App\Http\Controllers\Api\FavoritesAPIController@index');
$api->get('/{id}', 'App\Http\Controllers\Api\FavoritesAPIController@show')->where(['id'=>'^[0-9]+$']);
$api->post('/{id}', 'App\Http\Controllers\Api\FavoritesAPIController@store')->where(['id'=>'^[0-9]+$']);
$api->delete('/{id}', 'App\Http\Controllers\Api\FavoritesAPIController@destroy')->where(['id'=>'^[0-9]+$']);
});
$api->group(['prefix'=>'categories','middleware'=>['jwt.auth','RoleAndLang','uniqueToken',]], function (Router $api){
$api->get('/', 'App\Http\Controllers\Api\CategoriesAPIController@index');
$api->post('/{id}/favorites', 'App\Http\Controllers\Api\FavoriteCategoriesAPIController@store')->where(['id'=>'^[0-9]+$']);
$api->get('/{id}', 'App\Http\Controllers\Api\CategoriesAPIController@show')->where(['id'=>'^[0-9]+$']);
$api->get('/favorites', 'App\Http\Controllers\Api\FavoriteCategoriesAPIController@show');
});
$api->group(['prefix'=>'user','middleware'=>['jwt.auth','RoleAndLang','uniqueToken',]], function (Router $api){
$api->get('/', 'App\Http\Controllers\Api\UserAPIController@index');
$api->put('/', 'App\Http\Controllers\Api\UserAPIController@update');
$api->post('/update_avatar', 'App\Http\Controllers\Api\UserAPIController@update_avatar');
$api->put('bonus', 'App\Http\Controllers\Api\UserAPIController@bonus');
$api->post('/push', 'App\Http\Controllers\Api\UserAPIController@push');
$api->post('/regenerate', 'App\Http\Controllers\Api\UserAPIController@regenerate');
});
$api->get('home', function (){
return \App\Helpers\HomeHelper::getHome();
})->middleware(['jwt.auth','RoleAndLang','uniqueToken',]);
$api->get('news', function (){
return Response::json(\Backpack\NewsCRUD\app\Models\Article::orderBy('id', 'desc')->take(10)->get());
})->middleware(['jwt.auth','RoleAndLang','uniqueToken',]);
$api->get('news/{id}', function ($id){
return Response::json(\Backpack\NewsCRUD\app\Models\Article::where('id', $id)->get());
})->middleware(['jwt.auth','RoleAndLang','uniqueToken',]);
//$api->post('/city', 'App\Http\Controllers\Api\CityAPIController@index');
$api->get('config', 'App\Http\Controllers\Api\BonusConfigAPIController@index')->middleware(['jwt.auth','RoleAndLang','uniqueToken',]);
$api->post('/city', 'App\Http\Controllers\Api\CityAPIController@city')->middleware(['jwt.auth','RoleAndLang','uniqueToken',]);
$api->get('/city', 'App\Http\Controllers\Api\CityAPIController@index')->middleware(['jwt.auth','RoleAndLang','uniqueToken',]);
/*
$api->get('/export', 'App\Http\Controllers\ExportController@index');
$api->get('/export/dds', 'App\Http\Controllers\ExportController@dds');
$api->get('/export/cities', 'App\Http\Controllers\ExportController@cities');
$api->get('/export/areas', 'App\Http\Controllers\ExportController@areas');
$api->get('/export/regions', 'App\Http\Controllers\ExportController@regions');
$api->get('/export/types', 'App\Http\Controllers\ExportController@types');
$api->get('/export/pos', 'App\Http\Controllers\ExportController@insertPos');
$api->get('/export/relate', 'App\Http\Controllers\ExportController@relatePos');
$api->get('/export/newxls', 'App\Http\Controllers\ExportController@newxls');
$api->get('/export/xls2', 'App\Http\Controllers\ExportController@xls2');
$api->get('/export/geo', 'App\Http\Controllers\ExportController@geo');
$api->get('/export/restaurants', 'App\Http\Controllers\ExportController@restaurants');
$api->get('/export/food', 'App\Http\Controllers\ExportController@food');
$api->get('/export/assortment', 'App\Http\Controllers\ExportController@assortment');
$api->get('/export/discountcards', 'App\Http\Controllers\ExportController@discountcards');
*/
});
<file_sep>/database/migrations/2017_12_06_124310_push_messages_translate.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class PushMessagesTranslate extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('push_notification_messages', function ($table) {
$table->dropColumn('text');
});
Schema::table('push_notification_messages', function ($table) {
$table->json('text');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('push_notification_messages', function ($table) {
$table->dropColumn('text');
});
Schema::table('push_notification_messages', function ($table) {
$table->text('text')->nullable();
});
}
}
<file_sep>/resources/lang/vendor/backpack/ru/categories.php
<?php
return [
'singular' => 'категория меню',
'plural' => 'категории меню',
'title' => 'Название',
'image' => 'Фото категории',
//'' => '',
];
<file_sep>/database/migrations/2017_12_12_193327_bonuses_changes.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class BonusesChanges extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$removeConfig = ['birthday_gift', 'bonus_double_days', ''];
$renameConfig = [
'bonus_orange_cost' => 'bonus_orange_drink_cost',
'bonus_blue_cost' => 'bonus_blue_drink_cost',
'birthday_gift_term' => 'birthday_gift_from',
'birthday_gift_mention' => 'birthday_gift_to'
];
Schema::table('bonuses_config', function ($table) use ($removeConfig, $renameConfig) {
$sql = 'UPDATE `bonuses_config` SET `title`=LOWER(`title`)';
DB::connection()->getPdo()->exec($sql);
foreach ($removeConfig as $title) {
$sql = 'DELETE FROM `bonuses_config` WHERE `title`=\'' . $title . '\'';
DB::connection()->getPdo()->exec($sql);
}
foreach ($renameConfig as $oldTitle => $newTitle) {
$sql = 'UPDATE `bonuses_config` SET `title`=\'' . $newTitle . '\' WHERE `title`=\'' . $oldTitle . '\'';
DB::connection()->getPdo()->exec($sql);
}
});
Schema::table('menu', function ($table) {
$table->boolean('calculate_bonus')->default(true)->after('id');
});
Schema::create('koef_bonus_schedule', function (Blueprint $table) {
$table->increments('id');
$table->boolean('all');
$table->integer('role_id')->nullable();
$table->decimal('koef', 4, 1);
$table->date('start_at');
$table->date('end_at');
$table->timestamps();
});
Schema::create('menu_bonus_schedule', function (Blueprint $table) {
$table->increments('id');
$table->boolean('all');
$table->integer('menu_id');
$table->integer('geo_city_id')->nullable();
$table->integer('bonus');
$table->date('start_at');
$table->date('end_at');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/database/migrations/2018_01_03_144536_add_restaurant_search_view.php
<?php
use App\Models\Restaurants;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
class AddRestaurantSearchView extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::statement("
ALTER TABLE `restaurants` ADD
`search` LONGTEXT
GENERATED ALWAYS AS (
CONCAT(
JSON_UNQUOTE(
IFNULL(JSON_EXTRACT(
`restaurants`.`address`,
'$.ru'
), '')
),
' ',
JSON_UNQUOTE(
IFNULL(JSON_EXTRACT(
`restaurants`.`address`,
'$.uk'
), '')
),
' ',
JSON_UNQUOTE(
IFNULL(JSON_EXTRACT(
`restaurants`.`address`,
'$.en'
), '')
),
' ',
JSON_UNQUOTE(
IFNULL(JSON_EXTRACT(
`restaurants`.`keywords`,
'$.ru'
), '')
),
' ',
JSON_UNQUOTE(
IFNULL(JSON_EXTRACT(
`restaurants`.`keywords`,
'$.uk'
), '')
),
' ',
JSON_UNQUOTE(
IFNULL(JSON_EXTRACT(
`restaurants`.`keywords`,
'$.en'
), '')
)
)
) STORED
");
DB::statement('ALTER TABLE `restaurants` ADD FULLTEXT `search`(`search`)');
$locales = ['ru', 'uk', 'en'];
foreach (Restaurants::all() as $item) {
foreach ($locales as $locale) {
$keywords = $item->getTranslation('keywords', $locale);
$city = $item->geo_city->getTranslation('title', $locale);
$keywords = trim($city . ' ' . $keywords);
$item->setTranslation('keywords', $locale, $keywords);
}
$item->save();
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/resources/lang/vendor/backpack/en/categories.php
<?php
return [
'singular' => 'Menu Category',
'plural' => 'Menu Categories',
'title' => 'Title',
'image' => 'Category Photo',
//'' => '',
];
<file_sep>/database/seeds/FillCategories.php
<?php
/**
* Created by PhpStorm.
* User: dev
* Date: 31-Oct-17
* Time: 11:22 AM
*/
class FillCategories extends \Illuminate\Database\Seeder
{
public function run(){
$data = [
'Классический кофе',
'HOT Меню',
'Авторские кофейные напитки',
'Десерты',
'Горячие чаи',
'Выпечка & Сэндвичи',
'Круассаны с начинками',
'Салаты & Супы',
'Весовой кофе',
];
foreach($data as $point){
$model = new \App\Models\MenuCategories();
$model->title = $point;
$model->description = "test data";
$model->save();
}
}
}<file_sep>/features/bootstrap/LongContext.php
<?php
/**
* Created by PhpStorm.
* User: dev
* Date: 25-Oct-17
* Time: 8:10 AM
*/
class LongContext extends RestApiCo
{
}<file_sep>/routes/backpack/base.php
<?php
/**
* Created by PhpStorm.
* User: dev
* Date: 9/13/2017
* Time: 1:07 PM
*/
Route::group(
[
'namespace' => 'Backpack\Base\app\Http\Controllers',
'middleware' => ['web','RoleAndLang'],
'prefix' => config('backpack.base.route_prefix'),
],
function () {
// if not otherwise configured, setup the auth routes
if (config('backpack.base.setup_auth_routes')) {
/**/
// Authentication Routes...
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');
/**/
Route::get('logout', 'Auth\LoginController@logout');
}
}
);
Route::group(
[
'namespace' => 'Backpack\Base\app\Http\Controllers',
'middleware' => ['web','RoleAndLang', 'adminRole'],
'prefix' => config('backpack.base.route_prefix'),
],
function () {
// if not otherwise configured, setup the dashboard routes
if (config('backpack.base.setup_dashboard_routes')) {
Route::get('dashboard', 'AdminController@dashboard');
Route::get('/', 'AdminController@redirect');
}
}
);<file_sep>/database/migrations/2017_11_24_073814_create_tables_region_cities.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTablesRegionCities extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('geo_areas', function (Blueprint $table) {
$table->increments('id');
$table->string('group', 50);
$table->string('ref', 50);
$table->string('title_ru',50);
$table->string('title_ua', 50);
$table->string('title_en', 50);
$table->timestamps();
});
Schema::create('geo_cities', function (Blueprint $table) {
$table->increments('id');
$table->string('area',50);
$table->string('region',50);
$table->string('type',50);
$table->string('title_ru',50);
$table->string('title_ua', 50);
$table->string('title_en', 50);
$table->float('lat');
$table->string('lng');
$table->integer('center');
$table->integer('koatuu');
$table->integer('index1');
$table->integer('index2');
$table->timestamps();
});
Schema::create('geo_regions', function (Blueprint $table) {
$table->increments('id');
$table->string('ref', 50);
$table->string('title_ru',50);
$table->string('title_ua', 50);
$table->string('title_en', 50);
$table->timestamps();
});
Schema::create('geo_types', function (Blueprint $table) {
$table->increments('id');
$table->string('ref', 50);
$table->string('title_ru',50);
$table->string('title_ua', 50);
$table->string('title_en', 50);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/resources/lang/vendor/backpack/en/base.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Backpack\Base Language Lines
|--------------------------------------------------------------------------
*/
'bonus_gifts'=>'Gifts',
'map_title'=>'Cafe locations',
'other'=>'Other',
'crud'=>'Create / Edit',
'statistics'=>'Statistics',
'bonus_program'=>'Bonus programs',
'bonus_settings'=>'Bonus config',
'Sale'=>'Sale',
'sale'=>'Sale',
'cities'=>'Cities',
'popular'=>'Offer of the week',
'categories'=>'Categories',
'restaurants'=>'Cafe',
'menu'=>'Menu',
'users'=>'Users',
'registration_closed' => 'Registration is closed.',
'first_page_you_see' => 'The first page you see after login',
'login_status' => 'Login status',
'logged_in' => 'You are logged in!',
'toggle_navigation' => 'Toggle navigation',
'administration' => 'ADMINISTRATION',
'user' => 'USER',
'logout' => 'Logout',
'login' => 'Login',
'register' => 'Register',
'name' => 'Name',
'email_address' => 'E-Mail Address',
'password' => '<PASSWORD>',
'confirm_password' => '<PASSWORD>',
'remember_me' => 'Remember Me',
'forgot_your_password' => 'Forgot Your Password?',
'reset_password' => '<PASSWORD>',
'send_reset_link' => 'Send Password Reset Link',
'click_here_to_reset' => 'Click here to reset your password',
'unauthorized' => 'Unauthorized.',
'dashboard' => 'Dashboard',
'handcrafted_by' => 'Handcrafted by',
'powered_by' => 'Powered by',
'push_notifications' => 'Push Notifications',
'push_notification_templates' => 'Templates',
'push_notification_messages' => 'Messages',
'push_notification_schedule' => 'Schedule',
'push_notification_logs' => 'History',
'sms' => 'Sms',
'sms_messages' => 'Messages',
'sms_schedules' => 'Schedule',
'sms_logs' => 'History',
'user_settings' => 'User Settings',
'groups' => 'Groups',
'roles' => 'Roles',
'news' => 'News',
'articles' => 'Articles',
'tags' => 'Tags',
'settings' => 'Settings',
'costs' => 'Menu Costs',
'pos' => 'POS Terminals',
'percentgroups' => 'Sale Groups',
'menubonusschedule' => 'Menu Bonuses',
'koefbonusschedule' => 'Bonus Koef',
'nomenklatura' => '1C Products List',
'access_denied' => 'Access Denied',
'aroma_gifts_title' => 'Aroma Gifts'
];
<file_sep>/database/migrations/2017_11_06_063651_alter_menu_add_medium_big_costs.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterMenuAddMediumBigCosts extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('menu', function (Blueprint $table){
$table->float('medium',6,2)->default('0.00')->after('cost');
$table->float('large',6,2)->default('0.00')->after('medium');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/resources/lang/en/json.php
<?php
/**
* Created by PhpStorm.
* User: dev
* Date: 09-Nov-17
* Time: 11:17 AM
*/
return [
'City_not_found' => 'City not found',
'already_voted' => 'You are already voted by this coffeeshop',
'no_voting_transactions' => 'You do not have transaction for voting',
'User_not_found' => 'User not found',
'Incorrect_reset_link' => 'Incorrect reset link',
'Access_denied' => 'Access denied',
'Something_went_wrong' => 'Something went wrong',
'Password_changed' => '<PASSWORD>',
'Token_invalid' => 'Please login',
'Sms_code_invalid' => 'SMS code invalid',
'User_already_exists' => 'User already exists',
'User_register_error' => 'User register error',
'Categories not found' => 'Categories not found',
'Favorite_Restaurants_not_found' => 'Favorite Coffeeshop not found',
'Favorites_not_found' => 'Favorites products not found',
'Menu_not_found' => 'Menu not found',
'Menu_deleted_successfully' => 'Menu deleted successfully',
'Can_t_store_image' => 'Can\'t store image',
'User_deleted_successfully' => 'User deleted successfully',
'User_retrieved_successfully' => 'User retrieved successfully',
'User_saved_successfully' => 'User saved successfully',
'Favorite_Restaurants_saved_successfully' => 'Favorite Coffeeshop saved successfully',
'Phone_number_already_registered_in_our_system' => 'Phone number already registered in our system',
'Operator_not_allowed' => 'Operator not allowed',
'user_is_not_activated' => 'User is not activated',
'user_is_blocked' => 'User is blocked. Write to <EMAIL>',
'Entered_sms_code_invalid' => 'Invalid SMS code',
'error_adding_to_favorites' => 'Error adding to favorites',
'Popular_not_found' => 'Offer of the week not found',
'Restaurant_not_found' => 'Coffeeshop not found',
'Restaurants_not_found' => 'Coffeeshops not found',
'Favirite_ID_didn\'t_found' => 'Favorites Coffeeshops not found',
'Old_password_incorrect' => '<PASSWORD>',
'Token_expired' => 'Expired token',
'cant_change_bonus_type' => 'Can\'t change bonus type. Only once per day',
'sms_code_limit' => 'You can request SMS with the code no more than 3 times per hour',
'authorization_code' => 'Your authorization code: :code',
'email_is_taken' => 'This e-mail is already taken',
'wrong_credentials' => '<PASSWORD>',
'too_many_login_requests' => 'The number of attempts to enter the password is spent. Recover your password via SMS'
];<file_sep>/database/migrations/2018_01_12_164155_add_date_fields_to_newsletters.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddDateFieldsToNewsletters extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('push_notification_schedule', function(Blueprint $table) {
$table->datetime('send_at');
$table->boolean('sent')->default(false)->after('send_now');
$table->dropColumn(['cron', 'send_now']);
});
Schema::table('sms_schedules', function(Blueprint $table) {
$table->datetime('send_at');
$table->boolean('sent')->default(false)->after('send_now');
$table->dropColumn(['cron', 'send_now']);
});
$sql = 'UPDATE `push_notification_schedule` SET `sent`=1,`send_at`=\'2017-12-12 12:12:12\'';
DB::connection()->getPdo()->exec($sql);
$sql = 'UPDATE `sms_schedules` SET `sent`=1,`send_at`=\'2017-12-12 12:12:12\'';
DB::connection()->getPdo()->exec($sql);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/database/migrations/2018_01_15_100241_create_table_queue_files.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableQueueFiles extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (Schema::hasTable('queue_files')) return;
Schema::create('queue_files', function (Blueprint $table) {
$table->increments('id');
$table->string('file', 255);
$table->boolean('used')->default(false);
$table->integer('total_rows')->default(0);
$table->integer('process')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/resources/lang/ru/json.php
<?php
/**
* Created by PhpStorm.
* User: dev
* Date: 09-Nov-17
* Time: 11:17 AM
*/
return [
'City_not_found' => 'Город не найден',
'already_voted' => 'Вы уже оценивали эту кофейню',
'no_voting_transactions' => 'Вы не можете оценить эту кофейню',
'User_not_found' => 'Пользователь не найден',
'Incorrect_reset_link' => 'Неверный токен для сброса пароля',
'Access_denied' => 'Доступ запрещен',
'Something_went_wrong' => 'Что-то с авторизацией пошло не так, попробуйте повторить позже',
'Password_changed' => '<PASSWORD>',
'Token_invalid' => '<PASSWORD>',
'Sms_code_invalid' => 'Неверный код SMS',
'User_already_exists' => 'Пользователь уже существует',
'User_register_error' => 'Ошибка создания пользователя, проверьте правильность введенных данных',
'Categories not found' => 'Категория не найдена',
'Favorite_Restaurants_not_found' => 'Кофейня не найдена в избранном',
'Favorites_not_found' => 'У вас отсутствуют избранные товары',
'Menu_not_found' => 'Товары отсутствуют',
'Menu_deleted_successfully' => 'Товар удален',
'Can_t_store_image' => 'Неудалось сохранить аватар',
'User_deleted_successfully' => 'Пользователь удален',
'User_retrieved_successfully' => 'Пользователь успешно передан',
'User_saved_successfully' => 'Данные пользователя сохранены',
'Favorite_Restaurants_saved_successfully' => 'Кофейня успешно добавлена в избранное',
'Phone_number_already_registered_in_our_system' => 'Введенный телефон уже зарегистрирован в системе',
'Operator_not_allowed' => 'Неверный оператор',
'user_is_not_activated' => 'Пользователь не активирован',
'user_is_blocked' => 'Пользователь заблокирован. Обратитесь по адресу <EMAIL>',
'Entered_sms_code_invalid' => 'Неверный код SMS',
'error_adding_to_favorites' => 'Ошибка добавления в избранное',
'Popular_not_found' => 'Предложение недели не найдено',
'Restaurant_not_found' => 'Кофейня не найдена',
'Restaurants_not_found' => 'Кофейни не найдены',
'Favirite_ID_didn\'t_found' => 'Избранные кофейни не найдены',
'Old_password_incorrect' => 'Старый пароль указан неверно',
'Token_expired' => 'Истек срок действия токена',
'cant_change_bonus_type' => 'Бонусную программу можно менять не чаще раза в день',
'sms_code_limit' => 'Вы можете запрашивать SMS с кодом не чаще 3-х раз в час',
'authorization_code' => 'Ваш код авторизации: :code',
'email_is_taken' => 'Такой e-mail уже занят',
'wrong_credentials' => 'Пароль указан неверно',
'too_many_login_requests' => 'Количество попыток ввода пароля исчерпано. Восстановите пароль через SMS'
];<file_sep>/database/migrations/2017_12_11_131202_create_table_user_level.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableUserLevel extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (Schema::hasTable('user_bonuses')) return;
Schema::create('user_bonuses', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('bonus')->default(0);
$table->integer('bonus_type')->default(0);
$table->integer('level_date');
$table->enum('user_level', [ 'blue','orange']);
$table->integer('percent_group');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/database/migrations/2017_12_11_122042_add_photos_to_restaurant.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddPhotosToRestaurant extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::drop('restaurants_images');
Schema::table('restaurants', function ($table) {
$table->json('gallery');
});
$sql = 'UPDATE `restaurants` SET `gallery`=\'[]\'';
DB::connection()->getPdo()->exec($sql);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
|
96c38b8820848e54ef462a01a509a3a399ccea52
|
[
"Markdown",
"PHP"
] | 39 |
PHP
|
censore/EX-2
|
f3c4cba3e8f41f1ee393c25dc0cec407350bce71
|
6bab8f0d560f9b9fb09e97b250da18bb82e075ec
|
refs/heads/master
|
<repo_name>kazuhirosaji/nlp100<file_sep>/04/31_verb.py
# 31. 動詞
# 動詞の表層形をすべて抽出せよ.
import analyze as gal
list = gal.get_analyzed_list()
verbs = []
for res in list:
if (res['pos'] == '動詞'):
verbs.append(res['surface'])
print(verbs)<file_sep>/02/11_tab.py
# 11. タブをスペースに置換
# タブ1文字につきスペース1文字に置換せよ.確認にはsedコマンド,trコマンド,もしくはexpandコマンドを用いよ.
import sys
f = open('hightemp.txt', 'r')
for line in f:
sys.stdout.write(line.replace('\t', ' '))
<file_sep>/01/08_code.py
# 08. 暗号文
# 与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.
# 英小文字ならば(219 - 文字コード)の文字に置換
# その他の文字はそのまま出力
# この関数を用い,英語のメッセージを暗号化・復号化せよ.
def cipher(msg, encrypt = True):
code = ''
for s in msg:
if (s.isalpha() and s.islower()):
if (encrypt):
code += chr(219 - ord(s))
else:
code += s
return code
enc = cipher('I have an apple.')
dec = cipher(enc)
print(enc)
print(dec)
<file_sep>/03/25_get_template.py
# 25. テンプレートの抽出
# 記事中に含まれる「基礎情報」テンプレートのフィールド名と値を抽出し,辞書オブジェクトとして格納せよ
import nlp_json
import re
import regex
r = nlp_json.read_wikipedia()
# "{{基礎情報 ... }"の文字列の貪欲マッチ
list = re.findall('\{基礎情報[\s\S]*}', r['revisions'][0]['*'])
# {{基礎情報..}}の抽出のため、入れ子の括弧を正規表現で処理
# http://blog.ni-ken.net/2015/04/python-regex-tips/ 参照
pattern = r"(?<match>\{(?:[^{}]+|(?&match))*\})"
base_info = regex.search(pattern, list[0], flags=regex.VERBOSE).group('match')
# 辞書オブジェクトを作成
ans = {}
for fields in base_info.split('\n|'):
f = fields.split(' = ')
if len(f) > 1:
ans[f[0]] = f[1]
# 出力
for key, val in ans.items():
print(key + ': ' + val)
<file_sep>/03/21_category.py
# 21. カテゴリ名を含む行を抽出
# 記事中でカテゴリ名を宣言している行を抽出せよ.
import nlp_json
import re
r = nlp_json.read_wikipedia()
# 文字列から[[Category:~]]を探す
list = re.findall('\[\[Category:.*\]\]', r['revisions'][0]['*'])
print(list)
<file_sep>/01/06_shugo.py
# 06集合
import ngram as n
x = "paraparaparadise"
y = "paragraph"
x_set = set(n.get_ngram(2, x))
y_set = set(n.get_ngram(2, y))
print(x_set)
print(y_set)
# 和集合
print(x_set.union(y_set))
# 積集合
print(x_set.intersection(y_set))
# X-Y
print(x_set.intersection(y_set))
# Y-X
print(y_set.intersection(x_set))
# seがXに含まれるか
print('se' in x_set)
# seがYに含まれるか
print('se' in y_set)
<file_sep>/01/03_314.py
import re
text = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
regex = r'[a-zA-Z]+'
ans = ""
for word in text.split(" "):
w = re.match(regex, word).group()
ans += str(len(w))
print(ans)<file_sep>/04/33_sahenmeisi.py
# 33. サ変名詞
# サ変接続の名詞をすべて抽出せよ.
import analyze as gal
list = gal.get_analyzed_list()
ans = []
for res in list:
if (res['pos'] == '名詞' and res['pos1'] == 'サ変接続'):
ans.append(res)
print(ans)
<file_sep>/01/02_pato_taku.py
patoka = 'パトカー'
taku = 'タクシー'
patatoku = ''
for i in range(len(patoka)):
patatoku += patoka[i] + taku[i]
print(patatoku)<file_sep>/01/05_ngram.py
def get_ngram(n, s):
words = []
s = s.replace(' ', '')
for key, val in enumerate(s):
words.append(s[key:key+n])
return words
def get_ngram_word(n, s):
words = s.split(' ')
for key, val in enumerate(words):
words.append((' '.join(words[key:key+n])))
return words
<file_sep>/02/16_split.py
# 16. ファイルをN分割する
# 自然数Nをコマンドライン引数などの手段で受け取り,入力のファイルを行単位でN分割せよ.同様の処理をsplitコマンドで実現せよ.
import sys
import math
n = int(sys.argv[1])
with open('hightemp.txt') as f:
lines = f.readlines()
for key, line in enumerate(lines):
if (key % n == 0):
if (key != 0):
out.close()
out = open('split_' + str(math.floor(key / n)) + '.txt', 'w')
out.write(line)
<file_sep>/01/09_typoglycemia.py
# 09. Typoglycemia
# スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,
# それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.
# ただし,長さが4以下の単語は並び替えないこととする.
# 適当な英語の文(例えば"I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .")を与え,
# その実行結果を確認せよ.
import random
def typoglycemia(sentence):
res = ''
for word in sentence.split():
if (len(res) > 0):
res += ' '
new_word = ''
if (len(word) > 4):
# 並び替え順を決定
rep_list = list(range(1, len(word) - 1))
random.shuffle(rep_list)
# 先頭と最後尾はそのままにする
rep_list.insert(0, 0)
rep_list.append(len(word) - 1)
for key, str in enumerate(word):
new_word += word[rep_list[key]]
else:
new_word = word
res += new_word
return res
sentence = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."
res = typoglycemia(sentence)
print(sentence)
print(res)<file_sep>/03/24_media.py
# 24. ファイル参照の抽出
# 記事から参照されているメディアファイルをすべて抜き出せ.
import nlp_json
import re
r = nlp_json.read_wikipedia()
# 文字列から[[Category:~]]を探す
list = re.findall('File\:.*?\|', r['revisions'][0]['*'])
# print(list)
# 余分な文字を削除
ans = []
for matched in list:
ans.append(matched.replace('|', ''))
print(ans)<file_sep>/01/07_template.py
# 07テンプレート
# 引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.さらに,x=12, y="気温", z=22.4として,実行結果を確認せよ.
def template(x, y, z):
return str(x) + '時の' + str(y) + 'は' + str(z)
print(template(12, '気温', 22.4))
<file_sep>/03/23_section.py
# 23. セクション構造
# 記事中に含まれるセクション名とそのレベル(例えば"== セクション名 =="なら1)を表示せよ.
import nlp_json
import re
r = nlp_json.read_wikipedia()
# 文字列から[[Category:~]]を探す
list = re.findall('\==.*\==', r['revisions'][0]['*'])
print(list)
# 余分な文字を削除
ans = []
for matched in list:
level = matched.count('=') / 2 - 1
ans.append([matched.replace('=', ''), int(level)])
print(ans)<file_sep>/04/create_neko.py
import sys
import MeCab
m = MeCab.Tagger ("SNOW")
fin = open('neko.txt', 'r') # 解析対象のファイルを開く
fout = open('neko.txt.mecab', 'w') # 解析結果を書き出すファイルを開く
fout.write(m.parse(fin.read())) # 読み込んで解析して書き出し
fin.close() # ファイルを閉じる
fout.close()<file_sep>/03/22_category.py
# 22. カテゴリ名の抽出
# 記事のカテゴリ名を(行単位ではなく名前で)抽出せよ.
import nlp_json
import re
r = nlp_json.read_wikipedia()
# 文字列から[[Category:~]]を探す
list = re.findall('\[\[Category:.*\]\]', r['revisions'][0]['*'])
# 余分な文字を削除
ans = []
for matched in list:
matched = re.sub('Category:', "", matched)
matched = re.sub('[\[\]\|\*]', "", matched)
ans.append(matched)
print(ans)<file_sep>/01/04_genso.py
text = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
one_str_index = [1, 5, 6, 7, 8, 9, 15, 16, 19]
ans = {}
for key, val in enumerate(text.split(" ")):
key += 1
if (key) in one_str_index:
ans[val[0]] = key
else:
ans[val[0:2]] = key
print(ans)<file_sep>/02/15_tail.py
# 15. 末尾のN行を出力
# 自然数Nをコマンドライン引数などの手段で受け取り,入力のうち末尾のN行だけを表示せよ.確認にはtailコマンドを用いよ.
import sys
n = int(sys.argv[1])
f = open('hightemp.txt').readlines()
tail_n = len(f) - n
for key, line in enumerate(f):
if key < tail_n:
continue
sys.stdout.write(line)<file_sep>/02/10_wc.py
# 10. 行数のカウント
# 行数をカウントせよ.確認にはwcコマンドを用いよ.
count = 0
f = open('hightemp.txt', 'r')
for line in f:
count += 1
print(count)
<file_sep>/04/analyze.py
# 30. 形態素解析結果の読み込み
# 形態素解析結果(neko.txt.mecab)を読み込むプログラムを実装せよ.
# ただし,各形態素は表層形(surface),基本形(base),品詞(pos),
# 品詞細分類1(pos1)をキーとするマッピング型に格納し,
# 1文を形態素(マッピング型)のリストとして表現せよ.第4章の残りの問題では,
# ここで作ったプログラムを活用せよ.
# surface pos,pos1,,,,base
# 吾輩 名詞,代名詞,一般,*,*,*,吾輩,ワガハイ,ワガハイ
import sys
import MeCab
import re
def get_analyzed_list():
m = MeCab.Tagger ("SNOW")
list = []
with open('neko.txt.mecab', 'r') as f:
for line in f:
arr = re.split('[,\t]', line.strip('\n'))
if (len(arr) > 1):
list.append({'surface' : arr[0], 'pos' : arr[1], 'pos1' : arr[2], 'base' : arr[-1]})
# print(list)
return list
<file_sep>/02/17_sort.py
# 17. 1列目の文字列の異なり
# 1列目の文字列の種類(異なる文字列の集合)を求めよ.確認にはsort, uniqコマンドを用いよ.
list = []
with open('hightemp.txt') as f:
for line in f:
list.append(line.split('\t')[0])
uniq = sorted(set(list), key=list.index)
with open('sort_uniq.txt', 'w') as f:
for ken in uniq:
f.write(ken + '\n')
<file_sep>/01/01_patatokukasi.py
str = 'パタトクカシーー'
ans = str[0] + str[2] + str[4] + str[6]
print(ans)<file_sep>/04/32_verb.py
# 32. 動詞の原形
# 動詞の原形をすべて抽出せよ
import analyze as gal
list = gal.get_analyzed_list()
verbs = []
for res in list:
if (res['pos'] == '動詞'):
verbs.append(res['base'])
print(verbs)
<file_sep>/02/19_cut_uniq.py
# 19. 各行の1コラム目の文字列の出現頻度を求め,出現頻度の高い順に並べる
# 各行の1列目の文字列の出現頻度を求め,その高い順に並べて表示せよ.
# 確認にはcut, uniq, sortコマンドを用いよ.
import sys
from collections import Counter
list = []
with open('hightemp.txt') as f:
for line in f:
list.append(line.split('\t')[0])
for key, val in Counter(list).most_common():
print(val, key)
<file_sep>/02/14_head.py
# 14. 先頭からN行を出力
# 自然数Nをコマンドライン引数などの手段で受け取り,入力のうち先頭のN行だけを表示せよ.確認にはheadコマンドを用いよ.
import sys
n = int(sys.argv[1])
f = open('hightemp.txt', 'r')
for key, line in enumerate(f):
if key >= n:
break
sys.stdout.write(line)
<file_sep>/02/13_paste.py
# 13. col1.txtとcol2.txtをマージ
# 12で作ったcol1.txtとcol2.txtを結合し,元のファイルの1列目と2列目をタブ区切りで並べたテキストファイルを作成せよ.確認にはpasteコマンドを用いよ.
import sys
f1 = open('col1.txt', 'r')
f2 = open('col2.txt', 'r')
m = open('13merged.txt', 'w')
for (col1, col2) in zip(f1, f2):
m.write(col1.rstrip('\r\n') + '\t' + col2.rstrip('\r\n') + '\n')
<file_sep>/02/12_cut.py
# 12. 1列目をcol1.txtに,2列目をcol2.txtに保存
# 各行の1列目だけを抜き出したものをcol1.txtに,2列目だけを抜き出したものをcol2.txtとしてファイルに保存せよ.確認にはcutコマンドを用いよ.
import sys
f = open('hightemp.txt', 'r')
col1 = open('col1.txt', 'w')
col2 = open('col2.txt', 'w')
for line in f:
words = line.split('\t')
col1.write(words[0] + '\n')
col2.write(words[1] + '\n')
<file_sep>/02/18_sort.py
# 18. 各行を3コラム目の数値の降順にソート
# 各行を3コラム目の数値の逆順で整列せよ(注意: 各行の内容は変更せずに並び替えよ).
# 確認にはsortコマンドを用いよ(この問題はコマンドで実行した時の結果と合わなくてもよい).
import sys
list = []
with open('hightemp.txt') as f:
for line in f:
tmp_list = line.split('\t')
list.append(tmp_list)
list = sorted(list, key=lambda tmp: tmp[2])
with open('sort_tmp.txt', 'w') as f:
for line_list in list:
string = ''
for key, cell in enumerate(line_list):
if (key > 0):
string += '\t'
string += cell;
f.write(string)
# sys.stdout.write(string)
|
76f7f5e28a31e8b43f432b91aa0498cc0ba7b671
|
[
"Python"
] | 29 |
Python
|
kazuhirosaji/nlp100
|
b0990a73af246196e04b5a61ed2ec1a975b8871b
|
73a65961c07132b6e08bcfa0fe18c912d3d1ced4
|
refs/heads/master
|
<file_sep>import Vue from 'vue'
import Router from 'vue-router'
const Home = () => import ("../views/home/index")
const Login = () => import ("../views/login/index")
const Search = () => import ("../views/search/index")
const Detail = () => import ("../views/detail/index")
const Edit = () => import ("../views/edit/index")
const History = () => import ("../views/history/index")
const Sort = () => import ("../views/sort/index")
Vue.use(Router)
const router = new Router({
mode: "history",
routes: [
{
path: '/',
name: 'home',
component: Home,
meta:{
title:"加班/休假"
}
},
{
path:"/login",
name:"login",
component:Login,
meta:{
title:"登陆"
}
},
{
path:"/search",
name:"search",
component:Search,
meta:{
title:"搜索"
}
},
{
path:"/detail/:type/:id",
name:"detail",
component:Detail,
props:true,
meta:{
title:"详情"
}
},
{
path:"/edit/:type",
name:"edit",
component:Edit,
props:true,
meta:{
title:"编辑"
}
},
{
path:"/history/:id",
name:"history",
component:History,
props:true,
meta:{
title:"审批"
}
},
{
path:"/sort",
name:"sort",
component:Sort,
props:true,
meta:{
title:"排序"
}
}
]
})
export default router
router.beforeEach((to, from, next) => {
document.title=to.meta.title
next()
})<file_sep>class Files{
constructor(files,options){
this.size=files.size
this.type=files.type.match(/\/(\w+)$/i)[1]
this.options=options
}
isType(){
let {type}=this.options
return type.includes(this.type)
}
isSize(){
let {size}=this.options
return (size*1024*1024)>this.size
}
}
export default Files<file_sep>import request from "../utils/js/request"
export default{
// 登陆验证
isLogin:(data)=>request.get("/api/user/info",data),
// 获取列表数据
getList:(data)=>request.get("/api/task/list",data),
// 登陆接口
userLogin:(data)=>request.post("/api/login",data),
// 获取加班详情数据
overtimeDetail:(data)=>request.get("/api/apply/overtime",data),
// 获取调休详情数据
vacationDetail:(data)=>request.get("/api/apply/vacation",data),
// 获取文件数据
getFile:(file)=>request.post("/api/upload",file),
// 提交加班申请
submitovertime:(data)=>request.post("/api/apply/overtime",data),
// 提交休假申请
submitvacation:(data)=>request.post("/api/apply/vacation",data),
// 审批接口
historySubmit:(data)=>request.get("/api/task/history",data)
}<file_sep>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from "./store/index"
import "./utils/js/flexble.js"
import { DatePicker, TimePicker } from "element-ui"
Vue.config.productionTip = false
import Header from "./components/header"
import alert from "./components/alert/index"
Vue.use(DatePicker)
Vue.use(TimePicker)
Vue.component("Header", Header)
let alertClass = Vue.extend(alert)
Vue.prototype.$alert = (text) => {
let alertComponent = new alertClass({
propsData: {
text
}
})
alertComponent.$mount()
document.body.appendChild(alertComponent.$el)
}
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
|
cac04319f7e556522b6e956a33dca02389ba8062
|
[
"JavaScript"
] | 4 |
JavaScript
|
zhf0314/Starbucks
|
0a34a6c5dd027a7cd1ba73880eb33fc9db76cfd5
|
5234d2cc52cf2641e13f561b94a0d4814055e6b1
|
refs/heads/main
|
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
function Toolbar(props) {
const { filters, selected } = props;
const onClick = (filter) => props.onSelectFilter(filter);
return (
<div className='toolbar'>
{
filters.map((o) =>
<div className={'filter' + ((o === selected) ? ' selected' : '')} key={o} onClick={() => onClick(o)}>{o}</div>
)
}
</div>
);
}
export default Toolbar;
Toolbar.propTypes = {
filters: PropTypes.array.isRequired,
selected: PropTypes.string.isRequired,
onSelectFilter: PropTypes.func.isRequired,
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types'
import uniqid from 'uniqid';
function ProjectList(props) {
const { projects } = props;
return (
<div className='project-list'>
{projects.map((o) => <img className='card' src={o.img} alt='' key={uniqid()}/>)}
</div>
);
}
export default ProjectList;
ProjectList.propTypes = {
projects: PropTypes.array.isRequired,
}
<file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ProjectList from './ProjectList';
import Toolbar from './Toolbar';
export class Portfolio extends Component {
constructor(props) {
super(props);
this.filters = props.filters;
this.projects = props.projects;
this.state = {
selected: "All",
};
}
static propTypes = {
filters: PropTypes.array.isRequired,
projects: PropTypes.array.isRequired,
}
onSelectFilter = (filter) => {
this.setState({ selected: filter });
}
render() {
return (
<div className='portfolio'>
<Toolbar filters={this.filters} selected={this.state.selected} onSelectFilter={this.onSelectFilter}/>
<ProjectList projects={this.state.selected === 'All' ? this.projects : this.projects.filter((o) => o.category === this.state.selected)}/>
</div>
)
}
}
export default Portfolio
|
800d97e60e53adf6635feb0055696d44fad4adfc
|
[
"JavaScript"
] | 3 |
JavaScript
|
DravenRedgrave/Filter
|
ab71e3c7d7a0e073536a210b99db7beb1ae1a033
|
966b8d53e7a579a0150e91b2ae917148502090d4
|
refs/heads/master
|
<file_sep>var menuState = {
preload: function() {
this.numberOfBlocks = 0;
this.maxBlocks = 0;
this.blockSource = [];
this.blockDest = [];
this.currentBlock = null;
for (i = 0; i < game.height / 32; i++) {
this.blockSource.push({
x: 0,
y: 0 - 32
});
this.blockDest.push({
x: 0,
y: game.height - (i + 1) * 32
});
this.maxBlocks++;
}
for (i = 1; i < game.width / 32 - 1; i++) {
this.blockSource.push({
x: i * 32,
y: 0 - 32
});
this.blockDest.push({
x: i * 32,
y: game.height - 32
});
this.maxBlocks++;
this.blockSource.push({
x: i * 32,
y: 0 - 32
});
this.blockDest.push({
x: i * 32,
y: 0
});
this.maxBlocks++;
}
for (i = 0; i < game.height / 32; i++) {
this.blockSource.push({
x: game.width - 32,
y: 0 - 32
});
this.blockDest.push({
x: game.width - 32,
y: game.height - (i + 1) * 32
});
this.maxBlocks++;
}
},
createTitleText: function() {
var title = game.add.image(game.width/2, game.height / 6, 'colors_logo');
title.anchor.x = 0.5;
title.anchor.y = 0;
title.scale.x = 0.5;
title.scale.y = 0.5;
var authorLabel = game.add.text(game.width/2, game.height * .40,
'By <NAME>',
FontBuilder.build('24', '#aaa')
);
authorLabel.anchor.setTo(0.5, 0.5);
var highScoreLabel = game.add.text(game.width/2, game.height * .60,
'High Score: ' + HighScore.get(),
FontBuilder.build('32', '#aaa')
);
highScoreLabel.anchor.setTo(0.5, 0.5);
this.tweenTint(highScoreLabel, Phaser.Color.getColor(0,204,204), Phaser.Color.getColor(0,255,255), 2000);
var startLabel = game.add.text(game.width/2, game.height - 100,
'Press the Space Bar to Start!',
FontBuilder.build('25', '#fff')
);
startLabel.anchor.setTo(0.5, 0.5);
game.add.tween(startLabel).to({angle: -1}, 500).to({angle: 1}, 1000).to({angle: 0}, 500).loop().start();
var versionLabel = game.add.text(game.width - 38, game.height - 36,
'Version ' + game.VERSION,
FontBuilder.build('16', '#aaa')
);
versionLabel.anchor.setTo(1, 1);
var spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
spaceKey.onDown.add(this.start, this);
},
tweenTint: function(obj, startColor, endColor, time) {
// create an object to tween with our step value at 0
var colorBlend = { step: 0 };
// create the tween on this object and tween its step property to 100
var colorTween = game.add.tween(colorBlend).to({step: 100}, time).to({step: 0}, time).loop();
// run the interpolateColor function every time the tween updates, feeding it the
// updated value of our tween each time, and set the result as our tint
colorTween.onUpdateCallback(function() {
obj.tint = Phaser.Color.interpolateColor(startColor, endColor, 100, colorBlend.step);
});
// set the object to the start color straight away
obj.tint = startColor;
colorTween.start();
return colorTween;
},
spawnNextBlock: function() {
if (this.numberOfBlocks >= this.maxBlocks) {
return;
}
var i = this.numberOfBlocks;
var source = this.blockSource[i];
var dest = this.blockDest[i];
var sprite = game.add.sprite(source.x, source.y, game.rnd.pick(['aqua_block', 'blue_block', 'green_block', 'purple_block', 'red_block', 'orange_block', 'yellow_block']));
sprite.anchor.setTo(0,0);
sprite.data.dest = dest;
sprite.data.deltaY = 50;
this.currentBlock = sprite;
this.numberOfBlocks++;
},
create: function() {
game.add.image(0, 0, 'menu_background');
game.physics.startSystem(Phaser.Physics.ARCADE);
game.renderer.renderSession.roundPixels = true;
this.spawnNextBlock();
this.createTitleText();
this.music = game.add.audio('intro-music');
this.music.loop = true;
this.music.play();
},
update: function() {
var sprite = this.currentBlock;
if (sprite) {
sprite.y = sprite.y + sprite.data.deltaY;
if (sprite.y > sprite.data.dest.y) {
sprite.y = sprite.data.dest.y;
this.spawnNextBlock();
}
}
},
start: function() {
this.music.stop();
game.state.start('play');
}
}
<file_sep>var FontBuilder = {
build(size, color) {
var font = {};
font.font = size + 'px Exo 2';
font.fill = color;
return font;
}
}
<file_sep># About
Colors is a game that I originally wrote back in 1991 while in college. The original game was written in Turbo Pascal and Assembler.
I started this project to learn how game development was done in Javascript with Phaser.
This turned out to be a fun project, and I hope people have fun with the game and maybe learn a thing or two about Phaser.
## Warning ##
This game is an early work-in-progress!
I will try to make sure that the code checked into github is working and functional, but I make no promises right now!
# Running the Game
Deploy everything in the src directory to a web server. Have fun.
# Playing the game
*Colors* is a Tetris-like game where colored pieces fall into a pit. Blocks are made of different colors. While the blocks cannot be rotate, the colors inside of the block can be shifted.
Blocks are removed from the board when a match of three or greater blocks of the same color is formed. Block chains can be formed horizontally, vertically, and diagonally.
Once the pit fills up, the game is over.
# Controls
All control is currently by keyboard.
The following keys are used to move a piece:
+ **Left Arrow** - move piece to the Left
+ **Right Arrow** - move the piece to the Right
+ **Down Arrow** - move the piece Down
+ **Up Arrow** - rotate the piece colors upwards
+ **Space** - drop the piece to the bottom
The additional controls are available:
+ **Escape** - pause
# Credits
This game would not be possible without:
+ **[Phaser (Community Edition)](http://example.net/)** - A cool, open-source Javascript game development library.
+ **[SoundImage.org](http://soundimage.org)** - An awesome library of free, royal-free music, sounds effects, and artwork.
+ **[Affinity Designer](https://affinity.serif.com)** - Powerful, yet reasonable-priced, vector and pixel drawing software.
+ **[Google Fonts](https://fonts.google.com)** - Fast, beautiful, open web-based typography.
<file_sep>var loadState = {
preload: function() {
var loadingLabel = game.add.text(game.width/2, 150, 'Loading...',
{ font: '30px Helvetica', fill: '#ffffff' }
);
loadingLabel.anchor.setTo(0.5, 0.5);
var progressBar = game.add.sprite(game.width/2, 200, 'progress_bar');
progressBar.anchor.setTo(0.5, 0.5);
game.load.setPreloadSprite(progressBar);
// Logos
game.load.image('colors_logo', 'assets/colors_logo.png');
// Blocks
game.load.image('aqua_block', 'assets/aqua_block.png');
game.load.image('blue_block', 'assets/blue_block.png');
game.load.image('green_block', 'assets/green_block.png');
game.load.image('purple_block', 'assets/purple_block.png');
game.load.image('red_block', 'assets/red_block.png');
game.load.image('orange_block', 'assets/orange_block.png');
game.load.image('yellow_block', 'assets/yellow_block.png');
game.load.image('aqua2_block', 'assets/aqua2_block.png');
game.load.image('blue2_block', 'assets/blue2_block.png');
game.load.image('green2_block', 'assets/green2_block.png');
game.load.image('purple2_block', 'assets/purple2_block.png');
game.load.image('red2_block', 'assets/red2_block.png');
game.load.image('orange2_block', 'assets/orange2_block.png');
game.load.image('yellow2_block', 'assets/yellow2_block.png');
game.load.image('black_block', 'assets/black_block.png');
game.load.image('rainbow_block', 'assets/rainbow_block.png');
game.load.image('diamond', 'assets/diamond.png');
game.load.image('exploding_block', 'assets/exploding_block.png');
// Particles
game.load.image('red_particle', 'assets/red_particle.png');
game.load.image('orange_particle', 'assets/orange_particle.png');
game.load.image('yellow_particle', 'assets/yellow_particle.png');
// Panels, Backgrounds
game.load.image('menu_background', 'assets/menu_background.png');
game.load.image('game_background', 'assets/game_background.png');
game.load.image('popup_panel', 'assets/panel_640x120.png');
// Marquees
game.load.image('marquee_easy_peasy_title', 'assets/marquee_easy_peasy_title.png');
game.load.image('marquee_easy_peasy_help', 'assets/marquee_easy_peasy_help.png');
game.load.image('marquee_buckle_up_title', 'assets/marquee_buckle_up_title.png');
game.load.image('marquee_beware_title', 'assets/marquee_beware_title.png');
game.load.image('marquee_beware_help', 'assets/marquee_beware_help.png');
game.load.image('marquee_cursed_title', 'assets/marquee_cursed_title.png');
game.load.image('marquee_rainbow_title', 'assets/marquee_rainbow_title.png');
game.load.image('marquee_rainbow_help', 'assets/marquee_rainbow_help.png');
game.load.image('marquee_diamonds_title', 'assets/marquee_diamonds_title.png');
game.load.image('marquee_diamonds_help', 'assets/diamond.png');
// Misc
game.load.image('game_over', 'assets/game_over.png');
// Music
game.load.audio('intro-music', ['assets/Hypnotic-Puzzle.mp3']);
game.load.audio('music', ['assets/Action-Rhythm8.mp3']);
// Sound Effects
},
create: function() {
game.state.start('menu');
},
update: function() {
}
}
<file_sep>var Marquees = {
START: {
title_image_name: 'marquee_easy_peasy_title',
help_text: 'Line up three similar colors in a row to score points!',
help_sub_text: null,
help_image_name: 'marquee_easy_peasy_help',
help_image_scale: 1.0
},
BUCKLE_UP: {
title_image_name: 'marquee_buckle_up_title',
help_text: 'Things are going to get a little faster!',
help_sub_text: null,
help_image_name: null,
help_image_scale: 1.0
},
BEWARE: {
title_image_name: 'marquee_beware_title',
help_text: 'Clearing black blocks will result in a curse!',
help_sub_text: null,
help_image_name: 'marquee_beware_help',
help_image_scale: 1.0
},
RAINBOW: {
title_image_name: 'marquee_rainbow_title',
help_text: 'Rainbow blocks will explode other blocks when dropped',
help_sub_text: '(based on the color upon which it lands)',
help_image_name: 'marquee_rainbow_help',
help_image_scale: 1.0
},
DIAMONDS: {
title_image_name: 'marquee_diamonds_title',
help_text: 'Diamonds are forever!',
help_sub_text: 'Diamonds do not match and clear. But there may be a way to destory them!',
help_image_name: 'marquee_diamonds_help',
help_image_scale: 2
},
CURSED_BOARD_GROW: {
title_image_name: 'marquee_cursed_title',
help_text: 'Watch out! The board will start growing!',
help_sub_text: null,
help_image_name: null,
help_image_scale: 1.0
},
CURSED_COLORS: {
title_image_name: 'marquee_cursed_title',
help_text: 'Cursed colors will begin to appear',
help_sub_text: null,
help_image_name: null,
help_image_scale: 1.0
},
REVERSE_KEYS: {
title_image_name: 'marquee_cursed_title',
help_text: 'Go left... no the other left',
help_sub_text: null,
help_image_name: null,
help_image_scale: 1.0
},
HARDER_MATCHES: {
title_image_name: 'marquee_cursed_title',
help_text: 'Not quite tetris, you must now match 4',
help_sub_text: null,
help_image_name: null,
help_image_scale: 1.0
}
};
<file_sep>var modal = false;
var playState = {
initNewGame: function() {
game.global = {
level: 1,
score: 0,
piecesUntilNextLevel: 20,
totalBlocksCleared: 0,
pieceTimer: null,
collapseTimer: null,
collapseCycle: 0,
newCurse: null,
currentCurse: null,
cursePieceCount: 0,
piecesUntilNextBoardGrowth: 0,
marquee: {
visible: false,
graphics: null
},
showNextPiece: true,
board: new GameBoard(9, 19),
currentPiece: new GamePiece(true),
nextPiece: new GamePiece(false)
}
this.initPieceTimer();
game.global.board.print();
},
initPieceTimer: function() {
if (game.global.pieceTimer) {
game.global.pieceTimer.delay = GameSpeed.getSpeedForLevel(game.global.level);
}
else {
game.global.pieceTimer = game.time.events.loop(GameSpeed.getSpeedForLevel(game.global.level), this.fallPiece, this);
}
},
initKeyboard: function() {
game.input.keyboard.addKey(Phaser.Keyboard.LEFT).onDown.add(this.keyLeft, this);
game.input.keyboard.addKey(Phaser.Keyboard.RIGHT).onDown.add(this.keyRight, this);
game.input.keyboard.addKey(Phaser.Keyboard.UP).onDown.add(this.keyUp, this);
game.input.keyboard.addKey(Phaser.Keyboard.DOWN).onDown.add(this.keyDown, this);
game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR).onDown.add(this.keySpace, this);
game.input.keyboard.addKey(Phaser.Keyboard.TAB).onDown.add(this.keyTab, this);
game.input.keyboard.addKey(Phaser.Keyboard.ESC).onDown.add(this.keyEscape, this);
game.input.keyboard.addKey(Phaser.Keyboard.Q).onDown.add(this.keyQ, this);
game.input.keyboard.addKey(Phaser.Keyboard.T).onDown.add(this.keyT, this);
},
createKeyHelp: function() {
var y = 445;
game.add.text(10, y, 'Keys', FontBuilder.build('22', '#eee'));
y = y + 30;
this.creatKeyHelpLabel(y, 'LEFT', 'Move piece left');
y = y + 20;
this.creatKeyHelpLabel(y, 'RIGHT', 'Move piece right');
y = y + 20;
this.creatKeyHelpLabel(y, 'DOWN', 'Move piece down');
y = y + 20;
this.creatKeyHelpLabel(y, 'UP', 'Rotate colors');
y = y + 20;
this.creatKeyHelpLabel(y, 'SPACE', 'Drop Piece');
y = y + 40;
this.creatKeyHelpLabel(y, 'ESC', 'Pause');
y = y + 20;
this.creatKeyHelpLabel(y, 'Q', 'Quit');
y = y + 20;
},
creatKeyHelpLabel(y, key, message) {
var keyLabel = game.add.text(55, y, key, FontBuilder.build('14', '#aaa'));
keyLabel.anchor.setTo(1.0, 0.0);
var messageLabel = game.add.text(65, y, message, FontBuilder.build('14', '#aaa'));
messageLabel.anchor.setTo(0.0, 0.0);
},
createScoreBox: function() {
console.log("Creating the score box!");
this.scoreLabel = game.add.text(10, 10, '', FontBuilder.build('22', '#eee'));
this.scoreLabel.anchor.setTo(0.0, 0.0);
this.levelLabel = game.add.text(10, 50, '', FontBuilder.build('18', '#ccc'));
this.levelLabel.anchor.setTo(0.0, 0.0);
this.nextLevelLabel = game.add.text(10, 75, '', FontBuilder.build('18', '#ccc'));
this.nextLevelLabel.anchor.setTo(0.0, 0.0);
},
createNextPieceBox: function() {
this.nextPieceLabel = game.add.text(game.width * 5/6, 10, 'Next Piece', FontBuilder.build('22', '#eee'));
this.nextPieceLabel.anchor.setTo(0.5, 0.0);
},
createCurseBox: function() {
this.cursedLabel = game.add.text(game.width * 5/6, 220, 'Cursed!', FontBuilder.build('22', '#eee'));
this.cursedLabel.anchor.setTo(0.5, 0.0);
this.curseDetailsLabel = game.add.text(game.width * 5/6, 250, '', FontBuilder.build('18', '#ccc'));
this.curseDetailsLabel.anchor.setTo(0.5, 0.0);
},
updateScoreBox: function() {
this.scoreLabel.text = 'Score: ' + game.global.score;
this.levelLabel.text = 'Level: ' + game.global.level;
this.nextLevelLabel.text = 'Next Level in ' + game.global.piecesUntilNextLevel + ' Pieces';
},
updateCurseBox: function() {
var curse = game.global.currentCurse;
if (curse) {
this.cursedLabel.visible = true;
this.curseDetailsLabel.visible = true;
this.curseDetailsLabel.text = curse.name;
}
else {
this.cursedLabel.visible = false;
this.curseDetailsLabel.visible = false;
}
},
create: function() {
game.add.image(0, 0, 'game_background');
this.createScoreBox();
this.createNextPieceBox();
this.createCurseBox();
this.createKeyHelp();
this.initNewGame();
this.initKeyboard();
this.music = game.add.audio('music');
this.music.loop = true;
this.music.play();
this.updateScoreBox();
this.updateCurseBox();
this.showMarquee(Marquees.START);
},
showMarquee: function(config) {
m = game.global.marquee;
m.visible = true;
m.graphics = game.add.graphics(0, 0);
m.graphics.beginFill(0x000000, 0.85);
m.graphics.drawRect(0, 0, game.width, game.height);
m.graphics.endFill();
m.title = game.add.image(0 - game.width, game.height * .10, config.title_image_name);
m.title.anchor.x = 0.5;
m.title.anchor.y = 0;
m.titleTween = game.add.tween(m.title).to({x: game.width/2}, 2000).easing(Phaser.Easing.Bounce.Out).start();
m.helpLabel = game.add.text(game.width / 2, game.height * .35, config.help_text, FontBuilder.build('24', '#bbb'));
m.helpLabel.anchor.setTo(0.5, 0.5);
if (config.help_sub_text) {
m.subHelpLabel = game.add.text(game.width / 2, game.height * .40, config.help_sub_text, FontBuilder.build('18', '#bbb'));
m.subHelpLabel.anchor.setTo(0.5, 0.5);
}
m.helpImage = game.add.image(game.width / 2, game.height * .60, config.help_image_name);
m.helpImage.anchor.setTo(0.5, 0.5);
m.helpImage.scale.setTo(config.help_image_scale, config.help_image_scale);
m.helpImage.alpha = 0;
m.helpTween = game.add.tween(m.helpImage).to({alpha: 1.0}, 1000).start();
m.startLabel = game.add.text(game.width / 2, game.height * .90, 'Press the Space Bar to Start!', { font: '32px Exo 2', fill: '#eee' });
m.startLabel.anchor.setTo(0.5, 0.5);
game.paused = true;
game.input.keyboard.reset(true);
game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR).onDown.add(this.hideMarquee, this);
},
pauseUpdate: function() {
var m = game.global.marquee;
if (m && m.visible) {
m.titleTween.update();
m.helpTween.update();
}
var gop = game.global.gameOverPanel;
if (gop) {
if (gop.titleTween) {
gop.titleTween.update();
}
if (gop.scoreTween) {
gop.scoreTween.update();
}
if (gop.highScoreTween) {
gop.highScoreTween.update();
}
}
},
hideMarquee: function() {
var m = game.global.marquee;
m.visible = false;
if (m.title) {
m.title.destroy();
m.title = null;
}
m.titleTween = null;
if (m.helpLabel) {
m.helpLabel.destroy();
m.helpLabel = null;
}
if (m.subHelpLabel) {
m.subHelpLabel.destroy();
m.subHelpLabel = null;
}
if (m.helpImage) {
m.helpImage.destroy();
m.helpImage = null;
}
if (m.startLabel) {
m.startLabel.destroy();
m.startLabel = null;
}
if (m.graphics) {
m.graphics.destroy();
m.graphics = null;
}
game.paused = false;
game.input.keyboard.reset(true);
this.initKeyboard();
},
growBoard: function() {
var board = game.global.board;
if (!board.isTopRowEmpty()) {
this.gameOver();
}
board.grow();
this.lookForMatches();
return;
},
// The "T" key is simiply used to test things right now
keyT: function() {
this.levelUp();
return;
// game.camera.shake(0.08, 3000);
var leftEmitter = game.add.emitter(500, 500);
//leftEmitter.bounce.setTo(0.5, 0.5);
leftEmitter.setXSpeed(-100, 100);
leftEmitter.setYSpeed(-100, 100);
leftEmitter.gravity = {x: 0, y:0};
leftEmitter.makeParticles('red_particle', 0, 120, true, true);
leftEmitter.setAlpha(1, .2, 500);
leftEmitter.autoAlpha = true;
leftEmitter.start(true, 1000, 0, 100);
return;
},
keyQ: function() {
if (game.paused) {
return;
}
game.paused = true;
var w = game.width;
var h = game.height;
var panel = game.add.sprite(w / 2, h / 4, 'popup_panel');
panel.anchor.setTo(0.5, 0.5);
var label = game.add.text(w / 2, h / 4, 'Quit Game? (Y/N)', FontBuilder.build('32', '#eee'));
label.anchor.setTo(0.5, 0.5);
game.input.keyboard.reset(true);
game.input.keyboard.addKey(Phaser.Keyboard.Y).onDown.add(this.keyY, this);
game.input.keyboard.addKey(Phaser.Keyboard.N).onDown.add(this.keyN, this);
this.quitPanel = {
panel: panel,
label: label
}
},
keyY: function() {
if (this.quitPanel) {
game.paused = false;
this.destroyQuitPanel();
this.gameOver();
}
},
keyN: function() {
if (this.quitPanel) {
game.paused = false;
this.destroyQuitPanel();
this.initKeyboard();
}
},
keyTab: function() {
game.global.showNextPiece = !game.global.showNextPiece;
if (game.global.showNextPiece) {
game.global.nextPiece.show();
}
else {
game.global.nextPiece.hide();
};
},
destroyQuitPanel: function() {
var p = this.quitPanel;
p.panel.destroy();
p.label.destroy();
this.quitPanel = null;
},
keyEscape: function() {
game.paused = !game.paused;
var w = game.width;
var h = game.height;
if (game.paused) {
var panel = game.add.sprite(w / 2, h / 4, 'popup_panel');
panel.anchor.setTo(0.5, 0.5);
var label1 = game.add.text(w / 2, h / 4 - 10, 'Game Paused', FontBuilder.build('25', '#eee'));
label1.anchor.setTo(0.5, 1.0);
var label2 = game.add.text(w / 2, h / 4 + 10, 'Press ESC to resume.', FontBuilder.build('25', '#eee'));
label2.anchor.setTo(0.5, 0.0);
this.pausePanel = {
panel: panel,
label1: label1,
label2: label2
};
game.input.keyboard.reset(true);
game.input.keyboard.addKey(Phaser.Keyboard.ESC).onDown.add(this.keyEscape, this);
}
else {
this.pausePanel.panel.destroy();
this.pausePanel.label1.destroy();
this.pausePanel.label2.destroy();
this.pausePanel = null;
game.input.keyboard.reset(true);
this.initKeyboard();
}
},
moveLeft:function(){
console.log("Left");
var piece = game.global.currentPiece;
var board = game.global.board;
if (board.outOfBounds(piece, -1, 0)) {
return;
}
if (board.collides(piece, -1, 0)) {
return;
}
piece.moveLeft();
},
moveRight: function() {
console.log("Right");
var piece = game.global.currentPiece;
var board = game.global.board;
if (board.outOfBounds(piece, 1, 0)) {
return;
}
if (board.collides(piece, 1, 0)) {
return;
}
piece.moveRight();
},
keyLeft: function() {
if(game.global.currentCurse==CurseType.REVERSE_KEYS){
this.moveRight();
}
else{
this.moveLeft();
}
},
keyRight: function() {
if(game.global.currentCurse==CurseType.REVERSE_KEYS){
this.moveLeft();
}
else{
this.moveRight();
}
},
keyUp: function() {
console.log("Up");
var piece = game.global.currentPiece;
piece.rotate();
},
keyDown: function() {
console.log("Down");
this.fallPiece();
},
keySpace: function() {
console.log("Space");
var piece = game.global.currentPiece;
var board = game.global.board;
while (true) {
if (board.outOfBounds(piece, 0, 1) || board.collides(piece, 0, 1)) {
board.addPiece(piece);
this.newPiece();
this.lookForMatches();
return;
}
piece.moveDown();
}
},
lookForMatches: function() {
var board = game.global.board;
var matches = board.findMatches();
if ((!matches) || (matches.length == 0)) {
game.global.collapseCycle = 0;
return;
}
for (var block of matches) {
block.sprite.destroy();
}
var count = matches.length;
game.global.score = game.global.score + this.calcPoints(count, game.global.collapseCycle);
game.global.totalBlocksCleared = game.global.totalBlocksCleared + count;
this.updateScoreBox();
game.global.collapseCycle++;
game.time.events.add(400, this.collapse, this);
},
collapse: function() {
var board = game.global.board;
var blocks = board.clearExploding();
for (var block of blocks) {
block.sprite.destroy();
}
board.collapse();
this.lookForMatches();
},
fallPiece: function() {
var piece = game.global.currentPiece;
var board = game.global.board;
if (board.outOfBounds(piece, 0, 1)) {
board.addPiece(piece);
this.newPiece();
return;
}
if (board.collides(piece, 0, 1)) {
board.addPiece(piece);
this.newPiece();
this.lookForMatches();
return;
}
piece.moveDown();
},
update: function() {
if (game.global.newCurse) {
game.global.currentCurse = game.global.newCurse;
game.global.newCurse = null;
if (game.global.currentCurse!=null && game.global.currentCurse == CurseType.BOARD_GROW) {
this.showMarquee(Marquees.CURSED_BOARD_GROW);
}
if (game.global.currentCurse!=null && game.global.currentCurse == CurseType.CURSED_COLORS) {
this.showMarquee(Marquees.CURSED_COLORS);
}
if (game.global.currentCurse!=null && game.global.currentCurse == CurseType.REVERSE_KEYS) {
this.showMarquee(Marquees.REVERSE_KEYS);
}
if (game.global.currentCurse!=null && game.global.currentCurse == CurseType.HARDER_MATCHES) {
this.showMarquee(Marquees.HARDER_MATCHES);
}
this.updateCurseBox();
}
},
gameOver: function() {
this.music.stop();
game.global.gameOverPanel = {};
var gop = game.global.gameOverPanel;
gop.graphics = game.add.graphics(0, 0);
gop.graphics.beginFill(0x000000, 0.85);
gop.graphics.drawRect(0, 0, game.width, game.height);
gop.graphics.endFill();
gop.title = game.add.image(game.width / 2, -300, 'game_over');
gop.title.anchor.x = 0.5;
gop.title.anchor.y = 0.5;
gop.titleTween = game.add.tween(gop.title).to({y: game.height * 0.20}, 2000).easing(Phaser.Easing.Bounce.Out).start();
gop.scoreLabel = game.add.text(0 - game.width / 2, game.height * .40, 'Your Score: ' + game.global.score, FontBuilder.build('32', '#eee'));
gop.scoreLabel.anchor.setTo(0.5, 0.5);
gop.scoreTween = game.add.tween(gop.scoreLabel).to({x: game.width / 2}, 500).easing(Phaser.Easing.Linear.None).start();
gop.highScoreLabel = game.add.text(game.width + game.width / 2, game.height * .50, 'High Score: ' + HighScore.get(), FontBuilder.build('24', '#999'));
gop.highScoreLabel.anchor.setTo(0.5, 0.5);
gop.highScoreTween = game.add.tween(gop.highScoreLabel).to({x: game.width / 2}, 500).easing(Phaser.Easing.Linear.None).start();
if (game.global.score > HighScore.get()) {
HighScore.set(game.global.score);
gop.congratulationsLabel = game.add.text(game.width / 2, game.height * .60, 'Congratulations! You have a new High Score!', FontBuilder.build('24', '#fff'));
gop.congratulationsLabel.anchor.setTo(0.5, 0.5);
}
gop.pressLabel = game.add.text(game.width / 2, game.height * .90, 'Press Space Bar to Continue', { font: '32px Exo 2', fill: '#eee' });
gop.pressLabel.anchor.setTo(0.5, 0.5);
game.paused = true;
game.input.keyboard.reset(true);
game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR).onDown.add(this.goToMenu, this);
},
goToMenu: function() {
game.paused = false;
game.state.start('menu');
},
levelUp: function() {
game.global.piecesUntilNextLevel = 20;
game.global.level = game.global.level + 1;
this.updateScoreBox();
this.initPieceTimer();
if (game.global.level == 2) {
this.showMarquee(Marquees.DIAMONDS);
}
if (game.global.level == 4) {
this.showMarquee(Marquees.BEWARE);
}
if (game.global.level == 6) {
this.showMarquee(Marquees.RAINBOW);
}
},
newPiece: function() {
var gg = game.global;
var newPiece = gg.nextPiece;
if (gg.board.collides(newPiece, 0,0)) {
this.gameOver();
}
else {
gg.currentPiece = newPiece;
gg.currentPiece.setCurrent(true);
gg.currentPiece.show();
gg.nextPiece = new GamePiece(false);
if (gg.showNextPiece) {
gg.nextPiece.show();
}
else {
gg.nextPiece.hide();
}
gg.piecesUntilNextBoardGrowth = gg.piecesUntilNextBoardGrowth - 1;
if (gg.piecesUntilNextBoardGrowth <= 0) {
if (gg.currentCurse == CurseType.BOARD_GROW) {
gg.piecesUntilNextBoardGrowth = 10;
this.growBoard();
}
}
gg.cursePieceCount = gg.cursePieceCount + 1;
if (gg.cursePieceCount > 10) {
gg.cursePieceCount = 0;
gg.currentCurse = null;
this.updateCurseBox();
}
}
gg.piecesUntilNextLevel--;
if (gg.piecesUntilNextLevel <= 0) {
this.levelUp();
}
this.updateScoreBox();
},
calcPoints: function(numberOfBlocks, collapseCycle) {
return game.global.level * numberOfBlocks * (collapseCycle + 1);
}
}
<file_sep>var HighScore = {
get: function() {
var highScore = localStorage.getItem('colors.highScore');
if (!highScore) {
localStorage.setItem('colors.highScore', 0);
highScore = 0;
}
return highScore;
},
set: function(score) {
localStorage.setItem('colors.highScore', score);
}
}
<file_sep>var GameBlockType = {
EMPTY: {value: 0, char: '.', image: ''},
AQUA: {value: 1, char: 'A', image: 'aqua_block'},
AQUA2: {value: 101, char: 'AA', image: 'aqua2_block'},
BLUE: {value: 2, char: 'B', image: 'blue_block'},
BLUE2: {value: 102, char: 'BB', image: 'blue2_block'},
GREEN: {value: 3, char: 'G', image: 'green_block'},
GREEN2: {value: 103, char: 'GG', image: 'green2_block'},
PURPLE: {value: 4, char: 'P', image: 'purple_block'},
PURPLE2: {value: 104, char: 'PP', image: 'purple2_block'},
RED: {value: 5, char: 'R', image: 'red_block'},
RED2: {value: 105, char: 'RR', image: 'red2_block'},
ORANGE: {value: 6, char: 'O', image: 'orange_block'},
ORANGE2: {value: 106, char: 'OO', image: 'orange2_block'},
YELLOW: {value: 7, char: 'Y', image: 'yellow_block'},
YELLOW2: {value: 107, char: 'YY', image: 'yellow2_block'},
RAINBOW: {value: 10, char: 'r', image: 'rainbow_block'},
BLACK: {value: 11, char: 'r', image: 'black_block'},
DIAMOND: {value: 12, char: 'r', image: 'diamond'},
EXPLODING: {value: 100, char: '*', image: 'exploding_block'},
random: function() {
var type = this.normalRandom();
//Added in all these checks because global may not always
//exist at the start of the game.
if (game!=undefined ) {
if(game.global!=undefined){
if(game.global.currentCurse!=null && game.global.currentCurse == CurseType.CURSED_COLORS){
type = this.cursedRandom();
}
}
}
// Diamond Blocks start appearing at level 2
if ((game.global) && (game.global.level >= 2)) {
if (game.rnd.frac() < 0.10) {
return this.DIAMOND;
}
}
// Black Blocks start appearing at level 4
if ((game.global) && (game.global.level >= 4)) {
if (game.rnd.frac() < 0.10) {
return this.BLACK;
}
}
// Rainbox Blocks start appearing at level 6
if ((game.global) && (game.global.level >= 6)) {
if (game.rnd.frac() < 0.05) {
return this.RAINBOW;
}
}
return type;
},
normalRandom: function() {
return game.rnd.pick([
this.AQUA,
this.BLUE,
this.GREEN,
this.PURPLE,
this.RED
]);
},
cursedRandom: function() {
return game.rnd.pick([
// this.AQUA,
// this.BLUE,
// this.GREEN,
// this.PURPLE,
// this.RED,
this.AQUA2,
this.BLUE2,
this.GREEN2,
this.PURPLE2,
this.RED2,
]);
}
}
class GameBlock {
constructor(type, x, y) {
this.type = type;
this.x = x;
this.y = y;
this.offsetX = 0;
this.offsetY = 0;
this.sprite = game.add.image(0, 0, type.image);
this.sprite.anchor.setTo(0, 0);
this.updateSpritePosition();
}
cloneExploding() {
var block = new GameBlock(GameBlockType.EXPLODING, this.x, this.y);
block.setOffset(game.width/2 - (32 * 9)/2, 18);
block.sprite.alpha = 0;
var emitter = game.add.emitter(block.sprite.x + 16, block.sprite.y + 16);
emitter.setXSpeed(-50, 50);
emitter.setYSpeed(-50, 50);
emitter.gravity = {x: 0, y:0};
emitter.makeParticles('red_particle', 0, 24, true, true);
emitter.makeParticles('orange_particle', 0, 24, true, true);
emitter.makeParticles('yellow_particle', 0, 32, true, true);
emitter.setAlpha(1.0, 0.1, 300, Phaser.Easing.Exponential.None);
emitter.setScale(2.0, 1.0, 2.0, 1.0, 300);
emitter.autoAlpha = true;
emitter.start(true, 900, 0, 100);
return block;
}
getLogicalPosition() {
return {
x: this.x,
y: this.y
}
}
setOffset(x, y) {
this.offsetX = x;
this.offsetY = y;
this.updateSpritePosition();
}
setLogicalPosition(x, y) {
this.x = x;
this.y = y;
this.updateSpritePosition();
}
setLogicalX(x) {
this.x = x;
this.updateSpritePosition();
}
setLogicalY(y) {
this.y = y;
this.updateSpritePosition();
}
show() {
this.sprite.visible = true;
}
hide() {
this.sprite.visible = false;
}
moveUp(delta) {
this.y = this.y - delta;
this.updateSpritePosition();
}
moveDown(delta) {
console.log("Delta: %d, y: %d", delta, this.y);
this.y = this.y + delta;
this.updateSpritePosition();
console.log("Moved block [" + this.type.char + "] down to %d, %d", this.x, this.y);
}
updateSpritePosition() {
this.sprite.x = this.x * 32 + this.offsetX;
this.sprite.y = this.y * 32 + this.offsetY;
}
};
<file_sep>var bootState = {
preload: function() {
game.load.image('progress_bar', 'assets/progress_bar.png');
},
create: function() {
game.stage.backgroundColor = '#000000';
game.physics.startSystem(Phaser.Physics.ARCADE);
game.renderer.renderSession.roundPixels = false;
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
//game.scale.scaleMode = Phaser.ScaleManager.NO_SCALE;
game.scale.pageAlignVertically = true;
game.scale.pageAlignHorizontally = true;
document.body.style.backgroundColor = '#000';
},
update: function() {
game.state.start('load');
}
}
|
7e6de4e8d9d18f74815bcb886db9f7c48d540649
|
[
"JavaScript",
"Markdown"
] | 9 |
JavaScript
|
billkratzer/colors-game
|
44c2ac58872cf5a056d762099bf23ba7683d622c
|
0ee861aa481d5631f37c9927384bd8e4cc5f369f
|
refs/heads/master
|
<repo_name>MackenzieBerliner-Glasser/tcp-chat-server<file_sep>/lib/chat-room.js
module.exports = class Clients {
constructor() {
this.map = new Map;
this.userNumber = 1;
}
add(client) {
const username = client.username = `user${this.userNumber++}`;
this.map.set(username, client);
}
remove(client) {
this.map.delete(client);
}
getClient(username) {
return this.map.get(username);
}
rename(username, newUsername) {
if(this.map.has(newUsername)) return false;
else {
const socket = this.map.get(username);
socket.username = newUsername;
this.map.set(newUsername, socket);
return this.map.delete(username);
}
}
all() {
return [...this.map.values()];
}
getBroadcastClients(client) {
return this.all().filter(c => c !== client);
}
};
<file_sep>/test/chat-room.test.js
const assert = require('assert');
const ChatRoom = require('../lib/chat-room');
describe('Chatroom', () => {
const c1 = {};
const c2 = {};
const c3 = {};
let chatRoom = null;
beforeEach(() => {
chatRoom = new ChatRoom;
chatRoom.add(c1);
chatRoom.add(c2);
chatRoom.add(c3);
});
it('assigns names to user objects', () => {
assert.equal(c1.username, 'user1');
assert.equal(c2.username, 'user2');
assert.equal(c3.username, 'user3');
});
it('gets a client', () => {
const client = chatRoom.getClient(c1.username);
assert.deepEqual(client, c1);
});
it('removes a client', () => {
chatRoom.remove(c2.username);
const allClients = chatRoom.all();
assert.deepEqual(allClients, [c1, c3]);
});
it('it renames a user', () => {
const client = c1.username;
const newName = 'I-Love-ALC';
const newusername = chatRoom.rename(client, newName);
assert.equal(newusername, true);
assert.equal(chatRoom.getClient(client), undefined);
assert.ok(chatRoom.getClient(newName));
assert.equal(chatRoom.getClient(newName).username, newName);
});
it('doesnt allow renaming to existing usernames', () => {
const renameExists = chatRoom.rename(c1.username, c2.username);
assert.equal(renameExists, false);
assert.equal(c1, chatRoom.getClient(c1.username));
assert.equal(c2, chatRoom.getClient(c2.username));
});
it('stores clients', () => {
const allClients = chatRoom.all();
assert.deepEqual(allClients, [c1, c2, c3]);
});
it('lists of client minus sender', () => {
const broadcast = chatRoom.getBroadcastClients(c1);
assert.deepEqual(broadcast, [c2, c3]);
});
});
<file_sep>/README.md
# TCP Chatroom
## Overview
This chat app allows you to create a chatroom in your cli and send messages to users.
## How to use
* Clone down this repo.
* In your console run `node server.js` to get your server started.
* In a separate console run `node client.js` to connect to the chatroom as a new user.
* Once in the chatroom you can run:
1. `@all` command to send a message to the entire chatroom.
2. `@nick:<new username>` to change your username.
3. `@dm:<another user>` to direct message that user.
There you go! Now you can chat to yourself through endless command lines!<file_sep>/client.js
/*eslint-disable no-console*/
const net = require('net');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const socket = net.connect(15678, () => {
rl.setPrompt('');
rl.prompt();
rl.on('line', input => {
socket.write(input);
});
socket.on('data', data => {
console.log(data);
});
socket.on('close', () => {
console.log('server left :(');
socket.destroy();
});
});
socket.setEncoding('utf8');
<file_sep>/lib/app.js
const net = require('net');
const ChatRoom = require('./chat-room');
const parseMessage = require('./parse-message');
const chatRoom = new ChatRoom();
module.exports = net.createServer(client => {
client.setEncoding('utf8');
chatRoom.add(client);
client.write(`Welcome to the chatroom ${client.username}`);
client.write(
'use @all to talk to entire chat ' +
'@nick:<new username> to change your username ' +
'@dm:<another username> to direct message that user');
client.on('end', () => {
chatRoom.remove(client.username);
chatRoom
.all()
.forEach(c => c.write(`${client.username} has left`));
});
client.on('data', data => {
const message = parseMessage(data);
if(!message) {
//nothing to do
}
else if(message.cmd === 'all') {
chatRoom
.getBroadcastClients(client)
.forEach(c => c.write(`${client.username}: ${message.text}`));
}
else if(message.cmd === 'nick') {
chatRoom
.rename(client.username, message.arg);
chatRoom
.getClient(client.username)
.write(`you are now ${client.username}`);
}
else if(message.cmd === 'dm') {
const client = chatRoom
.getClient(message.arg);
if(client) {
client.write(`${client.username}[dm]: ${message.text}`);
}
}
});
});
<file_sep>/test/parse-message.test.js
const assert = require('assert');
const parseMessage = require('../lib/parse-message');
describe('parse message', () => {
it('returns null if no "@" is supplied', () => {
const failure = 'hello';
assert.equal(parseMessage(failure), null);
});
it('returns an object', () => {
const correct = '@all hello';
const expected = {
cmd: 'all',
arg: undefined,
text: 'hello'
};
assert.deepEqual(parseMessage(correct), expected);
});
it('handles @nick', () => {
const correct = '@nick:coolguy';
const expected = {
cmd: 'nick',
arg: 'coolguy',
text: ''
};
assert.deepEqual(parseMessage(correct), expected);
});
it('handles @dm', () => {
const correct = '@dm:coolguy what up bro?';
const expected = {
cmd: 'dm',
arg: 'coolguy',
text: 'what up bro?'
};
assert.deepEqual(parseMessage(correct), expected);
});
});
|
55bc188a18b1257b86c6ad7b1edccd26ae1e9892
|
[
"JavaScript",
"Markdown"
] | 6 |
JavaScript
|
MackenzieBerliner-Glasser/tcp-chat-server
|
8c7d2e2636b38e2e3f50bf1e00f4b524373c0a2e
|
2807b78535adb63362a681ecf2d401600745b94e
|
refs/heads/master
|
<file_sep>package filters
import (
"image"
"image/color"
"github.com/Aspirin4k/cv_school_test/project/imaginer"
)
type Flip struct {
imaginer.Filter
}
func (f *Flip) ApplyFilter(src image.Image) (image.Image, error) {
dstBounds := src.Bounds()
dstImage := image.NewRGBA(dstBounds)
// По сетке пикселей
// ... дополнить комментарий
for i := src.Bounds().Min.X ; i < src.Bounds().Max.X; i++ {
for j := src.Bounds().Min.Y ; j < src.Bounds().Max.Y; j++ {
r, g, b, a := src.At(i, j).RGBA()
pixel := color.RGBA{uint8(r),uint8(g),uint8(b),uint8(a)}
dstImage.Set(src.Bounds().Max.X - i - 1, j, pixel)
}
}
return dstImage, nil
}
<file_sep>package filters
import (
"image"
"image/color"
"math/rand"
"github.com/Aspirin4k/cv_school_test/project/imaginer"
)
var (
avg = float64(2)
stddev = float64(0.05)
)
type Noise struct {
imaginer.Filter
}
func (f *Noise) ApplyFilter(src image.Image) (image.Image, error) {
dstBounds := src.Bounds()
dstImage := image.NewRGBA(dstBounds)
for i := src.Bounds().Min.X ; i < src.Bounds().Max.X; i++ {
for j := src.Bounds().Min.Y ; j < src.Bounds().Max.Y; j++ {
r, g, b, _ := src.At(i, j).RGBA()
Y := R * float64(r) + G * float64(g) + B * float64(b)
// Нормальное распределение
rnd := (rand.NormFloat64() * stddev + avg) * MAX
newY := uint32(Y + rnd) % uint32(MAX)
pixel := color.Gray{uint8(newY / 256)}
dstImage.Set(i, j, pixel)
}
}
return dstImage, nil
}<file_sep>package fragmenter
import (
"strings"
"strconv"
"os"
"image"
"image/draw"
"image/png"
"path/filepath"
)
func ProcceedImage(fileName string, data []byte, imagesLocation string, fragmentsLocation string) error {
iterator := 0
srcFile, err := os.Open(imagesLocation + fileName + ".png")
if err != nil {
return err
}
defer srcFile.Close()
srcImage, _, err := image.Decode(srcFile)
if err != nil {
return err
}
// Сплитим байтовый массив как строку по строкам
lines := strings.Split(string(data[:]), "\n")
for _, line := range lines {
// Виндовые спецсимволы
line = strings.Replace(line, "\r", "", -1)
coords := strings.Split(line, ",")
// Неэлегантно
lx, err := strconv.Atoi(coords[0])
if err != nil {
return err
}
ly, err := strconv.Atoi(coords[1])
if err != nil {
return err
}
rx, err := strconv.Atoi(coords[2])
if err != nil {
return err
}
ry, err := strconv.Atoi(coords[3])
if err != nil {
return err
}
// Создается изображение размера фрагмента
dstImage := image.NewRGBA(image.Rect(0, 0, rx - lx, ry - ly))
// В целевое изображение рисуется фрагмент исходного
draw.Draw(dstImage, dstImage.Bounds(), srcImage, image.Point{lx,ly}, draw.Src)
// Создается папка, если еще не
dstPath, err := filepath.Abs(fragmentsLocation)
if err != nil {
return err
}
os.MkdirAll(dstPath, os.ModePerm)
// Создается файл в системе
dstFile, err := os.Create(fragmentsLocation + fileName + "_" + strconv.Itoa(iterator) + ".png")
if err != nil {
return err
}
// В созданный файл заносится полученное изображение
png.Encode(dstFile, dstImage)
// Т.к. в цикле, то лучше сразу закрыть файл без откладывания
dstFile.Close()
iterator++
}
return nil
}<file_sep>package main
import (
// Стандартные зависимости
"io/ioutil"
"flag"
"fmt"
"strings"
// Внешних зависимостей нет
// Внутренние зависимости
"github.com/Aspirin4k/cv_school_test/project/fragmenter"
"github.com/Aspirin4k/cv_school_test/project/imaginer/filters"
"github.com/Aspirin4k/cv_school_test/project/imaginer"
)
func main() {
// Возможные входные параметры
annotationsLocation := flag.String("annotations", "./../annotations/", "location of annotations")
imagesLocation := flag.String("images", "./../images/", "location of images")
fragmentsLocation := flag.String("fragments", "./../fragments/", "location for fragments")
greyscaleLocation := flag.String("greyscale", "./../fragments_grey/","location for greyscaled fragments")
flipLocation := flag.String("flip", "./../fragments_flip/", "location for flipped fragments")
normalizeLocation := flag.String("normalize", "./../fragments_normalized/", "location for normalized fragments")
noiseLocation := flag.String("noise", "./../fragments_noise/", "location for noised fragments")
flag.Parse()
annotations, err := ioutil.ReadDir(*annotationsLocation)
if err != nil {
fmt.Println(err)
}
for _, f := range annotations {
// Считываем файл с аннотациями и передаем обработчику
var filesData []byte
filesData, err = ioutil.ReadFile(*annotationsLocation + f.Name())
if err != nil {
fmt.Println(err)
}
// Убираем расширение
fragmenter.ProcceedImage(
f.Name()[:strings.LastIndex(f.Name(),".")],
filesData,
*imagesLocation,
*fragmentsLocation)
if err != nil {
fmt.Println(err)
}
}
// Далее идет дополнительная часть задания
fragments, err := ioutil.ReadDir(*fragmentsLocation)
if err != nil {
fmt.Println(err)
}
// 1. greyscale
for _, f := range fragments {
provider := &filters.GreyScale{}
fileName := f.Name()[:strings.LastIndex(f.Name(),".")]
err = imaginer.SetFilter(*fragmentsLocation + f.Name(), *greyscaleLocation + fileName + "_grey.png", provider)
if err != nil {
fmt.Println(err)
}
}
// 2. flip
for _, f := range fragments {
provider := &filters.Flip{}
fileName := f.Name()[:strings.LastIndex(f.Name(),".")]
err = imaginer.SetFilter(*fragmentsLocation + f.Name(), *flipLocation + fileName + "_flip.png", provider)
if err != nil {
fmt.Println(err)
}
}
// Возможно задание построенно некорректно (Предлагается сделать нормализацию изображений, полученных в пункте 2,
// предоставляя ссылку на метод нормализации черно-белых)
// Поэтому было реализовано 2 способа: для черно-белых и цветных
// 3 normalization - серые
fragmentsGrey, err := ioutil.ReadDir(*greyscaleLocation)
if err != nil {
fmt.Println(err)
}
for _, f := range fragmentsGrey {
provider := &filters.Normalize{}
provider.NormalizeType = filters.GREYSCALED
fileName := f.Name()[:strings.LastIndex(f.Name(),".")]
err = imaginer.SetFilter(*greyscaleLocation + f.Name(), *normalizeLocation + fileName + "_normalized.png", provider)
if err != nil {
fmt.Println(err)
}
}
// 3.5 normalization - цветные
fragmentsFlip, err := ioutil.ReadDir(*flipLocation)
if err != nil {
fmt.Println(err)
}
for _, f := range fragmentsFlip {
provider := &filters.Normalize{}
provider.NormalizeType = filters.COLORED
fileName := f.Name()[:strings.LastIndex(f.Name(),".")]
err = imaginer.SetFilter(*flipLocation + f.Name(), *normalizeLocation + fileName + "_normalized.png", provider)
if err != nil {
fmt.Println(err)
}
}
// Опять же, из-за нумерации неясно к какому пункту именно идет указание
// поэтому зашумлены были серые изображения
// 4 noise
for _, f := range fragmentsGrey {
provider := &filters.Noise{}
fileName := f.Name()[:strings.LastIndex(f.Name(),".")]
err = imaginer.SetFilter(*greyscaleLocation + f.Name(), *noiseLocation + fileName + "_noise.png", provider)
if err != nil {
fmt.Println(err)
}
}
fmt.Println("Done!")
}<file_sep>Описание:
Была реализована основная и дополнительная части задачи. Т.к. язык не был
регламентирован, приложение было написано на Golang.
Проблемы:
Постановка задачи была неясна, а именно пункт связанный с нормализацией:
В пункте указано применить нормализацию к фрагментам, полученным в пункте 2
и в качестве примера была предоставлена ссылка на wikipedia, содержащий
алгоритм нормализации серого (greyscaled) изображения. В следствие этого
возникли сомнения в правильности нумерации (основная часть содержит
единственный пункт 1., тогда как дополнительная аналогично начинается с пункта 1. ...,
не должна ли была она начаться с пункта 2?). Поэтому нормализация была
реализована в двух частях: для RGB (Алгоритм взят с недостоверенного сайта) и для Greyscaled
Запуск:
В папке Binaries лежат 4 исполняемых файла, собранных для linux и windows x32 и x64 архитектур.
Работоспособность приложений была проверена в системах:
Ubuntu Budgie x64
Linux Mint x32
Windows 10 x64
Windows 8 x32
Приложение ожидает "увидеть" необходимые папки по пути "./../*", т.е. на уровень ниже.
Однако есть возможность задать флаги с указанием каждой директории при запуске
приложения (Флаги можно посмотреть в исходнике main.go, перечислять не буду, т.к.
вряд ли они понадобятся)
<file_sep>package imaginer
import (
"os"
"image"
"strings"
"image/png"
)
// Применить некоторый фильтр
/*
Параметры - путь до исходного файла, путь до результата, применяемый фильтр
*/
func SetFilter(srcFilename string, dstFilename string, filter Filter) error {
srcFile, err := os.Open(srcFilename)
if err != nil {
return err
}
srcImage, _, err := image.Decode(srcFile)
if err != nil {
return err
}
defer srcFile.Close()
// Создается папка, если еще не
os.MkdirAll(dstFilename[:strings.LastIndex(dstFilename,"/")], os.ModePerm)
dstFile, err := os.Create(dstFilename)
if err != nil {
return err
}
defer dstFile.Close()
// Применяем кастомный фильтр
dstImage, err := filter.ApplyFilter(srcImage)
if err != nil {
return err
}
png.Encode(dstFile, dstImage)
return nil
}<file_sep># Тестовое задание Macroscop School 2017
Это проект был написан в рамках подготовки к Macroscop School 2017.
Представляет собой утилиту, позволяющую вырезать некоторые фрагменты из исходного изображения и обработать их
Утилита осуществляет следующее:
* Преобразует RGBA в Grey (Greyscale)
* Инвертирует по горизонтали (Flip)
* Осуществляет нормализацию серых изображений
* Осуществляет нормализацию цветных изображений (спорно)
* Применяет гауссов шум (Gauss noise)
<file_sep>package filters
import (
"image"
"errors"
"image/color"
"github.com/Aspirin4k/cv_school_test/project/imaginer"
)
var (
GREYSCALED = 0
COLORED = 1
)
type Normalize struct {
imaginer.Filter
// Тип нормализации
// Цветное или серое изображение
NormalizeType int
}
func (f *Normalize) ApplyFilter(src image.Image) (image.Image, error) {
switch {
case f.NormalizeType == GREYSCALED:
dstBounds := src.Bounds()
dstImage := image.NewRGBA(dstBounds)
// Максимальная и минимальная яркость
min := MAX
max := MIN
// Для нормализации необходимо знать max и min, а значит пройти по всем пикселям,
// что занимает n операций (очевидно, меньше невозможно)
// в дополнение к этому необходимо второй раз пройти по сетке, изменив
// каждый отдельный пиксель, что займет еще n времени
// по хорошему - необходимо распараллелить...
for i := src.Bounds().Min.X ; i < src.Bounds().Max.X; i++ {
for j := src.Bounds().Min.Y ; j < src.Bounds().Max.Y; j++ {
// К сожалению, файл енкодится в формат, в котором каждый пиксель
// закодирован в rgba, из-за чего по новой надо вычислять оттенок серого
r, g, b, _ := src.At(i, j).RGBA()
Y := R * float64(r) + G * float64(g) + B * float64(b)
if Y > max {
max = Y
}
if Y < min {
min = Y
}
}
}
for i := src.Bounds().Min.X ; i < src.Bounds().Max.X; i++ {
for j := src.Bounds().Min.Y ; j < src.Bounds().Max.Y; j++ {
r, g, b, _ := src.At(i, j).RGBA()
Y := R * float64(r) + G * float64(g) + B * float64(b)
// Если использовать эту формулу (из википедии),
// то при Y = max (самое белое место на фото) произойдет переполнение переменной
// Из-за чего белый конвертнеться в черный...
newY := (Y - min) * (MAX - MIN) / (max - min) + min
pixel := color.Gray{uint8(newY / 256)}
dstImage.Set(i, j, pixel)
}
}
return dstImage, nil
case f.NormalizeType == COLORED:
dstBounds := src.Bounds()
dstImage := image.NewRGBA(dstBounds)
for i := src.Bounds().Min.X ; i < src.Bounds().Max.X; i++ {
for j := src.Bounds().Min.Y; j < src.Bounds().Max.Y; j++ {
r, g, b, a := src.At(i, j).RGBA()
sum := r + g + b
pixel := color.RGBA{
uint8(float64(r) / float64(sum) * 255),
uint8(float64(g) / float64(sum) * 255),
uint8(float64(b) / float64(sum) * 255),
uint8(a)}
dstImage.Set(i, j, pixel)
}
}
return dstImage, nil
default:
return nil, errors.New("unexpected normalization type!!!")
}
}<file_sep>package imaginer
import (
"image"
)
// Интерфейс для реализации фильтров
type Filter interface {
ApplyFilter(src image.Image) (image.Image, error)
}<file_sep>package filters
// В файле содержаться константы, которые используются в более чем
// одном фильтре...
var (
// К-ты для грейскеллинга
R = 0.2126
G = 0.7152
B = 0.0722
// Минимальная и максимальная насыщенность серого
MAX = float64(65535)
MIN = float64(0)
)
|
63e991a2c0dfe45348e28c85dd9f22e9e5b27c2e
|
[
"Text",
"Go",
"Markdown"
] | 10 |
Go
|
Aspirin4k/cv-school-test
|
9269abd08f0188768b94e1378ea6049895d7d111
|
1142f3f1ae33b22195b2b56f59f66ba0402beb7a
|
refs/heads/master
|
<repo_name>JainRachit123/Games<file_sep>/README.md
# Games
This repository contains different games using python and its modules.
Tic Tac Toe is made using basic python.
Snake game is made using turtle module in python.
Car Dodge game is made using pygame module of python
<file_sep>/Snake Game.py
from turtle import *
from random import *
from time import *
# variables to store scores
high_score = 0
score = 0
d = 0.1
# setting up screen
screen = Screen()
screen.title('This is made by <NAME>')
screen.setup(420, 420, 470, 0)
screen.bgcolor('green')
screen.tracer(0)
# setting pen for score
pen = Turtle()
pen.penup()
pen.hideturtle()
pen.goto(0, 170)
pen.color('white')
pen.write('Score: {} High Score: {}'.format(score, high_score), align='center',
font=("Courier", 18, "normal"))
# snakes food
food = Turtle()
food.speed(0)
food.shape('circle')
food.shapesize(0.3)
food.color('red')
food.penup()
food.goto(50, 0)
# snake head
head = Turtle()
head.speed(0)
head.shape('square')
head.shapesize(0.5)
head.color('black')
head.penup()
head.direction = 'stop'
snake = []
# function to define movement of snake
def move():
if head.direction == 'Up':
y = head.ycor()
head.sety(y + 5)
elif head.direction == 'Down':
y = head.ycor()
head.sety(y - 5)
elif head.direction == 'Right':
x = head.xcor()
head.setx(x + 5)
elif head.direction == 'Left':
x = head.xcor()
head.setx(x - 5)
else:
head.speed(0)
head.goto(0, 0)
# function to change direction of movement
def change(x, y):
if x == 0:
if y == 5:
head.direction = 'Up'
else:
head.direction = 'Down'
else:
if x == 5:
head.direction = 'Right'
else:
head.direction = 'Left'
# functions to get inputs from keyboard
listen()
onkey(lambda: change(0, 5), 'Up')
onkey(lambda: change(0, -5), 'Down')
onkey(lambda: change(5, 0), 'Right')
onkey(lambda: change(-5, 0), 'Left')
try:
print("Game Started")
while True:
update()
# checking if the snake hit the boundary
if -210 > head.xcor() or head.xcor() > 210 or -210 > head.ycor() or head.ycor() > 210:
sleep(1)
head.goto(0, 0)
head.direction = 'stop'
for body in snake:
body.goto(1000, 1000)
score = 0 # resetting score
snake.clear() # making the snake list empty
pen.clear()
pen.write('Score: {} High Score: {}'.format(score, high_score), align='center',
font=("Courier", 18, "normal"))
print('Start Again')
# when the snake eats the food
if head.distance(food) < 10:
food.goto(randrange(-200, 200), randrange(-200, 200))
# initializing a new segment for body
segment = Turtle()
segment.speed(0)
segment.shape('square')
segment.shapesize(0.5)
segment.color('grey')
segment.penup()
snake.append(segment)
# updating score and delay
score += 10
d -= 0.001
if score > high_score:
high_score = score
pen.clear()
pen.write('Score: {} High Score: {}'.format(score, high_score), align='center',
font=("Courier", 18, "normal"))
# moving the body
for index in range(len(snake) - 1, 0, -1):
snake[index].goto(snake[index-1].position())
# moving the segment at 0 index
if len(snake) > 0:
snake[0].goto(head.position())
move()
# checking if the head collide with body
for segments in snake :
if segments.distance(head) < 5:
sleep(1)
head.goto(0, 0)
head.direction = 'stop'
for body in snake:
body.goto(1000, 1000)
score = 0
snake.clear()
pen.clear()
pen.write('Score: {} High Score: {}'.format(score, high_score), align='center',
font=("Courier", 18, "normal"))
print("Start Again")
sleep(d)
except :
print('Game Closed')
<file_sep>/Tic-Tac-Toe.py
from random import randrange
def DisplayBoard(board):
#
# the function accepts one parameter containing the board's current status
# and prints it out to the console
#
print('+-------+-------+-------+','| | | |', sep = '\n')
print('| ',board[0],' | ',board[1],' | ',board[2],' |')
print('| | | |')
print('+-------+-------+-------+','| | | |', sep = '\n')
print('| ',board[3],' | ',board[4],' | ',board[5],' |')
print('| | | |')
print('+-------+-------+-------+','| | | |', sep = '\n')
print('| ',board[6],' | ',board[7],' | ',board[8],' |')
print('| | | |')
print('+-------+-------+-------+')
def EnterMove(board):
#
# the function accepts the board current status, asks the user about their move,
# checks the input and updates the board according to the user's decision
#
num = int(input('Enter your move: '))
if ((num not in board) or num > 9 or num < 1):
print('Enter a valid move')
EnterMove(board)
else:
board[num-1] = 'O'
return board
def VictoryFor(board, sign):
#
# the function analyzes the board status in order to check if
# the player using 'O's or 'X's has won the game
#
if((board[0] == board[1] == board[2] == sign) or (board[3] == board[4] == board[5] == sign) or (board[6] == board[7] == board[8] == sign)\
or (board[0] == board[3] == board[6] == sign) or (board[1] == board[4] == board[7] == sign) or (board[2] == board[5] == board[8] == sign)\
or (board[0] == board[4] == board[8] == sign) or (board[2] == board[4] == board[6] == sign)):
if(sign == 'X'):
print('Computer Won!')
return False
else:
print('You Won!')
return False
else:
return True
def DrawMove(board):
#
# the function draws the computer's move and updates the board
#
Signal = True
while Signal:
choice = randrange(9)
if (choice not in board or choice == 0):
Signal = True
else:
Signal = False
else:
board[choice-1] = 'X'
return board
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
board[4] = 'X'
DisplayBoard(board)
Msg = True
count = 0
while Msg:
board = EnterMove(board)
DisplayBoard(board)
Msg = VictoryFor(board, 'O')
if(Msg == False):
break
board = DrawMove(board)
DisplayBoard(board)
Msg = VictoryFor(board, 'X')
if(Msg == False):
break
count += 1
if (count == 4):
print ('Match Draw')
Msg = False
print('Game End')
input('Press enter to exit')
<file_sep>/Car Dodge.py
import pygame
import random
import time
pygame.init()
car_width = 115
car_height = 236
screen_width = 600
screen_height = 700
car_speed = 7
screen = pygame.display.set_mode((screen_width, screen_height))
screen.fill((255, 255, 255))
clock = pygame.time.Clock()
img = pygame.image.load('car.jpg')
# Generating obstacle
def enemy_generation(enemy_x, enemy_y, radius):
pygame.draw.circle(screen, (0, 128, 0), (enemy_x, enemy_y), radius)
# checking for collision
def collision(car_x, car_y, enemy_x, enemy_y, radius):
if enemy_y >= car_y:
if car_x < enemy_x < car_x + car_width or car_x < enemy_x - radius < car_x + car_width or car_x < enemy_x + radius < car_x + car_width:
print('\n****** You Collided ******\n')
return True
elif car_x < 0 or car_x + car_width > screen_width:
print('\n****** You Collided ******\n')
return True
else:
return False
# Main game loop
def game_loop():
# defining basic parameters for game
car_x = 300
car_y = 450
radius = 20
enemy_x = 20
enemy_y = 20
enemy_speed = 5
score = 0
while True:
screen.fill((255, 255, 255)) # making the background white
for event in pygame.event.get():
if event.type == pygame.QUIT:
print('\n****** Game Closed ******\n')
pygame.quit()
quit()
enemy_y += enemy_speed
enemy_generation(enemy_x, enemy_y, radius)
if collision(car_x, car_y, enemy_x, enemy_y, radius):
time.sleep(2)
game_loop()
if enemy_y - radius > screen_height:
enemy_x = random.randrange(radius, screen_width)
enemy_generation(enemy_x, enemy_y, radius)
enemy_y = 0
score += 10
print('Score: {}'.format(score))
if score % 50 == 0:
enemy_speed += 1
pressed = pygame.key.get_pressed()
if pressed[pygame.K_RIGHT]: car_x += car_speed
if pressed[pygame.K_LEFT]: car_x -= car_speed
screen.blit(img, (car_x, car_y))
pygame.display.flip()
clock.tick(60)
game_loop() # calling the game loop function
pygame.quit()
quit()
|
115dfe863102ea21c831ede25a0c67f1610c015d
|
[
"Markdown",
"Python"
] | 4 |
Markdown
|
JainRachit123/Games
|
e12d5f7cdf0fe9d2a1b77795b296ec7ca0776cf7
|
825a7c36940c14ad66673e3a541679493fce1416
|
refs/heads/master
|
<repo_name>zachmartin9/hot-restaurant<file_sep>/routes/api-routes.js
const restaurant = require("../models/restaurant.js");
module.exports = (app) => {
app.get("/api/restaurant", (req, res) => {
restaurant.all((data) => {
let object = {
reservations: data
};
res.json(object);
});
})
app.post("/api/restaurant", (req, res) => {
const cols = Object.keys(req.body);
const vals = Object.values(req.body);
restaurant.create(cols, vals, (result) => {
res.json(result);
})
})
}
<file_sep>/db/seeds.sql
INSERT INTO reservations (full_name, email) VALUES ("<NAME>", "<EMAIL>");<file_sep>/README.md
# hot-restaurant Node.js / Express.js / MySQL
## Overview
This is a Node / Express based web applications for handling restaurant reservation requests from users and stores their information in a MySQL database. The application then displays the first five users as current reservations, and every additional reservation as the waiting list.
## Links
* [GitHub for this](https://github.com/zachmartin9/hot-restaurant)
## Technologies Used
- [x] HTML/Bootstrap/Javascript/jQuery
- [x] SQL (Local mySQL DB)
- [x] Node/Express/mysql
## Design
1. The `/tables` route displays all the current reservations for the restaurant. If a user would like to make a new reservation then the `/reservation` is used which asks the user for their full name and email. This information is then stored in a MySQL database.
2. `html-routes.js` serves up the html files.
3. `api-routes.js` handles all the data and repsonds with JSON.
4. Data is saved in a MySQL database which is called using an ORM. The `orm.js` file handles returning either all data or creating new data depending on which SQL function is called.
<file_sep>/public/assets/js/app.js
$.get("/api/restaurant", (data) => {
console.log(data.reservations);
let reservations = data.reservations;
let counter = 0;
reservations.forEach(element => {
counter++;
if (counter <= 5) {
let tableList = $("#tableList");
tableList.append(createTable(element, counter));
} else {
let waitingList = $("#waitingList");
waitingList.append(createTable(element, counter));
}
});
})
function createTable(element, counter) {
let listItems = $("<li class='list-group-item mt-4'>");
listItems.append(
$("<h2>").text(`Table #${counter}`),
$("<hr>"),
$("<h2>").text(`Name: ${element.full_name}`),
$("<h2>").text(`Email: ${element.email}`)
);
return listItems;
};
$(".submit").on("click", (event) => {
event.preventDefault();
if ($("#reserve-name").val() && $("#reserve-email").val()) {
let reservation = {
full_name: $("#reserve-name").val().trim(),
email: $("#reserve-email").val().trim()
};
$.post("/api/restaurant", reservation).then(() => {
location.reload();
})
} else {
alert("Please fill out all fields!");
}
$("#reserve-name").val("");
$("#reserve-email").val("");
});<file_sep>/db/schema.sql
DROP DATABASE IF EXISTS restaurant_db;
CREATE DATABASE restaurant_db;
USE restaurant_db;
CREATE TABLE reservations (
id INT NOT NULL AUTO_INCREMENT,
full_name VARCHAR(255) NOT NULL,
email VARCHAR (255) NOT NULL,
complete BOOLEAN DEFAULT false,
PRIMARY KEY (id)
);
|
a687e646493c0b63d31ac1488a5d97ae535efd3f
|
[
"JavaScript",
"SQL",
"Markdown"
] | 5 |
JavaScript
|
zachmartin9/hot-restaurant
|
c9764a25b414792c8302ebda89af82bdbcdeb6a6
|
473df85bddbeb2d79e02563d8824781133cd1a92
|
refs/heads/master
|
<repo_name>erdalceylan/InstagramPhotoPicker-Android<file_sep>/app/src/main/java/ly/kite/sample/MainActivity.java
package ly.kite.sample;
import android.app.Activity;
import android.content.Intent;
import android.os.Parcelable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import ly.kite.instagramphotopicker.InstagramPhoto;
import ly.kite.instagramphotopicker.InstagramPhotoPicker;
public class MainActivity extends ActionBarActivity {
private static final String CLIENT_ID = "aa314a392fdd4de7aa287a6614ea8897";
//private static final String REDIRECT_URI = "psapp://instagram-callback";
private static final String REDIRECT_URI = "http://instagram-callback";
private static final int REQUEST_CODE_INSTAGRAM_PICKER = 88;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonLaunchInstagramPickerClicked(View view) {
InstagramPhotoPicker.startPhotoPickerForResult(this, CLIENT_ID, REDIRECT_URI, REQUEST_CODE_INSTAGRAM_PICKER);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_INSTAGRAM_PICKER) {
if (resultCode == Activity.RESULT_OK) {
InstagramPhoto[] instagramPhotos = InstagramPhotoPicker.getResultPhotos(data);
Toast.makeText(this, "User selected " + instagramPhotos.length + " Instagram photos", Toast.LENGTH_SHORT).show();
for (int i = 0; i < instagramPhotos.length; ++i) {
Log.i("dbotha", "Photo: " + instagramPhotos[i].getFullURL());
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "Instagram Picking Cancelled", Toast.LENGTH_SHORT).show();
} else {
Log.i("dbotha", "Unknown result code: " + resultCode);
}
}
}
}
<file_sep>/README.md
# Android Instagram Photo Picker
A Instagram image picker providing a simple UI for a user to pick photos from their Instagram account.
It takes care of all authentication with Instagram as and when necessary. It will automatically renew auth tokens or prompt the user to re-authorize the app if needed.
## Video Preview
[](https://vimeo.com/135676657)
## Requirements
* Android API Level 14 - Android 4.0 (ICE_CREAM_SANDWICH)
## Installation
### Android Studio / Gradle
We publish builds of our library to the Maven central repository as an .aar file. This file contains all of the classes, resources, and configurations that you'll need to use the library. To install the library inside Android Studio, you can simply declare it as dependecy in your build.gradle file.
```java
dependencies {
compile 'ly.kite:instagram-photo-picker:1.+'
}
```
Once you've updated your build.gradle file, you can force Android Studio to sync with your new configuration by selecting Tools -> Android -> Sync Project with Gradle Files
This should download the aar dependency at which point you'll have access to the API calls. If it cannot find the dependency, you should make sure you've specified mavenCentral() as a repository in your build.gradle
## Usage
You need to have set up your application correctly to work with Instagram by registering a new Instagram application here: https://instagram.com/developer/ . For the redirect uri use something link `your-app-scheme://instagram-callback`.
To launch the Instagram Photo Picker:
```java
// Somewhere in an Activity:
import ly.kite.instagramphotopicker.InstagramPhoto;
import ly.kite.instagramphotopicker.InstagramPhotoPicker;
static final String CLIENT_ID = "YOUR_CLIENT_ID";
static final String REDIRECT_URI = "YOUR-APP-SCHEME://instagram-callback";
static final int REQUEST_CODE_INSTAGRAM_PICKER = 1;
InstagramPhotoPicker.startPhotoPickerForResult(this, CLIENT_ID, REDIRECT_URI, REQUEST_CODE_INSTAGRAM_PICKER);
```
Implement `onActivityResult`:
```java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_INSTAGRAM_PICKER) {
if (resultCode == Activity.RESULT_OK) {
InstagramPhoto[] instagramPhotos = InstagramPhotoPicker.getResultPhotos(data);
Log.i("dbotha", "User selected " + instagramPhotos.length + " Instagram photos");
for (int i = 0; i < instagramPhotos.length; ++i) {
Log.i("dbotha", "Photo: " + instagramPhotos[i].getFullURL());
}
}
}
}
```
### Sample Apps
The project is bundled with a Sample App to highlight the libraries usage.
## License
This project is available under the MIT license. See the [LICENSE](LICENSE) file for more info.
<file_sep>/settings.gradle
include ':app', ':instagramphotopicker'
|
1f8cdc9086d2137dcd39fd6ae1786d7e7cb9fdd5
|
[
"Markdown",
"Java",
"Gradle"
] | 3 |
Java
|
erdalceylan/InstagramPhotoPicker-Android
|
d6a94c1df99aff2439a16844012f79408dbecb5e
|
5265daa6c34dd4aa03110225df67c8ab2bdd44a9
|
refs/heads/master
|
<repo_name>Kazimbalti/AUTONOMOUS-MULTI-UAS-LAB-SETUP<file_sep>/Autonomous Multi-UAS/Base Computer/ros_ws/src/msral/scripts/ibc_image_receiver.py
#! /usr/bin/env python
'''
ibc_image_receiver.py
Written by <NAME>
Date: May 1, 2019
Subscribes to the 'ibc_cam_img' CompressedImage topic and displays
it with imshow.
The XY pixel location of a user's clicks are recorded and published
as a geometry_msgs/Point topic: 'ibc_img_click' with x,y being the
click location and z being the sequence number for the image topic.
NOTE: including the sequence number allows the click tracker
program to maintain a buffer of previous images to apply the image
projections from the clicked location on the actual image that was
clicked (to reduce errors due to latency of image transfer)
ROS Topic Published:
'ibc_img_click' (Point): XY click location, Z: img seq #
'''
import cv2
from geometry_msgs.msg import Point
import numpy as np
import rospy
from sensor_msgs.msg import CompressedImage
# *****************************************************************************
class VideoRecorder ( object ):
'''
Records images or videos from a RealSense Stream
'''
def __init__ (self):
pass
# -----------------------------------------------------------------------------
class IBCImageReceiver:
def __init__(self):
'''Initialize ROS and Publishers/Subscribers'''
rospy.init_node('image_receiver', anonymous=True)
rospy.loginfo('Initializing image_receiver...')
rospy.loginfo('Publishing /ibc_img_click...')
self.clickPub = rospy.Publisher("/ibc_img_click",
Point, queue_size=10)
rospy.loginfo('Subscribing to /ibc_cam_img/compressed...')
self.imgSub = rospy.Subscriber("/ibc_cam_img/compressed",
CompressedImage,
self.imgCB, queue_size = 1)
# Store the latest image sequence number
self.latestImg = None
# Store clicked pixel with image sequence number
self.clickPt = Point(x=-1, y=-1, z=-1)
cv2.namedWindow('I-BC Onboard Camera')
cv2.setMouseCallback("I-BC Onboard Camera", self.mouseCB)
def mouseCB(self, event, x, y, flags, param):
''' Handle OpenCV Mouse events '''
# Left mouse button released
if event == cv2.EVENT_LBUTTONUP:
# Check if a valid image has been received
if self.latestImg is not None:
self.clickPt.x = x
self.clickPt.y = y
self.clickPt.z = self.latestImg.header.seq
else:
self.clickPt.x = -1
self.clickPt.y = -1
self.clickPt.z = -1
# Publish the clicked point
self.clickPub.publish(self.clickPt)
# Right mouse button released (send -10, -10)
if event == cv2.EVENT_RBUTTONUP:
# Check if a valid image has been received
if self.latestImg is not None:
self.clickPt.x = -10
self.clickPt.y = -10
self.clickPt.z = self.latestImg.header.seq
else:
self.clickPt.x = -1
self.clickPt.y = -1
self.clickPt.z = -1
# Publish the clicked point
self.clickPub.publish(self.clickPt)
def imgCB(self, imgMsg):
'''Callback function for ibc_cam_img topic.
Decompresses images and displays with imshow'''
self.latestImg = imgMsg
# Decompress image and convert to CV2 format
np_arr = np.fromstring(imgMsg.data, np.uint8)
#image_np = cv2.imdecode(np_arr, cv2.CV_LOAD_IMAGE_COLOR)
image_np = cv2.imdecode(np_arr, cv2.IMREAD_COLOR) # OpenCV >= 3.0:
# Display image
cv2.imshow('I-BC Onboard Camera', image_np)
cv2.waitKey(2)
def run(self):
try:
rospy.spin()
except KeyboardInterrupt:
print "Shutting down ROS Image feature detector module"
cv2.destroyAllWindows()
if __name__ == '__main__':
receiver = IBCImageReceiver()
receiver.run()<file_sep>/UAV Initial Setup/Intel Aero Setup/Installing OpenCV.md
## Install OpenCV 3.4 (~1 hr)
* Reference: [OpenCV Docs](https://docs.opencv.org/3.4.3/d7/d9f/tutorial_linux_install.html)
* Full list of [CMake Options](https://github.com/opencv/opencv/blob/master/CMakeLists.txt#L198)
1. Install Dependencies
* General dependencies based on OpenCV Documentation
```
sudo apt install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev \
libavformat-dev libswscale-dev python-dev python-numpy libtbb2 libtbb-dev \
libjpeg-dev libjasper-dev libdc1394-22-dev checkinstall yasm libxine2-dev \
libv4l-dev libav-tools unzip libdc1394-22 libpng12-dev libtiff5-dev tar dtrx \
libopencore-amrnb-dev libopencore-amrwb-dev libtheora-dev libvorbis-dev \
libxvidcore-dev x264 libgstreamer0.10-dev libgstreamer-plugins-base0.10-dev \
libqt4-dev libmp3lame-dev
```
```
sudo apt install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev \
libavformat-dev libswscale-dev python-dev python-numpy libtbb2 libtbb-dev \
libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev \
libqt4-dev default-jdk
```
* Download OpenCV and OpenCV contrib source code
```
cd ~
mkdir OpenCV
cd OpenCV
git clone -b 3.4 --single-branch https://github.com/opencv/opencv.git
git clone -b 3.4 --single-branch https://github.com/opencv/opencv_contrib.git
```
* Build from source (~40 minutes)
```
cd ~/OpenCV/opencv
mkdir release
cd release
sudo cmake -D CMAKE_BUILD_TYPE=RELEASE -D BUILD_NEW_PYTHON_SUPPORT=ON -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_EXAMPLES=ON -D WITH_GTK=ON -D WITH_QT=ON -D WITH_GSTREAMER_0_10=ON -D WITH_TBB=ON -D BUILD_TBB=ON -D WITH_OPENGL-ES=ON -D WITH_V4L=ON -D CMAKE_INSTALL_PREFIX=/usr/local -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules ..
sudo make -j4
sudo make install
```
* Create config file (if it doesn't exist)
* `sudo nano /etc/ld.so.conf.d/opencv.conf`
* Add `/usr/local/lib/` to the file
* `sudo ldconfig`
* Test installation with Python
```
python
import cv2
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
```
* If Needed, Remove OpenCV source to free up storage
* `sudo rm -r ~/OpenCV/opencv/release`
* OR
* `sudo rm -r ~/OpenCV`
<file_sep>/Autonomous Multi-UAS/README.md
# AUTONOMOUS MULTI-UAS CODE
This directory holds all the key files we used to operate 2+ UAVs autonomously using a variety of tools including:
ROS
Python
C++
PX4
Mavros
MAVlink
QGC
This repository includes a ROS workspace folder we created and used to run all of the relevent programs for operating our multi-UAS platform such as code for:
* Streaming vicon data on ROS
* Running mavros natively on each UAS
* Python Scripts for autonomous flight
## Preflight Checks
1. Make sure your UAS is in shape to fly, check for damage, or lose connections etc.
2. Make sure your batteries are fully charged and you never fly with a battery charge below ___%
## The following steps show how to use the code provided to operate 2+ autonomous UAVs:
1. Start up the Vicon system
* Power on Vicon system, and computer running Vicon Nexus software.
* Make sure this computer is connected to the same network as all other machines such as the base station computer and UAVs.
* Use "ifconfig" to verify the IP of the computer to use for later.
* Open and configure Nexus software to start streaming position data.
2. Run roscore on the Base Station computer.
* ```
roscore
```
3. Start streaming the vicon data over the "/mavros/vision_pose/pose" rostopic
* ```
roslaunch msral vicon_stream_multi.launch ip:="IP_OF_COMPUTER_RUNNING_NEXUS"
```
4. Stop logging flight data on each UAV (this will also momentarily stop communication with QGC).
* ssh into the UAV
* ```
ssh hostname@ip_adress
```
* Stop the mavlink router
* ```
sudo systemctl stop mavlink-router
```
* Note: You may wish to check your flight log files, save or extract important ones and clear out the rest.
5. Start logging flight data on each UAV when you are ready to begin the test (this will also restart communication with QGC).
* ssh into the UAV
* ```
ssh hostname@ip_adress
```
* Stop the mavlink router
* ```
sudo systemctl start mavlink-router
```
* Note: You may wish to check your flight log files, save or extract important ones and clear out the rest. Flight logs are stored on the UAV at '/var/lib/mavlink-router' .
5. Verify that your vehicle is connected to QGC.
6. Start Mavros on each UAV you plan to fly
* ```
roslaunch msral mavros.launch
```
7. Run your autonomous UAS python/C script that publishes flight commands and waypoints over rostopics on the base station computer.
## Emergency Actions
*
<file_sep>/UAV Initial Setup/Intel Aero Setup/Troubleshooting.md
# Troubleshooting
* If Drone does not power off when pressing and holding power button, just disconnect power supply, wait 30 seconds and reconnect power
<file_sep>/UAV Initial Setup/Intel Aero Setup/Video4Linux Webcam Driver Usage.md
## Video4Linux Webcam Driver Usage
* Show available options for webcam
* `v4l2-ctl --list-formats-ext` (shows options, with associated fps)
* Set video output format
* `v4l2-ctl --set-fmt-video=width=1920,height=1080,pixelformat=YUYV`
* Show video capture options
* `v4l2-ctl --help-vidcap (shows video capture options)`
* Automatically configure webcam on plug-in
* Create udev rule in `/etc/udev/rules.d/99-webcam.rules`
* `udevadm info --attribute-walk --name /dev/video0`
* `SUBSYSTEM=="video4linux", SUBSYSTEMS=="usb", ATTRS{idVendor}=="05a3", ATTRS{idProduct}=="9230", PROGRAM="/usr/bin/v4l2-ctl --set-fmt-video=width=640,height=480,pixelformat=MJPG --device /dev/%k"`
<file_sep>/UAV Initial Setup/UVify Draco-R Setup/Installing ROS Melodic.md
## Install ROS melodic (~20 minutes)
* Follow [these instructions](http://wiki.ros.org/melodic/Installation/Ubuntu)
1. Set up
```
sudo add-apt-repository http://packages.ros.org/ros/ubuntu
sudo apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net --recv-key 0<KEY>
sudo apt update
```
* Install ROS desktop version and additional packages
```
sudo apt -y install ros-melodic-desktop-full ros-melodic-rqt python-rosinstall \
ros-melodic-realsense-camera ros-melodic-mavros ros-melodic-web-video-server \
ros-melodic-visp-tracker ros-melodic-visp-camera-calibration ros-melodic-vision-visp \
ros-melodic-vision-opencv ros-melodic-video-stream-opencv ros-melodic-uvc-camera \
ros-melodic-usb-cam ros-melodic-test-mavros ros-melodic-rviz-visual-tools \
ros-melodic-rostopic ros-melodic-roslaunch python-rosinstall python-rosinstall-generator \
python-wstool build-essential ros-melodic-pyros python-rosdep
sudo rosdep init
rosdep update
sudo geographiclib-get-geoids egm96-5
sudo apt autoremove
```
* Create Catkin workspace
```
source /opt/ros/melodic/setup.bash
mkdir -p ~/ros_ws/src
cd ~/ros_ws/
catkin_make
```
* Set up ROS Environment (auto-load in bashrc)
```
su
echo "# ROS Settings" | tee -a /home/intel2/.bashrc > /dev/null
echo "source /opt/ros/melodic/setup.bash" | tee -a /home/intel2/.bashrc > /dev/null
echo "source /home/intel2/ros_ws/devel/setup.bash" | tee -a /home/intel2/.bashrc > /dev/null
echo "export ROS_MASTER_URI=http://localhost:11311" | tee -a /home/intel2/.bashrc > /dev/null
echo "#export ROS_MASTER_URI=http://192.168.1.88:11311" | tee -a /home/intel2/.bashrc > /dev/null
echo "#export ROS_IP=192.168.1.122" | tee -a /home/intel2/.bashrc > /dev/null
exit
```
* Set up for 3D Mapping and Path-Planning
* Install [OctoMap](https://www.ros.org/wiki/octomap_server)
* `sudo apt install ros-melodic-octomap-server`
* Install [rtabmap_ros](http://wiki.ros.org/rtabmap_ros)
* `sudo apt install ros-melodic-rtabmap-ros`
* Create a custom package
* ```
cd ~/ros_ws/src/
catkin_create_pkg my_package rospy roscpp std_msgs geometry_msgs sensor_msgs cv_bridge
```
* Build only one or more specified package(s)
* List packages to build, separated by ';'
* `catkin_make -DCATKIN_WHITELIST_PACKAGES="pkg1;pkg2"`
<file_sep>/Autonomous Multi-UAS/Base Computer/ros_ws/src/msral/scripts/set_home.py
#!/usr/bin/env python
import rospy
from mavros_msgs.msg import HomePosition
from geometry_msgs.msg import Point, PoseStamped, Quaternion
viconDat = None
def viconCB(msg):
global viconDat
viconDat = msg
rospy.init_node('set_home_node', anonymous = True)
rospy.loginfo("Publishing: '/mavros/home_position/set'")
rospy.Subscriber('/mavros/vision_pose/pose', PoseStamped, viconCB)
# Publish home position
pubHome = rospy.Publisher('/mavros/home_position/set', HomePosition, queue_size=10)
rate = rospy.Rate(1)
while not rospy.is_shutdown():
#if viconDat is not None:
if viconDat is None:
msg = HomePosition()
#msg.position = #viconDat.pose.position
#msg.orientation = #viconDat.pose.orientation
msg.header.stamp = rospy.Time.now()
pubHome.publish(msg)
<file_sep>/UAV Initial Setup/Intel Aero Setup/Installing ROS Kinetic.md
## Install ROS Kinetic (~20 minutes)
* Follow [these instructions](https://github.com/intel-aero/meta-intel-aero/wiki/05-Autonomous-drone-programming-with-ROS)
1. Set up
```
sudo add-apt-repository http://packages.ros.org/ros/ubuntu
sudo apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net --recv-key 0<KEY>
sudo apt update
```
* Install ROS desktop version and additional packages
```
sudo apt -y install ros-kinetic-desktop-full ros-kinetic-rqt python-rosinstall \
ros-kinetic-realsense-camera ros-kinetic-mavros ros-kinetic-web-video-server \
ros-kinetic-visp-tracker ros-kinetic-visp-camera-calibration ros-kinetic-vision-visp \
ros-kinetic-vision-opencv ros-kinetic-video-stream-opencv ros-kinetic-uvc-camera \
ros-kinetic-usb-cam ros-kinetic-test-mavros ros-kinetic-rviz-visual-tools \
ros-kinetic-rostopic ros-kinetic-roslaunch python-rosinstall python-rosinstall-generator \
python-wstool build-essential ros-kinetic-pyros python-rosdep
sudo rosdep init
rosdep update
sudo geographiclib-get-geoids egm96-5
sudo apt autoremove
```
* Create Catkin workspace
```
source /opt/ros/kinetic/setup.bash
mkdir -p ~/ros_ws/src
cd ~/ros_ws/
catkin_make
```
* Set up ROS Environment (auto-load in bashrc)
```
su
echo "# ROS Settings" | tee -a /home/intel2/.bashrc > /dev/null
echo "source /opt/ros/kinetic/setup.bash" | tee -a /home/intel2/.bashrc > /dev/null
echo "source /home/intel2/ros_ws/devel/setup.bash" | tee -a /home/intel2/.bashrc > /dev/null
echo "export ROS_MASTER_URI=http://localhost:11311" | tee -a /home/intel2/.bashrc > /dev/null
echo "#export ROS_MASTER_URI=http://192.168.1.88:11311" | tee -a /home/intel2/.bashrc > /dev/null
echo "#export ROS_IP=192.168.1.122" | tee -a /home/intel2/.bashrc > /dev/null
exit
```
* Set up for 3D Mapping and Path-Planning
* Install [OctoMap](https://www.ros.org/wiki/octomap_server)
* `sudo apt install ros-kinetic-octomap-server`
* Install [rtabmap_ros](http://wiki.ros.org/rtabmap_ros)
* `sudo apt install ros-kinetic-rtabmap-ros`
* Create a custom package
* ```
cd ~/ros_ws/src/
catkin_create_pkg my_package rospy roscpp std_msgs geometry_msgs sensor_msgs cv_bridge
```
* Build only one or more specified package(s)
* List packages to build, separated by ';'
* `catkin_make -DCATKIN_WHITELIST_PACKAGES="pkg1;pkg2"`
<file_sep>/UAV Initial Setup/Intel Aero Setup/Access Intel Aero Cameras.md
## Accessing Camera Feeds
* Reference [06 Cameras and Video](https://github.com/intel-aero/meta-intel-aero/wiki/06-Cameras-and-Video)
* The camera data is streaming through the camera streaming daemon ([csd](https://github.com/intel-aero/meta-intel-aero/wiki/90-(References)-OS-user-Installation#intel-camera-streaming-daemon))
* Use `sudo systemctl stop/start/restart csd` to control the daemon
* NOTE: This is separate from the `systemctl stop/start/restart mavlink-router` which streams flight data
* The UDP endpoint for this can be configured in `/etc/mavlink-router/config.d/qgc.conf`
* Troubleshooting:
* "UVCIOC_CTRL_QUERY:UVC_GET_CUR error 5"
* This is likely because some other process is using the camera(s)
* e.g. `sudo systemctl stop csd` will stop camera streaming daemon
* Save camera setting defaults to file:
*
```
sudo v4l2-ctl --list-devices
mkdir ~/R200_settings/
v4l2-ctl --list-ctrls -d /dev/video13 > ~/R200_settings/video13.txt
```
* Recording Video (based on [these instructions](https://github.com/intel-aero/meta-intel-aero/wiki/06-Cameras-and-Video#record-video))
* Create bash function for easy access as "aero_record":
```
# Record R200 video based on GitHub Tutorials for Aero
# USAGE: 'aero_record <device> <width> <height> <output_filename>'
# e.g. 'aero_record /dev/video13 1920 1080 encoded_video'
function aero_record() {
sudo gst-launch-1.0 -e v4l2src device=$1 num-buffers=2000 ! autovideoconvert format=i420 width=$2 height=$3 framerate=30/1 ! vaapih264enc rate-control=cbr tune=high-compression ! qtmux ! filesink location=$4.mp4
ffmpeg -i $4.mp4
}
```
<file_sep>/UAV Initial Setup/readme.md
# UAV Setup
## Intel Aero RTF Drone Setup
### Familiarize yourself with the following resources and documentation from the main Intel Aero github: https://github.com/intel-aero/meta-intel-aero/wiki
* [About Intel Aero](https://github.com/intel-aero/meta-intel-aero/wiki/01-About-Intel-Aero)
* [First Flight with Receiver](https://github.com/intel-aero/meta-intel-aero/wiki/03-First-flight)
* [Initial Setup](https://github.com/intel-aero/meta-intel-aero/wiki/02-Initial-setup)
* [Installing Ubuntu](https://github.com/intel-aero/meta-intel-aero/wiki/90-(References)-OS-user-Installation)
* [Autonomous drone programming with ROS](https://github.com/intel-aero/meta-intel-aero/wiki/05-Autonomous-drone-programming-with-ROS)
* [Autonomous drone programming in Python](https://github.com/intel-aero/meta-intel-aero/wiki/04-Autonomous-drone-programming-in-Python)
1. Test fly your drone out of the box to ensure it is functioning properly.
2. [Update Yocto](https://github.com/nadiamcoleman/AUTONOMOUS-MULTI-UAS-LAB-SETUP/blob/master/UAV%20Initial%20Setup/Intel%20Aero%20Setup/Update%20Yocto.md)
3. Test fly your drone again to to ensure it is functioning properly.
4. [Install Ubuntu](https://github.com/nadiamcoleman/AUTONOMOUS-MULTI-UAS-LAB-SETUP/blob/master/UAV%20Initial%20Setup/Intel%20Aero%20Setup/Installing%20ROS%20Kinetic.md)
5. Test fly your drone again to to ensure it is functioning properly.
6. Install [ROS](http://wiki.ros.org/ROS/Installation)
## UVify Draco-R Setup
### Familiarize yourself with the resources and documentation provided.
1. Test fly your drone out of the box to ensure it is functioning properly.
2. Our Draco-R platforms came with Ubuntu and PX4 firmware already installed so we can move on to installing ROS.
3. Install [ROS](http://wiki.ros.org/ROS/Installation)
4. Install and configure [MAVLink router](https://github.com/intel/mavlink-router).
<file_sep>/Autonomous Multi-UAS/Base Computer/ros_ws/src/msral/scripts/pos_est_analyzer.py
#!/usr/bin/env python
'''
pos_est_analyzer.py
Written by <NAME>
Date: March 25, 2019
Subscribes to position estimation topics (Vicon and PX4:EKF2) and
calculates the error in the estimated PX4:EKF2 position/orientation.
Also subscribes to estimated clicked target position and tracks the
error in that position estimation.
'''
import rospy
import signal
from std_msgs.msg import String
from geometry_msgs.msg import PoseStamped
from mavros_msgs.msg import State, ActuatorControl
from mavros_msgs.srv import CommandBool, SetMode, CommandTOL
import readline
import time
import threading as th
class PosEstAnalyzer( object ):
def __init__(self):
pass
# ------------------ Initialize ROS ---------------------
rospy.init_node('pos_est_analyzer', anonymous=True)
rospy.loginfo("Subscribing to:\n '/mavros/setpoint_position/local'" \
+ ", '/mavros/actuator_control'")
# Initialize publisher for mavros setpoint (required for OFFBOARD mode)
pub_pose_sp = rospy.Publisher('/mavros/setpoint_position/local', \
PoseStamped, queue_size=10)
# Initialize publisher for actuator_control (to drive Boom-Prop)
pub_act_control = rospy.Publisher('/mavros/actuator_control', \
ActuatorControl, queue_size=10)
# ------------------ Subscribe to data streams ---------------------
rospy.Subscriber('mavros/state', State, state_cb)
# Get the MAVROS state
def state_cb(msg):
global cur_state
cur_state = msg
def setpoint_thread_cb(thread_name):
global pub_pose_sp, pose_sp
rate = rospy.Rate(20)
while not rospy.is_shutdown():
pub_pose_sp.publish(pose_sp)
rate.sleep()
# Main Publishing Function
def run():
global cur_state, pub_act_control, pub_pose_sp, pose_sp
# Initialize ROS
rospy.init_node('offboard_controller', anonymous=True)
rospy.loginfo("Publishing:\n '/mavros/setpoint_position/local'" \
+ ", '/mavros/actuator_control'")
# Initialize publisher for mavros setpoint (required for OFFBOARD mode)
pub_pose_sp = rospy.Publisher('/mavros/setpoint_position/local', \
PoseStamped, queue_size=10)
# Initialize publisher for actuator_control (to drive Boom-Prop)
pub_act_control = rospy.Publisher('/mavros/actuator_control', \
ActuatorControl, queue_size=10)
# ------------------ Subscribe to data streams ---------------------
rospy.Subscriber('mavros/state', State, state_cb)
#t = th.Thread(setpoint_thread_cb, 'thread-name')
#t.start()
# Setpoint publishing rate MUST be faster than 2Hz
rate = rospy.Rate(20.0)
# Wait for FCU connection
while(not rospy.is_shutdown() and (cur_state is None or not cur_state.connected)):
rospy.logwarn('Waiting for FCU connection...')
rate.sleep()
# Set up MAVROS services (for arming and setting flight mode)
rospy.wait_for_service('mavros/cmd/arming')
rospy.wait_for_service('mavros/set_mode')
rospy.wait_for_service('mavros/cmd/takeoff')
rospy.wait_for_service('mavros/cmd/land')
try:
arm = rospy.ServiceProxy('mavros/cmd/arming', CommandBool)
setMode = rospy.ServiceProxy('mavros/set_mode', SetMode)
except rospy.ServiceException, e:
print "Service call failed: %s" % e
# Prepare service calls
#arm_cmd = CommandBool()
#arm_cmd.request.value = True
#mode_cmd = SetMode()
#mode_cmd
# Prepare dummy pose sp
#send a few setpoints before starting
#pList = 10*[PoseStamped()]
pose_sp = PoseStamped()
pose_sp.pose.position.x = 5
pose_sp.pose.position.y = 2
pose_sp.pose.position.z = 2
actuator_sp = ActuatorControl()
actuator_sp.controls[5] = 0.5
actuator_sp.group_mix = ActuatorControl.PX4_MIX_MANUAL_PASSTHROUGH
i = 50
while (not rospy.is_shutdown()) and i > 0:
pub_pose_sp.publish(pose_sp);
i = i - 1
rate.sleep()
# Loop until ROS Shutdown
last_request = time.time()
while not rospy.is_shutdown():
#rospy.loginfo('state: ' + cur_state.mode)
if( cur_state.mode != "OFFBOARD" and (time.time() - last_request > 1)):
rospy.loginfo('attempting OFFBOARD')
success = setMode(custom_mode="OFFBOARD")
if( success and True ):# offb_set_mode.response.mode_sent){
rospy.loginfo("Offboard enabled")
last_request = time.time()
else:
if( not cur_state.armed and (time.time()- last_request > 1)):
rospy.loginfo('attempting ARM')
success = arm(True)
if( success and True ): #arm_cmd.response.success){
rospy.loginfo("Vehicle armed")
last_request = time.time()
pub_pose_sp.publish(pose_sp)
#actuator_sp.controls[5] = 0.5
#pub_act_control.publish(actuator_sp)
rate.sleep()
#try:
# userIN = raw_input("Type a gripper control command: \n"
# + " g<num>\n")
# pub_grip_cont.publish(userIN)
#except KeyboardInterrupt:
# break
rospy.loginfo("offboard_controller exiting...")
if __name__ == '__main__':
run()
<file_sep>/Autonomous Multi-UAS/Base Computer/ros_ws/src/msral/src/README.md
# Here is where the C++ scripts for streaming Vicon position data live.
<file_sep>/README.md
# AUTONOMOUS MULTI-UAS LAB SETUP
This repository contains information and files for setting up an autonomous multi-UAS laboratory. Two research based unmanned aerial vehicle platforms were used in our multi-UAS lab setup however these instructions can be apllied to a multitude of platforms. The two platforms we used were the Intel Aero RTF Drone, and the UVify Draco-R. This repo will include hardware information, software information and code that we used to setup our autonomous multi-UAS laboratory.
## Equipment Used
### UAS platforms:
1. 2 x [Intel Aero RTF Quadcopter](https://www.intel.com/content/www/us/en/support/articles/000023271/drones/development-drones.html "info and specs")
* [Ubuntu 16.04.3 LTS](https://ubuntu.com/download/alternative-downloads)
* [PX4](https://px4.io) [Firmware 1.8.2](https://github.com/PX4/Firmware/tree/v1.8.2)
* [ROS Kinetic](http://wiki.ros.org/kinetic)
2. 2 x [Draco-R Hexacopter](https://www.uvify.com/draco-r/ "info and specs")
* [Ubuntu 18.04.3 LTS](https://ubuntu.com/download/alternative-downloads)
* [PX4](https://px4.io) [Firmware 1.9.0](https://github.com/PX4/Firmware/tree/v1.9.0)
* [ROS Melodic](http://wiki.ros.org/melodic)
Note: These are the UAVs we chose to use however the processes described in this guide can be applied to a multitude of UAV platforms so long as they are PX4 firmware and Linux based.
3. Power Supplies
* 2 x 4S Lipo battery with XT60 connector
* 2 x UVify 4S Lipo battery
* 2 x [Wall power adapter](https://www.amazon.com/LEDMO-Power-Supply-Transformers-Adapter/dp/B01461MOGQ/ref=sr_1_3_sspa?keywords=12V+5A+Power+Adapter&qid=1567702141&refinements=p_72%3A1248909011&rnid=1248907011&s=hi&sr=1-3-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyWUtYRVhZN0JPM0lHJmVuY3J5cHRlZElkPUEwODU1MTU5MUFQMjJZSFc5VkZESiZlbmNyeXB0ZWRBZElkPUEwMzEyMTU5MkxBUTNTREg2VjlEMyZ3aWRnZXROYW1lPXNwX2F0ZiZhY3Rpb249Y2xpY2tSZWRpcmVjdCZkb05vdExvZ0NsaWNrPXRydWU=)
4. Miscellaneous
* HDMI Capable Computer Monitor
* Micro-HDMI to HDMI cable
* Mini-HDMI to HDMI cable
* Self-powered, 4 port, USB Hub
* Keyboard
* USB mouse
* USB drive (minimum 2GB)
### Desktop Computers:
1. Base Station Computer
* [Ubuntu 18.04.3 LTS](https://ubuntu.com/download/alternative-downloads)
* [ROS Melodic](http://wiki.ros.org/melodic)
2. Vicon Base Computer
* Windows Vista
* Vicon Nexus Software
* Vicon Tracker Software
### Motion Capture System
1. [Vicon Motion Capture System](https://www.vicon.com)
* 12 Vicon T160 motion/position tracking cameras.
### Asus Wifi Router
* DCHP server setup for static IP addressing for all aforementioned machines.
### Netted Lab Space
* Dimensions: 43' x 28' x 20'
# How to Setup an Autonomous Multi-UAS Laboratory
1. The first step to buidling your own UAV lab starts with router setup, netted area setup, and Vicon setup.
You will want a good size netted area space to fly in. You will also want some guidlines and saftey rules for operations inside the space.
2. You will also want some kind of motion capture system. One of the most widely used systems is the Vicon motion capture system which is the system we utilized for our platform. We will not cover specific instructions for setting up the entirety of the Vicon system however we will offer guidance on how to stream vicon position data using ROS. The basics of the Vicon system include the system itself i.e. cameras, markers, other hardware and also a computer, in our case, windows with the neccessary software (Nexus, and Tracker).
3. Next you need a wifi router, with both wireless and wired capability (wifi and ethernet). You will need to set up a DHCP server so that you can assign static IPs for all the machines you will use such as computers, UAVs, or other robotic system.
4. Next you will need an Ubuntu machine to serve as the "base station" for all your ROS communications. This computer will be the control center that sends out all control commands in the form of rostopic messages and also routes position data from the computer running the Vicon software
5. After all the previous conditions have been met you can start to setup your UAS platforms by following the intructions here:
https://github.com/nadiamcoleman/AUTONOMOUS-MULTI-UAS-LAB-SETUP/tree/master/UAV%20Initial%20Setup
<file_sep>/UAV Initial Setup/Intel Aero Setup/Installing Python Packages.md
## Installing Python Packages (if not already installed...)
1. [**Pip**](https://pip.pypa.io/en/stable/installing/)
* ```
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
sudo python get-pip.py
```
* **PySerial** (for Python access to serial ports)
* `sudo python -m pip install pyserial`
<file_sep>/Autonomous Multi-UAS/Base Computer/ros_ws/src/msral/scripts/offboard_ctl_square_path.py
#!/usr/bin/env python
# ROS python API
import rospy
# 3D point & Stamped Pose msgs
from geometry_msgs.msg import Point, PoseStamped
# import all mavros messages and services
from mavros_msgs.msg import *
from mavros_msgs.srv import *
import time
# Flight modes class
# Flight modes are activated using ROS services
class fcuModes:
def __init__(self):
pass
def setArm(self):
rospy.wait_for_service('/mavros/cmd/arming')
try:
armService = rospy.ServiceProxy('/mavros/cmd/arming', mavros_msgs.srv.CommandBool)
response = armService(True)
return response.success
except rospy.ServiceException, e:
print "Service arming call failed: %s"%e
return False
def setDisarm(self):
rospy.wait_for_service('/mavros/cmd/arming')
try:
armService = rospy.ServiceProxy('/mavros/cmd/arming', mavros_msgs.srv.CommandBool)
response = armService(False)
return response.success
except rospy.ServiceException, e:
print "Service disarming call failed: %s"%e
return False
def setStabilizedMode(self):
rospy.wait_for_service('/mavros/set_mode')
try:
flightModeService = rospy.ServiceProxy('/mavros/set_mode', mavros_msgs.srv.SetMode)
response = flightModeService(custom_mode='STABILIZED')
return response.mode_sent
except rospy.ServiceException, e:
print "service set_mode call failed: %s. Stabilized Mode could not be set."%e
return False
def setOffboardMode(self):
rospy.wait_for_service('/mavros/set_mode')
try:
flightModeService = rospy.ServiceProxy('/mavros/set_mode', mavros_msgs.srv.SetMode)
response = flightModeService(custom_mode='OFFBOARD')
return response.mode_sent
except rospy.ServiceException, e:
print "service set_mode call failed: %s. Offboard Mode could not be set."%e
return False
def setAltitudeMode(self):
rospy.wait_for_service('/mavros/set_mode')
try:
flightModeService = rospy.ServiceProxy('/mavros/set_mode', mavros_msgs.srv.SetMode)
response = flightModeService(custom_mode='ALTCTL')
return response.mode_sent
except rospy.ServiceException, e:
print "service set_mode call failed: %s. Altitude Mode could not be set."%e
return False
def setPositionMode(self):
rospy.wait_for_service('/mavros/set_mode')
try:
flightModeService = rospy.ServiceProxy('/mavros/set_mode', mavros_msgs.srv.SetMode)
response = flightModeService(custom_mode='POSCTL')
return response.mode_sent
except rospy.ServiceException, e:
print "service set_mode call failed: %s. Position Mode could not be set."%e
return False
def setAutoLandMode(self):
rospy.wait_for_service('/mavros/set_mode')
try:
flightModeService = rospy.ServiceProxy('/mavros/set_mode', mavros_msgs.srv.SetMode)
response = flightModeService(custom_mode='AUTO.LAND')
return response.mode_sent
except rospy.ServiceException, e:
print "service set_mode call failed: %s. Autoland Mode could not be set."%e
return False
# Main class: Converts joystick commands to position setpoints
class Controller:
# initialization method
def __init__(self):
# Drone state
self.state = State()
# Altitude setpoint, [meters]
self.ALT_SP = 1
# Instantiate setpoint messages
self.sp = PoseStamped()
self.home_sp = PoseStamped()
self.home_sp.pose.position.x = 0
self.home_sp.pose.position.y = 0
self.home_sp.pose.position.z = self.ALT_SP
self.sp.pose.position.x = 0
self.sp.pose.position.y = 0
self.sp.pose.position.z = self.ALT_SP
# A Message for the current local position of the drone
self.local_pos = Point(0.0, 0.0, 0.0)
# Handler to set FCU modes
self.modes = fcuModes()
# Create waypoints for path traversal
self.wp_pose = PoseStamped()
self.wp_pose.pose.position.z = self.ALT_SP
self.waypoints = []
self.waypoints.append([0.0, 0.5])
self.waypoints.append([0.0, -0.5])
self.waypoints.append([-1.0, -0.5])
self.waypoints.append([-1.0, 0.5])
# Waypoint control variables
self.wp_started = False
self.wp_finished = False
self.wp_timer = 0
self.wp_index = 0
# Callbacks
## local position callback
def posCb(self, msg):
self.local_pos.x = msg.pose.position.x
self.local_pos.y = msg.pose.position.y
self.local_pos.z = msg.pose.position.z
## Drone State callback
def stateCb(self, msg):
self.state = msg
## Update setpoint message
def updateSp(self):
self.sp.header.stamp = rospy.Time.now()
#self.sp.pose.position.x = self.local_pos.x + self.STEP_SIZE*x
#self.sp.pose.position.y = self.local_pos.y + self.STEP_SIZE*y
# Main function
def main():
# Initiate node
rospy.init_node('offboard_ctl_node', anonymous=True)
# Drone controller object
cnt = Controller()
# ROS loop rate, [Hz]
rate = rospy.Rate(20.0)
# Subscribe to drone state
rospy.Subscriber('/mavros/state', State, cnt.stateCb)
# Subscribe to drone's local position
rospy.Subscriber('/mavros/local_position/pose', PoseStamped, cnt.posCb)
# Setpoint publisher
sp_pub = rospy.Publisher('/mavros/setpoint_position/local', PoseStamped, queue_size=1)
# Send some setpoint messages to activate OFFBOARD mode
rospy.loginfo('Sending 20 setpoints...')
i=0
while i<20:
sp_pub.publish(cnt.home_sp)
rate.sleep()
i = i+1
# Arm the vehicle
rospy.loginfo('Arming...')
cnt.modes.setArm()
# Activate OFFBOARD mode
rospy.loginfo('Switching to OFFBOARD mode...')
cnt.modes.setOffboardMode()
# ROS main loop
loop_t = time.time()
landing = False
ground_count = 0 # Count number of times position reports on ground
rospy.loginfo('Streaming home_sp at 20 Hz...')
while not rospy.is_shutdown():
# Start waypoint path following
if(not cnt.wp_started):
cnt.wp_started = True
cnt.wp_index = 0
cnt.wp_timer = time.time()
# Update waypoint index every 5 seconds
if(time.time() - cnt.wp_timer > 8):
cnt.wp_index += 1
cnt.wp_timer = time.time() # Update wp timer
# Land at end of path (4 waypoints)
if(cnt.wp_index > 0):
cnt.wp_finished = True
# Land at end of path (4 waypoints)
if cnt.wp_finished:
if not landing:
cnt.modes.setAutoLandMode()
landing = True
else:
if cnt.local_pos.z < 0.3:
ground_count += 1
if ground_count >= 20:
cnt.modes.setDisarm()
break
else:
# Set current waypoint based on index
cnt.wp_pose.pose.position.x = cnt.waypoints[cnt.wp_index][0];
cnt.wp_pose.pose.position.y = cnt.waypoints[cnt.wp_index][1];
sp_pub.publish(cnt.wp_pose)
rate.sleep()
# Land the drone if CTRL+C
cnt.modes.setAutoLandMode()
if __name__ == '__main__':
try:
main()
except rospy.ROSInterruptException:
pass<file_sep>/Autonomous Multi-UAS/Vicon/README.md
# Vicon code
<file_sep>/Autonomous Multi-UAS/Base Computer/ros_ws/src/msral/scripts/multi_offboard_ctl_HAPP_test.py
#!/usr/bin/env python
# ROS python API
import rospy
# 3D point & Stamped Pose msgs
from geometry_msgs.msg import Point, PoseStamped
# import all mavros messages and services
from mavros_msgs.msg import *
from mavros_msgs.srv import *
import time
# Flight modes class
# Flight modes are activated using ROS services
class fcuModes:
def __init__(self):
pass
def setArm(self):
rospy.wait_for_service('/intel1/mavros/cmd/arming')
rospy.wait_for_service('/uvify1/mavros/cmd/arming')
try:
armService1 = rospy.ServiceProxy('/intel1/mavros/cmd/arming', mavros_msgs.srv.CommandBool)
armService2 = rospy.ServiceProxy('/uvify1/mavros/cmd/arming', mavros_msgs.srv.CommandBool)
response1 = armService1(True)
response2 = armService2(True)
return response1.success,response2.success
except rospy.ServiceException, e:
print "Service arming call failed: %s"%e
return False,False
def setDisarm(self):
rospy.wait_for_service('/intel1/mavros/cmd/arming')
rospy.wait_for_service('/uvify1/mavros/cmd/arming')
try:
armService1 = rospy.ServiceProxy('/intel1/mavros/cmd/arming', mavros_msgs.srv.CommandBool)
armService2 = rospy.ServiceProxy('/uvify1/mavros/cmd/arming', mavros_msgs.srv.CommandBool)
response1 = armService1(False)
response2 = armService2(False)
return response1.success,response2.success
except rospy.ServiceException, e:
print "Service disarming call failed: %s"%e
return False,False
rospy.loginfo('Streaming home_sp at 20 Hz...')
def setStabilizedMode(self):
rospy.wait_for_service('/intel1/mavros/set_mode')
rospy.wait_for_service('/uvify1/mavros/set_mode')
try:
flightModeService1 = rospy.ServiceProxy('/intel1/mavros/set_mode', mavros_msgs.srv.SetMode)
flightModeService2 = rospy.ServiceProxy('/uvify1/mavros/set_mode', mavros_msgs.srv.SetMode)
response1 = flightModeService1(custom_mode='STABILIZED')
response2 = flightModeService2(custom_mode='STABILIZED')
return response1.mode_sent,response2.mode_sent
except rospy.ServiceException, e:
print "service set_mode call failed: %s. Stabilized Mode could not be set."%e
return False,False
def setOffboardMode(self):
rospy.wait_for_service('/intel1/mavros/set_mode')
rospy.wait_for_service('/uvify1/mavros/set_mode')
try:
flightModeService1 = rospy.ServiceProxy('/intel1/mavros/set_mode', mavros_msgs.srv.SetMode)
flightModeService2 = rospy.ServiceProxy('/uvify1/mavros/set_mode', mavros_msgs.srv.SetMode)
response1 = flightModeService1(custom_mode='OFFBOARD')
response2 = flightModeService2(custom_mode='OFFBOARD')
return response1.mode_sent,response2.mode_sent
except rospy.ServiceException, e:
print "service set_mode call failed: %s. Offboard Mode could not be set."%e
return False,False
def setAltitudeMode(self):
rospy.wait_for_service('/intel1/mavros/set_mode')
rospy.wait_for_service('/uvify1/mavros/set_mode')
try:
flightModeService1 = rospy.ServiceProxy('/intel1/mavros/set_mode', mavros_msgs.srv.SetMode)
flightModeService2 = rospy.ServiceProxy('/uvify1/mavros/set_mode', mavros_msgs.srv.SetMode)
response1 = flightModeService1(custom_mode='ALTCTL')
response2 = flightModeService2(custom_mode='ALTCTL')
return response1.mode_sent,response2.mode_sent
except rospy.ServiceException, e:
print "service set_mode call failed: %s. Altitude Mode could not be set."%e
return False,False
def setPositionMode(self):
rospy.wait_for_service('/intel1/mavros/set_mode')
rospy.wait_for_service('/uvify1/mavros/set_mode')
try:
flightModeService1 = rospy.ServiceProxy('/intel1/mavros/set_mode', mavros_msgs.srv.SetMode)
flightModeService2 = rospy.ServiceProxy('/uvify1/mavros/set_mode', mavros_msgs.srv.SetMode)
response1 = flightModeService1(custom_mode='POSCTL')
response2 = flightModeService2(custom_mode='POSCTL')
return response1.mode_sent,response2.mode_sent
except rospy.ServiceException, e:
print "service set_mode call failed: %s. Position Mode could not be set."%e
return False,False
def setAutoLandMode(self):
rospy.wait_for_service('/intel1/mavros/set_mode')
rospy.wait_for_service('/uvify1/mavros/set_mode')
try:
flightModeService1 = rospy.ServiceProxy('/intel1/mavros/set_mode', mavros_msgs.srv.SetMode)
flightModeService2 = rospy.ServiceProxy('/uvify1/mavros/set_mode', mavros_msgs.srv.SetMode)
response1 = flightModeService1(custom_mode='AUTO.LAND')
response2 = flightModeService2(custom_mode='AUTO.LAND')
return response1.mode_sent,response2.mode_sent
except rospy.ServiceException, e:
print "service set_mode call failed: %s. Autoland Mode could not be set."%e
return False,False
# Main class: Converts joystick commands to position setpoints
class Controller:
# initialization method
def __init__(self):
# Drone state
self.state = State()
# Altitude setpoint, [meters]
self.ALT_SP1 = 1
self.ALT_SP2 = 2
# Instantiate setpoint messages
self.sp1 = PoseStamped()
self.sp2 = PoseStamped()
self.home_sp1 = PoseStamped()
self.home_sp2 = PoseStamped()
self.home_sp1.pose.position.x = 0
self.home_sp1.pose.position.y = 0
self.home_sp1.pose.position.z = self.ALT_SP1
self.home_sp2.pose.position.x = 0
self.home_sp2.pose.position.y = 0
self.home_sp2.pose.position.z = self.ALT_SP2
self.sp1.pose.position.x = 0
self.sp1.pose.position.y = 0
self.sp1.pose.position.z = self.ALT_SP1
self.sp2.pose.position.x = 0
self.sp2.pose.position.y = 0
self.sp2.pose.position.z = self.ALT_SP2
# A Message for the current local position of the drone
self.local_pos = Point(0.0, 0.0, 0.0)
# Handler to set FCU modes
self.modes = fcuModes()
# Create waypoints for path traversal
self.wp_pose1 = PoseStamped()
self.wp_pose2 = PoseStamped()
self.wp_pose1.pose.position.z = self.ALT_SP1
self.wp_pose2.pose.position.z = self.ALT_SP2
locn_file = open("../textfiles/locn.txt","r")
self.waypoints = []
for locn_line in locn_file:
sep_xy = locn_line.split(" ")
sep_xy[1] = sep_xy[1].replace("\n", "");
self.waypoints.append((float(sep_xy[0]), float(sep_xy[1])))
locn_file.close()
fp_file = open("../textfiles/finalpath.txt","r")
fp = []
self.new_waypoints = []
self.p1_waypoints = []
self.p2_waypoints = []
for fp_line in fp_file:
final_path = fp_line.split(" ")
for i in range(len(final_path)-1):
fp.append((int(final_path[i])))
self.new_waypoints.append(self.waypoints[int(fp[i])-1])
fp = []
path_idx = len(self.new_waypoints)-(len(final_path)-1)
self.p1_waypoints, self.p2_waypoints = self.new_waypoints[:path_idx], self.new_waypoints[path_idx:]
fp_file.close()
# Waypoint control variables
self.wp_started = False
self.wp_finished = False
self.wp_timer = 0
self.wp_index = 0
# Callbacks
## local position callback
def posCb(self, msg):
self.local_pos.x = msg.pose.position.x
self.local_pos.y = msg.pose.position.y
self.local_pos.z = msg.pose.position.z
## Drone State callback
def stateCb(self, msg):
self.state = msg
## Update setpoint message
def updateSp(self):
self.sp1.header.stamp = rospy.Time.now()
self.sp2.header.stamp = rospy.Time.now()
self.sp3.header.stamp = rospy.Time.now()
#self.sp1.pose.position.x = self.local_pos.x + self.STEP_SIZE*x
#self.sp1.pose.position.y = self.local_pos.y + self.STEP_SIZE*y
# Main function
def main():
# Initiate node
rospy.init_node('offboard_ctl_node', anonymous=True)
# Drone controller object
cnt1 = Controller()
cnt2 = Controller()
# ROS loop rate, [Hz]
rate = rospy.Rate(20.0)
# Subscribe to drone state
rospy.Subscriber('/intel1/mavros/state', State, cnt1.stateCb)
rospy.Subscriber('/uvify1/mavros/state', State, cnt2.stateCb)
# Subscribe to drone's local position
rospy.Subscriber('/intel1/mavros/local_position/pose', PoseStamped, cnt1.posCb)
rospy.Subscriber('/uvify1/mavros/local_position/pose', PoseStamped, cnt2.posCb)
# Setpoint publisher
sp_pub1 = rospy.Publisher('/intel1/mavros/setpoint_position/local', PoseStamped, queue_size=1)
sp_pub2 = rospy.Publisher('/uvify1/mavros/setpoint_position/local', PoseStamped, queue_size=1)
# Send some setpoint messages to activate OFFBOARD mode
rospy.loginfo('Sending 20 setpoints...')
i=0
while i<20:
sp_pub1.publish(cnt1.home_sp1)
sp_pub2.publish(cnt2.home_sp2)
rate.sleep()
i = i+1
# Arm the vehicle
rospy.loginfo('Arming...')
cnt1.modes.setArm()
cnt2.modes.setArm()
# Activate OFFBOARD mode
rospy.loginfo('Switching to OFFBOARD mode...')
cnt1.modes.setOffboardMode()
cnt2.modes.setOffboardMode()
# ROS main loop
loop_t = time.time()
landing = False
ground_count = 0 # Count number of times position reports on ground
rospy.loginfo('Streaming home_sp at 20 Hz...')
while not rospy.is_shutdown():
# Start waypoint path following
if(not cnt1.wp_started and not cnt2.wp_started):
cnt1.wp_started = True
cnt2.wp_started = True
cnt1.wp_index = 0
cnt2.wp_index = 0
cnt1.wp_timer = time.time()
cnt2.wp_timer = time.time()
# Update waypoint index every 5 seconds
if(time.time() - cnt1.wp_timer > 7):
if(cnt1.wp_index < (len(cnt1.p1_waypoints)-1)):
cnt1.wp_index += 1
cnt2.wp_index += 1
cnt1.wp_timer = time.time() # Update wp timer
cnt2.wp_timer = time.time()
# Land at end of path (4 waypoints)
if(cnt1.wp_index > (len(cnt1.p1_waypoints)-1)):
cnt1.wp_finished = True
if(cnt2.wp_index > (len(cnt2.p2_waypoints)-1)):
cnt2.wp_finished = True
# Land at end of path (4 waypoints)
if cnt1.wp_finished:
if not landing:
cnt1.modes.setAutoLandMode()
landing = True
else:
if cnt1.local_pos.z < 0.3:
ground_count += 1
if ground_count >= 20:
cnt1.modes.setDisarm()
break
else:
# Set current waypoint based on index
cnt1.wp_pose1.pose.position.x = cnt1.p1_waypoints[cnt1.wp_index][0];
cnt1.wp_pose1.pose.position.y = cnt1.p1_waypoints[cnt1.wp_index][1];
sp_pub1.publish(cnt1.wp_pose1)
# Land at end of path (4 waypoints)
if cnt2.wp_finished:
if not landing:
cnt2.modes.setAutoLandMode()
landing = True
else:
if cnt2.local_pos.z < 0.3:
ground_count += 1
if ground_count >= 20:
cnt2.modes.setDisarm()
break
else:
# Set current waypoint based on index
cnt2.wp_pose2.pose.position.x = cnt2.p2_waypoints[cnt2.wp_index][0];
cnt2.wp_pose2.pose.position.y = cnt2.p2_waypoints[cnt2.wp_index][1];
sp_pub2.publish(cnt2.wp_pose2)
rate.sleep()
# Land the drone if CTRL+C
cnt1.modes.setAutoLandMode()
if __name__ == '__main__':
try:
main()
except rospy.ROSInterruptException:
pass<file_sep>/UAV Initial Setup/Intel Aero Setup/Installing TurboVNC.md
## TurboVNC Installation
* References:
* [XKEYBOARD Issue](https://unix.stackexchange.com/questions/346107/keyboard-mapping-wrong-only-in-specific-applications-under-tightvnc)
* [Website](https://www.turbovnc.org/)
1. Pre-requisite: libjpeg-turbo
* Install pre-req: `sudo apt install libpam0g-dev`
* Download, build \& install source
```
cd ~
git clone https://github.com/libjpeg-turbo/libjpeg-turbo.git
cd libjpeg-turbo
git checkout tags/2.0.1
mkdir build
cd build
cmake -G"Unix Makefiles" ..
make -j4
sudo make install
```
* Download \& Build From Source
```
cd ~
git clone https://github.com/TurboVNC/turbovnc.git
git checkout tags/2.2.1
mkdir build
cd build
cmake -G"Unix Makefiles" -DTVNC_BUILDJAVA=0 ..
make -j4
```
* Set up the vnc password: `<PASSWORD>`
* Password: **<PASSWORD>**
* View-only password: **No**
* Create shell functions to start/stop vncserver
* Add a function to `~/.bashrc` to start server
* ```
echo -e "\n# Start TurboVNC Server\nfunction ovnc() {\
\n ~/turbovnc/build/bin/vncserver\n}"\
>> ~/.bashrc
source ~/.bashrc
```
* To run the server, type: `ovnc` in the shell
* This will output:
`New 'X' desktop is intel2-aero2:1`
* Calling `ovnc` again will start new servers at `:2`, `:3`, etc.
* View server at `<IP Address>:5901`
* **NOTE:** `5901` is for `:1`, `5902` for `:2`, etc.
* Add a function to `~/.bashrc` to kill server
* ```
echo -e "\n# Kill TurboVNC Server\nfunction okill() {\
\n ~/turbovnc/build/bin/vncserver -kill :$1\n}"\
>> ~/.bashrc
source ~/.bashrc
```
* To kill the server: `okill 1`
* **NOTE:** `1` above indicates index number (could be `1`, `2`...etc.)
* Install TurboVNC Viewer
* Download from [here](https://sourceforge.net/projects/turbovnc/files/)
* NOTE:
* Executables are now in `~/turbovnc/build/bin/`
<file_sep>/UAV Initial Setup/Intel Aero Setup/Installing Ubuntu on Intel Aero.md
## Install \& Set Up Ubuntu
1. Install Ubuntu
* Make bootable USB with Ubuntu 16.04.3
* Boot from USB, and click `Install Ubuntu`
* Do NOT check `Install third-party software for graphics...`
* Select `Erase disk and install Ubuntu`
* When done a pop-up will say: `Installation is complete... Restart Now`
* Click `Restart Now`... may take long time, ok to do hard reboot
* Install Intel Aero repository following instructions
* Set up WiFi
* Click Ubuntu icon in top left of dock to search computer
* Search for Network and select `Network` (orange folder with plug on it)
* Disable hotspot and connect to LabRouter5
* Set up QGC config as described [here](https://github.com/intel-aero/meta-intel-aero/wiki/90-(References)-OS-user-Installation)
* Install Intel RealSense SDK based on [this](https://github.com/intel-aero/meta-intel-aero/wiki/90-(References)-OS-user-Installation#intel-realsense-sdk) with some modifications
*
```
cd ~
sudo apt-get -y install git libusb-1.0-0-dev pkg-config libgtk-3-dev libglfw3-dev cmake
git clone -b legacy --single-branch https://github.com/IntelRealSense/librealsense.git
cd librealsense
mkdir build && cd build
cmake ../ -DBUILD_EXAMPLES=true -DBUILD_GRAPHICAL_EXAMPLES=true
make -j4
sudo make install
```
* Update the **PYTHONPATH** env. variable (add path to pyrealsense lib)
* Add the following line to **~/.bashrc**
* `export PYTHONPATH=$PYTHONPATH:/usr/local/lib`
* Install PyRealsense
* `sudo pip install pycparser`
* `sudo pip install cython`
* `sudo pip install pyrealsense`
## Set up Basic Applications/Environment
1. Enable root login
* `sudo passwd root`
* Enter new UNIX password: `<PASSWORD>`
* Add user to dialout group
* `sudo usermod -a -G dialout intel2`
* `sudo reboot`
* Install basic applications
*
```
sudo apt update
sudo apt install git cmake kate chrony screen unzip terminator v4l-utils htop curl vlc chromium-browser
```
* Configure **Chrony**
* This application will synchronize the clocks between multiple machines on the same network. This is necessary since the Time class in ROS uses the system clock for timing, and the system clock may differ between two machines, even if they are both using the same ntp server. Thus making it impossible to accurately compare timestamps between topics sent from different machines.
* References: [1](https://chrony.tuxfamily.org/documentation.html), [2](https://wiki.archlinux.org/index.php/Chrony), [3](http://cmumrsdproject.wikispaces.com/file/view/ROS_MultipleMachines_Wiki_namank_fi_dshroff.pdf), [4](http://wiki.ros.org/ROS/NetworkSetup), [5](https://github.com/pr2-debs/pr2/blob/master/pr2-chrony/root/unionfs/overlay/etc/chrony/chrony.conf), [6](https://www.digitalocean.com/community/tutorials/how-to-set-up-time-synchronization-on-ubuntu-16-04)
* To check the time difference between machines, use:
* `ntpdate -q <IP address of other machine>`
* Turn off **timesyncd**
* `sudo timedatectl set-ntp no`
* Configure Chrony (make these changes in `/etc/chrony/chrony.conf`)
* Add Purdue’s ntp servers
* ```
sudo sed -i 's/pool 2.debian.pool.ntp.org offline iburst$/pool 2.debian.pool.ntp.org offline iburst\nserver ntp3.itap.purdue.edu offline iburst\nserver ntp4.itap.purdue.edu offline iburst/' /etc/chrony/chrony.conf
```
* Set up chrony server for other devices
* ```
sudo sed -i 's/#local stratum 10$/local stratum 10/' /etc/chrony/chrony.conf
sudo sed -i 's~#allow ::/0 (allow access by any IPv6 node)$~#allow ::/0 (allow access by any IPv6 node)\nallow 192.168~' /etc/chrony/chrony.conf
```
* Allow for step time changes at startup (for initial time setup)
* ```
su
echo -e “# In first three updates step the system clock instead of slew\n# if the adjustment is larger than 10 seconds\nmakestep 10 3” | tee -a /etc/chrony/chrony.conf > /dev/null
exit
```
* Set timezone
* Get the exact name of the desired timezone (`America/Indiana/Indianapolis`)
* `timedatectl list-timezones`
* `sudo timedatectl set-timezone America/Indiana/Indianapolis`
* `date`
* Restart chrony to apply changes
* `sudo systemctl restart chrony`
* Configure **Chromium Browser**
* From Chrome Browser, search for `Markdown Viewer Chrome` [link](https://chrome.google.com/webstore/detail/markdown-viewer/ckkdlimhmcjmikdlpkmbgfkaikojcbjk?hl=en)
* Click `Add to Chrome`, Confirm in popup window: `Add extension`
* Allow access to file:/// URLs
* Click Markdown Viewer icon in chromium menu bar ('m' icon)
* Click `Advanced Options`
* Click `ALLOW ACCESS TO FILE:///URLS` which opens the extension options
* Scroll down and toggle `Allow access to file URLs` to ON position
* Open a markdown file (.m extension) and click Markdown Viewer icon to select desired Theme
* e.g. GitHub, Markdown9, etc.
* Configure **Kate**
* Top Menu --> Settings --> Configure Kate
* Application
* Sessions --> Check `Load last used session`
* Editor Component
* Appearance --> Borders --> Check `Show line numbers`
* Fonts & Colors --> Font --> `Size: 10`
* Editing --> General --> Check `Show static word wrap marker`
* Editing --> General --> Check `Enable automatic brackets`
* Editing --> Indentation --> `Tab width: 4 characters`
* Editing --> Indentation --> `Keep extra spaces`
* Open/Save --> Modes & Filetypes
* Select Filetype: `Markup/XML`
* Add `;*.launch` to 'File extensions'
* NOTE: Be careful not to add a space after the `;`
* Click `Apply` then `OK`
* Set Kate as default file editor (instead of GEdit)
* ```
sudo sed -i 's/gedit.desktop/kate.desktop/g' /etc/gnome/defaults.list
sudo cp /usr/share/applications/gedit.desktop /usr/share/applications/kate.desktop
sudo sed -i 's/gedit/kate/g' /usr/share/applications/kate.desktop
sudo sed -i 's/=Text\ Editor/=Kate/g' /usr/share/applications/kate.desktop
sudo reboot (to apply changes)
```
* Configure **Terminal**
* Top Menu --> Edit --> Profile Preferences
* General --> Initial terminal size: **80 x 20**
* Scrolling --> Check **Unlimited**
* Colors --> Check **Use transparent background**
* Configure **Terminator**
* Right Click --> Preferences --> Profiles
* Profiles --> Edit 'default' Profile:
* Colors --> UnCheck **Use colors from system theme**
* Colors --> Built-in schemes: **Ambience**
* Background --> Check **Transparent background**
* Background --> Transparency slider: 0.9
* Scrolling --> Check **Infinite Scrollback**
* Layouts
* Split Terminator screen into 4 terminals and then click 'Add' at bottom left
* Name the layout, e.g. 'Quad'
* Set up Desktop Apps
* Create directory for helper scripts
* `mkdir ~/helper_scripts && cd helper_scripts`
* Copy over the icons folder from Spira server at:
* `MSRAL/Current\ Projects/MAVs/Linux/desktop_apps_new/my_scripts`
* Create script to open Terminator using Quad layout
* Create a file named `runTerminator` and add the following:
```
#!/bin/bash
nohup terminator -l Quad
exit
```
* Make runTerminator executable
* `chmod +x runTerminator`
* Create a desktop app to launch terminator
* Create file called `termQuad.desktop` and add the following:
```
[Desktop Entry]
Name=Terminator (Quad Layout)
Comment=Launches Terminator with 4 shells
Exec=/home/intel2/helper_scripts/runTerminator
Icon=/home/intel2/helper_scripts/icons/terminator.png
Terminal=false
Type=Application
```
* Navigate to Desktop and right-click termQuad.desktop and select 'Properties'
* Check 'Allow executing file as program'
* Icon should now appear
* Double-click to open Terminator, then Lock to Launcher
* Configure **File Manager**
* Open File Browser, then select Edit --> Preferences
* Views --> View new folders using: **List View**
* Views --> List View Defaults: zoom level: `33%`
* Display --> List View --> Check **Navigate folders in a tree**
* Configure window size of **Compiz File Browser**
* `cd ~/.config/compiz-1/compizconfig`
* Add **size** setting in Compiz config file
* `nano config`
* Add `size = 800, 100` at bottom of file
<file_sep>/UAV Initial Setup/Intel Aero Setup/Update Yocto.md
## Update Yocto OS
* [Reference](https://github.com/intel-aero/meta-intel-aero/wiki/02-Initial-Setup)
1. Format USB drive (10 - 15 minutes)
* Insert USB drive into Laptop/PC
* Erase & Format USB drive
* **Windows 10**
* Right-click USB drive and select **Format**
* **Mac**
* Open **Disk Utility**
* Select the USB drive and click **Erase**
* Set new format to ExFAT and leave other options as defaults
* Navigate to the [Intel Download Center](https://downloadcenter.intel.com/download/27833/Intel-Aero-Platform-for-UAVs-Installation-Files?v=t)
* Download [intel-aero-image-1.6.2.iso](https://downloadcenter.intel.com/download/27833/Intel-Aero-Platform-for-UAVs-Installation-Files?v=t)
* Download and install [Etcher](https://etcher.io/)
* Insert USB Drive
* Open Etcher
* Click **Select Image** and browse to the ***.iso** downloaded above
* Select the USB Drive
* Click **Flash**
* Cable Connection Notes
* Use an **OTG** USB adapter (NOT JUST A NORMAL USB) to connect a USB hub with a keyboard, mouse and USB flash drive
* Use a micro-HDMI to HDMI cable and connect directly to a monitor with HDMI (avoid using e.g. HDMI to DVI connector since it seems to make the Aero crash)
* Install Yocto
* Hold ESC while booting up to get to BIOS
* Select the bootable USB to startup
* Select `install`
* Refer to [02-Initial Setup](https://github.com/intel-aero/meta-intel-aero/wiki/02-Initial-Setup) for information about install process (e.g. LED colors, etc.)
* Flash BIOS
* Copy the BIOS firmware onto the Aero Board
* [BIOS Link](https://downloadcenter.intel.com/downloads/eula/27833/Intel-Aero-Platform-for-UAVs-Installation-Files?httpDown=https%3A%2F%2Fdownloadmirror.intel.com%2F27833%2Feng%2Faero-bios-01.00.16-r1.corei7_64.rpm)
* Save it onto a USB drive, and then connect USB to aero board
* Mount the USB drive
```
mkdir /media/usb-drive
mount /dev/sda /media/usb-drive
cd /media/usb-drive
cp aero-bios-01.00.16-r1.corei7_64.rpm /home/root/
```
* Update bios by typing `aero-bios-update` in the terminal
* Reboot after it completes (this may require unplugging power supply)
* This may require unplugging the power supply if the terminal hangs after displaying the messages listed on the above '02-Initial-Setup' page
* Flash FPGA
* `cd /etc/fpga/`
* `jam -aprogram aero-rtf.jam`
* Terminal will say `Exit code = 0... Success` when done
* Flash Flight Controller with PX4 Firmware
* `cd /etc/aerofc/px4/`
* `aerofc-update.sh nuttx-aerofc-v1-default.px4`
* Reboot
* Confirm all versions are correct: `aero-get-version.py`
<file_sep>/UAV Initial Setup/Intel Aero Setup/udev rule setup.md
## General udev rule setup
1. Obtain device info
* References: [Debian Wiki: udev](https://wiki.debian.org/udev), [Overview](http://reactivated.net/writing_udev_rules.html#udevinfo)
* `udevadm info --attribute-walk --name /dev/<device_name>`
* Place udev rule files in: `/etc/udev/rules.d/`
* Example file: `99-usb-serial.rules`
* ```
# 3.3/5V FTDI Adapter
SUBSYSTEM=="tty", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", ATTRS{serial}=="AI04XENV", SYMLINK+="ttyFTDI3_5"
# 5V FTDI Adapter
SUBSYSTEM=="tty", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", ATTRS{serial}=="AK05C4L0", SYMLINK+="ttyFTDI5"
```
<file_sep>/UAV Initial Setup/Intel Aero Setup/Calibrate Intel Aero FC.md
## Calibrate Flight Controller
* [Reference](https://github.com/intel-aero/meta-intel-aero/wiki/02-Initial-Setup#calibration)
* Click Gear Icon to enter vehicle setup
* Configure Airframe (if summary doesn't already show Intel Aero RTF Drone)
* If Intel Aero RTF Drone is not listed under the Quadrotor X group...
* Uninstall QGroundcontrol and remove Airframe meta cache... see [here](https://github.com/mavlink/qgroundcontrol/issues/6794)
* Delete the PX4AirframeFactMetaData.xml in your ~/.config/QGroundControl.org directory (Ubuntu or Mac)
* Calibrate Sensors
* Calibrate Compass Gyro \& Accelerometer following QGC prompts
* Power Setup (Battery)
* Number of cells: `4`
* Voltage divider: `9.12139702`
* Click `Calculate`, Type in measured battery voltage (use multimeter) and click `Calculate`
* Amps per volt: `36.36751556`???
|
2087f77dc1e731703f0b2f72129230ff5cfca94b
|
[
"Markdown",
"Python"
] | 22 |
Python
|
Kazimbalti/AUTONOMOUS-MULTI-UAS-LAB-SETUP
|
e65cb097bc1449065a0a3531028f85ebe00f8701
|
9161ebf6505e86b3312f3a3484efc93c849ca822
|
refs/heads/master
|
<repo_name>MugLeo/sgfs<file_sep>/registrar_torneo/views.py
from django.shortcuts import render
from django.views.generic import View
from forms import FormTorneo
class RegistrarTorneoView(View):
def get(self, request, *args, **kwargs):
form = FormTorneo()
return render(request, 'registrar_torneo/registrar_torneo.html', locals())
def post(self, request, *args, **kwargs):
form = FormTorneo(request.POST)
if form.is_valid():
torneo = form.save()
torneo.save()
return render(request, 'index/index.html', locals())
return render(request, 'index/index.html', locals())<file_sep>/registrar_torneo/forms.py
from django import forms
from models import Torneo
class FormTorneo(forms.ModelForm):
nombre = forms.CharField(required=True,max_length=100)
class Meta:
model = Torneo
fields = ('nombre',)
<file_sep>/registrar_equipo/views.py
from django.shortcuts import render
from django.views.generic import View
from forms import FormEquipo
class RegistrarEquipoView(View):
def get(self, request, *args, **kwargs):
form = FormEquipo()
return render(request, 'registrar_equipo/registrar_equipo.html', locals())
def post(self, request, *args, **kwargs):
form = FormEquipo(request.POST)
if form.is_valid():
equipo = form.save()
equipo.save()
return render(request, 'index/index.html', locals())
return render(request, 'index/index.html', locals())<file_sep>/registrar_equipo/forms.py
from django import forms
from models import Equipo
from registrar_torneo.models import Torneo
class FormEquipo(forms.ModelForm):
nombre = forms.CharField(required=True,max_length=100)
encargado = forms.CharField(required=True,max_length=100)
torneo = forms.ModelChoiceField(Torneo.objects.all())
class Meta:
model = Equipo
<file_sep>/utils/templatetags/access.py
from django.http import HttpResponseRedirect
# Define si tiene acceso controlando login y acceso por menu
def validar_session(f):
def wrap(request, *args, **kwargs):
if 'sessionUsuario' not in request.session:
return HttpResponseRedirect('/login/')
request.session.set_expiry(600)
return f(request, *args, **kwargs)
wrap.__doc__ = f.__doc__
wrap.__name__ = f.__name__
return wrap<file_sep>/utils/static/js/jsBase.js
function numerosLetrasSinCaracteresEspeciales(event){
var code =event.charCode || event.keyCode;
if(code==46 || code== 8){
code=48;
}
if ((code < 48 || code > 57)&&
(code < 65 || code > 90)&&
(code < 97 || code > 122)&&
code > 32)
if(window.event){
event.returnValue = false;
}else{
event.preventDefault();
}
if (code == 13)
if(window.event){
event.returnValue = false;
}else{
event.preventDefault();
}
}
function soloNumeros(event){
var code =event.charCode || event.keyCode;
if(code==46 || code== 8){
code=48;
}
if ((code< 48) || (code> 57)){
if(window.event){
event.returnValue = false;
}else{
event.preventDefault();
}
}
}
function numerosLetrasPunto(e){
var key;
var keychar;
if (window.event) {
key = e.keyCode;
}
else if (e.which) {
key = e.which;
}else{return true;}
if ( (key >= 65 && key <= 90) || //LETRAS MAYUSCULAS
(key >= 97 && key <= 122) || //LETRAS MINUSCULAS
(key == 241) || (key == 209) || //ñ Ñ
(key == 225) || (key == 193) || //á Á
(key == 233) || (key == 201) || //é É
(key == 237) || (key == 205) || //í Í
(key == 243) || (key == 211) || //ó Ó
(key == 250) || (key == 218) || //ú Ú
(key == 9) || // Tabulador
(key == 8) || (key == 32)||
(key >= 48 && key <= 57) ||
(key ==46) ) { //BACKSPACE, || (key == 32)Espacio "."
return true;
}
return false;
}
function verificarSelect(){
var sel = document.getElementById( 'sel' );
if( sel.options[ sel.selectedIndex ].value !="" && sel.options[ sel.selectedIndex ].value !=0){
var contenedorCamposModificarMarca=document.getElementById("contenedorCamposModificarMarca");
var contenedorConsultaMarca=document.getElementById("contenedorConsultaMarca");
var contenedorDetalleConsultaMarca=document.getElementById("contenedorDetalleConsultaMarca");
if( sel.options[ sel.selectedIndex ].value ==1){
document.getElementById("mensaje").innerHTML="";
document.getElementById('solicitudNombreMarca').value="";
document.getElementById("solicitudNombreMarca").disabled=false;
document.getElementById("contenedorDatos").style.display="block";
contenedorConsultaMarca!=null?contenedorConsultaMarca.style.display="none":null;
contenedorCamposModificarMarca!=null?contenedorCamposModificarMarca.style.display="none":null;
contenedorDetalleConsultaMarca!=null?contenedorDetalleConsultaMarca.style.display="none":null;
}else if( sel.options[ sel.selectedIndex ].value ==2){
document.getElementById('solicitudNombreMarca').value="";
document.getElementById("solicitudNombreMarca").disabled=false;
document.getElementById("contenedorDatos").style.display="none";
contenedorConsultaMarca!=null?contenedorConsultaMarca.style.display="none":null;
contenedorCamposModificarMarca!=null?contenedorCamposModificarMarca.style.display="none":null;
contenedorDetalleConsultaMarca!=null?contenedorDetalleConsultaMarca.style.display="none":null;
consultarMarcasTodos();
}else if( sel.options[ sel.selectedIndex ].value =="select"){
document.getElementById("contenedorCamposModificarMarca").style.display="none";
document.getElementById("contenedorDatos").style.display="none";
contenedorConsultaMarca!=null?contenedorConsultaMarca.style.display="none":null;
contenedorCamposModificarMarca!=null?contenedorCamposModificarMarca.style.display="none":null;
contenedorDetalleConsultaMarca!=null?contenedorDetalleConsultaMarca.style.display="none":null;
}
}
}
function verificarSelectProducto(){
var sel = document.getElementById( 'sel' );
if( sel.options[ sel.selectedIndex ].value !="" && sel.options[ sel.selectedIndex ].value !=0){
var contenedorCamposModificarProducto=document.getElementById("contenedorCamposModificarProducto");
var contenedorConsultaProducto=document.getElementById("contenedorConsultaProducto");
var contenedorDetalleConsultaProducto=document.getElementById("contenedorDetalleConsultaProducto");
if( sel.options[ sel.selectedIndex ].value ==1){
document.getElementById("mensaje").innerHTML="";
document.getElementById('solicitudItemId').value="";
document.getElementById("solicitudItemId").disabled=false;
document.getElementById("contenedorDatosItemId").style.display="block";
document.getElementById("contenedorDatosMarca").style.display="none";
contenedorConsultaProducto!=null?contenedorConsultaProducto.style.display="none":null;
contenedorDetalleConsultaProducto!=null?contenedorDetalleConsultaProducto.style.display="none":null;
document.getElementById('solicitudMarcaProducto').value="";
document.getElementById("solicitudMarcaProducto").disabled=false;
}else if( sel.options[ sel.selectedIndex ].value ==2){
document.getElementById("mensaje").innerHTML="";
document.getElementById('solicitudMarcaProducto').value="";
document.getElementById("solicitudMarcaProducto").disabled=false;
document.getElementById("contenedorDatosItemId").style.display="none";
document.getElementById("contenedorDatosMarca").style.display="block";
contenedorConsultaProducto!=null?contenedorConsultaProducto.style.display="none":null;
contenedorDetalleConsultaProducto!=null?contenedorDetalleConsultaProducto.style.display="none":null;
document.getElementById('solicitudItemId').value="";
document.getElementById("solicitudItemId").disabled=false;
}else if( sel.options[ sel.selectedIndex ].value ==3){
contenedorConsultaProducto!=null?contenedorConsultaProducto.style.display="none":null;
contenedorDetalleConsultaProducto!=null?contenedorDetalleConsultaProducto.style.display="none":null;
document.getElementById('solicitudItemId').value="";
document.getElementById("solicitudItemId").disabled=false;
document.getElementById('solicitudMarcaProducto').value="";
document.getElementById("solicitudMarcaProducto").disabled=false;
consultarProductosTodosCargar();
}else if( sel.options[ sel.selectedIndex ].value =="select"){
document.getElementById("contenedorDatosItemId").style.display="none";
document.getElementById("contenedorDatosMarca").style.display="none";
contenedorConsultaProducto!=null?contenedorConsultaProducto.style.display="none":null;
contenedorCamposModificarProducto!=null?contenedorCamposModificarProducto.style.display="none":null;
contenedorDetalleConsultaProducto!=null?contenedorDetalleConsultaProducto.style.display="none":null;
}
}
}
function mostrarDetalleServicio(id, grupoServicio, nombre, descripcion, estatus, idContrato, usuarioCrea, fechaCreacion, usuarioModifica, fechaModifica, origenTransaccion){
document.getElementById("detalleIdServicio").innerHTML=id;
if (grupoServicio==0){
grupoServicio='Sin Servicio';
}else if(grupoServicio==1){
grupoServicio='Datos';
}
document.getElementById("detalleGrupoServicio").innerHTML=grupoServicio;
document.getElementById("detalleNombreServicio").innerHTML=nombre;
document.getElementById("nombreServicio").value=nombre;
document.getElementById("detalleDescripcionServicio").innerHTML=descripcion;
if (estatus=='A'){
estatus='Activo';
}else if(estatus=='I'){
estatus='Inactivo';
}
document.getElementById("detalleEstatusServicio").innerHTML=estatus;
document.getElementById("detalleContratoServicio").innerHTML=idContrato;
document.getElementById("detalleUsuarioCreacion").innerHTML=usuarioCrea;
document.getElementById("detalleFechaCreacion").innerHTML=fechaCreacion;
document.getElementById("detalleUsuarioModifica").innerHTML=usuarioModifica;
document.getElementById("detalleFechaModifica").innerHTML=fechaModifica;
document.getElementById("contenedorDatos").style.display="none";
document.getElementById("contenedorDetalleConsultaServicio").style.display="none"
// validacion que separa el flujo:
// si viene desde consultar marca muestra el detalle de la marca seleccionada
// sino va directo a modificar marca.
if (origenTransaccion=="consultarServicio"){
document.getElementById("contenedorConsultaServicio").style.display="none";
document.getElementById("contenedorDetalleConsultaServicio").style.display="block";
}else
if(origenTransaccion=="modificarServicio"){
modificarServicio();
}
}
function mostrarDetallePlan(id,nombre,descripcion,estatus,usuarioCrea,fechaCreacion,usuarioModifica,fechaModifica,tipoLinea,origenTransaccion){
document.getElementById("idPlan").value=id;
document.getElementById("detalleIdPlan").value=id;
document.getElementById("detalleNombrePlan").innerHTML=nombre;
document.getElementById("detalleDescripcionPlan").innerHTML=descripcion;
if (estatus=='A'){
estatus='Activo';
}else if(estatus=='I'){
estatus='Inactivo';
}
document.getElementById("detalleEstatusPlan").innerHTML= estatus;
document.getElementById("detalleUsuarioCrea").innerHTML=usuarioCrea;
document.getElementById("detalleFechaCrea").innerHTML=fechaCreacion;
document.getElementById("detalleUsuarioModifica").innerHTML=usuarioModifica;
document.getElementById("detalleFechaModifica").innerHTML=fechaModifica;
if (tipoLinea==1){
tipoLinea='Prepago';
}else if(tipoLinea==2){
tipoLinea='Pospago';
}else if(tipoLinea==3){
tipoLinea='Prepago y Pospago';
}
document.getElementById("detalleTipoLinea").innerHTML=tipoLinea;
document.getElementById("contenedorDatos").style.display="none";
document.getElementById("contenedorDetalleConsultaPlan").style.display="none"
if (origenTransaccion=="consultarPlan"){
document.getElementById("contenedorConsultaPlan").style.display="none";
document.getElementById("contenedorDetalleConsultaPlan").style.display="block";
}else
if(origenTransaccion=="modificarPlan"){
modificarPlan(origenTransaccion);
}
}
function mostrarMensajeInsertarMarca(mensaje){
if(mensaje=='fallido'){
jAlert('Su marca no pudo ser agregada')
}else{
jAlert('Su marca ha sido agregada exitosamente');
}
}
function modificarMarca(){
jConfirm("Esta seguro que desea modificar este elemento?",null, function (respuesta) {
if (respuesta) {
document.getElementById("idMarca").value=document.getElementById("detalleIdMarca").value;
document.getElementById("nombreMarca").value=document.getElementById("detalleNombreMarca").innerHTML;
document.getElementById("descripcionMarca").innerHTML=document.getElementById("detalleDescripcionMarca").innerHTML;
if (document.getElementById("detalleEstatusMarca").innerHTML=='Inactivo'){
document.getElementById("detalleEstatusMarca").innerHTML='I';
}
else{
document.getElementById("detalleEstatusMarca").innerHTML='A';
}
document.getElementById("estatusMarca").value= document.getElementById("detalleEstatusMarca").innerHTML;
document.getElementById("codigoMarca").value=document.getElementById("detalleCodigoMarca").innerHTML;
document.getElementById("contenedorCamposModificarMarca").style.display="block";
document.getElementById("contenedorConsultaMarca").style.display="none";
document.getElementById("contenedorDatos").style.display="none";
document.getElementById("contenedorDetalleConsultaMarca").style.display="none";
}
});
}
function mostrarDetalleMarca(id, nombre, descripcion, estatus, codigo, usuarioCrea, fechaCreacion, usuarioModifica,fechaModifica, origenTransaccion){
document.getElementById("detalleIdMarca").value=id;
document.getElementById("detalleNombreMarca").innerHTML=nombre;
document.getElementById("detalleDescripcionMarca").innerHTML=descripcion;
if (estatus=='A'){
estatus='Activo';
}else if(estatus=='I'){
estatus='Inactivo';
}
document.getElementById("detalleEstatusMarca").innerHTML=estatus;
document.getElementById("detalleCodigoMarca").innerHTML=codigo;
document.getElementById("detalleUsuarioCreaMarca").innerHTML=usuarioCrea;
document.getElementById("detalleFechaCreaMarca").innerHTML=fechaCreacion;
document.getElementById("detalleUsuarioModificaMarca").innerHTML=usuarioModifica;
document.getElementById("detalleFechaModificaMarca").innerHTML=fechaModifica;
document.getElementById("contenedorCamposModificarMarca").style.display="none";
document.getElementById("contenedorDatos").style.display="none";
document.getElementById("contenedorDetalleConsultaMarca").style.display="none"
// validacion que separa el flujo:
// si viene desde consultar marca muestra el detalle de la marca seleccionada
// sino va directo a modificar marca.
if (origenTransaccion=="consultarMarca"){
document.getElementById("contenedorConsultaMarca").style.display="none";
document.getElementById("contenedorDetalleConsultaMarca").style.display="block";
}else
if(origenTransaccion=="modificarMarca"){
modificarMarca();
}
}
function mostrarDetallePaquete(id, nombre, descripcion, grupoPaquete, estatus, contrato, usuarioCrea, fechaCreacion, usuarioModifica, fechaModifica, origenTransaccion){
document.getElementById("detalleIdPaquete").value=id;
document.getElementById("codigoPaquete").value=id;
document.getElementById("detalleNombrePaquete").innerHTML=nombre;
document.getElementById("detalleDescripcionPaquete").innerHTML=descripcion;
if (grupoPaquete==0){
grupoPaquete='Sin Paquete';
}
document.getElementById("detalleGrupoPaquete").innerHTML=grupoPaquete;
if (estatus=='A'){
estatus='Activo';
}else if(estatus=='I'){
estatus='Inactivo';
}
document.getElementById("detalleEstatusPaquete").innerHTML=estatus;
document.getElementById("detalleUsuarioCreacion").innerHTML=usuarioCrea;
document.getElementById("detalleFechaCreacion").innerHTML=fechaCreacion;
document.getElementById("detalleUsuarioModifica").innerHTML=usuarioModifica;
document.getElementById("detalleFechaModifica").innerHTML=fechaModifica;
document.getElementById("contenedorDatos").style.display="none";
document.getElementById("contenedorDetalleConsultaPaquete").style.display="none"
if (origenTransaccion=="consultarPaquete"){
document.getElementById("contenedorConsultaPaquete").style.display="none";
document.getElementById("contenedorDetalleConsultaPaquete").style.display="block";
}else
if(origenTransaccion=="modificarPaquete"){
modificarPaquete();
}
}
function cancelarModificacion(){
//Se envian los datos para modificar el producto
}
function modificarPie(mensajeTran){
if (mensajeTran=='limpiarPie'){
document.getElementById("msjPie").value="";
objetoImg = document.getElementById("imgMsjTran");
objetoImg.src="/static/img/pie_esq_izq3.jpg";
return
}
if (mensajeTran){
document.getElementById("msjPie").value=mensajeTran;
mensaje=mensajeTran;
buscar = "exito";
if(mensaje.indexOf(buscar) != -1){
objetoImg = document.getElementById("imgMsjTran");
objetoImg.src="/static/img/pie_esq_izq_true.jpg";
}else{
objetoImg = document.getElementById("imgMsjTran");
objetoImg.src="/static/img/pie_esq_izq_error.jpg";
}
}
}
function cargarImagenPortal(filename,fileid,idimg,widVal,heiVal,textid){
if (!(filename.files && filename.files[0])) {
jAlert("No se tiene Imagen válida para mostrar.","AdministradorTiendaVirtual","");
} else {
var reader = new FileReader();
reader.onload = function (e) {
var extension = document.getElementById(fileid).value.substring(document.getElementById(fileid).value.lastIndexOf(".")+1).toLowerCase();
if (extension != 'gif' && extension != 'jpg' && extension != 'jpeg' && extension != 'png'){
document.getElementById(textid).value = "";
document.getElementById(fileid).value = "";
jAlert("Formato de imagen inválido.","AdministradorTiendaVirtual","");
} else {
var img=new Image();
img.src = e.target.result;
img.onload = function (){
if (img.width != widVal){
document.getElementById(textid).value = "";
document.getElementById(fileid).value = "";
jAlert("El Tamaño de la Imagen es incorrecto. Deber ser de " + widVal + " x " + heiVal + ".","AdministradorTiendaVirtual","");
}else if (img.height != heiVal) {
document.getElementById(textid).value = "";
document.getElementById(fileid).value = "";
jAlert("El Tamaño de la Imagen es incorrecto. Deber ser de " + widVal + " x " + heiVal + ".","AdministradorTiendaVirtual","");
}else {
$('#'+idimg).attr('src', e.target.result);
}
}
}
}
reader.readAsDataURL(filename.files[0]);
}
}
function aceptarPortal(formulario){
document.getElementById(formulario).submit();
}
function verificarSelectProductoAdministrar(){
var sel = document.getElementById( 'sel' );
if( sel.options[ sel.selectedIndex ].value !="" && sel.options[ sel.selectedIndex ].value !=0){
var contenedorCamposModificarProducto=document.getElementById("contenedorCamposModificarProducto");
var contenedorConsultaProducto=document.getElementById("contenedorConsultaProducto");
var contenedorDetalleConsultaProducto=document.getElementById("contenedorDetalleConsultaProducto");
if( sel.options[ sel.selectedIndex ].value ==1){
document.getElementById("mensaje").innerHTML="";
document.getElementById('solicitudItemId').value="";
document.getElementById("solicitudItemId").disabled=false;
document.getElementById("contenedorDatosItemId").style.display="block";
document.getElementById("contenedorDatosMarca").style.display="none";
contenedorConsultaProducto!=null?contenedorConsultaProducto.style.display="none":null;
contenedorDetalleConsultaProducto!=null?contenedorDetalleConsultaProducto.style.display="none":null;
document.getElementById('solicitudMarcaProducto').value="";
document.getElementById("solicitudMarcaProducto").disabled=false;
}else if( sel.options[ sel.selectedIndex ].value ==2){
document.getElementById("mensaje").innerHTML="";
document.getElementById('solicitudMarcaProducto').value="";
document.getElementById("solicitudMarcaProducto").disabled=false;
document.getElementById("contenedorDatosItemId").style.display="none";
document.getElementById("contenedorDatosMarca").style.display="block";
contenedorConsultaProducto!=null?contenedorConsultaProducto.style.display="none":null;
contenedorDetalleConsultaProducto!=null?contenedorDetalleConsultaProducto.style.display="none":null;
document.getElementById('solicitudItemId').value="";
document.getElementById("solicitudItemId").disabled=false;
}else if( sel.options[ sel.selectedIndex ].value ==3){
contenedorConsultaProducto!=null?contenedorConsultaProducto.style.display="none":null;
contenedorDetalleConsultaProducto!=null?contenedorDetalleConsultaProducto.style.display="none":null;
document.getElementById('solicitudItemId').value="";
document.getElementById("solicitudItemId").disabled=false;
document.getElementById('solicitudMarcaProducto').value="";
document.getElementById("solicitudMarcaProducto").disabled=false;
consultarProductos_Act_Inac('activo');
}else if( sel.options[ sel.selectedIndex ].value ==4){
contenedorConsultaProducto!=null?contenedorConsultaProducto.style.display="none":null;
contenedorDetalleConsultaProducto!=null?contenedorDetalleConsultaProducto.style.display="none":null;
document.getElementById('solicitudItemId').value="";
document.getElementById("solicitudItemId").disabled=false;
document.getElementById('solicitudMarcaProducto').value="";
document.getElementById("solicitudMarcaProducto").disabled=false;
consultarProductos_Act_Inac('inactivo');
}else if( sel.options[ sel.selectedIndex ].value =="select"){
document.getElementById("contenedorDatosItemId").style.display="none";
document.getElementById("contenedorDatosMarca").style.display="none";
contenedorConsultaProducto!=null?contenedorConsultaProducto.style.display="none":null;
contenedorCamposModificarProducto!=null?contenedorCamposModificarProducto.style.display="none":null;
contenedorDetalleConsultaProducto!=null?contenedorDetalleConsultaProducto.style.display="none":null;
}
}
}<file_sep>/login/views.py
# Create your views here.
from django.shortcuts import render
from django.views.generic import View
#def login(request):
# return render_to_response('login/login.html', locals(), context_instance = RequestContext(request))
class LoginView(View):
def get(self, request, *args, **kwargs):
return render(request, 'login/login.html', locals())
<file_sep>/utils/templatetags/tags_html.py
import datetime
import locale
from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
register = template.Library()
# ---------- Ver la informacion del pie de pagina ----------
# ---------- tags para locate local ----------
#@register.simple_tag
#def info_fecha():
# now = datetime.datetime.now()
# locale.setlocale(locale.LC_ALL, 'esp')
# cadena = now.strftime("%A %d de %B de %Y - %I:%M %p")
# cadenaParse = unicode(cadena, "latin-1")
# return '%s' % (cadenaParse)
# ---------- tags para locate de desarrollo ----------
@register.simple_tag
def info_fecha():
now = datetime.datetime.now()
locale.setlocale(locale.LC_ALL, 'es_VE.utf8')
cadena = now.strftime("%A %d de %B de %Y - %I:%M %p")
return '%s' % cadena
# ---------- Referencias de la libreria static ----------
@register.simple_tag
def css_tag(css):
return '%s%s%s' % (settings.STATIC_URL, 'css/', css)
@register.simple_tag
def js_tag(js):
return '%s%s%s' % (settings.STATIC_URL, 'js/', js)
@register.inclusion_tag('img.html')
def image_tag(img, ancho, alto, ):
return {'imagen': '%s%s%s' % (settings.STATIC_URL, 'img/', img),
'ancho': '%s%s' % ('', ancho),
'alto': '%s%s' % ('', alto)}
@register.inclusion_tag('imgMenu.html')
def image_tag_menu(id, clas, img, alt, ancho, alto):
return {'id': '%s%s' % ('', id),
'clas': '%s%s' % ('', clas),
'imagen': '%s%s%s' % (settings.STATIC_URL, 'img/', img),
'alt': '%s%s' % ('', alt),
'ancho': '%s%s' % ('', ancho),
'alto': '%s%s' % ('', alto)}
# ---------- Link a cadenas o imagenes ----------
@register.simple_tag
def template_tag(templateTags):
return '%s%s' % (settings.AUTOLOAD_TEMPLATETAGS, templateTags)
@register.inclusion_tag('js_img.html')
def js_img_tag(js, img):
js = '%s' % (js)
imagen = '%s%s%s' % (settings.STATIC_URL, 'img/', img)
return {'js': js, 'imagen': imagen}
@register.inclusion_tag('url.html')
def url_tag(title, link):
link_to = reverse(link) # Del nombre del link se obtiene la url
return {'title': title, 'link_to': link_to, }
@register.inclusion_tag('url_img.html')
def url_img_tag(img, link):
imagen = '%s%s%s' % (settings.STATIC_URL, 'img/', img)
link_to = reverse(link) # Del nombre del link se obtiene la url
return {'imagen': imagen, 'link_to': link_to, }
@register.inclusion_tag('url_button.html')
def url_button(title, link):
link_to = reverse(link) # Del nombre del link se obtiene la url
return {'title': title, 'link_to': link_to, }
# ---------- Aplica un filtro en los campos de fecha ----------
@register.filter
def filtro_fecha(fecha):
return fecha.strftime("%d/%m/%Y - %H:%M")
# Modo de llamado {{ alguna_variable_a_filtrar|filtro_fecha }}
|
e8ece9144d4125799d534abc87f2f1ed87b83a14
|
[
"JavaScript",
"Python"
] | 8 |
Python
|
MugLeo/sgfs
|
19e1b02738a414a37a772b287de6c408aa3112e2
|
67fa2c81af37e0cda926c40083d5254aeac76d07
|
refs/heads/master
|
<repo_name>SampathSandaru/e-commerse-lab-practicele<file_sep>/index.php
<!DOCTYPE html>
<?php
include ('page/conn.php');
session_start();
$name="";
if(isset($_SESSION['id'])){
$name="WELCOME ".$_SESSION['fname'];
$val= "<a href=\"page/logout.php\"> Log out</a>";
}else{
$val= "<a href=\"page/login.php\"> Log in</a>";
}
if(isset($_POST['submit'])){
header("location:page/product.php");
}
?>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Shop Homepage - Shoe Box</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/shop-homepage.css" rel="stylesheet">
<!-- Custom icon package link -->
<link href="icon/open-iconic-master/font/css/open-iconic-bootstrap.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var cou=3;
$("button").click(function(){
cou=cou+3;
$("#sql").load("load.php",{
cou_N:cou
});
});
});
</script>
<style>
.img-fluid{
width:450px;
height: 300px;
}
.btn{
background-color: blue;
color: white;
padding: 5px;
margin: 3px;
width: 85%;
}
.a{
background-color: brown;
}
</style>
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="#">Shoe Box</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#"><?php echo $name;?><span class="oi oi-cart" ></span></a>
</li>
<li class="nav-item active">
<a class="nav-link" href="#">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="page/cart.php">Cart <span class="oi oi-cart" ></span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="page/contact.php">Contact</a>
</li>
<li class="nav-item">
<span class="nav-link"><?php echo $val;?></span>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1 class="my-4">Shop Name</h1>
<div class="list-group">
<a href="#" class="list-group-item">Category 1</a>
<a href="#" class="list-group-item">Category 2</a>
<a href="#" class="list-group-item">Category 3</a>
</div>
</div>
<!-- /.col-lg-3 -->
<div class="col-lg-9">
<div id="carouselExampleIndicators" class="carousel slide my-4" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner" role="listbox" >
<?php
$slide_query = "SELECT * FROM `slide`";
$slide_result = mysqli_query($con,$slide_query);
if($slide_result){
while($img = mysqli_fetch_assoc($slide_result)){
if ($img['id']==1){
echo "<div class=\"carousel-item active\">";
}else{
echo "<div class=\"carousel-item\">";
}
echo "<img class=\"d-block img-fluid\" src={$img['img']} alt=\"First slide\">";
echo "</div>";
}
}else{
echo "error";
}
?>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<div class="row" id="sql">
<?php
$sql="SELECT * FROM `sb_product` LIMIT 3";
$reu=mysqli_query($con,$sql);
if($reu){
while($recode=mysqli_fetch_assoc($reu)){
$id=$recode['id'];
echo "<div class=\"col-lg-4 col-md-6 mb-4\">";
echo "<div class=\"card h-100\">";
echo "<a href=\"#\"><img class=\"card-img-top\" src={$recode['prod_image']} ></a>";
echo "<div class=\"card-body\">";
echo "<h4 class=\"card-title\">";
echo "</h4>";
echo "<h5>Rs. $recode[prod_price]</h5>";
echo "<p class=\"card-text\">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur!</p>";
echo "</div>";
echo "<div class=\"card-footer\">";
echo "<a href=\"page/product.php?id=$id\" class=\"btn\">View Shoe</a>";
// echo "<input type=\"submit\" name=\"cart\" class=\"btn a\" value=\"Add to Cart\">";
// echo "<small class=\"text-muted\">★ ★ ★ ★ ☆</small>";
echo "</div>";
echo "</div>";
echo "</div>";
}
}
?>
</div>
<!-- /.row -->
</div>
<!-- /.col-lg-9 -->
</div>
<!-- /.row -->
<div id="demo">
<button type="button">More details</button>
</div>
</div>
<!-- /.container -->
<!-- Footer -->
<footer class="py-5 bg-dark">
<div class="container">
<div class="row ">
<a class="nav-link text-white" href="#">Home
<span class="sr-only">(current)</span>
</a>
<a class="nav-link text-white" href="#">Cart <span class="oi oi-cart" ></span></a>
<a class="nav-link text-white" href="#">Login / SignUp <span class="oi oi-account-login"></span></a>
<a class="nav-link text-white" href="#">Contact</a>
</div>
<p class="m-0 text-center text-white">Copyright © Your Website 2017</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
</body>
</html><file_sep>/page/cart.php
<?php
include('conn.php');
session_start();
if(isset($_GET['cart_id'])){
$delete_q="DELETE FROM `cart` WHERE cart_id=$_GET[cart_id]";
$re=mysqli_query($con,$delete_q);
if($re){
//echo "ok";
}
}else{
}
?>
<html>
<head>
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
.tb{
margin-top: 100px;
width: 100%;
text-align: center;
box-shadow: 8px 4px 8px 0 rgba(0, 0, 0, 0.3), 0 6px 20px 0 rgba(0, 0, 0, 0.2);
}
.tb th{
padding: 15px;
background-color: #e8e6e6;
}
.tb td{
padding: 10px;
background-color: #f7fafa;
border-bottom: 1px solid black;
}
img{
width:70px;
height: 70px;
}
.fa:hover{
transform: scale(1.03);
transition: 0.3s;
cursor: pointer;
color: red;
}
.card{
width: 90%;
height: 300px;
margin-top: 100px;
position: relative;
box-shadow: 8px 4px 8px 0 rgba(0, 0, 0, 0.3), 0 6px 20px 0 rgba(0, 0, 0, 0.2);
padding: 10px;
}
.tb_card{
width: 100%;
}
.tb_card th{
padding: 8px;
}
.tb_card td{
padding: 12px;
}
.btn{
background-color: red;
color: white;
}
</style>
</head>
<body>
<?php
include('prod_header.php');
?>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-6">
<table class="tb">
<tr>
<th>Item</th>
<th>Name</th>
<th>Quantity</th>
<th>Price (Rs)</th>
<th>Total Price (Rs)</th>
<th>Remove</th>
</tr>
<?php
$tot=0;
$di_tot=0;
$query="SELECT * FROM `cart` c,`sb_product` p WHERE user_id='{$_SESSION['id']}' AND c.item_id=p.id";
$result=mysqli_query($con,$query);
if($result){
while($recode=mysqli_fetch_assoc($result)){
$tot_pr=$recode['prod_price']*$recode['quantity'];
$tb="<tr>";
$tb.="<td><img src=\"$recode[prod_image]\"</td>";
$tb.="<td>$recode[prod_name]</td>";
$tb.="<td>$recode[quantity]</td>";
$tb.="<td>$recode[prod_price]</td>";
$tb.="<td>$tot_pr</td>";
$tb.="<td><a href=\"cart.php?cart_id=$recode[cart_id]\"<i class=\"fa fa-trash\"></i></a></td>";
$tb.="</tr>";
$tot=$tot+ $tot_pr;
echo $tb;
}
// echo "<tr><td>$tot</td></tr>";
}else{
echo "error";
}
?>
</table>
</div>
<div class="col-md-4">
<div class="card">
<table class="tb_card">
<tr>
<th>Your Order</th>
</tr>
<tr>
<td>SubTotal</td>
<td>Rs :<?php echo $tot;?></td>
</tr>
<tr>
<td>Discount 7%</td>
<td>-Rs :<?php if($tot>10000){ $di_tot=($tot*7)/100;}else{ $di_tot=0;} echo $di_tot;?></td>
</tr>
<tr>
<td>Total</td>
<td>Rs :<?php echo $tot-$di_tot;?></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="pay" value="Place Order" class="btn"></td>
</tr>
</table>
</div>
</div>
</div>
</body>
</html><file_sep>/page/conn.php
<?php
$con=mysqli_connect("localhost","root","","shop");
if($con){
// echo "database ok";
}
?><file_sep>/header.php
<html>
<head>
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="#">ShoeMart</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.php">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Services</a>
</li>
<li class="nav-item">
<a class="nav-link" href="contactus.php">Contact</a>
</li>
<li class="nav-item">
<a href="page/cart.php" class="nav-link">Cart</a>
</li>
<?php
if (isset($_SESSION['uname'])) {
echo '<li class="nav-item">';
echo '<a class="nav-link" href="logout.php">Logout</a>';
echo '</li>';
echo '<li class="nav-item">';
echo '<p style="color:white;">'.$_SESSION['uname'].'</p>';
echo '</li>';
}
else
{
echo '<li class="nav-item">';
echo '<a class="nav-link" href="login.php">Login</a>';
echo '</li>';
}
?>
</ul>
</div>
</div>
</nav>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Cart</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button class='btn btn-danger' type='submit' name='submit'>Pay Now</button>
</div>
</div>
</div>
</div>
</body>
</html><file_sep>/page/product.php
<?php
include('conn.php');
session_start();
if(!isset($_SESSION['id'])){
header("location:login.php");
}
$uid=$_SESSION['id'];
$id=$_GET['id'];
$_SESSION['item_id']=$_GET['id'];
$sql="SELECT * FROM `sb_product` p, `cart` c WHERE id='$id' AND c.item_id=p.id";
$result=mysqli_query($con,$sql);
if($result){
$recode=mysqli_fetch_assoc($result);
$img=$recode['prod_image'];
$prod_price=$recode['prod_price'];
$prod_name=$recode['prod_name'];
}
//
// if(isset($_POST['cart'])){
// $q=$_POST['quantity'];
//
// $c_tb="INSERT INTO `cart` (user_id,quantity,item_id) VALUES('{$uid}','{$q}','{$id}')";
// $c_result=mysqli_query($con,$c_tb);
// if($c_result){
//
// }else{
// echo "error";
// }
// }
?>
<html>
<head>
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="../vendor/jquery/jquery.min.js"></script>
<!--poup box link-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!--poup box link-->
<script>
function showSizeDetails(id){
var xhttp;
if(id == ""){
document.getElementById("d").innerHTML="ghdfgh";
return;
}
xhttp = new XMLHttpRequest();
var input = document.getElementById("quantity").value;
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var input = document.getElementById("quantity").value;
}
};
xhttp.open("GET","cart_ajex.php?qua=" + input, true);
xhttp.send();
}
</script>
<style>
img{
width:350px;
height: 350px;
margin-top:100px;
border: 1px solid red;
}
.details{
margin-top: 150px;
}
td{
padding: 15px;
}
.btn{
background-color: red;
color: antiquewhite;
width:46%;
}
</style>
</head>
<body>
<?php include('prod_header.php');?>
<br>
<br>
<div class="container">
<div class="row">
<div class="col-md-5">
<div class="">
<img src="<?php echo $img;?>" class="img1">
<?php
// echo $des;
?>
</div>
</div>
<div class="col-md-4 details">
<form method="post">
<table style="width:80%;">
<tr>
<td><b><?php echo "Rs ".$prod_price;?></b></td>
</tr>
<tr>
<td><?php echo $prod_name;?></td>
</tr>
<tr>
<td>Quantity <input type="number" value="1" id="quantity" min="1" name="quantity" style="width:40%;border-color:green;border-radius:10px;text-align: center;" max="10"></td>
</tr>
<tr>
<td><input type="submit" class="btn" value="Buy Now">
<button type="button" name="cart" class="btn" value="<?php echo $id;?>" onclick='showSizeDetails(this.value)' style="background-color:orange" data-toggle="modal" data-target="#exampleModal">Add to Cart</button>
</td>
</tr>
<tr>
<td> <i class="fa fa-cc-visa" style="color:navy;"></i>
<i class="fa fa-cc-amex" style="color:blue;"></i>
<i class="fa fa-cc-mastercard" style="color:red;"></i>
<i class="fa fa-cc-discover" style="color:orange;"></i>
</td>
</tr>
</table>
</form><samp id="d"></samp>
</div>
<!--poup box-->
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<!--
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
-->
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Cart</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Item Added to Cart.!
</div>
<div class="modal-footer">
<!--
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
-->
</div>
</div>
</div>
</div>
<!--poup box-->
</div>
</div>
</body>
</html><file_sep>/load.php
<?php
include ('page/conn.php');
$cou_N= $_POST['cou_N'];
$sql="SELECT * FROM `sb_product` LIMIT $cou_N";
$reu=mysqli_query($con,$sql);
if($reu){
while($recode=mysqli_fetch_assoc($reu)){
$id=$recode['id'];
echo "<div class=\"col-lg-4 col-md-6 mb-4\">";
echo "<div class=\"card h-100\">";
echo "<a href=\"#\"><img class=\"card-img-top\" src={$recode['prod_image']} ></a>";
echo "<div class=\"card-body\">";
echo "<h4 class=\"card-title\">";
echo "</h4>";
echo "<h5>Rs. $recode[prod_price]</h5>";
echo "<p class=\"card-text\">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur!</p>";
echo "</div>";
echo "<div class=\"card-footer\">";
echo "<a href=\"page/product.php?id=$id\" class=\"btn\">View Shoe</a>";
// echo "<input type=\"submit\" name=\"cart\" class=\"btn a\" value=\"Add to Cart\">";
// echo "<small class=\"text-muted\">★ ★ ★ ★ ☆</small>";
echo "</div>";
echo "</div>";
echo "</div>";
}
}
?> <file_sep>/page/prod_header.php
<?php
include('conn.php');
//session_start();
$user_id=$_SESSION['id'];
function cou($user_id,$con){
$count_query="SELECT sum(quantity) as num from `cart` WHERE user_id='$user_id' GROUP by (user_id)";
$count_result=mysqli_query($con,$count_query);
if($count_result){
$rec=mysqli_fetch_assoc($count_result);
$cart_num=$rec['num'];
}
return $cart_num;
}
?>
<html>
<head>
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="#">ShoeMart</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="../index.php">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Services</a>
</li>
<li class="nav-item">
<a class="nav-link" href="contact.php">Contact</a>
</li>
<li class="nav-item">
<a href="cart.php" class="nav-link"><sup><?php echo cou($user_id,$con);?></sup><i class="fa fa-shopping-cart" style="color:white;width:20%;"></i></a>
</li>
<?php
// if (isset($_SESSION['uname'])) {
// echo '<li class="nav-item">';
// echo '<a class="nav-link" href="logout.php">Logout</a>';
// echo '</li>';
// echo '<li class="nav-item">';
// echo '<p style="color:white;">'.$_SESSION['uname'].'</p>';
// echo '</li>';
// }
// else
// {
// echo '<li class="nav-item">';
// echo '<a class="nav-link" href="login.php">Login</a>';
// echo '</li>';
// }
?>
</ul>
</div>
</div>
</nav>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Cart</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
</body>
</html><file_sep>/page/cart_ajex.php
<?php
include('conn.php');
session_start();
$uid=$_SESSION['id'];
$q=$_GET['qua'];
$id=$_SESSION['item_id'];
$sql="INSERT INTO `cart` (user_id,quantity,item_id) VALUES('{$uid}','{$q}','{$id}')";
// $sql = "SELECT * FROM `stock` WHERE `size` = {$_GET['size']}";
$result = mysqli_query($con, $sql);
//$rowProId = mysqli_fetch_assoc($result);
//$_SESSION['maxSize'] = $rowProId['available'];
echo "ok";
//echo $rowProId['available'];
?><file_sep>/page/login.php
<?php
include('conn.php');
session_start();
if(isset($_POST['submit_reg'])){
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$number=$_POST['num'];
$email=$_POST['email'];
$pwd1=$_POST['pwd1'];
$pwd2=$_POST['pwd2'];
if($pwd1!=$pwd2){
echo "<script>alert('error')</script>";
}else{
$insert_query="INSERT INTO `user` (first_name,last_name,email,password,number) VALUES ('{$fname}','{$lname}','{$email}','{$pwd2}','{$number}')";
$insert_result=mysqli_query($con,$insert_query);
if($insert_result){
echo "<script>alert('success')</script>";
}else{
echo "<script>alert('error')</script>";
}
}
}
?>
<?php
$error="";
if(isset($_POST['submit'])){
$email=$_POST['email'];
$password=$_POST['<PASSWORD>'];
$query1 = "SELECT * FROM `user` WHERE email = '$email' AND password = '$<PASSWORD>' LIMIT 1";
$result = mysqli_query($con, $query1);
if($result){
if(mysqli_num_rows($result)==1){
$recode=mysqli_fetch_assoc($result);
$_SESSION['id']=$recode['id'];
$_SESSION['fname']=$recode['first_name'];
header("location:../index.php");
}else{
$error="<td style=\"color:red;\">Username or Password incorrect</td>";
}
}else{
//query error;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link href="../css/login_page.css" rel="stylesheet" type="text/css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js
"></script>
<style>
.btn_l{border: none;
background-color:#edf7f3;
width: 49%;
height: 40px;
}
</style>
</head>
<body>
<!--nav bar-->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="#">Shoe Box</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#"><span class="oi oi-cart" ></span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="../index.php">Home
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="contact.php">Contact <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<span class="nav-link"></span>
</li>
</ul>
</div>
</div>
</nav>
<!--end of nav bar-->
<div class="div2">
<form method="post">
<table class="table_1" id="log_tb">
<tr>
<?php echo $error;?>
</tr>
<tr>
<td>User Name</td>
</tr>
<tr>
<td><input type="text" name="email" class="form-control" placeholder="Email"> </td>
</tr>
<tr>
<td>Password</td>
</tr>
<tr>
<td><input type="password" name="password" class="form-control" placeholder="<PASSWORD>"> </td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Login" class="btn">
<input type="reset" value="Cansel" class="btn">
</td>
</tr>
<tr>
<td>Forget Your Password?</td>
</tr>
<tr>
<td> Don't have an account! <a href="#" id="sing_in">Sign Up Here</a></td>
</tr>
</table>
</form>
<!--user register form-->
<form method="post">
<table class="table2" id="rge_tb">
<tr>
<td>First Name</td>
<td><input type="text" name="fname" class="form-control" placeholder="First Name"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" class="form-control" placeholder="Last Name"></td>
</tr>
<tr>
<td>Contact Number</td>
<td><input type="text" name="num" class="form-control" placeholder="0711234567"></td>
</tr>
<tr>
<td>Email Address</td>
<td><input type="email" name="email" class="form-control" placeholder="email Address"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="<PASSWORD>" name="pwd1" class="form-control" placeholder="<PASSWORD>"> </td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="password" name="pwd2" class="form-control" placeholder="Confirm password"> </td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="submit_reg" value="Register" class="btn">
<input type="reset" value="Cansel" class="btn">
</td>
</tr>
<tr>
<td></td>
<td>Do you have an account? <a href="#" id="log">Log in</a> </td>
</tr>
</table>
</form>
<!---->
</div>
<script>
$(document).ready(function(){
$("#sing_in").click(function(){
$("#log_tb").fadeOut("3000");
$("#rge_tb").fadeIn("3000");
});
$("#log").click(function(){
$("#rge_tb").fadeOut("3000");
$("#log_tb").fadeIn("3000");
});
});
</script>
</body>
</html><file_sep>/shop.sql
-- phpMyAdmin SQL Dump
-- version 4.7.9
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Feb 23, 2020 at 10:19 AM
-- Server version: 5.7.21
-- PHP Version: 5.6.35
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `shop`
--
-- --------------------------------------------------------
--
-- Table structure for table `cart`
--
DROP TABLE IF EXISTS `cart`;
CREATE TABLE IF NOT EXISTS `cart` (
`cart_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`quantity` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
PRIMARY KEY (`cart_id`)
) ENGINE=MyISAM AUTO_INCREMENT=108 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `cart`
--
INSERT INTO `cart` (`cart_id`, `user_id`, `quantity`, `item_id`) VALUES
(79, 1, 2, 5),
(80, 1, 1, 1),
(107, 1, 1, 2),
(94, 1, 1, 3),
(102, 1, 1, 2),
(105, 1, 1, 2),
(106, 1, 1, 2),
(81, 1, 1, 1),
(96, 1, 1, 3),
(100, 1, 1, 2),
(68, 1, 2, 1),
(67, 1, 2, 2),
(57, 2, 1, 3);
-- --------------------------------------------------------
--
-- Table structure for table `item`
--
DROP TABLE IF EXISTS `item`;
CREATE TABLE IF NOT EXISTS `item` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`img` varchar(500) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `sb_product`
--
DROP TABLE IF EXISTS `sb_product`;
CREATE TABLE IF NOT EXISTS `sb_product` (
`id` varchar(5) NOT NULL,
`prod_name` varchar(70) NOT NULL,
`prod_price` decimal(10,0) NOT NULL,
`prod_stock` int(11) NOT NULL,
`prod_image` varchar(255) NOT NULL,
`prod_desc` varchar(500) NOT NULL,
`prod_weight` double NOT NULL,
`prod_location` int(100) NOT NULL,
`prod_cat_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `prod_cat_id` (`prod_cat_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `sb_product`
--
INSERT INTO `sb_product` (`id`, `prod_name`, `prod_price`, `prod_stock`, `prod_image`, `prod_desc`, `prod_weight`, `prod_location`, `prod_cat_id`) VALUES
('0001', 'LADIES FLIP FLOP', '500', 100, 'https://images-na.ssl-images-amazon.com/images/I/61qxQqexHGL._UX395_.jpg', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur! Lorem ipsum dolor sit amet.', 100, 1, 1),
('0002', 'Pasikuda Tribal Printed', '600', 200, 'http://www.dsifootwear.com/822-large_default/pasikuda-tribal-printed.jpg', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur!', 200, 1, 1),
('0003', 'Black Mumba Heel', '4000', 200, 'https://n.nordstrommedia.com/ImageGallery/store/product/Zoom/7/_9788727.jpg?h=365&w=240&dpr=2&quality=45&fit=fill&fm=jpg', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur!', 150, 1, 2),
('0004', 'Costbuy Pump Heel', '6000', 100, 'https://n.nordstrommedia.com/ImageGallery/store/product/Zoom/7/_9788727.jpg?h=365&w=240&dpr=2&quality=45&fit=fill&fm=jpg', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur! Lorem ipsum dolor sit amet.', 400, 1, 2),
('0005', 'Embelisshed Satin Block', '2000', 300, 'https://img.davidsbridal.com/is/image/DavidsBridalInc/Set-ELSA-10888854-Ivory', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur!', 0, 0, 2),
('0006', 'Sparx CD0096 Canvas Shoes', '6000', 50, 'https://rukminim1.flixcart.com/image/832/832/jao8uq80/shoe/3/r/q/sm323-9-sparx-white-original-imaezvxwmp6qz6tg.jpeg?q=70', 'Amet numquam aspernatur! Lorem ipsum dolor sit amet.', 0, 0, 3),
('0007', 'Nike OG Blue', '10000', 25, 'https://n1.sdlcdn.com/imgs/f/r/6/Nike-OG-Blue-Training-Shoes-SDL168067363-1-924bf.jpg', 'Founded in 1964, Nike is the world\'s leading manufacturer of sports apparel, footwear and sports equipment. Using high technology and design innovation, Nike continually creates what is aspired and not just what is necessary. All of Nike\'s products are meant to deliver high performance, durability and great comfort.', 0, 0, 3);
-- --------------------------------------------------------
--
-- Table structure for table `slide`
--
DROP TABLE IF EXISTS `slide`;
CREATE TABLE IF NOT EXISTS `slide` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`img` varchar(1000) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `slide`
--
INSERT INTO `slide` (`id`, `img`) VALUES
(1, 'https://images.ctfassets.net/od02wyo8cgm5/mwtuRPXhS6CHwQB0oqA11/78ebafbc12f98797c0fd7b5c4cd266bd/cloud_x_1-fw19-midnight_cobalt-m-g1.png'),
(2, 'https://vader-prod.s3.amazonaws.com/1565108493-nike-zoom-pegasus-35-turbo-0019-1530560986.jpg'),
(3, 'https://c.static-nike.com/a/images/t_PDP_1280_v1/f_auto/jnr2xxiyekwatkardxpr/air-presto-id-shoe.jpg'),
(4, 'https://dks.scene7.com/is/image/GolfGalaxy/18ADIMNMDR1BLKGRYMNS_Black_Gum?wid=1080&fmt=jpg'),
(5, 'https://c.static-nike.com/a/images/t_PDP_1280_v1/f_auto/17a6531e-d119-4edc-a8b5-ae9d068629d0/undercover-air-max-720-shoe-bspk4f.jpg'),
(9, 'https://vader-prod.s3.amazonaws.com/1565108493-nike-zoom-pegasus-35-turbo-0019-1530560986.jpg'),
(10, 'https://images.ctfassets.net/od02wyo8cgm5/mwtuRPXhS6CHwQB0oqA11/78ebafbc12f98797c0fd7b5c4cd266bd/cloud_x_1-fw19-midnight_cobalt-m-g1.png'),
(11, 'https://dks.scene7.com/is/image/GolfGalaxy/18ADIMNMDR1BLKGRYMNS_Black_Gum?wid=1080&fmt=jpg'),
(12, 'https://c.static-nike.com/a/images/t_PDP_1280_v1/f_auto/17a6531e-d119-4edc-a8b5-ae9d068629d0/undercover-air-max-720-shoe-bspk4f.jpg');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
DROP TABLE IF EXISTS `user`;
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(15) NOT NULL,
`last_name` varchar(15) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(60) NOT NULL,
`number` varchar(15) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`id`, `first_name`, `last_name`, `email`, `password`, `number`) VALUES
(1, 'lahiru', '<PASSWORD>ath', '<EMAIL>', '123', '<PASSWORD>'),
(2, 'lahiru', 'sampath', '<EMAIL>', '123', '07663304183');
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
26fa263fb5c32867a2175ae6ca3ace41cc535baf
|
[
"SQL",
"PHP"
] | 10 |
PHP
|
SampathSandaru/e-commerse-lab-practicele
|
cd78374560c91b24a7f5304fba7eb0eaf09f43a7
|
0d564279c2cf855a94771e690fc7f0adc4127adc
|
refs/heads/master
|
<repo_name>jordanmarques/issou-checker<file_sep>/src/main/java/task/CheckTask.java
package task;
import check.RestChecker;
import java.text.DateFormat;
import java.util.Date;
import java.util.TimerTask;
public class CheckTask extends TimerTask {
public void run() {
System.out.println("Start check " + getDate());
RestChecker request = new RestChecker("http://issou-randomizer.herokuapp.com/issou/wallpaper/random");
request.sendMailIfNotResponded("<EMAIL>", "issou-randomizer");
RestChecker request2 = new RestChecker(" https://issou-front.herokuapp.com");
request2.sendMailIfNotResponded("<EMAIL>", "issou-front");
System.out.println("End check " + getDate());
}
private String getDate() {
DateFormat shortDateFormat = DateFormat.getDateTimeInstance(
DateFormat.SHORT,
DateFormat.SHORT);
return shortDateFormat.format(new Date());
}
}
<file_sep>/src/main/java/check/RestChecker.java
package check;
import mail.Mail;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import javax.mail.MessagingException;
public class RestChecker {
private String url;
private Response response;
public RestChecker(String url) {
this.url = url;
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.build();
try{
this.response = client.newCall(request).execute();
} catch(Exception e){}
}
public int getCode(){
return response.code();
}
public Boolean isResponded(){
return response.code() == 200;
}
public void sendMailIfNotResponded(String recipients, String appName){
if( ! isResponded() ){
try {
Mail mail = new Mail();
mail.send(recipients,appName , appName + " is not responded to health check");
System.out.println(appName + " is not responded to health check");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
|
fce93c6635b3efa758a861984e496f14fdfc6ce4
|
[
"Java"
] | 2 |
Java
|
jordanmarques/issou-checker
|
fc3d7815007905ec2a14afeff2a008a19da73e41
|
f0ce501c5380810d637d82a307b8932fcf1130ea
|
refs/heads/master
|
<repo_name>ih-lab/CNN_Smoothie<file_sep>/CNN_basic/acc.py
import numpy as np
from collections import defaultdict
['adeno', 'squam']
def read_prediction(file_name, lables):
lable_dict = dict()
for i in range(len(lables)):
lable_dict[i] = lables[i]
evaluation = defaultdict(list)
f = open(file_name, 'r')
for line in f:
parsed = line.replace('\n', '').split('\t')
score = []
for i in range(1, len(parsed)):
score.append(float(parsed[i]))
image_name = parsed[0]
t_label = -1
image_name_ind = image_name.rfind('/')
image_name = image_name[image_name_ind+1:]
t_flag = True
for lable in ['adeno', 'squam']:
if image_name.find(lable) != -1 and t_flag:
t_label = lable
t_flag = False
if t_flag == -1:
print (image_name)
print('Error')
exit()
evaluation[image_name] = [t_label, score]
return evaluation, lables, lable_dict
def acc(evaluation, lables, lable_dict):
c = 0
t = 0
for image in evaluation:
t_label = evaluation[image][0]
p_label = lable_dict[np.argmax(evaluation[image][1])]
if t_label == p_label:
c+=1
t+=1
#print(image, p_label, t_label)
acc = c * 1. / t
return c, t, acc
def blend(preds):
c = 0
t = 0
pred1 = preds[0]
evaluation1 = pred1[0]
for image in evaluation1:
max_p = -1
max_s = -1
for p in range(len(preds)):
if np.max(preds[p][0][image][1]) > max_s:
max_p = p
max_s = np.max(preds[p][0][image][1])
t_label = evaluation1[image][0]
pred_ = preds[max_p]
vals_ = pred_[0][image][1]
lable_dict = pred_[2]
ind = np.argmax(vals_)
p_label = lable_dict[ind]
#print(image, t_label, p_label)
if t_label == p_label:
c+=1
t+=1
acc = c * 1. / t
return c, t, acc
#predictions from inception
file_name = 'result.txt'
lables1 = ['adeno', 'squam']
evaluation1, lables1, lable_dict1 = read_prediction(file_name, lables1)
print(acc(evaluation1, lables1, lable_dict1))
#exit()
<file_sep>/Readme.txt
The CNN_Smoothie pipeline presented here provides a novel framework that can be easily implemented for many different applications, including immunohistochemistry grading and detecting tumor subtypes and biomarkers. We revised the available Slim codes to fit the algorithms for running them on CPUs. For additional information and reference, please check the pre-print describing the method here:
Deep Convolutional Neural Networks Enable Discrimination of Heterogeneous Digital Pathology Images
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>
EBioMedicine (December 2017)
The link to the published journal version: http://dx.doi.org/10.1016/j.ebiom.2017.12.026
The Readme file is divided into two parts:
1) for running the CNN_basic algorithm look at the Readme at CNN_basic file.
2) for running other architectures of CNN such as Inception and ResNet look at the Readme in the "scripts" directory.
<file_sep>/CNN_basic/Readme.txt
Running the CNN with basic structure follow these steps:
1) Install the TensorFlow.
2) Divide the images with the original size into two or more classes based on the aim of classification (e.g. discrimination of adenocarcinoma and squamous cell lung cancer as two classes).
3) 70% of images should be selected as Train (train and validation) and 30% as Test sets. Therefore, the name of images as well as their path should be save as .txt files.
4) The CNN algorithm should be run on the Train set images using shell script.
5) The trained algorithms should be tested using Load.py on Test set images.
6) The accuracy can be measured using acc.py or other measurement codes.
7) The plot can be illustrated using plot illustration codes.
<file_sep>/CNN_basic/Load_2class.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib
matplotlib.use('TKAgg')
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets import base
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import random_seed
import matplotlib.pyplot as plt
import cv2
import numpy as np
import numpy as np
import gzip
import random as rand
import numpy
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.contrib.learn.python.learn.datasets import base
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import random_seed
class DataSet(object):
def __init__(self,
images,
labels,
fake_data=False,
one_hot=False,
dtype=dtypes.float32,
reshape=True,
seed=None):
"""Construct a DataSet.
one_hot arg is used only if fake_data is true. `dtype` can be either
`uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
`[0, 1]`. Seed arg provides for convenient deterministic testing.
"""
seed1, seed2 = random_seed.get_seed(seed)
# If op level seed is not set, use whatever graph level seed is returned
numpy.random.seed(seed1 if seed is None else seed2)
dtype = dtypes.as_dtype(dtype).base_dtype
if dtype not in (dtypes.uint8, dtypes.float32):
raise TypeError('Invalid image dtype %r, expected uint8 or float32' %
dtype)
if fake_data:
self._num_examples = 10000
self.one_hot = one_hot
else:
assert images.shape[0] == labels.shape[0], (
'images.shape: %s labels.shape: %s' % (images.shape, labels.shape))
self._num_examples = images.shape[0]
# Convert shape from [num examples, rows, columns, depth]
# to [num examples, rows*columns] (assuming depth == 1)
print(images.shape[0], images.shape[1], images.shape[2], images.shape[3])
if reshape:
images = images.reshape(images.shape[0],
images.shape[1] * images.shape[2] * images.shape[3])
if dtype == dtypes.float32:
# Convert from [0, 255] -> [0.0, 1.0].
images = images.astype(numpy.float32)
images = numpy.multiply(images, 1.0 / 255.0)
self._images = images
self._labels = labels
self._epochs_completed = 0
self._index_in_epoch = 0
@property
def images(self):
return self._images
@property
def labels(self):
return self._labels
@property
def num_examples(self):
return self._num_examples
@property
def epochs_completed(self):
return self._epochs_completed
def next_batch(self, batch_size, fake_data=False, shuffle=True):
start = self._index_in_epoch
# Shuffle for the first epoch
if self._epochs_completed == 0 and start == 0 and shuffle:
perm0 = numpy.arange(self._num_examples)
numpy.random.shuffle(perm0)
self._images = self.images[perm0]
self._labels = self.labels[perm0]
# Go to the next epoch
if start + batch_size > self._num_examples:
# Finished epoch
self._epochs_completed += 1
# Get the rest examples in this epoch
rest_num_examples = self._num_examples - start
images_rest_part = self._images[start:self._num_examples]
labels_rest_part = self._labels[start:self._num_examples]
# Shuffle the data
if shuffle:
perm = numpy.arange(self._num_examples)
numpy.random.shuffle(perm)
self._images = self.images[perm]
self._labels = self.labels[perm]
# Start next epoch
start = 0
self._index_in_epoch = batch_size - rest_num_examples
end = self._index_in_epoch
images_new_part = self._images[start:end]
labels_new_part = self._labels[start:end]
return numpy.concatenate((images_rest_part, images_new_part), axis=0) , numpy.concatenate((labels_rest_part, labels_new_part), axis=0)
else:
self._index_in_epoch += batch_size
end = self._index_in_epoch
return self._images[start:end], self._labels[start:end]
def read_image(image_path):
print(image_path)
image = cv2.imread(image_path, cv2.IMREAD_COLOR)
image = cv2.resize(image, (20, 20))
print("image shape", image.shape)
return np.array(image)
def read_labeled_image_list(image_list_file):
f = open(image_list_file, 'r')
filenames = []
labels = []
for line in f:
parsed = line.replace('\n', '').split('\t')
filenames.append(parsed[0])
print(line)
labels.append(int(parsed[1]))
return len(labels), filenames, labels
def read_dataset(image_list, lable_list):
nb_images = len(image_list)
images = np.zeros((nb_images, 20, 20, 3))
labels = np.zeros((nb_images, 2))
for i in range(nb_images):
images[i,:,:,:] = read_image(image_list[i])
labels[i, lable_list[i]] = 1
return images, labels
def read_data(image_list_file):
fake_data = False
one_hot = False
dtype = dtypes.float32
reshape = True
seed = None
nb_images, filenames, labels = read_labeled_image_list(image_list_file)
print(labels)
test_f = []
test_l = []
for i in range(nb_images):
test_f.append(filenames[i])
test_l.append(labels[i])
print(nb_images)
print(test_l)
test_images, test_labels = read_dataset(test_f, test_l)
print(test_labels)
options = dict(dtype=dtype, reshape=reshape, seed=seed)
test = DataSet(test_images, test_labels, **options)
return test._images, test._labels, filenames
test_images, test_labels, filenames = read_data('test.txt')
sess=tf.Session()
#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('my_test_model-1000.meta')
saver.restore(sess,tf.train.latest_checkpoint('./'))
graph = tf.get_default_graph()
x = graph.get_tensor_by_name("x:0")
y_ = graph.get_tensor_by_name("y_:0")
keep_prob = graph.get_tensor_by_name("keep_prob:0")
#W_conv1 = graph.get_tensor_by_name("W_conv1:0")
y = graph.get_tensor_by_name("y:0")
accuracy = graph.get_tensor_by_name("accuracy:0")
outputs = sess.run(y, feed_dict={x: test_images, y_: test_labels, keep_prob: 1.0})
lable_names = {0: 'adeno', 1 : 'squam'} #dictionary for name of classes. You can put anything you like.
cnt = 0
filename = 'result_06.txt'
fto = open(filename, 'w')
print(outputs)
for output in outputs:
label = np.argmax(output) #find the lable with the highest probabiliy
score = round(np.max(output),2)
print_out = filenames[cnt]
print(output, len(output))
for i in range(len(output)):
print_out += ('\t' + str(output[i]))
print_out += '\n'
output
print(print_out)
fto.write(print_out)
cnt+=1
fto.close()<file_sep>/CNN_basic/CNN_2class.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib
matplotlib.use('TKAgg')
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets import base
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import random_seed
import matplotlib.pyplot as plt
import cv2
import numpy as np
import numpy as np
import gzip
import random as rand
import numpy
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.contrib.learn.python.learn.datasets import base
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import random_seed
class DataSet(object):
def __init__(self,
images,
labels,
fake_data=False,
one_hot=False,
dtype=dtypes.float32,
reshape=True,
seed=None):
"""Construct a DataSet.
one_hot arg is used only if fake_data is true. `dtype` can be either
`uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
`[0, 1]`. Seed arg provides for convenient deterministic testing.
"""
seed1, seed2 = random_seed.get_seed(seed)
# If op level seed is not set, use whatever graph level seed is returned
numpy.random.seed(seed1 if seed is None else seed2)
dtype = dtypes.as_dtype(dtype).base_dtype
if dtype not in (dtypes.uint8, dtypes.float32):
raise TypeError('Invalid image dtype %r, expected uint8 or float32' %
dtype)
if fake_data:
self._num_examples = 10000
self.one_hot = one_hot
else:
assert images.shape[0] == labels.shape[0], (
'images.shape: %s labels.shape: %s' % (images.shape, labels.shape))
self._num_examples = images.shape[0]
# Convert shape from [num examples, rows, columns, depth]
# to [num examples, rows*columns] (assuming depth == 1)
print(images.shape[0], images.shape[1], images.shape[2], images.shape[3])
if reshape:
images = images.reshape(images.shape[0],
images.shape[1] * images.shape[2] * images.shape[3])
if dtype == dtypes.float32:
# Convert from [0, 255] -> [0.0, 1.0].
images = images.astype(numpy.float32)
images = numpy.multiply(images, 1.0 / 255.0)
self._images = images
self._labels = labels
self._epochs_completed = 0
self._index_in_epoch = 0
@property
def images(self):
return self._images
@property
def labels(self):
return self._labels
@property
def num_examples(self):
return self._num_examples
@property
def epochs_completed(self):
return self._epochs_completed
def next_batch(self, batch_size, fake_data=False, shuffle=True):
start = self._index_in_epoch
# Shuffle for the first epoch
if self._epochs_completed == 0 and start == 0 and shuffle:
perm0 = numpy.arange(self._num_examples)
numpy.random.shuffle(perm0)
self._images = self.images[perm0]
self._labels = self.labels[perm0]
# Go to the next epoch
if start + batch_size > self._num_examples:
# Finished epoch
self._epochs_completed += 1
# Get the rest examples in this epoch
rest_num_examples = self._num_examples - start
images_rest_part = self._images[start:self._num_examples]
labels_rest_part = self._labels[start:self._num_examples]
# Shuffle the data
if shuffle:
perm = numpy.arange(self._num_examples)
numpy.random.shuffle(perm)
self._images = self.images[perm]
self._labels = self.labels[perm]
# Start next epoch
start = 0
self._index_in_epoch = batch_size - rest_num_examples
end = self._index_in_epoch
images_new_part = self._images[start:end]
labels_new_part = self._labels[start:end]
return numpy.concatenate((images_rest_part, images_new_part), axis=0) , numpy.concatenate((labels_rest_part, labels_new_part), axis=0)
else:
self._index_in_epoch += batch_size
end = self._index_in_epoch
return self._images[start:end], self._labels[start:end]
def read_image(image_path):
# cv2.IMREAD_COLOR
# cv2.COLOR_BGR2GRAY
print(image_path)
image = cv2.imread(image_path, cv2.IMREAD_COLOR)
image = cv2.resize(image, (20, 20))
#image = cv2.resize(image, (48, 48))
print("image shape", image.shape)
#plt.imshow(image, cmap='gray')
#plt.show()
return np.array(image)
def read_labeled_image_list(image_list_file):
f = open(image_list_file, 'r')
filenames = []
labels = []
for line in f:
parsed = line.replace('\n', '').split('\t')
filenames.append(parsed[0])
print(line)
labels.append(int(parsed[1]))
return len(labels), filenames, labels
def read_dataset(image_list, lable_list):
nb_images = len(image_list)
images = np.zeros((nb_images, 20, 20, 3))
labels = np.zeros((nb_images, 2))
for i in range(nb_images):
images[i,:,:,:] = read_image(image_list[i])
labels[i, lable_list[i]] = 1
return images, labels
def read_data(image_list_file):
fake_data = False
one_hot = False
dtype = dtypes.float32
reshape = True
validation_size = 5000
seed = None
nb_images, filenames, labels = read_labeled_image_list(image_list_file)
combined = list(zip(filenames, labels))
rand.shuffle(combined)
filenames[:], labels[:] = zip(*combined)
for i in range(10):
print (filenames[i], labels[i])
print (nb_images)
nb_class = set()
for l in labels:
nb_class.add(l)
print (len(nb_class))
train_f = []
train_l = []
for i in range(532):
train_f.append(filenames[i])
train_l.append(labels[i])
validate_f = []
validate_l = []
for i in range(532,759):
validate_f.append(filenames[i])
validate_l.append(labels[i])
test_f = []
test_l = []
for i in range(759,760):
test_f.append(filenames[i])
test_l.append(labels[i])
print(nb_images)
train_images, train_labels = read_dataset(train_f, train_l)
validation_images, validation_labels = read_dataset(validate_f, validate_l)
test_images, test_labels = read_dataset(test_f, test_l)
options = dict(dtype=dtype, reshape=reshape, seed=seed)
train = DataSet(train_images, train_labels, **options)
validation = DataSet(validation_images, validation_labels, **options)
test = DataSet(test_images, test_labels, **options)
return base.Datasets(train=train, validation=validation, test = test)
TumorImage = read_data('train.txt')
def weight_variable(shape, name = 'noname'):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial, name = name)
def bias_variable(shape, name = 'noname'):
initial = tf.constant(0.1, shape = shape)
return tf.Variable(initial, name = name)
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
# Input layer
x = tf.placeholder(tf.float32, [None, 1200], name='x')
y_ = tf.placeholder(tf.float32, [None, 2], name='y_')
x_image = tf.reshape(x, [-1, 20, 20, 3])
# Convolutional layer 1
W_conv1 = weight_variable([5, 5, 3, 32], 'W_conv1')
b_conv1 = bias_variable([32], 'b_conv1')
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
# Convolutional layer 2
W_conv2 = weight_variable([5, 5, 32, 64], 'W_conv2')
b_conv2 = bias_variable([64], 'b_conv2')
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
# Fully connected layer 1
h_pool2_flat = tf.reshape(h_pool2, [-1, 5*5*64])
W_fc1 = weight_variable([5 * 5 * 64, 1024], 'W_fc1')
b_fc1 = bias_variable([1024], 'b_fc1')
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# Dropout
keep_prob = tf.placeholder(tf.float32, name = 'keep_prob')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# Fully connected layer 2 (Output layer)
W_fc2 = weight_variable([1024, 2], 'W_fc2')
b_fc2 = bias_variable([2], 'b_fc2')
y = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2, name='y')
# Evaluation functions
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')
print(x_image.get_shape())
print(h_pool2.get_shape())
print(h_pool2_flat.get_shape())
print(y.get_shape())
print(h_fc1.get_shape())
print(correct_prediction.get_shape())
# Training algorithm
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# Training steps
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
max_steps = 4000
for step in range(max_steps):
batch_xs, batch_ys = TumorImage.train.next_batch(200)
if (step % 50) == 0:
saver.save(sess, 'my_test_model',global_step=1000)
print(step, sess.run(accuracy, feed_dict={x: TumorImage.test.images, y_: TumorImage.test.labels, keep_prob: 1.0}))
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})
print(max_steps, sess.run(accuracy, feed_dict={x: TumorImage.test.images, y_: TumorImage.test.labels, keep_prob: 1.0}))
saver.save(sess, 'my_test_model', global_step=1000)
<file_sep>/SampleFinalResult/plot.py
import matplotlib
matplotlib.use('TKAgg')
import numpy as np
import matplotlib.pyplot as plt
import sys
import utils
import plot_utils as pu
def read_files(filename):
x = []
y = []
f = open(filename, 'r')
cnt = 0
for line in f:
if cnt != 0:
line_temp = line.replace(')\n', '')
line_temp = line_temp.replace(')', '')
line_temp = line_temp.replace(' (', '\t')
line_temp = line_temp.replace(' (', '\t')
line_temp = line_temp.replace(', ', '\t')
parsed = line_temp.split('\t')
print(parsed)
x.append(int(parsed[0]))
y.append(float(parsed[3]))
cnt+=1
return x, y
if __name__ == '__main__':
filenames = ['AdenoSquam', 'BladderBreastLungHe', 'BladderFourBiomarkers', 'BladderFourScores', 'BreastFiveBiomarkers', 'BreastFourScores']
pu.figure_setup()
fig_size = pu.get_fig_size(10, 8)
fig = plt.figure(figsize=fig_size)
ax = fig.add_subplot(111)
for filename in filenames:
x,y = read_files(filename + '.txt')
plt.plot(x, y, label=filename)
ax.set_xlabel('Number of Steps')
ax.set_ylabel('Accuracy')
ax.set_axisbelow(True)
ax.legend(loc='lower right')
plt.grid()
plt.tight_layout()
pu.save_fig(fig, '../cnn_acc_steps.pdf', 'pdf')
plt.show()<file_sep>/SampleFinalResult/FP_FN.py
import matplotlib
matplotlib.use('TKAgg')
import numpy as np
from collections import defaultdict
import matplotlib.pyplot as plt
import plot_utils as pu
def read_prediction(file_name, lables):
lable_dict = dict()
for i in range(len(lables)):
lable_dict[i] = lables[i]
evaluation = defaultdict(list)
f = open(file_name, 'r')
for line in f:
parsed = line.replace('\n', '').split('\t')
score = []
for i in range(1, len(parsed)):
score.append(float(parsed[i]))
image_name = parsed[0]
t_label = -1
image_name_ind = image_name.rfind('/')
image_name = image_name[image_name_ind+1:]
t_flag = True
for lable in lables:
if image_name.find('_' + lable) != -1 and t_flag:
t_label = lable
t_flag = False
if t_flag == -1:
print (image_name)
print('Error')
exit()
evaluation[image_name] = [t_label, score]
return evaluation, lables, lable_dict
def acc(evaluation, lables, lable_dict):
c = 0
t = 0
lables_count = dict()
for label in lables:
lables_count[label] = 0
cnt = 0
for image in evaluation:
t_label = evaluation[image][0]
p_label = lable_dict[np.argmax(evaluation[image][1])]
if t_label == p_label:
c+=1
t+=1
acc = 0
if t != 0:
acc = c * 1. / t
return c, t, acc
def TPR_FPR(evaluation, lables, lable_dict, thr):
c = 0
t = 0
lables_count = dict()
for label in lables:
lables_count[label] = 0
cnt = 0
FP = 0
FN = 0
TP = 0
TN = 0
for image in evaluation:
t_label = evaluation[image][0]
scores = evaluation[image][1]
#if np.max(evaluation[image][1]) >= thr:
if evaluation[image][1][0] > thr:
p_label = lable_dict[0]
if t_label == p_label:
TP+=1
else:
FP+=1
else:
p_label = lable_dict[1]
if t_label == p_label:
TN+=1
else:
FN+=1
return TP, FP, TN, FN
def TPR_FPR_01(evaluation, lables, lable_dict, thr):
c = 0
t = 0
lables_count = dict()
for label in lables:
lables_count[label] = 0
cnt = 0
FP = 0
FN = 0
TP = 0
TN = 0
for image in evaluation:
t_label = evaluation[image][0]
scores = evaluation[image][1]
#if np.max(evaluation[image][1]) >= thr:
if evaluation[image][1][1] > thr:
p_label = lable_dict[1]
if t_label == p_label:
TP+=1
else:
FP+=1
else:
p_label = lable_dict[0]
if t_label == p_label:
TN+=1
else:
FN+=1
return TP, FP, TN, FN
def clean_p(p):
c_p = []
c_flag = False
for v in p:
if v < 1 and not c_flag:
c_p.append(v)
else:
c_p.append(1)
c_flag = True
return c_p
lables1 = ['adeno', 'squam']
#exit()
lable_names = ['CNN', 'Inception-ResNet-v2 (last layer)', 'Inception-v3 (last layer)', 'Inception-v3 (last layer)', 'Inception-v3 (fine-tune)', 'Inception-v1 (fine-tune)']
file_names = ['CNN.txt', 'prediction_lastlayer_inception_resnet_v2.txt', 'inception3_lastlayer_4000.txt', 'inception3_lastlayer_12000.txt', 'prediction_load_inception_v3.txt', 'prediction_load_inception_v1.txt']
bins = []
bins.append(0.0)
bins.append(0.00001)
nb_bins = 10000
for i in range(1, nb_bins):
thr = ( 1. * i / nb_bins)
bins.append(thr)
print (bins)
bins.append(0.9999)
bins.append(0.99991)
bins.append(0.99992)
bins.append(0.99993)
bins.append(0.99994)
bins.append(0.99995)
bins.append(0.99996)
bins.append(0.99997)
bins.append(0.99998)
bins.append(0.99999)
bins.append(1.0)
pu.figure_setup()
fig_size = pu.get_fig_size(12, 10)
fig = plt.figure(figsize=fig_size)
ax = fig.add_subplot(111)
print(bins)
cnt = len(file_names) - 1
for file_name in reversed(file_names):
#print (file_name)
evaluation1, lables1, lable_dict1 = read_prediction(file_name, lables1)
#print(acc(evaluation1, lables1, lable_dict1))
p = []
r = []
FPR_0 = 0
FPR1_0 = 0
roc = 1
for thr in bins:
TP, FP, TN, FN = TPR_FPR(evaluation1, lables1, lable_dict1,thr)
TPR = TP * 1.0 / (TP + FN)
FPR = FP * 1.0 / (FP + TN)
TP1, FP1, TN1, FN1 = TPR_FPR_01(evaluation1, lables1, lable_dict1,thr)
TPR1 = TP1 * 1.0 / (TP1 + FN1)
FPR1 = FP1 * 1.0 / (FP1 + TN1)
p.append((TPR1 + TPR) / 2.0)
r.append((FPR1 + FPR) / 2.0)
roc += (0.5 * (FPR_0 - FPR) * TPR)
roc += (0.5 * (FPR1_0 - FPR1) * TPR1)
FPR_0 = FPR
FPR1_0 = FPR1
print(file_name, roc)
#print(p)
#print(r)
plt.plot(r, p, label=lable_names[cnt] + ', AUC=' + str(round(roc,2)))
cnt -= 1
#plt.title('')
plt.plot([0, 1], [0, 1], color='black', lw=1, linestyle='--')
plt.ylim([0., 1.05])
ax.legend(loc='lower right')
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.grid()
plt.tight_layout()
pu.save_fig(fig, 'adenosquam_FPR_TPR.pdf', 'pdf')
plt.show()
|
bad3364d8bb89dd09f520add95767c1d1f082571
|
[
"Python",
"Text"
] | 7 |
Python
|
ih-lab/CNN_Smoothie
|
6527337cc40311af78a416f5b3ebf607a7b04788
|
30d36e5c2dbc2dbe3dfb1f12f2734a46dc78dff5
|
refs/heads/master
|
<repo_name>GarridoSantiago/LUAMACROS<file_sep>/README.md
# LuaMacros
## English
This repo contains some code for programing a Numpad for personal use I upload a modified program written by a 3rd (keyID)
You will find the next codes in the repo:
- cambas3: a code for using in photoshop for digital painting
- F24: a blank code for you to modify as you want
- MatLab1: an initial code for using in MatLab
- keyID: a little modified code written by Potentium (Tanks Man!!)
##### if you wanna see the original code of Protentium look at this [video in youtube](https://www.youtube.com/watch?v=LsHhLZXrQsI&feature=youtu.be).
For now, the explanation of how to use the code is in Spanish someday of this I will translate it to English
## Spanish
Este repositorio contiene código para programar un teclado numérico para uso personal, use un programa modificado escrito por un tercero (KeyID). En este repositorio encontraras:
- cambas3: código para usar en Photoshop para pintura digital
- F24: un código en "blano" para modificar a tus necesidades
- MatLab1: un código inicial para usar en MatLab
- keyID: un codigo modificado ligeramente originalmente escrito por Potentium (Gracias!!)
##### Si quieres ver el contenido original de Potentium mira este [video en youtube](https://www.youtube.com/watch?v=LsHhLZXrQsI&feature=youtu.be).
## Download LuaMacros
[Download here/Descarga aquí](https://github.com/me2d13/luamacros).
<file_sep>/camvas3.lua
lmc_assign_keyboard('CAMBAS');
lmc_print_devices();
--[[PRES AND HOLD SHIFT (en los parenticis que hay abajo con 3 números el primero
es la tecla correspondiente al modificador en el teclado principal
en este caso 16 es shift usar key id para identificar)]]
lmc_set_handler('CAMBAS', function(button,direction)
if (direction == 0) then return end
if (button == 106) then lmc_send_input(16, 0, 0)
end
end
)
lmc_set_handler('CAMBAS', function(button,direction)
if (direction == 1) then return end
if (button == 106) then lmc_send_input(16, 0, 2)
end
end
)
--END PRESS AND HOLD shift------------------------------------------------------
--[[PRES AND HOLD CTRL (en los parenticis que hay abajo con 3 números el primero
es la tecla correspondiente al modificador en el teclado principal
en este caso 17 es ctrl usar key id para identificar)]]
lmc_set_handler('CAMBAS', function(button,direction)
if (direction == 0) then return end
if (button == 109) then lmc_send_input(17, 0, 0)
end
end
)
lmc_set_handler('CAMBAS', function(button,direction)
if (direction == 1) then return end
if (button == 109) then lmc_send_input(17, 0, 2)
end
end
)
--END PRESS AND HOLD CTRL-------------------------------------------------------
--[[PRES AND HOLD ALT (en los parenticis que hay abajo con 3 números el primero
es la tecla correspondiente al modificador en el teclado principal
en este caso 18 es alt usar key id para identificar)]]
lmc_set_handler('CAMBAS', function(button,direction)
if (direction == 0) then return end
if (button == 107) then lmc_send_input(18, 0, 0)
end
end
)
lmc_set_handler('CAMBAS', function(button,direction)
if (direction == 1) then return end
if (button == 107) then lmc_send_input(18, 0, 2)
end
end
)
--END PRESS AND HOLD ALT --------------------------------------------------------------------------
lmc_set_handler('CAMBAS', function(button,direction)
-- LA SIGUENTE LINEA ESPECIFICA CUANDO SE MANDA LA ORDEN:
-- 1 : CUANDO SE SUELTA LA TECLA 0: CUANDO SE APRIETA
if (direction == 0) then return end
--LOS SIGUIENTES COMANDOS ELIMINAN LA FUNCION DE LAS TECLAS QUE SE ASIGNARON COMO CTRL, ALT Y SHIFT
if (button == 106) then
lmc_send_keys('{F24}', 50)
elseif (button == 107) then
lmc_send_keys('{F24}', 50)
elseif (button == 109) then
lmc_send_keys('{F24}', 50)
--------------------------------------------------------------------------------------------------------------------------
--[[ sintaxis para programar las teclas:
elseif (button == NUMTECLA) then --EN ESTA LINEA SE CAMBIA "NUMTECLA" POR EL NÚMERO IDENTIFICADO CON keyID
lmc_send_keys('COMANDO', 50) -- EN ESTA SEGUNDA LINEA SE CAMBIA "COMANDO" POR LA TECLA O COMANDO DESEADO PARA LA TECLA
ESTO SE PUEDE REPETIR EL NÚMERO DE VECES NECESARIAS PARA UNA TECLA
SI QUIERES HACEr COMANDOS DE TECLAS COMO "CTRL+S" SE ESCRIBE ASI: '^s'
lo mismo con alt y shift
CTRL: ^
SHIFT: +
ALT: %
PARA ASIGNAR TECLAS ESPECIALES SE UTILIZAN LAS LLAMADAS CON {} POR EJEMPLO: {BACKSPACE}, {F12}, {TAB}.
PARA VER OTRAS TECLAS VE LA LISTA DE AQUÍ : https://github.com/me2d13/luamacros/wiki/List-of-Keys
SI QUIERES MODIFICAR UN GRUPO DE CARACTERES COMO "CTRL+ABC" EL GRUPO SE PONE ENTRE PARENTESIS '^(ABC)'
SI DEJAS UNA TECLA SIN NINGUNA FUNCION ES MEjOR ASIGNARLE {F24} COMO EN LAS LINEAS DE ARRIBA
]]
----------------------------------------------------------------------------------------------------------------------------
elseif (button == 8) then
lmc_send_keys('e', 50)
elseif (button == 12) then
lmc_send_keys('z', 50)
elseif (button == 13) then
lmc_send_keys('b', 50)
elseif (button == 33) then
lmc_send_keys('^w', 50)
elseif (button == 34) then
lmc_send_keys('n', 50)
elseif (button == 35) then
lmc_send_keys('^m', 50)
elseif (button == 36) then
lmc_send_keys('{F24}', 50)
elseif (button == 37) then
lmc_send_keys('^{F12}', 50)
elseif (button == 38) then
lmc_send_keys('f', 50)
elseif (button == 39) then
lmc_send_keys('v', 50)
elseif (button == 40) then
lmc_send_keys('%^h', 50)
elseif (button == 45) then
lmc_send_keys('^+z', 50)
elseif (button == 46) then
lmc_send_keys('s', 50)
elseif (button == 96) then
lmc_send_keys('^z', 50)
elseif (button == 97) then
lmc_send_keys('^{F10}', 50)
elseif (button == 98) then
lmc_send_keys('r', 50)
elseif (button == 99) then
lmc_send_keys('x', 50)
elseif (button == 100) then
lmc_send_keys('^{F11}', 50)
elseif (button == 101) then
lmc_send_keys('z', 50)
elseif (button == 102) then
lmc_send_keys('^t', 50)
elseif (button == 103) then
lmc_send_keys('^l', 50)
elseif (button == 104) then
lmc_send_keys('{TAB}', 50)
elseif (button == 105) then
lmc_send_keys('^d', 50)
elseif (button == 110) then
lmc_send_keys('p', 50)
elseif (button == 111) then
lmc_send_keys('m', 50)
-- A VECES CUANDO BOCK NUM ESTA ACTIVADO CADA TECLA NO SÓLO MANDA SU PROPIA ACCIÓN SI NO TAMBIEN UNA TAL TECLA 144
-- PARA EVITAR MALOS FUNCIONAMIENTOS LE ASIGNAREMOS A 144 F24
elseif (button == 144) then
lmc_send_keys('{F24}', 50)
end
end
)
|
a42ec7be5b9289f9c09f5ca3f0a117097d5d6ea6
|
[
"Markdown",
"Lua"
] | 2 |
Markdown
|
GarridoSantiago/LUAMACROS
|
91bf04df117f0b5cbe865c0e1ef50af092725824
|
1d1f5f521ee12606c0ffa208aef077f72aec666c
|
refs/heads/master
|
<file_sep># THIS MODULE CONTAINS ALL FUNCTIONS RESPONSIBLE FOR PROCESSING
# PARAMETERS AND FLAGS PASSED TO JETFREQ ON THE COMMAND LINE
import re
import json
import jfutil
import jfexceptions
# THIS FUNCTION CONDUCTS A 'RUN-THE-GAUNTLET' STYLE INTEGRITY CHECK
# OF THE PARAMETERS AND ABORTS JETFREQ IF ANY CONDITIONS FAIL
def check_params(params):
# IF JETFREQ IS RUN IN AN 'EVENT' MODE, CHECK THERE IS EXACTLY ONE EVENT TYPE FLAG (EXCLUDING CROSSPROCS)
if params['mode'] == 'BY_EVENT' or params['mode'] == 'COMPARE_EVENT':
flags = jfutil.get_event_type_flags(params)
if len(flags) > 1:
raise jfexceptions.IncorrectFlagUsageForModeError(params['mode'], flags)
if len(flags) == 0:
raise jfexceptions.ByEventModeFlagRequiredError(params['mode'])
if 'x' in flags:
raise jfexceptions.FlagsNotApplicableError(params['mode'], 'x')
# IF JETFREQ IS RUN IN A 'PROCESS' MODE, CHECK THERE IS ONE OR MORE EVENT TYPE FLAGS
if params['mode'] == 'BY_PROCESS' or params['mode'] == 'COMPARE_PROCESS':
if params['regmods'] == False and params['filemods'] == False and params['childprocs'] == False and params['netconns'] == False and params['crossprocs'] == False and params['modloads'] == False:
raise jfexceptions.ProcessModeMissingEventTypeError(params['mode'])
# IF JETFREQ IS RUN IN A 'COMPARE' MODE, CHECK THAT A SAMPLE FILE HAS BEEN IDENTIFIED
if params['import_sample'] == None and (params['mode'] == 'COMPARE_PROCESS' or params['mode'] == 'COMPARE_EVENT'):
raise jfexceptions.CompareModeMissingSampleFileError(params['mode'])
# IF JETFREQ IS NOT RUN IN A 'COMPARE' MODE, CHECK THAT A SAMPLE FILE HAS NOT BEEN IDENTIFIED
if re.match(r'COMPARE_', params['mode']) == None and not params['import_sample'] == None:
raise jfexceptions.FlagsNotApplicableError(params['mode'], 'i')
# CHECK THAT A USER NAME HAS BEEN INCLUDED OR EXCLUDED, BUT NOT BOTH
if not params['user_name'] == None and not params['exclude_user'] == None:
params['exclude_user'] == None
# CHECK THAT A HOST NAME HAS BEEN INCLUDED OR EXCLUDED, BUT NOT BOTH
if not params['host_name'] == None and not params['exclude_host'] == None:
params['exclude_host'] == None
# CHECK THAT THE GREATER-THAN AND LESS-THAN THRESHOLD VALUES ARE NOT EQUAL
if params['threshold_gt'] == params['threshold_lt']:
raise jfexceptions.NonsensicalThresholdValuesError(params['threshold_gt'], params['threshold_lt'])
# DO NOT TRUNCATE IF WRITING
if params['write_file'] and params['truncate']:
params['truncate'] = False
jfutil.debug(True, 'JetFreq does not truncate when writing to file. Ignoring -k flag.')
return params
# THIS FUNCTION IMPORTS THE SYS.ARGV[] ARRAY AND TRANSFORMS IT INTO A JSON OBJECT
# THAT CAN BE PASSED BETWEEN FUNCTIONS IN JETFREQ
def process_params(args):
# DEFINE THE FLAGS THAT ARE USED IN JETFREQ, INCLUDING THEIR NAME,
# WHETHER THEY REQUIRE A PARAMETER AND TRACK THEIR USE
flags = {
"u":{"name":"user_name","param":True,"assigned":False},
"U":{"name":"exclude_user","param":True,"assigned":False},
"h":{"name":"host_name","param":True,"assigned":False},
"H":{"name":"exclude_host","param":True,"assigned":False},
"s":{"name":"start_time","param":True,"assigned":False},
"n":{"name":"sample_size","param":True,"assigned":False},
"t":{"name":"threshold_lt","param":True,"assigned":False},
"T":{"name":"threshold_gt","param":True,"assigned":False},
"i":{"name":"import_sample","param":True,"assigned":False},
"w":{"name":"write_file","param":False,"assigned":False},
"v":{"name":"verbose","param":False,"assigned":False},
"r":{"name":"regmods","param":False,"assigned":False},
"f":{"name":"filemods","param":False,"assigned":False},
"c":{"name":"childprocs","param":False,"assigned":False},
"d":{"name":"netconns","param":False,"assigned":False},
"x":{"name":"crossprocs","param":False,"assigned":False},
"m":{"name":"modloads","param":False,"assigned":False},
"k":{"name":"truncate","param":False,"assigned":False},
"o":{"name":"homogenize","param":False,"assigned":False},
"by-process":{"name":"BY_PROCESS","param":False,"assigned":False},
"by-event":{"name":"BY_EVENT","param":False,"assigned":False},
"help":{"name":"SHOW_HELP","param":False,"assigned":False},
"compare-process":{"name":"COMPARE_PROCESS","param":False,"assigned":False},
"compare-event":{"name":"COMPARE_EVENT","param":False,"assigned":False}
}
# INITIALIZE THE 'PARAMS' JSON OBJECT TO HOLD THE PARAMETERS
params = {
"server":None,
"key":None,
"search_name":None,
"mode":'BY_PROCESS',
"user_name":None,
"exclude_user":None,
"host_name":None,
"exclude_host":None,
"import_sample":None,
"start_time":"-672h",
"write_file":False,
"sample_size":50,
"threshold_lt":100,
"threshold_gt":0,
"verbose":False,
"truncate":False,
"homogenize":False,
"regmods":False,
"filemods":False,
"childprocs":False,
"netconns":False,
"crossprocs":False,
"modloads":False
}
# REMOVE THE FIRST ARGUMENT FROM SYS.ARGV[] (ALWAYS './jetfreq.py')
args = args[1:len(args)]
# CHECK THAT THE ARGUMENT LIST IS NOT EMPTY
if len(args) == 0:
raise jfexceptions.NoArgsError("jetfreq.py requires arguments")
# IF THE FIRST ARGUMENT IS A MODE FLAG...
if args[0].startswith('--'):
a = args[0][2:len(args[0])]
# AND THE MODE EXISTS...
if a in flags:
# ASSIGN THE VALUE TO THE 'MODE' PARAMETER
params["mode"] = flags[a]['name']
# IF THE MODE IS --HELP, EXIT FUNCTION
if params["mode"] == "SHOW_HELP":
return params
else:
# TRIM THE ARGUMENT LIST
args = args[1:len(args)]
else:
raise jfexceptions.IncorrectUsageError(" ".join(args))
# OTHERWISE, ASSIGN THE DEFAULT MODE
else:
params["mode"] == flags["by-process"]['name']
# IF THE MODE IS A 'PROCESS' MODE, THE NEXT ARGUMENT MUST BE THE SEARCH NAME
if params['mode'] == 'BY_PROCESS' or params['mode'] == 'COMPARE_PROCESS':
if args[0].startswith('-'):
raise jfexceptions.IncorrectUsageError(" ".join(args))
else:
params['search_name'] = args[0]
args = args[1:len(args)]
# IF THE MODE IS AN 'EVENT' MODE, THE NEXT ARGUMENT MUST BE THE EVENT TYPE FLAG, FOLLOWED BY THE SEARCH NAME
else:
if not args[0].startswith('-'):
raise jfexceptions.IncorrectUsageError(" ".join(args))
else:
# IF THE FLAGS ARE NOT CLUSTERED (I.E. THERE IS ONLY ONE FLAG)...
if len(args[0][1:len(args[0])]) > 1:
raise jfexceptions.IncorrectUsageError(" ".join(args))
else:
# AND THERE ARE AT LEAST TWO ARGUMENTS (I.E. AN EVENT TYPE AND A SEARCH NAME)...
if len(args) == 1:
raise jfexceptions.IncorrectUsageError(" ".join(args))
else:
# AND THE CURRENT FLAG IS NOT FOLLOWED BY ANOTHER FLAG (I.E. IT MUST BE THE SEARCH NAME)...
if args[1].startswith('-'):
raise jfexceptions.IncorrectUsageError(" ".join(args[1:len(args)]))
else:
# ADD THE EVENT TYPE AND THE SEARCH NAME TO 'PARAMS' AND TRIM ARG LIST
params[flags[args[0][1:len(args[0])]]['name']] = True
params['search_name'] = args[1]
args = args[2:len(args)]
# FOR EACH REMAINING ELEMENT IN THE ARG LIST...
while len(args) > 0:
# ALL FLAGS MUST START WITH A '-' CHAR
if not args[0].startswith('-'):
raise jfexceptions.IncorrectUsageError(" ".join(args))
else:
# IF THE FLAGS ARE CLUSTERED (I.E. MORE THAN ONE FLAG)...
if len(args[0][1:len(args[0])]) > 1:
cluster = args[0][1:len(args[0])]
# FOR EACH FLAG IN THE CLUSTER...
for a in cluster:
if a in flags:
# IF THE FLAG DOES NOT REQUIRE A VALUE...
if flags[a]['param'] == True:
raise jfexceptions.IncorrectUsageError(" ".join(args))
# AND THE FLAG HAS NOT ALREADY BEEN USED...
elif flags[a]['assigned'] == True:
raise jfexceptions.DoubleArgumentError(a)
else:
# UPDATE THE VALUE IN 'PARAMS'
params[flags[a]['name']] = True
flags[a]['assigned'] = True
else:
raise jfexceptions.NoSuchArgumentError(a)
# TRIM THE ARGS LIST
args = args[1:len(args)]
else:
a = args[0][1:len(args[0])]
if a in flags:
# IF THE FLAG REQUIRES A VALUE...
if flags[a]['param'] == True:
# AND A POTENTIAL VALUE EXISTS...
if len(args) > 1:
# AND THE POTENTIAL VALUE IS NOT ANOTHER FLAG...
if args[1].startswith('-') and not flags[a]['name'] == 'start_time':
raise jfexceptions.MissingValueError(a, flags[a]['name'])
# AND THE FLAG HAS NOT YET BEEN USED...
elif flags[a]['assigned'] == True:
raise jfexceptions.DoubleArgumentError(a)
else:
# ASSIGN THE VALUE IN 'PARAMS'
params[flags[a]['name']] = args[1]
flags[a]['assigned'] = True
else:
raise jfexceptions.MissingValueError(a, flags[a]['name'])
# TRIM THE ARGS LIST
args = args[2:len(args)]
# IF THE FLAG DOES NOT REQUIRE A VALUE...
else:
# AND THE NEXT FLAG IS NOT A VALUE...
if len(args) > 1 and not args[1].startswith('-'):
raise jfexceptions.IncorrectUsageError(" ".join(args))
# AND THE FLAG HAS NOT YET BEEN USED...
elif flags[a]['assigned'] == True:
raise jfexceptions.DoubleArgumentError(a)
else:
# ASSIGN THE VALUE IN 'PARAMS'
params[flags[a]['name']] = True
flags[a]['assigned'] = True
# TRIM THE ARGS LIST
args = args[1:len(args)]
else:
raise jfexceptions.NoSuchArgumentError(a)
# IF THE USER HAS EXPLICITLY CALLED ONE OF THE THRESHOLD FLAGS, REMOVE THE DEFAULT VALUE FOR THE OTHER
if flags['t']['assigned'] == True and flags['T']['assigned'] == False:
params['threshold_gt'] = None
elif flags['T']['assigned'] == True and flags['t']['assigned'] == False:
params['threshold_lt'] = None
# IMPORT THE SERVER NAME AND API KEY VALUE FROM THE JETFREQ CONFIG FILE
params = jfutil.import_conf(params)
if params['server'] == None or len(params['server']) == 0 or params['key'] == None or len(params['key']) == 0:
raise jfexceptions.MissingConfigurationError()
return check_params(params)
<file_sep>________ _____________
______(_)______ /___ __/_________________ _
_____ /_ _ \ __/_ /_ __ ___/ _ \ __ `/
____ / / __/ /_ _ __/ _ / / __/ /_/ /
___ / \___/\__/ /_/ /_/ \___/\__, /
/___/ /_/
Author:
sjb-ch1mp
Description:
jetfreq.py uses the Carbon Black Response API to search for all instances of a given process and conduct frequency analysis on its associated
events. It can also be run in 'Event Mode' to search for a given event type (e.g. modload, regmod) and conduct frequency analysis on the processes that
access it. Running jetfreq.py in 'Compare Mode' allows users to compare a target sample with a representative sample that has been saved in the
./samples directory.
Usage:
By Process Mode : './jetfreq.py [--by-process] <search_name> -m|r|f|c|d|x [{-u|-U} <username> {-h|-H} <hostname> -s <start_time> -n <sample_size> {-t|-T} <threshold> -wvko]'
By Event Mode : './jetfreq.py --by-event -m|r|f|c|d <search_name> [{-u|-U} <username> {-h|-H} <hostname> -s <start_time> -n <sample_size> {-t|-T} <threshold> -vwko]'
Compare Processes : './jetfreq.py --compare-process <search_name> -i <sample_file> -m|r|f|c|d|x [{-u|-U} <username> {-h|-H} <hostname> -s <start_time> -n <sample_size> {-t|-T} <threshold> -wvko]'
Compare Events : './jetfreq.py --compare-event -m|r|f|c|d <search_name> -i <sample_file> [{-u|-U} <username> {-h|-H} <hostname> -s <start_time> -n <sample_size> {-t|-T} <threshold> -vwko]'
Show Help : './jetfreq.py --help'
Parameters:
:: Mandatory
search_name : The name of the process or modload
:: Modes
--by-process : Search for given process (default mode).
--by-event : Search for a given event, e.g. modload, regmod, netconn
--compare-process : Compare a representative by-process sample with a target by-process sample
--compare-event : Compare a representative by-event sample with a target by-event sample
--help : Show help (this)
:: With Value
-u : Filter results by <username>
-U : Exclude all results from <username>
-h : Filter results by <hostname>
-H : Exclude all results from <hostname>
-s : Get all results with a start time >= <s> (default = '-672h')
-n : Get first <n> results only (default = '50')
-t : Include events that occur in <= <threshold>% processes (default = '100')
-T : Include events that occur in >= <threshold>% processes (default = '0')
-i : Import <sample_file> to compare to target sample
:: Boolean
-w : Write results to CSV file (./samples)
-v : Verbose
-r : Include regmods in results (--by-process) | Search for regmod (--by-event)
-f : Include filemods in results (--by-process) | Search for filemod (--by-event)
-c : Include childprocs in results (--by-process) | Search for childproc (--by-event)
-d : Include netconns in results (--by-process) | Search for netconn (--by-event)
-x : Include crossprocs in results (--by-process only)
-m : Include modloads in results (--by-process) | Search for modload (--by-event)
-k : Truncates any directory path with greater than 4 levels to 4, or registry key paths with greater than 6 levels to 6.
-o : Homogenize directory and regkey paths, e.g. 'C:\user\mr_fluffy\...' -> 'C:\user\<USER>\...'
File name syntax:
--by-process : ./samples/process/<datetime>_s-<search-name>_e-<event-types>_n-<sample-size>_t-<upper_threshold>_T-<lower_threshold>[_u-<username>_h-<hostname>].csv
--by-event : ./samples/event/<datetime>_s-<search-name>_e-<event-type>_n-<sample-size>_t-<upper_threshold>_T-<lower_threshold>[_u-<username>_h-<hostname>].csv
--compare-process : ./samples/process/diff/<datetime>_s-<search-name>_e-<event-types>_n-<sample-size>_t-<upper_threshold>_T-<lower_threshold>[_u-<username>_h-<hostname>]_i-<sample-file-datetime>.csv
--compare-event : ./samples/event/diff/<datetime>_s-<search-name>_e-<event-type>_n-<sample-size>_t-<upper_threshold>_T-<lower_threshold>[_u-<username>_h-<hostname>]_i-<sample-file-datetime>.csv
<file_sep>#!/path/to/python
import json
import sys
import jfexceptions
import jfutil
import jfnet
import jfanalyze
import jfparser
# MAIN METHOD FOR JETFREQ.PY
try:
# IMPORT THE ARGUMENTS FROM COMMAND LINE AND LOAD
# AND LOAD THEM INTO A JSON OF PARAMETERS
# THAT CAN BE EASILY PASSED BETWEEN FUNCTIONS
if __name__ == "__main__":
params = jfparser.process_params(sys.argv)
# CHECK IF JETFREQ IS RUNNING IN HELP MODE
# IF SO, SHOW HELP AND EXIT
if params['mode'] == 'SHOW_HELP':
jfutil.show_help()
exit()
# DEBUG INFO
jfutil.debug(params['verbose'], "Running in {} mode".format(params['mode']))
jfutil.debug(params['verbose'], 'Parameters parsed as {}'.format(params))
# SHOW THE JETFREQ BANNER
banner = [" _ __ ___ "," (_)__ / /_/ _/______ ___ _",
" / / -_) __/ _/ __/ -_) _ `/"," __/ /\__/\__/_//_/ \__/\_, /",
"|___/ /_/"]
jfutil.debug(True, banner)
# CHECK FOR ATTEMPTS TO GENERATE LARGE SAMPLES AND WARN USER
jfutil.throttle(params)
# GET DATA FOR EVENT OR PROCESS FROM CBR SERVER AND ANALYZE IT
representative_sample = None
target_sample = None
data = None
event_freqs = None
if params['mode'] == 'BY_PROCESS':
jfutil.debug(True if params['verbose'] == False else False, 'Fetching data from {}'.format(params['server']))
data = jfnet.get_data_for_process(params)
jfutil.debug(True if params['verbose'] == False else False, 'Analyzing the search results')
event_freqs = jfanalyze.analyze_by_process(params, data)
elif params['mode'] == 'BY_EVENT':
jfutil.debug(True if params['verbose'] == False else False, 'Fetching data from {}'.format(params['server']))
data = jfnet.get_data_for_event(params)
jfutil.debug(True if params['verbose'] == False else False, 'Analyzing the search results')
event_freqs = jfanalyze.analyze_by_event(params, data)
elif params['mode'] == 'COMPARE_PROCESS':
jfutil.debug(True if params['verbose'] == False else False, 'Importing the representative sample')
representative_sample = jfutil.import_sample(params)
jfutil.debug(True if params['verbose'] == False else False, 'Fetching the target sample from {}'.format(params['server']))
target_sample = jfnet.get_data_for_process(params)
jfutil.debug(True if params['verbose'] == False else False, 'Analyzing the target sample')
target_sample = jfanalyze.analyze_by_process(params, target_sample)
jfutil.debug(True if params['verbose'] == False else False, 'Comparing target sample to representative sample')
event_freqs = jfanalyze.compare_process(params, representative_sample, target_sample)
elif params['mode'] == 'COMPARE_EVENT':
jfutil.debug(True if params['verbose'] == False else False, 'Importing the representative sample')
representative_sample = jfutil.import_sample(params)
jfutil.debug(True if params['verbose'] == False else False, 'Fetching the target sample from {}'.format(params['server']))
target_sample = jfnet.get_data_for_event(params)
jfutil.debug(True if params['verbose'] == False else False, 'Analyzing the target sample')
target_sample = jfanalyze.analyze_by_event(params, target_sample)
jfutil.debug(True if params['verbose'] == False else False, 'Comparing target sample to representative sample')
event_freqs = jfanalyze.compare_event(params, representative_sample, target_sample)
# WRITE RESULTS TO FILE OR DUMP REPORT TO STDOUT
if params['write_file'] == True:
file_path = None
if params['mode'] == 'BY_PROCESS':
file_path = jfutil.out_file_by_process(params, event_freqs)
elif params['mode'] == 'BY_EVENT':
file_path = jfutil.out_file_by_event(params, event_freqs)
elif params['mode'] == 'COMPARE_PROCESS':
file_path = jfutil.out_file_compare_process(params, event_freqs)
elif params['mode'] == 'COMPARE_EVENT':
file_path = jfutil.out_file_compare_event(params, event_freqs)
jfutil.debug(True, 'File successfully written to {}'.format(file_path))
else:
if params['mode'] == 'BY_PROCESS':
report = jfutil.format_report_by_process(params, event_freqs)
elif params['mode'] == 'BY_EVENT':
report = jfutil.format_report_by_event(params, event_freqs)
elif params['mode'] == 'COMPARE_PROCESS':
report = jfutil.format_report_compare_process(params, event_freqs)
elif params['mode'] == 'COMPARE_EVENT':
report = jfutil.format_report_compare_event(params, event_freqs)
jfutil.debug(True, report)
# CATCH DEFINED ERRORS TO PROVIDE DEBUG INFORMATION
except jfexceptions.IncorrectUsageError as err:
jfutil.debug(True, "Incorrect usage at argument: {}".format(err.context))
jfutil.show_usage()
except jfexceptions.NoArgsError as err:
jfutil.debug(True, err.message)
jfutil.show_usage()
except jfexceptions.NoSuchArgumentError as err:
jfutil.debug(True, "No such argument: {}".format(err.flag))
jfutil.show_usage()
except jfexceptions.MissingValueError as err:
jfutil.debug(True, "Flag \'{}\' ({}) requires a value".format(err.flag, err.name))
jfutil.show_usage()
except jfexceptions.FlagsNotApplicableError as err:
jfutil.debug(True, "Flags -{} not applicable in {} mode".format(err.flags, err.mode))
jfutil.show_usage()
except jfexceptions.DoubleArgumentError as err:
jfutil.debug(True, "Flag -{} not allowed twice".format(err.flag))
jfutil.show_usage()
except jfexceptions.MissingConfigurationError as err:
jfutil.debug(True, err.message)
except jfexceptions.UnexpectedResponseError as err:
jfutil.debug(True, "The JSON returned had an unexpected format:\n{}".format(err.data))
except jfexceptions.NoResultsError as err:
jfutil.debug(True, "There were no results for query \'{}\'".format(err.query))
except jfexceptions.NoEventsFoundError as err:
jfutil.debug(True, "There were no events found for process returned by query \'{}\'".format(err.query))
except jfexceptions.ProcessModeMissingEventTypeError as err:
jfutil.debug(True, "{} mode requires an event type to be specified".format(err.mode))
jfutil.show_usage()
except jfexceptions.IncorrectUseOfThresholdError as err:
jfutil.debug(True, "Threshold parameter requires a comparator to be specified: {}".format(err.threshold))
jfutil.show_usage()
except jfexceptions.IncorrectFlagUsageForModeError as err:
jfutil.debug(True, "Mode {} can only take a single event type flag: {}".format(err.mode, err.flags))
jfutil.show_usage()
except jfexceptions.ByEventModeFlagRequiredError as err:
jfutil.debug(True, "Mode {} requires an event_type to be specified with an event_type flag, e.g. -m|f|c|d|r".format(err.mode))
jfutil.show_usage()
except jfexceptions.IncorrectSampleForModeError as err:
sample_mode = 'BY_EVENT' if err.mode == 'COMPARE_PROCESS' else 'BY_PROCESS'
jfutil.debug(True, "The file {} contains data for a {} search, but jetfreq is being run in {} mode.".format(err.file_path, sample_mode, err.mode))
except jfexceptions.CompareModeMissingSampleFileError as err:
jfutil.debug(True, 'Import file must be specified (-i) when running jetfreq in {} mode'.format(err.mode))
jfutil.show_usage()
except jfexceptions.NoDiffsFoundError as err:
jfutil.debug(True, 'Target sample ({}) and representative sample ({}) are the same'.format(err.target_event, err.sample))
except jfexceptions.NonsensicalThresholdValuesError as err:
jfutil.debug(True, 'Greater Than Threshold value ({}) is equal to Less Than Threshold value ({}). This will return zero results.'.format(err.greater_than, err.less_than))
<file_sep># THIS MODULE CONTAINS VARIOUS UTILITY FUNCTIONS USED
# BY ALL OTHER MODULES IN JETFREQ
import re
import jfexceptions
import os
from jfanalyze import sort_events
from jfanalyze import EventFreq
from jfanalyze import EventDiff
from jfanalyze import DiffType
from datetime import datetime
# THIS FUNCTION FORMATS AND WRITES DEBUG INFORMATION TO STDOUT
def debug(verbose, message):
if verbose:
if type(message) == list:
for line in message:
print("jetfreq.py: {}".format(line))
else:
print("jetfreq.py: {}".format(message))
# THIS FUNCTION TRUNCATES ANY PATH WITH A HIERARCHY GREATER THAN
# 4 DOWN TO THE FIRST 3 AND THE LAST 1 FOR BREVITY
def truncate_path(path, path_type):
depth = 4 if path_type == 'dir' else 6;
if '\\' in path:
path_ary = path.split('\\')
if len(path_ary) > depth:
path = '\\'.join(path_ary[0:depth - 1]) + '\\ ... \\' + path_ary[len(path_ary) - 1]
elif '/' in path:
path_ary = path.split('/')
if len(path_ary) > depth:
path = '/'.join(path_ary[0:depth - 1]) + '/ ... /' + path_ary[len(path_ary) - 1]
return path
# THIS FUNCTION SORT A LIST OF EVENT_DIFF OBJECTS
# ALPHABETICALLY BY THEIR DIFFTYPE VALUE
def sort_event_diffs_by_type(event_diffs):
for i in range(len(event_diffs)):
j = i + 1
while j < len(event_diffs):
if event_diffs[i].difftype > event_diffs[j].difftype:
hold = event_diffs[i]
event_diffs[i] = event_diffs[j]
event_diffs[j] = hold
j = j + 1
return event_diffs
# THIS FUNCTION FORMATS THE CONTENTS OF EVENT_DIFF OBJECTS
# AND APPENDS IT TO THE REPORT LIST
def append_diff_to_report(report, event_diffs, event_type, truncate):
dt = DiffType()
report.append('::::::')
report.append(':::::: {}'.format(event_type))
report.append(':::::: {:<61} | {:<15} | PATH'.format('DIFFERENCE TYPE', 'FREQ'))
report.append(':::::: --------------------------------------------------------------|-----------------|------>')
path_type = 'reg' if event_type.upper().startswith('REGMOD') else 'dir'
event_diffs = sort_event_diffs_by_type(event_diffs)
for diff in event_diffs:
if diff.difftype == dt.MISS_FM_REP:
report.append(':::::: {:<61} | {:<15} | {}'.format(
diff.difftype,
'n/a',
truncate_path(diff.target_event.path, path_type) if truncate else diff.target_event.path))
elif diff.difftype == dt.MISS_FM_TAR:
report.append(':::::: {:<61} | {:<15} | {}'.format(
diff.difftype,
'n/a',
truncate_path(diff.representative_event.path, path_type) if truncate else diff.representative_event.path))
elif diff.difftype == dt.HIGH_FQ_REP:
report.append(':::::: {:<61} | {:<15} | {}'.format(
diff.difftype,
'{:<6.4f} > {:<6.4f}'.format(float(diff.representative_event.perc), float(diff.target_event.perc)),
truncate_path(diff.target_event.path, path_type) if truncate else diff.target_event.path))
elif diff.difftype == dt.HIGH_FQ_TAR:
report.append(':::::: {:<61} | {:<15} | {}'.format(
diff.difftype,
'{:<6.4f} > {:<6.4f}'.format(float(diff.target_event.perc), float(diff.representative_event.perc)),
truncate_path(diff.target_event.path, path_type) if truncate else diff.target_event.path))
elif diff.difftype.startswith('TARGET SAMPLE HAS NO'):
report.append(':::::: {:<61} | {:<15} | {}'.format(
diff.difftype,
'n/a',
truncate_path(diff.representative_event.path, path_type) if truncate else diff.representative_event.path))
elif diff.difftype.startswith('REPRESENTATIVE SAMPLE HAS NO'):
report.append(':::::: {:<61} | {:<15} | {}'.format(
diff.difftype,
'n/a',
truncate_path(diff.target_event.path, path_type) if truncate else diff.target_event.path))
return report
# THIS FUNCTION FORMATS THE CONTENTS OF EVENT_FREQ OBJECTS
# AND APPENDS IT TO THE REPORT LIST
def append_to_report(report, event_freqs, event_type, truncate):
report.append('::::::')
report.append(':::::: {}'.format(event_type))
report.append(':::::: RATIO | FREQ | PATH')
report.append(':::::: --------|--------|------->')
path_type = 'reg' if event_type.upper().startswith('REGMOD') else 'dir'
for event in event_freqs:
report.append(':::::: {:<7} | {:<6.4f} | {}'.format(
'{}/{}'.format(event.count, event.total),
event.perc,
truncate_path(event.path, path_type) if truncate else event.path))
return report
# THIS IS THE MAIN FUNCTION FOR FORMATTING THE RESULTS
# OF A --BY-PROCESS MODE QUERY INTO A REPORT
def format_report_by_process(params, event_freqs):
debug(params['verbose'], 'Generating report')
report = []
# CHECK THAT THERE ARE, IN FACT, RESULTS TO REPORT
no_results = True
for key in event_freqs:
if not event_freqs[key] == None and len(event_freqs[key]) > 0:
no_results = False
break
# OTHERWISE, YOU SHALL NOT PASS
if no_results == True:
report.append('::::::')
report.append(':::::: NO RESULTS FOR PROCESS {}'.format(params['search_name'].upper()))
return report
# APPEND THE REPORT HEADERS TO THE REPORT
report.append('::::::')
report.append(':::::: RESULTS FOR PROCESS {}'.format(params['search_name'].upper()))
report.append('::::::')
report.append(':::::: FILTERS')
report.append(':::::: start_time = {}'.format(params['start_time']))
if params['threshold_lt'] != None:
report.append(':::::: threshold (less than) = {}%'.format(params['threshold_lt']))
if params['threshold_gt'] != None:
report.append(':::::: threshold (greater than) = {}%'.format(params['threshold_gt']))
report.append(':::::: sample_size = {}'.format(params['sample_size']))
if not params['user_name'] == None:
report.append(':::::: user_name = {}'.format(params['user_name']))
elif not params['exclude_user'] == None:
report.append(':::::: exclude_user = {}'.format(params['exclude_user']))
if not params['host_name'] == None:
report.append(':::::: host_name = {}'.format(params['host_name']))
elif not params['exclude_host'] == None:
report.append(':::::: exclude_host = {}'.format(params['exclude_host']))
# APPEND THE EVENTS TO THE REPORT
if not event_freqs['modloads'] == None and len(event_freqs['modloads']) > 0:
report = append_to_report(report, event_freqs['modloads'], 'MODLOADS', params['truncate'])
if not event_freqs['regmods'] == None and len(event_freqs['regmods']) > 0:
report = append_to_report(report, event_freqs['regmods'], 'REGMODS', params['truncate'])
if not event_freqs['childprocs'] == None and len(event_freqs['childprocs']) > 0:
report = append_to_report(report, event_freqs['childprocs'], 'CHILDPROCS', params['truncate'])
if not event_freqs['filemods'] == None and len(event_freqs['filemods']) > 0:
report = append_to_report(report, event_freqs['filemods'], 'FILEMODS', params['truncate'])
if not event_freqs['netconns'] == None and len(event_freqs['netconns']) > 0:
report = append_to_report(report, event_freqs['netconns'], 'NETCONNS', params['truncate'])
if not event_freqs['crossprocs'] == None and len(event_freqs['crossprocs']) > 0:
report = append_to_report(report, event_freqs['crossprocs'], 'CROSSPROCS', params['truncate'])
# CLOSE AND RETURN THE REPORT
report.append('::::::')
report.append(':::::: END')
return report
# THIS IS THE MAIN FUNCTION FOR FORMATTING THE RESULTS OF A
# --BY-EVENT QUERY INTO A REPORT
def format_report_by_event(params, event_freqs):
debug(params['verbose'], 'Generating report')
report = []
# GET THE EVENT TYPE THAT WAS IN THE QUERY
event_type = get_event_type_flags(params)
if event_type == 'm':
event_type = 'MODLOAD'
elif event_type == 'r':
event_type = 'REGMOD'
elif event_type == 'f':
event_type = 'FILEMOD'
elif event_type == 'c':
event_type = 'CHILDMOD'
elif event_type == 'd':
event_type = 'NETCONN'
# IF THERE ARE NO RESULTS, GO NO FURTHER
if len(event_freqs) == 0:
report.append('::::::')
report.append(':::::: NO RESULTS FOR {} {}'.format(event_type, params['search_name'].upper()))
return report
# APPEND THE REPORT HEADERS TO THE REPORT
report.append('::::::')
report.append(':::::: RESULTS FOR {} {}'.format(event_type, params['search_name'].upper()))
report.append('::::::')
report.append(':::::: FILTERS')
report.append(':::::: start_time = {}'.format(params['start_time']))
if params['threshold_lt'] != None:
report.append(':::::: threshold (less than) = {}%'.format(params['threshold_lt']))
if params['threshold_gt'] != None:
report.append(':::::: threshold (greater than) = {}%'.format(params['threshold_gt']))
report.append(':::::: sample_size = {}'.format(params['sample_size']))
if not params['user_name'] == None:
report.append(':::::: user_name = {}'.format(params['user_name']))
elif not params['exclude_user'] == None:
report.append(':::::: exclude_user = {}'.format(params['exclude_user']))
if not params['host_name'] == None:
report.append(':::::: host_name = {}'.format(params['host_name']))
elif not params['exclude_host'] == None:
report.append(':::::: exclude_host = {}'.format(params['exclude_host']))
# APPEND THE PROCESSES TO THE REPORT
report = append_to_report(report, event_freqs, 'PROCESSES', params['truncate'])
# CLOSE AND RETURN THE REPORT
report.append('::::::')
report.append(':::::: END')
return report
# THIS FUNCTION TAKES A FILE NAME AND USES IT TO
# CREATE A PARAMS JSON CONTAINER TO HOLD THE PARAMETERS
# USED IN THE SEARCH THAT GENERATED THE FILE
def get_params_from_file_name(file_name):
# INITIALIZE JSON CONTAINER FOR PARAMETERS
params = {
'search_name':None,
'regmods':False,
'filemods':False,
'modloads':False,
'crossprocs':False,
'childprocs':False,
'netconns':False,
'sample_size':10,
'user_name':None,
'exclude_user':None,
'host_name':None,
'exclude_host':None,
'threshold_lt':100,
'threshold_gt':0,
'event_type':None
}
# SPLIT THE NAME AT THE DEFINED FLAGS, INTO AN ARRAY
name_ary = re.split(r'_[hHuUtTnse]{1}-', file_name[0:len(file_name) - 4]) # trim .csv
params['search_name'] = name_ary[1].replace('__BS__', '\\')
params['sample_size'] = int(name_ary[3])
params['threshold_lt'] = int(name_ary[4]) if not name_ary[4] == "None" else "None"
params['threshold_gt'] = int(name_ary[5]) if not name_ary[5] == "None" else "None"
flags = name_ary[2]
if 'r' in flags:
params['regmods'] = True
params['event_type'] = 'REGMOD'
if 'f' in flags:
params['filemods'] = True
params['event_type'] = 'FILEMOD'
if 'm' in flags:
params['modloads'] = True
params['event_type'] = 'MODLOAD'
if 'x' in flags:
params['crossprocs'] = True
params['event_type'] = 'CROSSPROC'
if 'c' in flags:
params['childprocs'] = True
params['event_type'] = 'CHILDPROC'
if 'd' in flags:
params['netconns'] = True
params['event_type'] = 'NETCONN'
# IF THERE ARE 8 ELEMENTS IN THE NAME_ARY, THEN A USER FLAG AND A HOST FLAG WAS USED
if len(name_ary) == 8:
if '_u-' in file_name:
params['user_name'] = name_ary[6]
elif '_U-' in file_name:
params['exclude_user'] = name_ary[6]
if '_h-' in file_name:
params['host_name'] = name_ary[7]
elif '_H-' in file_name:
params['exclude_host'] = name_ary[7]
# IF THERE ARE 7 ELEMENTS IN THE NAME_ARY, THEN EITHER A USER FLAG OR A HOST FLAG WAS USED
elif len(name_ary) == 7:
if '_h-' in file_name:
params['host_name'] = name_ary[6]
elif '_H-' in file_name:
params['exclude_host'] = name_ary[6]
elif '_u-' in file_name:
params['user_name'] = name_ary[6]
elif '_U-' in file_name:
params['exclude_user'] = name_ary[6]
return params
# THIS IS THE MAIN FUNCTION FOR FORMATTING THE RESULTS OF A
# --COMPARE-PROCESS MODE QUERY INTO A REPORT
def format_report_compare_process(params, event_freqs):
report = []
# CHECK THAT THERE ARE INDEED RESULTS
no_results = True
for key in event_freqs:
if not event_freqs[key] == None and len(event_freqs[key]) > 0:
no_results = False
break
# IF NOT, GO NO FURTHER
if no_results:
report.append('::::::')
report.append(':::::: TARGET AND REPRESENTATIVE SAMPLES ARE THE SAME')
return report
# EXTRACT THE PARAMETERS USED TO GENERATE THE REPRESENTATIVE SAMPLE FROM ITS FILE NAME
representative_sample_params = get_params_from_file_name(params['import_sample'])
# APPEND THE REPORT HEADERS TO THE REPORT
report.append('::::::')
report.append(':::::: PROCESS COMPARISON RESULTS')
report.append('::::::')
report.append(':::::: REPRESENTATIVE SAMPLE PROCESS {}'.format(representative_sample_params['search_name'].upper()))
report.append(':::::: file = {}'.format(params['import_sample'].replace('__BS__', '\\')))
if representative_sample_params['threshold_lt'] != None:
report.append(':::::: threshold (less than) = {}%'.format(representative_sample_params['threshold_lt']))
if representative_sample_params['threshold_gt'] != None:
report.append(':::::: threshold (greather than) = {}%'.format(representative_sample_params['threshold_gt']))
report.append(':::::: sample_size = {}'.format(representative_sample_params['sample_size']))
if not representative_sample_params['user_name'] == None:
report.append(':::::: user_name = {}'.format(representative_sample_params['user_name']))
elif not representative_sample_params['exclude_user'] == None:
report.append(':::::: exclude_user = {}'.format(representative_sample_params['exclude_user']))
if not representative_sample_params['host_name'] == None:
report.append(':::::: host_name = {}'.format(representative_sample_params['host_name']))
elif not representative_sample_params['exclude_host'] == None:
report.append(':::::: exclude_host = {}'.format(representative_sample_params['exclude_host']))
report.append('::::::')
report.append(':::::: TARGET SAMPLE PROCESS {}'.format(params['search_name'].upper()))
report.append(':::::: start_time = {}'.format(params['start_time']))
if params['threshold_lt'] != None:
report.append(':::::: threshold (less than) = {}%'.format(params['threshold_lt']))
if params['threshold_gt'] != None:
report.append(':::::: threshold (greater than) = {}%'.format(params['threshold_gt']))
report.append(':::::: sample_size = {}'.format(params['sample_size']))
if not params['user_name'] == None:
report.append(':::::: user_name = {}'.format(params['user_name']))
elif not params['exclude_user'] == None:
report.append(':::::: exclude_user = {}'.format(params['exclude_user']))
if not params['host_name'] == None:
report.append(':::::: host_name = {}'.format(params['host_name']))
elif not params['exclude_host'] == None:
report.append(':::::: exclude_host = {}'.format(params['exclude_host']))
# APPEND THE EVENT DIFFERENCES TO THE REPORT
for key in event_freqs:
if not event_freqs[key] == None and len(event_freqs[key]) > 0:
report = append_diff_to_report(report, event_freqs[key], key.upper(), params['truncate'])
# CLOSE AND RETURN REPORT
report.append('::::::')
report.append(':::::: END')
return report
# THIS IS THE MAIN FUNCTION FOR FORMATTING THE RESULTS
# OF A --COMPARE-EVENT QUERY INTO A REPORT
def format_report_compare_event(params, event_freqs):
report = []
# IF THERE ARE NO RESULTS, GO NO FURTHER
if len(event_freqs) == 0:
report.append('::::::')
report.append(':::::: TARGET AND REPRESENTATIVE SAMPLES ARE THE SAME')
return report
# GET THE EVENT TYPE USED IN THE TARGET SAMPLE
event_type = 'NETCONN'
if params['modloads'] == True:
event_type = 'MODLOAD'
elif params['regmods'] == True:
event_type = 'REGMOD'
elif params['filemods'] == True:
event_type = 'FILEMOD'
elif params['childprocs'] == True:
event_type = 'CHILDPROC'
# EXTRACT THE PARAMETERS USED TO GENERATE THE REPRESENTATIVE SAMPLE FROM THE FILE NAME
representative_sample_params = get_params_from_file_name(params['import_sample'])
# APPEND THE REPORT HEADERS TO THE REPORT
report.append('::::::')
report.append(':::::: EVENT COMPARISON RESULTS')
report.append('::::::')
report.append(':::::: REPRESENTATIVE SAMPLE {} {}'.format(representative_sample_params['event_type'], representative_sample_params['search_name'].upper()))
report.append(':::::: file = {}'.format(params['import_sample'].replace('__BS__', '\\')))
report.append(':::::: threshold (less than) = {}'.format(representative_sample_params['threshold_lt']))
report.append(':::::: threshold (greater than) = {}'.format(representative_sample_params['threshold_gt']))
report.append(':::::: sample_size = {}'.format(representative_sample_params['sample_size']))
if not representative_sample_params['user_name'] == None:
report.append(':::::: user_name = {}'.format(representative_sample_params['user_name']))
elif not representative_sample_params['exclude_user'] == None:
report.append(':::::: exclude_user = {}'.format(representative_sample_params['exclude_user']))
if not representative_sample_params['host_name'] == None:
report.append(':::::: host_name = {}'.format(representative_sample_params['host_name']))
elif not representative_sample_params['exclude_host'] == None:
report.append(':::::: exclude_host = {}'.format(representative_sample_params['exclude_host']))
report.append('::::::')
report.append(':::::: TARGET SAMPLE {} {}'.format(event_type, params['search_name'].upper()))
report.append(':::::: start_time = {}'.format(params['start_time']))
report.append(':::::: threshold (less than) = {}'.format(params['threshold_lt']))
report.append(':::::: threshold (greater than) = {}'.format(params['threshold_gt']))
report.append(':::::: sample_size = {}'.format(params['sample_size']))
if not params['user_name'] == None:
report.append(':::::: user_name = {}'.format(params['user_name']))
elif not params['exclude_user'] == None:
report.append(':::::: exclude_user = {}'.format(params['exclude_user']))
if not params['host_name'] == None:
report.append(':::::: host_name = {}'.format(params['host_name']))
elif not params['exclude_host'] == None:
report.append(':::::: exclude_host = {}'.format(params['exclude_host']))
# APPEND THE PROCESS DIFFERENCES TO THE REPORT
report = append_diff_to_report(report, event_freqs, 'PROCESSES', params['truncate'])
# CLOSE AND RETURN THE REPORT
report.append('::::::')
report.append(':::::: END')
return report
# THIS FUNCTION EXTRACTS THE EVENT TYPE FLAGS
# FROM PARAMS AND RETURN THEM IN A STRING
def get_event_type_flags(params):
flags = ""
if params['modloads'] == True:
flags += 'm'
if params['regmods'] == True:
flags += 'r'
if params['filemods'] == True:
flags += 'f'
if params['crossprocs'] == True:
flags += 'x'
if params['childprocs'] == True:
flags += 'c'
if params['netconns'] == True:
flags += 'd'
return flags
# THIS FUNCTION IMPORTS THE CONTENTS OF A SAMPLE FILE
# AND RETURNS THEM AS A LIST OR DICTIONARY OF EVENT_FREQ OBJECTS
def import_sample(params):
# INITIALIZE THE COLUMN INDEX VARIABLES
search_name = None
event_type = None
path = None
count = None
total = None
freq = None
# CHECK THAT THE USER HASN'T ACCIDENTALLY COPIED DIRECTORY SECTIONS INTO THE FILEPATH
file_path = ''
if '/' in params['import_sample']:
hold = params['import_sample'].split('/')
params['import_sample'] = hold[len(hold) - 1]
# FORMAT THE IMPORT_SAMPLE VALUE AS A FILE PATH
file_path = './samples/{}/{}'.format('process' if params['mode'] == 'COMPARE_PROCESS' else 'event', params['import_sample'])
# THE COLUMN IN THE .CSV FILE DIFFERS DEPENDING UPON WHETHER THE
# FILE IS THE RESULT OF A PROCESS OR EVENT SEARCH
if params['mode'] == 'COMPARE_PROCESS':
search_name = 0
event_type = 1
path = 2
count = 3
total = 4
freq = 5
elif params['mode'] == 'COMPARE_EVENT':
search_name = 0
path = 1
count = 2
total = 3
freq = 4
# INITIALIZE THE EVENT_FREQS CONTAINER AS A LIST (FOR --COMPARE-EVENT) OR DICTIONARY (FOR --COMPARE-PROCESS)
event_freqs = [] if event_type == None else {'modloads':None, 'regmods':None, 'childprocs':None, 'filemods':None, 'netconns':None, 'crossprocs':None}
file = open(file_path, 'r')
skip = True
for line in file:
# SKIP THE FIRST LINE IN THE FILE (I.E. THE HEADERS)
if skip:
skip = False
else:
# EXTRACT THE VALUES FROM THE LINE IN THE FILE AND REMOVE QUOTATION MARKS
path_value = line.split(',')[path].replace('\'','')
freq_value = line.split(',')[freq].replace('\'','')
freq_value = freq_value.replace('\n','')
count_value = line.split(',')[count].replace('\'','')
total_value = line.split(',')[total].replace('\'','')
if not event_type == None:
# IF RUNNING IN --COMPARE-PROCESS MODE, RETRIEVE THE EVENT_TYPE VALUE
event_type_value = '{}s'.format(line.split(',')[event_type].replace('\'',''))
if not event_freqs[event_type_value] == None:
event_freqs[event_type_value].append(EventFreq(path_value, freq_value, count_value, total_value))
else:
event_freqs[event_type_value] = []
event_freqs[event_type_value].append(EventFreq(path_value, freq_value, count_value, total_value))
else:
event_freqs.append(EventFreq(path_value, freq_value, count_value, total_value))
file.close()
return event_freqs
# THIS FUNCTION CHECKS WHETHER THE NECESSARY FILE DIRECTORIES
# EXISTS IN THE JETFREQ WORKING DIRECTORY AND CREATES THEM
# IF NECESSARY
def check_for_sample_dir():
dirs = [
"./samples",
"./samples/process",
"./samples/event",
"./samples/process/diff",
"./samples/event/diff"
]
for d in dirs:
try:
os.mkdir(d)
except OSError:
pass
# THIS FUNCTION FORMATS THE CURRENT DATE TIME INTO
# A STRING APPROPRIATE FOR A FILE NAME
def format_datetime():
dt = str(datetime.now())
# REMOVE COLONS AND PERIODS
dt = re.sub(r'(:|\.)', '-', dt)
# REMOVE WHITESPACE
dt = re.sub(r'\s', '_', dt)
return dt
# THIS FUNCTION CHECKS THE JETFREQ MODE AND CREATES
# AN APPROPRIATE SUB DIRECTORY PREFIX FOR THE FILENAME
def build_sub_dir(params):
if params['mode'] == 'BY_EVENT':
return 'event'
elif params['mode'] == 'COMPARE_PROCESS':
return 'process/diff'
elif params['mode'] == 'COMPARE_EVENT':
return 'event/diff'
return 'process'
# THIS FUNCTION AUTOMATICALLY GENERATES A FILEPATH IN
# WHICH TO SAVE THE CONTENTS OF A JETFREQ QUERY
def build_file_path(params):
debug(params['verbose'], 'Creating the file path')
# GENERATE THE BASE NAME OF THE FILE
file_path = './samples/{}/{}_s-{}_e-{}_n-{}'.format(
build_sub_dir(params),
format_datetime(),
params['search_name'].replace('\\', '__BS__'),
get_event_type_flags(params),
params['sample_size']
)
if params['threshold_lt'] == None:
file_path += "_t-None"
else:
file_path += "_t-{}".format(params['threshold_lt'])
if params['threshold_gt'] == None:
file_path += "_T-None"
else:
file_path += "_T-{}".format(params['threshold_gt'])
# APPEND THE USER NAME FILTERS, IF THEY EXIST
if params['user_name'] != None:
file_path += '_u-{}'.format(params['user_name'].lower())
elif params['exclude_user'] != None:
file_path += '_U-{}'.format(params['exclude_user'].lower())
# APPEND THE HOST NAME FILTERS, IF THEY EXIST
if params['host_name'] != None:
file_path += '_h-{}'.format(params['host_name'].lower())
elif params['exclude_host'] != None:
file_path += '_H-{}'.format(params['exclude_host'].lower())
# APPEND THE FILE NAME FOR THE REPRESENTATIVE SAMPLE IF WRITING A 'COMPARE' MODE REPORT
if not re.match(r'^COMPARE_', params['mode']) == None:
dt = params['import_sample']
if '/' in params['import_sample']:
fn_ary = params['import_sample'].split('/')
dt = fn_ary[len(fn_ary) - 1]
dt = re.split(r'_s-', dt)[0]
file_path += '_i-{}'.format(dt)
# CLOSE FILE PATH WITH CSV EXTENSION
file_path += '.csv'
# ALTHOUGH HIGHLY UNLIKELY BECAUSE OF THE TIME STAMP, IF THE FILE
# ALREADY EXISTS, APPEND A NUMERAL ON THE END OF THE FILENAME
sn = 0
while os.path.isfile(file_path):
sn = sn + 1
file_path = file_path[0:file_path.index('.csv')]
file_path += '_' + sn + '.csv'
debug(params['verbose'], 'File path is {}'.format(file_path))
return file_path
# THIS IS THE MAIN FUNCTION FOR WRITING THE RESULTS OF A --COMPARE-PROCESS
# QUERY TO FILE
def out_file_compare_process(params, event_diffs):
# CHECK THAT THERE ARE INDEED RESULTS
no_results = True
for key in event_diffs:
if len(event_diffs[key]) > 0:
no_results = False
# IF NOT, GO NO FURTHER
if no_results:
raise jfexceptions.NoDiffsFoundError(params['search_name'], params['import_sample'])
# CHECK THAT THE APPROPRIATE DIRECTORIES EXIST
# GENERATE THE FILE PATH AND RETRIEVE THE REPRESENTATIVE SAMPLE PARAMETERS
check_for_sample_dir()
file_path = build_file_path(params)
rep_params = get_params_from_file_name(params['import_sample'])
difftype = DiffType()
debug(params['verbose'], 'Writing to file {}'.format(file_path))
# WRITE THE EVENT DIFFERENCES TO FILE
file = open(file_path, 'w')
file.write('\'event_type\',\'diff_type\',\'tar_process\',\'tar_event\',\'tar_freq\',\'tar_count\',\'tar_total\',\'rep_process\',\'rep_event\',\'rep_freq\',\'rep_count\',\'rep_total\'\n')
for key in event_diffs:
if len(event_diffs[key]) > 0:
event_diffs_for_type = sort_event_diffs_by_type(event_diffs[key])
for event_diff in event_diffs_for_type:
if event_diff.difftype == difftype.MISS_FM_REP or not re.match(r'^REPRESENTATIVE SAMPLE HAS NO', event_diff.difftype) == None:
file.write('\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'NA\',\'NA\',\'NA\',\'NA\'\n'.format(
key,
event_diff.difftype,
params['search_name'],
event_diff.target_event.path,
event_diff.target_event.perc,
event_diff.target_event.count,
event_diff.target_event.total,
rep_params['search_name']
)
)
elif event_diff.difftype == difftype.MISS_FM_TAR or not re.match(r'^TARGET SAMPLE HAS NO', event_diff.difftype) == None:
file.write('\'{}\',\'{}\',\'{}\',\'NA\',\'NA\',\'NA\',\'NA\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\'\n'.format(
key,
event_diff.difftype,
params['search_name'],
rep_params['search_name'],
event_diff.representative_event.path,
event_diff.representative_event.perc,
event_diff.representative_event.count,
event_diff.representative_event.total
)
)
else:
file.write('\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\'\n'.format(
key,
event_diff.difftype,
params['search_name'],
event_diff.target_event.path,
event_diff.target_event.perc,
event_diff.target_event.count,
event_diff.target_event.total,
rep_params['search_name'],
event_diff.representative_event.path,
event_diff.representative_event.perc,
event_diff.representative_event.count,
event_diff.representative_event.total
)
)
file.close()
return file_path
# THIS IS THE MAIN FUNCTION FOR WRITING THE RESULTS OF
# A --COMPARE-EVENT QUERY TO FILE
def out_file_compare_event(params, event_diffs):
# IF THERE ARE NO RESULTS, GO NO FURTHER
if len(event_diffs) == 0:
raise NoDiffsFoundError(params['search_name'], params['import_sample'])
# CHECK THAT THE APPROPRIATE DIRECTORY EXISTS, GENERATE
# THE FILE NAME AND RETRIEVE THE PARAMETERS USED IN THE
# REPRESENTATIVE SAMPLE
check_for_sample_dir()
file_path = build_file_path(params)
rep_params = get_params_from_file_name(params['import_sample'])
difftype = DiffType()
event_diffs = sort_event_diffs_by_type(event_diffs)
# RETRIEVE THE EVENT TYPE USED IN THE QUERY
target_event_type = 'modload'
if params['regmods'] == True:
target_event_type = 'regmod'
elif params['filemods'] == True:
target_event_type = 'filemod'
elif params['childprocs'] == True:
target_event_type = 'childproc'
elif params['netconns'] == True:
target_event_type = 'netconn'
debug(params['verbose'], 'Writing to file {}'.format(file_path))
# WRITE TO FILE
file = open(file_path, 'w')
file.write('\'diff_type\',\'tar_event\',\'tar_process\',\'tar_freq\',\'tar_count\',\'tar_total\',\'rep_event\',\'rep_process\',\'rep_freq\',\'rep_count\',\'rep_total\'\n'.format())
for event_diff in event_diffs:
if event_diff.difftype == difftype.MISS_FM_REP:
file.write('\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'NA\',\'NA\',\'NA\',\'NA\'\n'.format(
event_diff.difftype,
target_event_type,
event_diff.target_event.path,
event_diff.target_event.perc,
event_diff.target_event.count,
event_diff.target_event.total,
rep_params['event_type'].lower()
)
)
elif event_diff.difftype == difftype.MISS_FM_TAR:
file.write('\'{}\',\'{}\',\'NA\',\'NA\',\'NA\',\'NA\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\'\n'.format(
event_diff.difftype,
target_event_type,
rep_params['event_type'].lower(),
event_diff.representative_event.path,
event_diff.representative_event.perc,
event_diff.representative_event.count,
event_diff.representative_event.total
)
)
else: #difftype.HIGH_FQ_*
file.write('\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\'\n'.format(
event_diff.difftype,
target_event_type,
event_diff.target_event.path,
event_diff.target_event.perc,
event_diff.target_event.count,
event_diff.target_event.total,
rep_params['event_type'].lower(),
event_diff.representative_event.path,
event_diff.representative_event.perc,
event_diff.representative_event.count,
event_diff.representative_event.total
)
)
file.close()
return file_path
# THIS IS THE MAIN FUNCTION FOR WRITING THE RESULTS OF A
# --BY-EVENT QUERY TO FILE
def out_file_by_event(params, event_freqs):
# IF THERE ARE NO RESULTS, GO NO FURTHER
if len(event_freqs) == 0:
raise jfexceptions.NoEventsFoundError(params['search_name'])
# CHECK THAT THE APPROPRIATE DIRECTORY EXISTS AND
# GENERATE THE FILE PATH
check_for_sample_dir()
file_path = build_file_path(params)
# GET THE EVENT TYPE USED IN THE QUERY
event_type = 'modload'
if params['filemods'] == True:
event_type = 'filemod'
elif params['regmods'] == True:
event_type = 'regmod'
elif params['childprocs'] == True:
event_type = 'childproc'
elif params['netconns'] == True:
event_type = 'netconn'
debug(params['verbose'], 'Writing to file {}'.format(file_path))
# WRITE TO FILE
file = open(file_path, 'w')
file.write('\'{}\',\'path\',\'count\',\'total\',\'frequency\'\n'.format(event_type))
for event in event_freqs:
file.write('\'{}\',\'{}\',\'{}\',\'{}\',\'{}\'\n'.format(params['search_name'], event.path, event.count, event.total, event.perc))
file.close()
return file_path
# THIS IS THE MAIN FUNCTION FOR WRITING THE RESULTS
# OF A --BY-PROCESS QUERY TO FILE
def out_file_by_process(params, event_freqs):
# CHECK THAT THERE ARE INDEED RESULTS
no_results = True
for key in event_freqs:
if not event_freqs[key] == None:
no_results = False
# IF NOT, THOU SHALT NOT PASSETH
if no_results:
raise jfexceptions.NoEventsFoundError(params['search_name'])
# CHECK THAT THE APPROPRIATE DIRECTORY EXISTS
# AND GENERATE THE FILE PATH
check_for_sample_dir()
file_path = build_file_path(params)
debug(params['verbose'], 'Writing to file {}'.format(file_path))
# WRITE TO FILE
file = open(file_path, 'w')
file.write('\'process\',\'event_type\',\'path\',\'count\',\'total\',\'freq\'\n')
if not event_freqs['modloads'] == None:
events = sort_events(event_freqs['modloads'])
for event in events:
file.write('\'{}\',\'modload\',\'{}\',\'{}\',\'{}\',\'{}\'\n'.format(params['search_name'], event.path, event.count, event.total, event.perc))
if not event_freqs['regmods'] == None:
events = sort_events(event_freqs['regmods'])
for event in events:
file.write('\'{}\',\'regmod\',\'{}\',\'{}\',\'{}\',\'{}\'\n'.format(params['search_name'], event.path, event.count, event.total, event.perc))
if not event_freqs['childprocs'] == None:
events = sort_events(event_freqs['childprocs'])
for event in events:
file.write('\'{}\',\'childproc\',\'{}\',\'{}\',\'{}\',\'{}\'\n'.format(params['search_name'], event.path, event.count, event.total, event.perc))
if not event_freqs['filemods'] == None:
events = sort_events(event_freqs['filemods'])
for event in events:
file.write('\'{}\',\'filemod\',\'{}\',\'{}\',\'{}\',\'{}\'\n'.format(params['search_name'], event.path, event.count, event.total, event.perc))
if not event_freqs['netconns'] == None:
events = sort_events(event_freqs['netconns'])
for event in events:
file.write('\'{}\',\'netconn\',\'{}\',\'{}\',\'{}\',\'{}\'\n'.format(params['search_name'], event.path, event.count, event.total, event.perc))
if not event_freqs['crossprocs'] == None:
events = sort_events(event_freqs['crossprocs'])
for event in events:
file.write('\'{}\',\'crossproc\',\'{}\',\'{}\',\'{}\',\'{}\'\n'.format(params['search_name'], event.path, event.count, event.total, event.perc))
file.close()
return file_path
# THIS FUNCTION READS THE README.TXT FILE
# OUT OUTPUTS THE USAGE SECTION TO STDOUT
def show_usage():
h = open("README.txt", "r")
usage = ""
capture = False
for line in h:
if capture == False and len(usage) > 0:
break
elif capture == True:
usage += line
if re.match(r'^Show Help :', line) != None:
capture = False
elif re.match(r'^Usage:', line) != None:
capture = True
print("\nUSAGE:\n{}".format(usage))
# THIS FUNCTION WRITES THE CONTENTS OF THE README.TXT
# FILE TO STDOUT
def show_help():
h = open("README.txt", "r")
print(h.read())
# THIS FUNCTION IMPORTS THE CONTENTS OF THE CONF FILE
# AND ADDS THEM TO THE PARAMS DICTIONARY
def import_conf(params):
debug(params['verbose'], 'Importing configuration file')
conf = open('./conf/jetfreq.cfg', 'r')
for line in conf:
if line.startswith('#'):
pass
else:
params[line.split('=')[0].lower().strip()] = line.split('=')[1].strip()
conf.close()
return params
# THIS FUNCTION CHECKS FOR USER SPECIFIC REG KEY ADDRESSES
# OR USER SPECIFIC FILE DIRECTORIES AND REPLACES THE UNIQUE
# STRINGS WITH A GENERIC STRING, E.G. 'BROOKES' TO '<USER>'.
# THIS ENSURES THAT THE SAME FILE OR REG KEY IN DIFFERENT USERS
# PROFILES OR MACHINES ARE CONSIDERED THE SAME FILE OR REG KEY
# BY JETFREQ.
def homogenize_path(path, path_type, homogenize):
if not homogenize:
return path
if path_type == "reg":
# \registry\...\usersettings\<sid>\\
# \registry\user\<sid>\
if path.lower().startswith('\\registry\\') and '\\usersettings\\' in path:
try:
path_ary = path.split('\\')
sid = False
for i in range(len(path_ary)):
if sid == True:
path_ary[i] = "<SID>"
sid = False
break
elif path_ary[i] == "usersettings":
sid = True
return '\\'.join(path_ary)
except:
debug(True, 'Error homogenizing regmod path {}'.format(path))
return path
elif path.lower().startswith('\\registry\\user\\'):
try:
path_ary = path.split('\\')
path_ary[3] = '<SID>'
return '\\'.join(path_ary)
except:
debug(True, 'Error homogenizing regmod path {}'.format(path))
else:
return path
elif path_type == "dir":
# c:\users\<user>\
if path.lower().startswith('c:\\users\\') or path.lower().startswith('\\users\\'):
try:
path_ary = path.split('\\')
path_ary[2] = '<USER>'
return '\\'.join(path_ary)
except:
debug(True, 'Error homogenizing path {}'.format(path))
return path
else:
return path
else:
return path
# THIS FUNCTION EXTRACTS THE PATH OF AN EVENT FROM THE
# DATA RETURNED BY THE CARBON BLACK REST API. AS EACH
# EVENT TYPE HAS A UNIQUE FORMAT, THE COLUMN MUST
# BE DEFINED.
def get_event_paths(events, col, path_type, homogenize):
paths = []
for event in events:
paths.append(homogenize_path(event.split('|')[col], path_type, homogenize))
return paths
# THIS FUNCTION CHECKS FOR ATTEMPTS TO GENERATE VERY LARGE
# SAMPLE SIZES AND WARNS THE USER THAT DUE THE VOLUME OF
# DATA, A QUERY WITH A LARGE SAMPLE SIZE MAY TAKE SOME TIME
# TO GENERATE
def throttle(params):
if params['mode'].upper().endswith('HELP'):
return
elif (params['mode'].upper().endswith('PROCESS') and int(params['sample_size']) > 50) or (params['mode'].upper().endswith('EVENT') and int(params['sample_size']) >= 1000):
debug(True, 'Consider reducing the sample size.')
debug(True, 'A sample size of {} in {} mode may generate a large amount of data and require a significant amount of time to process.'.format(params['sample_size'], params['mode']))
ans = raw_input('jetfreq.py: Would you like to continue (y/n)? ')
if ans.lower() == 'y':
return
elif ans.lower() == 'n':
exit()
else:
debug(True, 'Invalid response. Aborting.')
exit()
<file_sep># THIS MODULE CONTAINS ALL THE DEFINED EXCEPTIONS FOR JETFREQ.PY
class Error(Exception):
pass
# EXCEPTION FOR THE INCORRECT USAGE OF FLAGS
class IncorrectUsageError(Error):
def __init__(self, context):
self.context = context
# EXCEPTION FOR JETFREQ.PY BEING USED WITHOUT ANY ARGUMENTS
class NoArgsError(Error):
def __init__(self, message):
self.message = message
# EXCEPTION FOR AN UNDEFINED FLAG BEING USED
class NoSuchArgumentError(Error):
def __init__(self, flag):
self.flag = flag
# EXCEPTION FOR A PARAMETERIZED FLAG BEING USED WITHOUT A VALUE
class MissingValueError(Error):
def __init__(self, flag, name):
self.flag = flag
self.name = name
# EXCEPTION FOR A FLAG BEING USED MORE THAN ONCE
class DoubleArgumentError(Error):
def __init__(self, flag):
self.flag = flag
# EXCEPTION FOR A FLAG THAT IS NOT APPLICABLE IN THE GIVEN MODE
class FlagsNotApplicableError(Error):
def __init__(self, mode, flags):
self.mode = mode
self.flags = flags
# CATCH ALL EXCEPTION FOR AN ERROR FROM THE CARBON BLACK API
class APIQueryError(Error):
def __init__(self, message):
self.message = message
# EXCEPTION FOR MISSING PARAMETERS IN THE JETFREQ CONFIGURATION FILE
class MissingConfigurationError(Error):
def __init__(self):
self.message = "You need to configure jetfreq by adding the Carbon Black Server name and API Key to ./conf/jetfreq.cfg"
# EXCEPTION FOR A JSON FORMAT THAT IS NOT EXPECTED (E.G. MISSING KEY)
class UnexpectedResponseError(Error):
def __init__(self, data):
self.data = data
# EXCEPTION FOR NO RESULTS BEING RETURNED FOR A QUERY
class NoResultsError(Error):
def __init__(self, query):
self.query = query
# EXCEPTION FOR NO EVENTS BEING FOUND FOR A QUERY
class NoEventsFoundError(Error):
def __init__(self, query):
self.query = query
# EXCEPTION FOR --BY-PROCESS OR --COMPARE-PROCESS MODE MISSING EVENT TYPE FLAGS
class ProcessModeMissingEventTypeError(Error):
def __init__(self, mode):
self.mode = mode
# EXCEPTION FOR --COMPARE-PROCESS OR --COMPARE-EVENT MODE MISSING A SAMPLE FILE PATH
class CompareModeMissingSampleFileError(Error):
def __init__(self, mode):
self.mode = mode
# EXCEPTION FOR THE THRESHOLD FLAGS BEING USED INCORRECTLY
class IncorrectUseOfThresholdError(Error):
def __init__(self, threshold):
self.threshold = threshold
# EXCEPTION FOR A FLAG BEING USED THAT IS NOT APPLICABLE FOR THE GIVEN MODE
class IncorrectFlagUsageForModeError(Error):
def __init__(self, mode, flags):
self.mode = mode
self.flags = flags
# EXCEPTION FOR --BY-EVENT OR --COMPARE-EVENT MODE MISSING A MANDATORY FLAG
class ByEventModeFlagRequiredError(Error):
def __init__(self, mode):
self.mode = mode
# EXCEPTION FOR THE WRONG KIND OF SAMPLE FILE BEING IMPORTED FOR --COMPARE MODES
class IncorrectSampleForModeError(Error):
def __init__(self, file_path, mode):
self.file_path = file_path
self.mode = mode
# EXCEPTION FOR NO DIFFERENCES BEING FOUND BETWEEN SAMPLES FOR --COMPARE MODES
class NoDiffsFoundError(Error):
def __init__(self, target_event, sample):
self.target_event = target_event
self.sample = sample
# EXCEPTION FOR EQUAL THRESHOLD VALUES (E.G. -t 50 -T 50)
class NonsensicalThresholdValuesError(Error):
def __init__(self, greater_than, less_than):
self.greater_than = greater_than
self.less_than = less_than
<file_sep># MODULE CONTAINS ALL FUNCTIONS THAT CONDUCT FREQUENCY ANALYSIS ON
# THE RESULTS OF A CARBON BLACK QUERY
import jfutil
import jfexceptions
import re
import json
# CONTAINER CLASS FOR EVENT FREQUENCIES
class EventFreq():
def __init__(self, path, perc, count, total):
self.path = path # PATH OF EVENT
self.perc = perc # PERCENTAGE OF PROCESSES IN WHICH EVENT OCCURS
self.count = count # THE NUMBER OF PROCESSES IN WHICH EVENT OCCURS
self.total = total # THE TOTAL NUMBER OF PROCESSES THAT CONTAIN AN EVENT OF THIS TYPE
# CONTAINER CLASS FOR EVENT DIFFERENCES
class EventDiff():
def __init__(self, target_event, representative_event, difftype):
self.target_event = target_event # AN EVENT FROM THE TARGET SAMPLE
self.representative_event = representative_event # THE CORRESPONDING EVENT FROM THE REPRESENTATIVE SAMPLE
self.difftype = difftype # THE TYPE OF DIFFERENCE BETWEEN THE EVENTS
# CONTAINER CLASS FOR DIFFERENCE TYPES
class DiffType():
def __init__(self):
self.MISS_FM_REP = 'MISSING FROM REPRESENTATIVE SAMPLE'
self.MISS_FM_TAR = 'MISSING FROM TARGET SAMPLE'
self.HIGH_FQ_REP = 'OCCURS MORE IN REPRESENTATIVE SAMPLE'
self.HIGH_FQ_TAR = 'OCCURS MORE IN TARGET SAMPLE'
self.REP_MISS_M = 'REPRESENTATIVE SAMPLE HAS NO MODLOADS, BUT TARGET SAMPLE DOES'
self.REP_MISS_R = 'REPRESENTATIVE SAMPLE HAS NO REGMODS, BUT TARGET SAMPLE DOES'
self.REP_MISS_F = 'REPRESENTATIVE SAMPLE HAS NO FILEMODS, BUT TARGET SAMPLE DOES'
self.REP_MISS_C = 'REPRESENTATIVE SAMPLE HAS NO CHILDPROCS, BUT TARGET SAMPLE DOES'
self.REP_MISS_D = 'REPRESENTATIVE SAMPLE HAS NO NETCONNS, BUT TARGET SAMPLE DOES'
self.REP_MISS_X = 'REPRESENTATIVE SAMPLE HAS NO CROSSPROCS, BUT TARGET SAMPLE DOES'
self.TAR_MISS_M = 'TARGET SAMPLE HAS NO MODLOADS, BUT REPRESENTATIVE SAMPLE DOES'
self.TAR_MISS_R = 'TARGET SAMPLE HAS NO REGMODS, BUT REPRESENTATIVE SAMPLE DOES'
self.TAR_MISS_F = 'TARGET SAMPLE HAS NO FILEMODS, BUT REPRESENTATIVE SAMPLE DOES'
self.TAR_MISS_C = 'TARGET SAMPLE HAS NO CHILDPROCS, BUT REPRESENTATIVE SAMPLE DOES'
self.TAR_MISS_D = 'TARGET SAMPLE HAS NO NETCONNS, BUT REPRESENTATIVE SAMPLE DOES'
self.TAR_MISS_X = 'TARGET SAMPLE HAS NO CROSSPROCS, BUT REPRESENTATIVE SAMPLE DOES'
# TAKES AN EVENT TYPE AND RETURNS THE CORRESPONDING DIFFERENCE TYPE
def get_diff_type_by_event(self, event_type, sample):
if sample == 'rep':
if event_type == 'modloads':
return self.REP_MISS_M
elif event_type == 'regmods':
return self.REP_MISS_R
elif event_type == 'filemods':
return self.REP_MISS_F
elif event_type == 'childprocs':
return self.REP_MISS_C
elif event_type == 'netconns':
return self.REP_MISS_D
else:
return self.REP_MISS_X
else:
if event_type == 'modloads':
return self.TAR_MISS_M
elif event_type == 'regmods':
return self.TAR_MISS_R
elif event_type == 'filemods':
return self.TAR_MISS_F
elif event_type == 'childprocs':
return self.TAR_MISS_C
elif event_type == 'netconns':
return self.TAR_MISS_D
else:
return self.TAR_MISS_X
# ORDER A LIST OF EVENTS ALPHABETICALLY
def alphabetize_events(events):
for i in range(len(events)):
j = i
while j < len(events):
if events[i].path > events[j].path:
hold = events[i]
events[i] = events[j]
events[j] = hold
j = j + 1
return events
# ORDER A LIST OF EVENTS BY THEIR FREQUENCY
def sort_events(events):
for i in range(len(events)):
j = i
while j < len(events):
if events[i].perc > events[j].perc:
hold = events[i]
events[i] = events[j]
events[j] = hold
j = j + 1
return events
# CALCULATE THE FREQUENCY OF A GIVEN EVENT
def calculate_event_frequency(event_counts, total_processes, greater_than, less_than):
events = []
for key in event_counts:
perc = round((event_counts[key]/float(total_processes)), 5)
if greater_than == None:
if perc * 100 <= float(less_than):
events.append(EventFreq(key, perc, event_counts[key], total_processes))
elif less_than == None:
if perc * 100 >= float(greater_than):
events.append(EventFreq(key, perc, event_counts[key], total_processes))
elif float(greater_than) > float(less_than): # both are not None
if perc * 100 <= float(less_than) or perc * 100 >= float(greater_than):
events.append(EventFreq(key, perc, event_counts[key], total_processes))
else:
if perc * 100 <= float(less_than) and perc * 100 >= float(greater_than):
events.append(EventFreq(key, perc, event_counts[key], total_processes))
events = sort_events(events)
return events
# COUNT HOW MANY TIMES AN EVENT OCCURS IN A GIVEN PROCESS
def count_events(process, container, key):
for event in process[key]:
if event in container:
container[event] = container[event] + 1
else:
container[event] = 1
return container
# THE MAIN FUNCTION FOR THE --BY-PROCESS AND --COMPARE-PROCESS MODES
# THIS FUNCTION TAKES THE DATA RETURNED FROM CARBON BLACK AND CALCULATES
# THE FREQUENCY IN WHICH THE SPECIFIED EVENT TYPES OCCUR ACROSS PROCESSES
# IN THE SAMPLE
def analyze_by_process(params, data):
jfutil.debug(params['verbose'], "Conducting analysis for {}".format(params['search_name']))
# INITIALIZE THE JSON CONTAINER FOR THE RESULTS OF THE EVENT COUNT
event_counts = {
'modloads':{},
'regmods':{},
'childprocs':{},
'filemods':{},
'netconns':{},
'crossprocs':{}
}
# COUNT HOW MANY TIMES EACH SPECIFIC EVENT OCCURS ACROSS ALL
# PROCESSES IN THE SAMPLE RETURNED FROM CARBON BLACK
for process in data:
if 'modloads' in process:
jfutil.debug(params['verbose'], 'Counting modloads')
event_counts['modloads'] = count_events(process, event_counts['modloads'], 'modloads')
if 'regmods' in process:
jfutil.debug(params['verbose'], 'Counting regmods')
event_counts['regmods'] = count_events(process, event_counts['regmods'], 'regmods')
if 'childprocs' in process:
jfutil.debug(params['verbose'], 'Counting childprocs')
event_counts['childprocs'] = count_events(process, event_counts['childprocs'], 'childprocs')
if 'filemods' in process:
jfutil.debug(params['verbose'], 'Counting filemods')
event_counts['filemods'] = count_events(process, event_counts['filemods'], 'filemods')
if 'netconns' in process:
jfutil.debug(params['verbose'], 'Counting netconns')
event_counts['netconns'] = count_events(process, event_counts['netconns'], 'netconns')
if 'crossprocs' in process:
jfutil.debug(params['verbose'], 'Counting crossprocs')
event_counts['crossprocs'] = count_events(process, event_counts['crossprocs'], 'crossprocs')
jfutil.debug(params['verbose'], 'Count complete')
# INITIALIZE THE JSON CONTAINER FOR THE RESULTS OF THE EVENT FREQUENCY ANALYSIS
event_freqs = {
'modloads':None,
'regmods':None,
'childprocs':None,
'filemods':None,
'netconns':None,
'crossprocs':None
}
# USING THE COUNTS, CALCULATE THE FREQUENCY IN WHICH EACH EVENT OCCURS ACROSS
# PROCESSES IN THE SAMPLE RETURNED BY <NAME>
if len(event_counts['modloads']) > 0:
jfutil.debug(params['verbose'], 'Calculating freq of modloads')
event_freqs['modloads'] = calculate_event_frequency(event_counts['modloads'], len(data), params['threshold_gt'], params['threshold_lt'])
if len(event_counts['regmods']) > 0:
jfutil.debug(params['verbose'], 'Calculating freq of regmods')
event_freqs['regmods'] = calculate_event_frequency(event_counts['regmods'], len(data), params['threshold_gt'], params['threshold_lt'])
if len(event_counts['childprocs']) > 0:
jfutil.debug(params['verbose'], 'Calculating freq of childprocs')
event_freqs['childprocs'] = calculate_event_frequency(event_counts['childprocs'], len(data), params['threshold_gt'], params['threshold_lt'])
if len(event_counts['filemods']) > 0:
jfutil.debug(params['verbose'], 'Calculating freq of filemods')
event_freqs['filemods'] = calculate_event_frequency(event_counts['filemods'], len(data), params['threshold_gt'], params['threshold_lt'])
if len(event_counts['netconns']) > 0:
jfutil.debug(params['verbose'], 'Calculating freq of netconns')
event_freqs['netconns'] = calculate_event_frequency(event_counts['netconns'], len(data), params['threshold_gt'], params['threshold_lt'])
if len(event_counts['crossprocs']) > 0:
jfutil.debug(params['verbose'], 'Calculating freq of crossprocs')
event_freqs['crossprocs'] = calculate_event_frequency(event_counts['crossprocs'], len(data), params['threshold_gt'], params['threshold_lt'])
jfutil.debug(params['verbose'], "Freq calculations complete")
return event_freqs
# THIS IS THE MAIN FUNCTION FOR --COMPARE-EVENT AND --BY-EVENT MODES
# THIS FUNCTION CALCULATES THE FREQUENCY IN WHICH EACH PROCESS IN A SAMPLE
# CREATES A GIVEN EVENT
def analyze_by_event(params, data):
jfutil.debug(params['verbose'], "Conducting analysis for {}".format(params['search_name']))
# COUNT HOW MANY PROCESSES CREATE A GIVEN EVENT IN THE SAMPLE
event_counts = {}
for process in data:
if not process['path'] in event_counts:
event_counts[process['path']] = 1
else:
event_counts[process['path']] = event_counts[process['path']] + 1
jfutil.debug(params['verbose'], "Count complete")
# CALCULATE THE FREQUENCY IN WHICH PROCESSES CREATE THE EVENT
event_freqs = calculate_event_frequency(event_counts, len(data), params['threshold_gt'], params['threshold_lt'])
jfutil.debug(params['verbose'], "Freq calculations complete")
return event_freqs
# THIS IS A UTILITY FUNCTION THAT LOADS A LIST INTO A
# DICTIONARY IN ORDER TO MAKE THE COMPARISON PROCESS
# MORE EFFICIENT
def load_into_dict(events):
event_dict = {}
for event in events:
event_dict[event.path] = {'freq':event.perc,'object':event}
return event_dict
# THIS IS THE MAIN FUNCTION FOR THE --COMPARE-PROCESS MODE
# THIS FUNCTION COMPARES TWO SAMPLES, AND COLLATES THE DIFFERENCES
# BETWEEN THE SAMPLES INTO DEFINED DIFFERENCE CATEGORIES
def compare_process(params, representative_sample, target_sample):
jfutil.debug(params['verbose'], 'Comparing target process {} to representative sample {}'.format(params['search_name'], params['import_sample']))
# INITIALIZE THE JSON CONTAINER FOR EVENT DIFFERENCES
event_diffs = {'modloads':[],'regmods':[],'childprocs':[],'filemods':[],'netconns':[],'crossprocs':[]}
difftype = DiffType()
# FOR EACH EVENT TYPE
for key in event_diffs:
# IF THE EVENT TYPE EXISTS IN THE REP SAMPLE AND DOES NOT EXIST IN THE TAR SAMPLE
if not representative_sample[key] == None and target_sample[key] == None:
# FOR ALL EVENTS OF THIS TYPE IN THE REP SAMPLE, ADD AN APPROPRIATE 'MISSING FROM TAR' DIFF TYPE
for event in representative_sample[key]:
event_diffs[key].append(EventDiff(None, event, difftype.get_diff_type_by_event(key, 'rep')))
# IF THE EVENT TYPE EXISTS IN THE TAR SAMPLE AND DOES NOT EXIST IN THE REP SAMPLE
elif not target_sample[key] == None and representative_sample[key] == None:
# FOR ALL EVENTS OF THIS TYPE IN THE TAR SAMPLE, ADD AN APPROPRIATE 'MISSING FROM REP' DIFF TYPE
for event in target_sample[key]:
event_diffs[key].append(EventDiff(None, event, difftype.get_diff_type_by_event(key, 'tar')))
# IF THE EVENT TYPE EXISTS IN BOTH THE REP AND TAR SAMPLES
elif not target_sample[key] == None and not representative_sample[key] == None:
# LOAD THE EVENT LIST INTO A DICTIONARY
rep_dict = load_into_dict(representative_sample[key])
tar_dict = load_into_dict(target_sample[key])
# FOR EACH EVENT OF THIS TYPE IN THE TAR SAMPLE
for sub_key in tar_dict:
# IF THE EVENT DOES NOT EXIST IN THE REP SAMPLE, ADD A 'MISSING FROM REP' DIFF TYPE
if not sub_key in rep_dict:
event_diffs[key].append(EventDiff(tar_dict[sub_key]['object'], None, difftype.MISS_FM_REP))
else:
# IF THE EVENT EXISTS IN BOTH SAMPLES, CALCULATE WHETHER IT OCCURS MORE IN THE REP OR TAR SAMPLES
if float(tar_dict[sub_key]['freq']) > float(rep_dict[sub_key]['freq']):
event_diffs[key].append(EventDiff(tar_dict[sub_key]['object'], rep_dict[sub_key]['object'], difftype.HIGH_FQ_TAR))
elif float(tar_dict[sub_key]['freq']) < float(rep_dict[sub_key]['freq']):
event_diffs[key].append(EventDiff(tar_dict[sub_key]['object'], rep_dict[sub_key]['object'], difftype.HIGH_FQ_REP))
# FOR EACH EVENT OF THIS TYPE IN THE REP SAMPLE
for sub_key in rep_dict:
# IF THE EVENT DOES NOT EXIST IN THE TAR SAMPLE, ADD A 'MISSING FROM TAR' DIFF TYPE
if not sub_key in tar_dict:
event_diffs[key].append(EventDiff(None, rep_dict[sub_key]['object'], difftype.MISS_FM_TAR))
jfutil.debug(params['verbose'], 'Comparison complete')
return event_diffs
# THIS IS THE MAIN FUNCTION FOR THE --COMPARE-EVENT MODE
# THIS FUNCTION COMPARES TWO SAMPLES, AND COLLATES THE DIFFERENCES
# BETWEEN THE SAMPLES INTO DEFINED DIFFERENCE CATEGORIES
def compare_event(params, representative_sample, target_sample):
jfutil.debug(params['verbose'], 'Comparing target event {} to representative sample {}'.format(params['search_name'], params['import_sample']))
# INITIALIZE THE JSON CONTAINER FOR PROCESS DIFFERENCES
event_diffs = []
difftype = DiffType()
rep_dict = load_into_dict(representative_sample)
tar_dict = load_into_dict(target_sample)
# FOR EACH PROCESS IN THE TAR SAMPLE
for key in tar_dict:
# IF THE PROCESS DOES NOT EXIST IN THE REP SAMPLE, ADD A 'MISSING FROM REP' DIFF TYPE
if not key in rep_dict:
event_diffs.append(EventDiff(tar_dict[key]['object'], None, difftype.MISS_FM_REP))
else:
# IF THE EVENT EXISTS IN BOTH SAMPLES, CALCULATE WHETHER IT OCCURS MORE IN THE REP OR TAR SAMPLES
if float(tar_dict[key]['freq']) > float(rep_dict[key]['freq']):
event_diffs.append(EventDiff(tar_dict[key]['object'], rep_dict[key]['object'], difftype.HIGH_FQ_TAR))
elif float(tar_dict[key]['freq']) < float(rep_dict[key]['freq']):
event_diffs.append(EventDiff(tar_dict[key]['object'], rep_dict[key]['object'], difftype.HIGH_FQ_REP))
# FOR EACH PROCESS IN THE REP SAMPLE
for key in rep_dict:
# IF THE PROCESS DOES NOT EXIST IN THE TAR SAMPLE, ADD A 'MISSING FROM TAR' DIFF TYPE
if not key in tar_dict:
event_diffs.append(EventDiff(None, rep_dict[key]['object'], difftype.MISS_FM_TAR))
jfutil.debug(params['verbose'], 'Comparison complete')
return event_diffs
<file_sep># THIS MODULE CONTAINS ALL FUNCTIONS ASSOCIATED WITH COMMUNICATING
# WITH THE CARBON BLACK RESPONSE SERVER
import json
import ssl
import httplib
import jfexceptions
import jfutil
# THIS FUNCTION TAKES THE PARAMETERS PASSED TO JETFREQ AND FORMATS
# THE SEARCH QUERY FOR CARBON BLACK APPROPRIATELY
def format_query(params):
query = ""
# IF THE MODE IS AN 'EVENT' MODE, ONLY ONE EVENT TYPE IS ADDED TO THE QUERY
if params['mode'] == 'BY_EVENT' or params['mode'] == 'COMPARE_EVENT':
if params['modloads'] == True:
query += "modload%3A{}".format(params['search_name'])
elif params['regmods'] == True:
query += "regmod%3A{}".format(params['search_name'])
elif params['childprocs'] == True:
query += "childproc_name%3A{}".format(params['search_name'])
elif params['filemods'] == True:
query += "filemod%3A{}".format(params['search_name'])
elif params['netconns'] == True:
query += "domain%3A{}".format(params['search_name'])
query += "%20start%3A{}".format(params['start_time'])
else:
# IF THE MODE IS A 'PROCESS' MODE, ADD THE PROCESS SEARCH NAME ONLY
query += "process_name%3A{}%20start%3A{}".format(params['search_name'], params['start_time'])
# IF A USER OR EXCLUDE-USER HAS BEEN INCLUDED, APPEND IT TO THE QUERY
if params['user_name'] != None:
query += "%20username%3A{}".format(params['user_name'])
elif params['exclude_user'] != None:
query += "%20-username%3A{}".format(params['exclude_user'])
# IF A HOST OR EXLUDE-HOST HAS BEEN INCLUDED, APPEND IT TO THE QUERY
if params['host_name'] != None:
query += "%20hostname%3A{}".format(params['host_name'])
elif params['exclude_host'] != None:
query += "%20-hostname%3A{}".format(params['exclude_host'])
jfutil.debug(params['verbose'], "Query formatted \'{}\'".format(query))
return query
# THIS FUNCTION SENDS A QUERY OVER HTTPS TO THE CARBON BLACK SERVER
def send_query(params, url):
try:
conn = httplib.HTTPSConnection(params['server'], context=ssl._create_unverified_context())
conn.request("GET", url, None, headers={'X-Auth-Token':params['key']})
return conn.getresponse()
except Exception as err:
jfutil.debug(True, "Query \'{}\' failed\n{}".format(url, str(err)))
exit()
# THIS IS THE MAIN FUNCTION FOR FETCHING DATA FOR A GIVEN EVENT
def get_data_for_event(params):
# FORMAT THE URL, INCLUDING THE QUERY
query = format_query(params)
url = "/api/v1/process?cb.urlver=1&rows={}&start=0&q={}".format(params['sample_size'], query)
jfutil.debug(params['verbose'], 'Attempting to send query to Carbon Black server')
jfutil.debug(params['verbose'], 'Server: {}'.format(params['server']))
jfutil.debug(params['verbose'], 'API Key: {}'.format(params['key']))
jfutil.debug(params['verbose'], 'URL: {}'.format(url))
# SEND THE QUERY TO THE CARBON BLACK SERVER AND STORE THE RESULT
response = send_query(params, url)
jfutil.debug(params['verbose'], 'Response: \'{} {}\''.format(response.status, httplib.responses[response.status]))
# STORE THE PATH, PROCESS ID AND SEGMENT ID FOR EACH PROCESS RETURNED BY THE QUERY
data = json.loads(response.read())
process_list = []
jfutil.debug(True, 'Processing response from {}'.format(params['server']))
try:
if 'results' in data:
for result in data['results']:
process_list.append({
'path':jfutil.homogenize_path(result['path'], 'dir', params['homogenize']),
'process_id':result['id'],
'segment_id':result['segment_id']
})
except KeyError:
raise jfexceptions.UnexpectedResponseError(data)
# IF THERE ARE ANY RESULTS, RETURN THE LIST OF PROCESSES
if len(process_list) > 0:
return process_list
else:
raise jfexceptions.NoResultsError(query)
# THIS IS THE MAIN FUNCTION FOR FETCHING DATA FOR A GIVEN PROCESS
def get_data_for_process(params):
# FORMAT THE URL, INCLUDING THE QUERY
query = format_query(params)
url = "/api/v1/process?cb.urlver=1&rows={}&start=0&q={}".format(params['sample_size'], query)
jfutil.debug(params['verbose'], 'Attempting to send query to Carbon Black server')
jfutil.debug(params['verbose'], 'Server: {}'.format(params['server']))
jfutil.debug(params['verbose'], 'API Key: {}'.format(params['key']))
jfutil.debug(params['verbose'], 'URL: {}'.format(url))
# SEND THE QUERY TO THE CARBON BLACK SERVER AND STORE THE RESULT
response = send_query(params, url)
jfutil.debug(params['verbose'], 'Response: \'{} {}\''.format(response.status, httplib.responses[response.status]))
# FOR EACH PROCESS RETURNED IN THE RESULTS, STORE THE PROCESS ID AND SEGMENT ID
data = json.loads(response.read())
id_list = []
jfutil.debug(True, 'Processing response from {}'.format(params['server']))
try:
if 'results' in data:
for result in data['results']:
id_list.append({
'process_id':result['id'],
'segment_id':result['segment_id']
})
except KeyError:
raise jfexceptions.UnexpectedResponseError(data)
# FOR EACH PROCESS ID AND SEGMENT ID PAIR...
events = []
if len(id_list) > 0:
jfutil.debug(True, 'Fetching event details for {} processes'.format(len(id_list)))
event_cnt = 0
for i in id_list:
# USE THE IDS TO FORMAT A REST API URL AND FETCH THAT PROCESSES EVENT DETAILS
event_cnt = event_cnt + 1
event = {}
jfutil.debug(params['verbose'], "Getting events for result {}".format(event_cnt))
url = "/api/v1/process/{}/0/event".format(i['process_id'])
response = send_query(params, url)
data = json.loads(response.read())
# IF THE USER REQUESTED MODLOADS...
if params['modloads'] == True:
# AND THERE ARE MODLOADS IN THE SEARCH RESULTS...
if 'modload_complete' in data['process']:
# EXTRACT THE PATHS OF THE EVENTS AND STORE THEM IN THE MODLOADS LIST
event['modloads'] = jfutil.get_event_paths(data['process']['modload_complete'], 2, 'dir', params['homogenize'])
else:
jfutil.debug(params['verbose'], "Result {} has no modloads".format(event_cnt))
# IF THE USER REQUESTED FILEMODS...
if params['filemods'] == True:
# AND THERE ARE FILEMODS IN THE SEARCH RESULTS...
if 'filemod_complete' in data['process']:
# EXTRACT THE PATHS OF THE EVENTS AND STORE THEM IN THE FILEMODS LIST
event['filemods'] = jfutil.get_event_paths(data['process']['filemod_complete'], 2, 'dir', params['homogenize'])
else:
jfutil.debug(params['verbose'], "Result {} has no filemods".format(event_cnt))
# IF THE USER REQUESTED REGMODS...
if params['regmods'] == True:
# AND THERE ARE REGMODS IN THE SEARCH RESULTS...
if 'regmod_complete' in data['process']:
# EXTRACT THE PATHS OF THE EVENTS AND STORE THEM IN THE REGMODS LIST
event['regmods'] = jfutil.get_event_paths(data['process']['regmod_complete'], 2, 'reg', params['homogenize'])
else:
jfutil.debug(params['verbose'], "Result {} has no regmods".format(event_cnt))
# IF THE USER REQUESTED CHILDPROCS...
if params['childprocs'] == True:
# AND THERE ARE CHILDPROCS IN THE SEARCH RESULTS...
if 'childproc_complete' in data['process']:
# EXTRACT THE PATHS OF THE EVENTS AND STORE THEM IN THE CHILDPROCS LIST
event['childprocs'] = jfutil.get_event_paths(data['process']['childproc_complete'], 3, 'dir', params['homogenize'])
else:
jfutil.debug(params['verbose'], "Result {} has no childprocs".format(event_cnt))
# IF THE USER REQUESTED CROSSPROCS...
if params['crossprocs'] == True:
# AND THERE ARE CROSSPROCS IN THE SEARCH RESULTS...
if 'crossproc_complete' in data['process']:
# EXTRACT THE PATHS OF THE EVENTS AND STORE THEM IN THE CROSSPROCS LIST
event['crossprocs'] = jfutil.get_event_paths(data['process']['crossproc_complete'], 4, 'dir', params['homogenize'])
else:
jfutil.debug(params['verbose'], "Result {} has no crossprocs".format(event_cnt))
# IF THE USER REQUESTED NETCONNS...
if params['netconns'] == True:
# AND THERE ARE NETCONNS IN THE SEARCH RESULTS...
if 'netconn_complete' in data['process']:
# EXTRACT THE DOMAINS OF THE EVENTS AND STORE THEM IN THE NETCONNS LIST
event['netconns'] = jfutil.get_event_paths(data['process']['netconn_complete'], 4, 'dir', params['homogenize'])
else:
jfutil.debug(params['verbose'], "Result {} has no netconns".format(event_cnt))
# IF ANY REQUESTED EVENTS HAVE BEEN EXTRACTED FROM THIS PROCESS, ADD THEM TO THE EVENT LIST
if 'modloads' in event or 'filemods' in event or 'regmods' in event or 'childprocs' in event or 'crossprocs' in event or 'netconns' in event:
events.append(event)
else:
raise jfexceptions.NoResultsError(query)
# IF ANY EVENTS WERE FOUND, RETURN THE EVENTS LIST
if len(events) > 0:
return events
else:
raise jfexceptions.NoEventsFoundError(query)
|
0f9beb3c2d682bf57eb327fe0917bfae37f8e13c
|
[
"Python",
"Text"
] | 7 |
Python
|
sjb-ch1mp/jetfreq
|
681d0b7abca95716a30b11c88a7eb897021b863a
|
f37e1040d21d7b1c4795f836c545e69194d06124
|
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 lab3;
/**
*
* @author Benjamin
*/
public class ReportService {
private String report = "";
public void addData(String data) {
report += data;
}
public void outputReport() {
System.out.println(report);
}
public void clearReport() {
report = "";
}
}
<file_sep>package lab4;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Benjamin
*/
public class HrHead {
private List<Employee> employee;
public HrHead() {
employee = new ArrayList();
}
public void hireEmployee(String firstName, String lastName, String ssn) {
Employee e = new Employee(firstName, lastName, ssn);
e.setFirstName(firstName);
e.setLastName(lastName);
e.setSsn(ssn);
employee.add(e);
orientEmployee(e);
}
public void orientEmployee(Employee e) {
e.doFirstTimeOrientation("A101");
}
public void outputReport(String ssn) {
Employee e = null;
for (Employee emp : employee) {
if (emp.getSsn().equals(ssn)) {
e = emp;
break;
} else {
return;
}
}
if (e.isMetWithHr() && e.isMetDeptStaff() && e.isReviewedDeptPolicies() && e.isMovedIn()) {
e.getReportService().outputReport();
}
}
public List<Employee> getEmployee() {
return employee;
}
public void setEmployee(List<Employee> employee) {
this.employee = employee;
}
}
|
cadebc6a3ba606a3d03e8ae07352286ed2f74699
|
[
"Java"
] | 2 |
Java
|
bdavis32/Encapsulation
|
f502caeb9ed2d6da3a01f197e8c1ab42d47e08d8
|
c6daea064097942dfb695c7a4705dfb77abdada7
|
refs/heads/master
|
<repo_name>kalinon/mtgscan<file_sep>/README.md
### How to use
Update the cache of card images:
```bash
$ python3 -m mtgscan --update-cache
```
Then start the scanner:
```bash
$ python3 -m mtgscan --set=ust --cam=0 --threshold=4
```
<file_sep>/mtgscan/mtgscan.py
import cv2
import numpy as np
import json
from PIL import Image, ImageFilter
from glob import glob
import imagehash
class MtgScan:
def __init__(self, set_code, cam_num=0, threshold=10, debug=False) -> None:
self.cap = cv2.VideoCapture(cam_num)
self.sorted_contours = []
self.frame = None
self.threshold = threshold
self.set_code = set_code
self.debug = debug
def run(self):
while True:
_, self.frame = self.cap.read()
# Convert to grey scale
gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
# Create Threshold
_, thresh = cv2.threshold(gray, 130, 255, cv2.THRESH_BINARY)
# Find Contours
self.sorted_contours = self.find_contours(thresh)
# Identify a contour that is a card (or most likely)
card_contour, card_image, maxWidth, maxHeight = self.find_card_contour()
if card_contour is not None:
cv2.drawContours(self.frame, [card_contour], -1, (0, 255, 0), 2)
cv2.imshow("card?", card_image)
# Render Frame
self.render()
if cv2.waitKey(1) == ord('c') and card_image is not None:
self.identify_card(self.set_code, card_image, maxWidth, maxHeight, self.threshold)
if cv2.waitKey(1) == ord('q'):
break
self.cap.release()
cv2.destroyAllWindows()
def render(self):
cv2.imshow("frame", self.frame)
def draw_contours(self, contours):
for _, contour in contours:
cv2.drawContours(self.frame, [contour], -1, (0, 255, 0), 2)
def find_card_contour(self):
if self.sorted_contours is None:
return
for _, contour in self.sorted_contours:
dst, max_height, max_width, rect = self.warp_contour(contour)
if max_width == 0 or max_height == 0:
continue
ratio = max_height / max_width
if (ratio >= 0.730 or ratio <= 0.739) and dst[2][0] < 1200 and dst[2][1] < 1200:
if self.debug:
print(ratio)
M = cv2.getPerspectiveTransform(rect, dst)
return contour, cv2.warpPerspective(self.frame, M, (max_width, max_height)), max_width, max_height
def warp_contour(self, card_contour):
# create a min area rectangle from our contour
_rect = cv2.minAreaRect(card_contour)
box = cv2.boxPoints(_rect)
box = np.int0(box)
# create empty initialized rectangle
rect = np.zeros((4, 2), dtype="float32")
# get top left and bottom right points
s = box.sum(axis=1)
rect[0] = box[np.argmin(s)]
rect[2] = box[np.argmax(s)]
# get top right and bottom left points
diff = np.diff(box, axis=1)
rect[1] = box[np.argmin(diff)]
rect[3] = box[np.argmax(diff)]
(tl, tr, br, bl) = rect
widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
maxWidth = max(int(widthA), int(widthB))
heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
maxHeight = max(int(heightA), int(heightB))
dst = np.array([
[0, 0],
[maxWidth - 1, 0],
[maxWidth - 1, maxHeight - 1],
[0, maxHeight - 1]], dtype="float32")
return dst, maxHeight, maxWidth, rect
@staticmethod
def get_contour_points(contour):
rect = cv2.minAreaRect(contour)
points = cv2.boxPoints(rect)
points = np.int0(points)
return points
@staticmethod
def find_contours(thresh):
_, contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
return sorted([(cv2.contourArea(i), i) for i in contours], key=lambda a: a[0], reverse=True)
@staticmethod
def identify_card(set_code, card, max_width, max_height, threshold=10):
# hash our warped image
hash = imagehash.average_hash(Image.fromarray(card))
images = []
# loop over all official images
for orig in glob('images/{}/*.jpg'.format(set_code)):
# grayscale, resize, and blur original image
orig_image = Image.open(orig).convert('LA')
orig_image.resize((max_width, max_height))
orig_image.filter(ImageFilter.BLUR)
# hash original and get hash
orig_hash = imagehash.average_hash(orig_image)
score = hash - orig_hash
if score <= threshold:
images.append({'file': orig, 'score': score})
print('Comparing image to {}, score {}'.format(
orig, score
))
print('-' * 50)
if len(images) > 0:
best_match = sorted(images, key=lambda k: k['score'])[0]
print('Best match is file: {} with score of: {}'.format(best_match['file'], best_match['score']))
print('-' * 50)
<file_sep>/mtgscan/__main__.py
import sys
import argparse
from .mtgscan import MtgScan
from .scryfall import ScryFall
def main():
parser = argparse.ArgumentParser(description='MTG Scan Script')
parser.add_argument('--update-cache', action='store_true', required=False,
help='Will download and cache card images from scryfall.com')
parser.add_argument('--debug', action='store_true', required=False,
help='enable debug')
parser.add_argument('-s', '--set', type=str, required=False, help='The MTG set to search')
parser.add_argument('-c', '--camera', default=0, type=int, required=False, help='The Camera to bind to')
parser.add_argument('-t', '--threshold', default=10, type=int, required=False,
help='The threshold to decide a match. Min=1 Max=20')
args = parser.parse_args()
if args.update_cache:
ScryFall.cache_images()
exit()
if args.set is None:
print('Must provide a --set to search!')
exit(1)
if args.threshold < 1 or args.threshold > 20:
print('Must provide a --threshold between 1 and 20!')
exit(1)
MtgScan(args.set, args.camera, args.threshold, args.debug).run()
exit()
if __name__ == '__main__':
main()
<file_sep>/mtgscan/__init__.py
from mtgscan.mtgscan import MtgScan
from mtgscan.scryfall import ScryFall<file_sep>/mtgscan/scryfall.py
import json
import requests
from time import sleep
import urllib.request
import os
import os.path
class ScryFall:
BASE_URI = "https://api.scryfall.com"
def __init__(self) -> None:
super().__init__()
@staticmethod
def get_set_info():
sleep(0.07)
response = requests.get(ScryFall.BASE_URI + "/sets")
return response.json()
@staticmethod
def get_set_cards(set_code):
sleep(0.07)
search_url = "{}/cards/search".format(ScryFall.BASE_URI)
response = requests.get(search_url, params={'order': 'sets', 'q': 's:{}'.format(set_code), 'unique': 'prints'})
return response.json()
@staticmethod
def download_image(uri, path):
sleep(0.07)
urllib.request.urlretrieve(uri, path)
@staticmethod
def cache_images():
for set_data in ScryFall.get_set_info()['data']:
set_code = set_data['code']
set_name = set_data['name']
set_dir = 'images/' + set_code
set_data_file = set_dir + '/' + set_code + '.json'
print('{} - {}'.format(set_code, set_name))
# Make the dir if it does not exist
if not os.path.exists(set_dir):
os.mkdir(set_dir)
if os.path.exists(set_data_file):
f = open(set_data_file, 'r')
set_card_list = json.load(f)
f.close()
ScryFall.cache_set_images(set_code, set_card_list, set_dir)
else:
# Now gather all the cards in the set
set_card_list = ScryFall.get_set_cards(set_code)
# Write the response json for caching
f = open(set_data_file, 'w+')
f.write(json.dumps(set_card_list))
f.close()
ScryFall.cache_set_images(set_code, set_card_list, set_dir)
@staticmethod
def cache_set_images(set_code, set_card_list, set_dir):
if set_card_list is None:
print('Unable to get cards for set: {}').format(set_code)
else:
while ScryFall.download_cards(set_card_list, set_dir):
set_card_list = requests.get(set_card_list['next_page']).json()
@staticmethod
def download_cards(set_card_list, set_dir):
for card_data in set_card_list['data']:
try:
image_uri = card_data['image_uris']['large']
image_path = set_dir + '/' + card_data['id'] + '.jpg'
# if the file exits, don't download it again
if not os.path.exists(image_path):
ScryFall.download_image(image_uri, image_path)
except KeyError:
try:
if card_data['card_faces'][0]:
image_uri = card_data['card_faces'][0]['image_uris']['large']
image_path = set_dir + '/' + card_data['id'] + '.jpg'
# if the file exits, don't download it again
if not os.path.exists(image_path):
ScryFall.download_image(image_uri, image_path)
except:
print("failed to download image for {}".format(card_data))
return bool(set_card_list['has_more'])
|
f289457032d4d57e54271c729ed3e2bca0447fe5
|
[
"Markdown",
"Python"
] | 5 |
Markdown
|
kalinon/mtgscan
|
d64cd6308637e23f84fca30544bd9bf1f957d54c
|
3cae9eb3e7a657c20681652fbe2571e6c7c422a1
|
refs/heads/master
|
<repo_name>ravindracs0071/fullstackdotnet<file_sep>/HCL.UBP/HCL.UBP.WebUI/App_Start/UnityConfig.cs
using HCL.UBP.DataAccess.Interface;
using HCL.UBP.DataAccess.Repositories;
using System.Web.Mvc;
using log4net;
using Unity;
using Unity.Mvc5;
using UnityLog4NetExtension.Log4Net;
using Unity.Injection;
namespace HCL.UBP.WebUI
{
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<ILog>(new InjectionFactory(factory => new LoggerForInjection()));
container.RegisterType<IUserRepository, UserRepository>();
System.Web.Mvc.DependencyResolver.SetResolver(new UnityDependencyResolver(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
}
<file_sep>/HCL.UBP/HCL.UBP.DataAccess/App_Start/UnityConfig.cs
using HCL.UBP.DataAccess.Interface;
using HCL.UBP.DataAccess.Repositories;
using log4net;
using System.Web.Mvc;
using Unity;
using Unity.Mvc5;
namespace HCL.UBP.DataAccess
{
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
//container.RegisterType<ILog>(new Unity.Injection.InjectionFactory(factory => LogManager.GetLogger("",)));
container.RegisterType<IUserRepository, UserRepository>();
System.Web.Mvc.DependencyResolver.SetResolver(new UnityDependencyResolver(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
}<file_sep>/HCL.UBP/HCL.UBP.DataAccess/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Unity;
namespace HCL.UBP.DataAccess
{
public class Program
{
public static void Main()
{
//IUnityContainer unitycontainer = new Unity.UnityContainer();
//unitycontainer.RegisterType<Interface.IUserRepository, Repositories.UserRepository>();
//Repositories.UserRepository user = unitycontainer.Resolve<Repositories.UserRepository>();
//var result = user.GetUsers();
//string password = EncryptSource("<PASSWORD>");
//user.CreateUser(new Model.UserDetails {
// Id = 0,
// Username = "admin12345",
// Password = <PASSWORD>,
// CreationTime = DateTime.Now,
// LastModificationTime = DateTime.Now
//});
//result = user.GetUsers();
}
//private static string EncryptSource(string text)
//{
// byte[] bytes = Encoding.Unicode.GetBytes(text.Trim());
// byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(bytes);
// return Convert.ToBase64String(inArray);
//}
}
}
<file_sep>/HCL.UBP/HCL.UBP.DataAccess/UBPDbContext.cs
using HCL.UBP.DataAccess.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
namespace HCL.UBP.DataAccess
{
public class UBPDbContext : DbContext
{
public UBPDbContext()
: base("UBPEntities")
{
}
#region "DB Tables"
public DbSet<UserDetails> UserDetails { get; set; }
#endregion
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
#region "Custom implementation"
modelBuilder.Entity<UserDetails>().HasKey(p => p.Id);
modelBuilder.Entity<UserDetails>().HasIndex(p => p.Username).IsUnique();
#endregion
base.OnModelCreating(modelBuilder);
}
}
}
<file_sep>/HCL.UBP/HCL.UBP.DataAccess/Repositories/UserRepository.cs
using HCL.UBP.DataAccess.Interface;
using HCL.UBP.DataAccess.Model;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity.Attributes;
namespace HCL.UBP.DataAccess.Repositories
{
public class UserRepository : IUserRepository
{
[Dependency]
public UBPDbContext DbContext { get; set; }
private readonly ILog _logger;
public UserRepository(ILog logger)
{
_logger = logger;
}
public bool CreateUser(UserDetails input)
{
try
{
DbContext.UserDetails.Add(input);
DbContext.SaveChanges();
return true;
}
catch (Exception ex)
{
_logger.Error(ex);
throw new Exception(ex.Message);
}
}
public bool DeleteUser(int id)
{
try
{
UserDetails user = DbContext.UserDetails.Find(id);
DbContext.Entry(user).State = System.Data.Entity.EntityState.Deleted;
DbContext.SaveChanges();
return true;
}
catch (Exception ex)
{
_logger.Error(ex);
throw new Exception(ex.Message);
}
}
public UserDetails GetUser(int id)
{
try
{
return DbContext.UserDetails.Where(s => s.Id == id).FirstOrDefault();
}
catch (Exception ex)
{
_logger.Error(ex);
throw new Exception(ex.Message);
}
}
public IEnumerable<UserDetails> GetUsers()
{
try
{
return DbContext.UserDetails.ToList();
}
catch (Exception ex)
{
//TODO: ILogger
throw new Exception(ex.Message);
}
}
public bool UpdateUser(UserDetails input)
{
try
{
DbContext.Entry(input).State = System.Data.Entity.EntityState.Modified;
DbContext.SaveChanges();
return true;
}
catch (Exception ex)
{
_logger.Error(ex);
throw new Exception(ex.Message);
}
}
}
}
<file_sep>/HCL.UBP/HCL.UBP.DataAccess/Model/UserDetails.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HCL.UBP.DataAccess.Model
{
[Table("UserDetails")]
public class UserDetails : BaseEntity
{
public const int NVarcharLength36 = 36;
[Required]
[MaxLength(NVarcharLength36)]
public virtual string Username { get; set; }
[Required]
[MaxLength(NVarcharLength36)]
public virtual string Password { get; set; }
}
}
<file_sep>/HCL.UBP/HCL.UBP.DataAccess/Interface/IUserRepository.cs
using HCL.UBP.DataAccess.Model;
using System.Collections.Generic;
namespace HCL.UBP.DataAccess.Interface
{
public interface IUserRepository
{
bool CreateUser(UserDetails input);
bool DeleteUser(int id);
UserDetails GetUser(int id);
IEnumerable<UserDetails> GetUsers();
bool UpdateUser(UserDetails input);
}
}
<file_sep>/README.md
# fullstackdotnet
A POC on .NET 4.6.2 with MVC 5
<file_sep>/HCL.UBP/HCL.UBP.WebUI/Controllers/AccountController.cs
using HCL.UBP.DataAccess.Interface;
using HCL.UBP.WebUI.Models;
using log4net;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace HCL.UBP.WebUI.Controllers
{
public class AccountController : Controller
{
private readonly IUserRepository _userRepository;
private readonly ILog _logger;
public AccountController(IUserRepository userRepository, ILog logger)
{
_logger = logger;
_userRepository = userRepository;
}
[AllowAnonymous]
[HttpGet]
public ActionResult Login(string returnUrl = "")
{
ViewBag.ReturnUrl = returnUrl;
return View("Login");
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model, string returnUrl = "")
{
if (!ModelState.IsValid)
{
return View(model);
}
string encryptPassword = EncryptSource(model.Password);
var result = _userRepository.GetUsers().Where(u => u.Username.Equals(model.Username) && u.Password.Equals(encryptPassword)).FirstOrDefault();
if (result != null)
{
FormsAuthentication.SetAuthCookie(result.Username, false);
var authTicket = new FormsAuthenticationTicket(1, result.Username, DateTime.Now, DateTime.Now.AddMinutes(30), false, "User");
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Response.Cookies.Add(authCookie);
//Redirect
if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Invalid login attempt.");
}
return View("Login");
}
[HttpGet]
[AllowAnonymous]
public ActionResult Register()
{
ViewBag.IsSuccess = false;
return View("Register");
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model)
{
ViewBag.IsSuccess = false;
if (ModelState.IsValid)
{
var hasRows = _userRepository.GetUsers().Where(u => u.Username.Equals(model.Username.Trim())).Count();
if (hasRows == 0)
{
string encryptPassword = EncryptSource(model.Password.Trim());
var isSuccess = _userRepository.CreateUser(new DataAccess.Model.UserDetails
{
Id = 0,
Username = model.Username.Trim(),
Password = <PASSWORD>,
CreationTime = DateTime.Now
});
ViewBag.IsSuccess = true;
}
else
{
//Username already exists
ModelState.AddModelError("Username", "This username is already taken");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
#region "NonAction"
[NonAction]
private string EncryptSource(string text)
{
byte[] bytes = Encoding.Unicode.GetBytes(text.Trim());
byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(bytes);
return Convert.ToBase64String(inArray);
}
#endregion
}
}
|
989e58425f6682087d5c833feea3573c547fb1b7
|
[
"Markdown",
"C#"
] | 9 |
C#
|
ravindracs0071/fullstackdotnet
|
d7ecdf7609c9e257187e78f75e029394ced709ec
|
88947c3c6dbe5db351b742482e027103be6c9a38
|
refs/heads/master
|
<repo_name>vi255/WikiTutorial<file_sep>/src/WikiTutorial.Web/App/Main/views/cliente/cliente_create_or_edit.js
(function () {
'use strict';
angular
.module('app')
.controller('app.views.cliente.cliente_create_or_edit', ClienteModalController)
ClienteModalController.$inject =
[
'$scope',
'$uibModalInstance',
'abp.services.app.cliente',
'id',
'isEditing'
];
function ClienteModalController($scope, $uibModalInstance, clienteService, id, isEditing) {
var vm = this;
vm.save = save;
vm.cancel = cancel;
vm.isEditing = isEditing;
vm.product = {};
activate();
function activate() {
if (isEditing) {
abp.ui.setBusy();
getCliente();
}
}
function getCliente() {
clienteService.getById(id)
.then(fillCliente, errorMessage)
.catch(unblockByError);
function fillCliente(result) {
abp.ui.clearBusy();
vm.cliente = result.data;
}
}
function create() {
abp.ui.setBusy();
clienteService.createCliente(vm.cliente)
.then(success)
.catch(unblockByError);
}
function update() {
abp.ui.setBusy();
clienteService.updateCliente(vm.cliente)
.then(success)
.catch(unblockByError);
}
function success() {
abp.ui.clearBusy();
$uibModalInstance.close({});
}
function errorMessage(result) {
abp.ui.clearBusy();
abp.notify.error(result);
}
function unblockByError(error) {
console.log(error);
abp.ui.clearBusy();
}
function save() {
if (isEditing) {
update();
} else {
create();
}
};
function cancel() {
$uibModalInstance.dismiss({});
};
}
}) ();<file_sep>/src/WikiTutorial.Core/Entities/ClienteEntity/Manager/IClienteManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WikiTutorial.Entities.ClienteEntity.Manager
{
public interface IClienteManager
{
Task<long> Create(Cliente cliente);
Task<Cliente> Update(Cliente cliente);
Task Delete(long id);
Task<Cliente> GetById(long id);
Task<List<Cliente>> GetAllList();
}
}
<file_sep>/src/WikiTutorial.Application/ClienteServices/DTOs/GetAllClienteOutput.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WikiTutorial.ClienteServices.DTOs
{
public class GetAllClienteOutput
{
public List<GetAllClienteItem> Cliente { get; set; }
}
}
<file_sep>/src/WikiTutorial.Application/ProductServices/DTOs/GetAllProductsOutput .cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WikiTutorial.ProductServices.DTOs
{
public class GetAllProductsOutput
{
public List<GetAllProductsItem> Produtos { get; set; }
}
}
<file_sep>/src/WikiTutorial.Application/ClienteServices/IClienteAppService.cs
using Abp.Application.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WikiTutorial.ClienteServices.DTOs;
namespace WikiTutorial.ClienteServices
{
public interface IClienteAppService : IApplicationService
{
Task<CreateClienteOutput> CreateCliente(CreateClienteInput input);
Task<UpdateClienteOutput> UpdateCliente(UpdateClienteInput input);
Task DeleteCliente(long id);
Task<GetClienteByIdOutput> GetById(long id);
Task<GetAllClienteOutput> GetAllCliente();
}
}
<file_sep>/src/WikiTutorial.Application/ClienteServices/ClienteAppService.cs
using Abp.Application.Services;
using Abp.AutoMapper;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WikiTutorial.ClienteServices.DTOs;
using WikiTutorial.Entities.ClienteEntity;
using WikiTutorial.Entities.ClienteEntity.Manager;
namespace WikiTutorial.ClienteServices
{
public class ClienteAppService : ApplicationService, IClienteAppService
{
private IClienteManager _clienteManager;
public ClienteAppService(IClienteManager clienteManager)
{
_clienteManager = clienteManager;
}
public async Task<CreateClienteOutput> CreateCliente(CreateClienteInput input)
{
var cliente = input.MapTo<Cliente>();
var createdClienteId = await _clienteManager.Create(cliente);
return new CreateClienteOutput
{
Id = createdClienteId
};
}
public async Task DeleteCliente(long id)
{
await _clienteManager.Delete(id);
}
public async Task<GetAllClienteOutput> GetAllCliente()
{
var cliente = await _clienteManager.GetAllList();
return new GetAllClienteOutput { Cliente = Mapper.Map<List<GetAllClienteItem>>(cliente) };
}
public async Task<GetClienteByIdOutput> GetById(long id)
{
var cliente = await _clienteManager.GetById(id);
return Mapper.Map<GetClienteByIdOutput>(cliente);
}
public async Task<UpdateClienteOutput> UpdateCliente(UpdateClienteInput input)
{
var cliente = input.MapTo<Cliente>();
var clienteAtualizado = await _clienteManager.Update(cliente);
return clienteAtualizado.MapTo<UpdateClienteOutput>();
}
}
}
<file_sep>/src/WikiTutorial.Core/Entities/ClienteEntity/Cliente.cs
using Abp.Domain.Entities.Auditing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WikiTutorial.Entities.ClienteEntity
{
public class Cliente : FullAuditedEntity<long> //entidade coberta pela auditoria padrão do ABP, seu ID é do tipo long.
{
//Atributos
public string Name { get; set; }
public string LastName { get; set; }
public string Cpf { get; set; }
public string Idade { get; set; }
public string Email { get; set; }
//Construtores
public Cliente()
{
this.CreationTime = DateTime.Now;
}
public Cliente(string name, string lastname, string cpf, string idade, string email)//argumentos úteis para mapeamento
{
this.CreationTime = DateTime.Now;
this.Name = name;
this.LastName = lastname;
this.Cpf = cpf;
this.Idade = idade;
this.Email = email;
}
}
}
<file_sep>/src/WikiTutorial.Core/Entities/ClienteEntity/Manager/ClienteManager.cs
using Abp.Domain.Repositories;
using Abp.Domain.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WikiTutorial.Entities.ClienteEntity.Manager;
using WikiTutorial.Entities.ClienteEntity;
namespace WikiTutorial.Entities.Manager
{
public class ClienteManager : IDomainService, IClienteManager
{
private IRepository<Cliente, long> _clienteRepository;
public ClienteManager(IRepository<Cliente, long> clienteRepository)
{
_clienteRepository = clienteRepository;
}
public async Task<long> Create(Cliente cliente)
{
return await _clienteRepository.InsertAndGetIdAsync(cliente);
}
public async Task Delete(long id)
{
await _clienteRepository.DeleteAsync(id);
}
public async Task<List<Cliente>> GetAllList()
{
return await _clienteRepository.GetAllListAsync();
}
public async Task<Cliente> GetById(long id)
{
return await _clienteRepository.GetAsync(id);
}
public async Task<Cliente> Update(Cliente cliente)
{
return await _clienteRepository.UpdateAsync(cliente);
}
}
}<file_sep>/src/WikiTutorial.Application/WikiTutorialApplicationModule.cs
using System.Reflection;
using Abp.AutoMapper;
using Abp.Modules;
using WikiTutorial.ClienteServices.DTOs;
using WikiTutorial.Entities.ClienteEntity;
using WikiTutorial.Entities.ProductEntity;
using WikiTutorial.ProductServices.DTOs;
namespace WikiTutorial
{
[DependsOn(typeof(WikiTutorialCoreModule), typeof(AbpAutoMapperModule))]
public class WikiTutorialApplicationModule : AbpModule
{
public override void PreInitialize()
{
Configuration.Modules.AbpAutoMapper().Configurators.Add(config =>
{
config.CreateMap<CreateProductInput, Product>()
.ConstructUsing(x => new Product(x.Name, x.Description, x.Size, x.Value));
config.CreateMap<UpdateProductInput, Product>()
.ConstructUsing(x => new Product(x.Name, x.Description, x.Size, x.Value));
config.CreateMap<CreateClienteInput, Cliente>()
.ConstructUsing(x => new Cliente(x.Name, x.LastName, x.Cpf, x.Idade, x.Email));
config.CreateMap<UpdateClienteInput, Cliente>()
.ConstructUsing(x => new Cliente(x.Name, x.LastName, x.Cpf, x.Idade, x.Email));
});
}
public override void Initialize()
{
Configuration.Modules.AbpAutoMapper().Configurators.Add(configuration => {
configuration.CreateMissingTypeMaps = true;
});
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}
}
|
4d016dc6f2cbe6126ea0d2ba4af380156c44d4c9
|
[
"JavaScript",
"C#"
] | 9 |
JavaScript
|
vi255/WikiTutorial
|
7c1b78ac82ebaf3c60d038c4248ad6a01fe5ee09
|
10128bdfb89a6b12fdcc8764e4c8dfea665d8a16
|
refs/heads/main
|
<file_sep>namespace PrejittedLambda.Features.HealthCheck
{
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
[Route("api/[controller]")]
[ApiController]
public class HealthCheckController : ControllerBase
{
//private readonly IMediator _mediator;
//public HealthCheckController(IMediator mediator)
//{
// _mediator = mediator;
//}
[HttpGet]
[Route("")]
[AllowAnonymous]
public async Task<DoHealthCheck.Result> DoHealthCheck()
{
return new DoHealthCheck.Result
{
CurrentTime = System.DateTime.Now,
Status = new DoHealthCheck.Model
{
IsHealthy = true,
Reason = "200"
}
};
//return await _mediator.Send(new DoHealthCheck.Query());
}
}
}
<file_sep>using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace PrejittedLambda.Features.HealthCheck
{
public class DoHealthCheck
{
public class Query : IRequest<Result>
{
}
public class Result
{
public DateTime CurrentTime { get; internal set; }
public Model Status { get; internal set; }
}
public class Model
{
public bool IsHealthy { get; internal set; }
public string Reason { get; internal set; } = string.Empty;
}
public class QueryHandler : IRequestHandler<Query, Result>
{
public async Task<Result> Handle(Query request, CancellationToken cancellationToken)
{
return new Result
{
CurrentTime = DateTime.Now,
Status = await RunHealthCheck(() =>
{
return Task.CompletedTask;
})
};
}
public async Task<Model> RunHealthCheck(Func<Task> healthCheck)
{
var result = new Model();
try
{
await healthCheck();
result.IsHealthy = true;
}
catch (Exception e)
{
result.IsHealthy = false;
do
{
result.Reason += e.Message;
result.Reason += Environment.NewLine;
e = e.InnerException;
} while (e != null);
}
return result;
}
}
}
}
<file_sep>namespace PrejittedLambda
{
using System.Collections.Generic;
public class AppSettings
{
public List<string> JwtValidationKeys { get; set; } = new List<string>();
}
}<file_sep>aspnet core lambda w/ a pre-jitted lambda layer<file_sep>namespace PrejittedLambda.Infrastructure
{
using Amazon.CDK;
using Amazon.CDK.AWS.APIGateway;
using PrejittedLambda.Infrastructure.Constructs;
public class MainStack : Stack
{
public class MainStackProps : StackProps
{
public string LayerArn { get; internal set; }
public string StorePath { get; internal set; }
}
public MainStack(Construct scope, string id, MainStackProps props) : base(scope, id, props)
{
var apiGatewayProxyLambdaProps = new ApiGatewayProxyLambdaProps
{
ConstructIdPrefix = "PrejittedLambda",
ApplicationId = "PrejittedLambda",
LambdaExecutionRoleName = "PrejittedLambdaRole",
LambdaFunctionHandler = "PrejittedLambda::PrejittedLambda.LambdaEntryPoint::FunctionHandlerAsync",
LambdaFunctionName = "PrejittedLambdaFunction",
LambdFunctionAssetCodePath = $"{Utilities.GetDirectory("PrejittedLambda")}\\publish.zip",
StorePath = props.StorePath,
RestApiName = $"PrejittedLambda",
AspNetEnvironment = "Production",
CorsOptions = new CorsOptions
{
AllowCredentials = true,
/// TODO: #2 Set up CORS!
AllowOrigins = new string[] { "" },
AllowMethods = Cors.ALL_METHODS
},
LayerArn = props.LayerArn
};
var apiGatewayProxyLambda = new ApiGatewayProxyLambda(this, apiGatewayProxyLambdaProps.ConstructIdPrefix, apiGatewayProxyLambdaProps);
}
}
}
<file_sep>namespace PrejittedLambda
{
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using System.Security.Cryptography;
using MediatR;
using System.Collections.Generic;
public class Startup
{
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.AddConfiguration(configuration)
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
AppSettings = new AppSettings();
Configuration.GetSection("AppSettings").Bind(AppSettings);
HostingEnvironment = env;
}
public static IConfiguration Configuration { get; private set; }
public IWebHostEnvironment HostingEnvironment { get; }
public AppSettings AppSettings { get; set; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers(config =>
{
var policy = new AuthorizationPolicyBuilder()
//.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
//.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
//var validationParameters = new TokenValidationParameters
//{
// ValidateAudience = false,
// ValidateIssuer = false,
// ValidateLifetime = true,
// IssuerSigningKeyResolver = new IssuerSigningKeyResolver((token, securityToken, kid, validationParameters) =>
// {
// var keys = new List<RsaSecurityKey>();
// foreach (var key in AppSettings.JwtValidationKeys)
// {
// var rsa = RSA.Create();
// rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(key), out _);
// keys.Add(new RsaSecurityKey(rsa));
// }
// return keys;
// })
//};
//services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
//.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opts =>
//{
// opts.TokenValidationParameters = validationParameters;
// opts.RequireHttpsMetadata = false;
//});
//services.AddMediatR()
//services.AddMediatR(GetType().Assembly);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Use(async (context, next) =>
{
context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
context.Response.Headers.Add("X-Xss-Protection", "1");
context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
context.Response.Headers.Add("Strict-Transport-Security", "max-age=31536000");
context.Response.Headers.Add("Content-Security-Policy", "default-src 'self';");
context.Response.Headers.Add("Referrer-Policy", "no-referrer");
context.Response.Headers.Add("Feature-Policy", "sync-xhr 'self'");
await next();
});
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
app.UseHttpsRedirection();
app.UseRouting();
//app.UseAuthentication();
//app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
<file_sep>namespace PrejittedLambda.Infrastructure
{
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
public class Utilities
{
/// <summary>
/// Uses Newtonsoft to deserialize json file into Dictionary<string, string>
/// </summary>
public static async Task<Dictionary<string, string>> LoadFromJsonFile(string fileName)
{
Dictionary<string, string> tags;
using (StreamReader reader = new StreamReader(fileName))
{
string json = await reader.ReadToEndAsync();
tags = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}
return tags;
}
public static string GetDirectory(string directoryName)
{
var projectRelativePath = @"";
// Get currently executing test project path
var currentDirectory = Directory.GetCurrentDirectory();
// Find the path to the target folder
var directoryInfo = new DirectoryInfo(currentDirectory);
do
{
directoryInfo = directoryInfo.Parent;
var projectDirectoryInfo = new DirectoryInfo(Path.Combine(directoryInfo.FullName, projectRelativePath));
if (projectDirectoryInfo.Exists)
{
var dropDirectoryInfo = new DirectoryInfo(Path.Combine(projectDirectoryInfo.FullName, directoryName));
if (dropDirectoryInfo.Exists)
{
return Path.Combine(projectDirectoryInfo.FullName, directoryName);
}
}
}
while (directoryInfo.Parent != null);
throw new Exception($"Drop directory could not be found {currentDirectory}.");
}
}
}
<file_sep>namespace PrejittedLambda
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using System.Threading.Tasks;
using System;
using System.IO;
using FakeItEasy;
using MediatR;
internal static class TestFixture
{
internal static readonly IConfiguration Configuration;
private static readonly IServiceScopeFactory ScopeFactory;
static TestFixture()
{
var startupAssembly = typeof(Startup).GetTypeInfo().Assembly;
var projectPath = GetProjectPath("PrejittedLambda");
var host = A.Fake<IWebHostEnvironment>();
A.CallTo(() => host.ContentRootPath).Returns(projectPath);
A.CallTo(() => host.EnvironmentName).Returns("Development");
var startup = new Startup(A.Fake<IConfiguration>(), host);
Configuration = Startup.Configuration;
var services = new ServiceCollection();
startup.ConfigureServices(services);
var provider = services.BuildServiceProvider();
ScopeFactory = provider.GetService<IServiceScopeFactory>();
}
internal static string GetProjectPath(string projectName)
{
var projectRelativePath = @"";
// Get currently executing test project path
var applicationBasePath = AppContext.BaseDirectory;
// Find the path to the target project
var directoryInfo = new DirectoryInfo(applicationBasePath);
do
{
directoryInfo = directoryInfo.Parent;
var projectDirectoryInfo = new DirectoryInfo(Path.Combine(directoryInfo.FullName, projectRelativePath));
if (projectDirectoryInfo.Exists)
{
var projectFileInfo = new FileInfo(Path.Combine(projectDirectoryInfo.FullName, projectName, $"{projectName}.csproj"));
if (projectFileInfo.Exists)
{
return Path.Combine(projectDirectoryInfo.FullName, projectName);
}
}
}
while (directoryInfo.Parent != null);
throw new Exception($"Project root could not be located using the application root {applicationBasePath}.");
}
internal static int HealthCheck()
{
try
{
if (Configuration == null || ScopeFactory == null)
{
return 0;
}
}
catch { return 0; }
return 1;
}
public static async Task ExecuteScopeAsync(Func<IServiceProvider, Task> action)
{
using (var scope = ScopeFactory.CreateScope())
{
await action(scope.ServiceProvider);
}
}
public static async Task<T> ExecuteScopeAsync<T>(Func<IServiceProvider, Task<T>> action)
{
using (var scope = ScopeFactory.CreateScope())
{
try
{
var result = await action(scope.ServiceProvider);
return result;
}
catch (Exception)
{
throw;
}
}
}
public static Task<TResponse> SendAsync<TResponse>(IRequest<TResponse> request)
{
return ExecuteScopeAsync(sp =>
{
var mediator = sp.GetService<IMediator>();
return mediator.Send(request);
});
}
public static Task SendAsync(IRequest request)
{
return ExecuteScopeAsync(sp =>
{
var mediator = sp.GetService<IMediator>();
return mediator.Send(request);
});
}
}
}
<file_sep>namespace PrejittedLambda.Infrastructure.Constructs
{
using Amazon.CDK;
using Amazon.CDK.AWS.APIGateway;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.S3;
using System.Collections.Generic;
public class ApiGatewayProxyLambdaProps
{
/// <summary>
/// The prefix to append to logical IDs of resources in this construct. This value should be unique amongst ApiGatewayProxyLambda construct instances
/// ex: "MyBackendServiceAuthApi"
/// </summary>
public string ConstructIdPrefix { get; set; }
/// <summary>
/// The unique identifier of the application or service. Used for tagging
/// ex: "MyBackendService"
/// </summary>
public string ApplicationId { get; set; }
/// <summary>
/// The name to assign to the generated IAM Role
/// ex: "MyBackendServiceAuthApiRole"
/// </summary>
public string LambdaExecutionRoleName { get; set; }
/// <summary>
/// The name to assign to the generated Lambda Function
/// ex: "MyBackendServiceAuthApiFunction"
/// </summary>
public string LambdaFunctionName { get; set; }
/// <summary>
/// The value to assign to the Handler property of the generated lambda function
/// ex: "MyBackendService.AuthApi::MyBackendService.AuthApi.LambdaEntryPoint::FunctionHandlerAsync"
/// </summary>
public string LambdaFunctionHandler { get; set; }
/// <summary>
/// The local path of the lambda deployment package
/// ex: $"{Directory.GetCurrentDirectory()}\\LambdaPackage\\MyBackendService.AuthApi.zip"
/// </summary>
public string LambdFunctionAssetCodePath { get; set; }
/// <summary>
/// The name to assign to the generated Lambda Rest Api
/// ex: MyBackendServiceAuthApiRestApi
/// </summary>
public string RestApiName { get; set; }
/// <summary>
/// The value to assign to ASPNETCORE_ENVIRONMENT environment variable on the lambda function
/// </summary>
public string AspNetEnvironment { get; set; }
/// <summary>
/// The CorsOptions to add to the ApiGateway
/// </summary>
public ICorsOptions CorsOptions { get; set; }
/// <summary>
/// The number of provisioned (warm) lambda instances in the production environment
/// </summary>
public int ProvisionedProductionInstances { get; set; } = 0;
public string LayerArn { get; set; }
public string StorePath { get; set; }
}
public class ApiGatewayProxyLambda : Construct
{
internal Role LambdaExecutionRole { get; }
internal Function LambdaFunction { get; }
internal LambdaRestApi RestApi { get; }
public ApiGatewayProxyLambda(Construct scope, string id, ApiGatewayProxyLambdaProps props) : base(scope, id)
{
Tags.Of(this).Add(nameof(props.ApplicationId), props.ApplicationId);
LambdaExecutionRole = new Role(this, "LambdaExecutionRole", new RoleProps
{
AssumedBy = new ServicePrincipal("lambda.amazonaws.com"),
RoleName = props.LambdaExecutionRoleName,
InlinePolicies = new Dictionary<string, PolicyDocument>
{
{
"cloudwatch-policy",
new PolicyDocument(
new PolicyDocumentProps {
AssignSids = true,
Statements = new [] {
new PolicyStatement(new PolicyStatementProps {
Effect = Effect.ALLOW,
Actions = new string[] {
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:CreateLogGroup"
},
Resources = new string[] {
"arn:aws:logs:*:*:*"
}
})
}
})
}
}
});
Tags.Of(LambdaExecutionRole).Add("Name", props.LambdaExecutionRoleName);
Tags.Of(LambdaExecutionRole).Add("ApplicationRole", "Lambda Excution Role");
LambdaFunction = new Function(this, "LambdaFunction", new FunctionProps
{
Code = new AssetCode(props.LambdFunctionAssetCodePath),
Handler = props.LambdaFunctionHandler,
Runtime = Runtime.DOTNET_CORE_3_1,
Timeout = Duration.Seconds(30),
FunctionName = props.LambdaFunctionName,
CurrentVersionOptions = new VersionOptions
{
ProvisionedConcurrentExecutions = props.AspNetEnvironment == "Production" ? props.ProvisionedProductionInstances : 0
},
Layers = new ILayerVersion[]
{
LayerVersion.FromLayerVersionArn(this, "Layer", "arn:aws:lambda:us-west-2:685696558467:layer:Prejit:4")
},
MemorySize = 256,
RetryAttempts = 1,
Role = LambdaExecutionRole,
Environment = new Dictionary<string, string>
{
{ "ASPNETCORE_ENVIRONMENT", props.AspNetEnvironment },
{ "DOTNET_SHARED_STORE", props.StorePath }
}
});
Tags.Of(LambdaFunction).Add("Name", props.LambdaFunctionName);
Tags.Of(LambdaFunction).Add("ApplicationRole", "Lambda Function");
RestApi = new LambdaRestApi(this, "RestApi", new LambdaRestApiProps
{
Handler = LambdaFunction,
Proxy = true,
Deploy = true,
DefaultCorsPreflightOptions = props.CorsOptions,
DeployOptions = new StageOptions
{
StageName = "v1"
},
RestApiName = props.RestApiName,
EndpointConfiguration = new EndpointConfiguration
{
Types = new EndpointType[]
{
EndpointType.REGIONAL
}
}
});
Tags.Of(RestApi).Add("Name", props.RestApiName);
Tags.Of(RestApi).Add("ApplicationRole", "API Gateway");
}
}
}
<file_sep>namespace PrejittedLambda.Infrastructure
{
using Amazon.CDK;
using System.Threading.Tasks;
sealed class Program
{
public static async Task Main(string[] args)
{
var layerArn = (await Utilities.LoadFromJsonFile("appsettings.json"))["LayerArn"];
var storePath = (await Utilities.LoadFromJsonFile("appsettings.json"))["StorePath"];
var app = new App();
var dependenciesStack = new DependenciesStack(app, "Dependencies", new StackProps
{
Env = new Environment
{
Account = app.Account,
Region = "us-west-2"
}
});
_ = new MainStack(app, "MainStack", new MainStack.MainStackProps
{
LayerArn = layerArn,
StorePath = storePath,
Env = new Environment
{
Account = app.Account,
Region = "us-west-2"
},
});
app.Synth();
}
}
}
<file_sep>namespace PrejittedLambda.Infrastructure
{
using Amazon.CDK;
using Amazon.CDK.AWS.S3;
using System;
public class DependenciesStack : Stack
{
public Bucket Bucket { get; }
public DependenciesStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
{
Bucket = new Bucket(this, "PrejittedLambda.DependenciesBucket", new BucketProps
{
BucketName = "prejittedlambdadependencies290387498273498"
});
}
}
}
<file_sep>namespace PrejittedLambda.Tests
{
using PrejittedLambda.Features.HealthCheck;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using static PrejittedLambda.TestFixture;
[TestClass]
public class HealthCheckTests
{
[TestMethod]
public async Task SmokeTest()
{
var query = new DoHealthCheck.Query();
await SendAsync(query);
}
}
}
|
714a3fb1e591dc972e1a98212cd921d0f613c44f
|
[
"Markdown",
"C#"
] | 12 |
C#
|
colinmxs/prejit-lambda
|
e29a150d04700bc509598d2ed2e6b0cdec33b584
|
6f32d58e7048dec7529e2b18c9370ccee69e70f2
|
refs/heads/master
|
<file_sep># PhoneBookApp
Codul pentru activare este "test123"!
<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 AgendaTelefon;
/**
*
* @author Razvan
*/
public class Question{
public int a;
private int b;
protected int c;
int d;
}
|
2f96a33ce25b506ee06adb5dd6cb3060423baa5d
|
[
"Markdown",
"Java"
] | 2 |
Markdown
|
zaniev/PhoneBookApp
|
de25dd78d9cf39f7fa9e4e3be967d9db48cdc504
|
dbd73fd51627407697598aba0f44a977920695b7
|
refs/heads/master
|
<repo_name>MarshallPreuss/TheTalksMockup<file_sep>/src/components/Page.js
import React from 'react'
import Nav from './Nav'
const Dashboard = () => {
return(
<div className="Parent">
<Nav />
<div className="Content">
<div className="Section">
<h2 className="InterTitle">New Interview</h2>
<div className="New">
</div>
</div>
<div className="Section">
{/* <h2 className="InterTitle"> </h2> */}
<h2 className="InterTitle">Interview Directory</h2>
<div className="Inter">
<table>
<tr>
<td>Architecture</td>
<td>Art</td>
</tr>
<tr>
<td>Fashion</td>
<td>Film</td>
</tr>
<tr>
<td>Food</td>
<td>Literature</td>
</tr>
<tr>
<td>Music</td>
<td>Sports</td>
</tr>
</table>
</div>
</div>
<div className="Section">
<h5 className="InterTitle">December 11, 2019</h5>
<div className="Para1">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Egestas
maecenas pharetra convallis posuere morbi leo. Sem fringilla
ut morbi tincidunt. Nibh sit amet commodo nulla facilisi nullam
vehicula ipsum. Scelerisque mauris pellentesque pulvinar pellentesque
habitant morbi. Est sit amet facilisis magna
etiam tempor orci eu. At volutpat diam ut venenatis.
Eu volutpat odio facilisis mauris sit amet massa.
Ultrices gravida dictum fusce ut placerat orci nulla
pellentesque dignissim. Risus in hendrerit gravida rutrum
quisque. Amet venenatis urna cursus eget nunc scelerisque.
Dui vivamus arcu felis bibendum ut tristique et egestas.
Nunc sed augue lacus viverra vitae congue eu. Ut morbi
tincidunt augue interdum velit euismod in pellentesque.
Auctor neque vitae tempus quam pellentesque nec.
Turpis egestas sed tempus urna et.</p>
</div>
</div>
<div className="Section">
<h5 className="InterTitle">Life</h5>
<div className="Life">
<div>
<h3>"I cant make people happy if I am not happy myself. That
applies to anyone who tries to achieve something in their life:
if you are not happy, you cant transfer any happiness to anyone else.""
</h3>
</div>
</div>
</div>
<div className="Section">
<h2 className="InterTitle">Most Read Interviews</h2>
<div className="Most">
<div className="Mostread1">
</div>
{/* <h4 className="Names">Alicia Keys</h4> */}
<div className="Mostread2">
</div>
{/* <h4 className="Names"><NAME></h4> */}
<div className="Mostread3">
</div>
{/* <h4 className="Names"><NAME></h4> */}
</div>
</div>
<div className="Section">
<h2 className="InterTitle">World Guide</h2>
<div className="World">
</div>
</div>
<div className="Section">
<h2 className="InterTitle">Last Weeks Interview</h2>
<div className="New2">
</div>
</div>
<div className="Section">
<h2 className="InterTitle">Editors Picks</h2>
<div className="Editor">
<div className="EditorsPick1">
</div>
<h4 className="Names">Ang Lee</h4>
<div className="EditorsPick2">
</div>
<h4 className="Names">Bjork</h4>
<div className="EditorsPick3">
</div>
<h4 className="Names">Flying Lotus</h4>
</div>
</div>
<div className="Section">
<h5 className="InterTitle">Decemeber 4th, 2019</h5>
<div className="Para2">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Egestas
maecenas pharetra convallis posuere morbi leo. Sem fringilla
ut morbi tincidunt. Nibh sit amet commodo nulla facilisi nullam
vehicula ipsum. Scelerisque mauris pellentesque pulvinar pellentesque
habitant morbi. Est sit amet facilisis magna
etiam tempor orci eu. At volutpat diam ut venenatis.
Eu volutpat odio facilisis mauris sit amet massa.
Ultrices gravida dictum fusce ut placerat orci nulla
pellentesque dignissim. Risus in hendrerit gravida rutrum
quisque. Amet venenatis urna cursus eget nunc scelerisque.
Dui vivamus arcu felis bibendum ut tristique et egestas.
Nunc sed augue lacus viverra vitae congue eu. Ut morbi
tincidunt augue interdum velit euismod in pellentesque.
Auctor neque vitae tempus quam pellentesque nec.
Turpis egestas sed tempus urna et.</p>
</div>
</div>
<div className="Section">
<h2 className="InterTitle">Fashion Photgraphers</h2>
<div className="Latest">
</div>
</div>
</div>
</div>
)
}
export default Dashboard
|
0848526d9b54049e9d44a03d55a037c9f6c9587a
|
[
"JavaScript"
] | 1 |
JavaScript
|
MarshallPreuss/TheTalksMockup
|
a34c4e61848a5dc1f0b4d41c6c951a19946b9fc7
|
14724044a225c468e9a7236d3d20663550bbf3c9
|
refs/heads/master
|
<file_sep>package com.demo.ProyectoDemo.restController;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.demo.ProyectoDemo.entity.LibroEntity;
import com.demo.ProyectoDemo.exception.LibroNotFoundException;
import com.demo.ProyectoDemo.exception.LibroUnSupportedFieldPatchException;
import com.demo.ProyectoDemo.repository.LibroRepository;
@RestController
@RequestMapping("libro/")
public class LibroRestController {
@Autowired
LibroRepository libroRepository;
@GetMapping("listarTodos")
List<LibroEntity> listarTodos(){
return libroRepository.findAll();
}
@PostMapping("crear")
@ResponseStatus(code = HttpStatus.CREATED)
LibroEntity crear(@Valid @RequestBody LibroEntity libroEntity) {
return libroRepository.save(libroEntity);
}
@GetMapping("buscar/{id}")
LibroEntity buscarById(@PathVariable @Min(1) Long id){
return libroRepository.findById(id).orElseThrow(() -> new LibroNotFoundException(id));
}
@DeleteMapping("eliminar/{id}")
@ResponseStatus(code = HttpStatus.OK)
void eliminar(@PathVariable Long id) {
libroRepository.deleteById(id);
}
@PutMapping("actualizarCrear/{id}")
LibroEntity grabarActualizar(@RequestBody LibroEntity libroEntity, @PathVariable Long id) {
return libroRepository.findById(id)
.map(
x -> {
x.setAutor(libroEntity.getAutor());
x.setClasificacion(libroEntity.getClasificacion());
x.setTitulo(libroEntity.getTitulo());
x.setPrecio(libroEntity.getPrecio());
return libroRepository.save(x);
}
)
.orElseGet(
() -> {
return libroRepository.save(libroEntity);
}
);
}
@PatchMapping("actualizar/{id}")
LibroEntity actualizarPatch(@RequestBody Map<String, String> parametro, @PathVariable Long id) {
return libroRepository.findById(id)
.map(
x -> {
String autor = parametro.get("autor");
if(!StringUtils.isEmpty(autor)) {
x.setAutor(autor);
return libroRepository.save(x);
} else {
throw new LibroUnSupportedFieldPatchException(parametro.keySet());
}
}
)
.orElseGet(
() -> {
throw new LibroNotFoundException(id);
}
);
}
}<file_sep>package com.demo.ProyectoDemo.validator;
import java.util.Arrays;
import java.util.List;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class ClasificacionValidator implements ConstraintValidator<Clasificacion, String>{
List<String> clasificacionAceptada = Arrays.asList("TIPO A", "TIPO B");
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return clasificacionAceptada.contains(value);
}
}
<file_sep>package com.demo.ProyectoDemo.exception;
import java.util.Set;
@SuppressWarnings("serial")
public class LibroUnSupportedFieldPatchException extends RuntimeException{
public LibroUnSupportedFieldPatchException(Set<String> keys) {
super("Campo "+keys.toString()+" no esta permitido");
}
}
|
8bdad89c6431530ae927ccaa39678a982d256aea
|
[
"Java"
] | 3 |
Java
|
MiguelEspinozaMedina/java-spring-boot-201910
|
b64c671d10e1ba17f5b83dfc9be3ec6db8cb82f9
|
f2cf53618be50cb3bd4c79e34f60b0464287fc9f
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="viewproductStyle.css">
</head>
<body>
<div class="header">
<h1>xCompany</h1>
<div class="topnav">
<a href="registration.php">Registration</a>
<a href="login.php">Log In</a>
<a href="home_.php">Home</a>
<a href="viewproduct.php">View Product</a>
</div>
</div>
<div><h2>View Product</h2></div>
<?php
echo "<h3>All Products:</h3>";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM MyProducts";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ProductID</th><th>ProductName</th><th>Quantity</th><th>Action</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["pid"]."</td><td>".$row["name"]."</td><td>".$row["quantity"]."</td><td>"."<a href='productdetails.php?pid=".$row['pid']."'>View</a>"."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
<div class="footer">Copyright:2017</div>
</body>
</html><file_sep><?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="editprofileStyle.css">
</head>
<body>
<div class="header">
<h1>xCompany</h1>
<div align="right">Logged in as <?php echo $_SESSION["name"]; ?>
</div>
<div class="topnav">
<a href="home_.php">Log Out</a>
</div>
</div>
<div class="container">
<div class="column1">
<div class="subhead">
Account
</div>
<div class="sidenav">
<a href="dashboard.php">Dashboard</a>
<a href="viewprofile.php">View Profile</a>
<a href="editprofile.php">Edit Profile</a>
<a href="changeprofilepicture.php">Change Profile Picture</a>
<a href="changepassword.php">Change Password</a>
<a href="home_.php">Log Out</a>
</div>
<div class="subhead">
Product
</div>
<div class="sidenav">
<a href="viewproductloggedin.php">View Product</a>
</div>
</div>
<div class="column2">
<div><h2>View Product</h2></div>
<?php
echo "<h3>All Products:</h3>";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM MyProducts";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ProductID</th><th>ProductName</th><th>Quantity</th><th>Action</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["pid"]."</td><td>".$row["name"]."</td><td>".$row["quantity"]."</td>"."<td>"."<a href='productdetailslogged.php?pid=".$row['pid']."'>View</a>"."/"."<a href='editproduct.php?pid=".$row['pid']."'>Edit</a>"."/"."<a href='deleteproduct.php?pid=".$row['pid']."'>Delete</a>"."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</div>
</div>
<div class="footer">Copyright:2017</div>
</body>
</html>
|
1c45e4a7b57deefa02bc5c2dece153e5df87b2f7
|
[
"PHP"
] | 2 |
PHP
|
theZeuses/WebTech-Lab9-xCompany-Products
|
53afe3e98cf1a042505966aa571ac36d37bb57df
|
e26002ac669df03841b2c01ccbd06a7debb52420
|
refs/heads/master
|
<file_sep>###########################
# 6.00.2x Problem Set 1: Space Cows
from ps1_partition import get_partitions
import time
#================================
# Part A: Transporting Space Cows
#================================
def load_cows(filename):
"""
Read the contents of the given file. Assumes the file contents contain
data in the form of comma-separated cow name, weight pairs, and return a
dictionary containing cow names as keys and corresponding weights as values.
Parameters:
filename - the name of the data file as a string
Returns:
a dictionary of cow name (string), weight (int) pairs
"""
cow_dict = dict()
f = open(filename, 'r')
for line in f:
line_data = line.split(',')
cow_dict[line_data[0]] = int(line_data[1])
return cow_dict
# Problem 1
def greedy_cow_transport(cows,limit=10):
"""
Uses a greedy heuristic to determine an allocation of cows that attempts to
minimize the number of spaceship trips needed to transport all the cows. The
returned allocation of cows may or may not be optimal.
The greedy heuristic should follow the following method:
1. As long as the current trip can fit another cow, add the largest cow that will fit
to the trip
2. Once the trip is full, begin a new trip to transport the remaining cows
Does not mutate the given dictionary of cows.
Parameters:
cows - a dictionary of name (string), weight (int) pairs
limit - weight limit of the spaceship (an int)
Returns:
A list of lists, with each inner list containing the names of cows
transported on a particular trip and the overall list containing all the
trips
"""
trips = []
# Transform the dictionary to sorted list
cow_list = [[k, cows[k]] for k in sorted(cows, key=cows.get, reverse=True)]
while len(cow_list) > 0:
totalWeight = 0
temp = []
temp_list = cow_list.copy()
for cow in temp_list:
if totalWeight + cow[1] <= limit:
temp.append(cow[0])
cow_list.remove(cow)
totalWeight += cow[1]
trips.append(temp)
return trips
# Problem 2
# Helper to calculate weight of trip
def calc_weight(lst, dic):
total_weight = 0
for i in lst:
total_weight += dic[i]
return total_weight
def brute_force_cow_transport(cows,limit=10):
"""
Finds the allocation of cows that minimizes the number of spaceship trips
via brute force. The brute force algorithm should follow the following method:
1. Enumerate all possible ways that the cows can be divided into separate trips
2. Select the allocation that minimizes the number of trips without making any trip
that does not obey the weight limitation
Does not mutate the given dictionary of cows.
Parameters:
cows - a dictionary of name (string), weight (int) pairs
limit - weight limit of the spaceship (an int)
Returns:
A list of lists, with each inner list containing the names of cows
transported on a particular trip and the overall list containing all the
trips
"""
# Transform the dictionary to sorted list
cow_list = [k for k in cows]
list_of_combos = []
for partition in get_partitions(cow_list):
list_of_combos.append(partition)
list_of_combos.sort(key=len)
for combo in list_of_combos:
greater = 0
for i in range(len(combo)):
weight = calc_weight(combo[i], cows)
if weight > limit:
greater += 1
if greater == 0:
return combo
# Problem 3
def compare_cow_transport_algorithms():
"""
Using the data from ps1_cow_data.txt and the specified weight limit, run your
greedy_cow_transport and brute_force_cow_transport functions here. Use the
default weight limits of 10 for both greedy_cow_transport and
brute_force_cow_transport.
Print out the number of trips returned by each method, and how long each
method takes to run in seconds.
Returns:
Does not return anything.
"""
cows = load_cows("ps1_cow_data.txt")
limit=10
#print(cows)
start1 = time.time()
greedy = greedy_cow_transport(cows, limit)
end1 = time.time()
print('Greedy trips: ', len(greedy),'Greedy time:', end1 - start1)
start2 = time.time()
brute = brute_force_cow_transport(cows, limit)
end2 = time.time()
print('Brute trips: ', len(brute), 'Brute time:', end2 - start2)
"""
Here is some test data for you to see the results of your algorithms with.
Do not submit this along with any of your answers. Uncomment the last two
lines to print the result of your problem.
"""
#cows = load_cows("ps1_cow_data.txt")
#limit=10
#print(cows)
#greedy_cow_transport(cows, limit)
#brute_force_cow_transport(cows, limit)
#print(brute_force_cow_transport({'Milkshake': 40, 'Miss Bella': 25, 'Lotus': 40, 'Horns': 25, 'Boo': 20, 'MooMoo': 50}, 100))
compare_cow_transport_algorithms()<file_sep># edx_intro_to_computational_thinking_and_data_science_mit
## Completed programming assignments for Introduction to Computational Thinking and Data Science from MIT on edX.
**Assignment 1:** Solving a knapsack problem.<br>
**Assignment 2:** Simulating a roomba.<br>
**Assignment 3:** Simulating a virus.<br>
**Assignment 4:** Analyzing temperature data to answer a question on global warming.
|
66dffc71d35f16b15618be27fde50213dfc3ae7e
|
[
"Markdown",
"Python"
] | 2 |
Python
|
kfleming123/edx_intro_to_computational_thinking_and_data_science_mit
|
fdd83c5540b5ef8a5f5d124e629f7235d562b1df
|
af4e8ead5a32c6b1c254724a071a73157dfee5a1
|
refs/heads/master
|
<file_sep>#include "dialogset.h"
#include "ui_dialogset.h"
#include "setting.h"
DialogSet::DialogSet(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogSet)
{
ui->setupUi(this);
//加载qss
QFile file(":/qss/JobInfo.qss");
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << file.errorString() << __FILE__ << __LINE__;
} else {
setStyleSheet(file.readAll());
}
file.close();
setAttribute(Qt::WA_DeleteOnClose);
setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint);
setFixedSize(size());
m_appPath = QApplication::applicationFilePath();
m_settingPath = QApplication::applicationDirPath() + "/JobInfo/setting.ini";
readSettings();
ui->btnOK->setDefault(true);
m_intValid.setBottom(1);
ui->lineEditAheadDays->setValidator(&m_intValid);
ui->lineEditIntervalHours->setValidator(&m_intValid);
ui->lineEditRecordDays->setValidator(&m_intValid);
}
DialogSet::~DialogSet()
{
delete ui;
}
void DialogSet::readSettings()
{
#if defined(Q_WS_WIN)
QSettings settingAutoRun("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\"
"CurrentVersion\\Run\\", QSettings::NativeFormat);
if (settingAutoRun.value("JobInfo", QString("rem \"%1\"").arg(m_appPath)).toString()
== QString("\"%1\"").arg(m_appPath)) {
ui->checkBoxAutoRun->setChecked(true);
} else {
ui->checkBoxAutoRun->setChecked(false);
}
#endif
// QSettings setting(m_settingPath, QSettings::IniFormat);
ui->checkBoxStartMin->setChecked(g_setting->getIsStartMin());
ui->checkBoxCloseMin->setChecked(g_setting->getIsCloseMin());
ui->lineEditRecordDays->setText(QString::number(g_setting->getRecordDays()));
ui->lineEditAheadDays->setText(QString::number(g_setting->getAheadDays()));
ui->lineEditIntervalHours->setText(QString::number(g_setting->getIntervalHours()));
}
bool DialogSet::writeSettings()
{
#if defined(Q_WS_WIN)
QSettings settingAutoRun("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\"
"CurrentVersion\\Run\\", QSettings::NativeFormat);
if (ui->checkBoxAutoRun->checkState() == Qt::Checked) {
settingAutoRun.setValue("JobInfo", QString("\"%1\"").arg(m_appPath));
} else {
settingAutoRun.setValue("JobInfo", QString("rem \"%1\"").arg(m_appPath));
}
#endif
QSettings setting(m_settingPath, QSettings::IniFormat);
setting.clear();
setting.setValue("startmin", ui->checkBoxStartMin->checkState()==Qt::Checked ? true : false);
setting.setValue("closemin", ui->checkBoxCloseMin->checkState()==Qt::Checked ? true : false);
setting.setValue("recorddays", ui->lineEditRecordDays->text());
setting.setValue("aheaddays", ui->lineEditAheadDays->text());
setting.setValue("intervalhours", ui->lineEditIntervalHours->text());
return true;
}
void DialogSet::on_btnOK_clicked()
{
if (ui->lineEditAheadDays->text().toInt()<=0
|| ui->lineEditIntervalHours->text().toInt()<=0
|| ui->lineEditRecordDays->text().toInt()<=0) {
QMessageBox::information(this, "信息", "提前天数或间隔小时或记录天数都要大于0");
return;
}
#if defined(Q_WS_WIN)
QSettings settingAutoRun("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\"
"CurrentVersion\\Run\\", QSettings::NativeFormat);
if (ui->checkBoxAutoRun->checkState() == Qt::Checked) {
settingAutoRun.setValue("JobInfo", QString("\"%1\"").arg(m_appPath));
} else {
settingAutoRun.setValue("JobInfo", QString("rem \"%1\"").arg(m_appPath));
}
#endif
QSettings setting(m_settingPath, QSettings::IniFormat);
setting.setValue("startmin", ui->checkBoxStartMin->checkState()==Qt::Checked ? true : false);
setting.setValue("closemin", ui->checkBoxCloseMin->checkState()==Qt::Checked ? true : false);
setting.setValue("recorddays", ui->lineEditRecordDays->text());
setting.setValue("aheaddays", ui->lineEditAheadDays->text());
setting.setValue("intervalhours", ui->lineEditIntervalHours->text());
g_setting->updateSetting();
close();
}
void DialogSet::on_btnCancel_clicked()
{
close();
}
<file_sep>#ifndef CUSTOMTHREAD_H
#define CUSTOMTHREAD_H
#include <QThread>
#include <Qtcore>
#include <QtWebKit>
class CustomThread : public QThread
{
Q_OBJECT
public:
explicit CustomThread(QObject *parent = 0);
CustomThread(QObject *parent = 0, QMap<QDate, QString> fairDateMap = QMap<QDate, QString>());
void setFairDateMap(QMap<QDate, QString> fairDateMap);
private:
QMap<QDate, QString> m_fairDateMap;
QWebPage *m_pWebPage;
QDate m_fairMonth;
QTime m_fairTime;
QString m_fairTitle;
QString m_fairHref;
QString m_fairSite;
bool m_isLoading;
void examineChildElements(const QWebElement &parentElement);
protected:
void run();
signals:
private slots:
void slotRender();
void slotRenderHome();
};
#endif // CUSTOMTHREAD_H
<file_sep>#include "customthread.h"
CustomThread::CustomThread(QObject *parent) :
QThread(parent)
{
}
CustomThread::CustomThread(QObject *parent, QMap<QDate, QString> fairDateMap) :
QThread(parent), m_fairDateMap(fairDateMap)
{
m_isLoading = false;
m_pWebPage = new QWebPage();
connect(m_pWebPage, SIGNAL(loadFinished(bool)), this, SLOT(slotRender()));
QMap<QDate, QString>::iterator iter;
for (iter = m_fairDateMap.begin(); iter != m_fairDateMap.end(); iter++) {
qDebug() << iter.key() << ":" << iter.value() << __FILE__ << __LINE__;
while (m_isLoading) {
sleep(10);
}
m_pWebPage->mainFrame()->load(QUrl(iter.value()));
m_isLoading = true;
}
}
void CustomThread::run()
{
}
void CustomThread::setFairDateMap(QMap<QDate, QString> fairDateMap)
{
m_fairDateMap = fairDateMap;
}
void CustomThread::slotRenderHome()
{
QWebElement document = m_pWebPage->mainFrame()->documentElement();
QString htmlStr = m_pWebPage->mainFrame()->toHtml();
QRegExp regExpMonth("(\\d{4})年(\\d{1,2})月");
int index = regExpMonth.indexIn(htmlStr);
if (index != -1) {
m_fairMonth = QDate(regExpMonth.cap(1).toInt(), regExpMonth.cap(2).toInt(), 1);
} else {
qDebug() << "m_fairMonth is not initialized" << __FILE__ << __LINE__;
}
examineChildElements(document);
qDebug() << m_fairDateMap << __FILE__ << __LINE__;
m_isLoading = false;
}
void CustomThread::slotRender()
{
QWebElement document = m_pWebPage->mainFrame()->documentElement();
qDebug() << document.toOuterXml() << __FILE__ << __LINE__;
QWebElementCollection paraCollection = document.findAll("p.MsoNormal");
QString paraHtmlStr;
QRegExp regExpTime("(\\d{1,2}):(\\d\\d)"); //时间正则表达式
QRegExp regExpSite(">(\\w+)<"); //地点正则表达式
foreach(QWebElement paragraph, paraCollection) {
int index;
paraHtmlStr = paragraph.toOuterXml();
index = regExpTime.indexIn(paraHtmlStr);
if (index != -1 && !paraHtmlStr.contains("title", Qt::CaseInsensitive)) { //有可能title里有时间,所以不能包含title
//获得招聘会的时间
m_fairTime.setHMS(regExpTime.cap(1).toInt(), regExpTime.cap(2).toInt(), 0);
} else if (paraHtmlStr.contains("href=", Qt::CaseInsensitive)) {
QWebElementCollection linkCollection = paragraph.findAll("a");
//可能会有多个链接,所以取有标题的链接
foreach(QWebElement link, linkCollection) {
//获得链接地址
QStringList attrList = link.attributeNames();
foreach(QString attr, attrList) {
if (QString::compare(attr, "href", Qt::CaseInsensitive) == 0) {
m_fairHref = link.attribute(attr);
break;
}
}
//获得链接标题
m_fairTitle = link.findFirst("u").toInnerXml();
if (m_fairTitle.isEmpty()) {
m_fairTitle = link.toInnerXml();
}
if (!m_fairTitle.isEmpty()) {
break;
} else {
// qDebug() << link.toOuterXml() << __FILE__ << __LINE__;
}
}
} else {
//获取招聘会的地点
if (m_fairHref.isEmpty() || m_fairTitle.isEmpty()) {
continue;
} else {
// index = 0;
// while ((index = regExpSite.indexIn(paraHtmlStr, index)) != -1) {
// m_fairSite += regExpSite.cap(1);
// index += regExpSite.matchedLength();
// }
QWebElementCollection spanCollection = paragraph.findAll("span");
foreach(QWebElement span, spanCollection) {
// m_fairSite += span.toInnerXml();
if (!m_fairSite.contains(span.toPlainText())) {
m_fairSite += span.toPlainText();
}
}
qDebug() << m_fairTime << m_fairTitle << m_fairHref << m_fairSite << __FILE__ << __LINE__;
//清空
m_fairHref.clear();
m_fairSite.clear();
m_fairSite.clear();
}
}
}
m_isLoading = false;
}
void CustomThread::examineChildElements(const QWebElement &parentElement)
{
QWebElement element = parentElement.firstChild();
QRegExp regExp("\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}");
QString newsTitle;
QString newsTime;
QString newsHref;
QString title;
QStringList attrList;
while (!element.isNull()) {
attrList = element.attributeNames();
foreach(QString attr, attrList) {
if (QString::compare(attr, "title", Qt::CaseInsensitive) == 0) {
title = element.attribute(attr);
} else if (QString::compare(attr, "href", Qt::CaseInsensitive) == 0) {
newsHref = element.attribute(attr);
}
}
int pos = regExp.indexIn(title);
if (pos != -1) {
QString time;
QStringList dateTimeList;
QStringList dateList;
QStringList timeList;
time = title.mid(pos, regExp.matchedLength());
dateTimeList = time.split(" ");
dateList = dateTimeList.at(0).split("-");
timeList = dateTimeList.at(1).split(":");
newsTime.sprintf("%d-%02d-%02d %02d:%02d:%02d",
dateList.at(0).toInt(), dateList.at(1).toInt(), dateList.at(2).toInt(),
timeList.at(0).toInt(), timeList.at(1).toInt(), timeList.at(2).toInt());
}
if (!title.isEmpty()) {
if (title.left(3) == "点击数") {
newsTitle = element.toInnerXml().trimmed();
} else {
pos = title.indexOf("点击数");
if (pos != -1) {
newsTitle = title.left(pos).trimmed();
}
}
} else if (!newsHref.isEmpty() && newsHref.contains("招聘会日历2", Qt::CaseInsensitive)) {
//提取招聘会日历信息,保存至map
newsTitle = element.toInnerXml().trimmed();
if (newsTitle.contains("<")) {
QRegExp regExpDay(">(\\d+)<");
QDate fairDate;
int index;
int day;
int daysInterval;
index = regExpDay.indexIn(newsTitle);
if (index != -1) {
day = regExpDay.cap(1).toInt();
}
newsTitle.clear();
fairDate = QDate(m_fairMonth.year(), m_fairMonth.month(), day);
daysInterval = QDate::currentDate().daysTo(fairDate);
//保存招聘会日历未来一周的链接地址
if (daysInterval >= 0 && daysInterval <= 7) {
m_fairDateMap.insert(fairDate, newsHref);
}
if (day == m_fairMonth.daysInMonth()) {
m_fairMonth = m_fairMonth.addMonths(1);
}
}
}
// if (!newsTitle.isEmpty()) {
// qDebug() << newsTime << newsTitle << newsHref << __FILE__ << __LINE__;
// }
// if (!newsTime.isEmpty()) {
// QDateTime dateTime = QDateTime::fromString(newsTime, "yyyy-MM-dd hh:mm:ss");
// if (dateTime > m_lastCheckTime) {
// int row = ui->tableWidget->rowCount();
// ui->tableWidget->insertRow(row);
// ui->tableWidget->setItem(row, 0, new QTableWidgetItem(newsTime));
// ui->tableWidget->setItem(row, 1, new QTableWidgetItem(newsTitle));
// ui->tableWidget->setItem(row, 2, new QTableWidgetItem("详细"));
// ui->tableWidget->item(row, 2)->setData(Qt::UserRole, m_webPage.mainFrame()->url().toString() + newsHref);
// }
// }
examineChildElements(element);
element = element.nextSibling();
}
}
<file_sep>#ifndef DIALOGSET_H
#define DIALOGSET_H
#include <QDialog>
#include "config.h"
namespace Ui {
class DialogSet;
}
class DialogSet : public QDialog
{
Q_OBJECT
public:
explicit DialogSet(QWidget *parent = 0);
~DialogSet();
private slots:
void on_btnOK_clicked();
void on_btnCancel_clicked();
private:
Ui::DialogSet *ui;
QString m_appPath;
QString m_settingPath;
QIntValidator m_intValid;
void readSettings();
bool writeSettings();
};
#endif // DIALOGSET_H
<file_sep>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialogremind.h"
#include "dialogset.h"
#include "setting.h"
enum TableJobFairRemind {
TableJobFairRemind_Id,
TableJobFairRemind_Time,
TableJobFairRemind_Title,
TableJobFairRemind_Note
};
enum TableJobInfo {
TableJobInfo_Id,
TableJobInfo_Time,
TableJobInfo_Title,
TableJobInfo_View
};
enum TableJobFair {
TableJobFair_Id,
TableJobFair_Time,
TableJobFair_Title,
TableJobFair_View
};
const QString cons_jobinfo_id = "classId=020601";
const QString cons_jobfair_id = "classId=020604";
const QString cons_jobinfo_str = "JobInfo";
const QString cons_jobfair_str = "JobFair";
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
m_dJobFairRemind(NULL),
m_dRemind(NULL),
m_currentPage(1),
m_hasNewJobInfo(false),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
qApp->installTranslator(&m_tr);
m_tr.load(":/other/qt_zh_CN.qm");
initWidget();
createDatabase();
processOldJobInfo();
connect(g_setting, SIGNAL(signSettingChanged(bool,bool,bool)),
this, SLOT(slotProcessSettingChanged(bool, bool, bool)));
connect(&m_downloadManager, SIGNAL(finished(QMap<QUrl,QString>)),
this, SLOT(slotRenderGraduate(QMap<QUrl,QString>)));
m_timer.setInterval(g_setting->getIntervalHours() * 60 * 60 * 1000);
// m_timer.setInterval(3 * 1000);
connect(&m_timer, SIGNAL(timeout()), this, SLOT(slotAutoCheck()));
m_timer.start();
slotAutoCheck();
slotUpdateJobInfo();
slotUpdateJobFair();
slotUpdateJobFairRemind();
//没有新的招聘信息,则提醒招聘会
if (m_dRemind == NULL) {
slotReminder(false);
}
if (g_setting->getIsStartMin()) {
hide();
} else {
show();
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::showEvent(QShowEvent *se)
{
QMainWindow::showEvent(se);
updateTableJobInfoWidth();
}
void MainWindow::resizeEvent(QResizeEvent *re)
{
QMainWindow::resizeEvent(re);
updateTableJobInfoWidth();
}
void MainWindow::closeEvent(QCloseEvent *ce)
{
if (!g_setting->getIsCloseMin()) {
if (QMessageBox::Yes == QMessageBox::information(
this, "信息", "确定要退出?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No)) {
QApplication::quit();
}
} else {
QMainWindow::closeEvent(ce);
}
}
//重写设置可见
void MainWindow::setVisible(bool visible)
{
m_minAction->setVisible(visible); //主窗口可见时,最小化有效
m_restoreAction->setVisible(!visible); //主窗口不可见时,还原有效
QMainWindow::setVisible(visible); //调用基类函数
}
void MainWindow::updateTableJobInfoWidth()
{
int width;
if (ui->tabWidget->currentWidget()==ui->tabJobInfo) {
width = ui->tableWidgetJobInfo->width();
} else {
width = ui->tableWidgetJobFair->width();
}
int timeW = 130;
int viewW = 60;
int verticalWidth = 60;
ui->tableWidgetJobInfo->setColumnWidth(TableJobInfo_Time, timeW);
ui->tableWidgetJobInfo->setColumnWidth(TableJobInfo_View, viewW);
ui->tableWidgetJobInfo->setColumnWidth(TableJobInfo_Title, width - timeW - viewW - verticalWidth);
ui->tableWidgetJobFair->setColumnWidth(TableJobFair_Time, timeW);
ui->tableWidgetJobFair->setColumnWidth(TableJobFair_View, viewW);
ui->tableWidgetJobFair->setColumnWidth(TableJobFair_Title, width - timeW - viewW - verticalWidth);
}
void MainWindow::initWidget()
{
//加载qss
QFile file(":/qss/JobInfo.qss");
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << file.errorString() << __FILE__ << __LINE__;
} else {
setStyleSheet(file.readAll());
}
file.close();
QApplication::setQuitOnLastWindowClosed(false);
m_minAction = new QAction("最小化", this);
connect(m_minAction,SIGNAL(triggered()), this, SLOT(hide()));
m_restoreAction = new QAction("还原", this);
connect(m_restoreAction,SIGNAL(triggered()), this, SLOT(slotOpen()));
m_quitAction = new QAction("退出", this);
connect(m_quitAction,SIGNAL(triggered()),qApp,SLOT(quit()));
//创建托盘图标菜单并添加动作
trayIconMenu = new QMenu(QApplication::desktop());
trayIconMenu->addAction(m_restoreAction);
trayIconMenu->addAction(m_minAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(ui->actionUpdate);
trayIconMenu->addAction(ui->actionSet);
trayIconMenu->addSeparator();
trayIconMenu->addAction(m_quitAction);
//创建并设置托盘图标
trayIcon = new QSystemTrayIcon(this);
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(slotTrayIconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon->setToolTip("招聘提醒");
trayIcon->setContextMenu(trayIconMenu);
trayIcon->setIcon(QIcon(":/pic/tray.png"));
trayIcon->show();
QStringList jobInfoHeaderLabels;
QStringList jobFairHeaderLabels;
QStringList jobFairRemindHeaderLabels;
jobInfoHeaderLabels << "编号" << "发布时间" << "名称" << "查看";
ui->tableWidgetJobInfo->setColumnCount(jobInfoHeaderLabels.count());
ui->tableWidgetJobInfo->setHorizontalHeaderLabels(jobInfoHeaderLabels);
ui->tableWidgetJobInfo->setSortingEnabled(true);
ui->tableWidgetJobInfo->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableWidgetJobInfo->hideColumn(TableJobInfo_Id);
ui->tableWidgetJobInfo->horizontalHeader()->setSortIndicator(TableJobInfo_Id, Qt::DescendingOrder);
jobFairHeaderLabels << "编号" << "宣讲时间" << "名称" << "查看";
ui->tableWidgetJobFair->setColumnCount(jobFairHeaderLabels.count());
ui->tableWidgetJobFair->setHorizontalHeaderLabels(jobFairHeaderLabels);
ui->tableWidgetJobFair->setSortingEnabled(true);
ui->tableWidgetJobFair->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableWidgetJobFair->hideColumn(TableJobInfo_Id);
ui->tableWidgetJobFair->horizontalHeader()->setSortIndicator(TableJobFair_Id, Qt::DescendingOrder);
jobFairRemindHeaderLabels << "编号" << "时间" << "招聘会" << "备注";
ui->tableWidgetJobFairRemind->setColumnCount(jobFairRemindHeaderLabels.count());
ui->tableWidgetJobFairRemind->setHorizontalHeaderLabels(jobFairRemindHeaderLabels);
ui->tableWidgetJobFairRemind->setSortingEnabled(true);
ui->tableWidgetJobFairRemind->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableWidgetJobFairRemind->setSelectionMode(QAbstractItemView::ExtendedSelection);
ui->tableWidgetJobFairRemind->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableWidgetJobFairRemind->hideColumn(TableJobFairRemind_Id);
ui->tabWidget->setCurrentWidget(ui->tabJobInfo);
QSplitter *splitter = new QSplitter(Qt::Vertical, this);
splitter->addWidget(ui->tabWidget);
splitter->addWidget(ui->groupBoxJobFairRemind);
ui->widget->layout()->addWidget(splitter);
//窗口居中
QRect screenRect;
QPoint pos;
screenRect = QApplication::desktop()->availableGeometry();
pos = QPoint((screenRect.width() - frameSize().width()) / 2,
(screenRect.height() - frameSize().height()) / 2);
move(pos);
}
void MainWindow::slotTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch (reason) {
case QSystemTrayIcon::Trigger:
slotOpen();
break;
default:
break;
}
}
void MainWindow::slotOpen()
{
activateWindow();
showNormal();
}
void MainWindow::slotAutoCheck()
{
qDebug() << "auto check" << __FILE__ << __LINE__;
m_mainUrl = "http://graduate.cqu.edu.cn/fourthIndex.do?classId=020601";
m_downloadManager.append(QUrl(m_mainUrl));
m_downloadManager.append(QUrl("http://graduate.cqu.edu.cn/fourthIndex.do?classId=020604"));
}
void MainWindow::slotProcessSettingChanged(bool isRecordChanged, bool isAheadChanged, bool isIntervalChanged)
{
if (isRecordChanged) {
openDatabase();
QSqlQueryModel queryModel;
//清空招聘信息,重新更新
queryModel.setQuery("delete from JobInfo");
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
slotUpdateJobInfo();
slotUpdateJobFair();
m_lastId = 0;
m_timer.start();
slotAutoCheck();
} else if (isIntervalChanged) {
m_timer.setInterval(g_setting->getIntervalHours() * 60 * 60 * 1000);
m_timer.start();
slotAutoCheck();
}
}
bool MainWindow::openDatabase()
{
QString name = QSqlDatabase::database().connectionName();
QSqlDatabase::removeDatabase(name);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
QString fileName(QApplication::applicationDirPath() + "/JobInfo/JobInfo.db");
QFileInfo fileInfo(fileName);
QDir dir(fileInfo.absoluteDir());
if (!dir.exists()) {
dir.mkpath(dir.absolutePath());
}
db.setDatabaseName(fileName);
if (!db.open()) {
QMessageBox::information(this, "信息", db.lastError().text());
return false;
}
return true;
}
void MainWindow::createDatabase()
{
openDatabase();
QString sql;
QSqlQueryModel queryModel;
sql = QString("create table if not exists JobFairRemind("
"Id integer primary key autoincrement,"
"Title varchar,"
"Time date,"
"Note varchar)");
queryModel.setQuery(sql);
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
sql = QString("create table if not exists JobInfo("
"Id integer primary key not null,"
"Title varchar,"
"Addr varchar,"
"Time date,"
"IsRead bool default(0),"
"Type varchar)");
queryModel.setQuery(sql);
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
}
void MainWindow::processOldJobInfo()
{
openDatabase();
QString sql;
QSqlQueryModel queryModel;
sql = QString("select * from JobInfo order by Id desc");
queryModel.setQuery(sql);
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
//初始化最新id
if (queryModel.rowCount() > 0) {
m_lastId = queryModel.record(0).value(JobInfo_Id).toLongLong();
} else {
m_lastId = 0;
}
//清空旧信息
sql = QString("delete from JobInfo where Time<='%1'")
.arg(QDate::currentDate().addDays(0-g_setting->getRecordDays()).toString("yyyy-MM-dd"));
queryModel.setQuery(sql);
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
}
void MainWindow::slotRenderGraduate(const QMap<QUrl, QString> &downloadList)
{
// bool hasNewJobInfo = false;
QDateTime oldestJobInfoTime;
QDateTime oldestJobFairTime;
bool hasMoreJobInfo = true;
// bool hasMoreJobFair = oldestJobFairTime >= QDateTime::currentDateTime().addDays(0-g_setting->getRecordDays());
bool hasMoreJobFair = true;
qDebug() << "render graduate" << "count" << downloadList.count() << __FILE__ << __LINE__;
for (QMap<QUrl, QString>::const_iterator iter = downloadList.begin(); iter != downloadList.end(); iter++) {
QUrl url = iter.key();
m_webPage.mainFrame()->setHtml(iter.value());
QWebElement document = m_webPage.mainFrame()->documentElement();
QWebElementCollection links = document.findAll("li");
QRegExp timeExp("(\\d{4}-\\d{2}-\\d{2})");
QRegExp fairTimeExp("(\\d{4}.\\d{2}.\\d{2}-\\d{2}:\\d{2})");
QString curTypeStr;
// QDate oldestDate;
// int index = timeExp.indexIn(links.last().toPlainText());
// if (index != -1) {
// oldestDate = QDate::fromString(timeExp.cap(1), "yyyy-MM-dd"); //待修改
// } else {
// qDebug() << "this is a bug" << __FILE__ << __LINE__;
// }
if (url.toString().contains(cons_jobinfo_id)) {
curTypeStr = cons_jobinfo_str;
//// oldestJobInfoDate = oldestDate;
// index = timeExp.indexIn(links.last().toPlainText());
// if (index != -1) {
// oldestJobInfoDate = QDate::fromString(timeExp.cap(1), "yyyy-MM-dd");
// } else {
// qDebug() << "this is a bug" << __FILE__ << __LINE__;
// }
// qDebug() << "jobinfo date" << oldestJobInfoDate << __FILE__ << __LINE__;
} else {
curTypeStr = cons_jobfair_str;
//// oldestJobFairDate = oldestDate;
// index = fairTimeExp.indexIn(links.last().toPlainText());
// if (index != -1) {
// oldestJobFairDate = QDate::fromString(fairTimeExp.cap(1), "yyyy.MM.dd");
// } else {
// qDebug() << "this is a bug" << __FILE__ << __LINE__;
// }
// qDebug() << "oldestJobFairDate" << oldestJobFairDate << __FILE__ << __LINE__;
}
foreach(QWebElement link, links) {
QWebElementCollection addrs = link.findAll("a");
if (addrs.count() > 1) {
qDebug() << "addrs is more than one" << __FILE__ << __LINE__;
}
QWebElement addr = addrs.at(0);
QStringList attrs = addr.attributeNames();
QString href;
QString title = addr.toPlainText();
QRegExp idExp("newsinfoid=(\\d+)");
QDateTime time;
long long id;
int index;
if (curTypeStr == cons_jobinfo_str) {
index = timeExp.indexIn(link.toPlainText());
if (index != -1) {
time = QDateTime::fromString(timeExp.cap(1), "yyyy-MM-dd");
if (oldestJobInfoTime.isNull() || oldestJobInfoTime > time) {
oldestJobInfoTime = time;
}
}
} else {
index = fairTimeExp.indexIn(link.toPlainText());
if (index != -1) {
time = QDateTime::fromString(fairTimeExp.cap(1), "yyyy.MM.dd-hh:mm");
if (oldestJobFairTime.isNull() || oldestJobFairTime > time) {
oldestJobFairTime = time;
}
title = title.remove(fairTimeExp);
}
}
//链接地址
foreach(QString attr, attrs) {
if (QString::compare(attr, "href", Qt::CaseInsensitive) == 0) {
href = "http://graduate.cqu.edu.cn/" + addr.attribute(attr);
break;
}
}
int idIndex = idExp.indexIn(href);
if (idIndex == -1) {
continue;
} else {
id = idExp.cap(1).toLongLong();
}
qDebug() << "id:" << id << "title:" << title << "time" << time << __FILE__ << __LINE__;
if (curTypeStr==cons_jobinfo_str
&& (id<=m_lastId || time<=QDateTime::currentDateTime().addDays(0-g_setting->getRecordDays()))) {
hasMoreJobInfo = false;
break;
} else {
QString sql;
QSqlQueryModel queryModel;
sql = QString("select * from JobInfo where Id=%1").arg(id);
queryModel.setQuery(sql);
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
}
if (queryModel.rowCount() == 0) {
m_hasNewJobInfo = true;
sql = QString("insert into JobInfo (Id, Title, Addr, Time, IsRead, Type) values(%1, '%2', '%3', '%4', %5, '%6')")
.arg(id).arg(title).arg(href).arg(time.toString("yyyy-MM-dd hh:mm:ss")).arg(false).arg(curTypeStr);
queryModel.setQuery(sql);
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
}
} else {
qDebug() << id << "exist in JobInfo" << __FILE__ << __LINE__;
}
}
}
}
m_webPage.mainFrame()->setHtml("");
// QSqlQueryModel queryModel;
// QString sql = "select min(Time) from JobInfo";
// queryModel.setQuery(sql);
// if (queryModel.lastError().isValid()) {
// qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
// }
// QDate recordOldestDate = queryModel.record(0).value(0).toDate();
if (hasMoreJobInfo && oldestJobInfoTime < QDateTime::currentDateTime().addDays(0-g_setting->getRecordDays())) {
hasMoreJobInfo = false;
}
// bool hasMoreJobFair = oldestJobFairTime >= QDateTime::currentDateTime().addDays(0-g_setting->getRecordDays());
if (hasMoreJobFair && oldestJobFairTime.isNull()) {
hasMoreJobFair = false;
}
qDebug() << "has more jobinfo" << hasMoreJobInfo << oldestJobInfoTime
<< "has more jobfair" << hasMoreJobFair << oldestJobFairTime
<< __FILE__ << __LINE__;
// if (oldestJobInfoDate >= QDate::currentDate().addDays(0-g_setting->getRecordDays())
// || oldestJobFairDate >= QDate::currentDate().addDays(0-g_setting->getRecordDays())
// /*&& oldestJobInfoDate >= recordOldestDate*/) {
if (hasMoreJobInfo || hasMoreJobFair) {
m_currentPage++;
// QUrl url(QString("http://graduate.cqu.edu.cn/fourthIndex.do?classId=020601&viewPage=%1").arg(m_currentPage));
// m_downloadManager.append(url);
if (hasMoreJobInfo) {
m_downloadManager.append(QString("http://graduate.cqu.edu.cn/fourthIndex.do?classId=020601&viewPage=%1")
.arg(m_currentPage));
}
if (hasMoreJobFair) {
m_downloadManager.append(QString("http://graduate.cqu.edu.cn/fourthIndex.do?classId=020604&viewPage=%1")
.arg(m_currentPage));
}
return;
} else {
m_currentPage = 1;
}
qDebug() << "slotRenderGraduate" << m_hasNewJobInfo << __FILE__ << __LINE__;
if (m_hasNewJobInfo) {
slotUpdateJobInfo();
slotUpdateJobFair();
slotReminder(m_hasNewJobInfo);
m_hasNewJobInfo = false;
}
}
void MainWindow::slotUpdateJobInfo()
{
ui->tableWidgetJobInfo->clearContents();
ui->tableWidgetJobInfo->setRowCount(0);
openDatabase();
QSqlQueryModel queryModel;
queryModel.setQuery("select * from JobInfo where Type='JobInfo' order by Id desc");
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
Qt::SortOrder order = ui->tableWidgetJobInfo->horizontalHeader()->sortIndicatorOrder();
int section = ui->tableWidgetJobInfo->horizontalHeader()->sortIndicatorSection();
qDebug() << "jobinfo order" << section << order << __FILE__ << __LINE__;
ui->tableWidgetJobInfo->horizontalHeader()->setSortIndicator(TableJobInfo_Id, Qt::DescendingOrder);
int count = queryModel.rowCount();
ui->tableWidgetJobInfo->setRowCount(count);
for (int row=0; row<count; row++) {
QSqlRecord record = queryModel.record(row);
if (row == 0) {
m_lastId = record.value(JobInfo_Id).toLongLong();
}
ui->tableWidgetJobInfo->setItem(row, TableJobInfo_Id, new QTableWidgetItem(
record.value(JobInfo_Id).toString()));
ui->tableWidgetJobInfo->setItem(row, TableJobInfo_Time, new QTableWidgetItem(
record.value(JobInfo_Time).toDateTime().toString("yyyy-MM-dd hh:mm:ss")));
ui->tableWidgetJobInfo->setItem(row, TableJobInfo_Title, new QTableWidgetItem(
record.value(JobInfo_Title).toString()));
QTableWidgetItem *twItem = new QTableWidgetItem("详细");
twItem->setData(Qt::UserRole, record.value(JobInfo_Addr));
twItem->setForeground(QBrush(Qt::red));
twItem->setTextAlignment(Qt::AlignCenter);
QFont font(twItem->font());
font.setUnderline(true);
twItem->setFont(font);
ui->tableWidgetJobInfo->setItem(row, TableJobInfo_View, twItem);
if (!record.value(JobInfo_IsRead).toBool()) {
ui->tableWidgetJobInfo->item(row, TableJobFairRemind_Title)->setForeground(QBrush(Qt::blue));
}
}
ui->tableWidgetJobInfo->horizontalHeader()->setSortIndicator(section, order);
}
void MainWindow::slotUpdateJobFair()
{
ui->tableWidgetJobFair->clearContents();
ui->tableWidgetJobFair->setRowCount(0);
openDatabase();
QSqlQueryModel queryModel;
queryModel.setQuery("select * from JobInfo where Type='JobFair' order by Id desc");
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
Qt::SortOrder order = ui->tableWidgetJobFair->horizontalHeader()->sortIndicatorOrder();
int section = ui->tableWidgetJobFair->horizontalHeader()->sortIndicatorSection();
ui->tableWidgetJobFair->horizontalHeader()->setSortIndicator(TableJobFair_Id, Qt::DescendingOrder);
// queryModel.sort(section, order);
qDebug() << "jobinfo order" << order << section << __FILE__ << __LINE__;
int count = queryModel.rowCount();
ui->tableWidgetJobFair->setRowCount(count);
for (int row=0; row<count; row++) {
QSqlRecord record = queryModel.record(row);
if (row == 0) {
long long lastFairId = record.value(JobInfo_Id).toLongLong();
if (lastFairId > m_lastId) {
m_lastId = lastFairId;
}
}
ui->tableWidgetJobFair->setItem(row, TableJobFair_Id, new QTableWidgetItem(
record.value(JobInfo_Id).toString()));
ui->tableWidgetJobFair->setItem(row, TableJobFair_Time, new QTableWidgetItem(
record.value(JobInfo_Time).toDateTime().toString("yyyy-MM-dd hh:mm:ss")));
ui->tableWidgetJobFair->setItem(row, TableJobFair_Title, new QTableWidgetItem(
record.value(JobInfo_Title).toString()));
QTableWidgetItem *twItem = new QTableWidgetItem("详细");
twItem->setData(Qt::UserRole, record.value(JobInfo_Addr));
twItem->setForeground(QBrush(Qt::red));
twItem->setTextAlignment(Qt::AlignCenter);
QFont font(twItem->font());
font.setUnderline(true);
twItem->setFont(font);
ui->tableWidgetJobFair->setItem(row, TableJobFair_View, twItem);
// qDebug() << row << twItem->text() << twItem->data(Qt::UserRole) << __FILE__ << __LINE__;
if (!record.value(JobInfo_IsRead).toBool()) {
ui->tableWidgetJobFair->item(row, TableJobFairRemind_Title)->setForeground(QBrush(Qt::blue));
}
}
ui->tableWidgetJobFair->horizontalHeader()->setSortIndicator(section, order);
}
void MainWindow::slotUpdateJobFairRemind()
{
ui->tableWidgetJobFairRemind->clearContents();
ui->tableWidgetJobFairRemind->setRowCount(0);
openDatabase();
QSqlQueryModel queryModel;
queryModel.setQuery("select * from JobFairRemind order by Time asc");
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
int count = queryModel.rowCount();
ui->tableWidgetJobFairRemind->setRowCount(count);
for (int row=0; row<count; row++) {
QSqlRecord record = queryModel.record(row);
ui->tableWidgetJobFairRemind->setItem(row, TableJobFairRemind_Id, new QTableWidgetItem(
record.value(JobFairRemind_Id).toString()));
ui->tableWidgetJobFairRemind->setItem(row, TableJobFairRemind_Time, new QTableWidgetItem(
record.value(JobFairRemind_Time).toDate().toString("yyyy-MM-dd")));
ui->tableWidgetJobFairRemind->setItem(row, TableJobFairRemind_Title, new QTableWidgetItem(
record.value(JobFairRemind_Title).toString()));
ui->tableWidgetJobFairRemind->setItem(row, TableJobFairRemind_Note, new QTableWidgetItem(
record.value(JobFairRemind_Note).toString()));
ui->tableWidgetJobFairRemind->item(row, TableJobFairRemind_Note)->setToolTip("备注:\n" +
record.value(JobFairRemind_Note).toString());
}
}
void MainWindow::slotReminder(bool hasNewJobInfo)
{
QRect screenRect;
QPoint pos;
if (m_dRemind == NULL) {
m_dRemind = new DialogRemind;
connect(m_dRemind, SIGNAL(signView()), this, SLOT(showNormal()));
}
m_dRemind->init(hasNewJobInfo);
//show要放在move之前,不然对话框边框的尺寸获取不到
pos = QPoint(screenRect.width() - m_dRemind->frameSize().width(),
screenRect.height() - m_dRemind->frameSize().height());
m_dRemind->move(pos);
m_dRemind->activateWindow();
m_dRemind->showNormal();
screenRect = QApplication::desktop()->availableGeometry();
pos = QPoint(screenRect.width() - m_dRemind->frameSize().width(),
screenRect.height() - m_dRemind->frameSize().height());
m_dRemind->move(pos);
}
void MainWindow::viewJobFairRemind(int id)
{
if (m_dJobFairRemind == NULL) {
m_dJobFairRemind = new DialogJobFairRemind;
connect(m_dJobFairRemind, SIGNAL(signFairChanged()), this, SLOT(slotUpdateJobFairRemind()));
}
m_dJobFairRemind->init(id);
m_dJobFairRemind->showNormal();
}
void MainWindow::on_btnView_clicked()
{
QList<QTableWidgetSelectionRange> ranges = ui->tableWidgetJobFairRemind->selectedRanges();
if (ranges.count() > 0) {
if (ranges.count() > 1) {
qDebug() << "this is a bug" << __FILE__ << __LINE__;
}
QTableWidgetSelectionRange range = ranges.at(0);
if (range.bottomRow() != range.topRow()) {
qDebug() << "this is a bug" << __FILE__ << __LINE__;
}
int row = range.bottomRow();
viewJobFairRemind(ui->tableWidgetJobFairRemind->item(row, TableJobFairRemind_Id)->text().toInt());
}
}
void MainWindow::on_btnAdd_clicked()
{
viewJobFairRemind();
}
void MainWindow::on_btnDelete_clicked()
{
QList<QTableWidgetSelectionRange> ranges = ui->tableWidgetJobFairRemind->selectedRanges();
openDatabase();
foreach (QTableWidgetSelectionRange range, ranges) {
int bottomRow = range.bottomRow();
int topRow = range.topRow();
for (int row=topRow; row<=bottomRow; row++) {
int id = ui->tableWidgetJobFairRemind->item(row, TableJobFairRemind_Id)->text().toInt();
QString sql = QString("delete from JobFairRemind where Id=%1").arg(id);
QSqlQueryModel queryModel;
queryModel.setQuery(sql);
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
}
}
slotUpdateJobFairRemind();
}
void MainWindow::on_tableWidgetJobInfo_clicked(QModelIndex index)
{
QTableWidgetItem *item = ui->tableWidgetJobInfo->item(index.row(), index.column());
QString urlStr;
urlStr = item->data(Qt::UserRole).toString();
qDebug() << urlStr << __FILE__ << __LINE__;
if (index.column()==TableJobInfo_View && !urlStr.isNull()) {
openDatabase();
int id = ui->tableWidgetJobInfo->item(index.row(), TableJobInfo_Id)->text().toInt();
QString sql = QString("update JobInfo set isRead=1 where Id=%1").arg(id);
QSqlQueryModel queryModel;
queryModel.setQuery(sql);
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
slotUpdateJobInfo();
QDesktopServices::openUrl(QUrl::fromEncoded(urlStr.toLocal8Bit()));
}
}
void MainWindow::on_tableWidgetJobFair_clicked(QModelIndex index)
{
QTableWidgetItem *item = ui->tableWidgetJobFair->item(index.row(), index.column());
QString urlStr;
urlStr = item->data(Qt::UserRole).toString();
qDebug() << urlStr << item << __FILE__ << __LINE__;
if (index.column()==TableJobFair_View && !urlStr.isNull()) {
openDatabase();
int id = ui->tableWidgetJobFair->item(index.row(), TableJobFair_Id)->text().toInt();
QString sql = QString("update JobInfo set isRead=1 where Id=%1").arg(id);
QSqlQueryModel queryModel;
queryModel.setQuery(sql);
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
slotUpdateJobFair();
qDebug() << ui->tableWidgetJobFair->item(index.row(), index.column()) << __FILE__ << __LINE__;
QDesktopServices::openUrl(QUrl::fromEncoded(urlStr.toLocal8Bit()));
}
}
void MainWindow::on_tableWidgetJobFairRemind_doubleClicked(QModelIndex index)
{
if (index.isValid()) {
int row = index.row();
int id = ui->tableWidgetJobFairRemind->item(row, TableJobFairRemind_Id)->text().toInt();
viewJobFairRemind(id);
}
}
void MainWindow::on_actionSet_triggered()
{
DialogSet *dSet = new DialogSet;
dSet->exec();
}
void MainWindow::on_btnSetAllJobInfoRead_clicked()
{
openDatabase();
QString sql = QString("update JobInfo set isRead=1 where Type='JobInfo'");
QSqlQueryModel queryModel;
queryModel.setQuery(sql);
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
slotUpdateJobInfo();
}
void MainWindow::on_btnSetAllJobFairRead_clicked()
{
openDatabase();
QString sql = QString("update JobInfo set isRead=1 where Type='JobFair'");
QSqlQueryModel queryModel;
queryModel.setQuery(sql);
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
slotUpdateJobFair();
}
void MainWindow::on_btnMoreJobInfo_clicked()
{
QDesktopServices::openUrl(QUrl("http://graduate.cqu.edu.cn/fourthIndex.do?classId=020601"));
}
void MainWindow::on_btnMoreJobFair_clicked()
{
QDesktopServices::openUrl(QUrl("http://graduate.cqu.edu.cn/fourthIndex.do?classId=020604"));
}
void MainWindow::on_actionUpdate_triggered()
{
m_timer.start();
slotAutoCheck();
QTime t;
t.start();
while (t.elapsed() < 200) {
QCoreApplication::processEvents();
}
qDebug() << "actionUpdate" << __FILE__ << __LINE__;
if (m_dRemind->isHidden()) {
slotReminder(false);
}
}
void MainWindow::on_pushButton_clicked()
{
m_downloadManager.append(QUrl("http://192.168.100.210//red.rar"));
}
<file_sep>#ifndef SETTING_H
#define SETTING_H
#include <QObject>
#include "config.h"
#define g_setting Setting::instance()
class Setting : public QObject
{
Q_OBJECT
public:
static Setting *instance();
void updateSetting();
inline bool getIsCloseMin() {
return m_isCloseMin;
}
inline bool getIsStartMin() {
return m_isStartMin;
}
inline int getRecordDays() {
return m_recordDays;
}
inline int getAheadDays() {
return m_aheadDays;
}
inline int getIntervalHours() {
return m_intervalHours;
}
signals:
void signSettingChanged(bool, bool, bool);
private:
Setting(QObject *parent = 0);
static Setting *setting;
QString m_settingPath;
bool m_isCloseMin;
bool m_isStartMin;
int m_recordDays;
int m_aheadDays;
int m_intervalHours;
};
#endif // SETTING_H
<file_sep>#ifndef DIALOGREMIND_H
#define DIALOGREMIND_H
#include <QDialog>
#include <QDesktopServices>
#include <QUrl>
#include "config.h"
namespace Ui {
class DialogRemind;
}
class DialogRemind : public QDialog
{
Q_OBJECT
public:
explicit DialogRemind(QWidget *parent = 0);
~DialogRemind();
void init(bool hasNewJobInfo);
void readSettings();
signals:
void signView();
private slots:
void on_btnView_clicked();
private:
Ui::DialogRemind *ui;
bool openDatabase();
void updateJobFair();
};
#endif // DIALOGREMIND_H
<file_sep>#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtNetwork>
#include <QtWebKit>
#include <QtGui>
#include "config.h"
#include "downloadmanager.h"
#include "dialogJobFairRemind.h"
#include "dialogremind.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void setVisible(bool visible);
protected:
void showEvent(QShowEvent *se);
void resizeEvent(QResizeEvent *re);
void closeEvent(QCloseEvent *ce);
private:
Ui::MainWindow *ui;
//members
QTimer m_timer;
QWebPage m_webPage;
QWebPage m_webFairPage;
QDateTime m_lastCheckTime;
QString m_mainUrl;
DownloadManager m_downloadManager;
long long m_lastId;
int m_currentPage;
QTranslator m_tr;
bool m_hasNewJobInfo;
QSystemTrayIcon *trayIcon;
QMenu *trayIconMenu;
QAction *m_restoreAction; //还原
QAction *m_minAction; //最小化
QAction *m_quitAction; //退出
DialogJobFairRemind *m_dJobFairRemind;
DialogRemind *m_dRemind;
//methods
void initWidget();
bool openDatabase();
void createDatabase();
void writeSettings();
void viewJobFairRemind(int id=-1);
void processOldJobInfo();
void updateTableJobInfoWidth();
private slots:
void slotAutoCheck();
void slotRenderGraduate(const QMap<QUrl, QString> &downloadList);
void slotUpdateJobInfo();
void slotUpdateJobFair();
void slotUpdateJobFairRemind();
void slotReminder(bool hasNewJobInfo);
void slotProcessSettingChanged(bool isRecordChanged, bool isAheadChanged, bool isIntervalChanged);
void slotTrayIconActivated(QSystemTrayIcon::ActivationReason reason);
void slotOpen();
void on_tableWidgetJobInfo_clicked(QModelIndex index);
void on_tableWidgetJobFair_clicked(QModelIndex index);
void on_btnView_clicked();
void on_btnAdd_clicked();
void on_btnDelete_clicked();
void on_tableWidgetJobFairRemind_doubleClicked(QModelIndex index);
void on_actionSet_triggered();
void on_btnSetAllJobInfoRead_clicked();
void on_btnSetAllJobFairRead_clicked();
void on_btnMoreJobInfo_clicked();
void on_btnMoreJobFair_clicked();
void on_actionUpdate_triggered();
void on_pushButton_clicked();
};
#endif // MAINWINDOW_H
<file_sep>#ifndef DialogJobFairRemind_H
#define DialogJobFairRemind_H
#include <QDialog>
#include "config.h"
namespace Ui {
class DialogJobFairRemind;
}
class DialogJobFairRemind : public QDialog
{
Q_OBJECT
public:
explicit DialogJobFairRemind(QWidget *parent = 0);
~DialogJobFairRemind();
void init(int id=-1);
signals:
void signFairChanged();
private slots:
void on_btnOK_clicked();
void on_btnCancel_clicked();
private:
Ui::DialogJobFairRemind *ui;
int m_id;
bool openDatabase();
};
#endif // DialogJobFairRemind_H
<file_sep>#include "DialogJobFairRemind.h"
#include "ui_DialogJobFairRemind.h"
DialogJobFairRemind::DialogJobFairRemind(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogJobFairRemind)
{
ui->setupUi(this);
ui->labelId->hide();
ui->lineEditId->hide();
ui->dateEdit->setCalendarPopup(true);
//¼ÓÔØqss
QFile file(":/qss/JobInfo.qss");
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << file.errorString() << __FILE__ << __LINE__;
} else {
setStyleSheet(file.readAll());
}
file.close();
}
DialogJobFairRemind::~DialogJobFairRemind()
{
delete ui;
}
void DialogJobFairRemind::init(int id)
{
m_id = id;
QTextDocument *tDoc = ui->textEditNote->document();
qDebug() << tDoc->defaultFont() << ui->textEditNote->font() << __FILE__ << __LINE__;
ui->textEditNote->setFont(tDoc->defaultFont());
ui->textEditNote->setStyleSheet(tDoc->defaultStyleSheet());
qDebug() << ui->textEditNote->font() << __FILE__ << __LINE__;
if (id != -1) {
QSqlQueryModel queryModel;
queryModel.setQuery(QString("select * from JobFairRemind where Id=%1").arg(m_id));
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
if (queryModel.rowCount() == 0 || queryModel.rowCount() > 1) {
qDebug() << "this is a bug" << __FILE__ << __LINE__;
}
QSqlRecord record = queryModel.record(0);
ui->lineEditId->setText(record.value(JobFairRemind_Id).toString());
ui->lineEditTitle->setText(record.value(JobFairRemind_Title).toString());
ui->dateEdit->setDate(record.value(JobFairRemind_Time).toDate());
ui->textEditNote->setText(record.value(JobFairRemind_Note).toString());
} else {
ui->lineEditId->clear();
ui->lineEditTitle->clear();
ui->dateEdit->setDate(QDate::currentDate());
ui->textEditNote->clear();
}
}
bool DialogJobFairRemind::openDatabase()
{
QString name = QSqlDatabase::database().connectionName();
QSqlDatabase::removeDatabase(name);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
QString fileName(QApplication::applicationDirPath() + "/JobInfo/JobInfo.db");
QFileInfo fileInfo(fileName);
QDir dir(fileInfo.absoluteDir());
if (!dir.exists()) {
dir.mkpath(dir.absolutePath());
}
db.setDatabaseName(fileName);
if (!db.open()) {
QMessageBox::information(this, "ÐÅÏ¢", db.lastError().text());
return false;
}
return true;
}
void DialogJobFairRemind::on_btnOK_clicked()
{
openDatabase();
QString sql;
int id = ui->lineEditId->text().toInt();
QString title = ui->lineEditTitle->text();
QString time = ui->dateEdit->date().toString("yyyy-MM-dd");
QString note = ui->textEditNote->toPlainText();
if (m_id == -1) {
sql = QString("insert into JobFairRemind (Title, Time, Note) values('%1', '%2', '%3')")
.arg(title).arg(time).arg(note);
} else {
sql = QString("update JobFairRemind set Title='%1', Time='%2', Note='%3' where Id=%4")
.arg(title).arg(time).arg(note).arg(id);
}
QSqlQueryModel queryModel;
queryModel.setQuery(sql);
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
emit signFairChanged();
close();
}
void DialogJobFairRemind::on_btnCancel_clicked()
{
close();
}
<file_sep>#include "dialogremind.h"
#include "ui_dialogremind.h"
#include "setting.h"
enum TableJobFair {
TableJobFair_Id,
TableJobFair_Time,
TableJobFair_Title,
TableJobFair_Note
};
DialogRemind::DialogRemind(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogRemind)
{
ui->setupUi(this);
//加载qss
QFile file(":/qss/JobInfo.qss");
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << file.errorString() << __FILE__ << __LINE__;
} else {
setStyleSheet(file.readAll());
}
file.close();
setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint);
QStringList fairHeaderLabels;
fairHeaderLabels << "编号" << "时间" << "招聘会" << "备注";
ui->tableWidgetJobFair->setColumnCount(fairHeaderLabels.count());
ui->tableWidgetJobFair->setHorizontalHeaderLabels(fairHeaderLabels);
// ui->tableWidgetJobFair->horizontalHeader()->hide();
ui->tableWidgetJobFair->verticalHeader()->hide();
ui->tableWidgetJobFair->setSortingEnabled(true);
ui->tableWidgetJobFair->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableWidgetJobFair->setSelectionMode(QAbstractItemView::NoSelection);
ui->tableWidgetJobFair->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableWidgetJobFair->setFocusPolicy(Qt::NoFocus);
ui->tableWidgetJobFair->hideColumn(TableJobFair_Id);
}
DialogRemind::~DialogRemind()
{
delete ui;
}
void DialogRemind::init(bool hasNewJobInfo)
{
if (hasNewJobInfo) {
ui->label->setText("有新的招聘信息");
QPalette palette;
palette.setBrush(QPalette::WindowText, QBrush(Qt::red));
ui->label->setPalette(palette);
} else {
QPalette palette;
palette.setBrush(QPalette::WindowText, QBrush(Qt::black));
ui->label->setPalette(palette);
ui->label->setText("暂时没有新的招聘信息");
}
openDatabase();
updateJobFair();
}
bool DialogRemind::openDatabase()
{
QString name = QSqlDatabase::database().connectionName();
QSqlDatabase::removeDatabase(name);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(QApplication::applicationDirPath() + "/JobInfo/JobInfo.db");
if (!db.open()) {
QMessageBox::information(this, "msg", "open failed");
return false;
}
return true;
}
void DialogRemind::updateJobFair()
{
ui->tableWidgetJobFair->clearContents();
ui->tableWidgetJobFair->setRowCount(0);
openDatabase();
QDate currentDate = QDate::currentDate();
QSqlQueryModel queryModel;
QString sql = QString("select * from JobFairRemind where Time between '%1' and '%2'")
.arg(currentDate.toString("yyyy-MM-dd"))
.arg(currentDate.addDays(g_setting->getAheadDays()).toString("yyyy-MM-dd"));
queryModel.setQuery(sql);
if (queryModel.lastError().isValid()) {
qDebug() << queryModel.lastError() << __FILE__ << __LINE__;
return;
}
int count = queryModel.rowCount();
ui->tableWidgetJobFair->setRowCount(count);
for (int row=0; row<count; row++) {
QSqlRecord record = queryModel.record(row);
ui->tableWidgetJobFair->setItem(row, TableJobFair_Id, new QTableWidgetItem(
record.value(JobFairRemind_Id).toString()));
ui->tableWidgetJobFair->setItem(row, TableJobFair_Time, new QTableWidgetItem(
record.value(JobFairRemind_Time).toDate().toString("yyyy-MM-dd")));
ui->tableWidgetJobFair->setItem(row, TableJobFair_Title, new QTableWidgetItem(
record.value(JobFairRemind_Title).toString()));
ui->tableWidgetJobFair->setItem(row, TableJobFair_Note, new QTableWidgetItem(
record.value(JobFairRemind_Note).toString()));
ui->tableWidgetJobFair->item(row, TableJobFair_Note)->setToolTip(
"备注:\n" + record.value(JobFairRemind_Note).toString());
}
}
void DialogRemind::on_btnView_clicked()
{
emit signView();
close();
}
<file_sep>#include <QtGui/QApplication>
#include <QtCore>
#include "mainwindow.h"
//#include <QtTest>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTextCodec *tc = QTextCodec::codecForName("gb2312");
QTextCodec::setCodecForCStrings(tc);
QTextCodec::setCodecForLocale(tc);
QTextCodec::setCodecForTr(tc);
// 确保只运行一次
QSystemSemaphore sema("JAMKey",1,QSystemSemaphore::Open);
sema.acquire();// 在临界区操作共享内存 SharedMemory
QSharedMemory mem("JobInfo");// 全局对象名
if (!mem.create(1))// 如果全局对象以存在则退出
{
QMessageBox::warning(0, QObject::tr("警告"), QObject::tr("程序已经启动."));
sema.release();// 如果是 Unix 系统,会自动释放。
return 0;
}
sema.release();// 临界区
MainWindow w;
// w.show();
return a.exec();
}
<file_sep>#ifndef CONFIG_H
#define CONFIG_H
#include <QtGui>
#include <QtCore>
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QSqlTableModel>
#include <QSqlQueryModel>
#include <QSqlRecord>
#include <QSqlError>
enum JobFairRemind {
JobFairRemind_Id,
JobFairRemind_Title,
JobFairRemind_Time,
JobFairRemind_Note
};
enum JobInfo {
JobInfo_Id,
JobInfo_Title,
JobInfo_Addr,
JobInfo_Time,
JobInfo_IsRead
};
#endif // CONFIG_H
<file_sep>#include "setting.h"
Setting *Setting::setting = NULL;
Setting::Setting(QObject *parent) :
QObject(parent)
{
m_settingPath = QApplication::applicationDirPath() + "/JobInfo/setting.ini";
updateSetting();
}
Setting *Setting::instance()
{
if (setting == NULL) {
setting = new Setting;
}
return setting;
}
void Setting::updateSetting()
{
QSettings setting(m_settingPath, QSettings::IniFormat);
m_isStartMin = setting.value("startmin", true).toBool();
m_isCloseMin = setting.value("closemin", true).toBool();
int recordDays = setting.value("recorddays", 3).toInt();
int aheadDays = setting.value("aheaddays", 3).toInt();
int intervalHours = setting.value("intervalhours", 3).toInt();
bool isRecordChanged = recordDays!=m_recordDays;
bool isAheadChanged = aheadDays!=m_aheadDays;
bool isIntervalChanged = intervalHours!=m_intervalHours;
m_recordDays = recordDays;
m_aheadDays = aheadDays;
m_intervalHours = intervalHours;
emit signSettingChanged(isRecordChanged, isAheadChanged, isIntervalChanged);
}
|
aa2bc077ec19cb896f04fb533f15dd601187785e
|
[
"C",
"C++"
] | 14 |
C++
|
llong283/JobInfo
|
2a1084b67559e9316feaafeefe6f3fc296088d4d
|
dc1e7bd1aa19f277479bf4a78d6906e6b0d2beeb
|
refs/heads/master
|
<repo_name>LordOfTheBees/MicrophoneListener<file_sep>/App.js
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button, NativeModules } from 'react-native';
import { DeviceEventEmitter } from 'react-native';
const MicrophoneListener = NativeModules.IOMicrophoneListener;
const MicrophoneCallback = NativeModules.IOMicrophoneCallback;
type Props = {};
export default class App extends Component<Props> {
constructor() {
super()
this.state = {
myText: 'My Original Text'
}
MicrophoneListener.setBufferSize(1024);
DeviceEventEmitter.addListener('onNewSoundData', (e)=>{ this.onNewSoundData(e);});
}
onNewSoundData(e){
var data = e.data;
this.setState({myText: data[1000]});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>{this.state.myText}</Text>
<Button onPress={()=>this.start()} title='Start'/>
<Button onPress={()=>this.stop()} title='Stop'/>
</View>
);
}
start(){
MicrophoneListener.start();
}
stop(){
MicrophoneListener.stop();
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
<file_sep>/android/settings.gradle
rootProject.name = 'MicrophoneListener'
include ':app'
|
bd3cb695652bc966c28befa52b3d72ccbd4c00ca
|
[
"JavaScript",
"Gradle"
] | 2 |
JavaScript
|
LordOfTheBees/MicrophoneListener
|
9362809f552eeb9d19cbbe5771b76ba97d27d7c2
|
f93c770fa901c244d51e95d44e602e9063554b8b
|
refs/heads/master
|
<repo_name>reason18/ToDoList<file_sep>/src/store/actions/index.js
export * from "./CommentList";
export * from "./TaskList";
<file_sep>/src/app/App.jsx
import * as React from "react";
import { Col, Row } from "reactstrap";
import { Sidebar } from "./controls/Sidebar";
import { CommentsList } from "./controls/CommentsList";
import { TaskList } from "./controls/TaskList";
import {
inputTaskTitle,
addTask,
deleteTask,
selectTask,
inputComment,
addComment
} from "../store";
import { connect } from "react-redux";
class App extends React.Component {
render() {
return (
<div className="App">
<Row noGutters>
<Sidebar />
<Col xs={12} md={10} className="main-content max-height d-flex flex-wrap px-0 px-md-3 py-4">
<Col xs={12} md={6}>
<TaskList
state={this.props.tasks}
comments={this.props.comments.data}
onInputChange={this.props.onInputTaskTitle}
onInputSubmit={this.props.onSubmitTask}
onDelete={this.props.onDeleteTask}
onSelect={this.props.onSelectTask}
/>
</Col>
<Col xs={12} md={6}>
{this.props.tasks.selectedTask.id ? (
<CommentsList
state={this.props.comments}
selectedTask={this.props.tasks.selectedTask}
onInputChange={this.props.onInputComment}
onInputSubmit={this.props.onSubmitComment}
/>
) : null}
</Col>
</Col>
</Row>
</div>
);
}
}
export default connect(
state => {
return {
tasks: state.tasks,
comments: state.comments
};
},
dispatch => {
return {
onInputTaskTitle: text => dispatch(inputTaskTitle(text)),
onSubmitTask: item => dispatch(addTask(item)),
onDeleteTask: id => dispatch(deleteTask(id)),
onSelectTask: id => dispatch(selectTask(id)),
onInputComment: text => dispatch(inputComment(text)),
onSubmitComment: item => dispatch(addComment(item))
};
}
)(App);
<file_sep>/src/store/actions/CommentList.js
export const ADD_COMMENT = "ADD_COMMENT";
export const INPUT_COMMENT = "INPUT_COMMENT";
export const addComment = input => {
return {
type: ADD_COMMENT,
payload: input
};
};
export const inputComment = text => {
return {
type: INPUT_COMMENT,
payload: text
};
};
<file_sep>/src/store/reducers/TaskList.js
import {
ADD_TASK,
REMOVE_TASK,
SELECT_TASK,
INPUT_TASK_TITLE
} from "../actions/TaskList";
const initialState = {
data: [
{
id: 1,
title: "Firs task",
comments: 2
},
{
id: 2,
title: "Second task",
comments: 2
}
],
selectedTask: {},
inputData: ""
};
export const reducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TASK:
return {
...state,
data: [...state.data, action.payload],
inputData: ""
};
case REMOVE_TASK:
return {
...state,
data: state.data.filter(task => task.id !== action.payload)
};
case SELECT_TASK:
const selectedTask = state.data.find(task => task.id === action.payload);
return { ...state, selectedTask };
case INPUT_TASK_TITLE:
return { ...state, inputData: action.payload };
default:
return state;
}
};
<file_sep>/src/store/actions/TaskList.js
export const ADD_TASK = "ADD_TASK";
export const REMOVE_TASK = "REMOVE_TASK";
export const SELECT_TASK = "SELECT_TASK";
export const INPUT_TASK_TITLE = "INPUT_TASK_TITLE";
export const addTask = item => {
return {
type: ADD_TASK,
payload: item
};
};
export const deleteTask = id => {
return {
type: REMOVE_TASK,
payload: id
};
};
export const selectTask = id => {
return {
type: SELECT_TASK,
payload: id
};
};
export const inputTaskTitle = text => {
return {
type: INPUT_TASK_TITLE,
payload: text
};
};
<file_sep>/src/app/controls/Sidebar.jsx
import * as React from "react";
import { Col } from "reactstrap";
export class Sidebar extends React.Component {
render() {
return (
<Col xs={12} md={2} className="sidebar">
<Col className="pt-3 pb-2">
<h2 className="text-uppercase text-white">Dairy app</h2>
</Col>
<Col>
<span className="text-muted">Comment with no sense</span>
</Col>
</Col>
);
}
}
<file_sep>/src/app/controls/CommentsList.jsx
import * as React from "react";
import { Button, Col, Row, Input, ListGroup, ListGroupItem } from "reactstrap";
export class CommentsList extends React.Component {
componentDidMount() {
document.addEventListener("keydown", this.keydownHandler.bind(this));
}
componentWillUnmount() {
document.removeEventListener("keydown", this.keydownHandler.bind(this));
}
render() {
const { data, inputData } = this.props.state;
const selectedTask = this.props.selectedTask;
const title = this.props.selectedTask.title;
const dataItems = data.filter(item => item.taskId === selectedTask.id);
const listItems = dataItems.map(item => {
return (
<ListGroupItem className="p-0 m-0" key={item.id}>
<Row noGutters className="custom-list-item py-2">
<Col xs={2} className="pt-1">
<span className="avatar-block" />
</Col>
<Col xs={10} className="text-block pl-3 pl-md-0">
{item.text}
</Col>
</Row>
</ListGroupItem>
);
});
return (
<Col xs={12} className="comment-block bg-white p-2 px-4">
<Col xs={12} className="items-header">
<h2>{title}</h2>
</Col>
<Col xs={12} className="px-0">
<ListGroup className="py-2">{listItems}</ListGroup>
</Col>
<Row noGutters className="custom-list-item py-2 m-0">
<Col xs={2} className="pt-1">
<span className="avatar-block bg-success" />
</Col>
<Col xs={10} className="text-block pl-3 pl-md-0">
<Input
type="textarea"
name="text"
id="exampleText"
value={inputData}
onChange={this.onChange.bind(this)}
require="true"
/>
</Col>
<Button
className="col text-white mt-2 mt-md-0 turquoise-bg turquoise-border d-block d-md-none"
onClick={this.onSubmit.bind(this)}
disabled={this.props.state.inputData.length < 1}
>
Add new
</Button>
</Row>
</Col>
);
}
onChange(e) {
this.props.onInputChange(e.target.value);
}
keydownHandler(e) {
if (e.keyCode === 13 && e.ctrlKey) {
this.onSubmit();
}
}
onSubmit(e) {
const item = {
id: Math.ceil(Math.random() * 1000),
text: this.props.state.inputData,
taskId: this.props.selectedTask.id
};
this.props.onInputSubmit(item);
}
}
<file_sep>/src/store/reducers/index.js
import { combineReducers } from "redux";
import { reducer as tasksReducer } from "./TaskList";
import { reducer as commentsReducer } from "./CommentList";
export default combineReducers({
tasks: tasksReducer,
comments: commentsReducer
});
<file_sep>/src/store/reducers/CommentList.js
import { ADD_COMMENT, INPUT_COMMENT } from "../actions/CommentList";
const initialState = {
data: [
{
id: 1,
text: `First comment for first task`,
taskId: 1
},
{
id: 2,
text: `Second comment for first task`,
taskId: 1
},
{
id: 3,
text: `First comment for second task`,
taskId: 2
},
{
id: 4,
text: `Second comment for second task`,
taskId: 2
}
],
inputData: ""
};
export const reducer = (state = initialState, action) => {
switch (action.type) {
case ADD_COMMENT:
const data = [...state.data, action.payload];
return { ...state, data, inputData: "" };
case INPUT_COMMENT:
return { ...state, inputData: action.payload };
default:
return state;
}
};
|
84e14bb80f1d829cbe3b79b8db6acac1381ec6a5
|
[
"JavaScript"
] | 9 |
JavaScript
|
reason18/ToDoList
|
095beb5208f13601db5a80c35936622132b95bc0
|
aceec7387dc6a53baf144d592fca48a454e004bc
|
refs/heads/main
|
<file_sep>#include <iostream>
using namespace std;
int task1()
{
cout << "Task 1 " << endl;
int a, b;
cout << "enter first number - " << endl;
cin >> a;
cout << "enter second number - " << endl;
cin >> b;
if (10 < a + b < 20)
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
return 0;
}
int task2()
{
cout << "Task 2" << endl;
int c = 4, d = 6;
if ((c == 10 && d == 10) || (c + d == 10))
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
};
return 0;
}
int task31()
{
cout << "Task 3" << endl;
cout << "odd number ";
for (int i = 1; i <= 50; i = i + 2)
{
cout << i << " ";
}
cout << endl;
return 0;
}
int task32()
{
cout << "Task 3" << endl;
cout << "odd number ";
int i=1;
while (i < 50)
{
if ((1 <= i < 50) && (i % 2 == 1))
{
cout << i << " ";
}
i++;
}
cout << endl;
return 0;
}
int task41()
{
cout << "Task 4" << endl;
int i,x=2;
cout << "Enter number - " << endl;
cin >> i;
if (i < 0)
{
cout << i << " - not prime number" << endl;
}
else
while (x < i)
{
if (i % x == 0)
{
cout << i << " - not prime number" << endl;
break;
x++;
}
else
{
cout << i << " - prime number" << endl;
break;
}
}
return 0;
}
int task42()
{
cout << "Task 4" << endl;
int i, x = 2;
cout << "Enter number - " << endl;
cin >> i;
if (i < 0)
{
cout << i << " - not prime number" << endl;
}
else if (i == 1)
{
cout << i << " - prime number" << endl;
}
else if (i>0)
{
for (x; x < i; i++)
{
if (i % x == 0)
{
cout << i << " - not prime number" << endl;
break;
}
else
{
cout << i << " - prime number" << endl;
break;
}
}
}
return 0;
}
int task5()
{
cout << "Task 5" << endl;
int i;
do
{
cout << "Enter year between 1 to 3000 - " << endl;
cin >> i;
} while (3000 < i || i < 1);
if (i%4==0 && i%100!=0 || i%400==0)
cout << i << " - leap year" << endl;
else
cout << i << " - not leap year" << endl;
/*
if (i % 400 == 0 )
cout << i << " - leap year" << endl;
else if (i % 100 == 0)
cout << i << " - not leap year" << endl;
else if (i%4==0)
cout << i << " - leap year" << endl;
else
cout << i << " - not leap year" << endl;
*/
return 0;
}
int main()
{
task1();
task2();
task31();
task32();
task41();
task42();
task5();
return 0;
}
/*
1. Написать программу, проверяющую что сумма двух(введенных с клавиатуры) чисел лежит в пределах от 10 до 20 (включительно),
если да – вывести строку "true", в противном случае – "false";
2.Написать программу, выводящую на экран строку “true”, если две целочисленные константы, объявленные в её начале либо обе
равны десяти сами по себе, либо их сумма равна десяти.Иначе "false".
3.Написать программу которая выводит на экран список всех нечетных чисел он 1 до 50. Например: "Your numbers: 1 3 5 7 9 11 13 …".
Для решения используйте любой С++ цикл.
4.Со звёздочкой.Написать программу, проверяющую, является ли некоторое число - простым.Простое число — это целое
положительное число, которое делится без остатка только на единицу и себя само.
5.Со звёздочкой.Пользователь вводит с клавиатуры число(год) : от 1 до 3000. Написать программу, которая определяет
является ли этот год високосным.Каждый 4 - й год является високосным, кроме каждого 100 - го, при этом каждый 400 - й – високосный.
Вывести результаты работы программы в консоль.Замечание : Можно сделать в одном проекте(например разместить разные
задания в разных функциях).Или в разных проектах если это кажется удобнее.
*/
|
36f6f4a43b940b02c10783a31a593f10b90e540d
|
[
"C++"
] | 1 |
C++
|
amkstkn/Homework4
|
529fa67130a551f4bf6f769c4353c750e314615e
|
f377e7211a58063c56a2692c7f87c77621d22751
|
refs/heads/master
|
<repo_name>illi-507/ComputerGraphics-Amuse-Textured<file_sep>/GraphicsTown JS 2015!_files/TurboDrop.js
var grobjects = grobjects || [];
// allow the constructor to be "leaked" out
var Drop = undefined;
var carCount = 0;
var step = 0.2;
// this is a function that runs at loading time (note the parenthesis at the end)
(function() {
"use strict";
// i will use this function's scope for things that will be shared
// across all cubes - they can all have the same buffers and shaders
// note - twgl keeps track of the locations for uniforms and attributes for us!
var shaderProgram = undefined;
var buffers = undefined;
Drop = function(name, position){
this.name = name;
this.position = position;
//name, position, size, color,NAME
this.cube1 = new Pyramid("cube1",position,1.0,[1.0,1.0,1.0],0,LoadedImageFiles["Pattern9.jpg"].src);
this.cube2 = new Pyramid("cube2",position,1.0,[1.0,1.0,1.0],0,LoadedImageFiles["Pattern9.jpg"].src);
this.cube3 = new Pyramid("cube3",position,1.0,[1.0,1.0,1.0],0,LoadedImageFiles["Pattern9.jpg"].src);
this.cube4 = new Pyramid("cube4",position,1.0,[1.0,1.0,1.0],0,LoadedImageFiles["Pattern9.jpg"].src);
this.cube5 = new Pyramid("cube5",position,1.0,[1.0,1.0,1.0],0,LoadedImageFiles["Pattern9.jpg"].src);
this.cube6 = new Pyramid("cube5",position,0.5,[1.0,1.0,1.0],0,LoadedImageFiles["Pattern10.jpg"].src);
this.cube7 = new Pyramid("cube5",position,0.5,[1.0,1.0,1.0],0,LoadedImageFiles["Pattern10.jpg"].src);
this.cube8 = new Pyramid("cube5",position,0.5,[1.0,1.0,1.0],0,LoadedImageFiles["Pattern10.jpg"].src);
this.cube9 = new Pyramid("cube5",position,0.5,[1.0,1.0,1.0],0,LoadedImageFiles["Pattern10.jpg"].src);
this.cube10 = new Cube("cube7",position,0.5,[0.1,0.1,0.9],0);
this.cube11 = new Cube("cube7",position,0.5,[0.1,0.1,0.9],0);
this.cube12 = new Cube("cube7",position,0.5,[0.1,0.1,0.9],0);
this.cube13 = new Cube("cube7",position,0.5,[0.1,0.1,0.9],0);
this.cube14 = new Cube("cube7",position,0.5,[0.1,0.1,0.9],0);
this.cube15 = new Cube("cube7",position,0.5,[0.1,0.1,0.9],0);
/*this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);
this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);
this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);
this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);
this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);
this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);
this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);*/
//this.cube7 = new Cube("tube1",position,0.65,[0.0,1.0,0.2],1);
}
Drop.prototype.init = function(drawingState){
this.cube1.init(drawingState);
this.cube2.init(drawingState);
this.cube3.init(drawingState);
this.cube4.init(drawingState);
this.cube5.init(drawingState);
this.cube6.init(drawingState);
this.cube7.init(drawingState);
this.cube8.init(drawingState);
this.cube9.init(drawingState);
}
var x = 0.0;
var y = 2.0;
var z = 2.0;
var time = 0;
Drop.prototype.draw = function(drawingState) {
var TIME = Number(drawingState.realtime);
if(x < 0.5&& x >0.0){
x++;
}
else if(x>4.0 && x<5.0){
x--;
}
var position1 = [-3.5,0.0,3.5];
var position2 = [-3.5,1.0,3.5];
var position3 = [-3.5,2.0,3.5];
var position4 = [-3.5,3.0,3.5];
var position5 = [-3.5,4.0,3.5];
var position6 = [-3.5,2*Math.sin(TIME*0.0005)+2.5,4.5];
var position7 = [-3,2*Math.sin(TIME*0.0005)+2.5,4.5];
var position8 = [-3.5,2*Math.sin(TIME*0.0005+3.1415926)+2.5,3.0];
var position9 = [-3,2*Math.sin(TIME*0.0005+3.1415926)+2.5,3.0];
var position10 = [-3.25,0.5,4.75];
var position11 = [-3.25,0.5,4.75];
var position12 = [-3.25,0.5,4.75];
var position13 = [-3.25,0.5,4.75];
var position14 = [-3.25,0.5,4.75];
var position15 = [-3.25,0.5,4.75];
this.cube1.position = position1;
this.cube2.position = position2;
this.cube3.position = position3;
this.cube4.position = position4;
this.cube5.position = position5;
this.cube6.position = position6;
this.cube7.position = position7;
this.cube8.position = position8;
this.cube9.position = position9;
this.cube1.draw(drawingState);
this.cube2.draw(drawingState);
this.cube3.draw(drawingState);
this.cube4.draw(drawingState);
this.cube5.draw(drawingState);
this.cube6.draw(drawingState);
this.cube7.draw(drawingState);
this.cube8.draw(drawingState);
this.cube9.draw(drawingState);
}
Drop.prototype.center = function(drawingState) {
return this.position;
}
})();
// put some objects into the scene
// normally, this would happen in a "scene description" file
// but I am putting it here, so that if you want to get
// rid of cubes, just don't load this file.
grobjects.push(new Drop("TurboDrop",[5.0,5.0,5.0]));
//grobjects.push(new Wheel("Car1", [-centerSz,0.0,2.0], 1,1.0,2.0, [0.4,0.8,0.6], 0, 1));
//grobjects.push(new Cube("cube1",[-2,0.5, 0],1) );
/*
grobjects.push(new Cube("cube1",[-2,0.5, 0],1) );
grobjects.push(new Cube("cube2",[ 2,0.5, 0],1, [1,1,0]));
grobjects.push(new Cube("cube3",[ 0, 0.5, -2],1 , [0,1,1]));
grobjects.push(new Cube("cube4",[ 0,0.5, 2],1));
grobjects.push(new SpinningCube("scube 1",[-2,0.5, -2],1) );
grobjects.push(new SpinningCube("scube 2",[-2,0.5, 2],1, [1,0,0], 'Y'));
grobjects.push(new SpinningCube("scube 3",[ 2,0.5, -2],1 , [0,0,1], 'Z'));
grobjects.push(new SpinningCube("scube 4",[ 2,0.5, 2],1));
*/
<file_sep>/GraphicsTown JS 2015!_files/floor.js
var grobjects = grobjects || [];
var planeSz = planeSz || 10;
(function() {
"use strict";
var vertexPos = [
-planeSz, 0, -planeSz,
-planeSz, 0, planeSz,
planeSz, 0, planeSz, // black street
planeSz, 0, planeSz,
planeSz, 0, -planeSz,
-planeSz, 0, -planeSz,
];
var vertexColor = [
// 0,0,1, 0,0,1, 0,0,1, // black street
// 0,0,1, 0,0,1, 0,0,1,
];
var shaderProgram = undefined;
var buffers = undefined;
var floor = {
name : "Floor Plane",
init : function(drawingState) {
var gl = drawingState.gl;
if (!shaderProgram) {
shaderProgram = twgl.createProgramInfo(gl,["floor-vs","floor-fs"]);
}
var arrays = {
vpos : {
numComponents:3,
data:vertexPos
}
};
buffers = twgl.createBufferInfoFromArrays(gl,arrays);
},
draw : function(drawingState) {
var gl = drawingState.gl;
gl.useProgram(shaderProgram.program);
twgl.setBuffersAndAttributes(gl,shaderProgram,buffers);
twgl.setUniforms(shaderProgram,{
view:drawingState.view,
proj:drawingState.proj,
light:drawingState.sunDirection
});
twgl.drawBufferInfo(gl, gl.TRIANGLES, buffers);
},
center : function(drawingState) {
return [0,0,0];
}
};
grobjects.push(floor);
})();
<file_sep>/GraphicsTown JS 2015!_files/PirateBoat.js
var grobjects = grobjects || [];
// allow the constructor to be "leaked" out
var PirateBoat = undefined;
var carCount = 0;
var step = 0.2;
// this is a function that runs at loading time (note the parenthesis at the end)
(function() {
"use strict";
// i will use this function's scope for things that will be shared
// across all cubes - they can all have the same buffers and shaders
// note - twgl keeps track of the locations for uniforms and attributes for us!
var shaderProgram = undefined;
var buffers = undefined;
PirateBoat = function(name, position){
this.name = name;
this.position = position;
//name, position, size, color,NAME
this.tube7 = new newTube1("cube7",position,2,[1,1.0,1.0],0,LoadedImageFiles["IronTexture.jpg"].src);
this.tube8 = new newTube2("cube8",position,2,[1,1.0,1.0],0,LoadedImageFiles["IronTexture.jpg"].src);
this.boat1 = new Boat("cube1",position,0.5,[1.0,1.0,1.0],LoadedImageFiles["BoatTexture1.jpg"].src);
this.boat2 = new BoatBottom("cube2",position,0.5,[1.0,1.0,1.0],LoadedImageFiles["BoatTexture2.jpg"].src);
this.cube3 = new Cube("cube3",position,1.0,[1,0.1,0.1],0);
this.cube4 = new Cube("cube4",position,1.0,[1,0.1,0.1],0);
this.cube5 = new Cube("cube5",position,1.0,[1,0.1,0.1],0);
this.cube6 = new Cube("cube5",position,1.0,[1,0.1,0.1],0);
this.cube7 = new Cube("cube7",position,0.5,[0.1,0.9,0.2],0);
this.cube8 = new Cube("cube7",position,0.5,[0.9,0.9,0.0],0);
this.cube9 = new Cube("cube7",position,0.5,[0.9,0.9,0.0],0);
this.cube10 = new Cube("cube7",position,0.5,[0.1,0.1,0.9],0);
this.cube11 = new Cube("cube7",position,0.5,[0.1,0.1,0.9],0);
this.cube12 = new Cube("cube7",position,0.5,[0.1,0.1,0.9],0);
this.cube13 = new Cube("cube7",position,0.5,[0.1,0.1,0.9],0);
this.cube14 = new Cube("cube7",position,0.5,[0.1,0.1,0.9],0);
this.cube15 = new Cube("cube7",position,0.5,[0.1,0.1,0.9],0);
/*this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);
this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);
this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);
this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);
this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);
this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);
this.cube5 = new Cube("cube5",position,1.0,[0.1,0.1,0.9],0);*/
//this.cube7 = new Cube("tube1",position,0.65,[0.0,1.0,0.2],1);
}
PirateBoat.prototype.init = function(drawingState){
this.boat1.init(drawingState);
this.boat2.init(drawingState);
this.tube7.init(drawingState);
this.tube8.init(drawingState);
this.cube3.init(drawingState);
}
var x = 0.0;
var y = 2.0;
var z = 2.0;
var time = 0;
PirateBoat.prototype.draw = function(drawingState) {
var TIME = Number(drawingState.realtime);
if(x < 0.5&& x >0.0){
x++;
}
else if(x>4.0 && x<5.0){
x--;
}
var position1 = [-1.0,5.5,-4.0];
var position2 = [-1.0,1.5,-4.0];
var position3 = [-1.0,1.5,-3.0];
var position4 = [-1.0,0.5,-3.0];
var position5 = [-1.0,1.5,-5.0];
var position6 = [-1.0,0.5,-5.0];
//var position6 = [-3.25,2*Math.sin(TIME*0.0005)+2.5,4.75];
var position7 = [-2.75,2*Math.sin(TIME*0.0005)+2.5,4.75];
var position8 = [-3.25,2*Math.sin(TIME*0.0005+3.1415926)+2.5,3.25];
var position9 = [-2.75,2*Math.sin(TIME*0.0005+3.1415926)+2.5,3.25];
var position10 = [-3.25,0.5,4.75];
var position11 = [-3.25,0.5,4.75];
var position12 = [-3.25,0.5,4.75];
var position13 = [-3.25,0.5,4.75];
var position14 = [-3.25,0.5,4.75];
var position15 = [-3.25,0.5,4.75];
this.boat1.position = position1;
this.boat2.position = position1;
this.tube8.position = position2;
this.tube7.position = position2;
this.cube3.position = position3;
this.cube4.position = position4;
this.cube5.position = position5;
this.cube6.position = position6;
//this.cube2.position = position2;
this.cube7.position = position7;
this.cube8.position = position8;
this.cube9.position = position9;
this.boat1.draw(drawingState);
this.boat2.draw(drawingState);
this.tube7.draw(drawingState);
this.tube8.draw(drawingState);
this.cube3.draw(drawingState);
this.cube4.draw(drawingState);
this.cube5.draw(drawingState);
this.cube6.draw(drawingState);
}
PirateBoat.prototype.center = function(drawingState) {
return this.position;
}
})();
// put some objects into the scene
// normally, this would happen in a "scene description" file
// but I am putting it here, so that if you want to get
// rid of cubes, just don't load this file.
grobjects.push(new PirateBoat("PirateBoat1",[5.0,5.0,5.0]));
|
81aafa83ffa81c770caaaad633aefb037c339cc8
|
[
"JavaScript"
] | 3 |
JavaScript
|
illi-507/ComputerGraphics-Amuse-Textured
|
2deb702e29c1b614c598746586bd45bceb98f8ef
|
7c21fb9c124de63044b3296918a854132b74f237
|
refs/heads/master
|
<file_sep>package br.edu.ifpr.poo.campominado;
import java.util.Scanner;
import br.edu.ifpr.poo.campominado.mapa.Mapa;
public class CampoMinado {
private Mapa mapa;
private Jogada jogada;
private EstadoJogo situacao;
public CampoMinado(){
this(10);
}
public CampoMinado(int tamanho){
mapa = new Mapa(tamanho);
situacao = EstadoJogo.JOGANDO;
}
public void jogar(){
loopDoJogo();
imprimeSituacaoFinalJogo();
}
private void loopDoJogo() {
Jogada jogada = null;
do{
desenhaCampoMinado();
jogada = criarJogada();
situacao = mapa.jogar(jogada);
}while(situacao == EstadoJogo.JOGANDO);
}
private void imprimeSituacaoFinalJogo() {
if(situacao == EstadoJogo.DERROTA){
System.out.println("Você perdeu");
}
else{
System.out.println("Você venceu");
}
revelarMapa();
}
private Jogada criarJogada(){
Scanner scanner = null;
int x = 0, y = 0;
System.out.println("Digite a linha, depois a coluna (0 a 9)");
scanner = new Scanner(System.in);
x = scanner.nextInt();
y = scanner.nextInt();
jogada = new Jogada(x, y);
System.out.println("x=" + jogada.getX() + " y=" + jogada.getY());
return jogada;
}
private void desenhaCampoMinado(){
mapa.desenha();
}
private void revelarMapa(){
mapa.reveleSe();
desenhaCampoMinado();
}
}
<file_sep>package br.edu.ifpr.poo.campominado.mapa.casa;
import br.edu.ifpr.poo.campominado.EstadoJogo;
import br.edu.ifpr.poo.campominado.mapa.Mapa;
public class CasaVazia extends Casa {
private int numVizinhosMinados;
public CasaVazia(Mapa mapa, int x, int y, int numVizinhosMinados) {
super(mapa, x, y, TipoCasa.SEM_MINA);
this.numVizinhosMinados = numVizinhosMinados;
}
@Override
public String toString() {
if(numVizinhosMinados == 0)
return " ";
return numVizinhosMinados + "";
}
@Override
public boolean isEscondida() {
return false;
}
@Override
public EstadoJogo jogar() {
return EstadoJogo.JOGANDO;
}
}
<file_sep>package br.edu.ifpr.poo.campominado.mapa.casa;
public enum TipoCasa {
SEM_MINA, MINADO;
}
<file_sep>package br.edu.ifpr.poo.campominado.mapa.casa;
import br.edu.ifpr.poo.campominado.EstadoJogo;
import br.edu.ifpr.poo.campominado.mapa.Mapa;
public class CasaEscondida extends Casa {
public CasaEscondida(Mapa mapa, int x, int y, TipoCasa tipoCasa) {
super(mapa, x, y, tipoCasa);
}
@Override
public String toString() {
return "O";
}
@Override
public boolean isEscondida() {
return true;
}
public void reveleSe() {
mapa.revelarCasa(this);
}
@Override
public EstadoJogo jogar() {
return mapa.revelarCasa(this);
}
}
<file_sep>package br.edu.ifpr.poo.campominado.mapa.casa;
import br.edu.ifpr.poo.campominado.EstadoJogo;
import br.edu.ifpr.poo.campominado.mapa.Mapa;
public class CasaMinada extends Casa {
public CasaMinada(Mapa mapa, int x, int y) {
super(mapa, x, y, TipoCasa.MINADO);
}
@Override
public String toString() {
return "X";
}
@Override
public boolean isEscondida() {
return false;
}
@Override
public EstadoJogo jogar() {
return EstadoJogo.DERROTA;
}
}
<file_sep>package br.edu.ifpr.poo.campominado.mapa;
import java.util.ArrayList;
import java.util.List;
import br.edu.ifpr.poo.campominado.mapa.casa.Casa;
import br.edu.ifpr.poo.campominado.mapa.casa.CasaEscondida;
import br.edu.ifpr.poo.campominado.mapa.casa.TipoCasa;
public class MinasCanto implements EstrategiaMinas {
@Override
public void geraMinas(Mapa mapa) {
List<Casa> minado = new ArrayList<Casa>();
Casa[][] casas = mapa.getCasas();
for(int i = 0; i < casas.length; i++){
for(int j = 0; j < casas.length; j++){
if(ehCanto(i,j, casas.length)){
casas[i][j] = new CasaEscondida(mapa, i, j,
TipoCasa.MINADO);
minado.add(casas[i][j]);
}
else{
casas[i][j] = new CasaEscondida(mapa, i, j,
TipoCasa.SEM_MINA);
}
}
}
mapa.setCasas(casas);
mapa.setMinado(minado);
}
private boolean ehCanto(int linha, int coluna, int tamanho){
return ehPrimeiraLinha(linha) ||
ehUltimaLinha(linha, tamanho) ||
ehPrimeiraColuna(coluna) ||
ehUltimaColuna(coluna, tamanho);
}
private boolean ehUltimaColuna(int coluna, int tamanho) {
return coluna == tamanho - 1;
}
private boolean ehPrimeiraColuna(int coluna) {
return coluna == 0;
}
private boolean ehUltimaLinha(int linha, int tamanho) {
return linha == tamanho - 1;
}
private boolean ehPrimeiraLinha(int linha) {
return linha == 0;
}
}
<file_sep>package br.edu.ifpr.poo.campominado.mapa;
import java.util.ArrayList;
import java.util.List;
import br.edu.ifpr.poo.campominado.CampoMinado;
import br.edu.ifpr.poo.campominado.mapa.casa.Casa;
import br.edu.ifpr.poo.campominado.mapa.casa.CasaEscondida;
import br.edu.ifpr.poo.campominado.mapa.casa.TipoCasa;
public class MinasDiagonal implements EstrategiaMinas {
@Override
public void geraMinas(Mapa mapa) {
List<Casa> minado = new ArrayList<Casa>();
Casa[][] casas = mapa.getCasas();
for(int i = 0; i < casas.length; i++){
for(int j = 0; j < casas.length; j++){
if(i == j){
casas[i][j] = new CasaEscondida(mapa, i, j,
TipoCasa.MINADO);
minado.add(casas[i][j]);
}
else{
casas[i][j] = new CasaEscondida(mapa, i, j,
TipoCasa.SEM_MINA);
}
}
}
mapa.setCasas(casas);
mapa.setMinado(minado);
}
}
|
ea9cb8ca63834951327a6e89e7d07bb1764cf66b
|
[
"Java"
] | 7 |
Java
|
poo-ifpr/campo_minado
|
43280efa6e3174659168514645cea8811250cc23
|
8607e1241b211a2ebe93d4ea2f35347af4bda2ee
|
refs/heads/master
|
<repo_name>chenqi123/bk_dcmdb<file_sep>/src/github.com/shwinpiocess/cc/controllers/mail.go
package controllers
import (
//"net/url"
//"strconv"
"strings"
//"time"
"fmt"
"github.com/astaxie/beego"
//"github.com/shwinpiocess/cc/models"
//"github.com/shwinpiocess/cc/utils"
"net/smtp"
)
type MailController struct {
beego.Controller
}
func (this *MailController)Sendmail() {
user := "<EMAIL>"
password := "<PASSWORD>"
host := "10.70.102.54:25"
//to := "[email protected];<EMAIL>"
content := strings.TrimSpace(this.GetString("content", ""))
tos := strings.TrimSpace(this.GetString("tos", ""))
to:=strings.Replace(tos, ",", ";", -1)
subject := strings.TrimSpace(this.GetString("subject", ""))
//subject := "Test send email by golang"
body := `
<html>
<body>
<h3>
`+content+`
</h3>
</body>
</html>
`
fmt.Println("send email")
err := SMail(user, password, host, to, subject, body, "html")
/*
if err != nil {
fmt.Println("send mail error!")
fmt.Println(err)
}else{
fmt.Println("send mail success!")
}
*/
if err != nil {
this.Ctx.Output.Body([]byte(err.Error()))
} else {
this.Ctx.Output.Body([]byte("success"))
}
}
func SMail(user, password, host, to, subject, body, mailtype string) error{
hp := strings.Split(host, ":")
auth := smtp.PlainAuth("", user, password, hp[0])
var content_type string
if mailtype == "html" {
content_type = "Content-Type: text/"+ mailtype + "; charset=UTF-8"
}else{
content_type = "Content-Type: text/plain" + "; charset=UTF-8"
}
msg := []byte("To: " + to + "\r\nFrom: " + user + "<"+ user +">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
send_to := strings.Split(to, ";")
err := smtp.SendMail(host, auth, user, send_to, msg)
return err
}<file_sep>/src/github.com/shwinpiocess/cc/static/js/zjzModule.js
/* 拓扑配置 */
!(function(window){
window.CC.hostConf=CC.hostConf||{};
//首次加载的数据
window.CC.hostConf.init = function() {
/*
if (level == 2) {
var noset = true;
}
else {
var noset = false;
}
*/
$('#confTreeContainer').kendoTreeView({
template: kendo.template($("#treeview-template").html()),
dataSource: [{
id: appId,
text: appName,
//noset: noset,
spriteCssClass: 'c-icon icon-app application',
type: 'application',
number: 200,
expanded: true,
items: topo
}]
});
CC.hostConf.optionFn();
// 拓扑树根据浏览器调整自身高度
function treeHeightChange () {
$('.host-sidebar-left').css('position','fixed');
setTimeout(function (){
$('.c-host-side').css('height',$(window).outerHeight()-70-20);
if ($('.c-host-side').height()>820)$('.c-host-side').css('height',820);
$(".c-conf-tree").css('height',$('.c-host-side').outerHeight()-$('.conf-free-group').outerHeight()-$('.c-host-side>h4').outerHeight()-37);
},200)
}
treeHeightChange();
$(window).resize(function (){
treeHeightChange();
})
// 拓扑树根据浏览器调整自身高度 end
}
//弹窗事件
CC.hostConf.showWindow = function(Msg,level) {
if(level=='success')
{
var d = dialog({
width: 150,
content: '<div class="c-dialogdiv2"><i class="c-dialogimg-success"></i>'+Msg+'</div>'
});
d.show();
}
else if(level =='error')
{
var d = dialog({
title:'错误',
width:300,
okValue:"确定",
ok:function(){},
content: '<div class="c-dialogdiv"><i class="c-dialogimg-failure"></i>'+Msg+'</div>'
});
d.showModal();
}
else
{
var d = dialog({
title:'警告',
width:300,
okValue:"确定",
ok:function(){},
content: '<div class="c-dialogdiv"><i class="c-dialogimg-prompt"></i>'+Msg+'</div>'
});
d.showModal();
}
}
CC.hostConf.optionFn=function(){
//隐藏set菜单
$('#confTreeContainer').find('.c-icon.hide').closest('.k-top').hide();
$('#confTreeContainer').find('.c-icon.hide').closest('.k-mid').hide();
$('#confTreeContainer').find('.c-icon.hide').closest('.k-bot').hide();
//改变默认样式
if(emptys==1)
{
if(level==3)
{
$('.creat-container').css('display','none');
$('.creat-group-container').css('display','none');
}
else
{
$('.creat-container').css('display','none');
$('.creat-module-container').css('display','none');
}
}
//新增模块事件
$(".creat-module-btn").on("click", function(e) {
/*
if(defaultapp==1)
{
CC.hostConf.showWindow('资源池业务不能操作','notice');
return;
}
$.post("/App/getMainterners",
{}
,function(result) {
// rere = $.parseJSON(result);
rere = result;
{
var uinList = rere.uinList;
var UserNameList = rere.UserNameList;
var opstr='';
for(var i=0;i!=uinList.length;i++)
{
var uin=uinList[i];
opstr +=' <option value="'+uin+'">'+uin+'('+UserNameList[i]+')'+'</option>';
}
$("#Operator").html(opstr);
$("#BakOperator").html(opstr);
$("#Operator").select2();
$("#BakOperator").select2();
}
});
var domNode = $(e.target).closest('.k-item'),
node = $("#confTreeContainer").data('kendoTreeView').dataItem(domNode);
//对于二级业务来说重新取其setid
if(level==2)
{
var SetID = desetid;
var SetName = cookie.get('defaultAppName');
$("#newmodulebe").text("所属业务");
}
else
{
var SetID = node.id;
var SetName = node.text;
$("#newmodulebe").text("所属集群");
}
$("#newmodulegroupname").text(SetName);
$("#newmoduleModuleName").attr('setid',SetID);
*/
var SetName = cookie.get('defaultAppName');
$("#newmoduleappname").text(SetName);
$('.creat-container').css('display','none');
$('.creat-module-container').fadeIn();
$("#newmoduleModuleName").focus();
e.preventDefault();
e.stopPropagation();
return false;
});
//修改模块属性事件
$('.c-conf-tree .k-sprite.c-icon.icon-modal,.conf-free-group .k-in').parent().css('cursor','pointer').on("click dblclick", function(e) {
var padomNode=$(e.target).closest('.k-item').closest('.k-group').closest('.k-item'),
panode = $("#confTreeContainer").data('kendoTreeView').dataItem(padomNode);
var domNode = $(e.target).closest('.k-item'),
node = $("#confTreeContainer").data('kendoTreeView').dataItem(domNode);
/*
if(typeof panode == 'undefined')
{
return;
}
//二级结构,特殊处理
var SetID = panode.id;
if(level ==2)
{
var SetID = desetid;
var SetName = cookie.get('defaultAppName');
$("#editmodulebe").text("所属业务");
}
else
{
var SetID = panode.id;
var SetName = panode.text;
$("#editmodulebe").text("所属集群");
}
$.post("/App/getMainterners",
{}
,function(result) {
//rere = $.parseJSON(result);
rere = result;
{
var uinList = rere.uinList;
var UserNameList = rere.UserNameList;
var opstr='';
for(var i=0;i!=uinList.length;i++)
{
var uin=uinList[i];
opstr +=' <option value="'+uin+'">'+uin+'('+UserNameList[i]+')'+'</option>';
}
$("#editOperator").html(opstr);
$("#editBakOperator").html(opstr);
$("#editOperator").val(node.operator);
$("#editBakOperator").val(node.bakoperator);
$("#editOperator").select2();
$("#editBakOperator").select2();
}
});
// var SetName = panode.text;
*/
var AppName=cookie.get('defaultAppName');
var ModuleID = node.id;
var ModuleName = node.text;
$("#editmoduleapp").text(AppName);
$("#editmoduleModuleName").val(ModuleName);
$("#edit_module_property").html(ModuleName);
//$("#editmoduleModuleName").attr('SetID',SetID);
$("#editmoduleModuleName").attr('ModuleID',ModuleID);
$('.creat-container').css('display','none');
$('.edit-module-container').fadeIn();
$("#editmoduleModuleName").focus();
return false;
});
//新建模块取消事件
$("#new_module_cancel").on('click',function(e) {
e.preventDefault();
e.stopPropagation();
//$(".col-md-12.creat-container.creat-module-container").hide();
//$(".creat-container.creat-module-container").hide();
$('.creat-container').css('display','none');
$('.creat-module-container').fadeIn();
$("#newmoduleModuleName").val('').focus();
});
//保存新增模块
$("#newsavemodule").on('click',function(e){
e.preventDefault();
e.stopPropagation();
var ApplicationID = cookie.get('defaultAppId');
//var SetID = $("#newmoduleModuleName").attr('setid');
var ModuleName = $.trim($("#newmoduleModuleName").val());
//var Operator = $("#Operator").val();
//var BakOperator = $("#BakOperator").val();
if(ModuleName.length==0 ){
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">模块名不能为空</span>'
});
diaCopyMsg.show($("#newmoduleModuleName").get(0));
return ;
}
if(ModuleName.length>60){
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">模块名过长</span>'
});
diaCopyMsg.show($("#newmoduleModuleName").get(0));
return ;
}
$.post("/zjz_work_cmdb/cmdbmoule/newModule",
{ApplicationID:ApplicationID,ModuleName:ModuleName}
,function(result) {
// rere = $.parseJSON(result);
rere = result;
if (rere.success == false) {
CC.hostConf.showWindow(rere.errInfo,'notice');
return;
}
else {
if(firstmodule && firstapp){
var d = dialog({
title:'提示',
width:300,
height:30,
okValue:"确定",
ok:function(){window.location.href = '/host/hostQuery#em';return false;},
onclose:function(e){window.location.reload();},
content: '<div class="c-dialogdiv"><i class="c-dialogimg-success"></i>'+'模块添加好了,就差最后一步啦,点确定去往模块里添加主机'+'</div>'
});
d.showModal();
return;
}
else{
CC.hostConf.showWindow('新增模块成功!','success');
setTimeout(function(){window.location.reload();},1000);
return;
}
}
});
});
//删除模块
$("#editmoduledelete").on('click',function(e){
e.preventDefault();
e.stopPropagation();
var gridBatDel = dialog({
title:'确认11',
width:250,
content: '是否删除选中模块',
okValue:"确定",
cancelValue:"取消",
ok:function (){
var ApplicationID = cookie.get('defaultAppId');
//var SetID = $("#editmoduleModuleName").attr("setid");
var ModuleID = $("#editmoduleModuleName").attr("moduleid");
$.post("/zjz_work_cmdb/cmdbmoule/delModule",
{ApplicationID:ApplicationID,ModuleID:ModuleID}
,function(result) {
//rere = $.parseJSON(result);
rere = result;
if (rere.success == false) {
CC.hostConf.showWindow(rere.errInfo,'notice');
return;
}
else {
CC.hostConf.showWindow('删除模块成功!','success');
setTimeout(function(){window.location.reload();},1000);
}
});
},
cancel: function () {
}
});
gridBatDel.showModal();
});
//保存模块修改
$("#editmodulesave").on('click',function(e){
var ApplicationID = cookie.get('defaultAppId');
//var SetID = $("#editmoduleModuleName").attr("setid");
var ModuleID = $("#editmoduleModuleName").attr("moduleid");
var ModuleName = $.trim($("#editmoduleModuleName").val());
//var Operator = $("#editOperator").val();
//var BakOperator = $("#editBakOperator").val();
if(ModuleName.length==0 ){
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">模块名不能为空</span>'
});
diaCopyMsg.show($("#editmoduleModuleName").get(0));
return ;
}
if(ModuleName.length>60){
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">模块名过长</span>'
});
diaCopyMsg.show($("#editmoduleModuleName").get(0));
return ;
}
$.post("/zjz_work_cmdb/cmdbmoule/editModule",
{ApplicationID:ApplicationID,ModuleID:ModuleID,ModuleName:ModuleName}
,function(result) {
//rere = $.parseJSON(result);
rere = result;
if (rere.success == false) {
CC.hostConf.showWindow(rere.errInfo,'notice');
return;
}
else {
CC.hostConf.showWindow('更新模块成功!','success');
setTimeout(function(){window.location.reload();},1000);
return;
}
});
});
//关联监控修改
$("#newmodulefalcon").on('click',function(e){
var ApplicationID = cookie.get('defaultAppId');
var ModuleID = $("#editmoduleModuleName").attr("moduleid");
var ModuleName = $.trim($("#editmoduleModuleName").val());
//$.post("/zjz_work_cmdb/cmdbmoule/editModule",
// {ApplicationID:ApplicationID,ModuleID:ModuleID,ModuleName:ModuleName}
// ,function(result) {
// rere = result;
// if (rere.success == false) {
// CC.hostConf.showWindow(rere.errInfo,'notice');
// return;
// }
// else {
// CC.hostConf.showWindow('更新模块成功!','success');
// setTimeout(function(){window.location.reload();},1000);
// return;
// }
// });
});
}
})(window);
$(function() {
$(".c-host-switch").click(function(){
if($('.c-host-switch-img').hasClass("glyphicon-menu-left")){
$('.c-host-switch-img').removeClass('glyphicon-menu-left').addClass('glyphicon-menu-right');
$(".host-sidebar-left").animate({"width": "0px"}, "fast");
$(".host-main-right").animate({"right": "+=320px","width": "+=320px"}, "fast");
}else if($('.c-host-switch-img').hasClass("glyphicon-menu-right")){
$('.c-host-switch-img').removeClass('glyphicon-menu-right').addClass('glyphicon-menu-left');
$(".host-sidebar-left").animate({"width": "320px"}, "fast");
$(".host-main-right").animate({"right": "-=320px","width": "-=320px"}, "fast");
}
})
$("[name='my-checkbox']").bootstrapSwitch();
$("#new_set_sersta input").bootstrapSwitch(
{onText: '开放',
offText: '关闭'}
);
$(".c-conf-tree").mCustomScrollbar({
//setHeight: 400, //设置高度
theme: "minimal-dark" //设置风格
});
$('#date1').kendoDatePicker({
value : new Date(),
format : "yyyy-MM-dd"
});
$('#date2').kendoDatePicker({
value : new Date(),
format : "yyyy-MM-dd"
});
CC.hostConf.init();
})<file_sep>/src/github.com/shwinpiocess/cc/static/js/zjzcheckhost.js
$(document).ready(function() {
$('.check-more01').click(function(){
var tr = $(this).closest('li');
var HostID = tr.find('.HostID').val();
$.post("/zjz_work_cmdb/cmdb/checkmore_cmdbhost01",
{
HostID:HostID,
}
,function(result) {
var rere_msg=""
rere = result;
if(rere.success == false)
{
showWindows(rere.errInfo,'notice');
return;
}
else
{
$.each(rere.data[0],function(index, value){
//console.log('属性 ' + index + ', 值: ' + value);
rere_msg=rere_msg + index + ', 值: ' + value +'<br>'
});
showWindows(rere_msg,'show_msg');
//setTimeout(function(){window.location.reload();},3000);
return;
}
});
})
$('.check-more02').click(function(){
var tr = $(this).closest('li');
var HostID = tr.find('.HostID').val();
var Hostname = tr.find('.Hostname').val();
$.post("/zjz_work_cmdb/cmdb/checkmore_cmdbhost02",
{
HostID:HostID,
Hostname:Hostname
}
,function(result) {
var rere_msg=""
rere = result;
if(rere.success == false)
{
showWindows(rere.errInfo,'notice');
return;
}
else
{
$.each(rere.data[0],function(index, value){
//console.log('属性 ' + index + ', 值: ' + value);
rere_msg=rere_msg + index +": "+ value +'<br>'
//rere_msg=rere_msg + index + ', 值: ' + value +'<br>'
});
showWindows(rere_msg,'show_msg');
//setTimeout(function(){window.location.reload();},5000);
return;
}
});
})
$('.check-more03').click(function(){
var tr = $(this).closest('li');
var HostID = tr.find('.HostID').val();
$.post("/zjz_work_cmdb/cmdb/checkmore_cmdbhost01",
{
HostID:HostID,
}
,function(result) {
var rere_msg=""
rere = result;
if(rere.success == false)
{
showWindows(rere.errInfo,'notice');
return;
}
else
{
$.each(rere.data[0],function(index, value){
//console.log('属性 ' + index + ', 值: ' + value);
rere_msg=rere_msg + index + ', 值: ' + value +'<br>'
});
showWindows(rere_msg,'show_msg');
//setTimeout(function(){window.location.reload();},3000);
return;
}
});
})
$('.check-del01').click(function(){
var tr = $(this).closest('li');
var HostID = tr.find('.HostID').val();
$.post("/zjz_work_cmdb/cmdb/DelCmdbHost",
{
HostID:HostID,
}
,function(result) {
rere = result;
if(rere.success == false)
{
showWindows(rere.errInfo,'notice');
return;
}
else
{
showWindows('删除成功','success');
setTimeout(function(){window.location.reload();},1000);
return;
}
});
})
$('.check-update02').click(function(){
var tr = $(this).closest('li');
var HostID = tr.find('.HostID').val();
var Hostname = tr.find('.Hostname').val();
$.post("/zjz_work_cmdb/cmdb/cmdbhost_checkupdate02",
{
HostID:HostID,
Hostname:Hostname,
}
,function(result) {
rere = result;
if(rere.success == false)
{
showWindows(rere.errInfo,'notice');
return;
}
else
{
showWindows('更新成功','success');
setTimeout(function(){window.location.reload();},1000);
return;
}
});
})
function showWindows(Msg,level)
{
if(level=='show_msg')
{
var d = dialog({
width: 700,
title: "详细信息",
content: '<div class="c-dialogdiv2"><i class="c-dialogimg-success"></i>'+Msg+'</div>'
});
d.show();
}
else if(level=='success')
{
var d = dialog({
width: 150,
content: '<div class="c-dialogdiv2"><i class="c-dialogimg-success"></i>'+Msg+'</div>'
});
d.show();
}
else if(level =='error')
{
var d = dialog({
title:'错误',
width:300,
okValue:"确定",
ok:function(){},
content: '<div class="c-dialogdiv2"><i class="c-dialogimg-failure"></i>'+Msg+'</div>'
});
d.showModal();
}
else
{
var d = dialog({
title:'警告',
width:300,
okValue:"确定",
ok:function(){},
content: '<div class="c-dialogdiv2"><i class="c-dialogimg-prompt"></i>'+Msg+'</div>'
});
d.showModal();
}
}
});<file_sep>/src/github.com/shwinpiocess/cc/static/js/zjzapp.index.js
$(document).ready(function() {
function format(state) {
return state.id+"<span class='select-info'>("+state.text+")</span>";
}
$('.app-edit').click(function(){
var tr = $(this).closest('tr');
$(this).hide();
$(this).siblings().filter('a[name="deletes"]').hide();
$(this).siblings().filter('a[name="saves"]').show();
$(this).siblings().filter('a[name="cancels"]').show();
var domain_value=tr.find('.domain_name').text();
var scheme_value=tr.find('.scheme_name').text();
var business_value=tr.find('.business_name').text();
var owner_value=tr.find('.owner_name').text();
var department_value=tr.find('.department_name').text();
var remark_value=tr.find('.remark_name').text();
tr.find('.domain_name').html('<input type="text" value="'+domain_value+'" style="width:100%;height:36px;" class="k-input k-textbox domain_name_input">');
tr.find(".domain_name .k-input").attr('placeholder','请输入域名');
tr.find(".domain_name .k-input").attr('maxlength','32');
tr.find('.scheme_name').html('<input type="text" value="'+scheme_value+'" style="width:100%;height:36px;" class="k-input k-textbox scheme_name_input">');
tr.find(".scheme_name .k-input").attr('placeholder','请输入系统名');
tr.find(".scheme_name .k-input").attr('maxlength','32');
tr.find('.business_name').html('<input type="text" value="'+business_value+'" style="width:100%;height:36px;" class="k-input k-textbox business_name_input">');
tr.find(".business_name .k-input").attr('placeholder','请输入业务名');
tr.find(".business_name .k-input").attr('maxlength','32');
tr.find('.owner_name').html('<input type="text" value="'+owner_value+'" style="width:100%;height:36px;" class="k-input k-textbox owner_name_input">');
tr.find(".owner_name .k-input").attr('placeholder','请输入责任人');
tr.find(".owner_name .k-input").attr('maxlength','32');
tr.find('.department_name').html('<input type="text" value="'+department_value+'" style="width:100%;height:36px;" class="k-input k-textbox department_name_input">');
tr.find(".department_name .k-input").attr('placeholder','请输入所属部门');
tr.find(".department_name .k-input").attr('maxlength','32');
tr.find('.remark_name').html('<input type="text" value="'+remark_value+'" style="width:100%;height:36px;" class="k-input k-textbox remark_name_input">');
tr.find(".remark_name .k-input").attr('placeholder','请输入备注');
tr.find(".remark_name .k-input").attr('maxlength','32');
})
$('.app-cancel').click(function(){
var tr = $(this).closest('tr');
Domainname=tr.find('.Domainname').val();
Schemename=tr.find('.Schemename').val();
ApplicationName = tr.find('.ApplicationName').val();
Ownername = tr.find('.Ownername').val();
Departmentname=tr.find('.Departmentname').val();
Remarkname=tr.find('.Remarkname').val();
tr.find('.domain_name').html(Domainname);
tr.find('.scheme_name').html(Schemename);
tr.find('.business_name').html(ApplicationName);
tr.find('.owner_name').html(Ownername);
tr.find('.department_name').html(Departmentname);
tr.find('.remark_name').html(Remarkname);
$(this).hide();
$(this).siblings().filter('a[name="edits"]').show();
$(this).siblings().filter('a[name="deletes"]').show();
$(this).siblings().filter('a[name="saves"]').hide();
})
$('.app-save').click(function(){
var tr = $(this).closest('tr');
var nameDom4 = tr.find('.domain_name');
var domainName = $.trim(nameDom4.find('input').val());
var nameDom5 = tr.find('.scheme_name');
var schemeName = $.trim(nameDom5.find('input').val());
var nameDom = tr.find('.business_name');
var businessName = $.trim(nameDom.find('input').val());
var ApplicationID = tr.find('.ApplicationID').val();
var ApplicationName = $("#AppName").val();
var nameDom1 = tr.find('.owner_name');
var ownerName = $.trim(nameDom1.find('input').val());
var nameDom2 = tr.find('.department_name');
var departmentName = $.trim(nameDom2.find('input').val());
var nameDom3 = tr.find('.remark_name');
var remarkName = $.trim(nameDom3.find('input').val());
if((domainName.length> 16) || (domainName.length== 0)) {
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">请输入域名称并限制在16位字符</span>'
});
diaCopyMsg.show(tr.find('.domain_name').find('input').get(0));
return ;
}
if((schemeName.length> 16) || (schemeName.length== 0)) {
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">请输入系统名称并限制在16位字符</span>'
});
diaCopyMsg.show(tr.find('.scheme_name').find('input').get(0));
return ;
}
if((businessName.length> 16) || (businessName.length== 0)) {
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">请输入业务名称并限制在16位字符</span>'
});
diaCopyMsg.show(tr.find('.business_name').find('input').get(0));
return ;
}
if((ownerName.length> 16) || (ownerName.length== 0)) {
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">请输入责任人并限制在16位字符</span>'
});
diaCopyMsg.show(tr.find('.owner_name').find('input').get(0));
return ;
}
if((departmentName.length> 16) || (departmentName.length== 0)) {
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">请输入所属部门并限制在16位字符</span>'
});
diaCopyMsg.show(tr.find('.department_name').find('input').get(0));
return ;
}
if(remarkName.length> 32) {
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">备注请限制在32位字符</span>'
});
diaCopyMsg.show(tr.find('.remark_name').find('input').get(0));
return ;
}
$.post("/zjz_work_cmdb/cmdbapp/editapp",
{
Domain:domainName,
Scheme:schemeName,
ApplicationName:businessName,
ApplicationID:ApplicationID,
Owner:ownerName,
Department:departmentName,
Remark:remarkName
}
,function(result) {
//rere = $.parseJSON(result);
rere = result;
if(rere.success == false)
{
showWindows(rere.errInfo,'notice');
return;
}
else
{
showWindows('修改成功','success');
setTimeout(function(){window.location.reload();},1000);
return;
}
});
})
$('.app-delete').click(function(e){
var gridBatDel = dialog({
title:'确认',
width:250,
content: '是否删除选中业务',
okValue:"确定",
cancelValue:"取消",
ok:function (){
var tr = $(e.target).closest('tr');
var ApplicationID = tr.find('.ApplicationID').val();
$.post("/zjz_work_cmdb/cmdbapp/delapp",
{ApplicationID:ApplicationID}
,function(result) {
// rere = $.parseJSON(result);
rere = result;
if(rere.success == false)
{
showWindows(rere.errInfo,'notice');
return;
}
else
{
showWindows("删除成功!",'success');
setTimeout(function(){window.location.reload();},1000);
return;
}
});
},
cancel: function () {
}
});
gridBatDel.showModal();
})
$('.app-chooseapp').click(function(e){
var gridBatDel = dialog({
title:'确认',
width:250,
content: '是否重新选择默认业务',
okValue:"确定",
cancelValue:"取消",
ok:function (){
var tr = $(e.target).closest('tr');
var ApplicationID = tr.find('.ApplicationID').val();
$.post("/zjz_work_cmdb/cmdbapp/setDefaultApp",
{ApplicationID:ApplicationID}
,function(result) {
// rere = $.parseJSON(result);
rere = result;
if(rere.success == false)
{
showWindows(rere.errInfo,'notice');
return;
}
else
{
showWindows("选择成功!",'success');
setTimeout(function(){window.location.reload();},1000);
return;
}
});
},
cancel: function () {
}
});
gridBatDel.showModal();
})
function showWindows(Msg,level)
{
if(level=='success')
{
var d = dialog({
width: 150,
content: '<div class="c-dialogdiv2"><i class="c-dialogimg-success"></i>'+Msg+'</div>'
});
d.show();
}
else if(level =='error')
{
var d = dialog({
title:'错误',
width:300,
okValue:"确定",
ok:function(){},
content: '<div class="c-dialogdiv2"><i class="c-dialogimg-failure"></i>'+Msg+'</div>'
});
d.showModal();
}
else
{
var d = dialog({
title:'警告',
width:300,
okValue:"确定",
ok:function(){},
content: '<div class="c-dialogdiv2"><i class="c-dialogimg-prompt"></i>'+Msg+'</div>'
});
d.showModal();
}
}
});
<file_sep>/src/gitcafe.com/ops/meta/http/proc.go
package http
import (
"fmt"
"gitcafe.com/ops/meta/store"
"net/http"
"strings"
"time"
)
func configProcRoutes() {
http.HandleFunc("/status/json/", func(w http.ResponseWriter, r *http.Request) {
agentName := r.URL.Path[len("/status/json/"):]
if agentName == "" {
http.Error(w, "agent name is blank", http.StatusBadRequest)
return
}
data := store.HostAgents.Status(agentName)
RenderJson(w, data)
})
http.HandleFunc("/status/text/", func(w http.ResponseWriter, r *http.Request) {
agentName := r.URL.Path[len("/status/text/"):]
if agentName == "" {
http.Error(w, "agent name is blank", http.StatusBadRequest)
return
}
data := store.HostAgents.Status(agentName)
arr := make([]string, len(data))
i := 0
for hostname, ra := range data {
if ra != nil {
arr[i] = fmt.Sprintf(
"%s %s %s %v %s\n",
hostname,
ra.Version,
ra.Status,
ra.Timestamp,
time.Unix(ra.Timestamp, 0).Format("2006-01-02 15:04:05"),
)
} else {
arr[i] = fmt.Sprintf("%s not found\n", hostname)
}
i++
}
w.Write([]byte(strings.Join(arr, "")))
})
http.HandleFunc("/cmdbstatus/json/", func(w http.ResponseWriter, r *http.Request) {
/*
agentName := r.URL.Path[len("/cmdbstatus/json/"):]
if agentName == "" {
http.Error(w, "agent name is blank", http.StatusBadRequest)
return
}
*/
data := store.CmdbA.Status()
RenderJson(w, data)
})
http.HandleFunc("/cmdbstatus/text/", func(w http.ResponseWriter, r *http.Request) {
data := store.CmdbA.Status()
arr := make([]string, len(data))
i := 0
for hostname, ra := range data {
if ra != nil {
//publicip":" 20.26.12.206/24","privateip":"","osname":"SUSE11SP2","cpunum":2,"cputype":"AMD Opteron(tm) Processor 6140","memsize":"1.96 GB","disksize":"45.26 GB","vminfo":"vmware","timestamp":146460280
arr[i] = fmt.Sprintf(
"%s %s %s %s %d %s %s %s %s \n",
hostname,
ra.PublicIP,
ra.PrivateIP,
ra.OSName,
ra.Cpunum,
ra.Cputype,
ra.Memsize,
ra.Disksize,
//ra.Ifvmware,
time.Unix(ra.Timestamp, 0).Format("2006-01-02 15:04:05"),
)
} else {
arr[i] = fmt.Sprintf("%s not found\n", hostname)
}
i++
}
w.Write([]byte(strings.Join(arr, "")))
})
}
func configDelhnRoutes() {
http.HandleFunc("/stop/hn/", func(w http.ResponseWriter, r *http.Request) {
hName := r.URL.Path[len("/stop/hn/"):]
if hName == "" {
http.Error(w, "host name is blank", http.StatusBadRequest)
return
}
_,exist:=store.HostAgents.Get(hName)
if exist {
store.HostAgents.Delete(hName)
w.Write([]byte(hName+" is Deleted"))
} else {
http.Error(w, "host name is wrong", http.StatusBadRequest)
return
}
})
}
<file_sep>/src/gitcafe.com/ops/common/utils/ifvmware.go
package utils
import (
"log"
"os/exec"
"strings"
"strconv"
)
//Vminfo
func Ifvmware()(string,error) {
lsCmd := exec.Command("bash", "-c", "lscpu | grep -i vmware | wc -l")
lsOut, err := lsCmd.Output()
if err != nil {
log.Println("ERROR: ifvmware() fail", err)
}
//fmt.Println(string(lsOut))
value:=strings.Trim(string(lsOut),"\n")
//fmt.Println("value:",value)
number, _ := strconv.ParseInt(value, 10, 0)
if number==1 {
return "vmware",nil
}
return "",nil
}
<file_sep>/src/github.com/shwinpiocess/cc/controllers/cmdbhost.go
package controllers
import (
//"path"
"fmt"
//"encoding/json"
"errors"
"strconv"
"strings"
"github.com/shwinpiocess/cc/models"
"gitcafe.com/ops/meta/store"
"gitcafe.com/ops/common/model"
"time"
)
// oprations for Host
type CmdbController struct {
BaseController
}
func (this *CmdbController) CmdbImport() {
this.TplName = "cmdb/zjzImport.html"
}
func (this *CmdbController) Detail() {
this.TplName = "cmdb/detail.html"
}
func (this *CmdbController) Check() {
var fields []string
var sortby []string
var order []string
var limit int64 = 0
var offset int64 = 0
var cmdbhostquery map[string]interface{} = make(map[string]interface{})
fields=append(fields,"Hostname")
fields=append(fields,"HostID")
//store in memory
ss:=make(map[string]int)
data := store.CmdbA.Status()
for k,_:= range data {
ss[k]=1
}
//store in mysql
var cmdbcheck_hosts01 []interface{}
cmdbhosts,_:=models.GetCmdbAllHost(cmdbhostquery,fields, sortby, order, offset, limit)
for _,v:=range cmdbhosts {
cmh:=fmt.Sprintf("%s",v.(map[string]interface{})["Hostname"])
_, exists := ss[cmh]
if(exists==false) {
cmdbcheck_hosts01=append(cmdbcheck_hosts01,v)
}
}
fmt.Printf("cmdbcheck01 %#v\n",cmdbcheck_hosts01)
//add by 0710
ss1:=make(map[string]*model.CmdbAgent)
for k1,v1:=range data {
//ss1[k1]=v1.PublicIP
ss1[k1]=v1
}
var fields1 []string
fields1=append(fields1,"Hostname")
fields1=append(fields1,"HostID")
fields1=append(fields1,"PublicIP")
fields1=append(fields1,"PrivateIP")
fields1=append(fields1,"OSName")
fields1=append(fields1,"Cpunum")
fields1=append(fields1,"Cputype")
fields1=append(fields1,"Memsize")
fields1=append(fields1,"Disksize")
fields1=append(fields1,"Vminfo")
var cmdbcheck_hosts02 []interface{}
cmdbhosts1,_:=models.GetCmdbAllHost(cmdbhostquery,fields1, sortby, order, offset, limit)
for _,v:=range cmdbhosts1 {
cmh:=fmt.Sprintf("%s",v.(map[string]interface{})["Hostname"])
cmpublicip:=fmt.Sprintf("%s",v.(map[string]interface{})["PublicIP"])
cmprivateip:=fmt.Sprintf("%s",v.(map[string]interface{})["PrivateIP"])
cmosname:=fmt.Sprintf("%s",v.(map[string]interface{})["OSName"])
cmcpunum:=v.(map[string]interface{})["Cpunum"]
cmcputype:=fmt.Sprintf("%s",v.(map[string]interface{})["Cputype"])
cmmemsize:=fmt.Sprintf("%s",v.(map[string]interface{})["Memsize"])
cmdisksize:=fmt.Sprintf("%s",v.(map[string]interface{})["Disksize"])
cmvminfo:=fmt.Sprintf("%s",v.(map[string]interface{})["Vminfo"])
_,exists := ss1[cmh]
if (exists==true) {
switch {
case !strings.EqualFold(cmpublicip, ss1[cmh].PublicIP ):
//fmt.Printf("cmpublicip %#v\n",cmpublicip)
//fmt.Printf("ss1 %#v\n",ss1[cmh].PublicIP)
//fmt.Println(cmh,"publicip not equal")
cmdbcheck_hosts02=append(cmdbcheck_hosts02,v)
case !strings.EqualFold(cmprivateip,ss1[cmh].PrivateIP):
//fmt.Println(cmh,"privateip not equal")
cmdbcheck_hosts02=append(cmdbcheck_hosts02,v)
case !strings.EqualFold(cmosname,ss1[cmh].OSName):
//fmt.Println(cmh,"osname not equal")
cmdbcheck_hosts02=append(cmdbcheck_hosts02,v)
case !(cmcpunum==ss1[cmh].Cpunum):
//fmt.Println(cmh,"cpunum not equal")
cmdbcheck_hosts02=append(cmdbcheck_hosts02,v)
case !strings.EqualFold(cmcputype,ss1[cmh].Cputype):
//fmt.Println(cmh,"cputype not equal")
cmdbcheck_hosts02=append(cmdbcheck_hosts02,v)
case !strings.EqualFold(cmmemsize,ss1[cmh].Memsize):
//fmt.Println(cmh,"memsize not equal")
cmdbcheck_hosts02=append(cmdbcheck_hosts02,v)
case !strings.EqualFold(cmdisksize,ss1[cmh].Disksize):
//fmt.Println(cmh,"disksize not equal")
cmdbcheck_hosts02=append(cmdbcheck_hosts02,v)
case !strings.EqualFold(cmvminfo,ss1[cmh].Vminfo):
//fmt.Println(cmh,"vminfo not equal")
cmdbcheck_hosts02=append(cmdbcheck_hosts02,v)
//default:
// fmt.Println(cmh, "equal")
}
}
}
//add by 0711 check03
var cmdbcheck_hosts03 []interface{}
ss3:=make(map[string]int)
for k3,v3:=range data {
//ss1[k1]=v1.PublicIP
if (v3.Timestamp < (time.Now().Unix() - 3600)) {
ss3[k3]=1
}
}
var fields3 []string
fields3=append(fields3,"Hostname")
fields3=append(fields3,"HostID")
cmdbhosts3,_:=models.GetCmdbAllHost(cmdbhostquery,fields3, sortby, order, offset, limit)
for _,vv3:=range cmdbhosts3 {
cmh3:=fmt.Sprintf("%s",vv3.(map[string]interface{})["Hostname"])
_, exists := ss3[cmh3]
if(exists==true) {
cmdbcheck_hosts03=append(cmdbcheck_hosts03,vv3)
}
}
this.Data["cmdbcheck01"] = cmdbcheck_hosts01
this.Data["cmdbcheck02"] = cmdbcheck_hosts02
this.Data["cmdbcheck03"] = cmdbcheck_hosts03
this.TplName = "cmdb/check.html"
}
func (this *CmdbController) GetCmdbHost() {
isDistributed, _ := this.GetBool("IsDistributed")
//source := this.GetString("Source")
applicationId := this.GetString("ApplicationID")
var fields []string
var sortby []string
var order []string
var query = make(map[string]interface{})
var limit int64 = 0
var offset int64 = 0
query["is_distributed"] = isDistributed
//query["source"] = source
if isDistributed {
query["application_id"] = applicationId
}
fmt.Println("query=", query)
// fields: col1,col2,entity.col3
if v := this.GetString("fields"); v != "" {
fields = strings.Split(v, ",")
}
// limit: 10 (default is 10)
if v, err := this.GetInt64("limit"); err == nil {
limit = v
}
// offset: 0 (default is 0)
if v, err := this.GetInt64("offset"); err == nil {
offset = v
}
// sortby: col1,col2
if v := this.GetString("sortby"); v != "" {
sortby = strings.Split(v, ",")
}
// order: desc,asc
if v := this.GetString("order"); v != "" {
order = strings.Split(v, ",")
}
// query: k:v,k:v
if v := this.GetString("query"); v != "" {
for _, cond := range strings.Split(v, ",") {
kv := strings.Split(cond, ":")
if len(kv) != 2 {
this.Data["json"] = errors.New("Error: invalid query key/value pair")
this.ServeJSON()
return
}
k, v := kv[0], kv[1]
query[k] = v
}
}
fmt.Println("##query:",query,"##fields:",fields,"##sortby",sortby,"##order",order,"#offset",offset,"##limit",limit)
l, err := models.GetCmdbAllHost(query, fields, sortby, order, offset, limit)
out := make(map[string]interface{})
if err != nil {
out["success"] = false
this.jsonResult(out)
} else {
out["success"] = true
out["data"] = l
out["total"] = len(l)
this.jsonResult(out)
}
}
//CMDB DELETE
// 删除主机
func (this *CmdbController) DelCmdbHost() {
idStr := this.GetString("HostID")
var ids []int
for _, v := range strings.Split(idStr, ",") {
if id, err := strconv.Atoi(v); err == nil {
ids = append(ids, id)
}
}
out := make(map[string]interface{})
if _, err := models.DeleteCmdbHosts(ids); err == nil {
out["success"] = true
out["message"] = "删除成功!"
this.jsonResult(out)
} else {
out["success"] = false
out["errInfo"] = err.Error()
this.jsonResult(out)
}
}
//CMDB distribute
// 分配主机
func (this *CmdbController) CmdbDistribute() {
// HostID:29,30
// ApplicationID:4043
// ToApplicationID:4041
out := make(map[string]interface{})
idStr := this.GetString("HostID")
fmt.Println("##idStr###",idStr)
var ids []int
for _, v := range strings.Split(idStr, ",") {
if id, err := strconv.Atoi(v); err == nil {
ids = append(ids, id)
}
}
if toApplicationID, err := this.GetInt("ToApplicationID"); err != nil {
fmt.Println("toappid",toApplicationID)
out["success"] = false
out["errInfo"] = err.Error()
this.jsonResult(out)
} else {
if _, err := models.UpdateCmdbHostToApp(ids, toApplicationID); err != nil {
fmt.Println("ids toappid",ids,toApplicationID)
out["success"] = false
out["errInfo"] = err.Error()
this.jsonResult(out)
}
out["success"] = true
out["message"] = "分配成功"
this.jsonResult(out)
}
}
//CMDB host
func (this *CmdbController) CmdbQuery() {
//fmt.Println(this.defaultCmdbApp.Id)
info, options, _ := models.GetCmdbEmptyById(this.defaultCmdbApp.Id)
fmt.Println("#######control info######",info)
fmt.Println("#######control options#####",options)
this.Data["data"] = info
this.Data["options"] = options
this.TplName = "cmdb/hostQuery.html"
}
func (this *CmdbController) GetCmdbHostById() {
out := make(map[string]interface{})
// var data []interface{}
var fields []string
var sortby []string
var order []string
var query = make(map[string]interface{})
var limit int64 = 0
var offset int64 = 0
appId := this.GetString("ApplicationID")
//setId := this.GetString("SetID")
modId := this.GetString("ModuleID")
query["application_id"] = appId
/*
if setId != "" {
query["set_id"] = setId
}
*/
if modId != "" {
query["module_id__in"] = strings.Split(modId, ",")
}
data, _ := models.GetCmdbAllHost(query, fields, sortby, order, offset, limit)
out["data"] = data
out["total"] = len(data)
this.jsonResult(out)
}
//0708
func (this *CmdbController) GetCmdbHostBycheckhid() {
out := make(map[string]interface{})
var fields []string
var sortby []string
var order []string
var query = make(map[string]interface{})
var limit int64 = 0
var offset int64 = 0
Checkhid := this.GetString("HostID")
query["HostID"] = Checkhid
data, _ := models.GetCmdbAllHost(query, fields, sortby, order, offset, limit)
out["data"] = data
out["total"] = len(data)
this.jsonResult(out)
}
//0711
func (this *CmdbController) GetCmdbaAgentBycheckhid() {
out := make(map[string]interface{})
var fields []string
var sortby []string
var order []string
var query = make(map[string]interface{})
var limit int64 = 0
var offset int64 = 0
Checkhid := this.GetString("HostID")
Checkhn := this.GetString("Hostname")
query["HostID"] = Checkhid
data, _ := models.GetCmdbAllHost(query, fields, sortby, order, offset, limit)
data1 := store.CmdbA.Status()
//fmt.Printf("data %#v\n",data[0])
//fmt.Printf("data %#v\n",data[0].(models.CmdbHost).PublicIP)
//fmt.Printf("data1 %#v\n",data1[Checkhn].PublicIP)
var out_data = make(map[string]interface{})
var ls_out_data []interface{}
out_data["Hostname"]=Checkhn
out_data["PublicIP"]="新采集: "+data1[Checkhn].PublicIP+" ; "+"历史值: "+data[0].(models.CmdbHost).PublicIP
out_data["PrivateIP"]="新采集: "+data1[Checkhn].PrivateIP+" ; "+"历史值: "+data[0].(models.CmdbHost).PrivateIP
out_data["OSName"]="新采集: "+data1[Checkhn].OSName+" ; "+"历史值: "+data[0].(models.CmdbHost).OSName
out_data["Cpunum"]="新采集: "+fmt.Sprintf("%d",data1[Checkhn].Cpunum)+" ; "+"历史值: "+fmt.Sprintf("%d",data[0].(models.CmdbHost).Cpunum)
out_data["Cputype"]="新采集: "+data1[Checkhn].Cputype+" ; "+"历史值: "+data[0].(models.CmdbHost).Cputype
out_data["Memsize"]="新采集: "+data1[Checkhn].Memsize+" ; "+"历史值: "+data[0].(models.CmdbHost).Memsize
out_data["Disksize"]="新采集: "+data1[Checkhn].Disksize+" ; "+"历史值: "+data[0].(models.CmdbHost).Disksize
out_data["Vminfo"]="新采集: "+data1[Checkhn].Vminfo+" ; "+"历史值: "+data[0].(models.CmdbHost).Vminfo
out_data["ApplicationName"]=data[0].(models.CmdbHost).ApplicationName
out_data["ModuleName"]=data[0].(models.CmdbHost).ModuleName
out_data["Parentserver"]=data[0].(models.CmdbHost).Parentserver
out_data["AssetID"]=data[0].(models.CmdbHost).AssetID
out_data["Location"]=data[0].(models.CmdbHost).Location
out_data["Cabinets"]=data[0].(models.CmdbHost).Cabinets
out_data["Silo"]=data[0].(models.CmdbHost).Silo
out_data["Pilo"]=data[0].(models.CmdbHost).Pilo
out_data["Sn"]=data[0].(models.CmdbHost).Sn
ls_out_data=append(ls_out_data,out_data)
out["total"] = len(ls_out_data)
out["data"] = ls_out_data
this.jsonResult(out)
}
func (this *CmdbController) GetCmdbTopoTree4view() {
out := make(map[string]interface{})
if appID, err := this.GetInt("ApplicationID"); err != nil {
out["success"] = false
out["message"] = "参数不合法!"
this.jsonResult(out)
} else {
if data, _, err := models.GetCmdbEmptyById(appID); err != nil {
out["success"] = false
out["message"] = err
this.jsonResult(out)
} else {
out = data
this.jsonResult(out)
}
}
}
// 转移主机
func (this *CmdbController) ModCmdbHostModule() {
// ApplicationID:4050
// ModuleID:40
// HostID:41,42,43,44,45,46,47,48,49
var appID int
var moduleID int
var hostIds []int
var id int
var err error
out := make(map[string]interface{})
if appID, err = this.GetInt("ApplicationID"); err != nil {
out["success"] = false
out["message"] = "参数ApplicationID格式不正确"
this.jsonResult(out)
}
if moduleID, err = this.GetInt("ModuleID"); err != nil {
out["success"] = false
out["message"] = "参数ModuleID格式不正确"
this.jsonResult(out)
}
idStr := this.GetString("HostID")
for _, v := range strings.Split(idStr, ",") {
if id, err = strconv.Atoi(v); err != nil {
out["success"] = false
out["message"] = "参数HostID格式不正确"
this.jsonResult(out)
} else {
hostIds = append(hostIds, id)
}
}
//fmt.Println("##mod module#",appID,moduleID,hostIds)
if _, err = models.ModCmdbHostModule(appID, moduleID, hostIds); err != nil {
out["success"] = false
out["message"] = err.Error()
this.jsonResult(out)
} else {
out["success"] = true
out["message"] = "转移成功"
this.jsonResult(out)
}
}
// 移至空闲机/故障机
func (this *CmdbController) DelCmdbHostModule() {
out := make(map[string]interface{})
// ApplicationID:4050
// HostID:41,42,45,46,47,48,49
var appId int
var hostIds []int
var hostId int
var moduleName string
var err error
if appId, err = this.GetInt("ApplicationID"); err != nil {
out["success"] = false
out["message"] = "参数ApplicationID格式不正确"
this.jsonResult(out)
}
status := this.GetString("Status")
if status == "1" {
moduleName = "故障维护状态"
} else {
moduleName = "空闲状态"
}
for _, v := range strings.Split(this.GetString("HostID"), ",") {
if hostId, err = strconv.Atoi(v); err != nil {
out["success"] = false
out["message"] = "参数HostID格式不正确"
this.jsonResult(out)
} else {
hostIds = append(hostIds, hostId)
}
}
if _, err = models.DelCmdbHostModule(appId, moduleName, hostIds); err != nil {
out["success"] = false
out["message"] = err.Error()
this.jsonResult(out)
} else {
out["success"] = true
out["message"] = "转移成功"
this.jsonResult(out)
}
}
// 上交主机
func (this *CmdbController) ResCmdbHostModule() {
// ApplicationID:4048
// HostID:34
out := make(map[string]interface{})
idStr := this.GetString("HostID")
var ids []int
for _, v := range strings.Split(idStr, ",") {
if id, err := strconv.Atoi(v); err == nil {
ids = append(ids, id)
}
}
if _, err := models.ResCmdbHostModule(ids); err != nil {
out["success"] = false
out["errInfo"] = err
out["message"] = err
this.jsonResult(out)
} else {
out["success"] = true
out["message"] = "上交成功"
this.jsonResult(out)
}
}
//0711 update memory to mysql
func (this *CmdbController) UpdateCmdbhostcheck02() {
if this.isPost() {
cmdbhost := new(models.CmdbHost)
Checkhn := this.GetString("Hostname")
data1 := store.CmdbA.Status()
cmdbhost.HostID,_ = this.GetInt("HostID")
cmdbhost.PublicIP = data1[Checkhn].PublicIP
cmdbhost.PrivateIP = data1[Checkhn].PrivateIP
cmdbhost.OSName = data1[Checkhn].OSName
cmdbhost.Cpunum = data1[Checkhn].Cpunum
cmdbhost.Cputype = data1[Checkhn].Cputype
cmdbhost.Memsize = data1[Checkhn].Memsize
cmdbhost.Disksize = data1[Checkhn].Disksize
cmdbhost.Vminfo = data1[Checkhn].Vminfo
out := make(map[string]interface{})
fmt.Println("###cmdbhost",cmdbhost)
if err := models.UpdateCmdbHostcheck02(cmdbhost); err != nil {
out["errInfo"] = err.Error()
out["success"] = false
out["errCode"] = "0006"
this.jsonResult(out)
} else {
out["success"] = true
this.jsonResult(out)
}
}
}
// 编辑主机属性
func (this *CmdbController) EditCmdbhost01() {
if this.isPost() {
cmdbhost := new(models.CmdbHost)
cmdbhost.AssetID = strings.TrimSpace(this.GetString("AssetID"))
cmdbhost.Location = strings.TrimSpace(this.GetString("Location_1"))
cmdbhost.Cabinets = strings.TrimSpace(this.GetString("Cabinets"))
cmdbhost.Silo = strings.TrimSpace(this.GetString("Silo"))
cmdbhost.Pilo = strings.TrimSpace(this.GetString("Pilo"))
cmdbhost.HostID,_ = this.GetInt("HostID")
out := make(map[string]interface{})
fmt.Println("###cmdbhost",cmdbhost)
if err := models.UpdateCmdbHostById01(cmdbhost); err != nil {
out["errInfo"] = err.Error()
out["success"] = false
out["errCode"] = "0006"
this.jsonResult(out)
} else {
out["success"] = true
this.jsonResult(out)
}
}
}
func (this *CmdbController) EditCmdbhost02() {
if this.isPost() {
cmdbhost := new(models.CmdbHost)
cmdbhost.HostID,_ = this.GetInt("HostID")
cmdbhost.Sn = strings.TrimSpace(this.GetString("Sn"))
out := make(map[string]interface{})
fmt.Println("###cmdbhost",cmdbhost)
if err := models.UpdateCmdbHostById02(cmdbhost); err != nil {
out["errInfo"] = err.Error()
out["success"] = false
out["errCode"] = "0006"
this.jsonResult(out)
} else {
out["success"] = true
this.jsonResult(out)
}
}
}
<file_sep>/src/github.com/shwinpiocess/cc/controllers/upload.go
package controllers
import (
//"errors"
//"flag"
"fmt"
//"os"
//"strings"
"github.com/tealeg/xlsx"
"github.com/shwinpiocess/cc/models"
)
type CmdbUploadController struct {
BaseController
}
func (this *CmdbUploadController) Upload() {
fmt.Println("--upload------------------------------------------->")
if err := UploadFromXLSXFile("static/upload/uploadapp.xlsx"); err != nil {
this.Ctx.Output.Body([]byte(err.Error()))
}else {
this.Ctx.Output.Body([]byte("success"))
}
}
func UploadFromXLSXFile(excelFileName string) error {
xlFile, error := xlsx.OpenFile(excelFileName)
if error != nil {
return error
}
sheet := xlFile.Sheets[0]
app_map :=make(map[string]int)
for _, row := range sheet.Rows {
if row != nil {
Domain, err := row.Cells[1].String()
Scheme, err := row.Cells[2].String()
ApplicationName, err := row.Cells[3].String()
Owner, err := row.Cells[7].String()
Department, err := row.Cells[8].String()
Remark, err := row.Cells[9].String()
fmt.Println(Domain,Scheme,ApplicationName,Owner,Department,Remark)
if err!=nil {
fmt.Println(err)
}
_,ok:=app_map[ApplicationName]
if ok != true {
cmdbapp:=new(models.CmdbApp)
cmdbapp.Domain = Domain
cmdbapp.Scheme = Scheme
cmdbapp.ApplicationName = ApplicationName
cmdbapp.Owner = Owner
cmdbapp.Department = Department
cmdbapp.Remark = Remark
if !models.ExistCmdbByName(ApplicationName) {
//models.CmdbAddApp(cmdbapp)
if Id, err := models.CmdbAddApp(cmdbapp); err != nil {
return err
} else {
m := new(models.CmdbModule)
m.ApplicationId = int(Id)
m.ModuleName = "空闲状态"
models.CmdbAddModule(m)
m2 := new(models.CmdbModule)
m2.ApplicationId = int(Id)
m2.ModuleName = "故障维护状态"
models.CmdbAddModule(m2)
}
}
}
app_map[ApplicationName]= 1
/*
for _, cell := range row.Cells {
str, err := cell.String()
if err != nil {
vals = append(vals, err.Error())
}
vals = append(vals, fmt.Sprintf("%q", str))
}
outputf(strings.Join(vals, *delimiter) + "\n")
*/
}
}
return nil
}
<file_sep>/src/gitcafe.com/ops/common/utils/osname.go
package utils
import (
"fmt"
"strings"
"bufio"
"os"
"regexp"
"io/ioutil"
)
var (
pat_ver = regexp.MustCompile(`\d+.*`)
)
func Exist(filename string) bool {
_, err := os.Stat(filename)
return err == nil || os.IsExist(err)
}
func ReadRelease() (string, string, error) {
var (
ID string
VERSION string
)
var err error
fpath := "/etc/redhat-release"
if Exist(fpath) {
err = readLine(fpath, func(line string) error {
lines := strings.SplitN(line, " ", 2)
if len(lines) == 2 {
ID = strings.ToLower(lines[0])
VERSION = pat_ver.FindString(lines[1])
return nil
} else {
return fmt.Errorf("invalid file format: %v, %d", lines, len(lines))
}
})
}
fpath = "/etc/SuSE-release"
if Exist(fpath) {
ID,VERSION:=getOs(fpath)
return ID,VERSION,nil
}
return ID, VERSION, err
}
func readLine(fname string, line func(string) error) error {
f, err := os.Open(fname[:])
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if err := line(scanner.Text()); err != nil {
return err
}
}
return scanner.Err()
}
func getOs(fpath string) (string,string) {
data, err := ioutil.ReadFile(fpath)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lines := strings.Split(string(data), "\n")
ID:=strings.Split(lines[0]," ")[0]
VERSION:=strings.Replace(strings.Split(lines[1],"=")[1]," ","",-1)+"SP"+strings.Replace(strings.Split(lines[2],"=")[1]," ","",-1)
return ID,VERSION
}
<file_sep>/src/gitcafe.com/ops/common/utils/cpunum.go
package utils
import (
"log"
"os/exec"
"strings"
//"strconv"
)
//Cpunum
func Cpunum()(string,error) {
lsCmd := exec.Command("bash", "-c", "lscpu | grep ^CPU\\(s\\):")
lsOut, err := lsCmd.Output()
if err != nil {
log.Println("ERROR: Cpunum() fail", err)
}
value:=strings.Trim(string(lsOut),"\n")
cpunum_str:=strings.Split(value,":")[1]
cpunum:=strings.TrimSpace(cpunum_str)
return cpunum,nil
}
<file_sep>/src/github.com/shwinpiocess/cc/controllers/voice.go
package controllers
import (
"strings"
"fmt"
"github.com/astaxie/beego"
"database/sql"
"os"
_ "github.com/mattn/go-oci8"
)
type VoiceController struct {
beego.Controller
}
func (this *VoiceController)Sendvoice() {
content := strings.TrimSpace(this.GetString("content", ""))
tos := strings.TrimSpace(this.GetString("tos", ""))
err := Voice(content,tos)
if err != nil {
this.Ctx.Output.Body([]byte(err.Error()))
} else {
this.Ctx.Output.Body([]byte("success"))
}
}
func Voice(content, tos string) error{
os.Setenv("NLS_LANG", "SIMPLIFIED CHINESE_CHINA.ZHS16GBK")
db, err := sql.Open("oci8", getvoiceDSN())
if err != nil {
fmt.Println(err)
return err
}
defer db.Close()
if err = voiceinsert(db,content,tos); err != nil {
fmt.Println(err)
return err
}
return nil
}
func getvoiceDSN() string {
var dsn string
if len(os.Args) > 1 {
dsn = os.Args[1]
if dsn != "" {
return dsn
}
}
//dsn = os.Getenv("GO_OCI8_CONNECT_STRING")
dsn="hp_dbspi/[email protected]/kfdb/kfdb1"
if dsn != "" {
return dsn
}
fmt.Fprintln(os.Stderr, `Please specifiy connection parameter in GO_OCI8_CONNECT_STRING environment variable,
or as the first argument! (The format is user/name@host:port/sid)`)
return "scott/tiger@XE"
}
func voiceinsert(db *sql.DB,content string,tos string) error {
// sql="insert into icdmain.iptca_interface_voice(id,alarmtext,tel1,tel2,tel3,indb_time)\
//values(to_char(dbmon.iptca.nextval),'icinga has alarm,please check',%s,13656685957,15158116209,sysdate)" %phoneNumber
if _, err := db.Exec("INSERT INTO " + "icdmain.iptca_interface_voice(id,alarmtext,tel1,tel2,tel3,indb_time)" +
" VALUES (to_char(dbmon.iptca.nextval)" + ",'"+content+"',"+tos+","+"sysdate)"); err != nil {
return err
}
return nil
}
<file_sep>/src/github.com/shwinpiocess/cc/controllers/weixin.go
package controllers
import (
"net/http"
"fmt"
"io/ioutil"
"bytes"
"encoding/json"
"reflect"
"strings"
"net/url"
"github.com/astaxie/beego"
"code.google.com/p/mahonia"
//"github.com/shwinpiocess/cc/models"
//"github.com/shwinpiocess/cc/utils"
//"net/smtp"
)
type WeixinController struct {
beego.Controller
}
type CustomServiceMsg struct {
ToUser string `json:"touser"`
Toparty string `json:"toparty"`
Totag string `json:"totag"`
MsgType string `json:"msgtype"`
Agentid int `json:"agentid"`
Text TextMsgContent `json:"text"`
Safe int `json:"safe"`
}
type TextMsgContent struct {
Content string `json:"content"`
}
func (this *WeixinController)Sendweixin() {
content := strings.TrimSpace(this.GetString("content", ""))
tos := strings.TrimSpace(this.GetString("tos", ""))
x:=Gettoken("<KEY>","<KEY>")
y:= map[string]interface{}{}
json.Unmarshal(x, &y)
tk:= y["access_token"]
str:=fmt.Sprintf("%s",reflect.ValueOf(tk))
toUser:=tos
toParty:="@all"
toTag:="@all"
msg:=content
agentId:=13
saFe:=0
bs,_:=pushCustomMsg(toUser,toParty,toTag,msg,agentId,saFe)
err:=Sendmsg(str,bs)
if err != nil {
this.Ctx.Output.Body([]byte(err.Error()))
} else {
this.Ctx.Output.Body([]byte("success"))
}
}
func Sendmsg(token string,body []byte) error{
//var enc mahonia.Encoder
/*
var dec mahonia.Decoder
dec = mahonia.NewDecoder("GB18030")
if ret1, ok := dec.ConvertStringOK(string(body)); ok {
fmt.Println("GBK to UTF-8: ", ret1, " bytes:", []byte(ret1))
}
*/
var proxy_addr *string
proxy_addr=new(string)
*proxy_addr = "http://10.70.237.188:8080"
transport := getTransportFieldURL(proxy_addr)
client := &http.Client{Transport : transport}
/*enc = mahonia.NewEncoder("GBK")
if ret, ok := enc.ConvertStringOK(string(body)); ok {
fmt.Println("UTF-8 to GBK: ", ret, " bytes: ", []byte(ret))
}
*/
req, _ := http.NewRequest("POST", "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token, bytes.NewBuffer(body))
//req, _ := http.NewRequest("POST", "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token, bytes.NewBuffer([]byte(ret)))
req.Header.Set("Content-Type", "application/json; encoding=gbk")
//req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
resp_body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(resp_body))
//}
return nil
}
func getTransportFieldURL(proxy_addr *string) (transport *http.Transport) {
url_i := url.URL{}
url_proxy, _ := url_i.Parse(*proxy_addr)
transport = &http.Transport{Proxy : http.ProxyURL(url_proxy)}
return
}
func Gettoken(user string, passwd string) (token []byte) {
var proxy_addr *string
proxy_addr=new(string)
*proxy_addr = "http://10.70.237.188:8080"
transport := getTransportFieldURL(proxy_addr)
client := &http.Client{Transport : transport}
body := []byte("corpid="+user+"&corpsecret="+passwd)
req, _ := http.NewRequest("POST", "https://qyapi.weixin.qq.com/cgi-bin/gettoken", bytes.NewBuffer(body))
req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
resp_body, _ := ioutil.ReadAll(resp.Body)
return resp_body
}
func pushCustomMsg(toUser,toParty,toTag,msg string, agentId,saFe int) (body []byte ,err error) {
var dec mahonia.Decoder
dec = mahonia.NewDecoder("GB18030")
if ret1, ok := dec.ConvertStringOK(msg); ok {
//fmt.Println("GBK to UTF-8: ", ret1, " bytes:", []byte(ret1))
/*
csMsg := &CustomServiceMsg{
ToUser: toUser,
Toparty: toParty,
Totag: toTag,
MsgType: "text",
Agentid: agentId,
Text: TextMsgContent{Content: msg},
Safe: saFe,
}
var x []byte
body, err = json.MarshalIndent(csMsg, " ", " ")
if err != nil {
return x,err
}
*/
str_agentId:=fmt.Sprintf("%d",agentId)
str_saFe:=fmt.Sprintf("%d",saFe)
body=[]byte("{ \"touser\": \""+toUser+"\", \"toparty\": \""+toParty+"\", \"totag\": \""+toTag+"\", \"msgtype\": \"text\", \"agentid\": "+str_agentId+", \"text\": { \"content\": \""+ret1+"\", }, \"safe\":"+str_saFe+", }")
}
return body,nil
}
<file_sep>/src/github.com/shwinpiocess/cc/controllers/base.go
package controllers
import (
"net/url"
"strconv"
"strings"
"time"
"fmt"
"github.com/astaxie/beego"
"github.com/shwinpiocess/cc/models"
//"github.com/shwinpiocess/cc/utils"
)
type BaseController struct {
beego.Controller
userId int
userName string
requestPath string
today string
firstApp bool
firstSet bool
firtModule bool
//defaultApp *models.App
defaultCmdbApp *models.CmdbApp
}
func (this *BaseController) Prepare() {
this.requestPath = this.Ctx.Input.URL()
this.today = time.Now().Format("20060102")
//this.auth()
var fields []string
var sortby []string
var order []string
var query map[string]string = make(map[string]string)
var limit int64 = 0
var offset int64 = 0
query["owner_id"] = strconv.Itoa(this.userId)
query["default"] = strconv.FormatBool(false)
//fmt.Println("##control##base##query:##",query,"##fields",fields,"##sortby",sortby,"##order",order,"##offset",offset,"##limit",limit)
//apps, _ := models.GetAllApp(query, fields, sortby, order, offset, limit)
//fmt.Println("###apps",apps)
var cmdbquery map[string]string = make(map[string]string)
var cmdbhostquery map[string]interface{} = make(map[string]interface{})
cmdbapps, _:=models.GetCmdbAllApp(cmdbquery, fields, sortby, order, offset, limit)
cmdbhosts,_:=models.GetCmdbAllHost(cmdbhostquery,fields, sortby, order, offset, limit)
//fmt.Println("###cmdbapps",cmdbapps)
cnt,_:= models.GetCmdbAppCount()
apps_cnt := fmt.Sprintf("%d", cnt-1)
cnt1,_:=models.GetCmdbHostAllCount()
fmt.Println("##cnt1-->",cnt1)
hosts_cnt:=fmt.Sprintf("%d",cnt1)
cnt2,_:=models.GetCmdbHostCount(0,"ApplicationID")
free_hosts_cnt:=fmt.Sprintf("%d",cnt2)
//cnt3,_:=models.GetFalconClusterCount()
//cluster_cnt:=fmt.Sprintf("%d",cnt3)
/*
if len(apps) > 0 {
defaultAppId := this.Ctx.GetCookie("defaultAppId")
//fmt.Println("####defaultAPPID:###",defaultAppId)
if defaultAppId, err := strconv.Atoi(defaultAppId); err == nil {
if app, err := models.GetAppById(defaultAppId); err != nil {
defaultApp := apps[0].(models.App)
this.defaultApp = &defaultApp
//fmt.Println("###itoa defaultappid:",strconv.Itoa(this.defaultApp.Id))
this.Ctx.SetCookie("defaultAppId", strconv.Itoa(this.defaultApp.Id))
this.Ctx.SetCookie("defaultAppName", url.QueryEscape(this.defaultApp.ApplicationName))
} else {
this.defaultApp = app
}
} else {
defaultApp := apps[0].(models.App)
this.defaultApp = &defaultApp
//fmt.Println("##2#itoa defaultappid:",strconv.Itoa(this.defaultApp.Id))
this.Ctx.SetCookie("defaultAppId", strconv.Itoa(this.defaultApp.Id))
this.Ctx.SetCookie("defaultAppName", url.QueryEscape(this.defaultApp.ApplicationName))
}
} else {
this.firstApp = true
this.firstSet = true
this.firtModule = true
}
*/
if len(cmdbapps) > 0 {
defaultAppId := this.Ctx.GetCookie("defaultAppId")
//fmt.Println("####defaultAPPID:###",defaultAppId)
if defaultAppId, err := strconv.Atoi(defaultAppId); err == nil {
if app, err := models.GetCmdbAppById(defaultAppId); err != nil {
defaultCmdbApp := cmdbapps[0].(models.CmdbApp)
this.defaultCmdbApp = &defaultCmdbApp
//fmt.Println("###itoa defaultappid:",strconv.Itoa(this.defaultApp.Id))
this.Ctx.SetCookie("defaultAppId", strconv.Itoa(this.defaultCmdbApp.Id))
this.Ctx.SetCookie("defaultAppName", url.QueryEscape(this.defaultCmdbApp.ApplicationName))
} else {
this.defaultCmdbApp = app
}
} else {
defaultCmdbApp := cmdbapps[0].(models.CmdbApp)
this.defaultCmdbApp = &defaultCmdbApp
//fmt.Println("##2#itoa defaultappid:",strconv.Itoa(this.defaultApp.Id))
this.Ctx.SetCookie("defaultAppId", strconv.Itoa(this.defaultCmdbApp.Id))
this.Ctx.SetCookie("defaultAppName", url.QueryEscape(this.defaultCmdbApp.ApplicationName))
}
} else {
this.firstApp = true
this.firstSet = true
this.firtModule = true
}
this.Data["requestPath"] = this.requestPath
this.Data["today"] = this.today
this.Data["defaultApp"] = this.defaultCmdbApp
this.Data["apps"] = cmdbapps
this.Data["cmdbhosts"] = cmdbhosts
this.Data["appscnt"] = apps_cnt
this.Data["hostscnt"] =hosts_cnt
this.Data["freehostscnt"]= free_hosts_cnt
this.Data["firstApp"] = this.firstApp
this.Data["firstSet"] = this.firstSet
this.Data["firstModule"] = this.firtModule
//fmt.Println(this.Data)
}
func (this *BaseController) getClientIP() string {
return strings.Split(this.Ctx.Request.RemoteAddr, ":")[0]
}
func (this *BaseController) redirect(url string) {
this.Redirect(url, 302)
this.StopRun()
}
func (this *BaseController) isPost() bool {
return this.Ctx.Request.Method == "POST"
}
func (this *BaseController) jsonResult(out interface{}) {
this.Data["json"] = out
this.ServeJSON()
this.StopRun()
}
/*
func (this *BaseController) auth() {
arrs := strings.Split(this.Ctx.GetCookie("auth"), "|")
if len(arrs) == 2 {
idstr, password := arrs[0], arrs[1]
userId, _ := strconv.Atoi(idstr)
if userId > 0 {
user, err := models.GetUserById(userId)
if err == nil && password == utils.Md5([]byte(this.getClientIP()+"|"+user.Password+user.Salt)) {
this.userId = user.Id
this.userName = user.UserName
}
}
}
if this.userId == 0 && this.requestPath != beego.URLFor("MainController.Login") && this.requestPath != beego.URLFor("MainController.Logout") {
this.redirect(beego.URLFor("MainController.Login"))
}
}
*/
<file_sep>/src/github.com/shwinpiocess/cc/models/falconcluster.go
package models
import (
//"errors"
//"fmt"
//"reflect"
//"strconv"
//"strings"
"github.com/astaxie/beego/orm"
)
type Falconcluster struct {
Id int `orm:"column(id);auto"`
}
func (t *Falconcluster) TableName() string {
return "cluster"
}
func init() {
orm.RegisterModel(new(Falconcluster))
}
func GetFalconClusterCount() (cnt int64, err error) {
o := orm.NewOrm()
o.Using("falcon")
cnt, err = o.QueryTable("cluster").Count()
return
}<file_sep>/src/github.com/shwinpiocess/cc/models/cmdbhost.go
package models
import (
"errors"
"fmt"
"reflect"
"strings"
//"time"
"github.com/astaxie/beego/orm"
)
type CmdbHost struct {
HostID int `orm:"column(id);auto"`
Hostname string `orm:"column(host_name);size(255);null"`
PublicIP string `orm:"column(public_ip);size(255);null"`
PrivateIP string `orm:"column(private_ip);size(255);null"`
OSName string `orm:"column(os_name);size(255);null"`
Cpunum int `orm:"column(cpu_num);null"`
Cputype string `orm:"column(cpu_type);size(255);null"`
Memsize string `orm:"column(mem_size);null"`
Disksize string `orm:"column(disk_size);null"`
Vminfo string `orm:"column(vm_info);size(255);null"`
ApplicationID int `orm:"column(application_id);null"`
ApplicationName string `orm:"column(application_name);size(255);null"`
ModuleID int `orm:"column(module_id);null"`
ModuleName string `orm:"column(module_name);size(255);null"`
IsDistributed bool `orm:"column(is_distributed)"`
//add by cq 0702
Parentserver string `orm:"column(parentserver);size(255);null"` //承载服务器
AssetID string `orm:"column(assetid);size(255);null"` //固定资产编号
Location string `orm:"column(location);size(255);null"`
Cabinets string `orm:"column(carbinets);size(255);null"`
Silo string `orm:"column(silo);size(255);null"`
Pilo string `orm:"column(pilo);size(255);null"`
Sn string `orm:"column(sn);size(255);null"`
}
func (t *CmdbHost) TableName() string {
return "cmdbhost"
}
func init() {
orm.RegisterModel(new(CmdbHost))
}
func AddCmdbaHost(cmdbhost *CmdbHost) (err error) {
o := orm.NewOrm()
err = o.Begin()
cmdbhost.ModuleName="空闲状态"
_, err = o.Insert(cmdbhost)
if err == nil {
o.Commit()
} else {
o.Rollback()
}
return
}
// AddHost insert a new Host into database and returns
// last inserted Id on success.
func AddCmdbHost(cmdbhosts []*CmdbHost) (err error) {
o := orm.NewOrm()
err = o.Begin()
_, err = o.InsertMulti(len(cmdbhosts), cmdbhosts)
if err == nil {
o.Commit()
} else {
o.Rollback()
}
return
}
//CMDB get allhost
func GetCmdbAllHost(query map[string]interface{}, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
//qs := o.QueryTable(new(Host))
qs := o.QueryTable(new(CmdbHost))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
qs = qs.Filter(k, v)
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []CmdbHost
qs = qs.OrderBy(sortFields...)
if _, err := qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
//CMDB DELETE
func DeleteCmdbHosts(id []int) (num int64, err error) {
o := orm.NewOrm()
num, err = o.QueryTable("cmdbhost").Filter("HostID__in", id).Delete()
return
}
//CMDB UPDATE
// 分配主机
func UpdateCmdbHostToApp(ids []int, appID int) (num int64, err error) {
var app *CmdbApp
//var set Set
var mod CmdbModule
o := orm.NewOrm()
if app, err = GetCmdbAppById(appID); err != nil {
return
}
/*
if err = o.QueryTable("set").Filter("ApplicationID", appID).Filter("SetName", "空闲机池").One(&set); err != nil {
return
}
*/
if err = o.QueryTable("cmdbmodule").Filter("ApplicationId", appID).Filter("ModuleName", "空闲状态").One(&mod); err != nil {
return
}
num, err = o.QueryTable("cmdbhost").Filter("HostID__in", ids).Update(orm.Params{
"ApplicationID": appID,
"ApplicationName": app.ApplicationName,
//"SetID": set.SetID,
// "SetName": set.SetName,
"ModuleID": mod.Id,
"IsDistributed": true,
})
return
}
func GetCmdbHostCount(id int, field string) (cnt int64, err error) {
o := orm.NewOrm()
if field == "ApplicationID" {
//cnt, err = o.QueryTable("cmdbhost").Exclude("ModuleName", "空闲状态").Filter(field, id).Count()
cnt, err = o.QueryTable("cmdbhost").Filter(field, id).Count()
} else {
cnt, err = o.QueryTable("cmdbhost").Filter(field, id).Count()
}
return
}
func GetCmdbHostAllCount() (cnt int64, err error) {
o := orm.NewOrm()
cnt, err = o.QueryTable("cmdbhost").Count()
return
}
func GetCmdbHostCountbyHn(hn string) (cnt int64, err error) {
o := orm.NewOrm()
//if field == "Hostname" {
//cnt, err = o.QueryTable("cmdbhost").Exclude("ModuleName", "空闲状态").Filter(field, id).Count()
cnt, err = o.QueryTable("cmdbhost").Filter("Hostname", hn).Count()
//}
return
}
// 转移主机
func ModCmdbHostModule(appID int, moduleID int, hostIds []int) (num int64, err error) {
o := orm.NewOrm()
var app *CmdbApp
//var set *Set
var m *CmdbModule
if m, err = GetCmdbModuleById(moduleID); err != nil {
return
}
if appID != m.ApplicationId {
err = errors.New("不能跨业务进行主机转移")
}
if app, err = GetCmdbAppById(appID); err != nil {
return
}
/*
if set, err = GetSetById(m.SetId); err != nil {
return
}
*/
num, err = o.QueryTable("cmdbhost").Filter("HostID__in", hostIds).Update(orm.Params{
"ApplicationID": appID,
"ApplicationName": app.ApplicationName,
//"SetID": set.SetID,
//"SetName": set.SetName,
"ModuleID": moduleID,
"ModuleName": m.ModuleName,
"IsDistributed": true,
})
return
}
// 移至空闲机/故障机
func DelCmdbHostModule(appID int, moduleName string, hostIds []int) (num int64, err error) {
o := orm.NewOrm()
var app *CmdbApp
//var set Set
var m CmdbModule
if app, err = GetCmdbAppById(appID); err != nil {
return
}
/*
if set, err = GetDesetidByAppId(appID); err != nil {
return
}
*/
if err = o.QueryTable("cmdbmodule").Filter("ApplicationId", appID).Filter("ModuleName", moduleName).One(&m); err != nil {
return
}
num, err = o.QueryTable("cmdbhost").Filter("HostID__in", hostIds).Update(orm.Params{
"ApplicationID": appID,
"ApplicationName": app.ApplicationName,
//"SetID": set.SetID,
//"SetName": set.SetName,
"ModuleID": m.Id,
"ModuleName": m.ModuleName,
})
return
}
// 上交主机
func ResCmdbHostModule(ids []int) (num int64, err error) {
//var set Set
//var mod CmdbModule
o := orm.NewOrm()
/*
if err = o.QueryTable("set").Filter("ApplicationID", appID).Filter("SetName", "空闲机池").One(&set); err != nil {
return
}
if err = o.QueryTable("cmdbmodule").Filter("ApplicationId", appID).One(&mod); err != nil {
return
}
*/
num, err = o.QueryTable("cmdbhost").Filter("HostID__in", ids).Update(orm.Params{
"ApplicationID": 0,
"ApplicationName": "",
//"SetID": set.SetID,
// "SetName": set.SetName,
"ModuleID": 0,
"ModuleName": "空闲状态",
"IsDistributed": false,
})
return
}
//0711 update memory to mysql
func UpdateCmdbHostcheck02(m *CmdbHost) (err error) {
o := orm.NewOrm()
v := CmdbHost{HostID: m.HostID}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m,"PublicIP","PrivateIP","OSName","Cpunum","Cputype","Memsize","Disksize","Vminfo"); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
//更新主机属性
func UpdateCmdbHostById01(m *CmdbHost) (err error) {
o := orm.NewOrm()
v := CmdbHost{HostID: m.HostID}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m,"AssetID","Location","Cabinets","Silo","Pilo"); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
func UpdateCmdbHostById02(m *CmdbHost) (err error) {
o := orm.NewOrm()
v := CmdbHost{HostID: m.HostID}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m,"Sn"); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
<file_sep>/src/gitcafe.com/ops/updater/cron/heartbeat.go
package cron
import (
"encoding/json"
"fmt"
"gitcafe.com/ops/common/model"
"gitcafe.com/ops/common/utils"
"gitcafe.com/ops/updater/g"
"github.com/toolkits/net/httplib"
"log"
"time"
"strconv"
"strings"
//"reflect"
)
func Heartbeat() {
SleepRandomDuration()
for {
//heartbeat()
cmdbhb()
d := time.Duration(g.Config().Interval) * time.Second
time.Sleep(d)
}
}
func cmdbhb() {
hostname, err := utils.Hostname(g.Config().Hostname)
if err != nil {
return
}
vminfo,err:=utils.Ifvmware()
if err != nil {
return
}
cputype,err:=utils.Cputype()
if err != nil {
return
}
osname,osversion,err:=utils.ReadRelease()
if err != nil {
return
}
cpunum_str,err:=utils.Cpunum()
if err != nil {
return
}
cpunum,err:=strconv.Atoi(cpunum_str)
if err != nil {
return
}
memsize,err:=utils.Memsize()
if err != nil {
return
}
disksize,err:=utils.Disksize()
if err != nil {
return
}
// get publicip and privateip
var publicip string
var privateip string
Dev1:=utils.Getnetinfo()
//var dev_pp=utils.Dev{}
for _,dev_pp:= range Dev1 {
gw1:=strings.Split(dev_pp.Dev_gw[0]," ")[0]
if dev_pp.Dev_name == gw1 {
for _,ip1:= range dev_pp.Dev_ip {
if ip1!="" {
publicip=publicip+" "+ip1
}
}
} else {
if len(dev_pp.Dev_ip)== 0 {
continue
}else {
for _,ip1:= range dev_pp.Dev_ip {
privateip=privateip + " "+ ip1
}
}
}
}
cmdbhbRequest := BuildcmdbhbRequest(hostname, vminfo,cputype,osname+osversion,cpunum,memsize,disksize,publicip,privateip)
if g.Config().Debug {
log.Println("====>>>>")
log.Println(cmdbhbRequest)
}
bs, err := json.Marshal(cmdbhbRequest)
if err != nil {
log.Println("encode cmdbhb request fail", err)
return
}
url := fmt.Sprintf("http://%s/cmdbhb", g.Config().Server)
httpRequest := httplib.Post(url).SetTimeout(time.Second*10, time.Minute)
httpRequest.Body(bs)
httpResponse, err := httpRequest.Bytes()
if err != nil {
log.Printf("curl %s fail %v", url, err)
return
}
var cmdbhbResponse model.CmdbhbResponse
err = json.Unmarshal(httpResponse, &cmdbhbResponse)
if err != nil {
log.Println("decode cmdbhb response fail", err)
return
}
if g.Config().Debug {
log.Println("<<<<====")
log.Println(cmdbhbResponse)
}
}
func heartbeat() {
agentDirs, err := ListAgentDirs()
if err != nil {
return
}
hostname, err := utils.Hostname(g.Config().Hostname)
if err != nil {
return
}
heartbeatRequest := BuildHeartbeatRequest(hostname, agentDirs)
if g.Config().Debug {
log.Println("====>>>>")
log.Println(heartbeatRequest)
}
bs, err := json.Marshal(heartbeatRequest)
if err != nil {
log.Println("encode heartbeat request fail", err)
return
}
url := fmt.Sprintf("http://%s/heartbeat", g.Config().Server)
httpRequest := httplib.Post(url).SetTimeout(time.Second*10, time.Minute)
httpRequest.Body(bs)
httpResponse, err := httpRequest.Bytes()
if err != nil {
log.Printf("curl %s fail %v", url, err)
return
}
var heartbeatResponse model.HeartbeatResponse
err = json.Unmarshal(httpResponse, &heartbeatResponse)
if err != nil {
log.Println("decode heartbeat response fail", err)
return
}
if g.Config().Debug {
log.Println("<<<<====")
log.Println(heartbeatResponse)
}
HandleHeartbeatResponse(&heartbeatResponse)
}
<file_sep>/src/github.com/shwinpiocess/cc/models/cmdbapp.go
package models
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/astaxie/beego/orm"
)
type CmdbApp struct {
Id int `orm:"column(id);auto"`
Domain string `orm:"column(domain_name);size(255)"`
Scheme string `orm:"column(scheme_name);size(255)"`
ApplicationName string `orm:"column(application_name);size(255)"`
Owner string `orm:"column(owner);size(255);null"`
Department string `orm:"column(department);size(255);null"`
Remark string `orm:"column(remark);size(255);null"`
}
func (t *CmdbApp) TableName() string {
return "cmdbapp"
}
func init() {
orm.RegisterModel(new(CmdbApp))
}
// GetCmdbAllApp retrieves all App matches certain condition. Returns empty list if
// no records exist
func GetCmdbAllApp(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(CmdbApp))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
//fmt.Println("###k,v",k,v)
qs = qs.Filter(k, v)
}
// order by:
var sortFields []string
//fmt.Println("##sortby",len(sortby))
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
/*
var x = CmdbApp{Id:1,ApplicationName:"abc",Owner:"a1",Department:"d1",Remark:"r1"}
var xx []CmdbApp
xx=append(xx,x)
for _,vv:=range xx {
val := reflect.ValueOf(vv)
fmt.Println("####val",val)
z1:=val.FieldByName("Owner")
fmt.Println(z1)
z:=val.FieldByName("Owner").Interface()
fmt.Println(z)
}
*/
var l []CmdbApp
qs = qs.OrderBy(sortFields...)
if _, err := qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
func CmdbAddApp(m *CmdbApp) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
func GetCmdbAppById(id int) (v *CmdbApp, err error) {
o := orm.NewOrm()
v = &CmdbApp{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
func ExistCmdbByName(name string) bool {
o := orm.NewOrm()
return o.QueryTable("cmdbapp").Filter("ApplicationName", name).Exist()
}
func GetCmdbAppCount() (cnt int64, err error) {
o := orm.NewOrm()
cnt, err = o.QueryTable("cmdbapp").Count()
return
}
// UpdateApp updates App by Id and returns error if
// the record to be updated doesn't exist
func UpdateCmdbAppById(m *CmdbApp) (err error) {
o := orm.NewOrm()
v := CmdbApp{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteApp deletes App by Id and returns error if
// the record to be deleted doesn't exist
func DeleteCmdbApp(id int) (err error) {
// TODO: 检测要删除业务下是否有主机
o := orm.NewOrm()
v := CmdbApp{Id: id}
//DeleteSetByAppId(id)
DeleteCmdbModuleByAppId(id)
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&CmdbApp{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
func GetCmdbAppTopoById(id int) (ml []interface{}, err error) {
// [{"id":"5524","text":"aaa","spriteCssClass":"c-icon icon-group","type":"set","expanded":false,"number":32,"items":[{"id":"7025","spriteCssClass":"c-icon icon-modal","text":"1","operator":"1842605324","bakoperator":"1842605324","type":"module","number":32}]}]
var fields []string
var sortby []string
var order []string
var query map[string]string = make(map[string]string)
var limit int64 = 0
var offset int64 = 0
query["application_id"] = strconv.Itoa(id)
//app, _ := GetCmdbAppById(id)
s := make(map[string]interface{})
if mods, err := GetCmdbAllModule(query, fields, sortby, order, offset, limit); err == nil {
var items []interface{}
for _, mod := range mods {
if mod.(CmdbModule).ModuleName != "空闲状态" {
m := make(map[string]interface{})
m["id"] = mod.(CmdbModule).Id
m["text"] = mod.(CmdbModule).ModuleName
m["spriteCssClass"] = "c-icon icon-modal"
m["type"] = "module"
m["number"] = 32
items = append(items, m)
}
}
s["items"] = items
}
s["spriteCssClass"] = "c-icon icon-group hide"
s["expanded"] = true
ml = append(ml, s)
return
}
func GetCmdbEmptyById(id int) (info map[string]interface{}, options map[int]string, err error) {
info = make(map[string]interface{})
options = make(map[int]string)
var topo []interface{}
var setItems []interface{}
var emptyItems []interface{}
var cmdbapp *CmdbApp
//var sets []interface{}
var mods []interface{}
setItems = append(setItems,1)[:0]
// 1. 获取业务信息
if cmdbapp, err = GetCmdbAppById(id); err != nil {
return
}
// 2.获取业务下集群信息,2级结构需要特殊处理
var fields []string
var sortby []string
var order []string
var query map[string]string = make(map[string]string)
var limit int64 = 0
var offset int64 = 0
query["application_id"] = strconv.Itoa(id)
if mods, err = GetCmdbAllModule(query, fields, sortby, order, offset, limit); err != nil {
return
}
var modItems []interface{}
for _, mod := range mods {
m := mod.(CmdbModule)
modItem := make(map[string]interface{})
modItem["id"] = m.Id
modItem["appId"] = cmdbapp.Id
modItem["Name"] = m.ModuleName
modItem["spriteCssClass"] = "c-icon icon-modal module"
modItem["type"] = "module"
modItem["number"], _ = GetCmdbHostCount(m.Id, "ModuleID")
modItems = append(modItems, modItem)
if m.ModuleName == "空闲状态" || m.ModuleName == "故障维护状态" {
emptyItems = append(emptyItems, modItem)
} else {
setItems = append(setItems, modItem)
options[m.Id] = m.ModuleName
}
}
/*
setItem["items"] = modItems
setItems = append(setItems, setItem)
*/
topoItem := make(map[string]interface{})
topoItem["id"] = cmdbapp.Id
topoItem["Name"] = cmdbapp.ApplicationName
topoItem["type"] = "application"
topoItem["spriteCssClass"] = "c-icon icon-app application"
topoItem["expanded"] = true
//topoItem["lvl"] = app.Level
topoItem["number"], _ = GetCmdbHostCount(cmdbapp.Id, "ApplicationID")
topoItem["items"] = setItems
/*
var topo33 []interface{}
topo33 = append(topo33, topoItem)
topoItem1 := make(map[string]interface{})
topoItem1["id"] = 100
topoItem1["Name"] = "LEVEL2"
topoItem1["type"] = "application"
topoItem1["spriteCssClass"] = "c-icon icon-app application"
topoItem1["expanded"] = true
//topoItem["lvl"] = app.Level
topoItem1["number"]= 201
topoItem1["items"] = topo33
var topo44 []interface{}
topo44 = append(topo44, topoItem1)
topoItem2 := make(map[string]interface{})
topoItem2["id"] = 100
topoItem2["Name"] = "Level1"
topoItem2["type"] = "application"
topoItem2["spriteCssClass"] = "c-icon icon-app application"
topoItem2["expanded"] = true
//topoItem["lvl"] = app.Level
topoItem2["number"]= 201
topoItem2["items"] = topo44
topo = append(topo, topoItem2)
topo = append(topo, topoItem2)
*/
topo = append(topo,topoItem)
info["topo"] = topo
info["empty"] = emptyItems
//fmt.Println("###info###",info)
//fmt.Println("###options###",options)
return
}
<file_sep>/src/github.com/shwinpiocess/loadapp.go
package main
import (
//"path"
"fmt"
//"encoding/json"
//"errors"
//"strconv"
//"strings"
"github.com/tealeg/xlsx"
//"github.com/shwinpiocess/cc/models"
)
func main(){
//out := make(map[string]interface{})
excelFileName := "./uploadapp.xlsx"
if xlFile, err := xlsx.OpenFile(excelFileName); err == nil {
//var cmdbapps []*models.CmdbApp
for _, sheet := range xlFile.Sheets {
for _, row := range sheet.Rows {
Domain, err := row.Cells[2].String()
Scheme, err := row.Cells[3].String()
ApplicationName, err := row.Cells[4].String()
Owner, err := row.Cells[8].String()
Department, err := row.Cells[9].String()
Remark, err := row.Cells[10].String()
fmt.Println(Domain,Scheme,ApplicationName,Owner,Department,Remark)
if err!=nil {
fmt.Println(err)
}
}
}
}
}
<file_sep>/src/github.com/shwinpiocess/cc/models/base.go
package models
import (
"net/url"
_ "github.com/go-sql-driver/mysql"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
)
func init() {
dbhost := beego.AppConfig.String("db.host")
dbport := beego.AppConfig.String("db.port")
dbuser := beego.AppConfig.String("db.user")
dbpassword := beego.AppConfig.String("db.password")
dbname := beego.AppConfig.String("db.name")
timezone := beego.AppConfig.String("db.timezone")
if dbport == "" {
dbport = "3306"
}
dsn := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + dbname + "?charset=utf8"
if timezone != "" {
dsn = dsn + "&loc=" + url.QueryEscape(timezone)
}
orm.RegisterDataBase("default", "mysql", dsn)
//falcon by cq
dbhost1 := beego.AppConfig.String("db1.host")
dbport1 := beego.AppConfig.String("db1.port")
dbuser1 := beego.AppConfig.String("db1.user")
dbpassword1 := beego.AppConfig.String("db1.password")
dbname1 := beego.AppConfig.String("db1.name")
timezone1 := beego.AppConfig.String("db1.timezone")
if dbport1 == "" {
dbport1 = "3306"
}
dsn1 := dbuser1 + ":" + dbpassword1 + "@tcp(" + dbhost1 + ":" + dbport1 + ")/" + dbname1 + "?charset=utf8"
if timezone1 != "" {
dsn1 = dsn1 + "&loc=" + url.QueryEscape(timezone1)
}
orm.RegisterDataBase("falcon", "mysql", dsn1)
if beego.AppConfig.String("runmode") == "dev" {
orm.Debug = true
}
}
<file_sep>/src/github.com/shwinpiocess/cc/controllers/sms.go
package controllers
import (
//"net/url"
//"strconv"
"strings"
//"time"
"fmt"
"github.com/astaxie/beego"
"database/sql"
"os"
_ "github.com/mattn/go-oci8"
)
type SmsController struct {
beego.Controller
}
func (this *SmsController)Sendsms() {
content := strings.TrimSpace(this.GetString("content", ""))
tos := strings.TrimSpace(this.GetString("tos", ""))
err := Sms(content,tos)
if err != nil {
this.Ctx.Output.Body([]byte(err.Error()))
} else {
this.Ctx.Output.Body([]byte("success"))
}
}
func Sms(content, tos string) error{
//nlsLang:="SIMPLIFIED CHINESE_CHINA.ZHS16GBK"
os.Setenv("NLS_LANG", "SIMPLIFIED CHINESE_CHINA.ZHS16GBK")
db, err := sql.Open("oci8", getsmsDSN())
if err != nil {
fmt.Println(err)
return err
}
defer db.Close()
if err = smsinsert(db,content,tos); err != nil {
fmt.Println(err)
return err
}
return nil
}
func getsmsDSN() string {
var dsn string
if len(os.Args) > 1 {
dsn = os.Args[1]
if dsn != "" {
return dsn
}
}
//dsn = os.Getenv("GO_OCI8_CONNECT_STRING")
dsn="mon/[email protected]/zjmon"
if dsn != "" {
return dsn
}
fmt.Fprintln(os.Stderr, `Please specifiy connection parameter in GO_OCI8_CONNECT_STRING environment variable,
or as the first argument! (The format is user/name@host:port/sid)`)
return "scott/tiger@XE"
}
func smsinsert(db *sql.DB,content string,tos string) error {
to:=strings.Split(tos, ",")
for _,toone := range to {
/*
if _, err := db.Exec("INSERT INTO " + "app_sm" +
" VALUES (" + "'cq188','"+toone+"','"+content+"')"); err != nil {
return err
}
*/
if _, err := db.Exec("INSERT INTO " + "ZCJ_SMS" + "(RECEIVER,MSG)"+
" VALUES ('" +toone+"','"+content+"')"); err != nil {
return err
}
}
return nil
}<file_sep>/src/gitcafe.com/ops/common/utils/disksize.go
package utils
import (
"syscall"
"fmt"
)
func Disksize()(disksize string,err error){
var stat syscall.Statfs_t
wd:="/"
syscall.Statfs(wd, &stat)
disksize=fmt.Sprintf("%.2f GB", float64(stat.Blocks * uint64(stat.Bsize))/float64(GB))
return disksize,nil
}
<file_sep>/src/github.com/shwinpiocess/cc/controllers/cmdbmodule.go
package controllers
import (
//"encoding/json"
//"errors"
"github.com/shwinpiocess/cc/models"
//"strconv"
"strings"
)
// oprations for Module
type CmdbModuleController struct {
BaseController
}
func (this *CmdbModuleController) NewModule() {
out := make(map[string]interface{})
m := new(models.CmdbModule)
m.ApplicationId, _ = this.GetInt("ApplicationID")
m.ModuleName = this.GetString("ModuleName")
if _, err := models.CmdbAddModule(m); err == nil {
out["success"] = true
this.jsonResult(out)
} else {
out["success"] = false
out["errInfo"] = "重复的模块名!"
this.jsonResult(out)
}
}
func (this *CmdbModuleController) DelModule() {
out := make(map[string]interface{})
moduleId, _ := this.GetInt("ModuleID")
if err := models.DeleteCmdbModule(moduleId); err == nil {
out["success"] = true
this.jsonResult(out)
} else {
out["success"] = false
out["errInfo"] = err.Error()
this.jsonResult(out)
}
}
func (this *CmdbModuleController) EditModule() {
if this.isPost() {
cmdbmodule := new(models.CmdbModule)
cmdbmodule.Id,_ = this.GetInt("ModuleID")
cmdbmodule.ApplicationId,_ = this.GetInt("ApplicationID")
cmdbmodule.ModuleName = strings.TrimSpace(this.GetString("ModuleName"))
out := make(map[string]interface{})
if err := models.UpdateCmdbModuleById(cmdbmodule); err != nil {
out["errInfo"] = err.Error()
out["success"] = false
out["errCode"] = "0006"
this.jsonResult(out)
} else {
out["success"] = true
this.jsonResult(out)
}
}
}
<file_sep>/src/gitcafe.com/ops/common/utils/memsize.go
package utils
import (
"syscall"
"fmt"
)
const (
B = 1
KB = 1024 * B
MB = 1024 * KB
GB = 1024 * MB
)
func Memsize()(memsize string,err error){
sysInfo := new(syscall.Sysinfo_t)
err = syscall.Sysinfo(sysInfo)
if err != nil {
return
}
memsize=fmt.Sprintf("%.2f GB", float64(sysInfo.Totalram)/float64(GB))
return memsize,nil
}<file_sep>/src/github.com/shwinpiocess/cc/controllers/cmdbfalcon.go
package controllers
import (
"fmt"
//"net/url"
//"strconv"
//"strings"
//"github.com/shwinpiocess/cc/models"
)
type CmdbFalconController struct {
BaseController
}
func (this *CmdbFalconController) Portal() {
fmt.Println("--------------------------------------------->")
this.TplName = "cmdbfalcon/portal.html"
}
func (this *CmdbFalconController) Dashboard() {
fmt.Println("--------------------------------------------->")
this.TplName = "cmdbfalcon/dashboard.html"
}
<file_sep>/src/github.com/shwinpiocess/cc/main.go
package main
import (
_ "github.com/shwinpiocess/cc/routers"
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego"
"fmt"
"time"
//"github.com/shwinpiocess/cc/dcmdb"
"flag"
"gitcafe.com/ops/meta/g"
"gitcafe.com/ops/meta/http"
"log"
"os"
)
func int_to_string(in int)(out string){
out = fmt.Sprintf("%d",in)
return out
}
func main() {
cfg := flag.String("c", "cfg.json", "configuration file")
version := flag.Bool("v", false, "show version")
flag.Parse()
if *version {
fmt.Println(g.VERSION)
os.Exit(0)
}
if err := g.ParseConfig(*cfg); err != nil {
log.Fatalln(err)
}
beego.SetStaticPath("/zjz_work_cmdb/static","static")
orm.RunSyncdb("default", false, true)
ticket1 := time.NewTicker(time.Millisecond * 500)
go func() {
for i := range ticket1.C {
fmt.Println(i)
}
}()
go func() {
time.Sleep(time.Second*12)
//dcmdb.Dinsert()
}()
go func() {
time.Sleep(time.Second * 10)
ticket1.Stop()
fmt.Println("ticket1 stopped")
}()
go http.Start()
beego.AddFuncMap("itos",int_to_string)
beego.Run()
}
<file_sep>/src/github.com/shwinpiocess/cc/static/js/zjznewapp.js
$(document).ready(function() {
$(".btn-primary").click(function () {
var DomainName = $.trim($("#Domain").val());
if ((DomainName.length > 16) || (DomainName.length == 0)) {
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">请输入域名称并限制在16位字符</span>'
});
diaCopyMsg.show($("#Domain").get(0));
return;
}
var SchemeName = $.trim($("#Scheme").val());
if ((SchemeName.length > 16) || (SchemeName.length == 0)) {
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">请输入业务名称并限制在16位字符</span>'
});
diaCopyMsg.show($("#SchemeName").get(0));
return;
}
var ApplicationName = $.trim($("#AppName").val());
if ((ApplicationName.length > 16) || (ApplicationName.length == 0)) {
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">请输入业务名称并限制在16位字符</span>'
});
diaCopyMsg.show($("#AppName").get(0));
return;
}
var OwnerName = $.trim($("#Owner").val());
if ((OwnerName.length > 16) || (OwnerName.length == 0)) {
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">请输入责任人并限制在16位字符</span>'
});
diaCopyMsg.show($("#Owner").get(0));
return;
}
var DepartmentName = $.trim($("#Department").val());
if ((DepartmentName.length > 16) || (DepartmentName.length == 0)) {
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">请输入所属部门并限制在16位字符</span>'
});
diaCopyMsg.show($("#Department").get(0));
return;
}
var RemarkName = $.trim($("#Remark").val());
if (RemarkName.length > 32) {
var diaCopyMsg = dialog({
quickClose: true,
align: 'left',
padding:'5px 5px 5px 10px',
skin: 'c-Popuplayer-remind-left',
content: '<span style="color:#fff">备注请限制在32位字符</span>'
});
diaCopyMsg.show($("#Remark").get(0));
return;
}
$.post("/zjz_work_cmdb/cmdbapp/addapp",
{
Domain: DomainName,
Scheme: SchemeName,
ApplicationName: ApplicationName,
Owner: OwnerName,
Department: DepartmentName,
Remark: RemarkName
}
, function (result) {
// rere = $.parseJSON(result);
rere = result;
console.log(rere)
if (rere.success == false) {
showWindows(rere.errInfo, 'notice');
}
else {
//cookie.set('play_user_guide_imqcloud_index', 0);
if (rere.gotopo == 1) {
var d = dialog({
title: '提示',
width: 300,
height: 30,
okValue: "好",
ok: function () {
window.location.href = '/zjz_work_cmdb/cmdb/cmdbImport';
return false;
},
onclose: function () {
window.location.href = '/zjz_work_cmdb/cmdbapp/index'
},
content: '<div class="c-dialogdiv"><i class="c-dialogimg-success"></i>' + '业务建好了,接下来就给它分配一些主机</a>吧' + '</div>'
});
d.showModal();
return;
}
else {
showWindows('新增成功!', 'success');
setTimeout(function () {
window.location.href = '/zjz_work_cmdb/cmdbapp/index';
}, 1000);
}
}
});
});
$(".cancelb").click(function(){
reloadPage();
})
function showWindows(Msg, level) {
if (level == 'success') {
var d = dialog({
width: 150,
content: '<div class="c-dialogdiv2"><i class="c-dialogimg-success"></i>'+Msg+'</div>'
});
d.show();
}
else if (level == 'error') {
var d = dialog({
title: '错误',
width: 300,
okValue: "确定",
ok: function () {
},
content: '<div class="c-dialogdiv2"><i class="c-dialogimg-failure"></i>' + Msg + '</div>'
});
d.showModal();
}
else {
var d = dialog({
title: '警告',
width: 300,
okValue: "确定",
ok: function () {
},
content: '<div class="c-dialogdiv2"><i class="c-dialogimg-prompt"></i>' + Msg + '</div>'
});
d.showModal();
}
}
});
function reloadPage()
{
window.location.reload()
}<file_sep>/src/github.com/shwinpiocess/cc/routers/router.go
package routers
import (
"github.com/astaxie/beego"
"github.com/shwinpiocess/cc/controllers"
)
func init() {
beego.Router("/", &controllers.MainController{}, "*:Index")
//beego.Router("/login", &controllers.MainController{}, "*:Login")
//beego.Router("/logout", &controllers.MainController{}, "*:Logout")
// 业务管理
//beego.Router("/app/index", &controllers.AppController{}, "*:Index")
//beego.Router("/app/newapp", &controllers.AppController{}, "*:NewApp")
//beego.Router("/app/add", &controllers.AppController{}, "*:AddApp")
//beego.Router("/app/delete", &controllers.AppController{}, "*:DeleteApp")
//beego.Router("/welcome/setDefaultApp", &controllers.AppController{}, "*:SetDefaultApp")
//beego.Router("/App/getMainterners", &controllers.AppController{}, "*:GetMainterners")
//beego.Router("/app/getMainterners", &controllers.AppController{}, "*:GetMainterners")
//beego.Router("/topology/index", &controllers.AppController{}, "*:TopologyIndex")
//beego.Router("/Set/getAllSetInfo", &controllers.SetController{}, "*:GetAllSetInfo")
//beego.Router("/Set/newSet", &controllers.SetController{}, "*:NewSet")
//beego.Router("/Set/editSet", &controllers.SetController{}, "*:EditSet")
//beego.Router("/Set/delSet", &controllers.SetController{}, "*:DelSet")
//beego.Router("/Set/getSetInfoById", &controllers.SetController{}, "*:GetSetInfoById")
//beego.Router("/Module/newModule", &controllers.ModuleController{}, "*:NewModule")
// 快速分配
//beego.Router("/host/quickImport", &controllers.HostController{}, "*:QuickImport")
//beego.Router("host/hostQuery", &controllers.HostController{}, "*:HostQuery")
//beego.Router("/host/getHostById", &controllers.HostController{}, "post:GetHostById")
//beego.Router("/host/importPrivateHostByExcel", &controllers.HostController{}, "post:ImportPrivateHostByExcel")
//beego.Router("/host/getHost4QuickImport", &controllers.HostController{}, "post:GetHost4QuickImport")
//beego.Router("/host/delPrivateDefaultApplicationHost", &controllers.HostController{}, "post:DelPrivateDefaultApplicationHost")
//beego.Router("/host/quickDistribute", &controllers.HostController{}, "post:QuickDistribute")
//beego.Router("/host/details", &controllers.HostController{}, "post:Details")
//beego.Router("/host/resHostModule/", &controllers.HostController{}, "post:ResHostModule")
//beego.Router("/host/getTopoTree4view", &controllers.HostController{}, "post:GetTopoTree4view")
//beego.Router("/host/modHostModule/", &controllers.HostController{}, "post:ModHostModule")
//beego.Router("/host/delHostModule/", &controllers.HostController{}, "post:DelHostModule")
// 太空堡垒
//beego.Router("/tkbl/index", &controllers.TkblController{}, "*:Index")
/////////////////////
beego.Router("/zjz_work_cmdb/", &controllers.MainController{}, "*:Index")
//beego.Router("/zjz_work_cmdb/login", &controllers.MainController{}, "*:Login")
//beego.Router("/zjz_work_cmdb/logout", &controllers.MainController{}, "*:Logout")
//beego.Router("/zjz_work_cmdb/app/index", &controllers.AppController{}, "*:Index")
//beego.Router("/zjz_work_cmdb/app/newapp", &controllers.AppController{}, "*:NewApp")
//beego.Router("/zjz_work_cmdb/app/add", &controllers.AppController{}, "*:AddApp")
//beego.Router("/zjz_work_cmdb/app/delete", &controllers.AppController{}, "*:DeleteApp")
//beego.Router("/zjz_work_cmdb/welcome/setDefaultApp", &controllers.AppController{}, "*:SetDefaultApp")
//beego.Router("/zjz_work_cmdb/App/getMainterners", &controllers.AppController{}, "*:GetMainterners")
//beego.Router("/zjz_work_cmdb/app/getMainterners", &controllers.AppController{}, "*:GetMainterners")
//beego.Router("/zjz_work_cmdb/topology/index", &controllers.AppController{}, "*:TopologyIndex")
//beego.Router("/zjz_work_cmdb/Set/getAllSetInfo", &controllers.SetController{}, "*:GetAllSetInfo")
//beego.Router("/zjz_work_cmdb/Set/newSet", &controllers.SetController{}, "*:NewSet")
//beego.Router("/zjz_work_cmdb/Set/editSet", &controllers.SetController{}, "*:EditSet")
//beego.Router("/zjz_work_cmdb/Set/delSet", &controllers.SetController{}, "*:DelSet")
//beego.Router("/zjz_work_cmdb/Set/getSetInfoById", &controllers.SetController{}, "*:GetSetInfoById")
//beego.Router("/zjz_work_cmdb/Module/newModule", &controllers.ModuleController{}, "*:NewModule")
//cq 0602
beego.Router("/zjz_work_cmdb/cmdb/cmdbImport", &controllers.CmdbController{}, "*:CmdbImport")
beego.Router("/zjz_work_cmdb/cmdb/GetCmdbHost", &controllers.CmdbController{}, "post:GetCmdbHost")
beego.Router("/zjz_work_cmdb/cmdb/DelCmdbHost", &controllers.CmdbController{}, "post:DelCmdbHost")
beego.Router("/zjz_work_cmdb/cmdb/CmdbDistribute", &controllers.CmdbController{}, "post:CmdbDistribute")
//beego.Router("/zjz_work_cmdb/cmdb/cmdbhostQuery", &controllers.CmdbController{}, "*:CmdbHostQuery")
beego.Router("/zjz_work_cmdb/cmdbapp/index", &controllers.CmdbAppController{}, "*:Index")
beego.Router("/zjz_work_cmdb/cmdbapp/newapp", &controllers.CmdbAppController{}, "*:NewApp")
//cq 0603
beego.Router("/zjz_work_cmdb/cmdbapp/addapp", &controllers.CmdbAppController{}, "*:AddApp")
beego.Router("/zjz_work_cmdb/cmdbapp/editapp", &controllers.CmdbAppController{}, "*:EditApp")
beego.Router("/zjz_work_cmdb/cmdbapp/delapp", &controllers.CmdbAppController{}, "*:DeleteApp")
beego.Router("/zjz_work_cmdb/cmdbapp/setDefaultApp", &controllers.CmdbAppController{}, "*:SetDefaultApp")
beego.Router("/zjz_work_cmdb/cmdbmoule/index", &controllers.CmdbAppController{}, "*:ModuleIndex")
//cq 0606
beego.Router("/zjz_work_cmdb/cmdbmoule/newModule", &controllers.CmdbModuleController{}, "*:NewModule")
//cq 0607
beego.Router("/zjz_work_cmdb/cmdbmoule/delModule", &controllers.CmdbModuleController{}, "*:DelModule")
beego.Router("/zjz_work_cmdb/cmdbmoule/editModule", &controllers.CmdbModuleController{}, "*:EditModule")
beego.Router("/zjz_work_cmdb/cmdb/cmdbhostQuery", &controllers.CmdbController{}, "*:CmdbQuery")
beego.Router("/zjz_work_cmdb/cmdb/getcmdbHostById", &controllers.CmdbController{}, "post:GetCmdbHostById")
beego.Router("/zjz_work_cmdb/cmdb/getcmdbTopoTree4view", &controllers.CmdbController{}, "post:GetCmdbTopoTree4view")
//cq 0607 22:00
beego.Router("/zjz_work_cmdb/cmdb/modCmdbHostModule/", &controllers.CmdbController{}, "post:ModCmdbHostModule")
beego.Router("/zjz_work_cmdb/cmdb/delCmdbHostModule/", &controllers.CmdbController{}, "post:DelCmdbHostModule")
beego.Router("/zjz_work_cmdb/cmdb/resCmdbHostModule/", &controllers.CmdbController{}, "post:ResCmdbHostModule")
//cq 0613
beego.Router("/zjz_work_provider/mail/sendmail", &controllers.MailController{}, "post:Sendmail")
beego.Router("/zjz_work_provider/sms/sendsms", &controllers.SmsController{}, "post:Sendsms")
//cq 0615
beego.Router("/zjz_work_provider/voice/sendvoice", &controllers.VoiceController{}, "post:Sendvoice")
//cq 0627
beego.Router("/zjz_work_cmdb/upload/upload", &controllers.CmdbUploadController{}, "*:Upload")
//cq 0703
beego.Router("/zjz_work_cmdb/falcon/portal", &controllers.CmdbFalconController{}, "*:Portal")
beego.Router("/zjz_work_cmdb/falcon/dashboard", &controllers.CmdbFalconController{}, "*:Dashboard")
//cq 0704
beego.Router("/zjz_work_cmdb/cmdb/cmdbdetail", &controllers.CmdbController{}, "*:Detail")
beego.Router("/zjz_work_cmdb/tkbl/tkblapi", &controllers.TkblController{}, "*:Tkblapi")
beego.Router("/zjz_work_cmdb/tkbl/posttkblapi", &controllers.TkblController{}, "post:PostTkblapi")
beego.Router("/zjz_work_cmdb/cmdb/editcmdbhost01", &controllers.CmdbController{}, "post:EditCmdbhost01")
beego.Router("/zjz_work_cmdb/cmdb/editcmdbhost02", &controllers.CmdbController{}, "post:EditCmdbhost02")
//cq 0707
beego.Router("/zjz_work_cmdb/cmdb/cmdbcheck", &controllers.CmdbController{}, "*:Check")
//cq 0708
beego.Router("/zjz_work_cmdb/cmdb/checkmore_cmdbhost01",&controllers.CmdbController{},"*:GetCmdbHostBycheckhid")
beego.Router("/zjz_work_provider/weixin/sendweixin", &controllers.WeixinController{}, "post:Sendweixin")
//cq 0710
beego.Router("/zjz_work_cmdb/cmdb/checkmore_cmdbhost02",&controllers.CmdbController{},"*:GetCmdbaAgentBycheckhid")
//cq 0711
beego.Router("/zjz_work_cmdb/cmdb/cmdbhost_checkupdate02",&controllers.CmdbController{},"post:UpdateCmdbhostcheck02")
//beego.Router("host/hostQuery", &controllers.HostController{}, "*:HostQuery")
//beego.Router("/zjz_work_cmdb/host/getHostById", &controllers.HostController{}, "post:GetHostById")
//beego.Router("/zjz_work_cmdb/host/importPrivateHostByExcel", &controllers.HostController{}, "post:ImportPrivateHostByExcel")
//beego.Router("/zjz_work_cmdb/host/getHost4QuickImport", &controllers.HostController{}, "post:GetHost4QuickImport")
//beego.Router("/zjz_work_cmdb/host/delPrivateDefaultApplicationHost", &controllers.HostController{}, "post:DelPrivateDefaultApplicationHost")
//beego.Router("/zjz_work_cmdb/host/quickDistribute", &controllers.HostController{}, "post:QuickDistribute")
//beego.Router("/zjz_work_cmdb/host/details", &controllers.HostController{}, "post:Details")
//beego.Router("/zjz_work_cmdb/host/resHostModule/", &controllers.HostController{}, "post:ResHostModule")
//beego.Router("/zjz_work_cmdb/host/getTopoTree4view", &controllers.HostController{}, "post:GetTopoTree4view")
//beego.Router("/zjz_work_cmdb/host/modHostModule/", &controllers.HostController{}, "post:ModHostModule")
//beego.Router("/zjz_work_cmdb/host/delHostModule/", &controllers.HostController{}, "post:DelHostModule")
beego.Router("/zjz_work_cmdb/tkbl/index", &controllers.TkblController{}, "*:Index")
}
<file_sep>/src/github.com/shwinpiocess/cc/controllers/cmdbapp.go
package controllers
import (
"fmt"
"net/url"
"strconv"
"strings"
"github.com/shwinpiocess/cc/models"
)
type CmdbAppController struct {
BaseController
}
func (this *CmdbAppController) Index() {
fmt.Println("--------------------------------------------->")
this.TplName = "cmdbapp/index.html"
}
func (this *CmdbAppController) NewApp() {
this.TplName = "cmdbapp/newapp.html"
}
func (this *CmdbAppController) AddApp() {
if this.isPost() {
cmdbapp := new(models.CmdbApp)
cmdbapp.Domain = strings.TrimSpace(this.GetString("Domain"))
cmdbapp.Scheme = strings.TrimSpace(this.GetString("Scheme"))
cmdbapp.ApplicationName = strings.TrimSpace(this.GetString("ApplicationName"))
cmdbapp.Owner = strings.TrimSpace(this.GetString("Owner"))
cmdbapp.Department = strings.TrimSpace(this.GetString("Department"))
cmdbapp.Remark = strings.TrimSpace(this.GetString("Remark"))
out := make(map[string]interface{})
if models.ExistCmdbByName(cmdbapp.ApplicationName) {
out["errInfo"] = "同名的业务已经存在!"
out["success"] = false
out["errCode"] = "0006"
this.jsonResult(out)
}
var Id int64
if Id, err := models.CmdbAddApp(cmdbapp); err != nil {
out["errInfo"] = err.Error()
out["success"] = false
out["errCode"] = "0006"
this.jsonResult(out)
} else {
m := new(models.CmdbModule)
m.ApplicationId = int(Id)
m.ModuleName = "空闲状态"
models.CmdbAddModule(m)
m2 := new(models.CmdbModule)
m2.ApplicationId = int(Id)
m2.ModuleName = "故障维护状态"
models.CmdbAddModule(m2)
}
//models.AddDefApp(this.userId)
this.Ctx.SetCookie("defaultAppId", strconv.FormatInt(Id, 10))
this.Ctx.SetCookie("defaultAppName", url.QueryEscape(cmdbapp.ApplicationName))
var fields []string
var sortby []string
var order []string
var query map[string]string = make(map[string]string)
var limit int64 = 0
var offset int64 = 0
//query["owner_id"] = strconv.Itoa(this.userId)
//query["default"] = strconv.FormatBool(false)
cmdbapps, _ := models.GetCmdbAllApp(query, fields, sortby, order, offset, limit)
//fmt.Println("####cmdbapps len",len(cmdbapps))
if len(cmdbapps) > 1 {
out["success"] = true
out["gotopo"] = 0
this.jsonResult(out)
} else {
out["success"] = true
out["gotopo"] = 1
this.jsonResult(out)
}
}
}
func (this *CmdbAppController) DeleteApp() {
out := make(map[string]interface{})
applicationId, _ := this.GetInt("ApplicationID")
if err := models.DeleteCmdbApp(applicationId); err == nil {
out["success"] = true
this.jsonResult(out)
} else {
out["success"] = false
out["errInfo"] = err.Error()
this.jsonResult(out)
}
}
func (this *CmdbAppController) EditApp() {
if this.isPost() {
cmdbapp := new(models.CmdbApp)
cmdbapp.Domain = strings.TrimSpace(this.GetString("Domain"))
cmdbapp.Scheme = strings.TrimSpace(this.GetString("Scheme"))
cmdbapp.ApplicationName = strings.TrimSpace(this.GetString("ApplicationName"))
cmdbapp.Owner = strings.TrimSpace(this.GetString("Owner"))
cmdbapp.Department = strings.TrimSpace(this.GetString("Department"))
cmdbapp.Remark = strings.TrimSpace(this.GetString("Remark"))
cmdbapp.Id,_ = this.GetInt("ApplicationID")
out := make(map[string]interface{})
//fmt.Println("###cmdbapp",cmdbapp)
if err := models.UpdateCmdbAppById(cmdbapp); err != nil {
out["errInfo"] = err.Error()
out["success"] = false
out["errCode"] = "0006"
this.jsonResult(out)
} else {
out["success"] = true
this.jsonResult(out)
}
}
}
func (this *CmdbAppController) SetDefaultApp() {
out := make(map[string]interface{})
if applicationId, err := this.GetInt("ApplicationID"); err != nil {
out["success"] = false
this.jsonResult(out)
} else {
if app, err := models.GetCmdbAppById(applicationId); err != nil {
out["success"] = false
this.jsonResult(out)
} else {
this.Ctx.SetCookie("defaultAppId", strconv.Itoa(applicationId))
this.Ctx.SetCookie("defaultAppName", url.QueryEscape(app.ApplicationName))
fmt.Println("-------->", app.ApplicationName)
out["success"] = true
out["message"] = "业务切换成功"
this.jsonResult(out)
}
}
}
func (this *CmdbAppController) ModuleIndex() {
//fmt.Println(this.defaultCmdbApp.Id)
topo, err := models.GetCmdbAppTopoById(this.defaultCmdbApp.Id)
this.Data["topo"] = topo
fmt.Println("topo=", topo, "err=", err)
this.TplName = "cmdbmodule/index.html"
}
<file_sep>/src/gitcafe.com/ops/common/utils/netinfo.go
package utils
import (
"fmt"
"os"
"strings"
"strconv"
"net"
"io/ioutil"
"os/exec"
"bufio"
"bytes"
"io"
)
type Dev struct {
Dev_name string
Dev_type string
Dev_ip []string
Dev_gw []string
}
const (
PROC_TCP = "/proc/net/tcp"
PROC_UDP = "/proc/net/udp"
PROC_TCP6 = "/proc/net/tcp6"
PROC_UDP6 = "/proc/net/udp6"
PROC_ROUTE = "/proc/net/route"
)
type Rout struct {
iface string
dst string
gateway string
}
func check(err error) {
if err != nil {
panic(err)
}
}
func getData(t string) []string {
// Get data from tcp or udp file.
var proc_t string
if t == "tcp" {
proc_t = PROC_TCP
} else if t == "udp" {
proc_t = PROC_UDP
} else if t == "tcp6" {
proc_t = PROC_TCP6
} else if t == "udp6" {
proc_t = PROC_UDP6
} else if t == "route" {
proc_t = PROC_ROUTE
} else {
fmt.Printf("%s is a invalid type, tcp and udp only!\n", t)
os.Exit(1)
}
data, err := ioutil.ReadFile(proc_t)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lines := strings.Split(string(data), "\n")
// Return lines without Header line and blank line on the end
return lines[1:len(lines) - 1]
}
func removeEmpty(array []string) []string {
// remove empty data from line
var new_array [] string
for _, i := range(array) {
if i != "" {
new_array = append(new_array, i)
}
}
return new_array
}
func convertIp(ip string) string {
// Convert the ipv4 to decimal. Have to rearrange the ip because the
// default value is in little Endian order.
var out string
// Check ip size if greater than 8 is a ipv6 type
if len(ip) > 8 {
i := []string{ ip[30:32],
ip[28:30],
ip[26:28],
ip[24:26],
ip[22:24],
ip[20:22],
ip[18:20],
ip[16:18],
ip[14:16],
ip[12:14],
ip[10:12],
ip[8:10],
ip[6:8],
ip[4:6],
ip[2:4],
ip[0:2]}
out = fmt.Sprintf("%v%v:%v%v:%v%v:%v%v:%v%v:%v%v:%v%v:%v%v",
i[14], i[15], i[13], i[12],
i[10], i[11], i[8], i[9],
i[6], i[7], i[4], i[5],
i[2], i[3], i[0], i[1])
} else {
i := []int64{ hexToDec(ip[6:8]),
hexToDec(ip[4:6]),
hexToDec(ip[2:4]),
hexToDec(ip[0:2]) }
out = fmt.Sprintf("%v.%v.%v.%v", i[0], i[1], i[2], i[3])
}
return out
}
func hexToDec(h string) int64 {
// convert hexadecimal to decimal.
d, err := strconv.ParseInt(h, 16, 32)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return d
}
func gw2(t string) []Rout{
var Routs []Rout
data:=getData(t)
for _,line := range(data) {
line_array := removeEmpty(strings.Split(strings.TrimSpace(line), "\t"))
iface:=line_array[0]
dst:=line_array[1]
gateway:=convertIp(line_array[2])
if dst=="00000000" {
dst="default"
p:=Rout{iface,dst,gateway}
Routs=append(Routs,p)
}
}
return Routs
}
func Route2() []string {
data:=gw2("route")
//return data //data is []Rout
var s []string
for _,data_struct:=range data {
x:=data_struct.iface+" "+data_struct.gateway
s=append(s,x)
}
return s
}
func Getnetinfo() []Dev{
dev_array:=[]Dev{}
interfaces, err := net.Interfaces()
check(err)
gw_a:=Route2()
for _, i := range interfaces {
if strings.Contains(i.Flags.String(), "up") {
if strings.Contains(i.Name,"lo") {
continue
}
if strings.Contains(i.Name,"virbr") {
continue
}
if strings.Contains(i.Name,"docker") {
continue
}
fmt.Printf("Name: %v up \n", i.Name)
addrs,err:=i.Addrs()
check(err)
var ipstr []string
for _,a:=range addrs {
switch v:=a.(type){
case *net.IPNet:
ss:=fmt.Sprintf("%s",v)
if strings.Contains(ss,":") {
continue
}
fmt.Printf("%v : %s \n",i.Name,v)
ipstr=append(ipstr,ss)
}
}
devx:=Dev{}
devx.Dev_name=i.Name
devx.Dev_type=intftype(i.Name)
devx.Dev_ip=ipstr
devx.Dev_gw=gw_a
dev_array=append(dev_array,devx)
fmt.Printf("\n")
}
}
return dev_array
}
func intftype(dev string)string {
ifvm,_:=Ifvmware()
var line string
lsCmd := exec.Command("bash", "-c", "ethtool "+dev)
lsOut, err := lsCmd.Output()
if err != nil {
//panic(err)
return "unknown"
}
r := bytes.NewReader(lsOut)
r1 := bufio.NewReader(r)
for {
data, err := r1.ReadSlice('\n')
if err == io.EOF {
return line+" "+ifvm
break
}
if strings.Contains(string(data), "Speed:") || strings.Contains(string(data), "Port:") {
inputstring := strings.Trim(string(data), "\n")
inputstring1 := strings.Replace(inputstring,"Speed:","",-1)
inputstring2 := strings.Replace(inputstring1,"Port:","",-1)
inputstring3 := strings.TrimSpace(string(inputstring2))
line = line + " "+inputstring3
}
}
return line+" "+ifvm
}
<file_sep>/src/github.com/shwinpiocess/cc/dcmdb/dinsert.go
package dcmdb
import (
"fmt"
"github.com/shwinpiocess/cc/models"
)
func Dinsert() {
var cmdbhosts []*models.CmdbHost
out := make(map[string]interface{})
for i:=0;i<3;i++ {
cmdbhost := new(models.CmdbHost)
cmdbhost.Hostname = "odzipkin03"+fmt.Sprintf("%d", i)
cmdbhosts = append(cmdbhosts, cmdbhost)
}
/*
host.PublicIP = "10.78.210.105"
host.PrivateIP = ""
host.OSName = "CentOS Linux release 7.2.1511 (Core)"
host.Cpunum = 2
host.Cputype = "Intel Xeon E312xx (Sandy Bridge)"
host.Memsize = 4294967296
host.Disksize = 42949672960
*/
if len(cmdbhosts)==1 {
for _,cmdbhost := range cmdbhosts{
models.AddCmdbaHost(cmdbhost)
}
}else {
if err := models.AddCmdbHost(cmdbhosts); err == nil {
out["success"] = true
out["message"] = "导入成功!"
} else {
out["success"] = false
out["message"] = "主机导入数据库出现问题,请联系管理员!"
}
}
}<file_sep>/src/github.com/shwinpiocess/cc/controllers/tkbl.go
package controllers
import (
"fmt"
//"github.com/astaxie/beego"
//"strconv"
"strings"
//"time"
"net/http"
"bytes"
"io/ioutil"
"github.com/shwinpiocess/cc/models"
//"github.com/shwinpiocess/cc/utils"
)
type TkblController struct {
BaseController
}
func (this *TkblController) Index() {
id:=1
//info, options, _ := models.GetEmptyById(this.defaultApp.Id)
info, options, _ := models.GetCmdbEmptyById(id)
this.Data["data"] = info
this.Data["options"] = options
fmt.Println("###tkbl.data:####",info)
this.TplName = "tkbl/hindex.html"
}
func (this *TkblController) Tkblapi() {
fmt.Println("--->")
this.TplName = "tkbl/tkblapi.html"
}
func (this *TkblController) PostTkblapi() {
ep := strings.TrimSpace(this.GetString("endpoint", ""))
ops := strings.TrimSpace(this.GetString("ops", ""))
client := &http.Client{}
body := []byte("endpoint="+ep+"&ops="+ops)
req, _ := http.NewRequest("POST", "http://10.78.218.100:8089/tkbl", bytes.NewBuffer(body))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
resp_body, err := ioutil.ReadAll(resp.Body)
/*
if err != nil {
this.Ctx.Output.Body([]byte(err.Error()))
} else {
this.Ctx.Output.Body([]byte(resp_body))
}
*/
out := make(map[string]interface{})
if err != nil {
out["success"] = false
this.jsonResult(out)
} else {
out["success"] = true
out["data"] = string(resp_body)
//out["total"] = len(l)
this.jsonResult(out)
}
}<file_sep>/README.md
# bk_dcmdb
###0603 modify app
<file_sep>/src/gitcafe.com/ops/meta/store/agents.go
package store
import (
"gitcafe.com/ops/common/model"
"github.com/shwinpiocess/cc/models"
"sync"
"fmt"
)
type AgentsMap struct {
sync.RWMutex
M map[string]*model.RealAgent
}
func NewAgentsMap() *AgentsMap {
return &AgentsMap{M: make(map[string]*model.RealAgent)}
}
func (this *AgentsMap) Get(agentName string) (*model.RealAgent, bool) {
this.RLock()
defer this.RUnlock()
val, exists := this.M[agentName]
return val, exists
}
func (this *AgentsMap) Len() int {
this.RLock()
defer this.RUnlock()
return len(this.M)
}
func (this *AgentsMap) IsStale(before int64) bool {
this.RLock()
defer this.RUnlock()
for _, ra := range this.M {
if ra.Timestamp > before {
return false
}
}
return true
}
func (this *AgentsMap) Put(agentName string, realAgent *model.RealAgent) {
this.Lock()
defer this.Unlock()
this.M[agentName] = realAgent
}
type HostAgentsMap struct {
sync.RWMutex
M map[string]*AgentsMap
}
func NewHostAgentsMap() *HostAgentsMap {
return &HostAgentsMap{M: make(map[string]*AgentsMap)}
}
var HostAgents = NewHostAgentsMap()
func (this *HostAgentsMap) Get(hostname string) (*AgentsMap, bool) {
this.RLock()
defer this.RUnlock()
val, exists := this.M[hostname]
return val, exists
}
func (this *HostAgentsMap) Put(hostname string, am *AgentsMap) {
this.Lock()
defer this.Unlock()
this.M[hostname] = am
}
func (this *HostAgentsMap) Hostnames() []string {
this.RLock()
defer this.RUnlock()
count := len(this.M)
hostnames := make([]string, count)
i := 0
for hostname := range this.M {
hostnames[i] = hostname
i++
}
return hostnames
}
func (this *HostAgentsMap) Delete(hostname string) {
this.Lock()
defer this.Unlock()
delete(this.M, hostname)
}
func (this *HostAgentsMap) Status(agentName string) (ret map[string]*model.RealAgent) {
ret = make(map[string]*model.RealAgent)
this.RLock()
defer this.RUnlock()
for hostname, agents := range this.M {
ra, exists := agents.Get(agentName)
if !exists {
ret[hostname] = nil
} else {
ret[hostname] = ra
}
}
return
}
func ParseHeartbeatRequest(req *model.HeartbeatRequest) {
if req.RealAgents == nil || len(req.RealAgents) == 0 {
return
}
agentsMap, exists := HostAgents.Get(req.Hostname)
if exists {
for _, a := range req.RealAgents {
agentsMap.Put(a.Name, a)
}
} else {
am := NewAgentsMap()
for _, a := range req.RealAgents {
am.Put(a.Name, a)
}
HostAgents.Put(req.Hostname, am)
}
}
//CMDB
type CmdbsMap struct {
sync.RWMutex
M map[string]*model.CmdbAgent
}
func NewCmdbsMap() *CmdbsMap {
return &CmdbsMap{M: make(map[string]*model.CmdbAgent)}
}
var CmdbA = NewCmdbsMap()
func (this *CmdbsMap) Get(hostname string) (*model.CmdbAgent, bool) {
this.RLock()
defer this.RUnlock()
val, exists := this.M[hostname]
return val, exists
}
func (this *CmdbsMap) Len() int {
this.RLock()
defer this.RUnlock()
return len(this.M)
}
func (this *CmdbsMap) IsStale(before int64) bool {
this.RLock()
defer this.RUnlock()
for _, ra := range this.M {
if ra.Timestamp > before {
return false
}
}
return true
}
func (this *CmdbsMap) Put(hostname string, cmdbAgent *model.CmdbAgent) {
this.Lock()
defer this.Unlock()
this.M[hostname] = cmdbAgent
}
func (this *CmdbsMap) Status() (ret map[string]*model.CmdbAgent) {
/*
ret = make(map[string]*model.CmdbAgent)
this.RLock()
defer this.RUnlock()
*/
return this.M
}
func ParseCmdbhbRequest(req *model.CmdbhbRequest) {
if req.CmdbAgents == nil || len(req.CmdbAgents) == 0 {
return
}
_, exists := CmdbA.Get(req.Hostname)
if exists {
for _,cma := range req.CmdbAgents {
fmt.Println("have hostname",req.Hostname)
CmdbA.Put(req.Hostname,cma)
}
} else {
for _,cma := range req.CmdbAgents {
CmdbA.Put(req.Hostname,cma)
cnt,err:=models.GetCmdbHostCountbyHn(req.Hostname)
if cnt == 0 && err==nil {
Cinsert(req.Hostname,cma)
}
}
}
}
func Cinsert(hn string,cma *model.CmdbAgent) {
var cmdbhosts []*models.CmdbHost
out := make(map[string]interface{})
cmdbhost := new(models.CmdbHost)
cmdbhost.Hostname = hn
cmdbhost.PublicIP = cma.PublicIP
cmdbhost.PrivateIP = cma.PrivateIP
cmdbhost.OSName = cma.OSName
cmdbhost.Cpunum = cma.Cpunum
cmdbhost.Cputype = cma.Cputype
cmdbhost.Memsize = cma.Memsize
cmdbhost.Disksize = cma.Disksize
cmdbhost.Vminfo = cma.Vminfo
cmdbhosts = append(cmdbhosts, cmdbhost)
if len(cmdbhosts)==1 {
for _,cmdbhost := range cmdbhosts{
models.AddCmdbaHost(cmdbhost)
}
}else {
if err := models.AddCmdbHost(cmdbhosts); err == nil {
out["success"] = true
out["message"] = "导入成功!"
} else {
out["success"] = false
out["message"] = "主机导入数据库出现问题,请联系管理员!"
}
}
}
|
d0e1081a6f7aead193c56b94a2a001468b2cdfc4
|
[
"JavaScript",
"Go",
"Markdown"
] | 33 |
Go
|
chenqi123/bk_dcmdb
|
3a13e8e0ca09afbe28f0d1a8411c8e542d950a1f
|
ccac61262e8cf1a4158de5a910c3a54efbf5790d
|
refs/heads/main
|
<repo_name>MayankRanjan10/Car-Game<file_sep>/carcontrol.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class carcontrol : MonoBehaviour
{
private Vector3 startPosition, startRotation;
[Range(-1f, 1f)]
public float a, t;
public float timeSinceStart = 0f;
[Header("Fitness")]
public float overallFitness;
public float distanceMultipler = 1.4f;
public float avgSpeedMultiplier = 0.2f;
public float sensorMultiplier = 0.1f;
private Vector3 lastPosition;
private float totalDistanceTravelled;
private float avgSpeed;
private float aSensor, bSensor, cSensor;
private void Awake()
{
startPosition = transform.position;
startRotation = transform.eulerAngles;
}
public void Reset()
{
timeSinceStart = 0f;
totalDistanceTravelled = 0f;
avgSpeed = 0f;
lastPosition = startPosition;
overallFitness = 0f;
transform.position = startPosition;
transform.eulerAngles = startRotation;
}
private void OnCollisionEnter(Collision collision)
{
Reset();
}
private void FixedUpdate()
{
InputSensors();
lastPosition = transform.position;
MoveCar(a, t);
timeSinceStart += Time.deltaTime;
CalculateFitness();
//a = 0;
//t = 0;
}
private void CalculateFitness()
{
totalDistanceTravelled += Vector3.Distance(transform.position, lastPosition);
avgSpeed = totalDistanceTravelled / timeSinceStart;
overallFitness = (totalDistanceTravelled * distanceMultipler) + (avgSpeed * avgSpeedMultiplier) + (((aSensor + bSensor + cSensor) / 3) * sensorMultiplier);
if (timeSinceStart > 1000 && overallFitness < 50)
{
Reset();
}
if (overallFitness >= 1000)
{
Reset();
}
}
private void InputSensors()
{
Vector3 a = (transform.forward + transform.right);
Vector3 b = (transform.forward);
Vector3 c = (transform.forward - transform.right);
Ray r = new Ray(transform.position, a);
RaycastHit hit;
if (Physics.Raycast(r, out hit))
{
aSensor = hit.distance / 2;
//print("A = " + aSensor);
}
r.direction = b;
if (Physics.Raycast(r, out hit))
{
bSensor = hit.distance / 2;
//print("B = " + bSensor);
}
r.direction = c;
if (Physics.Raycast(r, out hit))
{
cSensor = hit.distance / 2;
//print("C = " + cSensor);
}
}
private Vector3 inp;
public void MoveCar(float v, float h)
{
inp = Vector3.Lerp(Vector3.zero, new Vector3(v * 11.4f, 0, 0), 0.02f);
inp = transform.TransformDirection(inp);
transform.position += inp;
transform.eulerAngles += new Vector3(0, (h * 90) * 0.02f, 0);
}
}
|
f853eb18c142aacf1333a102c4cba51f62bbb660
|
[
"C#"
] | 1 |
C#
|
MayankRanjan10/Car-Game
|
de5a9f3cf9c350a4124b68ce18468e2100529c8b
|
b7a493e34a81629dbf654c7d0b9332fefea5d24a
|
refs/heads/master
|
<file_sep>var image;
var link;
//main function runs on page load
function main() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
var t = setTimeout(main, 500);
document.getElementById('date').innerHTML =
today.toDateString() + " " + h + ":" + m + ":" + s;
link = document.getElementById("contactPage");
link.addEventListener("click", contactLink);
link = document.getElementById("homePage");
link.addEventListener("click", homeLink);
link = document.getElementById("orderPage");
link.addEventListener("click", orderLink);
var form = document.getElementById("orderForm");
form.addEventListener("change", formChanged);
form.addEventListener("submit", validateForm);
window.onscroll = function() {
scrollFunction()
};
}
function validateForm(event){
var formValid = true;
var valid = document.getElementById("selectPizza");
if (valid.address.value == ""){
formValid = false;
document.getElementById("addressLine").style.display="block";
event.preventDefault();
}
else {
document.getElementById("addressLine").style.display="none";
}
if (valid.postcode.value == ""){
formValid = false;
document.getElementById("postcode").style.display="block";
event.preventDefault();
}
else {
document.getElementById("postcode").style.display="none";
}
}
function formChanged(event){
var form = document.getElementById("selectPizza");
var total = 0;
var choices = "";
var itemPrice = 0;
var total2 = 0;
var choices2 = "";
var itemPrice2 = 0;
var total3 = 0;
var choices3 = "";
var itemPrice3 = 0;
for(var i = 0; i < form.size.length; i++){
if (form.size[i].checked){
itemPrice = parseFloat(form.size[i].dataset.price );
total = total + itemPrice;
choices = choices + form.size[i].dataset.humanDesc + " - £" + itemPrice + "<p>";
}
}
for(var i = 0; i < form.extra.length; i++){
if (form.extra[i].checked){
itemPrice2 = parseFloat(form.extra[i].dataset.price );
total2 = total2 + itemPrice2;
choices2 = choices2 + form.extra[i].dataset.humanDesc + " - £" + itemPrice2 + "<p>";
}
}
for(var i = 0; i < form.topping.length; i++){
if (form.topping[i].checked){
itemPrice3 = parseFloat(form.topping[i].dataset.price );
total3 = total3 + itemPrice3;
choices3 = choices3 + form.topping[i].dataset.humanDesc + " - £" + itemPrice3 + "<p>";
}
}
document.getElementById("choices").innerHTML = choices + choices3 + choices2;
document.getElementById("price").innerHTML ="Total: £" + (total+total2+total3);
}
function orderLink(){
window.location.href="order.html";
}
function homeLink(){
window.location.href="index.html";
}
function contactLink(){
window.location.href="contact.html";
}
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop >20)
{
document.getElementById("myBtn").style.display = "block";
}
else
{
document.getElementById("myBtn").style.display = "none";
}
}
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
function checkTime(i) {
if (i < 10) {i = "0" + i} // add zero in front of numbers < 10
return i;
}<file_sep>//global var
var image;
var mainImage;
var link;
//main function runs on page load
function main() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
var t = setTimeout(main, 500);
document.getElementById('date').innerHTML =
today.toDateString() + " " + h + ":" + m + ":" + s;
image = document.getElementById("rolloverpizza");
image.addEventListener("mouseover", mouseOver);
image.addEventListener("mouseout", mouseOut);
mainImage = document.getElementById("mainImg")
var img2 = document.getElementById("img2");
img2.addEventListener("click", img2Clicked);
var img1 = document.getElementById("img1");
img1.addEventListener("click", img1Clicked);
var img3 = document.getElementById("img3");
img3.addEventListener("click", img3Clicked);
var img4 = document.getElementById("img4");
img4.addEventListener("click", img4Clicked);
var img5 = document.getElementById("img5");
img5.addEventListener("click", img5Clicked);
link = document.getElementById("contactPage");
link.addEventListener("click", contactLink);
link = document.getElementById("homePage");
link.addEventListener("click", homeLink);
link = document.getElementById("orderPage");
link.addEventListener("click", orderLink);
window.onscroll = function() {
scrollFunction()
};
}
function orderLink(){
window.location.href="order.html";
}
function homeLink(){
window.location.href="index.html";
}
function contactLink(){
window.location.href="contact.html";
}
function img5Clicked(){
mainImage.src = "img/main5.jpg";
}
function img4Clicked(){
mainImage.src = "img/main4.jpeg";
}
function img3Clicked(){
mainImage.src = "img/main3.png";
}
function img1Clicked(){
mainImage.src = "img/main1.jpg";
}
function img2Clicked(){
mainImage.src = "img/main2.jpg";
}
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop >20)
{
document.getElementById("myBtn").style.display = "block";
}
else
{
document.getElementById("myBtn").style.display = "none";
}
}
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
function checkTime(i) {
if (i < 10) {i = "0" + i} // add zero in front of numbers < 10
return i;
}
function mouseOver() {
image.src = "img/pizza2.jpg";
}
function mouseOut() {
image.src = "img/pizza2gray.jpg";
}
function scrollToTop() {
window.scrollTo(0, 0);
}
|
fc15e728bed6dacf8903256cd45c1bf4a35e1979
|
[
"JavaScript"
] | 2 |
JavaScript
|
theodoros003/Final-Assesment
|
34d1f4d2f3900356c5401ae201daeda4665598c2
|
4990bf353b3d26944457483545c0aae3e65199d4
|
refs/heads/main
|
<repo_name>PopaBobaFeta/ToDoList<file_sep>/Back/src/main/java/com/csse/restapi/restapireact/repositories/CardsRepository.java
package com.csse.restapi.restapireact.repositories;
import com.csse.restapi.restapireact.entities.Cards;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface CardsRepository extends JpaRepository<Cards,Integer> {
Cards findAllById(int id);
Cards deleteById(int id);
List<Cards> findAllByPriority(String priority);
}
<file_sep>/Back/src/main/resources/application.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=<PASSWORD>
server.port=8080
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
<file_sep>/Back/src/main/java/com/csse/restapi/restapireact/services/impl/CardsServiceImpl.java
package com.csse.restapi.restapireact.services.impl;
import com.csse.restapi.restapireact.entities.Cards;
import com.csse.restapi.restapireact.repositories.CardsRepository;
import com.csse.restapi.restapireact.services.CardsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CardsServiceImpl implements CardsService {
@Autowired
private CardsRepository cardsRepository;
@Override
public List<Cards> getAllCards() {
return cardsRepository.findAll();
}
@Override
public Cards addCard(Cards c) {
return cardsRepository.save(c);
}
@Override
public Cards findAllById(int id) {
return cardsRepository.findAllById(id);
}
@Override
public Cards deleteById(int id) {
return cardsRepository.deleteById(id);
}
@Override
public List<Cards> getAllByPriority(String priority) {
return cardsRepository.findAllByPriority(priority);
}
}
<file_sep>/Front-React-Src/App.js
import React, { useState, useEffect } from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useRouteMatch,
useParams,
NavLink
} from "react-router-dom";
import logo from './logo.svg';
import './App.css';
import Navbar from './Layouts/Navbar'
import Footer from './Layouts/Footer'
import Ads from './Ads'
import Stations from './Stations'
import Login from './Login'
import Register from './Register'
import Cabinet from './Cabinet'
import AddCard from './AddCard'
import AddImage from './AddImage'
import AddCompany from './AddCompany'
import AddImageCompany from './AddImageCompany'
import Details from './Details'
import Request from './Request'
import { Children } from 'react';
import Responses from './Responses'
function App() {
function Main(){
const [requests, setRequests] = useState([]);
async function getAllRequests() {
let response = await fetch("http://localhost:8080/getAllCards");
let req = await response.json();
console.log('reqqqq', req);
setRequests(req);
}
useEffect(() => {
getAllRequests();
console.log("requests", requests);
}, []);
return (
<>
<div className="cardWrapper">
{requests.map((req, index) => {
return (
<div className="myCard">
<div className="myCardHeader">
{req.name}
</div>
<div className="myCardPriority">
{req.priority} <p>{req.addedDate}</p>
</div>
<div className="myCardDesc">
{req.description}
</div>
<div className="myCardDone">
Сделано
{req.done==true?<input type="checkbox" checked="checked"/> :<input type="checkbox"/>}
</div>
<div className="controlRow">
<button className="danger" ><p>Удалить</p></button>
</div>
</div>
);
})}
</div>
</>
);
}
return (
<>
<Router>
<Navbar/>
<div className="Container">
<Switch>
<Route exact path="/">
<Main/>
</Route>
<Route path="/Ads">
<Ads/>
</Route>
<Route path="/Stations">
<Stations/>
</Route>
<Route path="/Login">
<Login/>
</Route>
<Route path="/Register">
<Register/>
</Route>
<Route path="/cabinet">
<Cabinet/>
</Route>
<Route path="/AddCard">
<AddCard/>
</Route>
<Route path="/AddImage">
<AddImage/>
</Route>
<Route path="/AddCompany">
<AddCompany/>
</Route>
<Route path="/AddImageCompany">
<AddImageCompany/>
</Route>
<Route path={`/Details/:id`} children={<Details/>}>
</Route>
<Route path={`/Request/:id`}>
<Request/>
</Route>
<Route path={`/Responses/:id`}>
<Responses/>
</Route>
</Switch>
</div>
<Footer/>
</Router>
</>
);
}
export default App;
|
c4973a6e8e02e5e4fe8da21f7d3dfebcff4a5385
|
[
"JavaScript",
"Java",
"INI"
] | 4 |
Java
|
PopaBobaFeta/ToDoList
|
021cea04ec9f6cd348aa6ebd7bae905785620156
|
c11e4d0c2ffb6983c1967ed39b404e5810148d2f
|
refs/heads/master
|
<file_sep>import React from "react";
import { NavLink } from "react-router-dom";
import { TopBarLinkTypes } from "../../constants";
class TopBarLinks extends React.Component {
componentDidMount() {
this.setState({
active: window.location.href
});
}
state = {
active: ""
};
render() {
return (
<ul className="nav navbar-nav navbar-right">
{TopBarLinkTypes.map(link => {
return (
<li
className={
this.state.active.includes(link.path) ? "active" : null
}
>
<NavLink
onClick={() => this.setState({ active: link.path })}
to={link.path}
>
{link.title}
</NavLink>
</li>
);
})}
</ul>
);
}
}
export default TopBarLinks;
<file_sep>export * from "./actionTypes";
export * from "./TopBarLinkTypes";
export * from "./FormTypes";
<file_sep>import React from "react";
import Login from "../adminComponents/Login";
import AdminHome from "../adminComponents/AdminHome";
import { Switch, Route, withRouter, Redirect } from "react-router-dom";
import { connect } from "react-redux";
const Routes = props => {
const { authorized } = props.authorized;
return (
<div className="container-fluid routes-block">
<Switch>
<Route
path="/admin/login"
render={() => <Login history={props.history} />}
/>
<Route
path="/admin/home"
render={() =>
authorized ? <AdminHome /> : <Redirect to="/admin/login" />
}
/>
</Switch>
</div>
);
};
function mapStateToProps(state) {
return { authorized: state };
}
export default withRouter(connect(mapStateToProps)(Routes));
<file_sep>import {
UPDATE_STATE,
} from "../constants";
export const updateState = (key, value) => {
return {
type: UPDATE_STATE,
key,
value
};
};
export const handleLogin = ({ username, password, user }, history) => {
return dispatch => {
if (user.username === username && user.password === <PASSWORD>) {
dispatch(updateState("authorized", true));
dispatch(updateState("error", false));
history.push("/admin/home");
} else dispatch(updateState("error", true));
};
};
<file_sep>import React from "react";
import '../Editskills.css';
export default class EditSkills extends React.Component {
constructor(props) {
super(props)
this.state = {
Transactions: [
{ Transaction_id: 1, name: 'Kanishk', age: 21, email: '<EMAIL>' },
{ Transaction_id: 2, name: 'Shubham', age: 19, email: '<EMAIL>' },
{ Transaction_id: 3, name: 'Deepak', age: 16, email: '<EMAIL>' },
{ Transaction_id: 4, name: 'Abhishek', age: 25, email: '<EMAIL>' }
]
}
}
renderTableHeader() {
let header = Object.keys(this.state.Transactions[0])
return header.map((key, index) => {
return <th key={index}>{key.toUpperCase()}</th>
})
}
renderTableData() {
return this.state.Transactions.map((Transaction, index) => {
const { Transaction_id, name, age, email } = Transaction
return (
<tr key={Transaction_id}>
<td>{Transaction_id}</td>
<td>{name}</td>
<td>{age}</td>
<td>{email}</td>
</tr>
)
})
}
render() {
return (
<div>
<h1 id='title'>Transactions Data</h1>
<table id='Transactions'>
<tbody>
<tr>{this.renderTableHeader()}</tr>
{this.renderTableData()}
</tbody>
</table>
</div>
)
}
}<file_sep>import React from "react";
import EditSkills from "./EditSkills";
const AdminHome = () => {
return (
<React.Fragment>
<div className="container">
<EditSkills />
</div>
</React.Fragment>
);
};
export default AdminHome;
<file_sep>export const TopBarLinkTypes = [
{ title: "Login", path: "/admin/login" },
{ title: "Register", path: "/admin/login" }
];
|
5d2e872bffc42ed2862d94ad9cf26dd0875ac949
|
[
"JavaScript"
] | 7 |
JavaScript
|
gaurav145145/0to1SolutionsTask
|
a2e04f23055dac59be670d681994d2de6c53bc26
|
8982617edd1a5bf1b19f86ebde274a9ae9928de2
|
refs/heads/master
|
<repo_name>WebDevMichael/express-api-starter<file_sep>/config/localdev.js
module.exports = {
server: {
host: 'http://localhost',
port: 7878,
},
mysql: {
database: 'proveit',
user: 'gnomeknife',
password: '<PASSWORD>',
host: 'localhost',
port: 32773,
}
};<file_sep>/src/server.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const config = require('config');
const passport = require('passport');
const Sequelize = require('sequelize');
const { initialize } = require('./db/index');
// Start Express
const app = express();
app.use(express.static(`${__dirname}/public`));
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// intercept OPTIONS method
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
// load passport strategies
const localSignupStrategy = require('./passport/local-signup');
const localLoginStrategy = require('./passport/local-login');
passport.use('local-signup', localSignupStrategy);
passport.use('local-login', localLoginStrategy);
// routes
const authRoutes = require('./routes/auth');
app.use('/api/auth', authRoutes);
// pass the authentication checker middleware
const authCheckMiddleware = require('./middleware/auth-check');
// app.use('/api', authCheckMiddleware);
const userRoutes = require('./routes/user');
app.use('/api', authCheckMiddleware, userRoutes);
async function startListening() {
const host = config.get('server.host');
const port = config.get('server.port');
app.listen(port, () => {
console.log('App listening at http://%s:%s', host, port);
});
}
// createRoutes(app, path.join(__dirname, 'routes'));
app.get('/*', (request, response) => {
response.sendFile(path.join(__dirname, '../public/index.html'));
});
async function start() {
try {
// Install middlewares and routes
// Connect and start DB
const sequelize = new Sequelize(
config.get('mysql.database'),
config.get('mysql.user'),
config.get('mysql.password'),
{
host: config.get('mysql.host'),
port: config.get('mysql.port'),
dialect: 'mysql'
}
);
await initialize(sequelize);
} catch (e) {
console.error(e);
}
// Start listening
return await startListening();
}
start();
<file_sep>/src/routes/user.js
const express = require('express');
const config = require('config');
const jwt = require('jsonwebtoken');
const { models } = require('../db/index');
const router = new express.Router();
router.get('/user', async(req, res) => {
const token = req.headers.authorization.split(' ')[1];
jwt.verify(token, config.jwtSecret, (err, decoded) => {
if (err) { return res.status(401).end(); }
const userId = decoded.sub;
return models.user.findById(userId, (userErr, user) => {
if (userErr || !user) {
return res.status(401).end();
}
const { email } = user;
return res.status(200).json({ email });
});
});
});
module.exports = router;<file_sep>/src/db/models/user.js
/* jshint indent: 2 */
module.exports = function(sequelize, DataTypes) {
return sequelize.define('user', {
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'id'
},
name: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'name'
},
email: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true,
field: 'email'
},
password: {
type: DataTypes.STRING(60),
allowNull: false,
field: 'password'
},
rememberToken: {
type: DataTypes.STRING(100),
allowNull: true,
field: 'remember_token'
},
createdAt: {
type: DataTypes.TIME,
allowNull: false,
defaultValue: '0000-00-00 00:00:00',
field: 'created_at'
},
updatedAt: {
type: DataTypes.TIME,
allowNull: false,
defaultValue: '0000-00-00 00:00:00',
field: 'updated_at'
}
}, {
tableName: 'users'
});
};
<file_sep>/src/db/index.js
const fs = require('fs');
const path = require('path');
const Umzug = require('umzug');
const models = {};
exports.models = models;
// https://github.com/sequelize/express-example/blob/master/models/index.js
const loadModels = sequelize => {
const dirModels = path.resolve(__dirname, './models/');
fs
.readdirSync(dirModels)
.filter(file => file !== 'index.js' && file.indexOf('.js') > -1)
.forEach(file => {
const model = sequelize.import(path.join(dirModels, file));
models[model.name] = model;
});
Object.keys(models).forEach(modelName => {
const model = models[modelName];
// This is necessary for the 'as' associations to work in the tests
// Associations
if ('associate' in model) {
// Because the loadModels is being run for each test, it
// would otherwise give an error: You have used the alias ... in two separate associations.
if (!model.isAssociated) {
model.associate(models);
model.isAssociated = true;
}
}
});
};
/**
* Initialize the data layer. Connects and runs migrations.
*
* @returns {Promise}
*/
exports.initialize = async sequelize => {
try {
models.sequelize = sequelize;
const queryInterface = sequelize.getQueryInterface();
loadModels(sequelize);
// Run migrations
sequelize.sync();
} catch (err) {
throw err;
}
};
exports.loadModels = loadModels;
|
6567b031a5ef04e79f790d99348e85f2b5fbc4ea
|
[
"JavaScript"
] | 5 |
JavaScript
|
WebDevMichael/express-api-starter
|
afd8e09204f8e4b02d1a40f4ee035c5d53338140
|
e30e1137677e4f87f818b20dc65df14035150d7f
|
refs/heads/master
|
<file_sep>
/**
* Write a description of DistanceFilter here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class DistanceFilter implements Filter{
private double maxdis;
private Location currentloc;
public DistanceFilter(double max, Location current) {
maxdis = max;
currentloc = current;
}
public boolean satisfies(QuakeEntry qe) {
Location loc = qe.getLocation();
return currentloc.distanceTo(loc)<=maxdis;
}
public String getName() {
return "DistanceFilter";
}
}
<file_sep>
/**
* Write a description of CharactersInPlay here.
*
* @author (your name)
* @version (a version number or a date)
*/
import edu.duke.*;
import java.util.*;
public class CharactersInPlay {
private ArrayList<String> name;
private ArrayList<Integer> count;
public CharactersInPlay(){
name = new ArrayList<String>();
count = new ArrayList<Integer>();
}
public void update(String person) {
int index = person.indexOf(".");
if (index != -1) {
String maybename = person.substring(0, index);
int indexinside = name.indexOf(maybename);
if (indexinside ==-1) {
name.add(maybename);
count.add(1);
}
else {
int value = count.get(indexinside);
count.set(indexinside, value + 1);
}
}
}
public void findAllCharacters() {
FileResource fr = new FileResource();
for (String s : fr.lines()){
s = s.toLowerCase();
update(s);
}
}
public void tester() {
findAllCharacters();
int maxspeak = 0;
int location = 0;
for (int i = 0; i< count.size(); i++) {
if (count.get(i) > maxspeak) {
maxspeak = count.get(i);
location = i;
}
}
System.out.println("Most main character : " + name.get(location) + "and speaked " + maxspeak + " times.");
charactersWithNumParts(10, 15);
}
public void charactersWithNumParts(int num1, int num2) {
System.out.println("Speaked" + num1 +"~" + num2 + " times ");
for (int i = 0; i< count.size(); i++) {
if (count.get(i) >= num1 && count.get(i) <= num2 ) {
System.out.println(name.get(i) + " speaked " +count.get(i)+ " times.");
}
}
}
}
<file_sep>import java.io.BufferedReader;
/**
* The knight class provides a static main method to read the dimensions of a
* board and print a solution of the knight tour.
*
* See <a href="http://en.wikipedia.org/wiki/Knight%27s_tour">Wikipedia:
* Knight's tour</a> for more information.
*
* The algorithm employed is similar to the standard backtracking
* <a href="http://en.wikipedia.org/wiki/Eight_queens_puzzle">eight queens
* algorithm</a>.
*
*/
public class knight {
static long recurCalls = 0; // number of recursive calls to solve()
static final int[][] direction = { { -2, -1 }, { -2, 1 }, { -1, -2 }, { -1, 2 }, { 1, -2 }, { 1, 2 }, { 2, -1 },
{ 2, 1 } };
static int M = 4;
static int N = 4;
static int[][] Board;
static int[][] longestPartial;
private static BufferedReader read;
static boolean solve(int step, int i, int j) {
// recursive backtrack search.
recurCalls++;
Board[i][j] = step;
if (step == N * M)
return true; // all positions are filled
for (int k = 0; k < 8; k++) {
int i1 = i + direction[k][0];
int j1 = j + direction[k][1];
if (isInBounds(i1, j1, true))
if (solve(step + 1, i1, j1))
return true;
}
Board[i][j] = 0; // no more next position, reset on backtrack
return false;
}
static boolean isInBounds(int i, int j, boolean requireOpen) {
boolean isInBounds = 0 <= i && i < N && 0 <= j && j < M;
if (isInBounds && requireOpen)
return Board[i][j] == 0;
return isInBounds;
}
static boolean solveWarnsdorf(int step, int i, int j) {
// recursive backtrack search.
recurCalls++;
Board[i][j] = step;
if (step == N * M)
return true; // all positions are filled
int[][] sortedDirections = sortDirectionsByFewestOnwardMoves(i, j);
for (int k = 0; k < 8; k++) {
int i1 = i + sortedDirections[k][0];
int j1 = j + sortedDirections[k][1];
if (isInBounds(i1, j1, true))
if (solveWarnsdorf(step + 1, i1, j1))
return true;
}
Board[i][j] = 0; // no more next position, reset on backtrack
return false;
}
static int[][] sortDirectionsByFewestOnwardMoves(int i, int j) {
int[][] sortedDirections = copyArray(direction);
// Selection sort
int min;
int onwardMovesOfMin;
for (int x = 0; x < sortedDirections.length; x++) {
// Assume first element is min
min = x;
onwardMovesOfMin = getOnwardMoves(i, j, sortedDirections[x]);
for (int y = x + 1; y < sortedDirections.length; y++) {
int onwardMovesOfCurr = getOnwardMoves(i, j, sortedDirections[y]);
if (onwardMovesOfCurr < onwardMovesOfMin) {
min = y;
onwardMovesOfMin = getOnwardMoves(i, j, sortedDirections[min]);
}
}
if (min != x) {
int[] temp = sortedDirections[x];
sortedDirections[x] = sortedDirections[min];
sortedDirections[min] = temp;
}
}
return sortedDirections;
}
static int[][] copyArray(int[][] array) {
int[][] copy = new int[array.length][array[0].length];
for (int x = 0; x < array.length; x++) {
System.arraycopy(array[x], 0, copy[x], 0, array[0].length);
}
return copy;
}
static int getOnwardMoves(int i, int j, int[] coord) {
i = i + coord[0];
j = j + coord[1];
int moves = 0;
for (int k = 0; k < 8; k++) {
int i1 = i + direction[k][0];
int j1 = j + direction[k][1];
if (isInBounds(i1, j1, true)) {
moves++;
}
}
return moves;
}
static boolean knightMoveAway(int i, int j) {
for (int k = 0; k < 8; k++) {
int i1 = i + direction[k][0];
int j1 = j + direction[k][1];
if (isInBounds(i1, j1, false) && Board[i1][j1] == 1) {
return true;
}
}
return false;
}
static boolean solveClosed(int step, int i, int j) {
// recursive backtrack search.
recurCalls++;
Board[i][j] = step;
if (step == N * M) {
boolean is1MoveAway = knightMoveAway(i, j);
if (is1MoveAway) {
return true;
} else {
Board[i][j] = 0;
return false;
}
}
int[][] sortedDirections = sortDirectionsByFewestOnwardMoves(i, j);
for (int k = 0; k < 8; k++) {
int i1 = i + sortedDirections[k][0];
int j1 = j + sortedDirections[k][1];
if (isInBounds(i1, j1, true))
if (solveClosed(step + 1, i1, j1))
return true;
}
Board[i][j] = 0; // no more next position, reset on backtrack
return false;
}
static boolean solveClosedFixed() {
int i = 0;
int j = 0;
// Set initial step
int step = 1;
Board[i][j] = step;
// Fix the first step
step++;
i += 2;
j += 1;
Board[i][j] = step;
// Recursively find the closed tour
return solveClosed(step, i, j);
}
static boolean solveLongestPartial(int step, int i, int j, int longest) {
// recursive backtrack search.
recurCalls++;
Board[i][j] = step;
if (step == N * M)
return true; // all positions are filled
if (step > longest) {
longest = step;
longestPartial = copyArray(Board);
}
int[][] sortedDirections = sortDirectionsByFewestOnwardMoves(i, j);
for (int k = 0; k < 8; k++) {
int i1 = i + sortedDirections[k][0];
int j1 = j + sortedDirections[k][1];
if (isInBounds(i1, j1, true))
if (solveLongestPartial(step + 1, i1, j1, longest))
return true;
}
Board[i][j] = 0; // no more next position, reset on backtrack
return false;
}
static void printBoard(int[][] solution, String name) {
System.out.println(name);
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; j++)
System.out.print("------");
System.out.println("-");
for (int j = 0; j < M; ++j)
System.out.format("| %3d ", solution[i][j]);
System.out.println("|");
}
for (int j = 0; j < M; j++)
System.out.print("------");
System.out.println("-");
}
/*
* read in the dimensions of Knight's tour board and try to find one.
*/
public static void main(String[] args) {
/*
* read = new BufferedReader(new InputStreamReader(System.in)); try {
* System.out.print("Please enter the number of rows : "); N =
* Integer.parseInt(read.readLine());
*
* System.out.print("Please enter the number of columns : "); M =
* Integer.parseInt(read.readLine()); } catch (Exception ex) {
* System.err.println("Error: " + ex); ex.printStackTrace(); } if (N >
* M) { int i = N; N = M; M = i; }
*/
// 5010
// 25
for (int x = 3; x <= 6; x++) {
for (int y = 3; y <= 6; y++) {
N = x;
M = y;
// create Board and set each entry to 0
Board = new int[N][M];
System.out.println("---------------------------" + N + "x" + M + "-----------------------------");
// Regular
resetBoard();
if (solve(1, 0, 0))
printBoard(Board, "Regular");
else
System.out.println("No tour was found.");
System.out.println("Number of recursive calls = " + recurCalls);
// Warnsdorf
resetBoard();
if (solveWarnsdorf(1, 0, 0))
printBoard(Board, "Warnsdorf");
else
System.out.println("No tour was found.");
System.out.println("Number of recursive calls = " + recurCalls);
// Closed
resetBoard();
if (solveClosed(1, 0, 0))
printBoard(Board, "Closed");
else
System.out.println("No tour was found.");
System.out.println("Number of recursive calls = " + recurCalls);
// 98850173
resetBoard();
if (solveClosedFixed())
printBoard(Board, "Closed Fixed");
else
System.out.println("No tour was found.");
System.out.println("Number of recursive calls = " + recurCalls);
resetBoard();
if (solveLongestPartial(1, 0, 0, 0))
printBoard(Board, "Longest Partial");
else {
printBoard(longestPartial, "Longest Partial");
}
System.out.println("Number of recursive calls = " + recurCalls);
}
}
}
static void resetBoard() {
recurCalls = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
Board[i][j] = 0;
}
}<file_sep>package CSV;
/**
* Print out total number of babies born, as well as for each gender, in a given CSV file of baby name data.
*
* @author Duke Software Team
*/
import java.io.File;
import edu.duke.*;
import org.apache.commons.csv.*;
public class BabyBirth2 {
public void printNames () {
FileResource fr = new FileResource();
for (CSVRecord rec : fr.getCSVParser(false)) {
int numBorn = Integer.parseInt(rec.get(2));
if (numBorn <= 100) {
System.out.println("Name " + rec.get(0) +
" Gender " + rec.get(1) +
" Num Born " + rec.get(2));
}
}
}
public void totalBirths (FileResource fr) {
int totalBirths = 0;
int totalBoys = 0;
int totalGirls = 0;
for (CSVRecord rec : fr.getCSVParser(false)) {
int numBorn = Integer.parseInt(rec.get(2));
totalBirths += numBorn;
if (rec.get(1).equals("M")) {
totalBoys += numBorn;
}
else {
totalGirls += numBorn;
}
}
System.out.println("total births = " + totalBirths);
System.out.println("female girls = " + totalGirls);
System.out.println("male boys = " + totalBoys);
}
public void uniqueNames(FileResource fr) {
int totalBirths = 0;
int uniboys = 0;
int unigirls =0;
for (CSVRecord rec : fr.getCSVParser(false)) {
int numBorn = Integer.parseInt(rec.get(2));
totalBirths += numBorn;
if (rec.get(1).equals("M")) {
uniboys += 1;
}
else {
unigirls += 1;
}
}
System.out.println("total births = " + totalBirths);
System.out.println("# of unique boys names = " + uniboys);
System.out.println("# of unique girls names = " + unigirls);
}
public void tests() {
FileResource fr = new FileResource();
uniqueNames(fr);
}
public int getRank(int year, String name, String gender) {
FileResource fr =
new FileResource("C:\\Users\\박정??\\Downloads\\Course2-Java-CSV\\us_babynames\\us_babynames_by_year\\yob"+year+".csv");
int Rank = 0;
int total =0;
for (CSVRecord rec : fr.getCSVParser(false)) {
String genders = rec.get(1);
if (genders.equals(gender)) {
total += 1;
}
}
for (CSVRecord rec : fr.getCSVParser(false)) {
int numBorn = Integer.parseInt(rec.get(2));
String names = rec.get(0);
String genders = rec.get(1);
if (gender !="M" && gender !="F"){
System.out.println("Enter M or F for gender section");}
else
if (total == Rank) {
Rank = -1;
}
else{
if (genders.equals(gender)) {
Rank += 1;
if (names.equals(name)) {
break;
}
}
}
}
return Rank;
}
public void getName(int year, int rank, String gender) {
FileResource fr =
new FileResource("C:\\Users\\박정??\\Downloads\\Course2-Java-CSV\\us_babynames\\us_babynames_by_year\\yob"+year+".csv");
int Rank = 0;
int total =0;
for (CSVRecord rec : fr.getCSVParser(false)) {
String genders = rec.get(1);
if (genders.equals(gender)) {
total += 1;
}
}
for (CSVRecord rec : fr.getCSVParser(false)) {
int numBorn = Integer.parseInt(rec.get(2));
String names = rec.get(0);
String genders = rec.get(1);
if (gender !="M" && gender !="F"){
System.out.println("Enter M or F for gender section");}
else
if (total == Rank) {
System.out.println("NO NAME");
break;
}
else{
if (genders.equals(gender)) {
Rank += 1;
if (Rank == rank) {
System.out.println(names);
break;
}
}
}
}
}
public void whatIsNameInYear(int year, String name, int newyear, String gender) {
FileResource fr =
new FileResource("C:\\Users\\박정??\\Downloads\\Course2-Java-CSV\\us_babynames\\us_babynames_by_year\\yob"+year+".csv");
FileResource newfr =
new FileResource("C:\\Users\\박정??\\Downloads\\Course2-Java-CSV\\us_babynames\\us_babynames_by_year\\yob"+newyear+".csv");
int Rank = 0;
int total =0;
for (CSVRecord rec : fr.getCSVParser(false)) {
String genders = rec.get(1);
if (genders.equals(gender)) {
total += 1;
}
}
for (CSVRecord rec : fr.getCSVParser(false)) {
int numBorn = Integer.parseInt(rec.get(2));
String names = rec.get(0);
String genders = rec.get(1);
if (gender !="M" && gender !="F"){
System.out.println("Enter M or F for gender section");}
else
if (total == Rank) {
Rank = -1;
}
else{
if (genders.equals(gender)) {
Rank += 1;
if (names.equals(name)) {
break;
}
}
}
}
int rank = 0;
for (CSVRecord rec : newfr.getCSVParser(false)) {
String genders = rec.get(1);
if (genders.equals(gender)) {
total += 1;
}
}
for (CSVRecord rec : newfr.getCSVParser(false)) {
int numBorn = Integer.parseInt(rec.get(2));
String names = rec.get(0);
String genders = rec.get(1);
if (gender !="M" && gender !="F"){
System.out.println("Enter M or F for gender section");}
else
if (total == rank) {
System.out.println("NO NAME");
break;
}
else{
if (genders.equals(gender)) {
rank += 1;
if (Rank == rank) {
System.out.println(name + " born in " + year + " would be " + names + " if she was born in " + newyear);
break;
}
}
}
}
}
public void yearOfHighestRank(String name, String gender){
DirectoryResource dr = new DirectoryResource();
int highestRanka = gethighestRank(dr, gender, name);
System.out.println(highestRanka);
for (File f : dr.selectedFiles()) {
FileResource fr = new FileResource(f);
int eachRank = geteachRank(fr, name, gender);
if (eachRank == highestRanka) {
System.out.println(eachRank);
System.out.println(highestRanka);
System.out.println(f);
}
}
}
public int gethighestRank(DirectoryResource dr, String gender, String name) {
int highestRank = Integer.MAX_VALUE;
for (File f : dr.selectedFiles()) {
FileResource fr = new FileResource(f);
int eachrank = geteachRank(fr, name, gender);
if (eachrank !=-1){
if(highestRank>eachrank){
highestRank = eachrank;
}
}
}return highestRank;
}
}<file_sep>
/**
* Find N-closest quakes
*
* @author <NAME>/Learn to Program
* @version 1.0, November 2015
*/
import java.util.*;
public class ClosestQuakes {
public ArrayList<QuakeEntry> getClosest(ArrayList<QuakeEntry> quakeData, Location current, int howMany) {
ArrayList<QuakeEntry> ret = new ArrayList<QuakeEntry>();
ArrayList<QuakeEntry> copy = new ArrayList<QuakeEntry>(quakeData);
for (int k = 0; k<howMany; k++) {
double closestdis = Double.MAX_VALUE;
int smallest = 0;
for (QuakeEntry qe : copy) {
Location loc = qe.getLocation();
double distanceInMeters = current.distanceTo(loc);
if (distanceInMeters < closestdis) {
closestdis = distanceInMeters;
}
}
for (int i = 1; i<copy.size(); i++) {
QuakeEntry qentry = copy.get(i);
Location loc = qentry.getLocation();
double distanceInMeters = current.distanceTo(loc);
if (distanceInMeters == closestdis) {
smallest = i;
}
}
ret.add(copy.get(smallest));
copy.remove(copy.get(smallest));
}
return ret;
}
public void findLargestQuakes() {
EarthQuakeParser parser = new EarthQuakeParser();
String source = "data/nov20quakedata.atom";
//String source = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.atom";
ArrayList<QuakeEntry> list = parser.read(source);
ArrayList<QuakeEntry> answer = getLargest(list, 1518);
for (QuakeEntry qe: answer) {
System.out.println(qe);
}
System.out.println("read data for "+list.size());
}
public int indexOfLargest(ArrayList<QuakeEntry> data) {
ArrayList<QuakeEntry> answer = new ArrayList<QuakeEntry>();
double largestmag = 0;
int answerind = 0;
for (QuakeEntry qe : data) {
double magnitude = qe.getMagnitude();
if (magnitude > largestmag) {
largestmag = magnitude;
}
}
for (int i = 0; i<data.size(); i++) {
QuakeEntry qentry = data.get(i);
double mageach = qentry.getMagnitude();
if (mageach == largestmag){
answerind = i;
}
}
return answerind;
}
public ArrayList<QuakeEntry> getLargest(ArrayList<QuakeEntry> quakeData, int howMany) {
ArrayList<QuakeEntry> copy = new ArrayList<QuakeEntry>(quakeData);
ArrayList<QuakeEntry> answer = new ArrayList<QuakeEntry>();
for (int i = 0; i < howMany; i++) {
int maxind = indexOfLargest(copy);
answer.add(copy.get(maxind));
copy.remove(copy.get(maxind));
}
return answer;
}
public void findClosestQuakes() {
EarthQuakeParser parser = new EarthQuakeParser();
String source = "data/nov20quakedatasmall.atom";
//String source = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.atom";
ArrayList<QuakeEntry> list = parser.read(source);
System.out.println("read data for "+list.size());
Location jakarta = new Location(-6.211,106.845);
ArrayList<QuakeEntry> close = getClosest(list,jakarta,3);
for(int k=0; k < close.size(); k++){
QuakeEntry entry = close.get(k);
double distanceInMeters = jakarta.distanceTo(entry.getLocation());
System.out.printf("%4.2f\t %s\n", distanceInMeters/1000,entry);
}
System.out.println("number found: "+close.size());
}
}
<file_sep>
/**
* Write a description of TitleLastAndMagnitudeComparator here.
*
* @author (your name)
* @version (a version number or a date)
*/
import java.util.*;
public class TitleLastAndMagnitudeComparator implements Comparator<QuakeEntry>{
private Location myLocation;
private String title;
private double depth;
private double magnitude;
public Location getLocation(){
return myLocation;
}
public double getMagnitude(){
return magnitude;
}
public String getInfo(){
return title;
}
public double getDepth(){
return depth;
}
public int compare(QuakeEntry q1, QuakeEntry q2) {
String[] eachword1 = q1.getInfo().split(" ");
String title1 = eachword1[eachword1.length-1];
String[] eachword2 = q2.getInfo().split(" ");
String title2 = eachword2[eachword2.length-1];
//System.out.println(title1+" "+ title2);
//System.out.println(title1);
if (title1.compareTo(title2) < 0) {
return -1;}
if (title2.compareTo(title1) <0) {
return 1;}
else {
if (q1.getMagnitude() < q2.getMagnitude()) {
return -1;
}
if (q1.getMagnitude() > q2.getMagnitude()) {
return 1;
}
return 0;
}
}
}
<file_sep>import java.util.Random;
public class Project2 {
private static int[] arr;
private static int[] arrCopy;
private static Random randomGenerator;
private static void printArray(int[] arr) {
System.out.print(" [" + arr[0]);
for (int i = 1; i < 25; i++) {
System.out.print(", " + arr[i]);
}
System.out.println("]");
}
private static void printData(int totalTrials, int range, int size, long duration, long comparisons) {
System.out.println("Trial " + totalTrials + " Completed: Range(" + range + ") " + "Size(" + size
+ ") = Duration(" + duration + ") Comparisons(" + comparisons + ")");
}
private static int bottomUpMergeSort(int[] a, int iLeft, int iMiddle, int iRight, int[] tmp) {
int comparisons = 0;
int i, j, k;
i = iLeft;
j = iMiddle;
k = iLeft;
while (i < iMiddle || j < iRight) {
if (i < iMiddle && j < iRight) {
comparisons++;
if (a[i] < a[j])
tmp[k++] = a[i++];
else
tmp[k++] = a[j++];
}
else if (i == iMiddle)
tmp[k++] = a[j++];
else if (j == iRight)
tmp[k++] = a[i++];
}
return comparisons;
}
private static int mergesort(int low, int high) {
int comparisons = 0; // set comparisons as "0"
// Check if low is smaller then high, if not then the array is sorted
if (low < high) {
// Get the index of the element which is in the middle
int middle = low + (high - low) / 2;
// Sort the left side of the array
comparisons += mergesort(low, middle);
// Sort the right side of the array
comparisons += mergesort(middle + 1, high);
// Combine them both
comparisons += merge(low, middle, high);
}
return comparisons;
}
private static int merge(int low, int middle, int high) {
int comparisons = 0; // set comparisons as "0"
// Copy first part into the arrCopy array
for (int i = low; i <= middle; i++) {
arrCopy[i] = arr[i];
}
int i = low;
int j = middle + 1;
int k = low;
while (i <= middle && j <= high) {
comparisons++;
if (arrCopy[i] <= arr[j]) {
arr[k] = arrCopy[i];
i++;
} else {
arr[k] = arr[j];
j++;
}
k++;
}
// Copy the rest of the left part of the array into the target array
while (i <= middle) {
arr[k] = arrCopy[i];
k++;
i++;
}
return comparisons;
}
public static void main(String[] args) {
randomGenerator = new Random();
long start;
long finish;
int size;
int range;
int numTrials = 5;
long totalDuration = 0;
int totalTrials = 0;
long totalComparisons = 0;
// Do merge sort for different ranges of integer values as instructions
for (int currIntRange = 0; currIntRange < 2; currIntRange++) {
if (currIntRange == 0) {
range = 1000; // case 1
} else {
range = 1000000; // case 2
}
// Do merge sort for different sizes of integer values as instructions
for (int currIntSize = 0; currIntSize < 3; currIntSize++) {
if (currIntSize == 0) {
size = 1000000; // case 1
} else if (currIntSize == 1) {
size = 2000000; // case 2
} else {
size = 4000000; // case 3
}
// Do merge sort with current size and current range of integer with 100 trials
for (int currTrial = 0; currTrial < numTrials; currTrial++) {
arr = new int[size];
arrCopy = new int[size];
// Fill the array with 'size' amount of random numbers
for (int i = 0; i < size; i++) {
arr[i] = arrCopy[i] = randomGenerator.nextInt(range) + 1;
}
// get starting time
start = System.currentTimeMillis();
// perform sort
int comparisons = mergesort(0, size - 1);
// get ending time
finish = System.currentTimeMillis();
long duration = finish - start;
totalDuration += duration;
totalTrials++;
totalComparisons += comparisons;
// if we want to see detail processes in each trials, activate printData or erase it.
printData(totalTrials, range, size, duration, comparisons);
}
}
}
long avgDuration = totalDuration / totalTrials;
long avgComparisons = totalComparisons / totalTrials;
System.out.println(
"mergeSort() Average duration(" + avgDuration + ") Average comparisons(" + avgComparisons + ")");
totalTrials = 0;
totalDuration = 0;
totalComparisons = 0; // reset for other sort
// same with previous process
for (int currIntRange = 0; currIntRange < 2; currIntRange++) {
if (currIntRange == 0) {
range = 1000;
} else {
range = 1000000;
}
for (int currIntSize = 0; currIntSize < 3; currIntSize++) {
if (currIntSize == 0) {
size = 1000000;
} else if (currIntSize == 1) {
size = 2000000;
} else {
size = 4000000;
}
// Do merge sort with current size and current range of integer valuse 100 times
for (int currTrial = 0; currTrial < numTrials; currTrial++) {
arr = new int[size];
arrCopy = new int[size];
// Fill the array with 'size' amount of random numbers
for (int i = 0; i < size; i++) {
arr[i] = arrCopy[i] = randomGenerator.nextInt(range) + 1;
}
// get starting time
start = System.currentTimeMillis();
// perform sort
int middle = (size - 1) / 2;
int comparisons = bottomUpMergeSort(arr, 0, middle, size - 1, arrCopy);
// get ending time
finish = System.currentTimeMillis();
long duration = finish - start;
totalDuration += duration;
totalTrials++;
totalComparisons += comparisons;
// if we want to see detail processes in each trials, activate printData or erase it.
printData(totalTrials, range, size, duration, comparisons);
}
}
}
avgDuration = totalDuration / totalTrials;
avgComparisons = totalComparisons / totalTrials;
System.out.println("bottomUpMergeSort() Average duration(" + avgDuration + ") Average comparisons("
+ avgComparisons + ")");
}
}
// conclusion: bottomup merge sort has much less running time and much less comparisons.
// also, in bottom up merge sort, as size increases double, comparisons also double.
// as range <- 1000*range, duration = duration + x (couldnt find relation ship on x, but it increases as range increases
// also, in merge sort, as size increases double, duration increases to double
// as range <- 1000*range, duration = duration + x (couldnt find relation ship on x, but it increases as range increases<file_sep>package Gladlib;
/**
* Write a description of GladLibMap here.
*
* @author (your name)
* @version (a version number or a date)
*/
import edu.duke.*;
import java.util.*;
public class GladLibMap {
private HashMap<String, ArrayList<String>> myMap;
private HashMap<String, ArrayList<String>> UsedmyMap;
private Random myRandom;
private static String dataSourceURL = "http://dukelearntoprogram.com/course3/data";
private static String dataSourceDirectory = "data";
public GladLibMap(){
initializeFromSource(dataSourceDirectory);
myRandom = new Random();
}
public GladLibMap(String source){
initializeFromSource(source);
myRandom = new Random();
}
private void initializeFromSource(String source) {
myMap = new HashMap<String, ArrayList<String>>();
UsedmyMap = new HashMap<String, ArrayList<String>>();
String[] labels = {"adjective", "noun", "color", "country", "name", "animal", "timeframe"};
for (String s : labels){
ArrayList<String> list = readIt(source+"/"+s+".txt");
myMap.put(s, list);
}
}
private String randomFrom(ArrayList<String> source){
int index = myRandom.nextInt(source.size());
return source.get(index);
}
private String getSubstitute(String label) {
if (label.equals("country")) {
UsedmyMap.put("country", myMap.get("country"));
return randomFrom(myMap.get("country"));
}
if (label.equals("color")){
UsedmyMap.put("color", myMap.get("color"));
return randomFrom(myMap.get("color"));
}
if (label.equals("noun")){
UsedmyMap.put("noun", myMap.get("noun"));
return randomFrom(myMap.get("noun"));
}
if (label.equals("name")){
UsedmyMap.put("name", myMap.get("name"));
return randomFrom(myMap.get("name"));
}
if (label.equals("adjective")){
UsedmyMap.put("adjective", myMap.get("adjective"));
return randomFrom(myMap.get("adjective"));
}
if (label.equals("animal")){
UsedmyMap.put("animal", myMap.get("animal"));
return randomFrom(myMap.get("animal"));
}
if (label.equals("timeframe")){
UsedmyMap.put("timeframe", myMap.get("timeframe"));
return randomFrom(myMap.get("timeframe"));
}
if (label.equals("number")){
return ""+myRandom.nextInt(50)+5;
}
return "**UNKNOWN**";
}
private String processWord(String w){
int first = w.indexOf("<");
int last = w.indexOf(">",first);
if (first == -1 || last == -1){
return w;
}
String prefix = w.substring(0,first);
String suffix = w.substring(last+1);
String sub = getSubstitute(w.substring(first+1,last));
return prefix+sub+suffix;
}
private void printOut(String s, int lineWidth){
int charsWritten = 0;
for(String w : s.split("\\s+")){
if (charsWritten + w.length() > lineWidth){
System.out.println();
charsWritten = 0;
}
System.out.print(w+" ");
charsWritten += w.length() + 1;
}
}
private String fromTemplate(String source){
String story = "";
if (source.startsWith("http")) {
URLResource resource = new URLResource(source);
for(String word : resource.words()){
story = story + processWord(word) + " ";
}
}
else {
FileResource resource = new FileResource(source);
for(String word : resource.words()){
story = story + processWord(word) + " ";
}
}
return story;
}
private ArrayList<String> readIt(String source){
ArrayList<String> list = new ArrayList<String>();
if (source.startsWith("http")) {
URLResource resource = new URLResource(source);
for(String line : resource.lines()){
list.add(line);
}
}
else {
FileResource resource = new FileResource(source);
for(String line : resource.lines()){
list.add(line);
}
}
return list;
}
public void makeStory(){
System.out.println("\n");
String story = fromTemplate("data/madtemplate.txt");
printOut(story, 60);
System.out.println("\n");
totalWordsInMap();
System.out.println("\n");
totalWordsConsidered();
}
public void totalWordsInMap(){
int totalwordcount = 0;
for (String s : myMap.keySet()) {
totalwordcount = totalwordcount+myMap.get(s).size();
}
System.out.println(totalwordcount);
}
public void totalWordsConsidered(){
int totalwordcount = 0;
for (String s : UsedmyMap.keySet()) {
totalwordcount = totalwordcount+UsedmyMap.get(s).size();
}
System.out.println(totalwordcount);
}
}
|
a0768e49788aa5ed5b0356dbf69a7096ef5b623f
|
[
"Java"
] | 8 |
Java
|
junhkang/coursera-java
|
54f3ab035f0b9a2246480bbcb3e2f46e486d6e0a
|
3025965257c2e9cceb6ce51b86430d98db5c49c5
|
refs/heads/master
|
<repo_name>SongYHs/End2End-Multiple-Tagging-Model-for-Knowledge-Extraction<file_sep>/Evaluate.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 14 09:59:23 2019
@author: <NAME>
"""
import json
def evaluavtion_triple_new(testresult,senttext,savetagfile,kk=1,max_s=50):
total_predict_right=0.
total_predict=0.
total_right = 0.
prn={}
p={}
r={}
for i in range(kk):
prn[i],p[i],r[i]=0,0,0
f=open(savetagfile,'w')
for i,sent in enumerate(testresult):
tokens=senttext[i]
ptag = sent[0]
ttag = sent[1]
predictrightnum, predictnum ,rightnum,prn0,p0,r0,Pretriplets,Rigtriplets=\
count_sentence_triple_num(ptag,ttag,tokens,kk,max_s)
total_predict_right+=predictrightnum
total_predict+=predictnum
total_right += rightnum
for j in range(kk):
prn[j]+=prn0[j]
p[j]+=p0[j]
r[j]+=r0[j]
newsent=dict()
newsent['tokens']=senttext[i]
newsent['predict tags']=ptag
newsent['right tags']=ttag
newsent['Predict triplets']=Pretriplets
newsent['Right triplets']=Rigtriplets
f.write(json.dumps(newsent)+'\n')
f.close()
P = total_predict_right /float(total_predict) if total_predict!=0 else 0
R = total_predict_right /float(total_right)
F = (2*P*R)/float(P+R) if P!=0 else 0
return P,R,F,total_predict_right,total_predict,total_right,prn,p,r
def count_sentence_triple_num(ptag,ttag,tokens,kk=1,max_s=50):
#transfer the predicted tag sequence to triple index
predict_triplet=[]
right_triplet=[]
prn0={}
p0={}
r0={}
for i in range(kk):
predict_rmpair0= tag_to_triple_index_new1(ptag[i*max_s:i*max_s+max_s])
right_rmpair0 = tag_to_triple_index_new1(ttag[i*max_s:i*max_s+max_s])
predict_triplet0=proximity(predict_rmpair0)
right_triplet0=proximity(right_rmpair0)
for pt in predict_triplet0:
if not predict_triplet.__contains__(pt):
predict_triplet.append(pt)
for rt in right_triplet0:
if not right_triplet.__contains__(rt):
right_triplet.append(rt)
prn0[i]=0
p0[i]=len(predict_triplet0)
r0[i]=len(right_triplet0)
for triplet in predict_triplet0:
if right_triplet0.__contains__(triplet):
prn0[i]+=1
predict_right_num = 0 # the right number of predicted triple
predict_num = len(predict_triplet) # the number of predicted triples
right_num = len(right_triplet)
pre_relationMentions=get_triplet(predict_triplet,tokens)
rig_relationMentions=get_triplet(right_triplet,tokens)
for triplet in predict_triplet:
if right_triplet.__contains__(triplet):
predict_right_num+=1
return predict_right_num,predict_num,right_num,prn0,p0,r0,pre_relationMentions,rig_relationMentions
def get_triplet(tpositions,tokens):
rels=[]
for triplet in tpositions:
e1=triplet[0]
label=triplet[1]
e2=triplet[2]
entity1=''
for e1i in range(e1[0],e1[1]):
entity1+=' '+tokens[e1i]
entity2=''
for e2i in range(e2[0],e2[1]):
entity2+=' '+tokens[e2i]
rel={"em1Text":entity1,"em2Text":entity2,"label":label}
rels.append(rel)
return rels
def proximity(predict_rmpair):
triplet=[]
for type1 in predict_rmpair:
eelist = predict_rmpair[type1]
e1 = eelist[0]
e2 = eelist[1]
if len(e2)<len(e1):
for i in range(len(e2)):
e2i0,e2i1=e2[i][0],e2[i][1]
e2i=(e2i0+e2i1)/2
mineij=100
for j in range(len(e1)):
e1j=(e1[j][0]+e1[j][1])/2
if mineij>abs(e1j-e2i):
mineij=abs(e1j-e2i)
e1ij=e1[j]
e1.remove(e1ij)
triplet.append((e1ij,type1,e2[i]))
else:
for i in range(len(e1)):
e1i0,e1i1=e1[i][0],e1[i][1]
e1i=(e1i0+e1i1)/2
mineij=100
for j in range(len(e2)):
e2j=(e2[j][0]+e2[j][1])/2
if mineij>abs(e1i-e2j):
mineij=abs(e1i-e2j)
e2ij=e2[j]
e2.remove(e2ij)
triplet.append((e1[i],type1,e2ij))
return triplet
def tag_to_triple_index_new1(ptag):
rmpair={}
for i in range(0,len(ptag)):
tag = ptag[i]
if not tag.__eq__("O") and not tag.__eq__(""):
type_e = tag.split("__")
if not rmpair.__contains__(type_e[0]):
eelist=[]
e1=[]
e2=[]
if type_e[1].__contains__("1"):
if type_e[1].__contains__("S"):
e1.append((i,i+1))
elif type_e[1].__contains__("B"):
j=i+1
v='B'
while j < len(ptag):
# print(j,len(ptag))
if ptag[j].__contains__("1") and ptag[j].__contains__(type_e[0]):
if ptag[j].__contains__("I"):
j+=1
v='I'
elif ptag[j].__contains__("L") :
j+=1
v='L'
break
else:
break
else:
break
if v=='L':
e1.append((i, j))
elif type_e[1].__contains__("2"):
if type_e[1].__contains__("S"):
e2.append((i,i+1))
elif type_e[1].__contains__("B"):
j=i+1
v='B'
while j < len(ptag):
if ptag[j].__contains__("2") and ptag[j].__contains__(type_e[0]):
if ptag[j].__contains__("I"):
j+=1
v='I'
elif ptag[j].__contains__("L") :
j+=1
v='L'
break
else:
break
else:
break
if v=='L':
e2.append((i, j))
eelist.append(e1)
eelist.append(e2)
rmpair[type_e[0]] = eelist
else:
eelist=rmpair[type_e[0]]
e1=eelist[0]
e2=eelist[1]
if type_e[1].__contains__("1"):
if type_e[1].__contains__("S"):
e1.append((i,i+1))
elif type_e[1].__contains__("B"):
j=i+1
v='B'
while j < len(ptag):
if ptag[j].__contains__("1") and ptag[j].__contains__(type_e[0]):
if ptag[j].__contains__("I"):
j+=1
v='I'
elif ptag[j].__contains__("L") :
j+=1
v='L'
break
else:
break
else:
break
if v=='L':
e1.append((i, j))
elif type_e[1].__contains__("2"):
if type_e[1].__contains__("S"):
e2.append((i,i+1))
elif type_e[1].__contains__("B"):
j=i+1
v='B'
while j < len(ptag):
if ptag[j].__contains__("2") and ptag[j].__contains__(type_e[0]):
if ptag[j].__contains__("I"):
j+=1
v='I'
elif ptag[j].__contains__("L") :
j+=1
v='L'
break
else:
break
else:
break
if v=='L':
e2.append((i, j))
eelist[0]=e1
eelist[1]=e2
rmpair[type_e[0]] = eelist
return rmpair
<file_sep>/Encoder_Decoder.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 14 09:52:41 2019
@author: <NAME>
"""
from keras.layers.recurrent import GRU,LSTM
from keras.layers.core import Layer
import keras.backend as K
import theano
class LSTM_Decoder(LSTM):
input_ndim = 3
def __init__(self, output_length, hidden_dim=None,state_input=True, **kwargs):
self.output_length = output_length
self.hidden_dim = hidden_dim
# self.output_dim=output_dim
self.state_outputs = []
self.state_input = state_input
self.return_sequences = True #Decoder always returns a sequence.
self.updates = []
super(LSTM_Decoder, self).__init__(**kwargs)
def build(self):
input_shape = self.input_shape
dim = input_shape[-1]
self.input_dim = dim
self.input = K.placeholder(input_shape)
if not self.hidden_dim:
self.hidden_dim = dim
hdim = self.hidden_dim
if not self.output_dim:
self.output_dim = dim
outdim = self.output_dim
if self.stateful or self.state_input or len(self.state_outputs) > 0:
self.reset_states()
else:
self.states = [None, None]
self.W_i = self.init((outdim, hdim))
self.U_i = self.inner_init((hdim, hdim))
self.b_i = K.zeros((hdim))
self.W_f = self.init((outdim, hdim))
self.U_f = self.inner_init((hdim, hdim))
self.b_f = self.forget_bias_init((hdim))
self.W_c = self.init((outdim, hdim))
self.U_c = self.inner_init((hdim, hdim))
self.b_c = K.zeros((hdim))
self.W_o = self.init((outdim, hdim))
self.U_o = self.inner_init((hdim, hdim))
self.b_o = K.zeros((hdim))
self.W_x = self.init((hdim, outdim))
self.b_x = K.zeros((outdim))
self.V_i = self.init((dim, hdim))
self.V_f = self.init((dim, hdim))
self.V_c = self.init((dim, hdim))
self.V_o = self.init((dim, hdim))
self.trainable_weights = [
self.W_i, self.U_i, self.b_i,
self.W_c, self.U_c, self.b_c,
self.W_f, self.U_f, self.b_f,
self.W_o, self.U_o, self.b_o,
self.W_x, self.b_x,
self.V_i, self.V_c, self.V_f, self.V_o
]
self.input_length = self.input_shape[-2]
if not self.input_length:
raise Exception ('AttentionDecoder requires input_length.')
def set_previous(self, layer, connection_map={}):
self.previous = layer
self.build()
def get_initial_states(self, X):
# build an all-zero tensor of shape (samples, hidden_dim)
initial_state = K.zeros_like(X) # (samples, input_dim)
reducer = K.zeros((self.input_dim, self.hidden_dim))
initial_state = K.dot(initial_state, reducer) # (samples, hidden_dim)
initial_states = [initial_state for _ in range(len(self.states))]
return initial_states
def ssstep(self,
h,
x_tm1,
h_tm1, c_tm1,
u_i, u_f, u_o, u_c, w_i, w_f, w_c, w_o, w_x, v_i, v_f, v_c, v_o, b_i, b_f, b_c, b_o, b_x):
xi_t = K.dot(x_tm1, w_i)+ b_i+ K.dot(h, v_i)
xf_t = K.dot(x_tm1, w_f) + b_f+ K.dot(h, v_f)
xc_t = K.dot(x_tm1, w_c) + b_c+ K.dot(h, v_c)
xo_t = K.dot(x_tm1, w_o) + b_o+ K.dot(h, v_o)
i_t = self.inner_activation(xi_t + K.dot(h_tm1, u_i))
f_t = self.inner_activation(xf_t + K.dot(h_tm1, u_f))
c_t = f_t * c_tm1 + i_t * self.activation(xc_t + K.dot(h_tm1, u_c))
o_t = self.inner_activation(xo_t + K.dot(h_tm1, u_o))
h_t = o_t * self.activation(c_t)
x_t =self.activation(K.dot(h_t, w_x) + b_x)
return x_t, h_t, c_t
def get_output(self, train=False):
H = self.get_input(train)
Hh = K.permute_dimensions(H, (1, 0, 2))
def rstep(o,index,Hh):
return Hh[index],index-1
[RHh,index],update = theano.scan(
rstep,
n_steps=Hh.shape[0],
non_sequences=[Hh],
outputs_info= [Hh[-1]]+[-1])
X = K.permute_dimensions(H, (1, 0, 2))[-1]
outdim=self.output_dim
X1=X[:,:outdim]+X[:,outdim:]
if self.stateful or self.state_input or len(self.state_outputs) > 0:
initial_states = self.states
else:
initial_states = self.get_initial_states(X)
[outputs,hidden_states, cell_states], updates = theano.scan(
self.ssstep,
sequences=RHh,
n_steps = self.output_length,
outputs_info=[X1] + initial_states,
non_sequences=[self.U_i, self.U_f, self.U_o, self.U_c,
self.W_i, self.W_f, self.W_c, self.W_o,
self.W_x, self.V_i, self.V_f, self.V_c,
self.V_o, self.b_i, self.b_f, self.b_c,
self.b_o, self.b_x])
states = [hidden_states[-1], cell_states[-1]]
if self.stateful and not self.state_input:
self.updates = []
for i in range(2):
self.updates.append((self.states[i], states[i]))
for o in self.state_outputs:
o.updates = []
for i in range(2):
o.updates.append((o.states[i], states[i]))
return K.permute_dimensions(outputs, (1, 0, 2))
@property
def output_shape(self):
shape = list(super(LSTM_Decoder, self).output_shape)
shape[1] = self.output_length
return tuple(shape)
def get_config(self):
config = {'name': self.__class__.__name__}
base_config = super(LSTM_Decoder, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
class GRU_Decoder(GRU):
input_ndim = 3
def __init__(self, output_length, hidden_dim=None,state_input=True, **kwargs):
self.output_length = output_length
self.hidden_dim = hidden_dim
self.state_outputs = []
self.state_input = state_input
self.return_sequences = True #Decoder always returns a sequence.
self.updates = []
super(GRU_Decoder, self).__init__(**kwargs)
def build(self):
input_shape = self.input_shape
dim = input_shape[-1]
self.input_dim = dim
self.input = K.placeholder(input_shape)
if not self.hidden_dim:
self.hidden_dim = dim
hdim = self.hidden_dim
if not self.output_dim:
self.output_dim = dim
outdim = self.output_dim
if self.stateful or self.state_input or len(self.state_outputs) > 0:
self.reset_states()
else:
self.states = [None]
self.W_r = self.init((outdim, hdim))
self.U_r = self.inner_init((hdim, hdim))
self.b_r = K.zeros((hdim))
self.W_z = self.init((outdim, hdim))
self.U_z = self.inner_init((hdim, hdim))
self.b_z = K.zeros((hdim))#self.forget_bias_init((hdim))
self.W_s = self.init((outdim, hdim))
self.U_s = self.inner_init((hdim, hdim))
self.b_s = K.zeros((hdim))
self.W_x = self.init((hdim, outdim))
self.b_x = K.zeros((outdim))
self.V_r = self.init((dim, hdim))
self.V_z = self.init((dim, hdim))
self.V_s = self.init((dim, hdim))
self.trainable_weights = [
self.W_r, self.U_r, self.b_r,
self.W_z, self.U_z, self.b_z,
self.W_s, self.U_s, self.b_s,
self.W_x, self.b_x,
self.V_r, self.V_z, self.V_s
]
self.input_length = self.input_shape[-2]
if not self.input_length:
raise Exception ('AttentionDecoder requires input_length.')
def set_previous(self, layer, connection_map={}):
self.previous = layer
self.build()
def get_initial_states(self, X):
initial_state = K.zeros_like(X) # (samples, input_dim)
reducer = K.zeros((self.input_dim, self.hidden_dim))
initial_state = K.dot(initial_state, reducer) # (samples, hidden_dim)
initial_states = [initial_state]# for _ in range(len(self.states))]
return initial_states
def ssstep(self,
h,
x_tm1,
s_tm1,
u_r, u_z, u_s, w_r, w_z, w_s, w_x, v_r, v_z, v_s, b_r, b_z, b_s, b_x):
xr_t = K.dot(x_tm1, w_r)+ b_r+ K.dot(h, v_r)
xz_t = K.dot(x_tm1, w_z) + b_z+ K.dot(h, v_z)
r_t = self.inner_activation(xr_t + K.dot(s_tm1, u_r))
z_t = self.inner_activation(xz_t + K.dot(s_tm1, u_z))
xs_t = K.dot(x_tm1, w_s) + b_s+ K.dot(h, v_s)
s1_t = self.activation(xs_t + K.dot(r_t*s_tm1, u_s))
s_t = (1-z_t) * s_tm1 + z_t * s1_t
x_t = self.activation(K.dot(s_t, w_x) + b_x)
return x_t, s_t
def get_output(self, train=False):
H = self.get_input(train)
Hh = K.permute_dimensions(H, (1, 0, 2))
def rstep(o,index,Hh):
return Hh[index],index-1
[RHh,index],update = theano.scan(
rstep,
n_steps=Hh.shape[0],
non_sequences=[Hh],
outputs_info= [Hh[-1]]+[-1])
#RHh=K.permute_dimensions(RHh, (1, 0, 2))
X = K.permute_dimensions(H, (1, 0, 2))[-1]
#X1=(X[:,:self.input_shape//2,:]+X[:,:self.input_shape//2,:])/2
outdim=self.output_dim
X1=X[:,:outdim]+X[:,outdim:]
if self.stateful or self.state_input or len(self.state_outputs) > 0:
initial_states = self.states
else:
initial_states = self.get_initial_states(X)
[outputs,hidden_states], updates = theano.scan(
self.ssstep,
sequences=RHh,
n_steps = self.output_length,
outputs_info=[X1] + initial_states,#initial_states输入状态改为一个
non_sequences=[self.U_r, self.U_z, self.U_s,
self.W_r, self.W_z, self.W_s, self.W_x,
self.V_r, self.V_z, self.V_s,
self.b_r, self.b_z, self.b_s, self.b_x])
states = [hidden_states[-1]]
if self.stateful and not self.state_input:
self.updates = []
for i in range(2):
self.updates.append((self.states[i], states[i]))
for o in self.state_outputs:
o.updates = []
for i in range(2):
o.updates.append((o.states[i], states[i]))
return K.permute_dimensions(outputs, (1, 0, 2))
@property
def output_shape(self):
shape = list(super(GRU_Decoder, self).output_shape)
shape[1] = self.output_length
return tuple(shape)
def get_config(self):
config = {'name': self.__class__.__name__}
base_config = super(GRU_Decoder, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
class ReverseLayer2(Layer):
def __init__(self,layer):
self.layer=layer
self.trainable_weights = []
self.regularizers = []
self.constraints = []
self.updates = []
params, regs, consts, updates =self.layer.get_params()
self.regularizers += regs
self.updates += updates
# params and constraints have the same size
for p, c in zip(params, consts):
if p not in self.trainable_weights:
self.trainable_weights.append(p)
self.constraints.append(c)
super(ReverseLayer2, self).__init__()
@property
def output_shape(self,train=False):
return self.layer.output_shape
def get_output(self, train=False):
b=self.layer.get_output(train)
a=b.dimshuffle((1, 0, 2))
def rstep(o,index,H):
return H[index],index-1
[results,index],update = theano.scan(
rstep,
n_steps=a.shape[0],
non_sequences=[a],
outputs_info= [a[-1]]+[-1])
results2=results.dimshuffle((1, 0, 2))
return results2
def get_config(self):
config = {'name': self.__class__.__name__,
'layers': self.layer.get_config()}
base_config = super(ReverseLayer2, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
def get_input(self, train=False):
res = []
o = self.layer.get_input(train)
if not type(o) == list:
o = [o]
for output in o:
if output not in res:
res.append(output)
return res
@property
def input(self):
return self.get_input()
def supports_masked_input(self):
return False
def get_output_mask(self, train=None):
return None<file_sep>/TaggingScheme.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 14 09:29:08 2019
@author: <NAME>
"""
import json,unicodedata,nltk
def tag_sent(source_json,tag_json,max_token=50):
train_json_file = open(tag_json, 'w')
file = open(source_json, 'r')
sentences_0 = file.readlines()
c=0
Tkk=[]
ii=0
print(source_json)
print(len(sentences_0))
Tkk={}
vV=[]
Mlabel={}
count_r={}
for line in sentences_0:
c+=1
kk=1
count_r[c-1]=0
Tkk[c-1]=0
if not c%10000:
print(c)
sent = json.loads(line.strip('\r\n'))
flag=0
sentText = str(unicodedata.normalize('NFKD', sent['sentText']).encode('ascii','ignore'),'ascii').rstrip('\n').rstrip('\r')
tags=[]
# tokens = nltk.word_tokenize(sentText) #0311
tokens0 = nltk.word_tokenize(sentText) #0311
tokens=tokens0[:min(max_token,len(tokens0))] #0311
for i in range(0,len(tokens)):
tags.append('O')
emIndexByText = {}
for em in sent['entityMentions']:
emText = unicodedata.normalize('NFKD', em['text']).encode('ascii','ignore')
tokens1=tokens
em1=emText.split()
flagE=True
if emIndexByText.__contains__(emText):
flagE=False
while flagE:
start, end = find_index(tokens1, em1)
if start!=-1 and end!=-1:
tokens1=tokens1[end:]
if emText not in emIndexByText:
emIndexByText[emText]=[(start,end)]
elif not emIndexByText[emText].__contains__((start, end)):
offset = emIndexByText[emText][-1][1]
emIndexByText[emText].append((start+offset, end+offset))
else:
break
for rm in sent['relationMentions']:
if not rm['label'].__eq__('None'):
rmlabel=rm["label"]
em1 = unicodedata.normalize('NFKD', rm['em1Text']).encode('ascii','ignore')
em2 = unicodedata.normalize('NFKD', rm['em2Text']).encode('ascii','ignore')
if emIndexByText.__contains__(em1) and emIndexByText.__contains__(em2):
ind1=emIndexByText[em1]
ind2=emIndexByText[em2]
minind=len(tokens)
labelindex=[]
for i1ind,i1 in enumerate(ind1):
for i2ind,i2 in enumerate(ind2):
if (i2[0]-i1[1])*(i2[1]-i1[0])>0:
if minind>abs(i2[1]-i1[1]):
minind=abs(i2[1]-i1[1])
labelindex=[i1ind,i2ind]
if labelindex:
i1ind=labelindex[0]
i2ind=labelindex[1]
start1=ind1[i1ind][0]
end1 =ind1[i1ind][1]
start2=ind2[i2ind][0]
end2 =ind2[i2ind][1]
tag1Previous=[]
tag2Previous=[]
if end1 - start1 == 1:
tag1Previous.append(rmlabel+"__E1S")
elif end1 - start1 == 2:
tag1Previous.append( rmlabel + "__E1B")
tag1Previous.append(rmlabel + "__E1L")
else:
tag1Previous.append(rmlabel + "__E1B")
for ei in range(start1+1,end1-1):
tag1Previous.append(rmlabel + "__E1I")
tag1Previous.append(rmlabel + "__E1L")
if end2 - start2 == 1:
tag2Previous.append(rmlabel+"__E2S")
elif end2 - start2 == 2:
tag2Previous.append( rmlabel + "__E2B")
tag2Previous.append(rmlabel + "__E2L")
else:
tag2Previous.append(rmlabel + "__E2B")
for ei in range(start2+1,end2-1):
tag2Previous.append(rmlabel + "__E2I")
tag2Previous.append(rmlabel + "__E2L")
while True:
valid1=True
vT1=0
for ei in range(start1,end1):
if not tags[ei].__eq__('O'):
valid1 = False
break
if not valid1:
valid1=True
vT1=1
for ei in range(start1,end1):
if not tags[ei].__eq__(tag1Previous[ei-start1]):
valid1 = False
vT1=0
break
valid2=True
vT2=0
for ei in range(start2,end2):
if not tags[ei].__eq__('O'):
valid2 = False
break
if not valid2:
valid2=True
vT2=1
for ei in range(start2,end2):
if not tags[ei].__eq__(tag2Previous[ei-start2]):
valid2 = False
vT2=0
break
if valid1 and valid2:
for ei in range(start2,end2):
tags[ei]=tag2Previous[ei-start2]
for ei in range(start1,end1):
tags[ei]=tag1Previous[ei-start1]
Tkk[c-1]=kk
if not Mlabel.__contains__(rmlabel):
Mlabel[rmlabel]=[c-1]
else:
Mlabel[rmlabel].append(c-1)
if not (vT1 and vT2):
ii+=1
count_r[c-1]+=1
flag=1
if (vT1 or vT2) and not (vT1 and vT2):
vV.append(c-1)
break
else:
start1+=len(tokens)
end1+=len(tokens)
start2+=len(tokens)
end2+=len(tokens)
if end2>kk*len(tokens):
kk+=1
for ki in range(len(tokens)):
tags.append('O')
if 1:
newsent = dict()
newsent['tokens'] = tokens
newsent['tags'] = tags
newsent['lentags/lentokens']=kk*flag
train_json_file.write(json.dumps(newsent)+'\n')
train_json_file.close()
return Tkk,vV,ii,Mlabel,count_r
def datakk(file0,file1,kk=1,isTrain=True):
fread=open(file0,'r')
sentence=fread.readlines()
fwrite=open(file1,'w')
ii=0
print('Origin Sentence:'+str(len(sentence)))
for line in sentence:
sent=json.loads(line)
tkk=sent['lentags/lentokens']
tkk=len(sent['tags'])//len(sent['tokens'])
lent=len(sent['tokens'])
if kk==1:
for i in range(tkk):
newsent=dict()
newsent['tokens']=sent['tokens']
newsent['tags']=sent['tags'][i*lent:i*lent+lent]
ii+=1
fwrite.write(json.dumps(newsent)+'\n')
elif kk==2:
if tkk>=2:
for i in range(tkk):
for j in range(i+1,tkk):
newsent=dict()
newsent['tokens']=sent['tokens']
newsent['tags']=sent['tags'][i*lent:i*lent+lent]
newsent['tags'].extend(sent['tags'][j*lent:j*lent+lent])
fwrite.write(json.dumps(newsent)+'\n')
ii+=1
else:
newsent=dict()
newsent['tokens']=sent['tokens']
newsent['tags']=sent['tags']
newsent['tags'].extend(['O' for i in sent['tokens']])
fwrite.write(json.dumps(newsent)+'\n')
ii+=1
elif kk==3:
for _ in range(kk-tkk):
sent['tags'].extend(['O' for i in sent['tokens']])
tkk=3
for i in range(tkk):
for j in range(i+1,tkk):
for k in range(j+1,tkk):
newsent=dict()
newsent['tokens']=sent['tokens']
newsent['tags']=sent['tags'][i*lent:i*lent+lent]
newsent['tags'].extend(sent['tags'][j*lent:j*lent+lent])
newsent['tags'].extend(sent['tags'][k*lent:k*lent+lent])
fwrite.write(json.dumps(newsent)+'\n')
ii+=1
elif kk==4:
for _ in range(kk-tkk):
sent['tags'].extend(['O' for i in sent['tokens']])
tkk=4
for i in range(tkk):
for j in range(i+1,tkk):
for k in range(j+1,tkk):
for m in range(k+1,tkk):
newsent=dict()
newsent['tokens']=sent['tokens']
newsent['tags']=sent['tags'][i*lent:i*lent+lent]
newsent['tags'].extend(sent['tags'][j*lent:j*lent+lent])
newsent['tags'].extend(sent['tags'][k*lent:k*lent+lent])
newsent['tags'].extend(sent['tags'][m*lent:m*lent+lent])
fwrite.write(json.dumps(newsent)+'\n')
ii+=1
elif kk==8:
newsent=dict()
newsent['tokens']=sent['tokens']
newsent['tags']=sent['tags']
for j in range(kk-tkk):
newsent['tags'].extend(['O' for i in sent['tokens']])
fwrite.write(json.dumps(newsent)+'\n')
ii+=1
fread.close()
fwrite.close()
print("lenght of "+file1+' = '+str(ii))
def get_label(infile1,infile2,labeltxt):
file1 = open(infile1, 'r')
file2 = open(infile2, 'r')
labelset=[]
sentences_0 = file1.readlines()
sentences_1 = file2.readlines()
for line in sentences_0+sentences_1:
sent = json.loads(line.strip('\r\n'))
rel=sent['relationMentions']
for re in rel:
label=re['label']
if not labelset.__contains__(label) and not label.__eq__('None'):
labelset.append(label)
file1.close()
file2.close()
f=open(labeltxt,'w')
for label in labelset:
f.write(label+'\n')
f.close()
def no_overlap(index11,index12,index21,index22):
if index11>=index22:
return True
if index21>=index12:
return True
return False
def find_index(sen_split, word_split):
index1 = -1
index2 = -1
for i in range(len(sen_split)):
if str(sen_split[i]) == str(word_split[0],'ascii'):
flag = True
k = i
for j in range(len(word_split)):
if str(word_split[j],'ascii')!= sen_split[k]:
flag = False
if k < len(sen_split) - 1:
k+=1
if flag:
index1 = i
index2 = i + len(word_split)
break
return index1, index2<file_sep>/data/readme.md
Please download [trainfile, testfile and w2vfile](https://drive.google.com/drive/folders/0B--ZKWD8ahE4UktManVsY1REOUk?usp=sharing) and unzip these file here.
<file_sep>/PrecessData.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 14 09:50:34 2019
@author: <NAME>
"""
import numpy as np
import pickle as cPickle
import json
def load_vec_pkl(fname,vocab,k=300):
W = np.zeros(shape=(vocab.__len__() + 1, k))
w2v = cPickle.load(open(fname,'rb'),encoding='iso-8859-1')
w2v["UNK"] = np.random.uniform(-0.25, 0.25, k)
i=0
for word in vocab:
if not w2v.__contains__(word):
w2v[word] = w2v["UNK"]
i+=1
W[vocab[word]] = w2v[word]
print(str(i)+' words unknow in pretrain words')
return w2v,k,W
def make_idx_data_index_EE_LSTM(file,max_s,source_vob,target_vob):
data_s_all=[]
data_t_all=[]
f = open(file,'r')
fr = f.readlines()
sent=json.loads(fr[0].strip('\r\n'))
kk=len(sent['tags'])//len(sent['tokens'])
max_t=kk*max_s
for line in fr:
sent = json.loads(line.strip('\r\n'))
s_sent = sent['tokens']
len_s=len(sent['tokens'])
t_sent = sent['tags']
data_t = []
data_s = []
if len(s_sent) > max_s:
i=max_s-1
while i >= 0:
data_s.append(source_vob[s_sent[i]])
i-=1
else:
num=max_s-len(s_sent)
for inum in range(0,num):
data_s.append(0)
i=len(s_sent)-1
while i >= 0:
data_s.append(source_vob[s_sent[i]])
i-=1
data_s_all.append(data_s)
if len(t_sent) > max_t:
for i in range(kk):
for word in t_sent[i*len_s:i*len_s+max_s]:
data_t.append(target_vob[word])
else:
for ki in range(kk):
for word in t_sent[ki*len_s:ki*len_s+len_s]:
data_t.append(target_vob[word])
for word in range(len_s,max_s):
data_t.append(0)
data_t_all.append(data_t)
f.close()
return [data_s_all,data_t_all]
def get_word_index(train,test,labeltxt):
source_vob = {}
target_vob = {}
sourc_idex_word = {}
target_idex_word = {}
f=open(labeltxt,'r')
fr=f.readlines()
end=['__E1S','__E1B','__E1I','__E1L','__E2S','__E2B','__E2I','__E2L']
count = 2
target_vob['O']=1
target_idex_word[1]='O'
for line in fr:
line=line.strip('\n')
if line and not line=='O':
for lend in end:
target_vob[line+lend]=count
target_idex_word[count]=line+lend
count+=1
count = 1
max_s=0
f = open(train,'r')
fr = f.readlines()
for line in fr:
sent = json.loads(line.strip('\r\n'))
sourc = sent['tokens']
for word in sourc:
if not source_vob.__contains__(word):
source_vob[word] = count
sourc_idex_word[count] = word
count += 1
if sourc.__len__()>max_s:
max_s = sourc.__len__()
f.close()
f = open(test,'r')
fr = f.readlines()
for line in fr:
sent = json.loads(line.strip('\r\n'))
sourc = sent['tokens']
for word in sourc:
if not source_vob.__contains__(word):
source_vob[word] = count
sourc_idex_word[count] = word
count += 1
if sourc.__len__()>max_s:
max_s = sourc.__len__()
f.close()
if not source_vob.__contains__("**END**"):
source_vob["**END**"] = count
sourc_idex_word[count] = "**END**"
count+=1
if not source_vob.__contains__("UNK"):
source_vob["UNK"] = count
sourc_idex_word[count] = "UNK"
count+=1
return source_vob,sourc_idex_word,target_vob,target_idex_word,max_s
def get_data_e2e(trainfile,testfile,labeltxt,w2v_file,eelstmfile,maxlen = 50):
source_vob, sourc_idex_word, target_vob, target_idex_word, max_s = \
get_word_index(trainfile, testfile,labeltxt)
print("source vocab size: " + str(len(source_vob)))
print("target vocab size: " + str(len(target_vob)))
source_w2v ,k ,source_W= load_vec_pkl(w2v_file,source_vob)
print("word2vec loaded!")
print("num words in source word2vec: " + str(len(source_w2v))+\
"source unknown words: "+str(len(source_vob)-len(source_w2v)))
if max_s > maxlen:
max_s = maxlen
print('max soure sent lenth is ' + str(max_s))
train = make_idx_data_index_EE_LSTM(trainfile,max_s,source_vob,target_vob)
test = make_idx_data_index_EE_LSTM(testfile, max_s, source_vob, target_vob)
print("dataset created!")
cPickle.dump([train,test,source_W,source_vob,sourc_idex_word,
target_vob,target_idex_word,max_s,k],open(eelstmfile,'wb'))
<file_sep>/README.md
# A-Novel-End2End-Multiple-Tagging-Model-for-Knowledge-Extraction<file_sep>/Model.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 1 19:43:34 2019
@author: <NAME>
"""
from TaggingScheme import tag_sent,datakk,get_label
from PrecessData import get_data_e2e
from Encoder_Decoder import LSTM_Decoder,GRU_Decoder,ReverseLayer2
from keras.models import Sequential
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import GRU,LSTM
from keras.layers.core import TimeDistributedDense, Dropout, Activation,Merge
from Evaluate import evaluavtion_triple_new
import keras.backend as K
import pickle as cPickle
import numpy as np
import argparse,json,time,os
def get_training_batch_xy_bias(inputsX, inputsY, max_s, max_t,
batchsize, vocabsize, target_idex_word,lossnum,shuffle=False):
assert len(inputsX) == len(inputsY)
indices = np.arange(len(inputsX))
if shuffle:
np.random.shuffle(indices)
for start_idx in range(0, len(inputsX) - batchsize + 1, batchsize):
excerpt = indices[start_idx:start_idx + batchsize]
x = np.zeros((batchsize, max_s)).astype('int32')
y = np.zeros((batchsize, max_t, vocabsize + 1)).astype('int32')
for idx, s in enumerate(excerpt):
x[idx,] = inputsX[s]
for idx2, word in enumerate(inputsY[s]):
targetvec = np.zeros(vocabsize + 1)
wordstr=''
if word!=0:
wordstr = target_idex_word[word]
if wordstr.__contains__("E"):
targetvec[word] = lossnum
else:
targetvec[word] = 1
y[idx, idx2,] = targetvec
yield x, y
def save_model(nn_model, NN_MODEL_PATH):
nn_model.save_weights(NN_MODEL_PATH, overwrite=True)
def Loss(y_true,y_pred):
loss0=K.zeros_like(y_true[:,:1,0])
for i in range(kks):
p1=y_pred[:,i*max_tokens:i*max_tokens+max_tokens,:]
w1=K.sum(y_true[:,i*max_tokens:i*max_tokens+max_tokens,2:],axis=-1)
lossi=K.zeros_like(y_true[:,:max_tokens,0])
for j in range(kks):
p2=y_pred[:,j*max_tokens:j*max_tokens+max_tokens,:]
l=K.mean(K.square(p1-p2),axis=-1)*w1.any(axis=-1,keepdims=True)
w2=K.sum(y_true[:,j*max_tokens:j*max_tokens+max_tokens,2:],axis=-1)
lossi+=l*w2.any(axis=-1,keepdims=True)
loss0=K.concatenate((loss0,lossi),axis=-1)
return K.categorical_crossentropy(y_pred,y_true)-beta*loss0[:,1:]#-loss[:,1:]#
def creat_binary_tag_LSTM( sourcevocabsize,targetvocabsize, source_W,input_seq_lenth ,output_seq_lenth ,
hidden_dim ,emd_dim,cell='lstm1',loss=Loss,optimizer='rmsprop'):#'categorical_crossentropy'
encoder_a = Sequential()
encoder_b = Sequential()
l_A_embedding = Embedding(input_dim=sourcevocabsize+1,
output_dim=emd_dim,
input_length=input_seq_lenth,
mask_zero=True,
weights=[source_W])
encoder_a.add(l_A_embedding)
encoder_a.add(Dropout(0.3))
encoder_b.add(l_A_embedding)
encoder_b.add(Dropout(0.3))
Model = Sequential()
if cell.__contains__('lstm'):
encoder_a.add(LSTM(hidden_dim,return_sequences=True))
encoder_b.add(LSTM(hidden_dim,return_sequences=True,go_backwards=True))
decodelayer=LSTM_Decoder
else:
encoder_a.add(GRU(hidden_dim,return_sequences=True))
encoder_b.add(GRU(hidden_dim,return_sequences=True,go_backwards=True))
decodelayer=GRU_Decoder
encoder_rb = Sequential()
encoder_rb.add(ReverseLayer2(encoder_b))#在decodelayer.py的Reverselayer2注意可学习变量
encoder_ab=Merge(( encoder_a,encoder_rb),mode='concat')
kk=int(cell[-1])
if kk>1:
a=[]
for i in range(kk):
decoder_i=Sequential()
decoder_i.add(encoder_ab)
decoder_i.add(decodelayer(hidden_dim=hidden_dim, output_dim=hidden_dim
, input_length=input_seq_lenth,
output_length=output_seq_lenth,
state_input=False,
return_sequences=True))
a.append(decoder_i)
decoder=Merge(tuple(a),mode='concat',concat_axis=-2)
Model.add(decoder)
else:
Model.add(encoder_ab)
Model.add(decodelayer(hidden_dim=hidden_dim, output_dim=hidden_dim
, input_length=input_seq_lenth,
output_length=output_seq_lenth,
state_input=False,
return_sequences=True))
Model.add(TimeDistributedDense(targetvocabsize+1))
Model.add(Activation('softmax'))
Model.compile(loss=loss, optimizer=optimizer)
return Model
def test_model(nn_model,testdata,index2word,sent_i2w,resultfile='',rfile=''):
index2word[0]=''
testx = np.asarray(testdata[0],dtype="int32")
testy = np.asarray(testdata[1],dtype="int32")
sent_i2w[0]='UNK'
senttext=[]
for sent in testx:
stag=[]
for wi in range(len(sent)):
token=sent_i2w[sent[-wi-1]]
stag.append(token)
senttext.append(stag)
batch_size=len(testdata[0])
testlen = len(testx)
testlinecount=0
if len(testx)%batch_size ==0:
testnum = len(testx)/batch_size
else:
extra_test_num = batch_size - len(testx)%batch_size
extra_data = testx[:extra_test_num]
testx=np.append(testx,extra_data,axis=0)
extra_data = testy[:extra_test_num]
testy=np.append(testy,extra_data,axis=0)
testnum = len(testx)/batch_size
testresult=[]
for n in range(0,int(testnum)):
xbatch = testx[n*batch_size:(n+1)*batch_size]
ybatch = testy[n*batch_size:(n+1)*batch_size]
predictions = nn_model.predict(xbatch)
for si in range(0,len(predictions)):
if testlinecount < testlen:
sent = predictions[si]
ptag = []
for word in sent:
next_index = np.argmax(word)
#if next_index != 0:
next_token = index2word[next_index]
ptag.append(next_token)
senty = ybatch[si]
ttag=[]
for word in senty:
next_token = index2word[word]
ttag.append(next_token)
result = []
result.append(ptag)
result.append(ttag)
testlinecount += 1
testresult.append(result)
cPickle.dump(testresult,open(resultfile,'wb'))
max_s=50
kk=len(testy[0])//len(testx[0])
P2, R2, F2,numpr2,nump2,numr2,numprSeq,numpSeq,numrSeq = evaluavtion_triple_new(\
testresult,senttext,rfile,kk,max_s)
print ('new2 way',P2, R2, F2,numpr2,nump2,numr2)
if kk>1:
print('Seg result:')
for i in range(kk):
print(numprSeq[i],numpSeq[i],numrSeq[i])
return P2,R2,F2
def train_e2e_model(eelstmfile, modelfile,resultdir,cell,npochos,
lossnum=1,batch_size = 256,retrain=False):
traindata, testdata, source_W, source_vob, sourc_idex_word, target_vob, target_idex_word, max_s, k \
= cPickle.load(open(eelstmfile, 'rb'),encoding='iso-8859-1')
nn_model = creat_binary_tag_LSTM(sourcevocabsize=len(source_vob), targetvocabsize=len(target_vob),
source_W=source_W, input_seq_lenth=max_s, output_seq_lenth=max_s,
hidden_dim=k, emd_dim=k,cell=cell)
if retrain:
nn_model.load_weights(modelfile)
P, R, F= test_model(nn_model, testdata, target_idex_word,sourc_idex_word,resultdir+'result-0',rfile=resultdir+'triplet0.json')
x_train = np.asarray(traindata[0], dtype="int32")
y_train = np.asarray(traindata[1], dtype="int32")
epoch = 1
save_inter = 1
saveepoch = save_inter
maxF=F
kk=int(cell[-1])
max_t=kk*max_s
len_target_vob=len(target_vob)
bat=batch_size#len(x_train)//30-1
nn_model.optimizer.lr=0.001
prf=[]
print('start train')
while (epoch < npochos):
epoch = epoch + 1
t=time.time()
if not epoch%20:
nn_model.optimizer.lr=nn_model.optimizer.lr/10.0
for x, y in get_training_batch_xy_bias(x_train[:], y_train[:], max_s, max_t,
bat, len_target_vob,
target_idex_word,lossnum,shuffle=True):
nn_model.fit(x, y, batch_size=batch_size,
nb_epoch=1, show_accuracy=True, verbose=0)
if epoch > saveepoch:
saveepoch += save_inter
resultfile = resultdir+"result-all"+str(saveepoch)
print('Result of All testdata')
P, R, F= test_model(nn_model, testdata, target_idex_word,sourc_idex_word,resultfile,rfile=resultdir+"triplet"+str(saveepoch)+'.json')
prf.append([P,R,F])
if F>=maxF:
save_model(nn_model, modelfile.split('.pkl')[0]+str(saveepoch)+'.pkl')
print('epoch '+str(epoch-1)+' costs time:'+str(time.time()-t)+'s')
return nn_model,prf
def infer_e2e_model(eelstmfile, modelfile,resultdir,cell,predictfile):
traindata, testdata, source_W, source_vob, sourc_idex_word, target_vob, \
target_idex_word, max_s, k = cPickle.load(open(eelstmfile, 'rb'))
nnmodel = creat_binary_tag_LSTM(sourcevocabsize=len(source_vob),targetvocabsize= len(target_vob),
source_W=source_W,input_seq_lenth= max_s,output_seq_lenth= max_s,
hidden_dim=k, emd_dim=k,cell='lstm1')
nnmodel.load_weights(modelfile)
f = open(predictfile,'r')
fr = f.readlines()
data_s_all=[]
for line in fr:
sent = json.loads(line.strip('\r\n'))
s_sent = sent['tokens']
data_s = []
if len(s_sent) > max_s:
i=max_s-1
while i >= 0:
data_s.append(source_vob[s_sent[i]])
i-=1
else:
num=max_s-len(s_sent)
for inum in range(0,num):
data_s.append(0)
i=len(s_sent)-1
while i >= 0:
data_s.append(source_vob[s_sent[i]])
i-=1
data_s_all.append(data_s)
f.close()
predictions = nnmodel.predict(data_s_all)
testresult=[]
for si in range(0,len(predictions)):
sent = predictions[si]
ptag = []
for word in sent:
next_index = np.argmax(word)
#if next_index != 0:
next_token = target_idex_word[next_index]
ptag.append(next_token)
testresult.append(ptag)
cPickle.dump(testresult,open(resultdir+cell+'/result','wb'))
parser = argparse.ArgumentParser()
parser.add_argument('-train', dest='trainfile', type=str, default="./data/train.json")
parser.add_argument('-test', dest='testfile', type=str, default="./data/test.json")
parser.add_argument('-l', dest='label', type=str, default="./data/label.txt")
parser.add_argument('-w', dest='w2v', type=str, default="./data/w2v.pkl")
parser.add_argument('-e', dest='e2edatafile', type=str, default="./data/e2edata_0311_k3.pkl")
parser.add_argument('-m', dest='modeldir', type=str, default="./data/new/model_0_lstm_2/")
parser.add_argument('-r', dest='resultdir', type=str, default="./data/new/result_0_lstm_2/")
parser.add_argument('-p', dest='predictfile', type=str, default="./data/demo/result_1_lstm/predict.json")
parser.add_argument('-mode', dest='mode', type=str, default='Train', choices=['Train', 'Predict'],help='1 for train, 0 for predict')
parser.add_argument('-cell', dest='cell', type=str, default='lstm3', help='cell+k: lstm or gru+ 1,2,3')
parser.add_argument('-alpha', type=str, default="5 10 20 50", help='for test')
parser.add_argument('-beta', type=str, default="10 1 0.1 0.01", help='for test')
parser.add_argument('-epoch', type=int, default=30, help='for test')
args = parser.parse_args()
kks=int(args.cell[-1])
max_tokens=50
if __name__=="__main__":
mode=args.mode
alphas = args.alpha
betas = args.beta
labelfile=args.label
originTrainfile = args.trainfile
originTestfile = args.testfile
e2edatafile = args.e2edatafile
w2vfile=args.w2v
global beta
if not os.path.exists(args.modeldir):
os.makedirs(args.modeldir)
if not os.path.exists(args.resultdir):
os.makedirs(args.resultdir)
if not os.path.exists(e2edatafile):
print ("Precess lstm data....")
minkkTagTrainfile = originTrainfile[:-5]+'_all.json'
minkkTagTestfile = originTestfile[:-5]+'_all.json'
TagTrainfile = originTrainfile[:-5]+'Tag_'+str(kks)+'.json'
TagTestfile = originTestfile[:-5]+'Tag_'+str(kks)+'.json'
_= tag_sent(originTrainfile,minkkTagTrainfile)
_= tag_sent(originTestfile, minkkTagTestfile)
datakk(minkkTagTrainfile,TagTrainfile,kks,isTrain=True)
datakk(minkkTagTestfile ,TagTestfile ,kks,isTrain=False)
get_label(originTrainfile,originTestfile,labelfile)
get_data_e2e(TagTrainfile,TagTestfile,labelfile,w2vfile,e2edatafile,maxlen=max_tokens)
if args.mode=='Train':
print("Training EE model....cell="+args.cell+'\n'+'datafile:'+e2edatafile)
PRFs=[]
for a in alphas.split():
alpha=int(a)
for b in betas.split():
beta=float(b)
print('alpha,beta = ',alpha,beta)
modeldir=args.modeldir+'alpha'+a+'beta'+b+'/'
resultdir=args.resultdir+'alpha'+a+'beta'+b+'/'
if not os.path.exists(modeldir):
os.makedirs(modeldir)
if not os.path.exists(resultdir):
os.makedirs(resultdir)
nn_model,PRF=train_e2e_model(e2edatafile, modeldir+'e2edata_'+args.cell+'.pkl',resultdir,args.cell,
npochos=args.epoch,lossnum=alpha,retrain=False)
PRFs.append(PRF)
cPickle.dump(PRF,open(args.resultdir+'PRF_'+args.cell+'_alpha'+\
str(alpha)+'_beta'+str(beta)+'.pkl','wb'))
cPickle.dump([alphas,betas,PRFs],open(args.resultdir+'AllPRF_'+args.cell+'_alpha'+\
alphas+'_beta'+betas+'.pkl','wb'))
else:
infer_e2e_model(e2edatafile, args.modeldir+'e2edata'+args.cell+'.pkl',args.resultdir,args.cell,args.predictfile)
|
1e79599deff4f1c528339e932a9078d24d77ff2b
|
[
"Markdown",
"Python"
] | 7 |
Python
|
SongYHs/End2End-Multiple-Tagging-Model-for-Knowledge-Extraction
|
73feafd38c8ace8acf782caba76caa211f57eaed
|
e6c329a64ff3391c8c3b4db4b56e92ee3ca26a94
|
refs/heads/master
|
<repo_name>jamesbieber/React-Insta-Clone<file_sep>/instagram/src/components/CommentSection/CommentSection.js
import React from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import Comment from "../Comment/Comment";
import "./commentsection.css";
import { MessageCircle, Heart } from "react-feather";
const Comments = styled.div`
display: flex;
flex-direction: column;
border: 1px solid #dcdcdc;
padding-bottom: 2%;
`;
const SymbolsComments = styled.div`
margin-bottom: 1.5%;
margin-left: 1%;
margin-top: 2%;
display: flex;
justify-content: flex-start;
`;
const Likes = styled.h3`
margin-left: 1%;
margin-bottom: 1.5%;
`;
const Form = styled.form`
display: flex;
align-content: center;
justify-content: center;
button {
cursor: pointer;
margin-top: 3%;
padding-top: 1.2%;
padding-bottom: 1.1%;
text-align: center;
height: 100%;
width: 20%;
}
input {
margin: 0 auto;
width: 98%;
height: 30px;
margin-top: 3%;
padding-left: 2%;
background-color: #fafafa;
color: #cacacc;
border: 1px solid #dcdcdc;
}
`;
const Button = styled.button`
cursor: pointer;
margin-top: 3%;
padding-top: 1.2%;
padding-bottom: 1.1%;
text-align: center;
height: 100%;
width: 20%;
`;
class CommentSection extends React.Component {
state = {
comments: [],
likes: "",
comment: ""
};
inputChangeHandler = event => {
this.setState({ [event.target.name]: event.target.value });
};
componentDidMount() {
this.setState({
comments: this.props.comments,
likes: this.props.likes
});
}
addNewComment = event => {
event.preventDefault();
this.setState({
...this.state.likes,
comments: [
...this.state.comments,
{
username: "Jamesbieber",
text: this.state.comment
}
],
comment: ""
});
};
incrementLikes = event => {
this.setState({ likes: this.state.likes + 1 });
};
render() {
return (
<Comments>
<SymbolsComments>
<Heart id="heart-symbol" onClick={this.incrementLikes} />
<MessageCircle id="comment-symbol" />
</SymbolsComments>
<Likes>{this.state.likes} likes</Likes>
{this.state.comments.map((comment, index) => {
return <Comment comment={comment} key={index} />;
})}
<Form onSubmit={this.addNewComment}>
<input
type="text"
placeholder="Add a comment..."
name="comment"
value={this.state.comment}
onChange={this.inputChangeHandler}
/>
<Button>Add Comment</Button>
</Form>
</Comments>
);
}
}
CommentSection.propTypes = {
props: PropTypes.arrayOf(
PropTypes.shape({
likes: PropTypes.number,
comment: PropTypes.arrayOf(
PropTypes.shape({
username: PropTypes.string,
text: PropTypes.string
})
)
})
)
};
export default CommentSection;
<file_sep>/instagram/src/components/Styles/Styles.js
import React from "react";
import styled from "styled-componets";
const Username = styled.h2``;
<file_sep>/instagram/src/components/PostContainer/PostContainer.js
import React from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import CommentSection from "../CommentSection/CommentSection";
const Container = styled.div`
background-color: #ffffff;
margin-top: 5%;
`;
const UserInfo = styled.div`
display: flex;
align-items: center;
padding-top: 1%;
padding-bottom: 1%;
padding-left: 2%;
border: 1px solid #dcdcdc;
`;
const Thumbnail = styled.img`
width: 7%;
margin-right: 1%;
border-radius: 100px;
`;
const PostImage = styled.img`
margin-bottom: -10px;
`;
const Comments = styled.div`
border: 1px solid #dcdcdc;
`;
const PostContainer = props => {
return (
<Container>
<UserInfo>
<Thumbnail src={props.post.thumbnailUrl} />
<h2>{props.post.username}</h2>
</UserInfo>
<PostImage src={props.post.imageUrl} />
<Comments>
<CommentSection
key={props.key}
index={props.post}
likes={props.post.likes}
comments={props.post.comments}
/>
</Comments>
</Container>
);
};
PostContainer.propTypes = {
props: PropTypes.arrayOf(
PropTypes.shape({
posts: PropTypes.arrayOf(PropTypes.object),
post: PropTypes.arrayOf(PropTypes.object)
})
)
};
export default PostContainer;
<file_sep>/instagram/src/components/PostContainer/PostPage.js
import React from "react";
import PropTypes from "prop-types";
import "/Program Files/Git/projects/React-Insta-Clone/instagram/src/app.css";
import data from "/Program Files/Git/projects/React-Insta-Clone/instagram/src/dummy-data";
import SearchBar from "../SearchBar/SearchBar";
import PostContainer from "./PostContainer";
class PostPage extends React.Component {
state = {
posts: []
};
componentDidMount() {
this.setState({ posts: data });
localStorage.removeItem("username");
}
searchHandler = event => {
if (event.target.value.length > 0) {
let searchPosts = this.state.posts.filter(post => {
if (post.username.includes(event.target.value)) {
return post;
}
});
this.setState({ posts: searchPosts });
} else {
this.setState({ posts: data });
}
};
render() {
console.log(this.state.posts);
return (
<div className="App">
<SearchBar searchHandler={this.searchHandler} />
{this.state.posts.map((post, index) => {
return <PostContainer key={index} post={post} />;
})}
</div>
);
}
}
PostPage.propTypes = {
posts: PropTypes.arrayOf(
PropTypes.shape({
username: PropTypes.string.isRequired,
thumbnailUrl: PropTypes.string.isRequired,
imageUrl: PropTypes.string.isRequired,
likes: PropTypes.number.isRequired
})
)
};
export default PostPage;
|
b123171fef14dfce33ee302bb2055560fb377fa5
|
[
"JavaScript"
] | 4 |
JavaScript
|
jamesbieber/React-Insta-Clone
|
1591d70e558dc383482ead632e69da6fde2262ad
|
a026d033cb96d6d4a4d6aafa04aa161a63b243a0
|
refs/heads/main
|
<repo_name>ZZANZZAN/SNN<file_sep>/SNN(LIFmodel)/utils/image_utils.py
import random
import numpy as np
import matplotlib.pyplot as plt
from mnist import MNIST
mndata = MNIST('.\dirMNIST') #Put your directory where you downloaded the files
images, labels = mndata.load_training()
def get_next_image(index=0, pick_random = False, display=True):
if pick_random:
index = random.randint(0, len(images)-1)
image = images[index]
label = labels[index]
if display:
print('Label: {}'.format(label))
print(mndata.display(image))
image = np.asarray(image).reshape((28,28))
image_norm = (image * 255.0/image.max()) / 255.
return image_norm, label
def graph_retinal_image(image, stride):
fig = plt.figure()
len_x, len_y = image.shape
x_max = int(len_x/stride[0])
y_max = int(len_y/stride[0])
print('Convolution Dimensions: x={} / y={}'.format(x_max, y_max))
x_count, y_count = 1, 1
for y in range (0, len_y, stride[0]):
x_count = 1
for x in range(0, len_x, stride[0]):
x_end = x + stride[0]
y_end = y + stride[0]
kernel = image[y:y_end, x:x_end]
#orientation = s1(kernel)
a = fig.add_subplot(y_max, x_max, (y_count-1)*x_max+x_count)
a.axis('off')
plt.imshow(kernel, cmap="gray")
x_count += 1
y_count += 1
plt.show()
<file_sep>/SNN(LIFmodel)/utils/graph_results.py
import matplotlib.pyplot as plt
def plot_neuron_behaviour(time, data, neuron_type, neuron_id, y_title):
plt.plot(time,data)
plt.title('{} @ {}'.format(neuron_type, neuron_id))
plt.ylabel(y_title)
plt.xlabel('Time (msec)')
# Autoscale y-axis based on the data (is this needed??)
y_min = 0
y_max = max(data)*1.2
if y_max == 0:
y_max = 1
plt.ylim([y_min,y_max])
plt.show()
def plot_membrane_potential(time, Vm, neuron_type, neuron_id=0):
plot_neuron_behaviour(time, Vm, neuron_type, neuron_id, y_title='Membrane potential (V)')
def plot_spikes(time, Vm, neuron_type, neuron_id=0):
plot_neuron_behaviour(time, Vm, neuron_type, neuron_id, y_title='Spike (V)')
<file_sep>/SNN(LIFmodel)/utils/creating_weights.py
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import random
def cr_W(kernel_size, num_feature_maps, num_full_con_lay):
conv_kernel_layer2 = (0.5 - (-0.1))*np.random.random((kernel_size, kernel_size, num_feature_maps)) - 0.1
np.around(conv_kernel_layer2, decimals = 3)
full_con_lay_W = (0.5 - (-0.1))*np.random.random((num_full_con_lay)) - 0.1
np.around(full_con_lay_W, decimals = 3)
full_out_lay_W = (0.5 - (-0.1))*np.random.random((num_full_con_lay, num_feature_maps)) - 0.1
np.around(full_out_lay_W, decimals = 3)
pool_kernel_l3 = np.array([[1,1],[1,1]])
pool_kernel_l3.round(1)
np.save('data_weight/conv_kernel_layer2',conv_kernel_layer2)
np.save('data_weight/full_con_lay_W',full_con_lay_W)
np.save('data_weight/full_out_lay_W',full_out_lay_W)
np.save('data_weight/pool_kernel_l3',pool_kernel_l3)
def save_W(conv_kernel_layer2, full_con_lay_W, full_out_lay_W, pool_kernel_l3):
np.save('data_weight/conv_kernel_layer2',conv_kernel_layer2)
np.save('data_weight/full_con_lay_W',full_con_lay_W)
np.save('data_weight/full_out_lay_W',full_out_lay_W)
np.save('data_weight/pool_kernel_l3',pool_kernel_l3)
<file_sep>/SNN(LIFmodel)/SNN(v1).py
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import random
import redis
import math
from mnist import MNIST
from neurons import LIFNeuron as LIF
from utils import graph_results as graph, image_utils, creating_weights
T = 20
dt = 0.01
time = 100
_T = 1
stride = (4, 3, 2)
kernel_size = 3
num_feature_maps = 10
num_out_neuron = 10
debug=False
training = True
nu_BP = 0.003
mult_factor = 10
len_x = 28
len_y = 28
len_x_l2 = int(len_x - kernel_size + 1)
len_y_l2 = int(len_y - kernel_size + 1)
len_x_l3 = int(len_x_l2/stride[2])
len_y_l3 = int(len_y_l2/stride[2])
num_full_con_lay = num_feature_maps*len_x_l3*len_y_l3
creating_weights.cr_W(kernel_size, num_feature_maps, num_full_con_lay) #раскоментить чтобы сгенерить новые веса
conv_kernel_layer2 = np.load('data_weight/conv_kernel_layer2.npy')
full_con_lay_W = np.load('data_weight/full_con_lay_W.npy')
full_out_lay_W = np.load('data_weight/full_out_lay_W.npy')
pool_kernel_l3 = np.load('data_weight/pool_kernel_l3.npy')
#pool_kernel_l3 = np.array([[1,0.0],[0.0,0.0]])
#image_utils.graph_retinal_image(image, stride)
for num_iter in range(10):
print('Iteration number: {}'.format(num_iter))
image, label = image_utils.get_next_image(pick_random = True)
# Инициализация первого (входного) слоя
neurons_l1 = []
# print('Creating {} x {} neurons layer 1'.format(len_x, len_y))
for y in range (0, len_y, 1):
neuron_row=[]
for x in range(0, len_x, 1):
neuron_row.append(LIF.LIFNeuron(neuron_label="L1:{}/{}".format(y,x), debug=debug))
neurons_l1.append(neuron_row)
for y in range(0, len_y, 1):
for x in range(0, len_x, 1):
neuron_l1_stimulus = np.full((time), image[y,x])
neurons_l1[y][x].spike_generator(neuron_l1_stimulus)
# Инициализация второго (сверточного) слоя
neurons_l2 = []
for y in range (0, len_y_l2, 1):
neuron_row=[]
for x in range(0, len_x_l2, 1):
neuron_row.append(LIF.LIFNeuron(neuron_label="L2:{}/{}".format(y,x), debug=debug))
neurons_l2.append(neuron_row)
neuron_l2_stimulus = np.zeros((len_x_l2, len_y_l2, time, num_feature_maps))
for d in range(0,num_feature_maps,1):
l2x, l2y = 0,0
for x1 in range(0, len_x_l2, 1):
l2y = 0
for y1 in range(0, len_y_l2, 1):
stimulus_ret_unit = np.zeros(time)
for x2 in range(kernel_size):
for y2 in range(kernel_size):
x = x1+x2
y = y1+y2
stimulus_ret_unit += neurons_l1[x][y].spikes[:time] * conv_kernel_layer2[x2,y2,d]* mult_factor
neuron_l2_stimulus[l2x,l2y,:time,d] = stimulus_ret_unit
l2y += 1
l2x += 1
data_neuron_l2 = np.zeros((len_x_l2, len_y_l2, time, num_feature_maps))
for d in range(0,num_feature_maps,1):
for x in range(len_x_l2):
for y in range(len_y_l2):
neurons_l2[x][y].spike_generator(neuron_l2_stimulus[x,y,:,d])
data_neuron_l2[x,y,:time,d] = neurons_l2[x][y].spikes[:time]
if x == 12 and y == 12:
ny, nx = 12, 12
#graph.plot_spikes(neurons_l2[ny][nx].time, neurons_l2[ny][nx].spikes, 'Output Spikes for {}'.format(neurons_l2[ny][nx].type), neuron_id = '{}/{}'.format(ny, nx))
#graph.plot_membrane_potential(neurons_l2[ny][nx].time, neurons_l2[ny][nx].Vm, 'Membrane Potential {}'.format(neurons_l2[ny][nx].type), neuron_id = '{}/{}'.format(ny, nx))
neurons_l2[x][y].neuron_cleaning()
# Инициализация третьего (подвыборочного) слоя
neurons_l3 = []
neuron_l3_stimulus = np.zeros((len_x_l3, len_y_l3, time, num_feature_maps))
for y in range (0, len_y_l3, 1):
neuron_row=[]
for x in range(0, len_x_l3, 1):
neuron_row.append(LIF.LIFNeuron(neuron_label="L3:{}/{}".format(y,x), debug=debug))
neurons_l3.append(neuron_row)
for d in range(0,num_feature_maps,1):
l2x, l2y = 0,0
for x1 in range(0, len_x_l3, stride[2]):
l2y = 0
for y1 in range(0, len_y_l3, stride[2]):
stimulus_ret_unit = np.zeros(time)
maxsum = 0
#data_x = -1
#data_y = -1
for x2 in range(stride[2]):
for y2 in range(stride[2]):
x = x1+x2
y = y1+y2
if sum(data_neuron_l2[x,y,:time,d]) > maxsum:
maxsum = sum(data_neuron_l2[x,y,:time,d])
stimulus_ret_unit = data_neuron_l2[x,y,:time,d] * mult_factor
neuron_l3_stimulus[l2x,l2y,:time,d] = stimulus_ret_unit
l2y += 1
l2x += 1
data_neuron_l3 = np.zeros((len_x_l3, len_y_l3, time, num_feature_maps))
for d in range(0,num_feature_maps,1):
for x in range(len_x_l3):
for y in range(len_y_l3):
neurons_l3[x][y].spike_generator(neuron_l3_stimulus[x,y,:time,d])
data_neuron_l3[x,y,:time,d] = neurons_l3[x][y].spikes[:time]
if x == 6 and y == 6:
ny, nx = 6, 6
#graph.plot_spikes(neurons_l3[ny][nx].time, neurons_l3[ny][nx].spikes, 'Output Spikes for {}'.format(neurons_l3[ny][nx].type), neuron_id = '{}/{}'.format(ny, nx))
#graph.plot_membrane_potential(neurons_l3[ny][nx].time, neurons_l3[ny][nx].Vm, 'Membrane Potential {}'.format(neurons_l3[ny][nx].type), neuron_id = '{}/{}'.format(ny, nx))
neurons_l3[x][y].neuron_cleaning()
# создание полносвязного слоя
full_con_lay = []
for x in range(num_full_con_lay):
full_con_lay.append(LIF.LIFNeuron(neuron_label="FCL:{}".format(x), debug=debug))
neuron_full_stimulus = np.zeros(time)
x1 = 0
for d in range(0,num_feature_maps,1):
for x in range(len_x_l3):
for y in range(len_y_l3):
neuron_full_stimulus = data_neuron_l3[x,y,:time,d]*full_con_lay_W[x1]* mult_factor
full_con_lay[x1].spike_generator(neuron_full_stimulus[:time])
x1 += 1
# создание выходного слоя
full_out_lay = []
for x in range(num_out_neuron):
full_out_lay.append(LIF.LIFNeuron(neuron_label="FOL:{}".format(x), debug=debug))
for d in range(0,num_out_neuron,1):
stimulus_ret_unit = np.zeros(time)
for x in range(num_full_con_lay):
stimulus_ret_unit += full_con_lay[x].spikes[:time]*full_out_lay_W[x][d]* mult_factor
full_out_lay[d].spike_generator(stimulus_ret_unit)
#graph.plot_spikes(full_out_lay[d].time, full_out_lay[d].spikes, 'Output Spikes for {}'.format(full_out_lay[d].type), neuron_id = '{}'.format(d))
#graph.plot_membrane_potential(full_out_lay[d].time, full_out_lay[d].Vm, 'Membrane Potential {}'.format(full_out_lay[d].type), neuron_id = '{}'.format(d))
net_out_lay = np.zeros(num_out_neuron)
output = np.zeros(num_out_neuron)
for d in range(0, num_out_neuron, 1):
for x in range(num_full_con_lay):
net_out_lay[d] += full_out_lay_W[x][d] * sum(full_con_lay[x].spikes[:time])
output[d] = net_out_lay[d]/T
print("Output № {}: {}".format(d, output[d]))
if training:
#вычисление ошибки нейронов выходного слоя
q_L = np.zeros(num_out_neuron)
for d in range(0, num_out_neuron, 1):
q_L[d] = net_out_lay[d]/T
for d in range(0, num_out_neuron, 1):
if d == label: q_L[d] -= 1
q_L[d] = q_L[d]/T
#вычисление ошибки нейронов полносвязного слоя
q_L1 = np.zeros(num_full_con_lay)
for d in range(0, num_full_con_lay, 1):
W_Tr = full_out_lay_W[d][:num_out_neuron].transpose()
q_L1[d] = W_Tr.dot(q_L)
#вычисление ошибки нейронов подвыборочного слоя
x1 = 0
q_L2 = np.zeros((len_x_l3, len_y_l3, num_feature_maps))
for d in range(0,num_feature_maps,1):
for x in range(len_x_l3):
for y in range(len_y_l3):
q_L2[x, y, d] = full_con_lay_W[x1] * q_L1[x1]
x1 += 1
#вычисление ошибки нейронов сверточного слоя
q_L3 = np.zeros((len_x_l2, len_y_l2, num_feature_maps))
for d in range(0,num_feature_maps,1):
l2x, l2y = 0,0
for x1 in range(0, len_x_l3, stride[2]):
l2y = 0
for y1 in range(0, len_y_l3, stride[2]):
maxsum = 0
data_x = -1
data_y = -1
for x2 in range(stride[2]):
for y2 in range(stride[2]):
x = x1+x2
y = y1+y2
if sum(data_neuron_l2[x,y,:time,d]) > maxsum:
maxsum = sum(data_neuron_l2[x,y,:time,d])
data_x = x
data_y = y
q_L3[data_x, data_y, d] = q_L2[x1, y1, d]
l2y += 1
l2x += 1
#обновление весов сверточного слоя
for d in range(0,num_feature_maps,1):
l2x, l2y = 0,0
for x1 in range(0, len_x_l2, 1):
l2y = 0
for y1 in range(0, len_y_l2, 1):
stimulus_ret_unit = np.zeros(time)
for x2 in range(kernel_size):
for y2 in range(kernel_size):
x = x1+x2
y = y1+y2
df = 0
for i in range(0, time, 1):
if neurons_l1[x][y].spikes[i] != 0:
df += (-1/neurons_l1[x][y].tau_m)*(math.exp(-(time - i)/neurons_l1[x][y].tau_m))
dalif = (1/0.75)*(1 + ((1/sum(neurons_l1[x][y].spikes[:time]))*df))
#print("242 {}".format(dalif))
if math.isnan(dalif): dalif = 1
conv_kernel_layer2[x2, y2, d] = conv_kernel_layer2[x2, y2, d] - nu_BP * (sum(neurons_l1[x][y].spikes[:time]) * q_L3[l2x, l2y, d]) * dalif
l2y += 1
l2x += 1
x1 = 0
for d in range(0,num_feature_maps,1):
for x in range(len_x_l3):
for y in range(len_y_l3):
df = 0
for i in range(0, time, 1):
if data_neuron_l3[x,y,i,d] != 0:
df += (-1/100)*(math.exp(-(time - i)/100))
dalif = (1/0.75)*(1 + ((1/sum(data_neuron_l3[x,y,:time,d]))*df))
#print("256 {}".format(dalif))
if math.isnan(dalif): dalif = 1
full_con_lay_W[x1] = full_con_lay_W[x1] - nu_BP * (sum(data_neuron_l3[x,y,:time,d]) * q_L1[x1]) * dalif
x1 += 1
for d in range(0, num_out_neuron, 1):
for x in range(num_full_con_lay):
df = 0
for i in range(0, time, 1):
if full_con_lay[x].spikes[i] != 0:
df += (-1/100)*(math.exp(-(time - i)/100))
dalif = (1/0.75)*(1 + ((1/sum(full_con_lay[x].spikes[:time]))*df))
#print("267 {}".format(dalif))
if math.isnan(dalif): dalif = 1
full_out_lay_W[x, d] = full_out_lay_W[x, d] - nu_BP * (sum(full_con_lay[x].spikes[:time]) * q_L[d]) * dalif
creating_weights.save_W(conv_kernel_layer2, full_con_lay_W, full_out_lay_W, pool_kernel_l3)
|
4431a476af8a6f3397afad290f386501cfe1d8bc
|
[
"Python"
] | 4 |
Python
|
ZZANZZAN/SNN
|
594bfa4474097647e30e1542fc16bd46b37ae37d
|
28792d67ac82d787d3c746baf6a4094dde0f7405
|
refs/heads/master
|
<repo_name>Rin94/R-ML<file_sep>/CodigoR/SupportVectorMachines/support_ocr.R
letters<-read.csv(file.choose())
str(letters)
letters_train<-letters[1:16000,]
letters_test<-letters[16001:20000,]
library(e1071)
library(kernlab)
## suport vector m<-ksvm(target~predictors,data=mydata,kernel="rbfdot",c=1)
letter_model<-ksvm(letter~.,data=letters_train, kernel="vanilladot")
letter_model
letter_predictions<-predict(letter_model,letters_test)
letter_predictions <- predict(letter_model, letters_test)
head(letter_predictions)
#check other letters
table(letter_predictions, letters_test$letter)
agreement <- letter_predictions == letters_test$letter
table(agreement)
#accuracy table
prop.table(table(agreement))
### improving the model, witho other kernel
letter_classifier_rbf <- ksvm(letter ~ ., data = letters_train,
kernel = "rbfdot")
letter_predictions<-predict(letter_classifier_rbf,letters_test)
table(letter_predictions, letters_test$letter)
agreement <- letter_predictions == letters_test$letter
table(agreement)
<file_sep>/CodigoR/Regresiones/Rocket_Launcher_Regression.R
## read challenger.csv
launch<-read.csv(file.choose())
str(launch)
summary(launch)
lengths(launch)
### MADE THE COV, applying the formula
b<-cov(launch$temperature, launch$distress_ct)/var(launch$temperature)
b
## made the intercept using the formula
a<-mean(launch$distress_ct)-b*mean(launch$temperature)
a
##correlation
c_orr<-cov(launch$temperature, launch$distress_ct)/(sd(launch$temperature)*sd(launch$distress_ct))
c_orr
cor(launch$temperature,launch$distress_ct)
## linear regression applying the formula
#solve() takes the inverse of a matrix
#t() is used to traspose a matrix
#%*% multiplies two matrices
reg<-function(y,x){
x<-as.matrix(x)
x<-cbind(Intercept=1,x)#agregamos columna a x y la llenamos con unos
b<-solve(t(x)%*%x)%*%t(x)%*%y
colnames(b)<-"estimate"
print(b)
}
str(launch)
reg(y=launch$distress_ct, x=launch[3])
#x<-claunch[-2]
x1<-c(launch[1])
x2<-c(launch[3])
x3<-c(launch[4])
x4<-c(launch[5])
rocket_ln<-lm(launch$distress_ct~launch$temperature,data = launch)
rocket_ln
rocket_ln<-lm(launch$distress_ct~.,data = launch)
rocket_ln
summary(rocket_ln)
launch_1<-launch[-2]
launch_1<-launch_1[-1]
launch_1
reg(launch$distress_ct,launch_1[1:3])
<file_sep>/CodigoR/ArbolesDecision/Hongos_Arboles.R
### Arboles de decision
#posion mushrooms clasificator
## 1 exploring an preparing the data
hongos<-read.csv(file.choose(),stringsAsFactors = TRUE)
str(hongos)## describe the types of data
hongos$veil_type<-NULL#By assigning null a vector, R eliminates the feature from the mushrooms dataframe
table(hongos$type)#Ver los tipos de hongos
summary(hongos)
tail(hongos)
## 2 Training a model on the data
set.seed(123)
train_sample<-sample(8124,5686)
str(train_sample)
hongos_train<-hongos[train_sample,]
hongos_test<-hongos[-train_sample,]
# verify the dataset of train
prop.table(table(hongos_train$type))
#veryfi the dataset of test
prop.table(table(hongos_test$type))
library(C50)
modelo_hongos<-C5.0(hongos_train[-1],hongos_train$type,type="class")
modelo_hongos
summary(modelo_hongos)
library(gmodels)
hongos_pred<-predict(modelo_hongos,hongos_test)
CrossTable(hongos_test$type,hongos_pred, prop.chisq = FALSE,
prop.c = FALSE, prop.r=FALSE, dnn=c("actual default", "predict default"))
##install.packages("RWeka") #1Rule
#dyn.load('/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home/jre/lib/server/libjvm.dylib')
#library(RWeka)
#hongos_1R<-OneR(type~.,data=hongos)
#hongos_1R
## 3 Evaluar el performance del modelo
#summary(hongos_1R)
## 4 Mejorar el perfomance del modelo
#hongos_JRip<-JRip(type~ .,data=hongos )
#hongos_JRip
<file_sep>/Regresion1.Rmd
---
title: "Regresion Fundamentos"
author: "<NAME>"
date: "22/1/2019"
output: html_document
---
## Leyendo los datos
```{r}
launch<-read.csv("Data/challenger.csv")
```
## Obteniendo información del dataset
```{r}
str(launch)
```
```{r}
summary(launch)
```
```{r}
lengths(launch)
```
## Sacar la regresion lineal
sacamos ß
```{r}
b<-cov(launch$temperature, launch$distress_ct)/var(launch$temperature)
b
```
sacamos å
```{r}
a<-mean(launch$distress_ct)-b*mean(launch$temperature)
a
```
Verificamos la correlación
```{r}
c_orr<-cov(launch$temperature, launch$distress_ct)/(sd(launch$temperature)*sd(launch$distress_ct))
c_orr
cor(launch$temperature,launch$distress_ct)
```
## Generar funcion de regresion lineal para el dataset
```{r}
reg<-function(y,x){
x<-as.matrix(x)
x<-cbind(Intercept=1,x)#agregamos columna a x y la llenamos con unos
b<-solve(t(x)%*%x)%*%t(x)%*%y
colnames(b)<-"estimate"
print(b)
}
str(launch)
reg(y=launch$distress_ct, x=launch[3])
#x<-claunch[-2]
x1<-c(launch[1])
x2<-c(launch[3])
x3<-c(launch[4])
x4<-c(launch[5])
rocket_ln<-lm(launch$distress_ct~launch$temperature,data = launch)
rocket_ln
rocket_ln<-lm(launch$distress_ct~.,data = launch)
rocket_ln
summary(rocket_ln)
```
hacemos otras pruebas
```{r}
launch_1<-launch[-2]
launch_1<-launch_1[-1]
launch_1
reg(launch$distress_ct,launch_1[1:3])
```
<file_sep>/CodigoR/MarketBasketAnalisis/marketbasketanalysis.R
#Market Basket Analysis- tecnica recomendada para citas, dating sites, finding dangeous among medications
#9832 TRANSACTIONES (30 TRANSACTION PER HOUR), SE REMOVI?? EL VALOR DE MARCA.
#M??s granularidad,m??s datos
#cada transacci??n cada liea
#Matriz esparcida la mayoria de las transacciones tiene 0
install.packages("arules")
library("arules")
groceries <- read.transactions("groceries.csv",sep=",")#entienda que es una base de datos transaccional, separacion por comas
#densidad cuantos unos hay
#mean numero de transacciones, min 1, max 32 (n??mero de transacci??es)
#guardad unos o cero
summary(groceries)
inspect(groceries[1:5])
itemFrequency(groceries[,1:3])
itemFrequencyPlot(groceries, support=0.2)#aparezca el 10% de las observaciones
itemFrequencyPlot(groceries, topN=20)
image(groceries[1:5])#x articulos y transacciones
image(sample(groceries, 100))
#apriori
apriori(groceries)
groceryrules<-apriori(groceries, parameter = list(support=0.006, confidence=0.25, minlen=2))
groceryrules
summary(groceryrules)
inspect(groceryrules[1:100])#mostrar las reglas del 1 a la especificada
#se debe de buscar mucho lift para ver que no sea coincdencia
inspect(sort(groceryrules,by="lift")[1:10])#ordenar por lift
#funcion subset() para objetos que queramos juntos
berryrules<-subset(groceryrules, items %in% "berries")
inspect(berryrules)
milkrules<-subset(groceryrules, items %in%c ("whole milk",'berries'))
inspect(sort(milkrules,by="lift")[1:30])
#guardar resultados
write(groceryrules, file = "groceryrules.csv",sep=",", quote=TRUE, row.names=FALSE)<file_sep>/CodigoR/Regresiones/expenses-linearregression.R
insurance<-read.csv(file.choose(),stringsAsFactors = TRUE)
#gain information of the data
str(insurance)
summary(insurance)
summary(insurance$charges)#charges equals expenses
hist(insurance$charges)
#make correlation
colnames(insurance)
cor(insurance[c("age","bmi","children","charges")])
#scatterplot matrix
pairs(insurance[c("age","bmi","children","charges")])
#aumented our dataset
install.packages("psych")
library(psych)
pairs.panels(insurance[c("age","bmi","children","charges")])
#made our model
ins_model<-lm(charges~age+children+bmi+sex+smoker+region,data=insurance)
ins_model
summary(ins_model)
#improving our model
insurance$age2<-insurance$age^2
insurance$bmi30<-ifelse(insurance$bmi>=30,1,0)
ins_model2<-lm(charges~age+age2+children+bmi+sex+bmi30*smoker+region,data=insurance)
summary(ins_model2)
<file_sep>/.Rproj.user/3305E35A/sources/per/t/DACAD144-contents
---
title: "Arboles_Hongos"
author: "<NAME>"
date: "22/1/2019"
output: html_document
---
Identifiación de hongos venenosos y no venenosos, usando arboles
## Leyendo los datos
```{r}
hongos<-read.csv("data/mushrooms.csv",stringsAsFactors = TRUE)
```
## Viendo la información del dataset
```{r}
str(hongos)## describe the types of data
hongos$veil_type<-NULL#By assigning null a vector, R eliminates the feature from the mushrooms dataframe
table(hongos$type)#Ver los tipos de hongos
summary(hongos)
tail(hongos)
```
## Preparando los datos
```{r}
set.seed(123)
train_sample<-sample(8124,5686)
str(train_sample)
hongos_train<-hongos[train_sample,]
hongos_test<-hongos[-train_sample,]
# verify the dataset of train
prop.table(table(hongos_train$type))
#veryfi the dataset of test
prop.table(table(hongos_test$type))
```
## Creando modelo y evaluando el modelo
```{r}
library(C50)
modelo_hongos<-C5.0(hongos_train[-1],hongos_train$type,type="class")
modelo_hongos
summary(modelo_hongos)
library(gmodels)
hongos_pred<-predict(modelo_hongos,hongos_test)
CrossTable(hongos_test$type,hongos_pred, prop.chisq = FALSE,
prop.c = FALSE, prop.r=FALSE, dnn=c("actual default", "predict default"))
```
<file_sep>/CodigoR/KNN/knn-cancerbreast.R
## read the csv
wbcd<-read.csv(file.choose(),stringsAsFactors = FALSE)
##Str as describe on python
str(wbcd)
#drop the first column id
wbcd<-wbcd[-1]
# we are searching the diagnosis of cancer
table(wbcd$diagnosis)
wbcd$diagnosis<-factor(wbcd$diagnosis, levels=c("B","M"), labels = c("Benign","Malignant"))
#buscar porcentajes de las masas
round(prop.table(table(wbcd$diagnosis))*100,digits = 1)
#look for some characteristics
summary(wbcd[c("radius_mean","area_mean","smoothness_mean")])
#como vemos, el radio tiene medidas muy diferentes entre el area y el smoothnees en tamaño
#por eso debemos de normalizar los datos
normalize<-function(x){
return ((x-min(x))/(max(x)-min(x)))
}
#hacer pruebas en nuestra funcion de normalización
normalize(c(1,2,3,4,5))
normalize(c(10,20,30,40,50))
normalize(c(100,200,300,400,500))
#normalizar el dataset, con la funcion lapply y regresarlo como dataframe
wbcd_n<-as.data.frame(lapply(wbcd[2:31], normalize))
summary(wbcd_n$area_mean)
#data preparation @[row,column]
wbcd_train<-wbcd_n[1:469, ]
wbcd_test<-wbcd_n[470:569,]
#labels data preparations
wbcd_train_labels<-wbcd[1:469,1]
wbcd_test_labels<-wbcd[470:569,1]
#training a model on the data
#install packages where is the knn algorithm
install.packages("class")
library("class")
#aplicar el algoritmo knn
# knn buen numero de vecinos es la raiz cuadrada total de los datos sqrt(469)
wbcd_pred<-knn(train=wbcd_train,test=wbcd_test, cl=wbcd_train_labels,k=21)
install.packages("gmodels")
library(gmodels)
#ver el performance del algoritmo
CrossTable(x=wbcd_test_labels,y=wbcd_pred,prop.chsq=FALSE)
#improving algorithm
#using z score instead of normalization
wbcd_z<-as.data.frame(scale(wbcd[-1]))
summary(wbcd_z$area_mean)
wbcd_train<-wbcd_z[1:469,]
wbcd_test<-wbcd_z[470:569,]
wbcd_train_labels<-wbcd[1:469,1]
wbcd_test_labels<-wbcd[470:569,1]
wbcd_tes_pred<-knn(train = wbcd_train,test = wbcd_test, cl=wbcd_train_labels,k=21)
CrossTable(x=wbcd_test_labels,y=wbcd_tes_pred,prop.chisq = FALSE)
<file_sep>/CodigoR/K-means/Kmeans-teens.R
####K-means###
###Read the SNS DATA FOR TEENAGERS
sns<-read.csv("snsdata.csv")
str(sns)
#check missing values
table(sns$gender,useNA = "ifany")
summary(sns$age)#max age and min age are unreasonable for teenagers
###Data Preparation- dummy missing values
sns$female<-ifelse(sns$gender=="F" & !is.na(sns$gender),1,0)
sns$nogender<-ifelse(is.na(sns$gender),1,0)
table(sns$female)
table(sns$nogender)
###Data Preparation - Inputing missing values
sns$age<-ifelse(sns$age>=13&sns$age<20,sns$age,NA)
mean(sns$age, na.rm=TRUE)
#calcula la media de la edad por los valores de año
aggregate(data=sns,age~gradyear,mean,na.rm=TRUE)
#ave() regresa un vector con el grupo de medias repetidas, asi que el resultado
#es igual al vector original
ave_age<-ave(sns$age, sns$gradyear,FUN=function(x) mean(x,na.rm=TRUE))
ave_age
sns$age<-ifelse(is.na(sns$age),ave_age,sns$age)
summary(sns$age)
###Fit the data test
install.packages("stats")
library(stats)
interests<-sns[5:40]
interests
#normalize the interest-lapply returns matrix, as.data.frame convert to dataframe
interests_xyz<-as.data.frame(lapply(interests,scale))
interests_xyz
set.seed(2345)
sns_clusters<-kmeans(interests_xyz,5)
###Evaluate model performance
sns_clusters$size
sns_clusters$centers
sns_clusters$cluster
sns$cluster_id<-sns_clusters$cluster
###improving model performance
sns[1:5,c("cluster_id","gender","age","friends")]
aggregate(data=sns,age~cluster_id,mean)
aggregate(data=sns,female~cluster_id,mean)
aggregate(data=sns,friends~cluster_id,mean)
<file_sep>/.Rproj.user/3305E35A/sources/per/t/FA434F25-contents
---
title: "Naive Bayes"
author: "<NAME>"
date: "21/1/2019"
output:
html_document: default
pdf_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
### Leyendo la información
```{r}
sms_raw<-read.csv("data/sms_spam.csv",stringsAsFactors = FALSE)
```
Vemos información del dataset
```{r}
str(sms_raw)
```
La información son el texto, y una clasificación (spam o ham)
## Vemos información estadistica del caso de estudio
```{r}
summary(sms_raw)
```
Número de spam y ham
```{r}
table(sms_raw$type)
```
Hay más información sobre ham que de spam
## Procesamiento de los datos
Como es un conjunto de texto, tenemos que hacer una limpieza de los datos, quitar información
irrelevante para el clasificador, tener en cuenta que es importante saber que los mensajes que contienen spam, te regalan algo, o te dan algo muy dificil de obtener. Es por eso que usan mucho la
palabra "free"
```{r}
#importamos librería necesaria
library(tm)
```
```{r}
sms_corpus<-VCorpus(VectorSource(sms_raw$text))
print(sms_corpus)
```
Hacemos elementos de tipo documentos.
visualizamos los datos de los documentos.
```{r}
# visualizar los datos del corpus
inspect(sms_corpus[1:2])
as.character(sms_corpus[[1]])
```
La función lappy nos deja poder más de dos documentos, ya que afecta al conjunto
```{r}
lapply(sms_corpus[1:2], as.character)
```
Primero tenemos que hacer que nuestras cadenas de texto esten todas en minusculas
```{r}
sms_corpus_clean<-tm_map(sms_corpus, content_transformer(tolower))
as.character(sms_corpus[[1]])
as.character(sms_corpus_clean[[1]])
```
Removemos Números de nuestros textos
```{r}
sms_corpus_clean<-tm_map(sms_corpus_clean,removeNumbers)
```
También información irrelevante, en nuestro caso, son los nexos, uniones.
Para eso usamos la función stopwords y tambien puntuaciones con con removePunctuation
```{r}
sms_corpus_clean<-tm_map(sms_corpus_clean,removeWords,stopwords())
sms_corpus_clean<-tm_map(sms_corpus_clean,removePunctuation)
as.character(sms_corpus_clean[[1]])
```
```{r}
library(SnowballC)
```
WordStem nos saca la radical de las palabras
```{r}
wordStem(c("learn", "learned", "learning","learns"))
wordStem(c("videogamer","gamer","gaming","gamer"))
```
```{r}
sms_corpus_clean<-tm_map(sms_corpus_clean, stemDocument)
as.character(sms_corpus_clean[[1]])
```
Removemos espacios vacios
```{r}
sms_corpus_clean<-tm_map(sms_corpus_clean, stripWhitespace)
#print(as.character(sms_corpus[1:3]))
#as.character(sms_corpus[1:3])
print(as.character(sms_corpus_clean[1:3]))
as.character(sms_corpus_clean[1])
```
## Preparación de los datos
```{r}
sms_dtm<-DocumentTermMatrix(sms_corpus_clean)
```
Pudimos haber hecho todo lo anterior con la siguiente linea:
```{r}
sms_dtm2<-DocumentTermMatrix(sms_corpus,
control = list(tolower=TRUE,
removeNumbers=TRUE,
stopwords=TRUE,
removePunctuation=TRUE,
stemming=TRUE))
```
```{r}
sms_dtm
sms_dtm2
```
```{r}
sms_dtm_train<-sms_dtm[1:4169,]
sms_dtm_test<-sms_dtm[4170:5559,]
sms_train_labels<-sms_raw[1:4169,]$type
sms_test_labels<-sms_raw[4170:5559,]$type
prop.table(table(sms_train_labels))
prop.table(table(sms_test_labels))
```
Hacemos los cortes de prueba y entrenamiento y vemos la distribución del ham y el spam
## Visualizando la información
Además hacemos una nube de palabras para identificar las palabras más sonadas en el documento.
```{r}
library(wordcloud)
```
```{r}
wordcloud(sms_corpus_clean,min.freq = 50, random.order = FALSE)
options(warnings=2)
```
Vemos otras nubes de palabras unas del spam y otra del ham
```{r}
spam<-subset(sms_raw,type=="spam")
ham<-subset(sms_raw,type=="ham")
wordcloud(spam$text,max.words = 40,scale=c(3,0.5))
wordcloud(ham$text,max.words = 40, scale=c(3,0.5))
```
Vamos hacer más limpio la prueba, haciendo que solo busque la que tenga más de 5 menciones
```{r}
findFreqTerms(sms_dtm_train,5)
sms_freq_words<-findFreqTerms(sms_dtm_train,5)
str(sms_freq_words)
sms_dtm_freq_train<- sms_dtm_train[ , sms_freq_words]
sms_dtm_freq_test <- sms_dtm_test[ , sms_freq_words]
##hacer una funcion que nos diga si es spam o no
convert_counts <- function(x) {
x <- ifelse(x > 0, "Yes", "No")
}
sms_train <- apply(sms_dtm_freq_train, MARGIN = 2,
convert_counts)
sms_test <- apply(sms_dtm_freq_test, MARGIN = 2,
convert_counts)
str(sms_train)
str(sms_test)
```
## Haciendo el modelo y evaluando
```{r}
install.packages("e1071",repos = "http://cran.us.r-project.org")
library(e1071)
```
```{r}
sms_classifier <- naiveBayes(sms_train, sms_train_labels)
#making predictions
sms_test_pred <- predict(sms_classifier, sms_test)
head(sms_test_pred)
```
```{r}
#install.packages("gmodels", repos = "http://cran.us.r-project.org")
#library(gmodels)
length(sms_test_pred)
#CrossTable(sms_test_pred, sms_test_labels,
# prop.chisq = FALSE, prop.t = FALSE,
# dnn = c('predicted', 'actual'))
table(sms_test_pred,sms_test_labels)
```
## Buscando mejorar usando el estimador laplace
```{r}
sms_classifier2<-naiveBayes(sms_train,sms_train_labels,laplace = 1)
sms_tes_pred2<-predict(sms_classifier2,sms_test)
#CrossTable(sms_tes_pred2,sms_test_labels,prop.chisq = FALSE, prop.t = FALSE,
# dnn = c("predicted","actual"))
table(sms_tes_pred2,sms_test_labels)
```
<file_sep>/CodigoR/NaiveBayes/Bayes.R
#Bayes-Naive Bayes--- hagamos un resumen de la parte teoríca
sms_raw<-read.csv(file.choose(),stringsAsFactors = FALSE)
# Info of dataset
str(sms_raw)
sms_raw$type<-factor(sms_raw$type)
##convertir a factor
sms_raw$type<-factor(sms_raw$type)
str(sms_raw$type)
table(sms_raw$type)
### Data preparation - cleaning
install.packages("tm")
library(tm)
##corpus coleccion de documentos de textos,
sms_corpus<-VCorpus(VectorSource(sms_raw$text))
print(sms_corpus)
# visualizar los datos del corpus
inspect(sms_corpus[1:2])
as.character(sms_corpus[[1]])
## visualizar más de dos documentos usar la funcion lappy
lapply(sms_corpus[1:2], as.character)
## Limpiar el corpus, transformar los datos a minusculas
sms_corpus_clean<-tm_map(sms_corpus, content_transformer(tolower))
as.character(sms_corpus[[1]])
as.character(sms_corpus_clean[[1]])
## remover numeros
sms_corpus_clean<-tm_map(sms_corpus_clean,removeNumbers)
## Our next task is to remove filler words such: to, and, but, or from our
#SMS message. These terms are known as STOP WORDS, cuz do not provide much
#useful inofrmation and last remove these words
sms_corpus_clean<-tm_map(sms_corpus_clean,removeWords,stopwords())
## Next remove any punctiation from the text messages
sms_corpus_clean<-tm_map(sms_corpus_clean,removePunctuation)
removePunctuation("hello...,...world")
## Reducing words to ther root by the process called STEMMING
install.packages("SnowballC")
library(SnowballC)
wordStem(c("learn", "learned", "learning","learns"))
wordStem(c("videogame","game","gaming","gamer"))
sms_corpus_clean<-tm_map(sms_corpus_clean, stemDocument)
## REMOVE white_spaces
sms_corpus_clean<-tm_map(sms_corpus_clean, stripWhitespace)
print(as.character(sms_corpus[1:3]))
as.character(sms_corpus[1:3])
print(as.character(sms_corpus_clean[1:3]))
as.character(sms_corpus_clean[1:3])
### Data preparation
##Now that the data are processed to our liking, the final step is to split
#the messages into invidual components through a process called tokenization
#Tokenizer
#rows: documents, columns:words
#hace una columna de cuantas veces se muestra una palabra
sms_dtm<-DocumentTermMatrix(sms_corpus_clean)
sms_dtm2<-DocumentTermMatrix(sms_corpus,
control = list(tolower=TRUE,
removeNumbers=TRUE,
stopwords=TRUE,
removePunctuation=TRUE,
stemming=TRUE))
sms_dtm
sms_dtm2
##the order of preparation matters
### Data preparation- creating training and test datasets
sms_dtm_train<-sms_dtm[1:4169,]
sms_dtm_test<-sms_dtm[4170:5574,]
sms_train_labels<-sms_raw[1:4169,]$type
sms_test_labels<-sms_raw[4170:5574,]$type
prop.table(table(sms_train_labels))
prop.table(table(sms_test_labels))
### Visualizing text data - WORD CLOUDS
install.packages("wordcloud")
library(wordcloud)
wordcloud(sms_corpus_clean,min.freq = 50, random.order = FALSE)
options(warnings=2)
spam<-subset(sms_raw,type=="spam")
ham<-subset(sms_raw,type=="ham")
wordcloud(spam$text,max.words = 40,scale=c(3,0.5))
wordcloud(ham$text,max.words = 40, scale=c(3,0.5))
### Data preparation
## para hacerlo más limpio vamos a reducir el numero de caracteristicas,
##quitando palabras que tengan menos de 5 menciones usando
#FINDFREQTERMS
findFreqTerms(sms_dtm_train,5)
sms_freq_words<-findFreqTerms(sms_dtm_train,5)
str(sms_freq_words)
sms_dtm_freq_train<-sms_dtm_train[,sms_freq_words]
sms_dtm_freq_test<-sms_dtm_test[,sms_freq_words]
##hacer una funcion que nos diga si es spam o no
convert_counts<-function(x){
x<-ifelse(x>0,"Yes","No")
}
sms_train<-apply(sms_dtm_freq_train, MARGIN = 2, convert_counts)
sms_test<-apply(sms_dtm_freq_test, MARGIN = 2, convert_counts)
install.packages("e1071")
library(e1071)
#building the classifier
sms_classifier<-naiveBayes(sms_train,sms_train_labels)
#making predictions
sms_tes_pred<-predict(sms_classifier,sms_test)
#example
library(gmodels)
CrossTable(sms_tes_pred,sms_test_labels,prop.chisq = FALSE, prop.t = FALSE,
dnn = c("predicted","actual"))
## Mejorando con el laplace
sms_classifier2<-naiveBayes(sms_train,sms_train_labels,laplace = 1)
sms_tes_pred2<-predict(sms_classifier2,sms_test)
library(gmodels)
CrossTable(sms_tes_pred2,sms_test_labels,prop.chisq = FALSE, prop.t = FALSE,
dnn = c("predicted","actual"))
<file_sep>/CodigoR/ArbolesDecision/arboles_bancos.R
###Árboles de decición usando C5.0
###read the credit.csv dataset
credit<-read.csv(file.choose())
##check de columns of the data set, like age, housing, dependents
str(credit)
## check the features as factors
table(credit$checking_balance)
table(credit$savings_balance)
## check for distribution of some values
summary(credit$months_loan_duration)
summary(credit$amount)
## make y credit default<- factor (yes, no)
credit$default
credit$default <- factor(credit$default,
levels=c(1,2),
labels=c("No","Si"))
# credit table score
table(credit$default)
## Data preparation- creating random training and test datasets
set.seed(123)
train_sample<-sample(1000,900)
str(train_sample)
credit_train<-credit[train_sample,]
credit_test<-credit[-train_sample,]
# verify the dataset of train
prop.table(table(credit_train$default))
#veryfi the dataset of test
prop.table(table(credit_test$default))
##Training a model on the data
library(C50)
credit_model<-C5.0(credit_train[-17],credit_train$default,type="class")
credit_model ##gives info of the decision tree
summary(credit_model)
library(gmodels)
credit_pred<-predict(credit_model,credit_test)
CrossTable(credit_test$default,credit_pred, prop.chisq = FALSE,
prop.c = FALSE, prop.r=FALSE, dnn=c("actual default", "predict default"))
##Improving performance
#using trials for punning the tree
model_2<-C5.0(credit_train[-17],credit_train$default,type="Class",trials = 10)
model_2
summary(model_2)
credit_boost<-predict(model_2,credit_test)
table(credit_boost)
CrossTable(credit_test$default, credit_boost, prop.chisq = FALSE, prop.c = FALSE,
prop.r = FALSE,
dnn=c("actual defaul", "predicted default"))
### mejorar un tipo de error que sea menos costoso, vamos a mejorar la specfificidad
matrix_dimensions<-list(c("no","yes"), c("no","yes"))
names(matrix_dimensions)<-c("predicted","actual")
matrix_dimensions
error_cost<-matrix(c(0,1,4,0),nrow = 2, dimnames = matrix_dimensions)
error_cost
credit_cost<-C5.0(credit_train[-17],credit_train$default,type="Class",costs=error_cost)
credit_cost_pred<-predict(credit_cost,credit_test)
matrix_dimensions <- list(c("no", "yes"), c("no", "yes"))
names(matrix_dimensions) <- c("predicted", "actual")
matrix_dimensions
error_cost <- matrix(c(0, 1, 1, 0), nrow = 2,
dimnames = matrix_dimensions)
error_cost
credit_cost <- C5.0(credit_train[-17], credit_train$default, trials = 8,
costs =error_cost)
credit_cost_pred<-predict(credit_cost,credit_test)
CrossTable(credit_test$default, credit_cost_pred, prop.chisq = FALSE, prop.c = FALSE,
prop.r = FALSE,
dnn=c("actual defaul", "predicted default"))
<file_sep>/CodigoR/NeuralNetwork/RedesNeuronales.R
#Cargando los datos
concrete<-read.csv("concrete.csv")
str(concrete)
#Vamos a predecir la fortaleza del semento, la mayoria son numericos
#Vamos a normalizar de o a 1 Usando la funcion de minimos y maximos
normalize<-function(x){
return ((x-min(x))/ (max(x)- min(x)))
}
concrete_norm<-as.data.frame(lapply(concrete, normalize))
#lappy nos evita usar ciclo, donde le decimos que todas las columnas, le aplica la funci??n normalize
#Comprobamos si estan normalizados
summary(concrete_norm $ strength)
#Comprobamos con los valores normales
summary(concrete $ strength)
concrete_train<-concrete_norm[1:773,]
concrete_test<-concrete_norm[774:1030,]
install.packages("neuralnet")
library(neuralnet)
set.seed(12354)
#m<- neuralnet(target-predictors, data= mydata, hidden=1)
concrete_model<-neuralnet(strength ~ cement +slag + ash + water + superplastic + coarseagg + fineagg +age, data=concrete_train)
plot(concrete_model, rep="best")
#Evaluar el desempenio del modelo
#Pasarle nuestro modelo, con muestros datos de prueba, la parte es la comlumna, no se pasa la columna 9
model_result<-compute(concrete_model, concrete_test[1:8])
#vamos a guardar los resultados de nuestra prediccion
predicted_strength<-model_result$net.result
#Correlacion para no clasificacion
cor(predicted_strength,concrete_test$strength)[,1]
concrete_model2<-neuralnet(strength ~ cement +slag + ash + water + superplastic + coarseagg + fineagg +age, data=concrete_train,hidden=5)
plot(concrete_model2, rep="best")
model_result2<-compute(concrete_model2, concrete_test[1:8])
predicted_strength2<-model_result2$net.result
cor(predicted_strength2,concrete_test$strength)
<file_sep>/CodigoR/ArbolesRegresion/linear_tree_et_linear_models.R
##How it works?
tee<-c(1,1,1,2,2,3,4,5,5,6,6,7,7,7,7)
at1<-c(1,1,1,2,2,3,4,5,5)
at2<-c(6,6,7,7,7,7)
bt1<-c(1,1,1,2,2,3,4)
bt2<-c(5,5,6,6,7,7,7,7)
sdr_a<-sd(tee)-(length(at1)/length(tee)*sd(at1)+length(at2)/length(tee)*sd(at2))
sdr_b<-sd(tee)-(length(bt1)/length(tee)*sd(bt1)+length(bt2)/length(tee)*sd(bt2))
## read the archive
wine<-read.csv(file.choose(),stringsAsFactors = TRUE)
## examine the archive
str(wine)
summary(wine)
sum(is.na(wine))
## correlation
library(psych)
pairs.panels(wine[colnames(wine)])
cor(wine)
### hist
hist(wine$quality)
## make the split
set.seed(2)
train_sample<-sample(4898,3750)
train_sample
wine_train<-wine[train_sample,]
wine_test<-wine[-train_sample,]
str(wine_test)
str(wine_train)
## using rpart
library(rpart)
## m<-rpart(dv~iv, data=mydata)
#p<-predict(m,test,type="vector")
###vector->numeric values
###class->classification classes
###prob->predicted class probabilites
winemodel<-rpart(quality~.,data=wine_train)
winemodel
###Visualizing decision trees
library(rpart.plot)
rpart.plot(winemodel,digits = 3)
#extra parameters
rpart.plot(winemodel,digits=4,fallen.leaves = TRUE,type=3,extra = 101)
###Evaluating model performance
p.rpart<-predict(winemodel,wine_test)
summary(p.rpart)
summary(wine_test$quality)
cor(p.rpart,wine_test$quality)
#MAE Mean Absolute Error
MAE<-function(actual,predicted){
mean(abs(actual-predicted))
}
MAE(p.rpart,wine_test$quality)
mean(wine_train$quality)
MAE(5.87,wine_test$quality)
library(RWeka)
|
b23bcee8a3adc3b67b55d24dc5ddb321868c4338
|
[
"R",
"RMarkdown"
] | 14 |
R
|
Rin94/R-ML
|
1b07b5e8ebab27efd883f6f5685d6d5979334774
|
50d603fa4992fba73225e4d36cb4bcb2872dd3af
|
refs/heads/master
|
<repo_name>yribeiro/computer_vision<file_sep>/utils.py
import cv2
import numpy as np
def find_cb_points(img, cb_size):
"""
Function returns the corners for an image with a chessboard.
:param img: Image with chessboard in it.
:param cb_size: Size of the inner chessboard - tuple
:return:
(ret, corners) where ret is a boolean for points found in image and
corners are the pixel coordinates for the chessboard points.
"""
_criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, cb_size, None)
if ret:
corners = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), _criteria)
else:
print("No chess board found ...")
return ret, corners
def draw_cube_on_img(img, rvec, tvec, K, d):
"""
Helper function to ingest an image path , along with the rodrigues rotation,
translation vectors and the camera calibration matrix and distortion coefficients
to draw a cube on the image.
:param img: np array representing the image
:param rvec: rodrigues rotation vector to get toimage plane
:param tvec: translation vector to get to image plane
:param K: Camera calibration matrix
:param d: Camera distortion vector
:return: Image (np.array()) with the projected cube
"""
_3d_corners = np.float32([[0, 0, 0], [0, 3, 0], [3, 3, 0], [3, 0, 0],
[0, 0, -3], [0, 3, -3], [3, 3, -3], [3, 0, -3]])
print(f"3D corners shape: {_3d_corners}")
cube_corners_2d, _ = cv2.projectPoints(_3d_corners, rvec, tvec, K, d)
print(f"2D corners shape: {cube_corners_2d}")
red, blue, green = (0, 0, 255), (255, 0, 0), (0, 255, 0) # red (in BGR)
line_width = 3
# first draw the base in red
cv2.line(img, tuple(cube_corners_2d[0][0]), tuple(cube_corners_2d[1][0]), red, line_width)
cv2.line(img, tuple(cube_corners_2d[1][0]), tuple(cube_corners_2d[2][0]), red, line_width)
cv2.line(img, tuple(cube_corners_2d[2][0]), tuple(cube_corners_2d[3][0]), red, line_width)
cv2.line(img, tuple(cube_corners_2d[3][0]), tuple(cube_corners_2d[0][0]), red, line_width)
# now draw the pillars
cv2.line(img, tuple(cube_corners_2d[0][0]), tuple(cube_corners_2d[4][0]), blue, line_width)
cv2.line(img, tuple(cube_corners_2d[1][0]), tuple(cube_corners_2d[5][0]), blue, line_width)
cv2.line(img, tuple(cube_corners_2d[2][0]), tuple(cube_corners_2d[6][0]), blue, line_width)
cv2.line(img, tuple(cube_corners_2d[3][0]), tuple(cube_corners_2d[7][0]), blue, line_width)
# finally draw the top
cv2.line(img, tuple(cube_corners_2d[4][0]), tuple(cube_corners_2d[5][0]), green, line_width)
cv2.line(img, tuple(cube_corners_2d[5][0]), tuple(cube_corners_2d[6][0]), green, line_width)
cv2.line(img, tuple(cube_corners_2d[6][0]), tuple(cube_corners_2d[7][0]), green, line_width)
cv2.line(img, tuple(cube_corners_2d[7][0]), tuple(cube_corners_2d[4][0]), green, line_width)
return img
def find_chessboard_and_draw_cube(img, K, d, cb):
"""
Helper function to ingest an image, find a chessboard on it and draw a cube if it exists
:param img: Np array for the image
:param K: Camera calibration matrix
:param d: Camera distortion vector
:param cb: Tuple containing the (col, row) for the chessboard
:return: None if not chessboard, else the image with the cube on it
"""
_subpix_criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.1)
# get 3D image plane coords
objp = np.zeros((cb[0] * cb[1], 3), np.float32)
objp[:, :2] = np.mgrid[0:cb[0], 0:cb[1]].T.reshape(-1, 2)
ret, corners = find_cb_points(img, cb)
if ret:
print("Found corners")
_, rvec, tvec, _ = cv2.solvePnPRansac(objp, corners, K, d)
# print values
print(f"Found rvec: {rvec.tolist()}, tvec: {tvec.tolist()}")
return draw_cube_on_img(img, rvec, tvec, K, d)
else:
return None
<file_sep>/main.py
import cv2
import os
from camera_calib import CameraCalibration
from utils import find_chessboard_and_draw_cube, draw_cube_on_img
def main(cb_size, mtx, dist):
cap = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = cap.read()
if ret == True:
img = find_chessboard_and_draw_cube(frame, mtx, dist, cb_size)
if img is not None:
cv2.imshow("Cubed Feed!", img)
key = cv2.waitKey(1)
if key == ord("q"):
cv2.destroyAllWindows()
break
else:
cv2.destroyAllWindows()
# When everything done, release the capture
cap.release()
print("Exiting program ..")
if __name__ == "__main__":
# chessboard dimensions
cb_size = (8, 6)
calib = CameraCalibration(cb_size=cb_size)
calib.calibrate()
folder = "calibration_images"
for idx, img_path in enumerate(os.listdir(folder)):
img = draw_cube_on_img(
cv2.imread(os.path.join(folder, img_path)),
calib.rvecs[idx], calib.tvecs[idx], calib.cam_calib_mat, calib.lens_dist
)
cv2.imshow("Cube", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
main(cb_size=cb_size, mtx=calib.cam_calib_mat, dist=calib.lens_dist)
<file_sep>/camera_calib.py
import copy
import cv2
import os
import numpy as np
from utils import find_cb_points
class CameraCalibration:
def __init__(self, cb_size=(6, 8)):
self.cb_size = cb_size
# init necessary storage variables
self.cam_calib_mat, self.lens_dist = np.zeros((3, 3)), np.zeros((4, 1))
self.rvecs, self.tvecs = None, None
def _capture_webcam_chessboard_image(self):
"""
Function that returns a valid image with a chessboard pattern
"""
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if ret == True:
cb_ret, corners = find_cb_points(frame, self.cb_size)
if cb_ret == True:
break
cap.release()
return frame, corners
def capture_valid_images(self):
key = None
while key != ord("q"):
img, corners = self._capture_webcam_chessboard_image()
# create a copy for display purposes
img_temp = copy.deepcopy(img)
cv2.drawChessboardCorners(img_temp, self.cb_size, corners, True)
cv2.imshow("Chessboard", img_temp)
key = cv2.waitKey()
cv2.destroyAllWindows()
if key == ord("s"):
# persist image
rel_folder = os.path.join(os.getcwd(), "calibration_images")
num_files = len(os.listdir(rel_folder))
cv2.imwrite(os.path.join(rel_folder, f"calib_{num_files}.png"), img)
print("Finished image capture stage")
def _get_points(self):
"""
Function to get the object points in 3D chessboard plane coords and
the corresponding image points on the board.
Obtains images from the calibration_images folder in the cwd.
:return: (obj_coords_list, img_coords_list) where obj_coords_list is a collection
of the chessboard corner coordinates in 3D chessboard plane and the img_coords_list is a
collection of the corresponding image coords in pixels.
"""
files = os.listdir("calibration_images")
# create real world object points and associated real world axes based
# based on chessboard configuration
objp = np.zeros((self.cb_size[0] * self.cb_size[1], 3), np.float32)
objp[:, :2] = np.mgrid[0:self.cb_size[1], 0:self.cb_size[0]].T.reshape(-1, 2)
obj_coords_list = []
img_coords_list = []
for fname in files:
img = cv2.imread(os.path.join("calibration_images", fname))
cb_ret, corners = find_cb_points(img, self.cb_size)
if cb_ret == True:
obj_coords_list.append(objp)
img_coords_list.append(corners)
return obj_coords_list, img_coords_list
def calibrate(self, save_flag=False, save_loc=""):
print("Starting calibration")
obj_pts_list, img_pts_list = self._get_points()
# get the size of a random image
rimg = cv2.imread(os.path.join("calibration_images", os.listdir("calibration_images")[0]))
shape = (rimg.shape[1], rimg.shape[0])
rimg = None
rms, self.cam_calib_mat, self.lens_dist, self.rvecs, self.tvecs = cv2.calibrateCamera(
obj_pts_list, img_pts_list, shape, self.cam_calib_mat, self.lens_dist,
None, None, criteria=(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6)
)
print("-"*20)
print(f"Calibrated off {len(obj_pts_list)} images")
print(f"DIM = {shape}")
print(f"Camera Calibration Matrix = {self.cam_calib_mat}")
print(f"Camera Lens Distortion = {self.lens_dist}")
print(f"RMS = {rms}")
if save_flag:
np.savez(os.path.join(save_loc, "calib_mat"), self.cam_calib_mat, self.lens_dist)
if __name__ == "__main__":
calib = CameraCalibration()
calib.calibrate()
|
24fa1232c069c075ce1b8ac98fb73054999f4041
|
[
"Python"
] | 3 |
Python
|
yribeiro/computer_vision
|
9caaacc7cc1d0d87aa88be5d959f0b286e9806ca
|
a7323ef4afdfb056b3cfee91e05a7097603ef811
|
refs/heads/master
|
<repo_name>techleft/SwiftParsec<file_sep>/Tests/LinuxMain.swift
import XCTest
@testable import SwiftParsecTests
XCTMain([
testCase([
("testOneOf", CharacterTests.testOneOf),
("testOneOfInterval", CharacterTests.testOneOfInterval),
("testNoneOf", CharacterTests.testNoneOf),
("testSpaces", CharacterTests.testSpaces),
("testUnicodeSpace", CharacterTests.testUnicodeSpace),
("testSpace", CharacterTests.testSpace),
("testNewLine", CharacterTests.testNewLine),
("testCrlf", CharacterTests.testCrlf),
("testEndOfLine", CharacterTests.testEndOfLine),
("testTab", CharacterTests.testTab),
("testUppercase", CharacterTests.testUppercase),
("testLowercase", CharacterTests.testLowercase),
("testAlphaNumeric", CharacterTests.testAlphaNumeric),
("testLetter", CharacterTests.testLetter),
("testSymbol", CharacterTests.testSymbol),
("testDigit", CharacterTests.testDigit),
("testDecimalDigit", CharacterTests.testDecimalDigit),
("testHexadecimalDigit", CharacterTests.testHexadecimalDigit),
("testOctalDigit", CharacterTests.testOctalDigit),
("testString", CharacterTests.testString)
]),
testCase([
("testLarge", CharacterSetTests.testLarge)
]),
testCase([
("testChoice", CombinatorTests.testChoice),
("testOtherwise", CombinatorTests.testOtherwise),
("testOptional", CombinatorTests.testOptional),
("testDiscard", CombinatorTests.testDiscard),
("testBetween", CombinatorTests.testBetween),
("testSkipMany1", CombinatorTests.testSkipMany1),
("testMany1", CombinatorTests.testMany1),
("testSeparatedBy", CombinatorTests.testSeparatedBy),
("testSeparatedBy1", CombinatorTests.testSeparatedBy1),
("testDividedBy", CombinatorTests.testDividedBy),
("testDividedBy1", CombinatorTests.testDividedBy1),
("testCount", CombinatorTests.testCount),
("testChainRight", CombinatorTests.testChainRight),
("testChainRight1", CombinatorTests.testChainRight1),
("testChainLeft", CombinatorTests.testChainLeft),
("testChainLeft1", CombinatorTests.testChainLeft1),
("testNoOccurence", CombinatorTests.testNoOccurence),
("testManyTill", CombinatorTests.testManyTill),
("testRecursive", CombinatorTests.testRecursive),
("testEof", CombinatorTests.testEof)
]),
testCase([
("testIdentifier", GenericTokenParserTests.testIdentifier),
("testReservedName", GenericTokenParserTests.testReservedName),
("testLegalOperator", GenericTokenParserTests.testLegalOperator),
("testReservedOperator", GenericTokenParserTests.testReservedOperator),
("testCharacterLiteral", GenericTokenParserTests.testCharacterLiteral),
("testStringLiteral", GenericTokenParserTests.testStringLiteral),
("testSwiftStringLiteral",
GenericTokenParserTests.testSwiftStringLiteral),
("testJSONStringLiteral",
GenericTokenParserTests.testJSONStringLiteral),
("testNatural", GenericTokenParserTests.testNatural),
("testInteger", GenericTokenParserTests.testInteger),
("testIntegerAsFloat", GenericTokenParserTests.testIntegerAsFloat),
("testFloat", GenericTokenParserTests.testFloat),
("testNumber", GenericTokenParserTests.testNumber),
("testDecimal", GenericTokenParserTests.testDecimal),
("testHexadecimal", GenericTokenParserTests.testHexadecimal),
("testOctal", GenericTokenParserTests.testOctal),
("testSymbol", GenericTokenParserTests.testSymbol),
("testWhiteSpace", GenericTokenParserTests.testWhiteSpace),
("testParentheses", GenericTokenParserTests.testParentheses),
("testBraces", GenericTokenParserTests.testBraces),
("testAngles", GenericTokenParserTests.testAngles),
("testBrackets", GenericTokenParserTests.testBrackets),
("testPunctuations", GenericTokenParserTests.testPunctuations),
("testSemicolonSeparated",
GenericTokenParserTests.testSemicolonSeparated),
("testSemicolonSeparated1",
GenericTokenParserTests.testSemicolonSeparated1),
("testCommaSeparated", GenericTokenParserTests.testCommaSeparated),
("testCommaSeparated1", GenericTokenParserTests.testCommaSeparated1)
]),
testCase([
("testCharacterError", ErrorMessageTests.testCharacterError),
("testStringError", ErrorMessageTests.testStringError),
("testEofError", ErrorMessageTests.testEofError),
("testChoiceError", ErrorMessageTests.testChoiceError),
("testCtrlCharError", ErrorMessageTests.testCtrlCharError),
("testPositionError", ErrorMessageTests.testPositionError),
("testNoOccurenceError", ErrorMessageTests.testNoOccurenceError),
("testLabelError", ErrorMessageTests.testLabelError),
("testMultiLabelError", ErrorMessageTests.testMultiLabelError),
("testGenericError", ErrorMessageTests.testGenericError),
("testUnknownError", ErrorMessageTests.testUnknownError)
]),
testCase([
("testExpr", ExpressionTests.testExpr),
("testReplaceRange", ExpressionTests.testReplaceRange)
]),
testCase([
("testMap", GenericParserTests.testMap),
("testApplicative", GenericParserTests.testApplicative),
("testAlternative", GenericParserTests.testAlternative),
("testFlatMap", GenericParserTests.testFlatMap),
("testAtempt", GenericParserTests.testAtempt),
("testLookAhead", GenericParserTests.testLookAhead),
("testMany", GenericParserTests.testMany),
("testSkipMany", GenericParserTests.testSkipMany),
("testEmpty", GenericParserTests.testEmpty),
("testLabel", GenericParserTests.testLabel),
("testLift2", GenericParserTests.testLift2),
("testLift3", GenericParserTests.testLift3),
("testLift4", GenericParserTests.testLift4),
("testLift5", GenericParserTests.testLift5),
("testUpdateUserState", GenericParserTests.testUpdateUserState),
("testParseArray", GenericParserTests.testParseArray)
]),
testCase([
("testJSONStatisticsParserPerformance",
JSONBenchmarkTests.testJSONStatisticsParserPerformance)
]),
testCase([
("testCollectionMethods", PermutationTests.testCollectionMethods),
("testPermutation", PermutationTests.testPermutation),
("testPermutationWithSeparator",
PermutationTests.testPermutationWithSeparator),
("testPermutationWithOptional",
PermutationTests.testPermutationWithOptional),
("testPermutationWithSeparatorAndOptional",
PermutationTests.testPermutationWithSeparatorAndOptional),
("testPermutationWithNil", PermutationTests.testPermutationWithNil)
]),
testCase([
("testComparable", PositionTests.testComparable),
("testColumnPosition", PositionTests.testColumnPosition),
("testLineColumnPosition", PositionTests.testLineColumnPosition),
("testTabPosition", PositionTests.testTabPosition)
]),
testCase([
("testLast", StringTests.testLast)
]),
testCase([
("testFromInt", UnicodeScalarTests.testFromInt),
("testFromUInt32", UnicodeScalarTests.testFromUInt32)
])
])
|
6f0260988740bff2c0bdebe6d7736404e51ad864
|
[
"Swift"
] | 1 |
Swift
|
techleft/SwiftParsec
|
d78eb673422890d4ed7462bd1cc9374e1abfbef7
|
2097619abb2b25d1f79cd2c13261a7db69a4f11a
|
refs/heads/master
|
<file_sep>package com.makovetskiy.jdbc_template_dao;
import com.makovetskiy.jdbc_template_dao.template.CategoryJdbcTemplate;
import com.makovetskiy.model.Category;
import java.util.List;
import java.util.Optional;
//@Repository
public class CategoryDaoImpl implements CategoryDao {
//@Autowired
private CategoryJdbcTemplate template;
@Override
public Optional<List<Category>> getAll() {
return template.getAll();
}
@Override
public Optional<Category> create(Category category) {
return template.create(category);
}
@Override
public Optional<Category> getById(Long id) {
return template.getById(id);
}
@Override
public Optional<Category> update(Category category) {
return template.update(category);
}
@Override
public void delete(Long id) {
template.delete(id);
}
}
<file_sep>package com.makovetskiy.jdbc_template_dao.template;
import com.makovetskiy.model.Category;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.stereotype.Component;
import java.sql.ResultSet;
import java.util.List;
import java.util.Optional;
import static java.sql.Types.BIGINT;
@Component
public class CategoryJdbcTemplate {
//@Autowired
private JdbcTemplate jdbcTemplate;
public Optional<List<Category>> getAll() {
String query = "SELECT ID, NAME, DESCRIPTION FROM CATEGORIES";
List<Category> c = jdbcTemplate.query(query, (ResultSet rs, int n) ->
new Category(rs.getLong(1),
rs.getString(2),
rs.getString(3)));
return Optional.ofNullable(c);
}
public Optional<Category> create(Category category) {
String query = "INSERT INTO CATEGORIES VALUES (?, ?, ?)";
Category c = jdbcTemplate.execute(query, (PreparedStatementCallback<Category>) ps -> {
ps.setNull(1, BIGINT);
ps.setString(2, category.getName());
ps.setString(3, category.getDescription());
ps.execute();
ResultSet keys = ps.getGeneratedKeys();
if (keys.next()) {
category.setId(keys.getLong(1));
return category;
} else {
return null;
}
});
return Optional.ofNullable(c);
}
public Optional<Category> getById(Long id) {
String query = "SELECT ID, NAME, DESCRIPTION FROM CATEGORIES WHERE ID = ?";
Category c = jdbcTemplate.execute(query, (PreparedStatementCallback<Category>) ps -> {
ps.setLong(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return new Category(rs.getLong(1),
rs.getString(2),
rs.getString(3));
} else {
return null;
}
});
return Optional.ofNullable(c);
}
public Optional<Category> update(Category category) {
String query = "UPDATE CATEGORIES SET NAME=?, DESCRIPTION=? WHERE ID=?";
jdbcTemplate.update(query, ps -> {
ps.setString(1, category.getName());
ps.setString(2, category.getDescription());
ps.setLong(3, category.getId());
ps.executeUpdate();
});
return Optional.of(category);
}
public void delete(Long id) {
String query = "DELETE FROM CATEGORIES WHERE ID = ?";
jdbcTemplate.update(query, ps -> {
ps.setLong(1, id);
ps.executeUpdate();
});
}
}<file_sep>package com.makovetskiy.controller;
import com.makovetskiy.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController {
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String homePage() {
return "home";
}
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test() {
throw new RuntimeException();
//return "home";
}
@RequestMapping(value = "/params", method = RequestMethod.GET)
public ModelAndView params(@RequestParam(required = false) String name, @RequestParam String age, ModelAndView mv) {
mv.addObject("name", name);
mv.addObject("age", age);
mv.setViewName("params");
return mv;
}
@RequestMapping(value = "/add-user", method = RequestMethod.GET)
public ModelAndView addUser(ModelAndView mv) {
mv.setViewName("add-user");
return mv;
}
public ModelAndView addUser(@ModelAttribute User user) {
System.out.println();
return null;
}
}
|
8a1481d496bf8eb57d763551739b1995c5b754d9
|
[
"Java"
] | 3 |
Java
|
stanmak1991/SpringDemo
|
3d272e2e6ec94cae9d79960ee0c8a2883736d990
|
f0a83db8155736eb73414c4f3025a4de4cc14d14
|
refs/heads/master
|
<repo_name>greenleafservices/jms_app<file_sep>/routes/cards.js
const express = require('express');
const router = express.Router();
const { data } = require('../data/flashcardData.json');
const { cards } = data;
router.get( '/', ( req, res ) => {
const numberOfCards = cards.length;
const flashcardId = Math.floor( Math.random() * numberOfCards );
res.redirect( `/cards/${flashcardId}?side=question` )
});
router.get('/:id', (req, res) => {
const { side } = req.query;
const { id } = req.params;
if ( !side ) {
return res.redirect(`/cards/${id}?side=question`);
}
const name = req.cookies.username;
const text = cards[id][side];
const { hint } = cards[id];
const { prompt } = cards[id];
const { points } = cards[id];
/*
Create an object to store the data to be passed to the page
We pass the id so the the link on the card page will be able
to find the proper json object
*/
const templateData = { id, text, name, side };
/*
1. You can add properties to an object as needed - we'll add the score,
points, side, hint and prompt proerties to the templateData object as we go through this process
2. Notice that the data passed to the receiving template does not
have to have the same name as the data object from the json file
(score-points)
*/
templateData.score = points;
if (side === 'question') {
templateData.hint = hint;
templateData.side = 'question';
templateData.sideToShow = 'answer';
templateData.sideToShowDisplay = 'Answer';
/* You don't have to pass all the params - just the ones you want
to use in this request to render
*/
} else if ( side === 'answer' ) {
//templateData.side = 'a';
templateData.prompt = prompt;
templateData.sideToShow = 'question';
templateData.sideToShowDisplay = 'Question';
}
res.render('card', templateData);
});
module.exports = router;
|
23f388637a1f3425743260dd3ce85095e1136768
|
[
"JavaScript"
] | 1 |
JavaScript
|
greenleafservices/jms_app
|
893d498116f81a7be70bec5a86ae7493db435ff6
|
80a437fb14efa54f1976b7a2a289ce40b89c3148
|
refs/heads/main
|
<file_sep>/**
*
*/
package BasicWeb;
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
/**
* @author umutx
*
*/
public class AutoChrome {
/**
* @param args
*/
public static void main(String[] args) {
//System.setProperty("webdriver.chrome.driver","C:\\Users\\umutx\\OneDrive\\Desktop\\WORKSPSCE\\driver\\chrome\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String BaseURL = "https://www.guru99.com";
driver.get(BaseURL);
// switiching to alert to close alert pop up
//Alert al = driver.switchTo().alert();
// capture alert pop up text
//String alertMSG = driver.switchTo().alert().getText();
//System.out.println(alertMSG);
// dismiss alert msg
//al.dismiss();
// close dirver
driver.quit();
}
}
<file_sep>/**
*
*/
package ChromeProfile;
/**
* @author umutx
*
*/
public class chromePro {
}
<file_sep>/**
*
*/
package BasicWeb;
/**
* @author umutx
*
*/
public class ExpediaHiddenElement {
}
<file_sep>/**
*
*/
package BasicWeb;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
* @author umutx
*
*/
public class IEautoDrive {
/**
* @param args
*/
public static void main(String[] args) {
WebDriver driver;
String BaseURL = "https://www.guru99.com";
// need set Caps for IE driver to work it properly
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
caps.setCapability(InternetExplorerDriver.NATIVE_EVENTS, false);
caps.setCapability(InternetExplorerDriver.ENABLE_PERSISTENT_HOVERING, false);
caps.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, false);
caps.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
caps.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
System.setProperty("webdriver.ie.driver","C:\\Users\\umutx\\OneDrive\\Desktop\\WORKSPSCE\\driver\\IE\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(BaseURL);
}
}
<file_sep>/**
*
*/
package DBtesting;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* @author umutx
*
*/
public class Dbtestsmysql {
// build DB connection
static Connection conn = null;
// statement obj
private static Statement stmt;
// result set
private static ResultSet results = null;
// Result Set
public static String DB_URL = "jdbc:mysql://localhost:3306/users";
// Oracle DB: jdbc:oracle:thin:localhost:1521/sid
// DB username
public static String DB_user = "root";
// DB User password
public static String DB_password = "<PASSWORD>";
// Driver
public static String driver = "com.mysql.jdbc.driver"; // "oracle.jdbc.driver.OracleDriver"
@BeforeClass
public void beforeClass() {
Properties props = new Properties();
props.setProperty("user", "root");
props.setProperty("password", "<PASSWORD>");
try
{
// Step1:Register JDBC driver
Class.forName(driver).newInstance();
// Step2: Get connection to DB
System.out.println("Connecting to Selected DataBase........");
conn = DriverManager.getConnection(DB_URL, DB_user, DB_password);
// optional connect
//conn = DriverManager.getConnection(DB_URL, props);
System.out.println("Connceted DataBase successfully.......");
// Step3: Statement object to send the SQL statement to the database
System.out.println("Creating statement........");
stmt = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void test() throws SQLException
{
String query = "select * from user_info";
try
{
// Step4:Extract data from results set
results = stmt.executeQuery(query);
while (results.next()) {
int id = results.getInt("user_id");
String last = results.getString("last_name");
String first = results.getString("first_name");
String city = results.getString("city");
// display all the data
System.out.println("ID" + id);
System.out.println("last name" + last);
System.out.println("first name" + first);
System.out.println("city" + city);
}
// after test we are closing the results
results.close();
} catch(SQLException se) {
// Handle erroes for JDBC
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
@AfterClass
public void afterClass() {
try {
if(results != null)
results.close();
if(stmt != null)
stmt.close();
if(conn !=null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
<file_sep>/**
*
*/
package browserProfileFirefox;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.internal.ProfilesIni;
/**
* @author umutx
*
*/
public class FirefoxProfile {
public static void main(String[] args)
{
//System.setProperty("webdriver.gecko.driver", "C:\\Users\\umutx\\OneDrive\\Desktop\\WORKSPSCE\\driver\\firefox\\geckodriver-v0.26.0-win64\\geckodriver.exe");
String BaseURL= "https://www.letskodeit.com";
WebDriver driver;
ProfilesIni profile = new ProfilesIni();
org.openqa.selenium.firefox.FirefoxProfile fxProfile = profile.getProfile("automationprofile");
FirefoxOptions options = new FirefoxOptions();
options.setProfile(fxProfile);
driver = new FirefoxDriver(options);
driver.manage().window().maximize();
driver.get(BaseURL);
driver.quit();
}
}
|
06178437e4780b2c7113ae044913d609deb3db55
|
[
"Java"
] | 6 |
Java
|
UmutsDemo/Selenium-functional-regression
|
22b5bd8c98928ba44a29d5dbdbabda656aba37af
|
ddd0507768d336918b374e8836a99a4820ff3173
|
refs/heads/master
|
<file_sep>import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
declare var window: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
title = 'pay';
posting = false;
@ViewChild('myFormPost', { static: false }) myFormPost: ElementRef;
token: any;
constructor(private http: HttpClient,private window: Window) {
//this.signalRService.startConnection();
}
onPost(event): void {
let token = {
"getHostedPaymentPageRequest": {
"merchantAuthentication": {
"name": "",
"transactionKey": ""
},
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "20.00",
"profile": {
"customerProfileId": "123456789"
},
"customer": {
"email": "<EMAIL>"
},
"billTo": {
"firstName": "Ellen",
"lastName": "Johnson",
"company": "Souveniropolis",
"address": "14 Main Street",
"city": "Pecan Springs",
"state": "TX",
"zip": "44628",
"country": "USA"
}
},
"hostedPaymentSettings": {
"setting": [{
"settingName": "hostedPaymentReturnOptions",
"settingValue": "{\"showReceipt\": false, \"url\": \"https://payment1990.firebaseapp.com/receipt\", \"urlText\": \"Continue\", \"cancelUrl\": \"https://payment1990.firebaseapp.com/receipt?response=cancel\", \"cancelUrlText\": \"Cancel\"}"
}, {
"settingName": "hostedPaymentButtonOptions",
"settingValue": "{\"text\": \"Pay\"}"
}, {
"settingName": "hostedPaymentStyleOptions",
"settingValue": "{\"bgColor\": \"blue\"}"
}, {
"settingName": "hostedPaymentPaymentOptions",
"settingValue": "{\"cardCodeRequired\": false, \"showCreditCard\": true, \"showBankAccount\": true}"
}, {
"settingName": "hostedPaymentSecurityOptions",
"settingValue": "{\"captcha\": false}"
}, {
"settingName": "hostedPaymentShippingAddressOptions",
"settingValue": "{\"show\": false, \"required\": false}"
}, {
"settingName": "hostedPaymentBillingAddressOptions",
"settingValue": "{\"show\": true, \"required\": false}"
}, {
"settingName": "hostedPaymentCustomerOptions",
"settingValue": "{\"showEmail\": false, \"requiredEmail\": false, \"addPaymentProfile\": true}"
}, {
"settingName": "hostedPaymentOrderOptions",
"settingValue": "{\"show\": true, \"merchantName\": \"G and S Questions Inc.\"}"
}, {
"settingName": "hostedPaymentIFrameCommunicatorUrl",
"settingValue": "{\"url\": \"https://payment1990.firebaseapp.com/IFrameCommunicator.html\"}"
}]
}
}
}
this.http.post('https://apitest.authorize.net/xml/v1/request.api', token).subscribe((data) => {
console.log(data)
this.token = data["token"];
this.posting = true;
})
}
onReset(event): void {
this.posting = false;
}
ngAfterViewChecked() {
if (this.posting && this.myFormPost) {
this.myFormPost.nativeElement.submit();
}
}
ngAfterViewInit() {
window.CommunicationHandler = {};
window.CommunicationHandler.onReceiveCommunication = (argument) => {
console.log("iFrame argument: " + JSON.stringify(argument));
//Get the parameters from the argument.
let params = this.parseQueryString(argument.qstr)
console.log(params)
switch (params['action']) {
case "resizeWindow":
console.log("handle")
break;
case "successfulSave":
console.log("handle")
break;
case "cancel":
console.log("handle")
break;
case "transactResponse":
console.log('transaction complete');
const transResponse = JSON.parse(params['response']);
console.log(transResponse)
this.posting = false;
break;
default:
console.log('Unknown action: ' + params['action'])
break;
}
}
}
parseQueryString(str) {
var vars = [];
var arr = str.split('&');
var pair;
for (var i = 0; i < arr.length; i++) {
pair = arr[i].split('=');
//vars[pair[0]] = unescape(pair[1]);
vars[pair[0]] = pair[1];
}
return vars;
}
}
|
b747178a81cef4e276eb483ab82a569656af1d5d
|
[
"TypeScript"
] | 1 |
TypeScript
|
souravknath/Authorize.Net-Hosted-Form-in-angular
|
d858f15a994220369e8bdfb025ad44279ddc156b
|
9a1de3731fbb4512e2e7c0580593154dff110ecb
|
refs/heads/master
|
<repo_name>Esleiter/cutUrls<file_sep>/README.md
# CutURLs
***
The project consists of shortened URLs, it is a functional practice carried out with the MERN stack.
## Table of Contents
1. [General Info](#general-info)
2. [Technologies](#technologies)
3. [Installation](#installation)
## General Info
***
This is a first version, which when shortening a URL gives us a 5-digit code; or a new URL which we can more easily remember, and use to access the main web page to which the shortened URL points, all this immediately without any type of advertising.
### Screenshot

* [Demo](https://c.esleiter.com/): https://c.esleiter.com
* [Google](https://c.esleiter.com/gugol): https://c.esleiter.com/gugol This link for example will take you to the google page.
## Technologies
***
List of technologies used within the project:
* [MongoDB](https://www.mongodb.com): Version 5.0.2
* [Express](https://expressjs.com): Version 4.17.1
* [React](https://es.reactjs.org): Version 17.0.2
* [Node.js](https://nodejs.org): Version 14.17.4
## Installation
***
The project is divided into two parts, the Backend, an API; and the Frontend, built with React.
```
$ git clone https://github.com/Esleiter/cutURL
$ cd backend
$ npm install
$ npm start
```
In other terminal:
```
$ cd frontend
$ npm install
$ npm start
```
<file_sep>/backend/src/models/urls.js
import mongoose from "mongoose";
const { Schema } = mongoose;
const urlsSchema = new Schema({
url: { type: String, required: true },
code: { type: String, required: true },
date : {type : Date, default : Date.now}
});
const urls = mongoose.model('urls', urlsSchema);
export default urls;<file_sep>/backend/src/redirect.js
import urls from './models/urls.js';
export const redirect = async (req, res) => {
const codeRegex = /^([a-z0-9]){5}$/;
if (!codeRegex.test(req.params.code)) {
return res.status(404).json({msj : "URL not valid"});
} else {
const linkObj = await urls.findOne({code: req.params.code});
if (!linkObj) {
return res.status(404).json({msj : "URL not found"});
} else {
res.status(200).json({url : linkObj.url});
//res.redirect(linkObj.url);
};
};
};<file_sep>/frontend/src/js/redirect.js
import axios from 'axios';
import { useState } from 'react';
import { useParams } from 'react-router-dom';
const Loading = () => {
return (
<h1>Loading...</h1>
);
};
const NotFound = () => {
return (
<h1>Not found.<code><br/> error 404.</code></h1>
);
};
const Redirect= () => {
var { id } = useParams();
var api = `http://localhost:4000/${id}`;
const [state, setState] = useState({
'found': true
});
const on = () => {
axios.get(api)
.then(res => {
window.location = res.data.url;
})
.catch(e => {
if (e.response.status === 404) {
setState({
found: false
});
};
});
};
if (state.found === false) {
return (
<NotFound />
);
} else {
return (
<section className="app-section">
{window.onload = on()}
<Loading />
</section>
);
};
};
export default Redirect;<file_sep>/backend/app.js
import express from "express";
import "./database.js";
import { cut } from "./src/cut.js";
import { redirect } from "./src/redirect.js";
const app = express();
const port = 4000;
app.use(express.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.post("/cut", cut);
app.get("/:code", redirect);
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});<file_sep>/frontend/src/js/cut.js
import axios from 'axios';
import Social from './social';
import { useState } from 'react';
const Cut = () => {
var api = 'http://localhost:4000/cut';
const [state, setState] = useState({
'url': '',
'urlCut': ''
});
const handleChange = (e) => {
setState({ url: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
const validUrl = new RegExp(
/(http|https):\/\/(\w+:{0,1}\w*@)?[-a-zA-Z0-9@:%._~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_.~#?&//=]*)/g
);
const addhttp = (urlTest) => {
if (!validUrl.test(urlTest)) {
urlTest = 'http://'+urlTest;
};
return urlTest;
};
const urlHttp = addhttp(state.url);
axios.post(api, { url: urlHttp })
.then(res => {
setState({
url: urlHttp,
urlCut: res.data.code
});
});
};
return (
<section className="app-section">
<h1>CUT YOUR URL HERE!</h1>
<form onSubmit={handleSubmit}>
<input type="text" name="url" className="input-url" onChange={handleChange} placeholder="https://esleiter.com" />
<button type="submit" className="button-submit">CUT!</button>
</form>
{/*eslint-disable-next-line*/}
<a id="urlCut" href={state.urlCut} target="_blank">{window.location.href}{state.urlCut}</a>
<Social url={state.urlCut} />
</section>
);
};
export default Cut;
|
fefb2fee5c2d86c193dd11fd4db15baf41c78b0d
|
[
"Markdown",
"JavaScript"
] | 6 |
Markdown
|
Esleiter/cutUrls
|
cb23f1e08760eee1cb9a13af029789f1cb107418
|
d589bcaf424f331aad2aadad91fb0c91130d8884
|
refs/heads/master
|
<file_sep>import numpy as np
import pandas as pd
from tqdm import tqdm_notebook
import sklearn
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
from sklearn.base import BaseEstimator, ClassifierMixin
def batch_generator(X, y, shuffle=True, batch_size=1):
"""
Гератор новых батчей для обучения
X - матрица объекты-признаки
y_batch - вектор ответов
shuffle - нужно ли случайно перемешивать выборку
batch_size - размер батча ( 1 это SGD, > 1 mini-batch GD)
Генерирует подвыборку для итерации спуска (X_batch, y_batch)
"""
if shuffle:
X, y = sklearn.utils.shuffle(X, y)
for i in range(0, X.shape[0], batch_size):
X_batch = X[i:i+batch_size]
y_batch = y[i:i+batch_size]
yield (X_batch, y_batch)
def sigmoid(x):
"""
Вычисляем значение сигмоида.
X - выход линейной модели
"""
return 1 / (1 + np.exp(-x))
class MySGDClassifier(BaseEstimator, ClassifierMixin):
def __init__(self, batch_generator, C=1, alpha=0.01, max_epoch=10, model_type='lin_reg'):
"""
batch_generator -- функция генератор, которой будем создавать батчи
C - коэф. регуляризации
alpha - скорость спуска
max_epoch - максимальное количество эпох
model_type - тим модели, lin_reg или log_reg
"""
self.C = C
self.alpha = alpha
self.max_epoch = max_epoch
self.batch_generator = batch_generator
self.errors_log = {'iter' : [], 'loss' : []}
self.model_type = model_type
self.weights = None
def calc_loss(self, X_batch, y_batch):
"""
Считаем функцию потерь по батчу
X_batch - матрица объекты-признаки по батчу
y_batch - вектор ответов по батчу
Не забудте тип модели (линейная или логистическая регрессия)!
"""
loss = None
if self.model_type == 'lin_reg':
pred = self.__predict(X_batch)
loss = (pred - y_batch) ** 2
loss = np.mean(loss, axis=0) + self.weights[1:].T @ self.weights[1:] / self.C
elif self.model_type == 'log_reg':
pred = self.__predict(X_batch)
loss = -(y_batch * np.log(pred) + (1 - y_batch) * np.log(1 - pred))
loss = np.mean(loss, axis=0) + self.weights[1:].T @ self.weights[1:] / self.C
return loss
def calc_loss_grad(self, X_batch, y_batch):
"""
Считаем градиент функции потерь по батчу (то что Вы вывели в задании 1)
X_batch - матрица объекты-признаки по батчу
y_batch - вектор ответов по батчу
Не забудте тип модели (линейная или логистическая регрессия)!
"""
loss_grad = None
if self.model_type == 'lin_reg':
pred = self.__predict(X_batch)
reg = self.weights * 2 / self.C
reg[0] = 0
loss_grad = X_batch.T @ (pred - y_batch) * 2 / X_batch.shape[0] + reg
elif self.model_type == 'log_reg':
pred = self.__predict(X_batch)
reg = self.weights * 2 / self.C
reg[0] = 0
loss_grad = X_batch.T @ (pred - y_batch) / X_batch.shape[0] + reg
return loss_grad
def update_weights(self, new_grad):
"""
Обновляем вектор весов
new_grad - градиент по батчу
"""
self.weights = self.weights - self.alpha * new_grad
def fit(self, X, y, batch_size=1):
'''
Обучение модели
X - матрица объекты-признаки
y - вектор ответов
'''
X = np.hstack((np.ones((X.shape[0], 1)), X))
np.random.seed(1755)
self.weights = np.random.randn(X.shape[1]).astype(np.longdouble)
i = 0
for n in range(0, self.max_epoch):
new_epoch_generator = self.batch_generator(X, y, batch_size=batch_size)
for batch_num, new_batch in enumerate(new_epoch_generator):
X_batch = new_batch[0]
y_batch = new_batch[1]
batch_grad = self.calc_loss_grad(X_batch, y_batch)
self.update_weights(batch_grad)
batch_loss = self.calc_loss(X_batch, y_batch)
self.errors_log['iter'].append(i)
self.errors_log['loss'].append(batch_loss)
i += 1
return self
def __predict(self, X):
'''
Предсказание класса
X - матрица объекты-признаки
Не забудте тип модели (линейная или логистическая регрессия)!
'''
y_hat = X @ self.weights
if self.model_type == 'log_reg':
y_hat = sigmoid(y_hat)
return y_hat
def predict(self, X):
'''
Предсказание класса
X - матрица объекты-признаки
Не забудте тип модели (линейная или логистическая регрессия)!
'''
X = np.hstack((np.ones((X.shape[0], 1)), X))
y_hat = X @ self.weights
if self.model_type == 'log_reg':
y_hat = sigmoid(y_hat)
return y_hat<file_sep>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import re
from nltk.stem.snowball import SnowballStemmer
from sklearn.preprocessing import StandardScaler
def get_train_test():
doc_to_title = {}
with open('docs_titles.tsv', encoding='utf-8') as f:
for num_line, line in enumerate(f):
if num_line == 0:
continue
data = line.strip().split('\t', 1)
doc_id = int(data[0])
if len(data) == 1:
title = ''
else:
title = data[1]
doc_to_title[doc_id] = title
# print (len(doc_to_title))
stemmer = SnowballStemmer(language='russian').stem
train_data = pd.read_csv('train_groups.csv')
traingroups_titledata = {}
for i in range(len(train_data)):
new_doc = train_data.iloc[i]
doc_group = new_doc['group_id']
doc_id = new_doc['doc_id']
target = new_doc['target']
title = doc_to_title[doc_id]
if doc_group not in traingroups_titledata:
traingroups_titledata[doc_group] = []
traingroups_titledata[doc_group].append((doc_id, title, target))
y_train = []
X_train = []
groups_train = []
for new_group in traingroups_titledata:
docs = traingroups_titledata[new_group]
for k, (doc_id, title, target_id) in enumerate(docs):
y_train.append(target_id)
groups_train.append(new_group)
all_dist = []
words = set(map(stemmer, re.sub('[^a-z0-9а-я]', ' ', title.lower()).strip().split()))
for j in range(0, len(docs)):
if k == j:
continue
doc_id_j, title_j, target_j = docs[j]
words_j = set(map(stemmer, re.sub('[^a-z0-9а-я]', ' ', title_j.lower()).strip().split()))
all_dist.append(len(words.intersection(words_j)))
X_train.append(sorted(all_dist, reverse=True)[0:15])
X_train = np.array(X_train)
y_train = np.array(y_train)
groups_train = np.array(groups_train)
# print (X_train.shape, y_train.shape, groups_train.shape)
scaler = StandardScaler()
scaler.fit(X=X_train)
X_train = scaler.transform(X=X_train)
test_data = pd.read_csv('test_groups.csv')
testgroups_titledata = {}
for i in range(len(test_data)):
new_doc = test_data.iloc[i]
doc_group = new_doc['group_id']
doc_id = new_doc['doc_id']
title = doc_to_title[doc_id]
if doc_group not in testgroups_titledata:
testgroups_titledata[doc_group] = []
testgroups_titledata[doc_group].append((doc_id, title))
y_test = []
X_test = []
groups_test = []
for new_group in testgroups_titledata:
docs = testgroups_titledata[new_group]
for k, (doc_id, title) in enumerate(docs):
groups_test.append(new_group)
all_dist = []
words = set(map(stemmer, re.sub('[^a-z0-9а-я]', ' ', title.lower()).strip().split()))
for j in range(0, len(docs)):
if k == j:
continue
doc_id_j, title_j = docs[j]
words_j = set(map(stemmer, re.sub('[^a-z0-9а-я]', ' ', title_j.lower()).strip().split()))
all_dist.append(len(words.intersection(words_j)))
X_test.append(sorted(all_dist, reverse=True)[0:15])
X_test = np.array(X_test)
groups_test = np.array(groups_test)
# print (X_test.shape, groups_test.shape)
X_test = scaler.transform(X=X_test)
return X_train, X_test, y_train, y_test<file_sep># ml1_sphere_project
Technosphere 2019 ML1 Final Project
Kaggle: https://www.kaggle.com/c/anomaly-detection-competition-ml1-ts-fall-2019
### Общие замечания
Я плохо шарю за гит и разработку, но думаю оптимально будет, если все себе заведут по ветке, из которой уже будем части брать в `master`, чтобы его не засорять
Ну из совсем очевидного: не заливать временные файлы и всякие кэши и чекпоинты, что-то есть в `.gitignore`, но наверняка не все, если какой-то мусор постоянно генерится, то есть смысл его добавить в игнор
## Структура репозитория
#### Код/ноутбук:
* `Model.ipynb`
Ноутбук с описанием текущих задач по подбору моделей и параметров для них, с текущим лучшим решением
* `Data_extraction.ipynb`
Ноутбук с текущими задачами по извлечению признаков и текущим лучшим решением
* `Whole_pipeline.ipynb`
Полное решение с выбором модели и извлечением признаков, по сути объединение двух других ноутбуков
* `base_model.py`
Базовая модель для тестирования улучшений в извлечении признаков
* `base_extraction.py`
Базовое извлечение признаков для тестирования качества моделей
#### Данные
* `docs_titles.tsv`
Заголовки всех страниц
* `test_groups.csv`
Тестовая выборка, для которой необходимо совершить предсказание
* `train_groups.csv`
Обучающая выборка
* `content`
Папка со `.html` исходниками страниц, в репозитории **не находится** ввиду большого размера (5GB)
|
436ced02c56823f247c944dc525fcdd47320c904
|
[
"Markdown",
"Python"
] | 3 |
Python
|
AlexanderYakovenko1/ml1_sphere_project
|
44e38761d26916e172dd21f6989555fbb64a0348
|
2d790d1e5a3ce59f7288c9add82e6e8c3303b759
|
refs/heads/main
|
<repo_name>DOGANAY06/SwitchCaseEgzersizi<file_sep>/README.md
# SwitchCaseEgzersizi
Switch Case Örneği Form Uygulaması İle
<file_sep>/SwitchCase/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;
namespace SwitchCase
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int ay = Convert.ToInt32(textBox1.Text);
label2.Visible = true; //görünürlüğünü aktif edip değeri gösteririz
switch (ay)
{
case 1:
label2.Text = "Ocak";
break;
case 2:
label2.Text = "Subat";
break;
case 3:
label2.Text = "Mart";
break;
case 4:
label2.Text = "Nisan";
break;
case 5:
label2.Text = "Mayıs";
break;
case 6:
label2.Text = "Haziran";
break;
case 7:
label2.Text = "Temmuz";
break;
case 8:
label2.Text = "Ağustos";
break;
case 9:
label2.Text = "Eylül";
break;
case 10:
label2.Text = "Ekim";
break;
case 11:
label2.Text = "Kasım";
break;
case 12:
label2.Text = "Aralık";
break;
default:
label2.Text = "Bu ay tanımlı değil";
break;
}
}
private void button2_Click(object sender, EventArgs e)
{
string mevsim = textBox2.Text;
label3.Visible = true;
switch (mevsim)
{
case "YAZ" :
label3.Text = "Haziran Temmuz Ağustos";
break;
case "SONBAHAR":
label3.Text = "Eylül Ekim Kasım";
break;
case "KIŞ":
label3.Text = "<NAME>";
break;
case "İLKBAHAR":
label3.Text = "<NAME>";
break;
default:
label3.Text = "Böyle bir mevsim yok";
MessageBox.Show("Mevsim ismini tamamen büyük harfle giriniz");
break;
}
}
private void button3_Click(object sender, EventArgs e)
{
int sayi1 = Convert.ToInt32(textBox3.Text);
string sembol = textBox4.Text;
int sayi2 = Convert.ToInt32(textBox5.Text);
label6.Visible = true;
switch (sembol)
{
case "+":
int toplam = sayi1 + sayi2;
label6.Text = toplam.ToString();
break;
case "-":
int cikar = sayi1 - sayi2;
label6.Text = cikar.ToString() ;
break;
case "*":
int carp = sayi1 * sayi2;
label6.Text = carp.ToString();
break;
case "/":
double bol = Convert.ToDouble(sayi1) / Convert.ToDouble(sayi2);
label6.Text = bol.ToString();
break;
default:
label6.Text = "Hatalı işlem sembolü hesap makinesine göre giriniz:";
break;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
|
f302dc3df04d63ac6fecf59b4e815fb17aa4ff39
|
[
"Markdown",
"C#"
] | 2 |
Markdown
|
DOGANAY06/SwitchCaseEgzersizi
|
9b5fe867e922cd721789eb26e4ca4f15806e4431
|
1c46cb66b077bcdda29fda90c8b7f74caa54390c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.